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: keep delivered reminders and fence cross-account autosave

Amruth Pillaidf077900d2fe
diff --git a/apps/web/src/libs/auth/account-scope.test.ts b/apps/web/src/libs/auth/account-scope.test.ts
new file mode 100644
index 000000000..ad57e5375
--- /dev/null
+++ b/apps/web/src/libs/auth/account-scope.test.ts
@@ -0,0 +1,55 @@
+// @vitest-environment happy-dom
+import { describe, expect, it, vi } from "vite-plus/test";
+import {
+ getAccountGeneration,
+ getAccountId,
+ invalidateAccountScope,
+ setAccountScope,
+ subscribeAccountChange,
+} from "./account-scope";
+
+describe("account scope", () => {
+ it("advances the generation only when the account actually changes", () => {
+ invalidateAccountScope();
+ setAccountScope("alice");
+ const first = getAccountGeneration();
+ expect(getAccountId()).toBe("alice");
+ setAccountScope("alice");
+ expect(getAccountGeneration()).toBe(first);
+ setAccountScope("bob");
+ expect(getAccountGeneration()).toBe(first + 1);
+ expect(getAccountId()).toBe("bob");
+ });
+
+ it("clears the account and fences queued work on sign-out", () => {
+ setAccountScope("alice");
+ const before = getAccountGeneration();
+ invalidateAccountScope();
+ expect(getAccountId()).toBeNull();
+ expect(getAccountGeneration()).toBe(before + 1);
+ });
+
+ it("fences this tab when another tab reports the account change", () => {
+ setAccountScope("alice");
+ const before = getAccountGeneration();
+ const listener = vi.fn();
+ const stop = subscribeAccountChange(listener);
+ const event = new Event("storage");
+ Object.defineProperty(event, "key", { value: "reactive-resume:account-change" });
+ window.dispatchEvent(event);
+ expect(listener).toHaveBeenCalledOnce();
+ expect(getAccountId()).toBeNull();
+ expect(getAccountGeneration()).toBe(before + 1);
+ stop();
+ });
+
+ it("ignores unrelated storage keys", () => {
+ const listener = vi.fn();
+ const stop = subscribeAccountChange(listener);
+ const event = new Event("storage");
+ Object.defineProperty(event, "key", { value: "theme" });
+ window.dispatchEvent(event);
+ expect(listener).not.toHaveBeenCalled();
+ stop();
+ });
+});
diff --git a/apps/web/src/libs/auth/account-scope.ts b/apps/web/src/libs/auth/account-scope.ts
new file mode 100644
index 000000000..2fd099401
--- /dev/null
+++ b/apps/web/src/libs/auth/account-scope.ts
@@ -0,0 +1,80 @@
+/**
+ * The account this tab's interface belongs to. Session loads update it, and every tab that signs out (or whose session
+ * is replaced) advances the generation so text typed for the old account can never be queued against the new one.
+ *
+ * Kept free of React and app imports: the RPC transport reads the id, and the account reset code advances the
+ * generation. Requests carry the id so the server can refuse a write dispatched after the cookie already changed.
+ */
+let accountId: string | null = null;
+let generation = 0;
+
+export const getAccountId = () => accountId;
+export const getAccountGeneration = () => generation;
+
+/** A session belonging to another account fences work queued for the previous one. */
+export function setAccountScope(id: string | null) {
+ if (id === accountId) return;
+ accountId = id;
+ generation += 1;
+}
+
+/** Sign-out and account deletion fence the old account even when the next session is also signed out. */
+export function invalidateAccountScope() {
+ accountId = null;
+ generation += 1;
+}
+
+type AccountChangeListener = () => void;
+
+const channelName = "reactive-resume:account";
+// Storage is the fallback signal for browsers without BroadcastChannel. The key is not account data and is never
+// removed by the reset below; each write carries a distinct value so listeners always see a change.
+const storageKey = "reactive-resume:account-change";
+const listeners = new Set<AccountChangeListener>();
+let channel: BroadcastChannel | null | undefined;
+
+function notify() {
+ invalidateAccountScope();
+ for (const listener of listeners) listener();
+}
+
+function ensureChannel() {
+ if (channel !== undefined) return channel;
+ channel = null;
+ try {
+ if (typeof BroadcastChannel !== "undefined") {
+ channel = new BroadcastChannel(channelName);
+ channel.addEventListener("message", notify);
+ }
+ } catch {
+ channel = null;
+ }
+ return channel;
+}
+
+/** Listens for a sign-out or account change made in another tab. Returns the unsubscribe function. */
+export function subscribeAccountChange(listener: AccountChangeListener) {
+ ensureChannel();
+ listeners.add(listener);
+ if (typeof window !== "undefined")
+ window.addEventListener("storage", (event) => {
+ if (event.key === storageKey) notify();
+ });
+ return () => {
+ listeners.delete(listener);
+ };
+}
+
+/** Tells other tabs that the signed-in account changed, so their queued saves stop before they reach the server. */
+export function broadcastAccountChange() {
+ try {
+ ensureChannel()?.postMessage({ at: Date.now() });
+ } catch {
+ // A closed or unavailable channel still leaves the storage signal.
+ }
+ try {
+ localStorage.setItem(storageKey, String(Date.now()));
+ } catch {
+ // Blocked browser storage must not prevent signing out.
+ }
+}
diff --git a/apps/web/src/libs/auth/clear-account-data.test.ts b/apps/web/src/libs/auth/clear-account-data.test.ts
index fa7e95899..b65f8f984 100644
--- a/apps/web/src/libs/auth/clear-account-data.test.ts
+++ b/apps/web/src/libs/auth/clear-account-data.test.ts
@@ -1,6 +1,7 @@
import { expect, it, vi } from "vite-plus/test";
// @vitest-environment happy-dom
import { QueryClient } from "@tanstack/react-query";
+import { getAccountGeneration, getAccountId, setAccountScope } from "./account-scope";
import { clearAccountData } from "./clear-account-data";
vi.mock("@/features/resume/builder/draft", () => ({ clearResumeDrafts: vi.fn() }));
@@ -28,3 +29,13 @@ it("removes contact snapshots, unsaved resumes, and career drafts from both brow
}
expect(queryClient.getQueryData(["resume"])).toBeUndefined();
});
+
+it("signing out fences saves queued for the old account and tells other tabs", () => {
+ setAccountScope("alice");
+ const generation = getAccountGeneration();
+ const queryClient = new QueryClient();
+ clearAccountData(queryClient);
+ expect(getAccountId()).toBeNull();
+ expect(getAccountGeneration()).toBe(generation + 1);
+ expect(localStorage.getItem("reactive-resume:account-change")).not.toBeNull();
+});
diff --git a/apps/web/src/libs/auth/clear-account-data.ts b/apps/web/src/libs/auth/clear-account-data.ts
index 89f00d236..7d8d7644f 100644
--- a/apps/web/src/libs/auth/clear-account-data.ts
+++ b/apps/web/src/libs/auth/clear-account-data.ts
@@ -1,15 +1,37 @@
import type { QueryClient } from "@tanstack/react-query";
+import { broadcastAccountChange, invalidateAccountScope, subscribeAccountChange } from "./account-scope";
import { useNewDocumentsStore } from "@/features/documents/new-documents";
import { clearStoredThumbnails } from "@/features/documents/thumbnail-store";
import { useLetterEditorStore } from "@/features/letters/store";
import { clearResumeDrafts } from "@/features/resume/builder/draft";
-let accountGeneration = 0;
-export const getAccountGeneration = () => accountGeneration;
+export { getAccountGeneration } from "./account-scope";
/** Forgets the account that just signed out or was deleted: cached queries, and thumbnails saved on this device. */
export function clearAccountData(queryClient: QueryClient) {
- accountGeneration += 1;
+ invalidateAccountScope();
+ forgetAccountState(queryClient);
+ broadcastAccountChange();
+ void clearStoredThumbnails();
+}
+
+/**
+ * Applies a sign-out or account change made in another tab. Every mounted form and queued save belongs to the old
+ * account, so this tab fences them and reloads into the session the browser now holds; nothing typed for the old
+ * account is shown or written under the new one.
+ */
+let syncing = false;
+export function syncAccountDataAcrossTabs(queryClient: QueryClient) {
+ if (syncing) return;
+ syncing = true;
+ return subscribeAccountChange(() => {
+ forgetAccountState(queryClient);
+ void clearStoredThumbnails();
+ window.location.reload();
+ });
+}
+
+function forgetAccountState(queryClient: QueryClient) {
clearResumeDrafts();
useLetterEditorStore.getState().reset();
queryClient.clear();
@@ -29,5 +51,4 @@ export function clearAccountData(queryClient: QueryClient) {
// Blocked browser storage must not prevent signing out.
}
}
- void clearStoredThumbnails();
}
diff --git a/apps/web/src/libs/orpc/fetch.test.ts b/apps/web/src/libs/orpc/fetch.test.ts
index 0526ec56d..59de41576 100644
--- a/apps/web/src/libs/orpc/fetch.test.ts
+++ b/apps/web/src/libs/orpc/fetch.test.ts
@@ -76,4 +76,13 @@ describe("RPC fetch", () => {
expect(Buffer.from(sent.body as ArrayBuffer).equals(Buffer.from(largeBody))).toBe(true);
}
});
+
+ it("sends the account the page was rendered for so a swapped session refuses its writes", async () => {
+ fetchMock.mockResolvedValue(new Response("ok"));
+ const { setAccountScope } = await import("@/libs/auth/account-scope");
+ const { rpcFetch } = await import("./fetch");
+ setAccountScope("alice");
+ await rpcFetch(rpcUrl, { method: "POST", body: "small draft" });
+ expect(new Headers(fetchMock.mock.calls[0]?.[1]?.headers).get("x-account-id")).toBe("alice");
+ });
});
diff --git a/apps/web/src/libs/orpc/fetch.ts b/apps/web/src/libs/orpc/fetch.ts
index 3f63c804e..b2cc66d0d 100644
--- a/apps/web/src/libs/orpc/fetch.ts
+++ b/apps/web/src/libs/orpc/fetch.ts
@@ -1,9 +1,14 @@
+import { getAccountId } from "@/libs/auth/account-scope";
+
let stagingUnavailable = false;
/** Large RPC bodies bypass the hosting ingress limit while retaining their original wire format. */
export async function rpcFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
const request = new Request(input, { ...init, credentials: "include" });
request.headers.set("x-client-timezone", Intl.DateTimeFormat().resolvedOptions().timeZone);
+ // The account this page was rendered for. The server refuses writes when the cookie now belongs to someone else.
+ const accountId = getAccountId();
+ if (accountId) request.headers.set("x-account-id", accountId);
if (request.method !== "POST") return fetch(request);
// Buffer as bytes: a teed stream needs duplex mode, and a Blob body is not visible to DevTools/CDP.
const body = await request.arrayBuffer();
diff --git a/apps/web/src/libs/root-context.ts b/apps/web/src/libs/root-context.ts
index d4bf409e1..862c5942a 100644
--- a/apps/web/src/libs/root-context.ts
+++ b/apps/web/src/libs/root-context.ts
@@ -1,5 +1,6 @@
import type { AuthSession } from "@reactive-resume/auth/types";
import type { QueryClient } from "@tanstack/react-query";
+import { setAccountScope } from "./auth/account-scope";
import { getSession } from "./auth/session";
import { getLocale, loadLocale } from "./locale";
import { client } from "./orpc/client";
@@ -36,6 +37,8 @@ export async function loadRootContext(queryClient: QueryClient) {
queryClient.query({ queryKey: flagsQueryKey, queryFn: () => client.flags.get(), staleTime: 5 * 60_000 }),
loadLocale(locale),
]);
+ // Whatever this tab now renders for belongs to this session; a different account fences queued autosaves.
+ setAccountScope(session?.user.id ?? null);
return { theme, locale, session, flags };
}
diff --git a/apps/web/src/router.tsx b/apps/web/src/router.tsx
index 12dd2d6ec..c2fa7b942 100644
--- a/apps/web/src/router.tsx
+++ b/apps/web/src/router.tsx
@@ -2,6 +2,7 @@ import { createRouter } from "@tanstack/react-router";
import { ErrorScreen } from "./components/layout/error-screen";
import { LoadingScreen } from "./components/layout/loading-screen";
import { NotFoundScreen } from "./components/layout/not-found-screen";
+import { syncAccountDataAcrossTabs } from "./libs/auth/clear-account-data";
import { orpc } from "./libs/orpc/client";
import { getQueryClient } from "./libs/query/client";
import { loadRootContext } from "./libs/root-context";
@@ -13,6 +14,7 @@ const supportsTransitionTypes = globalThis.CSS?.supports?.("selector(:active-vie
export const getRouter = async () => {
const queryClient = getQueryClient();
+ syncAccountDataAcrossTabs(queryClient);
const { theme, locale, session, flags } = await loadRootContext(queryClient);
diff --git a/migrations/20261031160926_rx106_follow_up_owner/migration.sql b/migrations/20261031160926_rx106_follow_up_owner/migration.sql
index 172c3bdb9..b8c476ccc 100644
--- a/migrations/20261031160926_rx106_follow_up_owner/migration.sql
+++ b/migrations/20261031160926_rx106_follow_up_owner/migration.sql
@@ -24,10 +24,26 @@ FROM career_schedule s JOIN application a ON a.id=s.application_id AND a.user_id
WHERE j.schedule_id=s.id AND s.kind='follow-up' AND j.status IN ('queued','running')
AND ((CASE WHEN a.follow_up_date_only THEN ((a.follow_up_at AT TIME ZONE 'UTC')::date + time '09:00') AT TIME ZONE s.timezone ELSE a.follow_up_at END) IS DISTINCT FROM s.next_run_at OR NOT s.enabled);
--> statement-breakpoint
-UPDATE career_schedule s SET next_run_at=CASE WHEN a.follow_up_date_only THEN ((a.follow_up_at AT TIME ZONE 'UTC')::date + time '09:00') AT TIME ZONE s.timezone ELSE a.follow_up_at END,query=COALESCE(a.follow_up_note,''),
-last_queued_at=CASE WHEN s.next_run_at=CASE WHEN a.follow_up_date_only THEN ((a.follow_up_at AT TIME ZONE 'UTC')::date + time '09:00') AT TIME ZONE s.timezone ELSE a.follow_up_at END THEN s.last_queued_at ELSE NULL END
-FROM application a WHERE s.application_id=a.id AND s.user_id=a.user_id AND s.kind='follow-up' AND a.follow_up_at IS NOT NULL
-AND NOT EXISTS(SELECT 1 FROM career_schedule newer WHERE newer.user_id=s.user_id AND newer.application_id=s.application_id AND newer.kind='follow-up' AND (newer.updated_at,newer.id)>(s.updated_at,s.id));
+-- Move the delivery index to the projected clock. A completed occurrence on the same logical day stays delivered: its
+-- watermark follows the projected instant, so the scheduler does not treat the new time as an undelivered occurrence.
+-- Completed history keeps its original due time; only pending queued/running work moves to the projected clock.
+WITH projected AS (
+ SELECT s.id,s.last_queued_at,s.next_run_at AS current_at,
+ CASE WHEN a.follow_up_date_only THEN ((a.follow_up_at AT TIME ZONE 'UTC')::date + time '09:00') AT TIME ZONE s.timezone ELSE a.follow_up_at END AS at,
+ COALESCE((SELECT j.status='completed' FROM career_job j WHERE j.schedule_id=s.id ORDER BY j.created_at DESC,j.id DESC LIMIT 1),false) AS completed,
+ a.follow_up_note
+ FROM career_schedule s JOIN application a ON a.id=s.application_id AND a.user_id=s.user_id
+ WHERE s.kind='follow-up' AND a.follow_up_at IS NOT NULL
+ AND NOT EXISTS(SELECT 1 FROM career_schedule newer WHERE newer.user_id=s.user_id AND newer.application_id=s.application_id AND newer.kind='follow-up' AND (newer.updated_at,newer.id)>(s.updated_at,s.id))
+)
+UPDATE career_schedule s SET next_run_at=p.at,query=COALESCE(p.follow_up_note,''),
+last_queued_at=CASE
+ WHEN p.at IS NOT DISTINCT FROM p.current_at THEN s.last_queued_at
+ WHEN s.last_queued_at IS NOT NULL AND p.completed
+ AND (p.at AT TIME ZONE s.timezone)::date=(s.last_queued_at AT TIME ZONE s.timezone)::date
+ THEN p.at
+ ELSE NULL END
+FROM projected p WHERE s.id=p.id;
--> statement-breakpoint
INSERT INTO career_schedule(id,user_id,application_id,kind,query,timezone,enabled,next_run_at)
SELECT 'follow-up:'||a.id,a.user_id,a.id,'follow-up',COALESCE(a.follow_up_note,''),u.timezone,true,CASE WHEN a.follow_up_date_only THEN ((a.follow_up_at AT TIME ZONE 'UTC')::date + time '09:00') AT TIME ZONE u.timezone ELSE a.follow_up_at END
diff --git a/packages/api/src/context.test.ts b/packages/api/src/context.test.ts
index 9565d94a4..097636c6c 100644
--- a/packages/api/src/context.test.ts
+++ b/packages/api/src/context.test.ts
@@ -1,3 +1,4 @@
+import type { RequestAuthentication } from "./context";
import { describe, expect, it, vi } from "vite-plus/test";
import { createProcedureClient } from "@orpc/server";
import { env } from "@reactive-resume/env/server";
@@ -206,3 +207,46 @@ describe("credential authorization", () => {
expect(authMock.api.getSession).not.toHaveBeenCalled();
});
});
+
+describe("account scope binding", () => {
+ const authentication = {
+ user: { id: "bob" },
+ method: "session" as const,
+ permissions: ["read", "write", "delete"] as const,
+ } as unknown as RequestAuthentication;
+ const operation = (
+ headers: Record<string, string>,
+ method: "GET" | "POST" | "DELETE",
+ handler = vi.fn(() => "executed"),
+ ) =>
+ createProcedureClient(protectedProcedure.route({ method }).handler(handler), {
+ context: { locale: "en-US" as const, reqHeaders: new Headers(headers), authentication },
+ });
+
+ it.each(["POST", "DELETE"] as const)(
+ "refuses a %s rendered for another account before the handler runs",
+ async (method) => {
+ reset();
+ const handler = vi.fn(() => "executed");
+ await expect(operation({ "x-account-id": "alice" }, method, handler)(undefined)).rejects.toMatchObject({
+ code: "CONFLICT",
+ });
+ expect(handler).not.toHaveBeenCalled();
+ },
+ );
+
+ it("accepts a write when the page's account matches the signed-in session", async () => {
+ reset();
+ await expect(operation({ "x-account-id": "bob" }, "POST")(undefined)).resolves.toBe("executed");
+ });
+
+ it("keeps clients that send no account scope working", async () => {
+ reset();
+ await expect(operation({}, "POST")(undefined)).resolves.toBe("executed");
+ });
+
+ it("still allows reads from a page that has not caught up with the new session", async () => {
+ reset();
+ await expect(operation({ "x-account-id": "alice" }, "GET")(undefined)).resolves.toBe("executed");
+ });
+});
diff --git a/packages/api/src/context.ts b/packages/api/src/context.ts
index 00d73031f..44f7e7bc3 100644
--- a/packages/api/src/context.ts
+++ b/packages/api/src/context.ts
@@ -147,6 +147,13 @@ export const protectedProcedure = publicProcedure
.use(({ context, procedure, next }) => {
if (!context.user) throw new ORPCError("UNAUTHORIZED");
const permission = requiredPermission(procedure["~orpc"].route);
+ // A page sends the account it was rendered for. If a cookie changed after that page loaded (another tab signed
+ // out or signed in), a queued autosave must fail instead of writing the old account's text into the new one.
+ const scope = context.reqHeaders.get("x-account-id");
+ if (scope && scope !== context.user.id && permission !== "read")
+ throw new ORPCError("CONFLICT", {
+ message: "This page belongs to a different account now. Reload and try again.",
+ });
if (!context.authentication?.permissions.includes(permission)) {
context.resHeaders?.set("WWW-Authenticate", `Bearer error="insufficient_scope", scope="api:${permission}"`);
throw new ORPCError("FORBIDDEN", {
diff --git a/packages/api/src/features/career/jobs.integration.test.ts b/packages/api/src/features/career/jobs.integration.test.ts
index e1c6238f9..842abeb6b 100644
--- a/packages/api/src/features/career/jobs.integration.test.ts
+++ b/packages/api/src/features/career/jobs.integration.test.ts
@@ -665,6 +665,204 @@ describe.skipIf(!databaseUrl)("durable career scheduling", () => {
);
});
+ // Stages the shipped migrations so the two follow-up migrations run against a populated pre-patch schema. Drizzle
+ // migrations are forward-only here, so the safety property to prove is repeatability and preservation, not a down
+ // migration: re-running the same backfills must leave the upgraded rows byte-for-byte unchanged.
+ it("upgrades completed legacy reminders without delivering them twice and moves pending work", async () => {
+ const isolated = `rx106_upgrade_${randomUUID().replaceAll("-", "")}`;
+ await admin.query(`CREATE SCHEMA ${isolated}`);
+ const upgrade = new Pool({
+ connectionString: databaseUrl,
+ max: 1,
+ options: `-c search_path=${isolated} -c statement_timeout=10000`,
+ });
+ const readSchedule = async () =>
+ (
+ await upgrade.query(
+ "SELECT id,next_run_at,last_queued_at,timezone,enabled,query FROM career_schedule ORDER BY id",
+ )
+ ).rows.map((row) => ({
+ id: row.id as string,
+ next: (row.next_run_at as Date).toISOString(),
+ queued: row.last_queued_at === null ? null : (row.last_queued_at as Date).toISOString(),
+ timezone: row.timezone as string,
+ enabled: row.enabled as boolean,
+ query: row.query as string,
+ }));
+ const readJobs = async () =>
+ (await upgrade.query("SELECT * FROM career_job ORDER BY due_at, id")).rows.map((row) => ({
+ id: row.id as string,
+ scheduleId: row.schedule_id as string,
+ dueAt: (row.due_at as Date).toISOString(),
+ status: row.status as string,
+ }));
+ const readNotifications = async () =>
+ (await upgrade.query("SELECT id,key,application_id FROM career_notification ORDER BY id")).rows.map((row) => ({
+ id: row.id as string,
+ key: row.key as string,
+ applicationId: row.application_id as string | null,
+ }));
+ try {
+ const migrations = new URL("../../../../../migrations/", import.meta.url);
+ const directories = (await readdir(migrations, { withFileTypes: true }))
+ .filter((entry) => entry.isDirectory() && /^\d+_/.test(entry.name))
+ .map((entry) => entry.name)
+ .sort();
+ const owner = "20261031160926_rx106_follow_up_owner";
+ const clock = "20261031174650_rx106_follow_up_clock";
+ const apply = async (name: string) => {
+ const file = new URL(`${name}/migration.sql`, migrations);
+ await upgrade.query((await readFile(file, "utf8")).replaceAll('"public".', ""));
+ };
+ for (const directory of directories) {
+ if (directory === owner) break;
+ await apply(directory);
+ }
+
+ // Valid pre-patch state: the exact-time reminder (08:00) and the date-only follow-up were independent
+ // surfaces. The 08:00 occurrence already ran; the pending reminder has not.
+ await upgrade.query(`
+ INSERT INTO "user"(id,name,email,username,display_username,timezone,email_verified)
+ VALUES('upgrade','Fictional Upgrade','[email protected]','upgrade','upgrade','UTC',true);
+ INSERT INTO application(id,user_id,company,role,status,follow_up_at,follow_up_note) VALUES
+ ('same-day','upgrade','Same Day Labs','Engineer','applied','2026-10-30T00:00:00Z','Already delivered'),
+ ('other-day','upgrade','Other Day Labs','Engineer','applied','2026-10-28T00:00:00Z','New logical day'),
+ ('pending','upgrade','Pending Labs','Engineer','applied','2026-10-30T00:00:00Z','Still pending');
+ INSERT INTO career_schedule(id,user_id,application_id,kind,query,timezone,enabled,next_run_at,last_queued_at) VALUES
+ ('same-day','upgrade','same-day','follow-up','Already delivered','UTC',true,'2026-10-30T08:00:00Z','2026-10-30T08:00:00Z'),
+ ('other-day','upgrade','other-day','follow-up','Earlier delivery','UTC',true,'2026-10-27T08:00:00Z','2026-10-27T08:00:00Z'),
+ ('pending','upgrade','pending','follow-up','Still pending','UTC',true,'2026-10-30T08:00:00Z','2026-10-30T08:00:00Z');
+ INSERT INTO career_job(id,user_id,schedule_id,due_at,status,attempts) VALUES
+ ('job-same-day','upgrade','same-day','2026-10-30T08:00:00Z','completed',1),
+ ('job-other-day','upgrade','other-day','2026-10-27T08:00:00Z','completed',1),
+ ('job-pending','upgrade','pending','2026-10-30T08:00:00Z','queued',0);
+ INSERT INTO career_notification(id,user_id,application_id,key,notice) VALUES
+ ('notice-same-day','upgrade','same-day','job-same-day','{"type":"followup","company":"Same Day Labs","role":"Engineer","note":"Already delivered"}'),
+ ('notice-other-day','upgrade','other-day','job-other-day','{"type":"followup","company":"Other Day Labs","role":"Engineer","note":"Earlier delivery"}');
+ `);
+
+ const preSchedules = await readSchedule();
+ const preJobs = await readJobs();
+ const preNotifications = await readNotifications();
+ expect(preSchedules).toEqual([
+ {
+ id: "other-day",
+ next: "2026-10-27T08:00:00.000Z",
+ queued: "2026-10-27T08:00:00.000Z",
+ timezone: "UTC",
+ enabled: true,
+ query: "Earlier delivery",
+ },
+ {
+ id: "pending",
+ next: "2026-10-30T08:00:00.000Z",
+ queued: "2026-10-30T08:00:00.000Z",
+ timezone: "UTC",
+ enabled: true,
+ query: "Still pending",
+ },
+ {
+ id: "same-day",
+ next: "2026-10-30T08:00:00.000Z",
+ queued: "2026-10-30T08:00:00.000Z",
+ timezone: "UTC",
+ enabled: true,
+ query: "Already delivered",
+ },
+ ]);
+ expect(preJobs).toEqual([
+ { id: "job-other-day", scheduleId: "other-day", dueAt: "2026-10-27T08:00:00.000Z", status: "completed" },
+ { id: "job-pending", scheduleId: "pending", dueAt: "2026-10-30T08:00:00.000Z", status: "queued" },
+ { id: "job-same-day", scheduleId: "same-day", dueAt: "2026-10-30T08:00:00.000Z", status: "completed" },
+ ]);
+ expect(preNotifications).toHaveLength(2);
+
+ await apply(owner);
+ await apply(clock);
+
+ const migrated = await readSchedule();
+ expect(migrated).toEqual([
+ {
+ id: "other-day",
+ next: "2026-10-28T09:00:00.000Z",
+ queued: null,
+ timezone: "UTC",
+ enabled: true,
+ query: "New logical day",
+ },
+ {
+ id: "pending",
+ next: "2026-10-30T09:00:00.000Z",
+ queued: null,
+ timezone: "UTC",
+ enabled: true,
+ query: "Still pending",
+ },
+ {
+ id: "same-day",
+ next: "2026-10-30T09:00:00.000Z",
+ queued: "2026-10-30T09:00:00.000Z",
+ timezone: "UTC",
+ enabled: true,
+ query: "Already delivered",
+ },
+ ]);
+ expect(await readJobs()).toEqual([
+ { id: "job-other-day", scheduleId: "other-day", dueAt: "2026-10-27T08:00:00.000Z", status: "completed" },
+ { id: "job-pending", scheduleId: "pending", dueAt: "2026-10-30T08:00:00.000Z", status: "canceled" },
+ { id: "job-same-day", scheduleId: "same-day", dueAt: "2026-10-30T08:00:00.000Z", status: "completed" },
+ ]);
+
+ const oldDb = fixture.db;
+ fixture.db = drizzle({ client: upgrade });
+ try {
+ // One worker serves one job per account per tick, so two due accounts need two ticks.
+ await run();
+ await run();
+ } finally {
+ fixture.db = oldDb;
+ }
+
+ const delivered = await readJobs();
+ expect(delivered.filter((row) => row.scheduleId === "same-day")).toEqual([
+ { id: "job-same-day", scheduleId: "same-day", dueAt: "2026-10-30T08:00:00.000Z", status: "completed" },
+ ]);
+ expect(delivered.filter((row) => row.scheduleId === "other-day")).toEqual([
+ { id: "job-other-day", scheduleId: "other-day", dueAt: "2026-10-27T08:00:00.000Z", status: "completed" },
+ { id: expect.any(String), scheduleId: "other-day", dueAt: "2026-10-28T09:00:00.000Z", status: "completed" },
+ ]);
+ expect(delivered.filter((row) => row.scheduleId === "pending")).toEqual([
+ { id: "job-pending", scheduleId: "pending", dueAt: "2026-10-30T08:00:00.000Z", status: "canceled" },
+ { id: expect.any(String), scheduleId: "pending", dueAt: "2026-10-30T09:00:00.000Z", status: "completed" },
+ ]);
+ const notifications = await readNotifications();
+ expect(notifications.filter((row) => row.key === "job-same-day")).toHaveLength(1);
+ expect(notifications).toHaveLength(4);
+
+ // Re-running the same forward-only backfills is safe: completed history, watermarks and deliveries hold.
+ const beforeRepeat = {
+ schedules: await readSchedule(),
+ jobs: await readJobs(),
+ notifications: await readNotifications(),
+ };
+ const ownerSql = await readFile(new URL(`${owner}/migration.sql`, migrations), "utf8");
+ await upgrade.query(
+ ownerSql.slice(ownerSql.indexOf("--> statement-breakpoint") + "--> statement-breakpoint".length),
+ );
+ await upgrade.query(
+ 'UPDATE "user" SET timezone=timezone WHERE EXISTS (SELECT 1 FROM application a WHERE a.user_id="user".id AND a.follow_up_date_only AND a.follow_up_at IS NOT NULL)',
+ );
+ expect({
+ schedules: await readSchedule(),
+ jobs: await readJobs(),
+ notifications: await readNotifications(),
+ }).toEqual(beforeRepeat);
+ } finally {
+ await upgrade.end();
+ await admin.query(`DROP SCHEMA IF EXISTS ${isolated} CASCADE`);
+ }
+ });
+
it("distinguishes old-client dates from exact midnight reminders and preserves notes-only timestamps", async () => {
const { applicationService } = await import("../applications/service");
await getDb().update(tables.user).set({ timezone: "Asia/Tokyo" }).where(eq(tables.user.id, "alice"));
diff --git a/tests/e2e/specs/rx106-review-regressions.spec.ts b/tests/e2e/specs/rx106-review-regressions.spec.ts
index 4c4a97ad7..2e4969844 100644
--- a/tests/e2e/specs/rx106-review-regressions.spec.ts
+++ b/tests/e2e/specs/rx106-review-regressions.spec.ts
@@ -451,3 +451,142 @@ test("exact 10 MiB PDF accepted and cap-plus-one rejected before transport", asy
contentType: "application/json",
});
});
+
+async function signUpSecondAccount(page: Page) {
+ const stamp = Date.now();
+ const email = `rx106-second-${stamp}@example.test`;
+ const username = `rx106s${stamp}`;
+ const response = await page.request.post("/api/auth/sign-up/email", {
+ headers: { origin: process.env.APP_URL ?? "" },
+ data: { name: "RX106 Second", email, password: "Review-Password-106!", username, displayUsername: username },
+ });
+ expect(response.ok(), await response.text()).toBe(true);
+ const { user } = (await response.json()) as { user: { id: string } };
+ return { email, id: user.id };
+}
+
+async function alicePreferences(page: Page) {
+ const initial = await (await page.request.get("/api/openapi/career/profile")).json();
+ const profile = { ...initial, targetRoles: ["Alice private role"], priorities: "Alice private priorities" };
+ expect((await page.request.put("/api/openapi/career/profile", { data: profile })).ok()).toBe(true);
+ return profile;
+}
+
+const profileRows = async (userId: string) =>
+ (await pool.query("SELECT user_id, data FROM career_profile WHERE user_id=$1", [userId])).rows;
+
+test("a sign-out in another tab closes the old account's open Preferences tab", async ({ authPage: page }, info) => {
+ const session = await (await page.request.get("/api/auth/get-session")).json();
+ const alice = session.user.id as string;
+ await alicePreferences(page);
+ await page.goto("/dashboard/career/knowledge/preferences");
+ await expect(page.getByLabel("What matters to you")).toHaveValue("Alice private priorities");
+
+ const other = await page.context().newPage();
+ let second: { email: string; id: string } | null = null;
+ try {
+ await other.goto("/dashboard/settings/account");
+ await other.getByRole("button", { name: "Sign out", exact: true }).last().click();
+ await expect(other).toHaveURL(/\/$/);
+ second = await signUpSecondAccount(other);
+ // This tab received the account change, fenced its queued saves and reloaded into the new session.
+ await expect(page.getByLabel("What matters to you")).toHaveCount(0);
+ const rows = await profileRows(second.id);
+ const [aliceRow] = await pool
+ .query("SELECT data FROM career_profile WHERE user_id=$1", [alice])
+ .then((r) => r.rows);
+ await info.attach("cross-tab-signout-readback", {
+ body: JSON.stringify({ alice, second: second.id, rows, aliceRow }, null, 2),
+ contentType: "application/json",
+ });
+ expect(rows).toEqual([]);
+ expect(aliceRow.data.targetRoles).toEqual(["Alice private role"]);
+ } finally {
+ await other.close();
+ if (second) await pool.query('DELETE FROM "user" WHERE email=$1', [second.email]);
+ }
+});
+
+test("a stale tab that missed the account change cannot autosave into the new account", async ({
+ authPage: page,
+}, info) => {
+ // A suspended tab never sees the cross-tab signal. Only the server-side account binding can stop its queued write.
+ await page.addInitScript(() => {
+ Reflect.deleteProperty(window, "BroadcastChannel");
+ const add = window.addEventListener.bind(window);
+ window.addEventListener = ((
+ type: string,
+ listener: EventListenerOrEventListenerObject,
+ options?: boolean | AddEventListenerOptions,
+ ) => {
+ if (type === "storage") return;
+ add(type, listener, options);
+ }) as typeof window.addEventListener;
+ });
+ const session = await (await page.request.get("/api/auth/get-session")).json();
+ const alice = session.user.id as string;
+ await alicePreferences(page);
+ await page.goto("/dashboard/career/knowledge/preferences");
+ await expect(page.getByLabel("What matters to you")).toHaveValue("Alice private priorities");
+
+ let rejected = 0;
+ page.on("response", (response) => {
+ if (response.url().includes("/api/rpc/") && response.status() === 409) rejected++;
+ });
+ const other = await page.context().newPage();
+ let second: { email: string; id: string } | null = null;
+ try {
+ await other.goto("/dashboard/settings/account");
+ await other.getByRole("button", { name: "Sign out", exact: true }).last().click();
+ await expect(other).toHaveURL(/\/$/);
+ second = await signUpSecondAccount(other);
+ // This tab still shows the old account because it never observed the sign-out.
+ await expect(page.getByLabel("What matters to you")).toHaveValue("Alice private priorities");
+ await page.getByLabel("What matters to you").fill("Stale Alice tab edit");
+ await page.getByLabel("What matters to you").blur();
+ await expect.poll(() => rejected).toBeGreaterThan(0);
+ const rows = await profileRows(second.id);
+ await info.attach("stale-tab-boundary-readback", {
+ body: JSON.stringify({ alice, second: second.id, rejected, rows }, null, 2),
+ contentType: "application/json",
+ });
+ expect(rejected).toBeGreaterThan(0);
+ expect(rows).toEqual([]);
+ } finally {
+ await other.close();
+ if (second) await pool.query('DELETE FROM "user" WHERE email=$1', [second.email]);
+ }
+});
+
+test("HTTP profile writes bound to another account are refused and leave the new account empty", async ({
+ authPage: page,
+}, info) => {
+ const session = await (await page.request.get("/api/auth/get-session")).json();
+ const alice = session.user.id as string;
+ const profile = await alicePreferences(page);
+ const second = await signUpSecondAccount(page);
+ try {
+ const stale = await page.request.put("/api/openapi/career/profile", {
+ headers: { "x-account-id": alice },
+ data: { ...profile, priorities: "Stale tab write" },
+ });
+ expect(stale.status()).toBe(409);
+ const before = await profileRows(second.id);
+ const matched = await page.request.put("/api/openapi/career/profile", {
+ headers: { "x-account-id": second.id },
+ data: { ...profile, priorities: "Second account write" },
+ });
+ expect(matched.ok(), await matched.text()).toBe(true);
+ const after = await profileRows(second.id);
+ await info.attach("http-account-binding-readback", {
+ body: JSON.stringify({ alice, second: second.id, staleStatus: stale.status(), before, after }, null, 2),
+ contentType: "application/json",
+ });
+ expect(before).toEqual([]);
+ expect(after).toHaveLength(1);
+ expect(after[0].user_id).toBe(second.id);
+ expect(after[0].data.priorities).toBe("Second account write");
+ } finally {
+ await pool.query('DELETE FROM "user" WHERE email=$1', [second.email]);
+ }
+});