Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): 修复 sandbox: 文件链接不可点并补齐聊天文件交互 (#1835)
DavidShenXD5788041d8834
diff --git a/apps/desktop/src/main/__tests__/openWithApps.test.ts b/apps/desktop/src/main/__tests__/openWithApps.test.tsnew file mode 100644index 0000000000..94613b82f1--- /dev/null+++ b/apps/desktop/src/main/__tests__/openWithApps.test.ts@@ -0,0 +1,190 @@+import { describe, expect, it, vi } from 'vitest';++import {+ createOpenWithHandlers,+ decodeRegOutput,+ expandWindowsEnv,+ parseChcpCodepage,+ parseCommandLineExe,+ parseRegSubkeys,+ parseRegValues,+ type OpenWithDeps,+} from '../openWithApps';++describe('parseCommandLineExe', () => {+ it('extracts quoted and unquoted executable paths', () => {+ expect(parseCommandLineExe('"C:\\Program Files\\App\\app.exe" "%1"')).toBe(+ 'C:\\Program Files\\App\\app.exe',+ );+ expect(parseCommandLineExe('C:\\Tools\\a.exe %1')).toBe('C:\\Tools\\a.exe');+ // 无引号但路径含空格的老注册表项:按 .exe 边界截。+ expect(parseCommandLineExe('C:\\Program Files\\App\\app.exe /open %1')).toBe(+ 'C:\\Program Files\\App\\app.exe',+ );+ expect(parseCommandLineExe('')).toBeNull();+ expect(parseCommandLineExe('"unterminated')).toBeNull();+ });+});++describe('expandWindowsEnv', () => {+ it('expands %VAR% references and keeps unknown ones verbatim', () => {+ expect(expandWindowsEnv('%SystemRoot%\\notepad.exe', { SystemRoot: 'C:\\Windows' })).toBe(+ 'C:\\Windows\\notepad.exe',+ );+ expect(expandWindowsEnv('%NOPE%\\a.exe', {})).toBe('%NOPE%\\a.exe');+ });+});++describe('reg.exe output parsing', () => {+ it('parses value rows with names, types and data', () => {+ const stdout = [+ 'HKEY_CURRENT_USER\\...\\OpenWithList',+ ' a REG_SZ EXCEL.EXE',+ ' b REG_SZ notepad.exe',+ ' MRUList REG_SZ ab',+ '',+ ].join('\r\n');+ expect(parseRegValues(stdout)).toEqual([+ { name: 'a', data: 'EXCEL.EXE' },+ { name: 'b', data: 'notepad.exe' },+ { name: 'MRUList', data: 'ab' },+ ]);+ });++ it('parses empty-data rows (OpenWithProgids REG_NONE values)', () => {+ const stdout = ['HKEY_CLASSES_ROOT\\.xlsx\\OpenWithProgids', ' Excel.Sheet.12 REG_NONE ', ''].join(+ '\r\n',+ );+ expect(parseRegValues(stdout)).toEqual([{ name: 'Excel.Sheet.12', data: '' }]);+ });++ it('parses subkey listings relative to the parent key', () => {+ const parent = 'HKCR\\.xlsx\\OpenWithList';+ const stdout = [+ 'HKCR\\.xlsx\\OpenWithList\\EXCEL.EXE',+ 'HKCR\\.xlsx\\OpenWithList\\wps.exe',+ '',+ ].join('\r\n');+ expect(parseRegSubkeys(stdout, parent)).toEqual(['EXCEL.EXE', 'wps.exe']);+ });+});++describe('reg.exe output decoding', () => {+ it('decodes GBK bytes with codepage 936 (中文系统 reg.exe 实际输出)', () => {+ // 「工作表」的 GBK 编码字节;按 UTF-8 解会全变 U+FFFD。+ const gbk = new Uint8Array([0xb9, 0xa4, 0xd7, 0xf7, 0xb1, 0xed]);+ expect(decodeRegOutput(gbk, 936)).toBe('工作表');+ expect(decodeRegOutput(gbk, null)).toContain('�');+ });++ it('falls back to UTF-8 for unknown or unmapped codepages', () => {+ const utf8 = new TextEncoder().encode('Notepad');+ expect(decodeRegOutput(utf8, null)).toBe('Notepad');+ expect(decodeRegOutput(utf8, 850)).toBe('Notepad');+ expect(decodeRegOutput(new TextEncoder().encode('メモ帳'), 65001)).toBe('メモ帳');+ });++ it('parses chcp output across locales', () => {+ expect(parseChcpCodepage('活动代码页: 936\r\n')).toBe(936);+ expect(parseChcpCodepage('Active code page: 437\r\n')).toBe(437);+ expect(parseChcpCodepage('')).toBeNull();+ });+});++/** 以「.xlsx 有 MRU + ProgId 两个来源」为形状的假注册表。 */+function makeDeps(overrides: Partial<OpenWithDeps> = {}): OpenWithDeps & {+ spawnDetached: ReturnType<typeof vi.fn>;+} {+ const registry: Record<string, string> = {+ 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\.xlsx\\OpenWithList':+ ' a REG_SZ EXCEL.EXE\r\n MRUList REG_SZ a\r\n',+ 'HKCR\\Applications\\EXCEL.EXE\\shell\\open\\command':+ ' (Default) REG_SZ "C:\\Office\\EXCEL.EXE" "%1"\r\n',+ 'HKCR\\Applications\\EXCEL.EXE': ' FriendlyAppName REG_SZ Microsoft Excel\r\n',+ 'HKCR\\.xlsx\\OpenWithProgids': ' Wps.Sheet REG_NONE \r\n',+ 'HKCR\\Wps.Sheet\\shell\\open\\command':+ ' (Default) REG_SZ "C:\\WPS\\wps.exe" "%1"\r\n',+ 'HKCR\\Wps.Sheet': ' (Default) REG_SZ WPS 表格\r\n',+ };+ const spawnDetached = vi.fn();+ const base: OpenWithDeps = {+ platform: 'win32',+ isPathAllowed: () => true,+ fileExists: () => true,+ regQuery: async (keyPath: string) => registry[keyPath] ?? '',+ getAppIcon: async () => null,+ spawnDetached,+ };+ return { ...base, ...overrides, spawnDetached };+}++const FILE = 'C:\\work\\报表.xlsx';++describe('createOpenWithHandlers.list', () => {+ it('enumerates registry apps, resolves labels and dedupes by exe path', async () => {+ const handlers = createOpenWithHandlers(makeDeps());+ const res = await handlers.list({ filePath: FILE });+ expect(res.success).toBe(true);+ expect(res.apps.map((a) => a.label)).toEqual(['Microsoft Excel', 'WPS 表格']);+ });++ it('skips entries whose executable no longer exists', async () => {+ const deps = makeDeps({ fileExists: (p: string) => p !== 'C:\\WPS\\wps.exe' });+ const handlers = createOpenWithHandlers(deps);+ const res = await handlers.list({ filePath: FILE });+ expect(res.success).toBe(true);+ expect(res.apps.map((a) => a.label)).toEqual(['Microsoft Excel']);+ });++ it('returns an empty list on non-Windows platforms', async () => {+ const handlers = createOpenWithHandlers(makeDeps({ platform: 'darwin' }));+ const res = await handlers.list({ filePath: '/tmp/a.xlsx' });+ expect(res).toEqual({ success: true, apps: [] });+ });++ it('fails soft when the target path is rejected', async () => {+ const handlers = createOpenWithHandlers(makeDeps({ isPathAllowed: () => false }));+ const res = await handlers.list({ filePath: FILE });+ expect(res.success).toBe(false);+ expect(res.apps).toEqual([]);+ });+});++describe('createOpenWithHandlers.open', () => {+ it('opens via the main-side appId mapping only', async () => {+ const deps = makeDeps();+ const handlers = createOpenWithHandlers(deps);+ const res = await handlers.list({ filePath: FILE });+ const excel = res.apps.find((a) => a.label === 'Microsoft Excel');+ expect(excel).toBeDefined();+ await handlers.open({ filePath: FILE, appId: excel!.id });+ expect(deps.spawnDetached).toHaveBeenCalledWith('C:\\Office\\EXCEL.EXE', [FILE]);+ });++ it('rejects appIds that never came from an enumeration', async () => {+ const deps = makeDeps();+ const handlers = createOpenWithHandlers(deps);+ // 未 list 先 open:映射为空,任何 appId(包括看似路径的字符串)都拒绝。+ await expect(+ handlers.open({ filePath: FILE, appId: 'C:\\evil\\payload.exe' }),+ ).rejects.toThrow(/NOT_FOUND/);+ expect(deps.spawnDetached).not.toHaveBeenCalled();+ });++ it('validates the file path before spawning', async () => {+ const deps = makeDeps();+ const handlers = createOpenWithHandlers(deps);+ await expect(handlers.open({ filePath: 'relative.xlsx', appId: 'x' })).rejects.toThrow(+ /INVALID_PARAMS/,+ );+ });+});++describe('createOpenWithHandlers surface', () => {+ it('exposes only list/open — no system OpenAs dialog escape hatch', () => {+ // 「选择其他应用…」已下线(系统 OpenAs 对话框实测起不来,且与 Codex 形态+ // 不符),对应的 choose handler 与 showOpenAppDialog 依赖一并移除。+ const handlers = createOpenWithHandlers(makeDeps());+ expect(Object.keys(handlers).sort()).toEqual(['list', 'open']);+ });+});diff --git a/apps/desktop/src/main/__tests__/shellOpenPath.test.ts b/apps/desktop/src/main/__tests__/shellOpenPath.test.tsindex 35f920c922..195849dcd2 100644--- a/apps/desktop/src/main/__tests__/shellOpenPath.test.ts+++ b/apps/desktop/src/main/__tests__/shellOpenPath.test.ts@@ -13,6 +13,16 @@ describe('resolveShellOpenPathTarget', () => {expect(resolveShellOpenPathTarget(target)).toBe(target);});+ it('normalizes separators to the host form (forward-slash Windows paths)', () => {+ // 正斜杠 Windows 路径过 shell.openPath 会解析失败,必须折成本机分隔符。+ // 仅 win32 主机可直接断言反斜杠;POSIX 上 normalize 幂等。+ if (process.platform === 'win32') {+ expect(resolveShellOpenPathTarget('C:/Users/a/文档.docx')).toBe('C:\\Users\\a\\文档.docx');+ } else {+ expect(resolveShellOpenPathTarget('/tmp/a//b.txt')).toBe('/tmp/a/b.txt');+ }+ });+it('resolves a valid cindy-media reference inside the main process', () => {const hash = 'a'.repeat(64);expect(resolveShellOpenPathTarget(`cindy-media://blobs/${hash}.ogg`)).toBe(diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex a024efc748..1bc25915c5 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -252,6 +252,7 @@ import {isPathAllowedAgainst,} from './filePathPolicy';import { readFileThumbnail } from './fileThumbnail';+import { createOpenWithHandlers, decodeRegOutput, parseChcpCodepage } from './openWithApps';import { resolveShellOpenPathTarget } from './shellOpenPath';import { handleOpenFileInBrowser } from './openFileInBrowser';import { createWindowsFileUrlOpener } from './windowsFileUrlOpener';@@ -5232,6 +5233,78 @@ const registerIpcHandlers = () => {},);+ // 文件 chip 右键「打开方式」:枚举 / 指定应用打开 / 系统选择对话框。+ // 业务体在 openWithApps.ts(依赖注入,单测直接调 handler body);appId → exe+ // 映射只存 main 侧,renderer 传路径执行在结构上不可表达(该文件头注释)。+ {+ // app.getFileIcon 会偶发挂死(见 fileThumbnail.ts),这里同款硬超时 + 按+ // exe 路径的进程内缓存(打开方式菜单反复展开不重复付原生调用成本)。+ const appIconCache = new Map<string, string | null>();+ const getAppIcon = async (exePath: string): Promise<string | null> => {+ const key = exePath.toLowerCase();+ const cached = appIconCache.get(key);+ if (cached !== undefined) return cached;+ try {+ const icon = await Promise.race([+ app.getFileIcon(exePath, { size: 'small' }),+ new Promise<null>((resolve) => setTimeout(() => resolve(null), 4000)),+ ]);+ const dataUrl = icon && !icon.isEmpty() ? icon.toDataURL() : null;+ appIconCache.set(key, dataUrl);+ return dataUrl;+ } catch {+ appIconCache.set(key, null);+ return null;+ }+ };+ // reg.exe 重定向输出走控制台代码页(中文系统 GBK)而非 UTF-8,按字节取回、+ // 用 chcp 探测到的代码页解码,否则中文应用名会变 U+FFFD 乱码。+ let consoleCodepagePromise: Promise<number | null> | null = null;+ const getConsoleCodepage = (): Promise<number | null> => {+ consoleCodepagePromise ??= new Promise((resolve) => {+ execFile('chcp.com', { windowsHide: true, timeout: 3000 }, (err, stdout) => {+ resolve(err ? null : parseChcpCodepage(String(stdout ?? '')));+ });+ });+ return consoleCodepagePromise;+ };+ const openWith = createOpenWithHandlers({+ platform: process.platform,+ isPathAllowed,+ fileExists: (p) => fs.existsSync(p),+ regQuery: async (keyPath, args = []) => {+ const codepage = await getConsoleCodepage();+ return new Promise<string>((resolve) => {+ execFile(+ 'reg.exe',+ ['query', keyPath, ...args],+ { windowsHide: true, timeout: 5000, encoding: 'buffer' },+ (err, stdout) => resolve(err ? '' : decodeRegOutput(stdout ?? Buffer.alloc(0), codepage)),+ );+ });+ },+ getAppIcon,+ spawnDetached: (command, args) => {+ const child = spawn(command, args, { detached: true, stdio: 'ignore', windowsHide: false });+ // detached 子进程无人监听 'error' 会变成 EventEmitter 未处理错误直接压垮+ // main(典型:existsSync 通过后 exe 被卸载的窗口期)。spawn 错误是异步的,+ // IPC 已返回,只能记日志兜底(PR #1835 review)。+ child.once('error', (err) => {+ createLogger('open-with').warn('spawn failed', { command, message: err.message });+ });+ child.unref();+ },+ });+ ipcMain.handle('open-with:list', (event, params: { filePath: string }) => {+ assertTrustedAppRendererEvent(event);+ return openWith.list(params);+ });+ ipcMain.handle('open-with:open', (event, params: { filePath: string; appId: string }) => {+ assertTrustedAppRendererEvent(event);+ return openWith.open(params);+ });+ }+// 安全降级附件“另存为”:源文件必须通过统一路径策略,解析真实路径后还要// 位于聊天附件/远程文件缓存内;建议名在 main 侧清洗,复制完成后不调用// openPath,避免符号链接越界或恢复原扩展名后被自动执行。@@ -5434,6 +5507,9 @@ const registerIpcHandlers = () => {if (!absPath) {return { success: false, error: 'url 或 filePath 必须二选一' };}+ // Windows Explorer /select 不认正斜杠路径(showItemInFolder 会静默无反应),+ // 归一成本机分隔符;POSIX 幂等。+ absPath = path.normalize(absPath);if (!isPathAllowed(absPath)) {return { success: false, error: '不允许访问该路径' };}diff --git a/apps/desktop/src/main/fsBrowse/ipc.ts b/apps/desktop/src/main/fsBrowse/ipc.tsindex 2c00851f89..9b6a6c5f7f 100644--- a/apps/desktop/src/main/fsBrowse/ipc.ts+++ b/apps/desktop/src/main/fsBrowse/ipc.ts@@ -41,6 +41,10 @@ export interface FsListDirResult {export interface FsStatResult {kind: 'dir' | 'file' | 'missing';resolvedPath: string;+ /** 文件最后修改时间(unix ms);仅 kind==='file' 时有值。「本轮产出文件」卡用它做时间窗校验。 */+ mtimeMs?: number;+ /** 文件创建时间(unix ms);仅 kind==='file'。部分 Linux FS 不支持时为 0,调用方需判 >0。 */+ birthtimeMs?: number;}export interface FsMkdirResult {resolvedPath: string;@@ -97,7 +101,9 @@ export async function statPath(rawPath: string): Promise<FsStatResult> {const resolvedPath = expandHome(rawPath);try {const st = await fs.stat(resolvedPath);- return { kind: st.isDirectory() ? 'dir' : 'file', resolvedPath };+ return st.isDirectory()+ ? { kind: 'dir', resolvedPath }+ : { kind: 'file', resolvedPath, mtimeMs: st.mtimeMs, birthtimeMs: st.birthtimeMs };} catch (err) {if ((err as NodeJS.ErrnoException)?.code === 'ENOENT') {return { kind: 'missing', resolvedPath };diff --git a/apps/desktop/src/main/openWithApps.ts b/apps/desktop/src/main/openWithApps.tsnew file mode 100644index 0000000000..f615194049--- /dev/null+++ b/apps/desktop/src/main/openWithApps.ts@@ -0,0 +1,321 @@+/**+ * openWithApps — 聊天文件 chip 右键「打开方式」的 main 侧能力。+ * ---------------------------------------------------------------------------+ * 三个动作:+ * - list:枚举系统里能打开某扩展名的应用(Windows 注册表;macOS 无免原生+ * 依赖的枚举 API,返回空列表,菜单只剩「默认应用 / 选择其他应用…」)。+ * - open:用枚举结果中的指定应用打开文件。+ * - choose:唤起系统「打开方式」选择(Windows OpenAs 对话框;macOS 选 .app+ * 后 `open -a`)。+ *+ * 安全设计(electron-security §5「IPC 是授权边界」):+ * - renderer 只能回传 **appId**,不能传可执行路径。appId → exe 的映射只存在+ * main 侧 per-扩展名缓存里,由本模块自己的枚举写入;open 时反查不到即拒绝。+ * 「renderer 递来一个绝对路径就执行」在结构上不可表达。+ * - 待打开的文件路径每次都重新过绝对路径 + isPathAllowed + 存在性校验。+ * - 枚举里剔除宿主进程(rundll32 等)——它们不是"应用",且可被用作参数注入+ * 的跳板。+ *+ * Windows 枚举口径(reg.exe query,零原生依赖):+ * HKCU FileExts\<ext>\OpenWithList(MRU)∪ HKCR/HKCU <ext>\OpenWithProgids+ * → exe 引用经 HKCR\Applications\<exe> / HKLM App Paths 解析,ProgId 经+ * HKCR\<ProgId>\shell\open\command 解析 → 去重、验存在。UWP/MSIX 应用不在+ * 这些键下,属已知盲区,由「选择其他应用…」兜底(计划内取舍)。+ *+ * 错误协议(engineering-conventions §2):list 是查询型,失败仍要渲染菜单其余+ * 项 → `{ success, apps }` 模式;open / choose 是动作型 → throwIpcError。+ */++import path from 'node:path';++import { throwIpcError } from './utils/ipcValidate.js';++export interface OpenWithApp {+ /** 会话内一次性 id;renderer 原样回传,main 反查 exe。 */+ id: string;+ label: string;+ /** app.getFileIcon 提取的 dataURL;提取失败缺省,renderer 显示通用图标。 */+ iconDataUrl?: string;+}++export interface ListOpenWithAppsResult {+ success: boolean;+ apps: OpenWithApp[];+ error?: string;+}++export interface OpenWithDeps {+ platform: NodeJS.Platform;+ isPathAllowed(absPath: string): boolean;+ fileExists(absPath: string): boolean;+ /**+ * `reg.exe query` 包装(仅 Windows 用)。返回 stdout;键不存在等查询失败按+ * 空 stdout 处理(reg.exe 对 not-found 返回非 0,包装层不抛)。+ */+ regQuery(keyPath: string, args?: string[]): Promise<string>;+ /** 应用图标 dataURL;实现方必须自带超时防护(app.getFileIcon 会挂死,见 fileThumbnail.ts)。 */+ getAppIcon(exePath: string): Promise<string | null>;+ /** detached + unref 起进程;不回传输出。 */+ spawnDetached(command: string, args: string[]): void;+}++export interface OpenWithHandlers {+ list(params: { filePath: string }): Promise<ListOpenWithAppsResult>;+ open(params: { filePath: string; appId: string }): Promise<void>;+}++/** 单次枚举的应用数上限:图标提取按个计价,列表长尾对用户也没有意义。 */+const MAX_APPS = 12;++/** 宿主/中转进程不作为「应用」列出(也避免被当作参数注入跳板)。 */+const HOST_EXE_DENYLIST = new Set([+ 'rundll32.exe',+ 'dllhost.exe',+ 'openwith.exe',+ 'explorer.exe',+ 'cmd.exe',+ 'powershell.exe',+ 'wscript.exe',+ 'cscript.exe',+ 'mshta.exe',+]);++/** REG_EXPAND_SZ 的 `%SystemRoot%` 等环境变量引用展开;未定义的原样保留。 */+export function expandWindowsEnv(value: string, env: Record<string, string | undefined>): string {+ return value.replace(/%([^%]+)%/g, (raw, name: string) => env[name] ?? env[name.toUpperCase()] ?? raw);+}++/** `"C:\x\a.exe" %1` / `C:\x\a.exe %1` → exe 路径;解析不出回 null。 */+export function parseCommandLineExe(command: string): string | null {+ const trimmed = command.trim();+ if (!trimmed) return null;+ if (trimmed.startsWith('"')) {+ const end = trimmed.indexOf('"', 1);+ return end > 1 ? trimmed.slice(1, end) : null;+ }+ // 无引号形态:exe 路径可能含空格(老注册表项),按 `.exe` 边界截。+ const m = trimmed.match(/^(.*?\.exe)(?=\s|$)/i);+ return m ? m[1] : trimmed.split(/\s+/)[0] ?? null;+}++/**+ * Windows 控制台代码页 → WHATWG TextDecoder label。reg.exe 重定向输出用的是+ * 控制台代码页(中文系统 936/GBK)而非 UTF-8,直接按 UTF-8 解码会把中文应用名+ * 变成 U+FFFD。只映射 TextDecoder 支持的常见页;OEM 437/850 等西文页不在+ * TextDecoder 支持面内,回落 UTF-8(ASCII 部分不受影响)。+ */+const CODEPAGE_DECODER_LABELS: Record<number, string> = {+ 932: 'shift_jis',+ 936: 'gb18030',+ 949: 'euc-kr',+ 950: 'big5',+ 866: 'ibm866',+ 874: 'windows-874',+ 1250: 'windows-1250',+ 1251: 'windows-1251',+ 1252: 'windows-1252',+ 1253: 'windows-1253',+ 1254: 'windows-1254',+ 1255: 'windows-1255',+ 1256: 'windows-1256',+ 1257: 'windows-1257',+ 1258: 'windows-1258',+ 65001: 'utf-8',+};++/** `chcp` 输出(如 `活动代码页: 936` / `Active code page: 437`)→ 代码页号。 */+export function parseChcpCodepage(stdout: string): number | null {+ const digits = stdout.match(/\d+/g)?.pop();+ return digits ? Number(digits) : null;+}++/** reg.exe 原始 stdout 字节 → 字符串;代码页未知或不支持时回落 UTF-8。 */+export function decodeRegOutput(data: Uint8Array, codepage: number | null): string {+ const label = (codepage != null && CODEPAGE_DECODER_LABELS[codepage]) || 'utf-8';+ try {+ return new TextDecoder(label).decode(data);+ } catch {+ return new TextDecoder('utf-8').decode(data);+ }+}++/** reg.exe query 输出 → 该键下的值列表(name + REG_SZ data)。 */+export function parseRegValues(stdout: string): Array<{ name: string; data: string }> {+ const out: Array<{ name: string; data: string }> = [];+ for (const line of stdout.split(/\r?\n/)) {+ // 形如 ` a REG_SZ Excel.exe`(data 可含空格)。+ const m = line.match(/^\s{2,}(\S(?:.*?\S)?)\s+(REG_[A-Z_]+)\s+(.*)$/);+ if (m) out.push({ name: m[1], data: m[3].trim() });+ }+ return out;+}++/** reg.exe query 输出 → 子键名列表(完整行是键路径,取末段)。 */+export function parseRegSubkeys(stdout: string, parentKey: string): string[] {+ const prefix = parentKey.replace(/\\+$/, '').toLowerCase() + '\\';+ const out: string[] = [];+ for (const line of stdout.split(/\r?\n/)) {+ const t = line.trim();+ if (t.toLowerCase().startsWith(prefix)) out.push(t.slice(prefix.length));+ }+ return out;+}++interface ResolvedApp {+ exePath: string;+ label: string;+}++function dedupeKey(exePath: string): string {+ return exePath.toLowerCase();+}++export function createOpenWithHandlers(deps: OpenWithDeps): OpenWithHandlers {+ // 该模块是可注入 platform 的纯函数,单测会在 Linux runner 模拟 win32。+ // 路径语义必须跟 deps.platform 走,不能跟测试宿主的 process.platform 走。+ const platformPath = deps.platform === 'win32' ? path.win32 : path.posix;+ // ext → (appId → exePath)。每次 list 整体重建该 ext 的映射;open 只认最近+ // 一次枚举写入的 id。进程内存态即可——菜单打开到点击是同进程短会话。+ const appCacheByExt = new Map<string, Map<string, string>>();++ function assertOpenableFile(filePath: string): void {+ if (typeof filePath !== 'string' || !platformPath.isAbsolute(filePath)) {+ throwIpcError('INVALID_PARAMS', 'filePath must be absolute');+ }+ if (!deps.isPathAllowed(filePath)) {+ throwIpcError('PERMISSION_DENIED', '不允许访问该路径');+ }+ if (!deps.fileExists(filePath)) {+ throwIpcError('NOT_FOUND', '文件不存在');+ }+ }++ /** exe 名引用(`Excel.exe`)→ 完整路径 + 友好名。 */+ async function resolveExeReference(exeName: string): Promise<ResolvedApp | null> {+ const appKey = `HKCR\\Applications\\${exeName}`;+ const cmdOut = await deps.regQuery(`${appKey}\\shell\\open\\command`, ['/ve']);+ let exePath = parseCommandLineExe(parseRegValues(cmdOut)[0]?.data ?? '');+ if (!exePath) {+ const appPathsOut = await deps.regQuery(+ `HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\${exeName}`,+ ['/ve'],+ );+ exePath = parseRegValues(appPathsOut)[0]?.data?.trim() || null;+ }+ if (exePath) exePath = expandWindowsEnv(exePath, process.env);+ if (!exePath || !deps.fileExists(exePath)) return null;++ const friendlyOut = await deps.regQuery(appKey, ['/v', 'FriendlyAppName']);+ const friendly = parseRegValues(friendlyOut)[0]?.data;+ // `@resource.dll,-123` 形态的本地化引用没有免原生的解法,回落 exe 名。+ const label =+ friendly && !friendly.startsWith('@') ? friendly : platformPath.basename(exePath, platformPath.extname(exePath));+ return { exePath, label };+ }++ /** ProgId 引用 → 完整路径 + 友好名。 */+ async function resolveProgIdReference(progId: string): Promise<ResolvedApp | null> {+ const cmdOut = await deps.regQuery(`HKCR\\${progId}\\shell\\open\\command`, ['/ve']);+ const parsed = parseCommandLineExe(parseRegValues(cmdOut)[0]?.data ?? '');+ const exePath = parsed ? expandWindowsEnv(parsed, process.env) : null;+ if (!exePath || !deps.fileExists(exePath)) return null;++ const nameOut = await deps.regQuery(`HKCR\\${progId}`, ['/ve']);+ const friendly = parseRegValues(nameOut)[0]?.data;+ const label =+ friendly && !friendly.startsWith('@') ? friendly : platformPath.basename(exePath, platformPath.extname(exePath));+ return { exePath, label };+ }++ async function listWindowsApps(ext: string): Promise<ResolvedApp[]> {+ const fileExtsKey = `HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts\\${ext}`;++ const exeNames = new Set<string>();+ const progIds = new Set<string>();++ const mruOut = await deps.regQuery(`${fileExtsKey}\\OpenWithList`);+ for (const v of parseRegValues(mruOut)) {+ if (v.name.toLowerCase() !== 'mrulist' && /\.exe$/i.test(v.data)) exeNames.add(v.data);+ }+ const hkcrListKey = `HKCR\\${ext}\\OpenWithList`;+ for (const sub of parseRegSubkeys(await deps.regQuery(hkcrListKey), hkcrListKey)) {+ if (/\.exe$/i.test(sub)) exeNames.add(sub);+ }+ for (const src of [`${fileExtsKey}\\OpenWithProgids`, `HKCR\\${ext}\\OpenWithProgids`]) {+ for (const v of parseRegValues(await deps.regQuery(src))) {+ if (v.name && v.name !== '(Default)') progIds.add(v.name);+ }+ }+ // 扩展名默认 ProgId 也入列(它对应的应用不一定出现在 OpenWith* 里)。+ const defaultProgId = parseRegValues(await deps.regQuery(`HKCR\\${ext}`, ['/ve']))[0]?.data;+ if (defaultProgId) progIds.add(defaultProgId);++ const seen = new Set<string>();+ const apps: ResolvedApp[] = [];+ const push = (r: ResolvedApp | null): void => {+ if (!r) return;+ if (HOST_EXE_DENYLIST.has(platformPath.basename(r.exePath).toLowerCase())) return;+ const key = dedupeKey(r.exePath);+ if (seen.has(key)) return;+ seen.add(key);+ apps.push(r);+ };+ for (const exe of exeNames) {+ if (apps.length >= MAX_APPS) break;+ push(await resolveExeReference(exe));+ }+ for (const progId of progIds) {+ if (apps.length >= MAX_APPS) break;+ push(await resolveProgIdReference(progId));+ }+ return apps;+ }++ return {+ async list({ filePath }) {+ try {+ assertOpenableFile(filePath);+ } catch (err) {+ return { success: false, apps: [], error: err instanceof Error ? err.message : String(err) };+ }+ if (deps.platform !== 'win32') {+ // macOS/Linux:无免原生依赖的枚举 API,空列表 = 菜单只显示+ // 「默认应用 / 选择其他应用…」两个平台无关项。+ return { success: true, apps: [] };+ }+ const ext = platformPath.extname(filePath).toLowerCase();+ if (!ext) return { success: true, apps: [] };+ try {+ const resolved = await listWindowsApps(ext);+ const idMap = new Map<string, string>();+ // 图标提取彼此独立且每个自带 4s 超时:串行会把子菜单懒加载放大到+ // MAX_APPS * 4s(最坏 48s)。并行(至多 MAX_APPS=12 并发)取,顺序仍按+ // resolved 保持稳定(PR #1835 review)。+ const apps: OpenWithApp[] = await Promise.all(+ resolved.map(async (r, i) => {+ const id = `owa-${i}-${platformPath.basename(r.exePath).toLowerCase()}`;+ idMap.set(id, r.exePath);+ const iconDataUrl = (await deps.getAppIcon(r.exePath)) ?? undefined;+ return { id, label: r.label, ...(iconDataUrl ? { iconDataUrl } : {}) };+ }),+ );+ appCacheByExt.set(ext, idMap);+ return { success: true, apps };+ } catch (err) {+ return { success: false, apps: [], error: err instanceof Error ? err.message : String(err) };+ }+ },++ async open({ filePath, appId }) {+ assertOpenableFile(filePath);+ if (typeof appId !== 'string' || !appId) throwIpcError('INVALID_PARAMS', 'appId required');+ const ext = platformPath.extname(filePath).toLowerCase();+ // 只认 main 侧最近一次枚举写入的映射——查不到一律拒绝,绝不把 renderer+ // 提供的任何字符串当路径执行。+ const exePath = appCacheByExt.get(ext)?.get(appId);+ if (!exePath) throwIpcError('NOT_FOUND', '应用引用已失效,请重新打开菜单');+ if (!deps.fileExists(exePath)) throwIpcError('NOT_FOUND', '应用不存在');+ deps.spawnDetached(exePath, [filePath]);+ },+ };+}diff --git a/apps/desktop/src/main/shellOpenPath.ts b/apps/desktop/src/main/shellOpenPath.tsindex 5ea7499888..54f15d6901 100644--- a/apps/desktop/src/main/shellOpenPath.ts+++ b/apps/desktop/src/main/shellOpenPath.ts@@ -11,7 +11,10 @@ import * as cindyMediaBlobStore from './cindy-media/blobStore.js';*/export function resolveShellOpenPathTarget(value: string): string | null {if (!value) return null;- if (path.isAbsolute(value)) return value;+ // path.normalize 把正斜杠 Windows 路径(`C:/x/a.docx`,常见于模型输出与命令+ // 文本)折成本机分隔符:shell.openPath 对「正斜杠 + 仅用户层文件关联」的组合+ // 解析失败,showItemInFolder 对正斜杠更是静默无反应。POSIX 上是幂等操作。+ if (path.isAbsolute(value)) return path.normalize(value);if (value.startsWith('cindy-media://')) return cindyMediaBlobStore.resolveSafe(value).absPath;return null;}diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex b0eaeda00c..a60852bd3f 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -3156,6 +3156,18 @@ contextBridge.exposeInMainWorld('electronAPI', {openPath: (filePathOrUrl: string): Promise<{ success: boolean; error?: string }> =>ipcRenderer.invoke('shell:open-path', filePathOrUrl),+ // 文件 chip 右键「打开方式」。appId 只能是 listOpenWithApps 返回的 id,+ // main 侧反查可执行体;renderer 无法让 main 执行任意路径。+ listOpenWithApps: (params: {+ filePath: string;+ }): Promise<{+ success: boolean;+ apps: Array<{ id: string; label: string; iconDataUrl?: string }>;+ error?: string;+ }> => ipcRenderer.invoke('open-with:list', params),+ openFileWithApp: (params: { filePath: string; appId: string }): Promise<void> =>+ ipcRenderer.invoke('open-with:open', params),+// 危险本地附件入托盘前先复制成受控缓存里的 `.bin` 副本。显示名仍由// renderer 单独保留,后续只能经“另存为”恢复原始扩展名。stageChatAttachment: (params: {diff --git a/apps/desktop/src/renderer/__tests__/buildRenderItemsKeyStability.test.ts b/apps/desktop/src/renderer/__tests__/buildRenderItemsKeyStability.test.tsindex 06adabb426..5868fe410b 100644--- a/apps/desktop/src/renderer/__tests__/buildRenderItemsKeyStability.test.ts+++ b/apps/desktop/src/renderer/__tests__/buildRenderItemsKeyStability.test.ts@@ -274,6 +274,42 @@ describe('collectTurnFinalAssistantClientIds', () => {// ── case 1: 流式追加 token 不改变 message item key ────────────────────────describe('buildRenderItems — key stability', () => {+ it('bounds historical command-generated files by the next user turn timestamp', () => {+ const firstUser = { ...mkUser('u1'), createdAt: '2026-08-05T10:00:00.000Z' };+ const command = {+ ...mkTool('cmd1', 'Bash', { command: "python gen.py 'out/report.xlsx'" }),+ createdAt: '2026-08-05T10:00:05.000Z',+ };+ const nextUser = { ...mkUser('u2'), createdAt: '2026-08-05T10:01:00.000Z' };+ const { items } = buildRenderItems([firstUser, command, nextUser], undefined, undefined, {+ workingDir: 'C:/work',+ });+ const card = items.find(+ (it): it is Extract<RenderItem, { type: 'generated_files' }> =>+ it.type === 'generated_files',+ );++ expect(card?.turnStartMs).toBe(Date.parse(firstUser.createdAt));+ expect(card?.turnEndMs).toBe(Date.parse(nextUser.createdAt));+ });++ it('leaves the current tail turn unbounded above', () => {+ const user = { ...mkUser('u1'), createdAt: '2026-08-05T10:00:00.000Z' };+ const command = {+ ...mkTool('cmd1', 'Bash', { command: "python gen.py 'out/report.xlsx'" }),+ createdAt: '2026-08-05T10:00:05.000Z',+ };+ const { items } = buildRenderItems([user, command], undefined, undefined, {+ workingDir: 'C:/work',+ });+ const card = items.find(+ (it): it is Extract<RenderItem, { type: 'generated_files' }> =>+ it.type === 'generated_files',+ );++ expect(card?.turnEndMs).toBeNull();+ });+it('streaming token append to an assistant message keeps the same item key', () => {const m1: ChatMessage = { ...mkAssistant('a1', 'partial'), isStreaming: true };const before = buildRenderItems([mkUser('u1'), m1]);diff --git a/apps/desktop/src/renderer/__tests__/chatAttachmentSave.test.ts b/apps/desktop/src/renderer/__tests__/chatAttachmentSave.test.tsindex b9fabe0344..cdc92b935e 100644--- a/apps/desktop/src/renderer/__tests__/chatAttachmentSave.test.ts+++ b/apps/desktop/src/renderer/__tests__/chatAttachmentSave.test.ts@@ -65,10 +65,23 @@ describe('safe attachment routing', () => {'utf8',);expect(source).toMatch(- /const downloadOnly = isSafetyDowngradedAttachment\(f\);[\s\S]+if \(downloadOnly\) \{[\s\S]+saveChatAttachmentWithToasts\(sessionFileCtx, f\)[\s\S]+shouldOpenTextLightboxForOrigin/,+ /const downloadOnly = isSafetyDowngradedAttachment\(file\);[\s\S]+if \(downloadOnly\) \{[\s\S]+saveChatAttachmentWithToasts\(sessionFileCtx, file\)[\s\S]+shouldOpenTextLightboxForOrigin/,);expect(source).toContain('<Download size={14}');});++ it('gives the downgraded attachment chip a save-as-only context menu', () => {+ const source = readFileSync(+ resolve(__dirname, '..', 'components', 'chat', 'UserMessage.tsx'),+ 'utf8',+ );+ // 右键分流:降级附件只弹「另存为…」单项菜单,普通附件走共享文件 chip 菜单。+ // 受控 .bin 副本路径不得经复制路径 / 打开所在目录外泄。+ expect(source).toMatch(+ /onContextMenu=\{\(e\) => \{[\s\S]+?if \(downloadOnly\) \{[\s\S]+?setSaveMenuPos\(\{ x: e\.clientX, y: e\.clientY \}\);[\s\S]+?ctxMenu\.onContextMenu\(e\);/,+ );+ expect(source).toContain("t('chat.media.saveAs')");+ });});describe('saveChatAttachmentWithToasts', () => {diff --git a/apps/desktop/src/renderer/__tests__/fileChipCursor.test.ts b/apps/desktop/src/renderer/__tests__/fileChipCursor.test.tsindex 05f03e3545..58c65b7a4d 100644--- a/apps/desktop/src/renderer/__tests__/fileChipCursor.test.ts+++ b/apps/desktop/src/renderer/__tests__/fileChipCursor.test.ts@@ -33,11 +33,10 @@ const agentActionRow = readFileSync(describe('File chip cursor — points, not zooms (symptom #2)', () => {it('UserMessage file chip uses cursor-pointer (not cursor-zoom-in)', () => {- // Hunt for the attachment chip <button> by its stable file-chip key. The- // chip carries the user-bg/border tokens. The chip class- // list must include `cursor-pointer` and must NOT regress to- // `cursor-zoom-in`.- const chipBlockStart = userMessage.indexOf('key={`file-${idx}-${f.path}`}');+ // 附件 chip 的 <button> 现在封装在 UserAttachmentChip 组件里(右键菜单分流+ // 需要 hook,不能内联在 map 里)。从组件定义处起截到它的 </button>,断言 chip+ // class 含 `cursor-pointer` 且未回退 `cursor-zoom-in`。+ const chipBlockStart = userMessage.indexOf('function UserAttachmentChip');expect(chipBlockStart).toBeGreaterThan(-1);const chipBlockEnd = userMessage.indexOf('</button>', chipBlockStart);const chipBlock = userMessage.slice(chipBlockStart, chipBlockEnd);diff --git a/apps/desktop/src/renderer/__tests__/generatedFiles.test.ts b/apps/desktop/src/renderer/__tests__/generatedFiles.test.tsnew file mode 100644index 0000000000..d5d598e830--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/generatedFiles.test.ts@@ -0,0 +1,186 @@+import { describe, expect, it } from 'vitest';++import { collectGeneratedFiles, extractCommandPathCandidates } from '../lib/generatedFiles';++const WORKDIR = '/work';++function toolUse(toolName: string, toolInput: unknown) {+ return { role: 'tool_use', toolName, toolInput };+}++describe('collectGeneratedFiles', () => {+ it('collects Write (claude) and write (pi) created files', () => {+ const files = collectGeneratedFiles(+ [+ toolUse('Write', { file_path: 'report.md', content: 'x' }),+ toolUse('write', { path: 'data/out.csv', content: 'y' }),+ ],+ WORKDIR,+ );+ expect(files.map((f) => f.name)).toEqual(['report.md', 'out.csv']);+ // 相对路径按 workingDir 解析成绝对路径。+ expect(files[0].path.replace(/\\/g, '/')).toContain('/work/report.md');+ });++ it('collects codex file_change add entries but not updates', () => {+ // codex 协议形态:change 需带 kind.type 与 diff 字符串,缺任一整次降级 generic。+ const files = collectGeneratedFiles(+ [+ toolUse('file_change', {+ changes: [+ { path: 'new.txt', kind: { type: 'add' }, diff: '+hi' },+ { path: 'existing.txt', kind: { type: 'update' }, diff: '-a\n+b' },+ ],+ }),+ ],+ WORKDIR,+ );+ expect(files.map((f) => f.name)).toEqual(['new.txt']);+ });++ it('excludes edits, reads and searches', () => {+ const files = collectGeneratedFiles(+ [+ toolUse('Edit', { file_path: 'a.ts', old_string: 'a', new_string: 'b' }),+ toolUse('Read', { file_path: 'b.ts' }),+ toolUse('Grep', { pattern: 'foo' }),+ ],+ WORKDIR,+ );+ expect(files).toEqual([]);+ });++ it('dedupes the same created path across tool calls, keeping first order', () => {+ const files = collectGeneratedFiles(+ [+ toolUse('Write', { file_path: 'dup.md', content: '1' }),+ toolUse('Write', { file_path: 'other.md', content: '2' }),+ toolUse('Write', { file_path: 'dup.md', content: '3' }),+ ],+ WORKDIR,+ );+ expect(files.map((f) => f.name)).toEqual(['dup.md', 'other.md']);+ });++ it('folds case only for Windows-shaped paths, keeps POSIX case-sensitive', () => {+ // Windows 绝对路径:大小写不敏感,C:/A.md 与 c:/a.md 视为同一文件。+ const win = collectGeneratedFiles(+ [+ toolUse('Write', { file_path: 'C:/work/A.md', content: '1' }),+ toolUse('Write', { file_path: 'c:/work/a.md', content: '2' }),+ ],+ 'C:/work',+ );+ expect(win).toHaveLength(1);++ // POSIX 绝对路径:大小写敏感,/w/A.txt 与 /w/a.txt 是两个不同文件,不合并。+ const posix = collectGeneratedFiles(+ [+ toolUse('write', { path: '/w/A.txt', content: '1' }),+ toolUse('write', { path: '/w/a.txt', content: '2' }),+ ],+ '/w',+ );+ expect(posix.map((f) => f.name).sort()).toEqual(['A.txt', 'a.txt']);+ });++ it('ignores non-tool_use messages', () => {+ const files = collectGeneratedFiles(+ [+ { role: 'assistant', toolName: 'Write', toolInput: { file_path: 'no.md' } },+ toolUse('Write', { file_path: 'yes.md', content: 'x' }),+ ],+ WORKDIR,+ );+ expect(files.map((f) => f.name)).toEqual(['yes.md']);+ });++ it('collects script-generated paths from Bash commands as command-source candidates', () => {+ // Issue 场景:xlsx 由 python openpyxl 脚本生成,没有文件工具记录。+ const cmd =+ 'python -c "\nimport openpyxl\nwb = openpyxl.Workbook()\n' ++ "wb.save(r'C:\\Users\\Admin\\Documents\\测试表格.xlsx')\nprint('done')\n\"\n";+ const files = collectGeneratedFiles([toolUse('Bash', { command: cmd })], 'C:/work');+ expect(files).toHaveLength(1);+ expect(files[0].name).toBe('测试表格.xlsx');+ expect(files[0].source).toBe('command');+ });++ it('canonicalizes Windows-shaped paths to backslashes and dedupes across slash forms', () => {+ // 正斜杠 Windows 路径(命令文本常见)必须归一成反斜杠本机形态:Explorer+ // /select 与 shell.openPath 对正斜杠会失败;且与 Write 记录的反斜杠形态+ // 是同一文件,不归一会重复出 chip。+ const files = collectGeneratedFiles(+ [+ toolUse('Write', { file_path: 'C:\\work\\report.docx', content: 'x' }),+ toolUse('Bash', { command: "open 'C:/work/report.docx'" }),+ toolUse('Bash', { command: "save 'C:/work/输出/表格.xlsx'" }),+ ],+ 'C:\\work',+ );+ expect(files.map((f) => f.path)).toEqual(['C:\\work\\report.docx', 'C:\\work\\输出\\表格.xlsx']);+ expect(files[0].source).toBe('tool');+ });++ it('excludes command mentions of files edited by file tools this turn', () => {+ // 编码会话形态:Edit 改了源码文件,随后命令引用它(跑测试)。它是编辑不是+ // 新建,不能因 mtime 落在本轮窗口就被当成产物。+ const files = collectGeneratedFiles(+ [+ toolUse('Bash', { command: 'pnpm vitest run C:/work/src/openWithApps.test.ts' }),+ toolUse('Edit', {+ file_path: 'C:/work/src/openWithApps.test.ts',+ old_string: 'a',+ new_string: 'b',+ }),+ toolUse('Bash', { command: "python gen.py > 'C:/work/out/report.csv'" }),+ ],+ 'C:/work',+ );+ // Edit 出现在命令之后也要生效(两遍扫描),真产物 report.csv 不受影响。+ expect(files.map((f) => f.name)).toEqual(['report.csv']);+ });++ it('marks file-tool creates as tool source and wins over command mentions of the same path', () => {+ const files = collectGeneratedFiles(+ [+ toolUse('Bash', { command: 'ls C:/work/report.md' }),+ toolUse('Write', { file_path: 'C:/work/report.md', content: 'x' }),+ ],+ 'C:/work',+ );+ expect(files).toHaveLength(1);+ expect(files[0].source).toBe('tool');+ });+});++describe('extractCommandPathCandidates', () => {+ it('extracts quoted paths (CJK, spaces) and bare absolute paths', () => {+ expect(+ extractCommandPathCandidates("wb.save(r'C:\\Users\\A\\My Docs\\报表 v2.xlsx')"),+ ).toEqual(['C:\\Users\\A\\My Docs\\报表 v2.xlsx']);+ expect(extractCommandPathCandidates('node gen.js > C:/out/result.json')).toContain(+ 'C:/out/result.json',+ );+ expect(extractCommandPathCandidates('cp a "/home/u/输出/report.pdf"')).toContain(+ '/home/u/输出/report.pdf',+ );+ });++ it('skips temp dirs, extension-less tokens, plain filenames and URLs', () => {+ expect(extractCommandPathCandidates("save('/tmp/x.xlsx')")).toEqual([]);+ expect(extractCommandPathCandidates("save('C:\\Users\\A\\AppData\\Local\\Temp\\x.xlsx')")).toEqual([]);+ expect(extractCommandPathCandidates('cat /dev/null && echo done')).toEqual([]);+ // 纯文件名不收(随机带点 token 误报率太高),相对路径需含分隔符。+ expect(extractCommandPathCandidates("save('输出.xlsx')")).toEqual([]);+ expect(extractCommandPathCandidates("save('out/输出.xlsx')")).toEqual(['out/输出.xlsx']);+ expect(extractCommandPathCandidates('curl https://x.com/a.js')).toEqual([]);+ expect(extractCommandPathCandidates('')).toEqual([]);+ });++ it('dedupes the same path appearing quoted and bare', () => {+ expect(+ extractCommandPathCandidates('python gen.py C:/out/a.csv && stat "C:/out/a.csv"'),+ ).toEqual(['C:/out/a.csv']);+ });+});diff --git a/apps/desktop/src/renderer/__tests__/generatedFilesCard.test.ts b/apps/desktop/src/renderer/__tests__/generatedFilesCard.test.tsnew file mode 100644index 0000000000..874bfea9dd--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/generatedFilesCard.test.ts@@ -0,0 +1,71 @@+import { describe, expect, it } from 'vitest';++import { isLocalGeneratedFileInTurn } from '../components/chat/GeneratedFilesCard';+import type { GeneratedFileRef } from '../lib/generatedFiles';++const START = Date.parse('2026-08-05T10:00:00.000Z');+const END = Date.parse('2026-08-05T10:01:00.000Z');++const toolFile: GeneratedFileRef = {+ path: 'C:\\work\\report.md',+ name: 'report.md',+ source: 'tool',+};+const commandFile: GeneratedFileRef = { ...toolFile, source: 'command' };++describe('isLocalGeneratedFileInTurn', () => {+ it('accepts a tool-created file whose birthtime falls in the turn', () => {+ expect(+ isLocalGeneratedFileInTurn(+ toolFile,+ { kind: 'file', birthtimeMs: START + 5_000, mtimeMs: START + 5_000 },+ START,+ END,+ ),+ ).toBe(true);+ });++ it('rejects Write against an existing file even when mtime is current', () => {+ expect(+ isLocalGeneratedFileInTurn(+ toolFile,+ { kind: 'file', birthtimeMs: START - 60_000, mtimeMs: START + 5_000 },+ START,+ END,+ ),+ ).toBe(false);+ });++ it('rejects a failed tool path that only appears in a later turn', () => {+ expect(+ isLocalGeneratedFileInTurn(+ toolFile,+ { kind: 'file', birthtimeMs: END + 5_000, mtimeMs: END + 5_000 },+ START,+ END,+ ),+ ).toBe(false);+ });++ it('fails closed for tool entries when birthtime is unavailable', () => {+ expect(+ isLocalGeneratedFileInTurn(+ toolFile,+ { kind: 'file', birthtimeMs: 0, mtimeMs: START + 5_000 },+ START,+ END,+ ),+ ).toBe(false);+ });++ it('keeps the mtime fallback for command candidates on filesystems without birthtime', () => {+ expect(+ isLocalGeneratedFileInTurn(+ commandFile,+ { kind: 'file', birthtimeMs: 0, mtimeMs: START + 5_000 },+ START,+ END,+ ),+ ).toBe(true);+ });+});diff --git a/apps/desktop/src/renderer/__tests__/markdownTarget.test.ts b/apps/desktop/src/renderer/__tests__/markdownTarget.test.tsindex f611f42863..2399d6bd5b 100644--- a/apps/desktop/src/renderer/__tests__/markdownTarget.test.ts+++ b/apps/desktop/src/renderer/__tests__/markdownTarget.test.ts@@ -197,6 +197,54 @@ describe('classifyMarkdownLinkTarget', () => {reason: 'not-a-target',});});++ // Issue #1811:LLM 按 ChatGPT 沙箱习惯输出 `sandbox:/C:/…` 链接,此前被+ // unsupported-scheme 判成纯文本,生成的文件在界面上彻底失联。+ it('strips sandbox: prefixes into local path candidates', () => {+ expect(classifyMarkdownLinkTarget('sandbox:/C:/Users/u/Desktop/亚马逊多产品 成本统计.xlsx')).toEqual({+ kind: 'local-candidate',+ href: 'C:/Users/u/Desktop/亚马逊多产品 成本统计.xlsx',+ originalHref: 'C:/Users/u/Desktop/亚马逊多产品 成本统计.xlsx',+ localKind: 'text',+ });+ // 斜杠数量不敏感:sandbox:///C:/ 与 sandbox:/C:/ 同义;反斜杠盘符同样认。+ expect(classifyMarkdownLinkTarget('sandbox:///C:/tmp/a.md')).toMatchObject({+ kind: 'local-candidate',+ href: 'C:/tmp/a.md',+ });+ expect(classifyMarkdownLinkTarget('sandbox:/C:\\repo\\报告.xlsx')).toMatchObject({+ kind: 'local-candidate',+ href: 'C:\\repo\\报告.xlsx',+ });+ expect(classifyMarkdownLinkTarget('sandbox:/mnt/data/output.csv')).toMatchObject({+ kind: 'local-candidate',+ href: '/mnt/data/output.csv',+ localKind: 'text',+ });+ // 行号后缀照常剥离(与直写路径同链路)。+ expect(classifyMarkdownLinkTarget('sandbox:/C:/repo/src/App.tsx:42')).toMatchObject({+ kind: 'local-candidate',+ href: 'C:/repo/src/App.tsx',+ line: 42,+ });+ });++ it('keeps non-absolute sandbox: forms and other schemes as plain text', () => {+ // 相对形态没有可靠语义,不剥。+ expect(classifyMarkdownLinkTarget('sandbox:foo/bar.txt')).toEqual({+ kind: 'plain-text',+ href: 'sandbox:foo/bar.txt',+ reason: 'unsupported-scheme',+ });+ // 近似 scheme 不误伤。+ expect(classifyMarkdownLinkTarget('sandboxy:/C:/tmp/a.md')).toMatchObject({+ kind: 'plain-text',+ reason: 'unsupported-scheme',+ });+ expect(classifyMarkdownLinkTarget('https://example.com/sandbox:/C:/a.md')).toMatchObject({+ kind: 'external',+ });+ });});describe('classifyInlineCodeTarget', () => {diff --git a/apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx b/apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsxnew file mode 100644index 0000000000..c7b6a75c52--- /dev/null+++ b/apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx@@ -0,0 +1,287 @@+/**+ * GeneratedFilesCard — 每个 user turn 结尾的「本轮产出文件」卡。+ * ---------------------------------------------------------------------------+ * 对标 Codex Desktop 回复尾部的 artifact 文件卡:agent 本轮新建的文件不再只能+ * 靠模型在正文里写对 Markdown 链接才可见(Issue #1811 场景),而是从 tool_use+ * 结构化派生后集中呈现。文件来源判定见 lib/generatedFiles.ts。+ *+ * 交互:+ * - 左键 → 与正文文件链接同策(对齐 MarkdownRenderer activateResolvedLocalTarget):+ * 可识别文件直接在 Cindy 内打开——文本/代码 → TextLightbox,图片 → ImageLightbox,+ * glb/gltf → ModelLightbox;其余(xlsx / pdf 等)交系统默认应用(远程会话取回+ * 缓存副本再打开)。+ * - 右键 → 共享文件 chip 菜单(复制 / 路径 / 定位 / 打开方式…),与聊天里其它+ * 文件 chip 一致。+ *+ * 存在性门槛(DESIGN.md §14.5「可点必存在」):本地会话渲染前 stat 过滤,不存在+ * 的文件不出 chip,整卡为空则不渲染。远程会话经 verifyRemotePathCached 远端 stat+ * 复核:先按 tool_use 记录乐观呈现,verdict 回来后 nonfile/directory 摘掉;+ * unknown(断链 / 限流)保持乐观——与正文 chip 的远程点亮不变量同策。+ *+ * 本地文件统一要求时间戳落在本轮 `[turnStartMs, turnEndMs)` 窗口内。tool 来源+ * (Write / file-change add)也不能只凭存在性:Write 可能覆盖既有文件,失败路径也可能+ * 被后续轮次创建;因此它必须有落在窗口内的 birthtime,不可用时宁可不出。+ * command 来源为兼容不提供 birthtime 的 Linux FS 允许 mtime 回退,但同样受完整+ * 时间窗约束。远程会话无法读取创建时间,维持远端 stat 的存在性复核。+ */++import { useEffect, useState } from 'react';+import { ChevronDown, ChevronUp, FileText } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { cn } from '@/lib/utils';+import type { GeneratedFileRef } from '@/lib/generatedFiles';+import { classifyMarkdownHref, toLocalFileUrl } from '@/lib/localPathResolver';+import { isRemoteFileOrigin, toRemoteMediaOrigin } from '@/lib/sessionFileOrigin';+import {+ fetchChatFileWithToasts,+ revealRemoteChatFile,+ verifyRemotePathCached,+} from '@/lib/remoteFileOpen';+import { shouldOpenTextLightboxForOrigin } from '@/lib/filePreview';+import { rewriteToRemoteMediaOrigin } from '../../../shared/remoteMediaUrl';+import { useChatSessionFile } from './ChatSessionFileContext';+import { useFileChipContextMenu } from './useFileChipContextMenu';+import { ImageLightbox } from './ImageLightbox';+import { TextLightbox } from './TextLightbox';+import { ModelLightbox } from './ModelLightbox';++function GeneratedFileChip({ file }: { file: GeneratedFileRef }) {+ const fileCtx = useChatSessionFile();+ const remoteOrigin = isRemoteFileOrigin(fileCtx.origin) ? fileCtx.origin : null;+ const ctxMenu = useFileChipContextMenu({+ getAbsPath: () => file.path,+ // 生成物常是 .xlsx / .pdf / 图片等,"打开方式"对它们最有用;会话上下文+ // (含侧边栏定位目标)由 useFileChipContextMenu 内部从 ChatSessionFileContext 取。+ canOpenInBrowser: false,+ });++ const [lightboxSrc, setLightboxSrc] = useState<string | null>(null);+ const [textLightboxOpen, setTextLightboxOpen] = useState(false);+ const [modelLightboxPath, setModelLightboxPath] = useState<string | null>(null);++ // 左键与正文文件链接同策(见文件头注释)。非文本兜底交给+ // shouldOpenTextLightboxForOrigin:本地 openPath、远程取回缓存副本,均含失败 toast。+ const open = async (): Promise<void> => {+ const kind = classifyMarkdownHref(file.path);+ if (kind === 'image-local') {+ const localUrl = toLocalFileUrl(file.path);+ if (!remoteOrigin) {+ setLightboxSrc(localUrl);+ return;+ }+ // 远程:xdt-file:// 经 origin 改写走 cindy-remote-media 管线;改写不了+ // (ssh workdir 外)→ 取回缓存副本后按本机文件预览(与正文链接同策)。+ const rewritten = rewriteToRemoteMediaOrigin(+ localUrl,+ toRemoteMediaOrigin(fileCtx.origin, fileCtx.workingDir),+ );+ if (rewritten !== localUrl) {+ setLightboxSrc(rewritten);+ return;+ }+ const cachePath = await fetchChatFileWithToasts(remoteOrigin, fileCtx.workingDir, file.path);+ if (cachePath) setLightboxSrc(toLocalFileUrl(cachePath));+ return;+ }+ if (kind === 'model-local') {+ if (remoteOrigin) {+ await revealRemoteChatFile(remoteOrigin, fileCtx.workingDir, file.path);+ return;+ }+ // FBX 无应用内预览且 openPath 有误导弹窗风险(正文链接同款取舍)→ 定位。+ if (/\.fbx$/i.test(file.path)) {+ void window.electronAPI.showItemInFolder({ filePath: file.path });+ return;+ }+ setModelLightboxPath(file.path);+ return;+ }+ if (!(await shouldOpenTextLightboxForOrigin(fileCtx, file.path))) return;+ setTextLightboxOpen(true);+ };++ return (+ <>+ <button+ type="button"+ title={file.path}+ onClick={() => void open()}+ onContextMenu={ctxMenu.onContextMenu}+ className={cn(+ 'inline-flex items-center gap-1.5',+ 'h-7 px-2.5 py-1.5 max-w-[280px]',+ 'rounded-[9999px]',+ 'bg-[var(--msg-md-inline-code-bg)]',+ 'text-[13px] font-medium text-[var(--msg-assistant-text)]',+ 'hover:bg-[var(--cmd-palette-item-hover)]',+ 'transition-colors cursor-pointer',+ )}+ >+ <FileText size={14} className="shrink-0 opacity-70" />+ <span className="truncate">{file.name}</span>+ </button>+ {ctxMenu.menu}+ {lightboxSrc && <ImageLightbox src={lightboxSrc} onClose={() => setLightboxSrc(null)} />}+ {textLightboxOpen && (+ <TextLightbox+ filePath={file.path}+ fileName={file.name}+ onClose={() => setTextLightboxOpen(false)}+ />+ )}+ {modelLightboxPath && (+ <ModelLightbox+ source={{ kind: 'local', absPath: modelLightboxPath }}+ onClose={() => setModelLightboxPath(null)}+ />+ )}+ </>+ );+}++/** command 候选 mtime 下界的时钟余量:消息落库时间与文件写盘时间的抖动缓冲。 */+const TURN_START_SLACK_MS = 120_000;++interface GeneratedFileStat {+ kind: 'dir' | 'file' | 'missing';+ birthtimeMs?: number;+ mtimeMs?: number;+}++/**+ * 本地文件是否有足够证据归属于该 turn。tool 来源必须有真实创建时间:+ * Write 也可能覆盖既有文件,仅凭成功/mtime 不能把它当成“新建”;birthtime+ * 不可用时宁可不出。command 来源为兼容不提供 birthtime 的 Linux FS,维持+ * mtime 回退,但仍受完整 turn 时间窗约束。+ */+export function isLocalGeneratedFileInTurn(+ file: GeneratedFileRef,+ stat: GeneratedFileStat,+ turnStartMs: number | null,+ turnEndMs: number | null,+): boolean {+ if (stat.kind !== 'file' || turnStartMs === null) return false;+ const birthtimeMs =+ typeof stat.birthtimeMs === 'number' && stat.birthtimeMs > 0 ? stat.birthtimeMs : null;+ const ts = file.source === 'tool' ? birthtimeMs : (birthtimeMs ?? stat.mtimeMs);+ // tool 来源的 birthtime 是同机 FS 事实,不放宽下界:放 2 分钟 slack 会把本轮+ // 覆盖的旧文件误当新建。command 来源保留消息落库/执行时序抖动余量。+ const lowerBound =+ file.source === 'tool' ? turnStartMs : turnStartMs - TURN_START_SLACK_MS;+ return (+ typeof ts === 'number' &&+ ts >= lowerBound &&+ (turnEndMs === null || ts < turnEndMs)+ );+}++/** 折叠阈值:约两行 chip。超过则收起为「前 N 个 + 再显示 M 个文件」。 */+const MAX_VISIBLE_FILES = 6;++export function GeneratedFilesCard({+ files,+ turnStartMs,+ turnEndMs,+}: {+ files: readonly GeneratedFileRef[];+ turnStartMs: number | null;+ turnEndMs: number | null;+}) {+ const { t } = useTranslation();+ const fileCtx = useChatSessionFile();+ const remoteOrigin = isRemoteFileOrigin(fileCtx.origin) ? fileCtx.origin : null;+ // 本地会话:stat 过滤到真实存在的文件(null = 尚未算完,不渲染,避免闪现后+ // 又被过滤掉);远程:tool 来源先乐观呈现、远端 stat 复核,command 候选无法+ // 验证 mtime 一律不出(见文件头注释)。+ const [existing, setExisting] = useState<GeneratedFileRef[] | null>(+ remoteOrigin ? files.filter((f) => f.source === 'tool') : null,+ );+ const [expanded, setExpanded] = useState(false);++ useEffect(() => {+ let cancelled = false;+ if (remoteOrigin) {+ const toolFiles = files.filter((f) => f.source === 'tool');+ setExisting(toolFiles);+ void (async () => {+ const checks = await Promise.all(+ toolFiles.map(async (f) => {+ const verdict = await verifyRemotePathCached(remoteOrigin, fileCtx.workingDir, f.path);+ // nonfile(不存在 / 非普通文件)/ directory 是远端确定结论 → 摘掉;+ // unknown(断链 / 限流)保持乐观。+ return verdict !== 'nonfile' && verdict !== 'directory';+ }),+ );+ if (!cancelled) setExisting(toolFiles.filter((_, idx) => checks[idx]));+ })();+ return () => {+ cancelled = true;+ };+ }+ void (async () => {+ const checks = await Promise.all(+ files.map(async (f) => {+ try {+ const r = await window.electronAPI.fsBrowse.statPath(f.path);+ return isLocalGeneratedFileInTurn(f, r, turnStartMs, turnEndMs);+ } catch {+ return false;+ }+ }),+ );+ if (!cancelled) setExisting(files.filter((_, idx) => checks[idx]));+ })();+ return () => {+ cancelled = true;+ };+ }, [files, remoteOrigin, turnStartMs, turnEndMs, fileCtx.workingDir]);++ if (!existing || existing.length === 0) return null;++ // 折叠(对标 Codex 的可展开产物列表):超过 MAX_VISIBLE_FILES 时只显示前+ // MAX_VISIBLE_FILES 个 + 「再显示 N 个文件」;展开后提供「收起」回折。+ const visible = expanded ? existing : existing.slice(0, MAX_VISIBLE_FILES);+ const hiddenCount = existing.length - visible.length;++ return (+ <div className="my-1 flex flex-col gap-1.5">+ <span className="text-12 text-[var(--text-secondary)]">+ {t('chat.generatedFiles.title')}+ </span>+ <div className="flex flex-wrap gap-1.5">+ {visible.map((f) => (+ <GeneratedFileChip key={f.path} file={f} />+ ))}+ {hiddenCount > 0 && (+ <button+ type="button"+ onClick={() => setExpanded(true)}+ className={cn(+ 'inline-flex items-center gap-1 h-7 px-2.5 py-1.5 rounded-[9999px]',+ 'text-[13px] text-[var(--text-secondary)]',+ 'hover:bg-[var(--cmd-palette-item-hover)] transition-colors cursor-pointer',+ )}+ >+ {t('chat.generatedFiles.showMore', { count: hiddenCount })}+ <ChevronDown size={14} className="shrink-0" />+ </button>+ )}+ {expanded && existing.length > MAX_VISIBLE_FILES && (+ <button+ type="button"+ onClick={() => setExpanded(false)}+ className={cn(+ 'inline-flex items-center gap-1 h-7 px-2.5 py-1.5 rounded-[9999px]',+ 'text-[13px] text-[var(--text-secondary)]',+ 'hover:bg-[var(--cmd-palette-item-hover)] transition-colors cursor-pointer',+ )}+ >+ {t('chat.generatedFiles.showLess')}+ <ChevronUp size={14} className="shrink-0" />+ </button>+ )}+ </div>+ </div>+ );+}diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsxindex 3d9cec35ea..6cb1a81046 100644--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx@@ -48,6 +48,7 @@ import { Spinner } from '@/components/ui/spinner';import { useMessageNavRailPreference } from '@/hooks/useMessageNavRailPreference';import { HISTORY_GAP_SPLIT_MS } from '@/lib/historyGap';import type { KnownLocalFileRef } from '@/lib/localPathResolver';+import { collectGeneratedFiles, type GeneratedFileRef } from '@/lib/generatedFiles';import { createLogger } from '@/lib/logger';import { stopAllMedia } from '@/lib/mediaPlaybackBus';import {@@ -154,6 +155,7 @@ import { NewMessageIndicator } from './NewMessageIndicator';import { ThinkingCard } from './ThinkingCard';import { AgentActionsBlock } from './AgentActionsBlock';import { AgentTaskCard } from './AgentTaskCard';+import { GeneratedFilesCard } from './GeneratedFilesCard';import { WorkGroupBlock, type WorkGroupChild } from './WorkGroupBlock';import {extractAnchorCardId,@@ -316,6 +318,17 @@ type ForkOriginRenderItem = {parentSessionId: string;forkedAtMessageId: string;};+type GeneratedFilesRenderItem = {+ /** 每个 user turn 结尾聚合的「本轮 agent 新建文件」卡(Codex artifact 卡对标)。+ * 纯派生自 turn 内 tool_use;存在性过滤在组件里做,全不存在则整卡不渲染。 */+ type: 'generated_files';+ key: string;+ files: GeneratedFileRef[];+ /** 本轮首条消息时间(unix ms);command 候选的时间窗下界校验用,不可得为 null。 */+ turnStartMs: number | null;+ /** 下一条 user 边界时间(unix ms);已结束 turn 的 command 候选时间窗上界。 */+ turnEndMs: number | null;+};/** 原子工作子项:tool / agent task / thinking / assistant 工作文字。 */export type WorkChildItem = ToolSegmentRenderItem | AgentTaskRenderItem | MessageRenderItem;@@ -345,6 +358,7 @@ export type RenderItem =| ToolSegmentRenderItem| AgentTaskRenderItem| ForkOriginRenderItem+ | GeneratedFilesRenderItem| {/** tool-result-media: 把 tool_result 里的 xdt_image_url(s) / xdt_video_urls* 提取出来作为独立视觉消息渲染,跳出 tool_segment 折叠卡片。统一容器,@@ -891,6 +905,8 @@ export function buildRenderItems(* 「父调用在不在 messages 里」做的归属判定都不可信,必须放宽而不是丢弃。*/historyWindowIncomplete?: boolean;+ /** 会话工作目录:把 tool_use 里的相对路径解析成绝对路径供「本轮产出文件」卡使用。 */+ workingDir?: string;},): {items: RenderItem[];@@ -1035,10 +1051,49 @@ export function buildRenderItems(pendingSegmentGhostCards = [];};+ // 「本轮产出文件」卡:按 user turn 切片派生新建文件,在**下一个** user 边界+ // (或流末尾)把上一轮的产出 flush 到该轮所有内容之下。turnStartIdx 指向当前+ // turn 的首条消息。workingDir 缺省时跳过(无从解析相对路径,不出卡)。+ const workingDir = opts?.workingDir ?? '';+ let turnStartIdx = 0;+ const flushGeneratedFiles = (lo: number, hi: number): void => {+ if (!workingDir || hi <= lo) return;+ const slice = messages.slice(lo, hi);+ const files = collectGeneratedFiles(slice, workingDir);+ if (files.length === 0) return;+ // 本轮时间窗:下界取切片内最早 createdAt;上界取 hi 处的下一条 user+ // 边界。历史 command 候选必须同时落在这个窗口内,否则后续 turn 在同一路径+ // 创建/改写文件时,旧卡会被当前 stat 的新时间戳错误点亮(PR #1835 review)。+ let turnStartMs: number | null = null;+ for (const m of slice) {+ const ts = m.createdAt ? Date.parse(m.createdAt) : NaN;+ if (Number.isFinite(ts) && (turnStartMs === null || ts < turnStartMs)) turnStartMs = ts;+ }+ const boundaryCreatedAt = hi < messages.length ? messages[hi]?.createdAt : undefined;+ const parsedTurnEndMs = boundaryCreatedAt ? Date.parse(boundaryCreatedAt) : NaN;+ const turnEndMs = Number.isFinite(parsedTurnEndMs) ? parsedTurnEndMs : null;+ // key 锚定该 turn 首条消息 clientId,窗口滚动 / 流式增量下稳定。+ items.push({+ type: 'generated_files',+ key: `genfiles-${messages[lo].clientId}`,+ files,+ turnStartMs,+ turnEndMs,+ });+ };+let i = 0;while (i < messages.length) {const msg = messages[i];+ // user turn 边界(非 steer、非合成触发):先 flush 上一轮的产出文件卡,+ // 再进入常规处理。第一条 user 消息时 lo==hi,flushGeneratedFiles 自身 no-op。+ if (msg.role === 'user' && msg.delivery !== 'steer' && !msg.isSyntheticTrigger) {+ flushSegment();+ flushGeneratedFiles(turnStartIdx, i);+ turnStartIdx = i;+ }+// ask_user: pending lives in the bottom input overlay; expired/unanswered// questions have no user selection to show. Only the answered state surfaces// in the stream — rendered by AskUserQuestionBubble so the choice the user@@ -1333,6 +1388,8 @@ export function buildRenderItems(// Flush trailing segment — important for streaming, where the turn often// ends mid-segment (no closing text yet).flushSegment();+ // 末尾 turn 的产出文件卡(没有后续 user 边界触发)。+ flushGeneratedFiles(turnStartIdx, messages.length);if (taskUpdates) {// 父会话自己的 Bash 调用集合:local_bash 任务卡(#247 的「后台命令」卡,含@@ -2355,8 +2412,9 @@ export function MessageStream({() =>buildRenderItems(messages, taskUpdates, ghostCardSnapshot, {historyWindowIncomplete: Boolean(hasMoreMessages),+ workingDir,}),- [messages, taskUpdates, ghostCardSnapshot, hasMoreMessages],+ [messages, taskUpdates, ghostCardSnapshot, hasMoreMessages, workingDir],);const assistantsWithFollowingUserBoundary = useMemo(() => collectAssistantsWithFollowingUserBoundary(messages),@@ -3665,6 +3723,17 @@ export function MessageStream({return <ForkOriginMarker key={item.key} onClick={onOpenForkOrigin} />;}+ if (item.type === 'generated_files') {+ return (+ <GeneratedFilesCard+ key={item.key}+ files={item.files}+ turnStartMs={item.turnStartMs}+ turnEndMs={item.turnEndMs}+ />+ );+ }+if (item.type === 'tool_segment') {return (<AgentActionsBlockdiff --git a/apps/desktop/src/renderer/components/chat/UserMessage.tsx b/apps/desktop/src/renderer/components/chat/UserMessage.tsxindex a1ae16a914..f475fca81c 100644--- a/apps/desktop/src/renderer/components/chat/UserMessage.tsx+++ b/apps/desktop/src/renderer/components/chat/UserMessage.tsx@@ -78,6 +78,12 @@ import { RewindPreviewDialog } from './RewindPreviewDialog';import { UserMessageEditBox } from './UserMessageEditBox';import HookTaskCard from './HookTaskCard';import { useFileChipContextMenu } from './useFileChipContextMenu';+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from '@/components/ui/dropdown-menu';import {AUTOMATION_USER_MESSAGE_VISUAL_LINE_THRESHOLD,LONG_USER_MESSAGE_VISUAL_LINE_THRESHOLD,@@ -240,6 +246,117 @@ function UserFileChip({);}+/**+ * UserAttachmentChip — 用户消息下方的文件附件 chip(与正文里的 `@file` 引用+ * chip 是两种呈现;此前只有 onClick,右键无反应,与 UserFileChip 交互不一致,+ * Issue #1811 讨论中实捉)。左键保持既有行为:安全降级附件走另存流程,其余+ * 文本预览 / 交系统默认应用。右键:+ * - 普通附件 → 共享文件 chip 菜单(复制 / 路径 / 定位等,与 UserFileChip 同款);+ * - 安全降级附件 → 仅「另存为…」单项。受控 `.bin` 副本的路径不该经「复制+ * 文件路径 / 打开所在目录」外泄,打开类动作更会绕过降级本身。+ */+function UserAttachmentChip({+ file,+ onOpenTextPreview,+}: {+ file: { name: string; path: string };+ /** 文本预览分支的回调:父组件记录 chip 元素(关闭预览后焦点复位)并开 lightbox。 */+ onOpenTextPreview: (chip: HTMLElement) => void;+}) {+ const { t } = useTranslation();+ const sessionFileCtx = useChatSessionFile();+ const downloadOnly = isSafetyDowngradedAttachment(file);+ // Rules-of-hooks:两个菜单 hook/状态都无条件建,按 downloadOnly 选用其一。+ const ctxMenu = useFileChipContextMenu({+ getAbsPath: () => file.path,+ canOpenInBrowser: isBrowserOpenablePath(file.path),+ });+ const [saveMenuPos, setSaveMenuPos] = useState<{ x: number; y: number } | null>(null);++ const saveOnlyMenu = (+ <DropdownMenu+ open={saveMenuPos !== null}+ onOpenChange={(open) => {+ if (!open) setSaveMenuPos(null);+ }}+ >+ <DropdownMenuTrigger asChild>+ <span+ aria-hidden+ style={{+ position: 'fixed',+ left: saveMenuPos?.x ?? 0,+ top: saveMenuPos?.y ?? 0,+ width: 0,+ height: 0,+ pointerEvents: 'none',+ }}+ />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" sideOffset={2} onClick={(e) => e.stopPropagation()}>+ <DropdownMenuItem+ onClick={() => {+ setSaveMenuPos(null);+ void saveChatAttachmentWithToasts(sessionFileCtx, file);+ }}+ >+ <Download className="mr-2 h-4 w-4" />+ {t('chat.media.saveAs')}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ );++ return (+ <>+ <button+ type="button"+ aria-label={+ downloadOnly ? t('chat.userMessage.saveAttachmentAs', { name: file.name }) : undefined+ }+ onClick={async (e) => {+ if (downloadOnly) {+ await saveChatAttachmentWithToasts(sessionFileCtx, file);+ return;+ }+ const chip = e.currentTarget;+ if (!(await shouldOpenTextLightboxForOrigin(sessionFileCtx, file.path))) return;+ onOpenTextPreview(chip);+ }}+ onContextMenu={(e) => {+ if (downloadOnly) {+ e.preventDefault();+ e.stopPropagation();+ setSaveMenuPos({ x: e.clientX, y: e.clientY });+ return;+ }+ ctxMenu.onContextMenu(e);+ }}+ className={cn(+ 'inline-flex items-center gap-1.5',+ 'h-7 px-2.5 py-1.5',+ 'rounded-[9999px]',+ 'bg-[var(--msg-user-bg)]',+ 'border border-[var(--msg-user-border)]',+ 'text-[13px] font-medium',+ 'text-[var(--msg-user-text)]',+ 'hover:bg-[var(--cmd-palette-item-hover)]',+ 'transition-colors cursor-pointer',+ 'max-w-[280px]',+ )}+ >+ {downloadOnly ? (+ <Download size={14} className="shrink-0 text-[var(--msg-user-text)]" />+ ) : (+ <FileText size={14} className="shrink-0 text-[var(--msg-user-text)]" />+ )}+ <span className="truncate">{file.name}</span>+ </button>+ {downloadOnly ? saveOnlyMenu : ctxMenu.menu}+ </>+ );+}+/*** Render a plain-text segment, converting:* - http(s) URLs into links that follow the user's opening preference@@ -1183,47 +1300,16 @@ export function UserMessage({hookSource ? 'justify-start' : 'justify-end',)}>- {files.map((f, idx) => {- const downloadOnly = isSafetyDowngradedAttachment(f);- return (- <button- key={`file-${idx}-${f.path}`}- type="button"- aria-label={- downloadOnly ? t('chat.userMessage.saveAttachmentAs', { name: f.name }) : undefined- }- onClick={async (e) => {- if (downloadOnly) {- await saveChatAttachmentWithToasts(sessionFileCtx, f);- return;- }- const chip = e.currentTarget;- if (!(await shouldOpenTextLightboxForOrigin(sessionFileCtx, f.path))) return;- activeFileChipRef.current = chip;- setTextLightboxFile({ path: f.path, name: f.name });- }}- className={cn(- 'inline-flex items-center gap-1.5',- 'h-7 px-2.5 py-1.5',- 'rounded-[9999px]',- 'bg-[var(--msg-user-bg)]',- 'border border-[var(--msg-user-border)]',- 'text-[13px] font-medium',- 'text-[var(--msg-user-text)]',- 'hover:bg-[var(--cmd-palette-item-hover)]',- 'transition-colors cursor-pointer',- 'max-w-[280px]',- )}- >- {downloadOnly ? (- <Download size={14} className="shrink-0 text-[var(--msg-user-text)]" />- ) : (- <FileText size={14} className="shrink-0 text-[var(--msg-user-text)]" />- )}- <span className="truncate">{f.name}</span>- </button>- );- })}+ {files.map((f, idx) => (+ <UserAttachmentChip+ key={`file-${idx}-${f.path}`}+ file={f}+ onOpenTextPreview={(chip) => {+ activeFileChipRef.current = chip;+ setTextLightboxFile({ path: f.path, name: f.name });+ }}+ />+ ))}</div>) : null;diff --git a/apps/desktop/src/renderer/components/chat/__tests__/sidebarEmbeddedActionTarget.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/sidebarEmbeddedActionTarget.test.tsxindex 92b30ffd8b..5d5e8e8900 100644--- a/apps/desktop/src/renderer/components/chat/__tests__/sidebarEmbeddedActionTarget.test.tsx+++ b/apps/desktop/src/renderer/components/chat/__tests__/sidebarEmbeddedActionTarget.test.tsx@@ -19,6 +19,10 @@ vi.mock('@/components/ui/dropdown-menu', () => ({{children}</button>),+ // 「打开方式」子菜单:测试只关心顶层菜单项路由,子菜单展开为直接渲染即可。+ DropdownMenuSub: ({ children }: { children: ReactNode }) => <>{children}</>,+ DropdownMenuSubTrigger: ({ children }: { children: ReactNode }) => <div>{children}</div>,+ DropdownMenuSubContent: ({ children }: { children: ReactNode }) => <div>{children}</div>,}));vi.mock('@/features/right-sidebar/lib/openInSidebarBrowser', () => ({diff --git a/apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx b/apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsxindex 6fda1331c4..88eeca34bd 100644--- a/apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx+++ b/apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx@@ -10,12 +10,16 @@* Menu items:* 0. 在侧边栏文件浏览器中打开 → select/reveal the file in the RSB file browser* 1. 在侧边栏浏览器中打开(可选,sidebarOpenSessionId 提供时;html chip 用)- * 2. 复制 → copy the file itself as a clipboard file reference+ * 2. 打开方式 ▸ →(文件 + 本地会话)默认应用 + 枚举出的可用应用+ * (Windows 注册表,见 main/openWithApps.ts)。应用+ * 列表在子菜单展开时懒加载。不提供「选择其他应用…」+ * (系统 OpenAs 对话框实测起不来,且与 Codex 形态不符)。+ * 3. 复制 → copy the file itself as a clipboard file reference* (pasteable into Explorer / Finder / chat apps)- * 3. 复制文件路径 → copy the absolute path string- * 4. 打开文件所在目录 → reveal in the OS file manager- * 5. 在浏览器中查看 →(可选,canOpenInBrowser)file:// 交给系统浏览器- * 6. 查看源文件 →(可选,onViewSource 提供时;html chip 左键改为按+ * 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@@ -27,8 +31,17 @@* actually opens the menu — chips that are never right-clicked pay nothing.*/-import { useState, type ReactElement } from 'react';-import { ClipboardCopy, Copy, FileCode, FolderOpen, FolderTree, Globe, PanelRight } from 'lucide-react';+import { useRef, useState, type ReactElement } from 'react';+import {+ AppWindow,+ ClipboardCopy,+ Copy,+ FileCode,+ FolderOpen,+ FolderTree,+ Globe,+ PanelRight,+} from 'lucide-react';import { useTranslation } from 'react-i18next';import { toast } from '@/lib/toast';@@ -37,6 +50,10 @@ import {DropdownMenu,DropdownMenuContent,DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuSub,+ DropdownMenuSubContent,+ DropdownMenuSubTrigger,DropdownMenuTrigger,} from '@/components/ui/dropdown-menu';import {@@ -93,6 +110,12 @@ 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);// 远程会话(device-link / SSH):文件字节在远端机器,「复制文件 / 定位」改走// 取回缓存副本;「复制路径」保留远端原始路径;浏览器 / 侧边栏项(读本机// file://)隐藏。聊天流外 context 是 local 默认值 → 行为与引入前逐字节一致。@@ -201,6 +224,45 @@ export function useFileChipContextMenu({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 : []);+ }++ async function handleOpenWithDefault(): Promise<void> {+ setMenuPos(null);+ const abs = await getAbsPath();+ const res = await window.electronAPI.openPath(abs);+ if (!res.success) 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',+ }),+ ),+ );+ }+ }+const openAt = (x: number, y: number): void => {setMenuPos({ x, y });};@@ -215,7 +277,11 @@ export function useFileChipContextMenu({<DropdownMenuopen={menuPos !== null}onOpenChange={(open) => {- if (!open) setMenuPos(null);+ if (!open) {+ setMenuPos(null);+ setOpenWithApps(null);+ openWithEpochRef.current += 1;+ }}}><DropdownMenuTrigger asChild>@@ -254,6 +320,49 @@ export function useFileChipContextMenu({{t('chat.markdownRenderer.openInSidebarBrowser')}</DropdownMenuItem>) : null}+ {sidebarFileBrowserKind === 'file' && !remoteOrigin ? (+ // 打开方式:仅文件 + 本地会话。远程会话的字节在远端机器,本机应用+ // 枚举与执行都无意义(与「在浏览器中查看」同一门控口径)。+ <DropdownMenuSub+ onOpenChange={(open) => {+ if (open) void loadOpenWithApps();+ }}+ >+ <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>+ ))}+ </>+ ) : null}+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ ) : null}<DropdownMenuItem onClick={handleCopyFile}><Copy className="mr-2 h-4 w-4" />{t('chat.markdownRenderer.copyFile')}diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 04e7e17ba5..bd8e9dbc7f 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -6023,6 +6023,8 @@"duplicateFiles": "Found {{count}} files with the same name, please use an absolute path","copyFile": "Copy","copyFilePath": "Copy file path",+ "openWith": "Open with",+ "openWithAppFailed": "Couldn't open with the selected app","revealFile": "Reveal in folder","openInBrowser": "Open in browser","fileCopied": "File copied",@@ -6156,6 +6158,11 @@"DEVICE_LINK_CONTROL_DISABLED": "Control for this device is off; the message was not sent.","DEVICE_LINK_MEDIA_TRANSFER_FAILED": "Attachment transfer failed; the message was not sent. Please try again."},+ "generatedFiles": {+ "title": "Files created this turn",+ "showMore": "Show {{count}} more",+ "showLess": "Show less"+ },"agentActions": {"part": {"edited_one": "edited a file",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 9eed1c43e7..d52859f20b 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -6021,6 +6021,8 @@"duplicateFiles": "同名のファイルが {{count}} 件見つかりました。絶対パスを使用してください","copyFile": "コピー","copyFilePath": "ファイルパスをコピー",+ "openWith": "アプリで開く",+ "openWithAppFailed": "選択したアプリで開けませんでした","revealFile": "ファイルの場所を開く","openInBrowser": "ブラウザで開く","fileCopied": "ファイルをコピーしました",@@ -6154,6 +6156,11 @@"DEVICE_LINK_CONTROL_DISABLED": "このデバイスの操作はオフです。メッセージは送信されていません。","DEVICE_LINK_MEDIA_TRANSFER_FAILED": "添付ファイルの転送に失敗しました。メッセージは送信されていません。もう一度お試しください。"},+ "generatedFiles": {+ "title": "このターンで生成されたファイル",+ "showMore": "さらに {{count}} 件を表示",+ "showLess": "折りたたむ"+ },"agentActions": {"part": {"edited_other": "ファイル {{count}} 件を編集",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 6a4ea6a5d8..4c88088084 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -6021,6 +6021,8 @@"duplicateFiles": "동일한 이름의 파일 {{count}}개를 찾았습니다. 절대 경로를 사용해 주세요","copyFile": "복사","copyFilePath": "파일 경로 복사",+ "openWith": "앱으로 열기",+ "openWithAppFailed": "선택한 앱으로 열 수 없습니다","revealFile": "파일 위치 열기","openInBrowser": "브라우저에서 열기","fileCopied": "파일이 복사되었습니다",@@ -6154,6 +6156,11 @@"DEVICE_LINK_CONTROL_DISABLED": "이 기기의 제어가 꺼져 있어 메시지가 전송되지 않았습니다.","DEVICE_LINK_MEDIA_TRANSFER_FAILED": "첨부 파일 전송에 실패했습니다. 메시지가 전송되지 않았습니다. 다시 시도하세요."},+ "generatedFiles": {+ "title": "이번 턴에 생성된 파일",+ "showMore": "{{count}}개 더 보기",+ "showLess": "접기"+ },"agentActions": {"part": {"edited_other": "파일 {{count}}개 편집",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 026a784ac1..b1a1ee2013 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -6021,6 +6021,8 @@"duplicateFiles": "找到 {{count}} 个同名文件,请改用绝对路径","copyFile": "复制","copyFilePath": "复制文件路径",+ "openWith": "打开方式",+ "openWithAppFailed": "无法用所选应用打开","revealFile": "打开文件所在目录","openInBrowser": "在浏览器中查看","fileCopied": "文件已复制",@@ -6154,6 +6156,11 @@"DEVICE_LINK_CONTROL_DISABLED": "已关闭对该设备的控制,消息未发送。","DEVICE_LINK_MEDIA_TRANSFER_FAILED": "附件传输失败,消息未发送。请重试。"},+ "generatedFiles": {+ "title": "本轮生成的文件",+ "showMore": "再显示 {{count}} 个文件",+ "showLess": "收起"+ },"agentActions": {"part": {"edited_other": "编辑 {{count}} 个文件",diff --git a/apps/desktop/src/renderer/lib/generatedFiles.ts b/apps/desktop/src/renderer/lib/generatedFiles.tsnew file mode 100644index 0000000000..31369d5adc--- /dev/null+++ b/apps/desktop/src/renderer/lib/generatedFiles.ts@@ -0,0 +1,188 @@+/**+ * generatedFiles — 从一轮回复的 tool_use 消息里派生「本轮 agent 新建的文件」。+ * ---------------------------------------------------------------------------+ * 纯派生、不新增持久化:tool_use 消息本身已落库并原样回放,所以历史会话重开后+ * 这张卡能稳定重建。跨 agent(claude-code / codex / pi)的工具名差异统一交给+ * `describeToolUse` 归一化,不自己维护工具名表:+ * - kind==='file' 且 action==='create' → Write / write(claude / pi 新建文件)+ * - kind==='fileChange' 的 changes 里 action==='add' → codex file_change 新增文件+ * - kind==='command' → 从命令文本启发式提取产物路径候选(source:'command')。+ * Excel / Word / PDF 等二进制产物只能靠脚本(Bash/exec 跑 python、node)生成,+ * 没有文件工具记录;不补这个盲区,卡在「帮我生成个表格」主场景直接失灵。+ * 「修改已有文件」(edit / update)与读取不算产出(产品口径:只收新建,见+ * AskUserQuestion 决策)。move / delete 同样排除。+ *+ * 误报防线(source:'command' 特有,由渲染方 GeneratedFilesCard 执行):+ * 命令文本里出现路径 ≠ 命令创建了它(可能只是读输入)。所以 command 候选除+ * 存在性外,还必须满足「文件 mtime 落在本轮时间窗内」才出 chip;窗口不可得+ * (消息无 createdAt / 远程会话无法 stat)时宁可不出。tool 来源保持原判定。+ */++import { describeToolUse } from '@cindy/maker-shared';++import { resolveToolFilePath } from './localPathResolver';+import { basename } from './utils';++export interface GeneratedFileRef {+ /** 已按 workingDir 解析的绝对路径(用于存在性校验与 chip 打开)。 */+ path: string;+ /** 展示用文件名(basename)。 */+ name: string;+ /**+ * 'tool' = 文件工具结构化新建记录,存在即列;+ * 'command' = 命令文本启发式候选,渲染前还需 mtime 时间窗校验。+ */+ source: 'tool' | 'command';+}++interface ToolUseLike {+ role: string;+ toolName?: string;+ toolInput?: unknown;+}++/**+ * 去重 key。**只对 Windows 路径形态**(盘符前缀或含反斜杠)做大小写不敏感折叠——+ * NTFS 上 `A.txt` 与 `a.txt` 是同一文件;POSIX 路径(Linux 本地会话 / 远程 Linux+ * workdir)必须保留原大小写,否则会把两个真实不同的文件错误合并、丢掉一个+ * (PR #1835 review)。macOS 虽默认大小写不敏感,但无法从纯 POSIX 路径形态区分+ * macOS 与 Linux;两害相权取轻:宁可 macOS 偶尔多出一个重复 chip,也不能在 Linux+ * 上丢文件。+ */+function dedupeKeyForPath(abs: string): string {+ const isWindowsShape = /^[a-zA-Z]:[\\/]/.test(abs) || abs.includes('\\');+ // 斜杠也归一:`C:/x/a.md`(命令文本常见形态)与 `C:\x\a.md`(Write 记录)是+ // 同一文件,不折叠会重复出 chip。+ return isWindowsShape ? abs.replace(/\//g, '\\').toLowerCase() : abs;+}++/**+ * Windows 形态的绝对路径统一成反斜杠本机形态再往下传:Explorer `/select`+ * (定位)对正斜杠路径静默无反应,`shell.openPath` 在仅用户层文件关联的机器上+ * 对正斜杠也会解析失败(实测「本轮产出」卡 docx chip 打不开的根因)。POSIX+ * 路径原样保留。+ */+function canonicalizeWindowsShape(abs: string): string {+ return /^[a-zA-Z]:[\\/]/.test(abs) ? abs.replace(/\//g, '\\') : abs;+}++/** 单条 tool_use 消息 → 它新建的文件原始路径列表(可能为空)。 */+function createdPathsFromToolUse(toolName: string, input: unknown): string[] {+ const descriptor = describeToolUse(toolName, input);+ if (descriptor.kind === 'file') {+ return descriptor.action === 'create' && descriptor.filePath ? [descriptor.filePath] : [];+ }+ if (descriptor.kind === 'fileChange') {+ return descriptor.changes+ .filter((c) => c.action === 'add' && c.path)+ .map((c) => c.path);+ }+ return [];+}++/** 带扩展名(1–8 位字母数字,不含纯数字)的路径才算候选;`a.b.c` 取末段。 */+const EXT_RE = /\.[A-Za-z][A-Za-z0-9]{0,7}$/;++/** 临时目录里的产物是脚本自身/中间文件的高发区,一律不算「本轮产出」。 */+const TEMP_DIR_RE = /(^|[\\/])(tmp|temp)([\\/])|[\\/]AppData[\\/]Local[\\/]Temp[\\/]/i;++function isPathCandidate(raw: string): boolean {+ const s = raw.trim();+ if (s.length < 3 || s.length > 512) return false;+ if (!EXT_RE.test(s)) return false;+ if (TEMP_DIR_RE.test(s)) return false;+ // 绝对路径,或含分隔符的相对路径(交给 resolveToolFilePath 按 workingDir 解析)。+ // 纯文件名(`输出.xlsx`)不收:随机带点 token 误报率太高。+ const isAbs = /^[A-Za-z]:[\\/]/.test(s) || s.startsWith('/');+ const hasSep = s.includes('/') || s.includes('\\');+ return isAbs || hasSep;+}++/**+ * 命令文本 → 产物路径候选。两个来源:+ * 1. 引号字符串(`'...'` / `"..."`):脚本内路径的主形态,可含空格与 CJK,+ * 如 python 的 `wb.save(r'C:\Users\x\表格.xlsx')`;+ * 2. 裸 token:重定向 / CLI 参数里的无引号绝对路径(不含空格)。+ * 只做形态过滤,不判断读写意图——读写区分交给渲染方的 mtime 时间窗。+ */+export function extractCommandPathCandidates(command: string): string[] {+ if (!command) return [];+ const out: string[] = [];+ const seen = new Set<string>();+ const push = (raw: string): void => {+ const s = raw.trim();+ if (!isPathCandidate(s)) return;+ if (seen.has(s)) return;+ seen.add(s);+ out.push(s);+ };+ for (const m of command.matchAll(/'([^'\r\n]+)'|"([^"\r\n]+)"/g)) {+ push(m[1] ?? m[2] ?? '');+ }+ // 裸 Windows 盘符路径与裸 POSIX 绝对路径(前面是行首/空白/常见分隔)。+ // 盘符前不允许字母数字:排除 URL scheme 尾字母被当盘符(https://…)。+ for (const m of command.matchAll(/(?<![A-Za-z0-9])[A-Za-z]:[\\/][^\s'"<>|?*]+/g)) push(m[0]);+ for (const m of command.matchAll(/(?:^|[\s=(,>])(\/[^\s'"<>|?*:]+)/g)) push(m[1]);+ return out;+}++/**+ * 一组消息(通常是一个 turn 的切片,但对任意切片都成立)→ 新建文件的有序去重+ * 列表。路径经 `resolveToolFilePath` 解析成绝对路径;`workingDir` 为空时按原样+ * 保留(与其它 chip 解析同策)。存在性(及 command 候选的 mtime 时间窗)校验由+ * 调用方在渲染前做(异步 IPC)。同一路径同时有 tool 与 command 来源时按 tool 计+ * (tool 是结构化实锤,不该被降级成启发式候选)。+ */+export function collectGeneratedFiles(+ messages: readonly ToolUseLike[],+ workingDir: string,+): GeneratedFileRef[] {+ // 第一遍:收「本轮被文件工具**修改**过」的路径。它们是编辑不是新建,命令文本+ // 里再出现也不算产物候选——否则跑测试 / 构建命令引用刚编辑过的源码文件+ // (`vitest run src/x.test.ts`)会被 mtime 窗口放行,把编码会话的改动文件全+ // 误收进卡。read 不排除:agent 生成后回读验证是常见动作,不该反杀真产物。+ const editedKeys = new Set<string>();+ for (const msg of messages) {+ if (msg.role !== 'tool_use' || !msg.toolName) continue;+ const d = describeToolUse(msg.toolName, msg.toolInput);+ if (d.kind === 'file' && d.action === 'edit' && d.filePath) {+ editedKeys.add(dedupeKeyForPath(resolveToolFilePath(d.filePath, workingDir)));+ } else if (d.kind === 'fileChange') {+ for (const c of d.changes) {+ if (c.action !== 'add' && c.path) {+ editedKeys.add(dedupeKeyForPath(resolveToolFilePath(c.path, workingDir)));+ }+ }+ }+ }++ const byKey = new Map<string, GeneratedFileRef>();+ for (const msg of messages) {+ if (msg.role !== 'tool_use') continue;+ const toolName = msg.toolName ?? '';+ if (!toolName) continue;++ const addPath = (rawPath: string, source: GeneratedFileRef['source']): void => {+ const abs = canonicalizeWindowsShape(resolveToolFilePath(rawPath, workingDir));+ const key = dedupeKeyForPath(abs);+ if (source === 'command' && editedKeys.has(key)) return;+ const prev = byKey.get(key);+ if (prev) {+ if (prev.source === 'command' && source === 'tool') prev.source = 'tool';+ return;+ }+ byKey.set(key, { path: abs, name: basename(abs), source });+ };++ for (const rawPath of createdPathsFromToolUse(toolName, msg.toolInput)) {+ addPath(rawPath, 'tool');+ }+ const descriptor = describeToolUse(toolName, msg.toolInput);+ if (descriptor.kind === 'command' && descriptor.command) {+ for (const rawPath of extractCommandPathCandidates(descriptor.command)) {+ addPath(rawPath, 'command');+ }+ }+ }+ return [...byKey.values()];+}diff --git a/apps/desktop/src/renderer/lib/markdownTarget.ts b/apps/desktop/src/renderer/lib/markdownTarget.tsindex 7265e01460..aeefd70a50 100644--- a/apps/desktop/src/renderer/lib/markdownTarget.ts+++ b/apps/desktop/src/renderer/lib/markdownTarget.ts@@ -10,6 +10,14 @@ import {const HTTP_URL_RE = /^https?:\/\//i;const SCHEME_RE = /^[a-z][a-z0-9+.-]*:/i;const WINDOWS_ABSOLUTE_PATH_RE = /^[a-z]:[\\/]/i;+/**+ * `sandbox:` 前缀 + 斜杠若干 + 绝对路径(Windows 盘符或 POSIX)。LLM 受+ * ChatGPT 代码沙箱习惯影响,会把本地生成文件写成 `sandbox:/C:/…/报告.xlsx`+ * 或 `sandbox:/mnt/data/a.csv`(Issue #1811 实例)。捕获组 1 = 盘符路径,+ * 捕获组 2 = POSIX 路径(含前导 `/`)。只认这两种绝对路径形态——`sandbox:foo`+ * 之类的相对形态没有可靠语义,维持 unsupported-scheme 纯文本。+ */+const SANDBOX_HREF_RE = /^sandbox:\/*(?:([a-z]:[\\/][^\n]*)|(\/[^\n]*))$/i;const URL_WITH_DOUBLE_SLASH_RE = /^[a-z][a-z0-9+.-]*:\/\//i;const BARE_FILE_REF_RE = /^[^\s:<>()[\]{}"'`]+?\.[a-z0-9]{1,10}$/i;/**@@ -117,6 +125,19 @@ function hasUnsupportedScheme(value: string): boolean {return SCHEME_RE.test(value);}+/**+ * 把 `sandbox:/C:/…` / `sandbox:///mnt/…` 形态的链接剥成裸绝对路径,其余输入+ * 原样返回。剥完后走与直写路径完全相同的 candidate → 存在性/workdir 解析链路,+ * 所以这里**只做词法转换,不做任何信任判断**——不存在或越界的路径仍会在解析层+ * 落回纯文本(Issue #1811;非特权 Markdown 面由 stripPrivilegedMarkdownTarget+ * 继续兜底降级,不受影响)。+ */+export function normalizeSandboxHref(raw: string): string {+ const m = raw.match(SANDBOX_HREF_RE);+ if (!m) return raw;+ return m[1] ?? m[2] ?? raw;+}+function decodeAnchorId(value: string): string {try {return decodeURIComponent(value);@@ -241,7 +262,9 @@ export function classifyMarkdownLinkTarget(href: string | undefined,files?: readonly KnownLocalFileRef[],): MarkdownTarget {- const raw = href?.trim() ?? '';+ // sandbox: 前缀在进任何 scheme 判定前先剥掉——它只是 LLM 对本地路径的一种+ // 拼写习惯,剥完后与作者直写 `[x](C:/…)` 走同一条链路(含存在性校验)。+ const raw = normalizeSandboxHref(href?.trim() ?? '');if (!raw) return { kind: 'plain-text', href: raw, reason: 'empty' };if (raw.startsWith('#')) return { kind: 'anchor', id: decodeAnchorId(raw.slice(1)), href: raw };diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 58b1059c53..549348fe3d 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -2554,6 +2554,18 @@ interface ElectronAPI {*/openPath: (filePath: string) => Promise<{ success: boolean; error?: string }>;+ /**+ * 文件 chip 右键「打开方式」:枚举可打开该文件的应用(Windows 注册表;+ * 其余平台空列表)。appId 只在 main 侧映射到可执行体,renderer 原样回传。+ */+ listOpenWithApps: (params: { filePath: string }) => Promise<{+ success: boolean;+ apps: Array<{ id: string; label: string; iconDataUrl?: string }>;+ error?: string;+ }>;+ /** 用 listOpenWithApps 返回的 appId 指定应用打开文件;失败以 IPC 错误抛出。 */+ openFileWithApp: (params: { filePath: string; appId: string }) => Promise<void>;+/** Copy a dangerous local attachment into the controlled inert cache. */stageChatAttachment: (params: { sourcePath: string; suggestedName: string }) => Promise<| { success: true; path: string }@@ -2690,7 +2702,12 @@ interface ElectronAPI {entries: { name: string; kind: 'dir' | 'symlink'; path: string }[];parent: string | null;}>;- statPath: (path: string) => Promise<{ kind: 'dir' | 'file' | 'missing'; resolvedPath: string }>;+ statPath: (path: string) => Promise<{+ kind: 'dir' | 'file' | 'missing';+ resolvedPath: string;+ mtimeMs?: number;+ birthtimeMs?: number;+ }>;mkdirP: (path: string) => Promise<{ resolvedPath: string }>;};diff --git a/apps/mobile/src/__tests__/messageContentDesktopFirst.test.ts b/apps/mobile/src/__tests__/messageContentDesktopFirst.test.tsindex 34e20de09d..6fb824f1f6 100644--- a/apps/mobile/src/__tests__/messageContentDesktopFirst.test.ts+++ b/apps/mobile/src/__tests__/messageContentDesktopFirst.test.ts@@ -12,7 +12,7 @@ describe('mobile message content desktop-first surface', () => {const fileChipSource = source.slice(fileChipStart, fileChipEnd);expect(desktopSource).toContain("'h-7 px-2.5 py-1.5'");- expect(desktopSource).toContain('<span className="truncate">{f.name}</span>');+ expect(desktopSource).toContain('<span className="truncate">{file.name}</span>');expect(source).toContain('File as FileIcon,');expect(source).toContain('<FileIcon color={colors.textSecondary} size={iconSize.sm} strokeWidth={iconStroke.regular} />');expect(source).toContain('style={[styles.fileIconFrame, { width: layout.fileChipIconWidth }]}');