Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat: open web issues in desktop (MUL-8735) (#10170)
Bohan Jiang9f47c142b9bf
diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.tsindex bcf7d87418..3382ffd838 100644--- a/apps/desktop/src/main/index.ts+++ b/apps/desktop/src/main/index.ts@@ -243,7 +243,7 @@ function handOffToWorkspaceWindow(): boolean {if (!source || !mainWindows.has(source)) return false;if (!request || typeof request !== "object") return false;- const { workspaceSlug: rawSlug, path: rawPath } = request as Record<+ const { workspaceSlug: rawSlug, path: rawPath, navigate } = request as Record<string,unknown>;@@ -255,7 +255,11 @@ function handOffToWorkspaceWindow(const target = mainWindows.findByWorkspace(workspaceSlug, source);if (!target || target.isDestroyed()) return false;if (path) {- dispatchToMainRenderer(WORKSPACE_OPEN_PATH_CHANNEL, path, target);+ dispatchToMainRenderer(+ WORKSPACE_OPEN_PATH_CHANNEL,+ { path, navigate: navigate === true },+ target,+ );} else {focusWindow(target);}@@ -327,6 +331,12 @@ function handleDeepLink(url: string): void {if (id) dispatchToMainRenderer("invite:open", decodeURIComponent(id));return;}++ if (parsed.hostname === "open" && parsed.pathname === "/issue") {+ // Keep the source instance in the payload. The authenticated renderer+ // validates it against runtime config before opening a workspace tab.+ dispatchToMainRenderer("issue:open", url);+ }} catch {// Ignore malformed URLs}diff --git a/apps/desktop/src/preload/index.d.ts b/apps/desktop/src/preload/index.d.tsindex 14685870eb..350a809643 100644--- a/apps/desktop/src/preload/index.d.ts+++ b/apps/desktop/src/preload/index.d.ts@@ -17,6 +17,10 @@ import type {LocalRuntimeProbe,} from "../shared/daemon-types";import type { TabSelectionShortcutKey } from "../shared/main-renderer-messages";+import type {+ WorkspacePathOptions,+ WorkspacePathRequest,+} from "../shared/workspace-window";interface DesktopAPI {/** App version + normalized OS, captured synchronously at preload time. */@@ -45,6 +49,8 @@ interface DesktopAPI {onAuthToken: (callback: (token: string) => void) => () => void;/** Listen for invitation IDs delivered via deep link. Returns an unsubscribe function. */onInviteOpen: (callback: (invitationId: string) => void) => () => void;+ /** Listen for issue links from the web once authentication is ready. */+ onIssueOpen: (callback: (url: string) => void) => () => void;/** Open a URL in the default browser. */openExternal: (url: string) => Promise<void>;/** Download a file by URL through Electron's native download system.@@ -126,12 +132,16 @@ interface DesktopAPI {getOtherWindowWorkspaces: () => string[];/** Hand a workspace (and optionally a path inside it) to the other main* window that shows it. Returns false when no other window does. */- focusWorkspaceWindow: (workspaceSlug: string, path?: string) => boolean;+ focusWorkspaceWindow: (+ workspaceSlug: string,+ path?: string,+ options?: WorkspacePathOptions,+ ) => boolean;/** Open a workspace in its own main window, or focus the one showing it. */openWorkspaceWindow: (workspaceSlug: string) => Promise<{ ok: boolean }>;/** Listen for workspace paths routed here from another window.* Returns an unsubscribe function. */- onOpenWorkspacePath: (callback: (path: string) => void) => () => void;+ onOpenWorkspacePath: (callback: (request: WorkspacePathRequest) => void) => () => void;/** Listen for Cmd/Ctrl+Shift+N new-window requests. Returns an* unsubscribe function. */onNewWindowShortcut: (callback: () => void) => () => void;diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.tsindex f360d87274..3e91ad549b 100644--- a/apps/desktop/src/preload/index.ts+++ b/apps/desktop/src/preload/index.ts@@ -38,6 +38,8 @@ import {OPEN_WORKSPACE_WINDOW_CHANNEL,OTHER_WINDOW_WORKSPACES_CHANNEL,WINDOW_WORKSPACE_REPORT_CHANNEL,+ type WorkspacePathOptions,+ type WorkspacePathRequest,} from "../shared/workspace-window";// Synchronously fetch app metadata from main at preload time so the renderer@@ -155,6 +157,8 @@ const desktopAPI = {/** Listen for invitation IDs delivered via deep link */onInviteOpen: (callback: (invitationId: string) => void) =>subscribeToMainRendererChannel("invite:open", callback),+ onIssueOpen: (callback: (url: string) => void) =>+ subscribeToMainRendererChannel("issue:open", callback),/** Open a URL in the default browser */openExternal: (url: string) => ipcRenderer.invoke("shell:openExternal", url),/** Download a file by URL through Electron's native download system.@@ -268,12 +272,17 @@ const desktopAPI = {},/** Hand a workspace (and optionally a path inside it) to the other main* window that shows it. Returns false when no other window does. */- focusWorkspaceWindow: (workspaceSlug: string, path?: string): boolean => {+ focusWorkspaceWindow: (+ workspaceSlug: string,+ path?: string,+ options?: WorkspacePathOptions,+ ): boolean => {try {return (ipcRenderer.sendSync(FOCUS_WORKSPACE_WINDOW_CHANNEL, {workspaceSlug,...(path === undefined ? {} : { path }),+ navigate: options?.navigate === true,}) === true);} catch {@@ -284,11 +293,14 @@ const desktopAPI = {openWorkspaceWindow: (workspaceSlug: string) =>ipcRenderer.invoke(OPEN_WORKSPACE_WINDOW_CHANNEL, workspaceSlug),/** Listen for workspace paths routed here from another window. */- onOpenWorkspacePath: (callback: (path: string) => void) =>+ onOpenWorkspacePath: (callback: (request: WorkspacePathRequest) => void) =>subscribeToMainRendererChannel<unknown>(WORKSPACE_OPEN_PATH_CHANNEL,- (path) => {- if (typeof path === "string") callback(path);+ (payload) => {+ const request = payload as Partial<WorkspacePathRequest> | null;+ if (typeof request?.path === "string") {+ callback({ path: request.path, navigate: request.navigate === true });+ }},),/** Listen for Cmd/Ctrl+Shift+N new-window requests. */diff --git a/apps/desktop/src/renderer/src/App.auth-recovery.test.tsx b/apps/desktop/src/renderer/src/App.auth-recovery.test.tsxindex 5a7ec84299..04e6484bf4 100644--- a/apps/desktop/src/renderer/src/App.auth-recovery.test.tsx+++ b/apps/desktop/src/renderer/src/App.auth-recovery.test.tsx@@ -176,6 +176,7 @@ beforeEach(() => {onAuthToken: () => () => {},onCloseActiveTab: () => () => {},onInviteOpen: () => () => {},+ onIssueOpen: () => () => {},onSystemLocaleChanged: () => () => {},reportAuthSession: vi.fn(),runtimeConfig: {diff --git a/apps/desktop/src/renderer/src/App.tsx b/apps/desktop/src/renderer/src/App.tsxindex 3785af0016..3ad3b0b923 100644--- a/apps/desktop/src/renderer/src/App.tsx+++ b/apps/desktop/src/renderer/src/App.tsx@@ -30,6 +30,7 @@ import { DiagnosticRouteReporter } from "./platform/diagnostic-route-reporter";import { flushFreezeBreadcrumb } from "./freeze-flush";import { DesktopAuthSessionBridge } from "./platform/auth-session-bridge";import { WorkspaceWindowBridge } from "./platform/workspace-window-bridge";+import { IssueDeepLinkBridge } from "./platform/issue-deep-link-bridge";import {launchWorkspaceSlug,otherWindowWorkspaces,@@ -485,6 +486,7 @@ export default function App() {<DesktopAuthSessionBridge />{windowContext.kind === "main" && <DiagnosticRouteReporter />}{windowContext.kind === "main" && <WorkspaceWindowBridge />}+ {windowContext.kind === "main" && <IssueDeepLinkBridge />}{windowContext.kind === "main" && (<DesktopClientUsageReporterapiUrl={runtimeConfigResult.config.apiUrl}diff --git a/apps/desktop/src/renderer/src/platform/issue-deep-link-bridge.test.tsx b/apps/desktop/src/renderer/src/platform/issue-deep-link-bridge.test.tsxnew file mode 100644index 0000000000..4184887ca3--- /dev/null+++ b/apps/desktop/src/renderer/src/platform/issue-deep-link-bridge.test.tsx@@ -0,0 +1,195 @@+import { act, render } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { I18nProvider } from "@multica/core/i18n/react";+import enIssues from "@multica/views/locales/en/issues.json";+import enLayout from "@multica/views/locales/en/layout.json";+import type { ReactNode } from "react";+import type {+ WorkspacePathOptions,+ WorkspacePathRequest,+} from "../../../shared/workspace-window";++const { state, authState } = vi.hoisted(() => {+ const state = { authenticated: true, ready: true };+ return {+ state,+ authState: () => ({+ status: state.authenticated ? "authenticated" : "unauthenticated",+ user: state.authenticated ? { id: "user-1" } : null,+ }),+ };+});+vi.mock("@multica/core/auth", () => ({+ useAuthStore: Object.assign(+ (selector: (value: ReturnType<typeof authState>) => unknown) => selector(authState()),+ { getState: authState },+ ),+}));+vi.mock("@multica/core/workspace", () => ({+ useWorkspaceList: () => ({ ready: state.ready, workspaces: [{ slug: "acme" }, { slug: "other" }] }),+}));+const { error } = vi.hoisted(() => ({ error: vi.fn() }));+vi.mock("sonner", () => ({ toast: { error } }));++import { IssueDeepLinkBridge } from "./issue-deep-link-bridge";+import { WorkspaceWindowBridge } from "./workspace-window-bridge";+import { routeContentLinkPath } from "./navigation";+import { getActiveTab, useTabStore } from "@/stores/tab-store";++let receive: ((url: string) => void) | undefined;+let receiveWorkspace: ((request: WorkspacePathRequest) => void) | undefined;+const focusWorkspaceWindow = vi.fn(+ (_slug: string, _path?: string, _options?: WorkspacePathOptions) => false,+);+const unsubscribe = vi.fn();+const subscribe = vi.fn((callback: (url: string) => void) => {+ receive = callback;+ return unsubscribe;+});+const ui = (children: ReactNode = <IssueDeepLinkBridge />) => (+ <I18nProvider locale="en" resources={{ en: { issues: enIssues, layout: enLayout } }}>+ {children}+ </I18nProvider>+);+const link = (path: string, origin = "https://tasks.example") =>+ `multica://open/issue?url=${encodeURIComponent(origin + path)}`;++beforeEach(() => {+ vi.clearAllMocks();+ state.authenticated = true;+ state.ready = true;+ receive = undefined;+ receiveWorkspace = undefined;+ focusWorkspaceWindow.mockReturnValue(false);+ Object.defineProperty(window, "desktopAPI", {+ configurable: true,+ value: {+ runtimeConfig: { ok: true, config: { appUrl: "https://tasks.example" } },+ onIssueOpen: subscribe,+ focusWorkspaceWindow,+ onOpenWorkspacePath: (callback: (request: WorkspacePathRequest) => void) => {+ receiveWorkspace = callback;+ return () => { receiveWorkspace = undefined; };+ },+ },+ });+ useTabStore.getState().reset();+ useTabStore.getState().switchWorkspace("acme");+});++describe("IssueDeepLinkBridge", () => {+ it("leaves links in main's queue until sign-in and membership are ready", () => {+ state.authenticated = false;+ const { rerender } = render(ui());+ expect(subscribe).not.toHaveBeenCalled();+ state.authenticated = true;+ state.ready = false;+ rerender(ui());+ expect(subscribe).not.toHaveBeenCalled();+ state.ready = true;+ rerender(ui());+ expect(subscribe).toHaveBeenCalled();+ });++ it("opens a cross-workspace issue with its comment through the navigation flow", () => {+ const { unmount } = render(ui());+ act(() => receive!(link("/other/issues/OTH-2#comment-c1")));+ expect(useTabStore.getState().activeWorkspaceSlug).toBe("other");+ expect(getActiveTab(useTabStore.getState())?.url).toBe("/other/issues/OTH-2#comment-c1");+ unmount();+ expect(unsubscribe).toHaveBeenCalled();+ });++ it.each(["acme", "other"])("navigates an existing %s issue tab to the new comment", (slug) => {+ const oldPath = `/${slug}/issues/ACM-42#comment-old`;+ const newPath = `/${slug}/issues/ACM-42#comment-new`;+ useTabStore.getState().switchWorkspace(slug, oldPath);+ const existing = getActiveTab(useTabStore.getState())!;+ const tabCount = useTabStore.getState().byWorkspace[slug]!.tabs.length;+ if (slug !== "acme") useTabStore.getState().switchWorkspace("acme");+ render(ui());++ act(() => receive!(link(newPath)));++ const current = getActiveTab(useTabStore.getState())!;+ expect(current.id).toBe(existing.id);+ expect(current.url).toBe(newPath);+ expect(current.history.stack[current.history.index]).toBe(newPath);+ expect(useTabStore.getState().byWorkspace[slug]!.tabs).toHaveLength(tabCount);+ });++ it("applies the new comment in the workspace's existing window without moving the source", () => {+ const oldPath = "/other/issues/OTH-2#comment-old";+ const newPath = "/other/issues/OTH-2#comment-new";+ useTabStore.getState().switchWorkspace("other", oldPath);+ const destination = useTabStore.getState();+ const existing = getActiveTab(destination)!;+ // Each window has its own store. Save the destination's real sessions,+ // then restore them when delivering the request across the IPC boundary.+ useTabStore.getState().reset();+ useTabStore.getState().switchWorkspace("acme");+ const source = getActiveTab(useTabStore.getState());+ focusWorkspaceWindow.mockReturnValue(true);+ const { unmount } = render(ui());++ act(() => receive!(link(newPath)));++ expect(focusWorkspaceWindow).toHaveBeenCalledWith("other", newPath, { navigate: true });+ expect(getActiveTab(useTabStore.getState())).toBe(source);+ expect(useTabStore.getState().byWorkspace.other).toBeUndefined();+ const [, path, options] = focusWorkspaceWindow.mock.calls[0]!;+ unmount();+ useTabStore.setState({+ activeWorkspaceSlug: destination.activeWorkspaceSlug,+ byWorkspace: destination.byWorkspace,+ });+ render(ui(<WorkspaceWindowBridge />));++ act(() => receiveWorkspace!({ path: path!, ...options }));++ const current = getActiveTab(useTabStore.getState())!;+ expect(current.id).toBe(existing.id);+ expect(current.url).toBe(newPath);+ expect(current.history.stack[current.history.index]).toBe(newPath);+ expect(useTabStore.getState().byWorkspace.other!.tabs).toHaveLength(1);+ });++ it.each(["acme", "other"])("preserves the existing %s view on ordinary tab opens", (slug) => {+ const oldPath = `/${slug}/issues/ACM-42?view=activity#comment-old`;+ const newPath = `/${slug}/issues/ACM-42?view=activity#comment-new`;+ useTabStore.getState().switchWorkspace(slug, oldPath);+ const existing = getActiveTab(useTabStore.getState());+ useTabStore.getState().switchWorkspace("acme");++ routeContentLinkPath(newPath, "foreground-tab");++ expect(getActiveTab(useTabStore.getState())).toBe(existing);+ });++ it("preserves the destination's view for an ordinary request from another window", () => {+ const oldPath = "/other/issues/OTH-2?view=activity#comment-old";+ useTabStore.getState().switchWorkspace("other", oldPath);+ const existing = getActiveTab(useTabStore.getState());+ render(ui(<WorkspaceWindowBridge />));++ act(() => receiveWorkspace!({ path: "/other/issues/OTH-2?view=activity#comment-new" }));++ expect(getActiveTab(useTabStore.getState())).toBe(existing);+ });++ it("reports another instance without navigating", () => {+ render(ui());+ const previous = getActiveTab(useTabStore.getState());+ act(() => receive!(link("/acme/issues/ACM-1", "https://other.example")));+ expect(error).toHaveBeenCalledWith(enIssues.desktop.link_other_instance);+ expect(getActiveTab(useTabStore.getState())).toBe(previous);+ });++ it("does not navigate into a workspace outside the current account", () => {+ render(ui());+ const previous = getActiveTab(useTabStore.getState());+ act(() => receive!(link("/private/issues/PRI-1")));+ expect(error).toHaveBeenCalledWith(enIssues.desktop.link_workspace_unavailable);+ expect(getActiveTab(useTabStore.getState())).toBe(previous);+ });+});diff --git a/apps/desktop/src/renderer/src/platform/issue-deep-link-bridge.tsx b/apps/desktop/src/renderer/src/platform/issue-deep-link-bridge.tsxnew file mode 100644index 0000000000..e9d3336b93--- /dev/null+++ b/apps/desktop/src/renderer/src/platform/issue-deep-link-bridge.tsx@@ -0,0 +1,35 @@+import { useEffect } from "react";+import { toast } from "sonner";+import { useAuthStore } from "@multica/core/auth";+import { useWorkspaceList } from "@multica/core/workspace";+import { useT } from "@multica/views/i18n";+import { parseIssueDeepLink } from "../../../shared/issue-deep-link";+import { routeIssueDeepLinkPath } from "./navigation";++export function IssueDeepLinkBridge() {+ const { t } = useT("issues");+ const authenticated = useAuthStore((s) => s.status === "authenticated");+ const { workspaces, ready } = useWorkspaceList({ enabled: authenticated });+ const config = window.desktopAPI.runtimeConfig;++ useEffect(() => {+ // Main keeps the link queued through cold start and sign-in until this+ // listener can resolve the destination against authoritative membership.+ if (!authenticated || !ready || !config.ok) return;+ return window.desktopAPI.onIssueOpen((url) => {+ const target = parseIssueDeepLink(url, config.config.appUrl);+ if (!target) return;+ if (target.kind === "other-instance") {+ toast.error(t(($) => $.desktop.link_other_instance));+ return;+ }+ if (!workspaces.some((workspace) => workspace.slug === target.workspaceSlug)) {+ toast.error(t(($) => $.desktop.link_workspace_unavailable));+ return;+ }+ routeIssueDeepLinkPath(target.path);+ });+ }, [authenticated, ready, workspaces, config, t]);++ return null;+}diff --git a/apps/desktop/src/renderer/src/platform/navigation.tsx b/apps/desktop/src/renderer/src/platform/navigation.tsxindex e318b06bd7..937a4c4780 100644--- a/apps/desktop/src/renderer/src/platform/navigation.tsx+++ b/apps/desktop/src/renderer/src/platform/navigation.tsx@@ -132,6 +132,22 @@ export function routeContentLinkPath(store.openTab(path, "", { activate: disposition === "foreground-tab" });}+/** A desktop deep link explicitly targets its URL, including a new comment. */+export function routeIssueDeepLinkPath(path: string): void {+ const store = useTabStore.getState();+ const slug = workspaceSlugForPath(path);+ if (!slug) return;+ if (slug !== store.activeWorkspaceSlug) {+ if (handOffToWorkspaceWindow(slug, path, { navigate: true })) return;+ store.switchWorkspace(slug, path);+ } else {+ store.openTab(path, "", { activate: true });+ }+ // Ordinary opens restore a reused tab's view. A deep link must also apply+ // this address after deduplication, through the session's history flow.+ useTabStore.getState().navigateActiveSession(path);+}+/*** 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/desktop/src/renderer/src/platform/workspace-window-bridge.tsx b/apps/desktop/src/renderer/src/platform/workspace-window-bridge.tsxindex a608a0c474..af5e98b689 100644--- a/apps/desktop/src/renderer/src/platform/workspace-window-bridge.tsx+++ b/apps/desktop/src/renderer/src/platform/workspace-window-bridge.tsx@@ -34,9 +34,11 @@ export function WorkspaceWindowBridge() {useEffect(() =>- window.desktopAPI.onOpenWorkspacePath?.((path) => {+ window.desktopAPI.onOpenWorkspacePath?.(({ path, navigate }) => {const slug = workspaceSlugForPath(path);- if (slug) useTabStore.getState().switchWorkspace(slug, path);+ if (!slug) return;+ useTabStore.getState().switchWorkspace(slug, path);+ if (navigate) useTabStore.getState().navigateActiveSession(path);}),[],);diff --git a/apps/desktop/src/renderer/src/platform/workspace-windows.ts b/apps/desktop/src/renderer/src/platform/workspace-windows.tsindex b3a2d72af2..88dde80cb9 100644--- a/apps/desktop/src/renderer/src/platform/workspace-windows.ts+++ b/apps/desktop/src/renderer/src/platform/workspace-windows.ts@@ -1,3 +1,5 @@+import type { WorkspacePathOptions } from "../../../shared/workspace-window";+/*** Desktop main windows each show one workspace (the VS Code folder model).* These helpers send a workspace this window does not show to the window@@ -14,9 +16,14 @@ function isMainWindow(): boolean {* already shows that workspace. Returns false when no other window does, so* the caller switches its own workspace instead.*/-export function handOffToWorkspaceWindow(slug: string, path?: string): boolean {+export function handOffToWorkspaceWindow(+ slug: string,+ path?: string,+ options?: WorkspacePathOptions,+): boolean {if (!isMainWindow()) return false;- return window.desktopAPI.focusWorkspaceWindow?.(slug, path) ?? false;+ const focus = window.desktopAPI.focusWorkspaceWindow;+ return (options ? focus?.(slug, path, options) : focus?.(slug, path)) ?? false;}export function openWorkspaceInNewWindow(slug: string): void {diff --git a/apps/desktop/src/shared/issue-deep-link.test.ts b/apps/desktop/src/shared/issue-deep-link.test.tsnew file mode 100644index 0000000000..e4f6771d53--- /dev/null+++ b/apps/desktop/src/shared/issue-deep-link.test.ts@@ -0,0 +1,50 @@+// @vitest-environment node+import { describe, expect, it } from "vitest";+import { parseIssueDeepLink } from "./issue-deep-link";++const link = (url: string) => `multica://open/issue?url=${encodeURIComponent(url)}`;++describe("parseIssueDeepLink", () => {+ it("keeps the workspace, query and comment on a self-hosted instance", () => {+ expect(parseIssueDeepLink(link("https://tasks.example/acme/issues/ACM-42?view=activity#comment-c1"), "https://tasks.example")).toEqual({+ kind: "issue",+ workspaceSlug: "acme",+ path: "/acme/issues/ACM-42?view=activity#comment-c1",+ });+ });++ it("accepts UUID issue links and an app URL with a base path", () => {+ const path = "/acme/issues/01a1b5e5-e4c5-78d1-ab0e-9c6e708a9939";+ expect(parseIssueDeepLink(link(`http://localhost:3000/multica${path}`), "http://localhost:3000/multica/")).toEqual({+ kind: "issue", workspaceSlug: "acme", path,+ });+ });++ it.each([+ "http://tasks.example/acme/issues/ACM-42",+ "https://tasks.example:8443/acme/issues/ACM-42",+ "https://tasks.example.evil.test/acme/issues/ACM-42",+ "https://other.example/acme/issues/ACM-42",+ ])("rejects a different instance: %s", (url) => {+ expect(parseIssueDeepLink(link(url), "https://tasks.example")).toEqual({ kind: "other-instance" });+ });++ it("does not mistake another deployment on the same origin for the configured base path", () => {+ expect(parseIssueDeepLink(link("https://tasks.example/app-two/acme/issues/ACM-42"), "https://tasks.example/app")).toEqual({ kind: "other-instance" });+ });++ it.each([+ "multica://open/issue",+ "https://open/issue?url=https://tasks.example/acme/issues/ACM-42",+ "multica://auth/callback?token=secret",+ link("javascript:alert(1)"),+ link("file:///acme/issues/ACM-42"),+ link("https://user:[email protected]/acme/issues/ACM-42"),+ link("https://tasks.example/acme/settings"),+ link("https://tasks.example/acme/issues/ACM-42/extra"),+ link("https://tasks.example/acme%2Fevil/issues/ACM-42"),+ "invalid",+ ])("ignores malformed or non-issue links: %s", (url) => {+ expect(parseIssueDeepLink(url, "https://tasks.example")).toBeNull();+ });+});diff --git a/apps/desktop/src/shared/issue-deep-link.ts b/apps/desktop/src/shared/issue-deep-link.tsnew file mode 100644index 0000000000..2103fd9977--- /dev/null+++ b/apps/desktop/src/shared/issue-deep-link.ts@@ -0,0 +1,42 @@+import { parseIssueWindowPath } from "./issue-window";++export type IssueDeepLink =+ | { kind: "issue"; workspaceSlug: string; path: string }+ | { kind: "other-instance" };++/** Never interpret an issue identifier against a different server. */+export function parseIssueDeepLink(+ value: string,+ appUrl: string,+): IssueDeepLink | null {+ try {+ const link = new URL(value);+ if (+ link.protocol !== "multica:" ||+ link.host !== "open" ||+ link.pathname !== "/issue"+ ) return null;+ const url = new URL(link.searchParams.get("url") ?? "");+ if (+ !["http:", "https:"].includes(url.protocol) ||+ url.username ||+ url.password+ ) return null;+ const app = new URL(appUrl);+ const basePath = app.pathname.replace(/\/+$/, "");+ if (url.origin !== app.origin || !url.pathname.startsWith(`${basePath}/`)) {+ return { kind: "other-instance" };+ }+ const target = parseIssueWindowPath(+ url.pathname.slice(basePath.length) + url.search + url.hash,+ );+ if (!target) return null;+ return {+ kind: "issue",+ workspaceSlug: target.workspaceSlug,+ path: target.path,+ };+ } catch {+ return null;+ }+}diff --git a/apps/desktop/src/shared/main-renderer-messages.ts b/apps/desktop/src/shared/main-renderer-messages.tsindex 46bbb8a254..012f7e5edc 100644--- a/apps/desktop/src/shared/main-renderer-messages.ts+++ b/apps/desktop/src/shared/main-renderer-messages.ts@@ -30,6 +30,7 @@ export const NEW_WINDOW_SHORTCUT_CHANNEL = "window:new-by-shortcut";export const MAIN_RENDERER_MESSAGE_CHANNELS = ["auth:token","invite:open",+ "issue:open","inbox:open","settings:open",TAB_SELECTION_SHORTCUT_CHANNEL,diff --git a/apps/desktop/src/shared/workspace-window.ts b/apps/desktop/src/shared/workspace-window.tsindex d3cfe06f24..9eb436d339 100644--- a/apps/desktop/src/shared/workspace-window.ts+++ b/apps/desktop/src/shared/workspace-window.ts@@ -9,6 +9,15 @@ export const FOCUS_WORKSPACE_WINDOW_CHANNEL = "window:focus-workspace";/** Renderer → main: open a workspace in its own main window. */export const OPEN_WORKSPACE_WINDOW_CHANNEL = "window:open-workspace";+export interface WorkspacePathOptions {+ /** Navigate a reused tab to the requested URL instead of restoring its view. */+ navigate?: boolean;+}++export interface WorkspacePathRequest extends WorkspacePathOptions {+ path: string;+}+const WORKSPACE_SLUG_PATTERN = /^[a-z0-9][a-z0-9-]{0,62}$/;const MAX_WORKSPACE_PATH_LENGTH = 2_048;diff --git a/apps/web/platform/navigation.tsx b/apps/web/platform/navigation.tsxindex 5e35819826..3215665c55 100644--- a/apps/web/platform/navigation.tsx+++ b/apps/web/platform/navigation.tsx@@ -86,6 +86,10 @@ function NavigationProviderInner({hash,getShareableUrl: (path: string) =>typeof window === "undefined" ? path : window.location.origin + path,+ openInDesktop: (path: string) => {+ const url = window.location.origin + path;+ window.location.href = `multica://open/issue?url=${encodeURIComponent(url)}`;+ },// router.prefetch is a no-op in dev mode by Next.js design; in production// it warms the RSC payload + route chunk so the next push() commits with// no network round-trip. Safe to call repeatedly — Next dedupes internally.diff --git a/packages/views/issues/actions/__tests__/issue-actions-menu.test.tsx b/packages/views/issues/actions/__tests__/issue-actions-menu.test.tsxindex 08f1a8f770..abeb989f1a 100644--- a/packages/views/issues/actions/__tests__/issue-actions-menu.test.tsx+++ b/packages/views/issues/actions/__tests__/issue-actions-menu.test.tsx@@ -104,21 +104,23 @@ vi.mock("@multica/core/paths", async () => {// Module-level flag toggled per-test: desktop implements `openInNewTab`,// web omits it and the menu has to fall back to a real browser tab.-const { openInNewTabMock, getShareableUrlMock, navState } = vi.hoisted(() => ({+const { openInNewTabMock, openInDesktopMock, getShareableUrlMock, navState } = vi.hoisted(() => ({openInNewTabMock: vi.fn(),+ openInDesktopMock: vi.fn(),getShareableUrlMock: vi.fn((p: string) => `https://app.example${p}`),- navState: { hasOpenInNewTab: true },+ navState: { hasOpenInNewTab: true, hasOpenInDesktop: false, pathname: "/test/issues/issue-1", hash: "" },}));vi.mock("../../../navigation", () => ({useNavigation: () => ({push: vi.fn(),- pathname: "/test/issues/issue-1",+ pathname: navState.pathname,searchParams: new URLSearchParams(),- hash: "",+ hash: navState.hash,back: vi.fn(),replace: vi.fn(),...(navState.hasOpenInNewTab ? { openInNewTab: openInNewTabMock } : {}),+ ...(navState.hasOpenInDesktop ? { openInDesktop: openInDesktopMock } : {}),getShareableUrl: getShareableUrlMock,}),}));@@ -201,8 +203,12 @@ beforeEach(() => {deletionPolicy.allowed = true;mockOpenModal.mockReset();openInNewTabMock.mockReset();+ openInDesktopMock.mockReset();getShareableUrlMock.mockClear();navState.hasOpenInNewTab = true;+ navState.hasOpenInDesktop = false;+ navState.pathname = "/test/issues/issue-1";+ navState.hash = "";copyTextMock.mockReset();copyTextMock.mockResolvedValue(true);toastSuccessMock.mockReset();@@ -527,6 +533,39 @@ describe("Open in new tab", () => {});});+describe("Open in Desktop", () => {+ async function openMenu() {+ render(wrap(<IssueActionsDropdown issue={mockIssue} trigger={<button data-testid="trigger">Menu</button>} />));+ fireEvent.click(screen.getByTestId("trigger"));+ await screen.findByText("Open in new tab");+ }++ it("appears directly below Open in new tab on web and hands off the current comment", async () => {+ navState.hasOpenInDesktop = true;+ navState.pathname = "/test/issues/TES-1";+ navState.hash = "#comment-c1";+ await openMenu();+ const labels = screen.getAllByRole("menuitem").map((item) => item.textContent);+ expect(labels[labels.indexOf("Open in new tab") + 1]).toBe("Open in Desktop");+ fireEvent.click(screen.getByText("Open in Desktop"));+ expect(openInDesktopMock).toHaveBeenCalledWith("/test/issues/TES-1#comment-c1");+ });++ it("opens the selected issue without copying another issue's comment anchor", async () => {+ navState.hasOpenInDesktop = true;+ navState.pathname = "/test/issues/TES-99";+ navState.hash = "#comment-other";+ await openMenu();+ fireEvent.click(screen.getByText("Open in Desktop"));+ expect(openInDesktopMock).toHaveBeenCalledWith("/test/issues/TES-1");+ });++ it("is hidden in the desktop app", async () => {+ await openMenu();+ expect(screen.queryByText("Open in Desktop")).not.toBeInTheDocument();+ });+});+describe("IssueActionsContextMenu", () => {it("renders the menu when the wrapped element receives a contextmenu event", async () => {render(diff --git a/packages/views/issues/actions/issue-actions-menu-items.tsx b/packages/views/issues/actions/issue-actions-menu-items.tsxindex 5b44482a65..cbb406748e 100644--- a/packages/views/issues/actions/issue-actions-menu-items.tsx+++ b/packages/views/issues/actions/issue-actions-menu-items.tsx@@ -16,6 +16,7 @@ import {Hash,Link2,LocateFixed,+ Monitor,Network,Pin,PinOff,@@ -160,6 +161,7 @@ export function IssueActionsMenuItems({isPinned,updateField,openInNewTab,+ openInDesktop,togglePin,copyLink,openCreateSubIssue,@@ -417,6 +419,12 @@ export function IssueActionsMenuItems({<ExternalLink className="h-3.5 w-3.5" />{t(($) => $.actions.open_in_new_tab)}</P.Item>+ {openInDesktop && (+ <P.Item onClick={openInDesktop}>+ <Monitor className="h-3.5 w-3.5" />+ {t(($) => $.web.open_in_desktop)}+ </P.Item>+ )}<P.Item onClick={togglePin}>{isPinned ? (<PinOff className="h-3.5 w-3.5" />diff --git a/packages/views/issues/actions/use-issue-actions.ts b/packages/views/issues/actions/use-issue-actions.tsindex 669d43cfcb..0d89cc2e79 100644--- a/packages/views/issues/actions/use-issue-actions.ts+++ b/packages/views/issues/actions/use-issue-actions.ts@@ -27,6 +27,7 @@ export interface UseIssueActionsResult {options?: IssueSurfaceMutationOptions,) => void;openInNewTab: () => void;+ openInDesktop?: () => void;togglePin: () => void;copyLink: () => Promise<void>;copyCommentLink: (commentId: string) => Promise<void>;@@ -151,6 +152,15 @@ export function useIssueActions(issue: Issue | null): UseIssueActionsResult {);}, [issueId, issueIdentifier, navigation, paths]);+ const openInDesktop = useCallback(() => {+ if (!issueId) return;+ const path = paths.issueDetail(issueIdentifier || issueId);+ const isCurrentIssue =+ navigation.pathname === path ||+ navigation.pathname === paths.issueDetail(issueId);+ navigation.openInDesktop?.(path + (isCurrentIssue ? navigation.hash : ""));+ }, [issueId, issueIdentifier, navigation, paths]);+const togglePin = useCallback(() => {if (!issueId) return;if (isPinned) {@@ -299,6 +309,7 @@ export function useIssueActions(issue: Issue | null): UseIssueActionsResult {isPinned,updateField,openInNewTab,+ openInDesktop: navigation.openInDesktop ? openInDesktop : undefined,togglePin,copyLink,copyCommentLink,diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.jsonindex f3d3d00073..8b659d6ab6 100644--- a/packages/views/locales/en/issues.json+++ b/packages/views/locales/en/issues.json@@ -1,4 +1,11 @@{+ "web": {+ "open_in_desktop": "Open in Desktop"+ },+ "desktop": {+ "link_other_instance": "The desktop app is connected to a different Multica instance.",+ "link_workspace_unavailable": "This workspace is unavailable in the desktop app."+ },"inline_run": {"label": "{{name}} run","stop": "Stop",diff --git a/packages/views/locales/es/issues.json b/packages/views/locales/es/issues.jsonindex f20120ced5..5d67791e65 100644--- a/packages/views/locales/es/issues.json+++ b/packages/views/locales/es/issues.json@@ -1,4 +1,11 @@{+ "web": {+ "open_in_desktop": "Abrir en la aplicación de escritorio"+ },+ "desktop": {+ "link_other_instance": "La aplicación de escritorio está conectada a otra instancia de Multica.",+ "link_workspace_unavailable": "Este espacio de trabajo no está disponible en la aplicación de escritorio."+ },"inline_run": {"label": "Ejecución de {{name}}","stop": "Detener",diff --git a/packages/views/locales/fr/issues.json b/packages/views/locales/fr/issues.jsonindex db17022b33..a68fb6ec0a 100644--- a/packages/views/locales/fr/issues.json+++ b/packages/views/locales/fr/issues.json@@ -1,4 +1,11 @@{+ "web": {+ "open_in_desktop": "Ouvrir dans l’application de bureau"+ },+ "desktop": {+ "link_other_instance": "L’application de bureau est connectée à une autre instance Multica.",+ "link_workspace_unavailable": "Cet espace de travail n’est pas disponible dans l’application de bureau."+ },"inline_run": {"label": "Exécution de {{name}}","stop": "Arrêter",diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.jsonindex 140941e5cc..0d41e8e726 100644--- a/packages/views/locales/ja/issues.json+++ b/packages/views/locales/ja/issues.json@@ -1,4 +1,11 @@{+ "web": {+ "open_in_desktop": "デスクトップで開く"+ },+ "desktop": {+ "link_other_instance": "デスクトップアプリは別の Multica インスタンスに接続されています。",+ "link_workspace_unavailable": "このワークスペースはデスクトップアプリでは利用できません。"+ },"inline_run": {"label": "{{name}} の実行","stop": "停止",diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.jsonindex 1e4a7e21bd..fc46e47622 100644--- a/packages/views/locales/ko/issues.json+++ b/packages/views/locales/ko/issues.json@@ -1,4 +1,11 @@{+ "web": {+ "open_in_desktop": "데스크톱에서 열기"+ },+ "desktop": {+ "link_other_instance": "데스크톱 앱이 다른 Multica 인스턴스에 연결되어 있습니다.",+ "link_workspace_unavailable": "데스크톱 앱에서 이 워크스페이스를 사용할 수 없습니다."+ },"inline_run": {"label": "{{name}} 실행","stop": "중지",diff --git a/packages/views/locales/ru/issues.json b/packages/views/locales/ru/issues.jsonindex 9f55795e0d..156560f72a 100644--- a/packages/views/locales/ru/issues.json+++ b/packages/views/locales/ru/issues.json@@ -1,4 +1,11 @@{+ "web": {+ "open_in_desktop": "Открыть в приложении"+ },+ "desktop": {+ "link_other_instance": "Приложение подключено к другому экземпляру Multica.",+ "link_workspace_unavailable": "Это рабочее пространство недоступно в приложении."+ },"inline_run": {"label": "Запуск {{name}}","stop": "Остановить",diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.jsonindex e49f37437a..b87358c44e 100644--- a/packages/views/locales/zh-Hans/issues.json+++ b/packages/views/locales/zh-Hans/issues.json@@ -1,4 +1,11 @@{+ "web": {+ "open_in_desktop": "在桌面端打开"+ },+ "desktop": {+ "link_other_instance": "桌面端连接的是另一个 Multica 实例。",+ "link_workspace_unavailable": "此工作区在桌面端不可用。"+ },"inline_run": {"label": "{{name}} 的运行","stop": "停止",diff --git a/packages/views/locales/zh-Hant/issues.json b/packages/views/locales/zh-Hant/issues.jsonindex dd257a0746..18656ef3bb 100644--- a/packages/views/locales/zh-Hant/issues.json+++ b/packages/views/locales/zh-Hant/issues.json@@ -1,4 +1,11 @@{+ "web": {+ "open_in_desktop": "在桌面版開啟"+ },+ "desktop": {+ "link_other_instance": "桌面版連線的是另一個 Multica 執行個體。",+ "link_workspace_unavailable": "此工作區在桌面版中無法使用。"+ },"inline_run": {"label": "{{name}} 的執行","stop": "停止",diff --git a/packages/views/navigation/types.ts b/packages/views/navigation/types.tsindex 6893bb4534..1cc8c0cccc 100644--- a/packages/views/navigation/types.ts+++ b/packages/views/navigation/types.ts@@ -28,6 +28,8 @@ export interface NavigationAdapter {title?: string,opts?: { activate?: boolean },) => void;+ /** Web only: hand an issue path to the installed desktop app. */+ openInDesktop?: (path: string) => void;/*** Desktop only: show a workspace in its own window, or focus the window* that already shows it.diff --git a/scripts/dev-env.sh b/scripts/dev-env.shindex eca94c3d96..b3968dc61d 100755--- a/scripts/dev-env.sh+++ b/scripts/dev-env.sh@@ -966,6 +966,7 @@ write_desktop_env_file() {# Managed by scripts/dev-env.sh for environment ${NAME}.VITE_API_URL=http://localhost:${BACKEND_PORT}VITE_WS_URL=ws://localhost:${BACKEND_PORT}/ws+VITE_APP_URL=http://localhost:${FRONTEND_PORT}EOF}@@ -989,7 +990,8 @@ desktop_env_matches() {[ -f "$DESKTOP_ENV_FILE" ] \&& grep -Fqx "# Managed by scripts/dev-env.sh for environment ${NAME}." "$DESKTOP_ENV_FILE" \&& grep -Fqx "VITE_API_URL=http://localhost:${BACKEND_PORT}" "$DESKTOP_ENV_FILE" \- && grep -Fqx "VITE_WS_URL=ws://localhost:${BACKEND_PORT}/ws" "$DESKTOP_ENV_FILE"+ && grep -Fqx "VITE_WS_URL=ws://localhost:${BACKEND_PORT}/ws" "$DESKTOP_ENV_FILE" \+ && grep -Fqx "VITE_APP_URL=http://localhost:${FRONTEND_PORT}" "$DESKTOP_ENV_FILE"}desktop_cdp_ready() {diff --git a/scripts/dev-env.test.sh b/scripts/dev-env.test.shindex c1f7a45b32..66e96734a7 100644--- a/scripts/dev-env.test.sh+++ b/scripts/dev-env.test.sh@@ -451,7 +451,7 @@ assert_desktop_env_sync() (local case_name=$1 initial=$2 expected=$3# shellcheck disable=SC1090source "$root_dir/scripts/dev-env.sh"- NAME=sync-env BACKEND_PORT=18555+ NAME=sync-env BACKEND_PORT=18555 FRONTEND_PORT=13555DESKTOP_ENV_FILE="$tmp_dir/desktop-env-$case_name"rm -f "$DESKTOP_ENV_FILE"[ -z "$initial" ] || printf '%s\n' "$initial" > "$DESKTOP_ENV_FILE"@@ -462,6 +462,9 @@ assert_desktop_env_sync() (assert_desktop_env_sync missing "" "VITE_API_URL=http://localhost:18555"assert_desktop_env_sync managed-elsewhere "# Managed by scripts/dev-env.sh for environment old-env." \"VITE_API_URL=http://localhost:18555"+assert_desktop_env_sync managed-missing-app "# Managed by scripts/dev-env.sh for environment sync-env.+VITE_API_URL=http://localhost:18555+VITE_WS_URL=ws://localhost:18555/ws" "VITE_APP_URL=http://localhost:13555"assert_desktop_env_sync hand-written "VITE_API_URL=https://staging.example" "VITE_API_URL=https://staging.example"# Turbo puts Electron in a nested process group; the stop path finds it through