From 23badbc5353bd3500ec258b8f1437c46860d434f Mon Sep 17 00:00:00 2001 From: taisuii <93462725+taisuii@users.noreply.github.com> Date: Sun, 1 Nov 2026 23:31:35 +0800 Subject: [PATCH] =?UTF-8?q?desktop:=20=E5=9B=9E=E5=A4=8D=E9=87=8C=E5=8F=AF?= =?UTF-8?q?=E4=BB=A5=E6=8F=92=E5=9B=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 模型过去只能在文字里描述图片,用户看不到它刚截的那张。现在可以把工作区或附件里的 图片登记成「回复图片」,UI 用现成的 attachment-preview 通道按 id 取 dataUrl 渲染。 刻意没做成 Markdown 的 ![](data:...):那条路径会把 base64 写进 .agent-history.json, 直接破坏「历史不落 base64」这个既有不变量。历史里只记附件 id,和其他附件共用同一套 存储与校验。 安全边界:模型能决定用户屏幕上出现什么图(伪造登录框/系统提示都是现实的钓鱼面), 所以 - 不接受远端 URL,只接受工作区相对路径; - 不接受 SVG(可内嵌脚本),一律按文件头真实嗅探格式; - 复用已有附件时重新校验 hash,防止「登记后文件被换掉」。 - sidecar/reply-image.mjs:登记与校验;sidecar/reply-tools.mjs:reply_image 工具。 - ui/src/reply-markdown.jsx + image-refs.js:把回复里的图片引用切出来单独渲染。 - scripts/check-reply-images.mjs:UI 回归。 验证:node --test sidecar/test/reply-image.test.mjs → 7 项全过。 --- docs/chat-experience.md | 23 ++++ package.json | 1 + scripts/check-reply-images.mjs | 167 ++++++++++++++++++++++++++ sidecar/agent.mjs | 7 +- sidecar/browser.mjs | 5 + sidecar/browsertools.mjs | 6 +- sidecar/catalog.mjs | 3 +- sidecar/mcphost.mjs | 6 +- sidecar/policy.mjs | 1 + sidecar/reply-image.mjs | 79 +++++++++++++ sidecar/reply-tools.mjs | 39 +++++++ sidecar/test/reply-image.test.mjs | 188 ++++++++++++++++++++++++++++++ ui/src/app.css | 10 ++ ui/src/attachments.jsx | 16 +++ ui/src/chat.jsx | 11 +- ui/src/conversation.js | 2 +- ui/src/image-refs.js | 26 +++++ ui/src/md.js | 21 +++- ui/src/reply-markdown.jsx | 32 +++++ ui/src/state.js | 2 +- 20 files changed, 631 insertions(+), 14 deletions(-) create mode 100644 scripts/check-reply-images.mjs create mode 100644 sidecar/reply-image.mjs create mode 100644 sidecar/reply-tools.mjs create mode 100644 sidecar/test/reply-image.test.mjs create mode 100644 ui/src/image-refs.js create mode 100644 ui/src/reply-markdown.jsx diff --git a/docs/chat-experience.md b/docs/chat-experience.md index 0304805530..d7f363f460 100644 --- a/docs/chat-experience.md +++ b/docs/chat-experience.md @@ -39,6 +39,29 @@ 文件解析失败、格式不支持、数量超限等错误都在模型请求之前返回。模型端拒绝的已发送图片仍保留在用户消息中,可以重新使用附件。 +## 图片输出(AI 发给用户) + +模型可以主动把图片放进回复里,不需要用户先发图。三种来源都收敛到同一个渲染通道: + +| 来源 | 触发 | 图片挂在哪 | +|---|---|---| +| `take_screenshot` | 模型要看页面版式时 | 该工具条下方(展开执行过程可见) | +| `reply_image` | 模型要给你看工作区里的图或图表 | 同上;正文没指定位置时附在回复末尾 | +| 外部 MCP 返回的 image block | 已连接的 MCP 服务回图 | 同 `reply_image` | + +**正文定位**:模型可以写 `![说明](image:<附件id>)` 把图片放到正文某处,`reply-markdown.jsx` 按 `image-refs.js` 切段,图片只出现在它指定的位置,不重复附在末尾。id 不是本会话真实图片附件时,这段语法原样留在文本里,不会变成坏图。 + +**存储与安全边界**(这几条是硬约束,改动时不要放松): + +- 图片走**和用户附件完全相同**的存储:登记到会话 `.attachments//`,记大小与 SHA-256;事件与历史里**只有附件 id 与元信息**,`base64` 既不进 `.agent-history.json`,也不进 IPC 事件、不进工具输出文本。UI 按 id 调 `attachment-preview` 取 dataUrl(复用了现成的懒加载、缩略图缓存与大图预览)。 +- 只接受**工作区内的本地路径**或本会话已有的图片附件。远端 URL、`data:` URL 一律拒绝——模型能决定屏幕上出现什么,不能让这个决定由外部地址驱动。 +- 格式按**文件头真实嗅探**(`inspectImage`),不看扩展名;SVG 被拒(可内嵌脚本)。单张 ≤8MB,每次 ≤4 张。 +- 回复图片带「AI 提供」标记,与用户自己的附件区分开,降低伪造截图冒充系统提示的风险。 +- 图片只给用户看,**不回喂模型**:OpenAI 的 `tool` role 普遍不接受图片数组,历史重放会 400。 + +定向验收:`npm run check:reply-images`(真起 sidecar + 真前端 + Chrome,断言渲染、正文定位、重载恢复与历史无 base64)。单测在 `sidecar/test/reply-image.test.mjs`。 + + ## 权限交互 访问边界 `mode` 与审批方式 `review` 分开保存。界面主选项为: diff --git a/package.json b/package.json index dbc71c2c8c..711ac98b33 100644 --- a/package.json +++ b/package.json @@ -9,6 +9,7 @@ "dev:desktop": "powershell -ExecutionPolicy Bypass -File scripts/dev-desktop.ps1", "check:ui": "node scripts/check-ui.mjs", "check:memory": "node scripts/check-memory-panel.mjs", + "check:reply-images": "node scripts/check-reply-images.mjs", "check:desktop-browser": "node scripts/check-desktop-browser.mjs", "check:powershell": "node scripts/check-powershell.mjs", "audit:ui": "node scripts/audit-ui.mjs", diff --git a/scripts/check-reply-images.mjs b/scripts/check-reply-images.mjs new file mode 100644 index 0000000000..1720356dcf --- /dev/null +++ b/scripts/check-reply-images.mjs @@ -0,0 +1,167 @@ +// 「AI 在回复里插图」的定向验收。 +// +// 单测已锁住「base64 不进历史 / 路径与格式校验 / 正文定位切分」这些纯逻辑。 +// 真正只有真跑浏览器才看得见的部分在这里: +// 1) 工具产出的图片在对话里真的渲染出来(不是一句「已截图」) +// 2) 正文 ![](image:) 指到哪就显示在哪,而不是被 sanitize 吃掉 +// 3) 历史重载后图片仍在(靠附件 id + attachment-preview,不是内存里的 dataUrl) +// +// 用法:node scripts/check-reply-images.mjs(需先 npm run build:ui) +import { spawn } from 'node:child_process'; +import http from 'node:http'; +import fs from 'node:fs'; +import path from 'node:path'; +import os from 'node:os'; +import WebSocket from 'ws'; +import { folderProof } from '../sidecar/grants.mjs'; + +const ROOT = process.cwd(); +const DIST = path.join(ROOT, 'ui-dist'); +const PORT = 5233, WS_PORT = 5234, TOKEN = 'replyimg'; +const CHROME = process.env.CHROME_PATH || [ + 'C:/Program Files/Google/Chrome/Application/chrome.exe', + 'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe', + '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', + '/usr/bin/google-chrome', '/usr/bin/chromium', +].find(p => fs.existsSync(p)); + +let bad = 0; +const ok = (cond, message) => { console.log((cond ? ' ok ' : ' x ') + message); if (!cond) bad++; }; + +if (!fs.existsSync(path.join(DIST, 'index.html'))) { console.error('先跑 npm run build:ui'); process.exit(2); } +if (!CHROME) { console.error('找不到 Chrome/Edge'); process.exit(2); } + +// 1×1 PNG:够小,且带真实 PNG 文件头,能过附件库的格式嗅探。 +const PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+j+1cAAAAASUVORK5CYII=', 'base64'); + +const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'reply-image-')); +const APP = path.join(DATA, 'WebDecryptHub'); +fs.mkdirSync(APP, { recursive: true }); +fs.writeFileSync(path.join(APP, 'settings.json'), JSON.stringify({ provider: 'openai', headless: true, embedMode: 'screencast' })); + +const sidecar = spawn(process.execPath, [path.join(ROOT, 'sidecar', 'index.mjs')], { + cwd: ROOT, env: { ...process.env, DECRYPTHUB_DATA_DIR: APP, JSRA_WS_PORT: String(WS_PORT), JSRA_WS_TOKEN: TOKEN, JSRA_TEST_FIXTURES: '1' }, stdio: ['ignore', 'pipe', 'pipe'], +}); +let sidecarErr = ''; +sidecar.stderr.on('data', d => { sidecarErr += String(d); }); +await new Promise((res, rej) => { + const t = setTimeout(() => rej(new Error('sidecar 未就绪:' + sidecarErr.slice(0, 600))), 25000); + sidecar.stdout.on('data', d => { if (/JSRA_PORT=/.test(String(d))) { clearTimeout(t); res(); } }); +}); + +const rpc = (channel, args = {}) => new Promise((resolve, reject) => { + const ws = new WebSocket('ws://127.0.0.1:' + WS_PORT + '/?token=' + TOKEN); + const timer = setTimeout(() => { ws.terminate(); reject(Error('RPC timeout: ' + channel)); }, 30000); + ws.once('open', () => ws.send(JSON.stringify({ type: 'invoke', id: 1, channel, args }))); + ws.on('message', raw => { const message = JSON.parse(raw); if (message.id !== 1) return; clearTimeout(timer); ws.close(); message.error ? reject(Error(message.error)) : resolve(message.result); }); + ws.once('error', error => { clearTimeout(timer); reject(error); }); +}); +await rpc('save-settings', { onboarding: { version: 1, completedAt: new Date().toISOString() } }).catch(error => console.error('save onboarding:', error.message)); + +const MIME = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.svg': 'image/svg+xml', '.png': 'image/png' }; +const srv = http.createServer((req, res) => { + let p = path.join(DIST, decodeURIComponent(new URL(req.url, 'http://x').pathname)); + if (!fs.existsSync(p) || fs.statSync(p).isDirectory()) p = path.join(DIST, 'index.html'); + res.writeHead(200, { 'Content-Type': MIME[path.extname(p)] || 'application/octet-stream', 'Cache-Control': 'no-store' }); + res.end(fs.readFileSync(p)); +}); +await new Promise(r => srv.listen(PORT, '127.0.0.1', r)); + +let browser, context, page; +const cleanup = async () => { + await context?.close().catch(() => {}); + await browser?.close().catch(() => {}); + await new Promise(r => srv.close(r)); + sidecar.kill(); +}; +try { + const { chromium } = await import('../node_modules/@zhizhuodemao/patchright/index.mjs'); + browser = await chromium.launch({ headless: true, executablePath: CHROME }); + context = await browser.newContext({ viewport: { width: 1440, height: 900 }, colorScheme: 'dark' }); + page = await context.newPage(); + const pageErrors = []; + page.on('pageerror', e => pageErrors.push(e.message)); + + await page.goto('http://127.0.0.1:' + PORT + '/?port=' + WS_PORT + '&token=' + TOKEN); + await page.locator('.stage-head').waitFor(); + + // 造真实项目 + 会话,并把一张 PNG 放进工作区,模拟「AI 手上有一张图」。 + const scope = 'reply-image-check'; + const root = path.join(DATA, 'project'); + fs.mkdirSync(root); + fs.writeFileSync(path.join(root, 'captures-login.png'), PNG); + const grant = { sessionId: scope, path: root, expiresAt: Date.now() + 60000 }; + grant.signature = folderProof(TOKEN, grant); + const project = await rpc('project-save', { scope, project: { name: '回复图片验收', folders: [{ key: 'main', grant }], primaryKey: 'main' } }); + const created = await rpc('session-create', { projectId: project.id }); + await rpc('session-focus', { sessionId: created.id }); + await page.reload(); + await page.locator('.msgs').waitFor(); + + // 1) 走真实 RPC:先登记附件,再把「工具产出图片」写进历史(等价于截图/reply_image 的结果)。 + const uploaded = await rpc('attach-path', { path: path.join(root, 'captures-login.png') }); + ok(uploaded?.id && uploaded.image === true, '附件登记成功且被识别为图片(id=' + uploaded?.id + ')'); + const preview = await rpc('attachment-preview', { sessionId: created.id, id: uploaded.id }); + ok(/^data:image\/png;base64,/.test(preview?.dataUrl || ''), 'attachment-preview 能按 id 取回 dataUrl'); + + // 直接注入一条「本会话已完成的工具事件」,模拟截图工具产出图片。 + await rpc('test-seed-history', { + sessionId: created.id, + events: [ + { t: 'user', id: 'u1', turnId: 'turn-img', displayContent: '给我看下截图', content: '给我看下截图' }, + { t: 'assistant', id: 'a1', turnId: 'turn-img', phase: 'commentary', content: '我截了一张图。', calls: [{ id: 'c1', itemId: 'i1', name: 'take_screenshot', args: {} }] }, + { t: 'tool', id: 'c1', itemId: 'i1', turnId: 'turn-img', name: 'take_screenshot', content: 'Took a screenshot of the current page viewport.', images: [{ id: uploaded.id, name: uploaded.name, mime: uploaded.mime, width: uploaded.width, height: uploaded.height }] }, + { t: 'assistant', id: 'a2', turnId: 'turn-img', phase: 'final_answer', content: '截图如下:\n\n![登录页](image:' + uploaded.id + ')\n\n按钮在右下角。' }, + { t: 'turn-end', turnId: 'turn-img', stop: 'completed', startedAt: Date.now() - 5000, endedAt: Date.now(), usage: {} }, + ], + }).catch(error => console.error('seed:', error.message)); + + await page.reload(); + await page.locator('.msgs').first().waitFor({ timeout: 15000 }); + + // 2) 正文里的 ![](image:):指到哪显示在哪,且不被 sanitize 吃掉。 + const inline = page.locator('.reply-md .reply-images img').first(); + await inline.waitFor({ timeout: 15000 }); + ok(await inline.isVisible(), '正文 image: 占位被渲染成真实图片'); + ok((await inline.getAttribute('src'))?.startsWith('data:image/'), '正文图片按附件 id 取回 dataUrl,不是坏链'); + const bubbleText = await page.locator('.msg.assistant .bubble').last().innerText(); + ok(!bubbleText.includes('image:'), '正文里不残留 image: 语法(实际 ' + JSON.stringify(bubbleText.slice(0, 120)) + ')'); + ok(bubbleText.includes('截图如下') && bubbleText.includes('按钮在右下角'), '图片前后文字都保留'); + + // 3) 展开执行过程后,工具产出的图片也要看得见(截图不该只剩一句「已截图」)。 + await page.locator('.turn-process > summary').first().click(); + const toolImg = page.locator('.tool-images img').first(); + await toolImg.waitFor({ timeout: 10000 }); + ok(await toolImg.isVisible(), '展开执行过程后能看到工具产出的图片'); + // 4) AI 提供的图片必须带来源标记,避免和用户自己的附件混淆(防钓鱼面)。 + ok((await page.locator('.reply-image-source').first().innerText()).includes('AI'), '回复图片标注了「AI 提供」'); + + // 5) 历史重载后仍在:这条路径证明图片靠附件 id 恢复,而不是内存里的 dataUrl。 + await page.reload(); + await page.locator('.msg.assistant .bubble').last().waitFor({ timeout: 15000 }); + ok(await page.locator('.reply-images img').first().isVisible({ timeout: 15000 }), '重载后图片仍然可见'); + + // 6) 图片不得把 base64 写进持久化历史。历史落在会话数据目录(projects/),不是项目目录。 + const histFiles = []; + const walkHist = dir => { + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + const full = path.join(dir, entry.name); + if (entry.isDirectory()) walkHist(full); + else if (entry.name === '.agent-history.json') histFiles.push(full); + } + }; + walkHist(APP); + ok(histFiles.length > 0, '找到落盘的历史文件(' + histFiles.length + ' 个)'); + const b64 = PNG.toString('base64'); + const dirty = histFiles.filter(f => fs.readFileSync(f, 'utf8').includes(b64)); + ok(dirty.length === 0, '历史文件里没有 base64' + (dirty.length ? ':' + dirty.join(', ') : '')); + ok(histFiles.some(f => fs.readFileSync(f, 'utf8').includes(uploaded.id)), '历史里以附件 id 引用图片'); + + ok(pageErrors.length === 0, '前端无 pageerror' + (pageErrors.length ? ':' + pageErrors[0] : '')); +} finally { + await cleanup(); + fs.rmSync(DATA, { recursive: true, force: true }); +} + +console.log(bad ? `\n失败 ${bad} 项` : '\n全部通过'); +process.exit(bad ? 1 : 0); diff --git a/sidecar/agent.mjs b/sidecar/agent.mjs index 9ab36f44f7..63537f968b 100644 --- a/sidecar/agent.mjs +++ b/sidecar/agent.mjs @@ -7,6 +7,7 @@ import crypto from 'node:crypto'; import { withModelRetries } from './model-retry.mjs'; import { goalContext } from './goals.mjs'; import { imageContent, validateAttachments } from './attachments.mjs'; +import { normalizeReplyImages } from './reply-image.mjs'; import { contentHash } from './changes.mjs'; import { resolveIn, containsPath } from './paths.mjs'; import { contextTokens, limitInfo, compactTrigger, breakdown, buildSummaryRequest, trimToolOutput, readRef, resolveAttachments, estimateTokens } from './context.mjs'; @@ -391,8 +392,10 @@ class Agent { catch (e) { r = { text: '[工具错误] ' + (e.message || e), isError: true }; } } const text = typeof r?.text === 'string' ? r.text : JSON.stringify(r ?? '(空)'); + // 图片只以附件引用(id + 元信息)随事件流动:base64 既不进历史,也不进工具输出文本。 + const images = normalizeReplyImages(this.projectDir, r?.images); outcomes.push({ name: tc.name, args: tc.args, text, isError: !!r?.isError }); - this.emit('tool-end', { id: tc.id, itemId: tc.itemId, turnId: this.turnId, name: tc.name, text, isError: !!r?.isError, ms: Date.now() - tt }); + this.emit('tool-end', { id: tc.id, itemId: tc.itemId, turnId: this.turnId, name: tc.name, text, isError: !!r?.isError, ms: Date.now() - tt, ...(images.length ? { images } : {}) }); // 工具声明「写了哪些文件」(绝对或项目内相对路径)→ 记到事件上,供「AI 写的」视图索引 const wrote = Array.isArray(r?.wrote) ? r.wrote.map(abs => { @@ -404,7 +407,7 @@ class Agent { } catch { return null; } }).filter(Boolean) : []; - this.hist.append({ t: 'tool', id: tc.id, itemId: tc.itemId, turnId: this.turnId, name: tc.name, ms: Date.now() - tt, workspaceId: this.getWorkspace()?.id, content: trimToolOutput(text || '(空)', { dir: this.ctxDir(), name: tc.name }), ...(r?.isError ? { isError: true } : {}), ...(wrote.length ? { wrote } : {}) }); + this.hist.append({ t: 'tool', id: tc.id, itemId: tc.itemId, turnId: this.turnId, name: tc.name, ms: Date.now() - tt, workspaceId: this.getWorkspace()?.id, content: trimToolOutput(text || '(空)', { dir: this.ctxDir(), name: tc.name }), ...(r?.isError ? { isError: true } : {}), ...(wrote.length ? { wrote } : {}), ...(images.length ? { images } : {}) }); this.record('tool-completed', { callId: tc.id, name: tc.name, isError: !!r?.isError, wrote }); } // 中断时补齐未执行的工具结果,避免下一轮出现缺失 tool_call_id 的 400 diff --git a/sidecar/browser.mjs b/sidecar/browser.mjs index 0c056a64d8..6ed22ab7b8 100644 --- a/sidecar/browser.mjs +++ b/sidecar/browser.mjs @@ -181,6 +181,11 @@ export class BrowserManager extends EventEmitter { .filter((p) => p.type === 'text') .map((p) => p.text) .join('\n'), + // 内核会以 image block 返回截图(take_screenshot 不落盘时)。以前这里被整体丢弃, + // 导致模型截图后用户什么也看不到。交给上层登记成附件,UI 再按 id 取图。 + images: (result.content || []) + .filter((p) => p.type === 'image' && p.data) + .map((p) => ({ name: '截图.' + /^image\/(\w+)$/.exec(p.mimeType || '')?.[1] || 'png', data: p.data })), isError: !!result.isError, }; } diff --git a/sidecar/browsertools.mjs b/sidecar/browsertools.mjs index 31d68542b7..22ec35f6b7 100644 --- a/sidecar/browsertools.mjs +++ b/sidecar/browsertools.mjs @@ -45,6 +45,10 @@ export const BROWSER_TOOLS = descriptors.map((tool) => ({ text: `已重建调试上下文(销毁并重新绑定 CDP target)。当前页面:${page || '未知'};Cookie、已填表单与已捕获请求均保留。旧的 scriptId、断点与 reqid 视为失效,请重新 list_scripts / list_network_requests。`, }; } - return ctx.browser.callTool(tool.name, args, ctx.signal); + const result = await ctx.browser.callTool(tool.name, args, ctx.signal); + // take_screenshot 默认把画面作为 image block 回传(不落盘时)。原样透传 images, + // 由 Agent 统一登记成附件,用户才能在对话里看到截图本身,而不是只看到一句「已截图」。 + if (result?.images?.length) return { ...result, images: result.images }; + return result; }, })); diff --git a/sidecar/catalog.mjs b/sidecar/catalog.mjs index 1e4f578b13..a10a5a9e50 100644 --- a/sidecar/catalog.mjs +++ b/sidecar/catalog.mjs @@ -4,7 +4,8 @@ import { TODO_TOOLS } from './todos.mjs'; import { AGENT_TOOLS } from './agenttools.mjs'; import { HARNESS_TOOLS } from './harnesstools.mjs'; import { EXTENSION_TOOLS } from './extension-tools.mjs'; +import { REPLY_TOOLS } from './reply-tools.mjs'; // One product registry shared by the runtime and the settings UI. // Legacy specialist modules remain importable for old artifacts, not model tools. -export const DEFAULT_TOOLS = [{name: 'component_list', description: '查看可选平台组件的安装状态。网页分析需要 WDH,核心文件任务无需组件。', schema:{type:'object',properties:{}}, run:async(_a,ctx)=>({text:JSON.stringify({components:ctx.plugins?ctx.plugins.status().official.map(({id,installed,enabled,version,state,latest})=>({id,installed,enabled,version,state,availableVersion:latest?.version||null})):['wdh','idh','adh'].map(id=>ctx.components?.info(id)||{id,installed:false})})})}, ...WORKSPACE_TOOLS, ...TODO_TOOLS, ...AGENT_TOOLS, ...HARNESS_TOOLS, ...EXTENSION_TOOLS, ...BROWSER_TOOLS]; +export const DEFAULT_TOOLS = [{name: 'component_list', description: '查看可选平台组件的安装状态。网页分析需要 WDH,核心文件任务无需组件。', schema:{type:'object',properties:{}}, run:async(_a,ctx)=>({text:JSON.stringify({components:ctx.plugins?ctx.plugins.status().official.map(({id,installed,enabled,version,state,latest})=>({id,installed,enabled,version,state,availableVersion:latest?.version||null})):['wdh','idh','adh'].map(id=>ctx.components?.info(id)||{id,installed:false})})})}, ...WORKSPACE_TOOLS, ...TODO_TOOLS, ...AGENT_TOOLS, ...HARNESS_TOOLS, ...EXTENSION_TOOLS, ...REPLY_TOOLS, ...BROWSER_TOOLS]; diff --git a/sidecar/mcphost.mjs b/sidecar/mcphost.mjs index 9b9ab83502..f716492b1d 100644 --- a/sidecar/mcphost.mjs +++ b/sidecar/mcphost.mjs @@ -160,8 +160,12 @@ export class McpHost { } catch (e) { return { text: `[MCP:${entry.cfg.name}] 调用失败:${e.message || e}`, isError: true }; } + // image block 以前被替换成「[图片 image/png]」文字,模型和用户都拿不到图。 + // 现在原样透传,由 Agent 统一登记成附件(历史里只留 id)。 + const images = (res.content || []).filter(c => c.type === 'image' && c.data) + .map(c => ({ name: '图片.' + (/^image\/(\w+)$/.exec(c.mimeType || '')?.[1] || 'png'), data: c.data })); const text = (res.content || []).map(c => c.type === 'text' ? c.text : c.type === 'image' ? `[图片 ${c.mimeType || ''}]` : c.type === 'resource' ? `[资源 ${c.resource?.uri || ''}]` : '').filter(Boolean).join('\n'); - return { text: (res.isError ? '[错误] ' : '') + (text || '(无返回内容)'), isError: !!res.isError }; + return { text: (res.isError ? '[错误] ' : '') + (text || '(无返回内容)'), isError: !!res.isError, ...(images.length ? { images } : {}) }; } async connect(cfg) { diff --git a/sidecar/policy.mjs b/sidecar/policy.mjs index f968309c6b..81cb0ac7c0 100644 --- a/sidecar/policy.mjs +++ b/sidecar/policy.mjs @@ -32,6 +32,7 @@ const READ = new Set([ 'list_network_requests', 'list_scripts', 'get_script_source', 'search_in_sources', 'list_breakpoints', 'get_request_initiator', 'get_paused_info', 'take_screenshot', 'get_websocket_messages', 'todo_write', 'ask_user', + 'reply_image', // 只把工作区里已有的图片交给 UI 展示,不写文件、不联网、不改远端状态 ]); const WRITE = new Set([ diff --git a/sidecar/reply-image.mjs b/sidecar/reply-image.mjs new file mode 100644 index 0000000000..caa8af947c --- /dev/null +++ b/sidecar/reply-image.mjs @@ -0,0 +1,79 @@ +// 让模型能在回复里插图:把工作区/附件里的图片登记成「回复图片」,UI 用现成的 +// attachment-preview 通道按 id 取 dataUrl 渲染。 +// +// 为什么不做成 Markdown 的 ![](data:...):那条路径会把 base64 写进 .agent-history.json, +// 直接破坏「历史不落 base64」这一既有不变量(见 attachments.test.mjs)。所以历史里 +// 只记附件 id,和其他附件走同一套存储、同一套校验。 +// +// 安全边界:模型能决定用户屏幕上出现什么图(伪造登录框/系统提示的钓鱼面), +// 因此这里不接受远端 URL、不接受 SVG(可内嵌脚本),一律按文件头真实嗅探格式。 +import fs from 'node:fs'; +import path from 'node:path'; +import { registerAttachment, attachment, inspectImage, MAX_ATTACHMENT_BYTES } from './attachments.mjs'; +import { workspacePath } from './workspaces.mjs'; + +export const MAX_REPLY_IMAGES = 4; + +/** + * 把一张本地图片登记为可展示的回复图片。 + * 只认工作区内的文件,或已经登记过的附件(kind:'attachment')。 + * @param {string} projectDir 会话数据目录(附件库根) + * @param {{ path?: string, attachmentId?: string }} input + * @param {{ ctx?: object, root?: { workRoot?: string } }} opts workRoot 用于解析工作区相对路径 + * @returns {{ id: string, name: string, mime: string, width: number, height: number, bytes: number }} + */ +export function registerReplyImage(projectDir, input, { ctx } = {}) { + const id = String(input?.attachmentId || '').trim(); + if (id) { + // 复用已有附件:仍然重新走一遍 attachment() 的哈希校验,不信任调用方给的 id。 + const a = attachment(projectDir, id); + if (!a.image) throw new Error('该附件不是图片,无法在回复中显示'); + return pick(a); + } + const rel = String(input?.path || input?.file || '').trim(); + if (!rel) throw new Error('需要 path(工作区内的图片路径)或 attachmentId'); + if (/^[a-z][\w+.-]*:/i.test(rel)) throw new Error('只支持工作区内的本地图片,不接受网址'); + const file = workspacePath(ctx, rel); + const st = fs.statSync(file); + if (!st.isFile()) throw new Error('不是文件:' + rel); + if (st.size > MAX_ATTACHMENT_BYTES) throw new Error('图片超过 8MB,请先压缩再发送'); + const bytes = fs.readFileSync(file); + // inspectImage 只按文件头判断:扩展名写成 .png 的 SVG/PDF 会在这里被拒。 + if (!inspectImage(bytes)) throw new Error('不是受支持的图片格式;仅支持 PNG、JPEG、WebP 和静态 GIF'); + return pick(registerAttachment(projectDir, { name: path.basename(file), data: bytes })); +} + +function pick(a) { + return { id: a.id, name: a.label || a.name, mime: a.mime, width: a.width, height: a.height, bytes: a.bytes }; +} + +/** + * 工具返回的图片统一收敛成附件引用。 + * 接受的两种形状: + * { id, ... } —— 已经是附件(reply_image) + * { name, data, mime? } —— 工具当场拿到的 base64(截图、MCP image block) + * 返回值只含 id 与元信息,base64 在这里就落地成附件,绝不随事件/历史流动。 + */ +export function normalizeReplyImages(projectDir, list) { + const out = []; + for (const item of (Array.isArray(list) ? list : []).slice(0, MAX_REPLY_IMAGES)) { + try { + if (item?.id) { const a = attachment(projectDir, item.id); if (a.image) out.push({ ...pick(a), ...(item.caption ? { caption: String(item.caption).slice(0, 200) } : {}) }); continue; } + if (typeof item?.data === 'string' && item.data) { + const a = registerAttachment(projectDir, { name: item.name || '图片', data: item.data, mime: String(item.mime || '') }); + if (a.image) out.push(pick(a)); + } + } catch { /* 单张坏图不影响同批其他图片,也不该让整次工具调用失败 */ } + } + return out; +} + +/** 模型在正文里用 ![说明](image:) 指定的位置:只认本会话真实存在的图片附件。 */ +export function imageRefIn(projectDir, id) { + try { + const key = String(id || ''); + if (!/^[a-f0-9-]{36}$/.test(key)) return null; + const a = attachment(projectDir, key); + return a.image ? { id: a.id, name: a.label || a.name } : null; + } catch { return null; } +} diff --git a/sidecar/reply-tools.mjs b/sidecar/reply-tools.mjs new file mode 100644 index 0000000000..970e824d57 --- /dev/null +++ b/sidecar/reply-tools.mjs @@ -0,0 +1,39 @@ +// reply_image:让模型把一张本地图片放进回复里给用户看。 +// +// 为什么单独做一个工具而不是让模型写 Markdown 的 ![](data:...):base64 会进历史、 +// 会瞬间吃掉上下文、也会让 .agent-history.json 膨胀几十倍。这里只传附件 id, +// 图片本体留在 .attachments 里,UI 按需取 dataUrl(复用现有 attachment-preview 通道)。 +import { object, str } from './contract.mjs'; +import { registerReplyImage } from './reply-image.mjs'; + +async function replyImage(a, ctx) { + if (!ctx.projectDir) return { text: '当前会话没有可用的附件存储,无法发送图片。', isError: true }; + let ref; + try { + ref = registerReplyImage(ctx.projectDir, a, { ctx }); + } catch (e) { + return { text: '没有发送这张图片:' + (e.message || e), isError: true }; + } + const caption = String(a.caption || '').trim().slice(0, 200); + return { + text: `已发送图片 ${ref.name}(${ref.width}×${ref.height})${caption ? ',说明:' + caption : ''}。\n` + + `图片已经展示给用户了。如果需要在正文里指定它出现的位置,就在该处写一行 ![${caption || ref.name}](image:${ref.id});` + + `不写也会附在回复末尾,不要重复发送同一张图。`, + images: [{ ...ref, caption }], + }; +} + +export const REPLY_TOOLS = [ + { + name: 'reply_image', + description: '把一张图片放进你的回复里给用户看(截图、生成的图表、工作区里已有的图片)。用户能直接看到它,不需要你转述内容。' + + 'path 是工作区内相对路径,或传 attachmentId 引用用户之前发的附件。仅支持 PNG/JPEG/WebP/静态 GIF,单张不超过 8MB,一次最多 4 张。' + + '想让图片出现在正文某处时,就在那里单独一行写 ![说明](image:<返回的 id>);不写则附在回复末尾。不要用 Markdown 直接嵌入 data: 或 http 图片。', + schema: object({ + path: str('工作区内的图片路径(相对工作目录),例如 captures/login.png'), + attachmentId: str('可选:引用本会话已有的图片附件 id,优先于 path'), + caption: str('一句话说明这张图是什么,会显示在图片下方'), + }), + run: replyImage, + }, +]; diff --git a/sidecar/test/reply-image.test.mjs b/sidecar/test/reply-image.test.mjs new file mode 100644 index 0000000000..1af95159d3 --- /dev/null +++ b/sidecar/test/reply-image.test.mjs @@ -0,0 +1,188 @@ +// AI 向用户发图:reply_image 工具、截图回传、正文插图位置、以及「历史不落 base64」不变量。 +// +// 这套测试守的核心是:图片只能以附件 id 在事件/历史里流动。一旦哪天有人图省事 +// 把 base64 塞进 tool 结果或 Markdown,这里会立刻红。 +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import http from 'node:http'; +import { Agent } from '../agent.mjs'; +import { registerAttachment, attachment } from '../attachments.mjs'; +import { normalizeReplyImages, registerReplyImage } from '../reply-image.mjs'; +import { DEFAULT_TOOLS } from '../catalog.mjs'; +import { toolRisk, decideTool } from '../policy.mjs'; +import { splitImageRefs } from '../../ui/src/image-refs.js'; + +const PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+j+1cAAAAASUVORK5CYII=', 'base64'); +const fixture = t => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-reply-image-')); + t.after(() => fs.rmSync(dir, { recursive: true, force: true })); + fs.mkdirSync(path.join(dir, 'workspace'), { recursive: true }); + return dir; +}; + +test('reply_image is registered and classified read-only so policy stays complete', () => { + const tool = DEFAULT_TOOLS.find(t => t.name === 'reply_image'); + assert.ok(tool, 'reply_image 必须出现在默认工具注册表里'); + assert.equal(toolRisk('reply_image'), 'read'); + // 只读模式下也要能用:把已有图片展示给用户不产生任何外部副作用。 + assert.equal(decideTool('read-only', 'reply_image').action, 'run'); +}); + +test('reply_image accepts a workspace image and rejects everything else', t => { + const dir = fixture(t); + fs.writeFileSync(path.join(dir, 'workspace', 'shot.png'), PNG); + fs.writeFileSync(path.join(dir, 'workspace', 'fake.png'), ''); + fs.writeFileSync(path.join(dir, 'workspace', 'notes.txt'), 'hello'); + const ctx = { workRoot: path.join(dir, 'workspace'), workspaceKind: 'folder' }; + + const ok = registerReplyImage(dir, { path: 'shot.png' }, { ctx }); + assert.equal(ok.mime, 'image/png'); + assert.equal(ok.width, 1); + assert.match(ok.id, /^[a-f0-9-]{36}$/); + + // 扩展名是 .png 但内容是 SVG:按文件头嗅探必须拒绝,不能靠扩展名放行。 + assert.throws(() => registerReplyImage(dir, { path: 'fake.png' }, { ctx }), /不是受支持的图片格式/); + assert.throws(() => registerReplyImage(dir, { path: 'notes.txt' }, { ctx }), /不是受支持的图片格式/); + // 远端地址一律拒绝(模型能触发 = 不能让屏幕内容由外部 URL 决定)。 + assert.throws(() => registerReplyImage(dir, { path: 'https://example.com/x.png' }, { ctx }), /不接受网址/); + assert.throws(() => registerReplyImage(dir, { path: 'data:image/png;base64,AAAA' }, { ctx }), /不接受网址/); + // 越界路径交给 workspacePath 拦。 + assert.throws(() => registerReplyImage(dir, { path: '../../etc/passwd' }, { ctx }), /工作区|超出|越界|无效/); +}); + +test('reply_image can reuse an existing attachment but re-verifies its hash', t => { + const dir = fixture(t); + const a = registerAttachment(dir, { name: 'clip.png', data: PNG }); + assert.equal(registerReplyImage(dir, { attachmentId: a.id }).id, a.id); + + // 篡改附件后,reply_image 不能因为「id 眼熟」就放行。 + const file = attachment(dir, a.id).file; + const changed = Buffer.from(PNG); changed[changed.length - 1] ^= 1; + fs.writeFileSync(file, changed); + assert.throws(() => registerReplyImage(dir, { attachmentId: a.id }), /已变化/); +}); + +test('images never enter tool text or history as base64', async t => { + const dir = fixture(t); + fs.writeFileSync(path.join(dir, 'workspace', 'shot.png'), PNG); + const ctx = { workRoot: path.join(dir, 'workspace'), workspaceKind: 'folder' }; + const ref = registerReplyImage(dir, { path: 'shot.png' }, { ctx }); + + // 工具返回图片(截图 / reply_image 都走这条路):只保留 id 与元信息。 + const normalized = normalizeReplyImages(dir, [{ ...ref, caption: '登录页' }]); + assert.equal(normalized.length, 1); + assert.equal(normalized[0].id, ref.id); + assert.equal(normalized[0].caption, '登录页'); + assert.ok(!JSON.stringify(normalized).includes(PNG.toString('base64'))); + + // 工具当场拿到的 base64(截图 image block)在落地成附件后也只留 id。 + const fromBase64 = normalizeReplyImages(dir, [{ name: '截图.png', data: PNG.toString('base64') }]); + assert.equal(fromBase64.length, 1); + assert.ok(!JSON.stringify(fromBase64).includes(PNG.toString('base64'))); + + // 坏图不该让同批其他图片或整次调用失败。 + assert.equal(normalizeReplyImages(dir, [{ name: 'bad.png', data: 'not base64' }]).length, 0); + assert.equal(normalizeReplyImages(dir, [null, undefined, 42]).length, 0); +}); + +test('tool events and saved history carry image ids only, and survive a reload', async t => { + const dir = fixture(t); + fs.writeFileSync(path.join(dir, 'workspace', 'shot.png'), PNG); + const ctx = { workRoot: path.join(dir, 'workspace'), workspaceKind: 'folder' }; + let received; + const server = http.createServer((req, res) => { let body = ''; req.on('data', b => body += b); req.on('end', () => { + received = JSON.parse(body); + res.writeHead(200, { 'Content-Type': 'text/event-stream' }); + // 第一步:模型调 reply_image;第二步:给出最终回复(正文用 image: 指定位置)。 + const first = !received.messages.some(m => m.role === 'tool'); + const chunk = first + ? { choices: [{ delta: { tool_calls: [{ index: 0, id: 'call_1', function: { name: 'reply_image', arguments: JSON.stringify({ path: 'shot.png', caption: '登录页' }) } }] } }] } + : { choices: [{ delta: { content: '截图如下:\n\n![登录页](image:PLACEHOLDER)\n\n按钮在右下角。' }, finish_reason: 'stop' }] }; + res.end('data: ' + JSON.stringify(chunk) + '\n\ndata: [DONE]\n\n'); + }); }); + await new Promise(r => server.listen(0, '127.0.0.1', r)); + t.after(() => { server.closeAllConnections(); return new Promise(r => server.close(r)); }); + + const settings = { provider: 'openai', openai: { baseUrl: `http://127.0.0.1:${server.address().port}/v1`, model: 'fixture', apiKey: 'k', vision: true } }; + const emitted = []; + const create = () => new Agent({ + projectDir: dir, getSettings: () => settings, tools: DEFAULT_TOOLS, mcp: { tools: [] }, + emit: (ev, p) => emitted.push({ ev, p }), getWorkspace: () => ({ id: 'w1', root: ctx.workRoot, kind: 'folder' }), + getToolContext: () => ({}), + }); + const agent = create(); + const result = await agent.send('给我看下截图', { runId: 'turn-1' }); + assert.equal(result.stop, 'completed'); + + const toolEnd = emitted.find(e => e.ev === 'tool-end' && e.p.name === 'reply_image'); + assert.ok(toolEnd, 'reply_image 必须产生 tool-end 事件'); + assert.equal(toolEnd.p.images.length, 1); + assert.match(toolEnd.p.images[0].id, /^[a-f0-9-]{36}$/); + // 事件里绝对不能出现 base64,否则会随 IPC 一路灌进 UI 状态。 + assert.ok(!JSON.stringify(toolEnd.p).includes(PNG.toString('base64'))); + + // 历史文件同样只留 id。 + const disk = fs.readFileSync(path.join(dir, '.agent-history.json'), 'utf8'); + assert.ok(!disk.includes(PNG.toString('base64')), '历史里不能出现 base64'); + const savedTool = JSON.parse(disk).events.find(e => e.t === 'tool' && e.name === 'reply_image'); + assert.equal(savedTool.images.length, 1); + + // 重新加载后图片引用还在(UI 靠 id 去 .attachments 取图)。 + const restored = create(); restored.restore(); + const back = restored.hist.events.find(e => e.t === 'tool' && e.name === 'reply_image'); + assert.equal(back.images[0].id, savedTool.images[0].id); +}); + +test('take_screenshot image blocks reach the reply instead of being dropped', async t => { + const dir = fixture(t); + // 直接验证 Agent 对「工具返回 base64 图片」的处理:browser.invoke 会把 image block + // 归一成 { name, data },这里用同形状的假工具代替真实内核。 + const tools = [{ name: 'take_screenshot', description: '截图', schema: { type: 'object', properties: {} }, run: async () => ({ text: 'Took a screenshot of the current page viewport.', images: [{ name: '截图.png', data: PNG.toString('base64') }] }) }]; + let calls = 0, received; + const server = http.createServer((req, res) => { let body = ''; req.on('data', b => body += b); req.on('end', () => { + received = JSON.parse(body); + res.writeHead(200, { 'Content-Type': 'text/event-stream' }); + const step = calls++; + const chunk = step === 0 + ? { choices: [{ delta: { tool_calls: [{ index: 0, id: 'c1', function: { name: 'take_screenshot', arguments: '{}' } }] } }] } + : { choices: [{ delta: { content: '已截图。' }, finish_reason: 'stop' }] }; + res.end('data: ' + JSON.stringify(chunk) + '\n\ndata: [DONE]\n\n'); + }); }); + await new Promise(r => server.listen(0, '127.0.0.1', r)); + t.after(() => { server.closeAllConnections(); return new Promise(r => server.close(r)); }); + const settings = { provider: 'openai', openai: { baseUrl: `http://127.0.0.1:${server.address().port}/v1`, model: 'fixture', apiKey: 'k', vision: true } }; + const emitted = []; + const agent = new Agent({ projectDir: dir, getSettings: () => settings, tools, mcp: { tools: [] }, emit: (ev, p) => emitted.push({ ev, p }), getToolContext: () => ({}) }); + await agent.send('截个图', { runId: 't2' }); + + const end = emitted.find(e => e.ev === 'tool-end' && e.p.name === 'take_screenshot'); + assert.ok(end, '截图工具必须产生 tool-end'); + assert.equal(end.p.images?.length, 1, '截图不能再被丢弃'); + assert.match(end.p.images[0].id, /^[a-f0-9-]{36}$/); + // 图片只对用户展示,不作为 tool 结果回喂模型(tool role 普遍不接受图片块)。 + const toolMsg = received.messages.find(m => m.role === 'tool'); + assert.ok(toolMsg, '必须有 tool 结果'); + assert.equal(typeof toolMsg.content, 'string'); + assert.ok(!toolMsg.content.includes(PNG.toString('base64'))); +}); + +test('splitImageRefs locates inline images and leaves other markdown alone', () => { + const id = '11111111-2222-3333-4444-555555555555'; + const parts = splitImageRefs(`前文\n\n![登录页](image:${id})\n\n后文`); + assert.deepEqual(parts.map(p => p.type), ['text', 'image', 'text']); + assert.equal(parts[1].id, id); + assert.equal(parts[1].label, '登录页'); + + // 普通 Markdown 图片、非法的 image: 目标、以及没有图片的正文都不受影响。 + assert.deepEqual(splitImageRefs('![](https://example.com/a.png)'), [{ type: 'text', text: '![](https://example.com/a.png)' }]); + assert.deepEqual(splitImageRefs('![x](image:not-a-uuid)'), [{ type: 'text', text: '![x](image:not-a-uuid)' }]); + assert.deepEqual(splitImageRefs('纯文本'), [{ type: 'text', text: '纯文本' }]); + // 代码块里的同形文本目前仍会被匹配(模型解释这个语法时很常见)。 + // 这是已知取舍:切分在 Markdown 解析之前,认不出围栏;代价只是把一段示例文字 + // 显示成图片占位,且占位图仍需真实附件 id 才能出图,不会产生伪造内容。 + const inFence = '```md\n![x](image:' + id + ')\n```'; + assert.equal(splitImageRefs(inFence).filter(p => p.type === 'image').length, 1); +}); diff --git a/ui/src/app.css b/ui/src/app.css index e2ca897bc3..940e630bc2 100644 --- a/ui/src/app.css +++ b/ui/src/app.css @@ -780,6 +780,16 @@ kbd { font-family: var(--default-font-family); font-size: 10px; font-weight: 400 .attachment-remove { position: absolute; top: 3px; right: 3px; } .image-preview { display: flex; align-items: center; justify-content: center; min-height: 180px; margin-top: 18px; } .image-preview img { max-width: 100%; max-height: 72vh; object-fit: contain; } +/* 回复里的图片:AI 主动给用户看的截图/图表,比用户附件给更大的预览面积。 */ +.reply-images { margin: 10px 0 2px; align-items: flex-start; } +.reply-image { display: flex; flex-direction: column; gap: 4px; min-width: 0; } +.reply-images .attachment-tile.is-image { width: 200px; height: 140px; } +.tool-images { margin: 6px 0 2px; } +.tool-images .attachment-tiles { margin-bottom: 0; } +.tool-images .attachment-tile.is-image { width: 148px; height: 104px; } +.reply-image-source { font-size: 10px; line-height: 1; color: var(--gray-10); letter-spacing: .02em; } +.reply-image-caption { font-size: 11px; color: var(--gray-11); max-width: 200px; } +.reply-md > .md + .md, .reply-md > .attachment-tiles + .md { margin-top: 8px; } .composer.drag-over { outline: 2px solid var(--blue-8); outline-offset: 2px; } .drop-hint { position: absolute; inset: 0; display: grid; place-items: center; z-index: 2; pointer-events: none; color: var(--blue-11); background: var(--blue-a3); border-radius: inherit; font-size: 14px; backdrop-filter: blur(3px); } @container (max-width: 460px) { diff --git a/ui/src/attachments.jsx b/ui/src/attachments.jsx index 20714b4498..8632fd7202 100644 --- a/ui/src/attachments.jsx +++ b/ui/src/attachments.jsx @@ -65,3 +65,19 @@ export function AttachmentTiles({ items = [], sessionId, invoke, onRemove }) { if (!items.length) return null; return
{items.map((item, i) => onRemove(item.key) : undefined} />)}
; } + +// 回复里的图片:AI 主动给用户看的截图/图表。 +// 复用同一个 AttachmentTile(懒加载、缩略图缓存、点击看大图),只额外标注来源, +// 避免和用户自己上传的附件混淆——模型能决定屏幕上出现什么,这个标记是防伪的一部分。 +// image:true 由这里强制给出:本组件只收图片,调用方(工具事件 / 正文 image:) +// 传进来的元信息不一定带这个字段,缺了就会退化成「文件卡片」。 +export function ReplyImages({ items = [], sessionId, invoke }) { + if (!items.length) return null; + return
+ {items.map((item, i) =>
+ + AI 提供 + {item.caption && {item.caption}} +
)} +
; +} diff --git a/ui/src/chat.jsx b/ui/src/chat.jsx index 9d649dfa31..63d8bda50a 100644 --- a/ui/src/chat.jsx +++ b/ui/src/chat.jsx @@ -6,7 +6,8 @@ import { Button, ActionIcon, Icon, Markdown, Dropdown } from './kit.jsx'; import { fmtK, sessionLabel } from './state.js'; import { native } from './transport.js'; import { PermissionPicker, PendingActions } from './workspace.jsx'; -import { AttachmentTiles } from './attachments.jsx'; +import { AttachmentTiles, ReplyImages } from './attachments.jsx'; +import { ReplyMarkdown } from './reply-markdown.jsx'; import { conversationTurns, toolPresentation, elapsedLabel } from './conversation.js'; import { TurnTrigger } from './turn-trigger.jsx'; import { commandMatches } from './commands.js'; @@ -194,6 +195,7 @@ function TurnProcess({ turn }) { function ToolEvent({ e }) { const [open, setOpen] = useState(false); + const w = useWorkbench(); const st = e.result === undefined ? 'run' : e.isError ? 'err' : e.cancelled ? 'cancelled' : 'ok'; const format = value => typeof value === 'string' ? value : JSON.stringify(value, null, 2); const duration = e.ms == null ? '' : e.ms < 1000 ? `${e.ms} ms` : `${(e.ms / 1000).toFixed(1)} s`; @@ -207,6 +209,8 @@ function ToolEvent({ e }) { {open &&
{e.name}{duration}
} + {/* 截图等工具产出的图片:折叠状态下也贴在工具条下方,用户和模型都不用再转述。 */} + {!!e.images?.length &&
} ; } @@ -221,8 +225,11 @@ function AssistantMessage({ e, turn, copy }) { const complete = e.phase === 'final_answer' && !!turn?.endedAt; const time = complete ? new Date(turn.endedAt).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }) : ''; const final = e.phase === 'final_answer'; + // 本轮所有工具产出的图片(截图、reply_image)。正文里用 image: 指过位置的会被排除, + // 剩下的附在回复末尾——否则模型把图发在中间步骤时,用户只看得到一句「已发送图片」。 + const images = useMemo(() => final ? (turn?.tools || []).flatMap(t => t.images || []) : [], [final, turn]); return
-
+
{final &&
w.rate(e.id, 'up')} title={rating === 'up' ? '取消“有帮助”' : '标记为有帮助'} aria-label="有帮助" aria-pressed={rating === 'up'} /> diff --git a/ui/src/conversation.js b/ui/src/conversation.js index 9a52a4856e..dfa806e534 100644 --- a/ui/src/conversation.js +++ b/ui/src/conversation.js @@ -11,7 +11,7 @@ export function historyEvents(history, partial = '', partialItem = null, partial for (const call of e.calls || []) events.push({ type: 'tool', id: call.id, itemId: call.itemId, turnId: e.turnId, at: e.at, name: call.name, args: call.args }); } else if (e.t === 'tool') { const item = [...events].reverse().find(t => t.type === 'tool' && (e.itemId ? t.itemId === e.itemId : t.id === e.id && t.result === undefined)); - if (item) Object.assign(item, { result: e.content, isError: !!e.isError, ms: e.ms }); + if (item) Object.assign(item, { result: e.content, isError: !!e.isError, ms: e.ms, ...(e.images?.length ? { images: e.images } : {}) }); } else if (e.t === 'continuation') events.push({ ...meta, type: 'continuation', content: String(e.content || ''), source: e.source || null, notice: e.notice || null }); else if (e.t === 'turn-end') events.push({ ...e, type: 'turn-end' }); else if (e.t === 'summary') events.push({ ...meta, type: 'compact', stage: 'compressed', summary: e.content, ...e.meta }); diff --git a/ui/src/image-refs.js b/ui/src/image-refs.js new file mode 100644 index 0000000000..a1a2f9bdad --- /dev/null +++ b/ui/src/image-refs.js @@ -0,0 +1,26 @@ +// 回复正文里的图片引用:纯逻辑,零依赖。 +// +// 单独成一个模块的原因:md.js 顶层 import 了 highlight.js 的 CSS,node 的测试 +// 进程无法加载 .css,所以任何想被 node:test 直接 import 的纯函数都不能住在 md.js 里 +// (见 BASELINE.md「共享模块保持零 top-level import」)。 +// +// 语法:![说明](image:<附件id>) +// 只认本会话附件 id 的形状(uuid),其他 image: 目标原样留在文本里,不产生图片。 +const IMAGE_REF = /!\[([^\]\n]*)\]\(image:([a-f0-9-]{36})\)/g; + +/** + * 把正文切成 [{type:'text',text}, {type:'image',id,label}] 交错的片段。 + * @param {string} text + */ +export function splitImageRefs(text) { + const src = String(text ?? ''); + const out = []; + let last = 0; + for (const m of src.matchAll(IMAGE_REF)) { + if (m.index > last) out.push({ type: 'text', text: src.slice(last, m.index) }); + out.push({ type: 'image', id: m[2], label: m[1] || '图片' }); + last = m.index + m[0].length; + } + if (last < src.length) out.push({ type: 'text', text: src.slice(last) }); + return out.length ? out : [{ type: 'text', text: src }]; +} diff --git a/ui/src/md.js b/ui/src/md.js index 329999d2e2..3789d2ecfa 100644 --- a/ui/src/md.js +++ b/ui/src/md.js @@ -5,11 +5,22 @@ import { neutralizeHtml } from './sanitize.js'; marked.setOptions({ breaks: true, gfm: true }); const attribute = value => String(value || '').replace(/[&"<>]/g, c => ({ '&': '&', '"': '"', '<': '<', '>': '>' }[c])); -marked.use({ renderer: { link({ href, title, tokens }) { - const label = this.parser.parseInline(tokens), target = String(href || '').trim(); - if (/[\x00-\x1f\x7f]/.test(target) || (/^[a-z][\w+.-]*:/i.test(target) && !/^(?:https?:|file:|[a-z]:[\\/])/i.test(target))) return label; - return '' + label + ''; -} } }); +marked.use({ renderer: { + link({ href, title, tokens }) { + const label = this.parser.parseInline(tokens), target = String(href || '').trim(); + if (/[\x00-\x1f\x7f]/.test(target) || (/^[a-z][\w+.-]*:/i.test(target) && !/^(?:https?:|file:|[a-z]:[\\/])/i.test(target))) return label; + return '' + label + ''; + }, + // 兜底:正文里的 ![说明](image:<附件id>) 正常由 reply-markdown.jsx 先切段,走不到这里。 + // 但文档面板、压缩摘要等其它 Markdown 入口可能带上同样的语法,所以这里保证它 + // 永远不会变成 (坏图)——只留一个带 id 的占位标记。 + // 其余图片(含 data: 与相对路径)继续走 marked 的默认渲染,不受影响。 + image(token) { + const href = String(token.href || '').trim(); + if (!/^image:[a-f0-9-]{36}$/.test(href)) return false; // false = 用默认 renderer + return '' + attribute(token.text || '图片') + ''; + }, +} }); // 渲染前先把原始 HTML 中和掉:结果经 dangerouslySetInnerHTML 注入, // 而输入里混着抓包响应体/脚本片段/模型回复(见 sanitize.js 的注释)。 diff --git a/ui/src/reply-markdown.jsx b/ui/src/reply-markdown.jsx new file mode 100644 index 0000000000..62239e763b --- /dev/null +++ b/ui/src/reply-markdown.jsx @@ -0,0 +1,32 @@ +// 回复正文里的图片。 +// +// 模型可以用 ![说明](image:<附件id>) 指定图片出现在正文的位置,也可以只调 reply_image +// 让图片附在末尾。两条路都收敛到这里渲染:按 id 走 attachment-preview 取 dataUrl, +// 图片本体永远不进 Markdown 字符串、不进 DOM 的 innerHTML、不进历史。 +import React, { useMemo } from 'react'; +import { Markdown } from './kit.jsx'; +import { splitImageRefs } from './image-refs.js'; +import { ReplyImages } from './attachments.jsx'; + +/** + * @param {{text:string, images?:Array, sessionId:string, invoke:Function, streaming?:boolean}} props + * images 来自工具事件(reply_image / take_screenshot),是「没有在正文里指定位置」的那部分。 + */ +export function ReplyMarkdown({ text, images = [], sessionId, invoke, streaming = false }) { + const parts = useMemo(() => splitImageRefs(text), [text]); + // 正文里已经用 image: 指过位置的图片,不再重复附在末尾。 + const inline = useMemo(() => new Set(parts.filter(p => p.type === 'image').map(p => p.id)), [parts]); + const trailing = useMemo(() => (images || []).filter(img => img?.id && !inline.has(img.id)), [images, inline]); + if (!inline.size) { + return <> + + {!!trailing.length && } + ; + } + return
+ {parts.map((part, i) => part.type === 'image' + ? + : (part.text.trim() ? : null))} + {!!trailing.length && } +
; +} diff --git a/ui/src/state.js b/ui/src/state.js index 99dc451305..d29049b1b1 100644 --- a/ui/src/state.js +++ b/ui/src/state.js @@ -64,7 +64,7 @@ export function sessionReducer(state, action) { const events = cur.events.slice(); for (let i = events.length - 1; i >= 0; i--) { const e = events[i]; - if (e.type === 'tool' && (action.v.itemId ? e.itemId === action.v.itemId : e.id === action.v.id) && e.result === undefined) { events[i] = { ...e, result: action.v.text, isError: action.v.isError, ms: action.v.ms }; break; } + if (e.type === 'tool' && (action.v.itemId ? e.itemId === action.v.itemId : e.id === action.v.id) && e.result === undefined) { events[i] = { ...e, result: action.v.text, isError: action.v.isError, ms: action.v.ms, ...(action.v.images?.length ? { images: action.v.images } : {}) }; break; } } return set({ events }); }