Files
kandev/apps/web/hooks/use-utility-agent-generator.ts
T
José Almeida 7d900fea91 feat(vcs): add commit body field and AI generation for commit description and PR title (#465)
* feat(vcs): add commit body/description field to commit dialog

Add an optional description textarea below the commit title in both
desktop and mobile commit dialogs, with a dedicated AI generate button
for the description. Add builtin-commit-description utility agent and
E2E test.

* style: fix prettier formatting in mobile git controls and E2E test

* fix(e2e): use specific testid selectors for commit dialog inputs

The commit dialog now has two textboxes (title + body), so
getByRole("textbox") is ambiguous. Use getByTestId selectors
and add exact match for the Commit button.

* fix(ui): add cursor-pointer to mobile commit button

* fix(ui): remove "(optional)" from description label and "Generate" text from button

* fix(ui): match PR dialog style for commit description generate button

* feat(vcs): add AI generate button for PR title

Add builtin-pr-title utility agent and wire up a generate button
inside the PR title input, matching the commit title pattern.
Extract shared dialog field components into vcs-dialog-fields.tsx
to stay within the 600-line file limit.

* refactor(ui): unify generate buttons as icon-only sparkles inside inputs

Move AI generate buttons inside both title inputs and description
textareas (top-right corner) for a consistent look. Remove the
"Generate" label variant — all buttons are now icon-only sparkles.

* style: fix prettier formatting in utility agent generator hook

* fix(a11y): add aria-labels to generate buttons and PR title input

* ci: retrigger E2E tests

* fix(e2e): improve commit dialog button click reliability

Add exact match and enabled check before clicking the dialog
Commit button, increase close timeout.

* ci: retrigger checks

* fix(e2e): improve pre-hooks test commit button reliability

Add exact match, enabled check, and longer dialog timeout to match
the commit-body test pattern.

* fix(ui): prevent dialog field overflow and improve commit description prompt

- Add min-w-0 to relative wrappers in commit and PR dialog fields to
  prevent text inputs/textareas from overflowing the dialog bounds
- Rewrite commit description prompt to use system-role framing that
  prevents weaker models from adding conversational preamble
2026-03-26 13:24:30 +00:00

174 lines
5.3 KiB
TypeScript

"use client";
import { useState, useCallback } from "react";
import { executeUtilityPrompt, type ExecutePromptRequest } from "@/lib/api/domains/utility-api";
import { useToast } from "@/components/toast-provider";
import { useSessionGitStatus } from "@/hooks/domains/session/use-session-git-status";
import type { FileInfo } from "@/lib/state/slices";
type GeneratorType =
| "commit-message"
| "commit-description"
| "pr-title"
| "pr-description"
| "enhance-prompt";
const UTILITY_AGENT_IDS: Record<GeneratorType, string> = {
"commit-message": "builtin-commit-message",
"commit-description": "builtin-commit-description",
"pr-title": "builtin-pr-title",
"pr-description": "builtin-pr-description",
"enhance-prompt": "builtin-enhance-prompt",
};
type UseUtilityAgentGeneratorOptions = {
sessionId: string | null;
taskTitle?: string;
taskDescription?: string;
};
type GenerateOptions = {
onSuccess?: (content: string) => void;
// Additional context for PR description
commitLog?: string;
diffSummary?: string;
// User's original prompt for enhancement
userPrompt?: string;
};
export function useUtilityAgentGenerator({
sessionId,
taskTitle,
taskDescription,
}: UseUtilityAgentGeneratorOptions) {
const [generating, setGenerating] = useState<Set<GeneratorType>>(new Set());
const { toast } = useToast();
const gitStatus = useSessionGitStatus(sessionId);
const collectGitContext = useCallback(() => {
const changedFiles = gitStatus?.files ? Object.keys(gitStatus.files) : [];
const diffs = gitStatus?.files
? Object.values(gitStatus.files as Record<string, FileInfo>)
.filter((f) => f.diff)
.map((f) => f.diff)
.join("\n\n")
: undefined;
return { changedFiles, diffs };
}, [gitStatus]);
const generate = useCallback(
async (type: GeneratorType, options?: GenerateOptions) => {
if (!sessionId) {
toast({
title: "No active session",
description: "Start a session first to use AI generation",
variant: "error",
});
return;
}
setGenerating((prev) => new Set(prev).add(type));
try {
const { changedFiles, diffs } = collectGitContext();
const request: ExecutePromptRequest = {
utility_agent_id: UTILITY_AGENT_IDS[type],
session_id: sessionId,
task_title: taskTitle,
task_description: taskDescription,
git_diff: diffs || undefined,
changed_files: changedFiles.join("\n") || undefined,
commit_log: options?.commitLog,
diff_summary: options?.diffSummary,
user_prompt: options?.userPrompt,
};
const resp = await executeUtilityPrompt(request);
// Clear generating state BEFORE calling onSuccess so the editor is re-enabled
setGenerating((prev) => {
const next = new Set(prev);
next.delete(type);
return next;
});
if (resp.success && resp.response) {
const response = resp.response;
requestAnimationFrame(() => {
options?.onSuccess?.(response);
});
} else {
toast({
title: "Generation failed",
description: resp.error || "Failed to generate content",
variant: "error",
});
}
} catch (error) {
setGenerating((prev) => {
const next = new Set(prev);
next.delete(type);
return next;
});
toast({
title: "Generation failed",
description: error instanceof Error ? error.message : "Unknown error",
variant: "error",
});
}
},
[sessionId, taskTitle, taskDescription, collectGitContext, toast],
);
return useGeneratorCallbacks(generate, generating);
}
function useGeneratorCallbacks(
generate: (type: GeneratorType, options?: GenerateOptions) => Promise<void>,
generating: Set<GeneratorType>,
) {
const generateCommitMessage = useCallback(
(onSuccess: (message: string) => void) => generate("commit-message", { onSuccess }),
[generate],
);
const generateCommitDescription = useCallback(
(onSuccess: (description: string) => void) => generate("commit-description", { onSuccess }),
[generate],
);
const generatePRTitle = useCallback(
(onSuccess: (title: string) => void, extra?: { commitLog?: string; diffSummary?: string }) =>
generate("pr-title", { onSuccess, ...extra }),
[generate],
);
const generatePRDescription = useCallback(
(
onSuccess: (description: string) => void,
extra?: { commitLog?: string; diffSummary?: string },
) => generate("pr-description", { onSuccess, ...extra }),
[generate],
);
const enhancePrompt = useCallback(
(userPrompt: string, onSuccess: (enhanced: string) => void) =>
generate("enhance-prompt", { onSuccess, userPrompt }),
[generate],
);
return {
isGenerating: generating.size > 0,
isGeneratingCommitMessage: generating.has("commit-message"),
isGeneratingCommitDescription: generating.has("commit-description"),
isGeneratingPRTitle: generating.has("pr-title"),
isGeneratingPRDescription: generating.has("pr-description"),
isEnhancingPrompt: generating.has("enhance-prompt"),
generateCommitMessage,
generateCommitDescription,
generatePRTitle,
generatePRDescription,
enhancePrompt,
};
}