Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-6254: recover auth after transient Desktop startup failures (#7058)

Multica Eve9d6c0c81e0e0
diff --git a/apps/desktop/src/renderer/src/App.tsx b/apps/desktop/src/renderer/src/App.tsx
index e87a8588a7..52c830546d 100644
--- a/apps/desktop/src/renderer/src/App.tsx
+++ b/apps/desktop/src/renderer/src/App.tsx
@@ -1,10 +1,11 @@
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
-import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { useQueryClient } from "@tanstack/react-query";
import { CoreProvider } from "@multica/core/platform";
import { pickLocale, type SupportedLocale } from "@multica/core/i18n";
import { useAuthStore } from "@multica/core/auth";
import { useWelcomeStore } from "@multica/core/onboarding";
-import { workspaceKeys, workspaceListOptions } from "@multica/core/workspace/queries";
+import { workspaceKeys } from "@multica/core/workspace/queries";
+import { useWorkspaceList } from "@multica/core/workspace";
import { api } from "@multica/core/api";
import { useHasOnboarded } from "@multica/core/paths";
import { setCurrentWorkspace } from "@multica/core/platform";
@@ -12,6 +13,7 @@ import { ThemeProvider } from "@multica/ui/components/common/theme-provider";
import { MulticaIcon } from "@multica/ui/components/common/multica-icon";
import { Toaster } from "@multica/ui/components/ui/sonner";
import { DesktopLoginPage } from "./pages/login";
+import { DesktopAuthRecoveryPage } from "./pages/auth-recovery";
import { DesktopShell } from "./components/desktop-layout";
import { UpdateNotification } from "./components/update-notification";
import { IssueWindow } from "./components/issue-window";
@@ -26,6 +28,7 @@ import { RESOURCES } from "@multica/views/locales";
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";
// BCP-47 region tags for the <html lang> attribute, mirroring
// apps/web/app/layout.tsx HTML_LANG. index.html ships a static lang="en";
@@ -78,9 +81,11 @@ function useCmdWCloseTab() {
function IssueWindowContent() {
const user = useAuthStore((state) => state.user);
const isLoading = useAuthStore((state) => state.isLoading);
+ const authStatus = useAuthStore((state) => state.status);
const context = window.desktopAPI.windowContext ?? { kind: "main" as const };
if (context.kind !== "issue") return null;
+ if (authStatus === "recovering") return <DesktopAuthRecoveryPage />;
if (isLoading) {
return (
<div className="flex h-screen items-center justify-center">
@@ -92,28 +97,10 @@ function IssueWindowContent() {
return user ? <IssueWindow context={context} /> : <DesktopLoginPage />;
}
-/**
- * Keep the main process informed of the resolved account identity without
- * sharing credentials between renderer processes. Main uses this signal to
- * close dedicated windows on logout/account switch.
- */
-function DesktopAuthSessionBridge() {
- const userId = useAuthStore((state) => state.user?.id ?? null);
- const isLoading = useAuthStore((state) => state.isLoading);
-
- useEffect(() => {
- if (isLoading) return;
- // Optional chaining keeps renderer HMR safe during the brief interval in
- // which an old preload is still attached to the refreshed React tree.
- window.desktopAPI.reportAuthSession?.(userId);
- }, [isLoading, userId]);
-
- return null;
-}
-
function AppContent() {
const user = useAuthStore((s) => s.user);
const isLoading = useAuthStore((s) => s.isLoading);
+ const authStatus = useAuthStore((s) => s.status);
const qc = useQueryClient();
// Deep-link login runs loginWithToken → syncToken → listWorkspaces →
@@ -198,8 +185,13 @@ function AppContent() {
// account switches (user A logout → user B login) should not trigger a
// daemon restart here — daemon-manager already restarts on user change
// via syncToken.
- const { data: workspaces = [], isFetched: workspaceListFetched } = useQuery({
- ...workspaceListOptions(),
+ const {
+ workspaces,
+ ready: workspaceListReady,
+ unavailable: workspaceListUnavailable,
+ isFetching: workspaceListRetrying,
+ refetch: retryWorkspaceList,
+ } = useWorkspaceList({
enabled: !!user,
});
const wsCount = workspaces.length;
@@ -231,7 +223,7 @@ function AppContent() {
// /onboarding — we also clear the active workspace so the dashboard
// doesn't render under the overlay with stale workspace context.
useEffect(() => {
- if (!user || !workspaceListFetched) return undefined;
+ if (!user || !workspaceListReady) return undefined;
const { overlay, open } = useWindowOverlayStore.getState();
if (overlay) return undefined;
if (hasOnboarded && wsCount > 0) return undefined;
@@ -272,7 +264,7 @@ function AppContent() {
}
open({ type: "new-workspace" });
return undefined;
- }, [user, workspaceListFetched, wsCount, workspaces, hasOnboarded, qc]);
+ }, [user, workspaceListReady, wsCount, workspaces, hasOnboarded, qc]);
// Validate persisted tab state against the current user's workspace list,
@@ -284,20 +276,17 @@ function AppContent() {
// TabBar is subscribed to. useLayoutEffect flushes both renders before
// the user sees anything, so there's no visible flicker.
//
- // Gate on `workspaceListFetched`: useQuery defaults `data` to `[]` before
- // the first fetch, so without this guard we'd run validation against an
- // empty slug set, wipe the persisted `activeWorkspaceSlug`, then fall
- // back to `workspaces[0]` once the real list arrives — losing the user's
- // last-opened workspace on every app start.
+ // Gate on authoritative data: pending and initial errors expose no data,
+ // while a failed background refetch retains the last successful list.
useLayoutEffect(() => {
- if (!workspaceListFetched) return;
+ if (!workspaceListReady) return;
const validSlugs = new Set(workspaces.map((w) => w.slug));
useTabStore.getState().validateWorkspaceSlugs(validSlugs);
const { activeWorkspaceSlug, switchWorkspace } = useTabStore.getState();
if (!activeWorkspaceSlug && workspaces.length > 0) {
switchWorkspace(workspaces[0].slug);
}
- }, [workspaces, workspaceListFetched]);
+ }, [workspaces, workspaceListReady]);
// null = undecided (pre-login or list hasn't settled yet)
// true = session started with zero workspaces; next transition to >=1 triggers restart
@@ -308,7 +297,7 @@ function AppContent() {
sessionStartedEmptyRef.current = null;
return;
}
- if (!workspaceListFetched) return;
+ if (!workspaceListReady) return;
if (sessionStartedEmptyRef.current === null) {
sessionStartedEmptyRef.current = wsCount === 0;
return;
@@ -317,8 +306,11 @@ function AppContent() {
void window.daemonAPI.restart();
sessionStartedEmptyRef.current = false;
}
- }, [user, workspaceListFetched, wsCount]);
+ }, [user, workspaceListReady, wsCount]);
+ if (authStatus === "recovering") {
+ return <DesktopAuthRecoveryPage />;
+ }
if (isLoading || bootstrapping) {
return (
<div className="flex h-screen items-center justify-center">
@@ -327,6 +319,17 @@ function AppContent() {
);
}
+ if (workspaceListUnavailable) {
+ return (
+ <DesktopAuthRecoveryPage
+ isRetrying={workspaceListRetrying}
+ onRetry={() => {
+ void retryWorkspaceList();
+ }}
+ />
+ );
+ }
+
return user ? <DesktopShell /> : <DesktopLoginPage />;
}
diff --git a/apps/desktop/src/renderer/src/components/issue-window.test.tsx b/apps/desktop/src/renderer/src/components/issue-window.test.tsx
new file mode 100644
index 0000000000..25bba32450
--- /dev/null
+++ b/apps/desktop/src/renderer/src/components/issue-window.test.tsx
@@ -0,0 +1,124 @@
+import { fireEvent, render, screen } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const state = vi.hoisted(() => ({
+ workspaces: [] as { id: string; slug: string }[],
+ ready: false,
+ unavailable: false,
+ isFetching: false,
+ refetch: vi.fn(),
+}));
+
+vi.mock("@multica/core/auth", () => ({
+ useAuthStore: (selector: (auth: { user: { id: string } }) => unknown) =>
+ selector({ user: { id: "user-1" } }),
+}));
+
+vi.mock("@multica/core/workspace", () => ({
+ useWorkspaceList: () => ({
+ workspaces: state.workspaces,
+ ready: state.ready,
+ unavailable: state.unavailable,
+ isFetching: state.isFetching,
+ refetch: state.refetch,
+ }),
+}));
+
+vi.mock("@multica/core/platform", () => ({
+ setCurrentWorkspace: vi.fn(),
+}));
+
+vi.mock("@multica/core/paths", () => ({
+ WorkspaceSlugProvider: ({ children }: { children: React.ReactNode }) => (
+ <>{children}</>
+ ),
+}));
+
+vi.mock("@multica/ui/components/common/multica-icon", () => ({
+ MulticaIcon: () => <div data-testid="workspace-loading" />,
+}));
+
+vi.mock("@multica/views/modals/registry", () => ({
+ ModalRegistry: () => null,
+}));
+
+vi.mock("@multica/views/layout", () => ({
+ WorkspacePresencePrefetch: () => null,
+}));
+
+vi.mock("@multica/views/platform", () => ({
+ DragStrip: () => null,
+}));
+
+vi.mock("../pages/issue-detail-page", () => ({
+ IssueDetailPage: () => <div data-testid="issue-detail" />,
+}));
+
+vi.mock("../pages/auth-recovery", () => ({
+ DesktopAuthRecoveryPage: ({
+ onRetry,
+ isRetrying,
+ }: {
+ onRetry: () => void;
+ isRetrying: boolean;
+ }) => (
+ <button type="button" disabled={isRetrying} onClick={onRetry}>
+ Retry workspace list
+ </button>
+ ),
+}));
+
+vi.mock("../platform/issue-window-navigation", () => ({
+ IssueWindowNavigationProvider: ({ children }: { children: React.ReactNode }) => (
+ <>{children}</>
+ ),
+}));
+
+import { IssueWindow } from "./issue-window";
+
+const context = {
+ kind: "issue" as const,
+ path: "/acme/issues/MUL-1",
+ title: "MUL-1",
+ workspaceSlug: "acme",
+ issueId: "MUL-1",
+};
+
+beforeEach(() => {
+ state.workspaces = [];
+ state.ready = false;
+ state.unavailable = false;
+ state.isFetching = false;
+ state.refetch.mockReset();
+});
+
+describe("IssueWindow", () => {
+ it("keeps loading after an initial workspace-list failure", async () => {
+ render(<IssueWindow context={context} />);
+
+ expect(await screen.findByTestId("workspace-loading")).toBeInTheDocument();
+ expect(screen.queryByText("Issue unavailable")).toBeNull();
+ });
+
+ it("shows unavailable only after an authoritative list omits the workspace", async () => {
+ state.ready = true;
+
+ render(<IssueWindow context={context} />);
+
+ expect(await screen.findByText("Issue unavailable")).toBeInTheDocument();
+ expect(screen.queryByTestId("workspace-loading")).toBeNull();
+ });
+
+ it("offers a retry when the initial workspace-list request fails", async () => {
+ state.unavailable = true;
+
+ render(<IssueWindow context={context} />);
+
+ const retry = await screen.findByRole("button", {
+ name: "Retry workspace list",
+ });
+ fireEvent.click(retry);
+ expect(state.refetch).toHaveBeenCalledOnce();
+ expect(screen.queryByTestId("workspace-loading")).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/renderer/src/components/issue-window.tsx b/apps/desktop/src/renderer/src/components/issue-window.tsx
index 821d30b0c0..9719f366c1 100644
--- a/apps/desktop/src/renderer/src/components/issue-window.tsx
+++ b/apps/desktop/src/renderer/src/components/issue-window.tsx
@@ -1,5 +1,4 @@
import { useMemo } from "react";
-import { useQuery } from "@tanstack/react-query";
import {
createMemoryRouter,
RouterProvider,
@@ -10,13 +9,14 @@ import { AlertTriangle, RotateCw, X } from "lucide-react";
import { useAuthStore } from "@multica/core/auth";
import { setCurrentWorkspace } from "@multica/core/platform";
import { WorkspaceSlugProvider } from "@multica/core/paths";
-import { workspaceBySlugOptions } from "@multica/core/workspace";
+import { useWorkspaceList } from "@multica/core/workspace";
import { Button } from "@multica/ui/components/ui/button";
import { MulticaIcon } from "@multica/ui/components/common/multica-icon";
import { ModalRegistry } from "@multica/views/modals/registry";
import { WorkspacePresencePrefetch } from "@multica/views/layout";
import { DragStrip } from "@multica/views/platform";
import type { IssueWindowContext } from "../../../shared/issue-window";
+import { DesktopAuthRecoveryPage } from "../pages/auth-recovery";
import { IssueDetailPage } from "../pages/issue-detail-page";
import { IssueWindowNavigationProvider } from "../platform/issue-window-navigation";
@@ -42,16 +42,28 @@ export function IssueWindow({ context }: { context: IssueWindowContext }) {
function IssueWindowRoute() {
const { workspaceSlug } = useParams<{ workspaceSlug: string }>();
const user = useAuthStore((state) => state.user);
- const { data: workspace, isFetched } = useQuery({
- ...workspaceBySlugOptions(workspaceSlug ?? ""),
- enabled: !!user && !!workspaceSlug,
- });
+ const { workspaces, ready, unavailable, isFetching, refetch } =
+ useWorkspaceList({
+ enabled: !!user && !!workspaceSlug,
+ });
+ const workspace = workspaces.find((item) => item.slug === workspaceSlug);
if (workspace && workspaceSlug) {
setCurrentWorkspace(workspaceSlug, workspace.id);
}
- if (!isFetched) {
+ if (unavailable) {
+ return (
+ <DesktopAuthRecoveryPage
+ isRetrying={isFetching}
+ onRetry={() => {
+ void refetch();
+ }}
+ />
+ );
+ }
+
+ if (!ready) {
return (
<IssueWindowFrame>
<div className="flex min-h-0 flex-1 items-center justify-center">
diff --git a/apps/desktop/src/renderer/src/components/workspace-route-layout.test.tsx b/apps/desktop/src/renderer/src/components/workspace-route-layout.test.tsx
index 50ae62ab35..fb03537e33 100644
--- a/apps/desktop/src/renderer/src/components/workspace-route-layout.test.tsx
+++ b/apps/desktop/src/renderer/src/components/workspace-route-layout.test.tsx
@@ -1,5 +1,5 @@
import { describe, expect, it, vi, beforeEach } from "vitest";
-import { render } from "@testing-library/react";
+import { act, render, waitFor } from "@testing-library/react";
import { MemoryRouter, Route, Routes } from "react-router-dom";
// vi.hoisted shared state for all the stores / hooks the layout consumes.
@@ -8,6 +8,7 @@ const state = vi.hoisted(() => ({
isAuthLoading: false,
overlay: null as { type: string } | null,
workspace: null as { id: string; slug: string } | null,
+ workspaceError: false,
listFetched: true,
wsList: [] as { id: string; slug: string }[],
workspaceSeen: true,
@@ -48,7 +49,10 @@ vi.mock("@multica/core/workspace", async () => {
...actual,
workspaceBySlugOptions: () => ({
queryKey: ["workspace-by-slug"],
- queryFn: async () => state.workspace,
+ queryFn: async () => {
+ if (state.workspaceError) throw new Error("temporary failure");
+ return state.workspace;
+ },
}),
workspaceListOptions: () => ({
queryKey: ["workspace-list"],
@@ -119,7 +123,7 @@ function renderLayout() {
// synchronously — the real hook reads from cache.
qc.setQueryData(["workspace-by-slug"], state.workspace);
qc.setQueryData(["workspace-list"], state.wsList);
- return render(
+ const result = render(
<QueryClientProvider client={qc}>
<MemoryRouter initialEntries={["/acme/issues"]}>
<Routes>
@@ -130,6 +134,7 @@ function renderLayout() {
</MemoryRouter>
</QueryClientProvider>,
);
+ return { ...result, queryClient: qc };
}
beforeEach(() => {
@@ -137,6 +142,7 @@ beforeEach(() => {
state.isAuthLoading = false;
state.overlay = null;
state.workspace = { id: "ws-1", slug: "acme" };
+ state.workspaceError = false;
state.listFetched = true;
state.wsList = [{ id: "ws-1", slug: "acme" }];
state.workspaceSeen = true;
@@ -158,6 +164,27 @@ describe("WorkspaceRouteLayout", () => {
expect(queryByTestId(state.modalAriaLabel)).toBeNull();
expect(state.modalRenders).toBe(0);
});
+
+ it("keeps workspace content mounted when a background refetch fails", async () => {
+ const { queryByTestId, queryClient } = renderLayout();
+ expect(queryByTestId("outlet")).not.toBeNull();
+
+ state.workspaceError = true;
+ await act(async () => {
+ await queryClient.refetchQueries({ queryKey: ["workspace-by-slug"] });
+ });
+
+ await waitFor(() => {
+ expect(queryClient.getQueryState(["workspace-by-slug"])?.status).toBe(
+ "error",
+ );
+ });
+ expect(queryClient.getQueryData(["workspace-by-slug"])).toEqual({
+ id: "ws-1",
+ slug: "acme",
+ });
+ expect(queryByTestId("outlet")).not.toBeNull();
+ });
});
/**
diff --git a/apps/desktop/src/renderer/src/components/workspace-route-layout.tsx b/apps/desktop/src/renderer/src/components/workspace-route-layout.tsx
index f82301732b..2fb8b44dcc 100644
--- a/apps/desktop/src/renderer/src/components/workspace-route-layout.tsx
+++ b/apps/desktop/src/renderer/src/components/workspace-route-layout.tsx
@@ -53,10 +53,13 @@ export function WorkspaceRouteLayout() {
// code and violated MUL-4741 invariant 1 (only the Coordinator navigates).
// The `!user` early return below keeps the defense without navigating.
- const { data: workspace, isFetched: listFetched } = useQuery({
+ const { data: workspace } = useQuery({
...workspaceBySlugOptions(workspaceSlug ?? ""),
enabled: !!user && !!workspaceSlug,
});
+ // A failed background refetch retains the last authoritative selection.
+ // Only undefined means the shared workspace list has never resolved.
+ const listReady = workspace !== undefined;
const { data: wsList } = useQuery({
...workspaceListOptions(),
@@ -93,13 +96,13 @@ export function WorkspaceRouteLayout() {
// inconsistent "tab in group X with path /" state.
useEffect(() => {
if (!user) return;
- if (!listFetched) return;
+ if (!listReady) return;
if (workspace) return;
if (hasBeenSeen) return; // active eviction in flight — let the other path win
if (!wsList) return;
const validSlugs = new Set(wsList.map((w) => w.slug));
useTabStore.getState().validateWorkspaceSlugs(validSlugs);
- }, [user, listFetched, workspace, hasBeenSeen, wsList]);
+ }, [user, listReady, workspace, hasBeenSeen, wsList]);
// Release the platform singleton when this layout's workspace stops
// resolving, and again when the layout unmounts. Nothing else owned that
@@ -112,11 +115,11 @@ export function WorkspaceRouteLayout() {
// singleton to the NEW slug — before running the outgoing one's cleanup, so
// an unguarded clear would wipe the workspace context that just arrived.
useEffect(() => {
- if (!listFetched) return;
+ if (!listReady) return;
if (workspace) return;
if (getCurrentSlug() !== workspaceSlug) return;
setCurrentWorkspace(null, null);
- }, [listFetched, workspace, workspaceSlug]);
+ }, [listReady, workspace, workspaceSlug]);
useEffect(() => {
return () => {
@@ -128,7 +131,7 @@ export function WorkspaceRouteLayout() {
if (isAuthLoading) return null;
if (!user) return null;
if (!workspaceSlug) return null;
- if (!listFetched) return null;
+ if (!listReady) return null;
if (!workspace) return null; // auto-heal effect above handles the cleanup
return (
diff --git a/apps/desktop/src/renderer/src/pages/auth-recovery.tsx b/apps/desktop/src/renderer/src/pages/auth-recovery.tsx
new file mode 100644
index 0000000000..47a0459acf
--- /dev/null
+++ b/apps/desktop/src/renderer/src/pages/auth-recovery.tsx
@@ -0,0 +1,44 @@
+import { useAuthStore } from "@multica/core/auth";
+import { Button } from "@multica/ui/components/ui/button";
+import { MulticaIcon } from "@multica/ui/components/common/multica-icon";
+import { useT } from "@multica/views/i18n";
+import { DragStrip } from "@multica/views/platform";
+
+export function DesktopAuthRecoveryPage({
+ onRetry,
+ isRetrying = false,
+}: {
+ onRetry?: () => void;
+ isRetrying?: boolean;
+}) {
+ const { t } = useT("auth");
+ const retryAuthentication = useAuthStore(
+ (state) => state.retryAuthentication,
+ );
+
+ return (
+ <div className="flex h-screen flex-col">
+ <DragStrip />
+ <div className="flex flex-1 items-center justify-center p-8">
+ <div className="flex max-w-sm flex-col items-center text-center">
+ <MulticaIcon bordered size="lg" />
+ <h1 className="mt-6 text-title font-semibold">
+ {t(($) => $.desktop.recovery.title)}
+ </h1>
+ <p className="mt-2 text-body text-muted-foreground">
+ {t(($) => $.desktop.recovery.description)}
+ </p>
+ <Button
+ className="mt-6"
+ disabled={isRetrying}
+ onClick={onRetry ?? retryAuthentication}
+ >
+ {isRetrying
+ ? t(($) => $.desktop.recovery.retrying)
+ : t(($) => $.desktop.recovery.retry)}
+ </Button>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/desktop/src/renderer/src/platform/auth-session-bridge.test.ts b/apps/desktop/src/renderer/src/platform/auth-session-bridge.test.ts
new file mode 100644
index 0000000000..0e4e7d0dd5
--- /dev/null
+++ b/apps/desktop/src/renderer/src/platform/auth-session-bridge.test.ts
@@ -0,0 +1,18 @@
+import { describe, expect, it } from "vitest";
+import { authSessionReportValue } from "./auth-session-bridge";
+
+describe("authSessionReportValue", () => {
+ it("reports definitive authenticated and unauthenticated transitions", () => {
+ expect(authSessionReportValue("authenticated", "user-1")).toBe("user-1");
+ expect(authSessionReportValue("unauthenticated", null)).toBeNull();
+ });
+
+ it("does not report transient startup states", () => {
+ expect(authSessionReportValue("authenticating", null)).toBeUndefined();
+ expect(authSessionReportValue("recovering", null)).toBeUndefined();
+ });
+
+ it("fails safely when authenticated state has no user", () => {
+ expect(authSessionReportValue("authenticated", null)).toBeUndefined();
+ });
+});
diff --git a/apps/desktop/src/renderer/src/platform/auth-session-bridge.tsx b/apps/desktop/src/renderer/src/platform/auth-session-bridge.tsx
new file mode 100644
index 0000000000..58674974fd
--- /dev/null
+++ b/apps/desktop/src/renderer/src/platform/auth-session-bridge.tsx
@@ -0,0 +1,31 @@
+import { useEffect } from "react";
+import { useAuthStore, type AuthStatus } from "@multica/core/auth";
+
+export function authSessionReportValue(
+ status: AuthStatus,
+ userId: string | null,
+): string | null | undefined {
+ if (status === "authenticated") return userId ?? undefined;
+ if (status === "unauthenticated") return null;
+ return undefined;
+}
+
+/**
+ * Keep the main process informed of definitive account transitions without
+ * sharing credentials between renderer processes. Recoverable startup errors
+ * deliberately emit nothing so issue windows and tab state remain intact.
+ */
+export function DesktopAuthSessionBridge() {
+ const userId = useAuthStore((state) => state.user?.id ?? null);
+ const status = useAuthStore((state) => state.status);
+
+ useEffect(() => {
+ const reportValue = authSessionReportValue(status, userId);
+ if (reportValue === undefined) return;
+ // Optional chaining keeps renderer HMR safe during the brief interval in
+ // which an old preload is still attached to the refreshed React tree.
+ window.desktopAPI.reportAuthSession?.(reportValue);
+ }, [status, userId]);
+
+ return null;
+}
diff --git a/apps/web/app/(auth)/onboarding/page.tsx b/apps/web/app/(auth)/onboarding/page.tsx
index cc0388234e..a48b1d1727 100644
--- a/apps/web/app/(auth)/onboarding/page.tsx
+++ b/apps/web/app/(auth)/onboarding/page.tsx
@@ -2,14 +2,13 @@
import { useEffect, useRef } from "react";
import { useRouter } from "next/navigation";
-import { useQuery } from "@tanstack/react-query";
import { useAuthStore } from "@multica/core/auth";
import {
paths,
resolvePostAuthDestination,
useHasOnboarded,
} from "@multica/core/paths";
-import { workspaceListOptions } from "@multica/core/workspace/queries";
+import { useWorkspaceList } from "@multica/core/workspace";
import { CliInstallInstructions, OnboardingFlow } from "@multica/views/onboarding";
/**
@@ -30,8 +29,7 @@ export default function OnboardingPage() {
const user = useAuthStore((s) => s.user);
const isLoading = useAuthStore((s) => s.isLoading);
const hasOnboarded = useHasOnboarded();
- const { data: workspaces = [], isFetched: workspacesFetched } = useQuery({
- ...workspaceListOptions(),
+ const { workspaces, ready: workspacesReady } = useWorkspaceList({
enabled: !!user,
});
// The bootstrap path calls refreshMe() before returning, which flips
@@ -48,7 +46,7 @@ export default function OnboardingPage() {
if (!isLoading && !user) router.replace(paths.login());
return;
}
- if (!workspacesFetched) return;
+ if (!workspacesReady) return;
if (completingRef.current) return;
// Bounce out only when onboarding genuinely doesn't apply: the user is
// already onboarded. We deliberately don't bounce on `workspaces.length`
@@ -60,7 +58,7 @@ export default function OnboardingPage() {
if (hasOnboarded) {
router.replace(resolvePostAuthDestination(workspaces, hasOnboarded));
}
- }, [isLoading, user, hasOnboarded, workspacesFetched, workspaces, router]);
+ }, [isLoading, user, hasOnboarded, workspacesReady, workspaces, router]);
if (isLoading || !user || hasOnboarded) return null;
diff --git a/apps/web/app/[workspaceSlug]/layout.test.tsx b/apps/web/app/[workspaceSlug]/layout.test.tsx
new file mode 100644
index 0000000000..ecbe2a8af7
--- /dev/null
+++ b/apps/web/app/[workspaceSlug]/layout.test.tsx
@@ -0,0 +1,132 @@
+import { Suspense, type ReactNode } from "react";
+import { render, screen, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const state = vi.hoisted(() => ({
+ user: {
+ id: "user-1",
+ onboarded_at: "2026-01-01T00:00:00Z",
+ } as { id: string; onboarded_at: string | null } | null,
+ isAuthLoading: false,
+ workspace: null as { id: string; slug: string } | null,
+ workspaceError: false,
+ hasBeenSeen: false,
+ replace: vi.fn(),
+}));
+
+vi.mock("next/navigation", () => ({
+ useRouter: () => ({ replace: state.replace }),
+}));
+
+vi.mock("@multica/core/auth", () => ({
+ useAuthStore: (
+ selector: (auth: {
+ user: typeof state.user;
+ isLoading: boolean;
+ }) => unknown,
+ ) => selector({ user: state.user, isLoading: state.isAuthLoading }),
+}));
+
+vi.mock("@multica/core/workspace", () => ({
+ workspaceBySlugOptions: () => ({
+ queryKey: ["workspace-by-slug", "acme"],
+ queryFn: async () => {
+ if (state.workspaceError) throw new Error("temporary failure");
+ return state.workspace;
+ },
+ }),
+}));
+
+vi.mock("@multica/core/paths", () => ({
+ WorkspaceSlugProvider: ({ children }: { children: ReactNode }) => (
+ <>{children}</>
+ ),
+ paths: {
+ login: () => "/login",
+ onboarding: () => "/onboarding",
+ },
+}));
+
+vi.mock("@multica/core/platform", () => ({
+ setCurrentWorkspace: vi.fn(),
+}));
+
+vi.mock("@multica/views/workspace/no-access-page", () => ({
+ NoAccessPage: () => <div data-testid="no-access" />,
+}));
+
+vi.mock("@multica/views/workspace/welcome-after-onboarding", () => ({
+ WelcomeAfterOnboarding: () => null,
+}));
+
+vi.mock("@multica/views/workspace/use-workspace-seen", () => ({
+ useWorkspaceSeen: () => state.hasBeenSeen,
+}));
+
+vi.mock("@multica/ui/components/common/multica-icon", () => ({
+ MulticaIcon: () => <div data-testid="workspace-loading" />,
+}));
+
+import WorkspaceLayout from "./layout";
+
+function renderLayout() {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false, gcTime: Infinity } },
+ });
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
+ );
+ const resolvedParams = Object.assign(
+ Promise.resolve({ workspaceSlug: "acme" }),
+ {
+ status: "fulfilled",
+ value: { workspaceSlug: "acme" },
+ },
+ );
+ const result = render(
+ <Suspense fallback={<div data-testid="route-loading" />}>
+ <WorkspaceLayout
+ params={resolvedParams}
+ >
+ <div data-testid="workspace-content" />
+ </WorkspaceLayout>
+ </Suspense>,
+ { wrapper },
+ );
+ return { ...result, queryClient };
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ state.user = {
+ id: "user-1",
+ onboarded_at: "2026-01-01T00:00:00Z",
+ };
+ state.isAuthLoading = false;
+ state.workspace = null;
+ state.workspaceError = false;
+ state.hasBeenSeen = false;
+});
+
+describe("WorkspaceLayout", () => {
+ it("keeps loading instead of showing NoAccess when the initial list request fails", async () => {
+ state.workspaceError = true;
+ const { queryClient } = renderLayout();
+
+ await waitFor(() => {
+ expect(
+ queryClient.getQueryState(["workspace-by-slug", "acme"])?.status,
+ ).toBe("error");
+ });
+ expect(screen.queryByTestId("no-access")).toBeNull();
+ expect(screen.getByTestId("workspace-loading")).toBeInTheDocument();
+ });
+
+ it("shows NoAccess only after an authoritative list omits the slug", async () => {
+ renderLayout();
+
+ expect(await screen.findByTestId("no-access")).toBeInTheDocument();
+ expect(screen.queryByTestId("workspace-loading")).toBeNull();
+ });
+});
diff --git a/apps/web/app/[workspaceSlug]/layout.tsx b/apps/web/app/[workspaceSlug]/layout.tsx
index e0b9d00b93..cb92f72503 100644
--- a/apps/web/app/[workspaceSlug]/layout.tsx
+++ b/apps/web/app/[workspaceSlug]/layout.tsx
@@ -44,9 +44,10 @@ export default function WorkspaceLayout({
}
}, [user, router]);
- // Resolve workspace by slug from the React Query list cache.
- // Enabled only when user is authenticated — otherwise the list query isn't seeded.
- const { data: workspace, isFetched: listFetched } = useQuery({
+ // Resolve workspace by slug through the shared workspace-list query. A
+ // warm auth bootstrap reuses its cache; a cold route fetches it directly.
+ // Keep it disabled until identity has been verified.
+ const { data: workspace } = useQuery({
...workspaceBySlugOptions(workspaceSlug),
enabled: !!user,
});
@@ -84,8 +85,11 @@ export default function WorkspaceLayout({
// Don't render children until workspace is resolved. useWorkspaceId()
// throws when the list hasn't populated or the slug is unknown — gating
// here makes that invariant hold for every descendant.
- if (!listFetched) return loadingIndicator;
- if (!workspace) {
+ // The selector returns undefined until the list has resolved, including
+ // after an initial request failure. It returns null only when an
+ // authoritative list does not contain this slug.
+ if (workspace === undefined) return loadingIndicator;
+ if (workspace === null) {
// If we've resolved this slug before in this session, it was just
// removed from our list (deleted/left/evicted). A navigate is almost
// certainly in flight — render null to avoid a NoAccessPage flash.
diff --git a/apps/web/features/landing/components/redirect-if-authenticated.test.tsx b/apps/web/features/landing/components/redirect-if-authenticated.test.tsx
new file mode 100644
index 0000000000..1cdf8e85c0
--- /dev/null
+++ b/apps/web/features/landing/components/redirect-if-authenticated.test.tsx
@@ -0,0 +1,66 @@
+import { render, waitFor } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const state = vi.hoisted(() => ({
+ user: { id: "user-1" } as { id: string } | null,
+ isLoading: false,
+ workspaces: [] as { id: string; slug: string }[],
+ ready: false,
+ replace: vi.fn(),
+}));
+
+vi.mock("next/navigation", () => ({
+ useRouter: () => ({ replace: state.replace }),
+}));
+
+vi.mock("@multica/core/auth", () => ({
+ useAuthStore: (
+ selector: (auth: { user: typeof state.user; isLoading: boolean }) => unknown,
+ ) => selector({ user: state.user, isLoading: state.isLoading }),
+}));
+
+vi.mock("@multica/core/workspace", () => ({
+ useWorkspaceList: () => ({
+ workspaces: state.workspaces,
+ ready: state.ready,
+ }),
+}));
+
+vi.mock("@multica/core/paths", () => ({
+ useHasOnboarded: () => true,
+ resolvePostAuthDestination: (workspaces: { slug: string }[]) =>
+ workspaces[0] ? `/${workspaces[0].slug}/issues` : "/workspaces/new",
+}));
+
+vi.mock("@/lib/public-host", () => ({
+ isOfficialMarketingHost: () => false,
+}));
+
+import { RedirectIfAuthenticated } from "./redirect-if-authenticated";
+
+beforeEach(() => {
+ state.user = { id: "user-1" };
+ state.isLoading = false;
+ state.workspaces = [];
+ state.ready = false;
+ state.replace.mockReset();
+});
+
+describe("RedirectIfAuthenticated", () => {
+ it("does not redirect after an initial workspace-list failure", () => {
+ render(<RedirectIfAuthenticated />);
+
+ expect(state.replace).not.toHaveBeenCalled();
+ });
+
+ it("redirects only after an authoritative workspace list arrives", async () => {
+ state.ready = true;
+ state.workspaces = [{ id: "ws-1", slug: "acme" }];
+
+ render(<RedirectIfAuthenticated />);
+
+ await waitFor(() => {
+ expect(state.replace).toHaveBeenCalledWith("/acme/issues");
+ });
+ });
+});
diff --git a/apps/web/features/landing/components/redirect-if-authenticated.tsx b/apps/web/features/landing/components/redirect-if-authenticated.tsx
index 3438b9a25e..8e9a74799a 100644
--- a/apps/web/features/landing/components/redirect-if-authenticated.tsx
+++ b/apps/web/features/landing/components/redirect-if-authenticated.tsx
@@ -2,9 +2,8 @@
import { useEffect } from "react";
import { useRouter } from "next/navigation";
-import { useQuery } from "@tanstack/react-query";
import { useAuthStore } from "@multica/core/auth";
-import { workspaceListOptions } from "@multica/core/workspace";
+import { useWorkspaceList } from "@multica/core/workspace";
import { resolvePostAuthDestination, useHasOnboarded } from "@multica/core/paths";
import { isOfficialMarketingHost } from "@/lib/public-host";
@@ -30,16 +29,13 @@ export function RedirectIfAuthenticated() {
const isLoading = useAuthStore((s) => s.isLoading);
const hasOnboarded = useHasOnboarded();
- const { data: list = [], isFetched } = useQuery({
- ...workspaceListOptions(),
- enabled: !!user,
- });
+ const { workspaces, ready } = useWorkspaceList({ enabled: !!user });
useEffect(() => {
- if (isLoading || !user || !isFetched) return;
+ if (isLoading || !user || !ready) return;
if (isOfficialMarketingHost(window.location.hostname)) return;
- router.replace(resolvePostAuthDestination(list, hasOnboarded));
- }, [isLoading, user, isFetched, list, hasOnboarded, router]);
+ router.replace(resolvePostAuthDestination(workspaces, hasOnboarded));
+ }, [isLoading, user, ready, workspaces, hasOnboarded, router]);
return null;
}
diff --git a/apps/web/features/landing/utils/use-dashboard-cta.test.ts b/apps/web/features/landing/utils/use-dashboard-cta.test.ts
index 1e5faa8fbc..d48e72b73d 100644
--- a/apps/web/features/landing/utils/use-dashboard-cta.test.ts
+++ b/apps/web/features/landing/utils/use-dashboard-cta.test.ts
@@ -21,7 +21,7 @@ function makeWs(slug: string): Workspace {
const fetched = (workspaces: Workspace[], hasOnboarded = true) => ({
isAuthenticated: true,
- isWorkspaceListFetched: true,
+ workspaceListReady: true,
workspaces,
hasOnboarded,
});
@@ -31,8 +31,8 @@ describe("resolveDashboardCtaHref", () => {
expect(
resolveDashboardCtaHref({
isAuthenticated: false,
- isWorkspaceListFetched: false,
- workspaces: undefined,
+ workspaceListReady: false,
+ workspaces: [],
hasOnboarded: false,
}),
).toBe(paths.login());
@@ -57,17 +57,14 @@ describe("resolveDashboardCtaHref", () => {
expect(resolveDashboardCtaHref(fetched([]))).toBe(paths.newWorkspace());
});
- it.each([
- ["the list has not resolved yet", false, undefined],
- ["the list resolved as undefined", true, undefined],
- ])("falls back to /issues while %s", (_label, isWorkspaceListFetched, workspaces) => {
+ it("falls back to /issues while the list has not resolved yet", () => {
// /issues is a legacy route the proxy rewrites to the last workspace, so
// the button still works during hydration. It must not fall back to `/`,
// which is what made the CTA dead in the first place.
const href = resolveDashboardCtaHref({
isAuthenticated: true,
- isWorkspaceListFetched,
- workspaces,
+ workspaceListReady: false,
+ workspaces: [],
hasOnboarded: true,
});
expect(href).toBe("/issues");
diff --git a/apps/web/features/landing/utils/use-dashboard-cta.ts b/apps/web/features/landing/utils/use-dashboard-cta.ts
index 943fae4a78..4424767a43 100644
--- a/apps/web/features/landing/utils/use-dashboard-cta.ts
+++ b/apps/web/features/landing/utils/use-dashboard-cta.ts
@@ -1,8 +1,7 @@
"use client";
-import { useQuery } from "@tanstack/react-query";
import { useAuthStore } from "@multica/core/auth";
-import { workspaceListOptions } from "@multica/core/workspace";
+import { useWorkspaceList } from "@multica/core/workspace";
import {
paths,
resolvePostAuthDestination,
@@ -21,17 +20,17 @@ const LOADING_FALLBACK_HREF = "/issues";
export function resolveDashboardCtaHref({
isAuthenticated,
- isWorkspaceListFetched,
+ workspaceListReady,
workspaces,
hasOnboarded,
}: {
isAuthenticated: boolean;
- isWorkspaceListFetched: boolean;
- workspaces: Workspace[] | undefined;
+ workspaceListReady: boolean;
+ workspaces: Workspace[];
hasOnboarded: boolean;
}): string {
if (!isAuthenticated) return paths.login();
- if (!isWorkspaceListFetched || !workspaces) return LOADING_FALLBACK_HREF;
+ if (!workspaceListReady) return LOADING_FALLBACK_HREF;
return resolvePostAuthDestination(workspaces, hasOnboarded);
}
@@ -54,15 +53,12 @@ export function useDashboardCtaHref(): string {
const user = useAuthStore((s) => s.user);
const hasOnboarded = useHasOnboarded();
- const { data, isFetched } = useQuery({
- ...workspaceListOptions(),
- enabled: !!user,
- });
+ const { workspaces, ready } = useWorkspaceList({ enabled: !!user });
return resolveDashboardCtaHref({
isAuthenticated: !!user,
- isWorkspaceListFetched: isFetched,
- workspaces: data,
+ workspaceListReady: ready,
+ workspaces,
hasOnboarded,
});
}
diff --git a/packages/core/auth/index.ts b/packages/core/auth/index.ts
index 2247bca533..1bb48c56fc 100644
--- a/packages/core/auth/index.ts
+++ b/packages/core/auth/index.ts
@@ -1,5 +1,5 @@
export { createAuthStore } from "./store";
-export type { AuthStoreOptions, AuthState } from "./store";
+export type { AuthStoreOptions, AuthState, AuthStatus } from "./store";
export { sanitizeNextUrl } from "./utils";
import type { createAuthStore as CreateAuthStoreFn } from "./store";
diff --git a/packages/core/auth/store.test.ts b/packages/core/auth/store.test.ts
index 20a2516948..3eaf6052a1 100644
--- a/packages/core/auth/store.test.ts
+++ b/packages/core/auth/store.test.ts
@@ -1,6 +1,5 @@
import { describe, expect, it, vi } from "vitest";
import type { ApiClient } from "../api/client";
-import { ApiError } from "../api/client";
import type { StorageAdapter, User } from "../types";
import { createAuthStore } from "./store";
@@ -27,67 +26,38 @@ function makeStorage(initial: Record<string, string> = {}): StorageAdapter & {
};
}
-function makeApi(getMe: () => Promise<User>): ApiClient {
+function makeApi(): ApiClient {
return {
setToken: vi.fn(),
- getMe,
- // Only the methods touched by store.initialize are needed. Cast to
- // ApiClient for type compatibility — the store treats it opaquely.
} as unknown as ApiClient;
}
-describe("authStore.initialize — token mode", () => {
- it("keeps the stored token when getMe fails with a non-401 ApiError (e.g. 500)", async () => {
+describe("authStore", () => {
+ it("publishes a retry request instead of silently ignoring it", () => {
const storage = makeStorage({ multica_token: "t" });
- const api = makeApi(() =>
- Promise.reject(new ApiError("server error", 500, "Internal Server Error")),
- );
+ const api = makeApi();
const store = createAuthStore({ api, storage });
- await store.getState().initialize();
+ store.setState({ isLoading: true, status: "recovering" });
+ store.getState().retryAuthentication();
- expect(store.getState().user).toBeNull();
- expect(store.getState().isLoading).toBe(false);
- expect(storage.snapshot().multica_token).toBe("t");
+ expect(store.getState().status).toBe("authenticating");
+ expect(store.getState().retryGeneration).toBe(1);
});
- it("keeps the stored token on a network failure (non-ApiError throw)", async () => {
+ it("explicit logout still clears credentials and publishes unauthenticated state", () => {
const storage = makeStorage({ multica_token: "t" });
- const api = makeApi(() => Promise.reject(new TypeError("fetch failed")));
- const store = createAuthStore({ api, storage });
-
- await store.getState().initialize();
-
- expect(store.getState().user).toBeNull();
- expect(storage.snapshot().multica_token).toBe("t");
- });
-
- it("on 401, leaves storage cleanup to ApiClient.onUnauthorized and resets state", async () => {
- // Simulate the real path: ApiClient fires onUnauthorized on 401, which
- // removes the token from storage. The store's catch block must not
- // duplicate or short-circuit this — it should only reset in-memory
- // auth state.
- const storage = makeStorage({ multica_token: "t" });
- const api = makeApi(() => {
- storage.removeItem("multica_token"); // stand-in for onUnauthorized
- return Promise.reject(new ApiError("unauthorized", 401, "Unauthorized"));
- });
- const store = createAuthStore({ api, storage });
+ const api = makeApi();
+ const onLogout = vi.fn();
+ const store = createAuthStore({ api, storage, onLogout });
- await store.getState().initialize();
+ store.setState({ user: fakeUser, status: "authenticated", isLoading: false });
+ store.getState().logout();
- expect(store.getState().user).toBeNull();
expect(storage.snapshot().multica_token).toBeUndefined();
- });
-
- it("populates user when getMe succeeds", async () => {
- const storage = makeStorage({ multica_token: "t" });
- const api = makeApi(() => Promise.resolve(fakeUser));
- const store = createAuthStore({ api, storage });
-
- await store.getState().initialize();
-
- expect(store.getState().user).toEqual(fakeUser);
- expect(storage.snapshot().multica_token).toBe("t");
+ expect(api.setToken).toHaveBeenCalledWith(null);
+ expect(onLogout).toHaveBeenCalledOnce();
+ expect(store.getState().user).toBeNull();
+ expect(store.getState().status).toBe("unauthenticated");
});
});
diff --git a/packages/core/auth/store.ts b/packages/core/auth/store.ts
index a5fd472f97..9e81d655c3 100644
--- a/packages/core/auth/store.ts
+++ b/packages/core/auth/store.ts
@@ -1,7 +1,7 @@
import { create } from "zustand";
import type { User, StorageAdapter } from "../types";
import { identify as identifyAnalytics, resetAnalytics } from "../analytics";
-import { ApiError, type ApiClient } from "../api/client";
+import type { ApiClient } from "../api/client";
import { setCurrentWorkspace } from "../platform/workspace-storage";
export interface AuthStoreOptions {
@@ -13,11 +13,19 @@ export interface AuthStoreOptions {
cookieAuth?: boolean;
}
+export type AuthStatus =
+ | "authenticating"
+ | "authenticated"
+ | "unauthenticated"
+ | "recovering";
+
export interface AuthState {
user: User | null;
isLoading: boolean;
+ status: AuthStatus;
+ retryGeneration: number;
- initialize: () => Promise<void>;
+ retryAuthentication: () => void;
sendCode: (email: string) => Promise<void>;
verifyCode: (email: string, code: string) => Promise<User>;
loginWithGoogle: (code: string, redirectUri: string) => Promise<User>;
@@ -33,45 +41,15 @@ export function createAuthStore(options: AuthStoreOptions) {
return create<AuthState>((set) => ({
user: null,
isLoading: true,
-
- initialize: async () => {
- if (cookieAuth) {
- // In cookie mode, the HttpOnly cookie is sent automatically.
- // Try to fetch the current user — if the cookie exists the server will accept it.
- try {
- const user = await api.getMe();
- set({ user, isLoading: false });
- } catch {
- set({ user: null, isLoading: false });
- }
- return;
- }
-
- // Token mode: read from localStorage (Electron / legacy).
- const token = storage.getItem("multica_token");
- if (!token) {
- set({ isLoading: false });
- return;
- }
-
- api.setToken(token);
-
- try {
- const user = await api.getMe();
- set({ user, isLoading: false });
- } catch (err) {
- // Only clear the stored token on a genuine auth failure (401). For
- // transient errors — network blips, backend rolling restarts, 5xx,
- // aborted fetches — keep the token so the next initialize() (next
- // page load or focus-refresh) can retry. The 401 path's token
- // cleanup is handled upstream by ApiClient.handleUnauthorized via
- // the onUnauthorized callback; we only need to reset the in-memory
- // user + workspace state here.
- if (err instanceof ApiError && err.status === 401) {
- setCurrentWorkspace(null, null);
- }
- set({ user: null, isLoading: false });
- }
+ status: "authenticating",
+ retryGeneration: 0,
+
+ retryAuthentication: () => {
+ set((state) => ({
+ isLoading: true,
+ status: "authenticating",
+ retryGeneration: state.retryGeneration + 1,
+ }));
},
sendCode: async (email: string) => {
@@ -87,7 +65,7 @@ export function createAuthStore(options: AuthStoreOptions) {
}
onLogin?.();
identifyAnalytics(user.id, { email: user.email, name: user.name });
- set({ user });
+ set({ user, isLoading: false, status: "authenticated" });
return user;
},
@@ -99,7 +77,7 @@ export function createAuthStore(options: AuthStoreOptions) {
}
onLogin?.();
identifyAnalytics(user.id, { email: user.email, name: user.name });
- set({ user });
+ set({ user, isLoading: false, status: "authenticated" });
return user;
},
@@ -109,7 +87,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 });
+ set({ user, isLoading: false, status: "authenticated" });
return user;
},
@@ -123,16 +101,16 @@ export function createAuthStore(options: AuthStoreOptions) {
setCurrentWorkspace(null, null);
resetAnalytics();
onLogout?.();
- set({ user: null });
+ set({ user: null, isLoading: false, status: "unauthenticated" });
},
setUser: (user: User) => {
- set({ user });
+ set({ user, isLoading: false, status: "authenticated" });
},
refreshMe: async () => {
const user = await api.getMe();
- set({ user });
+ set({ user, isLoading: false, status: "authenticated" });
},
}));
}
diff --git a/packages/core/platform/auth-initializer.test.tsx b/packages/core/platform/auth-initializer.test.tsx
new file mode 100644
index 0000000000..4ee9a4dea0
--- /dev/null
+++ b/packages/core/platform/auth-initializer.test.tsx
@@ -0,0 +1,289 @@
+/**
+ * @vitest-environment jsdom
+ */
+import { act, render, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { setApiInstance } from "../api";
+import { ApiError, type ApiClient } from "../api/client";
+import {
+ createAuthStore,
+ registerAuthStore,
+ useAuthStore,
+} from "../auth";
+import type { StorageAdapter, User, Workspace } from "../types";
+import { workspaceKeys } from "../workspace/queries";
+import { AuthInitializer } from "./auth-initializer";
+
+const logger = vi.hoisted(() => ({
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+}));
+
+vi.mock("../logger", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("../logger")>();
+ return { ...actual, createLogger: () => logger };
+});
+
+vi.mock("../analytics", () => ({
+ captureSignupSource: vi.fn(),
+ identify: vi.fn(),
+ initAnalytics: vi.fn(),
+ resetAnalytics: vi.fn(),
+}));
+
+const fakeUser = {
+ id: "user-1",
+ name: "Alice",
+ email: "[email protected]",
+ avatar_url: null,
+} as User;
+
+const fakeWorkspaces = [{ id: "ws-1", slug: "acme" }] as Workspace[];
+
+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];
+ },
+ snapshot: () => ({ ...values }),
+ };
+}
+
+function makeApi(overrides: Partial<ApiClient> = {}): ApiClient {
+ return {
+ getConfig: vi.fn().mockResolvedValue({}),
+ getMe: vi.fn().mockResolvedValue(fakeUser),
+ listWorkspaces: vi.fn().mockResolvedValue(fakeWorkspaces),
+ setToken: vi.fn(),
+ ...overrides,
+ } as unknown as ApiClient;
+}
+
+function renderInitializer({
+ api,
+ storage = makeStorage({ multica_token: "token-1" }),
+ cookieAuth = false,
+ platform = "desktop",
+}: {
+ api: ApiClient;
+ storage?: StorageAdapter;
+ cookieAuth?: boolean;
+ platform?: "desktop" | "web";
+}) {
+ const onLogin = vi.fn();
+ const onLogout = vi.fn();
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false, gcTime: Infinity } },
+ });
+ setApiInstance(api);
+ registerAuthStore(
+ createAuthStore({ api, storage, cookieAuth, onLogin, onLogout }),
+ );
+
+ const result = render(
+ <QueryClientProvider client={queryClient}>
+ <AuthInitializer
+ cookieAuth={cookieAuth}
+ identity={{ platform }}
+ onLogin={onLogin}
+ onLogout={onLogout}
+ storage={storage}
+ >
+ <div>child</div>
+ </AuthInitializer>
+ </QueryClientProvider>,
+ );
+
+ return { ...result, onLogin, onLogout, queryClient };
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe("AuthInitializer recovery", () => {
+ it("keeps the token and recovers on the online event after a network failure", async () => {
+ const storage = makeStorage({ multica_token: "token-1" });
+ const getMe = vi
+ .fn()
+ .mockRejectedValueOnce(new TypeError("fetch failed"))
+ .mockResolvedValue(fakeUser);
+ const api = makeApi({ getMe });
+ const { onLogout } = renderInitializer({ api, storage });
+
+ await waitFor(() => {
+ expect(useAuthStore.getState().status).toBe("recovering");
+ });
+ expect(storage.snapshot().multica_token).toBe("token-1");
+ expect(onLogout).not.toHaveBeenCalled();
+
+ act(() => window.dispatchEvent(new Event("online")));
+
+ await waitFor(() => {
+ expect(useAuthStore.getState().user).toEqual(fakeUser);
+ });
+ expect(getMe).toHaveBeenCalledTimes(2);
+ expect(onLogout).not.toHaveBeenCalled();
+ });
+
+ it("lets a manual retry restart a recoverable auth attempt", async () => {
+ const getMe = vi
+ .fn()
+ .mockRejectedValueOnce(new ApiError("unavailable", 503, "Unavailable"))
+ .mockResolvedValue(fakeUser);
+ const api = makeApi({ getMe });
+ const { onLogout } = renderInitializer({ api });
+
+ await waitFor(() => {
+ expect(useAuthStore.getState().status).toBe("recovering");
+ });
+ act(() => useAuthStore.getState().retryAuthentication());
+
+ await waitFor(() => {
+ expect(useAuthStore.getState().status).toBe("authenticated");
+ });
+ expect(getMe).toHaveBeenCalledTimes(2);
+ expect(onLogout).not.toHaveBeenCalled();
+ });
+
+ it("continues automatic retries at the capped backoff interval", async () => {
+ vi.useFakeTimers();
+ const getMe = vi.fn().mockRejectedValue(new TypeError("still offline"));
+ const api = makeApi({ getMe });
+ const { onLogout } = renderInitializer({ api });
+
+ await act(async () => {
+ await Promise.resolve();
+ });
+ expect(useAuthStore.getState().status).toBe("recovering");
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(31_000);
+ });
+ expect(getMe).toHaveBeenCalledTimes(6);
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(30_000);
+ });
+ expect(getMe).toHaveBeenCalledTimes(7);
+ expect(logger.error).toHaveBeenCalledTimes(1);
+ expect(onLogout).not.toHaveBeenCalled();
+ });
+
+ it("does not invalidate a verified desktop session when workspace loading fails", async () => {
+ const listWorkspaces = vi
+ .fn()
+ .mockRejectedValue(new TypeError("network unavailable"));
+ const api = makeApi({ listWorkspaces });
+ const { onLogout, queryClient } = renderInitializer({ api });
+
+ await waitFor(() => {
+ expect(useAuthStore.getState().status).toBe("authenticated");
+ expect(
+ queryClient.getQueryState(workspaceKeys.list())?.status,
+ ).toBe("error");
+ });
+ expect(useAuthStore.getState().user).toEqual(fakeUser);
+ expect(onLogout).not.toHaveBeenCalled();
+ });
+
+ it("publishes web auth independently when workspace loading fails", async () => {
+ const listWorkspaces = vi
+ .fn()
+ .mockRejectedValue(new TypeError("backend restarting"));
+ const api = makeApi({ listWorkspaces });
+ const { onLogout, queryClient } = renderInitializer({
+ api,
+ cookieAuth: true,
+ platform: "web",
+ });
+
+ await waitFor(() => {
+ expect(useAuthStore.getState().status).toBe("authenticated");
+ expect(queryClient.getQueryState(workspaceKeys.list())?.status).toBe(
+ "error",
+ );
+ });
+ expect(useAuthStore.getState().user).toEqual(fakeUser);
+ expect(onLogout).not.toHaveBeenCalled();
+ });
+
+ it("reloads app config after auth recovers from a transient failure", async () => {
+ const getConfig = vi
+ .fn()
+ .mockRejectedValueOnce(new TypeError("network unavailable"))
+ .mockResolvedValue({ feature_flags: { recovered: true } });
+ const getMe = vi
+ .fn()
+ .mockRejectedValueOnce(new TypeError("network unavailable"))
+ .mockResolvedValue(fakeUser);
+ const api = makeApi({ getConfig, getMe });
+ renderInitializer({ api });
+
+ await waitFor(() => {
+ expect(useAuthStore.getState().status).toBe("recovering");
+ });
+ act(() => useAuthStore.getState().retryAuthentication());
+
+ await waitFor(() => {
+ expect(useAuthStore.getState().status).toBe("authenticated");
+ expect(getConfig).toHaveBeenCalledTimes(2);
+ });
+ });
+
+ it("keeps retrying app config until it loads", async () => {
+ vi.useFakeTimers();
+ const getConfig = vi
+ .fn()
+ .mockRejectedValueOnce(new TypeError("network unavailable"))
+ .mockRejectedValueOnce(new TypeError("still unavailable"))
+ .mockResolvedValue({ feature_flags: { recovered: true } });
+ const api = makeApi({ getConfig });
+ renderInitializer({ api });
+
+ await act(async () => {
+ await Promise.resolve();
+ });
+ expect(getConfig).toHaveBeenCalledTimes(1);
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(3_000);
+ });
+ expect(getConfig).toHaveBeenCalledTimes(3);
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(60_000);
+ });
+ expect(getConfig).toHaveBeenCalledTimes(3);
+ });
+
+ it("publishes a definitive logout for a genuine 401", async () => {
+ const storage = makeStorage({ multica_token: "token-1" });
+ const getMe = vi.fn().mockImplementation(() => {
+ storage.removeItem("multica_token");
+ return Promise.reject(new ApiError("unauthorized", 401, "Unauthorized"));
+ });
+ const api = makeApi({ getMe });
+ const { onLogout } = renderInitializer({ api, storage });
+
+ await waitFor(() => {
+ expect(useAuthStore.getState().status).toBe("unauthenticated");
+ });
+ expect(storage.snapshot().multica_token).toBeUndefined();
+ expect(onLogout).toHaveBeenCalledOnce();
+ });
+});
diff --git a/packages/core/platform/auth-initializer.tsx b/packages/core/platform/auth-initializer.tsx
index 8bdf65d423..1e15e93317 100644
--- a/packages/core/platform/auth-initializer.tsx
+++ b/packages/core/platform/auth-initializer.tsx
@@ -1,8 +1,9 @@
"use client";
-import { useEffect, type ReactNode } from "react";
+import { useCallback, useEffect, useRef, type ReactNode } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { getApi } from "../api";
+import { ApiError } from "../api/client";
import { useAuthStore } from "../auth";
import {
captureSignupSource,
@@ -11,7 +12,7 @@ import {
resetAnalytics,
} from "../analytics";
import { configStore } from "../config";
-import { workspaceKeys } from "../workspace/queries";
+import { workspaceListOptions } from "../workspace/queries";
import { createLogger } from "../logger";
import { defaultStorage } from "./storage";
import { setCurrentWorkspace } from "./workspace-storage";
@@ -20,6 +21,14 @@ import type { StorageAdapter } from "../types/storage";
import type { User } from "../types";
const logger = createLogger("auth");
+const RECOVERY_RETRY_DELAYS_MS = [
+ 1_000,
+ 2_000,
+ 4_000,
+ 8_000,
+ 16_000,
+ 30_000,
+] as const;
export function AuthInitializer({
children,
@@ -37,16 +46,17 @@ export function AuthInitializer({
identity?: ClientIdentity;
}) {
const qc = useQueryClient();
+ const retryGeneration = useAuthStore((state) => state.retryGeneration);
+ const configLoadedRef = useRef(false);
+ const configRequestRef = useRef<Promise<boolean> | null>(null);
+ const authRecoveryPendingRef = useRef(false);
+ const retryConfigRef = useRef<() => void>(() => {});
- useEffect(() => {
- const api = getApi();
+ const loadConfig = useCallback((): Promise<boolean> => {
+ if (configLoadedRef.current) return Promise.resolve(true);
+ if (configRequestRef.current) return configRequestRef.current;
- // Stamp attribution before anything else — the signup event (server-side)
- // reads this cookie, so it has to be present before the user hits submit.
- captureSignupSource();
-
- // Fetch app config (CDN domain, PostHog key, …) in the background — non-blocking.
- api
+ const request = getApi()
.getConfig()
.then((cfg) => {
if (cfg.cdn_domain) {
@@ -79,69 +89,252 @@ export function AuthInitializer({
environment: cfg.analytics_environment,
});
}
+ configLoadedRef.current = true;
+ return true;
})
- .catch(() => {
- /* config is optional — legacy file card matching degrades gracefully */
+ .catch(() => false)
+ .finally(() => {
+ configRequestRef.current = null;
});
+ configRequestRef.current = request;
+ return request;
+ }, [identity?.version]);
+
+ useEffect(() => {
+ // Stamp attribution before anything else — the signup event (server-side)
+ // reads this cookie, so it has to be present before the user hits submit.
+ captureSignupSource();
+
+ // Configuration is optional for startup, but an offline boot must still
+ // self-heal once connectivity returns. Keep retries rate-limited at the
+ // same 30-second ceiling as auth and accelerate them on `online`.
+ let cancelled = false;
+ let inFlight = false;
+ let retryAfterFlight = false;
+ let retryIndex = 0;
+ let retryTimer: ReturnType<typeof setTimeout> | undefined;
+
+ const attempt = async () => {
+ if (cancelled || configLoadedRef.current) return;
+ if (retryTimer !== undefined) {
+ clearTimeout(retryTimer);
+ retryTimer = undefined;
+ }
+ if (inFlight) {
+ retryAfterFlight = true;
+ return;
+ }
+
+ inFlight = true;
+ const loaded = await loadConfig();
+ inFlight = false;
+ if (cancelled) return;
+ if (loaded) {
+ window.removeEventListener("online", retryNow);
+ return;
+ }
+ if (retryAfterFlight) {
+ retryAfterFlight = false;
+ void attempt();
+ return;
+ }
+
+ const delay = RECOVERY_RETRY_DELAYS_MS[retryIndex];
+ retryIndex = Math.min(
+ retryIndex + 1,
+ RECOVERY_RETRY_DELAYS_MS.length - 1,
+ );
+ retryTimer = setTimeout(() => {
+ retryTimer = undefined;
+ void attempt();
+ }, delay);
+ };
+
+ const retryNow = () => {
+ if (cancelled || configLoadedRef.current) return;
+ retryIndex = 0;
+ if (retryTimer !== undefined) {
+ clearTimeout(retryTimer);
+ retryTimer = undefined;
+ }
+ if (inFlight) {
+ retryAfterFlight = true;
+ return;
+ }
+ void attempt();
+ };
+
+ retryConfigRef.current = retryNow;
+ window.addEventListener("online", retryNow);
+ void attempt();
+
+ return () => {
+ cancelled = true;
+ retryConfigRef.current = () => {};
+ window.removeEventListener("online", retryNow);
+ if (retryTimer !== undefined) clearTimeout(retryTimer);
+ };
+ }, [loadConfig]);
+
+ useEffect(() => {
+ const api = getApi();
+ let cancelled = false;
+ let settled = false;
+ let inFlight = false;
+ let retryAfterFlight = false;
+ let retryIndex = 0;
+ let loggedTransientFailure = false;
+ let retryTimer: ReturnType<typeof setTimeout> | undefined;
const onAuthSuccess = (user: User) => {
onLogin?.();
- useAuthStore.setState({ user, isLoading: false });
+ useAuthStore.setState({
+ user,
+ isLoading: false,
+ status: "authenticated",
+ });
identifyAnalytics(user.id, { email: user.email, name: user.name });
+ if (authRecoveryPendingRef.current) {
+ authRecoveryPendingRef.current = false;
+ // A network-not-ready boot can fail both auth and config requests;
+ // successful auth is a strong signal to accelerate config recovery.
+ retryConfigRef.current();
+ }
};
const onAuthFailure = () => {
onLogout?.();
resetAnalytics();
- useAuthStore.setState({ user: null, isLoading: false });
+ useAuthStore.setState({
+ user: null,
+ isLoading: false,
+ status: "unauthenticated",
+ });
};
- if (cookieAuth) {
- // Cookie mode: the HttpOnly cookie is sent automatically by the browser.
- // Call the API to check if the session is still valid.
- //
- // Seed the workspace list into React Query so the URL-driven layout can
- // resolve the slug without a second fetch. The active workspace itself
- // is derived from the URL by [workspaceSlug]/layout.tsx — no imperative
- // selection here.
- Promise.all([api.getMe(), api.listWorkspaces()])
- .then(([user, wsList]) => {
- onAuthSuccess(user);
- qc.setQueryData(workspaceKeys.list(), wsList);
- })
- .catch((err) => {
- logger.error("cookie auth init failed", err);
- onAuthFailure();
- });
- return;
- }
+ const rejectSession = () => {
+ settled = true;
+ window.removeEventListener("online", retryNow);
+ if (retryTimer !== undefined) clearTimeout(retryTimer);
+ if (!cookieAuth) {
+ setCurrentWorkspace(null, null);
+ }
+ onAuthFailure();
+ };
- // Token mode: read from localStorage (Electron / legacy).
- const token = storage.getItem("multica_token");
- if (!token) {
- onLogout?.();
- useAuthStore.setState({ isLoading: false });
- return;
- }
+ const scheduleRetry = (attempt: () => Promise<void>) => {
+ if (cancelled || settled) return;
+ const delay = RECOVERY_RETRY_DELAYS_MS[retryIndex];
+ retryIndex = Math.min(
+ retryIndex + 1,
+ RECOVERY_RETRY_DELAYS_MS.length - 1,
+ );
+ retryTimer = setTimeout(() => {
+ retryTimer = undefined;
+ void attempt();
+ }, delay);
+ };
+
+ const warmWorkspaces = () => {
+ void qc.fetchQuery(workspaceListOptions()).catch((err: unknown) => {
+ if (cancelled) return;
+ if (err instanceof ApiError && err.status === 401) {
+ rejectSession();
+ return;
+ }
+ // Workspace consumers observe this query directly. React Query owns
+ // retries and refetch-on-reconnect independently from identity auth.
+ logger.error("workspace bootstrap failed", err);
+ });
+ };
+
+ const attempt = async (): Promise<void> => {
+ if (cancelled || settled || inFlight) return;
+ if (retryTimer !== undefined) {
+ clearTimeout(retryTimer);
+ retryTimer = undefined;
+ }
+ inFlight = true;
- api.setToken(token);
+ try {
+ const user = await api.getMe();
+ if (cancelled) return;
- Promise.all([api.getMe(), api.listWorkspaces()])
- .then(([user, wsList]) => {
+ // Identity verification and workspace loading are separate concerns
+ // on both platforms. Publish the verified user immediately; route and
+ // shell consumers own the shared workspace query and its recovery.
+ settled = true;
+ window.removeEventListener("online", retryNow);
onAuthSuccess(user);
- // Seed React Query cache so the URL-driven layout can resolve the
- // slug without a second fetch.
- qc.setQueryData(workspaceKeys.list(), wsList);
- })
- .catch((err) => {
- logger.error("auth init failed", err);
- api.setToken(null);
- setCurrentWorkspace(null, null);
- storage.removeItem("multica_token");
- onAuthFailure();
- });
+ warmWorkspaces();
+ } catch (err) {
+ if (cancelled) return;
+ if (err instanceof ApiError && err.status === 401) {
+ rejectSession();
+ return;
+ }
+
+ if (!loggedTransientFailure) {
+ logger.error("auth init temporarily unavailable", err);
+ loggedTransientFailure = true;
+ }
+ authRecoveryPendingRef.current = true;
+ useAuthStore.setState({
+ user: null,
+ isLoading: true,
+ status: "recovering",
+ });
+ scheduleRetry(attempt);
+ } finally {
+ inFlight = false;
+ if (retryAfterFlight && !cancelled && !settled) {
+ retryAfterFlight = false;
+ void attempt();
+ }
+ }
+ };
+
+ const retryNow = () => {
+ if (cancelled || settled) return;
+ retryIndex = 0;
+ if (retryTimer !== undefined) {
+ clearTimeout(retryTimer);
+ retryTimer = undefined;
+ }
+ if (inFlight) {
+ retryAfterFlight = true;
+ return;
+ }
+ void attempt();
+ };
+
+ if (!cookieAuth) {
+ const token = storage.getItem("multica_token");
+ if (!token) {
+ settled = true;
+ onLogout?.();
+ useAuthStore.setState({
+ user: null,
+ isLoading: false,
+ status: "unauthenticated",
+ });
+ } else {
+ api.setToken(token);
+ window.addEventListener("online", retryNow);
+ void attempt();
+ }
+ } else {
+ window.addEventListener("online", retryNow);
+ void attempt();
+ }
+
+ return () => {
+ cancelled = true;
+ window.removeEventListener("online", retryNow);
+ if (retryTimer !== undefined) clearTimeout(retryTimer);
+ };
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, []);
+ }, [retryGeneration]);
return <>{children}</>;
}
diff --git a/packages/core/workspace/hooks.test.tsx b/packages/core/workspace/hooks.test.tsx
index e7644c7731..c0b70a7978 100644
--- a/packages/core/workspace/hooks.test.tsx
+++ b/packages/core/workspace/hooks.test.tsx
@@ -2,13 +2,14 @@
* @vitest-environment jsdom
*/
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { renderHook } from "@testing-library/react";
+import { act, renderHook, waitFor } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { ReactNode } from "react";
import { setApiInstance } from "../api";
import type { ApiClient } from "../api/client";
+import type { Workspace } from "../types";
import { workspaceKeys } from "./queries";
-import { useActorName } from "./hooks";
+import { useActorName, useWorkspaceList } from "./hooks";
// useActorName reads the current workspace from the core WorkspaceId provider;
// the directory-name resolution under test does not depend on the real id.
@@ -22,6 +23,69 @@ function createWrapper(qc: QueryClient) {
};
}
+function makeWorkspace(slug: string): Workspace {
+ return {
+ id: `id-${slug}`,
+ name: slug,
+ slug,
+ description: null,
+ context: null,
+ settings: {},
+ repos: [],
+ issue_prefix: slug.toUpperCase(),
+ avatar_url: null,
+ created_at: "",
+ updated_at: "",
+ };
+}
+
+describe("useWorkspaceList", () => {
+ let qc: QueryClient;
+
+ beforeEach(() => {
+ qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ });
+
+ afterEach(() => {
+ qc.clear();
+ vi.restoreAllMocks();
+ });
+
+ it("does not treat an initial request failure as an authoritative empty list", async () => {
+ setApiInstance({
+ listWorkspaces: () => Promise.reject(new Error("temporarily unavailable")),
+ } as unknown as ApiClient);
+
+ const { result } = renderHook(() => useWorkspaceList(), {
+ wrapper: createWrapper(qc),
+ });
+
+ await waitFor(() => expect(result.current.unavailable).toBe(true));
+ expect(result.current.ready).toBe(false);
+ expect(result.current.workspaces).toEqual([]);
+ });
+
+ it("keeps cached data authoritative when a background refetch fails", async () => {
+ const cached = [makeWorkspace("acme")];
+ qc.setQueryData(workspaceKeys.list(), cached);
+ setApiInstance({
+ listWorkspaces: () => Promise.reject(new Error("temporarily unavailable")),
+ } as unknown as ApiClient);
+
+ const { result } = renderHook(() => useWorkspaceList(), {
+ wrapper: createWrapper(qc),
+ });
+
+ await act(async () => {
+ await result.current.refetch();
+ });
+
+ expect(result.current.ready).toBe(true);
+ expect(result.current.unavailable).toBe(false);
+ expect(result.current.workspaces).toEqual(cached);
+ });
+});
+
describe("useActorName", () => {
let qc: QueryClient;
diff --git a/packages/core/workspace/hooks.ts b/packages/core/workspace/hooks.ts
index 34c069ca9a..9e97cc6beb 100644
--- a/packages/core/workspace/hooks.ts
+++ b/packages/core/workspace/hooks.ts
@@ -2,9 +2,14 @@
import { useCallback, useMemo } from "react";
import { useQuery } from "@tanstack/react-query";
-import type { Agent, MemberWithUser, Squad } from "../types";
+import type { Agent, MemberWithUser, Squad, Workspace } from "../types";
import { useWorkspaceId } from "../hooks";
-import { memberListOptions, agentListOptions, squadListOptions } from "./queries";
+import {
+ memberListOptions,
+ agentListOptions,
+ squadListOptions,
+ workspaceListOptions,
+} from "./queries";
import { resolvePublicFileUrl } from "./avatar-url";
// Stable empties for the still-loading directory queries. A fresh `= []`
@@ -20,6 +25,32 @@ import { resolvePublicFileUrl } from "./avatar-url";
const EMPTY_MEMBERS: MemberWithUser[] = [];
const EMPTY_AGENTS: Agent[] = [];
const EMPTY_SQUADS: Squad[] = [];
+const EMPTY_WORKSPACES: Workspace[] = [];
+
+/**
+ * Shared authoritative-state contract for the workspace list.
+ *
+ * TanStack Query's `isFetched` also becomes true after an initial failure, so
+ * it cannot distinguish "the account has no workspaces" from "the first
+ * request failed before any list arrived". Data presence can: a successful
+ * empty response is `[]`, while an initial failure remains `undefined`.
+ * Background failures retain cached data and therefore remain ready.
+ */
+export function useWorkspaceList({ enabled = true }: { enabled?: boolean } = {}) {
+ const query = useQuery({
+ ...workspaceListOptions(),
+ enabled,
+ });
+ const ready = query.data !== undefined;
+
+ return {
+ workspaces: query.data ?? EMPTY_WORKSPACES,
+ ready,
+ unavailable: enabled && !ready && query.isLoadingError,
+ isFetching: query.isFetching,
+ refetch: query.refetch,
+ };
+}
/**
* Pure actor-name resolution over explicit directory snapshots. Async flows
diff --git a/packages/core/workspace/queries.test.ts b/packages/core/workspace/queries.test.ts
new file mode 100644
index 0000000000..57f782317c
--- /dev/null
+++ b/packages/core/workspace/queries.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it } from "vitest";
+import type { Workspace } from "../types";
+import { workspaceBySlugOptions } from "./queries";
+
+function makeWorkspace(slug: string): Workspace {
+ return {
+ id: `id-${slug}`,
+ name: slug,
+ slug,
+ description: null,
+ context: null,
+ settings: {},
+ repos: [],
+ issue_prefix: slug.toUpperCase(),
+ avatar_url: null,
+ created_at: "",
+ updated_at: "",
+ };
+}
+
+describe("workspaceBySlugOptions", () => {
+ const workspaces = [makeWorkspace("acme")];
+
+ it("selects a matching workspace", () => {
+ expect(workspaceBySlugOptions("acme").select?.(workspaces)).toEqual(
+ workspaces[0],
+ );
+ });
+
+ it("returns null after an authoritative list omits the slug", () => {
+ expect(workspaceBySlugOptions("missing").select?.(workspaces)).toBeNull();
+ });
+});
diff --git a/packages/views/common/task-transcript/agent-transcript-dialog.test.tsx b/packages/views/common/task-transcript/agent-transcript-dialog.test.tsx
index efacf5d4b4..150ee2ab3f 100644
--- a/packages/views/common/task-transcript/agent-transcript-dialog.test.tsx
+++ b/packages/views/common/task-transcript/agent-transcript-dialog.test.tsx
@@ -1,7 +1,7 @@
// @vitest-environment jsdom
import { readFileSync } from "node:fs";
-import { cleanup, fireEvent, screen, within } from "@testing-library/react";
+import { act, cleanup, fireEvent, screen, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { ButtonHTMLAttributes, ReactNode } from "react";
@@ -401,7 +401,7 @@ describe("AgentTranscriptDialog", () => {
expect(screen.getByText("Tools")).toBeInTheDocument();
});
- it("copies RFC 3339 timestamps before event labels", () => {
+ it("copies RFC 3339 timestamps before event labels", async () => {
renderDialog([
{
seq: 1,
@@ -417,7 +417,9 @@ describe("AgentTranscriptDialog", () => {
},
]);
- fireEvent.click(screen.getByRole("button", { name: "Copy all" }));
+ await act(async () => {
+ fireEvent.click(screen.getByRole("button", { name: "Copy all" }));
+ });
// Full body (not the truncated summary) with the RFC 3339 prefix, events
// separated by a blank line.
@@ -429,7 +431,7 @@ describe("AgentTranscriptDialog", () => {
);
});
- it("keeps older events without a valid timestamp copyable", () => {
+ it("keeps older events without a valid timestamp copyable", async () => {
renderDialog([
{
seq: 1,
@@ -444,12 +446,35 @@ describe("AgentTranscriptDialog", () => {
},
]);
- fireEvent.click(screen.getByRole("button", { name: "Copy all" }));
+ await act(async () => {
+ fireEvent.click(screen.getByRole("button", { name: "Copy all" }));
+ });
expect(copyTextMock).toHaveBeenCalledWith(
["[Agent] Missing timestamp", "[Error] Invalid timestamp"].join("\n\n"),
);
});
+
+ it("cancels copy feedback timers when the dialog unmounts", async () => {
+ vi.useFakeTimers();
+ try {
+ const { unmount } = renderDialog();
+
+ await act(async () => {
+ fireEvent.click(screen.getByRole("button", { name: "Copy all" }));
+ await Promise.resolve();
+ });
+ expect(vi.getTimerCount()).toBeGreaterThan(0);
+
+ unmount();
+
+ expect(vi.getTimerCount()).toBe(0);
+ } finally {
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ }
+ });
+
it("renders a file edit as a diff instead of escaped JSON strings", () => {
const { container } = renderDialog([
{
diff --git a/packages/views/common/task-transcript/agent-transcript-dialog.tsx b/packages/views/common/task-transcript/agent-transcript-dialog.tsx
index 457c60c001..8bcc52e67d 100644
--- a/packages/views/common/task-transcript/agent-transcript-dialog.tsx
+++ b/packages/views/common/task-transcript/agent-transcript-dialog.tsx
@@ -265,6 +265,36 @@ const VirtuosoList = forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElem
},
);
const LIST_COMPONENTS: Components<TraceRow> = { List: VirtuosoList };
+const COPY_FEEDBACK_DURATION_MS = 2000;
+
+function useCopyFeedback() {
+ const [copied, setCopied] = useState(false);
+ const resetTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const mountedRef = useRef(true);
+
+ useEffect(() => {
+ mountedRef.current = true;
+ return () => {
+ mountedRef.current = false;
+ if (resetTimerRef.current !== null) {
+ clearTimeout(resetTimerRef.current);
+ resetTimerRef.current = null;
+ }
+ };
+ }, []);
+
+ const showCopied = useCallback(() => {
+ if (!mountedRef.current) return;
+ setCopied(true);
+ if (resetTimerRef.current !== null) clearTimeout(resetTimerRef.current);
+ resetTimerRef.current = setTimeout(() => {
+ resetTimerRef.current = null;
+ if (mountedRef.current) setCopied(false);
+ }, COPY_FEEDBACK_DURATION_MS);
+ }, []);
+
+ return [copied, showCopied] as const;
+}
export function AgentTranscriptDialog({
open,
@@ -280,9 +310,9 @@ export function AgentTranscriptDialog({
const [expandedGroups, setExpandedGroups] = useState<Set<number>>(() => new Set());
const [query, setQuery] = useState("");
const [elapsed, setElapsed] = useState("");
- const [copied, setCopied] = useState(false);
- const [copiedWorkdir, setCopiedWorkdir] = useState(false);
- const [copiedBranch, setCopiedBranch] = useState(false);
+ const [copied, showCopied] = useCopyFeedback();
+ const [copiedWorkdir, showCopiedWorkdir] = useCopyFeedback();
+ const [copiedBranch, showCopiedBranch] = useCopyFeedback();
const [agentInfo, setAgentInfo] = useState<Agent | null>(null);
const [runtimeInfo, setRuntimeInfo] = useState<AgentRuntime | null>(null);
const sortDirection = useTranscriptViewStore((s) => s.sortDirection);
@@ -581,10 +611,9 @@ export function AgentTranscriptDialog({
if (!task.relative_work_dir) return;
void copyText(task.relative_work_dir).then((ok) => {
if (!ok) return;
- setCopiedWorkdir(true);
- setTimeout(() => setCopiedWorkdir(false), 2000);
+ showCopiedWorkdir();
});
- }, [task.relative_work_dir]);
+ }, [task.relative_work_dir, showCopiedWorkdir]);
// Worktree-mode runs deliver a branch instead of edits in the working copy,
// so copying the name is the fastest path to `git diff <branch>`.
@@ -592,10 +621,9 @@ export function AgentTranscriptDialog({
if (!task.branch_name) return;
void copyText(task.branch_name).then((ok) => {
if (!ok) return;
- setCopiedBranch(true);
- setTimeout(() => setCopiedBranch(false), 2000);
+ showCopiedBranch();
});
- }, [task.branch_name]);
+ }, [task.branch_name, showCopiedBranch]);
const handleCopyAll = useCallback(() => {
// Copy the full body of each event (not the truncated row summary), with
@@ -620,10 +648,9 @@ export function AgentTranscriptDialog({
const text = events.map((event) => redactSecrets(traceEventCopyText(event))).join("\n\n");
void copyText(text).then((ok) => {
if (!ok) return;
- setCopied(true);
- setTimeout(() => setCopied(false), 2000);
+ showCopied();
});
- }, [displayRows]);
+ }, [displayRows, showCopied]);
const handleToggleGroup = useCallback((seq: number) => {
setExpandedGroups((prev) => {
@@ -1515,7 +1542,7 @@ function StepInspector({
onClose: () => void;
}) {
const { t } = useT("agents");
- const [copied, setCopied] = useState(false);
+ const [copied, showCopied] = useCopyFeedback();
const at = timeMs(step.startedAt);
const offset = at !== undefined && runStartMs !== undefined ? formatOffset(at - runStartMs) : null;
@@ -1533,10 +1560,9 @@ function StepInspector({
}
void copyText(redactSecrets(parts.join("\n\n"))).then((ok) => {
if (!ok) return;
- setCopied(true);
- setTimeout(() => setCopied(false), 2000);
+ showCopied();
});
- }, [call, message]);
+ }, [call, message, showCopied]);
const title =
call
diff --git a/packages/views/layout/use-dashboard-guard.ts b/packages/views/layout/use-dashboard-guard.ts
index 28cdb26a6e..c369844f14 100644
--- a/packages/views/layout/use-dashboard-guard.ts
+++ b/packages/views/layout/use-dashboard-guard.ts
@@ -1,7 +1,6 @@
"use client";
import { useEffect } from "react";
-import { useQuery } from "@tanstack/react-query";
import { useNavigationStore } from "@multica/core/navigation";
import { useAuthStore } from "@multica/core/auth";
import {
@@ -10,7 +9,7 @@ import {
useCurrentWorkspace,
useHasOnboarded,
} from "@multica/core/paths";
-import { workspaceListOptions } from "@multica/core/workspace";
+import { useWorkspaceList } from "@multica/core/workspace";
import { useRecentIssuesStore } from "@multica/core/issues/stores";
import { useNavigation } from "../navigation";
@@ -45,8 +44,7 @@ export function useDashboardGuard() {
const isLoading = useAuthStore((s) => s.isLoading);
const workspace = useCurrentWorkspace();
const hasOnboarded = useHasOnboarded();
- const { data: workspaces = [], isFetched: workspaceListFetched } = useQuery({
- ...workspaceListOptions(),
+ const { workspaces, ready: workspaceListReady } = useWorkspaceList({
enabled: !!user,
});
@@ -56,11 +54,11 @@ export function useDashboardGuard() {
replace(paths.login());
return;
}
- if (!workspaceListFetched) return;
+ if (!workspaceListReady) return;
if (!workspace) {
replace(resolvePostAuthDestination(workspaces, hasOnboarded));
}
- }, [user, isLoading, workspaceListFetched, workspace, workspaces, hasOnboarded, replace]);
+ }, [user, isLoading, workspaceListReady, workspace, workspaces, hasOnboarded, replace]);
useEffect(() => {
useNavigationStore.getState().onPathChange(pathname);
@@ -70,11 +68,11 @@ export function useDashboardGuard() {
// Runs once the workspace list resolves, and again whenever membership
// changes (workspace deleted, user kicked, user left).
useEffect(() => {
- if (!workspaceListFetched) return;
+ if (!workspaceListReady) return;
useRecentIssuesStore
.getState()
.pruneWorkspaces(workspaces.map((w) => w.id));
- }, [workspaceListFetched, workspaces]);
+ }, [workspaceListReady, workspaces]);
return { user, isLoading, workspace };
}
diff --git a/packages/views/locales/en/auth.json b/packages/views/locales/en/auth.json
index a7d0bea29e..a78de97619 100644
--- a/packages/views/locales/en/auth.json
+++ b/packages/views/locales/en/auth.json
@@ -43,5 +43,13 @@
"failed_title": "Sign-in Failed",
"prepare_failed": "Failed to prepare Desktop sign-in"
}
+ },
+ "desktop": {
+ "recovery": {
+ "title": "Reconnecting to Multica",
+ "description": "Your session is still saved. We'll retry automatically when the connection recovers.",
+ "retry": "Try again",
+ "retrying": "Trying again..."
+ }
}
}
diff --git a/packages/views/locales/ja/auth.json b/packages/views/locales/ja/auth.json
index 4fde775d20..9bb381c428 100644
--- a/packages/views/locales/ja/auth.json
+++ b/packages/views/locales/ja/auth.json
@@ -43,5 +43,13 @@
"failed_title": "ログインに失敗しました",
"prepare_failed": "デスクトップのログインを準備できませんでした"
}
+ },
+ "desktop": {
+ "recovery": {
+ "title": "Multica に再接続しています",
+ "description": "セッションは保持されています。接続が回復すると自動的に再試行します。",
+ "retry": "再試行",
+ "retrying": "再試行しています..."
+ }
}
}
diff --git a/packages/views/locales/ko/auth.json b/packages/views/locales/ko/auth.json
index e694524783..021e2041c0 100644
--- a/packages/views/locales/ko/auth.json
+++ b/packages/views/locales/ko/auth.json
@@ -43,5 +43,13 @@
"failed_title": "로그인 실패",
"prepare_failed": "데스크톱 로그인을 준비하지 못했습니다"
}
+ },
+ "desktop": {
+ "recovery": {
+ "title": "Multica에 다시 연결하는 중",
+ "description": "세션은 안전하게 유지됩니다. 연결이 복구되면 자동으로 다시 시도합니다.",
+ "retry": "다시 시도",
+ "retrying": "다시 시도하는 중..."
+ }
}
}
diff --git a/packages/views/locales/zh-Hans/auth.json b/packages/views/locales/zh-Hans/auth.json
index 8aec6463c1..065013ad44 100644
--- a/packages/views/locales/zh-Hans/auth.json
+++ b/packages/views/locales/zh-Hans/auth.json
@@ -43,5 +43,13 @@
"failed_title": "登录失败",
"prepare_failed": "桌面登录准备失败"
}
+ },
+ "desktop": {
+ "recovery": {
+ "title": "正在重新连接 Multica",
+ "description": "登录状态已保留。连接恢复后会自动重试。",
+ "retry": "重试",
+ "retrying": "正在重试..."
+ }
}
}
diff --git a/packages/views/onboarding/onboarding-flow-mode.test.tsx b/packages/views/onboarding/onboarding-flow-mode.test.tsx
index aa71f1855e..1b78399e5d 100644
--- a/packages/views/onboarding/onboarding-flow-mode.test.tsx
+++ b/packages/views/onboarding/onboarding-flow-mode.test.tsx
@@ -33,17 +33,13 @@ vi.mock("@multica/core/auth", () => ({
),
}));
-// The flow only queries the workspace list; returning one proves the
-// new-workspace mode does not offer to continue with it.
-vi.mock("@tanstack/react-query", async () => {
- const actual = await vi.importActual<Record<string, unknown>>(
- "@tanstack/react-query",
- );
+// Returning one workspace proves new-workspace mode does not offer to
+// continue with it.
+vi.mock("@multica/core/workspace", () => {
return {
- ...actual,
- useQuery: () => ({
- data: [{ id: "ws-1", name: "Existing", slug: "existing" }],
- isFetched: true,
+ useWorkspaceList: () => ({
+ workspaces: [{ id: "ws-1", name: "Existing", slug: "existing" }],
+ ready: true,
}),
};
});
diff --git a/packages/views/onboarding/onboarding-flow.tsx b/packages/views/onboarding/onboarding-flow.tsx
index d5b53d50e6..cc43950ab6 100644
--- a/packages/views/onboarding/onboarding-flow.tsx
+++ b/packages/views/onboarding/onboarding-flow.tsx
@@ -1,7 +1,6 @@
"use client";
import { useCallback, useState } from "react";
-import { useQuery } from "@tanstack/react-query";
import { toast } from "sonner";
import { useAuthStore } from "@multica/core/auth";
import {
@@ -13,7 +12,7 @@ import {
type OnboardingStep,
type QuestionnaireAnswers,
} from "@multica/core/onboarding";
-import { workspaceListOptions } from "@multica/core/workspace/queries";
+import { useWorkspaceList } from "@multica/core/workspace";
import type { AgentRuntime, Workspace } from "@multica/core/types";
import { StepWelcome } from "./steps/step-welcome";
import { StepShell } from "./components/step-shell";
@@ -167,14 +166,13 @@ function OnboardingStepFlow({
// whether to render the "I've done this before" skip button — only
// shown when the user already has at least one workspace, otherwise
// skipping would land them in limbo.
- const { data: workspaces = [], isFetched: workspacesFetched } = useQuery({
- ...workspaceListOptions(),
+ const { workspaces, ready: workspacesReady } = useWorkspaceList({
enabled: step === "welcome" || step === "workspace",
});
const existingWorkspace = isNewWorkspace
? workspace
: (workspace ?? workspaces[0] ?? null);
- const canSkipWelcome = workspacesFetched && workspaces.length > 0;
+ const canSkipWelcome = workspacesReady && workspaces.length > 0;
// The `runtimeInstructions` slot is only plumbed by the web shell
// (desktop bundles a daemon, so a CLI install card would be noise