Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(auth): send the user to login when the session expires (MUL-7028) (#7993)
Bohan Jiang7d339c186fa5
diff --git a/apps/desktop/src/renderer/src/App.tsx b/apps/desktop/src/renderer/src/App.tsxindex 4505cabd76..b0ea3461dc 100644--- a/apps/desktop/src/renderer/src/App.tsx+++ b/apps/desktop/src/renderer/src/App.tsx@@ -30,6 +30,11 @@ import { DesktopClientUsageReporter } from "./platform/client-usage-reporter";import { DiagnosticRouteReporter } from "./platform/diagnostic-route-reporter";import { flushFreezeBreadcrumb } from "./freeze-flush";import { DesktopAuthSessionBridge } from "./platform/auth-session-bridge";+import {+ tearDownOnLogout,+ tearDownOnSessionExpiry,+ type SessionTeardown,+} from "./platform/session-teardown";// BCP-47 region tags for the <html lang> attribute, mirroring// apps/web/app/layout.tsx HTML_LANG. index.html ships a static lang="en";@@ -350,30 +355,25 @@ function BlockingRuntimeConfigError({ message }: { message: string }) {);}-// On logout, wipe desktop-only in-memory state and stop the daemon so that-// a subsequent login as a different user never inherits the previous user's-// tabs, overlay, or credentials. Zustand persist only writes to localStorage;-// useLogout clears the storage key, but the live stores stay populated until-// we explicitly reset them here.-async function handleDaemonLogout() {- // Report synchronously before async daemon cleanup so a rapidly closed main- // window cannot leave authenticated issue renderers behind.- window.desktopAPI.reportAuthSession?.(null);- useTabStore.getState().reset();- useWindowOverlayStore.getState().close();- // Drop any post-onboarding welcome signal so user B logging in next- // doesn't inherit user A's pending modal state.- useWelcomeStore.getState().reset();- try {- await window.daemonAPI.clearToken();- } catch {- // Best-effort — clearing is followed by stop which also hardens state.- }- try {- await window.daemonAPI.stop();- } catch {- // Daemon may already be stopped.- }+// Binds the teardown steps to this renderer's real stores and IPC. Which of+// them each path runs — and why logout stops the daemon while an expiry+// leaves it running — lives in platform/session-teardown.+const sessionTeardown: SessionTeardown = {+ reportAuthSession: (userId) =>+ window.desktopAPI.reportAuthSession?.(userId),+ resetTabs: () => useTabStore.getState().reset(),+ closeOverlay: () => useWindowOverlayStore.getState().close(),+ resetWelcome: () => useWelcomeStore.getState().reset(),+ clearDaemonToken: () => window.daemonAPI.clearToken(),+ stopDaemon: () => window.daemonAPI.stop(),+};++function handleDaemonLogout() {+ return tearDownOnLogout(sessionTeardown);+}++function handleSessionExpired() {+ tearDownOnSessionExpiry(sessionTeardown);}export default function App() {@@ -461,6 +461,9 @@ export default function App() {onLogout={windowContext.kind === "main" ? handleDaemonLogout : undefined}+ onSessionExpired={+ windowContext.kind === "main" ? handleSessionExpired : undefined+ }identity={identity}locale={locale}resources={resources}diff --git a/apps/desktop/src/renderer/src/platform/session-teardown.test.ts b/apps/desktop/src/renderer/src/platform/session-teardown.test.tsnew file mode 100644index 0000000000..614a0ee2b8--- /dev/null+++ b/apps/desktop/src/renderer/src/platform/session-teardown.test.ts@@ -0,0 +1,87 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from "vitest";++import {+ tearDownOnLogout,+ tearDownOnSessionExpiry,+ type SessionTeardown,+} from "./session-teardown";++function makeTeardown(+ overrides: Partial<SessionTeardown> = {},+): SessionTeardown {+ return {+ reportAuthSession: vi.fn(),+ resetTabs: vi.fn(),+ closeOverlay: vi.fn(),+ resetWelcome: vi.fn(),+ clearDaemonToken: vi.fn(async () => {}),+ stopDaemon: vi.fn(async () => {}),+ ...overrides,+ };+}++beforeEach(() => {+ vi.clearAllMocks();+});++describe("tearDownOnLogout", () => {+ it("stops the daemon and wipes window state the next user must not inherit", async () => {+ const t = makeTeardown();+ await tearDownOnLogout(t);++ expect(t.reportAuthSession).toHaveBeenCalledWith(null);+ expect(t.resetTabs).toHaveBeenCalledOnce();+ expect(t.closeOverlay).toHaveBeenCalledOnce();+ expect(t.resetWelcome).toHaveBeenCalledOnce();+ expect(t.clearDaemonToken).toHaveBeenCalledOnce();+ expect(t.stopDaemon).toHaveBeenCalledOnce();+ });++ it("still stops the daemon when clearing its token fails", async () => {+ const t = makeTeardown({+ clearDaemonToken: vi.fn(async () => {+ throw new Error("profile locked");+ }),+ });++ await expect(tearDownOnLogout(t)).resolves.toBeUndefined();+ expect(t.stopDaemon).toHaveBeenCalledOnce();+ });++ it("survives a daemon that is already stopped", async () => {+ const t = makeTeardown({+ stopDaemon: vi.fn(async () => {+ throw new Error("not running");+ }),+ });++ await expect(tearDownOnLogout(t)).resolves.toBeUndefined();+ });+});++describe("tearDownOnSessionExpiry", () => {+ // The decision this file exists to protect: the daemon authenticates with+ // its own PAT and may be running agent work, so a UI credential expiring+ // must not take it down. Only this window has to sign in again (MUL-7028).+ it("leaves the daemon running", () => {+ const t = makeTeardown();+ tearDownOnSessionExpiry(t);++ expect(t.clearDaemonToken).not.toHaveBeenCalled();+ expect(t.stopDaemon).not.toHaveBeenCalled();+ });++ // Tab paths carry workspace slugs and issue ids. Leaving them for the+ // workspace validator to prune catches nothing when the next user shares a+ // workspace with the last one.+ it("clears window state the next user must not inherit", () => {+ const t = makeTeardown();+ tearDownOnSessionExpiry(t);++ expect(t.reportAuthSession).toHaveBeenCalledWith(null);+ expect(t.resetTabs).toHaveBeenCalledOnce();+ expect(t.closeOverlay).toHaveBeenCalledOnce();+ expect(t.resetWelcome).toHaveBeenCalledOnce();+ });+});diff --git a/apps/desktop/src/renderer/src/platform/session-teardown.ts b/apps/desktop/src/renderer/src/platform/session-teardown.tsnew file mode 100644index 0000000000..dc98b01b5c--- /dev/null+++ b/apps/desktop/src/renderer/src/platform/session-teardown.ts@@ -0,0 +1,79 @@+/**+ * What the end of a session tears down on Desktop — and what it deliberately+ * leaves alone.+ *+ * Two different events arrive here, and they differ in exactly one place. An+ * explicit logout is the user handing the machine back, so everything goes,+ * including the local daemon. A session the server ended (401) clears the same+ * window state — the login screen it lands on will take anyone's credentials —+ * but leaves the daemon alone: it holds its own PAT, minted separately from+ * this window's session token, and may be running agent work right now. An+ * expiring UI credential is no reason to kill it (MUL-7028).+ *+ * An account switch stays safe without the expiry path stopping anything,+ * because it is handled at the other end: `daemon:sync-token` mints a fresh+ * PAT and restarts the daemon whenever the user id changes.+ *+ * Side effects arrive as injected callbacks — the same shape as+ * `daemon-login-sync` — so the difference between the two paths is testable+ * without an Electron window.+ */+export interface SessionTeardown {+ /** Report the account transition to the main process. */+ reportAuthSession: (userId: string | null) => void;+ /** Desktop tab layout, which can name workspaces and issues. */+ resetTabs: () => void;+ /** Any pre-workspace overlay left open (invite, onboarding, …). */+ closeOverlay: () => void;+ /** The one-shot post-onboarding welcome signal. */+ resetWelcome: () => void;+ /** Credential the local daemon authenticates with. */+ clearDaemonToken: () => Promise<unknown>;+ /** The local daemon process itself. Resolves to an IPC result we ignore —+ * a daemon that was already down is success enough. */+ stopDaemon: () => Promise<unknown>;+}++/**+ * Explicit logout: wipe desktop-only in-memory state and stop the daemon, so a+ * subsequent login as a different user inherits none of the previous user's+ * tabs, overlay, or credentials. Zustand persist only writes to localStorage;+ * `useLogout` clears the storage key, but the live stores stay populated until+ * they are reset here.+ */+export async function tearDownOnLogout(t: SessionTeardown): Promise<void> {+ // Report synchronously before the async daemon cleanup, so a rapidly closed+ // main window cannot leave authenticated issue renderers behind.+ t.reportAuthSession(null);+ t.resetTabs();+ t.closeOverlay();+ t.resetWelcome();+ try {+ await t.clearDaemonToken();+ } catch {+ // Best-effort — clearing is followed by stop, which also hardens state.+ }+ try {+ await t.stopDaemon();+ } catch {+ // Daemon may already be stopped.+ }+}++/**+ * Session expiry: the same window teardown as a logout, because the screen it+ * lands on offers a login form and the next person to use it may not be the+ * one who was just signed in. Tabs go with it — their paths carry workspace+ * slugs and issue ids, and leaving them for the workspace validator to prune+ * catches nothing at all when the next user shares a workspace with the last.+ *+ * The daemon is the whole difference between the two paths, and the reason+ * this file exists: it authenticates with its own PAT and may be running agent+ * work, so a UI credential expiring must not take it down.+ */+export function tearDownOnSessionExpiry(t: SessionTeardown): void {+ t.reportAuthSession(null);+ t.resetTabs();+ t.closeOverlay();+ t.resetWelcome();+}diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.tsindex f26cdd244e..b8f197d669 100644--- a/packages/core/api/client.test.ts+++ b/packages/core/api/client.test.ts@@ -1,5 +1,7 @@import { afterEach, describe, expect, it, vi } from "vitest";+import { createAuthStore } from "../auth";import { configStore } from "../config";+import type { StorageAdapter, User } from "../types";import { ApiClient, ApiError, CHAT_DRAFT_RESTORE_CAPABILITY, clientErrorMessage } from "./client";import { EMPTY_PLUGIN_PACKAGE_LIST, EMPTY_PLUGIN_PREVIEW, EMPTY_PLUGIN_SURFACE_LAUNCH } from "./schemas";@@ -2627,3 +2629,59 @@ describe("clientErrorMessage", () => {expect(clientErrorMessage(undefined)).toBeUndefined();});});++// The wiring this exercises is the one CoreProvider installs: the client's+// 401 hook drives the auth store's session teardown. Before MUL-7028 the hook+// only dropped the stored token, so the shell stayed mounted with a live+// `user` and every following request came back "missing authorization" with+// no way for the user to get to the login page.+describe("ApiClient session expiry", () => {+ function makeStorage(+ initial: Record<string, string> = {},+ ): StorageAdapter {+ const values = { ...initial };+ return {+ getItem: (key) => values[key] ?? null,+ setItem: (key, value) => {+ values[key] = value;+ },+ removeItem: (key) => {+ delete values[key];+ },+ };+ }++ it("ends the session when the server rejects the credential mid-flight", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue(+ new Response(JSON.stringify({ error: "missing authorization" }), {+ status: 401,+ headers: { "Content-Type": "application/json" },+ }),+ ),+ );+ const storage = makeStorage({ multica_token: "live-token" });+ // The client is constructed before the store it notifies, exactly as+ // CoreProvider's initCore does; the hook only ever runs from a request.+ const session: { store?: ReturnType<typeof createAuthStore> } = {};+ const client = new ApiClient("https://api.example.test", {+ onUnauthorized: () => session.store?.getState().sessionExpired(),+ });+ const store = createAuthStore({ api: client, storage });+ session.store = store;+ store.setState({+ user: { id: "u1", email: "[email protected]" } as User,+ isLoading: false,+ status: "authenticated",+ });+ client.setToken("live-token");++ await expect(client.listProjects()).rejects.toBeInstanceOf(ApiError);++ expect(store.getState().user).toBeNull();+ expect(store.getState().status).toBe("unauthenticated");+ expect(store.getState().expired).toBe(true);+ expect(storage.getItem("multica_token")).toBeNull();+ });+});diff --git a/packages/core/auth/store.test.ts b/packages/core/auth/store.test.tsindex 3eaf6052a1..ae79dc5546 100644--- a/packages/core/auth/store.test.ts+++ b/packages/core/auth/store.test.ts@@ -59,5 +59,133 @@ describe("authStore", () => {expect(onLogout).toHaveBeenCalledOnce();expect(store.getState().user).toBeNull();expect(store.getState().status).toBe("unauthenticated");+ expect(store.getState().expired).toBe(false);+ });++ it("ends the session when the server rejects the credential", () => {+ const storage = makeStorage({ multica_token: "t" });+ const api = makeApi();+ const onLogout = vi.fn();+ const store = createAuthStore({ api, storage, onLogout });++ store.setState({ user: fakeUser, status: "authenticated", isLoading: false });+ store.getState().sessionExpired();++ expect(storage.snapshot().multica_token).toBeUndefined();+ expect(api.setToken).toHaveBeenCalledWith(null);+ expect(onLogout).toHaveBeenCalledOnce();+ expect(store.getState().user).toBeNull();+ expect(store.getState().isLoading).toBe(false);+ expect(store.getState().status).toBe("unauthenticated");+ expect(store.getState().expired).toBe(true);+ });++ // Desktop's deep link writes the token, then verifies it. A rejected token+ // never leaves "unauthenticated", so an idempotence guard placed before the+ // credential teardown would return with the invalid token still in storage,+ // to be replayed at the next launch. The old 401 handler always removed it.+ it("drops a rejected token even when there was no session to end", async () => {+ const storage = makeStorage();+ const api = {+ setToken: vi.fn(),+ getMe: vi.fn().mockRejectedValue(new Error("unauthorized")),+ } as unknown as ApiClient;+ const store = createAuthStore({ api, storage });+ store.setState({ user: null, status: "unauthenticated", isLoading: false });++ await expect(+ store.getState().loginWithToken("stale-deep-link-token"),+ ).rejects.toThrow();+ // Stands in for the api client's 401 hook, which fires inside getMe.+ store.getState().sessionExpired();++ expect(storage.snapshot().multica_token).toBeUndefined();+ expect(api.setToken).toHaveBeenLastCalledWith(null);+ });++ it("does not claim a session expired for a client that never had one", () => {+ const storage = makeStorage();+ const api = makeApi();+ const store = createAuthStore({ api, storage, cookieAuth: true });++ // Boot-time identity probe on a first visit: still "authenticating",+ // no stored credential.+ store.getState().sessionExpired();++ expect(store.getState().status).toBe("unauthenticated");+ expect(store.getState().expired).toBe(false);+ });++ it("flags expiry when a stored token is rejected at boot", () => {+ const storage = makeStorage({ multica_token: "stale" });+ const api = makeApi();+ const store = createAuthStore({ api, storage });++ store.getState().sessionExpired();++ expect(store.getState().expired).toBe(true);+ expect(storage.snapshot().multica_token).toBeUndefined();+ });++ it("runs the expiry handler instead of the logout one when given both", () => {+ const storage = makeStorage({ multica_token: "t" });+ const api = makeApi();+ const onLogout = vi.fn();+ const onSessionExpired = vi.fn();+ const store = createAuthStore({ api, storage, onLogout, onSessionExpired });++ store.setState({ user: fakeUser, status: "authenticated", isLoading: false });+ store.getState().sessionExpired();++ // Desktop's logout teardown stops the local daemon, which is the wrong+ // answer for a session the user did not choose to end (MUL-7028).+ expect(onSessionExpired).toHaveBeenCalledOnce();+ expect(onLogout).not.toHaveBeenCalled();+ });++ it("still runs the logout teardown for an explicit logout", () => {+ const storage = makeStorage({ multica_token: "t" });+ const api = makeApi();+ const onLogout = vi.fn();+ const onSessionExpired = vi.fn();+ const store = createAuthStore({ api, storage, onLogout, onSessionExpired });++ store.setState({ user: fakeUser, status: "authenticated", isLoading: false });+ store.getState().logout();++ expect(onLogout).toHaveBeenCalledOnce();+ expect(onSessionExpired).not.toHaveBeenCalled();+ });++ it("treats a burst of parallel 401s as the one expiry it is", () => {+ const storage = makeStorage({ multica_token: "t" });+ const api = makeApi();+ const onLogout = vi.fn();+ const store = createAuthStore({ api, storage, onLogout });++ store.setState({ user: fakeUser, status: "authenticated", isLoading: false });+ store.getState().sessionExpired();+ store.getState().sessionExpired();+ store.getState().sessionExpired();++ expect(onLogout).toHaveBeenCalledOnce();+ });++ it("clears the expired notice once the user signs back in", async () => {+ const storage = makeStorage();+ const api = {+ setToken: vi.fn(),+ getMe: vi.fn().mockResolvedValue(fakeUser),+ } as unknown as ApiClient;+ const store = createAuthStore({ api, storage });++ store.setState({ user: fakeUser, status: "authenticated", isLoading: false });+ store.getState().sessionExpired();+ expect(store.getState().expired).toBe(true);++ await store.getState().loginWithToken("fresh-token");++ expect(store.getState().status).toBe("authenticated");+ expect(store.getState().expired).toBe(false);});});diff --git a/packages/core/auth/store.ts b/packages/core/auth/store.tsindex 9e81d655c3..73917c9283 100644--- a/packages/core/auth/store.ts+++ b/packages/core/auth/store.ts@@ -9,6 +9,12 @@ export interface AuthStoreOptions {storage: StorageAdapter;onLogin?: () => void;onLogout?: () => void;+ /**+ * Cleanup for a session the server ended, as opposed to one the user did.+ * Defaults to `onLogout` — a shell only needs its own handler when some of+ * its logout teardown is too destructive for an expiry it did not ask for.+ */+ onSessionExpired?: () => void;/** When true, rely on HttpOnly cookies instead of localStorage for auth tokens. */cookieAuth?: boolean;}@@ -24,6 +30,13 @@ export interface AuthState {isLoading: boolean;status: AuthStatus;retryGeneration: number;+ /**+ * The last transition to `unauthenticated` was the server rejecting our+ * credential, not the user asking to leave. Purely presentational — the+ * login page uses it to say why the session ended. Cleared by any+ * successful login and by an explicit logout.+ */+ expired: boolean;retryAuthentication: () => void;sendCode: (email: string) => Promise<void>;@@ -31,18 +44,21 @@ export interface AuthState {loginWithGoogle: (code: string, redirectUri: string) => Promise<User>;loginWithToken: (token: string) => Promise<User>;logout: () => void;+ sessionExpired: () => void;setUser: (user: User) => void;refreshMe: () => Promise<void>;}export function createAuthStore(options: AuthStoreOptions) {- const { api, storage, onLogin, onLogout, cookieAuth } = options;+ const { api, storage, onLogin, onLogout, onSessionExpired, cookieAuth } =+ options;- return create<AuthState>((set) => ({+ return create<AuthState>((set, get) => ({user: null,isLoading: true,status: "authenticating",retryGeneration: 0,+ expired: false,retryAuthentication: () => {set((state) => ({@@ -65,7 +81,7 @@ export function createAuthStore(options: AuthStoreOptions) {}onLogin?.();identifyAnalytics(user.id, { email: user.email, name: user.name });- set({ user, isLoading: false, status: "authenticated" });+ set({ user, isLoading: false, status: "authenticated", expired: false });return user;},@@ -77,7 +93,7 @@ export function createAuthStore(options: AuthStoreOptions) {}onLogin?.();identifyAnalytics(user.id, { email: user.email, name: user.name });- set({ user, isLoading: false, status: "authenticated" });+ set({ user, isLoading: false, status: "authenticated", expired: false });return user;},@@ -87,7 +103,7 @@ export function createAuthStore(options: AuthStoreOptions) {const user = await api.getMe();onLogin?.();identifyAnalytics(user.id, { email: user.email, name: user.name });- set({ user, isLoading: false, status: "authenticated" });+ set({ user, isLoading: false, status: "authenticated", expired: false });return user;},@@ -101,16 +117,72 @@ export function createAuthStore(options: AuthStoreOptions) {setCurrentWorkspace(null, null);resetAnalytics();onLogout?.();- set({ user: null, isLoading: false, status: "unauthenticated" });+ set({+ user: null,+ isLoading: false,+ status: "unauthenticated",+ expired: false,+ });+ },++ /**+ * The server rejected our credential (401). Tears the session down to+ * exactly the state a cold boot with a dead token lands in, so the shell+ * unmounts and the app shows the login page instead of staying up while+ * every request fails with an auth error the user cannot act on+ * (MUL-7028).+ *+ * No server round-trip: the credential is already dead, and `/auth/logout`+ * would be one more request to answer a 401 with. Idempotent, because a+ * session dies once but a screen full of in-flight requests all learn+ * about it separately.+ */+ sessionExpired: () => {+ // "Expired" is a claim about the user's own history, so only make it+ // when this client really did present a credential the server then+ // rejected: a live session, or a stored token left by an earlier one.+ // A first visit to /login 401s on the identity probe too, and telling+ // that person their session expired would be a lie. Read before the+ // teardown below removes the evidence.+ const hadCredential =+ get().status === "authenticated" ||+ storage.getItem("multica_token") !== null;++ // Dropping the rejected credential happens before the idempotence+ // guard, and unconditionally. A login attempt that 401s never leaves+ // `unauthenticated` — Desktop's deep link writes the token, calls+ // getMe, and gets rejected — so a guard placed first would return with+ // that invalid token still sitting in storage, to be replayed at the+ // next launch. Nothing below this point is safe to repeat; this is.+ storage.removeItem("multica_token");+ api.setToken(null);++ // Past here we are ending a session, which happens once no matter how+ // many in-flight requests learn the credential is dead — and does not+ // happen at all when there was no session to end.+ if (get().status === "unauthenticated") return;++ // Cookie mode leaves the workspace singleton alone: there the URL owns+ // workspace identity and the login route overwrites it on the next+ // entry. Mirrors AuthInitializer's boot-time rejection.+ if (!cookieAuth) setCurrentWorkspace(null, null);+ resetAnalytics();+ (onSessionExpired ?? onLogout)?.();+ set({+ user: null,+ isLoading: false,+ status: "unauthenticated",+ expired: hadCredential,+ });},setUser: (user: User) => {- set({ user, isLoading: false, status: "authenticated" });+ set({ user, isLoading: false, status: "authenticated", expired: false });},refreshMe: async () => {const user = await api.getMe();- set({ user, isLoading: false, status: "authenticated" });+ set({ user, isLoading: false, status: "authenticated", expired: false });},}));}diff --git a/packages/core/drafts/cleanup-registry.ts b/packages/core/drafts/cleanup-registry.tsindex dad86cb812..74b7584f5c 100644--- a/packages/core/drafts/cleanup-registry.ts+++ b/packages/core/drafts/cleanup-registry.ts@@ -77,6 +77,24 @@ export function resetAllRegisteredDrafts(): void {}}+/**+ * Persist keys of every registered draft store, split by how they are+ * namespaced. Used to sweep drafts for workspaces whose slugs this process+ * never learned — a cold start that is rejected at the identity probe has no+ * workspace list to enumerate.+ */+export function registeredDraftKeys(): {+ workspaceScoped: string[];+ global: string[];+} {+ const workspaceScoped: string[] = [];+ const global: string[] = [];+ for (const entry of entries.values()) {+ (entry.workspaceScoped ? workspaceScoped : global).push(entry.storageKey);+ }+ return { workspaceScoped, global };+}+/** Test-only: drop all registrations. */export function __clearDraftCleanupRegistryForTest(): void {entries.clear();diff --git a/packages/core/platform/auth-initializer.test.tsx b/packages/core/platform/auth-initializer.test.tsxindex 4ee9a4dea0..b63d7b020a 100644--- a/packages/core/platform/auth-initializer.test.tsx+++ b/packages/core/platform/auth-initializer.test.tsx@@ -13,6 +13,10 @@ import {} from "../auth";import type { StorageAdapter, User, Workspace } from "../types";import { workspaceKeys } from "../workspace/queries";+import {+ registerDraftCleanup,+ __clearDraftCleanupRegistryForTest,+} from "../drafts/cleanup-registry";import { AuthInitializer } from "./auth-initializer";const logger = vi.hoisted(() => ({@@ -55,6 +59,7 @@ function makeStorage(initial: Record<string, string> = {}): StorageAdapter & {removeItem: (key) => {delete values[key];},+ keys: () => Object.keys(values),snapshot: () => ({ ...values }),};}@@ -96,7 +101,6 @@ function renderInitializer({cookieAuth={cookieAuth}identity={{ platform }}onLogin={onLogin}- onLogout={onLogout}storage={storage}><div>child</div>@@ -109,6 +113,7 @@ function renderInitializer({beforeEach(() => {vi.clearAllMocks();+ __clearDraftCleanupRegistryForTest();});afterEach(() => {@@ -271,6 +276,117 @@ describe("AuthInitializer recovery", () => {expect(getConfig).toHaveBeenCalledTimes(3);});+ // A → 401 → B, where B shares a workspace with A so the post-login stale-tab+ // validator prunes nothing. B must find none of A's client state. What+ // exactly gets cleared is pinned in platform/session-cleanup.test.ts; this+ // asserts the 401 is wired to it at all.+ it("erases the previous user's client state when a live session is rejected", async () => {+ const shared = "acme";+ const storage = makeStorage({+ multica_token: "token-1",+ "multica_comment_drafts:acme": '{"issue-1":"A private draft"}',+ multica_tabs: '[{"path":"/acme/issues/secret"}]',+ });+ const resetInMemory = vi.fn();+ registerDraftCleanup({+ storageKey: "multica_comment_drafts",+ workspaceScoped: true,+ resetInMemory,+ });+ const api = makeApi({+ listWorkspaces: vi+ .fn()+ .mockResolvedValue([{ id: "ws-1", slug: shared }] as Workspace[]),+ });+ const { queryClient } = renderInitializer({ api, storage });++ await waitFor(() => {+ expect(useAuthStore.getState().status).toBe("authenticated");+ });+ await waitFor(() => {+ expect(queryClient.getQueryData(workspaceKeys.list())).toHaveLength(1);+ });+ queryClient.setQueryData(["issues", "ws-1"], [{ id: "i-1" }]);++ act(() => {+ useAuthStore.getState().sessionExpired();+ });++ await waitFor(() => {+ expect(queryClient.getQueryData(["issues", "ws-1"])).toBeUndefined();+ });+ expect(storage.snapshot()).toEqual({});+ expect(resetInMemory).toHaveBeenCalled();+ expect(useAuthStore.getState().expired).toBe(true);+ });++ // Elon's cold-start repro: A closes the app, the token expires while it is+ // shut, and the next launch is rejected at the identity probe. This never+ // passes through `authenticated`, and there is no workspace list to+ // enumerate slugs from — so both the trigger and the sweep have to work+ // without either.+ // The failure mode that must never happen: a laptop with no connectivity+ // gets signed out and asked for credentials it cannot verify. Only a 401+ // ends a session — everything else waits.+ it.each([+ ["offline", new TypeError("fetch failed")],+ ["server error", new ApiError("boom", 500, "Internal Server Error")],+ ["gateway timeout", new ApiError("slow", 504, "Gateway Timeout")],+ ])("keeps the session and every draft when getMe fails: %s", async (_label, error) => {+ const before = {+ multica_token: "token-1",+ "multica_comment_drafts:acme": '{"issue-1":"unsent work"}',+ multica_tabs: '[{"path":"/acme/issues/1"}]',+ };+ const storage = makeStorage(before);+ const resetInMemory = vi.fn();+ registerDraftCleanup({+ storageKey: "multica_comment_drafts",+ workspaceScoped: true,+ resetInMemory,+ });+ const api = makeApi({ getMe: vi.fn().mockRejectedValue(error) });+ renderInitializer({ api, storage });++ await waitFor(() => {+ expect(useAuthStore.getState().status).toBe("recovering");+ });++ expect(useAuthStore.getState().status).not.toBe("unauthenticated");+ expect(storage.snapshot()).toEqual(before);+ expect(resetInMemory).not.toHaveBeenCalled();+ });++ it("erases the previous session on a cold start with a stale token", async () => {+ const storage = makeStorage({+ multica_token: "stale-token",+ "multica_comment_drafts:acme": '{"issue-1":"A private draft"}',+ "multica:chat:activeSessionId:acme": "session-1",+ multica_tabs: '[{"path":"/acme/issues/secret"}]',+ multica_locale: "zh-Hans",+ });+ registerDraftCleanup({+ storageKey: "multica_comment_drafts",+ workspaceScoped: true,+ resetInMemory: vi.fn(),+ });+ const api = makeApi({+ getMe: vi+ .fn()+ .mockRejectedValue(new ApiError("unauthorized", 401, "Unauthorized")),+ });+ const { queryClient } = renderInitializer({ api, storage });++ await waitFor(() => {+ expect(useAuthStore.getState().status).toBe("unauthenticated");+ });+ await waitFor(() => {+ // Only the device preference survives.+ expect(storage.snapshot()).toEqual({ multica_locale: "zh-Hans" });+ });+ expect(queryClient.getQueryData(workspaceKeys.list())).toBeUndefined();+ });+it("publishes a definitive logout for a genuine 401", async () => {const storage = makeStorage({ multica_token: "token-1" });const getMe = vi.fn().mockImplementation(() => {diff --git a/packages/core/platform/auth-initializer.tsx b/packages/core/platform/auth-initializer.tsxindex dbc4da583d..7efdc1681a 100644--- a/packages/core/platform/auth-initializer.tsx+++ b/packages/core/platform/auth-initializer.tsx@@ -9,13 +9,12 @@ import {captureSignupSource,identify as identifyAnalytics,initAnalytics,- resetAnalytics,} from "../analytics";import { configStore } from "../config";import { workspaceListOptions } from "../workspace/queries";import { createLogger } from "../logger";+import { clearClientSessionData } from "./session-cleanup";import { defaultStorage } from "./storage";-import { setCurrentWorkspace } from "./workspace-storage";import type { ClientIdentity } from "./types";import type { StorageAdapter } from "../types/storage";import type { User } from "../types";@@ -33,14 +32,15 @@ const RECOVERY_RETRY_DELAYS_MS = [export function AuthInitializer({children,onLogin,- onLogout,storage = defaultStorage,cookieAuth,identity,}: {children: ReactNode;onLogin?: () => void;- onLogout?: () => void;+ // No `onLogout`: every unauthenticated exit below delegates to the auth+ // store's own teardown, which is where the logout / session-expiry+ // callbacks live.storage?: StorageAdapter;cookieAuth?: boolean;identity?: ClientIdentity;@@ -205,6 +205,7 @@ export function AuthInitializer({user,isLoading: false,status: "authenticated",+ expired: false,});identifyAnalytics(user.id, { email: user.email, name: user.name });if (authRecoveryPendingRef.current) {@@ -215,24 +216,14 @@ export function AuthInitializer({}};- const onAuthFailure = () => {- onLogout?.();- resetAnalytics();- useAuthStore.setState({- user: null,- isLoading: false,- status: "unauthenticated",- });- };-const rejectSession = () => {settled = true;window.removeEventListener("online", retryNow);if (retryTimer !== undefined) clearTimeout(retryTimer);- if (!cookieAuth) {- setCurrentWorkspace(null, null);- }- onAuthFailure();+ // One teardown for every dead session, whether it died at boot or+ // under a running shell. The api client's 401 hook has normally run+ // this already by the time we get here; the action is idempotent.+ useAuthStore.getState().sessionExpired();};const scheduleRetry = (attempt: () => Promise<void>) => {@@ -324,13 +315,12 @@ export function AuthInitializer({if (!cookieAuth) {const token = storage.getItem("multica_token");if (!token) {+ // No credential to verify. Same published state as a rejected one,+ // and the same teardown — which on desktop is what keeps a daemon+ // running across the restart after an expiry, instead of the app+ // treating a missing token as if the user had signed out.settled = true;- onLogout?.();- useAuthStore.setState({- user: null,- isLoading: false,- status: "unauthenticated",- });+ useAuthStore.getState().sessionExpired();} else {api.setToken(token);window.addEventListener("online", retryNow);@@ -349,5 +339,41 @@ export function AuthInitializer({// eslint-disable-next-line react-hooks/exhaustive-deps}, [retryGeneration]);+ // A session that ends leaves its whole client side behind: a warmed query+ // cache whose every entry has `staleTime: Infinity`, per-workspace drafts+ // and chat selection, the desktop tab layout. The screen it lands on offers+ // a login form, and the next person to use it is not guaranteed to be the+ // one who was just signed in — on a shared machine a colleague would inherit+ // all of it, and sharing a workspace with them means the tab validator finds+ // nothing to drop. So an expiry erases exactly what a logout erases; only+ // the auth teardown differs (the auth store's `sessionExpired`), plus what+ // belongs to a process outliving the session — Desktop's daemon.+ //+ // Keyed on being unauthenticated rather than on a transition out of+ // `authenticated`, because the case that leaks worst never passes through+ // `authenticated` at all: the app starts, the stale token on disk is+ // rejected at the identity probe, and the previous session's drafts sit+ // there waiting for whoever signs in next.+ //+ // This cannot sign anyone out. Reaching `unauthenticated` IS the decision to+ // end the session, and only two things reach it: a 401 on a credential we+ // presented, or having no credential at all. A client that cannot reach the+ // server — offline, DNS down, 5xx — settles on `recovering` and keeps both+ // its token and everything below (see `attempt`'s catch, which narrows to+ // `ApiError` with status 401 before rejecting anything).+ const authStatus = useAuthStore((state) => state.status);+ const clearedForThisSession = useRef(false);+ useEffect(() => {+ if (authStatus === "authenticated") {+ clearedForThisSession.current = false;+ return;+ }+ if (authStatus !== "unauthenticated" || clearedForThisSession.current) {+ return;+ }+ clearedForThisSession.current = true;+ clearClientSessionData(qc, storage);+ }, [authStatus, qc, storage]);+return <>{children}</>;}diff --git a/packages/core/platform/core-provider.tsx b/packages/core/platform/core-provider.tsxindex 33cc194dc5..b7b80f1419 100644--- a/packages/core/platform/core-provider.tsx+++ b/packages/core/platform/core-provider.tsx@@ -29,14 +29,28 @@ import {let initialized = false;let authStore: ReturnType<typeof createAuthStore>;let chatStore: ReturnType<typeof createChatStore>;-function initCore(- apiBaseUrl: string,- storage: StorageAdapter,- onLogin?: () => void,- onLogout?: () => void,- cookieAuth?: boolean,- identity?: ClientIdentity,-) {+// Named rather than positional: onLogin / onLogout / onSessionExpired are+// three adjacent `() => void`, and nothing but the argument order would tell+// them apart at the call site.+interface InitCoreOptions {+ apiBaseUrl: string;+ storage: StorageAdapter;+ onLogin?: () => void;+ onLogout?: () => void;+ onSessionExpired?: () => void;+ cookieAuth?: boolean;+ identity?: ClientIdentity;+}++function initCore({+ apiBaseUrl,+ storage,+ onLogin,+ onLogout,+ onSessionExpired,+ cookieAuth,+ identity,+}: InitCoreOptions) {if (initialized) return;configureShortcutPlatform(@@ -55,8 +69,17 @@ function initCore(const api = new ApiClient(apiBaseUrl, {logger: createLogger("api"),+ // A 401 mid-session has to end the session, not just drop the token.+ // Dropping it alone left the shell mounted with `user` still set, so no+ // shell ever showed the login page and every following request went out+ // unauthenticated — the user got a wall of "missing authorization"+ // toasts with no way forward (MUL-7028). The store action is idempotent,+ // so a screenful of parallel 401s is still one expiry.+ //+ // `authStore` is assigned a few lines below, synchronously, and this+ // callback can only run from a request — never before boot finishes.onUnauthorized: () => {- storage.removeItem("multica_token");+ authStore.getState().sessionExpired();},identity,});@@ -73,7 +96,14 @@ function initCore(// client reads the slug from that singleton for the X-Workspace-Slug// header. No boot-time hydration from storage is required.- authStore = createAuthStore({ api, storage, onLogin, onLogout, cookieAuth });+ authStore = createAuthStore({+ api,+ storage,+ onLogin,+ onLogout,+ onSessionExpired,+ cookieAuth,+ });registerAuthStore(authStore);chatStore = createChatStore({ storage });@@ -90,6 +120,7 @@ export function CoreProvider({cookieAuth,onLogin,onLogout,+ onSessionExpired,identity,locale,resources,@@ -99,7 +130,19 @@ export function CoreProvider({// Initialize singletons on first render only. Dependencies are read-once:// apiBaseUrl, storage, and callbacks are set at app boot and never change at runtime.// eslint-disable-next-line react-hooks/exhaustive-deps- useMemo(() => initCore(apiBaseUrl, storage, onLogin, onLogout, cookieAuth, identity), []);+ useMemo(+ () =>+ initCore({+ apiBaseUrl,+ storage,+ onLogin,+ onLogout,+ onSessionExpired,+ cookieAuth,+ identity,+ }),+ [],+ );// Client-only freeze watchdog — shared by web and desktop. No-op on the// server and idempotent, so mounting it here covers both apps in one place.@@ -114,7 +157,6 @@ export function CoreProvider({<QueryProvider><AuthInitializeronLogin={onLogin}- onLogout={onLogout}storage={storage}cookieAuth={cookieAuth}identity={identity}diff --git a/packages/core/platform/index.ts b/packages/core/platform/index.tsindex ed68bfba00..aa82232cd8 100644--- a/packages/core/platform/index.ts+++ b/packages/core/platform/index.ts@@ -5,6 +5,7 @@ export { defaultStorage } from "./storage";export { createPersistStorage } from "./persist-storage";export { createWorkspaceAwareStorage, setCurrentWorkspace, getCurrentSlug, getCurrentWsId, subscribeToCurrentSlug, registerForWorkspaceRehydration } from "./workspace-storage";export { clearWorkspaceStorage } from "./storage-cleanup";+export { clearClientSessionData } from "./session-cleanup";export {registerSystemNotificationClickHandler,isWebNotificationSupported,diff --git a/packages/core/platform/session-cleanup.test.ts b/packages/core/platform/session-cleanup.test.tsnew file mode 100644index 0000000000..d14ac6565e--- /dev/null+++ b/packages/core/platform/session-cleanup.test.ts@@ -0,0 +1,145 @@+/**+ * @vitest-environment jsdom+ */+// jsdom rather than node: the cleanup writes an expiring `document.cookie`,+// and under node it would take the `typeof document === "undefined"` branch+// and pass without ever exercising that line.+import { QueryClient } from "@tanstack/react-query";+import { beforeEach, describe, expect, it, vi } from "vitest";+import {+ registerDraftCleanup,+ __clearDraftCleanupRegistryForTest,+} from "../drafts/cleanup-registry";+import type { StorageAdapter, Workspace } from "../types";+import { workspaceKeys } from "../workspace/queries";+import { clearClientSessionData } from "./session-cleanup";++function makeStorage(+ initial: Record<string, string> = {},+): StorageAdapter & { snapshot: () => Record<string, string> } {+ const values = { ...initial };+ return {+ getItem: (key) => values[key] ?? null,+ setItem: (key, value) => {+ values[key] = value;+ },+ removeItem: (key) => {+ delete values[key];+ },+ keys: () => Object.keys(values),+ snapshot: () => ({ ...values }),+ };+}++beforeEach(() => {+ __clearDraftCleanupRegistryForTest();+ document.cookie = "last_workspace_slug=acme; path=/";+});++describe("clearClientSessionData", () => {+ // The scenario this exists for: user A's session dies, the login form the+ // expiry lands on is used by B, and A and B share a workspace — so the+ // stale-tab validator that runs after login finds nothing to prune and+ // every one of these keys would otherwise still be A's.+ it("leaves nothing of the previous session for the next user to find", () => {+ const shared = "acme";+ const storage = makeStorage({+ // A workspace-scoped draft, through the registry.+ "multica_comment_drafts:acme": '{"issue-1":"A private draft"}',+ // A non-draft workspace-scoped key.+ "multica:chat:activeSessionId:acme": "session-1",+ // Desktop tab layout, whose paths carry slugs and issue ids.+ multica_tabs: '[{"path":"/acme/issues/secret-issue"}]',+ // Untouched: not owned by the session.+ multica_locale: "zh-Hans",+ });+ const resetInMemory = vi.fn();+ registerDraftCleanup({+ storageKey: "multica_comment_drafts",+ workspaceScoped: true,+ resetInMemory,+ });++ const queryClient = new QueryClient();+ queryClient.setQueryData(workspaceKeys.list(), [+ { id: "ws-1", slug: shared },+ ] as Workspace[]);+ queryClient.setQueryData(["issues", "ws-1"], [{ id: "issue-1" }]);++ clearClientSessionData(queryClient, storage);++ // Persisted layer.+ expect(storage.snapshot()).toEqual({ multica_locale: "zh-Hans" });+ // Memory layer — a client-side login does not reload the page, so the+ // Zustand singleton would otherwise still hold A's draft.+ expect(resetInMemory).toHaveBeenCalledOnce();+ // Server-state layer. Every query has staleTime: Infinity, so anything+ // left here would render for B and never refetch away.+ expect(queryClient.getQueryData(["issues", "ws-1"])).toBeUndefined();+ expect(queryClient.getQueryData(workspaceKeys.list())).toBeUndefined();+ expect(document.cookie).not.toContain("last_workspace_slug=acme");+ });++ it("clears every workspace the session had, not just the active one", () => {+ const storage = makeStorage({+ "multica_navigation:acme": "1",+ "multica_navigation:globex": "2",+ });+ const queryClient = new QueryClient();+ queryClient.setQueryData(workspaceKeys.list(), [+ { id: "ws-1", slug: "acme" },+ { id: "ws-2", slug: "globex" },+ ] as Workspace[]);++ clearClientSessionData(queryClient, storage);++ expect(storage.snapshot()).toEqual({});+ });++ // Each in-memory reset is a Zustand setState, and persist middleware writes+ // the reset state straight back to storage under the still-active workspace+ // slug. Resetting AFTER the per-slug removal therefore resurrects the keys+ // just deleted — for the issue draft store, with the previous user's+ // lastAssignee inside.+ it("resets in-memory drafts before removing their persisted keys", () => {+ const storage = makeStorage({ "multica_issue_draft:acme": "A's draft" });+ registerDraftCleanup({+ storageKey: "multica_issue_draft",+ workspaceScoped: true,+ // Stands in for persist middleware writing the emptied store back out.+ resetInMemory: () =>+ storage.setItem("multica_issue_draft:acme", '{"lastAssignee":"A"}'),+ });+ const queryClient = new QueryClient();+ queryClient.setQueryData(workspaceKeys.list(), [+ { id: "ws-1", slug: "acme" },+ ] as Workspace[]);++ clearClientSessionData(queryClient, storage);++ expect(storage.snapshot()["multica_issue_draft:acme"]).toBeUndefined();+ });++ // A cold start rejected at the identity probe has an empty Query cache, so+ // there is no workspace list to read slugs from. Asserting only the global+ // `multica_tabs` here would pass while every per-workspace key survived —+ // the exact hole that let a stale-token launch leak A's drafts to B.+ it("clears workspace-scoped keys even with no workspace list to enumerate", () => {+ const storage = makeStorage({+ "multica_comment_drafts:acme": '{"issue-1":"A private draft"}',+ "multica:chat:activeSessionId:acme": "session-1",+ multica_tabs: "[]",+ });+ registerDraftCleanup({+ storageKey: "multica_comment_drafts",+ workspaceScoped: true,+ resetInMemory: vi.fn(),+ });+ const queryClient = new QueryClient();+ expect(queryClient.getQueryData(workspaceKeys.list())).toBeUndefined();++ clearClientSessionData(queryClient, storage);++ expect(storage.snapshot()).toEqual({});+ });+});diff --git a/packages/core/platform/session-cleanup.ts b/packages/core/platform/session-cleanup.tsnew file mode 100644index 0000000000..f81ee3ebc2--- /dev/null+++ b/packages/core/platform/session-cleanup.ts@@ -0,0 +1,72 @@+import type { QueryClient } from "@tanstack/react-query";+import { resetAllRegisteredDrafts } from "../drafts/cleanup-registry";+import type { StorageAdapter } from "../types/storage";+import type { Workspace } from "../types";+import { workspaceKeys } from "../workspace/queries";+import { defaultStorage } from "./storage";+import {+ clearAllWorkspaceStorage,+ clearWorkspaceStorage,+} from "./storage-cleanup";++/**+ * Erase everything the finished session left on this client: in-memory draft+ * stores, per-workspace persisted state, the desktop tab layout, the+ * last-workspace cookie, and the React Query cache.+ *+ * Both ways a session can end share this. An explicit logout is the obvious+ * one; a session the server ended (401) needs it just as much, because that+ * screen offers a login form and the next person to use it may not be the one+ * who was just signed in. Skipping it there would hand a colleague on a shared+ * machine the previous user's drafts, chat selection, and tab titles — the+ * exact leak `drafts/cleanup-registry` was written to close.+ *+ * What it deliberately does not touch: auth state itself (callers own that,+ * and the two paths publish it differently) and anything belonging to a+ * process that outlives the session, such as Desktop's local daemon.+ */+export function clearClientSessionData(+ queryClient: QueryClient,+ storage: StorageAdapter = defaultStorage,+): void {+ // Reset draft stores' in-memory state FIRST, before removing persisted+ // keys. Each reset is a Zustand setState, and persist middleware writes the+ // new (empty) state straight back to storage under the still-active+ // workspace slug — so resetting after removal would resurrect the very keys+ // just deleted, with whatever the reset state still carries. Memory must be+ // wiped regardless of the workspace list below: ending a session does not+ // reload the page, so the singletons would otherwise surface the previous+ // user's draft after the next login.+ resetAllRegisteredDrafts();++ // Then clear workspace-scoped storage, BEFORE clearing the React Query cache+ // (which holds the workspace list). Otherwise per-workspace drafts/chat/etc+ // would leak to the next user on this device.+ //+ // Enumerating the stored keys rather than the workspace list is what makes+ // this work on a cold start: a session rejected at the identity probe never+ // loaded a workspace list, so there would be no slugs to iterate and every+ // per-workspace key would survive. Adapters that cannot list keys get the+ // narrower sweep over whatever workspaces this process did resolve.+ if (!clearAllWorkspaceStorage(storage)) {+ const cachedWorkspaces =+ queryClient.getQueryData<Workspace[]>(workspaceKeys.list()) ?? [];+ for (const ws of cachedWorkspaces) {+ clearWorkspaceStorage(storage, ws.slug);+ }+ }++ // Clear the last-workspace-slug cookie. Otherwise on a shared device the+ // next user gets redirected by the proxy to the previous user's last+ // workspace, then bounced to NoAccessPage — confusing.+ if (typeof document !== "undefined") {+ document.cookie = "last_workspace_slug=; path=/; max-age=0; SameSite=Lax";+ }++ // Clear desktop tab state. Tab paths can contain workspace slugs and issue+ // UUIDs that must not survive across user sessions on a shared machine.+ // No-op on web (web doesn't write this key).+ storage.removeItem("multica_tabs");++ queryClient.clear();+}diff --git a/packages/core/platform/storage-cleanup.test.ts b/packages/core/platform/storage-cleanup.test.tsindex 2b5ced8e50..3efc77e83a 100644--- a/packages/core/platform/storage-cleanup.test.ts+++ b/packages/core/platform/storage-cleanup.test.ts@@ -1,5 +1,8 @@import { describe, it, expect, vi, beforeEach } from "vitest";-import { clearWorkspaceStorage } from "./storage-cleanup";+import {+ clearAllWorkspaceStorage,+ clearWorkspaceStorage,+} from "./storage-cleanup";import {registerDraftCleanup,__clearDraftCleanupRegistryForTest,@@ -58,3 +61,62 @@ describe("clearWorkspaceStorage", () => {expect(adapter.removeItem).toHaveBeenCalledTimes(11);});});++describe("clearAllWorkspaceStorage", () => {+ function makeAdapter(values: Record<string, string>) {+ return {+ getItem: (k: string) => values[k] ?? null,+ setItem: (k: string, v: string) => {+ values[k] = v;+ },+ removeItem: (k: string) => {+ delete values[k];+ },+ keys: () => Object.keys(values),+ snapshot: () => ({ ...values }),+ };+ }++ // The point of enumerating: a cold start rejected at the identity probe+ // never loaded a workspace list, so it cannot name a single slug.+ it("removes workspace-scoped keys for slugs the caller never knew", () => {+ registerDraftCleanup({+ storageKey: "multica_comment_drafts",+ workspaceScoped: true,+ resetInMemory: vi.fn(),+ });+ registerDraftCleanup({+ storageKey: "multica_quick_create",+ workspaceScoped: false,+ resetInMemory: vi.fn(),+ });+ const adapter = makeAdapter({+ "multica_comment_drafts:acme": "1",+ "multica_comment_drafts:globex": "2",+ "multica_navigation:initech": "3",+ "multica:chat:activeSessionId:acme": "4",+ multica_quick_create: "5",+ // Not session state — a device preference and another app's key.+ multica_locale: "zh-Hans",+ unrelated_key: "keep",+ });++ expect(clearAllWorkspaceStorage(adapter)).toBe(true);++ expect(adapter.snapshot()).toEqual({+ multica_locale: "zh-Hans",+ unrelated_key: "keep",+ });+ });++ it("reports when the adapter cannot enumerate, instead of silently doing nothing", () => {+ const adapter = {+ getItem: vi.fn(),+ setItem: vi.fn(),+ removeItem: vi.fn(),+ };++ expect(clearAllWorkspaceStorage(adapter)).toBe(false);+ expect(adapter.removeItem).not.toHaveBeenCalled();+ });+});diff --git a/packages/core/platform/storage-cleanup.ts b/packages/core/platform/storage-cleanup.tsindex 1a08b179bb..359d681906 100644--- a/packages/core/platform/storage-cleanup.ts+++ b/packages/core/platform/storage-cleanup.ts@@ -1,5 +1,8 @@import type { StorageAdapter } from "../types/storage";-import { clearRegisteredWorkspaceDrafts } from "../drafts/cleanup-registry";+import {+ clearRegisteredWorkspaceDrafts,+ registeredDraftKeys,+} from "../drafts/cleanup-registry";// Ensure every module-level draft store has registered its key before cleanup// runs, so the registry is never partially populated at logout/delete time.import "../drafts/register-all-drafts";@@ -40,3 +43,35 @@ export function clearWorkspaceStorage(// new draft store can never be silently skipped by an out-of-date list.clearRegisteredWorkspaceDrafts(adapter, slug);}++/**+ * Remove workspace-scoped storage for EVERY workspace on this device, without+ * being told which ones exist.+ *+ * `clearWorkspaceStorage` needs a slug, and the slugs come from the workspace+ * list — which a session rejected at the identity probe never loaded. A cold+ * start with a stale token therefore had no way to clean up after the previous+ * session, leaving `multica_comment_drafts:<slug>` and friends for whoever+ * signed in next. Enumerating the keys removes that dependency entirely, and+ * also catches workspaces the last session had left before it ended.+ *+ * Returns false when the adapter cannot list its keys, so the caller can say+ * what it is falling back to rather than silently doing less.+ */+export function clearAllWorkspaceStorage(adapter: StorageAdapter): boolean {+ const storedKeys = adapter.keys?.();+ if (!storedKeys) return false;++ const drafts = registeredDraftKeys();+ const prefixes = [...WORKSPACE_SCOPED_KEYS, ...drafts.workspaceScoped].map(+ (base) => `${base}:`,+ );+ for (const key of storedKeys) {+ if (prefixes.some((prefix) => key.startsWith(prefix))) {+ adapter.removeItem(key);+ }+ }+ // Globally-namespaced draft keys carry no slug to match on.+ for (const key of drafts.global) adapter.removeItem(key);+ return true;+}diff --git a/packages/core/platform/storage.ts b/packages/core/platform/storage.tsindex 85a97c1150..80b5afb761 100644--- a/packages/core/platform/storage.ts+++ b/packages/core/platform/storage.ts@@ -10,4 +10,8 @@ export const defaultStorage: StorageAdapter = {removeItem: (k) => {if (typeof window !== "undefined") localStorage.removeItem(k);},+ keys: () => {+ if (typeof window === "undefined") return [];+ return Object.keys(localStorage);+ },};diff --git a/packages/core/platform/types.ts b/packages/core/platform/types.tsindex 1da5f079e0..31a054a5dc 100644--- a/packages/core/platform/types.ts+++ b/packages/core/platform/types.ts@@ -31,6 +31,10 @@ export interface CoreProviderProps {onLogin?: () => void;/** Called after logout (e.g. clear cookie). */onLogout?: () => void;+ /** Called when the server ends the session (401) rather than the user.+ * Defaults to `onLogout`; pass it only when some of this shell's logout+ * teardown is too destructive for an expiry the user did not ask for. */+ onSessionExpired?: () => void;/** Identifies the calling client (web/desktop + version + os) to the server. */identity?: ClientIdentity;/** Active locale, determined server-side (web) or at app boot (desktop). */diff --git a/packages/core/types/storage.ts b/packages/core/types/storage.tsindex 514d5a60e9..5afc96b130 100644--- a/packages/core/types/storage.ts+++ b/packages/core/types/storage.ts@@ -2,4 +2,14 @@ export interface StorageAdapter {getItem(key: string): string | null;setItem(key: string, value: string): void;removeItem(key: string): void;+ /**+ * Every key currently held, for callers that must clean up entries they+ * cannot name — workspace-scoped keys are `${base}:${slug}`, and a process+ * that never resolved a workspace list has no way to reconstruct the slugs.+ *+ * Optional because it is a real capability boundary, not a compatibility+ * shim: a backend with asynchronous or opaque storage genuinely cannot+ * answer this synchronously. Callers state what they degrade to without it.+ */+ keys?(): string[];}diff --git a/packages/views/auth/login-page.test.tsx b/packages/views/auth/login-page.test.tsxindex 19c43ff08b..358605d4ff 100644--- a/packages/views/auth/login-page.test.tsx+++ b/packages/views/auth/login-page.test.tsx@@ -35,6 +35,8 @@ const mockApiSetToken = vi.hoisted(() => vi.fn());const mockApiGetMe = vi.hoisted(() => vi.fn());const mockApiIssueCliToken = vi.hoisted(() => vi.fn());const mockSetQueryData = vi.hoisted(() => vi.fn());+// Mutable slice of auth state the component subscribes to.+const mockAuthState = vi.hoisted(() => ({ expired: false }));vi.mock("@tanstack/react-query", async () => {const actual = await vi.importActual<typeof import("@tanstack/react-query")>(@@ -47,7 +49,11 @@ vi.mock("@multica/core/auth", () => ({useAuthStore: Object.assign(// Zustand hook form — component may call useAuthStore(selector)(selector?: (s: unknown) => unknown) => {- const state = { sendCode: mockSendCode, verifyCode: mockVerifyCode };+ const state = {+ sendCode: mockSendCode,+ verifyCode: mockVerifyCode,+ expired: mockAuthState.expired,+ };return selector ? selector(state) : state;},{@@ -96,6 +102,7 @@ describe("LoginPage", () => {beforeEach(() => {vi.useFakeTimers({ shouldAdvanceTime: true });vi.clearAllMocks();+ mockAuthState.expired = false;// Default: no existing session (getMe rejects when no auth)mockApiGetMe.mockRejectedValue(new Error("unauthorized"));localStorage.clear();@@ -114,6 +121,19 @@ describe("LoginPage", () => {// Email step rendering// -------------------------------------------------------------------------+ it("says the session expired when that is why the user is here", () => {+ mockAuthState.expired = true;+ renderWithI18n(<LoginPage onSuccess={onSuccess} />);+ expect(+ screen.getByText(/your session expired/i),+ ).toBeInTheDocument();+ });++ it("stays quiet on an ordinary visit to the login page", () => {+ renderWithI18n(<LoginPage onSuccess={onSuccess} />);+ expect(screen.queryByText(/your session expired/i)).not.toBeInTheDocument();+ });+it("renders email form with 'Sign in to Multica' title", () => {renderWithI18n(<LoginPage onSuccess={onSuccess} />);expect(@@ -426,6 +446,37 @@ describe("LoginPage", () => {).toBeInTheDocument();});+ it("still finds the stored token after the cookie probe's 401 clears it", async () => {+ localStorage.setItem("multica_token", "existing-jwt");+ // The cookie probe 401s, and a 401 ends the session — which wipes the very+ // key the localStorage fallback is about to look for. The component has to+ // have read it before probing, or token-mode users can never authorize a+ // CLI (they land on the email step instead).+ mockApiGetMe+ .mockImplementationOnce(() => {+ localStorage.removeItem("multica_token");+ return Promise.reject(new Error("no cookie"));+ })+ .mockResolvedValueOnce({+ id: "u-1",+ email: "[email protected]",+ name: "Test User",+ });++ render(+ <LoginPage+ onSuccess={onSuccess}+ cliCallback={{ url: "http://localhost:9876/callback", state: "abc" }}+ />,+ );++ await waitFor(() => {+ expect(screen.getByText(/authorize cli/i)).toBeInTheDocument();+ });+ expect(mockApiSetToken).toHaveBeenCalledWith("existing-jwt");+ expect(localStorage.getItem("multica_token")).toBe("existing-jwt");+ });+it("CLI authorize button redirects to callback URL", async () => {localStorage.setItem("multica_token", "existing-jwt");// Cookie attempt fails, localStorage fallback succeedsdiff --git a/packages/views/auth/login-page.tsx b/packages/views/auth/login-page.tsxindex e5499cc5e4..ed1f578b5d 100644--- a/packages/views/auth/login-page.tsx+++ b/packages/views/auth/login-page.tsx@@ -10,6 +10,7 @@ import {CardContent,CardFooter,} from "@multica/ui/components/ui/card";+import { Alert, AlertDescription } from "@multica/ui/components/ui/alert";import { Input } from "@multica/ui/components/ui/input";import { Button } from "@multica/ui/components/ui/button";import { Label } from "@multica/ui/components/ui/label";@@ -118,6 +119,10 @@ export function LoginPage({// Tracks how the existing session was detected so handleCliAuthorize// uses the matching token source (cookie → issueCliToken, localStorage → direct).const authSourceRef = useRef<"cookie" | "localStorage">("cookie");+ // The last session ended because the server rejected its credential, not+ // because the user asked to leave. Without saying so, landing here reads as+ // the app having lost their work for no reason.+ const sessionExpired = useAuthStore((state) => state.expired);// Check for existing session when CLI callback is present.// Prioritises cookie auth (= current browser session) to avoid authorising@@ -125,6 +130,12 @@ export function LoginPage({useEffect(() => {if (!cliCallback) return;+ // Snapshot the token before probing. The probe below is *expected* to 401+ // for a token-mode session, and a 401 ends the session — clearing this+ // very key — so reading it after the probe would always come back null+ // and the fallback could never run.+ const storedToken = localStorage.getItem("multica_token");+// Ensure no stale bearer token interferes — we want to test the cookie first.api.setToken(null);@@ -136,11 +147,11 @@ export function LoginPage({setStep("cli_confirm");}).catch(() => {- // Cookie auth failed — fall back to localStorage token- const token = localStorage.getItem("multica_token");- if (!token) return;+ // Cookie auth failed — fall back to the token this browser had.+ if (!storedToken) return;- api.setToken(token);+ localStorage.setItem("multica_token", storedToken);+ api.setToken(storedToken);api.getMe().then((user) => {@@ -418,7 +429,14 @@ export function LoginPage({{t(($) => $.signin.description)}</CardDescription></CardHeader>- <CardContent>+ <CardContent className="space-y-4">+ {sessionExpired && (+ <Alert>+ <AlertDescription>+ {t(($) => $.errors.session_expired)}+ </AlertDescription>+ </Alert>+ )}<form id="login-form" onSubmit={handleSendCode} className="space-y-4"><div className="space-y-2"><Label htmlFor="login-email">{t(($) => $.common.email)}</Label>diff --git a/packages/views/auth/use-logout.test.ts b/packages/views/auth/use-logout.test.tsindex be5b74f39f..1f1217f98d 100644--- a/packages/views/auth/use-logout.test.ts+++ b/packages/views/auth/use-logout.test.ts@@ -3,26 +3,18 @@ import { describe, expect, it, vi, beforeEach } from "vitest";import { renderHook } from "@testing-library/react";import { useLogout } from "./use-logout";-// Order of the destructive calls is the contract under test: each in-memory-// reset is a Zustand setState, and persist middleware writes the reset state-// straight back to storage under the still-active workspace slug. Resetting-// AFTER the per-slug key removal therefore resurrects the just-deleted keys-// (for the issue draft store: with the previous user's lastAssignee inside).+// What client state gets erased, and the order it has to happen in, is pinned+// in core's platform/session-cleanup.test.ts — the session-expiry path runs+// the same function. What is left for this hook is the logout-only tail:+// erase, then drop auth, then move the URL.const calls = vi.hoisted(() => [] as string[]);-const mockReset = vi.hoisted(() => vi.fn());-const mockClearWorkspaceStorage = vi.hoisted(() => vi.fn());+const mockClearClientSessionData = vi.hoisted(() => vi.fn());const mockAuthLogout = vi.hoisted(() => vi.fn());const mockPush = vi.hoisted(() => vi.fn());-const mockQueryClientClear = vi.hoisted(() => vi.fn());+const queryClient = vi.hoisted(() => ({ id: "query-client" }));vi.mock("@tanstack/react-query", () => ({- useQueryClient: () => ({- getQueryData: () => [- { slug: "acme" },- { slug: "beta" },- ],- clear: mockQueryClientClear,- }),+ useQueryClient: () => queryClient,}));vi.mock("@multica/core/auth", () => ({@@ -35,17 +27,8 @@ vi.mock("@multica/core/auth", () => ({),}));-vi.mock("@multica/core/workspace/queries", () => ({- workspaceKeys: { list: () => ["workspaces", "list"] },-}));-vi.mock("@multica/core/platform", () => ({- clearWorkspaceStorage: mockClearWorkspaceStorage,- defaultStorage: { getItem: () => null, setItem: () => {}, removeItem: () => {} },-}));--vi.mock("@multica/core/drafts/cleanup-registry", () => ({- resetAllRegisteredDrafts: mockReset,+ clearClientSessionData: mockClearClientSessionData,}));vi.mock("@multica/core/paths", () => ({@@ -60,25 +43,20 @@ describe("useLogout", () => {beforeEach(() => {calls.length = 0;vi.clearAllMocks();- mockReset.mockImplementation(() => calls.push("reset"));- mockClearWorkspaceStorage.mockImplementation((_a: unknown, slug: string) =>- calls.push(`clear:${slug}`),- );- });-- it("resets in-memory drafts BEFORE removing their persisted keys", () => {- const { result } = renderHook(() => useLogout());- result.current();-- expect(calls).toEqual(["reset", "clear:acme", "clear:beta"]);+ mockClearClientSessionData.mockImplementation(() => calls.push("clear"));+ mockAuthLogout.mockImplementation(() => calls.push("authLogout"));+ mockPush.mockImplementation(() => calls.push("push"));});- it("still ends by clearing the query cache, auth, and navigating to /login", () => {+ // Erasing after the auth store publishes `unauthenticated` would race the+ // shells' login redirect, and navigating first would leave the caller on a+ // workspace URL that renders null.+ it("erases client state, then drops auth, then navigates to /login", () => {const { result } = renderHook(() => useLogout());result.current();- expect(mockQueryClientClear).toHaveBeenCalledTimes(1);- expect(mockAuthLogout).toHaveBeenCalledTimes(1);+ expect(calls).toEqual(["clear", "authLogout", "push"]);+ expect(mockClearClientSessionData).toHaveBeenCalledWith(queryClient);expect(mockPush).toHaveBeenCalledWith("/login");});});diff --git a/packages/views/auth/use-logout.ts b/packages/views/auth/use-logout.tsindex 2e4494df63..c2e58aa8f3 100644--- a/packages/views/auth/use-logout.ts+++ b/packages/views/auth/use-logout.ts@@ -3,11 +3,8 @@import { useCallback } from "react";import { useQueryClient } from "@tanstack/react-query";import { useAuthStore } from "@multica/core/auth";-import { workspaceKeys } from "@multica/core/workspace/queries";-import { clearWorkspaceStorage, defaultStorage } from "@multica/core/platform";-import { resetAllRegisteredDrafts } from "@multica/core/drafts/cleanup-registry";+import { clearClientSessionData } from "@multica/core/platform";import { paths } from "@multica/core/paths";-import type { Workspace } from "@multica/core/types";import { useNavigation } from "../navigation";/**@@ -29,40 +26,10 @@ export function useLogout() {const { push } = useNavigation();return useCallback(() => {- // Reset draft stores' in-memory state FIRST, before removing persisted- // keys. Each reset is a Zustand setState, and persist middleware writes- // the new (empty) state straight back to storage under the still-active- // workspace slug — so resetting after removal would resurrect the very- // keys just deleted, with whatever the reset state still carries. Memory- // must be wiped regardless of the workspace list below: a client-side- // navigation to /login does not reload the page, so the singletons would- // otherwise surface the previous user's draft after the next login.- resetAllRegisteredDrafts();-- // Then clear workspace-scoped storage for every workspace this user has- // access to, BEFORE clearing the React Query cache (which holds the- // workspace list). Otherwise per-workspace drafts/chat/etc would leak- // to the next user on this device.- const cachedWorkspaces =- queryClient.getQueryData<Workspace[]>(workspaceKeys.list()) ?? [];- for (const ws of cachedWorkspaces) {- clearWorkspaceStorage(defaultStorage, ws.slug);- }-- // Clear the last-workspace-slug cookie. Otherwise on a shared device- // the next user gets redirected by the proxy to the previous user's- // last workspace, then bounced to NoAccessPage — confusing.- if (typeof document !== "undefined") {- document.cookie =- "last_workspace_slug=; path=/; max-age=0; SameSite=Lax";- }-- // Clear desktop tab state. Tab paths can contain workspace slugs and- // issue UUIDs that must not survive across user sessions on a shared- // machine. No-op on web (web doesn't write this key).- defaultStorage.removeItem("multica_tabs");-- queryClient.clear();+ // Shared with the session-expiry path, which has to erase exactly the+ // same client-side state — see core's platform/session-cleanup for what+ // and why.+ clearClientSessionData(queryClient);authLogout();// Navigate to /login explicitly. authLogout() clears state but doesn'tdiff --git a/packages/views/locales/en/auth.json b/packages/views/locales/en/auth.jsonindex fadc547118..75ef6902ba 100644--- a/packages/views/locales/en/auth.json+++ b/packages/views/locales/en/auth.json@@ -30,7 +30,8 @@"send_failed": "Failed to send code.","resend_failed": "Failed to resend code","code_invalid": "Invalid or expired code",- "cli_auth_failed": "Failed to authorize CLI. Please log in again."+ "cli_auth_failed": "Failed to authorize CLI. Please log in again.",+ "session_expired": "Your session expired. Sign in again to continue."},"web": {"prefer_desktop": "Prefer the desktop app?",diff --git a/packages/views/locales/ja/auth.json b/packages/views/locales/ja/auth.jsonindex 34ebed3610..1237c26c2f 100644--- a/packages/views/locales/ja/auth.json+++ b/packages/views/locales/ja/auth.json@@ -30,7 +30,8 @@"send_failed": "コードを送信できませんでした。","resend_failed": "コードを再送信できませんでした","code_invalid": "コードが無効または期限切れです",- "cli_auth_failed": "CLIを承認できませんでした。もう一度ログインしてください。"+ "cli_auth_failed": "CLIを承認できませんでした。もう一度ログインしてください。",+ "session_expired": "セッションの有効期限が切れました。もう一度サインインしてください。"},"web": {"prefer_desktop": "デスクトップアプリをご利用ですか?",diff --git a/packages/views/locales/ko/auth.json b/packages/views/locales/ko/auth.jsonindex aa59932371..a07308c723 100644--- a/packages/views/locales/ko/auth.json+++ b/packages/views/locales/ko/auth.json@@ -30,7 +30,8 @@"send_failed": "코드 전송에 실패했습니다.","resend_failed": "코드를 다시 보내지 못했습니다","code_invalid": "코드가 잘못되었거나 만료되었습니다",- "cli_auth_failed": "CLI 승인에 실패했습니다. 다시 로그인하세요."+ "cli_auth_failed": "CLI 승인에 실패했습니다. 다시 로그인하세요.",+ "session_expired": "세션이 만료되었습니다. 다시 로그인해 주세요."},"web": {"prefer_desktop": "데스크톱 앱을 선호하시나요?",diff --git a/packages/views/locales/zh-Hans/auth.json b/packages/views/locales/zh-Hans/auth.jsonindex 54d324814c..db6e448d09 100644--- a/packages/views/locales/zh-Hans/auth.json+++ b/packages/views/locales/zh-Hans/auth.json@@ -30,7 +30,8 @@"send_failed": "发送验证码失败。","resend_failed": "重新发送失败","code_invalid": "验证码无效或已过期",- "cli_auth_failed": "CLI 授权失败,请重新登录。"+ "cli_auth_failed": "CLI 授权失败,请重新登录。",+ "session_expired": "登录已过期,请重新登录。"},"web": {"prefer_desktop": "想用桌面应用?",