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: refresh the jobs list on the add_job write, and answer the add-job suggestion without a turn

Khuram Niaz0742ab58173a
diff --git a/__tests__/AgentChatEmptyState.spec.tsx b/__tests__/AgentChatEmptyState.spec.tsx
new file mode 100644
index 0000000..2929b13
--- /dev/null
+++ b/__tests__/AgentChatEmptyState.spec.tsx
@@ -0,0 +1,54 @@
+import { render, screen } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+
+const sendMessage = vi.fn();
+const seedExchange = vi.fn();
+let preflight = { checked: true, ok: true };
+
+vi.mock("@/components/agent/AgentChatProvider", () => ({
+ useAgentChat: () => ({ sendMessage, seedExchange, preflight }),
+}));
+
+import { AgentChatEmptyState } from "@/components/agent/AgentChatEmptyState";
+import { AGENT_ADD_JOB_INTRO } from "@/lib/agent/prompt";
+
+describe("AgentChatEmptyState", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ preflight = { checked: true, ok: true };
+ });
+
+ // The click carries no company, title or posting, so add_job is
+ // unreachable and the prompt leaves the model one legal reply. Spending a
+ // 15-30s turn on it is latency for text we already know.
+ it("answers the add-job suggestion locally instead of calling the model", async () => {
+ render(<AgentChatEmptyState />);
+ await userEvent.click(screen.getByText("Add a job posting"));
+
+ expect(sendMessage).not.toHaveBeenCalled();
+ expect(seedExchange).toHaveBeenCalledWith(
+ "Add a job posting",
+ AGENT_ADD_JOB_INTRO,
+ );
+ });
+
+ // The other three end in a tool call whose outcome depends on the page.
+ it("sends the tool-backed suggestions to the model", async () => {
+ render(<AgentChatEmptyState />);
+ await userEvent.click(screen.getByText("Match a job"));
+
+ expect(seedExchange).not.toHaveBeenCalled();
+ expect(sendMessage).toHaveBeenCalledWith({
+ parts: [{ type: "text", text: "Match a job" }],
+ });
+ });
+
+ it("does nothing when preflight failed", async () => {
+ preflight = { checked: true, ok: false };
+ render(<AgentChatEmptyState />);
+ await userEvent.click(screen.getByText("Add a job posting"));
+
+ expect(seedExchange).not.toHaveBeenCalled();
+ expect(sendMessage).not.toHaveBeenCalled();
+ });
+});
diff --git a/__tests__/AgentChatProvider.spec.tsx b/__tests__/AgentChatProvider.spec.tsx
index d65b55e..f2d9267 100644
--- a/__tests__/AgentChatProvider.spec.tsx
+++ b/__tests__/AgentChatProvider.spec.tsx
@@ -28,6 +28,7 @@ vi.mock("next/navigation", () => ({
vi.mock("@/actions/agentChat.actions", () => ({
clearChatConversation: vi.fn(async () => ({ success: true })),
+ saveChatConversation: vi.fn(async () => ({ success: true })),
}));
vi.mock("@/actions/userSettings.actions", () => ({
getUserSettings: vi.fn(async () => ({
@@ -46,7 +47,10 @@ import {
} from "@/components/agent/AgentChatProvider";
import { RightRailProvider, useRightRail } from "@/context/RightRailContext";
import { SidebarProvider, useSidebar } from "@/context/SidebarContext";
-import { clearChatConversation } from "@/actions/agentChat.actions";
+import {
+ clearChatConversation,
+ saveChatConversation,
+} from "@/actions/agentChat.actions";
import { getUserSettings } from "@/actions/userSettings.actions";
import { checkOllamaConnection } from "@/utils/ai.utils";
@@ -67,6 +71,9 @@ function Probe() {
>
sendMessage
</button>
+ <button onClick={() => c.seedExchange("Add a job posting", "canned")}>
+ seedExchange
+ </button>
<button onClick={c.clearQueued}>clearQueued</button>
<span data-testid="queued">
{c.queued ? (c.queued.parts[0] as any).text : ""}
@@ -78,6 +85,7 @@ function Probe() {
<span data-testid="composer-nonce">{c.composerNonce}</span>
<span data-testid="panel-expanded">{String(c.isPanelExpanded)}</span>
<span data-testid="review-stream">{c.toolStreams["rv1"] ?? ""}</span>
+ <span data-testid="job-writes">{c.jobWrites}</span>
</div>
);
}
@@ -122,6 +130,28 @@ describe("AgentChatProvider", () => {
expect(chatInit().messages).toHaveLength(1);
});
+ // The canned exchange never reaches the route, so it is the one pair that
+ // has to persist itself or it disappears on the next reload.
+ it("appends a seeded exchange to the transcript and persists it", async () => {
+ chat.messages = [{ id: "m1", role: "user", parts: [] }];
+ setup();
+ await userEvent.click(screen.getByText("seedExchange"));
+
+ expect(chat.sendMessage).not.toHaveBeenCalled();
+ const next = chat.setMessages.mock.calls[0][0];
+ expect(next).toHaveLength(3);
+ expect(next[1]).toMatchObject({
+ role: "user",
+ parts: [{ type: "text", text: "Add a job posting" }],
+ });
+ expect(next[2]).toMatchObject({
+ role: "assistant",
+ parts: [{ type: "text", text: "canned" }],
+ });
+ expect(next[1].id).not.toBe(next[2].id);
+ expect(saveChatConversation).toHaveBeenCalledWith(next);
+ });
+
it("wires sendAutomaticallyWhen, without which an approved tool never executes", () => {
setup();
expect(chatInit().sendAutomaticallyWhen).toBeTypeOf("function");
@@ -417,6 +447,40 @@ describe("AgentChatProvider", () => {
],
} as any;
+ // add_job's approval splits the call and the execution across two POSTs, so
+ // stopWhen cannot end the second one — the model narrates the write in a
+ // full extra generation. Waiting for onFinish left the list stale for it.
+ it("announces a job write as soon as add_job returns, mid-stream", async () => {
+ const { rerender } = setup();
+ expect(screen.getByTestId("job-writes").textContent).toBe("0");
+
+ chat.messages = [createdToolMessage];
+ await act(async () => {
+ rerender(tree());
+ });
+
+ expect(screen.getByTestId("job-writes").textContent).toBe("1");
+ expect(refresh).toHaveBeenCalledTimes(1);
+
+ // The completed part stays in the transcript for every later token, so
+ // without the tool-call-id guard the prose would re-announce it.
+ chat.messages = [createdToolMessage, { id: "a4", role: "assistant", parts: [] }];
+ await act(async () => {
+ rerender(tree());
+ });
+ expect(screen.getByTestId("job-writes").textContent).toBe("1");
+ expect(refresh).toHaveBeenCalledTimes(1);
+ });
+
+ // The panel is mounted with the persisted conversation on every page load.
+ it("does not announce a job write seeded from the persisted transcript", async () => {
+ chat.messages = [createdToolMessage];
+ setup([createdToolMessage]);
+
+ expect(screen.getByTestId("job-writes").textContent).toBe("0");
+ expect(refresh).not.toHaveBeenCalled();
+ });
+
// The route stubs only the copy it writes to the DB. Without the client
// doing the same to its own transcript, the next thing the user types
// re-injects the posting and calls add_job again on the job just saved.
diff --git a/src/components/agent/AgentChatEmptyState.tsx b/src/components/agent/AgentChatEmptyState.tsx
index 67fc5fd..2fc0d54 100644
--- a/src/components/agent/AgentChatEmptyState.tsx
+++ b/src/components/agent/AgentChatEmptyState.tsx
@@ -2,24 +2,30 @@
import { Suggestion, Suggestions } from "@/components/ai-elements/suggestion";
import { useAgentChat } from "@/components/agent/AgentChatProvider";
+import { AGENT_ADD_JOB_INTRO } from "@/lib/agent/prompt";
-// All send immediately on click — none need 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. "Match a job" and "Generate cover
-// letter" have no page context here, so the tools reply with a graceful
-// "no_job" result telling the user to open a job's page first.
+// None need editing first, so they act on click. "Review resume" runs a real
+// turn. "Match a job" and "Generate cover letter" have no page context here,
+// so the tools reply with a graceful "no_job" result telling the user to open
+// a job's page first. ADD_JOB is the one whose answer is knowable without the
+// model — see AGENT_ADD_JOB_INTRO.
+const ADD_JOB = "Add a job posting";
const EXAMPLES = [
- "Add a job posting",
+ ADD_JOB,
"Review resume",
"Match a job",
"Generate cover letter",
];
export function AgentChatEmptyState() {
- const { sendMessage, preflight } = useAgentChat();
+ const { sendMessage, seedExchange, preflight } = useAgentChat();
const handleClick = (example: string) => {
if (!preflight.ok) return;
+ if (example === ADD_JOB) {
+ seedExchange(example, AGENT_ADD_JOB_INTRO);
+ return;
+ }
void sendMessage({ parts: [{ type: "text", text: example }] });
};
diff --git a/src/components/agent/AgentChatProvider.tsx b/src/components/agent/AgentChatProvider.tsx
index b1d8317..c119dfb 100644
--- a/src/components/agent/AgentChatProvider.tsx
+++ b/src/components/agent/AgentChatProvider.tsx
@@ -13,6 +13,7 @@ import { useRouter, usePathname } from "next/navigation";
import { useChat } from "@ai-sdk/react";
import {
DefaultChatTransport,
+ generateId,
getToolName,
isToolUIPart,
lastAssistantMessageIsCompleteWithApprovalResponses,
@@ -24,7 +25,10 @@ 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 {
+ clearChatConversation,
+ saveChatConversation,
+} from "@/actions/agentChat.actions";
import { getUserSettings } from "@/actions/userSettings.actions";
import { checkOllamaConnection } from "@/utils/ai.utils";
import { AiProvider } from "@/models/ai.model";
@@ -60,6 +64,22 @@ const AgentChatContext = createContext<AgentChatValue | null>(null);
const RESUME_ROUTE = /^\/dashboard\/profile\/resume\/([^/]+)$/;
const JOB_ROUTE = /^\/dashboard\/myjobs\/([^/]+)$/;
+// The completed add_job writes in a transcript, by tool call id. Name-checked
+// on purpose: created is add_job's field, and another tool reusing it is not a
+// job write.
+function createdJobToolCallIds(messages: UIMessage[]): string[] {
+ const ids: string[] = [];
+ for (const message of messages) {
+ for (const part of message.parts ?? []) {
+ if (!isToolUIPart(part) || part.state !== "output-available") continue;
+ if (getToolName(part) !== "add_job") continue;
+ if ((part.output as AgentAddJobResult | undefined)?.created !== true) continue;
+ ids.push(part.toolCallId);
+ }
+ }
+ return ids;
+}
+
export function pageContextFor(pathname: string): PageContext {
const resumeId = pathname.match(RESUME_ROUTE)?.[1];
const jobId = pathname.match(JOB_ROUTE)?.[1];
@@ -119,6 +139,15 @@ function useAgentChatValue(initialMessages: UIMessage[]) {
// cannot reach it — pages that hold their own rows subscribe to this counter.
const [jobWrites, setJobWrites] = useState(0);
+ // Which writes have already been announced. Seeded from the persisted
+ // transcript so a yesterday's add_job in initialMessages is not mistaken for
+ // one that just landed; lazily, because the effect below runs per token and
+ // the scan is not worth repeating.
+ const announcedJobWritesRef = useRef<Set<string> | null>(null);
+ if (announcedJobWritesRef.current === null) {
+ announcedJobWritesRef.current = new Set(createdJobToolCallIds(initialMessages));
+ }
+
const chat = useChat({
messages: initialMessages,
transport: new DefaultChatTransport({
@@ -141,13 +170,7 @@ function useAgentChatValue(initialMessages: UIMessage[]) {
if (isAbort || isError) return;
const finishedParts = message?.parts ?? [];
- const wrote = finishedParts.some((part) => {
- if (!isToolUIPart(part) || part.state !== "output-available") return false;
- // Name-checked for the same reason findConsumingWrite is: created is
- // add_job's field, and another tool reusing it is not a job write.
- if (getToolName(part) !== "add_job") return false;
- return (part.output as AgentAddJobResult | undefined)?.created === true;
- });
+ const wrote = createdJobToolCallIds(message ? [message] : []).length > 0;
// Any nested tool that saves server-side leaves the page behind the
// panel stale — the saved review card, the job's match score, or the
// job's cover-letter button flipping to "Regenerate Letter".
@@ -162,18 +185,34 @@ function useAgentChatValue(initialMessages: UIMessage[]) {
// it one user message later, and the next thing the user types calls
// add_job again on the job they just saved. It self-corrected only on
// reload, when the stubbed row re-seeded the transcript.
- if (wrote) {
- chat.setMessages((prev) => stubConsumedPastes(prev));
- setJobWrites((n) => n + 1);
- }
-
- // Unconditional: an RSC refresh on an irrelevant page is a wasted
- // request, not a bug. A stale jobs list, a stale saved review or a
- // stale match score right after watching one land reads as one.
- if (wrote || generated) router.refresh();
+ // Stays here rather than in the effect below: its deadline is the next
+ // POST, and writing to useChat's store mid-stream risks being clobbered.
+ if (wrote) chat.setMessages((prev) => stubConsumedPastes(prev));
+
+ // Only the nested tools. A job write refreshes the moment add_job
+ // returns — see the effect below. An RSC refresh on an irrelevant page
+ // is a wasted request, not a bug; a stale saved review or match score
+ // right after watching one land reads as one.
+ if (generated) router.refresh();
},
});
+ // add_job is approval-gated, so the model calls it on one POST and the SDK
+ // executes it on the next — where stopWhen's hasToolCall("add_job") never
+ // matches, and the model runs a whole extra generation narrating the write.
+ // Announcing in onFinish left the jobs list stale for the length of that
+ // generation; the output part is on the client the moment the tool returns.
+ useEffect(() => {
+ const announced = announcedJobWritesRef.current!;
+ const landed = createdJobToolCallIds(chat.messages).filter(
+ (id) => !announced.has(id),
+ );
+ if (landed.length === 0) return;
+ landed.forEach((id) => announced.add(id));
+ setJobWrites((n) => n + 1);
+ router.refresh();
+ }, [chat.messages, router]);
+
const streamingRef = useRef(false);
streamingRef.current =
chat.status === "streaming" || chat.status === "submitted";
@@ -300,6 +339,31 @@ function useAgentChatValue(initialMessages: UIMessage[]) {
[approvalPending, dispatch],
);
+ // A canned exchange, not a model turn: the caller supplies both halves and
+ // nothing is POSTed. Persisted here because the transcript only reaches the
+ // DB when the route runs, and a pair that vanishes on reload while every
+ // real turn survives reads as a bug.
+ const seedExchange = useCallback(
+ (userText: string, assistantText: string) => {
+ const next: UIMessage[] = [
+ ...chat.messages,
+ {
+ id: generateId(),
+ role: "user",
+ parts: [{ type: "text", text: userText }],
+ },
+ {
+ id: generateId(),
+ role: "assistant",
+ parts: [{ type: "text", text: assistantText }],
+ },
+ ];
+ chat.setMessages(next);
+ void saveChatConversation(next);
+ },
+ [chat],
+ );
+
// Both conditions are load-bearing. approvalPending flips false at the same
// instant sendAutomaticallyWhen fires the POST that executes the approved
// tool, so releasing on that alone would race it and cut the tool off
@@ -331,6 +395,7 @@ function useAgentChatValue(initialMessages: UIMessage[]) {
error: chat.error,
clearError: chat.clearError,
sendMessage,
+ seedExchange,
stop: chat.stop,
regenerate,
addToolApprovalResponse: chat.addToolApprovalResponse,
diff --git a/src/lib/agent/prompt.ts b/src/lib/agent/prompt.ts
index 00efa93..842c1c9 100644
--- a/src/lib/agent/prompt.ts
+++ b/src/lib/agent/prompt.ts
@@ -17,6 +17,23 @@ export const AGENT_CHAT_SYSTEM_PROMPT = [
AGENT_CHAT_PROMPT_SECTIONS.safety,
].join("\n\n");
+// The empty state's add-job suggestion answers with this instead of spending
+// a turn on the model. That click carries no company, title or posting, so
+// add_job is unreachable and the capabilities section above leaves exactly
+// one legal reply — ask for all three. Kept here so it stays in step with
+// that section's required-fields wording.
+export const AGENT_ADD_JOB_INTRO = [
+ "Happy to add it. Paste the job posting here and I'll pull the details out of it.",
+ "",
+ "If you don't have the posting text, tell me:",
+ "",
+ "- **Company** — who is hiring",
+ "- **Job title** — the role they are hiring for",
+ "- **What the role involves** — one sentence is enough",
+ "",
+ "You will see everything I extracted on a confirmation card before anything is saved.",
+].join("\n");
+
// Prompt surface, not documentation — kept beside the prompt so evals assert
// against the exact string the route registers. Mirrors
// src/lib/mcp/toolDescriptions.ts.