Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(desktop): one app-drawn right-click menu everywhere (MUL-9041) (#10382)
Jiayuan Zhang61cb146e6977
diff --git a/apps/desktop/src/main/context-menu.test.ts b/apps/desktop/src/main/context-menu.test.tsindex 553d1f1974..137ebbc9db 100644--- a/apps/desktop/src/main/context-menu.test.ts+++ b/apps/desktop/src/main/context-menu.test.ts@@ -1,61 +1,26 @@// @vitest-environment nodeimport { describe, expect, it, vi, beforeEach } from "vitest";-// Capture every MenuItem the SUT constructs so each test can assert-// on the menu that would appear at popup time without booting an-// actual Electron window. State is created via `vi.hoisted` because-// `vi.mock` factories are hoisted above all top-level statements; a-// plain `const` would be a TDZ ReferenceError when the factory runs.-type CapturedMenuItem = {- label?: string;- role?: string;- type?: string;- click?: () => void;-};+// State is created via `vi.hoisted` because `vi.mock` factories are hoisted+// above all top-level statements; a plain `const` would be a TDZ+// ReferenceError when the factory runs.const ctx = vi.hoisted(() => ({- capturedItems: [] as CapturedMenuItem[][],- browserWindowFromWebContents: vi.fn(),- popupSpy: vi.fn(),clipboardWriteText: vi.fn().mockResolvedValue(undefined),openExternalSpy: vi.fn().mockResolvedValue(undefined),- preferredLanguagesRef: { current: ["en-US"] as string[] },}));-vi.mock("electron", () => {- class MockMenu {- items: CapturedMenuItem[] = [];- constructor() {- ctx.capturedItems.push(this.items);- }- append(item: CapturedMenuItem) {- this.items.push(item);- }- popup(opts: unknown) {- ctx.popupSpy(opts);- }- }- class MockMenuItem {- label?: string;- role?: string;- type?: string;- click?: () => void;- constructor(opts: CapturedMenuItem) {- Object.assign(this, opts);- }- }- return {- BrowserWindow: { fromWebContents: ctx.browserWindowFromWebContents },- Menu: MockMenu,- MenuItem: MockMenuItem,- app: {- getPreferredSystemLanguages: () => ctx.preferredLanguagesRef.current,- },- clipboard: { writeText: ctx.clipboardWriteText },- shell: { openExternal: ctx.openExternalSpy },- };-});+vi.mock("electron", () => ({+ clipboard: { writeText: ctx.clipboardWriteText },+ shell: { openExternal: ctx.openExternalSpy },+}));import { installContextMenu } from "./context-menu";+import {+ CONTEXT_MENU_COMMAND_CHANNEL,+ CONTEXT_MENU_REQUEST_CHANNEL,+ hasContextMenuItems,+ type ContextMenuRequest,+} from "../shared/context-menu";type ContextMenuParams = {selectionText: string;@@ -75,27 +40,52 @@ type ContextMenuParams = {};};-type Listener = (event: unknown, params: ContextMenuParams) => void;--// Tiny WebContents stub — we only need the `.on("context-menu", ...)`-// hook the SUT installs and a way to fire it back at our own listener-// list. Everything else (clipboard, link opening, label resolution) is-// mocked above.+// WebContents stub: the `context-menu` hook and per-contents IPC the SUT+// installs, the requests it sends, and the edit commands it can run.function makeWebContents() {- const handlers: Listener[] = [];+ const contextMenuHandlers: Array<(event: unknown, params: ContextMenuParams) => void> = [];+ const ipcHandlers = new Map<string, (event: unknown, raw: unknown) => void>();+ const sent: Array<{ channel: string; request: ContextMenuRequest }> = [];return {+ sent,+ cut: vi.fn(),+ copy: vi.fn(),+ paste: vi.fn(),+ selectAll: vi.fn(),copyImageAt: vi.fn(),replaceMisspelling: vi.fn(),session: { addWordToSpellCheckerDictionary: vi.fn() },- on(event: string, fn: Listener) {- if (event === "context-menu") handlers.push(fn);+ on(event: string, fn: (event: unknown, params: ContextMenuParams) => void) {+ if (event === "context-menu") contextMenuHandlers.push(fn);+ },+ send(channel: string, request: ContextMenuRequest) {+ sent.push({ channel, request });+ },+ ipc: {+ on(channel: string, fn: (event: unknown, raw: unknown) => void) {+ ipcHandlers.set(channel, fn);+ },},fire(params: ContextMenuParams) {- for (const h of handlers) h({}, params);+ for (const h of contextMenuHandlers) h({}, params);+ },+ command(raw: unknown) {+ ipcHandlers.get(CONTEXT_MENU_COMMAND_CHANNEL)?.({}, raw);+ },+ lastRequest(): ContextMenuRequest {+ const last = sent[sent.length - 1];+ if (!last) throw new Error("no request was sent");+ return last.request;},};}+function setup() {+ const wc = makeWebContents();+ installContextMenu(wc as never);+ return wc;+}+const baseEditFlags = {canCut: false,canCopy: false,@@ -103,204 +93,225 @@ const baseEditFlags = {canSelectAll: false,};-describe("installContextMenu — spelling", () => {- beforeEach(() => {- ctx.capturedItems.length = 0;- ctx.preferredLanguagesRef.current = ["en-US"];- });+beforeEach(() => {+ ctx.clipboardWriteText.mockClear();+ ctx.openExternalSpy.mockClear();+});- it("shows suggestions and 'Add to Dictionary' first for a misspelled word in an editable field", () => {- const wc = makeWebContents();- installContextMenu(wc as never);+describe("installContextMenu — forwarding", () => {+ it("forwards an unhandled right-click to the renderer instead of popping a native menu", () => {+ const wc = setup();wc.fire(- baseSelection({+ params({isEditable: true,- misspelledWord: "teh",- dictionarySuggestions: ["the", "tea"],- editFlags: { ...baseEditFlags, canPaste: true },+ selectionText: "hello",+ x: 12,+ y: 34,+ editFlags: { canCut: true, canCopy: true, canPaste: true, canSelectAll: true },}),);- expect(lastMenuLabelsOrEmpty().slice(0, 3)).toEqual([- "the",- "tea",- "Add to Dictionary",- ]);- invokeByLabel("the");- expect(wc.replaceMisspelling).toHaveBeenCalledWith("the");- invokeByLabel("Add to Dictionary");- expect(wc.session.addWordToSpellCheckerDictionary).toHaveBeenCalledWith("teh");+ expect(wc.sent).toHaveLength(1);+ expect(wc.sent[0]!.channel).toBe(CONTEXT_MENU_REQUEST_CHANNEL);+ expect(wc.lastRequest()).toMatchObject({+ x: 12,+ y: 34,+ isEditable: true,+ canCut: true,+ canCopy: true,+ canPaste: true,+ canSelectAll: true,+ hasLink: false,+ hasImage: false,+ });});- it("omits spelling items when the field is not editable", () => {- const wc = makeWebContents();- installContextMenu(wc as never);- wc.fire(- baseSelection({ selectionText: "teh", misspelledWord: "teh", dictionarySuggestions: ["the"] }),- );- expect(lastMenuLabelsOrEmpty()).not.toContain("Add to Dictionary");+ it("forwards a right-click with nothing of main's to offer, for the page's own items", () => {+ const wc = setup();+ wc.fire(params({}));+ expect(wc.sent).toHaveLength(1);+ expect(hasContextMenuItems(wc.lastRequest())).toBe(false);});-});-describe("installContextMenu — link items", () => {- beforeEach(() => {- ctx.capturedItems.length = 0;- ctx.popupSpy.mockClear();- ctx.clipboardWriteText.mockClear();- ctx.openExternalSpy.mockClear();- ctx.browserWindowFromWebContents.mockReset();- ctx.preferredLanguagesRef.current = ["en-US"];+ it("does not offer copy for a whitespace-only selection", () => {+ const wc = setup();+ wc.fire(params({ selectionText: " ", editFlags: { ...baseEditFlags, canCopy: true } }));+ expect(wc.lastRequest()).toMatchObject({ canCopy: false });});- it("adds 'Open Link in Browser' and 'Copy Link Address' when right-clicking an http(s) link", () => {- // The link case is the one this test file is here to cover —- // before MUL-3083 follow-up, right-clicking an <a> in the- // renderer only surfaced 'copy' (when the user happened to have- // text selected) and gave no way to open the URL externally.- const wc = makeWebContents();- installContextMenu(wc as never);- wc.fire({- ...baseSelection({ linkURL: "https://multica.ai/welcome" }),- });-- const labels = lastMenuLabels();- expect(labels).toContain("Open Link in Browser");- expect(labels).toContain("Copy Link Address");-- // The two click handlers must route to the existing- // openExternalSafely allowlist + clipboard.writeText.- invokeByLabel("Open Link in Browser");- expect(ctx.openExternalSpy).toHaveBeenCalledWith("https://multica.ai/welcome");-- invokeByLabel("Copy Link Address");- expect(ctx.clipboardWriteText).toHaveBeenCalledWith(- "https://multica.ai/welcome",+ it("does not offer cut or paste outside an editable field", () => {+ const wc = setup();+ wc.fire(+ params({+ selectionText: "hello",+ editFlags: { canCut: true, canCopy: true, canPaste: true, canSelectAll: true },+ }),);- expect(ctx.popupSpy).toHaveBeenCalledTimes(1);+ expect(wc.lastRequest()).toMatchObject({+ canCut: false,+ canCopy: true,+ canPaste: false,+ canSelectAll: false,+ });});- it("does NOT add link items when the cursor is over a non-http(s) URL", () => {- // Only http(s) links are surfaced — we don't promise anything for- // mailto:, javascript:, custom app schemes, etc. Surfacing them- // would shell out via openExternalSafely (which would block the- // call anyway) or write a non-URL string to the clipboard, both- // of which violate user expectations for a "link" item.- const wc = makeWebContents();- installContextMenu(wc as never);- wc.fire(baseSelection({ linkURL: "javascript:alert(1)" }));- const labels = lastMenuLabelsOrEmpty();- expect(labels).not.toContain("Open Link in Browser");- expect(labels).not.toContain("Copy Link Address");+ it("never sends the link URL or the misspelled word to the renderer", () => {+ const wc = setup();+ wc.fire(+ params({+ isEditable: true,+ linkURL: "https://multica.ai/welcome",+ misspelledWord: "teh",+ dictionarySuggestions: ["the"],+ }),+ );+ const serialized = JSON.stringify(wc.lastRequest());+ expect(serialized).not.toContain("multica.ai");+ expect(serialized).not.toContain("teh");});+});- it("does NOT add link items when there is no link under the cursor", () => {- const wc = makeWebContents();- installContextMenu(wc as never);+describe("installContextMenu — commands", () => {+ it("runs the edit command for the latest request", () => {+ const wc = setup();wc.fire(- baseSelection({- selectionText: "hello",- editFlags: { ...baseEditFlags, canCopy: true },+ params({+ isEditable: true,+ selectionText: "hi",+ editFlags: { canCut: true, canCopy: true, canPaste: true, canSelectAll: true },}),);- const labels = lastMenuLabelsOrEmpty();- expect(labels).not.toContain("Open Link in Browser");- // Selection-only context still surfaces copy as before — guards- // against a regression where adding the link branch broke the- // base path.- expect(menuItemRoles()).toContain("copy");+ const { id } = wc.lastRequest();+ wc.command({ id, type: "paste" });+ expect(wc.paste).toHaveBeenCalledTimes(1);});- it("uses zh-Hans labels when the OS preferred language is Chinese", () => {- // Locale fallback is intentionally permissive: every zh-* variant- // routes to zh-Hans so users on zh-CN / zh-TW / zh-HK still see- // Chinese rather than dropping to English. The renderer ships only- // zh-Hans translations, so this matches the rest of the app.- ctx.preferredLanguagesRef.current = ["zh-CN"];- const wc = makeWebContents();- installContextMenu(wc as never);- wc.fire(baseSelection({ linkURL: "https://multica.ai" }));- expect(lastMenuLabels()).toContain("在浏览器中打开链接");- expect(lastMenuLabels()).toContain("复制链接地址");+ it("runs one command per request", () => {+ const wc = setup();+ wc.fire(params({ selectionText: "hi", editFlags: { ...baseEditFlags, canCopy: true } }));+ const { id } = wc.lastRequest();+ wc.command({ id, type: "copy" });+ wc.command({ id, type: "copy" });+ expect(wc.copy).toHaveBeenCalledTimes(1);});- it("uses Russian labels when the OS preferred language is Russian", () => {- ctx.preferredLanguagesRef.current = ["ru-RU"];- const wc = makeWebContents();- installContextMenu(wc as never);- wc.fire(baseSelection({ linkURL: "https://multica.ai" }));- expect(lastMenuLabels()).toContain("Открыть ссылку в браузере");- expect(lastMenuLabels()).toContain("Копировать адрес ссылки");+ it("drops a command for an older request", () => {+ const wc = setup();+ wc.fire(params({ selectionText: "hi", editFlags: { ...baseEditFlags, canCopy: true } }));+ const stale = wc.lastRequest().id;+ wc.fire(params({ selectionText: "hi", editFlags: { ...baseEditFlags, canCopy: true } }));+ wc.command({ id: stale, type: "copy" });+ expect(wc.copy).not.toHaveBeenCalled();});- it("falls back to English when the OS preferred language is something we don't ship", () => {- ctx.preferredLanguagesRef.current = ["fr-FR"];- const wc = makeWebContents();- installContextMenu(wc as never);- wc.fire(baseSelection({ linkURL: "https://multica.ai" }));- expect(lastMenuLabels()).toContain("Open Link in Browser");+ it("drops a command the request did not offer", () => {+ const wc = setup();+ wc.fire(params({ selectionText: "hi", editFlags: { ...baseEditFlags, canCopy: true } }));+ const { id } = wc.lastRequest();+ wc.command({ id, type: "openLink" });+ wc.command({ id, type: "paste" });+ expect(ctx.openExternalSpy).not.toHaveBeenCalled();+ expect(wc.paste).not.toHaveBeenCalled();});-});-describe("installContextMenu — image items", () => {- beforeEach(() => {- ctx.capturedItems.length = 0;- ctx.popupSpy.mockClear();- ctx.preferredLanguagesRef.current = ["en-US"];+ it("ignores malformed commands", () => {+ const wc = setup();+ wc.fire(params({ selectionText: "hi", editFlags: { ...baseEditFlags, canCopy: true } }));+ const { id } = wc.lastRequest();+ wc.command(null);+ wc.command({ id: String(id), type: "copy" });+ wc.command({ id, type: "exec" });+ expect(wc.copy).not.toHaveBeenCalled();+ wc.command({ id, type: "copy" });+ expect(wc.copy).toHaveBeenCalledTimes(1);});+});- it("adds 'Copy Image' on a loaded image and copies the pixels under the cursor", () => {- // MUL-7759: the attachment viewer and inline images had no way to- // copy the picture itself — Electron shows no menu at all by default.- const wc = makeWebContents();- installContextMenu(wc as never);+describe("installContextMenu — spelling", () => {+ it("offers suggestions and add-to-dictionary for a misspelled word in an editable field", () => {+ const wc = setup();wc.fire(- baseSelection({ mediaType: "image", hasImageContents: true, x: 120, y: 48 }),+ params({+ isEditable: true,+ misspelledWord: "teh",+ dictionarySuggestions: ["the", "tea"],+ }),);+ expect(wc.lastRequest()).toMatchObject({+ suggestions: ["the", "tea"],+ canAddToDictionary: true,+ });- expect(lastMenuLabels()).toEqual(["Copy Image"]);- invokeByLabel("Copy Image");- expect(wc.copyImageAt).toHaveBeenCalledWith(120, 48);- expect(ctx.popupSpy).toHaveBeenCalledTimes(1);+ wc.command({ id: wc.lastRequest().id, type: "replaceMisspelling", index: 1 });+ expect(wc.replaceMisspelling).toHaveBeenCalledWith("tea");+ });++ it("adds main's copy of the misspelled word to the dictionary", () => {+ const wc = setup();+ wc.fire(params({ isEditable: true, misspelledWord: "teh", dictionarySuggestions: [] }));+ wc.command({ id: wc.lastRequest().id, type: "addToDictionary" });+ expect(wc.session.addWordToSpellCheckerDictionary).toHaveBeenCalledWith("teh");});- it("does NOT add 'Copy Image' before the image has loaded", () => {- const wc = makeWebContents();- installContextMenu(wc as never);- wc.fire(baseSelection({ mediaType: "image", hasImageContents: false }));- expect(lastMenuLabelsOrEmpty()).not.toContain("Copy Image");- expect(ctx.popupSpy).not.toHaveBeenCalled();+ it("rejects a suggestion index outside the offered list", () => {+ const wc = setup();+ wc.fire(params({ isEditable: true, misspelledWord: "teh", dictionarySuggestions: ["the"] }));+ wc.command({ id: wc.lastRequest().id, type: "replaceMisspelling", index: 3 });+ expect(wc.replaceMisspelling).not.toHaveBeenCalled();});- it("lists the image items after the link items for an image inside a link", () => {- const wc = makeWebContents();- installContextMenu(wc as never);+ it("omits spelling outside an editable field", () => {+ const wc = setup();wc.fire(- baseSelection({- linkURL: "https://multica.ai",- mediaType: "image",- hasImageContents: true,+ params({+ selectionText: "teh",+ misspelledWord: "teh",+ dictionarySuggestions: ["the"],+ editFlags: { ...baseEditFlags, canCopy: true },}),);- expect(lastMenu().map((i) => i.label ?? i.type)).toEqual([- "Open Link in Browser",- "Copy Link Address",- "separator",- "Copy Image",- ]);+ expect(wc.lastRequest()).toMatchObject({ suggestions: [], canAddToDictionary: false });});+});- it("uses zh-Hans labels when the OS preferred language is Chinese", () => {- ctx.preferredLanguagesRef.current = ["zh-CN"];- const wc = makeWebContents();- installContextMenu(wc as never);- wc.fire(baseSelection({ mediaType: "image", hasImageContents: true }));- expect(lastMenuLabels()).toContain("复制图片");+describe("installContextMenu — links and images", () => {+ it("opens and copies main's copy of an http(s) link", () => {+ const wc = setup();+ wc.fire(params({ linkURL: "https://multica.ai/welcome" }));+ expect(wc.lastRequest().hasLink).toBe(true);++ wc.command({ id: wc.lastRequest().id, type: "openLink" });+ expect(ctx.openExternalSpy).toHaveBeenCalledWith("https://multica.ai/welcome");++ wc.fire(params({ linkURL: "https://multica.ai/welcome" }));+ wc.command({ id: wc.lastRequest().id, type: "copyLink" });+ expect(ctx.clipboardWriteText).toHaveBeenCalledWith("https://multica.ai/welcome");+ });++ it("does not offer links that are not http(s)", () => {+ const wc = setup();+ wc.fire(params({ linkURL: "javascript:alert(1)" }));+ expect(wc.lastRequest().hasLink).toBe(false);+ wc.fire(params({ linkURL: "file:///index.html#/acme/issues/1" }));+ expect(wc.lastRequest().hasLink).toBe(false);+ });++ it("copies the pixels of a loaded image under the cursor", () => {+ const wc = setup();+ wc.fire(params({ mediaType: "image", hasImageContents: true, x: 120, y: 48 }));+ expect(wc.lastRequest().hasImage).toBe(true);+ wc.command({ id: wc.lastRequest().id, type: "copyImage" });+ expect(wc.copyImageAt).toHaveBeenCalledWith(120, 48);});-});-// --- helpers ---+ it("does not offer copy image before the image has loaded", () => {+ const wc = setup();+ wc.fire(params({ mediaType: "image", hasImageContents: false }));+ expect(wc.lastRequest().hasImage).toBe(false);+ });+});-function baseSelection(over: Partial<ContextMenuParams>): ContextMenuParams {+function params(over: Partial<ContextMenuParams>): ContextMenuParams {return {selectionText: "",isEditable: false,@@ -315,28 +326,3 @@ function baseSelection(over: Partial<ContextMenuParams>): ContextMenuParams {...over,};}--function lastMenu(): CapturedMenuItem[] {- const last = ctx.capturedItems[ctx.capturedItems.length - 1];- if (!last) throw new Error("no menu was constructed");- return last;-}--function lastMenuLabelsOrEmpty(): string[] {- const last = ctx.capturedItems[ctx.capturedItems.length - 1] ?? [];- return last.map((i) => i.label ?? "");-}--function lastMenuLabels(): string[] {- return lastMenu().map((i) => i.label ?? "");-}--function menuItemRoles(): string[] {- return lastMenu().map((i) => i.role ?? "");-}--function invokeByLabel(label: string): void {- const item = lastMenu().find((i) => i.label === label);- if (!item) throw new Error(`menu item not found: ${label}`);- item.click?.();-}diff --git a/apps/desktop/src/main/context-menu.ts b/apps/desktop/src/main/context-menu.tsindex 463f2322da..8b16218293 100644--- a/apps/desktop/src/main/context-menu.ts+++ b/apps/desktop/src/main/context-menu.ts@@ -1,220 +1,115 @@import {- BrowserWindow,- Menu,- MenuItem,- app,clipboard,+ type ContextMenuParams,type WebContents,} from "electron";import { isSafeExternalHttpUrl, openExternalSafely } from "./external-url";+import {+ CONTEXT_MENU_COMMAND_CHANNEL,+ CONTEXT_MENU_REQUEST_CHANNEL,+ isOfferedCommand,+ parseContextMenuCommand,+ type ContextMenuCommand,+ type ContextMenuRequest,+} from "../shared/context-menu";-// Electron ships with no default right-click menu, so a user selecting text-// in the renderer has no way to copy it. Mirror Chrome's minimal clipboard-// menu using `roles`, which keeps i18n + accelerator handling native.-//-// Custom (non-role) link and image items below are NOT auto-localized by-// Electron — roles like "copy" pull labels from the OS, but a custom-// MenuItem only shows the `label` you give it. We translate by OS-preferred-// language so those items at least track Chinese / Japanese / Korean speakers-// alongside the English default; everything else falls through to English,-// which matches Chrome's behavior on those locales without app-level-// translation files.+// Electron ships with no default right-click menu. The app draws every menu+// in the renderer, in the app's own language and look: object menus (an+// issue, a comment, a project) handle the DOM `contextmenu` event and+// preventDefault it, which keeps Electron from firing `context-menu` at all.+// What reaches this handler is the content layer the page left alone — text+// fields, selected text, links, images, code, tables, attachments — and main+// forwards every one to the renderer, which adds what only the page knows+// (the code, the comment around it) and skips a menu with nothing in it.export function installContextMenu(webContents: WebContents): void {- webContents.on("context-menu", (_event, params) => {- const {- editFlags,- selectionText,- isEditable,- linkURL,- mediaType,- hasImageContents,- misspelledWord,- dictionarySuggestions,- } = params;- const hasSelection = selectionText.trim().length > 0;- // params.linkURL is the resolved absolute URL of the anchor under the- // cursor; Electron normalizes relative hrefs against the page URL for- // us, so we only need to gate on the http(s) scheme allowlist- // (mirrors openExternalSafely + the renderer's <a> usage). Empty for- // non-link right-clicks; other schemes (mailto:, javascript:, custom- // app schemes) are intentionally not surfaced — opening them via- // shell.openExternal would route through the OS handler and is- // outside what this menu promises.- const linkIsHttpUrl = !!linkURL && isSafeExternalHttpUrl(linkURL);- const labels = pickLabels();-- const menu = new Menu();-- // Spelling: suggestions first, like Chrome. Only in editable fields.- if (isEditable && misspelledWord) {- for (const suggestion of dictionarySuggestions) {- menu.append(- new MenuItem({- label: suggestion,- click: () => webContents.replaceMisspelling(suggestion),- }),- );- }- menu.append(- new MenuItem({- label: labels.addToDictionary,- click: () =>- webContents.session.addWordToSpellCheckerDictionary(misspelledWord),- }),- );- menu.append(new MenuItem({ type: "separator" }));- }-- if (isEditable && editFlags.canCut) {- menu.append(new MenuItem({ role: "cut" }));- }- if (hasSelection && editFlags.canCopy) {- menu.append(new MenuItem({ role: "copy" }));- }- if (isEditable && editFlags.canPaste) {- menu.append(new MenuItem({ role: "paste" }));- }- if (isEditable && editFlags.canSelectAll) {- if (menu.items.length > 0) {- menu.append(new MenuItem({ type: "separator" }));- }- menu.append(new MenuItem({ role: "selectAll" }));- }-- // Link items — only when the cursor is over an actual http(s) <a>.- // Without these the renderer's <a target="_blank"> gives users no- // standard right-click affordance ("Open in new window", "Copy link- // address"); the default click handler does forward to- // setWindowOpenHandler → openExternalSafely, but discoverability via- // the keyboard / mouse context menu was missing.- if (linkIsHttpUrl) {- if (menu.items.length > 0) {- menu.append(new MenuItem({ type: "separator" }));- }- menu.append(- new MenuItem({- label: labels.openLink,- click: () => {- // openExternalSafely re-validates the scheme — defense in- // depth in case Electron ever surfaces a non-http linkURL- // we forgot to filter at this layer.- void openExternalSafely(linkURL);- },- }),- );- menu.append(- new MenuItem({- label: labels.copyLinkAddress,- click: () => {- // Electron 44 made clipboard writes async (W3C Clipboard API- // alignment); catch so a failed write can't surface as an- // unhandled rejection in the main process.- clipboard.writeText(linkURL).catch((err: unknown) => {- console.warn("[context-menu] copy link address failed", err);- });- },- }),- );- }+ // The latest right-click and the params it came with. A command answers+ // only this one, once; anything older or repeated is dropped.+ let pending: { request: ContextMenuRequest; params: ContextMenuParams } | null = null;+ let nextId = 0;- // Image items — only for an <img> whose pixels have loaded. Copies the- // decoded bitmap Chromium already holds, so it works for any format and- // any origin (signed CDN URLs, blob: URLs) without refetching.- if (mediaType === "image" && hasImageContents) {- if (menu.items.length > 0) {- menu.append(new MenuItem({ type: "separator" }));- }- menu.append(- new MenuItem({- label: labels.copyImage,- click: () => {- webContents.copyImageAt(params.x, params.y);- },- }),- );- }+ webContents.on("context-menu", (_event, params) => {+ nextId += 1;+ const request = buildContextMenuRequest(nextId, params);+ pending = { request, params };+ webContents.send(CONTEXT_MENU_REQUEST_CHANNEL, request);+ });- if (menu.items.length === 0) return;- const window = BrowserWindow.fromWebContents(webContents) ?? undefined;- menu.popup({ window });+ webContents.ipc.on(CONTEXT_MENU_COMMAND_CHANNEL, (_event, raw: unknown) => {+ const command = parseContextMenuCommand(raw);+ if (!command || !pending || !isOfferedCommand(pending.request, command)) return;+ const { params } = pending;+ pending = null;+ runCommand(webContents, params, command);});}-// Labels for the custom menu items in the user's OS-preferred language,-// with English as the fallback. Kept inline because the main process has-// no shared i18n loader (the renderer's i18next is per-window and not-// reachable from here), and pulling one in for three strings would be-// more rope than payload. Matches the five locales the renderer ships.-type ContextMenuLabels = {- openLink: string;- copyLinkAddress: string;- copyImage: string;- addToDictionary: string;-};--const labelsByLocale: Record<string, ContextMenuLabels> = {- en: {- openLink: "Open Link in Browser",- copyLinkAddress: "Copy Link Address",- copyImage: "Copy Image",- addToDictionary: "Add to Dictionary",- },- "zh-Hans": {- openLink: "在浏览器中打开链接",- copyLinkAddress: "复制链接地址",- copyImage: "复制图片",- addToDictionary: "添加到词典",- },- "zh-Hant": {- openLink: "在瀏覽器中開啟連結",- copyLinkAddress: "複製連結網址",- copyImage: "複製圖片",- addToDictionary: "加入字典",- },- ja: {- openLink: "ブラウザでリンクを開く",- copyLinkAddress: "リンクのアドレスをコピー",- copyImage: "画像をコピー",- addToDictionary: "辞書に追加",- },- ko: {- openLink: "브라우저에서 링크 열기",- copyLinkAddress: "링크 주소 복사",- copyImage: "이미지 복사",- addToDictionary: "사전에 추가",- },- es: {- openLink: "Abrir enlace en el navegador",- copyLinkAddress: "Copiar dirección del enlace",- copyImage: "Copiar imagen",- addToDictionary: "Añadir al diccionario",- },- ru: {- openLink: "Открыть ссылку в браузере",- copyLinkAddress: "Копировать адрес ссылки",- copyImage: "Копировать изображение",- addToDictionary: "Добавить в словарь",- },-};+export function buildContextMenuRequest(+ id: number,+ params: ContextMenuParams,+): ContextMenuRequest {+ const { editFlags, isEditable, misspelledWord } = params;+ const hasSelection = params.selectionText.trim().length > 0;+ const spelling = isEditable && !!misspelledWord;+ return {+ id,+ x: params.x,+ y: params.y,+ isEditable,+ canCut: isEditable && editFlags.canCut,+ canCopy: hasSelection && editFlags.canCopy,+ canPaste: isEditable && editFlags.canPaste,+ canSelectAll: isEditable && editFlags.canSelectAll,+ suggestions: spelling ? [...params.dictionarySuggestions] : [],+ canAddToDictionary: spelling,+ // params.linkURL is the resolved absolute URL of the anchor under the+ // cursor. Only http(s) links are offered: other schemes (mailto:,+ // javascript:, the app's own file:// routes) would route through the OS+ // handler, which is outside what this menu promises.+ hasLink: !!params.linkURL && isSafeExternalHttpUrl(params.linkURL),+ // Copies the decoded bitmap Chromium already holds, so it needs pixels.+ hasImage: params.mediaType === "image" && params.hasImageContents,+ };+}-// pickLabels resolves the OS-preferred language to one of the locales we-// ship copy for. We say "Open Link in Browser" rather than-// "Open Link in New Window" because the link is opened via-// shell.openExternal — it lands in the user's default browser, not in-// another Multica window — so the wording matches what actually-// happens.-function pickLabels(): ContextMenuLabels {- const preferred = app.getPreferredSystemLanguages()[0]?.toLowerCase() ?? "";- if (preferred.startsWith("zh")) {- // Traditional-script and Taiwan/Hong Kong/Macau tags get zh-Hant; every- // other Chinese variant gets the Simplified copy.- return /^zh-(hant|tw|hk|mo)\b/.test(preferred)- ? labelsByLocale["zh-Hant"]- : labelsByLocale["zh-Hans"];+function runCommand(+ webContents: WebContents,+ params: ContextMenuParams,+ command: ContextMenuCommand,+): void {+ switch (command.type) {+ case "cut":+ webContents.cut();+ return;+ case "copy":+ webContents.copy();+ return;+ case "paste":+ webContents.paste();+ return;+ case "selectAll":+ webContents.selectAll();+ return;+ case "replaceMisspelling": {+ const suggestion = params.dictionarySuggestions[command.index];+ if (suggestion !== undefined) webContents.replaceMisspelling(suggestion);+ return;+ }+ case "addToDictionary":+ webContents.session.addWordToSpellCheckerDictionary(params.misspelledWord);+ return;+ case "openLink":+ // openExternalSafely re-validates the scheme.+ void openExternalSafely(params.linkURL);+ return;+ case "copyLink":+ // Electron 44 made clipboard writes async; catch so a failed write+ // can't surface as an unhandled rejection in the main process.+ clipboard.writeText(params.linkURL).catch((err: unknown) => {+ console.warn("[context-menu] copy link address failed", err);+ });+ return;+ case "copyImage":+ webContents.copyImageAt(params.x, params.y);+ return;}- if (preferred.startsWith("ja")) return labelsByLocale.ja;- if (preferred.startsWith("ko")) return labelsByLocale.ko;- if (preferred.startsWith("es")) return labelsByLocale.es;- if (preferred.startsWith("ru")) return labelsByLocale.ru;- return labelsByLocale.en;}diff --git a/apps/desktop/src/preload/index.d.ts b/apps/desktop/src/preload/index.d.tsindex c518c926a1..a3fa134653 100644--- a/apps/desktop/src/preload/index.d.ts+++ b/apps/desktop/src/preload/index.d.ts@@ -1,6 +1,7 @@import { ElectronAPI } from "@electron-toolkit/preload";import type { RuntimeConfigResult } from "../shared/runtime-config";import type { NavigationGesture } from "../shared/navigation-gestures";+import type { ContextMenuCommand, ContextMenuRequest } from "../shared/context-menu";import type { RendererRouteContextInput } from "../shared/renderer-route-context";import type { FreezeBreadcrumb } from "../shared/freeze-breadcrumb";import type {@@ -83,6 +84,10 @@ interface DesktopAPI {) => () => void;/** Listen for native macOS back/forward swipe gestures. Returns an unsubscribe function. */onNavigationGesture: (callback: (gesture: NavigationGesture) => void) => () => void;+ /** Listen for right-clicks the page left unhandled, to draw their menu. */+ onContextMenu: (callback: (request: ContextMenuRequest) => void) => () => void;+ /** Run the item picked in that menu. */+ runContextMenuCommand: (command: ContextMenuCommand) => void;/** Report the renderer's memory-router path for recovery diagnostics. */setRendererRouteContext: (context: RendererRouteContextInput) => void;/** Open the OS folder picker and return the chosen absolute path.diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.tsindex d5d95177fb..22da568817 100644--- a/apps/desktop/src/preload/index.ts+++ b/apps/desktop/src/preload/index.ts@@ -20,6 +20,13 @@ import {type IssueWindowRequest,} from "../shared/issue-window";import { AUTH_SESSION_STATE_CHANNEL } from "../shared/auth-session";+import {+ CONTEXT_MENU_COMMAND_CHANNEL,+ CONTEXT_MENU_REQUEST_CHANNEL,+ isContextMenuRequest,+ type ContextMenuCommand,+ type ContextMenuRequest,+} from "../shared/context-menu";import {THEME_FOLDER_CHANGED_CHANNEL,THEME_FOLDER_OPEN_CHANNEL,@@ -223,6 +230,19 @@ const desktopAPI = {ipcRenderer.removeListener(NAVIGATION_GESTURE_CHANNEL, handler);};},+ /** Listen for right-clicks the page left unhandled, to draw their menu. */+ onContextMenu: (callback: (request: ContextMenuRequest) => void) => {+ const handler = (_event: Electron.IpcRendererEvent, request: unknown) => {+ if (isContextMenuRequest(request)) callback(request);+ };+ ipcRenderer.on(CONTEXT_MENU_REQUEST_CHANNEL, handler);+ return () => {+ ipcRenderer.removeListener(CONTEXT_MENU_REQUEST_CHANNEL, handler);+ };+ },+ /** Run the item picked in that menu. */+ runContextMenuCommand: (command: ContextMenuCommand) =>+ ipcRenderer.send(CONTEXT_MENU_COMMAND_CHANNEL, command),/** Report the renderer's memory-router path for recovery diagnostics. */setRendererRouteContext: (context: RendererRouteContextInput) =>ipcRenderer.send(RENDERER_ROUTE_CONTEXT_CHANNEL, context),diff --git a/apps/desktop/src/renderer/src/App.auth-recovery.test.tsx b/apps/desktop/src/renderer/src/App.auth-recovery.test.tsxindex 04e6484bf4..cc0fd48675 100644--- a/apps/desktop/src/renderer/src/App.auth-recovery.test.tsx+++ b/apps/desktop/src/renderer/src/App.auth-recovery.test.tsx@@ -175,6 +175,7 @@ beforeEach(() => {getLastFreeze: vi.fn(),onAuthToken: () => () => {},onCloseActiveTab: () => () => {},+ onContextMenu: () => () => {},onInviteOpen: () => () => {},onIssueOpen: () => () => {},onSystemLocaleChanged: () => () => {},diff --git a/apps/desktop/src/renderer/src/App.tsx b/apps/desktop/src/renderer/src/App.tsxindex 973a5fa0ee..9693cdfb7a 100644--- a/apps/desktop/src/renderer/src/App.tsx+++ b/apps/desktop/src/renderer/src/App.tsx@@ -15,6 +15,7 @@ import { DesktopLoginPage } from "./pages/login";import { DesktopAuthRecoveryPage } from "./pages/auth-recovery";import { DesktopShell } from "./components/desktop-layout";import { UpdateNotification } from "./components/update-notification";+import { NativeContextMenu } from "./components/native-context-menu";import { IssueWindow } from "./components/issue-window";import { useTabStore } from "./stores/tab-store";import { useWindowOverlayStore } from "./stores/window-overlay-store";@@ -486,6 +487,7 @@ export default function App() {localeAdapter={localeAdapter}><DesktopAuthSessionBridge />+ <NativeContextMenu />{windowContext.kind === "main" && <DiagnosticRouteReporter />}{windowContext.kind === "main" && <WorkspaceWindowBridge />}{windowContext.kind === "main" && <IssueDeepLinkBridge />}diff --git a/apps/desktop/src/renderer/src/components/native-context-menu.test.tsx b/apps/desktop/src/renderer/src/components/native-context-menu.test.tsxnew file mode 100644index 0000000000..e01fb61990--- /dev/null+++ b/apps/desktop/src/renderer/src/components/native-context-menu.test.tsx@@ -0,0 +1,288 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { useState } from "react";+import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { I18nProvider } from "@multica/core/i18n/react";+import type { SupportedLocale } from "@multica/core/i18n";+import { RESOURCES } from "@multica/views/locales";+import { useContextMenuScope, type ContextMenuScope } from "@multica/views/common/context-menu-scope";+import type { ContextMenuRequest } from "../../../shared/context-menu";+import { SessionRenameInput } from "../../../../../../packages/views/chat/components/session-rename-input";+import { NativeContextMenu, tableToMarkdown } from "./native-context-menu";++const api = vi.hoisted(() => ({+ listener: null as ((request: ContextMenuRequest) => void) | null,+ runContextMenuCommand: vi.fn(),+ copyText: vi.fn(async (_text: string) => true),+}));++vi.mock("@multica/ui/lib/clipboard", () => ({ copyText: api.copyText }));++beforeEach(() => {+ api.listener = null;+ api.runContextMenuCommand.mockClear();+ api.copyText.mockClear();+ Object.assign(window, {+ desktopAPI: {+ onContextMenu: (callback: (request: ContextMenuRequest) => void) => {+ api.listener = callback;+ return () => {+ api.listener = null;+ };+ },+ runContextMenuCommand: api.runContextMenuCommand,+ },+ });+});++afterEach(() => {+ delete (window as { desktopAPI?: unknown }).desktopAPI;+});++function renderHost(locale: SupportedLocale = "en", page?: React.ReactNode) {+ return render(+ <I18nProvider locale={locale} resources={RESOURCES}>+ {page}+ <NativeContextMenu />+ </I18nProvider>,+ );+}++function Scope({ read, children }: { read: () => Partial<ContextMenuScope> | null; children: React.ReactNode }) {+ return <div ref={useContextMenuScope(read)}>{children}</div>;+}++/** A DOM right-click on `target`, then main's request for it. */+function rightClick(target: Element, req: ContextMenuRequest) {+ fireEvent.contextMenu(target, { clientX: 5, clientY: 5 });+ open(req);+}++function menuLabels() {+ return screen.getAllByRole("menuitem").map((item) => item.textContent);+}++function request(over: Partial<ContextMenuRequest>): ContextMenuRequest {+ return {+ id: 1,+ x: 10,+ y: 20,+ isEditable: false,+ canCut: false,+ canCopy: false,+ canPaste: false,+ canSelectAll: false,+ suggestions: [],+ canAddToDictionary: false,+ hasLink: false,+ hasImage: false,+ ...over,+ };+}++function open(req: ContextMenuRequest) {+ act(() => api.listener?.(req));+}++describe("NativeContextMenu", () => {+ it("draws only the items the request offers, in the app's language", async () => {+ renderHost("zh-Hans");+ open(request({ isEditable: true, canPaste: true, canSelectAll: true }));++ expect(await screen.findByRole("menuitem", { name: /粘贴/ })).toBeInTheDocument();+ expect(screen.getByRole("menuitem", { name: /全选/ })).toBeInTheDocument();+ expect(screen.queryByRole("menuitem", { name: /剪切/ })).toBeNull();+ expect(screen.queryByRole("menuitem", { name: /复制/ })).toBeNull();+ });++ it("lists spelling suggestions first and sends the picked index", async () => {+ renderHost();+ open(request({ id: 7, isEditable: true, suggestions: ["the", "tea"], canAddToDictionary: true }));++ const items = await screen.findAllByRole("menuitem");+ expect(items.map((item) => item.textContent)).toEqual(["the", "tea", "Add to dictionary"]);++ fireEvent.click(screen.getByRole("menuitem", { name: "tea" }));+ await waitFor(() =>+ expect(api.runContextMenuCommand).toHaveBeenCalledWith({+ id: 7,+ type: "replaceMisspelling",+ index: 1,+ }),+ );+ });++ it("sends the command once the menu has closed", async () => {+ renderHost();+ open(request({ id: 3, hasLink: true, hasImage: true }));++ fireEvent.click(await screen.findByRole("menuitem", { name: "Copy link address" }));+ await waitFor(() =>+ expect(api.runContextMenuCommand).toHaveBeenCalledWith({ id: 3, type: "copyLink" }),+ );+ expect(api.runContextMenuCommand).toHaveBeenCalledTimes(1);+ await waitFor(() => expect(screen.queryByRole("menu")).toBeNull());+ });++ it("sends nothing when the menu is dismissed", async () => {+ renderHost();+ open(request({ canCopy: true }));++ const menu = await screen.findByRole("menu");+ fireEvent.keyDown(menu, { key: "Escape" });+ await waitFor(() => expect(screen.queryByRole("menu")).toBeNull());+ expect(api.runContextMenuCommand).not.toHaveBeenCalled();+ });++ it("draws nothing for a right-click neither main nor the page has items for", () => {+ renderHost("en", <p>plain</p>);+ rightClick(screen.getByText("plain"), request({}));+ expect(screen.queryByRole("menu")).toBeNull();+ });++ it("offers Copy code on a code block and copies its text", async () => {+ renderHost("en", <pre><code>const a = 1;</code></pre>);+ rightClick(screen.getByText("const a = 1;"), request({}));++ fireEvent.click(await screen.findByRole("menuitem", { name: "Copy code" }));+ await waitFor(() => expect(api.copyText).toHaveBeenCalledWith("const a = 1;"));+ expect(api.runContextMenuCommand).not.toHaveBeenCalled();+ });++ it("copies a table as Markdown", () => {+ const table = document.createElement("table");+ table.innerHTML = "<tr><th>Name</th><th>A|B</th></tr><tr><td>x</td><td>y</td></tr>";+ expect(tableToMarkdown(table)).toBe("| Name | A\\|B |\n| --- | --- |\n| x | y |");+ });++ it("follows the content with the surrounding object's actions in one submenu", async () => {+ const reply = vi.fn();+ renderHost(+ "en",+ <Scope+ read={() => ({+ label: "Comment actions",+ icon: null,+ groups: [[{ key: "reply", icon: null, label: "Reply", onSelect: reply }]],+ selectionActions: (text) => [+ { key: "issue", icon: null, label: `Create issue: ${text}`, onSelect: vi.fn() },+ ],+ })}+ >+ <a href="https://example.com">a link</a>+ </Scope>,+ );+ rightClick(screen.getByText("a link"), request({ hasLink: true }));++ await screen.findByRole("menu");+ expect(screen.getByText("https://example.com/")).toBeInTheDocument();+ expect(menuLabels()).toEqual(["Open link in browser", "Copy link address", "Comment actions"]);++ fireEvent.click(screen.getByRole("menuitem", { name: "Comment actions" }));+ fireEvent.click(await screen.findByRole("menuitem", { name: "Reply" }));+ await waitFor(() => expect(reply).toHaveBeenCalledTimes(1));+ });++ it("adds the scope's selection actions after Copy", async () => {+ renderHost(+ "en",+ <Scope read={() => ({ selectionActions: (text) => [{ key: "a", icon: null, label: `Add ${text}`, onSelect: vi.fn() }] })}>+ <p>selected words</p>+ </Scope>,+ );+ const text = screen.getByText("selected words");+ const range = document.createRange();+ range.selectNodeContents(text);+ window.getSelection()!.removeAllRanges();+ window.getSelection()!.addRange(range);+ rightClick(text, request({ canCopy: true }));++ await screen.findByRole("menu");+ expect(menuLabels()).toEqual([expect.stringMatching(/^Copy/), "Add selected words"]);+ });++ it("leaves out selection entries for the word a right-click selects by itself", async () => {+ renderHost(+ "en",+ <Scope read={() => ({ selectionActions: () => [{ key: "a", icon: null, label: "Add", onSelect: vi.fn() }] })}>+ <p>a word</p>+ </Scope>,+ );+ window.getSelection()!.removeAllRanges();+ const text = screen.getByText("a word");+ fireEvent.contextMenu(text, { clientX: 5, clientY: 5 });+ // macOS selects the word as the right-click's default action.+ const range = document.createRange();+ range.selectNodeContents(text);+ window.getSelection()!.addRange(range);+ open(request({ canCopy: true }));++ await screen.findByRole("menu");+ expect(menuLabels()).toEqual([expect.stringMatching(/^Copy/)]);+ window.getSelection()!.removeAllRanges();+ });++ it("lets an attachment's own actions replace the link entries", async () => {+ renderHost(+ "en",+ <Scope read={() => ({ contentActions: [{ key: "preview", icon: null, label: "Preview", onSelect: vi.fn() }] })}>+ <a href="https://cdn.example/file.pdf?sig=1">file.pdf</a>+ </Scope>,+ );+ rightClick(screen.getByText("file.pdf"), request({ hasLink: true }));++ await screen.findByRole("menu");+ expect(menuLabels()).toEqual(["Preview"]);+ });++ it("keeps a text field to its edit menu", async () => {+ renderHost(+ "en",+ <Scope read={() => ({ label: "Comment actions", icon: null, groups: [[{ key: "r", icon: null, label: "Reply", onSelect: vi.fn() }]] })}>+ <textarea aria-label="field" />+ </Scope>,+ );+ rightClick(screen.getByLabelText("field"), request({ isEditable: true, canPaste: true }));++ await screen.findByRole("menu");+ expect(menuLabels()).toEqual([expect.stringMatching(/^Paste/)]);+ });++ it("opens the focused element's menu on Shift+F10", () => {+ const onContextMenu = vi.fn((event: React.MouseEvent) => event.preventDefault());+ renderHost("en", <button type="button" onContextMenu={onContextMenu}>row</button>);+ const button = screen.getByText("row");+ button.focus();++ expect(fireEvent.keyDown(button, { key: "F10", shiftKey: true })).toBe(false);+ expect(onContextMenu).toHaveBeenCalledTimes(1);++ fireEvent.keyDown(button, { key: "F10" });+ expect(onContextMenu).toHaveBeenCalledTimes(1);+ });++ it("does not suppress the native key when no DOM handler claims the link", () => {+ renderHost("en", <a href="https://example.com">regular link</a>);+ const link = screen.getByRole("link");+ link.focus();+ const handled = fireEvent.keyDown(link, { key: "F10", shiftKey: true });+ expect({ nativeAllowed: handled, customMenu: !!screen.queryByRole("menu") }).toEqual({ nativeAllowed: true, customMenu: false });+ });++ it("does not commit an inline title when choosing Cut from its context menu", async () => {+ const submit = vi.fn();+ function RenameHost() {+ const [editing, setEditing] = useState(true);+ return editing ? <SessionRenameInput initialValue="alpha beta" onSubmit={(value) => { submit(value); setEditing(false); }} onCancel={() => setEditing(false)} /> : <span>Committed title</span>;+ }+ renderHost("en", <RenameHost />);+ const input = screen.getByRole("textbox") as HTMLInputElement;+ input.focus();+ input.setSelectionRange(0, 5);+ rightClick(input, request({ isEditable: true, canCut: true, canCopy: true }));+ const cut = await screen.findByRole("menuitem", { name: /^Cut/ });+ fireEvent.pointerDown(cut, { button: 0 });+ fireEvent.click(cut);+ await waitFor(() => expect(api.runContextMenuCommand).toHaveBeenCalled());+ expect({ submitted: submit.mock.calls.length, inputConnected: input.isConnected }).toEqual({ submitted: 0, inputConnected: true });+ });+});diff --git a/apps/desktop/src/renderer/src/components/native-context-menu.tsx b/apps/desktop/src/renderer/src/components/native-context-menu.tsxnew file mode 100644index 0000000000..420e267d41--- /dev/null+++ b/apps/desktop/src/renderer/src/components/native-context-menu.tsx@@ -0,0 +1,348 @@+import { Fragment, useEffect, useMemo, useRef, useState, type ReactNode } from "react";+import { toast } from "sonner";+import { Code, Globe, ImageIcon, Link2, Table2 } from "@multica/ui/icons";+import {+ ContextMenu,+ ContextMenuContent,+ ContextMenuItem,+ ContextMenuSeparator,+ ContextMenuShortcut,+} from "@multica/ui/components/ui/context-menu";+import { copyText } from "@multica/ui/lib/clipboard";+import { createShortcutChord, formatShortcut } from "@multica/core/shortcuts";+import { useT } from "@multica/views/i18n";+import {+ ContextMenuScopeSubmenu,+ findContextMenuScope,+ type ResolvedContextMenuScope,+ type RowActionItem,+} from "@multica/views/common/context-menu-scope";+import { contextPrimitives } from "@multica/views/common/menu-primitives";+import {+ contextMenuActions,+ hasContextMenuItems,+ type ContextMenuAction,+ type ContextMenuCommand,+ type ContextMenuRequest,+} from "../../../shared/context-menu";+import { useKeyboardContextMenu } from "../hooks/use-keyboard-context-menu";++/** A request older than this no longer belongs to the last DOM right-click. */+const POINT_MAX_AGE_MS = 1000;++/** What the page itself adds to a right-click outside a text field. */+interface PageItems {+ linkUrl: string | null;+ scope: ResolvedContextMenuScope;+ selection: RowActionItem[];+ code: string | null;+ table: string | null;+}++interface OpenMenu {+ request: ContextMenuRequest;+ point: { x: number; y: number };+ /** Focus and selection when the menu opened; an edit command needs both back. */+ focus: HTMLElement | null;+ ranges: Range[];+ page: PageItems | null;+}++type Pending = { kind: "command"; command: ContextMenuCommand } | { kind: "local"; run: () => void };++function isTextField(el: HTMLElement | null): boolean {+ return el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement;+}++function restoreSelection(menu: OpenMenu) {+ // A text field keeps its own selection across focus changes; putting the+ // document ranges back would collapse it.+ if (isTextField(menu.focus)) return;+ const selection = window.getSelection();+ if (!selection || menu.ranges.length === 0) return;+ if (!menu.ranges.every((range) => range.startContainer.isConnected && range.endContainer.isConnected)) return;+ selection.removeAllRanges();+ for (const range of menu.ranges) selection.addRange(range);+}++function cellText(cell: HTMLTableCellElement): string {+ return (cell.textContent ?? "").trim().replace(/\s+/g, " ").replace(/\|/g, "\\|");+}++/** A rendered table as Markdown, its first row as the header. */+export function tableToMarkdown(table: HTMLTableElement): string {+ const rows = Array.from(table.rows, (row) => Array.from(row.cells, cellText));+ if (rows.length === 0) return "";+ const width = Math.max(...rows.map((row) => row.length));+ const line = (cells: string[]) =>+ `| ${Array.from({ length: width }, (_, i) => cells[i] ?? "").join(" | ")} |`;+ const [header, ...body] = rows;+ return [line(header!), line(Array(width).fill("---")), ...body.map(line)].join("\n");+}++function readPageItems(target: Element | null, request: ContextMenuRequest, selectedText: string): PageItems | null {+ // A text field only gets its edit menu.+ if (request.isEditable) return null;+ const scope = findContextMenuScope(target);+ const text = selectedText.trim();+ const pre = target?.closest("pre");+ const table = target?.closest("table");+ return {+ linkUrl: request.hasLink ? (target?.closest("a[href]") as HTMLAnchorElement | null)?.href ?? null : null,+ scope,+ selection: request.canCopy && text ? scope.selectionActions(text) : [],+ code: pre ? (pre.querySelector("code") ?? pre).textContent : null,+ table: table ? tableToMarkdown(table) : null,+ };+}++function hasPageItems(page: PageItems | null): boolean {+ if (!page) return false;+ return (+ !!page.scope.submenu ||+ page.scope.contentActions.length > 0 ||+ page.selection.length > 0 ||+ !!page.code ||+ !!page.table+ );+}++/**+ * Draws the menu for a right-click the page left unhandled — a text field,+ * selected text, a link, an image, code, a table, an attachment — which main+ * forwards instead of popping a native menu, so every menu in the app shares+ * one language and one look. Main's items act on its own copy of the click;+ * the page adds what only it knows: the attachment's own actions, the code to+ * copy, and the object around the content (a comment) as one submenu. Picking+ * an item runs it once the menu has closed and focus and selection are back+ * where the right-click found them, since cut, copy and paste act on whatever+ * holds them. Shift+F10 and the menu key open the focused element's menu.+ */+export function NativeContextMenu() {+ const { t } = useT("layout");+ useKeyboardContextMenu();+ const [menu, setMenu] = useState<OpenMenu | null>(null);+ const [open, setOpen] = useState(false);+ const lastEvent = useRef<{+ x: number;+ y: number;+ at: number;+ target: Element | null;+ selectedText: string;+ } | null>(null);+ const pending = useRef<Pending | null>(null);++ useEffect(() => {+ // Capture phase, so a right-click is seen even when a handler stops it.+ // The DOM position is in the page's own coordinates; Electron's is not+ // once the page is zoomed. The selection is read before the event's+ // default action, which on macOS selects the word under the cursor: only+ // text the user selected gets the selection entries.+ const record = (event: MouseEvent) => {+ lastEvent.current = {+ x: event.clientX,+ y: event.clientY,+ at: performance.now(),+ target: event.target instanceof Element ? event.target : null,+ selectedText: window.getSelection()?.toString() ?? "",+ };+ };+ window.addEventListener("contextmenu", record, true);+ const unsubscribe = window.desktopAPI.onContextMenu((request) => {+ const last = lastEvent.current;+ const fresh = !!last && performance.now() - last.at < POINT_MAX_AGE_MS;+ const point = fresh ? { x: last.x, y: last.y } : { x: request.x, y: request.y };+ const active = document.activeElement;+ const selection = window.getSelection();+ const ranges = selection+ ? Array.from({ length: selection.rangeCount }, (_, i) => selection.getRangeAt(i).cloneRange())+ : [];+ const page = readPageItems(+ fresh ? last.target : null,+ request,+ fresh ? last.selectedText : ranges.map((range) => range.toString()).join(""),+ );+ if (!hasContextMenuItems(request) && !hasPageItems(page)) return;+ pending.current = null;+ setMenu({+ request,+ point,+ focus: active instanceof HTMLElement && active !== document.body ? active : null,+ ranges,+ page,+ });+ setOpen(true);+ });+ return () => {+ window.removeEventListener("contextmenu", record, true);+ unsubscribe();+ };+ }, []);++ const point = menu?.point;+ const anchor = useMemo(+ () =>+ point+ ? {+ getBoundingClientRect: () =>+ DOMRect.fromRect({ x: point.x, y: point.y, width: 0, height: 0 }),+ }+ : undefined,+ [point],+ );++ if (!menu) return null;++ const { request, page } = menu;+ const contentActions = page?.scope.contentActions ?? [];+ // An attachment's own Copy link replaces the browser's link entries, which+ // would hand out the raw signed URL.+ const actions = new Set(+ contextMenuActions(request).filter(+ (type) => contentActions.length === 0 || (type !== "openLink" && type !== "copyLink"),+ ),+ );+ const pick = (command: ContextMenuCommand) => {+ pending.current = { kind: "command", command };+ };+ const pickLocal = (run: () => void) => {+ pending.current = { kind: "local", run };+ };+ const copy = (text: string) => {+ void copyText(text).then((ok) =>+ ok ? toast.success(t(($) => $.context_menu.copied)) : toast.error(t(($) => $.context_menu.copy_failed)),+ );+ };+ const shortcut = (key: string) => formatShortcut(createShortcutChord(key, { primary: true }));++ const labels: Record<ContextMenuAction, string> = {+ cut: t(($) => $.context_menu.cut),+ copy: t(($) => $.context_menu.copy),+ paste: t(($) => $.context_menu.paste),+ selectAll: t(($) => $.context_menu.select_all),+ addToDictionary: t(($) => $.context_menu.add_to_dictionary),+ openLink: t(($) => $.context_menu.open_link),+ copyLink: t(($) => $.context_menu.copy_link_address),+ copyImage: t(($) => $.context_menu.copy_image),+ };+ const extras: Partial<Record<ContextMenuAction, ReactNode>> = {+ cut: <ContextMenuShortcut>{shortcut("X")}</ContextMenuShortcut>,+ copy: <ContextMenuShortcut>{shortcut("C")}</ContextMenuShortcut>,+ paste: <ContextMenuShortcut>{shortcut("V")}</ContextMenuShortcut>,+ selectAll: <ContextMenuShortcut>{shortcut("A")}</ContextMenuShortcut>,+ };+ const icons: Partial<Record<ContextMenuAction, ReactNode>> = {+ openLink: <Globe />,+ copyLink: <Link2 />,+ copyImage: <ImageIcon />,+ };+ const item = (type: ContextMenuAction) =>+ actions.has(type) ? (+ <ContextMenuItem key={type} onClick={() => pick({ id: request.id, type })}>+ {icons[type]}+ {labels[type]}+ {extras[type]}+ </ContextMenuItem>+ ) : null;+ const localItem = (action: RowActionItem) => (+ <ContextMenuItem+ key={action.key}+ variant={action.danger ? "destructive" : "default"}+ onClick={() => pickLocal(action.onSelect)}+ >+ {action.icon}+ {action.label}+ </ContextMenuItem>+ );+ const submenu = page?.scope.submenu+ ? {+ ...page.scope.submenu,+ groups: page.scope.submenu.groups.map((group) =>+ group.map((action) => ({ ...action, onSelect: () => pickLocal(action.onSelect) })),+ ),+ }+ : null;++ const groups: ReactNode[][] = [+ [+ ...request.suggestions.map((suggestion, index) => (+ <ContextMenuItem+ key={`suggestion-${index}`}+ className="font-medium"+ onClick={() => pick({ id: request.id, type: "replaceMisspelling", index })}+ >+ {suggestion}+ </ContextMenuItem>+ )),+ item("addToDictionary"),+ ],+ contentActions.map(localItem),+ [item("cut"), item("copy"), item("paste"), ...(page?.selection ?? []).map(localItem)],+ [item("selectAll")],+ [item("openLink"), item("copyLink")],+ [item("copyImage")],+ [+ page?.code+ ? localItem({+ key: "copy-code",+ icon: <Code />,+ label: t(($) => $.context_menu.copy_code),+ onSelect: () => copy(page.code!),+ })+ : null,+ page?.table+ ? localItem({+ key: "copy-table",+ icon: <Table2 />,+ label: t(($) => $.context_menu.copy_table),+ onSelect: () => copy(page.table!),+ })+ : null,+ ],+ ]+ .map((group) => group.filter(Boolean))+ .filter((group) => group.length > 0);++ return (+ <ContextMenu+ open={open}+ onOpenChange={setOpen}+ onOpenChangeComplete={(isOpen) => {+ if (isOpen) return;+ const picked = pending.current;+ pending.current = null;+ if (!picked) return;+ restoreSelection(menu);+ if (picked.kind === "command") window.desktopAPI.runContextMenuCommand(picked.command);+ else picked.run();+ }}+ >+ <ContextMenuContent+ anchor={anchor}+ side="bottom"+ align="start"+ alignOffset={0}+ // A page action moves focus itself — into a reply box, an emoji picker.+ finalFocus={() => (pending.current?.kind === "local" ? false : menu.focus ?? false)}+ className="w-auto min-w-44 max-w-80"+ >+ {page?.linkUrl && (+ <div className="truncate px-2 py-1.5 text-xs text-muted-foreground" title={page.linkUrl}>+ {page.linkUrl}+ </div>+ )}+ {groups.map((group, index) => (+ <Fragment key={index}>+ {(index > 0 || !!page?.linkUrl) && <ContextMenuSeparator />}+ {group}+ </Fragment>+ ))}+ <ContextMenuScopeSubmenu+ submenu={submenu}+ primitives={contextPrimitives}+ separated={groups.length > 0 || !!page?.linkUrl}+ />+ </ContextMenuContent>+ </ContextMenu>+ );+}diff --git a/apps/desktop/src/renderer/src/components/tab-bar.test.tsx b/apps/desktop/src/renderer/src/components/tab-bar.test.tsxindex 0a98cfc93b..e6034a29c7 100644--- a/apps/desktop/src/renderer/src/components/tab-bar.test.tsx+++ b/apps/desktop/src/renderer/src/components/tab-bar.test.tsx@@ -34,6 +34,7 @@ const state = vi.hoisted(() => ({togglePin: vi.fn<(tabId: string) => void>(),closeTab: vi.fn<(tabId: string) => void>(),closeOtherTabs: vi.fn<(tabId: string) => void>(),+ closeTabsToRight: vi.fn<(tabId: string) => void>(),setActiveTab: vi.fn<(tabId: string) => void>(),moveTab: vi.fn<(from: number, to: number) => void>(),addTab: vi.fn<(path: string, title: string) => string>(),@@ -52,6 +53,7 @@ vi.mock("@/stores/tab-store", () => {togglePin: state.togglePin,closeTab: state.closeTab,closeOtherTabs: state.closeOtherTabs,+ closeTabsToRight: state.closeTabsToRight,setActiveTab: state.setActiveTab,moveTab: state.moveTab,addTab: state.addTab,@@ -69,6 +71,10 @@ vi.mock("@/stores/tab-store", () => {return { useTabStore, useActiveGroup };});+vi.mock("@multica/views/navigation", () => ({+ useNavigation: () => ({ getShareableUrl: (path: string) => `https://app.example${path}` }),+}));+vi.mock("@multica/core/paths", async (importOriginal) => ({// Spread the real module so pure helpers (parseTabSubject etc.) keep working....(await importOriginal<typeof import("@multica/core/paths")>()),@@ -133,6 +139,7 @@ function reset() {state.togglePin.mockReset();state.closeTab.mockReset();state.closeOtherTabs.mockReset();+ state.closeTabsToRight.mockReset();state.setActiveTab.mockReset();state.moveTab.mockReset();state.addTab.mockReset();@@ -566,6 +573,28 @@ describe("TabBar context menu", () => {expect(state.closeOtherTabs).toHaveBeenCalledWith("tB");});+ it("closes the tabs to the right, and only offers it when one would close", async () => {+ state.byWorkspace.acme.tabs = [+ { id: "tA", url: "/acme/issues", title: "Issues", pinned: false },+ { id: "tB", url: "/acme/projects", title: "Projects", pinned: false },+ { id: "tC", url: "/acme/agents", title: "Agents", pinned: true },+ ];++ const { findByRole, getByLabelText, unmount } = render(<TabBar />);+ fireEvent.contextMenu(getByLabelText("Issues"));+ fireEvent.click(await findByRole("menuitem", { name: "Close tabs to the right" }));+ expect(state.closeTabsToRight).toHaveBeenCalledWith("tA");+ unmount();++ // Only a pinned tab sits to the right of Projects.+ const second = render(<TabBar />);+ fireEvent.contextMenu(second.getByLabelText("Projects"));+ expect(await second.findByRole("menuitem", { name: "Close tabs to the right" })).toHaveAttribute(+ "aria-disabled",+ "true",+ );+ });+});describe("TabBar locale", () => {diff --git a/apps/desktop/src/renderer/src/components/tab-bar.tsx b/apps/desktop/src/renderer/src/components/tab-bar.tsxindex 4ed59a6721..89ac4087a5 100644--- a/apps/desktop/src/renderer/src/components/tab-bar.tsx+++ b/apps/desktop/src/renderer/src/components/tab-bar.tsx@@ -8,7 +8,10 @@ import {} from "react";import { motion } from "motion/react";import { useReducedMotion } from "@multica/core/appearance";-import { X, Plus, Pin, PinOff, ListX, AppWindow } from "@multica/ui/icons";+import { toast } from "sonner";+import { X, Plus, Pin, PinOff, ListX, ListEnd, AppWindow, Link2 } from "@multica/ui/icons";+import { copyText } from "@multica/ui/lib/clipboard";+import { useNavigation } from "@multica/views/navigation";import {DndContext,PointerSensor,@@ -135,6 +138,7 @@ function SortableTabItem({isActive,isOnly,canCloseOthers,+ canCloseRight,isNew,shouldReduceMotion,}: {@@ -147,6 +151,7 @@ function SortableTabItem({*/isOnly: boolean;canCloseOthers: boolean;+ canCloseRight: boolean;isNew: boolean;shouldReduceMotion: boolean;}) {@@ -154,6 +159,8 @@ function SortableTabItem({const setActiveTab = useTabStore((s) => s.setActiveTab);const closeTab = useTabStore((s) => s.closeTab);const closeOtherTabs = useTabStore((s) => s.closeOtherTabs);+ const closeTabsToRight = useTabStore((s) => s.closeTabsToRight);+ const { getShareableUrl } = useNavigation();const togglePin = useTabStore((s) => s.togglePin);const updateTab = useTabStore((s) => s.updateTab);const issueWindowPath = parseIssueWindowPath(tab.url);@@ -222,6 +229,12 @@ function SortableTabItem({e.stopPropagation();};+ const handleCopyLink = () => {+ void copyText(getShareableUrl(tab.url)).then((ok) => {+ if (ok) toast.success(t(($) => $.desktop.tab_bar.link_copied));+ });+ };+const handleOpenAsWindow = () => {if (!issueWindowPath) return;void window.desktopAPI.openIssueWindow({@@ -360,6 +373,10 @@ function SortableTabItem({</>)}</ContextMenuItem>+ <ContextMenuItem onClick={handleCopyLink}>+ <Link2 />+ {t(($) => $.desktop.tab_bar.copy_link)}+ </ContextMenuItem><ContextMenuSeparator /><ContextMenuItemvariant="destructive"@@ -377,6 +394,14 @@ function SortableTabItem({<ListX />{closeOthersLabel}</ContextMenuItem>+ <ContextMenuItem+ variant="destructive"+ disabled={!canCloseRight}+ onClick={() => closeTabsToRight(tab.id)}+ >+ <ListEnd />+ {t(($) => $.desktop.tab_bar.close_right)}+ </ContextMenuItem></ContextMenuContent></ContextMenu>{showAddedHighlight && (@@ -608,6 +633,9 @@ export function TabBar() {canCloseOthers={tabs.some((candidate) => candidate.id !== tab.id && !candidate.pinned,)}+ canCloseRight={tabs.some(+ (candidate, i) => i > index && !candidate.pinned,+ )}isNew={addedTabIdSet.has(tab.id)}shouldReduceMotion={shouldReduceMotion}/>diff --git a/apps/desktop/src/renderer/src/hooks/use-keyboard-context-menu.ts b/apps/desktop/src/renderer/src/hooks/use-keyboard-context-menu.tsnew file mode 100644index 0000000000..2c0cc48fec--- /dev/null+++ b/apps/desktop/src/renderer/src/hooks/use-keyboard-context-menu.ts@@ -0,0 +1,64 @@+import { useEffect } from "react";++/** A trusted `contextmenu` this soon after ours is Chromium's own for the same key. */+const NATIVE_ECHO_MS = 500;++function isEditable(el: Element): boolean {+ return (+ el instanceof HTMLInputElement ||+ el instanceof HTMLTextAreaElement ||+ el instanceof HTMLSelectElement ||+ (el instanceof HTMLElement && el.isContentEditable)+ );+}++/** Whether `event` asks for the focused element's context menu. */+export function isContextMenuKey(event: KeyboardEvent): boolean {+ if (event.key === "ContextMenu") return !event.metaKey && !event.ctrlKey && !event.altKey;+ return event.key === "F10" && event.shiftKey && !event.metaKey && !event.ctrlKey && !event.altKey;+}++/**+ * Shift+F10 and the menu key open the focused element's menu, as a+ * right-click on it would: every menu in the app listens for `contextmenu`,+ * so the keyboard gets the same menus with no per-menu wiring. Chromium does+ * this itself on Windows and Linux but not on macOS, and its event lands at+ * the element's corner; ours does it everywhere, near the element's start.+ * The key is only taken over when an app menu claims the event; otherwise+ * (a plain link, text fields) the platform's own path stays intact.+ */+export function useKeyboardContextMenu() {+ useEffect(() => {+ let dispatchedAt = -Infinity;+ const onKeyDown = (event: KeyboardEvent) => {+ if (event.defaultPrevented || !isContextMenuKey(event)) return;+ const target = document.activeElement;+ if (!target || target === document.body || isEditable(target)) return;+ const rect = target.getBoundingClientRect();+ const claimed = !target.dispatchEvent(+ new MouseEvent("contextmenu", {+ bubbles: true,+ cancelable: true,+ button: 2,+ clientX: rect.left + Math.min(16, rect.width / 2),+ clientY: rect.top + Math.min(rect.height, 24) / 2,+ }),+ );+ if (!claimed) return;+ event.preventDefault();+ dispatchedAt = performance.now();+ };+ const swallowEcho = (event: MouseEvent) => {+ if (!event.isTrusted || performance.now() - dispatchedAt > NATIVE_ECHO_MS) return;+ dispatchedAt = -Infinity;+ event.preventDefault();+ event.stopImmediatePropagation();+ };+ window.addEventListener("keydown", onKeyDown);+ window.addEventListener("contextmenu", swallowEcho, true);+ return () => {+ window.removeEventListener("keydown", onKeyDown);+ window.removeEventListener("contextmenu", swallowEcho, true);+ };+ }, []);+}diff --git a/apps/desktop/src/renderer/src/platform/navigation.tsx b/apps/desktop/src/renderer/src/platform/navigation.tsxindex 0381e0e8d8..2b56bf2bb0 100644--- a/apps/desktop/src/renderer/src/platform/navigation.tsx+++ b/apps/desktop/src/renderer/src/platform/navigation.tsx@@ -18,6 +18,7 @@ import {openWorkspaceInNewWindow,otherWindowWorkspaces,} from "./workspace-windows";+import { parseIssueWindowPath } from "../../../shared/issue-window";function requireRuntimeAppUrl(scope: string): string {const runtimeConfig = window.desktopAPI.runtimeConfig;@@ -266,6 +267,10 @@ export function DesktopNavigationProvider({store.openTab(path, title ?? "", { activate: opts?.activate });},openWorkspaceInNewWindow,+ openIssueInNewWindow: (path: string, title: string) => {+ if (!parseIssueWindowPath(path)) return;+ void window.desktopAPI.openIssueWindow({ path, title });+ },workspacesInOtherWindows: () => [...otherWindowWorkspaces()],getShareableUrl: (path: string) => `${appUrl}${path}`,}),diff --git a/apps/desktop/src/renderer/src/stores/tab-store.test.ts b/apps/desktop/src/renderer/src/stores/tab-store.test.tsindex a9ea5e3324..a756996c67 100644--- a/apps/desktop/src/renderer/src/stores/tab-store.test.ts+++ b/apps/desktop/src/renderer/src/stores/tab-store.test.ts@@ -1007,6 +1007,22 @@ describe("bulk tab closing", () => {expect(group.tabs.map((tab) => tab.id)).toEqual([issuesId, projectsId]);expect(group.activeTabId).toBe(issuesId);});++ it("closes only the unpinned tabs to the right of the target", () => {+ const store = useTabStore.getState();+ store.switchWorkspace("acme");+ const issuesId = useTabStore.getState().byWorkspace.acme.tabs[0].id;+ const projectsId = store.addTab("/acme/projects", "Projects");+ const agentsId = store.addTab("/acme/agents", "Agents");+ store.addTab("/acme/settings", "Settings");+ store.setActiveTab(agentsId);++ store.closeTabsToRight(projectsId);++ const group = useTabStore.getState().byWorkspace.acme;+ expect(group.tabs.map((tab) => tab.id)).toEqual([issuesId, projectsId]);+ expect(group.activeTabId).toBe(projectsId);+ });});describe("closeTab activation order (MUL-5665)", () => {diff --git a/apps/desktop/src/renderer/src/stores/tab-store.ts b/apps/desktop/src/renderer/src/stores/tab-store.tsindex ed65f60a27..6f2384992c 100644--- a/apps/desktop/src/renderer/src/stores/tab-store.ts+++ b/apps/desktop/src/renderer/src/stores/tab-store.ts@@ -200,6 +200,8 @@ interface TabStore {closeTab: (tabId: string) => void;/** Close every other unpinned tab in the target tab's workspace. */closeOtherTabs: (tabId: string) => void;+ /** Close the unpinned tabs after the target tab in its workspace. */+ closeTabsToRight: (tabId: string) => void;/*** Activate a tab. Finds it across all workspaces. Sets both the owning* workspace as active and that group's activeTabId; needed for any code@@ -682,12 +684,13 @@ function findTabLocation(function buildCloseOtherTabsResult(byWorkspace: Record<string, WorkspaceTabGroup>,tabId: string,+ scope: "others" | "right" = "others",): Record<string, WorkspaceTabGroup> | null {const hit = findTabLocation(byWorkspace, tabId);if (!hit) return null;- const { slug, group } = hit;+ const { slug, group, index } = hit;const closingTabs = group.tabs.filter(- (tab) => !tab.pinned && tab.id !== tabId,+ (tab, i) => !tab.pinned && tab.id !== tabId && (scope === "others" || i > index),);if (closingTabs.length === 0) return null;@@ -961,6 +964,13 @@ export const useTabStore = create<TabStore>()(set({ byWorkspace: next });},+ closeTabsToRight(tabId) {+ const { byWorkspace } = get();+ const next = buildCloseOtherTabsResult(byWorkspace, tabId, "right");+ if (!next) return;+ set({ byWorkspace: next });+ },+setActiveTab(tabId) {const { byWorkspace, activeWorkspaceSlug } = get();const hit = findTabLocation(byWorkspace, tabId);diff --git a/apps/desktop/src/shared/context-menu.ts b/apps/desktop/src/shared/context-menu.tsnew file mode 100644index 0000000000..57449cb0a2--- /dev/null+++ b/apps/desktop/src/shared/context-menu.ts@@ -0,0 +1,124 @@+/** main → renderer: a right-click the page left unhandled, to draw a menu for. */+export const CONTEXT_MENU_REQUEST_CHANNEL = "context-menu:request";+/** renderer → main: the item the user picked in that menu. */+export const CONTEXT_MENU_COMMAND_CHANNEL = "context-menu:command";++/**+ * What the renderer needs to draw the menu for one right-click. Main builds it+ * from Electron's context-menu params and keeps the params themselves: the+ * link, the misspelled word and the suggestions a command acts on are read+ * from main's copy, never from the renderer.+ */+export interface ContextMenuRequest {+ /** Matches a command to the right-click it answers. */+ id: number;+ /** Electron's cursor position, for when the renderer saw no DOM event. */+ x: number;+ y: number;+ isEditable: boolean;+ canCut: boolean;+ canCopy: boolean;+ canPaste: boolean;+ canSelectAll: boolean;+ /** Spelling suggestions for the misspelled word under the cursor. */+ suggestions: string[];+ canAddToDictionary: boolean;+ /** The cursor is on an http(s) link. */+ hasLink: boolean;+ /** The cursor is on an image whose pixels have loaded. */+ hasImage: boolean;+}++export type ContextMenuAction =+ | "cut"+ | "copy"+ | "paste"+ | "selectAll"+ | "addToDictionary"+ | "openLink"+ | "copyLink"+ | "copyImage";++export type ContextMenuCommand =+ | { id: number; type: ContextMenuAction }+ | { id: number; type: "replaceMisspelling"; index: number };++/** The plain actions a request offers, in menu order. */+export function contextMenuActions(request: ContextMenuRequest): ContextMenuAction[] {+ const actions: ContextMenuAction[] = [];+ if (request.canAddToDictionary) actions.push("addToDictionary");+ if (request.isEditable && request.canCut) actions.push("cut");+ if (request.canCopy) actions.push("copy");+ if (request.isEditable && request.canPaste) actions.push("paste");+ if (request.isEditable && request.canSelectAll) actions.push("selectAll");+ if (request.hasLink) actions.push("openLink", "copyLink");+ if (request.hasImage) actions.push("copyImage");+ return actions;+}++/** Whether a request has anything to show. */+export function hasContextMenuItems(request: ContextMenuRequest): boolean {+ return request.suggestions.length > 0 || contextMenuActions(request).length > 0;+}++/** Whether `command` is one the request's menu actually offered. */+export function isOfferedCommand(+ request: ContextMenuRequest,+ command: ContextMenuCommand,+): boolean {+ if (command.id !== request.id) return false;+ if (command.type === "replaceMisspelling") {+ return command.index >= 0 && command.index < request.suggestions.length;+ }+ return contextMenuActions(request).includes(command.type);+}++const ACTIONS: ReadonlySet<string> = new Set<ContextMenuAction>([+ "cut",+ "copy",+ "paste",+ "selectAll",+ "addToDictionary",+ "openLink",+ "copyLink",+ "copyImage",+]);++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null;+}++/** Validates a command arriving over IPC; null for anything malformed. */+export function parseContextMenuCommand(value: unknown): ContextMenuCommand | null {+ if (!isRecord(value) || !Number.isInteger(value.id)) return null;+ const id = value.id as number;+ if (value.type === "replaceMisspelling") {+ return Number.isInteger(value.index)+ ? { id, type: "replaceMisspelling", index: value.index as number }+ : null;+ }+ if (typeof value.type === "string" && ACTIONS.has(value.type)) {+ return { id, type: value.type as ContextMenuAction };+ }+ return null;+}++/** Validates a request arriving from main before the renderer draws it. */+export function isContextMenuRequest(value: unknown): value is ContextMenuRequest {+ if (!isRecord(value)) return false;+ return (+ Number.isInteger(value.id) &&+ typeof value.x === "number" &&+ typeof value.y === "number" &&+ typeof value.isEditable === "boolean" &&+ typeof value.canCut === "boolean" &&+ typeof value.canCopy === "boolean" &&+ typeof value.canPaste === "boolean" &&+ typeof value.canSelectAll === "boolean" &&+ Array.isArray(value.suggestions) &&+ value.suggestions.every((s) => typeof s === "string") &&+ typeof value.canAddToDictionary === "boolean" &&+ typeof value.hasLink === "boolean" &&+ typeof value.hasImage === "boolean"+ );+}diff --git a/packages/ui/components/common/quick-emoji-picker.tsx b/packages/ui/components/common/quick-emoji-picker.tsxindex f1f6208ebe..06b244f7cb 100644--- a/packages/ui/components/common/quick-emoji-picker.tsx+++ b/packages/ui/components/common/quick-emoji-picker.tsx@@ -17,10 +17,25 @@ interface QuickEmojiPickerProps {align?: "start" | "end";className?: string;ariaLabel?: string;+ /** Controlled open state, for opening the picker from elsewhere (a menu). */+ open?: boolean;+ onOpenChange?: (open: boolean) => void;}-function QuickEmojiPicker({ onSelect, align = "start", className, ariaLabel = "Add reaction" }: QuickEmojiPickerProps) {- const [open, setOpen] = useState(false);+function QuickEmojiPicker({+ onSelect,+ align = "start",+ className,+ ariaLabel = "Add reaction",+ open: controlledOpen,+ onOpenChange,+}: QuickEmojiPickerProps) {+ const [uncontrolledOpen, setUncontrolledOpen] = useState(false);+ const open = controlledOpen ?? uncontrolledOpen;+ const setOpen = (v: boolean) => {+ setUncontrolledOpen(v);+ onOpenChange?.(v);+ };const [showFull, setShowFull] = useState(false);const handleOpenChange = (v: boolean) => {diff --git a/packages/views/agents/components/agent-row-actions.tsx b/packages/views/agents/components/agent-row-actions.tsxindex 3d9293f9de..7021d3c2e0 100644--- a/packages/views/agents/components/agent-row-actions.tsx+++ b/packages/views/agents/components/agent-row-actions.tsx@@ -1,6 +1,6 @@"use client";-import { useState } from "react";+import { useState, type ReactNode } from "react";import {AlertCircle,Copy,@@ -48,6 +48,10 @@ interface AgentRowActionsProps {// 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;+ /** Items for the top of the menu, for actions only one surface offers. */+ leading?: ReactNode;+ /** For rows that open the menu only on right-click. */+ triggerHidden?: boolean;}/**@@ -61,6 +65,8 @@ export function AgentRowActions({presence,canManage,duplicateHref,+ leading,+ triggerHidden,}: AgentRowActionsProps) {const { t } = useT("agents");const { t: tCommon } = useT("common");@@ -129,7 +135,17 @@ export function AgentRowActions({return (<>- <CollectionRowMenu label={t(($) => $.row.actions_aria)} contentClassName="w-auto">+ <CollectionRowMenu+ label={t(($) => $.row.actions_aria)}+ contentClassName="w-auto"+ triggerHidden={triggerHidden}+ >+ {leading && (+ <>+ {leading}+ <DropdownMenuSeparator />+ </>+ )}{/* Same shape as every other entity row menu: an explicit CTA is aforeground open executed through the adapter (an anchor-baseditem would depend on native activation surviving the menudiff --git a/packages/views/chat/components/chat-thread-list.test.tsx b/packages/views/chat/components/chat-thread-list.test.tsxindex 5135b4e570..f4cbd9c035 100644--- a/packages/views/chat/components/chat-thread-list.test.tsx+++ b/packages/views/chat/components/chat-thread-list.test.tsx@@ -46,6 +46,7 @@ vi.mock("@multica/core/chat/mutations", () => ({useDeleteChatSession: () => ({ mutate: vi.fn(), isPending: false }),useSetChatSessionPinned: () => ({ mutate: vi.fn(), isPending: false }),useSetChatSessionArchived: () => ({ mutate: archiveMutate, isPending: false }),+ useUpdateChatSession: () => ({ mutate: vi.fn(), isPending: false }),}));vi.mock("@tanstack/react-query", async (importOriginal) => {@@ -318,3 +319,24 @@ describe("ChatThreadList row keyboard semantics", () => {expect(onSelectSession).not.toHaveBeenCalled();});});++describe("ChatThreadList right-click menu", () => {+ beforeEach(() => {+ archiveMutate.mockClear();+ });++ it("opens the row's actions at the cursor and acts on that row", async () => {+ const { onArchive, onSelectSession } = renderList("s1");++ fireEvent.contextMenu(screen.getByText("Chat s2"), { clientX: 30, clientY: 90 });+ const menu = await screen.findByRole("menu");+ expect(+ Array.from(menu.querySelectorAll('[role="menuitem"]'), (el) => el.textContent?.trim()),+ ).toEqual([enChat.list.pin, ARCHIVE_LABEL, enChat.header.rename]);++ fireEvent.click(screen.getByRole("menuitem", { name: ARCHIVE_LABEL }));+ expect(onArchive).toHaveBeenCalledTimes(1);+ expect(onArchive.mock.calls[0]![0]).toMatchObject({ id: "s2" });+ expect(onSelectSession).not.toHaveBeenCalled();+ });+});diff --git a/packages/views/chat/components/chat-thread-list.tsx b/packages/views/chat/components/chat-thread-list.tsxindex b9aa9b4b3b..b0888571ce 100644--- a/packages/views/chat/components/chat-thread-list.tsx+++ b/packages/views/chat/components/chat-thread-list.tsx@@ -8,13 +8,17 @@ import {ChevronLeft,ChevronRight,Clock,+ Link2,Loader2,+ Pencil,Pin,PinOff,Square,Trash2,} from "@multica/ui/icons";import { cn } from "@multica/ui/lib/utils";+import { copyText } from "@multica/ui/lib/clipboard";+import { toast } from "sonner";import { useWorkspaceId } from "@multica/core/hooks";import { paths, useWorkspaceSlug } from "@multica/core/paths";import { useWorkspacePresenceMap } from "@multica/core/agents";@@ -24,6 +28,7 @@ import {useDeleteChatSession,useSetChatSessionArchived,useSetChatSessionPinned,+ useUpdateChatSession,} from "@multica/core/chat/mutations";import { useChatStore } from "@multica/core/chat";import type { Agent, ChatSession, PendingChatTasksResponse } from "@multica/core/types";@@ -31,14 +36,17 @@ import { ActorAvatar } from "../../common/actor-avatar";import { DeferredTooltip } from "../../common/deferred-tooltip";import {RowActionsMenu,+ RowActionsPointMenu,handleRowActivationKey,type RowActionItem,} from "../../common/row-actions-menu";+import { CLOSED_ROW_MENU, shouldOpenRowMenu, type RowMenuState } from "../../common/point-menu";import { resolveClickIntent, useOptionalNavigation } from "../../navigation";import { createLogger } from "@multica/core/logger";import { removeChatMessageFromCaches } from "@multica/core/realtime";import { useLocale, useT } from "../../i18n";import { SessionHistoryList } from "./session-history-list";+import { SessionRenameInput } from "./session-rename-input";const apiLogger = createLogger("chat.api");@@ -97,6 +105,7 @@ export function ChatThreadList({onArchive: (session: ChatSession) => void;}) {const { t } = useT("chat");+ const { t: tLayout } = useT("layout");const locale = useLocale();const wsId = useWorkspaceId();// Null-safe slug (not useWorkspacePaths, which throws): the list renders in@@ -136,6 +145,14 @@ export function ChatThreadList({const [confirmingDeleteId, setConfirmingDeleteId] = useState<string | null>(null);const [confirmingStopId, setConfirmingStopId] = useState<string | null>(null);const [stoppingTaskId, setStoppingTaskId] = useState<string | null>(null);+ const [renamingId, setRenamingId] = useState<string | null>(null);+ const updateSession = useUpdateChatSession();+ // One right-click menu for every row; it keeps the session it opened on+ // through its close animation.+ const [contextMenu, setContextMenu] = useState<RowMenuState & { sessionId: string | null }>({+ ...CLOSED_ROW_MENU,+ sessionId: null,+ });const deleteSession = useDeleteChatSession();const setPinned = useSetChatSessionPinned();const setArchived = useSetChatSessionArchived();@@ -205,6 +222,94 @@ export function ChatThreadList({});};+ // One list drives every action surface — the compact menu without hover,+ // the hover strip with it, and the right-click menu — so they cannot drift.+ // The archived view is the only place hard-delete lives; the history view+ // offers the reversible archive instead.+ const rowActionsFor = (session: ChatSession): RowActionItem[] =>+ view === "archived"+ ? [+ {+ key: "unarchive",+ icon: <ArchiveRestore className="size-3.5" />,+ label: t(($) => $.list.unarchive),+ onSelect: () =>+ setArchived.mutate({ sessionId: session.id, archived: false }),+ },+ {+ key: "delete",+ icon: <Trash2 className="size-3.5" />,+ label: t(($) => $.session_history.row_delete_aria),+ danger: true,+ onSelect: () => setConfirmingDeleteId(session.id),+ },+ ]+ : [+ {+ key: "pin",+ icon: session.pinned ? (+ <PinOff className="size-3.5" />+ ) : (+ <Pin className="size-3.5 -rotate-45" />+ ),+ label: session.pinned+ ? t(($) => $.list.unpin)+ : t(($) => $.list.pin),+ onSelect: () =>+ setPinned.mutate({ sessionId: session.id, pinned: !session.pinned }),+ },+ pendingTaskBySessionId.has(session.id)+ ? {+ key: "stop",+ icon: <Square className="size-3 fill-current" />,+ label: t(($) => $.session_history.row_stop_aria),+ danger: true,+ onSelect: () => setConfirmingStopId(session.id),+ }+ : {+ key: "archive",+ icon: <Archive className="size-3.5" />,+ label: t(($) => $.list.archive),+ onSelect: () => onArchive(session),+ },+ ];++ // Menu-only entries: the touch and right-click menus have room for them,+ // the hover strip keeps its two quick actions.+ const menuActionsFor = (session: ChatSession): RowActionItem[] => {+ if (view === "archived") return [];+ const href = sessionHref(session.id);+ return [+ {+ key: "rename",+ icon: <Pencil className="size-3.5" />,+ label: t(($) => $.header.rename),+ onSelect: () => setRenamingId(session.id),+ },+ ...(href && getShareableUrl+ ? [+ {+ key: "copy-link",+ icon: <Link2 className="size-3.5" />,+ label: tLayout(($) => $.rail.copy_link),+ onSelect: () => {+ void copyText(getShareableUrl(href)).then((ok) => {+ if (ok) toast.success(tLayout(($) => $.rail.link_copied));+ });+ },+ },+ ]+ : []),+ ];+ };++ const commitRename = (session: ChatSession, value: string) => {+ setRenamingId(null);+ const title = value.trim();+ if (!title || title === (session.title ?? "")) return;+ updateSession.mutate({ sessionId: session.id, title });+ };+const renderRow = (session: ChatSession) => {const isCurrent = session.id === activeSessionId;const agent = agentById.get(session.agent_id) ?? null;@@ -221,6 +326,7 @@ export function ChatThreadList({const isConfirmingDelete = confirmingDeleteId === session.id;const isConfirmingStop = confirmingStopId === session.id && !!pendingTask;const isConfirmingAction = isConfirmingDelete || isConfirmingStop;+ const isRenaming = renamingId === session.id;const titleText = session.title?.trim() || t(($) => $.window.untitled);const last = session.last_message ?? null;const timeText = last@@ -267,57 +373,8 @@ export function ChatThreadList({previewNode = <span className="block truncate text-muted-foreground">{t(($) => $.list.no_messages)}</span>;}- // One list drives both action surfaces — the compact menu without hover- // and the hover strip with it — so they cannot drift. The archived view- // is the only place hard-delete lives; the history view offers the- // reversible archive instead.- const rowActions: RowActionItem[] =- view === "archived"- ? [- {- key: "unarchive",- icon: <ArchiveRestore className="size-3.5" />,- label: t(($) => $.list.unarchive),- onSelect: () =>- setArchived.mutate({ sessionId: session.id, archived: false }),- },- {- key: "delete",- icon: <Trash2 className="size-3.5" />,- label: t(($) => $.session_history.row_delete_aria),- danger: true,- onSelect: () => setConfirmingDeleteId(session.id),- },- ]- : [- {- key: "pin",- icon: session.pinned ? (- <PinOff className="size-3.5" />- ) : (- <Pin className="size-3.5 -rotate-45" />- ),- label: session.pinned- ? t(($) => $.list.unpin)- : t(($) => $.list.pin),- onSelect: () =>- setPinned.mutate({ sessionId: session.id, pinned: !session.pinned }),- },- isRunning- ? {- key: "stop",- icon: <Square className="size-3 fill-current" />,- label: t(($) => $.session_history.row_stop_aria),- danger: true,- onSelect: () => setConfirmingStopId(session.id),- }- : {- key: "archive",- icon: <Archive className="size-3.5" />,- label: t(($) => $.list.archive),- onSelect: () => onArchive(session),- },- ];+ const rowActions = rowActionsFor(session);+ const menuActions = menuActionsFor(session);return (<div@@ -325,7 +382,7 @@ export function ChatThreadList({aria-current={isCurrent ? "true" : undefined}tabIndex={0}onClick={(e) => {- if (isConfirmingAction || e.defaultPrevented) return;+ if (isConfirmingAction || isRenaming || 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 —@@ -356,9 +413,14 @@ export function ChatThreadList({window.open(getShareableUrl(href), "_blank", "noopener,noreferrer");}}onKeyDown={(e) => {- if (isConfirmingAction) return;+ if (isConfirmingAction || isRenaming) return;handleRowActivationKey(e, () => onSelectSession(session));}}+ onContextMenu={(e) => {+ if (isConfirmingAction || isRenaming || !shouldOpenRowMenu(e)) return;+ e.preventDefault();+ setContextMenu({ open: true, point: { x: e.clientX, y: e.clientY }, sessionId: session.id });+ }}className={cn(// Fixed height so nothing (hover actions, confirm prompts) can change// the row size and make the list jump. Content is vertically centered.@@ -384,9 +446,19 @@ export function ChatThreadList({className="size-3 shrink-0 -rotate-45 fill-current text-muted-foreground"/>)}- <span className={cn("min-w-0 flex-1 truncate text-body", unread > 0 ? "font-semibold text-foreground" : "font-medium")}>- {titleText}- </span>+ {isRenaming ? (+ <div className="min-w-0 flex-1">+ <SessionRenameInput+ initialValue={session.title ?? ""}+ onSubmit={(value) => commitRename(session, value)}+ onCancel={() => setRenamingId(null)}+ />+ </div>+ ) : (+ <span className={cn("min-w-0 flex-1 truncate text-body", unread > 0 ? "font-semibold text-foreground" : "font-medium")}>+ {titleText}+ </span>+ )}<span className="ml-auto shrink-0 text-micro text-muted-foreground">{timeText}</span></div>@@ -452,17 +524,17 @@ export function ChatThreadList({below, which a pointer without hover can never reach. It takes reallayout space (rather than overlaying the preview) and gives way tothe hover strip on a hover-capable pointer. */}- {!isConfirmingAction && (+ {!isConfirmingAction && !isRenaming && (<RowActionsMenulabel={t(($) => $.list.row_actions_aria)}- groups={[rowActions]}+ groups={[rowActions, menuActions]}/>)}{/* Hover actions — absolutely positioned so showing/hiding them neverchanges the row height (which was making the list jump). Keyboardfocus reveals them too, so they are reachable without a mouse. */}- {!isConfirmingAction && (+ {!isConfirmingAction && !isRenaming && (<div className="absolute inset-y-0 right-1 hidden items-center gap-0.5 rounded-md bg-gradient-to-l from-accent from-40% to-transparent pl-10 pr-1 [@media(hover:hover)]:group-hover/row:flex [@media(hover:hover)]:group-focus-within/row:flex">{rowActions.map((action) => (<RowAction@@ -479,6 +551,23 @@ export function ChatThreadList({);};+ const contextMenuSession = contextMenu.sessionId+ ? sessions.find((s) => s.id === contextMenu.sessionId)+ : undefined;+ const rowContextMenu = (+ <RowActionsPointMenu+ menu={contextMenuSession ? contextMenu : CLOSED_ROW_MENU}+ onOpenChange={(open) => {+ if (!open) setContextMenu((current) => ({ ...current, open: false }));+ }}+ groups={+ contextMenuSession+ ? [rowActionsFor(contextMenuSession), menuActionsFor(contextMenuSession)]+ : []+ }+ />+ );+// Archived view: a back header, then the archived rows. Delete lives only// here (via each row's hover actions).if (view === "archived") {@@ -498,6 +587,7 @@ export function ChatThreadList({<div className="min-h-0 flex-1"><SessionHistoryList sessions={archivedSessions} renderRow={renderRow} /></div>+ {rowContextMenu}</div>);}@@ -530,11 +620,14 @@ export function ChatThreadList({}return (- <SessionHistoryList- sessions={historySessions}- renderRow={renderRow}- footer={archivedEntry}- />+ <>+ <SessionHistoryList+ sessions={historySessions}+ renderRow={renderRow}+ footer={archivedEntry}+ />+ {rowContextMenu}+ </>);}diff --git a/packages/views/chat/components/session-rename-input.test.tsx b/packages/views/chat/components/session-rename-input.test.tsxindex e8a64941e9..494546b128 100644--- a/packages/views/chat/components/session-rename-input.test.tsx+++ b/packages/views/chat/components/session-rename-input.test.tsx@@ -50,6 +50,35 @@ describe("SessionRenameInput", () => {expect(onSubmit).toHaveBeenCalledWith("研究");});+ it("keeps editing while its own context menu is used", () => {+ const input = renderInput();+ const menu = document.createElement("div");+ menu.setAttribute("role", "menu");+ const cut = menu.appendChild(document.createElement("div"));+ cut.setAttribute("role", "menuitem");+ document.body.appendChild(menu);++ fireEvent.contextMenu(input);+ fireEvent.pointerDown(cut);+ fireEvent.click(cut);+ expect(onSubmit).not.toHaveBeenCalled();+ expect(input).toBeInTheDocument();++ fireEvent.pointerDown(document.body);+ expect(onSubmit).toHaveBeenCalledTimes(1);+ menu.remove();+ });++ it("submits on a menu it did not open", () => {+ renderInput();+ const menu = document.body.appendChild(document.createElement("div"));+ menu.setAttribute("role", "menu");++ fireEvent.pointerDown(menu);+ expect(onSubmit).toHaveBeenCalledTimes(1);+ menu.remove();+ });+it.each([["standard composition signal", { isComposing: true, keyCode: 27 }],["Safari composition signal", { isComposing: false, keyCode: 229 }],diff --git a/packages/views/chat/components/session-rename-input.tsx b/packages/views/chat/components/session-rename-input.tsxindex 720868700a..4cad3ff8de 100644--- a/packages/views/chat/components/session-rename-input.tsx+++ b/packages/views/chat/components/session-rename-input.tsx@@ -13,7 +13,8 @@ import { useT } from "../../i18n";* We do NOT commit on the input's `blur` event: the history popover can* move focus to sibling rows and nested actions while the user is still* interacting with the panel. Instead a document-level `pointerdown`- * listener commits only when the user actually clicks outside the input.+ * listener commits only when the user actually clicks outside the input+ * (the input's own context menu is not outside).*/export function SessionRenameInput({initialValue,@@ -35,6 +36,9 @@ export function SessionRenameInput({valueRef.current = value;const onSubmitRef = useRef(onSubmit);onSubmitRef.current = onSubmit;+ // A right-click on the input opens its edit menu; picking Cut or Paste+ // there is still editing, not a click outside.+ const ownMenuOpenRef = useRef(false);useEffect(() => {inputRef.current?.focus();@@ -44,6 +48,8 @@ export function SessionRenameInput({const input = inputRef.current;if (!input) return;if (input.contains(e.target as Node)) return;+ if (ownMenuOpenRef.current && e.target instanceof Element && e.target.closest('[role="menu"]')) return;+ ownMenuOpenRef.current = false;onSubmitRef.current(valueRef.current);};// Capture phase — commit before outside-click handling can close the@@ -64,6 +70,9 @@ export function SessionRenameInput({onChange={(e) => setValue(e.target.value)}onClick={(e) => e.stopPropagation()}onPointerDown={(e) => e.stopPropagation()}+ onContextMenu={() => {+ ownMenuOpenRef.current = true;+ }}onKeyDown={(e) => {// Keep editing keys inside the input instead of letting the row// selection keyboard handler consume them.diff --git a/packages/views/common/context-menu-scope.test.tsx b/packages/views/common/context-menu-scope.test.tsxnew file mode 100644index 0000000000..be65ce2550--- /dev/null+++ b/packages/views/common/context-menu-scope.test.tsx@@ -0,0 +1,75 @@+import { describe, expect, it, vi } from "vitest";+import { render, screen } from "@testing-library/react";+import type { ReactNode } from "react";+import { findContextMenuScope, useContextMenuScope, type ContextMenuScope } from "./context-menu-scope";++function Scope({+ read,+ content,+ children,+}: {+ read: () => Partial<ContextMenuScope> | null;+ content?: boolean;+ children: ReactNode;+}) {+ return <div ref={useContextMenuScope(read, { content })}>{children}</div>;+}++const item = (label: string) => ({ key: label, icon: null, label, onSelect: vi.fn() });++describe("findContextMenuScope", () => {+ it("names the submenu from the nearest scope with groups and gathers every scope's selection entries, outermost first", () => {+ render(+ <Scope read={() => ({ selectionActions: () => [item("Add to reply")] })}>+ <Scope+ read={() => ({+ label: "Comment actions",+ icon: null,+ groups: [[item("Reply")], []],+ selectionActions: (text) => [item(`Create from ${text}`)],+ })}+ >+ <Scope read={() => ({ contentActions: [item("Preview")] })} content>+ <span>inside</span>+ </Scope>+ </Scope>+ </Scope>,+ );++ const scope = findContextMenuScope(screen.getByText("inside"));+ expect(scope.submenu?.label).toBe("Comment actions");+ expect(scope.submenu?.groups.map((group) => group.map((action) => action.label))).toEqual([["Reply"]]);+ expect(scope.contentActions.map((action) => action.label)).toEqual(["Preview"]);+ expect(scope.selectionActions("x").map((action) => action.label)).toEqual(["Add to reply", "Create from x"]);+ });++ it("reads the latest actions when a menu opens and skips scopes that opt out", () => {+ let label = "First";+ render(+ <Scope read={() => ({ label, icon: null, groups: [[item("Reply")]] })}>+ <Scope read={() => null}>+ <span>inside</span>+ </Scope>+ </Scope>,+ );+ label = "Second";+ expect(findContextMenuScope(screen.getByText("inside")).submenu?.label).toBe("Second");+ });++ it("marks content scopes so an enclosing row defers to them", () => {+ render(+ <Scope read={() => null} content>+ <span>file</span>+ </Scope>,+ );+ expect(screen.getByText("file").parentElement).toHaveAttribute("data-context-menu-content");+ });++ it("finds nothing outside any scope", () => {+ render(<span>loose</span>);+ const scope = findContextMenuScope(screen.getByText("loose"));+ expect(scope.submenu).toBeNull();+ expect(scope.contentActions).toEqual([]);+ expect(scope.selectionActions("x")).toEqual([]);+ });+});diff --git a/packages/views/common/context-menu-scope.tsx b/packages/views/common/context-menu-scope.tsxnew file mode 100644index 0000000000..4f5875bc9b--- /dev/null+++ b/packages/views/common/context-menu-scope.tsx@@ -0,0 +1,173 @@+"use client";++import { Fragment, useCallback, useMemo, useRef, type ReactNode } from "react";+import type { MenuPrimitives } from "./menu-primitives";+import type { RowActionItem } from "./row-actions-menu";++export type { RowActionItem };++/**+ * The object around a right-clicked piece of content — a comment around a+ * link, a mention, an image or selected text. The content's own menu leads+ * and the object's actions follow in one submenu, so a menu never stacks+ * more than two layers.+ */+export interface ContextMenuScope {+ /** Names the submenu, e.g. "Comment actions". */+ label: string;+ icon: ReactNode;+ groups: RowActionItem[][];+ /** Entries for text selected inside the scope, after the host's Copy. */+ selectionActions?: (text: string) => RowActionItem[];+ /**+ * What the right-clicked content itself offers — an attachment's preview,+ * download and link. They lead the menu and stand in for the host's link+ * entries.+ */+ contentActions?: RowActionItem[];+}++const SCOPE_ATTRIBUTE = "data-context-menu-scope";+/** Marks content with a menu of its own, which an enclosing row defers to. */+const CONTENT_ATTRIBUTE = "data-context-menu-content";+const scopes = new WeakMap<Element, () => Partial<ContextMenuScope> | null>();++/**+ * A ref that registers its element as a scope. The reader runs when a menu+ * opens inside the element, so it always sees the latest render's actions.+ * A scope may provide only some fields: the nearest scope with groups names+ * the submenu, the nearest with content actions leads the menu, and every+ * scope's selection actions apply. Pass `content` for an element whose+ * content actions should win over an enclosing row's own menu.+ */+export function useContextMenuScope(+ read: () => Partial<ContextMenuScope> | null,+ { content = false }: { content?: boolean } = {},+) {+ const readRef = useRef(read);+ readRef.current = read;+ return useCallback((element: HTMLElement | null) => {+ if (!element) return;+ element.setAttribute(SCOPE_ATTRIBUTE, "");+ element.toggleAttribute(CONTENT_ATTRIBUTE, content);+ scopes.set(element, () => readRef.current());+ }, [content]);+}++export interface ResolvedContextMenuScope {+ submenu: Pick<ContextMenuScope, "label" | "icon" | "groups"> | null;+ /** Every scope's selection entries, outermost first. */+ selectionActions: (text: string) => RowActionItem[];+ contentActions: RowActionItem[];+}++/** The scopes around `from`, read when the menu opens. */+export function findContextMenuScope(from: Element | null): ResolvedContextMenuScope {+ let submenu: ResolvedContextMenuScope["submenu"] = null;+ let contentActions: RowActionItem[] | null = null;+ const selectionReaders: ((text: string) => RowActionItem[])[] = [];+ let element = from?.closest(`[${SCOPE_ATTRIBUTE}]`) ?? null;+ while (element) {+ const scope = scopes.get(element)?.();+ if (scope) {+ const groups = scope.groups?.filter((group) => group.length > 0) ?? [];+ if (!submenu && scope.label && groups.length > 0) {+ submenu = { label: scope.label, icon: scope.icon, groups };+ }+ if (!contentActions && scope.contentActions?.length) contentActions = scope.contentActions;+ if (scope.selectionActions) selectionReaders.unshift(scope.selectionActions);+ }+ element = element.parentElement?.closest(`[${SCOPE_ATTRIBUTE}]`) ?? null;+ }+ return {+ submenu,+ contentActions: contentActions ?? [],+ selectionActions: (text) => selectionReaders.flatMap((read) => read(text)),+ };+}++/**+ * The submenu with its actions marked, and a `finalFocus` for the host menu:+ * an action of the surrounding object moves focus itself (into a reply box,+ * an emoji picker), so the closing menu must not pull it back.+ */+export function useScopeSubmenuFocus(submenu: ResolvedContextMenuScope["submenu"]) {+ const picked = useRef(false);+ const wrapped = useMemo(+ () =>+ submenu && {+ ...submenu,+ groups: submenu.groups.map((group) =>+ group.map((action) => ({+ ...action,+ onSelect: () => {+ picked.current = true;+ action.onSelect();+ },+ })),+ ),+ },+ [submenu],+ );+ const finalFocus = useCallback(() => {+ const skip = picked.current;+ picked.current = false;+ return !skip;+ }, []);+ return { submenu: wrapped, finalFocus };+}++/** Action groups as menu items, a separator between groups. */+export function MenuActionGroups({+ groups,+ primitives: P,+}: {+ groups: RowActionItem[][];+ primitives: MenuPrimitives;+}) {+ return groups+ .filter((group) => group.length > 0)+ .map((group, index) => (+ <Fragment key={group[0]!.key}>+ {index > 0 && <P.Separator />}+ {group.map((item) => (+ <P.Item+ key={item.key}+ variant={item.danger ? "destructive" : "default"}+ onClick={item.onSelect}+ >+ {item.icon}+ {item.label}+ </P.Item>+ ))}+ </Fragment>+ ));+}++/** The surrounding object's actions as the menu's last entry. */+export function ContextMenuScopeSubmenu({+ submenu,+ primitives: P,+ separated = true,+}: {+ submenu: ResolvedContextMenuScope["submenu"];+ primitives: MenuPrimitives;+ /** Whether items come before it. */+ separated?: boolean;+}) {+ if (!submenu) return null;+ return (+ <>+ {separated && <P.Separator />}+ <P.Sub>+ <P.SubTrigger>+ {submenu.icon}+ {submenu.label}+ </P.SubTrigger>+ <P.SubContent className="w-auto min-w-44">+ <MenuActionGroups groups={submenu.groups} primitives={P} />+ </P.SubContent>+ </P.Sub>+ </>+ );+}diff --git a/packages/views/common/menu-primitives.ts b/packages/views/common/menu-primitives.tsnew file mode 100644index 0000000000..344dc75a78--- /dev/null+++ b/packages/views/common/menu-primitives.ts@@ -0,0 +1,44 @@+import {+ DropdownMenuItem,+ DropdownMenuSub,+ DropdownMenuSubTrigger,+ DropdownMenuSubContent,+ DropdownMenuSeparator,+} from "@multica/ui/components/ui/dropdown-menu";+import {+ ContextMenuItem,+ ContextMenuSub,+ ContextMenuSubTrigger,+ ContextMenuSubContent,+ ContextMenuSeparator,+} from "@multica/ui/components/ui/context-menu";++// Both Dropdown and Context menu wrappers expose an API-compatible surface+// (variant, inset, onClick, etc.). We bundle the primitives we need into a+// single object so shared menu items render the same JSX for both.+export interface MenuPrimitives {+ Item: typeof DropdownMenuItem;+ Sub: typeof DropdownMenuSub;+ SubTrigger: typeof DropdownMenuSubTrigger;+ SubContent: typeof DropdownMenuSubContent;+ Separator: typeof DropdownMenuSeparator;+}++export const dropdownPrimitives: MenuPrimitives = {+ Item: DropdownMenuItem,+ Sub: DropdownMenuSub,+ SubTrigger: DropdownMenuSubTrigger,+ SubContent: DropdownMenuSubContent,+ Separator: DropdownMenuSeparator,+};++// Context primitives are API-compatible with Dropdown primitives, but their+// TypeScript identities differ. Cast once here and call it a day — this is the+// single bridge between the two primitive sets.+export const contextPrimitives: MenuPrimitives = {+ Item: ContextMenuItem as unknown as typeof DropdownMenuItem,+ Sub: ContextMenuSub as unknown as typeof DropdownMenuSub,+ SubTrigger: ContextMenuSubTrigger as unknown as typeof DropdownMenuSubTrigger,+ SubContent: ContextMenuSubContent as unknown as typeof DropdownMenuSubContent,+ Separator: ContextMenuSeparator as unknown as typeof DropdownMenuSeparator,+};diff --git a/packages/views/common/point-menu.test.tsx b/packages/views/common/point-menu.test.tsxnew file mode 100644index 0000000000..3a0c65f76e--- /dev/null+++ b/packages/views/common/point-menu.test.tsx@@ -0,0 +1,92 @@+import { describe, expect, it, vi } from "vitest";+import { fireEvent, render, screen } from "@testing-library/react";+import { CLOSED_ROW_MENU, nextRowMenuState, shouldOpenRowMenu } from "./point-menu";++describe("nextRowMenuState", () => {+ it("keeps a right-click menu open when Base UI reads the pointer leaving its trigger", () => {+ const menu = { open: true, point: { x: 1, y: 2 } };+ expect(nextRowMenuState(menu, false, "trigger-hover")).toBeNull();+ });++ it("keeps the point while closing, so the menu does not jump as it animates out", () => {+ const menu = { open: true, point: { x: 1, y: 2 } };+ expect(nextRowMenuState(menu, false, "outside-press")).toEqual({ open: false, point: { x: 1, y: 2 } });+ });++ it("anchors a trigger-opened menu to its trigger", () => {+ expect(nextRowMenuState(CLOSED_ROW_MENU, true, "trigger-press")).toEqual({ open: true, point: null });+ });+});++describe("shouldOpenRowMenu", () => {+ function renderRow(deferToContent: boolean) {+ const onOpen = vi.fn();+ render(+ <div+ data-testid="row"+ onContextMenu={(event) => {+ if (shouldOpenRowMenu(event, { deferToContent })) onOpen();+ }}+ >+ <span>plain text</span>+ <a href="https://multica.ai">a link</a>+ <img alt="a picture" src="data:," />+ <pre>some code</pre>+ <table><tbody><tr><td>a cell</td></tr></tbody></table>+ <div data-context-menu-content="">an attachment</div>+ <span+ onContextMenu={(event) => event.preventDefault()}+ >+ handled inside+ </span>+ </div>,+ );+ return onOpen;+ }++ it("opens on plain row content", () => {+ const onOpen = renderRow(true);+ fireEvent.contextMenu(screen.getByText("plain text"));+ expect(onOpen).toHaveBeenCalledTimes(1);+ });++ it("leaves a right-click something inside already handled", () => {+ const onOpen = renderRow(false);+ fireEvent.contextMenu(screen.getByText("handled inside"));+ expect(onOpen).not.toHaveBeenCalled();+ });++ it("leaves links and images their own menu when deferring to content", () => {+ const onOpen = renderRow(true);+ fireEvent.contextMenu(screen.getByText("a link"));+ fireEvent.contextMenu(screen.getByAltText("a picture"));+ expect(onOpen).not.toHaveBeenCalled();+ });++ it("leaves code, tables and attachments their own menu when deferring to content", () => {+ const onOpen = renderRow(true);+ fireEvent.contextMenu(screen.getByText("some code"));+ fireEvent.contextMenu(screen.getByText("a cell"));+ fireEvent.contextMenu(screen.getByText("an attachment"));+ expect(onOpen).not.toHaveBeenCalled();+ });++ it("treats links as part of the row when not deferring to content", () => {+ const onOpen = renderRow(false);+ fireEvent.contextMenu(screen.getByText("a link"));+ expect(onOpen).toHaveBeenCalledTimes(1);+ });++ it("leaves selected text its own menu when deferring to content", () => {+ const onOpen = renderRow(true);+ const text = screen.getByText("plain text");+ const range = document.createRange();+ range.selectNodeContents(text);+ window.getSelection()!.removeAllRanges();+ window.getSelection()!.addRange(range);++ fireEvent.contextMenu(text);+ expect(onOpen).not.toHaveBeenCalled();+ window.getSelection()!.removeAllRanges();+ });+});diff --git a/packages/views/common/point-menu.ts b/packages/views/common/point-menu.tsnew file mode 100644index 0000000000..43ee5c9b51--- /dev/null+++ b/packages/views/common/point-menu.ts@@ -0,0 +1,108 @@+"use client";++import { useCallback, useMemo, useState, type MouseEvent } from "react";++/** A row menu's open state, and the cursor point it opened at when a+ * right-click (not its trigger) opened it. */+export interface RowMenuState {+ open: boolean;+ point: { x: number; y: number } | null;+}++export const CLOSED_ROW_MENU: RowMenuState = { open: false, point: null };++/** A zero-size virtual anchor at the menu's cursor point; undefined when the+ * menu opened from its trigger, so it anchors there instead. */+export function usePointAnchor(point: RowMenuState["point"]) {+ return useMemo(() => {+ if (!point) return undefined;+ return {+ getBoundingClientRect: () => ({+ x: point.x,+ y: point.y,+ top: point.y,+ left: point.x,+ right: point.x,+ bottom: point.y,+ width: 0,+ height: 0,+ toJSON: () => ({}),+ }),+ };+ }, [point]);+}++/**+ * The state a menu moves to when Base UI asks it to open or close, or null to+ * stay put. Base UI treats a menu its trigger did not press open as+ * hover-opened and closes it when the pointer leaves the trigger; a+ * right-click menu never touched the trigger.+ */+export function nextRowMenuState(+ menu: RowMenuState,+ open: boolean,+ reason: string,+): RowMenuState | null {+ if (!open && menu.point && reason === "trigger-hover") return null;+ return open ? { open: true, point: null } : { open: false, point: menu.point };+}++/**+ * Whether a right-click on `target` belongs to the text menu: the target is+ * inside a field or an editor, or selected text runs through it. An inline+ * object with a menu of its own (a mention) yields to it then.+ */+export function yieldsToTextMenu(target: Element): boolean {+ if (target.closest("input, textarea, [contenteditable='true']")) return true;+ const selection = window.getSelection();+ if (!selection || selection.isCollapsed) return false;+ for (let i = 0; i < selection.rangeCount; i++) {+ if (selection.getRangeAt(i).intersectsNode(target)) return true;+ }+ return false;+}++function isContentTarget(target: Element): boolean {+ return (+ !!target.closest("a[href], img, video, pre, table, [data-context-menu-content]") ||+ yieldsToTextMenu(target)+ );+}++/**+ * Whether a right-click on a row should open the row's menu. Not when+ * something inside the row already handled it, nor when the event bubbled up+ * the React tree from a portaled popup outside the row's DOM (the row's own+ * open menu included). With `deferToContent`, content that has a menu of its+ * own — a link, an image, a field, selected text, a code block, a table, an+ * attachment — keeps it.+ */+export function shouldOpenRowMenu(+ event: MouseEvent,+ { deferToContent = false }: { deferToContent?: boolean } = {},+): boolean {+ if (event.defaultPrevented) return false;+ const target = event.target;+ if (!(target instanceof Element) || !event.currentTarget.contains(target)) return false;+ return !(deferToContent && isContentTarget(target));+}++/** Open state for a menu that opens both from a trigger and at the cursor. */+export function useRowMenu() {+ const [menu, setMenu] = useState<RowMenuState>(CLOSED_ROW_MENU);+ const anchor = usePointAnchor(menu.point);++ const openAtPointer = useCallback((event: MouseEvent) => {+ event.preventDefault();+ setMenu({ open: true, point: { x: event.clientX, y: event.clientY } });+ }, []);++ const onOpenChange = useCallback(+ (open: boolean, details: { reason: string }) => {+ setMenu((current) => nextRowMenuState(current, open, details.reason) ?? current);+ },+ [],+ );++ return { menu, setMenu, anchor, openAtPointer, onOpenChange };+}diff --git a/packages/views/common/row-actions-menu.tsx b/packages/views/common/row-actions-menu.tsxindex 09983224d8..cafe17f0e5 100644--- a/packages/views/common/row-actions-menu.tsx+++ b/packages/views/common/row-actions-menu.tsx@@ -9,6 +9,7 @@ import {DropdownMenuSeparator,DropdownMenuTrigger,} from "@multica/ui/components/ui/dropdown-menu";+import { usePointAnchor, type RowMenuState } from "./point-menu";export interface RowActionItem {key: string;@@ -76,22 +77,52 @@ export function RowActionsMenu({}/><DropdownMenuContent align="end" className="w-auto">- {filled.map((group, index) => (- <Fragment key={group[0]!.key}>- {index > 0 && <DropdownMenuSeparator />}- {group.map((item) => (- <DropdownMenuItem- key={item.key}- variant={item.danger ? "destructive" : "default"}- onClick={item.onSelect}- >- {item.icon}- {item.label}- </DropdownMenuItem>- ))}- </Fragment>- ))}+ <RowActionGroups groups={filled} /></DropdownMenuContent></DropdownMenu>);}++/**+ * The same actions as a right-click menu at the cursor. A list keeps one for+ * all its rows and holds on to the last point after closing, so the menu does+ * not jump while it animates out.+ */+export function RowActionsPointMenu({+ menu,+ onOpenChange,+ groups,+}: {+ menu: RowMenuState;+ onOpenChange: (open: boolean) => void;+ groups: RowActionItem[][];+}) {+ const anchor = usePointAnchor(menu.point);+ const filled = groups.filter((group) => group.length > 0);++ return (+ <DropdownMenu open={menu.open && filled.length > 0} onOpenChange={onOpenChange}>+ <DropdownMenuContent align="start" anchor={anchor} className="w-auto">+ <RowActionGroups groups={filled} />+ </DropdownMenuContent>+ </DropdownMenu>+ );+}++function RowActionGroups({ groups }: { groups: RowActionItem[][] }) {+ return groups.map((group, index) => (+ <Fragment key={group[0]!.key}>+ {index > 0 && <DropdownMenuSeparator />}+ {group.map((item) => (+ <DropdownMenuItem+ key={item.key}+ variant={item.danger ? "destructive" : "default"}+ onClick={item.onSelect}+ >+ {item.icon}+ {item.label}+ </DropdownMenuItem>+ ))}+ </Fragment>+ ));+}diff --git a/packages/views/editor/attachment-card.tsx b/packages/views/editor/attachment-card.tsxindex 402bf395bb..554b7957e3 100644--- a/packages/views/editor/attachment-card.tsx+++ b/packages/views/editor/attachment-card.tsx@@ -149,6 +149,8 @@ export interface AttachmentCardProps {onDownload: () => void | Promise<unknown>;/** Optional remove button, used by editable comment/file-card surfaces. */onDelete?: () => void;+ /** Registers the card with the right-click menu. */+ scopeRef?: (element: HTMLElement | null) => void;}export function AttachmentCard({@@ -160,6 +162,7 @@ export function AttachmentCard({onPreview,onDownload,onDelete,+ scopeRef,}: AttachmentCardProps) {const kind = filename ? getPreviewKind(contentType, filename) : null;// Without an attachmentId only the URL-renderable kinds open — otherwise@@ -167,7 +170,7 @@ export function AttachmentCard({const canPreview = !!href && canOpenPreview(kind, !!attachmentId);return (- <div className="my-1">+ <div ref={scopeRef} className="my-1"><AttachmentCardChromefilename={filename}uploading={uploading}@@ -195,6 +198,8 @@ export interface AttachmentFileCardProps {onPreview: () => void;onDownload: () => void | Promise<unknown>;onDelete?: () => void;+ /** Registers the card with the right-click menu. */+ scopeRef?: (element: HTMLElement | null) => void;}/**@@ -213,6 +218,7 @@ export function AttachmentFileCard({onPreview,onDownload,onDelete,+ scopeRef,}: AttachmentFileCardProps) {const { t } = useT("editor");const { downloading, handleDownload } = useAttachmentDownloadState(onDownload);@@ -223,7 +229,7 @@ export function AttachmentFileCard({const open = canPreview ? onPreview : canDownload ? handleDownload : undefined;return (- <div className="group/file-card relative flex min-w-0 items-center gap-3 rounded-lg border border-border bg-card px-3 py-2.5 transition-colors hover:bg-muted/50">+ <div ref={scopeRef} className="group/file-card relative flex min-w-0 items-center gap-3 rounded-lg border border-border bg-card px-3 py-2.5 transition-colors hover:bg-muted/50">{/* The card's click target, under the content so text staysselectable-looking but every click lands here; the action buttonssit above it. */}diff --git a/packages/views/editor/attachment.tsx b/packages/views/editor/attachment.tsxindex d38c7afaa9..a1029c678b 100644--- a/packages/views/editor/attachment.tsx+++ b/packages/views/editor/attachment.tsx@@ -29,6 +29,7 @@import {Download,+ Eye,Loader2,Link as LinkIcon,Maximize2,@@ -49,6 +50,7 @@ import {} from "@multica/core/types/attachment-url";import { useT } from "../i18n";import { DeferredTooltip } from "../common/deferred-tooltip";+import { useContextMenuScope } from "../common/context-menu-scope";import { useAttachmentDownloadResolver } from "./attachment-download-context";import { useAttachmentPreview } from "./attachment-preview-modal";import { usePreviewSequence } from "./preview-sequence-context";@@ -297,6 +299,8 @@ export function Attachment({badge,className,}: AttachmentProps) {+ const { t } = useT("editor");+ const copyLink = useCopyAttachmentLink();const { resolveAttachment, openByUrl } = useAttachmentDownloadResolver();const cdnDomain = useConfigStore((s) => s.cdnDomain);const cdnSigned = useConfigStore((s) => s.cdnSigned);@@ -380,6 +384,38 @@ export function Attachment({if (shareUrl) return openByUrl(shareUrl);};+ const canPreview =+ kind === "image"+ ? !!mediaUrl+ : !!shareUrl && canOpenPreview(kind, !!state.attachmentId);+ const canDownload = !!shareUrl || !!state.attachmentId;+ // Read-only content offers these on right-click too; an editor keeps its+ // edit menu.+ const scopeRef = useContextMenuScope(() => {+ if (editable || state.uploading) return null;+ const contentActions = [+ canPreview && {+ key: "preview",+ icon: <Eye className="size-3.5" />,+ label: t(($) => $.attachment.preview),+ onSelect: openPreview,+ },+ canDownload && {+ key: "download",+ icon: <Download className="size-3.5" />,+ label: t(($) => $.image.download),+ onSelect: () => void handleDownload(),+ },+ shareUrl && {+ key: "copy-link",+ icon: <LinkIcon className="size-3.5" />,+ label: t(($) => $.image.copy_link),+ onSelect: () => void copyLink(shareUrl),+ },+ ].filter((item) => !!item);+ return { contentActions };+ }, { content: !editable });+if (kind === "image") {return (<>@@ -395,6 +431,7 @@ export function Attachment({onView={openPreview}onDownload={handleDownload}onDelete={onDelete}+ scopeRef={scopeRef}className={cn(layout === "card" && "image-standalone", className)}/>{preview.modal}@@ -410,8 +447,9 @@ export function Attachment({contentType={state.contentType}sizeBytes={state.record?.size_bytes}// Same gate as the row's Eye button: text kinds need the record.- canPreview={!!shareUrl && canOpenPreview(kind, !!state.attachmentId)}- canDownload={!!shareUrl || !!state.attachmentId}+ canPreview={canPreview}+ canDownload={canDownload}+ scopeRef={scopeRef}uploading={state.uploading}badge={badge}onPreview={openPreview}@@ -434,12 +472,24 @@ export function Attachment({onPreview={openPreview}onDownload={handleDownload}onDelete={editable ? onDelete : undefined}+ scopeRef={scopeRef}/>{preview.modal}</>);}+function useCopyAttachmentLink() {+ const { t } = useT("editor");+ return async (url: string) => {+ if (await copyText(url)) {+ toast.success(t(($) => $.image.link_copied));+ } else {+ toast.error(t(($) => $.image.copy_link_failed));+ }+ };+}+// ImageAttachmentView — inline image with hover toolbar//// DOM and styling are intentionally a direct port of the original@@ -465,6 +515,8 @@ interface ImageAttachmentViewProps {onView: () => void;onDownload: () => void | Promise<unknown>;onDelete?: () => void;+ /** Registers the image with the right-click menu. */+ scopeRef?: (element: HTMLElement | null) => void;className?: string;}@@ -480,18 +532,13 @@ function ImageAttachmentView({onView,onDownload,onDelete,+ scopeRef,className,}: ImageAttachmentViewProps) {const { t } = useT("editor");const { downloading, handleDownload } = useAttachmentDownloadState(onDownload);-- const handleCopyLink = async () => {- if (await copyText(linkUrl)) {- toast.success(t(($) => $.image.link_copied));- } else {- toast.error(t(($) => $.image.copy_link_failed));- }- };+ const copyLink = useCopyAttachmentLink();+ const handleCopyLink = () => copyLink(linkUrl);// Click on figure opens the preview only in non-editor / non-uploading// surfaces — inside the editor we let ProseMirror own the click for@@ -523,7 +570,7 @@ function ImageAttachmentView({// the NodeViewWrapper still emits its own outer .image-node div around// this — the duplicate `image-node` class is harmless.return (- <span className="image-node">+ <span ref={scopeRef} className="image-node"><spanclassName={cn("image-figure",diff --git a/packages/views/editor/content-editor-current-issue.test.tsx b/packages/views/editor/content-editor-current-issue.test.tsxindex b290bd5091..bac5f68032 100644--- a/packages/views/editor/content-editor-current-issue.test.tsx+++ b/packages/views/editor/content-editor-current-issue.test.tsx@@ -8,6 +8,7 @@ import type { NavigationAdapter } from "../navigation/types";import { CurrentIssueRenderContextProvider } from "../issues/current-issue-render-context";vi.mock("../issues/components/issue-chip", () => ({+ useChipIssue: () => undefined,IssueChip: ({issueId,children,diff --git a/packages/views/editor/extensions/mention-context-menu.test.tsx b/packages/views/editor/extensions/mention-context-menu.test.tsxnew file mode 100644index 0000000000..697b7a6016--- /dev/null+++ b/packages/views/editor/extensions/mention-context-menu.test.tsx@@ -0,0 +1,58 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { fireEvent, render, screen } from "@testing-library/react";+import type { ReactNode } from "react";+import { NavigationProvider } from "../../navigation";+import { IssueMentionCard } from "../../issues/components/issue-mention-card";+import { ProjectMentionCard } from "../../projects/components/project-mention-card";++vi.mock("@multica/core/paths", () => ({+ useWorkspacePaths: () => ({ issueDetail: (id: string) => `/acme/issues/${id}`, projectDetail: (id: string) => `/acme/projects/${id}` }),+}));+vi.mock("../../issues/components/issue-chip", () => ({+ useChipIssue: () => ({ id: "issue-1", title: "Mentioned issue" }),+ IssueChip: () => <span data-testid="mention">Mentioned issue</span>,+}));+vi.mock("../../projects/components/project-chip", () => ({+ useChipProject: () => ({ id: "project-1", title: "Mentioned project" }),+ ProjectChip: () => <span data-testid="mention">Mentioned project</span>,+}));+vi.mock("../../issues/components/issue-hover-card", () => ({+ IssueHoverCard: ({ children }: { children: ReactNode }) => children,+}));+vi.mock("../../issues/actions/issue-actions-context-menu", () => ({+ IssueContextMenuProvider: ({ children }: { children: ReactNode }) => children,+ useOpenIssueContextMenu: () => (_issue: unknown, event: React.MouseEvent) => event.preventDefault(),+}));+vi.mock("../../projects/components/project-row-actions", () => ({ ProjectMenu: () => null }));++afterEach(() => window.getSelection()?.removeAllRanges());++const variants = [+ ["issue", <IssueMentionCard key="issue" issueId="issue-1" />],+ ["project", <ProjectMentionCard key="project" projectId="project-1" />],+] as const;++describe.each(variants)("%s mention context menu", (_name, card) => {+ const show = (editable = false) => render(+ <NavigationProvider value={{ push: vi.fn(), replace: vi.fn(), back: vi.fn(), pathname: "/", searchParams: new URLSearchParams(), hash: "", getShareableUrl: (p) => p }}>+ <div data-testid="paragraph" contentEditable={editable} suppressContentEditableWarning>+ Selected text before {card} and after+ </div>+ </NavigationProvider>,+ );+ it("opens the object menu on a plain read-only mention", () => {+ show();+ expect(fireEvent.contextMenu(screen.getByTestId("mention"))).toBe(false);+ });+ it("lets a selection spanning the mention keep its text context menu", () => {+ show();+ const range = document.createRange();+ range.selectNodeContents(screen.getByTestId("paragraph"));+ window.getSelection()!.addRange(range);+ expect(fireEvent.contextMenu(screen.getByTestId("mention"))).toBe(true);+ });+ it("leaves an editor mention to the edit context menu", () => {+ show(true);+ expect(fireEvent.contextMenu(screen.getByTestId("mention"))).toBe(true);+ });+});diff --git a/packages/views/editor/extensions/mention-view.test.tsx b/packages/views/editor/extensions/mention-view.test.tsxindex 62329630a6..16bf722aac 100644--- a/packages/views/editor/extensions/mention-view.test.tsx+++ b/packages/views/editor/extensions/mention-view.test.tsx@@ -28,12 +28,14 @@ vi.mock("@multica/core/paths", () => ({}));vi.mock("../../issues/components/issue-chip", () => ({+ useChipIssue: () => undefined,IssueChip: ({ fallbackLabel }: { fallbackLabel?: string }) => (<span data-testid="issue-chip">{fallbackLabel}</span>),}));vi.mock("../../projects/components/project-chip", () => ({+ useChipProject: () => undefined,ProjectChip: ({ fallbackLabel }: { fallbackLabel?: string }) => (<span data-testid="project-chip">{fallbackLabel}</span>),diff --git a/packages/views/issues/actions/__tests__/issue-actions-menu.test.tsx b/packages/views/issues/actions/__tests__/issue-actions-menu.test.tsxindex a5dd3c4732..77b406257d 100644--- a/packages/views/issues/actions/__tests__/issue-actions-menu.test.tsx+++ b/packages/views/issues/actions/__tests__/issue-actions-menu.test.tsx@@ -276,7 +276,8 @@ describe("IssueActionsDropdown", () => {const labels = screen.getAllByRole("menuitem").map((item) => item.textContent?.trim());- expect(labels.slice(0, 3)).toEqual(["Rename issue", "Create sub-issue", "Status"]);+ // Status trails its current value.+ expect(labels.slice(0, 3)).toEqual(["Rename issue", "Create sub-issue", "StatusTodo"]);});it("opens Assignee as a submenu holding the shared assignee picker", async () => {diff --git a/packages/views/issues/actions/issue-actions-context-menu.tsx b/packages/views/issues/actions/issue-actions-context-menu.tsxindex 3c2f8d74fe..68866ba7ed 100644--- a/packages/views/issues/actions/issue-actions-context-menu.tsx+++ b/packages/views/issues/actions/issue-actions-context-menu.tsx@@ -5,6 +5,7 @@ import {createContext,useCallback,useContext,+ useEffect,useMemo,useRef,useState,@@ -24,6 +25,12 @@ import {contextPrimitives,} from "./issue-actions-menu-items";import { TerminateTaskConfirmDialog } from "../components/terminate-task-confirm-dialog";+import {+ ContextMenuScopeSubmenu,+ findContextMenuScope,+ useScopeSubmenuFocus,+ type ResolvedContextMenuScope,+} from "../../common/context-menu-scope";import { useT } from "../../i18n";/**@@ -43,6 +50,8 @@ import { useT } from "../../i18n";interface ActiveMenu {issue: Issue;position: { x: number; y: number };+ /** The object around the issue — a comment around a mention. */+ submenu: ResolvedContextMenuScope["submenu"];}type OpenIssueContextMenu = (issue: Issue, event: React.MouseEvent) => void;@@ -51,6 +60,27 @@ const IssueContextMenuContext = createContext<OpenIssueContextMenu | null>(null,);+/**+ * The surface's batch menu: a right-click on a row that is part of a+ * multi-row selection acts on the whole selection, not on that row alone.+ */+export interface IssueBatchMenu {+ covers: (issueId: string) => boolean;+ openAt: (point: { x: number; y: number }) => void;+}++const IssueBatchMenuRegistry = createContext<((menu: IssueBatchMenu | null) => void) | null>(null);++/** Hands the provider the batch menu; `menu` should be stable. */+export function useRegisterIssueBatchMenu(menu: IssueBatchMenu) {+ const register = useContext(IssueBatchMenuRegistry);+ useEffect(() => {+ if (!register) return;+ register(menu);+ return () => register(null);+ }, [register, menu]);+}+type IssueContextMenuVariant = "full" | "sidebar";export function IssueContextMenuProvider({@@ -69,14 +99,28 @@ export function IssueContextMenuProvider({// managing it imperatively here keeps the affordance without re-rendering// every row on open/close.const triggerElRef = useRef<HTMLElement | null>(null);+ const batchMenuRef = useRef<IssueBatchMenu | null>(null);+ const registerBatchMenu = useCallback((menu: IssueBatchMenu | null) => {+ batchMenuRef.current = menu;+ }, []);const openMenu = useCallback<OpenIssueContextMenu>((issue, event) => {event.preventDefault();+ const batch = batchMenuRef.current;+ if (batch?.covers(issue.id)) {+ setOpen(false);+ batch.openAt({ x: event.clientX, y: event.clientY });+ return;+ }triggerElRef.current?.removeAttribute("data-popup-open");const el = event.currentTarget as HTMLElement;el.setAttribute("data-popup-open", "");triggerElRef.current = el;- setActive({ issue, position: { x: event.clientX, y: event.clientY } });+ setActive({+ issue,+ position: { x: event.clientX, y: event.clientY },+ submenu: findContextMenuScope(el.parentElement).submenu,+ });setOpen(true);}, []);@@ -90,13 +134,14 @@ export function IssueContextMenuProvider({return (<IssueContextMenuContext.Provider value={openMenu}>- {children}+ <IssueBatchMenuRegistry.Provider value={registerBatchMenu}>{children}</IssueBatchMenuRegistry.Provider>{/* Mounted on first use, kept mounted after (one closed menu root persurface — the popup itself unmounts while closed). */}{active && (<IssueContextMenuSingletonissue={active.issue}position={active.position}+ submenu={active.submenu}open={open}onOpenChange={handleOpenChange}variant={variant}@@ -109,6 +154,7 @@ export function IssueContextMenuProvider({function IssueContextMenuSingleton({issue,position,+ submenu,open,onOpenChange,variant,@@ -119,6 +165,7 @@ function IssueContextMenuSingleton({}) {const actions = useIssueActions(issue);const [stopTask, setStopTask] = useState<AgentTask | null>(null);+ const scope = useScopeSubmenuFocus(submenu);// Point-sized virtual anchor at the right-click position — replaces the// cursor anchor Base UI's own trigger would have registered.@@ -140,7 +187,11 @@ function IssueContextMenuSingleton({<ContextMenu open={open} onOpenChange={(v) => onOpenChange(v)}>{/* A fixed width keeps the sidebar menu from resizing with theheader title, which is clamped to two lines instead. */}- <ContextMenuContent anchor={anchor} className={variant === "sidebar" ? "w-62" : undefined}>+ <ContextMenuContent+ anchor={anchor}+ className={variant === "sidebar" ? "w-62" : "w-auto min-w-56"}+ finalFocus={scope.finalFocus}+ ><IssueActionsMenuItemsissue={issue}actions={actions}@@ -149,6 +200,7 @@ function IssueContextMenuSingleton({variant={variant}onStopRun={setStopTask}/>+ <ContextMenuScopeSubmenu submenu={scope.submenu} primitives={contextPrimitives} /></ContextMenuContent></ContextMenu>{stopTask && (@@ -191,6 +243,19 @@ function StopRunConfirmDialog({);}+/** Opens the surrounding provider's issue menu at the event's cursor, for an+ * item that must stay selectable text (IssueActionsContextMenu makes its child+ * `select-none`). */+export function useOpenIssueContextMenu(): OpenIssueContextMenu {+ const openMenu = useContext(IssueContextMenuContext);+ if (!openMenu) {+ throw new Error(+ "useOpenIssueContextMenu requires an IssueContextMenuProvider ancestor",+ );+ }+ return openMenu;+}+interface IssueActionsContextMenuProps {issue: Issue;/** A single React element the menu trigger behavior is grafted onto. */diff --git a/packages/views/issues/actions/issue-actions-menu-items.tsx b/packages/views/issues/actions/issue-actions-menu-items.tsxindex ded90dd516..712e2479c9 100644--- a/packages/views/issues/actions/issue-actions-menu-items.tsx+++ b/packages/views/issues/actions/issue-actions-menu-items.tsx@@ -4,6 +4,7 @@ import { useCallback, useMemo, useRef, type ReactNode } from "react";import { useQuery } from "@tanstack/react-query";import { toast } from "sonner";import {+ AppWindow,ArrowDown,ArrowUp,Calendar,@@ -30,7 +31,7 @@ import {import { useIssueDeletion } from "@multica/core/issues/use-issue-deletion";import type { AgentTask, Issue } from "@multica/core/types";import { resolveWorkdirCopyTarget } from "@multica/core/issues";-import { todayDateOnly, addDaysDateOnly } from "@multica/core/issues/date";+import { todayDateOnly, addDaysDateOnly, formatDateOnly } from "@multica/core/issues/date";import { agentTaskSnapshotOptions } from "@multica/core/agents";import {PRIORITY_DISPLAY_ORDER,@@ -49,55 +50,18 @@ import { StatusIcon } from "../components/status-icon";import { PriorityIcon } from "../components/priority-icon";import { selectIssueTasks } from "../surface/activity";import { AssigneePickerPanel } from "../components/pickers";-import {- DropdownMenuItem,- DropdownMenuSub,- DropdownMenuSubTrigger,- DropdownMenuSubContent,- DropdownMenuSeparator,-} from "@multica/ui/components/ui/dropdown-menu";-import {- ContextMenuItem,- ContextMenuSub,- ContextMenuSubTrigger,- ContextMenuSubContent,- ContextMenuSeparator,-} from "@multica/ui/components/ui/context-menu";import { copyText } from "@multica/ui/lib/clipboard";+import {+ contextPrimitives,+ dropdownPrimitives,+ type MenuPrimitives,+} from "../../common/menu-primitives";import type { UseIssueActionsResult } from "./use-issue-actions";import { InboxRestoreMenuItem } from "./inbox-restore";import { PluginHookMenuItems, PluginModalMenuItems } from "../../plugins";-import { useT } from "../../i18n";--// Both Dropdown and Context menu wrappers expose an API-compatible surface-// (variant, inset, onClick, etc.). We bundle the primitives we need into a-// single object so `IssueActionsMenuItems` can render the same JSX for both.-export interface MenuPrimitives {- Item: typeof DropdownMenuItem;- Sub: typeof DropdownMenuSub;- SubTrigger: typeof DropdownMenuSubTrigger;- SubContent: typeof DropdownMenuSubContent;- Separator: typeof DropdownMenuSeparator;-}+import { useLocale, useT } from "../../i18n";-export const dropdownPrimitives: MenuPrimitives = {- Item: DropdownMenuItem,- Sub: DropdownMenuSub,- SubTrigger: DropdownMenuSubTrigger,- SubContent: DropdownMenuSubContent,- Separator: DropdownMenuSeparator,-};--// Context primitives are API-compatible with Dropdown primitives, but their-// TypeScript identities differ. Cast once here and call it a day — this is the-// single bridge between the two primitive sets.-export const contextPrimitives: MenuPrimitives = {- Item: ContextMenuItem as unknown as typeof DropdownMenuItem,- Sub: ContextMenuSub as unknown as typeof DropdownMenuSub,- SubTrigger: ContextMenuSubTrigger as unknown as typeof DropdownMenuSubTrigger,- SubContent: ContextMenuSubContent as unknown as typeof DropdownMenuSubContent,- Separator: ContextMenuSeparator as unknown as typeof DropdownMenuSeparator,-};+export { contextPrimitives, dropdownPrimitives, type MenuPrimitives };interface IssueActionsMenuItemsProps {issue: Issue;@@ -114,8 +78,7 @@ interface IssueActionsMenuItemsProps {/** The reader's archived inbox notification for this issue; adds "Restore to inbox". */archivedInboxItemId?: string;/** `sidebar` is the trimmed menu for sidebar rows, where only the title is- * visible: it names the issue in a header, shows current values beside- * Status / Priority / Assignee, and keeps only triage and navigation+ * visible: it names the issue in a header and keeps only triage and navigation* entries — in the full menu's order, so the shared entries sit where* users already expect them. */variant?: "full" | "sidebar";@@ -137,6 +100,8 @@ export function IssueActionsMenuItems({onShowInSidebar,}: IssueActionsMenuItemsProps) {const { t } = useT("issues");+ const locale = useLocale();+ const formatDate = (date: string) => formatDateOnly(date, { month: "short", day: "numeric" }, locale);const wsId = useWorkspaceId();const { canDelete } = useIssueDeletion(wsId);const sidebar = variant === "sidebar";@@ -160,6 +125,7 @@ export function IssueActionsMenuItems({isPinned,updateField,openInNewTab,+ openInNewWindow,openInDesktop,togglePin,copyLink,@@ -271,7 +237,7 @@ export function IssueActionsMenuItems({/><ItemLabellabel={t(($) => $.actions.status)}- value={sidebar ? statusLabel(issue.status) : undefined}+ value={statusLabel(issue.status)}/></P.SubTrigger><P.SubContent>@@ -305,7 +271,7 @@ export function IssueActionsMenuItems({<PriorityIcon priority={issue.priority} /><ItemLabellabel={t(($) => $.actions.priority)}- value={sidebar ? t(($) => $.priority[issue.priority]) : undefined}+ value={t(($) => $.priority[issue.priority])}/></P.SubTrigger><P.SubContent>@@ -334,7 +300,7 @@ export function IssueActionsMenuItems({<UserMinus className="h-3.5 w-3.5" /><ItemLabellabel={t(($) => $.actions.assignee)}- value={sidebar ? <AssigneeName issue={issue} /> : undefined}+ value={<AssigneeName issue={issue} />}/></P.SubTrigger><P.SubContent className="w-64 p-0">@@ -355,7 +321,10 @@ export function IssueActionsMenuItems({<P.Sub><P.SubTrigger><CalendarClock className="h-3.5 w-3.5" />- {t(($) => $.actions.start_date)}+ <ItemLabel+ label={t(($) => $.actions.start_date)}+ value={issue.start_date ? formatDate(issue.start_date) : undefined}+ /></P.SubTrigger><P.SubContent><P.Item onClick={() => updateField({ start_date: todayDateOnly() })}>@@ -382,7 +351,10 @@ export function IssueActionsMenuItems({<P.Sub><P.SubTrigger><Calendar className="h-3.5 w-3.5" />- {t(($) => $.actions.due_date)}+ <ItemLabel+ label={t(($) => $.actions.due_date)}+ value={issue.due_date ? formatDate(issue.due_date) : undefined}+ /></P.SubTrigger><P.SubContent><P.Item onClick={() => updateField({ due_date: todayDateOnly() })}>@@ -416,6 +388,12 @@ export function IssueActionsMenuItems({<ExternalLink className="h-3.5 w-3.5" />{t(($) => $.actions.open_in_new_tab)}</P.Item>+ {openInNewWindow && (+ <P.Item onClick={openInNewWindow}>+ <AppWindow className="h-3.5 w-3.5" />+ {t(($) => $.actions.open_in_new_window)}+ </P.Item>+ )}{openInDesktop && (<P.Item onClick={openInDesktop}><Monitor className="h-3.5 w-3.5" />@@ -551,7 +529,7 @@ function ItemLabel({ label, value }: { label: string; value?: ReactNode }) {/** Hosts a search box and list inside a submenu. The menu's typeahead and* arrow-key navigation would otherwise take the keys typed into the search* box; Escape and Tab still reach the menu so it can close. */-function SubmenuPanel({ children }: { children: ReactNode }) {+export function SubmenuPanel({ children }: { children: ReactNode }) {const ref = useRef<HTMLDivElement>(null);return (<divdiff --git a/packages/views/issues/actions/use-issue-actions.ts b/packages/views/issues/actions/use-issue-actions.tsindex 0d89cc2e79..d18050b4a2 100644--- a/packages/views/issues/actions/use-issue-actions.ts+++ b/packages/views/issues/actions/use-issue-actions.ts@@ -28,6 +28,7 @@ export interface UseIssueActionsResult {) => void;openInNewTab: () => void;openInDesktop?: () => void;+ openInNewWindow?: () => void;togglePin: () => void;copyLink: () => Promise<void>;copyCommentLink: (commentId: string) => Promise<void>;@@ -152,6 +153,14 @@ export function useIssueActions(issue: Issue | null): UseIssueActionsResult {);}, [issueId, issueIdentifier, navigation, paths]);+ const openInNewWindow = useCallback(() => {+ if (!issueId) return;+ navigation.openIssueInNewWindow?.(+ paths.issueDetail(issueIdentifier || issueId),+ issueIdentifier ? `${issueIdentifier} ${issueTitle}` : issueTitle,+ );+ }, [issueId, issueIdentifier, issueTitle, navigation, paths]);+const openInDesktop = useCallback(() => {if (!issueId) return;const path = paths.issueDetail(issueIdentifier || issueId);@@ -310,6 +319,7 @@ export function useIssueActions(issue: Issue | null): UseIssueActionsResult {updateField,openInNewTab,openInDesktop: navigation.openInDesktop ? openInDesktop : undefined,+ openInNewWindow: navigation.openIssueInNewWindow ? openInNewWindow : undefined,togglePin,copyLink,copyCommentLink,diff --git a/packages/views/issues/components/batch-action-toolbar.menu.test.tsx b/packages/views/issues/components/batch-action-toolbar.menu.test.tsxnew file mode 100644index 0000000000..71671fca11--- /dev/null+++ b/packages/views/issues/components/batch-action-toolbar.menu.test.tsx@@ -0,0 +1,80 @@+import { describe, expect, it, vi } from "vitest";+import { fireEvent, screen } from "@testing-library/react";+import type { Issue } from "@multica/core/types";+import { renderWithI18n } from "../../test/i18n";+import { BatchActionToolbar } from "./batch-action-toolbar";+import { IssueActionsContextMenu, IssueContextMenuProvider } from "../actions/issue-actions-context-menu";++// A right-click on a row that is part of a multi-row selection opens the+// batch menu for the whole selection instead of that row's own menu.++const selection = vi.hoisted(() => ({ selectedIds: new Set<string>(["a", "b"]), clear: vi.fn() }));++vi.mock("@multica/core/issues/stores/selection-store", () => ({+ useIssueSelectionStore: (selector: (s: typeof selection) => unknown) => selector(selection),+}));+vi.mock("@multica/core/issues/use-issue-deletion", () => ({+ useIssueDeletion: () => ({ canDelete: () => true }),+}));+vi.mock("@multica/core/issues/mutations", () => ({+ useBatchUpdateIssues: () => ({ mutateAsync: vi.fn(), isPending: false }),+ useBatchDeleteIssues: () => ({ mutateAsync: vi.fn(), isPending: false }),+ useCancelIssueRun: () => ({ mutateAsync: vi.fn() }),+}));+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));+vi.mock("@multica/core/issue-workflows", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@multica/core/issue-workflows")>()),+ useIssueWorkflows: () => ({ workflows: [] }),+}));+vi.mock("@tanstack/react-query", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@tanstack/react-query")>()),+ useQuery: () => ({ data: [] }),+}));+vi.mock("@multica/core/paths", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@multica/core/paths")>()),+ useWorkspacePaths: () => ({ issueDetail: (id: string) => `/acme/issues/${id}` }),+}));+vi.mock("../../navigation", () => ({+ useNavigation: () => ({ getShareableUrl: (path: string) => `https://app.example${path}` }),+}));+vi.mock("../utils/status-options", () => ({ useIssueStatusOptions: () => ({ options: [] }) }));+vi.mock("./pickers", () => ({+ StatusPicker: () => null,+ PriorityPicker: () => null,+ AssigneePicker: () => null,+ AssigneePickerPanel: () => null,+}));+vi.mock("../../search/register-context", () => ({ useRegisterCommandBarContext: () => {} }));+vi.mock("../actions/use-issue-actions", () => ({+ useIssueActions: () => {+ throw new Error("the single-issue menu must not open for a selected row");+ },+}));++function issue(id: string): Issue {+ return { id, identifier: `MUL-${id}`, title: id, status: "todo", priority: "none", project_id: null } as Issue;+}++describe("BatchActionToolbar — batch context menu", () => {+ it("opens for a right-click on a selected row and acts on the whole selection", async () => {+ const issues = [issue("a"), issue("b"), issue("c")];+ renderWithI18n(+ <IssueContextMenuProvider>+ {issues.map((row) => (+ <IssueActionsContextMenu key={row.id} issue={row}>+ <div>row {row.id}</div>+ </IssueActionsContextMenu>+ ))}+ <BatchActionToolbar issues={issues} />+ </IssueContextMenuProvider>,+ );++ fireEvent.contextMenu(screen.getByText("row a"), { clientX: 10, clientY: 20 });+ const menu = await screen.findByRole("menu");+ expect(menu).toHaveTextContent("2 selected");+ expect(screen.getByRole("menuitem", { name: "Delete 2 issues" })).toBeInTheDocument();++ fireEvent.click(screen.getByRole("menuitem", { name: "Clear selection" }));+ expect(selection.clear).toHaveBeenCalledTimes(1);+ });+});diff --git a/packages/views/issues/components/batch-action-toolbar.tsx b/packages/views/issues/components/batch-action-toolbar.tsxindex f855771929..52e9f4d4f8 100644--- a/packages/views/issues/components/batch-action-toolbar.tsx+++ b/packages/views/issues/components/batch-action-toolbar.tsx@@ -1,7 +1,7 @@"use client";-import { useEffect, useMemo, useState } from "react";-import { Trash2 } from "@multica/ui/icons";+import { useEffect, useMemo, useRef, useState } from "react";+import { Check, CircleDot, Link2, Trash2, UserMinus, X } from "@multica/ui/icons";import { toast } from "sonner";import { Button } from "@multica/ui/components/ui/button";import {@@ -14,6 +14,18 @@ import {AlertDialogHeader,AlertDialogTitle,} from "@multica/ui/components/ui/alert-dialog";+import {+ ContextMenu,+ ContextMenuContent,+ ContextMenuItem,+ ContextMenuSeparator,+ ContextMenuSub,+ ContextMenuSubContent,+ ContextMenuSubTrigger,+} from "@multica/ui/components/ui/context-menu";+import { copyText } from "@multica/ui/lib/clipboard";+import { PRIORITY_CONFIG, PRIORITY_DISPLAY_ORDER } from "@multica/core/issues/config";+import { useWorkspacePaths } from "@multica/core/paths";import { useQuery } from "@tanstack/react-query";import { useIssueDeletion } from "@multica/core/issues/use-issue-deletion";import type { Issue, UpdateIssueRequest } from "@multica/core/types";@@ -23,7 +35,13 @@ import { sharedWorkflowStatusKeys, useIssueWorkflows } from "@multica/core/issueimport { projectListOptions } from "@multica/core/projects/queries";import { useBatchUpdateIssues, useBatchDeleteIssues } from "@multica/core/issues/mutations";import { useModalStore } from "@multica/core/modals";-import { StatusPicker, PriorityPicker, AssigneePicker } from "./pickers";+import { StatusPicker, PriorityPicker, AssigneePicker, AssigneePickerPanel } from "./pickers";+import { StatusIcon } from "./status-icon";+import { PriorityIcon } from "./priority-icon";+import { useIssueStatusOptions } from "../utils/status-options";+import { SubmenuPanel } from "../actions/issue-actions-menu-items";+import { useRegisterIssueBatchMenu } from "../actions/issue-actions-context-menu";+import { useNavigation } from "../../navigation";import { useT } from "../../i18n";import { CollectionBatchBar } from "../../layout/collection-list";import { useIssueSurfaceActionsOptional } from "../surface/actions-context";@@ -110,6 +128,23 @@ export function BatchActionToolbar({const [priorityOpen, setPriorityOpen] = useState(false);const [assigneeOpen, setAssigneeOpen] = useState(false);const [deleteOpen, setDeleteOpen] = useState(false);+ const [menuPoint, setMenuPoint] = useState<{ x: number; y: number } | null>(null);+ const [menuOpen, setMenuOpen] = useState(false);+ const selectedRef = useRef(selectedIssues);+ selectedRef.current = selectedIssues;+ useRegisterIssueBatchMenu(+ useMemo(+ () => ({+ covers: (issueId: string) =>+ selectedRef.current.length > 1 && selectedRef.current.some((issue) => issue.id === issueId),+ openAt: (point: { x: number; y: number }) => {+ setMenuPoint(point);+ setMenuOpen(true);+ },+ }),+ [],+ ),+ );const surfaceActions = useIssueSurfaceActionsOptional();const batchUpdate = useBatchUpdateIssues();const batchDelete = useBatchDeleteIssues();@@ -124,6 +159,7 @@ export function BatchActionToolbar({setPriorityOpen(false);setAssigneeOpen(false);setDeleteOpen(false);+ setMenuOpen(false);}, [count]);const handleBatchUpdate = async (updates: Partial<UpdateIssueRequest>) => {@@ -265,6 +301,25 @@ export function BatchActionToolbar({</Button></CollectionBatchBar>+ {menuPoint && count > 1 && (+ <BatchContextMenu+ point={menuPoint}+ open={menuOpen}+ onOpenChange={setMenuOpen}+ issues={selectedIssues}+ projectId={sharedProjectId}+ allowedStatuses={allowedStatuses}+ common={common}+ disabled={loading}+ canDelete={canDeleteSelection}+ onStatus={(status) => handleBatchStatus({ status })}+ onPriority={(priority) => void handleBatchUpdate({ priority })}+ onAssignee={handleBatchAssignee}+ onClear={clear}+ onDelete={() => setDeleteOpen(true)}+ />+ )}+{count > 0 && <AlertDialog open={deleteOpen} onOpenChange={setDeleteOpen}><AlertDialogContent><AlertDialogHeader>@@ -290,3 +345,147 @@ export function BatchActionToolbar({</>);}++/** The batch bar's actions at the cursor, for a right-click on a selected row. */+function BatchContextMenu({+ point,+ open,+ onOpenChange,+ issues,+ projectId,+ allowedStatuses,+ common,+ disabled,+ canDelete,+ onStatus,+ onPriority,+ onAssignee,+ onClear,+ onDelete,+}: {+ point: { x: number; y: number };+ open: boolean;+ onOpenChange: (open: boolean) => void;+ issues: Issue[];+ projectId: string | null;+ allowedStatuses: ReadonlySet<string> | null;+ common: ReturnType<typeof commonIssueFields>;+ disabled: boolean;+ canDelete: boolean;+ onStatus: (status: string) => void;+ onPriority: (priority: Issue["priority"]) => void;+ onAssignee: (updates: Partial<UpdateIssueRequest>) => void;+ onClear: () => void;+ onDelete: () => void;+}) {+ const { t } = useT("issues");+ const { t: tLayout } = useT("layout");+ const wsId = useWorkspaceId();+ const paths = useWorkspacePaths();+ const { getShareableUrl } = useNavigation();+ const { options } = useIssueStatusOptions(wsId, projectId ?? undefined, common.status);+ const statusOptions = allowedStatuses ? options.filter((o) => allowedStatuses.has(o.key)) : options;+ const count = issues.length;+ const anchor = useMemo(+ () => ({+ getBoundingClientRect: () => DOMRect.fromRect({ x: point.x, y: point.y, width: 0, height: 0 }),+ }),+ [point.x, point.y],+ );+ const copyLinks = () => {+ const links = issues.map((issue) => getShareableUrl(paths.issueDetail(issue.identifier || issue.id)));+ void copyText(links.join("\n")).then((ok) => {+ if (ok) toast.success(t(($) => $.batch.links_copied, { count }));+ });+ };++ return (+ <ContextMenu open={open} onOpenChange={onOpenChange}>+ <ContextMenuContent anchor={anchor} className="w-auto min-w-52">+ <div className="px-2 pt-1 pb-1.5 text-caption text-muted-foreground">+ {t(($) => $.batch.selected, { count })}+ </div>+ <ContextMenuSeparator />+ <ContextMenuSub>+ <ContextMenuSubTrigger disabled={disabled}>+ {common.status ? (+ <StatusIcon status={common.status} className="h-3.5 w-3.5" />+ ) : (+ <CircleDot className="h-3.5 w-3.5" />+ )}+ {t(($) => $.batch.status)}+ </ContextMenuSubTrigger>+ <ContextMenuSubContent>+ {statusOptions.map((option) => (+ <ContextMenuItem key={option.key} onClick={() => onStatus(option.key)}>+ <StatusIcon+ status={option.key}+ category={option.category}+ color={option.color}+ icon={option.icon}+ className="h-3.5 w-3.5"+ />+ {option.label}+ {common.status === option.key && <Check className="ml-auto size-3.5 text-muted-foreground" />}+ </ContextMenuItem>+ ))}+ </ContextMenuSubContent>+ </ContextMenuSub>+ <ContextMenuSub>+ <ContextMenuSubTrigger disabled={disabled}>+ <PriorityIcon priority={common.priority ?? "none"} />+ {t(($) => $.batch.priority)}+ </ContextMenuSubTrigger>+ <ContextMenuSubContent>+ {PRIORITY_DISPLAY_ORDER.map((p) => (+ <ContextMenuItem key={p} onClick={() => onPriority(p)}>+ <span+ className={`inline-flex items-center gap-1 rounded-xs px-1.5 py-0.5 text-caption font-medium ${PRIORITY_CONFIG[p].badgeBg} ${PRIORITY_CONFIG[p].badgeText}`}+ >+ <PriorityIcon priority={p} className="h-3 w-3" inheritColor />+ {t(($) => $.priority[p])}+ </span>+ {common.priority === p && <Check className="ml-auto size-3.5 text-muted-foreground" />}+ </ContextMenuItem>+ ))}+ </ContextMenuSubContent>+ </ContextMenuSub>+ <ContextMenuSub>+ <ContextMenuSubTrigger disabled={disabled}>+ <UserMinus className="h-3.5 w-3.5" />+ {t(($) => $.batch.assignee)}+ </ContextMenuSubTrigger>+ <ContextMenuSubContent className="w-64 p-0">+ <SubmenuPanel>+ <AssigneePickerPanel+ assigneeType={common.assignee?.type ?? null}+ assigneeId={common.assignee?.id ?? null}+ onUpdate={onAssignee}+ onPicked={() => onOpenChange(false)}+ />+ </SubmenuPanel>+ </ContextMenuSubContent>+ </ContextMenuSub>+ <ContextMenuSeparator />+ <ContextMenuItem onClick={copyLinks}>+ <Link2 className="h-3.5 w-3.5" />+ {t(($) => $.batch.copy_links)}+ </ContextMenuItem>+ <ContextMenuItem onClick={onClear}>+ <X className="h-3.5 w-3.5" />+ {tLayout(($) => $.collection.clear_selection)}+ </ContextMenuItem>+ <ContextMenuSeparator />+ <ContextMenuItem+ variant="destructive"+ disabled={disabled || !canDelete}+ title={!canDelete ? t(($) => $.batch.delete_restricted) : undefined}+ onClick={onDelete}+ >+ <Trash2 className="h-3.5 w-3.5" />+ {t(($) => $.batch.delete_count, { count })}+ </ContextMenuItem>+ </ContextMenuContent>+ </ContextMenu>+ );+}diff --git a/packages/views/issues/components/comment-card-actions-menu.test.tsx b/packages/views/issues/components/comment-card-actions-menu.test.tsxindex a905e5bb92..eb9ad737c6 100644--- a/packages/views/issues/components/comment-card-actions-menu.test.tsx+++ b/packages/views/issues/components/comment-card-actions-menu.test.tsx@@ -5,10 +5,10 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import type { TimelineEntry } from "@multica/core/types";import { renderWithI18n } from "../../test/i18n";-// Comment "more actions" menu layout, in three groups: act on the comment-// (Edit, then Resolve), take it elsewhere (Copy, Copy link, Create sub-issue),-// and Delete alone at the bottom. Edit only shows on comments the viewer may-// edit, so on anyone else's comment Resolve leads the menu.+// Comment "more actions" menu layout, in four groups: respond (Reply, Add+// reaction, Edit), act on the thread (Resolve, Create sub-issue), share (Copy,+// Copy link), and Delete alone at the bottom. Edit and Delete only show on+// comments the viewer may change.vi.mock("@multica/core/api", () => ({api: { uploadFile: vi.fn() },@@ -52,6 +52,7 @@ vi.mock("../../editor", async () => ({}));import { CommentCard } from "./comment-card";+import { findContextMenuScope } from "../../common/context-menu-scope";function comment(id: string,@@ -113,16 +114,19 @@ async function openMenuLayout(index: number): Promise<string[]> {const agentAuthor = { actor_type: "agent", actor_id: "agent-1" } as const;describe("CommentCard — actions menu layout", () => {- it("groups the author's root menu as edit/resolve, copy/derive, delete", async () => {+ it("groups the author's root menu as respond, act, share, delete", async () => {renderThread(comment("root", null), []);expect(await openMenuLayout(0)).toEqual([+ "Reply",+ "Add reaction","Edit",+ SEPARATOR,"Resolve thread",+ "Create sub-issue from here",SEPARATOR,"Copy","Copy link",- "Create sub-issue from here",SEPARATOR,"Delete",]);@@ -133,32 +137,101 @@ describe("CommentCard — actions menu layout", () => {// Menus render in order: root first, then the reply.expect(await openMenuLayout(1)).toEqual([+ "Reply",+ "Add reaction","Edit",+ SEPARATOR,"Resolve thread with comment",+ "Create sub-issue from here",SEPARATOR,"Copy","Copy link",- "Create sub-issue from here",SEPARATOR,"Delete",]);});- it("leads with Resolve on someone else's comment", async () => {+ it("offers no Edit or Delete on someone else's comment", async () => {renderThread(comment("root", null, agentAuthor), []);expect(await openMenuLayout(0)).toEqual([+ "Reply",+ "Add reaction",+ SEPARATOR,"Resolve thread",+ "Create sub-issue from here",SEPARATOR,"Copy","Copy link",- "Create sub-issue from here",]);});- it("drops the leading separator when there is nothing to edit or resolve", async () => {+ it("keeps Create sub-issue when the thread cannot be resolved", async () => {renderThread(comment("root", null, agentAuthor), [], { resolvable: false });- expect(await openMenuLayout(0)).toEqual(["Copy", "Copy link", "Create sub-issue from here"]);+ expect(await openMenuLayout(0)).toEqual([+ "Reply",+ "Add reaction",+ SEPARATOR,+ "Create sub-issue from here",+ SEPARATOR,+ "Copy",+ "Copy link",+ ]);+ });+});++describe("CommentCard — right-click", () => {+ function menuItems(menu: HTMLElement) {+ return Array.from(menu.querySelectorAll('[role="menuitem"]'), (el) => el.textContent?.trim() ?? "");+ }++ it("opens the same menu as the ⋯ button at the cursor", async () => {+ renderThread(comment("root", null), []);++ fireEvent.contextMenu(screen.getByText("body root"), { clientX: 40, clientY: 60 });+ const menu = await screen.findByRole("menu");+ expect(menuItems(menu)).toEqual([+ "Reply",+ "Add reaction",+ "Edit",+ "Resolve thread",+ "Create sub-issue from here",+ "Copy",+ "Copy link",+ "Delete",+ ]);+ });++ it("leaves a right-click something inside already handled", () => {+ renderThread(comment("root", null), []);++ const body = screen.getByText("body root");+ body.addEventListener("contextmenu", (event) => event.preventDefault());+ fireEvent.contextMenu(body);+ expect(screen.queryByRole("menu")).toBeNull();+ });+});++describe("CommentCard — menus opened inside a comment", () => {+ it("offers the comment's actions as the submenu and adds selection entries", () => {+ renderThread(comment("root", null, agentAuthor), [comment("reply", "root")]);++ const scope = findContextMenuScope(screen.getByText("body reply"));+ expect(scope.submenu?.label).toBe("Comment actions");+ expect(scope.submenu?.groups.flat().map((action) => action.label)).toEqual([+ "Reply",+ "Add reaction",+ "Edit",+ "Resolve thread with comment",+ "Create sub-issue from here",+ "Copy",+ "Copy link",+ "Delete",+ ]);+ expect(scope.selectionActions("quoted").map((action) => action.label)).toEqual([+ "Add to reply",+ "Create sub-issue from selection",+ ]);});});diff --git a/packages/views/issues/components/comment-card.tsx b/packages/views/issues/components/comment-card.tsxindex af545545f8..8f4872824b 100644--- a/packages/views/issues/components/comment-card.tsx+++ b/packages/views/issues/components/comment-card.tsx@@ -1,7 +1,7 @@"use client";import { Fragment, memo, useCallback, useEffect, useRef, useState, type ReactNode } from "react";-import { CheckCircle2, ChevronRight, CornerUpLeft, ListChevronsDownUp, Copy, Link2, Loader2, MessageSquarePlus, MoreHorizontal, Pencil, RotateCcw, Trash2 } from "@multica/ui/icons";+import { CheckCircle2, ChevronRight, CornerUpLeft, ListChevronsDownUp, Copy, Link2, Loader2, MessageSquare, MessageSquarePlus, MoreHorizontal, Pencil, Plus, RotateCcw, SmilePlus, Trash2 } from "@multica/ui/icons";import { toast } from "sonner";import { Card } from "@multica/ui/components/ui/card";import { Button, buttonVariants } from "@multica/ui/components/ui/button";@@ -9,8 +9,6 @@ import {DropdownMenu,DropdownMenuTrigger,DropdownMenuContent,- DropdownMenuItem,- DropdownMenuSeparator,} from "@multica/ui/components/ui/dropdown-menu";import { Tooltip, TooltipTrigger, TooltipContent } from "@multica/ui/components/ui/tooltip";import {@@ -24,6 +22,10 @@ import {AlertDialogTitle,} from "@multica/ui/components/ui/alert-dialog";import { ActorAvatar } from "../../common/actor-avatar";+import { shouldOpenRowMenu, useRowMenu } from "../../common/point-menu";+import { MenuActionGroups, useContextMenuScope } from "../../common/context-menu-scope";+import { dropdownPrimitives } from "../../common/menu-primitives";+import type { RowActionItem } from "../../common/row-actions-menu";import { DeferredTooltip } from "../../common/deferred-tooltip";import { ReactionBar } from "@multica/ui/components/common/reaction-bar";import { QuickEmojiPicker } from "@multica/ui/components/common/quick-emoji-picker";@@ -35,7 +37,7 @@ import { ContentEditor, type ContentEditorRef, ReadonlyContent, useFileDropZone,import { useCommentUploads } from "./use-comment-uploads";import { FileUploadButton } from "@multica/ui/components/common/file-upload-button";import { api, dispatchReasonCode, errorCode } from "@multica/core/api";-import { ReplyInput } from "./reply-input";+import { ReplyInput, type ReplyInputHandle } from "./reply-input";import { VirtualThreadRow } from "./virtual-thread-row";import { CommentTriggerChips } from "./comment-trigger-chips";import { AppCallChips } from "./app-call-chips";@@ -141,7 +143,7 @@ interface CommentCardProps {onEdit: (commentId: string, content: string, attachmentIds: string[], suppressAgentIds?: string[], contentBase?: string) => Promise<void>;onDelete: (commentId: string) => void;onToggleReaction: (commentId: string, emoji: string) => void;- onCreateSubIssue?: (commentId: string) => void;+ onCreateSubIssue?: (commentId: string, prompt?: string) => void;/** Resolve/unresolve any comment in this thread (commentId = the target row). */onResolveToggle?: (commentId: string, resolved: boolean) => void;/** Copy a deep link (`#comment-…`) to a single comment in this thread. */@@ -627,6 +629,121 @@ function CommentRevisionConflict({// Single comment row (used for both parent and replies within the same Card)+/**+ * A comment's menu, the same groups on its ⋯ button, on right-click, and as+ * the "Comment actions" submenu of content inside it: answer it, change it,+ * take it elsewhere, then delete alone.+ */+function useCommentMenuGroups({+ entry,+ editing,+ canEdit,+ canDelete,+ resolve,+ onStartEdit,+ onReply,+ onAddReaction,+ onCopyLink,+ onCreateSubIssue,+ onDelete,+}: {+ entry: TimelineEntry;+ editing: boolean;+ canEdit: boolean;+ canDelete: boolean;+ resolve?: Pick<RowActionItem, "icon" | "label" | "onSelect">;+ onStartEdit: () => void;+ onReply?: () => void;+ onAddReaction: () => void;+ onCopyLink?: (commentId: string) => void;+ onCreateSubIssue?: (commentId: string, prompt?: string) => void;+ onDelete: () => void;+}): RowActionItem[][] {+ const { t } = useT("issues");+ const respond: RowActionItem[] = [];+ if (onReply) {+ respond.push({ key: "reply", icon: <CornerUpLeft className="h-3.5 w-3.5" />, label: t(($) => $.comment.reply_action), onSelect: onReply });+ }+ if (!editing) {+ respond.push({ key: "react", icon: <SmilePlus className="h-3.5 w-3.5" />, label: t(($) => $.comment.add_reaction), onSelect: onAddReaction });+ }+ if (canEdit) {+ respond.push({ key: "edit", icon: <Pencil className="h-3.5 w-3.5" />, label: t(($) => $.comment.edit_action), onSelect: onStartEdit });+ }+ const act: RowActionItem[] = [];+ if (resolve) act.push({ key: "resolve", ...resolve });+ if (onCreateSubIssue && entry.comment_type === "comment") {+ act.push({+ key: "sub-issue",+ icon: <MessageSquarePlus className="h-3.5 w-3.5" aria-hidden />,+ label: t(($) => $.source_context.create_action),+ onSelect: () => onCreateSubIssue(entry.id),+ });+ }+ const share: RowActionItem[] = [{+ key: "copy",+ icon: <Copy className="h-3.5 w-3.5" />,+ label: t(($) => $.comment.copy_action),+ onSelect: () => {+ void copyText(entry.content ?? "").then((ok) => {+ if (ok) toast.success(t(($) => $.comment.copied_toast));+ });+ },+ }];+ if (onCopyLink) {+ share.push({ key: "copy-link", icon: <Link2 className="h-3.5 w-3.5" />, label: t(($) => $.comment.copy_link_action), onSelect: () => onCopyLink(entry.id) });+ }+ const remove: RowActionItem[] = canDelete+ ? [{ key: "delete", icon: <Trash2 className="h-3.5 w-3.5" />, label: t(($) => $.comment.delete_action), danger: true, onSelect: onDelete }]+ : [];+ return [respond, act, share, remove];+}++/**+ * Registers a comment as the scope of content menus inside it: a link, a+ * mention or selected text there carries the comment's actions in a submenu,+ * and selected text can become a sub-issue.+ */+function useCommentScope(+ entry: TimelineEntry,+ groups: RowActionItem[][] | null,+ onCreateSubIssue?: (commentId: string, prompt?: string) => void,+) {+ const { t } = useT("issues");+ return useContextMenuScope(() => groups && {+ label: t(($) => $.comment.actions_label),+ icon: <MessageSquare className="h-3.5 w-3.5" />,+ groups,+ selectionActions: onCreateSubIssue && entry.comment_type === "comment"+ ? (text) => [{+ key: "create-issue",+ icon: <Plus className="h-3.5 w-3.5" />,+ label: t(($) => $.comment.create_issue_from_selection),+ onSelect: () => onCreateSubIssue(entry.id, quoteMarkdown(text)),+ }]+ : undefined,+ });+}++function quoteMarkdown(text: string) {+ return text.trim().split("\n").map((line) => `> ${line}`).join("\n");+}++/** Runs an action a menu item picked once the menu has closed, so the menu+ * does not hand focus back to its trigger over whatever the action opened. */+function useAfterMenuClose() {+ const pendingRef = useRef(false);+ const finalFocus = useCallback(() => !pendingRef.current, []);+ const schedule = useCallback((action: () => void) => () => {+ pendingRef.current = true;+ setTimeout(() => {+ action();+ setTimeout(() => { pendingRef.current = false; }, 300);+ }, 0);+ }, []);+ return { finalFocus, schedule };+}+function CommentRow({runHeader,runMetadata,@@ -644,6 +761,7 @@ function CommentRow({onCreateSubIssue,onResolveToggle,onCopyLink,+ onFocusReply,}: {runHeader?: ReactNode;runMetadata?: ReactNode;@@ -661,9 +779,11 @@ function CommentRow({onEdit: (commentId: string, content: string, attachmentIds: string[], suppressAgentIds?: string[], contentBase?: string) => Promise<void>;onDelete: (commentId: string) => void;onToggleReaction: (commentId: string, emoji: string) => void;- onCreateSubIssue?: (commentId: string) => void;+ onCreateSubIssue?: (commentId: string, prompt?: string) => void;onResolveToggle?: (commentId: string, resolved: boolean) => void;onCopyLink?: (commentId: string) => void;+ /** Moves the caret into the thread's reply box. */+ onFocusReply?: () => void;}) {const { t } = useT("issues");const locale = useLocale();@@ -679,6 +799,27 @@ function CommentRow({const canEditEntry = receipts.length === 0 && (isOwn || (canModerate && entry.actor_type === "member"));const canDeleteEntry = !receipts.some(isSupplementInFlight) && (isOwn || canModerate);const [confirmDelete, setConfirmDelete] = useState(false);+ // Right-click on the comment opens its ⋯ menu at the cursor; links, images+ // and selected text inside it keep their own menu.+ const rowMenu = useRowMenu();+ const [reactionOpen, setReactionOpen] = useState(false);+ const afterClose = useAfterMenuClose();+ const menuGroups = useCommentMenuGroups({+ entry,+ editing: edit.editing,+ canEdit: canEditEntry,+ canDelete: canDeleteEntry,+ resolve: onResolveToggle && (isResolution+ ? { icon: <RotateCcw className="h-3.5 w-3.5" />, label: t(($) => $.comment.resolve.unresolve_action), onSelect: () => onResolveToggle(entry.id, false) }+ : { icon: <CheckCircle2 className="h-3.5 w-3.5" />, label: t(($) => $.comment.resolve.resolve_with_comment_action), onSelect: () => onResolveToggle(entry.id, true) }),+ onStartEdit: edit.startEdit,+ onReply: onFocusReply && afterClose.schedule(onFocusReply),+ onAddReaction: afterClose.schedule(() => setReactionOpen(true)),+ onCopyLink,+ onCreateSubIssue,+ onDelete: () => setConfirmDelete(true),+ });+ const scopeRef = useCommentScope(entry, edit.editing ? null : menuGroups, onCreateSubIssue);const reactions = entry.reactions ?? [];@@ -690,7 +831,15 @@ function CommentRow({if (isDeletedComment(entry)) return null;return (- <div data-comment-block className="pb-3">+ <div+ ref={scopeRef}+ data-comment-block+ className="pb-3"+ onContextMenu={(e) => {+ if (edit.editing || !shouldOpenRowMenu(e, { deferToContent: true })) return;+ rowMenu.openAtPointer(e);+ }}+ >{/* Header pins to the timeline's scroll parent within this reply's ownrow box, so a LONG reply keeps itsauthor + actions visible while you scroll its body, then releases once@@ -744,9 +893,11 @@ function CommentRow({onSelect={(emoji) => onToggleReaction(entry.id, emoji)}ariaLabel={t(($) => $.comment.add_reaction)}align="end"+ open={reactionOpen}+ onOpenChange={setReactionOpen}className={buttonVariants({ variant: "ghost", size: "icon-sm", className: commentActionClassName })}/>}- <DropdownMenu>+ <DropdownMenu open={rowMenu.menu.open} onOpenChange={rowMenu.onOpenChange}><DeferredTooltipcontent={t(($) => $.comment.more_actions)}trigger={@@ -764,57 +915,13 @@ function CommentRow({/>}/>- <DropdownMenuContent align="end">- {/* Groups: act on it (edit, resolve), take it elsewhere, then delete alone. */}- {canEditEntry && (- <DropdownMenuItem onClick={edit.startEdit}>- <Pencil className="h-3.5 w-3.5" />- {t(($) => $.comment.edit_action)}- </DropdownMenuItem>- )}- {onResolveToggle && (- isResolution ? (- <DropdownMenuItem onClick={() => onResolveToggle(entry.id, false)}>- <RotateCcw className="h-3.5 w-3.5" />- {t(($) => $.comment.resolve.unresolve_action)}- </DropdownMenuItem>- ) : (- <DropdownMenuItem onClick={() => onResolveToggle(entry.id, true)}>- <CheckCircle2 className="h-3.5 w-3.5" />- {t(($) => $.comment.resolve.resolve_with_comment_action)}- </DropdownMenuItem>- )- )}- {(canEditEntry || onResolveToggle) && <DropdownMenuSeparator />}- <DropdownMenuItem onClick={() => {- void copyText(entry.content ?? "").then((ok) => {- if (ok) toast.success(t(($) => $.comment.copied_toast));- });- }}>- <Copy className="h-3.5 w-3.5" />- {t(($) => $.comment.copy_action)}- </DropdownMenuItem>- {onCopyLink && (- <DropdownMenuItem onClick={() => onCopyLink(entry.id)}>- <Link2 className="h-3.5 w-3.5" />- {t(($) => $.comment.copy_link_action)}- </DropdownMenuItem>- )}- {onCreateSubIssue && entry.comment_type === "comment" && (- <DropdownMenuItem onClick={() => onCreateSubIssue(entry.id)}>- <MessageSquarePlus className="h-3.5 w-3.5" aria-hidden />- {t(($) => $.source_context.create_action)}- </DropdownMenuItem>- )}- {canDeleteEntry && (- <>- <DropdownMenuSeparator />- <DropdownMenuItem onClick={() => setConfirmDelete(true)} variant="destructive">- <Trash2 className="h-3.5 w-3.5" />- {t(($) => $.comment.delete_action)}- </DropdownMenuItem>- </>- )}+ <DropdownMenuContent+ align={rowMenu.menu.point ? "start" : "end"}+ anchor={rowMenu.anchor}+ finalFocus={afterClose.finalFocus}+ className="w-auto min-w-44"+ >+ <MenuActionGroups groups={menuGroups} primitives={dropdownPrimitives} /></DropdownMenuContent></DropdownMenu><DeleteCommentDialog@@ -1082,6 +1189,50 @@ function CommentCardImpl({const canEditEntry = receipts.length === 0 && (isOwn || (canModerate && entry.actor_type === "member"));const canDeleteEntry = !receipts.some(isSupplementInFlight) && (isOwn || canModerate);const [confirmDelete, setConfirmDelete] = useState(false);+ const rowMenu = useRowMenu();+ const [reactionOpen, setReactionOpen] = useState(false);+ const afterClose = useAfterMenuClose();+ const replyBoxRef = useRef<ReplyInputHandle>(null);+ const revealReplyBox = () => {+ if (replyFolded) onResolvedExpandChange?.(entry.id, true);+ if (!open) toggleCollapse(issueId, entry.id);+ };+ const focusReply = () => {+ revealReplyBox();+ requestAnimationFrame(() => replyBoxRef.current?.focus());+ };+ const menuGroups = useCommentMenuGroups({+ entry,+ editing: edit.editing,+ canEdit: canEditEntry,+ canDelete: canDeleteEntry,+ resolve: onResolveToggle && (entry.resolved_at+ ? { icon: <RotateCcw className="h-3.5 w-3.5" />, label: t(($) => $.comment.resolve.unresolve_thread_action), onSelect: () => onResolveToggle(entry.id, false) }+ : { icon: <CheckCircle2 className="h-3.5 w-3.5" />, label: t(($) => $.comment.resolve.resolve_thread_action), onSelect: () => onResolveToggle(entry.id, true) }),+ onStartEdit: edit.startEdit,+ onReply: currentUserId ? afterClose.schedule(focusReply) : undefined,+ onAddReaction: afterClose.schedule(() => setReactionOpen(true)),+ onCopyLink,+ onCreateSubIssue,+ onDelete: () => setConfirmDelete(true),+ });+ const rootScopeRef = useCommentScope(entry, !open || isDeletedComment(entry) || edit.editing ? null : menuGroups, onCreateSubIssue);+ // Selected text gets the same "Add to reply" as the selection bubble.+ const threadScopeRef = useContextMenuScope(() => currentUserId ? {+ selectionActions: () => [+ {+ key: "annotate",+ icon: <MessageSquarePlus className="h-3.5 w-3.5" />,+ label: t(($) => $.reply.annotations.add),+ onSelect: () => { annotation.addSelection(); },+ },+ ],+ } : null);+ const annotationCardRef = annotation.cardRef;+ const cardRef = useCallback((node: HTMLDivElement | null) => {+ annotationCardRef(node);+ threadScopeRef(node);+ }, [annotationCardRef, threadScopeRef]);const allNestedReplies = replies;// What the thread shows. Tombstones are excluded from display and counts but@@ -1139,6 +1290,7 @@ function CommentCardImpl({onCreateSubIssue={onCreateSubIssue}onResolveToggle={onResolveToggle}onCopyLink={onCopyLink}+ onFocusReply={currentUserId ? focusReply : undefined}/></div>)}@@ -1204,7 +1356,7 @@ function CommentCardImpl({// overflow-clip (not -hidden) clips the rounded corners WITHOUT creating a// scroll container, so the sticky collapse affordances below resolve to the// timeline's scroll parent instead of this card. See PR #3623.- <Card data-mc="comment" data-author-type={entry.actor_type} ref={annotation.cardRef} {...annotation.captureProps} className="!py-0 !gap-0 overflow-clip transition-colors duration-700">+ <Card data-mc="comment" data-author-type={entry.actor_type} ref={cardRef} {...annotation.captureProps} className="!py-0 !gap-0 overflow-clip transition-colors duration-700">{annotation.popup}{onCollapseResolved && (<button@@ -1224,7 +1376,17 @@ function CommentCardImpl({That is what keeps exactly one header pinned at a time: without thiswrapper the header's containing block is the whole thread and itstays stuck behind every reply. */}- <div data-comment-block className={cn("transition-colors duration-700", isHighlighted && highlightedCommentBackgroundClass)}>+ <div+ ref={rootScopeRef}+ data-comment-block+ className={cn("transition-colors duration-700", isHighlighted && highlightedCommentBackgroundClass)}+ // Same right-click as a reply's; only while the thread is open, since+ // the menu lives in the open header.+ onContextMenu={(e) => {+ if (!open || deleted || edit.editing || !shouldOpenRowMenu(e, { deferToContent: true })) return;+ rowMenu.openAtPointer(e);+ }}+ >{/* Keep the author aligned with replies; thread controls sit on the right. */}<StickyHeaderShellsticky={stickyHeader}@@ -1307,9 +1469,11 @@ function CommentCardImpl({onSelect={(emoji) => onToggleReaction(entry.id, emoji)}ariaLabel={t(($) => $.comment.add_reaction)}align="end"+ open={reactionOpen}+ onOpenChange={setReactionOpen}className={buttonVariants({ variant: "ghost", size: "icon-sm", className: commentActionClassName })}/>}- <DropdownMenu>+ <DropdownMenu open={rowMenu.menu.open} onOpenChange={rowMenu.onOpenChange}><DeferredTooltipcontent={t(($) => $.comment.more_actions)}trigger={@@ -1327,59 +1491,13 @@ function CommentCardImpl({/>}/>- <DropdownMenuContent align="end">- {/* Groups: act on it (edit, resolve), take it elsewhere, then delete alone. */}- {canEditEntry && (- <DropdownMenuItem onClick={edit.startEdit}>- <Pencil className="h-3.5 w-3.5" />- {t(($) => $.comment.edit_action)}- </DropdownMenuItem>- )}- {onResolveToggle && (- <DropdownMenuItem onClick={() => onResolveToggle(entry.id, !entry.resolved_at)}>- {entry.resolved_at ? (- <>- <RotateCcw className="h-3.5 w-3.5" />- {t(($) => $.comment.resolve.unresolve_thread_action)}- </>- ) : (- <>- <CheckCircle2 className="h-3.5 w-3.5" />- {t(($) => $.comment.resolve.resolve_thread_action)}- </>- )}- </DropdownMenuItem>- )}- {(canEditEntry || onResolveToggle) && <DropdownMenuSeparator />}- <DropdownMenuItem onClick={() => {- void copyText(entry.content ?? "").then((ok) => {- if (ok) toast.success(t(($) => $.comment.copied_toast));- });- }}>- <Copy className="h-3.5 w-3.5" />- {t(($) => $.comment.copy_action)}- </DropdownMenuItem>- {onCopyLink && (- <DropdownMenuItem onClick={() => onCopyLink(entry.id)}>- <Link2 className="h-3.5 w-3.5" />- {t(($) => $.comment.copy_link_action)}- </DropdownMenuItem>- )}- {onCreateSubIssue && entry.comment_type === "comment" && (- <DropdownMenuItem onClick={() => onCreateSubIssue(entry.id)}>- <MessageSquarePlus className="h-3.5 w-3.5" aria-hidden />- {t(($) => $.source_context.create_action)}- </DropdownMenuItem>- )}- {canDeleteEntry && (- <>- <DropdownMenuSeparator />- <DropdownMenuItem onClick={() => setConfirmDelete(true)} variant="destructive">- <Trash2 className="h-3.5 w-3.5" />- {t(($) => $.comment.delete_action)}- </DropdownMenuItem>- </>- )}+ <DropdownMenuContent+ align={rowMenu.menu.point ? "start" : "end"}+ anchor={rowMenu.anchor}+ finalFocus={afterClose.finalFocus}+ className="w-auto min-w-44"+ >+ <MenuActionGroups groups={menuGroups} primitives={dropdownPrimitives} /></DropdownMenuContent></DropdownMenu><DeleteCommentDialog@@ -1551,6 +1669,7 @@ function CommentCardImpl({{/* Reply input */}<div className="border-t border-border/50 px-4 max-md:px-3 py-2.5"><ReplyInput+ handleRef={replyBoxRef}issueId={issueId}parentId={replyTargetId}targetMissing={replyTargetMissing}diff --git a/packages/views/issues/components/issue-chip.tsx b/packages/views/issues/components/issue-chip.tsxindex 830ec0e012..48e51d999d 100644--- a/packages/views/issues/components/issue-chip.tsx+++ b/packages/views/issues/components/issue-chip.tsx@@ -52,14 +52,10 @@ export interface IssueChipProps {const BASE_CLASS ="issue-mention inline-flex min-w-0 max-w-[min(18rem,100%)] items-center gap-1.5 rounded-md border mx-0.5 px-2 py-0.5 text-caption";-export function IssueChip({- issueId,- fallbackLabel,- children,- className,-}: IssueChipProps) {+/** The issue a chip shows, from the issue list cache or, past its first page,+ * the issue's own query. Undefined until it loads, or when it is gone. */+export function useChipIssue(issueId: string) {const wsId = useWorkspaceId();- const { colorOf: statusColorOf, iconOf: statusIconOf } = useIssueStatuses(wsId);const { data: issues = [] } = useQuery(issueListOptions(wsId));const listIssue = issues.find((i) => i.id === issueId);@@ -74,7 +70,18 @@ export function IssueChip({!(query.state.error instanceof ApiError && query.state.error.status === 404),});- const issue = listIssue ?? detailIssue;+ return listIssue ?? detailIssue;+}++export function IssueChip({+ issueId,+ fallbackLabel,+ children,+ className,+}: IssueChipProps) {+ const wsId = useWorkspaceId();+ const { colorOf: statusColorOf, iconOf: statusIconOf } = useIssueStatuses(wsId);+ const issue = useChipIssue(issueId);const cls = className ? `${BASE_CLASS} ${className}` : BASE_CLASS;if (children !== undefined) {diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsxindex c7a8d455b0..1dec2baf6e 100644--- a/packages/views/issues/components/issue-detail.tsx+++ b/packages/views/issues/components/issue-detail.tsx@@ -1742,11 +1742,12 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = trlabel: t(($) => $.reply.annotations.add_comment),onSelect: descriptionAnnotations.addSelection,} : undefined, [canAnnotateDescription, t, descriptionAnnotations.addSelection]);- const openCommentSubIssue = useCallback((commentId: string) => {+ const openCommentSubIssue = useCallback((commentId: string, prompt?: string) => {if (!issue) return;openModal("quick-create-issue", {...subIssueCreateDefaults(issue),anchor_comment_id: commentId,+ ...(prompt ? { prompt } : {}),});}, [issue, openModal]);diff --git a/packages/views/issues/components/issue-mention-card.test.tsx b/packages/views/issues/components/issue-mention-card.test.tsxindex 19ec0db0f9..c0d7039420 100644--- a/packages/views/issues/components/issue-mention-card.test.tsx+++ b/packages/views/issues/components/issue-mention-card.test.tsx@@ -21,6 +21,7 @@ vi.mock("@multica/core/paths", () => ({}));vi.mock("./issue-chip", () => ({+ useChipIssue: () => undefined,IssueChip: ({fallbackLabel,children,diff --git a/packages/views/issues/components/issue-mention-card.tsx b/packages/views/issues/components/issue-mention-card.tsxindex e2432b7856..5510b5d291 100644--- a/packages/views/issues/components/issue-mention-card.tsx+++ b/packages/views/issues/components/issue-mention-card.tsx@@ -1,12 +1,17 @@"use client";import { AppLink } from "../../navigation";+import { yieldsToTextMenu } from "../../common/point-menu";import { useWorkspacePaths } from "@multica/core/paths";-import { IssueChip } from "./issue-chip";+import { IssueChip, useChipIssue } from "./issue-chip";import { IssueHoverCard } from "./issue-hover-card";import { useT } from "../../i18n";import { useCurrentIssueRenderContext } from "../current-issue-render-context";import { useIssuePeekActions } from "../surface/peek-context";+import {+ IssueContextMenuProvider,+ useOpenIssueContextMenu,+} from "../actions/issue-actions-context-menu";/** Shift+Click with the primary button and no other modifier. */function isPeekClick(event: React.MouseEvent) {@@ -53,49 +58,74 @@ function CurrentIssueChipContent({ identifier }: { identifier: string }) {* for. No `delay` is passed, so it opens on Base UI's default dwell. The same* `fallbackLabel` the chip degrades to names the card when the detail fetch* fails.+ *+ * Right-click opens the sidebar's issue menu at the cursor once the issue has+ * loaded. Its provider sits outside the hover card, so the open menu does not+ * count as hovering the chip.*/export function IssueMentionCard({ issueId, fallbackLabel }: IssueMentionCardProps) {+ return (+ <IssueContextMenuProvider variant="sidebar">+ <IssueHoverCard issueId={issueId} fallbackLabel={fallbackLabel}>+ <IssueMentionLink issueId={issueId} fallbackLabel={fallbackLabel} />+ </IssueHoverCard>+ </IssueContextMenuProvider>+ );+}++function IssueMentionLink({ issueId, fallbackLabel }: IssueMentionCardProps) {const p = useWorkspacePaths();const currentIssue = useCurrentIssueRenderContext();const peek = useIssuePeekActions();+ const issue = useChipIssue(issueId);+ const openMenu = useOpenIssueContextMenu();const currentIdentifier =currentIssue && issueId === currentIssue.id? currentIssue.identifier: null;return (- <IssueHoverCard issueId={issueId} fallbackLabel={fallbackLabel}>- <AppLink- href={p.issueDetail(issueId)}- newTabTitle={fallbackLabel}- className="issue-mention align-middle"- onMouseDown={- peek- ? (event) => {- // Keep the shift-click from extending the text selection.- if (isPeekClick(event)) event.preventDefault();- }- : undefined- }- onClick={- peek- ? (event) => {- if (!isPeekClick(event)) return;- event.preventDefault();- peek.toggle(issueId);- }- : undefined- }+ <AppLink+ href={p.issueDetail(issueId)}+ newTabTitle={fallbackLabel}+ className="issue-mention align-middle"+ onContextMenu={+ issue+ ? (event) => {+ // The innermost object's menu wins; a row around the mention+ // must not open its own as well. Selected text and an editor+ // keep their text menu.+ event.stopPropagation();+ if (!yieldsToTextMenu(event.target as Element)) openMenu(issue, event);+ }+ : undefined+ }+ onMouseDown={+ peek+ ? (event) => {+ // Keep the shift-click from extending the text selection.+ if (isPeekClick(event)) event.preventDefault();+ }+ : undefined+ }+ onClick={+ peek+ ? (event) => {+ if (!isPeekClick(event)) return;+ event.preventDefault();+ peek.toggle(issueId);+ }+ : undefined+ }+ >+ <IssueChip+ issueId={issueId}+ fallbackLabel={fallbackLabel}+ className="cursor-pointer hover:bg-accent transition-colors">- <IssueChip- issueId={issueId}- fallbackLabel={fallbackLabel}- className="cursor-pointer hover:bg-accent transition-colors"- >- {currentIdentifier ? (- <CurrentIssueChipContent identifier={currentIdentifier} />- ) : undefined}- </IssueChip>- </AppLink>- </IssueHoverCard>+ {currentIdentifier ? (+ <CurrentIssueChipContent identifier={currentIdentifier} />+ ) : undefined}+ </IssueChip>+ </AppLink>);}diff --git a/packages/views/issues/components/reply-input.tsx b/packages/views/issues/components/reply-input.tsxindex 61473df3ad..3e9beeb181 100644--- a/packages/views/issues/components/reply-input.tsx+++ b/packages/views/issues/components/reply-input.tsx@@ -3,7 +3,7 @@import { composeAnnotatedReply, EMPTY_REPLY_ANNOTATIONS, hasReplyIntent } from "@multica/core/drafts/reply-annotation";import { annotationsWithPending, type AnnotationComposerSlot } from "./annotation-composer";import { ReplyAnnotations } from "./reply-annotations";-import { useRef, useState, useEffect, useMemo } from "react";+import { useRef, useState, useEffect, useImperativeHandle, useMemo, type Ref } from "react";import { toast } from "sonner";import { ContentEditor, type ContentEditorRef, useFileDropZone, FileDropOverlay, useLazyEditor, useUploadGate, useComposerSubmit } from "../../editor";import { FileUploadButton } from "@multica/ui/components/common/file-upload-button";@@ -27,7 +27,13 @@ import { useQuickActionMenu } from "../hooks/use-quick-action-menu";// Types+/** Lets the thread around the box move the caret into it, e.g. from a menu. */+interface ReplyInputHandle {+ focus: () => void;+}+interface ReplyInputProps {+ handleRef?: Ref<ReplyInputHandle>;issueId: string;parentId: string;placeholder?: string;@@ -56,6 +62,7 @@ const NEVER_STEER_BY_DEFAULT = () => false;// ReplyInputfunction ReplyInput({+ handleRef,issueId,parentId,placeholder,@@ -133,6 +140,7 @@ function ReplyInput({(draftKey ? useCommentDraftStore.getState().getUploads(draftKey).length > 0 : false),editorRef,});+ useImperativeHandle(handleRef, () => ({ focus: () => lazy.activate() }), [lazy]);const { isDragOver, dropZoneProps } = useFileDropZone({onDrop: lazy.uploadOrQueue,});@@ -380,4 +388,4 @@ function ReplyInput({</>);}-export { ReplyInput, type ReplyInputProps };+export { ReplyInput, type ReplyInputHandle, type ReplyInputProps };diff --git a/packages/views/layout/app-rail.tsx b/packages/views/layout/app-rail.tsxindex 3da5246cde..440a3d8923 100644--- a/packages/views/layout/app-rail.tsx+++ b/packages/views/layout/app-rail.tsx@@ -13,13 +13,16 @@ import {import { restrictToFirstScrollableAncestor, restrictToVerticalAxis } from "@dnd-kit/modifiers";import { SortableContext, arrayMove, useSortable, verticalListSortingStrategy } from "@dnd-kit/sortable";import { CSS } from "@dnd-kit/utilities";-import { Settings, Users, type IconComponent } from "@multica/ui/icons";+import { CheckCheck, ExternalLink, Link2, RotateCcw, Settings, Users, type IconComponent } from "@multica/ui/icons";+import { toast } from "sonner";import { useChatStore } from "@multica/core/chat";import { chatSessionsOptions } from "@multica/core/chat/queries";import { countUnreadChatMessages } from "@multica/core/chat/unread";import { useInboxUnreadCount } from "@multica/core/inbox/queries";+import { useMarkAllInboxRead } from "@multica/core/inbox/mutations";import { resolveRailOrder, useRailOrderStore } from "@multica/core/navigation";import {+ RAIL_SPACES,useCurrentWorkspace,useWorkspacePaths,type AppSpaceId,@@ -29,9 +32,17 @@ import { TooltipHint } from "@multica/ui/components/common/tooltip-hint";import { TruncatedTooltip } from "@multica/ui/components/common/truncated-tooltip";import { CappedNumberFlow } from "@multica/ui/components/ui/number-flow";import { cn } from "@multica/ui/lib/utils";+import { copyText } from "@multica/ui/lib/clipboard";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+} from "@multica/ui/components/ui/dropdown-menu";import { useAppForeground } from "../common/use-app-foreground";+import { useRowMenu } from "../common/point-menu";import { useT } from "../i18n";-import { AppLink, useNavigation } from "../navigation";+import { AppLink, useIntentNavigate, useNavigation } from "../navigation";import { AccountMenu } from "./account-menu";import { useAppShell } from "./app-shell-context";import { NewIssueButton, SearchButton } from "./global-actions";@@ -149,6 +160,9 @@ function RailSpaceLink({badge?: RailBadge;}) {const peekHandlers = usePeekHandlers(space, true);+ // Desktop only: in a browser the link keeps the browser's own link menu.+ const { openInNewTab } = useNavigation();+ const rowMenu = useRowMenu();const link = (<AppLinkhref={href}@@ -156,6 +170,7 @@ function RailSpaceLink({newTabTitle={fullLabel}draggable={false}aria-current={active ? "page" : undefined}+ onContextMenu={openInNewTab ? rowMenu.openAtPointer : undefined}{...peekHandlers}className="group relative flex size-12 flex-col items-center justify-center gap-1 rounded-rail-item text-rail-item transition-colors outline-none hover:bg-rail-item-hover hover:text-rail-item-active-foreground focus-visible:outline-2 focus-visible:outline-ring aria-[current=page]:bg-rail-item-active aria-[current=page]:font-medium aria-[current=page]:text-rail-item-active-foreground">@@ -164,19 +179,92 @@ function RailSpaceLink({{badge && <RailBadgeMark badge={badge} />}</AppLink>);+ // The menu portals out of the sortable item, but its React events still+ // bubble through it; a press inside the menu must not start a drag.+ const menu = rowMenu.menu.point && (+ <span className="contents" onPointerDown={(event) => event.stopPropagation()}>+ <RailSpaceMenu space={space} href={href} title={fullLabel} unread={badge?.kind === "count" ? badge.value : 0} state={rowMenu} />+ </span>+ );// A label the same as the full name still needs the tooltip whenever a// locale's text doesn't fit the 48px item.if (label === fullLabel) {return (- <TruncatedTooltip content={fullLabel} side="right">- {link}- </TruncatedTooltip>+ <>+ <TruncatedTooltip content={fullLabel} side="right">+ {link}+ </TruncatedTooltip>+ {menu}+ </>);}return (- <TooltipHint label={fullLabel} side="right">- {link}- </TooltipHint>+ <>+ <TooltipHint label={fullLabel} side="right">+ {link}+ </TooltipHint>+ {menu}+ </>+ );+}++/** A rail space's right-click menu. */+function RailSpaceMenu({+ space,+ href,+ title,+ unread,+ state,+}: {+ space: RailSpaceId;+ href: string;+ title: string;+ unread: number;+ state: ReturnType<typeof useRowMenu>;+}) {+ const { t } = useT("layout");+ const { t: tCommon } = useT("common");+ const { getShareableUrl } = useNavigation();+ const intentNavigate = useIntentNavigate();+ const copyLink = async () => {+ if (await copyText(getShareableUrl(href))) toast.success(t(($) => $.rail.link_copied));+ };+ const markAllRead = useMarkAllInboxRead();+ const customOrder = useRailOrderStore((s) => s.order !== null);+ const setOrder = useRailOrderStore((s) => s.setOrder);+ return (+ <DropdownMenu open={state.menu.open} onOpenChange={state.onOpenChange}>+ <DropdownMenuContent align="start" anchor={state.anchor} className="w-auto min-w-44">+ <DropdownMenuItem onClick={() => intentNavigate(href, "foreground-tab", title)}>+ <ExternalLink />+ {tCommon(($) => $.navigation.open_in_new_tab)}+ </DropdownMenuItem>+ <DropdownMenuItem onClick={() => void copyLink()}>+ <Link2 />+ {t(($) => $.rail.copy_link)}+ </DropdownMenuItem>+ {space === "inbox" && unread > 0 && (+ <>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ onClick={() =>+ markAllRead.mutate(undefined, {+ onError: () => toast.error(t(($) => $.rail.mark_all_read_failed)),+ })+ }+ >+ <CheckCheck />+ {t(($) => $.rail.mark_all_read)}+ </DropdownMenuItem>+ </>+ )}+ <DropdownMenuSeparator />+ <DropdownMenuItem disabled={!customOrder} onClick={() => setOrder(RAIL_SPACES)}>+ <RotateCcw />+ {t(($) => $.rail.reset_order)}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>);}diff --git a/packages/views/layout/collection-list/collection-row-menu.tsx b/packages/views/layout/collection-list/collection-row-menu.tsxindex eb4c0a0d29..8024bcb2b0 100644--- a/packages/views/layout/collection-list/collection-row-menu.tsx+++ b/packages/views/layout/collection-list/collection-row-menu.tsx@@ -1,6 +1,6 @@"use client";-import { useMemo, useState, type ReactNode } from "react";+import { useState, type ReactNode } from "react";import { MoreHorizontal } from "@multica/ui/icons";import { cn } from "@multica/ui/lib/utils";import { DeferredTooltip } from "@multica/ui/components/common/deferred-tooltip";@@ -10,87 +10,79 @@ import {DropdownMenuTrigger,} from "@multica/ui/components/ui/dropdown-menu";import { useT } from "../../i18n";+import { CLOSED_ROW_MENU, nextRowMenuState, usePointAnchor } from "../../common/point-menu";import { useCollectionRowMenuState, type RowMenuState } from "./row-context";/**- * The row's ⋯ button and its menu. Inside a CollectionList the same menu also- * opens on right-click, anchored at the cursor, so both entry points always- * show identical items.+ * The row's ⋯ button and its menu. Inside a CollectionList (or any row that+ * provides CollectionRowContext) the same menu also opens on right-click,+ * anchored at the cursor, so both entry points always show identical items.+ * `triggerHidden` drops the button for rows that only open it on right-click.*/export function CollectionRowMenu({label,children,contentClassName,triggerClassName,+ triggerHidden = false,+ finalFocus,}: {label?: string;children: ReactNode;contentClassName?: string;triggerClassName?: string;+ triggerHidden?: boolean;+ /** Where focus goes once the menu closes; see Base UI's `finalFocus`. */+ finalFocus?: () => boolean;}) {const { t } = useT("layout");const row = useCollectionRowMenuState();- const [local, setLocal] = useState<RowMenuState>({ open: false, point: null });+ const [local, setLocal] = useState<RowMenuState>(CLOSED_ROW_MENU);const menu = row?.menu ?? local;const setMenu = row?.setMenu ?? setLocal;const name = label ?? t(($) => $.collection.row_actions);const point = menu.point;- const anchor = useMemo(() => {- if (!point) return undefined;- return {- getBoundingClientRect: () => ({- x: point.x,- y: point.y,- top: point.y,- left: point.x,- right: point.x,- bottom: point.y,- width: 0,- height: 0,- toJSON: () => ({}),- }),- };- }, [point]);+ const anchor = usePointAnchor(point);return (<DropdownMenuopen={menu.open}onOpenChange={(open, details) => {- // Base UI treats a menu its trigger did not press open as hover-opened- // and closes it when the pointer leaves the trigger; a right-click menu- // never touched the trigger.- if (!open && point && details.reason === "trigger-hover") return;- setMenu(open ? { open: true, point: null } : { open: false, point });+ const next = nextRowMenuState(menu, open, details.reason);+ if (next) setMenu(next);}}>- <DeferredTooltip- content={name}- trigger={- <DropdownMenuTrigger- render={- <button- type="button"- aria-label={name}- data-collection-row-menu=""- className={cn(- "flex size-6 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity",- "hover:bg-accent hover:text-accent-foreground focus-visible:opacity-100",- "group-hover/row:opacity-100 group-data-menu-open/row:opacity-100",- "data-popup-open:bg-accent data-popup-open:text-accent-foreground data-popup-open:opacity-100",- "[@media(hover:none)]:opacity-100",- triggerClassName,- )}- >- <MoreHorizontal className="size-4" />- </button>- }- />- }- />+ {!triggerHidden && (+ <DeferredTooltip+ content={name}+ trigger={+ <DropdownMenuTrigger+ render={+ <button+ type="button"+ aria-label={name}+ data-collection-row-menu=""+ className={cn(+ "flex size-6 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity",+ "hover:bg-accent hover:text-accent-foreground focus-visible:opacity-100",+ "group-hover/row:opacity-100 group-data-menu-open/row:opacity-100",+ "data-popup-open:bg-accent data-popup-open:text-accent-foreground data-popup-open:opacity-100",+ "[@media(hover:none)]:opacity-100",+ triggerClassName,+ )}+ >+ <MoreHorizontal className="size-4" />+ </button>+ }+ />+ }+ />+ )}<DropdownMenuContentalign={point ? "start" : "end"}anchor={anchor}+ finalFocus={finalFocus}className={cn("w-48", contentClassName)}>{children}diff --git a/packages/views/layout/collection-list/row-context.ts b/packages/views/layout/collection-list/row-context.tsindex 3b60e4b8a9..f6198bff36 100644--- a/packages/views/layout/collection-list/row-context.ts+++ b/packages/views/layout/collection-list/row-context.ts@@ -1,17 +1,18 @@"use client";import { createContext, useContext } from "react";+import type { RowMenuState } from "../../common/point-menu";-export interface RowMenuState {- open: boolean;- point: { x: number; y: number } | null;-}+export type { RowMenuState };export interface RowContextValue {menu: RowMenuState;setMenu: (next: RowMenuState) => void;}+/** Shares one row's menu state between the row's right-click handler and the+ * CollectionRowMenu inside it. CollectionList provides it for its rows;+ * other rows provide it with `useRowMenu`. */export const CollectionRowContext = createContext<RowContextValue | null>(null);export function useCollectionRowMenuState(): RowContextValue | null {diff --git a/packages/views/layout/panel-nav.tsx b/packages/views/layout/panel-nav.tsxindex 4cb5adc940..6a4f8a79aa 100644--- a/packages/views/layout/panel-nav.tsx+++ b/packages/views/layout/panel-nav.tsx@@ -182,6 +182,10 @@ interface PanelLinkProps {trailing?: React.ReactNode;/** Runs before navigation, e.g. to select a list scope the page reads. */onNavigate?: () => void;+ onContextMenu?: React.MouseEventHandler<HTMLAnchorElement>;+ /** Rendered beside the link, inside the row's list item: a right-click menu,+ * which must not nest inside the anchor. */+ menu?: React.ReactNode;className?: string;}@@ -193,6 +197,8 @@ export function PanelLink({description,trailing,onNavigate,+ onContextMenu,+ menu,className,}: PanelLinkProps) {return (@@ -202,6 +208,7 @@ export function PanelLink({newTabTitle={label}aria-current={active ? "page" : undefined}onClick={onNavigate}+ onContextMenu={onContextMenu}{...panelRowAnchor(active)}className={cn(PANEL_ROW_CLASS,@@ -223,6 +230,7 @@ export function PanelLink({)}{trailing}</AppLink>+ {menu}</li>);}diff --git a/packages/views/layout/panels/team-panel.test.tsx b/packages/views/layout/panels/team-panel.test.tsxindex ddf2810389..c87407852a 100644--- a/packages/views/layout/panels/team-panel.test.tsx+++ b/packages/views/layout/panels/team-panel.test.tsx@@ -216,6 +216,19 @@ describe("TeamPanel agent previews", () => {});});+describe("TeamPanel agent menu", () => {+ it("opens the agents page's row menu on right-click", async () => {+ seedAgents(1);+ renderPanel([runtime()]);++ fireEvent.contextMenu(screen.getByText("running agent 1"), { clientX: 20, clientY: 40 });+ const menu = await screen.findByRole("menu");+ expect(+ Array.from(menu.querySelectorAll('[role="menuitem"]'), (el) => el.textContent?.trim()),+ ).toEqual(["Open in new tab", "Settings", "Duplicate"]);+ });+});+describe("TeamPanel runtime badge", () => {it("shows a green online machine count without a total or duplicate providers", () => {renderPanel([diff --git a/packages/views/layout/panels/team-panel.tsx b/packages/views/layout/panels/team-panel.tsxindex 25d95ce416..84c8fd5f5d 100644--- a/packages/views/layout/panels/team-panel.tsx+++ b/packages/views/layout/panels/team-panel.tsx@@ -2,13 +2,16 @@import { useId, useMemo, useState, type ReactNode } from "react";import { useQuery } from "@tanstack/react-query";-import { BarChart3, BookOpenText, Bot, Monitor, Plus, User, UserPlus, Users } from "@multica/ui/icons";+import { ArrowUpRight, BarChart3, BookOpenText, Bot, MessageSquare, Monitor, Plus, User, UserPlus, Users } from "@multica/ui/icons";+import { DropdownMenuItem } from "@multica/ui/components/ui/dropdown-menu";import { cn } from "@multica/ui/lib/utils";import { ActorAvatar } from "@multica/ui/components/common/actor-avatar";import { IconButton } from "@multica/ui/components/common/icon-button";import { agentTaskSnapshotOptions, type AgentPresenceDetail } from "@multica/core/agents";import { useAgentsViewStore } from "@multica/core/agents/stores";import { useAuthStore } from "@multica/core/auth";+import { useChatStore } from "@multica/core/chat";+import { canAssignAgentToIssue } from "@multica/core/permissions";import { issueDetailOptions } from "@multica/core/issues/queries";import { useSidebarTreeStore } from "@multica/core/issues/stores/sidebar-tree-store";import { useCurrentWorkspace, useWorkspacePaths } from "@multica/core/paths";@@ -17,6 +20,10 @@ import { memberListOptions, skillListOptions, squadListOptions } from "@multica/import { resolvePublicFileUrl } from "@multica/core/workspace/avatar-url";import type { Agent, AgentTask } from "@multica/core/types";import { useNavigation } from "../../navigation";+import { isFloatingChatRouteSuppressed } from "../../chat/floating-chat-visibility";+import { AgentRowActions } from "../../agents/components/agent-row-actions";+import { shouldOpenRowMenu, useRowMenu } from "../../common/point-menu";+import { CollectionRowContext } from "../collection-list/row-context";import { availabilityConfig } from "../../agents/presence";import { useT } from "../../i18n";import { buildRuntimeMachines, runtimeMachineCounts } from "../../runtimes/components/runtime-machines";@@ -105,10 +112,98 @@ function AgentAvatar({ agent, detail }: { agent: Agent; detail: AgentPresenceDet}/** "MUL-8317 Redesign the sidebar" for the issue the agent is running, if any. */-function useRunningIssueLabel(wsId: string, task: AgentTask | undefined) {+function useRunningIssue(wsId: string, task: AgentTask | undefined) {const issueId = task?.issue_id ?? "";const { data: issue } = useQuery({ ...issueDetailOptions(wsId, issueId), enabled: !!issueId });- return issue ? `${issue.identifier} ${issue.title}` : null;+ return issue ?? null;+}++/**+ * An agent's row in the status sections. Right-click opens the agents page's+ * row menu at the cursor; it mounts on the first right-click, so idle rows+ * hold no menu.+ */+function AgentPanelLink({+ agent,+ detail,+ active,+ description,+ canManage,+ canChat,+ currentIssue,+}: {+ agent: Agent;+ detail: AgentPresenceDetail | undefined;+ active: boolean;+ description: ReactNode;+ canManage: boolean;+ canChat: boolean;+ /** The issue the agent is working on, when it works on exactly one. */+ currentIssue?: { id: string; identifier: string } | null;+}) {+ const { t } = useT("layout");+ const { t: tChat } = useT("chat");+ const p = useWorkspacePaths();+ const { pathname, push } = useNavigation();+ const rowMenu = useRowMenu();+ const startChat = () => {+ const chat = useChatStore.getState();+ chat.setSelectedAgentId(agent.id);+ chat.setSelectedProjectId(null);+ chat.setActiveSession(null);+ if (chat.floatingChatEnabled && !isFloatingChatRouteSuppressed(pathname, p.chat())) {+ chat.setOpen(true);+ } else {+ push(p.chat());+ }+ };+ const leading =+ canChat || currentIssue ? (+ <>+ {canChat && (+ <DropdownMenuItem onClick={startChat}>+ <MessageSquare className="h-3.5 w-3.5" />+ {tChat(($) => $.empty_state.chat_with_named, { name: agent.name })}+ </DropdownMenuItem>+ )}+ {currentIssue && (+ <DropdownMenuItem onClick={() => push(p.issueDetail(currentIssue.id))}>+ <ArrowUpRight className="h-3.5 w-3.5" />+ {t(($) => $.panels.team.open_issue, { identifier: currentIssue.identifier })}+ </DropdownMenuItem>+ )}+ </>+ ) : undefined;+ const rowMenuContext = useMemo(+ () => ({ menu: rowMenu.menu, setMenu: rowMenu.setMenu }),+ [rowMenu.menu, rowMenu.setMenu],+ );+ return (+ <PanelLink+ href={p.agentDetail(agent.id)}+ label={agent.name}+ active={active}+ icon={<AgentAvatar agent={agent} detail={detail} />}+ description={description}+ onContextMenu={(event) => {+ if (shouldOpenRowMenu(event)) rowMenu.openAtPointer(event);+ }}+ menu={+ rowMenu.menu.point && (+ <CollectionRowContext.Provider value={rowMenuContext}>+ <AgentRowActions+ agent={agent}+ presence={detail}+ canManage={canManage}+ duplicateHref={`${p.newAgentManual()}?duplicate=${encodeURIComponent(agent.id)}`}+ leading={leading}+ triggerHidden+ />+ </CollectionRowContext.Provider>+ )+ }+ />+ );}function WorkingAgentRow({@@ -117,23 +212,29 @@ function WorkingAgentRow({task,wsId,active,+ canManage,+ canChat,}: {agent: Agent;detail: AgentPresenceDetail | undefined;task: AgentTask | undefined;wsId: string;active: boolean;+ canManage: boolean;+ canChat: boolean;}) {const { t } = useT("layout");- const p = useWorkspacePaths();- const issueLabel = useRunningIssueLabel(wsId, task);+ const issue = useRunningIssue(wsId, task);+ const issueLabel = issue ? `${issue.identifier} ${issue.title}` : null;const running = detail?.runningCount ?? 0;return (- <PanelLink- href={p.agentDetail(agent.id)}- label={agent.name}+ <AgentPanelLink+ agent={agent}+ detail={detail}active={active}- icon={<AgentAvatar agent={agent} detail={detail} />}+ canManage={canManage}+ canChat={canChat}+ currentIssue={running === 1 ? issue : null}description={running > 1 || !issueLabel ? t(($) => $.panels.team.running_tasks, { count: running }) : issueLabel}@@ -181,7 +282,11 @@ export function TeamPanel() {const mineCount = userId ? agents.filter((agent) => agent.owner_id === userId).length : 0;const myRole = members.find((member) => member.user_id === userId)?.role;- const canInvite = myRole === "owner" || myRole === "admin";+ const isAdmin = myRole === "owner" || myRole === "admin";+ const canInvite = isAdmin;+ const canManageAgent = (agent: Agent) => isAdmin || (!!userId && agent.owner_id === userId);+ const canChatWith = (agent: Agent) =>+ !agent.archived_at && canAssignAgentToIssue(agent, { userId: userId ?? null, role: myRole ?? null }).allowed;const onAgents = pathname === p.agents();// Member pages live under /members/:id; the list itself is a Settings tab.const membersRoot = p.memberDetail("").replace(/\/$/, "");@@ -220,12 +325,13 @@ export function TeamPanel() {renderAgent={(agent) => {const href = p.agentDetail(agent.id);return (- <PanelLink+ <AgentPanelLinkkey={agent.id}- href={href}- label={agent.name}+ agent={agent}+ detail={byAgent.get(agent.id)}active={isPathWithin(pathname, href)}- icon={<AgentAvatar agent={agent} detail={byAgent.get(agent.id)} />}+ canManage={canManageAgent(agent)}+ canChat={canChatWith(agent)}description={<span className="text-warning">{t(($) => $.panels.team.stuck, { count: byAgent.get(agent.id)?.queuedCount ?? 0 })}@@ -252,6 +358,8 @@ export function TeamPanel() {task={runningTaskByAgent.get(agent.id)}wsId={wsId}active={isPathWithin(pathname, p.agentDetail(agent.id))}+ canManage={canManageAgent(agent)}+ canChat={canChatWith(agent)}/>)}/>diff --git a/packages/views/layout/panels/views-section.tsx b/packages/views/layout/panels/views-section.tsxindex f0b1dcc49c..326ff0d9b2 100644--- a/packages/views/layout/panels/views-section.tsx+++ b/packages/views/layout/panels/views-section.tsx@@ -61,6 +61,7 @@ import { ViewNameInput } from "../../issue-views/view-name-input";import { UnreadViewIcon } from "../../issue-views/unread-view-icon";import { useBuiltinViewNavigation } from "../../issue-views/builtin-views";import { useNavigation } from "../../navigation";+import { shouldOpenRowMenu, useRowMenu } from "../../common/point-menu";import { useT } from "../../i18n";import { PANEL_ROW_CLASS, PanelCount, PanelLink, PanelList, PanelSection, isPathWithin, panelRowAnchor, panelRowStateClass } from "../panel-nav";import { useDragClickGuard } from "../use-drag-click-guard";@@ -257,21 +258,20 @@ function SortableViewRow({ id, children }: { id: string; children: (drag: DragBi}/** "…" on hover, and the same menu on right-click. */+/** A view row's ⋯ menu. A right-click on the row opens it at the cursor. */function RowMenu({label,- open,- onOpenChange,+ state,className,children,}: {label: string;- open: boolean;- onOpenChange: (open: boolean) => void;+ state: ReturnType<typeof useRowMenu>;className?: string;children: React.ReactNode;}) {return (- <DropdownMenu open={open} onOpenChange={onOpenChange}>+ <DropdownMenu open={state.menu.open} onOpenChange={state.onOpenChange}><DropdownMenuTriggerrender={<button@@ -284,7 +284,12 @@ function RowMenu({><MoreHorizontal className="size-3.5" /></DropdownMenuTrigger>- <DropdownMenuContent align="start" side="right" className="w-auto min-w-48">+ <DropdownMenuContent+ align="start"+ side={state.menu.point ? "bottom" : "right"}+ anchor={state.anchor}+ className="w-auto min-w-48"+ >{children}</DropdownMenuContent></DropdownMenu>@@ -322,7 +327,7 @@ function BuiltinViewRow({const p = useWorkspacePaths();const listId = useId();const linkRef = useRef<HTMLAnchorElement>(null);- const [menuOpen, setMenuOpen] = useState(false);+ const rowMenu = useRowMenu();const builtinNav = useBuiltinViewNavigation();const { searchParams } = useNavigation();const myScope = useStore(myIssuesViewStore, (s) => myIssuesScopeFor(NO_SEARCH, s.scope));@@ -374,12 +379,11 @@ function BuiltinViewRow({toggleLabel={t(($) => $.panels.work.project_issues, { name: label })}onPrefetch={prefetch}onContextMenu={(event) => {- event.preventDefault();- setMenuOpen(true);+ if (shouldOpenRowMenu(event)) rowMenu.openAtPointer(event);}}onNavigateInPlace={() => builtinNav.prepare(builtin)}trailing={- <RowMenu label={t(($) => $.panels.work.view_actions, { name: label })} open={menuOpen} onOpenChange={setMenuOpen}>+ <RowMenu label={t(($) => $.panels.work.view_actions, { name: label })} state={rowMenu}><DropdownMenuItem onClick={() => actions.copyLink(href)}><Link2 className="size-3.5" />{t(($) => $.panels.work.view_copy_link)}@@ -434,7 +438,7 @@ function UnreadViewRow({const p = useWorkspacePaths();const listId = useId();const linkRef = useRef<HTMLAnchorElement>(null);- const [menuOpen, setMenuOpen] = useState(false);+ const rowMenu = useRowMenu();const target = issueViewTarget(wsId, UNREAD_VIEW, p);const open = useActiveIssueViewStore((s) => pathname === target.path && s.active[target.containerKey] === UNREAD_VIEW_ID,@@ -468,8 +472,7 @@ function UnreadViewRow({toggleLabel={t(($) => $.panels.work.project_issues, { name: label })}onPrefetch={prefetch}onContextMenu={(event) => {- event.preventDefault();- setMenuOpen(true);+ if (shouldOpenRowMenu(event)) rowMenu.openAtPointer(event);}}onNavigateInPlace={() => setActive(target.containerKey, UNREAD_VIEW_ID)}trailing={@@ -481,8 +484,7 @@ function UnreadViewRow({/><RowMenulabel={t(($) => $.panels.work.view_actions, { name: label })}- open={menuOpen}- onOpenChange={setMenuOpen}+ state={rowMenu}className="absolute right-0"><DropdownMenuItem onClick={() => actions.copyLink(target.href)}>@@ -541,7 +543,7 @@ function SavedViewRow({const { view } = item;const listId = useId();const linkRef = useRef<HTMLAnchorElement>(null);- const [menuOpen, setMenuOpen] = useState(false);+ const rowMenu = useRowMenu();const target = issueViewTarget(wsId, view, p);const active = useActiveIssueViewStore((s) => plainRowsLit && pathname === target.path && s.active[target.containerKey] === view.id,@@ -594,12 +596,11 @@ function SavedViewRow({toggleLabel={t(($) => $.panels.work.project_issues, { name: view.name })}onPrefetch={prefetch}onContextMenu={(event) => {- event.preventDefault();- setMenuOpen(true);+ if (shouldOpenRowMenu(event)) rowMenu.openAtPointer(event);}}onNavigateInPlace={() => setActive(target.containerKey, view.id)}trailing={- <RowMenu label={t(($) => $.panels.work.view_actions, { name: view.name })} open={menuOpen} onOpenChange={setMenuOpen}>+ <RowMenu label={t(($) => $.panels.work.view_actions, { name: view.name })} state={rowMenu}>{canManage && (<><DropdownMenuItem onClick={() => actions.edit(view)}>diff --git a/packages/views/layout/panels/work-tree.test.tsx b/packages/views/layout/panels/work-tree.test.tsxindex f2391f61f5..19ce127a62 100644--- a/packages/views/layout/panels/work-tree.test.tsx+++ b/packages/views/layout/panels/work-tree.test.tsx@@ -42,7 +42,19 @@ vi.mock("@dnd-kit/core", async (importOriginal) => {vi.mock("@multica/core/issue-statuses/hooks", () => ({useIssueStatuses: () => buildIssueStatusCatalog([]),}));+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "ws-1" }));+vi.mock("@multica/core/auth", () => {+ const state = { user: { id: "u1" } };+ return {+ useAuthStore: Object.assign(+ (selector?: (s: typeof state) => unknown) => (selector ? selector(state) : state),+ { getState: () => state },+ ),+ };+});vi.mock("../../navigation", () => ({+ useIntentNavigate: () => vi.fn(),+ useNavigation: () => ({ getShareableUrl: (path: string) => `https://app.example${path}` }),AppLink: ({children,href,@@ -167,6 +179,18 @@ describe("ProjectsSection", () => {expect(openCreateIssue).toHaveBeenCalledWith({ project_id: "p2" });});+ it("opens the project's menu on right-click, led by a new issue in it", async () => {+ renderSection();+ fireEvent.contextMenu(screen.getByText("Mobile"), { clientX: 20, clientY: 40 });++ const menu = await screen.findByRole("menu");+ const items = Array.from(menu.querySelectorAll('[role="menuitem"]'), (el) => el.textContent?.trim());+ expect(items).toEqual(["New issue in this project", "Rename", "Open in new tab", "Pin to sidebar", "Copy link"]);++ fireEvent.click(screen.getByRole("menuitem", { name: "New issue in this project" }));+ expect(openCreateIssue).toHaveBeenCalledWith({ project_id: "p2" });+ });+it("collapses from the section label", () => {renderSection();fireEvent.click(screen.getByRole("button", { name: "Projects" }));diff --git a/packages/views/layout/panels/work-tree.tsx b/packages/views/layout/panels/work-tree.tsxindex 24fc87341c..fd83577964 100644--- a/packages/views/layout/panels/work-tree.tsx+++ b/packages/views/layout/panels/work-tree.tsx@@ -1,6 +1,6 @@"use client";-import { useCallback, useId, useMemo, useRef, useSyncExternalStore } from "react";+import { useCallback, useId, useMemo, useRef, useSyncExternalStore, type MouseEvent } from "react";import { useQueryClient } from "@tanstack/react-query";import { DndContext, PointerSensor, closestCenter, useSensor, useSensors, type DragEndEvent } from "@dnd-kit/core";import { SortableContext, arrayMove, useSortable, verticalListSortingStrategy } from "@dnd-kit/sortable";@@ -9,6 +9,7 @@ import { CSS } from "@dnd-kit/utilities";import { Folder, Plus } from "@multica/ui/icons";import { cn } from "@multica/ui/lib/utils";import { IconButton } from "@multica/ui/components/common/icon-button";+import { DropdownMenuItem } from "@multica/ui/components/ui/dropdown-menu";import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";import { issueKeys, sidebarIssuesOptions } from "@multica/core/issues/queries";import { filterDependencyState, statusCatalogSource } from "@multica/core/issues/surface/filter-dependency";@@ -36,6 +37,9 @@ import {panelRowStateClass,} from "../panel-nav";import { ProjectIcon } from "../../projects/components/project-icon";+import { ProjectMenu } from "../../projects/components/project-row-actions";+import { shouldOpenRowMenu, useRowMenu } from "../../common/point-menu";+import { CollectionRowContext } from "../collection-list/row-context";import { useDragClickGuard } from "../use-drag-click-guard";import { ProjectsSectionSettings } from "./sidebar-settings";import { SidebarIssueList, TreeRow } from "./sidebar-tree";@@ -280,6 +284,13 @@ function ProjectTreeItem({const prefetch = usePrefetch(wsId, source, params);const { listeners, setNodeRef, setActivatorNodeRef, transform, transition, isDragging } = useSortable({ id: project.id });+ // Right-click opens the projects page's row menu at the cursor. It mounts on+ // the first right-click, so idle rows hold no menu or its queries.+ const rowMenu = useRowMenu();+ const rowMenuContext = useMemo(+ () => ({ menu: rowMenu.menu, setMenu: rowMenu.setMenu }),+ [rowMenu.menu, rowMenu.setMenu],+ );return (<li@@ -306,6 +317,9 @@ function ProjectTreeItem({listId={listId}toggleLabel={t(($) => $.panels.work.project_issues, { name: project.title })}onPrefetch={prefetch}+ onContextMenu={(event: MouseEvent) => {+ if (shouldOpenRowMenu(event)) rowMenu.openAtPointer(event);+ }}trailing={// The button takes the count's place on hover, so the row never reflows.<span className="relative flex h-5 min-w-5 items-center justify-end">@@ -327,6 +341,20 @@ function ProjectTreeItem({</span>}/>+ {rowMenu.menu.point && (+ <CollectionRowContext.Provider value={rowMenuContext}>+ <ProjectMenu+ project={project}+ triggerHidden+ leading={+ <DropdownMenuItem onClick={() => openCreateIssueWithPreference({ project_id: project.id })}>+ <Plus />+ {t(($) => $.panels.work.new_issue_here)}+ </DropdownMenuItem>+ }+ />+ </CollectionRowContext.Provider>+ )}{expanded && (<SidebarIssueListid={listId}diff --git a/packages/views/layout/rail-workspaces.tsx b/packages/views/layout/rail-workspaces.tsxindex 8f0c01819c..5ec4af9c67 100644--- a/packages/views/layout/rail-workspaces.tsx+++ b/packages/views/layout/rail-workspaces.tsx@@ -2,7 +2,9 @@import { useMemo, useState, type MouseEvent } from "react";import { useQuery } from "@tanstack/react-query";-import { AppWindow, ArrowBigUp, Check, Mail, Pin, Plus } from "@multica/ui/icons";+import { AppWindow, ArrowBigUp, Check, Link2, Mail, Pin, PinOff, Plus, Settings, UserPlus } from "@multica/ui/icons";+import { toast } from "sonner";+import { copyText } from "@multica/ui/lib/clipboard";import type { api } from "@multica/core/api";import { useConfigStore } from "@multica/core/config";import {@@ -12,7 +14,9 @@ import {} from "@multica/core/inbox/queries";import { paths, useCurrentWorkspace } from "@multica/core/paths";import type { Invitation, Workspace } from "@multica/core/types";+import { useAuthStore } from "@multica/core/auth";import {+ memberListOptions,myInvitationListOptions,workspaceListOptions,} from "@multica/core/workspace/queries";@@ -29,6 +33,7 @@ import {} from "@multica/ui/components/ui/dropdown-menu";import { Kbd, KbdGroup } from "@multica/ui/components/ui/kbd";import { cn } from "@multica/ui/lib/utils";+import { useRowMenu } from "../common/point-menu";import { useT } from "../i18n";import { AppLink, useNavigation } from "../navigation";import { WorkspaceAvatar } from "../workspace/workspace-avatar";@@ -146,108 +151,176 @@ export function RailWorkspaces() {// Read when the menu opens: other windows switch workspaces independently.const [inOtherWindows, setInOtherWindows] = useState(EMPTY_SLUGS);+ // Right-click on the tile opens a menu for the current workspace itself.+ const tileMenu = useRowMenu();+const current = workspaces.find((ws) => ws.id === wsId) ?? workspace;if (!current) return null;const otherUnread = workspaces.some((ws) => ws.id !== wsId && unreadIds.has(ws.id));const label = t(($) => $.rail.switch_workspace);return (- <DropdownMenu- onOpenChange={(open) => {- if (open && workspacesInOtherWindows) {- setInOtherWindows(new Set(workspacesInOtherWindows()));- }- }}- >- <TooltipHint label={current.name} side="right">- <DropdownMenuTrigger- aria-label={label}- className="relative inline-flex size-[34px] shrink-0 cursor-pointer items-center justify-center rounded-lg outline-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring"- >- <WorkspaceAvatar- name={current.name}- avatarUrl={current.avatar_url}- className="h-[34px] w-[34px] rounded-lg border-surface-border bg-surface-raised text-body text-foreground shadow-[var(--surface-shadow)]"- />- {(otherUnread || invitations.length > 0) && (- <UnreadDot className="absolute -top-0.5 -right-0.5 ring-2 ring-app-shell" />- )}- </DropdownMenuTrigger>- </TooltipHint>- <DropdownMenuContent side="right" align="start" sideOffset={10} className="w-64">- <DropdownMenuGroup className="max-h-80 overflow-y-auto">- <DropdownMenuLabel className="text-caption text-muted-foreground">- {t(($) => $.sidebar.workspaces_label)}- </DropdownMenuLabel>- {workspaces.map((ws) => {- const isCurrent = ws.id === wsId;- // A workspace shown by another window is focused there by a- // plain click, so it offers no new window of its own.- const inOtherWindow = !isCurrent && inOtherWindows.has(ws.slug);- const openInNewWindow =- openWorkspaceInNewWindow && !isCurrent && !inOtherWindow- ? () => openWorkspaceInNewWindow(ws.slug)- : null;- return (- <DropdownMenuItem- key={ws.id}- aria-current={isCurrent ? "page" : undefined}- className="group/workspace"- onClick={- openInNewWindow- ? (event: MouseEvent) => {- if (event.defaultPrevented || !isNewWindowClick(event)) return;- event.preventDefault();- openInNewWindow();- }- : undefined- }- render={<AppLink href={paths.workspace(ws.slug).issues()} />}- >- <WorkspaceAvatar name={ws.name} avatarUrl={ws.avatar_url} size="sm" />- <span className="min-w-0 flex-1 truncate">{ws.name}</span>- {isCurrent && <Check />}- <span className="relative flex size-5 shrink-0 items-center justify-center">- <span className="flex group-hover/workspace:opacity-0 group-data-highlighted/workspace:opacity-0">- {ws.pinned_at ? (- <Pin className={cn("size-4 fill-current", !isCurrent && unreadIds.has(ws.id) ? "text-brand" : "text-muted-foreground")} />- ) : !isCurrent && unreadIds.has(ws.id) ? <UnreadDot /> : null}+ <>+ {tileMenu.menu.point && <WorkspaceTileMenu workspace={current} state={tileMenu} />}+ <DropdownMenu+ onOpenChange={(open) => {+ if (open && workspacesInOtherWindows) {+ setInOtherWindows(new Set(workspacesInOtherWindows()));+ }+ }}+ >+ <TooltipHint label={current.name} side="right">+ <DropdownMenuTrigger+ aria-label={label}+ onContextMenu={tileMenu.openAtPointer}+ className="relative inline-flex size-[34px] shrink-0 cursor-pointer items-center justify-center rounded-lg outline-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring"+ >+ <WorkspaceAvatar+ name={current.name}+ avatarUrl={current.avatar_url}+ className="h-[34px] w-[34px] rounded-lg border-surface-border bg-surface-raised text-body text-foreground shadow-[var(--surface-shadow)]"+ />+ {(otherUnread || invitations.length > 0) && (+ <UnreadDot className="absolute -top-0.5 -right-0.5 ring-2 ring-app-shell" />+ )}+ </DropdownMenuTrigger>+ </TooltipHint>+ <DropdownMenuContent side="right" align="start" sideOffset={10} className="w-64">+ <DropdownMenuGroup className="max-h-80 overflow-y-auto">+ <DropdownMenuLabel className="text-caption text-muted-foreground">+ {t(($) => $.sidebar.workspaces_label)}+ </DropdownMenuLabel>+ {workspaces.map((ws) => {+ const isCurrent = ws.id === wsId;+ // A workspace shown by another window is focused there by a+ // plain click, so it offers no new window of its own.+ const inOtherWindow = !isCurrent && inOtherWindows.has(ws.slug);+ const openInNewWindow =+ openWorkspaceInNewWindow && !isCurrent && !inOtherWindow+ ? () => openWorkspaceInNewWindow(ws.slug)+ : null;+ return (+ <DropdownMenuItem+ key={ws.id}+ aria-current={isCurrent ? "page" : undefined}+ className="group/workspace"+ onClick={+ openInNewWindow+ ? (event: MouseEvent) => {+ if (event.defaultPrevented || !isNewWindowClick(event)) return;+ event.preventDefault();+ openInNewWindow();+ }+ : undefined+ }+ render={<AppLink href={paths.workspace(ws.slug).issues()} />}+ >+ <WorkspaceAvatar name={ws.name} avatarUrl={ws.avatar_url} size="sm" />+ <span className="min-w-0 flex-1 truncate">{ws.name}</span>+ {isCurrent && <Check />}+ <span className="relative flex size-5 shrink-0 items-center justify-center">+ <span className="flex group-hover/workspace:opacity-0 group-data-highlighted/workspace:opacity-0">+ {ws.pinned_at ? (+ <Pin className={cn("size-4 fill-current", !isCurrent && unreadIds.has(ws.id) ? "text-brand" : "text-muted-foreground")} />+ ) : !isCurrent && unreadIds.has(ws.id) ? <UnreadDot /> : null}+ </span>+ <PinButton pinned={!!ws.pinned_at} unread={!isCurrent && unreadIds.has(ws.id)} onToggle={() => setPinned.mutate({ workspaceId: ws.id, pinned: !ws.pinned_at })} /></span>- <PinButton pinned={!!ws.pinned_at} unread={!isCurrent && unreadIds.has(ws.id)} onToggle={() => setPinned.mutate({ workspaceId: ws.id, pinned: !ws.pinned_at })} />- </span>- {inOtherWindow && <OtherWindowMarker />}- {openInNewWindow && <NewWindowButton onOpen={openInNewWindow} />}- </DropdownMenuItem>- );- })}- </DropdownMenuGroup>- {invitations.length > 0 && (- <>- <DropdownMenuSeparator />- <DropdownMenuGroup>- <DropdownMenuItem render={<AppLink href={paths.invitations()} />}>- <Mail />- <span className="min-w-0 flex-1 truncate">- {t(($) => $.sidebar.pending_invitations_label)}- </span>- <span className="text-caption text-muted-foreground tabular-nums">- {invitations.length}- </span>- <UnreadDot />- </DropdownMenuItem>- </DropdownMenuGroup>- </>- )}- {!workspaceCreationDisabled && (- <>- <DropdownMenuSeparator />- <DropdownMenuGroup>- <DropdownMenuItem render={<AppLink href={paths.newWorkspace()} />}>- <Plus />- {t(($) => $.sidebar.create_workspace)}- </DropdownMenuItem>- </DropdownMenuGroup>- </>+ {inOtherWindow && <OtherWindowMarker />}+ {openInNewWindow && <NewWindowButton onOpen={openInNewWindow} />}+ </DropdownMenuItem>+ );+ })}+ </DropdownMenuGroup>+ {invitations.length > 0 && (+ <>+ <DropdownMenuSeparator />+ <DropdownMenuGroup>+ <DropdownMenuItem render={<AppLink href={paths.invitations()} />}>+ <Mail />+ <span className="min-w-0 flex-1 truncate">+ {t(($) => $.sidebar.pending_invitations_label)}+ </span>+ <span className="text-caption text-muted-foreground tabular-nums">+ {invitations.length}+ </span>+ <UnreadDot />+ </DropdownMenuItem>+ </DropdownMenuGroup>+ </>+ )}+ {!workspaceCreationDisabled && (+ <>+ <DropdownMenuSeparator />+ <DropdownMenuGroup>+ <DropdownMenuItem render={<AppLink href={paths.newWorkspace()} />}>+ <Plus />+ {t(($) => $.sidebar.create_workspace)}+ </DropdownMenuItem>+ </DropdownMenuGroup>+ </>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ </>+ );+}++function WorkspaceTileMenu({+ workspace,+ state,+}: {+ workspace: Workspace;+ state: ReturnType<typeof useRowMenu>;+}) {+ const { t } = useT("layout");+ const { push, getShareableUrl } = useNavigation();+ const userId = useAuthStore((s) => s.user?.id);+ const { data: members = [] } = useQuery(memberListOptions(workspace.id));+ const role = members.find((member) => member.user_id === userId)?.role;+ const isAdmin = role === "owner" || role === "admin";+ const setPinned = useSetWorkspacePinned();+ const settings = paths.workspace(workspace.slug).settings();+ const pinned = !!workspace.pinned_at;+ const copyLink = async () => {+ if (await copyText(getShareableUrl(paths.workspace(workspace.slug).issues()))) {+ toast.success(t(($) => $.rail.link_copied));+ }+ };++ return (+ <DropdownMenu open={state.menu.open} onOpenChange={state.onOpenChange}>+ <DropdownMenuContent align="start" anchor={state.anchor} className="w-auto min-w-48">+ <div className="flex items-center gap-2 px-2 pt-1 pb-1.5">+ <WorkspaceAvatar name={workspace.name} avatarUrl={workspace.avatar_url} size="sm" />+ <div className="min-w-0">+ <div className="truncate text-body font-medium">{workspace.name}</div>+ <div className="truncate text-caption text-muted-foreground">+ {members.length > 0+ ? t(($) => $.rail.workspace_meta, { slug: workspace.slug, count: members.length })+ : workspace.slug}+ </div>+ </div>+ </div>+ <DropdownMenuSeparator />+ <DropdownMenuItem onClick={() => setPinned.mutate({ workspaceId: workspace.id, pinned: !pinned })}>+ {pinned ? <PinOff /> : <Pin />}+ {pinned ? t(($) => $.rail.unpin_workspace) : t(($) => $.rail.pin_workspace)}+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem onClick={() => void copyLink()}>+ <Link2 />+ {t(($) => $.rail.copy_workspace_link)}+ </DropdownMenuItem>+ <DropdownMenuItem onClick={() => push(settings)}>+ <Settings />+ {t(($) => $.rail.workspace_settings)}+ </DropdownMenuItem>+ {isAdmin && (+ <DropdownMenuItem onClick={() => push(`${settings}?tab=members&invite=1`)}>+ <UserPlus />+ {t(($) => $.panels.team.invite_member)}+ </DropdownMenuItem>)}</DropdownMenuContent></DropdownMenu>diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.jsonindex c62e39b8f0..b6c20bb8e3 100644--- a/packages/views/locales/en/issues.json+++ b/packages/views/locales/en/issues.json@@ -772,7 +772,10 @@"recipient_count_other": "{{count}} agents will receive this","steer_attachment_notice": "Only text can join a running run, so a message with files is handled after it.","restart_send": "Stop and send",- "restart_failed": "Couldn't stop the current run. Your message wasn't sent."+ "restart_failed": "Couldn't stop the current run. Your message wasn't sent.",+ "reply_action": "Reply",+ "actions_label": "Comment actions",+ "create_issue_from_selection": "Create sub-issue from selection"},"reply": {"recipients_changed": "Reply target changed. Review the recipients before sending again.",@@ -996,7 +999,12 @@"delete_dialog_title_other": "Delete {{count}} issues?","delete_dialog_desc_one": "This action cannot be undone. This will permanently delete the selected issue and all associated data.","delete_dialog_desc_other": "This action cannot be undone. This will permanently delete the selected issues and all associated data.",- "cancel": "Cancel"+ "cancel": "Cancel",+ "copy_links": "Copy links",+ "links_copied_one": "Copied {{count}} link",+ "links_copied_other": "Copied {{count}} links",+ "delete_count_one": "Delete {{count}} issue",+ "delete_count_other": "Delete {{count}} issues"},"card": {"update_failed": "Failed to update issue",@@ -1038,7 +1046,8 @@"remove_parent_issue_success": "Removed parent issue","add_sub_issue": "Add sub-issue...","delete_issue": "Delete issue",- "mark_duplicate": "Mark as duplicate..."+ "mark_duplicate": "Mark as duplicate...",+ "open_in_new_window": "Open in new window"},"pickers": {"custom_property": {diff --git a/packages/views/locales/en/layout.json b/packages/views/locales/en/layout.jsonindex 5667ad562d..71b98a0705 100644--- a/packages/views/locales/en/layout.json+++ b/packages/views/locales/en/layout.json@@ -104,7 +104,16 @@"open_in_new_window_click": "Click","open_in_other_window": "Already open in another window","in_other_window": "Other window",- "all_workspaces_open": "Every workspace is already open in a window"+ "all_workspaces_open": "Every workspace is already open in a window",+ "copy_link": "Copy link",+ "link_copied": "Link copied",+ "workspace_settings": "Workspace settings",+ "mark_all_read": "Mark all as read",+ "mark_all_read_failed": "Couldn't mark all as read",+ "reset_order": "Reset to default order",+ "copy_workspace_link": "Copy workspace link",+ "workspace_meta_one": "{{slug}} · {{count}} member",+ "workspace_meta_other": "{{slug}} · {{count}} members"},"bottom_bar": {"label": "Status bar",@@ -153,7 +162,8 @@"view_edit": "Edit view","view_rename": "Rename","view_duplicate": "Duplicate",- "view_delete": "Delete view"+ "view_delete": "Delete view",+ "new_issue_here": "New issue in this project"},"team": {"new_agent": "New agent",@@ -173,7 +183,8 @@"resources": "Resources","runtimes_online_one": "{{count}} online","runtimes_online_other": "{{count}} online",- "invite_member": "Invite member"+ "invite_member": "Invite member",+ "open_issue": "Open {{identifier}}"},"autopilots": {"all": "All autopilots",@@ -229,5 +240,19 @@"go_to_slide": "Go to slide {{index}}","previous": "Previous","next": "Next"+ },+ "context_menu": {+ "cut": "Cut",+ "copy": "Copy",+ "paste": "Paste",+ "select_all": "Select all",+ "add_to_dictionary": "Add to dictionary",+ "open_link": "Open link in browser",+ "copy_link_address": "Copy link address",+ "copy_image": "Copy image",+ "copy_code": "Copy code",+ "copy_table": "Copy table",+ "copied": "Copied",+ "copy_failed": "Couldn't copy"}}diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.jsonindex afd6cdfb5f..488c296bc8 100644--- a/packages/views/locales/en/settings.json+++ b/packages/views/locales/en/settings.json@@ -1409,7 +1409,10 @@"close_others": "Close other tabs","open_window": "Open as new window","new": "New tab",- "pinned_name": "{{title}} (pinned)"+ "pinned_name": "{{title}} (pinned)",+ "copy_link": "Copy link",+ "link_copied": "Link copied",+ "close_right": "Close tabs to the right"},"updates": {"title": "Updates",diff --git a/packages/views/locales/es/issues.json b/packages/views/locales/es/issues.jsonindex 5caa84ce2c..6d161b93de 100644--- a/packages/views/locales/es/issues.json+++ b/packages/views/locales/es/issues.json@@ -755,7 +755,10 @@"recipient_count_other": "{{count}} agentes recibirán esto","steer_attachment_notice": "Solo el texto puede unirse a una ejecución en marcha, así que un mensaje con archivos se procesa después.","restart_send": "Detener y enviar",- "restart_failed": "No se ha podido detener la ejecución actual. Tu mensaje no se envió."+ "restart_failed": "No se ha podido detener la ejecución actual. Tu mensaje no se envió.",+ "reply_action": "Responder",+ "actions_label": "Acciones del comentario",+ "create_issue_from_selection": "Crear subtarea a partir de la selección"},"reply": {"recipients_changed": "El destino de la respuesta ha cambiado. Revisa los destinatarios antes de volver a enviar.",@@ -910,7 +913,12 @@"cancel": "Cancelar","update_partial_one": "Actualizada {{updated}} de {{count}} tarea. El resto no admite este cambio y se quedó como estaba.","update_partial_other": "Actualizadas {{updated}} de {{count}} tareas. El resto no admite este cambio y se quedó como estaba.",- "delete_restricted": "Puedes eliminar las tareas que hayas creado tú o tus agentes. Los usuarios con rol owner o admin del espacio de trabajo pueden eliminar cualquier tarea."+ "delete_restricted": "Puedes eliminar las tareas que hayas creado tú o tus agentes. Los usuarios con rol owner o admin del espacio de trabajo pueden eliminar cualquier tarea.",+ "copy_links": "Copiar enlaces",+ "links_copied_one": "{{count}} enlace copiado",+ "links_copied_other": "{{count}} enlaces copiados",+ "delete_count_one": "Eliminar {{count}} tarea",+ "delete_count_other": "Eliminar {{count}} tareas"},"card": {"update_failed": "No se ha podido actualizar la tarea",@@ -952,7 +960,8 @@"mark_unread": "Marcar como no leído","copy_identifier": "Copiar identificador","identifier_copied": "{{identifier}} copiado",- "stop_agent_run": "Detener la ejecución de {{name}}"+ "stop_agent_run": "Detener la ejecución de {{name}}",+ "open_in_new_window": "Abrir en una ventana nueva"},"pickers": {"custom_property": {diff --git a/packages/views/locales/es/layout.json b/packages/views/locales/es/layout.jsonindex 5bbbc0bb10..ff3ffb46af 100644--- a/packages/views/locales/es/layout.json+++ b/packages/views/locales/es/layout.json@@ -104,7 +104,16 @@"open_in_new_window_click": "Clic","open_in_other_window": "Ya está abierto en otra ventana","in_other_window": "Otra ventana",- "all_workspaces_open": "Todos los espacios de trabajo ya están abiertos en una ventana"+ "all_workspaces_open": "Todos los espacios de trabajo ya están abiertos en una ventana",+ "copy_link": "Copiar enlace",+ "link_copied": "Enlace copiado",+ "workspace_settings": "Ajustes del espacio de trabajo",+ "mark_all_read": "Marcar todo como leído",+ "mark_all_read_failed": "No se pudo marcar todo como leído",+ "reset_order": "Restablecer el orden predeterminado",+ "copy_workspace_link": "Copiar enlace del espacio de trabajo",+ "workspace_meta_one": "{{slug}} · {{count}} miembro",+ "workspace_meta_other": "{{slug}} · {{count}} miembros"},"bottom_bar": {"label": "Barra de estado",@@ -153,7 +162,8 @@"view_edit": "Editar vista","view_rename": "Renombrar","view_duplicate": "Duplicar",- "view_delete": "Eliminar vista"+ "view_delete": "Eliminar vista",+ "new_issue_here": "Nueva tarea en este proyecto"},"team": {"new_agent": "Nuevo agente",@@ -173,7 +183,8 @@"resources": "Recursos","runtimes_online_one": "{{count}} en línea","runtimes_online_other": "{{count}} en línea",- "invite_member": "Invitar miembro"+ "invite_member": "Invitar miembro",+ "open_issue": "Abrir {{identifier}}"},"autopilots": {"all": "Todas las automatizaciones",@@ -229,5 +240,19 @@"go_to_slide": "Ir a la diapositiva {{index}}","previous": "Anterior","next": "Siguiente"+ },+ "context_menu": {+ "cut": "Cortar",+ "copy": "Copiar",+ "paste": "Pegar",+ "select_all": "Seleccionar todo",+ "add_to_dictionary": "Añadir al diccionario",+ "open_link": "Abrir enlace en el navegador",+ "copy_link_address": "Copiar dirección del enlace",+ "copy_image": "Copiar imagen",+ "copy_code": "Copiar código",+ "copy_table": "Copiar tabla",+ "copied": "Copiado",+ "copy_failed": "No se pudo copiar"}}diff --git a/packages/views/locales/es/settings.json b/packages/views/locales/es/settings.jsonindex 84f531102e..62d0fcb5d7 100644--- a/packages/views/locales/es/settings.json+++ b/packages/views/locales/es/settings.json@@ -1409,7 +1409,10 @@"close_others": "Cerrar las demás pestañas","open_window": "Abrir en ventana nueva","new": "Pestaña nueva",- "pinned_name": "{{title}} (fijada)"+ "pinned_name": "{{title}} (fijada)",+ "copy_link": "Copiar enlace",+ "link_copied": "Enlace copiado",+ "close_right": "Cerrar las pestañas a la derecha"},"updates": {"title": "Actualizaciones",diff --git a/packages/views/locales/fr/issues.json b/packages/views/locales/fr/issues.jsonindex 54e39d34fc..1fe9448823 100644--- a/packages/views/locales/fr/issues.json+++ b/packages/views/locales/fr/issues.json@@ -772,7 +772,10 @@"recipient_count_other": "{{count}} agents recevront ce message","steer_attachment_notice": "Seul du texte peut rejoindre une exécution en cours : un message avec des fichiers sera traité après.","restart_send": "Arrêter et envoyer",- "restart_failed": "Impossible d'arrêter l'exécution en cours. Votre message n'a pas été envoyé."+ "restart_failed": "Impossible d'arrêter l'exécution en cours. Votre message n'a pas été envoyé.",+ "reply_action": "Répondre",+ "actions_label": "Actions du commentaire",+ "create_issue_from_selection": "Créer une sous-tâche à partir de la sélection"},"reply": {"recipients_changed": "La cible de la réponse a changé. Vérifiez les destinataires avant de réessayer.",@@ -996,7 +999,12 @@"delete_dialog_title_other": "Supprimer {{count}} tâches ?","delete_dialog_desc_one": "Cette action est irréversible. La tâche sélectionnée et toutes ses données associées seront définitivement supprimées.","delete_dialog_desc_other": "Cette action est irréversible. Les tâches sélectionnées et toutes leurs données associées seront définitivement supprimées.",- "cancel": "Annuler"+ "cancel": "Annuler",+ "copy_links": "Copier les liens",+ "links_copied_one": "{{count}} lien copié",+ "links_copied_other": "{{count}} liens copiés",+ "delete_count_one": "Supprimer {{count}} tâche",+ "delete_count_other": "Supprimer {{count}} tâches"},"card": {"update_failed": "Échec de la mise à jour de la tâche",@@ -1038,7 +1046,8 @@"remove_parent_issue_success": "Tâche parente retirée","add_sub_issue": "Ajouter une sous-tâche...","delete_issue": "Supprimer la tâche",- "mark_duplicate": "Marquer comme doublon..."+ "mark_duplicate": "Marquer comme doublon...",+ "open_in_new_window": "Ouvrir dans une nouvelle fenêtre"},"pickers": {"custom_property": {diff --git a/packages/views/locales/fr/layout.json b/packages/views/locales/fr/layout.jsonindex f3ce4f5f27..5c1f64ce56 100644--- a/packages/views/locales/fr/layout.json+++ b/packages/views/locales/fr/layout.json@@ -104,7 +104,16 @@"open_in_new_window_click": "Clic","open_in_other_window": "Déjà ouvert dans une autre fenêtre","in_other_window": "Autre fenêtre",- "all_workspaces_open": "Chaque espace de travail est déjà ouvert dans une fenêtre"+ "all_workspaces_open": "Chaque espace de travail est déjà ouvert dans une fenêtre",+ "copy_link": "Copier le lien",+ "link_copied": "Lien copié",+ "workspace_settings": "Paramètres de l’espace de travail",+ "mark_all_read": "Tout marquer comme lu",+ "mark_all_read_failed": "Impossible de tout marquer comme lu",+ "reset_order": "Rétablir l’ordre par défaut",+ "copy_workspace_link": "Copier le lien de l’espace de travail",+ "workspace_meta_one": "{{slug}} · {{count}} membre",+ "workspace_meta_other": "{{slug}} · {{count}} membres"},"bottom_bar": {"label": "Barre d'état",@@ -153,7 +162,8 @@"view_edit": "Modifier la vue","view_rename": "Renommer","view_duplicate": "Dupliquer",- "view_delete": "Supprimer la vue"+ "view_delete": "Supprimer la vue",+ "new_issue_here": "Nouvelle tâche dans ce projet"},"team": {"new_agent": "Nouvel agent",@@ -173,7 +183,8 @@"resources": "Ressources","runtimes_online_one": "{{count}} en ligne","runtimes_online_other": "{{count}} en ligne",- "invite_member": "Inviter un membre"+ "invite_member": "Inviter un membre",+ "open_issue": "Ouvrir {{identifier}}"},"autopilots": {"all": "Toutes les automatisations",@@ -229,5 +240,19 @@"go_to_slide": "Aller à la diapositive {{index}}","previous": "Précédent","next": "Suivant"+ },+ "context_menu": {+ "cut": "Couper",+ "copy": "Copier",+ "paste": "Coller",+ "select_all": "Tout sélectionner",+ "add_to_dictionary": "Ajouter au dictionnaire",+ "open_link": "Ouvrir le lien dans le navigateur",+ "copy_link_address": "Copier l’adresse du lien",+ "copy_image": "Copier l’image",+ "copy_code": "Copier le code",+ "copy_table": "Copier le tableau",+ "copied": "Copié",+ "copy_failed": "Impossible de copier"}}diff --git a/packages/views/locales/fr/settings.json b/packages/views/locales/fr/settings.jsonindex d2c63c3bd9..c97f195e89 100644--- a/packages/views/locales/fr/settings.json+++ b/packages/views/locales/fr/settings.json@@ -1409,7 +1409,10 @@"close_others": "Fermer les autres onglets","open_window": "Ouvrir dans une nouvelle fenêtre","new": "Nouvel onglet",- "pinned_name": "{{title}} (épinglé)"+ "pinned_name": "{{title}} (épinglé)",+ "copy_link": "Copier le lien",+ "link_copied": "Lien copié",+ "close_right": "Fermer les onglets à droite"},"updates": {"title": "Mises à jour",diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.jsonindex 9f1a57a10c..d544170b3f 100644--- a/packages/views/locales/ja/issues.json+++ b/packages/views/locales/ja/issues.json@@ -748,7 +748,10 @@"recipient_count_other": "{{count}} 個のエージェントが受け取ります","steer_attachment_notice": "実行中に追加できるのはテキストのみのため、ファイル付きのメッセージはこの実行の後に処理されます。","restart_send": "停止して送信",- "restart_failed": "現在の実行を停止できませんでした。メッセージは送信されていません。"+ "restart_failed": "現在の実行を停止できませんでした。メッセージは送信されていません。",+ "reply_action": "返信",+ "actions_label": "コメントの操作",+ "create_issue_from_selection": "選択内容からサブタスクを作成"},"reply": {"recipients_changed": "返信先が変更されました。送信先を確認してから、もう一度送信してください。",@@ -949,7 +952,10 @@"delete_failed": "タスクを削除できませんでした","delete_dialog_title_other": "タスク {{count}} 件を削除しますか?","delete_dialog_desc_other": "この操作は元に戻せません。選択したタスクと関連データがすべて完全に削除されます。",- "cancel": "キャンセル"+ "cancel": "キャンセル",+ "copy_links": "リンクをコピー",+ "links_copied_other": "{{count}} 件のリンクをコピーしました",+ "delete_count_other": "タスク {{count}} 件を削除"},"card": {"update_failed": "タスクを更新できませんでした",@@ -991,7 +997,8 @@"remove_parent_issue_success": "親タスクを解除しました","add_sub_issue": "サブタスクを追加...","delete_issue": "タスクを削除",- "mark_duplicate": "重複としてマーク..."+ "mark_duplicate": "重複としてマーク...",+ "open_in_new_window": "新しいウィンドウで開く"},"pickers": {"custom_property": {diff --git a/packages/views/locales/ja/layout.json b/packages/views/locales/ja/layout.jsonindex 4af51e7762..401879f42f 100644--- a/packages/views/locales/ja/layout.json+++ b/packages/views/locales/ja/layout.json@@ -103,7 +103,15 @@"open_in_new_window_click": "クリック","open_in_other_window": "別のウィンドウで開いています","in_other_window": "別ウィンドウ",- "all_workspaces_open": "すべてのワークスペースがすでにウィンドウで開いています"+ "all_workspaces_open": "すべてのワークスペースがすでにウィンドウで開いています",+ "copy_link": "リンクをコピー",+ "link_copied": "リンクをコピーしました",+ "workspace_settings": "ワークスペース設定",+ "mark_all_read": "すべて既読にする",+ "mark_all_read_failed": "すべて既読にできませんでした",+ "reset_order": "デフォルトの順序に戻す",+ "copy_workspace_link": "ワークスペースのリンクをコピー",+ "workspace_meta_other": "{{slug}} · メンバー {{count}} 人"},"bottom_bar": {"label": "ステータスバー",@@ -150,7 +158,8 @@"view_edit": "ビューを編集","view_rename": "名前を変更","view_duplicate": "複製",- "view_delete": "ビューを削除"+ "view_delete": "ビューを削除",+ "new_issue_here": "このプロジェクトに新規タスク"},"team": {"new_agent": "新規エージェント",@@ -166,7 +175,8 @@"members_other": "メンバー {{count}} 人","resources": "リソース","runtimes_online_other": "{{count}} 台オンライン",- "invite_member": "メンバーを招待"+ "invite_member": "メンバーを招待",+ "open_issue": "{{identifier}} を開く"},"autopilots": {"all": "すべてのオートパイロット",@@ -220,5 +230,19 @@"go_to_slide": "{{index}} 枚目に移動","previous": "前へ","next": "次へ"+ },+ "context_menu": {+ "cut": "切り取り",+ "copy": "コピー",+ "paste": "貼り付け",+ "select_all": "すべて選択",+ "add_to_dictionary": "辞書に追加",+ "open_link": "ブラウザでリンクを開く",+ "copy_link_address": "リンクのアドレスをコピー",+ "copy_image": "画像をコピー",+ "copy_code": "コードをコピー",+ "copy_table": "表をコピー",+ "copied": "コピーしました",+ "copy_failed": "コピーできませんでした"}}diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.jsonindex d7d46c68ea..a8c94f62a3 100644--- a/packages/views/locales/ja/settings.json+++ b/packages/views/locales/ja/settings.json@@ -1398,7 +1398,10 @@"close_others": "他のタブを閉じる","open_window": "新しいウィンドウで開く","new": "新しいタブ",- "pinned_name": "{{title}}(ピン留め)"+ "pinned_name": "{{title}}(ピン留め)",+ "copy_link": "リンクをコピー",+ "link_copied": "リンクをコピーしました",+ "close_right": "右側のタブを閉じる"},"updates": {"title": "アップデート",diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.jsonindex b1811b59f3..003ef31493 100644--- a/packages/views/locales/ko/issues.json+++ b/packages/views/locales/ko/issues.json@@ -748,7 +748,10 @@"recipient_count_other": "에이전트 {{count}}개가 받습니다","steer_attachment_notice": "실행 중에는 텍스트만 추가할 수 있어, 파일이 있는 메시지는 이번 실행 후에 처리됩니다.","restart_send": "중지하고 보내기",- "restart_failed": "현재 실행을 중지하지 못했습니다. 메시지는 보내지 않았습니다."+ "restart_failed": "현재 실행을 중지하지 못했습니다. 메시지는 보내지 않았습니다.",+ "reply_action": "답글 달기",+ "actions_label": "댓글 작업",+ "create_issue_from_selection": "선택한 내용으로 하위 태스크 만들기"},"reply": {"recipients_changed": "답글 대상이 변경되었습니다. 받는 사람을 확인한 뒤 다시 보내 주세요.",@@ -949,7 +952,10 @@"delete_failed": "태스크를 삭제하지 못했습니다","delete_dialog_title_other": "태스크 {{count}}개를 삭제할까요?","delete_dialog_desc_other": "이 작업은 되돌릴 수 없습니다. 선택한 태스크와 관련 데이터가 영구 삭제됩니다.",- "cancel": "취소"+ "cancel": "취소",+ "copy_links": "링크 복사",+ "links_copied_other": "링크 {{count}}개를 복사했습니다",+ "delete_count_other": "태스크 {{count}}개 삭제"},"card": {"update_failed": "태스크를 업데이트하지 못했습니다",@@ -991,7 +997,8 @@"remove_parent_issue_success": "상위 태스크를 제거했습니다","add_sub_issue": "하위 태스크 추가...","delete_issue": "태스크 삭제",- "mark_duplicate": "중복으로 표시..."+ "mark_duplicate": "중복으로 표시...",+ "open_in_new_window": "새 창에서 열기"},"pickers": {"custom_property": {diff --git a/packages/views/locales/ko/layout.json b/packages/views/locales/ko/layout.jsonindex 2a8dbda452..816d1b99e9 100644--- a/packages/views/locales/ko/layout.json+++ b/packages/views/locales/ko/layout.json@@ -103,7 +103,15 @@"open_in_new_window_click": "클릭","open_in_other_window": "다른 창에서 열려 있음","in_other_window": "다른 창",- "all_workspaces_open": "모든 워크스페이스가 이미 창에 열려 있습니다"+ "all_workspaces_open": "모든 워크스페이스가 이미 창에 열려 있습니다",+ "copy_link": "링크 복사",+ "link_copied": "링크를 복사했습니다",+ "workspace_settings": "작업 공간 설정",+ "mark_all_read": "모두 읽음으로 표시",+ "mark_all_read_failed": "모두 읽음으로 표시하지 못했습니다",+ "reset_order": "기본 순서로 재설정",+ "copy_workspace_link": "작업 공간 링크 복사",+ "workspace_meta_other": "{{slug}} · 멤버 {{count}}명"},"bottom_bar": {"label": "상태 표시줄",@@ -150,7 +158,8 @@"view_edit": "뷰 편집","view_rename": "이름 변경","view_duplicate": "복제",- "view_delete": "뷰 삭제"+ "view_delete": "뷰 삭제",+ "new_issue_here": "이 프로젝트에 새 태스크"},"team": {"new_agent": "새 에이전트",@@ -166,7 +175,8 @@"members_other": "멤버 {{count}}명","resources": "리소스","runtimes_online_other": "{{count}}대 온라인",- "invite_member": "멤버 초대"+ "invite_member": "멤버 초대",+ "open_issue": "{{identifier}} 열기"},"autopilots": {"all": "전체 오토파일럿",@@ -220,5 +230,19 @@"go_to_slide": "{{index}}번째 슬라이드로 이동","previous": "이전","next": "다음"+ },+ "context_menu": {+ "cut": "잘라내기",+ "copy": "복사",+ "paste": "붙여넣기",+ "select_all": "모두 선택",+ "add_to_dictionary": "사전에 추가",+ "open_link": "브라우저에서 링크 열기",+ "copy_link_address": "링크 주소 복사",+ "copy_image": "이미지 복사",+ "copy_code": "코드 복사",+ "copy_table": "표 복사",+ "copied": "복사했습니다",+ "copy_failed": "복사하지 못했습니다"}}diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.jsonindex b751032fcf..fabe24c037 100644--- a/packages/views/locales/ko/settings.json+++ b/packages/views/locales/ko/settings.json@@ -1141,7 +1141,10 @@"close_others": "다른 탭 닫기","open_window": "새 창에서 열기","new": "새 탭",- "pinned_name": "{{title}} (고정됨)"+ "pinned_name": "{{title}} (고정됨)",+ "copy_link": "링크 복사",+ "link_copied": "링크를 복사했습니다",+ "close_right": "오른쪽 탭 닫기"},"updates": {"title": "업데이트",diff --git a/packages/views/locales/ru/issues.json b/packages/views/locales/ru/issues.jsonindex 556f748e44..2c1fa31e73 100644--- a/packages/views/locales/ru/issues.json+++ b/packages/views/locales/ru/issues.json@@ -819,7 +819,10 @@"trigger_will_start_count_few": "{{count}} агента запустятся при отправке","trigger_will_start_count_many": "{{count}} агентов запустится при отправке","recipient_count_few": "{{count}} агента получат это",- "recipient_count_many": "{{count}} агентов получат это"+ "recipient_count_many": "{{count}} агентов получат это",+ "reply_action": "Ответить",+ "actions_label": "Действия с комментарием",+ "create_issue_from_selection": "Создать подзадачу из выделенного"},"reply": {"recipients_changed": "Адресат ответа изменился. Проверьте получателей перед повторной отправкой.",@@ -1089,7 +1092,16 @@"delete_dialog_title_many": "Удалить задачи ({{count}})?","delete_dialog_desc_few": "Это действие нельзя отменить. Выбранные задачи и все связанные с ними данные будут удалены без возможности восстановления.","delete_dialog_desc_many": "Это действие нельзя отменить. Выбранные задачи и все связанные с ними данные будут удалены без возможности восстановления.",- "delete_restricted": "Вы можете удалять задачи, созданные вами или вашими агентами. Владельцы и администраторы рабочего пространства могут удалять любые задачи."+ "delete_restricted": "Вы можете удалять задачи, созданные вами или вашими агентами. Владельцы и администраторы рабочего пространства могут удалять любые задачи.",+ "copy_links": "Копировать ссылки",+ "links_copied_one": "Скопирована {{count}} ссылка",+ "links_copied_few": "Скопировано {{count}} ссылки",+ "links_copied_many": "Скопировано {{count}} ссылок",+ "links_copied_other": "Скопировано {{count}} ссылки",+ "delete_count_one": "Удалить {{count}} задачу",+ "delete_count_few": "Удалить {{count}} задачи",+ "delete_count_many": "Удалить {{count}} задач",+ "delete_count_other": "Удалить {{count}} задачи"},"card": {"update_failed": "Не удалось обновить задачу",@@ -1131,7 +1143,8 @@"delete_issue": "Удалить задачу","mark_duplicate": "Отметить как дубликат...","locate_in_sidebar": "Показать на боковой панели",- "restore_to_inbox": "Вернуть во входящие"+ "restore_to_inbox": "Вернуть во входящие",+ "open_in_new_window": "Открыть в новом окне"},"pickers": {"custom_property": {diff --git a/packages/views/locales/ru/layout.json b/packages/views/locales/ru/layout.jsonindex a6f5aca38a..cdb6e03946 100644--- a/packages/views/locales/ru/layout.json+++ b/packages/views/locales/ru/layout.json@@ -80,7 +80,18 @@"in_other_window": "Другое окно","all_workspaces_open": "Все рабочие пространства уже открыты в окнах","pin_workspace": "Закрепить рабочее пространство",- "unpin_workspace": "Открепить рабочее пространство"+ "unpin_workspace": "Открепить рабочее пространство",+ "copy_link": "Копировать ссылку",+ "link_copied": "Ссылка скопирована",+ "workspace_settings": "Настройки рабочего пространства",+ "mark_all_read": "Отметить все как прочитанные",+ "mark_all_read_failed": "Не удалось отметить все как прочитанные",+ "reset_order": "Вернуть порядок по умолчанию",+ "copy_workspace_link": "Копировать ссылку на рабочее пространство",+ "workspace_meta_one": "{{slug}} · {{count}} участник",+ "workspace_meta_few": "{{slug}} · {{count}} участника",+ "workspace_meta_many": "{{slug}} · {{count}} участников",+ "workspace_meta_other": "{{slug}} · {{count}} участника"},"bottom_bar": {"label": "Строка состояния",@@ -133,7 +144,8 @@"all_projects_few": "Всего {{count}} проекта","all_projects_many": "Всего {{count}} проектов","project_issues_retry": "Повторить",- "unread": "Непрочитанные"+ "unread": "Непрочитанные",+ "new_issue_here": "Новая задача в этом проекте"},"team": {"new_agent": "Новый агент",@@ -161,7 +173,8 @@"runtimes_online_many": "В сети: {{count}}","runtimes_online_other": "В сети: {{count}}","show_fewer_agents": "Показать меньше",- "show_more_agents": "Ещё {{count}}…"+ "show_more_agents": "Ещё {{count}}…",+ "open_issue": "Открыть {{identifier}}"},"autopilots": {"all": "Все автопилоты",@@ -247,5 +260,19 @@"star_label": "Поставить звезду Multica на GitHub","later": "Не сейчас","close": "Закрыть"+ },+ "context_menu": {+ "cut": "Вырезать",+ "copy": "Копировать",+ "paste": "Вставить",+ "select_all": "Выделить всё",+ "add_to_dictionary": "Добавить в словарь",+ "open_link": "Открыть ссылку в браузере",+ "copy_link_address": "Копировать адрес ссылки",+ "copy_image": "Копировать изображение",+ "copy_code": "Копировать код",+ "copy_table": "Копировать таблицу",+ "copied": "Скопировано",+ "copy_failed": "Не удалось скопировать"}}diff --git a/packages/views/locales/ru/settings.json b/packages/views/locales/ru/settings.jsonindex 9ee1d39e3a..97897c9844 100644--- a/packages/views/locales/ru/settings.json+++ b/packages/views/locales/ru/settings.json@@ -1430,7 +1430,10 @@"close_others": "Закрыть другие вкладки","open_window": "Открыть в новом окне","new": "Новая вкладка",- "pinned_name": "{{title}} (закреплено)"+ "pinned_name": "{{title}} (закреплено)",+ "copy_link": "Копировать ссылку",+ "link_copied": "Ссылка скопирована",+ "close_right": "Закрыть вкладки справа"},"updates": {"title": "Обновления",diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.jsonindex d9068c473d..3eb3ac5cff 100644--- a/packages/views/locales/zh-Hans/issues.json+++ b/packages/views/locales/zh-Hans/issues.json@@ -748,7 +748,10 @@"recipient_count_other": "{{count}} 个智能体会收到","steer_attachment_notice": "插话只支持文字,带附件的消息会在本轮结束后处理。","restart_send": "停止并发送",- "restart_failed": "没能停止当前运行,消息还没有发送。"+ "restart_failed": "没能停止当前运行,消息还没有发送。",+ "reply_action": "回复",+ "actions_label": "评论操作",+ "create_issue_from_selection": "用选中内容创建子任务"},"reply": {"recipients_changed": "回复目标已变化。请重新确认接收者后再发送。",@@ -949,7 +952,10 @@"delete_failed": "删除任务失败","delete_dialog_title_other": "删除 {{count}} 个任务?","delete_dialog_desc_other": "此操作无法撤销,所选任务及其全部关联数据都会被永久删除。",- "cancel": "取消"+ "cancel": "取消",+ "copy_links": "复制链接",+ "links_copied_other": "已复制 {{count}} 个链接",+ "delete_count_other": "删除 {{count}} 个任务"},"card": {"update_failed": "更新任务失败",@@ -991,7 +997,8 @@"remove_parent_issue_success": "已移除父任务","add_sub_issue": "添加子任务...","delete_issue": "删除任务",- "mark_duplicate": "标记为重复..."+ "mark_duplicate": "标记为重复...",+ "open_in_new_window": "在新窗口中打开"},"pickers": {"custom_property": {diff --git a/packages/views/locales/zh-Hans/layout.json b/packages/views/locales/zh-Hans/layout.jsonindex 528e15511b..87e753a412 100644--- a/packages/views/locales/zh-Hans/layout.json+++ b/packages/views/locales/zh-Hans/layout.json@@ -103,7 +103,15 @@"open_in_new_window_click": "点击","open_in_other_window": "已在其他窗口打开","in_other_window": "其他窗口",- "all_workspaces_open": "所有工作区都已在窗口中打开"+ "all_workspaces_open": "所有工作区都已在窗口中打开",+ "copy_link": "复制链接",+ "link_copied": "链接已复制",+ "workspace_settings": "工作区设置",+ "mark_all_read": "全部标为已读",+ "mark_all_read_failed": "全部标为已读失败",+ "reset_order": "恢复默认顺序",+ "copy_workspace_link": "复制工作区链接",+ "workspace_meta_other": "{{slug}} · {{count}} 位成员"},"bottom_bar": {"label": "状态栏",@@ -150,7 +158,8 @@"view_edit": "编辑视图","view_rename": "重命名","view_duplicate": "创建副本",- "view_delete": "删除视图"+ "view_delete": "删除视图",+ "new_issue_here": "在此项目中新建任务"},"team": {"new_agent": "新建智能体",@@ -166,7 +175,8 @@"members_other": "{{count}} 位成员","resources": "资源","runtimes_online_other": "{{count}} 台在线",- "invite_member": "邀请成员"+ "invite_member": "邀请成员",+ "open_issue": "打开 {{identifier}}"},"autopilots": {"all": "全部自动化",@@ -220,5 +230,19 @@"go_to_slide": "转到第 {{index}} 张","previous": "上一张","next": "下一张"+ },+ "context_menu": {+ "cut": "剪切",+ "copy": "复制",+ "paste": "粘贴",+ "select_all": "全选",+ "add_to_dictionary": "添加到词典",+ "open_link": "在浏览器中打开链接",+ "copy_link_address": "复制链接地址",+ "copy_image": "复制图片",+ "copy_code": "复制代码",+ "copy_table": "复制表格",+ "copied": "已复制",+ "copy_failed": "复制失败"}}diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.jsonindex d297f8cdb9..416ea3edcc 100644--- a/packages/views/locales/zh-Hans/settings.json+++ b/packages/views/locales/zh-Hans/settings.json@@ -1398,7 +1398,10 @@"close_others": "关闭其他标签页","open_window": "在新窗口打开","new": "新建标签页",- "pinned_name": "{{title}}(已固定)"+ "pinned_name": "{{title}}(已固定)",+ "copy_link": "复制链接",+ "link_copied": "已复制链接",+ "close_right": "关闭右侧标签页"},"updates": {"title": "更新",diff --git a/packages/views/locales/zh-Hant/issues.json b/packages/views/locales/zh-Hant/issues.jsonindex 0ed171f732..adb65eeeec 100644--- a/packages/views/locales/zh-Hant/issues.json+++ b/packages/views/locales/zh-Hant/issues.json@@ -748,7 +748,10 @@"recipient_count_other": "{{count}} 個 AI 代理會收到","steer_attachment_notice": "插話只支援文字,帶附件的訊息會在本輪結束後處理。","restart_send": "停止併傳送",- "restart_failed": "沒能停止當前執行,訊息還沒有傳送。"+ "restart_failed": "沒能停止當前執行,訊息還沒有傳送。",+ "reply_action": "回覆",+ "actions_label": "評論操作",+ "create_issue_from_selection": "用選取內容建立子任務"},"reply": {"recipients_changed": "回覆目標已變更。請重新確認收件者後再傳送。",@@ -949,7 +952,10 @@"delete_failed": "刪除任務失敗","delete_dialog_title_other": "刪除 {{count}} 個任務?","delete_dialog_desc_other": "此操作無法撤銷,所選任務及其全部關聯資料都會被永久刪除。",- "cancel": "取消"+ "cancel": "取消",+ "copy_links": "複製連結",+ "links_copied_other": "已複製 {{count}} 個連結",+ "delete_count_other": "刪除 {{count}} 個任務"},"card": {"update_failed": "更新任務失敗",@@ -991,7 +997,8 @@"remove_parent_issue_success": "已移除父任務","add_sub_issue": "新增子任務...","delete_issue": "刪除任務",- "mark_duplicate": "標記為重複..."+ "mark_duplicate": "標記為重複...",+ "open_in_new_window": "在新視窗中開啟"},"pickers": {"custom_property": {diff --git a/packages/views/locales/zh-Hant/layout.json b/packages/views/locales/zh-Hant/layout.jsonindex 9dc4d0b83e..e45ebda8a4 100644--- a/packages/views/locales/zh-Hant/layout.json+++ b/packages/views/locales/zh-Hant/layout.json@@ -103,7 +103,15 @@"open_in_new_window_click": "點擊","open_in_other_window": "已在其他視窗開啟","in_other_window": "其他視窗",- "all_workspaces_open": "所有工作區都已在視窗中開啟"+ "all_workspaces_open": "所有工作區都已在視窗中開啟",+ "copy_link": "複製連結",+ "link_copied": "已複製連結",+ "workspace_settings": "工作區設定",+ "mark_all_read": "全部標為已讀",+ "mark_all_read_failed": "全部標為已讀失敗",+ "reset_order": "恢復預設順序",+ "copy_workspace_link": "複製工作區連結",+ "workspace_meta_other": "{{slug}} · {{count}} 位成員"},"bottom_bar": {"label": "狀態列",@@ -150,7 +158,8 @@"view_edit": "編輯檢視","view_rename": "重新命名","view_duplicate": "建立副本",- "view_delete": "刪除檢視"+ "view_delete": "刪除檢視",+ "new_issue_here": "在此專案中新建任務"},"team": {"new_agent": "新建 AI 代理",@@ -166,7 +175,8 @@"members_other": "{{count}} 位成員","resources": "資源","runtimes_online_other": "{{count}} 台線上",- "invite_member": "邀請成員"+ "invite_member": "邀請成員",+ "open_issue": "開啟 {{identifier}}"},"autopilots": {"all": "全部自動化",@@ -220,5 +230,19 @@"go_to_slide": "前往第 {{index}} 張","previous": "上一張","next": "下一張"+ },+ "context_menu": {+ "cut": "剪下",+ "copy": "複製",+ "paste": "貼上",+ "select_all": "全選",+ "add_to_dictionary": "加入字典",+ "open_link": "在瀏覽器中開啟連結",+ "copy_link_address": "複製連結網址",+ "copy_image": "複製圖片",+ "copy_code": "複製程式碼",+ "copy_table": "複製表格",+ "copied": "已複製",+ "copy_failed": "複製失敗"}}diff --git a/packages/views/locales/zh-Hant/settings.json b/packages/views/locales/zh-Hant/settings.jsonindex 51c03221ee..97c48f2036 100644--- a/packages/views/locales/zh-Hant/settings.json+++ b/packages/views/locales/zh-Hant/settings.json@@ -1398,7 +1398,10 @@"close_others": "關閉其他標籤頁","open_window": "在新視窗開啟","new": "新建標籤頁",- "pinned_name": "{{title}}(已固定)"+ "pinned_name": "{{title}}(已固定)",+ "copy_link": "複製連結",+ "link_copied": "已複製連結",+ "close_right": "關閉右側標籤頁"},"updates": {"title": "更新",diff --git a/packages/views/navigation/types.ts b/packages/views/navigation/types.tsindex 1cc8c0cccc..c81d4ceb5b 100644--- a/packages/views/navigation/types.ts+++ b/packages/views/navigation/types.ts@@ -28,6 +28,8 @@ export interface NavigationAdapter {title?: string,opts?: { activate?: boolean },) => void;+ /** Desktop only: open an issue path in its own window. */+ openIssueInNewWindow?: (path: string, title: string) => void;/** Web only: hand an issue path to the installed desktop app. */openInDesktop?: (path: string) => void;/**diff --git a/packages/views/package.json b/packages/views/package.jsonindex 11638a7cec..ddf247f33b 100644--- a/packages/views/package.json+++ b/packages/views/package.json@@ -13,6 +13,8 @@"./common/actor-avatar": "./common/actor-avatar.tsx","./common/appearance-sync": "./common/appearance-sync.tsx","./common/cli-install-command": "./common/cli-install-command.tsx",+ "./common/context-menu-scope": "./common/context-menu-scope.tsx",+ "./common/menu-primitives": "./common/menu-primitives.ts","./common/shortcut-keycaps": "./common/shortcut-keycaps.tsx","./editor": "./editor/index.ts","./issue-views": "./issue-views/index.ts",diff --git a/packages/views/projects/components/project-chip.tsx b/packages/views/projects/components/project-chip.tsxindex 7d33216832..9b1b2f784f 100644--- a/packages/views/projects/components/project-chip.tsx+++ b/packages/views/projects/components/project-chip.tsx@@ -27,12 +27,8 @@ export interface ProjectChipProps {const BASE_CLASS ="project-chip inline-flex min-w-0 max-w-[min(18rem,100%)] items-center gap-1.5 rounded-md border mx-0.5 px-2 py-0.5 text-caption";-export function ProjectChip({- projectId,- fallbackLabel,- className,-}: ProjectChipProps) {- const { t } = useT("projects");+/** The project a chip shows, from the project list cache or its own query. */+export function useChipProject(projectId: string) {const wsId = useWorkspaceId();const { data: projects = [] } = useQuery(projectListOptions(wsId));const listProject = projects.find((p) => p.id === projectId);@@ -42,7 +38,16 @@ export function ProjectChip({enabled: !listProject,});- const project = listProject ?? detailProject;+ return listProject ?? detailProject;+}++export function ProjectChip({+ projectId,+ fallbackLabel,+ className,+}: ProjectChipProps) {+ const { t } = useT("projects");+ const project = useChipProject(projectId);const cls = className ? `${BASE_CLASS} ${className}` : BASE_CLASS;if (!project) {diff --git a/packages/views/projects/components/project-mention-card.tsx b/packages/views/projects/components/project-mention-card.tsxindex 5c6281227c..d3865182cb 100644--- a/packages/views/projects/components/project-mention-card.tsx+++ b/packages/views/projects/components/project-mention-card.tsx@@ -1,8 +1,19 @@"use client";+import { useMemo, useState } from "react";import { AppLink } from "../../navigation";+import { useRowMenu, yieldsToTextMenu } from "../../common/point-menu";+import {+ ContextMenuScopeSubmenu,+ findContextMenuScope,+ useScopeSubmenuFocus,+ type ResolvedContextMenuScope,+} from "../../common/context-menu-scope";+import { dropdownPrimitives } from "../../common/menu-primitives";+import { CollectionRowContext } from "../../layout/collection-list/row-context";+import { ProjectMenu } from "./project-row-actions";import { useWorkspacePaths } from "@multica/core/paths";-import { ProjectChip } from "./project-chip";+import { ProjectChip, useChipProject } from "./project-chip";interface ProjectMentionCardProps {projectId: string;@@ -36,17 +47,53 @@ export function ProjectMentionCard({fallbackLabel,}: ProjectMentionCardProps) {const p = useWorkspacePaths();+ const project = useChipProject(projectId);+ // Right-click opens the projects page's row menu at the cursor; it mounts+ // on the first right-click, so a page of mentions holds no menus.+ const rowMenu = useRowMenu();+ // The comment around the mention, read when the menu opens.+ const [outer, setOuter] = useState<ResolvedContextMenuScope["submenu"]>(null);+ const scope = useScopeSubmenuFocus(outer);+ const rowMenuContext = useMemo(+ () => ({ menu: rowMenu.menu, setMenu: rowMenu.setMenu }),+ [rowMenu.menu, rowMenu.setMenu],+ );return (- <AppLink- href={p.projectDetail(projectId)}- newTabTitle={fallbackLabel}- className="project-mention inline-flex"- >- <ProjectChip- projectId={projectId}- fallbackLabel={fallbackLabel}- className="cursor-pointer hover:bg-accent transition-colors"- />- </AppLink>+ <>+ <AppLink+ href={p.projectDetail(projectId)}+ newTabTitle={fallbackLabel}+ className="project-mention inline-flex"+ onContextMenu={+ project+ ? (event) => {+ // The innermost object's menu wins; a row around the mention+ // must not open its own as well. Selected text and an editor+ // keep their text menu.+ event.stopPropagation();+ if (yieldsToTextMenu(event.target as Element)) return;+ setOuter(findContextMenuScope(event.currentTarget.parentElement).submenu);+ rowMenu.openAtPointer(event);+ }+ : undefined+ }+ >+ <ProjectChip+ projectId={projectId}+ fallbackLabel={fallbackLabel}+ className="cursor-pointer hover:bg-accent transition-colors"+ />+ </AppLink>+ {project && rowMenu.menu.point && (+ <CollectionRowContext.Provider value={rowMenuContext}>+ <ProjectMenu+ project={project}+ triggerHidden+ trailing={<ContextMenuScopeSubmenu submenu={scope.submenu} primitives={dropdownPrimitives} />}+ finalFocus={scope.finalFocus}+ />+ </CollectionRowContext.Provider>+ )}+ </>);}diff --git a/packages/views/projects/components/project-row-actions.tsx b/packages/views/projects/components/project-row-actions.tsxnew file mode 100644index 0000000000..1173ee0fd8--- /dev/null+++ b/packages/views/projects/components/project-row-actions.tsx@@ -0,0 +1,267 @@+"use client";++import { useState, type ReactNode } from "react";+import { useQuery } from "@tanstack/react-query";+import { toast } from "sonner";+import { ExternalLink, Link2, Pencil, Pin, PinOff, Trash2 } from "@multica/ui/icons";+import { copyText } from "@multica/ui/lib/clipboard";+import { Button } from "@multica/ui/components/ui/button";+import { Spinner } from "@multica/ui/components/ui/spinner";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@multica/ui/components/ui/dialog";+import {+ DropdownMenuItem,+ DropdownMenuSeparator,+} from "@multica/ui/components/ui/dropdown-menu";+import { useAuthStore } from "@multica/core/auth";+import { useWorkspaceId } from "@multica/core/hooks";+import { useModalStore } from "@multica/core/modals";+import { useWorkspacePaths } from "@multica/core/paths";+import { pinListOptions, useCreatePin, useDeletePin } from "@multica/core/pins";+import { ProjectDeletionOfflineError, useDeleteProject } from "@multica/core/projects";+import { canDeleteProject } from "@multica/core/projects/deletion-permissions";+import type { Project } from "@multica/core/types";+import { agentListOptions, memberListOptions } from "@multica/core/workspace/queries";+import { useT } from "../../i18n";+import { useIntentNavigate, useNavigation } from "../../navigation";+import { CollectionRowMenu } from "../../layout/collection-list";++export function DeleteProjectsDialog({+ rows,+ open,+ onOpenChange,+ onDeleted,+}: {+ rows: Project[];+ open: boolean;+ onOpenChange: (open: boolean) => void;+ onDeleted?: () => void;+}) {+ const { t } = useT("projects");+ const deleteProject = useDeleteProject();+ const [deleting, setDeleting] = useState(false);++ const handleDelete = async () => {+ if (deleting) return;+ setDeleting(true);+ try {+ for (const project of rows) {+ await deleteProject.mutateAsync(project.id);+ }+ onOpenChange(false);+ onDeleted?.();+ } catch (err) {+ toast.error(+ err instanceof ProjectDeletionOfflineError+ ? t(($) => $.delete_dialog.offline_error)+ : err instanceof Error ? err.message : String(err),+ );+ } finally {+ setDeleting(false);+ }+ };++ return (+ <Dialog+ open={open}+ onOpenChange={(nextOpen) => {+ if (!deleting) onOpenChange(nextOpen);+ }}+ >+ <DialogContent className="sm:max-w-md" showCloseButton={!deleting}>+ <DialogHeader>+ <DialogTitle>{t(($) => $.delete_dialog.title)}</DialogTitle>+ <DialogDescription>+ {t(($) => $.delete_dialog.description)}+ </DialogDescription>+ </DialogHeader>+ <DialogFooter>+ <Button+ type="button"+ variant="outline"+ size="sm"+ disabled={deleting}+ onClick={() => onOpenChange(false)}+ >+ {t(($) => $.delete_dialog.cancel)}+ </Button>+ <Button+ type="button"+ variant="destructive"+ size="sm"+ disabled={deleting}+ aria-busy={deleting}+ onClick={handleDelete}+ >+ {deleting && <Spinner className="size-3.5" aria-hidden="true" />}+ {t(($) => $.delete_dialog.confirm)}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}++/**+ * A project's row menu, shared by the projects page (table rows, ⋯ and+ * right-click, and cards) and the sidebar. `leading` items go first, for+ * actions only one surface offers; `triggerHidden` is for rows that open it+ * only on right-click.+ */+export function ProjectRowActions({+ project,+ pinned,+ canDelete,+ leading,+ trailing,+ triggerHidden,+ finalFocus,+}: {+ project: Project;+ pinned: boolean;+ canDelete: boolean;+ leading?: ReactNode;+ /** After the project's own items, e.g. the surrounding comment's submenu. */+ trailing?: ReactNode;+ triggerHidden?: boolean;+ finalFocus?: () => boolean;+}) {+ const { t } = useT("projects");+ const { t: tCommon } = useT("common");+ const { t: tLayout } = useT("layout");+ const wsPaths = useWorkspacePaths();+ const intentNavigate = useIntentNavigate();+ const { getShareableUrl } = useNavigation();+ const createPin = useCreatePin();+ const deletePin = useDeletePin();+ const [deleteOpen, setDeleteOpen] = useState(false);++ const togglePin = () => {+ if (pinned) deletePin.mutate({ itemType: "project", itemId: project.id });+ else createPin.mutate({ item_type: "project", item_id: project.id });+ };+ const copyLink = async () => {+ if (await copyText(getShareableUrl(wsPaths.projectDetail(project.id)))) {+ toast.success(tLayout(($) => $.rail.link_copied));+ }+ };++ return (+ <>+ <CollectionRowMenu+ label={t(($) => $.page.row_menu)}+ contentClassName="w-auto min-w-52"+ triggerHidden={triggerHidden}+ finalFocus={finalFocus}+ >+ {leading && (+ <>+ {leading}+ <DropdownMenuSeparator />+ </>+ )}+ <DropdownMenuItem+ onClick={() =>+ useModalStore+ .getState()+ .open("project-rename", { projectId: project.id, title: project.title })+ }+ >+ <Pencil className="size-3.5" />+ {t(($) => $.page.rename)}+ </DropdownMenuItem>+ <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" />+ ) : (+ <Pin className="size-3.5" />+ )}+ {pinned ? t(($) => $.page.unpin) : t(($) => $.page.pin)}+ </DropdownMenuItem>+ <DropdownMenuItem onClick={() => void copyLink()}>+ <Link2 className="size-3.5" />+ {tLayout(($) => $.rail.copy_link)}+ </DropdownMenuItem>+ {canDelete && (+ <>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ variant="destructive"+ onClick={() => setDeleteOpen(true)}+ >+ <Trash2 className="size-3.5" />+ {t(($) => $.page.delete)}+ </DropdownMenuItem>+ </>+ )}+ {trailing}+ </CollectionRowMenu>++ <DeleteProjectsDialog+ rows={[project]}+ open={deleteOpen}+ onOpenChange={setDeleteOpen}+ />+ </>+ );+}++/**+ * ProjectRowActions for a surface that does not already hold the viewer's+ * pins and permissions: it reads them from the shared caches.+ */+export function ProjectMenu({+ project,+ leading,+ trailing,+ triggerHidden,+ finalFocus,+}: {+ project: Project;+ leading?: ReactNode;+ trailing?: ReactNode;+ triggerHidden?: boolean;+ finalFocus?: () => boolean;+}) {+ const wsId = useWorkspaceId();+ const userId = useAuthStore((s) => s.user?.id ?? null);+ const { data: members = [] } = useQuery(memberListOptions(wsId));+ const { data: agents = [] } = useQuery(agentListOptions(wsId));+ const { data: pins = [] } = useQuery({+ ...pinListOptions(wsId, userId ?? ""),+ enabled: !!wsId && !!userId,+ });+ const role = members.find((m) => m.user_id === userId)?.role ?? null;+ const pinned = pins.some((pin) => pin.item_type === "project" && pin.item_id === project.id);++ return (+ <ProjectRowActions+ project={project}+ pinned={pinned}+ canDelete={canDeleteProject(project, userId, role, agents)}+ leading={leading}+ trailing={trailing}+ triggerHidden={triggerHidden}+ finalFocus={finalFocus}+ />+ );+}diff --git a/packages/views/projects/components/projects-page.tsx b/packages/views/projects/components/projects-page.tsxindex 62c93662f1..a33ed56b0f 100644--- a/packages/views/projects/components/projects-page.tsx+++ b/packages/views/projects/components/projects-page.tsx@@ -2,22 +2,16 @@import { useCallback, useMemo, useState } from "react";import {- ExternalLink,FolderKanban,LayoutGrid,- Pencil,Pin,- PinOff,Rows3,Trash2,} from "@multica/ui/icons";import { useQuery } from "@tanstack/react-query";-import { toast } from "sonner";import {projectListOptions,useUpdateProject,- useDeleteProject,- ProjectDeletionOfflineError,useProjectViewStore,type ProjectColumnKey,type ProjectListFilters,@@ -27,7 +21,6 @@ import {import {pinListOptions,useCreatePin,- useDeletePin,} from "@multica/core/pins";import { useWorkspaceId } from "@multica/core/hooks";import { useWorkspacePaths } from "@multica/core/paths";@@ -39,26 +32,15 @@ import {} from "@multica/core/workspace/queries";import { canDeleteProject } from "@multica/core/projects/deletion-permissions";import { useModalStore } from "@multica/core/modals";-import { AppLink, useIntentNavigate } from "../../navigation";+import { AppLink } 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";import { Button } from "@multica/ui/components/ui/button";-import { Spinner } from "@multica/ui/components/ui/spinner";-import {- Dialog,- DialogContent,- DialogDescription,- DialogFooter,- DialogHeader,- DialogTitle,-} from "@multica/ui/components/ui/dialog";import {DropdownMenu,DropdownMenuCheckboxItem,DropdownMenuContent,- DropdownMenuItem,- DropdownMenuSeparator,DropdownMenuSub,DropdownMenuSubContent,DropdownMenuSubTrigger,@@ -86,13 +68,13 @@ import {CollectionEmptyValue,CollectionList,CollectionNameCell,- CollectionRowMenu,type CollectionColumn,type CollectionSort,} from "../../layout/collection-list";import { ProjectIcon } from "./project-icon";import { ProjectsIntro } from "./projects-intro";import { useT } from "../../i18n";+import { DeleteProjectsDialog, ProjectRowActions } from "./project-row-actions";import { useFormatRelativeDate } from "./labels";import { ProjectStatusBadge, ProjectPriorityBadge } from "./project-badge";import { ProjectLeadPicker } from "./project-lead-picker";@@ -152,162 +134,6 @@ function ProgressRing({ project }: { project: Project }) {);}-function DeleteProjectsDialog({- rows,- open,- onOpenChange,- onDeleted,-}: {- rows: Project[];- open: boolean;- onOpenChange: (open: boolean) => void;- onDeleted?: () => void;-}) {- const { t } = useT("projects");- const deleteProject = useDeleteProject();- const [deleting, setDeleting] = useState(false);-- const handleDelete = async () => {- if (deleting) return;- setDeleting(true);- try {- for (const project of rows) {- await deleteProject.mutateAsync(project.id);- }- onOpenChange(false);- onDeleted?.();- } catch (err) {- toast.error(- err instanceof ProjectDeletionOfflineError- ? t(($) => $.delete_dialog.offline_error)- : err instanceof Error ? err.message : String(err),- );- } finally {- setDeleting(false);- }- };-- return (- <Dialog- open={open}- onOpenChange={(nextOpen) => {- if (!deleting) onOpenChange(nextOpen);- }}- >- <DialogContent className="sm:max-w-md" showCloseButton={!deleting}>- <DialogHeader>- <DialogTitle>{t(($) => $.delete_dialog.title)}</DialogTitle>- <DialogDescription>- {t(($) => $.delete_dialog.description)}- </DialogDescription>- </DialogHeader>- <DialogFooter>- <Button- type="button"- variant="outline"- size="sm"- disabled={deleting}- onClick={() => onOpenChange(false)}- >- {t(($) => $.delete_dialog.cancel)}- </Button>- <Button- type="button"- variant="destructive"- size="sm"- disabled={deleting}- aria-busy={deleting}- onClick={handleDelete}- >- {deleting && <Spinner className="size-3.5" aria-hidden="true" />}- {t(($) => $.delete_dialog.confirm)}- </Button>- </DialogFooter>- </DialogContent>- </Dialog>- );-}--// Shared by table rows (⋯ and right-click) and cards.-function ProjectRowActions({- project,- pinned,- canDelete,-}: {- project: Project;- pinned: boolean;- canDelete: boolean;-}) {- const { t } = useT("projects");- const { t: tCommon } = useT("common");- const wsPaths = useWorkspacePaths();- const intentNavigate = useIntentNavigate();- const createPin = useCreatePin();- const deletePin = useDeletePin();- const [deleteOpen, setDeleteOpen] = useState(false);-- const togglePin = () => {- if (pinned) deletePin.mutate({ itemType: "project", itemId: project.id });- else createPin.mutate({ item_type: "project", item_id: project.id });- };-- return (- <>- <CollectionRowMenu label={t(($) => $.page.row_menu)} contentClassName="w-44">- <DropdownMenuItem- onClick={() =>- useModalStore- .getState()- .open("project-rename", { projectId: project.id, title: project.title })- }- >- <Pencil className="size-3.5" />- {t(($) => $.page.rename)}- </DropdownMenuItem>- <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" />- ) : (- <Pin className="size-3.5" />- )}- {pinned ? t(($) => $.page.unpin) : t(($) => $.page.pin)}- </DropdownMenuItem>- {canDelete && (- <>- <DropdownMenuSeparator />- <DropdownMenuItem- variant="destructive"- onClick={() => setDeleteOpen(true)}- >- <Trash2 className="size-3.5" />- {t(($) => $.page.delete)}- </DropdownMenuItem>- </>- )}- </CollectionRowMenu>-- <DeleteProjectsDialog- rows={[project]}- open={deleteOpen}- onOpenChange={setDeleteOpen}- />- </>- );-}-function ProjectInlineCell({project,children,diff --git a/packages/views/rich-content/current-issue-rendering.test.tsx b/packages/views/rich-content/current-issue-rendering.test.tsxindex 216b07aca9..a8230a8212 100644--- a/packages/views/rich-content/current-issue-rendering.test.tsx+++ b/packages/views/rich-content/current-issue-rendering.test.tsx@@ -24,6 +24,7 @@ vi.mock("../issues/hooks", () => ({}));vi.mock("../issues/components/issue-chip", () => ({+ useChipIssue: () => undefined,IssueChip: ({issueId,children,diff --git a/packages/views/rich-content/entity-link-unfurl.test.tsx b/packages/views/rich-content/entity-link-unfurl.test.tsxindex d27eb7163b..d958e22d6d 100644--- a/packages/views/rich-content/entity-link-unfurl.test.tsx+++ b/packages/views/rich-content/entity-link-unfurl.test.tsx@@ -67,6 +67,7 @@ vi.mock("../issues/components/issue-mention-card", () => ({}));vi.mock("../projects/components/project-chip", () => ({+ useChipProject: () => undefined,ProjectChip: ({ projectId }: { projectId: string }) => (<span data-testid="project-chip">{projectId}</span>),diff --git a/packages/views/rich-content/project-mention-a11y.test.tsx b/packages/views/rich-content/project-mention-a11y.test.tsxindex 6a95fca97e..98172f0a30 100644--- a/packages/views/rich-content/project-mention-a11y.test.tsx+++ b/packages/views/rich-content/project-mention-a11y.test.tsx@@ -52,6 +52,7 @@ vi.mock("../issues/components/issue-mention-card", () => ({}));vi.mock("../projects/components/project-chip", () => ({+ useChipProject: () => undefined,ProjectChip: ({ projectId, fallbackLabel }: { projectId: string; fallbackLabel?: string }) => (<span data-testid="project-chip">{fallbackLabel ?? projectId}</span>),diff --git a/packages/views/skills/components/file-tree.tsx b/packages/views/skills/components/file-tree.tsxindex 9a24463e91..f95cfce4aa 100644--- a/packages/views/skills/components/file-tree.tsx+++ b/packages/views/skills/components/file-tree.tsx@@ -1,6 +1,6 @@"use client";-import { useRef, useState } from "react";+import { useState } from "react";import {ChevronRight,ChevronDown,@@ -22,6 +22,7 @@ import {} from "@multica/ui/components/ui/dropdown-menu";import { cn } from "@multica/ui/lib/utils";import { useT } from "../../i18n";+import { shouldOpenRowMenu, useRowMenu } from "../../common/point-menu";import { DeferredTooltip } from "@multica/ui/components/common/deferred-tooltip";/**@@ -122,7 +123,7 @@ function TreeNodeItem({}) {const { t } = useT("skills");const [renaming, setRenaming] = useState(false);- const menuButtonRef = useRef<HTMLButtonElement | null>(null);+ const rowMenu = useRowMenu();const [expanded, setExpanded] = useState(true);const isSelected = node.path === selectedPath;@@ -188,14 +189,11 @@ function TreeNodeItem({? "bg-surface-selected": "hover:bg-surface-hover",)}- // Right-click opens the same menu the trailing button does. The menu- // anchors to that button rather than the cursor, which keeps one menu- // per row instead of a context-menu root beside a dropdown root.+ // Right-click opens the trailing button's menu at the cursor.onContextMenu={hasMenu? (event) => {- event.preventDefault();- menuButtonRef.current?.click();+ if (shouldOpenRowMenu(event)) rowMenu.openAtPointer(event);}: undefined}@@ -217,14 +215,13 @@ function TreeNodeItem({<span className="truncate">{node.name}</span></button>{actions && (- <DropdownMenu>+ <DropdownMenu open={rowMenu.menu.open} onOpenChange={rowMenu.onOpenChange}><DeferredTooltipcontent={t(($) => $.file_tree.actions.label, { path: node.path })}trigger={<DropdownMenuTriggerrender={<button- ref={menuButtonRef}type="button"aria-label={t(($) => $.file_tree.actions.label, {path: node.path,@@ -251,7 +248,11 @@ function TreeNodeItem({/>}/>- <DropdownMenuContent align="end" className="w-36">+ <DropdownMenuContent+ align={rowMenu.menu.point ? "start" : "end"}+ anchor={rowMenu.anchor}+ className="w-36"+ ><DropdownMenuItem onClick={() => actions.onEdit(node.path)}><PencilLine />{t(($) => $.file_tree.actions.edit)}