Skip to content

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

Go

MUL-6231: fix(desktop): stop the client blanking after the last workspace is deleted (#7021) (#7064)

Bohan Jiang245bc79eedcc
diff --git a/apps/desktop/src/renderer/src/components/app-crash-boundary.test.tsx b/apps/desktop/src/renderer/src/components/app-crash-boundary.test.tsx
new file mode 100644
index 0000000000..6be150fe5e
--- /dev/null
+++ b/apps/desktop/src/renderer/src/components/app-crash-boundary.test.tsx
@@ -0,0 +1,93 @@
+import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";
+import { render, screen } from "@testing-library/react";
+
+const captureException = vi.hoisted(() => vi.fn());
+vi.mock("@multica/core/analytics", () => ({ captureException }));
+
+// Marker stand-in so the structural assertion below tests the contract ("the
+// drag strip is the first flex child") rather than DragStrip's own markup.
+vi.mock("@multica/views/platform", () => ({
+ DragStrip: () => <div data-testid="drag-strip" />,
+}));
+
+import { AppCrashBoundary } from "./app-crash-boundary";
+
+function Boom(): never {
+ throw new Error("useWorkspaceId: no workspace selected");
+}
+
+beforeEach(() => {
+ captureException.mockClear();
+ // The boundary logs the captured error on purpose; keep the suite output
+ // readable without hiding a genuinely unexpected console.error elsewhere.
+ vi.spyOn(console, "error").mockImplementation(() => {});
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+/**
+ * MUL-6231 / #7021. The desktop renderer mounted <App /> with no boundary
+ * above it, so one throw in the shell emptied the window and left force-quit
+ * as the only way out.
+ */
+describe("AppCrashBoundary", () => {
+ it("renders children when nothing throws", () => {
+ render(
+ <AppCrashBoundary>
+ <div data-testid="app" />
+ </AppCrashBoundary>,
+ );
+
+ expect(screen.queryByTestId("app")).not.toBeNull();
+ });
+
+ it("shows a recoverable fallback instead of blanking the window", () => {
+ render(
+ <AppCrashBoundary>
+ <Boom />
+ </AppCrashBoundary>,
+ );
+
+ const alert = screen.getByRole("alert");
+ expect(alert).not.toBeNull();
+ expect(alert.textContent).toContain("useWorkspaceId: no workspace selected");
+ expect(screen.getByRole("button", { name: /reload/i })).not.toBeNull();
+ });
+
+ it("keeps the window draggable by mounting the drag strip as the first child", () => {
+ // A full-window view outside the dashboard shell owns its own window
+ // chrome. Without this the user loses the draggable top edge precisely
+ // when the app is least usable — see CLAUDE.md Desktop Rules.
+ const { container } = render(
+ <AppCrashBoundary>
+ <Boom />
+ </AppCrashBoundary>,
+ );
+
+ const shell = container.firstElementChild;
+ expect(shell).not.toBeNull();
+ expect(shell).toHaveClass("flex", "flex-col");
+ expect(shell?.firstElementChild).toHaveAttribute("data-testid", "drag-strip");
+ });
+
+ it("reports the crash through the exception pipeline, not as a plain event", () => {
+ // captureException routes into posthog's `$exception` path, the only one
+ // initAnalytics' before_send hook redacts and de-dupes. A plain
+ // captureEvent would ship the raw message and stack unredacted.
+ render(
+ <AppCrashBoundary>
+ <Boom />
+ </AppCrashBoundary>,
+ );
+
+ expect(captureException).toHaveBeenCalledTimes(1);
+ expect(captureException).toHaveBeenCalledWith(
+ expect.objectContaining({
+ message: "useWorkspaceId: no workspace selected",
+ }),
+ { source: "desktop-renderer-boundary" },
+ );
+ });
+});
diff --git a/apps/desktop/src/renderer/src/components/app-crash-boundary.tsx b/apps/desktop/src/renderer/src/components/app-crash-boundary.tsx
new file mode 100644
index 0000000000..f566ee6472
--- /dev/null
+++ b/apps/desktop/src/renderer/src/components/app-crash-boundary.tsx
@@ -0,0 +1,85 @@
+import type { ReactNode } from "react";
+import { ErrorBoundary } from "@multica/ui/components/common/error-boundary";
+import { Button } from "@multica/ui/components/ui/button";
+import { captureException } from "@multica/core/analytics";
+import { DragStrip } from "@multica/views/platform";
+
+/**
+ * Last-resort boundary around the entire desktop renderer.
+ *
+ * The renderer had no boundary above the shell at all: `createRoot().render()`
+ * mounted <App /> bare, and the router's `errorElement` only covers what the
+ * router itself renders — the sidebar, search dialog, modal registry and
+ * window overlay are siblings of the router, outside its reach. A render-time
+ * throw in any of them unmounted the whole React tree and left an empty,
+ * unresponsive window with no way back except force-quitting the app. That is
+ * exactly what #7021 reported after deleting the last workspace (MUL-6231).
+ *
+ * The specific throw behind that report is fixed at its source, but "one
+ * component throws" must not stay a whole-app kill switch on desktop, where
+ * there is no reload button and no URL bar to escape with. This turns the
+ * blank window into a readable error plus a Reload button.
+ *
+ * Deliberately NOT a `reset()` fallback: whatever state produced the throw is
+ * still in the stores, so re-rendering the same tree usually re-throws.
+ * A full `location.reload()` re-runs bootstrap from persisted state, which is
+ * the recovery path the user would otherwise get by restarting the app.
+ */
+export function AppCrashBoundary({ children }: { children: ReactNode }) {
+ return (
+ <ErrorBoundary
+ // captureException, not captureEvent: only `$exception` events pass
+ // through initAnalytics' before_send hook, which drops known-benign
+ // noise, runs redactExceptionProperties over the message and stack, and
+ // fuses repeats via shouldDropException. A plain event would ship a raw
+ // message and stack — which can carry emails, tokenised URLs or typed
+ // user input — straight to storage. Same entry point the web
+ // global-error route uses.
+ onError={(error) => {
+ captureException(error, { source: "desktop-renderer-boundary" });
+ }}
+ fallback={({ error }) => <CrashFallback error={error} />}
+ >
+ {children}
+ </ErrorBoundary>
+ );
+}
+
+/**
+ * Full-window view outside the dashboard shell, so it owes the same window
+ * chrome every other one does: `<DragStrip />` as the first flex child, or the
+ * user loses the draggable top edge exactly when the app is least usable. The
+ * Reload button sits inside the centred `flex-1` region, well clear of the top
+ * 48px, so it needs no `WebkitAppRegion: "no-drag"` opt-out.
+ *
+ * Everything rendered here has to be safe under a broken tree: an error thrown
+ * while rendering a fallback is NOT caught by its own boundary and would blank
+ * the window all over again. DragStrip and Button are static markup with no
+ * hooks, stores or workspace context.
+ */
+function CrashFallback({ error }: { error: Error }) {
+ return (
+ <div className="flex h-screen flex-col bg-background text-foreground">
+ <DragStrip />
+ <div
+ role="alert"
+ className="flex flex-1 items-center justify-center overflow-auto p-8"
+ >
+ <div className="max-w-xl rounded-lg border bg-card p-6 shadow-sm">
+ <h1 className="text-title font-semibold">Something went wrong</h1>
+ <p className="mt-3 text-body text-muted-foreground">
+ Multica Desktop hit an unexpected error and could not keep
+ rendering. Reloading usually recovers — your work is stored on the
+ server.
+ </p>
+ <pre className="mt-4 max-h-48 overflow-auto whitespace-pre-wrap rounded-md bg-muted p-3 text-caption text-muted-foreground">
+ {error.message || "An unexpected error occurred."}
+ </pre>
+ <Button className="mt-4" onClick={() => window.location.reload()}>
+ Reload
+ </Button>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/desktop/src/renderer/src/components/desktop-layout.test.tsx b/apps/desktop/src/renderer/src/components/desktop-layout.test.tsx
index 09f3308387..b1e9f47b4d 100644
--- a/apps/desktop/src/renderer/src/components/desktop-layout.test.tsx
+++ b/apps/desktop/src/renderer/src/components/desktop-layout.test.tsx
@@ -1,10 +1,17 @@
import type { ReactNode } from "react";
import { describe, expect, it, vi } from "vitest";
import { render } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { I18nProvider } from "@multica/core/i18n/react";
import { useSidebar } from "@multica/ui/components/ui/sidebar";
import { RESOURCES } from "@multica/views/locales";
+// The shell resolves the mocked `getCurrentSlug()` against the workspace list
+// before mounting workspace-scoped chrome, so the list has to contain it or
+// the sidebar under test never renders. Gating behaviour itself is covered by
+// desktop-layout.workspace-gate.test.tsx.
+const WORKSPACES = [{ id: "ws-1", slug: "acme" }];
+
// The shell is the only thing under test here, so everything it mounts around
// the sidebar is stubbed out. What survives is the pair that has to agree:
// `WindowToolbar`'s own trigger, and the `hasExternalTrigger` the provider
@@ -39,6 +46,13 @@ vi.mock("@multica/core/platform", () => ({
subscribeToCurrentSlug: () => () => {},
}));
+vi.mock("@multica/core/workspace", () => ({
+ workspaceListOptions: () => ({
+ queryKey: ["workspace-list"],
+ queryFn: async () => WORKSPACES,
+ }),
+}));
+
vi.mock("@multica/views/navigation", () => ({
useNavigation: () => ({ push: vi.fn() }),
}));
@@ -82,10 +96,17 @@ function renderShell() {
onInboxOpen: () => () => {},
};
+ const qc = new QueryClient({
+ defaultOptions: { queries: { retry: false, gcTime: 0 } },
+ });
+ qc.setQueryData(["workspace-list"], WORKSPACES);
+
return render(
- <I18nProvider locale="en" resources={RESOURCES}>
- <DesktopShell />
- </I18nProvider>,
+ <QueryClientProvider client={qc}>
+ <I18nProvider locale="en" resources={RESOURCES}>
+ <DesktopShell />
+ </I18nProvider>
+ </QueryClientProvider>,
);
}
diff --git a/apps/desktop/src/renderer/src/components/desktop-layout.tsx b/apps/desktop/src/renderer/src/components/desktop-layout.tsx
index 79f8f4e9f6..2f5b53c587 100644
--- a/apps/desktop/src/renderer/src/components/desktop-layout.tsx
+++ b/apps/desktop/src/renderer/src/components/desktop-layout.tsx
@@ -1,6 +1,7 @@
import { useEffect, useRef, useSyncExternalStore } from "react";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { motion } from "motion/react";
+import { useQuery } from "@tanstack/react-query";
import { cn } from "@multica/ui/lib/utils";
import {
useNavigationInputBindings,
@@ -16,6 +17,7 @@ import { AppSidebar, GlobalShortcuts } from "@multica/views/layout";
import { SearchCommand, SearchTrigger } from "@multica/views/search";
import { FloatingChat } from "@multica/views/chat";
import { WorkspaceSlugProvider, paths, useCurrentWorkspace } from "@multica/core/paths";
+import { workspaceListOptions } from "@multica/core/workspace";
import {
useNavigation,
type LinkClickIntent,
@@ -220,10 +222,35 @@ export function DesktopShell() {
useNavigationInputBindings();
// Reactive read of current workspace slug from the platform singleton.
- // On first mount, slug is null until WorkspaceRouteLayout (inside the tab
+ // On first mount, it is null until WorkspaceRouteLayout (inside the tab
// router) sets it. Once set, the sidebar and other shell-level components
// can resolve workspace-scoped paths via useWorkspacePaths().
- const slug = useSyncExternalStore(subscribeToCurrentSlug, getCurrentSlug, () => null);
+ const currentSlug = useSyncExternalStore(
+ subscribeToCurrentSlug,
+ getCurrentSlug,
+ () => null,
+ );
+ // Chrome gates on "the slug still resolves to a workspace", NOT on "the
+ // singleton is non-null" (MUL-6231 / #7021). The singleton is mutable
+ // process state that no single owner keeps in lockstep with the workspace
+ // list, so after the active workspace is deleted it can still hold the dead
+ // slug for a beat. Everything below mounts workspace-scoped components —
+ // SearchCommand calls useWorkspaceId(), which THROWS when the workspace is
+ // gone from the list. Nothing above this in the desktop tree is an error
+ // boundary, so that throw used to unmount the whole renderer and leave a
+ // blank, unresponsive window.
+ //
+ // Deriving from the list cache makes this the same gate web uses
+ // (DashboardGuard's `!workspace` check in packages/views/layout), so both
+ // shells drop workspace-scoped chrome on exactly the same signal instead of
+ // diverging. TabContent stays outside the gate: it must always render so
+ // the tab router can mount WorkspaceRouteLayout, which is what populates
+ // the singleton in the first place.
+ const { data: workspaces = [] } = useQuery(workspaceListOptions());
+ const slug =
+ currentSlug && workspaces.some((w) => w.slug === currentSlug)
+ ? currentSlug
+ : null;
return (
<DesktopNavigationProvider>
@@ -231,10 +258,11 @@ export function DesktopShell() {
use useWorkspaceSlug() (nullable) or useRequiredWorkspaceSlug()
(throws). TabContent MUST always render so the tab router can
mount WorkspaceRouteLayout, which calls setCurrentWorkspace()
- to populate the slug. The sidebar gates on slug being present
- to avoid the useRequiredWorkspaceSlug throw. Zero-workspace
- users see the window-level overlay (new-workspace flow)
- triggered by IndexRedirect, not a route. */}
+ to populate the slug. The sidebar gates on the resolved slug
+ (see above) to avoid the useRequiredWorkspaceSlug and
+ useWorkspaceId throws. Zero-workspace users see the
+ window-level overlay (new-workspace flow) triggered by
+ IndexRedirect, not a route. */}
<WorkspaceSlugProvider slug={slug}>
<DesktopInboxBridge />
<div className="flex h-screen bg-app-shell">
diff --git a/apps/desktop/src/renderer/src/components/desktop-layout.workspace-gate.test.tsx b/apps/desktop/src/renderer/src/components/desktop-layout.workspace-gate.test.tsx
new file mode 100644
index 0000000000..68867ee14c
--- /dev/null
+++ b/apps/desktop/src/renderer/src/components/desktop-layout.workspace-gate.test.tsx
@@ -0,0 +1,183 @@
+import type { ReactNode } from "react";
+import { describe, expect, it, vi, beforeEach } from "vitest";
+import { render } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { I18nProvider } from "@multica/core/i18n/react";
+import { RESOURCES } from "@multica/views/locales";
+
+/**
+ * Regression guard for MUL-6231 / #7021: deleting the last workspace blanked
+ * the desktop client.
+ *
+ * The shell used to decide whether to mount workspace-scoped chrome from the
+ * `getCurrentSlug()` singleton alone. That singleton is mutable process state
+ * with no owner keeping it in lockstep with the workspace list, so after the
+ * active workspace was deleted it kept returning the dead slug — and the shell
+ * kept `SearchCommand` mounted, whose `useWorkspaceId()` THROWS once the
+ * workspace leaves the list. Nothing above the shell was an error boundary, so
+ * that throw unmounted the entire renderer: a blank, unresponsive window.
+ *
+ * The invariant these tests lock is "a slug the workspace list no longer
+ * contains mounts no workspace-scoped chrome", which is the same signal web's
+ * DashboardGuard already gates on.
+ */
+
+const state = vi.hoisted(() => ({
+ currentSlug: "acme" as string | null,
+ wsList: [] as { id: string; slug: string }[],
+}));
+
+vi.mock("@/hooks/use-tab-history", () => ({
+ useTabHistory: () => ({
+ canGoBack: false,
+ canGoForward: false,
+ goBack: vi.fn(),
+ goForward: vi.fn(),
+ }),
+ useNavigationInputBindings: () => {},
+}));
+
+vi.mock("@/platform/navigation", () => ({
+ DesktopNavigationProvider: ({ children }: { children: ReactNode }) => (
+ <>{children}</>
+ ),
+ routeContentLinkPath: vi.fn(),
+}));
+
+vi.mock("@multica/core/paths", () => ({
+ WorkspaceSlugProvider: ({ children }: { children: ReactNode }) => (
+ <>{children}</>
+ ),
+ paths: { workspace: () => ({ inbox: () => "/acme/inbox" }) },
+ useCurrentWorkspace: () => null,
+}));
+
+vi.mock("@multica/core/platform", () => ({
+ getCurrentSlug: () => state.currentSlug,
+ subscribeToCurrentSlug: () => () => {},
+}));
+
+vi.mock("@multica/core/workspace", () => ({
+ workspaceListOptions: () => ({
+ queryKey: ["workspace-list"],
+ queryFn: async () => state.wsList,
+ }),
+}));
+
+vi.mock("@multica/views/navigation", () => ({
+ useNavigation: () => ({ push: vi.fn() }),
+}));
+
+vi.mock("@multica/views/platform", () => ({
+ useDesktopUnreadBadge: () => {},
+}));
+
+// Each workspace-scoped component gets a marker so the assertions can tell
+// which of them the shell decided to mount.
+vi.mock("@multica/views/layout", () => ({
+ AppSidebar: () => <div data-testid="app-sidebar" />,
+ GlobalShortcuts: () => <div data-testid="global-shortcuts" />,
+}));
+
+vi.mock("@multica/views/modals/registry", () => ({
+ ModalRegistry: () => <div data-testid="modal-registry" />,
+}));
+
+// Stands in for the real SearchCommand, which calls useWorkspaceId() at the
+// top of its body. Mounting it without a resolvable workspace is precisely
+// the crash this gate prevents, so the stub throws the same way.
+vi.mock("@multica/views/search", () => ({
+ SearchCommand: () => {
+ const resolved = state.wsList.some((w) => w.slug === state.currentSlug);
+ if (!resolved) {
+ throw new Error(
+ "useWorkspaceId: no workspace selected — ensure component renders inside a workspace route",
+ );
+ }
+ return <div data-testid="search-command" />;
+ },
+ SearchTrigger: () => null,
+}));
+
+vi.mock("@multica/views/chat", () => ({
+ FloatingChat: () => <div data-testid="floating-chat" />,
+}));
+
+vi.mock("./tab-bar", () => ({ TabBar: () => null }));
+vi.mock("./window-overlay", () => ({ WindowOverlay: () => null }));
+vi.mock("./tab-content", () => ({
+ TabContent: () => <div data-testid="tab-content" />,
+}));
+
+const { DesktopShell } = await import("./desktop-layout");
+
+function renderShell() {
+ (
+ window as unknown as { desktopAPI: Record<string, unknown> }
+ ).desktopAPI = {
+ onNavigationGesture: () => () => {},
+ onInboxOpen: () => () => {},
+ };
+
+ const qc = new QueryClient({
+ defaultOptions: { queries: { retry: false, gcTime: 0 } },
+ });
+ qc.setQueryData(["workspace-list"], state.wsList);
+
+ return render(
+ <QueryClientProvider client={qc}>
+ <I18nProvider locale="en" resources={RESOURCES}>
+ <DesktopShell />
+ </I18nProvider>
+ </QueryClientProvider>,
+ );
+}
+
+beforeEach(() => {
+ state.currentSlug = "acme";
+ state.wsList = [{ id: "ws-1", slug: "acme" }];
+});
+
+describe("DesktopShell workspace gating", () => {
+ it("mounts workspace-scoped chrome while the slug resolves", () => {
+ const { queryByTestId } = renderShell();
+
+ expect(queryByTestId("app-sidebar")).not.toBeNull();
+ expect(queryByTestId("search-command")).not.toBeNull();
+ expect(queryByTestId("global-shortcuts")).not.toBeNull();
+ expect(queryByTestId("modal-registry")).not.toBeNull();
+ expect(queryByTestId("floating-chat")).not.toBeNull();
+ });
+
+ it("drops workspace-scoped chrome when the singleton still points at a deleted workspace", () => {
+ // Exactly the post-delete window: the list refetch has landed empty, but
+ // nothing has cleared the slug singleton yet.
+ state.wsList = [];
+
+ const { queryByTestId } = renderShell();
+
+ expect(queryByTestId("app-sidebar")).toBeNull();
+ expect(queryByTestId("search-command")).toBeNull();
+ expect(queryByTestId("global-shortcuts")).toBeNull();
+ expect(queryByTestId("modal-registry")).toBeNull();
+ expect(queryByTestId("floating-chat")).toBeNull();
+ });
+
+ it("keeps TabContent mounted with no workspace so the tab router can still resolve one", () => {
+ state.wsList = [];
+
+ const { queryByTestId } = renderShell();
+
+ expect(queryByTestId("tab-content")).not.toBeNull();
+ });
+
+ it("drops chrome for a slug belonging to a workspace the user lost access to", () => {
+ state.currentSlug = "gone";
+ state.wsList = [{ id: "ws-1", slug: "acme" }];
+
+ const { queryByTestId } = renderShell();
+
+ expect(queryByTestId("app-sidebar")).toBeNull();
+ expect(queryByTestId("search-command")).toBeNull();
+ });
+});
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 428ed4fada..50ae62ab35 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
@@ -13,6 +13,8 @@ const state = vi.hoisted(() => ({
workspaceSeen: true,
modalRenders: 0,
modalAriaLabel: "source-backfill-modal-marker",
+ currentSlug: null as string | null,
+ pendingDeletes: new Set<string>(),
}));
vi.mock("@multica/core/auth", () => {
@@ -24,8 +26,18 @@ vi.mock("@multica/core/auth", () => {
return { useAuthStore };
});
+// A real-enough stand-in for the platform singleton: the layout both writes
+// and reads it (the clear paths check `getCurrentSlug()` before wiping), so a
+// bare vi.fn() would make every guard trivially true.
vi.mock("@multica/core/platform", () => ({
- setCurrentWorkspace: vi.fn(),
+ setCurrentWorkspace: vi.fn((slug: string | null) => {
+ state.currentSlug = slug;
+ }),
+ getCurrentSlug: () => state.currentSlug,
+}));
+
+vi.mock("@multica/core/workspace/pending-delete", () => ({
+ isWorkspaceDeletePending: (id: string) => state.pendingDeletes.has(id),
}));
vi.mock("@multica/core/workspace", async () => {
@@ -129,6 +141,8 @@ beforeEach(() => {
state.wsList = [{ id: "ws-1", slug: "acme" }];
state.workspaceSeen = true;
state.modalRenders = 0;
+ state.currentSlug = null;
+ state.pendingDeletes = new Set<string>();
});
describe("WorkspaceRouteLayout", () => {
@@ -145,3 +159,61 @@ describe("WorkspaceRouteLayout", () => {
expect(state.modalRenders).toBe(0);
});
});
+
+/**
+ * MUL-6231 / #7021. This layout is the only owner of the platform workspace
+ * singleton, and it used to only ever SET it. Deleting the active workspace
+ * therefore left the singleton pointing at a workspace that no longer existed,
+ * which is what kept the desktop shell mounting workspace-scoped chrome over
+ * nothing until a `useWorkspaceId()` throw blanked the whole renderer.
+ */
+describe("WorkspaceRouteLayout workspace singleton lifecycle", () => {
+ it("adopts the workspace while it resolves", () => {
+ renderLayout();
+ expect(state.currentSlug).toBe("acme");
+ });
+
+ it("releases the singleton once the workspace stops resolving", () => {
+ state.currentSlug = "acme";
+ state.workspace = null;
+ state.wsList = [];
+
+ renderLayout();
+
+ expect(state.currentSlug).toBeNull();
+ });
+
+ it("does not re-adopt a workspace whose delete this client started", () => {
+ // The exact post-delete window: useDeleteWorkspace has cleared the
+ // singleton and navigated, but its list invalidation is still in flight so
+ // the deleted workspace is very much still in the cache. Re-adopting here
+ // would stamp the dead slug back over the delete flow's own cleanup.
+ state.currentSlug = null;
+ state.pendingDeletes = new Set(["ws-1"]);
+
+ renderLayout();
+
+ expect(state.currentSlug).toBeNull();
+ });
+
+ it("releases the singleton on unmount", () => {
+ const { unmount } = renderLayout();
+ expect(state.currentSlug).toBe("acme");
+
+ unmount();
+
+ expect(state.currentSlug).toBeNull();
+ });
+
+ it("leaves the singleton alone when it already points at another workspace", () => {
+ // Workspace switch: React renders the incoming layout (which adopts the
+ // new slug) before running the outgoing layout's cleanup. An unguarded
+ // clear would wipe the workspace context that just arrived.
+ const { unmount } = renderLayout();
+ state.currentSlug = "other";
+
+ unmount();
+
+ expect(state.currentSlug).toBe("other");
+ });
+});
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 b346b094f1..f82301732b 100644
--- a/apps/desktop/src/renderer/src/components/workspace-route-layout.tsx
+++ b/apps/desktop/src/renderer/src/components/workspace-route-layout.tsx
@@ -6,7 +6,8 @@ import {
workspaceBySlugOptions,
workspaceListOptions,
} from "@multica/core/workspace";
-import { setCurrentWorkspace } from "@multica/core/platform";
+import { getCurrentSlug, setCurrentWorkspace } from "@multica/core/platform";
+import { isWorkspaceDeletePending } from "@multica/core/workspace/pending-delete";
import { useAuthStore } from "@multica/core/auth";
import { useWorkspaceSeen } from "@multica/views/workspace/use-workspace-seen";
import { WelcomeAfterOnboarding } from "@multica/views/workspace/welcome-after-onboarding";
@@ -65,7 +66,19 @@ export function WorkspaceRouteLayout() {
// Feed the URL slug into the platform singleton so the API client's
// X-Workspace-Slug header and persist namespace follow the active tab.
// setCurrentWorkspace self-dedupes on slug equality.
- if (workspace && workspaceSlug) {
+ //
+ // Stays in render (not an effect) on purpose: children mount below this
+ // one and their queries fire in effects, which run bottom-up — an effect
+ // here would set the header AFTER the first child query already used it.
+ //
+ // The pending-delete guard exists because this write would otherwise undo
+ // the delete flow's own cleanup (MUL-6231 / #7021). useDeleteWorkspace
+ // clears the singleton and navigates away, but this layout is subscribed to
+ // the overlay store, so opening the new-workspace overlay re-renders it
+ // while the deleted workspace is STILL in the list cache (the invalidation
+ // refetch is a network round-trip). Without the guard we write the dead slug
+ // straight back over the cleanup.
+ if (workspace && workspaceSlug && !isWorkspaceDeletePending(workspace.id)) {
setCurrentWorkspace(workspaceSlug, workspace.id);
}
@@ -88,6 +101,30 @@ export function WorkspaceRouteLayout() {
useTabStore.getState().validateWorkspaceSlugs(validSlugs);
}, [user, listFetched, workspace, hasBeenSeen, wsList]);
+ // Release the platform singleton when this layout's workspace stops
+ // resolving, and again when the layout unmounts. Nothing else owned that
+ // lifecycle: the singleton used to keep pointing at a deleted workspace
+ // indefinitely, which is how the shell ended up holding workspace-scoped
+ // chrome over a workspace that no longer existed (MUL-6231 / #7021).
+ //
+ // Both paths check `getCurrentSlug() === workspaceSlug` first. On a
+ // workspace switch React renders the incoming layout — which sets the
+ // 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 (workspace) return;
+ if (getCurrentSlug() !== workspaceSlug) return;
+ setCurrentWorkspace(null, null);
+ }, [listFetched, workspace, workspaceSlug]);
+
+ useEffect(() => {
+ return () => {
+ if (getCurrentSlug() !== workspaceSlug) return;
+ setCurrentWorkspace(null, null);
+ };
+ }, [workspaceSlug]);
+
if (isAuthLoading) return null;
if (!user) return null;
if (!workspaceSlug) return null;
diff --git a/apps/desktop/src/renderer/src/main.tsx b/apps/desktop/src/renderer/src/main.tsx
index 2ed0727594..56852a09c5 100644
--- a/apps/desktop/src/renderer/src/main.tsx
+++ b/apps/desktop/src/renderer/src/main.tsx
@@ -1,5 +1,6 @@
import ReactDOM from "react-dom/client";
import App from "./App";
+import { AppCrashBoundary } from "./components/app-crash-boundary";
// Inter variable font covers all weights (100-900) in a single file.
// CJK is handled by system font fallback (see globals.css --font-sans chain).
// Keep font stack in sync with apps/web/app/layout.tsx.
@@ -37,4 +38,8 @@ if (import.meta.env.DEV && import.meta.env.VITE_REACT_GRAB) {
document.head.appendChild(grab);
}
-ReactDOM.createRoot(document.getElementById("root")!).render(<App />);
+ReactDOM.createRoot(document.getElementById("root")!).render(
+ <AppCrashBoundary>
+ <App />
+ </AppCrashBoundary>,
+);
diff --git a/packages/core/package.json b/packages/core/package.json
index b42eb12c01..9c4f528559 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -25,6 +25,7 @@
"./workspace": "./workspace/index.ts",
"./workspace/queries": "./workspace/queries.ts",
"./workspace/mutations": "./workspace/mutations.ts",
+ "./workspace/pending-delete": "./workspace/pending-delete.ts",
"./workspace/hooks": "./workspace/hooks.ts",
"./workspace/workspace-url": "./workspace/workspace-url.ts",
"./workspace/avatar-url": "./workspace/avatar-url.ts",