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: make the agent chat safe to extend past three tools

Khuram Niaz1171f7efbb6e
diff --git a/__tests__/AgentChatProvider.spec.tsx b/__tests__/AgentChatProvider.spec.tsx
index fb3f99a..4367af2 100644
--- a/__tests__/AgentChatProvider.spec.tsx
+++ b/__tests__/AgentChatProvider.spec.tsx
@@ -342,7 +342,14 @@ describe("pageContextFor", () => {
});
});
- it("omits resumeId everywhere else", () => {
+ it("extracts the job id from a job detail route", () => {
+ expect(pageContextFor("/dashboard/myjobs/job-9")).toEqual({
+ route: "/dashboard/myjobs/job-9",
+ jobId: "job-9",
+ });
+ });
+
+ it("omits both ids everywhere else", () => {
expect(pageContextFor("/dashboard/myjobs")).toEqual({
route: "/dashboard/myjobs",
});
diff --git a/__tests__/agentChatRoute.spec.ts b/__tests__/agentChatRoute.spec.ts
index 3e4a2ec..9450ca8 100644
--- a/__tests__/agentChatRoute.spec.ts
+++ b/__tests__/agentChatRoute.spec.ts
@@ -146,6 +146,57 @@ describe("POST /api/ai/chat", () => {
);
});
+ // The log line discriminates on result shape, not on a tool-name allowlist.
+ // An allowlist logged get_resume as "duplicate" once; a fourth tool would
+ // have re-run that bug with a successful write logged as a rejected one.
+ it("logs a status-carrying result from an unrecognised tool by its status", async () => {
+ const info = vi.spyOn(console, "info").mockImplementation(() => {});
+ await POST(req({ messages: [pasteMessage("posting")] }));
+ await capturedOnFinish!({
+ messages: [],
+ responseMessage: {
+ id: "a1",
+ role: "assistant",
+ parts: [
+ {
+ type: "tool-match_job",
+ toolCallId: "c1",
+ state: "output-available",
+ output: { status: "ok", score: 78 },
+ },
+ ],
+ },
+ isAborted: false,
+ });
+ const logged = JSON.parse(info.mock.calls.at(-1)![1] as string);
+ expect(logged).toMatchObject({ tool: "match_job", outcome: "ok" });
+ info.mockRestore();
+ });
+
+ it("still logs add_job's create/duplicate outcome, which carries no status", async () => {
+ const info = vi.spyOn(console, "info").mockImplementation(() => {});
+ await POST(req({ messages: [pasteMessage("posting")] }));
+ await capturedOnFinish!({
+ messages: [],
+ responseMessage: {
+ id: "a1",
+ role: "assistant",
+ parts: [
+ {
+ type: "tool-add_job",
+ toolCallId: "c1",
+ state: "output-available",
+ output: { created: false, duplicateOf: { id: "j" } },
+ },
+ ],
+ },
+ isAborted: false,
+ });
+ const logged = JSON.parse(info.mock.calls.at(-1)![1] as string);
+ expect(logged).toMatchObject({ tool: "add_job", outcome: "duplicate" });
+ info.mockRestore();
+ });
+
// 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
diff --git a/__tests__/agentPaste.spec.ts b/__tests__/agentPaste.spec.ts
index 7401302..a65a7ec 100644
--- a/__tests__/agentPaste.spec.ts
+++ b/__tests__/agentPaste.spec.ts
@@ -149,6 +149,25 @@ describe("stubConsumedPastes", () => {
(stubConsumedPastes(messages)[0].parts[0] as any).data.text,
).toContain("6kb posting");
});
+
+ // created is add_job's field. Any future tool reusing the name would
+ // otherwise stub out a posting the user cannot re-derive.
+ it("ignores a created:true result from a tool that is not add_job", () => {
+ const messages = [
+ userMsg("1", [pastePart("p1", "the whole 6kb posting")]),
+ assistantMsg("2", [
+ {
+ ...toolPart("output-available", {
+ output: { created: true, coverLetterId: "cl-1" },
+ }),
+ type: "tool-write_cover_letter",
+ },
+ ]),
+ ] as any;
+ const part: any = stubConsumedPastes(messages)[0].parts[0];
+ expect(part.data.text).toContain("6kb posting");
+ expect(part.data.consumed).toBe(false);
+ });
});
describe("hasPendingApproval", () => {
diff --git a/evals/agent-chat/promptfooconfig.yaml b/evals/agent-chat/promptfooconfig.yaml
index 5c4163d..6d70f75 100644
--- a/evals/agent-chat/promptfooconfig.yaml
+++ b/evals/agent-chat/promptfooconfig.yaml
@@ -199,11 +199,16 @@ tests:
- type: javascript
value: file://./assertions.ts:assertFollowUpStaysConversational
+ # The follow-up must be answerable from the review ALONE — the resume text is
+ # never in this transcript, only the critique of it. An earlier version asked
+ # the model to "rewrite the summary bullet you flagged", which the review
+ # neither flags nor quotes, so fetching the resume was the correct response
+ # and the row failed on deepseek for the whole of its life.
- description: Follow-up asking about a specific section - still conversational
vars:
userMessage: Review my resume.
priorReview: file://./fixtures/prior-review.md
- followUp: Rewrite the summary bullet you flagged.
+ followUp: In the summary you said several achievements describe responsibilities rather than outcomes. What do you mean by that?
assert:
- type: javascript
value: file://./assertions.ts:assertFollowUpStaysConversational
diff --git a/src/app/api/ai/chat/route.ts b/src/app/api/ai/chat/route.ts
index 2524fe5..70edeed 100644
--- a/src/app/api/ai/chat/route.ts
+++ b/src/app/api/ai/chat/route.ts
@@ -29,11 +29,7 @@ import { mapAgentError } from "@/lib/agent/errors";
import { getUserSettings } from "@/actions/userSettings.actions";
import { saveChatConversation } from "@/actions/agentChat.actions";
import { AiProvider } from "@/models/ai.model";
-import type {
- AgentAddJobResult,
- AgentGetResumeResult,
- AgentReviewResumeResult,
-} from "@/models/agent.model";
+import { AGENT_CHAT_TERMINAL_TOOLS } from "@/models/agent.model";
// One structured line per turn. Sizes and outcomes only — never the pasted
// posting and never the extracted arguments.
@@ -52,16 +48,16 @@ function outcomeOf(message: UIMessage | undefined): {
if (part.state !== "output-available") {
return { tool, state: part.state, outcome: part.state };
}
- // Read and write tools report success differently; casting every output
- // to AgentAddJobResult logged a resume read as "duplicate".
- if (tool === "get_resume" || tool === "review_resume") {
- const output = part.output as
- | AgentGetResumeResult
- | AgentReviewResumeResult
- | undefined;
- return { tool, state: part.state, outcome: output?.status ?? "none" };
+ const output = part.output as
+ | { status?: string; created?: boolean; validationError?: string }
+ | undefined;
+ // Discriminated on shape, not on tool name: a name allowlist logged a
+ // resume read as "duplicate" once already. Status-carrying results report
+ // their own outcome, and add_job is the only shape without a status field,
+ // so it is the fallback rather than the default.
+ if (typeof output?.status === "string") {
+ return { tool, state: part.state, outcome: output.status };
}
- const output = part.output as AgentAddJobResult | undefined;
const outcome = output?.validationError
? "validation"
: output?.created
@@ -179,14 +175,11 @@ export const POST = async (req: NextRequest) => {
modelName,
writer,
}),
- // Stop after the write: the result card renders deterministically from
- // structured fields, so a second generation just to narrate it is 10-30s
- // of local inference for a sentence that could be wrong. Same reasoning
- // for review_resume — the card and the review are already on screen.
+ // Which tools end the turn — and why — lives beside the tool metadata
+ // in agent.model.ts, where a new tool is registered.
stopWhen: [
stepCountIs(APP_CONSTANTS.AGENT_CHAT_MAX_STEPS),
- hasToolCall("add_job"),
- hasToolCall("review_resume"),
+ ...AGENT_CHAT_TERMINAL_TOOLS.map((name) => hasToolCall(name)),
],
// Argument extraction wants determinism.
temperature: TEMPERATURES.ANALYSIS,
diff --git a/src/components/agent/AgentChatProvider.tsx b/src/components/agent/AgentChatProvider.tsx
index 4557129..9b2d1b3 100644
--- a/src/components/agent/AgentChatProvider.tsx
+++ b/src/components/agent/AgentChatProvider.tsx
@@ -49,14 +49,20 @@ type AgentChatValue = ReturnType<typeof useAgentChatValue>;
const AgentChatContext = createContext<AgentChatValue | null>(null);
-// The only route that identifies a resource the chat can read. Derived from
-// the pathname rather than plumbed through props so no page has to know the
+// The routes that identify a resource the chat can read. Derived from the
+// pathname rather than plumbed through props so no page has to know the
// panel exists.
const RESUME_ROUTE = /^\/dashboard\/profile\/resume\/([^/]+)$/;
+const JOB_ROUTE = /^\/dashboard\/myjobs\/([^/]+)$/;
export function pageContextFor(pathname: string): PageContext {
const resumeId = pathname.match(RESUME_ROUTE)?.[1];
- return resumeId ? { route: pathname, resumeId } : { route: pathname };
+ const jobId = pathname.match(JOB_ROUTE)?.[1];
+ return {
+ route: pathname,
+ ...(resumeId ? { resumeId } : {}),
+ ...(jobId ? { jobId } : {}),
+ };
}
function useAgentChatValue(initialMessages: UIMessage[]) {
@@ -128,6 +134,9 @@ function useAgentChatValue(initialMessages: UIMessage[]) {
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 reviewed = finishedParts.some((part) => {
diff --git a/src/lib/agent/paste.ts b/src/lib/agent/paste.ts
index d7cfb9d..d267bb1 100644
--- a/src/lib/agent/paste.ts
+++ b/src/lib/agent/paste.ts
@@ -1,4 +1,4 @@
-import { isToolUIPart, type UIMessage } from "ai";
+import { getToolName, isToolUIPart, type UIMessage } from "ai";
import { APP_CONSTANTS } from "@/lib/constants";
import {
isAgentPastePart,
@@ -46,6 +46,9 @@ function findConsumingWrite(
for (let i = messages.length - 1; i >= 0; i--) {
for (const part of messages[i]?.parts ?? []) {
if (!isToolUIPart(part) || part.state !== "output-available") continue;
+ // add_job is the only tool that consumes a paste. Without this guard any
+ // future tool returning created:true stubs the posting out from under it.
+ if (getToolName(part) !== "add_job") continue;
const output = part.output as AgentAddJobResult | undefined;
// Only a successful create consumes the paste. A duplicate or a
// validation failure leaves it available for the retry.
diff --git a/src/lib/constants.ts b/src/lib/constants.ts
index 6ce7a8a..5ad3333 100644
--- a/src/lib/constants.ts
+++ b/src/lib/constants.ts
@@ -130,9 +130,10 @@ export const APP_CONSTANTS = {
AGENT_CHAT_MAX_STEPS: 4,
AGENT_CHAT_MAX_STORED_MESSAGES: 50,
AGENT_CHAT_HISTORY_MESSAGES: 20,
- // Longer than the review timeout: one chat turn may contain more than one
- // generation (tool call, then a corrective retry).
- AGENT_CHAT_TIMEOUT_MS: 240_000,
+ // Must clear one nested generation plus the thinking steps around it: two
+ // 15-30s think steps plus a 180s review is ~242s, which the old 240s cut off
+ // after the user had watched the whole review stream in.
+ AGENT_CHAT_TIMEOUT_MS: 300_000,
// Deliberately not AI_OLLAMA_NUM_CTX: a chat turn carries a system prompt,
// tool schemas, a paste head and history. Raising the shared value would
// change review/match latency.
diff --git a/src/models/agent.model.ts b/src/models/agent.model.ts
index 5035120..70353c2 100644
--- a/src/models/agent.model.ts
+++ b/src/models/agent.model.ts
@@ -104,5 +104,9 @@ export type AgentReviewResumeResult =
| { status: "unreadable"; title: string; reason: string }
| { status: "generation_failed"; title: string; reason: string };
-export const AGENT_CHAT_TOOL_NAMES = ["add_job", "get_resume", "review_resume"] as const;
-export type AgentChatToolName = (typeof AGENT_CHAT_TOOL_NAMES)[number];
+// Tools that end the turn. The result card renders deterministically from
+// structured fields, so a second generation just to narrate it is 10-30s of
+// local inference for a sentence that could be wrong. A tool that runs its
+// own generation MUST be listed here or a single turn can chain two of them
+// and blow the turn timeout, discarding both.
+export const AGENT_CHAT_TERMINAL_TOOLS = ["add_job", "review_resume"] as const;