diff --git a/.gitattributes b/.gitattributes index 96ceb9af..a37de13c 100644 --- a/.gitattributes +++ b/.gitattributes @@ -12,3 +12,6 @@ docs/workers-*.json -text whitespace=blank-at-eol,blank-at-eof,space-before-tab, docs/controlled-engine-*.tap binary docs/controlled-engine-*-log.txt binary docs/controlled-engine-*.json -text whitespace=blank-at-eol,blank-at-eof,space-before-tab,cr-at-eol +docs/desktop-window-*.tap binary +docs/desktop-window-*.txt binary +docs/desktop-window-*.json -text whitespace=blank-at-eol,blank-at-eof,space-before-tab,cr-at-eol diff --git a/.gitignore b/.gitignore index 9ae2e7da..89adb101 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,8 @@ /node_modules/ /dist-client/ /dist-server/ +/dist-desktop/ +/.desktop-profile/ /dist/ /examples/delivery-report/dist/ /artifacts/ diff --git a/Start-Desktop.cmd b/Start-Desktop.cmd new file mode 100644 index 00000000..046ac5cb --- /dev/null +++ b/Start-Desktop.cmd @@ -0,0 +1,2 @@ +@echo off +powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0scripts\Start-Desktop.ps1" %* diff --git a/docs/QA-1.15.md b/docs/QA-1.15.md index be69763f..57e39cdf 100644 --- a/docs/QA-1.15.md +++ b/docs/QA-1.15.md @@ -22,6 +22,14 @@ Electron固定45.2.0的真实二进制为249810432字节,SHA256010ea51bfb528c8 Python依赖缺失的原失败未启动宿主,随后独立桌面虚拟环境固定Playwright1.64.1。真实UI首轮发现select可访问标签不完整,原失败报告/日志保留;补aria-label。首个已通过布局仍拥挤,保留prelayout原截图/报告,采用既有蓝白控制台的表单网格和当前标签可见性,再实际1440/390复验与人工截图审查通过。不同Windows账号未登录验收;已实际验证错误entropy/损坏并验证不同SID拒绝,不将其写为跨账号实测。 -## C–F +## C:实际桌面窗口与本机入口(通过) -Electron窗口与IPC正在实施,真实窗口尚未验收;安装/可回退更新、桌面三工程和独立发行按[执行方案](PLAN-1.15.md)继续。 +[17项边界与旧升级兼容](desktop-window-c-tests.tap)通过;[7组真实Electron流程](desktop-window-c-actual.json)及[独立原生选择框](desktop-window-c-native.json)通过。固定45.2.0桌面窗口与Node宿主分别拥有实际PID,窗口刷新、关闭和重新打开后保留原Task/Run/审批ID、eventSeq及完整已完成工具行。实际命令审批、文件提案和Node测试通过。渲染页无Node/require/ipcRenderer,固定六个preload方法,实际错误归属/路径/SHA/附加字段拒绝;外部窗口、导航与网络请求拒绝,原窗口刷新后仍可完成任务。 + +自动流程中的目录/文件系统Shell及停止确认明确使用自有dialog/shell适配夹具;没有将适配器调用记成真实Explorer或系统确认交互。另一个独立实际Windows目录选择框未替换dialog/shell,由computer-use实际观察地址栏、输入所属路径、导航并点击打开项目;宿主和原窗口选择了native-picked-project。首次UIA索引/焦点元数据不一致、set_value拒绝和取消后重开保留说明,最终通过地址栏与画面核对完成原生交互。 + +1440与390的真实窗口截图已人工检查,标题、宿主状态、长路径、项目操作和停止按钮完整可读,窄屏无页面横向溢出。原启动参数、Windows启动器PID、被取消导航的自动化待状态、needs_review误期待、动作未完成及窄屏检视区遮罩失败全部单独保留。补齐实际入口解析、旧升级夹具元数据和验证器原完成信号,未降低产品任务/文件守卫。完整工程、安装和发行留待D–F。 + +## D–F + +安装/可回退更新正在实施;桌面三工程和独立发行按[执行方案](PLAN-1.15.md)继续。 diff --git a/docs/RETROSPECTIVE-1.15.md b/docs/RETROSPECTIVE-1.15.md index e8c84c6a..b3bab0c6 100644 --- a/docs/RETROSPECTIVE-1.15.md +++ b/docs/RETROSPECTIVE-1.15.md @@ -17,3 +17,11 @@ 21专项/兼容和7组实际浏览器、独立宿主重启及HTTP验证通过。DPAPI密文同SQLite事务提交,保存失败回退连接、路由、旧内存引用和全部原行;仅处理用户新填或当前确认导入。已保存连接的原修订跨进程保持,临时连接清除;关闭、删除和清除语义分别验证。SID/目录/源修订异常不自动重写原块。跨Windows账号登录尚未进行,证据不从SID测试外推。 浏览器通过不等于视觉完成:首个窄屏截图仍使用挤在一行的默认控件,原结果保留,补既有控制台表单网格和选中导航自动可见后重新验收。下一C继续同一React客户端,原文件入口只在所属项目定位,不执行文件;Task审查核对当前项目/会话/Task。Electron窗口关闭后自行退出,独立Node继续执行;明确退出宿主才等待所属工具结束。单实例、主frame/固定IPC、导航与权限拒绝均需实际Electron验证。 + +## C回顾 + +17相关专项、7组实际Electron自动流程和独立原生目录选择框通过。实际程序的参数顺序、进程包装层及事件API需要直接观察,不能从旧Electron示例推断。宿主登记实际主进程创建/SID/程序,窗口登记与执行活动分别计数;更新需等待任务且关闭窗口,窗口关闭不结束后台任务。 + +本机入口保持六项固定行为及当前项目/Task/原文件SHA。目录选择在真实Windows原生窗口中完成,自动dialog/shell夹具与真实系统操作分别记录。原UIA元数据不一致时改由实际地址栏与截图核对;不能将注入dialog返回路径宣称原生选择框通过。1440/390截图人工核对通过。原运行失败均保存,校准等待真实任务needs_review、异步操作结束和检视区覆盖状态,产品守卫保持。 + +下一D把安装程序、活动版本指针和原执行宿主分开:候选写入新版本目录,预检不结束未知进程;完整输入核验/原持久行与工件对照后才切换,失败须恢复原处理器和指针。程序与用户数据目录分离,卸载先核对所属进程与活动,原数据保留。该安装管理器仍为草稿,不能按文件存在计入通过。 diff --git a/docs/desktop-window-argv-observation.json b/docs/desktop-window-argv-observation.json new file mode 100644 index 00000000..38442214 --- /dev/null +++ b/docs/desktop-window-argv-observation.json @@ -0,0 +1,14 @@ +{ + "argv": [ + "D:\\Ai-project\\REA逆向\\Agent-Workbench\\node_modules\\electron\\dist\\electron.exe", + "--inspect=0", + "--remote-debugging-port=0", + "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-argv-probe.cjs", + "--app-root", + "D:\\Ai-project\\REA逆向\\Agent-Workbench", + "--hidden-window" + ], + "packaged": false, + "defaultApp": true, + "appPath": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa" +} \ No newline at end of file diff --git a/docs/desktop-window-c-actual.json b/docs/desktop-window-c-actual.json new file mode 100644 index 00000000..1487c716 --- /dev/null +++ b/docs/desktop-window-c-actual.json @@ -0,0 +1,97 @@ +{ + "success": true, + "root": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-window-7c8a8e58-44e2-44c8-a306-6460dc9c19cf", + "appRoot": "D:\\Ai-project\\REA逆向\\Agent-Workbench", + "dataRoot": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-window-7c8a8e58-44e2-44c8-a306-6460dc9c19cf\\data", + "port": 52351, + "results": [ + { + "name": "actual Electron process registered and original host reused", + "passed": true, + "electronPid": 42352, + "launcherPid": 42588, + "hostPid": 45472 + }, + { + "name": "sandboxed renderer and fixed preload", + "passed": true, + "surface": { + "methods": [ + "pickProject", + "projectFolder", + "protocol", + "revealFile", + "reviewTask", + "status", + "stopHost" + ], + "require": "undefined", + "process": "undefined", + "ipc": "undefined", + "frozen": true + } + }, + { + "name": "external navigation, requests and popups rejected", + "passed": true, + "navigation": { + "url": "http://127.0.0.1:52351/?desktop=1&release=1.14.0", + "loading": false + }, + "originalWindowRefreshed": true + }, + { + "name": "offline original task and approval retained across refresh and window close", + "passed": true, + "taskId": "03a04c4b-f268-44aa-8a3d-1bf04601ef64", + "runId": "46c1e4ec-6a5c-4786-9fd0-14f88d86f7f2", + "approvalId": "c21e3256-eac2-47e6-91f6-7f872c792108", + "eventSeq": 39, + "completedTools": 3 + }, + { + "name": "actual command approval, proposal and project check", + "passed": true, + "changeId": "2cbcc343-1533-4001-99cd-05ec4feba6b8", + "checkId": "b0a19e01-9bb4-410b-b0ae-72b9f6e0b6f8", + "checkStatus": "passed" + }, + { + "name": "current project, task and file desktop entry scope", + "passed": true, + "invalidRejected": 4, + "fixtureCalls": [ + { + "folder": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-window-7c8a8e58-44e2-44c8-a306-6460dc9c19cf\\owned-project" + }, + { + "reveal": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-window-7c8a8e58-44e2-44c8-a306-6460dc9c19cf\\owned-project\\README.md" + } + ], + "screenshots": [ + { + "name": "desktop-host-1440", + "width": 1440, + "png": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-window-7c8a8e58-44e2-44c8-a306-6460dc9c19cf\\desktop-host-1440.png" + }, + { + "name": "desktop-host-390", + "width": 390, + "png": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-window-7c8a8e58-44e2-44c8-a306-6460dc9c19cf\\desktop-host-390.png" + } + ], + "nativeOperations": "Dialog/shell adapters are declared fixtures in this automated run; actual Windows picker separately verified." + }, + { + "name": "native stop cancelled, then original host explicitly stopped", + "passed": true, + "hostPid": 45472, + "exited": true, + "confirmation": "Declared native confirmation fixtures: cancelled first, confirmed second." + } + ], + "errors": [], + "requests": [], + "native": false, + "inference": "Offline demo/local engineering checks only; no configured model or existing credentials." +} \ No newline at end of file diff --git a/docs/desktop-window-c-actual.txt b/docs/desktop-window-c-actual.txt new file mode 100644 index 00000000..2cf9aadd --- /dev/null +++ b/docs/desktop-window-c-actual.txt @@ -0,0 +1,7 @@ +actual Electron process registered and original host reused: passed +sandboxed renderer and fixed preload: passed +external navigation, requests and popups rejected: passed +offline original task and approval retained across refresh and window close: passed +actual command approval, proposal and project check: passed +current project, task and file desktop entry scope: passed +native stop cancelled, then original host explicitly stopped: passed diff --git a/docs/desktop-window-c-cancelled-navigation-failure.json b/docs/desktop-window-c-cancelled-navigation-failure.json new file mode 100644 index 00000000..b98bb7b8 --- /dev/null +++ b/docs/desktop-window-c-cancelled-navigation-failure.json @@ -0,0 +1,44 @@ +{ + "success": false, + "root": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-window-482b51b0-7e5b-42da-86e6-3664468774ce", + "appRoot": "D:\\Ai-project\\REA逆向\\Agent-Workbench", + "dataRoot": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-window-482b51b0-7e5b-42da-86e6-3664468774ce\\data", + "stage": "offline original task and approval retained across refresh and window close", + "results": [ + { + "name": "actual Electron process registered and original host reused", + "passed": true, + "electronPid": 30828, + "launcherPid": 9640, + "hostPid": 6152 + }, + { + "name": "sandboxed renderer and fixed preload", + "passed": true, + "surface": { + "methods": [ + "pickProject", + "projectFolder", + "protocol", + "revealFile", + "reviewTask", + "status", + "stopHost" + ], + "require": "undefined", + "process": "undefined", + "ipc": "undefined", + "frozen": true + } + }, + { + "name": "external navigation, requests and popups rejected", + "passed": true + } + ], + "errors": [], + "requests": [], + "message": "locator.fill: Timeout 30000ms exceeded.\nCall log:\n\u001b[2m - waiting for getByRole('textbox', { name: '任务内容', exact: true })\u001b[22m\n\u001b[2m - waiting for navigation to finish...\u001b[22m\n", + "stack": "locator.fill: Timeout 30000ms exceeded.\nCall log:\n\u001b[2m - waiting for getByRole('textbox', { name: '任务内容', exact: true })\u001b[22m\n\u001b[2m - waiting for navigation to finish...\u001b[22m\n\n at D:\\Ai-project\\REA逆向\\Agent-Workbench\\scripts\\verify-desktop-window.mjs:75:68", + "native": false +} \ No newline at end of file diff --git a/docs/desktop-window-c-cancelled-navigation-failure.txt b/docs/desktop-window-c-cancelled-navigation-failure.txt new file mode 100644 index 00000000..51019ff3 --- /dev/null +++ b/docs/desktop-window-c-cancelled-navigation-failure.txt @@ -0,0 +1,21 @@ +actual Electron process registered and original host reused: passed +sandboxed renderer and fixed preload: passed +external navigation, requests and popups rejected: passed +node:internal/modules/run_main:107 + triggerUncaughtException( + ^ + +locator.fill: Timeout 30000ms exceeded. +Call log: + - waiting for getByRole('textbox', { name: '任务内容', exact: true }) + - waiting for navigation to finish... + + at D:\Ai-project\REA逆向\Agent-Workbench\scripts\verify-desktop-window.mjs:75:68 { + log: [ + " - waiting for getByRole('textbox', { name: '任务内容', exact: true })", + ' - waiting for navigation to finish...' + ], + name: 'TimeoutError' +} + +Node.js v24.22.1 diff --git a/docs/desktop-window-c-command-status-failure.json b/docs/desktop-window-c-command-status-failure.json new file mode 100644 index 00000000..b9ecb7c3 --- /dev/null +++ b/docs/desktop-window-c-command-status-failure.json @@ -0,0 +1,58 @@ +{ + "success": false, + "root": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-window-0aa718c0-123b-480a-be13-445c4cbeb3f9", + "appRoot": "D:\\Ai-project\\REA逆向\\Agent-Workbench", + "dataRoot": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-window-0aa718c0-123b-480a-be13-445c4cbeb3f9\\data", + "stage": "actual command approval, proposal and project check", + "results": [ + { + "name": "actual Electron process registered and original host reused", + "passed": true, + "electronPid": 22584, + "launcherPid": 38792, + "hostPid": 44740 + }, + { + "name": "sandboxed renderer and fixed preload", + "passed": true, + "surface": { + "methods": [ + "pickProject", + "projectFolder", + "protocol", + "revealFile", + "reviewTask", + "status", + "stopHost" + ], + "require": "undefined", + "process": "undefined", + "ipc": "undefined", + "frozen": true + } + }, + { + "name": "external navigation, requests and popups rejected", + "passed": true, + "navigation": { + "url": "http://127.0.0.1:61132/?desktop=1&release=1.14.0", + "loading": false + }, + "originalWindowRefreshed": true + }, + { + "name": "offline original task and approval retained across refresh and window close", + "passed": true, + "taskId": "2fa506b6-999b-4ea8-b21e-8ff9f1ba6604", + "runId": "83c4d394-13a1-4b55-99e5-27e0788e0fd5", + "approvalId": "4beab323-df6b-40c5-8f87-adf236dfc71f", + "eventSeq": 39, + "completedTools": 3 + } + ], + "errors": [], + "requests": [], + "message": "Timeout: actual command approval, proposal and project check", + "stack": "Error: Timeout: actual command approval, proposal and project check\n at until (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/scripts/verify-desktop-window.mjs:24:150)\n at process.processTicksAndRejections (node:internal/process/task_queues:104:5)\n at async file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/scripts/verify-desktop-window.mjs:91:5", + "native": false +} \ No newline at end of file diff --git a/docs/desktop-window-c-command-status-failure.txt b/docs/desktop-window-c-command-status-failure.txt new file mode 100644 index 00000000..0aaa33b5 --- /dev/null +++ b/docs/desktop-window-c-command-status-failure.txt @@ -0,0 +1,14 @@ +actual Electron process registered and original host reused: passed +sandboxed renderer and fixed preload: passed +external navigation, requests and popups rejected: passed +offline original task and approval retained across refresh and window close: passed +node:internal/modules/run_main:107 + triggerUncaughtException( + ^ + +Error: Timeout: actual command approval, proposal and project check + at until (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/scripts/verify-desktop-window.mjs:24:150) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + at async file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/scripts/verify-desktop-window.mjs:91:5 + +Node.js v24.22.1 diff --git a/docs/desktop-window-c-first-failure.tap b/docs/desktop-window-c-first-failure.tap new file mode 100644 index 00000000..e4fab508 --- /dev/null +++ b/docs/desktop-window-c-first-failure.tap @@ -0,0 +1,56 @@ +✔ native bridge refuses other origins, subframes, other windows and unsupported inputs before connecting (1041.1465ms) +✔ file reveal binds the current project, task, path, UTF-8 bytes and original SHA without executing the file (1052.7284ms) +✔ file changed during asynchronous task recheck is not revealed as the old bytes (763.4965ms) +✔ desktop browser profile and aliases stay outside project inventory and file access (555.4141ms) +✔ native picker cancel and origin change after dialog publish no project registration (751.8651ms) +✔ pending native action is not dispatched twice, and current task review returns its original seq (758.7382ms) +✔ native stop cancellation and changed original host never stop a replacement process (929.6215ms) +✔ window register rejects host PID, stale installation, extra fields and missing creation identity (0.3288ms) +✔ host challenge proof rejects a stale challenge, changed identity and changed signature (1.1508ms) +✔ stop confirmation binds the original instance, creation and loaded runtime (0.1309ms) +✔ state paths reject escaping, linked ancestors, ambiguous hardlinks and damaged JSON (1324.597ms) +✔ failed registration publishes no initialized memory and can complete after its actual inputs are supplied (2831.8227ms) +✔ host shutdown cancels an un-signalled HTTP model request and refuses later requests until recovered (1.2625ms) +✔ host shutdown cancels model-pool acquisition and releases queue ownership without inventing attempts (960.0883ms) +✖ a directly started compiled host upgrades twice with the same PID, sessions, applied bytes and volatile provider (2772.119ms) +✖ the running 0.1.0 process upgrades in place and retains its project, session, files and volatile model connection (5176.3498ms) +ℹ tests 16 +ℹ suites 0 +ℹ pass 14 +ℹ fail 2 +ℹ cancelled 0 +ℹ skipped 0 +ℹ todo 0 +ℹ duration_ms 13279.8574 + +✖ failing tests: + +test at tests\upgrade.test.mjs:10:1 +✖ a directly started compiled host upgrades twice with the same PID, sessions, applied bytes and volatile provider (2772.119ms) + Error: Runtime upgrade failed: Error: 宿主安装版本无效。 + at hostError (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/.qa/test-6bJFVa/compiled-upgrade-first/dist-server/hot-upgrade.mjs:20482:91) + at inspectHostInstallation (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/.qa/test-6bJFVa/compiled-upgrade-first/dist-server/hot-upgrade.mjs:31369:78) + at HostAuthority.refreshInstallation (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/.qa/test-6bJFVa/compiled-upgrade-first/dist-server/hot-upgrade.mjs:31472:28) + at Module.installUpgrade (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/.qa/test-6bJFVa/compiled-upgrade-first/dist-server/hot-upgrade.mjs:32511:17) + at :1:323 + at :1:526 + at upgradeRunning (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/scripts/upgrade-running.mjs:129:42) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + at async TestContext. (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/tests/upgrade.test.mjs:23:20) + at async Test.run (node:internal/test_runner/test:1409:7) + at async startSubtestAfterBootstrap (node:internal/test_runner/harness:387:3) + +test at tests\upgrade.test.mjs:37:1 +✖ the running 0.1.0 process upgrades in place and retains its project, session, files and volatile model connection (5176.3498ms) + Error: Runtime upgrade failed: Error: 宿主安装版本无效。 + at hostError (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/.qa/test-p8Dw4Q/upgrade-second/dist-server/hot-upgrade.mjs:20482:91) + at inspectHostInstallation (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/.qa/test-p8Dw4Q/upgrade-second/dist-server/hot-upgrade.mjs:31369:78) + at HostAuthority.refreshInstallation (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/.qa/test-p8Dw4Q/upgrade-second/dist-server/hot-upgrade.mjs:31472:28) + at Module.installUpgrade (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/.qa/test-p8Dw4Q/upgrade-second/dist-server/hot-upgrade.mjs:32511:17) + at :1:307 + at :1:502 + at upgradeRunning (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/scripts/upgrade-running.mjs:129:42) + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) + at async TestContext. (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/tests/upgrade.test.mjs:88:18) + at async Test.run (node:internal/test_runner/test:1409:7) + at async Test.processPendingSubtests (node:internal/test_runner/test:974:7) diff --git a/docs/desktop-window-c-initial-launch-failure.txt b/docs/desktop-window-c-initial-launch-failure.txt new file mode 100644 index 00000000..6b04df5c --- /dev/null +++ b/docs/desktop-window-c-initial-launch-failure.txt @@ -0,0 +1,10 @@ +file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/scripts/verify-desktop-window.mjs:8 +import { _electron, expect } from 'playwright'; + ^^^^^^ +SyntaxError: The requested module 'playwright' does not provide an export named 'expect' + at #asyncInstantiate (node:internal/modules/esm/module_job:455:21) + at async ModuleJob.run (node:internal/modules/esm/module_job:553:5) + at async node:internal/modules/esm/loader:647:26 + at async asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:101:5) + +Node.js v24.22.1 diff --git a/docs/desktop-window-c-narrow-inspector-failure.json b/docs/desktop-window-c-narrow-inspector-failure.json new file mode 100644 index 00000000..eaf452ab --- /dev/null +++ b/docs/desktop-window-c-narrow-inspector-failure.json @@ -0,0 +1,91 @@ +{ + "success": false, + "root": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-window-40bc2dad-d50f-4414-854d-ff84525f0f82", + "appRoot": "D:\\Ai-project\\REA逆向\\Agent-Workbench", + "dataRoot": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-window-40bc2dad-d50f-4414-854d-ff84525f0f82\\data", + "stage": "native stop cancelled, then original host explicitly stopped", + "results": [ + { + "name": "actual Electron process registered and original host reused", + "passed": true, + "electronPid": 20124, + "launcherPid": 24188, + "hostPid": 29036 + }, + { + "name": "sandboxed renderer and fixed preload", + "passed": true, + "surface": { + "methods": [ + "pickProject", + "projectFolder", + "protocol", + "revealFile", + "reviewTask", + "status", + "stopHost" + ], + "require": "undefined", + "process": "undefined", + "ipc": "undefined", + "frozen": true + } + }, + { + "name": "external navigation, requests and popups rejected", + "passed": true, + "navigation": { + "url": "http://127.0.0.1:60302/?desktop=1&release=1.14.0", + "loading": false + }, + "originalWindowRefreshed": true + }, + { + "name": "offline original task and approval retained across refresh and window close", + "passed": true, + "taskId": "687ec778-d8c9-4e79-9049-4c6b8fdb9638", + "runId": "d3e9a3f1-7e44-4ed4-b9fa-1cadcf420620", + "approvalId": "83e56937-b518-485a-a412-ec3010176a93", + "eventSeq": 39, + "completedTools": 3 + }, + { + "name": "actual command approval, proposal and project check", + "passed": true, + "changeId": "9a2fb972-dfcc-4262-869b-928d4057a3a7", + "checkId": "8bcb014d-afc7-4df5-b2f6-499a40509320", + "checkStatus": "passed" + }, + { + "name": "current project, task and file desktop entry scope", + "passed": true, + "invalidRejected": 4, + "fixtureCalls": [ + { + "folder": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-window-40bc2dad-d50f-4414-854d-ff84525f0f82\\owned-project" + }, + { + "reveal": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-window-40bc2dad-d50f-4414-854d-ff84525f0f82\\owned-project\\README.md" + } + ], + "screenshots": [ + { + "name": "desktop-host-1440", + "width": 1440, + "png": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-window-40bc2dad-d50f-4414-854d-ff84525f0f82\\desktop-host-1440.png" + }, + { + "name": "desktop-host-390", + "width": 390, + "png": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-window-40bc2dad-d50f-4414-854d-ff84525f0f82\\desktop-host-390.png" + } + ], + "nativeOperations": "Dialog/shell adapters are declared fixtures in this automated run; actual Windows picker separately verified." + } + ], + "errors": [], + "requests": [], + "message": "locator.click: Timeout 30000ms exceeded.\nCall log:\n\u001b[2m - waiting for getByRole('button', { name: '桌面宿主', exact: true })\u001b[22m\n\u001b[2m - locator resolved to \u001b[22m\n\u001b[2m - attempting click action\u001b[22m\n\u001b[2m 2 × waiting for element to be visible, enabled and stable\u001b[22m\n\u001b[2m - element is visible, enabled and stable\u001b[22m\n\u001b[2m - scrolling into view if needed\u001b[22m\n\u001b[2m - done scrolling\u001b[22m\n\u001b[2m - from subtree intercepts pointer events\u001b[22m\n\u001b[2m - retrying click action\u001b[22m\n\u001b[2m - waiting 20ms\u001b[22m\n\u001b[2m 2 × waiting for element to be visible, enabled and stable\u001b[22m\n\u001b[2m - element is visible, enabled and stable\u001b[22m\n\u001b[2m - scrolling into view if needed\u001b[22m\n\u001b[2m - done scrolling\u001b[22m\n\u001b[2m - from subtree intercepts pointer events\u001b[22m\n\u001b[2m - retrying click action\u001b[22m\n\u001b[2m - waiting 100ms\u001b[22m\n\u001b[2m 10 × waiting for element to be visible, enabled and stable\u001b[22m\n\u001b[2m - element is visible, enabled and stable\u001b[22m\n\u001b[2m - scrolling into view if needed\u001b[22m\n\u001b[2m - done scrolling\u001b[22m\n\u001b[2m - from subtree intercepts pointer events\u001b[22m\n\u001b[2m - retrying click action\u001b[22m\n\u001b[2m - waiting 500ms\u001b[22m\n\u001b[2m - waiting for element to be visible, enabled and stable\u001b[22m\n", + "stack": "locator.click: Timeout 30000ms exceeded.\nCall log:\n\u001b[2m - waiting for getByRole('button', { name: '桌面宿主', exact: true })\u001b[22m\n\u001b[2m - locator resolved to \u001b[22m\n\u001b[2m - attempting click action\u001b[22m\n\u001b[2m 2 × waiting for element to be visible, enabled and stable\u001b[22m\n\u001b[2m - element is visible, enabled and stable\u001b[22m\n\u001b[2m - scrolling into view if needed\u001b[22m\n\u001b[2m - done scrolling\u001b[22m\n\u001b[2m - from subtree intercepts pointer events\u001b[22m\n\u001b[2m - retrying click action\u001b[22m\n\u001b[2m - waiting 20ms\u001b[22m\n\u001b[2m 2 × waiting for element to be visible, enabled and stable\u001b[22m\n\u001b[2m - element is visible, enabled and stable\u001b[22m\n\u001b[2m - scrolling into view if needed\u001b[22m\n\u001b[2m - done scrolling\u001b[22m\n\u001b[2m - from subtree intercepts pointer events\u001b[22m\n\u001b[2m - retrying click action\u001b[22m\n\u001b[2m - waiting 100ms\u001b[22m\n\u001b[2m 10 × waiting for element to be visible, enabled and stable\u001b[22m\n\u001b[2m - element is visible, enabled and stable\u001b[22m\n\u001b[2m - scrolling into view if needed\u001b[22m\n\u001b[2m - done scrolling\u001b[22m\n\u001b[2m - from subtree intercepts pointer events\u001b[22m\n\u001b[2m - retrying click action\u001b[22m\n\u001b[2m - waiting 500ms\u001b[22m\n\u001b[2m - waiting for element to be visible, enabled and stable\u001b[22m\n\n at D:\\Ai-project\\REA逆向\\Agent-Workbench\\scripts\\verify-desktop-window.mjs:111:139", + "native": false +} \ No newline at end of file diff --git a/docs/desktop-window-c-narrow-inspector-failure.txt b/docs/desktop-window-c-narrow-inspector-failure.txt new file mode 100644 index 00000000..85dc1060 --- /dev/null +++ b/docs/desktop-window-c-narrow-inspector-failure.txt @@ -0,0 +1,70 @@ +actual Electron process registered and original host reused: passed +sandboxed renderer and fixed preload: passed +external navigation, requests and popups rejected: passed +offline original task and approval retained across refresh and window close: passed +actual command approval, proposal and project check: passed +current project, task and file desktop entry scope: passed +node:internal/modules/run_main:107 + triggerUncaughtException( + ^ + +locator.click: Timeout 30000ms exceeded. +Call log: + - waiting for getByRole('button', { name: '桌面宿主', exact: true }) + - locator resolved to + - attempting click action + 2 × waiting for element to be visible, enabled and stable + - element is visible, enabled and stable + - scrolling into view if needed + - done scrolling + - from subtree intercepts pointer events + - retrying click action + - waiting 20ms + 2 × waiting for element to be visible, enabled and stable + - element is visible, enabled and stable + - scrolling into view if needed + - done scrolling + - from subtree intercepts pointer events + - retrying click action + - waiting 100ms + 10 × waiting for element to be visible, enabled and stable + - element is visible, enabled and stable + - scrolling into view if needed + - done scrolling + - from subtree intercepts pointer events + - retrying click action + - waiting 500ms + - waiting for element to be visible, enabled and stable + + at D:\Ai-project\REA逆向\Agent-Workbench\scripts\verify-desktop-window.mjs:111:139 { + log: [ + " - waiting for getByRole('button', { name: '桌面宿主', exact: true })", + ' - locator resolved to ', + ' - attempting click action', + ' 2 × waiting for element to be visible, enabled and stable', + ' - element is visible, enabled and stable', + ' - scrolling into view if needed', + ' - done scrolling', + ' - from subtree intercepts pointer events', + ' - retrying click action', + ' - waiting 20ms', + ' 2 × waiting for element to be visible, enabled and stable', + ' - element is visible, enabled and stable', + ' - scrolling into view if needed', + ' - done scrolling', + ' - from subtree intercepts pointer events', + ' - retrying click action', + ' - waiting 100ms', + ' 10 × waiting for element to be visible, enabled and stable', + ' - element is visible, enabled and stable', + ' - scrolling into view if needed', + ' - done scrolling', + ' - from subtree intercepts pointer events', + ' - retrying click action', + ' - waiting 500ms', + ' - waiting for element to be visible, enabled and stable' + ], + name: 'TimeoutError' +} + +Node.js v24.22.1 diff --git a/docs/desktop-window-c-native-action-pending-failure.json b/docs/desktop-window-c-native-action-pending-failure.json new file mode 100644 index 00000000..86dcc163 --- /dev/null +++ b/docs/desktop-window-c-native-action-pending-failure.json @@ -0,0 +1,65 @@ +{ + "success": false, + "root": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-window-4405c645-1965-42a3-9b9d-19eda45915f5", + "appRoot": "D:\\Ai-project\\REA逆向\\Agent-Workbench", + "dataRoot": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-window-4405c645-1965-42a3-9b9d-19eda45915f5\\data", + "stage": "current project, task and file desktop entry scope", + "results": [ + { + "name": "actual Electron process registered and original host reused", + "passed": true, + "electronPid": 38140, + "launcherPid": 22964, + "hostPid": 9564 + }, + { + "name": "sandboxed renderer and fixed preload", + "passed": true, + "surface": { + "methods": [ + "pickProject", + "projectFolder", + "protocol", + "revealFile", + "reviewTask", + "status", + "stopHost" + ], + "require": "undefined", + "process": "undefined", + "ipc": "undefined", + "frozen": true + } + }, + { + "name": "external navigation, requests and popups rejected", + "passed": true, + "navigation": { + "url": "http://127.0.0.1:58653/?desktop=1&release=1.14.0", + "loading": false + }, + "originalWindowRefreshed": true + }, + { + "name": "offline original task and approval retained across refresh and window close", + "passed": true, + "taskId": "d09fdb94-113c-4f95-ba1b-5ba183e36fbd", + "runId": "903d110d-93c0-4af1-b990-f84a5f59a22e", + "approvalId": "369a25c6-40b1-4765-8e8b-7e479bb205ae", + "eventSeq": 39, + "completedTools": 3 + }, + { + "name": "actual command approval, proposal and project check", + "passed": true, + "changeId": "9db0d16e-6cae-4550-ae1b-5a69b173f142", + "checkId": "be1db518-c349-4944-80dc-f97161988f92", + "checkStatus": "passed" + } + ], + "errors": [], + "requests": [], + "message": "Expected values to be strictly deep-equal:\n+ actual - expected\n\n [\n {\n folder: 'D:\\\\Ai-project\\\\REA逆向\\\\Agent-Workbench\\\\.qa\\\\desktop-window-4405c645-1965-42a3-9b9d-19eda45915f5\\\\owned-project'\n },\n- {\n- reveal: 'D:\\\\Ai-project\\\\REA逆向\\\\Agent-Workbench\\\\.qa\\\\desktop-window-4405c645-1965-42a3-9b9d-19eda45915f5\\\\owned-project\\\\README.md'\n- }\n ]\n", + "stack": "AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:\n+ actual - expected\n\n [\n {\n folder: 'D:\\\\Ai-project\\\\REA逆向\\\\Agent-Workbench\\\\.qa\\\\desktop-window-4405c645-1965-42a3-9b9d-19eda45915f5\\\\owned-project'\n },\n- {\n- reveal: 'D:\\\\Ai-project\\\\REA逆向\\\\Agent-Workbench\\\\.qa\\\\desktop-window-4405c645-1965-42a3-9b9d-19eda45915f5\\\\owned-project\\\\README.md'\n- }\n ]\n\n at file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/scripts/verify-desktop-window.mjs:106:99", + "native": false +} \ No newline at end of file diff --git a/docs/desktop-window-c-native-action-pending-failure.txt b/docs/desktop-window-c-native-action-pending-failure.txt new file mode 100644 index 00000000..aff41d72 --- /dev/null +++ b/docs/desktop-window-c-native-action-pending-failure.txt @@ -0,0 +1,42 @@ +actual Electron process registered and original host reused: passed +sandboxed renderer and fixed preload: passed +external navigation, requests and popups rejected: passed +offline original task and approval retained across refresh and window close: passed +actual command approval, proposal and project check: passed +node:internal/modules/run_main:107 + triggerUncaughtException( + ^ + +AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal: ++ actual - expected + + [ + { + folder: 'D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-window-4405c645-1965-42a3-9b9d-19eda45915f5\\owned-project' + }, +- { +- reveal: 'D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-window-4405c645-1965-42a3-9b9d-19eda45915f5\\owned-project\\README.md' +- } + ] + + at file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/scripts/verify-desktop-window.mjs:106:99 { + generatedMessage: true, + code: 'ERR_ASSERTION', + actual: [ + { + folder: 'D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-window-4405c645-1965-42a3-9b9d-19eda45915f5\\owned-project' + } + ], + expected: [ + { + folder: 'D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-window-4405c645-1965-42a3-9b9d-19eda45915f5\\owned-project' + }, + { + reveal: 'D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-window-4405c645-1965-42a3-9b9d-19eda45915f5\\owned-project\\README.md' + } + ], + operator: 'deepStrictEqual', + diff: 'simple' +} + +Node.js v24.22.1 diff --git a/docs/desktop-window-c-native-interaction.md b/docs/desktop-window-c-native-interaction.md new file mode 100644 index 00000000..d041d53b --- /dev/null +++ b/docs/desktop-window-c-native-interaction.md @@ -0,0 +1,11 @@ +# 实际Windows目录选择框记录 + +2026-10-31,独立端口54547,Electron主PID18984,原Node宿主PID39972。原报告见desktop-window-c-native.json和desktop-window-c-native.txt。 + +- 系统dialog使用Electron45.2.0实际showOpenDialog/openDirectory,没有替换dialog或shell。由真实桌面“选择项目文件夹”打开。 +- computer-use/sky观察到标题“选择工作台项目”的实际Windows选择框。原生UIA树中出现重复子树,第一次字段索引和focused_element元数据与画面不同;set_value被系统拒绝,未把这次尝试算成选择成功。首次文字操作之后选择框取消,原宿主未登记新目录。 +- 重新打开实际选择框,通过Ctrl+L聚焦地址栏,输入独立自有native-picked-project目录。画面与原生地址Value均核对为报告root下的同一绝对路径。 +- 按Return导航后,原生地址工具栏与“文件夹”字段均显示native-picked-project。点击实际“打开项目”按钮,宿主实际登记该目录,React窗口选择该项目;未执行任何目录命令。 +- 验收器保存原窗口native-picker-result.png并返回success=true;宿主最后正常停止,正式23172进程未使用。 + +系统输入由Windows computer-use工具完成。自动化流程的文件管理器适配器和停止确认夹具只验证调用范围,不作为原生Explorer/系统确认窗口实测。 diff --git a/docs/desktop-window-c-native.json b/docs/desktop-window-c-native.json new file mode 100644 index 00000000..99d97ae3 --- /dev/null +++ b/docs/desktop-window-c-native.json @@ -0,0 +1,26 @@ +{ + "success": true, + "root": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-window-1099b6c3-c55e-49a4-955f-5331e43af2f1", + "appRoot": "D:\\Ai-project\\REA逆向\\Agent-Workbench", + "dataRoot": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-window-1099b6c3-c55e-49a4-955f-5331e43af2f1\\data", + "port": 54547, + "results": [ + { + "name": "actual Electron process registered and original host reused", + "passed": true, + "electronPid": 18984, + "launcherPid": 44920, + "hostPid": 39972 + }, + { + "name": "actual native directory picker", + "passed": true, + "directory": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-window-1099b6c3-c55e-49a4-955f-5331e43af2f1\\native-picked-project", + "dialog": "Actual Windows openDirectory dialog; no dialog/shell replacement in this run." + } + ], + "errors": [], + "requests": [], + "native": true, + "inference": "Offline demo/local engineering checks only; no configured model or existing credentials." +} \ No newline at end of file diff --git a/docs/desktop-window-c-native.txt b/docs/desktop-window-c-native.txt new file mode 100644 index 00000000..50154a93 --- /dev/null +++ b/docs/desktop-window-c-native.txt @@ -0,0 +1,3 @@ +actual Electron process registered and original host reused: passed +{"nativePickerReady":true,"expectedPath":"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-window-1099b6c3-c55e-49a4-955f-5331e43af2f1\\native-picked-project","electronPid":18984,"hostPid":39972,"root":"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-window-1099b6c3-c55e-49a4-955f-5331e43af2f1"} +actual native directory picker: passed diff --git a/docs/desktop-window-c-process-wrapper-failure.json b/docs/desktop-window-c-process-wrapper-failure.json new file mode 100644 index 00000000..82091fee --- /dev/null +++ b/docs/desktop-window-c-process-wrapper-failure.json @@ -0,0 +1,13 @@ +{ + "success": false, + "root": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-window-da84b90c-75c6-434e-804c-d2c12abf704f", + "appRoot": "D:\\Ai-project\\REA逆向\\Agent-Workbench", + "dataRoot": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-window-da84b90c-75c6-434e-804c-d2c12abf704f\\data", + "stage": "start", + "results": [], + "errors": [], + "requests": [], + "message": "Expected values to be strictly equal:\n\n31468 !== 12644\n", + "stack": "AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:\n\n31468 !== 12644\n\n at file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/scripts/verify-desktop-window.mjs:51:105\n at process.processTicksAndRejections (node:internal/process/task_queues:104:5)", + "native": false +} \ No newline at end of file diff --git a/docs/desktop-window-c-process-wrapper-failure.txt b/docs/desktop-window-c-process-wrapper-failure.txt new file mode 100644 index 00000000..92a56d63 --- /dev/null +++ b/docs/desktop-window-c-process-wrapper-failure.txt @@ -0,0 +1,19 @@ +node:internal/modules/run_main:107 + triggerUncaughtException( + ^ + +AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: + +31468 !== 12644 + + at file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/scripts/verify-desktop-window.mjs:51:105 + at process.processTicksAndRejections (node:internal/process/task_queues:104:5) { + generatedMessage: true, + code: 'ERR_ASSERTION', + actual: 31468, + expected: 12644, + operator: 'strictEqual', + diff: 'simple' +} + +Node.js v24.22.1 diff --git a/docs/desktop-window-c-second-launch-failure.json b/docs/desktop-window-c-second-launch-failure.json new file mode 100644 index 00000000..2f7a95d1 --- /dev/null +++ b/docs/desktop-window-c-second-launch-failure.json @@ -0,0 +1,13 @@ +{ + "success": false, + "root": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-window-c4954b58-c8e6-4d32-8131-7c64f6c11982", + "appRoot": "D:\\Ai-project\\REA逆向\\Agent-Workbench", + "dataRoot": "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-window-c4954b58-c8e6-4d32-8131-7c64f6c11982\\data", + "stage": "start", + "results": [], + "errors": [], + "requests": [], + "message": "electron.launch: Timeout 60000ms exceeded.\nCall log:\n\u001b[2m - \"D:\\Ai-project\\REA逆向\\Agent-Workbench\\node_modules\\electron\\dist\\electron.exe\" \"--inspect=0\" \"--remote-debugging-port=0\" \"D:\\Ai-project\\REA逆向\\Agent-Workbench\\dist-desktop\\main.cjs\" \"--app-root\" \"D:\\Ai-project\\REA逆向\\Agent-Workbench\" \"--data-root\" \"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-window-c4954b58-c8e6-4d32-8131-7c64f6c11982\\data\" \"--node\" \"D:\\Ai-project\\REA逆向\\tools\\node-v24.22.1-win-x64\\node.exe\" \"--port\" \"57080\" \"--hidden-window\"\u001b[22m\n\u001b[2m - pid=37120\u001b[22m\n\u001b[2m - [pid=37120][out]\u001b[22m\n\u001b[2m - [pid=37120][err] Debugger listening on ws://127.0.0.1:58046/f544cb03-bcab-40b7-b481-cdb75e7bffff\u001b[22m\n\u001b[2m - [pid=37120][err] For help, see: https://nodejs.org/learn/getting-started/debugging\u001b[22m\n\u001b[2m - ws://127.0.0.1:58046/f544cb03-bcab-40b7-b481-cdb75e7bffff\u001b[22m\n\u001b[2m - ws://127.0.0.1:58046/f544cb03-bcab-40b7-b481-cdb75e7bffff\u001b[22m\n\u001b[2m - [pid=37120][err] Debugger attached.\u001b[22m\n\u001b[2m - [pid=37120][err] App threw an error during load\u001b[22m\n\u001b[2m - [pid=37120][err] Error: Unsupported desktop option.\u001b[22m\n\u001b[2m - [pid=37120][err] at Object. (D:\\Ai-project\\REA逆向\\Agent-Workbench\\dist-desktop\\main.cjs:688:113)\u001b[22m\n\u001b[2m - [pid=37120][err] at Module._compile (node:internal/modules/cjs/loader:1937:14)\u001b[22m\n\u001b[2m - [pid=37120][err] at Object..js (node:internal/modules/cjs/loader:2070:10)\u001b[22m\n\u001b[2m - [pid=37120][err] at Module.load (node:internal/modules/cjs/loader:1658:32)\u001b[22m\n\u001b[2m - [pid=37120][err] at Module._load (node:internal/modules/cjs/loader:1450:12)\u001b[22m\n\u001b[2m - [pid=37120][err] at wrapModuleLoad (node:internal/modules/cjs/loader:268:19)\u001b[22m\n\u001b[2m - [pid=37120][err] at loadCJSModuleWithModuleLoad (node:internal/modules/esm/translators:378:15)\u001b[22m\n\u001b[2m - [pid=37120][err] at ModuleWrap. (node:internal/modules/esm/translators:246:9)\u001b[22m\n\u001b[2m - [pid=37120][err] at ModuleJob.run (node:internal/modules/esm/module_job:561:25)\u001b[22m\n\u001b[2m - [pid=37120][err] at async node:internal/modules/esm/loader:647:26\u001b[22m\n", + "stack": "electron.launch: Timeout 60000ms exceeded.\nCall log:\n\u001b[2m - \"D:\\Ai-project\\REA逆向\\Agent-Workbench\\node_modules\\electron\\dist\\electron.exe\" \"--inspect=0\" \"--remote-debugging-port=0\" \"D:\\Ai-project\\REA逆向\\Agent-Workbench\\dist-desktop\\main.cjs\" \"--app-root\" \"D:\\Ai-project\\REA逆向\\Agent-Workbench\" \"--data-root\" \"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-window-c4954b58-c8e6-4d32-8131-7c64f6c11982\\data\" \"--node\" \"D:\\Ai-project\\REA逆向\\tools\\node-v24.22.1-win-x64\\node.exe\" \"--port\" \"57080\" \"--hidden-window\"\u001b[22m\n\u001b[2m - pid=37120\u001b[22m\n\u001b[2m - [pid=37120][out]\u001b[22m\n\u001b[2m - [pid=37120][err] Debugger listening on ws://127.0.0.1:58046/f544cb03-bcab-40b7-b481-cdb75e7bffff\u001b[22m\n\u001b[2m - [pid=37120][err] For help, see: https://nodejs.org/learn/getting-started/debugging\u001b[22m\n\u001b[2m - ws://127.0.0.1:58046/f544cb03-bcab-40b7-b481-cdb75e7bffff\u001b[22m\n\u001b[2m - ws://127.0.0.1:58046/f544cb03-bcab-40b7-b481-cdb75e7bffff\u001b[22m\n\u001b[2m - [pid=37120][err] Debugger attached.\u001b[22m\n\u001b[2m - [pid=37120][err] App threw an error during load\u001b[22m\n\u001b[2m - [pid=37120][err] Error: Unsupported desktop option.\u001b[22m\n\u001b[2m - [pid=37120][err] at Object. (D:\\Ai-project\\REA逆向\\Agent-Workbench\\dist-desktop\\main.cjs:688:113)\u001b[22m\n\u001b[2m - [pid=37120][err] at Module._compile (node:internal/modules/cjs/loader:1937:14)\u001b[22m\n\u001b[2m - [pid=37120][err] at Object..js (node:internal/modules/cjs/loader:2070:10)\u001b[22m\n\u001b[2m - [pid=37120][err] at Module.load (node:internal/modules/cjs/loader:1658:32)\u001b[22m\n\u001b[2m - [pid=37120][err] at Module._load (node:internal/modules/cjs/loader:1450:12)\u001b[22m\n\u001b[2m - [pid=37120][err] at wrapModuleLoad (node:internal/modules/cjs/loader:268:19)\u001b[22m\n\u001b[2m - [pid=37120][err] at loadCJSModuleWithModuleLoad (node:internal/modules/esm/translators:378:15)\u001b[22m\n\u001b[2m - [pid=37120][err] at ModuleWrap. (node:internal/modules/esm/translators:246:9)\u001b[22m\n\u001b[2m - [pid=37120][err] at ModuleJob.run (node:internal/modules/esm/module_job:561:25)\u001b[22m\n\u001b[2m - [pid=37120][err] at async node:internal/modules/esm/loader:647:26\u001b[22m\n\n at async launch (D:\\Ai-project\\REA逆向\\Agent-Workbench\\scripts\\verify-desktop-window.mjs:31:19)\n at async file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/scripts/verify-desktop-window.mjs:49:28", + "native": false +} \ No newline at end of file diff --git a/docs/desktop-window-c-second-launch-failure.txt b/docs/desktop-window-c-second-launch-failure.txt new file mode 100644 index 00000000..c5c695cd --- /dev/null +++ b/docs/desktop-window-c-second-launch-failure.txt @@ -0,0 +1,55 @@ +node:internal/modules/run_main:107 + triggerUncaughtException( + ^ + +electron.launch: Timeout 60000ms exceeded. +Call log: + - "D:\Ai-project\REA逆向\Agent-Workbench\node_modules\electron\dist\electron.exe" "--inspect=0" "--remote-debugging-port=0" "D:\Ai-project\REA逆向\Agent-Workbench\dist-desktop\main.cjs" "--app-root" "D:\Ai-project\REA逆向\Agent-Workbench" "--data-root" "D:\Ai-project\REA逆向\Agent-Workbench\.qa\desktop-window-c4954b58-c8e6-4d32-8131-7c64f6c11982\data" "--node" "D:\Ai-project\REA逆向\tools\node-v24.22.1-win-x64\node.exe" "--port" "57080" "--hidden-window" + - pid=37120 + - [pid=37120][out] + - [pid=37120][err] Debugger listening on ws://127.0.0.1:58046/f544cb03-bcab-40b7-b481-cdb75e7bffff + - [pid=37120][err] For help, see: https://nodejs.org/learn/getting-started/debugging + - ws://127.0.0.1:58046/f544cb03-bcab-40b7-b481-cdb75e7bffff + - ws://127.0.0.1:58046/f544cb03-bcab-40b7-b481-cdb75e7bffff + - [pid=37120][err] Debugger attached. + - [pid=37120][err] App threw an error during load + - [pid=37120][err] Error: Unsupported desktop option. + - [pid=37120][err] at Object. (D:\Ai-project\REA逆向\Agent-Workbench\dist-desktop\main.cjs:688:113) + - [pid=37120][err] at Module._compile (node:internal/modules/cjs/loader:1937:14) + - [pid=37120][err] at Object..js (node:internal/modules/cjs/loader:2070:10) + - [pid=37120][err] at Module.load (node:internal/modules/cjs/loader:1658:32) + - [pid=37120][err] at Module._load (node:internal/modules/cjs/loader:1450:12) + - [pid=37120][err] at wrapModuleLoad (node:internal/modules/cjs/loader:268:19) + - [pid=37120][err] at loadCJSModuleWithModuleLoad (node:internal/modules/esm/translators:378:15) + - [pid=37120][err] at ModuleWrap. (node:internal/modules/esm/translators:246:9) + - [pid=37120][err] at ModuleJob.run (node:internal/modules/esm/module_job:561:25) + - [pid=37120][err] at async node:internal/modules/esm/loader:647:26 + + at async launch (D:\Ai-project\REA逆向\Agent-Workbench\scripts\verify-desktop-window.mjs:31:19) + at async file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/scripts/verify-desktop-window.mjs:49:28 { + log: [ + ' - "D:\\Ai-project\\REA逆向\\Agent-Workbench\\node_modules\\electron\\dist\\electron.exe" "--inspect=0" "--remote-debugging-port=0" "D:\\Ai-project\\REA逆向\\Agent-Workbench\\dist-desktop\\main.cjs" "--app-root" "D:\\Ai-project\\REA逆向\\Agent-Workbench" "--data-root" "D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\desktop-window-c4954b58-c8e6-4d32-8131-7c64f6c11982\\data" "--node" "D:\\Ai-project\\REA逆向\\tools\\node-v24.22.1-win-x64\\node.exe" "--port" "57080" "--hidden-window"', + ' - pid=37120', + ' - [pid=37120][out]', + ' - [pid=37120][err] Debugger listening on ws://127.0.0.1:58046/f544cb03-bcab-40b7-b481-cdb75e7bffff', + ' - [pid=37120][err] For help, see: https://nodejs.org/learn/getting-started/debugging', + ' - ws://127.0.0.1:58046/f544cb03-bcab-40b7-b481-cdb75e7bffff', + ' - ws://127.0.0.1:58046/f544cb03-bcab-40b7-b481-cdb75e7bffff', + ' - [pid=37120][err] Debugger attached.', + ' - [pid=37120][err] App threw an error during load', + ' - [pid=37120][err] Error: Unsupported desktop option.', + ' - [pid=37120][err] at Object. (D:\\Ai-project\\REA逆向\\Agent-Workbench\\dist-desktop\\main.cjs:688:113)', + ' - [pid=37120][err] at Module._compile (node:internal/modules/cjs/loader:1937:14)', + ' - [pid=37120][err] at Object..js (node:internal/modules/cjs/loader:2070:10)', + ' - [pid=37120][err] at Module.load (node:internal/modules/cjs/loader:1658:32)', + ' - [pid=37120][err] at Module._load (node:internal/modules/cjs/loader:1450:12)', + ' - [pid=37120][err] at wrapModuleLoad (node:internal/modules/cjs/loader:268:19)', + ' - [pid=37120][err] at loadCJSModuleWithModuleLoad (node:internal/modules/esm/translators:378:15)', + ' - [pid=37120][err] at ModuleWrap. (node:internal/modules/esm/translators:246:9)', + ' - [pid=37120][err] at ModuleJob.run (node:internal/modules/esm/module_job:561:25)', + ' - [pid=37120][err] at async node:internal/modules/esm/loader:647:26' + ], + name: 'TimeoutError' +} + +Node.js v24.22.1 diff --git a/docs/desktop-window-c-tests.tap b/docs/desktop-window-c-tests.tap new file mode 100644 index 00000000..bc9d6253 --- /dev/null +++ b/docs/desktop-window-c-tests.tap @@ -0,0 +1,25 @@ +✔ actual Electron debug argument ordering retains exactly the compiled entry and rejects extra or repeated actions (1.0927ms) +✔ native bridge refuses other origins, subframes, other windows and unsupported inputs before connecting (980.1395ms) +✔ file reveal binds the current project, task, path, UTF-8 bytes and original SHA without executing the file (993.3536ms) +✔ file changed during asynchronous task recheck is not revealed as the old bytes (720.5266ms) +✔ desktop browser profile and aliases stay outside project inventory and file access (702.1853ms) +✔ native picker cancel and origin change after dialog publish no project registration (870.3146ms) +✔ pending native action is not dispatched twice, and current task review returns its original seq (965.0119ms) +✔ native stop cancellation and changed original host never stop a replacement process (1054.7498ms) +✔ window register rejects host PID, stale installation, extra fields and missing creation identity (0.5311ms) +✔ host challenge proof rejects a stale challenge, changed identity and changed signature (1.1991ms) +✔ stop confirmation binds the original instance, creation and loaded runtime (0.1661ms) +✔ state paths reject escaping, linked ancestors, ambiguous hardlinks and damaged JSON (1268.6224ms) +✔ failed registration publishes no initialized memory and can complete after its actual inputs are supplied (2780.2907ms) +✔ host shutdown cancels an un-signalled HTTP model request and refuses later requests until recovered (1.5702ms) +✔ host shutdown cancels model-pool acquisition and releases queue ownership without inventing attempts (1226.9234ms) +✔ a directly started compiled host upgrades twice with the same PID, sessions, applied bytes and volatile provider (3460.2988ms) +✔ the running 0.1.0 process upgrades in place and retains its project, session, files and volatile model connection (5933.5396ms) +ℹ tests 17 +ℹ suites 0 +ℹ pass 17 +ℹ fail 0 +ℹ cancelled 0 +ℹ skipped 0 +ℹ todo 0 +ℹ duration_ms 14866.8561 diff --git a/docs/screenshots/desktop-host-1.15/desktop-host-1440.png b/docs/screenshots/desktop-host-1.15/desktop-host-1440.png new file mode 100644 index 00000000..7471c45d Binary files /dev/null and b/docs/screenshots/desktop-host-1.15/desktop-host-1440.png differ diff --git a/docs/screenshots/desktop-host-1.15/desktop-host-390.png b/docs/screenshots/desktop-host-1.15/desktop-host-390.png new file mode 100644 index 00000000..95864267 Binary files /dev/null and b/docs/screenshots/desktop-host-1.15/desktop-host-390.png differ diff --git a/docs/screenshots/desktop-host-1.15/native-picker-result.png b/docs/screenshots/desktop-host-1.15/native-picker-result.png new file mode 100644 index 00000000..04378bc7 Binary files /dev/null and b/docs/screenshots/desktop-host-1.15/native-picker-result.png differ diff --git a/findings.md b/findings.md index 92ddc2fd..21587348 100644 --- a/findings.md +++ b/findings.md @@ -626,3 +626,7 @@ A的49专项和9组实际隔离宿主通过,正式1.14/PID23172保持。PowerS # 2026-10-31 B收口与C边界 B实际DPAPI/21专项/7浏览器-重启组通过,未用正式Key。密文与registry同库事务,配置变化保留失效原块;新UI原可访问select错误和prelayout拥挤截图保留,表单网格/活动标签可见后复验。C采用Electron45.2隔离主窗口及6个固定IPC,不导出ipcRenderer/Node;打开目录与文件定位绑定登记项目/当前Task及SHA,窗口退出不结束Node,显式宿主退出保留核验。原窗口内核不复制第二套代理。 + +C实现核对:Electron45.2.0事件类型要求will-frame-navigate仅一个details参数,已修正草稿;窗口登记绑定实际Electron创建/SID/安装程序并与任务活动分开。保护.desktop-profile及本机来源路径,白名单改为实际DeepSeek/Python路径,无凭据。只读恢复曾猜测不存在文件、Windows通配和长minified样式输出失效,后续用rg清单和精确短段;一次重复同文件补丁整体未应用,已合并目标后修正。B已本地提交72a496a,C继续验收。 + +C实际目录选择完成:sky元数据焦点/重复索引与原生光标不一致,set_value原拒绝及首次取消明确未通过;改用实际地址栏Ctrl+L/可见路径/Return导航/实际打开按钮,宿主登记正确目录并选择。真实窗口1440/390截图人工核对状态、动作、长路径和停止入口全部可读。C的原16/17专项及7+2实际组分别记录,D草稿继续。 diff --git a/package.json b/package.json index 8726232f..1031e3a1 100644 --- a/package.json +++ b/package.json @@ -8,6 +8,8 @@ "dev": "vite --host 127.0.0.1", "build": "tsc --noEmit && vite build && node scripts/build-server.mjs", "start": "node dist-server/server.mjs", + "desktop": "electron dist-desktop/main.cjs", + "verify:desktop": "node scripts/verify-desktop-window.mjs", "test": "node --test --test-concurrency=2 tests/*.test.mjs", "verify:ui": "node scripts/verify-ui.mjs", "verify:diagnostics": "node scripts/verify-diagnostics-ui.mjs", diff --git a/progress.md b/progress.md index 47992d04..429d6d8f 100644 --- a/progress.md +++ b/progress.md @@ -652,3 +652,9 @@ # 2026-10-31 B交付前回顾 A提交249f191。B构建及21专项/兼容、7组浏览器/DPAPI恢复/HTTP/全数据目录明文扫描通过,实际28724→49924,新恢复两Key共3次夹具响应。完整公开配置和除runtimeOwner的6表原行保持。原Python缺依赖、首轮无select可访问标签和首个prelayout记录保留,采用独立Playwright1.64.1与既有蓝白网格复验。当前正式仍1.14/PID23172,未启动真实推理;C的主进程/桥/预加载初稿尚未编译或接入,不计交付。 + +C首轮16项14通过、旧两升级夹具缺少package版本元数据;补齐现代候选的原package文件后16/16通过。实际Electron首个验证器误用基础Playwright的expect导出、随后发现调试参数位于脚本前的真实argv顺序;两个原启动失败和实际argv观测保留,显式解析已编译入口及固定参数,继续复验。 + +C收口:7组实际Electron自动验收及2组独立原生选择框宿主/交互通过;关闭/重开保留原Task/Run/审批/eventSeq/完整完成工具行,原确认命令与真实Node检查通过,错误文件入口/外部导航拒绝。Windows原生选择框经sky观察/地址栏输入/导航/打开原目录并在宿主登记,未注入dialog;初次UIA索引/焦点不一致及取消保留说明。自动fixture的dialog/shell/停止确认明确区分。原请求导航待状态、needs_review误期待、异步动作未结束与390px检视区遮罩原失败分别保留,按实际完成信号/关闭检视区复验。D安装管理器是未接入草稿,不计完成。 + +C提交前发现暂存原日志仍为Git自动换行后的字节;为desktop-window日志增加明确binary/-text属性,并用git add --renormalize重新读取原工作区字节。21份窗口原证据与索引逐字节相同,diff --check通过;没有重写原日志或旧提交。 diff --git a/public/workbench-icon.ico b/public/workbench-icon.ico new file mode 100644 index 00000000..ee0c663d Binary files /dev/null and b/public/workbench-icon.ico differ diff --git a/public/workbench-icon.png b/public/workbench-icon.png new file mode 100644 index 00000000..98f98742 Binary files /dev/null and b/public/workbench-icon.png differ diff --git a/scripts/Start-Desktop.ps1 b/scripts/Start-Desktop.ps1 new file mode 100644 index 00000000..f53b61af --- /dev/null +++ b/scripts/Start-Desktop.ps1 @@ -0,0 +1,18 @@ +param([string]$AppRoot = (Split-Path -Parent $PSScriptRoot), [string]$DataRoot = '', [int]$Port = 4318) +$ErrorActionPreference = 'Stop' +$AppRoot = (Resolve-Path -LiteralPath $AppRoot).Path +if (-not $DataRoot) { $DataRoot = Join-Path $env:LOCALAPPDATA 'AgentWorkbench' } +$DesktopExe = Join-Path $AppRoot 'desktop\AgentWorkbench.exe' +$NodeExe = Join-Path $AppRoot 'runtime\node.exe' +$MainFile = Join-Path $AppRoot 'dist-desktop\main.cjs' +$DesktopArgs = @('--app-root', $AppRoot, '--data-root', $DataRoot, '--port', [string]$Port) +if (-not (Test-Path -LiteralPath $DesktopExe)) { + $DesktopExe = Join-Path $AppRoot 'node_modules\electron\dist\electron.exe' + $NodeExe = Join-Path (Split-Path -Parent $AppRoot) 'tools\node-v24.22.1-win-x64\node.exe' + $DesktopArgs = @($MainFile) + $DesktopArgs + @('--node', $NodeExe) +} +foreach ($Required in @($DesktopExe, $NodeExe, $MainFile)) { + if (-not (Test-Path -LiteralPath $Required -PathType Leaf)) { throw "Desktop runtime file is missing: $Required" } +} +$QuotedArgs = ($DesktopArgs | ForEach-Object { if ($_ -match '"') { throw 'Invalid launch path.' }; '"' + $_ + '"' }) -join ' ' +Start-Process -FilePath $DesktopExe -ArgumentList $QuotedArgs -WorkingDirectory $AppRoot -WindowStyle Hidden diff --git a/scripts/build-server.mjs b/scripts/build-server.mjs index 07c17e15..01aff941 100644 --- a/scripts/build-server.mjs +++ b/scripts/build-server.mjs @@ -7,4 +7,9 @@ await build({ entryPoints: ['src/server/hot-upgrade.mjs'], outfile: 'dist-server platform: 'node', target: 'node24', format: 'esm', sourcemap: false, legalComments: 'eof' }); await build({ entryPoints: ['src/desktop/host-cli.mjs'], outfile: 'dist-server/host-launcher.mjs', bundle: true, platform: 'node', target: 'node24', format: 'esm', sourcemap: false, legalComments: 'eof' }); +fs.mkdirSync('dist-desktop', { recursive: true }); +await build({ entryPoints: ['src/desktop/main.mjs'], outfile: 'dist-desktop/main.cjs', bundle: true, external: ['electron'], + platform: 'node', target: 'node24', format: 'cjs', sourcemap: false, legalComments: 'eof' }); +await build({ entryPoints: ['src/desktop/preload.cjs'], outfile: 'dist-desktop/preload.cjs', bundle: true, external: ['electron'], + platform: 'node', target: 'node24', format: 'cjs', sourcemap: false, legalComments: 'eof' }); console.log('Server bundle built.'); diff --git a/scripts/generate-desktop-icon.py b/scripts/generate-desktop-icon.py new file mode 100644 index 00000000..644b2ac4 --- /dev/null +++ b/scripts/generate-desktop-icon.py @@ -0,0 +1,28 @@ +"""Generate the product's deterministic original bracket/workbench icon (PNG and ICO).""" +import pathlib +import struct +import zlib + +size = 256 +rows = [] +for y in range(size): + row = bytearray([0]) + for x in range(size): + color = (28, 64, 115, 255) + if (46 <= x < 64 and 64 <= y < 192 or 46 <= x < 98 and (64 <= y < 82 or 174 <= y < 192) + or 192 <= x < 210 and 64 <= y < 192 or 158 <= x < 210 and (64 <= y < 82 or 174 <= y < 192)): + color = (238, 246, 255, 255) + if 100 <= x < 156 and 119 <= y < 137: + color = (105, 182, 247, 255) + row.extend(color) + rows.append(bytes(row)) + +def chunk(tag, value): + return struct.pack('>I', len(value)) + tag + value + struct.pack('>I', zlib.crc32(tag + value)) + +png = (b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', size, size, 8, 6, 0, 0, 0)) + + chunk(b'IDAT', zlib.compress(b''.join(rows), 9)) + chunk(b'IEND', b'')) +root = pathlib.Path(__file__).resolve().parent.parent / 'public' +(root / 'workbench-icon.png').write_bytes(png) +(root / 'workbench-icon.ico').write_bytes(struct.pack(' arg !== '--native-picker')) throw new Error('Use --help.'); +const native = process.argv.includes('--native-picker'), appRoot = process.cwd(), root = path.resolve('.qa', 'desktop-window-' + randomUUID()); +const dataRoot = path.join(root, 'data'), projectRoot = path.join(root, 'owned-project'); fs.mkdirSync(projectRoot, { recursive: true }); +fs.writeFileSync(path.join(projectRoot, 'README.md'), '# Owned desktop project\n\nOriginal source for desktop lifecycle acceptance.\n'); +fs.writeFileSync(path.join(projectRoot, 'package.json'), JSON.stringify({ name: 'owned-desktop-project', type: 'module', scripts: { test: 'node --test case.test.mjs' } })); +fs.writeFileSync(path.join(projectRoot, 'case.test.mjs'), "import test from 'node:test';import assert from 'node:assert/strict';import fs from 'node:fs';test('original desktop source retained',()=>assert.match(fs.readFileSync('README.md','utf8'),/Original source/));\n"); +const server = net.createServer(); await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); const port = server.address().port; await new Promise(resolve => server.close(resolve)); +const controller = new HostController({ appRoot, dataRoot, port, nodePath: process.execPath, timeoutMs: 60000 }); +let application, page, original, externalServer, stage = 'start', expectedNavigation = false; const results = [], errors = [], requests = []; +const record = (name, detail = {}) => { results.push({ name, passed: true, ...detail }); console.log(name + ': passed'); }; +const until = async (action, timeout = 30000) => { const deadline = Date.now() + timeout; while (!await action()) { if (Date.now() > deadline) throw new Error('Timeout: ' + stage); await new Promise(resolve => setTimeout(resolve, 100)); } }; +const save = result => { fs.writeFileSync(path.join(root, 'result.json'), JSON.stringify(result, null, 2)); fs.writeFileSync('.qa/desktop-window-' + (native ? 'native' : 'latest') + '.json', JSON.stringify(result, null, 2)); }; +const completedTools = id => { + const db = new DatabaseSync(path.join(dataRoot, 'workbench.sqlite'), { readOnly: true }); + try { return db.prepare("SELECT payload FROM records WHERE kind='tool' AND session_id=? ORDER BY id").all(id).map(row => JSON.parse(row.payload)).filter(value => value.state === 'completed'); } finally { db.close(); } +}; +async function launch() { + const current = await _electron.launch({ executablePath: path.join(appRoot, 'node_modules/electron/dist/electron.exe'), + args: [path.join(appRoot, 'dist-desktop/main.cjs'), '--app-root', appRoot, '--data-root', dataRoot, '--node', process.execPath, '--port', String(port), ...(native ? [] : ['--hidden-window'])], + cwd: appRoot, env: projectEnvironment(), timeout: 60000 }); + const window = await current.firstWindow(); + window.on('pageerror', error => errors.push(error.message)); window.on('requestfailed', request => { if (!expectedNavigation) requests.push({ url: request.url(), failure: request.failure()?.errorText }); }); + await window.locator('.connection.connected').waitFor({ timeout: 30000 }); + return { application: current, page: window }; +} +async function snapshot(name, width) { + const window = await application.browserWindow(page); await window.evaluate((value, width) => value.setContentSize(width, 900), width); + await until(() => page.evaluate(width => innerWidth === width, width)); + await page.screenshot({ path: path.join(root, name + '.png') }); fs.writeFileSync(path.join(root, name + '.html'), await page.content()); + const overflow = await page.evaluate(() => document.documentElement.scrollWidth > innerWidth); + assert.equal(overflow, false); return { name, width, png: path.join(root, name + '.png') }; +} +try { + original = (await controller.start()).identity; const project = await controller.api('/projects', { method: 'POST', input: { root: projectRoot } }); + const session = await controller.api('/sessions', { method: 'POST', input: { projectId: project.id } }); + ({ application, page } = await launch()); + const pid = await application.evaluate(() => process.pid), launcherPid = application.process().pid, observed = observeWindowsProcess(pid), status = await controller.status(); + assert.equal(status.identity.pid, original.pid); assert.equal(status.desktopWindows.count, 1); assert.equal(status.desktopWindows.entries[0].pid, pid); assert.equal(status.desktopWindows.entries[0].createdAt, observed.createdAt); record('actual Electron process registered and original host reused', { electronPid: pid, launcherPid, hostPid: original.pid }); + await page.getByRole('combobox', { name: '当前项目', exact: true }).selectOption(project.id); + if (native) { + stage = 'actual native directory picker'; const chosenRoot = path.join(root, 'native-picked-project'); fs.mkdirSync(chosenRoot); fs.writeFileSync(path.join(chosenRoot, 'README.md'), '# Actual native picker project\n'); + await page.getByRole('button', { name: '桌面宿主', exact: true }).click(); + const pending = page.getByRole('button', { name: '选择项目文件夹', exact: true }).click(); + console.log(JSON.stringify({ nativePickerReady: true, expectedPath: chosenRoot, electronPid: pid, hostPid: original.pid, root })); + await until(async () => (await controller.api('/bootstrap')).projects.some(value => value.root.toLowerCase() === chosenRoot.toLowerCase()), 1200000); await pending; + await until(async () => (await page.getByRole('combobox', { name: '当前项目', exact: true }).textContent()).includes('native-picked-project')); + record(stage, { directory: chosenRoot, dialog: 'Actual Windows openDirectory dialog; no dialog/shell replacement in this run.' }); + await snapshot('native-picker-result', 1440); + } else { + stage = 'sandboxed renderer and fixed preload'; + const surface = await page.evaluate(() => ({ methods: Object.keys(window.desktopWorkbench).sort(), require: typeof window.require, process: typeof window.process, ipc: typeof window.ipcRenderer, frozen: Object.isFrozen(window.desktopWorkbench) })); + assert.deepEqual(surface.methods, ['pickProject', 'projectFolder', 'protocol', 'revealFile', 'reviewTask', 'status', 'stopHost'].sort()); + assert.equal(surface.require, 'undefined'); assert.equal(surface.process, 'undefined'); assert.equal(surface.ipc, 'undefined'); assert.equal(surface.frozen, true); + const preferences = await (await application.browserWindow(page)).evaluate(value => value.webContents.getLastWebPreferences()); + assert.equal(preferences.sandbox, true); assert.equal(preferences.contextIsolation, true); assert.equal(preferences.nodeIntegration, false); record(stage, { surface }); + stage = 'external navigation, requests and popups rejected'; let outsideRequests = 0; + externalServer = http.createServer((_req, res) => { outsideRequests++; res.end('owned external fixture'); }); await new Promise(resolve => externalServer.listen(0, '127.0.0.1', resolve)); + const externalUrl = 'http://127.0.0.1:' + externalServer.address().port + '/outside'; expectedNavigation = true; + await page.evaluate(url => { window.open(url); location.href = url; }, externalUrl); await new Promise(resolve => setTimeout(resolve, 300)); + assert.equal(new URL(page.url()).origin, controller.url); assert.equal(application.windows().length, 1); assert.equal(outsideRequests, 0); + const navigation = await (await application.browserWindow(page)).evaluate(value => ({ url: value.webContents.getURL(), loading: value.webContents.isLoading() })); + assert.equal(navigation.loading, false); assert.equal(new URL(navigation.url).origin, controller.url); + // Chromium reports requestedNavigation to Playwright before Electron vetoes it. + // A real window refresh clears that automation-only pending document state. + const refreshed = page.waitForEvent('domcontentloaded'); await (await application.browserWindow(page)).evaluate(value => value.webContents.reload()); await refreshed; + await page.locator('.connection.connected').waitFor(); expectedNavigation = false; record(stage, { navigation, originalWindowRefreshed: true }); + stage = 'offline original task and approval retained across refresh and window close'; + await page.getByRole('textbox', { name: '任务内容', exact: true }).fill('Read this owned project and prepare the offline demonstration proposal.'); await page.getByRole('button', { name: '发送任务', exact: true }).click(); + await page.getByRole('button', { name: '确认执行', exact: true }).waitFor({ timeout: 20000 }); + const before = await controller.api('/sessions/' + session.id), tools = completedTools(session.id), hash = createHash('sha256').update(JSON.stringify(tools)).digest('hex'); assert.ok(tools.length >= 3); + await page.reload(); await page.getByRole('button', { name: '确认执行', exact: true }).waitFor({ timeout: 20000 }); assert.equal((await controller.api('/sessions/' + session.id)).approvals.at(-1).id, before.approvals.at(-1).id); + const closed = application.waitForEvent('close'); await (await application.browserWindow(page)).evaluate(value => value.close()); await closed; application = null; + assert.equal((await controller.connect()).identity.instanceId, original.instanceId); assert.equal(observeWindowsProcess(pid), null); assert.equal((await controller.status()).desktopWindows.count, 0); + ({ application, page } = await launch()); await page.getByRole('button', { name: '确认执行', exact: true }).waitFor({ timeout: 20000 }); + const reopened = await controller.api('/sessions/' + session.id); assert.equal(reopened.execution.task.id, before.execution.task.id); assert.equal(reopened.execution.runs.at(-1).id, before.execution.runs.at(-1).id); assert.equal(reopened.eventSeq, before.eventSeq); assert.equal(reopened.approvals.at(-1).id, before.approvals.at(-1).id); + assert.equal(createHash('sha256').update(JSON.stringify(completedTools(session.id))).digest('hex'), hash); record(stage, { taskId: before.execution.task.id, runId: before.execution.runs.at(-1).id, approvalId: before.approvals.at(-1).id, eventSeq: before.eventSeq, completedTools: tools.length }); + stage = 'actual command approval, proposal and project check'; await page.getByRole('button', { name: '确认执行', exact: true }).click(); + await until(async () => (await controller.api('/sessions/' + session.id)).status === 'needs_review'); + const done = await controller.api('/sessions/' + session.id); const change = done.changes.at(-1); assert.equal(change.status, 'pending'); + await controller.api('/sessions/' + session.id + '/changes/' + change.id + '/apply', { method: 'POST', input: {} }); + const planned = await controller.api('/sessions/' + session.id + '/check-plans', { method: 'POST', input: {} }); + const started = await controller.api('/sessions/' + session.id + '/check-jobs', { method: 'POST', input: { planId: planned.execution.plans.at(-1).id } }), checkId = started.execution.checks.at(-1).id; + await until(async () => !['queued', 'running'].includes((await controller.api('/sessions/' + session.id + '/check-jobs/' + checkId)).status)); + const check = await controller.api('/sessions/' + session.id + '/check-jobs/' + checkId); assert.equal(check.status, 'passed'); record(stage, { changeId: change.id, checkId, checkStatus: check.status }); + stage = 'current project, task and file desktop entry scope'; + await application.evaluate(({ dialog, shell }, projectRoot) => { globalThis.desktopFixtureCalls = []; dialog.showOpenDialog = async () => ({ canceled: false, filePaths: [projectRoot] }); dialog.showMessageBox = async () => ({ response: 0 }); shell.openPath = async value => { globalThis.desktopFixtureCalls.push({ folder: value }); return ''; }; shell.showItemInFolder = value => globalThis.desktopFixtureCalls.push({ reveal: value }); }, projectRoot); + await page.getByRole('button', { name: 'REA 工件研究', exact: true }).waitFor(); + await page.getByRole('button', { name: 'README.md', exact: true }).click(); await page.locator('.file-heading').getByText('README.md', { exact: true }).waitFor(); + const file = await controller.api('/projects/' + project.id + '/file?path=README.md'), scope = { projectId: project.id, sessionId: session.id, taskId: done.execution.task.id }; + const invalid = await page.evaluate(async input => { const rejected = []; for (const value of [{ ...input, path: '../outside' }, { ...input, taskId: '00000000-0000-0000-0000-000000000000' }, { ...input, sha256: '0'.repeat(64) }, { ...input, command: 'foreign' }]) { try { await window.desktopWorkbench.revealFile(value); rejected.push(false); } catch { rejected.push(true); } } return rejected; }, { ...scope, path: file.path, sha256: file.sha256 }); + assert.deepEqual(invalid, [true, true, true, true]); + await page.getByRole('button', { name: '桌面宿主', exact: true }).click(); await page.getByRole('button', { name: '打开项目目录', exact: true }).click(); await page.getByRole('button', { name: '定位当前文件', exact: true }).click(); + await until(() => application.evaluate(() => globalThis.desktopFixtureCalls.length === 2)); + const fixtureCalls = await application.evaluate(() => globalThis.desktopFixtureCalls); assert.deepEqual(fixtureCalls, [{ folder: projectRoot }, { reveal: path.join(projectRoot, 'README.md') }]); + const screenshots = [await snapshot('desktop-host-1440', 1440), await snapshot('desktop-host-390', 390)]; + await page.getByRole('button', { name: '审查当前任务', exact: true }).click(); await page.getByLabel('任务记录', { exact: true }).waitFor(); + record(stage, { invalidRejected: invalid.length, fixtureCalls, screenshots, nativeOperations: 'Dialog/shell adapters are declared fixtures in this automated run; actual Windows picker separately verified.' }); + stage = 'native stop cancelled, then original host explicitly stopped'; + await page.getByRole('button', { name: '关闭检视区', exact: true }).click(); + await page.getByRole('button', { name: '桌面宿主', exact: true }).click(); await page.getByRole('button', { name: '停止并退出', exact: true }).click(); + await until(() => page.getByRole('button', { name: '停止并退出', exact: true }).isEnabled()); + assert.equal((await controller.connect()).identity.instanceId, original.instanceId); + await application.evaluate(({ dialog }) => { dialog.showMessageBox = async () => ({ response: 1 }); }); + const exited = application.waitForEvent('close'); expectedNavigation = true; await page.getByRole('button', { name: '停止并退出', exact: true }).click(); await exited; application = null; + assert.equal(observeWindowsProcess(original.pid), null); assert.equal(await controller.health(), null); expectedNavigation = false; record(stage, { hostPid: original.pid, exited: true, confirmation: 'Declared native confirmation fixtures: cancelled first, confirmed second.' }); + } + assert.deepEqual(errors, []); assert.deepEqual(requests, []); + save({ success: true, root, appRoot, dataRoot, port, results, errors, requests, native, inference: 'Offline demo/local engineering checks only; no configured model or existing credentials.' }); +} catch (error) { + if (page && !page.isClosed()) { try { fs.writeFileSync(path.join(root, 'failure.html'), await page.content()); await page.screenshot({ path: path.join(root, 'failure.png') }); } catch {} } + save({ success: false, root, appRoot, dataRoot, stage, results, errors, requests, message: error.message, stack: error.stack, native }); throw error; +} finally { + if (application) await application.close(); + if (await controller.health()) await controller.stop(); + if (externalServer) { externalServer.closeAllConnections(); await new Promise(resolve => externalServer.close(resolve)); } +} diff --git a/src/client/App.tsx b/src/client/App.tsx index 520bea79..dea48a11 100644 --- a/src/client/App.tsx +++ b/src/client/App.tsx @@ -14,6 +14,8 @@ import { ProjectMemoryPanel } from './ProjectMemoryPanel'; import { SkillCenter } from './SkillCenter'; import { McpPanel } from './McpPanel'; import { WorkerPanel } from './WorkerPanel'; +import { DesktopPanel } from './DesktopPanel'; +import { desktop } from './desktop'; const activeStates = ['running', 'awaiting_approval', 'stopping']; const activeMcpStates = ['queued', 'connecting', 'discovering', 'calling', 'closing', 'stopping']; @@ -75,6 +77,8 @@ export default function App() { const [skillsOpen, setSkillsOpen] = useState(false); const [mcpOpen, setMcpOpen] = useState(false); const [workersOpen, setWorkersOpen] = useState(false); + const [desktopOpen, setDesktopOpen] = useState(false); + const [pickingProject, setPickingProject] = useState(false); const [researchDocs, setResearchDocs] = useState([]); const [report, setReport] = useState<{ title: string; content: string } | null>(null); const chatEnd = useRef(null); @@ -258,6 +262,16 @@ export default function App() { notify('已打开项目 ' + project.name); } catch (error) { failure(error); } } + async function acceptDesktopProject(project: Project) { + setProjects(previous => [project, ...previous.filter(item => item.id !== project.id)]); + await chooseProject(project.id); setProjectOpen(false); setDesktopOpen(false); notify('已打开项目 ' + project.name); + } + async function pickDesktopProject() { + if (!desktop || pickingProject) return; + setPickingProject(true); + try { const project = await desktop.pickProject(); if (project) await acceptDesktopProject(project); } catch (error) { failure(error); } + finally { setPickingProject(false); } + } async function loadFile(relative: string, location?: { line: number; expectedSha256: string }) { if (!projectId) return; const targetProject = projectId, request = ++fileRequest.current; @@ -520,7 +534,7 @@ export default function App() {
{(!sidebarOpen || mobile) && setSidebarOpen(true)}>}
{selectedProject?.name || '工作空间'} 任务

