Skip to content

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

Go

MUL-5860: unify internal link click semantics across all surfaces (#6667)

Naiyuan Qingad7e621139b5
diff --git a/apps/desktop/src/renderer/src/components/desktop-layout.tsx b/apps/desktop/src/renderer/src/components/desktop-layout.tsx
index 562c0d811c..c829488894 100644
--- a/apps/desktop/src/renderer/src/components/desktop-layout.tsx
+++ b/apps/desktop/src/renderer/src/components/desktop-layout.tsx
@@ -2,7 +2,10 @@ import { useEffect, useRef, useSyncExternalStore } from "react";
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 {
+ useNavigationInputBindings,
+ useTabHistory,
+} from "@/hooks/use-tab-history";
import {
SidebarProvider,
SidebarTrigger,
@@ -13,7 +16,10 @@ import { AppSidebar, GlobalShortcuts } from "@multica/views/layout";
import { SearchCommand, SearchTrigger } from "@multica/views/search";
import { FloatingChat } from "@multica/views/chat";
import { WorkspaceSlugProvider, paths, useCurrentWorkspace } from "@multica/core/paths";
-import { useNavigation } from "@multica/views/navigation";
+import {
+ useNavigation,
+ type LinkClickIntent,
+} from "@multica/views/navigation";
import { getCurrentSlug, subscribeToCurrentSlug } from "@multica/core/platform";
import { useDesktopUnreadBadge } from "@multica/views/platform";
import {
@@ -101,6 +107,7 @@ function useNativeNavigationGestures() {
}, [goBack, goForward]);
}
+
// The main area's top bar doubles as a window drag region. When the sidebar
// is not occupying main-flow width, leave room for the fixed window toolbar
// so tabs do not land beneath the traffic lights / navigation controls.
@@ -152,9 +159,11 @@ function MainCanvas({ children }: { children: React.ReactNode }) {
function useInternalLinkHandler() {
useEffect(() => {
const handler = (e: Event) => {
- const path = (e as CustomEvent).detail?.path;
- if (!path) return;
- routeContentLinkPath(path);
+ const detail = (
+ e as CustomEvent<{ path?: string; disposition?: LinkClickIntent }>
+ ).detail;
+ if (!detail?.path) return;
+ routeContentLinkPath(detail.path, detail.disposition);
};
window.addEventListener("multica:navigate", handler);
return () => window.removeEventListener("multica:navigate", handler);
@@ -208,6 +217,7 @@ function DesktopInboxBridge() {
export function DesktopShell() {
useInternalLinkHandler();
useNativeNavigationGestures();
+ useNavigationInputBindings();
// Reactive read of current workspace slug from the platform singleton.
// On first mount, slug is null until WorkspaceRouteLayout (inside the tab
diff --git a/apps/desktop/src/renderer/src/components/tab-bar.tsx b/apps/desktop/src/renderer/src/components/tab-bar.tsx
index dad859361d..3f95fbf3c4 100644
--- a/apps/desktop/src/renderer/src/components/tab-bar.tsx
+++ b/apps/desktop/src/renderer/src/components/tab-bar.tsx
@@ -256,6 +256,13 @@ function SortableTabItem({
{...attributes}
{...listeners}
onClick={handleClick}
+ // Browser convention: middle click closes the tab. Pinned (and sole)
+ // tabs suppress the close affordance, so middle click follows suit.
+ onAuxClick={(e) => {
+ if (e.button !== 1 || !showCloseButton) return;
+ e.preventDefault();
+ handleClose(e);
+ }}
aria-label={tab.pinned ? `${title} (pinned)` : title}
data-tab-active={isActive ? "true" : undefined}
data-tab-entering={isEntering ? "true" : undefined}
diff --git a/apps/desktop/src/renderer/src/hooks/use-navigation-input-bindings.test.tsx b/apps/desktop/src/renderer/src/hooks/use-navigation-input-bindings.test.tsx
new file mode 100644
index 0000000000..1cd8c2bbab
--- /dev/null
+++ b/apps/desktop/src/renderer/src/hooks/use-navigation-input-bindings.test.tsx
@@ -0,0 +1,108 @@
+// @vitest-environment jsdom
+import { beforeEach, describe, expect, it } from "vitest";
+import { render } from "@testing-library/react";
+import { useTabStore } from "@/stores/tab-store";
+import { useNavigationInputBindings } from "./use-tab-history";
+
+function Probe() {
+ useNavigationInputBindings();
+ return null;
+}
+
+/** Active tab sitting on entry index 1 of a two-entry history. */
+function seedHistory() {
+ useTabStore.setState({
+ activeWorkspaceSlug: "acme",
+ byWorkspace: {
+ acme: {
+ tabs: [
+ {
+ id: "t1",
+ url: "/acme/issues/abc",
+ resourceKey: "/acme/issues/abc",
+ title: "",
+ pinned: false,
+ history: {
+ stack: ["/acme/issues", "/acme/issues/abc"],
+ index: 1,
+ },
+ memento: { scroll: {} },
+ },
+ ],
+ activeTabId: "t1",
+ recentTabIds: ["t1"],
+ },
+ },
+ });
+}
+
+function activeHistoryIndex(): number {
+ return useTabStore.getState().byWorkspace.acme.tabs[0].history.index;
+}
+
+function keydown(init: KeyboardEventInit, target: EventTarget = window) {
+ const event = new KeyboardEvent("keydown", {
+ bubbles: true,
+ cancelable: true,
+ ...init,
+ });
+ target.dispatchEvent(event);
+ return event;
+}
+
+describe("useNavigationInputBindings", () => {
+ beforeEach(() => {
+ seedHistory();
+ });
+
+ it.each([
+ ["[", "Cmd+["],
+ ["ArrowLeft", "Cmd+Left"],
+ ])("goes back on %s", (key) => {
+ render(<Probe />);
+ const event = keydown({ key, metaKey: true });
+ expect(activeHistoryIndex()).toBe(0);
+ expect(event.defaultPrevented).toBe(true);
+ });
+
+ it.each([
+ ["]", "Cmd+]"],
+ ["ArrowRight", "Cmd+Right"],
+ ])("goes forward on %s", (key) => {
+ useTabStore.getState().goBack();
+ render(<Probe />);
+ keydown({ key, ctrlKey: true });
+ expect(activeHistoryIndex()).toBe(1);
+ });
+
+ it("leaves the chord to editable targets (caret navigation wins)", () => {
+ render(<Probe />);
+ const input = document.createElement("input");
+ document.body.appendChild(input);
+ const event = keydown({ key: "ArrowLeft", metaKey: true }, input);
+ expect(activeHistoryIndex()).toBe(1);
+ expect(event.defaultPrevented).toBe(false);
+ input.remove();
+ });
+
+ it("ignores the chord with extra modifiers held", () => {
+ render(<Probe />);
+ keydown({ key: "[", metaKey: true, shiftKey: true });
+ expect(activeHistoryIndex()).toBe(1);
+ });
+
+ it("navigates on mouse side buttons 3 (back) and 4 (forward)", () => {
+ render(<Probe />);
+ window.dispatchEvent(new MouseEvent("mouseup", { button: 3 }));
+ expect(activeHistoryIndex()).toBe(0);
+ window.dispatchEvent(new MouseEvent("mouseup", { button: 4 }));
+ expect(activeHistoryIndex()).toBe(1);
+ });
+
+ it("stops listening after unmount", () => {
+ const view = render(<Probe />);
+ view.unmount();
+ keydown({ key: "[", metaKey: true });
+ expect(activeHistoryIndex()).toBe(1);
+ });
+});
diff --git a/apps/desktop/src/renderer/src/hooks/use-tab-history.ts b/apps/desktop/src/renderer/src/hooks/use-tab-history.ts
index 90f6565d5b..866b02d8d1 100644
--- a/apps/desktop/src/renderer/src/hooks/use-tab-history.ts
+++ b/apps/desktop/src/renderer/src/hooks/use-tab-history.ts
@@ -1,4 +1,4 @@
-import { useCallback } from "react";
+import { useCallback, useEffect } from "react";
import { useTabStore, useActiveTabHistory } from "@/stores/tab-store";
/**
@@ -26,3 +26,48 @@ export function useTabHistory() {
return { canGoBack, canGoForward, goBack, goForward };
}
+
+function isEditableTarget(target: EventTarget | null): boolean {
+ if (!(target instanceof HTMLElement)) return false;
+ if (target.isContentEditable) return true;
+ const tag = target.tagName;
+ return tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT";
+}
+
+/**
+ * Keyboard and mouse back/forward for the active tab's history:
+ * Cmd/Ctrl+[ / ] and Cmd/Ctrl+←/→ (browser convention), plus mouse side
+ * buttons 3/4. The renderer's mouseup is the ONE cross-platform source for
+ * side buttons — the main process deliberately does not forward
+ * `app-command` (Windows/Linux emit both, which would double-navigate).
+ */
+export function useNavigationInputBindings() {
+ const { goBack, goForward } = useTabHistory();
+
+ useEffect(() => {
+ const onKeyDown = (e: KeyboardEvent) => {
+ const mod = e.metaKey || e.ctrlKey;
+ if (!mod || e.altKey || e.shiftKey) return;
+ const back = e.key === "[" || e.key === "ArrowLeft";
+ const forward = e.key === "]" || e.key === "ArrowRight";
+ if (!back && !forward) return;
+ // In editable contexts these chords belong to the text field:
+ // cmd+arrow moves the caret to the line edge, cmd+bracket indents.
+ if (isEditableTarget(e.target)) return;
+ e.preventDefault();
+ if (back) goBack();
+ else goForward();
+ };
+ const onMouseUp = (e: MouseEvent) => {
+ if (e.button !== 3 && e.button !== 4) return;
+ if (e.button === 3) goBack();
+ else goForward();
+ };
+ window.addEventListener("keydown", onKeyDown);
+ window.addEventListener("mouseup", onMouseUp);
+ return () => {
+ window.removeEventListener("keydown", onKeyDown);
+ window.removeEventListener("mouseup", onMouseUp);
+ };
+ }, [goBack, goForward]);
+}
diff --git a/apps/desktop/src/renderer/src/platform/issue-window-navigation.tsx b/apps/desktop/src/renderer/src/platform/issue-window-navigation.tsx
index 7b25c13315..380958e7e3 100644
--- a/apps/desktop/src/renderer/src/platform/issue-window-navigation.tsx
+++ b/apps/desktop/src/renderer/src/platform/issue-window-navigation.tsx
@@ -6,6 +6,7 @@ import {
} from "@multica/core/diagnostics";
import {
NavigationProvider,
+ type LinkClickIntent,
type NavigationAdapter,
} from "@multica/views/navigation";
import { parseIssueWindowPath } from "../../../shared/issue-window";
@@ -29,10 +30,23 @@ function useContentLinkHandler(
) {
useEffect(() => {
const handler = (e: Event) => {
- const path = (e as CustomEvent<{ path?: string }>).detail?.path;
+ const detail = (
+ e as CustomEvent<{ path?: string; disposition?: LinkClickIntent }>
+ ).detail;
+ const path = detail?.path;
if (!path) return;
const issuePath = parseIssueWindowPath(path);
if (issuePath) {
+ if (detail?.disposition && detail.disposition !== "push") {
+ // A modifier click asks for a separate surface; this window has no
+ // tabs, so its "new tab" is a detached issue window — the same
+ // thing the adapter's openInNewTab produces.
+ void window.desktopAPI.openIssueWindow({
+ path: issuePath.path,
+ title: "Issue",
+ });
+ return;
+ }
void navigate(issuePath.path);
return;
}
diff --git a/apps/desktop/src/renderer/src/platform/navigation.tsx b/apps/desktop/src/renderer/src/platform/navigation.tsx
index 48e7e6e4d9..8bf931140b 100644
--- a/apps/desktop/src/renderer/src/platform/navigation.tsx
+++ b/apps/desktop/src/renderer/src/platform/navigation.tsx
@@ -1,6 +1,7 @@
import { useMemo } from "react";
import {
NavigationProvider,
+ type LinkClickIntent,
type NavigationAdapter,
} from "@multica/views/navigation";
import { useAuthStore } from "@multica/core/auth";
@@ -96,27 +97,37 @@ function tryRouteToOtherWorkspace(path: string): boolean {
}
/**
- * 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.
+ * Execute a content link (the `multica:navigate` event fired by the shared
+ * editor/markdown link handler) with the disposition the click resolved to:
+ * a plain click navigates in place — the same thing a plain click means on
+ * every other internal link — and modifier clicks open a background or
+ * 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.
+ * A content link 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 {
+export function routeContentLinkPath(
+ path: string,
+ disposition: LinkClickIntent = "push",
+): void {
const store = useTabStore.getState();
const slug = extractWorkspaceSlug(path);
if (slug && slug !== store.activeWorkspaceSlug) {
store.switchWorkspace(slug, path);
return;
}
+ if (disposition === "push") {
+ const active = getActiveTab(store);
+ if (active && active.url === path) return;
+ if (tryRouteToPinnedNewTab(path)) return;
+ store.navigateActiveSession(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);
+ store.openTab(path, "", { activate: disposition === "foreground-tab" });
}
/**
@@ -210,10 +221,15 @@ export function DesktopNavigationProvider({
opts?: { activate?: boolean },
) => {
// Cross-workspace "open in new tab" switches workspace and opens
- // the path there (focus follows the user); same-workspace 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.
+ // the path there (focus follows the user), REGARDLESS of
+ // `opts.activate`. This is a deliberate product exception to the
+ // background-tab contract (decided with MUL-5860): a background tab
+ // added to a non-visible workspace's group would give the user zero
+ // feedback — "nothing happened" is worse than losing the background
+ // semantics for the rare cross-workspace link. Same-workspace
+ // 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 store = useTabStore.getState();
if (slug && slug !== store.activeWorkspaceSlug) {
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 d2b86db1a1..6b9cfe4840 100644
--- a/apps/desktop/src/renderer/src/stores/tab-store.test.ts
+++ b/apps/desktop/src/renderer/src/stores/tab-store.test.ts
@@ -194,6 +194,82 @@ describe("useTabStore actions", () => {
expect(s.byWorkspace.acme.tabs[0].url).toBe("/acme/issues");
});
+ describe("openTab insertion position (MUL-5860)", () => {
+ const urls = () =>
+ useTabStore.getState().byWorkspace.acme.tabs.map((t) => t.url);
+
+ it("inserts the new tab immediately right of the active tab, not at the end", () => {
+ const store = useTabStore.getState();
+ store.switchWorkspace("acme"); // A = /acme/issues, active
+ store.addTab("/acme/projects", "B");
+ store.addTab("/acme/skills", "C");
+ expect(urls()).toEqual(["/acme/issues", "/acme/projects", "/acme/skills"]);
+
+ store.openTab("/acme/issues/d", "D"); // background: A stays active
+ const s = useTabStore.getState();
+ expect(urls()).toEqual([
+ "/acme/issues",
+ "/acme/issues/d",
+ "/acme/projects",
+ "/acme/skills",
+ ]);
+ expect(getActiveTab(s)?.url).toBe("/acme/issues");
+ });
+
+ it("inserts right of a mid-strip opener", () => {
+ const store = useTabStore.getState();
+ store.switchWorkspace("acme"); // A
+ store.addTab("/acme/projects", "B");
+ store.addTab("/acme/skills", "C");
+ const bId = useTabStore.getState().byWorkspace.acme.tabs[1].id;
+ store.setActiveTab(bId);
+
+ store.openTab("/acme/issues/d", "D", { activate: true });
+ const s = useTabStore.getState();
+ expect(urls()).toEqual([
+ "/acme/issues",
+ "/acme/projects",
+ "/acme/issues/d",
+ "/acme/skills",
+ ]);
+ expect(getActiveTab(s)?.url).toBe("/acme/issues/d"); // foreground open
+ });
+
+ it("a pinned opener's 'right' is the start of the unpinned zone", () => {
+ const store = useTabStore.getState();
+ store.switchWorkspace("acme"); // A
+ store.addTab("/acme/projects", "B");
+ const aId = useTabStore.getState().byWorkspace.acme.tabs[0].id;
+ store.togglePin(aId); // [A(pinned, active), B]
+
+ store.openTab("/acme/issues/d", "D");
+ const s = useTabStore.getState();
+ expect(urls()).toEqual(["/acme/issues", "/acme/issues/d", "/acme/projects"]);
+ expect(s.byWorkspace.acme.tabs[0].pinned).toBe(true);
+ expect(s.byWorkspace.acme.tabs[1].pinned).toBe(false);
+ });
+
+ it("the explicit new-tab button (addTab) still appends", () => {
+ const store = useTabStore.getState();
+ store.switchWorkspace("acme"); // A active
+ store.addTab("/acme/projects", "B");
+ store.addTab("/acme/skills", "C"); // active is still A — must append anyway
+ expect(urls()).toEqual(["/acme/issues", "/acme/projects", "/acme/skills"]);
+ });
+
+ it("a dedupe hit focuses the existing tab without reordering", () => {
+ const store = useTabStore.getState();
+ store.switchWorkspace("acme"); // A active
+ store.addTab("/acme/projects", "B");
+ store.addTab("/acme/skills", "C");
+
+ store.openTab("/acme/skills", "C again"); // hits C, at the far end
+ const s = useTabStore.getState();
+ expect(urls()).toEqual(["/acme/issues", "/acme/projects", "/acme/skills"]);
+ expect(getActiveTab(s)?.url).toBe("/acme/skills");
+ });
+ });
+
it("closeTab on the last tab in a workspace reseeds the default tab", () => {
const store = useTabStore.getState();
store.switchWorkspace("acme");
diff --git a/apps/desktop/src/renderer/src/stores/tab-store.ts b/apps/desktop/src/renderer/src/stores/tab-store.ts
index 0654935f54..352e7cacd8 100644
--- a/apps/desktop/src/renderer/src/stores/tab-store.ts
+++ b/apps/desktop/src/renderer/src/stores/tab-store.ts
@@ -535,12 +535,29 @@ export const useTabStore = create<TabStore>()(
}
const tab = makeSession(clean, title);
+ // Insert immediately right of the opener (the active tab) — browser
+ // convention for cmd/middle/menu opens (MUL-5860) — rather than
+ // appending. The pinned-first invariant caps the left edge: a pinned
+ // opener's "right" is the start of the unpinned zone. The explicit
+ // "+" button appends instead (see addTab).
+ const activeIndex = group.tabs.findIndex(
+ (t) => t.id === group.activeTabId,
+ );
+ const insertAt =
+ activeIndex >= 0
+ ? Math.max(activeIndex + 1, pinnedBoundary(group.tabs))
+ : group.tabs.length;
+ const nextTabs = [
+ ...group.tabs.slice(0, insertAt),
+ tab,
+ ...group.tabs.slice(insertAt),
+ ];
set({
byWorkspace: {
...byWorkspace,
[activeWorkspaceSlug]: reconcileGroup(
group,
- [...group.tabs, tab],
+ nextTabs,
opts?.activate === true ? tab.id : group.activeTabId,
),
},
diff --git a/apps/web/components/web-providers.tsx b/apps/web/components/web-providers.tsx
index 898c4a722b..69dc7ffff5 100644
--- a/apps/web/components/web-providers.tsx
+++ b/apps/web/components/web-providers.tsx
@@ -7,6 +7,7 @@ import type { LocaleResources, SupportedLocale } from "@multica/core/i18n";
import { useWelcomeStore } from "@multica/core/onboarding";
import packageJson from "../package.json";
import { WebNavigationProvider } from "@/platform/navigation";
+import { WebScrollRestorationProvider } from "@/platform/scroll-restoration";
import {
setLoggedInCookie,
clearLoggedInCookie,
@@ -85,7 +86,9 @@ export function WebProviders({
resources={resources}
localeAdapter={localeAdapter}
>
- <WebNavigationProvider>{children}</WebNavigationProvider>
+ <WebNavigationProvider>
+ <WebScrollRestorationProvider>{children}</WebScrollRestorationProvider>
+ </WebNavigationProvider>
</CoreProvider>
);
}
diff --git a/apps/web/platform/navigation.tsx b/apps/web/platform/navigation.tsx
index b682b688d2..5b70a78d0f 100644
--- a/apps/web/platform/navigation.tsx
+++ b/apps/web/platform/navigation.tsx
@@ -11,15 +11,32 @@ import { canGoBackInApp } from "./in-app-history";
/**
* 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.
+ * destination. A plain click ("push") is a router push in place. A modifier
+ * click normally never reaches here on web — real anchors leave it to the
+ * browser — but the editor must intercept every click (contenteditable
+ * anchors don't navigate natively), and for those `window.open` is the
+ * closest the web can get: JS cannot open a background tab, so both tab
+ * dispositions land as a foreground browser tab.
*/
function useInternalLinkHandler(router: ReturnType<typeof useRouter>) {
useEffect(() => {
const handler = (e: Event) => {
- const path = (e as CustomEvent<{ path?: string }>).detail?.path;
+ const detail = (
+ e as CustomEvent<{ path?: string; disposition?: string }>
+ ).detail;
+ const path = detail?.path;
if (!path) return;
+ if (
+ detail?.disposition === "background-tab" ||
+ detail?.disposition === "foreground-tab"
+ ) {
+ window.open(
+ window.location.origin + path,
+ "_blank",
+ "noopener,noreferrer",
+ );
+ return;
+ }
router.push(path);
};
window.addEventListener("multica:navigate", handler);
diff --git a/apps/web/platform/scroll-restoration.test.tsx b/apps/web/platform/scroll-restoration.test.tsx
new file mode 100644
index 0000000000..c5e1b471dc
--- /dev/null
+++ b/apps/web/platform/scroll-restoration.test.tsx
@@ -0,0 +1,102 @@
+// @vitest-environment jsdom
+import { describe, expect, it } from "vitest";
+import { render, screen } from "@testing-library/react";
+import { useRestoredScrollOffset } from "@multica/views/platform";
+import { WebScrollRestorationProvider } from "./scroll-restoration";
+
+function ScrollProbe({ containerKey }: { containerKey: string }) {
+ const restored = useRestoredScrollOffset(containerKey);
+ return <output data-testid="restored">{restored ?? "none"}</output>;
+}
+
+/** Dispatch a real scroll event from a marked container element. */
+function scrollContainer(el: HTMLElement, top: number) {
+ Object.defineProperty(el, "scrollTop", { configurable: true, value: top });
+ Object.defineProperty(el, "scrollHeight", {
+ configurable: true,
+ value: 2000,
+ });
+ el.dispatchEvent(new Event("scroll", { bubbles: false }));
+}
+
+describe("WebScrollRestorationProvider", () => {
+ it("serves a captured container offset back for the same pathname", () => {
+ const view = render(
+ <WebScrollRestorationProvider>
+ <div data-tab-scroll-root="main" data-testid="container" />
+ <ScrollProbe containerKey="main" />
+ </WebScrollRestorationProvider>,
+ );
+
+ scrollContainer(screen.getByTestId("container"), 480);
+
+ // Remount — the same pull the view performs after navigating back.
+ view.rerender(
+ <WebScrollRestorationProvider>
+ <ScrollProbe containerKey="main" />
+ </WebScrollRestorationProvider>,
+ );
+ expect(screen.getByTestId("restored").textContent).toBe("480");
+ });
+
+ it("clears the saved offset when the container scrolls back to the top", () => {
+ const view = render(
+ <WebScrollRestorationProvider>
+ <div data-tab-scroll-root="cleared" data-testid="container" />
+ <ScrollProbe containerKey="cleared" />
+ </WebScrollRestorationProvider>,
+ );
+
+ scrollContainer(screen.getByTestId("container"), 480);
+ scrollContainer(screen.getByTestId("container"), 0);
+
+ view.rerender(
+ <WebScrollRestorationProvider>
+ <ScrollProbe containerKey="cleared" />
+ </WebScrollRestorationProvider>,
+ );
+ expect(screen.getByTestId("restored").textContent).toBe("none");
+ });
+
+ it("shields a just-served memento from the clamped scroll events a restore produces", () => {
+ const view = render(
+ <WebScrollRestorationProvider>
+ <div data-tab-scroll-root="shielded" data-testid="container" />
+ <ScrollProbe containerKey="shielded" />
+ </WebScrollRestorationProvider>,
+ );
+
+ scrollContainer(screen.getByTestId("container"), 480);
+
+ // Remount serves 480 (and arms the write shield) …
+ view.rerender(
+ <WebScrollRestorationProvider>
+ <div data-tab-scroll-root="shielded" data-testid="container" />
+ <ScrollProbe containerKey="shielded" />
+ </WebScrollRestorationProvider>,
+ );
+ expect(screen.getByTestId("restored").textContent).toBe("480");
+
+ // … so the browser clamping the restore assignment (content not yet at
+ // full height → scrollTop lands at 100) must not overwrite the memento.
+ scrollContainer(screen.getByTestId("container"), 100);
+ view.rerender(
+ <WebScrollRestorationProvider>
+ <ScrollProbe containerKey="shielded" />
+ </WebScrollRestorationProvider>,
+ );
+ expect(screen.getByTestId("restored").textContent).toBe("480");
+ });
+
+ it("ignores scrolls from unmarked elements", () => {
+ render(
+ <WebScrollRestorationProvider>
+ <div data-testid="plain" />
+ <ScrollProbe containerKey="plain" />
+ </WebScrollRestorationProvider>,
+ );
+
+ scrollContainer(screen.getByTestId("plain"), 480);
+ expect(screen.getByTestId("restored").textContent).toBe("none");
+ });
+});
diff --git a/apps/web/platform/scroll-restoration.tsx b/apps/web/platform/scroll-restoration.tsx
new file mode 100644
index 0000000000..e5ee57d7b4
--- /dev/null
+++ b/apps/web/platform/scroll-restoration.tsx
@@ -0,0 +1,103 @@
+"use client";
+
+import { useEffect, useMemo, type ReactNode } from "react";
+import {
+ ScrollRestorationProvider,
+ type ScrollRestorationAdapter,
+} from "@multica/views/platform";
+
+/**
+ * Web half of the MUL-4741 scroll-restoration protocol (desktop's half lives
+ * in the tab coordinator). The browser only restores the window's own scroll
+ * position on back/forward — the app's scrollable containers
+ * (`data-tab-scroll-root`) are inner divs and virtualized lists it knows
+ * nothing about, so without this, navigating back lands every list at the
+ * top.
+ *
+ * Capture is continuous rather than before-navigation: the App Router has no
+ * reliable "about to leave" hook, so a capture-phase scroll listener records
+ * each marked container's offset as the user scrolls, keyed by
+ * `pathname::containerKey`. Serving is the same pull-based adapter desktop
+ * uses — views read the offset at mount through `useRestoredScrollOffset` /
+ * `useRestoredScrollRef`.
+ *
+ * Keying by pathname (not by history entry) matches desktop's memento
+ * semantics: returning to a route — via back or via a fresh link — restores
+ * where you last were on it. The map is module state: per browser tab (web
+ * tabs are real tabs), reset on full reload where the browser's own
+ * restoration takes over.
+ */
+const savedOffsets = new Map<string, { top: number; height: number }>();
+
+/**
+ * Keys recently served through `adapter.get` are write-suppressed briefly:
+ * the restoring container assigns `scrollTop` at attach time, and if its
+ * content height isn't final yet the browser clamps the assignment and fires
+ * a scroll event — without suppression that clamped value (or a clamp to 0)
+ * would overwrite the very memento being restored. A real user scroll within
+ * the window is lost, which is the cheap side of the trade.
+ */
+const suppressedUntil = new Map<string, number>();
+const RESTORE_SUPPRESS_MS = 1000;
+
+function mementoKey(pathname: string, containerKey: string): string {
+ return `${pathname}::${containerKey}`;
+}
+
+export function WebScrollRestorationProvider({
+ children,
+}: {
+ children: ReactNode;
+}) {
+ useEffect(() => {
+ const onScroll = (e: Event) => {
+ const el = e.target;
+ if (!(el instanceof HTMLElement)) return;
+ const raw = el.getAttribute("data-tab-scroll-root");
+ if (raw === null) return;
+ const key = mementoKey(window.location.pathname, raw || "main");
+ const suppressed = suppressedUntil.get(key);
+ if (suppressed !== undefined) {
+ if (performance.now() < suppressed) return;
+ suppressedUntil.delete(key);
+ }
+ if (el.scrollTop <= 0) {
+ // Back at the top is the default state — a stale offset would
+ // otherwise resurrect on the next visit.
+ savedOffsets.delete(key);
+ } else {
+ savedOffsets.set(key, { top: el.scrollTop, height: el.scrollHeight });
+ }
+ };
+ // Scroll events don't bubble, but they do propagate on the capture
+ // phase, so one window listener observes every container.
+ window.addEventListener("scroll", onScroll, {
+ capture: true,
+ passive: true,
+ });
+ return () =>
+ window.removeEventListener("scroll", onScroll, { capture: true });
+ }, []);
+
+ const adapter = useMemo<ScrollRestorationAdapter>(
+ () => ({
+ get(containerKey) {
+ const key = mementoKey(window.location.pathname, containerKey);
+ const saved = savedOffsets.get(key);
+ if (saved) {
+ // The caller is about to restore this offset — shield the memento
+ // from the clamped scroll events the restore itself can produce.
+ suppressedUntil.set(key, performance.now() + RESTORE_SUPPRESS_MS);
+ }
+ return saved;
+ },
+ }),
+ [],
+ );
+
+ return (
+ <ScrollRestorationProvider adapter={adapter}>
+ {children}
+ </ScrollRestorationProvider>
+ );
+}
diff --git a/packages/core/issues/stores/index.ts b/packages/core/issues/stores/index.ts
index 0b35c11095..20fa75e673 100644
--- a/packages/core/issues/stores/index.ts
+++ b/packages/core/issues/stores/index.ts
@@ -27,7 +27,6 @@ export {
selectExpandedResolved,
} from "./resolved-expand-store";
export { useCommentComposerStore } from "./comment-composer-store";
-export { useIssueLinkStore } from "./issue-link-store";
export { useCommentDraftStore, type CommentDraftKey } from "./comment-draft-store";
export {
myIssuesViewStore,
@@ -68,6 +67,7 @@ export {
pruneIssueSurfaceViewStates,
getIssueSurfaceViewStateRegistrySnapshot,
} from "./surface-view-store";
+export { useSubIssuesCollapseStore } from "./sub-issues-collapse-store";
export {
useSubIssueDisplayStore,
SUB_ISSUE_ROW_PROPERTY_KEYS,
diff --git a/packages/core/issues/stores/issue-link-store.test.ts b/packages/core/issues/stores/issue-link-store.test.ts
deleted file mode 100644
index 188c3cc89b..0000000000
--- a/packages/core/issues/stores/issue-link-store.test.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-// @vitest-environment jsdom
-import { beforeAll, beforeEach, describe, expect, it } from "vitest";
-import { useIssueLinkStore } from "./issue-link-store";
-
-// Node 25 ships a partial `localStorage` shim under jsdom that's missing
-// `clear`/`removeItem`; replace it with a real in-memory Storage so persist
-// can round-trip values.
-beforeAll(() => {
- if (typeof globalThis.localStorage?.setItem !== "function") {
- const values = new Map<string, string>();
- const storage: Storage = {
- get length() { return values.size; },
- clear: () => values.clear(),
- getItem: (k) => values.get(k) ?? null,
- key: (i) => Array.from(values.keys())[i] ?? null,
- removeItem: (k) => { values.delete(k); },
- setItem: (k, v) => { values.set(k, v); },
- };
- Object.defineProperty(globalThis, "localStorage", { configurable: true, value: storage });
- Object.defineProperty(window, "localStorage", { configurable: true, value: storage });
- }
-});
-
-describe("issue link store", () => {
- beforeEach(() => {
- useIssueLinkStore.setState({ openInNewTab: true });
- });
-
- it("defaults to opening issue links in a new tab", () => {
- expect(useIssueLinkStore.getState().openInNewTab).toBe(true);
- });
-
- it("setOpenInNewTab switches to in-place navigation and back", () => {
- useIssueLinkStore.getState().setOpenInNewTab(false);
- expect(useIssueLinkStore.getState().openInNewTab).toBe(false);
-
- useIssueLinkStore.getState().setOpenInNewTab(true);
- expect(useIssueLinkStore.getState().openInNewTab).toBe(true);
- });
-});
diff --git a/packages/core/issues/stores/issue-link-store.ts b/packages/core/issues/stores/issue-link-store.ts
deleted file mode 100644
index 0f3f672330..0000000000
--- a/packages/core/issues/stores/issue-link-store.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import { create } from "zustand";
-import { createJSONStorage, persist } from "zustand/middleware";
-import { defaultStorage } from "../../platform/storage";
-
-/**
- * How issue mention links inside content (issue descriptions, comments,
- * chat markdown) open on plain click.
- *
- * `openInNewTab: true` (default) opens the linked issue in a new tab — a
- * browser tab on web, an app tab on desktop — so the reader keeps their
- * place in the issue they came from. `false` navigates in place. It's a
- * personal reading-ergonomics preference (like theme), so it persists
- * globally via `defaultStorage` rather than per-workspace storage.
- */
-interface IssueLinkStore {
- openInNewTab: boolean;
- setOpenInNewTab: (open: boolean) => void;
-}
-
-export const useIssueLinkStore = create<IssueLinkStore>()(
- persist(
- (set) => ({
- openInNewTab: true,
- setOpenInNewTab: (open) => set({ openInNewTab: open }),
- }),
- {
- name: "multica_issue_link",
- storage: createJSONStorage(() => defaultStorage),
- },
- ),
-);
diff --git a/packages/core/issues/stores/sub-issues-collapse-store.ts b/packages/core/issues/stores/sub-issues-collapse-store.ts
new file mode 100644
index 0000000000..cdd5d40256
--- /dev/null
+++ b/packages/core/issues/stores/sub-issues-collapse-store.ts
@@ -0,0 +1,29 @@
+import { create } from "zustand";
+
+/**
+ * Whether the sub-issues section of an issue detail page is collapsed, keyed
+ * by issue ID. Only collapsed ids are stored — expanded is the default.
+ *
+ * Deliberately NOT persisted (same contract as resolved-expand-store): the
+ * state lives in a store rather than issue-detail component state so leaving
+ * an issue and navigating back finds the section as it was left (MUL-4741
+ * state restoration on back), while a reload returns to the default.
+ */
+interface SubIssuesCollapseStore {
+ collapsedIssueIds: ReadonlySet<string>;
+ setCollapsed: (issueId: string, collapsed: boolean) => void;
+}
+
+export const useSubIssuesCollapseStore = create<SubIssuesCollapseStore>()(
+ (set) => ({
+ collapsedIssueIds: new Set<string>(),
+ setCollapsed: (issueId, collapsed) =>
+ set((s) => {
+ if (s.collapsedIssueIds.has(issueId) === collapsed) return s;
+ const next = new Set(s.collapsedIssueIds);
+ if (collapsed) next.add(issueId);
+ else next.delete(issueId);
+ return { collapsedIssueIds: next };
+ }),
+ }),
+);
diff --git a/packages/ui/components/ui/data-table.tsx b/packages/ui/components/ui/data-table.tsx
index 5c8b8a7cb7..1c8c7a3fae 100644
--- a/packages/ui/components/ui/data-table.tsx
+++ b/packages/ui/components/ui/data-table.tsx
@@ -44,8 +44,10 @@ interface DataTableProps<TData> extends React.ComponentProps<"div"> {
// descendant — buttons / dropdowns inside cells should call
// event.stopPropagation in their own handlers). Used to navigate to
// a detail page on row click without nesting an <a> around <tr>,
- // which is invalid HTML.
- onRowClick?: (row: Row<TData>) => void;
+ // which is invalid HTML. Receives the mouse event so callers can honor
+ // modifier keys; middle clicks arrive through the same callback (the
+ // caller reads `event.button`).
+ onRowClick?: (row: Row<TData>, event: React.MouseEvent) => void;
// Optional escape hatch for semantic rows such as collapsible group
// headers. Return null/undefined to use the standard data row renderer.
renderRow?: (row: Row<TData>) => React.ReactNode;
@@ -572,7 +574,7 @@ interface DataTableBodyProps<TData> {
table: TanstackTable<TData>;
rows: Row<TData>[];
emptyMessage: React.ReactNode;
- onRowClick?: (row: Row<TData>) => void;
+ onRowClick?: (row: Row<TData>, event: React.MouseEvent) => void;
renderRow?: (row: Row<TData>) => React.ReactNode;
hasExplicitSize: (columnId: string) => boolean;
// The virtualizer's own measuring ref; rows report their height through it.
@@ -620,7 +622,25 @@ function DataTableBody<TData>({
key={row.id}
{...measured}
data-state={row.getIsSelected() && "selected"}
- onClick={onRowClick ? () => onRowClick(row) : undefined}
+ onClick={
+ onRowClick
+ ? (e) => {
+ if (e.defaultPrevented) return;
+ onRowClick(row, e);
+ }
+ : undefined
+ }
+ // Middle click never produces a `click` event; forward it through the
+ // same callback (button === 1 only — button 2 is the context menu).
+ onAuxClick={
+ onRowClick
+ ? (e) => {
+ if (e.defaultPrevented || e.button !== 1) return;
+ e.preventDefault();
+ onRowClick(row, e);
+ }
+ : undefined
+ }
// `group` lets pinned cells track row hover via group-hover (their bg
// is in className, not on the row, so they stay opaque enough to cover
// content scrolling beneath them).
diff --git a/packages/views/agents/components/agent-detail-page.test.tsx b/packages/views/agents/components/agent-detail-page.test.tsx
index 3556a1c99e..5857c556b7 100644
--- a/packages/views/agents/components/agent-detail-page.test.tsx
+++ b/packages/views/agents/components/agent-detail-page.test.tsx
@@ -194,8 +194,11 @@ describe("AgentDetailPage DM button", () => {
// would get a wrong "no access" toast. Undetermined must disable, not deny.
membersPendingRef.current = true;
const { push } = renderPage();
+ // The control is an anchor now, so "disabled" is expressed the only way a
+ // link can express it: aria-disabled plus removal from the tab order.
const dm = await screen.findByRole("button", { name: "DM" });
- expect(dm).toBeDisabled();
+ expect(dm).toHaveAttribute("aria-disabled", "true");
+ expect(dm).toHaveAttribute("tabindex", "-1");
fireEvent.click(dm);
expect(mockToastError).not.toHaveBeenCalled();
expect(push).not.toHaveBeenCalled();
diff --git a/packages/views/agents/components/agent-detail-page.tsx b/packages/views/agents/components/agent-detail-page.tsx
index 290a99fc8b..7bcd446cf1 100644
--- a/packages/views/agents/components/agent-detail-page.tsx
+++ b/packages/views/agents/components/agent-detail-page.tsx
@@ -210,9 +210,9 @@ export function AgentDetailPage({ agentId }: AgentDetailPageProps) {
</p>
</div>
<Button
- type="button"
size="sm"
- onClick={() => navigation.push(paths.agents())}
+ render={<AppLink href={paths.agents()} />}
+ nativeButton={false}
>
{t(($) => $.detail.back_to_agents_full)}
</Button>
@@ -246,9 +246,9 @@ export function AgentDetailPage({ agentId }: AgentDetailPageProps) {
{t(($) => $.detail.try_again)}
</Button>
<Button
- type="button"
size="sm"
- onClick={() => navigation.push(paths.agents())}
+ render={<AppLink href={paths.agents()} />}
+ nativeButton={false}
>
{t(($) => $.detail.back_to_agents_full)}
</Button>
@@ -272,17 +272,23 @@ export function AgentDetailPage({ agentId }: AgentDetailPageProps) {
// click explains itself instead of the affordance silently missing. While
// membership is still resolving the decision is undetermined, so the button
// is disabled rather than toasting a false "no access" at a real member.
- const handleDm = () => {
- if (permissionsLoading) return;
+ //
+ // The control is a real link, so a failed gate has to cancel the navigation
+ // AppLink would otherwise perform — preventDefault is that cancel.
+ const handleDm = (e: React.MouseEvent<HTMLAnchorElement>) => {
+ if (permissionsLoading) {
+ e.preventDefault();
+ return;
+ }
if (!canAssign.allowed) {
+ e.preventDefault();
toast.error(t(($) => $.detail.dm_no_permission_toast));
return;
}
if (!runtimeBound) {
+ e.preventDefault();
toast.error(t(($) => $.detail.runtime_required_toast));
- return;
}
- navigation.push(`${paths.chat()}?agent=${agent.id}`);
};
const handleAssign = () => {
if (!runtimeBound) {
@@ -304,6 +310,7 @@ export function AgentDetailPage({ agentId }: AgentDetailPageProps) {
canAssign={canAssign.allowed}
canArchive={canEdit.allowed}
dmPending={permissionsLoading}
+ dmHref={`${paths.chat()}?agent=${agent.id}`}
onDm={handleDm}
onAssign={handleAssign}
onArchive={
@@ -428,6 +435,7 @@ function DetailHeader({
canAssign,
canArchive,
dmPending,
+ dmHref,
onDm,
onAssign,
onArchive,
@@ -439,7 +447,10 @@ function DetailHeader({
canAssign: boolean;
canArchive: boolean;
dmPending: boolean;
- onDm: () => void;
+ dmHref: string;
+ /** Runs before the link navigates; calls preventDefault when a gate denies
+ * the chat, which is what stops AppLink from pushing. */
+ onDm: (e: React.MouseEvent<HTMLAnchorElement>) => void;
onAssign: () => void;
/** Absent for Multica's built-in agents, which the server refuses to
* archive — the menu hides the action rather than offering a failure. */
@@ -508,11 +519,15 @@ function DetailHeader({
<div className="flex shrink-0 items-center gap-2 self-end lg:self-start">
{!isArchived && (
<Button
- type="button"
variant="outline"
size="sm"
disabled={dmPending}
- onClick={onDm}
+ // An anchor never matches `:disabled`, so the base variant's
+ // `disabled:` rules never fire here — Base UI's data-disabled
+ // is what carries the dimmed, inert look.
+ className="data-disabled:pointer-events-none data-disabled:opacity-50"
+ render={<AppLink href={dmHref} onClick={onDm} />}
+ nativeButton={false}
>
<MessageSquare className="h-4 w-4" aria-hidden="true" />
{t(($) => $.detail.dm)}
diff --git a/packages/views/agents/components/agent-row-actions.tsx b/packages/views/agents/components/agent-row-actions.tsx
index e8ada5ee0a..ece0476cdb 100644
--- a/packages/views/agents/components/agent-row-actions.tsx
+++ b/packages/views/agents/components/agent-row-actions.tsx
@@ -4,6 +4,7 @@ import { useState } from "react";
import {
AlertCircle,
Copy,
+ ExternalLink,
MoreHorizontal,
RotateCcw,
Square,
@@ -15,6 +16,7 @@ import type { Agent } from "@multica/core/types";
import type { AgentPresenceDetail } from "@multica/core/agents";
import { api } from "@multica/core/api";
import { useWorkspaceId } from "@multica/core/hooks";
+import { useWorkspacePaths } from "@multica/core/paths";
import { workspaceKeys } from "@multica/core/workspace/queries";
import {
AlertDialog,
@@ -34,6 +36,7 @@ import {
DropdownMenuTrigger,
} from "@multica/ui/components/ui/dropdown-menu";
import { useT } from "../../i18n";
+import { AppLink, useIntentNavigate } from "../../navigation";
interface AgentRowActionsProps {
agent: Agent;
@@ -43,17 +46,17 @@ interface AgentRowActionsProps {
// the server is still the source of truth, this only hides UI for ops
// the user can't perform.
canManage: boolean;
- // Called when the user picks "Duplicate" — the page opens a Create
- // dialog pre-populated with this agent's config as a template.
- onDuplicate: (agent: Agent) => void;
+ // Destination of "Duplicate" — the manual create form, pre-populated with
+ // this agent's config as a template. A href rather than a callback so the
+ // menu item is a real link (modifier-click opens it in a new tab).
+ duplicateHref: string;
}
/**
* Per-row dropdown menu for the agents list. The set of actions is derived
* from (a) the agent's lifecycle state (active vs archived) and (b) the
- * caller's permission level. If no actions apply, the trigger is omitted so
- * the row renders an empty cell (column width still preserved by the parent
- * ListGridCell).
+ * caller's permission level. "Open in new tab" applies to every row, so the
+ * trigger always renders.
*
* The row is a plain `<div>` whose whole-row navigation is a mouse `onClick`
* (see `useRowLink`), not an ancestor `<a>`. The host cell stops click
@@ -64,9 +67,12 @@ export function AgentRowActions({
agent,
presence,
canManage,
- onDuplicate,
+ duplicateHref,
}: AgentRowActionsProps) {
const { t } = useT("agents");
+ const { t: tCommon } = useT("common");
+ const paths = useWorkspacePaths();
+ const intentNavigate = useIntentNavigate();
const wsId = useWorkspaceId();
const qc = useQueryClient();
@@ -90,8 +96,6 @@ export function AgentRowActions({
const showArchive = canManage && !isArchived && !isSystemAgent;
const showRestore = canManage && isArchived;
- const hasAnyAction = showStop || showDuplicate || showArchive || showRestore;
-
const invalidateAgents = () => {
qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });
};
@@ -130,10 +134,6 @@ export function AgentRowActions({
}
};
- if (!hasAnyAction) {
- return null;
- }
-
return (
<>
<DropdownMenu>
@@ -149,6 +149,23 @@ export function AgentRowActions({
}
/>
<DropdownMenuContent align="end" className="w-auto">
+ {/* Same shape as every other entity row menu: an explicit CTA is a
+ foreground open executed through the adapter (an anchor-based
+ item would depend on native activation surviving the menu
+ closing under it). */}
+ <DropdownMenuItem
+ onClick={() =>
+ intentNavigate(
+ paths.agentDetail(agent.id),
+ "foreground-tab",
+ agent.name,
+ )
+ }
+ >
+ <ExternalLink className="h-3.5 w-3.5" />
+ {tCommon(($) => $.navigation.open_in_new_tab)}
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
{showStop && (
<DropdownMenuItem
onClick={() => setConfirmCancel(true)}
@@ -158,7 +175,7 @@ export function AgentRowActions({
</DropdownMenuItem>
)}
{showDuplicate && (
- <DropdownMenuItem onClick={() => onDuplicate(agent)}>
+ <DropdownMenuItem render={<AppLink href={duplicateHref} />}>
<Copy className="h-3.5 w-3.5" />
{t(($) => $.row_actions.duplicate)}
</DropdownMenuItem>
diff --git a/packages/views/agents/components/agents-page.tsx b/packages/views/agents/components/agents-page.tsx
index d203f5915d..8377efc0ac 100644
--- a/packages/views/agents/components/agents-page.tsx
+++ b/packages/views/agents/components/agents-page.tsx
@@ -971,11 +971,11 @@ export function AgentsPage(_props: AgentsPageProps = {}) {
// Straight to the manual form: a duplicate already has every field decided,
// so the method chooser would be a step with nothing to choose.
- const handleDuplicate = useCallback((agent: Agent) => {
- navigation.push(
+ const duplicateHref = useCallback(
+ (agent: Agent) =>
`${paths.newAgentManual()}?duplicate=${encodeURIComponent(agent.id)}`,
- );
- }, [navigation, paths]);
+ [paths],
+ );
const selectedRows = rows.filter((row) => selectedIds.has(row.agent.id));
const allSelected = rows.length > 0 && selectedRows.length === rows.length;
@@ -1106,7 +1106,7 @@ export function AgentsPage(_props: AgentsPageProps = {}) {
className={`h-16 cursor-pointer ${
selectedIds.has(row.agent.id) ? "bg-accent/30" : ""
}`}
- {...rowLink(paths.agentDetail(row.agent.id))}
+ {...rowLink(paths.agentDetail(row.agent.id), row.agent.name)}
>
<CheckboxCell
checked={selectedIds.has(row.agent.id)}
@@ -1172,7 +1172,7 @@ export function AgentsPage(_props: AgentsPageProps = {}) {
agent={row.agent}
presence={row.presence}
canManage={row.canManage}
- onDuplicate={handleDuplicate}
+ duplicateHref={duplicateHref(row.agent)}
/>
</span>
</ListGridCell>
diff --git a/packages/views/agents/create/ai-builder-session-page.tsx b/packages/views/agents/create/ai-builder-session-page.tsx
index fc98c067b0..09e5a96e98 100644
--- a/packages/views/agents/create/ai-builder-session-page.tsx
+++ b/packages/views/agents/create/ai-builder-session-page.tsx
@@ -5,7 +5,7 @@ import { useQuery } from "@tanstack/react-query";
import { agentBuilderSessionListOptions } from "@multica/core/agents";
import { useWorkspaceId } from "@multica/core/hooks";
import { useWorkspacePaths } from "@multica/core/paths";
-import { useNavigation } from "../../navigation";
+import { useBackOrReplace, useNavigation } from "../../navigation";
import { useT } from "../../i18n";
import { BuilderWorkspace } from "./builder-workspace";
import { AgentCreateChip, AgentCreateShell } from "./create-shell";
@@ -24,6 +24,7 @@ export function AiBuilderSessionPage({ sessionId }: { sessionId: string }) {
const wsId = useWorkspaceId();
const paths = useWorkspacePaths();
const navigation = useNavigation();
+ const backOrReplace = useBackOrReplace();
const squadId = navigation.searchParams.get("squad");
// The runtime this conversation was just started on. It cannot be read back
// for the first turn — a conversation joins the list only once it has a
@@ -55,7 +56,7 @@ export function AiBuilderSessionPage({ sessionId }: { sessionId: string }) {
: t(($) => $.creation_studio.title)
}
step={t(($) => $.creation_studio.step_ai)}
- onBack={() => navigation.push(paths.newAgent())}
+ onBack={() => backOrReplace(paths.newAgent())}
chips={
<>
<AgentCreateChip>
diff --git a/packages/views/agents/create/ai-create-agent-page.tsx b/packages/views/agents/create/ai-create-agent-page.tsx
index 6e9158ae12..6108f79c84 100644
--- a/packages/views/agents/create/ai-create-agent-page.tsx
+++ b/packages/views/agents/create/ai-create-agent-page.tsx
@@ -7,7 +7,7 @@ import { useWorkspaceId } from "@multica/core/hooks";
import { useWorkspacePaths } from "@multica/core/paths";
import { runtimeDisplayLabel } from "@multica/core/runtimes";
import type { RuntimeDevice } from "@multica/core/types";
-import { useNavigation } from "../../navigation";
+import { useBackOrReplace, useNavigation } from "../../navigation";
import { useT } from "../../i18n";
import { BuilderSetupPanel } from "./builder-setup-panel";
import { AgentCreateChip, AgentCreateShell } from "./create-shell";
@@ -33,6 +33,7 @@ export function AiCreateAgentPage() {
const wsId = useWorkspaceId();
const paths = useWorkspacePaths();
const navigation = useNavigation();
+ const backOrReplace = useBackOrReplace();
const squadId = navigation.searchParams.get("squad");
const builderSessions = useQuery(agentBuilderSessionListOptions(wsId));
@@ -65,7 +66,7 @@ export function AiCreateAgentPage() {
: t(($) => $.creation_studio.title)
}
step={t(($) => $.creation_studio.step_ai)}
- onBack={() => navigation.push(paths.newAgent())}
+ onBack={() => backOrReplace(paths.newAgent())}
chips={
<>
<AgentCreateChip>
diff --git a/packages/views/agents/create/builder-conversation.tsx b/packages/views/agents/create/builder-conversation.tsx
index 2a70aea5c4..38386b3888 100644
--- a/packages/views/agents/create/builder-conversation.tsx
+++ b/packages/views/agents/create/builder-conversation.tsx
@@ -23,6 +23,7 @@ import {
ChatMessageSkeleton,
} from "../../chat/components/chat-message-list";
import { useT } from "../../i18n";
+import { AppLink } from "../../navigation";
import { ModelDropdown } from "../components/model-dropdown";
import { RuntimePicker } from "../components/runtime-picker";
@@ -42,7 +43,7 @@ export function BuilderSetup({
starting,
error,
onStart,
- onConnectRuntime,
+ connectRuntimeHref,
banner,
}: {
draft: AgentDraft;
@@ -55,7 +56,7 @@ export function BuilderSetup({
starting: boolean;
error: string | null;
onStart: () => void;
- onConnectRuntime: () => void;
+ connectRuntimeHref: string;
/** Rendered above the card: the way back to an unfinished conversation, so
* this screen cannot silently start yet another one. */
banner?: ReactNode;
@@ -116,7 +117,10 @@ export function BuilderSetup({
{t(($) => $.creation_studio.builder.start)}
</Button>
) : (
- <Button onClick={onConnectRuntime}>
+ <Button
+ render={<AppLink href={connectRuntimeHref} />}
+ nativeButton={false}
+ >
{t(($) => $.creation_studio.builder.connect_runtime)}
</Button>
)}
diff --git a/packages/views/agents/create/builder-setup-panel.tsx b/packages/views/agents/create/builder-setup-panel.tsx
index b7cb70ea77..2d0524ec49 100644
--- a/packages/views/agents/create/builder-setup-panel.tsx
+++ b/packages/views/agents/create/builder-setup-panel.tsx
@@ -6,7 +6,6 @@ import type {
AgentBuilderSessionSummary,
RuntimeDevice,
} from "@multica/core/types";
-import { useNavigation } from "../../navigation";
import { BuilderSetup } from "./builder-conversation";
import { UnfinishedDraftsBanner } from "./unfinished-drafts";
import { useBuilderSession } from "./use-builder-session";
@@ -35,7 +34,6 @@ export function BuilderSetupPanel({
onRuntimeLabel: (runtime: RuntimeDevice | null) => void;
}) {
const paths = useWorkspacePaths();
- const navigation = useNavigation();
const form = useCreateAgentForm();
const { draft, setDraft, selectedRuntime } = form;
@@ -71,7 +69,7 @@ export function BuilderSetupPanel({
starting={builder.starting}
error={builder.error}
onStart={() => void startConversation()}
- onConnectRuntime={() => navigation.push(paths.runtimes())}
+ connectRuntimeHref={paths.runtimes()}
/>
);
}
diff --git a/packages/views/agents/create/choose-create-method-page.tsx b/packages/views/agents/create/choose-create-method-page.tsx
index 1757bb4f1e..15dc2183b0 100644
--- a/packages/views/agents/create/choose-create-method-page.tsx
+++ b/packages/views/agents/create/choose-create-method-page.tsx
@@ -3,7 +3,7 @@
import { ChevronRight, FileText, MessageSquare } from "lucide-react";
import { useWorkspacePaths } from "@multica/core/paths";
import { cn } from "@multica/ui/lib/utils";
-import { useNavigation } from "../../navigation";
+import { AppLink, useBackOrReplace, useNavigation } from "../../navigation";
import { useT } from "../../i18n";
import { AgentCreateShell } from "./create-shell";
import { withSquadParam } from "./squad-param";
@@ -17,6 +17,7 @@ export function ChooseCreateMethodPage() {
const { t } = useT("agents");
const paths = useWorkspacePaths();
const navigation = useNavigation();
+ const backOrReplace = useBackOrReplace();
const squadId = navigation.searchParams.get("squad");
return (
@@ -27,16 +28,12 @@ export function ChooseCreateMethodPage() {
: t(($) => $.creation_studio.title)
}
step={t(($) => $.creation_studio.step_choose)}
- onBack={() => navigation.push(paths.agents())}
+ onBack={() => backOrReplace(paths.agents())}
>
<main className="flex min-h-0 flex-1 flex-col overflow-y-auto px-5 py-10">
<CreateMethodChooser
- onBlank={() =>
- navigation.push(withSquadParam(paths.newAgentManual(), squadId))
- }
- onAI={() =>
- navigation.push(withSquadParam(paths.newAgentAi(), squadId))
- }
+ blankHref={withSquadParam(paths.newAgentManual(), squadId)}
+ aiHref={withSquadParam(paths.newAgentAi(), squadId)}
/>
</main>
</AgentCreateShell>
@@ -44,11 +41,11 @@ export function ChooseCreateMethodPage() {
}
export function CreateMethodChooser({
- onBlank,
- onAI,
+ blankHref,
+ aiHref,
}: {
- onBlank: () => void;
- onAI: () => void;
+ blankHref: string;
+ aiHref: string;
}) {
const { t } = useT("agents");
const modes = [
@@ -56,13 +53,13 @@ export function CreateMethodChooser({
icon: FileText,
title: t(($) => $.creation_studio.modes.blank.title),
description: t(($) => $.creation_studio.modes.blank.description),
- action: onBlank,
+ href: blankHref,
},
{
icon: MessageSquare,
title: t(($) => $.creation_studio.modes.ai.title),
description: t(($) => $.creation_studio.modes.ai.description),
- action: onAI,
+ href: aiHref,
recommended: true,
},
];
@@ -81,11 +78,10 @@ export function CreateMethodChooser({
</div>
<div className="mx-auto mt-9 grid max-w-3xl gap-4 md:grid-cols-2">
{modes.map(
- ({ icon: Icon, title, description, action, recommended }) => (
- <button
+ ({ icon: Icon, title, description, href, recommended }) => (
+ <AppLink
key={title}
- type="button"
- onClick={action}
+ href={href}
className={cn(
"group relative flex min-h-56 flex-col items-start rounded-xl border bg-card p-5 text-left",
"transition-[border-color,background-color,transform] hover:-translate-y-0.5 hover:border-primary/40 hover:bg-accent/30",
@@ -112,7 +108,7 @@ export function CreateMethodChooser({
aria-hidden="true"
/>
</span>
- </button>
+ </AppLink>
),
)}
</div>
diff --git a/packages/views/agents/create/create-agent-ui.test.ts b/packages/views/agents/create/create-agent-ui.test.ts
index b622d3e4d9..5f3acd5c6c 100644
--- a/packages/views/agents/create/create-agent-ui.test.ts
+++ b/packages/views/agents/create/create-agent-ui.test.ts
@@ -7,6 +7,16 @@ import { CreateMethodChooser } from "./choose-create-method-page";
import { CreateAgentFooter } from "./create-agent-footer";
import { draftPreview } from "./unfinished-drafts";
import { classifyAgentCreateError } from "./use-create-agent-submit";
+import { NavigationProvider, type NavigationAdapter } from "../../navigation";
+
+const TEST_NAVIGATION: NavigationAdapter = {
+ push: vi.fn(),
+ replace: vi.fn(),
+ back: vi.fn(),
+ pathname: "/acme/agents/new",
+ searchParams: new URLSearchParams(),
+ getShareableUrl: (path: string) => path,
+};
vi.mock("../../i18n", () => ({
useT: () => ({
@@ -194,13 +204,23 @@ describe("Unfinished draft preview", () => {
describe("Agent creation method chooser", () => {
it("always offers AI-assisted creation", () => {
render(
- createElement(CreateMethodChooser, {
- onBlank: vi.fn(),
- onAI: vi.fn(),
+ createElement(NavigationProvider, {
+ value: TEST_NAVIGATION,
+ children: createElement(CreateMethodChooser, {
+ blankHref: "/acme/agents/new/manual",
+ aiHref: "/acme/agents/new/ai",
+ }),
}),
);
expect(screen.getByText("Start blank")).toBeInTheDocument();
expect(screen.getByText("Build with AI")).toBeInTheDocument();
+ expect(
+ screen.getByText("Start blank").closest("a"),
+ ).toHaveAttribute("href", "/acme/agents/new/manual");
+ expect(screen.getByText("Build with AI").closest("a")).toHaveAttribute(
+ "href",
+ "/acme/agents/new/ai",
+ );
});
});
diff --git a/packages/views/agents/create/manual-create-agent-page.tsx b/packages/views/agents/create/manual-create-agent-page.tsx
index ced59fa9f6..37067ecf0c 100644
--- a/packages/views/agents/create/manual-create-agent-page.tsx
+++ b/packages/views/agents/create/manual-create-agent-page.tsx
@@ -6,7 +6,7 @@ import { useWorkspaceId } from "@multica/core/hooks";
import { useWorkspacePaths } from "@multica/core/paths";
import { runtimeDisplayLabel } from "@multica/core/runtimes";
import { agentListOptions } from "@multica/core/workspace/queries";
-import { useNavigation } from "../../navigation";
+import { useBackOrReplace, useNavigation } from "../../navigation";
import { useT } from "../../i18n";
import { AgentConfigurationPanel } from "./agent-configuration-panel";
import { CreateAgentFooter } from "./create-agent-footer";
@@ -31,6 +31,7 @@ export function ManualCreateAgentPage() {
const wsId = useWorkspaceId();
const paths = useWorkspacePaths();
const navigation = useNavigation();
+ const backOrReplace = useBackOrReplace();
const duplicateId = navigation.searchParams.get("duplicate");
const squadId = navigation.searchParams.get("squad");
@@ -106,7 +107,7 @@ export function ManualCreateAgentPage() {
// A duplicate arrives from the agents list, not from the chooser, so it
// returns to where it came from instead of offering a method to pick.
onBack={() =>
- navigation.push(duplicateId ? paths.agents() : paths.newAgent())
+ backOrReplace(duplicateId ? paths.agents() : paths.newAgent())
}
chips={
<>
diff --git a/packages/views/autopilots/components/autopilot-list-actions.tsx b/packages/views/autopilots/components/autopilot-list-actions.tsx
index 914e920b3a..c41fbe1f63 100644
--- a/packages/views/autopilots/components/autopilot-list-actions.tsx
+++ b/packages/views/autopilots/components/autopilot-list-actions.tsx
@@ -2,6 +2,7 @@
import { useState } from "react";
import {
+ ExternalLink,
Loader2,
MoreHorizontal,
Pause,
@@ -15,6 +16,7 @@ import {
useDeleteAutopilot,
useUpdateAutopilot,
} from "@multica/core/autopilots";
+import { useWorkspacePaths } from "@multica/core/paths";
import { Button } from "@multica/ui/components/ui/button";
import {
Dialog,
@@ -32,6 +34,7 @@ import {
DropdownMenuTrigger,
} from "@multica/ui/components/ui/dropdown-menu";
import { useT } from "../../i18n";
+import { useIntentNavigate } from "../../navigation";
// ---------------------------------------------------------------------------
// Delete dialog — single row (kebab) and batch share one implementation.
@@ -143,12 +146,17 @@ function useSetStatus() {
export function AutopilotRowActions({ row }: { row: Autopilot }) {
const { t } = useT("autopilots");
+ const { t: tCommon } = useT("common");
+ const wsPaths = useWorkspacePaths();
+ const intentNavigate = useIntentNavigate();
const [deleteOpen, setDeleteOpen] = useState(false);
const setStatus = useSetStatus();
- // The kebab only holds write actions (pause/resume/delete). Hide it entirely
- // for members without write access; an absent can_write (older server) keeps
- // the menu visible and lets the backend remain the gate.
+ // Apart from the navigation entry the kebab only holds write actions
+ // (pause/resume/delete), so hide it entirely for members without write
+ // access — they still reach a new tab through a modified row click. An
+ // absent can_write (older server) keeps the menu visible and lets the
+ // backend remain the gate.
if (row.can_write === false) return null;
return (
@@ -169,6 +177,19 @@ export function AutopilotRowActions({ row }: { row: Autopilot }) {
}
/>
<DropdownMenuContent align="end" className="w-48">
+ <DropdownMenuItem
+ onClick={() =>
+ intentNavigate(
+ wsPaths.autopilotDetail(row.id),
+ "foreground-tab",
+ row.title,
+ )
+ }
+ >
+ <ExternalLink className="size-3.5" />
+ {tCommon(($) => $.navigation.open_in_new_tab)}
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
{row.status === "active" && (
<DropdownMenuItem onClick={() => setStatus([row], "paused")}>
<Pause className="size-3.5" />
diff --git a/packages/views/autopilots/components/autopilots-page.tsx b/packages/views/autopilots/components/autopilots-page.tsx
index 93c603806a..c97598a014 100644
--- a/packages/views/autopilots/components/autopilots-page.tsx
+++ b/packages/views/autopilots/components/autopilots-page.tsx
@@ -898,7 +898,7 @@ export function AutopilotsPage() {
className={`cursor-pointer ${
selectedIds.has(autopilot.id) ? "bg-accent/30" : ""
}`}
- {...rowLink(wsPaths.autopilotDetail(autopilot.id))}
+ {...rowLink(wsPaths.autopilotDetail(autopilot.id), autopilot.title)}
>
<CheckboxCell
checked={selectedIds.has(autopilot.id)}
diff --git a/packages/views/chat/components/chat-session-header.tsx b/packages/views/chat/components/chat-session-header.tsx
index d4be8d87ff..6eadfde1a0 100644
--- a/packages/views/chat/components/chat-session-header.tsx
+++ b/packages/views/chat/components/chat-session-header.tsx
@@ -29,7 +29,7 @@ import {
import { useChatStore } from "@multica/core/chat";
import type { Agent, ChatSession } from "@multica/core/types";
import { ActorAvatar } from "../../common/actor-avatar";
-import { useNavigation } from "../../navigation";
+import { AppLink } from "../../navigation";
import { useT } from "../../i18n";
/**
@@ -52,7 +52,6 @@ export function ChatSessionHeader({
}) {
const { t } = useT("chat");
const wsPaths = useWorkspacePaths();
- const { push } = useNavigation();
const updateSession = useUpdateChatSession();
const deleteSession = useDeleteChatSession();
const setArchived = useSetChatSessionArchived();
@@ -86,10 +85,6 @@ export function ChatSessionHeader({
updateSession.mutate({ sessionId: session.id, title: trimmed });
};
- const viewProfile = () => {
- if (agent) push(wsPaths.agentDetail(agent.id));
- };
-
const doDelete = () => {
setConfirmDelete(false);
setActiveSession(null);
@@ -160,7 +155,9 @@ export function ChatSessionHeader({
{t(($) => $.header.rename)}
</DropdownMenuItem>
{agent && (
- <DropdownMenuItem onClick={viewProfile}>
+ <DropdownMenuItem
+ render={<AppLink href={wsPaths.agentDetail(agent.id)} />}
+ >
<UserRound className="h-4 w-4" />
{t(($) => $.header.view_profile)}
</DropdownMenuItem>
diff --git a/packages/views/chat/components/chat-thread-list.tsx b/packages/views/chat/components/chat-thread-list.tsx
index cbe3294b3e..ea55fb45ed 100644
--- a/packages/views/chat/components/chat-thread-list.tsx
+++ b/packages/views/chat/components/chat-thread-list.tsx
@@ -16,6 +16,7 @@ import {
} from "lucide-react";
import { cn } from "@multica/ui/lib/utils";
import { useWorkspaceId } from "@multica/core/hooks";
+import { paths, useWorkspaceSlug } from "@multica/core/paths";
import { useWorkspacePresenceMap } from "@multica/core/agents";
import { api } from "@multica/core/api";
import { pendingChatTasksOptions, chatKeys, sortChatSessions } from "@multica/core/chat/queries";
@@ -27,6 +28,7 @@ import {
import { useChatStore } from "@multica/core/chat";
import type { Agent, ChatSession, PendingChatTasksResponse } from "@multica/core/types";
import { ActorAvatar } from "../../common/actor-avatar";
+import { resolveClickIntent, useOptionalNavigation } from "../../navigation";
import { createLogger } from "@multica/core/logger";
import { removeChatMessageFromCaches } from "@multica/core/realtime";
import { useT } from "../../i18n";
@@ -88,6 +90,17 @@ export function ChatThreadList({
}) {
const { t } = useT("chat");
const wsId = useWorkspaceId();
+ // Null-safe slug (not useWorkspacePaths, which throws): the list renders in
+ // tests outside a workspace route; without a slug the web modifier-click
+ // affordance simply stays off.
+ const slug = useWorkspaceSlug();
+ const sessionHref = (sessionId: string) =>
+ slug ? `${paths.workspace(slug).chat()}?session=${sessionId}` : null;
+ // Optional: the list renders bare in tests; without an adapter the web
+ // modifier-click affordance stays off (desktop keeps selection anyway).
+ const navigation = useOptionalNavigation();
+ const openInNewTab = navigation?.openInNewTab;
+ const getShareableUrl = navigation?.getShareableUrl;
const agentById = useMemo(() => new Map(agents.map((a) => [a.id, a])), [agents]);
// Split the flat cache locally: active chats fill the default history view,
@@ -247,10 +260,37 @@ export function ChatThreadList({
key={session.id}
aria-current={isCurrent ? "true" : undefined}
tabIndex={0}
- onClick={() => {
- if (isConfirmingAction) return;
+ onClick={(e) => {
+ if (isConfirmingAction || e.defaultPrevented) return;
+ // Plain click keeps the master-detail selection. On web, a modifier
+ // click opens the session as its own browser tab. Desktop tabs
+ // dedupe chat by pathname (a session is view state, not a subject —
+ // see tab-store resourceKey), so a second chat tab cannot exist
+ // there; modifier clicks keep the selection behavior instead.
+ const href = sessionHref(session.id);
+ if (
+ href &&
+ getShareableUrl &&
+ !openInNewTab &&
+ resolveClickIntent(e) !== "push"
+ ) {
+ window.open(
+ getShareableUrl(href),
+ "_blank",
+ "noopener,noreferrer",
+ );
+ return;
+ }
onSelectSession(session);
}}
+ onAuxClick={(e) => {
+ if (isConfirmingAction || e.defaultPrevented || e.button !== 1) return;
+ if (openInNewTab) return; // desktop: no second chat tab exists
+ const href = sessionHref(session.id);
+ if (!href || !getShareableUrl) return;
+ e.preventDefault();
+ window.open(getShareableUrl(href), "_blank", "noopener,noreferrer");
+ }}
onKeyDown={(e) => {
if (isConfirmingAction) return;
if (e.key !== "Enter" && e.key !== " ") return;
diff --git a/packages/views/chat/components/runtime-required-banner.tsx b/packages/views/chat/components/runtime-required-banner.tsx
index 70a9c477cb..ba0ced9629 100644
--- a/packages/views/chat/components/runtime-required-banner.tsx
+++ b/packages/views/chat/components/runtime-required-banner.tsx
@@ -4,7 +4,7 @@ import { Server } from "lucide-react";
import { useWorkspacePaths } from "@multica/core/paths";
import { Button } from "@multica/ui/components/ui/button";
import { cn } from "@multica/ui/lib/utils";
-import { useNavigation } from "../../navigation";
+import { AppLink } from "../../navigation";
import { useT } from "../../i18n";
import { CHAT_COLUMN, CHAT_GUTTER } from "./chat-column";
@@ -17,7 +17,6 @@ export function RuntimeRequiredBanner({
}) {
const { t } = useT("chat");
const paths = useWorkspacePaths();
- const navigation = useNavigation();
const name = agentName?.trim() || t(($) => $.runtime_required_banner.fallback_name);
return (
@@ -33,13 +32,13 @@ export function RuntimeRequiredBanner({
{t(($) => $.runtime_required_banner.message, { name })}
</span>
<Button
- type="button"
variant="outline"
size="sm"
className="h-6 shrink-0 bg-background/70 text-caption"
- onClick={() =>
- navigation.push(`${paths.agentDetail(agentId)}?view=general`)
+ render={
+ <AppLink href={`${paths.agentDetail(agentId)}?view=general`} />
}
+ nativeButton={false}
>
{t(($) => $.runtime_required_banner.action)}
</Button>
diff --git a/packages/views/common/actor-avatar-profile-link.test.tsx b/packages/views/common/actor-avatar-profile-link.test.tsx
index db41cf4f86..8e27cfba7c 100644
--- a/packages/views/common/actor-avatar-profile-link.test.tsx
+++ b/packages/views/common/actor-avatar-profile-link.test.tsx
@@ -96,7 +96,7 @@ describe("ActorAvatar profile link", () => {
renderAvatar(makeAdapter({ push, openInNewTab }));
fireEvent.click(screen.getByRole("link"), { metaKey: true });
- expect(openInNewTab).toHaveBeenCalledWith(HREF);
+ expect(openInNewTab).toHaveBeenCalledWith(HREF, undefined);
expect(push).not.toHaveBeenCalled();
expect(open).not.toHaveBeenCalled();
});
diff --git a/packages/views/common/actor-avatar.tsx b/packages/views/common/actor-avatar.tsx
index 59a455add5..ac8cb4b75a 100644
--- a/packages/views/common/actor-avatar.tsx
+++ b/packages/views/common/actor-avatar.tsx
@@ -16,7 +16,11 @@ import { AgentLivePeekCard } from "../agents/components/agent-live-peek-card";
import { MemberProfileCard } from "../members/member-profile-card";
import { SquadProfileCard } from "../squads/components/squad-profile-card";
import { availabilityConfig } from "../agents/presence";
-import { useNavigation } from "../navigation";
+import {
+ resolveClickIntent,
+ useIntentNavigate,
+ type LinkClickIntent,
+} from "../navigation";
/**
* Selects which agent hover-card payload to render when `enableHoverCard` is
@@ -144,6 +148,15 @@ export function ActorAvatar({
return content;
}
+/**
+ * Not an `<a>` on purpose: the avatar is often composed inside menu items,
+ * options and buttons, where it must yield the click to the surrounding
+ * control untouched (no preventDefault — a real anchor would need one to
+ * suppress its own navigation, and a pre-prevented click can change how the
+ * host control behaves). The cost is no native context menu; modifier and
+ * middle clicks are implemented here instead, with the same intent semantics
+ * as AppLink.
+ */
function ActorAvatarProfileLink({
href,
children,
@@ -151,28 +164,26 @@ function ActorAvatarProfileLink({
href: string;
children: React.ReactNode;
}) {
- const { push, openInNewTab, getShareableUrl } = useNavigation();
+ // Web note: the trigger is a `<span role="link">`, not an anchor, so there
+ // is no native modifier-click behaviour to fall back to — useIntentNavigate
+ // opens the browser tab itself rather than letting the click navigate in
+ // place.
+ const intentNavigate = useIntentNavigate();
- const navigate = (event: React.MouseEvent | React.KeyboardEvent) => {
- const controlAncestor = event.currentTarget.parentElement?.closest(
- PROFILE_LINK_CONTROL_SELECTOR,
- );
- if (controlAncestor) return;
+ const insideControl = (event: React.SyntheticEvent) =>
+ !!event.currentTarget.parentElement?.closest(PROFILE_LINK_CONTROL_SELECTOR);
+ const open = (intent: LinkClickIntent) => intentNavigate(href, intent);
+
+ const navigate = (event: React.MouseEvent | React.KeyboardEvent) => {
+ if (insideControl(event)) return;
event.preventDefault();
event.stopPropagation();
- if ("metaKey" in event && (event.metaKey || event.ctrlKey || event.shiftKey)) {
- if (openInNewTab) {
- openInNewTab(href);
- return;
- }
- // Web: the trigger is a `<span role="link">`, not an anchor, so there is
- // no native modifier-click behaviour to fall back to — open the browser
- // tab here rather than letting the click navigate in place.
- window.open(getShareableUrl(href), "_blank", "noopener,noreferrer");
- return;
- }
- push(href);
+ open(
+ "metaKey" in event && "button" in event
+ ? resolveClickIntent(event as React.MouseEvent)
+ : "push",
+ );
};
return (
@@ -181,6 +192,13 @@ function ActorAvatarProfileLink({
tabIndex={-1}
className="inline-flex cursor-pointer rounded-full"
onClick={navigate}
+ onAuxClick={(event) => {
+ if (event.defaultPrevented || event.button !== 1) return;
+ if (insideControl(event)) return;
+ event.preventDefault();
+ event.stopPropagation();
+ open("background-tab");
+ }}
onKeyDown={(event) => {
if (event.key === "Enter" || event.key === " ") {
navigate(event);
diff --git a/packages/views/common/rich-content-sanitize-contract.test.tsx b/packages/views/common/rich-content-sanitize-contract.test.tsx
index 801a6d42a5..a40942669b 100644
--- a/packages/views/common/rich-content-sanitize-contract.test.tsx
+++ b/packages/views/common/rich-content-sanitize-contract.test.tsx
@@ -54,6 +54,8 @@ vi.mock("@multica/core/paths", () => ({
vi.mock("../navigation", () => ({
useNavigation: () => ({ push: vi.fn(), openInNewTab: vi.fn() }),
+ useOptionalNavigation: () => ({ push: vi.fn(), openInNewTab: vi.fn() }),
+ resolveClickIntent: () => "push",
useAppOrigin: () => null,
AppLink: ({ href, children }: { href: string; children: React.ReactNode }) => (
<a href={href}>{children}</a>
diff --git a/packages/views/dingtalk/bind-page.tsx b/packages/views/dingtalk/bind-page.tsx
index 455a85b52a..097fc3564b 100644
--- a/packages/views/dingtalk/bind-page.tsx
+++ b/packages/views/dingtalk/bind-page.tsx
@@ -5,7 +5,7 @@ import { Card, CardContent } from "@multica/ui/components/ui/card";
import { Button } from "@multica/ui/components/ui/button";
import { api, ApiError } from "@multica/core/api";
import { useAuthStore } from "@multica/core/auth";
-import { useNavigation } from "../navigation";
+import { AppLink } from "../navigation";
import { useT } from "../i18n";
type RedeemState =
@@ -29,7 +29,6 @@ export function DingTalkBindPage({ token }: { token: string | null }) {
const { t } = useT("common");
const user = useAuthStore((s) => s.user);
const isAuthLoading = useAuthStore((s) => s.isLoading);
- const navigation = useNavigation();
const [state, setState] = useState<RedeemState>({ kind: "idle" });
const redeemingToken = useRef<string | null>(null);
@@ -78,13 +77,14 @@ export function DingTalkBindPage({ token }: { token: string | null }) {
</p>
<Button
size="sm"
- onClick={() =>
- navigation.push(
- `/login?next=${encodeURIComponent(
+ render={
+ <AppLink
+ href={`/login?next=${encodeURIComponent(
`/dingtalk/bind?token=${encodeURIComponent(token ?? "")}`,
- )}`,
- )
+ )}`}
+ />
}
+ nativeButton={false}
>
{t(($) => $.dingtalk_bind.sign_in)}
</Button>
diff --git a/packages/views/editor/content-editor.tsx b/packages/views/editor/content-editor.tsx
index 54d0298bc5..9063cfff40 100644
--- a/packages/views/editor/content-editor.tsx
+++ b/packages/views/editor/content-editor.tsx
@@ -66,7 +66,7 @@ import {
import { configStore } from "@multica/core/config";
import { preprocessMarkdown } from "./utils/preprocess";
import { repairEmptyListItems } from "./utils/repair-list-items";
-import { useAppOrigin } from "../navigation";
+import { resolveClickIntent, useAppOrigin } from "../navigation";
import { openLink, isMentionHref } from "./utils/link-handler";
import { EditorBubbleMenu } from "./bubble-menu";
import { posFromAnchor, type TextAnchor } from "./text-anchor";
@@ -651,7 +651,30 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
if (!href || isMentionHref(href)) return false;
event.preventDefault();
- openLink(href, workspaceSlugRef.current, appOriginRef.current);
+ openLink(
+ href,
+ workspaceSlugRef.current,
+ appOriginRef.current,
+ resolveClickIntent(event),
+ );
+ return true;
+ },
+ // Middle click never produces a `click` event. Route it through the
+ // same path as a cmd-click (background tab) — on desktop the native
+ // window-open request dead-ends against the shell's deny handler.
+ auxclick(_view, event) {
+ if (event.button !== 1) return false;
+ const target = event.target as HTMLElement;
+ if (target.closest("[data-node-view-wrapper]")) return false;
+ const href = target.closest("a")?.getAttribute("href");
+ if (!href || isMentionHref(href)) return false;
+ event.preventDefault();
+ openLink(
+ href,
+ workspaceSlugRef.current,
+ appOriginRef.current,
+ "background-tab",
+ );
return true;
},
},
diff --git a/packages/views/editor/extensions/mention-view.test.tsx b/packages/views/editor/extensions/mention-view.test.tsx
index 072ea1a15b..0d592470f1 100644
--- a/packages/views/editor/extensions/mention-view.test.tsx
+++ b/packages/views/editor/extensions/mention-view.test.tsx
@@ -27,13 +27,6 @@ vi.mock("@multica/core/paths", () => ({
}),
}));
-const { newTabPreferred } = vi.hoisted(() => ({ newTabPreferred: { value: false } }));
-
-vi.mock("@multica/core/issues/stores", () => ({
- useIssueLinkStore: (selector: (s: { openInNewTab: boolean }) => unknown) =>
- selector({ openInNewTab: newTabPreferred.value }),
-}));
-
vi.mock("../../issues/components/issue-chip", () => ({
IssueChip: ({ fallbackLabel }: { fallbackLabel?: string }) => (
<span data-testid="issue-chip">{fallbackLabel}</span>
@@ -138,6 +131,19 @@ describe("MentionView issue mention", () => {
const ISSUE_ID = "1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed";
const ISSUE_PATH = `/acme/issues/${ISSUE_ID}`;
+ it("pushes in place on plain click — same as the readonly chip", () => {
+ const push = vi.fn();
+ const openInNewTab = vi.fn();
+ renderMention(
+ { type: "issue", id: ISSUE_ID, label: "MUL-7" },
+ makeAdapter({ push, openInNewTab }),
+ );
+
+ fireEvent.click(screen.getByTestId("issue-chip"));
+ expect(push).toHaveBeenCalledWith(ISSUE_PATH);
+ expect(openInNewTab).not.toHaveBeenCalled();
+ });
+
// The reference implementation the project mention was aligned to — guard it
// so the two chips can't drift apart again.
it("leaves modifier-click to the browser when openInNewTab is absent (web)", () => {
diff --git a/packages/views/editor/extensions/mention-view.tsx b/packages/views/editor/extensions/mention-view.tsx
index f6b8984baf..8b0fd5f658 100644
--- a/packages/views/editor/extensions/mention-view.tsx
+++ b/packages/views/editor/extensions/mention-view.tsx
@@ -4,39 +4,50 @@
* MentionView — NodeView for rendering @mentions inline in the editor.
*
* Member/agent mentions: plain "@Name" text with .mention class styling.
- * Issue mentions: IssueChip inside a custom <a> that supports cmd/shift-click
- * to open in a new tab (AppLink doesn't expose that intent hook).
+ * Issue/project mentions render the same navigable chips as readonly content
+ * (IssueMentionCard / ProjectMentionCard), so click behavior — plain click,
+ * modifier click, middle click — cannot drift between an editing and a
+ * readonly surface. The editor's ProseMirror click handler skips anything
+ * inside `[data-node-view-wrapper]`, so the AppLink inside the card owns the
+ * click alone.
*
* Issue chip sizing: must fit within the paragraph line box (14px * 1.625 =
* 22.75px). Card is text-caption (12px) + py-0.5 + border ≈ 22px total. The
* `vertical-align: middle` rule on `[data-node-view-wrapper]` in CSS handles
- * line-box alignment; setting it on the inner <a> has no effect because the
- * wrapper is the outermost inline element.
+ * line-box alignment; setting it on an inner element has no effect because
+ * the wrapper is the outermost inline element.
*/
import { NodeViewWrapper } from "@tiptap/react";
import type { NodeViewProps } from "@tiptap/react";
-import { useWorkspacePaths } from "@multica/core/paths";
-import { useIssueLinkStore } from "@multica/core/issues/stores";
-import { useNavigation } from "../../navigation";
-import { IssueChip } from "../../issues/components/issue-chip";
-import { ProjectChip } from "../../projects/components/project-chip";
+import { IssueMentionCard } from "../../issues/components/issue-mention-card";
+import { ProjectMentionCard } from "../../projects/components/project-mention-card";
export function MentionView({ node }: NodeViewProps) {
const { type, id, label } = node.attrs;
+ // stopPropagation mirrors the readonly renderer's mention wrappers: a chip
+ // click must not reach surrounding click handlers.
if (type === "issue") {
return (
- <NodeViewWrapper as="span" className="inline">
- <IssueMention issueId={id} fallbackLabel={label} />
+ <NodeViewWrapper
+ as="span"
+ className="inline"
+ onClick={(e: React.MouseEvent) => e.stopPropagation()}
+ >
+ <IssueMentionCard issueId={id} fallbackLabel={label} />
</NodeViewWrapper>
);
}
if (type === "project") {
return (
- <NodeViewWrapper as="span" className="inline">
- <ProjectMention projectId={id} fallbackLabel={label} />
+ <NodeViewWrapper
+ as="span"
+ className="inline"
+ onClick={(e: React.MouseEvent) => e.stopPropagation()}
+ >
+ <ProjectMentionCard projectId={id} fallbackLabel={label} />
</NodeViewWrapper>
);
}
@@ -47,92 +58,3 @@ export function MentionView({ node }: NodeViewProps) {
</NodeViewWrapper>
);
}
-
-function ProjectMention({
- projectId,
- fallbackLabel,
-}: {
- projectId: string;
- fallbackLabel?: string;
-}) {
- const p = useWorkspacePaths();
- const { push, openInNewTab } = useNavigation();
- const projectPath = p.projectDetail(projectId);
-
- const handleClick = (e: React.MouseEvent) => {
- e.stopPropagation();
- if (e.metaKey || e.ctrlKey || e.shiftKey) {
- if (openInNewTab) {
- e.preventDefault();
- openInNewTab(projectPath, fallbackLabel);
- }
- // Web: no adapter — leave the event alone so the browser's native
- // modifier-click on the anchor opens the tab (or window for shift),
- // preserving background/foreground semantics window.open would flatten.
- return;
- }
- e.preventDefault();
- push(projectPath);
- };
-
- return (
- <a href={projectPath} onClick={handleClick} className="project-mention">
- <ProjectChip
- projectId={projectId}
- fallbackLabel={fallbackLabel}
- className="cursor-pointer hover:bg-accent transition-colors"
- />
- </a>
- );
-}
-
-function IssueMention({
- issueId,
- fallbackLabel,
-}: {
- issueId: string;
- fallbackLabel?: string;
-}) {
- const p = useWorkspacePaths();
- const { push, openInNewTab } = useNavigation();
- const newTabPreferred = useIssueLinkStore((s) => s.openInNewTab);
- const issuePath = p.issueDetail(issueId);
-
- const handleClick = (e: React.MouseEvent) => {
- e.stopPropagation();
- if (e.metaKey || e.ctrlKey || e.shiftKey) {
- if (openInNewTab) {
- e.preventDefault();
- openInNewTab(issuePath, fallbackLabel);
- }
- // Web: no adapter — native modifier-click on the anchor opens a tab.
- return;
- }
- if (newTabPreferred) {
- if (openInNewTab) {
- e.preventDefault();
- openInNewTab(issuePath, fallbackLabel, { activate: true });
- }
- // Web: native target="_blank" opens a browser tab.
- return;
- }
- e.preventDefault();
- push(issuePath);
- };
-
- return (
- <a
- href={issuePath}
- target={newTabPreferred ? "_blank" : undefined}
- rel={newTabPreferred ? "noopener noreferrer" : undefined}
- onClick={handleClick}
- className="issue-mention"
- >
- <IssueChip
- issueId={issueId}
- fallbackLabel={fallbackLabel}
- className="cursor-pointer hover:bg-accent transition-colors"
- />
- </a>
- );
-}
diff --git a/packages/views/editor/readonly-content.test.tsx b/packages/views/editor/readonly-content.test.tsx
index 46505af892..04b6960bdd 100644
--- a/packages/views/editor/readonly-content.test.tsx
+++ b/packages/views/editor/readonly-content.test.tsx
@@ -42,6 +42,8 @@ vi.mock("@multica/core/paths", () => ({
vi.mock("../navigation", () => ({
useNavigation: () => ({ push: vi.fn(), openInNewTab: vi.fn() }),
+ useOptionalNavigation: () => ({ push: vi.fn(), openInNewTab: vi.fn() }),
+ resolveClickIntent: () => "push",
useAppOrigin: () => null,
}));
diff --git a/packages/views/editor/utils/link-handler.test.ts b/packages/views/editor/utils/link-handler.test.ts
index 064d42a6b2..09b60e2c14 100644
--- a/packages/views/editor/utils/link-handler.test.ts
+++ b/packages/views/editor/utils/link-handler.test.ts
@@ -110,6 +110,28 @@ describe("openLink", () => {
openLink("/other/issues/MUL-1", "acme", APP_ORIGIN);
expect(navigatedPaths()).toEqual(["/other/issues/MUL-1"]);
});
+
+ it("defaults the disposition to push and carries an explicit click intent through the event", () => {
+ openLink("/acme/issues/MUL-1", "acme", APP_ORIGIN);
+ openLink("/acme/issues/MUL-2", "acme", APP_ORIGIN, "background-tab");
+ const details = dispatched.map(
+ (e) => (e as CustomEvent<{ path: string; disposition: string }>).detail,
+ );
+ expect(details).toEqual([
+ { path: "/acme/issues/MUL-1", disposition: "push" },
+ { path: "/acme/issues/MUL-2", disposition: "background-tab" },
+ ]);
+ });
+
+ it("ignores the intent for an external URL — it always hands off to the browser", () => {
+ openLink("https://github.com/a/b", "acme", APP_ORIGIN, "foreground-tab");
+ expect(dispatched).toHaveLength(0);
+ expect(openSpy).toHaveBeenCalledWith(
+ "https://github.com/a/b",
+ "_blank",
+ "noopener,noreferrer",
+ );
+ });
});
describe("parseWorkspaceEntityLink", () => {
diff --git a/packages/views/editor/utils/link-handler.ts b/packages/views/editor/utils/link-handler.ts
index 0ee3231b03..5890c68fee 100644
--- a/packages/views/editor/utils/link-handler.ts
+++ b/packages/views/editor/utils/link-handler.ts
@@ -7,6 +7,7 @@
import { isGlobalPath, isReservedSlug } from "@multica/core/paths";
import { isIssueIdentifier } from "@multica/ui/markdown";
+import type { LinkClickIntent } from "../../navigation/click-intent";
/**
* Top-level workspace-scoped routes. Used to detect "/{route}/..." paths that
@@ -245,11 +246,17 @@ export function parseWorkspaceEntityLink(
*
* `appOrigin` lets absolute URLs pointing back at this deployment take the same
* internal route as a relative path.
+ *
+ * `intent` is how the user clicked (see `resolveClickIntent`); the platform
+ * listener answering `multica:navigate` executes it — in-place navigation for
+ * "push", a new tab otherwise. External links ignore it: they always hand off
+ * to the browser / system browser.
*/
export function openLink(
href: string,
currentSlug?: string | null,
appOrigin?: string | null,
+ intent: LinkClickIntent = "push",
): void {
const internalPath = href.startsWith("/")
? href
@@ -267,7 +274,9 @@ export function openLink(
// the user wrote what they meant.
}
window.dispatchEvent(
- new CustomEvent("multica:navigate", { detail: { path } }),
+ new CustomEvent("multica:navigate", {
+ detail: { path, disposition: intent },
+ }),
);
} else {
window.open(href, "_blank", "noopener,noreferrer");
diff --git a/packages/views/inbox/components/inbox-context-menu.test.tsx b/packages/views/inbox/components/inbox-context-menu.test.tsx
index 892e8d9883..06d5c0d076 100644
--- a/packages/views/inbox/components/inbox-context-menu.test.tsx
+++ b/packages/views/inbox/components/inbox-context-menu.test.tsx
@@ -1,7 +1,9 @@
import { describe, expect, it, vi } from "vitest";
import { fireEvent, render, screen } from "@testing-library/react";
import type { ReactNode } from "react";
+import { WorkspaceSlugProvider } from "@multica/core/paths";
import type { InboxItem } from "@multica/core/types";
+import { NavigationProvider } from "../../navigation";
import { I18nProvider } from "@multica/core/i18n/react";
import enInbox from "../../locales/en/inbox.json";
@@ -40,10 +42,22 @@ function item(overrides: Partial<InboxItem> = {}): InboxItem {
};
}
+const navigationAdapter = {
+ push: vi.fn(),
+ replace: vi.fn(),
+ back: vi.fn(),
+ pathname: "/",
+ searchParams: new URLSearchParams(),
+ getShareableUrl: (p: string) => p,
+ openInNewTab: vi.fn(),
+};
+
function wrap(ui: ReactNode) {
return (
<I18nProvider locale="en" resources={TEST_RESOURCES}>
- {ui}
+ <WorkspaceSlugProvider slug="acme">
+ <NavigationProvider value={navigationAdapter}>{ui}</NavigationProvider>
+ </WorkspaceSlugProvider>
</I18nProvider>
);
}
@@ -139,4 +153,26 @@ describe("inbox row context menu", () => {
expect(event.defaultPrevented).toBe(true);
});
+
+ it("offers Open in new tab as a foreground open when the row references an issue", async () => {
+ const { row } = renderRow({ entry: item({ issue_id: "issue-9" }) });
+
+ fireEvent.contextMenu(row);
+ fireEvent.click(await screen.findByText("Open in new tab"));
+
+ expect(navigationAdapter.openInNewTab).toHaveBeenCalledWith(
+ "/acme/issues/issue-9",
+ undefined,
+ { activate: true },
+ );
+ });
+
+ it("omits Open in new tab for a row without an issue", async () => {
+ const { row } = renderRow({ entry: item({ issue_id: null }) });
+
+ fireEvent.contextMenu(row);
+ await screen.findByText("Archive");
+
+ expect(screen.queryByText("Open in new tab")).toBeNull();
+ });
});
diff --git a/packages/views/inbox/components/inbox-context-menu.tsx b/packages/views/inbox/components/inbox-context-menu.tsx
index 1c9d73f7b0..466aa03bfd 100644
--- a/packages/views/inbox/components/inbox-context-menu.tsx
+++ b/packages/views/inbox/components/inbox-context-menu.tsx
@@ -10,8 +10,10 @@ import {
type MouseEvent,
type ReactNode,
} from "react";
-import { Archive, ArchiveRestore, Check, CircleDot } from "lucide-react";
+import { Archive, ArchiveRestore, Check, CircleDot, ExternalLink } from "lucide-react";
+import { paths, useWorkspaceSlug } from "@multica/core/paths";
import type { InboxItem } from "@multica/core/types";
+import { useIntentNavigate } from "../../navigation";
import {
ContextMenu,
ContextMenuContent,
@@ -130,6 +132,14 @@ function InboxContextMenuSingleton({
onOpenChange: (v: boolean) => void;
}) {
const { t } = useT("inbox");
+ // Null-safe slug (not useWorkspacePaths, which throws): keeps the menu
+ // renderable outside a workspace route; the item just doesn't show.
+ const slug = useWorkspaceSlug();
+ const issueHref =
+ slug && item.issue_id
+ ? paths.workspace(slug).issueDetail(item.issue_id)
+ : null;
+ const intentNavigate = useIntentNavigate();
const isArchivedView = view === "archived";
// Point-sized virtual anchor at the right-click position, so the menu opens
@@ -145,6 +155,20 @@ function InboxContextMenuSingleton({
return (
<ContextMenu open={open} onOpenChange={onOpenChange}>
<ContextMenuContent anchor={anchor}>
+ {/* An explicit "Open in new tab" CTA is a foreground open — focus
+ follows, per the navigation spec's right-click row. Only rows that
+ reference an issue have somewhere to open. */}
+ {issueHref && (
+ <>
+ <ContextMenuItem
+ onClick={() => intentNavigate(issueHref, "foreground-tab")}
+ >
+ <ExternalLink className="h-4 w-4" />
+ {t(($) => $.context_menu.open_in_new_tab)}
+ </ContextMenuItem>
+ <ContextMenuSeparator />
+ </>
+ )}
{/* The read toggle is main-view only. Archived rows deliberately render
as read (archiving preserves `read` so a restore can bring the real
state back) and the unread count excludes archived items — so a
diff --git a/packages/views/inbox/components/inbox-list-item.test.tsx b/packages/views/inbox/components/inbox-list-item.test.tsx
index b2a766039d..fdd791bb33 100644
--- a/packages/views/inbox/components/inbox-list-item.test.tsx
+++ b/packages/views/inbox/components/inbox-list-item.test.tsx
@@ -1,6 +1,9 @@
-import { render } from "@testing-library/react";
+import { fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
+import { WorkspaceSlugProvider } from "@multica/core/paths";
import type { InboxItem } from "@multica/core/types";
+import { NavigationProvider } from "../../navigation";
+import type { NavigationAdapter } from "../../navigation";
import { InboxListItem } from "./inbox-list-item";
vi.mock("../../issues/components", () => ({ StatusIcon: () => null }));
@@ -62,15 +65,38 @@ function item(overrides: Partial<InboxItem> = {}): InboxItem {
};
}
-function renderRow(props: { item: InboxItem; view: "inbox" | "archived" }) {
+function makeAdapter(
+ overrides: Partial<NavigationAdapter> = {},
+): NavigationAdapter {
+ return {
+ push: vi.fn(),
+ replace: vi.fn(),
+ back: vi.fn(),
+ pathname: "/",
+ searchParams: new URLSearchParams(),
+ getShareableUrl: (p) => p,
+ ...overrides,
+ };
+}
+
+function renderRow(props: {
+ item: InboxItem;
+ view: "inbox" | "archived";
+ adapter?: NavigationAdapter;
+ onClick?: () => void;
+}) {
return render(
- <InboxListItem
- item={props.item}
- view={props.view}
- isSelected={false}
- onClick={vi.fn()}
- onAction={vi.fn()}
- />,
+ <WorkspaceSlugProvider slug="acme">
+ <NavigationProvider value={props.adapter ?? makeAdapter()}>
+ <InboxListItem
+ item={props.item}
+ view={props.view}
+ isSelected={false}
+ onClick={props.onClick ?? vi.fn()}
+ onAction={vi.fn()}
+ />
+ </NavigationProvider>
+ </WorkspaceSlugProvider>,
);
}
@@ -137,3 +163,65 @@ describe("InboxListItem issue activity", () => {
expect(queryByTestId("issue-agent-activity")).toBeNull();
});
});
+
+describe("InboxListItem link semantics", () => {
+ it("plain click keeps the master-detail selection and does not navigate", () => {
+ const onClick = vi.fn();
+ const push = vi.fn();
+ renderRow({ item: item(), view: "inbox", onClick, adapter: makeAdapter({ push }) });
+
+ fireEvent.click(screen.getByTestId("actor-avatar").closest("button")!);
+ expect(onClick).toHaveBeenCalledTimes(1);
+ expect(push).not.toHaveBeenCalled();
+ });
+
+ it("cmd-click opens the referenced issue in a background tab (desktop)", () => {
+ const onClick = vi.fn();
+ const openInNewTab = vi.fn();
+ renderRow({
+ item: item(),
+ view: "inbox",
+ onClick,
+ adapter: makeAdapter({ openInNewTab }),
+ });
+
+ fireEvent.click(screen.getByTestId("actor-avatar").closest("button")!, {
+ metaKey: true,
+ });
+ expect(openInNewTab).toHaveBeenCalledWith("/acme/issues/issue-1", undefined);
+ expect(onClick).not.toHaveBeenCalled();
+ });
+
+ it("middle click opens the referenced issue in a background tab", () => {
+ const openInNewTab = vi.fn();
+ renderRow({ item: item(), view: "inbox", adapter: makeAdapter({ openInNewTab }) });
+
+ const row = screen.getByTestId("actor-avatar").closest("button")!;
+ const event = new MouseEvent("auxclick", {
+ bubbles: true,
+ button: 1,
+ cancelable: true,
+ });
+ row.dispatchEvent(event);
+
+ expect(event.defaultPrevented).toBe(true);
+ expect(openInNewTab).toHaveBeenCalledWith("/acme/issues/issue-1", undefined);
+ });
+
+ it("cmd-click on a row without an issue falls back to plain selection", () => {
+ const onClick = vi.fn();
+ const openInNewTab = vi.fn();
+ renderRow({
+ item: item({ issue_id: null }),
+ view: "inbox",
+ onClick,
+ adapter: makeAdapter({ openInNewTab }),
+ });
+
+ fireEvent.click(screen.getByTestId("actor-avatar").closest("button")!, {
+ metaKey: true,
+ });
+ expect(onClick).toHaveBeenCalledTimes(1);
+ expect(openInNewTab).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/views/inbox/components/inbox-list-item.tsx b/packages/views/inbox/components/inbox-list-item.tsx
index 9e0becb07b..bb4c379de9 100644
--- a/packages/views/inbox/components/inbox-list-item.tsx
+++ b/packages/views/inbox/components/inbox-list-item.tsx
@@ -12,6 +12,8 @@ import { InboxDetailLabel } from "./inbox-detail-label";
import { getInboxDisplayTitle } from "./inbox-display";
import { useInboxContextMenu } from "./inbox-context-menu";
import { useT } from "../../i18n";
+import { paths, useWorkspaceSlug } from "@multica/core/paths";
+import { resolveClickIntent, useIntentNavigate } from "../../navigation";
// Hook returning a localized relative-time formatter — the i18n equivalent
// of the previous static `timeAgo` function. Returning a function (rather
@@ -48,6 +50,15 @@ export function InboxListItem({
const { t } = useT("inbox");
const timeAgo = useTimeAgo();
const openContextMenu = useInboxContextMenu();
+ // Null-safe slug (not useWorkspacePaths, which throws): the row renders in
+ // tests and could render outside a workspace route; without a slug the
+ // modifier-click affordance simply stays off.
+ const slug = useWorkspaceSlug();
+ const issueHref =
+ slug && item.issue_id
+ ? paths.workspace(slug).issueDetail(item.issue_id)
+ : null;
+ const intentNavigate = useIntentNavigate();
const displayTitle = getInboxDisplayTitle(item);
const isArchivedView = view === "archived";
// Archiving deliberately leaves `read` untouched so unarchiving restores the
@@ -63,7 +74,23 @@ export function InboxListItem({
return (
<button
type="button"
- onClick={onClick}
+ onClick={(e) => {
+ // Plain click keeps the master-detail selection; a modifier click on
+ // a row that references an issue opens that issue as its own tab.
+ if (issueHref) {
+ const intent = resolveClickIntent(e);
+ if (intent !== "push") {
+ intentNavigate(issueHref, intent);
+ return;
+ }
+ }
+ onClick();
+ }}
+ onAuxClick={(e) => {
+ if (e.defaultPrevented || e.button !== 1 || !issueHref) return;
+ e.preventDefault();
+ intentNavigate(issueHref, "background-tab");
+ }}
// Right-click opens the list's shared menu (mark read/unread, archive).
// `select-none` mirrors what Base UI's own trigger used to merge in, so
// right-clicking a row never starts a text selection.
diff --git a/packages/views/invitations/invitations-page.test.tsx b/packages/views/invitations/invitations-page.test.tsx
index 55fb8c43d1..442fa9ac31 100644
--- a/packages/views/invitations/invitations-page.test.tsx
+++ b/packages/views/invitations/invitations-page.test.tsx
@@ -23,7 +23,9 @@ const {
listWorkspaces: vi.fn(),
}));
-vi.mock("../navigation", () => ({
+// Mocked at the context module rather than the barrel so <AppLink> stays the
+// real component and its click contract is what the test exercises.
+vi.mock("../navigation/context", () => ({
useNavigation: () => ({ push: navigate, replace: navigate }),
}));
diff --git a/packages/views/invitations/invitations-page.tsx b/packages/views/invitations/invitations-page.tsx
index dabf536a42..84bf889508 100644
--- a/packages/views/invitations/invitations-page.tsx
+++ b/packages/views/invitations/invitations-page.tsx
@@ -11,7 +11,7 @@ import {
} from "@multica/core/workspace/queries";
import { paths } from "@multica/core/paths";
import type { Invitation } from "@multica/core/types";
-import { useNavigation } from "../navigation";
+import { AppLink, useNavigation } from "../navigation";
import { useLogout } from "../auth";
import { DragStrip } from "../platform";
import { useT } from "../i18n";
@@ -167,7 +167,10 @@ export function InvitationsPage() {
<p className="text-body text-muted-foreground text-center">
{t(($) => $.batch.empty_hint)}
</p>
- <Button onClick={() => push(paths.onboarding())}>
+ <Button
+ render={<AppLink href={paths.onboarding()} />}
+ nativeButton={false}
+ >
{t(($) => $.batch.empty_continue)}
</Button>
</CardContent>
diff --git a/packages/views/invite/invite-page.tsx b/packages/views/invite/invite-page.tsx
index d17954c873..a63fe48729 100644
--- a/packages/views/invite/invite-page.tsx
+++ b/packages/views/invite/invite-page.tsx
@@ -13,7 +13,7 @@ import {
resolvePostAuthDestination,
useHasOnboarded,
} from "@multica/core/paths";
-import { useNavigation } from "../navigation";
+import { AppLink, useNavigation } from "../navigation";
import { useLogout } from "../auth";
import { DragStrip } from "../platform";
import { useT } from "../i18n";
@@ -136,7 +136,11 @@ export function InvitePage({ invitationId, onBack }: InvitePageProps) {
<p className="text-body text-muted-foreground text-center">
{t(($) => $.not_found.description)}
</p>
- <Button variant="outline" onClick={() => push(fallbackDest)}>
+ <Button
+ variant="outline"
+ render={<AppLink href={fallbackDest} />}
+ nativeButton={false}
+ >
{t(($) => $.not_found.go_to_dashboard)}
</Button>
</CardContent>
@@ -172,7 +176,11 @@ export function InvitePage({ invitationId, onBack }: InvitePageProps) {
<CardContent className="flex flex-col items-center gap-4 py-12">
<h2 className="text-title font-semibold">{t(($) => $.declined.title)}</h2>
<p className="text-body text-muted-foreground">{t(($) => $.declined.description)}</p>
- <Button variant="outline" onClick={() => push(fallbackDest)}>
+ <Button
+ variant="outline"
+ render={<AppLink href={fallbackDest} />}
+ nativeButton={false}
+ >
{t(($) => $.declined.go_to_dashboard)}
</Button>
</CardContent>
diff --git a/packages/views/issues/components/board-card.tsx b/packages/views/issues/components/board-card.tsx
index 66146526d4..458ae4c852 100644
--- a/packages/views/issues/components/board-card.tsx
+++ b/packages/views/issues/components/board-card.tsx
@@ -368,6 +368,7 @@ export const DraggableBoardCard = memo(function DraggableBoardCard({
>
<AppLink
href={p.issueDetail(issue.id)}
+ newTabTitle={issue.identifier}
className={`group block transition-colors ${isDragging ? "pointer-events-none" : ""}`}
>
<BoardCardContent
diff --git a/packages/views/issues/components/gantt-view.tsx b/packages/views/issues/components/gantt-view.tsx
index 2082ff4840..303b3b2d81 100644
--- a/packages/views/issues/components/gantt-view.tsx
+++ b/packages/views/issues/components/gantt-view.tsx
@@ -367,6 +367,7 @@ function ScheduledRow({
{/* Sticky label cell */}
<AppLink
href={p.issueDetail(issue.id)}
+ newTabTitle={issue.identifier}
className="sticky left-0 z-[1] flex shrink-0 items-center gap-2 border-r bg-background px-3 text-body min-w-0"
style={{ width: LEFT_COL_WIDTH }}
>
@@ -397,6 +398,7 @@ function ScheduledRow({
render={
<AppLink
href={p.issueDetail(issue.id)}
+ newTabTitle={issue.identifier}
className={cn(
"absolute top-1/2 -translate-y-1/2 transition-opacity hover:opacity-90",
bar.isMarker
diff --git a/packages/views/issues/components/issue-detail.test.tsx b/packages/views/issues/components/issue-detail.test.tsx
index 2e16456506..dca4351721 100644
--- a/packages/views/issues/components/issue-detail.test.tsx
+++ b/packages/views/issues/components/issue-detail.test.tsx
@@ -349,6 +349,11 @@ vi.mock("@multica/core/issues/stores", async () => ({
...(await vi.importActual<
typeof import("@multica/core/issues/stores/sub-issue-display-store")
>("@multica/core/issues/stores/sub-issue-display-store")),
+ // Real store, in-memory (no localStorage): backs the sub-issues section's
+ // collapsed state.
+ ...(await vi.importActual<
+ typeof import("@multica/core/issues/stores/sub-issues-collapse-store")
+ >("@multica/core/issues/stores/sub-issues-collapse-store")),
useRecentIssuesStore: Object.assign(
(selector?: any) => {
const state = { byWorkspace: {}, recordVisit: mockRecordVisit, pruneWorkspaces: vi.fn() };
diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsx
index b194b5dc1e..1221251b17 100644
--- a/packages/views/issues/components/issue-detail.tsx
+++ b/packages/views/issues/components/issue-detail.tsx
@@ -97,6 +97,7 @@ import {
selectExpandedResolved,
useRecentIssuesStore,
useResolvedExpandStore,
+ useSubIssuesCollapseStore,
useSubIssueDisplayStore,
SUB_ISSUE_ROW_PROPERTY_KEYS,
type SubIssueRowProperties,
@@ -1635,7 +1636,26 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
// definitions — ids from other workspaces or archived properties drop out.
const subIssueRowProps = useSubIssueDisplayStore((s) => s.rowProperties);
const subIssueRowPropertyIds = useSubIssueDisplayStore((s) => s.rowPropertyIds);
- const [subIssuesCollapsed, setSubIssuesCollapsed] = useState(false);
+ // Store-backed (not useState) so the collapsed state survives leaving the
+ // issue and navigating back within the session.
+ const subIssuesCollapsed = useSubIssuesCollapseStore((s) =>
+ s.collapsedIssueIds.has(issueId),
+ );
+ const setSubIssuesCollapsedFor = useSubIssuesCollapseStore(
+ (s) => s.setCollapsed,
+ );
+ const setSubIssuesCollapsed = useCallback(
+ (update: boolean | ((prev: boolean) => boolean)) => {
+ const prev = useSubIssuesCollapseStore
+ .getState()
+ .collapsedIssueIds.has(issueId);
+ setSubIssuesCollapsedFor(
+ issueId,
+ typeof update === "function" ? update(prev) : update,
+ );
+ },
+ [issueId, setSubIssuesCollapsedFor],
+ );
// Selection store is global (workspace-scoped); clear it whenever this
// issue detail is mounted or switched, so leftover selections from the
diff --git a/packages/views/issues/components/issue-mention-card.test.tsx b/packages/views/issues/components/issue-mention-card.test.tsx
index 040425687f..ea51605587 100644
--- a/packages/views/issues/components/issue-mention-card.test.tsx
+++ b/packages/views/issues/components/issue-mention-card.test.tsx
@@ -1,21 +1,9 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
+import { describe, expect, it, vi } from "vitest";
import { fireEvent, render, screen } from "@testing-library/react";
import { IssueMentionCard } from "./issue-mention-card";
import { NavigationProvider } from "../../navigation";
import type { NavigationAdapter } from "../../navigation";
-const { issueLinkState } = vi.hoisted(() => ({
- issueLinkState: { openInNewTab: true, setOpenInNewTab: vi.fn() },
-}));
-
-vi.mock("@multica/core/issues/stores", () => {
- const useIssueLinkStore = (
- selector?: (s: typeof issueLinkState) => unknown,
- ) => (selector ? selector(issueLinkState) : issueLinkState);
- useIssueLinkStore.getState = () => issueLinkState;
- return { useIssueLinkStore };
-});
-
vi.mock("@multica/core/paths", () => ({
useWorkspacePaths: () => ({
issueDetail: (id: string) => `/acme/issues/${id}`,
@@ -51,45 +39,40 @@ function renderCard(adapter: NavigationAdapter) {
}
describe("IssueMentionCard", () => {
- beforeEach(() => {
- issueLinkState.openInNewTab = true;
+ it("renders a real anchor with no target — a chip click navigates in place", () => {
+ renderCard(makeAdapter());
+ const anchor = screen.getByTestId("issue-chip").closest("a");
+ expect(anchor).toHaveAttribute("href", "/acme/issues/issue-1");
+ expect(anchor).not.toHaveAttribute("target");
});
- it("with the new-tab preference on (default), plain click opens a foreground new tab and does not push", () => {
+ it("plain click pushes in place", () => {
const push = vi.fn();
const openInNewTab = vi.fn();
renderCard(makeAdapter({ push, openInNewTab }));
- const anchor = screen.getByTestId("issue-chip").closest("a");
- expect(anchor).toHaveAttribute("target", "_blank");
-
fireEvent.click(screen.getByTestId("issue-chip"));
- expect(openInNewTab).toHaveBeenCalledWith("/acme/issues/issue-1", "MUL-7", {
- activate: true,
- });
- expect(push).not.toHaveBeenCalled();
+ expect(push).toHaveBeenCalledWith("/acme/issues/issue-1");
+ expect(openInNewTab).not.toHaveBeenCalled();
});
- it("with the preference off, plain click navigates in place", () => {
- issueLinkState.openInNewTab = false;
+ it("cmd-click opens a background tab labeled with the issue identifier (desktop)", () => {
const push = vi.fn();
const openInNewTab = vi.fn();
renderCard(makeAdapter({ push, openInNewTab }));
- const anchor = screen.getByTestId("issue-chip").closest("a");
- expect(anchor).not.toHaveAttribute("target");
-
- fireEvent.click(screen.getByTestId("issue-chip"));
- expect(push).toHaveBeenCalledWith("/acme/issues/issue-1");
- expect(openInNewTab).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByTestId("issue-chip"), { metaKey: true });
+ expect(openInNewTab).toHaveBeenCalledWith("/acme/issues/issue-1", "MUL-7");
+ expect(push).not.toHaveBeenCalled();
});
- it("with the preference on but no adapter openInNewTab (web), leaves the click to the browser's native target=_blank handling", () => {
+ it("cmd-click without an adapter (web) is left to the browser's native background-tab handling", () => {
const push = vi.fn();
renderCard(makeAdapter({ push }));
const defaultNotPrevented = fireEvent.click(
screen.getByTestId("issue-chip"),
+ { metaKey: true },
);
expect(defaultNotPrevented).toBe(true);
expect(push).not.toHaveBeenCalled();
diff --git a/packages/views/issues/components/issue-mention-card.tsx b/packages/views/issues/components/issue-mention-card.tsx
index 3fd88804c7..1fab876e60 100644
--- a/packages/views/issues/components/issue-mention-card.tsx
+++ b/packages/views/issues/components/issue-mention-card.tsx
@@ -2,7 +2,6 @@
import { AppLink } from "../../navigation";
import { useWorkspacePaths } from "@multica/core/paths";
-import { useIssueLinkStore } from "@multica/core/issues/stores";
import { IssueChip } from "./issue-chip";
interface IssueMentionCardProps {
@@ -16,16 +15,15 @@ interface IssueMentionCardProps {
* detail page. Hover/cursor affordance is layered onto the chip itself so
* the visual target matches the clickable target.
*
- * Plain click honors the "open issue links in new tab" preference
- * (Settings → Preferences): new browser tab on web, new app tab on desktop.
+ * AppLink owns the click semantics: plain click navigates in place, modifier
+ * and middle clicks open tabs. There is deliberately no per-surface or
+ * per-preference override.
*/
export function IssueMentionCard({ issueId, fallbackLabel }: IssueMentionCardProps) {
const p = useWorkspacePaths();
- const openInNewTab = useIssueLinkStore((s) => s.openInNewTab);
return (
<AppLink
href={p.issueDetail(issueId)}
- target={openInNewTab ? "_blank" : undefined}
newTabTitle={fallbackLabel}
className="issue-mention align-middle"
>
diff --git a/packages/views/issues/components/issues-cold-load-loop.test.tsx b/packages/views/issues/components/issues-cold-load-loop.test.tsx
index d89dae0099..291b8a1cee 100644
--- a/packages/views/issues/components/issues-cold-load-loop.test.tsx
+++ b/packages/views/issues/components/issues-cold-load-loop.test.tsx
@@ -66,6 +66,8 @@ vi.mock("../../navigation", () => ({
</a>
),
useNavigation: () => ({ push: vi.fn(), pathname: "/issues" }),
+ resolveClickIntent: () => "push",
+ useIntentNavigate: () => () => {},
NavigationProvider: ({ children }: { children: React.ReactNode }) => children,
}));
diff --git a/packages/views/issues/components/issues-page.test.tsx b/packages/views/issues/components/issues-page.test.tsx
index 5dbe961e35..c55d69b837 100644
--- a/packages/views/issues/components/issues-page.test.tsx
+++ b/packages/views/issues/components/issues-page.test.tsx
@@ -51,6 +51,8 @@ vi.mock("../../navigation", () => ({
</a>
),
useNavigation: () => ({ push: vi.fn(), pathname: "/issues" }),
+ resolveClickIntent: () => "push",
+ useIntentNavigate: () => () => {},
NavigationProvider: ({ children }: { children: React.ReactNode }) => children,
}));
diff --git a/packages/views/issues/components/list-row.tsx b/packages/views/issues/components/list-row.tsx
index 566c15a322..918e2d3b76 100644
--- a/packages/views/issues/components/list-row.tsx
+++ b/packages/views/issues/components/list-row.tsx
@@ -104,6 +104,7 @@ function ListRowContent({
</div>
<AppLink
href={p.issueDetail(issue.id)}
+ newTabTitle={issue.identifier}
className={`flex flex-1 items-center gap-2 min-w-0 ${isDragging ? "pointer-events-none" : ""}`}
>
<span className="w-16 shrink-0 text-caption text-muted-foreground">
diff --git a/packages/views/issues/components/swimlane-view.test.tsx b/packages/views/issues/components/swimlane-view.test.tsx
index 3a42989715..b1fb0c8c8b 100644
--- a/packages/views/issues/components/swimlane-view.test.tsx
+++ b/packages/views/issues/components/swimlane-view.test.tsx
@@ -95,6 +95,8 @@ vi.mock("../../navigation", () => ({
</a>
),
useNavigation: () => ({ push: vi.fn(), pathname: "/issues" }),
+ resolveClickIntent: () => "push",
+ useIntentNavigate: () => () => {},
NavigationProvider: ({ children }: { children: React.ReactNode }) => children,
}));
diff --git a/packages/views/issues/components/table-view-editing.test.tsx b/packages/views/issues/components/table-view-editing.test.tsx
index f8f56578e0..0d26d09e24 100644
--- a/packages/views/issues/components/table-view-editing.test.tsx
+++ b/packages/views/issues/components/table-view-editing.test.tsx
@@ -12,6 +12,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
act,
cleanup,
+ fireEvent,
render,
screen,
waitFor,
@@ -85,19 +86,49 @@ const navigationMocks = vi.hoisted(() => ({
}));
const navigationState = vi.hoisted(() => ({ hasOpenInNewTab: true }));
-vi.mock("../../navigation", () => ({
- AppLink: ({ children, ...props }: React.ComponentProps<"a">) => (
- <a {...props}>{children}</a>
- ),
- useNavigation: () => ({
- push: navigationMocks.push,
- openInNewTab: navigationState.hasOpenInNewTab
- ? navigationMocks.openInNewTab
- : undefined,
- getShareableUrl: navigationMocks.getShareableUrl,
- pathname: "/",
- }),
-}));
+vi.mock("../../navigation", async () => {
+ // Real resolver — pure, no React context.
+ const { resolveClickIntent } = await vi.importActual<
+ typeof import("../../navigation/click-intent")
+ >("../../navigation/click-intent");
+ return {
+ AppLink: ({ children, ...props }: React.ComponentProps<"a">) => (
+ <a {...props}>{children}</a>
+ ),
+ resolveClickIntent,
+ useNavigation: () => ({
+ push: navigationMocks.push,
+ openInNewTab: navigationState.hasOpenInNewTab
+ ? navigationMocks.openInNewTab
+ : undefined,
+ getShareableUrl: navigationMocks.getShareableUrl,
+ pathname: "/",
+ }),
+ // Mirrors the real hook's adapter semantics against the mocks above.
+ useIntentNavigate:
+ () => (href: string, intent: string, newTabTitle?: string) => {
+ if (intent === "push") {
+ navigationMocks.push(href);
+ return;
+ }
+ if (navigationState.hasOpenInNewTab) {
+ if (intent === "foreground-tab") {
+ navigationMocks.openInNewTab(href, newTabTitle, {
+ activate: true,
+ });
+ } else {
+ navigationMocks.openInNewTab(href, newTabTitle);
+ }
+ return;
+ }
+ window.open(
+ navigationMocks.getShareableUrl(href),
+ "_blank",
+ "noopener,noreferrer",
+ );
+ },
+ };
+});
vi.mock("@multica/core/paths", async () => {
const actual = await vi.importActual<typeof import("@multica/core/paths")>(
@@ -350,7 +381,7 @@ describe("TableView cell editors under data refresh", () => {
});
});
- it("opens title and row clicks in a foreground Desktop tab", async () => {
+ it("navigates in place on plain title and row clicks; modifiers open tabs", async () => {
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
serverIssues = [makeIssue("a", "Alpha task", "todo")];
@@ -364,16 +395,26 @@ describe("TableView cell editors under data refresh", () => {
);
const row = (await screen.findByText("MUL-a")).closest("tr")!;
- await user.click(within(row).getByRole("button", { name: "Alpha task" }));
+ const title = within(row).getByRole("button", { name: "Alpha task" });
+
+ await user.click(title);
+ expect(navigationMocks.push).toHaveBeenCalledWith("/test/issues/a");
+ expect(navigationMocks.openInNewTab).not.toHaveBeenCalled();
+
+ navigationMocks.push.mockClear();
+ await user.click(row);
+ expect(navigationMocks.push).toHaveBeenCalledWith("/test/issues/a");
+ expect(navigationMocks.openInNewTab).not.toHaveBeenCalled();
+
+ navigationMocks.push.mockClear();
+ fireEvent.click(title, { metaKey: true });
expect(navigationMocks.openInNewTab).toHaveBeenCalledWith(
"/test/issues/a",
"MUL-a",
- { activate: true },
);
- expect(navigationMocks.push).not.toHaveBeenCalled();
navigationMocks.openInNewTab.mockClear();
- await user.click(row);
+ fireEvent.click(row, { metaKey: true, shiftKey: true });
expect(navigationMocks.openInNewTab).toHaveBeenCalledWith(
"/test/issues/a",
"MUL-a",
@@ -382,7 +423,42 @@ describe("TableView cell editors under data refresh", () => {
expect(navigationMocks.push).not.toHaveBeenCalled();
});
- it("opens a real browser tab when the platform has no tab adapter", async () => {
+ it("middle click on an interactive cell does not trigger row navigation", async () => {
+ serverIssues = [makeIssue("a", "Alpha task", "todo")];
+
+ renderWithI18n(
+ <QueryClientProvider client={queryClient}>
+ <Harness
+ childProgressMap={new Map()}
+ surfaceKey={`test-aux-cells-${Math.floor(Math.random() * 1e9)}`}
+ />
+ </QueryClientProvider>,
+ );
+
+ const row = (await screen.findByText("MUL-a")).closest("tr")!;
+ const auxClick = (el: HTMLElement) =>
+ el.dispatchEvent(
+ new MouseEvent("auxclick", { bubbles: true, button: 1, cancelable: true }),
+ );
+
+ // Status cell trigger (interactive) — must NOT bubble into a row open.
+ auxClick(within(row).getByRole("button", { name: /Todo/ }));
+ expect(navigationMocks.openInNewTab).not.toHaveBeenCalled();
+ expect(navigationMocks.push).not.toHaveBeenCalled();
+
+ // Row checkbox — same.
+ auxClick(within(row).getByRole("checkbox"));
+ expect(navigationMocks.openInNewTab).not.toHaveBeenCalled();
+
+ // Dead space on the row still opens a background tab on middle click.
+ auxClick(row);
+ expect(navigationMocks.openInNewTab).toHaveBeenCalledWith(
+ "/test/issues/a",
+ "MUL-a",
+ );
+ });
+
+ it("without a tab adapter (web), plain click pushes and a modifier click opens a browser tab", async () => {
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
const windowOpen = vi.fn();
vi.stubGlobal("open", windowOpen);
@@ -399,8 +475,13 @@ describe("TableView cell editors under data refresh", () => {
);
const row = (await screen.findByText("MUL-a")).closest("tr")!;
- await user.click(within(row).getByRole("button", { name: "Alpha task" }));
+ const title = within(row).getByRole("button", { name: "Alpha task" });
+ await user.click(title);
+ expect(navigationMocks.push).toHaveBeenCalledWith("/test/issues/a");
+ expect(windowOpen).not.toHaveBeenCalled();
+
+ fireEvent.click(title, { metaKey: true });
expect(navigationMocks.getShareableUrl).toHaveBeenCalledWith(
"/test/issues/a",
);
@@ -409,7 +490,6 @@ describe("TableView cell editors under data refresh", () => {
"_blank",
"noopener,noreferrer",
);
- expect(navigationMocks.push).not.toHaveBeenCalled();
});
});
diff --git a/packages/views/issues/components/table-view-virtualized-hierarchy.test.tsx b/packages/views/issues/components/table-view-virtualized-hierarchy.test.tsx
index 6572788d55..067e059f0b 100644
--- a/packages/views/issues/components/table-view-virtualized-hierarchy.test.tsx
+++ b/packages/views/issues/components/table-view-virtualized-hierarchy.test.tsx
@@ -81,6 +81,8 @@ vi.mock("../../navigation", () => ({
<a {...props}>{children}</a>
),
useNavigation: () => navigation.value,
+ resolveClickIntent: () => "push",
+ useIntentNavigate: () => () => {},
}));
vi.mock("@multica/core/paths", async () => {
diff --git a/packages/views/issues/components/table-view.tsx b/packages/views/issues/components/table-view.tsx
index edd024130b..a608935394 100644
--- a/packages/views/issues/components/table-view.tsx
+++ b/packages/views/issues/components/table-view.tsx
@@ -115,7 +115,7 @@ import {
} from "@tanstack/react-query";
import { ActorAvatar } from "../../common/actor-avatar";
import { LabelChip } from "../../labels/label-chip";
-import { useNavigation } from "../../navigation";
+import { resolveClickIntent, useIntentNavigate } from "../../navigation";
import { ProjectPicker } from "../../projects/components/project-picker";
import { useT } from "../../i18n";
import { useIssueSurfaceActionsOptional } from "../surface/actions-context";
@@ -339,6 +339,7 @@ function IssueCheckbox({
event.stopPropagation();
onToggle(event.shiftKey);
}}
+ onAuxClick={stopRowNavigation}
onChange={() => undefined}
className="size-3.5 cursor-pointer accent-primary"
/>
@@ -631,7 +632,7 @@ export function InlineTitle({
onEditingChange: (editing: boolean) => void;
onUpdate: (updates: Partial<UpdateIssueRequest>) => void;
/** Navigate to the issue — clicking the title is the primary way IN. */
- onOpen: () => void;
+ onOpen: (event: React.MouseEvent) => void;
onCreateSubIssue: () => void;
onToggleParent: () => void;
toggleLabel: string;
@@ -681,6 +682,9 @@ export function InlineTitle({
}
gestureStartedWhileEditingRef.current = false;
}}
+ onAuxClickCapture={(event) => {
+ if (editing) event.stopPropagation();
+ }}
>
{row.hasChildren ? (
<button
@@ -691,6 +695,7 @@ export function InlineTitle({
event.stopPropagation();
onToggleParent();
}}
+ onAuxClick={stopRowNavigation}
>
{row.collapsed ? (
<ChevronRight className="size-3.5" />
@@ -727,7 +732,7 @@ export function InlineTitle({
className="min-w-0 flex-1 truncate text-left hover:underline"
onClick={(event) => {
event.stopPropagation();
- onOpen();
+ onOpen(event);
}}
>
{row.issue.title}
@@ -758,6 +763,7 @@ export function InlineTitle({
event.stopPropagation();
onCreateSubIssue();
}}
+ onAuxClick={stopRowNavigation}
>
<Plus className="size-3" />
</button>
@@ -770,6 +776,7 @@ export function InlineTitle({
setDraft(row.issue.title);
onEditingChange(true);
}}
+ onAuxClick={stopRowNavigation}
>
<Pencil className="size-3" />
</button>
@@ -793,7 +800,7 @@ function LazyLabelCell({
const labels = issue.labels ?? [];
if (open) {
return (
- <div onClick={stopRowNavigation}>
+ <div onClick={stopRowNavigation} onAuxClick={stopRowNavigation}>
<LabelPicker
issueId={issue.id}
open
@@ -813,6 +820,7 @@ function LazyLabelCell({
event.stopPropagation();
onOpenChange(true);
}}
+ onAuxClick={stopRowNavigation}
>
{labels.length > 0 ? (
<>
@@ -914,7 +922,7 @@ type TableViewMeta = {
editingCellKey: string | null;
setEditingCellKey: (key: string | null) => void;
updateIssue: (issueId: string, updates: Partial<UpdateIssueRequest>) => void;
- openIssue: (issue: Issue) => void;
+ openIssue: (issue: Issue, event?: React.MouseEvent) => void;
createSubIssue: (issue: Issue) => void;
toggleTableParentCollapsed: (issueId: string) => void;
handleIssueSelection: (issueId: string, shiftKey: boolean) => void;
@@ -1094,7 +1102,7 @@ function IssueTableBodyCell({
const property = meta.propertyById.get(propertyId);
if (!property) return null;
return (
- <div onClick={stopRowNavigation}>
+ <div onClick={stopRowNavigation} onAuxClick={stopRowNavigation}>
<CustomPropertyValueEditor
issue={issue}
property={property}
@@ -1112,7 +1120,7 @@ function IssueTableBodyCell({
editing={editorOpen}
onEditingChange={setEditorOpen}
onUpdate={onUpdate}
- onOpen={() => meta.openIssue(issue)}
+ onOpen={(event) => meta.openIssue(issue, event)}
onCreateSubIssue={() => meta.createSubIssue(issue)}
onToggleParent={() => meta.toggleTableParentCollapsed(issue.id)}
toggleLabel={t(($) => $.table.toggle_sub_issues)}
@@ -1126,7 +1134,7 @@ function IssueTableBodyCell({
);
case "status":
return (
- <div onClick={stopRowNavigation}>
+ <div onClick={stopRowNavigation} onAuxClick={stopRowNavigation}>
<StatusPicker
status={issue.status}
onUpdate={onUpdate}
@@ -1138,7 +1146,7 @@ function IssueTableBodyCell({
);
case "priority":
return (
- <div onClick={stopRowNavigation}>
+ <div onClick={stopRowNavigation} onAuxClick={stopRowNavigation}>
<PriorityPicker
priority={issue.priority}
onUpdate={onUpdate}
@@ -1150,7 +1158,7 @@ function IssueTableBodyCell({
);
case "assignee":
return (
- <div onClick={stopRowNavigation}>
+ <div onClick={stopRowNavigation} onAuxClick={stopRowNavigation}>
<AssigneePicker
assigneeType={issue.assignee_type}
assigneeId={issue.assignee_id}
@@ -1171,7 +1179,7 @@ function IssueTableBodyCell({
);
case "project":
return (
- <div onClick={stopRowNavigation}>
+ <div onClick={stopRowNavigation} onAuxClick={stopRowNavigation}>
<ProjectPicker
projectId={issue.project_id}
onUpdate={onUpdate}
@@ -1188,7 +1196,7 @@ function IssueTableBodyCell({
);
case "start_date":
return (
- <div onClick={stopRowNavigation}>
+ <div onClick={stopRowNavigation} onAuxClick={stopRowNavigation}>
<StartDatePicker
startDate={issue.start_date}
onUpdate={onUpdate}
@@ -1199,7 +1207,7 @@ function IssueTableBodyCell({
);
case "due_date":
return (
- <div onClick={stopRowNavigation}>
+ <div onClick={stopRowNavigation} onAuxClick={stopRowNavigation}>
<DueDatePicker
dueDate={issue.due_date}
onUpdate={onUpdate}
@@ -1260,7 +1268,7 @@ export function TableView({
const { t } = useT("issues");
const wsId = useWorkspaceId();
const queryClient = useQueryClient();
- const navigation = useNavigation();
+ const intentNavigate = useIntentNavigate();
const paths = useWorkspacePaths();
const actions = useIssueSurfaceActionsOptional();
const selection = useIssueSurfaceSelection();
@@ -2078,20 +2086,17 @@ export function TableView({
);
const openIssue = useCallback(
- (issue: Issue) => {
- const path = paths.issueDetail(issue.id);
- if (navigation.openInNewTab) {
- navigation.openInNewTab(path, issue.identifier, { activate: true });
- return;
- }
-
- window.open(
- navigation.getShareableUrl(path),
- "_blank",
- "noopener,noreferrer",
+ (issue: Issue, event?: React.MouseEvent) => {
+ // Standard link semantics: plain click navigates in place; modifier /
+ // middle clicks open tabs. Callbacks without an event (keyboard
+ // affordances) count as plain clicks.
+ intentNavigate(
+ paths.issueDetail(issue.id),
+ event ? resolveClickIntent(event) : "push",
+ issue.identifier,
);
},
- [navigation, paths],
+ [intentNavigate, paths],
);
const createSubIssue = useCallback(
@@ -2406,9 +2411,9 @@ export function TableView({
table={table}
virtualizeRows
emptyMessage={t(($) => $.table.empty)}
- onRowClick={(row) => {
+ onRowClick={(row, event) => {
if (row.original.kind === "issue") {
- openIssue(row.original.issue);
+ openIssue(row.original.issue, event);
}
}}
renderRow={(row) => {
diff --git a/packages/views/issues/surface/issue-surface.test.tsx b/packages/views/issues/surface/issue-surface.test.tsx
index 61a69b3f97..e1cf9dc490 100644
--- a/packages/views/issues/surface/issue-surface.test.tsx
+++ b/packages/views/issues/surface/issue-surface.test.tsx
@@ -89,6 +89,8 @@ vi.mock("../../navigation", () => ({
</a>
),
useNavigation: () => ({ push: vi.fn(), pathname: "/" }),
+ resolveClickIntent: () => "push",
+ useIntentNavigate: () => () => {},
}));
vi.mock("@multica/core/paths", async () => {
diff --git a/packages/views/lark/bind-page.test.tsx b/packages/views/lark/bind-page.test.tsx
index 7352d00f03..1a67b7a4b5 100644
--- a/packages/views/lark/bind-page.test.tsx
+++ b/packages/views/lark/bind-page.test.tsx
@@ -26,8 +26,11 @@ vi.mock("@multica/core/auth", () => {
return { useAuthStore };
});
-vi.mock("../navigation", () => ({
+// Mock the context module, not the barrel: AppLink stays the real component
+// (the sign-in button renders through it) and reads the mocked adapter.
+vi.mock("../navigation/context", () => ({
useNavigation: () => ({ push: mockNavigatePush }),
+ useOptionalNavigation: () => ({ push: mockNavigatePush }),
}));
vi.mock("@multica/core/api", () => ({
diff --git a/packages/views/lark/bind-page.tsx b/packages/views/lark/bind-page.tsx
index 6d85e3368b..89b0d9ec50 100644
--- a/packages/views/lark/bind-page.tsx
+++ b/packages/views/lark/bind-page.tsx
@@ -5,7 +5,7 @@ import { Card, CardContent } from "@multica/ui/components/ui/card";
import { Button } from "@multica/ui/components/ui/button";
import { api } from "@multica/core/api";
import { useAuthStore } from "@multica/core/auth";
-import { useNavigation } from "../navigation";
+import { AppLink } from "../navigation";
import { useT } from "../i18n";
type RedeemState =
@@ -30,7 +30,6 @@ export function LarkBindPage({ token }: { token: string | null }) {
const { t } = useT("common");
const user = useAuthStore((s) => s.user);
const isAuthLoading = useAuthStore((s) => s.isLoading);
- const navigation = useNavigation();
const [state, setState] = useState<RedeemState>({ kind: "idle" });
useEffect(() => {
@@ -76,13 +75,14 @@ export function LarkBindPage({ token }: { token: string | null }) {
</p>
<Button
size="sm"
- onClick={() =>
- navigation.push(
- `/login?next=${encodeURIComponent(
+ render={
+ <AppLink
+ href={`/login?next=${encodeURIComponent(
`/lark/bind?token=${encodeURIComponent(token ?? "")}`,
- )}`,
- )
+ )}`}
+ />
}
+ nativeButton={false}
>
{t(($) => $.lark_bind.sign_in)}
</Button>
diff --git a/packages/views/layout/app-sidebar.tsx b/packages/views/layout/app-sidebar.tsx
index 94fc13eeb5..345192373c 100644
--- a/packages/views/layout/app-sidebar.tsx
+++ b/packages/views/layout/app-sidebar.tsx
@@ -218,7 +218,7 @@ function SortablePinItem({
<SidebarMenuButton
size="sm"
isActive={isActive}
- render={<AppLink href={href} draggable={false} />}
+ render={<AppLink href={href} newTabTitle={label} draggable={false} />}
onClick={(event) => {
if (wasDragged.current) {
wasDragged.current = false;
diff --git a/packages/views/layout/breadcrumb-header.tsx b/packages/views/layout/breadcrumb-header.tsx
index 9d097dfac4..9b641c5dfb 100644
--- a/packages/views/layout/breadcrumb-header.tsx
+++ b/packages/views/layout/breadcrumb-header.tsx
@@ -51,6 +51,9 @@ export function BreadcrumbHeader({ segments, leaf, actions, leading, className }
<Fragment key={segment.href}>
<AppLink
href={segment.href}
+ newTabTitle={
+ typeof segment.label === "string" ? segment.label : undefined
+ }
className={cn(
"text-muted-foreground hover:text-foreground transition-colors",
segment.className ?? "shrink-0",
diff --git a/packages/views/locales/en/common.json b/packages/views/locales/en/common.json
index 19489ca4ae..4af6d68ab0 100644
--- a/packages/views/locales/en/common.json
+++ b/packages/views/locales/en/common.json
@@ -105,5 +105,8 @@
"error_already_bound": "This WeCom identity is already linked to a different Multica user. Account transfers must go through an explicit unbind first.",
"error_not_member": "You're signed in to a Multica account that isn't a member of this workspace.",
"error_unknown": "Something went wrong. Try again, and if the problem persists, contact the workspace admin."
+ },
+ "navigation": {
+ "open_in_new_tab": "Open in new tab"
}
}
diff --git a/packages/views/locales/en/inbox.json b/packages/views/locales/en/inbox.json
index 0ebe6b3575..7a5ebbd64e 100644
--- a/packages/views/locales/en/inbox.json
+++ b/packages/views/locales/en/inbox.json
@@ -13,7 +13,8 @@
"mark_read": "Mark as read",
"mark_unread": "Mark as unread",
"archive": "Archive",
- "unarchive": "Unarchive"
+ "unarchive": "Unarchive",
+ "open_in_new_tab": "Open in new tab"
},
"list": {
"empty": "No notifications",
diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.json
index a0317dbf62..7cd7391c81 100644
--- a/packages/views/locales/en/settings.json
+++ b/packages/views/locales/en/settings.json
@@ -77,10 +77,6 @@
"sticky_comment_bar": {
"title": "Sticky comment bar",
"hint": "Keep the comment bar pinned to the bottom while scrolling an issue page."
- },
- "issue_link_new_tab": {
- "title": "Open issue links in new tab",
- "hint": "Issue links in descriptions, comments, and chat open in a new tab instead of navigating in place."
}
},
"shortcuts": {
diff --git a/packages/views/locales/ja/common.json b/packages/views/locales/ja/common.json
index 149a36376e..a942005dd6 100644
--- a/packages/views/locales/ja/common.json
+++ b/packages/views/locales/ja/common.json
@@ -105,5 +105,8 @@
"error_already_bound": "この WeCom ID は別の Multica ユーザーにリンクされています。アカウントの移行には明示的な解除が必要です。",
"error_not_member": "サインインしている Multica アカウントはこのワークスペースのメンバーではありません。",
"error_unknown": "問題が発生しました。もう一度試し、それでも解決しない場合はワークスペース管理者にお問い合わせください。"
+ },
+ "navigation": {
+ "open_in_new_tab": "新しいタブで開く"
}
}
diff --git a/packages/views/locales/ja/inbox.json b/packages/views/locales/ja/inbox.json
index 0b342dda0d..eff170a760 100644
--- a/packages/views/locales/ja/inbox.json
+++ b/packages/views/locales/ja/inbox.json
@@ -13,7 +13,8 @@
"mark_read": "既読にする",
"mark_unread": "未読にする",
"archive": "アーカイブ",
- "unarchive": "アーカイブ解除"
+ "unarchive": "アーカイブ解除",
+ "open_in_new_tab": "新しいタブで開く"
},
"list": {
"empty": "通知はありません",
diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.json
index 778c3aff04..5924c2c652 100644
--- a/packages/views/locales/ja/settings.json
+++ b/packages/views/locales/ja/settings.json
@@ -77,10 +77,6 @@
"sticky_comment_bar": {
"title": "コメントバーを固定",
"hint": "タスクのページをスクロールしても、コメントバーを常に下部に固定します。"
- },
- "issue_link_new_tab": {
- "title": "タスクリンクを新しいタブで開く",
- "hint": "説明・コメント・チャット内のタスクリンクを、その場で移動せず新しいタブで開きます。"
}
},
"shortcuts": {
diff --git a/packages/views/locales/ko/common.json b/packages/views/locales/ko/common.json
index 40d32a465f..b872c908c6 100644
--- a/packages/views/locales/ko/common.json
+++ b/packages/views/locales/ko/common.json
@@ -105,5 +105,8 @@
"error_already_bound": "이 WeCom 신원은 다른 Multica 사용자에게 연결되어 있어요. 계정 이전은 명시적 해제가 필요해요.",
"error_not_member": "로그인한 Multica 계정이 이 워크스페이스의 멤버가 아니에요.",
"error_unknown": "문제가 발생했어요. 다시 시도해 보고, 계속되면 워크스페이스 관리자에게 문의하세요."
+ },
+ "navigation": {
+ "open_in_new_tab": "새 탭에서 열기"
}
}
diff --git a/packages/views/locales/ko/inbox.json b/packages/views/locales/ko/inbox.json
index d240219ff7..78ca9c047c 100644
--- a/packages/views/locales/ko/inbox.json
+++ b/packages/views/locales/ko/inbox.json
@@ -13,7 +13,8 @@
"mark_read": "읽음으로 표시",
"mark_unread": "읽지 않음으로 표시",
"archive": "보관",
- "unarchive": "보관 해제"
+ "unarchive": "보관 해제",
+ "open_in_new_tab": "새 탭에서 열기"
},
"list": {
"empty": "알림이 없습니다",
diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.json
index bcb7601301..5d40ab3eba 100644
--- a/packages/views/locales/ko/settings.json
+++ b/packages/views/locales/ko/settings.json
@@ -77,10 +77,6 @@
"sticky_comment_bar": {
"title": "댓글 입력창 고정",
"hint": "태스크 페이지를 스크롤할 때 댓글 입력창을 항상 하단에 고정합니다."
- },
- "issue_link_new_tab": {
- "title": "태스크 링크를 새 탭에서 열기",
- "hint": "설명, 댓글, 채팅의 태스크 링크를 현재 페이지에서 이동하지 않고 새 탭에서 엽니다."
}
},
"shortcuts": {
diff --git a/packages/views/locales/zh-Hans/common.json b/packages/views/locales/zh-Hans/common.json
index 716d250add..569c3cba94 100644
--- a/packages/views/locales/zh-Hans/common.json
+++ b/packages/views/locales/zh-Hans/common.json
@@ -105,5 +105,8 @@
"error_already_bound": "该企业微信身份已关联到其他 Multica 用户。账户转移需要先显式解绑。",
"error_not_member": "你登录的 Multica 账号不是当前工作区成员。",
"error_unknown": "出现未知错误。请稍后再试,如反复失败请联系工作区管理员。"
+ },
+ "navigation": {
+ "open_in_new_tab": "在新标签页打开"
}
}
diff --git a/packages/views/locales/zh-Hans/inbox.json b/packages/views/locales/zh-Hans/inbox.json
index e25b7a5168..9e73767174 100644
--- a/packages/views/locales/zh-Hans/inbox.json
+++ b/packages/views/locales/zh-Hans/inbox.json
@@ -13,7 +13,8 @@
"mark_read": "标为已读",
"mark_unread": "标为未读",
"archive": "归档",
- "unarchive": "取消归档"
+ "unarchive": "取消归档",
+ "open_in_new_tab": "在新标签页打开"
},
"list": {
"empty": "暂无通知",
diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.json
index 3710d3964e..28cd666a0d 100644
--- a/packages/views/locales/zh-Hans/settings.json
+++ b/packages/views/locales/zh-Hans/settings.json
@@ -77,10 +77,6 @@
"sticky_comment_bar": {
"title": "固定评论栏",
"hint": "滚动任务页面时,评论栏始终固定在底部。"
- },
- "issue_link_new_tab": {
- "title": "在新标签页打开任务链接",
- "hint": "点击描述、评论或聊天中的任务链接时,在新标签页中打开,而不是在当前页面跳转。"
}
},
"shortcuts": {
diff --git a/packages/views/modals/create-issue.test.tsx b/packages/views/modals/create-issue.test.tsx
index 2f7d3e6c9e..b47d40027a 100644
--- a/packages/views/modals/create-issue.test.tsx
+++ b/packages/views/modals/create-issue.test.tsx
@@ -1,4 +1,12 @@
-import { forwardRef, useImperativeHandle, useRef, useState, type ReactNode } from "react";
+import {
+ cloneElement,
+ forwardRef,
+ useImperativeHandle,
+ useRef,
+ useState,
+ type ReactElement,
+ type ReactNode,
+} from "react";
import { describe, it, expect, vi, beforeEach } from "vitest";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
@@ -139,7 +147,9 @@ const mockCreateSettingsStore = {
// the same or the two records drift apart only in tests.
let mockUploadIdSeq = 0;
-vi.mock("../navigation", () => ({
+// Mocked at the context module rather than the barrel so <AppLink> stays the
+// real component and its click contract is what the test exercises.
+vi.mock("../navigation/context", () => ({
useNavigation: () => ({ push: mockPush }),
}));
@@ -454,9 +464,23 @@ vi.mock("@multica/ui/components/ui/dropdown-menu", () => ({
DropdownMenu: ({ children }: { children: React.ReactNode }) => <>{children}</>,
DropdownMenuTrigger: ({ render }: { render: React.ReactNode }) => <>{render}</>,
DropdownMenuContent: ({ children }: { children: React.ReactNode }) => <>{children}</>,
- DropdownMenuItem: ({ children, onClick }: { children: React.ReactNode; onClick?: () => void }) => (
- <button type="button" onClick={onClick}>{children}</button>
- ),
+ // `render` mirrors Base UI: an item can BE another element (an <AppLink>).
+ // The real Item gives that element role="button", which is what the queries
+ // below match on.
+ DropdownMenuItem: ({
+ children,
+ onClick,
+ render,
+ }: {
+ children: React.ReactNode;
+ onClick?: () => void;
+ render?: ReactElement<{ role?: string; children?: ReactNode }>;
+ }) =>
+ render ? (
+ cloneElement(render, { role: "button" }, children)
+ ) : (
+ <button type="button" onClick={onClick}>{children}</button>
+ ),
DropdownMenuSeparator: () => null,
DropdownMenuSub: ({ children }: { children: React.ReactNode }) => <>{children}</>,
DropdownMenuSubTrigger: ({ children }: { children: React.ReactNode }) => <>{children}</>,
diff --git a/packages/views/modals/create-issue.tsx b/packages/views/modals/create-issue.tsx
index 24406458f6..a656006c5d 100644
--- a/packages/views/modals/create-issue.tsx
+++ b/packages/views/modals/create-issue.tsx
@@ -2,7 +2,7 @@
import { useState, useRef, useEffect, useLayoutEffect } from "react";
import { useQuery } from "@tanstack/react-query";
-import { useNavigation } from "../navigation";
+import { AppLink, resolveClickIntent, useNavigation } from "../navigation";
import {
AlertTriangle,
ArrowDown,
@@ -384,14 +384,6 @@ export function ManualCreatePanel({
start_date: manualFields.includes("start_date") || startDate !== null || startDatePickerOpen,
};
- // Field visibility lives in Settings → Issue; the modal closes first so the
- // dialog doesn't linger over the settings page. The draft store already
- // holds everything typed, so nothing is lost across the round-trip.
- const openFieldSettings = () => {
- onClose();
- router.push(`${p.settings()}?tab=issue`);
- };
-
const createIssueMutation = useCreateIssue();
const updateIssueMutation = useUpdateIssue();
const attachLabelMutation = useAttachLabelToIssue();
@@ -592,6 +584,9 @@ export function ManualCreatePanel({
<StatusIcon status={issue.status} className="size-3.5 shrink-0" />
<span className="truncate">{issue.identifier} – {issue.title}</span>
</div>
+ {/* Not an AppLink: sonner renders toast content under <Toaster />,
+ which is mounted outside NavigationProvider, so useNavigation()
+ would throw here. */}
<button
type="button"
className="ml-7 mt-2 text-body text-primary hover:underline cursor-pointer"
@@ -633,6 +628,8 @@ export function ManualCreatePanel({
<div className="flex items-center gap-2 text-body text-muted-foreground ml-7">
<span className="truncate">{dup.issue.identifier} – {dup.issue.title}</span>
</div>
+ {/* See the created-issue toast above: toast content lives
+ outside NavigationProvider, so this stays a button. */}
<button
type="button"
className="ml-7 mt-2 text-body text-primary hover:underline cursor-pointer"
@@ -1183,7 +1180,24 @@ export function ManualCreatePanel({
</DropdownMenuSub>
)}
<DropdownMenuSeparator />
- <DropdownMenuItem onClick={openFieldSettings}>
+ {/* Field visibility lives in Settings → Issue; the modal
+ closes first so the dialog doesn't linger over the
+ settings page. The draft store already holds everything
+ typed, so nothing is lost across the round-trip. */}
+ <DropdownMenuItem
+ render={
+ <AppLink
+ href={`${p.settings()}?tab=issue`}
+ onClick={(e) => {
+ // A modifier click opens Settings in another tab —
+ // the modal (and the draft in it) stays put. Only
+ // an in-place navigation closes it.
+ if (resolveClickIntent(e) !== "push") return;
+ onClose();
+ }}
+ />
+ }
+ >
<Settings2 className="h-3.5 w-3.5" />
{t(($) => $.create_issue.customize_fields)}
</DropdownMenuItem>
diff --git a/packages/views/modals/quick-create-issue.test.tsx b/packages/views/modals/quick-create-issue.test.tsx
index 7a54aa1393..6aa04d22b2 100644
--- a/packages/views/modals/quick-create-issue.test.tsx
+++ b/packages/views/modals/quick-create-issue.test.tsx
@@ -1,4 +1,12 @@
-import { forwardRef, useImperativeHandle, useRef, useState, type ReactNode } from "react";
+import {
+ cloneElement,
+ forwardRef,
+ useImperativeHandle,
+ useRef,
+ useState,
+ type ReactElement,
+ type ReactNode,
+} from "react";
import { describe, it, expect, vi, beforeEach } from "vitest";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
@@ -135,7 +143,9 @@ vi.mock("@multica/core/paths", () => ({
}),
}));
-vi.mock("../navigation", () => ({
+// Mocked at the context module rather than the barrel so <AppLink> stays the
+// real component and its click contract is what the test exercises.
+vi.mock("../navigation/context", () => ({
useNavigation: () => ({ push: mockNavigationPush }),
}));
@@ -228,9 +238,22 @@ vi.mock("@multica/ui/components/ui/dropdown-menu", () => ({
DropdownMenu: ({ children }: { children: ReactNode }) => <>{children}</>,
DropdownMenuTrigger: ({ render }: { render: ReactNode }) => <>{render}</>,
DropdownMenuContent: ({ children }: { children: ReactNode }) => <>{children}</>,
- DropdownMenuItem: ({ children, onClick }: any) => (
- <button type="button" onClick={onClick}>{children}</button>
- ),
+ // `render` mirrors Base UI: an item can BE another element (an <AppLink>).
+ // The real Item gives that element role="button", which the queries match.
+ DropdownMenuItem: ({
+ children,
+ onClick,
+ render,
+ }: {
+ children: ReactNode;
+ onClick?: () => void;
+ render?: ReactElement<{ role?: string; children?: ReactNode }>;
+ }) =>
+ render ? (
+ cloneElement(render, { role: "button" }, children)
+ ) : (
+ <button type="button" onClick={onClick}>{children}</button>
+ ),
DropdownMenuSeparator: () => null,
}));
diff --git a/packages/views/modals/quick-create-issue.tsx b/packages/views/modals/quick-create-issue.tsx
index b8104def11..1e0b203870 100644
--- a/packages/views/modals/quick-create-issue.tsx
+++ b/packages/views/modals/quick-create-issue.tsx
@@ -28,7 +28,7 @@ import { Switch } from "@multica/ui/components/ui/switch";
import { api, ApiError } from "@multica/core/api";
import { useWorkspaceId } from "@multica/core/hooks";
import { useCurrentWorkspace, useWorkspacePaths } from "@multica/core/paths";
-import { useNavigation } from "../navigation";
+import { AppLink, resolveClickIntent } from "../navigation";
import { agentListOptions, squadListOptions } from "@multica/core/workspace/queries";
import { projectListOptions } from "@multica/core/projects/queries";
import {
@@ -119,7 +119,6 @@ export function AgentCreatePanel({
const sendShortcut = useShortcut("send");
const workspaceName = useCurrentWorkspace()?.name;
const workspacePaths = useWorkspacePaths();
- const navigation = useNavigation();
const wsId = useWorkspaceId();
const userId = useAuthStore((s) => s.user?.id);
const { data: members = [] } = useQuery(memberListOptions(wsId));
@@ -532,10 +531,13 @@ export function AgentCreatePanel({
// Field visibility lives in Settings → Issue. Persist the prompt draft
// before leaving so what the user typed survives the round-trip, then
// close — the dialog would otherwise linger over the settings page.
- const openFieldSettings = () => {
+ const openFieldSettings = (e: React.MouseEvent) => {
+ // Persist the draft either way, but only an in-place navigation closes
+ // the dialog — a modifier click opens Settings in another tab and the
+ // modal stays put.
setAgent({ prompt: editorRef.current?.getMarkdown() ?? "" });
+ if (resolveClickIntent(e) !== "push") return;
onClose();
- navigation.push(`${workspacePaths.settings()}?tab=issue`);
};
return (
@@ -731,7 +733,14 @@ export function AgentCreatePanel({
</DropdownMenuItem>
)}
<DropdownMenuSeparator />
- <DropdownMenuItem onClick={openFieldSettings}>
+ <DropdownMenuItem
+ render={
+ <AppLink
+ href={`${workspacePaths.settings()}?tab=issue`}
+ onClick={openFieldSettings}
+ />
+ }
+ >
<Settings2 className="size-3.5 text-muted-foreground" />
{t(($) => $.create_issue.agent.customize_fields)}
</DropdownMenuItem>
diff --git a/packages/views/navigation/app-link.test.tsx b/packages/views/navigation/app-link.test.tsx
index 0cd22bf0b2..09f4fd6ec2 100644
--- a/packages/views/navigation/app-link.test.tsx
+++ b/packages/views/navigation/app-link.test.tsx
@@ -99,6 +99,42 @@ describe("AppLink", () => {
expect(openInNewTab).toHaveBeenCalledWith("/issues", "MUL-7");
});
+ it("cmd+shift-click opens a FOREGROUND tab (activate) — the spec's 'take me there' modifier", () => {
+ const push = vi.fn();
+ const openInNewTab = vi.fn();
+ const adapter = makeAdapter({ push, openInNewTab });
+
+ renderLink(adapter);
+ fireEvent.click(screen.getByText("go"), { metaKey: true, shiftKey: true });
+ expect(openInNewTab).toHaveBeenCalledWith("/issues", undefined, {
+ activate: true,
+ });
+ expect(push).not.toHaveBeenCalled();
+ });
+
+ it("shift-alone click on desktop is a plain click (in-place push) — shift is not a spec modifier", () => {
+ const push = vi.fn();
+ const openInNewTab = vi.fn();
+ const adapter = makeAdapter({ push, openInNewTab });
+
+ renderLink(adapter);
+ fireEvent.click(screen.getByText("go"), { shiftKey: true });
+ expect(push).toHaveBeenCalledWith("/issues");
+ expect(openInNewTab).not.toHaveBeenCalled();
+ });
+
+ it("shift-alone click without an adapter (web) is left to the browser's native new-window handling", () => {
+ const push = vi.fn();
+ const adapter = makeAdapter({ push });
+
+ renderLink(adapter);
+ const defaultNotPrevented = fireEvent.click(screen.getByText("go"), {
+ shiftKey: true,
+ });
+ expect(defaultNotPrevented).toBe(true);
+ expect(push).not.toHaveBeenCalled();
+ });
+
describe("target=_blank (open-in-new-tab links)", () => {
it("plain click opens a foreground new tab via the adapter (desktop) and does NOT push", () => {
const push = vi.fn();
@@ -285,7 +321,7 @@ describe("AppLink", () => {
it("a caller-supplied onClick passed via spread cannot silently override the navigation handler", () => {
const push = vi.fn();
const adapter = makeAdapter({ push });
- const spreadOnClick = vi.fn((e: React.MouseEvent) => e.preventDefault());
+ const spreadOnClick = vi.fn();
render(
<NavigationProvider value={adapter}>
@@ -297,8 +333,50 @@ describe("AppLink", () => {
);
fireEvent.click(screen.getByText("go"));
- // Caller still runs (it was hoisted into the named param), but push runs too.
+ // Caller still runs (it was hoisted into the named param), and push runs too.
expect(spreadOnClick).toHaveBeenCalled();
expect(push).toHaveBeenCalledWith("/issues");
});
+
+ describe("caller opt-out via preventDefault (drag guards, permission gates)", () => {
+ it("onClick calling preventDefault cancels the in-place push", () => {
+ const push = vi.fn();
+ const adapter = makeAdapter({ push });
+
+ renderLink(adapter, {
+ href: "/issues",
+ onClick: (e) => e.preventDefault(),
+ });
+ fireEvent.click(screen.getByText("go"));
+ expect(push).not.toHaveBeenCalled();
+ });
+
+ it("onClick calling preventDefault cancels a modifier-click new tab too", () => {
+ const push = vi.fn();
+ const openInNewTab = vi.fn();
+ const adapter = makeAdapter({ push, openInNewTab });
+
+ renderLink(adapter, {
+ href: "/issues",
+ onClick: (e) => e.preventDefault(),
+ });
+ fireEvent.click(screen.getByText("go"), { metaKey: true });
+ expect(openInNewTab).not.toHaveBeenCalled();
+ expect(push).not.toHaveBeenCalled();
+ });
+
+ it("onClick runs before a modifier-click open, so side effects (close menu) still land", () => {
+ const order: string[] = [];
+ const adapter = makeAdapter({
+ openInNewTab: vi.fn(() => order.push("openInNewTab")),
+ });
+
+ renderLink(adapter, {
+ href: "/issues",
+ onClick: () => order.push("onClick"),
+ });
+ fireEvent.click(screen.getByText("go"), { metaKey: true });
+ expect(order).toEqual(["onClick", "openInNewTab"]);
+ });
+ });
});
diff --git a/packages/views/navigation/app-link.tsx b/packages/views/navigation/app-link.tsx
index e03a39f83c..fd7eea1c7f 100644
--- a/packages/views/navigation/app-link.tsx
+++ b/packages/views/navigation/app-link.tsx
@@ -1,6 +1,7 @@
"use client";
import { forwardRef } from "react";
+import { resolveClickIntent } from "./click-intent";
import { useNavigation } from "./context";
interface AppLinkProps extends React.AnchorHTMLAttributes<HTMLAnchorElement> {
@@ -31,16 +32,37 @@ export const AppLink = forwardRef<HTMLAnchorElement, AppLinkProps>(
const { push, openInNewTab, prefetch } = useNavigation();
const handleClick = (e: React.MouseEvent<HTMLAnchorElement>) => {
- if (e.metaKey || e.ctrlKey || e.shiftKey) {
+ // Caller's onClick runs BEFORE any navigation, on every path, so:
+ // - synchronous side effects (close popover, clear selection, blur
+ // the trigger) land in the same tick rather than getting deferred
+ // behind the transition, and
+ // - calling preventDefault() inside it cancels the navigation
+ // entirely — the escape hatch drag guards and permission gates
+ // need, and the same one onAuxClick already offers.
+ onClick?.(e);
+ if (e.defaultPrevented) return;
+ const intent = resolveClickIntent(e);
+ if (intent !== "push") {
if (openInNewTab) {
e.preventDefault();
- openInNewTab(href, newTabTitle);
+ if (intent === "foreground-tab") {
+ openInNewTab(href, newTabTitle, { activate: true });
+ } else {
+ openInNewTab(href, newTabTitle);
+ }
}
+ // Web: no adapter — the browser's native anchor handling already
+ // implements the spec (cmd = background tab, cmd+shift = foreground).
+ return;
+ }
+ if (e.shiftKey && !openInNewTab) {
+ // Web shift-click is the browser's "new window". Shift alone is not a
+ // spec modifier (it resolves to "push"), but fighting the native
+ // behavior with an in-place push would swallow a deliberate gesture.
+ // Desktop has no native path, so it falls through to a plain push.
return;
}
if (target === "_blank") {
- // Caller's onClick runs first — same contract as the push path below.
- onClick?.(e);
if (openInNewTab) {
// Desktop: foreground app tab. target="_blank" carries "take me
// there" intent, matching the browser's foreground-tab behavior.
@@ -52,10 +74,6 @@ export const AppLink = forwardRef<HTMLAnchorElement, AppLinkProps>(
return;
}
e.preventDefault();
- // Caller's onClick runs BEFORE push so any synchronous side effect
- // (close popover, clear selection, blur the trigger) lands in the
- // same tick rather than getting deferred behind the transition.
- onClick?.(e);
push(href);
};
diff --git a/packages/views/navigation/click-intent.ts b/packages/views/navigation/click-intent.ts
new file mode 100644
index 0000000000..4f8bf2e315
--- /dev/null
+++ b/packages/views/navigation/click-intent.ts
@@ -0,0 +1,26 @@
+/**
+ * The one place a mouse event is mapped to a navigation intent, per the
+ * navigation behavior spec:
+ *
+ * plain click -> "push" (navigate in place)
+ * cmd/ctrl + click -> "background-tab" (open tab, keep focus here)
+ * cmd/ctrl + shift -> "foreground-tab" (open tab, move focus there)
+ * middle click -> "background-tab"
+ *
+ * Shift alone is deliberately NOT a modifier: browsers disagree about it
+ * (Chrome/Firefox open a new window, Safari adds to Reading List), so it maps
+ * to "push". On web, surfaces that render a real anchor should leave any
+ * modified click to the browser instead of consulting this function — native
+ * handling is the only way to get a true background tab there.
+ */
+export type LinkClickIntent = "push" | "background-tab" | "foreground-tab";
+
+export function resolveClickIntent(
+ e: Pick<MouseEvent, "button" | "metaKey" | "ctrlKey" | "shiftKey">,
+): LinkClickIntent {
+ if (e.button === 1) return "background-tab";
+ if (e.metaKey || e.ctrlKey) {
+ return e.shiftKey ? "foreground-tab" : "background-tab";
+ }
+ return "push";
+}
diff --git a/packages/views/navigation/index.ts b/packages/views/navigation/index.ts
index ba3cd06599..9d6e0dc083 100644
--- a/packages/views/navigation/index.ts
+++ b/packages/views/navigation/index.ts
@@ -1,10 +1,14 @@
export {
NavigationProvider,
useNavigation,
+ useOptionalNavigation,
useIsNavigating,
} from "./context";
export { AppLink } from "./app-link";
+export { resolveClickIntent } from "./click-intent";
+export type { LinkClickIntent } from "./click-intent";
export { useAppOrigin } from "./use-app-origin";
export { useRowLink } from "./use-row-link";
+export { useIntentNavigate } from "./use-intent-navigate";
export { useBackOrReplace } from "./use-back-or-replace";
export type { NavigationAdapter } from "./types";
diff --git a/packages/views/navigation/use-intent-navigate.ts b/packages/views/navigation/use-intent-navigate.ts
new file mode 100644
index 0000000000..49e31152a5
--- /dev/null
+++ b/packages/views/navigation/use-intent-navigate.ts
@@ -0,0 +1,40 @@
+"use client";
+
+import { useCallback } from "react";
+import type { LinkClickIntent } from "./click-intent";
+import { useNavigation } from "./context";
+
+/**
+ * Imperative sibling of AppLink / useRowLink for surfaces that receive the
+ * mouse event through a callback (DataTable rows, command palette items)
+ * instead of owning an anchor element: executes a resolved click intent
+ * against the navigation adapter.
+ *
+ * Same platform semantics as useRowLink: desktop routes tab intents through
+ * `openInNewTab` (background or foreground); web falls back to `window.open`
+ * on the shareable URL — always a foreground browser tab, since JS cannot
+ * open a background one.
+ */
+export function useIntentNavigate() {
+ const navigation = useNavigation();
+
+ return useCallback(
+ (href: string, intent: LinkClickIntent, newTabTitle?: string) => {
+ const { push, openInNewTab, getShareableUrl } = navigation;
+ if (intent === "push") {
+ push(href);
+ return;
+ }
+ if (openInNewTab) {
+ if (intent === "foreground-tab") {
+ openInNewTab(href, newTabTitle, { activate: true });
+ } else {
+ openInNewTab(href, newTabTitle);
+ }
+ return;
+ }
+ window.open(getShareableUrl(href), "_blank", "noopener,noreferrer");
+ },
+ [navigation],
+ );
+}
diff --git a/packages/views/navigation/use-row-link.test.tsx b/packages/views/navigation/use-row-link.test.tsx
index 3fd5bfb7cf..0d6591e654 100644
--- a/packages/views/navigation/use-row-link.test.tsx
+++ b/packages/views/navigation/use-row-link.test.tsx
@@ -61,11 +61,47 @@ describe("useRowLink", () => {
fireEvent.click(screen.getByRole("row"), { ctrlKey: true });
expect(openInNewTab).toHaveBeenCalledTimes(2);
- expect(openInNewTab).toHaveBeenNthCalledWith(1, "/acme/projects/p1");
- expect(openInNewTab).toHaveBeenNthCalledWith(2, "/acme/projects/p1");
+ expect(openInNewTab).toHaveBeenNthCalledWith(1, "/acme/projects/p1", undefined);
+ expect(openInNewTab).toHaveBeenNthCalledWith(2, "/acme/projects/p1", undefined);
expect(push).not.toHaveBeenCalled();
});
+ it("opens a foreground tab for cmd+shift click (spec's 'take me there' modifier)", () => {
+ const push = vi.fn();
+ const openInNewTab = vi.fn();
+ const adapter = makeAdapter({ push, openInNewTab });
+
+ renderProbe(adapter);
+ fireEvent.click(screen.getByRole("row"), { metaKey: true, shiftKey: true });
+
+ expect(openInNewTab).toHaveBeenCalledWith("/acme/projects/p1", undefined, {
+ activate: true,
+ });
+ expect(push).not.toHaveBeenCalled();
+ });
+
+ it("passes newTabTitle through as the desktop tab label", () => {
+ const openInNewTab = vi.fn();
+ const adapter = makeAdapter({ openInNewTab });
+
+ function TitledProbe() {
+ const rowLink = useRowLink();
+ return (
+ <div role="row" {...rowLink("/acme/projects/p1", "Roadmap")}>
+ row
+ </div>
+ );
+ }
+ render(
+ <NavigationProvider value={adapter}>
+ <TitledProbe />
+ </NavigationProvider>,
+ );
+ fireEvent.click(screen.getByRole("row"), { metaKey: true });
+
+ expect(openInNewTab).toHaveBeenCalledWith("/acme/projects/p1", "Roadmap");
+ });
+
// Web has no adapter, and the row is a <div> — there is no native
// modifier-click behaviour to inherit, so without an explicit window.open
// the row would navigate in place and swallow the user's intent (MUL-5456).
@@ -111,7 +147,7 @@ describe("useRowLink", () => {
screen.getByRole("row").dispatchEvent(event);
expect(event.defaultPrevented).toBe(true);
- expect(openInNewTab).toHaveBeenCalledWith("/acme/projects/p1");
+ expect(openInNewTab).toHaveBeenCalledWith("/acme/projects/p1", undefined);
expect(push).not.toHaveBeenCalled();
});
diff --git a/packages/views/navigation/use-row-link.ts b/packages/views/navigation/use-row-link.ts
index 7ee2ba664e..0c6381fcd4 100644
--- a/packages/views/navigation/use-row-link.ts
+++ b/packages/views/navigation/use-row-link.ts
@@ -1,6 +1,7 @@
"use client";
import { useCallback } from "react";
+import { resolveClickIntent, type LinkClickIntent } from "./click-intent";
import { useNavigation } from "./context";
/**
@@ -16,12 +17,17 @@ import { useNavigation } from "./context";
* second entry point). Interactive cells (checkbox, kebab, inline editors)
* call `stopPropagation` so clicking them never reaches these handlers.
*
- * Mirrors AppLink's modifier semantics: a plain left click pushes; cmd/ctrl
- * (or a middle click) opens a background tab on desktop. On web there is no
- * adapter and — because the row is a `<div>`, not an `<a>` — no native
- * modifier-click behaviour to inherit either, so the browser tab is opened
- * here against the shareable URL. Without that fallback a modifier or middle
- * click would silently navigate in place.
+ * Mirrors AppLink's modifier semantics via `resolveClickIntent`: a plain left
+ * click pushes; cmd/ctrl (or a middle click) opens a background tab on
+ * desktop; cmd/ctrl+shift opens a foreground tab. On web there is no adapter
+ * and — because the row is a `<div>`, not an `<a>` — no native modifier-click
+ * behaviour to inherit either, so the browser tab is opened here against the
+ * shareable URL (always foreground: JS cannot open a background browser tab).
+ * Without that fallback a modifier or middle click would silently navigate in
+ * place.
+ *
+ * `newTabTitle` labels the desktop tab a modifier/middle click creates until
+ * the tab bar resolves the real title from the URL.
*
* Callers add `cursor-pointer` to the row's own className (kept out of the
* returned props so it can't clash with the row's existing className).
@@ -30,14 +36,18 @@ export function useRowLink() {
const { push, openInNewTab, prefetch, getShareableUrl } = useNavigation();
return useCallback(
- (href: string) => {
- const open = (newTab: boolean) => {
- if (!newTab) {
+ (href: string, newTabTitle?: string) => {
+ const open = (intent: LinkClickIntent) => {
+ if (intent === "push") {
push(href);
return;
}
if (openInNewTab) {
- openInNewTab(href);
+ if (intent === "foreground-tab") {
+ openInNewTab(href, newTabTitle, { activate: true });
+ } else {
+ openInNewTab(href, newTabTitle);
+ }
return;
}
window.open(getShareableUrl(href), "_blank", "noopener,noreferrer");
@@ -48,12 +58,12 @@ export function useRowLink() {
// stopPropagation and never reach here; defaultPrevented guards
// any that preventDefault instead).
if (e.defaultPrevented || e.button !== 0) return;
- open(e.metaKey || e.ctrlKey);
+ open(resolveClickIntent(e));
},
onAuxClick: (e: React.MouseEvent) => {
if (e.defaultPrevented || e.button !== 1) return; // middle click
e.preventDefault();
- open(true);
+ open("background-tab");
},
onMouseEnter: () => prefetch?.(href),
};
diff --git a/packages/views/projects/components/projects-page.test.tsx b/packages/views/projects/components/projects-page.test.tsx
index 1787c6a3a9..cb0b6162e7 100644
--- a/packages/views/projects/components/projects-page.test.tsx
+++ b/packages/views/projects/components/projects-page.test.tsx
@@ -303,9 +303,9 @@ describe("ProjectsPage compact row navigation", () => {
expect(middleClick.defaultPrevented).toBe(true);
expect(openInNewTab).toHaveBeenCalledTimes(3);
- expect(openInNewTab).toHaveBeenNthCalledWith(1, "/test-workspace/projects/project-1");
- expect(openInNewTab).toHaveBeenNthCalledWith(2, "/test-workspace/projects/project-1");
- expect(openInNewTab).toHaveBeenNthCalledWith(3, "/test-workspace/projects/project-1");
+ expect(openInNewTab).toHaveBeenNthCalledWith(1, "/test-workspace/projects/project-1", "Launch Plan");
+ expect(openInNewTab).toHaveBeenNthCalledWith(2, "/test-workspace/projects/project-1", "Launch Plan");
+ expect(openInNewTab).toHaveBeenNthCalledWith(3, "/test-workspace/projects/project-1", "Launch Plan");
expect(push).not.toHaveBeenCalled();
});
diff --git a/packages/views/projects/components/projects-page.tsx b/packages/views/projects/components/projects-page.tsx
index 0563bda186..da1c932eb1 100644
--- a/packages/views/projects/components/projects-page.tsx
+++ b/packages/views/projects/components/projects-page.tsx
@@ -5,6 +5,7 @@ import {
ArrowDown,
ArrowUp,
ChevronDown,
+ ExternalLink,
Filter,
FolderKanban,
LayoutGrid,
@@ -40,7 +41,7 @@ import { useAuthStore } from "@multica/core/auth";
import { useActorName } from "@multica/core/workspace/hooks";
import { memberListOptions } from "@multica/core/workspace/queries";
import { useModalStore } from "@multica/core/modals";
-import { AppLink, useRowLink } from "../../navigation";
+import { AppLink, useIntentNavigate, useRowLink } from "../../navigation";
import { ActorAvatar } from "../../common/actor-avatar";
import { FILTER_ITEM_CLASS, HoverCheck } from "../../common/hover-check";
import { Skeleton } from "@multica/ui/components/ui/skeleton";
@@ -228,6 +229,9 @@ function ProjectRowActions({
canDelete: boolean;
}) {
const { t } = useT("projects");
+ const { t: tCommon } = useT("common");
+ const wsPaths = useWorkspacePaths();
+ const intentNavigate = useIntentNavigate();
const createPin = useCreatePin();
const deletePin = useDeletePin();
const deleteProject = useDeleteProject();
@@ -253,6 +257,19 @@ function ProjectRowActions({
}
/>
<DropdownMenuContent align="end" className="w-44">
+ <DropdownMenuItem
+ onClick={() =>
+ intentNavigate(
+ wsPaths.projectDetail(project.id),
+ "foreground-tab",
+ project.title,
+ )
+ }
+ >
+ <ExternalLink className="size-3.5" />
+ {tCommon(($) => $.navigation.open_in_new_tab)}
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
<DropdownMenuItem onClick={togglePin}>
{pinned ? (
<PinOff className="size-3.5" />
@@ -372,7 +389,7 @@ function ProjectTableRow({
return (
<ListGridRow
className={`h-11 cursor-pointer ${selected ? "bg-accent/30" : ""}`}
- {...rowLink(rowHref)}
+ {...rowLink(rowHref, project.title)}
>
<CheckboxCell checked={selected} onToggle={onToggleSelect} />
<ListGridCell className="gap-2">
diff --git a/packages/views/rich-content/app-url-link-routing.test.tsx b/packages/views/rich-content/app-url-link-routing.test.tsx
index 010137e920..7efd902a0e 100644
--- a/packages/views/rich-content/app-url-link-routing.test.tsx
+++ b/packages/views/rich-content/app-url-link-routing.test.tsx
@@ -32,6 +32,8 @@ vi.mock("@multica/core/paths", async (importOriginal) => ({
vi.mock("../navigation", () => ({
useNavigation: () => ({ push: vi.fn(), openInNewTab: vi.fn() }),
+ useOptionalNavigation: () => ({ push: vi.fn(), openInNewTab: vi.fn() }),
+ resolveClickIntent: () => "push",
useAppOrigin: () => APP_ORIGIN,
AppLink: ({ href, children }: { href: string; children: React.ReactNode }) => (
<a href={href}>{children}</a>
diff --git a/packages/views/rich-content/cdn-config-reactivity.test.tsx b/packages/views/rich-content/cdn-config-reactivity.test.tsx
index d4424c44bb..c7d75731f5 100644
--- a/packages/views/rich-content/cdn-config-reactivity.test.tsx
+++ b/packages/views/rich-content/cdn-config-reactivity.test.tsx
@@ -44,6 +44,8 @@ vi.mock("@multica/core/paths", () => ({
vi.mock("../navigation", () => ({
useNavigation: () => ({ push: vi.fn(), openInNewTab: vi.fn() }),
+ useOptionalNavigation: () => ({ push: vi.fn(), openInNewTab: vi.fn() }),
+ resolveClickIntent: () => "push",
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.tsx
index d70a7c1c12..8425c59097 100644
--- a/packages/views/rich-content/rich-content-parity.test.tsx
+++ b/packages/views/rich-content/rich-content-parity.test.tsx
@@ -54,6 +54,8 @@ vi.mock("@multica/core/paths", () => ({
vi.mock("../navigation", () => ({
useNavigation: () => ({ push: vi.fn(), openInNewTab: vi.fn() }),
+ useOptionalNavigation: () => ({ push: vi.fn(), openInNewTab: vi.fn() }),
+ resolveClickIntent: () => "push",
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.tsx
index 9f0f469666..34f0371f96 100644
--- a/packages/views/rich-content/rich-content.tsx
+++ b/packages/views/rich-content/rich-content.tsx
@@ -48,7 +48,11 @@ import {
markdownSanitizeSchema,
markdownUrlTransform,
} from "@multica/ui/markdown";
-import { useAppOrigin } from "../navigation";
+import {
+ resolveClickIntent,
+ useAppOrigin,
+ useOptionalNavigation,
+} from "../navigation";
import { IssueMentionCard } from "../issues/components/issue-mention-card";
import { useResolveIssueIdentifier } from "../issues/hooks";
import { ProjectMentionCard } from "../projects/components/project-mention-card";
@@ -200,6 +204,11 @@ function unfurlableEntityLink(
function RichLink({ href, children }: { href?: string; children?: ReactNode }) {
const slug = useWorkspaceSlug();
const appOrigin = useAppOrigin();
+ // Platform probe only: `openInNewTab` present means desktop, where native
+ // anchor behavior is a dead end and every click must be intercepted. Absent
+ // (web), modified clicks are left to the browser — the only way to get a
+ // real background tab.
+ const desktopTabs = !!useOptionalNavigation()?.openInNewTab;
if (href?.startsWith("slash://skill/")) {
return <span className="slash-command">{children}</span>;
@@ -235,8 +244,22 @@ function RichLink({ href, children }: { href?: string; children?: ReactNode }) {
<a
href={href}
onClick={(e) => {
+ if (!href) {
+ e.preventDefault();
+ return;
+ }
+ if (!desktopTabs && (e.metaKey || e.ctrlKey || e.shiftKey)) return;
+ e.preventDefault();
+ openLink(href, slug, appOrigin, resolveClickIntent(e));
+ }}
+ onAuxClick={(e) => {
+ if (e.button !== 1 || !href) return;
+ // Web: native middle click on a real anchor already opens a
+ // background tab. Desktop: the native window-open request dead-ends
+ // (denied, then dropped by the http/https allowlist), so route it.
+ if (!desktopTabs) return;
e.preventDefault();
- if (href) openLink(href, slug, appOrigin);
+ openLink(href, slug, appOrigin, "background-tab");
}}
>
{children}
diff --git a/packages/views/runtimes/components/runtime-detail-page.tsx b/packages/views/runtimes/components/runtime-detail-page.tsx
index f134f110e8..2639b7abd0 100644
--- a/packages/views/runtimes/components/runtime-detail-page.tsx
+++ b/packages/views/runtimes/components/runtime-detail-page.tsx
@@ -16,7 +16,7 @@ import {
} from "@multica/core/workspace/queries";
import { Button } from "@multica/ui/components/ui/button";
import { Skeleton } from "@multica/ui/components/ui/skeleton";
-import { AppLink, useNavigation } from "../../navigation";
+import { AppLink } from "../../navigation";
import { buildWorkloadIndex, RuntimeList } from "./runtime-list";
import {
buildRuntimeMachines,
@@ -88,7 +88,6 @@ export function RuntimeDetailPage({
const { t } = useT("runtimes");
const wsId = useWorkspaceId();
const paths = useWorkspacePaths();
- const navigation = useNavigation();
const qc = useQueryClient();
const healthLabel = useHealthLabel();
const timeAgo = useTimeAgo();
@@ -191,7 +190,11 @@ export function RuntimeDetailPage({
{t(($) => $.machine.not_found_hint)}
</p>
</div>
- <Button size="sm" onClick={() => navigation.push(paths.runtimes())}>
+ <Button
+ size="sm"
+ render={<AppLink href={paths.runtimes()} />}
+ nativeButton={false}
+ >
{t(($) => $.detail.all_runtimes)}
</Button>
</div>
diff --git a/packages/views/runtimes/components/runtime-list.tsx b/packages/views/runtimes/components/runtime-list.tsx
index b785a7ee1f..d8424526f9 100644
--- a/packages/views/runtimes/components/runtime-list.tsx
+++ b/packages/views/runtimes/components/runtime-list.tsx
@@ -3,6 +3,7 @@
import { useMemo, useState } from "react";
import {
AlertTriangle,
+ ExternalLink,
Globe,
Loader2,
MoreHorizontal,
@@ -36,6 +37,7 @@ import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
+ DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@multica/ui/components/ui/dropdown-menu";
import {
@@ -50,7 +52,7 @@ import {
TooltipContent,
TooltipTrigger,
} from "@multica/ui/components/ui/tooltip";
-import { useRowLink } from "../../navigation";
+import { useIntentNavigate, useRowLink } from "../../navigation";
import { ActorAvatar } from "../../common/actor-avatar";
import { useViewingTimezone } from "../../common/use-viewing-timezone";
import { ProviderLogo } from "./provider-logo";
@@ -533,18 +535,26 @@ export function RuntimeRowMenu({
profile,
wsId,
canDelete,
+ detailHref,
}: {
runtime: AgentRuntime;
profile: RuntimeProfile | null;
wsId: string;
canDelete: boolean;
+ /**
+ * Detail destination for the row, omitted when the row has none — pending
+ * custom runtimes are not navigable, mirroring the list's own row link.
+ */
+ detailHref?: string;
}) {
const { t } = useT("runtimes");
+ const { t: tCommon } = useT("common");
+ const intentNavigate = useIntentNavigate();
const [deleteOpen, setDeleteOpen] = useState(false);
const [editOpen, setEditOpen] = useState(false);
const isCustomRuntime = !!runtime.profile_id;
- // Delete is currently the only row action; if the row can't run it, drop
- // the kebab entirely so the column doesn't render an empty popover. We
+ // Delete is the row's only management action; if the row can't run it, drop
+ // the kebab entirely so the column doesn't render a near-empty popover. We
// used to also hide it for self-healing runtimes (live local daemon
// re-registers within seconds), but MUL-3352 surfaced that owners read
// a missing kebab as "I lost my permission" rather than "the daemon
@@ -570,6 +580,17 @@ export function RuntimeRowMenu({
}
/>
<DropdownMenuContent align="end" className="w-40">
+ {detailHref && (
+ <>
+ <DropdownMenuItem
+ onClick={() => intentNavigate(detailHref, "foreground-tab")}
+ >
+ <ExternalLink aria-hidden="true" className="h-3.5 w-3.5" />
+ {tCommon(($) => $.navigation.open_in_new_tab)}
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ </>
+ )}
{isCustomRuntime && profile && (
<DropdownMenuItem onClick={() => setEditOpen(true)}>
<Pencil aria-hidden="true" className="h-3.5 w-3.5" />
@@ -743,16 +764,15 @@ export function RuntimeList({
</ListGridHeader>
{rows.map((row) => {
const pending = isPendingCustomRuntime(row.runtime);
+ const detailHref = pending
+ ? undefined
+ : runtimeHref?.(row.runtime.id) ??
+ wsPaths.runtimeDetail(row.runtime.id);
return (
<ListGridRow
key={row.runtime.id}
className={pending ? "cursor-default" : "cursor-pointer"}
- {...(!pending
- ? rowLink(
- runtimeHref?.(row.runtime.id) ??
- wsPaths.runtimeDetail(row.runtime.id),
- )
- : {})}
+ {...(detailHref ? rowLink(detailHref) : {})}
>
<RuntimeNameCell runtime={row.runtime} machineTitle={machineTitle} />
<HealthCell
@@ -805,6 +825,7 @@ export function RuntimeList({
profile={row.profile}
wsId={wsId}
canDelete={row.canDelete}
+ detailHref={detailHref}
/>
</span>
</ListGridCell>
diff --git a/packages/views/runtimes/components/runtime-row-menu.test.tsx b/packages/views/runtimes/components/runtime-row-menu.test.tsx
index 22450380ce..ac698958fc 100644
--- a/packages/views/runtimes/components/runtime-row-menu.test.tsx
+++ b/packages/views/runtimes/components/runtime-row-menu.test.tsx
@@ -5,6 +5,7 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { fireEvent, render, screen } from "@testing-library/react";
import type { AgentRuntime, RuntimeProfile } from "@multica/core/types";
import { I18nProvider } from "@multica/core/i18n/react";
+import { NavigationProvider, type NavigationAdapter } from "../../navigation";
import enCommon from "../../locales/en/common.json";
import enRuntimes from "../../locales/en/runtimes.json";
import enAgents from "../../locales/en/agents.json";
@@ -146,21 +147,41 @@ function makeRow(
};
}
+function makeAdapter(
+ overrides: Partial<NavigationAdapter> = {},
+): NavigationAdapter {
+ return {
+ push: vi.fn(),
+ replace: vi.fn(),
+ back: vi.fn(),
+ pathname: "/ws-1/runtimes",
+ searchParams: new URLSearchParams(),
+ getShareableUrl: (p) => p,
+ ...overrides,
+ };
+}
+
// The row menu is a plain exported component on the ListGrid version of the
// list — render it directly with the row fields it reads.
-function renderActionsCell(row: RuntimeRow) {
+function renderActionsCell(
+ row: RuntimeRow,
+ options: { detailHref?: string; adapter?: NavigationAdapter } = {},
+) {
const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
return render(
<I18nProvider locale="en" resources={TEST_RESOURCES}>
- <QueryClientProvider client={qc}>
- <RuntimeRowMenu
- runtime={row.runtime}
- profile={row.profile}
- wsId="ws-1"
- canDelete={row.canDelete}
- />
- </QueryClientProvider>
+ <NavigationProvider value={options.adapter ?? makeAdapter()}>
+ <QueryClientProvider client={qc}>
+ <RuntimeRowMenu
+ runtime={row.runtime}
+ profile={row.profile}
+ wsId="ws-1"
+ canDelete={row.canDelete}
+ detailHref={options.detailHref}
+ />
+ </QueryClientProvider>
+ </NavigationProvider>
</I18nProvider>,
);
}
@@ -223,6 +244,30 @@ describe("runtime list row menu", () => {
expect(screen.getByLabelText("Display name")).toHaveValue("Custom Codex");
});
+ it("opens the row's detail in a foreground tab from the menu", () => {
+ const openInNewTab = vi.fn();
+ renderActionsCell(makeRow(makeRuntime({ runtime_mode: "local" })), {
+ detailHref: "/ws-1/runtimes/rt-1",
+ adapter: makeAdapter({ openInNewTab }),
+ });
+
+ fireEvent.click(screen.getByLabelText("Row actions"));
+ fireEvent.click(screen.getByText("Open in new tab"));
+
+ expect(openInNewTab).toHaveBeenCalledWith("/ws-1/runtimes/rt-1", undefined, {
+ activate: true,
+ });
+ });
+
+ it("omits the new-tab entry for rows with no detail destination", () => {
+ // Pending custom runtimes are not navigable, so the list passes no href.
+ renderActionsCell(makeRow(makeRuntime({ runtime_mode: "local" })));
+
+ fireEvent.click(screen.getByLabelText("Row actions"));
+
+ expect(screen.queryByText("Open in new tab")).not.toBeInTheDocument();
+ });
+
it("hides the kebab menu when the caller lacks delete permission", () => {
// Pre-existing behavior — re-asserted so the new self-healing guard
// doesn't accidentally regress it (both paths return the same empty
diff --git a/packages/views/search/search-command.test.tsx b/packages/views/search/search-command.test.tsx
index c8420c07ea..537fd87acb 100644
--- a/packages/views/search/search-command.test.tsx
+++ b/packages/views/search/search-command.test.tsx
@@ -1,5 +1,5 @@
import { act, type ReactNode } from "react";
-import { render, screen, waitFor } from "@testing-library/react";
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { I18nProvider } from "@multica/core/i18n/react";
@@ -236,13 +236,20 @@ vi.mock("@tanstack/react-query", () => ({
}),
}));
-vi.mock("../navigation", () => ({
- useNavigation: () => ({
+// Mock the context module, not the barrel: resolveClickIntent and
+// useIntentNavigate stay the REAL implementations and read this adapter
+// (no openInNewTab — the web shape, so tab intents go through window.open).
+vi.mock("../navigation/context", () => {
+ const adapter = () => ({
push: mockPush,
pathname: mockPathname.current,
getShareableUrl: mockGetShareableUrl,
- }),
-}));
+ });
+ return {
+ useNavigation: adapter,
+ useOptionalNavigation: adapter,
+ };
+});
vi.mock("@multica/ui/components/common/theme-provider", () => ({
useTheme: () => ({ theme: mockTheme.current, setTheme: mockSetTheme }),
@@ -345,6 +352,65 @@ describe("SearchCommand", () => {
expect(useSearchStore.getState().open).toBe(false);
});
+ it("cmd-click on a result opens it in a new tab instead of navigating in place", async () => {
+ const user = userEvent.setup();
+ const open = vi.spyOn(window, "open").mockReturnValue(null);
+ renderSearch();
+
+ const input = screen.getByPlaceholderText("Type a command or search...");
+ await user.type(input, "settings");
+
+ const settingsItem = await screen.findByText("Settings");
+ fireEvent.click(settingsItem, { metaKey: true });
+
+ expect(open).toHaveBeenCalledWith(
+ "https://app.multica//ws-test/settings",
+ "_blank",
+ "noopener,noreferrer",
+ );
+ expect(mockPush).not.toHaveBeenCalled();
+ expect(useSearchStore.getState().open).toBe(false);
+ open.mockRestore();
+ });
+
+ it("cmd+Enter opens the highlighted result in a new tab", async () => {
+ const user = userEvent.setup();
+ const open = vi.spyOn(window, "open").mockReturnValue(null);
+ renderSearch();
+
+ const input = screen.getByPlaceholderText("Type a command or search...");
+ await user.type(input, "settings");
+ await screen.findByText("Settings");
+ fireEvent.keyDown(input, { key: "Enter", metaKey: true });
+
+ expect(open).toHaveBeenCalledWith(
+ "https://app.multica//ws-test/settings",
+ "_blank",
+ "noopener,noreferrer",
+ );
+ expect(mockPush).not.toHaveBeenCalled();
+ open.mockRestore();
+ });
+
+ it("a plain selection after an abandoned cmd-click does not inherit the stale intent", async () => {
+ const user = userEvent.setup();
+ const open = vi.spyOn(window, "open").mockReturnValue(null);
+ renderSearch();
+
+ const input = screen.getByPlaceholderText("Type a command or search...");
+ // cmd-click somewhere that selects nothing…
+ fireEvent.click(input, { metaKey: true });
+ await user.type(input, "settings");
+
+ const settingsItem = await screen.findByText("Settings");
+ // …then a plain click must navigate in place, not open a tab.
+ await user.click(settingsItem);
+
+ expect(mockPush).toHaveBeenCalledWith("/ws-test/settings");
+ expect(open).not.toHaveBeenCalled();
+ open.mockRestore();
+ });
+
it("lists workspace members and navigates to the member page on selection", async () => {
const user = userEvent.setup();
mockMembers.current = [
diff --git a/packages/views/search/search-command.tsx b/packages/views/search/search-command.tsx
index 17e784cce9..2c214b0856 100644
--- a/packages/views/search/search-command.tsx
+++ b/packages/views/search/search-command.tsx
@@ -61,7 +61,12 @@ import {
} from "@multica/ui/components/ui/dialog";
import { useTheme } from "@multica/ui/components/common/theme-provider";
import { copyText } from "@multica/ui/lib/clipboard";
-import { useNavigation } from "../navigation";
+import {
+ resolveClickIntent,
+ useIntentNavigate,
+ useNavigation,
+ type LinkClickIntent,
+} from "../navigation";
import { useT } from "../i18n";
import { matchesPinyin } from "../editor/extensions/pinyin-match";
import { HighlightText } from "./highlight-text";
@@ -247,9 +252,27 @@ export function SearchCommand() {
{ key: "skills", label: t(($) => $.pages.skills), keywords: ["skills", "library"] },
{ key: "settings", label: t(($) => $.pages.settings), keywords: ["settings", "config", "preferences", "设置"] },
];
- const { push, pathname, getShareableUrl } = useNavigation();
+ const { pathname, getShareableUrl } = useNavigation();
+ const intentNavigate = useIntentNavigate();
const open = useSearchStore((s) => s.open);
const setOpen = useSearchStore((s) => s.setOpen);
+
+ // cmdk's onSelect carries no event, so the activating gesture's modifiers
+ // are recorded on the capture phase (click on a result, Enter in the input)
+ // and consumed by the select handlers below: cmd+click / cmd+Enter opens a
+ // result in a new tab instead of navigating in place.
+ const pendingIntentRef = useRef<LinkClickIntent>("push");
+ const recordIntent = useCallback(
+ (e: Pick<MouseEvent, "button" | "metaKey" | "ctrlKey" | "shiftKey">) => {
+ pendingIntentRef.current = resolveClickIntent(e);
+ },
+ [],
+ );
+ const consumeIntent = useCallback(() => {
+ const intent = pendingIntentRef.current;
+ pendingIntentRef.current = "push";
+ return intent;
+ }, []);
const wsId = useWorkspaceId();
const recentItems = useRecentIssuesStore(selectRecentIssues(wsId));
const p: WorkspacePaths = useWorkspacePaths();
@@ -570,30 +593,29 @@ export function SearchCommand() {
const handleSelect = useCallback(
(value: string) => {
setOpen(false);
- if (value.startsWith("project:")) {
- // value is "project:<id>" — slice off the 8-char prefix to extract the id.
- push(p.projectDetail(value.slice(8)));
- } else {
- push(p.issueDetail(value));
- }
+ const href = value.startsWith("project:")
+ ? // value is "project:<id>" — slice off the 8-char prefix to extract the id.
+ p.projectDetail(value.slice(8))
+ : p.issueDetail(value);
+ intentNavigate(href, consumeIntent());
},
- [push, setOpen, p],
+ [intentNavigate, consumeIntent, setOpen, p],
);
const handlePageSelect = useCallback(
(key: NavKey) => {
setOpen(false);
- push(p[key]());
+ intentNavigate(p[key](), consumeIntent());
},
- [push, setOpen, p],
+ [intentNavigate, consumeIntent, setOpen, p],
);
const handleMemberSelect = useCallback(
(userId: string) => {
- push(p.memberDetail(userId));
+ intentNavigate(p.memberDetail(userId), consumeIntent());
setOpen(false);
},
- [push, setOpen, p],
+ [intentNavigate, consumeIntent, setOpen, p],
);
return (
@@ -611,6 +633,18 @@ export function SearchCommand() {
</DialogHeader>
<CommandPrimitive
shouldFilter={false}
+ onPointerDownCapture={recordIntent}
+ onClickCapture={recordIntent}
+ onKeyDownCapture={(e) => {
+ if (e.key === "Enter") {
+ recordIntent({
+ button: 0,
+ metaKey: e.metaKey,
+ ctrlKey: e.ctrlKey,
+ shiftKey: e.shiftKey,
+ });
+ }
+ }}
className="flex size-full flex-col overflow-hidden rounded-xl bg-popover text-popover-foreground"
>
{/* Search input */}
diff --git a/packages/views/settings/components/github-tab.test.tsx b/packages/views/settings/components/github-tab.test.tsx
index f6c59d641b..f21c0024cc 100644
--- a/packages/views/settings/components/github-tab.test.tsx
+++ b/packages/views/settings/components/github-tab.test.tsx
@@ -96,7 +96,9 @@ vi.mock("@multica/core/auth", () => {
return { useAuthStore };
});
-vi.mock("../../navigation", () => ({
+// Mocked at the context module rather than the barrel so <AppLink> stays the
+// real component and its click contract is what the test exercises.
+vi.mock("../../navigation/context", () => ({
useNavigation: () => ({
push: mockNavPush,
replace: vi.fn(),
diff --git a/packages/views/settings/components/github-tab.tsx b/packages/views/settings/components/github-tab.tsx
index 1020665495..809b22aa3d 100644
--- a/packages/views/settings/components/github-tab.tsx
+++ b/packages/views/settings/components/github-tab.tsx
@@ -28,7 +28,7 @@ import {
} from "@multica/core/github";
import { api } from "@multica/core/api";
import type { Workspace } from "@multica/core/types";
-import { useNavigation } from "../../navigation";
+import { AppLink, useNavigation } from "../../navigation";
import { useT } from "../../i18n";
import { SettingsTab } from "./settings-layout";
import { GitHubMark } from "./github-mark";
@@ -318,7 +318,8 @@ export function GitHubTab() {
<Button
variant="outline"
size="sm"
- onClick={() => navigation.push(repositoriesHref)}
+ render={<AppLink href={repositoriesHref} />}
+ nativeButton={false}
>
<ExternalLink className="h-3 w-3" />
{t(($) => $.github.repositories_shortcut_link)}
diff --git a/packages/views/settings/components/preferences-tab.tsx b/packages/views/settings/components/preferences-tab.tsx
index ce31ef5c3d..357962d066 100644
--- a/packages/views/settings/components/preferences-tab.tsx
+++ b/packages/views/settings/components/preferences-tab.tsx
@@ -18,10 +18,7 @@ import {
} from "@multica/core/i18n";
import { useLocaleAdapter } from "@multica/core/i18n/react";
import { useAuthStore } from "@multica/core/auth";
-import {
- useCommentComposerStore,
- useIssueLinkStore,
-} from "@multica/core/issues/stores";
+import { useCommentComposerStore } from "@multica/core/issues/stores";
import { api } from "@multica/core/api";
import { browserTimezone, timezoneOptions } from "../../common/timezone-select";
import { useT } from "../../i18n";
@@ -166,8 +163,6 @@ export function PreferencesTab() {
<TimezoneRow />
<StickyCommentBarRow />
-
- <IssueLinkNewTabRow />
</SettingsCard>
</SettingsSection>
</SettingsTab>
@@ -198,30 +193,6 @@ function StickyCommentBarRow() {
);
}
-function IssueLinkNewTabRow() {
- const { t } = useT("settings");
- const openInNewTab = useIssueLinkStore((s) => s.openInNewTab);
- const setOpenInNewTab = useIssueLinkStore((s) => s.setOpenInNewTab);
-
- return (
- <SettingsRow
- label={t(($) => $.preferences.issue_link_new_tab.title)}
- description={t(($) => $.preferences.issue_link_new_tab.hint)}
- >
- <Switch
- checked={openInNewTab}
- onCheckedChange={(checked) => {
- setOpenInNewTab(checked === true);
- toast.success(t(($) => $.auto_save.toast_saved), {
- id: "settings-auto-save",
- });
- }}
- aria-label={t(($) => $.preferences.issue_link_new_tab.title)}
- />
- </SettingsRow>
- );
-}
-
// Base UI rejects "" as a SelectItem value, so route the "no preference"
// state through this sentinel and translate at the wire boundary.
const BROWSER_TZ_VALUE = "__browser__";
diff --git a/packages/views/skills/components/skill-list-actions.tsx b/packages/views/skills/components/skill-list-actions.tsx
index 72bd49eab0..1f2d3ab1d6 100644
--- a/packages/views/skills/components/skill-list-actions.tsx
+++ b/packages/views/skills/components/skill-list-actions.tsx
@@ -4,6 +4,7 @@ import { useState } from "react";
import {
Check,
ChevronRight,
+ ExternalLink,
Loader2,
MoreHorizontal,
Plus,
@@ -16,6 +17,7 @@ import { toast } from "sonner";
import type { Agent, SkillSummary } from "@multica/core/types";
import { api } from "@multica/core/api";
import { workspaceKeys } from "@multica/core/workspace/queries";
+import { useWorkspacePaths } from "@multica/core/paths";
import { resolvePublicFileUrl } from "@multica/core/workspace/avatar-url";
import { Button } from "@multica/ui/components/ui/button";
import { Checkbox } from "@multica/ui/components/ui/checkbox";
@@ -48,6 +50,7 @@ import {
import { ActorAvatar } from "@multica/ui/components/common/actor-avatar";
import { cn } from "@multica/ui/lib/utils";
import { useT } from "../../i18n";
+import { useIntentNavigate } from "../../navigation";
import type { SkillRow } from "./skills-page";
// Shared context the row kebab and the batch toolbar both need. Assembled
@@ -520,6 +523,9 @@ export function SkillRowActions({
ctx: SkillActionsContext;
}) {
const { t } = useT("skills");
+ const { t: tCommon } = useT("common");
+ const paths = useWorkspacePaths();
+ const intentNavigate = useIntentNavigate();
const [addOpen, setAddOpen] = useState(false);
const [deleteOpen, setDeleteOpen] = useState(false);
@@ -541,6 +547,19 @@ export function SkillRowActions({
}
/>
<DropdownMenuContent align="end" className="w-52">
+ <DropdownMenuItem
+ onClick={() =>
+ intentNavigate(
+ paths.skillDetail(row.skill.id),
+ "foreground-tab",
+ row.skill.name,
+ )
+ }
+ >
+ <ExternalLink className="size-3.5" />
+ {tCommon(($) => $.navigation.open_in_new_tab)}
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
<DropdownMenuItem onClick={() => setAddOpen(true)}>
<Plus className="size-3.5" />
{t(($) => $.actions.add_to_agent)}
diff --git a/packages/views/skills/components/skills-page.tsx b/packages/views/skills/components/skills-page.tsx
index 381d5f1301..ccbdc577d1 100644
--- a/packages/views/skills/components/skills-page.tsx
+++ b/packages/views/skills/components/skills-page.tsx
@@ -872,7 +872,7 @@ export default function SkillsPage() {
className={`cursor-pointer ${
selectedIds.has(row.skill.id) ? "bg-accent/30" : ""
}`}
- {...rowLink(paths.skillDetail(row.skill.id))}
+ {...rowLink(paths.skillDetail(row.skill.id), row.skill.name)}
>
<CheckboxCell
checked={selectedIds.has(row.skill.id)}
diff --git a/packages/views/slack/bind-page.tsx b/packages/views/slack/bind-page.tsx
index 3b0781a18c..e3aab33322 100644
--- a/packages/views/slack/bind-page.tsx
+++ b/packages/views/slack/bind-page.tsx
@@ -5,7 +5,7 @@ import { Card, CardContent } from "@multica/ui/components/ui/card";
import { Button } from "@multica/ui/components/ui/button";
import { api } from "@multica/core/api";
import { useAuthStore } from "@multica/core/auth";
-import { useNavigation } from "../navigation";
+import { AppLink } from "../navigation";
import { useT } from "../i18n";
type RedeemState =
@@ -29,7 +29,6 @@ export function SlackBindPage({ token }: { token: string | null }) {
const { t } = useT("common");
const user = useAuthStore((s) => s.user);
const isAuthLoading = useAuthStore((s) => s.isLoading);
- const navigation = useNavigation();
const [state, setState] = useState<RedeemState>({ kind: "idle" });
useEffect(() => {
@@ -75,13 +74,14 @@ export function SlackBindPage({ token }: { token: string | null }) {
</p>
<Button
size="sm"
- onClick={() =>
- navigation.push(
- `/login?next=${encodeURIComponent(
+ render={
+ <AppLink
+ href={`/login?next=${encodeURIComponent(
`/slack/bind?token=${encodeURIComponent(token ?? "")}`,
- )}`,
- )
+ )}`}
+ />
}
+ nativeButton={false}
>
{t(($) => $.slack_bind.sign_in)}
</Button>
diff --git a/packages/views/squads/components/squad-detail-page.tsx b/packages/views/squads/components/squad-detail-page.tsx
index beada3db88..8ecf948dae 100644
--- a/packages/views/squads/components/squad-detail-page.tsx
+++ b/packages/views/squads/components/squad-detail-page.tsx
@@ -243,7 +243,7 @@ export function SquadDetailPage() {
isArchived={isArchived}
getEntityName={getEntityName}
onAddMemberClick={() => setShowAddMember(true)}
- onCreateAgentClick={canManage ? () => push(`${p.newAgent()}?squad=${encodeURIComponent(squadId)}`) : undefined}
+ createAgentHref={canManage ? `${p.newAgent()}?squad=${encodeURIComponent(squadId)}` : undefined}
onSetLeader={(id) => setLeaderMut.mutate(id)}
onRemoveMember={(m) => removeMemberMut.mutate(m)}
onUpdateRole={async (m, role) => { await updateRoleMut.mutateAsync({ member: m, role }); }}
@@ -947,7 +947,7 @@ function SquadOverviewPane({
isArchived,
getEntityName,
onAddMemberClick,
- onCreateAgentClick,
+ createAgentHref,
onSetLeader,
onRemoveMember,
onUpdateRole,
@@ -968,7 +968,7 @@ function SquadOverviewPane({
// Optional — only passed when the current user can manage the squad
// (workspace owner/admin or the creator). Hidden otherwise so viewers
// don't see a button they can't action.
- onCreateAgentClick?: () => void;
+ createAgentHref?: string;
onSetLeader: (agentId: string) => void;
onRemoveMember: (m: SquadMember) => void;
onUpdateRole: (m: SquadMember, role: string) => Promise<void>;
@@ -1025,7 +1025,7 @@ function SquadOverviewPane({
isArchived={isArchived}
getEntityName={getEntityName}
onAddMemberClick={onAddMemberClick}
- onCreateAgentClick={onCreateAgentClick}
+ createAgentHref={createAgentHref}
onSetLeader={onSetLeader}
onRemoveMember={onRemoveMember}
onUpdateRole={onUpdateRole}
@@ -1090,7 +1090,7 @@ function SquadMembersTab({
isArchived,
getEntityName,
onAddMemberClick,
- onCreateAgentClick,
+ createAgentHref,
onSetLeader,
onRemoveMember,
onUpdateRole,
@@ -1106,7 +1106,7 @@ function SquadMembersTab({
getEntityName: (type: string, id: string) => string;
onAddMemberClick: () => void;
// Hidden for viewers who can't manage — see SquadOverviewPane.
- onCreateAgentClick?: () => void;
+ createAgentHref?: string;
onSetLeader: (agentId: string) => void;
onRemoveMember: (m: SquadMember) => void;
onUpdateRole: (m: SquadMember, role: string) => Promise<void>;
@@ -1126,8 +1126,13 @@ function SquadMembersTab({
</div>
{canManage && (
<div className="flex items-center gap-2">
- {onCreateAgentClick && (
- <Button size="sm" variant="outline" onClick={onCreateAgentClick}>
+ {createAgentHref && (
+ <Button
+ size="sm"
+ variant="outline"
+ render={<AppLink href={createAgentHref} />}
+ nativeButton={false}
+ >
<Plus className="size-3.5 mr-1.5" />
{t(($) => $.members_tab.create_agent_button)}
</Button>
diff --git a/packages/views/squads/components/squads-page.tsx b/packages/views/squads/components/squads-page.tsx
index e0c8d59dc8..e986ba937b 100644
--- a/packages/views/squads/components/squads-page.tsx
+++ b/packages/views/squads/components/squads-page.tsx
@@ -5,6 +5,7 @@ import {
ArrowDown,
ArrowUp,
ChevronDown,
+ ExternalLink,
Filter,
Loader2,
MoreHorizontal,
@@ -52,6 +53,7 @@ import {
DropdownMenuItem,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
+ DropdownMenuSeparator,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
@@ -81,7 +83,7 @@ import {
import { ActorAvatar as ActorAvatarBase } from "@multica/ui/components/common/actor-avatar";
import { ActorAvatar } from "../../common/actor-avatar";
import { FILTER_ITEM_CLASS, HoverCheck } from "../../common/hover-check";
-import { useRowLink } from "../../navigation";
+import { useIntentNavigate, useRowLink } from "../../navigation";
import {
CollectionPageHeader,
CollectionPageHeaderAction,
@@ -316,6 +318,9 @@ function ArchiveSquadDialog({
function SquadRowActions({ squad }: { squad: Squad }) {
const { t } = useT("squads");
+ const { t: tCommon } = useT("common");
+ const p = useWorkspacePaths();
+ const intentNavigate = useIntentNavigate();
const [archiveOpen, setArchiveOpen] = useState(false);
return (
<span
@@ -335,6 +340,19 @@ function SquadRowActions({ squad }: { squad: Squad }) {
}
/>
<DropdownMenuContent align="end" className="w-40">
+ <DropdownMenuItem
+ onClick={() =>
+ intentNavigate(
+ p.squadDetail(squad.id),
+ "foreground-tab",
+ squad.name,
+ )
+ }
+ >
+ <ExternalLink className="size-3.5" />
+ {tCommon(($) => $.navigation.open_in_new_tab)}
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
<DropdownMenuItem
variant="destructive"
onClick={() => setArchiveOpen(true)}
@@ -963,7 +981,7 @@ export function SquadsPage() {
<ListGridRow
key={squad.id}
className="cursor-pointer"
- {...rowLink(p.squadDetail(squad.id))}
+ {...rowLink(p.squadDetail(squad.id), squad.name)}
>
<NameCell squad={squad} />
<LeaderCell
diff --git a/packages/views/wecom/bind-page.test.tsx b/packages/views/wecom/bind-page.test.tsx
index 708730b9e1..ff43f2283c 100644
--- a/packages/views/wecom/bind-page.test.tsx
+++ b/packages/views/wecom/bind-page.test.tsx
@@ -27,8 +27,11 @@ vi.mock("@multica/core/auth", () => {
return { useAuthStore };
});
-vi.mock("../navigation", () => ({
+// Mock the context module, not the barrel: AppLink stays the real component
+// (the sign-in button renders through it) and reads the mocked adapter.
+vi.mock("../navigation/context", () => ({
useNavigation: () => ({ push: mockNavigatePush }),
+ useOptionalNavigation: () => ({ push: mockNavigatePush }),
}));
vi.mock("@multica/core/api", () => ({
diff --git a/packages/views/wecom/bind-page.tsx b/packages/views/wecom/bind-page.tsx
index 62cfc09ca0..f1b29526e2 100644
--- a/packages/views/wecom/bind-page.tsx
+++ b/packages/views/wecom/bind-page.tsx
@@ -5,7 +5,7 @@ import { Card, CardContent } from "@multica/ui/components/ui/card";
import { Button } from "@multica/ui/components/ui/button";
import { api } from "@multica/core/api";
import { useAuthStore } from "@multica/core/auth";
-import { useNavigation } from "../navigation";
+import { AppLink } from "../navigation";
import { useT } from "../i18n";
type RedeemState =
@@ -30,7 +30,6 @@ export function WecomBindPage({ token }: { token: string | null }) {
const { t } = useT("common");
const user = useAuthStore((s) => s.user);
const isAuthLoading = useAuthStore((s) => s.isLoading);
- const navigation = useNavigation();
const [state, setState] = useState<RedeemState>({ kind: "idle" });
useEffect(() => {
@@ -76,13 +75,14 @@ export function WecomBindPage({ token }: { token: string | null }) {
</p>
<Button
size="sm"
- onClick={() =>
- navigation.push(
- `/login?next=${encodeURIComponent(
+ render={
+ <AppLink
+ href={`/login?next=${encodeURIComponent(
`/wecom/bind?token=${encodeURIComponent(token ?? "")}`,
- )}`,
- )
+ )}`}
+ />
}
+ nativeButton={false}
>
{t(($) => $.wecom_bind.sign_in)}
</Button>