Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(web): only let the routed layout own the workspace singleton (#7346)
Eric Berryff90875003fe
diff --git a/apps/web/app/[workspaceSlug]/layout.test.tsx b/apps/web/app/[workspaceSlug]/layout.test.tsxindex ecbe2a8af7..d2ab07b9cb 100644--- a/apps/web/app/[workspaceSlug]/layout.test.tsx+++ b/apps/web/app/[workspaceSlug]/layout.test.tsx@@ -10,13 +10,16 @@ const state = vi.hoisted(() => ({} as { id: string; onboarded_at: string | null } | null,isAuthLoading: false,workspace: null as { id: string; slug: string } | null,+ workspacesBySlug: {} as Record<string, { id: string; slug: string } | null>,workspaceError: false,hasBeenSeen: false,+ pathname: "/acme/issues",replace: vi.fn(),}));vi.mock("next/navigation", () => ({useRouter: () => ({ replace: state.replace }),+ usePathname: () => state.pathname,}));vi.mock("@multica/core/auth", () => ({@@ -29,10 +32,11 @@ vi.mock("@multica/core/auth", () => ({}));vi.mock("@multica/core/workspace", () => ({- workspaceBySlugOptions: () => ({- queryKey: ["workspace-by-slug", "acme"],+ workspaceBySlugOptions: (slug: string) => ({+ queryKey: ["workspace-by-slug", slug],queryFn: async () => {if (state.workspaceError) throw new Error("temporary failure");+ if (slug in state.workspacesBySlug) return state.workspacesBySlug[slug];return state.workspace;},}),@@ -68,35 +72,40 @@ vi.mock("@multica/ui/components/common/multica-icon", () => ({MulticaIcon: () => <div data-testid="workspace-loading" />,}));+import { setCurrentWorkspace } from "@multica/core/platform";import WorkspaceLayout from "./layout";-function renderLayout() {+/** `use()` unwraps a params promise synchronously only when it is already+ * settled, which is how the App Router hands it over at runtime. */+function makeParams(workspaceSlug: string) {+ return Object.assign(Promise.resolve({ workspaceSlug }), {+ status: "fulfilled",+ value: { workspaceSlug },+ });+}++function renderTree(node: ReactNode) {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>,+ <Suspense fallback={<div data-testid="route-loading" />}>{node}</Suspense>,{ wrapper },);return { ...result, queryClient };}+function renderLayout(slug = "acme") {+ return renderTree(+ <WorkspaceLayout params={makeParams(slug)}>+ <div data-testid="workspace-content" />+ </WorkspaceLayout>,+ );+}+beforeEach(() => {vi.clearAllMocks();state.user = {@@ -105,8 +114,10 @@ beforeEach(() => {};state.isAuthLoading = false;state.workspace = null;+ state.workspacesBySlug = {};state.workspaceError = false;state.hasBeenSeen = false;+ state.pathname = "/acme/issues";});describe("WorkspaceLayout", () => {@@ -130,3 +141,80 @@ describe("WorkspaceLayout", () => {expect(screen.queryByTestId("workspace-loading")).toBeNull();});});++/**+ * The platform workspace singleton is a module global written from render, so+ * it is only safe while exactly one layout claims it. The App Router can keep+ * a previous workspace's layout mounted beside the incoming one; unguarded,+ * both wrote on every render and the singleton alternated indefinitely. That+ * churn tore down and rebuilt the realtime socket, which binds to this slug,+ * and re-pointed the @mention lookup, which reads it synchronously and returns+ * an empty list for a workspace with no warm cache. The live pathname is the+ * tiebreak: one value shared by every instance, so only the routed one writes.+ */+describe("WorkspaceLayout workspace singleton", () => {+ it("adopts the workspace when its slug is the routed one", async () => {+ state.pathname = "/acme/issues";+ state.workspacesBySlug = { acme: { id: "ws-acme", slug: "acme" } };++ renderLayout("acme");++ await waitFor(() => {+ expect(setCurrentWorkspace).toHaveBeenCalledWith("acme", "ws-acme");+ });+ });++ it("stays silent while another workspace owns the URL", async () => {+ state.pathname = "/globex/issues";+ state.workspacesBySlug = { acme: { id: "ws-acme", slug: "acme" } };++ const { queryClient } = renderLayout("acme");++ // Resolving the query is what would trigger the render-phase write.+ await waitFor(() => {+ expect(+ queryClient.getQueryState(["workspace-by-slug", "acme"])?.status,+ ).toBe("success");+ });+ expect(setCurrentWorkspace).not.toHaveBeenCalled();+ });++ it("lets only the routed layout write when both are mounted", async () => {+ state.pathname = "/globex/issues";+ state.workspacesBySlug = {+ acme: { id: "ws-acme", slug: "acme" },+ globex: { id: "ws-globex", slug: "globex" },+ };++ // The stale layout renders first, as it would during a transition the+ // router has not finished tearing down.+ const { queryClient } = renderTree(+ <>+ <WorkspaceLayout params={makeParams("acme")}>+ <div data-testid="stale-content" />+ </WorkspaceLayout>+ <WorkspaceLayout params={makeParams("globex")}>+ <div data-testid="routed-content" />+ </WorkspaceLayout>+ </>,+ );++ await waitFor(() => {+ expect(+ queryClient.getQueryState(["workspace-by-slug", "acme"])?.status,+ ).toBe("success");+ expect(+ queryClient.getQueryState(["workspace-by-slug", "globex"])?.status,+ ).toBe("success");+ });++ await waitFor(() => {+ expect(setCurrentWorkspace).toHaveBeenCalledWith("globex", "ws-globex");+ });+ // The regression: every call names the routed workspace. A single write+ // from the stale layout is one socket teardown and one empty mention list.+ for (const call of vi.mocked(setCurrentWorkspace).mock.calls) {+ expect(call).toEqual(["globex", "ws-globex"]);+ }+ });+});diff --git a/apps/web/app/[workspaceSlug]/layout.tsx b/apps/web/app/[workspaceSlug]/layout.tsxindex cb92f72503..f150e61d5f 100644--- a/apps/web/app/[workspaceSlug]/layout.tsx+++ b/apps/web/app/[workspaceSlug]/layout.tsx@@ -2,7 +2,7 @@import { use, useEffect } from "react";import { useQuery } from "@tanstack/react-query";-import { useRouter } from "next/navigation";+import { useRouter, usePathname } from "next/navigation";import { WorkspaceSlugProvider, paths } from "@multica/core/paths";import { workspaceBySlugOptions } from "@multica/core/workspace";import { setCurrentWorkspace } from "@multica/core/platform";@@ -11,6 +11,7 @@ import { NoAccessPage } from "@multica/views/workspace/no-access-page";import { WelcomeAfterOnboarding } from "@multica/views/workspace/welcome-after-onboarding";import { MulticaIcon } from "@multica/ui/components/common/multica-icon";import { useWorkspaceSeen } from "@multica/views/workspace/use-workspace-seen";+import { workspaceSlugFromPathname } from "@/lib/workspace-slug-from-pathname";export default function WorkspaceLayout({children,@@ -23,6 +24,7 @@ export default function WorkspaceLayout({const user = useAuthStore((s) => s.user);const isAuthLoading = useAuthStore((s) => s.isLoading);const router = useRouter();+ const pathname = usePathname();// Workspace routes require auth. If user is unauthenticated (initial visit// without a session, token expired, another tab logged out, etc.), bounce@@ -56,7 +58,25 @@ export default function WorkspaceLayout({// the first child query's X-Workspace-Slug header is already correct.// setCurrentWorkspace self-dedupes + runs rehydrate as a side effect;// safe to call on every render.- if (workspace) {+ //+ // Gated on the live pathname because this is a module-global write from+ // render, and the App Router can keep a previous workspace's layout mounted+ // beside the incoming one. Both instances re-render on their own query+ // activity, so an unguarded write let them alternate — every render flipping+ // the singleton back to its own slug, indefinitely. Each flip tore down and+ // rebuilt the realtime socket (packages/core/realtime/provider.tsx binds it+ // to this slug) and re-pointed the @mention lookup, which reads the same+ // singleton synchronously and falls back to an empty list when the workspace+ // it names has no warm cache (packages/views/editor/extensions/+ // mention-suggestion.tsx). Realtime went dead and the mention list came back+ // empty for whichever workspace the user was actually looking at.+ //+ // Comparing against the pathname resolves it without an ownership handshake:+ // the URL is the source of truth for workspace identity, and usePathname()+ // is one value shared by every mounted instance, so exactly one layout — the+ // routed one — can define it. Desktop needs its own protocol instead+ // (workspace-route-layout.tsx) because it has no URL bar to appeal to.+ if (workspace && workspaceSlug === workspaceSlugFromPathname(pathname)) {setCurrentWorkspace(workspaceSlug, workspace.id);}diff --git a/apps/web/lib/workspace-slug-from-pathname.test.ts b/apps/web/lib/workspace-slug-from-pathname.test.tsnew file mode 100644index 0000000000..16a3287589--- /dev/null+++ b/apps/web/lib/workspace-slug-from-pathname.test.ts@@ -0,0 +1,40 @@+// @vitest-environment node+import { describe, it, expect } from "vitest";+import { workspaceSlugFromPathname } from "./workspace-slug-from-pathname";++describe("workspaceSlugFromPathname", () => {+ it("reads the first segment of a workspace route", () => {+ expect(workspaceSlugFromPathname("/acme/issues")).toBe("acme");+ expect(workspaceSlugFromPathname("/acme")).toBe("acme");+ expect(workspaceSlugFromPathname("/acme/issues/ACME-1")).toBe("acme");+ });++ it("tolerates trailing and doubled separators", () => {+ expect(workspaceSlugFromPathname("/acme/")).toBe("acme");+ expect(workspaceSlugFromPathname("//acme//issues")).toBe("acme");+ });++ it("returns null when there is no first segment", () => {+ expect(workspaceSlugFromPathname("/")).toBeNull();+ expect(workspaceSlugFromPathname("")).toBeNull();+ expect(workspaceSlugFromPathname(null)).toBeNull();+ expect(workspaceSlugFromPathname(undefined)).toBeNull();+ });++ it("decodes the segment so it can compare equal to a route param", () => {+ // Route params arrive decoded; the pathname segment does not.+ expect(workspaceSlugFromPathname("/a%20b/issues")).toBe("a b");+ expect(workspaceSlugFromPathname("/caf%C3%A9")).toBe("café");+ });++ it("falls back to the raw segment when it is not valid encoding", () => {+ expect(workspaceSlugFromPathname("/100%/issues")).toBe("100%");+ });++ it("returns the first segment of a global route, which no slug equals", () => {+ // Reserved slugs are rejected at creation, so a workspace layout+ // comparing its own slug against these can never match.+ expect(workspaceSlugFromPathname("/login")).toBe("login");+ expect(workspaceSlugFromPathname("/workspaces/new")).toBe("workspaces");+ });+});diff --git a/apps/web/lib/workspace-slug-from-pathname.ts b/apps/web/lib/workspace-slug-from-pathname.tsnew file mode 100644index 0000000000..2c1477cbf3--- /dev/null+++ b/apps/web/lib/workspace-slug-from-pathname.ts@@ -0,0 +1,28 @@+/**+ * The workspace slug the router is currently on, read from the live pathname.+ *+ * The URL is the source of truth for workspace identity on web, so this is+ * what `app/[workspaceSlug]/layout.tsx` compares its own `params` slug against+ * before it writes the platform workspace singleton. `usePathname()` returns+ * one value shared by every mounted instance, which is what lets a stale+ * layout recognise that it is no longer the routed one.+ *+ * Returns null for the root and for anything without a first segment. Global+ * routes (`/login`, `/workspaces/new`) do return their first segment — the+ * caller is a workspace layout that only ever compares against its own slug,+ * and a reserved slug can never equal one.+ */+export function workspaceSlugFromPathname(+ pathname: string | null | undefined,+): string | null {+ const segment = pathname?.split("/").filter(Boolean)[0];+ if (!segment) return null;+ // Route params arrive decoded while the pathname segment stays encoded, so+ // a slug needing escapes would never compare equal without this. A lone `%`+ // throws rather than decoding, so fall back to the raw segment.+ try {+ return decodeURIComponent(segment);+ } catch {+ return segment;+ }+}