{session?.title || '让任务走到完成'}

-
+
{desktop && }
本地项目{session ? : 等待新任务}
openDiagnostics()}> @@ -562,7 +576,8 @@ export default function App() { {selectedProject && void loadFile(path, { line, expectedSha256 })} />}
{tab === 'changes' ? '应用前会核对文件基线' : tab === 'trace' ? '中断调用保留待核实状态' : tab === 'task' ? '任务目标、检查与结果持久保存' : tab === 'index' ? '结果绑定当前项目及文件 SHA256' : '读取范围限定在当前项目'}
- {projectOpen && setProjectOpen(false)}>
{ event.preventDefault(); openProject(); }}>
{exampleId && }
} + {projectOpen && setProjectOpen(false)}>
{ event.preventDefault(); openProject(); }}>
{desktop && }{exampleId && }
} + {desktopOpen && desktop && setDesktopOpen(false)}> { if (selectedProjectRef.current === scope.projectId && selectedSessionRef.current === scope.sessionId && selectedTaskRef.current === scope.taskId) { setDesktopOpen(false); showInspector('task'); } }} />} {settingsOpen && setSettingsOpen(false)}>
{ event.preventDefault(); saveSettings(); }}>
{settings.mode === 'compatible' && <>
Chat Completions 兼容接口
只在本次服务内存中使用,不写入会话与配置。{config.hasKey && }
填写服务提供的接口根地址。
{modelCheck &&
{modelCheck.message}
}}
上下文与任务预算

