Skip to content

Job application tracker and AI-powered job search assistant. Helps job seekers manage their search journey with AI resume review, job matching, task logging, and application analytics, all while keeping your data private.

fix: harden the resume Review button's chat clear

Khuram Niaze9cf03d4d1e1
diff --git a/__tests__/AgentChatClosePaths.spec.tsx b/__tests__/AgentChatClosePaths.spec.tsx
index 54c923a..adaee81 100644
--- a/__tests__/AgentChatClosePaths.spec.tsx
+++ b/__tests__/AgentChatClosePaths.spec.tsx
@@ -33,12 +33,14 @@ vi.mock("@/actions/userSettings.actions", () => ({
vi.mock("@/utils/ai.utils", () => ({
checkOllamaConnection: vi.fn(async () => ({ isConnected: true })),
}));
+vi.mock("@/lib/toast", () => ({ toastInfo: vi.fn() }));
import { AgentChatProvider } from "@/components/agent/AgentChatProvider";
import { AgentChatPanel } from "@/components/agent/AgentChatPanel";
import { AgentChatTrigger } from "@/components/AgentChatTrigger";
import { RightRailProvider, useRightRail } from "@/context/RightRailContext";
import { SidebarProvider } from "@/context/SidebarContext";
+import { toastInfo } from "@/lib/toast";
function OtherPanel() {
const { requestOpen } = useRightRail();
@@ -152,6 +154,39 @@ describe("agent chat close paths", () => {
).toBe("Chat AI");
});
+ // Closing is the only abort with no on-screen trace: the panel that would
+ // have shown it is gone, and interruptedTurn only surfaces on reopen.
+ it("toasts when closing aborts a stream", async () => {
+ setup();
+ await openPanel();
+ await act(async () => {
+ await userEvent.click(screen.getByRole("button", { name: "Close chat" }));
+ });
+ expect(vi.mocked(toastInfo).mock.calls[0]![0]).toMatch(/stopped/i);
+ });
+
+ it("toasts when Clear aborts a stream", async () => {
+ setup();
+ await openPanel();
+ await act(async () => {
+ await userEvent.click(screen.getByRole("button", { name: "Clear" }));
+ });
+ expect(vi.mocked(toastInfo).mock.calls[0]![0]).toMatch(/cleared/i);
+ });
+
+ // Both toasts are gated on an actual abort — closing or clearing an idle
+ // panel interrupted nothing and must stay silent.
+ it("stays silent when nothing was streaming", async () => {
+ chat.status = "ready";
+ setup();
+ await openPanel();
+ await act(async () => {
+ await userEvent.click(screen.getByRole("button", { name: "Clear" }));
+ await userEvent.click(screen.getByRole("button", { name: "Close chat" }));
+ });
+ expect(toastInfo).not.toHaveBeenCalled();
+ });
+
// The nested generation is inside the outer streamText's tool call, so the
// same abort covers it — nothing keeps reviewing while the panel is shut.
it("stops a running nested review when the panel closes", async () => {
diff --git a/__tests__/AgentChatProvider.spec.tsx b/__tests__/AgentChatProvider.spec.tsx
index e495dfe..fb3f99a 100644
--- a/__tests__/AgentChatProvider.spec.tsx
+++ b/__tests__/AgentChatProvider.spec.tsx
@@ -59,6 +59,10 @@ function Probe() {
<button onClick={c.open}>open</button>
<button onClick={c.close}>close</button>
<button onClick={c.clear}>clear</button>
+ <button onClick={() => void c.regenerate()}>regenerate</button>
+ <button onClick={() => void c.sendMessage({ parts: [] } as any)}>
+ sendMessage
+ </button>
<button onClick={c.togglePanelExpand}>togglePanelExpand</button>
<button onClick={toggle}>toggleSidebar</button>
<span data-testid="sidebar">{String(expanded)}</span>
@@ -154,6 +158,36 @@ describe("AgentChatProvider", () => {
);
});
+ // The interrupted notice describes a turn that is no longer interrupted the
+ // moment the user resumes it, so it must not outlive the reply it asked for.
+ it("clears the interrupted flag when the turn is resumed with Continue", async () => {
+ chat.status = "streaming";
+ setup();
+ await userEvent.click(screen.getByText("open"));
+ await userEvent.click(screen.getByText("close"));
+ expect(screen.getByTestId("state").textContent).toContain("|true|");
+
+ await userEvent.click(screen.getByText("regenerate"));
+ expect(chat.regenerate).toHaveBeenCalled();
+ expect(screen.getByTestId("state").textContent).toContain(
+ "false|false|false|null",
+ );
+ });
+
+ it("clears the interrupted flag when the user sends a new message instead", async () => {
+ chat.status = "streaming";
+ setup();
+ await userEvent.click(screen.getByText("open"));
+ await userEvent.click(screen.getByText("close"));
+ expect(screen.getByTestId("state").textContent).toContain("|true|");
+
+ await userEvent.click(screen.getByText("sendMessage"));
+ expect(chat.sendMessage).toHaveBeenCalled();
+ expect(screen.getByTestId("state").textContent).toContain(
+ "false|false|false|null",
+ );
+ });
+
it("reports a pending approval from a rehydrated transcript", () => {
chat.messages = [approvalMessage];
setup([approvalMessage]);
diff --git a/__tests__/ResumeContainer.spec.tsx b/__tests__/ResumeContainer.spec.tsx
new file mode 100644
index 0000000..e5b6454
--- /dev/null
+++ b/__tests__/ResumeContainer.spec.tsx
@@ -0,0 +1,110 @@
+import { render, screen } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import type { Resume } from "@/models/profile.model";
+
+const chat = {
+ open: vi.fn(),
+ sendMessage: vi.fn(),
+ clear: vi.fn(async () => {}),
+ approvalPending: false,
+};
+vi.mock("@/components/agent/AgentChatProvider", () => ({
+ useAgentChat: () => chat,
+}));
+
+vi.mock("next/navigation", () => ({
+ useRouter: () => ({ back: vi.fn(), refresh: vi.fn(), push: vi.fn() }),
+}));
+
+vi.mock("@/actions/profile.actions", () => ({
+ deleteResumeById: vi.fn(),
+ deleteSkillsSection: vi.fn(),
+ setDefaultResume: vi.fn(),
+}));
+vi.mock("@/actions/resumeImport.actions", () => ({
+ resolveImportCard: vi.fn(),
+}));
+vi.mock("@/actions/userSettings.actions", () => ({
+ getUserSettings: vi.fn(async () => ({ success: false })),
+}));
+vi.mock("@/utils/ai.utils", () => ({
+ checkOllamaConnection: vi.fn(async () => ({ isConnected: false })),
+}));
+
+// Unrelated to the Review button — stub out so its own heavy dialogs and
+// dependencies don't have to be satisfied for this test.
+vi.mock("@/components/profile/AddResumeSection", () => ({
+ default: () => null,
+}));
+
+import ResumeContainer from "@/components/profile/ResumeContainer";
+
+const resume: Resume = { id: "r1", title: "Senior Engineer Resume" };
+
+const clickReview = () =>
+ userEvent.click(screen.getByRole("button", { name: /^review$/i }));
+
+describe("ResumeContainer — Review button", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ chat.approvalPending = false;
+ chat.clear.mockImplementation(async () => {});
+ });
+
+ it("opens the panel before clearing, then sends the review request", async () => {
+ render(<ResumeContainer resume={resume} defaultResumeId={null} />);
+ await clickReview();
+
+ expect(chat.clear).toHaveBeenCalled();
+ expect(chat.sendMessage).toHaveBeenCalledWith({
+ parts: [{ type: "text", text: "Review Senior Engineer Resume" }],
+ });
+
+ // Opening first is what stops a failed clear from leaving a dead button.
+ const openOrder = chat.open.mock.invocationCallOrder[0];
+ const clearOrder = chat.clear.mock.invocationCallOrder[0];
+ const sendOrder = chat.sendMessage.mock.invocationCallOrder[0];
+ expect(openOrder).toBeLessThan(clearOrder);
+ expect(clearOrder).toBeLessThan(sendOrder);
+ });
+
+ it("still opens and sends when the clear fails", async () => {
+ chat.clear.mockRejectedValue(new Error("offline"));
+ render(<ResumeContainer resume={resume} defaultResumeId={null} />);
+ await clickReview();
+
+ expect(chat.open).toHaveBeenCalled();
+ expect(chat.sendMessage).toHaveBeenCalled();
+ });
+
+ it("asks before wiping a conversation with a pending approval", async () => {
+ chat.approvalPending = true;
+ render(<ResumeContainer resume={resume} defaultResumeId={null} />);
+ await clickReview();
+
+ expect(
+ screen.getByText(/waiting for your approval/i),
+ ).toBeInTheDocument();
+ expect(chat.clear).not.toHaveBeenCalled();
+ expect(chat.sendMessage).not.toHaveBeenCalled();
+
+ await userEvent.click(
+ screen.getByRole("button", { name: /clear and review/i }),
+ );
+ expect(chat.clear).toHaveBeenCalled();
+ expect(chat.sendMessage).toHaveBeenCalledWith({
+ parts: [{ type: "text", text: "Review Senior Engineer Resume" }],
+ });
+ });
+
+ it("leaves the pending approval alone when the confirm is cancelled", async () => {
+ chat.approvalPending = true;
+ render(<ResumeContainer resume={resume} defaultResumeId={null} />);
+ await clickReview();
+ await userEvent.click(screen.getByRole("button", { name: /^cancel$/i }));
+
+ expect(chat.clear).not.toHaveBeenCalled();
+ expect(chat.sendMessage).not.toHaveBeenCalled();
+ expect(chat.open).not.toHaveBeenCalled();
+ });
+});
diff --git a/__tests__/agentChatRoute.spec.ts b/__tests__/agentChatRoute.spec.ts
index abaccfd..3e4a2ec 100644
--- a/__tests__/agentChatRoute.spec.ts
+++ b/__tests__/agentChatRoute.spec.ts
@@ -28,9 +28,19 @@ const toUIMessageStream = vi.fn(
);
const streamText = vi.fn((..._args: any[]) => ({ toUIMessageStream }));
const streamArgs = (): any => streamText.mock.calls[0]![0];
+// The turn's write-back lives in onFinish, which only fires once the stream is
+// consumed. Captured here so the abort branch can be driven directly.
+let capturedOnFinish: ((arg: any) => Promise<void>) | undefined;
vi.mock("ai", async (importOriginal) => {
const actual = await importOriginal<typeof import("ai")>();
- return { ...actual, streamText: (...args: unknown[]) => streamText(...(args as [])) };
+ return {
+ ...actual,
+ streamText: (...args: unknown[]) => streamText(...(args as [])),
+ createUIMessageStream: (options: any) => {
+ capturedOnFinish = options.onFinish;
+ return actual.createUIMessageStream(options);
+ },
+ };
});
import { POST } from "@/app/api/ai/chat/route";
@@ -43,7 +53,10 @@ import { buildAgentTools } from "@/lib/agent/tools";
import { APP_CONSTANTS } from "@/lib/constants";
import { AGENT_PASTE_PART_TYPE } from "@/models/agent.model";
-const req = (body: unknown) => ({ json: async () => body }) as any;
+// signal is not optional on a real Request — the route composes the turn's
+// abort signal from it so a client disconnect stops generation.
+const req = (body: unknown) =>
+ ({ json: async () => body, signal: new AbortController().signal }) as any;
const pasteMessage = (text: string) => ({
id: "m1",
@@ -105,6 +118,34 @@ describe("POST /api/ai/chat", () => {
expect(saveOrder).toBeLessThan(streamOrder);
});
+ // Clear deletes the conversation row and the cancelled turn's onFinish fires
+ // afterwards — writing there would restore exactly what was just deleted.
+ it("does not write the turn back when it was cancelled", async () => {
+ await POST(req({ messages: [pasteMessage("posting")] }));
+ const afterReceipt = (saveChatConversation as any).mock.calls.length;
+
+ await capturedOnFinish!({
+ messages: [pasteMessage("posting")],
+ responseMessage: undefined,
+ isAborted: true,
+ });
+ expect((saveChatConversation as any).mock.calls.length).toBe(afterReceipt);
+ });
+
+ it("still writes the turn back when it finished normally", async () => {
+ await POST(req({ messages: [pasteMessage("posting")] }));
+ const afterReceipt = (saveChatConversation as any).mock.calls.length;
+
+ await capturedOnFinish!({
+ messages: [pasteMessage("posting")],
+ responseMessage: undefined,
+ isAborted: false,
+ });
+ expect((saveChatConversation as any).mock.calls.length).toBe(
+ afterReceipt + 1,
+ );
+ });
+
// Pasting and hitting Send without typing produces a message whose only
// part is the chip. convertToModelMessages drops that custom data part, so
// the message converts to empty content — and ollama-ai-provider-v2
@@ -166,6 +207,20 @@ describe("POST /api/ai/chat", () => {
expect(args.providerOptions.ollama.think).toBe(true);
});
+ // Without this the client aborting its fetch — stop(), Clear, closing the
+ // panel — was invisible to the server and generation ran to the deadline.
+ it("aborts the generation when the client disconnects", async () => {
+ const controller = new AbortController();
+ await POST({
+ json: async () => ({ messages: [pasteMessage("posting")] }),
+ signal: controller.signal,
+ } as any);
+ const { abortSignal } = streamArgs();
+ expect(abortSignal.aborted).toBe(false);
+ controller.abort();
+ expect(abortSignal.aborted).toBe(true);
+ });
+
it("returns 503 naming Settings when no model is configured, and never guesses one", async () => {
(getUserSettings as any).mockResolvedValue({
success: true,
diff --git a/__tests__/agentReviewResumeTool.spec.ts b/__tests__/agentReviewResumeTool.spec.ts
index bc86778..c3c5a4e 100644
--- a/__tests__/agentReviewResumeTool.spec.ts
+++ b/__tests__/agentReviewResumeTool.spec.ts
@@ -31,11 +31,12 @@ const REVIEW =
// A resume long enough that the old 12k get_resume ceiling would have cut it.
const LONG_RESUME = "R".repeat(APP_CONSTANTS.AGENT_CHAT_RESUME_MAX_CHARS + 5_000);
-function textStreamOf(chunks: string[]) {
+function textStreamOf(chunks: string[], finishReason: unknown = "stop") {
return {
textStream: (async function* () {
for (const chunk of chunks) yield chunk;
})(),
+ finishReason: Promise.resolve(finishReason),
};
}
@@ -181,6 +182,41 @@ describe("review_resume agent tool", () => {
expect(save).not.toHaveBeenCalled();
});
+ // The SCORES line is the FIRST line, so it survives any cut-off after the
+ // first few tokens. Without a completion check a half review parses, scores
+ // and all, and overwrites the last good one.
+ it("saves nothing when the sub-call is aborted mid-stream", async () => {
+ const abortError = Object.assign(new Error("This operation was aborted"), {
+ name: "AbortError",
+ });
+ const rejected = Promise.reject(abortError);
+ rejected.catch(() => {});
+ streamText.mockReturnValue({
+ textStream: (async function* () {
+ yield "SCORES: overall=78 impact=72 clarity=81 ats=69\n\n## Summary\nKhuram presents an";
+ })(),
+ finishReason: rejected,
+ });
+ const result = await execute(buildReviewResumeTool(ctx()), {});
+ expect(result.status).toBe("generation_failed");
+ expect(save).not.toHaveBeenCalled();
+ });
+
+ it.each(["other", "length"])(
+ "saves nothing when the stream ends with finishReason %s",
+ async (finishReason) => {
+ streamText.mockReturnValue(
+ textStreamOf(
+ ["SCORES: overall=78 impact=72 clarity=81 ats=69\n\n## Summary\nCut off mid-"],
+ finishReason,
+ ),
+ );
+ const result = await execute(buildReviewResumeTool(ctx()), {});
+ expect(result.status).toBe("generation_failed");
+ expect(save).not.toHaveBeenCalled();
+ },
+ );
+
it("returns generation_failed rather than throwing when the sub-call errors", async () => {
streamText.mockReturnValue({
textStream: (async function* () {
diff --git a/src/app/api/ai/chat/route.ts b/src/app/api/ai/chat/route.ts
index 1f3c84a..2524fe5 100644
--- a/src/app/api/ai/chat/route.ts
+++ b/src/app/api/ai/chat/route.ts
@@ -154,8 +154,14 @@ export const POST = async (req: NextRequest) => {
modelMessages.push({ role: "user", content: buildPasteContextMessage(block) });
}
- const controller = new AbortController();
- const timer = setTimeout(() => controller.abort(), APP_CONSTANTS.AGENT_CHAT_TIMEOUT_MS);
+ // req.signal is what makes stop()/Clear/close actually stop generating: the
+ // client aborting its fetch is otherwise invisible here, and streamText would
+ // keep pulling tokens until the deadline. Tools inherit this via execute's
+ // abortSignal, so a nested generation is cancelled too.
+ const turnSignal = AbortSignal.any([
+ req.signal,
+ AbortSignal.timeout(APP_CONSTANTS.AGENT_CHAT_TIMEOUT_MS),
+ ]);
const stream = createUIMessageStream({
originalMessages: messages,
@@ -184,7 +190,7 @@ export const POST = async (req: NextRequest) => {
],
// Argument extraction wants determinism.
temperature: TEMPERATURES.ANALYSIS,
- abortSignal: controller.signal,
+ abortSignal: turnSignal,
providerOptions: {
// qwen3.5 is a hybrid-reasoning model and the provider defaults
// think to false. With the thinking channel shut it deliberates in
@@ -198,7 +204,6 @@ export const POST = async (req: NextRequest) => {
writer.merge(result.toUIMessageStream());
},
onFinish: async ({ messages: finalMessages, responseMessage, isAborted }) => {
- clearTimeout(timer);
const { tool, state, outcome } = outcomeOf(responseMessage);
logTurn({
provider,
@@ -210,15 +215,18 @@ export const POST = async (req: NextRequest) => {
pasteChars: pastedText?.length ?? 0,
messageCount: finalMessages.length,
});
+ // A cancelled turn never writes back. Clear deletes the conversation and
+ // this fires afterwards on the stream's cancel path, so saving here would
+ // restore exactly what the user just deleted. The write-on-receipt above
+ // already made their message durable, and an incomplete review is not
+ // worth persisting.
+ if (isAborted) return;
// Stubbing happens here so it lives in exactly one place.
await saveChatConversation(stubConsumedPastes(finalMessages));
},
// NOTE: this signature takes the error directly, unlike streamText's
// onError which takes { error }.
- onError: (error) => {
- clearTimeout(timer);
- return mapAgentError(error, errorContext);
- },
+ onError: (error) => mapAgentError(error, errorContext),
});
return createUIMessageStreamResponse({ stream });
diff --git a/src/components/agent/AgentChatEmptyState.tsx b/src/components/agent/AgentChatEmptyState.tsx
index 9a67a0d..f51cf57 100644
--- a/src/components/agent/AgentChatEmptyState.tsx
+++ b/src/components/agent/AgentChatEmptyState.tsx
@@ -6,7 +6,7 @@ import { useAgentChat } from "@/components/agent/AgentChatProvider";
// Both send immediately on click — neither needs editing first. "Add this
// job posting" has no company/title yet, so the model asks the user to
// paste it rather than calling add_job.
-const EXAMPLES = ["Add this job posting", "Review my resume"];
+const EXAMPLES = ["Add a job posting", "Review resume"];
export function AgentChatEmptyState() {
const { sendMessage, preflight } = useAgentChat();
diff --git a/src/components/agent/AgentChatInput.tsx b/src/components/agent/AgentChatInput.tsx
index f881332..a580a08 100644
--- a/src/components/agent/AgentChatInput.tsx
+++ b/src/components/agent/AgentChatInput.tsx
@@ -76,7 +76,6 @@ export function AgentChatInput() {
error,
clearError,
preflight,
- prefill,
composerNonce,
} = useAgentChat();
@@ -138,12 +137,6 @@ export function AgentChatInput() {
}
}, [approvalPending, status, queued, sendMessage]);
- // The remounted textarea carries the prefill; `text` has to catch up or
- // send stays disabled until the user types a character.
- useEffect(() => {
- if (prefill) setText(prefill.text);
- }, [prefill]);
-
// Clearing the conversation clears the composer with it. The textarea empties
// by remounting on the same nonce below — nothing else resets it.
useEffect(() => {
@@ -234,8 +227,7 @@ export function AgentChatInput() {
{/* Uncontrolled: PromptInput reads the textarea through FormData and
resets it on submit. `text` mirrors it only to enable send. */}
<PromptInputTextarea
- defaultValue={prefill?.text}
- key={prefill?.nonce ?? composerNonce}
+ key={composerNonce}
onChange={(event) => setText(event.currentTarget.value)}
onPaste={onPaste}
placeholder="Ask or paste a job posting…"
diff --git a/src/components/agent/AgentChatProvider.tsx b/src/components/agent/AgentChatProvider.tsx
index eb6e400..4557129 100644
--- a/src/components/agent/AgentChatProvider.tsx
+++ b/src/components/agent/AgentChatProvider.tsx
@@ -23,6 +23,7 @@ import { useRightRail } from "@/context/RightRailContext";
import { useSidebar } from "@/context/SidebarContext";
import { useResizablePanel } from "@/hooks/useResizablePanel";
import { APP_CONSTANTS } from "@/lib/constants";
+import { toastInfo } from "@/lib/toast";
import { clearChatConversation } from "@/actions/agentChat.actions";
import { getUserSettings } from "@/actions/userSettings.actions";
import { checkOllamaConnection } from "@/utils/ai.utils";
@@ -152,6 +153,9 @@ function useAgentChatValue(initialMessages: UIMessage[]) {
if (streamingRef.current) {
chat.stop();
setInterruptedTurn(true);
+ // The one abort the user gets no on-screen signal for — the panel they
+ // would have read it in is the thing that just went away.
+ toastInfo("Generation stopped. Reopen the assistant to continue.");
}
setIsOpen(false);
releaseRail(AGENT_CHAT_PANEL_ID);
@@ -205,32 +209,46 @@ function useAgentChatValue(initialMessages: UIMessage[]) {
if (isOpen && holder !== AGENT_CHAT_PANEL_ID) close();
}, [holder, isOpen, close]);
- // A signal, not a value: the composer's textarea is uncontrolled, so it
- // remounts on the nonce and picks the text up as its defaultValue.
- const [prefill, setPrefill] = useState<{ text: string; nonce: number }>();
- const prefillComposer = useCallback(
- (text: string) => setPrefill({ text, nonce: Date.now() }),
- [],
- );
-
- // Same reason as prefill: nothing else empties an uncontrolled textarea.
+ // A signal, not a value: the composer's textarea is uncontrolled, so
+ // remounting it on the nonce is the only thing that empties it.
const [composerNonce, setComposerNonce] = useState(0);
- // Order matters: a late onFinish would otherwise write the conversation
- // back after the delete.
+ // stop() before the delete is load-bearing: the route skips its onFinish
+ // write when the turn was aborted, and that is what stops a late save from
+ // restoring the conversation this just deleted.
const clear = useCallback(async () => {
+ const wasStreaming = streamingRef.current;
chat.stop();
await clearChatConversation();
chat.setMessages([]);
chat.clearError();
setInterruptedTurn(false);
- // Dropped, not kept: a stale prefill would refill the textarea the next
- // time it remounts.
- setPrefill(undefined);
setComposerNonce((n) => n + 1);
setReviewStreams({});
+ // Clearing an idle conversation aborted nothing worth reporting.
+ if (wasStreaming) toastInfo("Conversation cleared and generation stopped.");
}, [chat]);
+ // Resuming the turn is what ends the interruption — Continue, or simply
+ // typing the next message. Cleared here rather than on a status transition
+ // because close() flags the turn while stop() is still settling, and an
+ // effect watching status would race it back to false.
+ const regenerate = useCallback<typeof chat.regenerate>(
+ (...args) => {
+ setInterruptedTurn(false);
+ return chat.regenerate(...args);
+ },
+ [chat],
+ );
+
+ const sendMessage = useCallback<typeof chat.sendMessage>(
+ (...args) => {
+ setInterruptedTurn(false);
+ return chat.sendMessage(...args);
+ },
+ [chat],
+ );
+
const approvalPending = useMemo(
() => hasPendingApproval(chat.messages),
[chat.messages],
@@ -247,17 +265,15 @@ function useAgentChatValue(initialMessages: UIMessage[]) {
status: chat.status,
error: chat.error,
clearError: chat.clearError,
- sendMessage: chat.sendMessage,
+ sendMessage,
stop: chat.stop,
- regenerate: chat.regenerate,
+ regenerate,
addToolApprovalResponse: chat.addToolApprovalResponse,
approvalPending,
interruptedTurn,
dismissInterrupted,
clear,
preflight,
- prefill,
- prefillComposer,
composerNonce,
panelWidth,
startResize,
diff --git a/src/components/profile/ResumeContainer.tsx b/src/components/profile/ResumeContainer.tsx
index 4767679..9052e20 100644
--- a/src/components/profile/ResumeContainer.tsx
+++ b/src/components/profile/ResumeContainer.tsx
@@ -361,8 +361,13 @@ function ResumeContainer({
const goBack = () => router.back();
const isDefault = !!resume?.id && resume.id === defaultResumeId;
const [setDefaultConfirmOpen, setSetDefaultConfirmOpen] = useState(false);
- const { open: openChat, prefillComposer, sendMessage, approvalPending } =
- useAgentChat();
+ const {
+ open: openChat,
+ sendMessage,
+ clear: clearChat,
+ approvalPending,
+ } = useAgentChat();
+ const [showClearChatConfirm, setShowClearChatConfirm] = useState(false);
const parsedReviewData = useMemo(() => {
if (!resume.reviewData) return null;
try {
@@ -678,6 +683,27 @@ function ResumeContainer({
(s) => s.sectionType === SectionType.SKILLS,
);
+ // Panel first so a failed clear can never leave the button looking dead,
+ // and the review is sent either way — a conversation that would not clear
+ // is no reason to withhold it.
+ const startReview = async () => {
+ openChat();
+ try {
+ await clearChat();
+ } catch {
+ // Reported by the action itself; the review still goes out.
+ }
+ void sendMessage({ parts: [{ type: "text", text: `Review ${title}` }] });
+ };
+
+ const onReviewClick = () => {
+ if (approvalPending) {
+ setShowClearChatConfirm(true);
+ return;
+ }
+ void startReview();
+ };
+
const openContactInfoDialog = () =>
resumeSectionRef.current?.openContactInfoDialog(ContactInfo!);
const openSummaryDialogForEdit = () =>
@@ -766,19 +792,7 @@ function ResumeContainer({
<AddResumeSection resume={resume} ref={resumeSectionRef} />
<Button
className="h-8 gap-1 cursor-pointer"
- onClick={() => {
- openChat();
- // A pending approval already owns the composer's queue slot
- // (see AgentChatInput), which this button can't reach, so it
- // falls back to prefill rather than sending underneath it.
- if (approvalPending) {
- prefillComposer(`Review ${title}`);
- } else {
- void sendMessage({
- parts: [{ type: "text", text: `Review ${title}` }],
- });
- }
- }}
+ onClick={onReviewClick}
size="sm"
variant="outline"
>
@@ -1027,6 +1041,28 @@ function ResumeContainer({
</AlertDialogContent>
</AlertDialog>
+ {/* CLEAR CHAT BEFORE REVIEW CONFIRM */}
+ <AlertDialog
+ open={showClearChatConfirm}
+ onOpenChange={setShowClearChatConfirm}
+ >
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Clear the assistant conversation?</AlertDialogTitle>
+ <AlertDialogDescription>
+ A job is waiting for your approval in the assistant. Starting a
+ review clears the conversation, and that job will not be saved.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction onClick={() => void startReview()}>
+ Clear and review
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+
{/* DISCARD IMPORT CONFIRM */}
<AlertDialog
open={showDiscardImportConfirm}
diff --git a/src/lib/agent/tools/reviewResume.ts b/src/lib/agent/tools/reviewResume.ts
index 4640e24..9e475f1 100644
--- a/src/lib/agent/tools/reviewResume.ts
+++ b/src/lib/agent/tools/reviewResume.ts
@@ -92,6 +92,20 @@ export function buildReviewResumeTool(ctx: ReviewResumeContext) {
transient: true,
});
}
+
+ // The stream running out is not the generation finishing, and neither
+ // case throws: an abort (the user closing the panel) ends textStream
+ // cleanly and rejects this promise, and a response body that stops
+ // without Ollama's done chunk resolves it to "other". The SCORES line
+ // is the first thing emitted, so both leave a fragment that parses.
+ const finishReason = await sub.finishReason;
+ if (finishReason !== "stop") {
+ return {
+ status: "generation_failed",
+ title,
+ reason: "The review stopped before it finished, so nothing was saved.",
+ };
+ }
} catch (error) {
console.error("[agent-chat] review_resume generation failed:", error);
return {
diff --git a/src/lib/toast.ts b/src/lib/toast.ts
index 5091855..05ca98f 100644
--- a/src/lib/toast.ts
+++ b/src/lib/toast.ts
@@ -12,6 +12,12 @@ export function toastError(message?: string, title?: string) {
else toast.error(text);
}
+// For outcomes that are neither: a deliberate interruption is not an error.
+export function toastInfo(message: string, title?: string) {
+ if (title) toast.info(title, { description: message });
+ else toast.info(message);
+}
+
// Collapses the repeated success/error branch into one call.
export function toastActionResult<T>(
result: ActionResult<T> | undefined,