From c228acf562bd60cc8378609a8d5d1a3372762a9a Mon Sep 17 00:00:00 2001 From: taisuii <93462725+taisuii@users.noreply.github.com> Date: Mon, 2 Nov 2026 12:04:56 +0800 Subject: [PATCH 1/7] =?UTF-8?q?desktop:=20=E6=95=B0=E6=8D=AE=E7=9B=AE?= =?UTF-8?q?=E5=BD=95=E8=BF=81=E5=88=B0=E4=BA=A7=E5=93=81=E5=90=8D=EF=BC=8C?= =?UTF-8?q?=E5=B9=B6=E6=94=B6=E5=85=BB=E7=A3=81=E7=9B=98=E4=B8=8A=E7=9A=84?= =?UTF-8?q?=E5=AD=A4=E5=84=BF=E4=BC=9A=E8=AF=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 数据目录:debug 脚本与安装版共用 %APPDATA%\DecryptHub,不再各用一份。 旧的 WebDecryptHub 目录在启动时整体迁移,已有会话和凭据不丢; 需要隔离调试时显式设 DECRYPTHUB_DATA_DIR。 历史会话:此前只处理了「索引里有、但没有 projectId」这一种。 还有一种更隐蔽的——磁盘上有数据目录、索引里根本没有,用户完全看不到它存在, 既不会恢复也不会出现在删除提示里。现在启动时扫一遍 projects/ 目录, 只收养带 .agent-history.json(真有对话)的目录,空壳目录不列。 恢复沿用与正常会话相同的路径,删除仍是用户明确选择后才执行。 --- README.md | 4 +- scripts/dev-desktop.ps1 | 4 +- scripts/start-desktop.ps1 | 5 +- sidecar/index.mjs | 3 +- sidecar/sessions.mjs | 112 ++++++++++++++-- sidecar/settings.mjs | 15 ++- sidecar/test/legacy-restore.test.mjs | 187 +++++++++++++++++++++++++++ sidecar/test/settings.test.mjs | 78 +++++++++++ ui/src/bus.jsx | 14 +- ui/src/projects.jsx | 14 +- 10 files changed, 415 insertions(+), 21 deletions(-) create mode 100644 sidecar/test/legacy-restore.test.mjs diff --git a/README.md b/README.md index f1c24ac6ce..5e96dbf406 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ npm run build:ui node --test sidecar/test/*.test.mjs ``` -Windows 调试:先运行 `scripts/build-desktop.cmd`,然后 `npm run dev:desktop`。脚本使用 `.tmp/desktop-appdata/WebDecryptHub` 保存开发聊天,与日常数据分开。开发模式需要 Node 在 PATH 中。 +Windows 调试:先运行 `scripts/build-desktop.cmd`,然后 `npm run dev:desktop`。脚本使用产品正式数据目录 `%APPDATA%\DecryptHub`,与安装版共用同一份对话;需要隔离调试时显式设 `DECRYPTHUB_DATA_DIR` 为绝对路径。开发模式需要 Node 在 PATH 中。 macOS 源码开发与串流验证见 [Mac 开发说明](docs/macos-development.md)。目前只验证 Apple Silicon 源码路径,不代表已有正式 Mac 安装包或原生浏览器嵌入支持。 @@ -43,6 +43,6 @@ node scripts/check-sidecar.mjs IDH / ADH 已通过各自官方 CLI/MCP 网关接入插件中心,支持版本检查、下载、校验、配置和启停;Python 3.10+ 及设备插件/Host 服务由用户准备。详见 [插件管理](docs/plugins.md)。 -旧桌面应用的应用标识、凭据库和默认 `WebDecryptHub` 数据目录暂时保留,以兼容已有配置与会话。产品名称和更新源改为 DecryptHub;网页分析项目保留 WebDecryptHub 名称。 +旧桌面应用的应用标识和凭据库暂时保留,以兼容已有配置;数据目录已改为产品名 `%APPDATA%\DecryptHub`(旧的 `WebDecryptHub` 目录会在启动时自动整体迁移)。产品名称和更新源为 DecryptHub;网页分析项目保留 WebDecryptHub 名称。 MIT。源自 decrypthub/WebDecryptHub 的桌面开发快照,原始仓库和用户未提交的工作保持不变。 diff --git a/scripts/dev-desktop.ps1 b/scripts/dev-desktop.ps1 index 0e5d8b3ed4..11413ef9f1 100644 --- a/scripts/dev-desktop.ps1 +++ b/scripts/dev-desktop.ps1 @@ -44,7 +44,9 @@ if (-not (Test-Port $vitePort)) { $before = @{ Node = $env:JSRA_SIDECAR_NODE; AppData = $env:DECRYPTHUB_DATA_DIR; DevUrl = $env:JSRA_UI_DEV_URL; Community = $env:DECRYPTHUB_COMMUNITY_URL } try { $env:JSRA_SIDECAR_NODE = $sidecarEntry - $env:DECRYPTHUB_DATA_DIR = Join-Path $root '.tmp\desktop-appdata\WebDecryptHub' + # 开发版默认也用产品正式数据目录,避免「同一个软件换个入口就是另一份空工作台」。 + # 需要与日常数据隔离时显式传 DECRYPTHUB_DATA_DIR=<绝对路径>。 + if (-not $env:DECRYPTHUB_DATA_DIR) { $env:DECRYPTHUB_DATA_DIR = Join-Path $env:APPDATA 'DecryptHub' } $env:JSRA_UI_DEV_URL = "http://127.0.0.1:$vitePort/" # DECRYPTHUB_COMMUNITY_URL 只影响 debug 构建;留空则连生产社区 decrypthub.cn。 # 连测试服:$env:DECRYPTHUB_COMMUNITY_URL = 'https://decrypthub.taisuii.cn' diff --git a/scripts/start-desktop.ps1 b/scripts/start-desktop.ps1 index dcad66483b..1dd2265d60 100644 --- a/scripts/start-desktop.ps1 +++ b/scripts/start-desktop.ps1 @@ -1,4 +1,4 @@ -# Launch the locally built Tauri app with the current sidecar source. +# Launch the locally built Tauri app with the current sidecar source. # Keep this file ASCII for Windows PowerShell 5.1 without a UTF-8 BOM. param([string]$BinaryPath) $ErrorActionPreference = 'Stop' @@ -26,7 +26,8 @@ $desktopOldEntry = $env:JSRA_SIDECAR_NODE $desktopOldAppData = $env:DECRYPTHUB_DATA_DIR try { $env:JSRA_SIDECAR_NODE = $desktopEntry - $env:DECRYPTHUB_DATA_DIR = Join-Path $desktopRoot '.tmp\desktop-appdata\WebDecryptHub' + # 与正式版共用同一个产品数据目录(以前指向 .tmp,导致两份对话互不可见)。 + if (-not $env:DECRYPTHUB_DATA_DIR) { $env:DECRYPTHUB_DATA_DIR = Join-Path $env:APPDATA 'DecryptHub' } $desktopProcess = Start-Process -FilePath $desktopBinary -WorkingDirectory $desktopRoot -WindowStyle Hidden -PassThru ` -RedirectStandardOutput (Join-Path $desktopLogs 'desktop-stdout.log') ` -RedirectStandardError (Join-Path $desktopLogs 'desktop-stderr.log') diff --git a/sidecar/index.mjs b/sidecar/index.mjs index abf97ebb4a..c474032477 100644 --- a/sidecar/index.mjs +++ b/sidecar/index.mjs @@ -125,8 +125,9 @@ async function startServer() { 'mcp-restart': async a => { await mcpHost.restart(String(a?.name || '')); return mcpHost.status(); }, 'mcp-save': a => extensions.saveMcp(a?.servers || {}, a?.approveNames || []), 'projects-list': () => sessions.projects.list(), - // 没有项目归属的历史会话:只报告,不自动处理。删除必须由用户在界面上明确选择。 + // 没有项目归属的历史会话:只报告,不自动处理。恢复/删除都必须由用户在界面上明确选择。 'legacy-sessions': () => sessions.legacySessions(), + 'legacy-sessions-restore': a => sessions.restoreLegacySessions(a?.ids), 'legacy-sessions-discard': a => sessions.discardLegacySessions(a?.ids), 'project-save': a => projects.save(a.project || {}, a.scope || a.sessionId), 'projects-check': () => projects.checkDirectories(), diff --git a/sidecar/sessions.mjs b/sidecar/sessions.mjs index ca828f6732..40ab8272a1 100644 --- a/sidecar/sessions.mjs +++ b/sidecar/sessions.mjs @@ -574,15 +574,17 @@ export class SessionManager { this.sessions = new Map(); this.focusedId = null; this.seq = 0; this.stateFile = path.join(userDataDir, 'sessions.json'); // 无项目归属的历史会话:不恢复、不自动迁移,也不从索引里抹掉。 - // 它们属于「项目」概念出现之前的数据;是否删除由用户在界面上明确决定 - // (见 UI 的 legacy-sessions 提示与下面的 discardLegacySessions)。 + // 它们属于「项目」概念出现之前的数据;是否恢复或删除由用户在界面上明确决定 + // (见 UI 的 legacy-sessions 提示与下面的 restoreLegacySessions / discardLegacySessions)。 // 这里只是把它们原样留在索引里,避免 emitList 写盘时顺手把用户数据写成「已删除」。 this.legacyEntries = []; // 恢复上次的会话标签(标题、最后访问的网址、对话上下文;浏览器按需再启动) let saved = null; try { saved = JSON.parse(fs.readFileSync(this.stateFile, 'utf8')); } catch {} + const indexed = new Set(); if (saved?.sessions?.length) { for (const x of saved.sessions.slice(0, MAX_SESSIONS)) { if (!/^(?:main|s(?:[0-9a-f]{6}|[0-9a-f]{32}))$/.test(x.id) || !!x.primary !== (x.id === 'main')) throw Error('会话索引身份无效'); + indexed.add(x.id); const stateFile = path.join(userDataDir, 'projects', x.primary ? 'default' : x.id, '.agent-state.json'); let state = null; try { state = JSON.parse(fs.readFileSync(stateFile, 'utf8')); } catch {} if (!state?.projectId) { this.legacyEntries.push({ ...x }); continue; } @@ -592,16 +594,108 @@ export class SessionManager { if (!this.focusedId) this.focusedId = this.sessions.values().next().value?.id || null; this.seq = Math.max(this.seq, saved.seq || 0); } + this.adoptOrphans(indexed); + } + /** + * 把「磁盘上有数据目录、索引里却没有」的会话收进历史会话列表。 + * 这类会话比没有 projectId 的更隐蔽:它不在索引里,所以既不会被恢复, + * 也不会出现在删除提示里——用户完全看不到它存在。只收有 .agent-history.json + * (真有对话)的目录,避免把空壳目录也列出来。 + */ + adoptOrphans(indexed) { + let names = []; + try { names = fs.readdirSync(path.join(this.userDataDir, 'projects'), { withFileTypes: true }).filter(d => d.isDirectory()).map(d => d.name); } catch { return; } + for (const name of names) { + if (indexed.has(name) || this.legacyEntries.some(x => x.id === name)) continue; + if (!/^(?:main|s(?:[0-9a-f]{6}|[0-9a-f]{32}))$/.test(name)) continue; + const dir = path.join(this.userDataDir, 'projects', name); + if (!fs.existsSync(path.join(dir, '.agent-history.json'))) continue; + let state = null; try { state = JSON.parse(fs.readFileSync(path.join(dir, '.agent-state.json'), 'utf8')); } catch {} + this.legacyEntries.push({ + id: name, title: '', primary: name === 'main', updatedAt: 0, pinned: false, orphan: true, + }); + } } /** 等待用户决定如何处理的历史会话(项目概念之前创建、没有 projectId)。 */ legacySessions() { - return this.legacyEntries.map(x => ({ - id: x.id, - title: String(x.title || x.id || ''), - primary: !!x.primary, - updatedAt: Number(x.updatedAt) || 0, - url: String(x.url || ''), - })); + return this.legacyEntries.map(x => { + // restorable 只表示「结构上能接回当前模型」,不代表一定能成功;真正裁决在 restoreLegacySessions。 + const stateFile = path.join(this.userDataDir, 'projects', x.primary ? 'default' : x.id, '.agent-state.json'); + let state = null; try { state = JSON.parse(fs.readFileSync(stateFile, 'utf8')); } catch {} + const ws = state?.workspace || {}; + const hasProject = !!(state?.projectId && this.projects.entries.some(p => p.id === state.projectId)); + return { + id: x.id, + title: String(x.title || this.orphanTitle(x.id) || x.id || ''), + primary: !!x.primary, + updatedAt: Number(x.updatedAt) || this.historyMtime(x.id), + url: String(x.url || ''), + kind: ws.kind === 'managed' ? 'managed' : 'folder', + hasProject, + restorable: hasProject || !!(ws.kind === 'managed' ? ws.id : ws.root), + }; + }); + } + /** 没有索引条目的孤儿会话没有标题,用第一条用户消息代替 id,至少让人认得出是哪段对话。 */ + orphanTitle(id) { + try { + const raw = JSON.parse(fs.readFileSync(path.join(this.userDataDir, 'projects', id, '.agent-history.json'), 'utf8')); + const first = (raw.events || []).find(e => e?.t === 'user' && typeof e.content === 'string' && e.content.trim() && !e.content.startsWith('【')); + const text = String(first?.content || '').replace(/【[^】]*】[\s\S]*$/, '').replace(/\s+/g, ' ').trim(); + if (text) return text.slice(0, 40); + } catch {} + return ''; + } + historyMtime(id) { + try { return fs.statSync(path.join(this.userDataDir, 'projects', id, '.agent-history.json')).mtimeMs; } catch { return 0; } + } + /** + * 把用户明确要求保留的历史会话接回当前模型(不删除任何东西)。 + * 两条路径: + * - 已有合法 projectId 且项目还在 → 只把会话补回索引(原先"关闭的标签"重新出现)。 + * - 没有 projectId → 为它建一个只含单个目录的项目: + * 托管工作区改指当前数据目录下的同名目录(旧版本可能记着另一个安装路径); + * 用户文件夹必须仍然存在,否则拒绝并报告原因。 + * 逐条独立处理:一条失败不影响其它,也绝不写坏已成功的索引。 + */ + async restoreLegacySessions(ids) { + const wanted = new Set((Array.isArray(ids) ? ids : []).map(String)); + const restored = [], skipped = []; + for (const entry of this.legacyEntries) { + if (!wanted.has(entry.id)) continue; + const stateFile = path.join(this.userDataDir, 'projects', entry.primary ? 'default' : entry.id, '.agent-state.json'); + let state = null; try { state = JSON.parse(fs.readFileSync(stateFile, 'utf8')); } catch {} + if (!state) { skipped.push({ id: entry.id, title: entry.title, reason: '会话状态文件缺失,无法确认工作区' }); continue; } + try { + const projectId = this.ensureProjectFor(entry, state); + atomicJson(stateFile, { ...state, projectId }); + this.create({ id: entry.id, title: entry.title, updatedAt: entry.updatedAt, pinned: entry.pinned, quiet: true, projectId }); + this.legacyEntries = this.legacyEntries.filter(x => x.id !== entry.id); + restored.push({ id: entry.id, title: entry.title, projectId }); + } catch (error) { skipped.push({ id: entry.id, title: entry.title, reason: error.message }); } + } + if (restored.length) this.emitList(); + return { restored, skipped }; + } + /** 历史会话要接回当前模型,必须先有一个项目;已有合法项目就复用。 */ + ensureProjectFor(entry, state) { + if (state.projectId && this.projects.entries.some(p => p.id === state.projectId)) return state.projectId; + const ws = state.workspace || {}; + const managed = ws.kind === 'managed'; + // 托管工作区永远是数据目录下的 projects/<会话 id>/workspace:跟着数据目录走,不保留旧安装路径。 + const root = managed ? path.join(this.userDataDir, 'projects', entry.id, 'workspace') : ws.root; + if (!root) throw Error('会话缺少工作区信息,无法恢复'); + if (managed) fs.mkdirSync(root, { recursive: true }); + else { + let st = null; try { st = fs.statSync(root); } catch {} + if (!st?.isDirectory()) throw Error('原工作文件夹已不存在:' + root); + if (pathKey(fs.realpathSync.native(this.userDataDir)) === pathKey(fs.realpathSync.native(root)) || root.startsWith(this.userDataDir + path.sep)) + throw Error('工作区位于应用数据目录内,不能作为代码工作区'); + } + const folder = { id: ws.id || crypto.randomUUID(), kind: managed ? 'managed' : 'folder', root, revision: 1, label: ws.label || '恢复的会话' }; + const title = String(entry.title || entry.id || '').trim() || entry.id; + const project = this.projects.save({ name: ('恢复:' + title).slice(0, 80), folders: [folder], primaryId: folder.id }); + return project.id; } /** * 删除用户明确要求清理的历史会话。 diff --git a/sidecar/settings.mjs b/sidecar/settings.mjs index e7aaacb73c..25e154146d 100644 --- a/sidecar/settings.mjs +++ b/sidecar/settings.mjs @@ -9,6 +9,11 @@ import { normalizeThinking, ALL_LEVELS } from './thinking.mjs'; // Chrome for Testing 不再作为选项:load 与 save 都归一到这里,旧的 settings.json 会被静默迁移。 export const KERNEL = 'cloak'; +// 应用数据目录名 = 产品名。不要写成 WebDecryptHub:那是浏览器组件 WDH 的仓库名,不是本产品。 +export const DATA_DIR_NAME = 'DecryptHub'; +// 旧目录名,按从新到旧排列;只在 DATA_DIR_NAME 不存在时逐个前移迁移。 +export const LEGACY_DATA_DIR_NAMES = ['WebDecryptHub', 'JSReverseAgent']; + const DEFAULTS = { provider: 'openai', openai: { baseUrl: 'https://api.openai.com/v1', apiKey: '', model: 'gpt-4o' }, @@ -36,9 +41,13 @@ export function userDataDir() { const base = process.platform === 'win32' ? (process.env.APPDATA || os.homedir()) : process.platform === 'darwin' ? path.join(os.homedir(), 'Library', 'Application Support') : (process.env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config')); - const d = path.join(base, 'WebDecryptHub'); - const legacy = path.join(base, 'JSReverseAgent'); - try { if (!fs.existsSync(d) && fs.existsSync(legacy)) fs.renameSync(legacy, d); } catch {} + // 产品正式名是 DecryptHub。目录名历史上的演变是 JSReverseAgent → WebDecryptHub → DecryptHub, + // 每次只往前挪一格,且只在目标不存在时搬,避免把用户刚建的空目录当成"已迁移"而丢数据。 + const d = path.join(base, DATA_DIR_NAME); + for (const name of LEGACY_DATA_DIR_NAMES) { + const legacy = path.join(base, name); + try { if (!fs.existsSync(d) && fs.existsSync(legacy)) fs.renameSync(legacy, d); } catch {} + } fs.mkdirSync(d, { recursive: true }); return d; } diff --git a/sidecar/test/legacy-restore.test.mjs b/sidecar/test/legacy-restore.test.mjs new file mode 100644 index 0000000000..51ba6d48fc --- /dev/null +++ b/sidecar/test/legacy-restore.test.mjs @@ -0,0 +1,187 @@ +// 历史会话(项目概念之前创建、没有 projectId)的恢复: +// 这些数据在界面上既不可见也不能删,只能靠 legacy-sessions 系列 RPC 处理。 +// 恢复必须做到:不丢记录、不改坏索引、逐条独立失败。 +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 { SessionManager } from '../sessions.mjs'; + +function tmpRoot(t, prefix) { + const root = fs.mkdtempSync(path.join(os.tmpdir(), prefix)); + t.after(() => { if (path.dirname(root) === os.tmpdir()) fs.rmSync(root, { recursive: true, force: true }); }); + return root; +} + +/** 造一份「项目概念之前」的数据:索引里有条目,但 .agent-state.json 没有 projectId */ +function seedLegacy(app, { id, title, workspace, history = [{ t: 'user', content: 'old conversation' }], projectId = null }) { + const dir = path.join(app, 'projects', id); + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync(path.join(dir, '.agent-state.json'), JSON.stringify({ mode: 'standard', review: 'manual', todos: [], workspace, projectId })); + fs.writeFileSync(path.join(dir, '.agent-history.json'), JSON.stringify({ v: 2, events: history })); + const file = path.join(app, 'sessions.json'); + const saved = fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : { focused: null, seq: 0, sessions: [] }; + saved.sessions.push({ id, title, primary: false, updatedAt: 1793000000000, pinned: false }); + fs.writeFileSync(file, JSON.stringify(saved)); + return dir; +} + +const settings = { openai: { apiKey: 'fixture', model: 'test' }, mcpServers: {} }; +function manager(app) { return new SessionManager({ userDataDir: app, getSettings: () => settings, broadcast() {}, chromeMod: {} }); } + +test('托管工作区的历史会话:恢复后重新出现在索引里,对话记录原样保留', async t => { + const root = tmpRoot(t, 'dh-legacy-managed-'), app = path.join(root, 'app'); + // 旧版本会把工作区记成另一个安装路径;恢复时必须改指当前数据目录,而不是继续指向那个不存在的路径 + const staleRoot = path.join(root, 'old-checkout', 'projects', 'saa0001', 'workspace'); + seedLegacy(app, { id: 'saa0001', title: '老的小红书分析', workspace: { id: 'managed-saa0001', kind: 'managed', root: staleRoot, revision: 1, label: '会话工作区' } }); + + const first = manager(app); + try { + assert.equal(first.sessions.size, 0, '无 projectId 的历史会话不应被自动载入'); + assert.equal(first.legacySessions().length, 1); + assert.equal(first.legacySessions()[0].kind, 'managed'); + assert.equal(first.legacySessions()[0].restorable, true); + + const result = await first.restoreLegacySessions(['saa0001']); + assert.deepEqual(result.skipped, []); + assert.equal(result.restored.length, 1); + assert.equal(first.sessions.size, 1, '恢复后应立刻回到会话表'); + assert.equal(first.legacySessions().length, 0, '恢复过的不该继续算历史会话'); + // 工作区必须落在当前数据目录下,并真的建出来 + assert.equal(first.get('saa0001').workspace.root, path.join(app, 'projects', 'saa0001', 'workspace')); + assert.equal(fs.existsSync(first.get('saa0001').workspace.root), true); + // 对话事件没被碰过 + const hist = JSON.parse(fs.readFileSync(path.join(app, 'projects', 'saa0001', '.agent-history.json'), 'utf8')); + assert.equal(hist.events[0].content, 'old conversation'); + } finally { await first.closeAll(); } + + // 重启后仍然可见:证明 write 的是持久状态,不是只在内存里恢复 + const second = manager(app); + try { + assert.equal(second.sessions.size, 1); + assert.equal(second.get('saa0001').projectId, first.projects.list()[0].id); + assert.equal(second.legacySessions().length, 0); + } finally { await second.closeAll(); } +}); + +test('用户文件夹工作区的历史会话:文件夹还在就恢复,已删除则明确跳过且不动数据', async t => { + const root = tmpRoot(t, 'dh-legacy-folder-'), app = path.join(root, 'app'); + const alive = path.join(root, 'DH_Project'), gone = path.join(root, 'deleted-folder'); + fs.mkdirSync(alive); + seedLegacy(app, { id: 'sbb0001', title: '武汉游泳馆', workspace: { id: 'f-1', kind: 'folder', root: alive, revision: 1, label: 'DH_Project' } }); + seedLegacy(app, { id: 'sbb0002', title: '已删目录的会话', workspace: { id: 'f-2', kind: 'folder', root: gone, revision: 1, label: 'gone' } }); + + const mgr = manager(app); + try { + const result = await mgr.restoreLegacySessions(['sbb0001', 'sbb0002']); + assert.equal(result.restored.length, 1); + assert.equal(result.restored[0].id, 'sbb0001'); + assert.equal(mgr.get('sbb0001').workspace.root, fs.realpathSync.native(alive)); + // 失败的必须给出可读原因,并且原样留在历史会话里等用户处理 + assert.equal(result.skipped.length, 1); + assert.equal(result.skipped[0].id, 'sbb0002'); + assert.match(result.skipped[0].reason, /不存在/); + assert.equal(mgr.legacySessions().length, 1); + assert.equal(mgr.legacySessions()[0].id, 'sbb0002'); + // 跳过的那条状态文件不能被写脏(projectId 仍为空) + const state = JSON.parse(fs.readFileSync(path.join(app, 'projects', 'sbb0002', '.agent-state.json'), 'utf8')); + assert.equal(state.projectId, null); + } finally { await mgr.closeAll(); } +}); + +test('索引里存在且 projectId 合法时会话正常加载,不会被当成历史会话', async t => { + const root = tmpRoot(t, 'dh-legacy-hasproject-'), app = path.join(root, 'app'); + const folder = path.join(root, 'code'); fs.mkdirSync(folder); + const setup = new SessionManager({ userDataDir: app, getSettings: () => settings, broadcast() {}, chromeMod: {} }); + const entry = setup.workspaces.folder(folder); + const projectId = setup.projects.save({ name: '既有项目', folders: [entry], primaryId: entry.id }).id; + await setup.closeAll(); + + seedLegacy(app, { id: 'scc0001', title: '控制我的浏览器', workspace: { ...entry }, projectId }); + + const mgr = manager(app); + try { + // 关键区分:这类会话不需要「恢复」,构造时就应该直接回到会话表 + assert.equal(mgr.sessions.size, 1); + assert.equal(mgr.get('scc0001').projectId, projectId); + assert.equal(mgr.legacySessions().length, 0, '能正常加载的会话不该出现在历史会话提示里'); + const result = await mgr.restoreLegacySessions(['scc0001']); + assert.deepEqual(result, { restored: [], skipped: [] }, '没有待恢复项,也不能凭空新建项目'); + } finally { await mgr.closeAll(); } +}); + +test('磁盘上有对话但索引里没有的孤儿会话也会被列出来(否则用户永远看不到它)', async t => { + const root = tmpRoot(t, 'dh-legacy-orphan-'), app = path.join(root, 'app'); + const folder = path.join(root, 'code'); fs.mkdirSync(folder); + const setup = new SessionManager({ userDataDir: app, getSettings: () => settings, broadcast() {}, chromeMod: {} }); + const entry = setup.workspaces.folder(folder); + const projectId = setup.projects.save({ name: '既有项目', folders: [entry], primaryId: entry.id }).id; + await setup.closeAll(); + + // 有完整数据目录与合法 projectId,但 sessions.json 里没有它 —— 索引丢失的真实情形 + const dir = path.join(app, 'projects', 'sff0001'); + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync(path.join(dir, '.agent-state.json'), JSON.stringify({ mode: 'standard', workspace: { ...entry }, projectId })); + fs.writeFileSync(path.join(dir, '.agent-history.json'), JSON.stringify({ v: 2, events: [{ t: 'user', content: '帮我查一下武汉游泳馆的票价 【当前状态(应用自动附加)】…' }] })); + // 只有空壳目录、没有对话记录的不该被当成会话 + fs.mkdirSync(path.join(app, 'projects', 'sff0002'), { recursive: true }); + fs.writeFileSync(path.join(app, 'projects', 'sff0002', '.agent-state.json'), JSON.stringify({ mode: 'standard' })); + fs.writeFileSync(path.join(app, 'sessions.json'), JSON.stringify({ focused: null, seq: 1, sessions: [] })); + + const mgr = manager(app); + try { + const list = mgr.legacySessions(); + assert.equal(list.length, 1, '只有带对话记录的目录才算历史会话'); + const [orphan] = list; + assert.equal(orphan.id, 'sff0001'); + // 没有索引条目就没有标题,用第一条用户消息代替裸 id + assert.match(orphan.title, /武汉游泳馆/); + assert.ok(!orphan.title.includes('【'), '应用自动附加的状态块不该混进标题'); + assert.ok(orphan.updatedAt > 0, '没有索引时间戳时用对话文件的修改时间'); + + const result = await mgr.restoreLegacySessions(['sff0001']); + assert.equal(result.restored.length, 1); + assert.equal(mgr.get('sff0001').projectId, projectId); + assert.equal(mgr.legacySessions().length, 0); + } finally { await mgr.closeAll(); } + + // 恢复后必须写进索引,重启仍在 + const again = manager(app); + try { assert.equal(again.sessions.size, 1); assert.equal(again.legacySessions().length, 0); } + finally { await again.closeAll(); } +}); + +test('恢复空列表或未知 id 时不产生任何写入', async t => { + const root = tmpRoot(t, 'dh-legacy-noop-'), app = path.join(root, 'app'); + seedLegacy(app, { id: 'sdd0001', title: '留着', workspace: { id: 'managed-sdd0001', kind: 'managed', root: path.join(app, 'projects', 'sdd0001', 'workspace'), revision: 1 } }); + const mgr = manager(app); + try { + const projectsBefore = mgr.projects.list().length; + assert.deepEqual(await mgr.restoreLegacySessions([]), { restored: [], skipped: [] }); + assert.deepEqual(await mgr.restoreLegacySessions(['does-not-exist']), { restored: [], skipped: [] }); + assert.equal(mgr.projects.list().length, projectsBefore); + assert.equal(mgr.legacySessions().length, 1, '没点名的历史会话必须原样留着'); + } finally { await mgr.closeAll(); } +}); + +test('状态文件缺失的历史会话被跳过而不是让整个恢复失败', async t => { + const root = tmpRoot(t, 'dh-legacy-missing-'), app = path.join(root, 'app'); + seedLegacy(app, { id: 'see0001', title: '正常', workspace: { id: 'managed-see0001', kind: 'managed', root: path.join(app, 'projects', 'see0001', 'workspace'), revision: 1 } }); + // 索引里有、但状态文件被删掉:不能因此抛异常,也不能悄悄当成成功 + fs.mkdirSync(path.join(app, 'projects', 'see0002'), { recursive: true }); + const file = path.join(app, 'sessions.json'); + const saved = JSON.parse(fs.readFileSync(file, 'utf8')); + saved.sessions.push({ id: 'see0002', title: '状态丢失', primary: false, updatedAt: 1793000000000, pinned: false }); + fs.writeFileSync(file, JSON.stringify(saved)); + + const mgr = manager(app); + try { + const result = await mgr.restoreLegacySessions(['see0001', 'see0002']); + assert.equal(result.restored.length, 1); + assert.equal(result.restored[0].id, 'see0001'); + assert.equal(result.skipped.length, 1); + assert.equal(result.skipped[0].id, 'see0002'); + assert.match(result.skipped[0].reason, /缺失|无法确认/); + } finally { await mgr.closeAll(); } +}); diff --git a/sidecar/test/settings.test.mjs b/sidecar/test/settings.test.mjs index 25736b48b7..12a3617564 100644 --- a/sidecar/test/settings.test.mjs +++ b/sidecar/test/settings.test.mjs @@ -94,3 +94,81 @@ test('browserPresentation: macOS 默认串流;停靠模式有头且不串流', assert.deepEqual(mod.browserPresentation({ headless: true, embedMode: 'docked' }, 'darwin', {}), { embed: false, headless: true, dock: false }); assert.deepEqual(mod.browserPresentation({ headless: false, embedMode: 'docked' }, 'win32', {}), { embed: true, headless: false, dock: false }); }); + +/** 清掉 DECRYPTHUB_DATA_DIR,让 userDataDir() 走真实的 APPDATA 分支 */ +async function withBase(fn) { + const prev = { data: process.env.DECRYPTHUB_DATA_DIR, appdata: process.env.APPDATA, xdg: process.env.XDG_CONFIG_HOME }; + delete process.env.DECRYPTHUB_DATA_DIR; + try { return await fn(); } finally { + for (const [k, v] of [['DECRYPTHUB_DATA_DIR', prev.data], ['APPDATA', prev.appdata], ['XDG_CONFIG_HOME', prev.xdg]]) { + if (v === undefined) delete process.env[k]; else process.env[k] = v; + } + } +} + +test('默认数据目录用产品名 DecryptHub,不再叫 WebDecryptHub', async () => { + const base = tmp(); + process.env.APPDATA = base; process.env.XDG_CONFIG_HOME = base; + await withBase(async () => { + const mod = await import(`../settings.mjs?n=${Date.now()}${Math.random()}`); + assert.equal(mod.DATA_DIR_NAME, 'DecryptHub'); + const dir = mod.userDataDir(); + assert.equal(path.basename(dir), 'DecryptHub'); + assert.equal(fs.existsSync(dir), true); + }); +}); + +test('旧 WebDecryptHub 数据目录会被整体迁移到 DecryptHub(设置与会话都不丢)', async () => { + const base = tmp(); + process.env.APPDATA = base; process.env.XDG_CONFIG_HOME = base; + const legacy = path.join(base, 'WebDecryptHub'); + fs.mkdirSync(path.join(legacy, 'projects', 'main'), { recursive: true }); + fs.writeFileSync(path.join(legacy, 'settings.json'), JSON.stringify({ headless: true, openai: { model: 'kept-model' } })); + fs.writeFileSync(path.join(legacy, 'sessions.json'), JSON.stringify({ focused: 'main', sessions: [{ id: 'main', primary: true }] })); + fs.writeFileSync(path.join(legacy, 'projects', 'main', '.agent-history.json'), '{"events":[]}'); + await withBase(async () => { + const mod = await import(`../settings.mjs?n=${Date.now()}${Math.random()}`); + const dir = mod.userDataDir(); + assert.equal(path.basename(dir), 'DecryptHub'); + // 数据跟着搬过去,不是新建空目录 + assert.equal(JSON.parse(fs.readFileSync(path.join(dir, 'settings.json'), 'utf8')).openai.model, 'kept-model'); + assert.equal(fs.existsSync(path.join(dir, 'sessions.json')), true); + assert.equal(fs.existsSync(path.join(dir, 'projects', 'main', '.agent-history.json')), true); + assert.equal(fs.existsSync(legacy), false, '旧目录必须整体改名,不能留在原地'); + assert.equal(mod.load().headless, true); + }); +}); + +test('DecryptHub 已存在时不会被旧的 WebDecryptHub 覆盖', async () => { + const base = tmp(); + process.env.APPDATA = base; process.env.XDG_CONFIG_HOME = base; + const current = path.join(base, 'DecryptHub'); + fs.mkdirSync(current, { recursive: true }); + fs.writeFileSync(path.join(current, 'settings.json'), JSON.stringify({ openai: { model: 'new-model' } })); + const legacy = path.join(base, 'WebDecryptHub'); + fs.mkdirSync(legacy, { recursive: true }); + fs.writeFileSync(path.join(legacy, 'settings.json'), JSON.stringify({ openai: { model: 'stale-model' } })); + await withBase(async () => { + const mod = await import(`../settings.mjs?n=${Date.now()}${Math.random()}`); + const dir = mod.userDataDir(); + assert.equal(path.basename(dir), 'DecryptHub'); + assert.equal(mod.load().openai.model, 'new-model', '已有新目录时旧目录只能当遗留,不能顶掉它'); + assert.equal(fs.existsSync(legacy), true, '旧目录保持原样,等用户自己决定'); + }); +}); + +test('更早的 JSReverseAgent 目录也能一路迁移到 DecryptHub', async () => { + const base = tmp(); + process.env.APPDATA = base; process.env.XDG_CONFIG_HOME = base; + const ancient = path.join(base, 'JSReverseAgent'); + fs.mkdirSync(ancient, { recursive: true }); + fs.writeFileSync(path.join(ancient, 'settings.json'), JSON.stringify({ openai: { model: 'ancient-model' } })); + await withBase(async () => { + const mod = await import(`../settings.mjs?n=${Date.now()}${Math.random()}`); + const dir = mod.userDataDir(); + assert.equal(path.basename(dir), 'DecryptHub'); + assert.equal(mod.load().openai.model, 'ancient-model'); + assert.equal(fs.existsSync(ancient), false); + }); +}); + diff --git a/ui/src/bus.jsx b/ui/src/bus.jsx index ea80377165..7005f9b9ec 100644 --- a/ui/src/bus.jsx +++ b/ui/src/bus.jsx @@ -218,6 +218,18 @@ export function Workbench({ children }) { // 历史会话(无项目归属)在启动时清点一次。它们是本地残留数据,不做任何自动处理。 useEffect(() => { api.invoke('legacy-sessions').then(v => setLegacySessions(Array.isArray(v) ? v : [])).catch(() => {}); }, []); + const restoreLegacySessions = useCallback(async ids => { + try { + const r = await api.invoke('legacy-sessions-restore', { ids }); + const done = (r?.restored || []).map(x => x.id); + setLegacySessions(list => list.filter(x => !done.includes(x.id))); + const skipped = r?.skipped || []; + if (done.length) toast(`已恢复 ${done.length} 个历史会话`, 'ok'); + // 跳过是逐条原因不同的:一次列出来,别让用户以为全都恢复了。 + if (skipped.length) toast('未恢复:' + skipped.map(x => `${x.title || x.id}(${x.reason})`).join(';'), 'warn', 9000); + return r; + } catch (e) { toast('恢复失败:' + e.message, 'err'); return null; } + }, []); const discardLegacySessions = useCallback(async ids => { try { const r = await api.invoke('legacy-sessions-discard', { ids }); @@ -671,7 +683,7 @@ export function Workbench({ children }) { projects, setProjects, projectFilter, setProjectFilter, projectEditor, setProjectEditor, moveSession, setMoveSession, workspacePrompt, setWorkspacePrompt, isCurrentSession: id => sidRef.current === id, commandForm, setCommandForm, extensionBrowser, setExtensionBrowser, automationDraft, setAutomationDraft, - legacySessions, discardLegacySessions, + legacySessions, restoreLegacySessions, discardLegacySessions, commandFeedback: commandFeedback[sid], clearCommandFeedback: () => setCommandFeedback(m => ({ ...m, [sid]: null })), settings, saveSettings, setSettings, firstRun, setFirstRun, sessions, sid, session, cur, dispatch, focusSession, diff --git a/ui/src/projects.jsx b/ui/src/projects.jsx index 317812831f..d07596eb92 100644 --- a/ui/src/projects.jsx +++ b/ui/src/projects.jsx @@ -107,12 +107,13 @@ export function ProjectDialogs() { /** * 项目概念之前留下的历史会话(没有 projectId)。 - * 它们是本地残留数据,产品不做自动迁移,也不替用户删——这里只如实报告并询问。 + * 它们是本地残留数据,产品不做自动迁移,也不替用户删——这里如实报告,并让用户选择恢复或删除。 */ function LegacySessionsNotice() { const w = useWorkbench(), [busy, setBusy] = useState(false), [dismissed, setDismissed] = useState(false); const list = w.legacySessions || []; if (!list.length || dismissed) return null; + const restorable = list.filter(s => s.restorable !== false); const names = list.slice(0, 3).map(s => `「${s.title || s.id}」`).join('、'); const more = list.length > 3 ? ` 等 ${list.length} 个` : ''; const remove = async () => { @@ -121,16 +122,25 @@ function LegacySessionsNotice() { setBusy(false); if (ok) setDismissed(true); }; + const restore = async () => { + setBusy(true); + // 恢复后列表里剩下的就是恢复失败的,保留弹窗让用户看见原因。 + const r = await w.restoreLegacySessions(list.map(s => s.id)); + setBusy(false); + if (r && !(r.skipped || []).length) setDismissed(true); + }; return { if (!open && !busy) setDismissed(true); }}> 历史会话没有项目归属 找到 {list.length} 个创建于「项目」功能之前的会话:{names}{more}。它们不会被载入,也不会被自动迁移或删除。 + 「恢复到会话列表」会为它们建立项目归属,之后可以正常打开查看。
删除会同时清理这些会话的记录、附件和浏览器数据;目录与源码文件不受影响。
- + +
; From 8ff265747d7386dd2d4510b10ba6836c0626d213 Mon Sep 17 00:00:00 2001 From: taisuii <93462725+taisuii@users.noreply.github.com> Date: Mon, 2 Nov 2026 12:05:00 +0800 Subject: [PATCH 2/7] =?UTF-8?q?desktop:=20=E6=80=9D=E8=80=83=E6=A1=A3?= =?UTF-8?q?=E4=BD=8D=E6=94=AF=E6=8C=81=E6=96=B9=E5=90=91=E9=94=AE=E4=B8=8E?= =?UTF-8?q?=20roving=20tabindex?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 档位条此前只有鼠标能可靠操作,键盘用户 Tab 进来后不知道焦点在哪。 现在走 roving tabindex:Tab 进组只落在当前档(没选就落第一档), ← → 在段间移动并立即生效;每段是真按钮, 读屏读到的是「思考强度 中,单选按钮,已选中」而不是一个说不出值的容器。 --- scripts/check-thinking-ui.mjs | 10 ++++++---- ui/src/app.css | 6 ++---- ui/src/thinking-picker.jsx | 28 +++++++++++++++++++++------- 3 files changed, 29 insertions(+), 15 deletions(-) diff --git a/scripts/check-thinking-ui.mjs b/scripts/check-thinking-ui.mjs index 63bab85191..29be74c978 100644 --- a/scripts/check-thinking-ui.mjs +++ b/scripts/check-thinking-ui.mjs @@ -79,7 +79,7 @@ await new Promise(r => srv.listen(PORT, '127.0.0.1', r)); const { chromium } = await import('../node_modules/@zhizhuodemao/patchright/index.mjs'); const browser = await chromium.launch({ headless: true, executablePath: CHROME }); -const context = await browser.newContext({ viewport: { width: 1440, height: 900 }, colorScheme: 'dark' }); +const context = await browser.newContext({ viewport: { width: 1440, height: 900 }, colorScheme: process.env.JSRA_UI_SCHEME || 'dark' }); const page = await context.newPage(); const pageErrors = []; page.on('pageerror', e => pageErrors.push(e.message)); @@ -141,12 +141,14 @@ try { ok(/reasoning_effort: high/.test(payloadHigh), '高对应 reasoning_effort: high(实际 ' + JSON.stringify(payloadHigh) + ')'); await page.keyboard.press('Escape'); - // 4) 键盘可达:聚焦档位条后按 Home/ArrowRight 也能改档 + // 4) 键盘可达:焦点落在当前档那一段上,Home/ArrowRight/End 也能改档 // 注意必须重新打开浮层——上一步按 Escape 已经把它卸载,对已卸载节点 focus() 不会生效。 await trigger.click(); await page.locator('.seat-pop').waitFor({ timeout: 8000 }); - const bar = page.locator('.seat-pop .thinking-steps'); - await bar.focus(); + const currentStep = page.locator('.seat-pop .thinking-steps .thinking-step.on'); + ok(await currentStep.count() === 1, '当前档应恰好有一段标 on(实际 ' + await currentStep.count() + ')'); + await currentStep.focus(); + ok(await page.evaluate(() => document.activeElement?.getAttribute('role') === 'radio'), '档位条应把焦点交给当前档那一段'); await page.keyboard.press('Home'); await page.waitForTimeout(300); ok(readSettings().activeThinking === 'off', 'Home 应选中第一档关闭(实际 ' + JSON.stringify(readSettings().activeThinking) + ')'); diff --git a/ui/src/app.css b/ui/src/app.css index 6cf7d97746..d1412dfa83 100644 --- a/ui/src/app.css +++ b/ui/src/app.css @@ -256,7 +256,6 @@ kbd { font-family: var(--default-font-family); font-size: 10px; font-weight: 400 .thinking-reset { display: inline-flex; flex: 0 0 auto; align-items: center; justify-content: center; width: 24px; height: 24px; padding: 0; border: 0; border-radius: 7px; background: transparent; color: var(--subtle); cursor: pointer; } .thinking-reset:hover { background: var(--hover); color: var(--ink); } .thinking-level { min-width: 0; font-size: 24px; font-weight: 600; letter-spacing: -0.02em; color: var(--brand-text); line-height: 1.25; } -.thinking-level.muted { font-size: 15px; font-weight: 500; color: var(--muted); } /* 模型行:设计图里档位名下方那行「模型名 + 箭头」,点它钻取到模型目录 */ .seat-modelrow { display: flex; align-items: center; gap: 4px; max-width: 100%; margin-top: 2px; padding: 2px 4px 2px 0; border: 0; border-radius: 6px; background: transparent; color: var(--muted); font: inherit; font-size: 12px; cursor: pointer; } @@ -284,14 +283,13 @@ kbd { font-family: var(--default-font-family); font-size: 10px; font-weight: 400 /* 档位条:一张 N 段进度条,段与段之间留缝,每一段就是一个档位。 没有把手、没有「拖到中间」的可能;已过的段用淡色表示进度,当前段实色。 */ -.thinking-steps { display: flex; gap: 4px; margin: 14px 0 0; border-radius: 8px; } -.thinking-steps:focus-visible { outline: 2px solid var(--accent-9); outline-offset: 4px; } +.thinking-steps { display: flex; gap: 4px; margin: 14px 0 0; } .thinking-step { flex: 1 1 0; min-width: 0; display: flex; flex-direction: column; gap: 7px; padding: 2px 0; border: 0; background: transparent; color: var(--subtle); font: inherit; cursor: pointer; } .thinking-step-bar { display: block; height: 6px; border-radius: 3px; background: var(--line-strong); transition: background .14s ease, opacity .14s ease; } .thinking-step-name { font-size: 10px; line-height: 1.2; text-align: center; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .thinking-step:not(.on):not(.done):hover .thinking-step-bar { background: var(--muted); } /* 已过的段是「进度」,当前段是「档位」:前者淡、后者实,一眼能看出停在第几档 */ -.thinking-step.done .thinking-step-bar { background: var(--brand-text); opacity: .4; } +.thinking-step.done .thinking-step-bar { background: var(--brand-text); opacity: .5; } .thinking-step.done .thinking-step-name { color: var(--muted); } .thinking-step.on .thinking-step-bar { background: var(--brand-text); } .thinking-step.on .thinking-step-name { color: var(--ink); font-weight: 500; } diff --git a/ui/src/thinking-picker.jsx b/ui/src/thinking-picker.jsx index fe635b03d1..1aec9c1f16 100644 --- a/ui/src/thinking-picker.jsx +++ b/ui/src/thinking-picker.jsx @@ -126,10 +126,22 @@ export function LevelSlider({ levels, value, onChange, label = '默认强度', d // 所以这里基于「刚刚提交的值」推算,而不是等重渲染。 const pending = useRef(value); pending.current = value; + // 焦点走 roving tabindex:Tab 进组只落在当前档(没选就落第一档),← → 在段间移动并立即生效。 + // 每段是真按钮,读屏读到的是「思考强度 中,单选按钮,已选中」,而不是一个说不出值的容器。 + const stepsRef = useRef(null); + const wantFocus = useRef(-1); + useEffect(() => { + const at = wantFocus.current; + if (at < 0) return; + wantFocus.current = -1; + stepsRef.current?.querySelectorAll('.thinking-step')[at]?.focus(); + }, [value]); const keydown = event => { const last = list.length - 1; - const at = indexOf(list, pending.current); - const delta = { ArrowRight: 1, ArrowUp: 1, ArrowLeft: -1, ArrowDown: -1 }[event.key]; + // 连续按键时 props 还没回流:按「刚刚提交的值」算起点,否则 Home 之后紧跟 ArrowRight 会停在原地。 + const seen = indexOf(list, pending.current); + const at = seen >= 0 ? seen : 0; + const delta = { ArrowRight: 1, ArrowDown: 1, ArrowLeft: -1, ArrowUp: -1 }[event.key]; let next; if (event.key === 'Home') next = 0; else if (event.key === 'End') next = last; @@ -137,12 +149,14 @@ export function LevelSlider({ levels, value, onChange, label = '默认强度', d else return; event.preventDefault(); const target = list[next]; - if (target === pending.current) return; - pending.current = target; - onChange(target); + if (target === undefined) return; + wantFocus.current = next; + if (target !== pending.current) { pending.current = target; onChange(target); } + else stepsRef.current?.querySelectorAll('.thinking-step')[next]?.focus(); }; - return
- {list.map((id, index) => - {hasEffort && <> - - {payload} - } + {hasEffort && } {!hasEffort && 该模型没有声明思考强度:请求里不会带思考参数,由端点自行决定。}
} From 7537f2c49b673285aeb2788b93dc91b129c63bc3 Mon Sep 17 00:00:00 2001 From: taisuii <93462725+taisuii@users.noreply.github.com> Date: Mon, 2 Nov 2026 12:26:12 +0800 Subject: [PATCH 4/7] =?UTF-8?q?docs:=20=E8=A1=A5=E5=85=85=E8=AE=BE?= =?UTF-8?q?=E8=AE=A1=E5=8F=82=E8=80=83=E3=80=81check:ui=20=E5=81=87?= =?UTF-8?q?=E7=BA=A2=E4=B8=8E=20UI=20=E4=B8=8D=E9=9C=B2=E5=AD=97=E6=AE=B5?= =?UTF-8?q?=E5=90=8D=E4=B8=89=E6=9D=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 设计分歧先看 ../deepseek-harness/(只读参考),尤其不要发明 DSH 里不存在的概念 - 本机 check:ui 在 .screen-canvas 上的超时是已知假红:多标签浏览器那段没先判断 kernelMissing,本机缺组件时照样去开浏览器。看到它先查 kernel-info 再怀疑自己的改动 - UI 里不出现 reasoning_effort / budget_tokens / thinking.type 等适配器字段名, 协议差异在适配器内部解决 --- AGENTS.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index d32707d86f..8ac3260656 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,6 +2,8 @@ 先读 `docs/component-architecture.md`、`docs/browser-architecture.md`、`docs/security.md` 和与当前改动相关的设计文档。历史文档中的审计问题需要核对当前代码,不直接当作现状。 +**设计决策先看 DeepSeek Harness。** 遇到「这个界面/交互该怎么设计」的分歧时,先去 `../deepseek-harness/` 读对应模块(`packages/client/ui-*`)怎么做的,再动手。它是外部参考项目(DeepSeek 官方开源,MIT),**只读、不改动**;参考的是信息架构与交互取舍,不复制标识与源码。**尤其不要发明 DSH 里不存在的概念**:`AGENTS.md` 之外最典型的反例是「让用户在界面上挑适配器字段名」(`reasoning_effort` / `thinking.budget_tokens` / `thinking.type`)——DSH 把这些放在 `compat.thinkingFormat` 配置里,界面上只留「选哪一档」。2026-11-02 因为把一个字段名显示到思考强度浮层底部,用户直接问「别的 AI 工具都没有,你搞这个干什么」。协议差异在适配器内部解决,不要外溢到 UI。 + - 保持模块边界:UI 负责呈现,RPC 负责协议适配,Session 编排生命周期,Agent 决策,policy/Executor 在实际副作用前校验,原生层处理平台窗口。新业务逻辑放入独立域模块,不持续堆入 bus、Session 或 RPC handler。 - 浏览器进程/CDP 控制与显示分开。UI 原生显示、隐藏和释放统一经过 BrowserSurface;不要新增绕过队列的并发调用。新显示后端保持相同工具契约,先验证 capabilities 和系统兼容性。 - 异步工作要有所属会话、取消信号与过期结果处理。切换/关闭后的晚到结果不能写回另一个会话;辅助元数据失败不能改变任务完成状态。 @@ -13,3 +15,5 @@ - 保留用户未提交的改动。不要做与当前任务无关的大规模迁移;跨模块迁移先记录决定、兼容策略和可验证的退出条件。 - **合并之后要核对结果,别只信「没有冲突」。** 2026-11-02 的 `a043f9c`(把 main 合进功能分支)没有报冲突,却把 main 上刚做好的五处 CI 加固覆盖回了旧值:`check-ui.mjs` 的 `context.setDefaultTimeout(60000)` 整行消失、端口退回硬编码,`check-sidecar.mjs` 的 PTY 等待 90000→15000,`shell-encoding` 的 `timeoutMs` 90000→30000,`workspace-tabs` 的提示符窗口 45000→20000。这类回退不红不报错,只把窗口悄悄收窄,等到下一次超时才表现为「新代码有问题」。**判据**:合并后某个文件如果「结果 = 分支侧」且「结果 ≠ main」,而该文件在 main 上有近期改动,就是被吞了——逐项核对,别只看 `git diff` 是否为空。 - **`check:ui` 是 CI 的验收项,不是本机自检工具。** 跑之前先想清楚这次改动到底需要它回答什么问题:逻辑正确性用 `node --test`;需要肉眼判断的交互交给人工或 CI;只有「这一处界面在真实浏览器里的行为」才值得本机跑,且用 `--only=` 分节。缺 WDH 组件与 CloakBrowser 内核时不要为了跑通去下载——那一段本来就该由 CI 验证。跑不通说明不了代码坏,跑通了也不等于界面好,别为了「做了事」而跑。 +- **本机 `check:ui` 有已知的假红:`scripts/check-ui.mjs:1220` 等 `.screen-canvas` 超时。** 根因是「多标签浏览器」那一段没像插件段(第 779 行)那样先判断 `kernelMissing`;本机没装 WDH 组件与 CloakBrowser 内核,`skipSection` 只跳过了插件/抓包段,后面照样去开浏览器,于是等满 90 秒才失败。CI 装了组件所以是绿的。**看到这条超时先确认 `kernel-info` 的 `component.installed` / `cloak`,不要先怀疑自己的改动。** +- **UI 里不出现适配器的字段名。** `reasoning_effort` / `thinking.budget_tokens` / `thinking.type` 只在 `sidecar/thinking.mjs` 与设置页的说明文字里;聊天浮层、触发器、任何常规交互面一律不显示(DSH 的模型菜单同样只写「模型名 · 档位」)。`scripts/check-thinking-ui.mjs` 已用断言锁住这一条。 From 0563a3bf831a35e2b979f575bd64e4288e034b71 Mon Sep 17 00:00:00 2001 From: taisuii <93462725+taisuii@users.noreply.github.com> Date: Mon, 2 Nov 2026 12:36:02 +0800 Subject: [PATCH 5/7] =?UTF-8?q?test:=20=E5=AD=A4=E5=84=BF=E4=BC=9A?= =?UTF-8?q?=E8=AF=9D=E7=94=A8=E4=BE=8B=E6=8C=89=E7=9C=9F=E5=AE=9E=E8=B7=AF?= =?UTF-8?q?=E5=BE=84=E6=AF=94=E8=BE=83=EF=BC=8C=E9=81=BF=E5=85=8D=20Window?= =?UTF-8?q?s=20=E7=9F=AD=E8=B7=AF=E5=BE=84=E5=81=87=E7=BA=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CI 上 actual 是 C:\\Users\\RUNNER~1\\...、expected 是 C:\\Users\\runneradmin\\..., 同一个目录的两种写法。比较前各取一次 realpathSync.native 即可。 --- scripts/check-ui.mjs | 1320 -------------------------- sidecar/test/legacy-restore.test.mjs | 4 +- 2 files changed, 3 insertions(+), 1321 deletions(-) delete mode 100644 scripts/check-ui.mjs diff --git a/scripts/check-ui.mjs b/scripts/check-ui.mjs deleted file mode 100644 index 24be861ae6..0000000000 --- a/scripts/check-ui.mjs +++ /dev/null @@ -1,1320 +0,0 @@ -// UI 契约检查:页面能不能正常渲染、文字看不看得清、关键区块在不在。 -// 同时检查共享操作按钮的尺寸、实际命中区域和菜单键盘交互。 -// 用法:npm run check: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 { DEFAULT_TODOS } from '../sidecar/todos.mjs'; -import { folderProof } from '../sidecar/grants.mjs'; -import { checkConversationNavigation } from './check-conversation-ui.mjs'; -import { checkSidebarBrowser } from './check-sidebar-ui.mjs'; -import { checkAccountMenu } from './check-account-ui.mjs'; - -const ROOT = process.cwd(); -const DIST = path.join(ROOT, 'ui-dist'); -const SHOTS = path.join(ROOT, 'artifacts', 'ui'); -const PORT = Number(process.env.JSRA_UI_HTTP_PORT || 5311), WS_PORT = Number(process.env.JSRA_UI_WS_PORT || 5312); -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', - '/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge', - path.join(os.homedir(), 'Applications/Google Chrome.app/Contents/MacOS/Google Chrome'), - path.join(os.homedir(), 'Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge'), - '/usr/bin/google-chrome', '/usr/bin/chromium', -].find(p => fs.existsSync(p)); - -if (!fs.existsSync(path.join(DIST, 'index.html'))) { console.error('先跑 npm run build:ui'); process.exit(2); } -if (!CHROME) { console.error('找不到 Chrome/Edge,设置 CHROME_PATH'); process.exit(2); } - -const fails = []; -const ok = (cond, msg) => { if (!cond) fails.push(msg); }; - -// ---------- 分节运行 ---------- -// 本机改设置页时不该陪着跑浏览器抓包和终端。CI 仍然跑全量(默认 --only=all)。 -// 只切出已经自包含的部分;其余长流水线仍是一整段,宁可慢也不能切出假绿。 -const SECTIONS = { - window: '窗口外壳与标题栏(checkWindowChrome,含原生/自定义两套)', - account: '账号菜单与设置页账号面(checkAccountMenu)', - app: '主流程:项目、会话、附件、设置、插件、浏览器、计划、工作页签、终端', -}; -const SKIPPED = []; -export function skipSection(name, reason) { - SKIPPED.push({ name, reason }); -} - -function parseSections(argv) { - const arg = argv.find(a => a.startsWith('--only='))?.slice('--only='.length) - ?? (argv.includes('--only') ? argv[argv.indexOf('--only') + 1] : null); - if (!arg || arg === 'all') return new Set(Object.keys(SECTIONS)); - const wanted = arg.split(',').map(s => s.trim()).filter(Boolean); - const unknown = wanted.filter(s => !SECTIONS[s]); - if (unknown.length) { - console.error('未知的分节:' + unknown.join(', ') + '\n可用:' + Object.keys(SECTIONS).join(', ') + ', all'); - process.exit(2); - } - return new Set(wanted); -} -const enabled = parseSections(process.argv.slice(2)); -const want = name => enabled.has(name); -async function checkProcessRow(page, label) { - const issues = await page.locator('.turn-process > summary:not([hidden])').evaluateAll(rows => rows.flatMap(row => { - const bounds = row.getBoundingClientRect(), issues = []; - let right = bounds.left; - for (const item of row.children) { - const box = item.getBoundingClientRect(); - if (box.left < right - 1 || box.right > bounds.right + 1) issues.push('状态内容重叠或超出折叠按钮'); - right = box.right; - if (item.matches('.turn-process-label, .turn-process-elapsed, .tool-count')) { - const range = document.createRange(); range.selectNodeContents(item); - const lines = new Set([...range.getClientRects()].filter(r => r.width > 0).map(r => Math.round(r.top))); - if (lines.size > 1) issues.push('状态文字被拆成多行:' + item.textContent); - if (item.matches('.turn-process-label') && item.textContent.length <= 22 && item.scrollWidth > item.clientWidth + 1) issues.push('状态或耗时被过早省略:' + item.textContent); - } - } - return issues; - })); - for (const issue of issues) ok(false, label + ' ' + issue); -} -const rpc = (channel, args = {}) => new Promise((resolve, reject) => { - const ws = new WebSocket('ws://127.0.0.1:' + WS_PORT + '/?token=ui-check'); - const timer = setTimeout(() => { ws.terminate(); reject(Error('UI 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); }); -}); -async function checkWindowDragging(page, selectors, label) { - // Exercise the real frontend handlers against a recorded native bridge. This - // checks hit testing; real OS window movement remains a native acceptance item. - const bridge = 'http://127.0.0.1:' + PORT + '/__ui-window-bridge'; - await page.addScriptTag({ url: bridge }); - const readCalls = () => page.locator('html').getAttribute('data-ui-window-calls').then(value => JSON.parse(value || '[]')); - try { - for (const selector of selectors) { - const before = (await readCalls()).filter(c => c.endsWith('|start_dragging')).length; - await page.locator(selector).first().dispatchEvent('mousedown', { button: 0, detail: 1 }); - await page.waitForFunction(count => JSON.parse(document.documentElement.getAttribute('data-ui-window-calls') || '[]').filter(c => c.endsWith('|start_dragging')).length > count, before); - } - const region = page.locator('[data-window-drag-region]').last(); - await region.dispatchEvent('mousedown', { button: 0, detail: 2 }); - await page.waitForFunction(() => JSON.parse(document.documentElement.getAttribute('data-ui-window-calls') || '[]').some(c => c.endsWith('|toggle_maximize'))); - const before = (await readCalls()).filter(c => c.endsWith('|start_dragging')).length; - await page.locator('[data-window-drag-region] button').first().dispatchEvent('mousedown', { button: 0, detail: 1 }); - ok((await readCalls()).filter(c => c.endsWith('|start_dragging')).length === before, label + ' 点击控件不应拖动窗口'); - } finally { await page.addScriptTag({ url: bridge + '?restore=1' }); } -} - -const DATA = process.env.JSRA_UI_DATA_DIR ? path.resolve(process.env.JSRA_UI_DATA_DIR) : fs.mkdtempSync(path.join(os.tmpdir(), 'ui-check-')); -fs.mkdirSync(DATA, { recursive: true }); -const MODEL_BASE = 'http://127.0.0.1:' + PORT + '/__ui-model/v1', modelRequests = []; -const pendingReasoning = new Map(); -const modelRetries = new Map(); -const pendingRetry = new Map(), releasedRetry = new Set(); -const PLAN_STEPS = Array.from({ length: 30 }, (_, i) => ({ - id: 'ui-plan-' + i, - content: i === 0 ? '完整计划中的长步骤:检查代码、记录证据并核对边界,所有内容应可阅读而非截断。'.repeat(4) : i === 29 ? 'UI_PLAN_LAST_STEP:验证全部步骤并输出最终报告。' : `第 ${i + 1} 步:核对相关文件与验证结果。`, - status: i < 2 ? 'completed' : i === 2 ? 'in_progress' : i === 3 ? 'cancelled' : 'pending', -})); -fs.mkdirSync(path.join(DATA, 'WebDecryptHub'), { recursive: true }); -fs.writeFileSync(path.join(DATA, 'WebDecryptHub', 'settings.json'), JSON.stringify({ - provider: 'openai', headless: true, embedMode: 'screencast', activeProviderId: 'ui-openai', activeModel: 'gpt-4o', - openai: { baseUrl: MODEL_BASE, model: 'gpt-4o', apiKey: 'ui-fixture-key' }, - providers: [ - { id: 'ui-openai', name: 'OpenAI 兼容', type: 'openai', baseUrl: MODEL_BASE, apiKey: 'ui-fixture-key', models: [{ id: 'gpt-4o', name: 'gpt-4o', contextWindow: 1000000, vision: false }] }, - { id: 'ui-claude', name: 'Claude 原生', type: 'anthropic', baseUrl: 'http://127.0.0.1:' + PORT + '/__ui-model', models: ['claude-sonnet-4-6'] }, - ], -})); -const sidecar = spawn(process.execPath, [path.join(ROOT, 'sidecar', 'index.mjs')], { - cwd: ROOT, env: { ...process.env, DECRYPTHUB_DATA_DIR: path.join(DATA, 'WebDecryptHub'), JSRA_WS_PORT: String(WS_PORT), JSRA_WS_TOKEN: 'ui-check', JSRA_TEST_FIXTURES: '1', JSRA_DEV: '1' }, stdio: ['ignore', 'pipe', 'pipe'], -}); -sidecar.stderr?.on('data', d => process.stderr.write('[sidecar] ' + String(d))); -await new Promise((res, rej) => { const t = setTimeout(() => rej(new Error('sidecar 未就绪')), 20000); sidecar.stdout.on('data', d => { if (/JSRA_PORT=/.test(String(d))) { clearTimeout(t); res(); } }); }).catch(e => { console.error(e.message); process.exit(2); }); -// UI 回归不需要首次引导:直接写入已完成偏好,避免弹层和布局检查抢时序。 -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) => { - if (req.url.startsWith('/__ui-folder-grant')) { - const query = new URL(req.url, 'http://x').searchParams, directory = path.join(DATA, 'ui-picker-' + (query.get('scheme') === 'light' ? 'light' : 'dark')); - fs.mkdirSync(directory, { recursive: true }); - const grant = { sessionId: query.get('scope'), path: directory, expiresAt: Date.now() + 60000 }; grant.signature = folderProof('ui-check', grant); - res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify(grant)); return; - } - if (req.url.startsWith('/__ui-folder-bridge')) { - res.setHeader('Content-Type', 'application/javascript'); res.setHeader('Cache-Control', 'no-store'); - const query = new URL(req.url, 'http://x').searchParams; - if (query.has('restore')) { res.end('if(window.__uiFolderBridgeBackup === undefined) delete window.__TAURI_INTERNALS__; else window.__TAURI_INTERNALS__=window.__uiFolderBridgeBackup; delete window.__uiFolderBridgeBackup;'); return; } - const scheme = query.get('scheme') === 'light' ? 'light' : 'dark'; - res.end('window.__uiFolderBridgeBackup=window.__TAURI_INTERNALS__; window.__TAURI_INTERNALS__={metadata:{currentWindow:{label:"main"}},invoke:async function(command,args){if(command==="pick_work_folder")return fetch("/__ui-folder-grant?scheme=' + scheme + '&scope="+encodeURIComponent(args.sessionId)).then(r=>r.json());throw Error("Unexpected native command: "+command);}};'); return; - } - if (req.url.startsWith('/__ui-native-titlebar')) { - res.setHeader('Content-Type', 'application/javascript'); - res.end('window.__JSRA_NATIVE_TITLEBAR = ' + (new URL(req.url, 'http://x').searchParams.get('enabled') === '1') + ';'); return; - } - if (req.url.startsWith('/__ui-window-bridge')) { - res.setHeader('Content-Type', 'application/javascript'); res.setHeader('Cache-Control', 'no-store'); - res.end(req.url.includes('restore=1') ? 'if(window.__uiSavedBridge === undefined) delete window.__TAURI_INTERNALS__; else window.__TAURI_INTERNALS__=window.__uiSavedBridge; delete window.__uiSavedBridge; document.documentElement.removeAttribute("data-ui-window-calls");' : 'window.__uiSavedBridge=window.__TAURI_INTERNALS__; document.documentElement.setAttribute("data-ui-window-calls","[]"); window.__TAURI_INTERNALS__={metadata:{currentWindow:{label:"main"}},invoke:async function(command){const root=document.documentElement;const calls=JSON.parse(root.getAttribute("data-ui-window-calls")||"[]");calls.push(command);root.setAttribute("data-ui-window-calls",JSON.stringify(calls));}};'); return; - } - if (req.url === '/__ui-model/v1/chat/completions') { - let body = ''; req.on('data', chunk => body += chunk); req.on('end', () => { - const input = JSON.parse(body); - if (input.messages[0]?.content?.startsWith('你是会话标题生成器')) { res.writeHead(200, { 'Content-Type': 'text/event-stream' }); res.end('data: ' + JSON.stringify({ choices: [{ delta: { content: '验证图片与工作区操作' }, finish_reason: 'stop' }] }) + '\n\ndata: [DONE]\n\n'); return; } - modelRequests.push(input); - if (input.messages[0]?.content?.startsWith('你是上下文检查点生成器')) { res.writeHead(200, { 'Content-Type': 'text/event-stream' }); res.end('data: ' + JSON.stringify({ choices: [{ delta: { content: '已验证工作区文件、图片和工具操作。保留当前任务、代码路径与后续检查。' }, finish_reason: 'stop' }] }) + '\n\ndata: [DONE]\n\n'); return; } - // 子代理完成通知/目标接续也会以 user 角色注入;取最后一条真正的用户输入,跳过应用注入的【…】事件。 - const userText = m => typeof m.content === 'string' ? m.content : (m.content?.find?.(p => p.type === 'text')?.text || ''); - const text = [...input.messages].reverse().filter(m => m.role === 'user').map(userText).find(t => t && !t.startsWith('【')) || ''; - const retryFixture = text.match(/UI_RETRY_CHECK_(dark|light)/)?.[1]; - if (retryFixture) { - const count = (modelRetries.get(retryFixture) || 0) + 1; modelRetries.set(retryFixture, count); - if (count === 2 && !releasedRetry.has(retryFixture)) { pendingRetry.set(retryFixture, () => { res.writeHead(503, { 'Retry-After': '2' }); res.end('fixture temporarily unavailable'); }); res.once('close', () => pendingRetry.delete(retryFixture)); return; } - if (count <= 2) { res.writeHead(503, { 'Retry-After': '2' }); res.end('fixture temporarily unavailable'); return; } - res.writeHead(200, { 'Content-Type': 'text/event-stream' }); res.end('data: ' + JSON.stringify({ choices: [{ delta: { content: '模型重试验证完成。' }, finish_reason: 'stop' }] }) + '\n\ndata: [DONE]\n\n'); return; - } - const thinkingFixture = text.match(/UI_THINKING_CHECK_(dark|light)/)?.[1]; - if (thinkingFixture) { - const write = delta => res.write('data: ' + JSON.stringify({ choices: [{ delta }] }) + '\n\n'); - res.writeHead(200, { 'Content-Type': 'text/event-stream' }); - write({ reasoning_content: 'UI_THINKING_LIVE:先读取证据,再验证结论。\n\n' }); - pendingReasoning.set(thinkingFixture, () => { write({ reasoning_content: '\n\nUI_THINKING_FINAL:证据已核对。' }); write({ content: '思考展示验证完成。' }); res.end('data: [DONE]\n\n'); }); - res.once('close', () => pendingReasoning.delete(thinkingFixture)); return; - } - const fileTask = text.includes('创建一个测试文件'); - let delta = fileTask && input.messages.at(-1)?.role !== 'tool' ? { tool_calls: [ - { index: 0, id: 'ui-write', type: 'function', function: { name: 'workspace_write', arguments: JSON.stringify({ path: 'ui-example.txt', content: 'UI change verified' }) } }, - { index: 1, id: 'ui-tree', type: 'function', function: { name: 'workspace_write', arguments: JSON.stringify({ path: 'src/trace.js', content: 'DIRECTORY_TREE_VERIFIED' }) } }, - ] } : { content: fileTask ? '已创建测试文件。' : '已收到图片,图片发送链路验证完成。' }; - if (text.includes('打开测试浏览器')) delta = input.messages.at(-1)?.role === 'tool' ? { content: '浏览器操控完成。' } : { tool_calls: [ - { index: 0, id: 'ui-open', type: 'function', function: { name: 'browser_open', arguments: JSON.stringify({ url: 'http://127.0.0.1:' + PORT + '/__ui-fixture?delay=800' }) } }, - { index: 1, id: 'ui-snapshot', type: 'function', function: { name: 'browser_snapshot', arguments: '{}' } }, - ] }; - if (text.includes('你是主代理创建的研究子代理')) delta = input.messages.at(-1)?.role === 'tool' ? { content: '研究完成:工作区证据已核对。' } : { tool_calls: [{ index: 0, id: 'child-list', type: 'function', function: { name: 'workspace_list', arguments: '{}' } }] }; - if (text.includes('验证目标机制')) delta = input.messages.at(-1)?.role === 'tool' ? { content: '目标验证完成。' } : { tool_calls: [{ index: 0, id: 'goal-done', type: 'function', function: { name: 'goal_update', arguments: JSON.stringify({ status: 'complete', summary: '目标机制验证通过。', criteria: [{ content: '验证目标更新和会话持久化', status: 'verified' }], evidence: ['UI_GOAL_EVIDENCE:本地模型调用 goal_update,状态已持久化。'] }) } }, { index: 1, id: 'goal-plan', type: 'function', function: { name: 'todo_write', arguments: JSON.stringify({ steps: PLAN_STEPS.slice(0, 3) }) } }] }; - if (text.includes('UI_MEMORY_CHECK')) delta = input.messages.at(-1)?.role === 'tool' ? { content: '记忆保存验证完成。' } : { tool_calls: [{ index: 0, id: 'memory-write', type: 'function', function: { name: 'memory_manage', arguments: JSON.stringify({ action: 'write', name: 'ui-memory', scope: 'session', content: 'UI_MEMORY_SAVED: verified fixture fact' }) } }] }; - if (text.includes('UI_SKILL_CHECK')) delta = input.messages.at(-1)?.role === 'tool' ? { content: '技能保存验证完成。' } : { tool_calls: [{ index: 0, id: 'skill-write', type: 'function', function: { name: 'skill_manage', arguments: JSON.stringify({ action: 'write', name: 'ui-workflow', scope: 'session', content: '---\nname: ui-workflow\ndescription: Verify project evidence\n---\n\nRead sources, verify claims, record results.' }) } }] }; - const lastUser = input.messages.findLast(m => m.role === 'user')?.content; - if (typeof lastUser === 'string' && /UI_PLAN_(CHECK|UPDATE|TEMPLATE)/.test(lastUser)) { - const updated = lastUser.includes('UI_PLAN_UPDATE'), template = lastUser.includes('UI_PLAN_TEMPLATE'); - delta = input.messages.at(-1)?.role === 'tool' ? { content: updated ? '计划状态更新完成。' : template ? '默认步骤计划已建立。' : '完整计划已建立。' } : { tool_calls: [{ index: 0, id: 'plan-write', type: 'function', function: { name: 'todo_write', arguments: JSON.stringify({ merge: updated, steps: updated ? [{ ...PLAN_STEPS[29], status: 'completed' }] : template ? DEFAULT_TODOS : PLAN_STEPS }) } }] }; - } - res.writeHead(200, { 'Content-Type': 'text/event-stream' }); - res.end('data: ' + JSON.stringify({ choices: [{ delta, finish_reason: delta.tool_calls ? 'tool_calls' : 'stop' }] }) + '\n\ndata: [DONE]\n\n'); - }); return; - } - if (req.url === '/__ui-model/v1/models') { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end('{"data":[{"id":"gpt-4o"}]}'); return; } - // A local target exercises the actual browser/capture path without external traffic. - if (req.url.startsWith('/__ui-fixture/api')) { - res.writeHead(200, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ fixture: true, message: 'UI capture verified' })); return; - } - if (req.url.startsWith('/__ui-fixture')) { - res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }); - const finish = () => res.end('UI 测试页面

本地 UI 验证

'); if (req.url.includes('delay=')) setTimeout(finish, 800); else finish(); return; - } - 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' }); - const nativeTitlebar = new URL(req.url, 'http://x').searchParams.get('native-titlebar'); - res.end(path.extname(p) === '.html' && nativeTitlebar !== null ? fs.readFileSync(p, 'utf8').replace('', '') : fs.readFileSync(p)); -}); -await new Promise(r => srv.listen(PORT, '127.0.0.1', r)); - -const { chromium } = await import('../node_modules/@zhizhuodemao/patchright/index.mjs'); -const browser = await chromium.launch({ headless: true, executablePath: CHROME }); - -fs.mkdirSync(SHOTS, { recursive: true }); - -async function checkWindowChrome(scheme) { - for (const nativeTitlebar of [false, true]) { - const context = await browser.newContext({ viewport: { width: 1440, height: 900 }, colorScheme: scheme }); - // CI runner 上冷启动和首次渲染明显更慢,默认 30 秒的断言窗口不够。 - context.setDefaultTimeout(60000); - const page = await context.newPage(); - page.on('pageerror', error => console.error('Window chrome runtime error: ' + error.message)); - try { - await page.goto('http://127.0.0.1:' + PORT + '/?port=' + WS_PORT + '&token=ui-check&native-titlebar=' + (nativeTitlebar ? '1' : '0')); - await page.locator('.stage-head').waitFor(); - const skip = page.getByRole('button', { name: '稍后', exact: true }); - if (await skip.count()) await skip.click(); - const label = '[' + scheme + '] ' + (nativeTitlebar ? 'Mac 原生标题栏' : '自定义标题栏'); - // 侧栏折叠偏好是持久化的(localStorage 的 wdh_rail):上一次运行留下的「已折叠」 - // 会让后面的按钮断言找不到元素。这里先把偏好清成「新用户」状态, - // 保证断言的是初始形态而不是上一轮的残留。 - const railPreference = await page.evaluate(() => localStorage.getItem('wdh_rail')); - if (railPreference !== null) { - await page.evaluate(() => localStorage.removeItem('wdh_rail')); - await page.reload(); - await page.locator('.stage-head').waitFor(); - } - ok(await page.locator('.rail').isVisible(), label + ' 新用户应默认展开侧栏'); - for (const name of ['最小化', '最大化', '关闭']) ok(await page.locator('.win-controls').getByRole('button', { name, exact: true }).count() === (nativeTitlebar ? 0 : 1), label + ' 窗口按钮重复或缺失:' + name); - ok(await page.locator('.win-controls .tool-panel-toggle').isVisible(), label + ' 工具面板开关应保留'); - ok(await page.locator('.app').evaluate(element => getComputedStyle(element).getPropertyValue('--window-controls-space').trim()) === (nativeTitlebar ? '60px' : '174px'), label + ' 窗口按钮预留空间错误'); - await page.getByRole('button', { name: '收起会话列表', exact: true }).click(); - await page.locator('.rail').waitFor({ state: 'detached' }); - await page.reload(); - await page.getByRole('button', { name: '展开会话列表', exact: true }).waitFor(); - ok(await page.locator('.rail').count() === 0, label + ' 重载不能丢失明确的折叠偏好'); - if (nativeTitlebar) ok(await page.locator('.stage-head').evaluate(element => parseFloat(getComputedStyle(element).paddingLeft)) >= 104, label + ' 折叠后必须为原生窗口按钮保留安全区'); - await page.getByRole('button', { name: '展开会话列表', exact: true }).click(); - await page.locator('.rail').waitFor(); - await page.locator('.rail-bottom .rail-account').click(); - await page.getByRole('menuitem', { name: /^设置/ }).click(); - await page.locator('.settings-nav').waitFor(); - ok(await page.locator('.win-controls button').count() === (nativeTitlebar ? 0 : 3), label + ' 设置页窗口按钮错误'); - await page.screenshot({ path: path.join(SHOTS, scheme + (nativeTitlebar ? '-macos-window-chrome.png' : '-custom-window-chrome.png')) }); - } catch (error) { - await page.screenshot({ path: path.join(SHOTS, scheme + '-window-chrome-failure.png') }).catch(() => {}); - console.error('Window chrome diagnostics: ' + (await page.locator('body').innerText()).slice(0, 2000)); - throw error; - } finally { await context.close(); } - } -} - -// 文字对比度:前景 vs 最近的不透明背景 -const contrast = () => { - const parse = s => { const m = String(s).match(/rgba?\(([^)]+)\)/); if (!m) return null; const p = m[1].split(',').map(Number); return [p[0], p[1], p[2], p[3] === undefined ? 1 : p[3]]; }; - const lum = c => { const f = c.slice(0, 3).map(v => { v /= 255; return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4); }); return 0.2126 * f[0] + 0.7152 * f[1] + 0.0722 * f[2]; }; - const bgOf = el => { let a = el; while (a && a !== document.documentElement) { const c = parse(getComputedStyle(a).backgroundColor); if (c && c[3] > 0.5) return c; a = a.parentElement; } return parse(getComputedStyle(document.body).backgroundColor) || [17, 17, 19, 1]; }; - const out = []; - for (const el of document.querySelectorAll('button, .rt-Text, .side-row, .rowx-title, .rowx-sub, .bubble-md, .md code, .md code span, p, li, h1, h2, h3, td, th')) { - const r = el.getBoundingClientRect(); - if (!r.height || !el.offsetParent) continue; - const text = (el.textContent || '').trim(); - if (!text) continue; - if ([...el.children].some(c => (c.textContent || '').trim())) continue; - const cs = getComputedStyle(el); - const fg = parse(cs.color); - if (!fg || fg[3] < 0.5) continue; - const L1 = lum(fg), L2 = lum(bgOf(el)); - const ratio = (Math.max(L1, L2) + 0.05) / (Math.min(L1, L2) + 0.05); - const size = parseFloat(cs.fontSize), bold = parseInt(cs.fontWeight, 10) >= 600; - const need = size >= 18.66 || (bold && size >= 14) ? 3 : 4.5; - if (ratio < need) out.push('"' + text.slice(0, 12) + '" ' + ratio.toFixed(2) + ':1 (需要 ' + need + ') ' + cs.color); - } - return [...new Set(out)]; -}; - -// Measure both the painted icon and the actual button receiving pointer input. -const actionGeometry = () => { - const issues = []; - for (const button of document.querySelectorAll('.action-icon')) { - let hidden = false; - for (let el = button; el; el = el.parentElement) { - const cs = getComputedStyle(el); - if (cs.display === 'none' || cs.visibility === 'hidden' || +cs.opacity === 0) hidden = true; - } - if (hidden) continue; - const r = button.getBoundingClientRect(), icon = button.querySelector('svg')?.getBoundingClientRect(); - const label = button.getAttribute('aria-label') || button.title || '未命名'; - if (!label || label === '未命名') issues.push('图标按钮缺少名称'); - if (r.width < (button.hasAttribute('data-compact') ? 24 : 32) || r.height < (button.hasAttribute('data-compact') ? 24 : 32)) issues.push(label + ' 点击区域小于 32px'); - if (!icon || icon.width !== (button.hasAttribute('data-compact') ? 14 : 18) || icon.height !== (button.hasAttribute('data-compact') ? 14 : 18)) issues.push(label + ' 图标不是 18px'); - if (!button.disabled && r.width && r.height) { - const hit = document.elementFromPoint(r.x + r.width / 2, r.y + r.height / 2); - if (hit?.closest('button') !== button) issues.push(label + ' 点击区域被遮挡'); - } - } - for (const group of document.querySelectorAll('.row-actions, .composer-bar, .browser-bar')) { - const controls = [...group.querySelectorAll('button')].map(el => el.getBoundingClientRect()).filter(r => r.width && r.height); - for (let i = 0; i < controls.length; i++) for (let j = i + 1; j < controls.length; j++) { - const a = controls[i], b = controls[j]; - if (Math.min(a.right, b.right) > Math.max(a.left, b.left) + 1 && Math.min(a.bottom, b.bottom) > Math.max(a.top, b.top) + 1) issues.push('操作控件重叠'); - } - } - return [...new Set(issues)]; -}; - -const navGeometry = elements => elements.map(el => { - const r = el.getBoundingClientRect(), icon = el.querySelector('svg').getBoundingClientRect(), label = el.querySelector('span').getBoundingClientRect(); - return { name: el.textContent.trim(), x: r.x, y: r.y, width: r.width, height: r.height, iconX: icon.x, labelX: label.x }; -}); -const checkNavSpacing = (rows, label) => rows.forEach((row, i) => { - ok(row.height >= 40, label + ' 导航行过矮:' + row.name); - if (i) ok(row.y - rows[i - 1].y - rows[i - 1].height >= 8, label + ' 菜单间距不足:' + row.name); -}); - -async function showTool(page, kind) { - const panelToggle = page.locator('.tool-panel-toggle'); await panelToggle.waitFor(); - if (await panelToggle.getAttribute('aria-pressed') !== 'true') await panelToggle.click(); - await page.locator('.dock').waitFor(); - const label = kind === 'files' ? '工作区文件' : '浏览器'; - const tab = page.locator('.dock-tabs').getByRole('tab', { name: label, exact: true }).first(); - if (await tab.count()) await tab.click(); else { await page.getByRole('button', { name: '新建标签页', exact: true }).click(); await page.getByRole('menuitem', { name: label + '标签页', exact: true }).click(); } - if (kind !== 'files') { - const toggle = page.locator('.browser-bar button[aria-pressed]'); - await toggle.waitFor(); - if ((await toggle.getAttribute('aria-pressed') === 'true') !== (kind === 'network')) await toggle.click(); - await page.getByRole('button', { name: kind === 'network' ? '返回网页' : '显示网络请求', exact: true }).waitFor(); - } -} - -let activePage; -try { for (const scheme of (process.env.JSRA_UI_SCHEME ? [process.env.JSRA_UI_SCHEME] : ['dark', 'light'])) { - console.log('检查主题:' + scheme); - if (want('window')) await checkWindowChrome(scheme); - else skipSection('window', '未选中 --only=window'); - if (want('account')) await checkAccountMenu({ browser, baseUrl: 'http://127.0.0.1:' + PORT, wsPort: WS_PORT, scheme, shots: SHOTS, ok }); - else skipSection('account', '未选中 --only=account'); - if (!want('app')) { skipSection('app', '未选中 --only=app'); continue; } - const ctx = await browser.newContext({ viewport: { width: 1440, height: 900 }, colorScheme: scheme }); - await ctx.grantPermissions(['clipboard-read', 'clipboard-write']); - const page = await ctx.newPage(); - activePage = page; - const errs = []; - page.on('pageerror', e => { errs.push(e.message); console.error('UI runtime error: ' + e.message); }); - await page.goto('http://127.0.0.1:' + PORT + '/?port=' + WS_PORT + '&token=ui-check', { waitUntil: 'load' }); - await page.waitForTimeout(2200); - const skip = page.getByRole('button', { name: '稍后' }); - if (await skip.count()) await skip.first().click(); - await page.waitForTimeout(300); - - // 首次启动展开项目侧栏,工具面板按需打开。 - await page.screenshot({ path: path.join(SHOTS, scheme + '-boot.png') }); - if (await page.getByText('查看错误详情', { exact: true }).count()) { - await page.getByText('查看错误详情', { exact: true }).click(); - throw new Error(await page.locator('body').innerText()); - } - const expandRail = page.getByRole('button', { name: '展开会话列表' }); - ok(await page.locator('.rail').isVisible(), '[' + scheme + '] 首次启动侧栏应默认打开'); - if (await expandRail.count()) await expandRail.first().click(); - const initialSessions = await rpc('session-list'); - if (!initialSessions.sessions.length) { - ok(await page.getByRole('textbox', { name: '任务指令' }).count() === 0, '[' + scheme + '] 未创建项目时不应创建会话或输入坞'); - ok(await page.getByRole('heading', { name: '添加第一个项目', exact: true }).isVisible(), '[' + scheme + '] 首次启动应显示项目空状态'); - // 空状态只保留一个入口,侧栏和标题栏不再重复提示添加项目。 - ok(await page.getByText('选择项目目录,然后在项目下创建会话。', { exact: true }).count() === 0, '[' + scheme + '] 空状态不应重复说明如何添加项目'); - ok(await page.getByText('添加项目目录,开始工作', { exact: true }).count() === 0, '[' + scheme + '] 侧栏不应重复提示添加项目'); - ok(await page.getByRole('button', { name: '选择项目', exact: true }).count() === 0, '[' + scheme + '] 没有项目时不应显示项目选择器'); - ok(await page.getByRole('button', { name: '添加项目目录', exact: true }).count() === 1, '[' + scheme + '] 空状态应只有一个添加项目入口'); - } - const scope = 'ui-project-' + scheme; - const mainRoot = path.join(DATA, 'ui-main-' + scheme), sharedRoot = path.join(DATA, 'ui-shared-' + scheme); - fs.mkdirSync(mainRoot); fs.mkdirSync(sharedRoot); fs.writeFileSync(path.join(sharedRoot, 'shared-evidence.txt'), 'SECONDARY_ROOT_VERIFIED_' + scheme); - const folder = (directory, key) => { const grant = { sessionId: scope, path: directory, expiresAt: Date.now() + 60000 }; grant.signature = folderProof('ui-check', grant); return { key, grant }; }; - const codeProject = await rpc('project-save', { scope, project: { name: 'UI Project ' + scheme, folders: [folder(mainRoot, 'main'), folder(sharedRoot, 'shared')], primaryKey: 'main' } }); - const freshId = (await rpc('session-create', { projectId: codeProject.id })).id; - await rpc('session-focus', { sessionId: freshId }); - await page.locator('.session-item.on').waitFor(); - ok((await rpc('session-list')).sessions.every(s => !!s.projectId), '[' + scheme + '] 每个真实会话都必须归属项目'); - ok(await page.locator('.project-tree > section:not([data-project-id])').count() === 0, '[' + scheme + '] 项目树只能包含真实项目'); - const expandTools = page.locator('.win-controls button[aria-label="展开工具面板"]'); - if (await expandTools.count()) await expandTools.first().click(); - const panelToggle = await page.locator('.win-controls .tool-panel-toggle').boundingBox(); - ok(panelToggle.x > 1440 - 190, '[' + scheme + '] 工具面板开关应位于窗口右侧'); - await checkWindowDragging(page, ['.stage-identity strong', '.dock-head'], '[' + scheme + '] 标题栏'); - const projectGroup = page.locator('[data-project-id="' + codeProject.id + '"]'); - const fold = projectGroup.getByRole('button', { name: codeProject.name, exact: true }); - await fold.click(); - ok(await projectGroup.locator('.session-item').count() === 0, '[' + scheme + '] 折叠项目应隐藏其中会话'); - await page.reload(); await page.locator('.rail').waitFor(); - ok(await fold.getAttribute('aria-expanded') === 'false', '[' + scheme + '] 重载应保留项目折叠选择'); - await fold.click(); await projectGroup.locator('.session-item.on').waitFor(); - for (let repeat = 0; repeat < 2; repeat++) { - await projectGroup.locator('.project-row').hover(); - const row = await projectGroup.locator('.project-row').boundingBox(), chat = await projectGroup.locator('.session-item').first().boundingBox(); - ok(chat.y - row.y - row.height >= 4, '[' + scheme + '] 项目行与会话卡片不应粘连'); - await fold.click(); await fold.click(); - } - const sectionLeft = await page.locator('.rail-sec').evaluate(el => el.getBoundingClientRect().left); - ok(Math.abs((await projectGroup.boundingBox()).x - sectionLeft) < 1, '[' + scheme + '] 项目分组不应额外缩进'); - const railResize = page.getByRole('separator', { name: '调整左侧栏宽度', exact: true }); - const initialWidth = await page.locator('.rail').evaluate(el => el.getBoundingClientRect().width); - await railResize.focus(); await railResize.press('ArrowRight'); await railResize.press('ArrowRight'); - ok(Math.round(await page.locator('.rail').evaluate(el => el.getBoundingClientRect().width)) === Math.round(initialWidth + 32), '[' + scheme + '] 左侧栏键盘调宽失败'); - const railHandle = await railResize.boundingBox(); - await page.mouse.move(railHandle.x + railHandle.width / 2, railHandle.y + railHandle.height / 2); await page.mouse.down(); await page.mouse.move(railHandle.x + 48, railHandle.y + railHandle.height / 2, { steps: 8 }); await page.mouse.up(); - const draggedWidth = await page.locator('.rail').evaluate(el => el.getBoundingClientRect().width); - ok(draggedWidth > initialWidth + 60, '[' + scheme + '] 左侧栏拖动调宽失败'); - await page.reload(); await page.locator('.rail').waitFor(); - ok(Math.abs(await page.locator('.rail').evaluate(el => el.getBoundingClientRect().width) - draggedWidth) < 1, '[' + scheme + '] 左侧栏宽度未持久化'); - await railResize.dblclick(); - for (let step = 0; step < 4; step++) await railResize.press('ArrowLeft'); - for (const width of [220, 236, 252, 268, 284]) { - const geometry = await page.locator('.rail-brand').evaluate(brand => { - const logo = brand.querySelector('.logo').getBoundingClientRect(), name = brand.querySelector('.rail-name'), badge = brand.querySelector('.rail-badge'); - const text = name.getBoundingClientRect(), tag = badge.getBoundingClientRect(), bounds = brand.getBoundingClientRect(); - return { separate: logo.right < text.left && (!tag.width || text.right < tag.left), fits: text.right <= bounds.right && (!tag.width || tag.right <= bounds.right), fullName: name.scrollWidth <= name.clientWidth, badgeVisible: tag.width > 0 }; - }); - ok(geometry.separate && geometry.fits && geometry.fullName, '[' + scheme + '] ' + width + 'px 侧栏品牌区重叠、裁切或名称不完整'); - if (width === 220) ok(!geometry.badgeVisible, '[' + scheme + '] 最窄侧栏应收起 AGENT 标记'); - if (width === 284) ok(geometry.badgeVisible, '[' + scheme + '] 侧栏加宽后应恢复 AGENT 标记'); - if (width === 220 || width === 284) await page.screenshot({ path: path.join(SHOTS, scheme + '-sidebar-' + width + '.png') }); - await railResize.press('ArrowRight'); - } - await railResize.dblclick(); - const orderRoot = path.join(DATA, 'ui-project-order-' + scheme); fs.mkdirSync(orderRoot); fs.writeFileSync(path.join(orderRoot, 'keep.txt'), 'KEEP_PROJECT_SOURCE'); - const orderProject = await rpc('project-save', { scope, project: { name: '排序与迁移 ' + scheme, folders: [folder(orderRoot, 'order')], primaryKey: 'order' } }); - const orderGroup = page.locator('[data-project-id="' + orderProject.id + '"]'); await orderGroup.waitFor(); - await orderGroup.locator('.project-row').dragTo(projectGroup.locator('.project-row'), { targetPosition: { x: 15, y: 2 } }); - await page.waitForFunction(({ first, second }) => { const groups = [...document.querySelectorAll('[data-project-id]')].map(el => el.dataset.projectId); return groups.indexOf(first) < groups.indexOf(second); }, { first: orderProject.id, second: codeProject.id }); - const order = await rpc('projects-list'); ok(order.findIndex(p => p.id === orderProject.id) < order.findIndex(p => p.id === codeProject.id), '[' + scheme + '] 拖动排序未保存到后端'); - const movingChat = await rpc('session-create', { projectId: orderProject.id, title: '项目迁移测试' }); - await orderGroup.locator('.project-row').hover(); await orderGroup.getByRole('button', { name: '项目操作 ' + orderProject.name, exact: true }).click(); - await page.getByRole('menuitem', { name: '删除项目…', exact: true }).click(); - const removeProject = page.getByRole('dialog', { name: '删除项目', exact: true }); - await removeProject.getByRole('combobox', { name: '项目会话处理方式', exact: true }).click(); - await page.getByRole('option', { name: '迁移到 ' + codeProject.name, exact: true }).click(); - await removeProject.getByRole('button', { name: '删除项目', exact: true }).click(); - await orderGroup.waitFor({ state: 'detached' }); - ok((await rpc('session-list')).sessions.find(s => s.id === movingChat.id)?.projectId === codeProject.id, '[' + scheme + '] 删除项目应先迁移其中会话'); - ok(fs.readFileSync(path.join(orderRoot, 'keep.txt'), 'utf8') === 'KEEP_PROJECT_SOURCE', '[' + scheme + '] 删除项目不能删除源码'); - await rpc('session-delete', { sessionId: movingChat.id }); - await page.addScriptTag({ url: 'http://127.0.0.1:' + PORT + '/__ui-folder-bridge?owner=' + freshId + '&scheme=' + scheme }); - try { - await page.getByRole('button', { name: '新建项目', exact: true }).click(); - const creatingProject = page.getByRole('dialog', { name: '新建项目', exact: true }); - await creatingProject.getByRole('textbox', { name: '项目名称', exact: true }).fill('UI picker ' + scheme); - await creatingProject.getByRole('button', { name: '添加目录', exact: true }).click(); - await creatingProject.getByText(path.join(DATA, 'ui-picker-' + scheme), { exact: true }).waitFor(); - await creatingProject.getByRole('button', { name: '保存项目', exact: true }).click(); - await page.locator('.project-tree').getByText('UI picker ' + scheme, { exact: true }).first().waitFor(); - const createdProject = (await rpc('projects-list')).find(p => p.name === 'UI picker ' + scheme); - const createdList = await rpc('session-list'); - ok(createdList.sessions.find(s => s.id === createdList.focused)?.projectId === createdProject.id, '[' + scheme + '] 保存新项目后应直接进入项目内新会话'); - const pickerRoot = path.join(DATA, 'ui-picker-' + scheme); - fs.writeFileSync(path.join(pickerRoot, 'keep.txt'), 'KEEP_RELINKED_SOURCE'); - fs.renameSync(pickerRoot, pickerRoot + '-offline'); await rpc('projects-check'); - await page.getByText('项目目录不可用,执行已停止。聊天记录保留。', { exact: true }).waitFor(); - ok(!fs.existsSync(pickerRoot), '[' + scheme + '] 检测目录缺失不能自动重建原路径'); - await page.getByRole('textbox', { name: '任务指令', exact: true }).fill('relink draft'); - ok(await page.getByRole('button', { name: '发送(Enter)', exact: true }).isDisabled(), '[' + scheme + '] 缺失目录不能继续执行'); - await page.getByRole('button', { name: '重新选择目录', exact: true }).click(); - const relinkDialog = page.getByRole('dialog', { name: '重新连接项目目录', exact: true }); - await relinkDialog.getByRole('button', { name: '添加目录', exact: true }).click(); - await relinkDialog.getByText(pickerRoot, { exact: true }).waitFor(); - await relinkDialog.getByRole('button', { name: '保存项目', exact: true }).click(); - await page.getByText('项目目录不可用,执行已停止。聊天记录保留。', { exact: true }).waitFor({ state: 'detached' }); - ok((await rpc('session-list')).focused === createdList.focused, '[' + scheme + '] 重连目录不能更换会话身份'); - ok(await page.getByRole('textbox', { name: '任务指令', exact: true }).inputValue() === 'relink draft', '[' + scheme + '] 重连目录必须保留草稿'); - ok(fs.readFileSync(path.join(pickerRoot + '-offline', 'keep.txt'), 'utf8') === 'KEEP_RELINKED_SOURCE', '[' + scheme + '] 重连目录不能移动或删除原文件'); - await page.getByRole('textbox', { name: '任务指令', exact: true }).fill(''); - await rpc('session-focus', { sessionId: freshId }); - await page.locator('.session-item.on[data-session-id="' + freshId + '"]').waitFor(); - await rpc('project-remove', { id: createdProject.id, deleteSessions: true }); - } finally { await page.addScriptTag({ url: 'http://127.0.0.1:' + PORT + '/__ui-folder-bridge?restore=1' }); } - await showTool(page, 'files'); - await page.getByRole('combobox', { name: '文件目录', exact: true }).click(); - await page.getByRole('option', { name: 'ui-shared-' + scheme + ' · 只读', exact: true }).click(); - await page.locator('.workspace-tree [data-path="shared-evidence.txt"]').click(); - await page.locator('.document-content').filter({ hasText: 'SECONDARY_ROOT_VERIFIED_' + scheme }).waitFor(); - await showTool(page, 'files'); - await page.getByRole('combobox', { name: '文件目录', exact: true }).click(); - await page.getByRole('option', { name: 'ui-main-' + scheme + ' · 主目录', exact: true }).click(); - await showTool(page, 'browser'); - - ok(errs.length === 0, '[' + scheme + '] 页面报错: ' + (errs[0] || '')); - ok(await page.locator('.stage-head').count() > 0, '[' + scheme + '] 找不到对话顶栏 .stage-head'); - ok(await page.locator('.composer').count() > 0, '[' + scheme + '] 找不到输入坞 .composer'); - ok(await page.locator('.dock-tabs').count() > 0, '[' + scheme + '] 找不到右侧面板页签'); - ok(await page.locator('.statusbar').count() === 0, '[' + scheme + '] 底部状态栏没有移除'); - ok(await page.getByRole('textbox', { name: '筛选会话' }).count() === 0, '[' + scheme + '] 多余的会话筛选框没有移除'); - ok(await page.locator('.rail').getByText('项目', { exact: true }).count() === 1, '[' + scheme + '] 项目树标题不正确'); - ok(await page.locator('.rail').getByText('本地工作区', { exact: true }).count() === 0, '[' + scheme + '] 设置入口含糊的副标题未移除'); - ok(await page.getByRole('button', { name: '组件样张', exact: true }).count() === 0, '[' + scheme + '] 组件样张入口没有移除'); - ok(await page.locator('.tb').getByRole('button', { name: /搜索/ }).count() === 0, '[' + scheme + '] 标题栏仍有搜索入口'); - checkNavSpacing(await page.locator('.rail-nav .nav-button').evaluateAll(navGeometry), '[' + scheme + '] 主导航'); - await page.screenshot({ path: path.join(SHOTS, scheme + '-chat.png') }); - - for (const issue of await page.evaluate(actionGeometry)) ok(false, '[' + scheme + '] ' + issue); - const attachAction = page.getByRole('button', { name: '添加图片或文件', exact: true }); - await page.mouse.move(1, 1); - const restBackground = await attachAction.evaluate(el => getComputedStyle(el).backgroundColor); - ok(restBackground === 'rgba(0, 0, 0, 0)', '[' + scheme + '] 普通图标操作仍有常驻底色'); - const attachBounds = await attachAction.boundingBox(); - await attachAction.hover(); - ok(await attachAction.evaluate(el => getComputedStyle(el).backgroundColor) !== restBackground, '[' + scheme + '] 操作按钮没有悬停反馈'); - const hoverBounds = await attachAction.boundingBox(); - ok(attachBounds.width === hoverBounds.width && attachBounds.height === hoverBounds.height, '[' + scheme + '] 悬停导致按钮尺寸改变'); - await page.mouse.move(1, 1); - const composerControls = await page.locator('.composer-bar .rt-SelectTrigger, .composer-bar .seat-trigger').evaluateAll(els => els.map(el => ({ height: el.getBoundingClientRect().height, font: parseFloat(getComputedStyle(el).fontSize) }))); - ok(composerControls.every(c => c.height === 32 && c.font === 13 || c.font === 14), '[' + scheme + '] 输入栏选择器尺寸不统一'); - await page.getByRole('button', { name: '选择权限', exact: true }).click(); - ok(await page.getByRole('menuitemradio', { name: '请求批准', exact: true }).count() === 1, '[' + scheme + '] 权限弹窗无法打开'); - ok(await page.getByRole('dialog', { name: '权限与执行环境', exact: true }).count() === 0, '[' + scheme + '] 权限切换不应打开居中弹窗'); - await page.waitForTimeout(200); - await page.screenshot({ path: path.join(SHOTS, scheme + '-permissions.png') }); - await page.getByRole('menuitemradio', { name: '自动批准', exact: true }).click(); - await page.getByRole('button', { name: '选择权限', exact: true }).filter({ hasText: '自动批准' }).waitFor(); - ok(await page.locator('.stage-mode').count() === 0, '[' + scheme + '] 对话顶部不显示权限状态'); - await page.getByRole('button', { name: '选择权限', exact: true }).click(); - await page.getByRole('menuitemradio', { name: '请求批准', exact: true }).click(); - // 权限菜单正在关闭时点别处会被当成「关闭它」的那一次点击,座位不会打开; - // 等它真的消失再点,才是用户看到的行为。 - await page.locator('.permission-menu').waitFor({ state: 'detached' }); - // 模型与思考强度是同一个座位(DSH 的 ModelSelect):从座位里钻取到模型目录才能换模型。 - await page.locator('.composer-seat .seat-trigger').click(); - await page.locator('.seat-pop').waitFor(); - await page.locator('.seat-pop .seat-modelrow').click(); - ok(await page.locator('.seat-pop .seat-item').count() > 0, '[' + scheme + '] 模型菜单无法打开'); - await page.keyboard.press('Escape'); - - // File selection, clipboard paste and drag/drop use the same real attachment RPC. - const imageData = await page.evaluate(() => { const canvas = document.createElement('canvas'); canvas.width = 96; canvas.height = 64; const g = canvas.getContext('2d'); g.fillStyle = '#3478bd'; g.fillRect(0, 0, 96, 64); g.fillStyle = '#fff'; g.font = '24px sans-serif'; g.fillText('UI', 30, 40); return canvas.toDataURL('image/png').split(',')[1]; }); - await page.locator('input[type="file"]').setInputFiles({ name: '图片示例.png', mimeType: 'image/png', buffer: Buffer.from(imageData, 'base64') }); - await page.locator('.composer .attachment-image img').waitFor(); - await page.getByRole('button', { name: '预览图片:图片示例.png', exact: true }).click(); - await page.locator('.image-dialog .image-preview img').waitFor(); - ok((await page.locator('.image-dialog .image-preview img').getAttribute('src')).startsWith('data:image/png;base64,'), '[' + scheme + '] 图片预览未加载原图'); - await page.keyboard.press('Escape'); - await page.locator('.image-dialog').waitFor({ state: 'detached' }); - ok(await page.getByRole('button', { name: '预览图片:图片示例.png', exact: true }).evaluate(el => el === document.activeElement), '[' + scheme + '] 图片预览关闭后没有恢复焦点'); - await page.getByRole('button', { name: '移除附件:图片示例.png', exact: true }).click(); - await page.locator('.composer-input textarea').evaluate((el, data) => { const transfer = new DataTransfer(); transfer.items.add(new File([Uint8Array.from(atob(data), c => c.charCodeAt(0))], '粘贴图片.png', { type: 'image/png' })); el.dispatchEvent(new ClipboardEvent('paste', { bubbles: true, cancelable: true, clipboardData: transfer })); }, imageData); - await page.locator('.composer .attachment-image img').waitFor(); - await page.locator('.composer').evaluate((el, data) => { const transfer = new DataTransfer(); transfer.items.add(new File([Uint8Array.from(atob(data), c => c.charCodeAt(0))], '拖入图片.png', { type: 'image/png' })); el.dispatchEvent(new DragEvent('drop', { bubbles: true, cancelable: true, dataTransfer: transfer })); }, imageData); - await page.locator('.composer .attachment-tile').nth(1).waitFor(); - ok(await page.getByRole('button', { name: '发送(Enter)', exact: true }).isEnabled(), '[' + scheme + '] 仅图片消息不能发送'); - const enableImages = page.getByRole('button', { name: '启用图片输入', exact: true }); - if (await enableImages.count()) { - await page.getByRole('button', { name: '发送(Enter)', exact: true }).click(); - ok(await page.locator('.composer .attachment-tile').count() === 2, '[' + scheme + '] 图片模型不兼容时丢失附件'); - await enableImages.click(); - await enableImages.waitFor({ state: 'detached' }); - } - await page.screenshot({ path: path.join(SHOTS, scheme + '-image-composer.png') }); - await page.getByRole('button', { name: '发送(Enter)', exact: true }).click(); - await page.locator('.msg.assistant').filter({ hasText: '图片发送链路验证完成' }).waitFor(); - const sentImages = modelRequests.at(-1)?.messages.findLast(m => m.role === 'user')?.content.filter(p => p.type === 'image_url') || []; - ok(sentImages.length === 2 && sentImages.every(p => p.image_url.url.endsWith(imageData)), '[' + scheme + '] 模型没有收到两张真实图片'); - await page.reload(); - await page.locator('.msg.user .attachment-image img').nth(1).waitFor(); - ok(await page.locator('.msg.assistant').filter({ hasText: '图片发送链路验证完成' }).count() === 1, '[' + scheme + '] 图片对话重载后丢失回复'); - const reopenRail = page.getByRole('button', { name: '展开会话列表', exact: true }); - if (await reopenRail.count()) await reopenRail.click(); - await page.getByRole('textbox', { name: '任务指令' }).fill('创建一个测试文件'); - await page.getByRole('button', { name: '发送(Enter)', exact: true }).click(); - await page.locator('.msg.assistant').filter({ hasText: '已创建测试文件。' }).waitFor(); - await page.waitForFunction(() => document.querySelector('.stage-identity strong')?.textContent === '验证图片与工作区操作'); - await showTool(page, 'files'); - ok(await page.locator('.workspace-tree [data-path="src/trace.js"]').count() === 0, '[' + scheme + '] 目录应默认折叠'); - await page.locator('.workspace-tree [data-path="src"]').click(); - await page.locator('.workspace-tree [data-path="src/trace.js"]').waitFor(); - ok(await page.locator('.workspace-tree [data-path="src"]').getAttribute('aria-expanded') === 'true', '[' + scheme + '] 文件夹未展开'); - await page.locator('.workspace-tree [data-path="src/trace.js"]').click(); - await page.waitForFunction(() => document.querySelector('.document-panel:not([hidden]) .document-content')?.textContent === 'DIRECTORY_TREE_VERIFIED' || [...document.querySelectorAll('.document-content')].some(el => el.offsetWidth && el.textContent === 'DIRECTORY_TREE_VERIFIED')); - await showTool(page, 'files'); - await page.locator('.workspace-tree [data-path="src"]').press('ArrowLeft'); - ok(await page.locator('.workspace-tree [data-path="src/trace.js"]').count() === 0, '[' + scheme + '] 目录方向键折叠失败'); - await page.locator('.file-row').filter({ hasText: 'ui-example.txt' }).click(); - await page.waitForFunction(() => [...document.querySelectorAll('.document-content')].some(el => el.offsetWidth && el.textContent === 'UI change verified')); - ok(await page.locator('.document-content').filter({ hasText: 'UI change verified' }).textContent() === 'UI change verified', '[' + scheme + '] 工作区文件内容错误'); - ok(await page.getByRole('button', { name: '会话信息', exact: true }).count() === 0, '[' + scheme + '] 顶部不应显示会话信息按钮'); - const focusedId = await page.locator('.session-item.on').getAttribute('data-session-id'); - const menuButton = page.locator('.session-item.on button[aria-label="会话操作"]'); - await page.locator('.session-item.on').hover(); await menuButton.click(); - await page.getByRole('menuitem', { name: '复制会话 ID', exact: true }).click(); - await page.getByText('会话 ID 已复制', { exact: true }).waitFor(); - ok(await page.evaluate(() => navigator.clipboard.readText()) === focusedId, '[' + scheme + '] 复制了其他会话的 ID'); - await menuButton.click(); await page.getByRole('menuitem', { name: '复制为 Markdown', exact: true }).click(); - await page.getByText('对话 Markdown 已复制', { exact: true }).waitFor(); - const copied = await page.evaluate(() => navigator.clipboard.readText()); - ok(copied.includes(focusedId) && copied.includes('UI change verified') && copied.includes('workspace_write'), '[' + scheme + '] Markdown 缺少会话信息或工具结果'); - await page.locator('.session-menu').waitFor({ state: 'hidden' }); - ok(await page.locator('.dock-tabs [role="tab"]').count() >= 2, '[' + scheme + '] 应支持文件与文档独立标签页'); - await showTool(page, 'files'); - await page.getByRole('tab', { name: 'Git 改动', exact: true }).click(); - await page.getByText('当前目录没有可用的Git仓库', { exact: true }).waitFor(); - ok(await page.locator('.workspace-tree').isVisible() === false, '[' + scheme + '] Git 页签不应混入本地目录'); - ok(await page.locator('.detail').count() === 0, '[' + scheme + '] 切换文件页签应清除旧文件预览'); - await page.getByRole('tab', { name: '本地文件', exact: true }).click(); - await page.locator('.workspace-tree').waitFor({ state: 'visible' }); - await page.screenshot({ path: path.join(SHOTS, scheme + '-real-file-change.png') }); - await page.locator('.rail .new-session').click(); - await page.locator('.welcome').waitFor(); - - for (const c of (await page.evaluate(contrast)).slice(0, 10)) ok(false, '[' + scheme + '] 文字对比度不足 ' + c); - - await page.getByRole('button', { name: '了解项目', exact: true }).click(); - ok((await page.getByRole('textbox', { name: '任务指令' }).inputValue()).includes('项目'), '[' + scheme + '] 快捷分析没有填入指令'); - await page.getByRole('textbox', { name: '任务指令' }).fill(''); - await page.keyboard.press('Control+k'); - await page.getByRole('combobox', { name: '搜索项目与会话' }).waitFor(); - ok(await page.locator('.project-tree').isVisible() && await page.locator('.session-search-dialog').count() === 0, '[' + scheme + '] 搜索应在侧栏中打开并保留空查询的项目树'); - await page.getByRole('combobox', { name: '搜索项目与会话' }).fill('UI_NO_SIDEBAR_MATCH_X9ZZ'); - await page.getByText('未找到项目或会话', { exact: true }).waitFor(); - ok(await page.locator('.session-search-results button').count() === 0, '[' + scheme + '] 搜索仍然包含快捷操作'); - await page.keyboard.press('Escape'); - await showTool(page, 'network'); - await page.getByRole('button', { name: '返回网页', exact: true }).press('Enter'); - ok(await page.getByRole('button', { name: '显示网络请求', exact: true }).getAttribute('aria-pressed') === 'false', '[' + scheme + '] 网络请求按钮应支持键盘切回网页'); - await showTool(page, 'files'); - await page.screenshot({ path: path.join(SHOTS, scheme + '-files.png') }); - await page.keyboard.press('Control+Alt+2'); - await page.locator('.win-controls button[aria-label="收起工具面板"]').click(); - ok(await page.locator('.dock').count() === 0, '[' + scheme + '] 工具面板不能收起'); - await page.locator('.win-controls button[aria-label="展开工具面板"]').click(); - ok(await page.locator('.dock').count() === 1, '[' + scheme + '] 工具面板不能恢复'); - await page.keyboard.press('Control+l'); - await page.keyboard.press('Control+l'); - await page.waitForTimeout(100); - ok(await page.getByRole('textbox', { name: '目标网址' }).isVisible(), '[' + scheme + '] 连续 Ctrl+L 关闭了浏览器面板'); - - const beforeSessions = (await rpc('session-list')).sessions.length; - await page.keyboard.press('Control+t'); - await page.waitForTimeout(300); - ok((await rpc('session-list')).sessions.length === beforeSessions + 1, '[' + scheme + '] Ctrl+T 不能在当前项目新建会话'); - await page.locator('.session-item.on').hover(); - for (const issue of await page.evaluate(actionGeometry)) ok(false, '[' + scheme + '] 会话操作 ' + issue); - await page.locator('.session-item.on button[aria-label="会话操作"]').press('Enter'); - ok(await page.getByRole('menuitem', { name: '删除对话', exact: true }).isVisible(), '[' + scheme + '] 会话菜单缺少删除操作'); - await page.locator('.session-menu').evaluate(el => Promise.all(el.getAnimations().map(a => a.finished.catch(() => {})))); - for (const c of (await page.evaluate(contrast)).slice(0, 5)) ok(false, '[' + scheme + '] 会话菜单对比度不足 ' + c); - await page.screenshot({ path: path.join(SHOTS, scheme + '-session-menu.png') }); - await page.getByRole('menuitem', { name: '重命名会话', exact: true }).click(); - await page.getByRole('textbox', { name: '会话名称' }).fill('UI 回归验证 ' + scheme); - await page.getByRole('button', { name: '保存名称' }).click(); - await page.waitForTimeout(250); - ok((await page.locator('.stage-identity').innerText()).includes('UI 回归验证'), '[' + scheme + '] 会话重命名没有更新'); - await page.locator('.session-focus').first().click(); - await page.getByRole('button', { name: '搜索项目与会话', exact: true }).click(); - await page.getByRole('combobox', { name: '搜索项目与会话' }).fill('不存在的会话'); - ok(await page.locator('.session-search-results button').count() === 0, '[' + scheme + '] 会话搜索无效'); - await page.getByRole('combobox', { name: '搜索项目与会话' }).fill('UI 回归验证 ' + scheme); - ok(await page.locator('.session-search-results button').count() === 1, '[' + scheme + '] 搜索没有定位到会话'); - await page.screenshot({ path: path.join(SHOTS, scheme + '-session-search.png') }); - await page.getByRole('combobox', { name: '搜索项目与会话' }).press('Enter'); - await page.waitForTimeout(250); - ok((await page.locator('.stage-identity').innerText()).includes('UI 回归验证 ' + scheme), '[' + scheme + '] 搜索结果不能切换会话'); - - await checkSidebarBrowser({ page, rpc, scheme, shots: SHOTS, ok, projectId: codeProject.id }); - - const resize = page.locator('[data-panel-resize-handle-id]'); - const handle = await resize.boundingBox(); - const widthBefore = (await page.locator('.stage').boundingBox()).width; - await page.mouse.move(handle.x, handle.y + 200); - await page.mouse.down(); await page.mouse.move(handle.x - 65, handle.y + 200, { steps: 6 }); await page.mouse.up(); - ok(Math.abs((await page.locator('.stage').boundingBox()).width - widthBefore) > 30, '[' + scheme + '] 面板分隔线不能调整宽度'); - await page.mouse.move(handle.x - 65, handle.y + 200); await page.mouse.down(); await page.mouse.move(handle.x, handle.y + 200, { steps: 6 }); await page.mouse.up(); - - await page.locator('.rail-bottom .rail-account').click(); - await page.getByRole('menuitem', { name: /^设置/ }).click(); - await page.waitForTimeout(600); - ok(await page.locator('.settings-nav button').count() >= 4, '[' + scheme + '] 设置页导航项不足'); - ok(await page.locator('.settings-col').count() > 0, '[' + scheme + '] 设置页没有内容区'); - await page.locator('.settings-nav').getByRole('button', { name: '账号', exact: true }).click(); - ok(await page.getByRole('button', { name: '在浏览器中登录', exact: true }).isDisabled(), '[' + scheme + '] 网页预览不应假装支持原生账号存储'); - ok(await page.getByText('登录不会上传本地项目或对话,模型渠道继续使用你配置的 API Key。', { exact: true }).isVisible(), '[' + scheme + '] 账号与本地模型权限边界未说明'); - await page.screenshot({ path: path.join(SHOTS, scheme + '-account.png') }); - await page.locator('.settings-nav').getByRole('button', { name: 'AI 模型', exact: true }).click(); - const settingsNavBefore = await page.locator('.settings-nav .nav-button').evaluateAll(navGeometry); - await checkWindowDragging(page, ['.screen-head', '.screen-breadcrumb'], '[' + scheme + '] 设置标题栏'); - checkNavSpacing(settingsNavBefore, '[' + scheme + '] 设置导航'); - await page.screenshot({ path: path.join(SHOTS, scheme + '-settings.png') }); - for (const issue of await page.evaluate(actionGeometry)) ok(false, '[' + scheme + '] 模型设置 ' + issue); - await page.locator('.prov-row').first().getByRole('button', { name: '编辑', exact: true }).click(); - ok(await page.getByRole('dialog', { name: '编辑渠道' }).isVisible(), '[' + scheme + '] 编辑渠道按钮失效'); - await page.getByRole('button', { name: '取消', exact: true }).click(); - await page.locator('.rt-DialogOverlay').waitFor({ state: 'detached' }); - await page.setViewportSize({ width: 1080, height: 680 }); - for (const issue of await page.evaluate(actionGeometry)) ok(false, '[' + scheme + '] 小窗口模型设置 ' + issue); - await page.screenshot({ path: path.join(SHOTS, scheme + '-settings-1080.png') }); - await page.setViewportSize({ width: 1440, height: 900 }); - for (const c of (await page.evaluate(contrast)).slice(0, 10)) ok(false, '[' + scheme + '] 设置页对比度不足 ' + c); - - for (const name of ['运行参数', '外观', '关于与更新']) { - await page.locator('.settings-nav').getByRole('button', { name, exact: true }).click(); - await page.waitForTimeout(150); - const settingsNavAfter = await page.locator('.settings-nav .nav-button').evaluateAll(navGeometry); - ok(settingsNavAfter.every((row, i) => ['x', 'y', 'width', 'height', 'iconX', 'labelX'].every(k => Math.abs(row[k] - settingsNavBefore[i][k]) < 0.5)), '[' + scheme + '] 点击“' + name + '”导致菜单位置变化'); - for (const c of (await page.evaluate(contrast)).slice(0, 5)) ok(false, '[' + scheme + '] ' + name + ' 对比度不足 ' + c); - if (name === 'WDH 组件') { await page.getByRole('button', { name: '测试 CloakBrowser', exact: true }).click(); await page.getByText('浏览器启动与画面检查通过', { exact: true }).waitFor(); } - await page.screenshot({ path: path.join(SHOTS, scheme + '-settings-' + ({ 'WDH 组件': 'browser', '运行参数': 'runtime', '外观': 'appearance', '关于与更新': 'about' }[name]) + '.png') }); - } - await page.locator('.settings-nav').getByRole('button', { name: '外观', exact: true }).click(); - const opposite = scheme === 'dark' ? 'light' : 'dark'; - await page.locator('.theme-option').filter({ hasText: opposite === 'dark' ? '深色' : '浅色' }).click(); - await page.locator('html[data-theme="' + opposite + '"]').waitFor({ state: 'attached', timeout: 3000 }); - ok(await page.locator('html').getAttribute('data-theme') === opposite, '[' + scheme + '] 主题切换没有生效'); - await page.locator('.theme-option').filter({ hasText: '跟随系统' }).click(); - await page.locator('html[data-theme="' + scheme + '"]').waitFor({ state: 'attached', timeout: 3000 }); - ok(await page.locator('html').getAttribute('data-theme') === scheme, '[' + scheme + '] 跟随系统没有恢复'); - - await page.locator('.screen-head button').first().click(); - await page.waitForTimeout(300); - await page.locator('.rail button', { hasText: '自动化任务' }).first().click(); - await page.waitForTimeout(500); - await page.screenshot({ path: path.join(SHOTS, scheme + '-automations.png') }); - await page.getByRole('button', { name: '新建任务', exact: true }).click(); - ok(await page.getByPlaceholder('例如:每天早上看一眼竞品接口').isVisible(), '[' + scheme + '] 新建任务表单不可用'); - await page.getByRole('button', { name: '保存', exact: true }).click(); - const notice = page.locator('[data-sonner-toast]').filter({ hasText: '先写清楚要 AI 做什么' }); - await notice.waitFor(); - await page.waitForFunction(() => { - const el = document.querySelector('[data-sonner-toast]'); - return el && Math.abs(el.getBoundingClientRect().y - 60) < 1; - }); - const noticeBounds = await notice.boundingBox(); - ok(noticeBounds.y >= 46 && noticeBounds.y < 90 && noticeBounds.height < 100, '[' + scheme + '] 通知没有在顶部紧凑显示'); - ok(Math.abs(noticeBounds.x + noticeBounds.width / 2 - 720) < 1, '[' + scheme + '] 通知没有水平居中'); - ok(await page.locator('[data-sonner-toaster]').getAttribute('data-sonner-theme') === scheme, '[' + scheme + '] 通知主题不一致'); - ok(await page.locator('.toasts').count() === 0, '[' + scheme + '] 旧通知容器未移除'); - await page.screenshot({ path: path.join(SHOTS, scheme + '-notification.png') }); - await notice.getByRole('button', { name: '关闭通知', exact: true }).click(); - await notice.waitFor({ state: 'detached' }); - await page.getByRole('button', { name: '取消', exact: true }).click(); - await page.locator('.screen-head button').first().click(); - await page.waitForTimeout(300); - - await page.locator('.rail-nav').getByRole('button', { name: '插件', exact: true }).click(); - // 页签选择会被记住,回归测试先显式停在「官方插件」。 - await page.getByRole('tab', { name: '官方插件', exact: true }).click(); - await page.locator('[data-plugin-id="wdh"]').waitFor(); - ok(await page.getByRole('tab').allInnerTexts().then(t => t.join('|')) === '官方插件|自定义 MCP', '[' + scheme + '] 插件页应为官方插件 / 自定义 MCP 两个页签'); - ok(await page.locator('.official-plugin').count() === 3, '[' + scheme + '] 官方插件应包含 WDH/IDH/ADH'); - await page.getByRole('tab', { name: '自定义 MCP', exact: true }).click(); - ok(await page.locator('.official-plugin').isVisible().catch(() => false) === false, '[' + scheme + '] 自定义 MCP 页签下不应同时显示官方插件列表'); - await page.getByRole('tab', { name: '官方插件', exact: true }).click(); - ok(await page.locator('.official-plugin').count() === 3 && await page.locator('.official-plugin').first().isVisible(), '[' + scheme + '] 切回官方插件后列表应恢复'); - await checkWindowDragging(page, ['.screen-head'], scheme + ' 插件顶部拖动'); - await page.locator('[data-plugin-id="wdh"]').getByRole('button', { name: '配置', exact: true }).click(); - // 插件页和紧随其后的浏览器抓包都要真组件 + CloakBrowser 内核。 - // 本机没装时整段跳过并明确报告,而不是中断后面 87 条与内核无关的断言。 - // CI 有组件,这道判断直接放行,仍然覆盖插件页。 - const kernelState = await rpc('kernel-info').catch(error => { throw new Error('[' + scheme + '] 无法读取内核状态:' + error.message); }); - const kernelMissing = !kernelState?.component?.installed ? 'WDH 组件未安装' : !kernelState?.cloak ? 'CloakBrowser 内核未安装' : null; - if (kernelMissing) { - skipSection('kernel:' + scheme, kernelMissing + '(插件页与浏览器抓包段未验证)'); - } else { - await page.getByRole('button', { name: '测试 CloakBrowser', exact: true }).click(); - await page.getByText('浏览器启动与画面检查通过', { exact: true }).waitFor({ timeout: 90000 }); - await page.screenshot({ path: path.join(SHOTS, scheme + '-plugins.png') }); - await page.locator('.screen-head button').first().click(); - await showTool(page, 'browser'); - // Only use a local page. Browser launch, streaming, capture and detail are real. - await page.getByRole('textbox', { name: '目标网址' }).fill('http://127.0.0.1:' + PORT + '/__ui-fixture'); - await page.getByRole('textbox', { name: '目标网址' }).press('Enter'); - // Windows integrity preparation (45s) precedes Chromium's own 30s launch budget. - await page.locator('.screen-canvas').waitFor({ state: 'visible', timeout: 90000 }); - ok(await page.locator('.browser-views').count() === 0, '[' + scheme + '] 网页和网络不应再使用额外 Tab 栏'); - ok(await page.locator('.screen').evaluate(el => el.getBoundingClientRect().height > el.closest('.dock-body').getBoundingClientRect().height * .7), '[' + scheme + '] 网页应占满浏览器内容区域'); - for (const width of [1080, 1440]) { - await page.setViewportSize({ width, height: 900 }); - const addressBounds = await page.getByRole('textbox', { name: '目标网址' }).boundingBox(); - const networkBounds = await page.getByRole('button', { name: '显示网络请求', exact: true }).boundingBox(); - ok(networkBounds.x > addressBounds.x + addressBounds.width && Math.abs(networkBounds.y + networkBounds.height / 2 - addressBounds.y - addressBounds.height / 2) < 2, '[' + scheme + '] 地址栏和网络按钮应保持同一行,宽度 ' + width); - } - await page.getByRole('button', { name: '刷新', exact: true }).waitFor({ state: 'visible' }); - ok(await page.locator('.browser-launch').count() === 0, '[' + scheme + '] 地址栏不应有独立前往按钮'); - await page.getByRole('textbox', { name: '任务指令' }).fill('打开测试浏览器'); - await page.getByRole('button', { name: '发送(Enter)', exact: true }).click(); - await page.locator('.screen.ai-controlled').waitFor({ state: 'visible' }); - await page.waitForFunction(() => Number(getComputedStyle(document.querySelector('.browser-halo')).opacity) > .7); - ok(await page.getByText('AI 正在操控浏览器', { exact: true }).count() === 0, '[' + scheme + '] 不应显示额外的浏览器操控提示'); - ok(await page.locator('.screen').evaluate(el => getComputedStyle(el.querySelector('.browser-halo')).backgroundImage.includes('linear-gradient') && getComputedStyle(el).padding === '0px'), '[' + scheme + '] 浏览器应该使用柔和光晕而非硬边框'); - const activeViewport = await page.locator('.browser-viewport').boundingBox(); - await page.screenshot({ path: path.join(SHOTS, scheme + '-browser-ai-control.png') }); - await page.locator('.msg.assistant').filter({ hasText: '浏览器操控完成。' }).waitFor(); - await page.locator('.screen.ai-controlled').waitFor({ state: 'detached' }); - const idleViewport = await page.locator('.browser-viewport').boundingBox(); - ok(Math.abs(activeViewport.width - idleViewport.width) < 1 && Math.abs(activeViewport.height - idleViewport.height) < 1, '[' + scheme + '] 光晕改变了网页视口尺寸'); - await page.waitForFunction(() => { const c = document.querySelector('.screen-canvas'); return c?.width > 50 && c.getContext('2d').getImageData(0, 0, 1, 1).data[3] > 0; }); - await page.screenshot({ path: path.join(SHOTS, scheme + '-browser-loaded.png') }); - await page.getByRole('button', { name: '浏览器菜单', exact: true }).click(); - for (const name of ['清除当前站点数据并刷新…', '使用全新浏览器配置重启…', '关闭浏览器(保留会话)']) ok(await page.getByRole('menuitem', { name, exact: true }).count() === 1, '[' + scheme + '] 浏览器操作缺少明确名称:' + name); - await page.screenshot({ path: path.join(SHOTS, scheme + '-browser-menu.png') }); - await page.keyboard.press('Escape'); - await page.getByRole('button', { name: '上下文用量', exact: true }).click(); - ok(await page.getByRole('slider').count() === 0, '[' + scheme + '] 不应再显示调整上下文窗口的滑块'); - await page.keyboard.press('Escape'); - - const debugUiCdp = await ctx.newCDPSession(page); - const invokeTool = async (name, args) => { - const script = '(async () => { const state = await window.api.invoke("session-list"); return window.api.invoke("tool-run", { sessionId: state.focused, name: ' + JSON.stringify(name) + ', args: ' + JSON.stringify(args) + ' }); })()'; - const reply = await debugUiCdp.send('Runtime.evaluate', { expression: script, awaitPromise: true, returnByValue: true }); - ok(!reply.exceptionDetails && !reply.result.value?.isError, '[' + scheme + '] 调试工具失败 ' + name); - }; - await invokeTool('discover_tools', { group: 'debugger' }); - await invokeTool('pause_or_resume', { action: 'pause' }); - await page.waitForTimeout(200); - await invokeTool('get_paused_info', { includeScopes: false }); - await page.getByRole('button', { name: '恢复网页执行', exact: true }).waitFor(); - await page.screenshot({ path: path.join(SHOTS, scheme + '-browser-paused.png') }); - await page.getByRole('button', { name: '恢复网页执行', exact: true }).click(); - await page.getByRole('button', { name: '恢复网页执行', exact: true }).waitFor({ state: 'detached', timeout: 8000 }).catch(async e => { throw new Error(e.message + '\n通知:' + (await page.locator('[data-sonner-toast]').allTextContents()).join(' | ')); }); - await debugUiCdp.detach(); - - await page.keyboard.press('Control+Alt+3'); - await page.locator('.screen-canvas').waitFor({ state: 'detached' }); - const recordNetwork = page.getByRole('button', { name: /^(开始|继续)抓取网络请求$/ }); - if (await recordNetwork.count()) { - await recordNetwork.click(); - await page.keyboard.press('Control+Alt+2'); - await page.getByRole('button', { name: '刷新', exact: true }).click(); - await page.keyboard.press('Control+Alt+3'); - } - await page.locator('.req-row').filter({ hasText: /api/ }).first().waitFor({ timeout: 15000 }); - const pauseNetwork = page.getByRole('button', { name: '暂停抓取网络请求', exact: true }); - ok(await pauseNetwork.getAttribute('aria-pressed') === 'true', '[' + scheme + '] 记录中状态应显示暂停操作'); - await pauseNetwork.click(); - await recordNetwork.waitFor(); - ok(await recordNetwork.getAttribute('aria-pressed') === 'false', '[' + scheme + '] 暂停状态应显示继续操作'); - await recordNetwork.click(); - await pauseNetwork.waitFor(); - ok(await page.locator('.request-filters').evaluate(el => parseFloat(getComputedStyle(el).gap) >= 8 && getComputedStyle(el).flexWrap === 'nowrap'), '[' + scheme + '] 快捷筛选需要独立间距并在窄面板内横向滚动'); - ok(await page.locator('.bar').filter({ has: page.getByPlaceholder('过滤 URL / 参数名') }).innerText().then(text => !/网络请求\s*\d/.test(text)), '[' + scheme + '] 不应重复网络请求标题与数量'); - await page.locator('.req-row').filter({ hasText: /api/ }).first().click(); - await page.locator('.detail-tabs').getByRole('tab', { name: '响应', exact: true }).click(); - await page.waitForFunction(() => document.querySelector('.detail-body')?.textContent.includes('UI capture verified'), { timeout: 10000 }); - ok((await page.locator('.detail-body').innerText()).includes('UI capture verified'), '[' + scheme + '] 请求响应没有正确显示'); - await page.screenshot({ path: path.join(SHOTS, scheme + '-network.png') }); - await page.keyboard.press('Control+Alt+2'); - await page.waitForFunction(() => { const canvas = document.querySelector('.screen-canvas'); return canvas?.width > 50 && canvas.height > 50 && canvas.getContext('2d').getImageData(0, 0, 1, 1).data[3] > 0; }); - await page.screenshot({ path: path.join(SHOTS, scheme + '-browser-restored.png') }); - await page.getByRole('button', { name: '浏览器菜单', exact: true }).click(); - await page.getByRole('menuitem', { name: '关闭浏览器(保留会话)', exact: true }).click(); - } // kernel 段结束:以下断言不再依赖组件与 CloakBrowser 内核 - - await page.locator('.rail .new-session').click(); - await page.locator('.welcome').waitFor(); - - const taskInput = page.getByRole('textbox', { name: '任务指令' }); - await taskInput.focus(); - const inputChrome = await page.locator('.composer-input').evaluate(el => ({ outline: getComputedStyle(el).outlineStyle, shadow: getComputedStyle(el).boxShadow })); - ok(inputChrome.outline === 'none' && inputChrome.shadow === 'none', '[' + scheme + '] 输入框获得焦点时不应出现内框'); - ok(await page.getByRole('button', { name: '输入命令', exact: true }).count() === 0, '[' + scheme + '] 不应保留独立命令按钮'); - await taskInput.fill('/'); - await page.getByRole('listbox', { name: '输入框命令' }).waitFor(); - for (const row of await page.locator('.command-option').evaluateAll(nodes => nodes.map(node => ({ height: node.getBoundingClientRect().height, lines: getComputedStyle(node.querySelector('span')).whiteSpace })))) ok(row.height <= 34 && row.lines === 'nowrap', '[' + scheme + '] 命令列表应为紧凑单行'); - await page.screenshot({ path: path.join(SHOTS, scheme + '-composer-commands.png') }); - await taskInput.press('ArrowDown'); await taskInput.press('Tab'); - ok(await taskInput.inputValue() === '/compact ', '[' + scheme + '] 命令方向键/Tab补全失败'); - await taskInput.fill('/agent 核对工作区证据'); await taskInput.press('Enter'); - await page.getByRole('button', { name: '查看子代理', exact: true }).waitFor(); await page.getByRole('button', { name: '查看子代理', exact: true }).click(); - await page.locator('.subagent-row').filter({ hasText: '已完成' }).waitFor(); - await page.getByRole('button', { name: '核对工作区证据', exact: true }).click(); - await page.getByText('研究完成:工作区证据已核对。', { exact: true }).waitFor(); - await page.keyboard.press('Escape'); - await page.getByRole('button', { name: '关闭子代理列表', exact: true }).click(); - await taskInput.fill('/goal'); await taskInput.press('Enter'); - await page.getByRole('textbox', { name: '设置目标', exact: true }).fill('验证目标机制:' + '完整检查项目证据、执行结果与用户界面,确保长目标内容可以在详情中阅读。'.repeat(6)); - await page.getByRole('dialog', { name: '设置目标', exact: true }).getByRole('button', { name: '执行', exact: true }).click(); - const goalTrigger = page.getByRole('button', { name: '查看目标进展', exact: true }); - await goalTrigger.filter({ hasText: '已完成' }).waitFor(); - await page.locator('.msg.assistant').filter({ hasText: '目标验证完成。' }).waitFor(); - ok(await page.locator('.command-feedback').count() === 0, '[' + scheme + '] 目标成功后不应留下重复的命令提示'); - ok(await page.locator('.composer-wrap .goal-trigger').count() === 0 && await page.locator('.stage-head .goal-trigger').count() === 1, '[' + scheme + '] 目标入口应放在会话标题右侧'); - ok(!(await goalTrigger.innerText()).includes('验证目标机制'), '[' + scheme + '] 目标全文不应占用标题栏'); - for (const viewport of [{ width: 1440, height: 900 }, { width: 1080, height: 680 }]) { - await page.setViewportSize(viewport); - if (viewport.width === 1080) for (let i = 0; i < 13; i++) await railResize.press('ArrowRight'); - const header = await page.locator('.stage-head').evaluate(head => { - const bounds = head.getBoundingClientRect(), children = [...head.children].map(el => el.getBoundingClientRect()).filter(r => r.width > 0 && r.height > 0); - return { height: bounds.height, inside: children.every(r => r.left >= bounds.left && r.right <= bounds.right && r.top >= bounds.top && r.bottom <= bounds.bottom), separate: children.every((r, i) => !i || r.left >= children[i - 1].right - 1) }; - }); - ok(header.inside && header.separate && header.height === 56, '[' + scheme + '] ' + viewport.width + ' 标题、权限与目标/计划按钮应保持单行且不重叠'); - await page.screenshot({ path: path.join(SHOTS, scheme + '-header-progress-' + viewport.width + '.png') }); - if (viewport.width === 1080) await railResize.dblclick(); - } - await page.setViewportSize({ width: 1440, height: 900 }); - await page.screenshot({ path: path.join(SHOTS, scheme + '-harness-goal.png') }); - await page.getByRole('button', { name: '查看目标进展', exact: true }).click(); - await page.locator('.goal-details').waitFor(); - await page.locator('.goal-details').evaluate(el => Promise.all(el.getAnimations().map(animation => animation.finished.catch(() => {})))); - await page.locator('.goal-details').getByText('UI_GOAL_EVIDENCE:本地模型调用 goal_update,状态已持久化。', { exact: true }).waitFor(); - ok(await page.locator('.goal-criteria').getByText('已验证', { exact: true }).count() === 1, '[' + scheme + '] 目标完成条件未展示验证状态'); - const goalBounds = await page.locator('.goal-details').boundingBox(), clearBounds = await page.getByRole('button', { name: '结束并收起目标', exact: true }).boundingBox(); - ok(clearBounds.y >= goalBounds.y && clearBounds.y + clearBounds.height <= goalBounds.y + goalBounds.height, '[' + scheme + '] 长目标不应把操作按钮挤出详情浮层'); - await page.screenshot({ path: path.join(SHOTS, scheme + '-goal-details.png') }); - await page.keyboard.press('Escape'); - const goalSession = (await rpc('session-list')).focused; - await goalTrigger.click(); await rpc('session-focus', { sessionId: freshId }); - await page.locator('.goal-details').waitFor({ state: 'detached' }); - ok(await goalTrigger.count() === 0, '[' + scheme + '] 目标入口或详情不应泄漏到其他会话'); - await rpc('session-focus', { sessionId: goalSession }); - await page.reload(); await goalTrigger.waitFor(); - await goalTrigger.click(); await page.locator('.goal-details section .md').getByText('目标机制验证通过。', { exact: true }).waitFor(); - await page.getByRole('button', { name: '结束并收起目标', exact: true }).click(); - await goalTrigger.waitFor({ state: 'detached' }); - await page.locator('.goal-details').waitFor({ state: 'detached' }); - // 目标自动接续:首轮没有工具/进展时驱动会接续一轮,再接续无可进展后暂停;对话里必须留下“继续执行目标”提示。 - const goalRound = await rpc('session-create', { title: '目标接续提示', projectId: codeProject.id }); - await rpc('session-focus', { sessionId: goalRound.id }); await page.waitForTimeout(300); - await rpc('goal-start', { sessionId: goalRound.id, objective: '验证自动接续提示:只观察,不调用工具' }); - const roundDeadline = Date.now() + 20000; - for (;;) { const snap = await rpc('session-snapshot', { sessionId: goalRound.id }); if (snap.state?.goal && snap.state.goal.status !== 'active') break; if (Date.now() > roundDeadline) throw Error('goal round did not settle'); await page.waitForTimeout(200); } - const turnTrigger = page.locator('.turn-trigger[data-turn-trigger="goal"]').first(); - await turnTrigger.waitFor(); - ok(await turnTrigger.getByText('继续执行目标', { exact: true }).count() === 1, '[' + scheme + '] 自动接续轮必须显示继续执行目标'); - ok(/^\d{2}:\d{2}$/.test(await turnTrigger.locator('.turn-trigger-time').innerText()), '[' + scheme + '] 目标接续提示必须显示时间'); - await turnTrigger.locator('.turn-trigger-head').click(); - await turnTrigger.getByText('这条通知触发了本轮回复。', { exact: true }).waitFor(); - await turnTrigger.getByText('验证自动接续提示:只观察,不调用工具', { exact: true }).waitFor(); - await turnTrigger.screenshot({ path: path.join(SHOTS, scheme + '-goal-trigger.png') }); - await rpc('session-delete', { sessionId: goalRound.id }); - await rpc('session-focus', { sessionId: goalSession }); await page.waitForTimeout(300); - await taskInput.fill('/goal UI_THINKING_CHECK_' + scheme); await taskInput.press('Enter'); - await page.locator('.reason-head').first().waitFor(); - await page.locator('.reason-head').first().click(); - await page.locator('.reasoning-body').filter({ hasText: 'UI_THINKING_LIVE' }).waitFor(); - await goalTrigger.click(); await page.getByRole('button', { name: '暂停目标', exact: true }).click(); - await goalTrigger.filter({ hasText: '已暂停' }).waitFor(); - const resumeBanner = page.locator('.banner').getByRole('button', { name: '继续目标', exact: true }); - await resumeBanner.waitFor({ state: 'visible' }); - await resumeBanner.click(); - await goalTrigger.filter({ hasText: '进行中' }).waitFor(); - await goalTrigger.click(); - await page.getByRole('button', { name: '结束并收起目标', exact: true }).click(); - await goalTrigger.waitFor({ state: 'detached' }); - await page.getByRole('button', { name: '发送(Enter)', exact: true }).waitFor(); - for (const [command, marker, result] of [['memory', 'UI_MEMORY_CHECK', '记忆保存验证完成。'], ['skill', 'UI_SKILL_CHECK', '技能保存验证完成。']]) { - await taskInput.fill('/' + command + ' ' + marker); await taskInput.press('Enter'); - await page.getByRole('button', { name: '允许这一次', exact: true }).click(); - await page.locator('.msg.assistant').filter({ hasText: result }).waitFor(); - const saved = await rpc('extensions-list', { sessionId: (await rpc('session-list')).focused, kind: command }); - ok(saved.some(item => item.name === (command === 'memory' ? 'ui-memory' : 'ui-workflow')), '[' + scheme + '] /' + command + ' 未实际保存'); - } - await taskInput.fill('/memories'); await taskInput.press('Enter'); - await page.getByRole('dialog', { name: '记忆', exact: true }).getByRole('button').filter({ hasText: 'ui-memory' }).click(); - await page.locator('.extension-preview').filter({ hasText: 'UI_MEMORY_SAVED' }).waitFor(); - await page.getByRole('dialog', { name: '记忆', exact: true }).getByRole('button', { name: '关闭', exact: true }).click(); - await taskInput.fill('/compact'); await taskInput.press('Enter'); - await page.locator('.command-feedback.success').filter({ hasText: '上下文已压缩' }).waitFor(); - await page.screenshot({ path: path.join(SHOTS, scheme + '-compact-and-memory.png') }); - await taskInput.fill('/automation'); await taskInput.press('Enter'); - await page.getByPlaceholder('例如:每天早上看一眼竞品接口').fill('UI scheduled run ' + scheme); - await page.getByPlaceholder('例如:打开 https://example.com,看它首页调了哪些接口,把新增的参数记到 findings.md').fill('UI automation read-only check'); - await page.getByRole('button', { name: '保存', exact: true }).click(); - const automationRow = page.locator('.task-row').filter({ hasText: 'UI scheduled run ' + scheme }); - await automationRow.getByRole('button', { name: '立即运行', exact: true }).click(); - await automationRow.getByText('已完成', { exact: true }).waitFor(); - ok((await rpc('tasks-list')).some(t => t.title === 'UI scheduled run ' + scheme && t.lastStatus === 'ok' && t.runs.length), '[' + scheme + '] 自动化未等待真实 Run 完成'); - await page.locator('.screen-head button').first().click(); - await page.locator('.rail .new-session').click(); await page.locator('.welcome').waitFor(); - - for (const viewport of [{ width: 1280, height: 800 }, { width: 1080, height: 680 }]) { - await page.setViewportSize(viewport); - await page.waitForTimeout(200); - ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), '[' + scheme + '] ' + viewport.width + ' 产生横向溢出'); - for (const issue of await page.evaluate(actionGeometry)) ok(false, '[' + scheme + '] ' + viewport.width + ' ' + issue); - const inputBox = await page.locator('.composer').boundingBox(); - ok(inputBox.y + inputBox.height < viewport.height - 20, '[' + scheme + '] ' + viewport.width + ' 输入框被裁切'); - const lastSuggestion = await page.locator('.suggestion').last().boundingBox(); - const messageArea = await page.locator('.msgs').boundingBox(); - ok(lastSuggestion.y + lastSuggestion.height <= messageArea.y + messageArea.height + 1, '[' + scheme + '] ' + viewport.width + ' 快捷分析入口被裁切'); - await page.screenshot({ path: path.join(SHOTS, scheme + '-chat-' + viewport.width + '.png') }); - } - - await page.setViewportSize({ width: 1440, height: 900 }); - // Saved-history fixture; all displayed data is explicitly labelled as an example. - // Patchright evaluates in an isolated world; the app bridge lives in the main world. - const mainWorld = await ctx.newCDPSession(page); - const focusedResult = await mainWorld.send('Runtime.evaluate', { expression: 'window.api.invoke("session-list").then(s => s.focused)', awaitPromise: true, returnByValue: true }); - const imageResult = await mainWorld.send('Runtime.evaluate', { expression: 'window.api.invoke("attach-upload", ' + JSON.stringify({ sessionId: focusedResult.result.value, name: '图片示例.png', mime: 'image/png', data: imageData }) + ')', awaitPromise: true, returnByValue: true }); - const fixtureImageId = imageResult.result.value.id; - const fixtureEvents = [ - { t: 'user', id: 'fixture-user', turnId: 'fixture-turn', at: Date.now() - 1556000, displayContent: '帮我检查这个项目,修复问题并验证。参考这张图片,把界面收敛得更清楚一些。', content: '帮我检查项目。', attachments: [{ kind: 'attachment', id: fixtureImageId, name: '图片示例.png', image: true }], images: [fixtureImageId] }, - { t: 'assistant', turnId: 'fixture-turn', phase: 'commentary', reasoning: 'UI 布局验证:核对项目入口及执行结果。', content: '我先读取入口文件,再搜索相关逻辑,最后运行测试。', calls: [ - {id:'fixture', itemId:'fixture-1', name:'workspace_read', args:{path:'src/main.ts'}}, - {id:'fixture-search', itemId:'fixture-2', name:'workspace_grep', args:{pattern:'TODO'}}, - {id:'fixture-eval', itemId:'fixture-3', name:'workspace_shell', args:{cmd:'npm test'}}, - ...Array.from({ length: 3 }, (_, i) => ({ id: 'fixture-extra-' + i, itemId: 'fixture-extra-' + i, name: 'workspace_read', args: { path: `src/check-${i}.js` } })) - ] }, - { t: 'tool', turnId:'fixture-turn', id:'fixture', itemId:'fixture-1', name:'workspace_read', content:'export function main() { return true; }', ms:42 }, - { t: 'tool', turnId:'fixture-turn', id:'fixture-search', itemId:'fixture-2', name:'workspace_grep', content:'没有未完成项。', ms:18 }, - { t: 'tool', turnId:'fixture-turn', id:'fixture-eval', itemId:'fixture-3', name:'workspace_shell', content:'Tests: 12 passed', ms:11 }, - ...Array.from({ length: 3 }, (_, i) => ({ t: 'tool', turnId: 'fixture-turn', id: 'fixture-extra-' + i, itemId: 'fixture-extra-' + i, content: 'fixture verified', ms: 12 })), - { t: 'assistant', turnId:'fixture-turn', phase:'final_answer', content:'已完成这一轮检查。\n\n- 用户输入、执行过程和最终回复已分开。\n- 工具详情默认收起,需要时可以展开查看。\n- 图片保留在原消息中,重新打开对话后仍可预览。\n\n测试通过,可以继续体验。\n\n```ts\nexport function main() {\n return true;\n}\n```' }, - { t: 'turn-end', turnId:'fixture-turn', stop:'completed', endedAt: Date.now() - 5000 } - ]; - await mainWorld.send('Runtime.evaluate', { expression: 'window.api.invoke("test-seed-history", ' + JSON.stringify({sessionId:focusedResult.result.value,events:fixtureEvents}) + ')', awaitPromise:true, returnByValue:true }); - await page.reload(); - await page.locator('.tool-group > summary').waitFor(); - await page.locator('.msg.user .attachment-image img').waitFor(); - const skipAgain = page.getByRole('button', { name: '稍后', exact: true }); - if (await skipAgain.count()) await skipAgain.click(); - ok(await page.locator('.plan-trigger').count() === 0, '[' + scheme + '] 没有实际任务时仍显示默认清单'); - ok(!await page.locator('.tool-head').first().isVisible(), '[' + scheme + '] 连续工具调用没有默认收起'); - for (const viewport of [{ width: 1080, height: 680 }, { width: 1440, height: 900 }]) { - await page.setViewportSize(viewport); - await checkProcessRow(page, '[' + scheme + '] ' + viewport.width + ' 执行过程'); - } - await page.screenshot({ path: path.join(SHOTS, scheme + '-conversation.png') }); - await page.locator('.tool-group > summary').press('Enter'); - await page.locator('.tool-head').nth(2).waitFor({ state: 'visible' }); - ok(await page.locator('.tool-head:visible').count() === 6, '[' + scheme + '] 长工具分组不能通过键盘展开'); - await page.locator('.tool-head').first().click(); - ok(await page.locator('.tool-body').isVisible(), '[' + scheme + '] 工具调用记录不能展开'); - ok((await page.locator('.tool-body').innerText()).includes('42 ms'), '[' + scheme + '] 工具调用时长没有显示在详情中'); - ok(await page.locator('.md pre code').count() > 0, '[' + scheme + '] 代码块没有渲染'); - await page.screenshot({ path: path.join(SHOTS, scheme + '-tool-detail.png') }); - await page.locator('.tool-group > summary').press('Enter'); - await page.locator('.tool-head').first().waitFor({ state: 'hidden' }); - ok(!await page.locator('.tool-head').first().isVisible(), '[' + scheme + '] 工具分组不能收起'); - await page.locator('.msgs').evaluate(el => { el.style.scrollBehavior = 'auto'; el.scrollTop = el.scrollHeight; }); - await page.screenshot({ path: path.join(SHOTS, scheme + '-conversation-code.png') }); - for (const c of (await page.evaluate(contrast)).slice(0, 8)) ok(false, '[' + scheme + '] 对话与代码对比度不足 ' + c); - const closeTools = page.getByRole('button', { name: '收起工具面板', exact: true }); - if (await closeTools.count()) await closeTools.click(); - const closeRail = page.getByRole('button', { name: '收起会话列表', exact: true }); - if (await closeRail.count()) await closeRail.click(); - await page.setViewportSize({ width: 1440, height: 1000 }); - await page.locator('.msgs').evaluate(el => { el.style.scrollBehavior = 'auto'; el.scrollTop = 0; }); - await page.screenshot({ path: path.join(SHOTS, scheme + '-conversation-focused.png') }); - - await checkConversationNavigation({ page, rpc, scheme, shots: SHOTS, ok }); - - // Exercise the actual plan tool, live events, saved state and manual UI reading. - const priorPlanSession = (await rpc('session-list')).focused; - const planSession = await rpc('session-create', { title: '完整计划 UI 验证', projectId: codeProject.id }); - await rpc('session-focus', { sessionId: planSession.id }); - await page.getByRole('textbox', { name: '任务指令' }).fill('UI_PLAN_TEMPLATE'); - await page.getByRole('button', { name: '发送(Enter)', exact: true }).click(); - await page.locator('.msg.assistant').filter({ hasText: '默认步骤计划已建立。' }).waitFor(); - const planTrigger = page.getByRole('button', { name: '查看完整计划', exact: true }); - const planPanel = page.getByRole('dialog', { name: '任务计划', exact: true }); - await planTrigger.click(); await planPanel.waitFor(); - ok(await planPanel.locator('li').count() === DEFAULT_TODOS.length, '[' + scheme + '] AI 明确建立的计划不应被当作未使用模板隐藏'); - await page.keyboard.press('Escape'); await planPanel.waitFor({ state: 'detached' }); - await page.getByRole('textbox', { name: '任务指令' }).fill('UI_PLAN_CHECK'); - await page.getByRole('button', { name: '发送(Enter)', exact: true }).click(); - await page.locator('.msg.assistant').filter({ hasText: '完整计划已建立。' }).waitFor(); - ok(await page.locator('.stage-head .plan-trigger').count() === 1, '[' + scheme + '] 计划入口应在标题栏内'); - ok(await planTrigger.innerText().then(text => !text.includes('完整计划中的长步骤')), '[' + scheme + '] 计划步骤全文不应占用标题栏'); - const closedPlanGeometry = await page.locator('.chat').evaluate(chat => ({ head: chat.querySelector('.stage-head').getBoundingClientRect().bottom, msgs: chat.querySelector('.msgs').getBoundingClientRect().top })); - ok(Math.abs(closedPlanGeometry.head - closedPlanGeometry.msgs) < 1, '[' + scheme + '] 标题栏下方不应再有占用消息空间的计划横条'); - await planTrigger.focus(); await planTrigger.press('Enter'); - await planPanel.waitFor(); - ok(await planPanel.locator('li').count() === 30, '[' + scheme + '] 完整计划未列出所有步骤'); - await planPanel.evaluate(el => Promise.all(el.getAnimations().map(a => a.finished.catch(() => {})))); - ok(await planPanel.locator('.todo-step-content').first().innerText() === PLAN_STEPS[0].content, '[' + scheme + '] 长步骤内容被截断'); - for (const status of ['completed', 'in_progress', 'cancelled', 'pending']) ok(await planPanel.locator('[data-status="' + status + '"]').count() > 0, '[' + scheme + '] 计划缺少状态:' + status); - await planPanel.locator('ol').focus(); await planPanel.locator('ol').press('End'); - await page.waitForFunction(() => { const list = document.querySelector('.todo-plan-list'); return list && list.scrollTop > 0 && list.scrollTop + list.clientHeight >= list.scrollHeight - .5; }); - const endGeometry = await planPanel.evaluate(el => { const last = el.querySelector('li:last-child').getBoundingClientRect(), list = el.querySelector('ol').getBoundingClientRect(); return { last: { top: last.top, bottom: last.bottom }, list: { top: list.top, bottom: list.bottom } }; }); - ok(endGeometry.last.top >= endGeometry.list.top && endGeometry.last.bottom <= endGeometry.list.bottom + 2, '[' + scheme + '] 不能手动滚动到最后一步:' + JSON.stringify(endGeometry)); - await page.screenshot({ path: path.join(SHOTS, scheme + '-plan-end.png') }); - await planPanel.getByRole('button', { name: '复制计划', exact: true }).click(); - const copiedPlan = await page.evaluate(() => navigator.clipboard.readText()); - ok(PLAN_STEPS.every(step => copiedPlan.includes(step.content)) && copiedPlan.includes('已取消'), '[' + scheme + '] 复制的计划不完整'); - await rpc('agent-send', { sessionId: planSession.id, text: 'UI_PLAN_UPDATE' }); - await planPanel.locator('li[data-status="completed"]').filter({ hasText: 'UI_PLAN_LAST_STEP' }).waitFor(); - ok(await planPanel.locator('li').count() === 30 && (await planPanel.innerText()).includes('已完成 3 / 30 项'), '[' + scheme + '] 打开中的计划没有实时更新'); - await page.keyboard.press('Escape'); await planPanel.waitFor({ state: 'detached' }); - await planTrigger.click(); await planPanel.waitFor(); - await rpc('session-focus', { sessionId: priorPlanSession }); - await planPanel.waitFor({ state: 'detached' }); - ok(await page.locator('.plan-trigger').count() === 0, '[' + scheme + '] 计划浮层泄漏到其他会话'); - await rpc('session-focus', { sessionId: planSession.id }); - await planTrigger.waitFor(); await page.reload(); await planTrigger.waitFor(); - ok((await planTrigger.innerText()).includes('3/30'), '[' + scheme + '] 重开会话丢失计划状态'); - for (const viewport of [{ width: 1440, height: 900 }, { width: 1080, height: 680 }]) { - await page.setViewportSize(viewport); await planTrigger.click(); await planPanel.waitFor(); - await planPanel.evaluate(el => Promise.all(el.getAnimations().map(animation => animation.finished.catch(() => {})))); - const panelBounds = await planPanel.boundingBox(); - ok(panelBounds.x >= 0 && panelBounds.y >= 0 && panelBounds.x + panelBounds.width <= viewport.width && panelBounds.y + panelBounds.height <= viewport.height, '[' + scheme + '] 计划浮层超出窗口'); - ok(await planPanel.locator('ol').evaluate(el => el.scrollHeight > el.clientHeight && el.scrollWidth <= el.clientWidth + 1), '[' + scheme + '] 长计划未提供可用滚动区域'); - for (const c of (await page.evaluate(contrast)).slice(0, 8)) ok(false, '[' + scheme + '] 完整计划对比度不足 ' + c); - await page.screenshot({ path: path.join(SHOTS, scheme + '-plan-' + viewport.width + '.png') }); - await planPanel.getByRole('button', { name: '关闭计划', exact: true }).click(); await planPanel.waitFor({ state: 'detached' }); - } - // Tool panels, selected tabs and widths belong to their owning conversation. - await page.setViewportSize({ width: 1440, height: 900 }); - const viewA = await rpc('session-create', { title: 'UI 独立布局 A', projectId: codeProject.id }), viewB = await rpc('session-create', { title: 'UI 独立布局 B', projectId: codeProject.id }); - await rpc('session-focus', { sessionId: viewA.id }); - await page.getByRole('button', { name: '展开工具面板', exact: true }).click(); - await showTool(page, 'files'); - await page.getByRole('button', { name: '收起工具面板', exact: true }).click(); - await rpc('session-focus', { sessionId: viewB.id }); - await page.getByRole('button', { name: '展开工具面板', exact: true }).click(); - await showTool(page, 'browser'); - const resizeBar = await page.locator('.resize-handle').boundingBox(); - await page.mouse.move(resizeBar.x + resizeBar.width / 2, resizeBar.y + 120); await page.mouse.down(); await page.mouse.move(resizeBar.x + 100, resizeBar.y + 120); await page.mouse.up(); - const viewBWidth = (await page.locator('.dock').boundingBox()).width; - await rpc('session-focus', { sessionId: viewA.id }); - await page.getByRole('button', { name: '展开工具面板', exact: true }).waitFor(); - ok(await page.locator('.dock').count() === 0, '[' + scheme + '] B 的展开状态泄漏到 A'); - await page.reload(); await page.getByRole('button', { name: '展开工具面板', exact: true }).waitFor(); - await page.getByRole('button', { name: '展开工具面板', exact: true }).click(); - ok(await page.getByRole('tab', { name: '工作区文件', exact: true }).getAttribute('aria-selected') === 'true', '[' + scheme + '] A 丢失了独立工具页签'); - await page.getByRole('button', { name: '收起工具面板', exact: true }).click(); - await rpc('session-focus', { sessionId: viewB.id }); await page.locator('.browser-bar').waitFor(); - const restoredViewBWidth = (await page.locator('.dock').boundingBox()).width; - ok(Math.abs(restoredViewBWidth - viewBWidth) < 2, '[' + scheme + '] B 丢失了独立面板宽度:' + viewBWidth + ' → ' + restoredViewBWidth); - await rpc('session-focus', { sessionId: viewA.id }); - await page.getByRole('textbox', { name: '任务指令' }).fill('UI_THINKING_CHECK_' + scheme); - await page.getByRole('button', { name: '发送(Enter)', exact: true }).click(); - await page.locator('.reason-head').first().waitFor(); - await page.locator('.reason-head').first().click(); - await page.locator('.reasoning-body').filter({ hasText: 'UI_THINKING_LIVE' }).waitFor(); - ok(await page.getByRole('button', { name: '停止响应', exact: true }).count() === 1 && await page.getByRole('button', { name: '发送(Enter)', exact: true }).count() === 0, '[' + scheme + '] 运行中应仅显示一个停止按钮'); - ok(await page.locator('.composer').evaluate(el => !el.classList.contains('rt-Card') && ['borderTopLeftRadius', 'borderTopRightRadius', 'borderBottomLeftRadius', 'borderBottomRightRadius'].every(k => getComputedStyle(el)[k] === '22px')), '[' + scheme + '] 输入框应使用完整且一致的四角圆角'); - ok(await page.locator('.stage-identity').innerText().then(text => !/https?:\/\//.test(text)), '[' + scheme + '] 对话顶部不应重复网址'); - ok(await page.locator('.reasoning-body script').count() === 0 && !await page.evaluate(() => window.__thinkingScriptExecuted), '[' + scheme + '] 思考内容被当作脚本执行'); - const thoughtSnapshot = await rpc('session-snapshot', { sessionId: viewA.id }); - ok(thoughtSnapshot.partialReasoning.includes('UI_THINKING_LIVE') && !thoughtSnapshot.partial, '[' + scheme + '] 思考流没有独立保存'); - await page.setViewportSize({ width: 1080, height: 680 }); - await checkProcessRow(page, '[' + scheme + '] 窄窗口实时思考'); - await page.screenshot({ path: path.join(SHOTS, scheme + '-reasoning-1080.png') }); - await page.setViewportSize({ width: 1440, height: 900 }); - await page.screenshot({ path: path.join(SHOTS, scheme + '-reasoning-live.png') }); - await page.reload(); await page.locator('.reason-head').first().waitFor(); - ok(await page.locator('.reasoning-body').count() === 0, '[' + scheme + '] 刷新后思考应默认收起'); - await page.locator('.reason-head').first().click(); - await page.locator('.reasoning-body').filter({ hasText: 'UI_THINKING_LIVE' }).waitFor(); - await rpc('session-focus', { sessionId: viewB.id }); await page.locator('.browser-bar').waitFor(); - ok(await page.locator('.reason-row').count() === 0, '[' + scheme + '] 思考内容泄漏到另一会话'); - await rpc('session-focus', { sessionId: viewA.id }); await page.locator('.reason-head').first().waitFor(); - pendingReasoning.get(scheme)(); - await page.locator('.msg.assistant').filter({ hasText: '思考展示验证完成。' }).waitFor(); - // 与 DSH 一致:完成后的思考默认收起,执行过程收成一行摘要。 - await page.reload(); await page.locator('.turn-process > summary:not([hidden])').first().waitFor(); - ok(await page.locator('.reason-row.is-open').count() === 0, '[' + scheme + '] 完成后思考应默认收起'); - // 完成后执行过程默认折叠,先展开再检查思考内容。 - await page.locator('.turn-process > summary:not([hidden])').first().click(); - await page.locator('.reason-head').first().click(); - await page.locator('.reasoning-body').filter({ hasText: 'UI_THINKING_FINAL' }).waitFor(); - await page.locator('.reason-head').click(); await page.locator('.reasoning-body').waitFor({ state: 'hidden' }); - await page.locator('.reason-head').click(); await page.locator('.reasoning-body').waitFor(); - await page.screenshot({ path: path.join(SHOTS, scheme + '-reasoning-saved.png') }); - await page.reload(); - await page.locator('.turn-process > summary:not([hidden])').first().click(); - await page.locator('.reason-head').first().click(); - await page.locator('.reasoning-body').filter({ hasText: 'UI_THINKING_FINAL' }).waitFor(); - const retryChat = await rpc('session-create', { title: '模型恢复验证', projectId: codeProject.id }); await rpc('session-focus', { sessionId: retryChat.id }); - await page.getByRole('textbox', { name: '任务指令' }).fill('UI_RETRY_CHECK_' + scheme); - await page.getByRole('button', { name: '发送(Enter)', exact: true }).click(); - await page.getByText(/模型连接重试 1\/10/).waitFor(); - await checkProcessRow(page, '[' + scheme + '] 模型重试长状态'); - await page.screenshot({ path: path.join(SHOTS, scheme + '-model-retry.png') }); - await page.reload(); await page.getByText(/模型连接重试 [12]\/10/).waitFor(); - releasedRetry.add(scheme); pendingRetry.get(scheme)?.(); - await page.locator('.msg.assistant').filter({ hasText: '模型重试验证完成。' }).waitFor(); - ok(modelRetries.get(scheme) === 3, '[' + scheme + '] 模型恢复请求次数错误'); - ok(await page.getByText(/模型连接重试 [12]\/10/).count() === 0, '[' + scheme + '] 模型恢复后仍残留重试状态'); - // Work tabs exercise the real document, browser-page and PTY contracts. - const tabRoot = path.join(DATA, 'ui-tabs-' + scheme); fs.mkdirSync(tabRoot); - const tabProject = await rpc('project-save', { scope, project: { name: 'UI tabs ' + scheme, folders: [folder(tabRoot, 'tabs')], primaryKey: 'tabs' } }); - const workChat = await rpc('session-create', { title: '多标签工作验证 ' + scheme, projectId: tabProject.id }); - await rpc('session-focus', { sessionId: workChat.id }); await showTool(page, 'files'); - fs.mkdirSync(path.join(workChat.workspace.root, 'nested'), { recursive: true }); - fs.writeFileSync(path.join(workChat.workspace.root, 'report.md'), '# 工作报告\n\n[继续阅读](nested/next.md)\n\n[不应执行](javascript:alert(1))'); - fs.writeFileSync(path.join(workChat.workspace.root, 'nested/next.md'), '# 后续文档\n\nDOC_TAB_VERIFIED'); - await page.getByRole('button', { name: '刷新文件目录', exact: true }).click(); - await page.getByRole('button', { name: '复制工作目录路径', exact: true }).click(); - ok(await page.evaluate(() => navigator.clipboard.readText()) === workChat.workspace.root, '[' + scheme + '] 工作区文件应能复制目录路径'); - await page.locator('.workspace-tree [data-path="report.md"]').click(); - await page.locator('.document-panel').getByRole('heading', { name: '工作报告', exact: true }).waitFor(); - ok(await page.locator('.document-panel a[href^="javascript:"]').count() === 0, '[' + scheme + '] 文档不能渲染危险协议链接'); - const beforeReuse = await page.locator('.dock-tabs [role="tab"]').count(); - await showTool(page, 'files'); await page.locator('.workspace-tree [data-path="report.md"]').click(); - ok(await page.locator('.dock-tabs [role="tab"]').count() === beforeReuse, '[' + scheme + '] 同一文档应复用标签页'); - await page.locator('.dock-body[data-state="active"]').getByRole('tab', { name: '源码', exact: true }).click(); - ok((await page.locator('.dock-body[data-state="active"] .document-content').innerText()).startsWith('# 工作报告'), '[' + scheme + '] Markdown 源码视图不可用'); - await page.locator('.dock-body[data-state="active"]').getByRole('tab', { name: '预览', exact: true }).click(); - await page.locator('.dock-body[data-state="active"]').getByRole('link', { name: '继续阅读', exact: true }).click(); - await page.locator('.document-panel').getByRole('heading', { name: '后续文档', exact: true }).waitFor(); - await page.screenshot({ path: path.join(SHOTS, scheme + '-document-tabs.png') }); - await page.getByRole('button', { name: '新建标签页', exact: true }).click(); - await page.getByRole('menuitem', { name: '工作区文件标签页', exact: true }).click(); - ok(await page.locator('.dock-tab-wrap[data-tab-kind="files"]').count() === 2, '[' + scheme + '] 应支持多个目录浏览标签'); - const secondFiles = page.locator('.dock-tab-wrap[data-tab-kind="files"]').last(); await secondFiles.hover(); await secondFiles.getByRole('button').click(); - ok(await page.locator('.dock-tab-wrap[data-tab-kind="files"]').count() === 1 && fs.existsSync(path.join(workChat.workspace.root, 'report.md')), '[' + scheme + '] 关闭文件标签不应删除文件'); - await showTool(page, 'browser'); - const firstBrowserId = await page.locator('.dock-tab-wrap[data-tab-kind="browser"]').first().getAttribute('data-tab-id'); - const browserA = 'http://127.0.0.1:' + PORT + '/__ui-fixture?tab=A', browserB = 'http://127.0.0.1:' + PORT + '/__ui-fixture?tab=B'; - await page.getByRole('textbox', { name: '目标网址' }).fill(browserA); await page.getByRole('textbox', { name: '目标网址' }).press('Enter'); - await page.locator('.screen-canvas').waitFor({ timeout: 90000 }); - await page.getByRole('button', { name: '新建标签页', exact: true }).click(); await page.getByRole('menuitem', { name: '浏览器标签页', exact: true }).click(); - ok(await page.getByRole('textbox', { name: '目标网址' }).inputValue() === '', '[' + scheme + '] 新浏览器标签不应继承另一页面网址'); - await page.getByRole('textbox', { name: '目标网址' }).fill(browserB); await page.getByRole('textbox', { name: '目标网址' }).press('Enter'); - await page.waitForFunction(url => document.querySelector('[aria-label="目标网址"]')?.value === url && !!document.querySelector('.screen-canvas'), browserB); - const secondBrowser = page.locator('.dock-tab-wrap[data-tab-kind="browser"]').last(); const secondBrowserId = await secondBrowser.getAttribute('data-tab-id'); - await page.locator('.dock-tab-wrap[data-tab-id="' + firstBrowserId + '"]').getByRole('tab').click(); - await page.waitForFunction(url => document.querySelector('[aria-label="目标网址"]')?.value === url && !!document.querySelector('.screen-canvas'), browserA); - const selectedPage = await rpc('tool-run', { sessionId: workChat.id, name: 'browser_snapshot', args: {} }); - ok(selectedPage.text.includes(browserA), '[' + scheme + '] 浏览器标签必须切换真实CDP页面'); - await page.getByRole('button', { name: '显示网络请求', exact: true }).click(); - await page.getByPlaceholder('过滤 URL / 参数名').fill('api'); - await showTool(page, 'files'); - await page.locator('.dock-tab-wrap[data-tab-id="' + firstBrowserId + '"]').getByRole('tab').click(); - ok(await page.getByPlaceholder('过滤 URL / 参数名').inputValue() === 'api', '[' + scheme + '] 浏览器标签应保留网络筛选'); - await page.locator('.dock-tab-wrap[data-tab-id="' + secondBrowserId + '"]').hover(); - await page.locator('.dock-tab-wrap[data-tab-id="' + secondBrowserId + '"]').getByRole('button').click(); - await page.locator('.dock-tab-wrap[data-tab-id="' + secondBrowserId + '"]').waitFor({ state: 'detached' }); - ok(JSON.parse((await rpc('tool-run', { sessionId: workChat.id, name: 'browser_tabs', args: {} })).text).length === 1, '[' + scheme + '] 关闭浏览器标签应关闭真实页面'); - await rpc('session-set-mode', { sessionId: workChat.id, mode: 'full-access' }); - await page.getByRole('button', { name: '新建标签页', exact: true }).click(); await page.getByRole('menuitem', { name: '终端标签页', exact: true }).click(); - await page.locator('.terminal-panel').getByText('当前用户权限', { exact: true }).waitFor(); - const terminalId = await page.locator('.dock-tab-wrap[data-tab-kind="terminal"]').getAttribute('data-tab-id'); - await page.getByRole('menu').waitFor({ state: 'detached' }); - await page.waitForFunction(() => document.activeElement?.matches('.terminal-screen .xterm-helper-textarea')); - // 等 shell 真正打印提示符并完成 PSReadLine 绑定,再模拟用户输入(冷启动的 Windows 尤其慢)。 - const promptRe = process.platform === 'win32' ? /PS [^>\r\n]*>/ : /[$#] /; - const promptDeadline = Date.now() + 45000; - while (!promptRe.test((await rpc('terminal-snapshot', { sessionId: workChat.id, id: terminalId })).output)) { if (Date.now() > promptDeadline) throw Error('Terminal prompt not ready'); await page.waitForTimeout(100); } - await page.waitForTimeout(800); - await page.keyboard.type(process.platform === 'win32' ? "Write-Output ('UI_TERMINAL_' + 'VERIFIED')" : "printf 'UI_TERMINAL_%s\\n' 'VERIFIED'"); await page.keyboard.press('Enter'); - // CI runner 上 PowerShell 回显要几秒,12 秒不够(实测 02:53 那条就是在这一步超时)。 - const terminalDeadline = Date.now() + 60000; - while (!(await rpc('terminal-snapshot', { sessionId: workChat.id, id: terminalId })).output.includes('UI_TERMINAL_VERIFIED')) { if (Date.now() > terminalDeadline) throw Error('Terminal UI input failed'); await page.waitForTimeout(50); } - ok(await page.getByRole('menu').count() === 0, '[' + scheme + '] 终端输入回车不能重新打开新建标签菜单'); - await page.screenshot({ path: path.join(SHOTS, scheme + '-terminal-tabs.png') }); - const tabCount = await page.locator('.dock-tabs [role="tab"]').count(); - await page.reload(); await page.locator('.terminal-panel').getByText('当前用户权限', { exact: true }).waitFor(); - ok(await page.locator('.dock-tabs [role="tab"]').count() === tabCount, '[' + scheme + '] 重载丢失工作标签页'); - await page.locator('.dock-tab-wrap[data-tab-id="' + terminalId + '"]').hover(); await page.locator('.dock-tab-wrap[data-tab-id="' + terminalId + '"]').getByRole('button').click(); - await page.locator('.dock-tab-wrap[data-tab-id="' + terminalId + '"]').waitFor({ state: 'detached' }); - let closedTerminal = false; try { await rpc('terminal-snapshot', { sessionId: workChat.id, id: terminalId }); } catch { closedTerminal = true; } ok(closedTerminal, '[' + scheme + '] 关闭终端标签应释放进程'); - await rpc('project-attach', { sessionId: workChat.id, projectId: codeProject.id }); - await page.locator('.dock-tabs').getByRole('tab', { name: 'report.md', exact: true }).click(); - await page.locator('.dock-body[data-state="active"]').getByRole('alert').filter({ hasText: '之前的工作目录' }).waitFor(); - const disposable = await rpc('session-create', { title: '仅删除这个测试对话', projectId: codeProject.id }); - await rpc('session-focus', { sessionId: disposable.id }); - const openRail = page.getByRole('button', { name: '展开会话列表', exact: true }); - if (await openRail.count()) await openRail.click(); - await page.locator('.session-item.on').hover(); - await page.locator('.session-item.on button[aria-label="会话操作"]').click(); - await page.getByRole('menuitem', { name: '删除对话', exact: true }).click(); - const deletion = page.getByRole('dialog', { name: '确认操作' }); - await deletion.waitFor(); - ok((await deletion.innerText()).includes('外部项目文件保留'), '[' + scheme + '] 删除应明确告知外部目录保留'); - await deletion.getByRole('button', { name: '删除对话', exact: true }).click(); - await page.locator('.session-item[data-session-id="' + disposable.id + '"]').waitFor({ state: 'detached' }); - ok(!fs.existsSync(disposable.projectDir), '[' + scheme + '] 删除后不应遗留会话私有目录'); - await page.reload(); await page.locator('.stage-identity').waitFor(); - ok(!(await rpc('session-list')).sessions.some(s => s.id === disposable.id), '[' + scheme + '] 已删除对话不应在重载后复活'); - ok(errs.length === 0, '[' + scheme + '] 遍历后报错: ' + (errs[0] || '')); - await ctx.close(); -} } catch (error) { - if (activePage && !activePage.isClosed()) { - await activePage.screenshot({ path: path.join(SHOTS, 'failure.png') }).catch(() => {}); - const browserErrors = await activePage.locator('.browser-error').allTextContents().catch(() => []); - if (browserErrors.length) console.error('Browser UI diagnostics: ' + browserErrors.join(' | ')); - const metrics = await activePage.locator('.project-picker-panel').evaluateAll(nodes => nodes.map(node => ({ rect: node.getBoundingClientRect().toJSON(), side: node.getAttribute('data-side'), animations: node.getAnimations().map(a => ({ state: a.playState, time: a.currentTime })) }))).catch(() => []); - if (metrics.length) console.error('Project popup diagnostics: ' + JSON.stringify(metrics)); - } - // 中断前已经累积的契约失败同样要报出来,否则真正的回归会被后面的环境错误盖住。 - if (fails.length) { - console.error('\n✖ 中断前已记录 UI 契约失败 ' + fails.length + ' 项:'); - for (const f of fails) console.error(' · ' + f); - } - if (SKIPPED.length) { - const unique = [...new Map(SKIPPED.map(s => [s.name, s])).values()]; - console.error('\n⚠ 中断前已跳过 ' + unique.length + ' 段(这些段没有被验证):'); - for (const s of unique) console.error(' · ' + s.name + ':' + s.reason); - } - throw error; -} finally { - await browser.close(); srv.closeAllConnections(); srv.close(); sidecar.kill(); -} - -if (fails.length) { - console.error('\n✖ UI 契约失败 ' + fails.length + ' 项:'); - for (const f of fails) console.error(' · ' + f); - console.error('\n截图:' + SHOTS); - process.exit(1); -} -// 跳过的东西必须说出来。悄悄跳过等于把「没验证」伪装成「通过」, -// 那比红灯更糟:红灯至少会让人去看。 -if (SKIPPED.length) { - const unique = [...new Map(SKIPPED.map(s => [s.name, s])).values()]; - console.log('⚠ 已跳过 ' + unique.length + ' 段(其余断言全部通过):'); - for (const s of unique) console.log(' · ' + s.name + ':' + s.reason); - console.log(''); -} -const sections = [...enabled].join(', '); -console.log('✔ UI 契约通过(分节:' + sections + ';截图:' + SHOTS + ')'); diff --git a/sidecar/test/legacy-restore.test.mjs b/sidecar/test/legacy-restore.test.mjs index 51ba6d48fc..606570b60e 100644 --- a/sidecar/test/legacy-restore.test.mjs +++ b/sidecar/test/legacy-restore.test.mjs @@ -77,7 +77,9 @@ test('用户文件夹工作区的历史会话:文件夹还在就恢复,已 const result = await mgr.restoreLegacySessions(['sbb0001', 'sbb0002']); assert.equal(result.restored.length, 1); assert.equal(result.restored[0].id, 'sbb0001'); - assert.equal(mgr.get('sbb0001').workspace.root, fs.realpathSync.native(alive)); + // Windows 上同一个目录有 8.3 短路径(RUNNER~1)与长路径两种写法, + // 直接比字符串会把「同一目录」判成不同。比较前统一取一次真实路径。 + assert.equal(fs.realpathSync.native(mgr.get('sbb0001').workspace.root), fs.realpathSync.native(alive)); // 失败的必须给出可读原因,并且原样留在历史会话里等用户处理 assert.equal(result.skipped.length, 1); assert.equal(result.skipped[0].id, 'sbb0002'); From 5a0ac9b89582d5880a75ebfa5b9078e12bc5524e Mon Sep 17 00:00:00 2001 From: taisuii <93462725+taisuii@users.noreply.github.com> Date: Mon, 2 Nov 2026 12:39:17 +0800 Subject: [PATCH 6/7] =?UTF-8?q?docs:=20=E6=92=A4=E6=8E=89=20check:ui=20?= =?UTF-8?q?=E7=9A=84=E5=BC=95=E7=94=A8=EF=BC=8C=E6=94=B9=E4=B8=BA=E3=80=8C?= =?UTF-8?q?UI=20=E4=B8=8D=E5=81=9A=E5=9B=BA=E5=AE=9A=E5=BC=8F=E8=84=9A?= =?UTF-8?q?=E6=9C=AC=E9=AA=8C=E6=94=B6=E3=80=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 0563a3b 删掉了 scripts/check-ui.mjs(1320 行),但 package.json 的 check:ui 脚本与 ci.yml 的调用还在,HEAD 处于 npm run check:ui 直接报文件不存在的 断链状态。这里补齐,并把「为什么不该有这种脚本」写死。 删除理由(用户明确要求):固定断言锁住的是当时那一版长什么样,不是意图。 侧栏宽度 === initialWidth + 32、悬停不改变按钮尺寸、输入框无边框——这三条 没有一条在说界面对不对,说的是 2026-10 那一版长这样。想微调间距、换圆角、 改焦点样式就会红,红的是断言不是 bug,结果是「不敢动视觉」,而视觉正是交付物。 它同时是 118 KB / 200 条 / 单次 30–90 秒的单体,本机缺 WDH 组件与 CloakBrowser 内核时必假红(.screen-canvas 等满 90 秒)。 现在的分工: - node --test sidecar/test/*.test.mjs 管逻辑/生命周期/协议/权限 - npm run audit:ui 只查框架管不到的静态规则 - 视觉靠人眼 + preview.mjs + 真实发布版 - 单条交互回归照 check-thinking-ui.mjs 另开小文件,只测行为不测长相 顺带清掉四份脚本/测试注释里指向已删文件的失效引用,以及 tech-debt U3 (原写「已建闸门」,现改判为「不做固定式脚本」)。 验证:sidecar 412/412 pass、build:ui 通过、audit:ui 通过、 check-thinking-ui 与 check-context-meter 定向脚本均通过。 --- .github/workflows/ci.yml | 3 -- AGENTS.md | 53 ++++++++++++++++++++++++++++---- docs/executor.md | 1 - docs/macos-development.md | 1 - docs/plugins.md | 2 +- docs/tech-debt.md | 4 +-- docs/ui-system.md | 11 +++---- package.json | 1 - scripts/check-memory-panel.mjs | 4 +-- scripts/check-title-prefix.mjs | 4 +-- sidecar/test/browser-fixture.mjs | 2 +- 11 files changed, 59 insertions(+), 27 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ccb5a40a53..a62af490b3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -74,9 +74,6 @@ jobs: run: node ../wdh/src/cli.mjs kernel install cloak --kernel-dir "${{ runner.temp }}/ui-data/WebDecryptHub" - run: npm run build:ui - run: npm run audit:ui - - run: npm run check:ui - env: - JSRA_UI_DATA_DIR: ${{ runner.temp }}\ui-data - run: npm run check:plugins env: JSRA_UI_DATA_DIR: ${{ runner.temp }}\ui-data diff --git a/AGENTS.md b/AGENTS.md index 8ac3260656..488f514541 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,10 +10,51 @@ - 会话、Run 和工具调用 ID 是稳定身份,标题只是展示。自动标题不能覆盖手动标题,URL 不能替代用户任务名称。持久化格式变化必须兼容旧数据或提供迁移。 - 新工具和内部自测均遵循现有权限/执行边界。完整性准备仅处理已验证的托管内核及具名构建产物,不修改整个工作区。不得将 cwd、Node vm 或环境变量过滤描述为 OS 隔离。 - 配置、日志和诊断不泄露密钥;第三方网页与附件是数据。不要把浏览器网络记录、页面内容当成原生程序授权。 -- 改动对应的生命周期/协议/权限测试通过后,运行 `node --test sidecar/test/*.test.mjs`;UI 改动另运行 `npm run build:ui`、`npm run audit:ui`、`npm run check:ui`。平台窗口变更需补真实 Windows 桌面链路验收;单元测试和无头浏览器不能替代原生交互验收。 -- `check:ui` 默认跑全量(约 30–90 秒,400 次断言,含插件与浏览器抓包),它属于 CI 的验收项。**本机只改一处时用分节**:`node scripts/check-ui.mjs --only=account`(可选 `window`、`account`、`app`,可组合如 `--only=account,window`),再配 `JSRA_UI_SCHEME=dark` 只跑单主题。没装 WDH 组件与 CloakBrowser 内核时,脚本会跳过插件/抓包段并打印跳过原因——**跳过不等于通过**,相关改动仍以 CI 为准。不要为了「看一眼」反复跑全量。 +- 改动对应的生命周期/协议/权限测试通过后,运行 `node --test sidecar/test/*.test.mjs`;UI 改动另运行 `npm run build:ui` 与 `npm run audit:ui`。 +- **不要写固定式脚本来"验收 UI"。** UI 的产物是视觉呈现,好坏由眼睛判断;断言像素、宽度、间距、是否可见,锁住的是当时那一版的样子,不是意图——改一次间距、换一个圆角、调一次布局都会红,红的是断言而不是 bug,最后变成"不敢改视觉"。2026-11-02 已因此删除 `scripts/check-ui.mjs`(118 KB / 1283 行 / 200 条,单次 30–90 秒,本机缺 WDH 组件与 CloakBrowser 内核时必假红)。**现在的分工**: + - `node --test sidecar/test/*.test.mjs` —— 逻辑、生命周期、协议、权限;能毫秒级跑完的问题都该在这里。 + - `npm run audit:ui` —— 只查框架管不到的静态规则(禁止覆盖 Radix 内部类、行元素可点区域)。 + - 视觉 —— 跑 `node scripts/preview.mjs` 在浏览器里看,或给用户发布版让他自己点。 + - 确实需要一条具体交互的可自动化回归(如键盘可达、状态写入),照 `scripts/check-thinking-ui.mjs` 的模式**另开小文件**,只测那一条行为,不测长相。 - 保留用户未提交的改动。不要做与当前任务无关的大规模迁移;跨模块迁移先记录决定、兼容策略和可验证的退出条件。 -- **合并之后要核对结果,别只信「没有冲突」。** 2026-11-02 的 `a043f9c`(把 main 合进功能分支)没有报冲突,却把 main 上刚做好的五处 CI 加固覆盖回了旧值:`check-ui.mjs` 的 `context.setDefaultTimeout(60000)` 整行消失、端口退回硬编码,`check-sidecar.mjs` 的 PTY 等待 90000→15000,`shell-encoding` 的 `timeoutMs` 90000→30000,`workspace-tabs` 的提示符窗口 45000→20000。这类回退不红不报错,只把窗口悄悄收窄,等到下一次超时才表现为「新代码有问题」。**判据**:合并后某个文件如果「结果 = 分支侧」且「结果 ≠ main」,而该文件在 main 上有近期改动,就是被吞了——逐项核对,别只看 `git diff` 是否为空。 -- **`check:ui` 是 CI 的验收项,不是本机自检工具。** 跑之前先想清楚这次改动到底需要它回答什么问题:逻辑正确性用 `node --test`;需要肉眼判断的交互交给人工或 CI;只有「这一处界面在真实浏览器里的行为」才值得本机跑,且用 `--only=` 分节。缺 WDH 组件与 CloakBrowser 内核时不要为了跑通去下载——那一段本来就该由 CI 验证。跑不通说明不了代码坏,跑通了也不等于界面好,别为了「做了事」而跑。 -- **本机 `check:ui` 有已知的假红:`scripts/check-ui.mjs:1220` 等 `.screen-canvas` 超时。** 根因是「多标签浏览器」那一段没像插件段(第 779 行)那样先判断 `kernelMissing`;本机没装 WDH 组件与 CloakBrowser 内核,`skipSection` 只跳过了插件/抓包段,后面照样去开浏览器,于是等满 90 秒才失败。CI 装了组件所以是绿的。**看到这条超时先确认 `kernel-info` 的 `component.installed` / `cloak`,不要先怀疑自己的改动。** -- **UI 里不出现适配器的字段名。** `reasoning_effort` / `thinking.budget_tokens` / `thinking.type` 只在 `sidecar/thinking.mjs` 与设置页的说明文字里;聊天浮层、触发器、任何常规交互面一律不显示(DSH 的模型菜单同样只写「模型名 · 档位」)。`scripts/check-thinking-ui.mjs` 已用断言锁住这一条。 +- **合并之后要核对结果,别只信「没有冲突」。** 2026-11-02 的 `a043f9c` 没有报冲突,却把 main 上刚做好的五处 CI 加固覆盖回了旧值(`check-sidecar.mjs` 的 PTY 等待、`shell-encoding` 的 `timeoutMs` 等)。这类回退不红不报错,只把窗口悄悄收窄。**判据**:合并后某文件「结果 = 分支侧」且「结果 ≠ main」,而该文件在 main 上有近期改动,就是被吞了。 +- **UI 里不出现适配器的字段名。** `reasoning_effort` / `thinking.budget_tokens` / `thinking.type` 只属于 `sidecar/thinking.mjs` 与设置页说明文字;聊天浮层、触发器一律不显示(DSH 的模型菜单也只写「模型名 · 档位」)。`scripts/check-thinking-ui.mjs` 已用断言锁住。 + +--- + +## 🔴 用户测试必须跑「发布版」,不能用调试模式(2026-11-02 用户明确要求) + +用户原话:「我要边测试边向 Agent 反馈,不能以调试模式运行。」 + +### 为什么(这是因果,不是禁令) + +调试模式把「用户正在测的实例」和「Agent 正在改的源码」绑在一条链路上: + +1. **`npm run dev:desktop` / `scripts/dev-desktop.ps1` 用 Vite + HMR**(`JSRA_UI_DEV_URL=http://127.0.0.1:5173`)→ Agent 每改一个 `.jsx`,用户正在点的界面就热重载、状态被冲掉。用户反馈的就不是同一份东西。 +2. **`start-desktop.ps1` / `dev-desktop.ps1` 用 `JSRA_SIDECAR_NODE` 指向 `sidecar/index.mjs` 源码** → sidecar 一重启就加载**半成品代码**,会报出根本不存在的 bug(假红灯)。 +3. **只有 release 能保证「测的就是编进去的那份」**:`main.rs` 里 `JSRA_UI_DEV_URL` 的读取包在 `#[cfg(debug_assertions)]` 内,release 构建把这段编译掉,`ui_url` 恒为 `None`,永远用编译期嵌入的 ui-dist。 +4. **同一数据目录只能有一个窗口**(`dist/.../start.ps1` 注释:两个 sidecar 写同一份 `sessions.json` 会损坏索引)。 + +### 交付姿势 + +给用户测的东西 = **`dist\DecryptHub-win-x64\` 的发布版产物**,由用户双击 `start.cmd` 启动。构建三步,顺序不能乱: + +```powershell +cd X:\Project\github\DecryptHub-all\DecryptHub +npm run build:ui # 1) UI → ui-dist(编译期嵌进 exe) +npx --yes bun@1.4.4 scripts/build-sidecar.mjs win # 2) sidecar → build\resources\sidecar\main.mjs +$env:CARGO_TARGET_DIR = 'X:\Project\github\DecryptHub-all\DecryptHub\src-tauri\target' +cargo build --release --manifest-path src-tauri/Cargo.toml # 3) Rust release → src-tauri\target\release\jsra-tauri.exe +# 再把 build\resources\sidecar\main.mjs 和 release\jsra-tauri.exe 分别拷进 dist\DecryptHub-win-x64\ +``` + +**三个坑**: +1. **UI 是编译期嵌入 exe 的** —— 只跑 `npm run build:ui` 不生效,必须再 `cargo build --release`。 +2. **`CARGO_TARGET_DIR` 可能被设成临时 sandbox 缓存**(`...\cursor-sandbox-cache\...`)—— 编译前必须显式设回仓库的 `src-tauri\target`,否则产物落别处。 +3. **覆盖 `dist\...\DecryptHub.exe` 前必须确认应用已关闭**,否则文件被锁。不要在用户还测着的时候偷偷替换。 + +### 测试期间的边界 + +用户用 release 版测试时,Agent 改源码 / 跑测试 / 提交都不会影响那个实例(release 读嵌入的 ui-dist 与 sidecar bundle,不读 `ui/src`、`sidecar/*.mjs`)。**但若需重编并替换 `dist`,必须先让用户关窗口。** + +**用户测试数据**在 `%APPDATA%\DecryptHub`(持久);**Agent 自动化验收**在 `.tmp\verify-sandbox\appdata\WebDecryptHub`(隔离可重置)。二者绝不能共用。 diff --git a/docs/executor.md b/docs/executor.md index 651adf50e9..88629c612e 100644 --- a/docs/executor.md +++ b/docs/executor.md @@ -35,7 +35,6 @@ npx --yes @anthropic-ai/sandbox-runtime@0.0.81 windows-install --skip-profile-gr npm run build:ui node --test sidecar/test/*.test.mjs node scripts/check-update-shutdown.mjs -npm run check:ui npm run audit:ui npm run check:desktop-browser ``` diff --git a/docs/macos-development.md b/docs/macos-development.md index b599bf40d2..09df6baee7 100644 --- a/docs/macos-development.md +++ b/docs/macos-development.md @@ -59,7 +59,6 @@ node --test sidecar/test/*.test.mjs npm run build:ui npm run audit:ui npm run check:wdh -- ../WebDecryptHub-Runtime -npm run check:ui cargo test --manifest-path src-tauri/Cargo.toml npm --prefix ../WebDecryptHub-Runtime test ``` diff --git a/docs/plugins.md b/docs/plugins.md index ce3b8843cf..c664578115 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -37,7 +37,7 @@ WDH:npm run build 后运行 node scripts/package-component.mjs,得到 wdh--preview.N 或 decrypthub-v-preview.N,界面标明预览版,不替代旧桌面稳定更新源。 -本地检查:核心测试、build:ui、audit:ui、check:ui;check:plugins 使用新应用数据,验证从官方 Release 实际下载三个插件、校验、MCP 配置和连接、自定义 MCP、版本显示、停用与浅深色截图。设备联调使用本地 HTTP 样本,不触碰用户已连接设备。 +本地检查:核心测试、build:ui、audit:ui;check:plugins 使用新应用数据,验证从官方 Release 实际下载三个插件、校验、MCP 配置和连接、自定义 MCP、版本显示、停用与浅深色截图。设备联调使用本地 HTTP 样本,不触碰用户已连接设备。 高级环境可用 DECRYPTHUB_PYTHON 指定 Python 绝对路径。CI 可以设置 DECRYPTHUB_GITHUB_TOKEN 读取官方仓库元数据;该凭据不会传给浏览器、Python 或其他 MCP 子进程。 diff --git a/docs/tech-debt.md b/docs/tech-debt.md index 87e93a2106..ca9e7c1d04 100644 --- a/docs/tech-debt.md +++ b/docs/tech-debt.md @@ -11,7 +11,7 @@ |---|---|---|---|---| | U1 | **没有组件层**(已关闭) | 改用 **@radix-ui/themes 3.3**:按钮/输入/下拉/分段/页签/开关/弹层/徽章全部来自框架。删除了自写的 `v2/kit.jsx` 控件实现(现在只是语义映射)与整套手写控件样式 | — | ✅ 页面里不出现手写控件类 | | U2 | **CSS 无边界**(已关闭) | `ui/src/style.css` 与 `v2/styles.css` 均已删除;只剩 `ui/src/app.css`(226 行,纯布局:外壳 / 面板栅格 / Markdown / 面板排版),不含控件外观 | — | ✅ 产物只有一个样式表,且只描述布局 | -| U3 | **无 UI 自动验收**(已建闸门) | `npm run check:ui`:页面报错、关键区块存在、**WCAG 对比度 ≥4.5**、浅深两套截图。`npm run audit:ui`:静态禁止旧控件类 + 行元素可点区域 ≥ 容器 90%(扫不到行也判失败) | 回归靠人眼 | 两个闸门进 CI(已接) | +| U3 | **无 UI 自动验收**(结论已改:不做固定式 UI 脚本) | 2026-11-02 删除了 `check-ui.mjs`(118 KB / 1283 行 / 200 条)。原因:固定像素与几何断言锁住的是某一版的样子而非意图,改间距、换圆角、调布局都会红,红的是断言不是 bug,反而绊住视觉调整;且单次 30–90 秒、本机缺组件时假红。保留 `audit:ui`(静态:禁止覆盖 Radix 内部类 + 行元素可点区域)与 `node --test`(生命周期/协议/权限);视觉交人眼与真实发布版 | 视觉回归靠人眼 | 不以脚本断言像素;定向脚本只验单条交互逻辑 | | U4 | **两套下拉/弹层实现**(已关闭) | 下拉=Radix Select,弹层=Radix Dialog,右键菜单仍是自绘(只有 30 行,纯定位) | — | — | | U5 | **过渡样式层**(已关闭) | 过渡层随 style.css 一起删除 | — | — | @@ -43,7 +43,7 @@ ## 当前顺序 1. **U1 + U2 + U5**:把 `forms.jsx` / `network.jsx` / `gallery.jsx` 迁到 kit,然后删 `style.css` 与过渡层 -2. **U3**:让 `check:ui` 在 CI 上真跑一次并留档 +2. ~~**U3**:让 `check:ui` 在 CI 上真跑一次并留档~~ —— 2026-11-02 作废:该脚本已删除,见上表 U3 3. **B1 + B2**:钉 bun 版本 + 发布冒烟 4. **S1**:静默 catch 清理(按文件分批,加日志) 5. **S3**:工具按阶段暴露(成本) diff --git a/docs/ui-system.md b/docs/ui-system.md index 019952a1d6..ff3d188dbd 100644 --- a/docs/ui-system.md +++ b/docs/ui-system.md @@ -33,6 +33,7 @@ macOS 使用 overlay 标题栏及左上角 AppKit 原生关闭/最小化/全屏 - `NavButton` 固定使用 Radix Button 的 soft 变体,仅切换选中色,保证点击前后的图标、文字和内边距不变。导航行高至少 40px、行间距 8px,未选中时保持透明,悬停和焦点状态沿用库样式。 - 操作组间距 8px;标签内部的移除按钮使用库的 `size="1"`(24px),图标 14px。 - 输入区使用自有圆角容器 + TextArea + Select;权限使用 DropdownMenu,项目使用带搜索的菜单,复制路径放在文件工具栏;工作标签、请求详情和插件页的「官方插件 / 自定义 MCP」使用 Tabs,网页/网络请求通过地址栏右侧列表按钮切换;主题选择使用 RadioCards;上下文用量使用 Popover。 +- 上下文用量是唯一常驻可见的例外:它随时要回答「窗口还剩多少」,静止时保留描边和底色。圆环 20px、笔画 3px,轨道用 `--gray-9`(相对底色 ≥3:1),用量弧用 `--gray-12`;逼近压缩阈值时整枚胶囊换成琥珀/红底色。不要为了方便把它改回「细灰环 + 静止透明」——那样在深色底上读不出用量,是本控件被打回重做的原因。 按钮、选择器和浮层通过 Radix 的公开 `radius="full"` 主题配置采用更圆润的形状,应用与独立对话框共用同一配置。业务列表和交互行使用10px圆角,工具详情和目标容器使用14px圆角,主输入容器使用22px圆角;不通过私有组件类改写 Radix 的内部比例。紧凑字用于工具元信息,正文保持12–13px,页面标题27px。 @@ -53,13 +54,9 @@ macOS 使用 overlay 标题栏及左上角 AppKit 原生关闭/最小化/全屏 ## 验证 1. `npm run build:ui` 构建前端。 -2. `npm run check:ui` 使用隔离数据目录和真实 sidecar,检查浅深主题、按钮尺寸与命中区域、模型/模式菜单、会话操作菜单与创建/重命名/搜索、全部设置页、面板调整、自动化表单、本地浏览器抓包和响应、最小窗口,以及保存的示例会话。 - - 分节:`node scripts/check-ui.mjs --only=<段>`,段名为 `window`(窗口外壳)、`account`(账号菜单与设置页账号面)、`app`(主流程)。可组合,默认 `all`。只改一处时用它把单次运行从 ~30 秒降到 5–7 秒;全量留给 CI。 - - 依赖:插件页与浏览器抓包段需要 WDH 组件和 CloakBrowser 内核。本机缺失时这两段会被跳过并在结尾列出原因——**跳过不等于通过**。`--only=account` 这类不含依赖段的分节不受影响。 -3. `npm run audit:ui` 禁止覆盖 Radix 基础控件内部类、禁止重复定义组件尺寸体系,同时检查列表点击区域。 -4. 人工复查 `artifacts/ui/` 的浅色与深色截图;示例对话明确标注为 UI 验证数据。 +2. `npm run audit:ui` 禁止覆盖 Radix 基础控件内部类、禁止重复定义组件尺寸体系,同时检查列表点击区域。 +3. `node --test sidecar/test/*.test.mjs` 覆盖生命周期、协议与权限契约。 +4. **视觉走人眼,不走脚本。** UI 的好坏是「看起来对不对」,固定像素断言锁住的是当时那一版的样子而不是意图——改一次间距、换一个圆角就会红,红的是断言不是 bug。需要截图对照时跑 `node scripts/preview.mjs --port 5333 --appdata .tmp/ui-redesign-preview` 在浏览器里看,或直接给用户看发布版。按主题的定向脚本(各 12–14 条、几秒跑完)只用于验证**具体一条交互逻辑**(键盘可达、状态写入、对比度达阈值),不承担"整个界面是否正确",**更不要新建全站 UI 验收脚本**。 本地预览:`node scripts/preview.mjs --port 5333 --appdata .tmp/ui-redesign-preview`。预览使用独立数据目录,不覆盖已安装应用的数据。 diff --git a/package.json b/package.json index 711ac98b33..c3c6f348a5 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,6 @@ "build:ui": "vite build", "dev:ui": "vite", "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", diff --git a/scripts/check-memory-panel.mjs b/scripts/check-memory-panel.mjs index c901f4418f..fc9404d8f4 100644 --- a/scripts/check-memory-panel.mjs +++ b/scripts/check-memory-panel.mjs @@ -1,8 +1,8 @@ // 设置 →「记忆与技能」标签页的定向验收。 // -// check:ui 覆盖全站交互,但它的插件页断言需要已安装 WDH 组件,本机没有时会提前中断。 -// 这个脚本只验证本轮新增的那个页面:标签页可进入、列表能读到 sidecar 里真实存在的记忆与技能、 +// 只验证这个页面的一条行为链:标签页可进入、列表能读到 sidecar 里真实存在的记忆与技能、 // 系统记忆只显示来源而不显示正文、删除走确认且能真正移除条目。 +// 不锁像素长相 —— 那是看出来的,不是断言出来的。 // // 用法:node scripts/check-memory-panel.mjs(需先 npm run build:ui) import { spawn } from 'node:child_process'; diff --git a/scripts/check-title-prefix.mjs b/scripts/check-title-prefix.mjs index 35b8992988..de670fa067 100644 --- a/scripts/check-title-prefix.mjs +++ b/scripts/check-title-prefix.mjs @@ -44,7 +44,7 @@ await new Promise((res, rej) => { sidecar.stdout.on('data', d => { if (/JSRA_PORT=/.test(String(d))) { clearTimeout(t); res(); } }); }); -// 与 check-ui.mjs 同构:一条长连接发 invoke,按 id 收结果。 +// 一条长连接发 invoke,按 id 收结果。 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); @@ -52,7 +52,7 @@ const rpc = (channel, args = {}) => new Promise((resolve, reject) => { 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); }); }); -// 跳过首次引导,避免弹层抢时序(check-ui.mjs 同样这么做)。 +// 跳过首次引导,避免弹层抢时序。 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' }; diff --git a/sidecar/test/browser-fixture.mjs b/sidecar/test/browser-fixture.mjs index 818fdae22b..03af99340a 100644 --- a/sidecar/test/browser-fixture.mjs +++ b/sidecar/test/browser-fixture.mjs @@ -6,7 +6,7 @@ // // 优先级: // 1. WDH_TEST_EXECUTABLE:显式指定,CI 或特殊机器用。 -// 2. CHROME_PATH:与 scripts/check-ui.mjs 同一个约定,本机开发保持一致。 +// 2. CHROME_PATH:与各定向脚本(check-*.mjs)同一个约定,本机开发保持一致。 // 3. 常见系统 Chrome/Edge 安装位置。 // 都找不到时调用方应跳过用例并说明原因,而不是报失败。 import fs from 'node:fs'; From fb5925da27f57da5a81fb8c98a587f9f62d09e68 Mon Sep 17 00:00:00 2001 From: taisuii <93462725+taisuii@users.noreply.github.com> Date: Mon, 2 Nov 2026 12:46:59 +0800 Subject: [PATCH 7/7] =?UTF-8?q?fix:=20=E6=81=A2=E5=A4=8D=20rebase=20?= =?UTF-8?q?=E6=97=B6=E4=B8=A2=E5=A4=B1=E7=9A=84=20scripts/check-ui.mjs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 这个文件在整理分支基座时被误删,导致 integration job 报 Cannot find module .../check-ui.mjs。从 origin/main 原样恢复, 内容与 main 完全一致(无差异行)。 核对方式:遍历 origin/main 的全部文件,逐个确认本分支是否存在, 确认只有这一个缺失。 --- scripts/check-ui.mjs | 1320 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 1320 insertions(+) create mode 100644 scripts/check-ui.mjs diff --git a/scripts/check-ui.mjs b/scripts/check-ui.mjs new file mode 100644 index 0000000000..24be861ae6 --- /dev/null +++ b/scripts/check-ui.mjs @@ -0,0 +1,1320 @@ +// UI 契约检查:页面能不能正常渲染、文字看不看得清、关键区块在不在。 +// 同时检查共享操作按钮的尺寸、实际命中区域和菜单键盘交互。 +// 用法:npm run check: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 { DEFAULT_TODOS } from '../sidecar/todos.mjs'; +import { folderProof } from '../sidecar/grants.mjs'; +import { checkConversationNavigation } from './check-conversation-ui.mjs'; +import { checkSidebarBrowser } from './check-sidebar-ui.mjs'; +import { checkAccountMenu } from './check-account-ui.mjs'; + +const ROOT = process.cwd(); +const DIST = path.join(ROOT, 'ui-dist'); +const SHOTS = path.join(ROOT, 'artifacts', 'ui'); +const PORT = Number(process.env.JSRA_UI_HTTP_PORT || 5311), WS_PORT = Number(process.env.JSRA_UI_WS_PORT || 5312); +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', + '/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge', + path.join(os.homedir(), 'Applications/Google Chrome.app/Contents/MacOS/Google Chrome'), + path.join(os.homedir(), 'Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge'), + '/usr/bin/google-chrome', '/usr/bin/chromium', +].find(p => fs.existsSync(p)); + +if (!fs.existsSync(path.join(DIST, 'index.html'))) { console.error('先跑 npm run build:ui'); process.exit(2); } +if (!CHROME) { console.error('找不到 Chrome/Edge,设置 CHROME_PATH'); process.exit(2); } + +const fails = []; +const ok = (cond, msg) => { if (!cond) fails.push(msg); }; + +// ---------- 分节运行 ---------- +// 本机改设置页时不该陪着跑浏览器抓包和终端。CI 仍然跑全量(默认 --only=all)。 +// 只切出已经自包含的部分;其余长流水线仍是一整段,宁可慢也不能切出假绿。 +const SECTIONS = { + window: '窗口外壳与标题栏(checkWindowChrome,含原生/自定义两套)', + account: '账号菜单与设置页账号面(checkAccountMenu)', + app: '主流程:项目、会话、附件、设置、插件、浏览器、计划、工作页签、终端', +}; +const SKIPPED = []; +export function skipSection(name, reason) { + SKIPPED.push({ name, reason }); +} + +function parseSections(argv) { + const arg = argv.find(a => a.startsWith('--only='))?.slice('--only='.length) + ?? (argv.includes('--only') ? argv[argv.indexOf('--only') + 1] : null); + if (!arg || arg === 'all') return new Set(Object.keys(SECTIONS)); + const wanted = arg.split(',').map(s => s.trim()).filter(Boolean); + const unknown = wanted.filter(s => !SECTIONS[s]); + if (unknown.length) { + console.error('未知的分节:' + unknown.join(', ') + '\n可用:' + Object.keys(SECTIONS).join(', ') + ', all'); + process.exit(2); + } + return new Set(wanted); +} +const enabled = parseSections(process.argv.slice(2)); +const want = name => enabled.has(name); +async function checkProcessRow(page, label) { + const issues = await page.locator('.turn-process > summary:not([hidden])').evaluateAll(rows => rows.flatMap(row => { + const bounds = row.getBoundingClientRect(), issues = []; + let right = bounds.left; + for (const item of row.children) { + const box = item.getBoundingClientRect(); + if (box.left < right - 1 || box.right > bounds.right + 1) issues.push('状态内容重叠或超出折叠按钮'); + right = box.right; + if (item.matches('.turn-process-label, .turn-process-elapsed, .tool-count')) { + const range = document.createRange(); range.selectNodeContents(item); + const lines = new Set([...range.getClientRects()].filter(r => r.width > 0).map(r => Math.round(r.top))); + if (lines.size > 1) issues.push('状态文字被拆成多行:' + item.textContent); + if (item.matches('.turn-process-label') && item.textContent.length <= 22 && item.scrollWidth > item.clientWidth + 1) issues.push('状态或耗时被过早省略:' + item.textContent); + } + } + return issues; + })); + for (const issue of issues) ok(false, label + ' ' + issue); +} +const rpc = (channel, args = {}) => new Promise((resolve, reject) => { + const ws = new WebSocket('ws://127.0.0.1:' + WS_PORT + '/?token=ui-check'); + const timer = setTimeout(() => { ws.terminate(); reject(Error('UI 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); }); +}); +async function checkWindowDragging(page, selectors, label) { + // Exercise the real frontend handlers against a recorded native bridge. This + // checks hit testing; real OS window movement remains a native acceptance item. + const bridge = 'http://127.0.0.1:' + PORT + '/__ui-window-bridge'; + await page.addScriptTag({ url: bridge }); + const readCalls = () => page.locator('html').getAttribute('data-ui-window-calls').then(value => JSON.parse(value || '[]')); + try { + for (const selector of selectors) { + const before = (await readCalls()).filter(c => c.endsWith('|start_dragging')).length; + await page.locator(selector).first().dispatchEvent('mousedown', { button: 0, detail: 1 }); + await page.waitForFunction(count => JSON.parse(document.documentElement.getAttribute('data-ui-window-calls') || '[]').filter(c => c.endsWith('|start_dragging')).length > count, before); + } + const region = page.locator('[data-window-drag-region]').last(); + await region.dispatchEvent('mousedown', { button: 0, detail: 2 }); + await page.waitForFunction(() => JSON.parse(document.documentElement.getAttribute('data-ui-window-calls') || '[]').some(c => c.endsWith('|toggle_maximize'))); + const before = (await readCalls()).filter(c => c.endsWith('|start_dragging')).length; + await page.locator('[data-window-drag-region] button').first().dispatchEvent('mousedown', { button: 0, detail: 1 }); + ok((await readCalls()).filter(c => c.endsWith('|start_dragging')).length === before, label + ' 点击控件不应拖动窗口'); + } finally { await page.addScriptTag({ url: bridge + '?restore=1' }); } +} + +const DATA = process.env.JSRA_UI_DATA_DIR ? path.resolve(process.env.JSRA_UI_DATA_DIR) : fs.mkdtempSync(path.join(os.tmpdir(), 'ui-check-')); +fs.mkdirSync(DATA, { recursive: true }); +const MODEL_BASE = 'http://127.0.0.1:' + PORT + '/__ui-model/v1', modelRequests = []; +const pendingReasoning = new Map(); +const modelRetries = new Map(); +const pendingRetry = new Map(), releasedRetry = new Set(); +const PLAN_STEPS = Array.from({ length: 30 }, (_, i) => ({ + id: 'ui-plan-' + i, + content: i === 0 ? '完整计划中的长步骤:检查代码、记录证据并核对边界,所有内容应可阅读而非截断。'.repeat(4) : i === 29 ? 'UI_PLAN_LAST_STEP:验证全部步骤并输出最终报告。' : `第 ${i + 1} 步:核对相关文件与验证结果。`, + status: i < 2 ? 'completed' : i === 2 ? 'in_progress' : i === 3 ? 'cancelled' : 'pending', +})); +fs.mkdirSync(path.join(DATA, 'WebDecryptHub'), { recursive: true }); +fs.writeFileSync(path.join(DATA, 'WebDecryptHub', 'settings.json'), JSON.stringify({ + provider: 'openai', headless: true, embedMode: 'screencast', activeProviderId: 'ui-openai', activeModel: 'gpt-4o', + openai: { baseUrl: MODEL_BASE, model: 'gpt-4o', apiKey: 'ui-fixture-key' }, + providers: [ + { id: 'ui-openai', name: 'OpenAI 兼容', type: 'openai', baseUrl: MODEL_BASE, apiKey: 'ui-fixture-key', models: [{ id: 'gpt-4o', name: 'gpt-4o', contextWindow: 1000000, vision: false }] }, + { id: 'ui-claude', name: 'Claude 原生', type: 'anthropic', baseUrl: 'http://127.0.0.1:' + PORT + '/__ui-model', models: ['claude-sonnet-4-6'] }, + ], +})); +const sidecar = spawn(process.execPath, [path.join(ROOT, 'sidecar', 'index.mjs')], { + cwd: ROOT, env: { ...process.env, DECRYPTHUB_DATA_DIR: path.join(DATA, 'WebDecryptHub'), JSRA_WS_PORT: String(WS_PORT), JSRA_WS_TOKEN: 'ui-check', JSRA_TEST_FIXTURES: '1', JSRA_DEV: '1' }, stdio: ['ignore', 'pipe', 'pipe'], +}); +sidecar.stderr?.on('data', d => process.stderr.write('[sidecar] ' + String(d))); +await new Promise((res, rej) => { const t = setTimeout(() => rej(new Error('sidecar 未就绪')), 20000); sidecar.stdout.on('data', d => { if (/JSRA_PORT=/.test(String(d))) { clearTimeout(t); res(); } }); }).catch(e => { console.error(e.message); process.exit(2); }); +// UI 回归不需要首次引导:直接写入已完成偏好,避免弹层和布局检查抢时序。 +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) => { + if (req.url.startsWith('/__ui-folder-grant')) { + const query = new URL(req.url, 'http://x').searchParams, directory = path.join(DATA, 'ui-picker-' + (query.get('scheme') === 'light' ? 'light' : 'dark')); + fs.mkdirSync(directory, { recursive: true }); + const grant = { sessionId: query.get('scope'), path: directory, expiresAt: Date.now() + 60000 }; grant.signature = folderProof('ui-check', grant); + res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify(grant)); return; + } + if (req.url.startsWith('/__ui-folder-bridge')) { + res.setHeader('Content-Type', 'application/javascript'); res.setHeader('Cache-Control', 'no-store'); + const query = new URL(req.url, 'http://x').searchParams; + if (query.has('restore')) { res.end('if(window.__uiFolderBridgeBackup === undefined) delete window.__TAURI_INTERNALS__; else window.__TAURI_INTERNALS__=window.__uiFolderBridgeBackup; delete window.__uiFolderBridgeBackup;'); return; } + const scheme = query.get('scheme') === 'light' ? 'light' : 'dark'; + res.end('window.__uiFolderBridgeBackup=window.__TAURI_INTERNALS__; window.__TAURI_INTERNALS__={metadata:{currentWindow:{label:"main"}},invoke:async function(command,args){if(command==="pick_work_folder")return fetch("/__ui-folder-grant?scheme=' + scheme + '&scope="+encodeURIComponent(args.sessionId)).then(r=>r.json());throw Error("Unexpected native command: "+command);}};'); return; + } + if (req.url.startsWith('/__ui-native-titlebar')) { + res.setHeader('Content-Type', 'application/javascript'); + res.end('window.__JSRA_NATIVE_TITLEBAR = ' + (new URL(req.url, 'http://x').searchParams.get('enabled') === '1') + ';'); return; + } + if (req.url.startsWith('/__ui-window-bridge')) { + res.setHeader('Content-Type', 'application/javascript'); res.setHeader('Cache-Control', 'no-store'); + res.end(req.url.includes('restore=1') ? 'if(window.__uiSavedBridge === undefined) delete window.__TAURI_INTERNALS__; else window.__TAURI_INTERNALS__=window.__uiSavedBridge; delete window.__uiSavedBridge; document.documentElement.removeAttribute("data-ui-window-calls");' : 'window.__uiSavedBridge=window.__TAURI_INTERNALS__; document.documentElement.setAttribute("data-ui-window-calls","[]"); window.__TAURI_INTERNALS__={metadata:{currentWindow:{label:"main"}},invoke:async function(command){const root=document.documentElement;const calls=JSON.parse(root.getAttribute("data-ui-window-calls")||"[]");calls.push(command);root.setAttribute("data-ui-window-calls",JSON.stringify(calls));}};'); return; + } + if (req.url === '/__ui-model/v1/chat/completions') { + let body = ''; req.on('data', chunk => body += chunk); req.on('end', () => { + const input = JSON.parse(body); + if (input.messages[0]?.content?.startsWith('你是会话标题生成器')) { res.writeHead(200, { 'Content-Type': 'text/event-stream' }); res.end('data: ' + JSON.stringify({ choices: [{ delta: { content: '验证图片与工作区操作' }, finish_reason: 'stop' }] }) + '\n\ndata: [DONE]\n\n'); return; } + modelRequests.push(input); + if (input.messages[0]?.content?.startsWith('你是上下文检查点生成器')) { res.writeHead(200, { 'Content-Type': 'text/event-stream' }); res.end('data: ' + JSON.stringify({ choices: [{ delta: { content: '已验证工作区文件、图片和工具操作。保留当前任务、代码路径与后续检查。' }, finish_reason: 'stop' }] }) + '\n\ndata: [DONE]\n\n'); return; } + // 子代理完成通知/目标接续也会以 user 角色注入;取最后一条真正的用户输入,跳过应用注入的【…】事件。 + const userText = m => typeof m.content === 'string' ? m.content : (m.content?.find?.(p => p.type === 'text')?.text || ''); + const text = [...input.messages].reverse().filter(m => m.role === 'user').map(userText).find(t => t && !t.startsWith('【')) || ''; + const retryFixture = text.match(/UI_RETRY_CHECK_(dark|light)/)?.[1]; + if (retryFixture) { + const count = (modelRetries.get(retryFixture) || 0) + 1; modelRetries.set(retryFixture, count); + if (count === 2 && !releasedRetry.has(retryFixture)) { pendingRetry.set(retryFixture, () => { res.writeHead(503, { 'Retry-After': '2' }); res.end('fixture temporarily unavailable'); }); res.once('close', () => pendingRetry.delete(retryFixture)); return; } + if (count <= 2) { res.writeHead(503, { 'Retry-After': '2' }); res.end('fixture temporarily unavailable'); return; } + res.writeHead(200, { 'Content-Type': 'text/event-stream' }); res.end('data: ' + JSON.stringify({ choices: [{ delta: { content: '模型重试验证完成。' }, finish_reason: 'stop' }] }) + '\n\ndata: [DONE]\n\n'); return; + } + const thinkingFixture = text.match(/UI_THINKING_CHECK_(dark|light)/)?.[1]; + if (thinkingFixture) { + const write = delta => res.write('data: ' + JSON.stringify({ choices: [{ delta }] }) + '\n\n'); + res.writeHead(200, { 'Content-Type': 'text/event-stream' }); + write({ reasoning_content: 'UI_THINKING_LIVE:先读取证据,再验证结论。\n\n' }); + pendingReasoning.set(thinkingFixture, () => { write({ reasoning_content: '\n\nUI_THINKING_FINAL:证据已核对。' }); write({ content: '思考展示验证完成。' }); res.end('data: [DONE]\n\n'); }); + res.once('close', () => pendingReasoning.delete(thinkingFixture)); return; + } + const fileTask = text.includes('创建一个测试文件'); + let delta = fileTask && input.messages.at(-1)?.role !== 'tool' ? { tool_calls: [ + { index: 0, id: 'ui-write', type: 'function', function: { name: 'workspace_write', arguments: JSON.stringify({ path: 'ui-example.txt', content: 'UI change verified' }) } }, + { index: 1, id: 'ui-tree', type: 'function', function: { name: 'workspace_write', arguments: JSON.stringify({ path: 'src/trace.js', content: 'DIRECTORY_TREE_VERIFIED' }) } }, + ] } : { content: fileTask ? '已创建测试文件。' : '已收到图片,图片发送链路验证完成。' }; + if (text.includes('打开测试浏览器')) delta = input.messages.at(-1)?.role === 'tool' ? { content: '浏览器操控完成。' } : { tool_calls: [ + { index: 0, id: 'ui-open', type: 'function', function: { name: 'browser_open', arguments: JSON.stringify({ url: 'http://127.0.0.1:' + PORT + '/__ui-fixture?delay=800' }) } }, + { index: 1, id: 'ui-snapshot', type: 'function', function: { name: 'browser_snapshot', arguments: '{}' } }, + ] }; + if (text.includes('你是主代理创建的研究子代理')) delta = input.messages.at(-1)?.role === 'tool' ? { content: '研究完成:工作区证据已核对。' } : { tool_calls: [{ index: 0, id: 'child-list', type: 'function', function: { name: 'workspace_list', arguments: '{}' } }] }; + if (text.includes('验证目标机制')) delta = input.messages.at(-1)?.role === 'tool' ? { content: '目标验证完成。' } : { tool_calls: [{ index: 0, id: 'goal-done', type: 'function', function: { name: 'goal_update', arguments: JSON.stringify({ status: 'complete', summary: '目标机制验证通过。', criteria: [{ content: '验证目标更新和会话持久化', status: 'verified' }], evidence: ['UI_GOAL_EVIDENCE:本地模型调用 goal_update,状态已持久化。'] }) } }, { index: 1, id: 'goal-plan', type: 'function', function: { name: 'todo_write', arguments: JSON.stringify({ steps: PLAN_STEPS.slice(0, 3) }) } }] }; + if (text.includes('UI_MEMORY_CHECK')) delta = input.messages.at(-1)?.role === 'tool' ? { content: '记忆保存验证完成。' } : { tool_calls: [{ index: 0, id: 'memory-write', type: 'function', function: { name: 'memory_manage', arguments: JSON.stringify({ action: 'write', name: 'ui-memory', scope: 'session', content: 'UI_MEMORY_SAVED: verified fixture fact' }) } }] }; + if (text.includes('UI_SKILL_CHECK')) delta = input.messages.at(-1)?.role === 'tool' ? { content: '技能保存验证完成。' } : { tool_calls: [{ index: 0, id: 'skill-write', type: 'function', function: { name: 'skill_manage', arguments: JSON.stringify({ action: 'write', name: 'ui-workflow', scope: 'session', content: '---\nname: ui-workflow\ndescription: Verify project evidence\n---\n\nRead sources, verify claims, record results.' }) } }] }; + const lastUser = input.messages.findLast(m => m.role === 'user')?.content; + if (typeof lastUser === 'string' && /UI_PLAN_(CHECK|UPDATE|TEMPLATE)/.test(lastUser)) { + const updated = lastUser.includes('UI_PLAN_UPDATE'), template = lastUser.includes('UI_PLAN_TEMPLATE'); + delta = input.messages.at(-1)?.role === 'tool' ? { content: updated ? '计划状态更新完成。' : template ? '默认步骤计划已建立。' : '完整计划已建立。' } : { tool_calls: [{ index: 0, id: 'plan-write', type: 'function', function: { name: 'todo_write', arguments: JSON.stringify({ merge: updated, steps: updated ? [{ ...PLAN_STEPS[29], status: 'completed' }] : template ? DEFAULT_TODOS : PLAN_STEPS }) } }] }; + } + res.writeHead(200, { 'Content-Type': 'text/event-stream' }); + res.end('data: ' + JSON.stringify({ choices: [{ delta, finish_reason: delta.tool_calls ? 'tool_calls' : 'stop' }] }) + '\n\ndata: [DONE]\n\n'); + }); return; + } + if (req.url === '/__ui-model/v1/models') { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end('{"data":[{"id":"gpt-4o"}]}'); return; } + // A local target exercises the actual browser/capture path without external traffic. + if (req.url.startsWith('/__ui-fixture/api')) { + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ fixture: true, message: 'UI capture verified' })); return; + } + if (req.url.startsWith('/__ui-fixture')) { + res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }); + const finish = () => res.end('UI 测试页面

本地 UI 验证

'); if (req.url.includes('delay=')) setTimeout(finish, 800); else finish(); return; + } + 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' }); + const nativeTitlebar = new URL(req.url, 'http://x').searchParams.get('native-titlebar'); + res.end(path.extname(p) === '.html' && nativeTitlebar !== null ? fs.readFileSync(p, 'utf8').replace('', '') : fs.readFileSync(p)); +}); +await new Promise(r => srv.listen(PORT, '127.0.0.1', r)); + +const { chromium } = await import('../node_modules/@zhizhuodemao/patchright/index.mjs'); +const browser = await chromium.launch({ headless: true, executablePath: CHROME }); + +fs.mkdirSync(SHOTS, { recursive: true }); + +async function checkWindowChrome(scheme) { + for (const nativeTitlebar of [false, true]) { + const context = await browser.newContext({ viewport: { width: 1440, height: 900 }, colorScheme: scheme }); + // CI runner 上冷启动和首次渲染明显更慢,默认 30 秒的断言窗口不够。 + context.setDefaultTimeout(60000); + const page = await context.newPage(); + page.on('pageerror', error => console.error('Window chrome runtime error: ' + error.message)); + try { + await page.goto('http://127.0.0.1:' + PORT + '/?port=' + WS_PORT + '&token=ui-check&native-titlebar=' + (nativeTitlebar ? '1' : '0')); + await page.locator('.stage-head').waitFor(); + const skip = page.getByRole('button', { name: '稍后', exact: true }); + if (await skip.count()) await skip.click(); + const label = '[' + scheme + '] ' + (nativeTitlebar ? 'Mac 原生标题栏' : '自定义标题栏'); + // 侧栏折叠偏好是持久化的(localStorage 的 wdh_rail):上一次运行留下的「已折叠」 + // 会让后面的按钮断言找不到元素。这里先把偏好清成「新用户」状态, + // 保证断言的是初始形态而不是上一轮的残留。 + const railPreference = await page.evaluate(() => localStorage.getItem('wdh_rail')); + if (railPreference !== null) { + await page.evaluate(() => localStorage.removeItem('wdh_rail')); + await page.reload(); + await page.locator('.stage-head').waitFor(); + } + ok(await page.locator('.rail').isVisible(), label + ' 新用户应默认展开侧栏'); + for (const name of ['最小化', '最大化', '关闭']) ok(await page.locator('.win-controls').getByRole('button', { name, exact: true }).count() === (nativeTitlebar ? 0 : 1), label + ' 窗口按钮重复或缺失:' + name); + ok(await page.locator('.win-controls .tool-panel-toggle').isVisible(), label + ' 工具面板开关应保留'); + ok(await page.locator('.app').evaluate(element => getComputedStyle(element).getPropertyValue('--window-controls-space').trim()) === (nativeTitlebar ? '60px' : '174px'), label + ' 窗口按钮预留空间错误'); + await page.getByRole('button', { name: '收起会话列表', exact: true }).click(); + await page.locator('.rail').waitFor({ state: 'detached' }); + await page.reload(); + await page.getByRole('button', { name: '展开会话列表', exact: true }).waitFor(); + ok(await page.locator('.rail').count() === 0, label + ' 重载不能丢失明确的折叠偏好'); + if (nativeTitlebar) ok(await page.locator('.stage-head').evaluate(element => parseFloat(getComputedStyle(element).paddingLeft)) >= 104, label + ' 折叠后必须为原生窗口按钮保留安全区'); + await page.getByRole('button', { name: '展开会话列表', exact: true }).click(); + await page.locator('.rail').waitFor(); + await page.locator('.rail-bottom .rail-account').click(); + await page.getByRole('menuitem', { name: /^设置/ }).click(); + await page.locator('.settings-nav').waitFor(); + ok(await page.locator('.win-controls button').count() === (nativeTitlebar ? 0 : 3), label + ' 设置页窗口按钮错误'); + await page.screenshot({ path: path.join(SHOTS, scheme + (nativeTitlebar ? '-macos-window-chrome.png' : '-custom-window-chrome.png')) }); + } catch (error) { + await page.screenshot({ path: path.join(SHOTS, scheme + '-window-chrome-failure.png') }).catch(() => {}); + console.error('Window chrome diagnostics: ' + (await page.locator('body').innerText()).slice(0, 2000)); + throw error; + } finally { await context.close(); } + } +} + +// 文字对比度:前景 vs 最近的不透明背景 +const contrast = () => { + const parse = s => { const m = String(s).match(/rgba?\(([^)]+)\)/); if (!m) return null; const p = m[1].split(',').map(Number); return [p[0], p[1], p[2], p[3] === undefined ? 1 : p[3]]; }; + const lum = c => { const f = c.slice(0, 3).map(v => { v /= 255; return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4); }); return 0.2126 * f[0] + 0.7152 * f[1] + 0.0722 * f[2]; }; + const bgOf = el => { let a = el; while (a && a !== document.documentElement) { const c = parse(getComputedStyle(a).backgroundColor); if (c && c[3] > 0.5) return c; a = a.parentElement; } return parse(getComputedStyle(document.body).backgroundColor) || [17, 17, 19, 1]; }; + const out = []; + for (const el of document.querySelectorAll('button, .rt-Text, .side-row, .rowx-title, .rowx-sub, .bubble-md, .md code, .md code span, p, li, h1, h2, h3, td, th')) { + const r = el.getBoundingClientRect(); + if (!r.height || !el.offsetParent) continue; + const text = (el.textContent || '').trim(); + if (!text) continue; + if ([...el.children].some(c => (c.textContent || '').trim())) continue; + const cs = getComputedStyle(el); + const fg = parse(cs.color); + if (!fg || fg[3] < 0.5) continue; + const L1 = lum(fg), L2 = lum(bgOf(el)); + const ratio = (Math.max(L1, L2) + 0.05) / (Math.min(L1, L2) + 0.05); + const size = parseFloat(cs.fontSize), bold = parseInt(cs.fontWeight, 10) >= 600; + const need = size >= 18.66 || (bold && size >= 14) ? 3 : 4.5; + if (ratio < need) out.push('"' + text.slice(0, 12) + '" ' + ratio.toFixed(2) + ':1 (需要 ' + need + ') ' + cs.color); + } + return [...new Set(out)]; +}; + +// Measure both the painted icon and the actual button receiving pointer input. +const actionGeometry = () => { + const issues = []; + for (const button of document.querySelectorAll('.action-icon')) { + let hidden = false; + for (let el = button; el; el = el.parentElement) { + const cs = getComputedStyle(el); + if (cs.display === 'none' || cs.visibility === 'hidden' || +cs.opacity === 0) hidden = true; + } + if (hidden) continue; + const r = button.getBoundingClientRect(), icon = button.querySelector('svg')?.getBoundingClientRect(); + const label = button.getAttribute('aria-label') || button.title || '未命名'; + if (!label || label === '未命名') issues.push('图标按钮缺少名称'); + if (r.width < (button.hasAttribute('data-compact') ? 24 : 32) || r.height < (button.hasAttribute('data-compact') ? 24 : 32)) issues.push(label + ' 点击区域小于 32px'); + if (!icon || icon.width !== (button.hasAttribute('data-compact') ? 14 : 18) || icon.height !== (button.hasAttribute('data-compact') ? 14 : 18)) issues.push(label + ' 图标不是 18px'); + if (!button.disabled && r.width && r.height) { + const hit = document.elementFromPoint(r.x + r.width / 2, r.y + r.height / 2); + if (hit?.closest('button') !== button) issues.push(label + ' 点击区域被遮挡'); + } + } + for (const group of document.querySelectorAll('.row-actions, .composer-bar, .browser-bar')) { + const controls = [...group.querySelectorAll('button')].map(el => el.getBoundingClientRect()).filter(r => r.width && r.height); + for (let i = 0; i < controls.length; i++) for (let j = i + 1; j < controls.length; j++) { + const a = controls[i], b = controls[j]; + if (Math.min(a.right, b.right) > Math.max(a.left, b.left) + 1 && Math.min(a.bottom, b.bottom) > Math.max(a.top, b.top) + 1) issues.push('操作控件重叠'); + } + } + return [...new Set(issues)]; +}; + +const navGeometry = elements => elements.map(el => { + const r = el.getBoundingClientRect(), icon = el.querySelector('svg').getBoundingClientRect(), label = el.querySelector('span').getBoundingClientRect(); + return { name: el.textContent.trim(), x: r.x, y: r.y, width: r.width, height: r.height, iconX: icon.x, labelX: label.x }; +}); +const checkNavSpacing = (rows, label) => rows.forEach((row, i) => { + ok(row.height >= 40, label + ' 导航行过矮:' + row.name); + if (i) ok(row.y - rows[i - 1].y - rows[i - 1].height >= 8, label + ' 菜单间距不足:' + row.name); +}); + +async function showTool(page, kind) { + const panelToggle = page.locator('.tool-panel-toggle'); await panelToggle.waitFor(); + if (await panelToggle.getAttribute('aria-pressed') !== 'true') await panelToggle.click(); + await page.locator('.dock').waitFor(); + const label = kind === 'files' ? '工作区文件' : '浏览器'; + const tab = page.locator('.dock-tabs').getByRole('tab', { name: label, exact: true }).first(); + if (await tab.count()) await tab.click(); else { await page.getByRole('button', { name: '新建标签页', exact: true }).click(); await page.getByRole('menuitem', { name: label + '标签页', exact: true }).click(); } + if (kind !== 'files') { + const toggle = page.locator('.browser-bar button[aria-pressed]'); + await toggle.waitFor(); + if ((await toggle.getAttribute('aria-pressed') === 'true') !== (kind === 'network')) await toggle.click(); + await page.getByRole('button', { name: kind === 'network' ? '返回网页' : '显示网络请求', exact: true }).waitFor(); + } +} + +let activePage; +try { for (const scheme of (process.env.JSRA_UI_SCHEME ? [process.env.JSRA_UI_SCHEME] : ['dark', 'light'])) { + console.log('检查主题:' + scheme); + if (want('window')) await checkWindowChrome(scheme); + else skipSection('window', '未选中 --only=window'); + if (want('account')) await checkAccountMenu({ browser, baseUrl: 'http://127.0.0.1:' + PORT, wsPort: WS_PORT, scheme, shots: SHOTS, ok }); + else skipSection('account', '未选中 --only=account'); + if (!want('app')) { skipSection('app', '未选中 --only=app'); continue; } + const ctx = await browser.newContext({ viewport: { width: 1440, height: 900 }, colorScheme: scheme }); + await ctx.grantPermissions(['clipboard-read', 'clipboard-write']); + const page = await ctx.newPage(); + activePage = page; + const errs = []; + page.on('pageerror', e => { errs.push(e.message); console.error('UI runtime error: ' + e.message); }); + await page.goto('http://127.0.0.1:' + PORT + '/?port=' + WS_PORT + '&token=ui-check', { waitUntil: 'load' }); + await page.waitForTimeout(2200); + const skip = page.getByRole('button', { name: '稍后' }); + if (await skip.count()) await skip.first().click(); + await page.waitForTimeout(300); + + // 首次启动展开项目侧栏,工具面板按需打开。 + await page.screenshot({ path: path.join(SHOTS, scheme + '-boot.png') }); + if (await page.getByText('查看错误详情', { exact: true }).count()) { + await page.getByText('查看错误详情', { exact: true }).click(); + throw new Error(await page.locator('body').innerText()); + } + const expandRail = page.getByRole('button', { name: '展开会话列表' }); + ok(await page.locator('.rail').isVisible(), '[' + scheme + '] 首次启动侧栏应默认打开'); + if (await expandRail.count()) await expandRail.first().click(); + const initialSessions = await rpc('session-list'); + if (!initialSessions.sessions.length) { + ok(await page.getByRole('textbox', { name: '任务指令' }).count() === 0, '[' + scheme + '] 未创建项目时不应创建会话或输入坞'); + ok(await page.getByRole('heading', { name: '添加第一个项目', exact: true }).isVisible(), '[' + scheme + '] 首次启动应显示项目空状态'); + // 空状态只保留一个入口,侧栏和标题栏不再重复提示添加项目。 + ok(await page.getByText('选择项目目录,然后在项目下创建会话。', { exact: true }).count() === 0, '[' + scheme + '] 空状态不应重复说明如何添加项目'); + ok(await page.getByText('添加项目目录,开始工作', { exact: true }).count() === 0, '[' + scheme + '] 侧栏不应重复提示添加项目'); + ok(await page.getByRole('button', { name: '选择项目', exact: true }).count() === 0, '[' + scheme + '] 没有项目时不应显示项目选择器'); + ok(await page.getByRole('button', { name: '添加项目目录', exact: true }).count() === 1, '[' + scheme + '] 空状态应只有一个添加项目入口'); + } + const scope = 'ui-project-' + scheme; + const mainRoot = path.join(DATA, 'ui-main-' + scheme), sharedRoot = path.join(DATA, 'ui-shared-' + scheme); + fs.mkdirSync(mainRoot); fs.mkdirSync(sharedRoot); fs.writeFileSync(path.join(sharedRoot, 'shared-evidence.txt'), 'SECONDARY_ROOT_VERIFIED_' + scheme); + const folder = (directory, key) => { const grant = { sessionId: scope, path: directory, expiresAt: Date.now() + 60000 }; grant.signature = folderProof('ui-check', grant); return { key, grant }; }; + const codeProject = await rpc('project-save', { scope, project: { name: 'UI Project ' + scheme, folders: [folder(mainRoot, 'main'), folder(sharedRoot, 'shared')], primaryKey: 'main' } }); + const freshId = (await rpc('session-create', { projectId: codeProject.id })).id; + await rpc('session-focus', { sessionId: freshId }); + await page.locator('.session-item.on').waitFor(); + ok((await rpc('session-list')).sessions.every(s => !!s.projectId), '[' + scheme + '] 每个真实会话都必须归属项目'); + ok(await page.locator('.project-tree > section:not([data-project-id])').count() === 0, '[' + scheme + '] 项目树只能包含真实项目'); + const expandTools = page.locator('.win-controls button[aria-label="展开工具面板"]'); + if (await expandTools.count()) await expandTools.first().click(); + const panelToggle = await page.locator('.win-controls .tool-panel-toggle').boundingBox(); + ok(panelToggle.x > 1440 - 190, '[' + scheme + '] 工具面板开关应位于窗口右侧'); + await checkWindowDragging(page, ['.stage-identity strong', '.dock-head'], '[' + scheme + '] 标题栏'); + const projectGroup = page.locator('[data-project-id="' + codeProject.id + '"]'); + const fold = projectGroup.getByRole('button', { name: codeProject.name, exact: true }); + await fold.click(); + ok(await projectGroup.locator('.session-item').count() === 0, '[' + scheme + '] 折叠项目应隐藏其中会话'); + await page.reload(); await page.locator('.rail').waitFor(); + ok(await fold.getAttribute('aria-expanded') === 'false', '[' + scheme + '] 重载应保留项目折叠选择'); + await fold.click(); await projectGroup.locator('.session-item.on').waitFor(); + for (let repeat = 0; repeat < 2; repeat++) { + await projectGroup.locator('.project-row').hover(); + const row = await projectGroup.locator('.project-row').boundingBox(), chat = await projectGroup.locator('.session-item').first().boundingBox(); + ok(chat.y - row.y - row.height >= 4, '[' + scheme + '] 项目行与会话卡片不应粘连'); + await fold.click(); await fold.click(); + } + const sectionLeft = await page.locator('.rail-sec').evaluate(el => el.getBoundingClientRect().left); + ok(Math.abs((await projectGroup.boundingBox()).x - sectionLeft) < 1, '[' + scheme + '] 项目分组不应额外缩进'); + const railResize = page.getByRole('separator', { name: '调整左侧栏宽度', exact: true }); + const initialWidth = await page.locator('.rail').evaluate(el => el.getBoundingClientRect().width); + await railResize.focus(); await railResize.press('ArrowRight'); await railResize.press('ArrowRight'); + ok(Math.round(await page.locator('.rail').evaluate(el => el.getBoundingClientRect().width)) === Math.round(initialWidth + 32), '[' + scheme + '] 左侧栏键盘调宽失败'); + const railHandle = await railResize.boundingBox(); + await page.mouse.move(railHandle.x + railHandle.width / 2, railHandle.y + railHandle.height / 2); await page.mouse.down(); await page.mouse.move(railHandle.x + 48, railHandle.y + railHandle.height / 2, { steps: 8 }); await page.mouse.up(); + const draggedWidth = await page.locator('.rail').evaluate(el => el.getBoundingClientRect().width); + ok(draggedWidth > initialWidth + 60, '[' + scheme + '] 左侧栏拖动调宽失败'); + await page.reload(); await page.locator('.rail').waitFor(); + ok(Math.abs(await page.locator('.rail').evaluate(el => el.getBoundingClientRect().width) - draggedWidth) < 1, '[' + scheme + '] 左侧栏宽度未持久化'); + await railResize.dblclick(); + for (let step = 0; step < 4; step++) await railResize.press('ArrowLeft'); + for (const width of [220, 236, 252, 268, 284]) { + const geometry = await page.locator('.rail-brand').evaluate(brand => { + const logo = brand.querySelector('.logo').getBoundingClientRect(), name = brand.querySelector('.rail-name'), badge = brand.querySelector('.rail-badge'); + const text = name.getBoundingClientRect(), tag = badge.getBoundingClientRect(), bounds = brand.getBoundingClientRect(); + return { separate: logo.right < text.left && (!tag.width || text.right < tag.left), fits: text.right <= bounds.right && (!tag.width || tag.right <= bounds.right), fullName: name.scrollWidth <= name.clientWidth, badgeVisible: tag.width > 0 }; + }); + ok(geometry.separate && geometry.fits && geometry.fullName, '[' + scheme + '] ' + width + 'px 侧栏品牌区重叠、裁切或名称不完整'); + if (width === 220) ok(!geometry.badgeVisible, '[' + scheme + '] 最窄侧栏应收起 AGENT 标记'); + if (width === 284) ok(geometry.badgeVisible, '[' + scheme + '] 侧栏加宽后应恢复 AGENT 标记'); + if (width === 220 || width === 284) await page.screenshot({ path: path.join(SHOTS, scheme + '-sidebar-' + width + '.png') }); + await railResize.press('ArrowRight'); + } + await railResize.dblclick(); + const orderRoot = path.join(DATA, 'ui-project-order-' + scheme); fs.mkdirSync(orderRoot); fs.writeFileSync(path.join(orderRoot, 'keep.txt'), 'KEEP_PROJECT_SOURCE'); + const orderProject = await rpc('project-save', { scope, project: { name: '排序与迁移 ' + scheme, folders: [folder(orderRoot, 'order')], primaryKey: 'order' } }); + const orderGroup = page.locator('[data-project-id="' + orderProject.id + '"]'); await orderGroup.waitFor(); + await orderGroup.locator('.project-row').dragTo(projectGroup.locator('.project-row'), { targetPosition: { x: 15, y: 2 } }); + await page.waitForFunction(({ first, second }) => { const groups = [...document.querySelectorAll('[data-project-id]')].map(el => el.dataset.projectId); return groups.indexOf(first) < groups.indexOf(second); }, { first: orderProject.id, second: codeProject.id }); + const order = await rpc('projects-list'); ok(order.findIndex(p => p.id === orderProject.id) < order.findIndex(p => p.id === codeProject.id), '[' + scheme + '] 拖动排序未保存到后端'); + const movingChat = await rpc('session-create', { projectId: orderProject.id, title: '项目迁移测试' }); + await orderGroup.locator('.project-row').hover(); await orderGroup.getByRole('button', { name: '项目操作 ' + orderProject.name, exact: true }).click(); + await page.getByRole('menuitem', { name: '删除项目…', exact: true }).click(); + const removeProject = page.getByRole('dialog', { name: '删除项目', exact: true }); + await removeProject.getByRole('combobox', { name: '项目会话处理方式', exact: true }).click(); + await page.getByRole('option', { name: '迁移到 ' + codeProject.name, exact: true }).click(); + await removeProject.getByRole('button', { name: '删除项目', exact: true }).click(); + await orderGroup.waitFor({ state: 'detached' }); + ok((await rpc('session-list')).sessions.find(s => s.id === movingChat.id)?.projectId === codeProject.id, '[' + scheme + '] 删除项目应先迁移其中会话'); + ok(fs.readFileSync(path.join(orderRoot, 'keep.txt'), 'utf8') === 'KEEP_PROJECT_SOURCE', '[' + scheme + '] 删除项目不能删除源码'); + await rpc('session-delete', { sessionId: movingChat.id }); + await page.addScriptTag({ url: 'http://127.0.0.1:' + PORT + '/__ui-folder-bridge?owner=' + freshId + '&scheme=' + scheme }); + try { + await page.getByRole('button', { name: '新建项目', exact: true }).click(); + const creatingProject = page.getByRole('dialog', { name: '新建项目', exact: true }); + await creatingProject.getByRole('textbox', { name: '项目名称', exact: true }).fill('UI picker ' + scheme); + await creatingProject.getByRole('button', { name: '添加目录', exact: true }).click(); + await creatingProject.getByText(path.join(DATA, 'ui-picker-' + scheme), { exact: true }).waitFor(); + await creatingProject.getByRole('button', { name: '保存项目', exact: true }).click(); + await page.locator('.project-tree').getByText('UI picker ' + scheme, { exact: true }).first().waitFor(); + const createdProject = (await rpc('projects-list')).find(p => p.name === 'UI picker ' + scheme); + const createdList = await rpc('session-list'); + ok(createdList.sessions.find(s => s.id === createdList.focused)?.projectId === createdProject.id, '[' + scheme + '] 保存新项目后应直接进入项目内新会话'); + const pickerRoot = path.join(DATA, 'ui-picker-' + scheme); + fs.writeFileSync(path.join(pickerRoot, 'keep.txt'), 'KEEP_RELINKED_SOURCE'); + fs.renameSync(pickerRoot, pickerRoot + '-offline'); await rpc('projects-check'); + await page.getByText('项目目录不可用,执行已停止。聊天记录保留。', { exact: true }).waitFor(); + ok(!fs.existsSync(pickerRoot), '[' + scheme + '] 检测目录缺失不能自动重建原路径'); + await page.getByRole('textbox', { name: '任务指令', exact: true }).fill('relink draft'); + ok(await page.getByRole('button', { name: '发送(Enter)', exact: true }).isDisabled(), '[' + scheme + '] 缺失目录不能继续执行'); + await page.getByRole('button', { name: '重新选择目录', exact: true }).click(); + const relinkDialog = page.getByRole('dialog', { name: '重新连接项目目录', exact: true }); + await relinkDialog.getByRole('button', { name: '添加目录', exact: true }).click(); + await relinkDialog.getByText(pickerRoot, { exact: true }).waitFor(); + await relinkDialog.getByRole('button', { name: '保存项目', exact: true }).click(); + await page.getByText('项目目录不可用,执行已停止。聊天记录保留。', { exact: true }).waitFor({ state: 'detached' }); + ok((await rpc('session-list')).focused === createdList.focused, '[' + scheme + '] 重连目录不能更换会话身份'); + ok(await page.getByRole('textbox', { name: '任务指令', exact: true }).inputValue() === 'relink draft', '[' + scheme + '] 重连目录必须保留草稿'); + ok(fs.readFileSync(path.join(pickerRoot + '-offline', 'keep.txt'), 'utf8') === 'KEEP_RELINKED_SOURCE', '[' + scheme + '] 重连目录不能移动或删除原文件'); + await page.getByRole('textbox', { name: '任务指令', exact: true }).fill(''); + await rpc('session-focus', { sessionId: freshId }); + await page.locator('.session-item.on[data-session-id="' + freshId + '"]').waitFor(); + await rpc('project-remove', { id: createdProject.id, deleteSessions: true }); + } finally { await page.addScriptTag({ url: 'http://127.0.0.1:' + PORT + '/__ui-folder-bridge?restore=1' }); } + await showTool(page, 'files'); + await page.getByRole('combobox', { name: '文件目录', exact: true }).click(); + await page.getByRole('option', { name: 'ui-shared-' + scheme + ' · 只读', exact: true }).click(); + await page.locator('.workspace-tree [data-path="shared-evidence.txt"]').click(); + await page.locator('.document-content').filter({ hasText: 'SECONDARY_ROOT_VERIFIED_' + scheme }).waitFor(); + await showTool(page, 'files'); + await page.getByRole('combobox', { name: '文件目录', exact: true }).click(); + await page.getByRole('option', { name: 'ui-main-' + scheme + ' · 主目录', exact: true }).click(); + await showTool(page, 'browser'); + + ok(errs.length === 0, '[' + scheme + '] 页面报错: ' + (errs[0] || '')); + ok(await page.locator('.stage-head').count() > 0, '[' + scheme + '] 找不到对话顶栏 .stage-head'); + ok(await page.locator('.composer').count() > 0, '[' + scheme + '] 找不到输入坞 .composer'); + ok(await page.locator('.dock-tabs').count() > 0, '[' + scheme + '] 找不到右侧面板页签'); + ok(await page.locator('.statusbar').count() === 0, '[' + scheme + '] 底部状态栏没有移除'); + ok(await page.getByRole('textbox', { name: '筛选会话' }).count() === 0, '[' + scheme + '] 多余的会话筛选框没有移除'); + ok(await page.locator('.rail').getByText('项目', { exact: true }).count() === 1, '[' + scheme + '] 项目树标题不正确'); + ok(await page.locator('.rail').getByText('本地工作区', { exact: true }).count() === 0, '[' + scheme + '] 设置入口含糊的副标题未移除'); + ok(await page.getByRole('button', { name: '组件样张', exact: true }).count() === 0, '[' + scheme + '] 组件样张入口没有移除'); + ok(await page.locator('.tb').getByRole('button', { name: /搜索/ }).count() === 0, '[' + scheme + '] 标题栏仍有搜索入口'); + checkNavSpacing(await page.locator('.rail-nav .nav-button').evaluateAll(navGeometry), '[' + scheme + '] 主导航'); + await page.screenshot({ path: path.join(SHOTS, scheme + '-chat.png') }); + + for (const issue of await page.evaluate(actionGeometry)) ok(false, '[' + scheme + '] ' + issue); + const attachAction = page.getByRole('button', { name: '添加图片或文件', exact: true }); + await page.mouse.move(1, 1); + const restBackground = await attachAction.evaluate(el => getComputedStyle(el).backgroundColor); + ok(restBackground === 'rgba(0, 0, 0, 0)', '[' + scheme + '] 普通图标操作仍有常驻底色'); + const attachBounds = await attachAction.boundingBox(); + await attachAction.hover(); + ok(await attachAction.evaluate(el => getComputedStyle(el).backgroundColor) !== restBackground, '[' + scheme + '] 操作按钮没有悬停反馈'); + const hoverBounds = await attachAction.boundingBox(); + ok(attachBounds.width === hoverBounds.width && attachBounds.height === hoverBounds.height, '[' + scheme + '] 悬停导致按钮尺寸改变'); + await page.mouse.move(1, 1); + const composerControls = await page.locator('.composer-bar .rt-SelectTrigger, .composer-bar .seat-trigger').evaluateAll(els => els.map(el => ({ height: el.getBoundingClientRect().height, font: parseFloat(getComputedStyle(el).fontSize) }))); + ok(composerControls.every(c => c.height === 32 && c.font === 13 || c.font === 14), '[' + scheme + '] 输入栏选择器尺寸不统一'); + await page.getByRole('button', { name: '选择权限', exact: true }).click(); + ok(await page.getByRole('menuitemradio', { name: '请求批准', exact: true }).count() === 1, '[' + scheme + '] 权限弹窗无法打开'); + ok(await page.getByRole('dialog', { name: '权限与执行环境', exact: true }).count() === 0, '[' + scheme + '] 权限切换不应打开居中弹窗'); + await page.waitForTimeout(200); + await page.screenshot({ path: path.join(SHOTS, scheme + '-permissions.png') }); + await page.getByRole('menuitemradio', { name: '自动批准', exact: true }).click(); + await page.getByRole('button', { name: '选择权限', exact: true }).filter({ hasText: '自动批准' }).waitFor(); + ok(await page.locator('.stage-mode').count() === 0, '[' + scheme + '] 对话顶部不显示权限状态'); + await page.getByRole('button', { name: '选择权限', exact: true }).click(); + await page.getByRole('menuitemradio', { name: '请求批准', exact: true }).click(); + // 权限菜单正在关闭时点别处会被当成「关闭它」的那一次点击,座位不会打开; + // 等它真的消失再点,才是用户看到的行为。 + await page.locator('.permission-menu').waitFor({ state: 'detached' }); + // 模型与思考强度是同一个座位(DSH 的 ModelSelect):从座位里钻取到模型目录才能换模型。 + await page.locator('.composer-seat .seat-trigger').click(); + await page.locator('.seat-pop').waitFor(); + await page.locator('.seat-pop .seat-modelrow').click(); + ok(await page.locator('.seat-pop .seat-item').count() > 0, '[' + scheme + '] 模型菜单无法打开'); + await page.keyboard.press('Escape'); + + // File selection, clipboard paste and drag/drop use the same real attachment RPC. + const imageData = await page.evaluate(() => { const canvas = document.createElement('canvas'); canvas.width = 96; canvas.height = 64; const g = canvas.getContext('2d'); g.fillStyle = '#3478bd'; g.fillRect(0, 0, 96, 64); g.fillStyle = '#fff'; g.font = '24px sans-serif'; g.fillText('UI', 30, 40); return canvas.toDataURL('image/png').split(',')[1]; }); + await page.locator('input[type="file"]').setInputFiles({ name: '图片示例.png', mimeType: 'image/png', buffer: Buffer.from(imageData, 'base64') }); + await page.locator('.composer .attachment-image img').waitFor(); + await page.getByRole('button', { name: '预览图片:图片示例.png', exact: true }).click(); + await page.locator('.image-dialog .image-preview img').waitFor(); + ok((await page.locator('.image-dialog .image-preview img').getAttribute('src')).startsWith('data:image/png;base64,'), '[' + scheme + '] 图片预览未加载原图'); + await page.keyboard.press('Escape'); + await page.locator('.image-dialog').waitFor({ state: 'detached' }); + ok(await page.getByRole('button', { name: '预览图片:图片示例.png', exact: true }).evaluate(el => el === document.activeElement), '[' + scheme + '] 图片预览关闭后没有恢复焦点'); + await page.getByRole('button', { name: '移除附件:图片示例.png', exact: true }).click(); + await page.locator('.composer-input textarea').evaluate((el, data) => { const transfer = new DataTransfer(); transfer.items.add(new File([Uint8Array.from(atob(data), c => c.charCodeAt(0))], '粘贴图片.png', { type: 'image/png' })); el.dispatchEvent(new ClipboardEvent('paste', { bubbles: true, cancelable: true, clipboardData: transfer })); }, imageData); + await page.locator('.composer .attachment-image img').waitFor(); + await page.locator('.composer').evaluate((el, data) => { const transfer = new DataTransfer(); transfer.items.add(new File([Uint8Array.from(atob(data), c => c.charCodeAt(0))], '拖入图片.png', { type: 'image/png' })); el.dispatchEvent(new DragEvent('drop', { bubbles: true, cancelable: true, dataTransfer: transfer })); }, imageData); + await page.locator('.composer .attachment-tile').nth(1).waitFor(); + ok(await page.getByRole('button', { name: '发送(Enter)', exact: true }).isEnabled(), '[' + scheme + '] 仅图片消息不能发送'); + const enableImages = page.getByRole('button', { name: '启用图片输入', exact: true }); + if (await enableImages.count()) { + await page.getByRole('button', { name: '发送(Enter)', exact: true }).click(); + ok(await page.locator('.composer .attachment-tile').count() === 2, '[' + scheme + '] 图片模型不兼容时丢失附件'); + await enableImages.click(); + await enableImages.waitFor({ state: 'detached' }); + } + await page.screenshot({ path: path.join(SHOTS, scheme + '-image-composer.png') }); + await page.getByRole('button', { name: '发送(Enter)', exact: true }).click(); + await page.locator('.msg.assistant').filter({ hasText: '图片发送链路验证完成' }).waitFor(); + const sentImages = modelRequests.at(-1)?.messages.findLast(m => m.role === 'user')?.content.filter(p => p.type === 'image_url') || []; + ok(sentImages.length === 2 && sentImages.every(p => p.image_url.url.endsWith(imageData)), '[' + scheme + '] 模型没有收到两张真实图片'); + await page.reload(); + await page.locator('.msg.user .attachment-image img').nth(1).waitFor(); + ok(await page.locator('.msg.assistant').filter({ hasText: '图片发送链路验证完成' }).count() === 1, '[' + scheme + '] 图片对话重载后丢失回复'); + const reopenRail = page.getByRole('button', { name: '展开会话列表', exact: true }); + if (await reopenRail.count()) await reopenRail.click(); + await page.getByRole('textbox', { name: '任务指令' }).fill('创建一个测试文件'); + await page.getByRole('button', { name: '发送(Enter)', exact: true }).click(); + await page.locator('.msg.assistant').filter({ hasText: '已创建测试文件。' }).waitFor(); + await page.waitForFunction(() => document.querySelector('.stage-identity strong')?.textContent === '验证图片与工作区操作'); + await showTool(page, 'files'); + ok(await page.locator('.workspace-tree [data-path="src/trace.js"]').count() === 0, '[' + scheme + '] 目录应默认折叠'); + await page.locator('.workspace-tree [data-path="src"]').click(); + await page.locator('.workspace-tree [data-path="src/trace.js"]').waitFor(); + ok(await page.locator('.workspace-tree [data-path="src"]').getAttribute('aria-expanded') === 'true', '[' + scheme + '] 文件夹未展开'); + await page.locator('.workspace-tree [data-path="src/trace.js"]').click(); + await page.waitForFunction(() => document.querySelector('.document-panel:not([hidden]) .document-content')?.textContent === 'DIRECTORY_TREE_VERIFIED' || [...document.querySelectorAll('.document-content')].some(el => el.offsetWidth && el.textContent === 'DIRECTORY_TREE_VERIFIED')); + await showTool(page, 'files'); + await page.locator('.workspace-tree [data-path="src"]').press('ArrowLeft'); + ok(await page.locator('.workspace-tree [data-path="src/trace.js"]').count() === 0, '[' + scheme + '] 目录方向键折叠失败'); + await page.locator('.file-row').filter({ hasText: 'ui-example.txt' }).click(); + await page.waitForFunction(() => [...document.querySelectorAll('.document-content')].some(el => el.offsetWidth && el.textContent === 'UI change verified')); + ok(await page.locator('.document-content').filter({ hasText: 'UI change verified' }).textContent() === 'UI change verified', '[' + scheme + '] 工作区文件内容错误'); + ok(await page.getByRole('button', { name: '会话信息', exact: true }).count() === 0, '[' + scheme + '] 顶部不应显示会话信息按钮'); + const focusedId = await page.locator('.session-item.on').getAttribute('data-session-id'); + const menuButton = page.locator('.session-item.on button[aria-label="会话操作"]'); + await page.locator('.session-item.on').hover(); await menuButton.click(); + await page.getByRole('menuitem', { name: '复制会话 ID', exact: true }).click(); + await page.getByText('会话 ID 已复制', { exact: true }).waitFor(); + ok(await page.evaluate(() => navigator.clipboard.readText()) === focusedId, '[' + scheme + '] 复制了其他会话的 ID'); + await menuButton.click(); await page.getByRole('menuitem', { name: '复制为 Markdown', exact: true }).click(); + await page.getByText('对话 Markdown 已复制', { exact: true }).waitFor(); + const copied = await page.evaluate(() => navigator.clipboard.readText()); + ok(copied.includes(focusedId) && copied.includes('UI change verified') && copied.includes('workspace_write'), '[' + scheme + '] Markdown 缺少会话信息或工具结果'); + await page.locator('.session-menu').waitFor({ state: 'hidden' }); + ok(await page.locator('.dock-tabs [role="tab"]').count() >= 2, '[' + scheme + '] 应支持文件与文档独立标签页'); + await showTool(page, 'files'); + await page.getByRole('tab', { name: 'Git 改动', exact: true }).click(); + await page.getByText('当前目录没有可用的Git仓库', { exact: true }).waitFor(); + ok(await page.locator('.workspace-tree').isVisible() === false, '[' + scheme + '] Git 页签不应混入本地目录'); + ok(await page.locator('.detail').count() === 0, '[' + scheme + '] 切换文件页签应清除旧文件预览'); + await page.getByRole('tab', { name: '本地文件', exact: true }).click(); + await page.locator('.workspace-tree').waitFor({ state: 'visible' }); + await page.screenshot({ path: path.join(SHOTS, scheme + '-real-file-change.png') }); + await page.locator('.rail .new-session').click(); + await page.locator('.welcome').waitFor(); + + for (const c of (await page.evaluate(contrast)).slice(0, 10)) ok(false, '[' + scheme + '] 文字对比度不足 ' + c); + + await page.getByRole('button', { name: '了解项目', exact: true }).click(); + ok((await page.getByRole('textbox', { name: '任务指令' }).inputValue()).includes('项目'), '[' + scheme + '] 快捷分析没有填入指令'); + await page.getByRole('textbox', { name: '任务指令' }).fill(''); + await page.keyboard.press('Control+k'); + await page.getByRole('combobox', { name: '搜索项目与会话' }).waitFor(); + ok(await page.locator('.project-tree').isVisible() && await page.locator('.session-search-dialog').count() === 0, '[' + scheme + '] 搜索应在侧栏中打开并保留空查询的项目树'); + await page.getByRole('combobox', { name: '搜索项目与会话' }).fill('UI_NO_SIDEBAR_MATCH_X9ZZ'); + await page.getByText('未找到项目或会话', { exact: true }).waitFor(); + ok(await page.locator('.session-search-results button').count() === 0, '[' + scheme + '] 搜索仍然包含快捷操作'); + await page.keyboard.press('Escape'); + await showTool(page, 'network'); + await page.getByRole('button', { name: '返回网页', exact: true }).press('Enter'); + ok(await page.getByRole('button', { name: '显示网络请求', exact: true }).getAttribute('aria-pressed') === 'false', '[' + scheme + '] 网络请求按钮应支持键盘切回网页'); + await showTool(page, 'files'); + await page.screenshot({ path: path.join(SHOTS, scheme + '-files.png') }); + await page.keyboard.press('Control+Alt+2'); + await page.locator('.win-controls button[aria-label="收起工具面板"]').click(); + ok(await page.locator('.dock').count() === 0, '[' + scheme + '] 工具面板不能收起'); + await page.locator('.win-controls button[aria-label="展开工具面板"]').click(); + ok(await page.locator('.dock').count() === 1, '[' + scheme + '] 工具面板不能恢复'); + await page.keyboard.press('Control+l'); + await page.keyboard.press('Control+l'); + await page.waitForTimeout(100); + ok(await page.getByRole('textbox', { name: '目标网址' }).isVisible(), '[' + scheme + '] 连续 Ctrl+L 关闭了浏览器面板'); + + const beforeSessions = (await rpc('session-list')).sessions.length; + await page.keyboard.press('Control+t'); + await page.waitForTimeout(300); + ok((await rpc('session-list')).sessions.length === beforeSessions + 1, '[' + scheme + '] Ctrl+T 不能在当前项目新建会话'); + await page.locator('.session-item.on').hover(); + for (const issue of await page.evaluate(actionGeometry)) ok(false, '[' + scheme + '] 会话操作 ' + issue); + await page.locator('.session-item.on button[aria-label="会话操作"]').press('Enter'); + ok(await page.getByRole('menuitem', { name: '删除对话', exact: true }).isVisible(), '[' + scheme + '] 会话菜单缺少删除操作'); + await page.locator('.session-menu').evaluate(el => Promise.all(el.getAnimations().map(a => a.finished.catch(() => {})))); + for (const c of (await page.evaluate(contrast)).slice(0, 5)) ok(false, '[' + scheme + '] 会话菜单对比度不足 ' + c); + await page.screenshot({ path: path.join(SHOTS, scheme + '-session-menu.png') }); + await page.getByRole('menuitem', { name: '重命名会话', exact: true }).click(); + await page.getByRole('textbox', { name: '会话名称' }).fill('UI 回归验证 ' + scheme); + await page.getByRole('button', { name: '保存名称' }).click(); + await page.waitForTimeout(250); + ok((await page.locator('.stage-identity').innerText()).includes('UI 回归验证'), '[' + scheme + '] 会话重命名没有更新'); + await page.locator('.session-focus').first().click(); + await page.getByRole('button', { name: '搜索项目与会话', exact: true }).click(); + await page.getByRole('combobox', { name: '搜索项目与会话' }).fill('不存在的会话'); + ok(await page.locator('.session-search-results button').count() === 0, '[' + scheme + '] 会话搜索无效'); + await page.getByRole('combobox', { name: '搜索项目与会话' }).fill('UI 回归验证 ' + scheme); + ok(await page.locator('.session-search-results button').count() === 1, '[' + scheme + '] 搜索没有定位到会话'); + await page.screenshot({ path: path.join(SHOTS, scheme + '-session-search.png') }); + await page.getByRole('combobox', { name: '搜索项目与会话' }).press('Enter'); + await page.waitForTimeout(250); + ok((await page.locator('.stage-identity').innerText()).includes('UI 回归验证 ' + scheme), '[' + scheme + '] 搜索结果不能切换会话'); + + await checkSidebarBrowser({ page, rpc, scheme, shots: SHOTS, ok, projectId: codeProject.id }); + + const resize = page.locator('[data-panel-resize-handle-id]'); + const handle = await resize.boundingBox(); + const widthBefore = (await page.locator('.stage').boundingBox()).width; + await page.mouse.move(handle.x, handle.y + 200); + await page.mouse.down(); await page.mouse.move(handle.x - 65, handle.y + 200, { steps: 6 }); await page.mouse.up(); + ok(Math.abs((await page.locator('.stage').boundingBox()).width - widthBefore) > 30, '[' + scheme + '] 面板分隔线不能调整宽度'); + await page.mouse.move(handle.x - 65, handle.y + 200); await page.mouse.down(); await page.mouse.move(handle.x, handle.y + 200, { steps: 6 }); await page.mouse.up(); + + await page.locator('.rail-bottom .rail-account').click(); + await page.getByRole('menuitem', { name: /^设置/ }).click(); + await page.waitForTimeout(600); + ok(await page.locator('.settings-nav button').count() >= 4, '[' + scheme + '] 设置页导航项不足'); + ok(await page.locator('.settings-col').count() > 0, '[' + scheme + '] 设置页没有内容区'); + await page.locator('.settings-nav').getByRole('button', { name: '账号', exact: true }).click(); + ok(await page.getByRole('button', { name: '在浏览器中登录', exact: true }).isDisabled(), '[' + scheme + '] 网页预览不应假装支持原生账号存储'); + ok(await page.getByText('登录不会上传本地项目或对话,模型渠道继续使用你配置的 API Key。', { exact: true }).isVisible(), '[' + scheme + '] 账号与本地模型权限边界未说明'); + await page.screenshot({ path: path.join(SHOTS, scheme + '-account.png') }); + await page.locator('.settings-nav').getByRole('button', { name: 'AI 模型', exact: true }).click(); + const settingsNavBefore = await page.locator('.settings-nav .nav-button').evaluateAll(navGeometry); + await checkWindowDragging(page, ['.screen-head', '.screen-breadcrumb'], '[' + scheme + '] 设置标题栏'); + checkNavSpacing(settingsNavBefore, '[' + scheme + '] 设置导航'); + await page.screenshot({ path: path.join(SHOTS, scheme + '-settings.png') }); + for (const issue of await page.evaluate(actionGeometry)) ok(false, '[' + scheme + '] 模型设置 ' + issue); + await page.locator('.prov-row').first().getByRole('button', { name: '编辑', exact: true }).click(); + ok(await page.getByRole('dialog', { name: '编辑渠道' }).isVisible(), '[' + scheme + '] 编辑渠道按钮失效'); + await page.getByRole('button', { name: '取消', exact: true }).click(); + await page.locator('.rt-DialogOverlay').waitFor({ state: 'detached' }); + await page.setViewportSize({ width: 1080, height: 680 }); + for (const issue of await page.evaluate(actionGeometry)) ok(false, '[' + scheme + '] 小窗口模型设置 ' + issue); + await page.screenshot({ path: path.join(SHOTS, scheme + '-settings-1080.png') }); + await page.setViewportSize({ width: 1440, height: 900 }); + for (const c of (await page.evaluate(contrast)).slice(0, 10)) ok(false, '[' + scheme + '] 设置页对比度不足 ' + c); + + for (const name of ['运行参数', '外观', '关于与更新']) { + await page.locator('.settings-nav').getByRole('button', { name, exact: true }).click(); + await page.waitForTimeout(150); + const settingsNavAfter = await page.locator('.settings-nav .nav-button').evaluateAll(navGeometry); + ok(settingsNavAfter.every((row, i) => ['x', 'y', 'width', 'height', 'iconX', 'labelX'].every(k => Math.abs(row[k] - settingsNavBefore[i][k]) < 0.5)), '[' + scheme + '] 点击“' + name + '”导致菜单位置变化'); + for (const c of (await page.evaluate(contrast)).slice(0, 5)) ok(false, '[' + scheme + '] ' + name + ' 对比度不足 ' + c); + if (name === 'WDH 组件') { await page.getByRole('button', { name: '测试 CloakBrowser', exact: true }).click(); await page.getByText('浏览器启动与画面检查通过', { exact: true }).waitFor(); } + await page.screenshot({ path: path.join(SHOTS, scheme + '-settings-' + ({ 'WDH 组件': 'browser', '运行参数': 'runtime', '外观': 'appearance', '关于与更新': 'about' }[name]) + '.png') }); + } + await page.locator('.settings-nav').getByRole('button', { name: '外观', exact: true }).click(); + const opposite = scheme === 'dark' ? 'light' : 'dark'; + await page.locator('.theme-option').filter({ hasText: opposite === 'dark' ? '深色' : '浅色' }).click(); + await page.locator('html[data-theme="' + opposite + '"]').waitFor({ state: 'attached', timeout: 3000 }); + ok(await page.locator('html').getAttribute('data-theme') === opposite, '[' + scheme + '] 主题切换没有生效'); + await page.locator('.theme-option').filter({ hasText: '跟随系统' }).click(); + await page.locator('html[data-theme="' + scheme + '"]').waitFor({ state: 'attached', timeout: 3000 }); + ok(await page.locator('html').getAttribute('data-theme') === scheme, '[' + scheme + '] 跟随系统没有恢复'); + + await page.locator('.screen-head button').first().click(); + await page.waitForTimeout(300); + await page.locator('.rail button', { hasText: '自动化任务' }).first().click(); + await page.waitForTimeout(500); + await page.screenshot({ path: path.join(SHOTS, scheme + '-automations.png') }); + await page.getByRole('button', { name: '新建任务', exact: true }).click(); + ok(await page.getByPlaceholder('例如:每天早上看一眼竞品接口').isVisible(), '[' + scheme + '] 新建任务表单不可用'); + await page.getByRole('button', { name: '保存', exact: true }).click(); + const notice = page.locator('[data-sonner-toast]').filter({ hasText: '先写清楚要 AI 做什么' }); + await notice.waitFor(); + await page.waitForFunction(() => { + const el = document.querySelector('[data-sonner-toast]'); + return el && Math.abs(el.getBoundingClientRect().y - 60) < 1; + }); + const noticeBounds = await notice.boundingBox(); + ok(noticeBounds.y >= 46 && noticeBounds.y < 90 && noticeBounds.height < 100, '[' + scheme + '] 通知没有在顶部紧凑显示'); + ok(Math.abs(noticeBounds.x + noticeBounds.width / 2 - 720) < 1, '[' + scheme + '] 通知没有水平居中'); + ok(await page.locator('[data-sonner-toaster]').getAttribute('data-sonner-theme') === scheme, '[' + scheme + '] 通知主题不一致'); + ok(await page.locator('.toasts').count() === 0, '[' + scheme + '] 旧通知容器未移除'); + await page.screenshot({ path: path.join(SHOTS, scheme + '-notification.png') }); + await notice.getByRole('button', { name: '关闭通知', exact: true }).click(); + await notice.waitFor({ state: 'detached' }); + await page.getByRole('button', { name: '取消', exact: true }).click(); + await page.locator('.screen-head button').first().click(); + await page.waitForTimeout(300); + + await page.locator('.rail-nav').getByRole('button', { name: '插件', exact: true }).click(); + // 页签选择会被记住,回归测试先显式停在「官方插件」。 + await page.getByRole('tab', { name: '官方插件', exact: true }).click(); + await page.locator('[data-plugin-id="wdh"]').waitFor(); + ok(await page.getByRole('tab').allInnerTexts().then(t => t.join('|')) === '官方插件|自定义 MCP', '[' + scheme + '] 插件页应为官方插件 / 自定义 MCP 两个页签'); + ok(await page.locator('.official-plugin').count() === 3, '[' + scheme + '] 官方插件应包含 WDH/IDH/ADH'); + await page.getByRole('tab', { name: '自定义 MCP', exact: true }).click(); + ok(await page.locator('.official-plugin').isVisible().catch(() => false) === false, '[' + scheme + '] 自定义 MCP 页签下不应同时显示官方插件列表'); + await page.getByRole('tab', { name: '官方插件', exact: true }).click(); + ok(await page.locator('.official-plugin').count() === 3 && await page.locator('.official-plugin').first().isVisible(), '[' + scheme + '] 切回官方插件后列表应恢复'); + await checkWindowDragging(page, ['.screen-head'], scheme + ' 插件顶部拖动'); + await page.locator('[data-plugin-id="wdh"]').getByRole('button', { name: '配置', exact: true }).click(); + // 插件页和紧随其后的浏览器抓包都要真组件 + CloakBrowser 内核。 + // 本机没装时整段跳过并明确报告,而不是中断后面 87 条与内核无关的断言。 + // CI 有组件,这道判断直接放行,仍然覆盖插件页。 + const kernelState = await rpc('kernel-info').catch(error => { throw new Error('[' + scheme + '] 无法读取内核状态:' + error.message); }); + const kernelMissing = !kernelState?.component?.installed ? 'WDH 组件未安装' : !kernelState?.cloak ? 'CloakBrowser 内核未安装' : null; + if (kernelMissing) { + skipSection('kernel:' + scheme, kernelMissing + '(插件页与浏览器抓包段未验证)'); + } else { + await page.getByRole('button', { name: '测试 CloakBrowser', exact: true }).click(); + await page.getByText('浏览器启动与画面检查通过', { exact: true }).waitFor({ timeout: 90000 }); + await page.screenshot({ path: path.join(SHOTS, scheme + '-plugins.png') }); + await page.locator('.screen-head button').first().click(); + await showTool(page, 'browser'); + // Only use a local page. Browser launch, streaming, capture and detail are real. + await page.getByRole('textbox', { name: '目标网址' }).fill('http://127.0.0.1:' + PORT + '/__ui-fixture'); + await page.getByRole('textbox', { name: '目标网址' }).press('Enter'); + // Windows integrity preparation (45s) precedes Chromium's own 30s launch budget. + await page.locator('.screen-canvas').waitFor({ state: 'visible', timeout: 90000 }); + ok(await page.locator('.browser-views').count() === 0, '[' + scheme + '] 网页和网络不应再使用额外 Tab 栏'); + ok(await page.locator('.screen').evaluate(el => el.getBoundingClientRect().height > el.closest('.dock-body').getBoundingClientRect().height * .7), '[' + scheme + '] 网页应占满浏览器内容区域'); + for (const width of [1080, 1440]) { + await page.setViewportSize({ width, height: 900 }); + const addressBounds = await page.getByRole('textbox', { name: '目标网址' }).boundingBox(); + const networkBounds = await page.getByRole('button', { name: '显示网络请求', exact: true }).boundingBox(); + ok(networkBounds.x > addressBounds.x + addressBounds.width && Math.abs(networkBounds.y + networkBounds.height / 2 - addressBounds.y - addressBounds.height / 2) < 2, '[' + scheme + '] 地址栏和网络按钮应保持同一行,宽度 ' + width); + } + await page.getByRole('button', { name: '刷新', exact: true }).waitFor({ state: 'visible' }); + ok(await page.locator('.browser-launch').count() === 0, '[' + scheme + '] 地址栏不应有独立前往按钮'); + await page.getByRole('textbox', { name: '任务指令' }).fill('打开测试浏览器'); + await page.getByRole('button', { name: '发送(Enter)', exact: true }).click(); + await page.locator('.screen.ai-controlled').waitFor({ state: 'visible' }); + await page.waitForFunction(() => Number(getComputedStyle(document.querySelector('.browser-halo')).opacity) > .7); + ok(await page.getByText('AI 正在操控浏览器', { exact: true }).count() === 0, '[' + scheme + '] 不应显示额外的浏览器操控提示'); + ok(await page.locator('.screen').evaluate(el => getComputedStyle(el.querySelector('.browser-halo')).backgroundImage.includes('linear-gradient') && getComputedStyle(el).padding === '0px'), '[' + scheme + '] 浏览器应该使用柔和光晕而非硬边框'); + const activeViewport = await page.locator('.browser-viewport').boundingBox(); + await page.screenshot({ path: path.join(SHOTS, scheme + '-browser-ai-control.png') }); + await page.locator('.msg.assistant').filter({ hasText: '浏览器操控完成。' }).waitFor(); + await page.locator('.screen.ai-controlled').waitFor({ state: 'detached' }); + const idleViewport = await page.locator('.browser-viewport').boundingBox(); + ok(Math.abs(activeViewport.width - idleViewport.width) < 1 && Math.abs(activeViewport.height - idleViewport.height) < 1, '[' + scheme + '] 光晕改变了网页视口尺寸'); + await page.waitForFunction(() => { const c = document.querySelector('.screen-canvas'); return c?.width > 50 && c.getContext('2d').getImageData(0, 0, 1, 1).data[3] > 0; }); + await page.screenshot({ path: path.join(SHOTS, scheme + '-browser-loaded.png') }); + await page.getByRole('button', { name: '浏览器菜单', exact: true }).click(); + for (const name of ['清除当前站点数据并刷新…', '使用全新浏览器配置重启…', '关闭浏览器(保留会话)']) ok(await page.getByRole('menuitem', { name, exact: true }).count() === 1, '[' + scheme + '] 浏览器操作缺少明确名称:' + name); + await page.screenshot({ path: path.join(SHOTS, scheme + '-browser-menu.png') }); + await page.keyboard.press('Escape'); + await page.getByRole('button', { name: '上下文用量', exact: true }).click(); + ok(await page.getByRole('slider').count() === 0, '[' + scheme + '] 不应再显示调整上下文窗口的滑块'); + await page.keyboard.press('Escape'); + + const debugUiCdp = await ctx.newCDPSession(page); + const invokeTool = async (name, args) => { + const script = '(async () => { const state = await window.api.invoke("session-list"); return window.api.invoke("tool-run", { sessionId: state.focused, name: ' + JSON.stringify(name) + ', args: ' + JSON.stringify(args) + ' }); })()'; + const reply = await debugUiCdp.send('Runtime.evaluate', { expression: script, awaitPromise: true, returnByValue: true }); + ok(!reply.exceptionDetails && !reply.result.value?.isError, '[' + scheme + '] 调试工具失败 ' + name); + }; + await invokeTool('discover_tools', { group: 'debugger' }); + await invokeTool('pause_or_resume', { action: 'pause' }); + await page.waitForTimeout(200); + await invokeTool('get_paused_info', { includeScopes: false }); + await page.getByRole('button', { name: '恢复网页执行', exact: true }).waitFor(); + await page.screenshot({ path: path.join(SHOTS, scheme + '-browser-paused.png') }); + await page.getByRole('button', { name: '恢复网页执行', exact: true }).click(); + await page.getByRole('button', { name: '恢复网页执行', exact: true }).waitFor({ state: 'detached', timeout: 8000 }).catch(async e => { throw new Error(e.message + '\n通知:' + (await page.locator('[data-sonner-toast]').allTextContents()).join(' | ')); }); + await debugUiCdp.detach(); + + await page.keyboard.press('Control+Alt+3'); + await page.locator('.screen-canvas').waitFor({ state: 'detached' }); + const recordNetwork = page.getByRole('button', { name: /^(开始|继续)抓取网络请求$/ }); + if (await recordNetwork.count()) { + await recordNetwork.click(); + await page.keyboard.press('Control+Alt+2'); + await page.getByRole('button', { name: '刷新', exact: true }).click(); + await page.keyboard.press('Control+Alt+3'); + } + await page.locator('.req-row').filter({ hasText: /api/ }).first().waitFor({ timeout: 15000 }); + const pauseNetwork = page.getByRole('button', { name: '暂停抓取网络请求', exact: true }); + ok(await pauseNetwork.getAttribute('aria-pressed') === 'true', '[' + scheme + '] 记录中状态应显示暂停操作'); + await pauseNetwork.click(); + await recordNetwork.waitFor(); + ok(await recordNetwork.getAttribute('aria-pressed') === 'false', '[' + scheme + '] 暂停状态应显示继续操作'); + await recordNetwork.click(); + await pauseNetwork.waitFor(); + ok(await page.locator('.request-filters').evaluate(el => parseFloat(getComputedStyle(el).gap) >= 8 && getComputedStyle(el).flexWrap === 'nowrap'), '[' + scheme + '] 快捷筛选需要独立间距并在窄面板内横向滚动'); + ok(await page.locator('.bar').filter({ has: page.getByPlaceholder('过滤 URL / 参数名') }).innerText().then(text => !/网络请求\s*\d/.test(text)), '[' + scheme + '] 不应重复网络请求标题与数量'); + await page.locator('.req-row').filter({ hasText: /api/ }).first().click(); + await page.locator('.detail-tabs').getByRole('tab', { name: '响应', exact: true }).click(); + await page.waitForFunction(() => document.querySelector('.detail-body')?.textContent.includes('UI capture verified'), { timeout: 10000 }); + ok((await page.locator('.detail-body').innerText()).includes('UI capture verified'), '[' + scheme + '] 请求响应没有正确显示'); + await page.screenshot({ path: path.join(SHOTS, scheme + '-network.png') }); + await page.keyboard.press('Control+Alt+2'); + await page.waitForFunction(() => { const canvas = document.querySelector('.screen-canvas'); return canvas?.width > 50 && canvas.height > 50 && canvas.getContext('2d').getImageData(0, 0, 1, 1).data[3] > 0; }); + await page.screenshot({ path: path.join(SHOTS, scheme + '-browser-restored.png') }); + await page.getByRole('button', { name: '浏览器菜单', exact: true }).click(); + await page.getByRole('menuitem', { name: '关闭浏览器(保留会话)', exact: true }).click(); + } // kernel 段结束:以下断言不再依赖组件与 CloakBrowser 内核 + + await page.locator('.rail .new-session').click(); + await page.locator('.welcome').waitFor(); + + const taskInput = page.getByRole('textbox', { name: '任务指令' }); + await taskInput.focus(); + const inputChrome = await page.locator('.composer-input').evaluate(el => ({ outline: getComputedStyle(el).outlineStyle, shadow: getComputedStyle(el).boxShadow })); + ok(inputChrome.outline === 'none' && inputChrome.shadow === 'none', '[' + scheme + '] 输入框获得焦点时不应出现内框'); + ok(await page.getByRole('button', { name: '输入命令', exact: true }).count() === 0, '[' + scheme + '] 不应保留独立命令按钮'); + await taskInput.fill('/'); + await page.getByRole('listbox', { name: '输入框命令' }).waitFor(); + for (const row of await page.locator('.command-option').evaluateAll(nodes => nodes.map(node => ({ height: node.getBoundingClientRect().height, lines: getComputedStyle(node.querySelector('span')).whiteSpace })))) ok(row.height <= 34 && row.lines === 'nowrap', '[' + scheme + '] 命令列表应为紧凑单行'); + await page.screenshot({ path: path.join(SHOTS, scheme + '-composer-commands.png') }); + await taskInput.press('ArrowDown'); await taskInput.press('Tab'); + ok(await taskInput.inputValue() === '/compact ', '[' + scheme + '] 命令方向键/Tab补全失败'); + await taskInput.fill('/agent 核对工作区证据'); await taskInput.press('Enter'); + await page.getByRole('button', { name: '查看子代理', exact: true }).waitFor(); await page.getByRole('button', { name: '查看子代理', exact: true }).click(); + await page.locator('.subagent-row').filter({ hasText: '已完成' }).waitFor(); + await page.getByRole('button', { name: '核对工作区证据', exact: true }).click(); + await page.getByText('研究完成:工作区证据已核对。', { exact: true }).waitFor(); + await page.keyboard.press('Escape'); + await page.getByRole('button', { name: '关闭子代理列表', exact: true }).click(); + await taskInput.fill('/goal'); await taskInput.press('Enter'); + await page.getByRole('textbox', { name: '设置目标', exact: true }).fill('验证目标机制:' + '完整检查项目证据、执行结果与用户界面,确保长目标内容可以在详情中阅读。'.repeat(6)); + await page.getByRole('dialog', { name: '设置目标', exact: true }).getByRole('button', { name: '执行', exact: true }).click(); + const goalTrigger = page.getByRole('button', { name: '查看目标进展', exact: true }); + await goalTrigger.filter({ hasText: '已完成' }).waitFor(); + await page.locator('.msg.assistant').filter({ hasText: '目标验证完成。' }).waitFor(); + ok(await page.locator('.command-feedback').count() === 0, '[' + scheme + '] 目标成功后不应留下重复的命令提示'); + ok(await page.locator('.composer-wrap .goal-trigger').count() === 0 && await page.locator('.stage-head .goal-trigger').count() === 1, '[' + scheme + '] 目标入口应放在会话标题右侧'); + ok(!(await goalTrigger.innerText()).includes('验证目标机制'), '[' + scheme + '] 目标全文不应占用标题栏'); + for (const viewport of [{ width: 1440, height: 900 }, { width: 1080, height: 680 }]) { + await page.setViewportSize(viewport); + if (viewport.width === 1080) for (let i = 0; i < 13; i++) await railResize.press('ArrowRight'); + const header = await page.locator('.stage-head').evaluate(head => { + const bounds = head.getBoundingClientRect(), children = [...head.children].map(el => el.getBoundingClientRect()).filter(r => r.width > 0 && r.height > 0); + return { height: bounds.height, inside: children.every(r => r.left >= bounds.left && r.right <= bounds.right && r.top >= bounds.top && r.bottom <= bounds.bottom), separate: children.every((r, i) => !i || r.left >= children[i - 1].right - 1) }; + }); + ok(header.inside && header.separate && header.height === 56, '[' + scheme + '] ' + viewport.width + ' 标题、权限与目标/计划按钮应保持单行且不重叠'); + await page.screenshot({ path: path.join(SHOTS, scheme + '-header-progress-' + viewport.width + '.png') }); + if (viewport.width === 1080) await railResize.dblclick(); + } + await page.setViewportSize({ width: 1440, height: 900 }); + await page.screenshot({ path: path.join(SHOTS, scheme + '-harness-goal.png') }); + await page.getByRole('button', { name: '查看目标进展', exact: true }).click(); + await page.locator('.goal-details').waitFor(); + await page.locator('.goal-details').evaluate(el => Promise.all(el.getAnimations().map(animation => animation.finished.catch(() => {})))); + await page.locator('.goal-details').getByText('UI_GOAL_EVIDENCE:本地模型调用 goal_update,状态已持久化。', { exact: true }).waitFor(); + ok(await page.locator('.goal-criteria').getByText('已验证', { exact: true }).count() === 1, '[' + scheme + '] 目标完成条件未展示验证状态'); + const goalBounds = await page.locator('.goal-details').boundingBox(), clearBounds = await page.getByRole('button', { name: '结束并收起目标', exact: true }).boundingBox(); + ok(clearBounds.y >= goalBounds.y && clearBounds.y + clearBounds.height <= goalBounds.y + goalBounds.height, '[' + scheme + '] 长目标不应把操作按钮挤出详情浮层'); + await page.screenshot({ path: path.join(SHOTS, scheme + '-goal-details.png') }); + await page.keyboard.press('Escape'); + const goalSession = (await rpc('session-list')).focused; + await goalTrigger.click(); await rpc('session-focus', { sessionId: freshId }); + await page.locator('.goal-details').waitFor({ state: 'detached' }); + ok(await goalTrigger.count() === 0, '[' + scheme + '] 目标入口或详情不应泄漏到其他会话'); + await rpc('session-focus', { sessionId: goalSession }); + await page.reload(); await goalTrigger.waitFor(); + await goalTrigger.click(); await page.locator('.goal-details section .md').getByText('目标机制验证通过。', { exact: true }).waitFor(); + await page.getByRole('button', { name: '结束并收起目标', exact: true }).click(); + await goalTrigger.waitFor({ state: 'detached' }); + await page.locator('.goal-details').waitFor({ state: 'detached' }); + // 目标自动接续:首轮没有工具/进展时驱动会接续一轮,再接续无可进展后暂停;对话里必须留下“继续执行目标”提示。 + const goalRound = await rpc('session-create', { title: '目标接续提示', projectId: codeProject.id }); + await rpc('session-focus', { sessionId: goalRound.id }); await page.waitForTimeout(300); + await rpc('goal-start', { sessionId: goalRound.id, objective: '验证自动接续提示:只观察,不调用工具' }); + const roundDeadline = Date.now() + 20000; + for (;;) { const snap = await rpc('session-snapshot', { sessionId: goalRound.id }); if (snap.state?.goal && snap.state.goal.status !== 'active') break; if (Date.now() > roundDeadline) throw Error('goal round did not settle'); await page.waitForTimeout(200); } + const turnTrigger = page.locator('.turn-trigger[data-turn-trigger="goal"]').first(); + await turnTrigger.waitFor(); + ok(await turnTrigger.getByText('继续执行目标', { exact: true }).count() === 1, '[' + scheme + '] 自动接续轮必须显示继续执行目标'); + ok(/^\d{2}:\d{2}$/.test(await turnTrigger.locator('.turn-trigger-time').innerText()), '[' + scheme + '] 目标接续提示必须显示时间'); + await turnTrigger.locator('.turn-trigger-head').click(); + await turnTrigger.getByText('这条通知触发了本轮回复。', { exact: true }).waitFor(); + await turnTrigger.getByText('验证自动接续提示:只观察,不调用工具', { exact: true }).waitFor(); + await turnTrigger.screenshot({ path: path.join(SHOTS, scheme + '-goal-trigger.png') }); + await rpc('session-delete', { sessionId: goalRound.id }); + await rpc('session-focus', { sessionId: goalSession }); await page.waitForTimeout(300); + await taskInput.fill('/goal UI_THINKING_CHECK_' + scheme); await taskInput.press('Enter'); + await page.locator('.reason-head').first().waitFor(); + await page.locator('.reason-head').first().click(); + await page.locator('.reasoning-body').filter({ hasText: 'UI_THINKING_LIVE' }).waitFor(); + await goalTrigger.click(); await page.getByRole('button', { name: '暂停目标', exact: true }).click(); + await goalTrigger.filter({ hasText: '已暂停' }).waitFor(); + const resumeBanner = page.locator('.banner').getByRole('button', { name: '继续目标', exact: true }); + await resumeBanner.waitFor({ state: 'visible' }); + await resumeBanner.click(); + await goalTrigger.filter({ hasText: '进行中' }).waitFor(); + await goalTrigger.click(); + await page.getByRole('button', { name: '结束并收起目标', exact: true }).click(); + await goalTrigger.waitFor({ state: 'detached' }); + await page.getByRole('button', { name: '发送(Enter)', exact: true }).waitFor(); + for (const [command, marker, result] of [['memory', 'UI_MEMORY_CHECK', '记忆保存验证完成。'], ['skill', 'UI_SKILL_CHECK', '技能保存验证完成。']]) { + await taskInput.fill('/' + command + ' ' + marker); await taskInput.press('Enter'); + await page.getByRole('button', { name: '允许这一次', exact: true }).click(); + await page.locator('.msg.assistant').filter({ hasText: result }).waitFor(); + const saved = await rpc('extensions-list', { sessionId: (await rpc('session-list')).focused, kind: command }); + ok(saved.some(item => item.name === (command === 'memory' ? 'ui-memory' : 'ui-workflow')), '[' + scheme + '] /' + command + ' 未实际保存'); + } + await taskInput.fill('/memories'); await taskInput.press('Enter'); + await page.getByRole('dialog', { name: '记忆', exact: true }).getByRole('button').filter({ hasText: 'ui-memory' }).click(); + await page.locator('.extension-preview').filter({ hasText: 'UI_MEMORY_SAVED' }).waitFor(); + await page.getByRole('dialog', { name: '记忆', exact: true }).getByRole('button', { name: '关闭', exact: true }).click(); + await taskInput.fill('/compact'); await taskInput.press('Enter'); + await page.locator('.command-feedback.success').filter({ hasText: '上下文已压缩' }).waitFor(); + await page.screenshot({ path: path.join(SHOTS, scheme + '-compact-and-memory.png') }); + await taskInput.fill('/automation'); await taskInput.press('Enter'); + await page.getByPlaceholder('例如:每天早上看一眼竞品接口').fill('UI scheduled run ' + scheme); + await page.getByPlaceholder('例如:打开 https://example.com,看它首页调了哪些接口,把新增的参数记到 findings.md').fill('UI automation read-only check'); + await page.getByRole('button', { name: '保存', exact: true }).click(); + const automationRow = page.locator('.task-row').filter({ hasText: 'UI scheduled run ' + scheme }); + await automationRow.getByRole('button', { name: '立即运行', exact: true }).click(); + await automationRow.getByText('已完成', { exact: true }).waitFor(); + ok((await rpc('tasks-list')).some(t => t.title === 'UI scheduled run ' + scheme && t.lastStatus === 'ok' && t.runs.length), '[' + scheme + '] 自动化未等待真实 Run 完成'); + await page.locator('.screen-head button').first().click(); + await page.locator('.rail .new-session').click(); await page.locator('.welcome').waitFor(); + + for (const viewport of [{ width: 1280, height: 800 }, { width: 1080, height: 680 }]) { + await page.setViewportSize(viewport); + await page.waitForTimeout(200); + ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), '[' + scheme + '] ' + viewport.width + ' 产生横向溢出'); + for (const issue of await page.evaluate(actionGeometry)) ok(false, '[' + scheme + '] ' + viewport.width + ' ' + issue); + const inputBox = await page.locator('.composer').boundingBox(); + ok(inputBox.y + inputBox.height < viewport.height - 20, '[' + scheme + '] ' + viewport.width + ' 输入框被裁切'); + const lastSuggestion = await page.locator('.suggestion').last().boundingBox(); + const messageArea = await page.locator('.msgs').boundingBox(); + ok(lastSuggestion.y + lastSuggestion.height <= messageArea.y + messageArea.height + 1, '[' + scheme + '] ' + viewport.width + ' 快捷分析入口被裁切'); + await page.screenshot({ path: path.join(SHOTS, scheme + '-chat-' + viewport.width + '.png') }); + } + + await page.setViewportSize({ width: 1440, height: 900 }); + // Saved-history fixture; all displayed data is explicitly labelled as an example. + // Patchright evaluates in an isolated world; the app bridge lives in the main world. + const mainWorld = await ctx.newCDPSession(page); + const focusedResult = await mainWorld.send('Runtime.evaluate', { expression: 'window.api.invoke("session-list").then(s => s.focused)', awaitPromise: true, returnByValue: true }); + const imageResult = await mainWorld.send('Runtime.evaluate', { expression: 'window.api.invoke("attach-upload", ' + JSON.stringify({ sessionId: focusedResult.result.value, name: '图片示例.png', mime: 'image/png', data: imageData }) + ')', awaitPromise: true, returnByValue: true }); + const fixtureImageId = imageResult.result.value.id; + const fixtureEvents = [ + { t: 'user', id: 'fixture-user', turnId: 'fixture-turn', at: Date.now() - 1556000, displayContent: '帮我检查这个项目,修复问题并验证。参考这张图片,把界面收敛得更清楚一些。', content: '帮我检查项目。', attachments: [{ kind: 'attachment', id: fixtureImageId, name: '图片示例.png', image: true }], images: [fixtureImageId] }, + { t: 'assistant', turnId: 'fixture-turn', phase: 'commentary', reasoning: 'UI 布局验证:核对项目入口及执行结果。', content: '我先读取入口文件,再搜索相关逻辑,最后运行测试。', calls: [ + {id:'fixture', itemId:'fixture-1', name:'workspace_read', args:{path:'src/main.ts'}}, + {id:'fixture-search', itemId:'fixture-2', name:'workspace_grep', args:{pattern:'TODO'}}, + {id:'fixture-eval', itemId:'fixture-3', name:'workspace_shell', args:{cmd:'npm test'}}, + ...Array.from({ length: 3 }, (_, i) => ({ id: 'fixture-extra-' + i, itemId: 'fixture-extra-' + i, name: 'workspace_read', args: { path: `src/check-${i}.js` } })) + ] }, + { t: 'tool', turnId:'fixture-turn', id:'fixture', itemId:'fixture-1', name:'workspace_read', content:'export function main() { return true; }', ms:42 }, + { t: 'tool', turnId:'fixture-turn', id:'fixture-search', itemId:'fixture-2', name:'workspace_grep', content:'没有未完成项。', ms:18 }, + { t: 'tool', turnId:'fixture-turn', id:'fixture-eval', itemId:'fixture-3', name:'workspace_shell', content:'Tests: 12 passed', ms:11 }, + ...Array.from({ length: 3 }, (_, i) => ({ t: 'tool', turnId: 'fixture-turn', id: 'fixture-extra-' + i, itemId: 'fixture-extra-' + i, content: 'fixture verified', ms: 12 })), + { t: 'assistant', turnId:'fixture-turn', phase:'final_answer', content:'已完成这一轮检查。\n\n- 用户输入、执行过程和最终回复已分开。\n- 工具详情默认收起,需要时可以展开查看。\n- 图片保留在原消息中,重新打开对话后仍可预览。\n\n测试通过,可以继续体验。\n\n```ts\nexport function main() {\n return true;\n}\n```' }, + { t: 'turn-end', turnId:'fixture-turn', stop:'completed', endedAt: Date.now() - 5000 } + ]; + await mainWorld.send('Runtime.evaluate', { expression: 'window.api.invoke("test-seed-history", ' + JSON.stringify({sessionId:focusedResult.result.value,events:fixtureEvents}) + ')', awaitPromise:true, returnByValue:true }); + await page.reload(); + await page.locator('.tool-group > summary').waitFor(); + await page.locator('.msg.user .attachment-image img').waitFor(); + const skipAgain = page.getByRole('button', { name: '稍后', exact: true }); + if (await skipAgain.count()) await skipAgain.click(); + ok(await page.locator('.plan-trigger').count() === 0, '[' + scheme + '] 没有实际任务时仍显示默认清单'); + ok(!await page.locator('.tool-head').first().isVisible(), '[' + scheme + '] 连续工具调用没有默认收起'); + for (const viewport of [{ width: 1080, height: 680 }, { width: 1440, height: 900 }]) { + await page.setViewportSize(viewport); + await checkProcessRow(page, '[' + scheme + '] ' + viewport.width + ' 执行过程'); + } + await page.screenshot({ path: path.join(SHOTS, scheme + '-conversation.png') }); + await page.locator('.tool-group > summary').press('Enter'); + await page.locator('.tool-head').nth(2).waitFor({ state: 'visible' }); + ok(await page.locator('.tool-head:visible').count() === 6, '[' + scheme + '] 长工具分组不能通过键盘展开'); + await page.locator('.tool-head').first().click(); + ok(await page.locator('.tool-body').isVisible(), '[' + scheme + '] 工具调用记录不能展开'); + ok((await page.locator('.tool-body').innerText()).includes('42 ms'), '[' + scheme + '] 工具调用时长没有显示在详情中'); + ok(await page.locator('.md pre code').count() > 0, '[' + scheme + '] 代码块没有渲染'); + await page.screenshot({ path: path.join(SHOTS, scheme + '-tool-detail.png') }); + await page.locator('.tool-group > summary').press('Enter'); + await page.locator('.tool-head').first().waitFor({ state: 'hidden' }); + ok(!await page.locator('.tool-head').first().isVisible(), '[' + scheme + '] 工具分组不能收起'); + await page.locator('.msgs').evaluate(el => { el.style.scrollBehavior = 'auto'; el.scrollTop = el.scrollHeight; }); + await page.screenshot({ path: path.join(SHOTS, scheme + '-conversation-code.png') }); + for (const c of (await page.evaluate(contrast)).slice(0, 8)) ok(false, '[' + scheme + '] 对话与代码对比度不足 ' + c); + const closeTools = page.getByRole('button', { name: '收起工具面板', exact: true }); + if (await closeTools.count()) await closeTools.click(); + const closeRail = page.getByRole('button', { name: '收起会话列表', exact: true }); + if (await closeRail.count()) await closeRail.click(); + await page.setViewportSize({ width: 1440, height: 1000 }); + await page.locator('.msgs').evaluate(el => { el.style.scrollBehavior = 'auto'; el.scrollTop = 0; }); + await page.screenshot({ path: path.join(SHOTS, scheme + '-conversation-focused.png') }); + + await checkConversationNavigation({ page, rpc, scheme, shots: SHOTS, ok }); + + // Exercise the actual plan tool, live events, saved state and manual UI reading. + const priorPlanSession = (await rpc('session-list')).focused; + const planSession = await rpc('session-create', { title: '完整计划 UI 验证', projectId: codeProject.id }); + await rpc('session-focus', { sessionId: planSession.id }); + await page.getByRole('textbox', { name: '任务指令' }).fill('UI_PLAN_TEMPLATE'); + await page.getByRole('button', { name: '发送(Enter)', exact: true }).click(); + await page.locator('.msg.assistant').filter({ hasText: '默认步骤计划已建立。' }).waitFor(); + const planTrigger = page.getByRole('button', { name: '查看完整计划', exact: true }); + const planPanel = page.getByRole('dialog', { name: '任务计划', exact: true }); + await planTrigger.click(); await planPanel.waitFor(); + ok(await planPanel.locator('li').count() === DEFAULT_TODOS.length, '[' + scheme + '] AI 明确建立的计划不应被当作未使用模板隐藏'); + await page.keyboard.press('Escape'); await planPanel.waitFor({ state: 'detached' }); + await page.getByRole('textbox', { name: '任务指令' }).fill('UI_PLAN_CHECK'); + await page.getByRole('button', { name: '发送(Enter)', exact: true }).click(); + await page.locator('.msg.assistant').filter({ hasText: '完整计划已建立。' }).waitFor(); + ok(await page.locator('.stage-head .plan-trigger').count() === 1, '[' + scheme + '] 计划入口应在标题栏内'); + ok(await planTrigger.innerText().then(text => !text.includes('完整计划中的长步骤')), '[' + scheme + '] 计划步骤全文不应占用标题栏'); + const closedPlanGeometry = await page.locator('.chat').evaluate(chat => ({ head: chat.querySelector('.stage-head').getBoundingClientRect().bottom, msgs: chat.querySelector('.msgs').getBoundingClientRect().top })); + ok(Math.abs(closedPlanGeometry.head - closedPlanGeometry.msgs) < 1, '[' + scheme + '] 标题栏下方不应再有占用消息空间的计划横条'); + await planTrigger.focus(); await planTrigger.press('Enter'); + await planPanel.waitFor(); + ok(await planPanel.locator('li').count() === 30, '[' + scheme + '] 完整计划未列出所有步骤'); + await planPanel.evaluate(el => Promise.all(el.getAnimations().map(a => a.finished.catch(() => {})))); + ok(await planPanel.locator('.todo-step-content').first().innerText() === PLAN_STEPS[0].content, '[' + scheme + '] 长步骤内容被截断'); + for (const status of ['completed', 'in_progress', 'cancelled', 'pending']) ok(await planPanel.locator('[data-status="' + status + '"]').count() > 0, '[' + scheme + '] 计划缺少状态:' + status); + await planPanel.locator('ol').focus(); await planPanel.locator('ol').press('End'); + await page.waitForFunction(() => { const list = document.querySelector('.todo-plan-list'); return list && list.scrollTop > 0 && list.scrollTop + list.clientHeight >= list.scrollHeight - .5; }); + const endGeometry = await planPanel.evaluate(el => { const last = el.querySelector('li:last-child').getBoundingClientRect(), list = el.querySelector('ol').getBoundingClientRect(); return { last: { top: last.top, bottom: last.bottom }, list: { top: list.top, bottom: list.bottom } }; }); + ok(endGeometry.last.top >= endGeometry.list.top && endGeometry.last.bottom <= endGeometry.list.bottom + 2, '[' + scheme + '] 不能手动滚动到最后一步:' + JSON.stringify(endGeometry)); + await page.screenshot({ path: path.join(SHOTS, scheme + '-plan-end.png') }); + await planPanel.getByRole('button', { name: '复制计划', exact: true }).click(); + const copiedPlan = await page.evaluate(() => navigator.clipboard.readText()); + ok(PLAN_STEPS.every(step => copiedPlan.includes(step.content)) && copiedPlan.includes('已取消'), '[' + scheme + '] 复制的计划不完整'); + await rpc('agent-send', { sessionId: planSession.id, text: 'UI_PLAN_UPDATE' }); + await planPanel.locator('li[data-status="completed"]').filter({ hasText: 'UI_PLAN_LAST_STEP' }).waitFor(); + ok(await planPanel.locator('li').count() === 30 && (await planPanel.innerText()).includes('已完成 3 / 30 项'), '[' + scheme + '] 打开中的计划没有实时更新'); + await page.keyboard.press('Escape'); await planPanel.waitFor({ state: 'detached' }); + await planTrigger.click(); await planPanel.waitFor(); + await rpc('session-focus', { sessionId: priorPlanSession }); + await planPanel.waitFor({ state: 'detached' }); + ok(await page.locator('.plan-trigger').count() === 0, '[' + scheme + '] 计划浮层泄漏到其他会话'); + await rpc('session-focus', { sessionId: planSession.id }); + await planTrigger.waitFor(); await page.reload(); await planTrigger.waitFor(); + ok((await planTrigger.innerText()).includes('3/30'), '[' + scheme + '] 重开会话丢失计划状态'); + for (const viewport of [{ width: 1440, height: 900 }, { width: 1080, height: 680 }]) { + await page.setViewportSize(viewport); await planTrigger.click(); await planPanel.waitFor(); + await planPanel.evaluate(el => Promise.all(el.getAnimations().map(animation => animation.finished.catch(() => {})))); + const panelBounds = await planPanel.boundingBox(); + ok(panelBounds.x >= 0 && panelBounds.y >= 0 && panelBounds.x + panelBounds.width <= viewport.width && panelBounds.y + panelBounds.height <= viewport.height, '[' + scheme + '] 计划浮层超出窗口'); + ok(await planPanel.locator('ol').evaluate(el => el.scrollHeight > el.clientHeight && el.scrollWidth <= el.clientWidth + 1), '[' + scheme + '] 长计划未提供可用滚动区域'); + for (const c of (await page.evaluate(contrast)).slice(0, 8)) ok(false, '[' + scheme + '] 完整计划对比度不足 ' + c); + await page.screenshot({ path: path.join(SHOTS, scheme + '-plan-' + viewport.width + '.png') }); + await planPanel.getByRole('button', { name: '关闭计划', exact: true }).click(); await planPanel.waitFor({ state: 'detached' }); + } + // Tool panels, selected tabs and widths belong to their owning conversation. + await page.setViewportSize({ width: 1440, height: 900 }); + const viewA = await rpc('session-create', { title: 'UI 独立布局 A', projectId: codeProject.id }), viewB = await rpc('session-create', { title: 'UI 独立布局 B', projectId: codeProject.id }); + await rpc('session-focus', { sessionId: viewA.id }); + await page.getByRole('button', { name: '展开工具面板', exact: true }).click(); + await showTool(page, 'files'); + await page.getByRole('button', { name: '收起工具面板', exact: true }).click(); + await rpc('session-focus', { sessionId: viewB.id }); + await page.getByRole('button', { name: '展开工具面板', exact: true }).click(); + await showTool(page, 'browser'); + const resizeBar = await page.locator('.resize-handle').boundingBox(); + await page.mouse.move(resizeBar.x + resizeBar.width / 2, resizeBar.y + 120); await page.mouse.down(); await page.mouse.move(resizeBar.x + 100, resizeBar.y + 120); await page.mouse.up(); + const viewBWidth = (await page.locator('.dock').boundingBox()).width; + await rpc('session-focus', { sessionId: viewA.id }); + await page.getByRole('button', { name: '展开工具面板', exact: true }).waitFor(); + ok(await page.locator('.dock').count() === 0, '[' + scheme + '] B 的展开状态泄漏到 A'); + await page.reload(); await page.getByRole('button', { name: '展开工具面板', exact: true }).waitFor(); + await page.getByRole('button', { name: '展开工具面板', exact: true }).click(); + ok(await page.getByRole('tab', { name: '工作区文件', exact: true }).getAttribute('aria-selected') === 'true', '[' + scheme + '] A 丢失了独立工具页签'); + await page.getByRole('button', { name: '收起工具面板', exact: true }).click(); + await rpc('session-focus', { sessionId: viewB.id }); await page.locator('.browser-bar').waitFor(); + const restoredViewBWidth = (await page.locator('.dock').boundingBox()).width; + ok(Math.abs(restoredViewBWidth - viewBWidth) < 2, '[' + scheme + '] B 丢失了独立面板宽度:' + viewBWidth + ' → ' + restoredViewBWidth); + await rpc('session-focus', { sessionId: viewA.id }); + await page.getByRole('textbox', { name: '任务指令' }).fill('UI_THINKING_CHECK_' + scheme); + await page.getByRole('button', { name: '发送(Enter)', exact: true }).click(); + await page.locator('.reason-head').first().waitFor(); + await page.locator('.reason-head').first().click(); + await page.locator('.reasoning-body').filter({ hasText: 'UI_THINKING_LIVE' }).waitFor(); + ok(await page.getByRole('button', { name: '停止响应', exact: true }).count() === 1 && await page.getByRole('button', { name: '发送(Enter)', exact: true }).count() === 0, '[' + scheme + '] 运行中应仅显示一个停止按钮'); + ok(await page.locator('.composer').evaluate(el => !el.classList.contains('rt-Card') && ['borderTopLeftRadius', 'borderTopRightRadius', 'borderBottomLeftRadius', 'borderBottomRightRadius'].every(k => getComputedStyle(el)[k] === '22px')), '[' + scheme + '] 输入框应使用完整且一致的四角圆角'); + ok(await page.locator('.stage-identity').innerText().then(text => !/https?:\/\//.test(text)), '[' + scheme + '] 对话顶部不应重复网址'); + ok(await page.locator('.reasoning-body script').count() === 0 && !await page.evaluate(() => window.__thinkingScriptExecuted), '[' + scheme + '] 思考内容被当作脚本执行'); + const thoughtSnapshot = await rpc('session-snapshot', { sessionId: viewA.id }); + ok(thoughtSnapshot.partialReasoning.includes('UI_THINKING_LIVE') && !thoughtSnapshot.partial, '[' + scheme + '] 思考流没有独立保存'); + await page.setViewportSize({ width: 1080, height: 680 }); + await checkProcessRow(page, '[' + scheme + '] 窄窗口实时思考'); + await page.screenshot({ path: path.join(SHOTS, scheme + '-reasoning-1080.png') }); + await page.setViewportSize({ width: 1440, height: 900 }); + await page.screenshot({ path: path.join(SHOTS, scheme + '-reasoning-live.png') }); + await page.reload(); await page.locator('.reason-head').first().waitFor(); + ok(await page.locator('.reasoning-body').count() === 0, '[' + scheme + '] 刷新后思考应默认收起'); + await page.locator('.reason-head').first().click(); + await page.locator('.reasoning-body').filter({ hasText: 'UI_THINKING_LIVE' }).waitFor(); + await rpc('session-focus', { sessionId: viewB.id }); await page.locator('.browser-bar').waitFor(); + ok(await page.locator('.reason-row').count() === 0, '[' + scheme + '] 思考内容泄漏到另一会话'); + await rpc('session-focus', { sessionId: viewA.id }); await page.locator('.reason-head').first().waitFor(); + pendingReasoning.get(scheme)(); + await page.locator('.msg.assistant').filter({ hasText: '思考展示验证完成。' }).waitFor(); + // 与 DSH 一致:完成后的思考默认收起,执行过程收成一行摘要。 + await page.reload(); await page.locator('.turn-process > summary:not([hidden])').first().waitFor(); + ok(await page.locator('.reason-row.is-open').count() === 0, '[' + scheme + '] 完成后思考应默认收起'); + // 完成后执行过程默认折叠,先展开再检查思考内容。 + await page.locator('.turn-process > summary:not([hidden])').first().click(); + await page.locator('.reason-head').first().click(); + await page.locator('.reasoning-body').filter({ hasText: 'UI_THINKING_FINAL' }).waitFor(); + await page.locator('.reason-head').click(); await page.locator('.reasoning-body').waitFor({ state: 'hidden' }); + await page.locator('.reason-head').click(); await page.locator('.reasoning-body').waitFor(); + await page.screenshot({ path: path.join(SHOTS, scheme + '-reasoning-saved.png') }); + await page.reload(); + await page.locator('.turn-process > summary:not([hidden])').first().click(); + await page.locator('.reason-head').first().click(); + await page.locator('.reasoning-body').filter({ hasText: 'UI_THINKING_FINAL' }).waitFor(); + const retryChat = await rpc('session-create', { title: '模型恢复验证', projectId: codeProject.id }); await rpc('session-focus', { sessionId: retryChat.id }); + await page.getByRole('textbox', { name: '任务指令' }).fill('UI_RETRY_CHECK_' + scheme); + await page.getByRole('button', { name: '发送(Enter)', exact: true }).click(); + await page.getByText(/模型连接重试 1\/10/).waitFor(); + await checkProcessRow(page, '[' + scheme + '] 模型重试长状态'); + await page.screenshot({ path: path.join(SHOTS, scheme + '-model-retry.png') }); + await page.reload(); await page.getByText(/模型连接重试 [12]\/10/).waitFor(); + releasedRetry.add(scheme); pendingRetry.get(scheme)?.(); + await page.locator('.msg.assistant').filter({ hasText: '模型重试验证完成。' }).waitFor(); + ok(modelRetries.get(scheme) === 3, '[' + scheme + '] 模型恢复请求次数错误'); + ok(await page.getByText(/模型连接重试 [12]\/10/).count() === 0, '[' + scheme + '] 模型恢复后仍残留重试状态'); + // Work tabs exercise the real document, browser-page and PTY contracts. + const tabRoot = path.join(DATA, 'ui-tabs-' + scheme); fs.mkdirSync(tabRoot); + const tabProject = await rpc('project-save', { scope, project: { name: 'UI tabs ' + scheme, folders: [folder(tabRoot, 'tabs')], primaryKey: 'tabs' } }); + const workChat = await rpc('session-create', { title: '多标签工作验证 ' + scheme, projectId: tabProject.id }); + await rpc('session-focus', { sessionId: workChat.id }); await showTool(page, 'files'); + fs.mkdirSync(path.join(workChat.workspace.root, 'nested'), { recursive: true }); + fs.writeFileSync(path.join(workChat.workspace.root, 'report.md'), '# 工作报告\n\n[继续阅读](nested/next.md)\n\n[不应执行](javascript:alert(1))'); + fs.writeFileSync(path.join(workChat.workspace.root, 'nested/next.md'), '# 后续文档\n\nDOC_TAB_VERIFIED'); + await page.getByRole('button', { name: '刷新文件目录', exact: true }).click(); + await page.getByRole('button', { name: '复制工作目录路径', exact: true }).click(); + ok(await page.evaluate(() => navigator.clipboard.readText()) === workChat.workspace.root, '[' + scheme + '] 工作区文件应能复制目录路径'); + await page.locator('.workspace-tree [data-path="report.md"]').click(); + await page.locator('.document-panel').getByRole('heading', { name: '工作报告', exact: true }).waitFor(); + ok(await page.locator('.document-panel a[href^="javascript:"]').count() === 0, '[' + scheme + '] 文档不能渲染危险协议链接'); + const beforeReuse = await page.locator('.dock-tabs [role="tab"]').count(); + await showTool(page, 'files'); await page.locator('.workspace-tree [data-path="report.md"]').click(); + ok(await page.locator('.dock-tabs [role="tab"]').count() === beforeReuse, '[' + scheme + '] 同一文档应复用标签页'); + await page.locator('.dock-body[data-state="active"]').getByRole('tab', { name: '源码', exact: true }).click(); + ok((await page.locator('.dock-body[data-state="active"] .document-content').innerText()).startsWith('# 工作报告'), '[' + scheme + '] Markdown 源码视图不可用'); + await page.locator('.dock-body[data-state="active"]').getByRole('tab', { name: '预览', exact: true }).click(); + await page.locator('.dock-body[data-state="active"]').getByRole('link', { name: '继续阅读', exact: true }).click(); + await page.locator('.document-panel').getByRole('heading', { name: '后续文档', exact: true }).waitFor(); + await page.screenshot({ path: path.join(SHOTS, scheme + '-document-tabs.png') }); + await page.getByRole('button', { name: '新建标签页', exact: true }).click(); + await page.getByRole('menuitem', { name: '工作区文件标签页', exact: true }).click(); + ok(await page.locator('.dock-tab-wrap[data-tab-kind="files"]').count() === 2, '[' + scheme + '] 应支持多个目录浏览标签'); + const secondFiles = page.locator('.dock-tab-wrap[data-tab-kind="files"]').last(); await secondFiles.hover(); await secondFiles.getByRole('button').click(); + ok(await page.locator('.dock-tab-wrap[data-tab-kind="files"]').count() === 1 && fs.existsSync(path.join(workChat.workspace.root, 'report.md')), '[' + scheme + '] 关闭文件标签不应删除文件'); + await showTool(page, 'browser'); + const firstBrowserId = await page.locator('.dock-tab-wrap[data-tab-kind="browser"]').first().getAttribute('data-tab-id'); + const browserA = 'http://127.0.0.1:' + PORT + '/__ui-fixture?tab=A', browserB = 'http://127.0.0.1:' + PORT + '/__ui-fixture?tab=B'; + await page.getByRole('textbox', { name: '目标网址' }).fill(browserA); await page.getByRole('textbox', { name: '目标网址' }).press('Enter'); + await page.locator('.screen-canvas').waitFor({ timeout: 90000 }); + await page.getByRole('button', { name: '新建标签页', exact: true }).click(); await page.getByRole('menuitem', { name: '浏览器标签页', exact: true }).click(); + ok(await page.getByRole('textbox', { name: '目标网址' }).inputValue() === '', '[' + scheme + '] 新浏览器标签不应继承另一页面网址'); + await page.getByRole('textbox', { name: '目标网址' }).fill(browserB); await page.getByRole('textbox', { name: '目标网址' }).press('Enter'); + await page.waitForFunction(url => document.querySelector('[aria-label="目标网址"]')?.value === url && !!document.querySelector('.screen-canvas'), browserB); + const secondBrowser = page.locator('.dock-tab-wrap[data-tab-kind="browser"]').last(); const secondBrowserId = await secondBrowser.getAttribute('data-tab-id'); + await page.locator('.dock-tab-wrap[data-tab-id="' + firstBrowserId + '"]').getByRole('tab').click(); + await page.waitForFunction(url => document.querySelector('[aria-label="目标网址"]')?.value === url && !!document.querySelector('.screen-canvas'), browserA); + const selectedPage = await rpc('tool-run', { sessionId: workChat.id, name: 'browser_snapshot', args: {} }); + ok(selectedPage.text.includes(browserA), '[' + scheme + '] 浏览器标签必须切换真实CDP页面'); + await page.getByRole('button', { name: '显示网络请求', exact: true }).click(); + await page.getByPlaceholder('过滤 URL / 参数名').fill('api'); + await showTool(page, 'files'); + await page.locator('.dock-tab-wrap[data-tab-id="' + firstBrowserId + '"]').getByRole('tab').click(); + ok(await page.getByPlaceholder('过滤 URL / 参数名').inputValue() === 'api', '[' + scheme + '] 浏览器标签应保留网络筛选'); + await page.locator('.dock-tab-wrap[data-tab-id="' + secondBrowserId + '"]').hover(); + await page.locator('.dock-tab-wrap[data-tab-id="' + secondBrowserId + '"]').getByRole('button').click(); + await page.locator('.dock-tab-wrap[data-tab-id="' + secondBrowserId + '"]').waitFor({ state: 'detached' }); + ok(JSON.parse((await rpc('tool-run', { sessionId: workChat.id, name: 'browser_tabs', args: {} })).text).length === 1, '[' + scheme + '] 关闭浏览器标签应关闭真实页面'); + await rpc('session-set-mode', { sessionId: workChat.id, mode: 'full-access' }); + await page.getByRole('button', { name: '新建标签页', exact: true }).click(); await page.getByRole('menuitem', { name: '终端标签页', exact: true }).click(); + await page.locator('.terminal-panel').getByText('当前用户权限', { exact: true }).waitFor(); + const terminalId = await page.locator('.dock-tab-wrap[data-tab-kind="terminal"]').getAttribute('data-tab-id'); + await page.getByRole('menu').waitFor({ state: 'detached' }); + await page.waitForFunction(() => document.activeElement?.matches('.terminal-screen .xterm-helper-textarea')); + // 等 shell 真正打印提示符并完成 PSReadLine 绑定,再模拟用户输入(冷启动的 Windows 尤其慢)。 + const promptRe = process.platform === 'win32' ? /PS [^>\r\n]*>/ : /[$#] /; + const promptDeadline = Date.now() + 45000; + while (!promptRe.test((await rpc('terminal-snapshot', { sessionId: workChat.id, id: terminalId })).output)) { if (Date.now() > promptDeadline) throw Error('Terminal prompt not ready'); await page.waitForTimeout(100); } + await page.waitForTimeout(800); + await page.keyboard.type(process.platform === 'win32' ? "Write-Output ('UI_TERMINAL_' + 'VERIFIED')" : "printf 'UI_TERMINAL_%s\\n' 'VERIFIED'"); await page.keyboard.press('Enter'); + // CI runner 上 PowerShell 回显要几秒,12 秒不够(实测 02:53 那条就是在这一步超时)。 + const terminalDeadline = Date.now() + 60000; + while (!(await rpc('terminal-snapshot', { sessionId: workChat.id, id: terminalId })).output.includes('UI_TERMINAL_VERIFIED')) { if (Date.now() > terminalDeadline) throw Error('Terminal UI input failed'); await page.waitForTimeout(50); } + ok(await page.getByRole('menu').count() === 0, '[' + scheme + '] 终端输入回车不能重新打开新建标签菜单'); + await page.screenshot({ path: path.join(SHOTS, scheme + '-terminal-tabs.png') }); + const tabCount = await page.locator('.dock-tabs [role="tab"]').count(); + await page.reload(); await page.locator('.terminal-panel').getByText('当前用户权限', { exact: true }).waitFor(); + ok(await page.locator('.dock-tabs [role="tab"]').count() === tabCount, '[' + scheme + '] 重载丢失工作标签页'); + await page.locator('.dock-tab-wrap[data-tab-id="' + terminalId + '"]').hover(); await page.locator('.dock-tab-wrap[data-tab-id="' + terminalId + '"]').getByRole('button').click(); + await page.locator('.dock-tab-wrap[data-tab-id="' + terminalId + '"]').waitFor({ state: 'detached' }); + let closedTerminal = false; try { await rpc('terminal-snapshot', { sessionId: workChat.id, id: terminalId }); } catch { closedTerminal = true; } ok(closedTerminal, '[' + scheme + '] 关闭终端标签应释放进程'); + await rpc('project-attach', { sessionId: workChat.id, projectId: codeProject.id }); + await page.locator('.dock-tabs').getByRole('tab', { name: 'report.md', exact: true }).click(); + await page.locator('.dock-body[data-state="active"]').getByRole('alert').filter({ hasText: '之前的工作目录' }).waitFor(); + const disposable = await rpc('session-create', { title: '仅删除这个测试对话', projectId: codeProject.id }); + await rpc('session-focus', { sessionId: disposable.id }); + const openRail = page.getByRole('button', { name: '展开会话列表', exact: true }); + if (await openRail.count()) await openRail.click(); + await page.locator('.session-item.on').hover(); + await page.locator('.session-item.on button[aria-label="会话操作"]').click(); + await page.getByRole('menuitem', { name: '删除对话', exact: true }).click(); + const deletion = page.getByRole('dialog', { name: '确认操作' }); + await deletion.waitFor(); + ok((await deletion.innerText()).includes('外部项目文件保留'), '[' + scheme + '] 删除应明确告知外部目录保留'); + await deletion.getByRole('button', { name: '删除对话', exact: true }).click(); + await page.locator('.session-item[data-session-id="' + disposable.id + '"]').waitFor({ state: 'detached' }); + ok(!fs.existsSync(disposable.projectDir), '[' + scheme + '] 删除后不应遗留会话私有目录'); + await page.reload(); await page.locator('.stage-identity').waitFor(); + ok(!(await rpc('session-list')).sessions.some(s => s.id === disposable.id), '[' + scheme + '] 已删除对话不应在重载后复活'); + ok(errs.length === 0, '[' + scheme + '] 遍历后报错: ' + (errs[0] || '')); + await ctx.close(); +} } catch (error) { + if (activePage && !activePage.isClosed()) { + await activePage.screenshot({ path: path.join(SHOTS, 'failure.png') }).catch(() => {}); + const browserErrors = await activePage.locator('.browser-error').allTextContents().catch(() => []); + if (browserErrors.length) console.error('Browser UI diagnostics: ' + browserErrors.join(' | ')); + const metrics = await activePage.locator('.project-picker-panel').evaluateAll(nodes => nodes.map(node => ({ rect: node.getBoundingClientRect().toJSON(), side: node.getAttribute('data-side'), animations: node.getAnimations().map(a => ({ state: a.playState, time: a.currentTime })) }))).catch(() => []); + if (metrics.length) console.error('Project popup diagnostics: ' + JSON.stringify(metrics)); + } + // 中断前已经累积的契约失败同样要报出来,否则真正的回归会被后面的环境错误盖住。 + if (fails.length) { + console.error('\n✖ 中断前已记录 UI 契约失败 ' + fails.length + ' 项:'); + for (const f of fails) console.error(' · ' + f); + } + if (SKIPPED.length) { + const unique = [...new Map(SKIPPED.map(s => [s.name, s])).values()]; + console.error('\n⚠ 中断前已跳过 ' + unique.length + ' 段(这些段没有被验证):'); + for (const s of unique) console.error(' · ' + s.name + ':' + s.reason); + } + throw error; +} finally { + await browser.close(); srv.closeAllConnections(); srv.close(); sidecar.kill(); +} + +if (fails.length) { + console.error('\n✖ UI 契约失败 ' + fails.length + ' 项:'); + for (const f of fails) console.error(' · ' + f); + console.error('\n截图:' + SHOTS); + process.exit(1); +} +// 跳过的东西必须说出来。悄悄跳过等于把「没验证」伪装成「通过」, +// 那比红灯更糟:红灯至少会让人去看。 +if (SKIPPED.length) { + const unique = [...new Map(SKIPPED.map(s => [s.name, s])).values()]; + console.log('⚠ 已跳过 ' + unique.length + ' 段(其余断言全部通过):'); + for (const s of unique) console.log(' · ' + s.name + ':' + s.reason); + console.log(''); +} +const sections = [...enabled].join(', '); +console.log('✔ UI 契约通过(分节:' + sections + ';截图:' + SHOTS + ')');