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.

feat: agent chat provider and composer

Khuram Niaz4a3c14684870
diff --git a/__tests__/AgentChatInput.spec.tsx b/__tests__/AgentChatInput.spec.tsx
new file mode 100644
index 0000000..a8c0be4
--- /dev/null
+++ b/__tests__/AgentChatInput.spec.tsx
@@ -0,0 +1,171 @@
+import { render, screen } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { APP_CONSTANTS } from "@/lib/constants";
+import { AGENT_PASTE_PART_TYPE } from "@/models/agent.model";
+
+const chat = {
+ sendMessage: vi.fn(),
+ stop: vi.fn(),
+ status: "ready" as string,
+ approvalPending: false,
+ error: undefined as Error | undefined,
+ clearError: vi.fn(),
+ preflight: { checked: true, ok: true } as any,
+};
+vi.mock("@/components/agent/AgentChatProvider", () => ({
+ useAgentChat: () => chat,
+}));
+
+import { AgentChatInput } from "@/components/agent/AgentChatInput";
+
+const paste = async (text: string) => {
+ const box = screen.getByRole("textbox");
+ box.focus();
+ await userEvent.paste(text);
+};
+
+const short = "a short pasted note";
+const long = "x".repeat(APP_CONSTANTS.AGENT_CHAT_PASTE_THRESHOLD + 100);
+const huge = "y".repeat(APP_CONSTANTS.AGENT_CHAT_PASTE_MAX_CHARS + 1000);
+
+describe("AgentChatInput", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ chat.status = "ready";
+ chat.approvalPending = false;
+ chat.error = undefined;
+ chat.preflight = { checked: true, ok: true };
+ });
+
+ it("leaves a short paste inline in the textarea", async () => {
+ render(<AgentChatInput />);
+ await paste(short);
+ // Not toHaveValue: jest-dom does not reliably accept asymmetric matchers.
+ expect((screen.getByRole("textbox") as HTMLTextAreaElement).value).toContain(
+ short,
+ );
+ expect(screen.queryByText(/pasted/i)).not.toBeInTheDocument();
+ });
+
+ it("turns an over-threshold paste into a removable chip", async () => {
+ render(<AgentChatInput />);
+ await paste(long);
+ expect(screen.getByText(/pasted/i)).toBeInTheDocument();
+ expect(screen.getByRole("textbox")).toHaveValue("");
+ await userEvent.click(screen.getByRole("button", { name: /remove/i }));
+ expect(screen.queryByText(/pasted/i)).not.toBeInTheDocument();
+ });
+
+ it("truncates and labels a paste above the ceiling", async () => {
+ render(<AgentChatInput />);
+ await paste(huge);
+ expect(screen.getByText(/truncated/i)).toBeInTheDocument();
+ await userEvent.type(screen.getByRole("textbox"), "add this");
+ await userEvent.click(screen.getByRole("button", { name: /send/i }));
+ const parts = chat.sendMessage.mock.calls[0][0].parts;
+ const pastePart = parts.find((p: any) => p.type === AGENT_PASTE_PART_TYPE);
+ expect(pastePart.data.text.length).toBe(
+ APP_CONSTANTS.AGENT_CHAT_PASTE_MAX_CHARS,
+ );
+ expect(pastePart.data.truncated).toBe(true);
+ });
+
+ it("sends the chip as a data part alongside the text", async () => {
+ render(<AgentChatInput />);
+ await paste(long);
+ await userEvent.type(screen.getByRole("textbox"), "add this job");
+ await userEvent.click(screen.getByRole("button", { name: /send/i }));
+ const parts = chat.sendMessage.mock.calls[0][0].parts;
+ expect(
+ parts.some((p: any) => p.type === "text" && p.text === "add this job"),
+ ).toBe(true);
+ expect(parts.some((p: any) => p.type === AGENT_PASTE_PART_TYPE)).toBe(true);
+ });
+
+ it("queues rather than sends while an approval is pending", async () => {
+ chat.approvalPending = true;
+ render(<AgentChatInput />);
+ await userEvent.type(screen.getByRole("textbox"), "the company is wrong");
+ await userEvent.click(screen.getByRole("button", { name: /send/i }));
+ expect(chat.sendMessage).not.toHaveBeenCalled();
+ expect(screen.getByText(/waiting on your approval/i)).toBeInTheDocument();
+ expect(screen.getByText(/the company is wrong/)).toBeInTheDocument();
+ });
+
+ it("keeps a new paste out of messages while the card is open — the paste-drift invariant", async () => {
+ chat.approvalPending = true;
+ render(<AgentChatInput />);
+ await paste(long);
+ await userEvent.click(screen.getByRole("button", { name: /send/i }));
+ expect(chat.sendMessage).not.toHaveBeenCalled();
+ });
+
+ it("dispatches the queued message once the approval resolves", async () => {
+ chat.approvalPending = true;
+ const { rerender } = render(<AgentChatInput />);
+ await userEvent.type(screen.getByRole("textbox"), "the company is wrong");
+ await userEvent.click(screen.getByRole("button", { name: /send/i }));
+ chat.approvalPending = false;
+ rerender(<AgentChatInput />);
+ expect(chat.sendMessage).toHaveBeenCalled();
+ expect(chat.sendMessage.mock.calls[0][0].parts[0].text).toBe(
+ "the company is wrong",
+ );
+ });
+
+ it("holds the queued message while the approval's follow-up POST is streaming", async () => {
+ // approvalPending clears at the same instant sendAutomaticallyWhen fires
+ // the POST that executes the approved tool. Dispatching on that render
+ // would race it — the queue waits for status to return to ready.
+ chat.approvalPending = true;
+ const { rerender } = render(<AgentChatInput />);
+ await userEvent.type(screen.getByRole("textbox"), "the company is wrong");
+ await userEvent.click(screen.getByRole("button", { name: /send/i }));
+ chat.approvalPending = false;
+ chat.status = "streaming";
+ rerender(<AgentChatInput />);
+ expect(chat.sendMessage).not.toHaveBeenCalled();
+ chat.status = "ready";
+ rerender(<AgentChatInput />);
+ expect(chat.sendMessage).toHaveBeenCalledTimes(1);
+ });
+
+ it("lets the user discard a queued message", async () => {
+ chat.approvalPending = true;
+ render(<AgentChatInput />);
+ await userEvent.type(screen.getByRole("textbox"), "never mind");
+ await userEvent.click(screen.getByRole("button", { name: /send/i }));
+ await userEvent.click(
+ screen.getByRole("button", { name: /remove from queue/i }),
+ );
+ chat.approvalPending = false;
+ expect(chat.sendMessage).not.toHaveBeenCalled();
+ });
+
+ it("swaps send for stop while streaming", async () => {
+ chat.status = "streaming";
+ render(<AgentChatInput />);
+ await userEvent.click(screen.getByRole("button", { name: /stop/i }));
+ expect(chat.stop).toHaveBeenCalled();
+ });
+
+ it("shows a dismissible error banner above the composer", async () => {
+ chat.error = new Error("Cannot reach ollama.");
+ render(<AgentChatInput />);
+ expect(screen.getByText(/cannot reach ollama/i)).toBeInTheDocument();
+ await userEvent.click(
+ screen.getByRole("button", { name: /dismiss error/i }),
+ );
+ expect(chat.clearError).toHaveBeenCalled();
+ });
+
+ it("disables sending entirely when the preflight failed", () => {
+ chat.preflight = {
+ checked: true,
+ ok: false,
+ error: "Ollama is not reachable.",
+ };
+ render(<AgentChatInput />);
+ expect(screen.getByRole("button", { name: /send/i })).toBeDisabled();
+ });
+});
diff --git a/__tests__/AgentChatProvider.spec.tsx b/__tests__/AgentChatProvider.spec.tsx
new file mode 100644
index 0000000..d0c871b
--- /dev/null
+++ b/__tests__/AgentChatProvider.spec.tsx
@@ -0,0 +1,184 @@
+import { render, screen, act } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+
+const chat = {
+ messages: [] as any[],
+ status: "ready" as string,
+ error: undefined as Error | undefined,
+ sendMessage: vi.fn(),
+ stop: vi.fn(),
+ regenerate: vi.fn(),
+ clearError: vi.fn(),
+ addToolApprovalResponse: vi.fn(),
+ setMessages: vi.fn(),
+};
+const useChatSpy = vi.fn((..._args: any[]) => chat);
+vi.mock("@ai-sdk/react", () => ({
+ useChat: (...a: unknown[]) => useChatSpy(...(a as [])),
+}));
+
+const chatInit = (call = 0) => useChatSpy.mock.calls[call][0] as any;
+
+const refresh = vi.fn();
+vi.mock("next/navigation", () => ({
+ useRouter: () => ({ refresh }),
+ usePathname: () => "/dashboard/myjobs",
+}));
+
+vi.mock("@/actions/agentChat.actions", () => ({
+ clearChatConversation: vi.fn(async () => ({ success: true })),
+}));
+vi.mock("@/actions/userSettings.actions", () => ({
+ getUserSettings: vi.fn(async () => ({
+ success: true,
+ data: { settings: { ai: { provider: "ollama", model: "qwen3.5:9b" } } },
+ })),
+}));
+vi.mock("@/utils/ai.utils", () => ({
+ checkOllamaConnection: vi.fn(async () => ({ isConnected: true })),
+}));
+
+import {
+ AgentChatProvider,
+ useAgentChat,
+} from "@/components/agent/AgentChatProvider";
+import { RightRailProvider, useRightRail } from "@/context/RightRailContext";
+import { clearChatConversation } from "@/actions/agentChat.actions";
+import { getUserSettings } from "@/actions/userSettings.actions";
+import { checkOllamaConnection } from "@/utils/ai.utils";
+
+function Probe() {
+ const c = useAgentChat();
+ const { holder } = useRightRail();
+ return (
+ <div>
+ <button onClick={c.open}>open</button>
+ <button onClick={c.close}>close</button>
+ <button onClick={c.clear}>clear</button>
+ <span data-testid="state">{`${c.isOpen}|${c.approvalPending}|${c.interruptedTurn}|${holder}|${c.preflight.ok}`}</span>
+ </div>
+ );
+}
+
+const setup = (initialMessages: any[] = []) =>
+ render(
+ <RightRailProvider>
+ <AgentChatProvider initialMessages={initialMessages}>
+ <Probe />
+ </AgentChatProvider>
+ </RightRailProvider>,
+ );
+
+const approvalMessage = {
+ id: "a1",
+ role: "assistant",
+ parts: [
+ {
+ type: "tool-add_job",
+ toolCallId: "c1",
+ state: "approval-requested",
+ input: { company: "Acme" },
+ approval: { id: "ap1" },
+ },
+ ],
+};
+
+describe("AgentChatProvider", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ chat.messages = [];
+ chat.status = "ready";
+ chat.error = undefined;
+ });
+
+ it("seeds useChat with the persisted transcript", () => {
+ setup([{ id: "m1", role: "user", parts: [{ type: "text", text: "hi" }] }]);
+ expect(chatInit().messages).toHaveLength(1);
+ });
+
+ it("wires sendAutomaticallyWhen, without which an approved tool never executes", () => {
+ setup();
+ expect(chatInit().sendAutomaticallyWhen).toBeTypeOf("function");
+ });
+
+ it("claims the right rail on open and releases it on close", async () => {
+ setup();
+ await userEvent.click(screen.getByText("open"));
+ expect(screen.getByTestId("state").textContent).toContain(
+ "true|false|false|chat",
+ );
+ await userEvent.click(screen.getByText("close"));
+ expect(screen.getByTestId("state").textContent).toContain(
+ "false|false|false|null",
+ );
+ });
+
+ it("stops the stream on close and flags the turn interrupted", async () => {
+ chat.status = "streaming";
+ setup();
+ await userEvent.click(screen.getByText("open"));
+ await userEvent.click(screen.getByText("close"));
+ expect(chat.stop).toHaveBeenCalled();
+ expect(screen.getByTestId("state").textContent).toContain("|true|");
+ });
+
+ it("does not flag an interrupted turn when nothing was streaming", async () => {
+ setup();
+ await userEvent.click(screen.getByText("open"));
+ await userEvent.click(screen.getByText("close"));
+ expect(screen.getByTestId("state").textContent).toContain(
+ "false|false|false|null",
+ );
+ });
+
+ it("reports a pending approval from a rehydrated transcript", () => {
+ chat.messages = [approvalMessage];
+ setup([approvalMessage]);
+ expect(screen.getByTestId("state").textContent).toContain("|true|");
+ });
+
+ it("does not report a pending approval for an ordinary reply", () => {
+ chat.messages = [
+ { id: "a1", role: "assistant", parts: [{ type: "text", text: "sure" }] },
+ ];
+ setup();
+ expect(screen.getByTestId("state").textContent).toContain("|false|");
+ });
+
+ it("clears in order: stop, delete, reset", async () => {
+ chat.status = "streaming";
+ setup();
+ await userEvent.click(screen.getByText("clear"));
+ const stopOrder = chat.stop.mock.invocationCallOrder[0];
+ const deleteOrder = (clearChatConversation as any).mock
+ .invocationCallOrder[0];
+ const resetOrder = chat.setMessages.mock.invocationCallOrder[0];
+ expect(stopOrder).toBeLessThan(deleteOrder);
+ expect(deleteOrder).toBeLessThan(resetOrder);
+ });
+
+ it("preflights Ollama on open and reports a failure", async () => {
+ (checkOllamaConnection as any).mockResolvedValue({
+ isConnected: false,
+ error: "Ollama is not reachable.",
+ });
+ setup();
+ await act(async () => {
+ await userEvent.click(screen.getByText("open"));
+ });
+ expect(screen.getByTestId("state").textContent).toMatch(/false$/);
+ });
+
+ it("fails the preflight when no model is configured, without probing Ollama", async () => {
+ (getUserSettings as any).mockResolvedValue({
+ success: true,
+ data: { settings: { ai: { provider: "ollama", model: undefined } } },
+ });
+ setup();
+ await act(async () => {
+ await userEvent.click(screen.getByText("open"));
+ });
+ expect(screen.getByTestId("state").textContent).toMatch(/false$/);
+ expect(checkOllamaConnection).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/components/agent/AgentChatInput.tsx b/src/components/agent/AgentChatInput.tsx
new file mode 100644
index 0000000..41e6b5f
--- /dev/null
+++ b/src/components/agent/AgentChatInput.tsx
@@ -0,0 +1,229 @@
+"use client";
+
+import { useCallback, useEffect, useState } from "react";
+import { XIcon } from "lucide-react";
+import type { TextUIPart } from "ai";
+import {
+ Attachment,
+ AttachmentInfo,
+ AttachmentPreview,
+ Attachments,
+ type AttachmentData,
+} from "@/components/ai-elements/attachments";
+import {
+ PromptInput,
+ PromptInputBody,
+ PromptInputFooter,
+ PromptInputHeader,
+ PromptInputSubmit,
+ PromptInputTextarea,
+} from "@/components/ai-elements/prompt-input";
+import { Alert, AlertDescription } from "@/components/ui/alert";
+import { Button } from "@/components/ui/button";
+import { useAgentChat } from "@/components/agent/AgentChatProvider";
+import { APP_CONSTANTS } from "@/lib/constants";
+import {
+ AGENT_PASTE_PART_TYPE,
+ isAgentPastePart,
+ type AgentPastePart,
+ type AgentPastePartData,
+} from "@/models/agent.model";
+
+type ComposerPart = TextUIPart | AgentPastePart;
+
+function chipLabel(chip: AgentPastePartData): string {
+ const chars = chip.chars.toLocaleString();
+ return chip.truncated
+ ? `Pasted posting · ${chars} chars (truncated)`
+ : `Pasted posting · ${chars} chars`;
+}
+
+// Synthesized at render time only. The wire format stays the custom data part:
+// a real FileUIPart is a standard type, so convertToModelMessages would carry
+// the whole posting to the model and defeat head truncation.
+function chipAttachment(chip: AgentPastePartData): AttachmentData {
+ return {
+ type: "file",
+ id: chip.id,
+ mediaType: "text/plain",
+ filename: chipLabel(chip),
+ url: "",
+ };
+}
+
+function queuedText(parts: ComposerPart[]): string {
+ const text = parts.find((part) => part.type === "text");
+ const chip = parts.find(isAgentPastePart);
+ if (text?.type === "text" && text.text) return text.text;
+ return chip ? chipLabel(chip.data) : "";
+}
+
+export function AgentChatInput() {
+ const {
+ sendMessage,
+ stop,
+ status,
+ approvalPending,
+ error,
+ clearError,
+ preflight,
+ } = useAgentChat();
+
+ const [text, setText] = useState("");
+ const [chip, setChip] = useState<AgentPastePartData | undefined>();
+ const [queued, setQueued] = useState<ComposerPart[] | undefined>();
+
+ const onPaste = (event: React.ClipboardEvent<HTMLTextAreaElement>) => {
+ const pasted = event.clipboardData.getData("text/plain");
+ if (pasted.length < APP_CONSTANTS.AGENT_CHAT_PASTE_THRESHOLD) return;
+ event.preventDefault();
+ const truncated = pasted.length > APP_CONSTANTS.AGENT_CHAT_PASTE_MAX_CHARS;
+ // The ceiling is enforced here, at chip creation, so nothing beyond it
+ // ever enters `messages` or the conversation row.
+ const body = truncated
+ ? pasted.slice(0, APP_CONSTANTS.AGENT_CHAT_PASTE_MAX_CHARS)
+ : pasted;
+ setChip({
+ id: crypto.randomUUID(),
+ text: body,
+ chars: body.length,
+ truncated,
+ });
+ };
+
+ const submit = (submitted: string) => {
+ const trimmed = submitted.trim();
+ const parts: ComposerPart[] = [
+ ...(trimmed ? [{ type: "text" as const, text: trimmed }] : []),
+ ...(chip
+ ? [
+ {
+ type: AGENT_PASTE_PART_TYPE,
+ id: chip.id,
+ data: chip,
+ } satisfies AgentPastePart,
+ ]
+ : []),
+ ];
+ if (parts.length === 0) return;
+ if (approvalPending) {
+ setQueued(parts); // client-only, never persisted
+ } else {
+ sendMessage({ parts });
+ }
+ setText("");
+ setChip(undefined);
+ };
+
+ // Dispatches once the approval resolves AND the follow-up POST that executes
+ // the approved tool has finished. approvalPending flips false at the same
+ // instant sendAutomaticallyWhen fires that POST — dispatching on that render
+ // would race it, and if sendMessage interrupts the in-flight stream, the
+ // approved tool can be cut off mid-execution server-side.
+ useEffect(() => {
+ if (!approvalPending && status === "ready" && queued) {
+ sendMessage({ parts: queued });
+ setQueued(undefined);
+ }
+ }, [approvalPending, status, queued, sendMessage]);
+
+ const onStop = useCallback(() => {
+ void stop();
+ }, [stop]);
+
+ const isGenerating = status === "submitted" || status === "streaming";
+ const canSend = preflight.ok && (text.trim().length > 0 || !!chip);
+
+ return (
+ <div className="flex flex-col gap-2">
+ {error ? (
+ <Alert variant="destructive" className="flex items-start gap-2">
+ <AlertDescription className="flex-1">
+ {error.message}
+ </AlertDescription>
+ <Button
+ aria-label="Dismiss error"
+ className="size-6 shrink-0"
+ onClick={clearError}
+ size="icon"
+ type="button"
+ variant="ghost"
+ >
+ <XIcon className="size-3.5" />
+ </Button>
+ </Alert>
+ ) : null}
+
+ {queued ? (
+ <div className="flex items-start gap-2 rounded-md border bg-muted/30 p-2 text-sm">
+ <div className="min-w-0 flex-1">
+ <p className="text-xs text-muted-foreground">
+ Queued — waiting on your approval above
+ </p>
+ <p className="truncate">{queuedText(queued)}</p>
+ </div>
+ <Button
+ aria-label="Remove from queue"
+ className="size-6 shrink-0"
+ onClick={() => setQueued(undefined)}
+ size="icon"
+ type="button"
+ variant="ghost"
+ >
+ <XIcon className="size-3.5" />
+ </Button>
+ </div>
+ ) : null}
+
+ {preflight.checked && !preflight.ok && preflight.error ? (
+ <p className="text-xs text-muted-foreground">{preflight.error}</p>
+ ) : null}
+
+ <PromptInput onSubmit={(message) => submit(message.text)}>
+ <PromptInputBody>
+ {chip ? (
+ <PromptInputHeader>
+ <Attachments variant="inline">
+ <Attachment data={chipAttachment(chip)}>
+ <AttachmentPreview />
+ <AttachmentInfo />
+ {/* Not AttachmentRemove: it repeats its label in an sr-only
+ span, so the chip's wording would appear twice. */}
+ <Button
+ aria-label="Remove pasted content"
+ className="size-5 shrink-0 rounded p-0 [&_svg]:size-2.5"
+ onClick={() => setChip(undefined)}
+ type="button"
+ variant="ghost"
+ >
+ <XIcon />
+ </Button>
+ </Attachment>
+ </Attachments>
+ </PromptInputHeader>
+ ) : null}
+ {/* Uncontrolled: PromptInput reads the textarea through FormData and
+ resets it on submit. `text` mirrors it only to enable send. */}
+ <PromptInputTextarea
+ onChange={(event) => setText(event.currentTarget.value)}
+ onPaste={onPaste}
+ placeholder="Ask or paste a job posting…"
+ />
+ <PromptInputFooter>
+ <span className="text-xs text-muted-foreground">
+ {approvalPending && !queued
+ ? "Waiting on your approval above"
+ : ""}
+ </span>
+ <PromptInputSubmit
+ aria-label={isGenerating ? "Stop response" : "Send"}
+ disabled={!isGenerating && !canSend}
+ onStop={onStop}
+ status={status}
+ />
+ </PromptInputFooter>
+ </PromptInputBody>
+ </PromptInput>
+ </div>
+ );
+}
diff --git a/src/components/agent/AgentChatProvider.tsx b/src/components/agent/AgentChatProvider.tsx
new file mode 100644
index 0000000..3fb227e
--- /dev/null
+++ b/src/components/agent/AgentChatProvider.tsx
@@ -0,0 +1,194 @@
+"use client";
+
+import {
+ createContext,
+ useCallback,
+ useContext,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
+import { useRouter, usePathname } from "next/navigation";
+import { useChat } from "@ai-sdk/react";
+import {
+ DefaultChatTransport,
+ isToolUIPart,
+ lastAssistantMessageIsCompleteWithApprovalResponses,
+ type UIMessage,
+} from "ai";
+import { hasPendingApproval } from "@/lib/agent/paste";
+import { useRightRail } from "@/context/RightRailContext";
+import { clearChatConversation } from "@/actions/agentChat.actions";
+import { getUserSettings } from "@/actions/userSettings.actions";
+import { checkOllamaConnection } from "@/utils/ai.utils";
+import { AiProvider } from "@/models/ai.model";
+import type { AgentAddJobResult, PageContext } from "@/models/agent.model";
+
+export const AGENT_CHAT_PANEL_ID = "chat";
+
+type Preflight = { checked: boolean; ok: boolean; error?: string };
+
+type AgentChatValue = ReturnType<typeof useAgentChatValue>;
+
+const AgentChatContext = createContext<AgentChatValue | null>(null);
+
+function useAgentChatValue(initialMessages: UIMessage[]) {
+ const router = useRouter();
+ const pathname = usePathname();
+ const { holder, requestOpen, close: releaseRail } = useRightRail();
+
+ const [isOpen, setIsOpen] = useState(false);
+ const [interruptedTurn, setInterruptedTurn] = useState(false);
+ const [preflight, setPreflight] = useState<Preflight>({
+ checked: false,
+ ok: true,
+ });
+
+ const pageContextRef = useRef<PageContext>({ route: pathname });
+ useEffect(() => {
+ pageContextRef.current = { route: pathname };
+ }, [pathname]);
+
+ const chat = useChat({
+ messages: initialMessages,
+ transport: new DefaultChatTransport({
+ api: "/api/ai/chat",
+ prepareSendMessagesRequest: ({ messages }) => ({
+ body: { messages, pageContext: pageContextRef.current },
+ }),
+ }),
+ // Without this the approval is resolved client-side and nothing ever
+ // POSTs back to execute the tool. It is the mechanism, not a nicety.
+ sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithApprovalResponses,
+ onFinish: ({ message }) => {
+ const wrote = (message?.parts ?? []).some((part) => {
+ if (!isToolUIPart(part) || part.state !== "output-available")
+ return false;
+ return (part.output as AgentAddJobResult | undefined)?.created === true;
+ });
+ // Unconditional: an RSC refresh on an irrelevant page is a wasted
+ // request, not a bug. A stale jobs list behind the panel right after
+ // watching a job get created reads as one.
+ if (wrote) router.refresh();
+ },
+ });
+
+ const streamingRef = useRef(false);
+ streamingRef.current =
+ chat.status === "streaming" || chat.status === "submitted";
+
+ // Every close path funnels through here — the X button, Escape, rail
+ // eviction, and the Header trigger toggling it shut. That is what
+ // guarantees nothing generates while the panel is closed.
+ const close = useCallback(() => {
+ if (streamingRef.current) {
+ chat.stop();
+ setInterruptedTurn(true);
+ }
+ setIsOpen(false);
+ releaseRail(AGENT_CHAT_PANEL_ID);
+ }, [chat, releaseRail]);
+
+ const runPreflight = useCallback(async () => {
+ const settings = await getUserSettings();
+ const ai = settings?.data?.settings?.ai;
+ const provider = ai?.provider ?? AiProvider.OLLAMA;
+
+ // No model configured is a configuration error, not a guess. Caught here
+ // so the empty state says it and send is disabled — the user never
+ // spends a turn to learn it, and the route's 503 stays the backstop.
+ if (!ai?.model) {
+ setPreflight({
+ checked: true,
+ ok: false,
+ error:
+ "No AI model is configured. Pick one in Settings to use the assistant.",
+ });
+ return;
+ }
+
+ if (provider !== AiProvider.OLLAMA) {
+ setPreflight({ checked: true, ok: true });
+ return;
+ }
+ const result = await checkOllamaConnection(provider);
+ setPreflight({
+ checked: true,
+ ok: result.isConnected,
+ error: result.isConnected
+ ? undefined
+ : (result.error ?? "Ollama is not reachable."),
+ });
+ }, []);
+
+ const open = useCallback(() => {
+ requestOpen(AGENT_CHAT_PANEL_ID);
+ setIsOpen(true);
+ void runPreflight();
+ }, [requestOpen, runPreflight]);
+
+ // Losing the rail to another panel is a close, with the same abort.
+ useEffect(() => {
+ if (isOpen && holder !== AGENT_CHAT_PANEL_ID) close();
+ }, [holder, isOpen, close]);
+
+ // Order matters: a late onFinish would otherwise write the conversation
+ // back after the delete.
+ const clear = useCallback(async () => {
+ chat.stop();
+ await clearChatConversation();
+ chat.setMessages([]);
+ chat.clearError();
+ setInterruptedTurn(false);
+ }, [chat]);
+
+ const approvalPending = useMemo(
+ () => hasPendingApproval(chat.messages),
+ [chat.messages],
+ );
+
+ const dismissInterrupted = useCallback(() => setInterruptedTurn(false), []);
+
+ return {
+ isOpen,
+ open,
+ close,
+ messages: chat.messages,
+ status: chat.status,
+ error: chat.error,
+ clearError: chat.clearError,
+ sendMessage: chat.sendMessage,
+ stop: chat.stop,
+ regenerate: chat.regenerate,
+ addToolApprovalResponse: chat.addToolApprovalResponse,
+ approvalPending,
+ interruptedTurn,
+ dismissInterrupted,
+ clear,
+ preflight,
+ };
+}
+
+export function AgentChatProvider({
+ initialMessages,
+ children,
+}: {
+ initialMessages: UIMessage[];
+ children: React.ReactNode;
+}) {
+ const value = useAgentChatValue(initialMessages);
+ return (
+ <AgentChatContext.Provider value={value}>
+ {children}
+ </AgentChatContext.Provider>
+ );
+}
+
+export function useAgentChat() {
+ const ctx = useContext(AgentChatContext);
+ if (!ctx) {
+ throw new Error("useAgentChat must be used within an AgentChatProvider");
+ }
+ return ctx;
+}