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 reviewed Improve request sources
Amruth Pillaia684eeef2c95
diff --git a/apps/mobile/scripts/letter-draft-keep.test.mjs b/apps/mobile/scripts/letter-draft-keep.test.mjsindex 741d6de05..522c4b355 100644--- a/apps/mobile/scripts/letter-draft-keep.test.mjs+++ b/apps/mobile/scripts/letter-draft-keep.test.mjs@@ -252,6 +252,7 @@ test("native Stop retains partial request lineage through recovery without anothtest("letter body wires the shared Improve history step and owned posting into its draft store", () => {const f = fixture();const current = letter();+ current.aiOperationIds = ["original-source"];f.setDocument(current);f.draft.useLetterDrafting.setState({ owner: f.draft.letterDraftOwner(current.id), draft: { phase: "idle" } });const { BodySection } = loadWriteCaller(f);@@ -267,7 +268,9 @@ test("letter body wires the shared Improve history step and owned posting into iwalk(tree);assert.ok(field);assert.equal(field.props.applicationId, "owned-application");- field.props.onChange("<p>Reviewed paragraph</p>", { newStep: true });+ field.props.onChange("<p>Reviewed paragraph</p>", { newStep: true, aiOperationIds: ["reviewed-improve"] });assert.equal(current.content, "<p>Reviewed paragraph</p>");- assert.deepEqual(f.lastUpdate, { coalesceKey: "content", newStep: true });+ assert.deepEqual(current.aiOperationIds, ["original-source", "reviewed-improve"]);+ assert.equal(current.aiUsage, null);+ assert.deepEqual(f.lastUpdate, { coalesceKey: "content", newStep: true, aiOperationIds: ["reviewed-improve"] });});diff --git a/apps/mobile/scripts/letter-improve.test.mjs b/apps/mobile/scripts/letter-improve.test.mjsindex 09c9c2e42..b49fc4341 100644--- a/apps/mobile/scripts/letter-improve.test.mjs+++ b/apps/mobile/scripts/letter-improve.test.mjs@@ -51,7 +51,7 @@ const Button = ({ label, onPress, disabled }) => h("button", { onClick: onPress,const deps = {react: React,"react/jsx-runtime": req("react/jsx-runtime"),- "@lingui/react/macro": { useLingui: () => ({ t: tag }) },+ "@lingui/react/macro": { useLingui: () => ({ t: tag, i18n: { number: String } }) },"@lingui/core/macro": { plural: (count) => `${count} characters` },"react-native": { View, ScrollView },"react-native-enriched-html": { EnrichedTextInput: NativeInput },@@ -86,7 +86,7 @@ const deps = {isError: false,mutate(input) {fixture.requests.push(input);- setData({ text: "Reviewed replacement", why: "Fictional suggestion", addsFacts: false });+ setData(fixture.result);},reset() {setData(null);@@ -159,6 +159,16 @@ async function mount(props = {}) {letterFocus: 0,letterBlur: 0,resumeFocus: 0,+ result: {+ text: "Reviewed replacement",+ why: "Fictional suggestion",+ addsFacts: false,+ aiOperationIds: ["reviewed-improve"],+ aiUsage: {+ requests: 2,+ models: [{ label: "Fictional Review AI", provider: "openai-compatible", model: "actual-fast" }],+ },+ },read: () => Promise.resolve(fixture.html),};const onChange = (html, options) => fixture.writes.push({ html, options });@@ -199,6 +209,7 @@ for (const [action, label] of [assert.deepEqual(fixture.requests, [{aiProviderId: "fixture-provider",+ includeProvenance: true,action,line: "Original line",where: "Letter body",@@ -210,9 +221,36 @@ for (const [action, label] of [await act(async () => {fireEvent.click(screen.getByRole("button", { name: "Replace", exact: true }));});- assert.deepEqual(fixture.writes, [{ html: "<p>Reviewed replacement</p>", options: { newStep: true } }]);+ assert.deepEqual(fixture.writes, [+ { html: "<p>Reviewed replacement</p>", options: { newStep: true, aiOperationIds: ["reviewed-improve"] } },+ ]);+ assert.ok(+ screen.queryByText("Fictional Review AI · openai-compatible · actual-fast") === null,+ "accepted panel closes",+ );});}+test("Improve review displays actual result model and attempts; Keep mine adds no sources", async () => {+ await mount();+ await choose("Warmer");+ assert.ok(screen.getByText("AI request attempts: 2"));+ assert.ok(screen.getByText("Fictional Review AI · openai-compatible · actual-fast"));+ assert.equal(fixture.writes.length, 0);+ await act(async () => fireEvent.click(screen.getByRole("button", { name: "Keep mine" })));+ assert.equal(fixture.writes.length, 0);+ assert.equal(fixture.requests.length, 1);+});+test("source-less older Improve response stays usable without repeating generation", async () => {+ await mount();+ fixture.result = { text: "Reviewed replacement", why: "Older server", addsFacts: false };+ await choose("Warmer");+ assert.ok(screen.getByText("AI request history unavailable for this result."));+ await act(async () => fireEvent.click(screen.getByRole("button", { name: "Replace", exact: true })));+ assert.deepEqual(fixture.writes, [+ { html: "<p>Reviewed replacement</p>", options: { newStep: true, aiOperationIds: undefined } },+ ]);+ assert.equal(fixture.requests.length, 1);+});test("standalone letter exposes warmer/shorter but no posting or resume-only presets", async () => {await mount();await act(async () => {@@ -300,5 +338,5 @@ test("two captured Replace presses commit one reviewed history step", async () =held.resolve("<p>Original line</p>");});assert.equal(fixture.writes.length, 1);- assert.deepEqual(fixture.writes[0].options, { newStep: true });+ assert.deepEqual(fixture.writes[0].options, { newStep: true, aiOperationIds: ["reviewed-improve"] });});diff --git a/apps/mobile/scripts/proposal-sync.test.mjs b/apps/mobile/scripts/proposal-sync.test.mjsindex 44cc7cca0..abce16632 100644--- a/apps/mobile/scripts/proposal-sync.test.mjs+++ b/apps/mobile/scripts/proposal-sync.test.mjs@@ -41,6 +41,7 @@ let fail = false;let blocked = false;let scope = "https://review.invalid:alice";let responseGate = null;+let requestDispatched = null;// The server's answer to an unchecked content save on a document an older app could edit wrongly.let refuseUnchecked = false;const { ORPCError } = await import("@orpc/client");@@ -49,6 +50,7 @@ function network(kind) {getById: async () => structuredClone(documents[kind]),update: async (input) => {requests.push(structuredClone({ kind, input }));+ requestDispatched?.();if (responseGate) await responseGate;if (fail) throw new Error("offline");if (refuseUnchecked && !input.proposalSafety)@@ -102,6 +104,7 @@ function setup(kind) {refuseUnchecked = false;scope = "https://review.invalid:alice";responseGate = null;+ requestDispatched = null;const now = new Date("2026-10-31T00:00:00Z");const data = structuredClone(fixtures.defaultResumeData);data.summary.content = proposal.before;@@ -179,6 +182,76 @@ function accept(s, kind) {);}for (const kind of ["resume", "letter"]) {+ for (const sameWords of [false, true]) {+ test(`${kind} reviewed Improve sources survive inflight Undo/Redo (same wording=${sameWords})`, async () => {+ const { owner } = setup(kind);+ documents[kind].aiOperationIds = ["original-source"];+ const o = owner();+ const s = o.store.getState;+ await s().open(kind);+ s().update(+ (draft) => {+ if (kind === "resume") draft.summary.content = sameWords ? proposal.before : proposal.after;+ else draft.content = sameWords ? proposal.before : proposal.after;+ },+ { newStep: true, aiOperationIds: ["reviewed-improve"] },+ );+ assert.deepEqual(s().document.aiOperationIds, ["original-source", "reviewed-improve"]);+ let release;+ responseGate = new Promise((resolve) => {+ release = resolve;+ });+ const dispatched = new Promise((resolve) => {+ requestDispatched = resolve;+ });+ const writing = s().flush();+ await dispatched;+ s().undo();+ assert.deepEqual(s().document.aiOperationIds, ["original-source"]);+ responseGate = null;+ release();+ await writing;+ assert.deepEqual(+ requests.map((r) => r.input.aiOperationIds),+ [["original-source", "reviewed-improve"], ["original-source"]],+ );+ assert.deepEqual(documents[kind].aiOperationIds, ["original-source"]);+ assert.equal(kind === "resume" ? documents[kind].data.summary.content : documents[kind].content, proposal.before);+ s().redo();+ await s().flush();+ assert.deepEqual(documents[kind].aiOperationIds, ["original-source", "reviewed-improve"]);+ assert.equal(+ kind === "resume" ? documents[kind].data.summary.content : documents[kind].content,+ sameWords ? proposal.before : proposal.after,+ );+ });+ test(`${kind} failed Improve save recovers sources with content (same wording=${sameWords})`, async () => {+ const { owner } = setup(kind);+ documents[kind].aiOperationIds = ["original-source"];+ const first = owner();+ await first.store.getState().open(kind);+ first.store.getState().update(+ (draft) => {+ if (kind === "resume") draft.summary.content = sameWords ? proposal.before : proposal.after;+ else draft.content = sameWords ? proposal.before : proposal.after;+ },+ { newStep: true, aiOperationIds: ["reviewed-improve"] },+ );+ fail = true;+ await first.store.getState().flush();+ await first.store.getState().close();+ const reopened = owner();+ await reopened.store.getState().open(kind);+ assert.deepEqual(reopened.store.getState().document.aiOperationIds, ["original-source", "reviewed-improve"]);+ fail = false;+ await reopened.store.getState().flush();+ assert.deepEqual(documents[kind].aiOperationIds, ["original-source", "reviewed-improve"]);+ assert.equal(+ kind === "resume" ? documents[kind].data.summary.content : documents[kind].content,+ sameWords ? proposal.before : proposal.after,+ );+ });+ }test(`${kind} refresh must honor newer remote Undo receipt`, async () => {const { owner } = setup(kind);const o = owner();diff --git a/apps/mobile/src/draft/adapters.ts b/apps/mobile/src/draft/adapters.tsindex 816caab0d..3a8ea4925 100644--- a/apps/mobile/src/draft/adapters.ts+++ b/apps/mobile/src/draft/adapters.ts@@ -4,6 +4,7 @@ import type { RouterInput } from "@/api/client";import { t } from "@lingui/core/macro";import { ORPCError } from "@orpc/client";import { produce } from "immer";+import { aiOperationIdsSchema } from "@reactive-resume/schema/ai-usage";import { coverLetterSchema } from "@reactive-resume/schema/cover-letter/data";import { resumeDataSchema } from "@reactive-resume/schema/resume/data";import { syncResumeDates } from "@reactive-resume/schema/resume/dates";@@ -23,6 +24,7 @@ function resumeFields(document: ResumeDocument) {isPublic: document.isPublic,showDownloadButtons: document.showDownloadButtons,data: document.data,+ aiOperationIds: document.aiOperationIds ?? [],};}@@ -72,6 +74,7 @@ export const resumeAdapter: DraftAdapter<ResumeDocument, ResumeDocument["data"]>...changedFields(resumeFields(current), resumeFields(submitted)),// Keep authored data and its references stable across the server's normalized echo.data: current.data,+ ...(JSON.stringify(saved.aiOperationIds) !== JSON.stringify(current.aiOperationIds) ? { aiUsage: null } : {}),}),parse: (value) => {const document = dates(value) as ResumeDocument;@@ -87,6 +90,10 @@ export const resumeAdapter: DraftAdapter<ResumeDocument, ResumeDocument["data"]>!Number.isFinite(document.updatedAt.getTime()))throw new Error("Invalid stored resume.");+ if (document.aiOperationIds !== undefined && !aiOperationIdsSchema.safeParse(document.aiOperationIds).success) {+ delete document.aiOperationIds;+ document.aiUsage = null;+ }return { ...document, data: resumeDataSchema.parse(document.data) };},save: async (document, baseline, sessionId, force, scope, proposalApplications, proposalSafety) => ({@@ -95,6 +102,9 @@ export const resumeAdapter: DraftAdapter<ResumeDocument, ResumeDocument["data"]>{id: document.id,...changedFields(resumeFields(document), resumeFields(baseline)),+ ...(JSON.stringify(document.aiOperationIds ?? []) !== JSON.stringify(baseline.aiOperationIds ?? [])+ ? { data: document.data }+ : {}),sessionId,// Only for drafts this app kept (see the draft store's proposalSafety)....(proposalSafety ? { proposalSafety } : {}),diff --git a/apps/mobile/src/draft/store.ts b/apps/mobile/src/draft/store.tsindex b8623c980..b00cf68e7 100644--- a/apps/mobile/src/draft/store.ts+++ b/apps/mobile/src/draft/store.ts@@ -1,5 +1,6 @@import type { DraftStore, UpdateOptions } from "./types";import type { ProposalApplications, ProposalSnapshot } from "@reactive-resume/resume/proposals";+import type { AiUsageSummary } from "@reactive-resume/schema/ai-usage";import type { WritableDraft } from "immer";import { produce } from "immer";import { create } from "zustand";@@ -12,7 +13,13 @@ import {} from "@reactive-resume/resume/proposals";import { generateId } from "@reactive-resume/utils/string";-type Document = { id: string; isLocked: boolean };+type Document = {+ id: string;+ isLocked: boolean;+ aiOperationIds?: string[] | undefined;+ aiUsage?: AiUsageSummary | null | undefined;+};+type Snapshot<T> = ProposalSnapshot<T> & Pick<Document, "aiOperationIds" | "aiUsage">;type Record<D> = {baseline: D;document: D;@@ -99,8 +106,8 @@ export function createDraftStore<D extends Document, T>(adapter: DraftAdapter<D,let replaying: Promise<void> | null = null;let resolving = false;let force = false;- let undo: ProposalSnapshot<T>[] = [];- let redo: ProposalSnapshot<T>[] = [];+ let undo: Snapshot<T>[] = [];+ let redo: Snapshot<T>[] = [];let last: { at: number; key: string | undefined; coalesce: boolean } | null = null;const prefix = (owner: string) => `reactive-resume:unsaved:${encodeURIComponent(owner)}:${adapter.kind}:`;const key = () => {@@ -120,6 +127,12 @@ export function createDraftStore<D extends Document, T>(adapter: DraftAdapter<D,flush,}));const state = store.getState;+ const checkpoint = (document: D): Snapshot<T> => ({+ data: adapter.data(document),+ applications: state().proposalApplications,+ aiOperationIds: document.aiOperationIds ?? [],+ aiUsage: document.aiUsage,+ });function publish(document: D, proposalApplications: ProposalApplications = state().proposalApplications) {store.setState({ document, data: adapter.data(document), locked: document.isLocked, proposalApplications });@@ -353,21 +366,35 @@ export function createDraftStore<D extends Document, T>(adapter: DraftAdapter<D,if (!record || state().locked || resolving) return;const before = adapter.data(record.document);const next = produce(before, recipe);- if (next === before) return;+ const existingSources = record.document.aiOperationIds ?? [];+ const newSources = options.aiOperationIds?.some((id) => !existingSources.includes(id));+ if (next === before && !newSources) return;const now = Date.now();const coalesce =!options.newStep &&last?.coalesce &&last.key === options.coalesceKey &&((options.sameStep && options.coalesceKey !== undefined) || now - last.at < (options.coalesceKey ? 1000 : 500));- if (!coalesce) undo = [...undo.slice(-199), { data: before, applications: state().proposalApplications }];+ if (!coalesce) undo = [...undo.slice(-199), checkpoint(record.document)];redo = [];last = { at: now, key: options.coalesceKey, coalesce: !options.newStep };history();- queue(adapter.withData(record.document, next), {- ...state().proposalApplications,- ...appliedApplications(options.applied ?? []),- });+ const document = adapter.withData(record.document, next);+ queue(+ newSources+ ? {+ ...document,+ aiOperationIds: [+ ...new Set([...(record.document.aiOperationIds ?? []), ...(options.aiOperationIds ?? [])]),+ ],+ aiUsage: null,+ }+ : document,+ {+ ...state().proposalApplications,+ ...appliedApplications(options.applied ?? []),+ },+ );}function updateDocument(recipe: (draft: WritableDraft<D>) => void) {@@ -387,16 +414,20 @@ export function createDraftStore<D extends Document, T>(adapter: DraftAdapter<D,queue(document);}- function travel(from: ProposalSnapshot<T>[], to: ProposalSnapshot<T>[]) {+ function travel(from: Snapshot<T>[], to: Snapshot<T>[]) {if (!record || state().locked || resolving) return;const next = from.pop();if (next === undefined) return;- to.push({ data: adapter.data(record.document), applications: state().proposalApplications });+ to.push(checkpoint(record.document));if (to.length > 200) to.shift();last = null;history();queue(- adapter.withData(record.document, next.data),+ {+ ...adapter.withData(record.document, next.data),+ aiOperationIds: next.aiOperationIds ?? [],+ aiUsage: next.aiUsage,+ },restoreProposalApplications(state().proposalApplications, next.applications),);}diff --git a/apps/mobile/src/draft/types.ts b/apps/mobile/src/draft/types.tsindex d511a1121..03a33684c 100644--- a/apps/mobile/src/draft/types.ts+++ b/apps/mobile/src/draft/types.ts@@ -30,6 +30,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">[];/** The field being edited. Consecutive edits with the same key within 1 s merge into one undo step. */diff --git a/apps/mobile/src/features/letters/write.tsx b/apps/mobile/src/features/letters/write.tsxindex 4451add04..24682ed21 100644--- a/apps/mobile/src/features/letters/write.tsx+++ b/apps/mobile/src/features/letters/write.tsx@@ -621,7 +621,19 @@ function BodySection({ letter, application, disabled }: LetterSectionProps) {value={letter.content}disabled={disabled}autoFocus={writing && countWords(letter.content) === 0}- onChange={(content, options) => edit("content", (value) => void (value.content = content), options)}+ onChange={(content, options) =>+ edit(+ "content",+ (value) => {+ value.content = content;+ if (options?.aiOperationIds?.length) {+ value.aiOperationIds = [...new Set([...(value.aiOperationIds ?? []), ...options.aiOperationIds])];+ value.aiUsage = null;+ }+ },+ options,+ )+ }/>) : (<EmptyBody letter={letter} application={application} disabled={disabled} onWrite={() => setWriting(true)} />diff --git a/apps/mobile/src/features/write/entry-fields.tsx b/apps/mobile/src/features/write/entry-fields.tsxindex 2103294ed..afc1594a2 100644--- a/apps/mobile/src/features/write/entry-fields.tsx+++ b/apps/mobile/src/features/write/entry-fields.tsx@@ -242,7 +242,7 @@ function Roles({ entry, write, page, disabled, focusField }: FieldProps) {const { t } = useLingui();const { colors, radius, space } = useTheme();const roles = (entry as unknown as Values).roles ?? [];- const writeRoles = (key: string, mutate: (roles: RoleItem[]) => void, options?: { newStep?: boolean }) =>+ const writeRoles = (key: string, mutate: (roles: RoleItem[]) => void, options?: Parameters<EntryWriter>[2]) =>write(`roles:${key}`,(target) => {@@ -250,7 +250,12 @@ function Roles({ entry, write, page, disabled, focusField }: FieldProps) {},options,);- const update = (role: RoleItem, key: string, mutate: (role: RoleItem) => void, options?: { newStep?: boolean }) =>+ const update = (+ role: RoleItem,+ key: string,+ mutate: (role: RoleItem) => void,+ options?: Parameters<EntryWriter>[2],+ ) =>writeRoles(`${role.id}:${key}`,(list) => {diff --git a/apps/mobile/src/features/write/entry-screen.tsx b/apps/mobile/src/features/write/entry-screen.tsxindex 3754334ec..9e84e1cbe 100644--- a/apps/mobile/src/features/write/entry-screen.tsx+++ b/apps/mobile/src/features/write/entry-screen.tsx@@ -96,6 +96,7 @@ export function EntryScreen({ resumeId, sectionId, entryId, focusField }: EntryS</Text>) : null}<EntryFields+ key={`${resumeId}:${entryId}`}type={section.type}entry={entry}write={write}@@ -125,12 +126,13 @@ export function SummaryScreen({ autoFocus }: SummaryScreenProps) {const title = useSectionTitle({ id: "summary", kind: "summary", type: "summary" });const locked = useIsResumeLocked();const update = useResumeStore((state) => state.update);- const loaded = useResumeStore((state) => state.document !== null);+ const documentId = useResumeStore((state) => state.document?.id);return (<EditorScreen title={title}>- {loaded ? (+ {documentId ? (<RichTextField+ key={documentId}label={t`Summary`}value={content}disabled={locked}diff --git a/apps/mobile/src/features/write/hooks.ts b/apps/mobile/src/features/write/hooks.tsindex 8266cd18c..9f7ce9fae 100644--- a/apps/mobile/src/features/write/hooks.ts+++ b/apps/mobile/src/features/write/hooks.ts@@ -1,4 +1,5 @@import type { Entry, WriteSection } from "./model";+import type { UpdateOptions } from "@/draft";import type { ResumeData } from "@reactive-resume/schema/resume/data";import type { WritableDraft } from "immer";import { useLingui } from "@lingui/react/macro";@@ -22,22 +23,26 @@ export const useEntry = (sectionId: string, entryId: string) =>export type EntryWriter = (key: string,mutate: (entry: Record<string, unknown>) => void,- options?: { newStep?: boolean },+ options?: Pick<UpdateOptions, "newStep" | "aiOperationIds">,) => void;/** Writes one field of an entry. Typing in one field folds into one undo step; another field starts a new one. */export function useEntryWriter(sectionId: string, entryId: string): EntryWriter {const update = useResumeStore((state) => state.update);+ const documentId = useResumeStore((state) => state.document?.id);return useCallback(- (key, mutate, options) =>+ (key, mutate, options) => {+ const current = useResumeStore.getState().document;+ if (!current || current.id !== documentId || !findEntry(current.data, sectionId, entryId)) return;update((draft) => {const entry = findEntry(draft, sectionId, entryId);if (entry) mutate(entry as Entry & Record<string, unknown>);},{ coalesceKey: `${entryId}:${key}`, ...options },- ),- [update, sectionId, entryId],+ );+ },+ [update, documentId, sectionId, entryId],);}diff --git a/apps/mobile/src/features/write/improve.tsx b/apps/mobile/src/features/write/improve.tsxindex b62e37dd9..e41fd4d5a 100644--- a/apps/mobile/src/features/write/improve.tsx+++ b/apps/mobile/src/features/write/improve.tsx@@ -8,6 +8,7 @@ import { aiModelForTask } from "@reactive-resume/ai/task-models";import { isNetworkError } from "@reactive-resume/utils/http";import { orpc } from "@/api/client";import { AIProviderSetupSheet, useHasAIProvider } from "@/features/ai/providers";+import { AiResultUsage } from "@/features/ai/usage";import { Button, ListRow, Text, TextField, useTheme } from "@/ui";type Action = "verb" | "result" | "shorter" | "posting" | "warmer" | "custom";@@ -21,7 +22,7 @@ type ImprovePanelProps = {letter?: { applicationId?: string | null | undefined } | undefined;onClose: () => void;/** Swaps the line; false when it changed since Improve was asked. */- onReplace: (text: string) => Promise<boolean>;+ onReplace: (text: string, aiOperationIds?: string[]) => Promise<boolean>;};/**@@ -67,6 +68,7 @@ export function ImprovePanel({ line, where, context, letter, onClose, onReplacesetLast({ action, words });improve.mutate({aiProviderId: ai.defaultProvider.id,+ includeProvenance: true,action,line: line.text,where,@@ -140,6 +142,7 @@ export function ImprovePanel({ line, where, context, letter, onClose, onReplace{improve.data.why}{improve.data.addsFacts ? ` ${t`Check it's accurate.`}` : ""}</Text>+ <AiResultUsage usage={improve.data.aiUsage} />{changed ? (<Text variant="caption" color="dangerText" accessibilityLiveRegion="assertive">{t`The line changed since you asked, so it wasn't replaced.`}@@ -150,7 +153,9 @@ export function ImprovePanel({ line, where, context, letter, onClose, onReplace<Buttonsize="sm"label={t`Replace`}- onPress={() => void onReplace(improve.data.text).then((done) => setChanged(!done))}+ onPress={() =>+ void onReplace(improve.data.text, improve.data.aiOperationIds).then((done) => setChanged(!done))+ }/>) : null}<Button size="sm" variant="secondary" label={t`Keep mine`} onPress={onClose} />diff --git a/apps/mobile/src/features/write/rich-text-field.tsx b/apps/mobile/src/features/write/rich-text-field.tsxindex 19320deff..f56eb39cf 100644--- a/apps/mobile/src/features/write/rich-text-field.tsx+++ b/apps/mobile/src/features/write/rich-text-field.tsx@@ -61,7 +61,7 @@ export type RichTextFieldProps = {improve?: boolean | undefined;minLines?: number | undefined;/** Receives document HTML, only after the user edits this field. `newStep` marks an accepted AI replacement. */- onChange: (html: string, options?: { newStep?: boolean }) => void;+ onChange: (html: string, options?: { newStep?: boolean; aiOperationIds?: string[] | undefined }) => void;/** Guidance while editing, e.g. "2–3 sentences reads best". */hint?: string | undefined;disabled?: boolean | undefined;@@ -249,7 +249,7 @@ export function RichTextField({improveSequence.current++;setImproving(null);}}- onReplace={async (replacement) => {+ onReplace={async (replacement, aiOperationIds) => {const current = () =>mounted.current &&!latest.current.disabled &&@@ -271,7 +271,7 @@ export function RichTextField({)return false;improveSequence.current++;- latest.current.onChange(next, { newStep: true });+ latest.current.onChange(next, { newStep: true, aiOperationIds });ref.current?.setValue(session.wrote(next));setImproving(null);return true;diff --git a/apps/web/src/features/resume/builder/draft.test.ts b/apps/web/src/features/resume/builder/draft.test.tsindex edc79c4ba..c4908bab3 100644--- a/apps/web/src/features/resume/builder/draft.test.ts+++ b/apps/web/src/features/resume/builder/draft.test.ts@@ -1782,6 +1782,109 @@ describe("concurrent receipt ownership", () => {vi.useRealTimers();});const s = () => useResumeStore.getState();+ 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"];+ initial.data.summary.content = "<p>Improved</p>";+ s().initialize(initial);+ orpcMocks.updateResume.mockImplementation(async (input) => ({+ ...initial,+ data: input.data,+ aiOperationIds: input.aiOperationIds,+ }));+ s().updateResumeData(+ (data) => {+ data.summary.content = "<p>Original</p>";+ },+ {+ newStep: true,+ removedAiOperationIds: ["reviewed-improve"],+ },+ );+ await vi.advanceTimersByTimeAsync(500);+ expect(orpcMocks.updateResume.mock.lastCall?.[0]).toMatchObject({+ data: { summary: { content: "<p>Original</p>" } },+ aiOperationIds: ["import-source", "other-field-source"],+ });+ expect(s().resume?.aiOperationIds).toEqual(["import-source", "other-field-source"]);+ });+ it.each([false, true])(+ "pairs Improve sources through inflight Undo and Redo, including unchanged wording=%s",+ async (sameWords) => {+ const initial = makeResume(`improve-inflight-${sameWords}`);+ initial.aiOperationIds = ["import-source"];+ initial.data.summary.content = "<p>Original</p>";+ s().initialize(initial);+ const accepted = deferred<Resume>();+ orpcMocks.updateResume+ .mockImplementationOnce(() => accepted.promise)+ .mockImplementation(async (input) => ({+ ...initial,+ data: input.data,+ aiOperationIds: input.aiOperationIds,+ updatedAt: new Date(initial.updatedAt.getTime() + 2),+ }));+ s().updateResumeData(+ (data) => {+ data.summary.content = sameWords ? initial.data.summary.content : "<p>Improved</p>";+ },+ { newStep: true, aiOperationIds: ["improve-source"] },+ );+ await vi.advanceTimersByTimeAsync(500);+ expect(orpcMocks.updateResume).toHaveBeenCalledOnce();+ s().undo();+ await vi.advanceTimersByTimeAsync(500);+ accepted.resolve({+ ...initial,+ data: {+ ...initial.data,+ summary: { ...initial.data.summary, content: sameWords ? initial.data.summary.content : "<p>Improved</p>" },+ },+ aiOperationIds: ["import-source", "improve-source"],+ updatedAt: new Date(initial.updatedAt.getTime() + 1),+ });+ await flushMicrotasks();+ await vi.advanceTimersByTimeAsync(0);+ expect(orpcMocks.updateResume.mock.calls.map(([input]) => input.aiOperationIds)).toEqual([+ ["import-source", "improve-source"],+ ["import-source"],+ ]);+ expect(s().resume?.aiOperationIds).toEqual(["import-source"]);+ expect(s().resume?.data.summary.content).toBe(initial.data.summary.content);+ s().redo();+ await vi.advanceTimersByTimeAsync(500);+ expect(s().resume?.aiOperationIds).toEqual(["import-source", "improve-source"]);+ expect(orpcMocks.updateResume.mock.lastCall?.[0].aiOperationIds).toEqual(["import-source", "improve-source"]);+ },+ );+ it.each([false, true])(+ "recovers unsaved Improve sources with their content, including unchanged wording=%s",+ async (sameWords) => {+ const initial = makeResume(`improve-recovery-${sameWords}`);+ initial.aiOperationIds = ["import-source"];+ s().initialize(initial);+ orpcMocks.updateResume.mockRejectedValue(new Error("offline"));+ s().updateResumeData(+ (data) => {+ if (!sameWords) data.summary.content = "<p>Improved</p>";+ },+ { newStep: true, aiOperationIds: ["improve-source"] },+ );+ await vi.advanceTimersByTimeAsync(500);+ clearResumeDrafts();+ orpcMocks.updateResume.mockReset().mockImplementation(async (input) => ({+ ...initial,+ data: input.data,+ aiOperationIds: input.aiOperationIds,+ updatedAt: new Date(initial.updatedAt.getTime() + 1),+ }));+ s().initialize(initial);+ expect(s().resume?.aiOperationIds).toEqual(["import-source", "improve-source"]);+ expect(s().resume?.data.summary.content).toBe(sameWords ? initial.data.summary.content : "<p>Improved</p>");+ await flushMicrotasks();+ expect(orpcMocks.updateResume.mock.lastCall?.[0].aiOperationIds).toEqual(["import-source", "improve-source"]);+ },+ );it("newer remote Undo must supersede clean local acceptance, including after restart", async () => {const initial = makeResume("remote-undo");initial.data.summary.content = "<p>Old</p>";diff --git a/apps/web/src/features/resume/builder/draft.ts b/apps/web/src/features/resume/builder/draft.tsindex 012dc9759..05db723c4 100644--- a/apps/web/src/features/resume/builder/draft.ts+++ b/apps/web/src/features/resume/builder/draft.ts@@ -18,6 +18,7 @@ import {readProposalApplications,restoreProposalApplications,} from "@reactive-resume/resume/proposals";+import { aiOperationIdsSchema } from "@reactive-resume/schema/ai-usage";import { parseResumeData } from "@reactive-resume/schema/resume/data";import { syncResumeDates } from "@reactive-resume/schema/resume/dates";import { toast } from "@reactive-resume/ui/components/toast";@@ -60,7 +61,9 @@ type ResumeUpdateEvent = { mutation: ResumeUpdateMutation };*/type SaveStatus = "idle" | "saving" | "saved" | "offline" | "error" | "conflict" | "locked";-type UpdateResumeDataOptions = {+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">[];/**@@ -77,6 +80,8 @@ type UpdateResumeDataOptions = {sameStep?: boolean;};+type ResumeSnapshot = ProposalSnapshot<ResumeData> & Pick<Resume, "aiOperationIds" | "aiUsage">;+type ResumeStoreState = {resume: Resume | null;resumeId?: string | undefined;@@ -85,8 +90,8 @@ type ResumeStoreState = {// Undo/redo stacks of `ResumeData` references. Immer's immutable updates share structure, so a// step costs only the parts that changed.proposalApplications: ProposalApplications;- undoStack: ProposalSnapshot<ResumeData>[];- redoStack: ProposalSnapshot<ResumeData>[];+ undoStack: ResumeSnapshot[];+ redoStack: ResumeSnapshot[];};type ResumeStoreActions = {@@ -194,6 +199,7 @@ function storeUnsavedResume(resume: Resume) {recoveryKey(resume),JSON.stringify({data: resume.data,+ aiOperationIds: resume.aiOperationIds,baseUpdatedAt: getRuntime(resume.id).baseUpdatedAt,storedAt: Date.now(),proposalApplications: getRuntime(resume.id).proposalApplications,@@ -214,6 +220,7 @@ function clearUnsavedResume(resume: Resume) {recoveryKey(resume),JSON.stringify({data: resume.data,+ aiOperationIds: resume.aiOperationIds,baseUpdatedAt: runtime.baseUpdatedAt,storedAt: Date.now(),clean: true,@@ -233,6 +240,7 @@ function clearUnsavedResume(resume: Resume) {type UnsavedResume = {data: ResumeData;+ aiOperationIds?: string[];baseUpdatedAt?: string;storedAt: number;key: string;@@ -253,6 +261,8 @@ function readUnsavedResume(id: string): UnsavedResume | undefined {if (!raw) continue;try {const parsed = JSON.parse(raw) as Omit<UnsavedResume, "key" | "raw">;+ if (parsed.aiOperationIds !== undefined && !aiOperationIdsSchema.safeParse(parsed.aiOperationIds).success)+ delete parsed.aiOperationIds;if (!Number.isFinite(parsed.storedAt) ||(Date.now() - parsed.storedAt > 7 * 86_400_000 &&@@ -405,6 +415,7 @@ async function flushResumeSave(id: string) {{id: submitted.id,data: submittedData,+ ...(submitted.aiOperationIds !== undefined ? { aiOperationIds: submitted.aiOperationIds } : {}),sessionId: runtime.sessionId,expectedUpdatedAt: runtime.baseUpdatedAt,...(runtime.proposalSafety ? { proposalSafety: runtime.proposalSafety } : {}),@@ -425,10 +436,12 @@ async function flushResumeSave(id: string) {runtime.queryClient?.setQueryData(getResumeQueryKey(submitted.id), updated);const currentResume = useResumeStore.getState().resume;- const currentDataStillMatchesSubmission =+ const contentStillMatchesSubmission =currentResume?.id === submitted.id &&isEqual(currentResume.data, submittedData) &&- Object.keys(runtime.pendingProposalApplications).length === 0;+ isEqual(currentResume.aiOperationIds ?? [], submitted.aiOperationIds ?? []);+ const currentDataStillMatchesSubmission =+ contentStillMatchesSubmission && Object.keys(runtime.pendingProposalApplications).length === 0;if (currentDataStillMatchesSubmission && !runtime.pendingResume) {runtime.hasPendingLocalChanges = false;@@ -443,7 +456,7 @@ async function flushResumeSave(id: string) {runtime.hasPendingLocalChanges = true;useResumeStore.getState().mergeResumeMetadata(updated);- if (!runtime.pendingResume && currentResume?.id === submitted.id && !isEqual(currentResume.data, submittedData)) {+ if (!runtime.pendingResume && currentResume?.id === submitted.id && !contentStillMatchesSubmission) {runtime.syncResume.cancel();runtime.pendingResume = structuredClone(currentResume);}@@ -599,9 +612,22 @@ export const useResumeStore = create<ResumeStore>()(const pending = readProposalApplications(unsaved?.pendingProposalApplications);const hasPendingDecisions = Object.keys(pending).length > 0;const sameRevision = unsaved?.baseUpdatedAt === resume?.updatedAt.toISOString();+ const hasSourceChanges =+ unsaved?.aiOperationIds !== undefined && !isEqual(unsaved.aiOperationIds, resume?.aiOperationIds ?? []);const restored =- resume && unsaved && ((!unsaved.clean && !isEqual(unsaved.data, resume.data)) || hasPendingDecisions)- ? { ...resume, data: unsaved.data }+ resume &&+ unsaved &&+ ((!unsaved.clean && (!isEqual(unsaved.data, resume.data) || hasSourceChanges)) || hasPendingDecisions)+ ? {+ ...resume,+ data: unsaved.data,+ ...(unsaved.aiOperationIds !== undefined+ ? {+ aiOperationIds: unsaved.aiOperationIds,+ aiUsage: hasSourceChanges ? null : resume.aiUsage,+ }+ : {}),+ }: null;if (resume) {const runtime = getRuntime(resume.id);@@ -717,8 +743,10 @@ export const useResumeStore = create<ResumeStore>()(state.resume.showInSearchEngines = resume.showInSearchEngines;state.resume.hideContactDetails = resume.hideContactDetails;state.resume.isPrimary = resume.isPrimary;- if (resume.aiOperationIds !== undefined) state.resume.aiOperationIds = resume.aiOperationIds;- if (resume.aiUsage !== undefined) state.resume.aiUsage = resume.aiUsage;+ if (!getRuntime(resume.id).hasPendingLocalChanges) {+ if (resume.aiOperationIds !== undefined) state.resume.aiOperationIds = resume.aiOperationIds;+ if (resume.aiUsage !== undefined) state.resume.aiUsage = resume.aiUsage;+ }});},@@ -751,13 +779,30 @@ export const useResumeStore = create<ResumeStore>()(if (!state.resume) return;if (snapshotBefore) {- state.undoStack.push({ data: snapshotBefore, applications: state.proposalApplications });+ state.undoStack.push({+ data: snapshotBefore,+ applications: state.proposalApplications,+ aiOperationIds: currentResume.aiOperationIds ?? [],+ aiUsage: currentResume.aiUsage,+ });if (state.undoStack.length > MAX_HISTORY_ENTRIES) state.undoStack.shift();// A fresh edit invalidates the redo branch.state.redoStack = [];}fn(state.resume.data as WritableDraft<ResumeData>);+ if (options.aiOperationIds?.length) {+ state.resume.aiOperationIds = [+ ...new Set([...(state.resume.aiOperationIds ?? []), ...options.aiOperationIds]),+ ];+ state.resume.aiUsage = null;+ }+ if (options.removedAiOperationIds?.length) {+ state.resume.aiOperationIds = (state.resume.aiOperationIds ?? []).filter(+ (id) => !options.removedAiOperationIds?.includes(id),+ );+ state.resume.aiUsage = null;+ }if (options.applied?.length)state.proposalApplications = { ...state.proposalApplications, ...appliedApplications(options.applied) };// The server writes the date text from the dates on save; doing the same here keeps its echo@@ -896,10 +941,17 @@ function applyHistoryStep(get: StoreGet, set: ImmerSet, direction: "undo" | "redconst snapshot = from.pop();if (snapshot === undefined) return;- to.push({ data: current as WritableDraft<ResumeData>, applications: draft.proposalApplications });+ to.push({+ data: current as WritableDraft<ResumeData>,+ applications: draft.proposalApplications,+ aiOperationIds: currentResume.aiOperationIds ?? [],+ aiUsage: currentResume.aiUsage,+ });if (to.length > MAX_HISTORY_ENTRIES) to.shift();draft.resume.data = snapshot.data;+ draft.resume.aiOperationIds = snapshot.aiOperationIds ?? [];+ draft.resume.aiUsage = snapshot.aiUsage;draft.proposalApplications = restoreProposalApplications(draft.proposalApplications, snapshot.applications);if (!getRuntime(currentResume.id).conflict) draft.saveStatus = "saving";});@@ -1081,7 +1133,7 @@ export function useUpdateResumeData() {return useCallback((fn: (draft: WritableDraft<ResumeData>) => void, options?: UpdateResumeDataOptions) => {- if (!resumeId) return;+ if (!resumeId || useResumeStore.getState().resume?.id !== resumeId) return;bindRuntimeQueryClient(resumeId, queryClient);updateResumeData(fn, options);},diff --git a/apps/web/src/features/resume/editor/write/entries.tsx b/apps/web/src/features/resume/editor/write/entries.tsxindex 9f09ff160..09e435c9d 100644--- a/apps/web/src/features/resume/editor/write/entries.tsx+++ b/apps/web/src/features/resume/editor/write/entries.tsx@@ -209,7 +209,7 @@ function IconAndColor({ entry, write }: FieldSetProps) {function Roles({ entry, write, page }: FieldSetProps) {const roles = valuesOf(entry).roles ?? [];- const writeRoles = (key: string, mutate: (roles: RoleItem[]) => void, options?: { newStep?: boolean }) =>+ const writeRoles = (key: string, mutate: (roles: RoleItem[]) => void, options?: Parameters<EntryWriter>[2]) =>write(`roles:${key}`,(target) => {diff --git a/apps/web/src/features/resume/editor/write/fields.tsx b/apps/web/src/features/resume/editor/write/fields.tsxindex d93a4b08f..4cf2dc493 100644--- a/apps/web/src/features/resume/editor/write/fields.tsx+++ b/apps/web/src/features/resume/editor/write/fields.tsx@@ -1,4 +1,5 @@import type { Entry } from "./model";+import type { UpdateResumeDataOptions } from "@/features/resume/builder/draft";import type { Website } from "@reactive-resume/schema/resume/data";import type { ComponentProps, ReactNode } from "react";import { t } from "@lingui/core/macro";@@ -11,7 +12,7 @@ import { Input } from "@reactive-resume/ui/components/input";import { cn } from "@reactive-resume/utils/style";import { findEntry } from "./model";import { URLInput } from "@/components/input/url-input";-import { useCurrentBuilderResumeSelector, useUpdateResumeData } from "@/features/resume/builder/draft";+import { useCurrentBuilderResumeSelector, useResumeStore, useUpdateResumeData } from "@/features/resume/builder/draft";/** One entry of a section, re-rendering only when that entry changes; null once it's deleted. */export const useEntry = (sectionId: string, entryId: string) =>@@ -20,7 +21,7 @@ export const useEntry = (sectionId: string, entryId: string) =>export type EntryWriter = (key: string,mutate: (entry: Record<string, unknown>) => void,- options?: { newStep?: boolean },+ options?: Pick<UpdateResumeDataOptions, "newStep" | "aiOperationIds" | "removedAiOperationIds">,) => void;/**@@ -32,6 +33,8 @@ export function useEntryWriter(sectionId: string, entryId: string): EntryWriterreturn useCallback((key, mutate, options) => {+ const current = useResumeStore.getState().resume;+ if (!current || !findEntry(current.data, sectionId, entryId)) return;updateResumeData((draft) => {const entry = findEntry(draft, sectionId, entryId);diff --git a/apps/web/src/features/resume/editor/write/improve-history.test.ts b/apps/web/src/features/resume/editor/write/improve-history.test.tsindex 320af4944..5d43a45f9 100644--- a/apps/web/src/features/resume/editor/write/improve-history.test.ts+++ b/apps/web/src/features/resume/editor/write/improve-history.test.ts@@ -20,7 +20,7 @@ describe("accepted Improve replacement history", () => {// The user's edit is already a history event. Replace 100 ms later, inside the editor's 500 ms group window.vi.setSystemTime(new Date(100));- acceptImproveLine(editor, { from: 1, to: 1 + user.length }, replacement);+ acceptImproveLine(editor, { from: 1, to: 1 + user.length }, replacement, ["reviewed-improve"]);expect(editor.getText()).toBe(replacement);editor.commands.undo();@@ -37,7 +37,9 @@ describe("accepted Improve replacement history", () => {const replacement = "Led fictional delivery work.";vi.setSystemTime(new Date(100));- acceptImproveLine(editor, { from: 1, to: "Owned synthetic delivery.".length + 1 }, replacement);+ acceptImproveLine(editor, { from: 1, to: "Owned synthetic delivery.".length + 1 }, replacement, [+ "reviewed-improve",+ ]);vi.setSystemTime(new Date(150));editor.commands.insertContent(" More");diff --git a/apps/web/src/features/resume/editor/write/improve-history.ts b/apps/web/src/features/resume/editor/write/improve-history.tsindex b6be3832d..df4a915ee 100644--- a/apps/web/src/features/resume/editor/write/improve-history.ts+++ b/apps/web/src/features/resume/editor/write/improve-history.ts@@ -1,17 +1,73 @@import type { ImproveLine } from "./improve";+import type { Node, Schema } from "@tiptap/pm/model";+import type { Transaction } from "@tiptap/pm/state";import type { Editor } from "@tiptap/react";import { closeHistory } from "@tiptap/pm/history";+import { Step, StepResult } from "@tiptap/pm/transform";+import { aiOperationIdsSchema } from "@reactive-resume/schema/ai-usage";++// Private editor history metadata: invert with the wording, never put request references in document HTML/JSON.+class ImproveSourcesStep extends Step {+ constructor(+ readonly ids: string[],+ readonly added: boolean,+ ) {+ super();+ }+ apply(doc: Node) {+ return StepResult.ok(doc);+ }+ invert() {+ return new ImproveSourcesStep(this.ids, !this.added);+ }+ map() {+ return this;+ }+ toJSON() {+ return { stepType: "reactiveResumeImproveSources", ids: this.ids, added: this.added };+ }+ static fromJSON(_schema: Schema, value: unknown) {+ if (+ !value ||+ typeof value !== "object" ||+ !("ids" in value) ||+ !("added" in value) ||+ typeof value.added !== "boolean"+ )+ throw new RangeError("Invalid Improve source step");+ return new ImproveSourcesStep(aiOperationIdsSchema.parse(value.ids), value.added);+ }+}+Step.jsonID("reactiveResumeImproveSources", ImproveSourcesStep);++export function improveSourceChanges(transaction: Transaction) {+ const steps = transaction.steps.filter((step): step is ImproveSourcesStep => step instanceof ImproveSourcesStep);+ if (!steps.length) return undefined;+ const added = steps.filter((step) => step.added).flatMap((step) => step.ids);+ const removed = steps.filter((step) => !step.added).flatMap((step) => step.ids);+ return {+ newStep: true,+ ...(added.length ? { aiOperationIds: added } : {}),+ ...(removed.length ? { removedAiOperationIds: removed } : {}),+ };+}/*** Applies an accepted Improve suggestion as its own editor history event. The first boundary ends the user's typing* group; the empty closing transaction makes the next keystroke start a new group instead of joining the AI edit.*/-export function acceptImproveLine(editor: Editor, line: Pick<ImproveLine, "from" | "to">, text: string) {+export function acceptImproveLine(+ editor: Editor,+ line: Pick<ImproveLine, "from" | "to">,+ text: string,+ aiOperationIds?: string[],+) {editor.chain().focus().insertContentAt({ from: line.from, to: line.to }, text).command(({ tr }) => {+ if (aiOperationIds?.length) tr.step(new ImproveSourcesStep(aiOperationIds, true));closeHistory(tr);return true;})diff --git a/apps/web/src/features/resume/editor/write/improve.test.tsx b/apps/web/src/features/resume/editor/write/improve.test.tsxnew file mode 100644index 000000000..a8eb8d583--- /dev/null+++ b/apps/web/src/features/resume/editor/write/improve.test.tsx@@ -0,0 +1,128 @@+// @vitest-environment happy-dom+import { act, fireEvent, render, screen } from "@testing-library/react";+import { beforeEach, expect, it, vi } from "vite-plus/test";+import { i18n } from "@lingui/core";+import { I18nProvider } from "@lingui/react";+import { RichTextEditor } from "./rich-text-editor-field";++const fixture = vi.hoisted(() => ({+ requests: [] as unknown[],+ result: {} as { text: string; why: string; addsFacts: boolean; aiOperationIds?: string[]; aiUsage?: unknown },+}));+vi.mock("@reactive-resume/ui/hooks/use-breakpoint", () => ({ useBreakpoint: () => "desktop" }));+vi.mock("@reactive-resume/ui/hooks/use-keyboard-inset", () => ({ useKeyboardInset: () => 0 }));+vi.mock("@/hooks/use-confirm", () => ({ usePrompt: () => vi.fn() }));+vi.mock("@/features/assistant/provider-setup", () => ({ SetUpAi: () => null }));+vi.mock("@/features/settings/integrations/hooks/use-has-usable-ai-provider", () => ({+ useHasUsableAiProvider: () => ({+ hasUsableProvider: true,+ usableProviders: [{ id: "current-provider", label: "Current AI", model: "main", fastModel: "fast" }],+ }),+}));+vi.mock("@/libs/orpc/client", () => ({ orpc: { ai: { improve: { mutationOptions: () => ({}) } } } }));+vi.mock("@tanstack/react-query", async (importOriginal) => {+ const original = await importOriginal<typeof import("@tanstack/react-query")>();+ const { useState } = await import("react");+ return {+ ...original,+ useMutation: () => {+ const [data, setData] = useState<typeof fixture.result | null>(null);+ return {+ data,+ error: null,+ isPending: false,+ mutate: (input: unknown) => {+ fixture.requests.push(input);+ setData(fixture.result);+ },+ reset: () => setData(null),+ };+ },+ };+});++beforeEach(() => {+ i18n.load("en", {});+ i18n.activate("en");+ fixture.requests = [];+ fixture.result = {+ text: "Reviewed replacement",+ why: "Clearer",+ addsFacts: false,+ aiOperationIds: ["reviewed-improve"],+ aiUsage: { requests: 2, models: [{ label: "Original AI", provider: "openai-compatible", model: "actual-fast" }] },+ };+});++async function review() {+ const onChange = vi.fn();+ render(+ <I18nProvider i18n={i18n}>+ <RichTextEditor+ label="Summary"+ value={'<p data-resume-whitespace="preserve">Original line</p>'}+ onChange={onChange}+ />+ </I18nProvider>,+ );+ const editor = await screen.findByRole("textbox", { name: "Summary" });+ await act(async () => editor.focus());+ fireEvent.click(screen.getByRole("button", { name: "Improve" }));+ fireEvent.click(screen.getByRole("button", { name: "Stronger verb" }));+ expect(onChange).not.toHaveBeenCalled();+ expect(fixture.requests).toEqual([expect.objectContaining({ includeProvenance: true, line: "Original line" })]);+ return onChange;+}++it.each([false, true])("Replace carries only reviewed sources, including identical wording=%s", async (sameWords) => {+ if (sameWords) fixture.result.text = "Original line";+ const onChange = await review();+ expect(screen.getByText("AI request attempts: 2")).toBeVisible();+ expect(screen.getByText("Original AI · openai-compatible · actual-fast")).toBeVisible();+ fireEvent.click(screen.getByRole("button", { name: "Replace" }));+ expect(onChange).toHaveBeenCalledExactlyOnceWith(+ '<p data-resume-whitespace="preserve">' + fixture.result.text + "</p>",+ {+ newStep: true,+ aiOperationIds: ["reviewed-improve"],+ },+ );+ expect(fixture.requests).toHaveLength(1);+});++it("Keep mine adds no document sources", async () => {+ const onChange = await review();+ fireEvent.click(screen.getByRole("button", { name: "Keep mine" }));+ expect(onChange).not.toHaveBeenCalled();+ expect(fixture.requests).toHaveLength(1);+});++it("older source-less response can be accepted without repeating generation", async () => {+ fixture.result = { text: "Older suggestion", why: "Clearer", addsFacts: false };+ const onChange = await review();+ expect(screen.getByText("AI request history unavailable for this result.")).toBeVisible();+ fireEvent.click(screen.getByRole("button", { name: "Replace" }));+ expect(onChange).toHaveBeenCalledExactlyOnceWith('<p data-resume-whitespace="preserve">Older suggestion</p>', {+ newStep: true,+ aiOperationIds: undefined,+ });+ expect(fixture.requests).toHaveLength(1);+});++it.each([false, true])("editor Undo and Redo carry the accepted source change (same wording=%s)", async (sameWords) => {+ if (sameWords) fixture.result.text = "Original line";+ const onChange = await review();+ fireEvent.click(screen.getByRole("button", { name: "Replace" }));+ const editor = screen.getByRole("textbox", { name: "Summary" });+ fireEvent.keyDown(editor, { key: "z", code: "KeyZ", ctrlKey: true });+ expect(onChange).toHaveBeenLastCalledWith('<p data-resume-whitespace="preserve">Original line</p>', {+ newStep: true,+ removedAiOperationIds: ["reviewed-improve"],+ });+ fireEvent.keyDown(editor, { key: "z", code: "KeyZ", ctrlKey: true, shiftKey: true });+ expect(onChange).toHaveBeenLastCalledWith('<p data-resume-whitespace="preserve">' + fixture.result.text + "</p>", {+ newStep: true,+ aiOperationIds: ["reviewed-improve"],+ });+ expect(fixture.requests).toHaveLength(1);+});diff --git a/apps/web/src/features/resume/editor/write/improve.tsx b/apps/web/src/features/resume/editor/write/improve.tsxindex 9751e5337..ced5aebb6 100644--- a/apps/web/src/features/resume/editor/write/improve.tsx+++ b/apps/web/src/features/resume/editor/write/improve.tsx@@ -3,11 +3,12 @@ import type { Editor } from "@tiptap/react";import { t } from "@lingui/core/macro";import { Trans } from "@lingui/react/macro";import { useMutation } from "@tanstack/react-query";-import { useId, useState } from "react";+import { useId, useRef, useState } from "react";import { aiModelForTask } from "@reactive-resume/ai/task-models";import { Button } from "@reactive-resume/ui/components/button";import { Icon } from "@reactive-resume/ui/components/icon";import { Input } from "@reactive-resume/ui/components/input";+import { AiResultUsage } from "@/features/ai/usage";import { SetUpAi } from "@/features/assistant/provider-setup";import { useHasUsableAiProvider } from "@/features/settings/integrations/hooks/use-has-usable-ai-provider";import { getOrpcErrorMessage } from "@/libs/error-message";@@ -36,7 +37,7 @@ type ImprovePanelProps = {where: string;onClose: () => void;/** Applies the accepted text as its own editor/app history event. */- onAccept: (text: string) => void;+ onAccept: (text: string, aiOperationIds?: string[]) => void;kind?: ImproveKind | undefined;};@@ -55,6 +56,7 @@ export function ImprovePanel({ editor, line, where, onClose, onAccept, kind }: I// The last request sent, with its words, so Try again and Try another send exactly that again.const [last, setLast] = useState<{ action: Action; words: string } | null>(null);const [changed, setChanged] = useState(false);+ const replaced = useRef(false);const improve = useMutation(orpc.ai.improve.mutationOptions());const resultId = useId();@@ -82,6 +84,7 @@ export function ImprovePanel({ editor, line, where, onClose, onAccept, kind }: IsetLast({ action, words });improve.mutate({aiProviderId: provider.id,+ includeProvenance: true,action,line: line.text,where,@@ -98,9 +101,11 @@ export function ImprovePanel({ editor, line, where, onClose, onAccept, kind }: I};const replace = (text: string) => {+ if (replaced.current) return;const current = editor.state.doc.textBetween(line.from, line.to);if (current !== line.text) return setChanged(true);- onAccept(text);+ replaced.current = true;+ onAccept(text, improve.data?.aiOperationIds);onClose();};@@ -155,6 +160,7 @@ export function ImprovePanel({ editor, line, where, onClose, onAccept, kind }: I{improve.data.why}{improve.data.addsFacts && <> {t`Check it's accurate.`}</>}</p>+ <AiResultUsage usage={improve.data.aiUsage} />{changed && (<p role="alert" className="text-xs text-danger-text"><Trans>The line changed since you asked, so it wasn't replaced.</Trans>diff --git a/apps/web/src/features/resume/editor/write/rich-text-editor-field.tsx b/apps/web/src/features/resume/editor/write/rich-text-editor-field.tsxindex 0e2edcef1..09a3ba2ac 100644--- a/apps/web/src/features/resume/editor/write/rich-text-editor-field.tsx+++ b/apps/web/src/features/resume/editor/write/rich-text-editor-field.tsx@@ -28,7 +28,7 @@ import { useBreakpoint } from "@reactive-resume/ui/hooks/use-breakpoint";import { useKeyboardInset } from "@reactive-resume/ui/hooks/use-keyboard-inset";import { cn } from "@reactive-resume/utils/style";import { ImprovePanel, lineAtCaret } from "./improve";-import { acceptImproveLine } from "./improve-history";+import { acceptImproveLine, improveSourceChanges } from "./improve-history";import { cleanPastedHtml } from "@/components/input/pasted-html";import { richTextExtensions } from "@/components/input/rich-text-extensions";import { hasUnsupportedTableMarkup, toPreviewHtml } from "@/components/input/rich-text-markup";@@ -181,7 +181,14 @@ export type RichTextEditorProps = {/** Accessible name of the text box. */label: string;value: string;- onChange: (html: string, options?: { newStep?: boolean }) => void;+ onChange: (+ html: string,+ options?: {+ newStep?: boolean;+ aiOperationIds?: string[] | undefined;+ removedAiOperationIds?: string[] | undefined;+ },+ ) => void;/** Guidance under the text while editing, e.g. "2–3 sentences reads best". */hint?: ReactNode;disabled?: boolean;@@ -219,7 +226,7 @@ export function RichTextEditor({const ai = useHasUsableAiProvider();const mobile = useBreakpoint() === "mobile";const keyboardInset = useKeyboardInset();- const acceptedReplacement = useRef(false);+ const acceptedReplacement = useRef<Parameters<RichTextEditorProps["onChange"]>[1]>(undefined);const readOnlyTable = useMemo(() => hasUnsupportedTableMarkup(value), [value]);const editorValue = useMemo(() => (readOnlyTable ? toPreviewHtml(value) : value), [readOnlyTable, value]);@@ -281,10 +288,16 @@ export function RichTextEditor({),},},- onUpdate: ({ editor }) => {- const newStep = acceptedReplacement.current;- acceptedReplacement.current = false;- onChange(editor.getHTML(), newStep ? { newStep: true } : undefined);+ onTransaction: ({ editor, transaction }) => {+ const sources = improveSourceChanges(transaction);+ if (!sources || transaction.getMeta("preventUpdate") || !transaction.before.eq(editor.state.doc)) return;+ acceptedReplacement.current = undefined;+ onChange(editor.getHTML(), sources);+ },+ onUpdate: ({ editor, transaction }) => {+ const options = improveSourceChanges(transaction) ?? acceptedReplacement.current;+ acceptedReplacement.current = undefined;+ onChange(editor.getHTML(), options);},});@@ -333,10 +346,16 @@ export function RichTextEditor({const editing = focused || improving !== null || menus.open;- const acceptImprove = (line: ImproveLine, text: string) => {- if (!editor) return;- acceptedReplacement.current = true;- acceptImproveLine(editor, line, text);+ const acceptImprove = (line: ImproveLine, text: string, aiOperationIds?: string[]) => {+ if (!editor?.isEditable || editor.state.doc.textBetween(line.from, line.to) !== line.text) return;+ acceptedReplacement.current = { newStep: true, aiOperationIds };+ acceptImproveLine(editor, line, text, aiOperationIds);+ // Identical wording can still have an accepted source; Tiptap emits no content update in that case.+ if (acceptedReplacement.current) {+ const options = acceptedReplacement.current;+ acceptedReplacement.current = undefined;+ onChange(editor.getHTML(), options);+ }};const startImprove = () => {@@ -469,7 +488,7 @@ export function RichTextEditor({line={improving}where={label}onClose={() => setImproving(null)}- onAccept={(text) => acceptImprove(improving, text)}+ onAccept={(text, aiOperationIds) => acceptImprove(improving, text, aiOperationIds)}kind={improve}/>)}diff --git a/apps/web/src/routes/builder/letter/-components/write-panel.test.tsx b/apps/web/src/routes/builder/letter/-components/write-panel.test.tsxindex 703010f63..2aa5a0c35 100644--- a/apps/web/src/routes/builder/letter/-components/write-panel.test.tsx+++ b/apps/web/src/routes/builder/letter/-components/write-panel.test.tsx@@ -18,6 +18,12 @@ const state = vi.hoisted(() => ({sessionId: "session",edit: vi.fn(),start: vi.fn(),+ changeBody: undefined as+ | ((+ html: string,+ options?: { newStep?: boolean; aiOperationIds?: string[]; removedAiOperationIds?: string[] },+ ) => void)+ | undefined,}));vi.mock("@/features/letters/store", () => ({@@ -63,12 +69,23 @@ vi.mock("@/features/resume/editor/write/fields", async (importOriginal) => ({validateEmail: () => null,}));vi.mock("@/features/resume/editor/write/rich-text-editor", () => ({- RichTextEditor: ({ label, disabled }: { label: ReactNode; disabled?: boolean }) => (- <label>- {label}- <textarea disabled={disabled} />- </label>- ),+ RichTextEditor: ({+ label,+ disabled,+ onChange,+ }: {+ label: ReactNode;+ disabled?: boolean;+ onChange: typeof state.changeBody;+ }) => {+ if (label === "Letter body") state.changeBody = onChange;+ return (+ <label>+ {label}+ <textarea disabled={disabled} />+ </label>+ );+ },}));vi.mock("@/features/settings/integrations/ai-provider-load-state", () => ({ AiProviderLoadState: () => null }));vi.mock("@/features/settings/integrations/hooks/use-has-usable-ai-provider", () => ({@@ -118,6 +135,8 @@ beforeEach(() => {state.draft = { phase: "idle" };state.status = "saved";state.changing = false;+ state.sessionId = "session";+ state.changeBody = undefined;});afterEach(cleanup);@@ -183,3 +202,29 @@ it("shows original requested provider and model beside a saved letter body", ()expect(screen.getByText("AI request attempts: 2")).toBeTruthy();expect(screen.getByText("Original connection · openai-compatible · original-model")).toBeTruthy();});++it("accepted Improve contributes sources without dropping the letter draft's original sources", () => {+ state.letter = { ...letter, aiOperationIds: ["original-operation"] };+ renderPanel();+ expect(state.changeBody).toBeTypeOf("function");+ state.changeBody?.("<p>Reviewed paragraph</p>", { newStep: true, aiOperationIds: ["reviewed-improve"] });+ expect(state.edit).toHaveBeenCalledExactlyOnceWith({+ content: "<p>Reviewed paragraph</p>",+ aiOperationIds: ["original-operation", "reviewed-improve"],+ });+ state.letter = { ...letter, aiOperationIds: ["original-operation", "reviewed-improve", "later-source"] };+ state.edit.mockClear();+ state.changeBody?.("<p>Saved</p>", { newStep: true, removedAiOperationIds: ["reviewed-improve"] });+ expect(state.edit).toHaveBeenCalledExactlyOnceWith({+ content: "<p>Saved</p>",+ aiOperationIds: ["original-operation", "later-source"],+ });+});++it("late Improve edit cannot write into another letter session", () => {+ renderPanel();+ const captured = state.changeBody;+ state.sessionId = "another-session";+ captured?.("<p>Wrong target</p>", { aiOperationIds: ["reviewed-improve"] });+ expect(state.edit).not.toHaveBeenCalled();+});diff --git a/apps/web/src/routes/builder/letter/-components/write-panel.tsx b/apps/web/src/routes/builder/letter/-components/write-panel.tsxindex d7883f754..bd6009ba4 100644--- a/apps/web/src/routes/builder/letter/-components/write-panel.tsx+++ b/apps/web/src/routes/builder/letter/-components/write-panel.tsx@@ -561,7 +561,26 @@ function BodySection({ letter, application, disabled }: LetterSectionProps) {disabled={disabled}heightClassName="min-h-[240px]"improve={{ letter: true, applicationId: application?.id }}- onChange={(content) => edit({ content })}+ onChange={(content, options) => {+ const current = useLetterEditorStore.getState();+ if (+ getAccountGeneration() !== account ||+ current.sessionId !== sessionId ||+ current.letter?.id !== letter.id ||+ current.letter.isLocked+ )+ return;+ edit({+ content,+ ...(options?.aiOperationIds?.length || options?.removedAiOperationIds?.length+ ? {+ aiOperationIds: [+ ...new Set([...(current.letter.aiOperationIds ?? []), ...(options.aiOperationIds ?? [])]),+ ].filter((id) => !options.removedAiOperationIds?.includes(id)),+ }+ : {}),+ });+ }}/>) : (<EmptyBodydiff --git a/docs/guides/undoing-changes-and-version-history.mdx b/docs/guides/undoing-changes-and-version-history.mdxindex 95f33de95..eb14c16f1 100644--- a/docs/guides/undoing-changes-and-version-history.mdx+++ b/docs/guides/undoing-changes-and-version-history.mdx@@ -37,8 +37,12 @@ How undo behaves:- **Undo lasts while the resume is open.** Reloading the page or opening the resume again starts a fresh undo history.So does restoring a version, or a change arriving from somewhere else, such as another tab or an API client.-The cover letter editor has no document-wide undo. Use <kbd>⌘</kbd> <kbd>Z</kbd> inside the text you're editing, or-restore a version from History.+On web, the cover letter editor has no document-wide undo. Use <kbd>⌘</kbd> <kbd>Z</kbd> inside the text you're editing, or+restore a version from History. Native mobile uses its editor-bar Undo and Redo controls.++An accepted **Improve** suggestion is a separate step. Undo and Redo restore its request references with its wording,+including an accepted suggestion whose wording is unchanged. Earlier import or letter-draft sources stay attached.+These actions do not send another AI request; weekly usage still includes the original attempt.<Tip>Changes that couldn't be saved, for example because you went offline or closed the tab, are kept on your device. Thediff --git a/docs/guides/using-ai.mdx b/docs/guides/using-ai.mdxindex 4b128b2f1..9b3173d6b 100644--- a/docs/guides/using-ai.mdx+++ b/docs/guides/using-ai.mdx@@ -194,6 +194,8 @@ Saved workspace **Library** results and **Check → Writing** reviews show theirReviewed AI PDF and Word imports retain their sources in resume **History** on web and mobile, including owned copies and saved versions. Sources stay out of portable resume JSON and employer downloads. Older-server import results may have no recorded source; reading them again is not automatic. See [Importing a resume](/guides/importing-resumes#review-what-came-in).+**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.+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/writing-a-cover-letter.mdx b/docs/guides/writing-a-cover-letter.mdxindex 0f5f6bf9e..34abc8724 100644--- a/docs/guides/writing-a-cover-letter.mdx+++ b/docs/guides/writing-a-cover-letter.mdx@@ -175,12 +175,14 @@ is linked to an application), **Warmer** and **Shorter**. You can also open the<Frame caption="Web parity reference: review a paragraph against the linked posting before choosing Replace. Android and iPhone use the same canonical Improve service; this image is from the web editor."><imgsrc="/images/guides/writing-a-cover-letter/letter-improve-review.png"- alt="Web letter Improve review showing the fictional provider and fast model, original paragraph, suggested replacement and explicit Replace and Keep mine controls"+ alt="Web letter Improve review showing one recorded request attempt through the fictional provider and fast model, original paragraph, suggested replacement and explicit Replace and Keep mine controls"/></Frame>On Android and iPhone, place the caret in a body paragraph and choose **Improve selected line** in the formatting toolbar. The review panel offers **Warmer** and **Shorter**, plus **Tie to the posting** when the letter has a linked application. It identifies the provider/model and the paragraph, surrounding letter text and linked posting that may be sent. Choose a preset, review the suggestion, then select **Replace** or **Keep mine**. A replacement is its own Undo step. A changed paragraph or a closed editor prevents a late replacement; recipient fields keep their formatting tools without AI rewriting.+On web and native mobile, the reviewed suggestion also shows its recorded request attempts and original model. **Replace** keeps those references alongside any earlier body-draft sources. Undo and Redo restore the corresponding wording and references together. Keeping your paragraph, saving, reopening or undoing does not generate another suggestion. Removing the provider does not erase saved request history; an older server may return a usable suggestion with unavailable history.+## Match your resume's designBy default, a letter linked to a resume uses the resume's template, type and colors, so the two always look like a pair. When you change the resume's design, the letter follows.diff --git a/docs/images/guides/writing-a-cover-letter/letter-improve-review.png b/docs/images/guides/writing-a-cover-letter/letter-improve-review.pngindex 3f28f272f..67649c326 100644Binary files a/docs/images/guides/writing-a-cover-letter/letter-improve-review.png and b/docs/images/guides/writing-a-cover-letter/letter-improve-review.png differdiff --git a/docs/spec.json b/docs/spec.jsonindex 2ca8ca84a..39730360c 100644--- a/docs/spec.json+++ b/docs/spec.json@@ -11483,6 +11483,9 @@},"applicationId": {"type": "string"+ },+ "includeProvenance": {+ "type": "boolean"}},"required": [@@ -11510,6 +11513,62 @@},"addsFacts": {"type": "boolean"+ },+ "aiOperationIds": {+ "type": "array",+ "maxItems": 1000,+ "items": {+ "type": "string",+ "minLength": 1,+ "maxLength": 64+ }+ },+ "aiUsage": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "requests": {+ "type": "integer",+ "minimum": 0,+ "maximum": 9007199254740991+ },+ "models": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "providerId": {+ "type": "string"+ },+ "label": {+ "type": "string"+ },+ "provider": {+ "type": "string"+ },+ "model": {+ "type": "string"+ }+ },+ "required": [+ "providerId",+ "label",+ "provider",+ "model"+ ]+ }+ }+ },+ "required": [+ "requests",+ "models"+ ]+ },+ {+ "type": "null"+ }+ ]}},"required": [@@ -178045,6 +178104,9 @@},"applicationId": {"type": "string"+ },+ "includeProvenance": {+ "type": "boolean"}},"required": [@@ -178072,6 +178134,62 @@},"addsFacts": {"type": "boolean"+ },+ "aiOperationIds": {+ "type": "array",+ "maxItems": 1000,+ "items": {+ "type": "string",+ "minLength": 1,+ "maxLength": 64+ }+ },+ "aiUsage": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "requests": {+ "type": "integer",+ "minimum": 0,+ "maximum": 9007199254740991+ },+ "models": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "providerId": {+ "type": "string"+ },+ "label": {+ "type": "string"+ },+ "provider": {+ "type": "string"+ },+ "model": {+ "type": "string"+ }+ },+ "required": [+ "providerId",+ "label",+ "provider",+ "model"+ ]+ }+ }+ },+ "required": [+ "requests",+ "models"+ ]+ },+ {+ "type": "null"+ }+ ]}},"required": [diff --git a/packages/api/src/features/ai/router.ts b/packages/api/src/features/ai/router.tsindex c2aab42ab..a4a87176f 100644--- a/packages/api/src/features/ai/router.ts+++ b/packages/api/src/features/ai/router.ts@@ -13,7 +13,7 @@ import { atsReviewInputSchema, atsReviewOutputSchema, reviewResumeText } from ".import { improveInputSchema, improveLine, improveOutputSchema } from "./improve";import { reportAiContent } from "./reports";import { aiService, fileInputSchema } from "./service";-import { createAiUsage, readWeeklyAiUsage } from "./usage";+import { createAiUsage, readAiUsage, readWeeklyAiUsage } from "./usage";import { beginWritingReview, readWritingReview, saveWritingReview } from "./writing-review";/**@@ -257,9 +257,14 @@ export const aiRouter = {"Suggests a rewrite of one line of a resume or cover letter: a stronger verb, an added result, a shorter version, or the user's own request. Returns the new line, a short reason, and whether it states anything the input didn't, so the user can check it. Writes nothing. Requires authentication and AI credentials.",successDescription: "The suggested line.",})- .input(improveInputSchema)+ .input(improveInputSchema.extend({ includeProvenance: z.boolean().optional() })).use(aiRequestRateLimit)- .output(improveOutputSchema)+ .output(+ improveOutputSchema.extend({+ aiOperationIds: aiOperationIdsSchema.optional(),+ aiUsage: aiUsageSummarySchema.nullable().optional(),+ }),+ ).errors(aiErrors).handler(async ({ context, input, signal }) => {try {@@ -273,10 +278,11 @@ export const aiRouter = {const posting = application?.jobDescription?.slice(0, 12_000);signal?.throwIfAborted();- return await improveLine({- usage: createAiUsage(context.user.id, "improve", provider, async (tx) => {- if (application) await assertApplicationVersion(tx, context.user.id, application);- }),+ const usage = createAiUsage(context.user.id, "improve", provider, async (tx) => {+ if (application) await assertApplicationVersion(tx, context.user.id, application);+ });+ const result = await improveLine({+ usage,...input,posting,signal,@@ -285,6 +291,13 @@ export const aiRouter = {apiKey: provider.apiKey,baseURL: provider.baseURL ?? "",});+ return input.includeProvenance+ ? {+ ...result,+ aiOperationIds: [usage.operationId],+ aiUsage: await readAiUsage(context.user.id, [usage.operationId]),+ }+ : result;} catch (error) {rethrowAiError(error, "The AI returned suggestions in the wrong format. Try again, or choose another model.");}diff --git a/packages/api/src/features/ai/usage.integration.test.ts b/packages/api/src/features/ai/usage.integration.test.tsindex 9b3678528..665ad1ed9 100644--- a/packages/api/src/features/ai/usage.integration.test.ts+++ b/packages/api/src/features/ai/usage.integration.test.ts@@ -45,7 +45,18 @@ describe.skipIf(!databaseUrl)("AI request metering through installed SDK, proteclet pool: Pool;let baseURL: string;let user: typeof tables.user.$inferSelect;- let mode: "text" | "retry" | "tools" | "stream" | "failure" | "hold" | "reply" | "answer" | "writing" | "resume";+ let mode:+ | "text"+ | "retry"+ | "tools"+ | "stream"+ | "failure"+ | "hold"+ | "reply"+ | "answer"+ | "writing"+ | "resume"+ | "improve";let release = () => {};let arrived = () => {};let requests: { model: string; path: string }[] = [];@@ -81,27 +92,29 @@ describe.skipIf(!databaseUrl)("AI request metering through installed SDK, protec}const callsTool = mode === "tools" && requests.length === 1;const text =- mode === "resume"- ? JSON.stringify(sampleResumeData)- : mode === "writing"- ? JSON.stringify({- summary: "Fictional saved wording review",- strengths: [],- suggestions: [],- jdAlignment: null,- })- : mode === "answer"- ? JSON.stringify({ text: "Built a fictional reporting workflow.", factIds: [], note: null })- : mode === "reply"- ? JSON.stringify({- title: "Reply",- asks: [],- unconfirmed: [],- reply: "Thank you.",- changes: [],- offer: null,- })- : "done";+ mode === "improve"+ ? JSON.stringify({ text: "Led fictional reliable delivery.", why: "Uses a direct verb.", addsFacts: false })+ : mode === "resume"+ ? JSON.stringify(sampleResumeData)+ : mode === "writing"+ ? JSON.stringify({+ summary: "Fictional saved wording review",+ strengths: [],+ suggestions: [],+ jdAlignment: null,+ })+ : mode === "answer"+ ? JSON.stringify({ text: "Built a fictional reporting workflow.", factIds: [], note: null })+ : mode === "reply"+ ? JSON.stringify({+ title: "Reply",+ asks: [],+ unconfirmed: [],+ reply: "Thank you.",+ changes: [],+ offer: null,+ })+ : "done";res.writeHead(200, { "content-type": "application/json" });res.end(JSON.stringify({@@ -561,6 +574,41 @@ describe.skipIf(!databaseUrl)("AI request metering through installed SDK, protecexpect(requests).toHaveLength(1);}));+ it("returns opt-in Improve sources from actual transport records while preserving the default result contract", () =>+ run(async () => {+ const connection = await provider();+ const api = client();+ mode = "improve";+ const input = { action: "verb" as const, line: "Helped with fictional reliable delivery." };+ const legacy = await api.ai.improve(input);+ expect(legacy).toEqual({+ text: "Led fictional reliable delivery.",+ why: "Uses a direct verb.",+ addsFacts: false,+ });+ const result = await api.ai.improve({ ...input, includeProvenance: true });+ expect(result.aiOperationIds).toEqual([expect.any(String)]);+ expect(result.aiUsage).toEqual({+ requests: 1,+ models: [+ { providerId: connection.id, label: connection.label, provider: connection.provider, model: "fast-model" },+ ],+ });+ expect((await pool.query("select * from resume")).rows).toEqual([]);+ const id = await api.resume.import({ data: sampleResumeData });+ const current = await api.resume.getById({ id });+ const data = { ...current.data, summary: { ...current.data.summary, content: `<p>${result.text}</p>` } };+ const accepted = await api.resume.update({+ id,+ data,+ aiOperationIds: result.aiOperationIds,+ expectedUpdatedAt: current.updatedAt,+ });+ expect(accepted.aiUsage).toEqual(result.aiUsage);+ expect(accepted.data.summary.content).toBe(`<p>${result.text}</p>`);+ expect(requests).toHaveLength(2);+ }));+it("pairs reviewed resume imports with real request sources through old edits, copies, history, export and deletion", () =>run(async () => {const connection = await provider();diff --git a/tests/e2e/specs/ai-usage.spec.ts b/tests/e2e/specs/ai-usage.spec.tsindex 7cbdce0b2..0fdc84180 100644--- a/tests/e2e/specs/ai-usage.spec.ts+++ b/tests/e2e/specs/ai-usage.spec.ts@@ -2,6 +2,7 @@ import { readFile } from "node:fs/promises";import { strToU8, zipSync } from "fflate";import { approveLocalStubOperations } from "../fixtures/ai-consent";import { startAiStub } from "../fixtures/ai-stub";+import { createSampleResumeFromDashboard, openSidebarSection } from "../fixtures/resume";import { expect, test } from "../fixtures/test";let stub: Awaited<ReturnType<typeof startAiStub>>;@@ -15,6 +16,66 @@ test.afterAll(async () => {await stub?.close();});+test("reviewed resume Improve sources follow editor Undo/Redo, save and reload after provider deletion", async ({+ authPage: page,+}, info) => {+ test.skip(process.env.FLAG_ALLOW_UNSAFE_AI_BASE_URL !== "true", "Needs isolated local AI stub permission");+ await approveLocalStubOperations(page);+ const created = await page.request.post("/api/openapi/ai-providers", {+ data: {+ label: "Fictional Improve AI",+ provider: "openai-compatible",+ model: "improve-main",+ fastModel: "improve-fast",+ baseURL: stub.baseURL,+ apiKey: "stub-key",+ },+ });+ await expect(created).toBeOK();+ const { id: providerId } = await created.json();+ await expect(await page.request.post(`/api/openapi/ai-providers/${providerId}/test`)).toBeOK();+ await createSampleResumeFromDashboard(page, info);+ const id = page.url().split("/builder/")[1]?.split("?")[0];+ await openSidebarSection(page, "Summary");+ const summary = page.getByRole("textbox", { name: "Summary", exact: true });+ await summary.fill("Owned fictional delivery.");+ await summary.press("End");+ const before = stub.requests.length;+ await page.getByRole("button", { name: "Improve", exact: true }).click();+ await page.getByRole("button", { name: "Stronger verb", exact: true }).click();+ await expect(page.getByText("Led fictional delivery work.", { exact: true })).toBeVisible();+ await expect(+ page.getByText("Fictional Improve AI · openai-compatible · improve-fast", { exact: true }),+ ).toBeVisible();+ expect((await (await page.request.get(`/api/openapi/resumes/${id}`)).json()).aiOperationIds).toEqual([]);+ await page.getByRole("button", { name: "Replace", exact: true }).click();+ const read = async () => await (await page.request.get(`/api/openapi/resumes/${id}`)).json();+ await expect.poll(read).toMatchObject({ aiOperationIds: [expect.any(String)], aiUsage: { requests: 1 } });+ const accepted = await read();+ expect(accepted.data.summary.content).toContain("Led fictional delivery work.");+ await summary.press("ControlOrMeta+z");+ await expect(summary).toHaveText("Owned fictional delivery.");+ await expect.poll(read).toMatchObject({+ aiOperationIds: [],+ data: { summary: { content: expect.stringContaining("Owned fictional delivery.") } },+ });+ await summary.press("ControlOrMeta+Shift+z");+ await expect.poll(read).toMatchObject({+ aiOperationIds: accepted.aiOperationIds,+ aiUsage: { requests: 1 },+ data: { summary: { content: expect.stringContaining("Led fictional delivery work.") } },+ });+ await expect(await page.request.delete(`/api/openapi/ai-providers/${providerId}`)).toBeOK();+ await page.reload();+ await page.getByRole("button", { name: "History", exact: true }).click();+ const history = page.getByRole("dialog", { name: "Download & history" });+ await expect(history.getByText("AI request attempts: 1", { exact: true })).toBeVisible();+ await expect(+ history.getByText("Fictional Improve AI · openai-compatible · improve-fast", { exact: true }),+ ).toBeVisible();+ expect(stub.requests.length - before).toBe(1);+});+test("reviewed Word import retains its original request source in resume History after connection deletion", async ({authPage: page,}, testInfo) => {@@ -127,6 +188,8 @@ test("letter Improve reviews an owned posting paragraph through the canonical seconst before = stub.requests.length;await body.getByRole("button", { name: "Tie to the posting", exact: true }).click();await expect(body.getByText("Led fictional delivery work.", { exact: true })).toBeVisible();+ await expect(body.getByText("AI request attempts: 1", { exact: true })).toBeVisible();+ await expect(body.getByText("Fictional Letter AI · openai-compatible · letter-fast", { exact: true })).toBeVisible();expect(stub.requests.length - before).toBe(1);const request = stub.requests.at(-1);expect(request?.model).toBe("letter-fast");@@ -142,6 +205,25 @@ test("letter Improve reviews an owned posting paragraph through the canonical seawait expect(body.getByRole("textbox", { name: "Letter body", exact: true })).toHaveText("Led fictional delivery work.",);+ const read = async () => await (await page.request.get(`/api/openapi/cover-letters/${id}`)).json();+ await expect.poll(read).toMatchObject({ aiOperationIds: [expect.any(String)], aiUsage: { requests: 1 } });+ const accepted = await read();+ const editor = body.getByRole("textbox", { name: "Letter body", exact: true });+ await editor.press("ControlOrMeta+z");+ await expect(editor).toHaveText("I maintain reliable services.");+ await expect+ .poll(read)+ .toMatchObject({ aiOperationIds: [], content: expect.stringContaining("I maintain reliable services.") });+ await editor.press("ControlOrMeta+Shift+z");+ await expect.poll(read).toMatchObject({+ aiOperationIds: accepted.aiOperationIds,+ aiUsage: { requests: 1 },+ content: expect.stringContaining("Led fictional delivery work."),+ });+ await expect(await page.request.delete(`/api/openapi/ai-providers/${providerId}`)).toBeOK();+ await page.reload();+ await expect(body.getByText("Fictional Letter AI · openai-compatible · letter-fast", { exact: true })).toBeVisible();+ expect(stub.requests.length - before).toBe(1);});test("letter Accept saves the displayed version's original model and request source", async ({