Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(chat): 统一消息链接快捷操作并精简右键菜单

Dashd45e46032e31
diff --git a/apps/desktop/src/main/__tests__/secondary-windows.test.ts b/apps/desktop/src/main/__tests__/secondary-windows.test.ts
new file mode 100644
index 0000000000..57d99e5e1d
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/secondary-windows.test.ts
@@ -0,0 +1,73 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({ loadURL: vi.fn(), loadFile: vi.fn() }));
+vi.mock('electron', () => ({
+ BrowserWindow: class {
+ webContents = { on: vi.fn(), once: vi.fn(), setWindowOpenHandler: vi.fn() };
+ once = vi.fn();
+ loadURL = mocks.loadURL;
+ loadFile = mocks.loadFile;
+ },
+ app: { isPackaged: false },
+ nativeTheme: { shouldUseDarkColors: false },
+ screen: {},
+ shell: {},
+}));
+vi.mock('../logger.js', () => ({ createLogger: () => ({ info: vi.fn() }) }));
+vi.mock('../app-shortcuts/new-maker-window-shortcut.js', () => ({
+ installNewMakerWindowShortcut: vi.fn(),
+}));
+vi.mock('../windowFocusClassifier.js', () => ({
+ markAppContentWindow: vi.fn(),
+ isAppContentWindow: vi.fn(),
+}));
+vi.mock('../window-behavior-settings-store.js', () => ({
+ readWindowBehaviorSettings: () => ({ swallowActivationClick: false }),
+}));
+vi.mock('../vibrancyConfig.js', () => ({ resolveVibrancyConfig: () => ({}) }));
+vi.mock('../selection-context-menu.js', () => ({ installSelectionContextMenu: vi.fn() }));
+vi.mock('../appearance-settings-ipc.js', () => ({ applyAppearanceToWindow: vi.fn() }));
+vi.mock('../mainWindowFullscreenStartup.js', () => ({
+ installWindowFullscreenStateBroadcast: vi.fn(),
+}));
+vi.mock('../window-theme-mode-store.js', () => ({ readWindowThemeSnapshot: () => null }));
+
+import { openSessionInNewWindow } from '../secondary-windows';
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ vi.stubGlobal('MAIN_WINDOW_VITE_NAME', 'main_window');
+});
+afterEach(() => vi.unstubAllGlobals());
+
+describe('session window link targets', () => {
+ it('encodes remote device and message anchors into the development window URL', () => {
+ vi.stubGlobal('MAIN_WINDOW_VITE_DEV_SERVER_URL', 'http://localhost:5173/');
+ openSessionInNewWindow('task/1', null, 'remote-device', undefined, 'message/1?x=2&y=3');
+ const url = new URL(mocks.loadURL.mock.calls[0]![0]);
+ expect(url.hash).toBe('#/cc-agent/boot');
+ expect(url.searchParams.get('bootSession')).toBe('task/1');
+ expect(url.searchParams.get('bootDevice')).toBe('remote-device');
+ expect(url.searchParams.get('bootMessage')).toBe('message/1?x=2&y=3');
+ expect(url.searchParams.get('y')).toBeNull();
+ });
+
+ it('passes the same target to packaged windows and keeps existing callers compatible', () => {
+ vi.stubGlobal('MAIN_WINDOW_VITE_DEV_SERVER_URL', undefined);
+ openSessionInNewWindow('task', null, 'remote-device', undefined, 'message');
+ expect(mocks.loadFile.mock.calls[0]![1]).toEqual({
+ query: {
+ secondaryWindow: '1',
+ bootSession: 'task',
+ bootDevice: 'remote-device',
+ bootMessage: 'message',
+ },
+ hash: '/cc-agent/boot',
+ });
+ openSessionInNewWindow('local-task', null);
+ expect(mocks.loadFile.mock.calls[1]![1].query).toEqual({
+ secondaryWindow: '1',
+ bootSession: 'local-task',
+ });
+ });
+});
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 3d2b6419c6..f1767ab4e5 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -4449,14 +4449,19 @@ const registerIpcHandlers = () => {
// 「在新窗口打开」会话多开 —— 新建一个完整窗口定位到该 session, 初始 bounds 取主窗。
ipcMain.handle(
MAKER_IPC_INVOKE.OPEN_SESSION_IN_NEW_WINDOW,
- (event, sessionId: unknown, deviceIdRaw: unknown) => {
+ (event, sessionId: unknown, deviceIdRaw: unknown, messageClientId: unknown) => {
assertTrustedAppRendererEvent(event);
if (typeof sessionId !== 'string' || sessionId.length === 0) {
throwIpcError('INVALID_PARAMS', 'sessionId required');
}
const deviceId = parseOptionalDeviceLinkDeviceId(deviceIdRaw);
+ if (messageClientId != null && (
+ typeof messageClientId !== 'string' || !messageClientId.trim() || messageClientId.length > 1024
+ )) {
+ throwIpcError('INVALID_PARAMS', 'messageClientId must be a non-empty string of at most 1024 characters');
+ }
const sourceWindow = BrowserWindow.fromWebContents(event.sender);
- openSessionInNewWindow(sessionId, sourceWindow ?? mainWindowRef, deviceId);
+ openSessionInNewWindow(sessionId, sourceWindow ?? mainWindowRef, deviceId, undefined, messageClientId);
},
);
diff --git a/apps/desktop/src/main/secondary-windows.ts b/apps/desktop/src/main/secondary-windows.ts
index 41c902ef61..cd9b6b2a8d 100644
--- a/apps/desktop/src/main/secondary-windows.ts
+++ b/apps/desktop/src/main/secondary-windows.ts
@@ -98,6 +98,7 @@ export function openSessionInNewWindow(
mainWindow: BrowserWindow | null,
deviceId?: string | null,
anchorPoint?: ScreenPoint,
+ messageClientId?: string | null,
): void {
const createdAt = performance.now();
// frame 配置复刻主窗(bootstrap-electron.ts createWindow): Mac 隐藏标题栏留红绿灯,
@@ -221,6 +222,7 @@ export function openSessionInNewWindow(
url.searchParams.set('secondaryWindow', '1');
url.searchParams.set('bootSession', sessionId);
if (deviceId) url.searchParams.set('bootDevice', deviceId);
+ if (messageClientId) url.searchParams.set('bootMessage', messageClientId);
url.hash = hash;
void win.loadURL(url.toString());
} else {
@@ -229,6 +231,7 @@ export function openSessionInNewWindow(
secondaryWindow: '1',
bootSession: sessionId,
...(deviceId ? { bootDevice: deviceId } : {}),
+ ...(messageClientId ? { bootMessage: messageClientId } : {}),
},
hash,
});
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 6b60c9c1ef..bf8351bf06 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -6502,8 +6502,10 @@ contextBridge.exposeInMainWorld('electronAPI', {
ipcRenderer.invoke('maker:model-context-limit:reset', target, owner),
// 「在新窗口打开」会话多开 —— 新建一个完整窗口定位到该 session。
- openSessionInNewWindow: (sessionId: string, deviceId?: string | null): Promise<void> =>
- ipcRenderer.invoke('maker:open-session-in-new-window', sessionId, deviceId),
+ openSessionInNewWindow: (
+ sessionId: string, deviceId?: string | null, messageClientId?: string | null,
+ ): Promise<void> =>
+ ipcRenderer.invoke('maker:open-session-in-new-window', sessionId, deviceId, messageClientId),
openSessionInNewWindowIfDroppedOutside: (
sessionId: string,
deviceId?: string | null,
diff --git a/apps/desktop/src/renderer/__tests__/agentActionRowRendering.test.ts b/apps/desktop/src/renderer/__tests__/agentActionRowRendering.test.ts
index 8c67a8b731..ff75c5008a 100644
--- a/apps/desktop/src/renderer/__tests__/agentActionRowRendering.test.ts
+++ b/apps/desktop/src/renderer/__tests__/agentActionRowRendering.test.ts
@@ -51,6 +51,7 @@ vi.mock('@/components/chat/useFileChipContextMenu', () => ({
useFileChipContextMenu: () => ({
menu: null,
onContextMenu: () => {},
+ onActivate: (_event: unknown, openDefault: () => void) => openDefault(),
openAt: () => {},
}),
}));
diff --git a/apps/desktop/src/renderer/__tests__/botGeneratedArtifactsCard.test.tsx b/apps/desktop/src/renderer/__tests__/botGeneratedArtifactsCard.test.tsx
index edee8ab802..5fee951f4b 100644
--- a/apps/desktop/src/renderer/__tests__/botGeneratedArtifactsCard.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/botGeneratedArtifactsCard.test.tsx
@@ -39,6 +39,7 @@ vi.mock('../components/chat/useOpenWithMenu', () => ({
vi.mock('../components/chat/useFileChipContextMenu', () => ({
useFileChipContextMenu: () => ({
onContextMenu: vi.fn(),
+ onActivate: (_event: unknown, openDefault: () => void) => openDefault(),
openAt: vi.fn(),
menu: null,
}),
diff --git a/apps/desktop/src/renderer/__tests__/fileChipCopyLocation.test.tsx b/apps/desktop/src/renderer/__tests__/fileChipCopyLocation.test.tsx
index c9a0cef5ed..d1fa514897 100644
--- a/apps/desktop/src/renderer/__tests__/fileChipCopyLocation.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/fileChipCopyLocation.test.tsx
@@ -8,6 +8,12 @@ const mocks = vi.hoisted(() => ({
success: vi.fn(),
error: vi.fn(),
getAbsPath: vi.fn(),
+ openPath: vi.fn(async () => ({ success: true })),
+ openFileInBrowser: vi.fn(async () => undefined),
+ openDefault: vi.fn(),
+ openRemoteChatFile: vi.fn(),
+ reveal: vi.fn(async () => ({ success: true })),
+ download: vi.fn(async () => undefined),
context: {
sessionId: undefined as string | undefined,
workingDir: '/repo',
@@ -17,55 +23,199 @@ const mocks = vi.hoisted(() => ({
vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
vi.mock('@/lib/toast', () => ({ toast: { success: mocks.success, error: mocks.error } }));
-vi.mock('@/components/chat/ChatSessionFileContext', () => ({ useChatSessionFile: () => mocks.context }));
+vi.mock('@/components/chat/ChatSessionFileContext', () => ({
+ useChatSessionFile: () => mocks.context,
+}));
vi.mock('@/features/cc-agent/embeddedSessionNavigation', () => ({
useSidebarTargetSessionId: (id: string | undefined) => id,
}));
vi.mock('@/features/right-sidebar/lib/openInSidebarBrowser', () => ({
- openUrlInSidebarBrowser: vi.fn(), pathToFileUrl: vi.fn(),
+ openUrlInSidebarBrowser: vi.fn(),
+ pathToFileUrl: vi.fn(),
}));
vi.mock('@/features/right-sidebar/lib/openInSidebarFileBrowser', () => ({
openDirInSidebarFileBrowser: vi.fn(),
openExternalFileInSidebarFileBrowser: vi.fn(),
openFileInSidebarFileBrowser: vi.fn(),
}));
-vi.mock('@/lib/remoteFileOpen', () => ({ copyRemoteChatFile: vi.fn(), downloadRemoteChatEntry: vi.fn() }));
+vi.mock('@/lib/remoteFileOpen', () => ({
+ copyRemoteChatFile: vi.fn(),
+ downloadRemoteChatEntry: mocks.download,
+ openRemoteChatFile: mocks.openRemoteChatFile,
+}));
+vi.mock('../components/chat/TextLightbox', () => ({
+ TextLightbox: ({ filePath }: { filePath: string }) => (
+ <div data-testid="source-preview">{filePath}</div>
+ ),
+}));
import { useFileChipContextMenu } from '../components/chat/useFileChipContextMenu';
import type { FileLocation } from '../lib/fileLocation';
-function FileReference({ location, directory = false }: { location?: FileLocation; directory?: boolean }) {
- const { onContextMenu, menu } = useFileChipContextMenu({
+function FileReference({
+ location,
+ directory = false,
+ html = false,
+}: {
+ location?: FileLocation;
+ directory?: boolean;
+ html?: boolean;
+}) {
+ const { onContextMenu, onActivate, menu } = useFileChipContextMenu({
getAbsPath: mocks.getAbsPath,
sidebarFileBrowserKind: directory ? 'directory' : 'file',
location,
+ canOpenInBrowser: html,
});
- return <><button onContextMenu={onContextMenu}>file reference</button>{menu}</>;
+ return (
+ <>
+ <button
+ onClick={(event) => onActivate(event, mocks.openDefault)}
+ onContextMenu={onContextMenu}
+ >
+ file reference
+ </button>
+ {menu}
+ </>
+ );
}
async function openMenu(location?: FileLocation, directory = false) {
render(<FileReference location={location} directory={directory} />);
- fireEvent.contextMenu(screen.getByRole('button', { name: 'file reference' }), { clientX: 10, clientY: 10 });
+ fireEvent.contextMenu(screen.getByRole('button', { name: 'file reference' }), {
+ clientX: 10,
+ clientY: 10,
+ });
await screen.findByRole('menuitem', { name: 'chat.markdownRenderer.copyFilePath' });
}
beforeEach(() => {
vi.clearAllMocks();
mocks.context.workingDir = '/repo';
+ mocks.context.sessionId = undefined;
mocks.context.origin = { kind: 'local' };
mocks.getAbsPath.mockResolvedValue('/repo/src/example.ts');
mocks.writeText.mockResolvedValue(undefined);
+ Object.defineProperty(window, 'electronAPI', {
+ configurable: true,
+ value: {
+ openPath: mocks.openPath,
+ openFileInBrowser: mocks.openFileInBrowser,
+ showItemInFolder: mocks.reveal,
+ },
+ });
Object.defineProperty(navigator, 'clipboard', {
- configurable: true, value: { writeText: mocks.writeText },
+ configurable: true,
+ value: { writeText: mocks.writeText },
});
});
afterEach(cleanup);
describe('file chip Copy Location action', () => {
+ it.each(['local', 'device'] as const)(
+ 'keeps the HTML menu flat and replaces reveal with download for %s files',
+ async (kind) => {
+ mocks.context.sessionId = 'task';
+ mocks.context.origin = kind === 'local' ? { kind } : { kind, deviceId: 'remote-device' };
+ mocks.getAbsPath.mockResolvedValue('/repo/page.html');
+ render(<FileReference html />);
+ fireEvent.contextMenu(screen.getByRole('button', { name: 'file reference' }));
+ const items = await screen.findAllByRole('menuitem');
+ expect(
+ items.map((item) => item.textContent?.replace('chat.markdownRenderer.shiftClick', '')),
+ ).toEqual([
+ 'chat.markdownRenderer.openInSidebarBrowser',
+ 'chat.markdownRenderer.openInDefaultBrowser',
+ 'chat.markdownRenderer.viewSourceFile',
+ kind === 'local' ? 'chat.markdownRenderer.revealFile' : 'chat.remoteFile.downloadToLocal',
+ 'chat.markdownRenderer.copyFilePath',
+ ]);
+ expect(items.every((item) => !item.hasAttribute('aria-haspopup'))).toBe(true);
+ fireEvent.click(items[3]);
+ if (kind === 'local') {
+ await waitFor(() =>
+ expect(mocks.reveal).toHaveBeenCalledWith({ filePath: '/repo/page.html' }),
+ );
+ expect(mocks.download).not.toHaveBeenCalled();
+ } else {
+ await waitFor(() =>
+ expect(mocks.download).toHaveBeenCalledWith(
+ { kind: 'device', deviceId: 'remote-device' },
+ '/repo',
+ '/repo/page.html',
+ ),
+ );
+ expect(mocks.reveal).not.toHaveBeenCalled();
+ }
+ },
+ );
+
+ it('keeps source viewing available for HTML callers without a custom preview callback', async () => {
+ mocks.getAbsPath.mockResolvedValue('/repo/page.html');
+ render(<FileReference html />);
+ fireEvent.contextMenu(screen.getByRole('button', { name: 'file reference' }));
+ fireEvent.click(
+ await screen.findByRole('menuitem', { name: 'chat.markdownRenderer.viewSourceFile' }),
+ );
+ expect((await screen.findByTestId('source-preview')).textContent).toBe('/repo/page.html');
+ expect(mocks.openPath).not.toHaveBeenCalled();
+ });
+
+ it('offers the default application directly for ordinary files', async () => {
+ await openMenu();
+ fireEvent.click(screen.getByRole('menuitem', { name: 'chat.media.openWithApp' }));
+ await waitFor(() => expect(mocks.openPath).toHaveBeenCalledWith('/repo/src/example.ts'));
+ });
+
+ it('keeps normal clicks in the preview and sends modifier clicks to the default application', async () => {
+ render(<FileReference />);
+ const link = screen.getByRole('button', { name: 'file reference' });
+ fireEvent.click(link);
+ expect(mocks.openDefault).toHaveBeenCalledOnce();
+ expect(mocks.openPath).not.toHaveBeenCalled();
+ fireEvent.click(link, { shiftKey: true });
+ await waitFor(() => expect(mocks.openPath).toHaveBeenCalledWith('/repo/src/example.ts'));
+ expect(mocks.openDefault).toHaveBeenCalledOnce();
+ });
+
+ it('opens modified HTML links in the system browser, not the file default application', async () => {
+ mocks.getAbsPath.mockResolvedValue('/repo/page.html');
+ render(<FileReference html />);
+ fireEvent.click(screen.getByRole('button', { name: 'file reference' }), { metaKey: true });
+ await waitFor(() => expect(mocks.openFileInBrowser).toHaveBeenCalledWith('/repo/page.html'));
+ expect(mocks.openPath).not.toHaveBeenCalled();
+ expect(mocks.openDefault).not.toHaveBeenCalled();
+ });
+
+ it('opens remote files through the source-aware transfer, never the local path', async () => {
+ mocks.context.origin = { kind: 'device', deviceId: 'remote-device' };
+ render(<FileReference />);
+ fireEvent.click(screen.getByRole('button', { name: 'file reference' }), { ctrlKey: true });
+ await waitFor(() =>
+ expect(mocks.openRemoteChatFile).toHaveBeenCalledWith(
+ { kind: 'device', deviceId: 'remote-device' },
+ '/repo',
+ '/repo/src/example.ts',
+ ),
+ );
+ expect(mocks.openPath).not.toHaveBeenCalled();
+ });
+
+ it('reports path resolution failures rather than leaking rejected promises', async () => {
+ mocks.getAbsPath.mockRejectedValueOnce(new Error('missing'));
+ render(<FileReference />);
+ fireEvent.click(screen.getByRole('button', { name: 'file reference' }), { shiftKey: true });
+ await waitFor(() =>
+ expect(mocks.error).toHaveBeenCalledWith('chat.markdownRenderer.openWithAppFailed'),
+ );
+ expect(mocks.openDefault).not.toHaveBeenCalled();
+ });
it('copies relative path, line and column without resolving or opening the file again', async () => {
await openMenu({ absPath: '/repo/src/example.ts', line: 42, column: 7 });
fireEvent.click(screen.getByRole('menuitem', { name: 'chat.markdownRenderer.copyLocation' }));
- await waitFor(() => expect(mocks.success).toHaveBeenCalledWith('chat.markdownRenderer.locationCopied'));
+ await waitFor(() =>
+ expect(mocks.success).toHaveBeenCalledWith('chat.markdownRenderer.locationCopied'),
+ );
expect(mocks.writeText).toHaveBeenCalledWith('src/example.ts:42:7');
expect(mocks.getAbsPath).not.toHaveBeenCalled();
});
@@ -82,10 +232,15 @@ describe('file chip Copy Location action', () => {
[{ absPath: '/repo/src/example.ts' }, false],
[{ absPath: '/outside/example.ts', line: 42 }, false],
[{ absPath: '/repo/src', line: 42 }, true],
- ] as const)('omits Copy Location for missing coordinates, outside files and directories (%j)', async (location, directory) => {
- await openMenu(location, directory);
- expect(screen.queryByRole('menuitem', { name: 'chat.markdownRenderer.copyLocation' })).toBeNull();
- });
+ ] as const)(
+ 'omits Copy Location for missing coordinates, outside files and directories (%j)',
+ async (location, directory) => {
+ await openMenu(location, directory);
+ expect(
+ screen.queryByRole('menuitem', { name: 'chat.markdownRenderer.copyLocation' }),
+ ).toBeNull();
+ },
+ );
it('uses the remote source workdir, not the local clipboard host', async () => {
mocks.context.workingDir = 'D:\\Remote';
diff --git a/apps/desktop/src/renderer/components/chat/AgentActionRow.tsx b/apps/desktop/src/renderer/components/chat/AgentActionRow.tsx
index bdc9d69a93..d75a00b747 100644
--- a/apps/desktop/src/renderer/components/chat/AgentActionRow.tsx
+++ b/apps/desktop/src/renderer/components/chat/AgentActionRow.tsx
@@ -103,6 +103,7 @@ import { ImageLightbox } from './ImageLightbox';
import { TextLightbox } from './TextLightbox';
import { ToolPayloadLightbox, type ToolPayloadMode } from './ToolPayloadLightbox';
import { useFileChipContextMenu } from './useFileChipContextMenu';
+import { activateInlineLinkFromKeyboard } from './linkInteraction';
import {
formatToolResultCompactionBytes,
parseToolResultCompactionMarker,
@@ -1078,6 +1079,10 @@ export function AgentActionRow({
const onRowKeyDown = (e: ReactKeyboardEvent<HTMLButtonElement>) => {
if (!chipFilePath) return;
+ if (e.key === 'Enter' || e.key === ' ') {
+ activateInlineLinkFromKeyboard(e);
+ return;
+ }
if (e.key !== 'ContextMenu' && !(e.shiftKey && e.key === 'F10')) return;
e.preventDefault();
e.stopPropagation();
@@ -1091,7 +1096,16 @@ export function AgentActionRow({
<div className="flex flex-col" data-message-client-id={message.clientId}>
<button
type="button"
- onClick={(e) => void onActivate(e.currentTarget)}
+ onClick={(e) => {
+ const anchor = e.currentTarget;
+ if (chipFilePath) fileChipMenu.onActivate(e, () => onActivate(anchor));
+ else void onActivate(anchor);
+ }}
+ onAuxClick={(e) => {
+ if (e.button !== 1 || !chipFilePath) return;
+ const anchor = e.currentTarget;
+ fileChipMenu.onActivate(e, () => onActivate(anchor));
+ }}
onContextMenu={onRowContextMenu}
onKeyDown={onRowKeyDown}
aria-expanded={isInlineExpand && !onActivateOverride ? expanded : undefined}
diff --git a/apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx b/apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx
index e8e2aeb341..6fbde210ed 100644
--- a/apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx
+++ b/apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx
@@ -62,6 +62,7 @@ import { rewriteToRemoteMediaOrigin } from '../../../shared/remoteMediaUrl';
import { isBrowserOpenablePath } from '../../../shared/browserOpenableExts';
import { useChatSessionFile } from './ChatSessionFileContext';
import { useFileChipContextMenu } from './useFileChipContextMenu';
+import { activateInlineLinkFromKeyboard } from './linkInteraction';
import { ImageLightbox } from './ImageLightbox';
import { TextLightbox } from './TextLightbox';
import { ModelLightbox } from './ModelLightbox';
@@ -355,7 +356,11 @@ function GeneratedFileChip({
type="button"
title={file.path}
disabled={pending}
- onClick={pending ? undefined : () => void open()}
+ onClick={pending ? undefined : (event) => ctxMenu.onActivate(event, open)}
+ onKeyDown={pending ? undefined : activateInlineLinkFromKeyboard}
+ onAuxClick={pending ? undefined : (event) => {
+ if (event.button === 1) ctxMenu.onActivate(event, open);
+ }}
onContextMenu={pending ? undefined : ctxMenu.onContextMenu}
className={cn(
CHAT_FOCUS_CLASS,
diff --git a/apps/desktop/src/renderer/components/chat/InlineReferenceChip.tsx b/apps/desktop/src/renderer/components/chat/InlineReferenceChip.tsx
index bd229915a5..fe93518ca6 100644
--- a/apps/desktop/src/renderer/components/chat/InlineReferenceChip.tsx
+++ b/apps/desktop/src/renderer/components/chat/InlineReferenceChip.tsx
@@ -19,6 +19,7 @@ import type { KeyboardEventHandler, MouseEventHandler, ReactNode, Ref } from 're
import { Tip } from '@/components/ui/tooltip';
import { cn } from '@/lib/utils';
+import { activateInlineLinkFromKeyboard } from './linkInteraction';
export interface InlineReferenceChipProps {
label: string;
@@ -28,6 +29,7 @@ export interface InlineReferenceChipProps {
tooltipContentClassName?: string;
selected?: boolean;
onClick?: MouseEventHandler<HTMLSpanElement>;
+ onAuxClick?: MouseEventHandler<HTMLSpanElement>;
onContextMenu?: MouseEventHandler<HTMLSpanElement>;
chipRef?: Ref<HTMLSpanElement>;
ariaLabel?: string;
@@ -52,6 +54,7 @@ export function InlineReferenceChip({
tooltipContentClassName,
selected = false,
onClick,
+ onAuxClick,
onContextMenu,
chipRef,
ariaLabel,
@@ -93,10 +96,8 @@ export function InlineReferenceChip({
// `<span role="button">` 换掉原生 `<button>` 后要自己补键盘激活:走 native
// click(),让 onClick 收到一个正常的合成鼠标事件,调用方无需区分入口。
const handleKeyDown: KeyboardEventHandler<HTMLSpanElement> = (e) => {
- if (!onClick) return;
- if (e.key !== 'Enter' && e.key !== ' ') return;
- e.preventDefault();
- e.currentTarget.click();
+ if (!onClick && e.key !== 'ContextMenu' && !(e.shiftKey && e.key === 'F10')) return;
+ activateInlineLinkFromKeyboard(e);
};
const trigger = (
<span
@@ -105,6 +106,7 @@ export function InlineReferenceChip({
tabIndex={interactive ? 0 : undefined}
aria-label={ariaLabel}
onClick={onClick}
+ onAuxClick={onAuxClick}
onContextMenu={onContextMenu}
onKeyDown={interactive ? handleKeyDown : undefined}
className={sharedClassName}
diff --git a/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx b/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx
index b1542b55ae..6449ba71ce 100644
--- a/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx
+++ b/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx
@@ -53,7 +53,7 @@ import { useStreamFadeEnabled } from '@/hooks/useStreamFadePreference';
import { CopyAsImageBlock, mathBlockToLatex, tableToTsv } from './CopyAsImageBlock';
import type { Components, UrlTransform } from 'react-markdown';
import type { PluggableList } from 'unified';
-import { Check, Copy, FolderOpen } from 'lucide-react';
+import { Check, Copy, FolderOpen, ArrowUpRight } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { cn, basename } from '@/lib/utils';
@@ -126,9 +126,11 @@ import { useFileChipContextMenu } from './useFileChipContextMenu';
import {
isHtmlFilePath,
openHtmlFileByPreference,
- openUrlByPreference,
+ activateMessageUrl,
useOpenWithMenu,
} from './useOpenWithMenu';
+import { activateInlineLinkFromKeyboard } from './linkInteraction';
+import { useLinkContextMenu } from './useLinkContextMenu';
/**
* Recursively flatten an arbitrary react-markdown children tree into a
@@ -1026,16 +1028,16 @@ function FileTargetChip({
onViewSource: htmlWithSession ? onOpen : undefined,
});
- const activate = () => {
+ const activate = (event: React.MouseEvent<HTMLElement>) => {
// 与输入附件一致:点击打开 lightbox 前先撤掉 hover 层,避免关闭大图后残留。
setImagePreviewOpen(false);
- if (htmlWithSession) {
- if (sidebarTargetSessionId) {
- void openHtmlFileByPreference(sidebarTargetSessionId, resolvedAbsPath, t, fileCtx);
+ ctxMenu.onActivate(event, async () => {
+ if (htmlWithSession && sidebarTargetSessionId) {
+ await openHtmlFileByPreference(sidebarTargetSessionId, resolvedAbsPath, t, fileCtx);
+ } else {
+ await onOpen();
}
- return;
- }
- void onOpen();
+ });
};
return (
@@ -1046,17 +1048,13 @@ function FileTargetChip({
tabIndex={0}
title={title}
onClick={activate}
+ onAuxClick={(event) => { if (event.button === 1) activate(event); }}
onContextMenu={ctxMenu.onContextMenu}
onPointerEnter={() => {
if (imagePreviewSrc) setImagePreviewOpen(true);
}}
onPointerLeave={() => setImagePreviewOpen(false)}
- onKeyDown={(e) => {
- // 换掉原生按钮元素后,键盘激活要自己补回来。
- if (e.key !== 'Enter' && e.key !== ' ') return;
- e.preventDefault();
- activate();
- }}
+ onKeyDown={activateInlineLinkFromKeyboard}
className={cn(
'inline rounded-[6px] border-0 px-1 py-0.5',
'font-mono text-14 align-baseline',
@@ -1143,21 +1141,22 @@ function ResolvedLocalLink({
onViewSource: htmlWithSession ? onOpen : undefined,
});
+ const activate = (event: React.MouseEvent<HTMLElement>) => ctxMenu.onActivate(event, async () => {
+ if (htmlWithSession && sidebarTargetSessionId) {
+ await openHtmlFileByPreference(sidebarTargetSessionId, resolvedAbsPath, t, fileCtx);
+ return;
+ }
+ await onOpen();
+ });
+
return (
<>
<a
href={href}
className={MARKDOWN_LINK_CLASS}
- onClick={async (e) => {
- e.preventDefault();
- if (htmlWithSession) {
- if (sidebarTargetSessionId) {
- await openHtmlFileByPreference(sidebarTargetSessionId, resolvedAbsPath, t, fileCtx);
- }
- return;
- }
- await onOpen();
- }}
+ onClick={activate}
+ onKeyDown={activateInlineLinkFromKeyboard}
+ onAuxClick={(event) => { if (event.button === 1) void activate(event); }}
onContextMenu={ctxMenu.onContextMenu}
{...anchorProps}
>
@@ -1475,6 +1474,21 @@ function MarkdownTargetLink({
return allowPrivilegedLinks ? target : stripPrivilegedMarkdownTarget(target);
}, [href, localFileRefs, allowPrivilegedLinks]);
const target = useResolvedMarkdownTarget(initialTarget, workingDir, isStreaming);
+ const openInlineTarget = () => {
+ if (target.kind === 'anchor') {
+ if (!target.id) return;
+ const element = document.getElementById(target.id);
+ if (element) element.scrollIntoView({ behavior: 'smooth', block: 'start' });
+ else toast.error(t('chat.markdownRenderer.anchorNotFound'));
+ } else if (target.kind === 'local-image-url') {
+ setLightboxSrc(rewriteToRemoteMediaOrigin(target.href, remoteMediaOrigin));
+ }
+ };
+ const inlineMenu = useLinkContextMenu(href ?? '', [{
+ label: t('chat.markdownRenderer.openLink'),
+ icon: <ArrowUpRight className="mr-2 h-4 w-4" />,
+ run: openInlineTarget,
+ }]);
if (target.kind === 'audio') {
return <InlineXdtAudioPlayer src={rewriteToRemoteMediaOrigin(target.href, remoteMediaOrigin)} />;
@@ -1549,52 +1563,36 @@ function MarkdownTargetLink({
<a
href={target.href}
className={MARKDOWN_LINK_CLASS}
+ onKeyDown={activateInlineLinkFromKeyboard}
onClick={async (e) => {
e.preventDefault();
- if (target.kind === 'anchor') {
- if (!target.id) return;
- const el = document.getElementById(target.id);
- if (el) {
- el.scrollIntoView({ behavior: 'smooth', block: 'start' });
- } else {
- toast.error(t('chat.markdownRenderer.anchorNotFound'));
- }
- return;
- }
-
if (target.kind === 'external') {
// 有会话上下文:左键按用户偏好直开(内置侧边栏 / 系统浏览器,设置 →
// 个性化 → 链接打开方式);右键弹"打开方式"菜单临时选另一种。
// 修饰键点击(macOS ⌘ / Windows Ctrl)临时强制走系统浏览器,不改偏好。
// 无会话上下文(Market 预览等)保持原有直开默认浏览器。
- if (openWith.isEnabled && sidebarTargetSessionId && !(e.metaKey || e.ctrlKey)) {
- await openUrlByPreference(sidebarTargetSessionId, target.href, t);
- return;
- }
- const res = await window.electronAPI.openExternal(target.href);
- if (!res.success) toast.error(t('chat.markdownRenderer.openLinkFailed'));
- return;
- }
-
- if (target.kind === 'local-image-url') {
- // 远程会话:本机媒体 scheme 链接改写到 cindy-remote-media://(同内嵌图);本地原样。
- setLightboxSrc(rewriteToRemoteMediaOrigin(target.href, remoteMediaOrigin));
+ await activateMessageUrl(e, sidebarTargetSessionId, target.href, t);
return;
}
+ openInlineTarget();
+ }}
+ onAuxClick={(event) => {
+ if (event.button !== 1) return;
+ event.preventDefault();
+ if (target.kind === 'external') void activateMessageUrl(event, sidebarTargetSessionId, target.href, t);
+ else openInlineTarget();
}}
onContextMenu={(e) => {
- // 仅外链有右键"打开方式"菜单;anchor / local-image-url 保持浏览器默认右键。
- if (target.kind !== 'external' || !openWith.isEnabled) return;
- e.preventDefault();
- e.stopPropagation();
- openWith.openAt(e.clientX, e.clientY, target.href);
+ if (target.kind === 'external') openWith.onContextMenu(e, target.href);
+ else inlineMenu.onContextMenu(e);
}}
{...anchorProps}
>
{children}
</a>
{openWith.menu}
+ {inlineMenu.menu}
</>
);
}
diff --git a/apps/desktop/src/renderer/components/chat/ProjectLinkChip.tsx b/apps/desktop/src/renderer/components/chat/ProjectLinkChip.tsx
index 85f679ac06..972d735b9c 100644
--- a/apps/desktop/src/renderer/components/chat/ProjectLinkChip.tsx
+++ b/apps/desktop/src/renderer/components/chat/ProjectLinkChip.tsx
@@ -16,11 +16,13 @@
import { useMemo } from 'react';
import { FolderOpen } from 'lucide-react';
import { useLocation, useNavigate } from 'react-router-dom';
+import { useTranslation } from 'react-i18next';
import { parseProjectDeepLinkHref, projectDisplayName } from '@/lib/deepLink';
import { useSessionNavigationMode } from '@/features/cc-agent/embeddedSessionNavigation';
import { requestProjectFocus } from '@/state/pendingProjectFocus';
import { InlineReferenceChip } from './InlineReferenceChip';
+import { useLinkContextMenu } from './useLinkContextMenu';
export interface ProjectLinkChipProps {
href: string;
@@ -29,32 +31,14 @@ export interface ProjectLinkChipProps {
}
export function ProjectLinkChip({ href, label }: ProjectLinkChipProps) {
+ const { t } = useTranslation();
const navigate = useNavigate();
const location = useLocation();
const navigationMode = useSessionNavigationMode();
const target = useMemo(() => parseProjectDeepLinkHref(href), [href]);
- // 深链形状不合法(理论上被 tokenizer / 渲染分支挡住,防御性兜底)→ 纯文本。
- if (!target) return <span>{label ?? href}</span>;
-
- const display = label?.trim() || projectDisplayName(target.workingDir);
-
- // embedded 会话面板(Orca worker 等)不拥有宿主路由:navigate('/cc-agent')
- // 会把宿主页面整个切走、把用户拽出嵌入上下文——与 SessionLinkChip 同口径,
- // 渲染为不可点的静态 chip(review P2)。
- if (navigationMode === 'sidebar-embedded') {
- return (
- <InlineReferenceChip
- label={display}
- icon={<FolderOpen aria-hidden />}
- tooltip={display}
- ariaLabel={display}
- className="relative top-[-1px] -my-[1px] max-w-[min(240px,55vw)] cursor-default align-middle"
- />
- );
- }
-
const handleClick = () => {
+ if (!target || navigationMode === 'sidebar-embedded') return;
// 与 MainLayout.handleDeepLinkPayload 的 project 分支同语义:发一次性
// focus 信号,消费方(CCAgentSidebarUpper → ExpandedView)不在挂载态时
// 信号沉淀,先 navigate 回 /cc-agent 促其 mount。
@@ -63,15 +47,33 @@ export function ProjectLinkChip({ href, label }: ProjectLinkChipProps) {
const inExpandedView = path.startsWith('/cc-agent') && !path.startsWith('/cc-agent/files/');
if (!inExpandedView) navigate('/cc-agent');
};
+ const linkMenu = useLinkContextMenu(
+ href,
+ navigationMode === 'sidebar-embedded'
+ ? []
+ : [
+ {
+ label: t('chat.markdownRenderer.locateProject'),
+ icon: <FolderOpen className="mr-2 h-4 w-4" />,
+ run: handleClick,
+ },
+ ],
+ );
+ if (!target) return <span>{label ?? href}</span>;
+ const display = label?.trim() || projectDisplayName(target.workingDir);
return (
- <InlineReferenceChip
- label={display}
- icon={<FolderOpen aria-hidden />}
- tooltip={display}
- ariaLabel={display}
- onClick={handleClick}
- className="relative top-[-1px] -my-[1px] max-w-[min(240px,55vw)] align-middle"
- />
+ <>
+ <InlineReferenceChip
+ label={display}
+ icon={<FolderOpen aria-hidden />}
+ tooltip={display}
+ ariaLabel={display}
+ onClick={navigationMode === 'sidebar-embedded' ? undefined : handleClick}
+ onContextMenu={linkMenu.onContextMenu}
+ className="relative top-[-1px] -my-[1px] max-w-[min(240px,55vw)] align-middle"
+ />
+ {linkMenu.menu}
+ </>
);
}
diff --git a/apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx b/apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx
index a2003d5317..3e8a2c6d43 100644
--- a/apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx
+++ b/apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx
@@ -15,8 +15,8 @@
* inline-flex 不打断文本流;不硬编码颜色(规则 16)。
*/
-import { useEffect, useMemo, useRef, useState } from 'react';
-import { CornerDownRight } from 'lucide-react';
+import { useEffect, useMemo, useRef, useState, type MouseEvent } from 'react';
+import { AppWindow, CornerDownRight } from 'lucide-react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
@@ -28,13 +28,19 @@ import { parseSessionDeepLinkHref } from '@/lib/deepLink';
import { getSessionRouteOwnerId, resolveSessionRoute } from '@/lib/orcaSessionIdentity';
import { resolveSessionMessageText } from '@/lib/sessionMessageText';
import * as sessionService from '@/lib/sessionService';
-import { remoteProjectsStore, useRemoteProjectSessions } from '@/features/device-link/remoteProjectsStore';
+import {
+ remoteProjectsStore,
+ useRemoteProjectSessions,
+} from '@/features/device-link/remoteProjectsStore';
import {
useSessionNavigationIntent,
useSessionNavigationMode,
} from '@/features/cc-agent/embeddedSessionNavigation';
import { InlineReferenceChip } from './InlineReferenceChip';
import { QuoteChip } from './QuoteChip';
+import { toast } from '@/lib/toast';
+import { useLinkContextMenu } from './useLinkContextMenu';
+import { activateInlineLinkFromKeyboard, isSeparateLinkActivation } from './linkInteraction';
const MESSAGE_LINK_LABEL_MAX = 240;
@@ -110,28 +116,33 @@ export function SessionLinkChip({ href, label }: SessionLinkChipProps) {
};
}, [sessionId, messageClientId]);
- // 深链形状不合法(理论上被 tokenizer / 渲染分支挡住,防御性兜底)→ 纯文本。
- if (!target || !sessionId) return <span>{label ?? href}</span>;
-
const remoteSession = remoteSessions.find((s) => s.id === sessionId) ?? null;
const remoteTitle = fetchedTitle ? null : remoteSession?.title?.trim() || null;
- const handleClick = () => {
+ const openTarget = async (separate: boolean) => {
+ if (!target || !sessionId) return;
const navigationRequestVersion = ++navigationRequestVersionRef.current;
const resolveTargetRoute = async () => {
- if (targetDeviceId) {
- const selfDeviceId = localDeviceId ?? await window.electronAPI.getDeviceId();
+ let deviceId = targetDeviceId ?? remoteProjectsStore.getSessionDeviceId(sessionId);
+ if (deviceId) {
+ const selfDeviceId = localDeviceId ?? (await window.electronAPI.getDeviceId());
if (navigationRequestVersionRef.current !== navigationRequestVersion) return null;
// 归档任务可能尚未进入远程镜像;先登记链接的归属,再由现有传输层按设备读取。
- if (targetDeviceId !== selfDeviceId) {
- remoteProjectsStore.pinSessionOrigin(targetDeviceId, sessionId);
+ if (deviceId !== selfDeviceId) {
+ remoteProjectsStore.pinSessionOrigin(deviceId, sessionId);
+ } else {
+ deviceId = undefined;
}
}
+ if (separate) {
+ await window.electronAPI.maker.openSessionInNewWindow(sessionId, deviceId, messageClientId);
+ return null;
+ }
return resolveSessionRoute(sessionId, remoteSession);
};
// device-link 远程会话本地无 row,resolveSessionRoute 内部的 sessionService.get
// 会 miss → 远程 Orca 会话被当普通会话路由,后续 redirect 会丢 searchJump 锚点。
// 把远程镜像里的 session 对象直接传入,让 Orca 路由一步到位(Codex review P2)。
- void resolveTargetRoute().then((route) => {
+ await resolveTargetRoute().then((route) => {
if (!route || navigationRequestVersionRef.current !== navigationRequestVersion) return;
reportSessionNavigation?.(sessionId, getSessionRouteOwnerId(route) ?? sessionId);
navigate(
@@ -152,6 +163,31 @@ export function SessionLinkChip({ href, label }: SessionLinkChipProps) {
);
});
};
+ const handleClick = (event: MouseEvent<HTMLElement>) => {
+ event.preventDefault();
+ event.stopPropagation();
+ void openTarget(isSeparateLinkActivation(event) || navigationMode === 'sidebar-embedded').catch(
+ () => toast.error(t('chat.markdownRenderer.openLinkFailed')),
+ );
+ };
+ const linkMenu = useLinkContextMenu(href, [
+ ...(navigationMode === 'sidebar-embedded'
+ ? []
+ : [
+ {
+ label: t('chat.markdownRenderer.openInCurrentWindow'),
+ icon: <CornerDownRight className="mr-2 h-4 w-4" />,
+ run: () => openTarget(false),
+ },
+ ]),
+ {
+ label: t('ccAgent.sidebar.sessionMenu.openInNewWindow'),
+ shortcut: t('chat.markdownRenderer.shiftClick'),
+ icon: <AppWindow className="mr-2 h-4 w-4" />,
+ run: () => openTarget(true),
+ },
+ ]);
+ if (!target || !sessionId) return <span>{label ?? href}</span>;
// 未起名会话过投影再显示:chip 直接摆在消息流里,原样会露出内部哨兵 "New Maker"。
const resolvedTitle = fetchedTitle ?? remoteTitle;
const display =
@@ -176,53 +212,45 @@ export function SessionLinkChip({ href, label }: SessionLinkChipProps) {
);
// items-center 保证 pill 保持自身高度(不被 align-items: stretch 撑成椭圆)。
const messageClass = 'inline-flex max-w-full items-center align-middle';
- if (navigationMode === 'sidebar-embedded') {
- return (
- <span
+ return (
+ <>
+ <button
+ type="button"
data-session-message-link=""
+ data-split-pane-route-action=""
+ aria-label={visibleMessageLabel}
title={display}
- className={cn(messageClass, 'cursor-default')}
+ onClick={handleClick}
+ onAuxClick={(event) => {
+ if (event.button === 1) handleClick(event);
+ }}
+ onKeyDown={activateInlineLinkFromKeyboard}
+ onContextMenu={linkMenu.onContextMenu}
+ className={cn(messageClass, 'cursor-pointer')}
>
{messageContent}
- </span>
- );
- }
- return (
- <button
- type="button"
- data-session-message-link=""
- data-split-pane-route-action=""
- aria-label={visibleMessageLabel}
- title={display}
- onClick={handleClick}
- className={cn(messageClass, 'cursor-pointer')}
- >
- {messageContent}
- </button>
+ </button>
+ {linkMenu.menu}
+ </>
);
}
- if (navigationMode === 'sidebar-embedded') {
- return (
+ return (
+ <>
<InlineReferenceChip
label={display}
icon={<CornerDownRight aria-hidden />}
tooltip={display}
ariaLabel={display}
- className="relative top-[-1px] -my-[1px] max-w-[min(240px,55vw)] cursor-default align-middle"
+ onClick={handleClick}
+ onAuxClick={(event) => {
+ if (event.button === 1) handleClick(event);
+ }}
+ onContextMenu={linkMenu.onContextMenu}
+ splitPaneRouteAction
+ className="relative top-[-1px] -my-[1px] max-w-[min(240px,55vw)] align-middle"
/>
- );
- }
-
- return (
- <InlineReferenceChip
- label={display}
- icon={<CornerDownRight aria-hidden />}
- tooltip={display}
- ariaLabel={display}
- onClick={handleClick}
- splitPaneRouteAction
- className="relative top-[-1px] -my-[1px] max-w-[min(240px,55vw)] align-middle"
- />
+ {linkMenu.menu}
+ </>
);
}
diff --git a/apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx b/apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx
index 995536533e..2d4e5cb445 100644
--- a/apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx
+++ b/apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx
@@ -29,6 +29,7 @@ import { useChatSessionFile } from './ChatSessionFileContext';
import { TextLightbox } from './TextLightbox';
import { useFileChipContextMenu } from './useFileChipContextMenu';
import { isHtmlFilePath } from './useOpenWithMenu';
+import { activateInlineLinkFromKeyboard } from './linkInteraction';
const MAX_VISIBLE_FILES = 3;
@@ -66,7 +67,9 @@ function TurnChangeFileRow({
ref={fileRowRef}
type="button"
title={absolutePath}
- onClick={onOpenReview}
+ onClick={(event) => contextMenu.onActivate(event, onOpenReview)}
+ onAuxClick={(event) => { if (event.button === 1) contextMenu.onActivate(event, onOpenReview); }}
+ onKeyDown={activateInlineLinkFromKeyboard}
onContextMenu={contextMenu.onContextMenu}
className="flex h-9 w-full items-center gap-2 rounded-lg px-2 text-left transition-colors hover:bg-[var(--surface-hover)]"
>
diff --git a/apps/desktop/src/renderer/components/chat/UserAttachmentChip.tsx b/apps/desktop/src/renderer/components/chat/UserAttachmentChip.tsx
index aa3f18d775..1a7d8fc7d8 100644
--- a/apps/desktop/src/renderer/components/chat/UserAttachmentChip.tsx
+++ b/apps/desktop/src/renderer/components/chat/UserAttachmentChip.tsx
@@ -18,6 +18,7 @@ import {
import { isBrowserOpenablePath } from '../../../shared/browserOpenableExts';
import { useChatSessionFile } from './ChatSessionFileContext';
import { useFileChipContextMenu } from './useFileChipContextMenu';
+import { activateInlineLinkFromKeyboard, linkMenuPosition } from './linkInteraction';
/**
* UserAttachmentChip — 用户消息下方的文件附件 chip(与正文里的 `@file` 引用
@@ -88,20 +89,30 @@ export function UserAttachmentChip({
aria-label={
downloadOnly ? t('chat.userMessage.saveAttachmentAs', { name: file.name }) : undefined
}
+ onKeyDown={activateInlineLinkFromKeyboard}
onClick={async (e) => {
if (downloadOnly) {
await saveChatAttachmentWithToasts(sessionFileCtx, file);
return;
}
const chip = e.currentTarget;
- if (!(await shouldOpenTextLightboxForOrigin(sessionFileCtx, file.path))) return;
- onOpenTextPreview(chip);
+ ctxMenu.onActivate(e, async () => {
+ if (!(await shouldOpenTextLightboxForOrigin(sessionFileCtx, file.path))) return;
+ onOpenTextPreview(chip);
+ });
+ }}
+ onAuxClick={(event) => {
+ if (event.button !== 1 || downloadOnly) return;
+ const chip = event.currentTarget;
+ ctxMenu.onActivate(event, async () => {
+ if (await shouldOpenTextLightboxForOrigin(sessionFileCtx, file.path)) onOpenTextPreview(chip);
+ });
}}
onContextMenu={(e) => {
if (downloadOnly) {
e.preventDefault();
e.stopPropagation();
- setSaveMenuPos({ x: e.clientX, y: e.clientY });
+ setSaveMenuPos(linkMenuPosition(e));
return;
}
ctxMenu.onContextMenu(e);
diff --git a/apps/desktop/src/renderer/components/chat/UserMessage.tsx b/apps/desktop/src/renderer/components/chat/UserMessage.tsx
index 3668fff8cd..1369a48359 100644
--- a/apps/desktop/src/renderer/components/chat/UserMessage.tsx
+++ b/apps/desktop/src/renderer/components/chat/UserMessage.tsx
@@ -95,6 +95,7 @@ import { UserMessageEditBox } from './UserMessageEditBox';
import HookTaskCard from './HookTaskCard';
import { useFileChipContextMenu } from './useFileChipContextMenu';
import { UserAttachmentChip } from './UserAttachmentChip';
+import { UserMessageImageLink } from './UserMessageImageLink';
import {
AUTOMATION_USER_MESSAGE_VISUAL_LINE_THRESHOLD,
LONG_USER_MESSAGE_VISUAL_LINE_THRESHOLD,
@@ -262,7 +263,10 @@ function UserFileChip({
tooltip={refText}
tooltipMono
ariaLabel={fileName}
- onClick={onClick}
+ onClick={(event) => ctxMenu.onActivate(event, () => onClick(event))}
+ onAuxClick={(event) => {
+ if (event.button === 1) ctxMenu.onActivate(event, () => onClick(event));
+ }}
onContextMenu={ctxMenu.onContextMenu}
className="relative top-[-1px] -my-[1px] max-w-[min(240px,55vw)] align-middle"
/>
@@ -327,15 +331,11 @@ function renderTextWithLinks(
} else {
const p = match.text;
result.push(
- <button
+ <UserMessageImageLink
key={`${keyPrefix}-img-${match.index}`}
- type="button"
- onClick={() => onImageClick?.(toLocalFileUrl(p))}
- // 同 UserMessageUrlLink:可点 = 正文色 + 常显下划线,不再靠 --msg-link 颜色。
- className="underline underline-offset-2 cursor-pointer break-all"
- >
- {p}
- </button>,
+ path={p}
+ onOpen={onImageClick}
+ />,
);
}
lastIndex = match.index + match.length;
diff --git a/apps/desktop/src/renderer/components/chat/UserMessageImageLink.tsx b/apps/desktop/src/renderer/components/chat/UserMessageImageLink.tsx
new file mode 100644
index 0000000000..06399f3282
--- /dev/null
+++ b/apps/desktop/src/renderer/components/chat/UserMessageImageLink.tsx
@@ -0,0 +1,33 @@
+import { toLocalFileUrl } from '@/lib/localPathResolver';
+import { activateInlineLinkFromKeyboard } from './linkInteraction';
+import { useFileChipContextMenu } from './useFileChipContextMenu';
+
+/** Bare image paths in user messages use the same file actions as Markdown references. */
+export function UserMessageImageLink({
+ path,
+ onOpen,
+}: {
+ path: string;
+ onOpen?: (url: string) => void;
+}) {
+ const fileMenu = useFileChipContextMenu({ getAbsPath: () => path });
+ const open = () => onOpen?.(toLocalFileUrl(path));
+ return (
+ <>
+ <span
+ role="button"
+ tabIndex={0}
+ onClick={(event) => fileMenu.onActivate(event, open)}
+ onAuxClick={(event) => {
+ if (event.button === 1) fileMenu.onActivate(event, open);
+ }}
+ onKeyDown={activateInlineLinkFromKeyboard}
+ onContextMenu={fileMenu.onContextMenu}
+ className="underline underline-offset-2 cursor-pointer break-all"
+ >
+ {path}
+ </span>
+ {fileMenu.menu}
+ </>
+ );
+}
diff --git a/apps/desktop/src/renderer/components/chat/UserMessageUrlLink.tsx b/apps/desktop/src/renderer/components/chat/UserMessageUrlLink.tsx
index b323bbbd30..87c8af508c 100644
--- a/apps/desktop/src/renderer/components/chat/UserMessageUrlLink.tsx
+++ b/apps/desktop/src/renderer/components/chat/UserMessageUrlLink.tsx
@@ -10,8 +10,8 @@ import type { MouseEvent } from 'react';
import { useTranslation } from 'react-i18next';
import { useSidebarTargetSessionId } from '@/features/cc-agent/embeddedSessionNavigation';
-import { toast } from '@/lib/toast';
-import { openUrlByPreference, useOpenWithMenu } from './useOpenWithMenu';
+import { activateMessageUrl, useOpenWithMenu } from './useOpenWithMenu';
+import { activateInlineLinkFromKeyboard } from './linkInteraction';
export function UserMessageUrlLink({ url, sessionId }: { url: string; sessionId?: string }) {
const { t } = useTranslation();
@@ -19,15 +19,7 @@ export function UserMessageUrlLink({ url, sessionId }: { url: string; sessionId?
const openWith = useOpenWithMenu({ sessionId });
async function handleClick(event: MouseEvent<HTMLAnchorElement>): Promise<void> {
- event.preventDefault();
-
- if (sidebarTargetSessionId && !(event.metaKey || event.ctrlKey)) {
- await openUrlByPreference(sidebarTargetSessionId, url, t);
- return;
- }
-
- const res = await window.electronAPI.openExternal(url);
- if (!res.success) toast.error(t('chat.markdownRenderer.openLinkFailed'));
+ await activateMessageUrl(event, sidebarTargetSessionId, url, t);
}
return (
@@ -39,11 +31,12 @@ export function UserMessageUrlLink({ url, sessionId }: { url: string; sessionId?
// 悬停才出下划线,而用户消息气泡里同样需要「不动鼠标就能看出哪个能点」。
className="underline underline-offset-2 cursor-pointer"
onClick={handleClick}
+ onKeyDown={activateInlineLinkFromKeyboard}
+ onAuxClick={(event) => {
+ if (event.button === 1) void handleClick(event);
+ }}
onContextMenu={(event) => {
- if (!openWith.isEnabled) return;
- event.preventDefault();
- event.stopPropagation();
- openWith.openAt(event.clientX, event.clientY, url);
+ openWith.onContextMenu(event, url);
}}
>
{url}
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/GeneratedFilesCard.localSeed.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/GeneratedFilesCard.localSeed.test.tsx
index 7759305014..b258c3be85 100644
--- a/apps/desktop/src/renderer/components/chat/__tests__/GeneratedFilesCard.localSeed.test.tsx
+++ b/apps/desktop/src/renderer/components/chat/__tests__/GeneratedFilesCard.localSeed.test.tsx
@@ -10,7 +10,9 @@ import {
import type { GeneratedFileRef } from '@/lib/generatedFiles';
vi.mock('../useFileChipContextMenu', () => ({
- useFileChipContextMenu: () => ({ menu: null, onContextMenu: vi.fn() }),
+ useFileChipContextMenu: () => ({ menu: null, onContextMenu: vi.fn(),
+ onActivate: (_event: unknown, openDefault: () => void) => openDefault(),
+ }),
}));
vi.mock('react-i18next', async (importOriginal) => ({
...(await importOriginal<typeof import('react-i18next')>()),
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/GeneratedFilesCard.remote.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/GeneratedFilesCard.remote.test.tsx
index 888c7d65ca..d94c0fdca8 100644
--- a/apps/desktop/src/renderer/components/chat/__tests__/GeneratedFilesCard.remote.test.tsx
+++ b/apps/desktop/src/renderer/components/chat/__tests__/GeneratedFilesCard.remote.test.tsx
@@ -6,7 +6,9 @@ import { GeneratedFilesCard } from '../GeneratedFilesCard';
import { _clearRemotePathVerdictCache } from '@/lib/remoteFileOpen';
vi.mock('../useFileChipContextMenu', () => ({
- useFileChipContextMenu: () => ({ menu: null, onContextMenu: vi.fn() }),
+ useFileChipContextMenu: () => ({ menu: null, onContextMenu: vi.fn(),
+ onActivate: (_event: unknown, openDefault: () => void) => openDefault(),
+ }),
}));
vi.mock('react-i18next', async (importOriginal) => ({
...(await importOriginal<typeof import('react-i18next')>()),
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/ProjectLinkChip.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/ProjectLinkChip.test.tsx
new file mode 100644
index 0000000000..21c156a2ae
--- /dev/null
+++ b/apps/desktop/src/renderer/components/chat/__tests__/ProjectLinkChip.test.tsx
@@ -0,0 +1,60 @@
+// @vitest-environment jsdom
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({ navigate: vi.fn(), focus: vi.fn(), writeText: vi.fn() }));
+vi.mock('react-router-dom', () => ({
+ useNavigate: () => mocks.navigate,
+ useLocation: () => ({ pathname: '/settings' }),
+}));
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+vi.mock('@/state/pendingProjectFocus', () => ({ requestProjectFocus: mocks.focus }));
+vi.mock('@/lib/toast', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
+
+import { ProjectLinkChip } from '../ProjectLinkChip';
+import { SessionNavigationModeProvider } from '@/features/cc-agent/embeddedSessionNavigation';
+
+const href = 'cindy://project/%2Fwork%2FMy%20Project';
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.writeText.mockResolvedValue(undefined);
+ Object.defineProperty(navigator, 'clipboard', {
+ configurable: true,
+ value: { writeText: mocks.writeText },
+ });
+});
+afterEach(cleanup);
+
+describe('ProjectLinkChip actions', () => {
+ it('keeps normal activation focused on the project', () => {
+ render(<ProjectLinkChip href={href} />);
+ fireEvent.click(screen.getByRole('button', { name: 'My Project' }));
+ expect(mocks.focus).toHaveBeenCalledWith('/work/My Project');
+ expect(mocks.navigate).toHaveBeenCalledWith('/cc-agent');
+ });
+
+ it('copies a project link from the keyboard menu without navigating', async () => {
+ render(<ProjectLinkChip href={href} />);
+ fireEvent.keyDown(screen.getByRole('button', { name: 'My Project' }), { key: 'ContextMenu' });
+ fireEvent.click(
+ await screen.findByRole('menuitem', { name: 'chat.markdownRenderer.copyLink' }),
+ );
+ await waitFor(() => expect(mocks.writeText).toHaveBeenCalledWith(href));
+ expect(mocks.focus).not.toHaveBeenCalled();
+ expect(mocks.navigate).not.toHaveBeenCalled();
+ });
+
+ it('offers copy in embedded content without exposing host-route actions', async () => {
+ render(
+ <SessionNavigationModeProvider mode="sidebar-embedded">
+ <ProjectLinkChip href={href} />
+ </SessionNavigationModeProvider>,
+ );
+ fireEvent.contextMenu(screen.getByRole('button', { name: 'My Project' }));
+ expect(
+ await screen.findByRole('menuitem', { name: 'chat.markdownRenderer.copyLink' }),
+ ).toBeTruthy();
+ expect(screen.queryByRole('menuitem', { name: 'chat.markdownRenderer.locateProject' })).toBeNull();
+ expect(mocks.navigate).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/TurnChangesCard.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/TurnChangesCard.test.tsx
index 2586aff3c0..8f65704836 100644
--- a/apps/desktop/src/renderer/components/chat/__tests__/TurnChangesCard.test.tsx
+++ b/apps/desktop/src/renderer/components/chat/__tests__/TurnChangesCard.test.tsx
@@ -93,6 +93,7 @@ describe('TurnChangesCard file actions', () => {
});
mocks.useFileChipContextMenu.mockReturnValue({
onContextMenu: mocks.onContextMenu,
+ onActivate: (_event: unknown, openDefault: () => void) => openDefault(),
openAt: vi.fn(),
menu: <div>file-context-menu</div> as ReactNode,
});
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/UserMessageUrlLink.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/UserMessageUrlLink.test.tsx
index c9e06c31f4..537afad7ed 100644
--- a/apps/desktop/src/renderer/components/chat/__tests__/UserMessageUrlLink.test.tsx
+++ b/apps/desktop/src/renderer/components/chat/__tests__/UserMessageUrlLink.test.tsx
@@ -14,6 +14,7 @@ vi.mock('@/components/ui/dropdown-menu', () => ({
DropdownMenuTrigger: ({ children }: { children: ReactNode }) => <>{children}</>,
DropdownMenuContent: ({ children }: { children: ReactNode }) => <div>{children}</div>,
DropdownMenuSeparator: () => <hr />,
+ DropdownMenuShortcut: ({ children }: { children: ReactNode }) => <span aria-hidden>{children}</span>,
DropdownMenuItem: ({ children, onClick }: { children: ReactNode; onClick?: () => void }) => (
<button type="button" onClick={onClick}>
{children}
@@ -141,13 +142,30 @@ describe('UserMessageUrlLink', () => {
expect(screen.getByText('chat.markdownRenderer.copyLink')).toBeTruthy();
});
- it('keeps Ctrl-click as a temporary external-browser override', async () => {
+ it.each([{ ctrlKey: true }, { metaKey: true }, { shiftKey: true }])('uses %j as a temporary external-browser override', async (modifier) => {
localStorage.setItem('chat.webLinkOpenPreference', 'sidebar');
render(<UserMessageUrlLink url={URL} sessionId="session-a" />);
- fireEvent.click(screen.getByRole('link'), { ctrlKey: true });
+ fireEvent.click(screen.getByRole('link'), modifier);
await waitFor(() => expect(openExternal).toHaveBeenCalledWith(URL));
expect(openUrlInSidebarBrowser).not.toHaveBeenCalled();
+ expect(localStorage.getItem('chat.webLinkOpenPreference')).toBe('sidebar');
+ });
+
+ it('supports middle click and Shift+Enter without changing the sidebar preference', async () => {
+ render(<UserMessageUrlLink url={LOCAL_URL} sessionId="session-a" />);
+ fireEvent(screen.getByRole('link'), new MouseEvent('auxclick', { bubbles: true, button: 1 }));
+ fireEvent.keyDown(screen.getByRole('link'), { key: 'Enter', shiftKey: true });
+ await waitFor(() => expect(openExternal).toHaveBeenCalledTimes(2));
+ expect(openUrlInSidebarBrowser).not.toHaveBeenCalled();
+ });
+
+ it('offers copy and system-browser actions without a session, including keyboard access', () => {
+ render(<UserMessageUrlLink url={URL} />);
+ fireEvent.keyDown(screen.getByRole('link'), { key: 'F10', shiftKey: true });
+ expect(screen.getByText('chat.markdownRenderer.copyLink')).toBeTruthy();
+ expect(screen.getByText('chat.markdownRenderer.openInDefaultBrowser')).toBeTruthy();
+ expect(screen.queryByText('chat.markdownRenderer.openInSidebarBrowser')).toBeNull();
});
});
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/embeddedSessionNavigation.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/embeddedSessionNavigation.test.tsx
index 7406030259..955d220b02 100644
--- a/apps/desktop/src/renderer/components/chat/__tests__/embeddedSessionNavigation.test.tsx
+++ b/apps/desktop/src/renderer/components/chat/__tests__/embeddedSessionNavigation.test.tsx
@@ -7,6 +7,9 @@ import type { ReactNode } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => ({
+ openSessionInNewWindow: vi.fn(async () => undefined),
+ writeText: vi.fn(async () => undefined),
+ error: vi.fn(),
navigate: vi.fn(),
pinSessionOrigin: vi.fn(),
resolveSessionRoute: vi.fn(async (sessionId: string) => `/cc-agent/${sessionId}`),
@@ -45,6 +48,7 @@ vi.mock('@/features/device-link/remoteProjectsStore', () => ({
},
}));
vi.mock('@/lib/sessionService', () => ({ get: mocks.getSession }));
+vi.mock('@/lib/toast', () => ({ toast: { error: mocks.error, success: vi.fn() } }));
vi.mock('@/contexts/AuthContext', () => ({ useOptionalAuthDeviceId: () => 'this-mac' }));
vi.mock('@/features/device-link/useDeviceLinkDeviceList', () => ({
useDeviceLinkDeviceList: () => [
@@ -100,6 +104,12 @@ function SidebarTargetProbe({ contentSessionId }: { contentSessionId?: string })
describe('sidebar-embedded session navigation boundary', () => {
beforeEach(() => {
vi.clearAllMocks();
+ Object.defineProperty(window, 'electronAPI', {
+ configurable: true, value: { maker: { openSessionInNewWindow: mocks.openSessionInNewWindow } },
+ });
+ Object.defineProperty(navigator, 'clipboard', {
+ configurable: true, value: { writeText: mocks.writeText },
+ });
});
it('keeps worker content identity while targeting the visible Lead sidebar bucket', () => {
@@ -115,10 +125,12 @@ describe('sidebar-embedded session navigation boundary', () => {
expect(screen.getByTestId('sidebar-target').textContent).toBe('');
});
- it('renders session links as static chips without resolving or navigating', async () => {
+ it('opens embedded session links in a separate window without taking the host route', async () => {
render(embedded(<SessionLinkChip href="xdt-maker://session/session-a" label="Session A" />));
- expect(screen.queryByRole('button')).toBeNull();
+ fireEvent.click(screen.getByRole('button', { name: 'Session A' }));
+ await waitFor(() => expect(mocks.openSessionInNewWindow)
+ .toHaveBeenCalledWith('session-a', undefined, null));
const chip = screen.getByText('Session A').closest('[data-inline-reference-chip]');
expect(chip).not.toBeNull();
expect(chip?.getAttribute('title')).toBeNull();
@@ -126,6 +138,65 @@ describe('sidebar-embedded session navigation boundary', () => {
expect(mocks.navigate).not.toHaveBeenCalled();
});
+ it.each([{ shiftKey: true }, { metaKey: true }, { ctrlKey: true }])(
+ 'opens remote task links separately for modifier %j, keeping the message anchor', async (modifier) => {
+ const onNavigate = vi.fn();
+ render(splitPane(<SessionLinkChip
+ href="cindy://session/remote-task?device=remote-mac&message=m%2F1" label="Remote task"
+ />, onNavigate));
+ fireEvent.click(screen.getByRole('button', { name: 'Remote task' }), modifier);
+ await waitFor(() => expect(mocks.openSessionInNewWindow)
+ .toHaveBeenCalledWith('remote-task', 'remote-mac', 'm/1'));
+ expect(mocks.navigate).not.toHaveBeenCalled();
+ expect(onNavigate).not.toHaveBeenCalled();
+ },
+ );
+
+ it('supports Shift+Enter on an inline task chip', async () => {
+ render(<SessionLinkChip href="cindy://session/local?device=this-mac" label="Local" />);
+ fireEvent.keyDown(screen.getByRole('button', { name: 'Local' }), { key: 'Enter', shiftKey: true });
+ await waitFor(() => expect(mocks.openSessionInNewWindow).toHaveBeenCalledWith('local', undefined, null));
+ expect(mocks.navigate).not.toHaveBeenCalled();
+ });
+
+ it('supports middle click without navigating the source pane', async () => {
+ render(<SessionLinkChip href="cindy://session/local" label="Local" />);
+ fireEvent(screen.getByRole('button', { name: 'Local' }), new MouseEvent('auxclick', { bubbles: true, button: 1 }));
+ await waitFor(() => expect(mocks.openSessionInNewWindow).toHaveBeenCalledWith('local', undefined, null));
+ expect(mocks.navigate).not.toHaveBeenCalled();
+ });
+
+ it('offers the same new-window action in the context menu without triggering parent clicks', async () => {
+ const parentClick = vi.fn();
+ render(<div onClick={parentClick}><SessionLinkChip
+ href="cindy://session/remote-task?device=remote-mac" label="Remote task"
+ /></div>);
+ fireEvent.contextMenu(screen.getByRole('button', { name: 'Remote task' }), { clientX: 12, clientY: 24 });
+ fireEvent.click(await screen.findByRole('menuitem', { name: 'ccAgent.sidebar.sessionMenu.openInNewWindow' }));
+ await waitFor(() => expect(mocks.openSessionInNewWindow).toHaveBeenCalledWith('remote-task', 'remote-mac', null));
+ expect(mocks.navigate).not.toHaveBeenCalled();
+ expect(parentClick).not.toHaveBeenCalled();
+ });
+
+ it('opens the menu with Shift+F10 and copies the complete link', async () => {
+ const href = 'cindy://session/remote-task?device=remote-mac&message=m%2F1';
+ render(<SessionLinkChip href={href} label="Remote task" />);
+ const link = screen.getByRole('button', { name: 'Remote task' });
+ fireEvent.keyDown(link, { key: 'F10', shiftKey: true });
+ fireEvent.click(await screen.findByRole('menuitem', { name: 'chat.markdownRenderer.copyLink' }));
+ await waitFor(() => expect(mocks.writeText).toHaveBeenCalledWith(href));
+ expect(mocks.openSessionInNewWindow).not.toHaveBeenCalled();
+ expect(mocks.navigate).not.toHaveBeenCalled();
+ });
+
+ it('reports a rejected window-open request and leaves the source pane intact', async () => {
+ mocks.openSessionInNewWindow.mockRejectedValueOnce(new Error('unavailable'));
+ render(<SessionLinkChip href="cindy://session/local" label="Local" />);
+ fireEvent.click(screen.getByRole('button', { name: 'Local' }), { shiftKey: true });
+ await waitFor(() => expect(mocks.error).toHaveBeenCalledWith('chat.markdownRenderer.openLinkFailed'));
+ expect(mocks.navigate).not.toHaveBeenCalled();
+ });
+
it('routes an unmirrored remote history link through its host before resolving the task', async () => {
render(<SessionLinkChip href="cindy://session/archived-task?device=remote-mac" />);
expect(mocks.getSession).not.toHaveBeenCalled();
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/messageLinkActions.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/messageLinkActions.test.tsx
new file mode 100644
index 0000000000..7fe2b94b5f
--- /dev/null
+++ b/apps/desktop/src/renderer/components/chat/__tests__/messageLinkActions.test.tsx
@@ -0,0 +1,96 @@
+// @vitest-environment jsdom
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ openExternal: vi.fn(async () => ({ success: true })),
+ openPath: vi.fn(async () => ({ success: true })),
+ writeText: vi.fn(async () => undefined),
+ sidebar: vi.fn(async () => undefined),
+}));
+vi.mock('react-i18next', async (original) => ({
+ ...(await original<typeof import('react-i18next')>()),
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+vi.mock('@/features/right-sidebar/lib/openInSidebarBrowser', () => ({
+ openUrlInSidebarBrowser: mocks.sidebar,
+ pathToFileUrl: (path: string) => `file://${path}`,
+}));
+vi.mock('@/lib/toast', () => ({ toast: { error: vi.fn(), success: vi.fn() } }));
+
+import { MarkdownRenderer } from '../MarkdownRenderer';
+import { UserMessageImageLink } from '../UserMessageImageLink';
+import { _resetLinkOpenPreferenceForTests } from '@/hooks/useLinkOpenPreference';
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ localStorage.clear();
+ _resetLinkOpenPreferenceForTests();
+ Object.defineProperty(window, 'electronAPI', {
+ configurable: true,
+ value: { openExternal: mocks.openExternal, openPath: mocks.openPath },
+ });
+ Object.defineProperty(navigator, 'clipboard', {
+ configurable: true,
+ value: { writeText: mocks.writeText },
+ });
+});
+afterEach(cleanup);
+
+describe('message link entry points', () => {
+ it('uses the same preference and Shift override for assistant Markdown URLs', async () => {
+ render(
+ <MarkdownRenderer
+ content="[Preview](http://localhost:3000)"
+ currentSessionId="task"
+ workingDir="/workspace"
+ />,
+ );
+ const link = screen.getByRole('link', { name: 'Preview' });
+ fireEvent.click(link);
+ await waitFor(() =>
+ expect(mocks.sidebar).toHaveBeenCalledWith('task', 'http://localhost:3000'),
+ );
+ fireEvent.click(link, { shiftKey: true });
+ await waitFor(() => expect(mocks.openExternal).toHaveBeenCalledWith('http://localhost:3000'));
+ expect(mocks.sidebar).toHaveBeenCalledOnce();
+ });
+
+ it('copies assistant URLs from a keyboard menu even without a task context', async () => {
+ render(<MarkdownRenderer content="[Website](https://example.com)" workingDir="/workspace" />);
+ fireEvent.keyDown(screen.getByRole('link', { name: 'Website' }), {
+ key: 'F10',
+ shiftKey: true,
+ });
+ fireEvent.click(
+ await screen.findByRole('menuitem', { name: 'chat.markdownRenderer.copyLink' }),
+ );
+ await waitFor(() => expect(mocks.writeText).toHaveBeenCalledWith('https://example.com'));
+ expect(mocks.openExternal).not.toHaveBeenCalled();
+ });
+
+ it('provides a copy menu for in-message heading anchors', async () => {
+ render(<MarkdownRenderer content="[Details](#details)" workingDir="/workspace" />);
+ fireEvent.contextMenu(screen.getByRole('link', { name: 'Details' }));
+ fireEvent.click(
+ await screen.findByRole('menuitem', { name: 'chat.markdownRenderer.copyLink' }),
+ );
+ await waitFor(() => expect(mocks.writeText).toHaveBeenCalledWith('#details'));
+ expect(mocks.openExternal).not.toHaveBeenCalled();
+ });
+
+ it('gives bare user image paths preview, separate-open and path-copy actions', async () => {
+ const preview = vi.fn();
+ render(<UserMessageImageLink path="/images/example.png" onOpen={preview} />);
+ const link = screen.getByRole('button', { name: '/images/example.png' });
+ fireEvent.click(link);
+ expect(preview).toHaveBeenCalledOnce();
+ fireEvent.click(link, { shiftKey: true });
+ await waitFor(() => expect(mocks.openPath).toHaveBeenCalledWith('/images/example.png'));
+ fireEvent.keyDown(link, { key: 'ContextMenu' });
+ fireEvent.click(
+ await screen.findByRole('menuitem', { name: 'chat.markdownRenderer.copyFilePath' }),
+ );
+ await waitFor(() => expect(mocks.writeText).toHaveBeenCalledWith('/images/example.png'));
+ });
+});
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/sidebarEmbeddedActionTarget.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/sidebarEmbeddedActionTarget.test.tsx
index efda1ddcdb..7a0b41014e 100644
--- a/apps/desktop/src/renderer/components/chat/__tests__/sidebarEmbeddedActionTarget.test.tsx
+++ b/apps/desktop/src/renderer/components/chat/__tests__/sidebarEmbeddedActionTarget.test.tsx
@@ -14,6 +14,9 @@ vi.mock('@/components/ui/dropdown-menu', () => ({
DropdownMenuTrigger: ({ children }: { children: ReactNode }) => <>{children}</>,
DropdownMenuContent: ({ children }: { children: ReactNode }) => <div>{children}</div>,
DropdownMenuSeparator: () => <hr />,
+ DropdownMenuShortcut: ({ children }: { children: ReactNode }) => (
+ <span aria-hidden>{children}</span>
+ ),
DropdownMenuItem: ({ children, onClick }: { children: ReactNode; onClick?: () => void }) => (
<button type="button" onClick={onClick}>
{children}
@@ -56,9 +59,10 @@ import { ChatSessionFileProvider } from '../ChatSessionFileContext';
import { useFileChipContextMenu } from '../useFileChipContextMenu';
import { useOpenWithMenu } from '../useOpenWithMenu';
-function ActionProbe() {
+function ActionProbe({ html = false }: { html?: boolean }) {
const menu = useFileChipContextMenu({
- getAbsPath: () => '/repo/src/index.html',
+ getAbsPath: () => (html ? '/repo/src/index.html' : '/repo/src/index.md'),
+ canOpenInBrowser: html,
sidebarOpenSessionId: 'worker-a',
});
return (
@@ -99,10 +103,7 @@ function LinkActionProbe() {
function wrapper(children: ReactNode) {
return (
- <SessionNavigationModeProvider
- mode="sidebar-embedded"
- sidebarTargetSessionId="lead-a"
- >
+ <SessionNavigationModeProvider mode="sidebar-embedded" sidebarTargetSessionId="lead-a">
<ChatSessionFileProvider
value={{
sessionId: 'worker-a',
@@ -119,27 +120,30 @@ function wrapper(children: ReactNode) {
describe('sidebar-embedded action target', () => {
beforeEach(() => {
vi.clearAllMocks();
- Object.defineProperty(window, 'electronAPI', { configurable: true, value: {
- fileBrowser: { previewHtml: vi.fn(async () => ({ ok: true, url: 'http://127.0.0.1:12345/preview/' })) },
- } });
+ Object.defineProperty(window, 'electronAPI', {
+ configurable: true,
+ value: {
+ fileBrowser: {
+ previewHtml: vi.fn(async () => ({ ok: true, url: 'http://127.0.0.1:12345/preview/' })),
+ },
+ },
+ });
});
it('opens file-browser and web-browser tabs in the visible Lead bucket', async () => {
- render(wrapper(<ActionProbe />));
+ const { rerender } = render(wrapper(<ActionProbe />));
fireEvent.click(screen.getByText('open-menu'));
fireEvent.click(screen.getByText('chat.markdownRenderer.openInSidebarFileBrowser'));
await waitFor(() =>
- expect(openFileInSidebarFileBrowser).toHaveBeenCalledWith('lead-a', 'src/index.html'),
+ expect(openFileInSidebarFileBrowser).toHaveBeenCalledWith('lead-a', 'src/index.md'),
);
+ rerender(wrapper(<ActionProbe html />));
fireEvent.click(screen.getByText('open-menu'));
fireEvent.click(screen.getByText('chat.markdownRenderer.openInSidebarBrowser'));
await waitFor(() =>
- expect(openUrlInSidebarBrowser).toHaveBeenCalledWith(
- 'lead-a',
- 'file:///repo/src/index.html',
- ),
+ expect(openUrlInSidebarBrowser).toHaveBeenCalledWith('lead-a', 'file:///repo/src/index.html'),
);
});
diff --git a/apps/desktop/src/renderer/components/chat/linkInteraction.ts b/apps/desktop/src/renderer/components/chat/linkInteraction.ts
new file mode 100644
index 0000000000..741f68a8ed
--- /dev/null
+++ b/apps/desktop/src/renderer/components/chat/linkInteraction.ts
@@ -0,0 +1,42 @@
+import type { KeyboardEvent, MouseEvent as ReactMouseEvent } from 'react';
+
+/** Leave the current reading surface intact; all message link renderers share this gesture. */
+export function isSeparateLinkActivation(event: {
+ shiftKey?: boolean;
+ metaKey?: boolean;
+ ctrlKey?: boolean;
+ button?: number;
+}): boolean {
+ return Boolean(event.shiftKey || event.metaKey || event.ctrlKey || event.button === 1);
+}
+
+/** Give anchors and inline chips the same keyboard activation, retaining modifiers. */
+export function activateInlineLinkFromKeyboard(event: KeyboardEvent<HTMLElement>): void {
+ if (event.key === 'ContextMenu' || (event.shiftKey && event.key === 'F10')) {
+ event.preventDefault();
+ event.stopPropagation();
+ event.currentTarget.dispatchEvent(
+ new MouseEvent('contextmenu', { bubbles: true, cancelable: true }),
+ );
+ return;
+ }
+ if (event.key !== 'Enter' && event.key !== ' ') return;
+ event.preventDefault();
+ event.currentTarget.dispatchEvent(
+ new MouseEvent('click', {
+ bubbles: true,
+ cancelable: true,
+ shiftKey: event.shiftKey,
+ metaKey: event.metaKey,
+ ctrlKey: event.ctrlKey,
+ altKey: event.altKey,
+ }),
+ );
+}
+
+/** Keyboard context menus anchor to the focused link, never the screen's top-left. */
+export function linkMenuPosition(event: ReactMouseEvent<HTMLElement>): { x: number; y: number } {
+ if (event.clientX || event.clientY) return { x: event.clientX, y: event.clientY };
+ const rect = event.currentTarget.getBoundingClientRect();
+ return { x: rect.left, y: rect.bottom };
+}
diff --git a/apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx b/apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx
index 6a6b8718be..251d95e0e6 100644
--- a/apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx
+++ b/apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx
@@ -1,38 +1,9 @@
import { shouldShowOpenPathError } from '../../../shared/openPathResult';
-/**
- * useFileChipContextMenu
- * ---------------------------------------------------------------------------
- * Shared right-click menu for the three kinds of "file chip" rendered in the
- * chat message flow:
- * - MarkdownRenderer inline-code path chip (assistant output)
- * - UserMessage @file chip (user-typed attachments)
- * - AgentActionRow tool-call file chip (Edit / Write / Read inputs)
- *
- * Menu items:
- * 0. 在侧边栏文件浏览器中打开 → select/reveal the file in the RSB file browser
- * 1. 在侧边栏浏览器中打开(可选,sidebarOpenSessionId 提供时;html chip 用)
- * 2. 打开方式 ▸ →(文件 + 本地会话)默认应用 + 枚举出的可用应用
- * (Windows 注册表,见 main/openWithApps.ts)。应用
- * 列表在子菜单展开时懒加载。不提供「选择其他应用…」
- * (系统 OpenAs 对话框实测起不来,且与 Codex 形态不符)。
- * 3. 复制 → copy the file itself as a clipboard file reference
- * (pasteable into Explorer / Finder / chat apps)
- * 4. 复制文件路径 → copy the absolute path string
- * 5. 打开文件所在目录 → reveal in the OS file manager
- * 6. 在浏览器中查看 →(可选,canOpenInBrowser)file:// 交给系统浏览器
- * 7. 查看源文件 →(可选,onViewSource 提供时;html chip 左键改为按
- * 偏好直开后,TextLightbox 从这里进)
- *
- * Returns `onContextMenu` (attach to the chip button) and `menu` (render once
- * next to the button). Uses Radix DropdownMenu with a 0×0 virtual trigger
- * positioned at the cursor, same pattern as LightboxImage in MarkdownRenderer.
- *
- * `getAbsPath` is async so callers can do path resolution (e.g.
- * resolveLocalPathSmart for monorepo relative refs) only when the user
- * actually opens the menu — chips that are never right-clicked pay nothing.
- */
+/** Shared flat menus for message file references. HTML exposes page/source actions;
+ * other files retain file operations. Local reveal and remote download occupy
+ * the same slot. Path resolution stays lazy until an action is selected. */
-import { useRef, useState, type ReactElement } from 'react';
+import { lazy, Suspense, useRef, useState, type ReactElement } from 'react';
import {
AppWindow,
ClipboardCopy,
@@ -48,15 +19,12 @@ import { useTranslation } from 'react-i18next';
import { toast } from '@/lib/toast';
import { formatFileLocation, type FileLocation } from '@/lib/fileLocation';
-import { mapIpcErrorToI18nKey } from '@/utils/ipcError';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
- DropdownMenuSub,
- DropdownMenuSubContent,
- DropdownMenuSubTrigger,
+ DropdownMenuShortcut,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
@@ -65,36 +33,34 @@ import {
openFileInSidebarFileBrowser,
} from '@/features/right-sidebar/lib/openInSidebarFileBrowser';
import { isRemoteFileOrigin } from '@/lib/sessionFileOrigin';
-import { copyRemoteChatFile, downloadRemoteChatEntry } from '@/lib/remoteFileOpen';
+import {
+ copyRemoteChatFile,
+ downloadRemoteChatEntry,
+ openRemoteChatFile,
+} from '@/lib/remoteFileOpen';
import { toWorkdirRel } from '../../../shared/workdirPath';
import { useSidebarTargetSessionId } from '@/features/cc-agent/embeddedSessionNavigation';
import { openHtmlFileByPreference } from './useOpenWithMenu';
import { useChatSessionFile } from './ChatSessionFileContext';
+import { isSeparateLinkActivation, linkMenuPosition } from './linkInteraction';
+
+// Load source preview only when requested; TextLightbox itself renders Markdown links.
+const SourcePreview = lazy(() =>
+ import('./TextLightbox').then((module) => ({ default: module.TextLightbox })),
+);
export interface UseFileChipContextMenu {
onContextMenu: (e: React.MouseEvent) => void;
openAt: (x: number, y: number) => void;
+ onActivate: (
+ event: React.MouseEvent<HTMLElement>,
+ openDefault: () => void | Promise<void>,
+ ) => void;
menu: ReactElement;
}
-/**
- * @param getAbsPath resolver invoked lazily on each menu-item click; must
- * return an absolute filesystem path.
- * @param canOpenInBrowser when true, adds a 4th "在浏览器中查看" menu item.
- * Callers compute this from the chip text's extension
- * via `isBrowserOpenablePath` (shared). Product policy
- * currently limits this to HTML files.
- * @param sidebarFileBrowserKind target kind for "在侧边栏文件浏览器中打开".
- * File chips select/reveal the file; directory chips
- * use directory reveal so the folder expands instead
- * of being read as a file.
- * @param sidebarOpenSessionId provided → prepend "在侧边栏浏览器中打开" item。
- * 默认写该 session;sidebar-embedded Provider 注入了
- * 可见 Lead bucket 时只替换 RSB 目标,不改变文件来源。
- * @param onViewSource provided → append "查看源文件" item. Used by html
- * chips whose LEFT click now opens the browser by
- * preference — TextLightbox stays reachable here.
- */
+/** sidebarOpenSessionId overrides the browser target, never the file origin.
+ * onViewSource reuses a caller's preview; other HTML references use TextLightbox. */
export function useFileChipContextMenu({
getAbsPath,
canOpenInBrowser = false,
@@ -113,22 +79,21 @@ export function useFileChipContextMenu({
}): UseFileChipContextMenu {
const { t } = useTranslation();
const [menuPos, setMenuPos] = useState<{ x: number; y: number } | null>(null);
- // 打开方式子菜单的应用列表:null = 未加载;子菜单展开时懒加载(枚举 + 图标
- // 提取都在 main,未展开不付成本)。root 菜单关闭即重置,注册表变化能被下次
- // 展开看到。
- const [openWithApps, setOpenWithApps] = useState<
- Array<{ id: string; label: string; iconDataUrl?: string }> | null
- >(null);
+ const triggerRef = useRef<HTMLElement | null>(null);
+ const [sourcePath, setSourcePath] = useState<string | null>(null);
// 远程会话(device-link / SSH):文件字节在远端机器,「复制文件 / 定位」改走
- // 取回缓存副本;「复制路径」保留远端原始路径;浏览器 / 侧边栏项(读本机
- // file://)隐藏。聊天流外 context 是 local 默认值 → 行为与引入前逐字节一致。
+ // 取回缓存副本;「复制路径」保留远端原始路径;HTML 使用远程预览服务。
+ // 聊天流外 context 是 local 默认值。
const sessionFileCtx = useChatSessionFile();
const remoteOrigin = isRemoteFileOrigin(sessionFileCtx.origin) ? sessionFileCtx.origin : null;
const sidebarFileTargetSessionId = useSidebarTargetSessionId(sessionFileCtx.sessionId);
- const sidebarBrowserTargetSessionId = useSidebarTargetSessionId(sidebarOpenSessionId);
- const copyLocation = location && sidebarFileBrowserKind === 'file'
- ? formatFileLocation(sessionFileCtx.workingDir, location)
- : null;
+ const sidebarBrowserTargetSessionId = useSidebarTargetSessionId(
+ sidebarOpenSessionId ?? sessionFileCtx.sessionId,
+ );
+ const copyLocation =
+ location && sidebarFileBrowserKind === 'file'
+ ? formatFileLocation(sessionFileCtx.workingDir, location)
+ : null;
async function handleCopyLocation(): Promise<void> {
setMenuPos(null);
@@ -234,46 +199,24 @@ export function useFileChipContextMenu({
async function handleViewSource(): Promise<void> {
setMenuPos(null);
- await onViewSource?.();
- }
-
- // 懒加载代际:root 菜单每次关闭 +1。在途枚举返回时代际不符 = 菜单已关过,
- // 丢弃写回——否则过期列表把 state 从 null 顶回非 null,下次展开会跳过重载,
- // 破坏「关闭即重置,注册表变化下次展开可见」的不变量(PR #1835 review)。
- const openWithEpochRef = useRef(0);
-
- async function loadOpenWithApps(): Promise<void> {
- if (openWithApps !== null) return;
- const epoch = openWithEpochRef.current;
- const abs = await getAbsPath();
- const res = await window.electronAPI.listOpenWithApps({ filePath: abs });
- if (openWithEpochRef.current !== epoch) return;
- // 枚举失败不挡菜单:空列表 = 只显示「用默认应用打开」。
- setOpenWithApps(res.success ? res.apps : []);
+ if (onViewSource) await onViewSource();
+ else setSourcePath(await getAbsPath());
}
async function handleOpenWithDefault(): Promise<void> {
setMenuPos(null);
const abs = await getAbsPath();
- const res = await window.electronAPI.openPath(abs);
- if (shouldShowOpenPathError(res)) toast.error(res.error ?? t('chat.markdownRenderer.openWithAppFailed'));
- }
-
- async function handleOpenWithApp(appId: string): Promise<void> {
- setMenuPos(null);
- const abs = await getAbsPath();
- try {
- await window.electronAPI.openFileWithApp({ filePath: abs, appId });
- } catch (error) {
- toast.error(
- t(
- mapIpcErrorToI18nKey(error, {
- namespace: 'chat.markdownRenderer',
- fallback: 'chat.markdownRenderer.openWithAppFailed',
- }),
- ),
- );
+ if (remoteOrigin) {
+ if (sidebarFileBrowserKind === 'directory') {
+ await downloadRemoteChatEntry(remoteOrigin, sessionFileCtx.workingDir, abs);
+ } else {
+ await openRemoteChatFile(remoteOrigin, sessionFileCtx.workingDir, abs);
+ }
+ return;
}
+ const res = await window.electronAPI.openPath(abs);
+ if (shouldShowOpenPathError(res))
+ toast.error(res.error ?? t('chat.markdownRenderer.openWithAppFailed'));
}
const openAt = (x: number, y: number): void => {
@@ -283,141 +226,137 @@ export function useFileChipContextMenu({
const onContextMenu = (e: React.MouseEvent): void => {
e.preventDefault();
e.stopPropagation();
- openAt(e.clientX, e.clientY);
+ triggerRef.current = e.currentTarget as HTMLElement;
+ const { x, y } = linkMenuPosition(e as React.MouseEvent<HTMLElement>);
+ openAt(x, y);
+ };
+ const onActivate: UseFileChipContextMenu['onActivate'] = (event, openDefault) => {
+ event.preventDefault();
+ event.stopPropagation();
+ void (async () => {
+ if (!isSeparateLinkActivation(event)) await openDefault();
+ else if (canOpenInBrowser) await handleOpenInBrowser();
+ else await handleOpenWithDefault();
+ })().catch(() => toast.error(t('chat.markdownRenderer.openWithAppFailed')));
};
+ const run = (action: () => Promise<void>) => () => {
+ void action().catch(() => toast.error(t('chat.markdownRenderer.openLinkFailed')));
+ };
+ const canLocateInSidebar = Boolean(sidebarFileTargetSessionId && sessionFileCtx.workingDir);
+ const hasOpenActions =
+ canOpenInBrowser || canLocateInSidebar || sidebarFileBrowserKind === 'file';
const menu = (
- <DropdownMenu
- open={menuPos !== null}
- onOpenChange={(open) => {
- if (!open) {
- setMenuPos(null);
- setOpenWithApps(null);
- openWithEpochRef.current += 1;
- }
- }}
- >
- <DropdownMenuTrigger asChild>
- <span
- aria-hidden
- data-fixed-menu-anchor
- style={{
- position: 'fixed',
- left: menuPos?.x ?? 0,
- top: menuPos?.y ?? 0,
- width: 0,
- height: 0,
- pointerEvents: 'none',
- }}
- />
- </DropdownMenuTrigger>
- <DropdownMenuContent
- align="start"
- sideOffset={2}
- // The chip and this menu render as siblings inside a clickable ancestor
- // (e.g. AgentActionRow's row has onClick→open-file). DropdownMenuContent
- // is DOM-portaled to <body>, but React synthetic events still bubble up
- // the React *tree* — so a click on any item would bubble item → content →
- // … → the row and re-trigger its open-file onClick. Stop it here (after
- // the item's own handler has already run at the target).
- onClick={(e) => e.stopPropagation()}
+ <>
+ <DropdownMenu
+ open={menuPos !== null}
+ onOpenChange={(open) => {
+ if (!open) setMenuPos(null);
+ }}
>
- {sidebarFileTargetSessionId && sessionFileCtx.workingDir ? (
- <DropdownMenuItem onClick={handleOpenInSidebarFileBrowser}>
- <FolderTree className="mr-2 h-4 w-4" />
- {t('chat.markdownRenderer.openInSidebarFileBrowser')}
- </DropdownMenuItem>
- ) : null}
- {sidebarBrowserTargetSessionId ? (
- <DropdownMenuItem onClick={handleOpenInSidebar}>
- <PanelRight className="mr-2 h-4 w-4" />
- {t('chat.markdownRenderer.openInSidebarBrowser')}
- </DropdownMenuItem>
- ) : null}
- {sidebarFileBrowserKind === 'file' && !remoteOrigin ? (
- // 打开方式:仅文件 + 本地会话。远程会话的字节在远端机器,本机应用
- // 枚举与执行都无意义(与「在浏览器中查看」同一门控口径)。
- <DropdownMenuSub
- onOpenChange={(open) => {
- if (open) void loadOpenWithApps();
+ <DropdownMenuTrigger asChild>
+ <span
+ aria-hidden
+ data-fixed-menu-anchor
+ style={{
+ position: 'fixed',
+ left: menuPos?.x ?? 0,
+ top: menuPos?.y ?? 0,
+ width: 0,
+ height: 0,
+ pointerEvents: 'none',
}}
- >
- <DropdownMenuSubTrigger>
- <AppWindow className="mr-2 h-4 w-4" />
- {t('chat.markdownRenderer.openWith')}
- </DropdownMenuSubTrigger>
- <DropdownMenuSubContent>
- <DropdownMenuItem onClick={handleOpenWithDefault}>
- <AppWindow className="mr-2 h-4 w-4" />
- {t('chat.media.openWithApp')}
- </DropdownMenuItem>
- {openWithApps && openWithApps.length > 0 ? (
- <>
- <DropdownMenuSeparator />
- {openWithApps.map((appEntry) => (
- <DropdownMenuItem
- key={appEntry.id}
- onClick={() => void handleOpenWithApp(appEntry.id)}
- >
- {appEntry.iconDataUrl ? (
- <img
- src={appEntry.iconDataUrl}
- alt=""
- aria-hidden
- className="mr-2 h-4 w-4"
- />
- ) : (
- <AppWindow className="mr-2 h-4 w-4" />
- )}
- {appEntry.label}
- </DropdownMenuItem>
- ))}
- </>
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ align="start"
+ sideOffset={2}
+ onClick={(event) => event.stopPropagation()}
+ onCloseAutoFocus={(event) => {
+ event.preventDefault();
+ if (triggerRef.current?.isConnected) triggerRef.current.focus({ preventScroll: true });
+ }}
+ >
+ {canOpenInBrowser ? (
+ <>
+ {sidebarBrowserTargetSessionId ? (
+ <DropdownMenuItem onClick={run(handleOpenInSidebar)}>
+ <PanelRight className="mr-2 h-4 w-4" />
+ {t('chat.markdownRenderer.openInSidebarBrowser')}
+ </DropdownMenuItem>
) : null}
- </DropdownMenuSubContent>
- </DropdownMenuSub>
- ) : null}
- {remoteOrigin && sidebarFileBrowserKind === 'directory' ? null : (
- <DropdownMenuItem onClick={handleCopyFile}>
- <Copy className="mr-2 h-4 w-4" />
- {t('chat.markdownRenderer.copyFile')}
- </DropdownMenuItem>
- )}
- <DropdownMenuItem onClick={handleCopyPath}>
- <ClipboardCopy className="mr-2 h-4 w-4" />
- {t('chat.markdownRenderer.copyFilePath')}
- </DropdownMenuItem>
- {copyLocation ? (
- <DropdownMenuItem onClick={handleCopyLocation}>
- <ClipboardCopy className="mr-2 h-4 w-4" />
- {t('chat.markdownRenderer.copyLocation')}
- </DropdownMenuItem>
- ) : null}
- <DropdownMenuItem onClick={handleReveal}>
- {remoteOrigin ? (
- <Download className="mr-2 h-4 w-4" />
+ <DropdownMenuItem onClick={run(handleOpenInBrowser)}>
+ <Globe className="mr-2 h-4 w-4" />
+ {t('chat.markdownRenderer.openInDefaultBrowser')}
+ <DropdownMenuShortcut aria-hidden>
+ {t('chat.markdownRenderer.shiftClick')}
+ </DropdownMenuShortcut>
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={run(handleViewSource)}>
+ <FileCode className="mr-2 h-4 w-4" />
+ {t('chat.markdownRenderer.viewSourceFile')}
+ </DropdownMenuItem>
+ </>
) : (
- <FolderOpen className="mr-2 h-4 w-4" />
+ <>
+ {canLocateInSidebar ? (
+ <DropdownMenuItem onClick={run(handleOpenInSidebarFileBrowser)}>
+ <FolderTree className="mr-2 h-4 w-4" />
+ {t('chat.markdownRenderer.openInSidebarFileBrowser')}
+ </DropdownMenuItem>
+ ) : null}
+ {sidebarFileBrowserKind === 'file' ? (
+ <DropdownMenuItem onClick={run(handleOpenWithDefault)}>
+ <AppWindow className="mr-2 h-4 w-4" />
+ {t('chat.media.openWithApp')}
+ <DropdownMenuShortcut aria-hidden>
+ {t('chat.markdownRenderer.shiftClick')}
+ </DropdownMenuShortcut>
+ </DropdownMenuItem>
+ ) : null}
+ </>
)}
- {remoteOrigin
- ? t('chat.remoteFile.downloadToLocal')
- : t('chat.markdownRenderer.revealFile')}
- </DropdownMenuItem>
- {canOpenInBrowser ? (
- <DropdownMenuItem onClick={handleOpenInBrowser}>
- <Globe className="mr-2 h-4 w-4" />
- {t('chat.markdownRenderer.openInBrowser')}
+ {hasOpenActions ? <DropdownMenuSeparator /> : null}
+ <DropdownMenuItem onClick={run(handleReveal)}>
+ {remoteOrigin ? (
+ <Download className="mr-2 h-4 w-4" />
+ ) : (
+ <FolderOpen className="mr-2 h-4 w-4" />
+ )}
+ {remoteOrigin
+ ? t('chat.remoteFile.downloadToLocal')
+ : t('chat.markdownRenderer.revealFile')}
</DropdownMenuItem>
- ) : null}
- {onViewSource ? (
- <DropdownMenuItem onClick={handleViewSource}>
- <FileCode className="mr-2 h-4 w-4" />
- {t('chat.markdownRenderer.viewSourceFile')}
+ {!canOpenInBrowser && !(remoteOrigin && sidebarFileBrowserKind === 'directory') ? (
+ <DropdownMenuItem onClick={run(handleCopyFile)}>
+ <Copy className="mr-2 h-4 w-4" />
+ {t('chat.markdownRenderer.copyFile')}
+ </DropdownMenuItem>
+ ) : null}
+ <DropdownMenuItem onClick={run(handleCopyPath)}>
+ <ClipboardCopy className="mr-2 h-4 w-4" />
+ {t('chat.markdownRenderer.copyFilePath')}
</DropdownMenuItem>
- ) : null}
- </DropdownMenuContent>
- </DropdownMenu>
+ {copyLocation ? (
+ <DropdownMenuItem onClick={run(handleCopyLocation)}>
+ <ClipboardCopy className="mr-2 h-4 w-4" />
+ {t('chat.markdownRenderer.copyLocation')}
+ </DropdownMenuItem>
+ ) : null}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ {sourcePath ? (
+ <Suspense fallback={null}>
+ <SourcePreview
+ filePath={sourcePath}
+ initialLine={location?.line}
+ triggerRef={triggerRef}
+ onClose={() => setSourcePath(null)}
+ />
+ </Suspense>
+ ) : null}
+ </>
);
- return { onContextMenu, openAt, menu };
+ return { onContextMenu, onActivate, openAt, menu };
}
diff --git a/apps/desktop/src/renderer/components/chat/useLinkContextMenu.tsx b/apps/desktop/src/renderer/components/chat/useLinkContextMenu.tsx
new file mode 100644
index 0000000000..a09803e8ef
--- /dev/null
+++ b/apps/desktop/src/renderer/components/chat/useLinkContextMenu.tsx
@@ -0,0 +1,104 @@
+import { useRef, useState, type MouseEvent, type ReactNode } from 'react';
+import { Link2 } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuShortcut,
+ DropdownMenuTrigger,
+} from '@/components/ui/dropdown-menu';
+import { toast } from '@/lib/toast';
+import { linkMenuPosition } from './linkInteraction';
+
+export interface LinkMenuAction {
+ label: string;
+ shortcut?: string;
+ icon: ReactNode;
+ run: () => void | Promise<void>;
+}
+
+/** Shared open-actions → copy-link menu for message URLs and internal links. */
+export function useLinkContextMenu(href: string, actions: LinkMenuAction[]) {
+ const { t } = useTranslation();
+ const triggerRef = useRef<HTMLElement | null>(null);
+ const [state, setState] = useState<{
+ x: number;
+ y: number;
+ href: string;
+ actions: LinkMenuAction[];
+ } | null>(null);
+ const onContextMenu = (event: MouseEvent<HTMLElement>) => {
+ event.preventDefault();
+ event.stopPropagation();
+ triggerRef.current = event.currentTarget;
+ setState({ ...linkMenuPosition(event), href, actions });
+ };
+ const run = async (action: () => void | Promise<void>) => {
+ setState(null);
+ try {
+ await action();
+ } catch {
+ toast.error(t('chat.markdownRenderer.openLinkFailed'));
+ }
+ };
+ const menu = (
+ <DropdownMenu
+ open={state !== null}
+ onOpenChange={(open) => {
+ if (!open) setState(null);
+ }}
+ >
+ <DropdownMenuTrigger asChild>
+ <span
+ aria-hidden
+ data-fixed-menu-anchor
+ style={{
+ position: 'fixed',
+ left: state?.x ?? 0,
+ top: state?.y ?? 0,
+ width: 0,
+ height: 0,
+ pointerEvents: 'none',
+ }}
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ align="start"
+ sideOffset={2}
+ onClick={(event) => event.stopPropagation()}
+ onCloseAutoFocus={(event) => {
+ event.preventDefault();
+ if (triggerRef.current?.isConnected) triggerRef.current.focus({ preventScroll: true });
+ }}
+ >
+ {state?.actions.map((action) => (
+ <DropdownMenuItem key={action.label} onClick={() => void run(action.run)}>
+ {action.icon}
+ {action.label}
+ {action.shortcut ? (
+ <DropdownMenuShortcut aria-hidden>{action.shortcut}</DropdownMenuShortcut>
+ ) : null}
+ </DropdownMenuItem>
+ ))}
+ {state?.actions.length ? <DropdownMenuSeparator /> : null}
+ <DropdownMenuItem
+ onClick={() => {
+ const value = state?.href;
+ setState(null);
+ if (value === undefined) return;
+ void navigator.clipboard.writeText(value).then(
+ () => toast.success(t('chat.markdownRenderer.linkCopied')),
+ () => toast.error(t('chat.media.copyFailed')),
+ );
+ }}
+ >
+ <Link2 className="mr-2 h-4 w-4" />
+ {t('chat.markdownRenderer.copyLink')}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+ return { onContextMenu, menu };
+}
diff --git a/apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx b/apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx
index d7ce7fb9c2..c8fb9e7423 100644
--- a/apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx
+++ b/apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx
@@ -10,14 +10,13 @@
* (复制 / 路径 / 目录 / 浏览器查看),「侧边栏打开 / 查看源文件」以可选项
* 合并进那份菜单,避免同一个元素挂两份右键菜单。
*
- * sessionId 缺失(Market 预览等无会话上下文)时 isEnabled=false,调用方保持
- * 原有行为(左键直开系统浏览器、无右键菜单)。
+ * sessionId 缺失时仍可右键复制和交给系统浏览器,只省略侧边栏项。
*
* 视觉与交互复用 useFileChipContextMenu 的模式:Radix DropdownMenu + 光标处
* 0×0 虚拟 trigger;menu 渲染一次挂在调用组件旁。
*/
-import { useState, type ReactElement } from 'react';
+import { useRef, useState, type ReactElement, type MouseEvent } from 'react';
import { Globe, Link2, PanelRight } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import type { TFunction } from 'i18next';
@@ -29,12 +28,17 @@ import {
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
+ DropdownMenuShortcut,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
-import { openUrlInSidebarBrowser, pathToFileUrl } from '@/features/right-sidebar/lib/openInSidebarBrowser';
+import {
+ openUrlInSidebarBrowser,
+ pathToFileUrl,
+} from '@/features/right-sidebar/lib/openInSidebarBrowser';
import { getLinkOpenPreference, getLinkOpenPreferenceForUrl } from '@/hooks/useLinkOpenPreference';
import { useSidebarTargetSessionId } from '@/features/cc-agent/embeddedSessionNavigation';
import type { SessionFileOrigin } from '@/lib/sessionFileOrigin';
+import { isSeparateLinkActivation, linkMenuPosition } from './linkInteraction';
/** 左键"按偏好直开"只对浏览器"作为页面渲染"有意义的 html 家族生效;其余本地
* 文件保持原有"点击即预览"。右键菜单的 BROWSER_OPENABLE_EXTS 也收敛到
@@ -67,6 +71,27 @@ export async function openUrlByPreference(
if (!res.success) toast.error(t('chat.markdownRenderer.openLinkFailed'));
}
+/** Identical activation for user URLs, assistant Markdown and keyboard/middle clicks. */
+export async function activateMessageUrl(
+ event: MouseEvent<HTMLElement>,
+ sessionId: string | undefined,
+ url: string,
+ t: TFunction,
+): Promise<void> {
+ event.preventDefault();
+ event.stopPropagation();
+ try {
+ if (sessionId && !isSeparateLinkActivation(event)) {
+ await openUrlByPreference(sessionId, url, t);
+ } else {
+ const result = await window.electronAPI.openExternal(url);
+ if (!result.success) toast.error(t('chat.markdownRenderer.openLinkFailed'));
+ }
+ } catch {
+ toast.error(t('chat.markdownRenderer.openLinkFailed'));
+ }
+}
+
/** Local HTML opens in place; remote HTML uses the viewer-local HTTP preview. */
export async function openHtmlFileByPreference(
sessionId: string,
@@ -85,9 +110,14 @@ export async function openHtmlFileByPreference(
try {
await window.electronAPI.openFileInBrowser(absPath);
} catch (error) {
- toast.error(t(mapIpcErrorToI18nKey(error, {
- namespace: 'chat.markdownRenderer', fallback: 'chat.markdownRenderer.openInBrowserFailed',
- })));
+ toast.error(
+ t(
+ mapIpcErrorToI18nKey(error, {
+ namespace: 'chat.markdownRenderer',
+ fallback: 'chat.markdownRenderer.openInBrowserFailed',
+ }),
+ ),
+ );
}
}
return;
@@ -110,9 +140,14 @@ export async function openHtmlFileByPreference(
}
} catch (error) {
const code = extractIpcError(error)?.code;
- const key = code === 'HTML_PREVIEW_TOO_LARGE' ? 'previewTooLarge'
- : code === 'HTML_PREVIEW_UNSUPPORTED' ? 'previewUnsupported'
- : code === 'NOT_FOUND' ? 'previewNotFound' : 'previewFailed';
+ const key =
+ code === 'HTML_PREVIEW_TOO_LARGE'
+ ? 'previewTooLarge'
+ : code === 'HTML_PREVIEW_UNSUPPORTED'
+ ? 'previewUnsupported'
+ : code === 'NOT_FOUND'
+ ? 'previewNotFound'
+ : 'previewFailed';
toast.error(t(`chat.remoteFile.${key}`));
} finally {
clearTimeout(delayed);
@@ -121,9 +156,8 @@ export async function openHtmlFileByPreference(
}
export interface UseOpenWithMenu {
- /** sessionId 就位才启用;false 时调用方保持原直开行为,不要 openAt。 */
- isEnabled: boolean;
openAt: (x: number, y: number, url: string) => void;
+ onContextMenu: (event: MouseEvent<HTMLElement>, url: string) => void;
menu: ReactElement | null;
}
@@ -131,12 +165,18 @@ export function useOpenWithMenu({ sessionId }: { sessionId?: string }): UseOpenW
const { t } = useTranslation();
const [state, setState] = useState<{ x: number; y: number; url: string } | null>(null);
const sidebarTargetSessionId = useSidebarTargetSessionId(sessionId);
-
- const isEnabled = Boolean(sidebarTargetSessionId);
+ const triggerRef = useRef<HTMLElement | null>(null);
const openAt = (x: number, y: number, url: string): void => {
setState({ x, y, url });
};
+ const onContextMenu = (event: MouseEvent<HTMLElement>, url: string) => {
+ event.preventDefault();
+ event.stopPropagation();
+ triggerRef.current = event.currentTarget;
+ const { x, y } = linkMenuPosition(event);
+ openAt(x, y, url);
+ };
async function handleOpenInSidebar(): Promise<void> {
const target = state;
@@ -149,8 +189,12 @@ export function useOpenWithMenu({ sessionId }: { sessionId?: string }): UseOpenW
const target = state;
setState(null);
if (!target) return;
- const res = await window.electronAPI.openExternal(target.url);
- if (!res.success) toast.error(t('chat.markdownRenderer.openLinkFailed'));
+ try {
+ const res = await window.electronAPI.openExternal(target.url);
+ if (!res.success) toast.error(t('chat.markdownRenderer.openLinkFailed'));
+ } catch {
+ toast.error(t('chat.markdownRenderer.openLinkFailed'));
+ }
}
async function handleCopyLink(): Promise<void> {
@@ -192,14 +236,23 @@ export function useOpenWithMenu({ sessionId }: { sessionId?: string }): UseOpenW
// 同 useFileChipContextMenu:menu portal 到 body 但 React 合成事件仍沿
// React 树冒泡,不拦会触发外层元素的 onClick。
onClick={(e) => e.stopPropagation()}
+ onCloseAutoFocus={(event) => {
+ event.preventDefault();
+ if (triggerRef.current?.isConnected) triggerRef.current.focus({ preventScroll: true });
+ }}
>
- <DropdownMenuItem onClick={handleOpenInSidebar}>
- <PanelRight className="mr-2 h-4 w-4" />
- {t('chat.markdownRenderer.openInSidebarBrowser')}
- </DropdownMenuItem>
+ {sidebarTargetSessionId ? (
+ <DropdownMenuItem onClick={handleOpenInSidebar}>
+ <PanelRight className="mr-2 h-4 w-4" />
+ {t('chat.markdownRenderer.openInSidebarBrowser')}
+ </DropdownMenuItem>
+ ) : null}
<DropdownMenuItem onClick={handleOpenInDefaultBrowser}>
<Globe className="mr-2 h-4 w-4" />
{t('chat.markdownRenderer.openInDefaultBrowser')}
+ <DropdownMenuShortcut aria-hidden>
+ {t('chat.markdownRenderer.shiftClick')}
+ </DropdownMenuShortcut>
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem onClick={handleCopyLink}>
@@ -210,5 +263,5 @@ export function useOpenWithMenu({ sessionId }: { sessionId?: string }): UseOpenW
</DropdownMenu>
);
- return { isEnabled, openAt, menu };
+ return { openAt, onContextMenu, menu };
}
diff --git a/apps/desktop/src/renderer/features/cc-agent/SecondaryWindowBootGate.tsx b/apps/desktop/src/renderer/features/cc-agent/SecondaryWindowBootGate.tsx
index 6197e557df..e8c0112586 100644
--- a/apps/desktop/src/renderer/features/cc-agent/SecondaryWindowBootGate.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/SecondaryWindowBootGate.tsx
@@ -19,10 +19,10 @@
* 渲染中性占位(content-area 底色),不出现空白帧。bootSession 缺失时回落 /cc-agent。
*/
-import { useEffect, useRef } from 'react';
+import { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
-import { getBootDeviceId, getBootSessionId } from '@/lib/secondaryWindow';
+import { getBootDeviceId, getBootSessionId, getBootMessageClientId } from '@/lib/secondaryWindow';
import { getSessionFor } from '@/lib/makerTransport';
import { resolveSessionRoute } from '@/lib/orcaSessionIdentity';
import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';
@@ -32,13 +32,7 @@ const log = createLogger('SecondaryWindowBootGate');
export function SecondaryWindowBootGate() {
const navigate = useNavigate();
- // 只 boot 一次:StrictMode(dev)下 effect 跑两次,ref 守住避免重复解析 / 跳转。
- const hasBootedRef = useRef(false);
-
useEffect(() => {
- if (hasBootedRef.current) return;
- hasBootedRef.current = true;
-
const bootSessionId = getBootSessionId();
if (!bootSessionId) {
// 异常进入(直接打开 /cc-agent/boot 而无 bootSession)→ 回落默认入口。
@@ -48,6 +42,7 @@ export function SecondaryWindowBootGate() {
let cancelled = false;
const bootDeviceId = getBootDeviceId();
+ const messageClientId = getBootMessageClientId();
void (async () => {
if (!bootDeviceId) return resolveSessionRoute(bootSessionId);
@@ -63,7 +58,22 @@ export function SecondaryWindowBootGate() {
})()
.then((target) => {
if (cancelled) return;
- navigate(target, { replace: true });
+ navigate(target, {
+ replace: true,
+ ...(messageClientId
+ ? {
+ state: {
+ searchJump: {
+ kind: 'conversation-search',
+ sessionId: bootSessionId,
+ messageId: messageClientId,
+ messageIdKind: 'clientId',
+ messageClientId,
+ },
+ },
+ }
+ : {}),
+ });
})
.catch((err) => {
log.warn('failed to resolve boot session route, falling back to /cc-agent', {
diff --git a/apps/desktop/src/renderer/features/cc-agent/__tests__/SecondaryWindowBootGate.test.tsx b/apps/desktop/src/renderer/features/cc-agent/__tests__/SecondaryWindowBootGate.test.tsx
index 00cd9223d0..d8a3cea927 100644
--- a/apps/desktop/src/renderer/features/cc-agent/__tests__/SecondaryWindowBootGate.test.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/__tests__/SecondaryWindowBootGate.test.tsx
@@ -1,11 +1,13 @@
// @vitest-environment jsdom
import { cleanup, render, waitFor } from '@testing-library/react';
+import { StrictMode } from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => ({
getBootDeviceId: vi.fn<() => string | null>(),
getBootSessionId: vi.fn<() => string | null>(),
+ getBootMessageClientId: vi.fn<() => string | null>(),
getVisibleMergedRemoteSessions: vi.fn<() => Array<Record<string, unknown>>>(),
getSessionFor: vi.fn(),
navigate: vi.fn(),
@@ -20,6 +22,7 @@ vi.mock('react-router-dom', () => ({
vi.mock('@/lib/secondaryWindow', () => ({
getBootDeviceId: mocks.getBootDeviceId,
getBootSessionId: mocks.getBootSessionId,
+ getBootMessageClientId: mocks.getBootMessageClientId,
}));
vi.mock('@/features/device-link/remoteProjectsStore', () => ({
@@ -47,6 +50,7 @@ describe('SecondaryWindowBootGate', () => {
beforeEach(() => {
mocks.getBootDeviceId.mockReset();
mocks.getBootSessionId.mockReset();
+ mocks.getBootMessageClientId.mockReturnValue(null);
mocks.getVisibleMergedRemoteSessions.mockReset();
mocks.getSessionFor.mockReset();
mocks.navigate.mockReset();
@@ -83,4 +87,32 @@ describe('SecondaryWindowBootGate', () => {
mocks.resolveSessionRoute.mock.invocationCallOrder[0],
);
});
+
+ it('retains the message anchor through remote Worker routing and StrictMode effect replay', async () => {
+ mocks.getBootMessageClientId.mockReturnValue('message/42');
+ mocks.getSessionFor.mockResolvedValue({ id: 'worker-remote', orcaRole: 'worker' });
+ mocks.resolveSessionRoute.mockResolvedValue('/cc-agent/lead-remote?worker=worker-remote');
+ render(
+ <StrictMode>
+ <SecondaryWindowBootGate />
+ </StrictMode>,
+ );
+ await waitFor(() =>
+ expect(mocks.navigate).toHaveBeenCalledExactlyOnceWith(
+ '/cc-agent/lead-remote?worker=worker-remote',
+ {
+ replace: true,
+ state: {
+ searchJump: {
+ kind: 'conversation-search',
+ sessionId: 'worker-remote',
+ messageId: 'message/42',
+ messageIdKind: 'clientId',
+ messageClientId: 'message/42',
+ },
+ },
+ },
+ ),
+ );
+ });
});
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index f78ea0c320..1d4e3356c9 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -11356,12 +11356,11 @@
"blockCopied": "Copied",
"duplicateFiles": "Found {{count}} files with the same name, please use an absolute path",
"copyFile": "Copy",
- "copyFilePath": "Copy file path",
+ "copyFilePath": "Copy path",
"copyLocation": "Copy Location",
"locationCopied": "Location copied",
- "openWith": "Open with",
"openWithAppFailed": "Couldn't open with the selected app",
- "revealFile": "Reveal in folder",
+ "revealFile": "Show in folder",
"openInBrowser": "Open in browser",
"fileCopied": "File copied",
"pathCopied": "Path copied",
@@ -11372,16 +11371,20 @@
"BROWSER_FILE_OPEN_FAILED": "Failed to open in browser",
"openInBrowserFailed": "Failed to open in browser",
"openLinkFailed": "Failed to open link",
+ "openLink": "Open link",
"anchorNotFound": "Heading not found",
- "openInSidebarBrowser": "Open in sidebar browser",
- "openInSidebarFileBrowser": "Open in sidebar file browser",
+ "openInSidebarBrowser": "Open in sidebar",
+ "openInSidebarFileBrowser": "Locate in file list",
"openInSidebarFileBrowserFailed": "Failed to open in sidebar file browser",
"openInSidebarFileBrowserOutsideWorkdir": "This file is outside the current session working directory and cannot be located in the sidebar file browser",
- "openInDefaultBrowser": "Open in default browser",
+ "openInDefaultBrowser": "Open in browser",
"copyLink": "Copy link",
"linkCopied": "Link copied",
- "viewSourceFile": "View source file",
- "openInSidebarFailed": "Failed to open in sidebar browser"
+ "viewSourceFile": "View source",
+ "openInSidebarFailed": "Failed to open in sidebar browser",
+ "openInCurrentWindow": "Open in current window",
+ "locateProject": "Locate project",
+ "shiftClick": "Shift+click"
},
"ghostSummon": {
"directiveLabel": "Directive appended for the model",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index cae827df72..346f626a6d 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -11311,12 +11311,11 @@
"blockCopied": "コピー済み",
"duplicateFiles": "同名のファイルが {{count}} 件見つかりました。絶対パスを使用してください",
"copyFile": "コピー",
- "copyFilePath": "ファイルパスをコピー",
+ "copyFilePath": "パスをコピー",
"copyLocation": "位置をコピー",
"locationCopied": "位置をコピーしました",
- "openWith": "アプリで開く",
"openWithAppFailed": "選択したアプリで開けませんでした",
- "revealFile": "ファイルの場所を開く",
+ "revealFile": "フォルダーで表示",
"openInBrowser": "ブラウザで開く",
"fileCopied": "ファイルをコピーしました",
"pathCopied": "パスをコピーしました",
@@ -11327,16 +11326,20 @@
"BROWSER_FILE_OPEN_FAILED": "ブラウザで開けませんでした",
"openInBrowserFailed": "ブラウザで開けませんでした",
"openLinkFailed": "リンクを開けませんでした",
+ "openLink": "リンクを開く",
"anchorNotFound": "対応する見出しが見つかりません",
- "openInSidebarBrowser": "サイドバーのブラウザで開く",
- "openInSidebarFileBrowser": "サイドバーのファイルブラウザで開く",
+ "openInSidebarBrowser": "サイドバーで開く",
+ "openInSidebarFileBrowser": "ファイル一覧で表示",
"openInSidebarFileBrowserFailed": "サイドバーのファイルブラウザで開けませんでした",
"openInSidebarFileBrowserOutsideWorkdir": "このファイルは現在のセッション作業ディレクトリ外にあるため、サイドバーのファイルブラウザで特定できません",
- "openInDefaultBrowser": "既定のブラウザで開く",
+ "openInDefaultBrowser": "ブラウザで開く",
"copyLink": "リンクをコピー",
"linkCopied": "リンクをコピーしました",
- "viewSourceFile": "ソースファイルを表示",
- "openInSidebarFailed": "サイドバーのブラウザで開けませんでした"
+ "viewSourceFile": "ソースを表示",
+ "openInSidebarFailed": "サイドバーのブラウザで開けませんでした",
+ "openInCurrentWindow": "現在のウィンドウで開く",
+ "locateProject": "プロジェクトを表示",
+ "shiftClick": "Shift+クリック"
},
"ghostSummon": {
"directiveLabel": "モデルに追加された指示",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 29d9868a4d..17d49f6c0a 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -11311,12 +11311,11 @@
"blockCopied": "복사됨",
"duplicateFiles": "동일한 이름의 파일 {{count}}개를 찾았습니다. 절대 경로를 사용해 주세요",
"copyFile": "복사",
- "copyFilePath": "파일 경로 복사",
+ "copyFilePath": "경로 복사",
"copyLocation": "위치 복사",
"locationCopied": "위치를 복사했습니다",
- "openWith": "앱으로 열기",
"openWithAppFailed": "선택한 앱으로 열 수 없습니다",
- "revealFile": "파일 위치 열기",
+ "revealFile": "폴더에서 표시",
"openInBrowser": "브라우저에서 열기",
"fileCopied": "파일이 복사되었습니다",
"pathCopied": "경로가 복사되었습니다",
@@ -11327,16 +11326,20 @@
"BROWSER_FILE_OPEN_FAILED": "브라우저에서 열지 못했습니다",
"openInBrowserFailed": "브라우저에서 열지 못했습니다",
"openLinkFailed": "링크를 열지 못했습니다",
+ "openLink": "링크 열기",
"anchorNotFound": "해당 제목을 찾을 수 없습니다",
- "openInSidebarBrowser": "사이드바 브라우저에서 열기",
- "openInSidebarFileBrowser": "사이드바 파일 브라우저에서 열기",
+ "openInSidebarBrowser": "사이드바에서 열기",
+ "openInSidebarFileBrowser": "파일 목록에서 표시",
"openInSidebarFileBrowserFailed": "사이드바 파일 브라우저에서 열지 못했습니다",
"openInSidebarFileBrowserOutsideWorkdir": "이 파일은 현재 세션 작업 디렉터리 밖에 있어 사이드바 파일 브라우저에서 찾을 수 없습니다",
- "openInDefaultBrowser": "기본 브라우저에서 열기",
+ "openInDefaultBrowser": "브라우저에서 열기",
"copyLink": "링크 복사",
"linkCopied": "링크가 복사되었습니다",
- "viewSourceFile": "소스 파일 보기",
- "openInSidebarFailed": "사이드바 브라우저에서 열지 못했습니다"
+ "viewSourceFile": "소스 보기",
+ "openInSidebarFailed": "사이드바 브라우저에서 열지 못했습니다",
+ "openInCurrentWindow": "현재 창에서 열기",
+ "locateProject": "프로젝트로 이동",
+ "shiftClick": "Shift+클릭"
},
"ghostSummon": {
"directiveLabel": "모델에 추가된 지시문",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 3fca5be454..b16fcb2b5d 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -11311,12 +11311,11 @@
"blockCopied": "已复制",
"duplicateFiles": "找到 {{count}} 个同名文件,请改用绝对路径",
"copyFile": "复制",
- "copyFilePath": "复制文件路径",
+ "copyFilePath": "复制路径",
"copyLocation": "复制位置",
"locationCopied": "位置已复制",
- "openWith": "打开方式",
"openWithAppFailed": "无法用所选应用打开",
- "revealFile": "打开文件所在目录",
+ "revealFile": "在文件夹中显示",
"openInBrowser": "在浏览器中查看",
"fileCopied": "文件已复制",
"pathCopied": "路径已复制",
@@ -11327,16 +11326,20 @@
"BROWSER_FILE_OPEN_FAILED": "在浏览器中打开失败",
"openInBrowserFailed": "在浏览器中打开失败",
"openLinkFailed": "打开链接失败",
+ "openLink": "打开链接",
"anchorNotFound": "未找到对应标题",
- "openInSidebarBrowser": "在侧边栏浏览器中打开",
- "openInSidebarFileBrowser": "在侧边栏文件浏览器中打开",
+ "openInSidebarBrowser": "在侧边栏打开",
+ "openInSidebarFileBrowser": "在文件列表中定位",
"openInSidebarFileBrowserFailed": "在侧边栏文件浏览器中打开失败",
"openInSidebarFileBrowserOutsideWorkdir": "该文件不在当前任务工作目录内,无法在侧边栏文件浏览器中定位",
- "openInDefaultBrowser": "在默认浏览器中打开",
+ "openInDefaultBrowser": "在浏览器打开",
"copyLink": "复制链接",
"linkCopied": "链接已复制",
- "viewSourceFile": "查看源文件",
- "openInSidebarFailed": "在侧边栏浏览器中打开失败"
+ "viewSourceFile": "查看源代码",
+ "openInSidebarFailed": "在侧边栏浏览器中打开失败",
+ "openInCurrentWindow": "在当前窗口打开",
+ "locateProject": "定位到项目",
+ "shiftClick": "Shift+点击"
},
"ghostSummon": {
"directiveLabel": "追加给模型的指令",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index fe740d7eb6..e85094d32b 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -11310,12 +11310,11 @@
"blockCopied": "已複製",
"duplicateFiles": "找到 {{count}} 個同名檔案,請改用絕對路徑",
"copyFile": "複製",
- "copyFilePath": "複製檔案路徑",
+ "copyFilePath": "複製路徑",
"copyLocation": "複製位置",
"locationCopied": "位置已複製",
- "openWith": "開啟方式",
"openWithAppFailed": "無法用所選應用開啟",
- "revealFile": "開啟檔案所在目錄",
+ "revealFile": "在資料夾中顯示",
"openInBrowser": "在瀏覽器中檢視",
"fileCopied": "檔案已複製",
"pathCopied": "路徑已複製",
@@ -11326,16 +11325,20 @@
"BROWSER_FILE_OPEN_FAILED": "在瀏覽器中開啟失敗",
"openInBrowserFailed": "在瀏覽器中開啟失敗",
"openLinkFailed": "開啟連結失敗",
+ "openLink": "開啟連結",
"anchorNotFound": "未找到對應標題",
- "openInSidebarBrowser": "在側邊欄瀏覽器中開啟",
- "openInSidebarFileBrowser": "在側邊欄檔案瀏覽器中開啟",
+ "openInSidebarBrowser": "在側邊欄開啟",
+ "openInSidebarFileBrowser": "在檔案列表中定位",
"openInSidebarFileBrowserFailed": "在側邊欄檔案瀏覽器中開啟失敗",
"openInSidebarFileBrowserOutsideWorkdir": "該檔案不在當前任務工作目錄內,無法在側邊欄檔案瀏覽器中定位",
- "openInDefaultBrowser": "在預設瀏覽器中開啟",
+ "openInDefaultBrowser": "在瀏覽器開啟",
"copyLink": "複製連結",
"linkCopied": "連結已複製",
- "viewSourceFile": "檢視原始檔",
- "openInSidebarFailed": "在側邊欄瀏覽器中開啟失敗"
+ "viewSourceFile": "檢視原始碼",
+ "openInSidebarFailed": "在側邊欄瀏覽器中開啟失敗",
+ "openInCurrentWindow": "在目前視窗開啟",
+ "locateProject": "定位到專案",
+ "shiftClick": "Shift+點擊"
},
"ghostSummon": {
"directiveLabel": "追加給模型的指令",
diff --git a/apps/desktop/src/renderer/lib/secondaryWindow.ts b/apps/desktop/src/renderer/lib/secondaryWindow.ts
index cbed91e652..a2d480cfa0 100644
--- a/apps/desktop/src/renderer/lib/secondaryWindow.ts
+++ b/apps/desktop/src/renderer/lib/secondaryWindow.ts
@@ -43,3 +43,8 @@ export function getBootDeviceId(): string | null {
return null;
}
}
+
+/** Optional message anchor; the boot gate retains it across canonical task routing. */
+export function getBootMessageClientId(): string | null {
+ return new URLSearchParams(window.location.search).get('bootMessage') || null;
+}
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index a9bc294a96..8855f9778e 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -5794,7 +5794,9 @@ interface ElectronAPI {
) => Promise<import('../shared/modelContextLimit').ModelContextLimitView>;
// 「在新窗口打开」会话多开
- openSessionInNewWindow: (sessionId: string, deviceId?: string | null) => Promise<void>;
+ openSessionInNewWindow: (
+ sessionId: string, deviceId?: string | null, messageClientId?: string | null,
+ ) => Promise<void>;
openSessionInNewWindowIfDroppedOutside: (
sessionId: string,
deviceId?: string | null,
diff --git a/docs/design-rules/DESIGN.md b/docs/design-rules/DESIGN.md
index 6fd05c93f9..0a90ef0ef6 100644
--- a/docs/design-rules/DESIGN.md
+++ b/docs/design-rules/DESIGN.md
@@ -1169,6 +1169,32 @@ Only the two registered chart members inside Usage History may enlarge their non
### 14.5 聊天正文的可点性信号(Clickability in message bodies)
+**桌面消息链接的操作(2026-10-16)**:用户消息与 AI 消息共用同一套点击与右键语义。
+任务链接右键提供「在当前窗口打开」「在新窗口打开」「复制链接」;Shift+点击、⌘/Ctrl+点击和
+中键点击均在新窗口打开,保留来源电脑与消息锚点,不切换原窗口或分屏 pane。
+嵌入式任务内容不拥有宿主路由,任务链接直接开新窗口,其菜单不提供当前窗口跳转。
+
+网页普通点击沿用用户的内置/系统浏览器偏好;上述修饰键和中键临时使用系统浏览器,
+不修改偏好。文件链接普通点击沿用预览/审查等原行为,修饰键和中键交给默认应用,
+HTML 则交给系统浏览器;远程文件复用现有下载缓存/HTML 预览通道,不读取本机同名路径。
+安全降级附件仍只允许另存,不因快捷键扩大打开能力。项目链接提供「定位到项目」与
+复制链接菜单;文内标题和媒体链接保留各自定位/预览动作,并可复制链接。
+
+菜单按对象精简并平铺,不使用「更多」或「打开方式」子菜单。HTML 的标准菜单为
+「在侧边栏打开」「在浏览器打开」「查看源代码」/「在文件夹中显示」「复制路径」;
+远程文件将「在文件夹中显示」替换为「下载到本地」,两者只占同一位置。
+HTML 不提供复制文件、在文件列表中定位或选择应用。无侧边栏上下文时省略该打开项。
+普通文件保留文件列表定位、默认应用打开/本地定位或远程下载、复制、复制路径;
+仅带有效行号的文件引用额外提供「复制位置」。不把「复制」「复制位置」扩成长文案。
+网页只保留在侧边栏打开、在浏览器打开/复制链接;文内链接保留打开与复制链接。
+任务新窗口、外部浏览器和默认应用动作右侧标注 Shift+点击,提示不增加菜单项。
+无任务上下文的网页链接仍可右键复制和交给系统浏览器,只省略不可用的侧边栏项。
+键盘聚焦后 Enter 激活;Shift+Enter 保留 Shift+点击语义,Shift+F10/菜单键打开链接菜单,
+关闭菜单后焦点回到原链接。所有菜单复用语义主题组件,同时支持 Light/Dark。
+这组窗口与鼠标快捷键仅属于桌面端,不向手机增加无效的新窗口入口。
+实现见 `components/chat/linkInteraction.ts`、`useLinkContextMenu.tsx`、`useOpenWithMenu.tsx`
+与 `useFileChipContextMenu.tsx`(均位于 Desktop renderer)。
+
> 拍板 2026-07-30。起因:用户问「哪些是链接可以点、哪些不是,现在是不是看得不够清楚?」
> 排查结论是**两个独立缺陷叠在一起**,且方向相反——加强可点信号会放大误判,所以两者必须
> 一起修。本节是聊天正文(消息气泡 + 文件阅读器)可点性的权威口径。