Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(chat): preserve remote file safety and anchored link affordance
Dashf58157adfe45
diff --git a/apps/desktop/src/renderer/__tests__/fileChipCopyLocation.test.tsx b/apps/desktop/src/renderer/__tests__/fileChipCopyLocation.test.tsxindex 9104c4b6b2..8277d77d14 100644--- a/apps/desktop/src/renderer/__tests__/fileChipCopyLocation.test.tsx+++ b/apps/desktop/src/renderer/__tests__/fileChipCopyLocation.test.tsx@@ -63,12 +63,15 @@ function FileReference({location,directory = false,html = false,+ fileName = 'example.ts',}: {location?: FileLocation;directory?: boolean;html?: boolean;+ fileName?: string;}) {const { onContextMenu, onActivate, openAt, menu } = useFileChipContextMenu({+ fileName,getAbsPath: mocks.getAbsPath,sidebarFileBrowserKind: directory ? 'directory' : 'file',location,@@ -129,6 +132,20 @@ beforeEach(() => {afterEach(cleanup);describe('file chip Copy Location action', () => {+ it.each([+ { kind: 'device', deviceId: 'remote-computer' },+ { kind: 'ssh', remoteHostId: 'ssh-host' },+ ])('hides default-app opening for remote scripts (%j)', async (origin) => {+ mocks.context.origin = origin;+ render(<FileReference fileName="script.PS1" />);+ fireEvent.contextMenu(screen.getByRole('button', { name: 'file reference' }));+ const download = await screen.findByRole('menuitem', { name: 'chat.remoteFile.downloadToLocal' });+ expect(screen.queryByRole('menuitem', { name: /chat.media.openWithApp/ })).toBeNull();+ fireEvent.click(download);+ await waitFor(() => expect(mocks.download).toHaveBeenCalled());+ expect(mocks.openPath).not.toHaveBeenCalled();+ });+it.each(['ContextMenu', 'F10'])('restores focus to the latest keyboard trigger (%s)', async (key) => {render(<FileReference />);const file = screen.getByRole('button', { name: 'file reference' });diff --git a/apps/desktop/src/renderer/__tests__/remoteFileProgress.test.ts b/apps/desktop/src/renderer/__tests__/remoteFileProgress.test.tsindex b3860ba56c..7136111ebb 100644--- a/apps/desktop/src/renderer/__tests__/remoteFileProgress.test.ts+++ b/apps/desktop/src/renderer/__tests__/remoteFileProgress.test.ts@@ -1,5 +1,5 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { downloadRemoteChatEntry, fetchChatFileWithToasts } from '../lib/remoteFileOpen';+import { downloadRemoteChatEntry, fetchChatFileWithToasts, openRemoteChatFile } from '../lib/remoteFileOpen';import { getToastSnapshot, toast } from '../lib/toast';import messages from '../i18n/locales/en/common.json';import {@@ -29,6 +29,7 @@ const chatFetch = vi.fn();const chatDownload = vi.fn();const chatCancel = vi.fn();const showItemInFolder = vi.fn();+const openPath = vi.fn();const success = { ok: true as const, cachePath: '/cache/file.zip', stale: false, size: 4096 };function deferred<T>() {@@ -60,6 +61,7 @@ beforeEach(() => {chatDownload.mockReset();chatCancel.mockReset().mockResolvedValue(undefined);showItemInFolder.mockReset().mockResolvedValue({ success: true });+ openPath.mockReset().mockResolvedValue({ success: true });vi.stubGlobal('window', {electronAPI: {fileBrowser: {@@ -72,6 +74,7 @@ beforeEach(() => {},},showItemInFolder,+ openPath,},});});@@ -86,6 +89,58 @@ afterEach(() => {});describe('remote file transfer toasts', () => {+ describe.each([origin, { kind: 'ssh' as const, remoteHostId: 'ssh-host' }])(+ 'default application safety (%j)',+ (remote) => {+ it.each(['/remote/file.js', '/remote/file.bat', 'C:\\remote\\file.PS1'])(+ 'downloads dangerous file %s without opening it',+ async (path) => {+ chatDownload.mockResolvedValue({ ok: true, path: '/downloads/file', stale: false, skipped: 0 });+ await openRemoteChatFile(remote, workdir, path);+ expect(chatFetch).not.toHaveBeenCalled();+ expect(chatDownload).toHaveBeenCalledWith(expect.objectContaining({ origin: remote, absPath: path }));+ expect(showItemInFolder).toHaveBeenCalledTimes(1);+ expect(openPath).not.toHaveBeenCalled();+ },+ );++ it('opens only a safe cache path after successful fetch', async () => {+ chatFetch.mockResolvedValue(success);+ await openRemoteChatFile(remote, workdir, absPath);+ expect(openPath).toHaveBeenCalledWith(success.cachePath);+ expect(chatDownload).not.toHaveBeenCalled();+ });++ it('also refuses an executable cache path for a safe original name', async () => {+ chatFetch.mockResolvedValue({ ...success, cachePath: '/cache/payload.js' });+ chatDownload.mockResolvedValue({ ok: true, path: '/downloads/file.zip', stale: false, skipped: 0 });+ await openRemoteChatFile(remote, workdir, absPath);+ expect(openPath).not.toHaveBeenCalled();+ expect(chatDownload).toHaveBeenCalledWith(expect.objectContaining({ absPath }));+ });++ it('does not open or download after fetch failure', async () => {+ chatFetch.mockRejectedValue(new Error('offline'));+ await openRemoteChatFile(remote, workdir, absPath);+ expect(openPath).not.toHaveBeenCalled();+ expect(chatDownload).not.toHaveBeenCalled();+ });++ it('does not open a late successful fetch after cancellation', async () => {+ const result = deferred<typeof success>();+ chatFetch.mockReturnValue(result.promise);+ const pending = openRemoteChatFile(remote, workdir, absPath);+ await vi.advanceTimersByTimeAsync(600);+ active()[0].action?.onClick();+ result.resolve(success);+ await pending;+ expect(openPath).not.toHaveBeenCalled();+ expect(chatDownload).not.toHaveBeenCalled();+ expect(listeners.size).toBe(0);+ });+ },+ );+it('preview observers ignore other requests and stop immediately on unmount', () => {const a = vi.fn();const b = vi.fn();diff --git a/apps/desktop/src/renderer/components/chat/AgentActionRow.tsx b/apps/desktop/src/renderer/components/chat/AgentActionRow.tsxindex 5dfd272e0f..bed70363e9 100644--- a/apps/desktop/src/renderer/components/chat/AgentActionRow.tsx+++ b/apps/desktop/src/renderer/components/chat/AgentActionRow.tsx@@ -1010,6 +1010,7 @@ export function AgentActionRow({// Claude 取 file_path,Codex 单文件 change 取目标路径 —— 模型可能给相对// 路径(见 onActivate 注释),菜单动作统一经 resolveToolFilePath 补成绝对路径。const fileChipMenu = useFileChipContextMenu({+ fileName: chipFilePath,getAbsPath: () => resolveToolFilePath(chipFilePath, fileCtx.workingDir),canOpenInBrowser: isBrowserOpenablePath(chipFilePath),});diff --git a/apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx b/apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsxindex 6fbde210ed..00f6ae19d3 100644--- a/apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx+++ b/apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx@@ -264,6 +264,7 @@ function GeneratedFileChip({const htmlWithSession = isHtmlFilePath(file.path) ? fileCtx.sessionId : undefined;const sidebarTargetSessionId = useSidebarTargetSessionId(htmlWithSession);const ctxMenu = useFileChipContextMenu({+ fileName: file.path,getAbsPath: () => file.path,// HTML 左键看渲染结果;源码仍可从右键菜单进入。其它生成文件沿用原菜单。canOpenInBrowser: isBrowserOpenablePath(file.path),diff --git a/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx b/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsxindex 6449ba71ce..e099dc897b 100644--- a/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx+++ b/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx@@ -1020,6 +1020,7 @@ function FileTargetChip({localKind !== 'directory' && isHtmlFilePath(resolvedAbsPath) && sessionId ? sessionId : undefined;const sidebarTargetSessionId = useSidebarTargetSessionId(htmlWithSession);const ctxMenu = useFileChipContextMenu({+ fileName: resolvedAbsPath,getAbsPath: async () => resolvedAbsPath,location: { absPath: resolvedAbsPath, line, column },canOpenInBrowser: localKind !== 'directory' && isBrowserOpenablePath(resolvedAbsPath),@@ -1133,6 +1134,7 @@ function ResolvedLocalLink({localKind !== 'directory' && isHtmlFilePath(resolvedAbsPath) && sessionId ? sessionId : undefined;const sidebarTargetSessionId = useSidebarTargetSessionId(htmlWithSession);const ctxMenu = useFileChipContextMenu({+ fileName: resolvedAbsPath,getAbsPath: () => resolvedAbsPath,location: { absPath: resolvedAbsPath, line, column },canOpenInBrowser: localKind !== 'directory' && isBrowserOpenablePath(resolvedAbsPath),diff --git a/apps/desktop/src/renderer/components/chat/QuoteChip.tsx b/apps/desktop/src/renderer/components/chat/QuoteChip.tsxindex 03e1af7cd4..9d0a649b24 100644--- a/apps/desktop/src/renderer/components/chat/QuoteChip.tsx+++ b/apps/desktop/src/renderer/components/chat/QuoteChip.tsx@@ -13,12 +13,14 @@ import { InlineReferenceChip } from './InlineReferenceChip';interface QuoteChipProps {quote: ChatQuote;selected?: boolean;+ className?: string;}/** 渲染紧凑、不可选中的引用摘要;完整内容仅在 tooltip 中展开。 */export function QuoteChip({quote,selected = false,+ className,}: QuoteChipProps) {const sourceLabel = quoteSourceDisplayLabel(quote);const compactText = quote.text.replace(/\s+/g, ' ').trim();@@ -48,6 +50,7 @@ export function QuoteChip({tooltipContentClassName="max-h-64 w-80 max-w-[70vw] overflow-y-auto whitespace-normal"ariaLabel={quote.text}selected={selected}+ className={className}// 刻意的例外:chip 上是把换行折叠成单行的**摘要**,不是引用原文。让它进// 剪贴板等于把压扁过的文本混进复制结果,原文本身就在被引用的那条消息里。// 其余消息内 chip(文件名、会话、项目)展示的是完整实体名,默认可复制。diff --git a/apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx b/apps/desktop/src/renderer/components/chat/SessionLinkChip.tsxindex 3e8a2c6d43..858472ee5f 100644--- a/apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx+++ b/apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx@@ -207,7 +207,7 @@ export function SessionLinkChip({ href, label }: SessionLinkChipProps) {// 发给模型的上下文范围(条数 / 是否截断)不在气泡里展示:用户无从理解也无从操作。const messageContent = (<span className="inline-flex min-w-0 max-w-[min(240px,55vw)]">- <QuoteChip quote={{ text: visibleMessageLabel }} />+ <QuoteChip quote={{ text: visibleMessageLabel }} className="underline underline-offset-2" /></span>);// items-center 保证 pill 保持自身高度(不被 align-items: stretch 撑成椭圆)。diff --git a/apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx b/apps/desktop/src/renderer/components/chat/TurnChangesCard.tsxindex 2d4e5cb445..80159f7595 100644--- a/apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx+++ b/apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx@@ -50,6 +50,7 @@ function TurnChangeFileRow({const absolutePath = resolveToolFilePath(file.path, cwd);const htmlWithSession = isHtmlFilePath(absolutePath) ? sessionId : undefined;const contextMenu = useFileChipContextMenu({+ fileName: absolutePath,getAbsPath: () => absolutePath,canOpenInBrowser: isBrowserOpenablePath(absolutePath),sidebarOpenSessionId: htmlWithSession,diff --git a/apps/desktop/src/renderer/components/chat/UserAttachmentChip.tsx b/apps/desktop/src/renderer/components/chat/UserAttachmentChip.tsxindex d5a2136d7a..7736ac5562 100644--- a/apps/desktop/src/renderer/components/chat/UserAttachmentChip.tsx+++ b/apps/desktop/src/renderer/components/chat/UserAttachmentChip.tsx@@ -42,6 +42,7 @@ export function UserAttachmentChip({const downloadOnly = isSafetyDowngradedAttachment(file);// Rules-of-hooks:两个菜单 hook/状态都无条件建,按 downloadOnly 选用其一。const ctxMenu = useFileChipContextMenu({+ fileName: file.name,getAbsPath: () => file.path,canOpenInBrowser: isBrowserOpenablePath(file.path),});diff --git a/apps/desktop/src/renderer/components/chat/UserMessage.tsx b/apps/desktop/src/renderer/components/chat/UserMessage.tsxindex 1369a48359..bbb5580d45 100644--- a/apps/desktop/src/renderer/components/chat/UserMessage.tsx+++ b/apps/desktop/src/renderer/components/chat/UserMessage.tsx@@ -246,6 +246,7 @@ function UserFileChip({// 按 workdir 风格直接 join(与 useResolvedMarkdownTarget 的 remote 分支同策)。const chipRemote = isRemoteFileOrigin(useChatSessionFile().origin);const ctxMenu = useFileChipContextMenu({+ fileName: refText,getAbsPath: async () => {if (chipRemote) return resolveLocalPath(refText, workingDir);const r = await resolveLocalPathSmart(refText, workingDir);diff --git a/apps/desktop/src/renderer/components/chat/UserMessageImageLink.tsx b/apps/desktop/src/renderer/components/chat/UserMessageImageLink.tsxindex 06399f3282..4b14d27b95 100644--- a/apps/desktop/src/renderer/components/chat/UserMessageImageLink.tsx+++ b/apps/desktop/src/renderer/components/chat/UserMessageImageLink.tsx@@ -10,7 +10,7 @@ export function UserMessageImageLink({path: string;onOpen?: (url: string) => void;}) {- const fileMenu = useFileChipContextMenu({ getAbsPath: () => path });+ const fileMenu = useFileChipContextMenu({ fileName: path, getAbsPath: () => path });const open = () => onOpen?.(toLocalFileUrl(path));return (<>diff --git a/apps/desktop/src/renderer/components/chat/__tests__/embeddedSessionNavigation.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/embeddedSessionNavigation.test.tsxindex 955d220b02..e841490b6a 100644--- a/apps/desktop/src/renderer/components/chat/__tests__/embeddedSessionNavigation.test.tsx+++ b/apps/desktop/src/renderer/components/chat/__tests__/embeddedSessionNavigation.test.tsx@@ -283,10 +283,9 @@ describe('sidebar-embedded session navigation boundary', () => {expect(mocks.navigate).not.toHaveBeenCalled();});- it('keeps the anchored pill on a single line without a context range summary', async () => {- const { container } = render(- <SessionLinkChip href="cindy://session/session-a?message=message-1" label="Session A" />,- );+ it.each([false, true])('keeps the anchored pill visibly clickable and on a single line (embedded=%s)', async (isEmbedded) => {+ const chip = <SessionLinkChip href="cindy://session/session-a?message=message-1" label="Session A" />;+ const { container } = render(isEmbedded ? embedded(chip) : chip);await act(async () => {await Promise.resolve();});@@ -295,6 +294,7 @@ describe('sidebar-embedded session navigation boundary', () => {const link = container.querySelector('button[data-session-message-link]');expect(link?.className).toContain('items-center');expect(link?.textContent).toBe('Session A');+ expect(container.querySelector('[data-inline-reference-chip]')?.className).toContain('underline');expect(container.querySelector('[data-inline-reference-chip]')?.parentElement?.className,).toContain('max-w-[min(240px,55vw)]');diff --git a/apps/desktop/src/renderer/components/chat/__tests__/sidebarEmbeddedActionTarget.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/sidebarEmbeddedActionTarget.test.tsxindex bad045114a..732bf5c0fd 100644--- a/apps/desktop/src/renderer/components/chat/__tests__/sidebarEmbeddedActionTarget.test.tsx+++ b/apps/desktop/src/renderer/components/chat/__tests__/sidebarEmbeddedActionTarget.test.tsx@@ -61,6 +61,7 @@ import { useOpenWithMenu } from '../useOpenWithMenu';function ActionProbe({ html = false }: { html?: boolean }) {const menu = useFileChipContextMenu({+ fileName: html ? 'index.html' : 'index.md',getAbsPath: () => (html ? '/repo/src/index.html' : '/repo/src/index.md'),canOpenInBrowser: html,sidebarOpenSessionId: 'worker-a',@@ -77,6 +78,7 @@ function ActionProbe({ html = false }: { html?: boolean }) {function ExternalFileActionProbe() {const menu = useFileChipContextMenu({+ fileName: 'outside.md',getAbsPath: () => 'C:\\tmp\\outside.md',});return (diff --git a/apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx b/apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsxindex b448a9651f..b7607e005f 100644--- a/apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx+++ b/apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx@@ -1,4 +1,5 @@import { shouldShowOpenPathError } from '../../../shared/openPathResult';+import { isDangerousAttachmentName } from '../../../shared/attachmentSafety';/** 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. */@@ -62,6 +63,7 @@ export interface UseFileChipContextMenu {/** sidebarOpenSessionId overrides the browser target, never the file origin.* onViewSource reuses a caller's preview; other HTML references use TextLightbox. */export function useFileChipContextMenu({+ fileName,getAbsPath,canOpenInBrowser = false,sidebarFileBrowserKind = 'file',@@ -69,6 +71,8 @@ export function useFileChipContextMenu({onViewSource,location,}: {+ /** Menu eligibility only; remote opening also checks the resolved path. */+ fileName: string;getAbsPath: () => Promise<string> | string;canOpenInBrowser?: boolean;sidebarFileBrowserKind?: 'file' | 'directory';@@ -244,8 +248,11 @@ export function useFileChipContextMenu({void action().catch(() => toast.error(t('chat.markdownRenderer.openLinkFailed')));};const canLocateInSidebar = Boolean(sidebarFileTargetSessionId && sessionFileCtx.workingDir);+ const canOpenWithDefault =+ sidebarFileBrowserKind === 'file' &&+ !(remoteOrigin && isDangerousAttachmentName(fileName));const hasOpenActions =- canOpenInBrowser || canLocateInSidebar || sidebarFileBrowserKind === 'file';+ canOpenInBrowser || canLocateInSidebar || canOpenWithDefault;const menu = (<><DropdownMenu@@ -305,7 +312,7 @@ export function useFileChipContextMenu({{t('chat.markdownRenderer.openInSidebarFileBrowser')}</DropdownMenuItem>) : null}- {sidebarFileBrowserKind === 'file' ? (+ {canOpenWithDefault ? (<DropdownMenuItem onClick={run(handleOpenWithDefault)}><AppWindow className="mr-2 h-4 w-4" />{t('chat.media.openWithApp')}diff --git a/apps/desktop/src/renderer/lib/remoteFileOpen.ts b/apps/desktop/src/renderer/lib/remoteFileOpen.tsindex 33edf022ef..2b86cb37d2 100644--- a/apps/desktop/src/renderer/lib/remoteFileOpen.ts+++ b/apps/desktop/src/renderer/lib/remoteFileOpen.ts@@ -1,4 +1,5 @@import { shouldShowOpenPathError } from '../../shared/openPathResult';+import { isDangerousAttachmentName } from '../../shared/attachmentSafety';/*** remoteFileOpen — 聊天流文件类交互的远程分流入口(renderer 侧)。* ---------------------------------------------------------------------------@@ -96,8 +97,18 @@ export async function openRemoteChatFile(workdir: string,absPath: string,): Promise<void> {+ // Remote scripts/installers follow the attachment save-only policy. Guard the+ // common entry so menu, modifier-click and ordinary fallback cannot diverge.+ if (isDangerousAttachmentName(absPath)) {+ await downloadRemoteChatEntry(origin, workdir, absPath);+ return;+ }const cachePath = await fetchChatFileWithToasts(origin, workdir, absPath);if (!cachePath) return;+ if (isDangerousAttachmentName(cachePath)) {+ await downloadRemoteChatEntry(origin, workdir, absPath);+ return;+ }const res = await window.electronAPI.openPath(cachePath);if (shouldShowOpenPathError(res)) toast.error(res.error || i18n.t('logic.errors.openFileFailed'));}diff --git a/docs/design-rules/DESIGN.md b/docs/design-rules/DESIGN.mdindex 5cb3b13717..02047decf9 100644--- a/docs/design-rules/DESIGN.md+++ b/docs/design-rules/DESIGN.md@@ -1177,7 +1177,8 @@ Only the two registered chart members inside Usage History may enlarge their non网页普通点击沿用用户的内置/系统浏览器偏好;上述修饰键和中键临时使用系统浏览器,不修改偏好。文件链接普通点击沿用预览/审查等原行为,修饰键和中键交给默认应用,HTML 则交给系统浏览器;远程文件复用现有下载缓存/HTML 预览通道,不读取本机同名路径。-安全降级附件仍只允许另存,不因快捷键扩大打开能力。项目链接提供「定位到项目」与+安全降级附件仍只允许另存,不因快捷键扩大打开能力。远程文件若命中已有危险扩展名规则,+快捷打开改为下载到本地,菜单省略默认应用打开。项目链接提供「定位到项目」与复制链接菜单;嵌入式项目引用只保留复制菜单,不带按钮语义、手形指针或下划线,仍可聚焦并用 Shift+F10/菜单键打开菜单。文内标题和媒体链接保留各自定位/预览动作,并可复制链接。