Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions docs/chat-experience.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<id>/`,记大小与 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` 分开保存。界面主选项为:
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
167 changes: 167 additions & 0 deletions scripts/check-reply-images.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
// 「AI 在回复里插图」的定向验收。
//
// 单测已锁住「base64 不进历史 / 路径与格式校验 / 正文定位切分」这些纯逻辑。
// 真正只有真跑浏览器才看得见的部分在这里:
// 1) 工具产出的图片在对话里真的渲染出来(不是一句「已截图」)
// 2) 正文 ![](image:<id>) 指到哪就显示在哪,而不是被 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:<id>):指到哪显示在哪,且不被 sanitize 吃掉。
const inline = page.locator('.reply-md .reply-images img').first();
await inline.waitFor({ timeout: 15000 });
ok(await inline.isVisible(), '正文 image:<id> 占位被渲染成真实图片');
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/<id>),不是项目目录。
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);
7 changes: 5 additions & 2 deletions sidecar/agent.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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 => {
Expand All @@ -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
Expand Down
5 changes: 5 additions & 0 deletions sidecar/browser.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
};
}
Expand Down
6 changes: 5 additions & 1 deletion sidecar/browsertools.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
},
}));
3 changes: 2 additions & 1 deletion sidecar/catalog.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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];
6 changes: 5 additions & 1 deletion sidecar/mcphost.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
Loading
Loading