A one-of-a-kind resume builder that keeps your privacy in mind. Completely secure, customizable, portable, open-source and free forever. Try it out today!
TypeScript agent-skillsaidsh-pluginhacktoberfestjavascriptmcp-serverreactresume-builderself-hostedtypescript
feat: retain accepted assistant and writing sources
Amruth Pillai228d2dd09986
diff --git a/apps/mobile/scripts/assistant-proposals.test.mjs b/apps/mobile/scripts/assistant-proposals.test.mjsindex e9e6d53a3..f573bbcb4 100644--- a/apps/mobile/scripts/assistant-proposals.test.mjs+++ b/apps/mobile/scripts/assistant-proposals.test.mjs@@ -91,7 +91,7 @@ function store(kind) {return { ...state, update: suppressed ? () => {} : state.update };};useStore.subscribe = (listener) => runtime.store.subscribe(listener);- useStore.load = async (content, initialData) => {+ useStore.load = async (content, initialData, aiOperationIds = []) => {let document = {id: kind,name: kind,@@ -100,6 +100,7 @@ function store(kind) {isLocked: false,revision: 1,updatedAt: new Date(),+ aiOperationIds,};storage = new Map();adapter = {@@ -115,7 +116,7 @@ function store(kind) {version: (doc) => doc.revision,parse: (doc) => ({ ...doc, updatedAt: new Date(doc.updatedAt) }),save: async (doc, _baseline, _session, _force, owner, applications) => {- documentSaves.push({ kind, owner, applications });+ documentSaves.push({ kind, owner, applications, aiOperationIds: doc.aiOperationIds });if (failedSave) throw new Error("Offline");document = { ...doc, revision: doc.revision + 1 };return document;@@ -155,8 +156,19 @@ function store(kind) {}const resumeStore = store("resume");const letterStore = store("letter");+const aiUsage = evaluate(+ buildSync({+ entryPoints: [mobileRequire.resolve("@reactive-resume/schema/ai-usage")],+ bundle: true,+ platform: "node",+ format: "cjs",+ write: false,+ }).outputFiles[0].text,+ {},+);const dependencies = {"@reactive-resume/ai/tools/agent-tool-contracts": agentContracts,+ "@reactive-resume/schema/ai-usage": aiUsage,react: { useMemo: (fn) => fn() },immer: { produce },zustand: {@@ -251,6 +263,32 @@ for (const kind of ["resume", "letter"]) {kind === "resume" ? documents.useResumeAssistantDocument("resume") : documents.useLetterAssistantDocument("letter");const owner = kind === "resume" ? resumeStore : letterStore;const current = () => owner.getState();+ test(`${kind} pairs only applied proposal sources through offline recovery and Undo/Redo`, async () => {+ await owner.load("<p>Old</p>", undefined, ["prior-source"]);+ const rewrite = { ...edit("source-rewrite", "<p>Rewritten</p>"), aiOperationIds: ["rewrite-source"] };+ const addition = {+ ...edit("source-addition", "<p>Old</p><p>Mentored two designers</p>"),+ aiOperationIds: ["addition-source", "rewrite-source"],+ };+ const stale = { ...edit("source-stale", "<p>Conflict</p>"), aiOperationIds: ["stale-source"] };+ assert.deepEqual(open().accept([rewrite, addition, stale]), { applied: [rewrite, addition], stale: [stale] });+ const expected = ["prior-source", "rewrite-source", "addition-source"];+ assert.deepEqual(current().document.aiOperationIds, expected, "Sources must be paired before any save");+ assert.equal(documentSaves.length, 0);+ current().undo();+ assert.deepEqual(current().document.aiOperationIds, ["prior-source"]);+ current().redo();+ assert.deepEqual(current().document.aiOperationIds, expected);+ failedSave = true;+ await current().flush();+ assert.equal(current().status, "error");+ await owner.restart();+ assert.deepEqual(current().document.aiOperationIds, expected);+ failedSave = false;+ await current().flush();+ assert.equal(current().status, "saved");+ assert.deepEqual(documentSaves.at(-1).aiOperationIds, expected);+ });test(`${kind} keeps real acceptance identity through refinements, save echoes and explicit Undo/Redo`, async () => {const doc = open();const rewrite = edit("rewrite", "<p>Rewritten</p>");@@ -771,7 +809,7 @@ test("provider Off keeps saved local Accept and Undo actionable while questions"@/ui": { ...dependencies["@/ui"], Button: "Button", Text: "Text", Icon: "Icon", useTheme: () => theme },},);- const proposal = edit("off-edit", "<p>Saved rewrite</p>");+ const proposal = { ...edit("off-edit", "<p>Saved rewrite</p>"), aiOperationIds: ["model-forged-source"] };const doc = documents.useResumeAssistantDocument("resume");const part = {type: "tool-propose_edits",@@ -800,6 +838,7 @@ test("provider Off keeps saved local Accept and Undo actionable while questionsmessage: {id: "off-message",role: "assistant",+ metadata: { aiOperationIds: ["saved-assistant-source"] },parts: [part,{@@ -830,6 +869,12 @@ test("provider Off keeps saved local Accept and Undo actionable while questionsreturn buttons;};const accept = render().find((b) => b.label === "Accept");+ assert.deepEqual(currentProposal.aiOperationIds, ["saved-assistant-source"]);+ assert.equal(+ proposals.toProposals(part, new Map())[0].aiOperationIds,+ undefined,+ "Old messages cannot inherit model-forged sources",+ );assert.ok(accept);assert.equal(accept.disabled, false);assert.equal(@@ -837,9 +882,12 @@ test("provider Off keeps saved local Accept and Undo actionable while questionsfalse,);accept.onPress();+ assert.deepEqual(resumeStore.getState().document.aiOperationIds, ["saved-assistant-source"]);await resumeStore.getState().flush();+ assert.deepEqual(documentSaves.at(-1).aiOperationIds, ["saved-assistant-source"]);assert.equal(documents.useResumeAssistantDocument("resume").stateOf(currentProposal), "accepted");resumeStore.getState().undo();+ assert.deepEqual(resumeStore.getState().document.aiOperationIds, []);await resumeStore.getState().flush();assert.equal(render().find((b) => b.label === "Accept").disabled, false);assert.equal(documents.useResumeAssistantDocument("resume").stateOf(currentProposal), "pending");diff --git a/apps/mobile/scripts/experience.test.mjs b/apps/mobile/scripts/experience.test.mjsindex c5be41876..cb0ef34cb 100644--- a/apps/mobile/scripts/experience.test.mjs+++ b/apps/mobile/scripts/experience.test.mjs@@ -2933,10 +2933,19 @@ console.log("@reactive-resume/resume/markdown": { buildMarkdown: () => "Fictional original" },"@reactive-resume/resume/proposals": {collectPassages: () => [{ id: "p1", location: "Summary", text: "Fictional original" }],+ getProposalState: () => "pending",+ blockText: (text) => text,},"./actions": {},"./issues": { getSectionName: () => "Summary" },- "./review": { mapWritingReview: () => ({ proposals: [], notes: [] }) },+ "./review": {+ mapWritingReview: () => ({+ proposals: [+ { id: "saved-rewrite", before: "Fictional original", after: "Fictional rewrite", status: "pending" },+ ],+ notes: [],+ }),+ },"@/draft": { useResumeStore: (select) => select({ proposalApplications: {} }) },"@/api/client": {client: {@@ -2986,6 +2995,7 @@ console.log(passages: [],review: { summary: "Latest saved", strengths: [], suggestions: [] },reviewedAt: new Date("2030-01-01T00:00:02Z"),+ aiOperationIds: ["saved-writing-source"],aiUsage: {requests: 2,models: [{ providerId: "old-provider", label: "Recorded AI", provider: "openai", model: "recorded-model" }],@@ -2993,6 +3003,7 @@ console.log(};render(Writing, writingProps);assert.equal(publishedWriting.summary, "Latest saved");+ assert.deepEqual(publishedWriting.proposals[0].aiOperationIds, ["saved-writing-source"]);writingProps.review = publishedWriting;assert.deepEqual(nodes(render(Writing, writingProps)).find((node) => node.type === "ResultUsage").props.usage,@@ -3001,11 +3012,18 @@ console.log(resolveOld({ summary: "Older discarded response" });await settle();assert.equal(publishedWriting.summary, "Latest saved");+ assert.deepEqual(publishedWriting.proposals[0].aiOperationIds, ["saved-writing-source"]);assert.deepEqual(calls,[["writing", "resume-a"]],"An unmounted canceled request cannot publish or invalidate a different document",);+ delete savedWriting.aiOperationIds;+ savedWriting.reviewedAt = new Date("2030-01-01T00:00:03Z");+ render(Writing, writingProps);+ assert.equal(publishedWriting.proposals.length, 1);+ assert.equal(publishedWriting.proposals[0].aiOperationIds, undefined, "Older source-less reviews remain usable");+ assert.equal(writingRequest, 2, "Hydration never repeats generation");console.log("PASS native Writing authoritative publication and unmounted request order");reset();diff --git a/apps/mobile/scripts/posting-capture.test.mjs b/apps/mobile/scripts/posting-capture.test.mjsindex aded978b8..e8b4d8cfb 100644--- a/apps/mobile/scripts/posting-capture.test.mjs+++ b/apps/mobile/scripts/posting-capture.test.mjs@@ -511,6 +511,10 @@ const { MessageView } = load(source("features/assistant/messages.tsx"), {"@tanstack/react-query": { useQueryClient: () => ({}) },"expo-router": { useRouter: () => ({}) },"@reactive-resume/ai/tools/agent-tool-contracts": contracts,+ "@reactive-resume/schema/ai-usage": load(+ new URL("../../../packages/schema/src/ai-usage.ts", import.meta.url).pathname,+ { zod },+ ),"@reactive-resume/resume/proposals": {},"@reactive-resume/resume/word-diff": {},"./chat": { webSources: contracts.agentWebSources },diff --git a/apps/mobile/src/draft/store.ts b/apps/mobile/src/draft/store.tsindex b00cf68e7..c9bdc4883 100644--- a/apps/mobile/src/draft/store.ts+++ b/apps/mobile/src/draft/store.ts@@ -10,6 +10,7 @@ import {queueProposalApplications,readProposalApplications,restoreProposalApplications,+ proposalAiOperationIds,} from "@reactive-resume/resume/proposals";import { generateId } from "@reactive-resume/utils/string";@@ -367,7 +368,8 @@ export function createDraftStore<D extends Document, T>(adapter: DraftAdapter<D,const before = adapter.data(record.document);const next = produce(before, recipe);const existingSources = record.document.aiOperationIds ?? [];- const newSources = options.aiOperationIds?.some((id) => !existingSources.includes(id));+ const sources = [...(options.aiOperationIds ?? []), ...proposalAiOperationIds(options.applied ?? [])];+ const newSources = sources.some((id) => !existingSources.includes(id));if (next === before && !newSources) return;const now = Date.now();const coalesce =@@ -384,9 +386,7 @@ export function createDraftStore<D extends Document, T>(adapter: DraftAdapter<D,newSources? {...document,- aiOperationIds: [- ...new Set([...(record.document.aiOperationIds ?? []), ...(options.aiOperationIds ?? [])]),- ],+ aiOperationIds: [...new Set([...(record.document.aiOperationIds ?? []), ...sources])],aiUsage: null,}: document,diff --git a/apps/mobile/src/draft/types.ts b/apps/mobile/src/draft/types.tsindex 03a33684c..25aea22a0 100644--- a/apps/mobile/src/draft/types.ts+++ b/apps/mobile/src/draft/types.ts@@ -32,7 +32,7 @@ export type DraftConflict<TDocument> = {export type UpdateOptions = {aiOperationIds?: string[] | undefined;/** Filled by the synchronous proposal recipe; travels with this undo step. */- applied?: readonly Pick<Proposal, "id" | "after" | "snapshot">[];+ applied?: readonly Pick<Proposal, "id" | "after" | "snapshot" | "aiOperationIds">[];/** The field being edited. Consecutive edits with the same key within 1 s merge into one undo step. */coalesceKey?: string | undefined;/** Always a step of its own (adding, moving or deleting). */diff --git a/apps/mobile/src/features/assistant/chat-view.tsx b/apps/mobile/src/features/assistant/chat-view.tsxindex 74328571e..aeb9aae23 100644--- a/apps/mobile/src/features/assistant/chat-view.tsx+++ b/apps/mobile/src/features/assistant/chat-view.tsx@@ -32,6 +32,7 @@ import {tailoringAllows,} from "@reactive-resume/ai/tools/agent-tool-contracts";import { withEditedText } from "@reactive-resume/resume/proposals";+import { aiOperationIds } from "@reactive-resume/schema/ai-usage";import { isNetworkError } from "@reactive-resume/utils/http";import { attachmentPart, refreshThreads, transcriptOf, useAssistantChat } from "./chat";import { FileChip, MessageView, Status } from "./messages";@@ -547,7 +548,9 @@ function Conversation(props: ConversationProps) {() =>document && receiptsReady? messages.flatMap((message) =>- message.parts.flatMap((part) => (isProposeEdits(part) ? toProposals(part, statuses) : [])),+ message.parts.flatMap((part) =>+ isProposeEdits(part) ? toProposals(part, statuses, aiOperationIds(message.metadata)) : [],+ ),): [],[messages, statuses, document, receiptsReady],diff --git a/apps/mobile/src/features/assistant/messages.tsx b/apps/mobile/src/features/assistant/messages.tsxindex d2d94de3a..444ff1298 100644--- a/apps/mobile/src/features/assistant/messages.tsx+++ b/apps/mobile/src/features/assistant/messages.tsx@@ -21,6 +21,7 @@ import { ActivityIndicator, Linking, Pressable, TextInput, View } from "react-naimport { agentKnowledgeUsed, agentReadPostings, agentWebFailure } from "@reactive-resume/ai/tools/agent-tool-contracts";import { additionParts, blockText, needsConfirmation, proposalText } from "@reactive-resume/resume/proposals";import { wordDiff } from "@reactive-resume/resume/word-diff";+import { aiOperationIds } from "@reactive-resume/schema/ai-usage";import { webSources } from "./chat";import { handToAssistant } from "./handoff";import { AssistantMarkdown } from "./markdown";@@ -386,7 +387,7 @@ function ToolPartView({ part, message, streaming, readOnly, answerable, proposal</Status>);if (!proposals) return null;- const list = toProposals(part, proposals.statuses);+ const list = toProposals(part, proposals.statuses, aiOperationIds(message.metadata));const skipped = skippedCount(part);const requirements = requirementsOf(part);const forJobCopy = proposals.forJobCopy(message, part);diff --git a/apps/mobile/src/features/assistant/proposals.ts b/apps/mobile/src/features/assistant/proposals.tsindex c0051f01a..73d24414b 100644--- a/apps/mobile/src/features/assistant/proposals.ts+++ b/apps/mobile/src/features/assistant/proposals.ts@@ -61,7 +61,11 @@ export const supersededIn = (messages: readonly { parts: readonly { type: stringexport const requirementsOf = (part: ToolPart) => (part.output as ProposeEditsOutput | undefined)?.requirements ?? [];/** The edits in a `propose_edits` result, with what the user has done with each since. */-export function toProposals(part: ToolPart, receipts: ReadonlyMap<string, Receipt>): Proposal[] {+export function toProposals(+ part: ToolPart,+ receipts: ReadonlyMap<string, Receipt>,+ sourceIds: string[] = [],+): Proposal[] {const output = part.output as ProposeEditsOutput | undefined;return (output?.edits ?? []).map((streamed) => {const receipt = receipts.get(streamed.id);@@ -77,6 +81,7 @@ export function toProposals(part: ToolPart, receipts: ReadonlyMap<string, Receipstatus: receipt?.status ?? edit.status,...(receipt?.superseded ? { superseded: true } : {}),source: "assistant",+ aiOperationIds: sourceIds.length ? sourceIds : undefined,};});}diff --git a/apps/mobile/src/features/check/writing.tsx b/apps/mobile/src/features/check/writing.tsxindex c4286adf3..6e0c6a75d 100644--- a/apps/mobile/src/features/check/writing.tsx+++ b/apps/mobile/src/features/check/writing.tsx@@ -71,10 +71,19 @@ export function Writing({ id, data, issues, offline, locked, review, setReview }const identity = `${id}:${entry?.reviewedAt.toISOString()}`;if (!entry || hydrated.current === identity) return;hydrated.current = identity;+ const mapped = mapWritingReview(+ entry.review.suggestions,+ entry.inputText === inputText ? passages : [],+ entry.passages,+ );setReview({summary: entry.review.summary,strengths: entry.review.strengths,- ...mapWritingReview(entry.review.suggestions, entry.inputText === inputText ? passages : [], entry.passages),+ notes: mapped.notes,+ proposals: mapped.proposals.map((proposal) => ({+ ...proposal,+ ...(entry.aiOperationIds?.length ? { aiOperationIds: entry.aiOperationIds } : {}),+ })),});setReviewInput(entry.inputText);setReviewedAt(entry.reviewedAt);diff --git a/apps/web/src/features/assistant/conversation.test.tsx b/apps/web/src/features/assistant/conversation.test.tsxindex 6dc7bc8e2..4ddacec67 100644--- a/apps/web/src/features/assistant/conversation.test.tsx+++ b/apps/web/src/features/assistant/conversation.test.tsx@@ -571,6 +571,26 @@ it("accepts in the same turn as the click, with the decision left to the documenexpect(mocks.record).not.toHaveBeenCalled();});+it.each([undefined, ["recorded-assistant-source"]])(+ "accepts only stored message sources, including older source-less replies: %s",+ (sources) => {+ const base = proposing({ tailoredFor: "application-2" });+ const part = base.parts[0];+ const proposal = part?.output.edits[0];+ if (!part || !proposal) throw new Error("Missing proposal fixture");+ const message = {+ ...base,+ metadata: { ...base.metadata, ...(sources ? { aiOperationIds: sources } : {}) },+ parts: [+ { ...part, output: { ...part.output, edits: [{ ...proposal, aiOperationIds: ["model-forged-source"] }] } },+ ],+ };+ const { accept } = renderConversation([message]);+ fireEvent.click(screen.getByRole("button", { name: "Accept" }));+ expect(accept).toHaveBeenCalledWith([expect.objectContaining({ aiOperationIds: sources })]);+ },+);+it("never accepts tailored or older sets into a resume that isn't the job's copy, whatever it's linked to now", () => {// The base resume after copying moved its job link: no posting is linked any more.const base = { jobCopy: true, madeFor: null, posting: null };diff --git a/apps/web/src/features/assistant/conversation.tsx b/apps/web/src/features/assistant/conversation.tsxindex 5f76c069c..1ae9979fc 100644--- a/apps/web/src/features/assistant/conversation.tsx+++ b/apps/web/src/features/assistant/conversation.tsx@@ -23,6 +23,7 @@ import {} from "@reactive-resume/ai/tools/agent-tool-contracts";import { measureOverflow } from "@reactive-resume/pdf/page-map";import { withEditedText } from "@reactive-resume/resume/proposals";+import { aiOperationIds } from "@reactive-resume/schema/ai-usage";import { Button } from "@reactive-resume/ui/components/button";import { Icon } from "@reactive-resume/ui/components/icon";import { IconButton } from "@reactive-resume/ui/components/icon-button";@@ -244,7 +245,9 @@ export function Conversation(props: ConversationProps) {const proposals = useMemo(() =>(receiptsReady ? messages : []).flatMap((message) =>- message.parts.flatMap((part) => (isProposeEdits(part) ? toProposals(part, statuses, document) : [])),+ message.parts.flatMap((part) =>+ isProposeEdits(part) ? toProposals(part, statuses, document, aiOperationIds(message.metadata)) : [],+ ),),[messages, statuses, document, receiptsReady],);@@ -495,7 +498,12 @@ const isProposeEdits = (part: Part): part is ToolPart =>part.type === "tool-propose_edits" && (part as ToolPart).state === "output-available";/** The edits in a result, with what the server's receipts say since: decisions, and the user's saved wording. */-function toProposals(part: ToolPart, receipts: ReadonlyMap<string, Receipt>, document: AssistantDocument): Proposal[] {+function toProposals(+ part: ToolPart,+ receipts: ReadonlyMap<string, Receipt>,+ document: AssistantDocument,+ sourceIds: string[] = [],+): Proposal[] {const output = part.output as ProposeEditsOutput | undefined;return (output?.edits ?? []).map((streamed) => {const receipt = receipts.get(streamed.id);@@ -513,6 +521,7 @@ function toProposals(part: ToolPart, receipts: ReadonlyMap<string, Receipt>, docstatus: receipt?.status ?? edit.status,...(receipt?.superseded ? { superseded: true } : {}),source: "assistant",+ aiOperationIds: sourceIds.length ? sourceIds : undefined,};});}@@ -874,7 +883,7 @@ function ToolPartView({</Status>);const output = part.output as ProposeEditsOutput;- const proposals = toProposals(part, statuses, document);+ const proposals = toProposals(part, statuses, document, aiOperationIds(message.metadata));const states = proposals.map(document.stateOf);const pending = states.filter((state) => state === "pending").length;const accepted = states.filter((state) => state === "accepted").length;diff --git a/apps/web/src/features/assistant/document.test.tsx b/apps/web/src/features/assistant/document.test.tsxindex 80f4a8bc2..73b063f42 100644--- a/apps/web/src/features/assistant/document.test.tsx+++ b/apps/web/src/features/assistant/document.test.tsx@@ -105,6 +105,30 @@ it("applies ordered additions and a rewrite through the real letter store, retaiexpect(result.current?.stateOf({ ...first, status: "accepted" })).toBe("accepted");});+it("pairs accepted letter sources with saves and toast Undo, excluding stale proposals", async () => {+ act(() => store().load({ ...letter, aiOperationIds: ["prior-source"] }));+ const { result } = renderHook(useLetterAssistantDocument);+ const rewrite = { ...edit("source-rewrite", "<p>Rewritten</p>"), aiOperationIds: ["assistant-source"] };+ const conflict = { ...edit("source-stale", "<p>Conflict</p>"), aiOperationIds: ["stale-source"] };+ act(() => {+ expect(result.current?.accept([rewrite, conflict])).toEqual({ applied: [rewrite], stale: [conflict] });+ });+ expect(store().letter?.aiOperationIds).toEqual(["prior-source", "assistant-source"]);+ expect(mocks.save).not.toHaveBeenCalled();+ const undo = mocks.toast.mock.lastCall?.[0].actionProps.onClick;+ await act(async () => {+ await store().flush();+ });+ expect(mocks.save.mock.lastCall?.[0].aiOperationIds).toEqual(["prior-source", "assistant-source"]);+ act(() => undo());+ expect(store().letter?.content).toBe(letter.content);+ expect(store().letter?.aiOperationIds).toEqual(["prior-source"]);+ await act(async () => {+ await store().flush();+ });+ expect(mocks.save.mock.lastCall?.[0].aiOperationIds).toEqual(["prior-source"]);+});+it("reports genuine stale edits and refuses old callbacks after switching or locking letters", () => {const { result } = renderHook(useLetterAssistantDocument);const doc = result.current;diff --git a/apps/web/src/features/assistant/document.ts b/apps/web/src/features/assistant/document.tsindex a757d6606..37d32f44c 100644--- a/apps/web/src/features/assistant/document.ts+++ b/apps/web/src/features/assistant/document.ts@@ -151,6 +151,7 @@ export function useLetterAssistantDocument(): AssistantDocument | null {const { letter: current, edit, changing, proposalApplications, sessionId } = useLetterEditorStore.getState();if (!current || current.id !== letter.id || current.isLocked || changing) return { applied: [], stale: [] };const before = current.content;+ const beforeSources = current.aiOperationIds ?? [];let content = before;const result = applyProposals(proposals,@@ -177,7 +178,10 @@ export function useLetterAssistantDocument(): AssistantDocument | null {!latest.letter.isLocked &&!latest.changing)- latest.edit({ content: before }, { restoreApplications: proposalApplications });+ latest.edit(+ { content: before, aiOperationIds: beforeSources },+ { restoreApplications: proposalApplications },+ );},},}diff --git a/apps/web/src/features/letters/store.ts b/apps/web/src/features/letters/store.tsindex ced9a0374..486d56c76 100644--- a/apps/web/src/features/letters/store.ts+++ b/apps/web/src/features/letters/store.ts@@ -10,6 +10,7 @@ import {queueProposalApplications,readProposalApplications,restoreProposalApplications,+ proposalAiOperationIds,} from "@reactive-resume/resume/proposals";import {coverLetterDocumentSchema,@@ -133,7 +134,7 @@ type LetterEditorStore = {edit: (edits: LetterEdits,options?: {- applied?: readonly Pick<Proposal, "id" | "after" | "snapshot">[];+ applied?: readonly Pick<Proposal, "id" | "after" | "snapshot" | "aiOperationIds">[];restoreApplications?: ProposalApplications;},) => void;@@ -427,8 +428,15 @@ export const useLetterEditorStore = create<LetterEditorStore>()((set, get) => ({edit: (input, options = {}) => {const { letter, changing, proposalApplications, pendingProposalApplications } = get();- const { sender, ...otherEdits } = input;- const edits = sender && (changing || (letter?.sourceResumeId && letter.senderLinked)) ? otherEdits : input;+ const sources = proposalAiOperationIds(options.applied ?? []);+ const withSources = sources.length+ ? {+ ...input,+ aiOperationIds: [...new Set([...(input.aiOperationIds ?? letter?.aiOperationIds ?? []), ...sources])],+ }+ : input;+ const { sender, ...otherEdits } = withSources;+ const edits = sender && (changing || (letter?.sourceResumeId && letter.senderLinked)) ? otherEdits : withSources;if (!hasEdits(edits) || letter?.isLocked) return;set((state) =>state.letterdiff --git a/apps/web/src/features/resume/builder/draft.test.ts b/apps/web/src/features/resume/builder/draft.test.tsindex c4908bab3..b3d513700 100644--- a/apps/web/src/features/resume/builder/draft.test.ts+++ b/apps/web/src/features/resume/builder/draft.test.ts@@ -1,11 +1,13 @@// @vitest-environment happy-domimport type { Resume } from "./draft";+import type { Proposal } from "@reactive-resume/resume/proposals";import type { ResumeData } from "@reactive-resume/schema/resume/data";import { act, renderHook } from "@testing-library/react";import { afterEach, assert, beforeEach, describe, expect, it, vi } from "vite-plus/test";import { i18n } from "@lingui/core";import { ORPCError } from "@orpc/client";+import { applyResumeProposals } from "@reactive-resume/resume/proposals";import { sortSectionItemsByPeriod } from "@reactive-resume/resume/section-sort";import { parseResumeData } from "@reactive-resume/schema/resume/data";import { defaultResumeData } from "@reactive-resume/schema/resume/default";@@ -1782,6 +1784,50 @@ describe("concurrent receipt ownership", () => {vi.useRealTimers();});const s = () => useResumeStore.getState();+ it("pairs sources populated by the acceptance recipe with save, Undo and Redo, excluding stale edits", async () => {+ const initial = makeResume("accepted-source-pairing");+ initial.aiOperationIds = ["prior-source"];+ initial.data.summary.content = "<p>Original</p>";+ s().initialize(initial);+ const proposal: Proposal = {+ id: "accepted",+ target: { sectionId: "summary", field: "content" },+ location: "Summary",+ why: "Clearer",+ before: initial.data.summary.content,+ after: "<p>Reviewed</p>",+ status: "pending",+ source: "assistant",+ aiOperationIds: ["assistant-source"],+ };+ const stale = { ...proposal, id: "stale", after: "<p>Conflicting</p>", aiOperationIds: ["stale-source"] };+ const applied: Proposal[] = [];+ orpcMocks.updateResume.mockImplementation(async (input) => ({+ ...initial,+ data: input.data,+ aiOperationIds: input.aiOperationIds,+ updatedAt: new Date(initial.updatedAt.getTime() + 1),+ }));+ s().updateResumeData(+ (data) => {+ applied.push(...applyResumeProposals(data, [proposal, stale]).applied);+ },+ { newStep: true, applied },+ );+ expect(applied.map((p) => p.id)).toEqual([proposal.id]);+ expect(s().resume?.aiOperationIds).toEqual(["prior-source", "assistant-source"]);+ expect(orpcMocks.updateResume).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(500);+ expect(orpcMocks.updateResume.mock.lastCall?.[0].aiOperationIds).toEqual(["prior-source", "assistant-source"]);+ s().undo();+ expect(s().resume?.aiOperationIds).toEqual(["prior-source"]);+ await vi.advanceTimersByTimeAsync(500);+ expect(orpcMocks.updateResume.mock.lastCall?.[0].aiOperationIds).toEqual(["prior-source"]);+ s().redo();+ expect(s().resume?.aiOperationIds).toEqual(["prior-source", "assistant-source"]);+ await vi.advanceTimersByTimeAsync(500);+ expect(orpcMocks.updateResume.mock.lastCall?.[0].aiOperationIds).toEqual(["prior-source", "assistant-source"]);+ });it("editor Undo removes only its Improve source and saves it alongside the restored wording", async () => {const initial = makeResume("improve-editor-undo");initial.aiOperationIds = ["import-source", "reviewed-improve", "other-field-source"];diff --git a/apps/web/src/features/resume/builder/draft.ts b/apps/web/src/features/resume/builder/draft.tsindex 05db723c4..f193016cb 100644--- a/apps/web/src/features/resume/builder/draft.ts+++ b/apps/web/src/features/resume/builder/draft.ts@@ -16,6 +16,7 @@ import {appliedApplications,queueProposalApplications,readProposalApplications,+ proposalAiOperationIds,restoreProposalApplications,} from "@reactive-resume/resume/proposals";import { aiOperationIdsSchema } from "@reactive-resume/schema/ai-usage";@@ -65,7 +66,7 @@ export type UpdateResumeDataOptions = {aiOperationIds?: string[] | undefined;removedAiOperationIds?: string[] | undefined;/** Proposals this edit applied, recorded with their wording in this undo step alongside the authored data. */- applied?: readonly Pick<Proposal, "id" | "after" | "snapshot">[];+ applied?: readonly Pick<Proposal, "id" | "after" | "snapshot" | "aiOperationIds">[];/*** Identifies the field being edited. Consecutive edits to the same field within a second merge into* one undo step, so typing a sentence undoes as a whole.@@ -791,10 +792,9 @@ export const useResumeStore = create<ResumeStore>()(}fn(state.resume.data as WritableDraft<ResumeData>);- if (options.aiOperationIds?.length) {- state.resume.aiOperationIds = [- ...new Set([...(state.resume.aiOperationIds ?? []), ...options.aiOperationIds]),- ];+ const sources = [...(options.aiOperationIds ?? []), ...proposalAiOperationIds(options.applied ?? [])];+ if (sources.length) {+ state.resume.aiOperationIds = [...new Set([...(state.resume.aiOperationIds ?? []), ...sources])];state.resume.aiUsage = null;}if (options.removedAiOperationIds?.length) {diff --git a/apps/web/src/features/resume/editor/check/writing-tab.test.tsx b/apps/web/src/features/resume/editor/check/writing-tab.test.tsxindex 8f40555ca..c1aae8dcd 100644--- a/apps/web/src/features/resume/editor/check/writing-tab.test.tsx+++ b/apps/web/src/features/resume/editor/check/writing-tab.test.tsx@@ -4,6 +4,8 @@ import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";import { i18n } from "@lingui/core";import { I18nProvider } from "@lingui/react";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { buildMarkdown } from "@reactive-resume/resume/markdown";+import { collectPassages } from "@reactive-resume/resume/proposals";import { defaultResumeData } from "@reactive-resume/schema/resume/default";import { useEditorStore } from "../store";@@ -49,6 +51,15 @@ it("publishes only the document's saved review when an older unmounted request fconst data = structuredClone(defaultResumeData);data.summary.content = "<p>Fictional original</p>";const review = (summary: string) => ({ summary, suggestions: [], strengths: [], jdAlignment: null });+ const passages = collectPassages(data, {+ summary: "Summary",+ sectionTitle: () => "Section",+ entryTitle: () => "Entry",+ bullet: String,+ paragraph: String,+ });+ const passage = passages[0];+ if (!passage) throw new Error("Missing fictional passage");let saved: unknown = null;api.read.mockImplementation(async () => saved);let old!: (value: unknown) => void;@@ -82,10 +93,22 @@ it("publishes only the document's saved review when an older unmounted request ffireEvent.click(screen.getByRole("button", { name: "Review writing" }));await waitFor(() => expect(api.review).toHaveBeenCalledTimes(2));saved = {- inputText: "original",- passages: [],- review: review("Latest saved review"),+ inputText: buildMarkdown(data).trim(),+ passages: [{ id: passage.id, where: passage.location, text: passage.text }],+ review: {+ ...review("Latest saved review"),+ suggestions: [+ {+ section: "Summary",+ passageId: passage.id,+ issue: "Clearer",+ rewrite: "Fictional reviewed wording",+ impact: "medium",+ },+ ],+ },reviewedAt: new Date("2030-01-01T00:00:02Z"),+ aiOperationIds: ["saved-writing-source"],aiUsage: {requests: 2,models: [{ providerId: "old-provider", label: "Recorded AI", provider: "openai", model: "recorded-model" }],@@ -95,12 +118,23 @@ it("publishes only the document's saved review when an older unmounted request fnewer(review("Latest saved review"));});await waitFor(() => expect(screen.getByText("Latest saved review")).toBeDefined());+ expect(useEditorStore.getState().proposals).toHaveLength(1);+ expect(useEditorStore.getState().proposals[0]?.aiOperationIds).toEqual(["saved-writing-source"]);await act(async () => {old(review("Older discarded response"));});expect(useEditorStore.getState().writingReview?.summary).toBe("Latest saved review");+ expect(useEditorStore.getState().proposals[0]?.aiOperationIds).toEqual(["saved-writing-source"]);expect(screen.queryByText("Older discarded response")).toBeNull();expect(screen.getByText("AI request attempts: 2")).toBeVisible();expect(screen.getByText("Recorded AI · openai · recorded-model")).toBeVisible();+ const { aiOperationIds: _sources, ...legacy } = saved as Record<string, unknown>;+ saved = { ...legacy, reviewedAt: new Date("2030-01-01T00:00:03Z") };+ await act(async () => {+ await client.invalidateQueries({ queryKey: ["writing", api.id] });+ });+ await waitFor(() => expect(useEditorStore.getState().proposals[0]?.aiOperationIds).toBeUndefined());+ expect(useEditorStore.getState().proposals).toHaveLength(1);+ expect(api.review).toHaveBeenCalledTimes(2);client.clear();});diff --git a/apps/web/src/features/resume/editor/check/writing-tab.tsx b/apps/web/src/features/resume/editor/check/writing-tab.tsxindex 0ccf82e03..56d2c042b 100644--- a/apps/web/src/features/resume/editor/check/writing-tab.tsx+++ b/apps/web/src/features/resume/editor/check/writing-tab.tsx@@ -81,7 +81,10 @@ export function WritingTab({ data, issues }: WritingTabProps) {entry.passages,);useEditorStore.setState({- proposals: next,+ proposals: next.map((proposal) => ({+ ...proposal,+ ...(entry.aiOperationIds?.length ? { aiOperationIds: entry.aiOperationIds } : {}),+ })),writingReview: { summary: entry.review.summary, strengths: entry.review.strengths, notes },});setReviewInput(entry.inputText);diff --git a/docs/guides/checking-your-resume.mdx b/docs/guides/checking-your-resume.mdxindex 6eb380865..14716b04a 100644--- a/docs/guides/checking-your-resume.mdx+++ b/docs/guides/checking-your-resume.mdx@@ -236,6 +236,8 @@ The checks are mechanical. The **Writing** tab asks an AI model how a reader migThe latest Writing review is saved with its input and review time. It remains readable after reload or when its provider is off. If the resume has changed, the review is marked out of date; original passages and suggestions remain visible. Review again before applying an out-of-date suggestion. Issues and Job match remain available without AI.+Accepting a rewrite keeps that saved review's recorded AI sources with the resume, visible in **History** on web and mobile. Undo restores the previous wording and sources together. Saving, reopening, Undo and accepting the same saved rewrite again do not run another review. Older reviews without recorded sources remain usable with unknown request history.+<Frame caption="A saved Writing review remains available with its provider off."><imgsrc="/images/guides/checking-your-resume/rx98-saved-writing.png"diff --git a/docs/guides/using-ai.mdx b/docs/guides/using-ai.mdxindex 9b3173d6b..f45039b5e 100644--- a/docs/guides/using-ai.mdx+++ b/docs/guides/using-ai.mdx@@ -196,6 +196,15 @@ Reviewed AI PDF and Word imports retain their sources in resume **History** on w**Improve** shows the reviewed suggestion's recorded attempts, original connection and model. **Replace** keeps those sources with the edited resume or letter; **Keep mine** leaves the document unchanged. Undo and Redo carry the sources with the accepted wording, including a suggestion with identical wording. Earlier import or draft sources remain. Saving, recovery, Undo and Redo never generate again; the weekly report still counts the original attempt if you discard or undo its result. Older-server suggestions remain usable with unknown request history.+Accepting an assistant edit or a **Writing** rewrite also keeps the saved result's recorded sources with the document. Pending, rejected and out-of-date edits add no sources. Undo restores the earlier content and sources; accepting again reuses the recorded result. If several accepted edits share one reply, undoing only one keeps that reply's source for the others. These actions make no new provider request, and earlier records without sources remain unknown.++<Frame caption="History retains the accepted Writing review's original source after its fictional connection is deleted.">+ <img+ src="/images/guides/using-ai/accepted-writing-sources.png"+ alt="Resume History showing one AI request attempt from Fictional Review AI, OpenAI-compatible provider, review-main model, and the current and earlier saved versions."+ />+</Frame>+Renaming, changing or deleting a connection does not rewrite its historical labels or models. Usage remains readable without an active AI provider. Account export includes usage history, and deleting the account removes it. An older server without reporting shows an update/retry notice.## Which provider is useddiff --git a/docs/guides/using-the-assistant.mdx b/docs/guides/using-the-assistant.mdxindex 18bff658e..92d74a172 100644--- a/docs/guides/using-the-assistant.mdx+++ b/docs/guides/using-the-assistant.mdx@@ -170,6 +170,8 @@ Turn on **Knowledge** in the message box to let the assistant look up your switcAccepting shows a notification with the number of edits applied and **Undo**. You can also press <kbd>⌘</kbd> <kbd>Z</kbd> (<kbd>Ctrl</kbd> <kbd>Z</kbd>) like any other change, or use History to restore an earlier document. An edit you explicitly undo becomes pending again when its original passage is available, so you can accept it later. That decision is saved with the document, even if you close the assistant. If an unsaved decision is recovered after another tab or device saved a newer version, saving pauses for the usual conflict controls; matching text alone does not choose which decision to keep. See [Undoing changes and version history](/guides/undoing-changes-and-version-history).+Accepted edits keep the reply's recorded AI request sources with your resume or letter, including through save, recovery and Undo. Other accepted edits from the same reply keep their source when you undo just one. Pending or rejected edits add none. Connection changes or deletion do not rewrite the original provider and model; accepting a saved edit makes no new AI request. See [AI usage](/guides/using-ai#see-your-ai-usage).+## Answer a questionWhen the assistant needs a fact or a choice from you, it shows a blue question card with a few answers. Select one, or type your own under **Or in your own words…** and select **Send**. The assistant then continues with your answer.diff --git a/docs/images/guides/using-ai/accepted-writing-sources.png b/docs/images/guides/using-ai/accepted-writing-sources.pngnew file mode 100644index 000000000..716b9b7d6Binary files /dev/null and b/docs/images/guides/using-ai/accepted-writing-sources.png differdiff --git a/docs/spec.json b/docs/spec.jsonindex 39730360c..5c4bc4ff3 100644--- a/docs/spec.json+++ b/docs/spec.json@@ -1838,6 +1838,15 @@"format": "date-time","x-native-type": "date"},+ "aiOperationIds": {+ "type": "array",+ "maxItems": 1000,+ "items": {+ "type": "string",+ "minLength": 1,+ "maxLength": 64+ }+ },"aiUsage": {"anyOf": [{diff --git a/packages/api/src/features/agent/proposal-applications.ts b/packages/api/src/features/agent/proposal-applications.tsindex d2ed89a2f..7283cb163 100644--- a/packages/api/src/features/agent/proposal-applications.ts+++ b/packages/api/src/features/agent/proposal-applications.ts@@ -2,10 +2,11 @@ import type { ProposedEdit, ProposeEditsOutput } from "@reactive-resume/ai/toolsimport type { DbOrTx } from "@reactive-resume/db/client";import type { ProposalApplications } from "@reactive-resume/resume/proposals";import type { UIMessage } from "ai";-import { and, asc, eq, isNull } from "drizzle-orm";+import { and, asc, eq, inArray, isNull, sql } from "drizzle-orm";import { tailoringAllows } from "@reactive-resume/ai/tools/agent-tool-contracts";import * as schema from "@reactive-resume/db/schema";import { appliedApplications, canApplyTo, holdsProposal } from "@reactive-resume/resume/proposals";+import { aiOperationIds, aiOperationIdsSchema } from "@reactive-resume/schema/ai-usage";import { parseStoredResumeData } from "../resume/resume-data-validation";import { lockThreadMessages, proposedEditsOf, withEditStatuses } from "./messages-persistence";@@ -19,6 +20,7 @@ export type DocumentReader = {kind: ProposalDocument["kind"];madeFor: string | null;pageLocale?: string;+ aiOperationIds?: string[];holds: (edit: HeldEdit) => boolean;};@@ -29,7 +31,11 @@ export async function documentReader(): Promise<DocumentReader | null> {if (document.kind === "resume") {const [row] = await tx- .select({ data: schema.resume.data, applicationId: schema.resume.applicationId })+ .select({+ data: schema.resume.data,+ applicationId: schema.resume.applicationId,+ aiOperationIds: schema.resume.aiOperationIds,+ }).from(schema.resume).where(and(eq(schema.resume.id, document.id), eq(schema.resume.userId, userId)));if (!row) return null;@@ -38,17 +44,19 @@ export async function documentReader(kind: "resume",madeFor: row.applicationId,pageLocale: data.metadata.page.locale,+ aiOperationIds: row.aiOperationIds,holds: (edit) => holdsProposal(data, edit),};}const [row] = await tx- .select({ content: schema.coverLetter.content })+ .select({ content: schema.coverLetter.content, aiOperationIds: schema.coverLetter.aiOperationIds }).from(schema.coverLetter).where(and(eq(schema.coverLetter.id, document.id), eq(schema.coverLetter.userId, userId)));if (!row) return null;return {kind: "letter",madeFor: null,+ aiOperationIds: row.aiOperationIds,holds: (edit) =>!edit.snapshot && edit.target.field === "content" && canApplyTo(row.content, { before: edit.after }),};@@ -126,12 +134,17 @@ export async function saveProposalApplications(if (!input.applications || Object.keys(input.applications).length === 0) return;const threads = await documentThreads(tx, input.userId, input.document);let reader: DocumentReader | null | undefined;+ const beforeSources = new Set<string>();+ const afterSources = new Set<string>();for (const thread of threads) {const rows = await lockThreadMessages(tx, { threadId: thread.id, userId: input.userId });let accepted = 0;for (const row of rows) {const original = row.uiMessage as unknown as UIMessage;if (!Array.isArray(original?.parts)) continue;+ const sources = row.role === "assistant" ? aiOperationIds(original.metadata) : [];+ if (proposedEditsOf(original).some((edit) => edit.status === "accepted"))+ for (const id of sources) beforeSources.add(id);const decisions = new Map<string, "accepted" | "pending">();for (const output of proposalSets(original)) {for (const edit of output.edits) {@@ -146,6 +159,8 @@ export async function saveProposalApplications(}}const message = withEditStatuses(original, null, decisions);+ if (proposedEditsOf(message).some((edit) => edit.status === "accepted"))+ for (const id of sources) afterSources.add(id);if (decisions.size > 0)await tx.update(schema.agentMessage)@@ -158,6 +173,35 @@ export async function saveProposalApplications(.set({ editsAccepted: accepted }).where(and(eq(schema.agentThread.id, thread.id), eq(schema.agentThread.userId, input.userId)));}+ const candidates = [...new Set([...beforeSources, ...afterSources])];+ if (!candidates.length) return;+ // Only this account's actual assistant attempts can supply saved-result provenance; old messages remain unknown.+ const attempts = await tx+ .select({ id: schema.aiRequest.operationId })+ .from(schema.aiRequest)+ .where(+ and(+ eq(schema.aiRequest.userId, input.userId),+ inArray(schema.aiRequest.operationId, candidates),+ inArray(schema.aiRequest.action, ["assistant", "career-chat"]),+ ),+ );+ const recorded = new Set(attempts.map((row) => row.id));+ reader ??= await documentReader(tx, input.userId, input.document);+ if (!reader) throw input.conflict();+ const removed = new Set([...beforeSources].filter((id) => recorded.has(id) && !afterSources.has(id)));+ const current = reader.aiOperationIds ?? [];+ const next = aiOperationIdsSchema.parse(+ [...new Set([...current, ...[...afterSources].filter((id) => recorded.has(id))])].filter((id) => !removed.has(id)),+ );+ if (JSON.stringify(next) === JSON.stringify(current)) return current;+ const table = input.document.kind === "resume" ? schema.resume : schema.coverLetter;+ // Receipt, wording and sources share the caller's revision; this metadata write must not create another revision.+ await tx+ .update(table)+ .set({ aiOperationIds: next, updatedAt: sql`${table.updatedAt}` })+ .where(and(eq(table.id, input.document.id), eq(table.userId, input.userId)));+ return next;}/** A content save from a client without proposalSafety, to a document whose edits an older app could apply wrongly. */diff --git a/packages/api/src/features/agent/service.test.ts b/packages/api/src/features/agent/service.test.tsindex cb5346911..ada6eb233 100644--- a/packages/api/src/features/agent/service.test.ts+++ b/packages/api/src/features/agent/service.test.ts@@ -826,7 +826,7 @@ describe("agentService.messages.send", () => {uiMessage: {id: "ui-assistant-1",role: "assistant",- metadata: { provider: "gemini", model: "gemini-3.8-flash" },+ metadata: { provider: "gemini", model: "gemini-3.8-flash", aiOperationIds: ["prior-operation"] },parts: [{type: "tool-ask_user_question",@@ -846,7 +846,7 @@ describe("agentService.messages.send", () => {};const answeredAssistantModelInput = {...unansweredAssistantMessage.uiMessage,- metadata: { provider: "gemini", model: "gemini-3.8-flash" },+ metadata: { provider: "gemini", model: "gemini-3.8-flash", aiOperationIds: ["prior-operation"] },parts: [{type: "tool-ask_user_question",@@ -990,9 +990,14 @@ describe("agentService.messages.send", () => {const { getAgentModel } = await import("../ai/service");expect(vi.mocked(getAgentModel).mock.calls.at(-1)?.[0]).toMatchObject({ model: provider.capableModel });const messageMetadata = uiStreamOptions?.messageMetadata as (event: { part: { type: string } }) => unknown;+ const usage = vi.mocked(getAgentModel).mock.calls.at(-1)?.[0].usage;+ expect(messageMetadata({ part: { type: "start" } })).toEqual({+ aiOperationIds: ["prior-operation", usage?.operationId],+ });expect(messageMetadata({ part: { type: "finish" } })).toMatchObject({provider: provider.provider,model: provider.capableModel,+ aiOperationIds: ["prior-operation", usage?.operationId],});const continuedMessage = {...answeredAssistantMessage.uiMessage,diff --git a/packages/api/src/features/agent/service.ts b/packages/api/src/features/agent/service.tsindex 3b355a400..0c866a85c 100644--- a/packages/api/src/features/agent/service.ts+++ b/packages/api/src/features/agent/service.ts@@ -1813,6 +1813,7 @@ export const agentService = {throw new ORPCError("CONFLICT", { message: "Shared context changed. Start a new reply." });},);+ const operationIds = [...new Set([...aiOperationIds(draftUiMessage.metadata), usage.operationId])];const agent = createAgent({authorize: async () => {controller.signal.throwIfAborted();@@ -1914,7 +1915,7 @@ export const agentService = {...(draftUiMessage.metadata as Record<string, unknown> | undefined),provider: runnableProvider.provider,model: capableModel,- aiOperationIds: [...new Set([...aiOperationIds(draftUiMessage.metadata), usage.operationId])],+ aiOperationIds: operationIds,},};const upserted = await upsertAssistantUiMessage({@@ -1942,16 +1943,18 @@ export const agentService = {sendSources: true,// Round-trips inside the persisted uiMessage jsonb — no migration needed.messageMetadata: ({ part }) =>- part.type === "finish"- ? {- usage: part.totalUsage,- model: capableModel,- aiOperationIds: [usage.operationId],- provider: runnableProvider.provider,- contextScope,- contextMessageId,- }- : undefined,+ part.type === "start"+ ? { aiOperationIds: operationIds }+ : part.type === "finish"+ ? {+ usage: part.totalUsage,+ model: capableModel,+ aiOperationIds: operationIds,+ provider: runnableProvider.provider,+ contextScope,+ contextMessageId,+ }+ : undefined,onFinish: async ({ responseMessage: completedMessage, isAborted, outcome }) => {let responseMessage = completedMessage;let persistError: unknown;diff --git a/packages/api/src/features/ai/router.ts b/packages/api/src/features/ai/router.tsindex a4a87176f..48cfc2390 100644--- a/packages/api/src/features/ai/router.ts+++ b/packages/api/src/features/ai/router.ts@@ -97,6 +97,7 @@ export const aiRouter = {passages: z.array(z.object({ id: z.string(), where: z.string(), text: z.string() })),review: atsReviewOutputSchema,reviewedAt: z.date(),+ aiOperationIds: aiOperationIdsSchema.optional(),aiUsage: aiUsageSummarySchema.nullable().optional(),}).nullable(),diff --git a/packages/api/src/features/ai/usage.integration.test.ts b/packages/api/src/features/ai/usage.integration.test.tsindex 665ad1ed9..0c101875b 100644--- a/packages/api/src/features/ai/usage.integration.test.ts+++ b/packages/api/src/features/ai/usage.integration.test.ts@@ -1,3 +1,4 @@+import type { ProposeEditsOutput } from "@reactive-resume/ai/tools/agent-tool-contracts";import type { AddressInfo } from "node:net";import { randomUUID } from "node:crypto";import { readdir, readFile } from "node:fs/promises";@@ -10,8 +11,12 @@ import { Pool } from "pg";import { z } from "zod";import { db, withDatabasePool } from "@reactive-resume/db/client";import * as tables from "@reactive-resume/db/schema";+import { aiOperationIds } from "@reactive-resume/schema/ai-usage";import { sampleResumeData } from "@reactive-resume/schema/resume/sample";import { buildAccountZip } from "@reactive-resume/utils/account-zip";+import { loadDocument } from "../agent/document";+import { upsertAssistantUiMessage } from "../agent/messages-persistence";+import { agentRouter } from "../agent/router";import { aiProvidersService } from "../ai-providers/service";import { authRouter } from "../auth/router";import { authService } from "../auth/service";@@ -56,7 +61,10 @@ describe.skipIf(!databaseUrl)("AI request metering through installed SDK, protec| "answer"| "writing"| "resume"+ | "agent"| "improve";+ let agentChanges: unknown[] = [];+ let agentStep = 0;let release = () => {};let arrived = () => {};let requests: { model: string; path: string }[] = [];@@ -79,6 +87,39 @@ describe.skipIf(!databaseUrl)("AI request metering through installed SDK, protecres.end(JSON.stringify({ error: { message: "Synthetic provider failure" } }));return;}+ if (mode === "agent") {+ const step = agentStep++;+ if (step === 2)+ await new Promise<void>((resolve) => {+ release = resolve;+ });+ res.writeHead(200, { "content-type": "text/event-stream" });+ const delta =+ step < 2+ ? {+ tool_calls: [+ {+ index: 0,+ id: `agent-call-${step}`,+ type: "function",+ function: {+ name: step === 0 ? "read_resume" : "propose_edits",+ arguments: JSON.stringify(+ step === 0 ? {} : { title: "Fictional rewrite", changes: agentChanges },+ ),+ },+ },+ ],+ }+ : { content: "Fictional proposal ready." };+ res.write(+ `data: ${JSON.stringify({ id: "agent", created: 1, model: body.model, choices: [{ index: 0, delta, finish_reason: null }] })}\n\n`,+ );+ res.end(+ `data: ${JSON.stringify({ id: "agent", created: 1, model: body.model, choices: [{ index: 0, delta: {}, finish_reason: step < 2 ? "tool_calls" : "stop" }] })}\n\ndata: [DONE]\n\n`,+ );+ return;+ }if (mode === "stream") {res.writeHead(200, { "content-type": "text/event-stream" });for (let index = 0; index < 50; index++)@@ -151,6 +192,7 @@ describe.skipIf(!databaseUrl)("AI request metering through installed SDK, protecletters: coverLettersRouter,resume: resumeRouter,documents: documentsRouter,+ agent: agentRouter,},{context: {@@ -160,9 +202,9 @@ describe.skipIf(!databaseUrl)("AI request metering through installed SDK, protec},},);- const provider = async () => {+ const provider = async (ownerId = user.id) => {const created = await aiProvidersService.create({- userId: user.id,+ userId: ownerId,label: "Fictional connection",provider: "openai-compatible",model: "main-model",@@ -172,7 +214,7 @@ describe.skipIf(!databaseUrl)("AI request metering through installed SDK, protecapiKey: "synthetic-key-207",});await pool.query("update ai_providers set enabled=true,test_status='success' where id=$1", [created.id]);- return aiProvidersService.getRunnableById({ userId: user.id, id: created.id });+ return aiProvidersService.getRunnableById({ userId: ownerId, id: created.id });};beforeAll(async () => {await admin.query(`create schema ${namespace}`);@@ -192,6 +234,8 @@ describe.skipIf(!databaseUrl)("AI request metering through installed SDK, protecrelease();arrived = () => {};requests = [];+ agentStep = 0;+ agentChanges = [];mode = "text";await pool.query('truncate "user" cascade');await withDatabasePool(pool, async () => {@@ -574,6 +618,222 @@ describe.skipIf(!databaseUrl)("AI request metering through installed SDK, protecexpect(requests).toHaveLength(1);}));+ it.each(["finish", "stop"] as const)(+ "accepts a real streamed proposal before %s with the same recorded sources in live metadata and storage",+ (ending) =>+ run(async () => {+ const connection = await provider();+ const api = client();+ const data = structuredClone(sampleResumeData);+ data.summary.content = "<p>Original fictional summary.</p>";+ const id = await api.resume.import({ data });+ const loaded = await loadDocument(user.id, { kind: "resume", id });+ const passage = loaded.passages.find((entry) => entry.target.sectionId === "summary");+ if (!passage) throw new Error("Missing fictional summary passage");+ agentChanges = [+ {+ kind: "text",+ sectionId: "summary",+ passageId: passage.id,+ text: "Led fictional delivery work.",+ why: "Clearer wording",+ },+ ];+ const thread = await api.agent.threads.start({ resumeId: id });+ mode = "agent";+ const held = new Promise<void>((resolve) => {+ arrived = () => {+ if (requests.length === 3) resolve();+ };+ });+ const stream = await api.agent.messages.send({+ threadId: thread.id,+ message: {+ id: randomUUID(),+ role: "user",+ parts: [{ type: "text", text: "Rewrite the summary for clarity without adding facts." }],+ },+ context: { document: true, posting: false, memory: false },+ });+ const chunks: Record<string, unknown>[] = [];+ const finished = (async () => {+ for await (const frame of stream)+ for (const line of frame.split("\n"))+ if (line.startsWith("data: ") && line !== "data: [DONE]") chunks.push(JSON.parse(line.slice(6)));+ })();+ try {+ await held;+ const sources = aiOperationIds(chunks.find((chunk) => chunk.type === "start")?.messageMetadata);+ expect(sources).toEqual([expect.any(String)]);+ const stored = await api.agent.threads.get({ id: thread.id });+ const message = stored.messages.find((entry) => entry.role === "assistant");+ expect(aiOperationIds(message?.metadata)).toEqual(sources);+ const output = message?.parts.find((part) => part.type === "tool-propose_edits") as+ | { output?: ProposeEditsOutput }+ | undefined;+ const edit = output?.output?.edits[0];+ if (!edit) throw new Error("Missing real streamed proposal");+ const current = await api.resume.getById({ id });+ const accepted = await api.resume.update({+ id,+ expectedUpdatedAt: current.updatedAt,+ data: { ...current.data, summary: { ...current.data.summary, content: edit.after } },+ proposalApplications: { [edit.id]: edit.after },+ proposalSafety: "v1",+ });+ expect(accepted.aiOperationIds).toEqual(sources);+ expect(accepted.aiUsage).toMatchObject({+ requests: 3,+ models: [expect.objectContaining({ providerId: connection.id, model: "capable-model" })],+ });+ if (ending === "stop") await api.agent.messages.stop({ threadId: thread.id });+ } finally {+ release();+ await finished;+ }+ const sources = aiOperationIds(chunks.find((chunk) => chunk.type === "start")?.messageMetadata);+ if (ending === "finish")+ expect(aiOperationIds(chunks.find((chunk) => chunk.type === "finish")?.messageMetadata)).toEqual(sources);+ const stored = await api.agent.threads.get({ id: thread.id });+ const message = stored.messages.find((entry) => entry.role === "assistant");+ expect(aiOperationIds(message?.metadata)).toEqual(sources);+ expect(+ (+ message?.parts.find((part) => part.type === "tool-propose_edits") as+ | { output?: ProposeEditsOutput }+ | undefined+ )?.output?.edits[0]?.status,+ ).toBe("accepted");+ expect((await api.resume.getById({ id })).aiOperationIds).toEqual(sources);+ expect(requests).toHaveLength(3);+ }),+ );++ it.each(["resume", "letter"] as const)(+ "%s accepted assistant sources preserve prior lineage, partial decisions and older clients",+ (kind) =>+ run(async () => {+ const connection = await provider();+ const priorUsage = createAiUsage(user.id, "improve", connection);+ await generateText({ model: getModel({ ...connection, usage: priorUsage }), prompt: "Fictional prior source" });+ const foreignConnection = await provider("usage-bob");+ const foreignUsage = createAiUsage("usage-bob", "assistant", foreignConnection);+ await generateText({+ model: getModel({ ...foreignConnection, usage: foreignUsage }),+ prompt: "Fictional other account",+ });+ const usage = createAiUsage(user.id, "assistant", connection);+ await generateText({ model: getModel({ ...connection, usage }), prompt: "Fictional source fixture" });+ const api = client();+ const data = structuredClone(sampleResumeData);+ const first = "<p>Original fictional summary.</p>";+ const second = "<p>Second fictional paragraph.</p>";+ const after = "<p>Led fictional delivery work.</p>";+ const afterSecond = "<p>Built fictional reporting tools.</p>";+ data.summary.content = first + second;+ const id =+ kind === "resume"+ ? await api.resume.import({ data, aiOperationIds: [priorUsage.operationId] })+ : (await api.letters.create({ name: "Fictional proposal letter", content: first + second })).id;+ if (kind === "letter") {+ const letter = await api.letters.getById({ id });+ await api.letters.update({+ id,+ content: letter.content,+ aiOperationIds: [priorUsage.operationId],+ expectedRevision: letter.revision,+ });+ }+ const [thread] = await db+ .insert(tables.agentThread)+ .values({+ userId: user.id,+ ...(kind === "resume" ? { workingResumeId: id, sourceResumeId: id } : { coverLetterId: id }),+ title: "Fictional proposal source",+ })+ .returning();+ if (!thread) throw new Error("Missing fixture thread");+ await upsertAssistantUiMessage({+ userId: user.id,+ threadId: thread.id,+ status: "completed",+ message: {+ id: "fictional-assistant",+ role: "assistant",+ metadata: {+ aiOperationIds: [usage.operationId, foreignUsage.operationId, priorUsage.operationId, "fabricated-op"],+ },+ parts: [+ {+ type: "tool-propose_edits",+ toolCallId: "fictional-edit-call",+ state: "output-available",+ input: {},+ output: {+ tailoredFor: null,+ edits: [+ {+ id: "fictional-edit",+ status: "pending",+ target: { sectionId: kind === "resume" ? "summary" : "letter", field: "content" },+ location: "Summary",+ before: first,+ after,+ why: "Fictional rewrite",+ },+ {+ id: "second-edit",+ status: "pending",+ target: { sectionId: kind === "resume" ? "summary" : "letter", field: "content" },+ location: "Summary",+ before: second,+ after: afterSecond,+ why: "Fictional second rewrite",+ },+ ],+ },+ },+ ],+ },+ });+ const save = async (content: string, applications: Record<string, string | boolean>) => {+ if (kind === "resume") {+ const current = await api.resume.getById({ id });+ return api.resume.update({+ id,+ data: { ...current.data, summary: { ...current.data.summary, content } },+ expectedUpdatedAt: current.updatedAt,+ proposalApplications: applications,+ proposalSafety: "v1",+ });+ }+ const current = await api.letters.getById({ id });+ return api.letters.update({+ id,+ content,+ expectedRevision: current.revision,+ proposalApplications: applications,+ proposalSafety: "v1",+ });+ };+ const accepted = await save(after + second, { "fictional-edit": after });+ expect(accepted.aiOperationIds).toEqual([priorUsage.operationId, usage.operationId]);+ expect(accepted.aiUsage).toMatchObject({+ requests: 2,+ models: [expect.objectContaining({ providerId: connection.id, model: connection.model })],+ });+ await save(after + afterSecond, { "second-edit": afterSecond });+ const partial = await save(first + afterSecond, { "fictional-edit": false });+ expect(partial.aiOperationIds).toEqual([priorUsage.operationId, usage.operationId]);+ const undone = await save(first + second, { "second-edit": false });+ expect(undone.aiOperationIds).toEqual([priorUsage.operationId]);+ const redone = await save(after + second, { "fictional-edit": after });+ expect(redone.aiOperationIds).toEqual([priorUsage.operationId, usage.operationId]);+ await api.ai.usage();+ expect(requests).toHaveLength(3);+ }),+ );+it("returns opt-in Improve sources from actual transport records while preserving the default result contract", () =>run(async () => {const connection = await provider();@@ -896,6 +1156,7 @@ describe.skipIf(!databaseUrl)("AI request metering through installed SDK, protec});const writing = await client(["read"]).ai.writingReview({ resumeId: resume.id });expect(writing?.review.summary).toBe("Fictional saved wording review");+ expect(writing?.aiOperationIds).toEqual([expect.any(String)]);expect(writing?.aiUsage).toEqual(saved[0]?.aiUsage);await aiProvidersService.update({ userId: user.id, id: connection.id, label: "Renamed", model: "replacement" });await aiProvidersService.delete({ userId: user.id, id: connection.id });@@ -903,6 +1164,9 @@ describe.skipIf(!databaseUrl)("AI request metering through installed SDK, protecsaved[0]?.aiUsage,);expect((await client(["read"]).ai.writingReview({ resumeId: resume.id }))?.aiUsage).toEqual(writing?.aiUsage);+ expect((await client(["read"]).ai.writingReview({ resumeId: resume.id }))?.aiOperationIds).toEqual(+ writing?.aiOperationIds,+ );const report = await client(["read"]).ai.usage({ userId: "usage-bob" } as {});expect(report.requests).toBe(2);expect(report.groups[0]).toMatchObject({ action: "reply", label: "Fictional connection", model: "main-model" });diff --git a/packages/api/src/features/ai/writing-review.ts b/packages/api/src/features/ai/writing-review.tsindex bea948644..7683f4adb 100644--- a/packages/api/src/features/ai/writing-review.ts+++ b/packages/api/src/features/ai/writing-review.ts@@ -27,6 +27,7 @@ export async function readWritingReview(userId: string, resumeId: string) {passages: row.passages,review: atsReviewOutputSchema.parse(row.review),reviewedAt: row.reviewedAt,+ aiOperationIds: row.aiOperationId ? [row.aiOperationId] : [],aiUsage: row.aiOperationId ? await readAiUsage(userId, [row.aiOperationId]) : null,}: null;diff --git a/packages/api/src/features/cover-letters/service.ts b/packages/api/src/features/cover-letters/service.tsindex 6ec52e3b4..ec2348a60 100644--- a/packages/api/src/features/cover-letters/service.ts+++ b/packages/api/src/features/cover-letters/service.ts@@ -692,12 +692,13 @@ export const coverLetterService = {changes.aiOperationIds = [...new Set(input.aiOperationIds)];}const updated = await updateRevision(input, changes, client, { proposalSafety: input.proposalSafety });- await saveProposalApplications(client, {+ const sourceIds = await saveProposalApplications(client, {userId: input.userId,document: { kind: "letter", id: input.id },applications: input.proposalApplications,conflict: letterConflict,});+ if (sourceIds !== undefined) updated.aiOperationIds = sourceIds;if (input.applicationId === null) {await linkLetterApplication(client, {userId: input.userId,diff --git a/packages/api/src/features/resume/service.ts b/packages/api/src/features/resume/service.tsindex 3db6db7bb..c42272cf7 100644--- a/packages/api/src/features/resume/service.ts+++ b/packages/api/src/features/resume/service.ts@@ -285,12 +285,13 @@ async function applyResumePatchTx(if (input.expectedUpdatedAt) throw resumeVersionConflict(existing.updatedAt);throw new ORPCError("NOT_FOUND");}- await saveProposalApplications(client, {+ const sourceIds = await saveProposalApplications(client, {userId: input.userId,document: { kind: "resume", id: input.id },applications: input.proposalApplications,conflict: () => resumeVersionConflict(existing.updatedAt),});+ if (sourceIds !== undefined) resume.aiOperationIds = sourceIds;// Checkpoint every patch (AI/API edit) atomically within the same transaction as the edit.// ponytail: a multi-patch agent turn writes one row per patch; 90-day retention bounds it.@@ -929,12 +930,13 @@ export const resumeService = {.returning(resumeColumns);if (!updated) throw new ORPCError("NOT_FOUND");- await saveProposalApplications(tx, {+ const sourceIds = await saveProposalApplications(tx, {userId: input.userId,document: { kind: "resume", id: input.id },applications: input.proposalApplications,conflict: () => resumeVersionConflict(existing.updatedAt),});+ if (sourceIds !== undefined) updated.aiOperationIds = sourceIds;return updated;}).catch(async (error: unknown) => {diff --git a/packages/resume/src/proposals.ts b/packages/resume/src/proposals.tsindex d9f2732dc..574c8ce07 100644--- a/packages/resume/src/proposals.ts+++ b/packages/resume/src/proposals.ts@@ -53,6 +53,8 @@ export type Proposal = {why: string;status: "pending" | "accepted" | "rejected";source: ProposalSource;+ /** Private request references from the saved result that proposed this edit, outside resume content. */+ aiOperationIds?: string[] | undefined;/** The posting requirement the edit addresses, when tailoring to a job. */requirement?: string | undefined;/** What the assistant cited for the edit, unverified. */@@ -321,6 +323,10 @@ export const appliedApplications = (applied.map((proposal) => [proposal.id, proposal.snapshot ? `snapshot:${proposal.id}` : proposal.after]),);+export const proposalAiOperationIds = (applied: readonly Pick<Proposal, "aiOperationIds">[]): string[] => [+ ...new Set(applied.flatMap((proposal) => proposal.aiOperationIds ?? [])),+];+/** Recovery data is untrusted; only own decisions are restored. */export function readProposalApplications(value: unknown): ProposalApplications {if (!value || typeof value !== "object" || Array.isArray(value)) return {};diff --git a/tests/e2e/specs/ai-usage.spec.ts b/tests/e2e/specs/ai-usage.spec.tsindex 0fdc84180..84a0342ba 100644--- a/tests/e2e/specs/ai-usage.spec.ts+++ b/tests/e2e/specs/ai-usage.spec.ts@@ -16,6 +16,96 @@ test.afterAll(async () => {await stub?.close();});+for (const kind of ["resume assistant", "letter assistant", "writing review"] as const)+ test(`${kind} acceptance pairs original sources with saved content and Undo without generating again`, async ({+ authPage: page,+ }, info) => {+ test.skip(process.env.FLAG_ALLOW_UNSAFE_AI_BASE_URL !== "true", "Needs isolated local AI stub permission");+ test.setTimeout(90_000);+ await page.setViewportSize({ width: 1440, height: 1000 });+ await approveLocalStubOperations(page);+ const connection = await page.request.post("/api/openapi/ai-providers", {+ data: {+ label: "Fictional Review AI",+ provider: "openai-compatible",+ model: "review-main",+ capableModel: "review-capable",+ baseURL: stub.baseURL,+ apiKey: "stub-key",+ },+ });+ await expect(connection).toBeOK();+ const { id: providerId } = await connection.json();+ await expect(await page.request.post(`/api/openapi/ai-providers/${providerId}/test`)).toBeOK();+ let id: string;+ if (kind === "letter assistant") {+ const created = await page.request.post("/api/openapi/cover-letters", {+ data: { name: "Fictional reviewed letter", content: "<p>Built fictional reliable services.</p>" },+ });+ await expect(created).toBeOK();+ id = (await created.json()).id;+ await page.goto(`/builder/letter/${id}`);+ } else {+ await createSampleResumeFromDashboard(page, info);+ id = new URL(page.url()).pathname.split("/").at(-1) ?? "";+ }+ const read = async () =>+ await (+ await page.request.get(`/api/openapi/${kind === "letter assistant" ? "cover-letters" : "resumes"}/${id}`)+ ).json();+ const original = await read();+ const before = stub.requests.length;+ if (kind === "writing review") {+ await page.getByRole("tab", { name: /^Check/ }).click();+ await page.getByRole("tab", { name: "Writing", exact: true }).click();+ await page.getByRole("button", { name: "Review writing", exact: true }).click();+ await expect(page.getByText("Fictional writing review retained after reload.")).toBeVisible();+ } else {+ await page.getByRole("button", { name: "Assistant", exact: true }).click();+ await page.getByLabel("Message the assistant").fill("Tighten the first passage without adding facts.");+ await page.getByRole("button", { name: "Send", exact: true }).last().click();+ }+ const edits = page.getByRole("list", { name: "Proposed edits" });+ await expect(edits).toBeVisible({ timeout: 20_000 });+ if (kind !== "writing review") await expect(page.getByRole("button", { name: "Stop", exact: true })).toBeHidden();+ expect((await read()).aiOperationIds).toEqual([]);+ const attempts = stub.requests.length - before;+ expect(attempts).toBe(kind === "writing review" ? 1 : 3);+ await edits.getByRole("button", { name: "Accept", exact: true }).click();+ await expect.poll(read).toMatchObject({ aiOperationIds: [expect.any(String)], aiUsage: { requests: attempts } });+ const accepted = await read();+ await page.locator('[data-slot="toast"]').getByRole("button", { name: "Undo", exact: true }).click();+ await expect.poll(read).toMatchObject({+ aiOperationIds: [],+ ...(kind === "letter assistant" ? { content: original.content } : { data: original.data }),+ });+ await expect(edits.getByRole("button", { name: "Accept", exact: true })).toBeVisible();+ await edits.getByRole("button", { name: "Accept", exact: true }).click();+ await expect.poll(read).toMatchObject({ aiOperationIds: accepted.aiOperationIds, aiUsage: accepted.aiUsage });+ await expect(await page.request.delete(`/api/openapi/ai-providers/${providerId}`)).toBeOK();+ await page.reload();+ expect((await read()).aiOperationIds).toEqual(accepted.aiOperationIds);+ if (kind === "letter assistant") {+ await expect(+ page+ .getByRole("region", { name: "Letter", exact: true })+ .getByText("Fictional Review AI · openai-compatible · review-capable", { exact: true }),+ ).toBeVisible();+ } else {+ await page.getByRole("button", { name: "History", exact: true }).click();+ const history = page.getByRole("dialog", { name: "Download & history" });+ await expect(history.getByText(`AI request attempts: ${attempts}`, { exact: true })).toBeVisible();+ await expect(+ history.getByText(+ `Fictional Review AI · openai-compatible · ${kind === "writing review" ? "review-main" : "review-capable"}`,+ { exact: true },+ ),+ ).toBeVisible();+ await history.screenshot({ path: info.outputPath("accepted-review-sources.png"), animations: "disabled" });+ }+ expect(stub.requests.length - before).toBe(attempts);+ });+test("reviewed resume Improve sources follow editor Undo/Redo, save and reload after provider deletion", async ({authPage: page,}, info) => {