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
fix: bound agent chat history by tokens and stub pastes client-side
Khuram Niaz7c6eb66a5f1e
diff --git a/__tests__/AgentChatProvider.spec.tsx b/__tests__/AgentChatProvider.spec.tsxindex 4367af2..829a4ee 100644--- a/__tests__/AgentChatProvider.spec.tsx+++ b/__tests__/AgentChatProvider.spec.tsx@@ -301,6 +301,67 @@ describe("AgentChatProvider", () => {expect(refresh).toHaveBeenCalled();});+ const createdToolMessage = {+ id: "a3",+ role: "assistant",+ parts: [+ {+ type: "tool-add_job",+ toolCallId: "c1",+ state: "output-available",+ input: { company: "Acme", jobTitle: "Engineer" },+ output: { created: true },+ },+ ],+ } as any;++ // 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.+ it("stubs the client-side paste after a successful add_job", async () => {+ setup();+ await act(async () => {+ chatInit().onFinish({+ message: createdToolMessage,+ messages: [createdToolMessage],+ });+ });+ const update = chat.setMessages.mock.calls.at(-1)![0] as any;+ const stubbed = update([+ {+ id: "u1",+ role: "user",+ parts: [+ {+ type: "data-paste",+ id: "p1",+ data: {+ id: "p1",+ text: "SECRET_POSTING_BODY",+ chars: 19,+ truncated: false,+ consumed: false,+ },+ },+ ],+ },+ createdToolMessage,+ ]);+ expect(stubbed[0].parts[0].data.consumed).toBe(true);+ expect(JSON.stringify(stubbed)).not.toContain("SECRET_POSTING_BODY");+ });++ it("does not stub the client-side paste when no job was created", async () => {+ setup();+ await act(async () => {+ chatInit().onFinish({+ message: reviewToolMessage,+ messages: [reviewToolMessage],+ });+ });+ expect(chat.setMessages).not.toHaveBeenCalled();+ });+it("accumulates transient review deltas keyed by tool call id", async () => {setup();await act(async () => {diff --git a/__tests__/agentPaste.spec.ts b/__tests__/agentPaste.spec.tsindex a65a7ec..a538d69 100644--- a/__tests__/agentPaste.spec.ts+++ b/__tests__/agentPaste.spec.ts@@ -212,6 +212,50 @@ describe("windowMessages", () => {expect(windowed).toHaveLength(APP_CONSTANTS.AGENT_CHAT_HISTORY_MESSAGES);expect(windowed[windowed.length - 1].id).toBe(`m${many.length - 1}`);});++ it("cuts on the token budget before the message count when messages are fat", () => {+ // A third of the budget each, so only the newest few fit.+ const fatText = "x".repeat(+ (APP_CONSTANTS.AGENT_CHAT_HISTORY_TOKEN_BUDGET / 3) *+ APP_CONSTANTS.AGENT_CHAT_CHARS_PER_TOKEN,+ );+ const many = Array.from(+ { length: APP_CONSTANTS.AGENT_CHAT_HISTORY_MESSAGES },+ (_, i) => userMsg(`m${i}`, [{ type: "text", text: fatText }]),+ );+ const windowed = windowMessages(many as any);+ expect(windowed.length).toBeLessThan(+ APP_CONSTANTS.AGENT_CHAT_HISTORY_MESSAGES,+ );+ expect(windowed[windowed.length - 1].id).toBe(`m${many.length - 1}`);+ });++ it("keeps the newest message even when it alone exceeds the budget", () => {+ const huge = "x".repeat(+ APP_CONSTANTS.AGENT_CHAT_HISTORY_TOKEN_BUDGET *+ APP_CONSTANTS.AGENT_CHAT_CHARS_PER_TOKEN *+ 2,+ );+ const messages = [+ userMsg("1", [{ type: "text", text: "earlier" }]),+ userMsg("2", [{ type: "text", text: huge }]),+ ] as any;+ const windowed = windowMessages(messages);+ expect(windowed).toHaveLength(1);+ expect(windowed[0].id).toBe("2");+ });++ // The payoff over a message count: a paste part is dropped by+ // convertToModelMessages, so charging history for it would evict real+ // context to make room for text the model never sees.+ it("does not charge the budget for a data-paste part", () => {+ const huge = "x".repeat(APP_CONSTANTS.AGENT_CHAT_PASTE_MAX_CHARS);+ const messages = [+ userMsg("1", [{ type: "text", text: "earlier" }]),+ userMsg("2", [{ type: "text", text: "add this" }, pastePart("p1", huge)]),+ ] as any;+ expect(windowMessages(messages)).toHaveLength(2);+ });});// Settles spec "to verify" item 1: the head has to be injected explicitlydiff --git a/src/app/api/ai/chat/route.ts b/src/app/api/ai/chat/route.tsindex 70edeed..b59009f 100644--- a/src/app/api/ai/chat/route.ts+++ b/src/app/api/ai/chat/route.ts@@ -124,9 +124,11 @@ export const POST = async (req: NextRequest) => {// Async in ai@6 (correction #5), and the messages array is client-supplied// — a shape z.array(z.any()) let through can reject the conversion, and// that is a bad request, not a server crash.+ const windowed = windowMessages(messages);+let modelMessages;try {- modelMessages = await convertToModelMessages(windowMessages(messages));+ modelMessages = await convertToModelMessages(windowed);} catch {return NextResponse.json({ error: "Invalid chat request." }, { status: 400 });}@@ -207,6 +209,9 @@ export const POST = async (req: NextRequest) => {aborted: isAborted,pasteChars: pastedText?.length ?? 0,messageCount: finalMessages.length,+ // Windowing is invisible to the user, so this is the only signal that+ // the model was given less history than the transcript holds.+ historyDropped: messages.length - windowed.length,});// A cancelled turn never writes back. Clear deletes the conversation and// this fires afterwards on the stream's cancel path, so saving here woulddiff --git a/src/components/agent/AgentChatProvider.tsx b/src/components/agent/AgentChatProvider.tsxindex 9b2d1b3..e90c9b0 100644--- a/src/components/agent/AgentChatProvider.tsx+++ b/src/components/agent/AgentChatProvider.tsx@@ -18,7 +18,7 @@ import {lastAssistantMessageIsCompleteWithApprovalResponses,type UIMessage,} from "ai";-import { hasPendingApproval } from "@/lib/agent/paste";+import { hasPendingApproval, stubConsumedPastes } from "@/lib/agent/paste";import { useRightRail } from "@/context/RightRailContext";import { useSidebar } from "@/context/SidebarContext";import { useResizablePanel } from "@/hooks/useResizablePanel";@@ -144,6 +144,14 @@ function useAgentChatValue(initialMessages: UIMessage[]) {return getToolName(part) === "review_resume";});+ // The route stubs the paste on its way into the DB, but that copy is+ // not the one the client POSTs next turn — so without this the browser+ // keeps a consumed posting marked unconsumed, resolvePastedText finds+ // 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));+// Unconditional: an RSC refresh on an irrelevant page is a wasted// request, not a bug. A stale jobs list or a stale saved review behind// the panel right after watching one land reads as one.diff --git a/src/lib/agent/paste.ts b/src/lib/agent/paste.tsindex d267bb1..439a024 100644--- a/src/lib/agent/paste.ts+++ b/src/lib/agent/paste.ts@@ -94,11 +94,46 @@ export function hasPendingApproval(messages: UIMessage[]): boolean {);}+// Approximates what a message costs the model after conversion. data-* parts+// are excluded because convertToModelMessages drops them — without that a+// 120k paste chip would evict the entire real history to make room for text+// the model never sees. Serializing the parts over-counts by the JSON+// structure, which errs toward cutting early.+function estimateTokens(message: UIMessage): number {+ const parts = (message.parts ?? []).filter(+ (part) => !part.type.startsWith("data-"),+ );+ if (parts.length === 0) return 0;+ return Math.ceil(+ JSON.stringify(parts).length / APP_CONSTANTS.AGENT_CHAT_CHARS_PER_TOKEN,+ );+}+// Bounds what is SENT. AGENT_CHAT_MAX_STORED_MESSAGES bounds what is stored;// the two are deliberately different numbers. If the cut lands mid-thread// the model conversation may open with an assistant turn; providers tolerate// that, but if the configured model chokes on it, trim forward to the first// user message here rather than widening the window.+//+// The message count is a hard upper bound and the token budget cuts inside+// it. Cutting on UIMessage boundaries rather than after conversion is the+// safe order: here a tool call and its result are one part of one message,+// where in ModelMessage form they are separate messages and a cut can orphan+// the tool result.export function windowMessages(messages: UIMessage[]): UIMessage[] {- return messages.slice(-APP_CONSTANTS.AGENT_CHAT_HISTORY_MESSAGES);+ const recent = messages.slice(-APP_CONSTANTS.AGENT_CHAT_HISTORY_MESSAGES);++ const kept: UIMessage[] = [];+ let total = 0;+ for (let i = recent.length - 1; i >= 0; i--) {+ const message = recent[i];+ total += estimateTokens(message);+ // The newest message goes in whatever it costs — a single oversized+ // review output must not window down to an empty conversation.+ if (total > APP_CONSTANTS.AGENT_CHAT_HISTORY_TOKEN_BUDGET && kept.length) {+ break;+ }+ kept.unshift(message);+ }+ return kept;}diff --git a/src/lib/constants.ts b/src/lib/constants.tsindex 5ad3333..f9352fe 100644--- a/src/lib/constants.ts+++ b/src/lib/constants.ts@@ -130,6 +130,18 @@ export const APP_CONSTANTS = {AGENT_CHAT_MAX_STEPS: 4,AGENT_CHAT_MAX_STORED_MESSAGES: 50,AGENT_CHAT_HISTORY_MESSAGES: 20,+ // Message count alone cannot bound context: one review output or resume read+ // is worth a dozen ordinary turns, and think:true adds 1.2-2.3k chars of+ // reasoning per turn that persists and replays. Derived from the+ // AGENT_CHAT_NUM_CTX floor: ~700 system prompt + ~950 tool schemas + ~500+ // paste head + ~3000 for reasoning and tool args across MAX_STEPS, rounded+ // up to a ~7000 reserve. Symptom it is too tight: the assistant forgets+ // things a 20-message window used to carry.+ AGENT_CHAT_HISTORY_TOKEN_BUDGET: 9000,+ // No tokenizer dependency: with Ollama, DeepSeek and OpenAI models all+ // reachable there is no single correct vocab, and a real tokenizer would be+ // precisely wrong rather than approximately right.+ AGENT_CHAT_CHARS_PER_TOKEN: 4,// 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.