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.
TypeScript ai-agentai-resume-analyzerapplication-trackerapplication-tracking-systematscareerjob-applicationjob-automationjob-huntingjob-searchjob-seeker-toolsjob-trackerjob-trackingjobsearchjobseekersmcpollamaresumeresume-reviewself-hosted
feat: agent chat panel, trigger and transcript
Khuram Niazc23f3a30085b
diff --git a/__tests__/AgentChatClosePaths.spec.tsx b/__tests__/AgentChatClosePaths.spec.tsxnew file mode 100644index 0000000..d6d0a53--- /dev/null+++ b/__tests__/AgentChatClosePaths.spec.tsx@@ -0,0 +1,138 @@+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(),+};+vi.mock("@ai-sdk/react", () => ({+ useChat: () => chat,+}));++vi.mock("next/navigation", () => ({+ useRouter: () => ({ refresh: vi.fn() }),+ 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 } from "@/components/agent/AgentChatProvider";+import { AgentChatPanel } from "@/components/agent/AgentChatPanel";+import { AgentChatTrigger } from "@/components/AgentChatTrigger";+import { RightRailProvider, useRightRail } from "@/context/RightRailContext";++function OtherPanel() {+ const { requestOpen } = useRightRail();+ return <button onClick={() => requestOpen("review")}>open review</button>;+}++const setup = (initialMessages: any[] = []) =>+ render(+ <RightRailProvider>+ <AgentChatProvider initialMessages={initialMessages}>+ <AgentChatTrigger />+ <OtherPanel />+ <AgentChatPanel />+ </AgentChatProvider>+ </RightRailProvider>,+ );++const openPanel = async () => {+ await act(async () => {+ await userEvent.click(screen.getByRole("button", { name: /open assistant/i }));+ });+};++const approvalMessage = {+ id: "a1",+ role: "assistant",+ parts: [+ {+ type: "tool-add_job",+ toolCallId: "c1",+ state: "approval-requested",+ input: { company: "Acme" },+ approval: { id: "ap1" },+ },+ ],+};++describe("agent chat close paths", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ chat.messages = [];+ chat.status = "streaming";+ chat.error = undefined;+ });++ it("stops the stream when the panel's close button is used", async () => {+ setup();+ await openPanel();+ await act(async () => {+ await userEvent.click(screen.getByRole("button", { name: "Close chat" }));+ });+ expect(chat.stop).toHaveBeenCalled();+ });++ it("stops the stream on Escape", async () => {+ setup();+ await openPanel();+ await act(async () => {+ await userEvent.keyboard("{Escape}");+ });+ expect(chat.stop).toHaveBeenCalled();+ });++ it("stops the stream when another panel takes the right rail", async () => {+ setup();+ await openPanel();+ await act(async () => {+ await userEvent.click(screen.getByText("open review"));+ });+ expect(chat.stop).toHaveBeenCalled();+ });++ it("stops the stream when the Header trigger toggles it shut", async () => {+ setup();+ await openPanel();+ await act(async () => {+ await userEvent.click(+ screen.getByRole("button", { name: /close assistant/i }),+ );+ });+ expect(chat.stop).toHaveBeenCalled();+ });++ it("flags a pending approval on the trigger", () => {+ chat.messages = [approvalMessage];+ setup([approvalMessage]);+ expect(screen.getByLabelText("Approval pending")).toBeInTheDocument();+ });++ it("never advertises streaming on the trigger — nothing runs while closed", () => {+ chat.status = "streaming";+ setup();+ expect(screen.queryByLabelText("Approval pending")).not.toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: /open assistant/i }).textContent,+ ).toBe("AI Agent");+ });+});diff --git a/__tests__/AgentChatMessages.spec.tsx b/__tests__/AgentChatMessages.spec.tsxnew file mode 100644index 0000000..3e54534--- /dev/null+++ b/__tests__/AgentChatMessages.spec.tsx@@ -0,0 +1,137 @@+import { render, screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { AGENT_PASTE_PART_TYPE } from "@/models/agent.model";++const chat = {+ messages: [] as any[],+ status: "ready" as string,+ regenerate: vi.fn(),+ resumeStream: vi.fn(),+ addToolApprovalResponse: vi.fn(),+ interruptedTurn: false,+ dismissInterrupted: vi.fn(),+};+vi.mock("@/components/agent/AgentChatProvider", () => ({+ useAgentChat: () => chat,+}));++import { AgentChatMessages } from "@/components/agent/AgentChatMessages";++const toolPart = (state: string, extra: Record<string, unknown> = {}) => ({+ type: "tool-add_job",+ toolCallId: "c1",+ state,+ input: { company: "Acme", jobTitle: "Platform Engineer" },+ ...extra,+});++const assistant = (parts: any[]) => ({ id: "a1", role: "assistant", parts });+const user = (parts: any[]) => ({ id: "u1", role: "user", parts });++const posting = "Senior Platform Engineer at Acme. We run payments reliability.";++describe("AgentChatMessages", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ chat.messages = [];+ chat.status = "ready";+ chat.interruptedTurn = false;+ });++ it("renders the running card while the tool input is still arriving", () => {+ chat.messages = [assistant([toolPart("input-available")])];+ render(<AgentChatMessages />);+ expect(screen.getByText(/preparing to add a job/i)).toBeInTheDocument();+ });++ it("renders the approval card for approval-requested", () => {+ chat.messages = [+ assistant([toolPart("approval-requested", { approval: { id: "ap1" } })]),+ ];+ render(<AgentChatMessages />);+ expect(screen.getByText("Needs approval")).toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Confirm" })).toBeInTheDocument();+ });++ it("renders the result card for output-available", () => {+ chat.messages = [+ assistant([+ toolPart("output-available", {+ output: { created: true, jobId: "j1", resolutions: [] },+ }),+ ]),+ ];+ render(<AgentChatMessages />);+ expect(screen.getByText(/added/i)).toBeInTheDocument();+ expect(screen.queryByText("Needs approval")).not.toBeInTheDocument();+ });++ it("feeds the approval card the pasted text from the same thread", () => {+ chat.messages = [+ user([+ { type: "text", text: "add this" },+ {+ type: AGENT_PASTE_PART_TYPE,+ id: "p1",+ data: {+ id: "p1",+ text: posting,+ chars: posting.length,+ truncated: false,+ },+ },+ ]),+ assistant([toolPart("approval-requested", { approval: { id: "ap1" } })]),+ ];+ render(<AgentChatMessages />);+ expect(screen.getByText(/pasted verbatim/i)).toBeInTheDocument();+ expect(screen.getByText(new RegExp(posting.slice(0, 30)))).toBeInTheDocument();+ });++ it("offers Continue on an interrupted turn and calls regenerate only on click", async () => {+ chat.interruptedTurn = true;+ chat.messages = [assistant([{ type: "text", text: "half a s" }])];+ render(<AgentChatMessages />);++ expect(chat.regenerate).not.toHaveBeenCalled();+ expect(chat.resumeStream).not.toHaveBeenCalled();++ await userEvent.click(screen.getByRole("button", { name: /continue/i }));+ expect(chat.regenerate).toHaveBeenCalled();+ expect(chat.resumeStream).not.toHaveBeenCalled();+ });++ it("lets the interrupted notice be dismissed", async () => {+ chat.interruptedTurn = true;+ chat.messages = [assistant([{ type: "text", text: "half a s" }])];+ render(<AgentChatMessages />);+ await userEvent.click(screen.getByRole("button", { name: /dismiss/i }));+ expect(chat.dismissInterrupted).toHaveBeenCalled();+ });++ it("offers Continue when a seeded transcript ends with a user message", () => {+ chat.messages = [user([{ type: "text", text: "add a job" }])];+ render(<AgentChatMessages />);+ expect(screen.getByRole("button", { name: /continue/i })).toBeInTheDocument();+ });++ it("does not offer Continue after a completed assistant turn", () => {+ chat.messages = [+ user([{ type: "text", text: "add a job" }]),+ assistant([{ type: "text", text: "Done." }]),+ ];+ render(<AgentChatMessages />);+ expect(+ screen.queryByRole("button", { name: /continue/i }),+ ).not.toBeInTheDocument();+ });++ it("renders assistant text as plain text, never as markdown media", () => {+ chat.messages = [+ assistant([{ type: "text", text: "" }]),+ ];+ const { container } = render(<AgentChatMessages />);+ expect(container.innerHTML).not.toContain("<img");+ expect(screen.getByText("")).toBeInTheDocument();+ });+});diff --git a/__tests__/JobDetailsPage.spec.tsx b/__tests__/JobDetailsPage.spec.tsxnew file mode 100644index 0000000..01f14ce--- /dev/null+++ b/__tests__/JobDetailsPage.spec.tsx@@ -0,0 +1,68 @@+import JobDetailsPage from "@/app/dashboard/myjobs/[id]/page";++const notFound = vi.fn(() => {+ throw new Error("NEXT_NOT_FOUND");+});++vi.mock("next/navigation", () => ({+ notFound: () => notFound(),+}));++const getJobDetails = vi.fn();++vi.mock("@/actions/job.actions", () => ({+ getJobDetails: (id: string) => getJobDetails(id),+ getJobSourceList: vi.fn(async () => []),+ getStatusList: vi.fn(async () => []),+}));++vi.mock("@/actions/company.actions", () => ({+ getAllCompanies: vi.fn(async () => []),+}));++vi.mock("@/actions/jobtitle.actions", () => ({+ getAllJobTitles: vi.fn(async () => []),+}));++vi.mock("@/actions/jobLocation.actions", () => ({+ getAllJobLocations: vi.fn(async () => []),+}));++vi.mock("@/actions/tag.actions", () => ({+ getAllTags: vi.fn(async () => []),+}));++vi.mock("@/components/myjobs/JobDetails", () => ({+ default: () => <div data-testid="job-details" />,+}));++describe("JobDetailsPage", () => {+ beforeEach(() => {+ notFound.mockClear();+ });++ // A chat/tool-card link to a job that was later deleted lands here.+ it("renders not found when the job does not resolve for the user", async () => {+ getJobDetails.mockResolvedValue({ job: null, success: true });++ await expect(+ JobDetailsPage({ params: Promise.resolve({ id: "missing-job" }) }),+ ).rejects.toThrow("NEXT_NOT_FOUND");+ expect(notFound).toHaveBeenCalled();+ });++ it("renders not found when the fetch failed", async () => {+ getJobDetails.mockResolvedValue({ success: false, message: "boom" });++ await expect(+ JobDetailsPage({ params: Promise.resolve({ id: "any" }) }),+ ).rejects.toThrow("NEXT_NOT_FOUND");+ });++ it("renders the job when it resolves", async () => {+ getJobDetails.mockResolvedValue({ job: { id: "job-1" }, success: true });++ await JobDetailsPage({ params: Promise.resolve({ id: "job-1" }) });+ expect(notFound).not.toHaveBeenCalled();+ });+});diff --git a/e2e/agent-chat.spec.ts b/e2e/agent-chat.spec.tsnew file mode 100644index 0000000..7dc6ff4--- /dev/null+++ b/e2e/agent-chat.spec.ts@@ -0,0 +1,210 @@+import { type Page } from "@playwright/test";+import { test, expect } from "./fixtures";++// The chat writes nothing of its own to the DB — /api/ai/chat is stubbed, so+// the route's persistence and the model never run. No cleanup registration.++const SSE_HEADERS = {+ "content-type": "text/event-stream",+ "cache-control": "no-cache",+ "x-vercel-ai-ui-message-stream": "v1",+};++// Matches JsonToSseTransformStream: one `data: <json>` frame per chunk, then+// the [DONE] terminator DefaultChatTransport's parser stops on.+function sse(chunks: Record<string, unknown>[]): string {+ return (+ chunks.map((chunk) => `data: ${JSON.stringify(chunk)}\n\n`).join("") ++ "data: [DONE]\n\n"+ );+}++function textTurn(text: string): Record<string, unknown>[] {+ return [+ { type: "start" },+ { type: "start-step" },+ { type: "text-start", id: "t1" },+ { type: "text-delta", id: "t1", delta: text },+ { type: "text-end", id: "t1" },+ { type: "finish-step" },+ { type: "finish" },+ ];+}++const ADD_JOB_INPUT = {+ company: "Northwind Trading",+ jobTitle: "Staff Platform Engineer",+ location: "Remote",+ source: "Company website",+ jobUrl: "https://northwind.example/careers/42",+ salaryRange: "$190k – $220k",+ tags: ["kubernetes", "go"],+};++function approvalTurn(): Record<string, unknown>[] {+ return [+ { type: "start" },+ { type: "start-step" },+ { type: "tool-input-start", toolCallId: "call-1", toolName: "add_job" },+ {+ type: "tool-input-available",+ toolCallId: "call-1",+ toolName: "add_job",+ input: ADD_JOB_INPUT,+ },+ { type: "tool-approval-request", approvalId: "appr-1", toolCallId: "call-1" },+ { type: "finish-step" },+ { type: "finish" },+ ];+}++// The denial POST continues the SAME assistant message, so it must carry that+// message's id — exactly what the real route does via `originalMessages`.+function deniedTurn(messageId: string): Record<string, unknown>[] {+ return [+ { type: "start", messageId },+ { type: "start-step" },+ { type: "tool-output-denied", toolCallId: "call-1" },+ { type: "finish-step" },+ { type: "finish" },+ ];+}++async function openChat(page: Page) {+ await page.goto("/dashboard/myjobs");+ await page.getByRole("button", { name: "Open assistant" }).click();+ // A shared user can carry a transcript in from another run or a manual+ // pass, so start from Clear. Then reload: clear() calls setMessages([])+ // only after the server action resolves, and waiting on the HTTP response+ // is not enough — it resolves on headers, while the action settles after+ // the RSC body is parsed. A late wipe would swallow the first message the+ // test sends. Remounting past it is deterministic; the row is already+ // deleted by the time the response arrives.+ await Promise.all([+ page.waitForResponse(+ (res) => res.request().method() === "POST" && res.url().includes("/dashboard"),+ ),+ page.getByRole("button", { name: "Clear" }).click(),+ ]);+ await page.reload();+ await page.getByRole("button", { name: "Open assistant" }).click();+ await expect(page.getByText(/I can add a job to your tracker/)).toBeVisible();+}++async function send(page: Page, text: string) {+ const box = page.getByRole("textbox", { name: /ask or paste/i });+ await box.fill(text);+ await page.getByRole("button", { name: "Send" }).click();+}++test.describe("agent chat", () => {+ test("opens from the header, leaves the page usable, and closes", async ({+ page,+ }) => {+ await openChat(page);++ // Docked, not a takeover: the page behind is still clickable, and the+ // panel survives the navigation because the provider is in the layout.+ await page.getByRole("link", { name: "Tasks" }).click();+ await expect(page).toHaveURL(/\/dashboard\/tasks/);+ await expect(page.getByRole("button", { name: "Clear" })).toBeVisible();++ await page.getByRole("button", { name: "Close chat" }).click();+ await expect(page.getByRole("button", { name: "Clear" })).toBeHidden();+ await expect(+ page.getByRole("button", { name: "Open assistant" }),+ ).toBeVisible();+ });++ test("keeps the transcript across navigation and reopening", async ({+ page,+ }) => {+ await page.route("**/api/ai/chat", (route) =>+ route.fulfill({+ headers: SSE_HEADERS,+ body: sse(textTurn("I can add a job for you.")),+ }),+ );++ await openChat(page);+ await send(page, "hello there");+ await expect(page.getByText("I can add a job for you.")).toBeVisible();++ await page.getByRole("link", { name: "Tasks" }).click();+ await expect(page).toHaveURL(/\/dashboard\/tasks/);+ await expect(page.getByText("I can add a job for you.")).toBeVisible();++ await page.getByRole("button", { name: "Close chat" }).click();+ await page.getByRole("button", { name: "Open assistant" }).click();+ await expect(page.getByText("hello there")).toBeVisible();+ await expect(page.getByText("I can add a job for you.")).toBeVisible();+ });++ test("turns an over-threshold paste into a chip instead of a wall of text", async ({+ page,+ }) => {+ await openChat(page);++ const posting = `Staff Platform Engineer at Northwind. ${"Responsibilities include running the payments platform. ".repeat(+ 40,+ )}`;+ const box = page.getByRole("textbox", { name: /ask or paste/i });+ await box.click();+ await box.evaluate((el, text) => {+ const data = new DataTransfer();+ data.setData("text/plain", text);+ el.dispatchEvent(+ new ClipboardEvent("paste", {+ clipboardData: data,+ bubbles: true,+ cancelable: true,+ }),+ );+ }, posting);++ await expect(page.getByText(/Pasted posting ·/)).toBeVisible();+ await expect(box).toHaveValue("");+ await page.getByRole("button", { name: "Remove pasted content" }).click();+ await expect(page.getByText(/Pasted posting ·/)).toBeHidden();+ });++ test("renders the approval card and creates nothing when it is cancelled", async ({+ page,+ }) => {+ let call = 0;+ await page.route("**/api/ai/chat", async (route) => {+ call += 1;+ if (call === 1) {+ await route.fulfill({ headers: SSE_HEADERS, body: sse(approvalTurn()) });+ return;+ }+ const body = route.request().postDataJSON() as {+ messages: { id: string }[];+ };+ const lastId = body.messages[body.messages.length - 1].id;+ await route.fulfill({+ headers: SSE_HEADERS,+ body: sse(deniedTurn(lastId)),+ });+ });++ await openChat(page);+ await send(page, "add the Northwind role");++ await expect(page.getByText("Needs approval")).toBeVisible();+ await expect(page.getByText("Northwind Trading")).toBeVisible();+ await expect(page.getByText("Staff Platform Engineer")).toBeVisible();+ await expect(page.getByText("$190k – $220k")).toBeVisible();+ await expect(page.getByRole("button", { name: "Confirm" })).toBeVisible();++ await page.getByRole("button", { name: "Cancel" }).click();+ await page.getByRole("button", { name: "Skip" }).click();++ await expect(page.getByText("Cancelled — nothing was saved.")).toBeVisible();+ await expect(page.getByRole("button", { name: "Confirm" })).toBeHidden();++ // Nothing reached the jobs list.+ await page.goto("/dashboard/myjobs");+ await expect(page.getByText("Staff Platform Engineer")).toBeHidden();+ });+});diff --git a/src/app/dashboard/layout.tsx b/src/app/dashboard/layout.tsxindex 726e490..6a5ae5d 100644--- a/src/app/dashboard/layout.tsx+++ b/src/app/dashboard/layout.tsx@@ -5,6 +5,10 @@ import { ActivityProvider } from "@/context/ActivityContext";import { GlobalActivityBanner } from "@/components/activities/GlobalActivityBanner";import { SidebarProvider } from "@/context/SidebarContext";import SidebarInset from "@/components/SidebarInset";+import { RightRailProvider } from "@/context/RightRailContext";+import { AgentChatProvider } from "@/components/agent/AgentChatProvider";+import { AgentChatPanel } from "@/components/agent/AgentChatPanel";+import { getChatConversation } from "@/actions/agentChat.actions";import { APP_CONSTANTS } from "@/lib/constants";export default async function RootLayout({@@ -15,20 +19,31 @@ export default async function RootLayout({const cookieStore = await cookies();const sidebarCookie = cookieStore.get(APP_CONSTANTS.SIDEBAR_STORAGE_KEY);const initialExpanded = sidebarCookie ? sidebarCookie.value === "true" : true;+ // Loaded here rather than in the client: avoids an empty-panel flash on+ // every load, and the race where a message sent before hydration completes+ // is merged against an empty transcript and then persisted.+ const conversation = await getChatConversation();return (<ActivityProvider><SidebarProvider initialExpanded={initialExpanded}>- <div className="flex min-h-screen w-full flex-col bg-muted/40">- <Sidebar />- <SidebarInset>- <Header />- <GlobalActivityBanner />- <main className="flex-1 md:block lg:grid items-start gap-4 p-4 sm:px-6 sm:py-0 md:gap-4 lg:grid-cols-3 xl:grid-cols-3">- {children}- </main>- </SidebarInset>- </div>+ <RightRailProvider>+ <AgentChatProvider initialMessages={conversation.data ?? []}>+ <div className="flex min-h-screen w-full flex-col bg-muted/40">+ <Sidebar />+ <SidebarInset>+ <Header />+ <GlobalActivityBanner />+ <main className="flex-1 md:block lg:grid items-start gap-4 p-4 sm:px-6 sm:py-0 md:gap-4 lg:grid-cols-3 xl:grid-cols-3">+ {children}+ </main>+ </SidebarInset>+ {/* Portaled, so it sits outside the 3-column grid and needs no+ col-span-3 wrapper. */}+ <AgentChatPanel />+ </div>+ </AgentChatProvider>+ </RightRailProvider></SidebarProvider></ActivityProvider>);diff --git a/src/app/dashboard/myjobs/[id]/page.tsx b/src/app/dashboard/myjobs/[id]/page.tsxindex 02e44cf..aaa071b 100644--- a/src/app/dashboard/myjobs/[id]/page.tsx+++ b/src/app/dashboard/myjobs/[id]/page.tsx@@ -8,6 +8,7 @@ import { getAllCompanies } from "@/actions/company.actions";import { getAllJobTitles } from "@/actions/jobtitle.actions";import { getAllJobLocations } from "@/actions/jobLocation.actions";import { getAllTags } from "@/actions/tag.actions";+import { notFound } from "next/navigation";async function JobDetailsPage({ params }: { params: Promise<{ id: string }> }) {const { id } = await params;@@ -22,6 +23,10 @@ async function JobDetailsPage({ params }: { params: Promise<{ id: string }> }) {getAllTags(),]);+ // A link to a job that was deleted (or never belonged to this user) would+ // otherwise crash JobDetails on the first job.* read.+ if (!job) notFound();+return (<div className="col-span-3"><JobDetailsdiff --git a/src/app/dashboard/not-found.tsx b/src/app/dashboard/not-found.tsxnew file mode 100644index 0000000..f3b9b48--- /dev/null+++ b/src/app/dashboard/not-found.tsx@@ -0,0 +1,18 @@+import Link from "next/link";+import { FileQuestion } from "lucide-react";+import { Button } from "@/components/ui/button";++export default function NotFound() {+ return (+ <div className="col-span-3 flex flex-col items-center justify-center py-24 text-center">+ <FileQuestion className="h-12 w-12 text-muted-foreground mb-4" />+ <h3 className="text-lg font-medium">Not found</h3>+ <p className="text-muted-foreground mt-2">+ This page doesn't exist, or the record was deleted.+ </p>+ <Button asChild variant="outline" className="mt-6">+ <Link href="/dashboard">Back to dashboard</Link>+ </Button>+ </div>+ );+}diff --git a/src/components/AgentChatTrigger.tsx b/src/components/AgentChatTrigger.tsxnew file mode 100644index 0000000..f526b75--- /dev/null+++ b/src/components/AgentChatTrigger.tsx@@ -0,0 +1,29 @@+"use client";++import { MessageSquare } from "lucide-react";+import { Button } from "@/components/ui/button";+import { useAgentChat } from "@/components/agent/AgentChatProvider";++export function AgentChatTrigger() {+ const { isOpen, open, close, approvalPending } = useAgentChat();++ return (+ <Button+ variant="outline"+ className="relative"+ aria-label={isOpen ? "Close assistant" : "Open assistant"}+ onClick={() => (isOpen ? close() : open())}+ >+ <MessageSquare className="h-4 w-4" />+ AI Agent+ {/* Deliberately no streaming state: nothing generates while the panel+ is closed, so there is no background activity to advertise. */}+ {approvalPending && (+ <span+ className="absolute right-1 top-1 h-2 w-2 rounded-full bg-primary"+ aria-label="Approval pending"+ />+ )}+ </Button>+ );+}diff --git a/src/components/Header.tsx b/src/components/Header.tsxindex cf97854..69fec07 100644--- a/src/components/Header.tsx+++ b/src/components/Header.tsx@@ -14,6 +14,7 @@ import { signOut } from "@/auth";import { getCurrentUser } from "@/utils/user.utils";import { ProfileDropdown } from "./ProfileDropdown";import SidebarToggle from "./SidebarToggle";+import { AgentChatTrigger } from "./AgentChatTrigger";async function Header() {// const session = await auth();@@ -71,6 +72,8 @@ async function Header() {/> */}</div>+ <AgentChatTrigger />+<ProfileDropdownuser={user}signOutAction={async () => {diff --git a/src/components/agent/AgentChatEmptyState.tsx b/src/components/agent/AgentChatEmptyState.tsxnew file mode 100644index 0000000..ee3b3af--- /dev/null+++ b/src/components/agent/AgentChatEmptyState.tsx@@ -0,0 +1,41 @@+"use client";++import { Suggestion, Suggestions } from "@/components/ai-elements/suggestion";+import { useAgentChat } from "@/components/agent/AgentChatProvider";++// Complete prompts, not fragments — clicking one fills the composer so it can+// be edited before it costs a 30–60s local generation.+const EXAMPLES = [+ "Add this job posting",+ "Add a job: Senior Platform Engineer at Stripe, remote",+];++export function AgentChatEmptyState() {+ const { preflight, prefillComposer } = useAgentChat();++ return (+ <div className="flex flex-1 flex-col justify-end gap-4 p-4">+ {/* Stated up front rather than left to the model to confess: a local 8B+ asked what it can do will happily invent capabilities. */}+ <p className="text-sm text-muted-foreground">+ I can add a job to your tracker — paste a posting or type the details,+ and I'll show you what I extracted before anything is saved. I+ can't read your existing jobs, resumes or tasks yet.+ </p>++ {preflight.checked && !preflight.ok ? (+ <p className="text-sm text-destructive">{preflight.error}</p>+ ) : (+ <Suggestions>+ {EXAMPLES.map((example) => (+ <Suggestion+ key={example}+ onClick={prefillComposer}+ suggestion={example}+ />+ ))}+ </Suggestions>+ )}+ </div>+ );+}diff --git a/src/components/agent/AgentChatInput.tsx b/src/components/agent/AgentChatInput.tsxindex 41e6b5f..5ed4529 100644--- a/src/components/agent/AgentChatInput.tsx+++ b/src/components/agent/AgentChatInput.tsx@@ -12,7 +12,6 @@ import {} from "@/components/ai-elements/attachments";import {PromptInput,- PromptInputBody,PromptInputFooter,PromptInputHeader,PromptInputSubmit,@@ -67,6 +66,7 @@ export function AgentChatInput() {error,clearError,preflight,+ prefill,} = useAgentChat();const [text, setText] = useState("");@@ -127,6 +127,12 @@ 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]);+const onStop = useCallback(() => {void stop();}, [stop]);@@ -179,50 +185,52 @@ export function AgentChatInput() {<p className="text-xs text-muted-foreground">{preflight.error}</p>) : null}+ {/* No PromptInputBody: it wraps these in a display:contents div, and+ InputGroup only stacks vertically via has-[>[data-align=block-end]],+ a DOM-child selector that wrapper defeats. Nested, the group stays a+ row and the textarea collapses to a ~24px sliver beside the footer. */}<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…"+ {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+ defaultValue={prefill?.text}+ key={prefill?.nonce}+ 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>- <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>+ </PromptInputFooter></PromptInput></div>);diff --git a/src/components/agent/AgentChatMessages.tsx b/src/components/agent/AgentChatMessages.tsxnew file mode 100644index 0000000..8037b1b--- /dev/null+++ b/src/components/agent/AgentChatMessages.tsx@@ -0,0 +1,141 @@+"use client";++import { useState } from "react";+import { FileTextIcon, XIcon } from "lucide-react";+import { isStaticToolUIPart, type UIMessage } from "ai";+import {+ Conversation,+ ConversationContent,+ ConversationScrollButton,+} from "@/components/ai-elements/conversation";+import { Button } from "@/components/ui/button";+import { AgentApprovalCard } from "@/components/agent/AgentApprovalCard";+import { AgentResultCard } from "@/components/agent/AgentResultCard";+import { AgentToolRunningCard } from "@/components/agent/AgentToolRunningCard";+import { useAgentChat } from "@/components/agent/AgentChatProvider";+import { resolvePastedText } from "@/lib/agent/paste";+import { cn } from "@/lib/utils";+import { isAgentPastePart, type AgentPastePartData } from "@/models/agent.model";++function PasteChip({ data }: { data: AgentPastePartData }) {+ const chars = data.chars.toLocaleString();+ return (+ <span className="inline-flex items-center gap-1.5 rounded-sm border bg-muted/30 px-2 py-1 text-xs text-muted-foreground">+ <FileTextIcon className="size-3" />+ Pasted posting · {chars} chars{data.truncated ? " (truncated)" : ""}+ </span>+ );+}++// The seeded transcript ending on a user message means the reply never came+// back — the tab was closed mid-turn, or the server died. Same remedy as an+// explicitly interrupted turn.+function endsAwaitingReply(messages: UIMessage[]): boolean {+ return messages[messages.length - 1]?.role === "user";+}++export function AgentChatMessages() {+ const {+ messages,+ regenerate,+ addToolApprovalResponse,+ interruptedTurn,+ dismissInterrupted,+ } = useAgentChat();+ const [dismissed, setDismissed] = useState(false);++ const pastedText = resolvePastedText(messages);+ const showContinue =+ !dismissed && (interruptedTurn || endsAwaitingReply(messages));++ const dismiss = () => {+ setDismissed(true);+ dismissInterrupted();+ };++ return (+ <Conversation className="flex-1">+ <ConversationContent className="gap-4">+ {messages.map((message) => (+ <div+ key={message.id}+ className={cn(+ "flex flex-col gap-2 text-sm",+ message.role === "user" && "items-end",+ )}+ >+ {message.parts.map((part, i) => {+ if (part.type === "text") {+ return (+ <p+ key={i}+ className={cn(+ "whitespace-pre-wrap break-words",+ message.role === "user" &&+ "rounded-md bg-muted px-3 py-2",+ )}+ >+ {part.text}+ </p>+ );+ }+ if (isAgentPastePart(part))+ return <PasteChip key={i} data={part.data} />;+ // Static, not dynamic: every tool this surface exposes is+ // declared in buildAgentTools, so a dynamic part is not ours.+ if (!isStaticToolUIPart(part)) return null;+ switch (part.state) {+ case "input-streaming":+ case "input-available":+ return <AgentToolRunningCard key={i} part={part} />;+ case "approval-requested":+ case "approval-responded":+ return (+ <AgentApprovalCard+ key={i}+ part={part}+ pastedText={pastedText}+ onRespond={addToolApprovalResponse}+ />+ );+ // Default, not a case list: AgentResultCard already returns+ // null for anything it does not recognize, and rendering+ // nothing beats rendering an unknown future state raw.+ default:+ return <AgentResultCard key={i} part={part} />;+ }+ })}+ </div>+ ))}++ {showContinue && (+ <div className="flex items-center gap-2 rounded-md border bg-muted/20 px-3 py-2 text-xs text-muted-foreground">+ <span className="flex-1">This reply was interrupted.</span>+ {/* Offered, never automatic — the user closed the panel, and+ silently restarting a 30–60s local generation on reopen undoes+ their own action. */}+ <Button+ onClick={() => void regenerate()}+ size="sm"+ type="button"+ variant="outline"+ >+ Continue+ </Button>+ <Button+ aria-label="Dismiss"+ className="size-6 shrink-0"+ onClick={dismiss}+ size="icon"+ type="button"+ variant="ghost"+ >+ <XIcon className="size-3.5" />+ </Button>+ </div>+ )}+ </ConversationContent>+ <ConversationScrollButton />+ </Conversation>+ );+}diff --git a/src/components/agent/AgentChatPanel.tsx b/src/components/agent/AgentChatPanel.tsxnew file mode 100644index 0000000..38a2e60--- /dev/null+++ b/src/components/agent/AgentChatPanel.tsx@@ -0,0 +1,88 @@+"use client";++import { X } from "lucide-react";+import { Sheet, SheetContent, SheetTitle } from "@/components/ui/sheet";+import { Button } from "@/components/ui/button";+import { AgentChatEmptyState } from "@/components/agent/AgentChatEmptyState";+import { AgentChatInput } from "@/components/agent/AgentChatInput";+import { AgentChatMessages } from "@/components/agent/AgentChatMessages";+import { useAgentChat } from "@/components/agent/AgentChatProvider";+import { useResizablePanel } from "@/hooks/useResizablePanel";+import { APP_CONSTANTS } from "@/lib/constants";++export function AgentChatPanel() {+ const { isOpen, close, clear, messages } = useAgentChat();+ // Not "ai-panel-width": that key is shared by the three AI sheets, and+ // dragging this panel would silently resize all of them.+ const { width, handleMouseDown } = useResizablePanel(+ APP_CONSTANTS.AGENT_CHAT_PANEL_WIDTH_KEY,+ );++ return (+ <Sheet+ open={isOpen}+ onOpenChange={(next) => {+ if (!next) close();+ }}+ modal={false}+ >+ <SheetContent+ overlay={false}+ // Docked, not a takeover: without these the first click on the jobs+ // list behind the panel would dismiss it, and refreshing that list+ // after a write would be pointless.+ onInteractOutside={(event) => event.preventDefault()}+ onPointerDownOutside={(event) => event.preventDefault()}+ className="flex flex-col p-0 overflow-hidden [&>button:last-child]:hidden w-full max-w-full sm:max-w-full lg:w-(--agent-chat-w) lg:max-w-(--agent-chat-max)"+ style={+ {+ "--agent-chat-w": `${width}px`,+ "--agent-chat-max": `${APP_CONSTANTS.RESIZABLE_PANEL_MAX_WIDTH_RATIO * 100}vw`,+ } as React.CSSProperties+ }+ >+ {/* VS Code-style drag handle; docking only applies at lg+ */}+ <div+ className="absolute left-0 top-0 h-full w-1 cursor-col-resize z-10 group hidden lg:block"+ onMouseDown={handleMouseDown}+ >+ <div className="h-full w-px bg-transparent group-hover:bg-primary/50 transition-colors" />+ </div>++ <div className="flex items-center gap-3 px-4 py-2.5 border-b bg-muted/20 shrink-0">+ <SheetTitle className="text-[11px] font-bold tracking-[0.15em] uppercase text-foreground leading-none shrink-0 m-0">+ JOBSYNC AGENT+ </SheetTitle>+ <span className="text-muted-foreground/30 text-xs select-none">+ ···+ </span>+ {/* Never gated on the approval: it is the way out of a card whose+ approvalId the server no longer recognizes. */}+ <Button+ className="h-6 ml-auto shrink-0 rounded-sm px-2 text-xs opacity-70 hover:opacity-100"+ onClick={() => void clear()}+ size="sm"+ variant="ghost"+ >+ Clear+ </Button>+ <Button+ aria-label="Close chat"+ className="h-6 w-6 shrink-0 rounded-sm opacity-70 hover:opacity-100"+ onClick={close}+ size="icon"+ variant="ghost"+ >+ <X className="h-3.5 w-3.5" />+ </Button>+ </div>++ {messages.length > 0 ? <AgentChatMessages /> : <AgentChatEmptyState />}++ <div className="shrink-0 border-t p-3">+ <AgentChatInput />+ </div>+ </SheetContent>+ </Sheet>+ );+}diff --git a/src/components/agent/AgentChatProvider.tsx b/src/components/agent/AgentChatProvider.tsxindex 3fb227e..32f75a6 100644--- a/src/components/agent/AgentChatProvider.tsx+++ b/src/components/agent/AgentChatProvider.tsx@@ -150,6 +150,14 @@ function useAgentChatValue(initialMessages: UIMessage[]) {const dismissInterrupted = useCallback(() => setInterruptedTurn(false), []);+ // 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() }),+ [],+ );+return {isOpen,open,@@ -167,6 +175,8 @@ function useAgentChatValue(initialMessages: UIMessage[]) {dismissInterrupted,clear,preflight,+ prefill,+ prefillComposer,};}