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 server helpers

Khuram Niaz7c89268be480
diff --git a/__tests__/agentChat.actions.spec.ts b/__tests__/agentChat.actions.spec.ts
new file mode 100644
index 0000000..e3f97da
--- /dev/null
+++ b/__tests__/agentChat.actions.spec.ts
@@ -0,0 +1,104 @@
+import {
+ getChatConversation,
+ saveChatConversation,
+ clearChatConversation,
+} from "@/actions/agentChat.actions";
+import { getCurrentUser } from "@/utils/user.utils";
+import { PrismaClient } from "@prisma/client";
+import { APP_CONSTANTS } from "@/lib/constants";
+
+const prisma = new PrismaClient();
+
+vi.mock("@prisma/client", () => {
+ const mPrismaClient = {
+ chatConversation: {
+ findUnique: vi.fn(),
+ upsert: vi.fn(),
+ deleteMany: vi.fn(),
+ },
+ };
+ return {
+ PrismaClient: vi.fn(function () {
+ return mPrismaClient;
+ }),
+ };
+});
+
+vi.mock("@/utils/user.utils", () => ({ getCurrentUser: vi.fn() }));
+
+const mockUser = { id: "user-1" };
+const msg = (id: string) => ({
+ id,
+ role: "user",
+ parts: [{ type: "text", text: id }],
+});
+
+describe("agentChat actions", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ (getCurrentUser as any).mockResolvedValue(mockUser);
+ });
+
+ it("getChatConversation scopes the read by userId", async () => {
+ (prisma.chatConversation.findUnique as any).mockResolvedValue({
+ messages: JSON.stringify([msg("a")]),
+ });
+ const result = await getChatConversation();
+ expect(prisma.chatConversation.findUnique).toHaveBeenCalledWith({
+ where: { userId: "user-1" },
+ });
+ expect(result.data).toEqual([msg("a")]);
+ });
+
+ it("getChatConversation returns an empty transcript when there is no row", async () => {
+ (prisma.chatConversation.findUnique as any).mockResolvedValue(null);
+ const result = await getChatConversation();
+ expect(result.success).toBe(true);
+ expect(result.data).toEqual([]);
+ });
+
+ it("getChatConversation returns an empty transcript when the JSON is corrupt", async () => {
+ (prisma.chatConversation.findUnique as any).mockResolvedValue({
+ messages: "{ not json",
+ });
+ const result = await getChatConversation();
+ expect(result.success).toBe(true);
+ expect(result.data).toEqual([]);
+ });
+
+ it("saveChatConversation upserts on userId and never accepts one as an argument", async () => {
+ await saveChatConversation([msg("a")] as any);
+ const call = (prisma.chatConversation.upsert as any).mock.calls[0][0];
+ expect(call.where).toEqual({ userId: "user-1" });
+ expect(call.create.userId).toBe("user-1");
+ expect(saveChatConversation.length).toBe(1);
+ });
+
+ it("saveChatConversation trims to the newest AGENT_CHAT_MAX_STORED_MESSAGES", async () => {
+ const many = Array.from(
+ { length: APP_CONSTANTS.AGENT_CHAT_MAX_STORED_MESSAGES + 5 },
+ (_, i) => msg(`m${i}`),
+ );
+ await saveChatConversation(many as any);
+ const call = (prisma.chatConversation.upsert as any).mock.calls[0][0];
+ const stored = JSON.parse(call.update.messages);
+ expect(stored).toHaveLength(APP_CONSTANTS.AGENT_CHAT_MAX_STORED_MESSAGES);
+ expect(stored[stored.length - 1].id).toBe(`m${many.length - 1}`);
+ });
+
+ it("clearChatConversation deletes only the caller's row", async () => {
+ await clearChatConversation();
+ expect(prisma.chatConversation.deleteMany).toHaveBeenCalledWith({
+ where: { userId: "user-1" },
+ });
+ });
+
+ it("every action fails closed without a session", async () => {
+ (getCurrentUser as any).mockResolvedValue(null);
+ expect((await getChatConversation()).success).toBe(false);
+ expect((await saveChatConversation([])).success).toBe(false);
+ expect((await clearChatConversation()).success).toBe(false);
+ expect(prisma.chatConversation.upsert).not.toHaveBeenCalled();
+ expect(prisma.chatConversation.deleteMany).not.toHaveBeenCalled();
+ });
+});
diff --git a/__tests__/agentErrors.spec.ts b/__tests__/agentErrors.spec.ts
new file mode 100644
index 0000000..0260521
--- /dev/null
+++ b/__tests__/agentErrors.spec.ts
@@ -0,0 +1,79 @@
+import { mapAgentError } from "@/lib/agent/errors";
+import { NoSuchToolError, InvalidToolInputError } from "ai";
+
+describe("mapAgentError", () => {
+ it("never echoes an unmapped error's message", () => {
+ const marker = "SENSITIVE-REQUEST-CONTEXT-9f3a";
+ const mapped = mapAgentError(new Error(`Request failed: ${marker}`));
+ expect(mapped).not.toContain(marker);
+ expect(mapped.length).toBeGreaterThan(0);
+ });
+
+ it("names the provider when the service is unreachable", () => {
+ const mapped = mapAgentError(new Error("fetch failed"), {
+ provider: "ollama",
+ });
+ expect(mapped).toMatch(/ollama/i);
+ expect(mapped).toMatch(/settings/i);
+ expect(
+ mapAgentError(new Error("connect ECONNREFUSED 127.0.0.1:11434"), {
+ provider: "ollama",
+ }),
+ ).toMatch(/ollama/i);
+ });
+
+ it("names the provider and model when the model cannot tool-call", () => {
+ const mapped = mapAgentError(new Error("model does not support tools"), {
+ provider: "ollama",
+ model: "llama3.1",
+ });
+ expect(mapped).toMatch(/llama3\.1/);
+ expect(mapped).toMatch(/tool/i);
+ expect(mapped).toMatch(/settings/i);
+ });
+
+ it("maps a stale approval to a message naming Clear as the remedy", () => {
+ const stale = Object.assign(new Error("no tool call found"), {
+ name: "AI_ToolCallNotFoundForApprovalError",
+ });
+ expect(mapAgentError(stale)).toMatch(/clear/i);
+ });
+
+ it("maps abort and timeout distinctly from a connection failure", () => {
+ const aborted = Object.assign(new Error("The operation was aborted."), {
+ name: "AbortError",
+ });
+ const mapped = mapAgentError(aborted);
+ expect(mapped).toMatch(/(stopped|took too long|timed out)/i);
+ expect(mapped).not.toMatch(/ECONNREFUSED/);
+ });
+
+ it("maps NoSuchToolError and InvalidToolInputError to distinct messages", () => {
+ const noSuch = mapAgentError(
+ new NoSuchToolError({ toolName: "delete_everything" }),
+ );
+ const badInput = mapAgentError(
+ new InvalidToolInputError({
+ toolName: "add_job",
+ toolInput: "{}",
+ cause: new Error("bad"),
+ }),
+ );
+ expect(noSuch).not.toBe(badInput);
+ expect(noSuch).toMatch(/tool/i);
+ expect(badInput).toMatch(/(argument|input)/i);
+ });
+
+ it("produces four distinct messages for the four headline failures", () => {
+ const messages = new Set([
+ mapAgentError(new Error("fetch failed"), { provider: "ollama" }),
+ mapAgentError(new Error("does not support tools"), {
+ provider: "ollama",
+ model: "m",
+ }),
+ mapAgentError(new NoSuchToolError({ toolName: "x" })),
+ mapAgentError(Object.assign(new Error("aborted"), { name: "AbortError" })),
+ ]);
+ expect(messages.size).toBe(4);
+ });
+});
diff --git a/__tests__/agentPaste.spec.ts b/__tests__/agentPaste.spec.ts
new file mode 100644
index 0000000..7401302
--- /dev/null
+++ b/__tests__/agentPaste.spec.ts
@@ -0,0 +1,214 @@
+import {
+ resolvePastedText,
+ stubConsumedPastes,
+ hasPendingApproval,
+ windowMessages,
+} from "@/lib/agent/paste";
+import { truncateForModel } from "@/lib/agent/paste.server";
+import { AGENT_PASTE_PART_TYPE } from "@/models/agent.model";
+import { APP_CONSTANTS } from "@/lib/constants";
+import { convertToModelMessages } from "ai";
+
+const pastePart = (id: string, text: string, consumed = false) => ({
+ type: AGENT_PASTE_PART_TYPE,
+ id,
+ data: { id, text, chars: text.length, truncated: false, consumed },
+});
+
+const userMsg = (id: string, parts: any[]) => ({
+ id,
+ role: "user" as const,
+ parts,
+});
+const assistantMsg = (id: string, parts: any[]) => ({
+ id,
+ role: "assistant" as const,
+ parts,
+});
+
+const toolPart = (state: string, extra: Record<string, unknown> = {}) => ({
+ type: "tool-add_job",
+ toolCallId: "call-1",
+ state,
+ input: { company: "Acme", jobTitle: "Engineer" },
+ ...extra,
+});
+
+describe("resolvePastedText", () => {
+ it("returns the newest unconsumed paste", () => {
+ const messages = [
+ userMsg("1", [pastePart("p1", "older posting")]),
+ userMsg("2", [pastePart("p2", "newer posting")]),
+ ] as any;
+ expect(resolvePastedText(messages)).toBe("newer posting");
+ });
+
+ it("skips a paste that has already been consumed", () => {
+ const messages = [
+ userMsg("1", [pastePart("p1", "still available")]),
+ userMsg("2", [pastePart("p2", "[stub]", true)]),
+ ] as any;
+ expect(resolvePastedText(messages)).toBe("still available");
+ });
+
+ it("returns undefined when nothing was pasted", () => {
+ expect(
+ resolvePastedText([userMsg("1", [{ type: "text", text: "hi" }])] as any),
+ ).toBeUndefined();
+ });
+
+ it("ignores a paste the user has moved past", () => {
+ const messages = [
+ userMsg("1", [pastePart("p1", "abandoned posting")]),
+ assistantMsg("2", [{ type: "text", text: "Looks interesting." }]),
+ userMsg("3", [{ type: "text", text: "what else should I apply to?" }]),
+ assistantMsg("4", [{ type: "text", text: "I cannot read your jobs yet." }]),
+ userMsg("5", [{ type: "text", text: "add a job: Eng at Acme, remote" }]),
+ ] as any;
+ expect(resolvePastedText(messages)).toBeUndefined();
+ });
+
+ it("still resolves a paste across one clarifying exchange", () => {
+ const messages = [
+ userMsg("1", [pastePart("p1", "the posting")]),
+ assistantMsg("2", [{ type: "text", text: "Shall I add it?" }]),
+ userMsg("3", [{ type: "text", text: "yes" }]),
+ ] as any;
+ expect(resolvePastedText(messages)).toBe("the posting");
+ });
+});
+
+describe("truncateForModel", () => {
+ it("truncates to the head length", () => {
+ const long = "x".repeat(APP_CONSTANTS.AGENT_CHAT_PASTE_HEAD_CHARS + 500);
+ const { block } = truncateForModel(long, "NONCE1");
+ const body = block.split("\n").slice(1, -1).join("\n");
+ expect(body).toHaveLength(APP_CONSTANTS.AGENT_CHAT_PASTE_HEAD_CHARS);
+ });
+
+ it("strips the nonce from the text before wrapping, not after", () => {
+ const attack = `Real posting NONCE1 more text`;
+ const { block } = truncateForModel(attack, "NONCE1");
+ const opens = block.split("<<<PASTED_NONCE1>>>").length - 1;
+ const closes = block.split("<<<END_PASTED_NONCE1>>>").length - 1;
+ expect(opens).toBe(1);
+ expect(closes).toBe(1);
+ const body = block.split("\n").slice(1, -1).join("\n");
+ expect(body).not.toContain("NONCE1");
+ });
+
+ it("generates a different nonce on each call by default", () => {
+ expect(truncateForModel("a").nonce).not.toBe(truncateForModel("a").nonce);
+ });
+});
+
+describe("stubConsumedPastes", () => {
+ it("replaces the payload once a write has produced output", () => {
+ const messages = [
+ userMsg("1", [pastePart("p1", "the whole 6kb posting")]),
+ assistantMsg("2", [
+ toolPart("output-available", {
+ output: { created: true, jobId: "job-1", resolutions: [] },
+ }),
+ ]),
+ ] as any;
+ const stubbed = stubConsumedPastes(messages);
+ const part: any = stubbed[0].parts[0];
+ expect(part.data.text).not.toContain("6kb posting");
+ expect(part.data.text).toContain("Engineer");
+ expect(part.data.text).toContain("Acme");
+ expect(part.data.consumed).toBe(true);
+ });
+
+ it("leaves an unconsumed paste alone while the approval is still pending", () => {
+ const messages = [
+ userMsg("1", [pastePart("p1", "the whole 6kb posting")]),
+ assistantMsg("2", [
+ toolPart("approval-requested", { approval: { id: "a1" } }),
+ ]),
+ ] as any;
+ expect(
+ (stubConsumedPastes(messages)[0].parts[0] as any).data.text,
+ ).toContain("6kb posting");
+ });
+
+ it("leaves the paste alone when the write reported a duplicate", () => {
+ const messages = [
+ userMsg("1", [pastePart("p1", "the whole 6kb posting")]),
+ assistantMsg("2", [
+ toolPart("output-available", {
+ output: {
+ created: false,
+ resolutions: [],
+ duplicateOf: { id: "j", title: "t", company: "c" },
+ },
+ }),
+ ]),
+ ] as any;
+ expect(
+ (stubConsumedPastes(messages)[0].parts[0] as any).data.text,
+ ).toContain("6kb posting");
+ });
+});
+
+describe("hasPendingApproval", () => {
+ it("is true while a tool part is awaiting a response", () => {
+ expect(
+ hasPendingApproval([
+ assistantMsg("1", [
+ toolPart("approval-requested", { approval: { id: "a1" } }),
+ ]),
+ ] as any),
+ ).toBe(true);
+ });
+
+ it("is false for an ordinary text reply", () => {
+ expect(
+ hasPendingApproval([
+ assistantMsg("1", [{ type: "text", text: "sure" }]),
+ ] as any),
+ ).toBe(false);
+ });
+
+ it("is false once the approval has been responded to", () => {
+ expect(
+ hasPendingApproval([
+ assistantMsg("1", [
+ toolPart("approval-responded", {
+ approval: { id: "a1", approved: true },
+ }),
+ ]),
+ ] as any),
+ ).toBe(false);
+ });
+});
+
+describe("windowMessages", () => {
+ it("sends at most AGENT_CHAT_HISTORY_MESSAGES, keeping the newest", () => {
+ const many = Array.from(
+ { length: APP_CONSTANTS.AGENT_CHAT_HISTORY_MESSAGES + 10 },
+ (_, i) => userMsg(`m${i}`, []),
+ );
+ const windowed = windowMessages(many as any);
+ expect(windowed).toHaveLength(APP_CONSTANTS.AGENT_CHAT_HISTORY_MESSAGES);
+ expect(windowed[windowed.length - 1].id).toBe(`m${many.length - 1}`);
+ });
+});
+
+// Settles spec "to verify" item 1: the head has to be injected explicitly
+// precisely because convertToModelMessages drops custom data parts.
+describe("convertToModelMessages and data parts", () => {
+ it("drops the paste part rather than carrying the full text to the model", async () => {
+ const messages = [
+ userMsg("1", [
+ { type: "text", text: "add this" },
+ pastePart("p1", "SECRET_POSTING_BODY"),
+ ]),
+ ] as any;
+ // convertToModelMessages is async (correction #5). Unawaited, this would
+ // stringify a Promise ("{}") and pass vacuously — and it is a security
+ // assertion, so vacuous-pass is worse than failing.
+ const modelMessages = await convertToModelMessages(messages);
+ expect(JSON.stringify(modelMessages)).not.toContain("SECRET_POSTING_BODY");
+ });
+});
diff --git a/src/actions/agentChat.actions.ts b/src/actions/agentChat.actions.ts
new file mode 100644
index 0000000..a1af093
--- /dev/null
+++ b/src/actions/agentChat.actions.ts
@@ -0,0 +1,76 @@
+"use server";
+
+import type { UIMessage } from "ai";
+import prisma from "@/lib/db";
+import { handleError } from "@/lib/utils";
+import { getCurrentUser } from "@/utils/user.utils";
+import { APP_CONSTANTS } from "@/lib/constants";
+
+export const getChatConversation = async (): Promise<{
+ success: boolean;
+ data?: UIMessage[];
+ message?: string;
+}> => {
+ try {
+ const user = await getCurrentUser();
+ if (!user) throw new Error("Not authenticated");
+
+ const row = await prisma.chatConversation.findUnique({
+ where: { userId: user.id },
+ });
+ if (!row) return { success: true, data: [] };
+
+ // A corrupt row must not break the whole dashboard layout, which awaits
+ // this on every render — an empty transcript is the safe answer.
+ try {
+ return { success: true, data: JSON.parse(row.messages) as UIMessage[] };
+ } catch {
+ console.error("Chat conversation JSON was unreadable; returning empty.");
+ return { success: true, data: [] };
+ }
+ } catch (error) {
+ return handleError(error, "Failed to load the conversation.");
+ }
+};
+
+export const saveChatConversation = async (
+ messages: UIMessage[],
+): Promise<{ success: boolean; message?: string }> => {
+ try {
+ const user = await getCurrentUser();
+ if (!user) throw new Error("Not authenticated");
+
+ const trimmed = messages.slice(
+ -APP_CONSTANTS.AGENT_CHAT_MAX_STORED_MESSAGES,
+ );
+ const serialized = JSON.stringify(trimmed);
+
+ await prisma.chatConversation.upsert({
+ where: { userId: user.id },
+ update: { messages: serialized },
+ create: { userId: user.id, messages: serialized },
+ });
+
+ return { success: true };
+ } catch (error) {
+ return handleError(error, "Failed to save the conversation.");
+ }
+};
+
+export const clearChatConversation = async (): Promise<{
+ success: boolean;
+ message?: string;
+}> => {
+ try {
+ const user = await getCurrentUser();
+ if (!user) throw new Error("Not authenticated");
+
+ // deleteMany, not delete: deleting a row that does not exist must not
+ // throw, since Clear is the hard reset and has to always work.
+ await prisma.chatConversation.deleteMany({ where: { userId: user.id } });
+
+ return { success: true };
+ } catch (error) {
+ return handleError(error, "Failed to clear the conversation.");
+ }
+};
diff --git a/src/lib/agent/errors.ts b/src/lib/agent/errors.ts
new file mode 100644
index 0000000..108f1cb
--- /dev/null
+++ b/src/lib/agent/errors.ts
@@ -0,0 +1,86 @@
+import {
+ InvalidToolApprovalError,
+ InvalidToolInputError,
+ NoSuchToolError,
+ ToolCallNotFoundForApprovalError,
+} from "ai";
+import { AIUnavailableError } from "@/lib/ai";
+
+type ErrorContext = { provider?: string; model?: string };
+
+// The single fixed fallback. Never interpolate error.message into what the
+// client sees — provider SDKs leak request context into their messages.
+const GENERIC = "Something went wrong on that turn. Try asking again.";
+
+function messageOf(error: unknown): string {
+ return error instanceof Error ? error.message : String(error ?? "");
+}
+
+function nameOf(error: unknown): string {
+ return error instanceof Error ? error.name : "";
+}
+
+/**
+ * One mapping shared by the route's pre-stream catch and by
+ * toUIMessageStreamResponse's onError, so the same failure reads the same on
+ * either side of the 200-response boundary.
+ */
+export function mapAgentError(
+ error: unknown,
+ context: ErrorContext = {},
+): string {
+ const provider = context.provider ?? "the AI provider";
+ const model = context.model;
+ const message = messageOf(error);
+ const name = nameOf(error);
+
+ // Always log the real error; only the mapped string crosses the wire.
+ console.error("[agent-chat] error:", error);
+
+ if (error instanceof AIUnavailableError) return error.message;
+
+ if (
+ name === "AbortError" ||
+ name === "TimeoutError" ||
+ /aborted|abort signal/i.test(message)
+ ) {
+ return "That response was stopped or took too long. Ask again to retry.";
+ }
+
+ if (
+ InvalidToolApprovalError.isInstance?.(error) ||
+ ToolCallNotFoundForApprovalError.isInstance?.(error) ||
+ /ToolCallNotFoundForApproval|InvalidToolApproval/i.test(name)
+ ) {
+ return "That proposal has expired — the server no longer recognizes it. Use Clear and ask again.";
+ }
+
+ if (/fetch failed|ECONNREFUSED|ENOTFOUND|ECONNRESET/i.test(message)) {
+ return `Cannot reach ${provider}. Make sure the service is running, or switch provider in Settings.`;
+ }
+
+ if (
+ /does not support tools|tool (use|calling) (is )?not supported|no tools support/i.test(
+ message,
+ )
+ ) {
+ return `${provider}${model ? ` / ${model}` : ""} cannot use tools, so it cannot add a job. Pick a tool-capable model in Settings.`;
+ }
+
+ if (NoSuchToolError.isInstance?.(error) || /NoSuchTool/i.test(name)) {
+ return "The model asked for a tool that does not exist here. It only has one: adding a job.";
+ }
+
+ if (
+ InvalidToolInputError.isInstance?.(error) ||
+ /InvalidToolInput/i.test(name)
+ ) {
+ return "The model sent arguments that did not fit the tool. Try rephrasing your request.";
+ }
+
+ if (/maximum number of steps|step limit|stopWhen/i.test(message)) {
+ return "The assistant stopped after reaching its step limit for this turn.";
+ }
+
+ return GENERIC;
+}
diff --git a/src/lib/agent/paste.server.ts b/src/lib/agent/paste.server.ts
new file mode 100644
index 0000000..03d0ea9
--- /dev/null
+++ b/src/lib/agent/paste.server.ts
@@ -0,0 +1,23 @@
+import { randomUUID } from "node:crypto";
+import { APP_CONSTANTS } from "@/lib/constants";
+
+// The only node:crypto user in the paste pipeline — kept out of paste.ts so
+// client components can import the rest.
+
+function generateNonce(): string {
+ return randomUUID().replace(/-/g, "").slice(0, 16).toUpperCase();
+}
+
+// Sanitize THEN wrap. A static delimiter is breakout-able by construction:
+// the attacker authors the posting and controls exactly the head that gets
+// injected, so closing the delimiter early is trivial. Stripping after
+// wrapping would remove the delimiters we just added.
+export function truncateForModel(
+ text: string,
+ nonce: string = generateNonce(),
+): { block: string; nonce: string } {
+ const head = text.slice(0, APP_CONSTANTS.AGENT_CHAT_PASTE_HEAD_CHARS);
+ const sanitized = head.split(nonce).join("");
+ const block = `<<<PASTED_${nonce}>>>\n${sanitized}\n<<<END_PASTED_${nonce}>>>`;
+ return { block, nonce };
+}
diff --git a/src/lib/agent/paste.ts b/src/lib/agent/paste.ts
new file mode 100644
index 0000000..d7cfb9d
--- /dev/null
+++ b/src/lib/agent/paste.ts
@@ -0,0 +1,101 @@
+import { isToolUIPart, type UIMessage } from "ai";
+import { APP_CONSTANTS } from "@/lib/constants";
+import {
+ isAgentPastePart,
+ type AgentAddJobResult,
+ type AgentPastePart,
+} from "@/models/agent.model";
+
+// Client-safe by design: no node:crypto here. truncateForModel lives in
+// paste.server.ts so the composer and transcript can import these helpers.
+
+// Newest unconsumed paste wins, but only while it is recent. A paste is only
+// marked consumed by a successful create, so a paste the user moved past —
+// pasted, then talked about something else — would otherwise splice itself
+// into a later typed add and re-enter the prompt on every turn. Two user
+// messages covers every designed flow: paste+ask in one message; paste →
+// clarifying question → confirm; and cancel → queued correction → retry
+// (approval responses are not user messages). Beyond the window the tool
+// asks for a re-paste, which is visible and cheap. Symptom the window is too
+// tight: the assistant asks the user to paste again mid-negotiation over a
+// single posting — widen the constant, do not remove the bound.
+export function resolvePastedText(messages: UIMessage[]): string | undefined {
+ let userMessagesSeen = 0;
+ for (let i = messages.length - 1; i >= 0; i--) {
+ const message = messages[i];
+ if (message?.role === "user") {
+ userMessagesSeen++;
+ if (
+ userMessagesSeen > APP_CONSTANTS.AGENT_CHAT_PASTE_ACTIVE_USER_MESSAGES
+ ) {
+ return undefined;
+ }
+ }
+ const parts = message?.parts ?? [];
+ for (let j = parts.length - 1; j >= 0; j--) {
+ const part = parts[j];
+ if (isAgentPastePart(part) && !part.data.consumed) return part.data.text;
+ }
+ }
+ return undefined;
+}
+
+function findConsumingWrite(
+ messages: UIMessage[],
+): { company?: string; jobTitle?: string } | undefined {
+ for (let i = messages.length - 1; i >= 0; i--) {
+ for (const part of messages[i]?.parts ?? []) {
+ if (!isToolUIPart(part) || part.state !== "output-available") 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.
+ if (!output?.created) continue;
+ const input = part.input as
+ | { company?: string; jobTitle?: string }
+ | undefined;
+ return { company: input?.company, jobTitle: input?.jobTitle };
+ }
+ }
+ return undefined;
+}
+
+// Called from the persistence path so stubbing happens in exactly one place.
+// Without it a conversation that added five jobs carries ~30KB of dead
+// posting text forever, re-sent on every request.
+export function stubConsumedPastes(messages: UIMessage[]): UIMessage[] {
+ const write = findConsumingWrite(messages);
+ if (!write) return messages;
+
+ const label = `[pasted posting — saved as ${write.jobTitle ?? "a job"} at ${write.company ?? "a company"}]`;
+
+ return messages.map((message) => ({
+ ...message,
+ parts: (message.parts ?? []).map((part) => {
+ if (!isAgentPastePart(part) || part.data.consumed) return part;
+ const stubbed: AgentPastePart = {
+ ...part,
+ data: { ...part.data, text: label, chars: label.length, consumed: true },
+ };
+ return stubbed;
+ }),
+ })) as UIMessage[];
+}
+
+// Derived from the messages array rather than live useChat state, so it works
+// identically on a transcript rehydrated from the DB.
+export function hasPendingApproval(messages: UIMessage[]): boolean {
+ return messages.some((message) =>
+ (message.parts ?? []).some(
+ (part) => isToolUIPart(part) && part.state === "approval-requested",
+ ),
+ );
+}
+
+// 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.
+export function windowMessages(messages: UIMessage[]): UIMessage[] {
+ return messages.slice(-APP_CONSTANTS.AGENT_CHAT_HISTORY_MESSAGES);
+}