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(applications): prepare stage moves before Undo acknowledgement

Amruth Pillaic3ceafafc840
diff --git a/apps/mobile/scripts/applications-summary.test.mjs b/apps/mobile/scripts/applications-summary.test.mjs
index 9d1a373b5..63ecebcb3 100644
--- a/apps/mobile/scripts/applications-summary.test.mjs
+++ b/apps/mobile/scripts/applications-summary.test.mjs
@@ -10,7 +10,11 @@ const { MutationObserver, QueryClient, QueryObserver } = createRequire(new URL("
let followUpDomain;
function load(path, mocks = {}) {
- const dependencies = { "@reactive-resume/schema/applications/follow-up": followUpDomain, ...mocks };
+ const dependencies = {
+ "@reactive-resume/schema/applications/follow-up": followUpDomain,
+ "@/api/client": { SessionChangedError: Error },
+ ...mocks,
+ };
const module = { exports: {} };
const code = transformSync(readFileSync(new URL("../src/" + path, import.meta.url), "utf8"), {
loader: path.endsWith(".tsx") ? "tsx" : "ts",
@@ -27,6 +31,31 @@ function load(path, mocks = {}) {
return module.exports;
}
+const { prepareRequest } = load("../../../packages/utils/src/deferred-request.ts");
+const prepareCall = (call) =>
+ prepareRequest(async (defer) => {
+ let result;
+ await defer(async () => {
+ result = await call();
+ return new Response();
+ });
+ return result;
+ });
+const deferredUndo = (options) => {
+ const ready = options.prepare().then((request) => {
+ options.onReady();
+ return request;
+ });
+ return {
+ ready,
+ restore: async () => {
+ (await ready).cancel();
+ return options.restore();
+ },
+ commit: async () => options.commit((await ready).send()),
+ };
+};
+
const zod = createRequire(new URL("../../../packages/schema/package.json", import.meta.url))("zod");
const timeParser = load("../../../packages/utils/src/timezone.ts", { zod });
followUpDomain = load("../../../packages/schema/src/applications/follow-up.ts", {
@@ -922,12 +951,11 @@ queryClient.clear();
applicationDetailQueryKey: detailKey,
stageScope: () => "fixture:account",
useApplicationMutations: () => ({
- bulkUpdate: {
- mutateAsync: async (input) => {
+ prepareBulkUpdate: (input) =>
+ prepareCall(async () => {
writes.push(input);
return { updated: input.ids.length };
- },
- },
+ }),
}),
},
"./stages": stages,
@@ -935,9 +963,9 @@ queryClient.clear();
"../../../packages/schema/src/applications/stage-baselines.ts",
{ "./data": applicationData },
),
- "@/auth/session": { useSession: () => ({ server: "fixture" }) },
+ "@/auth/session": { useSession: () => ({ server: "fixture" }), getServer: () => "fixture" },
"@/features/career/hooks": { useOffers: () => ({ data: undefined }) },
- "@/features/career/undo": { withUndo: (options) => pending.push(options) },
+ "@/features/career/undo": { withUndo: (options) => pending.push(deferredUndo(options)) },
"@/routes": { routes: { application: (id, tab) => `/applications/${id}/${tab}` } },
"@/ui": { showToast() {} },
});
@@ -952,6 +980,7 @@ queryClient.clear();
closedReason: "accepted-other",
message: "2 closed",
});
+ await pending[0].ready;
assert.deepEqual(
client.getQueryData(listKey).map((row) => [row.status, row.closedReason]),
[
@@ -961,7 +990,7 @@ queryClient.clear();
);
assert.equal(client.getQueryData(detailKey("a")).status, "closed", "the open application shows the move too");
assert.equal(writes.length, 0, "nothing is written until the toast ends");
- pending[0].restore();
+ await pending[0].restore();
assert.deepEqual(client.getQueryData(listKey), rows, "Undo puts every row back");
assert.equal(client.getQueryData(detailKey("a")).status, "applied");
move({ applications: [{ id: "b" }], lane: closed, supported: false, closedReason: "withdrew", message: "1 closed" });
@@ -985,6 +1014,7 @@ queryClient.clear();
closedReason: "withdrew",
message: "2 closed",
});
+ await pending[2].ready;
client.setQueryData(listKey, (current) =>
current.map((row) =>
row.id === "a"
@@ -994,7 +1024,7 @@ queryClient.clear();
: row,
),
);
- pending[2].restore();
+ await pending[2].restore();
assert.deepEqual(
client.getQueryData(listKey).map((row) => [row.id, row.status]),
[
@@ -1047,8 +1077,8 @@ queryClient.clear();
applicationDetailQueryKey: (id) => ["application", id, "fixture"],
stageScope: () => "fixture:account",
useApplicationMutations: () => ({
- bulkUpdate: {
- mutateAsync: async (input) => {
+ prepareBulkUpdate: (input) =>
+ prepareCall(async () => {
order.push({ status: input.status, expected: input.expectedStages });
const saved = [];
for (const { id, ...expected } of input.expectedStages) {
@@ -1058,15 +1088,14 @@ queryClient.clear();
saved.push({ id, ...server[id] });
}
return { updated: saved.length, stages: saved };
- },
- },
+ }),
}),
},
"./stages": stages,
"@reactive-resume/schema/applications/stage-baselines": stageBaselines,
- "@/auth/session": { useSession: () => ({ server: "fixture" }) },
+ "@/auth/session": { useSession: () => ({ server: "fixture" }), getServer: () => "fixture" },
"@/features/career/hooks": { useOffers: () => ({ data: undefined }) },
- "@/features/career/undo": { withUndo: (options) => pending.push(options) },
+ "@/features/career/undo": { withUndo: (options) => pending.push(deferredUndo(options)) },
"@/routes": { routes: { application: (id, tab) => `/applications/${id}/${tab}` } },
"@/ui": { showToast: (toast) => toasts.push(toast.message) },
});
@@ -1100,6 +1129,7 @@ queryClient.clear();
closedReason: "withdrew",
message: "closed",
});
+ await pending[3].ready;
server.a = { ...server.a, stageEntryId: "outside-change" };
await pending[3].commit();
assert.equal(server.a.status, "interview");
diff --git a/apps/mobile/scripts/deferred-stage.test.mjs b/apps/mobile/scripts/deferred-stage.test.mjs
new file mode 100644
index 000000000..7bb177623
--- /dev/null
+++ b/apps/mobile/scripts/deferred-stage.test.mjs
@@ -0,0 +1,389 @@
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import { createRequire } from "node:module";
+import { test } from "node:test";
+const mobileRequire = createRequire(new URL("../package.json", import.meta.url));
+const serverRequire = createRequire(new URL("../../server/package.json", import.meta.url));
+const { transformSync } = createRequire(serverRequire.resolve("tsx"))("esbuild");
+const { MutationObserver, QueryClient } = mobileRequire("@tanstack/react-query");
+const zod = createRequire(new URL("../../../packages/schema/package.json", import.meta.url))("zod");
+function load(file, mocks, timers = {}) {
+ const module = { exports: {} };
+ const code = transformSync(readFileSync(new URL(file, import.meta.url), "utf8"), {
+ loader: "ts",
+ format: "cjs",
+ }).code;
+ new Function("require", "module", "exports", "setTimeout", "clearTimeout", code)(
+ (name) => {
+ assert.ok(name in mocks, `Missing boundary: ${name}`);
+ return mocks[name];
+ },
+ module,
+ module.exports,
+ timers.set,
+ timers.clear,
+ );
+ return module.exports;
+}
+const { prepareRequest } = load("../../../packages/utils/src/deferred-request.ts", {});
+const data = load("../../../packages/schema/src/applications/data.ts", {
+ zod,
+ "@reactive-resume/utils/timezone": load("../../../packages/utils/src/timezone.ts", { zod }),
+});
+const schemaLanes = load("../../../packages/schema/src/applications/lanes.ts", { zod, "./data": data });
+const tracker = load("../../../packages/schema/src/applications/stage-baselines.ts", { "./data": data });
+const lanes = load("../src/features/applications/lanes.ts", {
+ "@reactive-resume/schema/applications/lanes": schemaLanes,
+ "./stages": { getStageLabel: (value) => value },
+});
+const deferred = () => {
+ let resolve;
+ const promise = new Promise((done) => {
+ resolve = done;
+ });
+ return { promise, resolve };
+};
+const drain = () => new Promise((resolve) => setImmediate(resolve));
+const tag = (parts, ...values) => parts.reduce((text, part, index) => text + part + (values[index] ?? ""), "");
+async function until(predicate) {
+ for (let attempt = 0; attempt < 100; attempt++) {
+ if (predicate()) return;
+ await drain();
+ }
+ assert.fail("Expected lifecycle did not settle");
+}
+function harness() {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: Infinity } } });
+ const initial = { id: "fictional-job", status: "applied", laneId: null, closedReason: null, activity: [] };
+ const env = {
+ account: "alice",
+ row: initial,
+ metadata: true,
+ laneGate: null,
+ notices: [],
+ sent: [],
+ reminders: [],
+ reads: 0,
+ sequence: 0,
+ };
+ const getServer = () => "fixture";
+ const auth = {
+ getServer,
+ getAccountScope: () => env.account,
+ useSession: () => ({ status: "signed-in", server: getServer() }),
+ };
+ const pipeline = { revision: 0, lanes: schemaLanes.createDefaultApplicationLanes() };
+ const metadataKey = ["lanes", "fixture", "alice"];
+ const query = (name, read) => ({
+ key: () => [name],
+ queryOptions: (options) => ({ queryKey: [name, ...(options?.input?.id ? [options.input.id] : [])], queryFn: read }),
+ });
+ const mutate = (name) => ({
+ mutationOptions: () => ({ mutationKey: [["applications", name], { type: "mutation" }] }),
+ });
+ const orpc = {
+ applications: {
+ key: () => ["applications"],
+ listSummary: query("applications", async () => {
+ env.reads++;
+ return [env.row];
+ }),
+ getById: query("detail", async () => env.row),
+ ...Object.fromEntries(
+ ["create", "update", "trash", "bulkUpdate", "bulkTrash", "import", "logFollowUp"].map((name) => [
+ name,
+ mutate(name),
+ ]),
+ ),
+ },
+ documents: { key: () => ["documents"] },
+ career: { key: () => ["career"] },
+ agent: { key: () => ["agent"] },
+ };
+ const saved = (status, laneId = null) => {
+ const entry = {
+ id: `stage-${++env.sequence}`,
+ type: "stage",
+ stage: status,
+ at: new Date(),
+ writeSequence: env.sequence,
+ };
+ env.row = {
+ ...env.row,
+ status,
+ laneId,
+ closedReason: status === "closed" ? "withdrew" : null,
+ activity: [...env.row.activity, entry],
+ };
+ return { id: env.row.id, status, laneId, closedReason: env.row.closedReason, stageEntryId: entry.id };
+ };
+ const rpc = {
+ applications: {
+ update: async (input, options) => {
+ assert.equal(options.context.scope, env.account);
+ saved(input.status, input.laneId);
+ return env.row;
+ },
+ bulkUpdate: async (input, options) => {
+ if (options.context.scope !== env.account) throw new Error("Account changed");
+ const response = await options.context.defer(async () => {
+ assert.equal(options.context.scope, env.account);
+ env.sent.push(input);
+ const expected = input.expectedStages[0];
+ if (expected.status !== env.row.status || expected.stageEntryId !== data.latestStageEntryId(env.row.activity))
+ return Response.json({ updated: 0, stages: [] });
+ const lane = pipeline.lanes.find((item) => item.id === input.laneId);
+ return Response.json({ updated: 1, stages: [saved(lane?.category ?? input.status, lane?.id ?? null)] });
+ });
+ return response.json();
+ },
+ },
+ };
+ const api = {
+ orpc,
+ client: rpc,
+ SessionChangedError: Error,
+ prepareRpc: (procedure, input) => {
+ const scope = env.account;
+ return prepareRequest((defer) => procedure(input, { context: { scope, defer } }));
+ },
+ };
+ const laneQueries = {
+ applicationLanesQueryOptions: () => ({
+ queryKey: metadataKey,
+ queryFn: async () => {
+ if (env.laneGate) await env.laneGate.promise;
+ return { supported: env.metadata, pipeline };
+ },
+ }),
+ useApplicationLanes: () => ({ ...pipeline, supported: true }),
+ };
+ const common = {
+ "@lingui/core/macro": { t: tag, plural: (n, forms) => forms[n === 1 ? "one" : "other"].replace("#", String(n)) },
+ "@/api/client": api,
+ "@/auth/session": auth,
+ "@/ui": {
+ showToast: (notice) => {
+ env.notices.push(notice);
+ return env.notices.length;
+ },
+ },
+ "./lanes": lanes,
+ "./lane-queries": laneQueries,
+ react: { useCallback: (fn) => fn, useRef: (value) => ({ current: value }), useEffect() {}, useMemo: (fn) => fn() },
+ "@tanstack/react-query": {
+ useQueryClient: () => client,
+ useMutation: (options) => ({ mutateAsync: (input) => new MutationObserver(client, options).mutate(input) }),
+ },
+ };
+ const queries = load("../src/features/applications/queries.ts", {
+ ...common,
+ "@/features/reminders": {
+ syncReminders: async (id, targets) => {
+ assert.deepEqual(targets, []);
+ env.reminders.push(id);
+ },
+ },
+ });
+ const listKey = queries.applicationsListQueryKey();
+ client.setQueryData(listKey, [initial]);
+ client.setQueryData(queries.applicationDetailQueryKey(initial.id), initial);
+ client.setQueryData(["documents"], ["fictional"]);
+ const listeners = new Set();
+ const timers = new Map();
+ let serial = 0;
+ const AppState = {
+ currentState: "active",
+ addEventListener: (_event, fn) => {
+ listeners.add(fn);
+ return { remove: () => listeners.delete(fn) };
+ },
+ };
+ const undo = load(
+ "../src/features/career/undo.ts",
+ {
+ ...common,
+ "react-native": { AppState },
+ "@/ui": { ...common["@/ui"], dismissToast() {}, toastLifetime: (value) => value },
+ },
+ {
+ set: (run) => {
+ const id = ++serial;
+ timers.set(id, run);
+ return id;
+ },
+ clear: (id) => timers.delete(id),
+ },
+ );
+ const actions = load("../src/features/applications/stage-actions.ts", {
+ ...common,
+ "./queries": queries,
+ "./stages": {},
+ "@reactive-resume/schema/applications/next-step": {},
+ "@reactive-resume/schema/applications/stage-baselines": tracker,
+ "expo-router": {},
+ "@/features/applications/error": {},
+ "@/features/career/hooks": {},
+ "@/features/career/undo": undo,
+ "@/routes": {},
+ });
+ tracker.followStageWrites(client, queries.stageScope, (id) => actions.listedApplication(client, id));
+ const move = (category, supported = true) =>
+ actions.useMoveWithUndo()({
+ applications: [{ id: initial.id }],
+ lane: pipeline.lanes.find((lane) => lane.category === category),
+ supported,
+ closedReason: category === "closed" ? "withdrew" : undefined,
+ message: `Moved to ${category}`,
+ });
+ const background = () => {
+ AppState.currentState = "background";
+ for (const fn of listeners) fn("background");
+ };
+ const releaseChain = async () => {
+ const next = tracker.stageBaselinesFor(client).begin("fixture:alice", new Map([[initial.id, initial]]));
+ let settled = false;
+ void next.baselines.get(initial.id).then(() => {
+ settled = true;
+ });
+ await until(() => settled);
+ next.settle([]);
+ };
+ const dispose = async () => {
+ env.account = "retired";
+ for (const run of timers.values()) run();
+ await drain();
+ client.clear();
+ };
+ return { env, client, queries, listKey, move, background, releaseChain, dispose };
+}
+
+test("native prepared bulk waits for real lane preflight; background dispatch preserves closed-reminder and cache lifecycle", async () => {
+ const h = harness();
+ h.env.laneGate = deferred();
+ try {
+ h.move("closed");
+ await drain();
+ assert.equal(h.env.notices.length, 0);
+ assert.equal(h.env.sent.length, 0);
+ assert.equal(h.client.getQueryData(h.listKey)[0].status, "applied");
+ h.env.laneGate.resolve();
+ await until(() => h.env.notices.some((notice) => notice.action?.label === "Undo"));
+ assert.equal(h.env.sent.length, 0);
+ assert.equal(h.client.getQueryData(h.listKey)[0].status, "closed");
+ h.background();
+ assert.equal(h.env.sent.length, 1, "transport enters before background listener returns");
+ h.background();
+ assert.equal(h.env.sent.length, 1);
+ await until(() => h.env.reminders.length === 1);
+ assert.deepEqual(h.env.reminders, ["fictional-job"]);
+ assert.equal(h.client.getQueryState(["documents"]).isInvalidated, true);
+ } finally {
+ await h.dispose();
+ }
+});
+
+test("native ready Undo cancels erasure, keeps reminders and releases the queued baseline", async () => {
+ const h = harness();
+ try {
+ h.move("closed");
+ await until(() => h.env.notices.some((notice) => notice.action?.label === "Undo"));
+ h.env.notices.find((notice) => notice.action?.label === "Undo").action.onPress();
+ await h.releaseChain();
+ assert.equal(h.env.sent.length, 0);
+ assert.deepEqual(h.env.reminders, []);
+ assert.equal(h.client.getQueryData(h.listKey)[0].status, "applied");
+ } finally {
+ await h.dispose();
+ }
+});
+
+test("native old-account stage receipt cannot clear replacement-account reminders", async () => {
+ const h = harness();
+ try {
+ h.move("closed");
+ await until(() => h.env.notices.some((notice) => notice.action?.label === "Undo"));
+ h.background();
+ assert.equal(h.env.sent.length, 1);
+ h.env.account = "bob";
+ await until(() =>
+ h.client
+ .getMutationCache()
+ .getAll()
+ .some((mutation) => mutation.state.status === "success"),
+ );
+ assert.deepEqual(h.env.reminders, []);
+ } finally {
+ await h.dispose();
+ }
+});
+
+test("native replacement account cannot dispatch while lane preflight is pending or after readiness", async () => {
+ for (const pending of [true, false]) {
+ const h = harness();
+ try {
+ if (pending) h.env.laneGate = deferred();
+ h.move("closed");
+ if (!pending) await until(() => h.env.notices.some((notice) => notice.action?.label === "Undo"));
+ h.env.account = "bob";
+ if (pending) h.env.laneGate.resolve();
+ else h.background();
+ await h.releaseChain();
+ assert.equal(h.env.sent.length, 0);
+ assert.deepEqual(h.env.reminders, []);
+ } finally {
+ await h.dispose();
+ }
+ }
+});
+
+test("native failed lane preparation releases a queued canonical move without acknowledgement", async () => {
+ const h = harness();
+ h.env.metadata = false;
+ try {
+ h.move("interview");
+ h.move("offer", false);
+ await until(() => h.env.notices.some((notice) => notice.message === "Moved to offer"));
+ assert.equal(
+ h.env.notices.some((notice) => notice.message === "Moved to interview"),
+ false,
+ );
+ h.background();
+ await until(() => h.env.row.status === "offer");
+ assert.equal(h.env.sent.length, 1);
+ assert.equal(h.env.sent[0].status, "offer");
+ } finally {
+ await h.dispose();
+ }
+});
+
+test("native later immediate stage remains visible when an old move becomes ready; partial closure uses canonical reminder state", async () => {
+ const h = harness();
+ h.env.laneGate = deferred();
+ try {
+ h.move("interview");
+ await drain();
+ await h.queries.useApplicationMutations().update.mutateAsync({ id: "fictional-job", status: "offer" });
+ h.env.laneGate.resolve();
+ await until(() => h.env.notices.some((notice) => notice.message === "Moved to interview"));
+ assert.equal(h.client.getQueryData(h.listKey)[0].status, "offer");
+ h.background();
+ await until(() => h.env.sent.length === 1);
+ await drain();
+ assert.equal(h.env.row.status, "offer");
+ assert.deepEqual(h.env.reminders, []);
+ } finally {
+ await h.dispose();
+ }
+ const closed = harness();
+ try {
+ closed.env.row = { ...closed.env.row, status: "closed" };
+ closed.move("closed");
+ await until(() => closed.env.notices.some((notice) => notice.action?.label === "Undo"));
+ closed.background();
+ await until(() => closed.env.reminders.length === 1);
+ assert.ok(closed.env.reads > 0, "partial bulk receipt refreshes canonical closure before reminder cleanup");
+ } finally {
+ await closed.dispose();
+ }
+});
diff --git a/apps/mobile/src/features/applications/queries.ts b/apps/mobile/src/features/applications/queries.ts
index f3c71fad1..0de00261c 100644
--- a/apps/mobile/src/features/applications/queries.ts
+++ b/apps/mobile/src/features/applications/queries.ts
@@ -1,12 +1,13 @@
import type { Application, ApplicationSummary } from "./types";
-import type { RouterInput } from "@/api/client";
+import type { RouterInput, RouterOutput } from "@/api/client";
+import type { DeferredFetch } from "@reactive-resume/utils/deferred-request";
import type { ListViewToken } from "react-native";
import { t } from "@lingui/core/macro";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useCallback, useEffect, useRef } from "react";
import { applicationLanesQueryOptions } from "./lane-queries";
import { resolveLane } from "./lanes";
-import { client, orpc } from "@/api/client";
+import { client, orpc, prepareRpc } from "@/api/client";
import { getAccountScope, getServer, useSession } from "@/auth/session";
import { syncReminders } from "@/features/reminders";
import { showToast } from "@/ui";
@@ -206,13 +207,19 @@ export function useApplicationMutations() {
},
onSettled,
});
- const bulkUpdate = useMutation({
+ const bulkUpdateOptions = (defer?: DeferredFetch) => ({
...orpc.applications.bulkUpdate.mutationOptions(),
mutationFn: async (input: RouterInput["applications"]["bulkUpdate"]) => {
await ensureLaneWrite(input);
- return client.applications.bulkUpdate(input, { context: { scope: scope ?? undefined } });
+ return client.applications.bulkUpdate(input, {
+ context: { scope: scope ?? undefined, ...(defer ? { defer } : {}) },
+ });
},
- onSuccess: async (data, input) => {
+ onSuccess: async (
+ data: RouterOutput["applications"]["bulkUpdate"],
+ input: RouterInput["applications"]["bulkUpdate"],
+ ) => {
+ if (scope !== getAccountScope()) return;
const metadata = queryClient.getQueryData(applicationLanesQueryOptions(server, scope).queryKey);
const category = input.status ?? metadata?.pipeline.lanes.find((lane) => lane.id === input.laneId)?.category;
// A successful receipt for every requested row plus an immutable target category confirms closure.
@@ -220,7 +227,6 @@ export function useApplicationMutations() {
cancelReminders(input.ids);
return;
}
- if (scope !== getAccountScope()) return;
// Bulk's count is not evidence of each row's canonical status. Read the authoritative result.
try {
await queryClient.cancelQueries({ queryKey: applicationsListQueryKey(server) });
@@ -238,6 +244,13 @@ export function useApplicationMutations() {
},
onSettled,
});
+ const bulkUpdate = useMutation(bulkUpdateOptions());
+ const prepareBulkUpdate = (input: RouterInput["applications"]["bulkUpdate"]) =>
+ prepareRpc(
+ (value, { context }) =>
+ queryClient.getMutationCache().build(queryClient, bulkUpdateOptions(context.defer)).execute(value),
+ input,
+ );
const bulkDelete = useMutation({
...orpc.applications.bulkTrash.mutationOptions(),
mutationFn: (input: RouterInput["applications"]["bulkTrash"]) =>
@@ -261,5 +274,5 @@ export function useApplicationMutations() {
},
onSettled,
});
- return { create, update, remove, bulkUpdate, bulkDelete, importCsv, logFollowUp };
+ return { create, update, remove, bulkUpdate, prepareBulkUpdate, bulkDelete, importCsv, logFollowUp };
}
diff --git a/apps/mobile/src/features/applications/stage-actions.ts b/apps/mobile/src/features/applications/stage-actions.ts
index a11cd5ad1..17404adfa 100644
--- a/apps/mobile/src/features/applications/stage-actions.ts
+++ b/apps/mobile/src/features/applications/stage-actions.ts
@@ -13,6 +13,7 @@ import { useApplicationLanes } from "./lane-queries";
import { getLaneLabel, laneInput, resolveLane } from "./lanes";
import { applicationDetailQueryKey, applicationsListQueryKey, stageScope, useApplicationMutations } from "./queries";
import { getClosedReasonLabel } from "./stages";
+import { SessionChangedError } from "@/api/client";
import { getServer, useSession } from "@/auth/session";
import { applicationError } from "@/features/applications/error";
import { useOffers } from "@/features/career/hooks";
@@ -51,9 +52,11 @@ export const listedApplication = (queryClient: QueryClient, id: string, server =
export function useMoveWithUndo() {
const queryClient = useQueryClient();
const session = useSession();
- const { bulkUpdate } = useApplicationMutations();
+ const { prepareBulkUpdate } = useApplicationMutations();
return ({ applications, lane, supported, closedReason, message }: MoveWithUndoInput) => {
+ const scope = stageScope();
+ const current = () => scope === stageScope() && getServer() === session.server;
const ids = applications.map((application) => application.id);
if (ids.length === 0) return;
const reason = lane.category === "closed" ? (lane.closedReason ?? closedReason ?? null) : null;
@@ -68,7 +71,7 @@ export function useMoveWithUndo() {
before.set(id, { status: row.status, laneId: row.laneId, closedReason: row.closedReason });
listed.set(id, row);
}
- const { baselines, settle } = stageBaselinesFor(queryClient).begin(stageScope(), listed);
+ const { baselines, settle, isLatest } = stageBaselinesFor(queryClient).begin(stageScope(), listed);
const input = {
ids,
...laneInput(lane, supported),
@@ -79,16 +82,20 @@ export function useMoveWithUndo() {
const showsMove = (row: Stage) =>
row.status === patch.status && (row.closedReason ?? null) === reason && row.laneId === patch.laneId;
const apply = <Row extends Stage & { id: string }>(row: Row): Row =>
- selected.has(row.id) ? { ...row, ...patch } : row;
+ selected.has(row.id) && isLatest(row.id) ? { ...row, ...patch } : row;
const revert = <Row extends Stage & { id: string }>(row: Row): Row => {
const stage = before.get(row.id);
return stage && showsMove(row) ? { ...row, ...stage } : row;
};
- queryClient.setQueryData<ApplicationSummary[]>(listKey, (current) => current?.map(apply));
- for (const id of ids) queryClient.setQueryData<Application>(detailKey(id), (current) => current && apply(current));
+ const showMove = () => {
+ queryClient.setQueryData<ApplicationSummary[]>(listKey, (current) => current?.map(apply));
+ for (const id of ids)
+ queryClient.setQueryData<Application>(detailKey(id), (current) => current && apply(current));
+ };
const restore = () => {
settle([]);
+ if (!current()) return;
queryClient.setQueryData<ApplicationSummary[]>(listKey, (current) => current?.map(revert));
for (const id of ids)
queryClient.setQueryData<Application>(detailKey(id), (current) => current && revert(current));
@@ -97,15 +104,35 @@ export function useMoveWithUndo() {
withUndo({
message,
- commit: async () => {
- const expectedStages = await Promise.all(
- [...baselines].map(async ([id, pending]) => {
- const { laneId, ...baseline } = await pending;
- return { id, ...baseline, ...(supported ? { laneId } : {}) };
- }),
- );
- const { updated, stages } = await bulkUpdate.mutateAsync({ ...input, expectedStages });
+ prepare: async () => {
+ try {
+ const expectedStages = await Promise.all(
+ [...baselines].map(async ([id, pending]) => {
+ const baseline = await pending;
+ before.set(id, { status: baseline.status, laneId: baseline.laneId, closedReason: baseline.closedReason });
+ const { laneId, ...stage } = baseline;
+ return { id, ...stage, ...(supported ? { laneId } : {}) };
+ }),
+ );
+ if (!current()) throw new SessionChangedError();
+ const request = await prepareBulkUpdate({ ...input, expectedStages });
+ return {
+ send: request.send,
+ cancel: () => {
+ request.cancel();
+ settle([]);
+ },
+ };
+ } catch (error) {
+ settle([]);
+ throw error;
+ }
+ },
+ onReady: showMove,
+ commit: async (result) => {
+ const { updated, stages } = await result;
settle(stages ?? []);
+ if (!current()) return;
const kept = ids.length - updated;
if (kept > 0)
showToast({
diff --git a/apps/web/src/features/applications/use-application-actions.test.tsx b/apps/web/src/features/applications/use-application-actions.test.tsx
index c2e293d16..39b20e92c 100644
--- a/apps/web/src/features/applications/use-application-actions.test.tsx
+++ b/apps/web/src/features/applications/use-application-actions.test.tsx
@@ -3,11 +3,14 @@ import type { ApplicationSummary } from "./types";
import type { ApplicationPipeline } from "@reactive-resume/schema/applications/lanes";
import type { ReactNode } from "react";
import { renderHook, waitFor } from "@testing-library/react";
-import { describe, expect, it, vi } from "vite-plus/test";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
import { i18n } from "@lingui/core";
import { MutationObserver, QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { createDefaultApplicationLanes } from "@reactive-resume/schema/applications/lanes";
-import { followStageWrites } from "@reactive-resume/schema/applications/stage-baselines";
+import { followStageWrites, stageBaselinesFor } from "@reactive-resume/schema/applications/stage-baselines";
+import { prepareRequest } from "@reactive-resume/utils/deferred-request";
+import { pendingCommits } from "@/features/career/pending-commits";
+import { invalidateAccountScope, setAccountScope } from "@/libs/auth/account-scope";
const mocks = vi.hoisted(() => ({
update: vi.fn(),
@@ -15,11 +18,13 @@ const mocks = vi.hoisted(() => ({
close: vi.fn(),
lanes: vi.fn(),
bulkUpdate: vi.fn(),
+ prepare: vi.fn(),
navigate: vi.fn(),
}));
vi.mock("@tanstack/react-router", () => ({ useRouter: () => ({ navigate: mocks.navigate }) }));
vi.mock("@/libs/orpc/client", () => ({
client: { applications: { bulkUpdate: mocks.bulkUpdate } },
+ prepareRpc: mocks.prepare,
orpc: {
applications: {
key: () => ["applications"],
@@ -58,6 +63,25 @@ import { listedApplication, STAGE_SCOPE, useApplicationActions, useMoveWithUndo
i18n.load("en", {});
i18n.activate("en");
+beforeEach(() => {
+ setAccountScope("stage-fixture");
+ mocks.prepare.mockReset().mockImplementation((procedure: (input: unknown) => Promise<unknown>, input: unknown) =>
+ prepareRequest(async (defer) => {
+ let result: unknown;
+ await defer(async () => {
+ result = await procedure(input);
+ return new Response();
+ });
+ return result;
+ }),
+ );
+});
+afterEach(() => {
+ invalidateAccountScope();
+ for (const flush of pendingCommits) flush();
+ pendingCommits.clear();
+});
+
const defaults = createDefaultApplicationLanes();
function lane(category: string) {
const found = defaults.find((item) => item.category === category);
@@ -182,6 +206,16 @@ type ToastCall = {
onClose?: () => void;
};
const lastToast = () => mocks.toast.mock.calls.at(-1)?.[0] as ToastCall;
+const undoNotice = async (description: string) => {
+ const find = () =>
+ mocks.toast.mock.calls
+ .map(([call]) => call as ToastCall)
+ .findLast((call) => call.description === description && call.actionProps?.children === "Undo");
+ await waitFor(() => expect(find()).toBeDefined());
+ const notice = find();
+ if (!notice) throw new Error("Undo notice missing");
+ return notice;
+};
describe("moves with Undo (J2-18)", () => {
const stageEntry = (id: string, stage: string) => [{ id: `${id}-${stage}`, type: "stage", stage, at: new Date(0) }];
@@ -204,10 +238,11 @@ describe("moves with Undo (J2-18)", () => {
return { client, ...renderHook(() => useMoveWithUndo(), { wrapper }) };
}
- it("shows the move at once and puts every row back on Undo without writing", () => {
+ it("shows the prepared move and puts every row back on Undo without writing", async () => {
const { client, result } = setupMove();
result.current({ applications: [{ id: "a" }, { id: "b" }], lane: lane("interview"), description: "2 moved" });
+ await undoNotice("2 moved");
expect(client.getQueryData<ApplicationSummary[]>(["applications"])?.map((row) => row.status)).toEqual([
"interview",
"interview",
@@ -232,8 +267,8 @@ describe("moves with Undo (J2-18)", () => {
closedReason: "accepted-other",
description: "2 closed",
});
- lastToast().onClose?.();
- lastToast().onClose?.();
+ (await undoNotice("2 closed")).onClose?.();
+ (await undoNotice("2 closed")).onClose?.();
await waitFor(() => expect(mocks.bulkUpdate).toHaveBeenCalledTimes(1));
expect(mocks.bulkUpdate).toHaveBeenCalledWith({
@@ -252,7 +287,7 @@ describe("moves with Undo (J2-18)", () => {
const { client, result } = setupMove();
mocks.bulkUpdate.mockRejectedValue(new Error("conflict"));
result.current({ applications: [{ id: "a" }], lane: lane("offer"), description: "moved" });
- lastToast().onClose?.();
+ (await undoNotice("moved")).onClose?.();
await waitFor(() => expect(client.getQueryData<ApplicationSummary[]>(["applications"])).toEqual(rows));
});
@@ -344,7 +379,7 @@ describe("moves with Undo beside later edits (J2-18)", () => {
const { stages, order } = server();
const { result } = setupBoth();
result.current.move({ applications: [{ id: "a" }, { id: "b" }], lane: lane("interview"), description: "2 moved" });
- const bulk = lastToast();
+ const bulk = await undoNotice("2 moved");
result.current.actions.moveTo({ id: "a" }, lane("offer"));
await waitFor(() => expect(mocks.update).toHaveBeenCalled());
@@ -366,13 +401,12 @@ describe("moves with Undo beside later edits (J2-18)", () => {
const { stages, order } = server();
const { result } = setupBoth();
result.current.move({ applications: [{ id: "a" }], lane: lane("interview"), description: "moved" });
- const first = lastToast();
+ const first = await undoNotice("moved");
result.current.move({ applications: [{ id: "a" }], lane: lane("offer"), description: "moved again" });
- const second = lastToast();
-
- // The second toast can close first; its write still waits for the first one's.
- second.onClose?.();
+ expect(lastToast()).toBe(first);
first.onClose?.();
+ const second = await undoNotice("moved again");
+ second.onClose?.();
await waitFor(() => expect(order).toEqual(["bulk a -> interview", "bulk a -> offer"]));
expect(mocks.bulkUpdate.mock.calls[1]?.[0].expectedStages).toEqual([
@@ -385,7 +419,7 @@ describe("moves with Undo beside later edits (J2-18)", () => {
// A third move before the list reloads starts from what the second saved, not the list's older timeline.
result.current.move({ applications: [{ id: "a" }], lane: lane("interview"), description: "moved back" });
- lastToast().onClose?.();
+ (await undoNotice("moved back")).onClose?.();
await waitFor(() => expect(stages.a?.status).toBe("interview"));
expect(mocks.bulkUpdate.mock.calls[2]?.[0].expectedStages).toEqual([
{ id: "a", status: "offer", laneId: null, closedReason: null, stageEntryId: "change-2" },
@@ -396,11 +430,11 @@ describe("moves with Undo beside later edits (J2-18)", () => {
const { stages, order } = server();
const { result } = setupBoth();
result.current.move({ applications: [{ id: "a" }], lane: lane("interview"), description: "moved" });
- const first = lastToast();
+ const first = await undoNotice("moved");
result.current.move({ applications: [{ id: "a" }], lane: lane("offer"), description: "moved again" });
- const second = lastToast();
first.onClose?.();
await waitFor(() => expect(order).toEqual(["bulk a -> interview"]));
+ const second = await undoNotice("moved again");
// Another device moves it away and back before the second move is saved.
stages.a = { status: "interview", laneId: null, closedReason: null, stageEntryId: "elsewhere" };
second.onClose?.();
@@ -416,11 +450,11 @@ describe("moves with Undo beside later edits (J2-18)", () => {
const { stages, order } = server();
const { result } = setupBoth();
result.current.move({ applications: [{ id: "a" }], lane: lane("interview"), description: "moved" });
- const first = lastToast();
+ const first = await undoNotice("moved");
result.current.move({ applications: [{ id: "a" }], lane: lane("offer"), description: "moved again" });
- const second = lastToast();
first.actionProps?.onClick();
+ const second = await undoNotice("moved again");
second.onClose?.();
await waitFor(() => expect(order).toEqual(["bulk a -> offer"]));
@@ -437,11 +471,11 @@ describe("moves with Undo beside later edits (J2-18)", () => {
result.current.actions.moveTo({ id: "a" }, lane("interview"));
await waitFor(() => expect(mocks.update).toHaveBeenCalled());
result.current.move({ applications: [{ id: "a" }], lane: lane("offer"), description: "moved" });
- lastToast().onClose?.();
// The bulk write waits for the single one's answer.
expect(order).toEqual([]);
held.open();
+ (await undoNotice("moved")).onClose?.();
await waitFor(() => expect(order).toEqual(["update a", "bulk a -> offer"]));
expect(mocks.bulkUpdate.mock.calls[0]?.[0].expectedStages).toEqual([
{ id: "a", status: "interview", laneId: null, closedReason: null, stageEntryId: "change-1" },
@@ -459,8 +493,8 @@ describe("moves with Undo beside later edits (J2-18)", () => {
result.current.actions.moveTo({ id: "a" }, lane("interview"));
await waitFor(() => expect(mocks.update).toHaveBeenCalled());
result.current.move({ applications: [{ id: "a" }], lane: lane("offer"), description: "moved" });
- lastToast().onClose?.();
held.fail(new Error("offline"));
+ (await undoNotice("moved")).onClose?.();
await waitFor(() => expect(order).toEqual(["bulk a -> offer"]));
expect(mocks.bulkUpdate.mock.calls[0]?.[0].expectedStages).toEqual([
@@ -473,20 +507,19 @@ describe("moves with Undo beside later edits (J2-18)", () => {
const { stages, order } = server();
const { result } = setupBoth();
result.current.move({ applications: [{ id: "a" }], lane: lane("interview"), description: "moved" });
- const first = lastToast();
+ const first = await undoNotice("moved");
const held = holdSingleWrites();
result.current.actions.moveTo({ id: "a" }, lane("screening"));
await waitFor(() => expect(mocks.update).toHaveBeenCalled());
result.current.move({ applications: [{ id: "a" }], lane: lane("offer"), description: "moved again" });
- const third = lastToast();
- third.onClose?.();
first.onClose?.();
held.open();
+ (await undoNotice("moved again")).onClose?.();
- await waitFor(() => expect(order).toHaveLength(3));
- // The first bulk move started before the single move, so the single move wins over it; the last move wins.
+ await waitFor(() => expect(order).toEqual(["bulk a -> interview", "update a", "bulk a -> offer"]));
+ // Prepared transport starts before the single-write gate opens; the final move starts from its later receipt.
expect(mocks.bulkUpdate.mock.calls.find(([input]) => input.status === "offer")?.[0].expectedStages).toEqual([
- { id: "a", status: "screening", laneId: null, closedReason: null, stageEntryId: "change-1" },
+ { id: "a", status: "screening", laneId: null, closedReason: null, stageEntryId: "change-2" },
]);
expect(stages.a?.status).toBe("offer");
});
@@ -495,16 +528,15 @@ describe("moves with Undo beside later edits (J2-18)", () => {
const { stages, order } = server();
const { result } = setupBoth();
result.current.move({ applications: [{ id: "a" }], lane: lane("interview"), description: "moved" });
- const first = lastToast();
+ const first = await undoNotice("moved");
const held = holdSingleWrites();
result.current.actions.moveTo({ id: "a" }, lane("screening"));
await waitFor(() => expect(mocks.update).toHaveBeenCalled());
result.current.move({ applications: [{ id: "a" }], lane: lane("offer"), description: "moved again" });
- const third = lastToast();
first.onClose?.();
await waitFor(() => expect(order).toEqual(["bulk a -> interview"]));
held.fail(new Error("offline"));
- third.onClose?.();
+ (await undoNotice("moved again")).onClose?.();
await waitFor(() => expect(order).toEqual(["bulk a -> interview", "bulk a -> offer"]));
expect(mocks.bulkUpdate.mock.calls[1]?.[0].expectedStages).toEqual([
@@ -539,10 +571,10 @@ describe("moves with Undo beside later edits (J2-18)", () => {
const submitted = submit("c", new Promise((resolve) => (open = resolve)));
const failed = submit("a", new Promise((_resolve, reject) => (fail = reject)));
result.current.move({ applications: [{ id: "a" }, { id: "c" }], lane: lane("interview"), description: "2 moved" });
- lastToast().onClose?.();
open();
fail(new Error("offline"));
await Promise.all([submitted, failed]);
+ (await undoNotice("2 moved")).onClose?.();
await waitFor(() => expect(order).toEqual(["submit c", "bulk a,c -> interview"]));
expect(mocks.bulkUpdate.mock.calls[0]?.[0].expectedStages).toEqual([
@@ -580,7 +612,7 @@ describe("moves with Undo beside later edits (J2-18)", () => {
}).mutate({ id: "a", status: "interview" });
await new Promise((resolve) => setTimeout(resolve, 0));
result.current.move({ applications: [{ id: "a" }], lane: lane("offer"), description: "moved" });
- lastToast().onClose?.();
+ (await undoNotice("moved")).onClose?.();
await waitFor(() => expect(order).toEqual(["bulk a -> offer"]));
expect(stages.a?.status).toBe("offer");
expect(mocks.bulkUpdate.mock.calls[0]?.[0].expectedStages[0].stageEntryId).toBe("morning");
@@ -595,7 +627,7 @@ describe("moves with Undo beside later edits (J2-18)", () => {
// Another device moves A away and back; B only gets a note, which adds no stage change.
stages.a = { status: "interview", laneId: null, closedReason: null, stageEntryId: "elsewhere" };
result.current.move({ applications: [{ id: "a" }, { id: "b" }], lane: lane("offer"), description: "2 moved" });
- lastToast().onClose?.();
+ (await undoNotice("2 moved")).onClose?.();
await waitFor(() => expect(order).toHaveLength(3));
expect(stages.a.status).toBe("interview");
@@ -609,7 +641,7 @@ describe("moves with Undo beside later edits (J2-18)", () => {
server();
const { client, result } = setupBoth();
result.current.move({ applications: [{ id: "a" }, { id: "b" }], lane: lane("interview"), description: "2 moved" });
- const bulk = lastToast();
+ const bulk = await undoNotice("2 moved");
result.current.actions.moveTo({ id: "a" }, lane("offer"));
result.current.actions.moveTo({ id: "c" }, lane("applied"));
await waitFor(() => expect(mocks.update).toHaveBeenCalledTimes(2));
@@ -623,6 +655,86 @@ describe("moves with Undo beside later edits (J2-18)", () => {
]);
expect(mocks.bulkUpdate).not.toHaveBeenCalled();
});
+
+ it("a later immediate move remains visible when an earlier bulk intent finishes preparing", async () => {
+ const { stages, order } = server();
+ const { result, client } = setupBoth();
+ let release!: () => void;
+ const held = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const prepare = mocks.prepare.getMockImplementation();
+ if (!prepare) throw new Error("Transport fixture missing");
+ mocks.prepare.mockImplementationOnce(async (procedure, input) => {
+ await held;
+ return prepare(procedure, input);
+ });
+ result.current.move({ applications: [{ id: "a" }], lane: lane("interview"), description: "pending move" });
+ await waitFor(() => expect(mocks.prepare).toHaveBeenCalledTimes(1));
+ result.current.actions.moveTo({ id: "a" }, lane("offer"));
+ await waitFor(() => expect(order).toEqual(["update a"]));
+ release();
+ const notice = await undoNotice("pending move");
+ expect(client.getQueryData<ApplicationSummary[]>(["applications"])?.[0]?.status).toBe("offer");
+ notice.onClose?.();
+ await waitFor(() => expect(order).toHaveLength(2));
+ expect(stages.a?.status).toBe("offer");
+ });
+
+ it("a failed preparation releases the next queued move without acknowledging the failed move", async () => {
+ const { stages, order } = server();
+ const { result } = setupBoth();
+ mocks.prepare.mockRejectedValueOnce(new Error("Preflight unavailable"));
+ result.current.move({ applications: [{ id: "a" }], lane: lane("interview"), description: "failed move" });
+ result.current.move({ applications: [{ id: "a" }], lane: lane("offer"), description: "next move" });
+ const next = await undoNotice("next move");
+ expect(mocks.toast.mock.calls.some(([call]) => call.description === "failed move")).toBe(false);
+ next.onClose?.();
+ await waitFor(() => expect(order).toEqual(["bulk a -> offer"]));
+ expect(stages.a?.status).toBe("offer");
+ });
+
+ it("an account switch while waiting for a baseline cannot prepare the old move for the replacement account", async () => {
+ const { order } = server();
+ const { client, result } = setupBoth();
+ const held = holdSingleWrites();
+ result.current.actions.moveTo({ id: "a" }, lane("interview"));
+ await waitFor(() => expect(mocks.update).toHaveBeenCalled());
+ result.current.move({ applications: [{ id: "a" }], lane: lane("offer"), description: "old account move" });
+ setAccountScope("replacement");
+ held.open();
+ await waitFor(() => expect(order).toEqual(["update a"]));
+ const row = rows()[0];
+ if (!row) throw new Error("Application fixture missing");
+ const next = stageBaselinesFor(client).begin(STAGE_SCOPE, new Map([["a", row]]));
+ let settled = false;
+ void next.baselines.get("a")?.then(() => {
+ settled = true;
+ });
+ await waitFor(() => expect(settled).toBe(true));
+ next.settle([]);
+ expect(mocks.prepare).not.toHaveBeenCalled();
+ expect(mocks.bulkUpdate).not.toHaveBeenCalled();
+ });
+
+ it("an account switch cancels a ready transport and releases its baseline chain", async () => {
+ server();
+ const { client, result } = setupBoth();
+ result.current.move({ applications: [{ id: "a" }], lane: lane("offer"), description: "ready move" });
+ const notice = await undoNotice("ready move");
+ setAccountScope("replacement");
+ notice.onClose?.();
+ const row = rows()[0];
+ if (!row) throw new Error("Application fixture missing");
+ const next = stageBaselinesFor(client).begin(STAGE_SCOPE, new Map([["a", row]]));
+ let settled = false;
+ void next.baselines.get("a")?.then(() => {
+ settled = true;
+ });
+ await waitFor(() => expect(settled).toBe(true));
+ next.settle([]);
+ expect(mocks.bulkUpdate).not.toHaveBeenCalled();
+ });
});
describe("Offer and accepted-offer follow-ups (J2-06, J2-07)", () => {
@@ -661,6 +773,7 @@ describe("Offer and accepted-offer follow-ups (J2-06, J2-07)", () => {
expect(mocks.bulkUpdate).not.toHaveBeenCalled();
lastToast().actionProps?.onClick();
+ await waitFor(() => expect(lastToast().actionProps?.children).toBe("Undo"));
lastToast().onClose?.();
await waitFor(() =>
expect(mocks.bulkUpdate).toHaveBeenCalledWith({
diff --git a/apps/web/src/features/applications/use-application-actions.ts b/apps/web/src/features/applications/use-application-actions.ts
index be81680ed..1b3f70d96 100644
--- a/apps/web/src/features/applications/use-application-actions.ts
+++ b/apps/web/src/features/applications/use-application-actions.ts
@@ -11,8 +11,9 @@ import { getCategoryLane, getLaneLabel, laneMoveInput } from "./lanes";
import { applicationDetailQueryKey, applicationsListQueryKey } from "./queries";
import { applicationLanesQueryKey, useApplicationLanes } from "./use-application-lanes";
import { withUndo } from "@/features/career/shared";
+import { getAccountGeneration } from "@/libs/auth/account-scope";
import { toastError } from "@/libs/error-message";
-import { client, orpc } from "@/libs/orpc/client";
+import { client, orpc, prepareRpc } from "@/libs/orpc/client";
/** Refreshes everything that shows applications: the list, the open one, stats, tags and documents' job lines. */
export function useInvalidateApplications() {
@@ -71,6 +72,8 @@ export function useMoveWithUndo() {
const listKey = applicationsListQueryKey();
return ({ applications, lane, closedReason, description }: MoveWithUndoInput) => {
+ const generation = getAccountGeneration();
+ const current = () => generation === getAccountGeneration();
const ids = applications.map((application) => application.id);
if (ids.length === 0) return;
const input = laneMoveInput(lane, mode, closedReason);
@@ -89,7 +92,7 @@ export function useMoveWithUndo() {
before.set(id, stageOf(row));
listed.set(id, row);
}
- const { baselines, settle } = stageBaselinesFor(queryClient).begin(STAGE_SCOPE, listed);
+ const { baselines, settle, isLatest } = stageBaselinesFor(queryClient).begin(STAGE_SCOPE, listed);
const revert = <Row extends Stage & { id: string }>(row: Row): Row => {
const stage = before.get(row.id);
@@ -97,30 +100,56 @@ export function useMoveWithUndo() {
};
const selected = new Set(ids);
const apply = <Row extends Stage & { id: string }>(row: Row): Row =>
- selected.has(row.id) ? { ...row, ...moved } : row;
+ selected.has(row.id) && isLatest(row.id) ? { ...row, ...moved } : row;
- queryClient.setQueryData<ApplicationSummary[]>(listKey, (current) => current?.map(apply));
- // The open application (sheet, workspace) shows the move too.
- for (const id of ids)
- queryClient.setQueryData<Application>(applicationDetailQueryKey(id), (current) => current && apply(current));
+ const showMove = () => {
+ queryClient.setQueryData<ApplicationSummary[]>(listKey, (current) => current?.map(apply));
+ for (const id of ids)
+ queryClient.setQueryData<Application>(applicationDetailQueryKey(id), (current) => current && apply(current));
+ };
const restore = () => {
settle([]);
+ if (!current()) return;
queryClient.setQueryData<ApplicationSummary[]>(listKey, (current) => current?.map(revert));
for (const id of ids)
queryClient.setQueryData<Application>(applicationDetailQueryKey(id), (current) => current && revert(current));
for (const id of ids) invalidate(id);
};
+ const failed = (error: unknown) => {
+ restore();
+ if (current()) toastError(error, t`Couldn't update the applications. Try again.`);
+ };
withUndo({
description,
- commit: async () => {
+ prepare: async () => {
try {
const expectedStages = await Promise.all(
[...baselines].map(async ([id, baseline]) => ({ id, ...(await baseline) })),
);
- const { updated, stages } = await client.applications.bulkUpdate({ ids, ...input, expectedStages });
+ if (!current()) throw new DOMException("", "AbortError");
+ for (const stage of expectedStages) before.set(stage.id, stageOf(stage));
+ const request = await prepareRpc(client.applications.bulkUpdate, { ids, ...input, expectedStages });
+ return {
+ send: request.send,
+ cancel: () => {
+ request.cancel();
+ settle([]);
+ },
+ };
+ } catch (error) {
+ settle([]);
+ throw error;
+ }
+ },
+ onReady: showMove,
+ onPrepareError: failed,
+ commit: async (result) => {
+ try {
+ const { updated, stages } = await result;
settle(stages ?? []);
+ if (!current()) return;
const kept = ids.length - updated;
if (kept > 0)
toast.add({
@@ -130,10 +159,9 @@ export function useMoveWithUndo() {
}),
});
} catch (error) {
- restore();
- toastError(error, t`Couldn't update the applications. Try again.`);
+ failed(error);
} finally {
- for (const id of ids) invalidate(id);
+ if (current()) for (const id of ids) invalidate(id);
}
},
onUndo: restore,
diff --git a/docs/guides/tracking-job-applications.mdx b/docs/guides/tracking-job-applications.mdx
index ae4efff93..09d76f158 100644
--- a/docs/guides/tracking-job-applications.mdx
+++ b/docs/guides/tracking-job-applications.mdx
@@ -137,7 +137,14 @@ In the List view on a computer or tablet, select the checkboxes next to the appl
/>
</Frame>
-Moves and closes show at once with **Undo** in the message. They're saved when the message goes away, or when you leave the page; **Undo** puts the selected applications back where they were, without recording a stage change. If you move one of them again before then, here or on another device, that later move stays, even if it moved away and back to the same stage: the bulk move leaves it and says so, and **Undo** leaves it too. Other edits, such as a note, don't stop the move. If you move the same applications again before the first move is saved, or while a move of one of them from its own menu or details, **Mark as applied**, or a message's changes are still being saved, the later move is saved after the earlier one, so it's the one that stays. Removing a stage in **Stages** moves its applications to another stage of the same kind without counting as a change. Tags and deletions are saved straight away.
+Bulk moves and keyboard triage show the new stage and **Undo** once the pending move is ready. They're saved when the message goes away, when you reload or close the tab, or when the native app goes to the background; **Undo** puts the selected applications back where they were, without recording a stage change. If you move one of them again before then, here or on another device, that later move stays, even if it moved away and back to the same stage: the bulk move leaves it and says so, and **Undo** leaves it too. Other edits, such as a note, don't stop the move. If you move the same applications again before the first move is saved, or while a move of one of them from its own menu or details, **Mark as applied**, or a message's changes are still being saved, the later move is saved after the earlier one, so it's the one that stays. Removing a stage in **Stages** moves its applications to another stage of the same kind without counting as a change. Tags and deletions are saved straight away.
+
+<Frame caption="The fictional application shows Offer while Undo can still cancel the pending move.">
+ <img
+ src="/images/guides/tracking-job-applications/stage-move-undo.png"
+ alt="Fictional Cedar Platform engineer in Offer with a Moved to Offer message and Undo button"
+ />
+</Frame>
You can act on up to 200 applications at once. Larger selections show a reminder; deselect rows or narrow the search before choosing an action. The list leaves room to scroll its final rows above the selection bar, including when its buttons wrap.
diff --git a/docs/images/guides/tracking-job-applications/stage-move-undo.png b/docs/images/guides/tracking-job-applications/stage-move-undo.png
new file mode 100644
index 000000000..49c05fa20
Binary files /dev/null and b/docs/images/guides/tracking-job-applications/stage-move-undo.png differ
diff --git a/packages/schema/src/applications/stage-baselines.ts b/packages/schema/src/applications/stage-baselines.ts
index db6da8048..129babdb8 100644
--- a/packages/schema/src/applications/stage-baselines.ts
+++ b/packages/schema/src/applications/stage-baselines.ts
@@ -63,6 +63,7 @@ function createStageBaselines() {
*/
begin(scope: string, rows: ReadonlyMap<string, ListedRow>) {
const baselines = new Map<string, Promise<StageBaseline>>();
+ const outcomes = new Map<string, Promise<StageBaseline>>();
for (const [id, row] of rows) {
const key = `${scope}:${id}`;
const earlier = pending.get(key);
@@ -81,10 +82,19 @@ function createStageBaselines() {
const { id: _id, ...saved } = stage;
return saved;
});
+ outcomes.set(id, outcome);
follow(`${scope}:${id}`, outcome);
}
- return { baselines, settle };
+ return {
+ baselines,
+ settle,
+ // Readiness can arrive after a later intent; only its own latest rows may change optimistically.
+ isLatest: (id: string) => {
+ const outcome = outcomes.get(id);
+ return outcome !== undefined && pending.get(`${scope}:${id}`) === outcome;
+ },
+ };
},
/**
diff --git a/tests/e2e/specs/applications-keyboard-triage.spec.ts b/tests/e2e/specs/applications-keyboard-triage.spec.ts
index 099121c1f..8c96e7619 100644
--- a/tests/e2e/specs/applications-keyboard-triage.spec.ts
+++ b/tests/e2e/specs/applications-keyboard-triage.spec.ts
@@ -1,6 +1,43 @@
import { Client } from "pg";
import { expect, test } from "../fixtures/test";
+for (const exit of ["reload", "close"] as const)
+ test(`acknowledged stage move persists through ${exit} during Undo`, async ({ authPage: page }, info) => {
+ const created = await page.request.post("/api/openapi/applications", {
+ data: { company: "Fictional Cedar", role: "Platform engineer", status: "applied" },
+ });
+ await expect(created).toBeOK();
+ const id: string = await created.json();
+ await page.goto("/dashboard/applications");
+ await page.locator(`tr[data-application-id="${id}"] [data-application-open]`).focus();
+ await page.keyboard.press("5");
+ await expect(page.getByRole("button", { name: "Undo", exact: true })).toBeVisible();
+ if (exit === "reload")
+ await page.screenshot({ path: info.outputPath("stage-move-undo.png"), animations: "disabled" });
+ const pending = await page.request.get(`/api/openapi/applications/${id}`);
+ await expect(pending).toBeOK();
+ expect((await pending.json()).status).toBe("applied");
+ await expect(page.getByRole("button", { name: "Undo", exact: true })).toBeVisible();
+ if (exit === "reload") await page.reload();
+ else await Promise.all([page.waitForEvent("close"), page.close({ runBeforeUnload: true })]);
+ const sql = new Client({ connectionString: process.env.DATABASE_URL });
+ await sql.connect();
+ try {
+ // Read SQL before reopening: persistence must not rely on recovery in another page.
+ await expect
+ .poll(async () => (await sql.query("select status from application where id = $1", [id])).rows[0]?.status)
+ .toBe("offer");
+ const stored = (await sql.query("select activity from application where id = $1", [id])).rows[0];
+ expect(
+ stored.activity.filter(
+ (entry: { type: string; stage?: string }) => entry.type === "stage" && entry.stage === "offer",
+ ),
+ ).toHaveLength(1);
+ } finally {
+ await sql.end();
+ }
+ });
+
test("focused triage persists canonical stages/contact, suppresses repeats, keeps Undo and stage conflicts", async ({
authPage: page,
}, info) => {