上下文使用本地估算;实际用量与未知用量分开保存。达到预算会暂停,已完成的工具结果保留。

{anyRunning &&

有任务在执行,请先停止任务再改变连接。

}
} diff --git a/src/client/DesktopPanel.tsx b/src/client/DesktopPanel.tsx new file mode 100644 index 00000000..f2e5d010 --- /dev/null +++ b/src/client/DesktopPanel.tsx @@ -0,0 +1,28 @@ +import { useEffect, useRef, useState } from 'react'; +import { ClipboardCheck, FolderOpen, Monitor, RotateCw, Square } from 'lucide-react'; +import type { OpenFile, Project, Session } from './types'; +import { desktop, type DesktopHostStatus, type DesktopTaskScope } from './desktop'; + +export function DesktopPanel({ project, session, file, onProject, onReview }: { + project?: Project; session: Session | null; file: OpenFile | null; onProject(project: Project): Promise; onReview(scope: DesktopTaskScope): void; +}) { + const [status, setStatus] = useState(null), [busy, setBusy] = useState(''), [error, setError] = useState(''); + const alive = useRef(true); + useEffect(() => { alive.current = true; void refresh(); return () => { alive.current = false; }; }, []); + async function act(name: string, action: () => Promise) { + if (busy || !desktop) return; + setBusy(name); setError(''); + try { await action(); } catch (value) { if (alive.current) setError(value instanceof Error ? value.message : '本机操作失败,请核对当前宿主。'); } + finally { if (alive.current) setBusy(''); } + } + async function refresh() { await act('refresh', async () => { const value = await desktop!.status(); if (alive.current) setStatus(value); }); } + const task = session?.execution?.task, scope = project && session && task ? { projectId: project.id, sessionId: session.id, taskId: task.id } : null; + return
+
{status?.state === 'ready' ? '执行宿主正在运行' : status?.state === 'stopping' ? '所属任务正在停止' : '正在核对执行宿主'}

关闭窗口后,后台任务继续。重新打开可查看原任务进度。

+ {status?.identity &&
当前程序
v{status.identity.version} · PID {status.identity.pid}
后台任务
{status.activity?.active ? '有所属操作正在执行' : '当前没有活动操作'} · {status.activity?.unresolvedTools || 0} 项结果待核对
桌面窗口
{status.desktopWindows?.count || 0} 个已登记窗口
会话与连接
{status.identity.dataRoot}
运行目录
{status.identity.runtimeRoot}
} +
+ {!scope &&

选择已有任务后,可核对任务归属并审查成果。读取文件后可在文件管理器中定位。

} + {error &&

{error}

} +
退出执行宿主

停止所属任务、模型请求和工具进程,再退出桌面。系统会要求确认。

+
; +} diff --git a/src/client/desktop.ts b/src/client/desktop.ts new file mode 100644 index 00000000..161fbd95 --- /dev/null +++ b/src/client/desktop.ts @@ -0,0 +1,20 @@ +import type { Project } from './types'; + +export type DesktopTaskScope = { projectId: string; sessionId: string; taskId: string }; +export type DesktopHostStatus = { + state: 'ready' | 'stopping' | 'not-running'; + identity?: { pid: number; createdAt: string; instanceId: string; runtimeIdentity: string; version: string; dataRoot: string; runtimeRoot: string }; + activity?: { active: boolean; counts: Record; unresolvedTools: number }; + desktopWindows?: { count: number }; +}; +type DesktopWorkbench = { + protocol: 'agent-workbench-desktop-v1'; + status(): Promise; + pickProject(): Promise; + projectFolder(projectId: string): Promise<{ opened: boolean }>; + reviewTask(input: DesktopTaskScope): Promise; + revealFile(input: DesktopTaskScope & { path: string; sha256: string }): Promise<{ revealed: boolean }>; + stopHost(): Promise<{ cancelled?: boolean; state?: string; processExited?: boolean }>; +}; +declare global { interface Window { desktopWorkbench?: DesktopWorkbench } } +export const desktop = window.desktopWorkbench?.protocol === 'agent-workbench-desktop-v1' ? window.desktopWorkbench : undefined; diff --git a/src/client/styles.css b/src/client/styles.css index db6f47a1..f4aa2005 100644 --- a/src/client/styles.css +++ b/src/client/styles.css @@ -20,3 +20,10 @@ html,body,#root{width:100%;height:100%;overflow:hidden}.workbench{grid-template- .example-tag{display:block;margin-top:8px;font-size:10px;line-height:1.6;color:#65766a}.review-toolbar{color:#426f53!important;background:#edf5ed;border-radius:5px}.approval-shell{font-size:11px;color:#5b7161;margin:8px 0}.message-text .research-content{white-space:normal;font-size:14px;line-height:1.85;color:inherit}.message-text .research-content p{margin-bottom:14px}.message-text .research-content h2,.message-text .research-content h3{font-size:16px}.message-text .research-content code{font-size:12px}.failure-card{white-space:normal;border:1px solid #e7c6a0;background:#fffaf2;border-radius:9px;padding:16px;line-height:1.75;color:#685039}.failure-heading{display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin-bottom:9px}.failure-heading>span{font-size:11px;padding:2px 6px;background:#f6e6d1;border-radius:4px}.failure-heading>strong{font-size:14px}.failure-card p{font-size:12px;margin:7px 0;overflow-wrap:anywhere}.failure-suggestion{color:#695d4b}.failure-meta{display:flex;gap:12px;flex-wrap:wrap;color:#82725e;font-size:10px;margin-top:12px}.failure-meta code{font-size:10px}.failure-card details{margin-top:10px;font-size:11px}.failure-card summary{cursor:pointer}.failure-actions{display:flex;gap:8px;flex-wrap:wrap;margin-top:15px}.failure-actions .button{font-size:11px;min-height:34px}.tool-retrying{border-color:#dfcc9f;background:#fffaf0}.tool-retrying .tool-symbol{background:#f7ecd3;color:#98722e}.status-retrying{background:#fff1d7;color:#82601f}.diagnostic-loading{display:flex;align-items:center;gap:12px;padding:24px;font-size:13px;color:#496656}.diagnostic-panel{overflow:auto;min-height:0;font-size:12px;line-height:1.8;padding-right:4px;color:#405b4e}.diagnostic-intro{display:flex;align-items:center;gap:12px;padding:6px 0 18px}.diagnostic-intro>div{flex:1;min-width:0}.diagnostic-intro strong{font-size:15px;color:#244c3d}.diagnostic-intro p{font-size:12px;color:#617566;margin:2px 0}.diagnostic-grid{display:grid;grid-template-columns:1fr 1fr;gap:14px}.diagnostic-panel section{border:1px solid #dce7df;border-radius:8px;padding:16px;margin-bottom:14px;background:#f8fbf8;min-width:0}.diagnostic-panel h3{font-size:13px;color:#315743;margin:0 0 12px;font-weight:600}.diagnostic-panel dl{display:grid;grid-template-columns:84px minmax(0,1fr);gap:8px;margin:0}.diagnostic-panel dt{color:#758378}.diagnostic-panel dd{margin:0;overflow-wrap:anywhere}.diagnostic-note{font-size:11px;color:#607566;margin-top:12px;line-height:1.8}.diagnostic-path{font-family:Consolas,monospace;font-size:11px;overflow-wrap:anywhere;margin-top:6px}.diagnostic-section-heading{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:10px}.diagnostic-section-heading h3{margin:0}.diagnostic-section-heading>span{font-size:11px;color:#82674a}.diagnostic-failure{border-color:#e7c6a0!important;background:#fffaf2!important}.diagnostic-failure p{margin:8px 0;overflow-wrap:anywhere}.diagnostic-failure small{font-size:10px;color:#87735c}.diagnostic-changes>div{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:9px 0;border-bottom:1px solid #e3ebe5}.diagnostic-changes>div:last-child{border-bottom:0}.diagnostic-changes code{font-size:11px;overflow-wrap:anywhere}.diagnostic-tools details{border-bottom:1px solid #e3ebe5;padding:10px 0}.diagnostic-tools details:last-child{border-bottom:0}.diagnostic-tools summary{cursor:pointer;display:flex;align-items:center;gap:12px;flex-wrap:wrap}.diagnostic-tools summary>code{margin-right:auto;font-size:11px}.diagnostic-tools summary>span:last-child{font-size:10px}.diagnostic-tools pre{white-space:pre-wrap;overflow-wrap:anywhere;font-size:11px;padding:12px;background:#edf3ee;border-radius:5px;margin-top:10px;max-height:220px;overflow:auto}.model-test-row{display:flex;align-items:center;gap:10px;justify-content:space-between;margin-top:13px}.model-test-row>span{font-size:11px;color:#67796a}.model-test-row>.button{font-size:11px}.model-check{font-size:12px;line-height:1.8;padding:10px 12px;border-radius:6px;margin-top:12px;overflow-wrap:anywhere}.model-check-success{background:#edf6ef;border:1px solid #c7dfce;color:#3e704c}.model-check-error{background:#fff5ec;border:1px solid #e8cdb0;color:#815e3d} @media(max-width:620px){.diagnostic-grid{grid-template-columns:1fr}.diagnostic-panel section{padding:13px}.diagnostic-intro strong{font-size:13px}.diagnostic-intro .button{padding:6px 8px;font-size:11px}.failure-card{padding:13px}.failure-heading>strong{font-size:13px}.example-tag{font-size:10px}.model-test-row{align-items:flex-start;flex-direction:column}.toolbar-actions .review-toolbar{font-size:10px}.message-text .research-content{font-size:13px}.diagnostic-panel dl{grid-template-columns:75px minmax(0,1fr)}} +.desktop-panel{font-size:12px;line-height:1.8;color:var(--muted)} +.desktop-host-heading{display:flex;align-items:flex-start;gap:12px;margin-bottom:22px;color:var(--ink)} +.desktop-host-heading>div{flex:1;min-width:0}.desktop-host-heading strong{font-size:16px}.desktop-host-heading p{margin:4px 0 0;color:var(--muted)} +.desktop-host-facts{display:grid;grid-template-columns:90px minmax(0,1fr);gap:12px;margin:0 0 24px;padding:18px;border:1px solid var(--line);background:var(--paper);border-radius:8px}.desktop-host-facts dt{color:var(--muted)}.desktop-host-facts dd{margin:0;color:var(--ink);overflow-wrap:anywhere} +.desktop-project-actions{display:flex;gap:10px;flex-wrap:wrap}.desktop-scope-note{margin:14px 0;color:var(--muted)} +.desktop-stop-row{display:flex;gap:18px;align-items:center;margin-top:26px;padding-top:20px;border-top:1px solid var(--line)}.desktop-stop-row>div{flex:1;min-width:0}.desktop-stop-row strong{color:var(--ink)}.desktop-stop-row p{margin:4px 0 0}.desktop-stop-row>.button{color:#a14236;border-color:#d5b1ab;flex-shrink:0}.desktop-error{color:#a14236;padding:12px;background:#fff6f2;overflow-wrap:anywhere} +@media(max-width:620px){.desktop-launch span{display:none}.desktop-host-facts{grid-template-columns:72px minmax(0,1fr);padding:13px;font-size:11px}.desktop-stop-row{align-items:flex-start;flex-direction:column}.desktop-project-actions>.button{flex-grow:1}.desktop-host-heading .button{min-height:34px;padding:5px 9px}} diff --git a/src/core/desktop/app-installation.mjs b/src/core/desktop/app-installation.mjs index da1a8619..9f139f46 100644 --- a/src/core/desktop/app-installation.mjs +++ b/src/core/desktop/app-installation.mjs @@ -16,12 +16,13 @@ export function inspectHostInstallation(directory, { full = false } = {}) { if (typeof version !== 'string' || !/^\d+\.\d+\.\d+$/.test(version)) throw hostError('宿主安装版本无效。'); const files = new Set(['dist-server/server.mjs', 'dist-server/hot-upgrade.mjs', 'dist-client/index.html']); if (!manifest || fs.existsSync(path.join(root, 'dist-server/host-launcher.mjs'))) files.add('dist-server/host-launcher.mjs'); + for (const relative of ['dist-desktop/main.cjs', 'dist-desktop/preload.cjs']) if (fs.existsSync(path.join(root, relative))) files.add(relative); const names = new Map(); for (const row of manifest?.files ?? []) { if (!row || typeof row.path !== 'string' || row.path.includes('\\') || row.path.split('/').includes('..') || names.has(row.path) || !/^[a-f0-9]{64}$/.test(row.sha256 ?? '') || !Number.isSafeInteger(row.bytes) || row.bytes < 0) throw hostError('宿主清单包含重复或越界输入。'); names.set(row.path, row); - if (full || row.path.startsWith('dist-client/') || row.path.startsWith('dist-server/')) files.add(row.path); + if (full || /^(dist-client|dist-server|dist-desktop)\//.test(row.path)) files.add(row.path); } if (!manifest) for (const entry of fs.readdirSync(path.join(root, 'dist-client/assets'))) files.add('dist-client/assets/' + entry); const inputs = [...files].sort().map(relative => { @@ -34,3 +35,15 @@ export function inspectHostInstallation(directory, { full = false } = {}) { inputs, verification: full ? 'full-manifest' : 'loaded-host-and-client-inputs' }; return { ...result, identitySha256: digest(JSON.stringify(canonicalHost(result))) }; } + +export function desktopExecutableIdentity(directory) { + const root = fs.realpathSync.native(directory), packaged = path.join(root, 'desktop/AgentWorkbench.exe'); + const relative = fs.existsSync(packaged) ? 'desktop/AgentWorkbench.exe' : 'node_modules/electron/dist/electron.exe'; + const executable = binaryIdentity(ownedChild(root, relative)); + const manifestFile = path.join(root, 'MANIFEST.json'); + if (fs.existsSync(manifestFile)) { + const declared = readState(manifestFile, 16 * 1024 * 1024).files?.find(row => row.path === relative); + if (!declared || declared.bytes !== executable.bytes || declared.sha256 !== executable.sha256) throw hostError('桌面程序与原发行清单不一致。'); + } + return executable; +} diff --git a/src/core/desktop/desktop-bridge.mjs b/src/core/desktop/desktop-bridge.mjs new file mode 100644 index 00000000..ce615c93 --- /dev/null +++ b/src/core/desktop/desktop-bridge.mjs @@ -0,0 +1,71 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { createHash } from 'node:crypto'; +import { safePath } from '../../server/files.mjs'; +import { assertLocalTree, samePath } from './file-state.mjs'; +import { desktopInput, assertDesktopFrame, desktopError } from '../../shared/contracts/desktop-bridge.mjs'; + +export class DesktopBridge { + constructor(controller, { dialog, shell, getWindow, onStopped = () => {} }) { Object.assign(this, { controller, dialog, shell, getWindow, onStopped }); this.pending = new Set(); } + async project(id) { + const project = (await this.controller.api('/bootstrap')).projects.find(value => value.id === id); + if (!project) throw desktopError('项目未在当前宿主登记。'); + assertLocalTree(project.root); + if (!samePath(project.root, fs.realpathSync.native(project.root))) throw desktopError('原项目目录已变化。'); + return project; + } + async task(input) { + const session = await this.controller.api('/sessions/' + input.sessionId); + if (session.projectId !== input.projectId || session.execution?.task?.id !== input.taskId) throw desktopError('该入口不属于当前项目与Task,请刷新后核对。'); + return session; + } + async execute(event, action, input) { + const window = this.getWindow(); assertDesktopFrame(event, window, this.controller.url); const value = desktopInput(action, input); + if (this.pending.has(action)) throw desktopError('同一项本机操作正在处理,请等待原操作。'); + this.pending.add(action); + try { + if (!await this.controller.connect()) throw desktopError('原执行宿主已结束,请重新打开工作台。'); + assertDesktopFrame(event, this.getWindow(), this.controller.url); + if (action === 'status') return this.controller.api('/host/status'); + if (action === 'pickProject') { + const selected = await this.dialog.showOpenDialog(window, { title: '选择工作台项目', properties: ['openDirectory'], buttonLabel: '打开项目' }); + assertDesktopFrame(event, this.getWindow(), this.controller.url); + if (selected.canceled) return null; + if (selected.filePaths.length !== 1 || !path.isAbsolute(selected.filePaths[0])) throw desktopError('请选择一个实际项目文件夹。'); + assertLocalTree(selected.filePaths[0]); + return this.controller.api('/projects', { method: 'POST', input: { root: selected.filePaths[0] } }); + } + if (action === 'projectFolder') { + const project = await this.project(value.projectId); + const error = await this.shell.openPath(project.root); if (error) throw desktopError('系统无法打开所属项目目录。'); + return { opened: true, projectId: project.id, root: project.root }; + } + if (action === 'reviewTask') { + const session = await this.task(value); await this.project(value.projectId); + return { projectId: session.projectId, sessionId: session.id, taskId: value.taskId, eventSeq: session.eventSeq }; + } + if (action === 'revealFile') { + await this.task(value); const project = await this.project(value.projectId), target = safePath(project, value.path); + assertLocalTree(target); const stat = fs.lstatSync(target); + if (!stat.isFile() || stat.nlink !== 1 || stat.size > 1024 * 1024) throw desktopError('原文件入口只接受当前工程的普通文本文件。'); + const bytes = fs.readFileSync(target); + if (bytes.includes(0) || createHash('sha256').update(bytes).digest('hex') !== value.sha256) throw desktopError('文件内容已变化或不是文本,请重新读取后定位。'); + try { new TextDecoder('utf8', { fatal: true }).decode(bytes); } catch { throw desktopError('当前文件不是UTF-8文本,请先核对编码。'); } + await this.task(value); assertLocalTree(target); + if (createHash('sha256').update(fs.readFileSync(target)).digest('hex') !== value.sha256) throw desktopError('核对期间原文件已变化,请重新读取后定位。'); + this.shell.showItemInFolder(target); + return { revealed: true, projectId: project.id, sessionId: value.sessionId, taskId: value.taskId, path: value.path, sha256: value.sha256 }; + } + if (action === 'stopHost') { + const status = await this.controller.status(); + const choice = await this.dialog.showMessageBox(window, { type: 'warning', title: '退出执行宿主', message: '停止当前执行宿主?', + detail: '所属任务、模型请求和工具进程会先结束。关闭普通窗口会保留后台任务。', buttons: ['保留后台任务', '停止并退出'], defaultId: 0, cancelId: 0, noLink: true }); + assertDesktopFrame(event, this.getWindow(), this.controller.url); + if (choice.response !== 1) return { cancelled: true }; + const current = await this.controller.connect(); + if (!current || current.identity.instanceId !== status.identity.instanceId || current.identity.runtimeIdentity !== status.identity.runtimeIdentity) throw desktopError('停止确认期间原宿主已变化,请重新核对。'); + const result = await this.controller.stop(); this.onStopped(); return result; + } + } finally { this.pending.delete(action); } + } +} diff --git a/src/core/desktop/host-authority.mjs b/src/core/desktop/host-authority.mjs index baef8e82..454d3ed1 100644 --- a/src/core/desktop/host-authority.mjs +++ b/src/core/desktop/host-authority.mjs @@ -5,10 +5,10 @@ import { APP_VERSION } from '../../server/diagnostics.mjs'; import { HOST_PROTOCOL, HOST_REGISTRATION_FILE, hostError, hostProof, assertHostStop } from '../../shared/contracts/desktop-host.mjs'; import { observeWindowsProcess, binaryIdentity, protectUserDirectory } from './process-identity.mjs'; import { ownedChild, readState, writeState, samePath } from './file-state.mjs'; -import { inspectHostInstallation } from './app-installation.mjs'; +import { inspectHostInstallation, desktopExecutableIdentity } from './app-installation.mjs'; export class HostAuthority { - constructor(context) { this.context = context; this.stopping = false; } + constructor(context) { this.context = context; this.stopping = false; this.windows = new Map(); } initialize() { if (this.registration) return; const { store, server, appDirectory } = this.context, observed = observeWindowsProcess(process.pid); @@ -81,7 +81,40 @@ export class HostAuthority { return { counts, active: Object.values(counts).some(value => value > 0), unresolvedTools: unresolved.length, unknownResults: unresolved.slice(0, 50), scope: 'Current host-owned active managers and saved tool verification flags; no tool/model/repair is executed.' }; } - status() { return { identity: this.identity(), state: this.stopping ? 'stopping' : 'ready', activity: this.activity(), windowClose: 'keep-host-running' }; } + desktopWindows() { + this.windows ??= new Map(); + for (const [id, registered] of this.windows) { + const actual = observeWindowsProcess(registered.pid); + if (!actual || actual.createdAt !== registered.createdAt || actual.userSid !== registered.userSid || !samePath(actual.executable, registered.executable.path)) this.windows.delete(id); + } + return { count: this.windows.size, entries: [...this.windows.values()].map(({ executable, userSid, ...value }) => value), scope: 'Attested Electron main processes; stale or reused PIDs are removed without sending a signal.' }; + } + assertWindowInput(input) { + const identity = this.identity(), fields = ['windowId', 'pid', 'createdAt', 'instanceId', 'runtimeIdentity']; + if (!input || typeof input !== 'object' || Array.isArray(input) || Object.keys(input).length !== fields.length || Object.keys(input).some(key => !fields.includes(key)) + || !/^[a-f0-9-]{36}$/i.test(input.windowId ?? '') || !Number.isInteger(input.pid) || input.pid < 1 || input.pid === identity.pid + || typeof input.createdAt !== 'string' || !Number.isFinite(Date.parse(input.createdAt)) || input.instanceId !== identity.instanceId + || input.runtimeIdentity !== identity.runtimeIdentity) throw hostError('桌面窗口登记不属于原执行宿主。', 'HOST_WINDOW_REJECTED', 403); + return identity; + } + registerWindow(input) { + const identity = this.assertWindowInput(input); + if (this.stopping) throw hostError('原宿主正在停止,不能登记新窗口。', 'HOST_STOP_PENDING', 409); + const actual = observeWindowsProcess(input.pid), executable = desktopExecutableIdentity(identity.runtimeRoot); + if (!actual || actual.createdAt !== input.createdAt || actual.userSid !== identity.userSid || !samePath(actual.executable, executable.path)) throw hostError('实际桌面PID创建、用户或程序无法核对。', 'HOST_WINDOW_REJECTED', 403); + this.desktopWindows(); + const previous = this.windows.get(input.windowId); + if (previous && (previous.pid !== input.pid || previous.createdAt !== input.createdAt) || [...this.windows.values()].some(value => value.pid === input.pid && value.windowId !== input.windowId) + || !previous && this.windows.size >= 8) throw hostError('桌面窗口已有原登记或达到当前上限。', 'HOST_WINDOW_REJECTED', 409); + this.windows.set(input.windowId, { ...input, userSid: actual.userSid, executable }); + return { registered: true, windowId: input.windowId, instanceId: identity.instanceId }; + } + unregisterWindow(input) { + this.assertWindowInput(input); this.windows ??= new Map(); const previous = this.windows.get(input.windowId); + if (previous && (previous.pid !== input.pid || previous.createdAt !== input.createdAt)) throw hostError('原窗口登记已变化。', 'HOST_WINDOW_REJECTED', 403); + this.windows.delete(input.windowId); return { unregistered: true, windowId: input.windowId }; + } + status() { return { identity: this.identity(), state: this.stopping ? 'stopping' : 'ready', activity: this.activity(), desktopWindows: this.desktopWindows(), windowClose: 'keep-host-running' }; } async stop(input) { assertHostStop(input, this.identity()); if (this.stopping) throw hostError('宿主已经在停止,请等待原操作。', 'HOST_STOP_PENDING'); diff --git a/src/core/desktop/host-controller.mjs b/src/core/desktop/host-controller.mjs index 8ada68aa..aeb70fa7 100644 --- a/src/core/desktop/host-controller.mjs +++ b/src/core/desktop/host-controller.mjs @@ -9,6 +9,8 @@ import { observeWindowsProcess, binaryIdentity } from './process-identity.mjs'; import { inspectHostInstallation } from './app-installation.mjs'; import { ownedChild, readState, writeState, samePath, assertLocalTree } from './file-state.mjs'; +export const HOST_ENVIRONMENT = Object.freeze(['AGENT_WORKBENCH_DEEPSEEK_ROOT', 'AGENT_WORKBENCH_PURGE_ROOT', 'AGENT_WORKBENCH_PYTHON_PATH', 'AGENT_WORKBENCH_TEST_PYTHON']); + async function jsonResponse(response) { if (!response.ok) throw hostError('本机宿主接口拒绝操作(HTTP ' + response.status + ')。', 'HOST_API_REJECTED', response.status); const chunks = []; let length = 0; @@ -28,8 +30,8 @@ export class HostController { const version = execFileSync(this.node.path, ['--version'], { encoding: 'utf8', windowsHide: true, timeout: 10000, env: projectEnvironment() }).trim(); if (!/^v24\./.test(version)) throw hostError('桌面宿主需要已经核验的Node24运行器。'); this.node.version = version; this.port = port; this.url = 'http://127.0.0.1:' + port; this.timeoutMs = Math.min(60000, Math.max(1000, timeoutMs)); - const allowed = new Set(['AGENT_WORKBENCH_ENGINE_ROOT', 'AGENT_WORKBENCH_PURGE_ROOT', 'AWB_QA_PYTHON']); - if (Object.keys(environment).some(key => !allowed.has(key) || typeof environment[key] !== 'string')) throw hostError('宿主启动不接受任意环境或模型凭据。'); + const allowed = new Set(HOST_ENVIRONMENT); + if (Object.keys(environment).some(key => !allowed.has(key) || typeof environment[key] !== 'string' || !path.isAbsolute(environment[key]))) throw hostError('宿主启动只接受已声明的本机运行器路径。'); this.environment = environment; } async api(route, { method = 'GET', input = null, timeoutMs = 15000 } = {}) { diff --git a/src/core/desktop/launch-options.mjs b/src/core/desktop/launch-options.mjs new file mode 100644 index 00000000..a4cb3ba4 --- /dev/null +++ b/src/core/desktop/launch-options.mjs @@ -0,0 +1,15 @@ +import path from 'node:path'; +import { samePath } from './file-state.mjs'; + +export function desktopLaunchOptions(argv, { defaultApp = false, mainFile } = {}) { + const args = argv.slice(1), options = {}; + while (/^--(?:inspect|remote-debugging-port)=\d+$/.test(args[0] ?? '')) args.shift(); + if (defaultApp && (!args.length || !mainFile || !samePath(path.resolve(args.shift()), mainFile))) throw new Error('Desktop entry does not match the compiled main program.'); + while (args.length) { + const flag = args.shift(); + if (flag === '--hidden-window' && !options.hidden) { options.hidden = true; continue; } + if (!['--app-root', '--data-root', '--node', '--port'].includes(flag) || !args.length || options[flag] !== undefined) throw new Error('Unsupported desktop option.'); + options[flag] = args.shift(); + } + return options; +} diff --git a/src/desktop/host-cli.mjs b/src/desktop/host-cli.mjs index c410930b..b272c77b 100644 --- a/src/desktop/host-cli.mjs +++ b/src/desktop/host-cli.mjs @@ -2,7 +2,7 @@ import fs from 'node:fs'; import path from 'node:path'; import os from 'node:os'; import { fileURLToPath } from 'node:url'; -import { HostController } from '../core/desktop/host-controller.mjs'; +import { HostController, HOST_ENVIRONMENT } from '../core/desktop/host-controller.mjs'; const args = process.argv.slice(2); if (args.includes('--help')) { console.log('node host-launcher.mjs [--app-root ] [--data-root ] [--node ] [--port <1..65535>]'); process.exit(0); } @@ -19,6 +19,6 @@ const dataRoot = options['--data-root'] || process.env.AGENT_WORKBENCH_DATA_DIR const nodePath = options['--node'] || (fs.existsSync(path.join(appRoot, 'runtime/node.exe')) ? path.join(appRoot, 'runtime/node.exe') : process.execPath); try { const controller = new HostController({ appRoot, dataRoot, nodePath, port: Number(options['--port'] || process.env.AGENT_WORKBENCH_PORT || 4318), - environment: Object.fromEntries(['AGENT_WORKBENCH_ENGINE_ROOT', 'AGENT_WORKBENCH_PURGE_ROOT', 'AWB_QA_PYTHON'].filter(key => process.env[key]).map(key => [key, process.env[key]])) }); + environment: Object.fromEntries(HOST_ENVIRONMENT.filter(key => process.env[key]).map(key => [key, process.env[key]])) }); console.log(JSON.stringify(await controller[command]())); } catch (cause) { console.error(JSON.stringify({ success: false, code: cause.code || 'HOST_FAILED', message: cause.message })); process.exitCode = 1; } diff --git a/src/desktop/main.mjs b/src/desktop/main.mjs new file mode 100644 index 00000000..91613a5e --- /dev/null +++ b/src/desktop/main.mjs @@ -0,0 +1,67 @@ +import { app, BrowserWindow, ipcMain, dialog, shell, Menu } from 'electron'; +import fs from 'node:fs'; +import path from 'node:path'; +import os from 'node:os'; +import { randomUUID } from 'node:crypto'; +import { HostController, HOST_ENVIRONMENT } from '../core/desktop/host-controller.mjs'; +import { DesktopBridge } from '../core/desktop/desktop-bridge.mjs'; +import { ownedChild, assertLocalTree, samePath } from '../core/desktop/file-state.mjs'; +import { observeWindowsProcess, protectUserDirectory } from '../core/desktop/process-identity.mjs'; +import { DESKTOP_CHANNELS, desktopOrigin } from '../shared/contracts/desktop-bridge.mjs'; +import { desktopLaunchOptions } from '../core/desktop/launch-options.mjs'; + +const options = desktopLaunchOptions(process.argv, { defaultApp: process.defaultApp, mainFile: __filename }); +const appRoot = path.resolve(options['--app-root'] || (app.isPackaged ? path.resolve(path.dirname(process.execPath), '..') : path.resolve(__dirname, '..'))); +const dataRoot = path.resolve(options['--data-root'] || path.join(process.env.LOCALAPPDATA || os.homedir(), 'AgentWorkbench')); +const port = Number(options['--port'] || 4318); +assertLocalTree(dataRoot, { missing: true }); fs.mkdirSync(dataRoot, { recursive: true }); +const profile = ownedChild(dataRoot, '.desktop-profile', { missing: true }); fs.mkdirSync(profile, { recursive: true }); protectUserDirectory(profile); app.setPath('userData', profile); +app.setAppUserModelId('local.agent-workbench'); app.setName('Agent Workbench'); +let window, controller, bridge, windowId, windowOwner, quitting = false; +const retained = app.requestSingleInstanceLock({ appRoot, dataRoot, port }); +if (!retained) app.quit(); +else { + app.on('second-instance', (_event, _argv, _directory, incoming) => { + if (!samePath(incoming?.appRoot ?? '', appRoot) || !samePath(incoming?.dataRoot ?? '', dataRoot) || incoming?.port !== port) return; + if (window && !window.isDestroyed()) { if (window.isMinimized()) window.restore(); window.show(); window.focus(); } + }); + app.on('window-all-closed', () => app.quit()); // Node owns execution, independent of Electron. + app.on('before-quit', event => { + if (quitting || !controller || !windowOwner) return; + event.preventDefault(); quitting = true; + void controller.api('/host/windows/unregister', { method: 'POST', input: windowOwner, timeoutMs: 5000 }).catch(() => {}).finally(() => app.quit()); + }); + app.whenReady().then(async () => { + controller = new HostController({ appRoot, dataRoot, port, nodePath: options['--node'], + environment: Object.fromEntries(HOST_ENVIRONMENT.filter(key => process.env[key]).map(key => [key, process.env[key]])) }); + const host = await controller.start(), observed = observeWindowsProcess(process.pid); + windowId = randomUUID(); windowOwner = { windowId, pid: process.pid, createdAt: observed.createdAt, instanceId: host.identity.instanceId, runtimeIdentity: host.identity.runtimeIdentity }; + await controller.api('/host/windows/register', { method: 'POST', input: windowOwner }); + const preload = path.join(appRoot, 'dist-desktop/preload.cjs'); + window = new BrowserWindow({ title: 'Agent Workbench', width: 1440, height: 1000, minWidth: 390, minHeight: 600, + show: false, backgroundColor: '#edf2f7', icon: path.join(appRoot, 'public/workbench-icon.png'), + webPreferences: { preload, sandbox: true, contextIsolation: true, nodeIntegration: false, webSecurity: true, allowRunningInsecureContent: false } }); + window.webContents.setWindowOpenHandler(() => ({ action: 'deny' })); + window.webContents.on('will-navigate', details => { if (!desktopOrigin(details.url, controller.url)) details.preventDefault(); }); + window.webContents.on('will-frame-navigate', details => { if (!desktopOrigin(details.url, controller.url)) details.preventDefault(); }); + window.webContents.on('will-attach-webview', event => event.preventDefault()); + const session = window.webContents.session; + session.setPermissionRequestHandler((_contents, _permission, callback) => callback(false)); + session.setPermissionCheckHandler(() => false); + session.webRequest.onBeforeRequest((details, callback) => { + const permitted = desktopOrigin(details.url, controller.url) || details.url.startsWith('data:image/') || details.url.startsWith('blob:' + controller.url + '/'); + callback({ cancel: !permitted }); + }); + bridge = new DesktopBridge(controller, { dialog, shell, getWindow: () => window, onStopped: () => setTimeout(() => app.quit(), 150) }); + for (const [action, channel] of Object.entries(DESKTOP_CHANNELS)) ipcMain.handle(channel, (event, input) => bridge.execute(event, action, input)); + Menu.setApplicationMenu(Menu.buildFromTemplate([{ label: '工作台', submenu: [ + { label: '刷新窗口', role: 'reload' }, { label: '关闭窗口(后台任务继续)', accelerator: 'Alt+F4', click: () => window.close() }, + ] }, { label: '编辑', submenu: [{ role: 'undo' }, { role: 'redo' }, { type: 'separator' }, { role: 'cut' }, { role: 'copy' }, { role: 'paste' }, { role: 'selectAll' }] }])); + window.on('closed', () => { window = null; }); + await window.loadURL(host.url + '/?desktop=1&release=' + host.identity.version); + if (!options.hidden) window.show(); + console.log(JSON.stringify({ app: 'agent-workbench-desktop', ready: true, pid: process.pid, hostPid: host.identity.pid, + instanceId: host.identity.instanceId, appRoot, dataRoot, url: host.url })); + }).catch(error => { console.error(JSON.stringify({ app: 'agent-workbench-desktop', ready: false, message: error.message })); + if (!options.hidden) dialog.showErrorBox('Agent Workbench 无法打开', error.message); app.exit(1); }); +} diff --git a/src/desktop/preload.cjs b/src/desktop/preload.cjs new file mode 100644 index 00000000..ff01c4d2 --- /dev/null +++ b/src/desktop/preload.cjs @@ -0,0 +1,10 @@ +const { contextBridge, ipcRenderer } = require('electron'); +contextBridge.exposeInMainWorld('desktopWorkbench', Object.freeze({ + protocol: 'agent-workbench-desktop-v1', + status: () => ipcRenderer.invoke('awb:desktop-status'), + pickProject: () => ipcRenderer.invoke('awb:desktop-pick-project'), + projectFolder: projectId => ipcRenderer.invoke('awb:desktop-project-folder', { projectId }), + reviewTask: input => ipcRenderer.invoke('awb:desktop-review-task', input), + revealFile: input => ipcRenderer.invoke('awb:desktop-reveal-file', input), + stopHost: () => ipcRenderer.invoke('awb:desktop-stop-host'), +})); diff --git a/src/server/app.mjs b/src/server/app.mjs index 224d83b7..85fabeeb 100644 --- a/src/server/app.mjs +++ b/src/server/app.mjs @@ -86,6 +86,8 @@ return async (request, response) => { if (method === 'GET' && route === '/api/health') return json(response, { app: 'agent-workbench', version: APP_VERSION, pid: process.pid, ready: server?.workbenchReady !== false, uptimeMs: Date.now() - started }); if (method === 'GET' && route === '/api/host/identity') return json(response, host().attest(url.searchParams.get('challenge'))); if (method === 'GET' && route === '/api/host/status') return json(response, host().status()); + if (method === 'POST' && route === '/api/host/windows/register') return json(response, host().registerWindow(await body(request))); + if (method === 'POST' && route === '/api/host/windows/unregister') return json(response, host().unregisterWindow(await body(request))); if (method === 'POST' && route === '/api/host/stop') { const result = await host().stop(await body(request)); json(response, result); setTimeout(shutdown, 100); return; } diff --git a/src/server/files.mjs b/src/server/files.mjs index 95f77dd3..97f00dd0 100644 --- a/src/server/files.mjs +++ b/src/server/files.mjs @@ -10,7 +10,7 @@ import { assertWorkersResolved, assertWorkerWriteScope } from '../shared/contrac export const hash = bytes => createHash('sha256').update(bytes).digest('hex'); const ignored = new Set(['node_modules', '.git', '.next', '.data', 'bin', 'obj', 'dist', 'dist-client', 'dist-server', '__pycache__', '.venv', 'venv', '.tox', '.pytest_cache', '.mypy_cache', '.ruff_cache', 'htmlcov']); -const secretName = /(^|\/)(\.env($|[./])|id_rsa($|[./])|id_ed25519($|[./])|credentials($|[./])|\.ssh($|\/)|\.secrets($|\/))/i; +const secretName = /(^|\/)(\.env($|[./])|id_rsa($|[./])|id_ed25519($|[./])|credentials($|[./])|\.ssh($|\/)|\.secrets($|\/)|\.desktop-profile($|\/))/i; const normalize = value => process.platform === 'win32' ? value.toLowerCase() : value; const inside = (root, target) => normalize(target) === normalize(root) || normalize(target).startsWith(normalize(root + path.sep)); const restricted = relative => { diff --git a/src/server/hot-upgrade.mjs b/src/server/hot-upgrade.mjs index 91ea5e2f..9d0e77d9 100644 --- a/src/server/hot-upgrade.mjs +++ b/src/server/hot-upgrade.mjs @@ -17,6 +17,7 @@ export function installUpgrade(context, { appDirectory, updateServiceInfo = true const { server, store, provider, runtime, token, clients, started, exampleProject, shutdown } = context; if (!server?.listening || !store || !provider || !runtime || !clients || !token) throw new Error('The existing Workbench context is incomplete.'); if (server.workbenchHostAuthority?.stopping) throw new Error('Wait for the original host stop operation before upgrading.'); + if (server.workbenchHostAuthority?.desktopWindows?.().count) throw new Error('Close the registered desktop windows before upgrading; the execution host remains running.'); if (runtime.active.size || runtime.waiters.size || runtime.workers?.active.size || runtime.controlledEngines?.drivers.size || runtime.mcp?.active.size || runtime.checks?.active.size || runtime.deliveries?.active.size || runtime.changeSets?.projects.size || runtime.workspaces?.projects.size || runtime.workspaces?.pending.size || runtime.research?.active.size || runtime.engines?.active.size || runtime.browser?.active.size || runtime.taskPlans?.active.size) throw new Error('Wait for active tasks, workers, controlled engines, MCP operations, checks, Git deliveries, file batches, workspaces, research, engines, browsers, task plans and approvals to finish before upgrading.'); if (provider.activeRequests || provider.hub?.waiting || [...(provider.hub?.leases.values() ?? [])].some(count => count > 0)) throw new Error('Wait for active model requests and probes before upgrading.'); const root = fs.realpathSync.native(path.resolve(appDirectory)); diff --git a/src/shared/contracts/desktop-bridge.mjs b/src/shared/contracts/desktop-bridge.mjs new file mode 100644 index 00000000..82c95649 --- /dev/null +++ b/src/shared/contracts/desktop-bridge.mjs @@ -0,0 +1,24 @@ +export const DESKTOP_CHANNELS = Object.freeze({ status: 'awb:desktop-status', pickProject: 'awb:desktop-pick-project', + revealFile: 'awb:desktop-reveal-file', projectFolder: 'awb:desktop-project-folder', reviewTask: 'awb:desktop-review-task', stopHost: 'awb:desktop-stop-host' }); +export const desktopError = message => Object.assign(new Error(message), { code: 'DESKTOP_SCOPE_REJECTED', status: 403 }); +export function desktopOrigin(value, origin) { + try { const url = new URL(value); return url.origin === origin && url.protocol === 'http:' && !url.username && !url.password; } catch { return false; } +} +export function assertDesktopFrame(event, window, origin) { + if (!window || window.isDestroyed() || event.sender !== window.webContents || event.senderFrame !== window.webContents.mainFrame + || !desktopOrigin(event.senderFrame.url, origin)) throw desktopError('本机操作只能由当前工作台主窗口发起。'); +} +export function desktopInput(action, input) { + const fields = { status: [], pickProject: [], stopHost: [], projectFolder: ['projectId'], reviewTask: ['projectId', 'sessionId', 'taskId'], + revealFile: ['projectId', 'sessionId', 'taskId', 'path', 'sha256'] }[action]; + if (!fields) throw desktopError('本机操作不存在。'); + const value = input ?? {}; + if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).some(key => !fields.includes(key))) throw desktopError('本机操作字段无效。'); + for (const key of fields) { + if (typeof value[key] !== 'string') throw desktopError('本机操作缺少当前归属。'); + if (key.endsWith('Id') && !/^[a-f0-9-]{36}$/i.test(value[key])) throw desktopError('项目或任务身份无效。'); + } + if (action === 'revealFile' && (!/^[a-f0-9]{64}$/i.test(value.sha256) || value.path.length > 2000 || !value.path + || value.path.includes('\0') || value.path.includes(':') || /^[\/\\]/.test(value.path) || value.path.replaceAll('\\', '/').split('/').includes('..'))) throw desktopError('原文件入口需要所属相对路径及当前SHA256。'); + return value; +} diff --git a/task_plan.md b/task_plan.md index 57d4ac09..b90c2041 100644 --- a/task_plan.md +++ b/task_plan.md @@ -6,8 +6,8 @@ 1. [complete] A:Windows实际SID/创建/程序/安装/数据目录与签名挑战,注册/并发锁/启动意图;49/49相关专项和9组真实隔离主机通过。原中文ACL编码/重复权限失败及验收字段失败保留,修正后新证据独立保存。关闭真实窗口留待C/E,A不宣称桌面交付;正式PID23172/1.14保持。 2. [complete] B:CurrentUser DPAPI密文与registry同一SQLite事务,显式新填/确认导入、保存/关闭/删除/清除及失败回退;21/21专项兼容、7组实际浏览器/重启/HTTP/明文扫描通过。实际PID28724→49924、原配置/密文/6表原行保持,2条恢复Key实际3次夹具响应通过。不同Windows账号未实际切换,仅SID拒绝/错误entropy/损坏实际验证;原UI无标签/环境依赖失败及布局截图保留。 -3. [in_progress] C:Electron隔离窗口和窄范围preload、项目选择及原文件/任务审查入口;实际窗口/刷新/关闭重开、导航/IPC/越界拒绝与390px兼容。 -4. [pending] D:固定依赖/清单、Windows安装与独立新目录更新、活动阻挡和失败回退;实际安装/更新/卸载演练及持久数据核对。 +3. [complete] C:Electron45.2实际隔离窗口、6固定preload与所属本机入口;17相关专项、7组真实自动流程和独立原生Windows目录选择框通过。原Task/Run/审批/eventSeq/完成工具保持,1440/390视觉核对;所有参数/PID/导航/状态/动作等待和遮罩原失败保留。 +4. [in_progress] D:固定依赖/清单、Windows安装与独立新目录更新、活动阻挡和失败回退;实际安装/更新/卸载演练及持久数据核对。安装管理器草稿未构建/验收,不计通过。 5. [pending] E:实际桌面Node/React/Python工程、原失败修复/审批/父审查/检查/Git与窗口/宿主生命周期及unknown不重放。 6. [pending] F:冻结代码/基准、完整回归/全部界面、独立源码/桌面安装/便携与保留状态升级,封存原日志/截图/失败、回顾和下一阶段计划。 diff --git a/tests/desktop-bridge.test.mjs b/tests/desktop-bridge.test.mjs new file mode 100644 index 00000000..ab66ed11 --- /dev/null +++ b/tests/desktop-bridge.test.mjs @@ -0,0 +1,94 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { randomUUID, createHash } from 'node:crypto'; +import { fixture } from './helpers.mjs'; +import { DesktopBridge } from '../src/core/desktop/desktop-bridge.mjs'; +import { desktopInput } from '../src/shared/contracts/desktop-bridge.mjs'; +import { readText, listFiles } from '../src/server/files.mjs'; +import { HostAuthority } from '../src/core/desktop/host-authority.mjs'; +import { desktopLaunchOptions } from '../src/core/desktop/launch-options.mjs'; + +test('actual Electron debug argument ordering retains exactly the compiled entry and rejects extra or repeated actions', () => { + const mainFile = path.resolve('dist-desktop/main.cjs'), argv = ['electron.exe', '--inspect=0', '--remote-debugging-port=0', mainFile, '--port', '4319', '--hidden-window']; + assert.deepEqual(desktopLaunchOptions(argv, { defaultApp: true, mainFile }), { '--port': '4319', hidden: true }); + assert.deepEqual(desktopLaunchOptions(['product.exe', '--port', '4319'], { defaultApp: false }), { '--port': '4319' }); + assert.throws(() => desktopLaunchOptions(argv, { defaultApp: true, mainFile: path.resolve('different.cjs') })); + assert.throws(() => desktopLaunchOptions([...argv, '--port', '4320'], { defaultApp: true, mainFile })); + assert.throws(() => desktopLaunchOptions([...argv, '--command', 'arbitrary'], { defaultApp: true, mainFile })); +}); + +function setup(t) { + const f = fixture(t), frame = { url: 'http://127.0.0.1:4319/' }, contents = { mainFrame: frame }; + const window = { webContents: contents, isDestroyed: () => false }, event = { sender: contents, senderFrame: frame }; + const scope = { projectId: f.project.id, sessionId: f.session.id, taskId: randomUUID() }, calls = []; + const saved = { id: f.session.id, projectId: f.project.id, execution: { task: { id: scope.taskId } }, eventSeq: 19 }; + const identity = { instanceId: randomUUID(), runtimeIdentity: 'original' }; + const controller = { url: 'http://127.0.0.1:4319', connect: async () => ({ identity }), status: async () => ({ identity }), + api: async (route, options) => { calls.push({ route, options }); if (route === '/bootstrap') return { projects: [f.project] }; if (route.startsWith('/sessions/')) return saved; return f.project; }, + stop: async () => { calls.push({ stop: true }); return { processExited: true }; } }; + const shell = { openPath: async value => { calls.push({ folder: value }); return ''; }, showItemInFolder: value => calls.push({ reveal: value }) }; + const dialog = { showOpenDialog: async () => ({ canceled: true, filePaths: [] }), showMessageBox: async () => ({ response: 0 }) }; + const bridge = new DesktopBridge(controller, { shell, dialog, getWindow: () => window }); + return { ...f, frame, contents, window, event, scope, calls, saved, identity, controller, shell, dialog, bridge }; +} + +test('native bridge refuses other origins, subframes, other windows and unsupported inputs before connecting', async t => { + const f = setup(t); + for (const event of [{ ...f.event, sender: {} }, { ...f.event, senderFrame: { url: f.frame.url } }]) await assert.rejects(f.bridge.execute(event, 'pickProject')); + f.frame.url = 'https://example.invalid/'; await assert.rejects(f.bridge.execute(f.event, 'status')); assert.equal(f.calls.length, 0); + for (const input of [{ projectId: f.project.id, command: 'arbitrary' }, { projectId: '../project' }, ['project']]) assert.throws(() => desktopInput('projectFolder', input)); + assert.throws(() => desktopInput('arbitrary', {})); +}); + +test('file reveal binds the current project, task, path, UTF-8 bytes and original SHA without executing the file', async t => { + const f = setup(t), file = readText(f.project, 'README.md'), input = { ...f.scope, path: file.path, sha256: file.sha256 }; + await f.bridge.execute(f.event, 'revealFile', input); assert.equal(f.calls.filter(value => value.reveal).length, 1); assert.equal(f.calls.filter(value => value.folder).length, 0); + for (const changed of [{ taskId: randomUUID() }, { projectId: randomUUID() }, { sha256: '0'.repeat(64) }, { path: '../outside' }, { path: 'C:\\outside' }]) await assert.rejects(f.bridge.execute(f.event, 'revealFile', { ...input, ...changed })); + assert.equal(f.calls.filter(value => value.reveal).length, 1); + const invalid = Buffer.from([255, 254, 255]); fs.writeFileSync(path.join(f.projectRoot, 'bad.txt'), invalid); + await assert.rejects(f.bridge.execute(f.event, 'revealFile', { ...input, path: 'bad.txt', sha256: createHash('sha256').update(invalid).digest('hex') })); +}); + +test('file changed during asynchronous task recheck is not revealed as the old bytes', async t => { + const f = setup(t), file = readText(f.project, 'README.md'), original = f.controller.api; let requests = 0; + f.controller.api = async (...args) => { if (args[0].startsWith('/sessions/') && ++requests === 2) fs.appendFileSync(path.join(f.projectRoot, file.path), 'changed during original check'); return original(...args); }; + await assert.rejects(f.bridge.execute(f.event, 'revealFile', { ...f.scope, path: file.path, sha256: file.sha256 }), /变化/); + assert.equal(f.calls.filter(value => value.reveal).length, 0); +}); + +test('desktop browser profile and aliases stay outside project inventory and file access', async t => { + const f = setup(t), profile = path.join(f.projectRoot, '.desktop-profile'); fs.mkdirSync(profile); fs.writeFileSync(path.join(profile, 'Cookies'), 'owned private profile'); + fs.symlinkSync(profile, path.join(f.projectRoot, 'profile-alias'), 'junction'); + assert.throws(() => readText(f.project, '.desktop-profile/Cookies')); assert.throws(() => readText(f.project, 'profile-alias/Cookies')); + assert.equal(listFiles(f.project).files.some(value => /profile|Cookies/.test(value.path)), false); +}); + +test('native picker cancel and origin change after dialog publish no project registration', async t => { + const f = setup(t); assert.equal(await f.bridge.execute(f.event, 'pickProject'), null); + f.dialog.showOpenDialog = async () => { f.frame.url = 'http://127.0.0.1:4320/'; return { canceled: false, filePaths: [f.projectRoot] }; }; + await assert.rejects(f.bridge.execute(f.event, 'pickProject')); assert.equal(f.calls.some(value => value.route === '/projects'), false); +}); + +test('pending native action is not dispatched twice, and current task review returns its original seq', async t => { + const f = setup(t); let finish; f.dialog.showOpenDialog = () => new Promise(resolve => { finish = resolve; }); + const first = f.bridge.execute(f.event, 'pickProject'); await new Promise(resolve => setImmediate(resolve)); + await assert.rejects(f.bridge.execute(f.event, 'pickProject'), /正在处理/); finish({ canceled: true, filePaths: [] }); await first; + assert.deepEqual(await f.bridge.execute(f.event, 'reviewTask', f.scope), { ...f.scope, eventSeq: 19 }); +}); + +test('native stop cancellation and changed original host never stop a replacement process', async t => { + const f = setup(t); assert.deepEqual(await f.bridge.execute(f.event, 'stopHost'), { cancelled: true }); assert.equal(f.calls.some(value => value.stop), false); + f.dialog.showMessageBox = async () => ({ response: 1 }); let connects = 0; + f.controller.connect = async () => ({ identity: ++connects === 1 ? f.identity : { ...f.identity, runtimeIdentity: 'replacement' } }); + await assert.rejects(f.bridge.execute(f.event, 'stopHost'), /已变化/); assert.equal(f.calls.some(value => value.stop), false); + f.controller.connect = async () => ({ identity: f.identity }); assert.equal((await f.bridge.execute(f.event, 'stopHost')).processExited, true); assert.equal(f.calls.filter(value => value.stop).length, 1); +}); + +test('window register rejects host PID, stale installation, extra fields and missing creation identity', () => { + const authority = new HostAuthority({}), identity = { pid: process.pid, instanceId: randomUUID(), runtimeIdentity: 'original' }; authority.identity = () => identity; + const input = { windowId: randomUUID(), pid: 1234, createdAt: '2026-10-31T00:00:00.000Z', instanceId: identity.instanceId, runtimeIdentity: identity.runtimeIdentity }; + assert.equal(authority.assertWindowInput(input), identity); + for (const changed of [{ pid: process.pid }, { createdAt: '' }, { runtimeIdentity: 'replacement' }, { program: 'foreign' }]) assert.throws(() => authority.assertWindowInput({ ...input, ...changed })); +}); diff --git a/tests/upgrade.test.mjs b/tests/upgrade.test.mjs index f525d3ab..5bf65c10 100644 --- a/tests/upgrade.test.mjs +++ b/tests/upgrade.test.mjs @@ -20,6 +20,7 @@ test('a directly started compiled host upgrades twice with the same PID, session for (const label of ['first', 'second']) { const nextRoot = path.join(f.root, 'compiled-upgrade-' + label); fs.mkdirSync(nextRoot); for (const name of ['dist-server', 'dist-client']) fs.cpSync(path.join(workspace, name), path.join(nextRoot, name), { recursive: true }); + fs.copyFileSync(path.join(workspace, 'package.json'), path.join(nextRoot, 'package.json')); const result = await upgradeRunning({ url: host.url, pid: host.child.pid, currentRoot: workspace, handlerRoot: previousRoot, newRoot: nextRoot }); assert.equal(result.version, APP_VERSION); assert.equal(result.pid, host.child.pid); assert.equal(result.verified, true); assert.equal(result.hasKey, true); const afterBootstrap = await host.api('/bootstrap'); @@ -83,6 +84,7 @@ test('the running 0.1.0 process upgrades in place and retains its project, sessi const secondRoot = path.join(f.root, 'upgrade-second'); fs.mkdirSync(secondRoot); for (const name of ['dist-server', 'dist-client']) fs.cpSync(path.join(workspace, name), path.join(secondRoot, name), { recursive: true }); + fs.copyFileSync(path.join(workspace, 'package.json'), path.join(secondRoot, 'package.json')); fs.mkdirSync(path.join(secondRoot, 'runtime/node_modules'), { recursive: true }); fs.cpSync(path.join(path.dirname(process.execPath), 'node_modules/npm'), path.join(secondRoot, 'runtime/node_modules/npm'), { recursive: true }); const second = await upgradeRunning({ url, pid: child.pid, currentRoot: oldRoot, handlerRoot: workspace, newRoot: secondRoot });