Skip to content

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

Go

MUL-8028: fix(desktop): navigate existing reserved workspace slugs (ZIC-336) (#9276)

ZIceb24d3595a18d
diff --git a/apps/desktop/src/renderer/src/platform/navigation.test.tsx b/apps/desktop/src/renderer/src/platform/navigation.test.tsx
index 52f3bdd651..feebef7600 100644
--- a/apps/desktop/src/renderer/src/platform/navigation.test.tsx
+++ b/apps/desktop/src/renderer/src/platform/navigation.test.tsx
@@ -1,5 +1,10 @@
-import { describe, expect, it, vi, beforeEach } from "vitest";
+import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";
import { act, render } from "@testing-library/react";
+import {
+ bindWorkspaceSlugLookup,
+ createQueryClient,
+} from "@multica/core/query-client";
+import { workspaceKeys } from "@multica/core/workspace/queries";
import { useEffect } from "react";
// MUL-4741: the adapter mutates tab sessions in the REAL store (no router,
@@ -31,6 +36,18 @@ import { DesktopNavigationProvider, routeContentLinkPath } from "./navigation";
import { currentPath, useNavigation } from "@multica/views/navigation";
import { useTabStore, getActiveTab } from "@/stores/tab-store";
+let unbindWorkspaces: () => void = () => {};
+
+/** Give the current account membership of `slugs`, as the mounted provider would. */
+function withWorkspaces(slugs: string[]) {
+ const client = createQueryClient();
+ unbindWorkspaces = bindWorkspaceSlugLookup(client);
+ client.setQueryData(workspaceKeys.list(), slugs.map((slug) => ({ slug })));
+ return client;
+}
+
+afterEach(() => unbindWorkspaces());
+
beforeEach(() => {
overlay.open.mockReset();
overlay.close.mockReset();
@@ -355,3 +372,31 @@ describe("routeContentLinkPath (links inside content — MUL-5208)", () => {
).toBe(false);
});
});
+
+describe("existing reserved workspace navigation", () => {
+ it.each(["push", "replace", "openInNewTab", "content"])(
+ "routes %s through the workspace switch flow",
+ (action) => {
+ withWorkspaces(["dingtalk"]);
+ const adapter = renderProvider();
+ act(() => {
+ if (action === "content") routeContentLinkPath("/dingtalk/issues/ISS-1", "background-tab");
+ else if (action === "openInNewTab") adapter().openInNewTab!("/dingtalk/issues/ISS-1");
+ else if (action === "replace") adapter().replace("/dingtalk/issues/ISS-1");
+ else adapter().push("/dingtalk/issues");
+ });
+ expect(useTabStore.getState().activeWorkspaceSlug).toBe("dingtalk");
+ expect(getActiveTab(useTabStore.getState())?.url).toBe(
+ action === "push" ? "/dingtalk/issues" : "/dingtalk/issues/ISS-1",
+ );
+ },
+ );
+
+ it("does not send a known invite workspace entity route to the invite overlay", () => {
+ withWorkspaces(["invite"]);
+ const adapter = renderProvider();
+ act(() => adapter().push("/invite/issues/MUL-123"));
+ expect(overlay.open).not.toHaveBeenCalled();
+ expect(getActiveTab(useTabStore.getState())?.url).toBe("/invite/issues/MUL-123");
+ });
+});
diff --git a/apps/desktop/src/renderer/src/platform/navigation.tsx b/apps/desktop/src/renderer/src/platform/navigation.tsx
index b469b05dfd..22ad250157 100644
--- a/apps/desktop/src/renderer/src/platform/navigation.tsx
+++ b/apps/desktop/src/renderer/src/platform/navigation.tsx
@@ -5,7 +5,7 @@ import {
type NavigationAdapter,
} from "@multica/views/navigation";
import { useAuthStore } from "@multica/core/auth";
-import { isReservedSlug, paths } from "@multica/core/paths";
+import { workspaceSlugForPath, paths } from "@multica/core/paths";
import {
useTabStore,
getActiveTab,
@@ -24,17 +24,6 @@ function requireRuntimeAppUrl(scope: string): string {
return runtimeConfig.config.appUrl;
}
-/**
- * Extract the leading workspace slug from a path, or null if the path isn't
- * workspace-scoped (root, login, any reserved prefix).
- */
-function extractWorkspaceSlug(path: string): string | null {
- const first = path.split("/").filter(Boolean)[0] ?? "";
- if (!first) return null;
- if (isReservedSlug(first)) return null;
- return first;
-}
-
/**
* Intercept navigation to "transition" paths — pre-workspace flows that on
* desktop are rendered as a window-level overlay instead of a tab route.
@@ -60,7 +49,7 @@ function tryRouteToOverlay(path: string): boolean {
overlay.open({ type: "invitations" });
return true;
}
- if (path.startsWith("/invite/")) {
+ if (path.startsWith("/invite/") && !workspaceSlugForPath(path)) {
let id = "";
try {
id = decodeURIComponent(path.slice("/invite/".length));
@@ -92,7 +81,7 @@ function tryRouteToOverlay(path: string): boolean {
* has none. Any deeper path opens exactly that path.
*/
function tryRouteToOtherWorkspace(path: string): boolean {
- const targetSlug = extractWorkspaceSlug(path);
+ const targetSlug = workspaceSlugForPath(path);
if (!targetSlug) return false;
const { activeWorkspaceSlug, switchWorkspace } = useTabStore.getState();
if (targetSlug === activeWorkspaceSlug) return false;
@@ -118,7 +107,7 @@ export function routeContentLinkPath(
disposition: LinkClickIntent = "push",
): void {
const store = useTabStore.getState();
- const slug = extractWorkspaceSlug(path);
+ const slug = workspaceSlugForPath(path);
if (slug && slug !== store.activeWorkspaceSlug) {
store.switchWorkspace(slug, path);
return;
@@ -242,7 +231,7 @@ export function DesktopNavigationProvider({
// defaults to background tab (browser cmd+click semantics); callers
// that represent an explicit "Open in new tab" CTA pass
// `activate: true` to bring the new tab to the foreground.
- const slug = extractWorkspaceSlug(path);
+ const slug = workspaceSlugForPath(path);
const store = useTabStore.getState();
if (slug && slug !== store.activeWorkspaceSlug) {
store.switchWorkspace(slug, path);
diff --git a/apps/desktop/src/renderer/src/stores/tab-store.test.ts b/apps/desktop/src/renderer/src/stores/tab-store.test.ts
index 84d5fec690..3a758856c5 100644
--- a/apps/desktop/src/renderer/src/stores/tab-store.test.ts
+++ b/apps/desktop/src/renderer/src/stores/tab-store.test.ts
@@ -1576,3 +1576,22 @@ describe("mergePersistedTabs (rehydration, MUL-4370)", () => {
});
});
});
+
+describe("reserved workspace restoration", () => {
+ it("preserves matching saved tabs before the membership list loads", () => {
+ useTabStore.getState().switchWorkspace("acme");
+ const group = useTabStore.getState().byWorkspace.acme;
+ const tabs = group.tabs.map((tab) => ({
+ ...tab, url: "/dingtalk/issues", history: { stack: ["/dingtalk/issues"], index: 0 },
+ }));
+ const restored = mergePersistedTabs({
+ activeWorkspaceSlug: "dingtalk",
+ byWorkspace: { dingtalk: { ...group, tabs, browsingHistory: ["/dingtalk/issues"] } },
+ }, { activeWorkspaceSlug: null as string | null, byWorkspace: {} as Record<string, WorkspaceTabGroup> });
+ expect(restored.byWorkspace.dingtalk.tabs[0].url).toBe("/dingtalk/issues");
+ expect(restored.byWorkspace.dingtalk.browsingHistory).toEqual(["/dingtalk/issues"]);
+ useTabStore.setState(restored);
+ useTabStore.getState().validateWorkspaceSlugs(new Set(["acme"]));
+ expect(useTabStore.getState().byWorkspace.dingtalk).toBeUndefined();
+ });
+});
diff --git a/apps/desktop/src/renderer/src/stores/tab-store.ts b/apps/desktop/src/renderer/src/stores/tab-store.ts
index f8c8be09b3..251fa9bd63 100644
--- a/apps/desktop/src/renderer/src/stores/tab-store.ts
+++ b/apps/desktop/src/renderer/src/stores/tab-store.ts
@@ -3,7 +3,7 @@ import { createJSONStorage, persist } from "zustand/middleware";
import { arrayMove } from "@dnd-kit/sortable";
import { createPersistStorage, defaultStorage } from "@multica/core/platform";
import { createSafeId } from "@multica/core/utils";
-import { isReservedSlug } from "@multica/core/paths";
+import { workspaceSlugForPath } from "@multica/core/paths";
// Tab sessions hold serializable URLs, identity, virtual history, and view
// mementos. The coordinator projects the active session onto the single router;
@@ -293,15 +293,6 @@ interface TabStore {
// surfaces cannot drift, and no stale icon can survive in persisted state.
// Title is likewise not determined here; it comes from document.title.
-/** Extract the leading workspace slug from a path, or null if the path
- * isn't workspace-scoped (global path, root, or empty). */
-function extractWorkspaceSlug(path: string): string | null {
- const first = path.split("/").filter(Boolean)[0] ?? "";
- if (!first) return null;
- if (isReservedSlug(first)) return null;
- return first;
-}
-
// URL helpers
/** Split a tab URL into pathname and the search+hash suffix. */
@@ -370,12 +361,12 @@ function inboxSelectionKeyForUrl(url: string): string | null {
* Returns null for rejects (caller decides how to recover — usually by
* dropping the tab or substituting a default).
*/
-export function sanitizeTabPath(path: string): string | null {
+export function sanitizeTabPath(path: string, savedGroupSlug?: string): string | null {
const { pathname, suffix } = splitTabUrl(path);
const segments = pathname.split("/").filter(Boolean);
const firstSegment = segments[0] ?? "";
if (!firstSegment) return null;
- if (isReservedSlug(firstSegment)) {
+ if (!workspaceSlugForPath(path, savedGroupSlug)) {
// Don't log for known transition paths — these are legitimate inputs
// at the interception boundary (older persisted state or stale callers).
const isTransition = path === "/workspaces/new" || path.startsWith("/invite/");
@@ -473,7 +464,7 @@ function withBrowsingVisit(
options: BrowsingVisitOptions = {},
): WorkspaceTabGroup {
const clean = sanitizeTabPath(url);
- if (!clean || extractWorkspaceSlug(clean) !== slug) return group;
+ if (!clean || workspaceSlugForPath(clean) !== slug) return group;
const historyKey = browsingHistoryKeyForUrl(clean);
const replacedHistoryKey = options.replacedUrl
? browsingHistoryKeyForUrl(options.replacedUrl)
@@ -565,8 +556,8 @@ function normalizeBrowsingHistory(value: unknown, slug: string): string[] {
const seenResources = new Set<string>();
for (const candidate of value) {
if (typeof candidate !== "string") continue;
- const clean = sanitizeTabPath(candidate);
- if (!clean || extractWorkspaceSlug(clean) !== slug) continue;
+ const clean = sanitizeTabPath(candidate, slug);
+ if (!clean || workspaceSlugForPath(clean, slug) !== slug) continue;
const resourceKey = browsingHistoryKeyForUrl(clean);
if (seenResources.has(resourceKey)) continue;
seenResources.add(resourceKey);
@@ -985,7 +976,7 @@ export const useTabStore = create<TabStore>()(
if (!clean) return;
// A session never navigates out of its workspace — cross-workspace
// pushes go through switchWorkspace at the adapter layer.
- if (extractWorkspaceSlug(clean) !== activeWorkspaceSlug) return;
+ if (workspaceSlugForPath(clean) !== activeWorkspaceSlug) return;
const current = group.tabs[index];
if (current.url === clean) return;
@@ -1344,11 +1335,11 @@ export function mergePersistedTabs<T extends PersistedTabState>(
for (const [slug, pGroup] of Object.entries(persisted.byWorkspace)) {
const tabs: TabSession[] = [];
for (const pTab of pGroup.tabs) {
- const clean = sanitizeTabPath(pTab.url);
+ const clean = sanitizeTabPath(pTab.url, slug);
// Persisted url may have come from a stale version or a
// manual edit. Drop rather than rewrite so we never silently
// put users on a url that doesn't match the group's slug.
- if (!clean || extractWorkspaceSlug(clean) !== slug) {
+ if (!clean || workspaceSlugForPath(clean, slug) !== slug) {
console.warn(
`[tab-store] dropping persisted tab "${pTab.url}" from ` +
`group "${slug}" — url/slug mismatch`,
@@ -1653,7 +1644,7 @@ export function migrateV1ToV2(v1: Partial<V1Persisted>): V2Persisted {
const byWorkspace: Record<string, V2PersistedGroup> = {};
const oldTabs = v1.tabs ?? [];
for (const tab of oldTabs) {
- const slug = extractWorkspaceSlug(tab.path);
+ const slug = workspaceSlugForPath(tab.path);
if (!slug) continue; // drop root / global-path tabs
if (!byWorkspace[slug]) byWorkspace[slug] = { tabs: [], activeTabId: "" };
byWorkspace[slug].tabs.push({
diff --git a/packages/core/paths/index.ts b/packages/core/paths/index.ts
index 1b92156831..6a7cfe4364 100644
--- a/packages/core/paths/index.ts
+++ b/packages/core/paths/index.ts
@@ -41,3 +41,5 @@ export {
useCurrentWorkspace,
useWorkspacePaths,
} from "./hooks";
+
+export { isKnownWorkspacePath, workspaceSlugForPath } from "./workspace-slugs";
diff --git a/packages/core/paths/workspace-slugs.test.ts b/packages/core/paths/workspace-slugs.test.ts
new file mode 100644
index 0000000000..5e58df2e53
--- /dev/null
+++ b/packages/core/paths/workspace-slugs.test.ts
@@ -0,0 +1,30 @@
+// @vitest-environment node
+import { afterEach, describe, expect, it } from "vitest";
+import { isReservedSlug } from "./reserved-slugs";
+import { setWorkspaceSlugLookup, workspaceSlugForPath } from "./workspace-slugs";
+
+afterEach(() => setWorkspaceSlugLookup(() => false));
+
+describe("workspaceSlugForPath", () => {
+ it("admits existing reserved workspaces without changing creation policy", () => {
+ expect(workspaceSlugForPath("/dingtalk/issues")).toBeNull();
+ setWorkspaceSlugLookup((slug) => slug === "dingtalk");
+ expect(workspaceSlugForPath("/dingtalk/issues?filter=mine#comment")).toBe("dingtalk");
+ expect(workspaceSlugForPath("/dingtalk/members/member-1")).toBe("dingtalk");
+ expect(workspaceSlugForPath("/dingtalk/attachments/file-1/preview")).toBe("dingtalk");
+ expect(isReservedSlug("dingtalk")).toBe(true);
+ });
+
+ it.each(["/dingtalk/bind", "/auth/callback", "/workspaces/new", "/invite/token", "/api/workspaces", "/uploads/file", "/login", "/"])("keeps %s global even with a matching membership", (path) => {
+ setWorkspaceSlugLookup(() => true);
+ expect(workspaceSlugForPath(path)).toBeNull();
+ });
+
+ it("only preserves matching saved workspace routes", () => {
+ expect(workspaceSlugForPath("/dingtalk/issues", "dingtalk")).toBe("dingtalk");
+ expect(workspaceSlugForPath("/dingtalk/issues", "acme")).toBeNull();
+ expect(workspaceSlugForPath("/dingtalk/bind", "dingtalk")).toBeNull();
+ expect(workspaceSlugForPath("/acme/issues")).toBe("acme");
+ expect(workspaceSlugForPath("/%broken/issues")).toBeNull();
+ });
+});
diff --git a/packages/core/paths/workspace-slugs.ts b/packages/core/paths/workspace-slugs.ts
new file mode 100644
index 0000000000..287fb4626f
--- /dev/null
+++ b/packages/core/paths/workspace-slugs.ts
@@ -0,0 +1,65 @@
+import { isReservedSlug } from "./reserved-slugs";
+import { WORKSPACE_PAGES } from "./route-icons";
+
+type WorkspaceSlugLookup = (slug: string) => boolean;
+
+const noWorkspaces: WorkspaceSlugLookup = () => false;
+let lookup: WorkspaceSlugLookup = noWorkspaces;
+
+/**
+ * Bind the account's workspace membership lookup without copying server
+ * state. Returns an unbind that only resets the lookup if it is still the one
+ * installed here, so a stale owner can never clear a newer binding.
+ */
+export function setWorkspaceSlugLookup(next: WorkspaceSlugLookup): () => void {
+ lookup = next;
+ return () => {
+ if (lookup === next) lookup = noWorkspaces;
+ };
+}
+
+const workspaceRoutes = new Set([
+ ...Object.values(WORKSPACE_PAGES).map((page) => page.segment),
+ "members",
+ "attachments",
+]);
+
+function splitWorkspacePath(path: string): { slug: string; route?: string } | null {
+ const pathname = path.split(/[?#]/, 1)[0] ?? "";
+ const [rawSlug, route] = pathname.split("/").filter(Boolean);
+ if (!rawSlug) return null;
+ try {
+ return { slug: decodeURIComponent(rawSlug), route };
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Reservation governs creation, not existing workspace membership. For a
+ * reserved slug, require a workspace route too so /dingtalk/bind and other
+ * global endpoints remain global. Saved groups may supply their own slug
+ * until the shell validates them against the loaded membership list.
+ */
+export function workspaceSlugForPath(path: string, savedGroupSlug?: string): string | null {
+ const parts = splitWorkspacePath(path);
+ if (!parts) return null;
+ const { slug, route } = parts;
+ if (isReservedSlug(slug.toLowerCase())) {
+ if (slug !== savedGroupSlug && !lookup(slug)) return null;
+ if (!route || !workspaceRoutes.has(route)) return null;
+ }
+ return slug;
+}
+
+/**
+ * Report whether a path is `/{slug}/{workspace-route}/...` for a workspace the
+ * current account actually belongs to. Unlike `workspaceSlugForPath`, an
+ * arbitrary non-reserved first segment does not qualify — callers use this to
+ * tell a real workspace URL apart from a legacy unscoped one such as `/chat`.
+ */
+export function isKnownWorkspacePath(path: string): boolean {
+ const parts = splitWorkspacePath(path);
+ if (!parts?.route || !workspaceRoutes.has(parts.route)) return false;
+ return lookup(parts.slug);
+}
diff --git a/packages/core/provider.tsx b/packages/core/provider.tsx
index c9be26457d..8e29e5561b 100644
--- a/packages/core/provider.tsx
+++ b/packages/core/provider.tsx
@@ -1,12 +1,16 @@
"use client";
-import { useState } from "react";
+import { useEffect, useState } from "react";
import { QueryClientProvider } from "@tanstack/react-query";
-import { createQueryClient } from "./query-client";
+import { bindWorkspaceSlugLookup, createQueryClient } from "./query-client";
import type { ReactNode } from "react";
export function QueryProvider({ children }: { children: ReactNode }) {
const [queryClient] = useState(createQueryClient);
+ // Bind the client React actually kept. Effects never run during server
+ // rendering, so account state is never shared between requests. Lookups
+ // read the cache lazily, and the workspace list only arrives after mount.
+ useEffect(() => bindWorkspaceSlugLookup(queryClient), [queryClient]);
return (
<QueryClientProvider client={queryClient}>
{children}
diff --git a/packages/core/query-client.ts b/packages/core/query-client.ts
index 831a2e9113..7a8ada9172 100644
--- a/packages/core/query-client.ts
+++ b/packages/core/query-client.ts
@@ -1,4 +1,7 @@
import { QueryClient } from "@tanstack/react-query";
+import { setWorkspaceSlugLookup } from "./paths/workspace-slugs";
+import { workspaceKeys } from "./workspace/queries";
+import type { Workspace } from "./types";
export function createQueryClient(): QueryClient {
return new QueryClient({
@@ -16,3 +19,18 @@ export function createQueryClient(): QueryClient {
},
});
}
+
+/**
+ * Point path resolution at `client`'s workspace list. Reading the cache on
+ * every lookup covers fetches, hydration, mutations and logout/clear. Owned by
+ * the mounted provider rather than the constructor: StrictMode builds and
+ * discards an extra client, which must never become the bound one.
+ */
+export function bindWorkspaceSlugLookup(client: QueryClient): () => void {
+ return setWorkspaceSlugLookup(
+ (slug) =>
+ client
+ .getQueryData<Workspace[]>(workspaceKeys.list())
+ ?.some((workspace) => workspace.slug === slug) ?? false,
+ );
+}
diff --git a/packages/core/workspace/navigation-cache.test.tsx b/packages/core/workspace/navigation-cache.test.tsx
new file mode 100644
index 0000000000..0788284b2b
--- /dev/null
+++ b/packages/core/workspace/navigation-cache.test.tsx
@@ -0,0 +1,72 @@
+// @vitest-environment jsdom
+import { StrictMode, useEffect } from "react";
+import { render, cleanup } from "@testing-library/react";
+import { dehydrate, hydrate, QueryClient, useQueryClient } from "@tanstack/react-query";
+import { afterEach, describe, expect, it } from "vitest";
+import { QueryProvider } from "../provider";
+import { bindWorkspaceSlugLookup, createQueryClient } from "../query-client";
+import { workspaceSlugForPath } from "../paths/workspace-slugs";
+import { workspaceKeys } from "./queries";
+
+let unbind: () => void = () => {};
+
+afterEach(() => {
+ cleanup();
+ unbind();
+});
+
+describe("workspace slug lookup binding", () => {
+ it("reads hydration and cache changes, and forgets membership on account cleanup", () => {
+ const source = new QueryClient();
+ source.setQueryData(workspaceKeys.list(), [{ slug: "dingtalk" }]);
+ const client = createQueryClient();
+ unbind = bindWorkspaceSlugLookup(client);
+ expect(workspaceSlugForPath("/dingtalk/issues")).toBeNull();
+ hydrate(client, dehydrate(source));
+ expect(workspaceSlugForPath("/dingtalk/issues")).toBe("dingtalk");
+ client.setQueryData(workspaceKeys.list(), [{ slug: "issues" }]);
+ expect(workspaceSlugForPath("/dingtalk/issues")).toBeNull();
+ expect(workspaceSlugForPath("/issues/issues")).toBe("issues");
+ client.clear();
+ expect(workspaceSlugForPath("/issues/issues")).toBeNull();
+ source.clear();
+ });
+
+ it("does not bind a client just by constructing it", () => {
+ const client = createQueryClient();
+ client.setQueryData(workspaceKeys.list(), [{ slug: "dingtalk" }]);
+ expect(workspaceSlugForPath("/dingtalk/issues")).toBeNull();
+ });
+
+ it("a stale unbind does not clear a newer binding", () => {
+ const first = createQueryClient();
+ const second = createQueryClient();
+ second.setQueryData(workspaceKeys.list(), [{ slug: "dingtalk" }]);
+ const unbindFirst = bindWorkspaceSlugLookup(first);
+ unbind = bindWorkspaceSlugLookup(second);
+ unbindFirst();
+ expect(workspaceSlugForPath("/dingtalk/issues")).toBe("dingtalk");
+ });
+
+ it.each([false, true])("binds the mounted provider's client (StrictMode=%s)", (strict) => {
+ let mounted: QueryClient | undefined;
+ function Probe() {
+ const client = useQueryClient();
+ useEffect(() => {
+ mounted = client;
+ client.setQueryData(workspaceKeys.list(), [{ slug: "dingtalk" }]);
+ }, [client]);
+ return null;
+ }
+ const tree = (
+ <QueryProvider>
+ <Probe />
+ </QueryProvider>
+ );
+ const { unmount } = render(strict ? <StrictMode>{tree}</StrictMode> : tree);
+ expect(workspaceSlugForPath("/dingtalk/issues")).toBe("dingtalk");
+ unmount();
+ expect(workspaceSlugForPath("/dingtalk/issues")).toBeNull();
+ mounted?.clear();
+ });
+});
diff --git a/packages/views/editor/utils/link-handler.test.ts b/packages/views/editor/utils/link-handler.test.ts
index 09b60e2c14..02bbb92990 100644
--- a/packages/views/editor/utils/link-handler.test.ts
+++ b/packages/views/editor/utils/link-handler.test.ts
@@ -1,3 +1,8 @@
+import {
+ bindWorkspaceSlugLookup,
+ createQueryClient,
+} from "@multica/core/query-client";
+import { workspaceKeys } from "@multica/core/workspace/queries";
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import {
openLink,
@@ -14,6 +19,16 @@ function navigatedPaths(): string[] {
let dispatched: Event[] = [];
let openSpy: ReturnType<typeof vi.spyOn>;
+let unbindWorkspaces: () => void = () => {};
+
+/** Give the current account membership of `slugs`, as the mounted provider would. */
+function withWorkspaces(slugs: string[]) {
+ const client = createQueryClient();
+ unbindWorkspaces = bindWorkspaceSlugLookup(client);
+ client.setQueryData(workspaceKeys.list(), slugs.map((slug) => ({ slug })));
+ return client;
+}
+
beforeEach(() => {
dispatched = [];
vi.spyOn(window, "dispatchEvent").mockImplementation((e: Event) => {
@@ -24,6 +39,7 @@ beforeEach(() => {
});
afterEach(() => {
+ unbindWorkspaces();
vi.restoreAllMocks();
});
@@ -261,3 +277,37 @@ describe("parseWorkspaceEntityLink", () => {
expect(parseWorkspaceEntityLink("/acme/projects/%E0%A4%A")).toBeNull();
});
});
+
+
+describe("existing reserved-slug workspaces", () => {
+ it("keeps known reserved workspace links internal, including route-name slugs", () => {
+ const client = withWorkspaces(["dingtalk", "issues"]);
+ expect(toInternalAppPath(`${APP_ORIGIN}/dingtalk/issues/MUL-123`, APP_ORIGIN)).toBe(
+ "/dingtalk/issues/MUL-123",
+ );
+ expect(
+ parseWorkspaceEntityLink(`${APP_ORIGIN}/dingtalk/issues/MUL-123`, APP_ORIGIN),
+ ).toEqual({ kind: "issue", id: "MUL-123", slug: "dingtalk" });
+ openLink(`${APP_ORIGIN}/dingtalk/issues/MUL-123`, "acme", APP_ORIGIN);
+ openLink("/issues/issues/MUL-123", "acme", APP_ORIGIN);
+ expect(navigatedPaths()).toEqual(["/dingtalk/issues/MUL-123", "/issues/issues/MUL-123"]);
+ expect(openSpy).not.toHaveBeenCalled();
+ expect(toInternalAppPath(`${APP_ORIGIN}/dingtalk/bind`, APP_ORIGIN)).toBeNull();
+ client.clear();
+ expect(toInternalAppPath(`${APP_ORIGIN}/dingtalk/issues/MUL-123`, APP_ORIGIN)).toBeNull();
+ });
+
+ it("still scopes legacy unscoped links whose route is not a reserved slug", () => {
+ withWorkspaces(["acme"]);
+ openLink("/chat", "acme", APP_ORIGIN);
+ openLink("/inbox", "acme", APP_ORIGIN);
+ expect(navigatedPaths()).toEqual(["/acme/chat", "/acme/inbox"]);
+ });
+
+ it("leaves a member workspace named after a route alone", () => {
+ withWorkspaces(["chat"]);
+ openLink("/chat/issues", "acme", APP_ORIGIN);
+ openLink("/chat", "acme", APP_ORIGIN);
+ expect(navigatedPaths()).toEqual(["/chat/issues", "/acme/chat"]);
+ });
+});
diff --git a/packages/views/editor/utils/link-handler.ts b/packages/views/editor/utils/link-handler.ts
index 5890c68fee..a381ea702e 100644
--- a/packages/views/editor/utils/link-handler.ts
+++ b/packages/views/editor/utils/link-handler.ts
@@ -5,7 +5,11 @@
* (react-markdown link component), and link-hover-card (Open button).
*/
-import { isGlobalPath, isReservedSlug } from "@multica/core/paths";
+import {
+ isGlobalPath,
+ isKnownWorkspacePath,
+ workspaceSlugForPath,
+} from "@multica/core/paths";
import { isIssueIdentifier } from "@multica/ui/markdown";
import type { LinkClickIntent } from "../../navigation/click-intent";
@@ -34,29 +38,6 @@ const WORKSPACE_ROUTE_SEGMENTS = new Set([
"settings",
]);
-/**
- * Report whether a path is a workspace-scoped app page — `/{slug}/...` where the
- * first segment is a slug a workspace could actually own.
- *
- * The app origin also serves things the app router does not own: `/api/*`,
- * `/uploads/*` (local-storage attachments, proxied by web), `/_next/*`,
- * `/favicon.ico`, and the pre-workspace routes. Every one of those first
- * segments is already a reserved slug, so the reserved list — the same one the
- * backend enforces at workspace creation — answers this question without a
- * parallel deny-list that has to be kept in sync with the backend's routes.
- */
-function isWorkspaceScopedPath(pathname: string): boolean {
- const first = pathname.split("/")[1] ?? "";
- if (!first) return false;
- let segment: string;
- try {
- segment = decodeURIComponent(first);
- } catch {
- return false;
- }
- return !isReservedSlug(segment.toLowerCase());
-}
-
/**
* Convert an absolute URL that points at a workspace page on this deployment's
* own app into the in-app path it addresses; `null` for anything else.
@@ -87,7 +68,7 @@ export function toInternalAppPath(
// Opaque origins (file:, data:) compare equal to each other; only real web
// origins identify the app.
if (target.protocol !== "http:" && target.protocol !== "https:") return null;
- if (!isWorkspaceScopedPath(target.pathname)) return null;
+ if (!workspaceSlugForPath(target.pathname)) return null;
return `${target.pathname}${target.search}${target.hash}`;
}
@@ -220,7 +201,7 @@ export function parseWorkspaceEntityLink(
let id: string | undefined;
if (segments.length === 3) {
const [first, second, third] = segments;
- if (!first || isReservedSlug(first.toLowerCase())) return null;
+ if (!first || !workspaceSlugForPath(path)) return null;
slug = first;
route = second;
id = third;
@@ -265,8 +246,14 @@ export function openLink(
let path = internalPath;
if (currentSlug && !isGlobalPath(path)) {
const firstSegment = path.split("/")[1];
- if (firstSegment && WORKSPACE_ROUTE_SEGMENTS.has(firstSegment)) {
- // Path looks like /issues/abc (no slug) — prepend current slug.
+ if (
+ firstSegment &&
+ WORKSPACE_ROUTE_SEGMENTS.has(firstSegment) &&
+ !isKnownWorkspacePath(path)
+ ) {
+ // Path looks like /issues/abc (no slug) — prepend current slug. A
+ // member workspace whose slug happens to be a route name
+ // (/issues/issues/MUL-1) is already scoped and is left as is.
path = `/${currentSlug}${path}`;
}
// Otherwise the first segment is either already a slug (e.g. "acme" in