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: establish canonical interview Undo reads
Amruth Pillai949adf6d1091
diff --git a/apps/mobile/scripts/experience.test.mjs b/apps/mobile/scripts/experience.test.mjsindex a1bb975cb..7138942e5 100644--- a/apps/mobile/scripts/experience.test.mjs+++ b/apps/mobile/scripts/experience.test.mjs@@ -998,13 +998,14 @@ const nativeInterviewUndo = load("features/career/undo.ts", {},"@/ui": { ...ui, dismissToast() {}, toastLifetime: (value) => value },});-const nativeQueryClient = {- cancelQueries: async () => {},- invalidateQueries: async () => {- calls.push("canonical-read");- },- setQueryData: (_key, update) => calls.push({ cachedActivity: update(nativeJob).activity }),-};+const { QueryClient: InterviewQueryClient } = mobileRequire("@tanstack/react-query");+const nativeQueryClient = new InterviewQueryClient({+ defaultOptions: { queries: { retry: false, gcTime: Infinity } },+});+const nativeInterviewKey = ["application", nativeJob.id];+let nativeCanonicalRow = nativeJob;+let nativeCanonicalError = false;+let nativeCanonicalReads = 0;const nativeReminders = {leadFor: () => 30,turnOn: async () => {@@ -1065,6 +1066,7 @@ const { InterviewSheet: NativeInterviewSheet } = load("features/application-detacalls.push({ deleteRound: input });if (switchDuringDelete) interviewScope = "another-account";if (deleteInterviewError) throw new Error("Unavailable");+ nativeCanonicalRow = { ...nativeCanonicalRow, activity: [] };},},},@@ -1072,6 +1074,14 @@ const { InterviewSheet: NativeInterviewSheet } = load("features/application-deta"@/auth/session": { getAccountScope: () => interviewScope },"@/features/applications/queries": {applicationDetailQueryKey: (id) => ["application", id],+ applicationDetailQueryOptions: (id) => ({+ queryKey: ["application", id],+ queryFn: async () => {+ nativeCanonicalReads++;+ if (nativeCanonicalError) throw new Error("Fictional detail unavailable");+ return nativeCanonicalRow;+ },+ }),useInvalidateApplications: () => () => calls.push("invalidate"),},"@/features/reminders": {@@ -1130,6 +1140,10 @@ const originalClearTimeout = globalThis.clearTimeout;try {for (const scenario of ["undo",+ "hydrated-undo",+ "erased-undo",+ "read-failed-undo",+ "preflight-failed","deleted","unmount-before-ready","background",@@ -1139,6 +1153,12 @@ try {"switch-during",]) {reset();+ nativeQueryClient.clear();+ nativeCanonicalRow = nativeJob;+ nativeCanonicalReads = 0;+ nativeCanonicalError = scenario === "preflight-failed";+ if (scenario === "hydrated-undo") nativeQueryClient.setQueryData(nativeInterviewKey, nativeJob);+ else assert.equal(nativeQueryClient.getQueryState(nativeInterviewKey), undefined);interviewScope = "fixture";deleteInterviewError = scenario === "delete-failed";switchDuringDelete = scenario === "switch-during";@@ -1167,9 +1187,41 @@ try {await settle();if (scenario === "unmount-before-ready")assert.equal(calls.includes("closed"), false, "late deletion does not close the next editor");+ if (scenario === "preflight-failed") {+ assert.equal(+ calls.some((call) => call?.action?.label === "Undo"),+ false,+ );+ assert.equal(+ calls.some((call) => call?.held || call?.deleteRound),+ false,+ );+ assert.equal(calls.includes("closed"), false);+ assert.ok(nativeCanonicalRow.activity.some((entry) => entry.id === nativeRound.id));+ continue;+ }assert.equal(calls.find((call) => call?.message)?.action.label, "Undo");assert.equal(calls.filter((call) => call?.event).length, 0);- if (scenario === "undo") calls.find((call) => call?.message).action.onPress();+ assert.deepEqual(nativeQueryClient.getQueryData(nativeInterviewKey).activity, []);+ if (scenario.endsWith("undo")) {+ if (scenario === "erased-undo") nativeCanonicalRow = { ...nativeJob, activity: [] };+ nativeCanonicalError = scenario === "read-failed-undo";+ const readsBeforeUndo = nativeCanonicalReads;+ calls.find((call) => call?.message).action.onPress();+ await settle();+ assert.ok(nativeCanonicalReads > readsBeforeUndo, "Undo reads canonical data on cold and hydrated entry points");+ if (nativeCanonicalError) {+ assert.deepEqual(nativeQueryClient.getQueryData(nativeInterviewKey).activity, []);+ nativeCanonicalError = false;+ calls.findLast((call) => call?.action?.label === "Retry").action.onPress();+ await settle();+ }+ assert.deepEqual(+ nativeQueryClient.getQueryData(nativeInterviewKey).activity,+ scenario === "erased-undo" ? [] : [nativeRound],+ "canonical read restores retained identity but never an erased interview's private fields",+ );+ }if (scenario === "switch-before") interviewScope = "another-account";if (scenario === "background") for (const run of nativeInterviewListeners) run("background");commit?.();@@ -1189,7 +1241,7 @@ try {assert.equal(shared.event.uid, nativeRound.id);assert.equal(shared.method, "CANCEL");} else assert.equal(cancellation, undefined);- if (scenario === "undo" || scenario === "switch-before")+ if (scenario.endsWith("undo") || scenario === "switch-before")assert.equal(calls.find((call) => call?.deleteRound),undefined,diff --git a/apps/mobile/src/features/application-detail/interview-sheet.tsx b/apps/mobile/src/features/application-detail/interview-sheet.tsxindex 9a5f6c269..cb9fa71e8 100644--- a/apps/mobile/src/features/application-detail/interview-sheet.tsx+++ b/apps/mobile/src/features/application-detail/interview-sheet.tsx@@ -20,7 +20,11 @@ import {} from "./hooks";import { client, prepareRpc } from "@/api/client";import { getAccountScope } from "@/auth/session";-import { applicationDetailQueryKey, useInvalidateApplications } from "@/features/applications/queries";+import {+ applicationDetailQueryKey,+ applicationDetailQueryOptions,+ useInvalidateApplications,+} from "@/features/applications/queries";import { withUndo } from "@/features/career/undo";import {DEFAULT_LEAD,@@ -288,6 +292,8 @@ function InterviewForm({ application, interview, onClose }: InterviewFormProps)withUndo({message: t`Interview deleted`,prepare: async () => {+ // Register the canonical reader before offering Undo, including summary-only calendar entry points.+ await queryClient.fetchQuery({ ...applicationDetailQueryOptions(application.id), staleTime: 0 });const request = await prepareRpc(client.applications.deleteTimelineEntry, {id: application.id,entryId: interview.id,diff --git a/apps/web/src/features/applications/components/interview-dialog.test.tsx b/apps/web/src/features/applications/components/interview-dialog.test.tsxindex ade8ba95d..a71cc6782 100644--- a/apps/web/src/features/applications/components/interview-dialog.test.tsx+++ b/apps/web/src/features/applications/components/interview-dialog.test.tsx@@ -27,7 +27,10 @@ vi.mock("@/libs/orpc/client", () => ({career: { schedules: { queryOptions: () => ({ queryKey: ["schedules"], queryFn: async () => [] }) } },},}));-vi.mock("../queries", () => ({ applicationsListQueryKey: () => ["applications"] }));+vi.mock("../queries", () => ({+ applicationsListQueryKey: () => ["applications"],+ applicationDetailQueryOptions: () => ({ queryKey: ["application"], queryFn: async () => (await api.read())[0] }),+}));vi.mock("@tanstack/react-router", () => ({useRouteContext: () => ({ session: { user: { id: "interview-test", timezone: "Europe/Berlin" } } }),}));diff --git a/apps/web/src/features/applications/components/interview-dialog.tsx b/apps/web/src/features/applications/components/interview-dialog.tsxindex 9ce390f92..402cf76a9 100644--- a/apps/web/src/features/applications/components/interview-dialog.tsx+++ b/apps/web/src/features/applications/components/interview-dialog.tsx@@ -21,7 +21,7 @@ import { cn } from "@reactive-resume/utils/style";import { fromZonedDateTime } from "@reactive-resume/utils/timezone";import { interviewCalendarAction, showInterviewCancellation } from "../calendar";import { dayKey, interviewTypeLabel } from "../interviews";-import { applicationsListQueryKey } from "../queries";+import { applicationDetailQueryOptions, applicationsListQueryKey } from "../queries";import { Combobox } from "@/components/ui/combobox";import { useCareerTime, withQueryUndo } from "@/features/career/shared";import { useClosingValue } from "@/hooks/use-closing-value";@@ -306,6 +306,8 @@ export function InterviewDialog({description: t`Interview deleted`,errorMessage: t`Couldn't delete the interview. Try again.`,prepare: async () => {+ // Calendar summaries can have no detail query, or a hydrated row without its read function.+ await queryClient.fetchQuery({ ...applicationDetailQueryOptions(applicationId), staleTime: 0 });const request = await prepareRpc(client.applications.deleteTimelineEntry, {id: applicationId,entryId: editing.id,diff --git a/docs/contributing/career-platform.mdx b/docs/contributing/career-platform.mdxindex 27edf10ec..fc51cdf0a 100644--- a/docs/contributing/career-platform.mdx+++ b/docs/contributing/career-platform.mdx@@ -145,7 +145,7 @@ Dates and times are entered in the account's timezone. Recurring discovery presePause or delete a schedule to cancel its queued or running work. Rescheduling an interview moves its briefing schedules to the new time and cancels work queued for the old one. Removing the interview pauses them and adds a notification to Today. Cancellation prevents later result publication but can't undo provider calls already made.-Interview calendar files use the shared UTC ICS builder in `packages/utils` and interview mapping in `packages/schema`. Web and native save notices offer **Update your calendar**; committed deletions offer **Download cancellation**. Both keep the round's original UID. Exports include METHOD and epoch-second SEQUENCE; cancellations add STATUS:CANCELLED, advance a same-second sequence and omit VALARM. Undo must never export cancellation. These files require manual import into an external calendar; calendar-client import behavior is a separate compatibility check.+Interview calendar files use the shared UTC ICS builder in `packages/utils` and interview mapping in `packages/schema`. Web and native save notices offer **Update your calendar**; committed deletions offer **Download cancellation**. Both keep the round's original UID. Exports include METHOD and epoch-second SEQUENCE; cancellations add STATUS:CANCELLED, advance a same-second sequence and omit VALARM. Undo must never export cancellation. Interview deletion preparation loads and registers the canonical application detail reader before acknowledging the action, including Calendar summaries without a detail query or hydrated without a query function. Undo and Retry must read that owner before revealing retained data; they never write an old interview back. These files require manual import into an external calendar; calendar-client import behavior is a separate compatibility check.### Understand delivery and retry limitsdiff --git a/docs/guides/career-workspace-reference.mdx b/docs/guides/career-workspace-reference.mdxindex 9faea0e0b..95a87451c 100644--- a/docs/guides/career-workspace-reference.mdx+++ b/docs/guides/career-workspace-reference.mdx@@ -249,4 +249,4 @@ a new letter, choose **Resume for a new letter**, or **No resume** for a standalA letter recorded as sent keeps its application link; pickers label unavailable targets **Letter already sent**.Builders offer a back link to their application. Submitted versions remain immutable; current drafts stay editable.-Contact and interview removal uses the same prepared **Undo** window on web and native. Reloading or closing a tab, or putting the native app in the background, sends an acknowledged pending deletion. Undo reads the current application before showing surviving content; **Retry** repeats that read without recreating erased text. See [Contacts](/guides/managing-an-application#contacts) and [Editing or deleting an interview](/guides/scheduling-interviews#edit-or-delete-an-interview).+Contact and interview removal uses the same prepared **Undo** window on web and native. Interview removal first loads the current application, including when opened directly from Calendar. Reloading or closing a tab, or putting the native app in the background, sends an acknowledged pending deletion. Undo reads the current application before showing surviving content; **Retry** repeats that read without recreating erased text. See [Contacts](/guides/managing-an-application#contacts) and [Editing or deleting an interview](/guides/scheduling-interviews#edit-or-delete-an-interview).diff --git a/docs/guides/scheduling-interviews.mdx b/docs/guides/scheduling-interviews.mdxindex d8385fe4d..76e92020e 100644--- a/docs/guides/scheduling-interviews.mdx+++ b/docs/guides/scheduling-interviews.mdx@@ -82,7 +82,7 @@ A date and time skipped by a daylight-saving change is rejected. Pick a valid loTo remove it, select **Delete** (**Delete interview** in the native app). The notice offers **Undo** for six seconds. Undo keeps the original round and its linked schedules. Removing an interview pauses its briefing schedules; rescheduling moves them to the new time. Check **Career → Today → Schedules** after a change.-The notice appears once the pending deletion is ready. Reloading, closing the tab or putting the native app in the background sends that acknowledged deletion. Undo cancels it and reloads the current application; a round already deleted in another session is not recreated. If that read fails, use **Retry** to refresh it. Device reminders are canceled only after the deletion succeeds.+The current application must load before the pending deletion is ready and its notice appears. Reloading, closing the tab or putting the native app in the background sends that acknowledged deletion. Undo cancels it and reloads the current application; a round already deleted in another session is not recreated. If that read fails, use **Retry** to refresh it. Device reminders are canceled only after the deletion succeeds.<Frame caption="Phone browser: the prepared interview deletion offers Undo"><img@@ -91,6 +91,13 @@ The notice appears once the pending deletion is ready. Reloading, closing the ta/></Frame>+<Frame caption="If Undo cannot reload the interview, Retry checks again before showing it.">+ <img+ src="/images/guides/scheduling-interviews/interview-undo-retry.png"+ alt="Phone browser Calendar keeps interviews hidden while a Couldn't load. Try again. notice offers Retry"+ />+</Frame>+After you save an edited interview, select **Update your calendar** in the notice to download its updated `.ics` file. After a deletion completes, select **Download cancellation** to download a cancellation for the same event. These actions are available on web and in the native app. Undo does not generate a cancellation. Deleting through **Activity** (**Timeline** in the native app) asks for confirmation instead of offering Undo, then offers the same cancellation action.<Frame caption="After changing an interview, download its updated calendar file from the save notice.">diff --git a/docs/images/guides/scheduling-interviews/interview-undo-retry.png b/docs/images/guides/scheduling-interviews/interview-undo-retry.pngnew file mode 100644index 000000000..2de756f87Binary files /dev/null and b/docs/images/guides/scheduling-interviews/interview-undo-retry.png differdiff --git a/tests/e2e/specs/interview-undo-canonical.spec.ts b/tests/e2e/specs/interview-undo-canonical.spec.tsnew file mode 100644index 000000000..062f101d3--- /dev/null+++ b/tests/e2e/specs/interview-undo-canonical.spec.ts@@ -0,0 +1,130 @@+import type { InterviewTimelineEntry } from "@reactive-resume/schema/applications/data";+import { Pool } from "pg";+import { failRpcProcedure } from "../fixtures/rpc-failure";+import { expect, test } from "../fixtures/test";++let database: Pool;+test.beforeAll(() => {+ if (!process.env.DATABASE_URL) throw new Error("Disposable DATABASE_URL is required.");+ database = new Pool({ connectionString: process.env.DATABASE_URL, max: 2 });+});+test.afterAll(async () => await database.end());++for (const scenario of ["cold-retained", "hydrated-erased"] as const) {+ test(`Calendar interview Undo reads canonical data and retries without writes: ${scenario}`, async ({+ authPage: page,+ account,+ }, info) => {+ const create = async (company: string) => {+ const response = await page.request.post("/api/openapi/applications", {+ data: { company, role: "Engineer", status: "interview" },+ });+ await expect(response).toBeOK();+ return (await response.json()) as string;+ };+ const id = await create("Fictional Calendar Undo");+ await expect(+ await page.request.post(`/api/openapi/applications/${id}/interviews`, {+ data: {+ at: new Date(Date.now() + 2 * 3_600_000).toISOString(),+ kind: "technical",+ timezone: "UTC",+ notes: "Fictional private preparation note",+ },+ }),+ ).toBeOK();+ const response = await page.request.get(`/api/openapi/applications/${id}`);+ await expect(response).toBeOK();+ const round = ((await response.json()) as { activity: InterviewTimelineEntry[] }).activity.find(+ (entry) => entry.type === "interview",+ );+ if (!round) throw new Error("Fixture interview was not persisted.");+ if (scenario === "cold-retained") for (let index = 0; index < 5; index++) await create(`Fictional Newer ${index}`);+ const summary = await page.request.get("/api/openapi/applications/summary", {+ params: { includeInitialDetails: 3 },+ });+ await expect(summary).toBeOK();+ const initial = ((await summary.json()) as { id: string; initialDetail?: unknown }[]).find((row) => row.id === id);+ if (scenario === "cold-retained") expect(initial?.initialDetail).toBeUndefined();+ else expect(initial?.initialDetail).toBeTruthy();++ let detailReads = 0;+ let writes = 0;+ let unavailable = false;+ await page.route("**/api/rpc/**", async (route) => {+ const request = route.request();+ const batched = new URL(request.url()).pathname.endsWith("/__batch__");+ const entries: { url: string }[] = batched ? JSON.parse(request.postData() ?? "[]") : [{ url: request.url() }];+ const paths = entries.map((entry) => new URL(entry.url).pathname);+ if (paths.includes("/api/rpc/applications/getById")) detailReads++;+ if (+ paths.some((path) =>+ /^\/api\/rpc\/applications\/(create|update|add|delete|restore|set|move|log|clear)/.test(path),+ )+ )+ writes++;+ if (unavailable) {+ const target = paths.includes("/api/rpc/applications/getById")+ ? "/api/rpc/applications/getById"+ : "/api/rpc/applications/listSummary";+ await failRpcProcedure(route, target, "Fictional readback unavailable");+ } else await route.continue();+ });+ const storedRounds = async () => {+ const result = await database.query(+ `select a.activity from application a join "user" u on u.id = a.user_id where a.id = $1 and u.email = $2`,+ [id, account.email],+ );+ return (result.rows[0] as { activity: InterviewTimelineEntry[] }).activity;+ };+ await page.setViewportSize({ width: 390, height: 844 });+ await page.goto("/dashboard/applications?view=calendar");+ const card = page.locator(`[data-upcoming-interview="${round.id}"]`);+ await expect(card).toBeVisible();+ await card.getByRole("button").filter({ hasText: "Fictional Calendar Undo" }).click();+ const editor = page.getByRole("dialog", { name: "Edit interview", exact: true });+ await expect(editor).toBeVisible();+ if (scenario === "cold-retained") expect(detailReads).toBe(0);+ await editor.getByRole("button", { name: "Delete", exact: true }).click();+ const undo = page.getByRole("button", { name: "Undo", exact: true });+ await expect(undo).toBeVisible();+ await expect(card).toHaveCount(0);+ if (scenario === "hydrated-erased") {+ await expect(await page.request.delete(`/api/openapi/applications/${id}/timeline/${round.id}`)).toBeOK();+ }+ const retained = scenario === "cold-retained";+ expect((await storedRounds()).some((entry) => entry.id === round.id)).toBe(retained);+ const beforeUndo = detailReads;+ unavailable = true;+ await undo.click();+ await expect.poll(() => detailReads).toBeGreaterThan(beforeUndo);+ await expect(page.getByRole("button", { name: "Retry", exact: true })).toBeVisible();+ await expect(card).toHaveCount(0);+ expect(writes).toBe(0);+ expect((await storedRounds()).some((entry) => entry.id === round.id)).toBe(retained);+ await page.screenshot({+ path: info.outputPath("interview-undo-retry.png"),+ fullPage: true,+ animations: "disabled",+ });+ unavailable = false;+ const beforeRetry = detailReads;+ const retryRead = page.waitForResponse((response) => {+ const request = response.request();+ const entries: { url: string }[] = new URL(request.url()).pathname.endsWith("/__batch__")+ ? JSON.parse(request.postData() ?? "[]")+ : [{ url: request.url() }];+ return response.ok() && entries.some((entry) => new URL(entry.url).pathname === "/api/rpc/applications/getById");+ });+ await page.getByRole("button", { name: "Retry", exact: true }).click();+ await (await retryRead).finished();+ await expect.poll(() => detailReads).toBeGreaterThan(beforeRetry);+ if (retained) await expect(card).toBeVisible();+ else await expect(card).toHaveCount(0);+ expect(writes).toBe(0);+ await page.reload();+ if (retained) await expect(card).toBeVisible();+ else await expect(card).toHaveCount(0);+ expect((await storedRounds()).some((entry) => entry.id === round.id)).toBe(retained);+ });+}