A one-of-a-kind resume builder that keeps your privacy in mind. Completely secure, customizable, portable, open-source and free forever. Try it out today!
TypeScript agent-skillsaidsh-pluginhacktoberfestjavascriptmcp-serverreactresume-builderself-hostedtypescript
fix: preserve offer retries and fence late save callbacks
Amruth Pillai507241328b0f
diff --git a/apps/mobile/scripts/experience.test.mjs b/apps/mobile/scripts/experience.test.mjsindex c803f85f0..3c0b54217 100644--- a/apps/mobile/scripts/experience.test.mjs+++ b/apps/mobile/scripts/experience.test.mjs@@ -21,6 +21,7 @@ const react = {if (ref) ref.current = make();},useEffect() {},+ useLayoutEffect() {},useState(initial) {const index = cursor++;if (!(index in hooks)) hooks[index] = typeof initial === "function" ? initial() : initial;@@ -95,6 +96,7 @@ const mocks = {react,"react-native": { View: "View", Pressable: "Pressable", ScrollView: "ScrollView", Platform: { OS: "android" } },"expo-router": {+ useIsFocused: () => true,useRouter: () => router,useLocalSearchParams: () => searchParams,Stack: { Screen: "StackScreen" },@@ -1355,52 +1357,91 @@ let savedOffers = [let offerApplications = { data: [] };let loseOfferResponse = false;let offerFailures = 0;-const { OfferEntry, OfferForm } = load("features/career/offer-entry.tsx", {- "@reactive-resume/utils/string": load("../../../packages/utils/src/string.ts", { uuid: serverRequire("uuid") }),+let holdOfferResponse = false;+let heldOffer;+let offerFocused = true;+const offerLayouts = [];+const offerStorage = new Map();+const nativeOfferSelection = load("features/career/offer-selection.ts", {"@/auth/session": { getAccountScope: () => offerScope },- "@reactive-resume/schema/career": careerSchema,- "@reactive-resume/schema/career-offer": offerParser,- "./hooks": {- useCareerTime: () => ({ locale: "en-US", timeZone: "Europe/Berlin", profile: offerProfile }),- useCareerAction: () => ({- pending: false,- run: async (work, success) => {- try {- success(await work());- } catch {- offerFailures++;- }+ "zustand/react": {+ create: (initialize) => {+ const store = createRequire(new URL("../../web/package.json", import.meta.url))("zustand/vanilla").createStore(+ initialize,+ );+ return Object.assign((selector) => selector(store.getState()), store);+ },+ },+});+const loadOfferEntry = () =>+ load("features/career/offer-entry.tsx", {+ react: {+ ...react,+ useLayoutEffect: (effect) => {+ offerLayouts.push(effect);},- }),- client: {- career: {- createOffer: async (input) => {- calls.push(input);- return { id: "new-offer", data: { kind: "offer", ...input } };- },- updateOffer: async (input) => {- calls.push(input);- if (loseOfferResponse) {- loseOfferResponse = false;- throw new Error("Response lost after commit");+ },+ "expo-router": { ...mocks["expo-router"], useIsFocused: () => offerFocused },+ "expo-sqlite/kv-store": {+ getItemSync: (key) => offerStorage.get(key) ?? null,+ setItemSync: (key, value) => {+ offerStorage.set(key, value);+ },+ removeItemSync: (key) => {+ offerStorage.delete(key);+ },+ },+ "./offer-selection": nativeOfferSelection,+ "@reactive-resume/utils/string": load("../../../packages/utils/src/string.ts", { uuid: serverRequire("uuid") }),+ "@/auth/session": { getAccountScope: () => offerScope },+ "@reactive-resume/schema/career": careerSchema,+ "@reactive-resume/schema/career-offer": offerParser,+ "./hooks": {+ useCareerTime: () => ({ locale: "en-US", timeZone: "Europe/Berlin", profile: offerProfile }),+ useCareerAction: () => ({+ pending: false,+ run: async (work, success) => {+ try {+ success(await work());+ } catch {+ offerFailures++;}- return { id: "new-version", data: { kind: "offer", ...input.terms } };+ },+ }),+ client: {+ career: {+ createOffer: async (input) => {+ calls.push(input);+ return { id: "new-offer", data: { kind: "offer", ...input } };+ },+ updateOffer: async (input) => {+ calls.push(input);+ if (loseOfferResponse) {+ loseOfferResponse = false;+ throw new Error("Response lost after commit");+ }+ if (holdOfferResponse) {+ heldOffer = Promise.withResolvers();+ await heldOffer.promise;+ }+ return { id: "new-version", data: { kind: "offer", ...input.terms } };+ },},},+ useOffers: () => ({ data: savedOffers }),+ useCareerQueries: () => ({ profile: { data: undefined } }),},- useOffers: () => ({ data: savedOffers }),- useCareerQueries: () => ({ profile: { data: undefined } }),- },- "./offer-compare": { formatMoney: (_locale, currency, amount) => `${currency} ${amount}` },- "./shared": { EditorSheet: "EditorSheet", LoadState: "LoadState" },- "@/features/application-detail/date-field": { WallClockField: "WallClockField" },- "@/features/applications/lane-queries": laneQuery,- "@/features/applications/lanes": lanes,- "@/features/applications/stage-actions": {- useMoveWithUndo: () => (input) => calls.push({ moveWithUndo: input }),- },- "@/features/applications/queries": { useApplications: () => offerApplications },-});+ "./offer-compare": { formatMoney: (_locale, currency, amount) => `${currency} ${amount}` },+ "./shared": { EditorSheet: "EditorSheet", LoadState: "LoadState" },+ "@/features/application-detail/date-field": { WallClockField: "WallClockField" },+ "@/features/applications/lane-queries": laneQuery,+ "@/features/applications/lanes": lanes,+ "@/features/applications/stage-actions": {+ useMoveWithUndo: () => (input) => calls.push({ moveWithUndo: input }),+ },+ "@/features/applications/queries": { useApplications: () => offerApplications },+ });+const { OfferEntry, OfferForm } = loadOfferEntry();reset();offerApplications = { isPending: true };assert.equal(render(OfferEntry, {}).type, "LoadState", "unknown metadata offers no ready action");@@ -1503,11 +1544,15 @@ const originalTerms = careerSchema.offerTermsSchema.parse({variable: null,variablePercent: 10,});+let CurrentOfferForm = OfferForm;+let offerCloses = 0;const correctedView = () =>- render(OfferForm, {+ render(CurrentOfferForm, {application: { id: "job", company: "Northwind Labs", role: "Engineer" },offer: { id: "original-offer", data: originalTerms },- onClose() {},+ onClose() {+ offerCloses++;+ },});assert.equal(control(correctedView(), "Bonus").value, "10%");assert.equal(control(correctedView(), "Bonus").keyboardType, "default", "percentage entry needs a percent key");@@ -1517,21 +1562,45 @@ control(correctedView(), "Save offer").onPress();await settle();assert.equal(offerFailures, 1);assert.equal(calls.length, 1, "lost response keeps the native form open without navigation");+const firstAttempt = calls[0];+CurrentOfferForm = loadOfferEntry().OfferForm;+reset();+control(correctedView(), "Bonus").onChangeText("12.5%");control(correctedView(), "Save offer").onPress();await settle();-assert.deepEqual(calls[1], calls[0], "retry uses the same version receipt after a lost response");+assert.deepEqual(calls[0], firstAttempt, "restart and re-entry retain the version receipt after a lost response");assert.match(calls[0].newId, /^[0-9a-f-]{36}$/);assert.equal(calls[0].id, "original-offer");assert.equal(calls[0].newVersion, true);assert.equal(calls[0].terms.variable, null);assert.equal(calls[0].terms.variablePercent, 12.5);assert.deepEqual(calls[0].expected, originalTerms);+assert.deepEqual(nativeOfferSelection.useSavedOffer.getState().accounts[offerScope], {+ id: "new-version",+ b: "pinned-offer",+});+assert.ok(!calls.some((call) => call?.params), "form never writes selection to the focused route");+assert.equal(offerCloses, 1);+calls.length = 0;+holdOfferResponse = true;+control(correctedView(), "Save offer").onPress();+await settle();+assert.ok(heldOffer);+offerFocused = false;+correctedView();+for (const effect of offerLayouts.splice(0)) effect();+heldOffer.resolve();+await settle();+assert.equal(offerCloses, 1, "late success cannot close a form after leaving its screen");assert.ok(- calls.some(- (call) =>- call?.params?.a === "new-version" && call.params.highlight === "new-version" && call.params.b === "pinned-offer",- ),+ !calls.some((call) => call?.params || call?.message),+ "late success cannot change another route or toast there",);+assert.equal(nativeOfferSelection.useSavedOffer.getState().accounts[offerScope].id, "new-version");+holdOfferResponse = false;+offerFocused = true;+correctedView();+for (const effect of offerLayouts.splice(0)) effect();calls.length = 0;offerScope = "another-account";control(correctedView(), "Save offer").onPress();diff --git a/apps/mobile/scripts/power-user-repairs.test.mjs b/apps/mobile/scripts/power-user-repairs.test.mjsindex d63844423..8b0113098 100644--- a/apps/mobile/scripts/power-user-repairs.test.mjs+++ b/apps/mobile/scripts/power-user-repairs.test.mjs@@ -88,7 +88,12 @@ const common = {Platform: { OS: "android" },BackHandler: { addEventListener: () => ({ remove() {} }) },},- "expo-router": { useRouter: () => router, useLocalSearchParams: () => ({}), Stack: { Screen: "StackScreen" } },+ "expo-router": {+ useRouter: () => router,+ useLocalSearchParams: () => ({}),+ useIsFocused: () => true,+ Stack: { Screen: "StackScreen" },+ },"@lingui/react/macro": { useLingui: () => ({ t: tag }) },"@lingui/core/macro": { t: tag, plural: (value, forms) => forms.other.replace("#", String(value)) },"@/ui": ui,@@ -162,7 +167,27 @@ const offerDomain = load("../../../packages/schema/src/career-offer.ts", {"@reactive-resume/utils/timezone": timeParser,});const shared = load("features/career/shared.tsx");+let selectionScope = "offer-account";+let offersFocused = true;+const selection = load("features/career/offer-selection.ts", {+ "@/auth/session": { getAccountScope: () => selectionScope },+ "zustand/react": {+ create: (initialize) => {+ const store = createRequire(new URL("../../web/package.json", import.meta.url))("zustand/vanilla").createStore(+ initialize,+ );+ return Object.assign((selector) => selector(store.getState()), store);+ },+ },+});const { OffersScreen } = load("features/career/offers.tsx", {+ "@/auth/session": { getAccountScope: () => selectionScope },+ "./offer-selection": selection,+ "expo-router": {+ ...common["expo-router"],+ useIsFocused: () => offersFocused,+ useRouter: () => ({ ...router, setParams: (params) => calls.push({ offerParams: params }) }),+ },"@reactive-resume/utils/timezone": timeParser,"./hooks": {useOffers: () => saved,@@ -279,6 +304,28 @@ for (const mode of ["pending", "error"]) {);if (mode === "error") assert.ok(nodes(retained).some((node) => node.type === "Banner"));}+selection.rememberSavedOffer(selectionScope, "retained", "pinned");+saved.data.push({ ...saved.data[0], id: "pinned" });+offersFocused = false;+calls.length = 0;+reset();+render(OffersScreen);+assert.ok(!calls.some((call) => call?.offerParams), "blurred Offers cannot mutate the current route");+assert.equal(selection.useSavedOffer.getState().accounts[selectionScope].id, "retained");+selectionScope = "another-account";+offersFocused = true;+reset();+render(OffersScreen);+assert.ok(!calls.some((call) => call?.offerParams), "another account cannot consume a saved selection");+selectionScope = "offer-account";+reset();+render(OffersScreen);+assert.deepEqual(calls.find((call) => call?.offerParams)?.offerParams, {+ a: "retained",+ b: "pinned",+ highlight: "retained",+});+assert.equal(selection.useSavedOffer.getState().accounts[selectionScope], undefined);saved.data = [];console.log("PASS native Offers loading/error/retry/persisted row and genuine-empty controls");diff --git a/apps/mobile/src/features/career/offer-entry.tsx b/apps/mobile/src/features/career/offer-entry.tsxindex e80f682cb..67d28fca4 100644--- a/apps/mobile/src/features/career/offer-entry.tsx+++ b/apps/mobile/src/features/career/offer-entry.tsx@@ -2,8 +2,9 @@ import type { SavedData } from "@/features/workspace/hooks";import type { ApplicationStatus } from "@reactive-resume/schema/applications/data";import type { OfferTerms } from "@reactive-resume/schema/career";import { useLingui } from "@lingui/react/macro";-import { useLocalSearchParams, useRouter } from "expo-router";-import { useState } from "react";+import { useIsFocused, useLocalSearchParams, useRouter } from "expo-router";+import Storage from "expo-sqlite/kv-store";+import { useLayoutEffect, useRef, useState } from "react";import { View } from "react-native";import { offerTermsSchema } from "@reactive-resume/schema/career";import {@@ -16,6 +17,7 @@ import {import { pendingRequestId, settleRequestId } from "@reactive-resume/utils/string";import { client, useCareerAction, useCareerQueries, useCareerTime, useOffers } from "./hooks";import { formatMoney } from "./offer-compare";+import { rememberSavedOffer } from "./offer-selection";import { EditorSheet, LoadState } from "./shared";import { getAccountScope } from "@/auth/session";import { WallClockField } from "@/features/application-detail/date-field";@@ -48,6 +50,12 @@ type OfferSaved = { id: string; data: OfferTermsSaved };/** Stages before Offer: saving an offer for an application still at one of these moves it to Offer, with Undo. */const BEFORE_OFFER: readonly ApplicationStatus[] = ["saved", "applied", "screening", "interview"];+const requestIds = {+ getItem: (key: string) => Storage.getItemSync(key),+ setItem: (key: string, value: string) => Storage.setItemSync(key, value),+ removeItem: (key: string) => Storage.removeItemSync(key),+};+/*** Add offer, and the offer saved last for this application in view as a one-line summary, so saving doesn't make the* terms disappear into Saved.@@ -152,6 +160,14 @@ const zonedFields = (value: string, timeZone: string) => {export function OfferForm({ application, offer: initialOffer, onClose, onSaved }: OfferFormProps) {const params = useLocalSearchParams<{ b?: string }>();+ const focused = useIsFocused();+ const active = useRef(focused);+ useLayoutEffect(() => {+ active.current = focused;+ return () => {+ active.current = false;+ };+ }, [focused]);const [scope] = useState(getAccountScope);// Draft and expected terms belong to the same edit session, even when saved offers refetch.const [offer] = useState(initialOffer);@@ -269,8 +285,9 @@ export function OfferForm({ application, offer: initialOffer, onClose, onSaved }const { applicationId: _applicationId, ...terms } = payload.data;const input = { id: offer.id, terms, expected: offerTermsSchema.parse(offer.data), newVersion: true };const key = JSON.stringify(["career:offer-version", scope, input]);- const result = await client.career.updateOffer({ ...input, newId: pendingRequestId(key) }, { context: { scope } });- settleRequestId(key);+ const newId = pendingRequestId(key, requestIds);+ const result = await client.career.updateOffer({ ...input, newId }, { context: { scope } });+ settleRequestId(key, requestIds, newId);return result;};return (@@ -420,14 +437,14 @@ export function OfferForm({ application, offer: initialOffer, onClose, onSaved }if (payload.success)void action.run(saveTerms, (result) => {if (getAccountScope() !== scope) return;+ if (result) rememberSavedOffer(scope, result.id, params.b);if (offer) {- if (result) router.setParams({ a: result.id, b: params.b, highlight: result.id });+ if (!active.current) return;showToast({ message: t`New offer version saved` });onClose();return;}- if (!application && result) router.setParams({ a: result.id, b: params.b, highlight: result.id });- if (result?.data.kind === "offer") onSaved?.({ id: result.id, data: result.data });+ if (active.current && result?.data.kind === "offer") onSaved?.({ id: result.id, data: result.data });const row = applications.data?.find((item) => item.id === payload.data.applicationId);const target = application ?? row;const status = application?.status ?? row?.status;@@ -440,7 +457,7 @@ export function OfferForm({ application, offer: initialOffer, onClose, onSaved }message: t`Offer saved. ${target.company} moved to Offer.`,});else showToast({ message: t`Offer saved` });- onClose();+ if (active.current) onClose();});}}/>diff --git a/apps/mobile/src/features/career/offer-selection.ts b/apps/mobile/src/features/career/offer-selection.tsnew file mode 100644index 000000000..780ffcaad--- /dev/null+++ b/apps/mobile/src/features/career/offer-selection.ts@@ -0,0 +1,17 @@+import { create } from "zustand/react";+import { getAccountScope } from "@/auth/session";++type SavedOffer = { id: string; b: string | undefined };++export const useSavedOffer = create<{ accounts: Record<string, SavedOffer | undefined> }>(() => ({ accounts: {} }));++/** A save can finish after Offers leaves the stack; apply its selection only when that account returns. */+export function rememberSavedOffer(scope: string, id: string, b: string | undefined) {+ if (getAccountScope() !== scope) return;+ useSavedOffer.setState((state) => ({ accounts: { ...state.accounts, [scope]: { id, b } } }));+}++export function consumeSavedOffer(scope: string, id: string) {+ if (getAccountScope() !== scope || useSavedOffer.getState().accounts[scope]?.id !== id) return;+ useSavedOffer.setState((state) => ({ accounts: { ...state.accounts, [scope]: undefined } }));+}diff --git a/apps/mobile/src/features/career/offers.tsx b/apps/mobile/src/features/career/offers.tsxindex 5bbd24585..76be4dffe 100644--- a/apps/mobile/src/features/career/offers.tsx+++ b/apps/mobile/src/features/career/offers.tsx@@ -3,7 +3,7 @@ import type { ApplicationSummary } from "@/features/applications/types";import type { CareerProfileData, OfferTerms } from "@reactive-resume/schema/career";import { plural, t } from "@lingui/core/macro";import { useLingui } from "@lingui/react/macro";-import { useLocalSearchParams, useRouter } from "expo-router";+import { useIsFocused, useLocalSearchParams, useRouter } from "expo-router";import { useEffect, useState } from "react";import { View } from "react-native";import { annualBaseHint, bonusAmount, selectOfferPair } from "@reactive-resume/schema/career-offer";@@ -12,8 +12,10 @@ import { useCareerQueries, useCareerTime, useNow, useOffers } from "./hooks";import { client } from "./hooks";import { formatBonus, formatMoney, matchingPlace, meetsMinimum, moneyDifference, sameTerms } from "./offer-compare";import { OfferEntry, OfferForm } from "./offer-entry";+import { consumeSavedOffer, useSavedOffer } from "./offer-selection";import { Actions, LoadState } from "./shared";import { withUndo } from "./undo";+import { getAccountScope } from "@/auth/session";import { useApplications } from "@/features/applications/queries";import { routes } from "@/routes";import { Banner, Button, Card, EmptyState, Screen, SelectSheet, Text, showToast, useTheme } from "@/ui";@@ -46,6 +48,21 @@ export function OffersScreen() {});};const params = useLocalSearchParams<{ a?: string; b?: string; highlight?: string }>();+ const focused = useIsFocused();+ const scope = getAccountScope();+ const saved = useSavedOffer((state) => (scope ? state.accounts[scope] : undefined));+ useEffect(() => {+ if (+ !focused ||+ !scope ||+ getAccountScope() !== scope ||+ !saved ||+ !query.data?.some((offer) => offer.id === saved.id)+ )+ return;+ router.setParams({ a: saved.id, b: params.b ?? saved.b, highlight: saved.id });+ consumeSavedOffer(scope, saved.id);+ }, [focused, scope, saved, query.data, params.b, router]);const setSelected = ([a, b]: (string | undefined)[]) => router.setParams({ a, b });const pair = selectOfferPair(offers, { a: params.a, b: params.b });const a = offers.find((row) => row.id === pair.a);diff --git a/apps/web/src/features/career/knowledge/knowledge.test.tsx b/apps/web/src/features/career/knowledge/knowledge.test.tsxindex 668fca818..e55777662 100644--- a/apps/web/src/features/career/knowledge/knowledge.test.tsx+++ b/apps/web/src/features/career/knowledge/knowledge.test.tsx@@ -76,6 +76,7 @@ vi.mock("@/libs/orpc/client", () => {});vi.mock("@tanstack/react-router", () => ({useNavigate: () => api.navigate,+ useRouter: () => ({ state: { location: { pathname: "/test" } } }),useSearch: () => ({}),useRouteContext: () => ({ session: { user: { id: api.userId } } }),Link: ({ children }: { children: ReactNode }) => <a href="#test-link">{children}</a>,diff --git a/apps/web/src/features/career/offer-entry.tsx b/apps/web/src/features/career/offer-entry.tsxindex 332c9c34c..fcc0a77d7 100644--- a/apps/web/src/features/career/offer-entry.tsx+++ b/apps/web/src/features/career/offer-entry.tsx@@ -10,8 +10,8 @@ import { t } from "@lingui/core/macro";import { Trans } from "@lingui/react/macro";import { ORPCError } from "@orpc/client";import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";-import { Link, useNavigate, useSearch } from "@tanstack/react-router";-import { useId, useState } from "react";+import { Link, useNavigate, useRouter, useSearch } from "@tanstack/react-router";+import { useId, useLayoutEffect, useRef, useState } from "react";import { offerTermsSchema } from "@reactive-resume/schema/career";import {bonusEntry,@@ -238,7 +238,17 @@ const zonedFields = (value: string, timeZone: string) => {export function OfferForm({ application, offer: initialOffer, onClose, onSaved }: OfferFormProps) {// Draft and expected terms belong to the same edit session, even when the comparison refetches.const [offer] = useState(initialOffer);+ const mounted = useRef(true);+ useLayoutEffect(() => {+ mounted.current = true;+ return () => {+ mounted.current = false;+ };+ }, []);const id = useId();+ const router = useRouter();+ const [pathname] = useState(() => router.state.location.pathname);+ const currentView = () => mounted.current && router.state.location.pathname === pathname;const navigate = useNavigate();const search = useSearch({ strict: false });const [owner] = useState(() => ({ id: getAccountId(), generation: getAccountGeneration() }));@@ -339,7 +349,7 @@ export function OfferForm({ application, offer: initialOffer, onClose, onSaved }onSuccess: (offer, input) => {if (!current()) return;if (offer) rememberOffer(offer);- if (!application && offer)+ if (!application && offer && currentView())void navigate({ to: "/dashboard/career/offers", search: { a: offer.id, b: search.b, highlight: offer.id } });const row = (applications.data ?? queryClient.getQueryData<ApplicationSummary[]>(applicationsListQueryKey())@@ -356,29 +366,29 @@ export function OfferForm({ application, offer: initialOffer, onClose, onSaved }} else {toast.add({ description: t`Offer saved` });}- onSaved?.(- offer?.data.kind === "offer"- ? { id: offer.id, data: offer.data, ...(target ? { application: { company: target.company } } : {}) }- : null,- );- if (!onSaved) onClose();+ if (currentView())+ onSaved?.(+ offer?.data.kind === "offer"+ ? { id: offer.id, data: offer.data, ...(target ? { application: { company: target.company } } : {}) }+ : null,+ );+ if (!onSaved && currentView()) onClose();},});const update = useMutation({...orpc.career.updateOffer.mutationOptions(),mutationFn: async (input: Parameters<typeof client.career.updateOffer>[0]) => {if (!current() || !owner.id) throw new Error("Account changed");- const key = JSON.stringify(["career:offer-version", owner.id, owner.generation, input]);- const result = await client.career.updateOffer(- { ...input, newId: pendingRequestId(key) },- { context: { accountId: owner.id } },- );- settleRequestId(key);+ const key = JSON.stringify(["career:offer-version", owner.id, input]);+ const newId = pendingRequestId(key, sessionStorage);+ const result = await client.career.updateOffer({ ...input, newId }, { context: { accountId: owner.id } });+ settleRequestId(key, sessionStorage, newId);return result;},onSuccess: (offer) => {if (!current()) return;rememberOffer(offer);+ if (!currentView()) return;void navigate({ to: "/dashboard/career/offers", search: { a: offer.id, b: search.b, highlight: offer.id } });toast.add({ description: t`New offer version saved` });onClose();diff --git a/docs/guides/comparing-job-offers.mdx b/docs/guides/comparing-job-offers.mdxindex 51832fef6..ece7f5984 100644--- a/docs/guides/comparing-job-offers.mdx+++ b/docs/guides/comparing-job-offers.mdx@@ -27,6 +27,8 @@ Repeat for the other application. A response deadline the employer states belongSaving terms records an offer; it does not accept it or reply to the employer.+If a save reports a connection problem, retrying the identical edit for that version recovers its saved result. After a reload or app restart, reopen the same version and re-enter those terms if needed; the form itself is not restored. Leaving while a save finishes keeps the page you opened. The saved version remains available in Offers; native Offers selects and highlights it when you return, keeping your comparison.+An application you moved to the **Offer** stage without saving terms appears in **Career → Offers** under **In the Offer stage, terms not added**, on web and in the native app. Each has its own **Add offer**, with the application already chosen. Nothing is compared, and no terms are filled in, until you enter them.Offers loads saved terms, preferences and application metadata separately. Saved offers and their comparison stay visible while application metadata loads or fails. The affected section shows an error with **Try again** on web or **Retry** in the native app. Retry reloads that account's data; an unavailable application list is never presented as an empty list or an AI setup step.diff --git a/packages/api/src/features/career/service.integration.test.ts b/packages/api/src/features/career/service.integration.test.tsindex bfacbef98..91ab93091 100644--- a/packages/api/src/features/career/service.integration.test.ts+++ b/packages/api/src/features/career/service.integration.test.ts@@ -1584,6 +1584,36 @@ describe.skipIf(!databaseUrl)("career knowledge, context and data lifecycle", ()await expect(service.updateOffer("alice", fit.id, terms, terms)).rejects.toMatchObject({ code: "NOT_FOUND" });});+ it("keeps a saved offer version when Undo removes the offer extracted by a reply", async () => {+ await applications.update({ userId: "alice", id: "alice-app", status: "applied" });+ const reply = await savedItem("alice-app", {+ kind: "reply",+ message: "An offer from Fictional Labs",+ title: "An offer",+ asks: [],+ unconfirmed: [],+ reply: "",+ changes: [{ type: "offer" }],+ offer: { currency: "EUR", period: "year", base: 90000, variable: null },+ });+ await service.applyReply("alice", reply.id, [0]);+ const [original] = await service.savedItems({ userId: "alice", applicationId: "alice-app", kind: "offer" });+ if (original?.data.kind !== "offer") throw new Error("Expected extracted offer");+ const expected = offerTermsSchema.parse(original.data);+ const version = await service.updateOffer(+ "alice",+ original.id,+ { ...expected, base: 95000 },+ expected,+ true,+ randomUUID(),+ );+ await service.undoReply("alice", reply.id);+ const remaining = await service.savedItems({ userId: "alice", applicationId: "alice-app", kind: "offer" });+ expect(remaining).toMatchObject([{ id: version.id, data: { base: 95000, origin: "message" } }]);+ expect(remaining.map((row) => row.id)).not.toContain(original.id);+ });+it("replays one receipted offer version without duplicating it or reviving a deleted version", async () => {const input = careerOfferInputSchema.parse({applicationId: "alice-app",@@ -1606,13 +1636,18 @@ describe.skipIf(!databaseUrl)("career knowledge, context and data lifecycle", ()service.updateOffer("alice", original.id, { ...terms, base: 1 }, expected, true, newId),).rejects.toMatchObject({ code: "CONFLICT" });await expect(service.updateOffer("bob", original.id, terms, expected, true, newId)).rejects.toMatchObject({+ code: "CONFLICT",+ });+ await expect(service.updateOffer("bob", original.id, terms, expected, true, randomUUID())).rejects.toMatchObject({code: "NOT_FOUND",});await service.updateOffer("alice", original.id, { ...expected, base: 86000 }, expected);expect((await save()).id).toBe(newId);+ await service.deleteSavedItem("alice", original.id);+ expect((await save()).id).toBe(newId);await service.deleteSavedItem("alice", newId);await expect(save()).rejects.toMatchObject({ code: "CONFLICT" });- expect(await service.savedItems({ userId: "alice", kind: "offer" })).toHaveLength(1);+ expect(await service.savedItems({ userId: "alice", kind: "offer" })).toHaveLength(0);});it("names the messages no longer sent after Knowledge changes, and replies that ended early", async () => {diff --git a/packages/api/src/features/career/service.ts b/packages/api/src/features/career/service.tsindex 305a1129b..56b0b007e 100644--- a/packages/api/src/features/career/service.ts+++ b/packages/api/src/features/career/service.ts@@ -1026,21 +1026,6 @@ export const careerService = {) =>db.transaction(async (tx) => {await lockUser(tx, userId);- const [row] = await tx- .select()- .from(tables.careerArtifact)- .where(- and(- eq(tables.careerArtifact.id, id),- and(- eq(tables.careerArtifact.userId, userId),- availableApplicationContext(userId, tables.careerArtifact.applicationId),- ),- ),- )- .for("update");- if (!row || row.data.kind !== "offer") throw new ORPCError("NOT_FOUND");- const { kind: _kind, origin, editedAt: _editedAt, ...current } = row.data;const nextTerms = { ...offerTermsSchema.parse(terms), variablePercent: terms.variablePercent ?? null };const expectedTerms = { ...offerTermsSchema.parse(expected), variablePercent: expected.variablePercent ?? null };const request = { kind: "offer-version", id, terms: nextTerms, expected: expectedTerms };@@ -1058,6 +1043,19 @@ export const careerService = {if (!version || version.data.kind !== "offer") throw new ORPCError("NOT_FOUND");return version;}+ const [row] = await tx+ .select()+ .from(tables.careerArtifact)+ .where(+ and(+ eq(tables.careerArtifact.id, id),+ eq(tables.careerArtifact.userId, userId),+ availableApplicationContext(userId, tables.careerArtifact.applicationId),+ ),+ )+ .for("update");+ if (!row || row.data.kind !== "offer") throw new ORPCError("NOT_FOUND");+ const { kind: _kind, origin, editedAt: _editedAt, ...current } = row.data;if (!isDeepStrictEqual({ ...offerTermsSchema.parse(current), variablePercent: current.variablePercent ?? null },diff --git a/packages/schema/src/career-offer.test.ts b/packages/schema/src/career-offer.test.tsindex 493cc1b3c..8281f67ff 100644--- a/packages/schema/src/career-offer.test.ts+++ b/packages/schema/src/career-offer.test.ts@@ -211,4 +211,5 @@ it("derives percentages only from their own base and round trips localized editiexpect(annualBaseHint(old, { ...yearly, currency: "USD" })).toBeNull();expect(annualBaseHint(old, { ...yearly, period: "hour" })).toBeNull();expect(annualBaseHint({ ...old, base: null }, yearly)).toBeNull();+ expect(annualBaseHint(yearly, yearly)).toBeNull();});diff --git a/packages/utils/src/amount.test.ts b/packages/utils/src/amount.test.tsindex 9e888a325..944bc4f99 100644--- a/packages/utils/src/amount.test.ts+++ b/packages/utils/src/amount.test.ts@@ -19,4 +19,6 @@ it("keeps monetary precision and safe bounds while accepting finite percentage dfor (const text of ["-1", "Infinity", "1e3", "1,23", "12."])expect(parseDecimal(text, "en-US"), text).toBeUndefined();expect(parseDecimal("9".repeat(400), "en-US")).toBeUndefined();+ expect(parseDecimal(`0.${"0".repeat(323)}1`, "en-US")).toBeUndefined();+ expect(parseDecimal(`0.${"0".repeat(323)}5`, "en-US")).toBe(Number.MIN_VALUE);});diff --git a/packages/utils/src/amount.ts b/packages/utils/src/amount.tsindex 8856c9ae4..b200f66ab 100644--- a/packages/utils/src/amount.ts+++ b/packages/utils/src/amount.ts@@ -23,6 +23,7 @@ function parseLocalizedNumber(input: string, locale: string, maximumFractionDigiif (whole !== normalized) return undefined;}const value = Number(`${ungrouped}.${fraction ?? "0"}`);+ if (value === 0 && /[1-9]/.test(`${ungrouped}${fraction ?? ""}`)) return undefined;return Number.isFinite(value) ? value : undefined;}diff --git a/packages/utils/src/string.test.ts b/packages/utils/src/string.test.tsindex 7045d5062..e5d97db3e 100644--- a/packages/utils/src/string.test.ts+++ b/packages/utils/src/string.test.ts@@ -2,6 +2,43 @@ import { describe, expect, it, vi } from "vite-plus/test";import { slugify } from "./slug";import { filterOptions, getInitials, isolate, rewriteSummary, toUsername } from "./string";+it("retains opaque pending request IDs across module restart until acknowledgement", async () => {+ const values = new Map<string, string>();+ const storage = {+ getItem: (key: string) => values.get(key) ?? null,+ setItem: (key: string, value: string) => {+ values.set(key, value);+ },+ removeItem: (key: string) => {+ values.delete(key);+ },+ };+ const key = JSON.stringify(["offer-version", "account-a", { id: "original", base: 90000 }]);+ const first = await import("./string");+ const id = first.pendingRequestId(key, storage);+ vi.resetModules();+ const restarted = await import("./string");+ expect(restarted.pendingRequestId(key, storage)).toBe(id);+ expect([...values.keys()].join()).not.toMatch(/account-a|original/);+ expect(restarted.pendingRequestId(key + "another-account", storage)).not.toBe(id);+ restarted.settleRequestId(key, storage, id);+ const next = restarted.pendingRequestId(key, storage);+ expect(next).not.toBe(id);+ restarted.settleRequestId(key, storage, id);+ expect(restarted.pendingRequestId(key, storage)).toBe(next);+ expect(() => restarted.pendingRequestId("corrupt", { ...storage, getItem: () => "invalid" })).toThrow(+ "Invalid pending request ID",+ );+ expect(() =>+ restarted.pendingRequestId("unwritable", {+ ...storage,+ setItem: () => {+ throw new Error("Disk full");+ },+ }),+ ).toThrow("Disk full");+});+describe("slugify", () => {it("falls back to a non-empty slug for CJK input", () => {expect(slugify("中文简历")).not.toBe("");diff --git a/packages/utils/src/string.ts b/packages/utils/src/string.tsindex dce5f0c21..d8d488c70 100644--- a/packages/utils/src/string.ts+++ b/packages/utils/src/string.ts@@ -1,4 +1,4 @@-import { v7 as uuidv7 } from "uuid";+import { validate as isUuid, v5 as uuidv5, v7 as uuidv7 } from "uuid";/*** Generates a unique ID using the UUIDv7 algorithm.@@ -10,22 +10,38 @@ export function generateId() {const pendingRequestIds = new Map<string, string>();+type RequestIdStorage = {+ getItem: (key: string) => string | null;+ setItem: (key: string, value: string) => void;+ removeItem: (key: string) => unknown;+};++// Persist only an opaque fingerprint and UUID, never the request's private fields.+const pendingRequestKey = (key: string) => `reactive-resume:pending-request:${uuidv5(key, uuidv5.URL)}`;+/*** The ID a create request sends, the same one each time until it succeeds: a retry after a lost response, a second* press or a remounted screen then returns what the first attempt saved instead of saving it again. `key` names the* request by what it saves, so changing the input starts a new one. Call `settleRequestId` once it has succeeded.*/-export function pendingRequestId(key: string) {- let id = pendingRequestIds.get(key);+export function pendingRequestId(key: string, storage?: RequestIdStorage) {+ const storageKey = storage ? pendingRequestKey(key) : key;+ let id = storage ? storage.getItem(storageKey) : pendingRequestIds.get(key);+ if (storage && id && !isUuid(id)) throw new Error("Invalid pending request ID");if (!id) {id = generateId();- pendingRequestIds.set(key, id);+ if (storage) storage.setItem(storageKey, id);+ else pendingRequestIds.set(key, id);}return id;}-export function settleRequestId(key: string) {- pendingRequestIds.delete(key);+export function settleRequestId(key: string, storage?: RequestIdStorage, expectedId?: string) {+ if (storage) {+ const storageKey = pendingRequestKey(key);+ if (expectedId !== undefined && storage.getItem(storageKey) !== expectedId) return;+ storage.removeItem(storageKey);+ } else pendingRequestIds.delete(key);}/**diff --git a/tests/e2e/specs/career-offer-accelerators.spec.ts b/tests/e2e/specs/career-offer-accelerators.spec.tsindex bf3886a29..0c099dcff 100644--- a/tests/e2e/specs/career-offer-accelerators.spec.ts+++ b/tests/e2e/specs/career-offer-accelerators.spec.ts@@ -70,6 +70,51 @@ test("saved offer opens side A, flashes, and preserves pinned side B", async ({await expect.poll(() => heading.evaluate((element) => element.getAnimations().length)).toBeGreaterThan(0);});+test("Delete commits when its Undo toast closes and stays deleted after reload", async ({ authPage: page }) => {+ const original = await offer(page, await application(page, "Northwind Labs"));+ await page.goto(`/dashboard/career/offers?a=${original.id}`);+ await page.getByRole("button", { name: /Northwind Labs.*Written offer/ }).click();+ await page.getByRole("menuitem", { name: "Delete offer", exact: true }).click();+ await expect(page.getByText("Offer deleted", { exact: true })).toBeVisible();+ await expect(page.getByText("Offer deleted", { exact: true })).toBeHidden({ timeout: 15000 });+ await expect.poll(() => offers(page)).toEqual([]);+ await page.reload();+ await expect(page.getByRole("heading", { name: "No offers to compare yet" })).toBeVisible();+});++test("a version save finishing after leaving the form keeps the destination route", async ({ authPage: page }) => {+ const original = await offer(page, await application(page, "Northwind Labs"));+ await page.goto(`/dashboard/career/offers?a=${original.id}`);+ await page.getByRole("button", { name: /Northwind Labs.*Written offer/ }).click();+ await page.getByRole("menuitem", { name: "Edit terms", exact: true }).click();+ await page.getByLabel("Base salary", { exact: true }).fill("90000");+ const arrived = Promise.withResolvers<void>();+ const release = Promise.withResolvers<void>();+ await page.route("**/api/rpc/career/updateOffer", async (route) => {+ const response = await route.fetch();+ expect(response.status()).toBe(200);+ arrived.resolve();+ await release.promise;+ await route.fulfill({ response });+ });+ try {+ const finished = page.waitForResponse((response) => response.url().includes("/career/updateOffer"));+ await page.getByRole("button", { name: "Save offer", exact: true }).click();+ await arrived.promise;+ await page.getByRole("tab", { name: "Knowledge", exact: true }).click();+ await expect(page).toHaveURL(/\/career\/knowledge/);+ release.resolve();+ await finished;+ await page.evaluate(+ () => new Promise<void>((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => resolve()))),+ );+ await expect(page).toHaveURL(/\/career\/knowledge/);+ expect((await offers(page)).map((row) => row.data.base).sort()).toEqual([85000, 90000]);+ } finally {+ release.resolve();+ }+});+test("percentage bonus persists as a percentage and reopens without becoming an amount", async ({authPage: page,}, info) => {@@ -112,7 +157,9 @@ test("a known monthly base still shows arithmetic against an unknown yearly baseawait expect(page.getByText("Different pay period, not compared", { exact: true })).toHaveCount(1);});-test("retrying a lost new-version response returns the single committed version", async ({ authPage: page }) => {+test("retrying a lost new-version response after reload returns the single committed version", async ({+ authPage: page,+}) => {const original = await offer(page, await application(page, "Northwind Labs"));await page.goto(`/dashboard/career/offers?a=${original.id}`);await page.getByRole("button", { name: /Northwind Labs.*Written offer/ }).click();@@ -130,6 +177,13 @@ test("retrying a lost new-version response returns the single committed version"await expect(page.getByText("Couldn't save the offer. Your draft is still here. Try again.")).toBeVisible();const committed = (await offers(page)).find((row) => row.id !== original.id);if (!committed) throw new Error("The discarded response must have committed a version.");+ await page.reload();+ await page+ .getByRole("button", { name: /Northwind Labs.*Written offer/ })+ .first()+ .click();+ await page.getByRole("menuitem", { name: "Edit terms", exact: true }).click();+ await page.getByLabel("Base salary", { exact: true }).fill("90000");await page.getByRole("button", { name: "Save offer", exact: true }).click();await expect(page.getByRole("heading", { name: "Edit offer terms", exact: true })).toHaveCount(0);await expect(page).toHaveURL(new RegExp(`a=${committed.id}`));