feat(companion): add task PWA and original execution controls
@@ -5,6 +5,10 @@
|
|||||||
*.jpg binary
|
*.jpg binary
|
||||||
*.ico binary
|
*.ico binary
|
||||||
docs/companion-a-b-evidence/*.tap binary
|
docs/companion-a-b-evidence/*.tap binary
|
||||||
|
docs/companion-c-e-evidence/**/*.tap binary
|
||||||
|
docs/companion-c-e-evidence/*.tap binary
|
||||||
|
docs/companion-c-e-evidence/**/*.json -text
|
||||||
|
docs/companion-c-e-evidence/*.json -text
|
||||||
tests/fixtures/legacy-workbench-0.1/dist-server/server.mjs binary
|
tests/fixtures/legacy-workbench-0.1/dist-server/server.mjs binary
|
||||||
docs/workers-*.tap binary
|
docs/workers-*.tap binary
|
||||||
docs/workers-*.log binary
|
docs/workers-*.log binary
|
||||||
|
|||||||
@@ -13,3 +13,11 @@
|
|||||||
## C–F:实施中及待验收
|
## C–F:实施中及待验收
|
||||||
|
|
||||||
设备权限、独立手机界面、审批/停止、事件恢复、真实iPhone与独立发行分别记录。手机界面和浏览器模拟结果不能代替真实设备步骤;没有设备结果时不记完整交付。
|
设备权限、独立手机界面、审批/停止、事件恢复、真实iPhone与独立发行分别记录。手机界面和浏览器模拟结果不能代替真实设备步骤;没有设备结果时不记完整交付。
|
||||||
|
|
||||||
|
## C–E本地结果
|
||||||
|
|
||||||
|
新增专项扩充到24/24通过、0跳过,包括实际Runtime命令单次执行、桌面先拒绝/手机迟到、手机停止原进程及心跳终结、等待期间更换Run拒绝、差异分页SHA、原工件损坏拒绝、活动TLS连接撤销、损坏授权登记不覆盖,以及网关开启时阻止升级和失败恢复。输入均为自有项目/凭据,真实模型0请求。[原TAP与界面证据](companion-c-e-evidence/manifest.json)。
|
||||||
|
|
||||||
|
实际Edge执行7组流程:桌面1440px显式开启/下载证书,390px配对/同一Task/Run审批、实际命令、分页差异、1项真实工程测试和报告SHA;断线/刷新只读恢复;PWA只缓存壳;768px列表和窄屏管理;桌面撤销后手机清空项目内容。7组通过且页面异常0;最终浏览器收据为[原结果](companion-c-e-evidence/final-ui/result.json)。已实际观察原审批、报告和管理页截图,修正虚拟网卡优先、waiting中文、任务全文折叠和对话框视口。原失败独立保留:检查准备分别早于命令收尾/文件审查完成,均由正确409保护拒绝,脚本明确完成原流程后复验。
|
||||||
|
|
||||||
|
浏览器验收使用自有loopback QA中继,并逐请求验证真实网关CA,没有安装根证书或绕过TLS警告;测试cookie仅在中继内存,故这些结果**不证明**iPhone Safari原生Secure cookie、系统证书信任和主屏幕PWA已完成。原生iPhone、后台/切网与实际软键盘仍待F。当前尚未发布1.16或升级正式4318。
|
||||||
|
|||||||
@@ -11,3 +11,9 @@
|
|||||||
原Store只保留桌面update observer;手机采用授权项目SQL分页和短轮询,不新增需跨热升级迁移的观察者。网关使用原宿主/用户/目录身份,默认关闭,升级前必须关闭独立监听;关闭手机网关不调用Runtime.stop。新的手机授权仅保留摘要和脱敏审计。TLS私钥通过原CurrentUser DPAPI保护,未读取Provider凭据。
|
原Store只保留桌面update observer;手机采用授权项目SQL分页和短轮询,不新增需跨热升级迁移的观察者。网关使用原宿主/用户/目录身份,默认关闭,升级前必须关闭独立监听;关闭手机网关不调用Runtime.stop。新的手机授权仅保留摘要和脱敏审计。TLS私钥通过原CurrentUser DPAPI保护,未读取Provider凭据。
|
||||||
|
|
||||||
首轮未经过bundle执行而只看源码会漏掉二维码库CommonJS依赖;实际API/热升级回归及时揭示了问题。修复发行require后又发现源码定位标记冲突,保持原管理处理器唯一标记并对旧版连续升级复验。最终54/54通过,原失败与最终日志分别保存。接下来独立手机entry、设备管理和任务详情进入C;审批/停止的真实原Runtime竞争、断线及实际iPhone分别验收。
|
首轮未经过bundle执行而只看源码会漏掉二维码库CommonJS依赖;实际API/热升级回归及时揭示了问题。修复发行require后又发现源码定位标记冲突,保持原管理处理器唯一标记并对旧版连续升级复验。最终54/54通过,原失败与最终日志分别保存。接下来独立手机entry、设备管理和任务详情进入C;审批/停止的真实原Runtime竞争、断线及实际iPhone分别验收。
|
||||||
|
|
||||||
|
## C–E本地回顾
|
||||||
|
|
||||||
|
任务队列/详情围绕原审批、差异、检查和报告组成,避免把桌面编辑器缩小到手机。7组实际宽窄屏流程与24项专项通过。实际原Runtime命令/进程检验证明操作归属和停止结果;浏览器截图只能证明页面结果,原生Safari证书/cookie与PWA留给真实iPhone,测试中继身份清楚记录。
|
||||||
|
|
||||||
|
两次UI检查均由产品正确409保护拒绝,原因分别是脚本过早开始检查、未审查待应用文件;补全原流程后通过。回顾发现WSL网卡默认地址会误导用户,已优先真实网卡;操作请求ID固定于一次确认,未知回执持久查询,刷新不再丢失。设备授权/日期登记损坏时明确拒绝并保留原数据,不把格式问题降级为永久授权。发行前继续全量回归和独立实机候选,正式4318保持原状。
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
|
||||||
|
> local-agent-workbench@1.15.0 build
|
||||||
|
> tsc --noEmit && vite build && node scripts/build-mobile.mjs && node scripts/build-server.mjs
|
||||||
|
|
||||||
|
vite v7.3.7 building client environment for production...
|
||||||
|
transforming...
|
||||||
|
✓ 1725 modules transformed.
|
||||||
|
rendering chunks...
|
||||||
|
computing gzip size...
|
||||||
|
dist-client/.vite/manifest.json 0.55 kB │ gzip: 0.22 kB
|
||||||
|
dist-client/index.html 0.58 kB │ gzip: 0.40 kB
|
||||||
|
dist-client/mobile.html 0.82 kB │ gzip: 0.45 kB
|
||||||
|
dist-client/assets/mobile-CPi1xsK3.css 11.10 kB │ gzip: 2.97 kB
|
||||||
|
dist-client/assets/desktop-BaQ1ZMRu.css 134.24 kB │ gzip: 25.64 kB
|
||||||
|
dist-client/assets/mobile-tKLJoem9.js 21.38 kB │ gzip: 7.64 kB
|
||||||
|
dist-client/assets/x-Cc3T3VuL.js 225.51 kB │ gzip: 70.77 kB
|
||||||
|
dist-client/assets/desktop-DmqBcePV.js 277.30 kB │ gzip: 78.12 kB
|
||||||
|
✓ built in 1.11s
|
||||||
|
Mobile shell built: 3 allowed assets; API and project data are never cached.
|
||||||
|
Server bundle built.
|
||||||
|
After Width: | Height: | Size: 170 KiB |
|
After Width: | Height: | Size: 59 KiB |
|
After Width: | Height: | Size: 171 KiB |
|
After Width: | Height: | Size: 57 KiB |
|
After Width: | Height: | Size: 84 KiB |
|
After Width: | Height: | Size: 19 KiB |
|
After Width: | Height: | Size: 29 KiB |
|
After Width: | Height: | Size: 35 KiB |
|
After Width: | Height: | Size: 22 KiB |
@@ -0,0 +1,37 @@
|
|||||||
|
{
|
||||||
|
"success": true,
|
||||||
|
"passed": [
|
||||||
|
"desktop explicitly enables HTTPS and downloads the actual public CA without changing OS trust",
|
||||||
|
"390px real gateway pairing clears fragment, displays scoped task list and registers the same device in desktop",
|
||||||
|
"phone UI confirms original Task/Run approval and the existing Runtime executes one command",
|
||||||
|
"original paginated diff and counted check/report display verified content from the same Task",
|
||||||
|
"disconnect and refresh recover from persistent seq without submitting a new command or Run",
|
||||||
|
"PWA service worker stores the shell and no API/project response",
|
||||||
|
"desktop revocation removes mobile project content immediately on the next read while preserving the original completed tool"
|
||||||
|
],
|
||||||
|
"screenshots": [
|
||||||
|
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\companion-ui-729c8012-e765-4d85-b988-dd9f8e19e1b8\\desktop-certificate.png",
|
||||||
|
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\companion-ui-729c8012-e765-4d85-b988-dd9f8e19e1b8\\desktop-pairing.png",
|
||||||
|
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\companion-ui-729c8012-e765-4d85-b988-dd9f8e19e1b8\\mobile-task-list.png",
|
||||||
|
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\companion-ui-729c8012-e765-4d85-b988-dd9f8e19e1b8\\mobile-original-approval.png",
|
||||||
|
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\companion-ui-729c8012-e765-4d85-b988-dd9f8e19e1b8\\mobile-original-diff.png",
|
||||||
|
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\companion-ui-729c8012-e765-4d85-b988-dd9f8e19e1b8\\mobile-original-report.png",
|
||||||
|
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\companion-ui-729c8012-e765-4d85-b988-dd9f8e19e1b8\\mobile-disconnected.png",
|
||||||
|
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\companion-ui-729c8012-e765-4d85-b988-dd9f8e19e1b8\\tablet-task-list.png",
|
||||||
|
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\companion-ui-729c8012-e765-4d85-b988-dd9f8e19e1b8\\desktop-management-narrow.png",
|
||||||
|
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\companion-ui-729c8012-e765-4d85-b988-dd9f8e19e1b8\\mobile-revoked.png"
|
||||||
|
],
|
||||||
|
"errors": [],
|
||||||
|
"viewports": [
|
||||||
|
1440,
|
||||||
|
390,
|
||||||
|
768
|
||||||
|
],
|
||||||
|
"browser": "Microsoft Edge via Playwright; owned loopback QA relay with actual CA verification",
|
||||||
|
"nativeSafariTrustCookiePWA": "pending-real-iPhone",
|
||||||
|
"osTrustChanged": false,
|
||||||
|
"certificateWarningsBypassed": false,
|
||||||
|
"realModelRequests": 0,
|
||||||
|
"taskId": "2dcd9268-70f1-4ab1-af8a-b8fd1288b10c",
|
||||||
|
"runId": "d8a42a75-3458-47a0-9666-79f397a20cd9"
|
||||||
|
}
|
||||||
|
After Width: | Height: | Size: 24 KiB |
@@ -0,0 +1,154 @@
|
|||||||
|
TAP version 13
|
||||||
|
# Subtest: pairing is short lived, single-use, generation-bound and validates exact permissions
|
||||||
|
ok 1 - pairing is short lived, single-use, generation-bound and validates exact permissions
|
||||||
|
---
|
||||||
|
duration_ms: 812.0727
|
||||||
|
type: 'test'
|
||||||
|
...
|
||||||
|
# Subtest: device transaction failure neither consumes the ticket nor leaves a credential
|
||||||
|
ok 2 - device transaction failure neither consumes the ticket nor leaves a credential
|
||||||
|
---
|
||||||
|
duration_ms: 720.9239
|
||||||
|
type: 'test'
|
||||||
|
...
|
||||||
|
# Subtest: devices have project and action boundaries; rotation, expiration, revocation and host changes reject old authority
|
||||||
|
ok 3 - devices have project and action boundaries; rotation, expiration, revocation and host changes reject old authority
|
||||||
|
---
|
||||||
|
duration_ms: 976.0319
|
||||||
|
type: 'test'
|
||||||
|
...
|
||||||
|
# Subtest: persistent registry stores hashes and a bounded audit, never raw credentials
|
||||||
|
ok 4 - persistent registry stores hashes and a bounded audit, never raw credentials
|
||||||
|
---
|
||||||
|
duration_ms: 981.4517
|
||||||
|
type: 'test'
|
||||||
|
...
|
||||||
|
# Subtest: real TLS verifies IP SAN, CA chain, encrypted restart and public fingerprint
|
||||||
|
ok 5 - real TLS verifies IP SAN, CA chain, encrypted restart and public fingerprint
|
||||||
|
---
|
||||||
|
duration_ms: 1045.3838
|
||||||
|
type: 'test'
|
||||||
|
...
|
||||||
|
# Subtest: TLS sealing failure leaves listener closed and no plaintext or successful TLS registration
|
||||||
|
ok 6 - TLS sealing failure leaves listener closed and no plaintext or successful TLS registration
|
||||||
|
---
|
||||||
|
duration_ms: 850.6399
|
||||||
|
type: 'test'
|
||||||
|
...
|
||||||
|
# Subtest: HTTP pairing is concurrent single-use; secure cookie and strict origin/host checks
|
||||||
|
ok 7 - HTTP pairing is concurrent single-use; secure cookie and strict origin/host checks
|
||||||
|
---
|
||||||
|
duration_ms: 900.8533
|
||||||
|
type: 'test'
|
||||||
|
...
|
||||||
|
# Subtest: gateway never exposes management routes, arbitrary assets or unpaired project data
|
||||||
|
ok 8 - gateway never exposes management routes, arbitrary assets or unpaired project data
|
||||||
|
---
|
||||||
|
duration_ms: 868.9467
|
||||||
|
type: 'test'
|
||||||
|
...
|
||||||
|
# Subtest: authorized project events paginate from original seq without leaking other project events or payloads
|
||||||
|
ok 9 - authorized project events paginate from original seq without leaking other project events or payloads
|
||||||
|
---
|
||||||
|
duration_ms: 1321.4981
|
||||||
|
type: 'test'
|
||||||
|
...
|
||||||
|
# Subtest: remote task projection excludes raw model history, host configuration, tool input and credentials
|
||||||
|
ok 10 - remote task projection excludes raw model history, host configuration, tool input and credentials
|
||||||
|
---
|
||||||
|
duration_ms: 686.7927
|
||||||
|
type: 'test'
|
||||||
|
...
|
||||||
|
# Subtest: permission checks apply to direct remote mutation, not only UI controls
|
||||||
|
ok 11 - permission checks apply to direct remote mutation, not only UI controls
|
||||||
|
---
|
||||||
|
duration_ms: 642.1176
|
||||||
|
type: 'test'
|
||||||
|
...
|
||||||
|
# Subtest: approval fingerprint and exact task/revision are bound; duplicate requests never execute twice
|
||||||
|
ok 12 - approval fingerprint and exact task/revision are bound; duplicate requests never execute twice
|
||||||
|
---
|
||||||
|
duration_ms: 876.5462
|
||||||
|
type: 'test'
|
||||||
|
...
|
||||||
|
# Subtest: unknown original operation is recorded and never replayed after response failure
|
||||||
|
ok 13 - unknown original operation is recorded and never replayed after response failure
|
||||||
|
---
|
||||||
|
duration_ms: 812.4198
|
||||||
|
type: 'test'
|
||||||
|
...
|
||||||
|
# Subtest: revocation and gateway closure reject old access without invoking runtime stop
|
||||||
|
ok 14 - revocation and gateway closure reject old access without invoking runtime stop
|
||||||
|
---
|
||||||
|
duration_ms: 653.0715
|
||||||
|
type: 'test'
|
||||||
|
...
|
||||||
|
# Subtest: rate limits reject pairing brute force and do not persist candidate secrets
|
||||||
|
ok 15 - rate limits reject pairing brute force and do not persist candidate secrets
|
||||||
|
---
|
||||||
|
duration_ms: 692.8977
|
||||||
|
type: 'test'
|
||||||
|
...
|
||||||
|
# Subtest: real Windows CurrentUser DPAPI persists only a sealed CA and reopens it
|
||||||
|
ok 16 - real Windows CurrentUser DPAPI persists only a sealed CA and reopens it
|
||||||
|
---
|
||||||
|
duration_ms: 2458.3847
|
||||||
|
type: 'test'
|
||||||
|
...
|
||||||
|
# Subtest: mobile approval executes the original Runtime command exactly once and rejects the later desktop decision
|
||||||
|
ok 17 - mobile approval executes the original Runtime command exactly once and rejects the later desktop decision
|
||||||
|
---
|
||||||
|
duration_ms: 2080.6441
|
||||||
|
type: 'test'
|
||||||
|
...
|
||||||
|
# Subtest: desktop rejection wins a concurrent mobile request and original command remains unexecuted
|
||||||
|
ok 18 - desktop rejection wins a concurrent mobile request and original command remains unexecuted
|
||||||
|
---
|
||||||
|
duration_ms: 1549.6235
|
||||||
|
type: 'test'
|
||||||
|
...
|
||||||
|
# Subtest: phone stop waits for the original process exit and prevents later heartbeats and command replay
|
||||||
|
ok 19 - phone stop waits for the original process exit and prevents later heartbeats and command replay
|
||||||
|
---
|
||||||
|
duration_ms: 2007.6397
|
||||||
|
type: 'test'
|
||||||
|
...
|
||||||
|
# Subtest: Run replacement during parent-stop wait is rejected rather than stopping the new Run
|
||||||
|
ok 20 - Run replacement during parent-stop wait is rejected rather than stopping the new Run
|
||||||
|
---
|
||||||
|
duration_ms: 499.7436
|
||||||
|
type: 'test'
|
||||||
|
...
|
||||||
|
# Subtest: diff pages preserve source SHA; report reads verify blobs and exclude unrelated artifact kinds
|
||||||
|
ok 21 - diff pages preserve source SHA; report reads verify blobs and exclude unrelated artifact kinds
|
||||||
|
---
|
||||||
|
duration_ms: 804.5479
|
||||||
|
type: 'test'
|
||||||
|
...
|
||||||
|
# Subtest: hot upgrade refuses an active gateway and restores closed gateway ownership on failure
|
||||||
|
ok 22 - hot upgrade refuses an active gateway and restores closed gateway ownership on failure
|
||||||
|
---
|
||||||
|
duration_ms: 602.6744
|
||||||
|
type: 'test'
|
||||||
|
...
|
||||||
|
# Subtest: damaged device permissions or expiry fail closed and never overwrite the original registry
|
||||||
|
ok 23 - damaged device permissions or expiry fail closed and never overwrite the original registry
|
||||||
|
---
|
||||||
|
duration_ms: 816.9531
|
||||||
|
type: 'test'
|
||||||
|
...
|
||||||
|
# Subtest: device revocation destroys its actual authenticated TLS connection
|
||||||
|
ok 24 - device revocation destroys its actual authenticated TLS connection
|
||||||
|
---
|
||||||
|
duration_ms: 854.0281
|
||||||
|
type: 'test'
|
||||||
|
...
|
||||||
|
1..24
|
||||||
|
# tests 24
|
||||||
|
# suites 0
|
||||||
|
# pass 24
|
||||||
|
# fail 0
|
||||||
|
# cancelled 0
|
||||||
|
# skipped 0
|
||||||
|
# todo 0
|
||||||
|
# duration_ms 24745.6476
|
||||||
@@ -0,0 +1,157 @@
|
|||||||
|
TAP version 13
|
||||||
|
# Subtest: pairing is short lived, single-use, generation-bound and validates exact permissions
|
||||||
|
ok 1 - pairing is short lived, single-use, generation-bound and validates exact permissions
|
||||||
|
---
|
||||||
|
duration_ms: 589.0293
|
||||||
|
type: 'test'
|
||||||
|
...
|
||||||
|
# Subtest: device transaction failure neither consumes the ticket nor leaves a credential
|
||||||
|
ok 2 - device transaction failure neither consumes the ticket nor leaves a credential
|
||||||
|
---
|
||||||
|
duration_ms: 679.4563
|
||||||
|
type: 'test'
|
||||||
|
...
|
||||||
|
# Subtest: devices have project and action boundaries; rotation, expiration, revocation and host changes reject old authority
|
||||||
|
ok 3 - devices have project and action boundaries; rotation, expiration, revocation and host changes reject old authority
|
||||||
|
---
|
||||||
|
duration_ms: 742.7184
|
||||||
|
type: 'test'
|
||||||
|
...
|
||||||
|
# Subtest: persistent registry stores hashes and a bounded audit, never raw credentials
|
||||||
|
ok 4 - persistent registry stores hashes and a bounded audit, never raw credentials
|
||||||
|
---
|
||||||
|
duration_ms: 559.8063
|
||||||
|
type: 'test'
|
||||||
|
...
|
||||||
|
# Subtest: real TLS verifies IP SAN, CA chain, encrypted restart and public fingerprint
|
||||||
|
ok 5 - real TLS verifies IP SAN, CA chain, encrypted restart and public fingerprint
|
||||||
|
---
|
||||||
|
duration_ms: 971.1269
|
||||||
|
type: 'test'
|
||||||
|
...
|
||||||
|
# Subtest: TLS sealing failure leaves listener closed and no plaintext or successful TLS registration
|
||||||
|
ok 6 - TLS sealing failure leaves listener closed and no plaintext or successful TLS registration
|
||||||
|
---
|
||||||
|
duration_ms: 507.5549
|
||||||
|
type: 'test'
|
||||||
|
...
|
||||||
|
# Subtest: HTTP pairing is concurrent single-use; secure cookie and strict origin/host checks
|
||||||
|
ok 7 - HTTP pairing is concurrent single-use; secure cookie and strict origin/host checks
|
||||||
|
---
|
||||||
|
duration_ms: 753.6926
|
||||||
|
type: 'test'
|
||||||
|
...
|
||||||
|
# Subtest: gateway never exposes management routes, arbitrary assets or unpaired project data
|
||||||
|
ok 8 - gateway never exposes management routes, arbitrary assets or unpaired project data
|
||||||
|
---
|
||||||
|
duration_ms: 693.6116
|
||||||
|
type: 'test'
|
||||||
|
...
|
||||||
|
# Subtest: authorized project events paginate from original seq without leaking other project events or payloads
|
||||||
|
ok 9 - authorized project events paginate from original seq without leaking other project events or payloads
|
||||||
|
---
|
||||||
|
duration_ms: 1163.7529
|
||||||
|
type: 'test'
|
||||||
|
...
|
||||||
|
# Subtest: remote task projection excludes raw model history, host configuration, tool input and credentials
|
||||||
|
ok 10 - remote task projection excludes raw model history, host configuration, tool input and credentials
|
||||||
|
---
|
||||||
|
duration_ms: 751.1109
|
||||||
|
type: 'test'
|
||||||
|
...
|
||||||
|
# Subtest: permission checks apply to direct remote mutation, not only UI controls
|
||||||
|
ok 11 - permission checks apply to direct remote mutation, not only UI controls
|
||||||
|
---
|
||||||
|
duration_ms: 681.1806
|
||||||
|
type: 'test'
|
||||||
|
...
|
||||||
|
# Subtest: approval fingerprint and exact task/revision are bound; duplicate requests never execute twice
|
||||||
|
ok 12 - approval fingerprint and exact task/revision are bound; duplicate requests never execute twice
|
||||||
|
---
|
||||||
|
duration_ms: 813.2138
|
||||||
|
type: 'test'
|
||||||
|
...
|
||||||
|
# Subtest: unknown original operation is recorded and never replayed after response failure
|
||||||
|
ok 13 - unknown original operation is recorded and never replayed after response failure
|
||||||
|
---
|
||||||
|
duration_ms: 808.2965
|
||||||
|
type: 'test'
|
||||||
|
...
|
||||||
|
# Subtest: revocation and gateway closure reject old access without invoking runtime stop
|
||||||
|
ok 14 - revocation and gateway closure reject old access without invoking runtime stop
|
||||||
|
---
|
||||||
|
duration_ms: 724.6912
|
||||||
|
type: 'test'
|
||||||
|
...
|
||||||
|
# Subtest: rate limits reject pairing brute force and do not persist candidate secrets
|
||||||
|
ok 15 - rate limits reject pairing brute force and do not persist candidate secrets
|
||||||
|
---
|
||||||
|
duration_ms: 866.1867
|
||||||
|
type: 'test'
|
||||||
|
...
|
||||||
|
# Subtest: real Windows CurrentUser DPAPI persists only a sealed CA and reopens it
|
||||||
|
ok 16 - real Windows CurrentUser DPAPI persists only a sealed CA and reopens it
|
||||||
|
---
|
||||||
|
duration_ms: 1815.7111
|
||||||
|
type: 'test'
|
||||||
|
...
|
||||||
|
# Subtest: mobile approval executes the original Runtime command exactly once and rejects the later desktop decision
|
||||||
|
ok 17 - mobile approval executes the original Runtime command exactly once and rejects the later desktop decision
|
||||||
|
---
|
||||||
|
duration_ms: 1825.7504
|
||||||
|
type: 'test'
|
||||||
|
...
|
||||||
|
# Subtest: desktop rejection wins a concurrent mobile request and original command remains unexecuted
|
||||||
|
ok 18 - desktop rejection wins a concurrent mobile request and original command remains unexecuted
|
||||||
|
---
|
||||||
|
duration_ms: 1557.2142
|
||||||
|
type: 'test'
|
||||||
|
...
|
||||||
|
# Subtest: phone stop waits for the original process exit and prevents later heartbeats and command replay
|
||||||
|
ok 19 - phone stop waits for the original process exit and prevents later heartbeats and command replay
|
||||||
|
---
|
||||||
|
duration_ms: 2106.1923
|
||||||
|
type: 'test'
|
||||||
|
...
|
||||||
|
# Subtest: Run replacement during parent-stop wait is rejected rather than stopping the new Run
|
||||||
|
ok 20 - Run replacement during parent-stop wait is rejected rather than stopping the new Run
|
||||||
|
---
|
||||||
|
duration_ms: 620.677
|
||||||
|
type: 'test'
|
||||||
|
...
|
||||||
|
# Subtest: diff pages preserve source SHA; report reads verify blobs and exclude unrelated artifact kinds
|
||||||
|
not ok 21 - diff pages preserve source SHA; report reads verify blobs and exclude unrelated artifact kinds
|
||||||
|
---
|
||||||
|
duration_ms: 789.5575
|
||||||
|
type: 'test'
|
||||||
|
location: 'D:\\Ai-project\\REA逆向\\Agent-Workbench\\tests\\companion.test.mjs:293:1'
|
||||||
|
failureType: 'testCodeFailure'
|
||||||
|
error: '记录不属于这个任务。'
|
||||||
|
code: 'ERR_TEST_FAILURE'
|
||||||
|
stack: |-
|
||||||
|
file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/src/server/store.mjs:173:99
|
||||||
|
Array.map (<anonymous>)
|
||||||
|
file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/src/server/store.mjs:169:117
|
||||||
|
Array.flatMap (<anonymous>)
|
||||||
|
Store.recordsFor (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/src/server/store.mjs:169:23)
|
||||||
|
Store.save (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/src/server/store.mjs:363:55)
|
||||||
|
TestContext.<anonymous> (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/tests/companion.test.mjs:299:97)
|
||||||
|
process.processTicksAndRejections (node:internal/process/task_queues:104:5)
|
||||||
|
async Test.run (node:internal/test_runner/test:1409:7)
|
||||||
|
async Test.processPendingSubtests (node:internal/test_runner/test:974:7)
|
||||||
|
...
|
||||||
|
# Subtest: hot upgrade refuses an active gateway and restores closed gateway ownership on failure
|
||||||
|
ok 22 - hot upgrade refuses an active gateway and restores closed gateway ownership on failure
|
||||||
|
---
|
||||||
|
duration_ms: 651.8724
|
||||||
|
type: 'test'
|
||||||
|
...
|
||||||
|
1..22
|
||||||
|
# tests 22
|
||||||
|
# suites 0
|
||||||
|
# pass 21
|
||||||
|
# fail 1
|
||||||
|
# cancelled 0
|
||||||
|
# skipped 0
|
||||||
|
# todo 0
|
||||||
|
# duration_ms 20907.3317
|
||||||
|
After Width: | Height: | Size: 170 KiB |
|
After Width: | Height: | Size: 171 KiB |
|
After Width: | Height: | Size: 160 KiB |
|
After Width: | Height: | Size: 52 KiB |
|
After Width: | Height: | Size: 88 KiB |
|
After Width: | Height: | Size: 26 KiB |
|
After Width: | Height: | Size: 22 KiB |
@@ -0,0 +1,21 @@
|
|||||||
|
{
|
||||||
|
"success": false,
|
||||||
|
"error": "任务或检查正在执行,请等待结束后再准备检查。",
|
||||||
|
"stack": "Error: 任务或检查正在执行,请等待结束后再准备检查。\n at Object.api (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/tests/helpers.mjs:107:43)\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-companion-ui.mjs:88:3",
|
||||||
|
"passed": [
|
||||||
|
"desktop explicitly enables HTTPS and downloads the actual public CA without changing OS trust",
|
||||||
|
"390px real gateway pairing clears fragment, displays scoped task list and registers the same device in desktop",
|
||||||
|
"phone UI confirms original Task/Run approval and the existing Runtime executes one command"
|
||||||
|
],
|
||||||
|
"screenshots": [
|
||||||
|
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\companion-ui-5c128b2b-1d2f-4673-8fdb-3d02a754cb50\\desktop-certificate.png",
|
||||||
|
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\companion-ui-5c128b2b-1d2f-4673-8fdb-3d02a754cb50\\desktop-pairing.png",
|
||||||
|
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\companion-ui-5c128b2b-1d2f-4673-8fdb-3d02a754cb50\\mobile-task-list.png",
|
||||||
|
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\companion-ui-5c128b2b-1d2f-4673-8fdb-3d02a754cb50\\mobile-original-approval.png",
|
||||||
|
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\companion-ui-5c128b2b-1d2f-4673-8fdb-3d02a754cb50\\mobile-original-diff.png",
|
||||||
|
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\companion-ui-5c128b2b-1d2f-4673-8fdb-3d02a754cb50\\failure-mobile.png",
|
||||||
|
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\companion-ui-5c128b2b-1d2f-4673-8fdb-3d02a754cb50\\failure-desktop.png"
|
||||||
|
],
|
||||||
|
"errors": [],
|
||||||
|
"realModelRequests": 0
|
||||||
|
}
|
||||||
@@ -0,0 +1,186 @@
|
|||||||
|
{
|
||||||
|
"schema": 1,
|
||||||
|
"description": "Unmodified fixture evidence; browser relay is not native iPhone acceptance",
|
||||||
|
"entries": [
|
||||||
|
{
|
||||||
|
"source": ".qa/companion-c-d-e-final.tap",
|
||||||
|
"file": "docs\\companion-c-e-evidence\\final.tap",
|
||||||
|
"bytes": 6119,
|
||||||
|
"sha256": "ecf0b9c3e47a75e5fb76666fcff7dc28d646e376da079cbc3ca6afbcfeb6fc96"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"source": ".qa/companion-d-e-first.tap",
|
||||||
|
"file": "docs\\companion-c-e-evidence\\first-runtime-fixture-failure.tap",
|
||||||
|
"bytes": 6671,
|
||||||
|
"sha256": "fae0e90d7af7234c6a215d38bd596235149b744f49e6c260568eb25e76470787"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"source": ".qa/companion-c-reviewed-build.txt",
|
||||||
|
"file": "docs\\companion-c-e-evidence\\build.txt",
|
||||||
|
"bytes": 978,
|
||||||
|
"sha256": "456f8e920a36e88cc6a5f903c2a1fb064fa6a9227f5183575940152c46be789f"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"source": ".qa\\companion-ui-5c128b2b-1d2f-4673-8fdb-3d02a754cb50\\desktop-certificate.png",
|
||||||
|
"file": "docs\\companion-c-e-evidence\\first-ui-failure\\desktop-certificate.png",
|
||||||
|
"bytes": 173988,
|
||||||
|
"sha256": "0b88931267a413a6b527f376e3db3cc7fd773c2d3dd2eef3621beb21609730ad"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"source": ".qa\\companion-ui-5c128b2b-1d2f-4673-8fdb-3d02a754cb50\\desktop-pairing.png",
|
||||||
|
"file": "docs\\companion-c-e-evidence\\first-ui-failure\\desktop-pairing.png",
|
||||||
|
"bytes": 175404,
|
||||||
|
"sha256": "a9732a3c0fde03ef0bb6980cb8e1d00eb3c18a660ecf7987bd12898f40c67495"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"source": ".qa\\companion-ui-5c128b2b-1d2f-4673-8fdb-3d02a754cb50\\failure-desktop.png",
|
||||||
|
"file": "docs\\companion-c-e-evidence\\first-ui-failure\\failure-desktop.png",
|
||||||
|
"bytes": 163674,
|
||||||
|
"sha256": "850ebcaa3a6c483736156e9a431287f8028ea43cfecdacdd00f9183d630e98d5"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"source": ".qa\\companion-ui-5c128b2b-1d2f-4673-8fdb-3d02a754cb50\\failure-mobile.png",
|
||||||
|
"file": "docs\\companion-c-e-evidence\\first-ui-failure\\failure-mobile.png",
|
||||||
|
"bytes": 53060,
|
||||||
|
"sha256": "98f6b31368d53b1157a864f83037e9aaab7a8adfcfe70a848b89b4a00db9a471"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"source": ".qa\\companion-ui-5c128b2b-1d2f-4673-8fdb-3d02a754cb50\\mobile-original-approval.png",
|
||||||
|
"file": "docs\\companion-c-e-evidence\\first-ui-failure\\mobile-original-approval.png",
|
||||||
|
"bytes": 90248,
|
||||||
|
"sha256": "6bb1ab73e275c1ddb3d05b8a00d88593372dd8d4226491b5d542db85ed1330ff"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"source": ".qa\\companion-ui-5c128b2b-1d2f-4673-8fdb-3d02a754cb50\\mobile-original-diff.png",
|
||||||
|
"file": "docs\\companion-c-e-evidence\\first-ui-failure\\mobile-original-diff.png",
|
||||||
|
"bytes": 26339,
|
||||||
|
"sha256": "edd84832429832c774ab8699b633821169de0eb6115f8d15c88241baa71311c9"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"source": ".qa\\companion-ui-5c128b2b-1d2f-4673-8fdb-3d02a754cb50\\mobile-task-list.png",
|
||||||
|
"file": "docs\\companion-c-e-evidence\\first-ui-failure\\mobile-task-list.png",
|
||||||
|
"bytes": 22258,
|
||||||
|
"sha256": "c038006b1131e2ac454ea07320af31bba51f3e6a30a1bbd0f79d7cf98069a8bd"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"source": ".qa\\companion-ui-5c128b2b-1d2f-4673-8fdb-3d02a754cb50\\result.json",
|
||||||
|
"file": "docs\\companion-c-e-evidence\\first-ui-failure\\result.json",
|
||||||
|
"bytes": 1799,
|
||||||
|
"sha256": "9fc01d1c6e890bca0810136af8b346afabe04cccd45d19175ec49181aca2c3db"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"source": ".qa\\companion-ui-74084878-28df-45f6-8f42-25ab09a68ee0\\desktop-certificate.png",
|
||||||
|
"file": "docs\\companion-c-e-evidence\\second-ui-failure\\desktop-certificate.png",
|
||||||
|
"bytes": 173789,
|
||||||
|
"sha256": "226b62575b4f1f75fa0cd9ecbf9e01d6add702ebcb653523ecc0438da615b234"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"source": ".qa\\companion-ui-74084878-28df-45f6-8f42-25ab09a68ee0\\desktop-pairing.png",
|
||||||
|
"file": "docs\\companion-c-e-evidence\\second-ui-failure\\desktop-pairing.png",
|
||||||
|
"bytes": 175151,
|
||||||
|
"sha256": "e46a65ea07cd507271e70270a83cfe85a1944a88bffc0274ff62d56e6fbf2ef1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"source": ".qa\\companion-ui-74084878-28df-45f6-8f42-25ab09a68ee0\\failure-desktop.png",
|
||||||
|
"file": "docs\\companion-c-e-evidence\\second-ui-failure\\failure-desktop.png",
|
||||||
|
"bytes": 163494,
|
||||||
|
"sha256": "3fca216b3e1cde8327d0dbc30f21f117650f5f5be51c56b3c0fb77add12114f8"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"source": ".qa\\companion-ui-74084878-28df-45f6-8f42-25ab09a68ee0\\failure-mobile.png",
|
||||||
|
"file": "docs\\companion-c-e-evidence\\second-ui-failure\\failure-mobile.png",
|
||||||
|
"bytes": 49654,
|
||||||
|
"sha256": "6d44f74586b8cb55b748cd954368e140f938ecc480bd4aace3c6bd719e1fda66"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"source": ".qa\\companion-ui-74084878-28df-45f6-8f42-25ab09a68ee0\\mobile-original-approval.png",
|
||||||
|
"file": "docs\\companion-c-e-evidence\\second-ui-failure\\mobile-original-approval.png",
|
||||||
|
"bytes": 90309,
|
||||||
|
"sha256": "d92225c3c98bf2fe56912db65e32d1225cb18ed5dd78a4fed2774bde27ef34db"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"source": ".qa\\companion-ui-74084878-28df-45f6-8f42-25ab09a68ee0\\mobile-original-diff.png",
|
||||||
|
"file": "docs\\companion-c-e-evidence\\second-ui-failure\\mobile-original-diff.png",
|
||||||
|
"bytes": 22874,
|
||||||
|
"sha256": "87477ba8ff21d11882236e86f4fe014f804955a1dd54588b5408824f340fe447"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"source": ".qa\\companion-ui-74084878-28df-45f6-8f42-25ab09a68ee0\\mobile-task-list.png",
|
||||||
|
"file": "docs\\companion-c-e-evidence\\second-ui-failure\\mobile-task-list.png",
|
||||||
|
"bytes": 22275,
|
||||||
|
"sha256": "fb0088858cf13985b4957401cf66b0c443393dde026dbb1826b848a5171f8999"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"source": ".qa\\companion-ui-74084878-28df-45f6-8f42-25ab09a68ee0\\result.json",
|
||||||
|
"file": "docs\\companion-c-e-evidence\\second-ui-failure\\result.json",
|
||||||
|
"bytes": 1812,
|
||||||
|
"sha256": "35f7a3031cf21fbd331dd98ab79f6641349c5c10bdf81153c40e5dbcf73733cf"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"source": ".qa\\companion-ui-729c8012-e765-4d85-b988-dd9f8e19e1b8\\desktop-certificate.png",
|
||||||
|
"file": "docs\\companion-c-e-evidence\\final-ui\\desktop-certificate.png",
|
||||||
|
"bytes": 174062,
|
||||||
|
"sha256": "37964d7720a0646c56cd4904cf432b37887bccc2cb26a35328ac854b0c9998a6"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"source": ".qa\\companion-ui-729c8012-e765-4d85-b988-dd9f8e19e1b8\\desktop-management-narrow.png",
|
||||||
|
"file": "docs\\companion-c-e-evidence\\final-ui\\desktop-management-narrow.png",
|
||||||
|
"bytes": 60084,
|
||||||
|
"sha256": "d2b44197ecea1ee8faf63bedc81c60eba44a1210aae871f5e75f58d2bedc4f2d"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"source": ".qa\\companion-ui-729c8012-e765-4d85-b988-dd9f8e19e1b8\\desktop-pairing.png",
|
||||||
|
"file": "docs\\companion-c-e-evidence\\final-ui\\desktop-pairing.png",
|
||||||
|
"bytes": 175465,
|
||||||
|
"sha256": "7d0ada471408019900d51e7a3c3d60f82a55e03ef2126b0c3bdc3cabfabc6dc3"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"source": ".qa\\companion-ui-729c8012-e765-4d85-b988-dd9f8e19e1b8\\mobile-disconnected.png",
|
||||||
|
"file": "docs\\companion-c-e-evidence\\final-ui\\mobile-disconnected.png",
|
||||||
|
"bytes": 58068,
|
||||||
|
"sha256": "f85175ebae4b9cb379db29fbd74abad8f8785f3eb0125e02216d6ce2af749b55"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"source": ".qa\\companion-ui-729c8012-e765-4d85-b988-dd9f8e19e1b8\\mobile-original-approval.png",
|
||||||
|
"file": "docs\\companion-c-e-evidence\\final-ui\\mobile-original-approval.png",
|
||||||
|
"bytes": 86546,
|
||||||
|
"sha256": "2e98bce96186fb8730c7fc109bcc15dd745c056c541c1c5c2b4cd38871cc50bd"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"source": ".qa\\companion-ui-729c8012-e765-4d85-b988-dd9f8e19e1b8\\mobile-original-diff.png",
|
||||||
|
"file": "docs\\companion-c-e-evidence\\final-ui\\mobile-original-diff.png",
|
||||||
|
"bytes": 19793,
|
||||||
|
"sha256": "45c16847826895264565826375041205bf79c897241b857b578f7dc30e35e833"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"source": ".qa\\companion-ui-729c8012-e765-4d85-b988-dd9f8e19e1b8\\mobile-original-report.png",
|
||||||
|
"file": "docs\\companion-c-e-evidence\\final-ui\\mobile-original-report.png",
|
||||||
|
"bytes": 29422,
|
||||||
|
"sha256": "ff06860dcaee104921ffac1e3bd7644a36d08d0598f97567e31e8c8090a4bb48"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"source": ".qa\\companion-ui-729c8012-e765-4d85-b988-dd9f8e19e1b8\\mobile-revoked.png",
|
||||||
|
"file": "docs\\companion-c-e-evidence\\final-ui\\mobile-revoked.png",
|
||||||
|
"bytes": 36012,
|
||||||
|
"sha256": "289e7d8ccdba182d5b1dd541935c1e75d1922ff18d89b3edc8f678038c2b77e4"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"source": ".qa\\companion-ui-729c8012-e765-4d85-b988-dd9f8e19e1b8\\mobile-task-list.png",
|
||||||
|
"file": "docs\\companion-c-e-evidence\\final-ui\\mobile-task-list.png",
|
||||||
|
"bytes": 22202,
|
||||||
|
"sha256": "d1fcf3cb24ebb5cfabf79a23bf6817dd3e3df627bb1e9c16eaca47dd91da7ca7"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"source": ".qa\\companion-ui-729c8012-e765-4d85-b988-dd9f8e19e1b8\\result.json",
|
||||||
|
"file": "docs\\companion-c-e-evidence\\final-ui\\result.json",
|
||||||
|
"bytes": 2504,
|
||||||
|
"sha256": "696166e34dc02faac22b942375abc5534c6d3395066884e011f1a4636c386e36"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"source": ".qa\\companion-ui-729c8012-e765-4d85-b988-dd9f8e19e1b8\\tablet-task-list.png",
|
||||||
|
"file": "docs\\companion-c-e-evidence\\final-ui\\tablet-task-list.png",
|
||||||
|
"bytes": 25003,
|
||||||
|
"sha256": "ff9a4f8ef3b39bc360be068b81210c8ae67e457d481bbe7e82663cfdaf2acc8c"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
After Width: | Height: | Size: 170 KiB |
|
After Width: | Height: | Size: 171 KiB |
|
After Width: | Height: | Size: 160 KiB |
|
After Width: | Height: | Size: 48 KiB |
|
After Width: | Height: | Size: 88 KiB |
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 22 KiB |
@@ -0,0 +1,21 @@
|
|||||||
|
{
|
||||||
|
"success": false,
|
||||||
|
"error": "先应用或撤回本任务的待审查改动,再检查实际工程。",
|
||||||
|
"stack": "Error: 先应用或撤回本任务的待审查改动,再检查实际工程。\n at Object.api (file:///D:/Ai-project/REA%E9%80%86%E5%90%91/Agent-Workbench/tests/helpers.mjs:107:43)\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-companion-ui.mjs:89:64",
|
||||||
|
"passed": [
|
||||||
|
"desktop explicitly enables HTTPS and downloads the actual public CA without changing OS trust",
|
||||||
|
"390px real gateway pairing clears fragment, displays scoped task list and registers the same device in desktop",
|
||||||
|
"phone UI confirms original Task/Run approval and the existing Runtime executes one command"
|
||||||
|
],
|
||||||
|
"screenshots": [
|
||||||
|
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\companion-ui-74084878-28df-45f6-8f42-25ab09a68ee0\\desktop-certificate.png",
|
||||||
|
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\companion-ui-74084878-28df-45f6-8f42-25ab09a68ee0\\desktop-pairing.png",
|
||||||
|
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\companion-ui-74084878-28df-45f6-8f42-25ab09a68ee0\\mobile-task-list.png",
|
||||||
|
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\companion-ui-74084878-28df-45f6-8f42-25ab09a68ee0\\mobile-original-approval.png",
|
||||||
|
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\companion-ui-74084878-28df-45f6-8f42-25ab09a68ee0\\mobile-original-diff.png",
|
||||||
|
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\companion-ui-74084878-28df-45f6-8f42-25ab09a68ee0\\failure-mobile.png",
|
||||||
|
"D:\\Ai-project\\REA逆向\\Agent-Workbench\\.qa\\companion-ui-74084878-28df-45f6-8f42-25ab09a68ee0\\failure-desktop.png"
|
||||||
|
],
|
||||||
|
"errors": [],
|
||||||
|
"realModelRequests": 0
|
||||||
|
}
|
||||||
@@ -690,3 +690,7 @@ A–E已提交并保留原证据。F源码包必须对实际重新生成的客
|
|||||||
1.16 A/B专项首轮14/16:两项测试夹具问题分别为重启身份回调每次生成新UUID、错误Host测试被Node TLS提前拒绝。修正夹具为固定重启身份、SNI空值仍校验目标IP后16/16通过(.qa/companion-a-b-rerun.tap),含真实DPAPI。关联38项首轮30/38,8项因qrcode CommonJS在ESM bundle中动态require fs失败;补createRequire后36/38,剩余2项热升级处理器唯一定位待修。失败日志独立保留,没有部署正式宿主。
|
1.16 A/B专项首轮14/16:两项测试夹具问题分别为重启身份回调每次生成新UUID、错误Host测试被Node TLS提前拒绝。修正夹具为固定重启身份、SNI空值仍校验目标IP后16/16通过(.qa/companion-a-b-rerun.tap),含真实DPAPI。关联38项首轮30/38,8项因qrcode CommonJS在ESM bundle中动态require fs失败;补createRequire后36/38,剩余2项热升级处理器唯一定位待修。失败日志独立保留,没有部署正式宿主。
|
||||||
|
|
||||||
手机UI结构比较:桌面缩小复制会保留大量编辑区/配置,任务队列→详情能把待审批/unknown/进展放在首屏;多面板仪表盘弱化同一Task归属。选择任务队列与独立详情,保留现有深蓝/冷灰/绿色状态语言,触控至少44px、中文系统字体、安全区、无额外动效。桌面只增加连接管理模态,手机不加载桌面入口或管理令牌。按product-ui-ux/frontend-design完成流程和实际宽窄屏验收。
|
手机UI结构比较:桌面缩小复制会保留大量编辑区/配置,任务队列→详情能把待审批/unknown/进展放在首屏;多面板仪表盘弱化同一Task归属。选择任务队列与独立详情,保留现有深蓝/冷灰/绿色状态语言,触控至少44px、中文系统字体、安全区、无额外动效。桌面只增加连接管理模态,手机不加载桌面入口或管理令牌。按product-ui-ux/frontend-design完成流程和实际宽窄屏验收。
|
||||||
|
|
||||||
|
C实际观察:已查看390px原审批和1440px电脑证书界面,任务归属/原命令/确认动作可读且不横向溢出。工具waiting状态仍为英文,准备补中文;当前网络枚举将vEthernet(WSL)列在以太网之前,默认地址会误导手机连接,准备优先展示非虚拟网卡。手机验证使用自有loopback QA中继,Node对每次真实HTTPS请求校验证书链,未绕过证书错误或改OS信任;明确不代表Safari原生Cookie/证书/PWA通过。
|
||||||
|
|
||||||
|
D/E新增真实Runtime四项通过:原命令只执行一次且迟到桌面审批拒绝;桌面拒绝赢得竞争不执行命令;手机停止等待原进程关闭且后续心跳不增长;stopParent等待期间换Run拒绝。首轮新增22项为21/22,差异工件夹具未登记原Task/Run被Store归属守卫拒绝;修正为实际createTask/createRun登记后专项通过。C首轮在命令开始执行后就准备检查,正常返回409;脚本改等原任务needs_review/completed,保留原失败和截图。一次猜测demo.mjs只读失败,实际离线脚本位于provider.mjs。
|
||||||
|
|||||||
@@ -0,0 +1,2 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="zh-CN"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" /><meta name="theme-color" content="#172b43" /><meta name="apple-mobile-web-app-capable" content="yes" /><meta name="apple-mobile-web-app-title" content="Workbench" /><link rel="manifest" href="/mobile.webmanifest" /><link rel="icon" type="image/svg+xml" href="/mobile-icon.svg" /><link rel="apple-touch-icon" href="/mobile-touch-icon.png" /><title>Agent Workbench · 手机伴随端</title></head><body><div id="mobile-root"></div><script type="module" src="/src/client/mobile/main.tsx"></script></body></html>
|
||||||
@@ -6,7 +6,7 @@
|
|||||||
"description": "A local coding workbench with explicit tool execution, reviewable changes and recoverable sessions.",
|
"description": "A local coding workbench with explicit tool execution, reviewable changes and recoverable sessions.",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite --host 127.0.0.1",
|
"dev": "vite --host 127.0.0.1",
|
||||||
"build": "tsc --noEmit && vite build && node scripts/build-server.mjs",
|
"build": "tsc --noEmit && vite build && node scripts/build-mobile.mjs && node scripts/build-server.mjs",
|
||||||
"start": "node dist-server/server.mjs",
|
"start": "node dist-server/server.mjs",
|
||||||
"desktop": "powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/Start-Desktop.ps1",
|
"desktop": "powershell.exe -NoProfile -ExecutionPolicy Bypass -File scripts/Start-Desktop.ps1",
|
||||||
"verify:desktop": "node scripts/verify-desktop-window.mjs",
|
"verify:desktop": "node scripts/verify-desktop-window.mjs",
|
||||||
@@ -37,7 +37,8 @@
|
|||||||
"verify:purge-comparison": "node scripts/verify-controlled-projects.mjs --purge-comparison",
|
"verify:purge-comparison": "node scripts/verify-controlled-projects.mjs --purge-comparison",
|
||||||
"verify:desktop-projects": "node scripts/verify-controlled-projects.mjs --desktop",
|
"verify:desktop-projects": "node scripts/verify-controlled-projects.mjs --desktop",
|
||||||
"verify:desktop-lifecycle": "node scripts/verify-controlled-ui.mjs --desktop",
|
"verify:desktop-lifecycle": "node scripts/verify-controlled-ui.mjs --desktop",
|
||||||
"verify:desktop-install": "node scripts/verify-desktop-install.mjs"
|
"verify:desktop-install": "node scripts/verify-desktop-install.mjs",
|
||||||
|
"verify:companion": "node scripts/verify-companion-ui.mjs"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@babel/parser": "7.29.11",
|
"@babel/parser": "7.29.11",
|
||||||
|
|||||||
@@ -762,3 +762,7 @@ F最终说明包首次全字节对照拒绝REA运行清单的builtAt时间变化
|
|||||||
A/B完成:16新增专项与38项API/桌面/Runtime/升级关联合并54/54通过,失败日志和最终原TAP封存在docs/companion-a-b-evidence。新增网关变量撞到旧管理处理器Debugger定位字符串,改为mobileUrl保持原定位契约,直接启动和旧0.1宿主连续升级通过。TLS套接字登记补充close清理和10秒握手超时。C界面已写入但尚未验收。一次状态补丁因计划原句不完全一致整批拒绝,无写入;读取原句后正确应用。
|
A/B完成:16新增专项与38项API/桌面/Runtime/升级关联合并54/54通过,失败日志和最终原TAP封存在docs/companion-a-b-evidence。新增网关变量撞到旧管理处理器Debugger定位字符串,改为mobileUrl保持原定位契约,直接启动和旧0.1宿主连续升级通过。TLS套接字登记补充close清理和10秒握手超时。C界面已写入但尚未验收。一次状态补丁因计划原句不完全一致整批拒绝,无写入;读取原句后正确应用。
|
||||||
|
|
||||||
A/B封存检查发现原失败TAP保留了空白行缩进,git diff --check据此报空格;不重写原日志。按仓库既有证据策略将这一目录的TAP标记binary,保留原字节,再做代码/文档检查。原失败和该检查结果已记录。
|
A/B封存检查发现原失败TAP保留了空白行缩进,git diff --check据此报空格;不重写原日志。按仓库既有证据策略将这一目录的TAP标记binary,保留原字节,再做代码/文档检查。原失败和该检查结果已记录。
|
||||||
|
|
||||||
|
C第三次7组实际界面通过(.qa/companion-ui-3318eab2-6aa7-4de1-9cfd-fb6020c9c3d6):桌面开启/证书下载、390px配对/原审批、原差异/实测1项工程检查/报告SHA、断线重连/刷新不重放、壳缓存不含API、768px/窄管理页、设备撤销清空手机数据。第二次失败是夹具未应用待审查改动就运行工程检查,被正确409拒绝;增加明确在原自有工程应用后才检查。实际界面观察后继续修正:优先非虚拟网卡、waiting中文、任务全文折叠、操作请求ID在确认期间稳定、未知回执跨刷新保留。新增修正后还需复验,第三次结果不当作最终新代码通过。窄屏管理和文档全页截图含滚动位置,截图助手改对原生dialog拍实际视口、管理页先回顶部;原截图保持。
|
||||||
|
|
||||||
|
C–E本地最终:24/24专项、7组真实Edge界面通过,最终原证据封存docs/companion-c-e-evidence;A/B提交dfe2e40保持。已实际查看最终原审批/报告/窄管理截图。iPhone原生证书/cookie/PWA与切网后台未验证,C/E标本地完成但设备待验;准备F全量回归与独立实机候选,不影响正式4318。QA Python发现desktop-python无pytest,改用已有python-qa-1.7.0(3.12.10/pytest8.4.2),不安装或修改原Python。探索rg传通配文件到Windows路径报错,后续改用目录+glob。
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 192 192"><rect width="192" height="192" rx="36" fill="#172b43"/><path d="M42 55h108v82H42z" fill="none" stroke="#f3f6fa" stroke-width="9"/><path d="m60 78 16 18-16 18m32 0h35" fill="none" stroke="#8bd0b9" stroke-width="9" stroke-linecap="square"/></svg>
|
||||||
|
After Width: | Height: | Size: 307 B |
@@ -0,0 +1 @@
|
|||||||
|
{"id":"/","name":"Agent Workbench 手机伴随端","short_name":"Workbench","lang":"zh-CN","start_url":"/","scope":"/","display":"standalone","background_color":"#f1f4f7","theme_color":"#172b43","icons":[{"src":"/mobile-icon.svg","sizes":"any","type":"image/svg+xml","purpose":"any"},{"src":"/mobile-touch-icon.png","sizes":"256x256","type":"image/png","purpose":"any"}]}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
import fs from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { createHash } from 'node:crypto';
|
||||||
|
|
||||||
|
// Vite's dependency graph defines the complete mobile allowlist. Desktop
|
||||||
|
// entries, arbitrary files and future chunks are not implicitly exposed.
|
||||||
|
const root = path.resolve('dist-client'), manifest = JSON.parse(fs.readFileSync(path.join(root, '.vite/manifest.json'), 'utf8'));
|
||||||
|
const seen = new Set(), assets = new Set();
|
||||||
|
function visit(name) {
|
||||||
|
if (seen.has(name)) return; seen.add(name);
|
||||||
|
const entry = manifest[name]; if (!entry) throw new Error('Mobile build dependency is missing: ' + name);
|
||||||
|
for (const file of [entry.file, ...(entry.css ?? []), ...(entry.assets ?? [])]) {
|
||||||
|
if (!/^assets\/[A-Za-z0-9_.-]+\.(js|css)$/.test(file)) throw new Error('Unexpected mobile asset: ' + file);
|
||||||
|
if (!fs.statSync(path.join(root, file)).isFile()) throw new Error('Mobile asset is not a file: ' + file);
|
||||||
|
assets.add('/' + file);
|
||||||
|
}
|
||||||
|
for (const imported of [...(entry.imports ?? []), ...(entry.dynamicImports ?? [])]) visit(imported);
|
||||||
|
}
|
||||||
|
visit('mobile.html');
|
||||||
|
const list = [...assets].sort();
|
||||||
|
fs.writeFileSync(path.join(root, 'mobile-assets.json'), JSON.stringify(list, null, 2) + '\n');
|
||||||
|
// Reuse our existing raster mark for iPhone's home-screen icon; no generated
|
||||||
|
// media or network dependency is needed for this product asset.
|
||||||
|
const icon = fs.readFileSync(path.join(root, 'workbench-icon.png'));
|
||||||
|
fs.writeFileSync(path.join(root, 'mobile-touch-icon.png'), icon);
|
||||||
|
const version = createHash('sha256').update(fs.readFileSync(path.join(root, 'mobile.html'))).update(JSON.stringify(list)).digest('hex').slice(0, 20);
|
||||||
|
const files = ['/', '/mobile.webmanifest', '/mobile-icon.svg', '/mobile-touch-icon.png', ...list];
|
||||||
|
const worker = `const CACHE = 'workbench-mobile-${version}';
|
||||||
|
const FILES = ${JSON.stringify(files)};
|
||||||
|
self.addEventListener('install', event => event.waitUntil(caches.open(CACHE).then(cache => cache.addAll(FILES)).then(() => self.skipWaiting())));
|
||||||
|
self.addEventListener('activate', event => event.waitUntil(caches.keys().then(names => Promise.all(names.filter(name => name.startsWith('workbench-mobile-') && name !== CACHE).map(name => caches.delete(name)))).then(() => self.clients.claim())));
|
||||||
|
self.addEventListener('fetch', event => {
|
||||||
|
const url = new URL(event.request.url);
|
||||||
|
if (event.request.method !== 'GET' || url.origin !== self.location.origin || url.search || !FILES.includes(url.pathname)) return;
|
||||||
|
event.respondWith(fetch(event.request).then(response => {
|
||||||
|
if (response.ok) { const copy = response.clone(); event.waitUntil(caches.open(CACHE).then(cache => cache.put(event.request, copy))); }
|
||||||
|
return response;
|
||||||
|
}).catch(async () => (await caches.match(event.request)) || Response.error()));
|
||||||
|
});
|
||||||
|
`;
|
||||||
|
fs.writeFileSync(path.join(root, 'mobile-sw.js'), worker);
|
||||||
|
console.log('Mobile shell built: ' + list.length + ' allowed assets; API and project data are never cached.');
|
||||||
@@ -0,0 +1,128 @@
|
|||||||
|
import fs from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
import http from 'node:http';
|
||||||
|
import https from 'node:https';
|
||||||
|
import { X509Certificate, randomUUID } from 'node:crypto';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { chromium, expect } from 'playwright/test';
|
||||||
|
import { fixture, launchWorkbench, until } from '../tests/helpers.mjs';
|
||||||
|
|
||||||
|
if (process.argv.includes('--help')) { console.log('node scripts/verify-companion-ui.mjs - isolated desktop and mobile UI via a loopback QA relay that verifies the actual gateway CA; does not modify certificate trust or substitute for iPhone Safari acceptance.'); process.exit(0); }
|
||||||
|
if (process.argv.length > 2) throw new Error('Unsupported arguments.');
|
||||||
|
const directory = path.resolve('.qa', 'companion-ui-' + randomUUID()); fs.mkdirSync(directory, { recursive: true });
|
||||||
|
const disposers = [], t = { after: action => disposers.push(action) }, f = fixture(t);
|
||||||
|
fs.writeFileSync(path.join(f.projectRoot, 'package.json'), JSON.stringify({ name: 'owned-companion-ui', private: true, type: 'module', scripts: { test: 'node --test fixture.test.mjs' } }));
|
||||||
|
fs.writeFileSync(path.join(f.projectRoot, 'fixture.test.mjs'), "import test from 'node:test';import assert from 'node:assert/strict';test('owned mobile fixture',()=>assert.equal(1+1,2));\n");
|
||||||
|
f.store.close();
|
||||||
|
const host = await launchWorkbench(t, f.data, { Path: path.dirname(process.execPath) + path.delimiter + process.env.Path });
|
||||||
|
await host.api('/sessions/' + f.session.id + '/messages', { content: '手机伴随端验收:读取项目、准备原差异并等待手机审批。明确为本地离线夹具。' });
|
||||||
|
await until(async () => (await host.api('/sessions/' + f.session.id)).status === 'awaiting_approval');
|
||||||
|
const before = await host.api('/sessions/' + f.session.id), browser = await chromium.launch({ channel: 'msedge', headless: true });
|
||||||
|
const desktop = await browser.newPage({ viewport: { width: 1440, height: 1000 } }), errors = [], passed = [], screenshots = [];
|
||||||
|
desktop.on('pageerror', error => errors.push(error.message));
|
||||||
|
const mark = text => { passed.push(text); console.log('PASS ' + text); };
|
||||||
|
async function shot(page, name) { const file = path.join(directory, name + '.png'); await page.screenshot({ path: file, fullPage: !(await page.locator(':modal').count()) }); screenshots.push(file); }
|
||||||
|
let mobile, relay, gatewayStatus, cookie = '', disconnected = false;
|
||||||
|
try {
|
||||||
|
await desktop.addInitScript(({ projectId, sessionId }) => { localStorage.setItem('awb-project', projectId); localStorage.setItem('awb-session', sessionId); }, { projectId: f.project.id, sessionId: f.session.id });
|
||||||
|
await desktop.goto(host.url); await desktop.getByRole('button', { name: '手机连接', exact: true }).click();
|
||||||
|
const panel = desktop.getByRole('dialog', { name: '手机连接', exact: true }); await expect(panel).toBeVisible();
|
||||||
|
await expect(panel).toContainText('默认关闭');
|
||||||
|
const initial = await host.api('/companion'); assert.ok(initial.addresses.length, 'Requires an actual owned private IPv4 interface.');
|
||||||
|
const reservation = http.createServer(); await new Promise(resolve => reservation.listen(0, initial.addresses[0].address, resolve));
|
||||||
|
const port = reservation.address().port; await new Promise(resolve => reservation.close(resolve));
|
||||||
|
await panel.getByLabel('手机连接端口', { exact: true }).fill(String(port));
|
||||||
|
await panel.getByRole('button', { name: '开启 HTTPS', exact: true }).click();
|
||||||
|
await expect(panel).toContainText('手机连接已开启', { timeout: 20000 });
|
||||||
|
await expect(panel).toContainText('证书信任设置'); await shot(desktop, 'desktop-certificate');
|
||||||
|
const downloadEvent = desktop.waitForEvent('download'); await panel.getByRole('button', { name: '下载手机根证书', exact: true }).click();
|
||||||
|
const download = await downloadEvent, certFile = path.join(directory, 'fixture-mobile-ca.cer'); await download.saveAs(certFile);
|
||||||
|
const ca = new X509Certificate(fs.readFileSync(certFile)).toString();
|
||||||
|
assert.equal(new X509Certificate(ca).ca, true); mark('desktop explicitly enables HTTPS and downloads the actual public CA without changing OS trust');
|
||||||
|
await panel.getByLabel('允许审批命令', { exact: true }).check(); await panel.getByLabel('允许停止任务', { exact: true }).check();
|
||||||
|
await panel.getByRole('button', { name: '生成一次性配对码', exact: true }).click(); await expect(panel.getByAltText('手机一次性配对二维码')).toBeVisible();
|
||||||
|
const pairUrl = await panel.locator('.companion-pair-url').textContent(); await shot(desktop, 'desktop-pairing');
|
||||||
|
gatewayStatus = await host.api('/companion');
|
||||||
|
// Browser rendering uses an owned loopback relay because this test must not
|
||||||
|
// silently install a root or bypass a TLS warning. The relay verifies the
|
||||||
|
// real gateway certificate for every request and holds only its fixture
|
||||||
|
// Secure cookie in memory. Native Safari cookie/trust/PWA remains device QA.
|
||||||
|
const target = new URL(gatewayStatus.origin);
|
||||||
|
relay = http.createServer((request, response) => {
|
||||||
|
if (disconnected && request.url.startsWith('/mobile-api/')) { response.writeHead(503, { 'Content-Type': 'application/json' }); response.end(JSON.stringify({ error: '自有断线夹具' })); return; }
|
||||||
|
const headers = { Host: target.host, Origin: target.origin, Connection: 'close', ...(cookie ? { Cookie: cookie } : {}),
|
||||||
|
...(request.headers['content-type'] ? { 'Content-Type': request.headers['content-type'] } : {}) };
|
||||||
|
const forwarded = https.request(new URL(request.url, target), { method: request.method, headers, ca, servername: '' }, incoming => {
|
||||||
|
const set = incoming.headers['set-cookie']; if (set?.length) cookie = set[0].split(';')[0];
|
||||||
|
const outgoing = { ...incoming.headers }; delete outgoing['set-cookie']; response.writeHead(incoming.statusCode, outgoing); incoming.pipe(response);
|
||||||
|
});
|
||||||
|
forwarded.on('error', () => { if (!response.headersSent) { response.writeHead(503, { 'Content-Type': 'application/json' }); response.end(JSON.stringify({ error: '自有TLS转发中断' })); } else response.destroy(); });
|
||||||
|
request.pipe(forwarded);
|
||||||
|
});
|
||||||
|
await new Promise(resolve => relay.listen(0, '127.0.0.1', resolve));
|
||||||
|
const relayUrl = 'http://127.0.0.1:' + relay.address().port;
|
||||||
|
const mobileContext = await browser.newContext({ viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true });
|
||||||
|
mobile = await mobileContext.newPage(); mobile.on('pageerror', error => errors.push(error.message));
|
||||||
|
await mobile.goto(relayUrl + '/#pair=' + new URLSearchParams(new URL(pairUrl).hash.slice(1)).get('pair'));
|
||||||
|
await expect(mobile.getByRole('heading', { name: '接续电脑上的任务', exact: true })).toBeVisible();
|
||||||
|
assert.equal(new URL(mobile.url()).hash, '');
|
||||||
|
await mobile.getByLabel('设备名称', { exact: true }).fill('验收 iPhone 观察窗口');
|
||||||
|
await mobile.getByRole('button', { name: '连接这台电脑', exact: true }).click();
|
||||||
|
await expect(mobile.getByRole('heading', { name: '项目任务', exact: true })).toBeVisible(); await shot(mobile, 'mobile-task-list');
|
||||||
|
await expect(panel).toContainText('验收 iPhone 观察窗口', { timeout: 10000 });
|
||||||
|
mark('390px real gateway pairing clears fragment, displays scoped task list and registers the same device in desktop');
|
||||||
|
await mobile.locator('.mobile-task-row').filter({ hasText: before.title }).click();
|
||||||
|
await expect(mobile.getByRole('heading', { name: '等待你的确认', exact: true })).toBeVisible();
|
||||||
|
await mobile.getByText('原任务与运行', { exact: true }).click(); await expect(mobile.locator('.mobile-task-title code')).toContainText(before.taskId);
|
||||||
|
assert.ok(await mobile.locator('body').evaluate(body => body.scrollWidth <= innerWidth)); await shot(mobile, 'mobile-original-approval');
|
||||||
|
await mobile.getByRole('button', { name: '核对并批准', exact: true }).click();
|
||||||
|
const confirmation = mobile.getByRole('dialog'); await expect(confirmation).toContainText(before.runId);
|
||||||
|
await confirmation.getByRole('button', { name: '确认', exact: true }).click();
|
||||||
|
await until(async () => ['needs_review', 'completed'].includes((await host.api('/sessions/' + f.session.id)).status));
|
||||||
|
await expect(mobile.locator('.mobile-receipt')).toContainText('已批准原请求');
|
||||||
|
const after = await host.api('/sessions/' + f.session.id); assert.equal(after.taskId, before.taskId); assert.equal(after.runId, before.runId);
|
||||||
|
assert.equal(after.events.filter(item => item.tool === 'run_command').length, 1); mark('phone UI confirms original Task/Run approval and the existing Runtime executes one command');
|
||||||
|
await mobile.getByRole('button', { name: /^文件差异/ }).click();
|
||||||
|
await mobile.getByRole('button', { name: /WORKBENCH-NOTES.md/ }).click(); await expect(mobile.getByRole('dialog')).toContainText('SHA-256 已核对');
|
||||||
|
await shot(mobile, 'mobile-original-diff'); await mobile.getByRole('button', { name: '返回任务', exact: true }).click();
|
||||||
|
await host.api('/sessions/' + f.session.id + '/changes/' + after.changes.at(-1).id + '/apply', {});
|
||||||
|
assert.equal(fs.existsSync(path.join(f.projectRoot, 'WORKBENCH-NOTES.md')), true);
|
||||||
|
await host.api('/sessions/' + f.session.id + '/check-plans', { names: ['test'] });
|
||||||
|
const planned = await host.api('/sessions/' + f.session.id); await host.api('/sessions/' + f.session.id + '/check-jobs', { planId: planned.execution.plans.at(-1).id });
|
||||||
|
await until(async () => ['passed', 'failed', 'unverified'].includes((await host.api('/sessions/' + f.session.id)).execution.checks.at(-1)?.status), 30000);
|
||||||
|
const checked = await host.api('/sessions/' + f.session.id); assert.equal(checked.execution.checks.at(-1).status, 'passed');
|
||||||
|
await host.api('/sessions/' + f.session.id + '/delivery-reports', {});
|
||||||
|
await mobile.getByRole('button', { name: '检查与报告', exact: true }).click();
|
||||||
|
await expect(mobile.locator('.mobile-checks')).toContainText('通过', { timeout: 12000 });
|
||||||
|
await mobile.getByRole('button', { name: /^交付报告 [\d,]+ bytes/ }).click(); await expect(mobile.getByRole('dialog')).toContainText('SHA-256 已核对');
|
||||||
|
await shot(mobile, 'mobile-original-report'); await mobile.getByRole('button', { name: '返回任务', exact: true }).click();
|
||||||
|
mark('original paginated diff and counted check/report display verified content from the same Task');
|
||||||
|
disconnected = true; await mobile.getByRole('button', { name: '刷新任务', exact: true }).click();
|
||||||
|
await expect(mobile.locator('.mobile-connection')).toContainText('连接中断'); await shot(mobile, 'mobile-disconnected');
|
||||||
|
disconnected = false; await mobile.getByRole('button', { name: '重新同步', exact: true }).click(); await expect(mobile.locator('.mobile-connection')).toContainText('已同步');
|
||||||
|
assert.equal((await host.api('/sessions/' + f.session.id)).events.filter(item => item.tool === 'run_command').length, 1);
|
||||||
|
await mobile.reload(); await expect(mobile.getByRole('heading', { name: '项目任务', exact: true })).toBeVisible();
|
||||||
|
mark('disconnect and refresh recover from persistent seq without submitting a new command or Run');
|
||||||
|
const cacheEntries = await mobile.evaluate(async () => { const names = await caches.keys(); return (await Promise.all(names.map(async name => (await (await caches.open(name)).keys()).map(request => new URL(request.url).pathname)))).flat(); });
|
||||||
|
assert.ok(cacheEntries.length > 0 && cacheEntries.every(route => !route.startsWith('/mobile-api/'))); mark('PWA service worker stores the shell and no API/project response');
|
||||||
|
await mobile.setViewportSize({ width: 768, height: 1024 }); await shot(mobile, 'tablet-task-list');
|
||||||
|
await desktop.setViewportSize({ width: 390, height: 844 }); await panel.evaluate(node => { node.scrollTop = 0; }); await shot(desktop, 'desktop-management-narrow');
|
||||||
|
assert.ok(await desktop.locator('body').evaluate(body => body.scrollWidth <= innerWidth));
|
||||||
|
await panel.getByRole('button', { name: '撤销', exact: true }).click();
|
||||||
|
await mobile.getByRole('button', { name: '刷新任务', exact: true }).click(); await expect(mobile.getByRole('heading', { name: '接续电脑上的任务', exact: true })).toBeVisible();
|
||||||
|
await expect(mobile.locator('.mobile-task-row')).toHaveCount(0); await shot(mobile, 'mobile-revoked');
|
||||||
|
assert.equal((await host.api('/sessions/' + f.session.id)).events.filter(item => item.tool === 'run_command').length, 1);
|
||||||
|
mark('desktop revocation removes mobile project content immediately on the next read while preserving the original completed tool');
|
||||||
|
assert.deepEqual(errors, []);
|
||||||
|
const result = { success: true, passed, screenshots, errors, viewports: [1440, 390, 768], browser: 'Microsoft Edge via Playwright; owned loopback QA relay with actual CA verification',
|
||||||
|
nativeSafariTrustCookiePWA: 'pending-real-iPhone', osTrustChanged: false, certificateWarningsBypassed: false, realModelRequests: 0, taskId: before.taskId, runId: before.runId };
|
||||||
|
fs.writeFileSync(path.join(directory, 'result.json'), JSON.stringify(result, null, 2));
|
||||||
|
} catch (error) {
|
||||||
|
if (mobile) await shot(mobile, 'failure-mobile').catch(() => {}); await shot(desktop, 'failure-desktop').catch(() => {});
|
||||||
|
fs.writeFileSync(path.join(directory, 'result.json'), JSON.stringify({ success: false, error: error.message, stack: error.stack, passed, screenshots, errors, realModelRequests: 0 }, null, 2)); throw error;
|
||||||
|
} finally {
|
||||||
|
console.log('EVIDENCE ' + directory); await browser.close();
|
||||||
|
if (relay) await new Promise(resolve => { relay.closeAllConnections(); relay.close(resolve); });
|
||||||
|
await host.api('/companion/close', {}).catch(() => {});
|
||||||
|
for (const dispose of disposers.reverse()) await dispose();
|
||||||
|
}
|
||||||
@@ -15,6 +15,7 @@ import { SkillCenter } from './SkillCenter';
|
|||||||
import { McpPanel } from './McpPanel';
|
import { McpPanel } from './McpPanel';
|
||||||
import { WorkerPanel } from './WorkerPanel';
|
import { WorkerPanel } from './WorkerPanel';
|
||||||
import { DesktopPanel } from './DesktopPanel';
|
import { DesktopPanel } from './DesktopPanel';
|
||||||
|
import { CompanionPanel } from './CompanionPanel';
|
||||||
import { desktop } from './desktop';
|
import { desktop } from './desktop';
|
||||||
|
|
||||||
const activeStates = ['running', 'awaiting_approval', 'stopping'];
|
const activeStates = ['running', 'awaiting_approval', 'stopping'];
|
||||||
@@ -78,6 +79,7 @@ export default function App() {
|
|||||||
const [mcpOpen, setMcpOpen] = useState(false);
|
const [mcpOpen, setMcpOpen] = useState(false);
|
||||||
const [workersOpen, setWorkersOpen] = useState(false);
|
const [workersOpen, setWorkersOpen] = useState(false);
|
||||||
const [desktopOpen, setDesktopOpen] = useState(false);
|
const [desktopOpen, setDesktopOpen] = useState(false);
|
||||||
|
const [companionOpen, setCompanionOpen] = useState(false);
|
||||||
const [pickingProject, setPickingProject] = useState(false);
|
const [pickingProject, setPickingProject] = useState(false);
|
||||||
const [researchDocs, setResearchDocs] = useState<ResearchDoc[]>([]);
|
const [researchDocs, setResearchDocs] = useState<ResearchDoc[]>([]);
|
||||||
const [report, setReport] = useState<{ title: string; content: string } | null>(null);
|
const [report, setReport] = useState<{ title: string; content: string } | null>(null);
|
||||||
@@ -534,7 +536,7 @@ export default function App() {
|
|||||||
</aside>
|
</aside>
|
||||||
<main className="task-pane">
|
<main className="task-pane">
|
||||||
<header className="work-header"><div className="work-title">{(!sidebarOpen || mobile) && <IconButton label="展开项目栏" onClick={() => setSidebarOpen(true)}><PanelLeftOpen size={18} /></IconButton>}<span className="header-symbol"><Code2 size={17} /></span><div><span className="header-breadcrumb">{selectedProject?.name || '工作空间'} <ChevronRight size={12} /> 任务</span><h1>{session?.title || '让任务走到完成'}</h1></div></div>
|
<header className="work-header"><div className="work-title">{(!sidebarOpen || mobile) && <IconButton label="展开项目栏" onClick={() => setSidebarOpen(true)}><PanelLeftOpen size={18} /></IconButton>}<span className="header-symbol"><Code2 size={17} /></span><div><span className="header-breadcrumb">{selectedProject?.name || '工作空间'} <ChevronRight size={12} /> 任务</span><h1>{session?.title || '让任务走到完成'}</h1></div></div>
|
||||||
<div className="model-launch">{desktop && <button className="button secondary desktop-launch" onClick={() => setDesktopOpen(true)} aria-label="桌面宿主"><SquareTerminal size={16} /><span>桌面宿主</span></button>}<button className="button secondary" onClick={() => setModelCenterOpen(true)} aria-label="打开模型中心"><ModelServer size={16} /><span>模型中心</span></button><button className={'model-button ' + (config.mode === 'demo' ? 'demo' : '')} onClick={openSettings}><span className="model-light" />{config.mode === 'demo' ? '离线演示' : config.model || '选择模型'}<ChevronDown size={13} /></button></div>
|
<div className="model-launch"><button className="button secondary" onClick={() => setCompanionOpen(true)} aria-label="手机连接"><Link2 size={16} /><span>手机连接</span></button>{desktop && <button className="button secondary desktop-launch" onClick={() => setDesktopOpen(true)} aria-label="桌面宿主"><SquareTerminal size={16} /><span>桌面宿主</span></button>}<button className="button secondary" onClick={() => setModelCenterOpen(true)} aria-label="打开模型中心"><ModelServer size={16} /><span>模型中心</span></button><button className={'model-button ' + (config.mode === 'demo' ? 'demo' : '')} onClick={openSettings}><span className="model-light" />{config.mode === 'demo' ? '离线演示' : config.model || '选择模型'}<ChevronDown size={13} /></button></div>
|
||||||
</header>
|
</header>
|
||||||
<div className="task-toolbar"><span className="task-local"><GitBranch size={13} />本地项目</span>{session ? <Status value={session.status} /> : <span className="subtle">等待新任务</span>}<div className="toolbar-actions">
|
<div className="task-toolbar"><span className="task-local"><GitBranch size={13} />本地项目</span>{session ? <Status value={session.status} /> : <span className="subtle">等待新任务</span>}<div className="toolbar-actions">
|
||||||
<IconButton label="运行诊断" onClick={() => openDiagnostics()}><Activity size={15} /></IconButton>
|
<IconButton label="运行诊断" onClick={() => openDiagnostics()}><Activity size={15} /></IconButton>
|
||||||
@@ -577,6 +579,7 @@ export default function App() {
|
|||||||
<div className="inspector-footer"><ShieldCheck size={13} /><span>{tab === 'changes' ? '应用前会核对文件基线' : tab === 'trace' ? '中断调用保留待核实状态' : tab === 'task' ? '任务目标、检查与结果持久保存' : tab === 'index' ? '结果绑定当前项目及文件 SHA256' : '读取范围限定在当前项目'}</span></div>
|
<div className="inspector-footer"><ShieldCheck size={13} /><span>{tab === 'changes' ? '应用前会核对文件基线' : tab === 'trace' ? '中断调用保留待核实状态' : tab === 'task' ? '任务目标、检查与结果持久保存' : tab === 'index' ? '结果绑定当前项目及文件 SHA256' : '读取范围限定在当前项目'}</span></div>
|
||||||
</aside>
|
</aside>
|
||||||
{projectOpen && <Modal title="打开项目" description="选择要在本机读取和开发的项目文件夹。" onClose={() => setProjectOpen(false)}><form onSubmit={event => { event.preventDefault(); openProject(); }}><label className="form-field">项目文件夹<input autoFocus value={projectInput} onChange={event => setProjectInput(event.target.value)} placeholder="C:\Projects\my-app" aria-label="项目文件夹路径" /></label><div className="modal-actions">{desktop && <button type="button" className="button secondary" disabled={pickingProject} onClick={() => void pickDesktopProject()}>选择文件夹</button>}{exampleId && <button type="button" className="button secondary" onClick={() => { chooseProject(exampleId); setProjectOpen(false); }}>打开示例项目</button>}<button type="submit" className="button primary" disabled={!projectInput.trim()}><FolderOpen size={15} />打开项目</button></div></form></Modal>}
|
{projectOpen && <Modal title="打开项目" description="选择要在本机读取和开发的项目文件夹。" onClose={() => setProjectOpen(false)}><form onSubmit={event => { event.preventDefault(); openProject(); }}><label className="form-field">项目文件夹<input autoFocus value={projectInput} onChange={event => setProjectInput(event.target.value)} placeholder="C:\Projects\my-app" aria-label="项目文件夹路径" /></label><div className="modal-actions">{desktop && <button type="button" className="button secondary" disabled={pickingProject} onClick={() => void pickDesktopProject()}>选择文件夹</button>}{exampleId && <button type="button" className="button secondary" onClick={() => { chooseProject(exampleId); setProjectOpen(false); }}>打开示例项目</button>}<button type="submit" className="button primary" disabled={!projectInput.trim()}><FolderOpen size={15} />打开项目</button></div></form></Modal>}
|
||||||
|
{companionOpen && <Modal title="手机连接" description="指定项目和权限,连接到同一个Windows执行宿主。" onClose={() => setCompanionOpen(false)} wide><CompanionPanel projects={projects} selectedProjectId={selectedProject?.id ?? ''} /></Modal>}
|
||||||
{desktopOpen && desktop && <Modal title="桌面与后台任务" description="当前窗口连接同一个本机执行宿主。" onClose={() => setDesktopOpen(false)}><DesktopPanel project={selectedProject} session={session} file={openFile} onProject={acceptDesktopProject} onReview={scope => { if (selectedProjectRef.current === scope.projectId && selectedSessionRef.current === scope.sessionId && selectedTaskRef.current === scope.taskId) { setDesktopOpen(false); showInspector('task'); } }} /></Modal>}
|
{desktopOpen && desktop && <Modal title="桌面与后台任务" description="当前窗口连接同一个本机执行宿主。" onClose={() => setDesktopOpen(false)}><DesktopPanel project={selectedProject} session={session} file={openFile} onProject={acceptDesktopProject} onReview={scope => { if (selectedProjectRef.current === scope.projectId && selectedSessionRef.current === scope.sessionId && selectedTaskRef.current === scope.taskId) { setDesktopOpen(false); showInspector('task'); } }} /></Modal>}
|
||||||
{settingsOpen && <Modal title="模型连接" description="同一套项目工具,可以使用离线演示或你自己的模型服务。" onClose={() => setSettingsOpen(false)}><form onSubmit={event => { event.preventDefault(); saveSettings(); }}><div className="mode-picker"><button type="button" className={settings.mode === 'demo' ? 'selected' : ''} onClick={() => setSettings(previous => ({ ...previous, mode: 'demo' }))}><Play size={18} /><strong>离线演示</strong><span>固定脚本,真实本地工具</span></button><button type="button" className={settings.mode === 'compatible' ? 'selected' : ''} onClick={() => setSettings(previous => ({ ...previous, mode: 'compatible' }))}><Link2 size={18} /><strong>兼容模型服务</strong><span>使用自己的本地或远程模型</span></button></div>
|
{settingsOpen && <Modal title="模型连接" description="同一套项目工具,可以使用离线演示或你自己的模型服务。" onClose={() => setSettingsOpen(false)}><form onSubmit={event => { event.preventDefault(); saveSettings(); }}><div className="mode-picker"><button type="button" className={settings.mode === 'demo' ? 'selected' : ''} onClick={() => setSettings(previous => ({ ...previous, mode: 'demo' }))}><Play size={18} /><strong>离线演示</strong><span>固定脚本,真实本地工具</span></button><button type="button" className={settings.mode === 'compatible' ? 'selected' : ''} onClick={() => setSettings(previous => ({ ...previous, mode: 'compatible' }))}><Link2 size={18} /><strong>兼容模型服务</strong><span>使用自己的本地或远程模型</span></button></div>
|
||||||
{settings.mode === 'compatible' && <><div className="connection-presets"><button type="button" onClick={() => setSettings(previous => ({ ...previous, baseUrl: 'http://127.0.0.1:11434/v1' }))}>Ollama</button><button type="button" onClick={() => setSettings(previous => ({ ...previous, baseUrl: 'http://127.0.0.1:8000/v1' }))}>vLLM</button><span>Chat Completions 兼容接口</span></div><label className="form-field">接口根地址<input type="url" value={settings.baseUrl} onChange={event => setSettings(previous => ({ ...previous, baseUrl: event.target.value }))} placeholder="http://127.0.0.1:11434/v1" /></label><label className="form-field">API Key(按服务要求填写)<input type="password" autoComplete="off" value={keyValue} onChange={event => { setKeyValue(event.target.value); setClearKey(false); }} placeholder={config.hasKey ? '本次运行已设置,留空保留' : '本地服务可以不填'} /></label><div className="key-note"><span>只在本次服务内存中使用,不写入会话与配置。</span>{config.hasKey && <button type="button" onClick={() => { setClearKey(true); setKeyValue(''); }}>{clearKey ? '保存后清除' : '清除 Key'}</button>}</div><div className="model-field"><label className="form-field">模型名称<input list="model-list" value={settings.model} onChange={event => setSettings(previous => ({ ...previous, model: event.target.value }))} placeholder="例如 qwen3:8b" /><datalist id="model-list">{models.map(model => <option key={model} value={model} />)}</datalist></label><button className="button secondary" type="button" onClick={readModels} disabled={settingsBusy || anyRunning}>{settingsBusy ? <LoaderCircle size={14} className="spin" /> : <Search size={14} />}读取模型列表</button></div><div className="model-test-row"><span>填写服务提供的接口根地址。</span><button type="button" className="button secondary" onClick={testModel} disabled={settingsBusy || anyRunning || !settings.model}><Activity size={14} />验证模型响应</button></div>{modelCheck && <div className={'model-check model-check-' + modelCheck.kind} role="status">{modelCheck.message}</div>}</>}
|
{settings.mode === 'compatible' && <><div className="connection-presets"><button type="button" onClick={() => setSettings(previous => ({ ...previous, baseUrl: 'http://127.0.0.1:11434/v1' }))}>Ollama</button><button type="button" onClick={() => setSettings(previous => ({ ...previous, baseUrl: 'http://127.0.0.1:8000/v1' }))}>vLLM</button><span>Chat Completions 兼容接口</span></div><label className="form-field">接口根地址<input type="url" value={settings.baseUrl} onChange={event => setSettings(previous => ({ ...previous, baseUrl: event.target.value }))} placeholder="http://127.0.0.1:11434/v1" /></label><label className="form-field">API Key(按服务要求填写)<input type="password" autoComplete="off" value={keyValue} onChange={event => { setKeyValue(event.target.value); setClearKey(false); }} placeholder={config.hasKey ? '本次运行已设置,留空保留' : '本地服务可以不填'} /></label><div className="key-note"><span>只在本次服务内存中使用,不写入会话与配置。</span>{config.hasKey && <button type="button" onClick={() => { setClearKey(true); setKeyValue(''); }}>{clearKey ? '保存后清除' : '清除 Key'}</button>}</div><div className="model-field"><label className="form-field">模型名称<input list="model-list" value={settings.model} onChange={event => setSettings(previous => ({ ...previous, model: event.target.value }))} placeholder="例如 qwen3:8b" /><datalist id="model-list">{models.map(model => <option key={model} value={model} />)}</datalist></label><button className="button secondary" type="button" onClick={readModels} disabled={settingsBusy || anyRunning}>{settingsBusy ? <LoaderCircle size={14} className="spin" /> : <Search size={14} />}读取模型列表</button></div><div className="model-test-row"><span>填写服务提供的接口根地址。</span><button type="button" className="button secondary" onClick={testModel} disabled={settingsBusy || anyRunning || !settings.model}><Activity size={14} />验证模型响应</button></div>{modelCheck && <div className={'model-check model-check-' + modelCheck.kind} role="status">{modelCheck.message}</div>}</>}
|
||||||
|
|||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import { useEffect, useRef, useState } from 'react';
|
||||||
|
import { Download, Link2, ShieldCheck, Smartphone, X } from 'lucide-react';
|
||||||
|
import { api, downloadCompanionCertificate } from './api';
|
||||||
|
import type { Project } from './types';
|
||||||
|
import type { CompanionStatus } from './companion-types';
|
||||||
|
import './companion-panel.css';
|
||||||
|
|
||||||
|
export function CompanionPanel({ projects, selectedProjectId }: { projects: Project[]; selectedProjectId: string }) {
|
||||||
|
const [status, setStatus] = useState<CompanionStatus | null>(null), [address, setAddress] = useState(''), [port, setPort] = useState(4319);
|
||||||
|
const [selected, setSelected] = useState<string[]>(selectedProjectId ? [selectedProjectId] : []);
|
||||||
|
const [approve, setApprove] = useState(false), [stop, setStop] = useState(false), [hours, setHours] = useState(24);
|
||||||
|
const [pair, setPair] = useState<{ url: string; qr: string; expiresAt: string } | null>(null), [busy, setBusy] = useState(''), [error, setError] = useState('');
|
||||||
|
const mounted = useRef(true);
|
||||||
|
async function refresh() { const result = await api<CompanionStatus>('/companion'); if (mounted.current) { setStatus(result); setAddress(previous => previous || result.addresses[0]?.address || ''); } }
|
||||||
|
useEffect(() => {
|
||||||
|
mounted.current = true; void refresh().catch(value => { if (mounted.current) setError(value.message); });
|
||||||
|
const timer = setInterval(() => void refresh().catch(() => {}), 5000);
|
||||||
|
return () => { mounted.current = false; clearInterval(timer); };
|
||||||
|
}, []);
|
||||||
|
useEffect(() => { if (!pair) return; const timer = setTimeout(() => setPair(null), Math.max(0, Date.parse(pair.expiresAt) - Date.now())); return () => clearTimeout(timer); }, [pair]);
|
||||||
|
async function act(name: string, action: () => Promise<unknown>) {
|
||||||
|
if (busy) return; setBusy(name); setError('');
|
||||||
|
try { await action(); await refresh(); } catch (value) { if (mounted.current) setError(value instanceof Error ? value.message : '手机连接操作失败。'); }
|
||||||
|
finally { if (mounted.current) setBusy(''); }
|
||||||
|
}
|
||||||
|
return <div className="companion-panel">
|
||||||
|
<div className="companion-heading"><Smartphone size={25} /><div><strong>{status?.enabled ? '手机连接已开启' : '在 iPhone 上接续任务'}</strong><p>同一 Wi-Fi,通过 Safari 查看原任务、确认审批和停止执行。</p></div><span className="companion-state">{status?.enabled ? 'HTTPS' : '默认关闭'}</span></div>
|
||||||
|
{error && <p className="companion-error" role="alert">{error}</p>}
|
||||||
|
<section className="companion-network"><h3>Windows 连接地址</h3>
|
||||||
|
{status?.enabled ? <div className="companion-address"><code>{status.origin}</code><button className="button secondary" disabled={!!busy} onClick={() => void act('close', async () => { await api('/companion/close', {}); setPair(null); })}>关闭手机连接</button></div>
|
||||||
|
: <form onSubmit={event => { event.preventDefault(); void act('start', () => api('/companion/start', { address, port })); }}><label>局域网地址<select aria-label="手机连接地址" value={address} onChange={event => setAddress(event.target.value)}>{!address && <option value="">请选择网络</option>}{status?.addresses.map(item => <option key={item.address} value={item.address}>{item.name} · {item.address}</option>)}</select></label><label>端口<input aria-label="手机连接端口" type="number" min={1024} max={65535} value={port} onChange={event => setPort(Number(event.target.value))} /></label><button className="button primary" disabled={!!busy || !address || !!status?.busy}><Link2 size={15} />{busy === 'start' ? '正在生成证书…' : '开启 HTTPS'}</button></form>}
|
||||||
|
{status && !status.addresses.length && !status.enabled && <p>尚未找到局域网地址。请先让电脑连接 Wi-Fi 或有线局域网,再刷新此窗口。</p>}
|
||||||
|
<p className="companion-note">关闭手机连接后,电脑上的任务继续运行。宿主重启后,需要在这里重新开启。</p>
|
||||||
|
</section>
|
||||||
|
{status?.certificate && <details className="companion-certificate" open={!status.devices.length}><summary><ShieldCheck size={16} />首次连接:在 iPhone 信任证书</summary><ol><li>下载本机根证书,用你自己的文件传输方式保存到 iPhone「文件」,点开安装。</li><li>在 iPhone「设置 → 通用 → VPN 与设备管理」安装此证书描述文件。</li><li>在「设置 → 通用 → 关于本机 → 证书信任设置」开启此根证书的完全信任。</li><li>核对下方证书指纹,然后扫描新的配对码。连接地址发生变化时,在电脑重新开启网关。</li></ol><button className="button secondary" disabled={!!busy} onClick={() => void act('certificate', downloadCompanionCertificate)}><Download size={14} />下载手机根证书</button><code className="companion-fingerprint">SHA-256 {status.certificate.sha256}</code><p className="companion-note">证书到期 {new Date(status.certificate.expiresAt).toLocaleDateString()}。若无法连接,请核对同一 Wi-Fi、访客网络隔离和 Windows 防火墙的当前端口;这里不会修改系统信任或防火墙。</p></details>}
|
||||||
|
<section><h3>连接一台手机</h3><p className="companion-note">仅授予选中项目。配对链接两分钟内有效,用过即失效。</p>
|
||||||
|
<fieldset disabled={!!busy || !status?.enabled}><legend>允许查看的项目</legend><div className="companion-projects">{projects.map(project => <label key={project.id}><input type="checkbox" checked={selected.includes(project.id)} onChange={event => { setPair(null); setSelected(previous => event.target.checked ? [...previous, project.id] : previous.filter(id => id !== project.id)); }} />{project.name}</label>)}</div></fieldset>
|
||||||
|
<div className="companion-grant"><span>观察任务 · 必选</span><label><input type="checkbox" checked={approve} onChange={event => { setApprove(event.target.checked); setPair(null); }} />允许审批命令</label><label><input type="checkbox" checked={stop} onChange={event => { setStop(event.target.checked); setPair(null); }} />允许停止任务</label><label>有效期<select aria-label="手机设备有效期" value={hours} onChange={event => { setHours(Number(event.target.value)); setPair(null); }}><option value={24}>24 小时</option><option value={168}>7 天</option><option value={720}>30 天</option></select></label></div>
|
||||||
|
<button className="button primary" disabled={!!busy || !status?.enabled || !selected.length || selected.length > 16} onClick={() => void act('pair', async () => { const result = await api<{ url: string; qr: string; expiresAt: string }>('/companion/pair', { projectIds: selected, permissions: { observe: true, approve, stop }, expiresInHours: hours }); if (mounted.current) setPair(result); })}>生成一次性配对码</button>
|
||||||
|
{pair && status?.enabled && <div className="companion-pair"><img src={pair.qr} alt="手机一次性配对二维码" width={224} height={224} /><div><strong>使用 iPhone 相机扫描</strong><p>请先完成证书信任。{new Date(pair.expiresAt).toLocaleTimeString()} 失效。</p><p className="companion-pair-url">{pair.url}</p><p>把链接发给自己时,接收者可以取得所选项目权限。完成配对后此链接立即失效。</p></div></div>}
|
||||||
|
</section>
|
||||||
|
<section><h3>已登记设备 <span>{status?.devices.length ?? 0}</span></h3>{!status?.devices.length && <p className="companion-note">配对完成后,设备和授权范围会显示在这里。</p>}{status?.devices.map(device => <div key={device.id} className="companion-device"><Smartphone size={18} /><div><strong>{device.name}</strong><p>{device.projectIds.map(id => projects.find(project => project.id === id)?.name ?? '原项目').join('、')} · {device.permissions.approve ? '可审批' : '观察'}{device.permissions.stop ? ' · 可停止' : ''}</p><small>{({ active: '已授权', revoked: '已撤销', expired: '已到期', reconnect_required: '需重新配对' } as Record<string, string>)[device.status ?? ''] ?? device.status} · {new Date(device.expiresAt).toLocaleString()} 到期</small></div><button className="button secondary" disabled={!!busy || device.status !== 'active'} onClick={() => void act('revoke', async () => { await api('/companion/devices/' + device.id + '/revoke', { revision: device.revision }); setPair(null); })}><X size={13} />撤销</button></div>)}</section>
|
||||||
|
{!!status?.audit.length && <details className="companion-audit"><summary>最近的设备操作</summary>{status.audit.slice(0, 12).map(item => <p key={item.id}><time>{new Date(item.at).toLocaleTimeString()}</time><span>{status.devices.find(device => device.id === item.deviceId)?.name ?? '原设备'} · {({ pair: '配对', rotate: '轮换会话', revoke: '撤销', approve: '审批', stop: '停止' } as Record<string, string>)[item.action] ?? item.action}</span><code>{item.status}</code></p>)}</details>}
|
||||||
|
</div>;
|
||||||
|
}
|
||||||
@@ -16,6 +16,11 @@ export async function exportSession(id: string) {
|
|||||||
const blob = await response.blob();
|
const blob = await response.blob();
|
||||||
downloadBlob(blob, 'agent-workbench-session-' + id + '.json');
|
downloadBlob(blob, 'agent-workbench-session-' + id + '.json');
|
||||||
}
|
}
|
||||||
|
export async function downloadCompanionCertificate() {
|
||||||
|
const response = await fetch('/api/companion/certificate', { headers: { 'X-Workbench-Token': accessToken } });
|
||||||
|
if (!response.ok) { const value = await response.json().catch(() => ({})); throw new Error(value.error || '手机根证书下载失败。'); }
|
||||||
|
downloadBlob(await response.blob(), 'Agent-Workbench-Mobile-CA.cer');
|
||||||
|
}
|
||||||
export async function downloadArtifact(sessionId: string, artifactId: string, name: string) {
|
export async function downloadArtifact(sessionId: string, artifactId: string, name: string) {
|
||||||
const response = await fetch('/api/artifacts/' + artifactId + '?session=' + sessionId + '&download=1', { headers: { 'X-Workbench-Token': accessToken } });
|
const response = await fetch('/api/artifacts/' + artifactId + '?session=' + sessionId + '&download=1', { headers: { 'X-Workbench-Token': accessToken } });
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
.companion-panel{color:var(--ink);font-size:13px;line-height:1.7}.companion-heading{display:flex;gap:14px;align-items:flex-start;margin-bottom:22px}.companion-heading>div{flex:1}.companion-heading strong{font-size:18px}.companion-heading p{margin:5px 0;color:var(--muted)}.companion-state{padding:3px 8px;border:1px solid var(--line);border-radius:4px;font-size:11px;white-space:nowrap}.companion-panel section{padding:20px 0;border-top:1px solid var(--line)}.companion-panel h3{font-size:14px;margin:0 0 12px}.companion-panel h3 span{font-size:12px;color:var(--muted);margin-left:8px}.companion-network form,.companion-address{display:flex;align-items:flex-end;gap:12px;flex-wrap:wrap}.companion-network label{display:grid;gap:5px}.companion-network select,.companion-network input,.companion-grant select{background:var(--paper);color:var(--ink);padding:9px;border:1px solid #b5c9c3;border-radius:5px}.companion-network input{width:96px}.companion-note{font-size:12px;color:var(--muted)}.companion-address code{flex:1;overflow-wrap:anywhere}.companion-panel fieldset{margin:12px 0;border:1px solid var(--line);padding:12px;border-radius:5px}.companion-panel legend{padding:0 6px;font-size:12px}.companion-projects{display:flex;gap:12px 18px;flex-wrap:wrap;max-height:150px;overflow:auto}.companion-projects label,.companion-grant label{display:flex;gap:7px;align-items:center}.companion-projects input,.companion-grant input{accent-color:var(--teal);width:17px;height:17px}.companion-grant{display:flex;gap:14px;align-items:center;flex-wrap:wrap;margin:14px 0 18px;font-size:12px}.companion-grant>span{color:var(--muted)}.companion-certificate{border-top:1px solid var(--line);padding:18px 0}.companion-certificate summary{display:flex;gap:8px;align-items:center;cursor:pointer;font-weight:600}.companion-certificate ol{padding-left:22px;color:var(--muted);line-height:1.9}.companion-fingerprint{display:block;font-size:11px;overflow-wrap:anywhere;margin-top:12px;color:var(--muted)}.companion-pair{display:flex;gap:22px;margin-top:20px;padding:16px;background:var(--paper);border:1px solid var(--line);align-items:center}.companion-pair img{background:white;flex-shrink:0}.companion-pair>div{min-width:0}.companion-pair p{font-size:12px;color:var(--muted)}.companion-pair-url{overflow-wrap:anywhere;font-family:Consolas,monospace}.companion-device{display:flex;gap:12px;align-items:center;padding:14px 0;border-bottom:1px solid var(--line)}.companion-device>div{flex:1;min-width:0}.companion-device p{margin:2px 0;color:var(--muted);overflow-wrap:anywhere;font-size:12px}.companion-device small{color:var(--muted);font-size:11px}.companion-device button{flex-shrink:0}.companion-audit summary{cursor:pointer;font-size:12px}.companion-audit p{display:flex;gap:14px;color:var(--muted);font-size:11px}.companion-audit p>span{flex:1}.companion-error{padding:12px;color:#943b2c;background:#fff2ed;border:1px solid #e7b9a9;overflow-wrap:anywhere}@media(max-width:620px){.companion-heading strong{font-size:16px}.companion-pair{flex-direction:column;align-items:flex-start}.companion-pair img{align-self:center}.companion-network form{align-items:stretch}.companion-network label:first-child{flex-basis:100%}.companion-network .button{align-self:flex-end}.companion-grant{gap:12px}.companion-address{align-items:flex-start;flex-direction:column}}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
export interface CompanionPermissions { observe: boolean; approve: boolean; stop: boolean }
|
||||||
|
export interface CompanionDevice { id: string; name: string; projectIds: string[]; permissions: CompanionPermissions; revision: number; expiresAt: string; createdAt?: string; status?: string }
|
||||||
|
export interface CompanionStatus {
|
||||||
|
enabled: boolean; busy: boolean; origin: string | null; addresses: { name: string; address: string }[];
|
||||||
|
gatewayId: string; revision: number; devices: CompanionDevice[];
|
||||||
|
certificate: { sha256: string; expiresAt: string } | null;
|
||||||
|
audit: { id: string; at: string; deviceId: string; action: string; status: string; taskId?: string }[];
|
||||||
|
}
|
||||||
|
export interface MobileBrief { id: string; projectId: string; taskId?: string; runId?: string; title: string; status: string; revision: number; eventSeq: number; updatedAt: string }
|
||||||
|
export interface MobileUsage { totalTokens: number; unknownRequests: number; estimatedUnknownTokens: number }
|
||||||
|
export interface MobileTask extends MobileBrief {
|
||||||
|
task: { id: string; goal: string; status: string; usage: MobileUsage; budget: { maxTokens: number }; verification: { status: string } } | null;
|
||||||
|
run: { id: string; status: string; steps: number; toolCalls: number; stopReason: string | null; usage: MobileUsage } | null;
|
||||||
|
progress: { total: number; completed: number; unknown: { id: string; tool: string; state: string; runId: string }[] };
|
||||||
|
events: { id: string; label: string; phase: string; output: string; taskId?: string; runId?: string; createdAt: string; exitCode?: number }[];
|
||||||
|
messages: { id: string; role: string; content: string; createdAt: string }[];
|
||||||
|
approvals: { id: string; taskId: string; runId: string; projectId: string; command: string; reason: string; shell: string; fingerprint: string; actionable: boolean }[];
|
||||||
|
changes: { id: string; path: string; reason: string; status: string; sha256: string; baseSha256: string; additions: number; deletions: number }[];
|
||||||
|
checks: { id: string; status: string; summary: string; requiresVerification?: boolean; results: { name: string; status: string; exitCode?: number; tests?: { total: number; passed: number; failed: number; skipped: number; cancelled: number } }[] }[];
|
||||||
|
reports: { id: string; kind: string; sha256: string; bytes: number }[];
|
||||||
|
}
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||||
|
import { ArrowLeft, ChevronRight, ClipboardCheck, FileDiff, Folder, Link2, RefreshCw, ShieldCheck, Square, Terminal, Wifi, WifiOff, X } from 'lucide-react';
|
||||||
|
import type { CompanionDevice, MobileBrief, MobileTask } from '../companion-types';
|
||||||
|
import { mobileApi, MobileError, verifiedText, verifyDigest } from './api';
|
||||||
|
|
||||||
|
const stateLabel = (state: string) => ({ idle: '未开始', waiting: '等待审批', validating: '校验中', queued: '排队中', executing: '执行中', error: '错误', running: '执行中', awaiting_approval: '等待审批', stopping: '正在停止', completed: '已完成', needs_review: '待审查', failed: '失败', interrupted: '已中断', cancelled: '已停止', paused: '已暂停', unknown: '需核对', completed_with_changes: '待审查', passed: '通过', pending: '待处理', applied: '已应用', denied: '已拒绝', approved: '已批准', conflict: '有冲突', unverified: '需核对', stale: '已变化' } as Record<string, string>)[state] ?? state;
|
||||||
|
const time = (value: string) => new Date(value).toLocaleString('zh-CN', { month: 'numeric', day: 'numeric', hour: '2-digit', minute: '2-digit' });
|
||||||
|
type Me = { device: CompanionDevice; gatewayId: string; operations: { requestId: string; action: string; status: string; taskId: string; runId: string; createdAt: string }[] };
|
||||||
|
type Decision = { requestId: string; kind: 'approve' | 'stop'; task: MobileTask; approval?: MobileTask['approvals'][number]; allow?: boolean };
|
||||||
|
|
||||||
|
export function MobileApp({ initialToken }: { initialToken: string }) {
|
||||||
|
const [me, setMe] = useState<Me | null>(null), [pairToken, setPairToken] = useState(initialToken), [name, setName] = useState('iPhone');
|
||||||
|
const [projects, setProjects] = useState<{ id: string; name: string }[]>([]), [sessions, setSessions] = useState<MobileBrief[]>([]), [project, setProject] = useState('');
|
||||||
|
const [selected, setSelected] = useState(''), [task, setTask] = useState<MobileTask | null>(null), [tab, setTab] = useState('progress');
|
||||||
|
const [busy, setBusy] = useState(''), [error, setError] = useState(''), [fresh, setFresh] = useState(false), [lastSync, setLastSync] = useState('');
|
||||||
|
const [connectionRequired, setConnectionRequired] = useState(!!initialToken), [decision, setDecision] = useState<Decision | null>(null);
|
||||||
|
const [document, setDocument] = useState<{ title: string; text: string; sha256: string; redacted?: boolean } | null>(null), [receipt, setReceipt] = useState('');
|
||||||
|
const cursor = useRef(0), identity = useRef<Me | null>(null), chosen = useRef(''), running = useRef(false), actionBusy = useRef(false), alive = useRef(true), generation = useRef(0), dialog = useRef<HTMLDialogElement>(null), documentDialog = useRef<HTMLDialogElement>(null);
|
||||||
|
const revoke = useCallback((message: string) => {
|
||||||
|
generation.current++; identity.current = null; cursor.current = 0; chosen.current = '';
|
||||||
|
setMe(null); setProjects([]); setSessions([]); setTask(null); setSelected(''); setDocument(null); setDecision(null); setFresh(false); setConnectionRequired(true); setError(message);
|
||||||
|
}, []);
|
||||||
|
const refresh = useCallback(async () => {
|
||||||
|
if (running.current || !alive.current || globalThis.document.visibilityState === 'hidden') return;
|
||||||
|
running.current = true; const epoch = generation.current;
|
||||||
|
try {
|
||||||
|
const current = await mobileApi<Me>('/me');
|
||||||
|
if (!alive.current || epoch !== generation.current) return;
|
||||||
|
const key = 'workbench-mobile-cursor:' + current.gatewayId + ':' + current.device.id;
|
||||||
|
if (!identity.current || identity.current.device.id !== current.device.id || identity.current.gatewayId !== current.gatewayId) {
|
||||||
|
let saved = ''; try { saved = sessionStorage.getItem(key) ?? ''; } catch {}
|
||||||
|
cursor.current = /^\d+$/.test(saved) && Number.isSafeInteger(Number(saved)) ? Number(saved) : 0;
|
||||||
|
}
|
||||||
|
// Drain bounded original event pages. They invalidate displayed snapshots;
|
||||||
|
// reconnecting only reads data and never submits an execution request.
|
||||||
|
for (let page = 0; page < 10; page++) {
|
||||||
|
const history = await mobileApi<{ events: { seq: number }[]; nextCursor: number; hasMore: boolean }>('/events?after=' + cursor.current + '&limit=200');
|
||||||
|
if (!Number.isSafeInteger(history.nextCursor) || history.nextCursor < cursor.current || history.events.some((event, index) => event.seq <= (index ? history.events[index - 1].seq : cursor.current))) throw new MobileError('原进展顺序无法核对,请在电脑查看。');
|
||||||
|
cursor.current = history.nextCursor; try { sessionStorage.setItem(key, String(cursor.current)); } catch {}
|
||||||
|
if (!history.hasMore) break;
|
||||||
|
}
|
||||||
|
const [nextProjects, nextSessions, nextTask] = await Promise.all([mobileApi<{ id: string; name: string }[]>('/projects'), mobileApi<MobileBrief[]>('/sessions'),
|
||||||
|
chosen.current ? mobileApi<MobileTask>('/sessions/' + chosen.current) : Promise.resolve(null)]);
|
||||||
|
if (!alive.current || epoch !== generation.current) return;
|
||||||
|
identity.current = current; setMe(current); setProjects(nextProjects); setSessions(nextSessions);
|
||||||
|
if (nextTask && nextTask.id === chosen.current) setTask(previous => previous && previous.id === nextTask.id && previous.revision > nextTask.revision ? previous : nextTask);
|
||||||
|
setFresh(true); setConnectionRequired(false); setError(''); setLastSync(new Date().toISOString());
|
||||||
|
} catch (value) {
|
||||||
|
if (!alive.current || epoch !== generation.current) return;
|
||||||
|
if (value instanceof MobileError && [401, 403].includes(value.status)) revoke(value.message);
|
||||||
|
else { setFresh(false); setError(value instanceof Error ? value.message : '手机连接未完成。'); }
|
||||||
|
} finally { running.current = false; }
|
||||||
|
}, [revoke]);
|
||||||
|
useEffect(() => {
|
||||||
|
alive.current = true; if (!initialToken) void refresh();
|
||||||
|
const timer = setInterval(() => { if (identity.current) void refresh(); }, 2500);
|
||||||
|
const resume = () => { if (identity.current || !initialToken) void refresh(); };
|
||||||
|
const offline = () => setFresh(false);
|
||||||
|
globalThis.document.addEventListener('visibilitychange', resume); window.addEventListener('online', resume); window.addEventListener('offline', offline);
|
||||||
|
return () => { alive.current = false; clearInterval(timer); globalThis.document.removeEventListener('visibilitychange', resume); window.removeEventListener('online', resume); window.removeEventListener('offline', offline); };
|
||||||
|
}, [initialToken, refresh]);
|
||||||
|
useEffect(() => { if (decision && dialog.current && !dialog.current.open) dialog.current.showModal(); }, [decision]);
|
||||||
|
useEffect(() => { if (document && documentDialog.current && !documentDialog.current.open) documentDialog.current.showModal(); }, [document]);
|
||||||
|
async function act(action: string, run: () => Promise<unknown>) {
|
||||||
|
if (actionBusy.current) return; actionBusy.current = true; setBusy(action); setError('');
|
||||||
|
try { await run(); } catch (value) {
|
||||||
|
if (value instanceof MobileError && [401, 403].includes(value.status)) revoke(value.message);
|
||||||
|
else { if (value instanceof MobileError && (value.status === 0 || value.status >= 500)) setFresh(false); setError(value instanceof Error ? value.message : '手机操作未完成。'); }
|
||||||
|
} finally { actionBusy.current = false; if (alive.current) setBusy(''); }
|
||||||
|
}
|
||||||
|
async function pair(event: React.FormEvent) {
|
||||||
|
event.preventDefault(); await act('pair', async () => {
|
||||||
|
let token = pairToken.trim();
|
||||||
|
if (token.startsWith('https://')) { const url = new URL(token); if (url.origin !== location.origin) throw new MobileError('配对链接不属于当前电脑地址,请重新扫码。'); token = new URLSearchParams(url.hash.slice(1)).get('pair') ?? ''; }
|
||||||
|
await mobileApi('/pair', { token, name }); setPairToken(''); setConnectionRequired(false); await refresh();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
async function openTask(id: string) {
|
||||||
|
chosen.current = id; setSelected(id); setTask(null); setTab('progress'); setDocument(null); setReceipt('');
|
||||||
|
await act('task', async () => { const next = await mobileApi<MobileTask>('/sessions/' + id); if (chosen.current === id) setTask(next); });
|
||||||
|
}
|
||||||
|
async function submitDecision() {
|
||||||
|
if (!decision) return;
|
||||||
|
const value = decision, original = value.task;
|
||||||
|
await act('operation', async () => {
|
||||||
|
const result = await mobileApi<{ status: string; requestId: string }>('/sessions/' + original.id + '/' + value.kind, { requestId: value.requestId, taskId: original.taskId, runId: original.runId, revision: original.revision,
|
||||||
|
...(value.kind === 'approve' ? { approvalId: value.approval!.id, fingerprint: value.approval!.fingerprint, allow: value.allow } : {}) });
|
||||||
|
setDecision(null); setReceipt(result.status === 'completed' ? (value.kind === 'stop' ? '原任务停止操作已返回。' : value.allow ? '已批准原请求。' : '已拒绝原请求。') : '原操作结果需在电脑核对;不会自动重放。'); await refresh();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
async function openDiff(change: MobileTask['changes'][number]) {
|
||||||
|
if (!task) return; const owner = task.id;
|
||||||
|
await act('document', async () => {
|
||||||
|
let text = '', after = 0, hash = '', more = true;
|
||||||
|
while (more) {
|
||||||
|
const page = await mobileApi<{ id: string; text: string; sha256: string; nextOffset: number; offset: number; hasMore: boolean }>('/sessions/' + owner + '/changes/' + change.id + '?offset=' + after);
|
||||||
|
if (page.offset !== after || page.nextOffset !== after + page.text.length || hash && page.sha256 !== hash || page.hasMore && !page.text.length) throw new MobileError('文件差异已变化,请刷新任务后重试。');
|
||||||
|
hash = page.sha256; text += page.text; after = page.nextOffset; more = page.hasMore;
|
||||||
|
if (text.length > 2 * 1024 * 1024) throw new MobileError('文件差异超过手机显示范围,请在电脑查看。');
|
||||||
|
}
|
||||||
|
await verifyDigest(text, hash); if (chosen.current === owner) setDocument({ title: change.path, text, sha256: hash });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const projectName = (id: string) => projects.find(value => value.id === id)?.name ?? '原项目';
|
||||||
|
const selectedTask = task?.id === selected ? task : null;
|
||||||
|
return <div className="mobile-app">
|
||||||
|
<header className="mobile-header"><span className="mobile-mark"><Terminal size={20} /></span><div><strong>Agent Workbench</strong><span>手机伴随端 · Windows 执行宿主</span></div><button aria-label="刷新任务" disabled={!!busy} onClick={() => void refresh()}><RefreshCw size={19} /></button></header>
|
||||||
|
{me && <div className={'mobile-connection ' + (fresh ? '' : 'disconnected')}>{fresh ? <Wifi size={14} /> : <WifiOff size={14} />}<span>{fresh ? '已同步 · ' + time(lastSync) : '连接中断 · 当前内容可能已过期'}</span><span>{me.device.permissions.approve ? '可审批' : '观察'}</span></div>}
|
||||||
|
{error && <div className="mobile-error" role="alert"><strong>{fresh ? '操作未完成' : connectionRequired ? '需要连接' : '连接待恢复'}</strong><p>{error}</p>{me && <button onClick={() => void refresh()} disabled={!!busy}>重新同步</button>}</div>}
|
||||||
|
{me?.operations?.some(value => value.status === 'unknown') && <div className="mobile-unknown"><strong>手机操作回执需要核对</strong><p>有原审批或停止操作没有完整回执,请在电脑核对;手机不会自动重放。</p>{me.operations.filter(value => value.status === 'unknown').map(value => <code key={value.requestId}>Task {value.taskId} · {value.action === 'stop' ? '停止' : '审批'}</code>)}</div>}
|
||||||
|
{!me && <main className="mobile-pair-page"><div className="mobile-pair-heading"><Link2 size={32} /><h1>接续电脑上的任务</h1><p>在 Windows 工作台打开「手机连接」,选择项目并生成一次性配对码。</p></div>{connectionRequired || pairToken ? <form onSubmit={event => void pair(event)}><label>设备名称<input value={name} maxLength={60} onChange={event => setName(event.target.value)} autoComplete="off" /></label><label>配对码或配对链接<input type="password" value={pairToken} onChange={event => setPairToken(event.target.value)} autoComplete="off" autoCapitalize="none" spellCheck={false} placeholder="扫描电脑上的二维码后自动填写" /></label><button className="mobile-primary" disabled={!!busy || !pairToken.trim() || !name.trim()}>{busy === 'pair' ? '正在核对授权…' : '连接这台电脑'}</button></form> : <p role="status">正在核对当前手机连接…</p>}<div className="mobile-pair-help"><ShieldCheck size={18} /><p>首次使用需要在 iPhone 安装并信任电脑生成的根证书。请按电脑「手机连接」中的指引操作。</p></div></main>}
|
||||||
|
{me && !selected && <main className="mobile-task-list"><div className="mobile-page-title"><div><span className="mobile-eyebrow">{me.device.name}</span><h1>项目任务</h1></div><span>{sessions.length} 个会话</span></div><label className="mobile-project-filter"><Folder size={17} /><select aria-label="筛选项目" value={project} onChange={event => setProject(event.target.value)}><option value="">全部授权项目</option>{projects.map(item => <option key={item.id} value={item.id}>{item.name}</option>)}</select></label>
|
||||||
|
{!sessions.length && <div className="mobile-empty"><ClipboardCheck size={30} /><h2>暂无任务</h2><p>在电脑创建或打开任务,手机会同步该项目的执行进展。</p></div>}
|
||||||
|
{sessions.filter(item => !project || item.projectId === project).map(item => <button className="mobile-task-row" key={item.id} onClick={() => void openTask(item.id)}><div><span className="mobile-project-name">{projectName(item.projectId)}</span><strong>{item.title}</strong><span className="mobile-row-meta"><span className={'mobile-state state-' + item.status}>{stateLabel(item.status)}</span><time>{time(item.updatedAt)}</time></span></div><ChevronRight size={19} /></button>)}
|
||||||
|
<details className="mobile-device-settings"><summary>设备连接与授权</summary><p>{projects.map(item => item.name).join('、')}</p><p>观察{me.device.permissions.approve ? ' · 审批' : ''}{me.device.permissions.stop ? ' · 停止' : ''} · {time(me.device.expiresAt)} 到期</p><p>手机显示最近200个未归档会话,完整历史在电脑保留。</p><p>iPhone Safari 中点「共享 → 添加到主屏幕」可安装伴随端。主屏幕应用如要求连接,请在电脑生成新的配对码。</p><div><button disabled={!!busy || !fresh} onClick={() => void act('rotate', async () => { await mobileApi('/rotate', {}); await refresh(); setReceipt('手机会话已轮换。'); })}>轮换手机会话</button><button disabled={!!busy} onClick={() => void act('logout', async () => { await mobileApi('/logout', {}); revoke('已断开并撤销这台手机。'); })}>断开并撤销</button></div></details></main>}
|
||||||
|
{me && selected && <main className="mobile-task-detail"><button className="mobile-back" onClick={() => { chosen.current = ''; setSelected(''); setTask(null); setDocument(null); }}><ArrowLeft size={18} />项目任务</button>{!selectedTask ? <div className="mobile-empty" role="status">正在读取原任务…</div> : <>
|
||||||
|
<div className="mobile-task-title"><span className="mobile-eyebrow">{projectName(selectedTask.projectId)}</span><h1>{selectedTask.title}</h1><div><span className={'mobile-state state-' + selectedTask.status}>{stateLabel(selectedTask.status)}</span><span>修订 {selectedTask.revision}</span></div><details className="mobile-goal"><summary>完整任务目标</summary><p>{selectedTask.task?.goal ?? '此会话尚未创建执行任务。'}</p></details><details><summary>原任务与运行</summary><code>Task {selectedTask.taskId ?? '未开始'}<br />Run {selectedTask.runId ?? '未开始'}</code></details></div>
|
||||||
|
{receipt && <p className="mobile-receipt" role="status">{receipt}</p>}
|
||||||
|
{!!selectedTask.progress.unknown.length && <div className="mobile-unknown"><strong>{selectedTask.progress.unknown.length} 项工具结果需要核对</strong><p>请在电脑核对原输入和实际结果。刷新、重连和手机审批均不会自动重新执行。</p>{selectedTask.progress.unknown.map(item => <code key={item.id}>{item.tool} · {stateLabel(item.state)}</code>)}</div>}
|
||||||
|
{!!selectedTask.approvals.length && <section className="mobile-approvals"><h2><ShieldCheck size={18} />等待你的确认</h2>{selectedTask.approvals.map(approval => <article key={approval.id}><span>{approval.shell}</span><pre>{approval.command}</pre><p>{approval.reason}</p>{!me.device.permissions.approve ? <p className="mobile-muted">此设备仅可观察,请在电脑审批。</p> : !approval.actionable ? <p className="mobile-muted">原审批已失效,请在电脑核对。</p> : <div className="mobile-action-pair"><button disabled={!fresh || !!busy} onClick={() => setDecision({ requestId: crypto.randomUUID(), kind: 'approve', task: selectedTask, approval, allow: false })}>拒绝</button><button className="mobile-primary" disabled={!fresh || !!busy} onClick={() => setDecision({ requestId: crypto.randomUUID(), kind: 'approve', task: selectedTask, approval, allow: true })}>核对并批准</button></div>}</article>)}</section>}
|
||||||
|
<nav className="mobile-tabs" aria-label="任务内容">{[['progress', '执行进展'], ['changes', '文件差异'], ['checks', '检查与报告']].map(([key, label]) => <button key={key} aria-current={tab === key ? 'page' : undefined} onClick={() => { setTab(key); setDocument(null); }}>{label}{key === 'changes' && !!selectedTask.changes.length && <span>{selectedTask.changes.length}</span>}</button>)}</nav>
|
||||||
|
{tab === 'progress' && <section className="mobile-progress"><div className="mobile-section-heading"><h2>原执行记录</h2><span>{selectedTask.progress.completed} / {selectedTask.progress.total} 工具完成</span></div><ol>{selectedTask.events.map(item => <li key={item.id}><div><strong>{item.label || '执行事件'}</strong><span className={'mobile-state state-' + item.phase}>{stateLabel(item.phase)}</span></div>{item.output && <details><summary>查看原输出片段{item.exitCode !== undefined ? ' · 退出码 ' + item.exitCode : ''}</summary><pre>{item.output}</pre></details>}</li>)}</ol>{!selectedTask.events.length && <p className="mobile-muted">尚无工具执行记录。</p>}{selectedTask.messages.map(message => <article className="mobile-message" key={message.id}><span>{message.role === 'assistant' ? '代理回复' : '系统记录'} · {time(message.createdAt)}</span><p>{message.content}</p></article>)}<p className="mobile-muted">手机显示最近60条执行记录和8条回复;完整记录保留在电脑原会话。</p></section>}
|
||||||
|
{tab === 'changes' && <section className="mobile-changes"><div className="mobile-section-heading"><h2>当前任务的改动</h2><span>{selectedTask.changes.length} 个文件</span></div>{!selectedTask.changes.length && <p className="mobile-muted">尚未提出文件改动。</p>}{selectedTask.changes.map(change => <button key={change.id} className="mobile-file-row" disabled={!!busy || !fresh} onClick={() => void openDiff(change)}><FileDiff size={19} /><div><strong>{change.path}</strong><span>{stateLabel(change.status)} · <b>+{change.additions}</b> / −{change.deletions}</span></div><ChevronRight size={17} /></button>)}<p className="mobile-muted">手机可查看原差异;应用、恢复和 Git 提交在电脑审查。</p></section>}
|
||||||
|
{tab === 'checks' && <section className="mobile-checks"><h2>工程检查</h2>{!selectedTask.checks.length && <p className="mobile-muted">尚无工程检查结果。</p>}{selectedTask.checks.map(check => <article key={check.id}><div className="mobile-section-heading"><strong>检查 {check.id.slice(0, 8)}</strong><span className={'mobile-state state-' + check.status}>{stateLabel(check.status)}</span></div><p>{check.summary}</p>{check.results.map((result, index) => <p className="mobile-check-result" key={index}><span>{result.name}</span><span>{stateLabel(result.status)}{result.exitCode !== undefined ? ' · ' + result.exitCode : ''}{result.tests ? ' · ' + result.tests.passed + '/' + result.tests.total + ' 项测试' : ''}</span></p>)}</article>)}<h2>原交付报告</h2>{!selectedTask.reports.length && <p className="mobile-muted">尚未生成交付报告。</p>}{selectedTask.reports.map(report => <button className="mobile-file-row" key={report.id} disabled={!!busy || !fresh} onClick={() => void act('document', async () => { const value = await verifiedText('/sessions/' + selectedTask.id + '/reports/' + report.id); if (chosen.current === selectedTask.id) setDocument({ title: report.kind === 'delivery-report-markdown' ? '交付报告' : '交付报告 JSON', ...value }); })}><ClipboardCheck size={18} /><div><strong>{report.kind === 'delivery-report-markdown' ? '交付报告' : '交付报告 JSON'}</strong><span>{report.bytes.toLocaleString()} bytes · 校验后显示</span></div><ChevronRight size={17} /></button>)}</section>}
|
||||||
|
{selectedTask.task && <div className="mobile-budget"><span>任务累计用量</span><strong>{selectedTask.task.usage.totalTokens.toLocaleString()} tokens / {selectedTask.task.budget.maxTokens.toLocaleString()}</strong>{!!selectedTask.task.usage.unknownRequests && <p>{selectedTask.task.usage.unknownRequests} 次用量未知,另按 {selectedTask.task.usage.estimatedUnknownTokens.toLocaleString()} tokens 估算;不计为已确认用量。</p>}</div>}
|
||||||
|
{['running', 'awaiting_approval', 'stopping'].includes(selectedTask.status) && <div className="mobile-stop"><span>{me.device.permissions.stop ? '停止仍由电脑等待所属工具退出' : '此设备没有停止权限'}</span><button disabled={!me.device.permissions.stop || !fresh || !!busy || selectedTask.status === 'stopping'} onClick={() => setDecision({ requestId: crypto.randomUUID(), kind: 'stop', task: selectedTask })}><Square size={14} />停止原任务</button></div>}
|
||||||
|
</>}</main>}
|
||||||
|
{document && <dialog ref={documentDialog} className="mobile-document" aria-label={document.title} onCancel={() => setDocument(null)}><header><button aria-label="关闭文档" onClick={() => setDocument(null)}><ArrowLeft size={20} /></button><strong>{document.title}</strong></header><p><ShieldCheck size={14} />SHA-256 已核对{document.redacted ? ' · 已脱敏' : ''}</p><code>{document.sha256}</code><pre>{document.text}</pre><button onClick={() => setDocument(null)}>返回任务</button></dialog>}
|
||||||
|
{decision && <dialog ref={dialog} className="mobile-confirm" onCancel={() => setDecision(null)}><button className="mobile-confirm-close" aria-label="关闭确认" onClick={() => setDecision(null)} disabled={!!busy}><X size={20} /></button><h2>{decision.kind === 'stop' ? '停止这个原任务' : decision.allow ? '批准原命令请求' : '拒绝原命令请求'}</h2><p>{projectName(decision.task.projectId)} · {decision.task.title}</p>{decision.approval && <pre>{decision.approval.command}</pre>}<code>Task {decision.task.taskId}<br />Run {decision.task.runId}<br />修订 {decision.task.revision}</code>{decision.task.revision !== task?.revision && <p role="alert">任务修订已变化,请关闭并重新核对。</p>}<p>{decision.kind === 'stop' ? '电脑将停止此运行,并保留已经完成的工具结果。' : decision.allow ? '批准后,电脑将在原项目中执行这条已登记命令。' : '拒绝后,这条原命令不会执行。'}</p><div className="mobile-action-pair"><button disabled={!!busy} onClick={() => setDecision(null)}>返回核对</button><button className={decision.kind === 'stop' ? 'mobile-danger' : 'mobile-primary'} disabled={!!busy || !fresh || decision.task.revision !== task?.revision} onClick={() => void submitDecision()}>{busy === 'operation' ? '等待原回执…' : '确认'}</button></div></dialog>}
|
||||||
|
</div>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
export class MobileError extends Error { constructor(message: string, public status = 0) { super(message); } }
|
||||||
|
export async function mobileApi<T>(route: string, value?: unknown): Promise<T> {
|
||||||
|
const controller = new AbortController(), timer = setTimeout(() => controller.abort(), route.endsWith('/stop') ? 75000 : 15000);
|
||||||
|
try {
|
||||||
|
const response = await fetch('/mobile-api' + route, { method: value === undefined ? 'GET' : 'POST', credentials: 'same-origin', cache: 'no-store', signal: controller.signal,
|
||||||
|
headers: value === undefined ? {} : { 'Content-Type': 'application/json' }, ...(value === undefined ? {} : { body: JSON.stringify(value) }) });
|
||||||
|
const body = await response.json();
|
||||||
|
if (!response.ok) throw new MobileError(body.error || '当前手机请求未完成。', response.status);
|
||||||
|
return body as T;
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof MobileError) throw error;
|
||||||
|
throw new MobileError(value === undefined ? '连接已断开。请核对 Wi-Fi 与电脑上的手机连接。' : '没有收到完整回执,请先刷新并在电脑核对原操作。');
|
||||||
|
} finally { clearTimeout(timer); }
|
||||||
|
}
|
||||||
|
export async function verifiedText(route: string, maximum = 8 * 1024 * 1024) {
|
||||||
|
const value = await mobileApi<{ text: string; sha256: string; sourceSha256?: string; redacted?: boolean }>(route);
|
||||||
|
if (typeof value.text !== 'string' || value.text.length > maximum) throw new MobileError('报告超出手机显示范围,请在电脑查看。');
|
||||||
|
await verifyDigest(value.text, value.sha256); return value;
|
||||||
|
}
|
||||||
|
export async function verifyDigest(text: string, expected: string) {
|
||||||
|
if (!/^[a-f0-9]{64}$/.test(expected)) throw new MobileError('原结果缺少可核对的SHA-256。');
|
||||||
|
const hash = Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text)))).map(value => value.toString(16).padStart(2, '0')).join('');
|
||||||
|
if (hash !== expected) throw new MobileError('结果内容校验失败,请在电脑核对原工件。');
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { StrictMode } from 'react';
|
||||||
|
import { createRoot } from 'react-dom/client';
|
||||||
|
import { MobileApp } from './MobileApp';
|
||||||
|
import './mobile.css';
|
||||||
|
|
||||||
|
const fragment = new URLSearchParams(location.hash.slice(1));
|
||||||
|
const token = fragment.get('pair') ?? '';
|
||||||
|
if (fragment.has('pair')) history.replaceState(null, '', location.pathname);
|
||||||
|
createRoot(document.getElementById('mobile-root')!).render(<StrictMode><MobileApp initialToken={token} /></StrictMode>);
|
||||||
|
if ('serviceWorker' in navigator && isSecureContext) navigator.serviceWorker.register('/mobile-sw.js', { scope: '/' }).catch(() => {});
|
||||||
@@ -2,10 +2,13 @@ import fs from 'node:fs';
|
|||||||
import { randomBytes, randomUUID } from 'node:crypto';
|
import { randomBytes, randomUUID } from 'node:crypto';
|
||||||
import { companionError, companionHash, companionName, deviceGrant, COMPANION_SCHEMA } from '../../shared/contracts/companion.mjs';
|
import { companionError, companionHash, companionName, deviceGrant, COMPANION_SCHEMA } from '../../shared/contracts/companion.mjs';
|
||||||
import { assertLocalTree } from '../desktop/file-state.mjs';
|
import { assertLocalTree } from '../desktop/file-state.mjs';
|
||||||
|
import { isId } from '../../shared/contracts/execution.mjs';
|
||||||
|
|
||||||
const key = 'mobileCompanion';
|
const key = 'mobileCompanion';
|
||||||
const instant = value => new Date(value).toISOString();
|
const instant = value => new Date(value).toISOString();
|
||||||
const secret = () => randomBytes(32).toString('base64url');
|
const secret = () => randomBytes(32).toString('base64url');
|
||||||
|
const dictionary = value => value !== null && typeof value === 'object' && !Array.isArray(value);
|
||||||
|
const date = value => typeof value === 'string' && Number.isFinite(Date.parse(value));
|
||||||
export class DeviceRegistry {
|
export class DeviceRegistry {
|
||||||
constructor(store, identity, { clock = Date.now } = {}) {
|
constructor(store, identity, { clock = Date.now } = {}) {
|
||||||
this.store = store; this.identity = identity; this.clock = clock; this.pairings = new Map();
|
this.store = store; this.identity = identity; this.clock = clock; this.pairings = new Map();
|
||||||
@@ -22,9 +25,20 @@ export class DeviceRegistry {
|
|||||||
}
|
}
|
||||||
read() {
|
read() {
|
||||||
const state = this.store.storage.meta(key);
|
const state = this.store.storage.meta(key);
|
||||||
if (state && (state.schema !== COMPANION_SCHEMA || state.binding !== this.binding || !Number.isSafeInteger(state.revision)
|
if (state && (state.schema !== COMPANION_SCHEMA || state.binding !== this.binding || !isId(state.gatewayId) || !Number.isSafeInteger(state.revision) || state.revision < 0
|
||||||
|| !state.devices || Array.isArray(state.devices) || Object.keys(state.devices).length > 128 || !Array.isArray(state.audit)
|
|| !dictionary(state.devices) || Object.keys(state.devices).length > 128 || !Array.isArray(state.audit) || state.audit.length > 500
|
||||||
|| !state.operations || Array.isArray(state.operations))) throw companionError('原手机登记无法核对;请保留数据并检查原Windows用户和目录。', 409);
|
|| !dictionary(state.operations) || Object.keys(state.operations).length > 2000
|
||||||
|
|| Object.entries(state.devices).some(([id, device]) => !dictionary(device) || id !== device.id || !isId(id)
|
||||||
|
|| typeof device.name !== 'string' || !device.name.trim() || device.name.length > 60 || /[\x00-\x1f\x7f]/.test(device.name)
|
||||||
|
|| !Number.isSafeInteger(device.revision) || device.revision < 1 || !date(device.createdAt) || !date(device.expiresAt)
|
||||||
|
|| device.revokedAt !== null && !date(device.revokedAt) || device.credentialHash !== null && !/^[a-f0-9]{64}$/.test(device.credentialHash)
|
||||||
|
|| !Array.isArray(device.projectIds) || !device.projectIds.length || device.projectIds.length > 16 || device.projectIds.some(id => !isId(id)) || new Set(device.projectIds).size !== device.projectIds.length
|
||||||
|
|| !dictionary(device.permissions) || Object.keys(device.permissions).length !== 3 || device.permissions.observe !== true || typeof device.permissions.approve !== 'boolean' || typeof device.permissions.stop !== 'boolean')
|
||||||
|
|| Object.entries(state.operations).some(([id, value]) => !dictionary(value) || id !== value.deviceId + ':' + value.requestId
|
||||||
|
|| !isId(value.deviceId) || !isId(value.requestId) || !isId(value.projectId) || !isId(value.sessionId) || !isId(value.taskId) || !isId(value.runId)
|
||||||
|
|| !['approve', 'stop'].includes(value.action) || !['pending', 'completed', 'unknown'].includes(value.status) || !/^[a-f0-9]{64}$/.test(value.hash)))) {
|
||||||
|
throw companionError('原手机登记无法核对;请保留数据并检查原Windows用户和目录。', 409);
|
||||||
|
}
|
||||||
return state ?? { schema: COMPANION_SCHEMA, binding: this.binding, gatewayId: randomUUID(), revision: 0, devices: {}, audit: [], operations: {} };
|
return state ?? { schema: COMPANION_SCHEMA, binding: this.binding, gatewayId: randomUUID(), revision: 0, devices: {}, audit: [], operations: {} };
|
||||||
}
|
}
|
||||||
mutate(action) {
|
mutate(action) {
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ export function mobileSession(store, runtime, session, redact = String) {
|
|||||||
fingerprint: approvalBinding(session, value), actionable: runtime.waiters.get(value.id)?.runId === session.runId })),
|
fingerprint: approvalBinding(session, value), actionable: runtime.waiters.get(value.id)?.runId === session.runId })),
|
||||||
changes: session.changes.filter(value => value.taskId === session.taskId).slice(-100).map(value => pick(value, ['id', 'path', 'reason', 'status', 'sha256', 'baseSha256', 'additions', 'deletions'])),
|
changes: session.changes.filter(value => value.taskId === session.taskId).slice(-100).map(value => pick(value, ['id', 'path', 'reason', 'status', 'sha256', 'baseSha256', 'additions', 'deletions'])),
|
||||||
checks: checks.slice(-12).map(value => ({ ...pick(value, ['id', 'status', 'summary', 'requiresVerification', 'createdAt', 'finishedAt']),
|
checks: checks.slice(-12).map(value => ({ ...pick(value, ['id', 'status', 'summary', 'requiresVerification', 'createdAt', 'finishedAt']),
|
||||||
results: (value.results ?? []).map(item => pick(item, ['name', 'status', 'exitCode', 'counts', 'durationMs'])) })),
|
results: (value.results ?? []).map(item => pick(item, ['name', 'status', 'exitCode', 'tests', 'durationMs'])) })),
|
||||||
reports: [...store.core.artifact.values()].filter(value => value.sessionId === session.id && value.taskId === session.taskId && reportKinds.has(value.kind))
|
reports: [...store.core.artifact.values()].filter(value => value.sessionId === session.id && value.taskId === session.taskId && reportKinds.has(value.kind))
|
||||||
.slice(-10).map(value => pick(value, ['id', 'kind', 'sha256', 'bytes', 'createdAt', 'taskId', 'runId'])),
|
.slice(-10).map(value => pick(value, ['id', 'kind', 'sha256', 'bytes', 'createdAt', 'taskId', 'runId'])),
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -31,7 +31,10 @@ const cookieName = '__Host-Workbench-Device';
|
|||||||
const privateV4 = value => /^10\./.test(value) || /^192\.168\./.test(value) || /^172\.(1[6-9]|2\d|3[01])\./.test(value);
|
const privateV4 = value => /^10\./.test(value) || /^192\.168\./.test(value) || /^172\.(1[6-9]|2\d|3[01])\./.test(value);
|
||||||
export function companionAddresses() {
|
export function companionAddresses() {
|
||||||
return Object.entries(os.networkInterfaces()).flatMap(([name, entries]) => (entries ?? []).filter(entry => entry.family === 'IPv4' && !entry.internal && privateV4(entry.address))
|
return Object.entries(os.networkInterfaces()).flatMap(([name, entries]) => (entries ?? []).filter(entry => entry.family === 'IPv4' && !entry.internal && privateV4(entry.address))
|
||||||
.map(entry => ({ name, address: entry.address })));
|
.map(entry => ({ name, address: entry.address }))).sort((left, right) => {
|
||||||
|
const virtual = value => /vethernet|hyper-v|wsl|virtual|vmware|vbox|docker|vpn|\btun\b|\btap\b|虚拟/i.test(value.name) ? 1 : 0;
|
||||||
|
return virtual(left) - virtual(right) || left.name.localeCompare(right.name);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
function reply(response, data, status = 200) {
|
function reply(response, data, status = 200) {
|
||||||
response.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' }); response.end(JSON.stringify(data));
|
response.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' }); response.end(JSON.stringify(data));
|
||||||
@@ -197,7 +200,12 @@ export class CompanionGateway {
|
|||||||
const device = this.registry.authenticate(cookie(request)); this.limit('device:' + device.id, 240);
|
const device = this.registry.authenticate(cookie(request)); this.limit('device:' + device.id, 240);
|
||||||
if (!this.sockets.has(request.socket)) request.socket.once('close', () => this.sockets.delete(request.socket));
|
if (!this.sockets.has(request.socket)) request.socket.once('close', () => this.sockets.delete(request.socket));
|
||||||
this.sockets.set(request.socket, device.id);
|
this.sockets.set(request.socket, device.id);
|
||||||
if (method === 'GET' && route === '/mobile-api/me') return reply(response, { device: { id: device.id, name: device.name, projectIds: device.projectIds, permissions: device.permissions, expiresAt: device.expiresAt, revision: device.revision }, gatewayId: this.registry.read().gatewayId });
|
if (method === 'GET' && route === '/mobile-api/me') {
|
||||||
|
const state = this.registry.read();
|
||||||
|
return reply(response, { device: { id: device.id, name: device.name, projectIds: device.projectIds, permissions: device.permissions, expiresAt: device.expiresAt, revision: device.revision },
|
||||||
|
gatewayId: state.gatewayId, operations: Object.values(state.operations).filter(value => value.deviceId === device.id && device.projectIds.includes(value.projectId)).slice(-20)
|
||||||
|
.map(value => ({ requestId: value.requestId, action: value.action, status: value.status === 'pending' ? 'unknown' : value.status, taskId: value.taskId, runId: value.runId, createdAt: value.createdAt })) });
|
||||||
|
}
|
||||||
if (method === 'POST' && route === '/mobile-api/rotate') {
|
if (method === 'POST' && route === '/mobile-api/rotate') {
|
||||||
fields(await input(request), []); const token = this.registry.rotate(device); setCookie(response, token, device.expiresAt); return reply(response, { rotated: true });
|
fields(await input(request), []); const token = this.registry.rotate(device); setCookie(response, token, device.expiresAt); return reply(response, { rotated: true });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,10 +6,10 @@
|
|||||||
|
|
||||||
1. [complete] A:默认关闭的独立HTTPS监听、宿主/用户/网关绑定、256位短效单次配对与原子设备登记;实际受信TLS、Windows DPAPI和54项关联检查通过,正式宿主未操作。
|
1. [complete] A:默认关闭的独立HTTPS监听、宿主/用户/网关绑定、256位短效单次配对与原子设备登记;实际受信TLS、Windows DPAPI和54项关联检查通过,正式宿主未操作。
|
||||||
2. [complete] B:项目范围、观察/审批/停止权限、会话轮换、撤销/到期、速率限制与脱敏审计;越权/直调/事务回滚通过。C–E新增流程继续独立验收。
|
2. [complete] B:项目范围、观察/审批/停止权限、会话轮换、撤销/到期、速率限制与脱敏审计;越权/直调/事务回滚通过。C–E新增流程继续独立验收。
|
||||||
3. [in_progress] C:桌面连接管理与独立手机PWA,复用原Task/Run、进展/差异/检查/预算/unknown与报告;界面已写入,实际宽窄屏尚待构建与观察。
|
3. [in_progress] C:桌面管理与独立PWA本地完成,1440/390/768px共7组流程通过;iPhone原生证书/cookie/主屏幕仍待F实机。
|
||||||
4. [pending] D:原审批ID/Task/Run/输入指纹/修订绑定、幂等与同一原任务停止;实际竞争和未知结果检查。
|
4. [complete] D:原审批ID/Task/Run/输入指纹/修订和幂等、真实Runtime单次命令、桌面竞争、手机停止原进程/心跳及更换Run拒绝通过;24项专项包含原unknown不重放。
|
||||||
5. [pending] E:授权项目原seq分页、断线补发/去重、工件SHA与撤销活动连接;原结果不重放。
|
5. [in_progress] E:授权项目原seq分页/去重、原差异/报告SHA、实际TLS撤销连接和浏览器断线/刷新本地通过;真实手机后台/切Wi-Fi仍待F。
|
||||||
6. [pending] F:全量源码/历史UI/独立发行及保留状态部署;真实iPhone配对、证书信任、后台/切网/撤销由设备结果判定,不用390px模拟代替。
|
6. [in_progress] F:准备全量源码/历史UI和独立iPhone候选;真实iPhone、发行与保留状态部署待验收,不用390px/中继模拟代替。
|
||||||
|
|
||||||
初读纠错:实际入口为src/server/index.mjs和src/server/runtime.mjs,一次猜测路径读取失败无副作用。首次计划批量补丁因findings标题锚点错误整批拒绝,未写入;移除错误锚点后重试。后续按实际文件定位。
|
初读纠错:实际入口为src/server/index.mjs和src/server/runtime.mjs,一次猜测路径读取失败无副作用。首次计划批量补丁因findings标题锚点错误整批拒绝,未写入;移除错误锚点后重试。后续按实际文件定位。
|
||||||
|
|
||||||
|
|||||||
@@ -4,7 +4,12 @@ import https from 'node:https';
|
|||||||
import fs from 'node:fs';
|
import fs from 'node:fs';
|
||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
import { randomBytes, randomUUID, createCipheriv, createDecipheriv, X509Certificate } from 'node:crypto';
|
import { randomBytes, randomUUID, createCipheriv, createDecipheriv, X509Certificate } from 'node:crypto';
|
||||||
import { fixture } from './helpers.mjs';
|
import { fixture, call, until, workspace } from './helpers.mjs';
|
||||||
|
import { Provider } from '../src/server/provider.mjs';
|
||||||
|
import { Runtime } from '../src/server/runtime.mjs';
|
||||||
|
import { installUpgrade } from '../src/server/hot-upgrade.mjs';
|
||||||
|
import { createTask, createRun } from '../src/shared/contracts/execution.mjs';
|
||||||
|
import http from 'node:http';
|
||||||
import { CompanionGateway } from '../src/server/companion-gateway.mjs';
|
import { CompanionGateway } from '../src/server/companion-gateway.mjs';
|
||||||
import { DeviceRegistry } from '../src/core/companion/device-registry.mjs';
|
import { DeviceRegistry } from '../src/core/companion/device-registry.mjs';
|
||||||
import { CompanionTLS } from '../src/core/companion/tls-authority.mjs';
|
import { CompanionTLS } from '../src/core/companion/tls-authority.mjs';
|
||||||
@@ -200,6 +205,9 @@ test('unknown original operation is recorded and never replayed after response f
|
|||||||
const value = { requestId: randomUUID(), taskId: f.session.taskId, runId: f.session.runId, revision: f.session.revision }, route = '/mobile-api/sessions/' + f.session.id + '/stop';
|
const value = { requestId: randomUUID(), taskId: f.session.taskId, runId: f.session.runId, revision: f.session.revision }, route = '/mobile-api/sessions/' + f.session.id + '/stop';
|
||||||
assert.equal((await f.request(route, value, { cookie })).status, 409);
|
assert.equal((await f.request(route, value, { cookie })).status, 409);
|
||||||
const retry = await f.request(route, value, { cookie }); assert.equal(retry.body.status, 'unknown'); assert.equal(calls, 1);
|
const retry = await f.request(route, value, { cookie }); assert.equal(retry.body.status, 'unknown'); assert.equal(calls, 1);
|
||||||
|
const me = await f.request('/mobile-api/me', undefined, { cookie });
|
||||||
|
assert.equal(me.body.operations.at(-1).status, 'unknown'); assert.equal(me.body.operations.at(-1).requestId, value.requestId);
|
||||||
|
assert.ok(!JSON.stringify(me.body).includes('credentialHash') && !JSON.stringify(me.body).includes('"hash"'));
|
||||||
});
|
});
|
||||||
|
|
||||||
test('revocation and gateway closure reject old access without invoking runtime stop', async t => {
|
test('revocation and gateway closure reject old access without invoking runtime stop', async t => {
|
||||||
@@ -221,3 +229,128 @@ test('real Windows CurrentUser DPAPI persists only a sealed CA and reopens it',
|
|||||||
await new CompanionTLS(f.registry).material('127.0.0.1');
|
await new CompanionTLS(f.registry).material('127.0.0.1');
|
||||||
assert.equal(tls.publicCertificate().sha256, hash);
|
assert.equal(tls.publicCertificate().sha256, hash);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
function realRuntime(f, command) {
|
||||||
|
const provider = new Provider(), runtime = new Runtime(f.store, provider);
|
||||||
|
provider.complete = async (_config, messages) => ({ message: messages.some(value => value.role === 'tool') ? { role: 'assistant', content: '本地夹具完成。' }
|
||||||
|
: { role: 'assistant', content: '', tool_calls: [call('owned-mobile-command', 'run_command', { command, reason: '原Runtime手机审批夹具' })] }, usage: null });
|
||||||
|
f.gateway.runtime = runtime; f.onCleanup(() => runtime.stopAll()); return runtime;
|
||||||
|
}
|
||||||
|
const fixtureCommand = source => (process.platform === 'win32' ? '& ' : '') + '"' + process.execPath + '" -e "' + source + '"';
|
||||||
|
|
||||||
|
test('mobile approval executes the original Runtime command exactly once and rejects the later desktop decision', async t => {
|
||||||
|
const f = await running(t), runtime = realRuntime(f, fixtureCommand("require('node:fs').appendFileSync('phone-approved.txt','one\\n')"));
|
||||||
|
const { cookie } = await f.pair({ ...f.grant, permissions: { observe: true, approve: true, stop: true } });
|
||||||
|
runtime.start(f.session.id, '只运行这个自有夹具命令。');
|
||||||
|
await until(() => f.session.status === 'awaiting_approval');
|
||||||
|
const before = await f.request('/mobile-api/sessions/' + f.session.id, undefined, { cookie }), approval = before.body.approvals[0];
|
||||||
|
const value = { requestId: randomUUID(), taskId: before.body.taskId, runId: before.body.runId, revision: before.body.revision,
|
||||||
|
approvalId: approval.id, fingerprint: approval.fingerprint, allow: true };
|
||||||
|
const route = '/mobile-api/sessions/' + f.session.id + '/approve';
|
||||||
|
const results = await Promise.all([f.request(route, value, { cookie }), f.request(route, value, { cookie })]);
|
||||||
|
assert.ok(results.every(value => value.status === 200));
|
||||||
|
assert.throws(() => runtime.decide(f.session.id, approval.id, true), /过期/);
|
||||||
|
await until(() => !runtime.active.has(f.session.id));
|
||||||
|
assert.equal(fs.readFileSync(path.join(f.projectRoot, 'phone-approved.txt'), 'utf8'), 'one\n');
|
||||||
|
assert.equal(f.session.events.filter(value => value.tool === 'run_command').length, 1);
|
||||||
|
assert.equal((await f.request(route, value, { cookie })).body.duplicate, true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('desktop rejection wins a concurrent mobile request and original command remains unexecuted', async t => {
|
||||||
|
const f = await running(t), runtime = realRuntime(f, fixtureCommand("require('node:fs').writeFileSync('should-not-exist.txt','no')"));
|
||||||
|
const { cookie } = await f.pair({ ...f.grant, permissions: { observe: true, approve: true, stop: true } });
|
||||||
|
runtime.start(f.session.id, '原桌面和手机审批竞争夹具。'); await until(() => f.session.status === 'awaiting_approval');
|
||||||
|
const before = await f.request('/mobile-api/sessions/' + f.session.id, undefined, { cookie }), approval = before.body.approvals[0];
|
||||||
|
const pending = f.request('/mobile-api/sessions/' + f.session.id + '/approve', { requestId: randomUUID(), taskId: before.body.taskId,
|
||||||
|
runId: before.body.runId, revision: before.body.revision, approvalId: approval.id, fingerprint: approval.fingerprint, allow: true }, { cookie });
|
||||||
|
runtime.decide(f.session.id, approval.id, false);
|
||||||
|
assert.equal((await pending).status, 409); await until(() => !runtime.active.has(f.session.id));
|
||||||
|
assert.equal(fs.existsSync(path.join(f.projectRoot, 'should-not-exist.txt')), false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('phone stop waits for the original process exit and prevents later heartbeats and command replay', async t => {
|
||||||
|
const f = await running(t), runtime = realRuntime(f, fixtureCommand("setInterval(()=>require('node:fs').appendFileSync('heartbeat.txt','x'),80)"));
|
||||||
|
const { cookie } = await f.pair({ ...f.grant, permissions: { observe: true, approve: true, stop: true } });
|
||||||
|
runtime.start(f.session.id, '手机停止自有心跳进程。'); await until(() => f.session.status === 'awaiting_approval');
|
||||||
|
runtime.decide(f.session.id, f.session.approvals.at(-1).id, true);
|
||||||
|
await until(() => fs.existsSync(path.join(f.projectRoot, 'heartbeat.txt')));
|
||||||
|
const before = await f.request('/mobile-api/sessions/' + f.session.id, undefined, { cookie });
|
||||||
|
const value = { requestId: randomUUID(), taskId: before.body.taskId, runId: before.body.runId, revision: before.body.revision };
|
||||||
|
const route = '/mobile-api/sessions/' + f.session.id + '/stop', result = await f.request(route, value, { cookie });
|
||||||
|
assert.equal(result.status, 200); assert.equal(runtime.active.has(f.session.id), false);
|
||||||
|
const bytes = fs.readFileSync(path.join(f.projectRoot, 'heartbeat.txt'));
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 250));
|
||||||
|
assert.deepEqual(fs.readFileSync(path.join(f.projectRoot, 'heartbeat.txt')), bytes);
|
||||||
|
assert.equal((await f.request(route, value, { cookie })).body.duplicate, true);
|
||||||
|
assert.equal(f.session.events.filter(value => value.tool === 'run_command').length, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Run replacement during parent-stop wait is rejected rather than stopping the new Run', async t => {
|
||||||
|
const f = setup(t), runtime = new Runtime(f.store, new Provider());
|
||||||
|
f.session.taskId = randomUUID(); f.session.runId = randomUUID(); const expected = { taskId: f.session.taskId, runId: f.session.runId };
|
||||||
|
let stopped = 0;
|
||||||
|
runtime.workers = { async stopParent() { f.session.runId = randomUUID(); runtime.active.set(f.session.id, { controller: { abort() { stopped++; } }, promise: Promise.resolve() }); } };
|
||||||
|
await assert.rejects(runtime.stop(f.session.id, expected), /已变化/); assert.equal(stopped, 0);
|
||||||
|
runtime.active.clear();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('diff pages preserve source SHA; report reads verify blobs and exclude unrelated artifact kinds', async t => {
|
||||||
|
const f = await running(t), task = createTask(f.session, '原差异及工件夹具', f.store.config);
|
||||||
|
const run = createRun(f.session, task, f.store.config);
|
||||||
|
f.store.core.task.set(task.id, task); f.store.core.run.set(run.id, run); f.session.taskId = task.id; f.session.runId = run.id;
|
||||||
|
const text = '+line\\n'.repeat(17000), change = { id: randomUUID(), taskId: f.session.taskId, sha256: companionHash('new file'), baseSha256: companionHash('old'), path: 'long/path.ts', diff: [{ value: text, added: true }] };
|
||||||
|
f.session.changes.push(change); f.store.save(f.session);
|
||||||
|
const report = f.store.artifactStore.write(f.session, null, '# 原报告\nfixture-secret\n', { kind: 'delivery-report-markdown', mediaType: 'text/markdown' });
|
||||||
|
const raw = f.store.artifactStore.write(f.session, null, 'never expose tool input', { kind: 'tool-result' });
|
||||||
|
f.store.core.artifact.set(report.id, report); f.store.core.artifact.set(raw.id, raw); f.store.save(f.session);
|
||||||
|
const { cookie } = await f.pair(); let assembled = '', offset = 0, hash;
|
||||||
|
for (let page = 0; page < 20; page++) {
|
||||||
|
const value = await f.request('/mobile-api/sessions/' + f.session.id + '/changes/' + change.id + '?offset=' + offset, undefined, { cookie }); assert.equal(value.status, 200);
|
||||||
|
assert.equal(value.body.sourceSha256, change.sha256); if (hash) assert.equal(value.body.sha256, hash); hash = value.body.sha256;
|
||||||
|
assembled += value.body.text; offset = value.body.nextOffset; if (!value.body.hasMore) break;
|
||||||
|
}
|
||||||
|
assert.equal(companionHash(assembled), hash); assert.ok(assembled.length > 100000);
|
||||||
|
const route = '/mobile-api/sessions/' + f.session.id + '/reports/';
|
||||||
|
const delivered = await f.request(route + report.id, undefined, { cookie }); assert.equal(delivered.status, 200);
|
||||||
|
assert.equal(delivered.body.sourceSha256, report.sha256); assert.equal(delivered.body.sha256, companionHash(delivered.body.text)); assert.equal(delivered.body.redacted, true);
|
||||||
|
assert.equal((await f.request(route + raw.id, undefined, { cookie })).status, 404);
|
||||||
|
fs.appendFileSync(path.join(f.store.artifactStore.root, report.relative), 'corrupt');
|
||||||
|
assert.equal((await f.request(route + report.id, undefined, { cookie })).status, 500);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('hot upgrade refuses an active gateway and restores closed gateway ownership on failure', async t => {
|
||||||
|
const f = setup(t), provider = new Provider(), runtime = new Runtime(f.store, provider), server = http.createServer((_request, response) => response.end('old'));
|
||||||
|
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
|
||||||
|
f.onCleanup(() => new Promise(resolve => server.close(resolve)));
|
||||||
|
const context = { server, store: f.store, provider, runtime, token: 'test-upgrade-owned', clients: new Set(), started: Date.now() };
|
||||||
|
const gateway = { server: { listening: true }, busy: false }; server.workbenchCompanion = gateway;
|
||||||
|
assert.throws(() => installUpgrade(context, { appDirectory: workspace, updateServiceInfo: false }), /Close the mobile/);
|
||||||
|
gateway.server = null;
|
||||||
|
f.store.claimRuntime = () => { throw new Error('fixture upgrade failure'); };
|
||||||
|
assert.throws(() => installUpgrade(context, { appDirectory: workspace, updateServiceInfo: false }), /fixture upgrade failure/);
|
||||||
|
assert.equal(server.workbenchCompanion, gateway);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('damaged device permissions or expiry fail closed and never overwrite the original registry', t => {
|
||||||
|
const f = setup(t), accepted = f.registry.consume(f.registry.pair(f.grant, 'g').token, 'phone', 'g');
|
||||||
|
const original = f.store.storage.meta('mobileCompanion');
|
||||||
|
for (const damage of [value => { value.devices[accepted.device.id].permissions.stop = 'true'; }, value => { value.devices[accepted.device.id].expiresAt = 'invalid'; }]) {
|
||||||
|
const changed = structuredClone(original); damage(changed); f.store.storage.setMeta('mobileCompanion', changed);
|
||||||
|
assert.throws(() => f.registry.authenticate(accepted.token), /原手机登记无法核对/);
|
||||||
|
assert.throws(() => f.registry.initialize(), /原手机登记无法核对/);
|
||||||
|
assert.deepEqual(f.store.storage.meta('mobileCompanion'), changed);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('device revocation destroys its actual authenticated TLS connection', async t => {
|
||||||
|
const f = await running(t), { cookie, device } = await f.pair();
|
||||||
|
const agent = new https.Agent({ keepAlive: true, ca: f.gateway.registry.read().tls.certificate });
|
||||||
|
let socket;
|
||||||
|
await new Promise((resolve, reject) => {
|
||||||
|
const request = https.get(f.gateway.origin + '/mobile-api/me', { agent, servername: '', headers: { Cookie: cookie } }, response => {
|
||||||
|
socket = response.socket; response.resume(); response.on('end', resolve);
|
||||||
|
}); request.on('error', reject);
|
||||||
|
});
|
||||||
|
assert.ok(socket && !socket.destroyed); f.gateway.revoke(device.id, device.revision);
|
||||||
|
await until(() => socket.destroyed); agent.destroy();
|
||||||
|
});
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import { defineConfig } from 'vite';
|
import { defineConfig } from 'vite';
|
||||||
import react from '@vitejs/plugin-react';
|
import react from '@vitejs/plugin-react';
|
||||||
|
import { resolve } from 'node:path';
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
plugins: [react()],
|
plugins: [react()],
|
||||||
build: { outDir: 'dist-client', sourcemap: false },
|
build: { outDir: 'dist-client', sourcemap: false, manifest: true, rollupOptions: { input: { desktop: resolve('index.html'), mobile: resolve('mobile.html') } } },
|
||||||
server: { proxy: { '/api': 'http://127.0.0.1:4318' } },
|
server: { proxy: { '/api': 'http://127.0.0.1:4318' } },
|
||||||
});
|
});
|
||||||
|
|||||||