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
fix(career): persist workspace answer removal and safe Undo
Amruth Pillai2d97d1db226e
diff --git a/apps/mobile/scripts/application-review.test.mjs b/apps/mobile/scripts/application-review.test.mjsindex fa44188f1..7c9fc9041 100644--- a/apps/mobile/scripts/application-review.test.mjs+++ b/apps/mobile/scripts/application-review.test.mjs@@ -75,6 +75,7 @@ function load(data, overrides = {}) {"../state": {},"@/api/client": { orpc: { career: { submitApplication: { mutationOptions: () => ({}) } } } },"@/draft": {},+ "@/auth/session": { getAccountScope: () => "fixture" },"@/features/ai/providers": {},"@/features/application-detail/sections": {},"@/features/applications/prior-no-response": { PriorNoResponse: "PriorNoResponse" },diff --git a/apps/mobile/scripts/career-undo.test.mjs b/apps/mobile/scripts/career-undo.test.mjsindex 17a678719..58cbeed49 100644--- a/apps/mobile/scripts/career-undo.test.mjs+++ b/apps/mobile/scripts/career-undo.test.mjs@@ -75,6 +75,7 @@ function harness() {const options = (preparing) => ({message: "Fact forgotten",prepare: () => preparing,+ onReady: () => {},commit: (result) => result,restore: () => {env.restored++;@@ -248,11 +249,12 @@ async function rowsHarness() {return (cells[i] ??= { current: initial });},useLayoutEffect: (run) => run(),- useEffect: (run) => {+ useEffect: (run, deps) => {const i = cursor++;- if (!(i in cells)) {- cells[i] = true;- cleanup.push(run());+ if (!(i in cells) || deps.some((value, j) => value !== cells[i][j])) {+ cleanup[i]?.();+ cells[i] = deps;+ cleanup[i] = run();}},};@@ -285,9 +287,10 @@ const drain = () => new Promise((resolve) => setImmediate(resolve));test("actual native row Undo waits for canonical readback; failed read keeps stale private text hidden until Retry", async () => {const h = await rowsHarness();const preparing = h.request();- h.render().remove("fact", "Fact forgotten", () => preparing);- assert.deepEqual(h.render().hidden, ["fact"]);+ h.render().remove("fact", "Fact forgotten", () => preparing, h.key);+ assert.deepEqual(h.render().hidden, []);await preparing;+ assert.deepEqual(h.render().hidden, ["fact"]);h.env.canonical = [];h.env.offline = true;h.notices[0].action.onPress();@@ -324,3 +327,43 @@ test("actual native row navigation flushes a prepared deletion synchronously andawait drain();h.queryClient.clear();});++test("actual native rows discard hidden IDs when account changes before commit, and returning account sees survivor", async () => {+ const h = await rowsHarness();+ const preparing = h.request();+ h.render().remove("fact", "Fact forgotten", () => preparing, h.key);+ await preparing;+ assert.deepEqual(h.render().hidden, ["fact"]);+ h.env.account = "bob";+ h.render();+ h.background();+ await drain();+ h.env.account = "alice";+ h.render();+ assert.deepEqual(h.render().hidden, []);+ assert.equal(h.env.sent, 0);+ assert.equal(h.queryClient.getQueryData(h.key)[0].id, "fact");+ h.unmount();+ h.queryClient.clear();+});++test("actual native Undo reveals canonical list even while an unrelated Career endpoint fails", async () => {+ const h = await rowsHarness();+ await h.queryClient+ .fetchQuery({+ queryKey: ["career", "stories"],+ queryFn: () => {+ throw new Error("unrelated unavailable");+ },+ })+ .catch(() => {});+ const preparing = h.request();+ h.render().remove("fact", "Fact forgotten", () => preparing, h.key);+ await preparing;+ h.notices[0].action.onPress();+ await drain();+ assert.deepEqual(h.render().hidden, []);+ assert.equal(h.env.sent, 0);+ h.unmount();+ h.queryClient.clear();+});diff --git a/apps/mobile/scripts/experience.test.mjs b/apps/mobile/scripts/experience.test.mjsindex 59fa9834a..531484ea6 100644--- a/apps/mobile/scripts/experience.test.mjs+++ b/apps/mobile/scripts/experience.test.mjs@@ -96,6 +96,16 @@ ui.useFirstAppearance = () => false;ui.useReducedMotion = () => false;const mocks = {"@lingui/core": { i18n },+ "@/api/client": {+ orpc: {+ career: Object.fromEntries(+ ["facts", "stories", "savedItems", "notifications", "opportunities", "schedules"].map((name) => [+ name,+ { key: () => ["career", name] },+ ]),+ ),+ },+ },"@/shell/shortcut-help": {ShortcutHelpButton: "ShortcutHelpButton",CharacterShortcutSetting: "CharacterShortcutSetting",@@ -469,7 +479,6 @@ const nativeInterviewCalendar = load("features/application-detail/calendar.ts",});let applicationDocuments = [];let rejectDocumentLink = false;-let creatingApplicationLetter = false;let stageUpdate = (input) => calls.push(input);let stageUpdateAsync = (input) =>new Promise((resolve, reject) => stageUpdate(input, { onSuccess: resolve, onError: reject }));@@ -486,12 +495,7 @@ const { StageStepper, NextStepCard, WhatYouSent, Timeline } = load("features/app"./notes-queue": { createNotesQueue: () => ({}) },"./hooks": {useDocuments: () => ({ data: applicationDocuments }),- useDetailMutations: () => ({- createLetter: { isPending: creatingApplicationLetter },- addNote: {},- updateEntry: {},- deleteEntry: {},- }),+ useDetailMutations: () => ({ addNote: {}, updateEntry: {}, deleteEntry: {} }),useNow: () => new Date(),useUserTime: () => time,followUpReminder: () => null,@@ -856,11 +860,18 @@ assert.deepEqual(calls.filter((call) => call?.documentLink).at(-1).documentLink,id: "existing-letter",applicationId: "job-a",});-creatingApplicationLetter = true;-tree = render(WhatYouSent, { application });-assert.equal(control(tree, "Use Fictional Cedar — Portfolio · Resume").disabled, true);-assert.equal(control(tree, "Use an existing letter").disabled, true);-creatingApplicationLetter = false;+for (const resumeId of [null, "resume-for-letter"]) {+ tree = render(WhatYouSent, { application: { ...application, resumeId } });+ control(tree, "Write a letter").onPress();+ assert.deepEqual(+ calls.at(-1),+ {+ pathname: "/new",+ params: { context: "letters", applicationId: "job-a", ...(resumeId ? { sourceResumeId: resumeId } : {}) },+ },+ "Letter creation opens the reusable document picker with this job and its linked resume",+ );+}applicationDocuments = [];console.log("PASS native company-matched resume/letter selection, revision guard, pending state and failed-link retry");diff --git a/apps/mobile/scripts/layout.test.mjs b/apps/mobile/scripts/layout.test.mjsindex df608f4f0..27f27e611 100644--- a/apps/mobile/scripts/layout.test.mjs+++ b/apps/mobile/scripts/layout.test.mjs@@ -576,6 +576,9 @@ const librarySession = load("features/documents/library-session.ts", {"@/auth/session": { getAccountScope: () => libraryAccountScope },});const { DocumentsLibrary } = load("features/documents/library.tsx", {+ "@reactive-resume/schema/applications/document-groups": load(+ "../../../packages/schema/src/applications/document-groups.ts",+ ),"./library-session": librarySession,"@legendapp/list/reanimated": { AnimatedLegendList: "FlatList" },"./document-sheets": { DocumentSheets: "DocumentSheets" },@@ -737,7 +740,7 @@ const sheetDocument = { type: "resume", id: "restore-sheet", trashedAt: new DatedocumentQuery = { ...originalDocumentQuery, data: { ...originalDocumentQuery.data, items: [sheetDocument], total: 1 } };render(DocumentsLibrary, { trashed: true });let trashList = nodes(render(DocumentsLibrary, { trashed: true })).find((node) => node.type === "FlatList");-const trashItem = trashList.props.renderItem({ item: sheetDocument, index: 0 });+const trashItem = trashList.props.renderItem({ item: trashList.props.data[0], index: 0 });// Row body is wrapped by the motion frame; its menu opens the sheet owned by DocumentsLibrary.nodes(trashItem).find((node) => typeof node.props.onMenu === "function")diff --git a/apps/mobile/scripts/power-user-repairs.test.mjs b/apps/mobile/scripts/power-user-repairs.test.mjsindex 5a3ac147f..67291f636 100644--- a/apps/mobile/scripts/power-user-repairs.test.mjs+++ b/apps/mobile/scripts/power-user-repairs.test.mjs@@ -76,6 +76,16 @@ const routes = {trash: () => "/documents/trash",};const common = {+ "@/api/client": {+ orpc: {+ career: Object.fromEntries(+ ["facts", "stories", "savedItems", "notifications", "opportunities", "schedules"].map((name) => [+ name,+ { key: () => ["career", name] },+ ]),+ ),+ },+ },"@/shell/shortcut-help": {ShortcutHelpButton: "ShortcutHelpButton",CharacterShortcutSetting: "CharacterShortcutSetting",diff --git a/apps/mobile/scripts/workspace-answer-undo.test.mjs b/apps/mobile/scripts/workspace-answer-undo.test.mjsnew file mode 100644index 000000000..e44ed1b92--- /dev/null+++ b/apps/mobile/scripts/workspace-answer-undo.test.mjs@@ -0,0 +1,383 @@+import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import { createRequire } from "node:module";+import { test } from "node:test";+import { i18n } from "@lingui/core";+i18n.loadAndActivate({ locale: "en-US", messages: {} });+const requireServer = createRequire(new URL("../../server/package.json", import.meta.url));+const { transformSync } = createRequire(requireServer.resolve("tsx"))("esbuild");+const { QueryClient } = createRequire(new URL("../package.json", import.meta.url))("@tanstack/react-query");+function load(path, mocks, timers = {}) {+ const module = { exports: {} };+ const code = transformSync(readFileSync(new URL(path, import.meta.url), "utf8"), {+ loader: path.endsWith("tsx") ? "tsx" : "ts",+ format: "cjs",+ jsx: "automatic",+ }).code;+ new Function("require", "module", "exports", "setTimeout", "clearTimeout", code)(+ (name) => {+ assert.ok(name in mocks, name);+ return mocks[name];+ },+ module,+ module.exports,+ timers.set,+ timers.clear,+ );+ return module.exports;+}+const { prepareRequest } = load("../../../packages/utils/src/deferred-request.ts", {});+const deferred = () => {+ let resolve;+ const promise = new Promise((done) => {+ resolve = done;+ });+ return { promise, resolve };+};+const drain = () => new Promise((resolve) => setImmediate(resolve));+const tag = (parts, ...values) => parts.reduce((out, part, index) => out + part + (values[index] ?? ""), "");+const empty = { answers: [], checklist: [], questions: [], evidence: {}, ticks: {}, message: "" };+const target = { id: "first", question: "Fictional first question", answer: "Original answer", factIds: [] };+const second = { ...target, id: "second", question: "Fictional second question" };++async function harness() {+ const env = {+ account: "alice",+ backend: { ...empty, answers: [target, second] },+ offline: false,+ holdSave: null,+ heldRead: null,+ reads: 0,+ deletions: [],+ notices: [],+ };+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: Infinity } } });+ const key = ["career", "workspace", "job", "fixture"];+ const query = {+ queryKey: key.slice(0, -1),+ queryFn: async () => {+ env.reads++;+ if (env.offline) throw new Error("offline");+ if (env.heldRead) {+ const held = env.heldRead;+ env.heldRead = null;+ return held.promise;+ }+ return env.backend;+ },+ };+ await queryClient.fetchQuery({ ...query, queryKey: key });+ const cells = [];+ const cleanups = [];+ const listeners = new Set();+ const timers = new Map();+ let cursor = 0;+ let serial = 0;+ const react = {+ useState: (initial) => {+ const i = cursor++;+ if (!(i in cells)) cells[i] = typeof initial === "function" ? initial() : initial;+ return [+ cells[i],+ (next) => {+ cells[i] = typeof next === "function" ? next(cells[i]) : next;+ },+ ];+ },+ useRef: (initial) => {+ const i = cursor++;+ return (cells[i] ??= { current: initial });+ },+ useCallback: (fn) => fn,+ useLayoutEffect: (run) => run(),+ useEffect: (run) => {+ const i = cursor++;+ if (!(i in cells)) {+ cells[i] = true;+ cleanups.push(run());+ }+ },+ };+ const AppState = {+ currentState: "active",+ addEventListener: (_event, run) => {+ listeners.add(run);+ return { remove: () => listeners.delete(run) };+ },+ };+ const ui = {+ showToast: (notice) => {+ env.notices.push(notice);+ return env.notices.length;+ },+ dismissToast: () => {},+ toastLifetime: (value) => value,+ useTheme: () => ({ space: {} }),+ };+ const session = {+ getAccountScope: () => env.account,+ getServer: () => "fixture",+ useSession: () => ({ server: "fixture", status: "signed-in" }),+ };+ const client = {+ career: {+ deleteWorkspaceAnswer: async (input) => {+ env.deletions.push(input);+ assert.equal(input.applicationId, "job");+ assert.deepEqual(+ input.expected,+ env.backend.answers.find((answer) => answer.id === input.id),+ );+ env.backend = { ...env.backend, answers: env.backend.answers.filter((answer) => answer.id !== input.id) };+ return env.backend;+ },+ },+ };+ const orpc = {+ career: {+ workspace: { queryOptions: () => query, queryKey: () => query.queryKey },+ saveWorkspace: {+ mutationOptions: () => ({+ mutationFn: async (input) => {+ if (env.holdSave) await env.holdSave.promise;+ env.backend = { ...env.backend, answers: input.answers };+ return env.backend;+ },+ }),+ },+ },+ };+ const api = {+ client,+ orpc,+ SessionChangedError: Error,+ prepareRpc: (procedure, input) =>+ prepareRequest((defer) => defer(() => Promise.resolve(procedure(input)).then((value) => Response.json(value)))),+ };+ const queryHooks = {+ useQueryClient: () => queryClient,+ useQuery: () => ({ data: queryClient.getQueryData(key), isPending: false }),+ useMutation: (options) => ({ mutateAsync: (input) => options.mutationFn(input) }),+ };+ const hooks = load("../src/features/workspace/hooks.ts", {+ "@lingui/core/macro": { t: tag },+ "@lingui/react/macro": { useLingui: () => ({ t: tag }) },+ "@orpc/client": { ORPCError: Error },+ "@tanstack/react-query": queryHooks,+ "expo-sqlite/kv-store": {},+ react,+ "react-native": { AppState },+ "@reactive-resume/schema/career": { EMPTY_WORKSPACE: empty },+ "./state": { createDraftStore: () => ({}) },+ "@/api/client": api,+ "@/auth/session": session,+ "@/draft": {},+ "@/features/ai/providers": {},+ "@/ui": ui,+ });+ const undo = load(+ "../src/features/career/undo.ts",+ {+ "@lingui/core/macro": { t: tag },+ "react-native": { AppState },+ "@/auth/session": session,+ "@/ui": ui,+ },+ {+ set: (run) => {+ const id = ++serial;+ timers.set(id, run);+ return id;+ },+ clear: (id) => timers.delete(id),+ },+ );+ const jsx = (type, props) => ({ type, props });+ const apply = load("../src/features/workspace/tabs/apply.tsx", {+ "@lingui/core": { i18n },+ "@lingui/core/macro": {+ ph: (named) => Object.values(named)[0],+ plural: (count, forms) => forms[count === 1 ? "one" : "other"].replace("#", String(count)),+ },+ "@lingui/react/macro": { useLingui: () => ({ t: tag }) },+ "@tanstack/react-query": queryHooks,+ "expo-clipboard": {},+ "expo-crypto": {},+ "expo-router": { useRouter: () => ({}) },+ react,+ "react/jsx-runtime": { jsx, jsxs: jsx },+ "react-native": { View: "View" },+ "@reactive-resume/schema/application-answers": {},+ "@reactive-resume/schema/applications/data": { hasApplicationSubmission: () => false },+ "@reactive-resume/schema/applications/preparation": {},+ "@reactive-resume/schema/career": {},+ "@reactive-resume/utils/string": {},+ "../answer-library": {},+ "../hooks": { ...hooks, useSavedItems: () => ({ data: [], isPending: false }), useFacts: () => ({ data: [] }) },+ "../logic": {},+ "../parts": {},+ "../preparation": {},+ "../share": {},+ "../shell": { WorkspaceScreen: "WorkspaceScreen" },+ "@/api/client": api,+ "@/auth/session": session,+ "@/features/ai/providers": {},+ "@/features/application-detail/sections": {},+ "@/features/applications/prior-no-response": {},+ "@/features/applications/queries": {},+ "@/features/career/undo": undo,+ "@/features/documents/queries": {},+ "@/routes": {},+ "@/ui": ui,+ });+ const props = { application: { id: "job", company: "Fictional Northwind", activity: [] }, go() {} };+ const entry = apply.ApplyTab().props.children(props);+ const render = () => {+ cursor = 0;+ return entry.type(entry.props);+ };+ const nodes = (node) =>+ !node || typeof node !== "object"+ ? []+ : Array.isArray(node)+ ? node.flatMap(nodes)+ : [node, ...nodes(node.props?.children)];+ const cards = () => nodes(render()).filter((node) => node.props?.answer && node.props?.onRemove);+ const remove = () => {+ const row = cards().find((card) => card.props.answer.id === "first");+ assert.ok(row);+ row.props.onRemove();+ };+ return {+ env,+ queryClient,+ key,+ timers,+ listeners,+ hooks,+ remove,+ cards,+ background: () => {+ AppState.currentState = "background";+ for (const listener of listeners) listener("background");+ },+ unmount: () => cleanups.forEach((run) => run?.()),+ };+}++test("actual native question removal awaits queued workspace saves, then background sends only one answer synchronously", async () => {+ const h = await harness();+ h.env.holdSave = deferred();+ const write = h.hooks.useWorkspace("job").save({+ answers: [+ { ...target, answer: "Newer target answer" },+ { ...second, answer: "Newer independent answer" },+ ],+ });+ h.remove();+ h.remove();+ assert.ok(+ h.cards().some((row) => row.props.answer.id === "first"),+ "No removal acknowledgement before preparation",+ );+ assert.equal(h.env.notices.length, 0);+ assert.equal(h.env.deletions.length, 0);+ h.env.holdSave.resolve();+ await write;+ await drain();+ assert.equal(h.env.notices[0].action.label, "Undo");+ h.background();+ assert.equal(h.env.deletions.length, 1, "transport begins within background callback");+ assert.equal(h.env.deletions[0].expected.answer, "Newer target answer");+ await drain();+ assert.equal(h.env.backend.answers[0].answer, "Newer independent answer");+ assert.equal(h.cards().length, 1);+ h.unmount();+ h.queryClient.clear();+});++test("actual native question Undo keeps stale data hidden after a failed read; Retry cannot resurrect external erasure", async () => {+ const h = await harness();+ h.remove();+ await drain();+ h.env.backend = { ...h.env.backend, answers: [second] };+ h.env.offline = true;+ h.env.notices[0].action.onPress();+ await drain();+ assert.equal(+ h.cards().some((card) => card.props.answer.id === "first"),+ false,+ );+ assert.equal(h.env.deletions.length, 0);+ assert.equal(h.env.notices.at(-1).action.label, "Retry");+ h.env.offline = false;+ h.env.notices.at(-1).action.onPress();+ await drain();+ assert.deepEqual(h.queryClient.getQueryData(h.key).answers, [second]);+ assert.equal(+ h.cards().some((card) => card.props.answer.id === "first"),+ false,+ );+ h.unmount();+ h.queryClient.clear();+});++test("native confirmed workspace fetch cancels an older in-flight response before reading post-deletion state", async () => {+ const h = await harness();+ const old = deferred();+ h.env.heldRead = old;+ const previous = h.queryClient+ .fetchQuery({+ queryKey: h.key,+ queryFn: async () => {+ h.env.heldRead = null;+ return old.promise;+ },+ })+ .catch(() => undefined);+ h.env.backend = { ...h.env.backend, answers: [second] };+ const reading = h.hooks.useWorkspace("job").fetchConfirmed();+ await drain();+ old.resolve({ ...empty, answers: [target, second] });+ await previous;+ const confirmed = await reading;+ await drain();+ assert.deepEqual(confirmed.answers, [second]);+ assert.deepEqual(h.queryClient.getQueryData(h.key).answers, [second]);+ h.unmount();+ h.queryClient.clear();+});++test("native pending question removal cannot dispatch under a replacement account", async () => {+ const h = await harness();+ h.env.holdSave = deferred();+ const write = h.hooks.useWorkspace("job").save({ answers: [target, second] });+ h.remove();+ h.env.account = "bob";+ h.env.holdSave.resolve();+ await write;+ await drain();+ h.background();+ assert.equal(h.env.deletions.length, 0);+ assert.equal(h.env.notices.length, 0);+ h.unmount();+ h.queryClient.clear();+});++test("actual native question unmount during preparation flushes once after its queued save settles", async () => {+ const h = await harness();+ h.env.holdSave = deferred();+ const writing = h.hooks.useWorkspace("job").save({ answers: [target, second] });+ h.remove();+ h.unmount();+ assert.equal(h.env.deletions.length, 0);+ h.env.holdSave.resolve();+ await writing;+ await drain();+ assert.equal(h.env.deletions.length, 1);+ assert.equal(h.env.deletions[0].id, "first");+ assert.deepEqual(h.env.backend.answers, [second]);+ assert.equal(h.timers.size, 0);+ assert.equal(h.listeners.size, 0);+ h.queryClient.clear();+});diff --git a/apps/mobile/src/features/career/facts.tsx b/apps/mobile/src/features/career/facts.tsxindex b0349bce0..41047a9cc 100644--- a/apps/mobile/src/features/career/facts.tsx+++ b/apps/mobile/src/features/career/facts.tsx@@ -13,6 +13,7 @@ import { categoryLabel, factCategories } from "./fact-categories";import { client, prepareRpc, useCareerAction, useCareerQueries, useCareerTime, useUndoRows } from "./hooks";import { ResumeFacts } from "./resume-facts";import { Actions, EditorSheet, LoadState, SwitchRow } from "./shared";+import { orpc } from "@/api/client";import { getServer, useSession } from "@/auth/session";import {Banner,@@ -107,8 +108,11 @@ export function Facts({ children, onRefresh }: FactsProps) {onSource: setSource,onCorrect: (fact) => setEditor({ fact }),onForget: (fact) =>- latest.current.remove(fact.id, latest.current.forgotten, () =>- prepareRpc(client.career.forgetFact, { id: fact.id }),+ latest.current.remove(+ fact.id,+ latest.current.forgotten,+ () => prepareRpc(client.career.forgetFact, { id: fact.id }),+ orpc.career.facts.key(),),}));const renderItem = useCallback(diff --git a/apps/mobile/src/features/career/hooks.ts b/apps/mobile/src/features/career/hooks.tsindex 3aee1ab94..abe030377 100644--- a/apps/mobile/src/features/career/hooks.ts+++ b/apps/mobile/src/features/career/hooks.ts@@ -1,5 +1,6 @@import type { RouterOutput } from "@/api/client";import type { PreparedRequest } from "@reactive-resume/utils/deferred-request";+import type { QueryKey } from "@tanstack/react-query";import { useLingui } from "@lingui/react/macro";import { ORPCError } from "@orpc/client";import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";@@ -185,6 +186,12 @@ export function useUndoRows() {const queryClient = useQueryClient();const session = useSession();const [hidden, setHidden] = useState<string[]>([]);+ const accountScope = getAccountScope();+ const [hiddenScope, setHiddenScope] = useState(accountScope);+ if (hiddenScope !== accountScope) {+ setHiddenScope(accountScope);+ setHidden([]);+ }const pending = useRef(new Map<string, ReturnType<typeof withUndo>>());const active = useRef(session);useLayoutEffect(() => {@@ -200,24 +207,28 @@ export function useUndoRows() {}operations.clear();};- }, [session.server]);- const remove = (id: string, message: string, prepare: () => Promise<PreparedRequest<unknown>>) => {+ }, [session.server, accountScope]);+ const remove = (+ id: string,+ message: string,+ prepare: () => Promise<PreparedRequest<unknown>>,+ queryKey: QueryKey,+ ) => {if (pending.current.has(id)) return;const server = session.server;const scope = getAccountScope();const current = () =>getAccountScope() === scope && getServer() === server && active.current.status === "signed-in";- setHidden((rows) => [...rows, id]);const reconcile = async () => {try {if (!current()) return;- await queryClient.cancelQueries({ queryKey: orpc.career.key() });+ await queryClient.cancelQueries({ queryKey });if (!current()) return;- await queryClient.invalidateQueries(- { queryKey: orpc.career.key(), refetchType: "all" },- { throwOnError: true },- );- if (current()) setHidden((rows) => rows.filter((value) => value !== id));+ await queryClient.invalidateQueries({ queryKey, refetchType: "all" }, { throwOnError: true });+ if (current()) {+ setHidden((rows) => rows.filter((value) => value !== id));+ void action.refresh();+ }} finally {pending.current.delete(id);}@@ -237,6 +248,7 @@ export function useUndoRows() {const operation = withUndo({message,prepare,+ onReady: () => setHidden((rows) => [...rows, id]),restore: reconcile,failed,commit: (result) =>diff --git a/apps/mobile/src/features/career/offers.tsx b/apps/mobile/src/features/career/offers.tsxindex cd9e3ee17..8f843feee 100644--- a/apps/mobile/src/features/career/offers.tsx+++ b/apps/mobile/src/features/career/offers.tsx@@ -14,6 +14,7 @@ import { formatBonus, formatMoney, matchingPlace, meetsMinimum, moneyDifference,import { OfferEntry, OfferForm } from "./offer-entry";import { consumeSavedOffer, useSavedOffer } from "./offer-selection";import { Actions, LoadState } from "./shared";+import { orpc } from "@/api/client";import { getAccountScope } from "@/auth/session";import { useApplications } from "@/features/applications/queries";import { routes } from "@/routes";@@ -38,7 +39,12 @@ export function OffersScreen() {);// Deleting waits out its Undo toast, as everywhere else saved work is deleted.const remove = (offer: Offer) => {- undo.remove(offer.id, t`Offer deleted`, () => prepareRpc(client.career.deleteSavedItem, { id: offer.id }));+ undo.remove(+ offer.id,+ t`Offer deleted`,+ () => prepareRpc(client.career.deleteSavedItem, { id: offer.id }),+ orpc.career.savedItems.key(),+ );};const params = useLocalSearchParams<{ a?: string; b?: string; highlight?: string }>();const focused = useIsFocused();diff --git a/apps/mobile/src/features/career/stories.tsx b/apps/mobile/src/features/career/stories.tsxindex 7cd764cf9..75dad7862 100644--- a/apps/mobile/src/features/career/stories.tsx+++ b/apps/mobile/src/features/career/stories.tsx@@ -9,6 +9,7 @@ import Animated from "react-native-reanimated";import { careerStoryInputSchema } from "@reactive-resume/schema/career";import { client, prepareRpc, useCareerAction, useCareerQueries, useUndoRows } from "./hooks";import { Actions, EditorSheet, LoadState, SwitchRow } from "./shared";+import { orpc } from "@/api/client";import {Banner,Button,@@ -90,8 +91,11 @@ export function Stories() {label={t`Delete story`}variant="ghost"onPress={() =>- undo.remove(story.id, t`Story deleted`, () =>- prepareRpc(client.career.deleteStory, { id: story.id }),+ undo.remove(+ story.id,+ t`Story deleted`,+ () => prepareRpc(client.career.deleteStory, { id: story.id }),+ orpc.career.stories.key(),)}/>diff --git a/apps/mobile/src/features/career/today.tsx b/apps/mobile/src/features/career/today.tsxindex a04826fce..ce0adfc75 100644--- a/apps/mobile/src/features/career/today.tsx+++ b/apps/mobile/src/features/career/today.tsx@@ -23,6 +23,7 @@ import {import { ScheduleSheet, scheduleTitle } from "./schedule-sheet";import { rollForward } from "./scheduling";import { Actions, LoadState, Section, SwitchRow } from "./shared";+import { orpc } from "@/api/client";import { useApplicationLanes } from "@/features/applications/lane-queries";import { getLaneLabel, resolveLane } from "@/features/applications/lanes";import {@@ -344,8 +345,11 @@ export function TodayScreen() {label={t`Mark as read`}variant="ghost"onPress={() =>- undo.remove(row.id, t`Marked as read`, () =>- prepareRpc(client.career.markNotificationRead, { id: row.id }),+ undo.remove(+ row.id,+ t`Marked as read`,+ () => prepareRpc(client.career.markNotificationRead, { id: row.id }),+ orpc.career.notifications.key(),)}/>@@ -478,8 +482,11 @@ export function TodayScreen() {label={t`Track in Applications`}disabled={action.pending}onPress={() =>- undo.remove(row.id, t`Saved to Applications with the posting`, () =>- prepareRpc(client.career.trackOpportunity, { id: row.id }),+ undo.remove(+ row.id,+ t`Saved to Applications with the posting`,+ () => prepareRpc(client.career.trackOpportunity, { id: row.id }),+ orpc.career.opportunities.key(),)}/>@@ -498,8 +505,11 @@ export function TodayScreen() {label={t`Not for me`}disabled={action.pending}onPress={() =>- undo.remove(row.id, t`Hidden from New roles`, () =>- prepareRpc(client.career.dismissOpportunity, { id: row.id }),+ undo.remove(+ row.id,+ t`Hidden from New roles`,+ () => prepareRpc(client.career.dismissOpportunity, { id: row.id }),+ orpc.career.opportunities.key(),)}/>@@ -580,7 +590,12 @@ export function TodayScreen() {{...sheet}onClose={() => setSheet(null)}onDelete={(id) =>- undo.remove(id, t`Schedule deleted`, () => prepareRpc(client.career.deleteSchedule, { id }))+ undo.remove(+ id,+ t`Schedule deleted`,+ () => prepareRpc(client.career.deleteSchedule, { id }),+ orpc.career.schedules.key(),+ )}/>) : null}diff --git a/apps/mobile/src/features/career/undo.ts b/apps/mobile/src/features/career/undo.tsindex c911ab71a..778d4e588 100644--- a/apps/mobile/src/features/career/undo.ts+++ b/apps/mobile/src/features/career/undo.ts@@ -8,7 +8,7 @@ type UndoNotice = { message: string; restore: () => unknown; failed: () => voidtype UndoOptions<T> = UndoNotice &(| { commit: () => Promise<unknown> }- | { prepare: () => Promise<PreparedRequest<T>>; commit: (result: Promise<T>) => unknown }+ | { prepare: () => Promise<PreparedRequest<T>>; onReady: () => void; commit: (result: Promise<T>) => unknown });/** Prepared requests reach the transport in the background event's stack, before JS can suspend. */@@ -37,6 +37,7 @@ export function withUndo<T>(options: UndoOptions<T>) {if (intent === "cancel") void restore(true);return;}+ options.onReady();operation = showUndo({message: options.message,commit: () => {diff --git a/apps/mobile/src/features/workspace/hooks.ts b/apps/mobile/src/features/workspace/hooks.tsindex 968b9502b..267b3e308 100644--- a/apps/mobile/src/features/workspace/hooks.ts+++ b/apps/mobile/src/features/workspace/hooks.ts@@ -111,6 +111,7 @@ export function useWorkspace(applicationId: string) {*/fetchConfirmed: async () => {while (pending.size > 0) await Promise.allSettled(pending);+ await queryClient.cancelQueries({ queryKey });return queryClient.fetchQuery({...orpc.career.workspace.queryOptions({ input: { applicationId } }),queryKey,diff --git a/apps/mobile/src/features/workspace/tabs/apply.tsx b/apps/mobile/src/features/workspace/tabs/apply.tsxindex ccaa7949f..53ab35137 100644--- a/apps/mobile/src/features/workspace/tabs/apply.tsx+++ b/apps/mobile/src/features/workspace/tabs/apply.tsx@@ -11,7 +11,7 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";import * as Clipboard from "expo-clipboard";import { randomUUID } from "expo-crypto";import { useRouter } from "expo-router";-import { useCallback, useLayoutEffect, useRef, useState } from "react";+import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";import { Pressable, View } from "react-native";import { answerLimit } from "@reactive-resume/schema/application-answers";import { hasApplicationSubmission } from "@reactive-resume/schema/applications/data";@@ -35,9 +35,8 @@ import { Actions, AiNotice, Block, CheckRow, SaveError, GenerateNotice, useWorkiimport { Preparation } from "../preparation";import { shareText } from "../share";import { WorkspaceScreen } from "../shell";-import { dispatchForOrigin } from "../state";-import { orpc } from "@/api/client";-import { getDraftScope } from "@/draft";+import { client, orpc, prepareRpc, SessionChangedError } from "@/api/client";+import { getAccountScope } from "@/auth/session";import { useHasAIProvider } from "@/features/ai/providers";import { WhatYouSent } from "@/features/application-detail/sections";import { PriorNoResponse } from "@/features/applications/prior-no-response";@@ -70,6 +69,20 @@ function Apply({ application, version, go }: WorkspaceTabProps) {const sentItem = candidate?.data.kind === "answers" ? { ...candidate, data: candidate.data } : undefined;// Removed questions wait out their Undo here; the workspace drops them when the toast closes.const [removed, setRemoved] = useState<string[]>([]);+ const accountScope = getAccountScope();+ const [removedFor, setRemovedFor] = useState({ accountScope, applicationId: application.id });+ if (removedFor.accountScope !== accountScope || removedFor.applicationId !== application.id) {+ setRemovedFor({ accountScope, applicationId: application.id });+ setRemoved([]);+ }+ const removals = useRef(new Map<string, ReturnType<typeof withUndo>>());+ useEffect(() => {+ const pending = removals.current;+ return () => {+ for (const operation of pending.values()) operation.flush();+ pending.clear();+ };+ }, [application.id, accountScope]);const [unit, setUnit] = useState<CountUnit>("words");const [submitting, setSubmitting] = useState(false);const [canSubmit, setCanSubmit] = useState(true);@@ -124,22 +137,42 @@ function Apply({ application, version, go }: WorkspaceTabProps) {};const currentAnswers = () => shown.map((answer) => drafts.current.get(answer.id)?.() ?? answer);const removeAnswer = (id: string) => {- setRemoved((ids) => [...ids, id]);- const origin = getDraftScope();- withUndo({+ if (removals.current.has(id)) return;+ const scope = getAccountScope();+ const current = () => scope === getAccountScope();+ const reconcile = async () => {+ if (!current()) return;+ await workspace.fetchConfirmed();+ if (current()) setRemoved((ids) => ids.filter((item) => item !== id));+ removals.current.delete(id);+ };+ const failed = () => {+ if (!current()) return;+ showToast({+ message: t`Couldn't complete this action. Try again.`,+ action: {+ label: t`Retry`,+ onPress: () => {+ void reconcile().catch(failed);+ },+ },+ });+ };+ const operation = withUndo({message: t`Question removed`,- // `save` reports its own failure; rejecting here shows the question again.- commit: () =>- // Dropped if another account is signed in when the Undo window ends.- dispatchForOrigin(origin, getDraftScope, async () => {- const result = await workspace.save({- answers: workspace.current().answers.filter((answer) => answer.id !== id),- });- if (!result.ok) throw new Error("Not removed");- }),- restore: () => setRemoved((ids) => ids.filter((item) => item !== id)),- failed: () => undefined,+ onReady: () => setRemoved((ids) => [...ids, id]),+ prepare: async () => {+ const value = await workspace.settled();+ if (!current()) throw new SessionChangedError();+ const expected = value.answers.find((answer) => answer.id === id);+ if (!expected) throw new Error("Answer no longer available");+ return prepareRpc(client.career.deleteWorkspaceAnswer, { applicationId: application.id, id, expected });+ },+ commit: (result) => result.then(reconcile).finally(() => removals.current.delete(id)),+ restore: reconcile,+ failed,});+ removals.current.set(id, operation);};const submitted = hasApplicationSubmission(application);@@ -311,17 +344,22 @@ function AnswerCard({before: { text: string; factIds: string[] };} | null>(null);// The answer as it reads now, for a toast's Undo that runs after later renders.- const current = useRef({ text, factIds: answer.factIds });+ const current = useRef({ text, question, factIds: answer.factIds });useLayoutEffect(() => {- current.current = { text, factIds: answer.factIds };+ current.current = { text, question, factIds: answer.factIds };});- const previousSaved = useRef(answer.answer);+ const previousSaved = useRef({ text: answer.answer, question: answer.question });useLayoutEffect(() => {// A refetch is not a local edit to autosave. Keep only text the user changed since the last saved copy.- if (previousSaved.current !== answer.answer && current.current.text === previousSaved.current)+ if (previousSaved.current.text !== answer.answer && current.current.text === previousSaved.current.text)setText(answer.answer);- previousSaved.current = answer.answer;- }, [answer.answer, setText]);+ if (+ previousSaved.current.question !== answer.question &&+ current.current.question === previousSaved.current.question+ )+ setQuestion(answer.question);+ previousSaved.current = { text: answer.answer, question: answer.question };+ }, [answer.answer, answer.question, setText, setQuestion]);const generate = useGenerate(applicationId);const provider = useHasAIProvider().defaultProvider;const answerSave = useAutosave(diff --git a/apps/mobile/src/features/workspace/tabs/saved.tsx b/apps/mobile/src/features/workspace/tabs/saved.tsxindex bfa07ff23..54a302b3c 100644--- a/apps/mobile/src/features/workspace/tabs/saved.tsx+++ b/apps/mobile/src/features/workspace/tabs/saved.tsx@@ -12,7 +12,7 @@ import { Pressable, View } from "react-native";import { useFacts, useSavedItems } from "../hooks";import { Actions, Block, tabLabel } from "../parts";import { WorkspaceScreen } from "../shell";-import { client, prepareRpc } from "@/api/client";+import { client, orpc, prepareRpc } from "@/api/client";import { useUserTime } from "@/features/application-detail/hooks";import { useUndoRows } from "@/features/career/hooks";import { formatMoney } from "@/features/career/offer-compare";@@ -72,7 +72,12 @@ function Saved({ application, go }: WorkspaceTabProps) {const onDelete = (item: SavedItem) => {if (filter === item.data.kind && shown.length === 1) setFilter(null);- undo.remove(item.id, t`Deleted from Library`, () => prepareRpc(client.career.deleteSavedItem, { id: item.id }));+ undo.remove(+ item.id,+ t`Deleted from Library`,+ () => prepareRpc(client.career.deleteSavedItem, { id: item.id }),+ orpc.career.savedItems.key(),+ );};return (diff --git a/apps/web/src/features/career/coach-thread.tsx b/apps/web/src/features/career/coach-thread.tsxindex d3c29e511..340fe1139 100644--- a/apps/web/src/features/career/coach-thread.tsx+++ b/apps/web/src/features/career/coach-thread.tsx@@ -134,13 +134,13 @@ export function useConversationDate() {* the delete fails.*/export function deleteConversation(queryClient: QueryClient, id: string, hide: () => void, restore: () => void) {- hide();withQueryUndo({queryClient,queryKey: orpc.agent.threads.list.key(),description: t`Conversation deleted`,errorMessage: t`Couldn't delete this conversation. Try again.`,prepare: () => prepareRpc(client.agent.threads.delete, { id }),+ hide,restore: () => {const threads = queryClient.getQueryData(orpc.agent.threads.list.queryKey());if (threads?.some((thread) => thread.id === id)) restore();diff --git a/apps/web/src/features/career/conversation-delete.test.ts b/apps/web/src/features/career/conversation-delete.test.tsindex e654b40f6..3d7f909de 100644--- a/apps/web/src/features/career/conversation-delete.test.ts+++ b/apps/web/src/features/career/conversation-delete.test.ts@@ -24,10 +24,10 @@ vi.mock("@reactive-resume/ui/components/toast", () => ({vi.mock("@/libs/orpc/client", () => ({orpc: { agent: { threads: { list: { key: () => ["threads"], queryKey: () => ["threads"] } } } },client: { agent: { threads: { delete: env.deleted } } },- prepareRpc: (procedure: () => Promise<unknown>) =>+ prepareRpc: (procedure: (input: unknown) => Promise<unknown>, input: unknown) =>prepareRequest((defer) =>defer(async () => {- await procedure();+ await procedure(input);return new Response();}),),@@ -55,8 +55,9 @@ async function scenario() {const hide = vi.fn();const restore = vi.fn();deleteConversation(queryClient, "fictional-thread", hide, restore);- expect(hide).toHaveBeenCalledOnce();+ expect(hide).not.toHaveBeenCalled();await vi.waitFor(() => expect(env.notices).toHaveLength(1));+ expect(hide).toHaveBeenCalledOnce();return { queryClient, restore };}it("committed conversation deletion refreshes the list without reopening the deleted thread", async () => {@@ -64,6 +65,7 @@ it("committed conversation deletion refreshes the list without reopening the delfor (const flush of pendingCommits) flush();await vi.waitFor(() => expect(h.queryClient.getQueryData(["threads"])).toEqual([]));expect(env.deleted).toHaveBeenCalledOnce();+ expect(env.deleted).toHaveBeenCalledWith({ id: "fictional-thread" });expect(h.restore).not.toHaveBeenCalled();});for (const erasedElsewhere of [false, true])diff --git a/apps/web/src/features/career/knowledge/facts.tsx b/apps/web/src/features/career/knowledge/facts.tsxindex b0fe970aa..e2cb3a644 100644--- a/apps/web/src/features/career/knowledge/facts.tsx+++ b/apps/web/src/features/career/knowledge/facts.tsx@@ -88,14 +88,16 @@ export function FactsPage({ highlight }: FactsPageProps) {};const forget = (fact: Fact) => {- setHidden((current) => [...current, fact.id]);withQueryUndo({queryClient,- queryKey: orpc.career.key(),+ queryKey: orpc.career.facts.key(),description: t`Fact forgotten`,errorMessage: t`Couldn't forget that fact. Try again.`,prepare: () => prepareRpc(client.career.forgetFact, { id: fact.id }),- restore: () => setHidden((current) => current.filter((id) => id !== fact.id)),+ hide: () => setHidden((current) => [...current, fact.id]),+ restore: () => {+ setHidden((current) => current.filter((id) => id !== fact.id));+ },});};diff --git a/apps/web/src/features/career/knowledge/stories.tsx b/apps/web/src/features/career/knowledge/stories.tsxindex 89b78c770..4a1f27e3e 100644--- a/apps/web/src/features/career/knowledge/stories.tsx+++ b/apps/web/src/features/career/knowledge/stories.tsx@@ -99,15 +99,19 @@ export function StoriesPage({ storyId, edit, start: planStart }: StoriesPageProp});const remove = (story: Story) => {- hide(story.id);- open(undefined);withQueryUndo({queryClient,- queryKey: orpc.career.key(),+ queryKey: orpc.career.stories.key(),description: t`Story deleted`,errorMessage: t`Couldn't delete that story. Try again.`,prepare: () => prepareRpc(client.career.deleteStory, { id: story.id }),- restore: () => unhide(story.id),+ hide: () => {+ hide(story.id);+ open(undefined);+ },+ restore: () => {+ unhide(story.id);+ },});};diff --git a/apps/web/src/features/career/offers.tsx b/apps/web/src/features/career/offers.tsxindex 8e991e755..1bf44c3c1 100644--- a/apps/web/src/features/career/offers.tsx+++ b/apps/web/src/features/career/offers.tsx@@ -131,13 +131,13 @@ export function OffersPage({ a, b, highlight }: OffersPageProps) {// Deleting waits out its Undo toast, as everywhere else saved work is deleted.const remove = (offer: Offer) => {- setHidden((ids) => [...ids, offer.id]);withQueryUndo({queryClient,queryKey: orpc.career.savedItems.key(),description: t`Offer deleted`,errorMessage: t`Couldn't delete that offer. Try again.`,prepare: () => prepareRpc(client.career.deleteSavedItem, { id: offer.id }),+ hide: () => setHidden((ids) => [...ids, offer.id]),restore: () => setHidden((ids) => ids.filter((id) => id !== offer.id)),});};diff --git a/apps/web/src/features/career/shared-undo.test.ts b/apps/web/src/features/career/shared-undo.test.tsindex 14c49e17f..b14e61919 100644--- a/apps/web/src/features/career/shared-undo.test.ts+++ b/apps/web/src/features/career/shared-undo.test.ts@@ -1,7 +1,7 @@// @vitest-environment happy-domimport { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";import { i18n } from "@lingui/core";-import { QueryClient } from "@tanstack/react-query";+import { QueryClient, QueryObserver } from "@tanstack/react-query";import { prepareRequest } from "@reactive-resume/utils/deferred-request";import { pendingCommits } from "./pending-commits";import { withQueryUndo } from "./shared";@@ -44,7 +44,7 @@ async function scenario() {const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });clients.push(client);const key = ["facts"];- const state = { canonical: [{ text: "Fictional private fact" }], offline: false, hidden: true, sent: 0 };+ const state = { canonical: [{ text: "Fictional private fact" }], offline: false, hidden: false, sent: 0 };await client.fetchQuery({queryKey: key,queryFn: () => {@@ -64,6 +64,9 @@ async function scenario() {description: "Fact forgotten",errorMessage: "Try again",prepare: () => preparing,+ hide: () => {+ state.hidden = true;+ },restore: () => {state.hidden = false;},@@ -91,7 +94,7 @@ it("Undo waits for canonical readback; failed read cannot reveal cached erased tit("prepared page-close flush enters transport synchronously once", async () => {const h = await scenario();- for (const flush of pendingCommits) flush();+ window.dispatchEvent(new Event("pagehide"));expect(h.state.sent).toBe(1);expect(pendingCommits.size).toBe(0);await vi.waitFor(() => expect(h.state.hidden).toBe(false));@@ -115,3 +118,76 @@ it("a departed account cannot reveal rows after a pending canonical read", asyncexpect(h.state.hidden).toBe(true);expect(h.state.sent).toBe(0);});++it("does not hide a row or acknowledge Undo until its transport is ready", async () => {+ const client = new QueryClient();+ clients.push(client);+ let release!: () => void;+ const wait = new Promise<void>((resolve) => {+ release = resolve;+ });+ let hidden = false;+ const preparing = prepareRequest(async (defer) => {+ await wait;+ return defer(() => Promise.resolve(new Response()));+ });+ withQueryUndo({+ queryClient: client,+ queryKey: ["facts"],+ description: "Fact forgotten",+ errorMessage: "Try again",+ prepare: () => preparing,+ hide: () => {+ hidden = true;+ },+ restore: () => {+ hidden = false;+ },+ });+ expect(hidden).toBe(false);+ expect(notices).toHaveLength(0);+ release();+ await preparing;+ expect(hidden).toBe(true);+ expect(notices).toHaveLength(1);+});++it("prepared deletion refreshes dependent application state without unrelated failures blocking canonical reveal", async () => {+ const h = await scenario();+ const applicationKey = ["applications", "detail", "fictional-job"];+ const reportKey = ["reports"];+ h.client.setQueryData(applicationKey, { followUp: "old schedule" });+ h.client.setQueryData(reportKey, { count: 1 });+ h.client.setQueryData(["auth"], { id: "alice" });+ h.client.setQueryData(["flags"], {});+ const applicationObserver = new QueryObserver(h.client, {+ queryKey: applicationKey,+ queryFn: async () => ({ followUp: null }),+ staleTime: Infinity,+ });+ let reportReads = 0;+ const reportObserver = new QueryObserver(h.client, {+ queryKey: reportKey,+ queryFn: async () => {+ reportReads++;+ throw new Error("Unrelated report unavailable");+ },+ staleTime: Infinity,+ });+ const unsubscribeApplication = applicationObserver.subscribe(() => {});+ const unsubscribeReport = reportObserver.subscribe(() => {});+ try {+ h.state.canonical = [];+ notice(0).onClose?.();+ await vi.waitFor(() => expect(h.state.hidden).toBe(false));+ expect(h.client.getQueryData(h.key)).toEqual([]);+ await vi.waitFor(() => expect(h.client.getQueryData(applicationKey)).toEqual({ followUp: null }));+ expect(reportReads).toBe(1);+ expect(notices).toHaveLength(1);+ expect(h.client.getQueryState(["auth"])?.isInvalidated).toBe(false);+ expect(h.client.getQueryState(["flags"])?.isInvalidated).toBe(false);+ } finally {+ unsubscribeApplication();+ unsubscribeReport();+ }+});diff --git a/apps/web/src/features/career/shared.tsx b/apps/web/src/features/career/shared.tsxindex 4d4e4d31c..de4bf129d 100644--- a/apps/web/src/features/career/shared.tsx+++ b/apps/web/src/features/career/shared.tsx@@ -21,6 +21,7 @@ import { deviceTimeZone } from "@/features/settings/use-save-timezone";import { getAccountGeneration } from "@/libs/auth/account-scope";import { getOrpcErrorMessage } from "@/libs/error-message";import { D2, EASE, EXIT } from "@/libs/motion";+import { invalidateMutationQueries } from "@/libs/query/client";// ---- Time: always in the user's timezone, "Thu 8 Oct, 17:58". Relative time is secondary text. ----@@ -99,6 +100,7 @@ type UndoInput<T> = { description: string; onUndo: () => unknown } & (| { commit: () => unknown }| {prepare: () => Promise<PreparedRequest<T>>;+ onReady: () => void;commit: (result: Promise<T>) => unknown;onPrepareError: (error: unknown) => unknown;}@@ -125,6 +127,7 @@ export function withUndo<T>(input: UndoInput<T>) {request.cancel();return;}+ input.onReady();const operation = showUndo({description: input.description,onUndo: () => {@@ -178,6 +181,7 @@ type QueryUndoOptions<T> = {description: string;errorMessage: string;prepare: () => Promise<PreparedRequest<T>>;+ hide: () => void;restore: () => void;};@@ -188,12 +192,14 @@ export function withQueryUndo<T>({description,errorMessage,prepare,+ hide,restore,}: QueryUndoOptions<T>) {const generation = getAccountGeneration();const current = () => generation === getAccountGeneration();const reconcile = async () => {if (!current()) return;+ void invalidateMutationQueries(queryClient, queryKey);await queryClient.cancelQueries({ queryKey });if (!current()) return;await queryClient.invalidateQueries({ queryKey, refetchType: "all" }, { throwOnError: true });@@ -219,6 +225,7 @@ export function withQueryUndo<T>({withUndo({description,prepare,+ onReady: hide,onPrepareError: failed,onUndo: () => reconcile().catch(report),commit: (result) => result.then(() => reconcile().catch(report), failed),diff --git a/apps/web/src/features/career/today.tsx b/apps/web/src/features/career/today.tsxindex 211fc4a5a..4973bf1c1 100644--- a/apps/web/src/features/career/today.tsx+++ b/apps/web/src/features/career/today.tsx@@ -55,13 +55,13 @@ export function TodayPage({ schedule, onScheduleChange }: TodayPageProps) {const [deleted, setDeleted] = useState<string[]>([]);const deleteSchedule = (id: string) => {- setDeleted((current) => [...current, id]);withQueryUndo({queryClient,queryKey: orpc.career.schedules.key(),description: t`Schedule deleted`,errorMessage: t`Couldn't delete this schedule. Try again.`,prepare: () => prepareRpc(client.career.deleteSchedule, { id }),+ hide: () => setDeleted((current) => [...current, id]),restore: () => setDeleted((current) => current.filter((item) => item !== id)),});};@@ -188,7 +188,7 @@ function NeedsYou({ now, onReview, className }: NeedsYouProps) {const isUnread = (row: Notification) => !row.readAt && !pending.includes(row.id);const unread = data?.filter(isUnread) ?? [];const read = data?.filter((row) => !isUnread(row)) ?? [];- const rows = showRead ? (data ?? []) : unread;+ const rows = showRead ? (data ?? []).filter((row) => !pending.includes(row.id)) : unread;// The same next-step rules as the Applications list: due follow-ups, no reply, interviews this week, offers.const attention = (applications ?? []).flatMap((application) => {@@ -202,14 +202,16 @@ function NeedsYou({ now, onReview, className }: NeedsYouProps) {// Hidden at once; the server hears about it when the toast closes. The cache edit drops the sidebar count too,// while `pending` keeps the row hidden through any refetch.const dismiss = (row: Notification) => {- setPending((current) => [...current, row.id]);- setReadAt(row.id, new Date());withQueryUndo({queryClient,queryKey: orpc.career.notifications.key(),description: t`Marked as read`,errorMessage: t`Couldn't mark this as read. Try again.`,prepare: () => prepareRpc(client.career.markNotificationRead, { id: row.id }),+ hide: () => {+ setPending((current) => [...current, row.id]);+ setReadAt(row.id, new Date());+ },restore: () => setPending((current) => current.filter((id) => id !== row.id)),});};@@ -520,13 +522,13 @@ function NewRoles({ ref, now, deleted, onOpenSchedule, className }: NewRolesPropconst onUndoTrack = (applicationId: string) => untrack.mutate({ id: applicationId });const onDismiss = (row: Opportunity) => {- setHidden((current) => [...current, row.id]);withQueryUndo({queryClient,queryKey: orpc.career.opportunities.key(),description: t`Hidden from New roles`,errorMessage: t`Couldn't hide this role. Try again.`,prepare: () => prepareRpc(client.career.dismissOpportunity, { id: row.id }),+ hide: () => setHidden((current) => [...current, row.id]),restore: () => setHidden((current) => current.filter((id) => id !== row.id)),});};diff --git a/apps/web/src/features/career/workspace/apply.tsx b/apps/web/src/features/career/workspace/apply.tsxindex 9301d6a47..fb413f242 100644--- a/apps/web/src/features/career/workspace/apply.tsx+++ b/apps/web/src/features/career/workspace/apply.tsx@@ -45,8 +45,10 @@ import { AiNotice } from "./fit";import { Preparation } from "./preparation";import { SentDocuments } from "@/features/applications/components/detail/sent-documents";import { useInvalidateApplications } from "@/features/applications/use-application-actions";+import { getAccountGeneration } from "@/libs/auth/account-scope";import { toastError } from "@/libs/error-message";-import { orpc } from "@/libs/orpc/client";+import { client, orpc, prepareRpc } from "@/libs/orpc/client";+import { invalidateMutationQueries } from "@/libs/query/client";type Answer = CareerWorkspace["answers"][number];type AnswerSnapshot = Pick<Answer, "answer" | "factIds">;@@ -71,6 +73,7 @@ const checklistItems = () =>/** W4–W5: the written answers for the employer's form, and a checklist before submitting there yourself. */export function ApplyTab({ application, version, go }: WorkspaceTabProps) {+ const queryClient = useQueryClient();const saved = useSavedItems(application.id);const workspace = useWorkspace(application.id);const { data: facts } = useQuery(orpc.career.facts.queryOptions({ input: { applicationId: application.id } }));@@ -82,6 +85,7 @@ export function ApplyTab({ application, version, go }: WorkspaceTabProps) {const sentItem = candidate?.data.kind === "answers" ? { ...candidate, data: candidate.data } : undefined;// Removed questions wait out their Undo here; the workspace drops them when the toast closes.const [removed, setRemoved] = useState<string[]>([]);+ const removing = useRef(new Set<string>());const [unit, setUnit] = useState<CountUnit>("words");const [submitting, setSubmitting] = useState(false);const [canSubmit, setCanSubmit] = useState(true);@@ -142,11 +146,51 @@ export function ApplyTab({ application, version, go }: WorkspaceTabProps) {};const currentAnswers = () => shown.map((answer) => drafts.current.get(answer.id)?.() ?? answer);const removeAnswer = (id: string) => {- setRemoved((ids) => [...ids, id]);+ const generation = getAccountGeneration();+ const key = JSON.stringify([generation, application.id, id]);+ if (removing.current.has(key)) return;+ removing.current.add(key);+ const current = () => generation === getAccountGeneration();+ const reconcile = async () => {+ removing.current.delete(key);+ await workspace.settled();+ if (!current()) return;+ const queryKey = orpc.career.workspace.queryKey({ input: { applicationId: application.id } });+ void invalidateMutationQueries(queryClient, queryKey);+ await queryClient.cancelQueries({ queryKey });+ if (!current()) return;+ await queryClient.invalidateQueries({ queryKey, refetchType: "all" }, { throwOnError: true });+ if (current()) setRemoved((ids) => ids.filter((item) => item !== id));+ };+ const failed = () => {+ if (!current()) return;+ toast.add({+ type: "error",+ description: t`Couldn't save that change. Check your connection and try again.`,+ actionProps: {+ children: t`Retry`,+ onClick: () => {+ void reconcile().catch(failed);+ },+ },+ });+ };withUndo({description: t`Question removed`,- commit: () => workspace.save({ answers: workspace.current().answers.filter((answer) => answer.id !== id) }),- onUndo: () => setRemoved((ids) => ids.filter((item) => item !== id)),+ onReady: () => setRemoved((ids) => [...ids, id]),+ prepare: async () => {+ const value = await workspace.settled();+ if (!current()) throw new DOMException("", "AbortError");+ const expected = value.answers.find((answer) => answer.id === id);+ if (!expected) throw new Error("Answer no longer available");+ return prepareRpc(client.career.deleteWorkspaceAnswer, { applicationId: application.id, id, expected });+ },+ onPrepareError: () => {+ failed();+ void reconcile().catch(failed);+ },+ commit: (result) => result.catch(failed).then(() => reconcile().catch(failed)),+ onUndo: () => reconcile().catch(failed),});};@@ -358,17 +402,22 @@ function AnswerCard({before: { text: string; factIds: string[] };} | null>(null);// The answer as it reads now, for a toast's Undo that runs after later renders.- const current = useRef({ text, factIds: answer.factIds });+ const current = useRef({ text, question, factIds: answer.factIds });useLayoutEffect(() => {- current.current = { text, factIds: answer.factIds };+ current.current = { text, question, factIds: answer.factIds };});- const previousSaved = useRef(answer.answer);+ const previousSaved = useRef({ text: answer.answer, question: answer.question });useLayoutEffect(() => {// A refetch is not a local edit to autosave. Keep only text the user changed since the last saved copy.- if (previousSaved.current !== answer.answer && current.current.text === previousSaved.current)+ if (previousSaved.current.text !== answer.answer && current.current.text === previousSaved.current.text)setText(answer.answer);- previousSaved.current = answer.answer;- }, [answer.answer, setText]);+ if (+ previousSaved.current.question !== answer.question &&+ current.current.question === previousSaved.current.question+ )+ setQuestion(answer.question);+ previousSaved.current = { text: answer.answer, question: answer.question };+ }, [answer.answer, answer.question, setText, setQuestion]);const generate = useGenerate(applicationId);const { provider } = useDefaultProvider();const flushAnswer = useDebouncedSave(diff --git a/apps/web/src/features/career/workspace/saved.tsx b/apps/web/src/features/career/workspace/saved.tsxindex 39588b03d..2c9c86309 100644--- a/apps/web/src/features/career/workspace/saved.tsx+++ b/apps/web/src/features/career/workspace/saved.tsx@@ -90,6 +90,7 @@ export function SavedTab({ application, go }: WorkspaceTabProps) {description: t`Deleted from Library`,errorMessage: t`Couldn't save that change. Check your connection and try again.`,prepare: () => prepareRpc(client.career.deleteSavedItem, { id: item.id }),+ hide: () => hide(item.id),restore: () => unhide(item.id),});};diff --git a/apps/web/src/libs/query/client.ts b/apps/web/src/libs/query/client.tsindex 592063176..b473b3149 100644--- a/apps/web/src/libs/query/client.ts+++ b/apps/web/src/libs/query/client.ts@@ -1,8 +1,18 @@+import type { QueryKey } from "@tanstack/react-query";import { StandardRPCJsonSerializer } from "@orpc/client/standard";-import { MutationCache, QueryClient } from "@tanstack/react-query";+import { matchQuery, MutationCache, QueryClient } from "@tanstack/react-query";const serializer = new StandardRPCJsonSerializer();+/** Prepared mutations read their hidden rows separately; other caches retain the normal mutation policy. */+export const invalidateMutationQueries = (queryClient: QueryClient, canonicalKey?: QueryKey) =>+ queryClient.invalidateQueries({+ predicate: (query) => {+ const key = query.queryKey[0];+ return key !== "auth" && key !== "flags" && (!canonicalKey || !matchQuery({ queryKey: canonicalKey }, query));+ },+ });+export const getQueryClient = () => {const queryClient = new QueryClient({defaultOptions: {@@ -18,12 +28,7 @@ export const getQueryClient = () => {mutationCache: new MutationCache({onSettled: (_1, _2, _3, _4, _5, context) => {if (context?.meta?.noInvalidate) return;- void queryClient.invalidateQueries({- predicate: (query) => {- const key = query.queryKey[0];- return key !== "auth" && key !== "flags";- },- });+ void invalidateMutationQueries(queryClient);},}),});diff --git a/docs/guides/career-workspace-reference.mdx b/docs/guides/career-workspace-reference.mdxindex 01a3b530b..de917967e 100644--- a/docs/guides/career-workspace-reference.mdx+++ b/docs/guides/career-workspace-reference.mdx@@ -181,7 +181,7 @@ Speech connections may charge separately from text AI. Browser speech does not uUndo notices for Career deletions and applied message changes last six seconds. Once committed, deletion is not an ongoing trash or restore feature. Exported copies, previously sent material, provider-retained data and installation backups have their own lifetimes.-For **Forget**, story deletion, saved-result deletion, schedule deletion, individual role dismissal and marking a Today notice read, the Undo notice appears after the pending action is ready. Leaving the page or putting the native app in the background starts it immediately. Undo checks the saved state before revealing a hidden row; an item removed elsewhere stays removed. If that check fails, **Retry** checks again without recreating erased content. Career conversation deletion on web follows the same rule and only reopens a conversation still present in the saved list.+For **Forget**, story deletion, saved-result deletion, schedule deletion, individual role dismissal and marking a Today notice read, the Undo notice appears after the pending action is ready. Leaving the page or putting the native app in the background starts it immediately. Undo checks the saved state before revealing a hidden row; an item removed elsewhere stays removed. If that check fails, **Retry** checks again without recreating erased content. Career conversation deletion on web follows the same rule and only reopens a conversation still present in the saved list. **Apply → Question options → Remove question** also follows this rule. It removes only the unchanged current draft answer, preserves other workspace fields and retains recorded submission copies and review checks.Knowledge can support Fit, answers, preparation, practice and message reviews as well as Coach. Each AI action names the selected connection and the context it sends. Facts with coaching switched off, forgotten facts, unsupported stories and stories awaiting correction review are excluded from new context.diff --git a/docs/guides/writing-application-answers.mdx b/docs/guides/writing-application-answers.mdxindex 99232b593..eeb4d9d97 100644--- a/docs/guides/writing-application-answers.mdx+++ b/docs/guides/writing-application-answers.mdx@@ -16,7 +16,16 @@ Saved jobs start in **Apply**, where the preparation card names your current ste3. Paste the question, including any limit such as “Maximum 200 words.”4. Press Enter or leave the question field to finish editing it.-Use **Question options → Edit question** to change it later. **Remove question** offers **Undo**.+Use **Question options → Edit question** to change it later. **Remove question** offers **Undo** once the removal is ready. Leaving the page or backgrounding the native app commits the pending removal. Undo reads the saved workspace before showing the question again; a question removed elsewhere stays removed. If that read fails, **Retry** checks again without recreating the answer.++Removal affects only that current draft question and answer. Other answers, recorded submission copies and first-submission review checks stay intact. If the target question changes on another device before removal commits, its newer wording is kept; review it before trying again.++<Frame caption="Removing a current draft question leaves the other answer in place and offers Undo.">+ <img+ src="/images/guides/career/question-removal-undo.png"+ alt="Fictional Northwind application in Apply with a remaining answer about joining the company and a Question removed notice offering Undo"+ />+</Frame>## Draft from your experiencediff --git a/docs/images/guides/career/question-removal-undo.png b/docs/images/guides/career/question-removal-undo.pngnew file mode 100644index 000000000..90d031517Binary files /dev/null and b/docs/images/guides/career/question-removal-undo.png differdiff --git a/docs/spec.json b/docs/spec.jsonindex 00d6c8d7d..6c5dc25d2 100644--- a/docs/spec.json+++ b/docs/spec.json@@ -60874,6 +60874,306 @@]}},+ "/career/workspace/{applicationId}/answers/{id}": {+ "delete": {+ "operationId": "deleteCareerWorkspaceAnswer",+ "summary": "Remove one unchanged workspace answer",+ "description": "Removes only the answer matching the supplied previous value. Other answers, workspace fields and submitted history remain unchanged. Repeating an already completed removal is safe.",+ "tags": [+ "Career"+ ],+ "parameters": [+ {+ "name": "applicationId",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "minLength": 1+ }+ },+ {+ "name": "id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "minLength": 1,+ "maxLength": 64+ }+ }+ ],+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "type": "object",+ "properties": {+ "expected": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string",+ "minLength": 1,+ "maxLength": 64+ },+ "question": {+ "type": "string",+ "maxLength": 2000+ },+ "answer": {+ "type": "string",+ "maxLength": 6000+ },+ "factIds": {+ "type": "array",+ "maxItems": 10,+ "items": {+ "type": "string"+ }+ }+ },+ "required": [+ "id",+ "question",+ "answer",+ "factIds"+ ]+ }+ },+ "required": [+ "expected"+ ]+ }+ }+ }+ },+ "responses": {+ "200": {+ "description": "OK",+ "content": {+ "application/json": {+ "schema": {+ "type": "object",+ "properties": {+ "answers": {+ "type": "array",+ "maxItems": 30,+ "items": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string",+ "minLength": 1,+ "maxLength": 64+ },+ "question": {+ "type": "string",+ "maxLength": 2000+ },+ "answer": {+ "type": "string",+ "maxLength": 6000+ },+ "factIds": {+ "type": "array",+ "maxItems": 10,+ "items": {+ "type": "string"+ }+ }+ },+ "required": [+ "id",+ "question",+ "answer",+ "factIds"+ ]+ }+ },+ "checklist": {+ "type": "array",+ "maxItems": 10,+ "items": {+ "type": "integer",+ "minimum": 0,+ "maximum": 10+ }+ },+ "submissionReview": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "at": {+ "type": "string",+ "format": "date-time"+ },+ "checklist": {+ "type": "array",+ "maxItems": 10,+ "items": {+ "type": "integer",+ "minimum": 0,+ "maximum": 10+ }+ },+ "documents": {+ "type": "boolean"+ },+ "answers": {+ "type": "boolean"+ },+ "answerVersionId": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "stageEntryId": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ }+ },+ "required": [+ "at",+ "checklist",+ "documents",+ "answers"+ ]+ },+ {+ "type": "null"+ }+ ]+ },+ "questions": {+ "type": "array",+ "maxItems": 20,+ "items": {+ "type": "object",+ "properties": {+ "text": {+ "type": "string",+ "maxLength": 400+ },+ "origin": {+ "type": "string",+ "maxLength": 60+ }+ },+ "required": [+ "text",+ "origin"+ ]+ }+ },+ "evidence": {+ "type": "object",+ "propertyNames": {+ "type": "string",+ "maxLength": 300+ },+ "additionalProperties": {+ "type": "string",+ "maxLength": 64+ }+ },+ "ticks": {+ "type": "object",+ "propertyNames": {+ "type": "string",+ "maxLength": 100+ },+ "additionalProperties": {+ "type": "array",+ "maxItems": 20,+ "items": {+ "type": "string",+ "maxLength": 20+ }+ }+ },+ "message": {+ "type": "string",+ "maxLength": 20000+ }+ },+ "required": [+ "answers",+ "checklist",+ "questions",+ "evidence",+ "ticks",+ "message"+ ]+ }+ }+ }+ },+ "default": {+ "description": "Structured API error. See status and code; do not branch on message text.",+ "content": {+ "application/json": {+ "schema": {+ "type": "object",+ "required": [+ "defined",+ "code",+ "status",+ "message"+ ],+ "properties": {+ "defined": {+ "type": "boolean"+ },+ "code": {+ "type": "string"+ },+ "status": {+ "type": "integer"+ },+ "message": {+ "type": "string"+ },+ "data": {}+ }+ }+ }+ }+ }+ },+ "security": [+ {+ "apiKey": []+ },+ {+ "bearerAuth": []+ },+ {+ "cookieAuth": []+ }+ ],+ "x-codeSamples": [+ {+ "lang": "bash",+ "label": "cURL",+ "source": "curl --request DELETE \"https://rxresu.me/api/openapi/career/workspace/<applicationId>/answers/<id>\" --header \"x-api-key: <api-key>\" --header \"Content-Type: application/json\" --data '{\n \"expected\": {\n \"id\": \"<string>\",\n \"question\": \"<string>\",\n \"answer\": \"<string>\",\n \"factIds\": [\n \"<string>\"\n ]\n }\n}'"+ }+ ]+ }+ },"/career/workspace/{applicationId}/submit": {"post": {"operationId": "submitCareerApplication",diff --git a/packages/api/src/features/career/router.ts b/packages/api/src/features/career/router.tsindex dfd6a3654..35b9abbb3 100644--- a/packages/api/src/features/career/router.ts+++ b/packages/api/src/features/career/router.ts@@ -495,6 +495,23 @@ export const careerRouter = {.handler(({ context, input: { applicationId, expected, ...patch } }) =>careerService.saveWorkspace(context.user.id, applicationId, patch, expected),),+ deleteWorkspaceAnswer: protectedProcedure+ .route({+ method: "DELETE",+ path: "/career/workspace/{applicationId}/answers/{id}",+ tags: ["Career"],+ operationId: "deleteCareerWorkspaceAnswer",+ summary: "Remove one unchanged workspace answer",+ description:+ "Removes only the answer matching the supplied previous value. Other answers, workspace fields and submitted history remain unchanged. Repeating an already completed removal is safe.",+ })+ .input(+ applicationInput.extend({ id: z.string().min(1).max(64), expected: careerWorkspaceSchema.shape.answers.element }),+ )+ .output(careerWorkspaceSchema)+ .handler(({ context, input }) =>+ careerService.deleteWorkspaceAnswer(context.user.id, input.applicationId, input.id, input.expected),+ ),submitApplication: protectedProcedure.route({method: "POST",diff --git a/packages/api/src/features/career/service.integration.test.ts b/packages/api/src/features/career/service.integration.test.tsindex 5df12f848..c60218c14 100644--- a/packages/api/src/features/career/service.integration.test.ts+++ b/packages/api/src/features/career/service.integration.test.ts@@ -1752,6 +1752,89 @@ describe.skipIf(!databaseUrl)("career knowledge, context and data lifecycle", ()});});+ it("removes only the unchanged owned answer, retains other fields, and never recreates a removed answer", async () => {+ const applicationId = "answer-remove-owned";+ await getDb()+ .insert(tables.application)+ .values({ id: applicationId, userId: "alice", company: "Northwind", role: "Engineer" });+ const answer = { id: "why", question: "Why Northwind?", answer: "Fictional reliability work.", factIds: [] };+ const other = { ...answer, id: "other", question: "Another question" };+ await service.saveWorkspace(+ "alice",+ applicationId,+ { answers: [answer, other], checklist: [1], message: "Keep this" },+ { answers: [], checklist: [], message: "" },+ );+ await expect(service.deleteWorkspaceAnswer("bob", applicationId, answer.id, answer)).rejects.toMatchObject({+ code: "NOT_FOUND",+ });+ expect((await service.workspace("alice", applicationId)).answers).toEqual([answer, other]);+ await service.deleteWorkspaceAnswer("alice", applicationId, answer.id, answer);+ await expect(+ service.saveWorkspace("alice", applicationId, { answers: [answer, other] }, { answers: [answer, other] }),+ ).rejects.toMatchObject({ code: "CONFLICT" });+ await service.deleteWorkspaceAnswer("alice", applicationId, answer.id, answer);+ expect(await service.workspace("alice", applicationId)).toMatchObject({+ answers: [other],+ checklist: [1],+ message: "Keep this",+ });+ });++ it("refuses stale answer removal and preserves an independent concurrent workspace save", async () => {+ const applicationId = "answer-remove-concurrent";+ await getDb()+ .insert(tables.application)+ .values({ id: applicationId, userId: "alice", company: "Northwind", role: "Engineer" });+ const answer = { id: "why", question: "Why Northwind?", answer: "Original answer", factIds: [] };+ const updated = { ...answer, answer: "Newer answer" };+ await service.saveWorkspace("alice", applicationId, { answers: [answer] }, { answers: [] });+ await service.saveWorkspace("alice", applicationId, { answers: [updated] }, { answers: [answer] });+ await expect(service.deleteWorkspaceAnswer("alice", applicationId, answer.id, answer)).rejects.toMatchObject({+ code: "CONFLICT",+ });+ await Promise.all([+ service.deleteWorkspaceAnswer("alice", applicationId, answer.id, updated),+ service.saveWorkspace("alice", applicationId, { checklist: [2] }, { checklist: [] }),+ ]);+ expect(await service.workspace("alice", applicationId)).toMatchObject({ answers: [], checklist: [2] });+ });++ it("workspace answer removal preserves the immutable submitted answer, review receipt and stage history", async () => {+ const applicationId = "answer-removal-review";+ await getDb()+ .insert(tables.application)+ .values({ id: applicationId, userId: "alice", company: "Northwind", role: "Engineer" });+ const answer = { id: "why", question: "Why Northwind?", answer: "Fictional submitted answer", factIds: [] };+ await service.saveWorkspace(+ "alice",+ applicationId,+ { answers: [answer], checklist: [1, 3] },+ { answers: [], checklist: [] },+ );+ await service.submitApplication("alice", applicationId, [answer], [answer]);+ const before = await applications.getById({ userId: "alice", id: applicationId });+ const saved = await service.savedItems({ userId: "alice", applicationId, kind: "answers" });+ const review = (await service.workspace("alice", applicationId)).submissionReview;+ expect(review).toMatchObject({ checklist: [1, 3], answerVersionId: expect.any(String) });+ const removed = await service.deleteWorkspaceAnswer("alice", applicationId, answer.id, answer);+ expect(removed).toMatchObject({ answers: [], submissionReview: review });+ const repeated = await service.deleteWorkspaceAnswer("alice", applicationId, answer.id, answer);+ expect(repeated.submissionReview).toEqual(review);+ expect(await service.workspace("alice", applicationId)).toMatchObject({ answers: [], submissionReview: review });+ const [stored] = await getDb()+ .select()+ .from(tables.careerWorkspace)+ .where(eq(tables.careerWorkspace.applicationId, applicationId));+ expect(stored?.submissionReview).toEqual(review);+ expect(stored?.data).not.toHaveProperty("submissionReview");+ expect(await service.savedItems({ userId: "alice", applicationId, kind: "answers" })).toEqual(saved);+ const after = await applications.getById({ userId: "alice", id: applicationId });+ expect(after.activity).toEqual(before.activity);+ expect(after.sentResumeVersionId).toBe(before.sentResumeVersionId);+ expect(after.sentCoverLetterVersionId).toBe(before.sentCoverLetterVersionId);+ });+it("adopts the device country on the first search without a Preferences visit", async () => {const { searchScope } = await import("../web-access/regions");await service.saveProfile("alice", careerProfileDataSchema.parse({ priorities: "Autonomy" }));diff --git a/packages/api/src/features/career/service.ts b/packages/api/src/features/career/service.tsindex dc6dcd42c..9c584b465 100644--- a/packages/api/src/features/career/service.ts+++ b/packages/api/src/features/career/service.ts@@ -1634,6 +1634,47 @@ export const careerService = {};});},+ /** The application lock serializes removal with workspace saves; only the unchanged target is removed. */+ deleteWorkspaceAnswer: async (+ userId: string,+ applicationId: string,+ id: string,+ expected: CareerWorkspace["answers"][number],+ ) => {+ await requireCareerApplication({ userId, applicationId });+ return db.transaction(async (tx) => {+ const [application] = await tx+ .select()+ .from(tables.application)+ .where(and(eq(tables.application.id, applicationId), activeApplications(userId)))+ .for("update");+ if (!application) throw new ORPCError("NOT_FOUND");+ const [row] = await tx+ .select()+ .from(tables.careerWorkspace)+ .where(and(eq(tables.careerWorkspace.applicationId, applicationId), eq(tables.careerWorkspace.userId, userId)));+ const current = careerWorkspaceDataSchema.parse({ ...EMPTY_WORKSPACE, ...row?.data });+ const answer = current.answers.find((item) => item.id === id);+ if (answer && !isDeepStrictEqual(answer, expected))+ throw new ORPCError("CONFLICT", {+ message: "This answer changed elsewhere. Review its latest version before removing it.",+ });+ const data = answer ? { ...current, answers: current.answers.filter((item) => item.id !== id) } : current;+ if (answer)+ await tx+ .update(tables.careerWorkspace)+ .set({ data, updatedAt: new Date() })+ .where(+ and(eq(tables.careerWorkspace.applicationId, applicationId), eq(tables.careerWorkspace.userId, userId)),+ );+ return {+ ...data,+ ...(row?.submissionReview || hasSubmitted(application)+ ? { submissionReview: row?.submissionReview ?? null }+ : {}),+ };+ });+ },/** The submitted answers, document versions and stage are one committed action. */submitApplication: (userId: string,diff --git a/packages/utils/src/deferred-request.test.ts b/packages/utils/src/deferred-request.test.tsindex 27b4ef2a0..cf2abd4c1 100644--- a/packages/utils/src/deferred-request.test.ts+++ b/packages/utils/src/deferred-request.test.ts@@ -86,3 +86,24 @@ it("allows an existing transport to retry after its first authenticated send", aawait request.send();expect(sent).toBe(2);});++it("cannot dispatch a held request after its preparation callback rejects", async () => {+ let sent = 0;+ const error = new Error("Preparation failed after defer");+ let fail!: (error: Error) => void;+ const failed = new Promise<never>((_resolve, reject) => {+ fail = reject;+ });+ const request = await prepareRequest(async (defer) => {+ void defer(() => {+ sent++;+ return Promise.resolve(new Response());+ });+ return failed;+ });+ fail(error);+ await failed.catch(() => {});+ await new Promise<void>((resolve) => setImmediate(resolve));+ await expect(request.send()).rejects.toBe(error);+ expect(sent).toBe(0);+});diff --git a/packages/utils/src/deferred-request.ts b/packages/utils/src/deferred-request.tsindex 7796c2d83..3c48153d8 100644--- a/packages/utils/src/deferred-request.ts+++ b/packages/utils/src/deferred-request.ts@@ -44,6 +44,17 @@ export function prepareRequest<T>(call: (defer: DeferredFetch) => Promise<T>): Preturn response;}),);- void result.then(() => failed(new Error("Request was not prepared")), failed);+ void result.then(+ () => failed(new Error("Request was not prepared")),+ (error) => {+ if (state === "held") {+ state = "cancelled";+ reject(error);+ }+ failed(error);+ },+ );+ // A callback may fail independently after handing over its transport.+ void response.catch(() => {});return ready;}diff --git a/tests/e2e/specs/career-undo-lifecycle.spec.ts b/tests/e2e/specs/career-undo-lifecycle.spec.tsindex 0766b67c7..aec26c398 100644--- a/tests/e2e/specs/career-undo-lifecycle.spec.ts+++ b/tests/e2e/specs/career-undo-lifecycle.spec.ts@@ -165,3 +165,62 @@ test("failed Undo readback keeps erased text hidden; Retry reads canonical dataawait expect(page.getByText(saved.text, { exact: true })).toHaveCount(0);expect(await readFact(saved.id, account.email)).toEqual({ status: "forgotten", text: "", quote: "", revisions: [] });});++test("Forget Undo reads its own canonical list when another Career endpoint fails", async ({+ authPage: page,+ account,+}) => {+ const saved = await fact(page);+ await page.goto("/dashboard/career/knowledge/facts");+ await expect(page.getByText(saved.text, { exact: true })).toBeVisible();+ await page.getByRole("button", { name: "Forget", exact: true }).click();+ await expect(page.getByRole("button", { name: "Undo", exact: true })).toBeVisible();+ let failures = 0;+ await page.route("**/api/rpc/**", async (route) => {+ if (await failRpcProcedure(route, "/api/rpc/career/stories", "Fictional unrelated endpoint unavailable"))+ failures++;+ });+ await page.getByRole("button", { name: "Undo", exact: true }).click();+ await expect(page.getByText(saved.text, { exact: true })).toBeVisible();+ await expect.poll(() => failures).toBeGreaterThan(0);+ await expect(page.getByRole("button", { name: "Retry", exact: true })).toHaveCount(0);+ expect(await readFact(saved.id, account.email)).toMatchObject({ status: "active", text: saved.text });+});++test("pending Mark as read stays out of Show read until canonical retry succeeds", async ({+ authPage: page,+ account,+}) => {+ const id = `notification-${Date.now()}`;+ await database.query(+ `insert into career_notification(id, user_id, key, notice) select $1, id, $1, $2::jsonb from "user" where email=$3`,+ [id, JSON.stringify({ type: "briefing-paused" }), account.email],+ );+ await page.goto("/dashboard/career");+ await page.getByRole("button", { name: "Mark as read", exact: true }).click();+ await expect(page.getByRole("button", { name: "Undo", exact: true })).toBeVisible();+ let failures = 0;+ await page.route("**/api/rpc/**", async (route) => {+ if (await failRpcProcedure(route, "/api/rpc/career/notifications", "Fictional read unavailable")) failures++;+ });+ await page.getByRole("button", { name: "Undo", exact: true }).click();+ await expect.poll(() => failures).toBeGreaterThan(0);+ await expect(page.getByRole("button", { name: "Retry", exact: true })).toBeVisible();+ // A successful focus refetch does not settle the failed Undo operation.+ await page.unroute("**/api/rpc/**");+ const refreshed = page.waitForResponse(+ (response) =>+ response.ok() &&+ (response.url().includes("/career/notifications") ||+ (response.url().includes("/__batch__") &&+ (response.request().postData() ?? "").includes("career/notifications"))),+ );+ await page.evaluate(() => window.dispatchEvent(new Event("visibilitychange")));+ await refreshed;+ await page.getByRole("button", { name: "Show 1 read", exact: true }).click();+ await expect(page.getByText("Interview briefing paused", { exact: true })).toHaveCount(0);+ await page.getByRole("button", { name: "Retry", exact: true }).click();+ await expect(page.getByText("Interview briefing paused", { exact: true })).toBeVisible();+ const result = await database.query("select read_at from career_notification where id=$1", [id]);+ expect(result.rows[0].read_at).toBeNull();+});diff --git a/tests/e2e/specs/career-workspace-undo.spec.ts b/tests/e2e/specs/career-workspace-undo.spec.tsnew file mode 100644index 000000000..ee5146014--- /dev/null+++ b/tests/e2e/specs/career-workspace-undo.spec.ts@@ -0,0 +1,225 @@+import type { Page } from "@playwright/test";+import { Pool } from "pg";+import { createAuthenticatedContext } from "../fixtures/auth";+import { createAccount } from "../fixtures/data";+import { deleteE2EUser } from "../fixtures/db";+import { expect, test } from "../fixtures/test";++let database: Pool;+test.beforeAll(() => {+ if (!process.env.DATABASE_URL) throw new Error("Disposable DATABASE_URL required");+ database = new Pool({ connectionString: process.env.DATABASE_URL, max: 2 });+});+test.afterAll(async () => await database.end());++async function workspace(+ page: Page,+ answers = Array.from({ length: 14 }, (_, index) => ({+ id: `fictional-${index}`,+ question: `Fictional question ${index}`,+ answer: "Fictional answer. ".repeat(300),+ factIds: [],+ })),+) {+ const response = await page.request.post("/api/openapi/applications", {+ data: { company: "Fictional Northwind", role: "Product engineer", status: "saved" },+ });+ await expect(response).toBeOK();+ const id = (await response.json()) as string;+ const saved = await page.request.patch(`/api/openapi/career/workspace/${id}`, {+ data: { answers, expected: { answers: [] } },+ });+ await expect(saved).toBeOK();+ return { id, answers: (await saved.json()).answers as typeof answers };+}++async function removeFirst(page: Page) {+ await page.getByRole("button", { name: "Question options", exact: true }).first().click();+ await page.getByRole("menuitem", { name: "Remove question", exact: true }).click();+ await expect(page.getByRole("button", { name: "Undo", exact: true })).toBeVisible();+}++for (const mode of ["reload", "close"] as const)+ test(`acknowledged question removal survives ${mode} without sending the whole large workspace`, async ({+ authPage: page,+ account,+ }) => {+ const saved = await workspace(page);+ const remaining = saved.answers.slice(1);+ expect(+ Buffer.byteLength(JSON.stringify({ answers: remaining, expected: { answers: saved.answers } })),+ ).toBeGreaterThan(60 * 1024);+ await page.goto(`/dashboard/applications/${saved.id}/apply`);++ await removeFirst(page);+ if (mode === "reload") await page.reload();+ else await Promise.all([page.waitForEvent("close"), page.close({ runBeforeUnload: true })]);+ // SQL is read before reopening a closed page: no recovery replay can manufacture persistence.+ await expect+ .poll(async () => {+ const result = await database.query(+ `select w.data->'answers' as answers from career_workspace w join "user" u on u.id = w.user_id where w.application_id=$1 and u.email=$2`,+ [saved.id, account.email],+ );+ return result.rows[0]?.answers;+ })+ .toEqual(remaining);+ });++test("question removal preserves another client's independent answer edit", async ({ authPage: page }) => {+ const saved = await workspace(page);+ await page.goto(`/dashboard/applications/${saved.id}/apply`);+ await removeFirst(page);+ const newer = saved.answers.map((answer, index) =>+ index === 1 ? { ...answer, answer: "Fictional newer answer", question: "Fictional newer question" } : answer,+ );+ await expect(+ await page.request.patch(`/api/openapi/career/workspace/${saved.id}`, {+ data: { answers: newer, expected: { answers: saved.answers } },+ }),+ ).toBeOK();+ const committed = page.waitForResponse(+ (response) => response.url().includes("/career/deleteWorkspaceAnswer") && response.ok(),+ );+ const response = await committed;+ const bytes = response.request().postDataBuffer()?.byteLength ?? 0;+ expect(bytes).toBeGreaterThan(0);+ expect(bytes).toBeLessThan(60 * 1024);+ await expect+ .poll(async () => (await (await page.request.get(`/api/openapi/career/workspace/${saved.id}`)).json()).answers)+ .toEqual(newer.slice(1));+ await expect(page.getByText("Fictional newer question", { exact: true })).toBeVisible();+ await page.reload();+ await expect(page.getByText("Fictional question 0", { exact: true })).toHaveCount(0);+});++test("prepared question removal rejects a stale target and shows its current wording", async ({ authPage: page }) => {+ const saved = await workspace(page);+ await page.goto(`/dashboard/applications/${saved.id}/apply`);+ await removeFirst(page);+ const newer = saved.answers.map((answer, index) =>+ index === 0 ? { ...answer, question: "Fictional updated question" } : answer,+ );+ await expect(+ await page.request.patch(`/api/openapi/career/workspace/${saved.id}`, {+ data: { answers: newer, expected: { answers: saved.answers } },+ }),+ ).toBeOK();+ const conflict = page.waitForResponse(+ (response) => response.url().includes("/career/deleteWorkspaceAnswer") && response.status() === 409,+ );+ await conflict;+ await expect(page.getByText("Fictional updated question", { exact: true })).toBeVisible();+ const current = await page.request.get(`/api/openapi/career/workspace/${saved.id}`);+ await expect(current).toBeOK();+ expect((await current.json()).answers).toEqual(newer);+});++test("question Undo cancels deletion and cannot recreate an answer erased elsewhere", async ({+ authPage: page,+}, info) => {+ const title = "Tell us about improving a team workflow.";+ const saved = await workspace(page, [+ {+ id: "fictional-0",+ question: title,+ answer: "I introduced a shared onboarding checklist and reviewed it with the support team.",+ factIds: [],+ },+ {+ id: "fictional-1",+ question: "Why would you like to join Northwind?",+ answer: "I enjoy building reliable tools that make everyday work easier.",+ factIds: [],+ },+ ]);+ await page.goto(`/dashboard/applications/${saved.id}/apply`);+ await removeFirst(page);+ await page.screenshot({ path: info.outputPath("question-removal-undo.png"), fullPage: true, animations: "disabled" });+ await page.getByRole("button", { name: "Undo", exact: true }).click();+ await expect(page.getByText(title, { exact: true })).toBeVisible();+ await expect(page.getByRole("button", { name: "Undo", exact: true })).toHaveCount(0);+ await removeFirst(page);+ const updatedQuestion = "Fictional question added on another device.";+ const newer = [+ ...saved.answers,+ { id: "external-third", question: updatedQuestion, answer: "Fictional new answer.", factIds: [] },+ ];+ await expect(+ await page.request.patch(`/api/openapi/career/workspace/${saved.id}`, {+ data: { answers: newer, expected: { answers: saved.answers } },+ }),+ ).toBeOK();+ await expect(+ await page.request.delete(`/api/openapi/career/workspace/${saved.id}/answers/fictional-0`, {+ data: { expected: saved.answers[0] },+ }),+ ).toBeOK();+ await page.getByRole("button", { name: "Undo", exact: true }).click();+ await expect(page.getByText(updatedQuestion, { exact: true })).toBeVisible();+ await expect(page.getByRole("button", { name: "Question options", exact: true })).toHaveCount(2);+ await expect(page.getByText(title, { exact: true })).toHaveCount(0);+ await page.reload();+ await expect(page.getByText(title, { exact: true })).toHaveCount(0);+ const current = await page.request.get(`/api/openapi/career/workspace/${saved.id}`);+ await expect(current).toBeOK();+ expect((await current.json()).answers).toEqual(newer.slice(1));+});++test("owned answer deletion returns the immutable submission receipt, including an idempotent repeat", async ({+ authPage: page,+ account,+ browser,+ request,+}, info) => {+ const saved = await workspace(page);+ await expect(+ await page.request.patch(`/api/openapi/career/workspace/${saved.id}`, {+ data: { checklist: [1, 3], expected: { checklist: [] } },+ }),+ ).toBeOK();+ await expect(+ await page.request.post(`/api/openapi/career/workspace/${saved.id}/submit`, {+ data: { answers: saved.answers, expectedAnswers: saved.answers },+ }),+ ).toBeOK();+ const before = await (await page.request.get(`/api/openapi/career/workspace/${saved.id}`)).json();+ expect(before.submissionReview).toMatchObject({ checklist: [1, 3], answerVersionId: expect.any(String) });+ const stranger = createAccount(info);+ const other = await createAuthenticatedContext(browser, request, stranger, String(info.project.use.baseURL));+ try {+ const denied = await other.request.delete(`/api/openapi/career/workspace/${saved.id}/answers/fictional-0`, {+ data: { expected: saved.answers[0] },+ });+ expect(denied.status()).toBe(404);+ expect(await denied.text()).not.toContain("Fictional answer.");+ const untouched = await page.request.get(`/api/openapi/career/workspace/${saved.id}`);+ await expect(untouched).toBeOK();+ expect(await untouched.json()).toMatchObject({ answers: saved.answers, submissionReview: before.submissionReview });+ for (const _attempt of ["remove", "repeat"]) {+ const removed = await page.request.delete(`/api/openapi/career/workspace/${saved.id}/answers/fictional-0`, {+ data: { expected: saved.answers[0] },+ });+ await expect(removed).toBeOK();+ expect(await removed.json()).toMatchObject({+ answers: saved.answers.slice(1),+ submissionReview: before.submissionReview,+ });+ }+ const current = await page.request.get(`/api/openapi/career/workspace/${saved.id}`);+ await expect(current).toBeOK();+ expect(await current.json()).toMatchObject({+ answers: saved.answers.slice(1),+ submissionReview: before.submissionReview,+ });+ const rows = await database.query(+ `select w.submission_review, w.data from career_workspace w join "user" u on u.id=w.user_id where w.application_id=$1 and u.email=$2`,+ [saved.id, account.email],+ );+ expect(rows.rows[0].submission_review).toEqual(before.submissionReview);+ expect(rows.rows[0].data).not.toHaveProperty("submissionReview");+ } finally {+ await other.close();+ await deleteE2EUser(stranger);+ }+});