Skip to content

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!

fix: persist contact and interview deletion through exit

Amruth Pillaie18f54580c4e
diff --git a/apps/mobile/scripts/career-undo.test.mjs b/apps/mobile/scripts/career-undo.test.mjs
index 58cbeed49..3bfa1d09c 100644
--- a/apps/mobile/scripts/career-undo.test.mjs
+++ b/apps/mobile/scripts/career-undo.test.mjs
@@ -8,7 +8,8 @@ const { QueryClient } = createRequire(new URL("../package.json", import.meta.url
function load(path, mocks, timers) {
const module = { exports: {} };
const code = transformSync(readFileSync(new URL(path, import.meta.url), "utf8"), {
- loader: "ts",
+ loader: path.endsWith(".tsx") ? "tsx" : "ts",
+ jsx: "automatic",
format: "cjs",
}).code;
new Function("require", "module", "exports", "setTimeout", "clearTimeout", code)(
@@ -280,7 +281,20 @@ async function rowsHarness() {
cursor = 0;
return readRows();
}
- return { ...h, env, queryClient, key, render, unmount: () => cleanup.forEach((run) => run?.()) };
+ return {
+ ...h,
+ env,
+ queryClient,
+ key,
+ react,
+ readRows,
+ render,
+ renderComponent: (component) => {
+ cursor = 0;
+ return component();
+ },
+ unmount: () => cleanup.forEach((run) => run?.()),
+ };
}
const drain = () => new Promise((resolve) => setImmediate(resolve));
@@ -367,3 +381,180 @@ test("actual native Undo reveals canonical list even while an unrelated Career e
h.unmount();
h.queryClient.clear();
});
+
+test("actual native committed row removal clears temporary hiding only after canonical readback", async () => {
+ const h = await rowsHarness();
+ try {
+ const preparing = h.request();
+ h.render().remove("fact", "Removed fictional contact", () => preparing, h.key);
+ await preparing;
+ assert.deepEqual(h.render().hidden, ["fact"]);
+ h.env.canonical = [{ id: "survivor", text: "Fictional second matching contact" }];
+ h.background();
+ await drain();
+ assert.equal(h.env.sent, 1);
+ assert.deepEqual(h.queryClient.getQueryData(h.key), h.env.canonical);
+ assert.deepEqual(h.render().hidden, []);
+ } finally {
+ h.unmount();
+ h.queryClient.clear();
+ }
+});
+
+async function contactsHarness(contacts) {
+ const h = await rowsHarness();
+ h.env.application = { id: "fictional-job", contacts, contactsVersion: "reviewed" };
+ h.env.snapshotWrites = [];
+ const key = ["application", "fictional-job"];
+ await h.queryClient.fetchQuery({
+ queryKey: key,
+ queryFn: () => {
+ if (h.env.offline) throw new Error("offline");
+ return structuredClone(h.env.application);
+ },
+ });
+ const tag = (parts, ...values) => parts.reduce((text, part, index) => text + part + (values[index] ?? ""), "");
+ const runtime = { jsx: (type, props) => ({ type, props }), jsxs: (type, props) => ({ type, props }) };
+ const { ContactsSheet } = load("../src/features/application-detail/sheets.tsx", {
+ react: h.react,
+ "react/jsx-runtime": runtime,
+ "@lingui/react/macro": { useLingui: () => ({ t: tag }) },
+ "expo-web-browser": {},
+ "react-native": { View: "View", Linking: {} },
+ "@reactive-resume/schema/applications/data": {},
+ "@reactive-resume/schema/applications/follow-up": {},
+ "@reactive-resume/schema/applications/posting-source": {},
+ "@reactive-resume/utils/timezone": {},
+ "./date-field": {},
+ "./hooks": {},
+ "@/features/applications-board/calendar": {},
+ "@/features/applications/error": {},
+ "@/features/applications/lane-notice": {},
+ "@/features/applications/lane-queries": {},
+ "@/features/applications/lanes": {},
+ "@/features/applications/prior-no-response": {},
+ "@/features/applications/stage-actions": {},
+ "@/features/applications/stages": {},
+ "@/features/reminders": {},
+ "@/features/applications/queries": {
+ applicationDetailQueryKey: () => key,
+ useApplicationMutations: () => ({
+ update: {
+ isPending: false,
+ mutate: (input, callbacks) => {
+ h.env.snapshotWrites.push(input);
+ callbacks.onSuccess();
+ },
+ },
+ }),
+ },
+ "@/features/career/hooks": {
+ useUndoRows: h.readRows,
+ client: {
+ applications: {
+ deleteContact: async (input) => {
+ assert.equal(input.expectedVersion, h.env.application.contactsVersion);
+ h.env.application = {
+ ...h.env.application,
+ contacts: h.env.application.contacts.filter((_, index) => index !== input.index),
+ contactsVersion: "after-removal",
+ };
+ },
+ },
+ },
+ prepareRpc: (procedure, input) => {
+ const account = h.env.account;
+ return prepareRequest(async (defer) => {
+ await defer(async () => {
+ assert.equal(account, h.env.account);
+ h.env.sent++;
+ await procedure(input);
+ return new Response();
+ });
+ });
+ },
+ },
+ "@/ui": {
+ showToast: (notice) => h.notices.push(notice),
+ ...Object.fromEntries(
+ ["Sheet", "Text", "ListRow", "View", "IconButton", "TextField", "Button"].map((name) => [name, name]),
+ ),
+ useTheme: () => ({ space: { s2: 8, s3: 12, s4: 16 } }),
+ },
+ });
+ const tree = () =>
+ h.renderComponent(() => ContactsSheet({ application: h.queryClient.getQueryData(key), open: true, onClose() {} }));
+ const nodes = (value) =>
+ Array.isArray(value)
+ ? value.flatMap(nodes)
+ : value && typeof value === "object" && "props" in value
+ ? [value, ...Object.values(value.props).flatMap(nodes)]
+ : [];
+ const remove = (index) =>
+ nodes(tree())
+ .filter((node) => node.type === "IconButton" && node.props.label.startsWith("Remove "))
+ [index].props.onPress();
+ const names = () =>
+ nodes(tree())
+ .filter((node) => node.type === "ListRow")
+ .map((node) => node.props.title);
+ return { ...h, tree, nodes: () => nodes(tree()), remove, names, appKey: key };
+}
+const fictionalSam = { name: "Fictional Sam", role: "", type: "", email: "", phone: "" };
+
+test("native contact Undo never writes erased text back; failed read stays hidden until read-only Retry", async () => {
+ const h = await contactsHarness([fictionalSam]);
+ try {
+ h.nodes()
+ .find((node) => node.type === "TextField" && node.props.label === "Name")
+ .props.onChangeText("Fictional Alex");
+ h.remove(0);
+ await drain();
+ assert.equal(h.env.sent, 0);
+ assert.deepEqual(h.env.snapshotWrites, []);
+ assert.deepEqual(h.names(), []);
+ assert.equal(
+ h.nodes().find((node) => node.type === "Button" && node.props.label === "Add contact").props.disabled,
+ true,
+ "saving a stale contacts array stays unavailable until canonical readback",
+ );
+ h.env.application = { ...h.env.application, contacts: [], contactsVersion: "externally-erased" };
+ h.env.offline = true;
+ h.notices.find((notice) => notice.action?.label === "Undo").action.onPress();
+ await drain();
+ assert.deepEqual(h.names(), []);
+ assert.equal(h.notices.at(-1).action.label, "Retry");
+ h.env.offline = false;
+ h.notices.at(-1).action.onPress();
+ await drain();
+ assert.deepEqual(h.queryClient.getQueryData(h.appKey).contacts, []);
+ assert.deepEqual(h.names(), []);
+ assert.equal(h.env.sent, 0);
+ assert.deepEqual(h.env.snapshotWrites, []);
+ assert.equal(
+ h.nodes().find((node) => node.type === "Button" && node.props.label === "Add contact").props.disabled,
+ false,
+ );
+ } finally {
+ h.unmount();
+ h.queryClient.clear();
+ }
+});
+
+test("native contact background deletion keeps an identical sibling visible after canonical readback", async () => {
+ const h = await contactsHarness([fictionalSam, fictionalSam]);
+ try {
+ h.remove(1);
+ await drain();
+ assert.deepEqual(h.names(), ["Fictional Sam"]);
+ h.background();
+ assert.equal(h.env.sent, 1);
+ await drain();
+ assert.deepEqual(h.env.application.contacts, [fictionalSam]);
+ assert.deepEqual(h.names(), ["Fictional Sam"]);
+ assert.deepEqual(h.env.snapshotWrites, []);
+ } finally {
+ h.unmount();
+ h.queryClient.clear();
+ }
+});
diff --git a/apps/mobile/scripts/experience.test.mjs b/apps/mobile/scripts/experience.test.mjs
index ddf34fa16..b043c8010 100644
--- a/apps/mobile/scripts/experience.test.mjs
+++ b/apps/mobile/scripts/experience.test.mjs
@@ -966,7 +966,39 @@ const nativeRound = {
participants: [{ name: "Maya Example", role: "Lead" }],
};
const nativeJob = { ...application, role: "Engineer", activity: [nativeRound] };
+let pendingInterviewReady;
+let nativeFormCleanup;
+const nativeFormReact = {
+ ...react,
+ useLayoutEffect: (run, deps) => {
+ const state = react.useRef({ deps: null });
+ if (!state.current.deps || deps.some((value, index) => value !== state.current.deps[index])) {
+ nativeFormCleanup?.();
+ state.current.deps = deps;
+ nativeFormCleanup = run();
+ }
+ },
+};
+const nativeInterviewListeners = new Set();
+const { prepareRequest: prepareInterviewRequest } = load("../../../packages/utils/src/deferred-request.ts");
+const nativeInterviewUndo = load("features/career/undo.ts", {
+ "@/auth/session": { getAccountScope: () => interviewScope },
+ "react-native": {
+ AppState: {
+ currentState: "active",
+ addEventListener: (_name, run) => {
+ nativeInterviewListeners.add(run);
+ return { remove: () => nativeInterviewListeners.delete(run) };
+ },
+ },
+ },
+ "@/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 nativeReminders = {
@@ -981,6 +1013,7 @@ const nativeReminders = {
},
};
const { InterviewSheet: NativeInterviewSheet } = load("features/application-detail/interview-sheet.tsx", {
+ react: nativeFormReact,
"react-native": { View: "View", Linking: { openSettings: () => calls.push("settings") } },
"@tanstack/react-query": { useQueryClient: () => nativeQueryClient },
"@reactive-resume/schema/applications/data": mobileRequire("@reactive-resume/schema/applications/data"),
@@ -1007,7 +1040,21 @@ const { InterviewSheet: NativeInterviewSheet } = load("features/application-deta
},
}),
},
+ "@/features/career/undo": nativeInterviewUndo,
"@/api/client": {
+ prepareRpc: (procedure, input) => {
+ const scope = interviewScope;
+ return prepareInterviewRequest(async (defer) => {
+ await pendingInterviewReady;
+ let saved;
+ await defer(async () => {
+ assert.equal(interviewScope, scope);
+ saved = await procedure(input);
+ return new Response();
+ });
+ return saved;
+ });
+ },
client: {
applications: {
deleteTimelineEntry: async (input) => {
@@ -1077,7 +1124,16 @@ switchDuringSave = saveInterviewError = false;
const originalTimeout = globalThis.setTimeout;
const originalClearTimeout = globalThis.clearTimeout;
try {
- for (const scenario of ["undo", "deleted", "reminder-failed", "delete-failed", "switch-before", "switch-during"]) {
+ for (const scenario of [
+ "undo",
+ "deleted",
+ "unmount-before-ready",
+ "background",
+ "reminder-failed",
+ "delete-failed",
+ "switch-before",
+ "switch-during",
+ ]) {
reset();
interviewScope = "fixture";
deleteInterviewError = scenario === "delete-failed";
@@ -1092,15 +1148,35 @@ try {
globalThis.clearTimeout = () => {
commit = null;
};
+ let releaseReady;
+ pendingInterviewReady =
+ scenario === "unmount-before-ready"
+ ? new Promise((resolve) => {
+ releaseReady = resolve;
+ })
+ : undefined;
control(renderNativeInterview(), "Delete interview").onPress();
+ if (scenario === "unmount-before-ready") {
+ nativeFormCleanup?.();
+ releaseReady();
+ }
+ await settle();
+ if (scenario === "unmount-before-ready")
+ assert.equal(calls.includes("closed"), false, "late deletion does not close the next editor");
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();
if (scenario === "switch-before") interviewScope = "another-account";
+ if (scenario === "background") for (const run of nativeInterviewListeners) run("background");
commit?.();
await settle();
const cancellation = calls.find((call) => call?.action?.label === "Download cancellation");
- if (scenario === "deleted" || scenario === "reminder-failed") {
+ if (
+ scenario === "deleted" ||
+ scenario === "unmount-before-ready" ||
+ scenario === "background" ||
+ scenario === "reminder-failed"
+ ) {
assert.ok(cancellation, "only a committed server delete offers cancellation");
if (reminderOffError) assert.ok(cancellation.message.includes("Couldn't cancel its device reminder"));
cancellation.action.onPress();
diff --git a/apps/mobile/src/features/application-detail/interview-sheet.tsx b/apps/mobile/src/features/application-detail/interview-sheet.tsx
index 6aeacabb2..9a5f6c269 100644
--- a/apps/mobile/src/features/application-detail/interview-sheet.tsx
+++ b/apps/mobile/src/features/application-detail/interview-sheet.tsx
@@ -3,7 +3,7 @@ import type { InterviewKind, InterviewTimelineEntry } from "@reactive-resume/sch
import { i18n } from "@lingui/core";
import { useLingui } from "@lingui/react/macro";
import { useQueryClient } from "@tanstack/react-query";
-import { useRef, useState } from "react";
+import { useLayoutEffect, useRef, useState } from "react";
import { Linking, View } from "react-native";
import { interviewDetailsSchema, nextInterviewKind } from "@reactive-resume/schema/applications/data";
import { generateId } from "@reactive-resume/utils/string";
@@ -18,9 +18,10 @@ import {
useDetailMutations,
useUserTime,
} from "./hooks";
-import { client } from "@/api/client";
+import { client, prepareRpc } from "@/api/client";
import { getAccountScope } from "@/auth/session";
import { applicationDetailQueryKey, useInvalidateApplications } from "@/features/applications/queries";
+import { withUndo } from "@/features/career/undo";
import {
DEFAULT_LEAD,
holdReminder,
@@ -39,7 +40,6 @@ import {
ListRow,
Segmented,
showToast,
- toastLifetime,
Switch,
Text,
TextArea,
@@ -49,7 +49,6 @@ import {
const KINDS: InterviewKind[] = ["screening", "technical", "behavioral", "onsite", "other"];
const LENGTHS = [30, 45, 60, 90];
-const UNDO_MS = 6000;
type Participant = { id: string; name: string; role: string; profileUrl: string };
@@ -143,6 +142,14 @@ function InterviewForm({ application, interview, onClose }: InterviewFormProps)
);
const [draft, setDraft] = useState(initial);
const saving = useRef(false);
+ const activeForm = useRef<symbol | null>(null);
+ useLayoutEffect(() => {
+ activeForm.current = Symbol();
+ return () => {
+ activeForm.current = null;
+ };
+ }, [application.id, interview?.id]);
+
const [zonePicker, setZonePicker] = useState(false);
const [zoneLimit, setZoneLimit] = useState(40);
const [zoneQuery, setZoneQuery] = useState("");
@@ -255,54 +262,68 @@ function InterviewForm({ application, interview, onClose }: InterviewFormProps)
}
};
- // Hidden at once and committed when the undo toast ends, so Undo keeps the round's identity and history.
- // ponytail: the commit lives in a JS timer; if the app is killed first, the interview simply stays.
const remove = () => {
if (!interview || saving.current) return;
+ const form = activeForm.current;
+ saving.current = true;
const scope = getAccountScope();
+ const current = () => !!scope && scope === getAccountScope();
const key = applicationDetailQueryKey(application.id);
- queryClient.setQueryData<Application>(key, (current) =>
- current ? { ...current, activity: current.activity.filter((entry) => entry.id !== interview.id) } : current,
- );
- onClose();
- // Its reminder stays scheduled through the undo window and is cancelled only once the delete commits.
- holdReminder(interview.id);
- const target = { kind: "interview", applicationId: application.id, entryId: interview.id } as const;
- const timer = setTimeout(() => {
- // The form is gone by now, so this calls the client directly rather than through a mounted mutation.
- if (!scope || scope !== getAccountScope()) {
- releaseReminder(interview.id);
- return;
- }
- void client.applications
- .deleteTimelineEntry({ id: application.id, entryId: interview.id })
- .then(async () => {
+ const reconcile = async () => {
+ releaseReminder(interview.id);
+ if (!current()) return;
+ await queryClient.cancelQueries({ queryKey: key });
+ if (!current()) return;
+ await queryClient.invalidateQueries({ queryKey: key, refetchType: "all" }, { throwOnError: true });
+ if (current()) void invalidate();
+ };
+ const failed = () => {
+ saving.current = false;
+ if (current())
+ showToast({
+ message: t`Couldn't delete the interview. Try again.`,
+ action: { label: t`Retry`, onPress: () => void reconcile().catch(failed) },
+ });
+ };
+ withUndo({
+ message: t`Interview deleted`,
+ prepare: async () => {
+ const request = await prepareRpc(client.applications.deleteTimelineEntry, {
+ id: application.id,
+ entryId: interview.id,
+ });
+ return {
+ send: request.send,
+ cancel: () => {
+ request.cancel();
+ releaseReminder(interview.id);
+ },
+ };
+ },
+ onReady: () => {
+ holdReminder(interview.id);
+ queryClient.setQueryData<Application>(key, (row) =>
+ row ? { ...row, activity: row.activity.filter((entry) => entry.id !== interview.id) } : row,
+ );
+ if (form && activeForm.current === form) onClose();
+ },
+ restore: reconcile,
+ failed,
+ commit: async (result) => {
+ try {
+ await result;
let message = t`Interview deleted`;
+ const target = { kind: "interview", applicationId: application.id, entryId: interview.id } as const;
try {
- if (scope === getAccountScope()) await reminders.turnOff(target);
+ if (current()) await reminders.turnOff(target);
} catch {
message = t`Interview deleted. Couldn't cancel its device reminder.`;
}
showInterviewCancellation(application, interview, scope, message);
- })
- .catch(() => {
- if (scope === getAccountScope()) showToast({ message: t`Couldn't delete the interview. Try again.` });
- })
- .finally(() => {
- releaseReminder(interview.id);
- if (scope === getAccountScope()) void invalidate();
- });
- }, toastLifetime(UNDO_MS));
- showToast({
- message: t`Interview deleted`,
- duration: UNDO_MS,
- action: {
- label: t`Undo`,
- onPress: () => {
- clearTimeout(timer);
+ } finally {
releaseReminder(interview.id);
- if (scope === getAccountScope()) void invalidate();
- },
+ if (current()) void invalidate();
+ }
},
});
};
diff --git a/apps/mobile/src/features/application-detail/sheets.tsx b/apps/mobile/src/features/application-detail/sheets.tsx
index dc1d6496e..e3ee2e531 100644
--- a/apps/mobile/src/features/application-detail/sheets.tsx
+++ b/apps/mobile/src/features/application-detail/sheets.tsx
@@ -8,7 +8,7 @@ import type {
} from "@reactive-resume/schema/applications/data";
import { useLingui } from "@lingui/react/macro";
import { openBrowserAsync } from "expo-web-browser";
-import { useEffect, useRef, useState } from "react";
+import { useState } from "react";
import { Linking, View } from "react-native";
import { contactSchema } from "@reactive-resume/schema/applications/data";
import { followUpInstant, isDateOnlyFollowUp } from "@reactive-resume/schema/applications/follow-up";
@@ -22,9 +22,10 @@ import { LaneNotice } from "@/features/applications/lane-notice";
import { useApplicationLanes } from "@/features/applications/lane-queries";
import { getLaneLabel, laneInput, resolveLane } from "@/features/applications/lanes";
import { PriorNoResponse } from "@/features/applications/prior-no-response";
-import { useApplication, useApplicationMutations } from "@/features/applications/queries";
+import { applicationDetailQueryKey, useApplication, useApplicationMutations } from "@/features/applications/queries";
import { useAcceptedPrompt } from "@/features/applications/stage-actions";
import { CLOSED_REASONS, getClosedReasonLabel } from "@/features/applications/stages";
+import { client, prepareRpc, useUndoRows } from "@/features/career/hooks";
import { DEFAULT_LEAD, REMINDER_LEADS, useReminders, zonedParts } from "@/features/reminders";
import {
Banner,
@@ -489,18 +490,14 @@ export function ContactsSheet({ application, open, onClose }: ApplicationContent
const [error, setError] = useState("");
// The contact being corrected: its position, and what it said when the form opened (web contacts.tsx).
const [editing, setEditing] = useState<{ index: number; original: Contact } | null>(null);
- // Undo reinserts into the list as it is then, not the list from before the removal.
- const latest = useRef(application.contacts);
- useEffect(() => {
- latest.current = application.contacts;
- }, [application.contacts]);
+ const undo = useUndoRows();
+ const contactId = (contact: Contact, index: number) => JSON.stringify([index, contactKey(contact)]);
+ const contacts = application.contacts.filter((contact, index) => !undo.hidden.includes(contactId(contact, index)));
const save = (contacts: Contact[], onSuccess = () => {}) =>
update.mutate(
{ id: application.id, contacts },
{
onSuccess: () => {
- // The saved list is current at once, before the detail refetch lands, so Undo builds on it.
- latest.current = contacts;
onSuccess();
},
onError: () => showToast({ message: t`Couldn't save the contacts. Try again.` }),
@@ -538,64 +535,63 @@ export function ContactsSheet({ application, open, onClose }: ApplicationContent
phone: contact.phone,
});
};
- // Removing saves at once. Undo puts the contact back where it was in the list as it is then, so a contact added or
- // edited after the removal survives.
const remove = (index: number) => {
const contact = application.contacts[index];
if (!contact) return;
- // Identical contacts are allowed, so Undo compares how many match, not whether one does.
- const matches = (list: Contact[]) => list.filter((item) => sameContact(item, contact)).length;
- const before = matches(application.contacts);
if (editing) {
setEditing(null);
setDraft(EMPTY_CONTACT);
setError("");
}
- save(
- application.contacts.filter((_, i) => i !== index),
- () =>
- showToast({
- message: t`Removed ${contact.name}`,
- undo: () => {
- const current = latest.current;
- if (matches(current) >= before) return;
- save([...current.slice(0, index), contact, ...current.slice(index)]);
- },
- }),
+ undo.remove(
+ contactId(contact, index),
+ t`Removed ${contact.name}`,
+ () => {
+ if (!application.contactsVersion) throw new Error(t`Couldn't save the contacts. Try again.`);
+ return prepareRpc(client.applications.deleteContact, {
+ id: application.id,
+ index,
+ expectedVersion: application.contactsVersion,
+ });
+ },
+ applicationDetailQueryKey(application.id),
);
};
return (
<Sheet open={open} onClose={onClose} detents={[0.9]} title={t`Contacts`}>
- {application.contacts.length === 0 ? (
+ {contacts.length === 0 ? (
<Text color="ink3" style={{ paddingHorizontal: space.s4 }}>
{t`No contacts yet.`}
</Text>
) : null}
- {application.contacts.map((contact, index) => (
- <ListRow
- key={`${contact.name}-${index}`}
- title={contact.type ? `${contact.name} · ${contact.type}` : contact.name}
- subtitle={[contact.role, contact.email, contact.phone].filter(Boolean).join(" · ") || undefined}
- {...(contact.email ? { onPress: () => void Linking.openURL(`mailto:${contact.email}`) } : {})}
- trailing={
- <View style={{ flexDirection: "row" }}>
- <IconButton
- icon="pencil-simple"
- label={t`Edit ${contact.name}`}
- disabled={update.isPending}
- onPress={() => edit(index)}
- />
- <IconButton
- icon="x"
- label={t`Remove ${contact.name}`}
- disabled={update.isPending}
- onPress={() => remove(index)}
- />
- </View>
- }
- />
- ))}
+ {application.contacts.map(
+ (contact, index) =>
+ !undo.hidden.includes(contactId(contact, index)) && (
+ <ListRow
+ key={`${contact.name}-${index}`}
+ title={contact.type ? `${contact.name} · ${contact.type}` : contact.name}
+ subtitle={[contact.role, contact.email, contact.phone].filter(Boolean).join(" · ") || undefined}
+ {...(contact.email ? { onPress: () => void Linking.openURL(`mailto:${contact.email}`) } : {})}
+ trailing={
+ <View style={{ flexDirection: "row" }}>
+ <IconButton
+ icon="pencil-simple"
+ label={t`Edit ${contact.name}`}
+ disabled={update.isPending || undo.hidden.length > 0}
+ onPress={() => edit(index)}
+ />
+ <IconButton
+ icon="x"
+ label={t`Remove ${contact.name}`}
+ disabled={update.isPending || undo.hidden.length > 0}
+ onPress={() => remove(index)}
+ />
+ </View>
+ }
+ />
+ ),
+ )}
<View style={{ gap: space.s3, paddingHorizontal: space.s4, paddingTop: space.s3 }}>
<Text variant="label">{editing === null ? t`Add contact` : t`Edit contact`}</Text>
<TextField label={t`Name`} value={draft.name} onChangeText={set("name")} />
@@ -626,7 +622,7 @@ export function ContactsSheet({ application, open, onClose }: ApplicationContent
size="lg"
label={editing === null ? t`Add contact` : t`Save contact`}
loading={update.isPending}
- disabled={!draft.name.trim()}
+ disabled={!draft.name.trim() || undo.hidden.length > 0}
onPress={add}
/>
{editing !== null ? (
diff --git a/apps/mobile/src/features/career/hooks.ts b/apps/mobile/src/features/career/hooks.ts
index abe030377..4ed834089 100644
--- a/apps/mobile/src/features/career/hooks.ts
+++ b/apps/mobile/src/features/career/hooks.ts
@@ -251,11 +251,7 @@ export function useUndoRows() {
onReady: () => setHidden((rows) => [...rows, id]),
restore: reconcile,
failed,
- commit: (result) =>
- result.finally(() => {
- if (current()) void action.refresh();
- pending.current.delete(id);
- }),
+ commit: (result) => result.then(reconcile),
});
pending.current.set(id, operation);
};
diff --git a/apps/web/src/features/applications/components/application-detail-sheet.tsx b/apps/web/src/features/applications/components/application-detail-sheet.tsx
index 337761495..9a69b6cd7 100644
--- a/apps/web/src/features/applications/components/application-detail-sheet.tsx
+++ b/apps/web/src/features/applications/components/application-detail-sheet.tsx
@@ -422,7 +422,7 @@ function Facts({ application, locale }: { application: Application; locale: stri
</dt>
<dd className="min-w-0">
<Contacts
- contacts={application.contacts}
+ application={application}
disabled={update.isPending}
onChange={(contacts) => update.mutate({ id: application.id, contacts })}
/>
diff --git a/apps/web/src/features/applications/components/detail/contacts.tsx b/apps/web/src/features/applications/components/detail/contacts.tsx
index 4d5b3efcc..dd43c96ed 100644
--- a/apps/web/src/features/applications/components/detail/contacts.tsx
+++ b/apps/web/src/features/applications/components/detail/contacts.tsx
@@ -1,35 +1,70 @@
+import type { Application } from "../../types";
import type { Contact } from "@reactive-resume/schema/applications/data";
-import type { RefObject } from "react";
import { i18n } from "@lingui/core";
import { t } from "@lingui/core/macro";
import { Trans } from "@lingui/react/macro";
-import { useEffect, useId, useRef, useState } from "react";
+import { useQueryClient } from "@tanstack/react-query";
+import { useId, useRef, useState } from "react";
import { contactSchema } from "@reactive-resume/schema/applications/data";
import { Button } from "@reactive-resume/ui/components/button";
import { Icon } from "@reactive-resume/ui/components/icon";
import { Input } from "@reactive-resume/ui/components/input";
import { Popover, PopoverContent, PopoverTrigger } from "@reactive-resume/ui/components/popover";
-import { toast } from "@reactive-resume/ui/components/toast";
-import { withUndo } from "@/features/career/shared";
+import { applicationDetailQueryKey } from "../../queries";
+import { withQueryUndo } from "@/features/career/shared";
+import { client, prepareRpc } from "@/libs/orpc/client";
const EMPTY_CONTACT = { name: "", role: "", type: "", email: "", phone: "" };
-type ContactsProps = { contacts: Contact[]; disabled: boolean; onChange: (contacts: Contact[]) => void };
+type ContactsProps = {
+ application: Pick<Application, "id" | "contacts" | "contactsVersion">;
+ disabled: boolean;
+ onChange: (contacts: Contact[]) => void;
+};
+type Removing = { index: number; contact: Contact };
const contactKey = (contact: Contact) =>
JSON.stringify([contact.name, contact.role ?? "", contact.type ?? "", contact.email ?? "", contact.phone ?? ""]);
const sameContact = (a: Contact | undefined, b: Contact | undefined) => !!a && !!b && contactKey(a) === contactKey(b);
/** The Contact cell: the primary contact (the first), and the full list, with add and remove, in a popover. */
-export function Contacts({ contacts, disabled, onChange }: ContactsProps) {
- // A removed contact hides at once, here and in the list, and is saved away when its Undo toast closes.
- const [removing, setRemoving] = useState<Contact | null>(null);
- const shown = removing ? contacts.filter((contact) => contact !== removing) : contacts;
- // The removal saves against the latest list when its Undo closes, even after the popover (and the list) has closed.
- const latest = useRef(contacts);
- useEffect(() => {
- latest.current = contacts;
- }, [contacts]);
+export function Contacts({ application, disabled, onChange }: ContactsProps) {
+ const { contacts } = application;
+ const queryClient = useQueryClient();
+ const [removing, setRemoving] = useState<Removing | null>(null);
+ const [preparing, setPreparing] = useState(false);
+ const pending = useRef(false);
+ const visible = (contact: Contact, index: number) =>
+ !removing || index !== removing.index || !sameContact(contact, removing.contact);
+ const shown = contacts.filter(visible);
+ const remove = (contact: Contact) => {
+ if (pending.current) return;
+ pending.current = true;
+ setPreparing(true);
+ withQueryUndo({
+ queryClient,
+ queryKey: applicationDetailQueryKey(application.id),
+ description: t`Removed ${contact.name}`,
+ errorMessage: t`Couldn't save the change. Try again.`,
+ prepare: () => {
+ if (!application.contactsVersion) throw new Error(t`Couldn't save the change. Try again.`);
+ return prepareRpc(client.applications.deleteContact, {
+ id: application.id,
+ index: contacts.indexOf(contact),
+ expectedVersion: application.contactsVersion,
+ });
+ },
+ hide: () => {
+ setRemoving({ index: contacts.indexOf(contact), contact });
+ setPreparing(false);
+ },
+ restore: () => {
+ setRemoving(null);
+ setPreparing(false);
+ pending.current = false;
+ },
+ });
+ };
const [primary, ...others] = shown;
return (
@@ -54,33 +89,36 @@ export function Contacts({ contacts, disabled, onChange }: ContactsProps) {
</h3>
<ContactList
contacts={contacts}
- disabled={disabled}
+ disabled={disabled || preparing}
onChange={onChange}
removing={removing}
- onRemoving={setRemoving}
- latest={latest}
+ onRemove={remove}
/>
</PopoverContent>
</Popover>
);
}
-type ContactListProps = ContactsProps & {
- removing: Contact | null;
- onRemoving: (contact: Contact | null) => void;
- latest: RefObject<Contact[]>;
+type ContactListProps = {
+ contacts: Contact[];
+ disabled: boolean;
+ onChange: (contacts: Contact[]) => void;
+ removing: Removing | null;
+ onRemove: (contact: Contact) => void;
};
-function ContactList({ contacts, disabled, onChange, removing, onRemoving, latest }: ContactListProps) {
+function ContactList({ contacts, disabled, onChange, removing, onRemove }: ContactListProps) {
const id = useId();
const [adding, setAdding] = useState(false);
// The contact being corrected: its position, and what it said when the form opened.
const [editing, setEditing] = useState<{ index: number; original: Contact } | null>(null);
const [draft, setDraft] = useState(EMPTY_CONTACT);
const [error, setError] = useState("");
- const shown = contacts.filter((contact) => contact !== removing);
+ const shown = contacts.filter(
+ (contact, index) => !removing || index !== removing.index || !sameContact(contact, removing.contact),
+ );
const formOpen = adding || editing !== null;
- // Until a removal's Undo closes, the list it will save is fixed; changes made meanwhile would be overwritten.
+ // Keep one reviewed contact removal active until canonical readback settles it.
const locked = disabled || removing !== null;
const close = () => {
@@ -122,29 +160,6 @@ function ContactList({ contacts, disabled, onChange, removing, onRemoving, lates
setEditing({ index, original: contact });
};
- const remove = (contact: Contact) => {
- // The list as it was: if it changes before the Undo closes (another tab or device), the removal stops.
- const snapshot = contacts.map(contactKey).join("\n");
- onRemoving(contact);
- withUndo({
- description: t`Removed ${contact.name}`,
- onUndo: () => onRemoving(null),
- commit: () => {
- const current = latest.current;
- onRemoving(null);
- if (current.map(contactKey).join("\n") !== snapshot) {
- toast.add({
- type: "error",
- description: t`The contacts changed somewhere else, so ${contact.name} wasn't removed. Remove it again.`,
- });
- return;
- }
- const at = current.indexOf(contact);
- onChange(current.filter((_, index) => index !== (at === -1 ? contacts.indexOf(contact) : at)));
- },
- });
- };
-
const field = (key: keyof typeof EMPTY_CONTACT, label: string, type = "text") => (
<Input
aria-label={label}
@@ -206,7 +221,7 @@ function ContactList({ contacts, disabled, onChange, removing, onRemoving, lates
className="touch-target relative"
disabled={locked || formOpen}
aria-label={t`Remove ${contact.name}`}
- onClick={() => remove(contact)}
+ onClick={() => onRemove(contact)}
>
<Icon name="x" size={16} />
</Button>
diff --git a/apps/web/src/features/applications/components/interview-dialog.test.tsx b/apps/web/src/features/applications/components/interview-dialog.test.tsx
index 938d89f20..ade8ba95d 100644
--- a/apps/web/src/features/applications/components/interview-dialog.test.tsx
+++ b/apps/web/src/features/applications/components/interview-dialog.test.tsx
@@ -8,11 +8,17 @@ import { I18nProvider } from "@lingui/react";
import { QueryClient, QueryClientProvider, useQuery } from "@tanstack/react-query";
import { useState } from "react";
import { Toaster } from "@reactive-resume/ui/components/toast";
+import { prepareRequest } from "@reactive-resume/utils/deferred-request";
+import { pendingCommits } from "@/features/career/pending-commits";
+import { invalidateAccountScope, setAccountScope } from "@/libs/auth/account-scope";
-const api = vi.hoisted(() => ({ add: vi.fn(), update: vi.fn(), remove: vi.fn(), read: vi.fn() }));
+const api = vi.hoisted(() => ({ add: vi.fn(), update: vi.fn(), remove: vi.fn(), read: vi.fn(), prepare: vi.fn() }));
vi.mock("@/libs/orpc/client", () => ({
+ client: { applications: { deleteTimelineEntry: api.remove } },
+ prepareRpc: api.prepare,
orpc: {
applications: {
+ key: () => ["applications"],
addInterview: { mutationOptions: (options: object) => ({ mutationFn: api.add, ...options }) },
updateInterview: { mutationOptions: (options: object) => ({ mutationFn: api.update, ...options }) },
deleteTimelineEntry: { mutationOptions: (options: object) => ({ mutationFn: api.remove, ...options }) },
@@ -77,8 +83,10 @@ const application: Application = {
const clients: QueryClient[] = [];
function Harness({ editing }: { editing: boolean }) {
const [open, setOpen] = useState(true);
- const { data } = useQuery({ queryKey: ["applications"], queryFn: api.read });
- const loaded = (data as Application[] | undefined)?.[0];
+ const { data: loaded } = useQuery<Application>({
+ queryKey: ["application"],
+ queryFn: async () => (await api.read())[0],
+ });
return (
<>
<output aria-label="Saved round identity">
@@ -108,6 +116,17 @@ function mount(editing: boolean) {
}
beforeEach(() => {
vi.clearAllMocks();
+ setAccountScope("interview-test");
+ api.prepare.mockImplementation((procedure: (input: unknown) => Promise<unknown>, input: unknown) =>
+ prepareRequest(async (defer) => {
+ let saved: unknown;
+ await defer(async () => {
+ saved = await procedure(input);
+ return new Response();
+ });
+ return saved;
+ }),
+ );
api.read.mockResolvedValue([application]);
api.add.mockResolvedValue(application);
api.update.mockResolvedValue(application);
@@ -115,6 +134,9 @@ beforeEach(() => {
i18n.loadAndActivate({ locale: "en-US", messages: {} });
});
afterEach(() => {
+ invalidateAccountScope();
+ for (const flush of pendingCommits) flush();
+ pendingCommits.clear();
cleanup();
clients.splice(0).forEach((client) => client.clear());
});
@@ -159,3 +181,32 @@ it("offers Update your calendar only after a successful reschedule", async () =>
expect(await screen.findByRole("button", { name: "Update your calendar" })).toBeVisible();
expect(api.update).toHaveBeenCalledWith(expect.objectContaining({ entryId: "original-round" }), expect.anything());
});
+
+it("late deletion preparation cannot close a departed interview editor", async () => {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ clients.push(client);
+ client.setQueryData(["applications"], [application]);
+ let release!: (request: Awaited<ReturnType<typeof prepareRequest>>) => void;
+ const held = new Promise<Awaited<ReturnType<typeof prepareRequest>>>((resolve) => {
+ release = resolve;
+ });
+ api.prepare.mockReturnValueOnce(held);
+ const changed = vi.fn();
+ const view = render(
+ <QueryClientProvider client={client}>
+ <I18nProvider i18n={i18n}>
+ <Toaster>
+ <InterviewDialog open onOpenChange={changed} application={application} interview={interview} />
+ </Toaster>
+ </I18nProvider>
+ </QueryClientProvider>,
+ );
+ fireEvent.click(await screen.findByRole("button", { name: /^Delete$/ }));
+ await waitFor(() => expect(api.prepare).toHaveBeenCalled());
+ view.unmount();
+ release(await prepareRequest((defer) => defer(() => Promise.resolve(new Response()))));
+ await held;
+ await waitFor(() => expect(client.getQueryData<Application[]>(["applications"])?.[0]?.activity).toEqual([]));
+ expect(changed).not.toHaveBeenCalled();
+ expect(api.remove).not.toHaveBeenCalled();
+});
diff --git a/apps/web/src/features/applications/components/interview-dialog.tsx b/apps/web/src/features/applications/components/interview-dialog.tsx
index b5869a7ff..9ce390f92 100644
--- a/apps/web/src/features/applications/components/interview-dialog.tsx
+++ b/apps/web/src/features/applications/components/interview-dialog.tsx
@@ -5,7 +5,7 @@ import { t } from "@lingui/core/macro";
import { Trans } from "@lingui/react/macro";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { m } from "motion/react";
-import { useId, useMemo, useState } from "react";
+import { useId, useLayoutEffect, useMemo, useRef, useState } from "react";
import { interviewDetailsSchema, nextInterviewKind } from "@reactive-resume/schema/applications/data";
import { Button } from "@reactive-resume/ui/components/button";
import { Dialog, DialogContent, DialogDescription, DialogTitle } from "@reactive-resume/ui/components/dialog";
@@ -23,11 +23,11 @@ import { interviewCalendarAction, showInterviewCancellation } from "../calendar"
import { dayKey, interviewTypeLabel } from "../interviews";
import { applicationsListQueryKey } from "../queries";
import { Combobox } from "@/components/ui/combobox";
-import { useCareerTime, withUndo } from "@/features/career/shared";
+import { useCareerTime, withQueryUndo } from "@/features/career/shared";
import { useClosingValue } from "@/hooks/use-closing-value";
import { getAccountGeneration } from "@/libs/auth/account-scope";
import { D2, EASE } from "@/libs/motion";
-import { orpc } from "@/libs/orpc/client";
+import { client, orpc, prepareRpc } from "@/libs/orpc/client";
export { interviewTypeLabel } from "../interviews";
@@ -172,6 +172,13 @@ export function InterviewDialog({
: emptyDraft(application?.id ?? "", preferredZone, day, suggestedKind(application)),
);
const [otherZone, setOtherZone] = useState(false);
+ const activeForm = useRef<symbol | null>(null);
+ useLayoutEffect(() => {
+ activeForm.current = Symbol();
+ return () => {
+ activeForm.current = null;
+ };
+ }, [open, draft.applicationId, interview?.id]);
// A fresh draft each time the dialog opens, adjusted during render so the first frame is never stale.
const [wasOpen, setWasOpen] = useState(open);
@@ -205,12 +212,6 @@ export function InterviewDialog({
onError: () => toast.add({ type: "error", description: t`Couldn't update the interview. Try again.` }),
}),
);
- const remove = useMutation(
- orpc.applications.deleteTimelineEntry.mutationOptions({
- onSettled: (_data, _error, variables) => invalidate(variables.id),
- onError: () => toast.add({ type: "error", description: t`Couldn't delete the interview. Try again.` }),
- }),
- );
const zones = useMemo(() => {
const all = Intl.supportedValuesOf("timeZone");
@@ -291,6 +292,7 @@ export function InterviewDialog({
// Commit after Undo closes so a restored round retains its identity, history and briefing schedules.
const deleteInterview = () => {
if (!editing) return;
+ const form = activeForm.current;
const applicationId = draft.applicationId;
const generation = getAccountGeneration();
const savedApplication = application ?? applications.find((item) => item.id === applicationId);
@@ -298,25 +300,34 @@ export function InterviewDialog({
item.id === applicationId
? { ...item, activity: item.activity.filter((entry) => entry.id !== editing.id) }
: item;
- queryClient.setQueryData(applicationsListQueryKey(), (list) => list?.map(drop));
- queryClient.setQueryData(
- orpc.applications.getById.queryKey({ input: { id: applicationId } }),
- (item) => item && drop(item),
- );
- onOpenChange(false);
- withUndo({
+ withQueryUndo({
+ queryClient,
+ queryKey: orpc.applications.getById.queryKey({ input: { id: applicationId } }),
description: t`Interview deleted`,
- onUndo: () => invalidate(applicationId),
- commit: () => {
- if (generation !== getAccountGeneration()) return;
- void remove
- .mutateAsync({ id: applicationId, entryId: editing.id })
- .then(() => {
- if (savedApplication) showInterviewCancellation(savedApplication, editing, generation);
- })
- .catch(() => undefined)
- .finally(() => invalidate(applicationId));
+ errorMessage: t`Couldn't delete the interview. Try again.`,
+ prepare: async () => {
+ const request = await prepareRpc(client.applications.deleteTimelineEntry, {
+ id: applicationId,
+ entryId: editing.id,
+ });
+ return {
+ cancel: request.cancel,
+ send: () =>
+ request.send().then((saved) => {
+ if (savedApplication) showInterviewCancellation(savedApplication, editing, generation);
+ return saved;
+ }),
+ };
+ },
+ hide: () => {
+ queryClient.setQueryData(applicationsListQueryKey(), (list) => list?.map(drop));
+ queryClient.setQueryData(
+ orpc.applications.getById.queryKey({ input: { id: applicationId } }),
+ (item) => item && drop(item),
+ );
+ if (form && activeForm.current === form) onOpenChange(false);
},
+ restore: () => {},
});
};
diff --git a/apps/web/src/features/applications/queries.test.ts b/apps/web/src/features/applications/queries.test.ts
index 339b937fd..768d21295 100644
--- a/apps/web/src/features/applications/queries.test.ts
+++ b/apps/web/src/features/applications/queries.test.ts
@@ -1,6 +1,16 @@
+// @vitest-environment happy-dom
import type { Application, ApplicationSummary } from "./types";
import { describe, expect, it, vi } from "vite-plus/test";
+import { i18n } from "@lingui/core";
import { QueryClient, QueryObserver } from "@tanstack/react-query";
+import { prepareRequest } from "@reactive-resume/utils/deferred-request";
+import { withQueryUndo } from "@/features/career/shared";
+import { setAccountScope } from "@/libs/auth/account-scope";
+
+const undoNotices = vi.hoisted(() => [] as { type?: string; actionProps?: { onClick: () => void } }[]);
+vi.mock("@reactive-resume/ui/components/toast", () => ({
+ toast: { add: (notice: (typeof undoNotices)[number]) => undoNotices.push(notice), close: vi.fn() },
+}));
const mocks = vi.hoisted(() => ({
query: (key: readonly unknown[]) => ({
@@ -150,3 +160,77 @@ describe("application detail cache hydration", () => {
second.destroy();
});
});
+
+it("Undo canonical read survives fresher application-list hydration without a spurious Retry", async () => {
+ i18n.loadAndActivate({ locale: "en", messages: {} });
+ setAccountScope("alice");
+ undoNotices.length = 0;
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ const key = applicationDetailQueryKey("a");
+ const old = detail("2026-10-01T00:00:00Z", "old");
+ const fresh = detail("2026-10-02T00:00:00Z", "canonical");
+ let releaseDetail!: (value: Application) => void;
+ const detailGate = new Promise<Application>((resolve) => {
+ releaseDetail = resolve;
+ });
+ let releaseList!: () => void;
+ const listGate = new Promise<void>((resolve) => {
+ releaseList = resolve;
+ });
+ let detailStarted = false;
+ client.setQueryDefaults(key, {
+ queryFn: () => {
+ detailStarted = true;
+ return detailGate;
+ },
+ });
+ client.setQueryData(key, old);
+ let refreshing = false;
+ const listOptions = {
+ queryKey: ["application-list"],
+ staleTime: Infinity,
+ queryFn: async () => {
+ if (!refreshing) return summary(old);
+ await listGate;
+ // The list's real consumer hydrates refreshed embedded full detail.
+ hydrateApplicationDetail(client, summary(fresh));
+ return summary(fresh);
+ },
+ };
+ await client.fetchQuery(listOptions);
+ const stop = new QueryObserver(client, listOptions).subscribe(() => {});
+ refreshing = true;
+ let hidden = false;
+ try {
+ const prepared = prepareRequest((defer) => defer(() => Promise.resolve(new Response())));
+ withQueryUndo({
+ queryClient: client,
+ queryKey: key,
+ description: "Removed fictional contact",
+ errorMessage: "Try again",
+ prepare: () => prepared,
+ hide: () => {
+ hidden = true;
+ },
+ restore: () => {
+ hidden = false;
+ },
+ });
+ await prepared;
+ const undo = undoNotices[0]?.actionProps;
+ if (!undo) throw new Error("Missing Undo");
+ undo.onClick();
+ await vi.waitFor(() => expect(detailStarted).toBe(true));
+ releaseList();
+ await Promise.resolve();
+ releaseDetail(fresh);
+ await vi.waitFor(() => expect(hidden).toBe(false));
+ expect(client.getQueryData<Application>(key)?.notes).toBe("canonical");
+ expect(undoNotices.filter((notice) => notice.type === "error")).toEqual([]);
+ } finally {
+ releaseList();
+ releaseDetail(fresh);
+ stop();
+ client.clear();
+ }
+});
diff --git a/apps/web/src/features/career/shared.tsx b/apps/web/src/features/career/shared.tsx
index de4bf129d..d270c63f7 100644
--- a/apps/web/src/features/career/shared.tsx
+++ b/apps/web/src/features/career/shared.tsx
@@ -199,11 +199,15 @@ export function withQueryUndo<T>({
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 });
- if (current()) restore();
+ try {
+ await queryClient.invalidateQueries({ queryKey, refetchType: "all" }, { throwOnError: true });
+ if (current()) restore();
+ } finally {
+ // A refreshed list can hydrate detail and cancel its read, so settle the canonical target first.
+ if (current()) void invalidateMutationQueries(queryClient, queryKey);
+ }
};
const report = (error: unknown, fallback = t`Couldn't load. Try again.`) => {
if (!current()) return;
diff --git a/docs/guides/career-workspace-reference.mdx b/docs/guides/career-workspace-reference.mdx
index 47ed1618f..084d7ae84 100644
--- a/docs/guides/career-workspace-reference.mdx
+++ b/docs/guides/career-workspace-reference.mdx
@@ -234,3 +234,5 @@ For a saved job, **Use an existing letter** links a letter from Documents. Docum
a new letter, choose **Resume for a new letter**, or **No resume** for a standalone letter.
A 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).
diff --git a/docs/guides/managing-an-application.mdx b/docs/guides/managing-an-application.mdx
index 300641ed0..f7ad1c4df 100644
--- a/docs/guides/managing-an-application.mdx
+++ b/docs/guides/managing-an-application.mdx
@@ -161,6 +161,17 @@ Below **What you sent** are four facts:
Select the **Contact** value to see every contact. Select **Add contact**, then enter a **Name** and, if you like, a role, a label (such as Recruiter, Hiring manager, Referral or Interviewer), an email and a phone number. Emails and phone numbers become links you can select. Select **×** next to a contact to remove it.
+Removal offers **Undo** once the pending request is ready. Undo cancels that removal and reads the current application; it never writes a captured contact back. Reloading, closing the tab or putting the native app in the background sends an acknowledged pending removal. If another session changes the contacts before removal finishes, refresh and review them before trying again. Other edits, such as notes, are kept. Self-hosted servers need an update to support reviewed contact removal.
+
+If the current application cannot be read, the removed contact stays hidden. **Retry** reads the application again without repeating the deletion or restoring erased text.
+
+<Frame caption="Retry reads the current contacts without recreating erased text">
+ <img
+ src="/images/guides/managing-an-application/contacts-readback-retry.png"
+ alt="Fictional Cedar application with no contacts visible and a Couldn’t load. Try again. notice offering Retry"
+ />
+</Frame>
+
<Frame caption="Contacts for one application">
<img
src="/images/guides/managing-an-application/detail-sheet-contacts.webp"
diff --git a/docs/guides/scheduling-interviews.mdx b/docs/guides/scheduling-interviews.mdx
index bc415c889..d8385fe4d 100644
--- a/docs/guides/scheduling-interviews.mdx
+++ b/docs/guides/scheduling-interviews.mdx
@@ -82,6 +82,15 @@ A date and time skipped by a daylight-saving change is rejected. Pick a valid lo
To 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.
+
+<Frame caption="Phone browser: the prepared interview deletion offers Undo">
+ <img
+ src="/images/guides/scheduling-interviews/interview-undo-ready.png"
+ alt="Phone browser Calendar with no upcoming interviews and an Interview deleted notice offering Undo above the navigation tabs"
+ />
+</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/managing-an-application/contacts-readback-retry.png b/docs/images/guides/managing-an-application/contacts-readback-retry.png
new file mode 100644
index 000000000..0a4eac441
Binary files /dev/null and b/docs/images/guides/managing-an-application/contacts-readback-retry.png differ
diff --git a/docs/images/guides/scheduling-interviews/interview-undo-ready.png b/docs/images/guides/scheduling-interviews/interview-undo-ready.png
new file mode 100644
index 000000000..a7218b2da
Binary files /dev/null and b/docs/images/guides/scheduling-interviews/interview-undo-ready.png differ
diff --git a/docs/spec.json b/docs/spec.json
index 3045b00ca..619689531 100644
--- a/docs/spec.json
+++ b/docs/spec.json
@@ -19994,6 +19994,12 @@
"minLength": 64,
"maxLength": 64,
"description": "Opaque snapshot for logReply. Read the full application, review it, then send this value as expectedVersion. On CONFLICT, reload and review again."
+ },
+ "contactsVersion": {
+ "type": "string",
+ "minLength": 64,
+ "maxLength": 64,
+ "description": "Opaque contacts snapshot for deleteContact. Unrelated application edits do not change it."
}
},
"required": [
@@ -22464,6 +22470,12 @@
"minLength": 64,
"maxLength": 64,
"description": "Opaque snapshot for logReply. Read the full application, review it, then send this value as expectedVersion. On CONFLICT, reload and review again."
+ },
+ "contactsVersion": {
+ "type": "string",
+ "minLength": 64,
+ "maxLength": 64,
+ "description": "Opaque contacts snapshot for deleteContact. Unrelated application edits do not change it."
}
},
"required": [
@@ -23281,6 +23293,12 @@
"minLength": 64,
"maxLength": 64,
"description": "Opaque snapshot for logReply. Read the full application, review it, then send this value as expectedVersion. On CONFLICT, reload and review again."
+ },
+ "contactsVersion": {
+ "type": "string",
+ "minLength": 64,
+ "maxLength": 64,
+ "description": "Opaque contacts snapshot for deleteContact. Unrelated application edits do not change it."
}
},
"required": [
@@ -24720,6 +24738,12 @@
"minLength": 64,
"maxLength": 64,
"description": "Opaque snapshot for logReply. Read the full application, review it, then send this value as expectedVersion. On CONFLICT, reload and review again."
+ },
+ "contactsVersion": {
+ "type": "string",
+ "minLength": 64,
+ "maxLength": 64,
+ "description": "Opaque contacts snapshot for deleteContact. Unrelated application edits do not change it."
}
},
"required": [
@@ -26231,6 +26255,12 @@
"minLength": 64,
"maxLength": 64,
"description": "Opaque snapshot for logReply. Read the full application, review it, then send this value as expectedVersion. On CONFLICT, reload and review again."
+ },
+ "contactsVersion": {
+ "type": "string",
+ "minLength": 64,
+ "maxLength": 64,
+ "description": "Opaque contacts snapshot for deleteContact. Unrelated application edits do not change it."
}
},
"required": [
@@ -26757,6 +26787,111 @@
]
}
},
+ "/applications/{id}/contacts/{index}": {
+ "delete": {
+ "operationId": "deleteApplicationContact",
+ "summary": "Remove an application contact",
+ "description": "Read the full application and retain its contactsVersion as expectedVersion. Removes only the contact at the reviewed index. On CONFLICT (409), reload and review again; never retry automatically with a new version. Requires authentication and delete permission.",
+ "tags": [
+ "Applications"
+ ],
+ "parameters": [
+ {
+ "name": "id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ },
+ {
+ "name": "index",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "integer",
+ "minimum": 0,
+ "maximum": 9007199254740991
+ }
+ }
+ ],
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "object",
+ "properties": {
+ "expectedVersion": {
+ "type": "string",
+ "minLength": 64,
+ "maxLength": 64,
+ "description": "The contactsVersion of the contacts array reviewed before removal."
+ }
+ },
+ "required": [
+ "expectedVersion"
+ ]
+ }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "OK"
+ },
+ "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/applications/<id>/contacts/<index>\" --header \"x-api-key: <api-key>\" --header \"Content-Type: application/json\" --data '{\n \"expectedVersion\": \"<string>\"\n}'"
+ }
+ ]
+ }
+ },
"/applications/{id}/documents/{kind}": {
"post": {
"operationId": "attachApplicationDocument",
@@ -27465,6 +27600,12 @@
"minLength": 64,
"maxLength": 64,
"description": "Opaque snapshot for logReply. Read the full application, review it, then send this value as expectedVersion. On CONFLICT, reload and review again."
+ },
+ "contactsVersion": {
+ "type": "string",
+ "minLength": 64,
+ "maxLength": 64,
+ "description": "Opaque contacts snapshot for deleteContact. Unrelated application edits do not change it."
}
},
"required": [
@@ -28233,6 +28374,12 @@
"minLength": 64,
"maxLength": 64,
"description": "Opaque snapshot for logReply. Read the full application, review it, then send this value as expectedVersion. On CONFLICT, reload and review again."
+ },
+ "contactsVersion": {
+ "type": "string",
+ "minLength": 64,
+ "maxLength": 64,
+ "description": "Opaque contacts snapshot for deleteContact. Unrelated application edits do not change it."
}
},
"required": [
@@ -29025,6 +29172,12 @@
"minLength": 64,
"maxLength": 64,
"description": "Opaque snapshot for logReply. Read the full application, review it, then send this value as expectedVersion. On CONFLICT, reload and review again."
+ },
+ "contactsVersion": {
+ "type": "string",
+ "minLength": 64,
+ "maxLength": 64,
+ "description": "Opaque contacts snapshot for deleteContact. Unrelated application edits do not change it."
}
},
"required": [
@@ -29794,6 +29947,12 @@
"minLength": 64,
"maxLength": 64,
"description": "Opaque snapshot for logReply. Read the full application, review it, then send this value as expectedVersion. On CONFLICT, reload and review again."
+ },
+ "contactsVersion": {
+ "type": "string",
+ "minLength": 64,
+ "maxLength": 64,
+ "description": "Opaque contacts snapshot for deleteContact. Unrelated application edits do not change it."
}
},
"required": [
@@ -30584,6 +30743,12 @@
"minLength": 64,
"maxLength": 64,
"description": "Opaque snapshot for logReply. Read the full application, review it, then send this value as expectedVersion. On CONFLICT, reload and review again."
+ },
+ "contactsVersion": {
+ "type": "string",
+ "minLength": 64,
+ "maxLength": 64,
+ "description": "Opaque contacts snapshot for deleteContact. Unrelated application edits do not change it."
}
},
"required": [
@@ -31445,6 +31610,12 @@
"minLength": 64,
"maxLength": 64,
"description": "Opaque snapshot for logReply. Read the full application, review it, then send this value as expectedVersion. On CONFLICT, reload and review again."
+ },
+ "contactsVersion": {
+ "type": "string",
+ "minLength": 64,
+ "maxLength": 64,
+ "description": "Opaque contacts snapshot for deleteContact. Unrelated application edits do not change it."
}
},
"required": [
@@ -32305,6 +32476,12 @@
"minLength": 64,
"maxLength": 64,
"description": "Opaque snapshot for logReply. Read the full application, review it, then send this value as expectedVersion. On CONFLICT, reload and review again."
+ },
+ "contactsVersion": {
+ "type": "string",
+ "minLength": 64,
+ "maxLength": 64,
+ "description": "Opaque contacts snapshot for deleteContact. Unrelated application edits do not change it."
}
},
"required": [
@@ -33162,6 +33339,12 @@
"minLength": 64,
"maxLength": 64,
"description": "Opaque snapshot for logReply. Read the full application, review it, then send this value as expectedVersion. On CONFLICT, reload and review again."
+ },
+ "contactsVersion": {
+ "type": "string",
+ "minLength": 64,
+ "maxLength": 64,
+ "description": "Opaque contacts snapshot for deleteContact. Unrelated application edits do not change it."
}
},
"required": [
@@ -33960,6 +34143,12 @@
"minLength": 64,
"maxLength": 64,
"description": "Opaque snapshot for logReply. Read the full application, review it, then send this value as expectedVersion. On CONFLICT, reload and review again."
+ },
+ "contactsVersion": {
+ "type": "string",
+ "minLength": 64,
+ "maxLength": 64,
+ "description": "Opaque contacts snapshot for deleteContact. Unrelated application edits do not change it."
}
},
"required": [
@@ -34735,6 +34924,12 @@
"minLength": 64,
"maxLength": 64,
"description": "Opaque snapshot for logReply. Read the full application, review it, then send this value as expectedVersion. On CONFLICT, reload and review again."
+ },
+ "contactsVersion": {
+ "type": "string",
+ "minLength": 64,
+ "maxLength": 64,
+ "description": "Opaque contacts snapshot for deleteContact. Unrelated application edits do not change it."
}
},
"required": [
@@ -35530,6 +35725,12 @@
"minLength": 64,
"maxLength": 64,
"description": "Opaque snapshot for logReply. Read the full application, review it, then send this value as expectedVersion. On CONFLICT, reload and review again."
+ },
+ "contactsVersion": {
+ "type": "string",
+ "minLength": 64,
+ "maxLength": 64,
+ "description": "Opaque contacts snapshot for deleteContact. Unrelated application edits do not change it."
}
},
"required": [
@@ -45435,6 +45636,12 @@
"maxLength": 64,
"description": "Opaque snapshot for logReply. Read the full application, review it, then send this value as expectedVersion. On CONFLICT, reload and review again."
},
+ "contactsVersion": {
+ "type": "string",
+ "minLength": 64,
+ "maxLength": 64,
+ "description": "Opaque contacts snapshot for deleteContact. Unrelated application edits do not change it."
+ },
"submittedAt": {
"anyOf": [
{
diff --git a/packages/api/src/dto/application.ts b/packages/api/src/dto/application.ts
index d994c52df..4c3a7b97a 100644
--- a/packages/api/src/dto/application.ts
+++ b/packages/api/src/dto/application.ts
@@ -103,6 +103,11 @@ const applicationSchema = createSelectSchema(schema.application, {
.describe(
"Opaque snapshot for logReply. Read the full application, review it, then send this value as expectedVersion. On CONFLICT, reload and review again.",
),
+ contactsVersion: z
+ .string()
+ .length(64)
+ .optional()
+ .describe("Opaque contacts snapshot for deleteContact. Unrelated application edits do not change it."),
});
/** An application's stage as a write left it, with the ID of its latest stage change: what a later move expects. */
@@ -262,6 +267,18 @@ export const applicationDto = {
output: applicationSchema.omit({ userId: true }),
},
+ deleteContact: {
+ input: z.object({
+ id: z.string(),
+ index: z.number().int().min(0),
+ expectedVersion: z
+ .string()
+ .length(64)
+ .describe("The contactsVersion of the contacts array reviewed before removal."),
+ }),
+ output: z.void(),
+ },
+
attachDocument: {
input: z.object({
id: z.string(),
diff --git a/packages/api/src/features/applications/crud.ts b/packages/api/src/features/applications/crud.ts
index 399e21453..335cfcf0d 100644
--- a/packages/api/src/features/applications/crud.ts
+++ b/packages/api/src/features/applications/crud.ts
@@ -258,6 +258,21 @@ export const crudRouter = {
}),
),
+ deleteContact: protectedProcedure
+ .route({
+ method: "DELETE",
+ path: "/applications/{id}/contacts/{index}",
+ tags: ["Applications"],
+ operationId: "deleteApplicationContact",
+ summary: "Remove an application contact",
+ description:
+ "Read the full application and retain its contactsVersion as expectedVersion. Removes only the contact at the reviewed index. On CONFLICT (409), reload and review again; never retry automatically with a new version. Requires authentication and delete permission.",
+ })
+ .input(applicationDto.deleteContact.input)
+ .use(resumeMutationRateLimit)
+ .output(applicationDto.deleteContact.output)
+ .handler(({ input, context }) => applicationService.deleteContact({ ...input, userId: context.user.id })),
+
attachDocument: protectedProcedure
.route({
method: "POST",
diff --git a/packages/api/src/features/applications/router.ts b/packages/api/src/features/applications/router.ts
index 6cf4bad39..b0d7aad38 100644
--- a/packages/api/src/features/applications/router.ts
+++ b/packages/api/src/features/applications/router.ts
@@ -19,6 +19,7 @@ export const applicationsRouter = {
create: crudRouter.create,
import: crudRouter.import,
update: crudRouter.update,
+ deleteContact: crudRouter.deleteContact,
attachDocument: crudRouter.attachDocument,
removeDocument: crudRouter.removeDocument,
addNote: crudRouter.addNote,
diff --git a/packages/api/src/features/applications/service.test.ts b/packages/api/src/features/applications/service.test.ts
index cf23af52f..023dc7f71 100644
--- a/packages/api/src/features/applications/service.test.ts
+++ b/packages/api/src/features/applications/service.test.ts
@@ -81,6 +81,7 @@ const existing = {
laneId: "application-lane:user-1:saved",
closedReason: null,
tags: [],
+ contacts: [],
activity: [{ id: "e0", type: "stage" as const, stage: "saved" as const, at: new Date("2026-07-01T12:00:00.000Z") }],
appliedAt: new Date("2026-07-01T12:00:00.000Z"),
createdAt: new Date("2026-07-01T12:00:00.000Z"),
diff --git a/packages/api/src/features/applications/service.ts b/packages/api/src/features/applications/service.ts
index d22a32af6..5fda0582e 100644
--- a/packages/api/src/features/applications/service.ts
+++ b/packages/api/src/features/applications/service.ts
@@ -606,7 +606,13 @@ const stripUserId = <T extends { userId: string; activity?: ApplicationTimelineE
// Hash the stored snapshot before display sorting; a timestamp alone can collide within one millisecond.
const applicationReplyVersion = (row: ApplicationRow) => createHash("sha256").update(JSON.stringify(row)).digest("hex");
-const applicationView = (row: ApplicationRow) => ({ ...stripUserId(row), replyVersion: applicationReplyVersion(row) });
+const applicationContactsVersion = (row: Pick<ApplicationRow, "contacts">) =>
+ createHash("sha256").update(JSON.stringify(row.contacts)).digest("hex");
+const applicationView = (row: ApplicationRow) => ({
+ ...stripUserId(row),
+ replyVersion: applicationReplyVersion(row),
+ contactsVersion: applicationContactsVersion(row),
+});
const applicationSummarySelect = {
id: schema.application.id,
@@ -1157,6 +1163,24 @@ export const applicationService = {
return applicationView(updated);
},
+ deleteContact: (input: { id: string; userId: string; index: number; expectedVersion: string }) =>
+ db.transaction(async (tx) => {
+ const [existing] = await tx
+ .select()
+ .from(schema.application)
+ .where(and(eq(schema.application.id, input.id), activeApplications(input.userId)))
+ .for("update");
+ if (!existing) throw new ORPCError("NOT_FOUND");
+ if (applicationContactsVersion(existing) !== input.expectedVersion || !existing.contacts[input.index])
+ throw new ORPCError("CONFLICT", { message: "The contacts changed. Reload them before removing the contact." });
+ const [updated] = await tx
+ .update(schema.application)
+ .set({ contacts: existing.contacts.filter((_, index) => index !== input.index) })
+ .where(and(eq(schema.application.id, input.id), activeApplications(input.userId)))
+ .returning({ id: schema.application.id });
+ if (!updated) throw new ORPCError("NOT_FOUND");
+ }),
+
/** Records contact within the locked visit; an explicit reply also clears the owned follow-up and its schedule. */
logFollowUp: (input: { id: string; userId: string; reply?: { expectedVersion: string } | undefined }) =>
db.transaction(async (tx) => {
diff --git a/packages/api/src/features/applications/trash.integration.test.ts b/packages/api/src/features/applications/trash.integration.test.ts
index 0e18cdd6d..a4cec0373 100644
--- a/packages/api/src/features/applications/trash.integration.test.ts
+++ b/packages/api/src/features/applications/trash.integration.test.ts
@@ -57,7 +57,12 @@ describe.skipIf(!databaseUrl)("application Trash: real retained rows, storage an
fixture.directory = await mkdtemp(join(tmpdir(), "rr-application-trash-"));
admin = new Pool({ connectionString: databaseUrl });
await admin.query(`CREATE SCHEMA ${namespace}`);
- pool = new Pool({ connectionString: databaseUrl, max: 4, options: `-c search_path=${namespace}` });
+ pool = new Pool({
+ connectionString: databaseUrl,
+ max: 4,
+ application_name: namespace,
+ options: `-c search_path=${namespace}`,
+ });
fixture.db = drizzle({ client: pool });
const migrations = new URL("../../../../../migrations/", import.meta.url);
for (const name of (await readdir(migrations)).filter((name) => /^\d+_/.test(name)).sort()) {
@@ -98,6 +103,90 @@ describe.skipIf(!databaseUrl)("application Trash: real retained rows, storage an
const contents = (row: Record<string, unknown>) =>
Object.fromEntries(Object.entries(row).filter(([key]) => !["trashed_at", "updated_at"].includes(key)));
+ it("removes only the reviewed contact and refuses stale, unauthorized or invalid removal", async () => {
+ const contact = {
+ name: "Fictional Sam",
+ role: "Recruiter",
+ type: "Recruiter",
+ email: "[email protected]",
+ phone: "",
+ };
+ const contacts = [contact, contact, { ...contact, name: "Fictional Alex" }];
+ const id = await api().create({
+ company: "Fictional Cedar",
+ role: "Engineer",
+ contacts,
+ notes: "Fictional retained note",
+ });
+ const reviewed = await api().getById({ id });
+ if (!reviewed.contactsVersion) throw new Error("Missing review version");
+ const input = { id, index: 1, expectedVersion: reviewed.contactsVersion };
+ await expect(api("bob").deleteContact(input)).rejects.toMatchObject({ code: "NOT_FOUND" });
+ await expect(api("alice", ["read", "write"]).deleteContact(input)).rejects.toMatchObject({ code: "FORBIDDEN" });
+ await expect(api().deleteContact({ ...input, index: -1 })).rejects.toMatchObject({ code: "BAD_REQUEST" });
+ await expect(api().deleteContact({ ...input, index: 8 })).rejects.toMatchObject({ code: "CONFLICT" });
+ await expect(api("alice", ["delete"]).deleteContact(input)).resolves.toBeUndefined();
+ await expect(api().deleteContact(input)).rejects.toMatchObject({ code: "CONFLICT" });
+ const saved = await api().getById({ id });
+ expect(saved.contacts).toEqual([contact, contacts[2]]);
+ expect(saved.notes).toBe(reviewed.notes);
+ expect(saved.activity).toEqual(reviewed.activity);
+ expect((await raw(id)).contacts).toEqual(saved.contacts);
+ await api().update({ id, contacts: [] });
+ await expect(api().deleteContact(input)).rejects.toMatchObject({ code: "CONFLICT" });
+ expect((await raw(id)).contacts).toEqual([]);
+ });
+
+ it("contact removal preserves a newer note without treating that unrelated edit as a contact conflict", async () => {
+ const contact = { name: "Fictional Sam", role: "", type: "", email: "", phone: "" };
+ const id = await api().create({ company: "Fictional Cedar", role: "Engineer", contacts: [contact] });
+ const reviewed = await api().getById({ id });
+ if (!reviewed.contactsVersion) throw new Error("Missing review version");
+ await api().update({ id, notes: "Fictional newer note" });
+ await api().deleteContact({ id, index: 0, expectedVersion: reviewed.contactsVersion });
+ const saved = await api().getById({ id });
+ expect(saved.contacts).toEqual([]);
+ expect(saved.notes).toBe("Fictional newer note");
+ });
+
+ it("serializes simultaneous removals at the reviewed version without deleting both duplicate contacts", async () => {
+ const contact = { name: "Fictional Sam", role: "", type: "", email: "", phone: "" };
+ const id = await api().create({ company: "Fictional Cedar", role: "Engineer", contacts: [contact, contact] });
+ const reviewed = await api().getById({ id });
+ if (!reviewed.contactsVersion) throw new Error("Missing review version");
+ const blocker = await pool.connect();
+ let requests: Promise<PromiseSettledResult<unknown>[]> | undefined;
+ try {
+ await blocker.query("BEGIN");
+ await blocker.query("SELECT id FROM application WHERE id=$1 FOR UPDATE", [id]);
+ const input = { id, index: 0, expectedVersion: reviewed.contactsVersion };
+ requests = Promise.allSettled([api().deleteContact(input), api().deleteContact(input)]);
+ await expect
+ .poll(async () =>
+ Number(
+ (
+ await admin.query(
+ "SELECT count(*) FROM pg_stat_activity WHERE application_name=$1 AND wait_event_type='Lock'",
+ [namespace],
+ )
+ ).rows[0].count,
+ ),
+ )
+ .toBe(2);
+ await blocker.query("COMMIT");
+ const outcomes = await requests;
+ expect(outcomes.filter((result) => result.status === "fulfilled")).toHaveLength(1);
+ expect(outcomes.filter((result) => result.status === "rejected")).toEqual([
+ expect.objectContaining({ reason: expect.objectContaining({ code: "CONFLICT" }) }),
+ ]);
+ expect((await raw(id)).contacts).toEqual([contact]);
+ } finally {
+ await blocker.query("ROLLBACK");
+ blocker.release();
+ await requests;
+ }
+ });
+
it("retains timeline, linked snapshots, workspace, facts, coach and real attachment bytes across reload/restore", async () => {
await getDb()
.insert(tables.resume)
diff --git a/tests/e2e/specs/career-undo-lifecycle.spec.ts b/tests/e2e/specs/career-undo-lifecycle.spec.ts
index aec26c398..281bbeed7 100644
--- a/tests/e2e/specs/career-undo-lifecycle.spec.ts
+++ b/tests/e2e/specs/career-undo-lifecycle.spec.ts
@@ -224,3 +224,160 @@ test("pending Mark as read stays out of Show read until canonical retry succeeds
const result = await database.query("select read_at from career_notification where id=$1", [id]);
expect(result.rows[0].read_at).toBeNull();
});
+
+for (const action of ["contact", "interview"] as const)
+ for (const exit of ["reload", "close"] as const)
+ test(`${action} deletion persists through ${exit} during Undo`, async ({ authPage: page }, info) => {
+ const created = await page.request.post("/api/openapi/applications", {
+ data: { company: "Fictional Cedar", role: "Fictional engineer", status: "applied" },
+ });
+ await expect(created).toBeOK();
+ const id: string = await created.json();
+ let entryId: string | undefined;
+ if (action === "contact") {
+ await expect(
+ await page.request.put(`/api/openapi/applications/${id}`, {
+ data: {
+ contacts: [
+ { name: "Fictional Sam", role: "Recruiter", email: "[email protected]", phone: "", type: "Recruiter" },
+ ],
+ },
+ }),
+ ).toBeOK();
+ await page.goto(`/dashboard/applications?applicationId=${id}`);
+ await page.getByRole("button", { name: "Contact: Fictional Sam", exact: true }).click();
+ await page.getByRole("button", { name: "Remove Fictional Sam", exact: true }).click();
+ } else {
+ await expect(
+ await page.request.post(`/api/openapi/applications/${id}/interviews`, {
+ data: { at: "2026-11-15T14:00:00Z", kind: "technical", durationMinutes: 60, timezone: "UTC" },
+ }),
+ ).toBeOK();
+ const read = await page.request.get(`/api/openapi/applications/${id}`);
+ await expect(read).toBeOK();
+ entryId = (await read.json()).activity.find((entry: { type: string }) => entry.type === "interview").id;
+ await page.setViewportSize({ width: 375, height: 812 });
+ await page.goto("/dashboard/applications?view=calendar");
+ await page
+ .getByTestId("interview-agenda")
+ .getByRole("button")
+ .filter({ hasText: "Fictional Cedar" })
+ .first()
+ .click();
+ await page
+ .getByRole("dialog", { name: "Edit interview", exact: true })
+ .getByRole("button", { name: "Delete", exact: true })
+ .click();
+ }
+ await expect(page.getByRole("button", { name: "Undo", exact: true })).toBeVisible();
+ if (action === "interview" && exit === "reload") {
+ await expect(page.getByRole("dialog", { name: "Edit interview", exact: true })).toBeHidden();
+ await page.screenshot({ path: info.outputPath("interview-undo-ready.png"), animations: "disabled" });
+ }
+ const pending = (await database.query("select contacts, activity from application where id=$1", [id])).rows[0];
+ expect(
+ action === "contact"
+ ? pending.contacts.length === 1
+ : pending.activity.some((entry: { id: string }) => entry.id === entryId),
+ ).toBe(true);
+ await expect(page.getByRole("button", { name: "Undo", exact: true })).toBeVisible();
+ await leave(page, exit);
+ // No page is reopened before SQL proves the deletion reached storage.
+ await expect
+ .poll(async () => {
+ const row = (await database.query("select contacts, activity from application where id=$1", [id])).rows[0];
+ if (!row) return false;
+ return action === "contact"
+ ? row.contacts.length === 0
+ : !row.activity.some((entry: { id: string }) => entry.id === entryId);
+ })
+ .toBe(true);
+ });
+
+test("contact Undo reads canonical survivors and read-only Retry cannot restore externally erased text", async ({
+ authPage: page,
+}, info) => {
+ const created = await page.request.post("/api/openapi/applications", {
+ data: { company: "Fictional Cedar", role: "Fictional engineer", status: "applied" },
+ });
+ await expect(created).toBeOK();
+ const id: string = await created.json();
+ await expect(
+ await page.request.put(`/api/openapi/applications/${id}`, {
+ data: {
+ contacts: [
+ { name: "Fictional Sam", role: "Recruiter", email: "[email protected]", phone: "", type: "Recruiter" },
+ ],
+ },
+ }),
+ ).toBeOK();
+ await page.goto(`/dashboard/applications?applicationId=${id}`);
+ await page.getByRole("button", { name: "Contact: Fictional Sam", exact: true }).click();
+ const remove = page.getByRole("button", { name: "Remove Fictional Sam", exact: true });
+ await remove.click();
+ await expect(page.getByRole("button", { name: "Undo", exact: true })).toBeVisible();
+ await expect(remove).toHaveCount(0);
+ await page.getByRole("button", { name: "Undo", exact: true }).click();
+ await expect(page.getByRole("button", { name: "Contact: Fictional Sam", exact: true })).toBeVisible();
+ await page.getByRole("button", { name: "Contact: Fictional Sam", exact: true }).click();
+ await expect(remove).toBeVisible();
+ expect((await database.query("select contacts from application where id=$1", [id])).rows[0].contacts).toHaveLength(1);
+ await remove.click();
+ await expect(page.getByRole("button", { name: "Undo", exact: true })).toBeVisible();
+ await expect(await page.request.put(`/api/openapi/applications/${id}`, { data: { contacts: [] } })).toBeOK();
+ let failed = true;
+ let retryReads = 0;
+ await page.route("**/api/rpc/**", async (route) => {
+ if (failed) await failRpcProcedure(route, "/api/rpc/applications/getById", "Fictional readback unavailable");
+ else {
+ const request = route.request();
+ const entries: { url: string }[] = new URL(request.url()).pathname.endsWith("/__batch__")
+ ? JSON.parse(request.postData() ?? "[]")
+ : [{ url: request.url() }];
+ if (entries.some((entry) => new URL(entry.url).pathname === "/api/rpc/applications/getById")) retryReads++;
+ await route.continue();
+ }
+ });
+ await page.getByRole("button", { name: "Undo", exact: true }).click();
+ await expect(page.getByRole("button", { name: "Retry", exact: true })).toBeVisible();
+ await expect(remove).toHaveCount(0);
+ await expect(page.getByRole("button", { name: "Contact: none yet", exact: true })).toBeVisible();
+ await page.getByRole("button", { name: "Contact: none yet", exact: true }).click();
+ await page.screenshot({ path: info.outputPath("contacts-readback-retry.png"), animations: "disabled" });
+ failed = false;
+ await page.getByRole("button", { name: "Retry", exact: true }).click();
+ // Empty UI was already hidden; prove Retry actually requests its canonical target.
+ await expect.poll(() => retryReads).toBeGreaterThan(0);
+ await expect(page.getByRole("button", { name: "Contact: none yet", exact: true })).toBeVisible();
+ await expect(remove).toHaveCount(0);
+ expect((await database.query("select contacts from application where id=$1", [id])).rows[0].contacts).toEqual([]);
+ await page.reload();
+ await page.locator(`tr[data-application-id="${id}"] [data-application-open]`).click();
+ await expect(page.getByRole("button", { name: "Contact: none yet", exact: true })).toBeVisible();
+});
+
+test("contact removal HTTP contract converts the reviewed path index and refuses replay", async ({
+ authPage: page,
+}) => {
+ const contact = { name: "Fictional Sam", role: "", type: "", email: "", phone: "" };
+ const created = await page.request.post("/api/openapi/applications", {
+ data: { company: "Fictional Cedar", role: "Engineer", contacts: [contact, contact] },
+ });
+ await expect(created).toBeOK();
+ const id: string = await created.json();
+ const read = await page.request.get(`/api/openapi/applications/${id}`);
+ await expect(read).toBeOK();
+ const reviewed = await read.json();
+ const input = { data: { expectedVersion: reviewed.contactsVersion } };
+ const removed = await page.request.delete(`/api/openapi/applications/${id}/contacts/1`, input);
+ await expect(removed).toBeOK();
+ expect(removed.status()).toBe(200);
+ expect(await removed.text()).toBe("");
+ const after = await page.request.get(`/api/openapi/applications/${id}`);
+ await expect(after).toBeOK();
+ expect((await after.json()).contacts).toEqual([contact]);
+ expect((await page.request.delete(`/api/openapi/applications/${id}/contacts/1`, input)).status()).toBe(409);
+ expect((await database.query("select contacts from application where id=$1", [id])).rows[0].contacts).toEqual([
+ contact,
+ ]);
+});