Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(desktop): open in-app links in a tab instead of the browser (MUL-5208) (#5826)
Bohan Jiang1fef98c24fed
diff --git a/apps/desktop/src/renderer/src/components/desktop-layout.tsx b/apps/desktop/src/renderer/src/components/desktop-layout.tsxindex 6d2258bc63..f58cd8cf5e 100644--- a/apps/desktop/src/renderer/src/components/desktop-layout.tsx+++ b/apps/desktop/src/renderer/src/components/desktop-layout.tsx@@ -3,7 +3,6 @@ import { ChevronLeft, ChevronRight } from "lucide-react";import { motion } from "motion/react";import { cn } from "@multica/ui/lib/utils";import { useTabHistory } from "@/hooks/use-tab-history";-import { useTabStore } from "@/stores/tab-store";import {SidebarProvider,SidebarTrigger,@@ -17,7 +16,10 @@ import { WorkspaceSlugProvider, paths, useCurrentWorkspace } from "@multica/coreimport { useNavigation } from "@multica/views/navigation";import { getCurrentSlug, subscribeToCurrentSlug } from "@multica/core/platform";import { useDesktopUnreadBadge } from "@multica/views/platform";-import { DesktopNavigationProvider } from "@/platform/navigation";+import {+ DesktopNavigationProvider,+ routeContentLinkPath,+} from "@/platform/navigation";import { TabBar } from "./tab-bar";import { TabContent } from "./tab-content";import { WindowOverlay } from "./window-overlay";@@ -152,11 +154,7 @@ function useInternalLinkHandler() {const handler = (e: Event) => {const path = (e as CustomEvent).detail?.path;if (!path) return;- const store = useTabStore.getState();- // Empty seed title — the tab bar derives the real title from the URL and- // cache; a raw path would flash before that resolves.- const tabId = store.openTab(path, "");- store.setActiveTab(tabId);+ routeContentLinkPath(path);};window.addEventListener("multica:navigate", handler);return () => window.removeEventListener("multica:navigate", handler);diff --git a/apps/desktop/src/renderer/src/platform/issue-window-navigation.test.tsx b/apps/desktop/src/renderer/src/platform/issue-window-navigation.test.tsxnew file mode 100644index 0000000000..bad596de3e--- /dev/null+++ b/apps/desktop/src/renderer/src/platform/issue-window-navigation.test.tsx@@ -0,0 +1,98 @@+/**+ * MUL-5208 — a dedicated issue window must answer content-link navigation.+ *+ * `multica:navigate` is fired by the shared link handler for every in-app+ * destination, including an absolute URL on this deployment's own origin. Only+ * the main shell listened for it, so a link clicked inside an issue window did+ * nothing at all. This window hosts exactly one issue route: another issue opens+ * in place, anything else goes to the browser — never a silent no-op.+ */+import { describe, expect, it, vi, beforeEach } from "vitest";+import { act, render, screen } from "@testing-library/react";+import { MemoryRouter, Route, Routes, useLocation } from "react-router-dom";++const APP_URL = "https://app.example";++vi.mock("@multica/core/paths", () => ({+ useCurrentWorkspace: () => ({ slug: "acme", id: "ws-1" }),+}));++import { IssueWindowNavigationProvider } from "./issue-window-navigation";++const openExternal = vi.fn().mockResolvedValue(undefined);+const setRendererRouteContext = vi.fn();++beforeEach(() => {+ openExternal.mockClear();+ setRendererRouteContext.mockClear();+ Object.defineProperty(window, "desktopAPI", {+ configurable: true,+ value: {+ runtimeConfig: { ok: true, config: { appUrl: APP_URL } },+ openExternal,+ setRendererRouteContext,+ openIssueWindow: vi.fn(),+ },+ });+});++function CurrentPath() {+ const location = useLocation();+ return <span data-testid="path">{location.pathname}</span>;+}++function renderWindow() {+ return render(+ <MemoryRouter initialEntries={["/acme/issues/MUL-1"]}>+ <Routes>+ <Route+ path=":workspaceSlug/issues/:id"+ element={+ <IssueWindowNavigationProvider>+ <CurrentPath />+ </IssueWindowNavigationProvider>+ }+ />+ </Routes>+ </MemoryRouter>,+ );+}++function navigate(path: string) {+ // The listener runs outside React's event system; act() flushes the router+ // state update it triggers.+ act(() => {+ window.dispatchEvent(+ new CustomEvent("multica:navigate", { detail: { path } }),+ );+ });+}++describe("IssueWindowNavigationProvider content links", () => {+ it("opens another issue in place", () => {+ renderWindow();++ navigate("/acme/issues/MUL-2");++ expect(screen.getByTestId("path")).toHaveTextContent("/acme/issues/MUL-2");+ expect(openExternal).not.toHaveBeenCalled();+ });++ it("hands a page this window cannot host to the browser instead of swallowing it", () => {+ renderWindow();++ navigate("/acme/chat");++ expect(screen.getByTestId("path")).toHaveTextContent("/acme/issues/MUL-1");+ expect(openExternal).toHaveBeenCalledWith(`${APP_URL}/acme/chat`);+ });++ it("stops listening once unmounted", () => {+ const { unmount } = renderWindow();++ unmount();+ navigate("/acme/chat");++ expect(openExternal).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/renderer/src/platform/issue-window-navigation.tsx b/apps/desktop/src/renderer/src/platform/issue-window-navigation.tsxindex 95fd7ff799..57a3f51775 100644--- a/apps/desktop/src/renderer/src/platform/issue-window-navigation.tsx+++ b/apps/desktop/src/renderer/src/platform/issue-window-navigation.tsx@@ -7,6 +7,42 @@ import {} from "@multica/views/navigation";import { parseIssueWindowPath } from "../../../shared/issue-window";+/**+ * Answer the `multica:navigate` event inside a dedicated issue window (MUL-5208).+ *+ * The event is what a link in content (comment, description) fires once it+ * resolves to an in-app destination, including an absolute URL on this+ * deployment's own origin. Only the main shell listened for it, so in this+ * window such a click did nothing at all.+ *+ * Another issue opens in place — the same thing a mention chip does here, since+ * the window's adapter push is `navigateToIssue`. Any other app page cannot be+ * hosted by this single-route window, so it goes to the browser rather than+ * being swallowed.+ */+function useContentLinkHandler(+ navigate: ReturnType<typeof useNavigate>,+ runtimeConfig: typeof window.desktopAPI.runtimeConfig,+) {+ useEffect(() => {+ const handler = (e: Event) => {+ const path = (e as CustomEvent<{ path?: string }>).detail?.path;+ if (!path) return;+ const issuePath = parseIssueWindowPath(path);+ if (issuePath) {+ void navigate(issuePath.path);+ return;+ }+ if (!runtimeConfig.ok) return;+ void window.desktopAPI.openExternal(+ `${runtimeConfig.config.appUrl}${path}`,+ );+ };+ window.addEventListener("multica:navigate", handler);+ return () => window.removeEventListener("multica:navigate", handler);+ }, [navigate, runtimeConfig]);+}+/*** Navigation bridge for a dedicated issue window. Unlike the main Desktop* shell, this window owns a tiny MemoryRouter and intentionally accepts only@@ -32,6 +68,8 @@ export function IssueWindowNavigationProvider({});}, [currentPath, workspace?.slug]);+ useContentLinkHandler(navigate, runtimeConfig);+const adapter = useMemo<NavigationAdapter>(() => {const navigateToIssue = (path: string, replace = false) => {const issuePath = parseIssueWindowPath(path);diff --git a/apps/desktop/src/renderer/src/platform/navigation.test.tsx b/apps/desktop/src/renderer/src/platform/navigation.test.tsxindex 857ff9e44c..e8e7bc7d56 100644--- a/apps/desktop/src/renderer/src/platform/navigation.test.tsx+++ b/apps/desktop/src/renderer/src/platform/navigation.test.tsx@@ -27,7 +27,7 @@ vi.mock("@multica/core/auth", () => ({}),}));-import { DesktopNavigationProvider } from "./navigation";+import { DesktopNavigationProvider, routeContentLinkPath } from "./navigation";import { useNavigation } from "@multica/views/navigation";import { useTabStore, getActiveTab } from "@/stores/tab-store";@@ -218,3 +218,24 @@ describe("back", () => {expect(active.history.index).toBe(0);});});++describe("routeContentLinkPath (links inside content — MUL-5208)", () => {+ it("opens a same-workspace path in a foreground tab of its own", () => {+ routeContentLinkPath("/acme/issues/MUL-1");++ const group = useTabStore.getState().byWorkspace.acme;+ const opened = group.tabs.find((t) => t.url === "/acme/issues/MUL-1")!;+ expect(opened).toBeDefined();+ expect(group.activeTabId).toBe(opened.id);+ });++ it("switches workspace instead of opening the path under the active group", () => {+ routeContentLinkPath("/butter/issues/BUT-1");++ const state = useTabStore.getState();+ expect(state.activeWorkspaceSlug).toBe("butter");+ expect(+ state.byWorkspace.acme.tabs.some((t) => t.url === "/butter/issues/BUT-1"),+ ).toBe(false);+ });+});diff --git a/apps/desktop/src/renderer/src/platform/navigation.tsx b/apps/desktop/src/renderer/src/platform/navigation.tsxindex b88d617f63..9a72e6f5c7 100644--- a/apps/desktop/src/renderer/src/platform/navigation.tsx+++ b/apps/desktop/src/renderer/src/platform/navigation.tsx@@ -95,6 +95,30 @@ function tryRouteToOtherWorkspace(path: string): boolean {return true;}+/**+ * Open a path that a link inside content resolved to (the `multica:navigate`+ * event fired by the shared editor/markdown link handler) in a foreground tab.+ *+ * A content link is a jump to another subject, so it gets its own tab rather+ * than replacing what the user was reading. It can also address another+ * workspace — a pasted app URL, an agent quoting a cross-workspace issue — and+ * opening that inside the active workspace's tab group would mount it under the+ * wrong group, so the slug check routes it through switchWorkspace exactly like+ * an adapter push does.+ */+export function routeContentLinkPath(path: string): void {+ const store = useTabStore.getState();+ const slug = extractWorkspaceSlug(path);+ if (slug && slug !== store.activeWorkspaceSlug) {+ store.switchWorkspace(slug, path);+ return;+ }+ // Empty seed title — the tab bar derives the real title from the URL and+ // cache; a raw path would flash before that resolves.+ const tabId = store.openTab(path, "");+ store.setActiveTab(tabId);+}+/*** Intercept pushes originating in a pinned tab and force them into a new* tab. Returns `true` if the navigation was redirected (caller should NOTdiff --git a/apps/web/platform/navigation.test.tsx b/apps/web/platform/navigation.test.tsxnew file mode 100644index 0000000000..1d7b4a1f6a--- /dev/null+++ b/apps/web/platform/navigation.test.tsx@@ -0,0 +1,64 @@+/**+ * MUL-5208 — the web half of the `multica:navigate` bridge.+ *+ * Shared content (comments, chat, issue descriptions) fires this event whenever+ * a link resolves to an in-app destination, including an absolute URL on this+ * deployment's own origin. Desktop answers it by opening a tab; the web must+ * answer it with a router push, or those links silently do nothing.+ */+import { describe, expect, it, vi, beforeEach } from "vitest";+import { render } from "@testing-library/react";++const router = vi.hoisted(() => ({+ push: vi.fn(),+ replace: vi.fn(),+ back: vi.fn(),+ prefetch: vi.fn(),+}));++vi.mock("next/navigation", () => ({+ useRouter: () => router,+ usePathname: () => "/acme/issues",+ useSearchParams: () => new URLSearchParams(),+}));++import { WebNavigationProvider } from "./navigation";++function navigate(path: string) {+ window.dispatchEvent(+ new CustomEvent("multica:navigate", { detail: { path } }),+ );+}++beforeEach(() => {+ router.push.mockReset();+});++describe("WebNavigationProvider internal link bridge", () => {+ it("pushes the path a content link resolved to", () => {+ render(<WebNavigationProvider>{null}</WebNavigationProvider>);++ navigate("/acme/issues/MUL-1");++ expect(router.push).toHaveBeenCalledWith("/acme/issues/MUL-1");+ });++ it("ignores an event without a path", () => {+ render(<WebNavigationProvider>{null}</WebNavigationProvider>);++ window.dispatchEvent(new CustomEvent("multica:navigate", { detail: {} }));++ expect(router.push).not.toHaveBeenCalled();+ });++ it("stops listening once unmounted", () => {+ const { unmount } = render(+ <WebNavigationProvider>{null}</WebNavigationProvider>,+ );++ unmount();+ navigate("/acme/issues/MUL-1");++ expect(router.push).not.toHaveBeenCalled();+ });+});diff --git a/apps/web/platform/navigation.tsx b/apps/web/platform/navigation.tsxindex 804a9ab66c..f840a8cd98 100644--- a/apps/web/platform/navigation.tsx+++ b/apps/web/platform/navigation.tsx@@ -1,12 +1,31 @@"use client";-import { Suspense } from "react";+import { Suspense, useEffect } from "react";import { useRouter, usePathname, useSearchParams } from "next/navigation";import {NavigationProvider,type NavigationAdapter,} from "@multica/views/navigation";+/**+ * Web half of the `multica:navigate` bridge — the event shared content+ * (comments, chat, issue descriptions) fires when a link resolves to an in-app+ * destination. Desktop's shell answers it by opening a tab; on the web the+ * equivalent is a router push in place. Without this the event has no listener+ * and such links do nothing at all.+ */+function useInternalLinkHandler(router: ReturnType<typeof useRouter>) {+ useEffect(() => {+ const handler = (e: Event) => {+ const path = (e as CustomEvent<{ path?: string }>).detail?.path;+ if (!path) return;+ router.push(path);+ };+ window.addEventListener("multica:navigate", handler);+ return () => window.removeEventListener("multica:navigate", handler);+ }, [router]);+}+function NavigationProviderInner({children,}: {@@ -15,6 +34,7 @@ function NavigationProviderInner({const router = useRouter();const pathname = usePathname();const searchParams = useSearchParams();+ useInternalLinkHandler(router);const adapter: NavigationAdapter = {push: router.push,diff --git a/packages/views/common/rich-content-sanitize-contract.test.tsx b/packages/views/common/rich-content-sanitize-contract.test.tsxindex 12a4de5610..5a715697b8 100644--- a/packages/views/common/rich-content-sanitize-contract.test.tsx+++ b/packages/views/common/rich-content-sanitize-contract.test.tsx@@ -54,6 +54,7 @@ vi.mock("@multica/core/paths", () => ({vi.mock("../navigation", () => ({useNavigation: () => ({ push: vi.fn(), openInNewTab: vi.fn() }),+ useAppOrigin: () => null,AppLink: ({ href, children }: { href: string; children: React.ReactNode }) => (<a href={href}>{children}</a>),diff --git a/packages/views/editor/content-editor.tsx b/packages/views/editor/content-editor.tsxindex 327615a670..97568a9737 100644--- a/packages/views/editor/content-editor.tsx+++ b/packages/views/editor/content-editor.tsx@@ -61,6 +61,7 @@ import { uploadAndInsertFile } from "./extensions/file-upload";import { configStore } from "@multica/core/config";import { preprocessMarkdown } from "./utils/preprocess";import { repairEmptyListItems } from "./utils/repair-list-items";+import { useAppOrigin } from "../navigation";import { openLink, isMentionHref } from "./utils/link-handler";import { EditorBubbleMenu } from "./bubble-menu";import { posFromAnchor, type TextAnchor } from "./text-anchor";@@ -397,6 +398,13 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(const workspaceSlugRef = useRef(workspaceSlug);workspaceSlugRef.current = workspaceSlug;+ // Same reasoning for this deployment's app origin: it tells openLink which+ // absolute URLs address this app and must route in-app instead of opening+ // the system browser.+ const appOrigin = useAppOrigin();+ const appOriginRef = useRef(appOrigin);+ appOriginRef.current = appOrigin;+// Keep refs in sync without recreating editoronUpdateRef.current = onUpdate;onSubmitRef.current = onSubmit;@@ -538,7 +546,7 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(if (!href || isMentionHref(href)) return false;event.preventDefault();- openLink(href, workspaceSlugRef.current);+ openLink(href, workspaceSlugRef.current, appOriginRef.current);return true;},},diff --git a/packages/views/editor/link-hover-card.tsx b/packages/views/editor/link-hover-card.tsxindex 941afe31c1..007bb21428 100644--- a/packages/views/editor/link-hover-card.tsx+++ b/packages/views/editor/link-hover-card.tsx@@ -17,6 +17,7 @@ import { toast } from "sonner";import { Button } from "@multica/ui/components/ui/button";import { copyText } from "@multica/ui/lib/clipboard";import { useWorkspaceSlug } from "@multica/core/paths";+import { useAppOrigin } from "../navigation";import { useT } from "../i18n";import { openLink, isMentionHref } from "./utils/link-handler";@@ -137,6 +138,7 @@ function LinkHoverCard({const [pos, setPos] = useState({ top: 0, left: 0 });const [positioned, setPositioned] = useState(false);const slug = useWorkspaceSlug();+ const appOrigin = useAppOrigin();const { t } = useT("editor");// Position the card when the portal div is mounted (ref callback).@@ -181,7 +183,7 @@ function LinkHoverCard({const handleOpen = (e: React.MouseEvent) => {e.stopPropagation();e.preventDefault();- openLink(href, slug);+ openLink(href, slug, appOrigin);};return createPortal(diff --git a/packages/views/editor/readonly-content.test.tsx b/packages/views/editor/readonly-content.test.tsxindex 13fb8bed9b..cf7266065f 100644--- a/packages/views/editor/readonly-content.test.tsx+++ b/packages/views/editor/readonly-content.test.tsx@@ -42,6 +42,7 @@ vi.mock("@multica/core/paths", () => ({vi.mock("../navigation", () => ({useNavigation: () => ({ push: vi.fn(), openInNewTab: vi.fn() }),+ useAppOrigin: () => null,}));vi.mock("../issues/components/issue-mention-card", () => ({diff --git a/packages/views/editor/utils/link-handler.test.ts b/packages/views/editor/utils/link-handler.test.tsnew file mode 100644index 0000000000..c559f9f587--- /dev/null+++ b/packages/views/editor/utils/link-handler.test.ts@@ -0,0 +1,109 @@+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";+import { openLink, toInternalAppPath } from "./link-handler";++const APP_ORIGIN = "https://app.multica.ai";++function navigatedPaths(): string[] {+ return dispatched.map((e) => (e as CustomEvent<{ path: string }>).detail.path);+}++let dispatched: Event[] = [];+let openSpy: ReturnType<typeof vi.spyOn>;++beforeEach(() => {+ dispatched = [];+ vi.spyOn(window, "dispatchEvent").mockImplementation((e: Event) => {+ dispatched.push(e);+ return true;+ });+ openSpy = vi.spyOn(window, "open").mockImplementation(() => null);+});++afterEach(() => {+ vi.restoreAllMocks();+});++describe("toInternalAppPath", () => {+ it("returns the path (with search and hash) for a URL on the app origin", () => {+ expect(+ toInternalAppPath(`${APP_ORIGIN}/acme/issues/MUL-1?tab=a#c`, APP_ORIGIN),+ ).toBe("/acme/issues/MUL-1?tab=a#c");+ });++ it("returns null for another origin", () => {+ expect(toInternalAppPath("https://github.com/a/b/pull/1", APP_ORIGIN)).toBeNull();+ });++ it("returns null when the platform exposes no app origin", () => {+ expect(toInternalAppPath(`${APP_ORIGIN}/acme/issues/1`, null)).toBeNull();+ });++ it("keeps backend-served paths external so downloads and assets still work", () => {+ // Every one of these first segments is a reserved slug, which is exactly+ // why the reserved list — not a hand-kept deny-list — decides this.+ expect(+ toInternalAppPath(`${APP_ORIGIN}/api/attachments/abc/download`, APP_ORIGIN),+ ).toBeNull();+ expect(+ toInternalAppPath(`${APP_ORIGIN}/uploads/2026/07/report.pdf`, APP_ORIGIN),+ ).toBeNull();+ expect(toInternalAppPath(`${APP_ORIGIN}/uploads`, APP_ORIGIN)).toBeNull();+ expect(toInternalAppPath(`${APP_ORIGIN}/_next/static/x.js`, APP_ORIGIN)).toBeNull();+ expect(toInternalAppPath(`${APP_ORIGIN}/favicon.ico`, APP_ORIGIN)).toBeNull();+ });++ it("keeps pre-workspace and root paths external — they are not workspace pages", () => {+ expect(toInternalAppPath(`${APP_ORIGIN}/login`, APP_ORIGIN)).toBeNull();+ expect(toInternalAppPath(`${APP_ORIGIN}/auth/callback`, APP_ORIGIN)).toBeNull();+ expect(toInternalAppPath(`${APP_ORIGIN}/`, APP_ORIGIN)).toBeNull();+ });++ it("ignores case and percent-encoding when matching a reserved first segment", () => {+ expect(toInternalAppPath(`${APP_ORIGIN}/UPLOADS/x.pdf`, APP_ORIGIN)).toBeNull();+ expect(toInternalAppPath(`${APP_ORIGIN}/%75ploads/x.pdf`, APP_ORIGIN)).toBeNull();+ });++ it("returns null for non-http schemes and unparseable hrefs", () => {+ expect(toInternalAppPath("mailto:[email protected]", APP_ORIGIN)).toBeNull();+ expect(toInternalAppPath("not a url", APP_ORIGIN)).toBeNull();+ });+});++describe("openLink", () => {+ it("navigates in-app for a URL pointing back at this deployment (MUL-5208)", () => {+ openLink(`${APP_ORIGIN}/acme/issues/MUL-1`, "acme", APP_ORIGIN);+ expect(navigatedPaths()).toEqual(["/acme/issues/MUL-1"]);+ expect(openSpy).not.toHaveBeenCalled();+ });++ it("navigates in-app for a cross-workspace app URL without rewriting the slug", () => {+ openLink(`${APP_ORIGIN}/other/issues/MUL-1`, "acme", APP_ORIGIN);+ expect(navigatedPaths()).toEqual(["/other/issues/MUL-1"]);+ });++ it("opens an external URL in a new window", () => {+ openLink("https://github.com/multica-ai/multica/pull/1", "acme", APP_ORIGIN);+ expect(dispatched).toHaveLength(0);+ expect(openSpy).toHaveBeenCalledWith(+ "https://github.com/multica-ai/multica/pull/1",+ "_blank",+ "noopener,noreferrer",+ );+ });++ it("still opens an app URL externally when no app origin is known", () => {+ openLink(`${APP_ORIGIN}/acme/issues/MUL-1`, "acme");+ expect(dispatched).toHaveLength(0);+ expect(openSpy).toHaveBeenCalled();+ });++ it("prefixes the current slug on a slugless workspace path", () => {+ openLink("/issues/MUL-1", "acme", APP_ORIGIN);+ expect(navigatedPaths()).toEqual(["/acme/issues/MUL-1"]);+ });++ it("leaves a path that already carries a slug alone", () => {+ openLink("/other/issues/MUL-1", "acme", APP_ORIGIN);+ expect(navigatedPaths()).toEqual(["/other/issues/MUL-1"]);+ });+});diff --git a/packages/views/editor/utils/link-handler.ts b/packages/views/editor/utils/link-handler.tsindex 743ab284dc..0fb42a1a4d 100644--- a/packages/views/editor/utils/link-handler.ts+++ b/packages/views/editor/utils/link-handler.ts@@ -5,7 +5,7 @@* (react-markdown link component), and link-hover-card (Open button).*/-import { isGlobalPath } from "@multica/core/paths";+import { isGlobalPath, isReservedSlug } from "@multica/core/paths";/*** Top-level workspace-scoped routes. Used to detect "/{route}/..." paths that@@ -32,6 +32,63 @@ 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.+ *+ * An agent or a user pasting `https://<app-host>/acme/issues/123` means the same+ * destination as `/acme/issues/123`. Without this, the URL reads as external and+ * the desktop app hands it to the system browser instead of opening a tab+ * (MUL-5208).+ *+ * `appOrigin` is the deployment's public app URL, which only the platform layer+ * knows (web: the current origin; desktop: the connected environment's app URL).+ * See `useAppOrigin()`.+ */+export function toInternalAppPath(+ href: string,+ appOrigin?: string | null,+): string | null {+ if (!appOrigin) return null;+ let target: URL;+ let app: URL;+ try {+ target = new URL(href);+ app = new URL(appOrigin);+ } catch {+ return null;+ }+ if (target.origin !== app.origin) return null;+ // 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;+ return `${target.pathname}${target.search}${target.hash}`;+}+/*** Open a link — internal paths dispatch multica:navigate, external open new tab.*@@ -39,10 +96,20 @@ const WORKSPACE_ROUTE_SEGMENTS = new Set([* slug (e.g. "/issues/abc" instead of "/{slug}/issues/abc"), the slug is* prepended. This is for legacy markdown content authored before the URL* refactor, or future content where users forget the slug when pasting.+ *+ * `appOrigin` lets absolute URLs pointing back at this deployment take the same+ * internal route as a relative path.*/-export function openLink(href: string, currentSlug?: string | null): void {- if (href.startsWith("/")) {- let path = href;+export function openLink(+ href: string,+ currentSlug?: string | null,+ appOrigin?: string | null,+): void {+ const internalPath = href.startsWith("/")+ ? href+ : toInternalAppPath(href, appOrigin);+ if (internalPath) {+ let path = internalPath;if (currentSlug && !isGlobalPath(path)) {const firstSegment = path.split("/")[1];if (firstSegment && WORKSPACE_ROUTE_SEGMENTS.has(firstSegment)) {diff --git a/packages/views/navigation/context.tsx b/packages/views/navigation/context.tsxindex fb5779ba9c..c74165a03e 100644--- a/packages/views/navigation/context.tsx+++ b/packages/views/navigation/context.tsx@@ -36,6 +36,16 @@ export function NavigationProvider({);}+/**+ * Non-throwing read of the adapter. For components that legitimately render+ * outside a provider — leaf editor UI mounted in isolation, and the tests that+ * exercise it — where the navigation-dependent behaviour has a sane fallback.+ * Anything that must navigate should use `useNavigation()` and keep the throw.+ */+export function useOptionalNavigation(): NavigationAdapter | null {+ return use(NavigationContext);+}+export function useNavigation(): NavigationAdapter {const ctx = use(NavigationContext);if (!ctx)diff --git a/packages/views/navigation/index.ts b/packages/views/navigation/index.tsindex 52dc3d4a28..df579ebb97 100644--- a/packages/views/navigation/index.ts+++ b/packages/views/navigation/index.ts@@ -4,5 +4,6 @@ export {useIsNavigating,} from "./context";export { AppLink } from "./app-link";+export { useAppOrigin } from "./use-app-origin";export { useRowLink } from "./use-row-link";export type { NavigationAdapter } from "./types";diff --git a/packages/views/navigation/use-app-origin.ts b/packages/views/navigation/use-app-origin.tsnew file mode 100644index 0000000000..b2ed5c1260--- /dev/null+++ b/packages/views/navigation/use-app-origin.ts@@ -0,0 +1,32 @@+"use client";++import { useMemo } from "react";+import { useOptionalNavigation } from "./context";++/**+ * Origin of this deployment's public app URL, or `null` when the platform can't+ * name one (server render, desktop before runtime config lands, or a component+ * mounted outside a NavigationProvider).+ *+ * Derived from the adapter's `getShareableUrl` rather than a separate adapter+ * field: "the public URL of this app" is already implemented per platform there+ * (web: the current origin, desktop: the connected environment's app URL), and a+ * second copy of the same fact is a copy that can drift.+ *+ * Used to tell an in-app destination written as an absolute URL+ * (`https://<app-host>/acme/issues/1`) from a genuinely external link. `null`+ * degrades to the old behaviour — every absolute URL reads as external — which+ * is why a missing provider is tolerated instead of thrown on.+ */+export function useAppOrigin(): string | null {+ const navigation = useOptionalNavigation();+ const getShareableUrl = navigation?.getShareableUrl;+ return useMemo(() => {+ if (!getShareableUrl) return null;+ try {+ return new URL(getShareableUrl("/")).origin;+ } catch {+ return null;+ }+ }, [getShareableUrl]);+}diff --git a/packages/views/rich-content/app-url-link-routing.test.tsx b/packages/views/rich-content/app-url-link-routing.test.tsxnew file mode 100644index 0000000000..010137e920--- /dev/null+++ b/packages/views/rich-content/app-url-link-routing.test.tsx@@ -0,0 +1,133 @@+/**+ * MUL-5208 — a link that points back at this deployment is an in-app+ * destination, not an external one.+ *+ * Chat and comments render agent-written content full of absolute URLs. When one+ * of them addresses this app, `window.open` sends it to the system browser on+ * desktop (Electron routes every renderer-opened window through+ * `shell.openExternal`), which is how "click an issue link, get a browser+ * window" happens. The real `openLink` is exercised here — mocking it would test+ * nothing about the routing decision.+ */+import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";+import { render, screen } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";++const APP_ORIGIN = "https://app.example";++vi.mock("../issues/hooks", () => ({+ useResolveIssueIdentifier: () => null,+}));++// Only the workspace hooks are stubbed — the real path helpers stay in place so+// the reserved-slug rule that decides in-app vs external is the shipped one.+vi.mock("@multica/core/paths", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@multica/core/paths")>()),+ useWorkspacePaths: () => ({+ issueDetail: (id: string) => `/test/issues/${id}`,+ projectDetail: (id: string) => `/test/projects/${id}`,+ }),+ useWorkspaceSlug: () => "test",+}));++vi.mock("../navigation", () => ({+ useNavigation: () => ({ push: vi.fn(), openInNewTab: vi.fn() }),+ useAppOrigin: () => APP_ORIGIN,+ AppLink: ({ href, children }: { href: string; children: React.ReactNode }) => (+ <a href={href}>{children}</a>+ ),+}));++vi.mock("../editor/link-hover-card", () => ({+ useLinkHover: () => ({}),+ LinkHoverCard: () => null,+}));++vi.mock("mermaid", () => ({+ default: { initialize: vi.fn(), render: vi.fn() },+}));++import { RichContent } from "./rich-content";++let navigatedPaths: string[] = [];+let openSpy: ReturnType<typeof vi.spyOn>;++beforeEach(() => {+ navigatedPaths = [];+ window.addEventListener("multica:navigate", captureNavigate);+ openSpy = vi.spyOn(window, "open").mockImplementation(() => null);+});++afterEach(() => {+ window.removeEventListener("multica:navigate", captureNavigate);+ vi.restoreAllMocks();+});++function captureNavigate(e: Event) {+ const path = (e as CustomEvent<{ path?: string }>).detail?.path;+ if (path) navigatedPaths.push(path);+}++function renderContent(content: string) {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false, gcTime: 0 } },+ });+ return render(+ <QueryClientProvider client={client}>+ <RichContent content={content} />+ </QueryClientProvider>,+ );+}++describe("RichContent link routing", () => {+ it("routes a link to this deployment into the app instead of the browser", () => {+ renderContent(`[MUL-1](${APP_ORIGIN}/acme/issues/MUL-1)`);++ screen.getByText("MUL-1").click();++ expect(navigatedPaths).toEqual(["/acme/issues/MUL-1"]);+ expect(openSpy).not.toHaveBeenCalled();+ });++ it("still hands a genuinely external link to the browser", () => {+ const external = "https://github.com/multica-ai/multica/pull/1";+ renderContent(`[#1](${external})`);++ screen.getByText("#1").click();++ expect(navigatedPaths).toEqual([]);+ expect(openSpy).toHaveBeenCalledWith(+ external,+ "_blank",+ "noopener,noreferrer",+ );+ });++ it("keeps an attachment download URL on the app origin external", () => {+ const download = `${APP_ORIGIN}/api/attachments/abc/download`;+ renderContent(`[report.pdf](${download})`);++ screen.getByText("report.pdf").click();++ expect(navigatedPaths).toEqual([]);+ expect(openSpy).toHaveBeenCalledWith(+ download,+ "_blank",+ "noopener,noreferrer",+ );+ });++ it("keeps a same-origin /uploads file external — the backend serves it, not the router", () => {+ const upload = `${APP_ORIGIN}/uploads/2026/07/notes.pdf`;+ renderContent(`[notes.pdf](${upload})`);++ screen.getByText("notes.pdf").click();++ expect(navigatedPaths).toEqual([]);+ expect(openSpy).toHaveBeenCalledWith(+ upload,+ "_blank",+ "noopener,noreferrer",+ );+ });+});diff --git a/packages/views/rich-content/cdn-config-reactivity.test.tsx b/packages/views/rich-content/cdn-config-reactivity.test.tsxindex e3684a66a0..d4424c44bb 100644--- a/packages/views/rich-content/cdn-config-reactivity.test.tsx+++ b/packages/views/rich-content/cdn-config-reactivity.test.tsx@@ -44,6 +44,7 @@ vi.mock("@multica/core/paths", () => ({vi.mock("../navigation", () => ({useNavigation: () => ({ push: vi.fn(), openInNewTab: vi.fn() }),+ useAppOrigin: () => null,AppLink: ({ href, children }: { href: string; children: React.ReactNode }) => (<a href={href}>{children}</a>),diff --git a/packages/views/rich-content/rich-content-parity.test.tsx b/packages/views/rich-content/rich-content-parity.test.tsxindex deef87cfe5..d70a7c1c12 100644--- a/packages/views/rich-content/rich-content-parity.test.tsx+++ b/packages/views/rich-content/rich-content-parity.test.tsx@@ -54,6 +54,7 @@ vi.mock("@multica/core/paths", () => ({vi.mock("../navigation", () => ({useNavigation: () => ({ push: vi.fn(), openInNewTab: vi.fn() }),+ useAppOrigin: () => null,AppLink: ({ href, children }: { href: string; children: React.ReactNode }) => (<a href={href}>{children}</a>),diff --git a/packages/views/rich-content/rich-content.tsx b/packages/views/rich-content/rich-content.tsxindex f7c60af6e9..292c6bf55b 100644--- a/packages/views/rich-content/rich-content.tsx+++ b/packages/views/rich-content/rich-content.tsx@@ -48,7 +48,7 @@ import {markdownSanitizeSchema,markdownUrlTransform,} from "@multica/ui/markdown";-import { AppLink } from "../navigation";+import { AppLink, useAppOrigin } from "../navigation";import { IssueMentionCard } from "../issues/components/issue-mention-card";import { useResolveIssueIdentifier } from "../issues/hooks";import { ProjectChip } from "../projects/components/project-chip";@@ -163,6 +163,7 @@ function childrenToLabel(children: ReactNode): string | undefined {function RichLink({ href, children }: { href?: string; children?: ReactNode }) {const slug = useWorkspaceSlug();+ const appOrigin = useAppOrigin();if (href?.startsWith("slash://skill/")) {return <span className="slash-command">{children}</span>;@@ -185,13 +186,14 @@ function RichLink({ href, children }: { href?: string; children?: ReactNode }) {return <span className="mention">{children}</span>;}- // Regular links — open directly on click+ // Regular links — open directly on click. A URL pointing back at this+ // deployment routes in-app rather than out to the browser.return (<ahref={href}onClick={(e) => {e.preventDefault();- if (href) openLink(href, slug);+ if (href) openLink(href, slug, appOrigin);}}>{children}