跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

提交记录
新增mobile/.gitignore+6 −0看文件
@@ -0,0 +1,6 @@
1新增:.build/
2新增:android/.gradle/
3新增:android/local.properties
4新增:android/**/build/
5新增:ios/**/xcuserdata/
6新增:*.xcuserstate
新增mobile/README.md+125 −0看文件
@@ -0,0 +1,125 @@
1新增:# 在手机上使用 Cage
2新增:
3新增:手机 Cage 是远程客户端。点首页中央的「连接电脑」,用二维码或配对码连接主机,即可查看项目、接续 Claude Code 会话和处理工具审批。配对后还可在手机上操作主机里的浏览器和 Claude Desktop。代理、时区和语言在远程主机的 Cage 中设置。右上角的设置提供主题和电脑连接选项。
4新增:
5新增:Android 开发版提供 arm64 调试 APK。iPhone 设备版可通过 Xcode 为自己的测试设备签名后安装。
6新增:
7新增:## 扫码连接电脑
8新增:
9新增:1. 在电脑上打开并解锁 Cage,选择本机工作台,在「设置 → 远程连接 → 手机连接」点「生成配对二维码」。电脑显示二维码后,用手机扫描。
10新增:2. 在手机 Cage 首页中央点「连接电脑」,在弹出的卡片里选择扫码,允许使用相机,把电脑上的二维码完整放入取景框中。二维码约两分钟有效,过期后可在电脑上刷新。
11新增:3. 扫码成功后手机会保存这台电脑并打开工作台。工作台默认打开左侧栏。点「浏览器」「Claude.ai」或「Claude Desktop」进入对应画面,「Claude Code」分区列出各个项目。点项目名展开或收起会话,点会话进入对话。左上角的 Cage Logo 可重新打开侧栏,右上角图标表示当前工具。下次打开手机,从「连接电脑」卡片重新连接已配对的电脑。电脑重启后,打开 Cage 即可恢复扫码配对的连接。
12新增:
13新增:二维码只交给希望授权的手机。要更换扫码配对的手机,先在电脑「设置 → 远程连接」移除旧手机,再为新手机生成二维码。手机可以在指纹配对或主机设置中忘记本机保存的连接。
14新增:
15新增:暂不连接时,可点击卡片外侧收起;Android 也可使用系统返回,iPhone 可使用系统下滑手势。配对过程中需等待本次操作结束。
16新增:
17新增:## 用手机操作远程浏览器
18新增:
19新增:1. 更新电脑和手机的 Cage,并在电脑上启动环境,等待网络检查通过。如果界面提示客机版本较旧,在电脑上关闭并重新启动环境,让新的浏览器组件生效。
20新增:2. 通过电脑生成的二维码或配对码连接。已配对手机可以直接重新连接。
21新增:3. 在手机左侧栏点「浏览器」,会打开电脑 Cage 浏览器设置中的「新标签页地址」。电脑保存新地址后,下次从手机打开浏览器即生效。「Claude.ai」入口始终直达 Claude.ai。
22新增:4. 点网页中的输入框后,打开「输入文字」使用手机键盘。先点勾号把文字插入网页,需要提交时再点「发送回车」。如果发生断线,先读取最新画面再决定是否重新输入。
23新增:
24新增:点手机浏览器底部的「收藏夹」,可以按电脑上的文件夹浏览收藏、打开网址,或把当前页存入指定文件夹。两端共用配对主机的收藏。另一端有更改时,重新打开收藏夹,或在手机上点刷新即可看到。
25新增:
26新增:手机和电脑各用自己的浏览器窗口,首次访问需要在手机的远程窗口里登录。同一配对重新打开后可以沿用已保存的登录资料。网络出口、时区和首选语言取自主机的 Cage。关闭浏览器会结束手机的浏览进程。取消配对或锁定 Cage 会中止访问。
27新增:
28新增:手机浏览器按手机宽度请求移动网页。拖动时连续发送滚动位移,页面静止时只检查是否有变化。图像和输入经配对通道传输,反馈速度受网络往返延迟影响。支持公网 IPv4 的 HTTP 和 HTTPS。需要另开弹窗登录、上传或下载附件、播放声音的网页场景尚未接入。模拟器扫码示例用于预览侧栏和对话,测试真实窗口请用配对码连接电脑。
29新增:
30新增:## 用手机操作 Claude Desktop
31新增:
32新增:在电脑的 Cage 环境中安装 Claude Desktop 并通过网络检查。已配对的手机连接电脑后打开左侧栏,点「Claude Desktop」,等待应用画面出现。
33新增:
34新增:手机直接访问电脑上同一份 Claude Desktop,共用账号、应用数据和当前窗口。电脑已登录时,手机可以直接接续。手机的点击、输入和切换页面会同步显示在电脑上,两端共用鼠标与输入焦点。应用尚未运行时,由电脑的 Cage 启动。
35新增:
36新增:新版手机端会自动读取屏幕像素密度,使远程画面匹配当前显示分辨率。手机进入后,共享窗口按手机宽度重新排版,旋转屏幕或弹出键盘时跟随调整,电脑也会同步显示这个布局。点「放大阅读」可查看局部。退出手机的 Desktop 页面后恢复电脑尺寸,电脑上的应用和任务继续运行。需要重新登录或选择本机文件时,在电脑上完成。
37新增:
38新增:## 使用指纹和文件配对
39新增:
40新增:相机不可用时,在电脑点「复制配对码」,再在手机首页点「连接电脑」,选择配对码入口并粘贴这串一次性配对码。使用命令行连接助手时,从手机右上角的设置进入指纹与连接文件选项,再按以下步骤交换指纹与文件。
41新增:
42新增:在电脑上运行包含移动会话接口的 Cage,解锁账户并启动工作环境。电脑上的连接助手可在仓库根目录构建。
43新增:
44新增:```sh
45新增:go build -o ./cage-mobile-link ./cmd/cage-mobile-link
46新增:```
47新增:
48新增:1. 在电脑上用 `cage-mobile-link init --state <新私有目录>` 创建主机身份,记录显示的公开指纹。以后可用 `fingerprint --state <原目录>` 再次查看。
49新增:2. 手机打开 Cage,在“这台手机的指纹”下复制公开指纹。对照手机屏幕,在电脑上执行 `cage-mobile-link trust --state <原目录> --peer-pin <已核对的手机指纹>`。
50新增:3. 在电脑上生成这台手机的连接文件,并保持连接助手运行。官方中继允许直接创建连接。请填写主机身份目录、新连接文件路径,以及 Cage 后台程序和配置文件的绝对路径。
51新增:
52新增:```sh
53新增:./cage-mobile-link host --state "$host_state" --connection-out "$new_connection_json" \
54新增: --cage-bin "$cage_binary" --config "$cage_config"
55新增:```
56新增:
57新增:4. 通过自己的私有文件传输方式将 JSON 送到手机。在 App 中点“导入连接文件”,对照**电脑独立显示的公开指纹**,确认与手机上填入的指纹一致。勾选核对项,点“保存已核对的主机”,然后点“重新连接”。换用另一台电脑或更换电脑密钥时需再次核对。
58新增:
59新增:进入工作台后,在左侧栏的「Claude Code」下选择项目,新建或继续会话。工具需要授权时,手机显示本次调用的具体参数,可选择“允许一次”或“拒绝”。此入口列出通过 Cage 会话界面创建的对话,普通终端里手工启动的 CLI 仍在原终端操作。
60新增:
61新增:续聊前,Cage 检查原会话使用的账号和模型服务地址,避免把历史发到另一个服务。主机无法确认所用配置的身份时,手机会提示本次仅支持一轮;可以新建会话再发消息。
62新增:
63新增:## 使用自己的 VPS
64新增:
65新增:部署[自建中继](../deploy/relay/README.md)后,在桌面「设置 → 远程连接」选择「自建中继」,填写 VPS 的 HTTPS 地址并保存。手机进入设置并展开「中继设置」,开启自建中继,填写同一地址并保存。需要管理令牌的自建中继只在电脑端填写令牌。选择官方中继并保存可恢复默认。新配对采用保存的地址,手机导入连接文件时会自动填入同一地址。自建中继要求管理令牌时,在上面的 host 命令中同时指定 `--relay` 和 `--admin-token-file`,明确私有令牌的接收方。
66新增:
67新增:已配对的手机继续使用原来的地址与凭据。要迁往另一台中继,扫码设备在桌面设置中移除后重新扫码;命令行配对设备用下文的 revoke 撤销后重新登记。
68新增:
69新增:## 下次使用
70新增:
71新增:点左上角的 Cage Logo 打开侧栏,点侧栏底部「退出」回到首页。需要切换电脑时,点首页的「连接电脑」,在卡片的「已连接设备」中选另一台电脑。长按设备可取消这次连接,配对记录会保留。
72新增:
73新增:Claude Code 的项目可以各自展开,方便在不同项目的会话之间切换。会话进度自动刷新;读取失败时可以点提示中的「重新读取」。聊天通过气泡区分消息来源,输入框为大圆角,右侧箭头用于发送,运行时显示停止按钮。
74新增:
75新增:在已配对的手机上,短暂断网时可以留在当前会话。网络恢复后,工作台再次读取进度时会重新验证电脑身份并恢复连接,输入框里的草稿仍在。若发消息或审批时断线,先看电脑返回的最新记录。已收到的消息会显示在历史里;电脑仍在等待同一项审批时,手机会重新显示可选的「允许一次」和「拒绝」。
76新增:
77新增:主动断开或重新打开 App 后,从「连接电脑」卡片选择已配对的电脑,再打开原会话即可继续。如果使用命令行连接助手,电脑重启后先启动 Cage,再运行以下命令恢复该助手的配对:
78新增:
79新增:```sh
80新增:./cage-mobile-link host --state "$host_state" --serve-saved
81新增:```
82新增:
83新增:连接文件包含中继地址、电脑公开指纹和持久查询凭据,请只交给配对手机。Android 用独立的 Android Keystore AES-GCM 密钥加密查询凭据,并将密文绑定到已核对的中继地址和指纹。iPhone 将记录保存在仅限本设备、解锁时可访问的 Keychain 项中。设备签名私钥由 Android Keystore 或 iPhone Secure Enclave 保管。仅 iPhone 模拟器的 Debug 构建使用单独的软件测试密钥,设置中的设备指纹旁会注明。网页只访问本机受限的会话接口。
84新增:
85新增:在手机点“忘记主机”会清除保存的主机地址、指纹和重连凭据,手机仍使用自己的设备签名身份。要同时在电脑端撤销访问,执行 `cage-mobile-link revoke --state <主机身份目录>`。使用旧版单次邀请时,在电脑以 `--invitation-out <新邀请文件>` 代替 `--connection-out`,手机手工核对并保存中继地址与电脑指纹,再通过同一个导入入口打开邀请。单次邀请断开后需要新邀请。
86新增:
87新增:## 构建 Android 调试 APK
88新增:
89新增:准备项目要求的 Go 和 Node.js、JDK 21、Android SDK 平台 35、Build Tools 35.0.0,以及 NDK r27c 或兼容版本。设置 `ANDROID_HOME`、`ANDROID_NDK_HOME` 和 `JAVA_HOME` 到对应的安装目录。从仓库根目录执行:
90新增:
91新增:```sh
92新增:npm ci --prefix ui
93新增:bash mobile/build.sh android
94新增:```
95新增:
96新增:可安装的 APK 位于 `mobile/.build/android/cage-mobile-debug.apk`,支持 Android 8.0(API 26)及更新的 arm64 设备。手机需要支持现代 JavaScript 的 Android System WebView。脚本使用 Android SDK 自带的编译和签名工具,并校验 APK 签名和 16 KiB 对齐。调试签名密钥保存在 `mobile/.build/android/development.p12`。要覆盖安装调试版本并保留手机身份,请保留这份签名密钥。
97新增:
98新增:## 构建 iPhone 客户端
99新增:
100新增:在 iPhone 模拟器中,首页点「连接电脑 → 扫码连接」可预览扫码画面。约两秒后自动进入带「模拟器预览」标识的示例工作台,提供两台示例设备,支持切换项目、新建会话、发送示例消息和查看工具审批;左上角 Logo 返回首页后,仍可从连接卡片进入。示例只在内存中运行,不连接电脑、不调用模型,也不保存主机凭据。真机继续使用相机扫码和真实配对。
101新增:
102新增:在配有完整 Xcode 和 iOS SDK 的 Mac 上构建。先按 Mac 的系统版本选择兼容的 Xcode。若开发工具仍指向 Command Line Tools,可以在当前终端设置 `export DEVELOPER_DIR="/Applications/Xcode.app/Contents/Developer"`。用 `xcrun --sdk iphoneos --show-sdk-path` 确认设备 SDK 已就绪。客户端支持 iOS 17 及以上,测试设备需支持 Secure Enclave。[Apple 版本兼容表](https://developer.apple.com/xcode/system-requirements)
103新增:
104新增:```sh
105新增:npm ci --prefix ui
106新增:bash mobile/build.sh ios
107新增:```
108新增:
109新增:这条命令构建设备 App 和模拟器使用的 XCFramework。真机调试时,打开 `mobile/ios/CageMobile.xcodeproj`,选择 `CageMobile` 方案,在应用 target 的签名设置中选择自己的开发团队,再选择已配对并开启开发者模式的 iPhone 运行。配对凭据绑定原应用标识,覆盖安装应使用相同的标识和开发团队。[Apple 真机运行说明](https://developer.apple.com/documentation/xcode/running-your-app-on-simulated-or-physical-devices)
110新增:
111新增:**需要交给已登记测试设备的 IPA 时**,在 Mac 上为该 App 配置好 Apple Development 签名身份和包含目标设备的描述文件,把开发团队的十位 Team ID 填入 `CAGE_TEAM_ID` 再运行:
112新增:
113新增:```sh
114新增:bash mobile/build.sh ios-ipa "$CAGE_TEAM_ID"
115新增:```
116新增:
117新增:脚本重新构建并归档,使用 Xcode 的 Debugging 选项导出到本机,检查 IPA 中的签名和描述文件后打印文件路径。每次导出使用独立目录。已有构建脚本也可继续使用 `ios-ipa-basic` 导出同样功能的远程客户端。[Apple 已登记设备分发说明](https://developer.apple.com/documentation/xcode/distributing-your-app-to-registered-devices)
118新增:
119新增:## 维护入口
120新增:
121新增:两端的首页、配对卡片和设置使用各平台的原生界面。连接电脑后,两端使用同一份[远程工作台界面](../ui/src/mobile-cli/main.jsx)和 [Go 客户端](../internal/mobilelink/nativeclient/client.go)。Go 绑定的版本固定在 `bindings/go.mod`。Android 和 iOS 各自负责设备签名、核对电脑指纹、导入邀请和限制 WebView 导航。Go 在随机回环端口提供 App 内的界面资源和允许的会话接口,WebView 通过单次入口换取本地 HttpOnly 会话。Android 的网络安全配置、iOS 的 ATS 配置仅为数值回环地址 `127.0.0.1` 开放本地 HTTP。
122新增:
123新增:## 移动包第三方许可
124新增:
125新增:构建脚本根据远程客户端实际使用的 Go 依赖生成许可说明,并随包附带 AndroidX 和 ZXing 的许可文件。
新增mobile/android/AndroidManifest.xml+22 −0看文件
@@ -0,0 +1,22 @@
1新增:<?xml version="1.0" encoding="utf-8"?>
2新增:<manifest xmlns:android="http://schemas.android.com/apk/res/android"
3新增: package="io.github.leexeo.cage.mobile" android:versionCode="1" android:versionName="development">
4新增: <uses-sdk android:minSdkVersion="26" android:targetSdkVersion="35"/>
5新增: <uses-permission android:name="android.permission.INTERNET"/>
6新增: <uses-permission android:name="android.permission.CAMERA"/>
7新增: <uses-feature android:name="android.hardware.camera" android:required="false"/>
8新增: <application android:label="Cage" android:icon="@drawable/cage_icon" android:allowBackup="false"
9新增: android:networkSecurityConfig="@xml/network_security_config"
10新增: android:theme="@android:style/Theme.Material.Light.NoActionBar"
11新增: android:extractNativeLibs="true">
12新增: <activity android:name=".ScanActivity" android:exported="false" />
13新增: <activity android:name=".MainActivity" android:exported="true"
14新增: android:configChanges="orientation|screenSize|keyboardHidden|screenLayout"
15新增: android:windowSoftInputMode="adjustResize">
16新增: <intent-filter>
17新增: <action android:name="android.intent.action.MAIN"/>
18新增: <category android:name="android.intent.category.LAUNCHER"/>
19新增: </intent-filter>
20新增: </activity>
21新增: </application>
22新增:</manifest>
新增mobile/android/fetch-webkit.sh+12 −0看文件
@@ -0,0 +1,12 @@
1新增:#!/bin/bash
2新增:# Pinned AndroidX artifacts from Google's Maven repository.
3新增:set -euo pipefail
4新增:build="$1"
5新增:fetch_aar() {
6新增: local name="$1" url="$2" digest="$3"
7新增: if [[ ! -s "$build/$name.aar" ]]; then curl -fLsS --retry 2 "$url" -o "$build/$name.aar"; fi
8新增: printf '%s %s\n' "$digest" "$build/$name.aar" | shasum -a 256 --check --status
9新增: unzip -p "$build/$name.aar" classes.jar > "$build/$name.jar"
10新增:}
11新增:fetch_aar webkit-1.14.0 https://dl.google.com/dl/android/maven2/androidx/webkit/webkit/1.14.0/webkit-1.14.0.aar 265604786ea1c9679e3f860f7f13072375c141f46db9092ed8ef5ecd599a516d
12新增:fetch_aar core-1.1.0 https://dl.google.com/dl/android/maven2/androidx/core/core/1.1.0/core-1.1.0.aar 76c7cfbe596fe3c09a6983bf1c89e889299c08ac9a3b52ce5182a088d056647e
新增mobile/android/licenses/ZXing-LICENSE.txt+245 −0看文件
@@ -0,0 +1,245 @@
1新增: Apache License
2新增: Version 2.0, January 2004
3新增: http://www.apache.org/licenses/
4新增:
5新增: TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6新增:
7新增: 1. Definitions.
8新增:
9新增: "License" shall mean the terms and conditions for use, reproduction,
10新增: and distribution as defined by Sections 1 through 9 of this document.
11新增:
12新增: "Licensor" shall mean the copyright owner or entity authorized by
13新增: the copyright owner that is granting the License.
14新增:
15新增: "Legal Entity" shall mean the union of the acting entity and all
16新增: other entities that control, are controlled by, or are under common
17新增: control with that entity. For the purposes of this definition,
18新增: "control" means (i) the power, direct or indirect, to cause the
19新增: direction or management of such entity, whether by contract or
20新增: otherwise, or (ii) ownership of fifty percent (50%) or more of the
21新增: outstanding shares, or (iii) beneficial ownership of such entity.
22新增:
23新增: "You" (or "Your") shall mean an individual or Legal Entity
24新增: exercising permissions granted by this License.
25新增:
26新增: "Source" form shall mean the preferred form for making modifications,
27新增: including but not limited to software source code, documentation
28新增: source, and configuration files.
29新增:
30新增: "Object" form shall mean any form resulting from mechanical
31新增: transformation or translation of a Source form, including but
32新增: not limited to compiled object code, generated documentation,
33新增: and conversions to other media types.
34新增:
35新增: "Work" shall mean the work of authorship, whether in Source or
36新增: Object form, made available under the License, as indicated by a
37新增: copyright notice that is included in or attached to the work
38新增: (an example is provided in the Appendix below).
39新增:
40新增: "Derivative Works" shall mean any work, whether in Source or Object
41新增: form, that is based on (or derived from) the Work and for which the
42新增: editorial revisions, annotations, elaborations, or other modifications
43新增: represent, as a whole, an original work of authorship. For the purposes
44新增: of this License, Derivative Works shall not include works that remain
45新增: separable from, or merely link (or bind by name) to the interfaces of,
46新增: the Work and Derivative Works thereof.
47新增:
48新增: "Contribution" shall mean any work of authorship, including
49新增: the original version of the Work and any modifications or additions
50新增: to that Work or Derivative Works thereof, that is intentionally
51新增: submitted to Licensor for inclusion in the Work by the copyright owner
52新增: or by an individual or Legal Entity authorized to submit on behalf of
53新增: the copyright owner. For the purposes of this definition, "submitted"
54新增: means any form of electronic, verbal, or written communication sent
55新增: to the Licensor or its representatives, including but not limited to
56新增: communication on electronic mailing lists, source code control systems,
57新增: and issue tracking systems that are managed by, or on behalf of, the
58新增: Licensor for the purpose of discussing and improving the Work, but
59新增: excluding communication that is conspicuously marked or otherwise
60新增: designated in writing by the copyright owner as "Not a Contribution."
61新增:
62新增: "Contributor" shall mean Licensor and any individual or Legal Entity
63新增: on behalf of whom a Contribution has been received by Licensor and
64新增: subsequently incorporated within the Work.
65新增:
66新增: 2. Grant of Copyright License. Subject to the terms and conditions of
67新增: this License, each Contributor hereby grants to You a perpetual,
68新增: worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69新增: copyright license to reproduce, prepare Derivative Works of,
70新增: publicly display, publicly perform, sublicense, and distribute the
71新增: Work and such Derivative Works in Source or Object form.
72新增:
73新增: 3. Grant of Patent License. Subject to the terms and conditions of
74新增: this License, each Contributor hereby grants to You a perpetual,
75新增: worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76新增: (except as stated in this section) patent license to make, have made,
77新增: use, offer to sell, sell, import, and otherwise transfer the Work,
78新增: where such license applies only to those patent claims licensable
79新增: by such Contributor that are necessarily infringed by their
80新增: Contribution(s) alone or by combination of their Contribution(s)
81新增: with the Work to which such Contribution(s) was submitted. If You
82新增: institute patent litigation against any entity (including a
83新增: cross-claim or counterclaim in a lawsuit) alleging that the Work
84新增: or a Contribution incorporated within the Work constitutes direct
85新增: or contributory patent infringement, then any patent licenses
86新增: granted to You under this License for that Work shall terminate
87新增: as of the date such litigation is filed.
88新增:
89新增: 4. Redistribution. You may reproduce and distribute copies of the
90新增: Work or Derivative Works thereof in any medium, with or without
91新增: modifications, and in Source or Object form, provided that You
92新增: meet the following conditions:
93新增:
94新增: (a) You must give any other recipients of the Work or
95新增: Derivative Works a copy of this License; and
96新增:
97新增: (b) You must cause any modified files to carry prominent notices
98新增: stating that You changed the files; and
99新增:
100新增: (c) You must retain, in the Source form of any Derivative Works
101新增: that You distribute, all copyright, patent, trademark, and
102新增: attribution notices from the Source form of the Work,
103新增: excluding those notices that do not pertain to any part of
104新增: the Derivative Works; and
105新增:
106新增: (d) If the Work includes a "NOTICE" text file as part of its
107新增: distribution, then any Derivative Works that You distribute must
108新增: include a readable copy of the attribution notices contained
109新增: within such NOTICE file, excluding those notices that do not
110新增: pertain to any part of the Derivative Works, in at least one
111新增: of the following places: within a NOTICE text file distributed
112新增: as part of the Derivative Works; within the Source form or
113新增: documentation, if provided along with the Derivative Works; or,
114新增: within a display generated by the Derivative Works, if and
115新增: wherever such third-party notices normally appear. The contents
116新增: of the NOTICE file are for informational purposes only and
117新增: do not modify the License. You may add Your own attribution
118新增: notices within Derivative Works that You distribute, alongside
119新增: or as an addendum to the NOTICE text from the Work, provided
120新增: that such additional attribution notices cannot be construed
121新增: as modifying the License.
122新增:
123新增: You may add Your own copyright statement to Your modifications and
124新增: may provide additional or different license terms and conditions
125新增: for use, reproduction, or distribution of Your modifications, or
126新增: for any such Derivative Works as a whole, provided Your use,
127新增: reproduction, and distribution of the Work otherwise complies with
128新增: the conditions stated in this License.
129新增:
130新增: 5. Submission of Contributions. Unless You explicitly state otherwise,
131新增: any Contribution intentionally submitted for inclusion in the Work
132新增: by You to the Licensor shall be under the terms and conditions of
133新增: this License, without any additional terms or conditions.
134新增: Notwithstanding the above, nothing herein shall supersede or modify
135新增: the terms of any separate license agreement you may have executed
136新增: with Licensor regarding such Contributions.
137新增:
138新增: 6. Trademarks. This License does not grant permission to use the trade
139新增: names, trademarks, service marks, or product names of the Licensor,
140新增: except as required for reasonable and customary use in describing the
141新增: origin of the Work and reproducing the content of the NOTICE file.
142新增:
143新增: 7. Disclaimer of Warranty. Unless required by applicable law or
144新增: agreed to in writing, Licensor provides the Work (and each
145新增: Contributor provides its Contributions) on an "AS IS" BASIS,
146新增: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147新增: implied, including, without limitation, any warranties or conditions
148新增: of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149新增: PARTICULAR PURPOSE. You are solely responsible for determining the
150新增: appropriateness of using or redistributing the Work and assume any
151新增: risks associated with Your exercise of permissions under this License.
152新增:
153新增: 8. Limitation of Liability. In no event and under no legal theory,
154新增: whether in tort (including negligence), contract, or otherwise,
155新增: unless required by applicable law (such as deliberate and grossly
156新增: negligent acts) or agreed to in writing, shall any Contributor be
157新增: liable to You for damages, including any direct, indirect, special,
158新增: incidental, or consequential damages of any character arising as a
159新增: result of this License or out of the use or inability to use the
160新增: Work (including but not limited to damages for loss of goodwill,
161新增: work stoppage, computer failure or malfunction, or any and all
162新增: other commercial damages or losses), even if such Contributor
163新增: has been advised of the possibility of such damages.
164新增:
165新增: 9. Accepting Warranty or Additional Liability. While redistributing
166新增: the Work or Derivative Works thereof, You may choose to offer,
167新增: and charge a fee for, acceptance of support, warranty, indemnity,
168新增: or other liability obligations and/or rights consistent with this
169新增: License. However, in accepting such obligations, You may act only
170新增: on Your own behalf and on Your sole responsibility, not on behalf
171新增: of any other Contributor, and only if You agree to indemnify,
172新增: defend, and hold each Contributor harmless for any liability
173新增: incurred by, or claims asserted against, such Contributor by reason
174新增: of your accepting any such warranty or additional liability.
175新增:
176新增: END OF TERMS AND CONDITIONS
177新增:
178新增: APPENDIX: How to apply the Apache License to your work.
179新增:
180新增: To apply the Apache License to your work, attach the following
181新增: boilerplate notice, with the fields enclosed by brackets "[]"
182新增: replaced with your own identifying information. (Don't include
183新增: the brackets!) The text should be enclosed in the appropriate
184新增: comment syntax for the file format. We also recommend that a
185新增: file or class name and description of purpose be included on the
186新增: same "printed page" as the copyright notice for easier
187新增: identification within third-party archives.
188新增:
189新增: Copyright [yyyy] [name of copyright owner]
190新增:
191新增: Licensed under the Apache License, Version 2.0 (the "License");
192新增: you may not use this file except in compliance with the License.
193新增: You may obtain a copy of the License at
194新增:
195新增: http://www.apache.org/licenses/LICENSE-2.0
196新增:
197新增: Unless required by applicable law or agreed to in writing, software
198新增: distributed under the License is distributed on an "AS IS" BASIS,
199新增: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200新增: See the License for the specific language governing permissions and
201新增: limitations under the License.
202新增:
203新增:========================================================================
204新增:jai-imageio
205新增:========================================================================
206新增:
207新增:Copyright (c) 2005 Sun Microsystems, Inc.
208新增:Copyright © 2010-2014 University of Manchester
209新增:Copyright © 2010-2015 Stian Soiland-Reyes
210新增:Copyright © 2015 Peter Hull
211新增:All Rights Reserved.
212新增:
213新增:Redistribution and use in source and binary forms, with or without
214新增:modification, are permitted provided that the following conditions
215新增:are met:
216新增:
217新增:- Redistribution of source code must retain the above copyright
218新增: notice, this list of conditions and the following disclaimer.
219新增:
220新增:- Redistribution in binary form must reproduce the above copyright
221新增: notice, this list of conditions and the following disclaimer in
222新增: the documentation and/or other materials provided with the
223新增: distribution.
224新增:
225新增:Neither the name of Sun Microsystems, Inc. or the names of
226新增:contributors may be used to endorse or promote products derived
227新增:from this software without specific prior written permission.
228新增:
229新增:This software is provided "AS IS," without a warranty of any
230新增:kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
231新增:WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
232新增:FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
233新增:EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
234新增:NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
235新增:USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
236新增:DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
237新增:ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
238新增:CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
239新增:REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
240新增:INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
241新增:POSSIBILITY OF SUCH DAMAGES.
242新增:
243新增:You acknowledge that this software is not designed or intended for
244新增:use in the design, construction, operation or maintenance of any
245新增:nuclear facility.
文件末尾没有换行
新增mobile/android/package.sh+49 −0看文件
@@ -0,0 +1,49 @@
1新增:#!/bin/bash
2新增:# Assemble a development APK from the local AAR, the bundled UI and Android SDK tools.
3新增:set -euo pipefail
4新增:mobile_dir="$(cd "$(dirname "$0")/.." && pwd)"
5新增:android="$mobile_dir/android"
6新增:build="$mobile_dir/.build/android"
7新增:aar="$build/Cagemobile.aar"
8新增:sdk="${ANDROID_HOME:?Set ANDROID_HOME to the Android SDK directory}"
9新增:tools="$sdk/build-tools/${CAGE_BUILD_TOOLS:-35.0.0}"
10新增:platform="$sdk/platforms/android-${CAGE_ANDROID_PLATFORM:-35}/android.jar"
11新增:if [[ -n "${JAVA_HOME:-}" ]]; then export PATH="$JAVA_HOME/bin:$PATH"; fi
12新增:[[ -f "$aar" && -f "$mobile_dir/.build/resources/mobile-ui/mobile.html" && -f "$platform" ]] || { echo 'Missing native AAR, mobile UI, or Android platform.' >&2; exit 1; }
13新增:mkdir -p "$build"
14新增:work="$(mktemp -d "$build/package.XXXXXX")"
15新增:trap 'rm -rf "$work"' EXIT
16新增:mkdir -p "$work/classes" "$work/dex" "$work/aar" "$work/apk/lib/arm64-v8a"
17新增:mkdir -p "$work/brand/drawable-nodpi"
18新增:cp "$mobile_dir/assets/pair-devices.png" "$work/brand/drawable-nodpi/pair_devices.png"
19新增:cp "$mobile_dir/../ui/src/logo.png" "$work/brand/drawable-nodpi/cage_icon.png"
20新增:unzip -q "$aar" -d "$work/aar"
21新增:cp "$work/aar/jni/arm64-v8a/libgojni.so" "$work/apk/lib/arm64-v8a/"
22新增:mkdir -p "$work/apk/assets/licenses"
23新增:cp "$android/licenses/ZXing-LICENSE.txt" "$work/apk/assets/licenses/"
24新增:"$tools/aapt2" compile --dir "$android/res" -o "$work/res.zip"
25新增:"$tools/aapt2" compile --dir "$work/brand" -o "$work/brand.zip"
26新增:"$tools/aapt2" link -o "$work/base.apk" -I "$platform" -A "$mobile_dir/.build/resources" --manifest "$android/AndroidManifest.xml" "$work/res.zip" "$work/brand.zip"
27新增:zxing="$build/zxing-core-3.5.3.jar"
28新增:if [[ ! -f "$zxing" ]]; then
29新增: curl --fail --location --silent --show-error https://repo.maven.apache.org/maven2/com/google/zxing/core/3.5.3/core-3.5.3.jar -o "$work/zxing.jar"
30新增: cp "$work/zxing.jar" "$zxing"
31新增:fi
32新增:echo "8d8064c1636fdaef7189dd9055c7d59950a8940a12f2293956446ec3c109fd82 $zxing" | shasum -a 256 --check --status
33新增:bash "$android/fetch-webkit.sh" "$build"
34新增:javac --release 8 -encoding UTF-8 -classpath "$platform:$work/aar/classes.jar:$zxing:$build/webkit-1.14.0.jar:$build/core-1.1.0.jar" -d "$work/classes" "$android"/src/io/github/leexeo/cage/mobile/*.java
35新增:jar cf "$work/app.jar" -C "$work/classes" .
36新增:"$tools/d8" --min-api 26 --lib "$platform" --output "$work/dex" "$work/app.jar" "$work/aar/classes.jar" "$zxing" "$build/webkit-1.14.0.jar" "$build/core-1.1.0.jar"
37新增:cp "$work/dex/"*.dex "$work/apk/"
38新增:(cd "$work/apk" && zip -q -0 "$work/base.apk" ./*.dex lib/arm64-v8a/libgojni.so assets/licenses/ZXing-LICENSE.txt)
39新增:"$tools/zipalign" -f -P 16 4 "$work/base.apk" "$work/aligned.apk"
40新增:key="$build/development.p12"
41新增:if [[ ! -f "$key" ]]; then
42新增: (umask 077; keytool -genkeypair -alias development -keyalg RSA -keysize 2048 -validity 3650 \
43新增: -keystore "$key" -storetype PKCS12 -storepass android -keypass android -dname "CN=Cage local development")
44新增:fi
45新增:out="$build/cage-mobile-debug.apk"
46新增:"$tools/apksigner" sign --ks "$key" --ks-key-alias development --ks-pass pass:android --out "$out" "$work/aligned.apk"
47新增:"$tools/apksigner" verify --verbose "$out"
48新增:"$tools/zipalign" -c -P 16 4 "$out"
49新增:echo "$out"
新增mobile/android/res/drawable/cage_back.xml+6 −0看文件
@@ -0,0 +1,6 @@
1新增:<vector xmlns:android="http://schemas.android.com/apk/res/android"
2新增: android:width="22dp" android:height="22dp" android:viewportWidth="24" android:viewportHeight="24">
3新增: <path android:pathData="M14.5,5 L7.5,12 L14.5,19"
4新增: android:strokeColor="#ff292a27" android:strokeWidth="1.7" android:strokeLineJoin="round"
5新增: android:strokeLineCap="round" android:fillColor="@android:color/transparent" />
6新增:</vector>
新增mobile/android/res/drawable/cage_close.xml+6 −0看文件
@@ -0,0 +1,6 @@
1新增:<vector xmlns:android="http://schemas.android.com/apk/res/android"
2新增: android:width="22dp" android:height="22dp" android:viewportWidth="24" android:viewportHeight="24">
3新增: <path android:pathData="M6,6 L18,18 M6,18 L18,6"
4新增: android:strokeColor="#ff292a27" android:strokeWidth="1.7" android:strokeLineJoin="round"
5新增: android:strokeLineCap="round" android:fillColor="@android:color/transparent" />
6新增:</vector>
新增mobile/android/res/drawable/cage_computer.xml+6 −0看文件
@@ -0,0 +1,6 @@
1新增:<vector xmlns:android="http://schemas.android.com/apk/res/android"
2新增: android:width="22dp" android:height="22dp" android:viewportWidth="24" android:viewportHeight="24">
3新增: <path android:pathData="M4,4.5 H20 Q21,4.5 21,5.5 V16 Q21,17 20,17 H4 Q3,17 3,16 V5.5 Q3,4.5 4,4.5Z M12,17 V20 M8,20 H16"
4新增: android:strokeColor="#ff292a27" android:strokeWidth="1.7" android:strokeLineJoin="round"
5新增: android:strokeLineCap="round" android:fillColor="@android:color/transparent" />
6新增:</vector>
新增mobile/android/res/drawable/cage_gear.xml+6 −0看文件
@@ -0,0 +1,6 @@
1新增:<vector xmlns:android="http://schemas.android.com/apk/res/android"
2新增: android:width="22dp" android:height="22dp" android:viewportWidth="24" android:viewportHeight="24">
3新增: <path android:pathData="M9.2,3.5 L9.8,2 H14.2 L14.8,3.5 L15.1,4.5 L16.6,5.4 L19.1,5 L21.3,8.8 L19.6,10.6 V13.4 L21.3,15.2 L19.1,19 L16.6,18.6 L15.1,19.5 L14.2,22 H9.8 L8.9,19.5 L7.4,18.6 L4.9,19 L2.7,15.2 L4.4,13.4 V10.6 L2.7,8.8 L4.9,5 L7.4,5.4 L8.9,4.5 Z M15.5,12 A3.5,3.5 0,1 1,8.5 12 A3.5,3.5 0,1 1,15.5 12Z"
4新增: android:strokeColor="#ff292a27" android:strokeWidth="1.7" android:strokeLineJoin="round"
5新增: android:strokeLineCap="round" android:fillColor="@android:color/transparent" />
6新增:</vector>
新增mobile/android/res/drawable/cage_menu.xml+6 −0看文件
@@ -0,0 +1,6 @@
1新增:<vector xmlns:android="http://schemas.android.com/apk/res/android"
2新增: android:width="22dp" android:height="22dp" android:viewportWidth="24" android:viewportHeight="24">
3新增: <path android:pathData="M3,4 H21 V20 H3 Z M9,4 V20"
4新增: android:strokeColor="#ff292a27" android:strokeWidth="1.7" android:strokeLineJoin="round"
5新增: android:strokeLineCap="round" android:fillColor="@android:color/transparent" />
6新增:</vector>
新增mobile/android/res/xml/network_security_config.xml+7 −0看文件
@@ -0,0 +1,7 @@
1新增:<?xml version="1.0" encoding="utf-8"?>
2新增:<network-security-config>
3新增: <base-config cleartextTrafficPermitted="false"/>
4新增: <domain-config cleartextTrafficPermitted="true">
5新增: <domain includeSubdomains="false">127.0.0.1</domain>
6新增: </domain-config>
7新增:</network-security-config>
新增mobile/android/src/io/github/leexeo/cage/mobile/DeviceKey.java+40 −0看文件
@@ -0,0 +1,40 @@
1新增:package io.github.leexeo.cage.mobile;
2新增:
3新增:import android.security.keystore.KeyGenParameterSpec;
4新增:import android.security.keystore.KeyProperties;
5新增:import cagemobile.DeviceSigner;
6新增:import java.security.KeyPairGenerator;
7新增:import java.security.KeyStore;
8新增:import java.security.PrivateKey;
9新增:import java.security.Signature;
10新增:import java.security.spec.ECGenParameterSpec;
11新增:
12新增:final class DeviceKey implements DeviceSigner {
13新增: private static final String ALIAS = "cage-mobile-device-v1";
14新增: private final KeyStore store;
15新增:
16新增: DeviceKey() throws Exception {
17新增: store = KeyStore.getInstance("AndroidKeyStore");
18新增: store.load(null);
19新增: if (!store.containsAlias(ALIAS)) {
20新增: KeyPairGenerator generator = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC, "AndroidKeyStore");
21新增: generator.initialize(new KeyGenParameterSpec.Builder(ALIAS, KeyProperties.PURPOSE_SIGN)
22新增: .setAlgorithmParameterSpec(new ECGenParameterSpec("secp256r1"))
23新增: .setDigests(KeyProperties.DIGEST_NONE)
24新增: .build());
25新增: generator.generateKeyPair();
26新增: }
27新增: }
28新增:
29新增: @Override public byte[] publicKeyDER() throws Exception {
30新增: return store.getCertificate(ALIAS).getPublicKey().getEncoded();
31新增: }
32新增:
33新增: @Override public byte[] signSHA256(byte[] digest) throws Exception {
34新增: if (digest == null || digest.length != 32) throw new IllegalArgumentException("Expected a SHA-256 digest");
35新增: Signature signature = Signature.getInstance("NONEwithECDSA");
36新增: signature.initSign((PrivateKey) store.getKey(ALIAS, null));
37新增: signature.update(digest);
38新增: return signature.sign();
39新增: }
40新增:}
新增mobile/android/src/io/github/leexeo/cage/mobile/HostCredentials.java+89 −0看文件
@@ -0,0 +1,89 @@
1新增:package io.github.leexeo.cage.mobile;
2新增:
3新增:import android.content.SharedPreferences;
4新增:import android.security.keystore.KeyGenParameterSpec;
5新增:import android.security.keystore.KeyProperties;
6新增:import android.util.Base64;
7新增:import java.io.IOException;
8新增:import java.nio.ByteBuffer;
9新增:import java.nio.charset.StandardCharsets;
10新增:import java.security.KeyStore;
11新增:import java.util.Arrays;
12新增:import java.security.MessageDigest;
13新增:import javax.crypto.Cipher;
14新增:import javax.crypto.KeyGenerator;
15新增:import javax.crypto.SecretKey;
16新增:import javax.crypto.spec.GCMParameterSpec;
17新增:
18新增:// The public address and verified fingerprint also authenticate the ciphertext.
19新增:// Keep the AES key separate from the P-256 device identity so forgetting a host
20新增:// leaves the device fingerprint intact.
21新增:final class HostCredentials {
22新增: private static final String ALIAS = "cage-mobile-saved-host-aes-v1";
23新增: private static final String SEALED = "sealed-lookup-v1";
24新增: private final SharedPreferences prefs;
25新增: HostCredentials(SharedPreferences prefs) { this.prefs = prefs; }
26新增: boolean saved() { return prefs.contains(SEALED); }
27新增: boolean matches(String relay, String pin) { return relay.equals(prefs.getString("relay", "")) && pin.equals(prefs.getString("pin", "")); }
28新增: private static String entry(String relay, String pin) throws Exception {
29新增: byte[] digest = MessageDigest.getInstance("SHA-256").digest(context(relay, pin));
30新增: return "host-lookup-v2-" + Base64.encodeToString(digest, Base64.NO_WRAP | Base64.URL_SAFE);
31新增: }
32新增:
33新增: private static KeyStore store() throws Exception {
34新增: KeyStore store = KeyStore.getInstance("AndroidKeyStore");
35新增: store.load(null);
36新增: return store;
37新增: }
38新增: private SecretKey key(boolean create) throws Exception {
39新增: KeyStore store = store();
40新增: if (store.containsAlias(ALIAS)) return (SecretKey) store.getKey(ALIAS, null);
41新增: if (!create) throw new IOException("设备凭据不可用。");
42新增: KeyGenerator generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
43新增: generator.init(new KeyGenParameterSpec.Builder(ALIAS, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
44新增: .setKeySize(256).setBlockModes(KeyProperties.BLOCK_MODE_GCM)
45新增: .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE).build());
46新增: return generator.generateKey();
47新增: }
48新增: private static byte[] context(String relay, String pin) {
49新增: return ("Cage saved host v1\n" + relay + "\n" + pin).getBytes(StandardCharsets.UTF_8);
50新增: }
51新增: synchronized void save(String relay, String pin, String lookup) throws Exception {
52新增: SharedPreferences.Editor change = prefs.edit().putString("relay", relay).putString("pin", pin);
53新增: String previousRelay = prefs.getString("relay", ""), previousPin = prefs.getString("pin", "");
54新增: if (prefs.contains(SEALED)) change.putString(entry(previousRelay, previousPin), prefs.getString(SEALED, ""));
55新增: if (lookup != null) {
56新增: Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
57新增: cipher.init(Cipher.ENCRYPT_MODE, key(true));
58新增: cipher.updateAAD(context(relay, pin));
59新增: byte[] plain = lookup.getBytes(StandardCharsets.UTF_8);
60新增: byte[] encrypted;
61新增: try { encrypted = cipher.doFinal(plain); } finally { Arrays.fill(plain, (byte) 0); }
62新增: String value = Base64.encodeToString(cipher.getIV(), Base64.NO_WRAP) + "." + Base64.encodeToString(encrypted, Base64.NO_WRAP);
63新增: change.putString(SEALED, value).putString(entry(relay, pin), value);
64新增: } else if (!matches(relay, pin)) {
65新增: String saved = prefs.getString(entry(relay, pin), null);
66新增: if (saved == null) change.remove(SEALED); else change.putString(SEALED, saved);
67新增: }
68新增: if (!change.commit()) throw new IOException("无法保存主机。");
69新增: }
70新增: synchronized String lookup(String relay, String pin) throws Exception {
71新增: String value = matches(relay,pin) ? prefs.getString(SEALED, "") : prefs.getString(entry(relay, pin), "");
72新增: String[] parts = value.split("\\.", -1);
73新增: if (parts.length != 2) throw new IOException("无可用重连凭据。");
74新增: Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
75新增: cipher.init(Cipher.DECRYPT_MODE, key(false), new GCMParameterSpec(128, Base64.decode(parts[0], Base64.NO_WRAP)));
76新增: cipher.updateAAD(context(relay, pin));
77新增: byte[] plain = cipher.doFinal(Base64.decode(parts[1], Base64.NO_WRAP));
78新增: try {
79新增: String token = StandardCharsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(plain)).toString();
80新增: if (!Invitation.capability(token)) throw new IOException("重连凭据无效。");
81新增: return token;
82新增: } finally { Arrays.fill(plain, (byte) 0); }
83新增: }
84新增: synchronized void forget() throws Exception {
85新增: // Other computers share the encryption key. Forget only the selected host.
86新增: if (!prefs.edit().remove(entry(prefs.getString("relay", ""), prefs.getString("pin", "")))
87新增: .remove(SEALED).remove("relay").remove("pin").commit()) throw new IOException("无法移除主机。");
88新增: }
89新增:}
新增mobile/android/src/io/github/leexeo/cage/mobile/Invitation.java+82 −0看文件
@@ -0,0 +1,82 @@
1新增:package io.github.leexeo.cage.mobile;
2新增:
3新增:import android.util.Base64;
4新增:import org.json.JSONObject;
5新增:import java.io.ByteArrayOutputStream;
6新增:import java.io.IOException;
7新增:import java.io.InputStream;
8新增:import java.net.URI;
9新增:import java.nio.charset.StandardCharsets;
10新增:import java.time.Instant;
11新增:
12新增:final class Invitation {
13新增: final String room, token;
14新增: final Instant expiry;
15新增:
16新增: private Invitation(String room, String token, Instant expiry) {
17新增: this.room = room;
18新增: this.token = token;
19新增: this.expiry = expiry;
20新增: }
21新增:
22新增: static final class Saved {
23新增: final String relay, pin, lookup;
24新增: Saved(JSONObject object) throws Exception {
25新增: if (object.length() != 4 || !Integer.valueOf(1).equals(object.opt("version"))) throw new IOException("连接文件版本无效。");
26新增: relay = relay(object.getString("relay"));
27新增: pin = pin(object.getString("host_pin"));
28新增: lookup = object.getString("lookup_token");
29新增: if (!capability(lookup)) throw new IOException("连接文件无效。");
30新增: }
31新增: }
32新增:
33新增: static JSONObject read(InputStream stream) throws Exception {
34新增: if (stream == null) throw new IOException("无法读取邀请文件。");
35新增: ByteArrayOutputStream buffer = new ByteArrayOutputStream();
36新增: byte[] chunk = new byte[1024];
37新增: int count;
38新增: while ((count = stream.read(chunk)) != -1) {
39新增: if (buffer.size() + count > 4096) throw new IOException("邀请文件过大。");
40新增: buffer.write(chunk, 0, count);
41新增: }
42新增: return new JSONObject(new String(buffer.toByteArray(), StandardCharsets.UTF_8));
43新增: }
44新增:
45新增: static boolean capability(String value) {
46新增: if (!value.matches("[A-Za-z0-9_-]{43}")) return false;
47新增: int flags = Base64.URL_SAFE | Base64.NO_PADDING | Base64.NO_WRAP;
48新增: byte[] bytes = Base64.decode(value, flags);
49新增: return bytes.length == 32 && value.equals(Base64.encodeToString(bytes, flags));
50新增: }
51新增:
52新增: static Invitation room(JSONObject object) throws Exception {
53新增: String room = object.getString("id"), token = object.getString("client_token");
54新增: Instant expiry = Instant.parse(object.getString("expires_at"));
55新增: if (object.length() != 3 || !capability(room) || !capability(token) || !expiry.isAfter(Instant.now())) {
56新增: throw new IOException("邀请无效或已过期。");
57新增: }
58新增: return new Invitation(room, token, expiry);
59新增: }
60新增:
61新增: static String relay(String value) throws Exception {
62新增: URI uri = new URI(value.trim());
63新增: if (!"https".equalsIgnoreCase(uri.getScheme()) || uri.getHost() == null ||
64新增: uri.getRawUserInfo() != null || uri.getRawQuery() != null || uri.getRawFragment() != null ||
65新增: !(uri.getRawPath().isEmpty() || uri.getRawPath().equals("/")) || uri.getPort() == 0 || uri.getPort() > 65535) {
66新增: throw new IllegalArgumentException("请填写 HTTPS 中继地址,地址中只保留主机和端口。");
67新增: }
68新增: return new URI("https", null, uri.getHost(), uri.getPort(), null, null, null).toASCIIString();
69新增: }
70新增:
71新增: static String pin(String value) {
72新增: String pin = value.trim();
73新增: if (pin.startsWith("sha256:")) {
74新增: String encoded = pin.substring(7);
75新增: try {
76新增: byte[] bytes = Base64.decode(encoded, Base64.NO_WRAP);
77新增: if (bytes.length == 32 && encoded.equals(Base64.encodeToString(bytes, Base64.NO_WRAP))) return pin;
78新增: } catch (IllegalArgumentException ignored) { }
79新增: }
80新增: throw new IllegalArgumentException("电脑指纹需要完整的 sha256: 值。");
81新增: }
82新增:}
新增mobile/android/src/io/github/leexeo/cage/mobile/MainActivity.java+852 −0看文件
@@ -0,0 +1,852 @@
1新增:package io.github.leexeo.cage.mobile;
2新增:
3新增:import android.app.Activity;
4新增:import android.app.AlertDialog;
5新增:import android.app.Dialog;
6新增:import android.content.ClipData;
7新增:import android.content.ClipboardManager;
8新增:import android.content.Intent;
9新增:import android.content.SharedPreferences;
10新增:import android.content.res.AssetManager;
11新增:import android.graphics.Typeface;
12新增:import android.graphics.drawable.Drawable;
13新增:import android.graphics.drawable.GradientDrawable;
14新增:import android.graphics.drawable.RippleDrawable;
15新增:import android.content.res.ColorStateList;
16新增:import android.view.Gravity;
17新增:import android.net.Uri;
18新增:import android.os.Bundle;
19新增:import android.os.Build;
20新增:import android.text.InputType;
21新增:import android.text.Editable;
22新增:import android.text.TextWatcher;
23新增:import android.view.View;
24新增:import android.webkit.CookieManager;
25新增:import android.webkit.WebResourceRequest;
26新增:import android.webkit.WebResourceResponse;
27新增:import android.webkit.WebSettings;
28新增:import android.webkit.WebView;
29新增:import android.webkit.WebViewClient;
30新增:import android.widget.*;
31新增:import cagemobile.Cagemobile;
32新增:import cagemobile.Client;
33新增:import java.io.*;
34新增:import java.time.Instant;
35新增:import java.util.concurrent.ExecutorService;
36新增:import java.util.concurrent.Executors;
37新增:import org.json.JSONObject;
38新增:import org.json.JSONArray;
39新增:import java.util.LinkedHashMap;
40新增:import java.util.Map;
41新增:import androidx.webkit.WebViewCompat;
42新增:import androidx.webkit.WebViewFeature;
43新增:import androidx.webkit.ScriptHandler;
44新增:
45新增:public final class MainActivity extends Activity {
46新增: private static final int PICK_INVITATION = 41;
47新增: private final ExecutorService worker = Executors.newSingleThreadExecutor();
48新增: private SharedPreferences trust;
49新增: private HostCredentials credentials;
50新增: private DeviceKey device;
51新增: private String fingerprint = "";
52新增: private Invitation invitation;
53新增: private Invitation.Saved imported;
54新增: private WebView browser;
55新增: private final Map<String, ConnectedDevice> connections = new LinkedHashMap<>();
56新增: private ConnectedDevice activeDevice;
57新增: private boolean viewingWorkspace;
58新增: private boolean openArchivedAfterConnect;
59新增: private static final class ConnectedDevice {
60新增: final String id;
61新增: final String hostKey;
62新增: final Client client;
63新增: final Uri launch;
64新增: WebView view;
65新增: ScriptHandler script;
66新增: String name;
67新增: ConnectedDevice(String hostKey, Client client, Uri launch, String name) {
68新增: this.id=java.util.UUID.randomUUID().toString(); this.hostKey=hostKey;
69新增: this.client=client; this.launch=launch; this.name=name;
70新增: }
71新增: }
72新增: private enum Page { HOME, SETTINGS, HOST, RELAY, PAIR, CODE }
73新增: private Page page = Page.HOME;
74新增: private FrameLayout root;
75新增: private LinearLayout form;
76新增: private FrameLayout home;
77新增: private View overlay;
78新增: private EditText relayField, pinField;
79新增: private TextView localPin, status, inviteStatus;
80新增: private CheckBox verified;
81新增: private Switch customRelay;
82新增: private Button connect, forgetHost;
83新增: private boolean busy;
84新增: private int generation;
85新增: private MobileTheme palette;
86新增: private SharedPreferences appearance;
87新增: private static final int SCAN = 42;
88新增:
89新增: private void rememberRelay(String relay) {
90新增: trust.edit().putString("preferred-relay", relay).apply();
91新增: }
92新增: private String preferredRelay() {
93新增: return trust.getString("preferred-relay", trust.getString("relay", Cagemobile.defaultRelay()));
94新增: }
95新增: private static String deviceModel() {
96新增: String model = Build.MODEL.trim();
97新增: String brand = Build.MANUFACTURER.trim();
98新增: if (brand.isEmpty() || model.regionMatches(true, 0, brand, 0, brand.length())) return model;
99新增: return Character.toUpperCase(brand.charAt(0)) + brand.substring(1) + " " + model;
100新增: }
101新增: private String selectedRelay() throws Exception {
102新增: return customRelay.isChecked() ? Invitation.relay(relayField.getText().toString()) : Cagemobile.defaultRelay();
103新增: }
104新增: private void displayRelay(String value) {
105新增: boolean custom = !Cagemobile.defaultRelay().equals(value);
106新增: customRelay.setChecked(custom);
107新增: relayField.setText(custom ? value : "");
108新增: relayField.setVisibility(custom ? View.VISIBLE : View.GONE);
109新增: }
110新增: private void pairScan(String code) {
111新增: if (busy) return;
112新增: if (device == null) { status.setText("设备密钥尚未就绪,请稍后重试。"); return; }
113新增: String relay = preferredRelay();
114新增: int attempt = ++generation;
115新增: setConnecting(true);
116新增: status.setText("正在与电脑配对…");
117新增: worker.execute(() -> {
118新增: try {
119新增: Invitation.Saved saved = new Invitation.Saved(new JSONObject(Cagemobile.pair(code, relay, device)));
120新增: credentials.save(saved.relay, saved.pin, saved.lookup);
121新增: rememberRelay(saved.relay);
122新增: runOnUiThread(() -> {
123新增: if (generation != attempt) return;
124新增: invitation = null;
125新增: imported = null;
126新增: setConnecting(false);
127新增: connect();
128新增: });
129新增: } catch (Exception e) {
130新增: runOnUiThread(() -> {
131新增: if (generation != attempt) return;
132新增: setConnecting(false);
133新增: status.setText("配对未完成。请确认两端使用同一中继,再用电脑上新生成的二维码或配对码重试。");
134新增: });
135新增: }
136新增: });
137新增: }
138新增:
139新增: @Override public void onCreate(Bundle state) {
140新增: super.onCreate(state);
141新增: trust = getSharedPreferences("verified-host", MODE_PRIVATE);
142新增: appearance = getSharedPreferences("appearance", MODE_PRIVATE);
143新增: palette = MobileTheme.apply(this, themeMode());
144新增: credentials = new HostCredentials(trust);
145新增: showSetup();
146新增: if (state != null) {
147新增: String restoredPage = state.getString("page", Page.HOME.name());
148新增: Page restored = "ENVIRONMENT".equals(restoredPage) ? Page.HOME : Page.valueOf(restoredPage);
149新增: if (restored == Page.PAIR || restored == Page.CODE) showPair(restored == Page.CODE);
150新增: if (restored == Page.SETTINGS) showSettings(false);
151新增: if (restored == Page.HOST || restored == Page.RELAY) showAdvanced(restored);
152新增: }
153新增: worker.execute(() -> {
154新增: try {
155新增: DeviceKey key = new DeviceKey();
156新增: String pin = Cagemobile.fingerprint(key);
157新增: runOnUiThread(() -> {
158新增: if (isDestroyed()) return;
159新增: device = key;
160新增: fingerprint = pin;
161新增: if (localPin != null) localPin.setText(pin);
162新增: });
163新增: } catch (Exception e) {
164新增: runOnUiThread(() -> {
165新增: if (!isDestroyed()) status.setText("无法使用 Android Keystore 设备密钥。");
166新增: });
167新增: }
168新增: });
169新增: }
170新增: @Override protected void onSaveInstanceState(Bundle saved) {
171新增: super.onSaveInstanceState(saved);
172新增: saved.putString("page", page.name());
173新增: }
174新增:
175新增: private int dp(int value) { return Math.round(getResources().getDisplayMetrics().density * value); }
176新增: private String themeMode() { return appearance.getString("theme", "system"); }
177新增: private void insets(View root) {
178新增: root.setOnApplyWindowInsetsListener((v, w) -> {
179新增: v.setPadding(w.getSystemWindowInsetLeft(), w.getSystemWindowInsetTop(), w.getSystemWindowInsetRight(), w.getSystemWindowInsetBottom());
180新增: return w.consumeSystemWindowInsets();
181新增: });
182新增: root.requestApplyInsets();
183新增: }
184新增: private LinearLayout column() {
185新增: LinearLayout group = new LinearLayout(this);
186新增: group.setOrientation(LinearLayout.VERTICAL);
187新增: return group;
188新增: }
189新增: private GradientDrawable surface(int color, int radius, boolean outline) {
190新增: GradientDrawable shape = new GradientDrawable();
191新增: shape.setColor(color);
192新增: shape.setCornerRadius(dp(radius));
193新增: if (outline) shape.setStroke(dp(1), palette.line);
194新增: return shape;
195新增: }
196新增: private Drawable pressable(int color, int radius, boolean outline) {
197新增: return new RippleDrawable(ColorStateList.valueOf(palette.dark ? 0x14ffffff : 0x0d000000), surface(color, radius, outline), null);
198新增: }
199新增: private TextView text(String value, int size, int color) {
200新增: TextView view = new TextView(this);
201新增: view.setText(value);
202新增: view.setTextSize(size);
203新增: view.setTextColor(color);
204新增: return view;
205新增: }
206新增: private TextView label(String value, int size) {
207新增: TextView view = text(value, size, palette.muted);
208新增: view.setPadding(0, dp(12), 0, dp(3));
209新增: form.addView(view);
210新增: return view;
211新增: }
212新增: private Button button(LinearLayout parent, String name, boolean primary, View.OnClickListener action) {
213新增: Button view = new Button(this);
214新增: view.setText(name);
215新增: view.setAllCaps(false);
216新增: view.setTextSize(16);
217新增: view.setTextColor(primary ? palette.onAction : palette.ink);
218新增: view.setTypeface(Typeface.create("sans-serif-medium", Typeface.NORMAL));
219新增: view.setStateListAnimator(null);
220新增: view.setBackground(pressable(primary ? palette.action : palette.soft, 14, false));
221新增: view.setOnClickListener(action);
222新增: LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(-1, dp(52));
223新增: lp.topMargin = dp(8);
224新增: parent.addView(view, lp);
225新增: return view;
226新增: }
227新增: private ImageButton icon(String resource, String name, View.OnClickListener action) {
228新增: ImageButton view = new ImageButton(this);
229新增: view.setImageResource(getResources().getIdentifier("cage_" + resource, "drawable", getPackageName()));
230新增: view.setContentDescription(name);
231新增: view.setColorFilter(palette.ink);
232新增: view.setScaleType(ImageView.ScaleType.CENTER);
233新增: view.setBackground(pressable(palette.soft, 24, false));
234新增: view.setOnClickListener(action);
235新增: return view;
236新增: }
237新增: private View connectComputerButton(View.OnClickListener action) {
238新增: LinearLayout view = new LinearLayout(this);
239新增: view.setOrientation(LinearLayout.HORIZONTAL);
240新增: view.setGravity(Gravity.CENTER);
241新增: view.setPadding(dp(16), 0, dp(16), 0);
242新增: view.setBackground(pressable(palette.action, 14, false));
243新增: view.setFocusable(true);
244新增: view.setContentDescription("连接电脑");
245新增: view.setOnClickListener(action);
246新增: view.setAccessibilityDelegate(new View.AccessibilityDelegate() {
247新增: @Override public void onInitializeAccessibilityNodeInfo(View host, android.view.accessibility.AccessibilityNodeInfo info) {
248新增: super.onInitializeAccessibilityNodeInfo(host, info);
249新增: info.setClassName(Button.class.getName());
250新增: }
251新增: });
252新增: ImageView computer = image("cage_computer");
253新增: computer.setColorFilter(palette.onAction);
254新增: view.addView(computer, dp(22), dp(22));
255新增: TextView title = text("连接电脑", 16, palette.onAction);
256新增: title.setTypeface(Typeface.create("sans-serif-medium", Typeface.NORMAL));
257新增: title.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);
258新增: LinearLayout.LayoutParams caption = new LinearLayout.LayoutParams(-2, -2);
259新增: caption.setMarginStart(dp(10));
260新增: view.addView(title, caption);
261新增: return view;
262新增: }
263新增: private EditText field(String hint, String value) {
264新增: EditText input = new EditText(this);
265新增: input.setSingleLine();
266新增: input.setTextSize(16);
267新增: input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
268新增: input.setHint(hint);
269新增: input.setText(value);
270新增: form.addView(input);
271新增: return input;
272新增: }
273新增: private void statusView() {
274新增: status = label("", 14);
275新增: status.setAccessibilityLiveRegion(View.ACCESSIBILITY_LIVE_REGION_POLITE);
276新增: status.setMinHeight(dp(22));
277新增: }
278新增: private void layout(Page next) {
279新增: page = next;
280新增: overlay = null;
281新增: root = new FrameLayout(this);
282新增: root.setBackgroundColor(palette.bg);
283新增: setContentView(root);
284新增: insets(root);
285新增: localPin = null;
286新增: }
287新增: private ImageView image(String resource) {
288新增: ImageView img = new ImageView(this);
289新增: img.setImageResource(getResources().getIdentifier(resource, "drawable", getPackageName()));
290新增: img.setScaleType(ImageView.ScaleType.FIT_CENTER);
291新增: img.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);
292新增: return img;
293新增: }
294新增: private void showSetup() {
295新增: viewingWorkspace = false;
296新增: if (browser != null) browser.onPause();
297新增: layout(Page.HOME);
298新增: ScrollView scroll = new ScrollView(this);
299新增: scroll.setFillViewport(true);
300新增: root.addView(scroll, -1, -1);
301新增: FrameLayout body = new FrameLayout(this);
302新增: body.setMinimumHeight(dp(440));
303新增: scroll.addView(body, new ScrollView.LayoutParams(-1, -2));
304新增: home = body;
305新增: FrameLayout.LayoutParams gear = new FrameLayout.LayoutParams(dp(48), dp(48), Gravity.TOP | Gravity.RIGHT);
306新增: gear.setMargins(dp(18), dp(12), dp(18), 0);
307新增: body.addView(icon("gear", "设置", v -> showSettings(false)), gear);
308新增:
309新增: form = column();
310新增: form.setGravity(Gravity.CENTER);
311新增: LinearLayout homeForm = form;
312新增: // Balance the larger brand/action gap so the logo stays in place (§3.6).
313新增: form.setPadding(0, dp(32), 0, 0);
314新增: FrameLayout.LayoutParams hero = new FrameLayout.LayoutParams(dp(276), -2, Gravity.CENTER);
315新增: hero.leftMargin = dp(24);
316新增: hero.rightMargin = dp(24);
317新增: body.addView(form, hero);
318新增: ImageView mark = image("cage_icon");
319新增: mark.setBackground(surface(palette.panel, 18, false));
320新增: mark.setClipToOutline(true);
321新增: form.addView(mark, dp(120), dp(120));
322新增: TextView title = text("Cage", 38, palette.ink);
323新增: title.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
324新增: title.setGravity(Gravity.CENTER);
325新增: title.setPadding(0, dp(8), 0, dp(52));
326新增: form.addView(title);
327新增: LinearLayout.LayoutParams action = new LinearLayout.LayoutParams(-1, dp(60));
328新增: action.topMargin = dp(8);
329新增: form.addView(connectComputerButton(v -> showPair(false)), action);
330新增: statusView();
331新增: body.addOnLayoutChangeListener((view, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom) -> {
332新增: int height = bottom - top;
333新增: if (height == oldBottom - oldTop && right - left == oldRight - oldLeft) return;
334新增: hero.width = Math.min(dp(276), Math.max(0, right - left - dp(48)));
335新增: homeForm.setLayoutParams(hero);
336新增: int spacing = Math.min(dp(60), Math.max(dp(28), Math.round(height * 0.075f))) + dp(32);
337新增: title.setPadding(0, dp(8), 0, spacing - dp(8));
338新增: });
339新增: }
340新增: private void closeSheet() {
341新增: if (busy) return;
342新增: showSetup();
343新增: }
344新增: private void showPair(boolean code) {
345新增: boolean opening = overlay == null;
346新增: if (overlay != null) root.removeView(overlay);
347新增: page = code ? Page.CODE : Page.PAIR;
348新增: home.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS);
349新增: home.setDescendantFocusability(android.view.ViewGroup.FOCUS_BLOCK_DESCENDANTS);
350新增: FrameLayout layer = new FrameLayout(this);
351新增: overlay = layer;
352新增: root.addView(layer, -1, -1);
353新增: View shade = new View(this);
354新增: shade.setBackgroundColor(0x64000000);
355新增: shade.setOnClickListener(v -> closeSheet());
356新增: shade.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);
357新增: shade.setFocusable(false);
358新增: layer.addView(shade, -1, -1);
359新增: ScrollView scroll = new ScrollView(this);
360新增: scroll.setFillViewport(false);
361新增: scroll.setBackground(surface(palette.panel, 26, false));
362新增: scroll.setClickable(true);
363新增: FrameLayout.LayoutParams sheet = new FrameLayout.LayoutParams(Math.min(getResources().getDisplayMetrics().widthPixels, dp(500)), -2,
364新增: Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
365新增: sheet.setMargins(dp(8), dp(12), dp(8), dp(8));
366新增: sheet.width = Math.min(sheet.width - dp(16), dp(500));
367新增: layer.addView(scroll, sheet);
368新增: form = column();
369新增: form.setPadding(dp(20), dp(14), dp(20), dp(14));
370新增: scroll.addView(form);
371新增: FrameLayout heading = new FrameLayout(this);
372新增: form.addView(heading, -1, dp(48));
373新增: TextView title = text(code ? "配对码" : "连接电脑", 24, palette.ink);
374新增: title.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
375新增: heading.addView(title, new FrameLayout.LayoutParams(-2, -2, Gravity.LEFT | Gravity.CENTER_VERTICAL));
376新增: if (!code) {
377新增: form.addView(image("pair_devices"), -1, dp(112));
378新增: label("在电脑的「设置 → 远程连接」中生成配对二维码或配对码。", 14);
379新增: button(form, "扫码连接", true, v -> startActivityForResult(new Intent(this, ScanActivity.class), SCAN));
380新增: button(form, "使用配对码", false, v -> showPair(true));
381新增: } else {
382新增: label("粘贴电脑上复制的一次性配对码。", 15);
383新增: EditText manualCode = field("一次性配对码", "");
384新增: button(form, "连接电脑", true, v -> {
385新增: String value = manualCode.getText().toString().trim();
386新增: if (value.isEmpty()) { status.setText("请粘贴配对码。"); return; }
387新增: manualCode.setText("");
388新增: android.view.inputmethod.InputMethodManager ime = (android.view.inputmethod.InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
389新增: ime.hideSoftInputFromWindow(manualCode.getWindowToken(), 0);
390新增: pairScan(value);
391新增: });
392新增: button(form, "返回配对方式", false, v -> showPair(false));
393新增: }
394新增: if (!code && !connections.isEmpty()) {
395新增: label("已连接的设备", 15);
396新增: label("长按设备可取消连接", 14);
397新增: for (ConnectedDevice connected : connections.values()) {
398新增: Button entry = button(form, connected.name + " · 进入", false, v -> enterDevice(connected));
399新增: entry.setOnLongClickListener(v -> {confirmDisconnect(connected); return true;});
400新增: }
401新增: }
402新增: if (credentials.saved() && !code) button(form, "重新连接已配对电脑", false, v -> connect());
403新增: statusView();
404新增: form.setFocusableInTouchMode(true);
405新增: form.requestFocus();
406新增: if (opening && android.animation.ValueAnimator.areAnimatorsEnabled()) {
407新增: shade.setAlpha(0f);
408新增: scroll.getViewTreeObserver().addOnPreDrawListener(new android.view.ViewTreeObserver.OnPreDrawListener() {
409新增: @Override public boolean onPreDraw() {
410新增: scroll.getViewTreeObserver().removeOnPreDrawListener(this);
411新增: if (overlay != layer) return true;
412新增: // Start below the viewport after measuring, before the first visible frame.
413新增: scroll.setTranslationY(scroll.getHeight() + sheet.bottomMargin);
414新增: scroll.animate().translationY(0).setDuration(300)
415新增: .setInterpolator(new android.view.animation.PathInterpolator(0.2f, 0f, 0f, 1f)).start();
416新增: shade.animate().alpha(1f).setDuration(200).start();
417新增: return true;
418新增: }
419新增: });
420新增: }
421新增: }
422新增:
423新增: private void settingsPage(Page next, String name, Runnable back) {
424新增: layout(next);
425新增: ScrollView scroll = new ScrollView(this);
426新增: root.addView(scroll, -1, -1);
427新增: form = column();
428新增: form.setPadding(dp(22), dp(14), dp(22), dp(28));
429新增: form.setFocusableInTouchMode(true);
430新增: scroll.addView(form);
431新增: form.addView(icon("back", "返回", v -> back.run()), dp(48), dp(48));
432新增: TextView title = text(name, 32, palette.ink);
433新增: title.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
434新增: title.setPadding(0, dp(26), 0, dp(18));
435新增: form.addView(title);
436新增: }
437新增: private Button row(String title, View.OnClickListener listener) {
438新增: Button b = button(form, title, false, listener);
439新增: b.setGravity(Gravity.CENTER_VERTICAL | Gravity.START);
440新增: b.setPadding(dp(20), 0, dp(16), 0);
441新增: b.setBackground(pressable(palette.panel, 14, true));
442新增: return b;
443新增: }
444新增: private static final String[] THEMES = {"system", "light", "dark"};
445新增: private static final String[] THEME_NAMES = {"跟随系统", "浅色", "深色"};
446新增: private void showSettings(boolean focusTheme) {
447新增: settingsPage(Page.SETTINGS, "设置", this::showSetup);
448新增: label("外观", 14);
449新增: int index = java.util.Arrays.asList(THEMES).indexOf(themeMode());
450新增: LinearLayout options = column();
451新增: String current = "主题 · " + THEME_NAMES[Math.max(0, index)];
452新增: Button chooser = row(current + " ▾", v -> {
453新增: boolean opening = options.getVisibility() != View.VISIBLE;
454新增: options.setVisibility(opening ? View.VISIBLE : View.GONE);
455新增: ((Button)v).setText(current + (opening ? " ▴" : " ▾"));
456新增: });
457新增: form.addView(options);
458新增: options.setVisibility(View.GONE);
459新增: for (int i = 0; i < THEMES.length; i++) {
460新增: String value = THEMES[i];
461新增: Button choice = button(options, (i == index ? "✓ " : "") + THEME_NAMES[i], false, v -> {
462新增: appearance.edit().putString("theme", value).apply();
463新增: palette = MobileTheme.apply(this, value);
464新增: showSettings(!v.isInTouchMode());
465新增: });
466新增: choice.setSelected(i == index);
467新增: }
468新增: label("远程连接", 14);
469新增: row("已归档会话", v -> openArchivedSessions());
470新增: row("中继设置", v -> showAdvanced(Page.RELAY));
471新增: row("主机与指纹", v -> showAdvanced(Page.HOST));
472新增: statusView();
473新增: if (focusTheme) chooser.requestFocus();
474新增: }
475新增:
476新增: private void showAdvanced(Page next) {
477新增: boolean host = next == Page.HOST;
478新增: settingsPage(next, host ? "主机与指纹" : "中继设置", () -> showSettings(false));
479新增: verified = new CheckBox(this);
480新增: customRelay = new Switch(this);
481新增: customRelay.setText("使用自建中继");
482新增: form.addView(customRelay, -1, dp(48));
483新增: relayField = field("自建 VPS 的 HTTPS 地址", "");
484新增: customRelay.setOnCheckedChangeListener((view, enabled) -> {
485新增: relayField.setVisibility(enabled ? View.VISIBLE : View.GONE);
486新增: verified.setChecked(false);
487新增: });
488新增: displayRelay(imported != null && host ? imported.relay : preferredRelay());
489新增: if (!host) {
490新增: label("关闭自建中继后,使用 Cage 官方中继。", 14);
491新增: button(form, "保存中继设置", true, v -> {
492新增: try { rememberRelay(selectedRelay()); status.setText("中继设置已保存。"); }
493新增: catch (Exception e) { status.setText("请填写有效的 HTTPS 地址。"); }
494新增: });
495新增: statusView();
496新增: return;
497新增: }
498新增: label("这台手机的指纹", 15);
499新增: localPin = label(fingerprint.isEmpty() ? "正在读取设备密钥…" : fingerprint, 14);
500新增: localPin.setTypeface(Typeface.MONOSPACE);
501新增: localPin.setTextIsSelectable(true);
502新增: button(form, "复制手机指纹", false, v -> {
503新增: if (fingerprint.isEmpty()) return;
504新增: ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
505新增: clipboard.setPrimaryClip(ClipData.newPlainText("Cage 手机指纹", fingerprint));
506新增: status.setText("手机指纹已复制,请在电脑上核对并信任。");
507新增: });
508新增: label("电脑指纹", 15);
509新增: pinField = field("sha256:…", imported != null ? imported.pin : trust.getString("pin", ""));
510新增: verified.setText("我已与电脑上独立显示的指纹核对");
511新增: form.addView(verified);
512新增: TextWatcher changed = new TextWatcher() {
513新增: public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
514新增: public void onTextChanged(CharSequence s, int start, int before, int count) { verified.setChecked(false); }
515新增: public void afterTextChanged(Editable text) {}
516新增: };
517新增: pinField.addTextChangedListener(changed);
518新增: relayField.addTextChangedListener(changed);
519新增: button(form, "保存已核对的主机", true, v -> saveVerified());
520新增: forgetHost = button(form, "忘记主机", false, v -> new AlertDialog.Builder(this)
521新增: .setMessage("移除这台电脑的地址、指纹和重连凭据?")
522新增: .setNegativeButton("取消", null).setPositiveButton("忘记主机", (dialog, which) -> forget()).show());
523新增: forgetHost.setVisibility(trust.contains("pin") ? View.VISIBLE : View.GONE);
524新增: inviteStatus = label(imported != null ? "请与电脑独立显示的指纹核对,再保存主机。" :
525新增: invitation != null ? "已导入本次临时邀请。" :
526新增: credentials.saved() ? "这台电脑已保存,可以直接重新连接。" : "导入电脑生成的连接文件或临时邀请。", 14);
527新增: button(form, "导入连接文件", false, v -> {
528新增: Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT).addCategory(Intent.CATEGORY_OPENABLE).setType("*/*");
529新增: startActivityForResult(intent, PICK_INVITATION);
530新增: });
531新增: connect = button(form, credentials.saved() ? "重新连接" : "连接工作台", false, v -> connect());
532新增: statusView();
533新增: }
534新增:
535新增: private void saveVerified() {
536新增: if (!verified.isChecked()) { status.setText("请先在电脑上核对指纹。"); return; }
537新增: final String relay, pin;
538新增: try { relay = selectedRelay(); pin = Invitation.pin(pinField.getText().toString()); }
539新增: catch (Exception e) { status.setText("中继地址或电脑指纹格式无效。"); return; }
540新增: Invitation.Saved record = imported;
541新增: if (record != null && (!record.relay.equals(relay) || !record.pin.equals(pin))) { status.setText("填写内容与导入的连接文件不一致,请重新核对。"); return; }
542新增: int attempt = ++generation;
543新增: setConnecting(true);
544新增: worker.execute(() -> {
545新增: try {
546新增: credentials.save(relay, pin, record == null ? null : record.lookup);rememberRelay(relay);
547新增: runOnUiThread(() -> { if (generation == attempt) {
548新增: imported = null; verified.setChecked(false); setConnecting(false); forgetHost.setVisibility(View.VISIBLE);
549新增: connect.setText(credentials.saved() && invitation == null ? "重新连接" : "连接工作台");
550新增: if (credentials.saved() && invitation == null) inviteStatus.setText("这台电脑已保存,可以直接重新连接。");
551新增: status.setText(credentials.saved() ? "已保存这台电脑,可以重新连接。" : "已保存主机指纹。");
552新增: } });
553新增: } catch (Exception e) { runOnUiThread(() -> { if (generation == attempt) { setConnecting(false); status.setText("无法安全保存主机,请解锁手机后重试。"); } }); }
554新增: });
555新增: }
556新增: private void forget() {
557新增: int attempt = ++generation; setConnecting(true);
558新增: worker.execute(() -> {
559新增: try {
560新增: credentials.forget();
561新增: runOnUiThread(() -> { if (generation == attempt) { invitation=null; imported=null; setConnecting(false); showAdvanced(Page.HOST); status.setText("已忘记主机。"); } });
562新增: } catch (Exception e) { runOnUiThread(() -> { if (generation == attempt) { setConnecting(false); status.setText("移除未完成,请重试。"); } }); }
563新增: });
564新增: }
565新增:
566新增: @Override protected void onActivityResult(int code, int result, Intent data) {
567新增: super.onActivityResult(code, result, data);
568新增: if (code == SCAN) {
569新增: if(result==RESULT_OK && data!=null) pairScan(data.getStringExtra("code"));
570新增: else if(data!=null && data.hasExtra("error"))status.setText(data.getStringExtra("error"));
571新增: return;
572新增: }
573新增: if (code != PICK_INVITATION || result != RESULT_OK || data == null || data.getData() == null) return;
574新增: Uri file = data.getData();
575新增: if (!"content".equals(file.getScheme())) { status.setText("请选择设备文件应用中的邀请。"); return; }
576新增: int attempt = ++generation;
577新增: invitation = null; imported = null; verified.setChecked(false); setConnecting(true);
578新增: worker.execute(() -> {
579新增: try (InputStream input = getContentResolver().openInputStream(file)) {
580新增: JSONObject object = Invitation.read(input);
581新增: Invitation.Saved saved = object.has("version") ? new Invitation.Saved(object) : null;
582新增: Invitation item = saved == null ? Invitation.room(object) : null;
583新增: runOnUiThread(() -> { if (attempt == generation) {
584新增: setConnecting(false); invitation = item; imported = saved; status.setText("");
585新增: if (saved != null) {
586新增: displayRelay(saved.relay); pinField.setText(saved.pin); verified.setChecked(false);
587新增: inviteStatus.setText("请与电脑独立显示的指纹核对,再保存主机。");
588新增: } else { inviteStatus.setText("已导入本次临时邀请。"); }
589新增: connect.setText("连接工作台");
590新增: } });
591新增: } catch (Exception e) {
592新增: runOnUiThread(() -> { if (attempt == generation) { setConnecting(false); inviteStatus.setText("文件无效或临时邀请已过期,请重新导入。"); } });
593新增: }
594新增: });
595新增: }
596新增:
597新增: private void connect() {
598新增: connect(false);
599新增: }
600新增: private void connect(boolean archivedEntry) {
601新增: if (busy) return;
602新增: openArchivedAfterConnect = archivedEntry;
603新增: final String relay, pin;
604新增: try {
605新增: relay = page == Page.HOST ? selectedRelay() : trust.getString("relay", preferredRelay());
606新增: pin = Invitation.pin(page == Page.HOST ? pinField.getText().toString() : trust.getString("pin", ""));
607新增: } catch (Exception e) { status.setText("请在「设置 → 主机与指纹」保存电脑指纹。"); return; }
608新增: if ((page == Page.HOST && imported != null) || !credentials.matches(relay,pin)) { status.setText("请先核对并保存这台主机。"); return; }
609新增: ConnectedDevice existing = connections.get(relay + "\n" + pin);
610新增: if (existing != null) {
611新增: enterDevice(existing);
612新增: if (openArchivedAfterConnect) {
613新增: openArchivedAfterConnect = false;
614新增: browser.evaluateJavascript("window.dispatchEvent(new Event('cage-open-archives'))", null);
615新增: }
616新增: return;
617新增: }
618新增: if (device == null) { status.setText("设备密钥尚未就绪。"); return; }
619新增: Invitation item = page == Page.HOST ? invitation : null;
620新增: if (item == null && !credentials.saved()) { status.setText("请导入连接文件或有效的临时邀请。"); return; }
621新增: if (item != null && !item.expiry.isAfter(Instant.now())) { invitation=null; status.setText("临时邀请已过期,请重新连接或导入新邀请。"); return; }
622新增: invitation = null;
623新增: if (item != null) inviteStatus.setText("本次邀请已用于连接。");
624新增: int attempt = ++generation; setConnecting(true); status.setText("正在验证电脑并连接…");
625新增: worker.execute(() -> {
626新增: Client opened = null;
627新增: try {
628新增: String directory = extractUI();
629新增: opened = item == null
630新增: ? Cagemobile.openSaved(relay, credentials.lookup(relay, pin), pin, device)
631新增: : Cagemobile.open(relay, item.room, item.token, pin, device);
632新增: if (item == null) opened.reportDevice("android", deviceModel());
633新增: String launch = opened.startUI(directory);
634新增: Uri url = Uri.parse(launch);
635新增: if (!"http".equals(url.getScheme()) || !"127.0.0.1".equals(url.getHost()) || url.getPort()<1 || url.getUserInfo()!=null) throw new IOException();
636新增: Client connected = opened;
637新增: runOnUiThread(() -> {
638新增: if (attempt != generation || isDestroyed()) { close(connected); return; }
639新增: setConnecting(false);
640新增: ConnectedDevice next = new ConnectedDevice(relay + "\n" + pin, connected, url,
641新增: "电脑 " + (connections.size() + 1));
642新增: connections.put(next.hostKey, next);
643新增: createBrowser(next);
644新增: enterDevice(next);
645新增: broadcastDevices();
646新增: });
647新增: } catch (Exception e) {
648新增: close(opened);
649新增: runOnUiThread(() -> { if (attempt == generation) {
650新增: setConnecting(false); if (page == Page.HOST) connect.setText(credentials.saved() ? "重新连接" : "连接工作台");
651新增: status.setText(item == null ? "连接未完成。请确认电脑上的连接服务正在运行,再点重新连接。若已更换凭据,请导入新的连接文件。" : "连接未完成。请核对双方指纹与网络,再导入新邀请。");
652新增: } });
653新增: }
654新增: });
655新增: }
656新增: private void setConnecting(boolean connecting) {
657新增: busy = connecting;
658新增: enableActions(root, !connecting);
659新增: }
660新增: private static void enableActions(View view, boolean enabled) {
661新增: if (view instanceof android.view.ViewGroup) {
662新增: android.view.ViewGroup group = (android.view.ViewGroup)view;
663新增: for (int i = 0; i < group.getChildCount(); i++) enableActions(group.getChildAt(i), enabled);
664新增: } else if (view.isClickable() || view instanceof EditText) view.setEnabled(enabled);
665新增: }
666新增: private String extractUI() throws IOException {
667新增: File root = new File(getCacheDir(), "cage-mobile-ui");
668新增: copyAssets(getAssets(), "mobile-ui", root);
669新增: return root.getAbsolutePath();
670新增: }
671新增: private static void copyAssets(AssetManager assets, String path, File dest) throws IOException {
672新增: String[] children = assets.list(path);
673新增: if (children == null) throw new IOException("missing bundled assets");
674新增: if (children.length == 0) {
675新增: try (InputStream input = assets.open(path); OutputStream output = new FileOutputStream(dest)) {
676新增: byte[] bytes = new byte[16384]; int n;
677新增: while ((n=input.read(bytes))!=-1) output.write(bytes,0,n);
678新增: }
679新增: return;
680新增: }
681新增: if (!dest.isDirectory() && !dest.mkdirs()) throw new IOException("asset storage unavailable");
682新增: for (String child: children) copyAssets(assets,path+"/"+child,new File(dest,child));
683新增: }
684新增: private static boolean allowed(Uri url, int port) {
685新增: return "http".equals(url.getScheme()) && "127.0.0.1".equals(url.getHost()) && url.getPort() == port && url.getUserInfo() == null;
686新增: }
687新增: private JSONObject deviceSnapshot(ConnectedDevice current) {
688新增: JSONObject state = new JSONObject();
689新增: JSONArray devices = new JSONArray();
690新增: try {
691新增: for (ConnectedDevice connected : connections.values()) {
692新增: JSONObject item = new JSONObject();
693新增: item.put("id", connected.id); item.put("name", connected.name); devices.put(item);
694新增: }
695新增: state.put("current", current.id); state.put("devices", devices);
696新增: } catch (org.json.JSONException impossible) {throw new IllegalStateException(impossible);}
697新增: return state;
698新增: }
699新增: private String deviceScript(ConnectedDevice current) {
700新增: return "window.__cageDevices=" + deviceSnapshot(current).toString() +
701新增: ";window.dispatchEvent(new CustomEvent('cage-devices',{detail:window.__cageDevices}));";
702新增: }
703新增: private void broadcastDevices() {
704新增: for (ConnectedDevice connected : connections.values()) {
705新增: if (connected.script != null) connected.script.remove();
706新增: if (WebViewFeature.isFeatureSupported(WebViewFeature.DOCUMENT_START_SCRIPT))
707新增: connected.script = WebViewCompat.addDocumentStartJavaScript(connected.view, deviceScript(connected),
708新增: java.util.Collections.singleton("http://127.0.0.1:" + connected.launch.getPort()));
709新增: if (connected.view.getUrl() != null && allowed(Uri.parse(connected.view.getUrl()), connected.launch.getPort()))
710新增: connected.view.evaluateJavascript(deviceScript(connected), null);
711新增: }
712新增: }
713新增: private void deviceCommand(ConnectedDevice source, String json) {
714新增: if (!connections.containsValue(source) || isDestroyed()) return;
715新增: try {
716新增: JSONObject command = new JSONObject(json);
717新增: String action = command.optString("action");
718新增: if ("name".equals(action)) {
719新增: String name = command.optString("name").trim();
720新增: if (!name.isEmpty() && name.length() <= 120 && !name.equals(source.name)) {
721新增: source.name = name; broadcastDevices();
722新增: }
723新增: return;
724新增: }
725新增: if (!viewingWorkspace || source != activeDevice) return;
726新增: if ("home".equals(action)) showSetup();
727新增: } catch (org.json.JSONException ignored) {}
728新增: }
729新增: private void createBrowser(ConnectedDevice connected) {
730新增: WebView view = new WebView(this);
731新增: connected.view = view;
732新增: WebView.setWebContentsDebuggingEnabled(false);
733新增: WebSettings settings = view.getSettings(); settings.setJavaScriptEnabled(true); settings.setAllowFileAccess(false); settings.setAllowContentAccess(false);
734新增: settings.setUserAgentString(settings.getUserAgentString() + " CageMobile/1");
735新增: settings.setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW); settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
736新增: CookieManager.getInstance().setAcceptThirdPartyCookies(view,false);
737新增: final int port = connected.launch.getPort();
738新增: java.util.Set<String> origins = java.util.Collections.singleton("http://127.0.0.1:" + port);
739新增: if (WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER)) {
740新增: WebViewCompat.addWebMessageListener(view, "CageDevices", origins, (web, message, origin, mainFrame, reply) -> {
741新增: if (message.getType() == androidx.webkit.WebMessageCompat.TYPE_STRING && mainFrame &&
742新增: allowed(origin, port) && web.getUrl() != null && allowed(Uri.parse(web.getUrl()), port))
743新增: runOnUiThread(() -> deviceCommand(connected, message.getData()));
744新增: });
745新增: }
746新增: if (WebViewFeature.isFeatureSupported(WebViewFeature.DOCUMENT_START_SCRIPT))
747新增: connected.script = WebViewCompat.addDocumentStartJavaScript(view, deviceScript(connected), origins);
748新增: view.setWebViewClient(new WebViewClient() {
749新增: @Override public void onPageFinished(WebView w, String url) {
750新增: if (allowed(Uri.parse(url), port)) w.evaluateJavascript(deviceScript(connected), null);
751新增: }
752新增: @Override public boolean shouldOverrideUrlLoading(WebView w, WebResourceRequest r) {
753新增: String command = r.getUrl().toString();
754新增: if (r.isForMainFrame() && r.hasGesture() && w.getUrl() != null && allowed(Uri.parse(w.getUrl()), port)) {
755新增: if (command.equals("cage://home")) { w.post(() -> showSetup()); return true; }
756新增: }
757新增: return !allowed(r.getUrl(),port);
758新增: }
759新增: @Override public WebResourceResponse shouldInterceptRequest(WebView w, WebResourceRequest r) {
760新增: if (allowed(r.getUrl(),port)) return null;
761新增: return new WebResourceResponse("text/plain","UTF-8",403,"Forbidden",java.util.Collections.emptyMap(),new ByteArrayInputStream(new byte[0]));
762新增: }
763新增: });
764新增: Uri launch = connected.launch;
765新增: if (openArchivedAfterConnect) {
766新增: launch = launch.buildUpon().appendQueryParameter("page", "archived").build();
767新增: openArchivedAfterConnect = false;
768新增: }
769新增: view.loadUrl(launch.toString());
770新增: }
771新增: private void openArchivedSessions() {
772新增: if (activeDevice != null && connections.containsValue(activeDevice)) {
773新增: enterDevice(activeDevice);
774新增: browser.evaluateJavascript("window.dispatchEvent(new Event('cage-open-archives'))", null);
775新增: } else {
776新增: connect(true);
777新增: }
778新增: }
779新增: private void enterDevice(ConnectedDevice selected) {
780新增: if (!connections.containsValue(selected)) return;
781新增: if (browser != null && browser != selected.view) browser.onPause();
782新增: activeDevice = selected; browser = selected.view; viewingWorkspace = true;
783新增: LinearLayout pane = column();
784新增: if (browser.getParent() instanceof android.view.ViewGroup)
785新增: ((android.view.ViewGroup)browser.getParent()).removeView(browser);
786新增: pane.addView(browser, new LinearLayout.LayoutParams(-1,0,1));
787新增: setContentView(pane); insets(pane); browser.onResume(); broadcastDevices();
788新增: }
789新增: private void confirmDisconnect(ConnectedDevice selected) {
790新增: Dialog dialog = new Dialog(this);
791新增: LinearLayout panel = column(); panel.setPadding(dp(22),dp(18),dp(22),dp(22));
792新增: panel.setBackground(surface(palette.panel,26,false));
793新增: TextView title = text("取消与“" + selected.name + "”的连接?",20,palette.ink);
794新增: title.setTypeface(Typeface.DEFAULT,Typeface.BOLD); panel.addView(title);
795新增: TextView explanation = text("设备将从当前连接列表移除,已保存的配对信息仍然保留。",14,palette.muted);
796新增: explanation.setPadding(0,dp(12),0,dp(12)); panel.addView(explanation);
797新增: button(panel,"取消连接",true,v -> {dialog.dismiss(); disconnectDevice(selected);});
798新增: button(panel,"继续连接",false,v -> dialog.dismiss());
799新增: dialog.setContentView(panel);
800新增: android.view.Window window = dialog.getWindow();
801新增: if (window != null) {
802新增: window.setBackgroundDrawableResource(android.R.color.transparent);
803新增: window.setGravity(Gravity.BOTTOM);
804新增: window.setLayout(-1,-2);
805新增: }
806新增: dialog.show();
807新增: if (window != null) window.setLayout(-1,-2);
808新增: }
809新增: private static void close(Client c) { if (c!=null) try { c.close(); } catch (Exception ignored) { } }
810新增: private void disconnectDevice(ConnectedDevice connected) {
811新增: if (connections.remove(connected.hostKey) == null) return;
812新增: if (connected.script != null) connected.script.remove();
813新增: connected.view.stopLoading();
814新增: if (connected.view.getParent() instanceof android.view.ViewGroup)
815新增: ((android.view.ViewGroup)connected.view.getParent()).removeView(connected.view);
816新增: connected.view.destroy();
817新增: worker.execute(() -> close(connected.client));
818新增: if (activeDevice == connected) {
819新增: browser = null; activeDevice = null;
820新增: if (viewingWorkspace) showSetup();
821新增: }
822新增: if (page == Page.PAIR) showPair(false);
823新增: broadcastDevices();
824新增: }
825新增: private void endSession() {
826新增: ++generation; invitation = null;
827新增: for (ConnectedDevice connected : new java.util.ArrayList<>(connections.values())) {
828新增: if (connected.script != null) connected.script.remove();
829新增: connected.view.stopLoading(); connected.view.destroy();
830新增: worker.execute(() -> close(connected.client));
831新增: }
832新增: connections.clear(); browser = null; activeDevice = null;
833新增: }
834新增: @Override protected void onPause() {
835新增: if (viewingWorkspace && browser != null) browser.onPause();
836新增: super.onPause();
837新增: }
838新增: @Override protected void onResume() {
839新增: super.onResume();
840新增: if (viewingWorkspace && browser != null) browser.onResume();
841新增: }
842新增: @Override public void onBackPressed() {
843新增: if (busy) return;
844新增: if (viewingWorkspace && browser != null && browser.canGoBack()) browser.goBack();
845新增: else if (viewingWorkspace) showSetup();
846新增: else if (page == Page.CODE) showPair(false);
847新增: else if (page == Page.RELAY || page == Page.HOST) showSettings(false);
848新增: else if (page != Page.HOME) showSetup();
849新增: else super.onBackPressed();
850新增: }
851新增: @Override public void onDestroy() { endSession(); worker.shutdown(); super.onDestroy(); }
852新增:}
新增mobile/android/src/io/github/leexeo/cage/mobile/MobileTheme.java+34 −0看文件
@@ -0,0 +1,34 @@
1新增:package io.github.leexeo.cage.mobile;
2新增:
3新增:import android.app.Activity;
4新增:import android.content.res.Configuration;
5新增:import android.view.View;
6新增:
7新增:final class MobileTheme {
8新增: final boolean dark;
9新增: final int bg, panel, ink, muted, line, soft, action, onAction;
10新增:
11新增: private MobileTheme(boolean dark) {
12新增: this.dark = dark;
13新增: bg = dark ? 0xff191a18 : 0xfffaf9f6;
14新增: panel = dark ? 0xff252623 : 0xffffffff;
15新增: ink = dark ? 0xfff6f5ef : 0xff292a27;
16新增: muted = dark ? 0xffb5b6af : 0xff62645e;
17新增: line = dark ? 0xff44463f : 0xffdeded6;
18新增: soft = dark ? 0xff32342f : 0xffeeeee8;
19新增: action = ink;
20新增: onAction = bg;
21新增: }
22新增:
23新增: static MobileTheme apply(Activity activity, String mode) {
24新增: int night = activity.getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
25新增: boolean dark = "dark".equals(mode) || (!"light".equals(mode) && night == Configuration.UI_MODE_NIGHT_YES);
26新增: activity.setTheme(dark ? android.R.style.Theme_Material_NoActionBar : android.R.style.Theme_Material_Light_NoActionBar);
27新增: MobileTheme theme = new MobileTheme(dark);
28新增: activity.getWindow().setStatusBarColor(theme.bg);
29新增: activity.getWindow().setNavigationBarColor(theme.bg);
30新增: activity.getWindow().getDecorView().setSystemUiVisibility(dark ? 0 :
31新增: View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR | View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
32新增: return theme;
33新增: }
34新增:}
新增mobile/android/src/io/github/leexeo/cage/mobile/ScanActivity.java+139 −0看文件
@@ -0,0 +1,139 @@
1新增:package io.github.leexeo.cage.mobile;
2新增:
3新增:import android.animation.ValueAnimator;
4新增:import android.app.Activity;
5新增:import android.content.Intent;
6新增:import android.content.pm.PackageManager;
7新增:import android.graphics.*;
8新增:import android.hardware.Camera;
9新增:import android.os.Bundle;
10新增:import android.view.*;
11新增:import android.view.animation.LinearInterpolator;
12新增:import android.widget.*;
13新增:import com.google.zxing.*;
14新增:import com.google.zxing.common.HybridBinarizer;
15新增:import com.google.zxing.qrcode.QRCodeReader;
16新增:
17新增:// The camera only runs on this screen. Preview frames are decoded on-device.
18新增:@SuppressWarnings("deprecation")
19新增:public final class ScanActivity extends Activity implements SurfaceHolder.Callback, Camera.PreviewCallback {
20新增: private Camera camera;
21新增: private SurfaceView preview;
22新增: private TextView message;
23新增: private Finder finder;
24新增: private final QRCodeReader reader = new QRCodeReader();
25新增: private boolean resumed, finished;
26新增: private static final int PERMISSION = 1;
27新增: private int dp(float n) { return Math.round(n * getResources().getDisplayMetrics().density); }
28新增:
29新增: @Override public void onCreate(Bundle state) {
30新增: super.onCreate(state);
31新增: getWindow().getDecorView().setSystemUiVisibility(0);
32新增: getWindow().setStatusBarColor(0xff141716); getWindow().setNavigationBarColor(0xff141716);
33新增: FrameLayout frame = new FrameLayout(this); frame.setBackgroundColor(0xff141716);
34新增: preview = new SurfaceView(this);
35新增: frame.addView(preview,new FrameLayout.LayoutParams(-1,-1,Gravity.CENTER));
36新增: preview.getHolder().addCallback(this);
37新增: finder = new Finder(); frame.addView(finder,new FrameLayout.LayoutParams(-1,-1));
38新增: LinearLayout bar = new LinearLayout(this);bar.setGravity(Gravity.CENTER_VERTICAL);bar.setPadding(dp(12),0,dp(20),0);
39新增: Button cancel = new Button(this);cancel.setText("取消");cancel.setTextColor(Color.WHITE);cancel.setTextSize(15);
40新增: cancel.setBackgroundColor(Color.TRANSPARENT);cancel.setOnClickListener(v -> finish());bar.addView(cancel,new LinearLayout.LayoutParams(dp(72),dp(56)));
41新增: TextView title = new TextView(this);title.setText("扫描电脑二维码");title.setTextColor(Color.WHITE);title.setTextSize(18);title.setTypeface(Typeface.DEFAULT,Typeface.BOLD);
42新增: bar.addView(title); frame.addView(bar,new FrameLayout.LayoutParams(-1,dp(64),Gravity.TOP));
43新增: LinearLayout instructions = new LinearLayout(this);instructions.setOrientation(LinearLayout.VERTICAL);instructions.setGravity(Gravity.CENTER);
44新增: instructions.setPadding(dp(24),dp(12),dp(24),dp(20));
45新增: TextView heading = new TextView(this);heading.setText("连接你的电脑");heading.setTextSize(22);heading.setTextColor(Color.WHITE);heading.setTypeface(Typeface.DEFAULT,Typeface.BOLD);instructions.addView(heading);
46新增: message = new TextView(this);message.setGravity(Gravity.CENTER);message.setTextSize(15);message.setPadding(0,dp(12),0,dp(10));
47新增: message.setTextColor(0xffe1e5e2);message.setText("将 Cage 配对二维码放入框内\n在电脑「设置 → 远程连接」中生成");
48新增: message.setAccessibilityLiveRegion(View.ACCESSIBILITY_LIVE_REGION_POLITE);instructions.addView(message);
49新增: TextView privacy = new TextView(this);privacy.setText("仅识别 Cage 配对码");privacy.setTextSize(12);privacy.setTextColor(0xffa9b4ae);instructions.addView(privacy);
50新增: FrameLayout.LayoutParams copy = new FrameLayout.LayoutParams(-1,-2,Gravity.BOTTOM);frame.addView(instructions,copy);
51新增: frame.setOnApplyWindowInsetsListener((view,insets) -> {
52新增: view.setPadding(insets.getSystemWindowInsetLeft(),insets.getSystemWindowInsetTop(),insets.getSystemWindowInsetRight(),insets.getSystemWindowInsetBottom());return insets;
53新增: });
54新增: setContentView(frame);
55新增: if(checkSelfPermission(android.Manifest.permission.CAMERA)!=PackageManager.PERMISSION_GRANTED)
56新增: requestPermissions(new String[]{android.Manifest.permission.CAMERA},PERMISSION);
57新增: }
58新增: @Override public void onRequestPermissionsResult(int id,String[] names,int[] results) {
59新增: super.onRequestPermissionsResult(id,names,results);
60新增: if(id!=PERMISSION)return;
61新增: if(results.length>0 && results[0]==PackageManager.PERMISSION_GRANTED) start();
62新增: else finishWithError("相机权限未开启。可返回使用配对码,或在系统设置中允许相机访问。");
63新增: }
64新增: private void finishWithError(String error) {setResult(RESULT_CANCELED,new Intent().putExtra("error",error));finish();}
65新增: private void start() {
66新增: if(!resumed || isFinishing() || camera!=null || !preview.getHolder().getSurface().isValid() ||
67新增: checkSelfPermission(android.Manifest.permission.CAMERA)!=PackageManager.PERMISSION_GRANTED) return;
68新增: try {
69新增: camera=Camera.open();
70新增: Camera.Parameters p=camera.getParameters();
71新增: if(p.getSupportedFocusModes()!=null && p.getSupportedFocusModes().contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {
72新增: p.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);camera.setParameters(p);
73新增: }
74新增: Camera.CameraInfo info=new Camera.CameraInfo();Camera.getCameraInfo(0,info);
75新增: int rotation=(info.orientation-getWindowManager().getDefaultDisplay().getRotation()*90+360)%360;
76新增: camera.setDisplayOrientation(rotation);
77新增: // Keep the camera image in proportion; the parent clips the overflow.
78新增: Camera.Size size=p.getPreviewSize();
79新增: preview.post(() -> {
80新增: int width=(rotation%180==0)?size.width:size.height, height=(rotation%180==0)?size.height:size.width;
81新增: View parent=(View)preview.getParent();
82新增: float scale=Math.max((float)parent.getWidth()/width,(float)parent.getHeight()/height);
83新增: preview.setLayoutParams(new FrameLayout.LayoutParams(Math.round(width*scale),Math.round(height*scale),Gravity.CENTER));
84新增: });
85新增: camera.setPreviewDisplay(preview.getHolder());camera.setPreviewCallback(this);camera.startPreview();finder.animateScan(true);
86新增: } catch(Exception e){stop();finishWithError("无法打开相机,请重试或返回使用配对码。");}
87新增: }
88新增: private void stop(){finder.animateScan(false);if(camera!=null){camera.setPreviewCallback(null);camera.release();camera=null;}}
89新增: @Override public void onPreviewFrame(byte[] data,Camera source){
90新增: if(data==null || isFinishing() || finished)return;
91新增: Camera.Size size=source.getParameters().getPreviewSize();
92新增: try{
93新增: PlanarYUVLuminanceSource pixels=new PlanarYUVLuminanceSource(data,size.width,size.height,0,0,size.width,size.height,false);
94新增: String code=reader.decode(new BinaryBitmap(new HybridBinarizer(pixels))).getText();
95新增: if(code.startsWith("CAGE1:") && code.length()<=4096){
96新增: finished=true;finder.performHapticFeedback(HapticFeedbackConstants.CONFIRM);
97新增: setResult(RESULT_OK,new Intent().putExtra("code",code));finish();
98新增: } else message.setText("请扫描 Cage 配对二维码\n在电脑「设置 → 远程连接」中生成");
99新增: } catch(ReaderException ignored){} finally {reader.reset();}
100新增: }
101新增: @Override public void onResume(){super.onResume();resumed=true;start();}
102新增: @Override public void onPause(){resumed=false;stop();super.onPause();}
103新增: public void surfaceCreated(SurfaceHolder h){start();}
104新增: public void surfaceChanged(SurfaceHolder h,int f,int w,int height){start();}
105新增: public void surfaceDestroyed(SurfaceHolder h){stop();}
106新增:
107新增: private final class Finder extends View {
108新增: private final Paint paint=new Paint(Paint.ANTI_ALIAS_FLAG);
109新增: private final ValueAnimator sweep=ValueAnimator.ofFloat(0,1);
110新增: private float progress=.5f;
111新增: Finder(){
112新增: super(ScanActivity.this);setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO);
113新增: sweep.setDuration(2400);sweep.setRepeatCount(ValueAnimator.INFINITE);sweep.setRepeatMode(ValueAnimator.REVERSE);sweep.setInterpolator(new LinearInterpolator());
114新增: sweep.addUpdateListener(value -> {progress=(float)value.getAnimatedValue();invalidate();});
115新增: }
116新增: void animateScan(boolean running){
117新增: if(running && ValueAnimator.areAnimatorsEnabled()){if(!sweep.isStarted())sweep.start();}
118新增: else {sweep.cancel();progress=.5f;invalidate();}
119新增: }
120新增: @Override protected void onDraw(Canvas canvas){
121新增: float side=Math.max(dp(96),Math.min(dp(280),Math.min(getWidth()-dp(56),getHeight()-dp(250))));
122新增: float left=(getWidth()-side)/2, top=dp(72)+Math.max(0,(getHeight()-dp(250)-side)/2);
123新增: RectF box=new RectF(left,top,left+side,top+side);
124新增: Path shade=new Path();shade.setFillType(Path.FillType.EVEN_ODD);
125新增: shade.addRect(0,0,getWidth(),getHeight(),Path.Direction.CW);shade.addRoundRect(box,dp(18),dp(18),Path.Direction.CW);
126新增: paint.setStyle(Paint.Style.FILL);paint.setColor(0xb8141716);canvas.drawPath(shade,paint);
127新增: paint.setStyle(Paint.Style.STROKE);paint.setStrokeWidth(dp(1));paint.setColor(0x70ffffff);canvas.drawRoundRect(box,dp(18),dp(18),paint);
128新增: paint.setColor(0xffe8b79d);paint.setStrokeWidth(dp(4));paint.setStrokeCap(Paint.Cap.ROUND);
129新增: for(int x=0;x<2;x++)for(int y=0;y<2;y++){
130新增: canvas.save();canvas.translate(x==0?box.left:box.right,y==0?box.top:box.bottom);canvas.scale(x==0?1:-1,y==0?1:-1);
131新增: Path corner=new Path();corner.moveTo(0,dp(30));corner.lineTo(0,dp(18));corner.quadTo(0,0,dp(18),0);corner.lineTo(dp(30),0);canvas.drawPath(corner,paint);canvas.restore();
132新增: }
133新增: canvas.save();canvas.clipRect(box);float line=box.top+dp(24)+(side-dp(48))*progress;
134新增: paint.setStyle(Paint.Style.FILL);paint.setShader(new LinearGradient(0,line-dp(28),0,line,0x00e8b79d,0x35e8b79d,Shader.TileMode.CLAMP));
135新增: canvas.drawRect(box.left+dp(10),line-dp(28),box.right-dp(10),line,paint);paint.setShader(null);
136新增: paint.setColor(0xffe8b79d);canvas.drawRoundRect(box.left+dp(12),line,box.right-dp(12),line+dp(2),dp(1),dp(1),paint);canvas.restore();
137新增: }
138新增: }
139新增:}
新增mobile/assets/pair-devices.png看文件

二进制文件,不显示改动。

新增mobile/bindings/client.go+62 −0看文件
@@ -0,0 +1,62 @@
1新增:// Package cagemobile exposes the native signing and foreground connection API
2新增:// to generated Java and Objective-C code. gomobile's generated module must be
3新增:// able to import this public package; the implementation stays internal.
4新增:package cagemobile
5新增:
6新增:import (
7新增: "context"
8新增: "encoding/json"
9新增: "time"
10新增:
11新增: "github.com/sylvinus/agent-vm/internal/mobilelink"
12新增: "github.com/sylvinus/agent-vm/internal/mobilelink/nativeclient"
13新增:)
14新增:
15新增:func DefaultRelay() string { return mobilelink.OfficialRelay }
16新增:
17新增:type DeviceSigner interface {
18新增: PublicKeyDER() ([]byte, error)
19新增: SignSHA256(digest []byte) ([]byte, error)
20新增:}
21新增:
22新增:func Fingerprint(device DeviceSigner) (string, error) { return nativeclient.Fingerprint(device) }
23新增:
24新增:type Client struct{ native *nativeclient.Client }
25新增:
26新增:func Open(relayOrigin, roomID, clientToken, trustedHostPin string, device DeviceSigner) (*Client, error) {
27新增: client, err := nativeclient.Open(relayOrigin, roomID, clientToken, trustedHostPin, device)
28新增: if err != nil {
29新增: return nil, err
30新增: }
31新增: return &Client{native: client}, nil
32新增:}
33新增:
34新增:func OpenSaved(relayOrigin, lookupToken, trustedHostPin string, device DeviceSigner) (*Client, error) {
35新增: client, err := nativeclient.OpenSaved(relayOrigin, lookupToken, trustedHostPin, device)
36新增: if err != nil {
37新增: return nil, err
38新增: }
39新增: return &Client{native: client}, nil
40新增:}
41新增:
42新增:func (c *Client) StartUI(directory string) (string, error) { return c.native.StartUI(directory) }
43新增:func (c *Client) Close() error { return c.native.Close() }
44新增:
45新增:// ReportDevice is optional metadata for the desktop pairing card. An older host
46新增:// can refuse the operation without preventing the phone from opening its UI.
47新增:func (c *Client) ReportDevice(platform, model string) {
48新增: body, _ := json.Marshal(mobilelink.DeviceInfo{Platform: platform, Model: mobilelink.DeviceModel(platform, model)})
49新增: ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
50新增: defer cancel()
51新增: _, _ = c.native.Do(ctx, "POST", "/api/mobile/device", body)
52新增:}
53新增:
54新增:func Pair(code, relay string, device DeviceSigner) (string, error) {
55新增: pin, err := Fingerprint(device)
56新增: if err != nil {
57新增: return "", err
58新增: }
59新增: ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
60新增: defer cancel()
61新增: return mobilelink.RedeemPair(ctx, code, relay, pin)
62新增:}
新增mobile/bindings/go.mod+22 −0看文件
@@ -0,0 +1,22 @@
1新增:module github.com/sylvinus/agent-vm/mobile/bindings
2新增:
3新增:go 1.26.10
4新增:
5新增:require github.com/sylvinus/agent-vm v0.0.0
6新增:
7新增:require (
8新增: github.com/gorilla/websocket v1.5.3 // indirect
9新增: golang.org/x/mobile v0.0.0-20261011034528-197770444867 // indirect
10新增: golang.org/x/mod v0.42.0 // indirect
11新增: golang.org/x/net v0.61.0 // indirect
12新增: golang.org/x/sync v0.24.0 // indirect
13新增: golang.org/x/text v0.43.0 // indirect
14新增: golang.org/x/tools v0.52.0 // indirect
15新增:)
16新增:
17新增:replace github.com/sylvinus/agent-vm => ../..
18新增:
19新增:tool (
20新增: golang.org/x/mobile/cmd/gobind
21新增: golang.org/x/mobile/cmd/gomobile
22新增:)
新增mobile/bindings/go.sum+20 −0看文件
@@ -0,0 +1,20 @@
1新增:github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
2新增:github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
3新增:github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
4新增:github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
5新增:golang.org/x/mobile v0.0.0-20261011034528-197770444867 h1:rav73cdd7OQUPgt1aIFbZQTiPNnjfueKXvfOiLCY0Ss=
6新增:golang.org/x/mobile v0.0.0-20261011034528-197770444867/go.mod h1:HR/iBzuQmVTl/us733QPwrqHp43a8m9ZLgyKXD3ST6U=
7新增:golang.org/x/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg=
8新增:golang.org/x/mod v0.42.0/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs=
9新增:golang.org/x/net v0.61.0 h1:RR+6j/BTBCrggOLugxa+66R8FvoN6MHlzDlZIbN9YFw=
10新增:golang.org/x/net v0.61.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
11新增:golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
12新增:golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
13新增:golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
14新增:golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
15新增:golang.org/x/tools v0.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs=
16新增:golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs=
17新增:golang.org/x/tools/go/expect v0.1.1-deprecated h1:jpBZDwmgPhXsKZC6WhL20P4b/wmnpsEAGHaNy0n/rJM=
18新增:golang.org/x/tools/go/expect v0.1.1-deprecated/go.mod h1:eihoPOH+FgIqa3FpoTwguz/bVUSGBlGQU67vpBeOrBY=
19新增:golang.org/x/tools/go/packages/packagestest v0.1.1-deprecated h1:1h2MnaIAIXISqTFKdENegdpAgUXz6NrPEsbIeWaBRvM=
20新增:golang.org/x/tools/go/packages/packagestest v0.1.1-deprecated/go.mod h1:RVAQXBGNv1ib0J382/DPCRS/BPnsGebyM1Gj5VSDpG8=
新增mobile/build-ui.mjs+20 −0看文件
@@ -0,0 +1,20 @@
1新增:// Build only the phone entry and its imported assets into the app bundle.
2新增:import { createRequire } from "node:module";
3新增:import { fileURLToPath, pathToFileURL } from "node:url";
4新增:import { resolve } from "node:path";
5新增:
6新增:const ui = fileURLToPath(new URL("../ui/", import.meta.url));
7新增:const require = createRequire(new URL("../ui/package.json", import.meta.url));
8新增:const { build } = await import(pathToFileURL(require.resolve("vite")));
9新增:const { default: react } = await import(pathToFileURL(require.resolve("@vitejs/plugin-react")));
10新增:await build({
11新增: root: ui,
12新增: configFile: false,
13新增: publicDir: false,
14新增: plugins: [react()],
15新增: build: {
16新增: outDir: fileURLToPath(new URL("./.build/resources/mobile-ui/", import.meta.url)),
17新增: emptyOutDir: true,
18新增: rolldownOptions: { input: resolve(ui, "mobile.html") },
19新增: },
20新增:});
新增mobile/build.sh+75 −0看文件
@@ -0,0 +1,75 @@
1新增:#!/bin/bash
2新增:set -euo pipefail
3新增:mobile_dir="$(cd "$(dirname "$0")" && pwd)"
4新增:cd "$mobile_dir"
5新增:case "${1:-}" in
6新增: android|ios) platform="$1" ;;
7新增: ios-ipa|ios-ipa-basic)
8新增: platform=ios
9新增: if [[ $# != 2 || ! $2 =~ ^[A-Z0-9]{10}$ ]]; then
10新增: echo "Usage: mobile/build.sh $1 TEAM_ID (10 uppercase letters or digits)" >&2
11新增: exit 2
12新增: fi
13新增: ;;
14新增: *) echo "Usage: mobile/build.sh android | ios | ios-ipa TEAM_ID | ios-ipa-basic TEAM_ID" >&2; exit 2 ;;
15新增:esac
16新增:if [[ "$platform" == ios ]]; then
17新增: # xcrun distinguishes a missing SDK from a pending Xcode license or setup step.
18新增: xcrun --sdk iphoneos --show-sdk-path >/dev/null
19新增:fi
20新增:mkdir -p .build/bin ".build/$platform"
21新增:node build-ui.mjs
22新增:if [[ "$platform" == android ]]; then bash android/fetch-webkit.sh "$mobile_dir/.build/android"; fi
23新增:bash scripts/licenses.sh
24新增:(
25新增: cd bindings
26新增: go build -o ../.build/bin/gomobile golang.org/x/mobile/cmd/gomobile
27新增: go build -o ../.build/bin/gobind golang.org/x/mobile/cmd/gobind
28新增:)
29新增:export PATH="$mobile_dir/.build/bin:$PATH"
30新增:if [[ -n "${JAVA_HOME:-}" ]]; then export PATH="$JAVA_HOME/bin:$PATH"; fi
31新增:if [[ "$platform" == ios ]]; then
32新增: brand=".build/ios/Assets.xcassets/CageMark.imageset"
33新增: mkdir -p "$brand"
34新增: cp ../ui/src/logo.png "$brand/mark.png"
35新增: printf '%s\n' '{"images":[{"filename":"mark.png","idiom":"universal"}],"info":{"author":"xcode","version":1}}' > "$brand/Contents.json"
36新增: devices=".build/ios/Assets.xcassets/PairDevices.imageset"
37新增: mkdir -p "$devices"
38新增: cp assets/pair-devices.png "$devices/devices.png"
39新增: sed 's/mark.png/devices.png/' "$brand/Contents.json" > "$devices/Contents.json"
40新增: icon=".build/ios/Assets.xcassets/AppIcon.appiconset"
41新增: mkdir -p "$icon"
42新增: printf '%s\n' '{"info":{"author":"xcode","version":1}}' > ".build/ios/Assets.xcassets/Contents.json"
43新增: cp ios/AppIcon.json "$icon/Contents.json"
44新增: sips -z 1024 1024 ../ui/src/logo.png --out "$icon/Cage.png" >/dev/null
45新增: # One arm64 iPhone slice and one simulator slice for this Mac.
46新增: # Each platform framework is then passed to -create-xcframework exactly once.
47新增: (cd bindings && gomobile bind -target="ios/arm64,iossimulator/$(go env GOHOSTARCH)" -iosversion=17.0 -o "$mobile_dir/.build/ios/Cagemobile.xcframework" .)
48新增: if [[ "$1" == ios-ipa* ]]; then
49新增: scheme=CageMobile
50新增: if [[ "$1" == ios-ipa-basic ]]; then scheme=CageMobileBasic; fi
51新增: output=$(mktemp -d "$mobile_dir/.build/ios/device-XXXXXXXX")
52新增: xcodebuild -project ios/CageMobile.xcodeproj -scheme "$scheme" -configuration Release \
53新增: -destination 'generic/platform=iOS' -archivePath "$output/CageMobile.xcarchive" \
54新增: DEVELOPMENT_TEAM="$2" archive
55新增: xcodebuild -exportArchive -archivePath "$output/CageMobile.xcarchive" \
56新增: -exportOptionsPlist ios/DebuggingExport.plist -exportPath "$output/export"
57新增: ipa="$output/export/$scheme.ipa"
58新增: # Inspect the exported payload, which Xcode can re-sign after archiving.
59新增: ditto -x -k "$ipa" "$output/check"
60新增: app="$output/check/Payload/$scheme.app"
61新增: test -s "$app/embedded.mobileprovision"
62新增: codesign --verify --deep --strict "$app"
63新增: rm -r "$output/check"
64新增: printf 'Cage iPhone development IPA: %s\n' "$ipa"
65新增: else
66新增: xcodebuild -project ios/CageMobile.xcodeproj -target CageMobile -sdk iphoneos -configuration Debug \
67新增: CODE_SIGNING_ALLOWED=NO SYMROOT="$mobile_dir/.build/ios/products" OBJROOT="$mobile_dir/.build/ios/obj" build
68新增: fi
69新增:else
70新增: : "${ANDROID_HOME:?Set ANDROID_HOME to the Android SDK directory}"
71新增: (cd bindings && gomobile bind -target=android/arm64 -androidapi=26 \
72新增: -ldflags='-extldflags=-Wl,-z,max-page-size=16384,-z,common-page-size=16384' \
73新增: -o "$mobile_dir/.build/android/Cagemobile.aar" .)
74新增: bash android/package.sh
75新增:fi
新增mobile/ios/AppIcon.json+4 −0看文件
@@ -0,0 +1,4 @@
1新增:{
2新增: "images": [{ "filename": "Cage.png", "idiom": "universal", "platform": "ios", "size": "1024x1024" }],
3新增: "info": { "author": "xcode", "version": 1 }
4新增:}
新增mobile/ios/CageMobile.xcodeproj/project.pbxproj+58 −0看文件
@@ -0,0 +1,58 @@
1新增:// !$*UTF8*$!
2新增:{
3新增: archiveVersion = 1;
4新增: classes = {};
5新增: objectVersion = 56;
6新增: objects = {
7新增: 010000000000000000000001 = {isa = PBXProject; attributes = {LastUpgradeCheck = 1600;}; buildConfigurationList = 030000000000000000000001; compatibilityVersion = "Xcode 14.0"; developmentRegion = zh_CN; hasScannedForEncodings = 0; knownRegions = (zh_CN, Base); mainGroup = 020000000000000000000001; productRefGroup = 020000000000000000000002; projectDirPath = ""; projectRoot = ""; targets = (040000000000000000000001,040000000000000000000301); };
8新增: 020000000000000000000001 = {isa = PBXGroup; children = (020000000000000000000003, 050000000000000000000005, 050000000000000000000006, 050000000000000000000008, 050000000000000000000010, 020000000000000000000002); sourceTree = "<group>";};
9新增: 020000000000000000000002 = {isa = PBXGroup; children = (050000000000000000000007,050000000000000000000307); name = Products; sourceTree = "<group>";};
10新增: 020000000000000000000003 = {isa = PBXGroup; children = (050000000000000000000011, 050000000000000000000001, 050000000000000000000009, 050000000000000000000002, 050000000000000000000003, 050000000000000000000004); path = CageMobile; sourceTree = "<group>";};
11新增: 030000000000000000000001 = {isa = XCConfigurationList; buildConfigurations = (080000000000000000000001,080000000000000000000002); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release;};
12新增: 030000000000000000000002 = {isa = XCConfigurationList; buildConfigurations = (080000000000000000000003,080000000000000000000004); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release;};
13新增: 040000000000000000000001 = {isa = PBXNativeTarget; buildConfigurationList = 030000000000000000000002; buildPhases = (070000000000000000000001,070000000000000000000002,070000000000000000000003); buildRules = (); dependencies = (); name = CageMobile; productName = CageMobile; productReference = 050000000000000000000007; productType = "com.apple.product-type.application";};
14新增: 050000000000000000000011 = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SimulatorWorkspacePreview.swift; sourceTree = "<group>";};
15新增: 050000000000000000000001 = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CageMobile.swift; sourceTree = "<group>";};
16新增: 050000000000000000000002 = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = NativeConnection.m; sourceTree = "<group>";};
17新增: 050000000000000000000003 = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = NativeConnection.h; sourceTree = "<group>";};
18新增: 050000000000000000000004 = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>";};
19新增: 050000000000000000000005 = {isa = PBXFileReference; lastKnownFileType = wrapper.xcframework; name = Cagemobile.xcframework; path = ../.build/ios/Cagemobile.xcframework; sourceTree = "<group>";};
20新增: 050000000000000000000006 = {isa = PBXFileReference; lastKnownFileType = folder; name = "mobile-ui"; path = "../.build/resources/mobile-ui"; sourceTree = "<group>";};
21新增: 050000000000000000000007 = {isa = PBXFileReference; explicitFileType = wrapper.application; path = CageMobile.app; sourceTree = BUILT_PRODUCTS_DIR;};
22新增: 050000000000000000000008 = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Assets.xcassets; path = ../.build/ios/Assets.xcassets; sourceTree = "<group>";};
23新增: 050000000000000000000009 = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConnectionFile.swift; sourceTree = "<group>";};
24新增: 050000000000000000000010 = {isa = PBXFileReference; lastKnownFileType = folder; name = licenses; path = "../.build/resources/licenses"; sourceTree = "<group>";};
25新增: 060000000000000000000008 = {isa = PBXBuildFile; fileRef = 050000000000000000000011;};
26新增: 060000000000000000000007 = {isa = PBXBuildFile; fileRef = 050000000000000000000010;};
27新增: 060000000000000000000006 = {isa = PBXBuildFile; fileRef = 050000000000000000000009;};
28新增: 060000000000000000000005 = {isa = PBXBuildFile; fileRef = 050000000000000000000008;};
29新增: 060000000000000000000001 = {isa = PBXBuildFile; fileRef = 050000000000000000000001;};
30新增: 060000000000000000000002 = {isa = PBXBuildFile; fileRef = 050000000000000000000002;};
31新增: 060000000000000000000003 = {isa = PBXBuildFile; fileRef = 050000000000000000000005;};
32新增: 060000000000000000000004 = {isa = PBXBuildFile; fileRef = 050000000000000000000006;};
33新增: 070000000000000000000001 = {isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = (060000000000000000000001,060000000000000000000002,060000000000000000000006,060000000000000000000008); runOnlyForDeploymentPostprocessing = 0;};
34新增: 070000000000000000000002 = {isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = (060000000000000000000003); runOnlyForDeploymentPostprocessing = 0;};
35新增: 070000000000000000000003 = {isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = (060000000000000000000004,060000000000000000000005,060000000000000000000007); runOnlyForDeploymentPostprocessing = 0;};
36新增: 080000000000000000000001 = {isa = XCBuildConfiguration; buildSettings = {CAGE_APP_ID = "io.github.lee-xeo.claude-cage.mobile"; SDKROOT = iphoneos; SUPPORTED_PLATFORMS = "iphoneos iphonesimulator"; "ONLY_ACTIVE_ARCH[sdk=iphonesimulator*]" = YES; IPHONEOS_DEPLOYMENT_TARGET = 17.0; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; OTHER_LDFLAGS = ("$(inherited)", "-lresolv", "-framework", Security); SWIFT_VERSION = 5.0; SWIFT_OPTIMIZATION_LEVEL = "-Onone";}; name = Debug;};
37新增: 080000000000000000000002 = {isa = XCBuildConfiguration; buildSettings = {CAGE_APP_ID = "io.github.lee-xeo.claude-cage.mobile"; SDKROOT = iphoneos; SUPPORTED_PLATFORMS = "iphoneos iphonesimulator"; "ONLY_ACTIVE_ARCH[sdk=iphonesimulator*]" = YES; IPHONEOS_DEPLOYMENT_TARGET = 17.0; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; OTHER_LDFLAGS = ("$(inherited)", "-lresolv", "-framework", Security); SWIFT_VERSION = 5.0;}; name = Release;};
38新增: 080000000000000000000003 = {isa = XCBuildConfiguration; buildSettings = {"GCC_PREPROCESSOR_DEFINITIONS[sdk=iphonesimulator*]" = ("$(inherited)", "CAGE_SIMULATOR_DEBUG=1"); ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CODE_SIGN_STYLE = Automatic; INFOPLIST_FILE = CageMobile/Info.plist; PRODUCT_BUNDLE_IDENTIFIER = "$(CAGE_APP_ID)"; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OBJC_BRIDGING_HEADER = CageMobile/NativeConnection.h; TARGETED_DEVICE_FAMILY = "1,2";}; name = Debug;};
39新增: 080000000000000000000004 = {isa = XCBuildConfiguration; buildSettings = {ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CODE_SIGN_STYLE = Automatic; INFOPLIST_FILE = CageMobile/Info.plist; PRODUCT_BUNDLE_IDENTIFIER = "$(CAGE_APP_ID)"; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OBJC_BRIDGING_HEADER = CageMobile/NativeConnection.h; TARGETED_DEVICE_FAMILY = "1,2";}; name = Release;};
40新增: 030000000000000000000302 = {isa = XCConfigurationList; buildConfigurations = (080000000000000000000303,080000000000000000000304); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release;};
41新增: 040000000000000000000301 = {isa = PBXNativeTarget; buildConfigurationList = 030000000000000000000302; buildPhases = (070000000000000000000301,070000000000000000000302,070000000000000000000303); buildRules = (); dependencies = (); name = CageMobileBasic; productName = CageMobileBasic; productReference = 050000000000000000000307; productType = "com.apple.product-type.application";};
42新增: 050000000000000000000307 = {isa = PBXFileReference; explicitFileType = wrapper.application; path = CageMobileBasic.app; sourceTree = BUILT_PRODUCTS_DIR;};
43新增: 060000000000000000000301 = {isa = PBXBuildFile; fileRef = 050000000000000000000001;};
44新增: 060000000000000000000302 = {isa = PBXBuildFile; fileRef = 050000000000000000000002;};
45新增: 060000000000000000000303 = {isa = PBXBuildFile; fileRef = 050000000000000000000005;};
46新增: 060000000000000000000304 = {isa = PBXBuildFile; fileRef = 050000000000000000000006;};
47新增: 060000000000000000000305 = {isa = PBXBuildFile; fileRef = 050000000000000000000008;};
48新增: 060000000000000000000306 = {isa = PBXBuildFile; fileRef = 050000000000000000000009;};
49新增: 060000000000000000000307 = {isa = PBXBuildFile; fileRef = 050000000000000000000010;};
50新增: 060000000000000000000308 = {isa = PBXBuildFile; fileRef = 050000000000000000000011;};
51新增: 070000000000000000000301 = {isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = (060000000000000000000301,060000000000000000000302,060000000000000000000306,060000000000000000000308); runOnlyForDeploymentPostprocessing = 0;};
52新增: 070000000000000000000302 = {isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = (060000000000000000000303); runOnlyForDeploymentPostprocessing = 0;};
53新增: 070000000000000000000303 = {isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = (060000000000000000000304,060000000000000000000305,060000000000000000000307); runOnlyForDeploymentPostprocessing = 0;};
54新增: 080000000000000000000303 = {isa = XCBuildConfiguration; buildSettings = {"GCC_PREPROCESSOR_DEFINITIONS[sdk=iphonesimulator*]" = ("$(inherited)", "CAGE_SIMULATOR_DEBUG=1"); ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CODE_SIGN_STYLE = Automatic; INFOPLIST_FILE = CageMobile/Info.plist; PRODUCT_BUNDLE_IDENTIFIER = "$(CAGE_APP_ID)"; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OBJC_BRIDGING_HEADER = CageMobile/NativeConnection.h; TARGETED_DEVICE_FAMILY = "1,2";}; name = Debug;};
55新增: 080000000000000000000304 = {isa = XCBuildConfiguration; buildSettings = {ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; CODE_SIGN_STYLE = Automatic; INFOPLIST_FILE = CageMobile/Info.plist; PRODUCT_BUNDLE_IDENTIFIER = "$(CAGE_APP_ID)"; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OBJC_BRIDGING_HEADER = CageMobile/NativeConnection.h; TARGETED_DEVICE_FAMILY = "1,2";}; name = Release;};
56新增: };
57新增: rootObject = 010000000000000000000001;
58新增:}
新增mobile/ios/CageMobile.xcodeproj/xcshareddata/xcschemes/CageMobile.xcscheme+23 −0看文件
@@ -0,0 +1,23 @@
1新增:<?xml version="1.0" encoding="UTF-8"?>
2新增:<Scheme LastUpgradeVersion="1600" version="1.7">
3新增: <BuildAction parallelizeBuildables="YES" buildImplicitDependencies="YES">
4新增: <BuildActionEntries>
5新增: <BuildActionEntry buildForTesting="YES" buildForRunning="YES" buildForProfiling="YES" buildForArchiving="YES" buildForAnalyzing="YES">
6新增: <BuildableReference BuildableIdentifier="primary" BlueprintIdentifier="040000000000000000000001" BuildableName="CageMobile.app" BlueprintName="CageMobile" ReferencedContainer="container:CageMobile.xcodeproj"/>
7新增: </BuildActionEntry>
8新增: </BuildActionEntries>
9新增: </BuildAction>
10新增: <TestAction buildConfiguration="Debug" selectedDebuggerIdentifier="Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier="Xcode.DebuggerFoundation.Launcher.LLDB" shouldUseLaunchSchemeArgsEnv="YES"/>
11新增: <LaunchAction buildConfiguration="Debug" selectedDebuggerIdentifier="Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier="Xcode.DebuggerFoundation.Launcher.LLDB" launchStyle="0" useCustomWorkingDirectory="NO" ignoresPersistentStateOnLaunch="NO" debugDocumentVersioning="YES" allowLocationSimulation="YES">
12新增: <BuildableProductRunnable runnableDebuggingMode="0">
13新增: <BuildableReference BuildableIdentifier="primary" BlueprintIdentifier="040000000000000000000001" BuildableName="CageMobile.app" BlueprintName="CageMobile" ReferencedContainer="container:CageMobile.xcodeproj"/>
14新增: </BuildableProductRunnable>
15新增: </LaunchAction>
16新增: <ProfileAction buildConfiguration="Release" shouldUseLaunchSchemeArgsEnv="YES" savedToolIdentifier="" useCustomWorkingDirectory="NO" debugDocumentVersioning="YES">
17新增: <BuildableProductRunnable runnableDebuggingMode="0">
18新增: <BuildableReference BuildableIdentifier="primary" BlueprintIdentifier="040000000000000000000001" BuildableName="CageMobile.app" BlueprintName="CageMobile" ReferencedContainer="container:CageMobile.xcodeproj"/>
19新增: </BuildableProductRunnable>
20新增: </ProfileAction>
21新增: <AnalyzeAction buildConfiguration="Debug"/>
22新增: <ArchiveAction buildConfiguration="Release" revealArchiveInOrganizer="YES"/>
23新增:</Scheme>
新增mobile/ios/CageMobile.xcodeproj/xcshareddata/xcschemes/CageMobileBasic.xcscheme+23 −0看文件
@@ -0,0 +1,23 @@
1新增:<?xml version="1.0" encoding="UTF-8"?>
2新增:<Scheme LastUpgradeVersion="1600" version="1.7">
3新增: <BuildAction parallelizeBuildables="YES" buildImplicitDependencies="YES">
4新增: <BuildActionEntries>
5新增: <BuildActionEntry buildForTesting="YES" buildForRunning="YES" buildForProfiling="YES" buildForArchiving="YES" buildForAnalyzing="YES">
6新增: <BuildableReference BuildableIdentifier="primary" BlueprintIdentifier="040000000000000000000301" BuildableName="CageMobileBasic.app" BlueprintName="CageMobileBasic" ReferencedContainer="container:CageMobile.xcodeproj"/>
7新增: </BuildActionEntry>
8新增: </BuildActionEntries>
9新增: </BuildAction>
10新增: <TestAction buildConfiguration="Debug" selectedDebuggerIdentifier="Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier="Xcode.DebuggerFoundation.Launcher.LLDB" shouldUseLaunchSchemeArgsEnv="YES"/>
11新增: <LaunchAction buildConfiguration="Debug" selectedDebuggerIdentifier="Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier="Xcode.DebuggerFoundation.Launcher.LLDB" launchStyle="0" useCustomWorkingDirectory="NO" ignoresPersistentStateOnLaunch="NO" debugDocumentVersioning="YES" allowLocationSimulation="YES">
12新增: <BuildableProductRunnable runnableDebuggingMode="0">
13新增: <BuildableReference BuildableIdentifier="primary" BlueprintIdentifier="040000000000000000000301" BuildableName="CageMobileBasic.app" BlueprintName="CageMobileBasic" ReferencedContainer="container:CageMobile.xcodeproj"/>
14新增: </BuildableProductRunnable>
15新增: </LaunchAction>
16新增: <ProfileAction buildConfiguration="Release" shouldUseLaunchSchemeArgsEnv="YES" savedToolIdentifier="" useCustomWorkingDirectory="NO" debugDocumentVersioning="YES">
17新增: <BuildableProductRunnable runnableDebuggingMode="0">
18新增: <BuildableReference BuildableIdentifier="primary" BlueprintIdentifier="040000000000000000000301" BuildableName="CageMobileBasic.app" BlueprintName="CageMobileBasic" ReferencedContainer="container:CageMobile.xcodeproj"/>
19新增: </BuildableProductRunnable>
20新增: </ProfileAction>
21新增: <AnalyzeAction buildConfiguration="Debug"/>
22新增: <ArchiveAction buildConfiguration="Release" revealArchiveInOrganizer="YES"/>
23新增:</Scheme>
新增mobile/ios/CageMobile/CageMobile.swift+690 −0看文件
@@ -0,0 +1,690 @@
1新增:import Foundation
2新增:import SwiftUI
3新增:import VisionKit
4新增:import AVFoundation
5新增:import UniformTypeIdentifiers
6新增:import WebKit
7新增:private var simulatorPreviewEnabled: Bool {
8新增: #if targetEnvironment(simulator)
9新增: return true
10新增: #else
11新增: return false
12新增: #endif
13新增:}
14新增:
15新增:struct ConnectedDevice: Identifiable {
16新增: let id: String
17新增: var name: String
18新增: let connection: CMConnection?
19新增: let webView: WKWebView
20新增:}
21新增:
22新增:final class DeviceWebBridge: NSObject, WKScriptMessageHandler {
23新增: weak var model: ConnectionModel?
24新增: let id: String
25新增: let origin: URL
26新增: init(model: ConnectionModel, id: String, origin: URL) {self.model = model; self.id = id; self.origin = origin}
27新增: func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
28新增: guard let model, model.devices.contains(where: {$0.id == id && $0.webView === message.webView}),
29新增: message.frameInfo.isMainFrame, let url = message.frameInfo.request.url,
30新增: url.scheme == origin.scheme, url.host == origin.host, url.port == origin.port,
31新增: let body = message.body as? [String: Any], let action = body["action"] as? String else {return}
32新增: if action == "name" {
33新增: if let name = body["name"] as? String {model.nameDevice(id, name)}
34新增: return
35新增: }
36新增: guard model.showingWorkspace, model.selectedDeviceID == id else {return}
37新增: if action == "home" {model.leaveWorkspace()}
38新增: }
39新增:}
40新增:
41新增:final class ConnectionModel: ObservableObject {
42新增:
43新增: @Published var relay = CMConnection.defaultRelay()
44新增: @Published var pin = ""
45新增: @Published var fingerprint = ""
46新增: @Published var verified = false
47新增: @Published var hasInvitation = false
48新增: @Published var hasSaved = false
49新增: @Published var needsTrust = false
50新增: @Published var status = ""
51新增: @Published var connecting = false
52新增: @Published var session: CMConnection?
53新增: @Published var devices: [ConnectedDevice] = []
54新增: @Published var selectedDeviceID: String?
55新增: @Published var showingWorkspace = false
56新增: var selectedDevice: ConnectedDevice? {devices.first {$0.id == selectedDeviceID}}
57新增:
58新增: private var invitation: Invitation?
59新增: private var imported: HostAccess?
60新增: private var trusted: Host?
61新增: private var generation = 0
62新增: private var openArchivedAfterConnect = false
63新增: private let trustKey = "independently-verified-host-v1"
64新增: private let linkQueue = DispatchQueue(label: "CageMobile.connection")
65新增: var canForget: Bool { trusted != nil }
66新增: var canConnect: Bool { !connecting && !needsTrust && !fingerprint.isEmpty && (hasInvitation || hasSaved) }
67新增:
68新增: init() {
69新增: if let data = UserDefaults.standard.data(forKey: trustKey), let host = try? JSONDecoder().decode(Host.self, from: data) {
70新增: trusted = host; relay = host.relay; pin = host.pin
71新增: }
72新增: do {
73新增: if let saved = try HostKeychain.read() {
74新增: trusted = saved.host; relay = saved.host.relay; pin = saved.host.pin; hasSaved = true
75新增: }
76新增: } catch {
77新增: status = "无法读取已保存的连接,请解锁手机后重新打开。"
78新增: }
79新增: if let selected = UserDefaults.standard.string(forKey:"preferred-relay") {relay = selected}
80新增: DispatchQueue.global(qos: .userInitiated).async {
81新增: do {
82新增: let value = try CMConnection.deviceFingerprint()
83新增: DispatchQueue.main.async { self.fingerprint = value }
84新增: } catch {
85新增: DispatchQueue.main.async { self.status = error.localizedDescription }
86新增: }
87新增: }
88新增: }
89新增: func pair(code: String) {
90新增: guard !connecting else {return}
91新增: connecting = true; generation += 1
92新增: let attempt = generation
93新增: let address = UserDefaults.standard.string(forKey: "preferred-relay") ?? trusted?.relay ?? CMConnection.defaultRelay()
94新增: status = "正在与电脑配对…"
95新增: linkQueue.async {
96新增: let result = Result { () throws -> HostAccess in
97新增: let data = Data(try CMConnection.pair(code: code, relay: address).utf8)
98新增: guard case .persistent(let access) = try ConnectionFile.parse(data) else {throw InputError.invalid}
99新增: return access
100新增: }
101新增: DispatchQueue.main.async {
102新增: guard attempt == self.generation else {return}
103新增: self.connecting = false
104新增: do {
105新增: let saved = try result.get()
106新增: try HostKeychain.write(saved)
107新增: UserDefaults.standard.set(saved.host.relay,forKey:"preferred-relay")
108新增: self.trusted = saved.host; self.pin = saved.host.pin; self.relay = saved.host.relay
109新增: self.imported = nil; self.invitation = nil; self.hasInvitation = false
110新增: self.hasSaved = true; self.needsTrust = false; self.verified = false
111新增: self.connect()
112新增: } catch { self.status = error.localizedDescription }
113新增: }
114新增: }
115新增: }
116新增: func saveRelay() {
117新增: let input = relay.trimmingCharacters(in: .whitespacesAndNewlines)
118新增: guard let u = URLComponents(string: input), u.scheme?.lowercased() == "https",
119新增: let host=u.host, !host.isEmpty, u.user==nil, u.password==nil, u.query==nil, u.fragment==nil,
120新增: (u.path=="" || u.path=="/"), (1...65535).contains(u.port ?? 443) else {status="请填写有效的 HTTPS 地址。";return}
121新增: relay=input.hasSuffix("/") ? String(input.dropLast()) : input
122新增: UserDefaults.standard.set(relay,forKey:"preferred-relay")
123新增: status="中继设置已保存。"
124新增: }
125新增: func saveTrust() {
126新增: guard verified, let host = try? Host(relay: relay, pin: pin), let data = try? JSONEncoder().encode(host) else {
127新增: status = "请填写有效的中继地址,核对电脑指纹后再保存。"; return
128新增: }
129新增: do {
130新增: if let record = imported {
131新增: guard record.host == host else { status = "填写内容与连接文件不一致,请重新核对。"; return }
132新增: try HostKeychain.write(record)
133新增: hasSaved = true
134新增: } else if trusted != host {
135新增: hasSaved = try HostKeychain.read(host: host) != nil
136新增: }
137新增: } catch { status = "无法安全保存主机,请解锁手机后重试。"; return }
138新增: trusted = host; UserDefaults.standard.set(host.relay,forKey:"preferred-relay"); UserDefaults.standard.set(data, forKey: trustKey); verified = false
139新增: imported = nil; needsTrust = false
140新增: status = hasSaved ? "已保存这台电脑,可以重新连接。" : "已保存主机指纹。"
141新增: }
142新增: func loadInvitation(_ file: URL) {
143新增: invitation = nil; imported = nil; needsTrust = false; hasInvitation = false; verified = false
144新增: do {
145新增: switch try ConnectionFile.load(file) {
146新增: case .temporary(let room):
147新增: invitation = room; hasInvitation = true; status = "已导入本次临时邀请。"
148新增: case .persistent(let saved):
149新增: imported = saved; needsTrust = true; relay = saved.host.relay; pin = saved.host.pin
150新增: status = "请与电脑上独立显示的指纹核对,再保存这台主机。"
151新增: }
152新增: } catch { status = "文件无效或临时邀请已过期,请重新导入。" }
153新增: }
154新增: func forget() {
155新增: do { try HostKeychain.forget(host: trusted) } catch { status = "移除未完成,请解锁手机后重试。"; return }
156新增: UserDefaults.standard.removeObject(forKey: trustKey)
157新增: trusted = nil; imported = nil; invitation = nil; relay = UserDefaults.standard.string(forKey:"preferred-relay") ?? CMConnection.defaultRelay(); pin = ""
158新增: hasSaved = false; needsTrust = false; verified = false; hasInvitation = false
159新增: status = "已忘记主机。"
160新增: }
161新增: func connect() {
162新增: connect(openArchived: false)
163新增: }
164新增: private func connect(openArchived: Bool) {
165新增: guard !connecting, !needsTrust, let host = trusted else {
166新增: status = "请先核对并保存这台主机。"; return
167新增: }
168新增: openArchivedAfterConnect = openArchived
169新增: if let existing = devices.first(where: {$0.id == host.relay + "|" + host.pin}) {
170新增: selectDevice(existing.id)
171新增: if openArchivedAfterConnect {
172新增: openArchivedAfterConnect = false
173新增: existing.webView.evaluateJavaScript("window.dispatchEvent(new Event('cage-open-archives'))")
174新增: }
175新增: return
176新增: }
177新增: let item = invitation
178新增:
179新增: guard item != nil || hasSaved else { status = "请导入连接文件或有效的临时邀请。"; return }
180新增: if let item, (item.expiry ?? .distantPast) <= Date() { invitation = nil; hasInvitation = false; status = "临时邀请已过期,请重新连接或导入新邀请。"; return }
181新增: guard let directory = Bundle.main.url(forResource: "mobile-ui", withExtension: nil) else { status = "安装包缺少工作台资源。"; return }
182新增: invitation = nil; hasInvitation = false; connecting = true; generation += 1
183新增: let attempt = generation
184新增: status = "正在验证电脑并连接…"
185新增: linkQueue.async {
186新增: let result = Result {
187新增: if let item { return try CMConnection.connect(relay: host.relay, room: item.id, token: item.client_token, pin: host.pin, assets: directory.path) }
188新增: guard let saved = try HostKeychain.read(host: host), saved.host == host else { throw InputError.unavailable }
189新增: return try CMConnection.connectSaved(relay: host.relay, lookup: saved.lookup, pin: host.pin, assets: directory.path)
190新增: }
191新增: DispatchQueue.main.async {
192新增: guard attempt == self.generation else {
193新增: if case .success(let old) = result { DispatchQueue.global().async { old.close() } }
194新增: return
195新增: }
196新增: self.connecting = false
197新增: switch result {
198新增: case .success(let session): self.status = ""; self.addDevice(session, host: host)
199新增: case .failure(let error): self.status = error.localizedDescription
200新增: }
201新增: }
202新增: }
203新增: }
204新增: func leaveWorkspace() {showingWorkspace = false}
205新增: func openArchivedSessions() {
206新增: if let device = selectedDevice {
207新增: selectDevice(device.id)
208新增: device.webView.evaluateJavaScript("window.dispatchEvent(new Event('cage-open-archives'))")
209新增: } else {
210新增: connect(openArchived: true)
211新增: }
212新增: }
213新增: func selectDevice(_ id: String) {
214新增: guard devices.contains(where: {$0.id == id}) else {return}
215新增: selectedDeviceID = id; showingWorkspace = true
216新增: session = selectedDevice?.connection
217新增: publishDevices()
218新增: }
219新增: func nameDevice(_ id: String, _ value: String) {
220新增: guard let index = devices.firstIndex(where: {$0.id == id}) else {return}
221新增: let name = value.trimmingCharacters(in: .whitespacesAndNewlines)
222新增: guard !name.isEmpty, devices[index].name != name else {return}
223新增: devices[index].name = String(name.prefix(120)); publishDevices()
224新增: }
225新增: private func addDevice(_ connection: CMConnection, host: Host) {
226新增: let id = host.relay + "|" + host.pin
227新增: let config = WKWebViewConfiguration()
228新增: config.websiteDataStore = .nonPersistent()
229新增: config.allowsInlineMediaPlayback = true
230新增: config.preferences.javaScriptCanOpenWindowsAutomatically = false
231新增: config.applicationNameForUserAgent = "CageMobile/1"
232新增: let delegate = WorkspaceNavigation(connection.launchURL)
233新增: config.userContentController.add(DeviceWebBridge(model: self, id: id, origin: connection.launchURL), name: "cageDevices")
234新增: config.userContentController.addUserScript(WKUserScript(source: deviceScript(id), injectionTime: .atDocumentStart, forMainFrameOnly: true))
235新增: let web = WKWebView(frame: .zero, configuration: config)
236新增: web.scrollView.contentInsetAdjustmentBehavior = .never
237新增: web.navigationDelegate = delegate
238新增: // WKWebView holds its navigation delegate weakly.
239新增: navigationDelegates[id] = delegate
240新增: devices.append(ConnectedDevice(id: id, name: "已连接电脑", connection: connection, webView: web))
241新增: selectDevice(id)
242新增: var launch = connection.launchURL
243新增: if openArchivedAfterConnect {
244新增: var parts = URLComponents(url: launch, resolvingAgainstBaseURL: false)!
245新增: parts.queryItems = (parts.queryItems ?? []) + [URLQueryItem(name: "page", value: "archived")]
246新增: launch = parts.url!
247新增: openArchivedAfterConnect = false
248新增: }
249新增: web.load(URLRequest(url: launch))
250新增: }
251新增: private var navigationDelegates: [String: WKNavigationDelegate] = [:]
252新增: private func deviceScript(_ current: String) -> String {
253新增: let value: [String: Any] = ["current": current, "devices": devices.map {["id": $0.id, "name": $0.name]}]
254新增: let data = try! JSONSerialization.data(withJSONObject: value, options: [.sortedKeys])
255新增: return "window.__cageDevices=" + String(decoding: data, as: UTF8.self) + ";window.dispatchEvent(new CustomEvent('cage-devices',{detail:window.__cageDevices}));"
256新增: }
257新增: func publishDevices() {
258新增: for device in devices {
259新增: let script = deviceScript(device.id)
260新增: device.webView.configuration.userContentController.removeAllUserScripts()
261新增: device.webView.configuration.userContentController.addUserScript(WKUserScript(source: script, injectionTime: .atDocumentStart, forMainFrameOnly: true))
262新增: // The preview fixture is installed separately and must survive navigation/reloads.
263新增: #if targetEnvironment(simulator)
264新增: if device.connection == nil {
265新增: device.webView.configuration.userContentController.addUserScript(WKUserScript(source: SimulatorWorkspacePreview.fixture, injectionTime: .atDocumentStart, forMainFrameOnly: true))
266新增: }
267新增: #endif
268新增: device.webView.evaluateJavaScript(script)
269新增: }
270新增: }
271新增: func disconnectDevice(_ id: String) {
272新增: guard let old = devices.first(where: {$0.id == id}) else {return}
273新增: old.webView.stopLoading(); old.webView.navigationDelegate = nil
274新增: old.webView.configuration.userContentController.removeScriptMessageHandler(forName: "cageDevices")
275新增: devices.removeAll {$0.id == id}; navigationDelegates.removeValue(forKey: id)
276新增: if selectedDeviceID == id {
277新增: selectedDeviceID = devices.first?.id; session = selectedDevice?.connection
278新增: if selectedDeviceID == nil {showingWorkspace = false}
279新增: }
280新增: if let connection = old.connection {linkQueue.async {connection.close()}}
281新增: publishDevices()
282新增: }
283新增: func disconnect() {if let id = selectedDeviceID {disconnectDevice(id)}}
284新增: func reconnect() {disconnect(); connect()}
285新增: func startPreview() {
286新增: #if targetEnvironment(simulator)
287新增: for (id, name) in [("preview-mac", "我的电脑 · 模拟器预览"), ("preview-linux", "Linux 工作站 · 模拟器预览")] {
288新增: if !devices.contains(where: {$0.id == id}) {
289新增: let preview = SimulatorWorkspacePreview.makeWebView(model: self, id: id)
290新增: devices.append(ConnectedDevice(id: id, name: name, connection: nil, webView: preview.web))
291新增: navigationDelegates[id] = preview.delegate
292新增: }
293新增: }
294新增: selectDevice("preview-mac")
295新增: #endif
296新增: }
297新增:}
298新增:
299新增:private final class WorkspaceNavigation: NSObject, WKNavigationDelegate {
300新增: let origin: URL
301新增: init(_ origin: URL) {self.origin = origin}
302新增: func webView(_ webView: WKWebView, decidePolicyFor action: WKNavigationAction,
303新增: decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
304新增: guard let url = action.request.url, action.targetFrame?.isMainFrame == true,
305新增: url.scheme == origin.scheme, url.host == origin.host, url.port == origin.port,
306新增: url.user == nil, url.password == nil else {decisionHandler(.cancel); return}
307新增: decisionHandler(.allow)
308新增: }
309新增:}
310新增:
311新增:private struct Workspace: UIViewRepresentable {
312新增: let webView: WKWebView
313新增: func makeUIView(context: Context) -> WKWebView {webView}
314新增: func updateUIView(_ view: WKWebView, context: Context) {}
315新增:}
316新增:
317新增:private enum CageStyle {
318新增: static let paper = Color(uiColor: UIColor { traits in
319新增: traits.userInterfaceStyle == .dark ? UIColor(white: 0.075, alpha: 1) : UIColor(red: 0.982, green: 0.978, blue: 0.967, alpha: 1)
320新增: })
321新增: static let ink = Color(uiColor: .label)
322新增: static let inverse = Color(uiColor: .systemBackground)
323新增:}
324新增:
325新增:private struct CageButtonStyle: ButtonStyle {
326新增: @Environment(\.isEnabled) private var enabled
327新增: func makeBody(configuration: Configuration) -> some View {
328新增: configuration.label
329新增: .opacity(enabled ? (configuration.isPressed ? 0.9 : 1) : 0.5)
330新增: }
331新增:}
332新增:
333新增:private struct ActionLabel: View {
334新增: let title: String
335新增: let symbol: String
336新增: var primary = true
337新增: var height: CGFloat = 52
338新增: var body: some View {
339新增: Label(title, systemImage: symbol)
340新增: .font(.headline).frame(maxWidth: .infinity, minHeight: height)
341新增: .foregroundStyle(primary ? CageStyle.inverse : CageStyle.ink)
342新增: .background(primary ? CageStyle.ink : Color(uiColor: .secondarySystemFill),
343新增: in: RoundedRectangle(cornerRadius: 16))
344新增: .contentShape(Rectangle())
345新增: }
346新增:}
347新增:
348新增:private struct QRScanner: UIViewControllerRepresentable {
349新增: let region: CGRect
350新增: @Binding var hint: String
351新增: let result: (String?) -> Void
352新增: final class Delegate: NSObject, DataScannerViewControllerDelegate {
353新增: let result: (String?) -> Void
354新增: var hint: Binding<String>
355新增: var finished = false
356新增: init(_ result: @escaping (String?) -> Void, hint: Binding<String>) {self.result = result; self.hint = hint}
357新增: func dataScanner(_ scanner: DataScannerViewController, didAdd items: [RecognizedItem], allItems: [RecognizedItem]) {
358新增: for case .barcode(let barcode) in items {
359新增: guard !finished, let code = barcode.payloadStringValue else {continue}
360新增: guard code.hasPrefix("CAGE1:"), code.utf8.count <= 4096 else {
361新增: hint.wrappedValue = "请扫描电脑「设置 → 远程连接」中的 Cage 配对二维码"; continue
362新增: }
363新增: UINotificationFeedbackGenerator().notificationOccurred(.success)
364新增: finished = true; scanner.stopScanning(); result(code); return
365新增: }
366新增: }
367新增: func dataScanner(_ scanner: DataScannerViewController, becameUnavailableWithError error: DataScannerViewController.ScanningUnavailable) {
368新增: if !finished {finished = true; result(nil)}
369新增: }
370新增: }
371新增: func makeCoordinator() -> Delegate { Delegate(result, hint: $hint) }
372新增: func makeUIViewController(context: Context) -> DataScannerViewController {
373新增: let scanner = DataScannerViewController(recognizedDataTypes: [.barcode(symbologies: [.qr])], qualityLevel: .balanced, isGuidanceEnabled: false, isHighlightingEnabled: false)
374新增: scanner.delegate = context.coordinator
375新增: DispatchQueue.main.async {
376新增: guard !context.coordinator.finished else {return}
377新增: scanner.regionOfInterest = region
378新增: do { try scanner.startScanning() } catch {context.coordinator.finished = true; result(nil)}
379新增: }
380新增: return scanner
381新增: }
382新增: func updateUIViewController(_ scanner: DataScannerViewController, context: Context) {scanner.regionOfInterest = region}
383新增: static func dismantleUIViewController(_ scanner: DataScannerViewController, coordinator: Delegate) {coordinator.finished = true; scanner.stopScanning()}
384新增:}
385新增:
386新增:private struct FinderMask: Shape {
387新增: let box: CGRect
388新增: func path(in rect: CGRect) -> Path {
389新增: var path = Path(rect)
390新增: path.addRoundedRect(in: box, cornerSize: CGSize(width: 18, height: 18))
391新增: return path
392新增: }
393新增:}
394新增:private struct FinderCorners: Shape {
395新增: func path(in rect: CGRect) -> Path {
396新增: var path = Path()
397新增: for x in [CGFloat(0), CGFloat(1)] {for y in [CGFloat(0), CGFloat(1)] {
398新增: var corner = Path()
399新增: corner.move(to: CGPoint(x: 0, y: 30)); corner.addLine(to: CGPoint(x: 0, y: 18))
400新增: corner.addQuadCurve(to: CGPoint(x: 18, y: 0), control: .zero); corner.addLine(to: CGPoint(x: 30, y: 0))
401新增: let transform = CGAffineTransform(a: x == 0 ? 1 : -1, b: 0, c: 0, d: y == 0 ? 1 : -1, tx: x * rect.width, ty: y * rect.height)
402新增: path.addPath(corner, transform: transform)
403新增: }}
404新增: return path
405新增: }
406新增:}
407新增:private struct QRScannerScreen: View {
408新增: let result: (String?) -> Void
409新增: @Environment(\.accessibilityReduceMotion) private var reduceMotion
410新增: @State private var sweeping = false
411新增: @State private var hint = "将 Cage 配对二维码放入框内\n在电脑「设置 → 远程连接」中生成"
412新增: private let accent = Color(red: 0.91, green: 0.72, blue: 0.62)
413新增: var body: some View {
414新增: GeometryReader { geometry in
415新增: let side = max(96, min(280, min(geometry.size.width - 56, geometry.size.height - 190)))
416新增: let box = CGRect(x: (geometry.size.width - side) / 2, y: 24 + max(0, (geometry.size.height - 190 - side) / 2), width: side, height: side)
417新增: ZStack(alignment: .bottom) {
418新增: #if targetEnvironment(simulator)
419新增: Color(white: 0.15)
420新增: Image(systemName: "qrcode").resizable().interpolation(.none).scaledToFit()
421新增: .foregroundStyle(.white.opacity(0.8)).frame(width: side * 0.65, height: side * 0.65)
422新增: .position(x: box.midX, y: box.midY).accessibilityHidden(true)
423新增: #else
424新增: QRScanner(region: box, hint: $hint, result: result)
425新增: #endif
426新增: FinderMask(box: box).fill(Color(red: 0.08, green: 0.09, blue: 0.09).opacity(0.72), style: FillStyle(eoFill: true))
427新增: RoundedRectangle(cornerRadius: 18).stroke(.white.opacity(0.45), lineWidth: 1)
428新增: .frame(width: side, height: side).position(x: box.midX, y: box.midY)
429新增: FinderCorners().stroke(accent, style: StrokeStyle(lineWidth: 4, lineCap: .round))
430新增: .frame(width: side, height: side).position(x: box.midX, y: box.midY)
431新增: VStack(spacing: 0) {
432新增: LinearGradient(colors: [accent.opacity(0), accent.opacity(0.22)], startPoint: .top, endPoint: .bottom).frame(height: 26)
433新增: Capsule().fill(accent).frame(height: 2)
434新增: }.frame(width: side - 24)
435新增: .position(x: box.midX, y: reduceMotion ? box.midY : box.minY + 24 + (sweeping ? side - 48 : 0))
436新增: .animation(reduceMotion ? nil : .linear(duration: 2.4).repeatForever(autoreverses: true), value: sweeping)
437新增: .accessibilityHidden(true)
438新增: VStack(spacing: 12) {
439新增: Text("连接你的电脑").font(.title2.bold())
440新增: Text(hint).font(.subheadline).foregroundStyle(.white.opacity(0.88)).multilineTextAlignment(.center)
441新增: Text(simulatorPreviewEnabled ? "模拟器预览 · 即将进入示例工作台" : "仅识别 Cage 配对码")
442新增: .font(.caption).foregroundStyle(.white.opacity(0.6))
443新增: }.foregroundStyle(.white).padding(.horizontal, 24).padding(.bottom, 24).accessibilityElement(children: .combine)
444新增: }.background(Color.black).onAppear {sweeping = true}
445新增: .task {
446新增: #if targetEnvironment(simulator)
447新增: do {try await Task.sleep(for: .seconds(2))} catch {return}
448新增: result(nil)
449新增: #endif
450新增: }
451新增: }.toolbarColorScheme(.dark, for: .navigationBar)
452新增: .toolbarBackground(Color(red: 0.08, green: 0.09, blue: 0.09), for: .navigationBar).toolbarBackground(.visible, for: .navigationBar)
453新增: }
454新增:}
455新增:
456新增:private struct ConnectionSheet: View {
457新增: @ObservedObject var model: ConnectionModel
458新增: let previewConnected: () -> Void
459新增: @State private var manual = false
460新增: @State private var scanning = false
461新增: @State private var disconnecting: ConnectedDevice?
462新增: @State private var previewScanned = false
463新增: @State private var code = ""
464新增: var body: some View {
465新增: NavigationStack {
466新增: ScrollView {
467新增: VStack(spacing: 12) {
468新增: Image("PairDevices").resizable().scaledToFit().frame(maxWidth: .infinity)
469新增: .frame(height: 150).accessibilityHidden(true)
470新增: Text("连接电脑").font(.title.bold())
471新增: Text("在电脑的 Cage 设置中打开「远程连接」,生成配对二维码或复制配对码。")
472新增: .font(.subheadline).foregroundStyle(.secondary).multilineTextAlignment(.center)
473新增: .padding(.bottom, 10)
474新增: Button {
475新增: Task { @MainActor in
476新增: if simulatorPreviewEnabled {scanning = true; return}
477新增: guard DataScannerViewController.isSupported,
478新增: await AVCaptureDevice.requestAccess(for: .video),
479新增: DataScannerViewController.isAvailable else {
480新增: model.status = "相机暂不可用,请检查相机权限或使用配对码。"; return
481新增: }
482新增: scanning = true
483新增: }
484新增: } label: {ActionLabel(title: "扫码连接", symbol: "qrcode.viewfinder")}
485新增: Button {manual = true} label: {ActionLabel(title: "使用配对码", symbol: "key", primary: false)}
486新增: if model.hasSaved || model.hasInvitation {
487新增: Button("重新连接", action: model.connect).frame(minHeight: 44).disabled(!model.canConnect)
488新增: }
489新增: if !model.devices.isEmpty {
490新增: Divider().padding(.vertical, 8)
491新增: Text("已连接设备").font(.headline).frame(maxWidth: .infinity, alignment: .leading)
492新增: Text("长按设备可取消连接").font(.footnote).foregroundStyle(.secondary)
493新增: .frame(maxWidth: .infinity, alignment: .leading)
494新增: ForEach(model.devices) {device in
495新增: Button {if disconnecting == nil {model.selectDevice(device.id)}} label: {
496新增: HStack {Image(systemName: "desktopcomputer"); Text(device.name); Spacer(); Image(systemName: "chevron.right")}
497新增: .frame(minHeight: 48).contentShape(Rectangle())
498新增: }
499新增: .simultaneousGesture(LongPressGesture().onEnded { _ in disconnecting = device })
500新增: .accessibilityAction(named: Text("取消连接")) {disconnecting = device}
501新增: }
502新增: }
503新增: status
504新增: }.padding(24).frame(maxWidth: 520)
505新增: .frame(maxWidth: .infinity)
506新增: }.background(CageStyle.paper).buttonStyle(CageButtonStyle())
507新增: .navigationDestination(isPresented: $manual) {
508新增: Form {
509新增: Section {
510新增: SecureField("粘贴电脑上的一次性配对码", text: $code)
511新增: .textInputAutocapitalization(.never).autocorrectionDisabled()
512新增: Button("连接电脑") {model.pair(code: code); code = ""}
513新增: .accessibilityIdentifier("redeem-pair-code")
514新增: .disabled(code.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || model.connecting)
515新增: }
516新增: if !model.status.isEmpty {Section {status}}
517新增: }.navigationTitle("配对码")
518新增: }
519新增: .sheet(item: $disconnecting) {device in
520新增: VStack(spacing: 20) {
521新增: Text("取消连接?").font(.title2.bold())
522新增: Text(device.name).foregroundStyle(.secondary)
523新增: Text("将关闭这台设备的连接。已保存的配对信息会保留。")
524新增: .font(.subheadline).foregroundStyle(.secondary).multilineTextAlignment(.center)
525新增: Button("取消连接", role: .destructive) {
526新增: model.disconnectDevice(device.id)
527新增: disconnecting = nil
528新增: }.frame(maxWidth: .infinity, minHeight: 48)
529新增: Button("保留连接") {disconnecting = nil}.frame(minHeight: 44)
530新增: }.padding(24).presentationDetents([.height(300)]).presentationDragIndicator(.visible)
531新增: }
532新增: .sheet(isPresented: $scanning, onDismiss: {
533新增: if previewScanned {previewScanned = false; previewConnected()}
534新增: }) {
535新增: NavigationStack {
536新增: QRScannerScreen { result in
537新增: scanning = false
538新增: if simulatorPreviewEnabled {previewScanned = true}
539新增: else if let result {model.pair(code: result)}
540新增: else {model.status = "无法读取二维码,请重试或使用配对码。"}
541新增: }.navigationTitle("扫描电脑二维码").navigationBarTitleDisplayMode(.inline)
542新增: .toolbar {Button("取消") {scanning = false}}
543新增: }
544新增: }
545新增: }.disabled(model.connecting).interactiveDismissDisabled(model.connecting)
546新增: .presentationDetents([.fraction(0.72), .large]).presentationDragIndicator(.visible)
547新增: }
548新增: @ViewBuilder private var status: some View {
549新增: if !model.status.isEmpty {
550新增: Text(model.status).font(.footnote).foregroundStyle(.secondary)
551新增: .accessibilityAddTraits(.updatesFrequently)
552新增: }
553新增: }
554新增:}
555新增:
556新增:private enum CageTheme: String, CaseIterable {
557新增: case system = "跟随系统", light = "浅色", dark = "深色"
558新增: var scheme: ColorScheme? {
559新增: switch self {case .system: return nil; case .light: return .light; case .dark: return .dark}
560新增: }
561新增:}
562新增:
563新增:private struct SettingsScreen: View {
564新增: @ObservedObject var model: ConnectionModel
565新增: @Binding var theme: CageTheme
566新增: let connect: () -> Void
567新增: @State private var relaySettings = false
568新增: @State private var advanced = false
569新增: @State private var themes = false
570新增: @State private var picking = false
571新增: @State private var confirmingForget = false
572新增:
573新增: var body: some View {
574新增: Form {
575新增: Section("外观") {
576新增: DisclosureGroup(isExpanded: $themes) {
577新增: ForEach(CageTheme.allCases, id: \.self) {option in
578新增: Button {
579新增: theme = option; themes = false
580新增: } label: {
581新增: HStack {Text(option.rawValue); Spacer(); if theme == option {Image(systemName: "checkmark")}}
582新增: .frame(minHeight: 44).contentShape(Rectangle())
583新增: }.accessibilityAddTraits(theme == option ? .isSelected : [])
584新增: }
585新增: } label: {
586新增: HStack {
587新增: Label("主题", systemImage: "circle.lefthalf.filled")
588新增: Spacer(); Text(theme.rawValue).foregroundStyle(.secondary)
589新增: }
590新增: }
591新增: }
592新增: Section("电脑连接") {
593新增: Button("已归档会话", action: model.openArchivedSessions)
594新增: .disabled(model.selectedDevice == nil && !model.canConnect)
595新增: DisclosureGroup("中继设置", isExpanded: $relaySettings) {
596新增: Toggle("使用自建中继", isOn: Binding(get: {model.relay != CMConnection.defaultRelay()},
597新增: set: {model.relay = $0 ? "" : CMConnection.defaultRelay()}))
598新增: if model.relay != CMConnection.defaultRelay() {
599新增: TextField("自建 VPS 的 HTTPS 地址", text: $model.relay)
600新增: .keyboardType(.URL).textInputAutocapitalization(.never).autocorrectionDisabled()
601新增: } else {Text("Cage 官方中继").foregroundStyle(.secondary)}
602新增: Button("保存中继设置", action: model.saveRelay)
603新增: }
604新增: DisclosureGroup("指纹与连接文件", isExpanded: $advanced) {
605新增: Text(CMConnection.usesSimulatorIdentity ? "模拟器测试身份的指纹" : "这台手机的指纹").font(.headline)
606新增: Text(model.fingerprint).font(.caption.monospaced()).textSelection(.enabled)
607新增: Button("复制手机指纹") {UIPasteboard.general.string = model.fingerprint; model.status = "手机指纹已复制"}
608新增: .disabled(model.fingerprint.isEmpty)
609新增: Button("导入连接文件") {picking = true}
610新增: TextField("电脑指纹 sha256:…", text: $model.pin).textInputAutocapitalization(.never).autocorrectionDisabled()
611新增: Toggle("已核对电脑指纹", isOn: $model.verified)
612新增: Button("保存已核对的主机", action: model.saveTrust).disabled(!model.verified)
613新增: if model.hasInvitation || model.hasSaved {Button("连接工作台", action: connect).disabled(!model.canConnect)}
614新增: }
615新增: if model.canForget {Button("忘记主机", role: .destructive) {confirmingForget = true}}
616新增: }
617新增: if !model.status.isEmpty {Section {Text(model.status).font(.footnote).foregroundStyle(.secondary)}}
618新增: }.navigationTitle("设置").disabled(model.connecting)
619新增: .alert("忘记主机?", isPresented: $confirmingForget) {
620新增: Button("取消", role: .cancel) {}
621新增: Button("忘记主机", role: .destructive, action: model.forget)
622新增: } message: {Text("将移除这台电脑的地址、指纹和重连凭据。")}
623新增: .fileImporter(isPresented: $picking, allowedContentTypes: [.json, .plainText]) {result in
624新增: if case .success(let file) = result {model.loadInvitation(file)}
625新增: }
626新增: }
627新增:}
628新增:
629新增:@main
630新增:struct CageMobileApp: App {
631新增: @StateObject private var model = ConnectionModel()
632新增: @AppStorage("appearance-theme") private var theme = CageTheme.system
633新增: @State private var showingSettings = false
634新增: @State private var pairing = false
635新增:
636新增: var body: some Scene {
637新增: WindowGroup {
638新增: NavigationStack {
639新增: Group {
640新增: if model.showingWorkspace, let device = model.selectedDevice {
641新增: Workspace(webView: device.webView).id(device.id)
642新增: } else {
643新增: home
644新增: }
645新增: }
646新增: .navigationDestination(isPresented: $showingSettings) {
647新增: SettingsScreen(model: model, theme: $theme, connect: model.connect)
648新增: }
649新增: }.buttonStyle(CageButtonStyle()).tint(CageStyle.ink).preferredColorScheme(theme.scheme)
650新增: .sheet(isPresented: $pairing) {
651新增: ConnectionSheet(model: model, previewConnected: {
652新增: pairing = false; showingSettings = false; model.startPreview()
653新增: }).buttonStyle(CageButtonStyle()).tint(CageStyle.ink).preferredColorScheme(theme.scheme)
654新增: }
655新增: .onChange(of: model.showingWorkspace) { _, connected in
656新增: if connected {pairing = false; showingSettings = false}
657新增: }
658新增: .onChange(of: model.relay) {model.verified = false}
659新增: .onChange(of: model.pin) {model.verified = false}
660新增: }
661新增: }
662新增: private var home: some View {
663新增: GeometryReader { geometry in
664新增: let brandSpacing = min(60, max(28, geometry.size.height * 0.075)) + 32
665新增: ScrollView {
666新增: VStack(spacing: 0) {
667新增: Spacer(minLength: 12)
668新增: VStack(spacing: brandSpacing) {
669新增: VStack(spacing: 12) {
670新增: Image("CageMark").resizable().scaledToFit().frame(width: 120, height: 120)
671新增: .clipShape(RoundedRectangle(cornerRadius: 16)).accessibilityHidden(true)
672新增: Text("Cage").font(.system(size: 36, weight: .semibold, design: .rounded))
673新增: }
674新增: Button {pairing = true} label: {
675新增: ActionLabel(title: "连接电脑", symbol: "desktopcomputer", height: 60)
676新增: }
677新增: }.frame(maxWidth: 276).padding(.top, 32)
678新增: Spacer(minLength: 12)
679新增: }.padding(.horizontal, 24).frame(maxWidth: .infinity).frame(minHeight: geometry.size.height)
680新增: }.scrollBounceBehavior(.basedOnSize)
681新增: }.background(CageStyle.paper.ignoresSafeArea()).buttonStyle(CageButtonStyle())
682新增: .navigationBarTitleDisplayMode(.inline)
683新增: .toolbar {
684新增: ToolbarItem(placement: .topBarTrailing) {
685新增: Button {showingSettings = true} label: {Image(systemName: "gearshape")}
686新增: .accessibilityLabel("设置")
687新增: }
688新增: }
689新增: }
690新增:}
新增mobile/ios/CageMobile/ConnectionFile.swift+142 −0看文件
@@ -0,0 +1,142 @@
1新增:import Foundation
2新增:import Security
3新增:
4新增:enum InputError: LocalizedError {
5新增: case invalid, unavailable
6新增: var errorDescription: String? {
7新增: switch self {
8新增: case .invalid: return "连接文件或指纹格式无效。"
9新增: case .unavailable: return "无法读取已保存的凭据,请解锁手机或重新导入连接文件。"
10新增: }
11新增: }
12新增:}
13新增:
14新增:struct Host: Codable, Equatable {
15新增: let relay: String
16新增: let pin: String
17新增:
18新增: init(relay: String, pin: String) throws {
19新增: guard var u = URLComponents(string: relay.trimmingCharacters(in: .whitespacesAndNewlines)),
20新增: u.scheme?.lowercased() == "https", let host = u.host, !host.isEmpty,
21新增: u.user == nil, u.password == nil, u.query == nil, u.fragment == nil,
22新增: u.path.isEmpty || u.path == "/", (1...65535).contains(u.port ?? 443) else { throw InputError.invalid }
23新增: u.scheme = "https"; u.path = ""
24新增: let pin = pin.trimmingCharacters(in: .whitespacesAndNewlines)
25新增: let encoded = String(pin.dropFirst(7))
26新增: guard pin.hasPrefix("sha256:"), let bytes = Data(base64Encoded: encoded), bytes.count == 32,
27新增: bytes.base64EncodedString() == encoded, let address = u.url?.absoluteString else { throw InputError.invalid }
28新增: self.relay = address; self.pin = pin
29新增: }
30新增:}
31新增:
32新增:struct Invitation: Decodable {
33新增: let id: String
34新增: let client_token: String
35新增: let expires_at: String
36新增:
37新增: var expiry: Date? {
38新增: let iso = ISO8601DateFormatter()
39新增: iso.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
40新增: return iso.date(from: expires_at) ?? ISO8601DateFormatter().date(from: expires_at)
41新增: }
42新增:}
43新增:
44新增:struct HostAccess: Codable {
45新增: let host: Host
46新增: let lookup: String
47新增:}
48新增:
49新增:enum ConnectionFile {
50新增: case temporary(Invitation)
51新增: case persistent(HostAccess)
52新增:
53新增: static func load(_ file: URL) throws -> Self {
54新增: let access = file.startAccessingSecurityScopedResource()
55新增: defer { if access { file.stopAccessingSecurityScopedResource() } }
56新增: let handle = try FileHandle(forReadingFrom: file)
57新增: defer { try? handle.close() }
58新增: let data = try handle.read(upToCount: 4097) ?? Data()
59新增: return try parse(data)
60新增: }
61新增: static func parse(_ data: Data) throws -> Self {
62新增: guard data.count <= 4096, let object = try JSONSerialization.jsonObject(with: data) as? [String: Any] else { throw InputError.invalid }
63新增: let keys = Set(object.keys)
64新增: if keys == Set(["id", "client_token", "expires_at"]) {
65新增: let value = try JSONDecoder().decode(Invitation.self, from: data)
66新增: guard capability(value.id), capability(value.client_token), (value.expiry ?? .distantPast) > Date() else { throw InputError.invalid }
67新增: return .temporary(value)
68新增: }
69新增: struct Record: Decodable { let version: Int; let relay, host_pin, lookup_token: String }
70新增: guard keys == Set(["version", "relay", "host_pin", "lookup_token"]) else { throw InputError.invalid }
71新增: let record = try JSONDecoder().decode(Record.self, from: data)
72新增: guard record.version == 1, capability(record.lookup_token) else { throw InputError.invalid }
73新增: return .persistent(HostAccess(host: try Host(relay: record.relay, pin: record.host_pin), lookup: record.lookup_token))
74新增: }
75新增: static func capability(_ s: String) -> Bool {
76新增: guard s.utf8.count == 43 else { return false }
77新增: let base = s.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/") + "="
78新增: guard let bytes = Data(base64Encoded: base), bytes.count == 32 else { return false }
79新增: return bytes.base64EncodedString().replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: "_")
80新增: .trimmingCharacters(in: CharacterSet(charactersIn: "=")) == s
81新增: }
82新增:}
83新增:
84新增:enum HostKeychain {
85新增: private static var query: [String: Any] {
86新增: [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: "io.github.lee-xeo.claude-cage.mobile.saved-host",
87新增: kSecAttrAccount as String: "v1", kSecAttrSynchronizable as String: false]
88新增: }
89新增: private static var collectionQuery: [String: Any] {
90新增: var q = query; q[kSecAttrAccount as String] = "v2-hosts"; return q
91新增: }
92新增: private static func data(_ item: [String: Any]) throws -> Data? {
93新增: var q = item
94新增: q[kSecReturnData as String] = true
95新增: q[kSecMatchLimit as String] = kSecMatchLimitOne
96新增: var found: CFTypeRef?
97新增: let status = SecItemCopyMatching(q as CFDictionary, &found)
98新增: if status == errSecItemNotFound {return nil}
99新增: guard status == errSecSuccess, let data = found as? Data else {throw InputError.unavailable}
100新增: return data
101新增: }
102新增: static func readAll() throws -> [HostAccess] {
103新增: let records: [HostAccess]
104新增: if let data = try data(collectionQuery) {
105新增: records = try JSONDecoder().decode([HostAccess].self, from: data)
106新增: } else if let data = try data(query) {
107新增: records = [try JSONDecoder().decode(HostAccess.self, from: data)]
108新增: } else {return []}
109新增: for record in records {
110新增: guard ConnectionFile.capability(record.lookup),
111新增: try Host(relay: record.host.relay, pin: record.host.pin) == record.host else {throw InputError.invalid}
112新增: }
113新增: return records
114新增: }
115新增: static func read(host: Host? = nil) throws -> HostAccess? {
116新增: let records = try readAll()
117新增: if let host {return records.first {$0.host == host}}
118新增: return records.last
119新增: }
120新增: private static func store(_ records: [HostAccess]) throws {
121新增: let values: [String:Any] = [kSecValueData as String: try JSONEncoder().encode(records),
122新增: kSecAttrAccessible as String: kSecAttrAccessibleWhenUnlockedThisDeviceOnly]
123新增: var status = SecItemUpdate(collectionQuery as CFDictionary, values as CFDictionary)
124新增: if status == errSecItemNotFound {
125新增: status = SecItemAdd(collectionQuery.merging(values) {_, value in value} as CFDictionary, nil)
126新增: }
127新增: guard status == errSecSuccess else {throw InputError.unavailable}
128新增: // The v2 collection is durable before removing its migrated v1 copy.
129新增: let legacy = SecItemDelete(query as CFDictionary)
130新增: guard legacy == errSecSuccess || legacy == errSecItemNotFound else {throw InputError.unavailable}
131新增: }
132新增: static func write(_ record: HostAccess) throws {
133新增: var records = try readAll(); records.removeAll {$0.host == record.host}; records.append(record)
134新增: try store(records)
135新增: }
136新增: static func forget(host: Host? = nil) throws {
137新增: var records = try readAll()
138新增: if let host {records.removeAll {$0.host == host}} else {records = []}
139新增: // Writing the collection also prevents an old v1 record from reappearing.
140新增: try store(records)
141新增: }
142新增:}
新增mobile/ios/CageMobile/Info.plist+63 −0看文件
@@ -0,0 +1,63 @@
1新增:<?xml version="1.0" encoding="UTF-8"?>
2新增:<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3新增:<plist version="1.0">
4新增:<dict>
5新增: <key>CFBundleDevelopmentRegion</key>
6新增: <string>zh_CN</string>
7新增: <key>CFBundleDisplayName</key>
8新增: <string>Cage</string>
9新增: <key>CFBundleExecutable</key>
10新增: <string>$(EXECUTABLE_NAME)</string>
11新增: <key>CFBundleIdentifier</key>
12新增: <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
13新增: <key>CFBundleInfoDictionaryVersion</key>
14新增: <string>6.0</string>
15新增: <key>CFBundleName</key>
16新增: <string>$(PRODUCT_NAME)</string>
17新增: <key>CFBundlePackageType</key>
18新增: <string>APPL</string>
19新增: <key>CFBundleShortVersionString</key>
20新增: <string>0.1</string>
21新增: <key>CFBundleVersion</key>
22新增: <string>1</string>
23新增: <key>LSRequiresIPhoneOS</key>
24新增: <true/>
25新增: <key>NSAppTransportSecurity</key>
26新增: <dict>
27新增: <key>NSExceptionDomains</key>
28新增: <dict>
29新增: <key>127.0.0.1</key>
30新增: <dict>
31新增: <key>NSExceptionAllowsInsecureHTTPLoads</key>
32新增: <true/>
33新增: </dict>
34新增: </dict>
35新增: </dict>
36新增: <key>NSCameraUsageDescription</key>
37新增: <string>扫描电脑上的 Cage 配对二维码。</string>
38新增: <key>NSLocalNetworkUsageDescription</key>
39新增: <string>连接您配置的局域网 Cage 中继。</string>
40新增: <key>UIApplicationSceneManifest</key>
41新增: <dict>
42新增: <key>UIApplicationSupportsMultipleScenes</key>
43新增: <false/>
44新增: <key>UISceneConfigurations</key>
45新增: <dict/>
46新增: </dict>
47新增: <key>UILaunchScreen</key>
48新增: <dict/>
49新增: <key>UISupportedInterfaceOrientations</key>
50新增: <array>
51新增: <string>UIInterfaceOrientationPortrait</string>
52新增: <string>UIInterfaceOrientationLandscapeLeft</string>
53新增: <string>UIInterfaceOrientationLandscapeRight</string>
54新增: </array>
55新增: <key>UISupportedInterfaceOrientations~ipad</key>
56新增: <array>
57新增: <string>UIInterfaceOrientationPortrait</string>
58新增: <string>UIInterfaceOrientationPortraitUpsideDown</string>
59新增: <string>UIInterfaceOrientationLandscapeLeft</string>
60新增: <string>UIInterfaceOrientationLandscapeRight</string>
61新增: </array>
62新增:</dict>
63新增:</plist>
新增mobile/ios/CageMobile/NativeConnection.h+15 −0看文件
@@ -0,0 +1,15 @@
1新增:#import <Foundation/Foundation.h>
2新增:NS_ASSUME_NONNULL_BEGIN
3新增:@interface CMConnection : NSObject
4新增:+ (NSString *)defaultRelay;
5新增:@property(class, nonatomic, readonly) BOOL usesSimulatorIdentity;
6新增:+ (nullable NSString *)pairCode:(NSString *)code relay:(NSString *)relay error:(NSError **)error NS_SWIFT_NAME(pair(code:relay:));
7新增:+ (nullable NSString *)deviceFingerprint:(NSError **)error NS_SWIFT_NAME(deviceFingerprint());
8新增:+ (nullable instancetype)connectToRelay:(NSString *)relay room:(NSString *)room token:(NSString *)token
9新增: pin:(NSString *)pin assets:(NSString *)assets error:(NSError **)error NS_SWIFT_NAME(connect(relay:room:token:pin:assets:));
10新增:+ (nullable instancetype)connectSavedRelay:(NSString *)relay lookup:(NSString *)lookup pin:(NSString *)pin
11新增: assets:(NSString *)assets error:(NSError **)error NS_SWIFT_NAME(connectSaved(relay:lookup:pin:assets:));
12新增:@property(nonatomic, readonly) NSURL *launchURL;
13新增:- (void)close;
14新增:@end
15新增:NS_ASSUME_NONNULL_END
新增mobile/ios/CageMobile/NativeConnection.m+156 −0看文件
@@ -0,0 +1,156 @@
1新增:#import "NativeConnection.h"
2新增:#import <Cagemobile/Cagemobile.h>
3新增:#import <Security/Security.h>
4新增:#import <TargetConditionals.h>
5新增:#import <sys/utsname.h>
6新增:#import <UIKit/UIKit.h>
7新增:
8新增:#if TARGET_OS_SIMULATOR && CAGE_SIMULATOR_DEBUG
9新增:static const BOOL simulatorIdentity = YES;
10新增:#else
11新增:static const BOOL simulatorIdentity = NO;
12新增:#endif
13新增:
14新增:static void setError(NSError **error, NSString *text) {
15新增: if (error) *error = [NSError errorWithDomain:@"CageMobile" code:1 userInfo:@{NSLocalizedDescriptionKey:text}];
16新增:}
17新增:
18新增:@interface CMDeviceKey : NSObject <CagemobileDeviceSigner>
19新增:- (instancetype)initWithError:(NSError **)error;
20新增:@end
21新增:
22新增:@implementation CMDeviceKey {
23新增: SecKeyRef _key;
24新增:}
25新增:- (instancetype)initWithError:(NSError **)error {
26新增: self = [super init];
27新增: if (!self) return nil;
28新增: NSString *name = simulatorIdentity ? @"io.github.lee-xeo.claude-cage.mobile.simulator.v1" : @"io.github.lee-xeo.claude-cage.mobile.device.v1";
29新增: NSData *tag = [name dataUsingEncoding:NSUTF8StringEncoding];
30新增: NSMutableDictionary *query = [@{(__bridge id)kSecClass:(__bridge id)kSecClassKey,
31新增: (__bridge id)kSecAttrApplicationTag:tag, (__bridge id)kSecAttrKeyType:(__bridge id)kSecAttrKeyTypeECSECPrimeRandom,
32新增: (__bridge id)kSecAttrKeyClass:(__bridge id)kSecAttrKeyClassPrivate,
33新增: (__bridge id)kSecReturnRef:@YES} mutableCopy];
34新增: if (!simulatorIdentity) query[(__bridge id)kSecAttrTokenID] = (__bridge id)kSecAttrTokenIDSecureEnclave;
35新增: @synchronized ([CMDeviceKey class]) {
36新增: CFTypeRef found = NULL;
37新增: OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)query, &found);
38新增: if (status == errSecSuccess) { _key = (SecKeyRef)found; return self; }
39新增: if (status != errSecItemNotFound) { setError(error, @"无法读取设备密钥。请先解锁 iPhone。"); return nil; }
40新增: CFErrorRef failure = NULL;
41新增: NSMutableDictionary *privateAttrs = [@{(__bridge id)kSecAttrIsPermanent:@YES,
42新增: (__bridge id)kSecAttrApplicationTag:tag} mutableCopy];
43新增: NSMutableDictionary *attrs = [@{(__bridge id)kSecAttrKeyType:(__bridge id)kSecAttrKeyTypeECSECPrimeRandom,
44新增: (__bridge id)kSecAttrKeySizeInBits:@256, (__bridge id)kSecPrivateKeyAttrs:privateAttrs} mutableCopy];
45新增: if (simulatorIdentity) {
46新增: privateAttrs[(__bridge id)kSecAttrAccessible] = (__bridge id)kSecAttrAccessibleWhenUnlockedThisDeviceOnly;
47新增: } else {
48新增: SecAccessControlRef access = SecAccessControlCreateWithFlags(NULL, kSecAttrAccessibleWhenUnlockedThisDeviceOnly,
49新增: kSecAccessControlPrivateKeyUsage, &failure);
50新增: if (!access) {
51新增: if (failure) CFRelease(failure);
52新增: setError(error, @"无法设置设备密钥访问权限。"); return nil;
53新增: }
54新增: attrs[(__bridge id)kSecAttrTokenID] = (__bridge id)kSecAttrTokenIDSecureEnclave;
55新增: privateAttrs[(__bridge id)kSecAttrAccessControl] = CFBridgingRelease(access);
56新增: }
57新增: _key = SecKeyCreateRandomKey((__bridge CFDictionaryRef)attrs, &failure);
58新增: if (failure) CFRelease(failure);
59新增: if (!_key) { setError(error, @"设备安全芯片无法创建设备密钥。请使用已解锁的 iPhone。"); return nil; }
60新增: }
61新增: return self;
62新增:}
63新增:- (NSData *)publicKeyDER:(NSError **)error {
64新增: SecKeyRef publicKey = SecKeyCopyPublicKey(_key);
65新增: if (!publicKey) { setError(error, @"无法取得设备公钥。"); return nil; }
66新增: CFErrorRef failure = NULL;
67新增: NSData *point = CFBridgingRelease(SecKeyCopyExternalRepresentation(publicKey, &failure));
68新增: CFRelease(publicKey);
69新增: if (failure) CFRelease(failure);
70新增: if (point.length != 65 || ((const uint8_t *)point.bytes)[0] != 4) {
71新增: setError(error, @"设备公钥格式无效。"); return nil;
72新增: }
73新增: // RFC 5480 SubjectPublicKeyInfo header for an uncompressed P-256 point.
74新增: static const uint8_t header[] = {0x30,0x59,0x30,0x13,0x06,0x07,0x2a,0x86,0x48,0xce,0x3d,0x02,0x01,
75新增: 0x06,0x08,0x2a,0x86,0x48,0xce,0x3d,0x03,0x01,0x07,0x03,0x42,0x00};
76新增: NSMutableData *der = [NSMutableData dataWithBytes:header length:sizeof(header)];
77新增: [der appendData:point];
78新增: return der;
79新增:}
80新增:- (NSData *)signSHA256:(NSData *)digest error:(NSError **)error {
81新增: if (digest.length != 32) { setError(error, @"签名摘要长度无效。"); return nil; }
82新增: CFErrorRef failure = NULL;
83新增: NSData *signature = CFBridgingRelease(SecKeyCreateSignature(_key, kSecKeyAlgorithmECDSASignatureDigestX962SHA256,
84新增: (__bridge CFDataRef)digest, &failure));
85新增: if (failure) CFRelease(failure);
86新增: if (!signature) setError(error, @"设备密钥签名失败。");
87新增: return signature;
88新增:}
89新增:- (void)dealloc { if (_key) CFRelease(_key); }
90新增:@end
91新增:
92新增:@implementation CMConnection {
93新增: CagemobileClient *_client;
94新增:}
95新增:+ (instancetype)workspaceWithClient:(CagemobileClient *)client assets:(NSString *)assets error:(NSError **)error {
96新增: NSError *failure = nil;
97新增: NSString *entry = [client startUI:assets error:&failure];
98新增: NSURLComponents *url = [NSURLComponents componentsWithString:entry];
99新增: if (failure || ![url.scheme isEqualToString:@"http"] || ![url.host isEqualToString:@"127.0.0.1"] ||
100新增: url.port.integerValue < 1 || url.port.integerValue > 65535 || url.user || url.password || !url.URL) {
101新增: [client close:nil]; setError(error, @"无法打开手机工作台。"); return nil;
102新增: }
103新增: CMConnection *result = [[CMConnection alloc] init];
104新增: result->_client = client; result->_launchURL = url.URL;
105新增: return result;
106新增:}
107新增:+ (NSString *)pairCode:(NSString *)code relay:(NSString *)relay error:(NSError **)error {
108新增: CMDeviceKey *device = [[CMDeviceKey alloc] initWithError:error];
109新增: if (!device) return nil;
110新增: NSError *failure = nil;
111新增: NSString *result = CagemobilePair(code, relay, device, &failure);
112新增: if (failure || !result.length) {setError(error, @"配对未完成。请确认两端使用同一中继,再扫描新二维码。"); return nil;}
113新增: return result;
114新增:}
115新增:+ (BOOL)usesSimulatorIdentity { return simulatorIdentity; }
116新增:+ (NSString *)defaultRelay { return CagemobileDefaultRelay(); }
117新增:
118新增:+ (NSString *)deviceFingerprint:(NSError **)error {
119新增: CMDeviceKey *device = [[CMDeviceKey alloc] initWithError:error];
120新增: if (!device) return nil;
121新增: NSError *failure = nil;
122新增: NSString *pin = CagemobileFingerprint(device,&failure);
123新增: if (failure || !pin.length) { setError(error, @"无法读取设备指纹。"); return nil; }
124新增: return pin;
125新增:}
126新增:+ (instancetype)connectToRelay:(NSString *)relay room:(NSString *)room token:(NSString *)token
127新增: pin:(NSString *)pin assets:(NSString *)assets error:(NSError **)error {
128新增: CMDeviceKey *device = [[CMDeviceKey alloc] initWithError:error];
129新增: if (!device) return nil;
130新增: NSError *failure = nil;
131新增: CagemobileClient *client = CagemobileOpen(relay, room, token, pin, device, &failure);
132新增: if (!client || failure) { setError(error, @"连接未完成。请核对中继、双方指纹,并使用新邀请。"); return nil; }
133新增: return [self workspaceWithClient:client assets:assets error:error];
134新增:}
135新增:+ (instancetype)connectSavedRelay:(NSString *)relay lookup:(NSString *)lookup pin:(NSString *)pin
136新增: assets:(NSString *)assets error:(NSError **)error {
137新增: CMDeviceKey *device = [[CMDeviceKey alloc] initWithError:error];
138新增: if (!device) return nil;
139新增: NSError *failure = nil;
140新增: CagemobileClient *client = CagemobileOpenSaved(relay, lookup, pin, device, &failure);
141新增: if (!client || failure) { setError(error, @"连接未完成。请确认电脑上的连接服务正在运行,再点重新连接。若已更换凭据,请导入新的连接文件。"); return nil; }
142新增: struct utsname hardware;
143新增: NSString *model = uname(&hardware) == 0 ? [NSString stringWithUTF8String:hardware.machine] : nil;
144新增:#if TARGET_OS_SIMULATOR
145新增: model = NSProcessInfo.processInfo.environment[@"SIMULATOR_MODEL_IDENTIFIER"] ?: model;
146新增:#endif
147新增: [client reportDevice:@"ios" model:model ?: UIDevice.currentDevice.model];
148新增: return [self workspaceWithClient:client assets:assets error:error];
149新增:}
150新增:- (void)close {
151新增: CagemobileClient *client;
152新增: @synchronized (self) { client = _client; _client = nil; }
153新增: [client close:nil];
154新增:}
155新增:- (void)dealloc { [self close]; }
156新增:@end
新增mobile/ios/CageMobile/SimulatorWorkspacePreview.swift+94 −0看文件
@@ -0,0 +1,94 @@
1新增:// In-memory design preview. Compiled only for the simulator; never pairs a host.
2新增:#if targetEnvironment(simulator)
3新增:import SwiftUI
4新增:import WebKit
5新增:
6新增:enum SimulatorWorkspacePreview {
7新增: final class Preview: NSObject, WKURLSchemeHandler, WKNavigationDelegate {
8新增: func webView(_ webView: WKWebView, start urlSchemeTask: WKURLSchemeTask) {
9新增: guard let url = urlSchemeTask.request.url,
10新增: let root = Bundle.main.url(forResource: "mobile-ui", withExtension: nil) else {return}
11新增: let file = root.appendingPathComponent(url.path == "/" ? "mobile.html" : String(url.path.dropFirst())).standardizedFileURL
12新增: guard file.path.hasPrefix(root.path + "/"), let data = try? Data(contentsOf: file) else {
13新增: urlSchemeTask.didFailWithError(URLError(.fileDoesNotExist)); return
14新增: }
15新增: let types = ["html": "text/html", "js": "text/javascript", "css": "text/css", "png": "image/png"]
16新增: urlSchemeTask.didReceive(URLResponse(url: url, mimeType: types[file.pathExtension] ?? "application/octet-stream",
17新增: expectedContentLength: data.count, textEncodingName: "utf-8"))
18新增: urlSchemeTask.didReceive(data); urlSchemeTask.didFinish()
19新增: }
20新增: func webView(_ webView: WKWebView, stop urlSchemeTask: WKURLSchemeTask) {}
21新增: func webView(_ webView: WKWebView, decidePolicyFor action: WKNavigationAction,
22新增: decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
23新增: decisionHandler(action.request.url?.scheme == "cage-preview" ? .allow : .cancel)
24新增: }
25新增: }
26新增: static func makeWebView(model: ConnectionModel, id: String) -> (web: WKWebView, delegate: Preview) {
27新增: let delegate = Preview()
28新增: let origin = URL(string: "cage-preview://app/")!
29新增: let config = WKWebViewConfiguration()
30新增: config.websiteDataStore = .nonPersistent()
31新增: config.applicationNameForUserAgent = "CageMobile/1"
32新增: config.setURLSchemeHandler(delegate, forURLScheme: "cage-preview")
33新增: config.userContentController.add(DeviceWebBridge(model: model, id: id, origin: origin), name: "cageDevices")
34新增: config.userContentController.addUserScript(WKUserScript(source: fixture, injectionTime: .atDocumentStart, forMainFrameOnly: true))
35新增: let view = WKWebView(frame: .zero, configuration: config)
36新增: view.scrollView.contentInsetAdjustmentBehavior = .never
37新增: view.navigationDelegate = delegate
38新增: view.load(URLRequest(url: origin))
39新增: return (view, delegate)
40新增: }
41新增:
42新增: static let fixture = #"""
43新增: (() => {
44新增: const projects = [{name: "Cage", path: "/示例项目/cage"}, {name: "个人网站", path: "/示例项目/website"}];
45新增: let sequence = 0;
46新增: const uuid = () => "preview-" + (++sequence);
47新增: if (!crypto.randomUUID) crypto.randomUUID = uuid;
48新增: const snapshot = (id, workspace, title, turns = []) => ({id, workspace, title, turns,
49新增: revision: 1, generation: "simulator-preview", updated_at: new Date().toISOString()});
50新增: const sessions = [
51新增: snapshot("preview-ui", projects[0].path, "检查移动端界面", [{id: "turn-ui", prompt: "帮我检查移动端的布局和侧栏。",
52新增: text: "这里是示例会话,可以查看消息排版、输入框和项目切换。\n\n你也可以新建会话,输入一条消息查看交互效果。", status: "completed"}]),
53新增: snapshot("preview-approval", projects[0].path, "工具审批示例", [{id: "turn-approval", prompt: "查看项目目录。", text: "需要确认以下工具调用。",
54新增: status: "running", approval: {id: "approval-demo", tool: "Bash", input: {command: "ls -la", description: "查看示例项目文件"}}}]),
55新增: snapshot("preview-website", projects[1].path, "调整首页排版", [{id: "turn-website", prompt: "看看首页标题的间距。",
56新增: text: "这是第二个项目的示例会话。", status: "completed"}])
57新增: ];
58新增: window.fetch = async (input, options = {}) => {
59新增: const url = new URL(typeof input === "string" ? input : input.url, location.href);
60新增: const path = url.pathname.replace("/api/mobile/cli", "");
61新增: const body = options.body ? JSON.parse(options.body) : null;
62新增: let value;
63新增: if (path === "/projects") value = {host: window.__cageDevices?.devices.find(d => d.id === window.__cageDevices.current)?.name || "模拟器预览", ready: true, projects};
64新增: else if (path === "/sessions" && !body) value = {sessions};
65新增: else if (path === "/sessions") {
66新增: value = snapshot(uuid(), body.workspace, "新会话"); sessions.unshift(value);
67新增: } else {
68新增: const [, , id, action] = path.split("/");
69新增: value = sessions.find(s => s.id === id);
70新增: if (!value) return new Response("示例会话不存在", {status: 404, headers: {"Content-Type": "text/plain"}});
71新增: if (action === "metadata") {
72新增: if (body.title !== undefined) value.title = value.custom_title = body.title;
73新增: if (body.pinned !== undefined) value.pinned = body.pinned;
74新增: value.metadata_set = true;
75新增: } else if (action === "delete") {
76新增: sessions.splice(sessions.indexOf(value), 1);
77新增: return new Response(JSON.stringify({ok: true}), {headers: {"Content-Type": "application/json"}});
78新增: } else if (action === "messages") {
79新增: if (!value.custom_title) value.title = body.text.slice(0, 30);
80新增: value.turns.push({id: body.request_id, prompt: body.text, status: "completed",
81新增: text: "已收到示例消息。这是模拟器界面预览,没有连接电脑,也没有调用模型。"});
82新增: } else if (action === "approval") {
83新增: const turn = value.turns.at(-1);
84新增: turn.status = "completed"; delete turn.approval;
85新增: turn.text = body.allow ? "示例审批已允许。实际命令不会执行。" : "示例审批已拒绝。";
86新增: } else if (action === "stop") value.turns.at(-1).status = "stopped";
87新增: if (body) {value.revision++; value.updated_at = new Date().toISOString();}
88新增: }
89新增: return new Response(JSON.stringify(value), {headers: {"Content-Type": "application/json"}});
90新增: };
91新增: })();
92新增: """#
93新增:}
94新增:#endif
新增mobile/ios/DebuggingExport.plist+12 −0看文件
@@ -0,0 +1,12 @@
1新增:<?xml version="1.0" encoding="UTF-8"?>
2新增:<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3新增:<plist version="1.0">
4新增:<dict>
5新增: <key>method</key>
6新增: <string>debugging</string>
7新增: <key>destination</key>
8新增: <string>export</string>
9新增: <key>signingStyle</key>
10新增: <string>automatic</string>
11新增:</dict>
12新增:</plist>
新增mobile/scripts/licenses.sh+37 −0看文件
@@ -0,0 +1,37 @@
1新增:#!/bin/bash
2新增:# Bundle notices for the actual mobile Go dependency graph.
3新增:set -euo pipefail
4新增:mobile_dir="$(cd "$(dirname "$0")/.." && pwd)"
5新增:cd "$mobile_dir/bindings"
6新增:output="$mobile_dir/.build/resources/licenses"
7新增:mkdir -p "$output"
8新增:list="$(mktemp)"
9新增:trap 'rm -f "$list"' EXIT
10新增:# Both gomobile targets share the bundled notices.
11新增:for target in android ios; do
12新增: GOOS="$target" GOARCH=arm64 CGO_ENABLED=1 go list -deps -f '{{with .Module}}{{.Path}}{{"\t"}}{{.Version}}{{"\t"}}{{.Dir}}{{end}}' .
13新增:done | awk -F '\t' 'NF == 3 && !seen[$1]++' | LC_ALL=C sort > "$list"
14新增:{
15新增: cat <<'NOTICE'
16新增:Cage mobile third-party notices
17新增:
18新增:Cage mobile source and build scripts: https://github.com/Lee-xeo/claude-cage
19新增:The licenses of the linked Go modules are included below.
20新增:
21新增:NOTICE
22新增: go_license="$(go env GOROOT)/LICENSE"
23新增: [[ -f "$go_license" ]] || go_license="$(go env GOROOT)/../LICENSE"
24新增: cat "$go_license"
25新增: while IFS=$'\t' read -r path version directory; do
26新增: for file in "$directory"/LICENSE* "$directory"/LICENCE* "$directory"/COPYING* "$directory"/NOTICE* "$directory"/UNLICENSE*; do
27新增: [[ -f "$file" ]] || continue
28新增: printf '\n======== %s %s: %s ========\n\n' "$path" "$version" "$(basename "$file")"
29新增: cat "$file"
30新增: done
31新增: done < "$list"
32新增:} > "$output/THIRD_PARTY_NOTICES.txt"
33新增:cp "$mobile_dir/../ui/node_modules/marked/LICENSE" "$output/Marked-LICENSE.txt"
34新增:cp "$mobile_dir/android/licenses/ZXing-LICENSE.txt" "$output/ZXing-LICENSE.txt"
35新增:if [[ -f "$mobile_dir/.build/android/webkit-1.14.0.aar" ]]; then
36新增: unzip -p "$mobile_dir/.build/android/webkit-1.14.0.aar" META-INF/androidx/webkit/webkit/LICENSE.txt > "$output/AndroidX-LICENSE.txt"
37新增:fi
修改scripts/browser-audit-smoke.mjs+13 −8看文件
@@ -109,12 +109,17 @@ try {
109109 (await cdp("Target.getBrowserContexts")).browserContextIds,
110110 [],
111111 );
112删除: assert.deepEqual(
113删除: (await cdp("Target.getTargets")).targetInfos
114删除: .filter((page) => page.type === "page")
115删除: .map((page) => page.targetId),
116删除: [userPage.targetId],
117删除: );
112新增: // A normal background tab can finish its close animation after the CDP
113新增: // acknowledgement. It must disappear within the bounded cleanup interval.
114新增: let pages;
115新增: const deadline = Date.now() + 2000;
116新增: do {
117新增: pages = (await cdp("Target.getTargets")).targetInfos
118新增: .filter(page => page.type === "page").map(page => page.targetId);
119新增: if (pages.length === 1 && pages[0] === userPage.targetId) break;
120新增: await delay(25);
121新增: } while (Date.now() < deadline);
122新增: assert.deepEqual(pages, [userPage.targetId]);
118123 assert.equal(await state(), before, "The user's page or focus changed");
119124 };
120125 for (let index = 0; index < 20; index++) {
@@ -125,7 +130,7 @@ try {
125130 }
126131 await assert.rejects(
127132 auditBrowser(cdp, excluded, false, "Invalid/Timezone"),
128删除: /浏览器诊断未完成/,
133新增: /浏览器(?:配置)?诊断未完成/,
129134 );
130135 await clean();
131136 // The guest's existing diagnostic endpoint exercises navigation and fetch.
@@ -137,7 +142,7 @@ try {
137142 } catch (error) {
138143 // The diagnostic endpoint is only served during network verification.
139144 // Outside that window, verify cleanup of the failed navigation as well.
140删除: assert.match(error.message, /诊断页面无法连接|诊断页面尚未就绪/);
145新增: assert.match(error.message, /诊断页面无法连接|诊断页面尚未就绪|Timeout: Page.navigate/);
141146 }
142147 await clean();
143148 console.log(
修改scripts/browser-controls-smoke.mjs+8 −3看文件
@@ -119,7 +119,7 @@ try {
119119 .replaceAll("/usr/local/lib/cage-split", join(directory, "split-extension"))
120120 .replace("/etc/claude-cage/browser-control.json", join(directory, "control.json"))
121121 .replace(listen, 'server.listen(0, "127.0.0.1", () => console.log("CONTROL_PORT=" + server.address().port));'));
122删除: for (const name of ["browser-audit", "browser-downloads", "browser-uploads", "browser-login", "browser-vault", "browser-clipboard", "native-input"])
122新增: for (const name of ["browser-audit", "browser-downloads", "browser-uploads", "browser-login", "browser-private", "browser-cookies", "browser-extensions", "browser-vault", "browser-clipboard", "native-input"])
123123 await copyFile(new URL(`../internal/cage/${name}.mjs`, import.meta.url), join(directory, `${name}.mjs`));
124124 await cp(new URL("../internal/cage/split-extension", import.meta.url), join(directory, "split-extension"), { recursive: true });
125125 await writeFile(join(directory, "control.json"), JSON.stringify({ token, workspace: directory }));
@@ -178,11 +178,16 @@ try {
178178 assert.equal(restored.tabs.length, 1);
179179 assert.equal(restored.tabs[0].url, origin + "/third");
180180 await api("/close", { id: restored.active });
181删除: assert.equal((await api("/tabs")).tabs.length, 1, "Closing the last tab must create a homepage tab");
181新增: const empty = await api("/tabs");
182新增: assert.equal(empty.tabs.length, 0, "Closing the last tab must leave the browser empty");
183新增: assert.equal(empty.active, "");
184新增: await waitFor(() => eventState?.tabs.length === 0 && eventState.active === "", "empty browser events");
185新增: const reopened = await api("/new", { url: origin + "/first" });
186新增: assert.equal((await api("/tabs")).active, reopened.id);
182187 console.log(JSON.stringify({
183188 webdriver: false, newTab: true, activate: true, navigate: true,
184189 back: true, forward: true, reload: true, close: true,
185删除: sessionRestored: true, cookiesPreserved: true, lastTabReplaced: true,
190新增: sessionRestored: true, cookiesPreserved: true, lastTabClosed: true, reopened: true,
186191 unauthenticatedRejected: true, crossOriginRejected: true,
187192 }));
188193} finally {
新增scripts/browser-language-smoke.mjs+85 −0看文件
@@ -0,0 +1,85 @@
1新增:// Run in an isolated Linux guest with chromium-l10n installed:
2新增:// CAGE_TEST_BROWSER_PATH=/usr/bin/chromium TZ=Asia/Taipei node scripts/browser-language-smoke.mjs
3新增:import assert from 'node:assert/strict';
4新增:import { createPrivacyController } from './browser-privacy-fixture.mjs';
5新增:
6新增:assert.equal(process.platform, 'linux');
7新增:const languages = process.env.CAGE_TEST_LANGUAGES?.split(',') || ['en-US', 'zh-TW', 'zh-CN', 'ja-JP', 'de-DE', 'fr-FR'];
8新增:for (const language of languages) {
9新增: process.env.CAGE_LANGUAGE = language;
10新增: // Cage applies both the guest locale and the browser language at startup.
11新增: process.env.LANG = process.env.LC_ALL = process.env.CAGE_TEST_SYSTEM_LOCALE || language.replace('-', '_') + '.UTF-8';
12新增: const fixture = await createPrivacyController({
13新增: preferences: { intl: { accept_languages: 'en-US', selected_languages: 'en-US' } },
14新增: });
15新增: try {
16新增: const { api, cdp, evaluate, restart, waitFor } = fixture;
17新增: const normal = (await api('/tabs')).active;
18新增: const expression = '({language:navigator.language,languages:[...navigator.languages],timezone:Intl.DateTimeFormat().resolvedOptions().timeZone})';
19新增: const page = await evaluate(normal, expression);
20新增: if (process.env.CAGE_TEST_NETWORK === '1') {
21新增: const cookie = await cdp(normal, 'Network.setCookie', {
22新增: name: 'account-sentinel', value: 'must-not-enter-probe', url: 'http://198.18.0.254/',
23新增: });
24新增: assert.equal(cookie.success, true);
25新增: }
26新增: const tabsBefore = await api('/tabs');
27新增: const streamAbort = new AbortController();
28新增: const stream = await fixture.states(streamAbort.signal);
29新增: const events = [];
30新增: const reading = (async () => {
31新增: let buffer = '';
32新增: try {
33新增: for await (const chunk of stream.body) {
34新增: buffer += new TextDecoder().decode(chunk);
35新增: let end;
36新增: while ((end = buffer.indexOf('\n\n')) >= 0) {
37新增: const event = buffer.slice(0, end);
38新增: buffer = buffer.slice(end + 2);
39新增: const data = event.split('\n').find(line => line.startsWith('data: '));
40新增: if (data) events.push(JSON.parse(data.slice(6)));
41新增: }
42新增: }
43新增: } catch (error) { if (error.name !== 'AbortError') throw error; }
44新增: })();
45新增: let audit;
46新增: try {
47新增: audit = await api('/audit', { timezone: process.env.TZ || 'UTC', network: process.env.CAGE_TEST_NETWORK === '1' });
48新增: } finally { streamAbort.abort(); await reading; }
49新增: console.log(JSON.stringify({ configured: language, normal: page, audit }));
50新增: assert.equal(page.language, language);
51新增: assert.equal(audit.language, language);
52新增: assert.equal(audit.timezone, audit.expected_timezone);
53新增: const tabsAfter = await api('/tabs');
54新增: assert.equal(tabsAfter.active, tabsBefore.active);
55新增: assert.deepEqual(tabsAfter.tabs.map(tab => tab.id), tabsBefore.tabs.map(tab => tab.id));
56新增: assert.ok(events.length > 0);
57新增: for (const state of events) {
58新增: assert.equal(state.active, tabsBefore.active);
59新增: assert.deepEqual(state.tabs.map(tab => tab.id), tabsBefore.tabs.map(tab => tab.id), 'diagnostic tab entered live state');
60新增: }
61新增: if (process.env.CAGE_TEST_NETWORK === '1') {
62新增: assert.equal(audit.network.status, 200);
63新增: assert.equal(audit.network.seen_cookie, '', 'diagnostic network request carried an account cookie');
64新增: }
65新增:
66新增: const privatePage = await api('/new', { incognito: true });
67新增: const privateLanguage = await evaluate(privatePage.id, 'navigator.language');
68新增: assert.equal(privateLanguage, language);
69新增: await api('/close', { id: privatePage.id });
70新增:
71新增: // Observe a real request header, with no Network or Emulation override.
72新增: await cdp(normal, 'Network.enable');
73新增: await cdp(normal, 'Page.navigate', { url: fixture.origin + '/language' });
74新增: await waitFor(() => evaluate(normal, 'document.readyState === "complete"'), 'language page loaded');
75新增: const header = await evaluate(normal, `fetch('/language-header').then(r=>r.text())`);
76新增: assert.match(header, new RegExp('^' + language + '(?:,|$)', 'i'));
77新增:
78新增: // The command-line preference must also survive a profile restart.
79新增: await restart();
80新增: assert.equal(await evaluate((await api('/tabs')).active, 'navigator.language'), language);
81新增: console.log(JSON.stringify({ configured: language, privateLanguage, header, staleProfileRestart: 'passed' }));
82新增: } finally {
83新增: await fixture.close();
84新增: }
85新增:}
新增scripts/browser-last-tab-smoke.mjs+56 −0看文件
@@ -0,0 +1,56 @@
1新增:import assert from 'node:assert/strict';
2新增:import { createPrivacyController } from './browser-privacy-fixture.mjs';
3新增:
4新增:const fixture = await createPrivacyController();
5新增:const { api, cdp, waitFor, origin } = fixture;
6新增:const events = [];
7新增:const stream = new AbortController();
8新增:let eventLoop;
9新增:try {
10新增: const response = await fixture.states(stream.signal);
11新增: assert.equal(response.status, 200);
12新增: eventLoop = (async () => {
13新增: const decoder = new TextDecoder();
14新增: let buffer = '';
15新增: for await (const chunk of response.body) {
16新增: buffer += decoder.decode(chunk, { stream: true });
17新增: let end;
18新增: while ((end = buffer.indexOf('\n\n')) !== -1) {
19新增: const frame = buffer.slice(0, end);
20新增: buffer = buffer.slice(end + 2);
21新增: if (frame.startsWith('data: ')) events.push(JSON.parse(frame.slice(6)));
22新增: }
23新增: }
24新增: })().catch(error => { if (!stream.signal.aborted) throw error; });
25新增: const assertEmpty = async () => {
26新增: const state = await api('/tabs');
27新增: assert.deepEqual(state.tabs, []);
28新增: assert.equal(state.active, '');
29新增: await waitFor(() => events.at(-1)?.tabs.length === 0, 'empty browser event');
30新增: assert.equal(events.at(-1).active, '', 'empty snapshot must not reference a destroyed tab');
31新增: };
32新增: await api('/close', { id: (await api('/tabs')).active });
33新增: await assertEmpty();
34新增: const reopened = await api('/new', { url: origin + '/reopened' });
35新增: assert.equal((await api('/tabs')).tabs.length, 1);
36新增: assert.equal((await api('/tabs')).active, reopened.id);
37新增:
38新增: // Native Chromium closes must publish the same empty state as the HTTP action.
39新增: await cdp(reopened.id, 'Target.closeTarget', { targetId: reopened.id });
40新增: await waitFor(async () => (await api('/tabs')).tabs.length === 0, 'external close');
41新增: await assertEmpty();
42新增: const privateTab = await api('/new', { url: origin + '/private', incognito: true });
43新增: const context = (await cdp(privateTab.id, 'Target.getTargetInfo')).targetInfo.browserContextId;
44新增: await api('/close', { id: privateTab.id });
45新增: await assertEmpty();
46新增: const contexts = await cdp('', 'Target.getBrowserContexts');
47新增: assert.ok(!contexts.browserContextIds.includes(context), 'last private tab must dispose its context');
48新增: const final = await api('/new', { url: origin + '/final' });
49新增: assert.equal((await api('/tabs')).active, final.id);
50新增: console.log(JSON.stringify({ passed: true, lastTabClosed: true, emptyEvents: true,
51新增: externalClose: true, privateContextDisposed: true, reopened: true }));
52新增:} finally {
53新增: stream.abort();
54新增: await eventLoop;
55新增: await fixture.close();
56新增:}
修改scripts/browser-metadata-smoke.mjs+2 −1看文件
@@ -51,7 +51,7 @@ const site = http.createServer((req, res) => {
5151 };
5252 </script>` : "";
5353 const frame = req.url === "/frame" ? `<iframe id="child" width="1000" height="300" allow="clipboard-write" src="http://127.0.0.1:${site.address().port}/copy"></iframe>` : "";
54删除: res.end(`<!doctype html><title>${req.url}</title><link rel="icon" href="${iconOrigin}/${icon}.svg"><p>Isolated browser metadata fixture</p>${buttons}${frame}`);
54新增: res.end(`<!doctype html><script>globalThis.webdriverAtLoad = navigator.webdriver</script><title>${req.url}</title><link rel="icon" href="${iconOrigin}/${icon}.svg"><p>Isolated browser metadata fixture</p>${buttons}${frame}`);
5555});
5656await new Promise(resolve => site.listen(0, "127.0.0.1", resolve));
5757const origin = `http://localhost:${site.address().port}`;
@@ -175,6 +175,7 @@ try {
175175 const id = initial.id, red = initial.favicon;
176176 checkPNG(red);
177177 assert.equal(await evaluate(id, "navigator.webdriver"), false);
178新增: assert.equal(await evaluate(id, "globalThis.webdriverAtLoad"), false, "identity must be ready before the first website script");
178179 assert.equal((await api("/tabs")).tabs.find(item => item.id === id).favicon, red);
179180
180181 await api("/navigate", { id, url: origin + "/blue" });
新增scripts/browser-privacy-fixture.mjs+119 −0看文件
@@ -0,0 +1,119 @@
1新增:// Real production controller; only deployment paths, headless display and a
2新增:// private authenticated test-driving CDP route differ from the guest service.
3新增:import assert from 'node:assert/strict';
4新增:import { spawn } from 'node:child_process';
5新增:import { once } from 'node:events';
6新增:import { randomBytes } from 'node:crypto';
7新增:import { cp, mkdir, mkdtemp, readdir, readFile, realpath, rm, writeFile } from 'node:fs/promises';
8新增:import http from 'node:http';
9新增:import { tmpdir } from 'node:os';
10新增:import { join } from 'node:path';
11新增:import { setTimeout as delay } from 'node:timers/promises';
12新增:
13新增:export async function createPrivacyController({ preferences } = {}) {
14新增: const browserPath = process.env.CAGE_PRIVACY_BROWSER_PATH || process.env.CAGE_TEST_BROWSER_PATH;
15新增: assert.ok(browserPath, 'Set CAGE_PRIVACY_BROWSER_PATH or CAGE_TEST_BROWSER_PATH to Chromium');
16新增: const directory = await realpath(await mkdtemp(join(tmpdir(), 'cage-browser-privacy-')));
17新增: if (preferences) {
18新增: await mkdir(join(directory, 'profile/Default'), { recursive: true });
19新增: await writeFile(join(directory, 'profile/Default/Preferences'), JSON.stringify(preferences));
20新增: }
21新增: const token = randomBytes(32).toString('hex');
22新增: const site = http.createServer((req, res) => {
23新增: if (req.url === '/language-header') {
24新增: res.end(req.headers['accept-language'] || '');
25新增: return;
26新增: }
27新增: res.setHeader('Content-Type', 'text/html');
28新增: res.end('<!doctype html><script>globalThis.webdriverAtLoad = navigator.webdriver; if (parent !== self) parent.postMessage({fixtureIdentity: navigator.webdriver}, "*")</script><title>Privacy fixture</title><form><input autocomplete="username"><input type="password" autocomplete="current-password"><button>Sign in</button></form>');
29新增: });
30新增: await new Promise(resolve => site.listen(0, '127.0.0.1', resolve));
31新增: const origin = `http://localhost:${site.address().port}`;
32新增: let agent, control, stderr = '';
33新增: const waitFor = async (read, label) => {
34新增: const deadline = Date.now() + 15000;
35新增: while (Date.now() < deadline) {
36新增: if (agent && agent.exitCode !== null) throw new Error(`Controller exited: ${stderr}`);
37新增: const value = await read();
38新增: if (value) return value;
39新增: await delay(50);
40新增: }
41新增: throw new Error(`Timed out: ${label}. ${stderr.slice(-1000)}`);
42新增: };
43新增: const api = async (path, body) => {
44新增: const response = await fetch(control + path, {
45新增: method: body === undefined ? 'GET' : 'POST',
46新增: headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
47新增: body: body === undefined ? undefined : JSON.stringify(body),
48新增: });
49新增: const result = await response.json();
50新增: if (!response.ok) throw new Error(result.error || 'Controller request failed');
51新增: return result;
52新增: };
53新增: const cdp = (id, method, params = {}) => api('/__privacy-test', { id, method, params });
54新增: const evaluate = async (id, expression) => {
55新增: const result = await cdp(id, 'Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true });
56新增: assert.equal(result.exceptionDetails, undefined);
57新增: return result.result.value;
58新增: };
59新增: const stop = async () => {
60新增: if (agent?.exitCode === null) {
61新增: const done = once(agent, 'exit'); agent.kill('SIGTERM');
62新增: const kill = setTimeout(() => agent.kill('SIGKILL'), 5000);
63新增: await done; clearTimeout(kill);
64新增: }
65新增: };
66新增: const close = async () => {
67新增: await stop();
68新增: site.closeAllConnections();
69新增: await new Promise(resolve => site.close(resolve));
70新增: await rm(directory, { recursive: true, force: true });
71新增: };
72新增: try {
73新增: const sourceDirectory = new URL('../internal/cage/', import.meta.url);
74新增: for (const name of await readdir(sourceDirectory))
75新增: if ((name.startsWith('browser-') && name.endsWith('.mjs')) || name === 'native-input.mjs' || name === 'tailnet-client.mjs' || name === 'browser-extension-archive.py')
76新增: await cp(new URL(name, sourceDirectory), join(directory, name));
77新增: await cp(new URL('split-extension', sourceDirectory), join(directory, 'extension'), { recursive: true });
78新增: const source = await readFile(new URL('browser-agent.mjs', sourceDirectory), 'utf8');
79新增: const marker = 'const input = JSON.parse(text || "{}");';
80新增: assert.ok(source.includes(marker));
81新增: const adapted = source.replaceAll('/home/cage-browser', directory)
82新增: .replace('/etc/claude-cage/browser-control.json', join(directory, 'control.json'))
83新增: .replace('/usr/local/lib/cage-split', join(directory, 'extension'))
84新增: .replace('spawn("/usr/bin/chromium", flags', `spawn(${JSON.stringify(browserPath)}, flags`)
85新增: .replace('"--start-fullscreen",', '"--headless=new", "--disable-background-networking",')
86新增: .replace('server.listen(18500, "127.0.0.1");', 'server.listen(0,"127.0.0.1",()=>console.log("PORT="+server.address().port));')
87新增: .replace(marker, `${marker}\nif(req.url === "/__privacy-test") { res.end(JSON.stringify(await cdp(input.method, input.params || {}, input.id ? await session(input.id) : input.sessionId))); return; }`);
88新增: await writeFile(join(directory, 'browser-agent.mjs'), adapted);
89新增: await writeFile(join(directory, 'control.json'), JSON.stringify({ token, workspace: directory }));
90新增: await writeFile(join(directory, 'homepage.json'), JSON.stringify({ url: origin + '/home' }));
91新增: const start = async () => {
92新增: control = ''; stderr = '';
93新增: agent = spawn(process.execPath, [join(directory, 'browser-agent.mjs')], { stdio: ['ignore', 'pipe', 'pipe'] });
94新增: let output = '';
95新增: agent.stdout.on('data', chunk => {
96新增: output += chunk;
97新增: const match = output.match(/PORT=(\d+)/);
98新增: if (match) control = 'http://127.0.0.1:' + match[1];
99新增: });
100新增: agent.stderr.on('data', chunk => { stderr = (stderr + chunk).slice(-4000); });
101新增: await waitFor(() => control, 'listener');
102新增: await waitFor(async () => {
103新增: try {
104新增: const response = await fetch(control + '/health', { headers: { Authorization: `Bearer ${token}` } });
105新增: return response.ok;
106新增: } catch { return false; }
107新增: }, 'browser readiness');
108新增: };
109新增: await start();
110新增: const uploadExtension = async bytes => {
111新增: const response = await fetch(control + '/extensions-upload', { method: 'POST', headers: { Authorization: `Bearer ${token}` }, body: bytes });
112新增: const result = await response.json();
113新增: if (!response.ok) throw new Error(result.error || '扩展包读取失败');
114新增: return result;
115新增: };
116新增: const states = signal => fetch(control + '/events', { headers: { Authorization: `Bearer ${token}` }, signal });
117新增: return { api, cdp, evaluate, waitFor, origin, directory, close, uploadExtension, states, restart: async () => { await stop(); await start(); } };
118新增: } catch (error) { await close(); throw error; }
119新增:}
新增scripts/browser-privacy-smoke.mjs+101 −0看文件
@@ -0,0 +1,101 @@
1新增:import assert from 'node:assert/strict';
2新增:import { readFile } from 'node:fs/promises';
3新增:import { join } from 'node:path';
4新增:import { createPrivacyController } from './browser-privacy-fixture.mjs';
5新增:
6新增:const fixture = await createPrivacyController();
7新增:const { api, cdp, evaluate, waitFor, origin, directory } = fixture;
8新增:const list = (id, extra = {}) => api('/cookies', { id, mode: 'list', scope: 'all', ...extra });
9新增:const checks = [];
10新增:try {
11新增: const normal = (await api('/tabs')).active;
12新增: const ready = id => waitFor(() => evaluate(id, 'document.readyState === "complete"'), 'page loaded');
13新增: await ready(normal);
14新增: await cdp(normal, 'Network.setCookie', { name: 'normal', value: 'normal-value', url: origin, expires: Date.now() / 1000 + 3600 });
15新增: assert.equal((await list(normal)).cookies[0].name, 'normal');
16新增: const restored = await readFile(join(directory, 'workbench-state.json'), 'utf8');
17新增: const first = await api('/new', { url: origin + '/private', incognito: true });
18新增: await ready(first.id);
19新增: assert.equal((await api('/tabs')).tabs.find(tab => tab.id === first.id).incognito, true);
20新增: assert.equal((await list(first.id)).total, 0);
21新增: assert.equal(await evaluate(first.id, 'document.cookie'), '');
22新增: await evaluate(first.id, 'localStorage.setItem("private-only", "temporary"); document.cookie = "private=private-value;path=/"');
23新增: assert.equal(await readFile(join(directory, 'workbench-state.json'), 'utf8'), restored);
24新增: const second = await api('/new', { url: origin + '/private-second', incognito: true });
25新增: await ready(second.id);
26新增: assert.equal(await evaluate(second.id, 'localStorage.getItem("private-only")'), 'temporary');
27新增: assert.match(await evaluate(second.id, 'document.cookie'), /private=private-value/);
28新增: checks.push('private cookies and localStorage isolated from normal tabs, shared by private tabs; restore URL unchanged');
29新增:
30新增: const privateCookie = (await list(first.id)).cookies.find(cookie => cookie.name === 'private');
31新增: assert.equal('value' in privateCookie, false);
32新增: assert.equal((await api('/cookies', { id: first.id, mode: 'details', scope: 'all', cookieKey: privateCookie.key })).value, 'private-value');
33新增: await api('/cookies', { id: second.id, mode: 'clear', scope: 'all' });
34新增: assert.equal((await list(first.id)).total, 0);
35新增: assert.equal((await list(normal)).total, 1);
36新增: checks.push('values are returned only on demand; clearing private cookies preserves normal login');
37新增:
38新增: await api('/close', { id: first.id });
39新增: assert.equal(await evaluate(second.id, 'localStorage.getItem("private-only")'), 'temporary');
40新增: const popup = await cdp(second.id, 'Target.createTarget', {
41新增: url: origin + '/popup', browserContextId: (await cdp(second.id, 'Target.getTargetInfo')).targetInfo.browserContextId,
42新增: });
43新增: await waitFor(async () => (await api('/tabs')).tabs.find(tab => tab.id === popup.targetId)?.incognito, 'private popup classification');
44新增: await api('/close', { id: second.id });
45新增: await ready(popup.targetId);
46新增: assert.equal(await evaluate(popup.targetId, 'localStorage.getItem("private-only")'), 'temporary');
47新增: await api('/close', { id: popup.targetId });
48新增: const third = await api('/new', { url: origin + '/private-fresh', incognito: true });
49新增: await ready(third.id);
50新增: assert.equal(await evaluate(third.id, 'localStorage.getItem("private-only")'), null);
51新增: assert.equal((await list(third.id)).total, 0);
52新增: const vault = await api('/vault', { action: 'status', tab: third.id, lease: 'f'.repeat(64) });
53新增: assert.equal(vault.origin, ''); assert.deepEqual(vault.candidates, []);
54新增: checks.push('private popups stay private; closing final private tab clears storage; private pages do not enter vault');
55新增:
56新增: // Same name and domain, different paths and partition keys must be distinct.
57新增: await cdp(normal, 'Network.setCookies', { cookies: [
58新增: { name: 'same', value: 'root', domain: 'localhost', path: '/' },
59新增: { name: 'same', value: 'nested', domain: 'localhost', path: '/nested' },
60新增: { name: 'unrelated', value: 'preserve', domain: 'other.test', path: '/' },
61新增: { name: 'partition', value: 'plain', domain: 'localhost', path: '/', secure: true },
62新增: { name: 'partition', value: 'partitioned', domain: 'localhost', path: '/', secure: true, partitionKey: { topLevelSite: 'https://example.test', hasCrossSiteAncestor: true } },
63新增: ] });
64新增: let cookies = await list(normal, { scope: 'site' });
65新增: assert.ok(cookies.cookies.every(cookie => cookie.domain === 'localhost'));
66新增: const nested = cookies.cookies.find(cookie => cookie.name === 'same' && cookie.path === '/nested');
67新增: await api('/cookies', { id: normal, mode: 'delete', scope: 'site', cookieKey: nested.key });
68新增: cookies = await list(normal);
69新增: assert.equal(cookies.cookies.filter(cookie => cookie.name === 'same').length, 1);
70新增: const partitioned = cookies.cookies.find(cookie => cookie.partitionKey);
71新增: assert.ok(partitioned, 'real partitioned fixture stored');
72新增: await api('/cookies', { id: normal, mode: 'delete', scope: 'all', cookieKey: partitioned.key });
73新增: assert.equal((await list(normal)).cookies.filter(cookie => cookie.name === 'partition').length, 1);
74新增: checks.push('deletion respects path and partition key; site filtering excludes unrelated hosts');
75新增:
76新增: await cdp(normal, 'Network.setCookies', { cookies: Array.from({ length: 57 }, (_, i) => ({ name: 'paged-' + i, value: String(i), domain: 'localhost', path: '/' })) });
77新增: cookies = await list(normal, { query: 'paged-', page: 1 });
78新增: assert.equal(cookies.total, 57); assert.equal(cookies.cookies.length, 7);
79新增: await api('/cookies', { id: normal, mode: 'clear', scope: 'site', query: 'paged-' });
80新增: cookies = await list(normal);
81新增: assert.equal(cookies.total, 1); assert.equal(cookies.cookies[0].name, 'unrelated');
82新增: checks.push('search and pagination; clearing a site ignores search and preserves other hosts');
83新增:
84新增: await cdp(normal, 'Network.setCookie', { name: 'persistent', value: 'retained', url: origin, expires: Date.now() / 1000 + 3600 });
85新增: await assert.rejects(api('/cookies', { id: normal, url: origin + '/stale-page', mode: 'clear', scope: 'all' }), /网页已切换/);
86新增: assert.ok((await list(normal)).cookies.some(cookie => cookie.name === 'persistent'));
87新增: await api('/activate', { id: normal });
88新增: await api('/activate', { id: third.id });
89新增: await fixture.restart();
90新增: const afterRestart = await api('/tabs');
91新增: assert.ok(afterRestart.tabs.every(tab => !tab.incognito && !tab.url.includes('/private')));
92新增: assert.ok((await list(afterRestart.active)).cookies.some(cookie => cookie.name === 'persistent'));
93新增: checks.push('controller restart restores normal state and persistent cookies, never private pages');
94新增: const lastPrivate = await api('/new', { url: origin + '/private-last', incognito: true });
95新增: for (const tab of (await api('/tabs')).tabs.filter(tab => !tab.incognito)) await api('/close', { id: tab.id });
96新增: await api('/close', { id: lastPrivate.id });
97新增: const last = await api('/tabs');
98新增: assert.equal(last.tabs.length, 0); assert.equal(last.active, '');
99新增: checks.push('closing the only remaining private page leaves the browser empty');
100新增: console.log(JSON.stringify({ passed: true, checks }, null, 2));
101新增:} finally { await fixture.close(); }
新增scripts/browser-settings-smoke.mjs+70 −0看文件
@@ -0,0 +1,70 @@
1新增:import assert from 'node:assert/strict';
2新增:import { execFileSync } from 'node:child_process';
3新增:import { readFile } from 'node:fs/promises';
4新增:import { join } from 'node:path';
5新增:import { createPrivacyController } from './browser-privacy-fixture.mjs';
6新增:const fixture = await createPrivacyController();
7新增:const { api, cdp, evaluate, waitFor, origin, directory } = fixture;
8新增:const checks = [];
9新增:try {
10新增: const one = await api('/settings', { mode: 'general' });
11新增: assert.equal(one.kind, 'browser-settings'); assert.equal(one.url, 'cage://settings#general');
12新增: const two = await api('/settings', { mode: 'extensions' });
13新增: assert.equal(two.id, one.id);
14新增: assert.equal((await api('/tabs')).tabs.find(tab => tab.id === one.id).kind, 'browser-settings');
15新增: assert.equal((await api('/cookies', { id: one.id, url: two.url, mode: 'list', scope: 'all' })).incognito, false);
16新增: checks.push('menu settings action reuses one real browser target; public internal URL and ordinary-session cookie management work');
17新增: const bytes = execFileSync('uv', ['run', '--no-project', 'python', '-c', `import io,zipfile,json,sys
18新增:b=io.BytesIO()
19新增:with zipfile.ZipFile(b,'w') as z:
20新增: z.writestr('manifest.json',json.dumps({'manifest_version':3,'name':'Cage test extension','version':'1.0','permissions':['storage'],'content_scripts':[{'matches':['http://localhost/*'],'js':['content.js']}]}))
21新增: z.writestr('content.js','document.documentElement.dataset.cageExtension="active"; chrome.storage.local.set({persisted:"retained"});')
22新增:sys.stdout.buffer.write(b.getvalue())`], { maxBuffer: 1 << 20, stdio: ['ignore', 'pipe', 'ignore'] });
23新增: const selected = await fixture.uploadExtension(bytes);
24新增: assert.equal(selected.name, 'Cage test extension'); assert.deepEqual(selected.permissions, ['storage']);
25新增: assert.ok(selected.hostPermissions.includes('http://localhost/*'));
26新增: assert.equal((await api('/extensions', { mode: 'list' })).items.length, 0);
27新增: const source = 'a'.repeat(32) + ':' + 'b'.repeat(32);
28新增: const installed = await api('/extensions', { mode: 'install', session: selected.session, target: source });
29新增: const extension = installed.items.find(item => item.name === selected.name);
30新增: assert.ok(extension?.enabled); assert.ok(extension.managed);
31新增: assert.equal(extension.source, source);
32新增: const tab = await api('/new', { url: origin + '/extension-test' });
33新增: await waitFor(() => evaluate(tab.id, 'document.documentElement.dataset.cageExtension === "active"'), 'real extension content script');
34新增: checks.push('ZIP review does not install until confirmed; declared and content-script permissions shown; installed extension executes in a real page');
35新增: await fixture.restart();
36新增: let list = await api('/extensions', { mode: 'list' });
37新增: assert.equal(list.items.find(item => item.id === extension.id).enabled, true);
38新增: assert.equal(list.items.find(item => item.id === extension.id).source, source);
39新增: let page = await api('/new', { url: origin + '/after-restart' });
40新增: await waitFor(() => evaluate(page.id, 'document.documentElement.dataset.cageExtension === "active"'), 'extension restored after restart');
41新增: await api('/extensions', { mode: 'disable', id: extension.id });
42新增: page = await api('/new', { url: origin + '/disabled' });
43新增: await waitFor(() => evaluate(page.id, 'document.readyState === "complete"'), 'disabled fixture ready');
44新增: assert.equal(await evaluate(page.id, 'document.documentElement.dataset.cageExtension || ""'), '');
45新增: await fixture.restart();
46新增: list = await api('/extensions', { mode: 'list' });
47新增: assert.equal(list.items.find(item => item.id === extension.id).enabled, false);
48新增: await api('/extensions', { mode: 'enable', id: extension.id });
49新增: page = await api('/new', { url: origin + '/enabled-again' });
50新增: await waitFor(() => evaluate(page.id, 'document.documentElement.dataset.cageExtension === "active"'), 'enabled fixture');
51新增: const storage = await cdp(page.id, 'Extensions.getStorageItems', { id: extension.id, storageArea: 'local' });
52新增: assert.equal(storage.data.persisted, 'retained');
53新增: checks.push('enabled extensions restore after restart; disable survives restart; re-enable preserves extension storage');
54新增: await api('/extensions', { mode: 'remove', id: extension.id });
55新增: assert.equal((await api('/extensions', { mode: 'list' })).items.length, 0);
56新增: await fixture.restart();
57新增: assert.equal((await api('/extensions', { mode: 'list' })).items.length, 0);
58新增: const registry = JSON.parse(await readFile(join(directory, 'extensions/registry.json'), 'utf8'));
59新增: assert.deepEqual(registry, []);
60新增: checks.push('uninstall removes the extension and persistent installation record');
61新增: const helper = (await cdp(null, 'Extensions.getExtensions')).extensions.find(item => item.name === 'Cage browser panes');
62新增: const control = (await cdp(null, 'Target.getTargets')).targetInfos.find(item => item.url.endsWith('/control.html'));
63新增: const { sessionId } = await cdp(null, 'Target.attachToTarget', { targetId: control.targetId, flatten: true });
64新增: await api('/__privacy-test', { sessionId, method: 'Runtime.evaluate', params: { expression: `chrome.management.setEnabled(${JSON.stringify(helper.id)}, false)`, userGesture: true } }).catch(() => {});
65新增: await waitFor(async () => { try { return Array.isArray((await api('/extensions', { mode: 'list' })).items); } catch { return false; } }, 'built-in browser controller recovers after native extension disable');
66新增: checks.push('built-in browser component is protected by controller recovery');
67新增: await assert.rejects(api('/internal-page', { mode: 'arbitrary' }), /内部页面无效/);
68新增: await assert.rejects(fixture.uploadExtension(Buffer.from('invalid zip')));
69新增: console.log(JSON.stringify({ passed: true, checks }, null, 2));
70新增:} finally { await fixture.close(); }
新增scripts/browser-warning-smoke.mjs+44 −0看文件
@@ -0,0 +1,44 @@
1新增:import assert from "node:assert/strict";
2新增:import { createPrivacyController } from "./browser-privacy-fixture.mjs";
3新增:
4新增:const fixture = await createPrivacyController();
5新增:try {
6新增: const { api, evaluate, waitFor, origin, restart } = fixture;
7新增: async function check(id) {
8新增: await waitFor(() => evaluate(id, "document.readyState === 'complete'"), "page loaded");
9新增: assert.deepEqual(await evaluate(id, "[navigator.webdriver, globalThis.webdriverAtLoad]"), [false, false]);
10新增: }
11新增: await check((await api("/tabs")).active);
12新增: for (const incognito of [false, true]) {
13新增: const tab = await api("/new", { url: origin + "/identity", incognito });
14新增: await check(tab.id);
15新增: const frameIdentity = await evaluate(tab.id, `new Promise(resolve => {
16新增: const frame = document.createElement('iframe');
17新增: const received = event => {
18新增: if (event.source !== frame.contentWindow || !('fixtureIdentity' in (event.data || {}))) return;
19新增: removeEventListener('message', received); frame.remove(); resolve(event.data.fixtureIdentity);
20新增: };
21新增: addEventListener('message', received);
22新增: frame.src = ${JSON.stringify(origin.replace("localhost", "127.0.0.1") + "/frame")};
23新增: document.body.append(frame);
24新增: })`);
25新增: assert.equal(frameIdentity, false, "cross-site frame must retain the same browser identity");
26新增: await fixture.cdp(tab.id, "Runtime.evaluate", {
27新增: expression: `window.open(${JSON.stringify(origin + "/popup")}, '_blank'); true`,
28新增: userGesture: true,
29新增: });
30新增: const popup = await waitFor(async () => (await api("/tabs")).tabs.find(item => item.url === origin + "/popup"), "popup loaded");
31新增: await check(popup.id);
32新增: await api("/close", { id: popup.id });
33新增: await api("/navigate", { id: tab.id, url: origin + "/next" });
34新增: await check(tab.id);
35新增: await api("/close", { id: tab.id });
36新增: }
37新增: await restart();
38新增: await check((await api("/tabs")).active);
39新增: const beforeAudit = (await api("/tabs")).tabs.map(tab => tab.id);
40新增: const audit = await api("/audit", { timezone: "UTC", network: false });
41新增: assert.ok(audit.language && audit.timezone);
42新增: assert.deepEqual((await api("/tabs")).tabs.map(tab => tab.id), beforeAudit, "settings audit must not retain a diagnostic tab");
43新增: console.log("PASS: first page script, normal/private navigation and profile restart retain browser identity without the warning flag");
44新增:} finally { await fixture.close(); }
新增ui/mobile.html+11 −0看文件
@@ -0,0 +1,11 @@
1新增:<!doctype html>
2新增:<html lang="zh-CN">
3新增: <head>
4新增: <meta charset="UTF-8" />
5新增: <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover, interactive-widget=resizes-content" />
6新增: <meta name="color-scheme" content="light dark" />
7新增: <link rel="icon" href="/src/logo.png" />
8新增: <title>Claude Code · Cage</title>
9新增: </head>
10新增: <body><div id="root"></div><script type="module" src="/src/mobile-cli/main.jsx"></script></body>
11新增:</html>
修改ui/package-lock.json+13 −0看文件
@@ -11,6 +11,7 @@
1111 "@xterm/addon-fit": "0.11.0",
1212 "@xterm/xterm": "6.0.0",
1313 "lucide-react": "1.65.0",
14新增: "marked": "18.1.3",
1415 "react": "19.3.1",
1516 "react-dom": "19.3.1"
1617 },
@@ -1402,6 +1403,18 @@
14021403 }
14031404 }
14041405 },
1406新增: "node_modules/marked": {
1407新增: "version": "18.1.3",
1408新增: "resolved": "https://registry.npmjs.org/marked/-/marked-18.1.3.tgz",
1409新增: "integrity": "sha512-9ChMH8EVVgjgID49nsL6IWxWk5c6GtAsq/xw7U1ggkjkU5AGuv68oLTVlFRtvcUYZtpbNyjyvGo3YDu0fGapiw==",
1410新增: "license": "MIT",
1411新增: "bin": {
1412新增: "marked": "bin/marked.js"
1413新增: },
1414新增: "engines": {
1415新增: "node": ">= 20"
1416新增: }
1417新增: },
14051418 "node_modules/minimatch": {
14061419 "version": "10.2.6",
14071420 "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz",
修改ui/package.json+3 −2看文件
@@ -6,14 +6,15 @@
66 "scripts": {
77 "prepare-vnc": "node scripts/prepare-vnc.mjs",
88 "dev": "npm run prepare-vnc && vite --host 127.0.0.1",
9删除: "build": "npm run prepare-vnc && vite build",
10删除: "test": "node --test src/*.test.mjs",
9新增: "build": "npm run prepare-vnc && vite build && node scripts/verify-build.mjs",
10新增: "test": "node --test src/*.test.mjs scripts/verify-build.test.mjs",
1111 "lint": "eslint src"
1212 },
1313 "dependencies": {
1414 "@xterm/addon-fit": "0.11.0",
1515 "@xterm/xterm": "6.0.0",
1616 "lucide-react": "1.65.0",
17新增: "marked": "18.1.3",
1718 "react": "19.3.1",
1819 "react-dom": "19.3.1"
1920 },
新增ui/scripts/account-remember-live-smoke.mjs+106 −0看文件
@@ -0,0 +1,106 @@
1新增:// Production UI + real local controller. Uses only a freshly created profile;
2新增:// never opens or starts a VM, and stores OS trust under its temporary HOME.
3新增:import assert from "node:assert/strict";
4新增:import { randomBytes } from "node:crypto";
5新增:import fs from "node:fs/promises";
6新增:import os from "node:os";
7新增:import path from "node:path";
8新增:import { execFile } from "node:child_process";
9新增:import { promisify } from "node:util";
10新增:import { createRequire } from "node:module";
11新增:import { fileURLToPath } from "node:url";
12新增:
13新增:const cage = process.argv[2];
14新增:assert.ok(path.isAbsolute(cage || ""), "Supply an absolute Cage helper path");
15新增:const run = promisify(execFile);
16新增:const root = await fs.mkdtemp(path.join(os.tmpdir(), "cage-remember-live-"));
17新增:const env = { ...process.env, HOME: root, LOCALAPPDATA: root, CLAUDE_CAGE_CONFIG: path.join(root, "profile", "config.json") };
18新增:const output = new URL("../../docs/test-reports/2026-11-08-remember-device/", import.meta.url);
19新增:await fs.mkdir(output, { recursive: true });
20新增:const require = createRequire(import.meta.url);
21新增:const { chromium, webkit } = require(process.env.CAGE_PLAYWRIGHT_MODULE || "playwright");
22新增:const engine = process.env.CAGE_TEST_BROWSER === "webkit" ? webkit : chromium;
23新增:const browser = await engine.launch({ headless: true });
24新增:let context, page;
25新增:const errors = [];
26新增:const command = async (...args) => JSON.parse((await run(cage, args, { env, timeout: 60000 })).stdout);
27新增:const account = () => page.evaluate(async () => {
28新增: const context = await (await fetch("/api/client/context")).json();
29新增: return (await fetch("/api/account", { headers: { "X-Cage-Connection": context.connection_id } })).json();
30新增:});
31新增:const menu = () => page.getByRole("button", { name: /^账户菜单,/ });
32新增:const remember = () => page.getByRole("checkbox", { name: /^记住我/ });
33新增:const password = randomBytes(24).toString("base64url");
34新增:const restart = async () => {
35新增: await context?.close();
36新增: await command("prepare-update", "--json");
37新增: const entry = await command("desktop", "--json");
38新增: context = await browser.newContext();
39新增: page = await context.newPage();
40新增: page.on("pageerror", e => errors.push(e.message));
41新增: await page.goto(entry.url);
42新增:};
43新增:const unlock = async (enabled) => {
44新增: await remember().setChecked(enabled);
45新增: await page.getByLabel("账户密码", { exact: true }).fill(password);
46新增: const response = page.waitForResponse(r => r.url().endsWith("/api/client/trusted-login"));
47新增: await page.getByRole("button", { name: "解锁 Cage", exact: true }).click();
48新增: assert.equal((await response).status(), 200);
49新增: await menu().waitFor();
50新增:};
51新增:try {
52新增: await restart();
53新增: await page.getByRole("button", { name: "使用用户名和密码", exact: true }).click();
54新增: await remember().waitFor();
55新增: assert.equal(await remember().isChecked(), true);
56新增: await remember().uncheck();
57新增: await page.getByLabel("用户名", { exact: true }).fill("Remember Live QA");
58新增: await page.getByLabel("设置密码", { exact: true }).fill(password);
59新增: await page.getByLabel("确认密码", { exact: true }).fill(password);
60新增: const created = page.waitForResponse(r => r.url().endsWith("/api/client/trusted-login"));
61新增: await page.getByRole("button", { name: "创建本地账户", exact: true }).click();
62新增: assert.equal((await created).status(), 200);
63新增: await menu().waitFor();
64新增: assert.equal(Boolean((await account()).trusted_login), false);
65新增:
66新增: await restart();
67新增: await remember().waitFor();
68新增: assert.equal(await remember().isChecked(), false);
69新增: await unlock(true);
70新增: assert.equal((await account()).trusted_login, true);
71新增: const record = JSON.parse(await fs.readFile(path.join(root, "profile", "account.json"), "utf8"));
72新增: assert.equal(record.devices?.automatic, undefined);
73新增: assert.equal(record.trusted_unlock.sealed_key.length > 0, true);
74新增:
75新增: await restart();
76新增: await menu().waitFor();
77新增: assert.equal((await account()).unlocked, true);
78新增: await menu().click();
79新增: await page.getByRole("menuitem", { name: /锁定 Cage/ }).click();
80新增: await page.getByRole("region", { name: "解锁 Cage", exact: true }).waitFor();
81新增: await restart();
82新增: await remember().waitFor();
83新增: assert.equal((await account()).unlocked, false);
84新增: assert.equal((await account()).require_authentication, true);
85新增: await page.screenshot({ path: fileURLToPath(new URL(`live-${engine === webkit ? "webkit" : "chromium"}-locked.png`, output)) });
86新增: await unlock(false);
87新增: assert.equal(Boolean((await account()).trusted_login), false);
88新增: await restart();
89新增: await remember().waitFor();
90新增: assert.equal(await remember().isChecked(), false);
91新增: assert.equal((await account()).unlocked, false);
92新增: await unlock(true);
93新增: await menu().click();
94新增: await page.getByRole("menuitem", { name: "退出账户", exact: true }).click();
95新增: await page.getByRole("dialog").getByRole("button", { name: "停止环境并退出账户", exact: true }).click();
96新增: await page.getByRole("region", { name: "解锁 Cage", exact: true }).waitFor();
97新增: assert.equal(Boolean((await account()).trusted_login), false);
98新增: const final = JSON.parse(await fs.readFile(path.join(root, "profile", "account.json"), "utf8"));
99新增: assert.equal(final.sealed_key, record.sealed_key, "workspace password-wrapped key changed");
100新增: assert.deepEqual(errors, []);
101新增: console.log("PASS: real production UI/controller, isolated OS trust, create opt-out, password opt-in, controller restart, remembered login, persistent manual lock, opt-out restart, logout revocation and unchanged workspace key");
102新增:} finally {
103新增: await browser.close();
104新增: await command("prepare-update", "--json");
105新增: await fs.rm(root, { recursive: true, force: true });
106新增:}
新增ui/scripts/account-remember-smoke.mjs+159 −0看文件
@@ -0,0 +1,159 @@
1新增:import assert from "node:assert/strict";
2新增:import fs from "node:fs/promises";
3新增:import { fileURLToPath } from "node:url";
4新增:import { createWorkbench } from "./workbench-fixture.mjs";
5新增:
6新增:const output = new URL("../../docs/test-reports/2026-11-08-remember-device/", import.meta.url);
7新增:await fs.mkdir(output, { recursive: true });
8新增:
9新增:for (const platform of ["windows", "darwin", "linux"]) {
10新增: let fixture, failTrust = false;
11新增: const actions = [];
12新增: const clientContext = { mode: "local", desktop_gateway: true, connection_id: "local", client_platform: platform, server_platform: platform, connection: { state: "connected" } };
13新增: fixture = await createWorkbench({
14新增: clientContext,
15新增: // Automatic trust must work without the macOS-only Keychain bridge.
16新增: nativeRequest: async ({ action }) => action === "accountDevice" ? { supported: false } : null,
17新增: clientRequest: async (route, path, body) => {
18新增: if (path === "/client/context") return route.fulfill({ json: clientContext });
19新增: if (path !== "/client/trusted-login") return route.fulfill({ json: {} });
20新增: const a = fixture.state.account;
21新增: actions.push(body.action);
22新增: if (failTrust) return route.fulfill({ status: 409, contentType: "text/plain; charset=utf-8", body: "测试:无法保存本机信任凭据" });
23新增: if (body.action === "enable") {
24新增: assert.equal(body.password, fixture.state.accountPassword);
25新增: a.trusted_login = true;
26新增: delete (a.devices ||= {}).automatic;
27新增: } else if (body.action === "disable") {
28新增: a.trusted_login = false;
29新增: delete (a.devices ||= {}).automatic;
30新增: } else if (body.action === "resume") {
31新增: assert.equal(a.require_authentication, false, "automatic login bypassed manual lock");
32新增: assert.equal(a.trusted_login, true);
33新增: a.unlocked = true;
34新增: } else throw Error(`Unexpected trust action: ${body.action}`);
35新增: return route.fulfill({ json: { ok: true } });
36新增: },
37新增: });
38新增: const { browser, page, state, errors } = fixture;
39新增: const workbenchURL = page.url();
40新增: const reopenLocked = async () => {
41新增: await page.goto("about:blank");
42新增: state.account.unlocked = false;
43新增: await page.goto(workbenchURL);
44新增: };
45新增: const menu = () => page.getByRole("button", { name: /^账户菜单,/ });
46新增: const remember = () => page.getByRole("checkbox", { name: /^记住我/ });
47新增: const trustReply = () => page.waitForResponse(response => response.url().endsWith("/api/client/trusted-login"));
48新增: const login = async (password = "fixture-password") => {
49新增: await page.getByLabel("账户密码", { exact: true }).fill(password);
50新增: const saved = password === "fixture-password" ? trustReply() : null;
51新增: await page.getByRole("button", { name: "解锁 Cage", exact: true }).click();
52新增: if (saved) await (await saved).finished();
53新增: };
54新增: const settings = async () => {
55新增: await menu().click();
56新增: await page.getByRole("menuitem", { name: "设置", exact: true }).click();
57新增: };
58新增: try {
59新增: Object.assign(state.account, { unlocked: false, require_authentication: false });
60新增: await page.reload();
61新增: await remember().waitFor();
62新增: assert.equal(await remember().isChecked(), false, "existing account was opted in without consent");
63新增: await remember().check();
64新增: await login("incorrect-password");
65新增: await page.getByRole("alert").filter({ hasText: "密码不正确" }).waitFor();
66新增: assert.deepEqual(actions, []);
67新增: await page.screenshot({ path: fileURLToPath(new URL(`${platform}-login.png`, output)) });
68新增: await login();
69新增: assert.equal(state.account.trusted_login, true);
70新增: await menu().waitFor();
71新增: await reopenLocked();
72新增: await menu().waitFor();
73新增: assert.equal(actions.filter(a => a === "resume").length, 1);
74新增:
75新增: await menu().click();
76新增: await page.getByRole("menuitem", { name: /锁定 Cage/ }).click();
77新增: await page.getByRole("region", { name: "解锁 Cage", exact: true }).waitFor();
78新增: await page.reload();
79新增: await remember().waitFor();
80新增: assert.equal(await remember().isChecked(), true);
81新增: assert.equal(actions.filter(a => a === "resume").length, 1);
82新增: await remember().uncheck();
83新增: assert.equal(await remember().isChecked(), false);
84新增: await login();
85新增: assert.equal(state.account.trusted_login, false);
86新增: await reopenLocked();
87新增: await remember().waitFor();
88新增: assert.equal(await remember().isChecked(), false);
89新增: assert.equal(actions.filter(a => a === "resume").length, 1);
90新增: await login();
91新增: await settings();
92新增: await page.getByLabel("验证账户密码", { exact: true }).fill("fixture-password");
93新增: await page.getByRole("button", { name: "信任此电脑", exact: true }).click();
94新增: await page.getByRole("button", { name: "关闭记住我", exact: true }).waitFor();
95新增: await page.screenshot({ path: fileURLToPath(new URL(`${platform}-settings.png`, output)) });
96新增: await page.getByRole("button", { name: "关闭记住我", exact: true }).click();
97新增: await page.getByLabel("验证账户密码", { exact: true }).waitFor();
98新增:
99新增: // Existing macOS grants share the same opt-out control.
100新增: state.account.devices = { automatic: "legacy-keychain", biometric: "touch-id" };
101新增: await page.reload();
102新增: await settings();
103新增: await page.getByRole("button", { name: "关闭记住我", exact: true }).click();
104新增: await page.getByLabel("验证账户密码", { exact: true }).waitFor();
105新增: assert.deepEqual(state.account.devices, { biometric: "touch-id" });
106新增:
107新增: // A trust-storage failure must not undo a successful password login.
108新增: await reopenLocked();
109新增: await remember().check();
110新增: failTrust = true;
111新增: await login();
112新增: await menu().waitFor();
113新增: await settings();
114新增: await page.getByText(/已登录,记住我未能开启/).waitFor();
115新增: assert.equal(Boolean(state.account.trusted_login), false);
116新增: failTrust = false;
117新增:
118新增: Object.assign(state.account, { exists: false, unlocked: false, username: "", devices: {}, require_authentication: false });
119新增: await page.reload();
120新增: await page.getByRole("button", { name: "使用用户名和密码", exact: true }).click();
121新增: await remember().waitFor();
122新增: assert.equal(await remember().isChecked(), true);
123新增: await page.getByLabel("用户名", { exact: true }).fill("测试工作区");
124新增: await page.getByLabel("设置密码", { exact: true }).fill("fixture-password");
125新增: await page.getByLabel("确认密码", { exact: true }).fill("fixture-password");
126新增: const createdTrust = trustReply();
127新增: await page.getByRole("button", { name: "创建本地账户", exact: true }).click();
128新增: await (await createdTrust).finished();
129新增: assert.equal(state.account.trusted_login, true);
130新增: await menu().click();
131新增: await page.getByRole("menuitem", { name: "退出账户", exact: true }).click();
132新增: await page.getByRole("dialog").getByRole("button", { name: "停止环境并退出账户", exact: true }).click();
133新增: // The real backend revokes the grant after a successful environment stop.
134新增: state.account.trusted_login = false;
135新增: await page.reload();
136新增: await remember().waitFor();
137新增: assert.equal(await remember().isChecked(), false);
138新增: assert.deepEqual(errors, []);
139新增: console.log(`PASS ${platform}: create, password login, remember, reopen, manual lock, opt-out, legacy migration, settings, storage failure and logout`);
140新增: } catch (error) {
141新增: await page.screenshot({ path: fileURLToPath(new URL(`${platform}-failure.png`, output)) });
142新增: console.error(await page.locator("body").innerText());
143新增: console.error({ actions, account: state.account });
144新增: throw error;
145新增: } finally { await browser.close(); }
146新增:}
147新增:
148新增:const remote = await createWorkbench({
149新增: clientContext: { mode: "remote", desktop_gateway: true, connection_id: "remote", client_platform: "windows", server_platform: "linux", connection: { state: "connected" } },
150新增: nativeRequest: async ({ action }) => action === "accountDevice" ? { supported: false } : null,
151新增:});
152新增:try {
153新增: remote.state.account.unlocked = false;
154新增: await remote.page.reload();
155新增: await remote.page.getByLabel("账户密码", { exact: true }).waitFor();
156新增: assert.equal(await remote.page.getByRole("checkbox", { name: /^记住我/ }).count(), 0);
157新增: assert.deepEqual(remote.errors, []);
158新增: console.log("PASS remote: local computer trust is unavailable for a remote host");
159新增:} finally { await remote.browser.close(); }
新增ui/scripts/account-scheduling-smoke.mjs+88 −0看文件
@@ -0,0 +1,88 @@
1新增:import assert from "node:assert/strict";
2新增:import {mkdir} from "node:fs/promises";
3新增:import {fileURLToPath} from "node:url";
4新增:import {createWorkbench} from "./workbench-fixture.mjs";
5新增:
6新增:const out=new URL("../../docs/test-reports/2026-11-08-account-scheduling/",import.meta.url);
7新增:await mkdir(out,{recursive:true});
8新增:const scheduling={mode:"balanced",switch_policy:"ask"};
9新增:let profiles=[{id:"a",label:"账号 A",email:"[email protected]",status:"ready",enabled:true},{id:"b",label:"账号 B",email:"[email protected]",status:"ready",enabled:true}];
10新增:const sid="12345678-1234-4321-aaaa-123456789abc";
11新增:const session={id:sid,workspace:"/Users/shihao/.claude-cage-workspace",title:"调度验证",terminal_available:true,desktop_terminal_id:"first",can_send:true,revision:1,account_id:"a",account_label:"账号 A",switch_policy:"ask",turns:[]};
12新增:let switchCalls=[];
13新增:const account=(route,body)=>{
14新增: if(body.action==="policy")session.switch_policy=body.policy;
15新增: if(body.action==="switch"){
16新增: switchCalls.push(body);session.account_id="b";session.account_label="账号 B";session.desktop_terminal_id="second";
17新增: session.account_switch={id:body.request_id,phase:"completed",target_label:"账号 B"};
18新增: }
19新增: return route.fulfill({json:{session,source_id:"12345678-1234-4321-aaaa-123456789abd",switch_policy:session.switch_policy,supported:true,candidates:[{id:"b",label:"账号 B"}]}});
20新增:};
21新增:const fixture=await createWorkbench();
22新增:const {browser,page,state,errors}=fixture;
23新增:try{
24新增: await page.route("**/api/claude-accounts*",async route=>{
25新增: const body=route.request().postDataJSON();
26新增: if(body?.action==="scheduling"){
27新增: Object.assign(scheduling,body.scheduling);
28新增: if(body.order)profiles=body.order.map(id=>profiles.find(a=>a.id===id));
29新增: }
30新增: if(body?.action==="update")Object.assign(profiles.find(a=>a.id===body.id),body);
31新增: return route.fulfill({json:{accounts:profiles,scheduling,detection_status:"offline"}});
32新增: });
33新增: await page.getByRole("button",{name:"设置",exact:true}).click();
34新增: await page.getByRole("button",{name:"Claude 账号",exact:true}).click();
35新增: await page.getByText("调度设置 · 均衡分配",{exact:true}).click();
36新增: const select=page.getByRole("combobox",{name:"新会话分配",exact:true});
37新增: const policy=page.getByRole("combobox",{name:"新会话切换授权",exact:true});
38新增: const before=(await policy.boundingBox()).y;
39新增: await select.click();
40新增: assert.ok((await policy.boundingBox()).y>before+20,"options must occupy layout space");
41新增: await select.press("End");await select.press("Enter");
42新增: await page.getByRole("region",{name:"账号优先顺序"}).count();
43新增: assert.equal(scheduling.mode,"sequential");
44新增: await page.getByRole("button",{name:"提高 账号 B 的优先级"}).click();
45新增: await page.waitForFunction(()=>document.querySelector('.claude-account-order')?.textContent.startsWith('1. 账号 B'));
46新增: assert.equal(profiles[0].id,"b");
47新增: await policy.click();await page.getByRole("option",{name:"额度耗尽后自动接续",exact:true}).click();
48新增: assert.equal(scheduling.switch_policy,"allow");
49新增: await page.getByRole("textbox",{name:"账号 A 的接续分组"}).fill("本人账号");
50新增: await page.getByRole("article",{name:"账号 A",exact:true}).getByRole("button",{name:"保存分组"}).click();
51新增: assert.equal(profiles.find(a=>a.id==="a").handoff_group,"本人账号");
52新增: await page.screenshot({path:fileURLToPath(new URL("scheduling-desktop.png",out))});
53新增: await page.reload();
54新增: await page.getByRole("button",{name:"设置",exact:true}).click();await page.getByRole("button",{name:"Claude 账号",exact:true}).click();
55新增: await page.getByText("调度设置 · 顺序优先",{exact:true}).waitFor();
56新增:
57新增: const phoneContext=await browser.newContext({viewport:{width:390,height:844},isMobile:true,hasTouch:true,userAgent:"CageMobile/1"});
58新增: const phone=await phoneContext.newPage();
59新增: const phoneErrors=[];phone.on("pageerror",e=>phoneErrors.push(e.message));
60新增: await phone.route("**/api/**",async route=>{
61新增: const path=new URL(route.request().url()).pathname;const body=route.request().postDataJSON();
62新增: if(path.endsWith("/account"))return account(route,body);
63新增: if(path.endsWith("/projects"))return route.fulfill({json:{host:"测试电脑",ready:true,shared_sessions:true,projects:[{path:session.workspace,name:"默认工作区"}]}});
64新增: if(path.endsWith("/sessions"))return route.fulfill({json:{sessions:[session]}});
65新增: return route.fulfill({json:session});
66新增: });
67新增: await phone.goto((process.env.CAGE_UI_URL || "http://127.0.0.1:5198")+"/mobile.html");
68新增: const drawer=phone.getByRole("dialog",{name:"工作区侧栏"});
69新增: await drawer.waitFor();
70新增: const folder=drawer.getByRole("button",{name:"项目 默认工作区",exact:true});
71新增: if(await folder.getAttribute("aria-expanded")==="false")await folder.click();
72新增: await phone.getByRole("button",{name:"调度验证",exact:true}).click();
73新增: await phone.getByRole("button",{name:"账号 A · 会话绑定",exact:true}).click();
74新增: const switchButton=phone.getByRole("button",{name:"切换并恢复历史",exact:true});
75新增: assert.equal(await switchButton.isDisabled(),true);
76新增: await phone.getByRole("combobox",{name:"此会话切换授权"}).click();
77新增: await phone.getByRole("option",{name:"始终等待原账号",exact:true}).click();
78新增: assert.equal(session.switch_policy,"wait");
79新增: await phone.getByRole("checkbox",{name:"允许将此会话历史交给所选账号"}).check();
80新增: await switchButton.click();
81新增: await phone.getByRole("button",{name:"账号 B · 会话绑定",exact:true}).waitFor();
82新增: assert.equal(switchCalls.length,1);assert.equal(switchCalls[0].confirm,true);assert.equal(switchCalls[0].target,"b");
83新增: assert.equal(switchCalls[0].continue,false,"switching must not imply task continuation");
84新增: assert.ok(await phone.evaluate(()=>document.documentElement.scrollWidth<=innerWidth));
85新增: await phone.screenshot({path:fileURLToPath(new URL("session-account-phone.png",out))});
86新增: assert.deepEqual(errors,[]);assert.deepEqual(phoneErrors,[]);
87新增: console.log("Scheduling: inline mouse/keyboard selection, ordering, group persistence, session authorization and explicit mobile switch passed.");
88新增:}finally{await browser.close();}
新增ui/scripts/app-update-retry-smoke.mjs+43 −0看文件
@@ -0,0 +1,43 @@
1新增:import assert from "node:assert/strict";
2新增:import { createWorkbench } from "./workbench-fixture.mjs";
3新增:
4新增:const epoch = new Date("2026-11-07T14:00:00Z");
5新增:for (const platform of ["darwin", "windows", "linux"]) {
6新增: const calls = [];
7新增: let update = platform === "linux" ? { phase: "manual", message: "使用系统包更新" } : {
8新增: phase: "failed", message: "更新源请求受限,请稍后重试", currentVersion: "0.1.0", latestVersion: "0.2.0",
9新增: retryable: true, retryAt: new Date(+epoch + 60*60*1000).toISOString(),
10新增: };
11新增: const fixture = await createWorkbench({
12新增: clientContext: { mode: "local", connection_id: "local", client_platform: platform, server_platform: platform, connection: { state: "disconnected" } },
13新增: beforeNavigate: page => page.clock.install({ time: epoch }),
14新增: nativeRequest: async body => {
15新增: if (body.action !== "appUpdate") return null;
16新增: calls.push(body.operation);
17新增: if (body.operation === "check") update = { phase: "current", currentVersion: "0.1.0", retryAt: "" };
18新增: return update;
19新增: },
20新增: });
21新增: const { page, browser, errors } = fixture;
22新增: try {
23新增: await page.waitForFunction(() => document.querySelector(".app-update-button") || !document.querySelector(".loading-screen"));
24新增: if (platform === "linux") {
25新增: await page.clock.fastForward(7*60*60*1000);
26新增: assert.deepEqual(calls, ["status"], "Linux must keep system package updates");
27新增: } else {
28新增: await page.getByRole("button", { name: "等待重试更新", exact: true }).waitFor();
29新增: assert.ok(await page.getByRole("button", { name: "等待重试更新", exact: true }).isDisabled());
30新增: assert.deepEqual(calls, ["status"], "startup must respect the native retry deadline");
31新增: await page.clock.fastForward(6*60*1000);
32新增: await page.evaluate(() => window.dispatchEvent(new Event("focus")));
33新增: assert.deepEqual(calls, ["status"], "the five-minute timer and focus must not bypass cooldown");
34新增: await page.clock.fastForward(53*60*1000);
35新增: assert.deepEqual(calls, ["status"], "must not retry before the server deadline");
36新增: await page.clock.fastForward(2*60*1000);
37新增: await page.waitForFunction(() => !document.querySelector(".app-update-button"));
38新增: assert.deepEqual(calls, ["status", "check"], "retry once when the server deadline passes");
39新增: }
40新增: assert.deepEqual(errors, []);
41新增: console.log(`PASS: ${platform} update cooldown`);
42新增: } finally { await browser.close(); }
43新增:}
新增ui/scripts/archive-bulk-smoke.mjs+154 −0看文件
@@ -0,0 +1,154 @@
1新增:import assert from "node:assert/strict";
2新增:import { mkdir } from "node:fs/promises";
3新增:import { createWorkbench } from "./workbench-fixture.mjs";
4新增:
5新增:const base = process.env.CAGE_UI_URL || "http://127.0.0.1:5209";
6新增:const engine = process.env.CAGE_TEST_BROWSER || "chromium";
7新增:const output = process.env.CAGE_TEST_CAPTURE || "../output/archive-bulk-20261108";
8新增:const alpha = "/fixture/alpha", beta = "/fixture/beta";
9新增:const seed = [
10新增: {id:"a1",workspace:alpha,title:"项目方案",pinned:true},
11新增: {id:"a2",workspace:alpha,title:"接口检查"},
12新增: {id:"b1",workspace:beta,title:"移动端检查"},
13新增: {id:"b2",workspace:beta,title:"待完成删除",deleting:true},
14新增:].map(s => ({...s,archived:true,updated_at:"2026-11-08T00:00:00Z"}));
15新增:let sessions = structuredClone(seed), failID = "", holdID = "", release;
16新增:const operations = [];
17新增:const handle = async (route, path, body) => {
18新增: if (path === "/cli/sessions") return route.fulfill({json:{sessions:sessions.filter(s => s.archived === (new URL(route.request().url()).searchParams.get("archived") === "true"))}});
19新增: const [, id, operation] = path.match(/\/sessions\/([^/]+)\/(restore|purge)$/) || [];
20新增: if (!id) return route.fulfill({json:{}});
21新增: operations.push({id,operation});
22新增: if (operation === "purge") assert.equal(body.confirm,true);
23新增: if (id === holdID) await new Promise(resolve => { release = resolve; });
24新增: if (id === failID) return route.fulfill({status:503,contentType:"text/plain; charset=utf-8",body:"测试连接中断"});
25新增: const session = sessions.find(s => s.id === id);
26新增: if (operation === "restore") session.archived = false;
27新增: else sessions = sessions.filter(s => s.id !== id);
28新增: return route.fulfill({json:{ok:true}});
29新增:};
30新增:const desktop = await createWorkbench({url:base,cliRequest:handle});
31新增:const {page,browser,state,errors} = desktop;
32新增:const checkbox = (scope,name) => scope.getByRole("checkbox",{name,exact:true});
33新增:const allName = "全选当前筛选结果";
34新增:const projectName = path => `全选项目 ${path} 的当前筛选结果`;
35新增:try {
36新增: state.status.ready = state.status.vm_running = true;
37新增: await page.getByRole("button",{name:"设置",exact:true}).click();
38新增: await page.getByRole("navigation",{name:"设置分组"}).getByRole("button",{name:"已归档会话",exact:true}).click();
39新增: const panel = page.getByRole("region",{name:"已归档会话",exact:true});
40新增: await checkbox(panel,allName).waitFor();
41新增: const inputBox = await checkbox(panel,allName).boundingBox();
42新增: const labelBox = await panel.locator(".archive-selection").first().locator("span").boundingBox();
43新增: assert.ok(labelBox.x > inputBox.x && Math.abs(labelBox.y + labelBox.height / 2 - inputBox.y - inputBox.height / 2) < 2,"select-all label did not align with its checkbox");
44新增: // Keyboard selection and mixed states must match the visible project and total.
45新增: await checkbox(panel,"选择会话 项目方案").focus(); await page.keyboard.press("Space");
46新增: assert.equal(await checkbox(panel,projectName(alpha)).evaluate(el => el.indeterminate),true);
47新增: assert.equal(await checkbox(panel,allName).evaluate(el => el.indeterminate),true);
48新增: await checkbox(panel,projectName(alpha)).check();
49新增: assert.equal(await checkbox(panel,"选择会话 接口检查").isChecked(),true);
50新增: assert.equal(await checkbox(panel,"选择会话 移动端检查").isChecked(),false);
51新增: await checkbox(panel,allName).check();
52新增: assert.equal(await panel.getByRole("button",{name:"批量取消归档",exact:true}).isDisabled(),true);
53新增: await panel.getByRole("button",{name:"清空选择",exact:true}).click();
54新增: assert.equal(await checkbox(panel,allName).isChecked(),false);
55新增: const search = panel.getByRole("searchbox");
56新增: await checkbox(panel,allName).check();
57新增: await search.fill("接口");
58新增: assert.equal(await checkbox(panel,allName).isChecked(),false,"filter kept hidden selections");
59新增: await checkbox(panel,allName).check();
60新增: await panel.getByRole("button",{name:"批量取消归档",exact:true}).click();
61新增: await panel.getByRole("status").filter({hasText:"已取消归档 1 个会话"}).waitFor();
62新增: assert.deepEqual(operations.splice(0),[{id:"a2",operation:"restore"}],"filtered select all affected hidden sessions");
63新增: await search.fill("");
64新增: // Changing project filters also clears selection, and the dropdown pushes content down.
65新增: await checkbox(panel,allName).check();
66新增: const filter = panel.getByRole("combobox",{name:"项目筛选"});
67新增: const toolbar = panel.getByRole("group",{name:"批量处理会话"});
68新增: const before = await toolbar.boundingBox();
69新增: await filter.click();
70新增: const list = await panel.getByRole("listbox",{name:"项目筛选选项"}).boundingBox();
71新增: assert.ok((await toolbar.boundingBox()).y >= list.y + list.height);
72新增: await filter.press("Escape");
73新增: assert.ok(Math.abs((await toolbar.boundingBox()).y-before.y)<2);
74新增: await filter.press("End"); await filter.press("Enter");
75新增: assert.equal(await checkbox(panel,allName).isChecked(),false);
76新增: await filter.press("Home"); await filter.press("Enter");
77新增: // Partial restore keeps only the failed selection and allows retry.
78新增: sessions = structuredClone(seed);
79新增: // A polling refresh brings the externally restored session back into the list.
80新增: await panel.getByRole("heading",{name:"接口检查",exact:true}).waitFor();
81新增: failID = "a2"; holdID = "a1";
82新增: await checkbox(panel,projectName(alpha)).check();
83新增: await panel.getByRole("button",{name:"批量取消归档",exact:true}).click();
84新增: await panel.getByRole("status").filter({hasText:"正在处理"}).waitFor();
85新增: assert.equal(await search.isDisabled(),true);
86新增: assert.equal(await checkbox(panel,allName).isDisabled(),true);
87新增: assert.equal(await panel.getByRole("button",{name:"批量删除",exact:true}).isDisabled(),true);
88新增: release(); holdID = "";
89新增: await panel.getByRole("alert").filter({hasText:"1 个会话处理失败"}).waitFor();
90新增: assert.equal(await panel.getByRole("heading",{name:"项目方案",exact:true}).count(),0);
91新增: assert.equal(await checkbox(panel,"选择会话 接口检查").isChecked(),true);
92新增: assert.equal(await checkbox(panel,"选择会话 移动端检查").isChecked(),false);
93新增: failID = "";
94新增: await panel.getByRole("button",{name:"批量取消归档",exact:true}).click();
95新增: await panel.getByRole("heading",{name:"接口检查",exact:true}).waitFor({state:"hidden"});
96新增: // Batch purge requires confirmation. Partial purge retains failures for a fresh confirmation.
97新增: await checkbox(panel,projectName(beta)).check();
98新增: await panel.getByRole("button",{name:"批量删除",exact:true}).click();
99新增: let confirm = panel.getByRole("group",{name:"确认批量永久删除会话",exact:true});
100新增: await confirm.getByRole("button",{name:"取消",exact:true}).click();
101新增: assert.equal(operations.filter(o => o.operation === "purge").length,0);
102新增: failID = "b2";
103新增: await panel.getByRole("button",{name:"批量删除",exact:true}).click();
104新增: await confirm.getByRole("button",{name:"永久删除所选会话",exact:true}).click();
105新增: await panel.getByRole("alert").filter({hasText:"待完成删除"}).waitFor();
106新增: assert.equal(await checkbox(panel,"选择会话 待完成删除").isChecked(),true);
107新增: assert.equal(await panel.getByRole("heading",{name:"移动端检查",exact:true}).count(),0);
108新增: failID = "";
109新增: await panel.getByRole("button",{name:"批量删除",exact:true}).click();
110新增: await confirm.getByText(/所选的 1 个会话/).waitFor();
111新增: await confirm.getByRole("button",{name:"永久删除所选会话",exact:true}).click();
112新增: await panel.getByText("暂无已归档会话。",{exact:true}).waitFor();
113新增: assert.deepEqual(operations.filter(o => o.operation === "purge").map(o => o.id),["b1","b2","b2"]);
114新增: // Phone uses the same component and host API, including offline restore and deletion restrictions.
115新增: sessions = structuredClone(seed);
116新增: const context = await browser.newContext({viewport:{width:390,height:844},isMobile:true,hasTouch:true,userAgent:"CageMobile/1"});
117新增: const phone = await context.newPage();
118新增: const phoneErrors = []; phone.on("pageerror",e => phoneErrors.push(e.message));
119新增: let ready = false;
120新增: await phone.route("**/api/**", async route => {
121新增: const path = new URL(route.request().url()).pathname.replace("/api/mobile/cli","/cli");
122新增: if (path.endsWith("/projects")) return route.fulfill({json:{host:"隔离测试主机",ready,shared_sessions:true,projects:[{path:alpha,name:"alpha"},{path:beta,name:"beta"}]}});
123新增: return handle(route,path,route.request().postDataJSON());
124新增: });
125新增: await phone.goto(base+"/mobile.html");
126新增: await phone.getByRole("dialog",{name:"工作区侧栏"}).getByRole("button",{name:"设置",exact:true}).click();
127新增: await phone.getByRole("button",{name:"已归档会话",exact:true}).click();
128新增: await checkbox(phone,projectName(alpha)).check();
129新增: assert.equal(await phone.getByRole("button",{name:"批量删除",exact:true}).isDisabled(),true);
130新增: assert.equal(await phone.getByRole("button",{name:"批量取消归档",exact:true}).isEnabled(),true);
131新增: await phone.getByRole("button",{name:"批量取消归档",exact:true}).click();
132新增: await phone.getByRole("heading",{name:"接口检查",exact:true}).waitFor({state:"hidden"});
133新增: ready = true;
134新增: await phone.getByRole("button",{name:"返回设置",exact:true}).click();
135新增: await phone.getByRole("button",{name:"已归档会话",exact:true}).click();
136新增: await checkbox(phone,allName).check();
137新增: await phone.getByRole("button",{name:"批量删除",exact:true}).click();
138新增: await phone.getByRole("group",{name:"确认批量永久删除会话"}).waitFor();
139新增: await mkdir(output,{recursive:true});
140新增: await phone.screenshot({path:`${output}/${engine}-mobile.png`,fullPage:true});
141新增: assert.equal(await phone.evaluate(() => document.documentElement.scrollWidth <= innerWidth),true,"mobile layout overflowed");
142新增: await phone.getByRole("button",{name:"永久删除所选会话",exact:true}).click();
143新增: await phone.getByText("暂无已归档会话。",{exact:true}).waitFor();
144新增: await phone.reload();
145新增: await phone.getByRole("heading",{name:"已归档会话",exact:true}).waitFor();
146新增: await phone.getByText("暂无已归档会话。",{exact:true}).waitFor();
147新增: assert.equal(sessions.filter(s => s.archived).length,0);
148新增: // Capture the desktop controls with selections for visual review.
149新增: sessions = structuredClone(seed);
150新增: await checkbox(panel,projectName(alpha)).check();
151新增: await page.screenshot({path:`${output}/${engine}-desktop.png`});
152新增: assert.deepEqual(errors,[]); assert.deepEqual(phoneErrors,[]);
153新增: console.log(`${engine}: item/project/all selection, mixed state, keyboard, filter scope, progress/locking, restore/purge partial failure and retry, delete cancellation, mobile/offline/reload passed`);
154新增:} finally { await browser.close(); }
新增ui/scripts/archive-position-smoke.mjs+101 −0看文件
@@ -0,0 +1,101 @@
1新增:import assert from "node:assert/strict";
2新增:import { mkdir, writeFile } from "node:fs/promises";
3新增:import { createWorkbench } from "./workbench-fixture.mjs";
4新增:
5新增:const output = process.env.CAGE_TEST_CAPTURE || "/tmp/cage-archive-position";
6新增:const engine = process.env.CAGE_TEST_BROWSER || "chromium";
7新增:const { page, state, browser, errors } = await createWorkbench({
8新增: url: process.env.CAGE_UI_URL || "http://127.0.0.1:5217",
9新增:});
10新增:const workspace = state.settings.workspace;
11新增:const sessions = Array.from({ length: 18 }, (_, i) => ({
12新增: id: `archive-position-${i}`, workspace, title: i ? `历史会话 ${i}` : "正在处理的会话",
13新增: updated_at: "2026-11-08T08:00:00Z",
14新增:}));
15新增:const evidence = [];
16新增:let failArchive = false;
17新增:let archived = 0;
18新增:const dialog = page.getByRole("dialog", { name: "归档这段会话?", exact: true });
19新增:const actions = title => page.getByRole("group", { name: `${title} 的操作`, exact: true, includeHidden: true });
20新增:const open = async title => {
21新增: const row = page.locator(".sidebar-tab").filter({ has: actions(title) });
22新增: await row.hover();
23新增: const trigger = actions(title).getByRole("button", { name: "归档", exact: true });
24新增: await trigger.click();
25新增: await dialog.waitFor();
26新增: return trigger;
27新增:};
28新增:try {
29新增: await page.route("**/api/cli/sessions", route => route.fulfill({ json: { sessions } }));
30新增: await page.route("**/api/cli/sessions/*/archive", async route => {
31新增: if (failArchive) return route.fulfill({ status: 500, contentType: "text/plain", body: "测试:归档暂时失败" });
32新增: const id = route.request().url().split("/").at(-2);
33新增: sessions.splice(sessions.findIndex(session => session.id === id), 1);
34新增: state.terminals = state.terminals.filter(terminal => terminal.cli_session_id !== id);
35新增: archived++;
36新增: await route.fulfill({ json: { ok: true } });
37新增: });
38新增: state.status.ready = state.status.vm_running = true;
39新增: state.terminals = [{ id: "archive-live", kind: "claude", workspace,
40新增: title: sessions[0].title, cli_session_id: sessions[0].id }];
41新增: await page.getByRole("tab", { name: sessions[0].title, exact: true }).waitFor();
42新增: await page.getByRole("button", { name: sessions.at(-1).title, exact: true }).waitFor();
43新增: await mkdir(output, { recursive: true });
44新增: for (const width of [1280, 820]) {
45新增: await page.setViewportSize({ width, height: 850 });
46新增: const trigger = await open(sessions[0].title);
47新增: const anchor = await trigger.boundingBox();
48新增: const box = await dialog.boundingBox();
49新增: assert.ok(Math.abs(box.y - anchor.y - anchor.height - 6) < 1, "confirmation is not below archive trigger");
50新增: assert.ok(box.width <= 305 && box.x >= 8 && box.x + box.width <= width - 8, "confirmation overflows window");
51新增: assert.ok(Math.abs(box.x + box.width / 2 - anchor.x) < 100, "confirmation is too far from trigger");
52新增: await page.screenshot({ path: `${output}/${engine}-${width}.png` });
53新增: await dialog.getByRole("button", { name: "取消", exact: true }).click();
54新增: await dialog.waitFor({ state: "hidden" });
55新增: assert.equal(archived, 0, "cancel archived a session");
56新增: assert.equal(await trigger.evaluate(node => node === document.activeElement), true, "cancel did not restore trigger focus");
57新增: await trigger.press("Enter");
58新增: await dialog.waitFor();
59新增: await page.keyboard.press("Shift+Tab");
60新增: assert.equal(await dialog.getByRole("button", { name: "归档会话", exact: true }).evaluate(node => node === document.activeElement), true);
61新增: await page.keyboard.press("Tab");
62新增: assert.equal(await dialog.getByRole("button", { name: "关闭面板", exact: true }).evaluate(node => node === document.activeElement), true);
63新增: await page.keyboard.press("Escape");
64新增: await dialog.waitFor({ state: "hidden" });
65新增: assert.equal(await trigger.evaluate(node => node === document.activeElement), true);
66新增: await trigger.press("Enter");
67新增: await dialog.waitFor();
68新增: await page.mouse.click(width - 20, 20);
69新增: await dialog.waitFor({ state: "hidden" });
70新增: assert.equal(archived, 0);
71新增: evidence.push({ width, anchor, box });
72新增: }
73新增: // The last history row is at the bottom of a scrollable sidebar.
74新增: const last = sessions.at(-1).title;
75新增: const bottomTrigger = await open(last);
76新增: const bottomAnchor = await bottomTrigger.boundingBox();
77新增: const bottomBox = await dialog.boundingBox();
78新增: assert.ok(bottomBox.y >= 8 && bottomBox.y + bottomBox.height <= 842, "bottom confirmation is clipped");
79新增: assert.ok(bottomBox.y + bottomBox.height <= bottomAnchor.y, "bottom confirmation did not move above the trigger");
80新增: await page.screenshot({ path: `${output}/${engine}-bottom.png` });
81新增: await page.keyboard.press("Escape");
82新增: await open(sessions[0].title);
83新增: failArchive = true;
84新增: await dialog.getByRole("button", { name: "归档会话", exact: true }).click();
85新增: await page.getByRole("status").filter({ hasText: "归档暂时失败" }).waitFor();
86新增: assert.equal(archived, 0, "failed archive removed a session");
87新增: failArchive = false;
88新增: await open(sessions[0].title);
89新增: await dialog.getByRole("button", { name: "归档会话", exact: true }).press("Enter");
90新增: await actions("正在处理的会话").waitFor({ state: "hidden" });
91新增: assert.equal(archived, 1, "confirm should archive exactly once");
92新增: await open(last);
93新增: await dialog.getByRole("button", { name: "归档会话", exact: true }).click();
94新增: await actions(last).waitFor({ state: "hidden" });
95新增: assert.equal(archived, 2, "history session archive failed");
96新增: assert.deepEqual(errors, []);
97新增: await writeFile(`${output}/${engine}-result.json`, JSON.stringify(evidence, null, 2));
98新增: console.log(`${engine}: archive positioning, viewport edges, focus, keyboard, cancel, outside dismissal, failure/retry and live/history archive passed`);
99新增:} finally {
100新增: await browser.close();
101新增:}
修改ui/scripts/audio-fixture.jsx+2 −1看文件
@@ -1,9 +1,10 @@
11import React, { useState } from "react";
22import { createRoot } from "react-dom/client";
33import { AudioControls, useAudioOutput } from "../src/audio";
4新增:import "../src/style.css";
45function Fixture() {
56 const [enabled, setEnabled] = useState(true);
67 const audio = useAudioOutput(enabled);
7删除: return <><AudioControls audio={audio} /><output>{audio.state}</output><button onClick={() => setEnabled(false)}>停止测试环境</button></>;
8新增: return <div className="app"><output style={{ position: "absolute", top: 0 }}>{audio.state}</output><div style={{ flex: 1 }} /><div className="status-bar"><span className="status-spacer" /><AudioControls audio={audio} /><span>文件与本机同步</span><button onClick={() => setEnabled(false)}>停止测试环境</button></div></div>;
89}
910createRoot(document.getElementById("root")).render(<Fixture />);
修改ui/scripts/audio-installed-smoke.mjs+1 −0看文件
@@ -27,6 +27,7 @@ await page.addInitScript(() => {
2727try {
2828 await page.goto(entry.url);
2929 const volume = page.getByRole("slider", { name: "环境音量" });
30新增: await page.getByRole("button", { name: "打开音量控制" }).click();
3031 await volume.press("End");
3132 await page.waitForFunction(() => window.testAudioGain && window.testAudioContext.state === "running");
3233 await page.evaluate(() => {
修改ui/scripts/audio-smoke.mjs+40 −8看文件
@@ -3,11 +3,12 @@ import { createRequire } from "node:module";
33import { fileURLToPath } from "node:url";
44import { createServer } from "vite";
55const require = createRequire(import.meta.url);
6删除:const { chromium } = require(process.env.CAGE_PLAYWRIGHT_MODULE || "playwright");
6新增:const browserName = process.env.CAGE_TEST_BROWSER || "chromium";
7新增:const browserEngine = require(process.env.CAGE_PLAYWRIGHT_MODULE || "playwright")[browserName];
78const vite = await createServer({ root: fileURLToPath(new URL("..", import.meta.url)), configFile: fileURLToPath(new URL("../vite.config.js", import.meta.url)), server: { host: "127.0.0.1", port: 0 } });
89await vite.listen();
910const origin = `http://127.0.0.1:${vite.httpServer.address().port}`;
10删除:const browser = await chromium.launch({ headless: true, args: ["--autoplay-policy=user-gesture-required"] });
11新增:const browser = await browserEngine.launch({ headless: true, ...(browserName === "chromium" ? { args: ["--autoplay-policy=user-gesture-required"] } : {}) });
1112const page = await browser.newPage();
1213let connected = 0, open = 0;
1314const timers = new Set(), errors = [];
@@ -21,10 +22,14 @@ await page.addInitScript(() => {
2122});
2223await page.route("**/audio-test", async route => route.fulfill({ contentType: "text/html", body: await vite.transformIndexHtml("/audio-test", '<div id="root"></div><script type="module" src="/scripts/audio-fixture.jsx"></script>') }));
2324const format = { format: "s16le", sample_rate: 48000, channels: 2 };
24删除:await page.route("**/api/audio", route => route.fulfill({ json: format }));
25新增:let permissionMissing = false;
26新增:const permissionMessage = "请在虚拟 Mac 的系统设置中允许 Cage Guest Window 录制屏幕和系统声音";
27新增:await page.route("**/api/audio", route => route.fulfill(permissionMissing
28新增: ? { status: 409, contentType: "text/plain", body: permissionMessage }
29新增: : { json: format }));
2530const packet = Buffer.alloc(3840);
2631for (let i = 0; i < 960; i++) for (let channel = 0; channel < 2; channel++) packet.writeInt16LE(Math.round(Math.sin(i * 2 * Math.PI * 1000 / 48000) * 10000), i * 4 + channel * 2);
27删除:await page.routeWebSocket("**/api/audio", socket => {
32新增:await page.routeWebSocket("**/api/audio**", socket => {
2833 connected++; open++;
2934 socket.send(JSON.stringify(format));
3035 const timer = setInterval(() => socket.send(packet), 20);
@@ -44,7 +49,26 @@ const rms = () => page.evaluate(() => {
4449try {
4550 await page.goto(origin + "/audio-test");
4651 await page.waitForFunction(() => !!window.testAudioContext);
47删除: await page.locator('input[aria-label="环境音量"]').click();
52新增: const slider = page.getByRole("slider", { name: "环境音量" });
53新增: const speaker = page.locator(".audio-controls button");
54新增: assert.equal(await slider.count(), 0);
55新增: await speaker.click();
56新增: assert.equal(await speaker.getAttribute("aria-expanded"), "true");
57新增: const buttonBox = await speaker.boundingBox();
58新增: const sliderBox = await slider.boundingBox();
59新增: assert.ok(sliderBox.height > sliderBox.width && sliderBox.y + sliderBox.height < buttonBox.y, "slider opens vertically above the speaker");
60新增: await page.mouse.move(sliderBox.x + sliderBox.width / 2, sliderBox.y + sliderBox.height / 2, { steps: 10 });
61新增: assert.equal(await slider.count(), 1, "moving from the speaker into the slider keeps it open");
62新增: await page.mouse.move(10, 10);
63新增: assert.equal(await slider.count(), 0, "moving away closes the slider");
64新增: await speaker.focus();
65新增: await page.keyboard.press("Enter");
66新增: assert.equal(await slider.count(), 1, "keyboard opens the slider");
67新增: assert.equal(await slider.evaluate(element => element === document.activeElement), true);
68新增: await page.keyboard.press("Escape");
69新增: assert.equal(await slider.count(), 0, "Escape closes the slider");
70新增: assert.equal(await speaker.evaluate(element => element === document.activeElement), true);
71新增: await speaker.click();
4872 await page.locator("output").filter({ hasText: "playing" }).waitFor();
4973 await page.evaluate(() => {
5074 window.testAudioAnalyser = window.testAudioContext.createAnalyser();
@@ -63,17 +87,25 @@ try {
6387 assert.ok(half > .09 && half < .13, `half-volume RMS ${half}`);
6488 await page.getByRole("button", { name: "静音", exact: true }).click();
6589 await waitFor(() => open === 0);
66删除: assert.equal(await page.evaluate(() => window.testAudioContext.state), "suspended");
90新增: await page.waitForFunction(() => window.testAudioContext.state === "suspended");
6791 await page.getByRole("button", { name: "取消静音", exact: true }).click();
6892 await waitFor(() => connected === 2 && open === 1);
6993 await page.locator("output").filter({ hasText: "playing" }).waitFor();
94新增: permissionMissing = true;
95新增: await page.getByRole("button", { name: "静音", exact: true }).click();
96新增: await waitFor(() => open === 0);
97新增: await page.getByRole("button", { name: "取消静音", exact: true }).click();
98新增: await page.waitForFunction(message => document.querySelector(".audio-controls button")?.title.includes(message), permissionMessage);
99新增: assert.ok((await speaker.getAttribute("title")).includes(permissionMessage), "guest permission failure stays available on the audio control");
100新增: permissionMissing = false;
101新增: await page.locator("output").filter({ hasText: "playing" }).waitFor();
70102 await page.getByRole("button", { name: "停止测试环境" }).click();
71103 await waitFor(() => open === 0);
72104 assert.equal(await page.evaluate(() => JSON.parse(localStorage.getItem("cage.audio")).volume), .5);
73105 assert.deepEqual(errors, []);
74删除: console.log(JSON.stringify({ result: "PASS", fullVolumeRMS: full, halfVolumeRMS: half, checks: ["real AudioWorklet PCM output", "volume", "mute closes stream", "unmute reconnects", "environment stop", "preference persistence"] }));
106新增: console.log(JSON.stringify({ result: "PASS", fullVolumeRMS: full, halfVolumeRMS: half, checks: ["real AudioWorklet PCM output", "volume", "mute closes stream", "unmute reconnects", "guest permission error", "recovery after permission restored", "environment stop", "preference persistence"] }));
75107} catch (error) {
76删除: console.error({ pageErrors: errors, body: await page.locator("body").innerText() });
108新增: console.error({ pageErrors: errors, body: await page.locator("body").innerText(), connected, open, preference: await page.evaluate(() => localStorage.getItem("cage.audio")) });
77109 throw error;
78110} finally {
79111 for (const timer of timers) clearInterval(timer);
新增ui/scripts/browser-close-smoke.mjs+211 −0看文件
@@ -0,0 +1,211 @@
1新增:import assert from 'node:assert/strict';
2新增:import { mkdir, writeFile } from 'node:fs/promises';
3新增:import { fileURLToPath } from 'node:url';
4新增:import { createWorkbench, chooseInline } from './workbench-fixture.mjs';
5新增:
6新增:const engine = process.env.CAGE_TEST_BROWSER || 'chromium';
7新增:const output = new URL(`../../docs/test-reports/2026-11-07-browser-close/${engine}/`, import.meta.url);
8新增:await mkdir(output, { recursive: true });
9新增:const { browser, page, state, errors } = await createWorkbench();
10新增:page.setDefaultTimeout(10000);
11新增:const checks = [];
12新增:const close = page.getByRole('button', { name: '关闭浏览器', exact: true });
13新增:const open = page.getByRole('button', { name: '打开浏览器', exact: true });
14新增:const home = page.getByRole('heading', { name: 'Cage 环境已就绪', exact: true });
15新增:const shot = name => page.screenshot({ path: fileURLToPath(new URL(name + '.png', output)) });
16新增:try {
17新增: await page.addInitScript(() => {
18新增: window.EventSource = class extends EventTarget {
19新增: constructor() { super(); window.closeBrowserEvents = this; queueMicrotask(() => this.onopen?.()); }
20新增: close() {}
21新增: };
22新增: });
23新增: await page.route('**/api/claude-desktop', route => route.fulfill({ json: {
24新增: installed: true, running: true, failed: false, managed: true, version: 'fixture',
25新增: } }));
26新增: state.status.ready = state.status.vm_running = true;
27新增: state.tabs = [
28新增: { id: 'page-one', title: '网页一', kind: 'web', url: 'https://example.test/one' },
29新增: { id: 'page-two', title: '网页二', kind: 'web', url: 'https://example.test/two' },
30新增: ];
31新增: state.active = 'page-one';
32新增: state.terminals = [
33新增: { id: 'terminal-one', title: '工作终端一', workspace: state.settings.workspace },
34新增: { id: 'terminal-two', title: '工作终端二', workspace: state.settings.workspace },
35新增: ];
36新增: await page.reload();
37新增: await home.waitFor();
38新增: const send = async extra => page.evaluate(snapshot => {
39新增: window.closeBrowserEvents.onmessage({ data: JSON.stringify(snapshot) });
40新增: }, { tabs: state.tabs, active: state.active, ...extra });
41新增: await open.click();
42新增: await close.waitFor();
43新增: assert.equal(await close.count(), 1);
44新增: const address = await page.locator('.navigation-row').boundingBox();
45新增: const x = await close.boundingBox();
46新增: assert.ok(x.y < address.y && x.x > address.x + address.width * 0.85, 'X sits at the top right');
47新增: await page.getByRole('button', { name: '搜索标签页', exact: true }).click();
48新增: const withList = await close.boundingBox();
49新增: assert.ok(withList.y < (await page.locator('.navigation-row').boundingBox()).y, 'X stays in top row while tab search is expanded');
50新增: await shot('horizontal-close');
51新增: await close.focus(); await page.keyboard.press('Enter');
52新增: await home.waitFor();
53新增: assert.equal(await page.locator('.browser-lane').count(), 0);
54新增: assert.equal(state.tabs.length, 2);
55新增: await send({ focus: true });
56新增: await home.waitFor();
57新增: assert.equal(await page.locator('.browser-lane').count(), 0);
58新增: checks.push('top-right X works by keyboard and with tab search expanded; returns to home; tabs retained; late focus does not reopen browser');
59新增:
60新增: await page.getByRole('tab', { name: '工作终端一', exact: true }).click();
61新增: await page.locator('.terminal-lane:not([hidden])').waitFor();
62新增: await open.click();
63新增: await page.getByRole('tab', { name: '网页二', exact: true }).click();
64新增: await close.click();
65新增: await page.locator('.terminal-lane:not([hidden])').waitFor();
66新增: assert.equal(await page.getByRole('tab', { name: '工作终端一', exact: true }).getAttribute('aria-selected'), 'true');
67新增: await open.click();
68新增: assert.equal(await page.getByRole('tab', { name: '网页二', exact: true }).getAttribute('aria-selected'), 'true');
69新增: await page.waitForFunction(() => document.querySelector('.browser-tabs [role="tab"]')?.getBoundingClientRect().width >= 100);
70新增: const source = await page.getByRole('tab', { name: '网页一', exact: true }).boundingBox();
71新增: const body = await page.locator('.browser-lane .pane-body').boundingBox();
72新增: await page.mouse.move(source.x + source.width / 2, source.y + source.height / 2);
73新增: await page.mouse.down();
74新增: await page.mouse.move(body.x + body.width * 0.8, body.y + body.height / 2, { steps: 12 });
75新增: await page.mouse.up();
76新增: await page.waitForFunction(() => document.querySelectorAll('.browser-header-cell').length === 2);
77新增: assert.equal(await close.count(), 1, 'dual-browser layout has one workspace close button');
78新增: await close.click();
79新增: await page.locator('.terminal-lane:not([hidden])').waitFor();
80新增: checks.push('returns to the original terminal after switching browser tabs or closing both browser panes; reopening resumes the selected browser tab');
81新增:
82新增: await page.getByRole('button', { name: 'Claude Desktop', exact: true }).click();
83新增: const desktop = page.getByRole('region', { name: 'Claude Desktop', exact: true });
84新增: await desktop.waitFor();
85新增: await open.click();
86新增: await close.click();
87新增: await desktop.waitFor();
88新增: let releaseNewPage;
89新增: const pendingNewPage = new Promise(resolve => { releaseNewPage = resolve; });
90新增: await page.route('**/api/browser/new', async route => { await pendingNewPage; await route.fallback(); });
91新增: const newRequest = page.waitForRequest('**/api/browser/new');
92新增: await page.getByRole('button', { name: 'claude.ai', exact: true }).click();
93新增: await newRequest;
94新增: await desktop.waitFor();
95新增: assert.equal(await close.count(), 0, 'pending creation preserves the previous view');
96新增: releaseNewPage();
97新增: await close.waitFor();
98新增: await close.click();
99新增: await desktop.waitFor();
100新增: checks.push('returns to Claude Desktop after opening existing tabs or asynchronously creating a new page; pending creation preserves the previous view');
101新增:
102新增: await open.click();
103新增: await page.getByRole('button', { name: '浏览器菜单', exact: true }).click();
104新增: await page.getByRole('menuitem', { name: '设置', exact: true }).click();
105新增: const settings = page.getByRole('region', { name: '浏览器设置', exact: true });
106新增: await settings.getByRole('navigation', { name: '浏览器设置分类' }).getByRole('button', { name: '外观', exact: true }).click();
107新增: await chooseInline(page.getByRole('combobox', { name: '标签栏布局' }), 'vertical');
108新增: await page.getByRole('button', { name: '关闭 设置', exact: true }).click();
109新增: await page.setViewportSize({ width: 820, height: 558 });
110新增: await page.getByRole('complementary', { name: '竖排标签栏' }).waitFor();
111新增: await close.waitFor();
112新增: const navigation = await page.locator('.navigation-row').boundingBox();
113新增: const verticalX = await close.boundingBox();
114新增: assert.ok(verticalX.x + verticalX.width <= 820 && verticalX.y >= navigation.y && verticalX.y < navigation.y + navigation.height);
115新增: await shot('vertical-close-minimum');
116新增: await close.click();
117新增: await desktop.waitFor();
118新增: checks.push('vertical tabs show X at the right of the address row at 820×558; settings do not replace the return destination');
119新增:
120新增: // If the previous terminal ends while browsing, return to home safely.
121新增: await page.getByRole('tab', { name: '工作终端二', exact: true }).click();
122新增: await open.click();
123新增: state.terminals = state.terminals.filter(tab => tab.id !== 'terminal-two');
124新增: await page.waitForResponse(response => response.url().endsWith('/api/terminals') && response.request().method() === 'GET');
125新增: await page.getByRole('tab', { name: '工作终端二', exact: true }).waitFor({ state: 'hidden' });
126新增: await close.click();
127新增: await home.waitFor();
128新增: assert.equal(state.requests.some(request => request.path === '/stop' || (request.path === '/browser/close' && request.body.id !== 'browser-settings')), false);
129新增: checks.push('ended return terminal falls back to home; closing browser never stops environment or closes individual tabs');
130新增:
131新增: const singlePage = async () => {
132新增: state.tabs = [{ id: 'last-page', title: '最后一页', kind: 'web', url: 'https://example.test/last' }];
133新增: state.active = 'last-page';
134新增: await send();
135新增: await open.click();
136新增: await page.getByRole('tab', { name: '最后一页', exact: true }).waitFor();
137新增: };
138新增: await singlePage();
139新增: await page.getByRole('button', { name: '关闭 最后一页', exact: true }).click();
140新增: await home.waitFor();
141新增: assert.equal(state.tabs.length, 0);
142新增: assert.equal(await close.count(), 0);
143新增: await send({ focus: true });
144新增: await home.waitFor();
145新增: await open.click();
146新增: await close.waitFor();
147新增: assert.equal(state.tabs.length, 1, 'reopening an empty browser creates one page');
148新增: checks.push('closing the last tab exits to home without a replacement; empty events stay closed; reopening creates one page');
149新增: await close.click();
150新增:
151新增: await page.getByRole('tab', { name: '工作终端一', exact: true }).click();
152新增: await singlePage();
153新增: await page.keyboard.press('Meta+w');
154新增: await page.locator('.terminal-lane:not([hidden])').waitFor();
155新增: assert.equal(await page.getByRole('tab', { name: '工作终端一', exact: true }).getAttribute('aria-selected'), 'true');
156新增: assert.equal(state.tabs.length, 0);
157新增: await send();
158新增: await page.getByRole('button', { name: 'Claude Desktop', exact: true }).click();
159新增: await singlePage();
160新增: // Destruction can arrive before the close request completes.
161新增: let releaseClose;
162新增: const pendingClose = new Promise(resolve => { releaseClose = resolve; });
163新增: await page.route('**/api/browser/close', async route => {
164新增: state.tabs = []; state.active = '';
165新增: await send();
166新增: await pendingClose;
167新增: await route.fulfill({ json: { ok: true } });
168新增: });
169新增: await page.getByRole('button', { name: '关闭 最后一页', exact: true }).click();
170新增: await desktop.waitFor();
171新增: const closeResponse = page.waitForResponse('**/api/browser/close');
172新增: releaseClose();
173新增: await closeResponse;
174新增: await desktop.waitFor();
175新增: await page.unroute('**/api/browser/close');
176新增: checks.push('last-tab keyboard close restores the terminal; a destruction event before the close response restores Claude Desktop');
177新增:
178新增: await singlePage();
179新增: await page.route('**/api/browser/close', route => route.fulfill({ status: 400, body: '标签尚未关闭,请重试' }));
180新增: await page.getByRole('button', { name: '关闭 最后一页', exact: true }).click();
181新增: await page.getByText('标签尚未关闭,请重试', { exact: true }).waitFor();
182新增: assert.equal(await close.count(), 1, 'failed close preserves the browser');
183新增: await page.unroute('**/api/browser/close');
184新增: state.tabs = []; state.active = '';
185新增: await send();
186新增: await desktop.waitFor();
187新增: assert.equal(await close.count(), 0);
188新增: checks.push('failed last-tab close preserves the page; external last-tab destruction also exits the browser');
189新增:
190新增: await singlePage();
191新增: state.tabs = []; state.active = '';
192新增: await page.evaluate(() => window.closeBrowserEvents.onerror());
193新增: await desktop.waitFor();
194新增: assert.equal(await close.count(), 0);
195新增: checks.push('fallback polling detects the last-tab removal and restores the previous view');
196新增:
197新增: await singlePage();
198新增: await close.click();
199新增: await page.getByRole('tab', { name: '工作终端一', exact: true }).click();
200新增: state.tabs = []; state.active = '';
201新增: await send();
202新增: assert.equal(await page.getByRole('tab', { name: '工作终端一', exact: true }).getAttribute('aria-selected'), 'true');
203新增: assert.equal(await close.count(), 0);
204新增: checks.push('background last-tab destruction preserves the currently selected terminal');
205新增: assert.deepEqual(errors, []);
206新增: await writeFile(new URL('result.json', output), JSON.stringify({ passed: true, engine, checks }, null, 2) + '\n');
207新增: console.log(JSON.stringify({ passed: true, engine, checks }, null, 2));
208新增:} catch (error) {
209新增: await shot('failure');
210新增: throw error;
211新增:} finally { await browser.close(); }
新增ui/scripts/browser-download-panel-smoke.mjs+253 −0看文件
@@ -0,0 +1,253 @@
1新增:import assert from "node:assert/strict";
2新增:import fs from "node:fs/promises";
3新增:import { createWorkbench } from "./workbench-fixture.mjs";
4新增:
5新增:// Isolated records and native bridge; no personal files or running environment.
6新增:const downloads = [
7新增: {
8新增: id: "report",
9新增: name: "产品需求与界面验收报告.pdf",
10新增: state: "saved",
11新增: path: "/Users/test/Cage/Downloads/产品需求与界面验收报告.pdf",
12新增: },
13新增: {
14新增: id: "video",
15新增: name: "很长的视频文件名称_20261107_项目演示与操作录屏.mp4",
16新增: state: "downloading",
17新增: receivedBytes: 42,
18新增: totalBytes: 100,
19新增: },
20新增: {
21新增: id: "failed",
22新增: name: "assets.zip",
23新增: state: "failed",
24新增: error: "保存失败,请检查连接后重试。",
25新增: retryable: true,
26新增: },
27新增: { id: "canceled", name: "installer.dmg", state: "canceled" },
28新增: ...Array.from({ length: 10 }, (_, index) => ({
29新增: id: `history-${index}`,
30新增: name: `历史文件 ${index + 1}.txt`,
31新增: state: "saved",
32新增: path: `/Users/test/Cage/Downloads/历史文件 ${index + 1}.txt`,
33新增: })),
34新增:];
35新增:let records = downloads;
36新增:const output = process.env.CAGE_DOWNLOAD_CAPTURE || "/tmp/cage-download-panel";
37新增:await fs.mkdir(output, { recursive: true });
38新增:for (const platform of ["darwin", "win32", "linux"]) {
39新增: const calls = [];
40新增: const { browser, page, state, errors } = await createWorkbench({
41新增: clientContext: {
42新增: mode: "local",
43新增: connection_id: "local",
44新增: client_platform: platform,
45新增: server_platform: platform,
46新增: connection: { state: "disconnected" },
47新增: },
48新增: nativeRequest: async (body) => {
49新增: calls.push(body);
50新增: return body.action === "saveBrowserDownload"
51新增: ? { canceled: true }
52新增: : { ok: true };
53新增: },
54新增: });
55新增: try {
56新增: records = downloads;
57新增: await page.route("**/api/browser/tabs", (route) =>
58新增: route.fulfill({
59新增: json: { tabs: state.tabs, active: state.active, downloads: records },
60新增: }),
61新增: );
62新增: await page.route("**/api/browser/files/saved", (route) =>
63新增: route.fulfill({ json: [] }),
64新增: );
65新增: await page.route("**/api/browser/download-retry", (route) => {
66新增: calls.push({ action: "retry", ...route.request().postDataJSON() });
67新增: return route.fulfill({ json: { ok: true } });
68新增: });
69新增: state.status.ready = state.status.vm_running = true;
70新增: await page.reload();
71新增: await page.getByRole("button", { name: "打开浏览器", exact: true }).click();
72新增: const trigger = page.getByRole("button", {
73新增: name: "浏览器下载",
74新增: exact: true,
75新增: });
76新增: const panel = page.getByRole("dialog", { name: "下载文件", exact: true });
77新增: const toolbar = page.locator(".browser-chrome .navigation-row");
78新增: assert.equal(
79新增: await page
80新增: .getByRole("button", { name: "设置", exact: true })
81新增: .locator("svg.lucide-settings")
82新增: .count(),
83新增: 1,
84新增: );
85新增: await page.getByRole("button", { name: "收起侧栏", exact: true }).click();
86新增: for (const width of [1280, 375]) {
87新增: await page.setViewportSize({ width, height: 850 });
88新增: const before = await toolbar.boundingBox();
89新增: await trigger.focus();
90新增: await trigger.press("Enter");
91新增: await panel.waitFor();
92新增: const box = await panel.boundingBox(),
93新增: after = await toolbar.boundingBox();
94新增: assert.ok(
95新增: box.x >= 0 &&
96新增: box.x + box.width <= width &&
97新增: box.y >= after.y + after.height,
98新增: "download panel stays below the toolbar and inside the viewport",
99新增: );
100新增: assert.ok(
101新增: box.y + box.height <= 850 && Math.abs(after.height - before.height) < 1,
102新增: "panel stays inside the window without shifting the toolbar",
103新增: );
104新增: assert.equal(
105新增: await page.locator(".modal-scrim").count(),
106新增: 0,
107新增: "downloads do not dim the page",
108新增: );
109新增: assert.equal(
110新增: await panel.getByRole("progressbar").getAttribute("value"),
111新增: "42",
112新增: );
113新增: const list = panel.locator(".browser-download-list");
114新增: assert.equal(
115新增: await list.evaluate((el) => el.scrollHeight > el.clientHeight),
116新增: true,
117新增: "long history scrolls inside the panel",
118新增: );
119新增: assert.equal(
120新增: await list.evaluate((el) => el.scrollWidth <= el.clientWidth),
121新增: true,
122新增: "long file names and paths do not widen the panel",
123新增: );
124新增: const row = panel.locator("article").first();
125新增: await row.getByRole("button", { name: "打开文件", exact: true }).click();
126新增: await row
127新增: .getByRole("button", { name: "在文件夹中显示", exact: true })
128新增: .click();
129新增: await row.getByRole("button", { name: "另存为…", exact: true }).click();
130新增: await panel
131新增: .getByRole("button", { name: "重试保存", exact: true })
132新增: .click();
133新增: await panel
134新增: .getByRole("button", { name: "重试保存", exact: true })
135新增: .waitFor({ state: "visible" });
136新增: await panel.getByRole("button", { name: "关闭面板", exact: true }).focus();
137新增: await page.screenshot({ path: `${output}/${platform}-${width}.png` });
138新增: if (platform === "darwin" && width === 1280) await panel.screenshot({ path: `${output}/panel.png` });
139新增: await list.evaluate((el) => {
140新增: el.scrollTop = el.scrollHeight;
141新增: });
142新增: await panel
143新增: .getByText("历史文件 10.txt", { exact: true })
144新增: .scrollIntoViewIfNeeded();
145新增: await page.keyboard.press("Escape");
146新增: await panel.waitFor({ state: "hidden" });
147新增: assert.equal(
148新增: await trigger.evaluate((el) => el === document.activeElement),
149新增: true,
150新增: "Escape restores the download button focus",
151新增: );
152新增: await trigger.click();
153新增: await page.getByRole("textbox", { name: "网页地址或搜索" }).click();
154新增: await panel.waitFor({ state: "hidden" });
155新增: assert.equal(
156新增: await page
157新增: .getByRole("textbox", { name: "网页地址或搜索" })
158新增: .evaluate((el) => el === document.activeElement),
159新增: true,
160新增: "outside clicks keep their intended focus",
161新增: );
162新增: }
163新增: await page.setViewportSize({ width: 1280, height: 850 });
164新增: if (platform === "darwin") {
165新增: await page.emulateMedia({ colorScheme: "dark" });
166新增: await page.waitForFunction(
167新增: () => document.documentElement.dataset.theme === "dark",
168新增: );
169新增: await trigger.click();
170新增: await panel.waitFor();
171新增: await page.screenshot({ path: `${output}/dark.png` });
172新增: await page.evaluate(() =>
173新增: document.documentElement.style.setProperty("--ui-font-size", "28px"),
174新增: );
175新增: await page.screenshot({ path: `${output}/large-text.png` });
176新增: assert.equal(
177新增: await panel
178新增: .locator(".browser-download-list")
179新增: .evaluate((el) => el.scrollWidth <= el.clientWidth),
180新增: true,
181新增: );
182新增: await page.setViewportSize({ width: 900, height: 600 });
183新增: await page.waitForFunction(() => {
184新增: const box = document.querySelector(".browser-download-panel").getBoundingClientRect();
185新增: return box.right <= window.innerWidth && box.bottom <= window.innerHeight;
186新增: });
187新增: const resized = await panel.boundingBox();
188新增: assert.ok(
189新增: resized.x + resized.width <= 900 && resized.y + resized.height <= 600,
190新增: "open panel follows window resizing",
191新增: );
192新增: await page.keyboard.press("Escape");
193新增: await page.evaluate(() =>
194新增: document.documentElement.style.removeProperty("--ui-font-size"),
195新增: );
196新增: await page.emulateMedia({ colorScheme: "light" });
197新增: await page.setViewportSize({ width: 1280, height: 850 });
198新增: }
199新增: await page.getByRole("button", { name: "浏览器菜单", exact: true }).click();
200新增: const menu = page.getByRole("menu", { name: "浏览器菜单", exact: true });
201新增: assert.equal(
202新增: await menu
203新增: .getByRole("menuitem", { name: "设置", exact: true })
204新增: .locator("svg.lucide-settings")
205新增: .count(),
206新增: 1,
207新增: );
208新增: await menu
209新增: .getByRole("menuitem", { name: "浏览器下载", exact: true })
210新增: .click();
211新增: await panel.waitFor();
212新增: await page.keyboard.press("Escape");
213新增: await panel.waitFor({ state: "hidden" });
214新增: await page.getByRole("button", { name: "展开侧栏", exact: true }).click();
215新增: await page.getByRole("button", { name: "下载文件", exact: true }).click();
216新增: await panel.waitFor();
217新增: assert.ok(
218新增: (await panel.boundingBox()).x > 800,
219新增: "sidebar also opens the panel at the upper right",
220新增: );
221新增: await panel.getByRole("button", { name: "关闭面板", exact: true }).click();
222新增: records = [];
223新增: await page.reload();
224新增: await page.getByRole("button", { name: "打开浏览器", exact: true }).click();
225新增: await trigger.click();
226新增: await panel.getByText("暂无下载", { exact: true }).waitFor();
227新增: await page.screenshot({ path: `${output}/${platform}-empty.png` });
228新增: assert.ok(
229新增: calls.some(
230新增: (call) =>
231新增: call.action === "browserDownloadAction" && call.operation === "open",
232新增: ),
233新增: );
234新增: assert.ok(
235新增: calls.some(
236新增: (call) =>
237新增: call.action === "browserDownloadAction" &&
238新增: call.operation === "reveal",
239新增: ),
240新增: );
241新增: assert.ok(calls.some((call) => call.action === "saveBrowserDownload"));
242新增: assert.ok(
243新增: calls.some((call) => call.action === "retry" && call.id === "failed"),
244新增: );
245新增: assert.deepEqual(errors, []);
246新增: console.log(
247新增: `PASS: ${platform} context, toolbar/menu/sidebar downloads, 1280/375 layout, progress, scroll, empty state, file actions, retry, Escape/outside dismissal and gear icons.`,
248新增: );
249新增: } finally {
250新增: await browser.close();
251新增: }
252新增:}
253新增:console.log(`Screenshots: ${output}`);
新增ui/scripts/browser-menu-smoke.mjs+99 −0看文件
@@ -0,0 +1,99 @@
1新增:import assert from "node:assert/strict";
2新增:import fs from "node:fs/promises";
3新增:import { createWorkbench } from "./workbench-fixture.mjs";
4新增:
5新增:// Isolated UI data; no running environment, credentials or personal files.
6新增:const { browser, page, state, errors } = await createWorkbench();
7新增:page.setDefaultTimeout(10000);
8新增:const output = process.env.CAGE_MENU_CAPTURE || `/tmp/cage-browser-menu-${browser.browserType().name()}`;
9新增:await fs.mkdir(output, { recursive: true });
10新增:await page.route("**/api/vault/browser", route => route.fulfill({ json: {
11新增: available: true, entries: [], candidates: [], origin: "https://example.test",
12新增:} }));
13新增:try {
14新增: state.status.ready = state.status.vm_running = true;
15新增: state.tabs = [{ id: "menu-web", kind: "web", title: "测试网页", url: "https://example.test" }];
16新增: state.active = "menu-web";
17新增: await page.reload();
18新增: await page.getByRole("button", { name: "打开浏览器", exact: true }).click();
19新增: await page.getByRole("button", { name: "收起侧栏", exact: true }).click();
20新增: const trigger = page.getByRole("button", { name: "浏览器菜单", exact: true });
21新增: const menu = page.getByRole("menu", { name: "浏览器菜单", exact: true });
22新增: const header = page.locator(".browser-chrome");
23新增: const star = header.getByRole("button", { name: "收藏此页", exact: true });
24新增: const folder = header.getByRole("button", { name: "收藏夹", exact: true });
25新增: for (const width of [1280, 375]) {
26新增: await page.setViewportSize({ width, height: 850 });
27新增: const address = await page.locator(".address-bar").boundingBox();
28新增: const starBox = await star.boundingBox(), folderBox = await folder.boundingBox(), triggerBox = await trigger.boundingBox();
29新增: assert.ok(address.x + address.width <= starBox.x && starBox.x + starBox.width <= folderBox.x && folderBox.x + folderBox.width <= triggerBox.x, "favorites stay beside the address bar without overlapping");
30新增: assert.ok(triggerBox.x + triggerBox.width <= width, "toolbar actions stay within the viewport");
31新增: await page.screenshot({ path: `${output}/toolbar-${width}.png` });
32新增: const closed = await header.boundingBox();
33新增: await trigger.focus();
34新增: await trigger.press("ArrowDown");
35新增: await menu.waitFor();
36新增: const opened = await header.boundingBox(), box = await menu.boundingBox();
37新增: assert.ok(Math.abs(opened.height - closed.height) < 1, "menu does not change the header height");
38新增: const body = await page.locator(".browser-lane .pane-body").boundingBox();
39新增: assert.ok(box.y >= body.y - 1 && box.y < body.y + 10, "menu overlays the browser content below the toolbar");
40新增: assert.ok(box.width <= 240 && box.x >= 0 && box.x + box.width <= width, "menu stays compact and within the viewport");
41新增: const items = menu.getByRole("menuitem");
42新增: const required = ["下载", "密码"];
43新增: assert.deepEqual((await items.allTextContents()).filter(text => required.includes(text)), required);
44新增: assert.equal(await menu.getByRole("menuitem", { name: /收藏/ }).count(), 0);
45新增: for (let i = 1; i < await items.count(); i++) assert.ok((await items.nth(i).boundingBox()).y > (await items.nth(i - 1).boundingBox()).y);
46新增: assert.equal(await items.first().evaluate(el => el === document.activeElement), true);
47新增: await page.keyboard.press("ArrowDown");
48新增: assert.equal(await items.nth(1).evaluate(el => el === document.activeElement), true);
49新增: await page.keyboard.press("End");
50新增: assert.equal(await menu.getByRole("menuitem", { name: "设置", exact: true }).evaluate(el => el === document.activeElement), true);
51新增: await menu.getByRole("menuitem", { name: "密码", exact: true }).focus();
52新增: await page.keyboard.press("Enter");
53新增: const picker = page.getByRole("region", { name: "当前网站的密码" });
54新增: await picker.waitFor();
55新增: await picker.getByText("此网站尚未保存账号密码。", { exact: true }).waitFor();
56新增: await page.keyboard.press("Escape");
57新增: await picker.waitFor({ state: "hidden" });
58新增: await page.screenshot({ path: `${output}/menu-${width}.png` });
59新增: await page.keyboard.press("Escape");
60新增: await menu.waitFor({ state: "hidden" });
61新增: assert.equal(await trigger.evaluate(el => el === document.activeElement), true);
62新增: assert.ok(Math.abs((await header.boundingBox()).height - closed.height) < 1, "closing restores the original layout");
63新增: await trigger.click();
64新增: await page.getByRole("textbox", { name: "网页地址或搜索" }).click();
65新增: await menu.waitFor({ state: "hidden" });
66新增: }
67新增: await star.click();
68新增: const editor = page.getByRole("dialog", { name: "添加收藏", exact: true });
69新增: await editor.waitFor();
70新增: await menu.waitFor({ state: "hidden" });
71新增: await editor.getByRole("button", { name: "取消", exact: true }).click();
72新增: await editor.waitFor({ state: "hidden" });
73新增: assert.equal(await star.evaluate(el => el === document.activeElement), true);
74新增: await folder.focus();
75新增: await folder.press("Enter");
76新增: const favorites = page.getByRole("dialog", { name: "收藏夹", exact: true });
77新增: await favorites.waitFor();
78新增: await menu.waitFor({ state: "hidden" });
79新增: await favorites.getByRole("button", { name: "关闭收藏夹", exact: true }).click();
80新增: assert.equal(await folder.evaluate(el => el === document.activeElement), true);
81新增: await trigger.click();
82新增: await menu.getByRole("menuitem", { name: "浏览器下载", exact: true }).click();
83新增: const downloads = page.getByRole("dialog", { name: "下载文件", exact: true });
84新增: await downloads.waitFor();
85新增: await menu.waitFor({ state: "hidden" });
86新增: await downloads.getByRole("button", { name: "关闭面板", exact: true }).click();
87新增: await downloads.waitFor({ state: "hidden" });
88新增: assert.equal(await trigger.evaluate(el => el === document.activeElement), true);
89新增: await page.keyboard.press("Meta+d");
90新增: await editor.waitFor();
91新增: await editor.getByRole("button", { name: "取消", exact: true }).click();
92新增: await page.keyboard.press("Meta+Shift+o");
93新增: await favorites.waitFor();
94新增: await page.keyboard.press("Escape");
95新增: await favorites.waitFor({ state: "hidden" });
96新增: assert.equal(await folder.evaluate(el => el === document.activeElement), true);
97新增: assert.deepEqual(errors, []);
98新增: console.log(`PASS: favorites toolbar at 1280/375, direct and keyboard access, focus restoration, browser menu, downloads, passwords and favorites shortcuts. Screenshots: ${output}`);
99新增:} finally { await browser.close(); }
新增ui/scripts/browser-privacy-smoke.mjs+114 −0看文件
@@ -0,0 +1,114 @@
1新增:// UI actions reach a real isolated production browser controller. The VM status,
2新增:// remote display and account are the existing workbench fixture.
3新增:import assert from 'node:assert/strict';
4新增:import { fileURLToPath } from 'node:url';
5新增:import { mkdir, writeFile } from 'node:fs/promises';
6新增:import { createWorkbench } from './workbench-fixture.mjs';
7新增:import { createPrivacyController } from '../../scripts/browser-privacy-fixture.mjs';
8新增:
9新增:const output = new URL('../../docs/test-reports/2026-11-07-browser-privacy/', import.meta.url);
10新增:const engine = process.env.CAGE_TEST_BROWSER || 'chromium';
11新增:await mkdir(output, { recursive: true });
12新增:const controller = await createPrivacyController();
13新增:let workbench;
14新增:let failCookies = false;
15新增:const checks = [];
16新增:try {
17新增: const normal = (await controller.api('/tabs')).active;
18新增: await controller.cdp(normal, 'Network.setCookies', { cookies: [
19新增: { name: 'fixture-session', value: 'fixture-only-value', domain: 'localhost', path: '/', httpOnly: true },
20新增: { name: 'unrelated', value: 'fixture-other', domain: 'other.test', path: '/' },
21新增: ] });
22新增: workbench = await createWorkbench({ browserRequest: async (route, path, body) => {
23新增: if (path === '/browser/resize') return route.fulfill({ json: { ok: true } });
24新增: if (path === '/browser/cookies' && failCookies) return route.fulfill({ status: 502, body: '测试:Cookie 服务暂时不可用' });
25新增: try { return await route.fulfill({ json: await controller.api(path.replace('/browser', ''), body ?? undefined) }); }
26新增: catch (error) { return route.fulfill({ status: 400, body: error.message }); }
27新增: } });
28新增: const { page, errors } = workbench;
29新增: page.setDefaultTimeout(10000);
30新增: workbench.state.settings.browser_home_url = controller.origin + '/ui-home';
31新增: await page.getByRole('button', { name: '启动 Cage 环境', exact: true }).click();
32新增: await page.getByRole('heading', { name: 'Cage 环境已就绪', exact: true }).waitFor();
33新增: await page.getByRole('button', { name: '打开浏览器', exact: true }).click();
34新增: await page.getByRole('tab', { name: 'Privacy fixture', exact: true }).waitFor();
35新增: const menu = page.getByRole('button', { name: '浏览器菜单', exact: true });
36新增: await menu.focus(); await page.keyboard.press('ArrowDown');
37新增: await page.getByRole('menuitem', { name: '新建无痕标签', exact: true }).press('Enter');
38新增: await page.getByRole('tab', { name: /无痕 ·/ }).waitFor();
39新增: await page.locator('.browser-private-badge').waitFor();
40新增: assert.equal((await controller.api('/tabs')).tabs.filter(tab => tab.incognito).length, 1);
41新增: await page.getByRole('button', { name: '新建网页', exact: true }).click();
42新增: await controller.waitFor(async () => (await controller.api('/tabs')).tabs.filter(tab => tab.incognito).length === 2, 'plus inherits private session');
43新增: await page.screenshot({ path: fileURLToPath(new URL(`private-tabs-${engine}.png`, output)) });
44新增: checks.push('keyboard menu creates a real private session; tab title, address badge and notice identify privacy; plus inherits private mode');
45新增:
46新增: // Private label edits must remain in memory even after the tab closes.
47新增: const privateTab = page.getByRole('tab', { name: /无痕 ·/ }).last();
48新增: await privateTab.click({ button: 'right' });
49新增: await page.getByRole('menuitem', { name: '重命名标签', exact: true }).click();
50新增: await page.getByRole('dialog', { name: '重命名标签' }).locator('input').fill('PRIVATE_TITLE_MUST_NOT_PERSIST');
51新增: await page.getByRole('button', { name: '保存名称', exact: true }).click();
52新增: assert.equal(await page.evaluate(() => JSON.stringify(localStorage).includes('PRIVATE_TITLE_MUST_NOT_PERSIST')), false);
53新增: await page.getByRole('button', { name: '关闭 无痕 · PRIVATE_TITLE_MUST_NOT_PERSIST', exact: true }).click();
54新增: await page.getByRole('tab', { name: 'Privacy fixture', exact: true }).click();
55新增: await page.getByRole('tab', { name: 'Privacy fixture', exact: true }).click({ button: 'right' });
56新增: await page.getByRole('menuitem', { name: '置顶标签', exact: true }).click();
57新增: assert.equal(await page.evaluate(() => JSON.stringify(localStorage).includes('PRIVATE_TITLE_MUST_NOT_PERSIST')), false);
58新增: checks.push('private rename never persists, including after closing the tab and saving normal tab metadata');
59新增:
60新增: await menu.click();
61新增: await page.getByRole('menuitem', { name: '管理 Cookie', exact: true }).click();
62新增: const panel = page.getByRole('region', { name: 'Cookie 管理' });
63新增: await panel.getByText('fixture-session', { exact: true }).waitFor();
64新增: assert.equal(await panel.getByText('unrelated', { exact: true }).count(), 0);
65新增: await panel.getByRole('button', { name: '查看值', exact: true }).click();
66新增: await panel.getByText('fixture-only-value', { exact: true }).waitFor();
67新增: await panel.getByRole('button', { name: '隐藏值', exact: true }).click();
68新增: const range = panel.getByRole('combobox', { name: 'Cookie 网站范围' });
69新增: const listY = async () => (await panel.locator('.cookie-list').boundingBox()).y;
70新增: const collapsedY = await listY();
71新增: await range.click();
72新增: await panel.getByRole('option', { name: '所有网站', exact: true }).waitFor();
73新增: assert.ok(await listY() > collapsedY + 30, 'inline choices occupy layout space');
74新增: await page.screenshot({ path: fileURLToPath(new URL(`cookie-range-inline-${engine}.png`, output)) });
75新增: await range.press('ArrowDown'); await range.press('Enter');
76新增: await panel.getByText('unrelated', { exact: true }).waitFor();
77新增: await panel.getByRole('textbox', { name: '搜索 Cookie' }).fill('fixture-session');
78新增: await panel.getByText('共 1 条', { exact: false }).waitFor();
79新增: await panel.getByRole('button', { name: '删除 Cookie fixture-session', exact: true }).click();
80新增: await panel.getByText('没有匹配的 Cookie。', { exact: true }).waitFor();
81新增: assert.equal((await controller.api('/cookies', { id: normal, mode: 'list', scope: 'all' })).total, 1);
82新增: checks.push('real cookies viewed, values revealed and hidden, range selects inline with keyboard, search and exact deletion preserve other cookies');
83新增:
84新增: await panel.getByRole('textbox', { name: '搜索 Cookie' }).fill('');
85新增: await panel.getByText('unrelated', { exact: true }).waitFor();
86新增: await panel.getByRole('button', { name: '清空所有网站', exact: true }).click();
87新增: await panel.getByRole('button', { name: '取消', exact: true }).click();
88新增: assert.equal((await controller.api('/cookies', { id: normal, mode: 'list', scope: 'all' })).total, 1);
89新增: failCookies = true;
90新增: await panel.getByRole('button', { name: '刷新 Cookie', exact: true }).click();
91新增: await panel.getByRole('alert').getByText('测试:Cookie 服务暂时不可用', { exact: true }).waitFor();
92新增: failCookies = false;
93新增: await panel.getByRole('button', { name: '刷新 Cookie', exact: true }).click();
94新增: await panel.getByText('unrelated', { exact: true }).waitFor();
95新增: await page.setViewportSize({ width: 820, height: 558 });
96新增: await page.screenshot({ path: fileURLToPath(new URL(`cookies-minimum-window-${engine}.png`, output)) });
97新增: assert.ok((await panel.boundingBox()).x >= 0);
98新增: assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth + 1), false);
99新增: await panel.getByRole('button', { name: '清空所有网站', exact: true }).click();
100新增: await panel.getByRole('button', { name: '确认清空', exact: true }).click();
101新增: await panel.getByText('没有匹配的 Cookie。', { exact: true }).waitFor();
102新增: await panel.getByRole('textbox', { name: '搜索 Cookie' }).press('Escape');
103新增: assert.equal(await panel.count(), 0);
104新增: checks.push('clear cancel and confirm, error and refresh recovery, 820×558 layout, Escape closes and restores focus');
105新增: assert.deepEqual(errors, []);
106新增: await writeFile(new URL(`ui-result-${engine}.json`, output), JSON.stringify({ passed: true, engine, checks }, null, 2) + '\n');
107新增: console.log(JSON.stringify({ passed: true, checks }, null, 2));
108新增:} catch (error) {
109新增: if (workbench) {
110新增: await workbench.page.screenshot({ path: fileURLToPath(new URL('failure.png', output)) });
111新增: console.error({ tabs: await workbench.page.getByRole('tab').allTextContents(), errors: workbench.errors });
112新增: }
113新增: throw error;
114新增:} finally { await workbench?.browser.close(); await controller.close(); }
新增ui/scripts/browser-resize-smoke.mjs+59 −0看文件
@@ -0,0 +1,59 @@
1新增:import assert from "node:assert/strict";
2新增:import { createWorkbench } from "./workbench-fixture.mjs";
3新增:import { startDisplay } from "./rfb-wire-fixture.mjs";
4新增:
5新增:const display = await startDisplay(process.env.CAGE_UI_URL || "http://127.0.0.1:5198", { frameInterval: 200 });
6新增:const { browser, page, state, errors } = await createWorkbench({
7新增: url: display.url, mockWebSockets: false, viewport: { width: 1000, height: 740 },
8新增:});
9新增:page.setDefaultTimeout(10000);
10新增:await page.route("**/api/browser/resize", route => {
11新增: return route.fulfill({ json: { ok: true } });
12新增:});
13新增:try {
14新增: state.status.ready = state.status.vm_running = true;
15新增: state.tabs = [{ id: "page", kind: "web", title: "Resize", url: "https://example.test" }];
16新增: state.active = "page";
17新增: await page.reload();
18新增: await page.getByRole("button", { name: "打开浏览器", exact: true }).click();
19新增: const canvas = page.locator(".browser-lane .remote-canvas canvas");
20新增: const pixel = () => canvas.evaluate(c => [...c.getContext("2d").getImageData(c.width - 1, c.height - 1, 1, 1).data]);
21新增: await page.waitForFunction(() => {
22新增: const c = document.querySelector(".browser-lane canvas");
23新增: return c?.width && c.getContext("2d").getImageData(0, 0, 1, 1).data[0] > 0;
24新增: });
25新增: display.pauseFrames(true);
26新增: const oldPixel = await pixel();
27新增: const connections = display.stats.connections;
28新增: const oldBox = await canvas.boundingBox();
29新增: const resized = page.waitForRequest(req => req.url().endsWith("/api/browser/resize") && req.postDataJSON().width > oldBox.width * 2);
30新增: await page.setViewportSize({ width: 1240, height: 760 });
31新增: const box = await page.locator(".browser-lane .remote-canvas").boundingBox();
32新增: const shown = await canvas.boundingBox();
33新增: assert.ok(Math.abs(shown.width - box.width) < 1 && Math.abs(shown.height - box.height) < 1,
34新增: "the previous frame must fill the browser pane before the guest responds");
35新增: const x = Math.floor(box.width * .75), y = Math.floor(box.height * .25);
36新增: await canvas.click({ position: { x, y } });
37新增: assert.ok(Math.abs(display.stats.pointer.x - x / box.width * 640) <= 1);
38新增: assert.ok(Math.abs(display.stats.pointer.y - y / box.height * 480) <= 1);
39新增: const desired = (await resized).postDataJSON();
40新增: assert.equal(desired.width, Math.floor(box.width * 2));
41新增: display.resize(desired); // Send dimensions now, withhold all pixel updates.
42新增: await page.waitForFunction(w => document.querySelector(".browser-lane canvas")?.width === w, desired.width);
43新增: assert.deepEqual(await pixel(), oldPixel, "enlarging must preserve the visible corner until new pixels arrive");
44新增: display.pauseFrames(false);
45新增: await page.waitForFunction(value => {
46新增: const c = document.querySelector(".browser-lane canvas");
47新增: const p = c.getContext("2d").getImageData(c.width - 1, c.height - 1, 1, 1).data;
48新增: return p[3] === 255 && p[0] !== value;
49新增: }, oldPixel[0]);
50新增: assert.equal(display.stats.connections, connections);
51新增: assert.deepEqual(errors, []);
52新增: console.log("PASS: browser resize fills the pane, preserves the last frame and pointer mapping, then repaints over the same RFB connection");
53新增:} catch (error) {
54新增: console.error({ errors, stats: display.stats, body: await page.locator("body").innerText() });
55新增: throw error;
56新增:} finally {
57新增: await browser.close();
58新增: await display.close();
59新增:}
新增ui/scripts/browser-settings-fixture.mjs+68 −0看文件
@@ -0,0 +1,68 @@
1新增:import { execFileSync } from 'node:child_process';
2新增:import http from 'node:http';
3新增:import { createWorkbench } from './workbench-fixture.mjs';
4新增:import { createPrivacyController } from '../../scripts/browser-privacy-fixture.mjs';
5新增:export async function createSettingsWorkbench(options = {}) {
6新增: const clientContext = options.clientContext || { mode: 'local', connection_id: 'local', client_platform: 'darwin', server_platform: 'darwin', connection: { state: 'disconnected' } };
7新增: const controller = await createPrivacyController();
8新增: const fixtureState = { failSave: false, home: controller.origin + '/home' };
9新增: const archive = execFileSync('uv', ['run', '--no-project', 'python', '-c', `import io,json,sys,zipfile
10新增:b=io.BytesIO()
11新增:with zipfile.ZipFile(b,'w') as z:
12新增: z.writestr('manifest.json',json.dumps({'manifest_version':3,'name':'阅读助手','version':'1.0','description':'调整网页阅读体验。','permissions':['storage'],'content_scripts':[{'matches':['http://localhost/*'],'js':['content.js']}]}))
13新增: z.writestr('content.js','document.documentElement.dataset.cageSettingsExtension="active";')
14新增:sys.stdout.buffer.write(b.getvalue())`], { stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 1 << 20 });
15新增: const profileID = 'a'.repeat(32), extensionID = 'b'.repeat(32);
16新增: // WebKit's routing protocol omits Blob upload bodies. Keep those uploads on
17新增: // real HTTP, so the controller receives the actual File bytes in both engines.
18新增: const proxy = http.createServer(async (request, response) => {
19新增: if (request.url === '/api/browser/extensions/upload' && request.method === 'POST') {
20新增: try {
21新增: const chunks = []; for await (const chunk of request) chunks.push(chunk);
22新增: const result = await controller.uploadExtension(Buffer.concat(chunks));
23新增: response.setHeader('Content-Type', 'application/json'); response.end(JSON.stringify(result));
24新增: } catch (error) { response.writeHead(400); response.end(error.message); }
25新增: return;
26新增: }
27新增: if (request.url.startsWith('/api/')) { response.writeHead(404); response.end(); return; }
28新增: const target = new URL(request.url, process.env.CAGE_UI_URL || 'http://127.0.0.1:5198');
29新增: const upstream = http.request(target, { headers: { ...request.headers, host: target.host } }, source => { response.writeHead(source.statusCode, source.headers); source.pipe(response); });
30新增: upstream.on('error', error => { response.writeHead(502); response.end(error.message); }); request.pipe(upstream);
31新增: });
32新增: await new Promise(resolve => proxy.listen(0, '127.0.0.1', resolve));
33新增: let workbench;
34新增: try {
35新增: workbench = await createWorkbench({ ...options, clientContext, url: `http://127.0.0.1:${proxy.address().port}`,
36新增: browserRequest: async (route, path, body) => {
37新增: if (path === '/browser/extensions/upload') return route.continue();
38新增: if (path === '/browser/resize') return route.fulfill({ json: { ok: true } });
39新增: if (path === '/browser/preferences') {
40新增: if (body) {
41新增: if (fixtureState.failSave) return route.fulfill({ status: 500, contentType: 'text/plain; charset=utf-8', body: '保存浏览器设置失败,请重试' });
42新增: await controller.api('/homepage', { url: body.browser_home_url }); fixtureState.home = body.browser_home_url;
43新增: }
44新增: return route.fulfill({ json: { browser_home_url: fixtureState.home } });
45新增: }
46新增: try {
47新增: const result = await controller.api(path.replace('/browser', ''), body);
48新增: return route.fulfill({ json: result });
49新增: } catch (error) { return route.fulfill({ status: 400, contentType: 'text/plain; charset=utf-8', body: error.message }); }
50新增: },
51新增: clientRequest: async (route, path, body) => {
52新增: if (path === '/client/context') return route.fulfill({ json: clientContext });
53新增: if (path === '/client/browser-extensions') {
54新增: if (body) return route.fulfill({ contentType: 'application/zip', body: archive });
55新增: return route.fulfill({ json: { profiles: [{ id: profileID, browser: 'Microsoft Edge', name: '个人配置', extensions: [
56新增: { id: extensionID, name: '阅读助手', version: '1.0', enabled: false, state_known: true, compatible: true, identity_preserved: false, permissions: ['storage'], hostPermissions: ['http://localhost/*'] },
57新增: { id: 'c'.repeat(32), name: '旧版扩展', version: '2.0', enabled: true, state_known: true, compatible: false, identity_preserved: false, permissions: [], hostPermissions: [] },
58新增: ] }] } });
59新增: }
60新增: return route.fulfill({ json: path === '/client/hosts' ? { hosts: [] } : {} });
61新增: },
62新增: });
63新增: workbench.state.status.ready = workbench.state.status.vm_running = true;
64新增: workbench.state.settings.browser_home_url = fixtureState.home;
65新增: await workbench.page.reload();
66新增: return { ...workbench, controller, fixtureState, archive, profileID, extensionID, close: async () => { await workbench.browser.close(); await new Promise(resolve => proxy.close(resolve)); await controller.close(); } };
67新增: } catch (error) { await workbench?.browser.close(); await new Promise(resolve => proxy.close(resolve)); await controller.close(); throw error; }
68新增:}
新增ui/scripts/browser-settings-review.mjs+10 −0看文件
@@ -0,0 +1,10 @@
1新增:import { createSettingsWorkbench } from './browser-settings-fixture.mjs';
2新增:const fixture = await createSettingsWorkbench({ launchOptions: { args: ['--remote-debugging-port=9233'] } });
3新增:const { page } = fixture;
4新增:await page.getByRole('button', { name: '打开浏览器', exact: true }).click();
5新增:await page.getByRole('button', { name: '浏览器菜单', exact: true }).click();
6新增:await page.getByRole('menuitem', { name: '设置', exact: true }).click();
7新增:await page.getByRole('region', { name: '浏览器设置', exact: true }).waitFor();
8新增:console.log('REVIEW_READY: isolated browser at http://127.0.0.1:9233; test site and APIs only; no user environment');
9新增:process.on('SIGTERM', async () => { await fixture.close(); process.exit(0); });
10新增:await new Promise(() => {});
新增ui/scripts/browser-settings-smoke.mjs+116 −0看文件
@@ -0,0 +1,116 @@
1新增:import assert from 'node:assert/strict';
2新增:import { writeFile } from 'node:fs/promises';
3新增:import { join } from 'node:path';
4新增:import { smokeCaptureDirectory } from './smoke-captures.mjs';
5新增:import { createSettingsWorkbench } from './browser-settings-fixture.mjs';
6新增:const engine = process.env.CAGE_TEST_BROWSER || 'chromium';
7新增:const output = await smokeCaptureDirectory('browser-settings-' + engine);
8新增:const f = await createSettingsWorkbench();
9新增:const { page, controller, fixtureState, errors } = f;
10新增:page.setDefaultTimeout(12000);
11新增:const checks = [];
12新增:const shot = name => page.screenshot({ path: join(output, name + '.png'), animations: 'disabled' });
13新增:try {
14新增: await page.getByRole('button', { name: '打开浏览器', exact: true }).click();
15新增: await page.getByRole('button', { name: '浏览器菜单', exact: true }).click();
16新增: await page.getByRole('menuitem', { name: '设置', exact: true }).click();
17新增: const settings = page.getByRole('region', { name: '浏览器设置', exact: true });
18新增: const nav = settings.getByRole('navigation', { name: '浏览器设置分类' });
19新增: await settings.waitFor();
20新增: const address = settings.getByRole('textbox', { name: '新标签页地址', exact: true });
21新增: const nextHome = controller.origin + '/custom';
22新增: await address.fill(nextHome);
23新增: await nav.getByRole('button', { name: '外观', exact: true }).click();
24新增: await nav.getByRole('button', { name: '新标签页', exact: true }).click();
25新增: assert.equal(await address.inputValue(), nextHome, 'switching categories preserves unsaved address');
26新增: fixtureState.failSave = true;
27新增: await settings.getByRole('button', { name: '保存地址', exact: true }).click();
28新增: await settings.getByRole('alert').getByText('保存浏览器设置失败,请重试', { exact: true }).waitFor();
29新增: assert.equal(await address.inputValue(), nextHome);
30新增: fixtureState.failSave = false;
31新增: await settings.getByRole('button', { name: '保存地址', exact: true }).click();
32新增: await settings.getByRole('status').getByText('已保存', { exact: true }).waitFor();
33新增: await shot('new-tab-settings');
34新增: await page.getByRole('button', { name: '新建网页', exact: true }).click();
35新增: await controller.waitFor(async () => (await controller.api('/tabs')).tabs.some(tab => tab.url === nextHome), 'new page uses saved address');
36新增: await page.waitForFunction(url => document.querySelector('.address-bar input')?.value === url, nextHome);
37新增: await page.getByRole('button', { name: '浏览器菜单', exact: true }).click();
38新增: await page.getByRole('menuitem', { name: '设置', exact: true }).click();
39新增: await settings.waitFor();
40新增: assert.equal(await page.getByRole('tab', { name: '设置', exact: true }).count(), 1);
41新增: await nav.getByRole('button', { name: '外观', exact: true }).click();
42新增: const layout = settings.getByRole('combobox', { name: '标签栏布局', exact: true });
43新增: await layout.click();
44新增: await settings.getByRole('option', { name: '竖排(左侧)', exact: true }).click();
45新增: await page.getByRole('complementary', { name: '竖排标签栏' }).waitFor();
46新增: await page.reload();
47新增: await page.getByRole('button', { name: '打开浏览器', exact: true }).click();
48新增: await page.getByRole('complementary', { name: '竖排标签栏' }).waitFor();
49新增: await settings.waitFor();
50新增: await nav.getByRole('button', { name: '新标签页', exact: true }).click();
51新增: assert.equal(await address.inputValue(), nextHome);
52新增: checks.push('real menu opens and reuses settings tab; unsaved form survives category changes; save failure retains input; saved default affects new tabs; address and layout survive reload');
53新增:
54新增: await page.getByRole('button', { name: /^设置/ }).filter({ has: page.locator('svg') }).first().click();
55新增: const globalSettings = page.getByRole('region', { name: '设置', exact: true });
56新增: await globalSettings.waitFor();
57新增: assert.equal(await globalSettings.getByRole('button', { name: '浏览器', exact: true }).count(), 0);
58新增: assert.equal(await globalSettings.getByText('浏览器默认网站', { exact: true }).count(), 0);
59新增: await globalSettings.getByRole('button', { name: '返回工作台', exact: true }).first().click();
60新增: await nav.getByRole('button', { name: '扩展', exact: true }).click();
61新增: await settings.getByText('让浏览器更合用', { exact: true }).waitFor();
62新增: await settings.getByRole('button', { name: '从本机导入', exact: true }).click();
63新增: const importer = settings.getByRole('region', { name: '从本机导入扩展', exact: true });
64新增: await importer.getByText('阅读助手', { exact: true }).waitFor();
65新增: assert.equal(await importer.getByRole('checkbox').nth(1).isDisabled(), true);
66新增: await importer.getByRole('button', { name: '选择全部兼容扩展', exact: true }).click();
67新增: await importer.getByRole('button', { name: '导入所选扩展(1)', exact: true }).click();
68新增: await importer.getByText('已导入,保持停用', { exact: true }).waitFor();
69新增: await shot('import-results');
70新增: await importer.getByRole('button', { name: '完成并关闭', exact: true }).click();
71新增: await importer.waitFor({ state: 'hidden' });
72新增: const enabled = settings.getByRole('checkbox', { name: '启用 阅读助手', exact: true });
73新增: assert.equal(await enabled.isChecked(), false);
74新增: await enabled.click();
75新增: await page.waitForFunction(() => document.querySelector('input[aria-label="启用 阅读助手"]')?.checked === true);
76新增: await controller.waitFor(async () => (await controller.api('/extensions', { mode: 'list' })).items.some(item => item.enabled), 'enable imported extension');
77新增: await settings.evaluate(element => { element.scrollTop = 0; });
78新增: await shot('extensions-imported');
79新增: const web = await controller.api('/new', { url: controller.origin + '/import-test' });
80新增: await controller.waitFor(() => controller.evaluate(web.id, 'document.documentElement.dataset.cageSettingsExtension === "active"'), 'imported extension runs');
81新增: await page.getByRole('tab', { name: '设置', exact: true }).click();
82新增: await settings.getByRole('button', { name: '刷新扩展', exact: true }).click();
83新增: await settings.getByRole('button', { name: '移除', exact: true }).click();
84新增: await page.getByRole('dialog', { name: '移除此扩展?', exact: true }).getByRole('button', { name: '移除扩展', exact: true }).click();
85新增: await settings.getByText('让浏览器更合用', { exact: true }).waitFor();
86新增: checks.push('global settings no longer own browser preferences; local import shows per-extension compatibility and permissions, skips legacy extensions, preserves disabled state; enable runs real content script and removal works');
87新增:
88新增: const file = settings.getByLabel('选择扩展 ZIP', { exact: true });
89新增: await file.setInputFiles({ name: 'reading-extension.zip', mimeType: 'application/zip', buffer: f.archive });
90新增: const preview = settings.getByRole('region', { name: '确认扩展安装', exact: true });
91新增: await preview.getByText('storage', { exact: true }).waitFor();
92新增: await preview.getByRole('button', { name: '取消', exact: true }).click();
93新增: assert.equal((await controller.api('/extensions', { mode: 'list' })).items.length, 0);
94新增: await file.setInputFiles({ name: 'reading-extension.zip', mimeType: 'application/zip', buffer: f.archive });
95新增: await preview.getByRole('button', { name: '安装扩展', exact: true }).click();
96新增: await page.waitForFunction(() => document.querySelector('input[aria-label="启用 阅读助手"]')?.checked === true);
97新增: checks.push('ZIP install shows permissions before confirmation; cancel installs nothing; confirming installs the real extension');
98新增: await settings.getByRole('textbox', { name: '搜索浏览器设置', exact: true }).fill('新标签');
99新增: await address.waitFor();
100新增: await settings.getByRole('textbox', { name: '搜索浏览器设置', exact: true }).fill('');
101新增: await nav.getByRole('button', { name: '外观', exact: true }).click();
102新增: await page.setViewportSize({ width: 820, height: 558 });
103新增: await shot('minimum-window');
104新增: assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth + 1), false);
105新增: await page.setViewportSize({ width: 1280, height: 850 });
106新增: await page.evaluate(() => { document.documentElement.style.zoom = '2'; });
107新增: await settings.getByRole('combobox', { name: '浏览器设置分类', exact: true }).waitFor();
108新增: await settings.getByRole('combobox', { name: '标签栏布局', exact: true }).scrollIntoViewIfNeeded();
109新增: await shot('zoom-200');
110新增: assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth + 1), false);
111新增: await page.evaluate(() => { document.documentElement.style.zoom = ''; });
112新增: assert.deepEqual(errors, []);
113新增: await writeFile(join(output, 'result.json'), JSON.stringify({ passed: true, engine, checks }, null, 2) + '\n');
114新增: console.log(JSON.stringify({ passed: true, engine, checks }, null, 2));
115新增:} catch (error) { await shot('failure'); throw error; }
116新增:finally { await f.close(); }
新增ui/scripts/browser-vertical-tabs-smoke.mjs+150 −0看文件
@@ -0,0 +1,150 @@
1新增:import assert from "node:assert/strict";
2新增:import fs from "node:fs/promises";
3新增:import { fileURLToPath } from "node:url";
4新增:import { createWorkbench } from "./workbench-fixture.mjs";
5新增:import { startDisplay } from "./rfb-wire-fixture.mjs";
6新增:
7新增:const engine = process.env.CAGE_TEST_BROWSER || "chromium";
8新增:const output = new URL(`../../docs/test-reports/2026-11-07-browser-vertical-tabs/${engine}/`, import.meta.url);
9新增:await fs.mkdir(output, { recursive: true });
10新增:const display = await startDisplay(process.env.CAGE_UI_URL || "http://127.0.0.1:5198", { frameInterval: 200 });
11新增:const { browser, page, state, errors } = await createWorkbench({ url: display.url, mockWebSockets: engine === "webkit" });
12新增:page.setDefaultTimeout(10000);
13新增:const checks = [];
14新增:const tabs = page.getByRole("tablist", { name: "浏览器标签页", exact: true });
15新增:const settings = page.getByRole("region", { name: "浏览器设置", exact: true });
16新增:const rail = page.getByRole("complementary", { name: "竖排标签栏", exact: true });
17新增:const shot = name => page.screenshot({ path: fileURLToPath(new URL(name + ".png", output)) });
18新增:async function openSettings() {
19新增: await page.getByRole("button", { name: "浏览器菜单", exact: true }).last().click();
20新增: await page.getByRole("menuitem", { name: "设置", exact: true }).click();
21新增: await settings.getByRole("navigation", { name: "浏览器设置分类" }).getByRole("button", { name: "外观", exact: true }).click();
22新增:}
23新增:async function closeSettings() {
24新增: await page.getByRole("button", { name: "关闭 设置", exact: true }).click();
25新增: await settings.waitFor({ state: "hidden" });
26新增:}
27新增:async function drag(from, to) {
28新增: const a = await from.boundingBox(), b = await to.boundingBox();
29新增: await page.mouse.move(a.x + a.width / 2, a.y + a.height / 2);
30新增: await page.mouse.down();
31新增: await page.mouse.move(b.x + b.width / 2, b.y + b.height / 2, { steps: 12 });
32新增: await page.mouse.up();
33新增:}
34新增:try {
35新增: state.status.ready = state.status.vm_running = true;
36新增: state.tabs = Array.from({ length: 5 }, (_, i) => ({
37新增: id: `tab-${i}`, kind: i === 4 ? "editor" : "web", title: `测试网页 ${i}`,
38新增: workspace: i === 4 ? state.settings.workspace : undefined, url: `https://example.test/${i}`,
39新增: }));
40新增: state.active = "tab-0";
41新增: await page.reload();
42新增: await page.getByRole("button", { name: "打开浏览器", exact: true }).click();
43新增: if (engine !== "webkit") await page.locator(".remote-canvas canvas").waitFor();
44新增: assert.equal(await tabs.getAttribute("aria-orientation"), "horizontal");
45新增: const surface = await page.locator(".remote-view").elementHandle();
46新增: await openSettings();
47新增: const picker = page.getByRole("combobox", { name: "标签栏布局", exact: true });
48新增: const help = settings.getByText("浏览器设置页跟随 Cage 当前的字体与配色。", { exact: true });
49新增: await settings.locator('.browser-settings-section').evaluate(element => Promise.all(element.getAnimations().map(animation => animation.finished)));
50新增: const before = await help.boundingBox();
51新增: await picker.click();
52新增: const expanded = await help.boundingBox();
53新增: assert.ok(expanded.y > before.y + 40, "options must push the following content down");
54新增: await page.keyboard.press("Escape");
55新增: assert.ok(Math.abs((await help.boundingBox()).y - before.y) < 1, "closing options restores the layout");
56新增: await picker.click();
57新增: await page.getByRole("option", { name: "竖排(左侧)", exact: true }).click();
58新增: await shot("browser-settings");
59新增: assert.equal(await picker.getAttribute("aria-expanded"), "false");
60新增: await closeSettings();
61新增: await rail.waitFor();
62新增: assert.equal(await tabs.getAttribute("aria-orientation"), "vertical");
63新增: assert.ok(await surface.evaluate(node => node === document.querySelector(".remote-view")), "changing layout must retain the remote-view component");
64新增: const first = tabs.getByRole("tab", { name: "测试网页 0", exact: true });
65新增: const second = tabs.getByRole("tab", { name: "测试网页 1", exact: true });
66新增: assert.ok((await second.boundingBox()).y > (await first.boundingBox()).y);
67新增: const railBox = await rail.boundingBox(), bodyBox = await page.locator(".browser-lane .pane-body").boundingBox();
68新增: assert.ok(railBox.x + railBox.width <= bodyBox.x + 1);
69新增: await shot("vertical-desktop");
70新增: await first.focus();
71新增: await page.keyboard.press("ArrowDown");
72新增: await page.waitForFunction(() => document.querySelector('[data-tab-id="tab-1"] [role="tab"]').getAttribute("aria-selected") === "true");
73新增: await page.keyboard.press("End");
74新增: await page.waitForFunction(() => document.querySelector('[data-tab-id="tab-4"] [role="tab"]').getAttribute("aria-selected") === "true");
75新增: await page.keyboard.press("Home");
76新增: await drag(first, tabs.getByRole("tab", { name: "测试网页 3", exact: true }));
77新增: await page.waitForFunction(() => [...document.querySelectorAll('.browser-tabs [role="tab"]')].findIndex(t => t.textContent === "测试网页 0") === 2);
78新增: await first.click({ button: "right" });
79新增: await page.getByRole("menuitem", { name: "置顶标签", exact: true }).click();
80新增: await page.waitForFunction(() => document.querySelector(".browser-tabs .browser-tab").dataset.tabId === "tab-0");
81新增: const order = await tabs.getByRole("tab").allTextContents();
82新增: await first.click({ button: "right" });
83新增: await page.getByRole("menuitem", { name: "重命名标签", exact: true }).click();
84新增: const rename = page.getByRole("dialog", { name: "重命名标签", exact: true });
85新增: await rename.getByRole("textbox").fill("命名后的网页");
86新增: await rename.getByRole("button", { name: "保存名称", exact: true }).click();
87新增: order[0] = "命名后的网页";
88新增: await page.reload();
89新增: await page.getByRole("button", { name: "打开浏览器", exact: true }).click();
90新增: await rail.waitFor();
91新增: assert.deepEqual(await tabs.getByRole("tab").allTextContents(), order);
92新增: await page.getByRole("button", { name: "新建网页", exact: true }).click();
93新增: await page.waitForFunction(() => document.querySelectorAll('.browser-tabs [role="tab"]').length === 6);
94新增: await tabs.getByRole("tab", { name: "测试网页 2", exact: true }).click();
95新增: await page.getByRole("button", { name: "关闭 测试网页 2", exact: true }).click();
96新增: await tabs.getByRole("tab", { name: "测试网页 2", exact: true }).waitFor({ state: "hidden" });
97新增: checks.push("横排默认值;设置下拉内嵌展开与收起;竖排切换保留画面组件;上下键和 Home/End;拖动排序、置顶、刷新保留、新建和关闭");
98新增:
99新增: // Drag from the rail into the page to exercise native dual-browser splitting.
100新增: await drag(tabs.getByRole("tab", { name: "测试网页 3", exact: true }), page.locator(".browser-lane .pane-body"));
101新增: await page.waitForFunction(() => document.querySelectorAll(".browser-header-cell").length === 2);
102新增: assert.equal(await rail.count(), 1);
103新增: assert.equal(await tabs.count(), 1);
104新增: assert.ok(state.split?.left && state.split?.right);
105新增: await page.locator(".browser-header-cell").first().getByRole("button", { name: "退出分屏", exact: true }).click();
106新增: await page.waitForFunction(() => document.querySelectorAll(".browser-header-cell").length === 1);
107新增: checks.push("竖排标签拖入网页进入双网页分屏;共享一列标签;退出分屏");
108新增:
109新增: for (let i = 5; i < 35; i++) state.tabs.push({ id: `tab-${i}`, kind: "web", title: `更多网页 ${i}`, url: `https://example.test/${i}` });
110新增: await page.waitForFunction(() => document.querySelectorAll('.browser-tabs [role="tab"]').length === 35);
111新增: await page.getByRole("button", { name: "收起侧栏", exact: true }).click();
112新增: for (const width of [1280, 820, 375]) {
113新增: await page.setViewportSize({ width, height: 850 });
114新增: await tabs.getByRole("tab").first().focus();
115新增: await page.keyboard.press("End");
116新增: await page.waitForFunction(() => {
117新增: const list = document.querySelector(".browser-tabs"), selected = list.querySelector('[aria-selected="true"]');
118新增: const a = list.getBoundingClientRect(), b = selected.getBoundingClientRect();
119新增: return list.scrollHeight > list.clientHeight && list.scrollWidth <= list.clientWidth + 1 && b.y >= a.y && b.bottom <= a.bottom + 1;
120新增: });
121新增: assert.ok((await page.locator(".browser-lane .pane-body").boundingBox()).width > 100);
122新增: await shot("many-tabs-" + width);
123新增: }
124新增: checks.push("35 个标签在 1280/820/375 宽度下纵向滚动,键盘选中末项自动滚入视野,网页仍有可用空间");
125新增: await page.setViewportSize({ width: 1280, height: 850 });
126新增: await page.getByRole("button", { name: "展开侧栏", exact: true }).click();
127新增: await openSettings();
128新增: await picker.focus();
129新增: await page.keyboard.press("Enter");
130新增: await page.keyboard.press("Home");
131新增: await page.keyboard.press("Enter");
132新增: assert.equal(await picker.getAttribute("aria-expanded"), "false");
133新增: await closeSettings();
134新增: await rail.waitFor({ state: "hidden" });
135新增: assert.equal(await tabs.getAttribute("aria-orientation"), "horizontal");
136新增: await page.reload();
137新增: await page.getByRole("button", { name: "打开浏览器", exact: true }).click();
138新增: assert.equal(await tabs.getAttribute("aria-orientation"), "horizontal");
139新增: assert.equal(state.saves.length, 0, "layout preferences must not save or restart the guest environment");
140新增: assert.deepEqual(errors, []);
141新增: checks.push("键盘切回横排并刷新保留;未写入环境设置或重启环境;无页面异常");
142新增: await fs.writeFile(new URL("result.json", output), JSON.stringify({ passed: true, checks, scope: `真实 React DOM 与存储;${engine === "webkit" ? "显示连接使用替身" : "WebSocket/RFB 使用隔离显示服务"};客机网页与控制 API 使用隔离替身,未实测三平台原生应用。` }, null, 2));
143新增: console.log(JSON.stringify({ passed: true, checks }, null, 2));
144新增:} catch (error) {
145新增: await shot("failure");
146新增: throw error;
147新增:} finally {
148新增: await browser.close();
149新增: await display.close();
150新增:}
修改ui/scripts/claude-accounts-smoke.mjs+15 −4看文件
@@ -100,6 +100,7 @@ async function checkLocalCountdown() {
100100 await openAccounts();
101101 const row = page.getByRole("article", { name: "工作", exact: true });
102102 await row.getByText("5秒后", { exact: true }).waitFor();
103新增: await row.getByText("最近更新 刚刚", { exact: true }).waitFor();
103104 await page.getByText("正在请求账号用量…").waitFor({ state: "hidden" });
104105 const requestsBefore = accountRequests;
105106 const wavesBefore = usageRequests.filter((r) => r.action === "usage_panel").length;
@@ -121,6 +122,10 @@ async function checkLocalCountdown() {
121122 assert.equal(joins.length, joinedBefore, "discovering a new default identity during polling cannot enroll it");
122123 assert.equal(usageRequests.filter((r) => r.action === "usage_panel").length, wavesBefore, "12-second panel polling cannot start another usage query");
123124 assert.ok(usageRequests.some((r) => !r.action && r.visible), "a visible panel keeps the existing queue alive via GET");
125新增: await page.clock.runFor(47_000);
126新增: await row.getByText("最近更新 1分钟前", { exact: true }).waitFor();
127新增: await page.clock.runFor(240_000);
128新增: await row.getByText("最近更新 5分钟前", { exact: true }).waitFor();
124129}
125130
126131async function checkUsagePanel() {
@@ -187,7 +192,7 @@ try {
187192 if (body?.action === "join") {
188193 joins.push(body);
189194 if (!defaultLogin || body.identity !== defaultLogin.identity)
190删除: return route.fulfill({ status: 409, body: "普通终端登录已改变,请确认当前身份" });
195新增: return route.fulfill({ status: 409, contentType: "text/plain; charset=utf-8", body: "普通终端登录已改变,请确认当前身份" });
191196 profiles.push({ id: "default-" + defaultLogin.identity, source: "default", label: defaultLogin.email,
192197 email: defaultLogin.email, plan: defaultLogin.plan, enabled: true, status: "ready" });
193198 }
@@ -199,7 +204,7 @@ try {
199204 if (body?.action === "update") Object.assign(profiles.find((a) => a.id === body.id),
200205 body.label !== undefined ? { label: body.label } : { enabled: body.enabled });
201206 if (body?.action === "refresh" && failRefresh)
202删除: return route.fulfill({ status: 503, body: "暂时无法检查登录" });
207新增: return route.fulfill({ status: 503, contentType: "text/plain; charset=utf-8", body: "暂时无法检查登录" });
203208 if (body?.action === "refresh" && heldRefresh) await heldRefresh.promise;
204209 if (body?.action === "refresh_default") {
205210 assert.equal(body.identity, defaultLogin?.identity);
@@ -215,7 +220,7 @@ try {
215220 if (!body) return route.fulfill({ json: state.terminals });
216221 starts.push(body);
217222 if (body.kind === "claude" && profiles.length && !profiles[assignedProfile].enabled)
218删除: return route.fulfill({ status: 409, body: "没有可用 Claude 账号" });
223新增: return route.fulfill({ status: 409, contentType: "text/plain; charset=utf-8", body: "没有可用 Claude 账号" });
219224 const terminal = { id: String(starts.length), title: "终端 " + starts.length, kind: body.kind,
220225 workspace: body.workspace, claude_account_id: body.kind === "claude-login" ? body.claude_account_id || "one"
221226 : body.kind === "claude" ? profiles[assignedProfile]?.id : undefined,
@@ -305,7 +310,11 @@ try {
305310 await card.getByText("重置时间未知", { exact: true }).waitFor();
306311 const oldWeek = card.getByRole("group", { name: "7d 额度" }).getByText(/^上次 100% ·/);
307312 assert.equal(await oldWeek.locator("time").getAttribute("datetime"), new Date((now - 7200) * 1000).toISOString());
308删除: assert.notEqual((await card.getByText(/^上次查询 /).innerText()).slice(5), (await card.getByText(/^最近读数 /).innerText()).slice(5));
313新增: const updated = card.getByText(/^最近更新 /);
314新增: assert.equal(await updated.count(), 1);
315新增: assert.equal(await updated.locator("time").getAttribute("datetime"), new Date((now - 3600) * 1000).toISOString(),
316新增: "a newer query must not make retained quota readings appear fresh");
317新增: assert.equal(await card.getByText(/^(上次查询|最近读数) /).count(), 0);
309318 heldRefresh = null;
310319 await back();
311320 await launchClaude();
@@ -345,6 +354,8 @@ try {
345354 assert.equal(profiles.length, 1, "detected identity is not in the pool");
346355 await detectedA.getByRole("button", { name: "检查状态" }).click();
347356 await detectedA.getByText("本次未返回额度").waitFor();
357新增: assert.equal(await detectedA.getByText(/^最近更新 /).locator("time").getAttribute("datetime"), new Date(now * 1000).toISOString(),
358新增: "accounts without readings fall back to the latest query time");
348359 assert.equal(await detectedA.getByText("暂无读数", { exact: true }).count(), 2);
349360 assert.deepEqual(usageRequests.filter((r) => r.action === "refresh_default").at(-1), { action: "refresh_default", identity: identityA.identity, visible: false });
350361 await detectedA.getByRole("button", { name: "加入调度" }).click();
新增ui/scripts/cli-session-management-smoke.mjs+161 −0看文件
@@ -0,0 +1,161 @@
1新增:import assert from "node:assert/strict";
2新增:import { mkdir } from "node:fs/promises";
3新增:import { createWorkbench } from "./workbench-fixture.mjs";
4新增:
5新增:const base = process.env.CAGE_UI_URL || "http://127.0.0.1:5209";
6新增:const output = process.env.CAGE_TEST_CAPTURE || "../docs/test-reports/2026-11-07-cli-session-sync";
7新增:const workspace = "/Users/shihao/.claude-cage-workspace";
8新增:const id = "12345678-1234-4321-aaaa-123456789abc";
9新增:const otherID = "12345678-1234-4321-aaaa-123456789abd";
10新增:const otherProject = "/Users/shihao/Projects/mobile";
11新增:const sessions = [
12新增: {id, workspace, title:"电脑保留的历史", terminal_available:true, revision:1, updated_at:"2026-11-07T08:00:00Z",
13新增: turns:[{id:"turn-1", prompt:"原来的问题", text:"原来的回答", status:"completed"}]},
14新增: {id:otherID, workspace, title:"另一段会话", revision:1, updated_at:"2026-11-07T07:00:00Z", turns:[]},
15新增: {id:"12345678-1234-4321-aaaa-123456789abe", workspace, title:"准备发布说明", archived:true, pinned:true, updated_at:"2026-11-06T09:00:00Z", turns:[]},
16新增: {id:"12345678-1234-4321-aaaa-123456789abf", workspace, title:"核对接口", archived:true, updated_at:"2026-11-05T08:00:00Z", turns:[]},
17新增: {id:"12345678-1234-4321-aaaa-123456789ac0", workspace:otherProject, title:"移动端布局检查", archived:true, updated_at:"2026-11-04T08:00:00Z", turns:[]},
18新增:];
19新增:let state, failPurge = true, failOpen = true, opens = 0, releaseOpen;
20新增:const handle = async (route, path, body) => {
21新增: const archived = new URL(route.request().url()).searchParams.get("archived") === "true";
22新增: if (path === "/cli/sessions") return route.fulfill({json:{sessions:sessions.filter(s => Boolean(s.archived) === archived),notice:""}});
23新增: const session = sessions.find(s => path.includes(s.id));
24新增: if (!session) return route.fulfill({status:404});
25新增: if (path.endsWith("/open")) {
26新增: opens++;
27新增: if (failOpen) return route.fulfill({status:409,contentType:"text/plain; charset=utf-8",body:"测试:原终端仍在运行,请先退出其中的 Claude Code"});
28新增: await new Promise(resolve => { releaseOpen = resolve; });
29新增: const terminal = {id:"restored-terminal", kind:"claude", workspace, title:session.title, cli_session_id:session.id};
30新增: state.terminals = [terminal];
31新增: return route.fulfill({json:{...session,desktop_terminal_id:terminal.id}});
32新增: }
33新增: if (path.endsWith("/archive")) {
34新增: session.archived = true; session.revision++;
35新增: state.terminals = state.terminals.filter(t => t.cli_session_id !== session.id);
36新增: } else if (path.endsWith("/restore")) {
37新增: session.archived = false; session.revision++;
38新增: } else if (path.endsWith("/purge")) {
39新增: assert.equal(body.confirm,true);
40新增: if (failPurge) return route.fulfill({status:503,contentType:"text/plain; charset=utf-8",body:"删除连接中断,请重试"});
41新增: sessions.splice(sessions.indexOf(session),1);
42新增: } else if (path.endsWith("/metadata")) Object.assign(session,body);
43新增: return route.fulfill({json:session});
44新增:};
45新增:const desktop = await createWorkbench({url:base, cliRequest:handle});
46新增:state = desktop.state;
47新增:const {page,browser,errors} = desktop;
48新增:try {
49新增: state.status.ready = state.status.vm_running = true;
50新增: state.status.projects = [workspace, otherProject];
51新增: const history = page.getByRole("button",{name:"电脑保留的历史",exact:true});
52新增: await history.waitFor();
53新增: await history.click();
54新增: await page.getByRole("status").filter({hasText:"测试:原终端仍在运行"}).waitFor();
55新增: assert.equal(await page.getByRole("dialog",{name:"电脑保留的历史"}).count(),0,"session click opened an intermediate preview");
56新增: assert.equal(await history.isEnabled(),true,"failed session open could not be retried");
57新增: failOpen = false;
58新增: await history.click();
59新增: await page.waitForFunction(() => document.querySelector('.sidebar-session[aria-busy="true"]')?.disabled);
60新增: assert.equal(await page.getByRole("button",{name:"另一段会话",exact:true}).isDisabled(),true,"another open was allowed during terminal restore");
61新增: releaseOpen();
62新增: await page.getByRole("tab",{name:"电脑保留的历史",exact:true}).waitFor();
63新增: assert.equal(await history.count(),0,"history duplicated its live terminal");
64新增: assert.equal(opens,2,"clicking one session sent duplicate open requests");
65新增: assert.equal(state.terminalConnections,1,"restored terminal did not connect");
66新增: assert.equal(state.requests.filter(r => r.path === "/cli/sessions/" + id).length,0,"desktop fetched a history preview");
67新增: await page.getByRole("tab",{name:"电脑保留的历史",exact:true}).hover();
68新增: await page.getByRole("group",{name:"电脑保留的历史 的操作"}).getByRole("button",{name:"归档",exact:true}).click();
69新增: await page.getByRole("dialog",{name:"归档这段会话?"}).getByRole("button",{name:"归档会话",exact:true}).click();
70新增: await page.getByRole("tab",{name:"电脑保留的历史",exact:true}).waitFor({state:"hidden"});
71新增: assert.deepEqual(errors,[],"desktop archive");
72新增:
73新增: const context = await browser.newContext({viewport:{width:390,height:844},isMobile:true,hasTouch:true,userAgent:"CageMobile/1"});
74新增: const phone = await context.newPage();
75新增: const phoneErrors = [];
76新增: phone.on("pageerror",error => phoneErrors.push(error.message));
77新增: await phone.route("**/api/**",async route => {
78新增: const path = new URL(route.request().url()).pathname.replace("/api/mobile/cli","/cli");
79新增: if (path.endsWith("/projects")) return route.fulfill({json:{host:"测试电脑",ready:true,shared_sessions:true,projects:[{path:workspace,name:"默认工作区"},{path:otherProject,name:"mobile"}]}});
80新增: return handle(route,path,route.request().postDataJSON());
81新增: });
82新增: await phone.goto(base+"/mobile.html");
83新增: const drawer = phone.getByRole("dialog",{name:"工作区侧栏"});
84新增: await drawer.getByRole("button",{name:"设置",exact:true}).click();
85新增: await phone.getByRole("button",{name:"已归档会话",exact:true}).click();
86新增: let archived = phone.getByRole("article").filter({has:phone.getByRole("heading",{name:"电脑保留的历史",exact:true})});
87新增: await archived.getByRole("button",{name:"取消归档"}).click();
88新增: await history.waitFor();
89新增: await phone.getByRole("button",{name:"返回设置"}).click();
90新增: await phone.getByRole("button",{name:"返回会话"}).click();
91新增: const row = drawer.locator(".swipe-session").filter({has:phone.getByRole("button",{name:"电脑保留的历史",exact:true})});
92新增: await row.getByRole("button",{name:"电脑保留的历史的更多操作"}).click();
93新增: await row.getByRole("button",{name:"归档",exact:true}).click();
94新增: await phone.getByRole("dialog",{name:"归档会话",exact:true}).getByRole("button",{name:"归档会话",exact:true}).click();
95新增: await history.waitFor({state:"hidden"});
96新增: assert.deepEqual(errors,[],"phone archive");
97新增:
98新增: await page.getByRole("button",{name:"设置",exact:true}).click();
99新增: await page.getByRole("navigation",{name:"设置分组"}).getByRole("button",{name:"已归档会话",exact:true}).click();
100新增: const panel = page.getByRole("region",{name:"已归档会话",exact:true});
101新增: const projectFilter = panel.getByRole("combobox",{name:"项目筛选"});
102新增: const group = panel.locator(".archive-project").first();
103新增: await group.waitFor();
104新增: const before = await group.boundingBox();
105新增: await projectFilter.click();
106新增: const options = panel.getByRole("listbox",{name:"项目筛选选项"});
107新增: const opened = await options.boundingBox();
108新增: const shifted = await group.boundingBox();
109新增: assert.ok(shifted.y > before.y + 20 && opened.y + opened.height <= shifted.y,"project filter covered content");
110新增: await projectFilter.press("Escape");
111新增: assert.ok(Math.abs((await group.boundingBox()).y - before.y) < 2,"filter did not restore layout");
112新增: await projectFilter.press("End"); await projectFilter.press("Enter");
113新增: await panel.getByRole("heading",{name:"移动端布局检查",exact:true}).waitFor();
114新增: assert.equal(await panel.getByRole("heading",{name:"电脑保留的历史",exact:true}).count(),0);
115新增: await projectFilter.press("Home"); await projectFilter.press("Enter");
116新增: const filter = panel.getByRole("combobox",{name:"会话筛选"});
117新增: await filter.click(); await panel.getByRole("option",{name:"已置顶",exact:true}).click();
118新增: assert.equal(await panel.getByRole("article").count(),1);
119新增: await filter.press("Home"); await filter.press("Enter");
120新增: const search = panel.getByRole("searchbox",{name:"搜索已归档的会话"});
121新增: await search.fill("核对");
122新增: assert.equal(await panel.getByRole("article").count(),1);
123新增: await search.fill("");
124新增: await panel.getByRole("heading",{name:".claude-cage-workspace",exact:true}).click();
125新增: await mkdir(output,{recursive:true});
126新增: await page.screenshot({path:output+"/"+(process.env.CAGE_TEST_BROWSER||"chromium")+"-archive-layout.png"});
127新增: const target = panel.getByRole("article").filter({has:page.getByRole("heading",{name:"电脑保留的历史",exact:true})});
128新增: await target.getByRole("button",{name:"删除会话",exact:true}).click();
129新增: await target.getByRole("button",{name:"永久删除",exact:true}).click();
130新增: await panel.getByRole("alert").filter({hasText:"删除连接中断"}).waitFor();
131新增: assert.equal(sessions.length,5,"failed purge removed history");
132新增: await mkdir(output,{recursive:true});
133新增: await page.screenshot({path:output+"/"+(process.env.CAGE_TEST_BROWSER||"chromium")+"-archived-desktop.png"});
134新增: failPurge = false;
135新增: await target.getByRole("button",{name:"永久删除",exact:true}).click();
136新增: await target.waitFor({state:"hidden"});
137新增: await phone.evaluate(() => window.dispatchEvent(new Event("cage-open-archives")));
138新增: await drawer.waitFor({state:"hidden"});
139新增: await phone.getByRole("heading",{name:"准备发布说明",exact:true}).waitFor();
140新增: assert.equal(await phone.getByRole("heading",{name:"电脑保留的历史",exact:true}).count(),0);
141新增: const phoneGroup = phone.locator(".archive-project").first();
142新增: const phoneBefore = await phoneGroup.boundingBox();
143新增: const phoneFilter = phone.getByRole("combobox",{name:"项目筛选"});
144新增: await phoneFilter.click();
145新增: const phoneOptions = await phone.getByRole("listbox",{name:"项目筛选选项"}).boundingBox();
146新增: assert.ok((await phoneGroup.boundingBox()).y >= phoneOptions.y + phoneOptions.height,"phone filter covered content");
147新增: await phoneFilter.press("Escape");
148新增: assert.ok(Math.abs((await phoneGroup.boundingBox()).y-phoneBefore.y)<2);
149新增: await phone.getByRole("heading",{name:"已归档会话",exact:true}).click();
150新增: await phone.screenshot({path:output+"/"+(process.env.CAGE_TEST_BROWSER||"chromium")+"-archived-mobile.png"});
151新增: assert.deepEqual(errors,[],"before reload");
152新增: await page.waitForLoadState("networkidle");
153新增: await page.reload();
154新增: await page.getByRole("button",{name:"另一段会话",exact:true}).waitFor();
155新增: assert.equal(await history.count(),0);
156新增: assert.equal(sessions.length,4);
157新增: assert.equal(sessions[0].id,otherID);
158新增: assert.deepEqual(errors,[]);
159新增: assert.deepEqual(phoneErrors,[]);
160新增: console.log("Persistent desktop history, terminal resume, bidirectional archive/restore, purge confirmation/failure/retry, reload passed");
161新增:} finally { await browser.close(); }
修改ui/scripts/desktop-downloads-smoke.mjs+8 −1看文件
@@ -44,6 +44,13 @@ try {
4444 await page.getByRole("button", { name: "下载文件", exact: true }).click();
4545 await dialog.getByText(item.path, { exact: true }).waitFor();
4646 assert.equal(calls.filter((call) => call.action === "saveBrowserDownload").length, 1, "history reopened a save dialog");
47新增: const openError = "文件打开关联未能完成,请在 Cage 下载列表中打开文件。";
48新增: downloads = [{ ...item, openError }];
49新增: await dialog.getByText(openError, { exact: true }).waitFor();
50新增: assert.equal(await page.getByRole("button", { name: "下载文件", exact: true }).getAttribute("title"), "有下载需要处理,点击查看");
51新增: await dialog.getByText(item.path, { exact: true }).waitFor();
52新增: downloads = [item];
53新增: await dialog.getByText(openError, { exact: true }).waitFor({ state: "hidden" });
4754 saved = [];
4855 downloads = [{ ...item, state: "failed", retryable: true, path: "", error: "共享目录暂时不可写" }];
4956 await page.reload();
@@ -52,5 +59,5 @@ try {
5259 await waitFor(() => retries === 1);
5360 assert.equal(await dialog.getByRole("button", { name: "另存为…", exact: true }).count(), 0);
5461 assert.deepEqual(errors, []);
55删除: console.log("PASS: Desktop instant export, native Save As cancel retains fallback, reveal, history does not reprompt, failed export uses Desktop retry");
62新增: console.log("PASS: Desktop instant export, native Save As cancel retains fallback, reveal, history does not reprompt, saved-file open warning and recovery, failed export uses Desktop retry");
5663} finally { await browser.close(); }
修改ui/scripts/diagnostics-smoke.mjs+19 −9看文件
@@ -13,7 +13,9 @@ const root = await fs.mkdtemp(path.join(os.tmpdir(), "cage-diagnostics-"));
1313const profile = path.join(root, "profile");
1414const env = { ...process.env, CLAUDE_CAGE_CONFIG: path.join(profile, "config.json") };
1515let browser;
16删除:const reportDirectory = path.resolve(process.env.CAGE_DIAGNOSTIC_REPORT || "docs/test-reports/2026-11-03-diagnostics");
16新增:const reportDirectory = process.env.CAGE_DIAGNOSTIC_REPORT
17新增: ? path.resolve(process.env.CAGE_DIAGNOSTIC_REPORT)
18新增: : await fs.mkdtemp(path.join(os.tmpdir(), "cage-diagnostics-report-"));
1719await fs.mkdir(reportDirectory, { recursive: true });
1820try {
1921 const { stdout } = await run(cage, ["desktop", "--json"], { env });
@@ -22,6 +24,7 @@ try {
2224 browser = await chromium.launch({ headless: true });
2325 const page = await browser.newPage({ acceptDownloads: true, viewport: { width: 1280, height: 900 } });
2426 await page.goto(entry.url);
27新增: await page.getByRole("button", { name: "使用用户名和密码", exact: true }).click();
2528 await page.getByLabel("用户名", { exact: true }).fill("诊断验证账户");
2629 await page.getByLabel("设置密码", { exact: true }).fill("Test-only-password-8712");
2730 await page.getByLabel("确认密码", { exact: true }).fill("Test-only-password-8712");
@@ -30,11 +33,13 @@ try {
3033 await page.getByRole("button", { name: "环境与恢复", exact: true }).click();
3134 await page.getByRole("heading", { name: "日志与诊断" }).waitFor();
3235 // Exercise browser event handlers, the actual authenticated endpoint and disk.
36新增: const reports = Promise.all(["diagnostic-ui-sentinel", "diagnostic-rejection-sentinel"].map(marker =>
37新增: page.waitForResponse(response => response.url().endsWith("/api/diagnostics/events") && response.request().postData()?.includes(marker) && response.ok())));
3338 await page.evaluate(() => {
3439 window.dispatchEvent(new ErrorEvent("error", { error: new Error("password=ui-private-secret diagnostic-ui-sentinel") }));
3540 window.dispatchEvent(new PromiseRejectionEvent("unhandledrejection", { promise: Promise.resolve(), reason: new Error("token=rejection-secret diagnostic-rejection-sentinel") }));
3641 });
37删除: await page.waitForResponse(response => response.url().endsWith("/api/diagnostics/events") && response.ok());
42新增: await reports;
3843 const downloaded = page.waitForEvent("download");
3944 await page.getByRole("button", { name: "导出诊断包", exact: true }).click();
4045 await (await downloaded).saveAs(path.join(root, "browser.zip"));
@@ -44,23 +49,28 @@ try {
4449 const nativeOutput = path.join(root, "native.zip");
4550 const saved = await run(cage, ["diagnostics", "--json", nativeOutput], { env });
4651 assert.equal(JSON.parse(saved.stdout).status, "ok");
52新增: const selected = await page.evaluate(async () => (await fetch("/api/client/context")).json());
53新增: const selectedOutput = path.join(root, "selected-native.zip");
54新增: const selectedSave = await run(cage, ["diagnostics", "--json", "--connection", selected.connection_id, selectedOutput], { env });
55新增: assert.equal(JSON.parse(selectedSave.stdout).status, "ok");
56新增: // Stop only this isolated controller, then check the offline ZIP as well.
57新增: await run(cage, ["prepare-update", "--json"], { env });
58新增: const offline = await run(cage, ["diagnostics", "--json", path.join(root, "offline.zip")], { env });
59新增: assert.equal(JSON.parse(offline.stdout).status, "ok");
4760 const checks = [];
48删除: for (const filename of ["browser.zip", "native.zip"]) {
61新增: for (const filename of ["browser.zip", "native.zip", "selected-native.zip", "offline.zip"]) {
4962 const { stdout: contents } = await run("uv", ["run", "--no-project", "python", "-c", "import sys,zipfile,json; z=zipfile.ZipFile(sys.argv[1]); print(json.dumps({'names':z.namelist(),'text':'\\n'.join(z.read(n).decode() for n in z.namelist())}))", path.join(root, filename)]);
5063 const parsed = JSON.parse(contents);
5164 assert.match(parsed.text, /diagnostic-ui-sentinel/);
5265 assert.match(parsed.text, /diagnostic-rejection-sentinel/);
5366 for (const secret of ["ui-private-secret", "rejection-secret", "Test-only-password-8712"]) assert.ok(!parsed.text.includes(secret), `secret in ${filename}`);
54删除: assert.ok(parsed.names.every(name => ["manifest.json", "README.txt"].includes(name) || name.startsWith("logs/")));
67新增: assert.ok(parsed.names.every(name => ["manifest.json", "README.txt", "desktop/manifest.json", "desktop/README.txt"].includes(name) || name.startsWith("logs/") || name.startsWith("desktop/logs/")));
68新增: assert.ok(parsed.names.some(name => name.startsWith("desktop/logs/")), `desktop log owner missing from ${filename}`);
5569 checks.push(`${filename}: valid redacted ZIP`);
5670 }
57删除: // Stop only this isolated controller, then verify offline recovery export.
58删除: await run(cage, ["prepare-update", "--json"], { env });
59删除: const offline = await run(cage, ["diagnostics", "--json", path.join(root, "offline.zip")], { env });
60删除: assert.equal(JSON.parse(offline.stdout).status, "ok");
6171 checks.push("real browser settings export", "frontend error and rejection captured", "offline CLI export", "no user files/config/terminal content");
6272 await fs.writeFile(path.join(reportDirectory, "browser-result.json"), JSON.stringify({ success: true, checks }, null, 2));
63删除: console.log(JSON.stringify({ success: true, checks }));
73新增: console.log(JSON.stringify({ success: true, reportDirectory, checks }));
6474} finally {
6575 await browser?.close();
6676 await run(cage, ["prepare-update", "--json"], { env }).catch(() => {});
修改ui/scripts/display-resolution-smoke.mjs+22 −6看文件
@@ -11,10 +11,12 @@ page.setDefaultTimeout(10000);
1111const output = process.env.CAGE_DISPLAY_REPORT || "/tmp/cage-display-resolution";
1212const requests = [], actions = [];
1313let failResize = false;
14新增:let runningDensity; // Existing guests/servers omit the density field.
15新增:state.settings.balanced_display = false;
1416const desktop = { installed: true, running: true, managed: true, version: "fixture" };
1517await page.route("**/api/claude-desktop**", async (route) => {
1618 const path = new URL(route.request().url()).pathname;
17删除: if (path.endsWith("/vnc-credentials")) return route.fulfill({ json: { password: "fixture" } });
19新增: if (path.endsWith("/vnc-credentials")) return route.fulfill({ json: { password: "fixture", display_scale: runningDensity } });
1820 if (path.endsWith("/resize")) {
1921 const size = route.request().postDataJSON();
2022 requests.push(size);
@@ -26,15 +28,15 @@ await page.route("**/api/claude-desktop**", async (route) => {
2628 actions.push(path);
2729 return route.fulfill({ json: { ok: true } });
2830});
29删除:async function matched(zoom = 1) {
30删除: await page.waitForFunction((zoom) => {
31新增:async function matched(zoom = 1, density = runningDensity ?? 2) {
32新增: await page.waitForFunction(({ zoom, density }) => {
3133 const box = document.querySelector(".claude-desktop-view .remote-canvas"), canvas = box?.querySelector("canvas");
3234 if (!canvas) return false;
3335 const bounds = box.getBoundingClientRect(), shown = canvas.getBoundingClientRect();
34删除: return canvas.width === Math.floor(bounds.width * 2 / zoom) &&
35删除: canvas.height === Math.floor(bounds.height * 2 / zoom) &&
36新增: return canvas.width === Math.floor(bounds.width * density / zoom) &&
37新增: canvas.height === Math.floor(bounds.height * density / zoom) &&
3638 Math.abs(shown.width - bounds.width) < 2 && Math.abs(shown.height - bounds.height) < 2;
37删除: }, zoom, { timeout: 10000 });
39新增: }, { zoom, density }, { timeout: 10000 });
3840}
3941try {
4042 state.status.vm_running = state.status.ready = true;
@@ -88,6 +90,20 @@ try {
8890 await matched();
8991 await page.setViewportSize({ width: 820, height: 558 });
9092 await matched();
93新增: await page.getByRole("button", { name: "设置", exact: true }).click();
94新增: await page.getByRole("switch", { name: /流畅画质/ }).check();
95新增: await page.getByRole("button", { name: "保存设置", exact: true }).click();
96新增: await page.getByRole("region", { name: "设置", exact: true }).waitFor({ state: "hidden" });
97新增: assert.equal(state.settings.balanced_display, true);
98新增: await matched(1, 2); // Reconnect to the application that was already running.
99新增: runningDensity = 1.5;
100新增: await page.reload();
101新增: await page.getByRole("button", { name: "Claude Desktop", exact: true }).click();
102新增: await matched();
103新增: await chooseInline(selector, "1.25");
104新增: await matched(1.25);
105新增: await chooseInline(selector, "1");
106新增: await matched();
91107 assert.deepEqual(actions, [], "display changes must not restart the application");
92108 assert.deepEqual(errors, []);
93109 await page.screenshot({ path: `${output}/small-window.png` });
修改ui/scripts/environment-smoke.mjs+6 −6看文件
@@ -52,18 +52,18 @@ try {
5252 "https://www.bing.com/",
5353 );
5454 assert.equal(state.tabs[0].url, "https://www.bing.com/");
55删除: await page.getByRole("button", { name: /^设置/ }).click();
56删除: await page.getByLabel("浏览器默认网站").fill("https://example.com/start");
55新增: await page.getByRole("button", { name: "浏览器菜单", exact: true }).click();
56新增: await page.getByRole("menuitem", { name: "设置", exact: true }).click();
57新增: await page.getByLabel("新标签页地址", { exact: true }).fill("https://example.com/start");
5758 assert.equal(
5859 await page.getByRole("button", { name: "保存并重启", exact: true }).count(),
5960 0,
6061 );
6162 const starts = state.requests.filter((r) => r.path === "/start").length;
6263 await shot("settings");
63删除: await page.getByRole("button", { name: "保存设置", exact: true }).click();
64删除: await page
65删除: .getByRole("heading", { name: "设置", exact: true })
66删除: .waitFor({ state: "hidden" });
64新增: await page.getByRole("button", { name: "保存地址", exact: true }).click();
65新增: await page.getByText("已保存", { exact: true }).waitFor();
66新增: await page.getByRole("button", { name: "关闭 设置", exact: true }).click();
6767 assert.equal(state.settings.browser_home_url, "https://example.com/start");
6868 assert.equal(
6969 state.requests.filter((r) => r.path === "/start").length,
修改ui/scripts/environment-storage-smoke.mjs+40 −9看文件
@@ -1,20 +1,27 @@
11import assert from "node:assert/strict";
22import { createWorkbench } from "./workbench-fixture.mjs";
33
4删除:const { browser, page, state, errors } = await createWorkbench();
4新增:const platform = process.env.CAGE_STORAGE_PLATFORM || "windows";
5新增:const { browser, page, state, errors } = await createWorkbench({
6新增: viewport: { width: Number(process.env.CAGE_STORAGE_WIDTH || 1280), height: 850 },
7新增: clientContext: { mode: "local", connection_id: "local", client_platform: platform, server_platform: platform, connection: { state: "disconnected" } },
8新增:});
59try {
610 state.status.local_vm_storage = true;
7删除: let location = { directory: "C:\\Users\\demo\\.claude-cage\\state", has_environment: false };
11新增: const windows = platform === "windows";
12新增: let location = { directory: windows ? "C:\\Users\\demo\\.claude-cage\\state" : "/home/demo/.claude-cage/state", has_environment: false };
813 const writes = [];
9删除: const destination = "D:\\开发工具\\Cage 环境";
14新增: const destination = windows ? "D:\\开发工具\\Cage 环境" : "/Volumes/开发工具/Cage 环境";
15新增: const occupied = windows ? "E:\\occupied" : "/mnt/occupied";
16新增: const migrated = windows ? "E:\\Cage 环境" : "/mnt/Cage 环境";
1017 await page.route("**/api/environment/storage", (route) => {
1118 if (route.request().method() === "GET") return route.fulfill({ json: location });
1219 const input = route.request().postDataJSON();
1320 writes.push(input);
1421 const rejected = input.directory.endsWith("occupied");
15删除: const job = { kind: "storage", id: String(writes.length), running: false, error: rejected ? "目录必须为空" : "" };
22新增: const job = { kind: "storage", id: String(writes.length), running: !rejected && input.migrate, error: rejected ? "目录必须为空" : "", message: "正在复制并校验虚拟磁盘,请保持 Cage 开启。" };
1623 state.status.job = job;
17删除: if (!rejected) location = { ...location, directory: input.directory, backup: location.has_environment ? location.directory : "" };
24新增: if (!rejected && !job.running) location = { ...location, directory: input.directory, backup: location.has_environment ? location.directory : "" };
1825 return route.fulfill({ json: job });
1926 });
2027 await page.getByRole("button", { name: "选择环境存储位置" }).click();
@@ -34,20 +41,44 @@ try {
3441 await page.reload();
3542 await page.getByRole("button", { name: "选择环境存储位置" }).click();
3643 await panel.getByText(destination, { exact: true }).waitFor();
37删除: await target.fill("E:\\occupied");
44新增: await target.fill(occupied);
3845 await panel.getByRole("button", { name: "迁移到此位置" }).click();
3946 await page.getByRole("dialog").getByRole("button", { name: "取消" }).click();
4047 assert.equal(writes.length, 1);
4148 await panel.getByRole("button", { name: "迁移到此位置" }).click();
4249 await page.getByRole("dialog").getByRole("button", { name: "迁移环境" }).click();
4350 await panel.getByText("目录必须为空", { exact: true }).waitFor();
44删除: await target.fill("E:\\Cage 环境");
51新增: await target.fill(migrated);
4552 await panel.getByRole("button", { name: "迁移到此位置" }).click();
4653 await page.getByRole("dialog").getByRole("button", { name: "迁移环境" }).click();
47删除: await panel.getByText("E:\\Cage 环境", { exact: true }).waitFor();
54新增: const progress = panel.getByRole("status");
55新增: await progress.waitFor();
56新增: const actions = panel.locator(".storage-actions");
57新增: await actions.scrollIntoViewIfNeeded();
58新增: const geometry = await panel.evaluate((element) => {
59新增: const buttons = element.querySelector(".storage-actions").getBoundingClientRect();
60新增: const status = element.querySelector('[role="status"]').getBoundingClientRect();
61新增: return { buttonsBottom: buttons.bottom, statusTop: status.top };
62新增: });
63新增: if (process.env.CAGE_STORAGE_SCREENSHOT) {
64新增: await panel.getByRole("heading", { name: "本机环境存储" }).scrollIntoViewIfNeeded();
65新增: await page.screenshot({ path: process.env.CAGE_STORAGE_SCREENSHOT });
66新增: }
67新增: assert.ok(geometry.statusTop >= geometry.buttonsBottom + 8, `Migration status overlaps actions: ${JSON.stringify(geometry)}`);
68新增: for (const button of await actions.getByRole("button").all()) {
69新增: assert.equal(await button.isDisabled(), true);
70新增: assert.equal(await button.evaluate((element) => getComputedStyle(element).opacity), "1");
71新增: }
72新增: assert.equal(await target.isDisabled(), true);
73新增: assert.equal(writes.length, 3);
74新增: location = { ...location, directory: writes.at(-1).directory, backup: location.directory };
75新增: state.status.job = { ...state.status.job, running: false };
76新增: await panel.getByText(migrated, { exact: true }).waitFor();
77新增: await page.waitForFunction(() => !document.querySelector('.environment-storage input').disabled);
78新增: assert.equal(await progress.count(), 0);
4879 assert.equal(writes.at(-1).migrate, true);
4980 assert.equal(writes.at(-1).previous, destination);
5081 assert.equal(await panel.locator("code").textContent(), destination);
5182 assert.deepEqual(errors, []);
52删除: console.log("Storage selection, picker cancellation, migration confirmation, failure and backup location passed");
83新增: console.log(`Storage selection, picker cancellation, migration confirmation, running layout, failure and backup location passed (${platform}, ${process.env.CAGE_TEST_BROWSER || "chromium"}, ${page.viewportSize().width}px; status gap ${geometry.statusTop - geometry.buttonsBottom}px)`);
5384} finally { await browser.close(); }
新增ui/scripts/exit-policy-region-smoke.mjs+69 −0看文件
@@ -0,0 +1,69 @@
1新增:import assert from "node:assert/strict";
2新增:import fs from "node:fs/promises";
3新增:import { fileURLToPath } from "node:url";
4新增:import { chooseInline, createWorkbench } from "./workbench-fixture.mjs";
5新增:
6新增:const output = new URL("../../docs/test-reports/2026-11-07-user-feedback/", import.meta.url);
7新增:await fs.mkdir(output, { recursive: true });
8新增:const { browser, page, state, errors } = await createWorkbench();
9新增:try {
10新增: state.settings.exit_policy = { mode: "dynamic", scope: "city", country_code: "JP", region: "Kanagawa", city: "Yokohama" };
11新增: await page.reload();
12新增: await page.route("**/api/settings/probe", route => route.fulfill({ json: {
13新增: ip: "192.0.2.10", country: "Japan", country_code: "JP", region: "Kanagawa", city: "Kawasaki",
14新增: timezone: "Asia/Tokyo", checked_at: new Date().toISOString(),
15新增: } }));
16新增: const openSettings = async () => {
17新增: await page.getByRole("button", { name: /^设置/ }).click();
18新增: await page.getByRole("button", { name: "网络与代理", exact: true }).click();
19新增: };
20新增: await openSettings();
21新增: await page.getByText("中国大陆出口禁止放行;静态 IP 和不限地区也必须确认出口国家。", { exact: true }).waitFor();
22新增: const picker = page.getByRole("combobox", { name: "动态 IP 的允许范围", exact: true });
23新增: const layoutTop = locator => locator.evaluate(element => {
24新增: let top = element.getBoundingClientRect().top;
25新增: for (let parent = element.parentElement; parent; parent = parent.parentElement) top += parent.scrollTop;
26新增: return top;
27新增: });
28新增: const country = page.getByLabel("允许的国家/地区代码", { exact: true });
29新增: await country.click();
30新增: assert.equal(await page.getByRole("option", { name: "中国", exact: true }).count(), 0, "mainland must not be offered as an allowed exit country");
31新增: await country.press("Escape");
32新增: const before = await layoutTop(country);
33新增: await picker.click();
34新增: const options = picker.locator("..").getByRole("listbox");
35新增: await options.waitFor();
36新增: const expanded = await layoutTop(country);
37新增: const list = await options.boundingBox();
38新增: assert.ok(expanded > before, "expanded options must move the following fields down");
39新增: assert.ok((await layoutTop(options)) + list.height <= expanded, "options must not cover the next control");
40新增: await picker.press("ArrowDown");
41新增: await picker.press("Enter");
42新增: await page.getByLabel("允许的城市", { exact: true }).waitFor({ state: "hidden" });
43新增: assert.equal(await picker.getAttribute("value"), "region");
44新增: assert.equal(await page.getByLabel("所属州/省", { exact: true }).inputValue(), "Kanagawa");
45新增: await page.getByRole("button", { name: "检测当前出口", exact: true }).click();
46新增: await page.getByText("Japan · Kanagawa · Kawasaki", { exact: true }).waitFor();
47新增: await page.getByRole("button", { name: "用检测结果填写", exact: true }).click();
48新增: await page.screenshot({ path: fileURLToPath(new URL("region-settings.png", output)), fullPage: true });
49新增: await page.getByRole("button", { name: "保存设置", exact: true }).click();
50新增: await page.getByRole("heading", { name: "网络与代理", exact: true }).waitFor({ state: "hidden" });
51新增: assert.equal(state.settings.exit_policy.scope, "region");
52新增: assert.equal(state.settings.exit_policy.region, "Kanagawa");
53新增: assert.equal(state.settings.exit_policy.country_code, "JP");
54新增: assert.equal(state.settings.exit_policy.city, "Yokohama", "relaxing the scope must preserve the previously saved city");
55新增: await page.reload();
56新增: await openSettings();
57新增: assert.equal(await picker.getAttribute("value"), "region");
58新增: assert.equal(await page.getByLabel("所属州/省", { exact: true }).inputValue(), "Kanagawa");
59新增: await chooseInline(picker, "city");
60新增: assert.equal(await page.getByLabel("允许的城市", { exact: true }).inputValue(), "Yokohama");
61新增: await picker.click();
62新增: await picker.press("Escape");
63新增: assert.equal(await picker.getAttribute("aria-expanded"), "false");
64新增: await chooseInline(picker, "any");
65新增: assert.match(await picker.textContent(), /中国大陆除外/);
66新增: await page.getByText(/命中大陆网段、定位为中国大陆、无法确认出口地区/).waitFor();
67新增: assert.deepEqual(errors, []);
68新增: console.log("PASS: inline mouse/keyboard expansion, region binding, city preservation, save and reload");
69新增:} finally { await browser.close(); }
新增ui/scripts/guest-install-smoke.mjs+73 −0看文件
@@ -0,0 +1,73 @@
1新增:import assert from "node:assert/strict";
2新增:import { createWorkbench } from "./workbench-fixture.mjs";
3新增:
4新增:for (const [id, name, platform] of [["macos", "macOS", "darwin"], ["windows-11", "Windows 11", "windows"]]) {
5新增: let submitted;
6新增: const { page, browser } = await createWorkbench({
7新增: clientContext: { mode: "local", connection_id: "local", client_platform: platform, server_platform: platform },
8新增: nativeRequest: ({ action }) => action === "chooseGuestMedia" ? "C:\\media\\Windows11.iso" : null,
9新增: async beforeNavigate(page, state) {
10新增: state.status.local_vm_storage = true;
11新增: await page.route("**/api/environment/guest-systems", r => r.fulfill({ json: { fresh: true, available: true, system: id } }));
12新增: await page.route("**/api/start", r => {
13新增: submitted = r.request().postDataJSON();
14新增: return r.fulfill({ json: { id: "native", running: true, kind: "guest-install" } });
15新增: });
16新增: },
17新增: });
18新增: try {
19新增: const picker = page.getByRole("combobox", { name: "客户机系统" });
20新增: const storage = page.getByRole("button", { name: "选择环境存储位置" });
21新增: const storageBefore = await storage.boundingBox();
22新增: await picker.click();
23新增: const option = page.getByRole("option", { name, exact: true });
24新增: await option.waitFor();
25新增: const row = await option.boundingBox(), below = await storage.boundingBox();
26新增: assert.ok(below.y > storageBefore.y && row.y + row.height <= below.y);
27新增: await picker.press("Escape");
28新增: assert.equal((await storage.boundingBox()).y, storageBefore.y);
29新增: await picker.press("Enter"); await picker.press("End"); await picker.press("Enter");
30新增: const button = page.getByRole("button", { name: "安装客户机" });
31新增: if (platform === "darwin") {
32新增: assert.ok(await button.isEnabled());
33新增: assert.equal(await page.getByLabel("客机账户密码",{exact:true}).count(),0);
34新增: } else {
35新增: assert.ok(await button.isDisabled());
36新增: await page.getByRole("button", { name: "选择本机 ISO" }).click();
37新增: await page.getByText("C:\\media\\Windows11.iso", { exact: true }).waitFor();
38新增: await page.getByLabel("ISO 的 SHA-256").fill("a".repeat(64));
39新增: assert.ok(await button.isDisabled());
40新增: await page.getByRole("checkbox").check();
41新增: }
42新增: await Promise.all([
43新增: page.waitForResponse(response => response.url().endsWith("/api/start")),
44新增: button.click(),
45新增: ]);
46新增: assert.equal(submitted.guest_system, id);
47新增: if (platform === "windows") assert.ok(submitted.editor_terms && submitted.sha256.length === 64 && submitted.media.endsWith(".iso"));
48新增: else assert.equal(submitted.password, undefined);
49新增: console.log(platform, "inline picker, keyboard, validation and start request passed");
50新增: } catch (error) {
51新增: console.error((await page.locator("body").innerText()).slice(-2300));
52新增: throw error;
53新增: } finally { await browser.close(); }
54新增:}
55新增:
56新增:{
57新增: const calls=[];
58新增: const {page,browser,errors}=await createWorkbench({
59新增: nativeRequest: message=>{ calls.push(message.action); return null; },
60新增: async beforeNavigate(page,state) {
61新增: state.status.local_vm_storage=true;
62新增: await page.route("**/api/environment/guest-systems",r=>r.fulfill({json:{fresh:false,available:true,system:"macos",pending:{system:"macos",id:"activation-fixture"},activate:true}}));
63新增: await page.route("**/api/environment/guest-systems/activate",r=>{ calls.push("activate"); return r.fulfill({json:{stopping:true}}); });
64新增: }
65新增: });
66新增: try {
67新增: for(let i=0; !calls.includes("reconnect") && i<150;i++) await new Promise(resolve=>setTimeout(resolve,20));
68新增: assert.equal(calls.filter(action=>action==="activate").length,1);
69新增: assert.equal(calls.filter(action=>action==="reconnect").length,1);
70新增: assert.deepEqual(errors,[]);
71新增: console.log("installed guest automatically activated and reconnected");
72新增: } finally { await browser.close(); }
73新增:}
修改ui/scripts/guest-system-icon-smoke.mjs+16 −0看文件
@@ -36,4 +36,20 @@ try {
3636 console.log(`PASS 客机 ${label},客户端 ${host}`);
3737 } finally { await browser.close(); }
3838 }
39新增: const fixture = await createWorkbench({
40新增: url,
41新增: beforeNavigate: async (page, state) => {
42新增: state.status.local_vm_storage = true;
43新增: await page.route("**/api/environment/guest-systems", route => route.fulfill({ json: { fresh: true, system: "macos", available: true } }));
44新增: },
45新增: });
46新增: try {
47新增: const { page } = fixture;
48新增: await page.getByRole("img", { name: "客户机系统:Linux" }).waitFor();
49新增: await page.getByRole("combobox", { name: "客户机系统" }).click();
50新增: await page.getByRole("option", { name: "macOS", exact: true }).click();
51新增: await page.getByRole("img", { name: "客户机系统:macOS" }).waitFor();
52新增: assert.deepEqual(fixture.errors, []);
53新增: console.log("PASS 首次安装选择时图标随客机系统变化");
54新增: } finally { await fixture.browser.close(); }
3955} finally { await vite.close(); }
新增ui/scripts/guest-system-picker-smoke.mjs+40 −0看文件
@@ -0,0 +1,40 @@
1新增:import assert from "node:assert/strict";
2新增:import { createWorkbench } from "./workbench-fixture.mjs";
3新增:
4新增:for (const [platform, id] of [["darwin","macos"], ["windows","windows-11"], ["linux",null]]) {
5新增: for (const fresh of [true, false]) {
6新增: const fixture = await createWorkbench({
7新增: clientContext: {mode:"local", connection_id:"local", client_platform:platform, server_platform:platform},
8新增: async beforeNavigate(page, state) {
9新增: state.status.local_vm_storage = true;
10新增: await page.route("**/api/environment/guest-systems", route => route.fulfill({
11新增: json:{fresh, available:false, system:fresh ? id : null, reason:"此构建缺少原生客户机安装组件"},
12新增: }));
13新增: },
14新增: });
15新增: const { browser, page, errors } = fixture;
16新增: try {
17新增: const region = page.locator(".guest-system-picker");
18新增: if (fresh) {
19新增: await region.waitFor();
20新增: if (id) {
21新增: const picker = region.getByRole("combobox");
22新增: const storage = page.getByRole("button",{name:"选择环境存储位置"});
23新增: const initialY = (await storage.boundingBox()).y;
24新增: await picker.click();
25新增: const option = region.getByRole("option").last();
26新增: assert.equal(await option.getAttribute("aria-disabled"),"true");
27新增: const position = await option.boundingBox();
28新增: assert.ok((await storage.boundingBox()).y >= position.y + position.height);
29新增: await picker.press("Escape");
30新增: assert.ok(Math.abs((await storage.boundingBox()).y - initialY) <= 1, "collapsed picker restores the following control");
31新增: }
32新增: } else await region.waitFor({state:"hidden"});
33新增: const submitted = page.waitForRequest(req => req.url().endsWith("/api/start") && req.method()==="POST");
34新增: await page.getByRole("button",{name:"启动 Cage 环境",exact:true}).click();
35新增: assert.deepEqual((await submitted).postDataJSON(), fresh ? {guest_system:"debian-13"} : {});
36新增: assert.deepEqual(errors,[]);
37新增: } finally { await browser.close(); }
38新增: }
39新增:}
40新增:console.log("Debian fallback and existing environments verified on all three host types.");
新增ui/scripts/host-clone-smoke.mjs+91 −0看文件
@@ -0,0 +1,91 @@
1新增:import assert from "node:assert/strict";
2新增:import { createWorkbench } from "./workbench-fixture.mjs";
3新增:for (const [platform, system, version, edition] of [
4新增: ["darwin", "macos", "26.5", ""],
5新增: ["windows", "windows-11", "25H2", "Professional"],
6新增: ["linux", "ubuntu-22.04", "22.04", ""],
7新增: ["linux", "ubuntu-24.04", "24.04", ""],
8新增:]) {
9新增: let planRequests = 0;
10新增: const fixture = await createWorkbench({
11新增: clientContext: {
12新增: mode: "local",
13新增: connection_id: "local",
14新增: client_platform: platform,
15新增: server_platform: platform,
16新增: },
17新增: beforeNavigate: async (page, state) => {
18新增: state.status.local_vm_storage = true;
19新增: await page.route("**/api/environment/guest-systems", (route) =>
20新增: route.fulfill({ json: { fresh: true, available: true, system } }),
21新增: );
22新增: await page.route("**/api/environment/guest-systems/clone", (route) => {
23新增: planRequests++;
24新增: return route.fulfill({
25新增: json: {
26新增: key: "source-key",
27新增: enough_space: true,
28新增: minimum_free_gib: 64,
29新增: free_gib: 100,
30新增: download_bytes: 5000000000,
31新增: plan: {
32新增: host: {
33新增: system,
34新增: version,
35新增: build: "host-build",
36新增: edition,
37新增: language: "zh-CN",
38新增: },
39新增: version,
40新增: build: "image-build",
41新增: format: system === "macos" ? "ipsw" : "esd",
42新增: },
43新增: },
44新增: });
45新增: });
46新增: },
47新增: });
48新增: try {
49新增: const { page } = fixture;
50新增: const region = page.locator(".guest-system-picker");
51新增: const picker = region.getByRole("combobox");
52新增: await picker.waitFor();
53新增: const initialHeight = (await region.boundingBox()).height;
54新增: await picker.focus();
55新增: await picker.press("ArrowDown");
56新增: const option = region.getByRole("option", {
57新增: name: "自动匹配本机系统版本",
58新增: exact: true,
59新增: });
60新增: await option.waitFor();
61新增: assert.ok(
62新增: (await region.boundingBox()).height > initialHeight,
63新增: "options occupy layout space",
64新增: );
65新增: await picker.press("Home");
66新增: await picker.press("Enter");
67新增: assert.equal(await picker.getAttribute("aria-expanded"), "false");
68新增: await region
69新增: .getByText("本机构建号 host-build · 镜像构建号 image-build")
70新增: .waitFor();
71新增: if (system === "windows-11") await region.getByRole("checkbox").check();
72新增: const submit = page.waitForRequest(
73新增: (request) =>
74新增: request.url().endsWith("/api/start") && request.method() === "POST",
75新增: );
76新增: await page
77新增: .getByRole("button", {
78新增: name: "安装客户机",
79新增: exact: true,
80新增: })
81新增: .click();
82新增: const body = (await submit).postDataJSON();
83新增: assert.equal(body.clone_key, "source-key");
84新增: assert.equal(body.guest_system, system);
85新增: assert.equal(planRequests, 1);
86新增: assert.deepEqual(fixture.errors, []);
87新增: console.log(platform, "host clone selection and submission passed");
88新增: } finally {
89新增: await fixture.browser.close();
90新增: }
91新增:}
修改ui/scripts/image-input-smoke.mjs+12 −3看文件
@@ -15,7 +15,9 @@ const origin = process.env.CAGE_UI_URL || "http://127.0.0.1:5173";
1515const received = [];
1616let release,
1717 fail = false;
18新增:await page.route("**/api/**", route => route.fulfill({ json: { ok: true } }));
1819await page.route("**/api/appearance", (route) => route.fulfill({ json: {} }));
20新增:await page.route("**/api/input/paste/start", route => route.fulfill({ json: { available: true, context: "a".repeat(32) } }));
1921await page.route("**/api/input/image", async (route) => {
2022 received.push(route.request().postDataJSON());
2123 await new Promise((resolve) => {
@@ -81,7 +83,7 @@ const imageEvent = (selector, type, image = true) =>
8183try {
8284 await page.goto(origin + "/image-input-test");
8385 await page.evaluate(async () => {
84删除: const [{ default: RFB }, { installRemoteInput }, { sendImage }] =
86新增: const [{ default: RFB }, { installRemoteInput }, { sendImage, imagePayload }] =
8587 await Promise.all([
8688 import("/.generated/novnc/core/rfb.js"),
8789 import("/src/remote-input.js"),
@@ -105,7 +107,14 @@ try {
105107 rfb.cagePasteText = (text) =>
106108 rfb._cageQueueInput(() => rfb._cagePasteText(text));
107109 let active = true;
108删除: const input = installRemoteInput(rfb, container, {
110新增: const input = installRemoteInput({
111新增: events: rfb,
112新增: setKeyboardTarget: target => rfb.cageSetKeyboardTarget(target),
113新增: sendKey: (...key) => rfb.sendKey(...key),
114新增: focus: () => rfb.focus(),
115新增: pasteText: text => rfb.cagePasteText(text),
116新增: runKeyAction: action => rfb._cageQueueInput(() => action((...key) => rfb._cageSendKey(...key))),
117新增: }, container, {
109118 mode: () => "mac",
110119 isActive: () => active,
111120 insertText: async () => {},
@@ -117,7 +126,7 @@ try {
117126 rfb.cagePasteContent(
118127 content,
119128 async (payload) => {
120删除: await sendImage(payload, "browser", "tab-1");
129新增: await sendImage(payload.files ? await imagePayload(payload.files[0]) : payload, "browser", "tab-1");
121130 order.push("image");
122131 },
123132 () => active && Boolean(rfb.target),
新增ui/scripts/initialization-smoke.mjs+88 −0看文件
@@ -0,0 +1,88 @@
1新增:import assert from "node:assert/strict";
2新增:import fs from "node:fs/promises";
3新增:import { createWorkbench } from "./workbench-fixture.mjs";
4新增:
5新增:const evidence = process.env.CAGE_INITIALIZATION_EVIDENCE;
6新增:if (evidence) await fs.mkdir(evidence, { recursive: true });
7新增:
8新增:for (const [platform, system] of [["darwin", "macos"], ["windows", "windows-11"], ["linux", "ubuntu-22.04"]]) {
9新增: let starts = 0, rejectComplete = true;
10新增: const fixture = await createWorkbench({
11新增: initialization: { required: true, tracked: true, started: false },
12新增: clientContext: { mode: "local", connection_id: "local", client_platform: platform, server_platform: platform },
13新增: beforeNavigate: async (page, state) => {
14新增: state.status.local_vm_storage = true;
15新增: await page.route("**/api/environment/storage", route => route.fulfill({ json: { directory: "/preview/cage-state", has_environment: false } }));
16新增: await page.route("**/api/environment/guest-systems", route => route.fulfill({ json: { fresh: true, available: true, system } }));
17新增: await page.route("**/api/environment/guest-systems/clone", route => route.fulfill({ json: { key: "matched-image", enough_space: true, minimum_free_gib: 51, free_gib: 120, download_bytes: 19769944180, plan: { host: { system, version: system === "windows-11" ? "25H2" : "26.5", build: "123", edition: "Professional", language: "zh-CN" }, version: "26.5", build: "456", bytes: 19769944180 } } }));
18新增: await page.route("**/api/start", route => {
19新增: starts++;
20新增: const submitted = route.request().postDataJSON();
21新增: assert.equal(submitted.guest_system, system);
22新增: if (starts === 1) assert.equal(submitted.clone_key, "matched-image");
23新增: state.status.job = { id: "install-" + starts, running: true, kind: "guest-install", setup_progress: { system, phase: "image", operation: "download", label: "正在下载系统镜像", received: 25 * 1048576, total: 100 * 1048576, bytes_per_second: 1048576 }, log: "镜像下载已开始" };
24新增: return route.fulfill({ json: state.status.job });
25新增: });
26新增: await page.route("**/api/environment/initialization", route => {
27新增: const action = route.request().method() === "POST" ? route.request().postDataJSON()?.action : "";
28新增: if (action === "complete" && rejectComplete) return route.fulfill({ status: 400, contentType: "text/plain; charset=utf-8", body: "环境网络检查尚未通过,请重新检查" });
29新增: if (action === "install") state.initialization.started = true;
30新增: if (action === "complete") state.initialization.required = false;
31新增: return route.fulfill({ json: state.initialization });
32新增: });
33新增: },
34新增: });
35新增: const { page, state, errors, browser } = fixture;
36新增: try {
37新增: assert.equal(await page.getByRole("complementary", { name: "项目与终端" }).count(), 0);
38新增: const picker = page.getByRole("combobox", { name: "客户机系统" });
39新增: const storage = page.getByRole("region", { name: "本机环境存储" });
40新增: await storage.getByText("/preview/cage-state").waitFor();
41新增: const before = await storage.boundingBox();
42新增: await picker.click();
43新增: const option = page.getByRole("option", { name: "自动匹配本机系统版本", exact: true });
44新增: await option.waitFor();
45新增: const expanded = await storage.boundingBox();
46新增: assert.ok(expanded.y > before.y);
47新增: await picker.press("Home"); await picker.press("Enter");
48新增: await page.getByText("Cage 会检测本机系统版本。配置代理后匹配官方镜像,并显示下载量与空间要求。").waitFor();
49新增: if (system === "windows-11") await page.getByRole("checkbox").check();
50新增: if (evidence) await page.screenshot({ path: `${evidence}/${platform}-system.png`, fullPage: true });
51新增: await page.getByRole("button", { name: "下一步:配置代理" }).click();
52新增: await page.getByRole("heading", { name: "连接你的网络代理" }).waitFor();
53新增: await page.getByText("根据本机系统版本匹配官方镜像,安装到独立客机中。").waitFor();
54新增: await page.getByRole("button", { name: "上一步", exact: true }).click();
55新增: await page.getByRole("combobox", { name: "客户机系统" }).getByText("自动匹配本机系统版本").waitFor();
56新增: await page.getByRole("button", { name: "下一步:配置代理" }).click();
57新增: await page.getByRole("button", { name: "开始安装", exact: true }).click();
58新增: const progress = page.getByRole("region", { name: "环境安装进度" });
59新增: await progress.getByText("25 MiB / 100 MiB", { exact: true }).waitFor();
60新增: assert.equal(await progress.getByRole("progressbar").getAttribute("aria-valuenow"), "25");
61新增: assert.equal(await page.getByRole("complementary", { name: "项目与终端" }).count(), 0);
62新增: await page.reload();
63新增: await progress.getByText("25 MiB / 100 MiB", { exact: true }).waitFor();
64新增: assert.equal(starts, 1, "refresh must not restart the accepted installation");
65新增: state.status.job = { ...state.status.job, running: false, error: "下载中断,已保存部分文件" };
66新增: await progress.getByRole("alert").waitFor();
67新增: if (evidence) await page.screenshot({ path: `${evidence}/${platform}-failed.png`, fullPage: true });
68新增: await progress.getByRole("button", { name: "继续安装", exact: true }).click();
69新增: await progress.getByRole("progressbar").waitFor();
70新增: assert.equal(starts, 2);
71新增: await page.setViewportSize({ width: 600, height: 650 });
72新增: assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false);
73新增: if (evidence) await page.screenshot({ path: `${evidence}/${platform}-progress-compact.png`, fullPage: true });
74新增: state.status.job = { id: "install-2", kind: "start", running: false };
75新增: Object.assign(state.status, { ready: true, vm_running: true, safety: { gate: { mode: "open", until: new Date(Date.now() + 3600000).toISOString() } } });
76新增: await page.getByRole("button", { name: "进入工作台", exact: true }).click();
77新增: await page.getByRole("alert").filter({ hasText: "网络检查" }).waitFor();
78新增: assert.equal(await page.getByRole("complementary", { name: "项目与终端" }).count(), 0, "server completion rejection must keep initialization visible");
79新增: rejectComplete = false;
80新增: await page.getByRole("button", { name: "进入工作台", exact: true }).click();
81新增: await page.getByRole("complementary", { name: "项目与终端" }).waitFor();
82新增: await page.reload();
83新增: await page.getByRole("complementary", { name: "项目与终端" }).waitFor();
84新增: assert.equal(await page.getByRole("heading", { name: "为 Cage 准备独立环境" }).count(), 0);
85新增: assert.deepEqual(errors, []);
86新增: console.log(`PASS ${platform}: independent initialization, inline keyboard selection, back navigation, progress, refresh, retry, completion gate and reopen`);
87新增: } finally { await browser.close(); }
88新增:}
新增ui/scripts/input-paste-order-smoke.mjs+64 −0看文件
@@ -0,0 +1,64 @@
1新增:import assert from "node:assert/strict";
2新增:import { createWorkbench } from "./workbench-fixture.mjs";
3新增:import { startDisplay } from "./rfb-wire-fixture.mjs";
4新增:
5新增:const display = await startDisplay(process.env.CAGE_UI_URL || "http://127.0.0.1:5198", { sharedClipboard: true });
6新增:let context = "a".repeat(32);
7新增:const { browser, page, errors } = await createWorkbench({
8新增: mockWebSockets: false, url: display.url,
9新增: nativeRequest: request => {
10新增: if (request.action === "clipboardRevision") return 1;
11新增: if (request.action === "clipboardSyncRead") return { text: "synthetic shared clipboard", revision: 1 };
12新增: return true;
13新增: },
14新增: async beforeNavigate(page, state) {
15新增: state.status.ready = state.status.vm_running = true;
16新增: await page.route("**/api/claude-desktop", route => route.fulfill({ json: { installed: true, running: true, managed: true } }));
17新增: await page.route("**/api/input", route => route.fulfill({ json: { available: true, context, rect: [20, 20, 1, 24] } }));
18新增: },
19新增:});
20新增:page.setDefaultTimeout(10000);
21新增:async function until(predicate) {
22新增: for (let attempt = 0; attempt < 200; attempt++) {
23新增: if (predicate()) return;
24新增: await page.waitForTimeout(20);
25新增: }
26新增: assert(predicate(), "expected RFB input did not arrive");
27新增:}
28新增:async function delaySync() {
29新增: await page.evaluate(() => {
30新增: window.pendingSync = false;
31新增: window.cageSyncClipboard = () => new Promise(resolve => {
32新增: window.pendingSync = true;
33新增: window.releaseSync = resolve;
34新增: });
35新增: });
36新增:}
37新增:try {
38新增: await page.getByRole("button", { name: "Claude Desktop", exact: true }).click();
39新增: await page.getByText("正在连接画面", { exact: true }).waitFor({ state: "hidden" });
40新增: await page.waitForFunction(() => window.cageSharedClipboardActive === true);
41新增: await page.locator(".remote-canvas canvas").click({ position: { x: 40, y: 40 } });
42新增: display.stats.keys.length = 0;
43新增: await delaySync();
44新增: await page.keyboard.press("Meta+v");
45新增: await page.waitForFunction(() => window.pendingSync);
46新增: await page.keyboard.press("Enter");
47新增: assert(!display.stats.keys.some(key => key.symbol === 118 || key.symbol === 0xff0d));
48新增: await page.evaluate(() => window.releaseSync());
49新增: await until(() => display.stats.keys.some(key => key.symbol === 0xff0d && !key.down));
50新增: const ordered = display.stats.keys.map(key => [key.symbol, key.down]);
51新增: assert(ordered.findIndex(([symbol, down]) => symbol === 118 && down) < ordered.findIndex(([symbol, down]) => symbol === 0xff0d && down));
52新增:
53新增: display.stats.keys.length = 0;
54新增: await delaySync();
55新增: await page.keyboard.press("Meta+v");
56新增: await page.waitForFunction(() => window.pendingSync);
57新增: context = "b".repeat(32);
58新增: await page.keyboard.press("Enter");
59新增: await page.evaluate(() => window.releaseSync());
60新增: await page.getByText("粘贴位置已切换,请回到原输入位置重试", { exact: true }).waitFor();
61新增: assert(!display.stats.keys.some(key => key.symbol === 118 || key.symbol === 0xff0d));
62新增: assert.deepEqual(errors, []);
63新增: console.log(JSON.stringify({ result: "PASS", checks: ["shared clipboard gate reserves the real RFB queue", "paste precedes Enter", "focus change cancels paste and queued Enter"], wire: ordered }));
64新增:} finally { await browser.close(); await display.close(); }
新增ui/scripts/installation-preview.mjs+84 −0看文件
@@ -0,0 +1,84 @@
1新增:// Local copy preview of the production workbench. API requests stay in this
2新增:// process; none are forwarded to Cage or used to install a guest.
3新增:import http from "node:http";
4新增:import { defaultAppearance } from "../src/appearance-state.mjs";
5新增:
6新增:const port = Number(process.env.CAGE_INSTALL_PREVIEW_PORT || 5208);
7新增:const upstream = new URL(process.env.CAGE_UI_URL || "http://127.0.0.1:5198");
8新增:const hosts = {
9新增: macos: { system: "macos", version: "26.5", build: "25F71", arch: "arm64", platform: "darwin", bytes: 19769944180, imageBuild: "25F71" },
10新增: windows: { system: "windows-11", version: "25H2", build: "26200.9711", edition: "Professional", language: "zh-CN", arch: "amd64", platform: "windows", bytes: 5314951294, imageBuild: "26200.6584" },
11新增: linux: { system: "ubuntu-22.04", version: "22.04", arch: "amd64", platform: "linux", bytes: 650000000 },
12新增:};
13新增:const sessions = new Map();
14新增:
15新增:http.createServer(async (req, res) => {
16新增: const url = new URL(req.url, `http://127.0.0.1:${port}`);
17新增: const saved = Object.fromEntries((req.headers.cookie || "").split(";").map(value => value.trim().split("=")));
18新增: const selected = url.searchParams.get("host") || saved.preview_host || "macos";
19新增: const scenario = url.searchParams.get("state") || saved.preview_state || "download";
20新增: const host = hosts[selected] || hosts.macos;
21新增: const system = host.system;
22新增: const plan = {
23新增: host, version: host.version, build: host.imageBuild, bytes: host.bytes,
24新增: format: system === "macos" ? "ipsw" : system === "windows-11" ? "esd" : "qcow2",
25新增: ...(scenario === "cached" ? { path: "/preview/cached-system-image" } : {}),
26新增: };
27新增: const sessionKey = `${selected}:${scenario}`;
28新增: if (!sessions.has(sessionKey)) sessions.set(sessionKey, { required: true, tracked: true, started: ["resume", "progress", "failure", "ready"].includes(scenario), created: Date.now() });
29新增: const session = sessions.get(sessionKey);
30新增: const showProgress = scenario === "progress" || session.installing;
31新增: const showFailure = scenario === "failure";
32新增: const showReady = scenario === "ready";
33新增: const job = showProgress || showFailure ? { id: "preview-install", kind: "guest-install", running: !showFailure, error: showFailure ? "系统镜像下载中断。请检查代理连接,已下载文件和虚拟磁盘会保留。" : "", message: "正在下载系统镜像", setup_progress: { system, phase: "image", operation: "download", label: `正在下载 ${system === "macos" ? "macOS" : system === "windows-11" ? "Windows 11" : "Ubuntu"} 系统镜像`, received: Math.floor(host.bytes * .43), total: host.bytes, bytes_per_second: 26 * 1048576 }, log: "正在通过所选代理下载官方系统镜像。" } : { running: false };
34新增: const status = { local_vm_storage: true, ready: showReady, vm_running: showReady, safety: showReady ? { gate: { mode: "open", until: new Date(Date.now()+3600000).toISOString() } } : {}, keyboard: host.platform === "darwin" ? "mac" : "native", job, projects: [], environment_workspace: true, environment_directory: "/preview/workspace", workspace: "/preview/workspace" };
35新增: const pending = scenario === "resume" ? { version: 1, id: "preview-install", system, source: plan, editor_terms: true } : undefined;
36新增: if (url.pathname.startsWith("/api/")) {
37新增: let value = {};
38新增: if (url.pathname === "/api/client/context") value = { mode: "local", connection_id: "local", client_platform: host.platform, server_platform: host.platform, connection: { state: "disconnected" } };
39新增: else if (url.pathname === "/api/account") value = { exists: true, unlocked: true, username: "安装界面预览" };
40新增: else if (url.pathname === "/api/status") value = status;
41新增: else if (url.pathname === "/api/environment/initialization") {
42新增: if (req.method === "POST") {
43新增: let body=""; for await (const part of req) body+=part;
44新增: const action=JSON.parse(body || "{}").action;
45新增: if(action === "install") session.started=true;
46新增: if(action === "complete" && showReady) session.required=false;
47新增: }
48新增: value=session;
49新增: }
50新增: else if (url.pathname === "/api/environment/storage") value={directory: host.platform === "windows" ? "D:\\CageData" : "/preview/cage-state",has_environment:false};
51新增: else if (url.pathname === "/api/settings") value = { workspace: "/preview/workspace", browser_home_url: "https://www.bing.com/", timezone: "Asia/Shanghai", locale: "zh_CN.UTF-8", keyboard: status.keyboard };
52新增: else if (url.pathname === "/api/appearance") value = { ...defaultAppearance, mode: "light" };
53新增: else if (url.pathname === "/api/proxy") value = { active: true, selected: "preview-node", port: 17896, core_available: true, state: "prepared", sources: [{ id: "preview", name: "预览代理", nodes: [{ id: "preview-node", name: "预览节点", type: "http" }] }] };
54新增: else if (url.pathname === "/api/environment/guest-systems") value = { fresh: !pending, available: true, system, pending };
55新增: else if (url.pathname === "/api/environment/guest-systems/clone") value = { plan, key: "preview-only", enough_space: scenario !== "space", download_bytes: scenario === "cached" ? 0 : scenario === "resume" ? Math.floor(host.bytes / 3) : host.bytes, minimum_free_gib: 32 + Math.ceil(host.bytes / 1073741824), free_gib: scenario === "space" ? 10 : 120, installation_started: Boolean(pending) };
56新增: else if (url.pathname === "/api/host/git") value = { state: "ok", ready: true, message: "本机 Git 安全保护已启用。" };
57新增: else if (url.pathname === "/api/terminals") value = [];
58新增: else if (url.pathname === "/api/browser/tabs") value = { tabs: [], active: "" };
59新增: else if (url.pathname === "/api/start") { session.installing=true; value={ id: "preview-install", kind: "guest-install", running: true }; }
60新增: else if (url.pathname === "/api/stop") { session.installing=false; value={ id: "preview-stop", kind: "stop", running:false }; }
61新增: else if (url.pathname === "/api/diagnostics") value={bytes:0,files:0};
62新增: else if (url.pathname.endsWith("/events")) { res.writeHead(200, { "Content-Type": "text/event-stream" }); res.end(": preview\n\n"); return; }
63新增: res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" }); res.end(JSON.stringify(value)); return;
64新增: }
65新增: if (url.pathname === "/") res.setHeader("Set-Cookie", [`preview_host=${hosts[selected] ? selected : "macos"}; SameSite=Strict; Path=/`, `preview_state=${scenario}; SameSite=Strict; Path=/`]);
66新增: const request = http.request(new URL(url.pathname + url.search, upstream), { headers: { ...req.headers, host: upstream.host } }, response => {
67新增: const parts = [];
68新增: response.on("data", part => parts.push(part));
69新增: response.on("end", () => {
70新增: let body = Buffer.concat(parts);
71新增: const headers = { ...response.headers };
72新增: if (url.pathname === "/") {
73新增: const links = Object.keys(hosts).map(key => `<a href="/?host=${key}&state=${scenario}" ${key === selected ? 'aria-current="page"' : ""}>${key === "macos" ? "Mac" : key === "windows" ? "Windows" : "Linux"}</a>`).join("");
74新增: const states = [["download", "首次配置"], ["cached", "已有镜像"], ["progress", "安装进度"], ["failure", "安装失败"], ["ready", "环境就绪"]].map(([key, label]) => `<a href="/?host=${selected}&state=${key}" ${key === scenario ? 'aria-current="page"' : ""}>${label}</a>`).join("");
75新增: const banner = `<aside class="installation-preview"><strong>安装界面预览</strong><span>模拟数据 · 不会安装</span><nav>${links}</nav><nav>${states}</nav></aside>`;
76新增: body = Buffer.from(body.toString().replace("</head>", `<style>.installation-preview{display:flex;align-items:center;gap:14px;flex-wrap:wrap;padding:10px 18px;background:#f5f5f5;border-bottom:1px solid #ddd;font:13px -apple-system,BlinkMacSystemFont,'PingFang SC',sans-serif}.installation-preview span{color:#777}.installation-preview nav{display:flex;gap:12px}.installation-preview a{color:#666;text-decoration:none}.installation-preview a[aria-current]{color:#111;text-decoration:underline;text-underline-offset:4px}.client-shell{height:calc(100dvh - 45px)!important}.client-shell>.app{height:auto;flex:1;min-height:0}</style><script>window.cageNativeBridge={postMessage:async()=>null};</script></head>`).replace('<div id="root">', banner + '<div id="root">'));
77新增: delete headers["content-length"];
78新增: }
79新增: res.writeHead(response.statusCode, headers); res.end(body);
80新增: });
81新增: });
82新增: request.on("error", () => { res.writeHead(502); res.end("Start the Cage frontend preview server first."); });
83新增: req.pipe(request);
84新增:}).listen(port, "127.0.0.1", () => console.log(`Installation copy preview: http://127.0.0.1:${port}/?host=macos`));
新增ui/scripts/log-audit-smoke.mjs+73 −0看文件
@@ -0,0 +1,73 @@
1新增:import assert from "node:assert/strict";
2新增:import { createWorkbench } from "./workbench-fixture.mjs";
3新增:
4新增:const epoch = new Date("2026-11-08T03:00:00Z");
5新增:for (const platform of ["darwin", "windows"]) {
6新增: let proxyReady = false;
7新增: const calls = [];
8新增: const fixture = await createWorkbench({
9新增: clientContext: { mode: "local", connection_id: "local", client_platform: platform, server_platform: platform, connection: { state: "disconnected" } },
10新增: beforeNavigate: page => page.clock.install({ time: epoch }),
11新增: nativeRequest: async body => {
12新增: if (body.action !== "appUpdate") return null;
13新增: calls.push(body.operation);
14新增: return { phase: proxyReady ? "current" : "waiting", message: proxyReady ? "已是最新版本" : "所选代理未运行,更新检查将在代理就绪后重试", retryAt: "" };
15新增: },
16新增: });
17新增: try {
18新增: await fixture.page.waitForFunction(() => !document.querySelector(".loading-screen"));
19新增: await fixture.page.evaluate(() => window.dispatchEvent(new Event("focus")));
20新增: assert.deepEqual(calls, ["status", "check"]);
21新增: assert.equal(await fixture.page.locator(".app-update-error").count(), 0, "waiting is not an update-failure alert");
22新增: await fixture.page.clock.fastForward(4 * 60 * 1000);
23新增: assert.deepEqual(calls, ["status", "check"], "no tight retry loop while proxy is unavailable");
24新增: proxyReady = true;
25新增: await fixture.page.clock.fastForward(2 * 60 * 1000);
26新增: await fixture.page.waitForFunction(() => !document.querySelector(".app-update-error"));
27新增: assert.deepEqual(calls, ["status", "check", "check"], "waiting checks resume on the existing five-minute retry schedule");
28新增: assert.deepEqual(fixture.errors, []);
29新增: console.log(`PASS: ${platform} update waits and recovers without failure alerts`);
30新增: } finally { await fixture.browser.close(); }
31新增:}
32新增:
33新增:const fixture = await createWorkbench({ beforeNavigate: page => page.clock.install({ time: epoch }) });
34新增:try {
35新增: const { page, state } = fixture;
36新增: let broken = true;
37新增: let polls = 0;
38新增: await page.exposeFunction("filePollCountForTest", () => polls);
39新增: const failure = "Claude Desktop 的文件服务已经退出,请重新打开应用";
40新增: await page.route("**/api/input/files/desktop/requests", route => {
41新增: polls++;
42新增: return broken ? route.fulfill({ status: 503, contentType: "text/plain", body: failure })
43新增: : route.fulfill({ json: { available: true, uploads: [], downloads: [], opens: [] } });
44新增: });
45新增: state.status.ready = state.status.vm_running = true;
46新增: await page.reload();
47新增: await page.getByText(failure, { exact: false }).waitFor();
48新增: assert.equal(polls, 1, "real file-service failure is visible to the user");
49新增: await page.clock.fastForward(2500);
50新增: assert.equal(polls, 1, "failed poll backs off instead of retrying at 1.5 seconds");
51新增: await page.clock.fastForward(1000);
52新增: await page.waitForFunction(async () => await window.filePollCountForTest() >= 2);
53新增: assert.equal(polls, 2);
54新增: broken = false;
55新增: await page.clock.fastForward(6500);
56新增: await page.waitForFunction(async () => await window.filePollCountForTest() >= 3);
57新增: const recovered = polls;
58新增: await page.clock.fastForward(1600);
59新增: await page.waitForFunction(async previous => await window.filePollCountForTest() > previous, recovered);
60新增: assert.ok(polls > recovered, "normal polling cadence returns after recovery");
61新增:
62新增: await page.getByRole("button", { name: "打开浏览器", exact: true }).click();
63新增: const trigger = page.getByRole("button", { name: "浏览器下载", exact: true });
64新增: for (let round = 0; round < 4; round++) {
65新增: await trigger.click();
66新增: await page.getByRole("dialog", { name: "下载文件", exact: true }).waitFor();
67新增: await page.getByRole("button", { name: "工作台", exact: true }).click();
68新增: await page.setViewportSize({ width: 950 + round * 25, height: 720 });
69新增: await page.getByRole("button", { name: "打开浏览器", exact: true }).click();
70新增: }
71新增: assert.deepEqual(fixture.errors, [], "closing panels and resizing must not leave null-reference callbacks");
72新增: console.log("PASS: file polling reports failures, backs off, recovers, and panel teardown remains safe");
73新增:} finally { await fixture.browser.close(); }
新增ui/scripts/macos-claude-display-smoke.mjs+60 −0看文件
@@ -0,0 +1,60 @@
1新增:import assert from "node:assert/strict";
2新增:import { createWorkbench } from "./workbench-fixture.mjs";
3新增:
4新增:const frames = new Map(), clicks = [];
5新增:let fixed = false;
6新增:const { page, browser, errors } = await createWorkbench({
7新增: viewport: {width:1280, height:882}, deviceScaleFactor:2,
8新增: async beforeNavigate(page, state) {
9新增: state.account.guest_system = "macos";
10新增: state.status.vm_running = state.status.ready = true;
11新增: await page.route("**/api/macos/claude/window", async route => {
12新增: const input = route.request().postDataJSON();
13新增: if (input.action === "pointer" && input.phase === "down") clicks.push(input);
14新增: if (input.action !== "frame") return route.fulfill({json:{installed:true,running:true,screen:true,input:true}});
15新增: const width = fixed ? 600 : input.width, height = fixed ? 560 : input.height;
16新增: assert.equal(input.scale, 2);
17新增: const geometry = width + "x" + height;
18新增: if (!frames.has(geometry)) frames.set(geometry, await page.evaluate(([w,h]) => {
19新增: const canvas = document.createElement("canvas");
20新增: canvas.width=w*2; canvas.height=h*2;
21新增: const ctx=canvas.getContext("2d");
22新增: ctx.fillStyle="#f7f5f1"; ctx.fillRect(0,0,canvas.width,canvas.height);
23新增: ctx.fillStyle="#202020"; ctx.font="32px sans-serif"; ctx.fillText("Claude",60,100);
24新增: return canvas.toDataURL().split(",")[1];
25新增: }, [width,height]));
26新增: return route.fulfill({json:{window:70,pid:23,image:frames.get(geometry),contentWidth:width,contentHeight:height,geometry}});
27新增: });
28新增: },
29新增:});
30新增:try {
31新增: await page.getByRole("button",{name:"Claude Desktop",exact:true}).click();
32新增: const pane = page.locator(".mac-claude-frame");
33新增: const img = pane.getByRole("img");
34新增: async function fillsPane() {
35新增: await page.waitForFunction(() => {
36新增: const box=document.querySelector(".mac-claude-frame"), img=box?.querySelector("img");
37新增: if (!img?.complete || !img.naturalWidth) return false;
38新增: const a=img.getBoundingClientRect(), b=box.getBoundingClientRect();
39新增: return Math.abs(a.width-b.width)<2 && Math.abs(a.height-b.height)<2 &&
40新增: Math.abs(img.naturalWidth-2*b.width)<3 && Math.abs(img.naturalHeight-2*b.height)<3;
41新增: });
42新增: }
43新增: await fillsPane();
44新增: await page.setViewportSize({width:1110,height:750});
45新增: await fillsPane();
46新增: fixed=true;
47新增: await page.waitForFunction(() => document.querySelector(".mac-claude-frame img")?.naturalWidth===1200 &&
48新增: getComputedStyle(document.querySelector(".mac-claude-frame")).backgroundColor==="rgb(247, 245, 241)");
49新增: const bounds = await img.boundingBox();
50新增: assert.ok(Math.abs(bounds.width-600)<1);
51新增: await img.click({position:{x:bounds.width/2,y:bounds.height/2}});
52新增: await page.waitForFunction(() => document.activeElement?.classList.contains("mac-claude-typing"));
53新增: for (let i=0; !clicks.length && i<40; i++) await new Promise(r=>setTimeout(r,25));
54新增: assert.equal(clicks[0]?.geometry,"600x560");
55新增: assert.ok(Math.abs(clicks[0].x-0.5)<0.005 && Math.abs(clicks[0].y-0.5)<0.005);
56新增: assert.equal(await img.evaluate(el=>getComputedStyle(el).outlineStyle),"none");
57新增: assert.equal(await page.evaluate(()=>document.fullscreenElement),null);
58新增: assert.deepEqual(errors,[]);
59新增: console.log("2x pixels, panel resize, fixed-window background, focus and cropped-frame inputs passed.");
60新增:} finally { await browser.close(); }
新增ui/scripts/macos-default-workspace-smoke.mjs+85 −0看文件
@@ -0,0 +1,85 @@
1新增:import assert from "node:assert/strict";
2新增:import { mkdir, mkdtemp, writeFile } from "node:fs/promises";
3新增:import { tmpdir } from "node:os";
4新增:import { join } from "node:path";
5新增:import { createWorkbench } from "./workbench-fixture.mjs";
6新增:
7新增:const output = process.env.CAGE_WORKSPACE_QA_OUTPUT || await mkdtemp(join(tmpdir(), "cage-default-workspace-ui-"));
8新增:await mkdir(output, { recursive: true });
9新增:const notice = "此历史会话仍使用原来的客机目录,文件保留在虚拟 Mac 内。要使用与主机共享的默认工作区,请从默认工作区新建会话。";
10新增:let allowed = false;
11新增:let screenAllowed = false, frameReads = 0, frameReadsAtClick = 0;
12新增:const actions = [];
13新增:const fixture = await createWorkbench({
14新增: beforeNavigate: async (page, state) => {
15新增: const panelImage = await page.evaluate(() => {
16新增: const canvas = document.createElement("canvas");
17新增: canvas.width = 480;
18新增: canvas.height = 260;
19新增: const context = canvas.getContext("2d");
20新增: context.fillStyle = "#eee";
21新增: context.fillRect(0, 0, canvas.width, canvas.height);
22新增: return canvas.toDataURL("image/png").split(",")[1];
23新增: });
24新增: state.account.guest_system = state.status.guest_system = "macos";
25新增: state.status.vm_running = state.status.ready = true;
26新增: state.status.project_error = "请在虚拟 Mac 的项目授权窗口中选中此项目,然后重新打开";
27新增: state.status.project_errors = [{ path: state.settings.workspace, message: state.status.project_error }];
28新增: await page.route("**/api/projects/open", async route => {
29新增: actions.push(route.request().postDataJSON());
30新增: if (allowed) {
31新增: state.status.project_error = "";
32新增: state.status.project_errors = [];
33新增: }
34新增: return route.fulfill({ json: { workspace: state.settings.workspace, ...(allowed ? {} : { approval: "fixture-grant" }) } });
35新增: });
36新增: await page.route("**/api/macos/project-approval", route => {
37新增: if (route.request().postDataJSON().action === "click") {
38新增: frameReadsAtClick = frameReads;
39新增: return route.fulfill({ json: { error: "accessibility_permission" } });
40新增: }
41新增: frameReads++;
42新增: return route.fulfill({ json: screenAllowed
43新增: ? { image: panelImage, window: 1, pid: 5, nonce: "fixture" }
44新增: : { error: "project_screen_permission" } });
45新增: });
46新增: await page.route("**/api/cli/sessions/*/account", route => route.fulfill({ json: { supported: false, candidates: [], session: {} } }));
47新增: await page.routeWebSocket("**/api/terminals/**", socket => socket.send(Buffer.from("隔离测试终端\r\n/Users/cage/.local/share/cage/workspace $ ")));
48新增: },
49新增:});
50新增:const { page, state, browser, errors } = fixture;
51新增:try {
52新增: await page.getByRole("button", { name: "连接项目", exact: true }).click();
53新增: const project = page.getByRole("dialog", { name: "打开项目", exact: true });
54新增: await project.waitFor();
55新增: assert.equal(await project.getByRole("textbox", { name: "新项目文件夹", exact: true }).inputValue(), state.settings.workspace);
56新增: await project.getByRole("button", { name: "打开项目", exact: true }).click();
57新增: const permission = page.getByRole("dialog", { name: "允许客机访问所选项目", exact: true });
58新增: await permission.waitFor();
59新增: await permission.getByText(state.settings.workspace, { exact: true }).waitFor();
60新增: await permission.getByRole("status").filter({ hasText: "屏幕与系统音频录制" }).waitFor();
61新增: await page.screenshot({ path: join(output, "default-workspace-approval.png"), animations: "disabled" });
62新增: screenAllowed = true;
63新增: await permission.getByRole("img").click();
64新增: const inputError = permission.getByRole("alert").filter({ hasText: "辅助功能" });
65新增: await inputError.waitFor();
66新增: await permission.getByRole("img").waitFor();
67新增: assert.ok(frameReads > frameReadsAtClick, "next guest frame was fetched");
68新增: assert.ok(await inputError.isVisible(), "polling must retain the failed click");
69新增: allowed = true;
70新增: await permission.getByRole("button", { name: "验证授权", exact: true }).click();
71新增: await permission.waitFor({ state: "hidden" });
72新增: assert.equal(actions.length, 2);
73新增: assert.ok(actions.every(item => item.workspace === state.settings.workspace));
74新增:
75新增: state.terminals = [{ id: "legacy-default", kind: "claude", title: "历史默认会话", workspace: state.settings.workspace,
76新增: cli_session_id: "01234567-1234-4234-8234-0123456789ab", workspace_notice: notice, closed: true }];
77新增: await page.reload();
78新增: await page.getByRole("tab", { name: "历史默认会话", exact: true }).click();
79新增: await page.getByRole("status").filter({ hasText: notice }).waitFor();
80新增: await page.screenshot({ path: join(output, "default-workspace-legacy-notice.png"), animations: "disabled" });
81新增: assert.deepEqual(errors, []);
82新增: const result = { passed: true, browser: browser.browserType().name(), actions, checks: ["default workspace reconnect opens existing project authorization", "missing screen permission shows the macOS settings path", "click permission error survives the next frame", "permission retry keeps the same host directory", "legacy guest-private workspace notice is visible in the terminal"] };
83新增: await writeFile(join(output, "result.json"), JSON.stringify(result, null, 2));
84新增: console.log(JSON.stringify(result));
85新增:} finally { await browser.close(); }
新增ui/scripts/macos-desktop-files-fixture.jsx+15 −0看文件
@@ -0,0 +1,15 @@
1新增:import React, { useState } from "react";
2新增:import { createRoot } from "react-dom/client";
3新增:import { MacOSClaudeWindow } from "../src/macos-claude-window";
4新增:import { useDesktopFiles } from "../src/browser-downloads";
5新增:import "../src/style.css";
6新增:
7新增:function Fixture() {
8新增: const [notice, setNotice] = useState("");
9新增: const files = useDesktopFiles(true, setNotice);
10新增: return <div className="app">
11新增: <output>{notice}</output>
12新增: <MacOSClaudeWindow visible uploads={files.uploads} onStatus={setNotice} onConfirm={async () => true} />
13新增: </div>;
14新增:}
15新增:createRoot(document.getElementById("root")).render(<Fixture />);
新增ui/scripts/macos-desktop-files-smoke.mjs+103 −0看文件
@@ -0,0 +1,103 @@
1新增:import assert from "node:assert/strict";
2新增:import { createRequire } from "node:module";
3新增:import { fileURLToPath } from "node:url";
4新增:import { createServer } from "vite";
5新增:
6新增:const require = createRequire(import.meta.url);
7新增:const engine = process.env.CAGE_TEST_BROWSER || "chromium";
8新增:const playwright = require(process.env.CAGE_PLAYWRIGHT_MODULE || "playwright");
9新增:const vite = await createServer({ root: fileURLToPath(new URL("..", import.meta.url)), configFile: fileURLToPath(new URL("../vite.config.js", import.meta.url)), server: { host: "127.0.0.1", port: 0 } });
10新增:await vite.listen();
11新增:const origin = `http://127.0.0.1:${vite.httpServer.address().port}`;
12新增:const browser = await playwright[engine].launch({ headless: true });
13新增:const page = await browser.newPage({ viewport: { width: 1280, height: 850 } });
14新增:const png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIHWP4z8DwHwAFgAI/ScLbtAAAAABJRU5ErkJggg==";
15新增:const operations = [], errors = [];
16新增:let sequence = 0, failUpload = false, chooser = null;
17新增:page.on("pageerror", error => errors.push(error.message));
18新增:await page.route("**/mac-files-test", async route => route.fulfill({ contentType: "text/html", body: await vite.transformIndexHtml("/mac-files-test", '<div id="root"></div><script type="module" src="/scripts/macos-desktop-files-fixture.jsx"></script>') }));
19新增:await page.route("**/api/**", async route => {
20新增: const request = route.request(), url = new URL(request.url());
21新增: if (url.pathname === "/api/macos/claude/window") {
22新增: const value = request.postDataJSON();
23新增: if (value.action === "status") return route.fulfill({ json: { installed: true, running: true, input: true, screen: true, persistent: false, version: "fixture" } });
24新增: if (value.action === "frame") return route.fulfill({ json: { image: png, pid: 100, window: 7, geometry: "stable-window", contentWidth: 640, contentHeight: 480 } });
25新增: return route.fulfill({ json: { ok: true } });
26新增: }
27新增: if (url.pathname === "/api/input/files/desktop/requests") return route.fulfill({ json: { available: true, uploads: chooser ? [chooser] : [], downloads: [], opens: [] } });
28新增: if (url.pathname === "/api/input/files/start") {
29新增: const body = request.postDataJSON();
30新增: operations.push({ action: "start", body });
31新增: return route.fulfill({ json: { ok: true, id: `11111111-2222-4333-8444-${String(++sequence).padStart(12, "0")}` } });
32新增: }
33新增: if (url.pathname.startsWith("/api/input/files/desktop/")) {
34新增: operations.push({ action: "upload", name: url.searchParams.get("name"), bytes: request.postDataBuffer()?.length });
35新增: if (failUpload) { failUpload = false; return route.fulfill({ status: 500, contentType: "text/plain", body: "测试附件传递中断,请重新选择文件" }); }
36新增: return route.fulfill({ json: { ok: true } });
37新增: }
38新增: if (["/api/input/files/finish", "/api/input/files/cancel"].includes(url.pathname)) {
39新增: operations.push({ action: url.pathname.split("/").at(-1), body: request.postDataJSON() });
40新增: chooser = null;
41新增: return route.fulfill({ json: { ok: true } });
42新增: }
43新增: if (url.pathname === "/api/input/image") {
44新增: operations.push({ action: "image", body: request.postDataJSON() });
45新增: return route.fulfill({ json: { ok: true } });
46新增: }
47新增: if (url.pathname === "/api/input/paste/start") return route.fulfill({ json: { available: true, transfer: "22222222-3333-4444-8555-666666666666" } });
48新增: return route.fulfill({ json: { running: true, ready: true, available: true } });
49新增:});
50新增:const waitForCount = async (action, count) => {
51新增: for (let attempt = 0; attempt < 150; attempt++) {
52新增: if (operations.filter(item => item.action === action).length >= count) return;
53新增: await new Promise(resolve => setTimeout(resolve, 40));
54新增: }
55新增: throw new Error(`Did not observe ${count} ${action} operations`);
56新增:};
57新增:const choose = async name => {
58新增: const selected = page.waitForEvent("filechooser");
59新增: await page.getByRole("button", { name: "添加附件", exact: true }).click();
60新增: await (await selected).setFiles({ name, mimeType: "text/plain", buffer: Buffer.from("file bytes 中文") });
61新增:};
62新增:try {
63新增: await page.goto(origin + "/mac-files-test");
64新增: await page.getByAltText("Claude Desktop 客机窗口").waitFor();
65新增: await choose("paper.txt");
66新增: await waitForCount("finish", 1);
67新增: assert.deepEqual(operations.slice(0, 3).map(item => item.action), ["start", "upload", "finish"]);
68新增: assert.equal(operations[0].body.target, "desktop");
69新增: assert.equal(operations[0].body.pid, 100);
70新增: assert.equal(operations[0].body.window, 7);
71新增: assert.equal(operations[1].name, "paper.txt");
72新增: await page.locator(".mac-claude-frame").evaluate(element => {
73新增: const data = new DataTransfer();
74新增: data.items.add(new File(["drop data"], "dropped.txt", { type: "text/plain" }));
75新增: const box = element.getBoundingClientRect();
76新增: element.dispatchEvent(new DragEvent("drop", { bubbles: true, cancelable: true, dataTransfer: data, clientX: box.x + box.width / 2, clientY: box.y + box.height / 2 }));
77新增: });
78新增: await waitForCount("finish", 2);
79新增: assert.equal(operations.filter(item => item.action === "start").at(-1).body.kind, "drop");
80新增: await page.getByLabel("向 Claude Desktop 输入").evaluate((element, png) => {
81新增: const data = new DataTransfer();
82新增: const bytes = Uint8Array.from(atob(png), value => value.charCodeAt(0));
83新增: data.items.add(new File([bytes], "image.png", { type: "image/png" }));
84新增: element.dispatchEvent(new ClipboardEvent("paste", { bubbles: true, cancelable: true, clipboardData: data }));
85新增: }, png);
86新增: await waitForCount("image", 1);
87新增: assert.equal(operations.find(item => item.action === "image").body.target, "desktop");
88新增: assert.equal(operations.find(item => item.action === "image").body.pid, 100);
89新增: assert.equal(operations.find(item => item.action === "image").body.window, 7);
90新增: failUpload = true;
91新增: await choose("failed.txt");
92新增: await waitForCount("cancel", 1);
93新增: await page.getByRole("alert").filter({ hasText: "测试附件传递中断" }).waitFor();
94新增: await choose("retry.txt");
95新增: await waitForCount("finish", 3);
96新增: chooser = { id: "99999999-2222-4333-8444-111111111111", kind: "chooser", multiple: true, target: "desktop" };
97新增: await page.getByText("上传本机文件", { exact: true }).waitFor();
98新增: await page.locator('.browser-upload-body input[type="file"]').setInputFiles({ name: "native-dialog.txt", mimeType: "text/plain", buffer: Buffer.from("chooser bytes") });
99新增: await waitForCount("finish", 4);
100新增: assert.equal(operations.filter(item => item.action === "finish").at(-1).body.id, "99999999-2222-4333-8444-111111111111");
101新增: assert.deepEqual(errors, []);
102新增: console.log(JSON.stringify({ result: "PASS", engine, checks: ["attachment button", "file drop", "PNG paste", "failed upload cancels", "retry after failure", "native chooser request"], operations: operations.map(({ body, ...item }) => ({ ...item, ...(body ? { target: body.target, kind: body.kind } : {}) })) }));
103新增:} finally { await browser.close(); await vite.close(); }
新增ui/scripts/macos-display-push-smoke.mjs+98 −0看文件
@@ -0,0 +1,98 @@
1新增:import assert from "node:assert/strict";
2新增:import { createWorkbench } from "./workbench-fixture.mjs";
3新增:
4新增:const actions = [], subscriptions = [], acknowledgements = [];
5新增:let activeSocket, image, closed = 0;
6新增:const status = { installed: true, running: true, screen: true, input: true, persistent: true, push_frames: true };
7新增:function frame(sequence, revision, geometry = "geometry-1") {
8新增: const header = Buffer.from(JSON.stringify({
9新增: imageLength: image.length, mime: "image/png", sequence, revision, geometry,
10新增: window: 70, pid: 23, contentWidth: 400, contentHeight: 300, pixelWidth: 800, pixelHeight: 600,
11新增: }));
12新增: const size = Buffer.alloc(4);
13新增: size.writeUInt32BE(header.length);
14新增: activeSocket.send(Buffer.concat([size, header, image]));
15新增:}
16新增:const { page, browser, errors } = await createWorkbench({
17新增: async beforeNavigate(page, state) {
18新增: state.account.guest_system = "macos";
19新增: state.status.vm_running = state.status.ready = true;
20新增: image = Buffer.from(await page.evaluate(() => {
21新增: const canvas = document.createElement("canvas");
22新增: canvas.width = 800; canvas.height = 600;
23新增: const context = canvas.getContext("2d");
24新增: context.fillStyle = "#f7f5f1"; context.fillRect(0, 0, 800, 600);
25新增: return canvas.toDataURL().split(",")[1];
26新增: }), "base64");
27新增: await page.addInitScript(() => {
28新增: const create = URL.createObjectURL.bind(URL), revoke = URL.revokeObjectURL.bind(URL);
29新增: window.frameURLs = new Set();
30新增: URL.createObjectURL = blob => { const url = create(blob); window.frameURLs.add(url); return url; };
31新增: URL.revokeObjectURL = url => { window.frameURLs.delete(url); revoke(url); };
32新增: });
33新增: await page.route("**/api/macos/claude/window", route => {
34新增: assert.equal(route.request().postDataJSON().action, "status");
35新增: return route.fulfill({ json: status });
36新增: });
37新增: await page.routeWebSocket("**/api/macos/claude/connection**", socket => {
38新增: socket.onClose(() => { closed++; });
39新增: socket.onMessage(data => {
40新增: const { id, request } = JSON.parse(data);
41新增: actions.push(request.action);
42新增: assert.notEqual(request.action, "frame", "capture waits must use the separate frame channel");
43新增: socket.send(JSON.stringify({ id, result: status }));
44新增: });
45新增: });
46新增: await page.routeWebSocket("**/api/macos/claude/frames**", socket => {
47新增: activeSocket = socket;
48新增: socket.onClose(() => { closed++; });
49新增: socket.onMessage(data => {
50新增: const request = JSON.parse(data);
51新增: if (request.ack) { acknowledgements.push(request.ack); return; }
52新增: subscriptions.push(request);
53新增: if (request.revision === 1) frame(`initial-${subscriptions.length}`, request.revision);
54新增: });
55新增: });
56新增: },
57新增:});
58新增:async function until(condition) {
59新增: const deadline = Date.now() + 5000;
60新增: while (!condition()) {
61新增: assert(Date.now() < deadline, "timed out waiting for a frame channel event");
62新增: await new Promise(resolve => setTimeout(resolve, 20));
63新增: }
64新增:}
65新增:try {
66新增: await page.getByRole("button", { name: "Claude Desktop", exact: true }).click();
67新增: await page.waitForFunction(() => document.querySelector(".mac-claude-frame img")?.naturalWidth === 800);
68新增: await until(() => acknowledgements.length === 1);
69新增: assert((await page.locator(".mac-claude-frame img").getAttribute("src")).startsWith("blob:"));
70新增: await page.locator(".mac-claude-frame img").click();
71新增: await page.locator(".mac-claude-typing").press("ArrowRight");
72新增: await until(() => actions.includes("pointer") && actions.includes("key"));
73新增: await new Promise(resolve => setTimeout(resolve, 350));
74新增: assert.equal(subscriptions.length, 1, "static windows must retain one subscription");
75新增: assert.equal(acknowledgements.length, 1, "static windows must not request repeated images");
76新增: frame("changed", 1);
77新增: await until(() => acknowledgements.includes("changed"));
78新增: assert.equal(await page.evaluate(() => window.frameURLs.size), 1, "replaced frames must release their blob URLs");
79新增: await page.setViewportSize({ width: 1380, height: 900 });
80新增: await until(() => subscriptions.at(-1).revision > 1);
81新增: const revision = subscriptions.at(-1).revision;
82新增: frame("stale", revision - 1, "stale-geometry");
83新增: frame("resized", revision, "geometry-2");
84新增: await until(() => acknowledgements.includes("resized"));
85新增: assert(!acknowledgements.includes("stale"), "a stale frame must not replace the resized view");
86新增: await page.evaluate(() => { window.cageWindowVisible = false; window.dispatchEvent(new Event("cage-window-visibility")); });
87新增: await until(() => closed === 2);
88新增: assert.equal(await page.evaluate(() => window.frameURLs.size), 0);
89新增: const hiddenActions = actions.length, hiddenSubscriptions = subscriptions.length;
90新增: await new Promise(resolve => setTimeout(resolve, 300));
91新增: assert.equal(actions.length, hiddenActions);
92新增: assert.equal(subscriptions.length, hiddenSubscriptions);
93新增: await page.evaluate(() => { window.cageWindowVisible = true; window.dispatchEvent(new Event("cage-window-visibility")); });
94新增: await until(() => subscriptions.length > hiddenSubscriptions);
95新增: await page.waitForFunction(() => document.querySelector(".mac-claude-frame img")?.naturalWidth === 800);
96新增: assert.deepEqual(errors, []);
97新增: console.log("Binary push, decode acknowledgements, independent input, resize, blob cleanup, hide and resume passed.");
98新增:} finally { await browser.close(); }
新增ui/scripts/macos-display-stream-smoke.mjs+62 −0看文件
@@ -0,0 +1,62 @@
1新增:import assert from "node:assert/strict";
2新增:import { createWorkbench } from "./workbench-fixture.mjs";
3新增:
4新增:let requests = 0, images = 0, closed = 0;
5新增:const actions = [];
6新增:const status = { installed: true, running: true, screen: true, input: true, persistent: true };
7新增:const { page, browser, errors } = await createWorkbench({
8新增: async beforeNavigate(page, state) {
9新增: state.account.guest_system = "macos";
10新增: state.status.vm_running = state.status.ready = true;
11新增: const image = await page.evaluate(() => {
12新增: const canvas = document.createElement("canvas");
13新增: canvas.width = 800; canvas.height = 600;
14新增: const context = canvas.getContext("2d");
15新增: context.fillStyle = "#f7f5f1"; context.fillRect(0, 0, 800, 600);
16新增: return canvas.toDataURL().split(",")[1];
17新增: });
18新增: await page.route("**/api/macos/claude/window", route => {
19新增: assert.equal(route.request().postDataJSON().action, "status");
20新增: return route.fulfill({ json: status });
21新增: });
22新增: await page.routeWebSocket("**/api/macos/claude/connection**", socket => {
23新增: socket.onClose(() => { closed++; });
24新增: socket.onMessage(data => {
25新增: requests++;
26新增: const { id, request } = JSON.parse(data);
27新增: actions.push(request.action);
28新增: let result = status;
29新增: if (request.action === "frame") {
30新增: if (request.after === "frame-1") result = { unchanged: true, sequence: "frame-1" };
31新增: else {
32新增: images++;
33新增: result = { window: 70, pid: 23, image, sequence: "frame-1", geometry: "geometry-1", contentWidth: 400, contentHeight: 300 };
34新增: }
35新增: }
36新增: socket.send(JSON.stringify({ id, result }));
37新增: });
38新增: });
39新增: },
40新增:});
41新增:try {
42新增: await page.getByRole("button", { name: "Claude Desktop", exact: true }).click();
43新增: await page.locator(".mac-claude-frame img").waitFor();
44新增: await page.waitForFunction(() => document.querySelector(".mac-claude-frame img")?.naturalWidth === 800);
45新增: await page.locator(".mac-claude-frame img").click();
46新增: await page.locator(".mac-claude-typing").press("ArrowRight");
47新增: assert(actions.includes("click") && actions.includes("key"));
48新增: await new Promise(resolve => setTimeout(resolve, 300));
49新增: assert.equal(images, 1, "static frames must keep their existing decoded image");
50新增: await page.evaluate(() => { window.cageWindowVisible = false; window.dispatchEvent(new Event("cage-window-visibility")); });
51新增: await new Promise(resolve => setTimeout(resolve, 150));
52新增: const hiddenRequests = requests;
53新增: await new Promise(resolve => setTimeout(resolve, 350));
54新增: assert.equal(requests, hiddenRequests, "hidden windows must stop requesting frames");
55新增: assert.equal(closed, 1);
56新增: await page.evaluate(() => { window.cageWindowVisible = true; window.dispatchEvent(new Event("cage-window-visibility")); });
57新增: await page.waitForFunction(() => document.querySelector(".mac-claude-frame img")?.naturalWidth === 800);
58新增: await new Promise(resolve => setTimeout(resolve, 150));
59新增: assert.equal(images, 2, "restoring a window must request a fresh frame");
60新增: assert.deepEqual(errors, []);
61新增: console.log("Persistent frame/input channel, unchanged-frame reuse, hide and restore passed.");
62新增:} finally { await browser.close(); }
新增ui/scripts/macos-first-setup-smoke.mjs+80 −0看文件
@@ -0,0 +1,80 @@
1新增:import assert from "node:assert/strict";
2新增:import { createWorkbench } from "./workbench-fixture.mjs";
3新增:for (const failure of ["http", "native"]) {
4新增: const user = "cage";
5新增: const permissions = { screen:false, input:false, projects:false, managed_credential:true };
6新增: const calls = []; let finishFailed = false;
7新增: const {page, browser, errors} = await createWorkbench({
8新增: async beforeNavigate(page, state) {
9新增: Object.assign(state.account, {initial_mac_setup:true, guest_system:"macos", macos_guest_user:user});
10新增: Object.assign(state.status, {ready:true, vm_running:true});
11新增: const frame = await page.evaluate(() => {
12新增: const canvas = document.createElement("canvas");
13新增: canvas.width = 160; canvas.height = 100;
14新增: return canvas.toDataURL("image/png").split(",")[1];
15新增: });
16新增: await page.route("**/api/macos/first-setup", async r => {
17新增: const q = r.request().postDataJSON(); calls.push(q.action);
18新增: if (q.action === "permissions") return r.fulfill({json:permissions});
19新增: if (q.action === "open") return r.fulfill({json:{session:"setup-fixture"}});
20新增: if (q.action === "frame") return r.fulfill({json:{image:frame}});
21新增: if (q.action === "scroll") {
22新增: assert.equal(q.session,"setup-fixture");
23新增: assert.ok(Number.isInteger(q.x) && q.x >= 0 && q.x < 1024);
24新增: assert.ok(Number.isInteger(q.y) && q.y >= 0 && q.y < 640);
25新增: assert.ok(q.delta_y > 0 && q.delta_y <= 512);
26新增: }
27新增: if (q.action === "fill-password") {
28新增: assert.equal(q.password,undefined,"browser sent a credential");
29新增: assert.equal(q.session,"setup-fixture");
30新增: }
31新增: if (q.action === "finish") {
32新增: assert.ok(permissions.screen && permissions.input && permissions.projects);
33新增: if (!finishFailed) {
34新增: finishFailed=true;
35新增: return failure === "http"
36新增: ? r.fulfill({status:409,body:"临时设置账户未关闭,请重试完成设置"})
37新增: : r.fulfill({json:{error:"未能保存首次设置,请重试"}});
38新增: }
39新增: state.account.initial_mac_setup = false; return r.fulfill({json:{closed:true}});
40新增: }
41新增: return r.fulfill({json:{}});
42新增: });
43新增: },
44新增: });
45新增: async function waitCall(action) {
46新增: for(let i=0; !calls.includes(action) && i<200; i++) await new Promise(resolve=>setTimeout(resolve,20));
47新增: assert.ok(calls.includes(action),`missing ${action}`);
48新增: }
49新增: try {
50新增: await page.getByRole("dialog",{name:"首次设置虚拟 Mac"}).waitFor();
51新增: await waitCall("screen");
52新增: const image = page.getByRole("dialog",{name:"首次设置虚拟 Mac"}).getByRole("img");
53新增: await image.waitFor();
54新增: const box = await image.boundingBox();
55新增: await page.mouse.move(box.x+box.width/2,box.y+box.height/2);
56新增: await page.mouse.wheel(0,400);
57新增: await waitCall("scroll");
58新增: const tools=page.getByRole("toolbar",{name:"画面工具"});
59新增: await tools.getByRole("button",{name:"填写授权密码"}).click();
60新增: await waitCall("fill-password");
61新增: permissions.screen=true;
62新增: await waitCall("input");
63新增: permissions.input=true;
64新增: await waitCall("projects");
65新增: assert.ok(!calls.includes("finish"),"finished before filesystem permission");
66新增: permissions.projects=true;
67新增: await page.getByRole("button",{name:"返回设置指引"}).click();
68新增: const retry=page.getByRole("button",{name:"重试完成设置"});
69新增: await retry.waitFor();
70新增: await page.getByRole("button",{name:"文件系统扩展 ✓",exact:true}).click();
71新增: await page.getByRole("alert").waitFor({state:"hidden"});
72新增: assert.ok(await retry.isVisible(), "checking permissions hid the completion retry");
73新增: await retry.click();
74新增: await page.getByRole("heading",{name:"正在准备虚拟 Mac"}).waitFor({state:"hidden"});
75新增: assert.equal(calls.filter(c=>c==="finish").length,2);
76新增: assert.equal(calls.filter(c=>c==="verify-projects").length,0);
77新增: assert.deepEqual(errors, []);
78新增: console.log(user,failure,"automatic setup view, permission progression, credential fill, completion and failure recovery passed");
79新增: } finally { await browser.close(); }
80新增:}
新增ui/scripts/macos-input-smoke.mjs+100 −0看文件
@@ -0,0 +1,100 @@
1新增:import assert from "node:assert/strict";
2新增:import { createWorkbench } from "./workbench-fixture.mjs";
3新增:
4新增:const inputs = [], status = { installed: true, running: true, screen: true, input: true, input_protocol: 1, persistent: true };
5新增:let image, geometry = "input-geometry-1";
6新增:const { page, browser, errors } = await createWorkbench({
7新增: async beforeNavigate(page, state) {
8新增: state.account.guest_system = state.status.guest_system = "macos";
9新增: state.status.vm_running = state.status.ready = true;
10新增: image = await page.evaluate(() => {
11新增: const canvas = document.createElement("canvas");
12新增: canvas.width = 640; canvas.height = 480;
13新增: const context = canvas.getContext("2d");
14新增: context.fillStyle = "#f7f5f1"; context.fillRect(0, 0, 640, 480);
15新增: context.fillStyle = "#303030"; context.font = "22px sans-serif";
16新增: context.fillText("Synthetic Claude input surface", 30, 45);
17新增: return canvas.toDataURL().split(",")[1];
18新增: });
19新增: await page.route("**/api/macos/claude/window", route => route.fulfill({ json: status }));
20新增: await page.routeWebSocket("**/api/macos/claude/connection**", socket => {
21新增: socket.onMessage(data => {
22新增: const { id, request } = JSON.parse(data);
23新增: let result = { ok: true };
24新增: if (request.action === "status") result = status;
25新增: else if (request.action === "frame") result = { image, pid: 23, window: 70, geometry, contentWidth: 640, contentHeight: 480 };
26新增: else {
27新增: inputs.push(request);
28新增: if (request.action === "ime") result = { available: true, context: "a".repeat(32), preedit_supported: false,
29新增: rect: [80, 70, 1, 24], width: 640, height: 480 };
30新增: }
31新增: socket.send(JSON.stringify({ id, result }));
32新增: });
33新增: });
34新增: },
35新增:});
36新增:page.setDefaultTimeout(10000);
37新增:async function until(predicate) {
38新增: for (let attempt = 0; attempt < 200; attempt++) {
39新增: if (predicate()) return;
40新增: await page.waitForTimeout(20);
41新增: }
42新增: assert(predicate(), "expected native window input did not arrive");
43新增:}
44新增:try {
45新增: await page.getByRole("button", { name: "Claude Desktop", exact: true }).click();
46新增: const surface = page.getByAltText("Claude Desktop 客机窗口");
47新增: await surface.waitFor();
48新增: await page.getByLabel("向 Claude Desktop 输入").waitFor({ state: "attached" });
49新增: const bounds = await surface.boundingBox();
50新增: await page.mouse.move(bounds.x + 80, bounds.y + 100);
51新增: await page.mouse.down();
52新增: await page.mouse.move(bounds.x + 360, bounds.y + 160, { steps: 5 });
53新增: await page.mouse.up();
54新增: await until(() => inputs.some(input => input.action === "pointer" && input.phase === "up"));
55新增: const drag = inputs.filter(input => input.action === "pointer");
56新增: const firstDown = drag.findIndex(input => input.phase === "down");
57新增: assert(firstDown >= 0 && drag.slice(firstDown + 1, -1).some(input => input.phase === "move" && input.buttons === 1));
58新增: assert.equal(drag.at(-1).phase, "up");
59新增: assert(drag.every(input => input.geometry === geometry && input.pid === 23 && input.window === 70));
60新增: await surface.click({ button: "right", position: { x: 150, y: 160 } });
61新增: await surface.dblclick({ position: { x: 200, y: 190 } });
62新增: await until(() => inputs.some(input => input.button === 2 && input.phase === "up") && inputs.some(input => input.clicks === 2));
63新增:
64新增: await page.keyboard.press("Meta+f");
65新增: assert.equal(await page.evaluate(() => window.cageEditAction("selectAll")), true);
66新增: await page.keyboard.press("F5");
67新增: await until(() => inputs.some(input => input.action === "key" && input.code === "F5" && !input.down));
68新增: assert(inputs.some(input => input.code === "KeyF" && input.command));
69新增: assert(inputs.some(input => input.code === "KeyA" && input.command));
70新增: await until(() => inputs.some(input => input.action === "ime" && input.mode === "status"));
71新增: await page.getByLabel("向 Claude Desktop 输入").evaluate(element => {
72新增: element.dispatchEvent(new CompositionEvent("compositionstart", { bubbles: true }));
73新增: element.value = "nihao";
74新增: element.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "insertCompositionText", isComposing: true, data: "nihao" }));
75新增: element.dispatchEvent(new CompositionEvent("compositionend", { bubbles: true, data: "你好🙂" }));
76新增: });
77新增: await page.keyboard.press("Enter");
78新增: await until(() => inputs.some(input => input.action === "ime" && input.mode === "commit"));
79新增: const composition = inputs.filter(input => input.action === "ime" && input.mode !== "status");
80新增: assert.deepEqual(composition.map(input => input.mode), ["begin", "update", "commit"]);
81新增: assert.equal(composition[2].text, "你好🙂");
82新增: assert(composition.every(input => input.session === composition[0].session && input.geometry === geometry));
83新增: assert.deepEqual(composition.map(input => input.sequence), [0, 1, 2]);
84新增: await until(() => inputs.some(input => input.code === "Enter" && !input.down));
85新增: assert(inputs.indexOf(composition[2]) < inputs.findIndex(input => input.code === "Enter" && input.down));
86新增:
87新增: const resetCount = inputs.filter(input => input.action === "input-reset").length;
88新增: await page.mouse.down();
89新增: await page.evaluate(() => window.dispatchEvent(new Event("blur")));
90新增: await until(() => inputs.filter(input => input.action === "input-reset").length > resetCount);
91新增: await page.mouse.up();
92新增: const beforeResize = inputs.filter(input => input.action === "input-reset").length;
93新增: geometry = "input-geometry-2";
94新增: await until(() => inputs.filter(input => input.action === "input-reset").length > beforeResize);
95新增: await surface.click({ position: { x: 40, y: 50 } });
96新增: await page.keyboard.press("ArrowLeft");
97新增: await until(() => inputs.some(input => input.code === "ArrowLeft" && !input.down && input.geometry === geometry));
98新增: assert.deepEqual(errors, []);
99新增: console.log(JSON.stringify({ result: "PASS", checks: ["drag with held left button", "right click", "double click count", "Command find", "host edit menu select-all", "F5", "IME begin/update/commit before Enter", "blur releases input", "geometry change resets and rebinds input"], requests: inputs.filter(input => input.action !== "frame" && input.mode !== "status") }));
100新增:} finally { await browser.close(); }
新增ui/scripts/macos-login-fullscreen-smoke.mjs+123 −0看文件
@@ -0,0 +1,123 @@
1新增:import assert from "node:assert/strict";
2新增:import { createWorkbench } from "./workbench-fixture.mjs";
3新增:
4新增:for (const viewport of [{ width: 1280, height: 900 }, { width: 1920, height: 1080 }, { width: 390, height: 700 }]) {
5新增: const nativeCalls = [], inputs = [], closed = [];
6新增: let finish = false, sessionID = 0, frameMime = "image/jpeg";
7新增: const fixture = await createWorkbench({
8新增: viewport,
9新增: nativeRequest: (message) => nativeCalls.push(message),
10新增: async beforeNavigate(page, state) {
11新增: state.status.ready = true; state.status.vm_running = true;
12新增: const images = await page.evaluate(() => {
13新增: const canvas = document.createElement("canvas");
14新增: canvas.width = 1920; canvas.height = 1200;
15新增: const ctx = canvas.getContext("2d");
16新增: ctx.fillStyle = "#526482"; ctx.fillRect(0, 0, 1920, 1200);
17新增: ctx.fillStyle = "#ddd"; ctx.beginPath(); ctx.arc(960, 1000, 32, 0, Math.PI*2); ctx.fill();
18新增: ctx.fillStyle = "white"; ctx.font = "20px sans-serif"; ctx.textAlign = "center";
19新增: ctx.fillText("Cage", 960, 1050);
20新增: ctx.fillStyle = "#ffffff88"; ctx.fillRect(880, 1070, 160, 30);
21新增: ctx.fillStyle = "white"; ctx.font = "14px sans-serif";
22新增: ctx.fillText("Enter Password", 960, 1091);
23新增: return Object.fromEntries(["image/jpeg", "image/png"].map((m) => [m, canvas.toDataURL(m).split(",")[1]]));
24新增: });
25新增: await page.route("**/api/account", (r) => r.fulfill({json:{exists:true, unlocked:true, trusted_local:true, guest_system:"macos"}}));
26新增: await page.route("**/api/terminals", (r) => r.fulfill({json:[]}));
27新增: await page.route("**/api/macos/login", (r) => {
28新增: const q = r.request().postDataJSON();
29新增: if (q.action === "open") return r.fulfill({json:{session:"trial-" + (++sessionID)}});
30新增: if (q.action === "close") { closed.push(q.session); return r.fulfill({json:{closed:true}}); }
31新增: if (q.action === "frame") return r.fulfill({json:finish ? {closed:true} :
32新增: {image:images[frameMime], ...(frameMime === "image/jpeg" ? {mime:frameMime} : {})}});
33新增: inputs.push(q);
34新增: return r.fulfill({json:{}});
35新增: });
36新增: },
37新增: });
38新增: const { page, browser, errors } = fixture;
39新增: async function waitInput(count) {
40新增: for (let i=0; inputs.length < count && i<150; i++) await new Promise((r) => setTimeout(r, 20));
41新增: assert.equal(inputs.length, count);
42新增: }
43新增: try {
44新增: if (viewport.width < 600) await page.getByRole("button",{name:"收起侧栏",exact:true}).click();
45新增: const trigger=page.getByRole("button",{name:"登录客机账户"});
46新增: await trigger.click({timeout:7000});
47新增: const screen=page.getByRole("dialog",{name:"登录虚拟 Mac"});
48新增: const img=screen.getByRole("img");
49新增: const input=screen.getByLabel(/^客机登录键盘/);
50新增: await img.waitFor();
51新增: await page.waitForFunction(() => document.activeElement?.classList.contains("mac-login-keyboard") &&
52新增: document.querySelector(".mac-login-canvas img")?.naturalWidth === 1920);
53新增: assert.equal(await screen.evaluate((el) => el.parentElement === document.body),true);
54新增: assert.equal(await page.locator("#root").evaluate((el) => el.inert),true);
55新增: const panel=await screen.locator(".mac-login-panel").boundingBox();
56新增: assert.ok(panel.width < viewport.width && panel.height < viewport.height, "login should use a compact panel");
57新增: const stage=screen.locator(".mac-login-stage");
58新增: const area=await stage.boundingBox();
59新增: const focus=screen.getByRole("button",{name:"登录区域", exact:true});
60新增: assert.equal(await focus.getAttribute("aria-pressed"),"true");
61新增: const initial=await img.boundingBox();
62新增: // Avatar, password and the lower login message must all remain in the crop.
63新增: for (const [x,y] of [[.5,.82],[.5,.9],[.5,.96]]) {
64新增: assert.ok(initial.x+initial.width*x >= area.x && initial.x+initial.width*x < area.x+area.width);
65新增: assert.ok(initial.y+initial.height*y >= area.y && initial.y+initial.height*y < area.y+area.height);
66新增: }
67新增: const passwordX=Math.round(initial.x+initial.width*.5), passwordY=Math.round(initial.y+initial.height*.9);
68新增: await page.mouse.click(passwordX,passwordY);
69新增: await waitInput(1);
70新增: assert.ok(Math.abs(inputs[0].x-512)<=1 && Math.abs(inputs[0].y-576)<=1);
71新增: inputs.length=0;
72新增: if (process.env.CAGE_LOGIN_SCREENSHOTS) await page.screenshot({path:`${process.env.CAGE_LOGIN_SCREENSHOTS}/login-${viewport.width}.png`});
73新增: assert.equal(await page.evaluate(() => window.cageEditAction("paste")),false);
74新增: await screen.getByRole("button",{name:"完整画面"}).click();
75新增: const fit=await img.boundingBox();
76新增: assert.ok(Math.abs(fit.width/fit.height - 1.6)<.005);
77新增: if (fit.x > area.x+1) await page.mouse.click((area.x+fit.x)/2,area.y+area.height/2);
78新增: else await page.mouse.click(area.x+area.width/2,(area.y+area.height+fit.y+fit.height)/2);
79新增: assert.equal(inputs.length,0,"letterbox click leaked");
80新增: const fitX=Math.round(fit.x+fit.width/2), fitY=Math.round(fit.y+fit.height/2);
81新增: await page.mouse.click(fitX,fitY);
82新增: await waitInput(1);
83新增: assert.equal(inputs[0].x,Math.floor((fitX-fit.x)*1024/fit.width));
84新增: assert.equal(inputs[0].y,Math.floor((fitY-fit.y)*640/fit.height));
85新增: await focus.click();
86新增: const zoom=await img.boundingBox();
87新增: assert.ok(zoom.width > 3*fit.width);
88新增: await page.mouse.move(area.x+area.width/2,area.y+area.height/2);
89新增: await page.mouse.down(); await page.mouse.move(area.x+area.width/2+90,area.y+area.height/2+55,{steps:5}); await page.mouse.up();
90新增: const pan=await img.boundingBox();
91新增: assert.ok(pan.x>zoom.x+60 && pan.y>zoom.y+30);
92新增: const x=Math.round(area.x+area.width*.65), y=Math.round(area.y+area.height*.6);
93新增: await page.mouse.click(x,y);
94新增: await waitInput(2);
95新增: assert.equal(inputs[1].x,Math.floor((x-pan.x)*1024/pan.width));
96新增: assert.equal(inputs[1].y,Math.floor((y-pan.y)*640/pan.height));
97新增: await input.press("Enter"); await waitInput(3); assert.equal(inputs[2].code,36);
98新增: await input.evaluate((el) => {
99新增: const data=new DataTransfer(); data.setData("text/plain","Z7");
100新增: el.dispatchEvent(new ClipboardEvent("paste",{bubbles:true,cancelable:true,clipboardData:data}));
101新增: });
102新增: await waitInput(5);
103新增: assert.deepEqual(inputs.slice(-2).map(({code,shift})=>[code,shift]),[[6,true],[26,false]]);
104新增: assert.equal(await input.inputValue(),"");
105新增: await screen.getByRole("button",{name:"完整画面"}).click();
106新增: assert.deepEqual(await img.boundingBox(),fit);
107新增: await page.evaluate(() => window.cageNativeAction("closeTab"));
108新增: await screen.waitFor({state:"detached"});
109新增: await page.waitForFunction(() => document.activeElement?.textContent === "登录客机账户");
110新增: assert.ok(!await page.locator("#root").evaluate((el)=>el.inert));
111新增: frameMime="image/png";
112新增: await trigger.click();
113新增: await page.waitForFunction(() => document.querySelector(".mac-login-canvas img")?.src.startsWith("data:image/png;"));
114新增: assert.equal(await focus.getAttribute("aria-pressed"),"true", "reopening should restore the login crop");
115新增: finish=true;
116新增: await screen.waitFor({state:"detached"});
117新增: assert.deepEqual(closed, ["trial-1","trial-2"]);
118新增: assert.deepEqual(nativeCalls.filter((m)=>/fullscreen/i.test(m.action)),[]);
119新增: assert.equal(await page.evaluate(()=>document.fullscreenElement),null);
120新增: assert.deepEqual(errors,[]);
121新增: console.log(`${viewport.width}×${viewport.height}: default login crop, compact panel, coordinate mapping, fit, pan, paste, native close and completion passed.`);
122新增: } catch (error) { console.error("page:",(await page.locator("body").innerText()).slice(0,700), "errors:", errors); throw error; } finally { await browser.close(); }
123新增:}
新增ui/scripts/macos-phone-desktop-smoke.mjs+107 −0看文件
@@ -0,0 +1,107 @@
1新增:// Phone UI fixture. Native capture and AX input are verified separately.
2新增:import assert from "node:assert/strict";
3新增:import { createRequire } from "node:module";
4新增:import { mkdir, mkdtemp, writeFile } from "node:fs/promises";
5新增:import { tmpdir } from "node:os";
6新增:import { join } from "node:path";
7新增:const require = createRequire(import.meta.url);
8新增:const playwright = require(process.env.CAGE_PLAYWRIGHT_MODULE || "playwright");
9新增:const engine = process.env.CAGE_TEST_BROWSER || "chromium";
10新增:const browser = await playwright[engine].launch({ executablePath: process.env.CAGE_TEST_BROWSER_PATH });
11新增:const output = process.env.CAGE_PHONE_QA_OUTPUT || await mkdtemp(join(tmpdir(), "cage-macos-phone-"));
12新增:await mkdir(output, { recursive: true });
13新增:try {
14新增: const context = await browser.newContext({ viewport: { width: 390, height: 844 }, hasTouch: true, isMobile: true, userAgent: "CageMobile/1" });
15新增: const page = await context.newPage();
16新增: const errors = [], actions = [];
17新增: page.on("pageerror", error => errors.push(error.message));
18新增: const image = await page.evaluate(() => {
19新增: const canvas = document.createElement("canvas"); canvas.width = 900; canvas.height = 600;
20新增: const ctx = canvas.getContext("2d"); ctx.fillStyle = "#eeeae3"; ctx.fillRect(0, 0, 900, 600);
21新增: ctx.fillStyle = "#30312e"; ctx.font = "28px sans-serif";
22新增: ctx.fillText("Claude Desktop · isolated test image", 90, 100);
23新增: ctx.fillStyle = "white"; ctx.fillRect(100, 260, 700, 80);
24新增: ctx.fillStyle = "#555"; ctx.fillText("Tap the input to continue", 150, 310);
25新增: return canvas.toDataURL("image/jpeg").split(",")[1];
26新增: });
27新增: let frame, locked = false;
28新增: await page.route("**/api/**", route => {
29新增: const request = route.request(), path = new URL(request.url()).pathname;
30新增: const input = request.postDataJSON();
31新增: if (path.endsWith("/projects")) return route.fulfill({ json: { host: "隔离测试虚拟 Mac", ready: true, projects: [] } });
32新增: if (path.endsWith("/sessions")) return route.fulfill({ json: { sessions: [] } });
33新增: if (!path.startsWith("/api/mobile/desktop/")) return route.fulfill({ status: 404 });
34新增: const operation = path.split("/").at(-1);
35新增: if (operation === "close") return route.fulfill({ json: { id: frame.id } });
36新增: if (operation === "open") {
37新增: locked = false;
38新增: frame = { ...input, image, document: "mac-window-geometry", focus: "", shared: true, window: "desktop",
39新增: content_width: 900, content_height: 600, login_supported: false, pixel_ratio_supported: true, requested_pixel_ratio: input.pixel_ratio || 1 };
40新增: }
41新增: if (locked) return route.fulfill({ status: 410, contentType: "text/plain; charset=utf-8", body: "Claude Desktop 会话已结束,请重新打开" });
42新增: if (operation === "action") {
43新增: actions.push(input);
44新增: if (input.type === "resize") Object.assign(frame, { width: input.width, height: input.height, requested_pixel_ratio: input.pixel_ratio });
45新增: if (input.type === "tap") { assert.equal(input.document, frame.document); frame.focus = "current-ax-input"; }
46新增: if (input.type === "text") { assert.equal(input.focus, frame.focus); assert.ok(new TextEncoder().encode(input.text).length <= 8192); }
47新增: }
48新增: return route.fulfill({ json: operation === "frame" ? frame : { id: frame.id } });
49新增: });
50新增: await page.goto((process.env.CAGE_UI_URL || "http://127.0.0.1:5298") + "/mobile.html");
51新增: await page.getByRole("dialog", { name: "工作区侧栏" }).getByRole("button", { name: "Claude Desktop", exact: true }).click();
52新增: const screen = page.getByRole("img", { name: "远程 Desktop 画面", exact: true });
53新增: await screen.waitFor();
54新增: await page.getByText(/请在电脑的 Cage 中完成 Claude Desktop 登录/).waitFor();
55新增: assert.equal(await page.getByRole("button", { name: "登录窗口", exact: true }).count(), 0);
56新增: const keyboard = page.getByRole("button", { name: "输入文字", exact: true });
57新增: assert.ok(await keyboard.isDisabled());
58新增: await screen.tap();
59新增: await keyboard.click();
60新增: const tap = actions.find(action => action.type === "tap");
61新增: assert.ok(Math.abs(tap.x - 450) <= 2 && Math.abs(tap.y - 300) <= 2, JSON.stringify(tap));
62新增: const field = page.getByLabel("待插入文字");
63新增: await field.fill("中".repeat(2731));
64新增: assert.ok(await page.getByRole("button", { name: "插入文字" }).isDisabled());
65新增: await page.getByRole("alert").getByText(/单次输入最多 8192 字节/).waitFor();
66新增: const text = "中".repeat(2730) + "ab";
67新增: await field.fill(text);
68新增: await page.getByRole("button", { name: "插入文字" }).click();
69新增: await page.waitForFunction(() => document.querySelector('[aria-label="待插入文字"]')?.value === "");
70新增: assert.equal(actions.filter(action => action.type === "text").at(-1).text, text);
71新增: await page.getByRole("button", { name: "收起输入框" }).click();
72新增: await page.screenshot({ path: join(output, "macos-phone-desktop.png") });
73新增: locked = true;
74新增: await page.getByRole("button", { name: "重新打开", exact: true }).waitFor();
75新增: assert.equal(await screen.count(), 0);
76新增: await page.getByRole("button", { name: "重新打开", exact: true }).click();
77新增: await screen.waitFor();
78新增: assert.ok(await keyboard.isDisabled());
79新增: assert.deepEqual(errors, []);
80新增: const retryPage = await context.newPage();
81新增: let opens = 0, frameReads = 0, opened;
82新增: await retryPage.route("**/api/**", route => {
83新增: const path = new URL(route.request().url()).pathname;
84新增: if (path.endsWith("/projects")) return route.fulfill({ json: { host: "隔离测试虚拟 Mac", ready: true, projects: [] } });
85新增: if (path.endsWith("/sessions")) return route.fulfill({ json: { sessions: [] } });
86新增: if (path.endsWith("/open")) { opened = route.request().postDataJSON(); opens++; return route.fulfill({ json: { id: opened.id } }); }
87新增: if (path.endsWith("/frame")) {
88新增: if (opens === 1) return route.fulfill({ status: ++frameReads === 1 ? 425 : 503, body: "客机浏览器尚未就绪" });
89新增: return route.fulfill({ json: { ...opened, image, document: "browser-page", url: "about:blank" } });
90新增: }
91新增: return route.fulfill({ status: 404 });
92新增: });
93新增: await retryPage.goto((process.env.CAGE_UI_URL || "http://127.0.0.1:5298") + "/mobile.html");
94新增: await retryPage.getByRole("dialog", { name: "工作区侧栏" }).getByRole("button", { name: "浏览器", exact: true }).click();
95新增: await retryPage.getByText("正在启动远程浏览器…", { exact: true }).waitFor();
96新增: const reopen = retryPage.getByRole("button", { name: "重新打开", exact: true });
97新增: await reopen.waitFor();
98新增: assert.equal(await retryPage.getByRole("button", { name: "重新读取画面", exact: true }).count(), 0);
99新增: await reopen.click();
100新增: await retryPage.getByRole("img", { name: "远程浏览器画面" }).waitFor();
101新增: assert.equal(opens, 2);
102新增: assert.equal(frameReads, 2);
103新增: const result = { passed: true, engine, actions: actions.map(({ text, ...action }) => ({ ...action, ...(text ? { textBytes: new TextEncoder().encode(text).length } : {}) })),
104新增: checks: ["native content geometry maps center", "focus required before typing", "8192-byte UTF-8 limit", "shared login instruction", "expired GUI session removes image and reopens", "browser waits after 425, reopens directly after frame 503"] };
105新增: await writeFile(join(output, "result.json"), JSON.stringify(result, null, 2));
106新增: console.log(JSON.stringify(result));
107新增:} finally { await browser.close(); }
新增ui/scripts/macos-resources-smoke.mjs+73 −0看文件
@@ -0,0 +1,73 @@
1新增:import assert from "node:assert/strict";
2新增:import { mkdir, mkdtemp, writeFile } from "node:fs/promises";
3新增:import { tmpdir } from "node:os";
4新增:import { join } from "node:path";
5新增:import { createWorkbench } from "./workbench-fixture.mjs";
6新增:
7新增:const output = process.env.CAGE_RESOURCE_QA_OUTPUT || await mkdtemp(join(tmpdir(), "cage-macos-resource-ui-"));
8新增:await mkdir(output, { recursive: true });
9新增:const requests = [];
10新增:let failSave = false, reads = 0;
11新增:const resource = { runtime: "vz-macos", memory_policy: "fixed", automatic_reclaim: false, running: true,
12新增: automatic: false, memory_gib: 4, cpus: 2, min_memory_gib: 4, min_cpus: 2, max_memory_gib: 12, max_cpus: 5,
13新增: minimum_requirements: { source: "existing-configuration" }, recommended_memory_bytes: 12 * 2 ** 30,
14新增: recommended_cpus: 5, configured_memory_bytes: 4 * 2 ** 30, configured_cpus: 2, restart_required: false,
15新增: observation: { cpus: 2, cpu_percent: null, guest: { total_bytes: 4 * 2 ** 30, available_bytes: 2 * 2 ** 30 } } };
16新增:const fixture = await createWorkbench({ beforeNavigate: async (page, state) => {
17新增: state.account.guest_system = state.status.guest_system = "macos";
18新增: state.status.vm_running = state.status.ready = true;
19新增: await page.route("**/api/environment/resources", route => {
20新增: if (route.request().method() === "POST") {
21新增: const body = route.request().postDataJSON(); requests.push(body);
22新增: if (failSave) return route.fulfill({ status: 400, contentType: "text/plain; charset=utf-8", body: "资源配置保存失败,请检查磁盘权限。" });
23新增: if (body.allocation) Object.assign(resource, body.allocation, { restart_required: true });
24新增: return route.fulfill({ json: { ok: true } });
25新增: }
26新增: reads++;
27新增: resource.observation.observed_at = new Date().toISOString();
28新增: return route.fulfill({ json: resource });
29新增: });
30新增:} });
31新增:const { page, browser, errors } = fixture;
32新增:try {
33新增: await page.getByRole("button", { name: "设置", exact: true }).click();
34新增: await page.getByRole("navigation", { name: "设置分组" }).getByRole("button", { name: "环境与恢复", exact: true }).click();
35新增: const panel = page.getByRole("region", { name: "计算资源", exact: true });
36新增: await panel.getByText(/macOS 客机使用固定的启动内存容量/).waitFor();
37新增: const cpu = panel.locator(".setting-summary-row").filter({ hasText: "CPU 使用率" }).locator("strong");
38新增: assert.equal(await cpu.innerText(), "等待采样");
39新增: assert.equal(await panel.getByLabel("内存上限(GiB)", { exact: true }).getAttribute("min"), "4");
40新增: assert.equal(await panel.getByLabel("CPU 逻辑核心数", { exact: true }).getAttribute("min"), "2");
41新增: await panel.getByText(/当前最低值沿用已有启动配置/).waitFor();
42新增: await panel.getByLabel("内存上限(GiB)", { exact: true }).fill("3");
43新增: await panel.getByRole("button", { name: "保存资源配置", exact: true }).click();
44新增: assert.equal(requests.length, 0);
45新增: await panel.getByLabel("内存上限(GiB)", { exact: true }).fill("6");
46新增: await panel.getByLabel("CPU 逻辑核心数", { exact: true }).fill("3");
47新增: await panel.getByRole("button", { name: "保存资源配置", exact: true }).click();
48新增: await panel.getByText("已保存,重启环境后生效。", { exact: true }).waitFor();
49新增: assert.deepEqual(requests[0].allocation, { automatic: false, memory_gib: 6, cpus: 3 });
50新增: failSave = true;
51新增: await panel.getByRole("button", { name: "保存资源配置", exact: true }).click();
52新增: const error = panel.getByRole("alert").filter({ hasText: "资源配置保存失败" });
53新增: await error.waitFor();
54新增: const before = reads;
55新增: resource.observation.cpu_percent = 50;
56新增: await cpu.getByText("50% / 2 个核心", { exact: true }).waitFor({ timeout: 6000 });
57新增: assert.ok(reads > before);
58新增: assert.ok(await error.isVisible());
59新增: failSave = false;
60新增: await panel.getByRole("button", { name: "重启并应用已保存配置", exact: true }).click();
61新增: await page.getByRole("dialog", { name: "重启并应用已保存的资源配置?", exact: true }).getByRole("button", { name: "保存后重启", exact: true }).click();
62新增: await error.waitFor({ state: "hidden" });
63新增: assert.deepEqual(requests.at(-1), {});
64新增: await panel.getByRole("heading", { name: "计算资源", exact: true }).scrollIntoViewIfNeeded();
65新增: await page.screenshot({ path: join(output, "macos-resources.png"), animations: "disabled" });
66新增: await panel.getByText(/内存估算使用客机物理容量/).scrollIntoViewIfNeeded();
67新增: await page.screenshot({ path: join(output, "macos-resource-observation.png"), animations: "disabled" });
68新增: assert.deepEqual(errors, []);
69新增: const result = { passed: true, browser: browser.browserType().name(), requests, reads,
70新增: checks: ["Mac fixed-capacity policy and minimum source visible", "first CPU sample unknown", "minimum enforced before save", "saved allocation waits for restart", "polling preserves save failure", "restart uses existing confirmation and shared endpoint"] };
71新增: await writeFile(join(output, "result.json"), JSON.stringify(result, null, 2));
72新增: console.log(JSON.stringify(result));
73新增:} finally { await browser.close(); }
新增ui/scripts/mobile-browser-latency-smoke.mjs+140 −0看文件
@@ -0,0 +1,140 @@
1新增:// Build with node mobile/build-ui.mjs. Optional CAGE_MOBILE_BASELINE points
2新增:// at the previous mobile-ui directory. Both builds use the same real remote
3新增:// Chromium and page. Only the paired-host HTTP adapter and WAN delay are local.
4新增:import assert from "node:assert/strict";
5新增:import {once} from "node:events";
6新增:import {mkdtemp, readFile, rm} from "node:fs/promises";
7新增:import http from "node:http";
8新增:import net from "node:net";
9新增:import {tmpdir} from "node:os";
10新增:import {join} from "node:path";
11新增:import {setTimeout as delay} from "node:timers/promises";
12新增:import {fileURLToPath} from "node:url";
13新增:import {PhoneBrowser} from "../../internal/cage/browser-phone.mjs";
14新增:
15新增:const playwright = await import(process.env.CAGE_PLAYWRIGHT_MODULE || "playwright");
16新增:const binary = process.env.CAGE_TEST_CHROMIUM || playwright.chromium.executablePath();
17新增:const engine = process.env.CAGE_TEST_MOBILE_BROWSER || "webkit";
18新增:const current = fileURLToPath(new URL("../../mobile/.build/resources/mobile-ui/",import.meta.url));
19新增:const site = http.createServer((req,res) => {
20新增: res.setHeader("Content-Type","text/html; charset=utf-8");
21新增: res.end('<meta name="viewport" content="width=device-width, initial-scale=1"><title>Scroll test</title>' +
22新增: '<style>*{box-sizing:border-box}body{margin:0;font:18px sans-serif;scrollbar-width:none}::-webkit-scrollbar{display:none}button{display:block;width:100%;height:80px;touch-action:manipulation}p{padding:24px;margin:0;border-bottom:1px solid silver}</style>' +
23新增: '<button onclick="document.body.style.backgroundColor=\'wheat\'">Change page colour</button>' +
24新增: Array.from({length:100},(_,i)=>"<p>Row "+(i+1)+"</p>").join(""));
25新增:}).listen(0,"127.0.0.1");
26新增:await once(site,"listening");
27新增:
28新增:async function measure(directory, baseline) {
29新增: const profile = await mkdtemp(join(tmpdir(),"cage-phone-latency-"));
30新增: const guest = new PhoneBrowser({directory:profile,binary,connect:async (host,port) => {
31新增: if (host !== "scroll.example" || port !== site.address().port) throw Error("Unexpected test destination");
32新增: const socket = net.connect({host:"127.0.0.1",port}); await once(socket,"connect"); return socket;
33新增: }});
34新增: const events = [];
35新增: let pageReady = false;
36新增: const host = http.createServer(async (req,res) => {
37新增: const url = new URL(req.url,"http://localhost");
38新增: const send = value => {res.setHeader("Content-Type","application/json"); res.end(JSON.stringify(value));};
39新增: try {
40新增: if (url.pathname === "/api/mobile/cli/projects") return send({ready:true,host:"Test",projects:[]});
41新增: if (url.pathname === "/api/mobile/cli/sessions") return send({sessions:[]});
42新增: if (!url.pathname.startsWith("/api/mobile/browser/")) {
43新增: const asset = url.pathname.slice(1) || "mobile.html";
44新增: if (asset !== "mobile.html" && !/^assets\/[\w.-]+$/.test(asset)) throw Error("Missing asset");
45新增: res.setHeader("Content-Type",asset.endsWith(".js") ? "text/javascript" : asset.endsWith(".css") ? "text/css" : asset.endsWith(".png") ? "image/png" : "text/html");
46新增: res.end(await readFile(join(directory,asset))); return;
47新增: }
48新增: const parts = url.pathname.split("/"), op = parts.at(-1);
49新增: const chunks = []; for await (const b of req) chunks.push(b);
50新增: const input = chunks.length ? JSON.parse(Buffer.concat(chunks)) : {};
51新增: if (op === "open") input.profile = "a".repeat(64);
52新增: else input.id = parts.at(-2);
53新增: if (url.searchParams.has("after")) input.after = url.searchParams.get("after");
54新增: const log = {op,type:input.type,at:Date.now(),after:!!input.after,delta:input.dy||0};
55新增: events.push(log);
56新增: await delay(80);
57新增: const output = await guest.run(op,input);
58新增: if (op === "open" || output.image) output.action_frame = true;
59新增: if (output.title === "Scroll test") pageReady = true;
60新增: log.bytes = Buffer.byteLength(JSON.stringify(output));
61新增: log.image = !!output.image;
62新增: await delay(80);
63新增: send(output);
64新增: } catch (error) { if (!res.headersSent) res.writeHead(error.status || 500); res.end(error.message); }
65新增: }).listen(0,"127.0.0.1");
66新增: await once(host,"listening");
67新增: const browser = await playwright[engine].launch();
68新增: try {
69新增: const page = await browser.newPage({viewport:{width:390,height:844},deviceScaleFactor:1,isMobile:true,hasTouch:true,userAgent:"CageMobile/1"});
70新增: await page.goto("http://127.0.0.1:"+host.address().port);
71新增: await page.getByRole("button",{name:"浏览器",exact:true}).click();
72新增: const address = page.getByRole("textbox",{name:"远程网页地址"});
73新增: await address.fill("http://scroll.example:"+site.address().port);
74新增: await address.press("Enter");
75新增: for(let i=0; i<80 && !pageReady; i++) await delay(100);
76新增: assert.ok(pageReady,"remote Chromium did not load the local page");
77新增: await delay(550);
78新增: const stage = page.getByRole("img",{name:"远程浏览器画面"});
79新增: const rect = await stage.boundingBox();
80新增: const start = async type => {
81新增: await page.evaluate(type => {
82新增: const stage = document.querySelector(".remote-stage");
83新增: const img = stage.querySelector("img"), original = img.src;
84新增: window.result = null;
85新增: stage.addEventListener(type, () => {
86新增: const start = performance.now();
87新增: const observer = new MutationObserver(() => {
88新增: if (img.src === original) return;
89新增: requestAnimationFrame(() => requestAnimationFrame(() => {window.result = {ms:Math.round(performance.now()-start),wall:Date.now()};}));
90新增: observer.disconnect();
91新增: });
92新增: observer.observe(img,{attributes:true,attributeFilter:["src"]});
93新增: },{once:true});
94新增: },type);
95新增: };
96新增: const finish = async (logStart,timeout=5000) => {
97新增: await page.waitForFunction(() => window.result !== null,null,{timeout});
98新增: const result = await page.evaluate(() => window.result);
99新增: const log = events.slice(logStart).filter(event => event.at <= result.wall);
100新增: const first = log.findIndex(e => e.op === "action");
101新增: assert.notEqual(first,-1);
102新增: return {ms:result.ms, requests:log.slice(first).length};
103新增: };
104新增: const tapStart = events.length;
105新增: await start("pointerup");
106新增: await page.touchscreen.tap(rect.x+rect.width/2,rect.y+40);
107新增: const tap = await finish(tapStart);
108新增: const x = rect.x + rect.width/2, y = rect.y + rect.height*.75;
109新增: await page.mouse.move(x,y); await page.mouse.down();
110新增: await start("pointermove");
111新增: const dragStart = events.length;
112新增: for (let i=1; i<=12; i++) {await page.mouse.move(x,y-i*12); await delay(32);}
113新增: const beforeRelease = await page.evaluate(() => window.result !== null);
114新增: await page.mouse.up();
115新增: const scroll = await finish(dragStart);
116新增: assert.equal(beforeRelease,!baseline,"scroll feedback while the finger is down");
117新增: // Allow compositor scrolling and its temporary scrollbar to settle.
118新增: await delay(2000);
119新增: const sent = events.slice(dragStart).filter(e => e.type === "scroll");
120新增: assert.equal(sent.reduce((sum,e)=>sum+e.delta,0),144,"only unsent motion may be coalesced");
121新增: if (!baseline) assert.ok(sent.length > 1 && sent.length < 12);
122新增: const idleStart = events.length;
123新增: await delay(5200);
124新增: const idle = events.slice(idleStart).filter(e=>e.op === "frame" && e.bytes);
125新增: if (!baseline) assert.ok(idle.length && idle.every(e=>e.after && !e.image),"the idle page must not keep downloading JPEGs");
126新增: return {tap,scroll:{...scroll,paintedWhileDragging:beforeRelease,writes:sent.length},idle:{reads:idle.length,bodyBytes:idle.reduce((sum,e)=>sum+e.bytes,0)}};
127新增: } finally {
128新增: await browser.close(); await guest.dispose(); host.closeAllConnections(); await new Promise(resolve => host.close(resolve));
129新增: await rm(profile,{recursive:true,force:true});
130新增: }
131新增:}
132新增:try {
133新增: const before = process.env.CAGE_MOBILE_BASELINE ? await measure(process.env.CAGE_MOBILE_BASELINE,true) : null;
134新增: const after = await measure(current,false);
135新增: if (before) {
136新增: assert.ok(after.tap.ms < before.tap.ms,"combined action feedback must remove one round trip");
137新增: assert.ok(after.scroll.ms < before.scroll.ms,"continuous drag must paint sooner");
138新增: }
139新增: console.log(JSON.stringify({engine,roundTripMs:160,before,after},null,2));
140新增:} finally {site.closeAllConnections(); site.close();}
新增ui/scripts/mobile-browser-smoke.mjs+587 −0看文件
@@ -0,0 +1,587 @@
1新增:// Exercises UI recovery and touch mapping with a synthetic, paired-host API.
2新增:// Run after node mobile/build-ui.mjs with CAGE_PLAYWRIGHT_MODULE as needed.
3新增:import assert from "node:assert/strict";
4新增:import http from "node:http";
5新增:import {mkdir, readFile} from "node:fs/promises";
6新增:import {join} from "node:path";
7新增:import {fileURLToPath} from "node:url";
8新增:const playwright = await import(process.env.CAGE_PLAYWRIGHT_MODULE || "playwright");
9新增:const engine = process.env.CAGE_TEST_MOBILE_BROWSER || "chromium";
10新增:const resources = new URL("../../mobile/.build/resources/mobile-ui/", import.meta.url);
11新增:const httpd = http.createServer(async (req, res) => {
12新增: const path = new URL(req.url, "http://localhost").pathname;
13新增: try {
14新增: if (path !== "/" && path !== "/mobile.html" && !/^\/assets\/[\w.-]+$/.test(path)) throw Error();
15新增: const file = new URL(path.slice(1) || "mobile.html", resources);
16新增: const mime = {js:"text/javascript", html:"text/html", png:"image/png", css:"text/css"}[file.pathname.split(".").pop()];
17新增: res.setHeader("Content-Type", mime);
18新增: res.end(await readFile(fileURLToPath(file)));
19新增: } catch {res.writeHead(404).end();}
20新增:});
21新增:await new Promise(resolve => httpd.listen(0, "127.0.0.1", resolve));
22新增:let browser;
23新增:try {
24新增: browser = await playwright[engine].launch();
25新增: const context = await browser.newContext({viewport:{width:390, height:844}, hasTouch:true, isMobile:true, deviceScaleFactor:1, userAgent:"CageMobile/1"});
26新增: await context.addInitScript(() => {
27新增: window.__cageDevices = {current:"a", devices:[{id:"a",name:"Cage 工作电脑"},{id:"b",name:"另一台电脑"}]};
28新增: window.deviceCommands = [];
29新增: window.CageDevices = {postMessage(raw) {
30新增: const message = JSON.parse(raw); window.deviceCommands.push(message);
31新增: if (message.action === "select") {
32新增: window.__cageDevices = {...window.__cageDevices,current:message.id};
33新增: window.dispatchEvent(new CustomEvent("cage-devices",{detail:window.__cageDevices}));
34新增: }
35新增: }};
36新增: });
37新增: const page = await context.newPage();
38新增: page.setDefaultTimeout(8000);
39新增: const image = await page.evaluate(() => {
40新增: const canvas = document.createElement("canvas");
41新增: canvas.width = 12; canvas.height = 16;
42新增: const c = canvas.getContext("2d"); c.fillStyle = "#555"; c.fillRect(0,0,12,16);
43新增: return canvas.toDataURL("image/jpeg").split(",")[1];
44新增: });
45新增: const homeNotice = "电脑的新标签页无法在手机浏览器打开,请输入其他网址。";
46新增: let enabled = false, frame, opens = 0, closes = 0, reads = 0;
47新增: let dropNextText = false, resizeHold, reloadHold;
48新增: let modern = false, readGate, writeGate, failedScroll, disconnectNavigation, idOnly;
49新增: let tag = 0;
50新增: const frameTag = () => tag.toString(16).padStart(32,"0");
51新增: const responseFrame = () => ({...frame, frame_tag:frameTag(), ...(modern && {action_frame:true})});
52新增: const gate = () => {
53新增: let enter, release;
54新增: const entered = new Promise(resolve => {enter = resolve;});
55新增: const hold = new Promise(resolve => {release = resolve;});
56新增: return {entered,release,wait:() => {enter(); return hold;}};
57新增: };
58新增: let desktopEnabled = false, desktopStartupReads = 0;
59新增: let favoritesAvailable = false, favoritesGate;
60新增: const favoriteWrites = [];
61新增: const favorites = {folders:[{id:"ref",title:"参考资料"}],items:[
62新增: {id:"one",title:"设计指引",url:"https://design.example/",folder_id:"ref"},
63新增: {id:"another",title:"日历",url:"https://calendar.example/",folder_id:""},
64新增: ]};
65新增: const sessionList = [{id:"70d7194d-33c0-428d-867e-f9e4cb9f902e",workspace:"/work/cage",
66新增: title:"移动端导航",generation:"qa",revision:1,turns:[],updated_at:new Date().toISOString()}];
67新增: const graphicCalls = [];
68新增: const holdResize = () => {
69新增: let release;
70新增: resizeHold = new Promise(resolve => {release = resolve;});
71新增: return release;
72新增: };
73新增: const actions = [];
74新增: const pairedHost = async route => {
75新增: const req = route.request();
76新增: const path = new URL(req.url()).pathname, body = req.postDataJSON();
77新增: const reply = (value) => route.fulfill({json: value});
78新增: if (path === "/api/mobile/cli/projects") return reply({host:"Cage 工作电脑", ready:true,
79新增: projects:[{path:"/work/cage",name:"Cage"},{path:"/work/web",name:"个人网站"}]});
80新增: if (path === "/api/mobile/cli/sessions" && body) {
81新增: const session = {id:body.id, workspace:body.workspace, title:"测试会话", generation:"qa", revision:1, turns:[], updated_at:new Date().toISOString()};
82新增: sessionList.push(session);
83新增: return reply(session);
84新增: }
85新增: if (path === "/api/mobile/cli/sessions") return reply({sessions:sessionList});
86新增: if (path.startsWith("/api/mobile/cli/sessions/")) return reply(sessionList.find(s => path.endsWith(s.id)));
87新增: if (path.startsWith("/api/mobile/desktop/")) {
88新增: if (!desktopEnabled) return route.fulfill({status:403,contentType:"text/plain",body:"请在电脑上允许 Claude Desktop。"});
89新增: const op = path.split("/").at(-1);
90新增: if (op !== "frame") graphicCalls.push({tool:"desktop",op,body});
91新增: if (op === "open") {frame = {...body, document:"desktop-doc", focus:"", window:"desktop", image}; return reply({id:frame.id});}
92新增: assert.ok(path.includes("/" + frame.id + "/"));
93新增: if (op === "frame" && !desktopStartupReads++) return route.fulfill({status:425});
94新增: if (op === "frame") return reply(frame);
95新增: if (op === "action") {
96新增: assert.equal(body.document, frame.document);
97新增: if (body.type === "resize") Object.assign(frame,{width:body.width,height:body.height,
98新增: ...(body.pixel_ratio && {requested_pixel_ratio:body.pixel_ratio,pixel_ratio:body.pixel_ratio})});
99新增: if (body.type === "tap") frame.focus = "compose";
100新增: if (body.type === "login") Object.assign(frame,{window:"login",document:"login-doc",focus:"credential",password:true});
101新增: if (body.type === "key" || body.type === "text") assert.equal(frame.focus,body.focus);
102新增: if (body.type === "key") await new Promise(resolve => setTimeout(resolve,65));
103新增: }
104新增: return reply({id:frame.id});
105新增: }
106新增: if (!path.startsWith("/api/mobile/browser/")) return route.fulfill({status:404});
107新增: if (path === "/api/mobile/browser/favorites") {
108新增: if (!favoritesAvailable) return route.fulfill({status:404});
109新增: if (body) {
110新增: favoriteWrites.push(body);
111新增: if (body.action === "save") favorites.items.push({id:"new",...body});
112新增: else if (body.action === "delete") favorites.items = favorites.items.filter(item => item.id !== body.id);
113新增: else throw Error("unexpected favorite mutation");
114新增: }
115新增: const result = structuredClone(favorites);
116新增: const pending = favoritesGate; favoritesGate = null;
117新增: if (pending) await pending.wait();
118新增: return reply(result);
119新增: }
120新增: if (!enabled) return route.fulfill({status:403, contentType:"text/plain", body:"请先在电脑上允许远程浏览器。"});
121新增: if (path.endsWith("/open")) {
122新增: opens++;
123新增: graphicCalls.push({tool:"browser",op:"open",body});
124新增: frame = {...body, document:"doc-1", focus:"", password:false, url:"", image};
125新增: tag++;
126新增: return reply({id:body.id, ...(modern && {action_frame:true,home_notice:homeNotice})});
127新增: }
128新增: assert.ok(path.includes("/" + frame.id + "/"));
129新增: if (path.endsWith("/close")) {closes++; return reply({id:frame.id});}
130新增: if (path.endsWith("/frame")) {
131新增: reads++;
132新增: const after = new URL(req.url()).searchParams.get("after");
133新增: if (!modern) assert.equal(after,null,"a tag from an older host must not enable conditional requests");
134新增: const snapshot = responseFrame();
135新增: const pending = readGate; readGate = null;
136新增: if (pending) {
137新增: await pending.wait();
138新增: return reply({...snapshot,url:"https://stale.example/",document:"obsolete-doc"});
139新增: }
140新增: return reply(after === frameTag() ? {id:frame.id,unchanged:true,frame_tag:after} : snapshot);
141新增: }
142新增: assert.ok(path.endsWith("/action"));
143新增: actions.push(body);
144新增: assert.equal(body.return_frame,modern || undefined,"only a capable host accepts the new action field");
145新增: assert.equal(body.document, frame.document);
146新增: if (body.type === "resize") {
147新增: const hold = resizeHold;
148新增: resizeHold = null;
149新增: if (hold) await hold;
150新增: Object.assign(frame, {width:body.width, height:body.height, document:"viewport-" + actions.length});
151新增: }
152新增: if (body.type === "reload" && reloadHold) await reloadHold;
153新增: if (body.type === "navigate") Object.assign(frame, {url:body.url,document:"doc-2"});
154新增: if (body.type === "tap") frame.focus = "email-field";
155新增: if (body.type === "text" || body.type === "key") assert.equal(body.focus,frame.focus);
156新增: if (body.type === "text" && dropNextText) {
157新增: dropNextText = false;
158新增: return route.abort("internetdisconnected");
159新增: }
160新增: tag++;
161新增: if (modern) {
162新增: const snapshot = responseFrame();
163新增: const pending = writeGate; writeGate = null;
164新增: if (pending) await pending.wait();
165新增: if (failedScroll && body.type === "scroll") {failedScroll = false; return route.abort("internetdisconnected");}
166新增: if (disconnectNavigation && body.type === "navigate") {
167新增: disconnectNavigation = false;
168新增: frame.url = "https://recovered.example/";
169新增: return reply({...snapshot,url:"https://obsolete-write.example/"});
170新增: }
171新增: if (idOnly) {idOnly = false; return reply({id:frame.id});}
172新增: return reply(snapshot);
173新增: }
174新增: return reply({id:frame.id});
175新增: };
176新增: const origin = "http://127.0.0.1:" + httpd.address().port;
177新增: await page.route("**/api/mobile/**",pairedHost);
178新增: await page.goto(origin);
179新增: const drawer = page.getByRole("dialog",{name:"工作区侧栏"});
180新增: await drawer.waitFor();
181新增: for (const name of ["浏览器","Claude.ai","Claude Desktop"]) assert.equal(await drawer.getByRole("button",{name,exact:true}).count(),1);
182新增: await drawer.getByRole("heading",{name:"Claude Code",exact:true}).waitFor();
183新增: assert.equal(await drawer.getByRole("button",{name:"Claude Code",exact:true}).count(),0);
184新增: assert.equal(await drawer.getByRole("combobox").count(),0);
185新增: const menu = page.getByRole("button",{name:"展开侧栏",exact:true});
186新增: const firstFolder = drawer.getByRole("button",{name:"项目 Cage",exact:true});
187新增: const secondFolder = drawer.getByRole("button",{name:"项目 个人网站",exact:true});
188新增: const exit = drawer.getByRole("link",{name:"退出",exact:true});
189新增: await drawer.getByRole("button",{name:"移动端导航",exact:true}).waitFor();
190新增: if (process.env.CAGE_TEST_MOBILE_CAPTURE) {
191新增: await mkdir(process.env.CAGE_TEST_MOBILE_CAPTURE,{recursive:true});
192新增: await page.screenshot({path:join(process.env.CAGE_TEST_MOBILE_CAPTURE,engine+"-workspace-drawer.png")});
193新增: }
194新增: await page.setViewportSize({width:390,height:300});
195新增: const scroll = drawer.locator(".drawer-content");
196新增: await page.waitForFunction(() => {const el = document.querySelector(".drawer-content"); return el.scrollHeight > el.clientHeight;});
197新增: const footerTop = (await exit.boundingBox()).y;
198新增: await scroll.evaluate(el => {el.scrollTop = el.scrollHeight;});
199新增: assert.ok(await scroll.evaluate(el => el.scrollTop > 0));
200新增: assert.equal((await exit.boundingBox()).y,footerTop);
201新增: assert.ok(footerTop > 200 && footerTop < 300);
202新增: await page.setViewportSize({width:390,height:844});
203新增: assert.equal(await drawer.getByRole("button",{name:"收起侧栏"}).count(),0);
204新增: await page.touchscreen.tap(380, 400);
205新增: await drawer.waitFor({state:"hidden"});
206新增: assert.equal(await page.locator(".topbar button").count(),1);
207新增: assert.ok(await menu.getByRole("img",{name:"Cage"}).count());
208新增: await page.getByRole("img",{name:"Claude Code",exact:true}).waitFor();
209新增: await menu.click();
210新增: await page.waitForFunction(() => document.querySelector(".workspace-drawer")?.getAnimations().some(animation => animation.transitionProperty === "transform"));
211新增: await page.keyboard.press("Escape");
212新增: await drawer.waitFor({state:"hidden"});
213新增: await menu.click();
214新增: await drawer.getByRole("button", {name:"浏览器",exact:true}).click();
215新增: await drawer.waitFor({state:"hidden"});
216新增: await page.getByRole("img",{name:"浏览器",exact:true}).waitFor();
217新增: await page.getByText("请先在电脑上允许远程浏览器。").waitFor();
218新增: enabled = true;
219新增: await page.getByRole("button",{name:"重新打开",exact:true}).click();
220新增: const imageView = page.getByRole("img",{name:"远程浏览器画面"});
221新增: const ready = async () => {
222新增: await imageView.waitFor();
223新增: await page.waitForFunction(() => !document.querySelector('button[aria-label="重新加载网页"]')?.disabled);
224新增: };
225新增: await ready();
226新增: assert.equal(await page.locator(".topbar input").count(),1);
227新增: assert.equal(Math.round((await imageView.boundingBox()).y), Math.round((await page.locator(".topbar").boundingBox()).height));
228新增: // Browser reload must resume by GET, even when the remote browser is idle.
229新增: await page.reload();
230新增: await ready();
231新增: assert.equal(opens,1);
232新增: const address = page.getByRole("textbox",{name:"远程网页地址"});
233新增: // The soft keyboard can start resize before the user presses Go. Hold the
234新增: // resize response until the address is submitted and confirm a single write.
235新增: const duringResize = async (height, url) => {
236新增: const release = holdResize();
237新增: const resize = page.waitForRequest(req => req.url().endsWith("/action") && req.postDataJSON()?.type === "resize");
238新增: await address.focus();
239新增: await page.setViewportSize({width:390, height});
240新增: await resize;
241新增: await address.fill(url);
242新增: await address.press("Enter");
243新增: await page.waitForFunction(() => document.querySelector('[aria-label="前往网址"]').getAttribute("aria-busy") === "true");
244新增: assert.equal(actions.filter(action => action.type === "navigate" && action.url === url).length,0);
245新增: return release;
246新增: };
247新增: const target = "https://example.org/";
248新增: const navigation = page.waitForResponse(res => res.url().endsWith("/action") && res.request().postDataJSON()?.type === "navigate");
249新增: const release = await duringResize(682, target);
250新增: release();
251新增: await navigation;
252新增: await ready();
253新增: assert.equal(actions.filter(action => action.type === "navigate" && action.url === target).length,1);
254新增: // A different user action (reload) must never silently queue navigation.
255新增: let releaseReload;
256新增: reloadHold = new Promise(resolve => {releaseReload = resolve;});
257新增: await page.getByRole("button",{name:"重新加载网页"}).click();
258新增: await address.fill("https://busy.example.org/");
259新增: await address.press("Enter");
260新增: await page.getByText("上一项操作尚未完成,请稍后再次前往。").waitFor();
261新增: releaseReload();
262新增: await ready();
263新增: assert.equal(actions.filter(action => action.url === "https://busy.example.org/").length, 0);
264新增: const matchingFrame = page.waitForResponse(async response => {
265新增: if (!response.url().endsWith("/frame") || !response.ok()) return false;
266新增: const captured = await response.json(), rect = await imageView.boundingBox();
267新增: return rect && Math.round(rect.width) === captured.width && Math.round(rect.height) === captured.height;
268新增: });
269新增: await address.press("Escape");
270新增: await matchingFrame;
271新增: await ready();
272新增: const box = await imageView.boundingBox();
273新增: await page.touchscreen.tap(box.x + box.width * .25,box.y + box.height * .45);
274新增: const keyboard = page.getByRole("button",{name:"输入文字",exact:true});
275新增: await keyboard.click();
276新增: const tap = actions.find(a => a.type === "tap");
277新增: assert.ok(Math.abs(tap.x / Math.round(box.width) - .25) < .01 && Math.abs(tap.y / Math.round(box.height) - .45) < .01);
278新增: const field = page.getByLabel("待插入文字");
279新增: await field.fill("手机中文输入");
280新增: const initialField = await field.elementHandle();
281新增: // Shrinking for a soft keyboard and rotating both invalidate the frame's
282新增: // coordinates. Neither changes the identity of this remote editable field.
283新增: for (const size of [{width:390,height:575}, {width:844,height:390}, {width:390,height:844}]) {
284新增: const before = frame.document;
285新增: const fresh = page.waitForResponse(async response => {
286新增: if (!response.url().endsWith("/frame") || !response.ok()) return false;
287新增: const value = await response.json();
288新增: const stage = await imageView.boundingBox();
289新增: return stage && value.document !== before && value.focus === "email-field" &&
290新增: value.width === Math.round(stage.width) && value.height === Math.round(stage.height);
291新增: });
292新增: await page.setViewportSize(size);
293新增: await fresh;
294新增: await ready();
295新增: assert.equal(await field.evaluate((el, original) => el === original && document.activeElement === el, initialField), true);
296新增: assert.equal(await field.inputValue(), "手机中文输入");
297新增: assert.equal(frame.width,size.width);
298新增: assert.equal(await page.getByRole("navigation",{name:"远程网页操作"}).count(),0);
299新增: }
300新增: await initialField.dispose();
301新增: await page.getByRole("button",{name:"插入文字",exact:true}).click();
302新增: await page.getByRole("button",{name:"发送回车",exact:true}).click();
303新增: assert.deepEqual(actions.filter(a => a.type === "text").map(a => a.text),["手机中文输入"]);
304新增: assert.deepEqual(actions.filter(a => a.type === "key").map(a => a.key),["Enter"]);
305新增: // An ambiguous text write may already have reached the host. Refresh must
306新增: // only read status, and no password/text draft should survive the disconnect.
307新增: await field.fill("uncertain");
308新增: dropNextText = true;
309新增: await page.getByRole("button",{name:"插入文字",exact:true}).click();
310新增: await page.getByText("输入结果待确认", {exact:false}).waitFor();
311新增: assert.equal(await imageView.count(),0);
312新增: await page.getByRole("button",{name:"重新读取画面",exact:true}).click();
313新增: await ready();
314新增: assert.equal(actions.filter(a => a.text === "uncertain").length,1);
315新增: assert.equal(opens,1);
316新增: if (await field.count()) assert.equal(await field.inputValue(),"");
317新增: // A new focused element must not receive the draft for its predecessor.
318新增: if (!await field.count()) await keyboard.click();
319新增: await field.fill("draft for email only");
320新增: frame.focus = "password-field";
321新增: frame.password = true;
322新增: await field.waitFor({state:"detached"});
323新增: await keyboard.click();
324新增: assert.equal(await field.getAttribute("type"), "password");
325新增: assert.equal(await field.inputValue(), "");
326新增: await field.fill("synthetic password");
327新增: await page.evaluate(() => window.dispatchEvent(new Event("pagehide")));
328新增: await imageView.waitFor({state:"detached"});
329新增: assert.equal(await field.count(), 0);
330新增: const suspended = reads;
331新增: await page.waitForTimeout(900);
332新增: assert.equal(reads, suspended);
333新增: await page.evaluate(() => window.dispatchEvent(new Event("pageshow")));
334新增: await ready();
335新增: assert.equal(await field.count(), 0);
336新增: assert.equal(actions.filter(a => a.text === "synthetic password").length, 0);
337新增: await page.setViewportSize({width:844,height:390});
338新增: await page.waitForFunction(() => !document.querySelector('button[aria-label="重新加载网页"]').disabled);
339新增: for (let i=0; i<40 && !actions.some(a => a.type === "resize" && a.width > 600); i++) await page.waitForTimeout(100);
340新增: assert.ok(actions.some(a => a.type === "resize" && a.width > 600));
341新增: await ready();
342新增: const before = await imageView.boundingBox();
343新增: const xy = {x:before.x+before.width/2, y:before.y+before.height*.7};
344新增: await page.mouse.move(xy.x,xy.y);
345新增: await page.mouse.down();
346新增: await page.mouse.move(xy.x,xy.y-45);
347新增: await page.mouse.up();
348新增: for (let i=0; i<30 && !actions.some(a => a.type === "scroll"); i++) await page.waitForTimeout(100);
349新增: assert.ok(actions.some(a => a.type === "scroll" && a.dy > 0));
350新增: const abandoned = "https://abandoned.example.org/";
351新增: const afterClose = await duringResize(777, abandoned);
352新增: await page.getByRole("button",{name:"关闭远程浏览器",exact:true}).click();
353新增: await page.getByRole("button",{name:"浏览器",exact:true}).waitFor();
354新增: afterClose();
355新增: const count = reads;
356新增: await page.waitForTimeout(900);
357新增: assert.equal(reads,count);
358新增: assert.equal(closes,1);
359新增: assert.equal(actions.filter(action => action.type === "navigate" && action.url === abandoned).length,0);
360新增: await drawer.waitFor();
361新增: assert.equal(await firstFolder.getAttribute("aria-expanded"),"true");
362新增: assert.equal(await secondFolder.getAttribute("aria-expanded"),"false");
363新增: await secondFolder.click();
364新增: assert.equal(await firstFolder.getAttribute("aria-expanded"),"true");
365新增: assert.equal(await secondFolder.getAttribute("aria-expanded"),"true");
366新增: await firstFolder.focus(); await firstFolder.press("Enter");
367新增: assert.equal(await firstFolder.evaluate(el => el === document.activeElement),true);
368新增: assert.equal(await drawer.getByRole("button",{name:"移动端导航",exact:true}).count(),0);
369新增: assert.equal(await secondFolder.getAttribute("aria-expanded"),"true");
370新增: await drawer.getByRole("button",{name:"在 个人网站 新建会话",exact:true}).click();
371新增: await drawer.waitFor({state:"hidden"});
372新增: const composer = page.getByRole("textbox",{name:"消息"});
373新增: await composer.fill("尚未发送的草稿");
374新增: assert.equal(sessionList.at(-1).workspace,"/work/web");
375新增: await menu.click(); await drawer.getByRole("button",{name:"Claude.ai",exact:true}).click();
376新增: await ready();
377新增: await page.getByRole("img",{name:"Claude.ai",exact:true}).waitFor();
378新增: assert.equal(await address.count(),0);
379新增: const claudeBox = await imageView.boundingBox();
380新增: assert.equal(claudeBox.width,390);
381新增: assert.ok(claudeBox.height > 667);
382新增: await page.getByRole("button",{name:"网页地址",exact:true}).click();
383新增: assert.equal(await address.count(),1);
384新增: assert.equal((await imageView.boundingBox()).height,claudeBox.height);
385新增: assert.equal(graphicCalls.filter(call => call.tool === "browser" && call.op === "open").at(-1).body.url, "https://claude.ai/");
386新增: await menu.click();
387新增: await firstFolder.click();
388新增: assert.equal(await firstFolder.getAttribute("aria-expanded"),"true");
389新增: assert.equal(await secondFolder.getAttribute("aria-expanded"),"true");
390新增: await page.getByRole("img",{name:"Claude.ai",exact:true}).waitFor();
391新增: await drawer.getByRole("button",{name:"测试会话",exact:true}).click();
392新增: await composer.waitFor();
393新增: assert.equal(await composer.inputValue(), "尚未发送的草稿");
394新增: await menu.click(); await drawer.getByRole("button",{name:"Claude Desktop",exact:true}).click();
395新增: await page.getByRole("img",{name:"Claude Desktop",exact:true}).waitFor();
396新增: await page.getByText("请在电脑上允许 Claude Desktop。").waitFor();
397新增: desktopEnabled = true;
398新增: await page.getByRole("button",{name:"重新打开",exact:true}).click();
399新增: await page.getByText("正在启动远程 Claude Desktop…").waitFor();
400新增: const desktop = page.getByRole("img",{name:"远程 Desktop 画面"});
401新增: await desktop.waitFor();
402新增: const logicalWidth = frame.width;
403新增: const fit = await desktop.boundingBox();
404新增: const desktopResizes = () => graphicCalls.filter(call => call.tool === "desktop" && call.body?.type === "resize").length;
405新增: const priorResizes = desktopResizes();
406新增: await page.getByRole("button",{name:"放大阅读",exact:true}).click();
407新增: assert.ok((await desktop.boundingBox()).width > fit.width * 1.5);
408新增: const stage = page.locator(".remote-stage");
409新增: const priorLeft = await stage.evaluate(el => el.scrollLeft);
410新增: await page.mouse.move(fit.x + fit.width/2, fit.y + fit.height/2); await page.mouse.down();
411新增: await page.mouse.move(fit.x + fit.width/2 - 50, fit.y + fit.height/2); await page.mouse.up();
412新增: assert.ok(await stage.evaluate(el => el.scrollLeft) > priorLeft);
413新增: await page.getByRole("button",{name:"全幅",exact:true}).click();
414新增: assert.equal(frame.width,logicalWidth); assert.equal(desktopResizes(),priorResizes);
415新增: await desktop.tap();
416新增: await page.getByRole("button",{name:"输入文字",exact:true}).click();
417新增: await field.fill("Desktop 中文");
418新增: await page.getByRole("button",{name:"插入文字",exact:true}).click();
419新增: await page.getByRole("button",{name:"收起输入框",exact:true}).click();
420新增: await page.getByRole("button",{name:"登录窗口",exact:true}).click();
421新增: await page.getByRole("button",{name:"返回 Desktop",exact:true}).waitFor();
422新增: await page.getByRole("button",{name:"输入文字",exact:true}).click();
423新增: const loginField = page.getByLabel("逐键登录输入");
424新增: await loginField.pressSequentially("Ab2");
425新增: assert.equal(await loginField.inputValue(),"");
426新增: for (let i=0; i<40 && graphicCalls.filter(call => call.body?.type === "key").length < 3; i++) await page.waitForTimeout(100);
427新增: assert.deepEqual(graphicCalls.filter(call => call.body?.type === "key").map(call=>call.body.key),["A","b","2"]);
428新增: assert.equal(graphicCalls.filter(call => call.body?.type === "text").length,1);
429新增: await page.getByRole("button",{name:"收起输入框",exact:true}).click();
430新增: Object.assign(frame, {shared:true});
431新增: await page.getByRole("button",{name:"返回 Desktop",exact:true}).waitFor({state:"hidden"});
432新增: assert.equal(await page.getByRole("button",{name:"登录窗口",exact:true}).count(),0);
433新增: await page.getByRole("button",{name:"断开远程桌面",exact:true}).waitFor();
434新增: assert.equal(graphicCalls.filter(call => call.body?.pixel_ratio).length,0);
435新增: Object.assign(frame,{pixel_ratio_supported:true,requested_pixel_ratio:2,pixel_ratio:2});
436新增: for (const ratio of [3.5,2.625]) {
437新增: await page.evaluate(value => Object.defineProperty(window,"devicePixelRatio",{configurable:true,value}),ratio);
438新增: for (let i=0; i<60 && frame.requested_pixel_ratio!==ratio; i++) await page.waitForTimeout(100);
439新增: assert.equal(frame.requested_pixel_ratio,ratio);
440新增: assert.equal(graphicCalls.filter(call=>call.body?.pixel_ratio===ratio).length,1);
441新增: }
442新增: await menu.click(); await exit.click();
443新增: await page.waitForFunction(() => window.deviceCommands.some(m => m.action === "home"));
444新增: await desktop.waitFor({state:"detached"});
445新增: for (let i=0; i<20 && !graphicCalls.some(c => c.tool === "desktop" && c.op === "close"); i++) await page.waitForTimeout(100);
446新增: assert.equal(graphicCalls.filter(c => c.tool === "desktop" && c.op === "close").length,1);
447新增: assert.ok(await page.evaluate(() => window.deviceCommands.every(m => m.action !== "disconnect" && m.action !== "select")));
448新增: modern = true;
449新增: await drawer.getByRole("button",{name:"浏览器",exact:true}).click();
450新增: await drawer.waitFor({state:"hidden"});
451新增: await ready();
452新增: await page.getByText(homeNotice).waitFor();
453新增: assert.equal(await address.isEnabled(),true);
454新增: assert.equal(await page.getByRole("button",{name:"收藏夹",exact:true}).isEnabled(),true);
455新增: // A previous conditional read may finish well after an accepted action.
456新增: // Its old URL/document must never replace the action's newer frame.
457新增: const oldRead = readGate = gate();
458新增: await oldRead.entered;
459新增: const latestAction = page.waitForResponse(res => res.url().endsWith("/action") && res.request().postDataJSON()?.url === "https://latest.example/");
460新增: await address.fill("https://latest.example/"); await address.press("Enter");
461新增: await latestAction;
462新增: await page.waitForFunction(() => document.activeElement !== document.querySelector('[aria-label="远程网页地址"]'));
463新增: oldRead.release();
464新增: await page.waitForTimeout(160);
465新增: assert.equal(await address.inputValue(),"https://latest.example/");
466新增: assert.equal(await page.getByText(homeNotice).count(),0);
467新增: const pausedWrite = writeGate = gate();
468新增: disconnectNavigation = true;
469新增: await address.fill("https://background.example/"); await address.press("Enter");
470新增: await pausedWrite.entered;
471新增: await page.evaluate(() => window.dispatchEvent(new Event("pagehide")));
472新增: await imageView.waitFor({state:"detached"});
473新增: await page.evaluate(() => window.dispatchEvent(new Event("pageshow")));
474新增: pausedWrite.release();
475新增: await ready();
476新增: assert.equal(await address.inputValue(),"https://recovered.example/");
477新增: const motion = await imageView.boundingBox();
478新增: const firstWrite = writeGate = gate();
479新增: failedScroll = true;
480新增: const startActions = actions.length;
481新增: const x = motion.x + motion.width/2, y = motion.y + motion.height*.7;
482新增: await page.mouse.move(x,y); await page.mouse.down(); await page.mouse.move(x,y-24);
483新增: await firstWrite.entered;
484新增: await page.mouse.move(x,y-56); await page.mouse.move(x,y-84); await page.mouse.up();
485新增: firstWrite.release();
486新增: await page.getByText("输入结果待确认",{exact:false}).waitFor();
487新增: assert.deepEqual(actions.slice(startActions).map(a=>a.dy),[24]);
488新增: await page.getByRole("button",{name:"重新读取画面"}).click(); await ready();
489新增: await page.waitForTimeout(330);
490新增: assert.deepEqual(actions.slice(startActions).map(a=>a.dy),[24],"unsent movement must be discarded after uncertain input");
491新增: // A fresh touch cancels the tail of the prior drag. Do not send that tail
492新增: // to a different scrollable panel under the next finger.
493新增: const interrupted = writeGate = gate();
494新增: const firstDrag = actions.length;
495新增: await page.mouse.move(x,y); await page.mouse.down(); await page.mouse.move(x,y-20);
496新增: await interrupted.entered;
497新增: await page.mouse.move(x,y-55); await page.mouse.up();
498新增: await page.mouse.move(x+64,y); await page.mouse.down(); await page.mouse.move(x+64,y-18); await page.mouse.up();
499新增: interrupted.release();
500新增: for (let i=0; i<25 && actions.length < firstDrag+2; i++) await page.waitForTimeout(50);
501新增: assert.deepEqual(actions.slice(firstDrag).map(a=>[a.x,a.dy]),[[Math.floor(x-motion.x),20],[Math.floor(x+64-motion.x),18]]);
502新增: // An upgraded host may bridge an older guest which only acknowledges the
503新增: // write. Fetch the result once with no tag and never resend that action.
504新增: idOnly = true;
505新增: const once = actions.length;
506新增: const fallback = page.waitForResponse(res => res.url().endsWith("/frame") && res.ok());
507新增: const longAddress = "https://ack-only.example/" + "a".repeat(5000);
508新增: await address.fill(longAddress); await address.press("Enter");
509新增: await fallback;
510新增: await ready();
511新增: assert.deepEqual(actions.slice(once).map(a=>a.type),["navigate"]);
512新增: assert.equal(await address.inputValue(),longAddress);
513新增: const bookmarks = page.getByRole("button",{name:"收藏夹",exact:true});
514新增: const panel = page.getByRole("region",{name:"电脑收藏夹",exact:true});
515新增: await bookmarks.click();
516新增: await panel.getByText("这台电脑尚不支持共享收藏夹,请更新电脑端 Cage。").waitFor();
517新增: favoritesAvailable = true;
518新增: await panel.getByRole("button",{name:"刷新收藏夹"}).click();
519新增: const folder = panel.getByRole("button",{name:"参考资料",exact:true});
520新增: const rootFavorite = panel.getByRole("button",{name:/^日历/});
521新增: const rootTop = (await rootFavorite.boundingBox()).y;
522新增: await folder.focus(); await folder.press("Enter");
523新增: assert.ok((await rootFavorite.boundingBox()).y >= rootTop + 40);
524新增: await folder.press("Space");
525新增: assert.equal((await rootFavorite.boundingBox()).y,rootTop);
526新增: await panel.getByRole("button",{name:"收藏此页"}).click();
527新增: const destination = panel.getByRole("combobox",{name:"保存到"});
528新增: const saveBookmark = panel.getByRole("button",{name:"保存收藏"});
529新增: const saveTop = (await saveBookmark.boundingBox()).y;
530新增: await destination.focus(); await destination.press("Enter");
531新增: assert.ok((await saveBookmark.boundingBox()).y >= saveTop + 72);
532新增: await destination.press("ArrowDown"); await destination.press("Enter");
533新增: assert.equal(await destination.evaluate(el => document.activeElement === el),true);
534新增: assert.equal((await saveBookmark.boundingBox()).y,saveTop);
535新增: await saveBookmark.click();
536新增: await panel.getByRole("button",{name:"取消此页收藏",exact:true}).waitFor();
537新增: assert.deepEqual(favoriteWrites[0],{action:"save",title:"ack-only.example",url:longAddress,folder_id:"ref"});
538新增: assert.equal(await folder.getAttribute("aria-expanded"),"true");
539新增: favorites.items.push({id:"from-computer",title:"电脑新加入",url:"https://added.example/",folder_id:"ref"});
540新增: await panel.getByRole("button",{name:"刷新收藏夹"}).click();
541新增: const added = panel.getByRole("button",{name:/^电脑新加入/});
542新增: await added.waitFor();
543新增: if (process.env.CAGE_TEST_MOBILE_CAPTURE) await page.screenshot({path:join(process.env.CAGE_TEST_MOBILE_CAPTURE,engine+"-phone-favorites.png")});
544新增: const opensBefore = actions.filter(a=>a.type === "navigate").length;
545新增: await added.click();
546新增: await panel.waitFor({state:"detached"});
547新增: assert.equal(frame.url,"https://added.example/");
548新增: assert.equal(actions.filter(a=>a.type === "navigate").length,opensBefore+1);
549新增: assert.equal(new URL(page.url()).origin,origin);
550新增: await bookmarks.click();
551新增: await panel.getByRole("button",{name:"取消此页收藏",exact:true}).click();
552新增: await panel.getByRole("button",{name:"收藏此页",exact:true}).waitFor();
553新增: assert.deepEqual(favoriteWrites.at(-1),{action:"delete",id:"from-computer"});
554新增: const oldFavorites = favoritesGate = gate();
555新增: await panel.getByRole("button",{name:"刷新收藏夹"}).click(); await oldFavorites.entered;
556新增: await page.evaluate(() => window.dispatchEvent(new Event("offline")));
557新增: await panel.waitFor({state:"detached"});
558新增: oldFavorites.release();
559新增: await page.getByRole("button",{name:"重新读取画面"}).click(); await ready();
560新增: assert.equal(await panel.count(),0);
561新增: favorites.items = [];
562新增: await bookmarks.click(); await folder.waitFor();
563新增: assert.equal(await rootFavorite.count(),0,"favorites from a previous connection must not reappear");
564新增: await panel.getByRole("button",{name:"返回网页"}).click();
565新增: await panel.waitFor({state:"detached"});
566新增: await page.getByRole("button",{name:"关闭远程浏览器"}).click();
567新增: const legacy = await browser.newPage({viewport:{width:850,height:720}});
568新增: await legacy.route("**/api/mobile/**",pairedHost);
569新增: await legacy.goto(origin + "/mobile.html");
570新增: const project = legacy.getByRole("combobox",{name:"选择项目"});
571新增: const newSession = legacy.getByRole("button",{name:"新建会话",exact:true});
572新增: await project.waitFor();
573新增: assert.equal(await legacy.getByRole("dialog").count(),0);
574新增: const headingY = (await newSession.boundingBox()).y;
575新增: await project.focus(); await project.press("Enter");
576新增: assert.ok((await newSession.boundingBox()).y > headingY + 50);
577新增: await project.press("ArrowDown"); await project.press("Enter");
578新增: assert.equal(await project.getAttribute("aria-expanded"),"false");
579新增: assert.equal(await project.evaluate(el => el === document.activeElement),true);
580新增: assert.ok(Math.abs((await newSession.boundingBox()).y - headingY) <= 1);
581新增: await legacy.getByRole("button",{name:"测试会话",exact:true}).click();
582新增: await legacy.getByRole("textbox",{name:"消息"}).waitFor();
583新增: console.log(engine + ": logo, project tree, drafts, fixed exit, shared favorites, viewport, Desktop pan and login keyboard passed");
584新增:} finally {
585新增: await browser?.close();
586新增: await new Promise(resolve => httpd.close(resolve));
587新增:}
新增ui/scripts/mobile-cli-live-smoke.mjs+78 −0看文件
@@ -0,0 +1,78 @@
1新增:// Started by TestMobileCLIThroughRelayAndSSH. The private one-time launch URL
2新增:// is read from stdin; browser automation uses the real production endpoints.
3新增:import process from "node:process";
4新增:import { mkdir, readFile } from "node:fs/promises";
5新增:import path from "node:path";
6新增:import assert from "node:assert/strict";
7新增:const chunks = [];
8新增:for await (const chunk of process.stdin) chunks.push(chunk);
9新增:const entry = Buffer.concat(chunks).toString("utf8").trim();
10新增:const engine = process.env.CAGE_TEST_MOBILE_BROWSER;
11新增:if (!["chromium", "webkit"].includes(engine)) throw Error("Choose chromium or webkit");
12新增:const playwright = await import(process.env.CAGE_PLAYWRIGHT_MODULE || "playwright");
13新增:const browser = await playwright[engine].launch({headless:true});
14新增:try {
15新增: const page = await browser.newPage({viewport:{width:390,height:844},deviceScaleFactor:1,isMobile:true,hasTouch:true});
16新增: page.setDefaultTimeout(18000);
17新增: // Exercise compatibility with the original independent-session capability.
18新增: // The shared-terminal user flow has its own real CLI/browser integration test.
19新增: await page.route("**/api/mobile/cli/projects", async route => {
20新增: const response = await route.fetch();
21新增: const value = await response.json();
22新增: delete value.shared_sessions;
23新增: await route.fulfill({response, json:value});
24新增: });
25新增: await page.route("**/api/mobile/cli/sessions", async route => {
26新增: if (route.request().method() !== "POST") return route.continue();
27新增: // Existing headless history is seeded by Go; new production sessions use
28新增: // the shared path covered by shared-cli-live-smoke.mjs.
29新增: await route.fulfill({status:200,contentType:"application/json",body:process.env.CAGE_TEST_MOBILE_LEGACY_SESSION});
30新增: });
31新增: await page.goto(entry);
32新增: await page.getByRole("dialog", {name:"工作区侧栏"}).getByRole("button", {name:/ 新建会话$/}).first().click();
33新增: await page.getByRole("dialog", {name:"工作区侧栏"}).waitFor({state:"hidden"});
34新增: const message = page.getByRole("textbox", {name:"消息"});
35新增: await message.fill("initial mobile prompt");
36新增: await page.getByRole("button", {name:"发送",exact:true}).click();
37新增: const approve = page.getByRole("button",{name:"允许一次"});
38新增: await approve.waitFor();
39新增: assert.match(await page.getByLabel("完整工具参数").innerText(), /mobile-approved\.txt/);
40新增: await assert.rejects(readFile(process.env.CAGE_TEST_MOBILE_MARKER), {code:"ENOENT"});
41新增: const out = process.env.CAGE_TEST_MOBILE_CAPTURE;
42新增: if(out) {
43新增: await mkdir(out,{recursive:true});
44新增: await page.screenshot({path:path.join(out,engine+"-cli-approval.png")});
45新增: }
46新增: // The pending tool request belongs to the host, so a page reload must
47新增: // recover it and its original arguments.
48新增: await page.reload();
49新增: // Losing both the decision and its immediate status check must not leave
50新增: // the approval disabled after the next successful read.
51新增: let offline = false;
52新增: const sessionRequests = "**/api/mobile/cli/sessions/**";
53新增: await page.route(sessionRequests, async route => {
54新增: if (route.request().method() === "POST" && route.request().url().endsWith("/approval")) offline = true;
55新增: if (offline) await route.abort("internetdisconnected");
56新增: else await route.continue();
57新增: });
58新增: await approve.click();
59新增: await page.getByRole("alert").getByRole("button", {name:"重新读取"}).waitFor();
60新增: await page.unroute(sessionRequests);
61新增: await page.getByText("主机仍在等待这次审批。请核对参数后再次选择。", {exact:true}).waitFor();
62新增: await assert.rejects(readFile(process.env.CAGE_TEST_MOBILE_MARKER), {code:"ENOENT"});
63新增: await approve.click();
64新增: await page.getByText("isolated tool completed", {exact:true}).waitFor();
65新增: const tools = page.locator(".tool-history");
66新增: await tools.locator("summary").click();
67新增: await tools.getByText("Bash", {exact:true}).waitFor();
68新增: await tools.getByText("已完成", {exact:true}).waitFor();
69新增: assert.equal(await readFile(process.env.CAGE_TEST_MOBILE_MARKER,"utf8"),"approved");
70新增: await message.fill("follow-up");
71新增: await page.getByRole("button", {name:"发送",exact:true}).click();
72新增: await page.getByText("isolated continuation",{exact:true}).waitFor();
73新增: if(out) await page.screenshot({path:path.join(out,engine+"-cli-result.png")});
74新增:} catch(error) {
75新增: throw Error(String(error).replace(/(link-bootstrap)#[A-Za-z0-9_-]+/g,"$1#[redacted]"));
76新增:} finally {
77新增: await browser.close();
78新增:}
新增ui/scripts/mobile-inline-select-smoke.mjs+97 −0看文件
@@ -0,0 +1,97 @@
1新增:import assert from "node:assert/strict";
2新增:import { createRequire } from "node:module";
3新增:import { join } from "node:path";
4新增:import { smokeCaptureDirectory } from "./smoke-captures.mjs";
5新增:
6新增:const require = createRequire(import.meta.url);
7新增:const engines = require(process.env.CAGE_PLAYWRIGHT_MODULE || "playwright");
8新增:const engine = process.env.CAGE_TEST_BROWSER || "chromium";
9新增:const browser = await engines[engine].launch();
10新增:const output = await smokeCaptureDirectory("mobile-inline-select");
11新增:const origin = process.env.CAGE_UI_URL || "http://127.0.0.1:5399";
12新增:const errors = [];
13新增:try {
14新增: const page = await browser.newPage({ viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true });
15新增: page.on("pageerror", error => errors.push(error.message));
16新增: const projects = [{ path: "/work/alpha", name: "alpha" }, { path: "/work/beta", name: "beta" }, { path: "/work/gamma", name: "gamma" }];
17新增: const sessions = [];
18新增: let creations = 0;
19新增: await page.route("**/api/**", route => {
20新增: const request = route.request(), path = new URL(request.url()).pathname;
21新增: if (path.endsWith("/projects")) return route.fulfill({ json: { host: "隔离主机", ready: true, projects, shared_sessions: true } });
22新增: if (path.endsWith("/sessions")) {
23新增: if (request.method() === "POST") {
24新增: creations++;
25新增: const input = request.postDataJSON();
26新增: const session = { ...input, title: "测试会话", revision: 1, generation: input.id, turns: [] };
27新增: sessions.push(session);
28新增: return route.fulfill({ json: session });
29新增: }
30新增: return route.fulfill({ json: { sessions } });
31新增: }
32新增: if (path.endsWith("/account")) return route.fulfill({ json: { session: sessions[0], supported: false, candidates: [] } });
33新增: return route.fulfill({ json: sessions[0] || {} });
34新增: });
35新增: await page.goto(origin + "/mobile.html");
36新增: const picker = page.getByRole("combobox", { name: "选择项目", exact: true });
37新增: await picker.waitFor();
38新增: const create = page.getByRole("button", { name: "新建会话", exact: true });
39新增: const collapsed = await create.boundingBox();
40新增: await picker.press("Enter");
41新增: assert.ok((await create.boundingBox()).y > collapsed.y);
42新增: await picker.press("End");
43新增: await picker.press("Enter");
44新增: await picker.getByText("gamma", { exact: true }).waitFor();
45新增: assert.equal(await picker.getAttribute("aria-expanded"), "false");
46新增: assert.equal(await picker.evaluate(element => document.activeElement === element), true);
47新增: await picker.press("ArrowDown");
48新增: await picker.press("Escape");
49新增: assert.equal(await picker.getAttribute("aria-expanded"), "false");
50新增: assert.equal((await create.boundingBox()).y, collapsed.y);
51新增: await picker.tap();
52新增: await create.tap();
53新增: await page.getByRole("textbox", { name: "消息", exact: true }).waitFor();
54新增: assert.equal(creations, 1, "one tap after an expanded project selector must create exactly one session");
55新增: assert.equal(sessions[0].workspace, "/work/gamma");
56新增: await page.screenshot({ path: join(output, `${engine}-new-session.png`) });
57新增: await page.close();
58新增:
59新增: const phone = await browser.newPage({ viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true, userAgent: "CageMobile/1" });
60新增: phone.on("pageerror", error => errors.push(error.message));
61新增: const image = await phone.evaluate(() => {
62新增: const canvas = document.createElement("canvas");
63新增: canvas.width = 390; canvas.height = 600;
64新增: return canvas.toDataURL("image/jpeg").split(",")[1];
65新增: });
66新增: let frame, writes = 0;
67新增: const favorites = { folders: [{ id: "work", title: "工作" }, { id: "reference", title: "资料" }], items: [] };
68新增: await phone.route("**/api/**", route => {
69新增: const request = route.request(), path = new URL(request.url()).pathname, body = request.postDataJSON();
70新增: if (path.endsWith("/projects")) return route.fulfill({ json: { host: "隔离测试电脑", ready: true, projects: [] } });
71新增: if (path.endsWith("/sessions")) return route.fulfill({ json: { sessions: [] } });
72新增: if (path.endsWith("/favorites")) {
73新增: if (body) { writes++; favorites.items.push({ id: "saved", ...body }); }
74新增: return route.fulfill({ json: favorites });
75新增: }
76新增: if (path.endsWith("/open")) {
77新增: frame = { ...body, image, document: "fixture-document", url: "https://example.com/", title: "测试网页" };
78新增: return route.fulfill({ json: { id: frame.id } });
79新增: }
80新增: if (path.endsWith("/frame")) return route.fulfill({ json: frame });
81新增: return route.fulfill({ json: { id: frame?.id } });
82新增: });
83新增: await phone.goto(origin + "/mobile.html");
84新增: await phone.getByRole("dialog", { name: "工作区侧栏" }).getByRole("button", { name: "浏览器", exact: true }).click();
85新增: await phone.getByRole("img", { name: "远程浏览器画面" }).waitFor();
86新增: await phone.getByRole("button", { name: "收藏夹", exact: true }).tap();
87新增: await phone.getByRole("button", { name: "收藏此页", exact: true }).tap();
88新增: await phone.getByRole("combobox", { name: "保存到", exact: true }).tap();
89新增: await phone.getByRole("button", { name: "保存收藏", exact: true }).tap();
90新增: await phone.getByRole("button", { name: "取消此页收藏", exact: true }).waitFor();
91新增: assert.equal(writes, 1, "one tap after the expanded folder selector must save exactly once");
92新增: await phone.screenshot({ path: join(output, `${engine}-saved-favorite.png`) });
93新增: assert.deepEqual(errors, []);
94新增: console.log(`${engine}: inline layout, keyboard selection, Escape, focus restoration and first-tap session/favorite mutations passed.`);
95新增:} finally {
96新增: await browser.close();
97新增:}
新增ui/scripts/mobile-pair-settings-smoke.mjs+81 −0看文件
@@ -0,0 +1,81 @@
1新增:import assert from "node:assert/strict";
2新增:import fs from "node:fs/promises";
3新增:import { fileURLToPath } from "node:url";
4新增:import { createWorkbench } from "./workbench-fixture.mjs";
5新增:
6新增:const output = fileURLToPath(new URL("../../docs/test-reports/2026-11-07-paired-phone-model/", import.meta.url));
7新增:await fs.mkdir(output, { recursive: true });
8新增:let paired = true, device = null, rejectRemove = false, removals = 0;
9新增:let power = {active:true};
10新增:let holdNextStatus = false, releaseStatus;
11新增:let signalStatus, signalDelivered;
12新增:const statusHeld = new Promise(resolve => { signalStatus = resolve; });
13新增:const statusDelivered = new Promise(resolve => { signalDelivered = resolve; });
14新增:const { browser, page, errors } = await createWorkbench({
15新增: beforeNavigate: async page => page.route("**/api/mobile-pair", async route => {
16新增: if (route.request().method() === "GET" && holdNextStatus) {
17新增: holdNextStatus = false;
18新增: const snapshot = { paired, status: "", device };
19新增: await new Promise(resolve => { releaseStatus = resolve; signalStatus(); });
20新增: await route.fulfill({ json: snapshot });
21新增: signalDelivered();
22新增: return;
23新增: }
24新增: if (route.request().method() === "DELETE") {
25新增: if (rejectRemove) return route.fulfill({ status: 500, contentType:"text/plain; charset=utf-8", body: "移除失败,请重试" });
26新增: paired = false; device = null; removals++;
27新增: }
28新增: return route.fulfill({ json: { paired, status: "", device, keep_awake:power } });
29新增: }),
30新增:});
31新增:async function open() {
32新增: await page.getByRole("button", { name: "设置", exact: true }).click();
33新增: await page.getByRole("navigation", { name: "设置分组" }).getByRole("button", { name: "远程连接", exact: true }).click();
34新增: await page.getByRole("heading", { name: "手机已配对", exact: true }).waitFor();
35新增:}
36新增:async function confirmRemoval() {
37新增: await page.getByRole("button", { name: "移除配对手机", exact: true }).click();
38新增: await page.getByRole("heading", { name: "移除配对手机?", exact: true }).waitFor();
39新增:}
40新增:try {
41新增: await open();
42新增: await page.getByText("远程待机已请求主机保持运行,屏幕可正常熄灭。移除配对或结束后台服务后恢复原系统休眠策略。",{exact:true}).waitFor();
43新增: power = {active:false,error:"测试:系统未允许防休眠"};
44新增: await page.getByRole("alert").filter({hasText:"主机防休眠未生效:测试:系统未允许防休眠"}).waitFor();
45新增: power = {active:true};
46新增: await page.getByRole("alert").filter({hasText:"主机防休眠未生效"}).waitFor({state:"hidden"});
47新增: await page.getByText("型号待获取,请更新手机端 Cage 后重新连接。", { exact: true }).waitFor();
48新增: device = { platform: "android", model: "Google Pixel 9 Pro" };
49新增: await page.getByLabel("已配对手机", { exact: true }).getByText(device.model, { exact: true }).waitFor();
50新增: assert.equal(await page.getByLabel("已配对手机", { exact: true }).innerText(), "Google Pixel 9 Pro\nAndroid");
51新增: await page.screenshot({ path: output + "android-model.png", fullPage: true });
52新增: await page.reload(); await open();
53新增: await page.getByLabel("已配对手机", { exact: true }).getByText(device.model, { exact: true }).waitFor();
54新增: await confirmRemoval();
55新增: await page.getByText("移除 Google Pixel 9 Pro 后,这部手机需要重新扫码才能访问工作台。", { exact: true }).waitFor();
56新增: await page.getByRole("button", { name: "取消", exact: true }).click();
57新增: assert.equal(removals, 0);
58新增:
59新增: device = { platform: "ios", model: "iPhone 16 Pro" };
60新增: await page.getByLabel("已配对手机", { exact: true }).getByText(device.model, { exact: true }).waitFor();
61新增: await page.getByLabel("已配对手机", { exact: true }).getByText("iOS", { exact: true }).waitFor();
62新增: await page.screenshot({ path: output + "iphone-model.png", fullPage: true });
63新增: rejectRemove = true;
64新增: await confirmRemoval();
65新增: await page.getByRole("button", { name: "移除手机", exact: true }).click();
66新增: await page.getByText("移除失败,请重试", { exact: true }).waitFor();
67新增: await page.getByLabel("已配对手机", { exact: true }).getByText(device.model, { exact: true }).waitFor();
68新增: rejectRemove = false;
69新增: holdNextStatus = true;
70新增: await statusHeld;
71新增: await confirmRemoval();
72新增: await page.getByRole("button", { name: "移除手机", exact: true }).click();
73新增: await page.getByRole("heading", { name: "用手机连接 Cage", exact: true }).waitFor();
74新增: releaseStatus();
75新增: await statusDelivered;
76新增: await page.getByRole("heading", { name: "用手机连接 Cage", exact: true }).waitFor();
77新增: assert.equal(await page.getByLabel("已配对手机", { exact: true }).count(), 0);
78新增: assert.equal(removals, 1);
79新增: assert.deepEqual(errors, []);
80新增: console.log("Paired phone model: legacy fallback, live Android/iOS metadata, reload, cancel, failed removal, successful removal and stale polling response passed.");
81新增:} finally { await browser.close(); }
新增ui/scripts/mobile-transcript-smoke.mjs+97 −0看文件
@@ -0,0 +1,97 @@
1新增:// Reads the one-time URL from stdin. Run by TestMobileTranscriptInBrowser.
2新增:import assert from "node:assert/strict";
3新增:import { mkdir } from "node:fs/promises";
4新增:import path from "node:path";
5新增:const parts = [];
6新增:for await (const chunk of process.stdin) parts.push(chunk);
7新增:const entry = Buffer.concat(parts).toString().trim();
8新增:const engine = process.env.CAGE_TEST_MOBILE_BROWSER;
9新增:const playwright = await import(
10新增: process.env.CAGE_PLAYWRIGHT_MODULE || "playwright"
11新增:);
12新增:const browser = await playwright[engine].launch();
13新增:try {
14新增: const page = await browser.newPage({
15新增: viewport: { width: 390, height: 844 },
16新增: isMobile: true,
17新增: hasTouch: true,
18新增: colorScheme: "dark",
19新增: });
20新增: const errors = [];
21新增: page.on("pageerror", (e) => errors.push(e.message));
22新增: await page.goto(entry);
23新增: await page.getByRole("button", { name: "宣传片制作", exact: true }).click();
24新增: await page.getByRole("heading", { name: "交付文件" }).waitFor();
25新增: assert.equal(
26新增: await page.locator(".markdown strong").first().innerText(),
27新增: "以后维护",
28新增: );
29新增: assert.equal(await page.getByRole("table").count(), 1);
30新增: assert.equal(await page.getByRole("checkbox", { checked: true }).count(), 1);
31新增: const transcript = page.getByRole("region", { name: "会话消息" });
32新增: assert(await transcript.evaluate((el) => el.scrollWidth <= el.clientWidth));
33新增: const call = page.locator("summary").filter({ hasText: "2 次工具调用" });
34新增: await call.click();
35新增: await page.getByText("检查帧率", { exact: true }).waitFor();
36新增: await call.click();
37新增: const task = page.locator("summary").filter({ hasText: "后台任务" });
38新增: assert.equal(await task.count(), 1);
39新增: await task.focus();
40新增: await page.keyboard.press("Enter");
41新增: await page.getByText("fixture-id", { exact: true }).waitFor();
42新增: await task.click();
43新增: const capture = process.env.CAGE_TEST_MOBILE_CAPTURE;
44新增: if (capture) {
45新增: await mkdir(capture, { recursive: true });
46新增: await page.screenshot({
47新增: path: path.join(capture, engine + "-transcript.png"),
48新增: });
49新增: }
50新增: await page.getByRole("button", { name: /封面.*查看图片/ }).click();
51新增: await page.waitForFunction(
52新增: () => document.querySelector(".project-media img")?.naturalWidth > 0,
53新增: );
54新增: await page.getByRole("button", { name: /成片.*加载视频/ }).click();
55新增: await page.waitForFunction(
56新增: () => document.querySelector("video")?.videoWidth > 0,
57新增: );
58新增: const video = page.locator("video");
59新增: await video.evaluate(async (el) => {
60新增: el.muted = true;
61新增: await el.play();
62新增: });
63新增: await page.waitForFunction(
64新增: () => document.querySelector("video")?.currentTime > 0,
65新增: );
66新增: await video.evaluate((el) => el.pause());
67新增: if (capture)
68新增: await page.screenshot({ path: path.join(capture, engine + "-media.png") });
69新增: await page.getByRole("button", { name: /成片.*收起/ }).click();
70新增: assert.equal(await video.count(), 0);
71新增: await page.getByRole("button", { name: /缺失.*查看图片/ }).click();
72新增: await page.getByText(/未找到媒体文件/).waitFor();
73新增: await page.reload();
74新增: await page.getByRole("heading", { name: "交付文件" }).waitFor();
75新增: assert.equal(await page.locator("video").count(), 0);
76新增: const opened = page.waitForRequest(
77新增: (r) =>
78新增: r.method() === "POST" &&
79新增: new URL(r.url()).pathname === "/api/mobile/browser/open",
80新增: );
81新增: await page.getByRole("link", { name: "查看网页" }).click();
82新增: assert.equal((await opened).postDataJSON().url, "https://example.org/demo");
83新增: assert.deepEqual(errors, []);
84新增: console.log(
85新增: engine +
86新增: " Markdown, tool history, task notice, image decode, video playback, retry affordance, reload and remote link passed",
87新增: );
88新增:} catch (error) {
89新增: throw Error(
90新增: String(error).replace(
91新增: /link-bootstrap#[\w-]+/g,
92新增: "link-bootstrap#[redacted]",
93新增: ),
94新增: );
95新增:} finally {
96新增: await browser.close();
97新增:}
新增ui/scripts/native-display-live.mjs+172 −0看文件
@@ -0,0 +1,172 @@
1新增:import assert from "node:assert/strict";
2新增:import { pathToFileURL } from "node:url";
3新增:import path from "node:path";
4新增:import { writeFile } from "node:fs/promises";
5新增:import { execFile } from "node:child_process";
6新增:import { promisify } from "node:util";
7新增:
8新增:const { chromium } = await import(pathToFileURL(process.env.CAGE_NATIVE_DISPLAY_PLAYWRIGHT).href);
9新增:let input = "";
10新增:for await (const chunk of process.stdin) input += chunk;
11新增:const config = JSON.parse(input);
12新增:const browser = await chromium.launch({
13新增: executablePath: process.env.CAGE_NATIVE_DISPLAY_CHROMIUM || path.join(process.env["ProgramFiles(x86)"], "Microsoft", "Edge", "Application", "msedge.exe"),
14新增: headless: true,
15新增:});
16新增:const measurements = [], errors = [];
17新增:let received = 0, bytes = 0, opened = 0, closed = 0;
18新增:const context = await browser.newContext({ viewport: { width: 1440, height: 950 }, deviceScaleFactor: 1 });
19新增:await context.addCookies(config.cookies.map(cookie => ({ ...cookie, url: config.url, httpOnly: true, sameSite: "Strict" })));
20新增:const page = await context.newPage();
21新增:page.setDefaultTimeout(45000);
22新增:page.on("pageerror", error => errors.push(error.message));
23新增:const diagnostics = [];
24新增:page.on("console", message => {
25新增: if (["error", "warning"].includes(message.type())) diagnostics.push(message.text());
26新增:});
27新增:page.on("response", response => {
28新增: if (response.status() >= 400) diagnostics.push(`${response.status()} ${new URL(response.url()).pathname}`);
29新增:});
30新增:page.on("websocket", socket => {
31新增: if (!new URL(socket.url()).pathname.endsWith("/vnc")) return;
32新增: opened++;
33新增: socket.on("close", () => { closed++; });
34新增: socket.on("framereceived", event => { received++; bytes += Buffer.byteLength(event.payload); });
35新增:});
36新增:const canvas = page.locator(".remote-canvas canvas:visible").last();
37新增:const execute = promisify(execFile);
38新增:async function cpuSample() {
39新增: if (!process.env.CAGE_NATIVE_DISPLAY_SAMPLE) return null;
40新增: const result = await execute("powershell.exe", ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", process.env.CAGE_NATIVE_DISPLAY_SAMPLE, "-ServiceProcessId", String(process.ppid)]);
41新增: return JSON.parse(result.stdout.replace(/^\uFEFF/, ""));
42新增:}
43新增:async function measure(name, milliseconds) {
44新增: const before = { received, bytes, opened, closed }, start = performance.now();
45新增: const cpuBefore = await cpuSample();
46新增: await new Promise(resolve => setTimeout(resolve, milliseconds));
47新增: const cpuAfter = await cpuSample();
48新增: const sample = { name, milliseconds: performance.now() - start, messages: received - before.received, bytes: bytes - before.bytes, opened: opened - before.opened, closed: closed - before.closed };
49新增: if (cpuBefore && cpuAfter) {
50新增: sample.guest_cpu_seconds = cpuAfter.guest.cpu - cpuBefore.guest.cpu;
51新增: sample.guest_process_cpu_percent_one_core = 100000 * sample.guest_cpu_seconds / (cpuAfter.guest.timestamp - cpuBefore.guest.timestamp);
52新增: sample.guest_process_groups = Object.fromEntries(Object.entries(cpuAfter.guest.groups || {}).map(([name, value]) => [name, 100000 * (value - (cpuBefore.guest.groups?.[name] || 0)) / (cpuAfter.guest.timestamp - cpuBefore.guest.timestamp)]));
53新增: sample.host_service_cpu_seconds = cpuAfter.hostCPU - cpuBefore.hostCPU;
54新增: sample.host_service_cpu_percent_one_core = 100000 * sample.host_service_cpu_seconds / (cpuAfter.timestamp - cpuBefore.timestamp);
55新增: }
56新增: measurements.push(sample);
57新增: return sample;
58新增:}
59新增:async function point(x, y) {
60新增: const position = await canvas.evaluate((element, coordinate) => {
61新增: const box = element.getBoundingClientRect();
62新增: return { x: box.x + coordinate.x * 2 / element.width * box.width, y: box.y + coordinate.y * 2 / element.height * box.height };
63新增: }, { x, y });
64新增: await page.mouse.click(position.x, position.y);
65新增:}
66新增:try {
67新增: await page.goto(config.url);
68新增: await page.getByRole("navigation", { name: "主导航" }).getByRole("button", { name: "打开浏览器", exact: true }).click();
69新增: const address = page.locator(".address-bar input").first();
70新增: await address.fill(config.fixture);
71新增: await address.press("Enter");
72新增: await page.waitForFunction(() => [...document.querySelectorAll(".remote-canvas canvas")].some(element => {
73新增: if (element.getBoundingClientRect().width < 100 || element.width < 320 || element.height < 740) return false;
74新增: const pixel = element.getContext("2d").getImageData(150, 650, 1, 1).data;
75新增: return Math.abs(pixel[0] - 220) < 20 && Math.abs(pixel[1] - 80) < 20;
76新增: }));
77新增: await measure("warmup", 1500);
78新增: const idle = await measure("static", 5000);
79新增: assert.equal(idle.closed, 0, "static frames disconnected the native bridge");
80新增: assert.equal(idle.opened, 0, "static frames triggered reconnection");
81新增: assert(idle.bytes < 65536, `static frames repeatedly transferred pixels (${idle.bytes} bytes)`);
82新增: await page.screenshot({ path: path.join(config.evidence, "windows-browser-static.png") });
83新增:
84新增: await point(120, 65);
85新增: const typed = performance.now();
86新增: await page.keyboard.type("Cage live 123", { delay: 30 });
87新增: await page.waitForFunction(() => [...document.querySelectorAll(".remote-canvas canvas")].some(element => {
88新增: if (element.getBoundingClientRect().width < 100 || element.width < 320) return false;
89新增: const pixel = element.getContext("2d").getImageData(20, 20, 1, 1).data;
90新增: return Math.abs(pixel[0] - 40) < 20 && Math.abs(pixel[1] - 160) < 20;
91新增: }));
92新增: measurements.push({ name: "input_to_visible_confirmation", milliseconds: performance.now() - typed });
93新增: await point(600, 100);
94新增: await point(120, 175);
95新增: await page.waitForFunction(() => [...document.querySelectorAll(".remote-canvas canvas")].some(element => {
96新增: if (element.getBoundingClientRect().width < 100 || element.height < 740) return false;
97新增: const pixels = element.getContext("2d").getImageData(0, 650, element.width, 1).data;
98新增: const red = x => Math.abs(pixels[x * 4] - 220) < 20 && Math.abs(pixels[x * 4 + 1] - 80) < 20;
99新增: return !red(90) && Array.from({ length: 80 }, (_, index) => 160 + index * 10).some(x => x < element.width && red(x));
100新增: }), null, { timeout: 5000 });
101新增: const motion = await measure("animation", 4500);
102新增: assert(motion.bytes > 65536, "animation produced no changed-frame payload");
103新增: assert.equal(motion.closed, 0);
104新增: await page.waitForFunction(() => [...document.querySelectorAll(".remote-canvas canvas")].some(element => {
105新增: if (element.getBoundingClientRect().width < 100 || element.height < 740) return false;
106新增: const pixel = element.getContext("2d").getImageData(150, 650, 1, 1).data;
107新增: return Math.abs(pixel[0] - 220) < 20 && Math.abs(pixel[1] - 80) < 20;
108新增: }));
109新增: await page.mouse.wheel(0, 650);
110新增: const scrolling = await measure("scroll", 800);
111新增: assert(scrolling.bytes > 0, "scrolling did not update the rendered page");
112新增: assert.equal(scrolling.closed, 0);
113新增: await page.keyboard.press("Control+Home");
114新增:
115新增: await page.keyboard.press("Control+f");
116新增: const menu = await measure("native_find", 1200);
117新增: assert(menu.bytes > 1000, "native find UI did not update the frame");
118新增: await page.screenshot({ path: path.join(config.evidence, "windows-browser-native-find.png") });
119新增: await page.keyboard.press("Escape");
120新增: const previousWidth = await canvas.evaluate(element => element.width);
121新增: await page.setViewportSize({ width: 1280, height: 850 });
122新增: await page.waitForFunction(width => [...document.querySelectorAll(".remote-canvas canvas")].some(element => element.getBoundingClientRect().width > 100 && element.width >= 320 && element.width !== width), previousWidth);
123新增: await page.screenshot({ path: path.join(config.evidence, "windows-browser-resized.png") });
124新增:
125新增: const edge = await canvas.evaluate(element => ({ x: element.width / 2 - 90, y: element.height / 2 - 42 }));
126新增: await point(edge.x, edge.y);
127新增: await page.waitForFunction(() => [...document.querySelectorAll(".remote-canvas canvas")].some(element => {
128新增: if (element.getBoundingClientRect().width < 100 || element.width < 320 || element.height < 240) return false;
129新增: const pixel = element.getContext("2d").getImageData(element.width - 100, element.height - 50, 1, 1).data;
130新增: return Math.abs(pixel[0] - 90) < 20 && Math.abs(pixel[1] - 60) < 20 && Math.abs(pixel[2] - 210) < 20;
131新增: }), null, { timeout: 5000 });
132新增: measurements.push({ name: "resized_edge_click", confirmed: true });
133新增:
134新增: await page.evaluate(() => { window.cageWindowVisible = false; window.dispatchEvent(new Event("cage-window-visibility")); });
135新增: await measure("hide_transition", 500);
136新增: const hidden = await measure("hidden", 2000);
137新增: assert.equal(hidden.messages, 0, "hidden workbench retained its frame stream");
138新增: await page.evaluate(() => { window.cageWindowVisible = true; window.dispatchEvent(new Event("cage-window-visibility")); });
139新增: await canvas.waitFor();
140新增: const resumed = await measure("resume", 2000);
141新增: assert(resumed.bytes > 0, "restoring the workbench did not deliver pixels");
142新增: if (process.env.CAGE_NATIVE_DISPLAY_DESKTOP === "1") {
143新增: await page.getByRole("navigation", { name: "主导航" }).getByRole("button", { name: "Claude Desktop", exact: true }).click();
144新增: await page.waitForFunction(() => [...document.querySelectorAll('section[aria-label="Claude Desktop"] canvas')].some(element => {
145新增: if (element.getBoundingClientRect().width < 100 || element.width < 320 || element.height < 240) return false;
146新增: const pixels = element.getContext("2d").getImageData(0, 0, element.width, element.height).data;
147新增: for (let y = 0; y < element.height; y += 8) for (let x = 0; x < element.width; x += 8) {
148新增: const index = (y * element.width + x) * 4;
149新增: if (pixels[index] > 180 && pixels[index + 1] > 70 && pixels[index + 1] < 160 && pixels[index + 2] < 130) return true;
150新增: }
151新增: return false;
152新增: }), null, { timeout: 75000 });
153新增: await page.screenshot({ path: path.join(config.evidence, "windows-claude-live.png") });
154新增: const desktop = await measure("claude_visible", 5000);
155新增: assert.equal(desktop.closed, 0, "the official Claude window disconnected while visible");
156新增: await page.evaluate(() => { window.cageWindowVisible = false; window.dispatchEvent(new Event("cage-window-visibility")); });
157新增: await measure("claude_hide_transition", 500);
158新增: const desktopHidden = await measure("claude_hidden", 2000);
159新增: assert.equal(desktopHidden.messages, 0);
160新增: await page.evaluate(() => { window.cageWindowVisible = true; window.dispatchEvent(new Event("cage-window-visibility")); });
161新增: const desktopResumed = await measure("claude_resume", 2000);
162新增: assert(desktopResumed.bytes > 0);
163新增: }
164新增: assert.deepEqual(errors, []);
165新增: await writeFile(path.join(config.evidence, "windows-browser-live.json"), JSON.stringify({ measurements, diagnostics, errors, opened, closed }, null, 2));
166新增: console.log(JSON.stringify({ measurements, opened, closed }));
167新增:} catch (error) {
168新增: await page.screenshot({ path: path.join(config.evidence, "windows-browser-failure.png") });
169新增: await writeFile(path.join(config.evidence, "windows-browser-live-partial.json"), JSON.stringify({ measurements, diagnostics, errors, received, bytes, opened, closed }, null, 2));
170新增: console.log(JSON.stringify({ diagnostics, measurements, errors, received, bytes, opened, closed }));
171新增: throw error;
172新增:} finally { await browser.close(); }
新增ui/scripts/native-maintenance-smoke.mjs+51 −0看文件
@@ -0,0 +1,51 @@
1新增:import assert from "node:assert/strict";
2新增:import { createWorkbench } from "./workbench-fixture.mjs";
3新增:
4新增:for (const system of ["macos", "windows-11", "debian"]) {
5新增: const calls = [];
6新增: const native = system !== "debian";
7新增: const fixture = await createWorkbench({ beforeNavigate: async (page, state) => {
8新增: state.account.guest_system = state.status.guest_system = system;
9新增: state.status.vm_running = state.status.ready = true;
10新增: await page.route("**/api/environment/versions", route => route.fulfill({ json: {
11新增: vm_running: true, tools_update_allowed: true,
12新增: components: { status: "update_required", update_required: true },
13新增: controller: { version: "fixture-controller" },
14新增: tools: { claude: { current: "2.1.300", required: "2.1.311" }, node: { current: "v24.22.2", required: "24.22.2" } },
15新增: maintenance: native ? { native: true, guest_system: system, requires_closed_terminals: true } : undefined,
16新增: } }));
17新增: for (const operation of ["update", "tools"]) {
18新增: await page.route(`**/api/environment/${operation}`, route => {
19新增: calls.push(operation);
20新增: return route.fulfill({ status: 409, contentType: "text/plain; charset=utf-8", body: "请先保存工作,结束正在运行的终端和 Claude Code 轮次,再重试更新。" });
21新增: });
22新增: }
23新增: } });
24新增: const { page, browser, errors } = fixture;
25新增: try {
26新增: await page.getByRole("button", { name: "设置", exact: true }).click();
27新增: await page.getByRole("navigation", { name: "设置分组" }).getByRole("button", { name: "环境与恢复", exact: true }).click();
28新增: const panel = page.getByRole("region", { name: "环境版本", exact: true });
29新增: await panel.getByText("2.1.300", { exact: true }).waitFor();
30新增: await panel.getByText("2.1.311", { exact: true }).waitFor();
31新增: for (const operation of ["组件", "工具"]) {
32新增: await panel.getByRole("button", { name: `更新环境${operation}`, exact: true }).click();
33新增: const dialog = page.getByRole("dialog", { name: `更新环境${operation}?`, exact: true });
34新增: const text = await dialog.innerText();
35新增: if (native) {
36新增: assert.ok(text.includes("结束正在运行的终端和 Claude Code 轮次"));
37新增: assert.ok(text.includes("聊天历史、项目文件与登录资料会保留"));
38新增: assert.equal(text.includes("验证已绑定客机的管理员账户"), system === "windows-11");
39新增: } else {
40新增: assert.ok(text.includes("工作台终端、项目文件和登录状态会保留"));
41新增: }
42新增: await dialog.getByRole("button", { name: `更新${operation}`, exact: true }).click();
43新增: await panel.getByRole("alert").filter({ hasText: "结束正在运行的终端" }).waitFor();
44新增: }
45新增: assert.deepEqual(calls, ["update", "tools"]);
46新增: assert.deepEqual(errors, []);
47新增: console.log(JSON.stringify({ system, passed: true, calls }));
48新增: } finally {
49新增: await browser.close();
50新增: }
51新增:}
新增ui/scripts/native-workbench-smoke.mjs+42 −0看文件
@@ -0,0 +1,42 @@
1新增:// Verify that switching the guest keeps the Linux workbench's actual entry points.
2新增:import assert from "node:assert/strict";
3新增:import { createWorkbench } from "./workbench-fixture.mjs";
4新增:
5新增:let baseline;
6新增:for (const system of ["debian-13", "windows-11", "macos"]) {
7新增: const fixture = await createWorkbench({
8新增: beforeNavigate: async (page, state) => {
9新增: state.account.guest_system = system;
10新增: state.status.guest_system = system;
11新增: state.status.vm_running = state.status.ready = true;
12新增: const status = { installed: true, running: true, native_user_session: true, version: "4.0", screen: false, input: false };
13新增: await page.route("**/api/claude-desktop", route => route.fulfill({json:status}));
14新增: await page.route("**/api/macos/claude/window", route => route.fulfill({json:status}));
15新增: },
16新增: });
17新增: const { page, state, errors, browser } = fixture;
18新增: try {
19新增: const nav = page.getByRole("navigation", { name: "主导航" });
20新增: await nav.getByRole("button", { name: "工作台", exact: true }).waitFor();
21新增: const labels = await nav.getByRole("button").allTextContents();
22新增: if (system === "debian-13") baseline = labels;
23新增: else assert.deepEqual(labels, baseline, system);
24新增:
25新增: await nav.getByRole("button", { name: "Claude Desktop", exact: true }).click();
26新增: await page.locator(".claude-desktop-toolbar").getByText("Claude Desktop", { exact:true }).waitFor();
27新增: const zoom = page.getByRole("combobox", {name:"Desktop 显示大小"});
28新增: await zoom.click();
29新增: await page.getByRole("option", {name:"125%"}).click();
30新增: assert.match(await zoom.innerText(), /125%/);
31新增: await nav.getByRole("button", {name:"打开浏览器"}).click();
32新增: await page.locator(".address-bar input").first().waitFor();
33新增: assert.ok(state.requests.some(r => r.path === "/browser/new"));
34新增: await nav.getByRole("button", {name:"工作台", exact:true}).click();
35新增: await page.locator('[data-terminal-location="shortcuts"]').click();
36新增: await page.getByRole("menuitem", {name:"Claude 终端"}).click();
37新增: await page.waitForFunction(() => document.querySelector(".terminal-lane:not([hidden]) .terminal-view"));
38新增: assert.ok(state.requests.some(r => r.path === "/terminals" && r.body?.kind === "claude"));
39新增: assert.deepEqual(errors, []);
40新增: console.log(system, "shared navigation, Claude Desktop zoom, browser and Claude Code entry passed");
41新增: } finally { await browser.close(); }
42新增:}
修改ui/scripts/packaged-startup-smoke.mjs+10 −7看文件
@@ -28,8 +28,8 @@ try {
2828 const page = await browser.newPage();
2929 const errors = [];
3030 page.on("pageerror", (error) => errors.push(error.message));
31删除: const statusResponse = page.waitForResponse((response) => response.url().endsWith("/api/status") && response.ok());
3231 await page.goto(entry.url);
32新增: await page.getByRole("button", { name: "使用用户名和密码", exact: true }).click();
3333 await page.getByLabel("用户名",{exact:true}).waitFor();
3434 const initial = await page.evaluate(async () => (await fetch("/api/client/local-status")).json());
3535 assert.ok(initial.known && initial.service_running && !initial.running, "opening the local home must not boot the VM");
@@ -39,22 +39,25 @@ try {
3939 await page.getByLabel("用户名",{exact:true}).fill("Packaged Smoke");
4040 await page.getByLabel("设置密码",{exact:true}).fill(password);
4141 await page.getByLabel("确认密码",{exact:true}).fill(password);
42新增: const statusResponse = page.waitForResponse((response) => response.url().endsWith("/api/status") && response.ok());
4243 await page.getByRole("button",{name:"创建本地账户",exact:true}).click();
4344 const status = await (await statusResponse).json();
4445 assert.equal(status.vm_running, false);
45删除: await page.getByRole("button", { name: "配置网络与代理", exact: true }).waitFor();
46新增: await page.getByRole("heading", { name: "为 Cage 准备独立环境", exact: true }).waitFor();
4647 const nav = page.getByRole("navigation", {name:"主导航"});
47删除: assert.equal(await nav.getByRole("button", {name:/Claude(?: Code)? 会话/}).count(), 0);
48删除: assert.equal(await nav.getByRole("button", {name:"Claude Desktop",exact:true}).count(), 1);
49删除: await page.getByRole("button",{name:"SSH 主机",exact:true}).click();
48新增: assert.equal(await nav.count(), 0, "fresh profile must not mount workbench navigation");
49新增: await page.getByRole("button",{name:"只连接 SSH 主机",exact:true}).click();
5050 await page.getByRole("complementary",{name:"SSH 主机"}).waitFor();
5151 if (evidence) await page.screenshot({ path:path.join(evidence,"local-ssh-sidebar.png") });
5252 await page.getByRole("button",{name:"返回工作台侧栏"}).click();
5353 assert.equal(new URL(page.url()).hash, "", "launch ticket was not removed");
54删除: await page.getByRole("button", { name: "配置网络与代理", exact: true }).click();
54新增: await page.getByRole("button", { name: "下一步:配置代理", exact: true }).click();
55新增: await page.getByRole("heading",{name:"连接你的网络代理",exact:true}).waitFor();
56新增: assert.ok(await page.getByRole("button",{name:"开始安装",exact:true}).isDisabled(), "proxy must be applied before installation");
57新增: if(evidence) await page.screenshot({ path:path.join(evidence,"initialization-proxy.png") });
5558 await page.getByText("添加来源", { exact: true }).first().waitFor();
5659 assert.deepEqual(errors, []);
57删除: console.log(JSON.stringify({ checks: ["original local home by default", "VM stopped throughout", "isolated local account setup", packaged ? "packaged helper bootstrap" : "development helper bootstrap", "real session and APIs", "embedded production UI loaded", "private profile onboarding", "launch ticket removed"], version: entry.controller.version }));
60新增: console.log(JSON.stringify({ checks: ["standalone initialization after account setup", "VM stopped throughout", "no workbench navigation before initialization", "SSH-only alternative", "proxy required before installation", packaged ? "packaged helper bootstrap" : "development helper bootstrap", "real session and APIs", "embedded production UI loaded", "private profile onboarding", "launch ticket removed"], version: entry.controller.version }));
5861} finally {
5962 await browser?.close();
6063 await run(cage, ["prepare-update", "--json"], { env });
修改ui/scripts/password-vault-smoke.mjs+8 −4看文件
@@ -2,7 +2,7 @@ import assert from "node:assert/strict";
22import fs from "node:fs/promises";
33import { fileURLToPath } from "node:url";
44import { createWorkbench } from "./workbench-fixture.mjs";
5删除:const output = fileURLToPath(new URL("../../docs/test-reports/2026-11-05-password-vault/", import.meta.url));
5新增:const output = process.env.CAGE_VAULT_CAPTURE || fileURLToPath(new URL("../../docs/test-reports/2026-11-05-password-vault/", import.meta.url));
66await fs.mkdir(output, { recursive: true });
77let clipboard = "";
88const { browser, page, state, errors } = await createWorkbench({ nativeRequest: async ({ action, text }) => {
@@ -94,8 +94,9 @@ try {
9494 state.tabs = [{ id: "web-vault", title: "邮箱", kind: "web", url: "https://mail.example.test/login" }]; state.active = "web-vault";
9595 await page.reload();
9696 await page.getByRole("button", { name: "打开浏览器", exact: true }).click();
97删除: await page.getByRole("button", { name: /密码 · 1 个账号/ }).waitFor();
98删除: const trigger = page.getByRole("button", { name: /密码 · 1 个账号/ });
97新增: await page.getByRole("button", { name: "浏览器菜单", exact: true }).click();
98新增: await page.getByRole("menuitem", { name: /密码 · 1 个账号/ }).waitFor();
99新增: const trigger = page.getByRole("menuitem", { name: /密码 · 1 个账号/ });
99100 const before = await page.locator(".browser-chrome").boundingBox();
100101 await trigger.press("Enter");
101102 const picker = page.getByRole("region", { name: "当前网站的密码" });
@@ -106,9 +107,12 @@ try {
106107 await page.keyboard.press("Enter");
107108 await page.getByRole("status").filter({ hasText: "已填写" }).waitFor();
108109 assert.equal(filled, entries[0].id);
110新增: const filledHeight = (await page.locator(".browser-chrome").boundingBox()).height;
111新增: const pickerHeight = (await picker.boundingBox()).height;
109112 await trigger.press("Escape");
110113 await picker.waitFor({ state: "hidden" });
111删除: assert.equal(Math.round((await page.locator(".browser-chrome").boundingBox()).height), Math.round(before.height));
114新增: assert.equal(Math.round((await page.locator(".browser-chrome").boundingBox()).height), Math.round(filledHeight - pickerHeight),
115新增: "closing the password picker releases its space while preserving the fill confirmation");
112116 candidate = { id: "pending", tab: "web-vault", origin: "https://mail.example.test", username: "[email protected]", password: "new-fixture-secret" };
113117 await page.getByText("更新此账号的密码?", { exact: true }).waitFor();
114118 await page.screenshot({ path: output + "vault-save-prompt.png" });
新增ui/scripts/private-browser-paste-smoke.mjs+130 −0看文件
@@ -0,0 +1,130 @@
1新增:import assert from "node:assert/strict";
2新增:import { createWorkbench } from "./workbench-fixture.mjs";
3新增:import { startDisplay } from "./rfb-wire-fixture.mjs";
4新增:
5新增:const display = await startDisplay(process.env.CAGE_UI_URL || "http://127.0.0.1:5198", { sharedClipboard: true });
6新增:const reads = [], prepared = [], cancelled = [], delivered = [];
7新增:const png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIHWP4z8DwHwAFgAI/ScLbtAAAAABJRU5ErkJggg==";
8新增:const { browser, page, state, errors } = await createWorkbench({
9新增: url: display.url, mockWebSockets: false,
10新增: nativeRequest: request => {
11新增: if (request.action === "clipboardRevision") return 1;
12新增: if (request.action === "clipboardSyncRead") return { text: "synthetic system clipboard", revision: 1 };
13新增: if (request.action === "clipboardReadContent") return new Promise(resolve => reads.push(resolve));
14新增: return true;
15新增: },
16新增: async beforeNavigate(page, state) {
17新增: state.status.ready = state.status.vm_running = true;
18新增: state.status.guest_system = state.account.guest_system = "macos";
19新增: state.tabs = [
20新增: { id: "input-one", kind: "web", title: "输入测试一", url: "https://one.example.test" },
21新增: { id: "input-two", kind: "web", title: "输入测试二", url: "https://two.example.test" },
22新增: ];
23新增: state.active = "input-one";
24新增: await page.route("**/api/browser/tabs", route => route.fulfill({ json: {
25新增: tabs: state.tabs, active: state.active, capabilities: { nativeClipboard: true, systemClipboard: false },
26新增: } }));
27新增: await page.route("**/api/input", route => route.fulfill({ json: { available: true, context: "a".repeat(32), rect: [20, 20, 1, 24] } }));
28新增: await page.route("**/api/input/paste/start", route => {
29新增: const body = route.request().postDataJSON();
30新增: const context = String(prepared.length + 1).padStart(32, "0");
31新增: prepared.push({ ...body, context });
32新增: return route.fulfill({ json: { available: true, context } });
33新增: });
34新增: await page.route("**/api/input/paste/cancel", route => {
35新增: cancelled.push(route.request().postDataJSON());
36新增: return route.fulfill({ json: { ok: true } });
37新增: });
38新增: for (const kind of ["text", "image"]) await page.route(`**/api/input/${kind}`, route => {
39新增: delivered.push({ kind, body: route.request().postDataJSON() });
40新增: return route.fulfill({ json: { ok: true } });
41新增: });
42新增: },
43新增:});
44新增:page.setDefaultTimeout(10000);
45新增:async function until(predicate) {
46新增: for (let attempt = 0; attempt < 200; attempt++) {
47新增: if (predicate()) return;
48新增: await page.waitForTimeout(20);
49新增: }
50新增: assert(predicate(), "expected private clipboard operation did not arrive");
51新增:}
52新增:try {
53新增: await page.getByRole("button", { name: "打开浏览器", exact: true }).click();
54新增: await page.getByText("正在连接画面", { exact: true }).waitFor({ state: "hidden" });
55新增: await page.waitForFunction(() => window.cageSharedClipboardActive === true);
56新增: const canvas = page.locator(".browser-lane .remote-canvas canvas");
57新增: await canvas.click({ position: { x: 40, y: 40 } });
58新增: display.stats.keys.length = 0;
59新增: await page.keyboard.press("Meta+f");
60新增: await until(() => display.stats.keys.some(key => key.symbol === 102 && !key.down));
61新增: assert(display.stats.keys.some(key => key.symbol === 0xffeb && key.down));
62新增: assert(!display.stats.keys.some(key => key.symbol === 0xffe3));
63新增: await page.keyboard.press("Control+a");
64新增: await until(() => display.stats.keys.some(key => key.symbol === 0xffe3 && !key.down));
65新增: await page.evaluate(() => {
66新增: window.pasteIntent = [];
67新增: const fetch = window.fetch.bind(window);
68新增: window.fetch = (...args) => {
69新增: if (String(args[0]).endsWith("/input/paste/start")) window.pasteIntent.push("prepare");
70新增: return fetch(...args);
71新增: };
72新增: const bridge = window.webkit.messageHandlers.cage, post = bridge.postMessage.bind(bridge);
73新增: bridge.postMessage = body => {
74新增: if (body.action === "clipboardReadContent") window.pasteIntent.push("read");
75新增: return post(body);
76新增: };
77新增: const create = URL.createObjectURL.bind(URL);
78新增: URL.createObjectURL = value => { window.pasteIntent.push("decode"); return create(value); };
79新增: });
80新增: display.stats.keys.length = 0;
81新增: await page.keyboard.press("Meta+v");
82新增: await until(() => reads.length === 1 && prepared.length === 1);
83新增: assert.deepEqual(await page.evaluate(() => window.pasteIntent), ["prepare", "read"]);
84新增: await page.keyboard.press("Enter");
85新增: assert(!display.stats.keys.some(key => key.symbol === 0xff0d));
86新增: const longText = "共享架构🙂\n".repeat(2000);
87新增: reads[0]({ text: longText });
88新增: await until(() => delivered.length === 1 && display.stats.keys.some(key => key.symbol === 0xff0d && !key.down));
89新增: assert.equal(delivered[0].kind, "text");
90新增: assert.equal(delivered[0].body.text, longText);
91新增: assert.equal(delivered[0].body.id, "input-one");
92新增: assert.equal(delivered[0].body.context, prepared[0].context);
93新增: assert(!display.stats.keys.some(key => key.symbol === 118), "private clipboard text must not depend on a guest OS paste chord");
94新增:
95新增: await page.keyboard.press("Meta+v");
96新增: await until(() => reads.length === 2);
97新增: await page.getByRole("tab", { name: "输入测试二", exact: true }).click();
98新增: await until(() => state.active === "input-two");
99新增: reads[1]({ png });
100新增: await until(() => cancelled.some(item => item.context === prepared[1].context));
101新增: assert.equal(delivered.length, 1, "an old tab must reject the delayed PNG");
102新增:
103新增: await canvas.click({ position: { x: 50, y: 50 } });
104新增: assert.deepEqual(await page.evaluate(() => [window.cageEditAction("paste"), window.cageEditAction("paste")]), [true, true]);
105新增: await until(() => reads.length === 4 && prepared.length === 4);
106新增: reads[3]({ text: "second queued paste" });
107新增: await page.waitForTimeout(80);
108新增: assert.equal(delivered.length, 1, "the second clipboard read must wait for the first paste");
109新增: reads[2]({ png });
110新增: await until(() => delivered.length === 3);
111新增: assert.deepEqual(delivered.slice(1).map(item => item.kind), ["image", "text"]);
112新增: assert(delivered.slice(1).every(item => item.body.id === "input-two"));
113新增:
114新增: await page.evaluate(() => { window.pasteIntent.length = 0; });
115新增: await page.getByLabel("Cage 网页输入").evaluate((element, encoded) => {
116新增: const data = new DataTransfer();
117新增: data.items.add(new File([Uint8Array.from(atob(encoded), value => value.charCodeAt(0))], "screenshot.png", { type: "image/png" }));
118新增: element.dispatchEvent(new ClipboardEvent("paste", { bubbles: true, cancelable: true, clipboardData: data }));
119新增: }, png);
120新增: await until(() => delivered.length === 4);
121新增: assert.deepEqual(await page.evaluate(() => window.pasteIntent), ["prepare", "decode"]);
122新增: assert.equal(delivered[3].kind, "image");
123新增: await until(() => cancelled.length === prepared.length);
124新增: assert.deepEqual(errors, []);
125新增: console.log(JSON.stringify({ result: "PASS", browser: browser.version(), textBytes: Buffer.byteLength(longText), checks: [
126新增: "Mac browser Command and physical Control keep separate RFB modifiers",
127新增: "private clipboard stays reachable while OS sharing is active", "preparation precedes clipboard read and bitmap decode",
128新增: "long Unicode text uses bound text transfer before Enter", "tab change rejects a pending PNG", "successive pastes stay ordered", "unused and completed preparations are cancelled",
129新增: ], deliveries: delivered.map(item => ({ kind: item.kind, id: item.body.id, context: item.body.context })) }));
130新增:} finally { await browser.close(); await display.close(); }
新增ui/scripts/proxy-yaml-drop-smoke.mjs+171 −0看文件
@@ -0,0 +1,171 @@
1新增:// Frontend interaction checks with synthetic files and isolated API fixtures.
2新增:import assert from "node:assert/strict";
3新增:import fs from "node:fs/promises";
4新增:import path from "node:path";
5新增:import { createWorkbench } from "./workbench-fixture.mjs";
6新增:
7新增:const engine = process.env.CAGE_TEST_BROWSER || "chromium";
8新增:const output = path.resolve(process.env.CAGE_YAML_QA_OUTPUT || "/tmp/cage-yaml-drop-qa", engine);
9新增:await fs.mkdir(output, { recursive: true });
10新增:const { browser, page, state, errors } = await createWorkbench({ viewport: { width: 1280, height: 1000 } });
11新增:const yaml = "proxies:\n - {name: 本地测试, type: socks5, server: 127.0.0.1, port: 1080}\n";
12新增:const proxy = { active: false, sources: [], port: 17896, core_available: true };
13新增:const imports = [];
14新增:try {
15新增: await page.route("**/api/proxy", (route) => route.fulfill({ json: proxy }));
16新增: await page.route("**/api/proxy/import", (route) => {
17新增: const body = route.request().postDataJSON();
18新增: imports.push(body);
19新增: const job = { id: "yaml-drop-import", running: false, message: "已导入" };
20新增: state.status.job = job;
21新增: proxy.sources.push({ id: "drop-source", name: body.name, nodes: [{ id: "drop-node", name: "本地测试", type: "socks5" }], remote: false, updated_at: new Date().toISOString() });
22新增: return route.fulfill({ json: job });
23新增: });
24新增: const open = async () => {
25新增: await page.getByRole("button", { name: /^设置/ }).click();
26新增: await page.getByRole("button", { name: "网络与代理", exact: true }).click();
27新增: await page.getByRole("tab", { name: "订阅", exact: true }).click();
28新增: await page.getByRole("button", { name: "添加来源", exact: true }).click();
29新增: await page.getByRole("button", { name: "本地 YAML", exact: true }).click();
30新增: };
31新增: await open();
32新增: const region = page.locator(".proxy-yaml-input");
33新增: const dropzone = page.locator(".proxy-yaml-dropzone");
34新增: const editor = page.getByRole("textbox", { name: "节点 YAML", exact: true });
35新增: const name = page.getByLabel("来源名称", { exact: true });
36新增: const submit = page.getByRole("button", { name: "导入并验证", exact: true });
37新增: const expectText = async (locator, value) => {
38新增: await locator.filter({ hasText: value }).waitFor();
39新增: };
40新增: const dataTransfer = async (files) => page.evaluateHandle((entries) => {
41新增: const transfer = new DataTransfer();
42新增: for (const entry of entries) transfer.items.add(new File([entry.content || ""], entry.name, { type: entry.type || "application/yaml" }));
43新增: return transfer;
44新增: }, files);
45新增: const drop = async (files, target = dropzone) => {
46新增: const transfer = await dataTransfer(files);
47新增: await target.dispatchEvent("dragenter", { dataTransfer: transfer });
48新增: await target.dispatchEvent("dragover", { dataTransfer: transfer });
49新增: await target.dispatchEvent("drop", { dataTransfer: transfer });
50新增: await transfer.dispose();
51新增: };
52新增: const payload = (filename = "日常代理.yaml", content = yaml) => ({ name: filename, mimeType: "application/yaml", buffer: Buffer.from(content) });
53新增: const fileInput = region.locator('input[type="file"]');
54新增: assert.equal(await submit.isDisabled(), true);
55新增: await dropzone.scrollIntoViewIfNeeded();
56新增: await page.screenshot({ path: path.join(output, "empty.png"), fullPage: true });
57新增:
58新增: // Keyboard activation reaches the actual file input, including same-file reselection.
59新增: await dropzone.focus();
60新增: const firstChooser = page.waitForEvent("filechooser");
61新增: await dropzone.press("Enter");
62新增: await (await firstChooser).setFiles(payload());
63新增: await expectText(region.getByRole("status"), "文件已读取");
64新增: assert.equal(await editor.inputValue(), yaml);
65新增: assert.equal(await name.inputValue(), "日常代理");
66新增: assert.equal(await submit.isEnabled(), true);
67新增: await editor.fill(yaml + "# 手动编辑\n");
68新增: await expectText(region.getByRole("status"), "内容已编辑");
69新增: await dropzone.focus();
70新增: const secondChooser = page.waitForEvent("filechooser");
71新增: await dropzone.press("Space");
72新增: await (await secondChooser).setFiles(payload());
73新增: await page.waitForFunction((expected) => document.querySelector('[aria-label="节点 YAML"]').value === expected, yaml);
74新增: await name.fill("我的来源");
75新增:
76新增: // Nested drag events must keep the highlight until the pointer leaves the region.
77新增: const transfer = await dataTransfer([{ name: "替换.YML", content: yaml + "# 拖入\n" }]);
78新增: await dropzone.dispatchEvent("dragenter", { dataTransfer: transfer });
79新增: await dropzone.locator("strong").dispatchEvent("dragenter", { dataTransfer: transfer });
80新增: await dropzone.dispatchEvent("dragleave", { dataTransfer: transfer });
81新增: assert.match(await region.getAttribute("class"), /is-dragging/);
82新增: await expectText(dropzone, "松开以读取配置文件");
83新增: await page.screenshot({ path: path.join(output, "dragging.png"), fullPage: true });
84新增: await editor.dispatchEvent("drop", { dataTransfer: transfer });
85新增: await transfer.dispose();
86新增: await expectText(dropzone, "替换.YML");
87新增: assert.equal(await editor.inputValue(), yaml + "# 拖入\n");
88新增: assert.equal(await name.inputValue(), "我的来源", "replacement preserves the explicit source name");
89新增: assert.doesNotMatch(await region.getAttribute("class"), /is-dragging/);
90新增:
91新增: const preserved = await editor.inputValue();
92新增: for (const [files, message] of [
93新增: [[{ name: "image.png", content: "image" }], ".yaml、.yml 或 .json"],
94新增: [[{ name: "a.yaml", content: yaml }, { name: "b.yml", content: yaml }], "一次只能导入一个"],
95新增: [[{ name: "empty.yaml", content: " " }], "文件内容为空"],
96新增: ]) {
97新增: await drop(files);
98新增: await expectText(region.getByRole("alert"), message);
99新增: assert.equal(await editor.inputValue(), preserved);
100新增: }
101新增: await fileInput.setInputFiles(payload("large.yaml", "x".repeat(8 * 1024 * 1024 + 1)));
102新增: await expectText(region.getByRole("alert"), "文件超过 8 MiB");
103新增: assert.equal(await editor.inputValue(), preserved);
104新增: await page.screenshot({ path: path.join(output, "error.png"), fullPage: true });
105新增: await page.evaluate(() => {
106新增: window.originalFileText = File.prototype.text;
107新增: File.prototype.text = function () { return Promise.reject(new Error("Synthetic read failure")); };
108新增: });
109新增: await drop([{ name: "unreadable.yaml", content: yaml }]);
110新增: await expectText(region.getByRole("alert"), "文件读取失败");
111新增: assert.equal(await editor.inputValue(), preserved);
112新增: await page.evaluate(() => { File.prototype.text = window.originalFileText; });
113新增:
114新增: // A newer file must win even if an earlier asynchronous read completes later.
115新增: await page.evaluate(() => {
116新增: File.prototype.text = function () {
117新增: if (this.name === "slow.yaml") return new Promise((resolve) => { window.finishSlowRead = resolve; });
118新增: return window.originalFileText.call(this);
119新增: };
120新增: });
121新增: await drop([{ name: "slow.yaml", content: yaml }]);
122新增: await expectText(region.getByRole("status"), "正在读取");
123新增: assert.equal(await submit.isDisabled(), true);
124新增: await drop([{ name: "最新.json", content: '{"proxies": []}' }]);
125新增: await expectText(dropzone, "最新.json");
126新增: await page.evaluate(() => window.finishSlowRead("stale content"));
127新增: assert.equal(await editor.inputValue(), '{"proxies": []}');
128新增: await drop([{ name: "slow.yaml", content: yaml }]);
129新增: await expectText(region.getByRole("status"), "正在读取");
130新增: await page.getByRole("button", { name: "订阅链接", exact: true }).click();
131新增: await page.evaluate(() => window.finishSlowRead("stale content"));
132新增: await page.getByRole("button", { name: "本地 YAML", exact: true }).click();
133新增: assert.equal(await editor.inputValue(), "");
134新增: await page.evaluate(() => { File.prototype.text = window.originalFileText; });
135新增:
136新增: const origin = page.url();
137新增: await drop([{ name: "outside.yaml", content: yaml }], page.locator("h4").filter({ hasText: "添加节点来源" }));
138新增: assert.equal(page.url(), origin);
139新增: assert.equal(await editor.inputValue(), "");
140新增: await drop([{ name: "最终配置.yaml", content: yaml }]);
141新增: await expectText(dropzone, "最终配置.yaml");
142新增: await editor.fill(yaml + "# 已编辑\n");
143新增: await page.locator(".proxy-import").evaluate((element) => element.scrollIntoView({ block: "start" }));
144新增: await page.screenshot({ path: path.join(output, "selected.png"), fullPage: true });
145新增: await page.locator(".proxy-import").screenshot({ path: path.join(output, "preview.png") });
146新增:
147新增: // Test the component's narrow layout in the existing settings shell.
148新增: await page.setViewportSize({ width: 375, height: 1000 });
149新增: await dropzone.scrollIntoViewIfNeeded();
150新增: const box = await dropzone.boundingBox();
151新增: assert.ok(box.x >= 0 && box.x + box.width <= 376, "dropzone stays within the narrow viewport");
152新增: await page.screenshot({ path: path.join(output, "narrow.png"), fullPage: true });
153新增: await page.setViewportSize({ width: 1280, height: 1000 });
154新增: await page.emulateMedia({ colorScheme: "dark" });
155新增: await page.waitForFunction(() => document.documentElement.dataset.theme === "dark");
156新增: await page.locator(".proxy-import").evaluate((element) => element.scrollIntoView({ block: "start" }));
157新增: await page.screenshot({ path: path.join(output, "dark.png"), fullPage: true });
158新增: await submit.click();
159新增: await expectText(page.locator(".proxy-notice"), "已导入 1 个节点");
160新增: assert.equal(imports.length, 1);
161新增: assert.equal(imports[0].content, yaml + "# 已编辑\n");
162新增: assert.equal(imports[0].name, "我的来源");
163新增: assert.equal(imports[0].interval_hours, 0);
164新增: await expectText(page.locator(".proxy-source"), "我的来源");
165新增: assert.deepEqual(errors, []);
166新增: const result = { engine, passed: true, imports: imports.length, browserErrors: errors, scope: "Synthetic browser file drops and file chooser; mocked API. Native OS drag and backend validation are outside this check." };
167新增: await fs.writeFile(path.join(output, "result.json"), JSON.stringify(result, null, 2));
168新增: console.log(JSON.stringify(result));
169新增:} finally {
170新增: await browser.close();
171新增:}
新增ui/scripts/readable-errors-smoke.mjs+42 −0看文件
@@ -0,0 +1,42 @@
1新增:import assert from "node:assert/strict";
2新增:import { mkdir, writeFile } from "node:fs/promises";
3新增:import { createWorkbench } from "./workbench-fixture.mjs";
4新增:
5新增:const output = process.env.CAGE_ERROR_QA_OUTPUT || "/tmp/cage-readable-errors";
6新增:await mkdir(output, { recursive: true });
7新增:for (const platform of ["darwin", "windows", "linux"]) {
8新增: const fixture = await createWorkbench({
9新增: clientContext: { mode: "local", connection_id: "local", client_platform: platform, server_platform: platform, connection: { state: "disconnected" } },
10新增: });
11新增: const { page, browser, state, errors } = fixture;
12新增: try {
13新增: state.status.job = { id: "readable-failure", kind: "start", running: false, message: "启动环境失败", error: "下载 Linux 镜像失败:等待下载服务器响应超时。请检查所选节点,再继续安装。", log: "fixture download timeout" };
14新增: await page.reload();
15新增: await page.getByText("启动环境失败", { exact: true }).first().waitFor();
16新增: await page.getByRole("alert").filter({ hasText: "等待下载服务器响应超时" }).first().waitFor();
17新增: await page.getByRole("button", { name: "查看操作详情", exact: true }).first().click();
18新增: await page.getByRole("dialog", { name: "操作详情", exact: true }).getByText("fixture download timeout", { exact: true }).waitFor();
19新增: await page.keyboard.press("Escape");
20新增: await page.screenshot({ path: `${output}/${platform}-startup.png` });
21新增:
22新增: await page.route("**/api/environment/resources", route => route.fulfill({ status: 503, contentType: "text/html", body: "<html>upstream failed token=private-test-secret</html>" }));
23新增: const failure = await page.evaluate(async () => {
24新增: const { api } = await import("/src/api.js");
25新增: try { await api("/environment/resources"); return "unexpected success"; }
26新增: catch (error) { return { message: error.message, status: error.status }; }
27新增: });
28新增: assert.match(failure.message, /资源配置.*HTTP 503.*尚未就绪/);
29新增: assert.equal(failure.status, 503);
30新增: assert.ok(!failure.message.includes("private-test-secret") && !failure.message.includes("<html>"));
31新增: await page.route("**/api/environment/resources", route => route.fulfill({ status: 200, contentType: "application/json", body: "not-json token=private-test-secret" }));
32新增: const malformed = await page.evaluate(async () => {
33新增: const { api } = await import("/src/api.js");
34新增: try { await api("/environment/resources"); } catch (error) { return error.message; }
35新增: });
36新增: assert.match(malformed, /资源配置.*格式无效/);
37新增: assert.ok(!malformed.includes("private-test-secret"));
38新增: assert.deepEqual(errors, []);
39新增: await writeFile(`${output}/${platform}.json`, JSON.stringify({ platform, failure, malformed }, null, 2));
40新增: console.log(`PASS: ${platform} readable failures`);
41新增: } finally { await browser.close(); }
42新增:}
修改ui/scripts/recovery-ui-smoke.mjs+10 −9看文件
@@ -1,10 +1,10 @@
11import assert from "node:assert/strict";
22import fs from "node:fs/promises";
3删除:import { fileURLToPath } from "node:url";
3新增:import { join } from "node:path";
4新增:import { smokeCaptureDirectory } from "./smoke-captures.mjs";
45import { createWorkbench } from "./workbench-fixture.mjs";
56
6删除:const output = new URL("../../docs/test-reports/2026-11-01-system-remediation/", import.meta.url);
7删除:await fs.mkdir(output, { recursive: true });
7新增:const output = await smokeCaptureDirectory("recovery-ui");
88const calls = [];
99let update = { phase: "available", currentVersion: "0.2.0-alpha.1", latestVersion: "0.2.0-alpha.2", message: "发现新版本,可下载更新", retryable: true };
1010const fixture = await createWorkbench({ nativeRequest: async (body) => {
@@ -23,7 +23,7 @@ try {
2323 assert.match(await button.getAttribute("title"), /点击后将自动停止环境、安装并重启/);
2424 const bounds = await button.boundingBox();
2525 assert.ok(bounds.x < 248 && bounds.y > 700, "update action is not in the bottom-left sidebar");
26删除: await page.screenshot({ path: fileURLToPath(new URL("update-available.png", output)) });
26新增: await page.screenshot({ path: join(output, "update-available.png") });
2727 await button.click();
2828 assert.equal(calls.filter((call) => call.operation === "install").length, 1);
2929 await page.getByRole("progressbar", { name: "更新下载进度" }).waitFor();
@@ -55,16 +55,17 @@ try {
5555 await page.route("**/api/environment/update", (route) => { componentUpdates++; return route.fulfill({ json: { id: "qa-components" } }); });
5656 await page.getByRole("button", { name: "启动 Cage 环境", exact: true }).click();
5757 await page.getByRole("heading", { name: "Cage 环境已就绪", exact: true }).waitFor();
58删除: await page.getByText("“report.txt”未能保存:目标目录暂时无法写入", { exact: true }).waitFor();
5958 await page.getByRole("button", { name: "打开浏览器", exact: true }).click();
6059 await page.getByRole("button", { name: "浏览器下载", exact: true }).click();
60新增: await page.getByRole("dialog", { name: "下载文件" }).getByText("目标目录暂时无法写入", { exact: true }).waitFor();
6161 await page.getByRole("button", { name: "重试保存", exact: true }).click();
6262 await page.getByText("已保存到本机", { exact: true }).waitFor();
6363 assert.equal(retries, 1);
64删除: await page.screenshot({ path: fileURLToPath(new URL("download-recovery.png", output)) });
64新增: await page.screenshot({ path: join(output, "download-recovery.png") });
6565 await page.getByRole("dialog", { name: "下载文件" }).getByRole("button", { name: "关闭面板" }).click();
6666 await page.getByRole("button", { name: "打开 默认工作区 的编辑器", exact: true }).click();
67删除: await page.getByRole("button", { name: "恢复编辑器", exact: true }).click();
67新增: await page.getByRole("button", { name: "浏览器菜单", exact: true }).click();
68新增: await page.getByRole("menuitem", { name: "恢复编辑器", exact: true }).click();
6869 await page.getByRole("dialog", { name: "重启编辑器?" }).getByRole("button", { name: "重启编辑器", exact: true }).click();
6970 await page.getByText("编辑器已恢复", { exact: true }).waitFor();
7071 assert.equal(editorRestarts, 1);
@@ -75,7 +76,7 @@ try {
7576 await page.getByRole("region", { name: "环境版本" }).getByText("需要更新", { exact: true }).waitFor();
7677 assert.equal(await page.getByRole("button", { name: "更新环境工具", exact: true }).isDisabled(), true);
7778 await page.getByRole("button", { name: "更新环境工具", exact: true }).scrollIntoViewIfNeeded();
78删除: await page.screenshot({ path: fileURLToPath(new URL("environment-versions.png", output)) });
79新增: await page.screenshot({ path: join(output, "environment-versions.png") });
7980 await page.getByRole("button", { name: "更新环境组件", exact: true }).click();
8081 await page.getByRole("dialog", { name: "更新环境组件?" }).getByRole("button", { name: "更新组件", exact: true }).click();
8182 await page.waitForTimeout(50);
@@ -96,5 +97,5 @@ try {
9697 assert.equal(prematureReady, false, "failed API initialization acknowledged update success");
9798 checks.push("startup failure never acknowledges upgrade");
9899} finally { await broken.browser.close(); }
99删除:await fs.writeFile(new URL("ui-checks.json", output), JSON.stringify({ checks }, null, 2));
100新增:await fs.writeFile(join(output, "ui-checks.json"), JSON.stringify({ checks }, null, 2));
100101console.log(JSON.stringify({ checks }));
修改ui/scripts/remote-input-smoke.mjs+8 −1看文件
@@ -83,7 +83,14 @@ try {
8383 onStatus() {},
8484 onFallback() {},
8585 };
86删除: const install = () => installRemoteInput(rfb, container, options);
86新增: const install = () => installRemoteInput({
87新增: events: rfb,
88新增: setKeyboardTarget: target => rfb.cageSetKeyboardTarget(target),
89新增: sendKey: (...key) => rfb.sendKey(...key),
90新增: focus: () => rfb.focus(),
91新增: pasteText: text => rfb.cagePasteText(text),
92新增: runKeyAction: action => rfb._cageQueueInput(() => action((...key) => rfb._cageSendKey(...key))),
93新增: }, container, options);
8794 window.probe = {
8895 rfb,
8996 packets,
新增ui/scripts/resources-smoke.mjs+66 −0看文件
@@ -0,0 +1,66 @@
1新增:import assert from "node:assert/strict";
2新增:import { createWorkbench } from "./workbench-fixture.mjs";
3新增:
4新增:const { browser, page, errors } = await createWorkbench();
5新增:const windowsRuntime = process.env.CAGE_RESOURCE_RUNTIME === "hyperv";
6新增:let allocation = { automatic: true, memory_gib: 12, cpus: 5 };
7新增:let rejectSave = false;
8新增:const saves = [];
9新增:await page.route("**/api/environment/resources", async (route) => {
10新增: if (route.request().method() === "POST") {
11新增: if (rejectSave) return route.fulfill({ status: 400, contentType: "text/plain; charset=utf-8", body: "资源配置保存失败" });
12新增: const body = route.request().postDataJSON();
13新增: saves.push(body);
14新增: if (body.allocation) allocation = body.allocation.automatic ? { automatic: true, memory_gib: 12, cpus: 5 } : body.allocation;
15新增: return route.fulfill({ json: { ok: true } });
16新增: }
17新增: return route.fulfill({ json: { ...allocation, ...(windowsRuntime ? { runtime: "hyperv", min_memory_gib: 4, min_cpus: 2 } : {}), running: false, recommended_memory_bytes: 12 * 2 ** 30, recommended_cpus: rejectSave ? 6 : 5, max_memory_gib: 12, max_cpus: 5 } });
18新增:});
19新增:async function open() {
20新增: await page.getByRole("button", { name: "设置", exact: true }).click();
21新增: await page.getByRole("navigation", { name: "设置分组" }).getByRole("button", { name: "环境与恢复", exact: true }).click();
22新增: await page.getByLabel("自动分配资源上限").waitFor();
23新增:}
24新增:try {
25新增: await open();
26新增: assert.equal(await page.getByLabel("自动分配资源上限").isChecked(), true);
27新增: await page.getByLabel("自动分配资源上限").uncheck();
28新增: if (windowsRuntime) {
29新增: assert.equal(await page.getByLabel("内存上限(GiB)", { exact: true }).getAttribute("min"), "4");
30新增: assert.equal(await page.getByLabel("CPU 逻辑核心数", { exact: true }).getAttribute("min"), "2");
31新增: await page.getByLabel("内存上限(GiB)", { exact: true }).fill("3");
32新增: await page.getByRole("button", { name: "保存资源配置", exact: true }).click();
33新增: assert.equal(saves.length, 0);
34新增: await page.getByText(/内存与 CPU 用量来自 Windows 客机的系统观测/).waitFor();
35新增: }
36新增: await page.getByLabel("内存上限(GiB)", { exact: true }).fill("4");
37新增: await page.getByLabel("CPU 逻辑核心数", { exact: true }).fill("2");
38新增: await page.screenshot({ path: "/tmp/cage-resource-settings.png", fullPage: true });
39新增: await page.getByRole("button", { name: "保存资源配置", exact: true }).click();
40新增: await page.getByText("已保存,下次启动环境时生效。", { exact: true }).waitFor();
41新增: assert.deepEqual(allocation, { automatic: false, memory_gib: 4, cpus: 2 });
42新增: await page.reload();
43新增: await open();
44新增: assert.equal(await page.getByLabel("内存上限(GiB)", { exact: true }).inputValue(), "4");
45新增: assert.equal(await page.getByLabel("CPU 逻辑核心数", { exact: true }).inputValue(), "2");
46新增: const count = saves.length;
47新增: await page.getByLabel("内存上限(GiB)", { exact: true }).fill("13");
48新增: await page.getByRole("button", { name: "保存资源配置", exact: true }).click();
49新增: assert.equal(saves.length, count);
50新增: await page.getByLabel("内存上限(GiB)", { exact: true }).fill("6");
51新增: rejectSave = true;
52新增: await page.getByRole("button", { name: "保存资源配置", exact: true }).click();
53新增: await page.getByRole("alert").filter({ hasText: "资源配置保存失败" }).waitFor();
54新增: await page.waitForResponse(response => response.url().endsWith("/api/environment/resources") && response.request().method() === "GET" && response.ok());
55新增: await page.getByText("6 个逻辑核心", { exact: true }).waitFor();
56新增: assert.equal(await page.getByRole("alert").filter({ hasText: "资源配置保存失败" }).isVisible(), true);
57新增: assert.equal(await page.getByLabel("内存上限(GiB)", { exact: true }).inputValue(), "6");
58新增: rejectSave = false;
59新增: await page.getByLabel("自动分配资源上限").check();
60新增: await page.getByRole("button", { name: "保存资源配置", exact: true }).click();
61新增: await page.getByText("已保存,下次启动环境时生效。", { exact: true }).waitFor();
62新增: assert.equal(allocation.automatic, true);
63新增: assert.equal(await page.getByRole("alert").filter({ hasText: "资源配置保存失败" }).count(), 0);
64新增: assert.deepEqual(errors, []);
65新增: console.log("Resource settings: manual save, reload, bounds, failure retention, automatic mode passed.");
66新增:} finally { await browser.close(); }
修改ui/scripts/rfb-wire-fixture.mjs+24 −8看文件
@@ -3,12 +3,13 @@ import { createHash } from "node:crypto";
33
44// A bounded RFB display over real browser WebSockets. Playwright's WebSocket
55// replacement lacks the prototype properties checked by the shipped noVNC.
6删除:export async function startDisplay(upstream, { frameInterval = 50 } = {}) {
7删除: const stats = { connections: 0, closed: 0, frames: 0 };
6新增:export async function startDisplay(upstream, { frameInterval = 50, sharedClipboard = false } = {}) {
7新增: const stats = { connections: 0, closed: 0, frames: 0, clipboardConnections: 0, clipboardUpdates: [], keys: [] };
88 const sockets = new Set();
99 const displays = new Set();
1010 const clipboardWriters = new Set();
11删除: let width = 640, height = 480;
11新增: const sharedWriters = new Set(), sharedSockets = new Set();
12新增: let width = 640, height = 480, framesPaused = false;
1213 const server = http.createServer((req, res) => {
1314 if (req.url.startsWith("/api/")) {
1415 res.writeHead(503); res.end("Unmocked fixture request"); return;
@@ -21,7 +22,8 @@ export async function startDisplay(upstream, { frameInterval = 50 } = {}) {
2122 proxy.on("error", () => { res.writeHead(502); res.end(); });
2223 });
2324 server.on("upgrade", (req, socket) => {
24删除: if (!["/api/vnc", "/api/claude-desktop/vnc"].includes(req.url)) { socket.destroy(); return; }
25新增: const shared = sharedClipboard && new URL(req.url,upstream).pathname === "/api/clipboard";
26新增: if (!shared && !["/api/vnc", "/api/claude-desktop/vnc"].includes(new URL(req.url, upstream).pathname)) { socket.destroy(); return; }
2527 sockets.add(socket);
2628 stats.connections++;
2729 const key = createHash("sha1").update(req.headers["sec-websocket-key"] + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").digest("base64");
@@ -36,6 +38,11 @@ export async function startDisplay(upstream, { frameInterval = 50 } = {}) {
3638 if (header.length === 10) header.writeBigUInt64BE(BigInt(length), 2);
3739 socket.write(Buffer.concat([header, payload]));
3840 };
41新增: const sharedWrite = value => send(Buffer.from(JSON.stringify(value)),1);
42新增: if (shared) {
43新增: stats.clipboardConnections++; sharedWriters.add(sharedWrite); sharedSockets.add(socket);
44新增: sharedWrite({ hello: { version: 1, os: "linux", session: "fixture-session", formats: ["text", "png", "files"], available: true } });
45新增: }
3946 const clipboard = (text) => {
4047 const bytes = Buffer.from(text, "latin1"), message = Buffer.alloc(8 + bytes.length);
4148 message[0] = 3;
@@ -77,7 +84,7 @@ export async function startDisplay(upstream, { frameInterval = 50 } = {}) {
7784 displays.add(resize);
7885 clipboardWriters.add(clipboard);
7986 timer = setInterval(() => {
80删除: if (socket.writableLength > frame.length * 2) return;
87新增: if (framesPaused || socket.writableLength > frame.length * 2) return;
8188 frame.fill(stats.frames % 255, 16);
8289 send(frame); stats.frames++;
8390 }, frameInterval);
@@ -97,6 +104,8 @@ export async function startDisplay(upstream, { frameInterval = 50 } = {}) {
97104 }
98105 if (!length) { socket.destroy(); return; }
99106 if (rfb.length < length) return;
107新增: if (type === 5) stats.pointer = { x: rfb.readUInt16BE(2), y: rfb.readUInt16BE(4) };
108新增: if (type === 4) stats.keys.push({ down: Boolean(rfb[1]), symbol: rfb.readUInt32BE(4) });
100109 if (type === 248 && (rfb.readUInt32BE(4) & 0x80000000)) {
101110 const response = Buffer.from(rfb.subarray(0, length));
102111 response.writeUInt32BE(rfb.readUInt32BE(4) & 3, 4);
@@ -120,18 +129,25 @@ export async function startDisplay(upstream, { frameInterval = 50 } = {}) {
120129 wire = wire.subarray(offset + maskBytes + length);
121130 if (opcode === 8) { send(payload, 8); socket.end(); return; }
122131 if (opcode === 9) send(payload, 10);
123删除: if (opcode === 1 || opcode === 2) consume(payload);
132新增: if (shared && opcode === 1) {
133新增: const value = JSON.parse(payload.toString());
134新增: stats.clipboardUpdates.push(value);
135新增: sharedWrite({ ack: value.serial });
136新增: } else if (opcode === 1 || opcode === 2) consume(payload);
124137 }
125138 });
126139 socket.on("error", () => {});
127删除: socket.on("close", () => { clearInterval(timer); displays.delete(resize); clipboardWriters.delete(clipboard); sockets.delete(socket); stats.closed++; });
128删除: send(Buffer.from("RFB 003.008\n"));
140新增: socket.on("close", () => { clearInterval(timer); displays.delete(resize); clipboardWriters.delete(clipboard); sharedWriters.delete(sharedWrite); sharedSockets.delete(socket); sockets.delete(socket); stats.closed++; });
141新增: if (!shared) send(Buffer.from("RFB 003.008\n"));
129142 });
130143 await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
131144 return {
132145 url: `http://127.0.0.1:${server.address().port}`,
133146 stats,
147新增: pauseFrames(paused) { framesPaused = paused; },
134148 clipboard(text) { for (const write of clipboardWriters) write(text); },
149新增: sharedClipboard(value) { for (const write of sharedWriters) write(value); },
150新增: disconnectClipboard() { for (const socket of sharedSockets) socket.destroy(); },
135151 resize(size) { width = size.width; height = size.height; for (const resize of displays) resize(); },
136152 close: async () => {
137153 for (const socket of sockets) socket.destroy();
新增ui/scripts/safety-checklist-smoke.mjs+133 −0看文件
@@ -0,0 +1,133 @@
1新增:import assert from "node:assert/strict";
2新增:import { mkdir } from "node:fs/promises";
3新增:import { createWorkbench } from "./workbench-fixture.mjs";
4新增:
5新增:const failure = "联网检查未通过:浏览器语言未通过。语言与已保存的设置不一致。请核对语言设置后重新检测。外网保持关闭。";
6新增:const output = process.env.CAGE_SAFETY_SCREENSHOTS || "/tmp/cage-safety-checklist";
7新增:await mkdir(output, { recursive: true });
8新增:const platforms = process.env.CAGE_TEST_BROWSER === "webkit" ? ["darwin"] : ["darwin", "windows", "linux"];
9新增:
10新增:for (const platform of platforms) {
11新增: const { browser, page, state, errors } = await createWorkbench({
12新增: clientContext: { mode: "local", connection_id: "local", client_platform: platform, server_platform: platform, connection: { state: "disconnected" } },
13新增: // Session history is unrelated to this check. Resolve its poll immediately
14新增: // so WebKit does not report a cancelled poll when this test reloads pages.
15新增: beforeNavigate: page => page.addInitScript(() => {
16新增: const fetch = window.fetch;
17新增: window.fetch = (input, ...args) => String(input) === "/api/cli/sessions"
18新增: ? Promise.resolve(new Response('{"sessions":[]}', { headers: { "Content-Type": "application/json" } }))
19新增: : fetch(input, ...args);
20新增: }),
21新增: });
22新增: const checklist = page.getByRole("dialog", { name: "网络与隔离检查", exact: true });
23新增: const link = parent => parent.getByRole("button", { name: "查看检查清单", exact: true });
24新增: const showChecklist = async (button, keyboard = false) => {
25新增: if (keyboard) { await button.focus(); await button.press("Enter"); }
26新增: else await button.click();
27新增: await checklist.waitFor();
28新增: assert.equal(await page.getByRole("dialog").evaluateAll(nodes => nodes.at(-1).getAttribute("aria-label")), "网络与隔离检查");
29新增: await checklist.getByRole("heading", { name: "关键检查", exact: true }).waitFor();
30新增: await checklist.getByText("1 / 2 通过", { exact: true }).waitFor();
31新增: const failed = checklist.locator("details").filter({ hasText: "浏览器语言" });
32新增: await failed.locator("summary").click();
33新增: await failed.getByText("语言与已保存的设置不一致", { exact: true }).waitFor();
34新增: await failed.getByText("请核对语言设置后重新检测", { exact: true }).waitFor();
35新增: };
36新增: const closeChecklist = async () => {
37新增: await page.keyboard.press("Escape");
38新增: await checklist.waitFor({ state: "hidden" });
39新增: };
40新增: try {
41新增: Object.assign(state.status, {
42新增: ready: true, vm_running: true,
43新增: job: { id: "failed-check", kind: "safety", running: false, error: failure, message: "环境检查未完成", log: "fixture check log" },
44新增: safety: {
45新增: gate: { mode: "closed", reason: failure }, error: failure,
46新增: report: { created_at: new Date().toISOString(), checks: [
47新增: { id: "dns", title: "加密 DNS", critical: true, state: "passed", evidence: "DNS 通过指定代理" },
48新增: { id: "browser", title: "浏览器语言", critical: true, state: "failed", evidence: "语言与已保存的设置不一致", remedy: "请核对语言设置后重新检测" },
49新增: ] },
50新增: },
51新增: });
52新增: await page.reload();
53新增: const homeError = page.getByRole("alert").filter({ hasText: failure });
54新增: await link(homeError).waitFor();
55新增: await page.screenshot({ path: `${output}/${platform}-failure.png` });
56新增: const postCount = () => state.requests.filter(r => r.method === "POST").length;
57新增: const beforeOpening = postCount();
58新增: await showChecklist(link(homeError), true);
59新增: await page.screenshot({ path: `${output}/${platform}-checklist.png` });
60新增: await closeChecklist();
61新增: assert.equal(postCount(), beforeOpening, "viewing a checklist must not start checks or open networking");
62新增: assert.equal(await link(homeError).evaluate(node => node === document.activeElement), true);
63新增:
64新增: const feedback = page.locator(".status-feedback");
65新增: state.status.job = { ...state.status.job, id: "failed-check-notification" };
66新增: await link(feedback).waitFor();
67新增: await showChecklist(link(feedback));
68新增: await closeChecklist();
69新增:
70新增: await page.getByRole("button", { name: "查看操作详情", exact: true }).click();
71新增: const details = page.getByRole("dialog", { name: "操作详情", exact: true });
72新增: await showChecklist(link(details));
73新增: await closeChecklist();
74新增: assert.equal(await details.isVisible(), true, "closing the checklist must preserve operation details");
75新增: await details.getByRole("button", { name: "关闭面板", exact: true }).click();
76新增:
77新增: state.status.job.setup_progress = { phase: "services", label: "环境服务" };
78新增: await page.reload();
79新增: const setup = page.getByRole("region", { name: "环境安装进度", exact: true });
80新增: await showChecklist(link(setup));
81新增: await closeChecklist();
82新增: delete state.status.job.setup_progress;
83新增: await page.reload();
84新增:
85新增: await page.route("**/api/settings/probe", route => route.fulfill({ status: 409, contentType: "text/plain; charset=utf-8", body: failure }));
86新增: await page.getByRole("button", { name: "设置", exact: true }).click();
87新增: await page.getByRole("navigation", { name: "设置分组" }).getByRole("button", { name: "网络与代理", exact: true }).click();
88新增: const settings = page.getByRole("region", { name: "设置", exact: true });
89新增: const dns = settings.getByLabel("加密 DNS", { exact: true });
90新增: await dns.fill("https://example.com/dns-query");
91新增: await settings.getByRole("button", { name: "验证出口", exact: true }).click();
92新增: const settingsError = settings.getByRole("alert").filter({ hasText: failure });
93新增: await showChecklist(link(settingsError), true);
94新增: await closeChecklist();
95新增: assert.equal(await dns.inputValue(), "https://example.com/dns-query", "viewing checks must preserve unsaved settings");
96新增: assert.equal(await settings.isVisible(), true);
97新增: await dns.fill(state.settings.dns_url);
98新增:
99新增: await page.route("**/api/proxy/route", route => route.fulfill({ status: 409, contentType: "text/plain; charset=utf-8", body: "关键检测证据不完整,外网保持关闭" }));
100新增: await settings.getByRole("button", { name: "重新应用", exact: true }).click();
101新增: const proxyError = settings.getByRole("alert").filter({ hasText: "关键检测证据不完整" });
102新增: await showChecklist(link(proxyError));
103新增: await closeChecklist();
104新增: await settings.getByRole("button", { name: "返回工作台", exact: true }).first().click();
105新增:
106新增: await page.route("**/api/projects/open", route => route.fulfill({ status: 409, contentType: "text/plain; charset=utf-8", body: failure }));
107新增: await page.getByRole("button", { name: "打开项目", exact: true }).click();
108新增: const projects = page.getByRole("dialog", { name: "打开项目", exact: true });
109新增: await projects.getByRole("button", { name: "打开项目", exact: true }).click();
110新增: await showChecklist(link(projects));
111新增: await closeChecklist();
112新增: assert.equal(await projects.isVisible(), true);
113新增: await projects.getByRole("button", { name: "取消", exact: true }).click();
114新增:
115新增: for (const viewport of [{ width: 820, height: 558 }, { width: 560, height: 812 }]) {
116新增: await page.setViewportSize(viewport);
117新增: if (viewport.width === 560) await page.getByRole("button", { name: "收起侧栏", exact: true }).click();
118新增: await showChecklist(link(homeError));
119新增: assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false);
120新增: await closeChecklist();
121新增: await page.screenshot({ path: `${output}/${platform}-${viewport.width}.png` });
122新增: }
123新增:
124新增: state.status.job = { ...state.status.job, id: "unrelated-error", error: "项目文件夹连接失败" };
125新增: await page.reload();
126新增: const unrelated = page.getByRole("alert").filter({ hasText: "项目文件夹连接失败" });
127新增: await unrelated.waitFor();
128新增: assert.equal(await link(unrelated).count(), 0);
129新增: assert.equal(state.status.safety.gate.mode, "closed");
130新增: assert.deepEqual(errors, []);
131新增: console.log(`PASS ${platform}: home, notification, details, setup, settings, proxy, project, keyboard, return focus, compact layout and no mutations`);
132新增: } finally { await browser.close(); }
133新增:}
新增ui/scripts/session-actions-smoke.mjs+141 −0看文件
@@ -0,0 +1,141 @@
1新增:// Both real UIs share one isolated host fixture. No request reaches personal data.
2新增:import assert from "node:assert/strict";
3新增:import { join } from "node:path";
4新增:import { smokeCaptureDirectory } from "./smoke-captures.mjs";
5新增:import { createWorkbench } from "./workbench-fixture.mjs";
6新增:
7新增:const base = process.env.CAGE_UI_URL || "http://127.0.0.1:5178";
8新增:const engine = process.env.CAGE_TEST_BROWSER || "chromium";
9新增:const output = await smokeCaptureDirectory("session-actions-" + engine);
10新增:const desktop = await createWorkbench({url:base});
11新增:const {page, state, browser, errors} = desktop;
12新增:const workspace = state.settings.workspace;
13新增:const id = "12345678-1234-4321-aaaa-123456789abc";
14新增:const sessions = [
15新增: {id, workspace, title:"待处理的会话", revision:1, generation:id, updated_at:"2026-11-07T08:00:00Z", pinned:false},
16新增: {id:"12345678-1234-4321-aaaa-123456789abd", workspace, title:"另一段会话", revision:1, generation:id, updated_at:"2026-11-07T09:00:00Z", pinned:false},
17新增:];
18新增:let failSave = false;
19新增:const update = (target, body) => {
20新增: if (body.title) target.title = target.custom_title = body.title;
21新增: if (body.pinned !== undefined) target.pinned = body.pinned;
22新增: target.metadata_set = true; target.revision++;
23新增: state.terminals = state.terminals.map(t => t.cli_session_id === target.id ? {...t, title:target.title, custom_title:target.custom_title, pinned:target.pinned, metadata_set:true} : t);
24新增: return {...target, turns:[]};
25新增:};
26新增:const remove = target => {
27新增: sessions.splice(sessions.indexOf(target),1);
28新增: state.terminals = state.terminals.filter(t => t.cli_session_id !== target.id);
29新增:};
30新增:try {
31新增: state.status.ready = state.status.vm_running = true;
32新增: await page.evaluate(({workspace,title}) => localStorage.setItem("cage-tab-layout",JSON.stringify({[workspace]:{"terminal:fixture-shared":{title,pinned:false}}})),{workspace,title:sessions[0].title});
33新增: state.terminals = [{id:"fixture-shared", kind:"claude", workspace, title:sessions[0].title, cli_session_id:id, metadata_set:false, pinned:false}];
34新增: await page.route("**/api/terminals/*/metadata", async route => route.fulfill({json:update(sessions[0],route.request().postDataJSON())}));
35新增: await page.route("**/api/terminals/*", async route => {
36新增: if (route.request().method() !== "DELETE") return route.fallback();
37新增: remove(sessions[0]); await route.fulfill({json:{ok:true}});
38新增: });
39新增: await page.route("**/api/cli/sessions/*/archive", async route => {
40新增: const target = sessions.find(s => route.request().url().includes(s.id));
41新增: remove(target); await route.fulfill({json:{ok:true}});
42新增: });
43新增: await page.getByRole("tab",{name:/待处理的会话/}).first().hover();
44新增: await page.getByRole("group",{name:"待处理的会话 的操作"}).waitFor();
45新增: assert.equal(sessions[0].metadata_set,true,"desktop local label was not imported into host metadata");
46新增: const phoneContext = await browser.newContext({viewport:{width:390,height:844},isMobile:true,hasTouch:true,userAgent:"CageMobile/1"});
47新增: const phone = await phoneContext.newPage();
48新增: const phoneErrors = [];
49新增: phone.on("pageerror",error => phoneErrors.push(error.message));
50新增: await phone.route("**/api/**",async route => {
51新增: const path = new URL(route.request().url()).pathname;
52新增: if (path.endsWith("/projects")) return route.fulfill({json:{host:"隔离测试主机",ready:true,shared_sessions:true,projects:[{path:workspace,name:"测试项目"}]}});
53新增: if (path.endsWith("/sessions")) return route.fulfill({json:{sessions,notice:""}});
54新增: const target = sessions.find(s => path.includes(s.id));
55新增: if (!target) return route.fulfill({status:404});
56新增: if (path.endsWith("/account")) return route.fulfill({ json: { session: target, supported: false, candidates: [] } });
57新增: if (path.endsWith("/metadata")) {
58新增: if (failSave) return route.fulfill({status:500,contentType:"text/plain",body:"测试:磁盘暂时不可写"});
59新增: return route.fulfill({json:update(target,route.request().postDataJSON())});
60新增: }
61新增: if (path.endsWith("/archive")) { remove(target); return route.fulfill({json:{ok:true}}); }
62新增: return route.fulfill({json:{...target,turns:[]}});
63新增: });
64新增: await phone.goto(base+"/mobile.html");
65新增: const drawer = phone.getByRole("dialog",{name:"工作区侧栏"});
66新增: await drawer.getByRole("button",{name:"待处理的会话",exact:true}).waitFor();
67新增: await phone.waitForFunction(() => document.querySelector(".workspace-drawer")?.dataset.visible === "true" && document.querySelector(".workspace-drawer").getBoundingClientRect().left >= 0);
68新增: const row = phone.locator(".swipe-session").filter({has:phone.getByRole("button",{name:"待处理的会话",exact:true})});
69新增: const box = await row.boundingBox();
70新增: // A vertical drag must keep the toolbar closed.
71新增: await phone.mouse.move(box.x+30,box.y+20); await phone.mouse.down();
72新增: await phone.mouse.move(box.x+31,box.y+65,{steps:8}); await phone.mouse.up();
73新增: assert.equal(await row.getByRole("group").count(),0);
74新增: // Drag left on the actual row, then ensure it did not navigate into chat.
75新增: if (engine === "chromium") {
76新增: const touch = await phoneContext.newCDPSession(phone);
77新增: await touch.send("Input.dispatchTouchEvent",{type:"touchStart",touchPoints:[{x:box.x+box.width-24,y:box.y+20}]});
78新增: for(let dx=24;dx<=154;dx+=13) await touch.send("Input.dispatchTouchEvent",{type:"touchMove",touchPoints:[{x:box.x+box.width-dx,y:box.y+20}]});
79新增: await touch.send("Input.dispatchTouchEvent",{type:"touchEnd",touchPoints:[]});
80新增: await touch.detach();
81新增: } else {
82新增: await phone.mouse.move(box.x+box.width-40,box.y+20); await phone.mouse.down();
83新增: await phone.mouse.move(box.x+box.width-170,box.y+20,{steps:12}); await phone.mouse.up();
84新增: }
85新增: await row.getByRole("button",{name:"置顶",exact:true}).waitFor();
86新增: await row.locator(".session-slide").evaluate(el => Promise.all(el.getAnimations().map(animation => animation.finished)));
87新增: assert.equal(await phone.getByRole("textbox",{name:"消息"}).count(),0,"swipe opened chat");
88新增: await phone.screenshot({path:join(output,engine+"-swipe.png")});
89新增: await row.getByRole("button",{name:"置顶",exact:true}).click();
90新增: await row.getByRole("button",{name:"取消置顶",exact:true}).waitFor();
91新增: assert.match(await phone.locator(".swipe-session").first().innerText(),/待处理的会话/);
92新增: await page.getByRole("group",{name:"待处理的会话 的操作"}).getByRole("button",{name:"取消置顶",exact:true}).waitFor();
93新增: await row.getByRole("button",{name:"重命名",exact:true}).click();
94新增: let dialog = phone.getByRole("dialog",{name:"重命名会话"});
95新增: await dialog.getByRole("textbox",{name:"会话名称"}).fill("手机改名同步电脑");
96新增: failSave = true;
97新增: await dialog.getByRole("button",{name:"保存名称"}).click();
98新增: await dialog.getByRole("alert").filter({hasText:"磁盘暂时不可写"}).waitFor();
99新增: assert.equal(sessions[0].title,"待处理的会话");
100新增: failSave = false;
101新增: await dialog.getByRole("button",{name:"保存名称"}).click();
102新增: await dialog.waitFor({state:"hidden"});
103新增: const desktopActions = page.getByRole("group",{name:"手机改名同步电脑 的操作"});
104新增: await desktopActions.waitFor();
105新增: await desktopActions.getByRole("button",{name:"重命名",exact:true}).click();
106新增: await page.getByRole("textbox",{name:"标签名称"}).fill("电脑改名同步手机");
107新增: await page.getByRole("button",{name:"保存名称",exact:true}).click();
108新增: await phone.getByRole("button",{name:"电脑改名同步手机",exact:true}).waitFor();
109新增: await phone.reload();
110新增: await drawer.getByRole("button",{name:"电脑改名同步手机",exact:true}).waitFor();
111新增: const currentRow = phone.locator(".swipe-session").filter({has:phone.getByRole("button",{name:"电脑改名同步手机",exact:true})});
112新增: await currentRow.getByRole("button",{name:"电脑改名同步手机",exact:true}).focus();
113新增: await phone.keyboard.press("ArrowLeft");
114新增: await currentRow.getByRole("button",{name:"取消置顶",exact:true}).waitFor();
115新增: await phone.keyboard.press("Escape");
116新增: assert.equal(await currentRow.getByRole("group").count(),0);
117新增: await currentRow.getByRole("button",{name:/更多操作/}).click();
118新增: await currentRow.getByRole("button",{name:"归档",exact:true}).click();
119新增: dialog=phone.getByRole("dialog",{name:"归档会话"});
120新增: await dialog.getByRole("button",{name:"取消",exact:true}).click();
121新增: assert.equal(sessions.length,2);
122新增: await currentRow.getByRole("button",{name:"归档",exact:true}).click();
123新增: await dialog.getByRole("button",{name:"归档会话",exact:true}).click();
124新增: await currentRow.waitFor({state:"hidden"});
125新增: await page.getByRole("group",{name:"电脑改名同步手机 的操作"}).waitFor({state:"hidden"});
126新增: await phone.reload();
127新增: await drawer.getByRole("button",{name:"另一段会话",exact:true}).waitFor();
128新增: assert.equal(await drawer.getByRole("button",{name:"电脑改名同步手机",exact:true}).count(),0);
129新增: // Archiving the selected conversation on the desktop exits the phone chat.
130新增: state.terminals = [{id:"fixture-second",kind:"claude",workspace,title:sessions[0].title,cli_session_id:sessions[0].id,closed:true}];
131新增: await drawer.getByRole("button",{name:"另一段会话",exact:true}).click();
132新增: await phone.getByRole("textbox",{name:"消息"}).waitFor();
133新增: await page.getByRole("tab",{name:"另一段会话",exact:true}).hover();
134新增: await page.getByRole("group",{name:"另一段会话 的操作"}).getByRole("button",{name:"归档",exact:true}).click();
135新增: await page.getByRole("dialog",{name:"归档这段会话?"}).getByRole("button",{name:"归档会话"}).click();
136新增: await drawer.waitFor();
137新增: await drawer.getByText("暂无会话",{exact:true}).waitFor();
138新增: assert.equal(await phone.getByRole("textbox",{name:"消息"}).count(),0);
139新增: assert.deepEqual(errors,[]); assert.deepEqual(phoneErrors,[]);
140新增: console.log(engine+": left swipe, vertical scroll, keyboard, pin, bidirectional rename, failure/retry, archive/cancel, peer archive, label migration, reload passed");
141新增:} finally { await browser.close(); }
新增ui/scripts/session-order-smoke.mjs+84 −0看文件
@@ -0,0 +1,84 @@
1新增:import assert from "node:assert/strict";
2新增:import { mkdir, writeFile } from "node:fs/promises";
3新增:import { createWorkbench } from "./workbench-fixture.mjs";
4新增:
5新增:const engine = process.env.CAGE_TEST_BROWSER || "chromium";
6新增:const output = process.env.CAGE_TEST_CAPTURE || "/tmp/cage-session-order";
7新增:let state, opens = 0;
8新增:const sessions = [
9新增: { id:"order-idle", title:"已打开的空闲会话", updated_at:"2026-11-07T10:00:00Z" },
10新增: { id:"order-active", title:"正在执行的会话", active:true, updated_at:"2026-11-07T09:00:00Z" },
11新增: { id:"order-saved", title:"保存的会话", updated_at:"2026-11-07T08:00:00Z" },
12新增:];
13新增:const fixture = await createWorkbench({ url: process.env.CAGE_UI_URL || "http://127.0.0.1:5217",
14新增: cliRequest: async (route, path) => {
15新增: if (path === "/cli/sessions") return route.fulfill({json:{sessions}});
16新增: const session = sessions.find(s => path.includes(s.id));
17新增: if (path.endsWith("/open")) {
18新增: opens++;
19新增: const terminal = {id:"opened-history", workspace:state.settings.workspace, title:session.title, cli_session_id:session.id};
20新增: state.terminals.push(terminal);
21新增: return route.fulfill({json:{...session,desktop_terminal_id:terminal.id}});
22新增: }
23新增: return route.fulfill({json:session});
24新增: },
25新增:});
26新增:state = fixture.state;
27新增:const {page,browser,errors} = fixture;
28新增:try {
29新增: sessions.forEach(session => {session.workspace = state.settings.workspace;});
30新增: state.status.ready = state.status.vm_running = true;
31新增: state.terminals = [{id:"idle", workspace:state.settings.workspace, title:sessions[0].title, cli_session_id:sessions[0].id}];
32新增: const project = page.getByRole("region",{name:"项目 默认工作区",exact:true});
33新增: const order = () => project.locator(".sidebar-tab").evaluateAll(rows => rows.map(row => row.querySelector(":scope > button").textContent));
34新增: const saved = project.getByRole("button",{name:"保存的会话",exact:true});
35新增: await saved.waitFor();
36新增: assert.deepEqual(await order(),[sessions[1].title,sessions[0].title,sessions[2].title]);
37新增: await project.getByRole("img",{name:"会话正在运行"}).waitFor();
38新增: await mkdir(output,{recursive:true});
39新增: await page.screenshot({path:`${output}/${engine}-active.png`});
40新增: const phoneContext = await browser.newContext({viewport:{width:390,height:844},isMobile:true,hasTouch:true,userAgent:"CageMobile/1"});
41新增: const phone = await phoneContext.newPage();
42新增: await phone.route("**/api/**", async route => {
43新增: const pathname = new URL(route.request().url()).pathname;
44新增: return route.fulfill({json:pathname.endsWith("/projects")
45新增: ? {host:"隔离测试",ready:true,shared_sessions:true,projects:[{path:state.settings.workspace,name:"默认工作区"}]}
46新增: : {sessions}});
47新增: });
48新增: await phone.goto((process.env.CAGE_UI_URL || "http://127.0.0.1:5217")+"/mobile.html");
49新增: const drawer = phone.getByRole("dialog",{name:"工作区侧栏"});
50新增: await drawer.getByRole("img",{name:"会话正在运行"}).waitFor();
51新增: assert.equal(await drawer.locator(".session-select").first().getAttribute("aria-label"),sessions[1].title);
52新增: await phoneContext.close();
53新增: const target = project.getByRole("button",{name:sessions[1].title,exact:true});
54新增: const from = await saved.boundingBox(), to = await target.boundingBox();
55新增: await page.mouse.move(from.x+35,from.y+from.height/2); await page.mouse.down();
56新增: await page.mouse.move(to.x+35,to.y+to.height/2,{steps:12}); await page.mouse.up();
57新增: assert.equal(opens,0,"drag opened a conversation");
58新增: assert.deepEqual(await order(),[sessions[2].title,sessions[1].title,sessions[0].title]);
59新增: await saved.click();
60新增: await project.getByRole("tab",{name:sessions[2].title,exact:true}).waitFor();
61新增: assert.deepEqual(await order(),[sessions[2].title,sessions[1].title,sessions[0].title],"opening changed order");
62新增: await project.getByRole("tab",{name:sessions[0].title,exact:true}).click();
63新增: assert.deepEqual(await order(),[sessions[2].title,sessions[1].title,sessions[0].title],"click changed order");
64新增: sessions[1].active = false;
65新增: await page.evaluate(() => window.dispatchEvent(new Event("cage-cli-sessions-changed")));
66新增: await project.getByRole("img",{name:"会话正在运行"}).waitFor({state:"hidden"});
67新增: assert.deepEqual(await order(),[sessions[2].title,sessions[1].title,sessions[0].title],"activity changed manual order");
68新增: await page.reload();
69新增: await project.getByRole("tab",{name:sessions[2].title,exact:true}).waitFor();
70新增: assert.deepEqual(await order(),[sessions[2].title,sessions[1].title,sessions[0].title],"reload lost manual order");
71新增: const selected = project.getByRole("tab",{name:sessions[2].title,exact:true});
72新增: await selected.focus(); await selected.press("Alt+ArrowDown");
73新增: assert.deepEqual(await order(),[sessions[1].title,sessions[2].title,sessions[0].title],"keyboard reorder failed");
74新增: const before = await order();
75新增: const a = await selected.boundingBox(), b = await project.getByRole("tab",{name:sessions[0].title,exact:true}).boundingBox();
76新增: await page.mouse.move(a.x+30,a.y+15); await page.mouse.down();
77新增: await page.mouse.move(b.x+30,b.y+15,{steps:8}); await page.keyboard.press("Escape"); await page.mouse.up();
78新增: assert.deepEqual(await order(),before,"Escape committed a drag");
79新增: assert.deepEqual(errors,[]);
80新增: await mkdir(output,{recursive:true});
81新增: await page.screenshot({path:`${output}/${engine}.png`});
82新增: await writeFile(`${output}/${engine}.json`,JSON.stringify({order:await order(),opens,errors}));
83新增: console.log(`${engine}: active priority/spinner, mixed live/history drag, no click reorder, manual priority, reload, keyboard and cancellation passed`);
84新增:} finally {await browser.close();}
修改ui/scripts/setup-progress-smoke.mjs+42 −0看文件
@@ -52,3 +52,45 @@ try {
5252 assert.deepEqual(errors, []);
5353 console.log("PASS: measured bytes and percent, unknown size, phase only, details, compact layout, cancel and retry.");
5454} finally { await browser.close(); }
55新增:
56新增:{
57新增: const {browser,page,state,errors} = await createWorkbench();
58新增: try {
59新增: state.status.job = {id:"mac-install",kind:"guest-install",running:true,message:"正在安装所选客户机系统…",setup_progress:{system:"macos",operation:"download",phase:"image",label:"正在下载 macOS 系统镜像",received:8*1024**3,total:20*1024**3,bytes_per_second:26*1024**2}};
60新增: const panel = page.getByRole("region",{name:"环境安装进度"});
61新增: const bar = panel.getByRole("progressbar");
62新增: await panel.getByText("8 GiB / 20 GiB",{exact:true}).waitFor();
63新增: await panel.getByText("· 26 MiB/s",{exact:true}).waitFor();
64新增: assert.equal(await bar.getAttribute("aria-valuenow"),"40");
65新增: if (process.env.CAGE_SETUP_NATIVE_SCREENSHOT) await page.screenshot({path:process.env.CAGE_SETUP_NATIVE_SCREENSHOT,animations:"disabled"});
66新增: await page.reload();
67新增: await panel.getByText("8 GiB / 20 GiB",{exact:true}).waitFor();
68新增: assert.equal(await bar.getAttribute("aria-valuenow"),"40");
69新增: state.status.job.setup_progress = {...state.status.job.setup_progress,operation:"verify",label:"正在校验 macOS 系统镜像",received:0};
70新增: await panel.getByRole("heading",{name:"正在校验 macOS 系统镜像"}).waitFor();
71新增: assert.equal(await bar.getAttribute("aria-valuenow"),"0");
72新增: assert.equal(await panel.getByText(/MiB\/s/).count(),0);
73新增: state.status.job.setup_progress = {system:"macos",phase:"packages",label:"正在安装 macOS 系统"};
74新增: await panel.getByRole("heading",{name:"正在安装 macOS 系统"}).waitFor();
75新增: assert.equal(await panel.locator('[aria-current="step"]').textContent(),"系统安装");
76新增: assert.equal(await bar.getAttribute("aria-valuenow"),null);
77新增: await page.setViewportSize({width:375,height:812});
78新增: await page.getByRole("button",{name:"收起侧栏",exact:true}).click();
79新增: assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth),false);
80新增: if (process.env.CAGE_SETUP_MOBILE_SCREENSHOT) await page.screenshot({path:process.env.CAGE_SETUP_MOBILE_SCREENSHOT,animations:"disabled"});
81新增: state.status.job = {...state.status.job,running:false,error:"安装中断,原文件和磁盘已保留"};
82新增: await panel.getByRole("alert").waitFor();
83新增: let submitted;
84新增: await page.route("**/api/start",route=>{
85新增: submitted = route.request().postDataJSON();
86新增: state.status.job = {...state.status.job,running:true,error:""};
87新增: return route.fulfill({json:state.status.job});
88新增: });
89新增: const response = page.waitForResponse("**/api/start");
90新增: await panel.getByRole("button",{name:"继续安装"}).click();
91新增: await response;
92新增: assert.equal(submitted.guest_system,"macos");
93新增: assert.deepEqual(errors,[]);
94新增: console.log("PASS: native image bytes, percent, measured rate, refresh, separate verification, install stage, 375px layout and native retry.");
95新增: } finally {await browser.close();}
96新增:}
新增ui/scripts/shared-cli-live-smoke.mjs+146 −0看文件
@@ -0,0 +1,146 @@
1新增:import process from "node:process";
2新增:import assert from "node:assert/strict";
3新增:import {mkdir, readFile} from "node:fs/promises";
4新增:import path from "node:path";
5新增:
6新增:const parts = [];
7新增:for await (const chunk of process.stdin) parts.push(chunk);
8新增:const entry = Buffer.concat(parts).toString("utf8").trim();
9新增:const engine = process.env.CAGE_TEST_CHANNEL_BROWSER;
10新增:const playwright = await import(process.env.CAGE_PLAYWRIGHT_MODULE || "playwright");
11新增:const browser = await playwright[engine].launch({headless:true});
12新增:let page;
13新增:const snapshots = [];
14新增:try {
15新增: page = await browser.newPage({viewport:{width:390,height:844},isMobile:true,hasTouch:true});
16新增: await page.addInitScript(() => {
17新增: window.fixtureInputEvents = [];
18新增: for (const kind of ["input","change"]) document.addEventListener(kind,event=>{
19新增: if (event.target.tagName === "TEXTAREA") window.fixtureInputEvents.push({kind,value:event.target.value});
20新增: },true);
21新增: });
22新增: page.on("response", async response => {
23新增: if (!/\/api\/mobile\/cli\/sessions\/[^/]+(\/open)?(?:\?|$)/.test(response.url())) return;
24新增: try {
25新增: const value = await response.json();
26新增: snapshots.push({path:new URL(response.url()).pathname,status:response.status(),id:value.id,revision:value.revision,can_send:value.can_send,terminal_available:value.terminal_available,connection_notice:value.connection_notice});
27新增: } catch { /* Incremental reads may have no response body. */ }
28新增: });
29新增: page.setDefaultTimeout(25000);
30新增: let sentRequests = 0, interruptedReads = 0;
31新增: let persistentReadFailure = false, persistentReadAttempts = 0;
32新增: const recovering = process.env.CAGE_TEST_SESSION_RECOVERY === "1";
33新增: if (recovering) {
34新增: await page.route("**/api/mobile/cli/sessions/*/messages", async route => {
35新增: sentRequests++;
36新增: if (sentRequests === 1) {
37新增: await route.fetch();
38新增: // The guest accepted the message, but its HTTP receipt is lost.
39新增: await route.fulfill({status:503,contentType:"text/plain",body:"电脑暂时无法连接运行环境,聊天记录已保留。"});
40新增: } else await route.continue();
41新增: });
42新增: await page.route(/\/api\/mobile\/cli\/sessions\/[^/?]+(?:\?.*)?$/, async route => {
43新增: if (route.request().method() === "GET" && persistentReadFailure) {
44新增: persistentReadAttempts++;
45新增: await route.fulfill({status:503,contentType:"text/plain",body:"电脑暂时无法连接运行环境,聊天记录已保留。"});
46新增: } else if (route.request().method() === "GET" && sentRequests && interruptedReads++ < 2) {
47新增: await route.fulfill({status:503,contentType:"text/plain",body:"电脑暂时无法连接运行环境,聊天记录已保留。"});
48新增: } else await route.continue();
49新增: });
50新增: }
51新增: await page.goto(entry);
52新增: await page.getByRole("dialog",{name:"工作区侧栏"}).getByRole("button",{name:/ 新建会话$/}).first().click();
53新增: await page.getByRole("dialog",{name:"工作区侧栏"}).waitFor({state:"hidden"});
54新增: const message = page.getByRole("textbox",{name:"消息"});
55新增: await message.fill("initial mobile prompt");
56新增: await page.getByRole("button",{name:"发送",exact:true}).click();
57新增: const approve = page.getByRole("button",{name:"允许一次"});
58新增: await approve.waitFor();
59新增: if (recovering) {
60新增: assert.equal(sentRequests,1,"a lost receipt replayed an accepted message");
61新增: assert.ok(interruptedReads >= 2);
62新增: assert.equal(await page.getByText(/尚未收到主机确认|同一编号|已自动重连5次/).count(),0);
63新增: assert.equal(await page.getByRole("alert").count(),0,"a recovered interruption left a failure card");
64新增: }
65新增: assert.equal(await page.getByRole("button",{name:"在电脑打开会话",exact:true}).count(),0);
66新增: assert.equal(await page.getByRole("alert").count(),0,"normal startup displayed an extra notice");
67新增: assert.match(await page.getByLabel("工具参数预览").innerText(), /mobile-approved\.txt/);
68新增: await assert.rejects(readFile(process.env.CAGE_TEST_MOBILE_MARKER),{code:"ENOENT"});
69新增: await page.reload();
70新增: await approve.waitFor();
71新增: const capture = process.env.CAGE_TEST_MOBILE_CAPTURE;
72新增: if (capture) {
73新增: await mkdir(capture,{recursive:true});
74新增: await page.screenshot({path:path.join(capture,engine+"-shared-approval.png")});
75新增: }
76新增: await approve.click();
77新增: await page.getByText("isolated tool completed",{exact:true}).waitFor();
78新增: await page.getByText("follow-up",{exact:true}).waitFor();
79新增: await page.getByText("isolated continuation",{exact:true}).waitFor();
80新增: assert.equal(await readFile(process.env.CAGE_TEST_MOBILE_MARKER,"utf8"),"approved");
81新增: await page.reload();
82新增: await page.getByText("isolated continuation",{exact:true}).waitFor();
83新增: assert.equal(await page.getByLabel("会话消息").getByText("initial mobile prompt",{exact:true}).count(),1);
84新增: if (capture) await page.screenshot({path:path.join(capture,engine+"-shared-history.png")});
85新增: const title = await page.locator(".chat-header h1").innerText();
86新增: // Prepare an ended history through the real archive/restore API. The user
87新增: // then opens it from the actual phone list, with no desktop helper.
88新增: await page.evaluate(async () => {
89新增: const selected = history.state.cageCLI;
90新增: const root = "/api/mobile/cli/sessions/" + selected.session;
91新增: for (const operation of ["archive", "restore"]) {
92新增: const result = await fetch(root+"/"+operation,{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"});
93新增: if (!result.ok) throw Error("history setup failed: "+result.status);
94新增: }
95新增: history.replaceState({...history.state,cageCLI:{tool:"code",project:selected.project,session:""}},"");
96新增: });
97新增: await page.reload();
98新增: await page.getByRole("button",{name:"展开侧栏",exact:true}).click();
99新增: await page.getByRole("dialog",{name:"工作区侧栏"}).getByRole("button",{name:title,exact:true}).click();
100新增: await page.getByRole("dialog",{name:"工作区侧栏"}).waitFor({state:"hidden"});
101新增: await message.fill("after reopen");
102新增: await page.getByRole("button",{name:"发送",exact:true}).click();
103新增: await page.getByLabel("会话消息").getByText("after reopen",{exact:true}).waitFor();
104新增: await page.waitForFunction(() => document.querySelectorAll('.message:not(.user)').length === 3 &&
105新增: document.querySelectorAll('.message:not(.user)')[2].textContent.includes("isolated continuation"));
106新增: assert.equal(await page.getByRole("alert").count(),0,"history restore displayed an extra notice");
107新增: if (capture) await page.screenshot({path:path.join(capture,engine+"-seamless-resume.png")});
108新增: await page.getByRole("button",{name:"展开侧栏",exact:true}).click();
109新增: await page.getByRole("dialog",{name:"工作区侧栏"}).getByRole("button",{name:/ 新建会话$/}).first().click();
110新增: await page.getByRole("dialog",{name:"工作区侧栏"}).waitFor({state:"hidden"});
111新增: await message.fill("draft for second");
112新增: const secondTitle = await page.locator(".chat-header h1").innerText();
113新增: const select = async name => {
114新增: await page.getByRole("button",{name:"展开侧栏",exact:true}).click();
115新增: await page.getByRole("dialog",{name:"工作区侧栏"}).getByRole("button",{name,exact:true}).click();
116新增: await page.getByRole("dialog",{name:"工作区侧栏"}).waitFor({state:"hidden"});
117新增: };
118新增: await select(title);
119新增: assert.equal(await message.inputValue(),"");
120新增: await message.fill("draft for first");
121新增: await select(secondTitle);
122新增: assert.equal(await message.inputValue(),"draft for second");
123新增: await select(title);
124新增: assert.equal(await message.inputValue(),"draft for first");
125新增: assert.equal(await page.getByRole("alert").count(),0,"session switching displayed an extra notice");
126新增: if (recovering) {
127新增: persistentReadFailure = true;
128新增: await page.getByRole("alert").filter({hasText:"已自动重连5次"}).waitFor({timeout:40000});
129新增: assert.equal(persistentReadAttempts,6,"initial failure must be followed by five retries");
130新增: assert.equal(await message.inputValue(),"draft for first");
131新增: if (capture) await page.screenshot({path:path.join(capture,engine+"-reconnect-exhausted.png")});
132新增: persistentReadFailure = false;
133新增: await page.getByRole("button",{name:"再次连接",exact:true}).click();
134新增: await page.getByRole("alert").waitFor({state:"hidden"});
135新增: assert.equal(await message.inputValue(),"draft for first");
136新增: assert.equal(sentRequests,2,"reconnection replayed a user message");
137新增: }
138新增:} catch (error) {
139新增: console.error(JSON.stringify(snapshots.slice(-12)));
140新增: console.error(await page?.locator("body").innerText());
141新增: console.error(await page?.getByRole("textbox",{name:"消息"}).evaluate(el=>({value:el.value,disabled:el.disabled})));
142新增: console.error(await page?.evaluate(()=>window.fixtureInputEvents));
143新增: throw Error(String(error).replace(/(link-bootstrap)#[A-Za-z0-9_-]+/g,"$1#[redacted]"));
144新增:} finally {
145新增: await browser.close();
146新增:}
新增ui/scripts/shared-clipboard-smoke.mjs+62 −0看文件
@@ -0,0 +1,62 @@
1新增:// Production workbench and RFB input with an isolated recording native bridge.
2新增:// The user's OS clipboard, profile and Claude conversations are never accessed.
3新增:import assert from "node:assert/strict";
4新增:import { createWorkbench } from "./workbench-fixture.mjs";
5新增:import { startDisplay } from "./rfb-wire-fixture.mjs";
6新增:
7新增:const display = await startDisplay(process.env.CAGE_UI_URL || "http://127.0.0.1:5198", { sharedClipboard: true });
8新增:let revision = 1, clipboard = { text: "initial host text" };
9新增:const writes = [];
10新增:const { browser, page, state, errors } = await createWorkbench({
11新增: mockWebSockets: false, url: display.url,
12新增: nativeRequest: request => {
13新增: if (request.action === "clipboardRevision") return revision;
14新增: if (request.action === "clipboardSyncRead") return { ...clipboard, revision };
15新增: if (request.action === "clipboardSyncWrite") {
16新增: if (request.revision !== revision) return { revision, superseded: true };
17新增: clipboard = Object.fromEntries(Object.entries(request).filter(([key]) => ["text","png","files"].includes(key)));
18新增: writes.push(clipboard); return { revision: ++revision };
19新增: }
20新增: return true;
21新增: },
22新增:});
23新增:const waitFor = async predicate => { for (let attempt = 0; attempt < 100; attempt++) { if (predicate()) return; await page.waitForTimeout(30); } assert.ok(predicate(),"clipboard state did not arrive"); };
24新增:try {
25新增: await page.route("**/api/claude-desktop", route => route.fulfill({ json: { installed: true, running: true, failed: false, managed: true, version: "fixture" } }));
26新增: state.status.ready = state.status.vm_running = true;
27新增: await page.reload();
28新增: await page.getByRole("button",{ name:"Claude Desktop", exact:true }).click();
29新增: await page.getByText("正在连接画面",{ exact:true }).waitFor({ state:"hidden" });
30新增: await page.waitForFunction(() => window.cageSharedClipboardActive === true);
31新增: assert.equal(display.stats.clipboardUpdates.at(-1).text,"initial host text");
32新增:
33新增: for (const content of [{ text:"Claude 消息🙂\n保留换行" },{ png:"fixture-png" },{ files:"10000000-2222-4333-8444-123456789abc" }]) {
34新增: display.sharedClipboard(content);
35新增: await waitFor(() => JSON.stringify(writes.at(-1)) === JSON.stringify(content));
36新增: const count = display.stats.clipboardUpdates.length;
37新增: await page.waitForTimeout(350);
38新增: assert.equal(display.stats.clipboardUpdates.length,count,"native writes must not echo");
39新增: }
40新增:
41新增: clipboard = { text:"new host copy" }; revision++;
42新增: await page.locator(".remote-canvas canvas").click({ position:{ x:40,y:40 } });
43新增: display.stats.keys.length = 0;
44新增: await page.keyboard.press("Meta+v");
45新增: await waitFor(() => display.stats.keys.some(key => key.down && key.symbol === 118));
46新增: assert.equal(display.stats.clipboardUpdates.at(-1).text,"new host copy");
47新增: assert.equal(state.requests.some(request => request.path === "/input/image"),false,"synchronized paste uses the actual guest clipboard");
48新增:
49新增: await page.getByRole("button",{ name:"工作台", exact:true }).click();
50新增: await page.getByRole("region",{ name:"Claude Desktop", exact:true }).waitFor({ state:"hidden" });
51新增: display.sharedClipboard({ text:"guest background copy" });
52新增: await waitFor(() => clipboard.text === "guest background copy");
53新增: assert.equal(display.stats.clipboardConnections,1,"hiding a canvas retains the shared clipboard");
54新增:
55新增: const connections = display.stats.clipboardConnections;
56新增: display.disconnectClipboard();
57新增: clipboard = { text:"copy during disconnection" }; revision++;
58新增: await waitFor(() => display.stats.clipboardConnections > connections && display.stats.clipboardUpdates.at(-1).text === "copy during disconnection");
59新增: await page.waitForFunction(() => window.cageSharedClipboardActive === true);
60新增: assert.deepEqual(errors,[]);
61新增: console.log("PASS: Desktop text/image/files copy, no echo, native paste, background sharing, disconnect and fresh host snapshot on reconnect.");
62新增:} finally { await browser.close(); await display.close(); }
新增ui/scripts/sidebar-session-error-smoke.mjs+100 −0看文件
@@ -0,0 +1,100 @@
1新增:import assert from "node:assert/strict";
2新增:import { mkdir, writeFile } from "node:fs/promises";
3新增:import { createWorkbench } from "./workbench-fixture.mjs";
4新增:
5新增:const output = process.env.CAGE_TEST_CAPTURE || "/tmp/cage-sidebar-session-error";
6新增:await mkdir(output, { recursive: true });
7新增:const original = "Windows Claude Code 尚未就绪,请检查原生组件、图形登录和官方账号登录";
8新增:const current = "未能连接 Windows 会话服务,请确认 Windows 环境已启动;持续失败时在设置中导出诊断包";
9新增:const longError = (current + "。").repeat(4);
10新增:const evidence = [];
11新增:for (const [platform, guestSystem] of [["windows", "windows-11"], ["darwin", "macos"], ["linux", "debian-13"]]) {
12新增: let message = original, httpFailure = false, pending = false, release, requests = 0;
13新增: const fixture = await createWorkbench({
14新增: url: process.env.CAGE_UI_URL || "http://127.0.0.1:5217",
15新增: clientContext: { mode: "local", connection_id: "local", client_platform: platform, server_platform: platform, connection: { state: "disconnected" } },
16新增: beforeNavigate: async (_page, state) => {
17新增: state.account.guest_system = state.status.guest_system = guestSystem;
18新增: state.status.ready = state.status.vm_running = true;
19新增: },
20新增: cliRequest: async route => {
21新增: requests++;
22新增: if (pending) await new Promise(resolve => { release = resolve; });
23新增: if (httpFailure) return route.fulfill({ status: 503, contentType: "text/plain; charset=utf-8", body: message });
24新增: return route.fulfill({ json: { sessions: [{ id: "error-history", title: "保留的历史会话", workspace: "/Users/shihao/.claude-cage-workspace" }], notice: message } });
25新增: },
26新增: });
27新增: const { page, browser, errors } = fixture;
28新增: try {
29新增: const card = page.locator(".sidebar-session-error");
30新增: const alert = card.getByRole("alert");
31新增: await alert.getByText(original, { exact: true }).waitFor();
32新增: const retry = card.getByRole("button", { name: "重新读取会话", exact: true });
33新增: await page.getByRole("button", { name: "保留的历史会话", exact: true }).waitFor();
34新增: await retry.waitFor();
35新增: await page.locator(".sidebar-scroll").screenshot({ path: `${output}/${platform}-legacy-message.png` });
36新增:
37新增: for (const [theme, sidebarWidth, fontSize, error] of [["light", 248, 14, current], ["dark", 220, 14, longError], ["light", 248, 28, current]]) {
38新增: message = error;
39新增: await page.emulateMedia({ colorScheme: theme });
40新增: await page.evaluate(({sidebarWidth, fontSize}) => {
41新增: document.documentElement.style.setProperty("--sidebar-width", `${sidebarWidth}px`);
42新增: document.documentElement.style.setProperty("font-size", `${fontSize}px`);
43新增: }, {sidebarWidth, fontSize});
44新增: await retry.click();
45新增: await alert.getByText(error, { exact: true }).waitFor();
46新增: await page.waitForFunction(() => document.querySelector(".sidebar-session-error > button")?.disabled === false);
47新增: const layout = await card.evaluate(element => {
48新增: const box = node => { const r = node.getBoundingClientRect(); return { top:r.top, bottom:r.bottom, left:r.left, right:r.right }; };
49新增: const button = element.querySelector("button"), paragraph = element.querySelector("p");
50新增: return { card:box(element), paragraph:box(paragraph), button:box(button),
51新增: project:box(element.nextElementSibling), width:element.clientWidth, scrollWidth:element.scrollWidth,
52新增: buttonHeight:button.clientHeight, buttonScrollHeight:button.scrollHeight,
53新增: text:paragraph.textContent };
54新增: });
55新增: assert.ok(layout.button.top >= layout.paragraph.bottom + 8, "retry overlaps the explanation");
56新增: assert.ok(layout.project.top >= layout.card.bottom, "error covers project controls");
57新增: assert.ok(layout.scrollWidth <= layout.width + 1, "error overflows narrow sidebar");
58新增: assert.ok(layout.buttonScrollHeight <= layout.buttonHeight + 1, "retry label is clipped");
59新增: assert.equal(layout.text, error, "long error was truncated");
60新增: // A large-font card can be taller than the scroll viewport. Increase only
61新增: // the capture height so the artifact contains the entire card.
62新增: if (fontSize === 28) await page.setViewportSize({ width:1280, height:1400 });
63新增: await card.screenshot({ path: `${output}/${platform}-${theme}-${fontSize}.png` });
64新增: if (fontSize === 14 && theme === "light") await page.locator(".sidebar-scroll").screenshot({ path: `${output}/${platform}-after.png` });
65新增: if (fontSize === 28) await page.setViewportSize({ width:1280, height:850 });
66新增: evidence.push({ platform, theme, sidebarWidth, fontSize, layout });
67新增: }
68新增:
69新增: await page.evaluate(() => document.documentElement.style.setProperty("font-size", "14px"));
70新增: message = "会话服务连接中断,请重试";
71新增: httpFailure = true;
72新增: await retry.click();
73新增: await alert.getByText(message, { exact: true }).waitFor();
74新增: await page.waitForFunction(() => document.querySelector(".sidebar-session-error > button")?.disabled === false);
75新增: assert.equal(await page.getByRole("button", { name: "保留的历史会话", exact: true }).count(), 1, "HTTP failure discarded saved history");
76新增:
77新增: pending = true;
78新增: await retry.focus();
79新增: await page.keyboard.press("Enter");
80新增: await card.getByRole("button", { name: "正在读取…", exact: true }).waitFor();
81新增: assert.equal(await card.getByRole("button").isDisabled(), true);
82新增: assert.equal(await card.getByRole("button").getAttribute("aria-busy"), "true");
83新增: await alert.getByText(message, { exact: true }).waitFor();
84新增: const inFlight = requests;
85新增: await page.keyboard.press("Enter");
86新增: assert.equal(requests, inFlight, "keyboard submitted a duplicate retry");
87新增: await card.screenshot({ path: `${output}/${platform}-retry.png` });
88新增: httpFailure = pending = false;
89新增: message = "";
90新增: release();
91新增: await card.waitFor({ state: "hidden" });
92新增: await page.getByRole("button", { name: "保留的历史会话", exact: true }).waitFor();
93新增: await page.reload();
94新增: await page.getByRole("button", { name: "保留的历史会话", exact: true }).waitFor();
95新增: assert.equal(await card.count(), 0, "successful reload restored a stale error");
96新增: assert.deepEqual(errors, []);
97新增: console.log(`${platform}: notice/HTTP failure, long text, narrow sidebar, dark theme, 200% text, keyboard retry and recovery passed`);
98新增: } finally { release?.(); await browser.close(); }
99新增:}
100新增:await writeFile(`${output}/result.json`, JSON.stringify(evidence, null, 2));
新增ui/scripts/sidebar-session-layout-smoke.mjs+81 −0看文件
@@ -0,0 +1,81 @@
1新增:import assert from "node:assert/strict";
2新增:import { mkdir, writeFile } from "node:fs/promises";
3新增:import { createWorkbench } from "./workbench-fixture.mjs";
4新增:
5新增:const output = process.env.CAGE_TEST_CAPTURE || "/tmp/cage-sidebar-session-layout";
6新增:const engine = process.env.CAGE_TEST_BROWSER || "chromium";
7新增:const { page, state, browser, errors } = await createWorkbench({
8新增: url: process.env.CAGE_UI_URL || "http://127.0.0.1:5217",
9新增:});
10新增:const workspace = state.settings.workspace;
11新增:const titles = ["你好", "软件宣传视频制作", "这是一段用于检查窄侧栏省略显示的很长很长的会话标题"];
12新增:const sessions = titles.map((title, index) => ({
13新增: id: `layout-session-${index}`, workspace, title, pinned: index === 2,
14新增: updated_at: "2026-11-07T08:00:00Z",
15新增:}));
16新增:const evidence = [];
17新增:try {
18新增: await page.route("**/api/cli/sessions", route => route.fulfill({ json: { sessions } }));
19新增: state.status.ready = state.status.vm_running = true;
20新增: state.terminals = [{ id: "layout-live", workspace, title: "已打开的会话" }];
21新增: const project = page.getByRole("region", { name: "项目 默认工作区", exact: true });
22新增: const history = project.locator(".sidebar-session");
23新增: await history.last().waitFor();
24新增: await project.getByRole("tab", { name: "已打开的会话", exact: true }).waitFor();
25新增: await mkdir(output, { recursive: true });
26新增: for (const width of [1280, 820]) {
27新增: await page.setViewportSize({ width, height: 850 });
28新增: await page.mouse.move(width - 10, 10);
29新增: const layout = await project.evaluate(section => {
30新增: const rows = [...section.querySelectorAll('.sidebar-tab > button[role="tab"], .sidebar-session')];
31新增: return rows.map(button => {
32新增: const box = button.getBoundingClientRect();
33新增: const icon = button.querySelector("svg")?.getBoundingClientRect();
34新增: const title = button.querySelector("span").getBoundingClientRect();
35新增: return { title: button.textContent, x: box.x, iconX: icon?.x, textX: title.x, height: box.height,
36新增: right: box.right, titleRight: title.right, clipped: button.querySelector("span").scrollWidth > title.width };
37新增: });
38新增: });
39新增: await page.screenshot({ path: `${output}/${engine}-${width}.png` });
40新增: assert.equal(layout.length, 4);
41新增: for (const row of layout) {
42新增: assert.ok(row.iconX !== undefined, `missing session icon: ${row.title}`);
43新增: assert.ok(Math.abs(row.iconX - layout[0].iconX) < 1, `session icons misaligned: ${JSON.stringify(layout)}`);
44新增: assert.ok(Math.abs(row.textX - layout[0].textX) < 1, `session titles misaligned: ${JSON.stringify(layout)}`);
45新增: assert.ok(row.height >= 40, `session row too short: ${row.title}`);
46新增: assert.ok(row.titleRight <= row.right, `title overflow: ${row.title}`);
47新增: }
48新增: assert.ok(layout.find(row => row.title.startsWith("这是一段")).clipped, "long session title was not truncated");
49新增: const short = project.getByRole("button", { name: "你好", exact: true });
50新增: const before = await short.locator("svg").first().boundingBox();
51新增: await short.hover();
52新增: await project.getByRole("group", { name: "你好 的操作", exact: true }).getByRole("button", { name: "重命名", exact: true }).waitFor();
53新增: const after = await short.locator("svg").first().boundingBox();
54新增: assert.ok(Math.abs(before.x - after.x) < 1, "hover shifted the session icon");
55新增: await short.focus();
56新增: if (engine !== "webkit") {
57新增: await page.keyboard.press("Tab");
58新增: assert.equal(await page.locator(":focus").getAttribute("aria-label"), "置顶");
59新增: }
60新增: const rename = project.getByRole("group", { name: "你好 的操作", exact: true }).getByRole("button", { name: "重命名", exact: true });
61新增: await rename.focus();
62新增: await page.keyboard.press("Enter");
63新增: const dialog = page.getByRole("dialog");
64新增: await dialog.getByRole("textbox", { name: "标签名称" }).waitFor();
65新增: await dialog.getByRole("button", { name: "取消", exact: true }).click();
66新增: evidence.push({ width, layout });
67新增: }
68新增: const folder = project.locator(".project-disclosure");
69新增: await folder.click();
70新增: await history.first().waitFor({ state: "hidden" });
71新增: assert.equal(await folder.getAttribute("aria-expanded"), "false");
72新增: await folder.press("Enter");
73新增: await history.first().waitFor();
74新增: await page.reload();
75新增: await page.getByRole("button", { name: "你好", exact: true }).waitFor();
76新增: assert.deepEqual(errors, []);
77新增: await writeFile(`${output}/${engine}-result.json`, JSON.stringify(evidence, null, 2));
78新增: console.log(`${engine}: live/history alignment, short/long/pinned titles, hover, keyboard, collapse and reload passed`);
79新增:} finally {
80新增: await browser.close();
81新增:}
新增ui/scripts/smoke-captures.mjs+13 −0看文件
@@ -0,0 +1,13 @@
1新增:import { mkdir, mkdtemp } from "node:fs/promises";
2新增:import { tmpdir } from "node:os";
3新增:import { join, resolve } from "node:path";
4新增:
5新增:// Historical reports are immutable inputs unless the caller selects an output.
6新增:export async function smokeCaptureDirectory(name) {
7新增: if (process.env.CAGE_TEST_CAPTURE) {
8新增: const directory = resolve(process.env.CAGE_TEST_CAPTURE);
9新增: await mkdir(directory, { recursive: true });
10新增: return directory;
11新增: }
12新增: return mkdtemp(join(tmpdir(), "cage-" + name + "-"));
13新增:}
修改ui/scripts/start-feedback-smoke.mjs+2 −2看文件
@@ -44,12 +44,12 @@ try {
4444 state.status.job = { ...state.status.job, running: false, error: "测试启动失败" };
4545 await page.getByRole("button", { name: "启动 Cage 环境", exact: true }).waitFor();
4646
47删除: await page.route("**/api/start", route => route.fulfill({ status: 503, body: "测试请求失败" }));
47新增: await page.route("**/api/start", route => route.fulfill({ status: 503, contentType: "text/plain; charset=utf-8", body: "测试请求失败" }));
4848 await page.getByRole("button", { name: "启动 Cage 环境", exact: true }).click();
4949 await page.getByText("测试请求失败", { exact: true }).waitFor();
5050 assert.equal(await page.getByRole("button", { name: "启动 Cage 环境", exact: true }).isEnabled(), true);
5151
52删除: await page.route("**/api/host/git", route => route.fulfill({ status: 503, body: "测试检查失败" }));
52新增: await page.route("**/api/host/git", route => route.fulfill({ status: 503, contentType: "text/plain; charset=utf-8", body: "测试检查失败" }));
5353 await page.getByRole("button", { name: "启动 Cage 环境", exact: true }).click();
5454 await page.getByRole("alert").filter({ hasText: "测试检查失败" }).waitFor();
5555 await page.getByRole("button", { name: "暂不启动", exact: true }).click();
新增ui/scripts/subscription-import-smoke.mjs+139 −0看文件
@@ -0,0 +1,139 @@
1新增:// Real authenticated workbench and bundled Mihomo, with a new private profile.
2新增:// Uses synthetic local YAML only; never reads the user's profile or subscription.
3新增:import assert from "node:assert/strict";
4新增:import fs from "node:fs/promises";
5新增:import path from "node:path";
6新增:import { spawn, execFile } from "node:child_process";
7新增:import { promisify } from "node:util";
8新增:import { createRequire } from "node:module";
9新增:
10新增:const require = createRequire(import.meta.url);
11新增:const { chromium } = require(process.env.CAGE_PLAYWRIGHT_MODULE || "playwright");
12新增:const run = promisify(execFile);
13新增:const executable = process.env.CAGE_SUBSCRIPTION_QA_EXECUTABLE;
14新增:assert.ok(executable, "Set CAGE_SUBSCRIPTION_QA_EXECUTABLE to the newly built cage beside mihomo");
15新增:const output = path.resolve(process.env.CAGE_SUBSCRIPTION_QA_OUTPUT || "/tmp/cage-subscription-ui");
16新增:await fs.mkdir(output, { recursive: true });
17新增:const profile = await fs.mkdtemp("/private/tmp/cage-subscription-qa-");
18新增:const env = { ...process.env, CLAUDE_CAGE_CONFIG: path.join(profile, "config.json") };
19新增:await run(executable, ["init"], { env });
20新增:const log = await fs.open(path.join(profile, "server.log"), "w", 0o600);
21新增:const service = spawn(executable, ["serve"], { env, stdio: ["ignore", log.fd, log.fd] });
22新增:let browser;
23新增:const errors = [];
24新增:try {
25新增: let control;
26新增: for (let i = 0; i < 100; i++) {
27新增: try {
28新增: control = JSON.parse(await fs.readFile(path.join(profile, "control.json")));
29新增: break;
30新增: } catch {
31新增: if (service.exitCode !== null) throw new Error("Private service exited before readiness");
32新增: await new Promise((resolve) => setTimeout(resolve, 100));
33新增: }
34新增: }
35新增: assert.ok(control, "Private control service did not start");
36新增: const origin = `http://localhost:${control.port}`;
37新增: const launch = await fetch(`${origin}/api/launch`, {
38新增: method: "POST",
39新增: headers: { Origin: origin, "Content-Type": "application/json" },
40新增: body: JSON.stringify({ token: control.token }),
41新增: }).then((response) => response.json());
42新增: browser = await chromium.launch({ headless: true, executablePath: process.env.CAGE_TEST_BROWSER_PATH });
43新增: const page = await browser.newPage({ viewport: { width: 1280, height: 1000 } });
44新增: page.on("pageerror", (error) => errors.push(error.message));
45新增: await page.goto(launch.url);
46新增: await page.getByLabel("用户名", { exact: true }).fill("订阅验证");
47新增: await page.getByLabel("设置密码", { exact: true }).fill("isolated-subscription-qa-password");
48新增: await page.getByLabel("确认密码", { exact: true }).fill("isolated-subscription-qa-password");
49新增: await page.getByRole("button", { name: "创建本地账户", exact: true }).click();
50新增: const enter = async () => {
51新增: await page.getByRole("button", { name: /^设置/ }).click();
52新增: await page.getByRole("button", { name: "网络与代理", exact: true }).click();
53新增: await page.getByRole("heading", { name: "内置代理", exact: true }).waitFor();
54新增: await page.getByRole("tab", { name: "订阅", exact: true }).click();
55新增: };
56新增: const importYAML = async (name, content) => {
57新增: await page.getByRole("button", { name: "添加来源", exact: true }).click();
58新增: await page.getByRole("button", { name: "本地 YAML", exact: true }).click();
59新增: await page.getByLabel("来源名称", { exact: true }).fill(name);
60新增: await page.getByLabel("节点 YAML", { exact: true }).fill(content);
61新增: await page.getByRole("button", { name: "导入并验证", exact: true }).click();
62新增: await page.locator(".proxy-progress").waitFor({ state: "hidden" });
63新增: };
64新增: await enter();
65新增: const pin = "ab".repeat(32);
66新增: const mixed = `proxies:
67新增: - {name: 普通节点, type: socks5, server: 127.0.0.1, port: 1080}
68新增: - {name: 端口跳跃节点, type: hysteria2, server: example.com, port: 35000, password: private-password, mport: 35000-39000, pinSHA256: "${pin}"}
69新增: - {name: VLESS扩展参数, type: vless, server: example.com, port: 443, uuid: 00000000-0000-4000-8000-000000000000, tls: true, udp: true, xudp: true, future-option: private-field-value, reality-opts: {public-key: CQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA, short-id: "0123456789abcdef", support-x25519mlkem768: true}}
70新增: - {name: 不兼容节点, type: socks5, server: example.com, port: 1080, INTERFACE_NAME: private-field-value}
71新增: - {name: 依赖不兼容节点, type: http, server: example.com, port: 8080, dialer-proxy: 不兼容节点}
72新增:`;
73新增: await importYAML("兼容性验证", mixed);
74新增: await page.locator(".proxy-notice").filter({ hasText: "已导入 3 个节点,跳过 2 个" }).waitFor();
75新增: const state = () => page.evaluate(() => fetch("/api/proxy").then((response) => response.json()));
76新增: const imported = await state();
77新增: assert.equal(imported.sources[0].nodes.length, 3);
78新增: assert.equal(imported.sources[0].skipped.length, 2);
79新增: const stored = JSON.parse(await fs.readFile(path.join(profile, "proxy/sources.json")));
80新增: const hy2 = stored.sources[0].nodes.find((node) => node.type === "hysteria2").config;
81新增: assert.equal(hy2.ports, "35000-39000");
82新增: assert.equal(hy2.fingerprint, pin);
83新增: const vless = stored.sources[0].nodes.find((node) => node.type === "vless").config;
84新增: assert.equal(vless.xudp, true);
85新增: assert.equal(vless["future-option"], "private-field-value");
86新增: assert.equal(vless["reality-opts"]["support-x25519mlkem768"], true);
87新增: assert.equal(vless.udp, false);
88新增: for (const secret of [pin, "private-password", "private-field-value", stored.auth]) {
89新增: assert.ok(!JSON.stringify(imported).includes(secret), "Public import status leaked a field value");
90新增: }
91新增: await importYAML("第二来源", "proxies: [{name: 备用节点, type: http, server: 127.0.0.1, port: 8080}]");
92新增: await page.locator(".proxy-notice").filter({ hasText: "已导入 1 个节点,跳过 0 个" }).waitFor();
93新增: const details = page.locator(".proxy-source-skipped").first();
94新增: const summary = details.locator("summary");
95新增: const secondSource = page.locator(".proxy-source").nth(1);
96新增: // Measure relative positions so scrolling cannot hide a layout regression.
97新增: const relativeY = async () => (await secondSource.boundingBox()).y - (await details.boundingBox()).y;
98新增: await summary.scrollIntoViewIfNeeded();
99新增: const before = await relativeY();
100新增: await summary.click();
101新增: await details.getByText(/节点不能引用本机文件、网络接口或额外路由/).waitFor();
102新增: await details.getByText(/代理链必须引用同一来源中成功导入/).waitFor();
103新增: assert.ok((await relativeY()) > before + 30, "Expanded reasons did not push the next source down");
104新增: await page.locator(".settings-content").evaluate((element) => { element.scrollTop = 0; });
105新增: await page.screenshot({ path: path.join(output, "partial-import.png") });
106新增: await summary.focus();
107新增: await summary.press("Enter");
108新增: assert.equal(await details.getAttribute("open"), null);
109新增: assert.ok(Math.abs((await relativeY()) - before) < 2, "Collapsed reasons did not restore layout");
110新增: await page.reload();
111新增: await enter();
112新增: await page.locator(".proxy-source-skipped summary").click();
113新增: await page.locator(".proxy-source-skipped").getByText(/节点不能引用本机文件、网络接口或额外路由/).waitFor();
114新增: assert.equal((await state()).sources[0].skipped.length, 2, "Reload lost the import report");
115新增: await page.setViewportSize({ width: 760, height: 1000 });
116新增: const bounds = await page.locator(".proxy-source").first().boundingBox();
117新增: assert.ok(bounds.x >= 0 && bounds.x + bounds.width <= 760, "Import report overflowed the narrow viewport");
118新增: await page.screenshot({ path: path.join(output, "narrow.png") });
119新增: await page.setViewportSize({ width: 1280, height: 1000 });
120新增: await importYAML("全部不兼容", "proxies: [{name: 证书参数无效, type: hysteria2, server: example.com, port: 443, password: private-password, pinSHA256: private-pin}]");
121新增: await page.getByRole("alert").filter({ hasText: "没有可导入的节点" }).waitFor();
122新增: assert.equal((await state()).sources.length, 2, "Failed import changed existing sources");
123新增: assert.ok(!(await page.getByRole("alert").innerText()).includes("private-pin"));
124新增: await page.screenshot({ path: path.join(output, "all-skipped.png") });
125新增: assert.deepEqual(errors, []);
126新增: const result = { passed: true, imported: 3, skipped: 2, checks: ["real UI import", "bundled core validation", "VLESS xudp and nested REALITY options retained", "unknown protocol field retained", "interface key variant rejected", "guest UDP remains disabled", "port hopping and pin retained", "dependent chain skipped", "public status privacy", "success summary", "inline reasons and keyboard collapse", "reload persistence", "narrow viewport", "all-skipped rejection preserves sources"], browserErrors: errors };
127新增: await fs.writeFile(path.join(output, "result.json"), JSON.stringify(result, null, 2));
128新增: console.log(JSON.stringify(result));
129新增:} finally {
130新增: await browser?.close();
131新增: const stopped = new Promise((resolve) => service.once("exit", resolve));
132新增: if (service.exitCode === null) {
133新增: service.kill("SIGTERM");
134新增: const force = setTimeout(() => service.kill("SIGKILL"), 5000);
135新增: await stopped;
136新增: clearTimeout(force);
137新增: }
138新增: await log.close();
139新增:}
新增ui/scripts/tailscale-smoke.mjs+66 −0看文件
@@ -0,0 +1,66 @@
1新增:import assert from "node:assert/strict";
2新增:import { mkdir, writeFile } from "node:fs/promises";
3新增:import { fileURLToPath } from "node:url";
4新增:import { createWorkbench } from "./workbench-fixture.mjs";
5新增:const engine = process.env.CAGE_TEST_BROWSER || "chromium";
6新增:const output = new URL(`../../docs/test-reports/2026-11-09-tailscale/${engine}/`, import.meta.url);
7新增:await mkdir(output, { recursive: true });
8新增:let copied = "", fail = false, delayed = false;
9新增:let tail = { installed: true, version: "1.104.5", enabled: false, backend: "Stopped", ips: [], peers: [], keys: [], user: "cage", ssh_port: 22 };
10新增:const { browser, page, state, errors } = await createWorkbench({ nativeRequest: body => { if (body.action === "clipboardWrite") { copied = body.text; return true; } } });
11新增:const checks = [];
12新增:const open = page.getByRole("button", { name: "打开 Tailscale", exact: true });
13新增:const panel = page.getByRole("dialog", { name: "Tailscale", exact: true });
14新增:try {
15新增: await page.route("**/api/tailscale**", async route => {
16新增: const request = route.request(), action = new URL(request.url()).pathname.split("/").at(-1), body = request.postDataJSON();
17新增: if (fail) return route.fulfill({ status: 502, contentType: "text/plain", body: "Tailscale 暂未响应,请稍后重试" });
18新增: if (["connect", "login"].includes(action)) tail = { ...tail, enabled: true, backend: "NeedsLogin", ...(delayed ? {} : { auth_url: "https://login.tailscale.com/a/fixture-login" }) };
19新增: if (action === "disconnect") tail = { ...tail, enabled: false, backend: "Stopped" };
20新增: if (action === "add-key") tail.keys.push(body.key);
21新增: if (action === "remove-key") tail.keys = tail.keys.filter(key => key !== body.key);
22新增: return route.fulfill({ json: tail });
23新增: });
24新增: state.status.ready = state.status.vm_running = true;
25新增: await page.reload(); await open.waitFor();
26新增: const position = await open.boundingBox(), browserPosition = await page.getByRole("button", { name: "打开浏览器", exact: true }).boundingBox();
27新增: assert.ok(position.y > browserPosition.y && position.y < browserPosition.y + browserPosition.height * 2 + 8);
28新增: await open.focus(); await page.keyboard.press("Enter"); await panel.getByText("已断开", { exact: true }).waitFor();
29新增: await panel.getByRole("button", { name: "连接 Tailscale", exact: true }).click();
30新增: await panel.waitFor({ state: "hidden" });
31新增: assert.ok(state.requests.some(r => r.path === "/browser/new" && r.body.url === "https://login.tailscale.com/a/fixture-login" && r.body.incognito === false));
32新增: checks.push("entry immediately follows Browser; keyboard opens panel; connect opens official auth URL in regular Cage browser");
33新增: tail = { ...tail, enabled: true, backend: "Running", name: "cage-workbench.test.ts.net", auth_url: "", ips: ["100.88.2.3"], peers: [{ name: "my-computer.test.ts.net", ip: "100.88.2.4", online: true }] };
34新增: await open.click(); await panel.getByText("已连接", { exact: true }).waitFor();
35新增: await panel.getByRole("button", { name: "复制连接 Cage 命令" }).click(); assert.equal(copied, "ssh [email protected]");
36新增: await panel.getByLabel("本机 SSH 公钥", { exact: true }).fill("ssh-ed25519 AAAAFixture local");
37新增: await panel.getByRole("button", { name: "添加公钥", exact: true }).click(); await panel.locator(".tailscale-key").waitFor();
38新增: await page.screenshot({ path: fileURLToPath(new URL("connected.png", output)) });
39新增: await panel.getByRole("button", { name: "移除 SSH 公钥" }).click(); await panel.locator(".tailscale-key").waitFor({ state: "hidden" });
40新增: await panel.getByRole("button", { name: "复制命令", exact: true }).click(); assert.equal(copied, "ssh 本机用户名@100.88.2.4");
41新增: checks.push("connected address, peer presence, inbound and outbound command copy, add and remove public key");
42新增: await page.keyboard.press("Escape"); await panel.waitFor({ state: "hidden" });
43新增: await open.click(); await panel.getByRole("button", { name: "断开连接", exact: true }).click();
44新增: await page.getByRole("dialog", { name: "断开 Tailscale?", exact: true }).getByRole("button", { name: "取消", exact: true }).click();
45新增: assert.equal(tail.enabled, true);
46新增: await panel.getByRole("button", { name: "断开连接", exact: true }).click();
47新增: await page.getByRole("dialog", { name: "断开 Tailscale?", exact: true }).getByRole("button", { name: "断开连接", exact: true }).click();
48新增: await panel.getByText("已断开", { exact: true }).waitFor();
49新增: checks.push("closing and reopening retains status; cancel preserves active connection; explicit disconnect closes connection");
50新增: delayed = true; delete tail.auth_url;
51新增: await panel.getByRole("button", { name: "连接 Tailscale", exact: true }).click();
52新增: await panel.getByText("等待登录", { exact: true }).waitFor();
53新增: tail.auth_url = "https://login.tailscale.com/a/delayed-login";
54新增: await panel.waitFor({ state: "hidden" });
55新增: assert.ok(state.requests.some(r => r.path === "/browser/new" && r.body.url === tail.auth_url));
56新增: checks.push("asynchronously generated auth URL opens without a second login click");
57新增: fail = true; await open.click(); await panel.getByRole("alert").waitFor(); assert.ok(await panel.getByRole("alert").textContent());
58新增: fail = false; await panel.getByRole("button", { name: "刷新 Tailscale 状态" }).click(); await panel.getByRole("alert").waitFor({ state: "hidden" });
59新增: await page.setViewportSize({ width: 820, height: 600 });
60新增: await page.screenshot({ path: fileURLToPath(new URL("compact.png", output)) });
61新增: assert.ok(await panel.evaluate(node => node.scrollWidth <= node.clientWidth + 1));
62新增: assert.deepEqual(errors, []);
63新增: checks.push("service failure is actionable, refresh recovers, compact panel has no horizontal overflow, no browser exceptions");
64新增: await writeFile(new URL("result.json", output), JSON.stringify({ engine, checks, errors }, null, 2));
65新增: console.log(JSON.stringify({ engine, checks, errors }, null, 2));
66新增:} finally { await browser.close(); }
新增ui/scripts/terminal-startup-live-smoke.mjs+45 −0看文件
@@ -0,0 +1,45 @@
1新增:import assert from "node:assert/strict";
2新增:import { createWorkbench } from "./workbench-fixture.mjs";
3新增:
4新增:const parts = [];
5新增:for await (const chunk of process.stdin) parts.push(chunk);
6新增:const input = JSON.parse(Buffer.concat(parts).toString());
7新增:const fixture = await createWorkbench({
8新增: url: input.origin,
9新增: mockWebSockets: false,
10新增: cliRequest: route => route.continue(),
11新增: beforeNavigate: page => page.context().addCookies([{ name: input.cookie, value: input.session, url: input.origin }]),
12新增:});
13新增:try {
14新增: const { page, state } = fixture;
15新增: await page.route("**/api/terminals**", route => route.continue());
16新增: state.status.ready = state.status.vm_running = true;
17新增: state.status.projects = [input.project];
18新增: state.status.environment_directory = state.settings.workspace = input.project;
19新增: let output = "";
20新增: page.on("websocket", socket => {
21新增: if (!socket.url().includes("/terminals/")) return;
22新增: socket.on("framereceived", ({ payload }) => { output = (output + payload.toString()).slice(-65536); });
23新增: });
24新增: await page.reload();
25新增: await page.evaluate(() => {
26新增: window.visibleStartupWarnings = 0;
27新增: const check = () => {
28新增: for (const host of document.querySelectorAll(".terminal-host")) {
29新增: const text = host.querySelector(".xterm-rows")?.textContent.replace(/\s/g, "") || "";
30新增: if (getComputedStyle(host).visibility === "visible" && text.includes("Loadingdevelopmentchannels")) window.visibleStartupWarnings++;
31新增: }
32新增: };
33新增: new MutationObserver(check).observe(document.body, { attributes: true, childList: true, subtree: true });
34新增: });
35新增: await page.getByRole("button", { name: "新建终端", exact: true }).first().click();
36新增: await page.getByRole("menuitem", { name: "Claude 终端", exact: true }).click();
37新增: await page.getByText("正在准备 Claude 会话…", { exact: true }).waitFor();
38新增: await page.locator(".terminal-host").waitFor({ state: "visible" });
39新增: await page.waitForFunction(() => document.querySelector(".xterm-rows")?.textContent.includes("Claude Code"));
40新增: const text = output.replace(/\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g, "").replace(/\s/g, "");
41新增: assert.ok(text.includes("Loadingdevelopmentchannels"), "the genuine CLI confirmation must still exist in the raw output");
42新增: assert.equal(await page.evaluate(() => window.visibleStartupWarnings), 0, "the genuine startup confirmation flashed on screen");
43新增: assert.deepEqual(fixture.errors, []);
44新增: console.log("PASS: genuine Claude Code, isolated SSH/PTY and product WebSocket reach the desktop session without displaying the channel confirmation");
45新增:} finally { await fixture.browser.close(); }
新增ui/scripts/terminal-startup-smoke.mjs+74 −0看文件
@@ -0,0 +1,74 @@
1新增:import assert from "node:assert/strict";
2新增:import { createWorkbench } from "./workbench-fixture.mjs";
3新增:
4新增:const warning = "WARNING: Loading development channels\r\nChannels: server:cage\r\n1. I am using this for local development\r\nEnter to confirm";
5新增:for (const platform of ["darwin", "windows", "linux"]) {
6新增: const fixture = await createWorkbench({
7新增: mockWebSockets: false,
8新增: clientContext: { mode: "local", connection_id: "local", client_platform: platform, server_platform: platform, connection: { state: "disconnected" } },
9新增: beforeNavigate: page => page.clock.install(),
10新增: });
11新增: const { page, state } = fixture;
12新增: let terminalSocket;
13新增: const inputs = [];
14新增: try {
15新增: await page.route("**/api/terminals", route => {
16新增: if (route.request().method() !== "POST") return route.fallback();
17新增: const tab = { id: "startup-test", title: "Claude 1", kind: "claude", workspace: state.settings.workspace, cli_session_id: "fixture-cli", cli_starting: true };
18新增: state.terminals = [tab];
19新增: return route.fulfill({ json: tab });
20新增: });
21新增: await page.routeWebSocket("**/api/**", socket => {
22新增: if (!socket.url().includes("/terminals/")) return socket.close();
23新增: terminalSocket = socket;
24新增: socket.onMessage(message => { const value = JSON.parse(message); if (value.type === "input") inputs.push(value.data); });
25新增: socket.send(JSON.stringify({ type: "cli-startup", pending: true }));
26新增: socket.send(Buffer.from(warning.slice(0, 22)));
27新增: socket.send(Buffer.from(warning.slice(22)));
28新增: });
29新增: await page.reload();
30新增: await page.getByRole("button", { name: "启动 Cage 环境", exact: true }).click();
31新增: await page.getByRole("button", { name: "新建终端", exact: true }).first().click();
32新增: await page.getByRole("menuitem", { name: /Claude/ }).first().click();
33新增: await page.getByText("正在准备 Claude 会话…", { exact: true }).waitFor();
34新增: await page.waitForFunction(() => document.querySelector(".xterm-rows")?.textContent.includes("Loading development channels"));
35新增: assert.equal(await page.locator(".terminal-host").isVisible(), false);
36新增: await page.evaluate(() => {
37新增: window.startupFlashes = [];
38新增: const observer = new MutationObserver(() => {
39新增: const host = document.querySelector(".terminal-host");
40新增: const text = host?.querySelector(".xterm-rows")?.textContent || "";
41新增: if (host && getComputedStyle(host).visibility === "visible" && text.includes("Loading development channels")) window.startupFlashes.push(text.slice(0, 250));
42新增: });
43新增: observer.observe(document.querySelector(".terminal-view"), { childList: true, subtree: true, attributes: true });
44新增: });
45新增: terminalSocket.send(JSON.stringify({ type: "cli-startup", pending: false }));
46新增: await page.clock.runFor(120);
47新增: assert.equal(await page.locator(".terminal-host").isVisible(), false, "channel registration must not expose the previous warning screen");
48新增: await page.clock.resume();
49新增: terminalSocket.send(Buffer.from("\x1b[2J\x1b[HWelcome to Claude\r\n> "));
50新增: await page.locator(".terminal-host").waitFor({ state: "visible" });
51新增: assert.deepEqual(await page.evaluate(() => window.startupFlashes), []);
52新增: assert.deepEqual(inputs, [], "presentation never confirms tools or other prompts");
53新增: await page.keyboard.type("hello");
54新增: await page.waitForFunction(() => document.querySelector(".xterm-helper-textarea") === document.activeElement);
55新增:
56新增: // A new attachment can be waiting for login. It must become interactive
57新增: // without channel readiness, and the user can reveal it immediately.
58新增: terminalSocket.close();
59新增: await page.getByRole("button", { name: "重新连接", exact: true }).click();
60新增: await page.getByText("正在准备 Claude 会话…", { exact: true }).waitFor();
61新增: terminalSocket.send(Buffer.from("\x1b[2J\x1b[HSelect login method\r\n1. Claude account"));
62新增: await page.clock.fastForward(8100);
63新增: await page.clock.resume();
64新增: await page.locator(".terminal-host").waitFor({ state: "visible" });
65新增: assert.ok((await page.locator(".xterm-rows").textContent()).includes("Select login method"));
66新增: terminalSocket.close();
67新增: await page.getByRole("button", { name: "重新连接", exact: true }).click();
68新增: await page.getByText("正在准备 Claude 会话…", { exact: true }).waitFor();
69新增: await page.getByRole("button", { name: "显示启动过程", exact: true }).click();
70新增: await page.locator(".terminal-host").waitFor({ state: "visible" });
71新增: assert.deepEqual(fixture.errors, []);
72新增: console.log(`PASS: ${platform} hides split confirmation output, waits for repaint, restores focus, and exposes stalled/login output`);
73新增: } finally { await fixture.browser.close(); }
74新增:}
新增ui/scripts/ubuntu-guest-choice-smoke.mjs+74 −0看文件
@@ -0,0 +1,74 @@
1新增:import assert from "node:assert/strict";
2新增:import { createWorkbench } from "./workbench-fixture.mjs";
3新增:
4新增:for (const [platform, system] of [["darwin", "macos"], ["windows", "windows-11"], ["linux", "ubuntu-24.04"], ["linux", ""]]) {
5新增: let submitted;
6新增: const fixture = await createWorkbench({
7新增: clientContext: { mode: "local", connection_id: "local", client_platform: platform, server_platform: platform },
8新增: async beforeNavigate(page, state) {
9新增: state.status.local_vm_storage = true;
10新增: await page.route("**/api/environment/guest-systems", route => route.fulfill({ json: {
11新增: fresh: true, available: Boolean(system), ...(system ? { system } : {}), linux_systems: ["ubuntu-22.04"],
12新增: } }));
13新增: await page.route("**/api/environment/guest-systems/clone", () => { throw Error("Ubuntu requested host clone metadata"); });
14新增: await page.route("**/api/start", route => {
15新增: submitted = route.request().postDataJSON();
16新增: return route.fulfill({ json: { id: "ubuntu-choice", running: true, kind: "guest-install" } });
17新增: });
18新增: },
19新增: });
20新增: try {
21新增: const { page } = fixture;
22新增: const picker = page.getByRole("combobox", { name: "客户机系统" });
23新增: const storage = page.getByRole("button", { name: "选择环境存储位置" });
24新增: await picker.waitFor();
25新增: const initial = await storage.boundingBox();
26新增: await picker.click();
27新增: const option = page.getByRole("option", { name: "Ubuntu 22.04", exact: true });
28新增: await option.waitFor();
29新增: const box = await option.boundingBox();
30新增: const expanded = await storage.boundingBox();
31新增: assert.ok(expanded.y > initial.y && box.y + box.height <= expanded.y, "inline options overlap the next control");
32新增: await picker.press("Escape");
33新增: assert.equal((await storage.boundingBox()).y, initial.y);
34新增: await picker.press("Enter");
35新增: await picker.press("Home");
36新增: for (let index = 0; index < (system ? 2 : 1); index++) await picker.press("ArrowDown");
37新增: await picker.press("Enter");
38新增: await picker.click();
39新增: await option.click();
40新增: await page.getByText("从 Ubuntu 官方源下载 Ubuntu 22.04 LTS 镜像", { exact: false }).waitFor();
41新增: assert.equal(await page.getByLabel("ISO 的 SHA-256").count(), 0);
42新增: assert.equal(await page.getByRole("button", { name: "选择本机 ISO" }).count(), 0);
43新增: const install = page.getByRole("button", { name: "安装客户机", exact: true });
44新增: assert.equal(await install.isEnabled(), true);
45新增: await Promise.all([page.waitForResponse(response => response.url().endsWith("/api/start")), install.click()]);
46新增: assert.equal(submitted.guest_system, "ubuntu-22.04");
47新增: assert.equal(submitted.clone_key || "", "");
48新增: assert.equal(submitted.media, "");
49新增: assert.deepEqual(fixture.errors, []);
50新增: console.log(`${platform}/${system || "other-linux"}: explicit Ubuntu option, inline layout and install request passed`);
51新增: } finally { await fixture.browser.close(); }
52新增:}
53新增:
54新增:{
55新增: const fixture = await createWorkbench({
56新增: async beforeNavigate(page, state) {
57新增: state.status.local_vm_storage = true;
58新增: await page.route("**/api/environment/guest-systems", route => route.fulfill({ json: {
59新增: fresh: false, available: true, system: "macos", linux_systems: ["ubuntu-22.04"], reselect: false,
60新增: pending: { id: "ubuntu-resume", system: "ubuntu-22.04", source_kind: "linux-image", source: { host: { system: "ubuntu-22.04", arch: "arm64" } } },
61新增: } }));
62新增: await page.route("**/api/environment/guest-systems/clone", () => { throw Error("Ubuntu resume was treated as a host clone"); });
63新增: },
64新增: });
65新增: try {
66新增: const picker = fixture.page.getByRole("combobox", { name: "客户机系统" });
67新增: await picker.waitFor();
68新增: assert.equal(await picker.isDisabled(), true);
69新增: assert.match(await picker.innerText(), /Ubuntu 22.04/);
70新增: assert.equal(await fixture.page.getByRole("button", { name: "重新选择系统或镜像" }).count(), 0);
71新增: assert.deepEqual(fixture.errors, []);
72新增: console.log("Ubuntu interrupted installation retains its system and cannot replace an existing disk");
73新增: } finally { await fixture.browser.close(); }
74新增:}
新增ui/scripts/verify-build.mjs+47 −0看文件
@@ -0,0 +1,47 @@
1新增:import { createHash } from "node:crypto";
2新增:import { readFile, readdir, stat, writeFile } from "node:fs/promises";
3新增:import { join, resolve } from "node:path";
4新增:import { fileURLToPath } from "node:url";
5新增:import { spawnSync } from "node:child_process";
6新增:
7新增:const defaultDirectory = fileURLToPath(new URL("../../internal/workbench/web/", import.meta.url));
8新增:export async function verifyBuild(directory = defaultDirectory) {
9新增: const files = {};
10新增: async function inspect(relative = "") {
11新增: for (const entry of await readdir(join(directory, relative), { withFileTypes: true })) {
12新增: const name = [relative, entry.name].filter(Boolean).join("/");
13新增: if (entry.isDirectory()) { await inspect(name); continue; }
14新增: if (name === "README" || name === "build-integrity.json") continue;
15新增: const bytes = await readFile(join(directory, name));
16新增: if (bytes.length === 0) throw new Error(`Empty build resource: ${name}`);
17新增: if (/\.(?:js|css|html)$/.test(name)) {
18新增: if (bytes.includes(0)) throw new Error(`NUL bytes in build resource: ${name}`);
19新增: if (name.endsWith(".js")) {
20新增: const parsed = spawnSync(process.execPath, ["--check", "--input-type=module"], { input: bytes, encoding: "utf8" });
21新增: if (parsed.error) throw parsed.error;
22新增: if (parsed.status !== 0) throw new Error(`Invalid JavaScript build resource: ${name}\n${parsed.stderr}`);
23新增: }
24新增: }
25新增: files[name] = createHash("sha256").update(bytes).digest("hex");
26新增: }
27新增: }
28新增: await inspect();
29新增: for (const entry of ["index.html", "mobile.html"]) {
30新增: const html = await readFile(join(directory, entry), "utf8");
31新增: const scripts = [...html.matchAll(/<script\b[^>]*\bsrc=["']([^"']+)["']/gi)];
32新增: if (!scripts.length) throw new Error(`Missing entry script: ${entry}`);
33新增: for (const match of html.matchAll(/<(?:script|link)\b[^>]*\b(?:src|href)=["']([^"']+)["']/gi)) {
34新增: const url = new URL(match[1], "http://cage.local/" + entry);
35新增: if (url.origin !== "http://cage.local") throw new Error(`External build resource: ${match[1]}`);
36新增: const resource = decodeURIComponent(url.pathname).slice(1);
37新增: if (!files[resource] || !(await stat(join(directory, resource))).isFile()) throw new Error(`Missing build resource: ${resource}`);
38新增: }
39新增: }
40新增: await writeFile(join(directory, "build-integrity.json"), JSON.stringify({ version: 1, files }, null, 2) + "\n");
41新增: return Object.keys(files).length;
42新增:}
43新增:
44新增:if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
45新增: const count = await verifyBuild(process.argv[2] ? resolve(process.argv[2]) : defaultDirectory);
46新增: console.log(`Verified ${count} frontend build resources.`);
47新增:}
新增ui/scripts/verify-build.test.mjs+29 −0看文件
@@ -0,0 +1,29 @@
1新增:import assert from "node:assert/strict";
2新增:import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
3新增:import { tmpdir } from "node:os";
4新增:import { join } from "node:path";
5新增:import test from "node:test";
6新增:import { verifyBuild } from "./verify-build.mjs";
7新增:
8新增:test("build verification rejects corrupted or missing frontend resources", async (t) => {
9新增: for (const problem of ["none", "zero JS", "invalid JS", "zero CSS", "missing script", "missing entry"]) {
10新增: await t.test(problem, async () => {
11新增: const directory = await mkdtemp(join(tmpdir(), "cage-web-integrity-"));
12新增: try {
13新增: await mkdir(join(directory, "assets"));
14新增: const html = '<div id="root"></div><script type="module" src="/assets/main.js"></script><link rel="stylesheet" href="/assets/main.css">';
15新增: await writeFile(join(directory, "index.html"), html);
16新增: await writeFile(join(directory, "mobile.html"), problem === "missing entry" ? '<div id="root"></div>' : html);
17新增: if (problem !== "missing script") await writeFile(join(directory, "assets/main.js"), problem === "zero JS" ? Buffer.alloc(100) : problem === "invalid JS" ? "export const =;" : "export const valid = true;");
18新增: await writeFile(join(directory, "assets/main.css"), problem === "zero CSS" ? Buffer.alloc(10) : "body { color: black }");
19新增: if (problem !== "none") {
20新增: await assert.rejects(verifyBuild(directory), /(?:NUL bytes|Invalid JavaScript|Missing build resource|Missing entry script)/);
21新增: } else {
22新增: assert.equal(await verifyBuild(directory), 4);
23新增: const manifest = JSON.parse(await readFile(join(directory, "build-integrity.json"), "utf8"));
24新增: assert.match(manifest.files["assets/main.js"], /^[a-f0-9]{64}$/);
25新增: }
26新增: } finally { await rm(directory, { recursive: true, force: true }); }
27新增: });
28新增: }
29新增:});
新增ui/scripts/windows-fresh-desktop-smoke.mjs+167 −0看文件
@@ -0,0 +1,167 @@
1新增:import { pathToFileURL } from "node:url";
2新增:const { chromium } = await import(
3新增: process.env.CAGE_WINDOWS_QA_PLAYWRIGHT
4新增: ? pathToFileURL(process.env.CAGE_WINDOWS_QA_PLAYWRIGHT).href
5新增: : "playwright"
6新增:);
7新增:import path from "node:path";
8新增:let input = "";
9新增:for await (const chunk of process.stdin) input += chunk;
10新增:const config = JSON.parse(input);
11新增:const browser = await chromium.launch({
12新增: executablePath: path.join(
13新增: process.env["ProgramFiles(x86)"],
14新增: "Microsoft",
15新增: "Edge",
16新增: "Application",
17新增: "msedge.exe",
18新增: ),
19新增: headless: true,
20新增:});
21新增:try {
22新增: const ctx = await browser.newContext({
23新增: viewport: { width: 1440, height: 900 },
24新增: deviceScaleFactor: 1,
25新增: });
26新增: await ctx.addCookies(
27新增: config.cookies.map((c) => ({
28新增: ...c,
29新增: url: config.url,
30新增: httpOnly: true,
31新增: sameSite: "Strict",
32新增: })),
33新增: );
34新增: const page = await ctx.newPage();
35新增: page.setDefaultTimeout(30000);
36新增: const pointers = [];
37新增: page.on("websocket", (socket) => {
38新增: if (new URL(socket.url()).pathname !== "/api/claude-desktop/vnc") return;
39新增: socket.on("framesent", ({ payload }) => {
40新增: if (!Buffer.isBuffer(payload) || payload.length !== 6 || payload[0] !== 5)
41新增: return;
42新增: if (pointers.length < 24)
43新增: pointers.push([
44新增: payload[1],
45新增: payload.readUInt16BE(2),
46新增: payload.readUInt16BE(4),
47新增: ]);
48新增: });
49新增: });
50新增: await page.goto(config.url);
51新增: const nav = page.getByRole("navigation", { name: "主导航" });
52新增: await nav
53新增: .getByRole("button", { name: "Claude Desktop", exact: true })
54新增: .click();
55新增: const canvas = page
56新增: .locator('section[aria-label="Claude Desktop"] canvas:visible')
57新增: .last();
58新增: await canvas.waitFor({ timeout: 45000 });
59新增: // The guest view is an RFB canvas. Match the two observed public screens of
60新增: // the pinned Windows app before issuing a click or accepting the result.
61新增: function onboardingScreen(requireSignIn) {
62新增: const el = Array.from(
63新增: document.querySelectorAll('section[aria-label="Claude Desktop"] canvas'),
64新增: ).find(
65新增: (c) =>
66新增: c.getBoundingClientRect().width > 100 &&
67新增: c.width >= 1100 &&
68新增: c.height >= 240,
69新增: );
70新增: if (!el) return;
71新增: const { width, height } = el;
72新增: const pixels = el.getContext("2d").getImageData(0, 0, width, height).data;
73新增: const near = (x, y, red, green, blue, tolerance) => {
74新增: const index = (y * width + x) * 4;
75新增: return (
76新增: Math.abs(pixels[index] - red) <= tolerance &&
77新增: Math.abs(pixels[index + 1] - green) <= tolerance &&
78新增: Math.abs(pixels[index + 2] - blue) <= tolerance
79新增: );
80新增: };
81新增: const cx = Math.floor(width / 2);
82新增: let logo = 0,
83新增: googleBlue = 0,
84新增: googleGreen = 0,
85新增: googleRed = 0;
86新增: for (let y = Math.floor(height * 0.1); y < height * 0.8; y += 2) {
87新增: for (
88新增: let x = Math.max(0, cx - 220);
89新增: x < Math.min(width, cx + 220);
90新增: x += 2
91新增: ) {
92新增: if (near(x, y, 220, 115, 77, 22)) logo++;
93新增: if (near(x, y, 66, 133, 244, 24)) googleBlue++;
94新增: if (near(x, y, 52, 168, 83, 24)) googleGreen++;
95新增: if (near(x, y, 234, 67, 53, 24)) googleRed++;
96新增: }
97新增: }
98新增: const signIn =
99新增: googleBlue >= 1 && googleRed >= 1 && googleGreen >= 1 && logo < 80;
100新增: if (!signIn && (requireSignIn || logo < 100)) return;
101新增: const lower = signIn ? 0.33 : 0.6,
102新增: upper = signIn ? 0.83 : 0.999;
103新增: let first = -1,
104新增: last = -1;
105新增: for (let y = Math.floor(height * lower); y < height * upper; y++) {
106新增: if (
107新增: !near(cx - 45, y, 24, 24, 24, 15) ||
108新增: !near(cx + 45, y, 24, 24, 24, 15)
109新增: )
110新增: continue;
111新增: let left = cx - 45,
112新增: right = cx + 45;
113新增: while (left > 0 && near(left, y, 24, 24, 24, 15)) left--;
114新增: while (right < width - 1 && near(right, y, 24, 24, 24, 15)) right++;
115新增: if (
116新增: right - left < 230 ||
117新增: right - left > 820 ||
118新增: Math.abs((right + left) / 2 - cx) > 6
119新增: )
120新增: continue;
121新增: if (first < 0) first = y;
122新增: last = y;
123新增: }
124新增: if (first < 0 || last - first < 20 || last - first > 100) return;
125新增: const bounds = el.getBoundingClientRect();
126新增: return {
127新增: signIn,
128新增: x: bounds.left + bounds.width / 2,
129新增: y: bounds.top + bounds.height * ((first + last) / 2 / height),
130新增: };
131新增: }
132新增: const screenshot = async (name) =>
133新增: page.screenshot({
134新增: clip: { x: 0, y: 0, width: 1440, height: 855 },
135新增: path: path.join(config.evidence, name + ".png"),
136新增: });
137新增: const state = await (
138新增: await page.waitForFunction(onboardingScreen, false, { timeout: 60000 })
139新增: ).jsonValue();
140新增: if (!state.signIn) {
141新增: await screenshot("windows-workbench-welcome");
142新增: // Wait for the noVNC resize acknowledgement. The very first WGC frame
143新增: // is the app's 600×600 startup window and cannot locate a later button.
144新增: await page.waitForTimeout(1000);
145新增: const live = await page.evaluate(onboardingScreen, false);
146新增: if (!live || live.signIn)
147新增: throw new Error("Welcome button changed before clicking");
148新增: await page.mouse.click(live.x, live.y);
149新增: try {
150新增: await page.waitForFunction(onboardingScreen, true, { timeout: 80000 });
151新增: } catch {
152新增: await screenshot("windows-workbench-after-click");
153新增: throw new Error(
154新增: "Login form was not observed; welcome point=" +
155新增: JSON.stringify(live) +
156新增: "; guest pointer coordinates=" +
157新增: JSON.stringify(pointers),
158新增: );
159新增: }
160新增: }
161新增: await screenshot("windows-workbench-signin");
162新增: console.log(
163新增: "Verified the official Google/email form inside the shared Windows workbench.",
164新增: );
165新增:} finally {
166新增: await browser.close();
167新增:}
修改ui/scripts/workbench-fixture.mjs+41 −7看文件
@@ -5,19 +5,25 @@ const require = createRequire(import.meta.url);
55export async function createWorkbench({
66 viewport = { width: 1280, height: 850 },
77 recordVideo,
8新增: deviceScaleFactor = 1,
89 favoritesRequest,
10新增: browserRequest,
911 mockWebSockets = true,
1012 url,
1113 nativeRequest,
1214 clientRequest,
15新增: cliRequest,
16新增: beforeNavigate,
17新增: launchOptions = {},
1318 startupFailure = false,
19新增: initialization = { required: false },
1420 clientContext = { mode: "local", connection_id: "local", client_platform: "darwin", server_platform: "darwin", connection: { state: "disconnected" } },
1521} = {}) {
1622 const engines = require(
1723 process.env.CAGE_PLAYWRIGHT_MODULE || "playwright",
1824 );
19删除: const browser = await engines[process.env.CAGE_TEST_BROWSER || "chromium"].launch({ headless: true, executablePath: process.env.CAGE_TEST_BROWSER_PATH });
20删除: const context = await browser.newContext({ viewport, recordVideo });
25新增: const browser = await engines[process.env.CAGE_TEST_BROWSER || "chromium"].launch({ headless: true, executablePath: process.env.CAGE_TEST_BROWSER_PATH, ...launchOptions });
26新增: const context = await browser.newContext({ viewport, recordVideo, deviceScaleFactor });
2127 const page = await context.newPage();
2228 const errors = [];
2329 page.on("pageerror", (error) => errors.push(error.message));
@@ -52,6 +58,7 @@ export async function createWorkbench({
5258 saves: [],
5359 requests: [],
5460 terminalConnections: 0,
61新增: initialization: structuredClone(initialization),
5562 account: { exists: true, unlocked: true, username: "林间工作室", avatar: "" },
5663 accountPassword: "fixture-password",
5764 failAccountSave: false,
@@ -111,10 +118,15 @@ export async function createWorkbench({
111118 await page.route("**/api/**", async (route) => {
112119 const request = route.request();
113120 const path = new URL(request.url()).pathname.replace("/api", "");
114删除: const body = request.postDataJSON();
121新增: const body = request.headers()["content-type"]?.includes("application/json") ? request.postDataJSON() : undefined;
115122 state.requests.push({ path, method: request.method(), body: path.startsWith("/account") ? undefined : body });
116123 if (clientRequest && path.startsWith("/client/")) return clientRequest(route, path, body);
117124 if (path === "/client/context") return route.fulfill({ json: clientContext });
125新增: if (path === "/environment/initialization") {
126新增: if (body?.action === "install") state.initialization.started = true;
127新增: if (body?.action === "complete") state.initialization.required = false;
128新增: return route.fulfill({ json: state.initialization });
129新增: }
118130 const accountView = () => ({ ...state.account, background_running: state.status.vm_running });
119131 if (path === "/account") return route.fulfill({ json: accountView() });
120132 if (path.startsWith("/account/")) {
@@ -125,7 +137,7 @@ export async function createWorkbench({
125137 Object.assign(state.account, { exists: true, unlocked: true, username: body.username.trim(), avatar: body.avatar || "" });
126138 state.accountPassword = body.password;
127139 } else if (action === "unlock") {
128删除: if (body.password !== state.accountPassword) return route.fulfill({ status: 400, body: "密码不正确" });
140新增: if (body.password !== state.accountPassword) return route.fulfill({ status: 400, contentType: "text/plain; charset=utf-8", body: "密码不正确" });
129141 state.account.unlocked = true;
130142 state.account.require_authentication = false;
131143 } else if (action === "profile") {
@@ -149,6 +161,13 @@ export async function createWorkbench({
149161 return route.fulfill({ json: accountView() });
150162 }
151163 if (!state.account.unlocked && !["/session", "/launch", "/appearance"].includes(path)) return route.fulfill({ status: 423, body: "Cage 已锁定,请先登录" });
164新增: if (browserRequest && path.startsWith("/browser/") && path !== "/browser/events") return browserRequest(route, path, body);
165新增: if (path.startsWith("/cli/")) {
166新增: if (cliRequest) return cliRequest(route, path, body);
167新增: const account = path.match(/^\/cli\/sessions\/([^/]+)\/account$/);
168新增: if (account) return route.fulfill({ json: { session: { id: account[1] }, supported: false, candidates: [] } });
169新增: return route.fulfill({ json: { sessions: [], notice: "" } });
170新增: }
152171 if (startupFailure && path === "/status") return route.fulfill({ status: 503, body: "测试:控制服务暂不可用" });
153172 let result = {};
154173 if (path === "/favorites") {
@@ -211,7 +230,7 @@ export async function createWorkbench({
211230 else if (path === "/status")
212231 result = { ...state.status, workspace: state.settings.workspace };
213232 else if (path === "/projects/open") {
214删除: if (state.failJob) return route.fulfill({ status: 400, body: "项目文件夹连接失败,原项目保持不变" });
233新增: if (state.failJob) return route.fulfill({ status: 400, contentType: "text/plain; charset=utf-8", body: "项目文件夹连接失败,原项目保持不变" });
215234 if (!body.add && !state.status.projects.includes(body.workspace)) return route.fulfill({ status: 400, body: "请选择已授权的项目" });
216235 if (body.add && !state.status.projects.includes(body.workspace)) state.status.projects.push(body.workspace);
217236 if (body.activate) {
@@ -225,7 +244,8 @@ export async function createWorkbench({
225244 if (state.failSave)
226245 return route.fulfill({
227246 status: 400,
228删除: json: { error: "保存失败,请重试" },
247新增: contentType: "text/plain; charset=utf-8",
248新增: body: "保存失败,请重试",
229249 });
230250 const id = "job-" + ++state.sequence;
231251 const switching = state.settings.workspace !== body.workspace;
@@ -274,6 +294,19 @@ export async function createWorkbench({
274294 contentType: "text/event-stream",
275295 body: ": fixture\n\n",
276296 });
297新增: else if (path === "/browser/preferences") {
298新增: if (request.method() === "POST") {
299新增: if (state.failSave) return route.fulfill({ status: 500, body: "浏览器设置保存失败,请重试" });
300新增: state.settings.browser_home_url = body.browser_home_url;
301新增: }
302新增: result = { browser_home_url: state.settings.browser_home_url };
303新增: }
304新增: else if (path === "/browser/settings") {
305新增: let tab = state.tabs.find(tab => tab.kind === "browser-settings");
306新增: if (!tab) { tab = { id: "browser-settings", kind: "browser-settings", title: "设置", url: "cage://settings#general" }; state.tabs.push(tab); }
307新增: tab.url = "cage://settings#" + (body?.mode || "general"); state.active = tab.id; result = tab;
308新增: }
309新增: else if (path === "/browser/extensions") result = { items: [] };
277310 else if (path === "/vnc-credentials") result = { password: "fixture-only" };
278311 else if (path === "/terminals" && request.method() === "GET")
279312 result = state.terminals;
@@ -344,8 +377,9 @@ export async function createWorkbench({
344377 };
345378 return route.fulfill({ json: result });
346379 });
380新增: if (beforeNavigate) await beforeNavigate(page, state);
347381 await page.goto(url || process.env.CAGE_UI_URL || "http://127.0.0.1:5198");
348删除: if (!startupFailure && clientContext.mode !== "none") await page.getByRole("heading", { name: "先启动 Cage 环境" }).waitFor();
382新增: if (!startupFailure && !state.status.vm_running && clientContext.mode !== "none") await page.getByRole("heading", { name: state.initialization.required ? state.initialization.started ? "安装并检查客机环境" : "为 Cage 准备独立环境" : "先启动 Cage 环境" }).waitFor();
349383 return { browser, context, page, state, errors };
350384}
351385
修改ui/scripts/workbench-smoke.mjs+15 −21看文件
@@ -1,19 +1,14 @@
11import assert from "node:assert/strict";
22import fs from "node:fs/promises";
3删除:import { fileURLToPath } from "node:url";
3新增:import { join } from "node:path";
4新增:import { smokeCaptureDirectory } from "./smoke-captures.mjs";
45import { createWorkbench } from "./workbench-fixture.mjs";
56
6删除:const output = fileURLToPath(
7删除: new URL(
8删除: "../../docs/test-reports/2026-10-31-project-browser/",
9删除: import.meta.url,
10删除: ),
11删除:);
12删除:await fs.mkdir(output, { recursive: true });
7新增:const output = await smokeCaptureDirectory("workbench");
138const { browser, page, state, errors } = await createWorkbench();
149const checks = [];
1510const shot = (name) =>
16删除: page.screenshot({ path: output + name + ".png", animations: "disabled" });
11新增: page.screenshot({ path: join(output, name + ".png"), animations: "disabled" });
1712const settings = async () => {
1813 await page.getByRole("button", { name: /^设置/ }).click();
1914 await page.getByRole("navigation", { name: "设置分组" }).getByRole("button", { name: "通用", exact: true }).click();
@@ -110,7 +105,9 @@ try {
110105 await page.getByRole("button", { name: "工作台", exact: true }).hover();
111106 await actions.waitFor({ state: "hidden" });
112107 await terminalTab.focus();
113删除: await page.keyboard.press("Tab");
108新增: // WebKit's default keyboard mode skips buttons when tabbing. The tab's
109新增: // context-menu shortcut reaches its actions in that mode too.
110新增: await terminalTab.press(process.env.CAGE_TEST_BROWSER === "webkit" ? "Shift+F10" : "Tab");
114111 assert.equal(await page.locator(":focus").getAttribute("aria-label"), "置顶");
115112 await page.keyboard.press("Enter");
116113 await actions.getByRole("button", { name: "取消置顶", exact: true }).click();
@@ -154,14 +151,11 @@ try {
154151 assert.equal(await page.locator(".content-breadcrumb").count(), 0);
155152 await page.getByRole("button", { name: "新建网页", exact: true }).click();
156153 await tabs().getByRole("tab", { name: "新标签页", exact: true }).waitFor();
157删除: await tabs()
158删除: .getByRole("tab", { name: "新标签页", exact: true })
159删除: .locator("..")
160删除: .dragTo(
161删除: tabs()
162删除: .getByRole("tab", { name: "文件 · design-lab", exact: true })
163删除: .locator(".."),
164删除: );
154新增: const newTab = tabs().getByRole("tab", { name: "新标签页", exact: true });
155新增: const editorTab = tabs().getByRole("tab", { name: "文件 · design-lab", exact: true });
156新增: // Drop past the editor tab's midpoint to put the new tab before it.
157新增: await newTab.dragTo(editorTab, { targetPosition: { x: 5, y: 10 } });
158新增: await tabs().getByRole("tab").nth(1).and(newTab).waitFor();
165159 await page.reload();
166160 await page.getByRole("button", { name: "打开浏览器", exact: true }).click();
167161 assert.deepEqual(await tabs().getByRole("tab").allTextContents(), [
@@ -339,7 +333,7 @@ try {
339333 "两个项目终端各自归组、指定目录新建不受最后打开项目影响、浏览器与终端保持运行",
340334 );
341335 const deleteTab = page.getByRole("tab", { name: "终端 3", exact: true });
342删除: const remove = page.getByRole("group", { name: "终端 3 的操作" }).getByRole("button", { name: "删除" });
336新增: const remove = page.getByRole("group", { name: "终端 3 的操作" }).getByRole("button", { name: "关闭终端", exact: true });
343337 await deleteTab.hover();
344338 await remove.click();
345339 const confirmClose = page.getByRole("dialog", { name: "关闭这个终端会话?" });
@@ -350,7 +344,7 @@ try {
350344 await confirmClose.getByRole("button", { name: "关闭终端" }).click();
351345 await deleteTab.waitFor({ state: "detached" });
352346 assert.equal(state.terminals.length, 2);
353删除: checks.push("终端行悬停展开、键盘置顶、重命名、取消和确认删除指定终端");
347新增: checks.push("终端行悬停展开、键盘置顶、重命名、取消和确认关闭指定普通终端");
354348 await page.getByRole("button", { name: "工作台", exact: true }).click();
355349 await shot("main-minimum");
356350 await page.getByRole("button", { name: "收起侧栏", exact: true }).click();
@@ -371,7 +365,7 @@ try {
371365 );
372366 assert.deepEqual(errors, []);
373367 await fs.writeFile(
374删除: output + "smoke-result.json",
368新增: join(output, "smoke-result.json"),
375369 JSON.stringify(
376370 {
377371 passed: true,
修改ui/src/account.css+1 −0看文件
@@ -311,6 +311,7 @@
311311.account-device-option {
312312 display: flex;
313313 align-items: flex-start;
314新增: text-align: left;
314315 gap: 12px;
315316 margin: 20px 0;
316317 cursor: var(--control-cursor);
修改ui/src/account.jsx+32 −21看文件
@@ -15,7 +15,7 @@ import {
1515 Fingerprint,
1616 LockKeyhole,
1717 LogOut,
18删除: Settings2,
18新增: Settings,
1919} from "lucide-react";
2020import { api, native, nativeAvailable } from "./api";
2121import { getClientContext, isRemoteClient } from "./client-context.mjs";
@@ -179,7 +179,7 @@ export function AccountGate({ children }) {
179179 const [username, setUsername] = useState("");
180180 const [password, setPassword] = useState("");
181181 const [confirmation, setConfirmation] = useState("");
182删除: const [rememberLogin, setRememberLogin] = useState(true);
182新增: const [rememberLogin, setRememberLogin] = useState(null);
183183 const [busy, setBusy] = useState(false);
184184 const [error, setError] = useState("");
185185 const automaticAttempt = useRef("");
@@ -193,11 +193,13 @@ export function AccountGate({ children }) {
193193 finally { setBusy(false); }
194194 };
195195 useEffect(() => {
196删除: if (account?.unlocked) { trustedAttempt.current = false; return; }
197删除: if (!(account?.trusted_local || account?.trusted_login) || !localDesktop() || trustedAttempt.current || account.require_authentication) return;
196新增: if (account?.unlocked) { trustedAttempt.current = false; setRememberLogin(null); return; }
197新增: if (!account || !localDesktop() || trustedAttempt.current || account.require_authentication) return;
198新增: const firstMacGuest = account.guest_system === "macos" && !account.exists;
199新增: if (!firstMacGuest && !(account.trusted_local || account.trusted_login)) return;
198200 trustedAttempt.current = true;
199删除: void enterTrusted("resume");
200删除: }, [account?.unlocked, account?.trusted_local, account?.trusted_login, account?.require_authentication]);
201新增: void enterTrusted(firstMacGuest ? "create" : "resume");
202新增: }, [account?.unlocked, account?.exists, account?.guest_system, account?.trusted_local, account?.trusted_login, account?.require_authentication]);
201203 useEffect(() => {
202204 if (!account || account.unlocked || connectionError || gateAcknowledged.current || !nativeAvailable()) return;
203205 // A working lock/setup screen is a valid upgraded UI. Waiting for the
@@ -224,6 +226,7 @@ export function AccountGate({ children }) {
224226 }, [account?.unlocked]);
225227 if (account?.unlocked) return children;
226228 const creating = account && !account.exists;
229新增: const rememberThisDevice = rememberLogin ?? Boolean(creating || account?.trusted_login || account?.devices?.automatic);
227230 const submit = async (event) => {
228231 event.preventDefault();
229232 if (busy) return;
@@ -240,12 +243,19 @@ export function AccountGate({ children }) {
240243 ? { username, password, confirm_password: confirmation }
241244 : { password },
242245 );
243删除: setPassword("");
244删除: setConfirmation("");
245删除: if (creating && rememberLogin && deviceSupport?.supported && deviceSupport.device_status) {
246新增: if (localDesktop()) {
247新增: try {
248新增: await trustedLogin(rememberThisDevice ? "enable" : "disable", password);
249新增: await refresh();
250新增: } catch (e) {
251新增: setDeviceNotice(`已登录,${rememberThisDevice ? "记住我未能开启" : "记住我未能关闭"}:${e.message}。可在「设置 → 账户」中重试。`);
252新增: }
253新增: } else if (creating && rememberThisDevice && deviceSupport?.supported && deviceSupport.device_status) {
246254 try { await deviceAction("enable", "automatic"); }
247255 catch (e) { setDeviceNotice(`账户已创建,记住登录未能开启:${e.message}。可在「设置 → 账户」中重试。`); }
248256 }
257新增: setPassword("");
258新增: setConfirmation("");
249259 } catch (e) {
250260 setError(e.message);
251261 } finally {
@@ -348,10 +358,10 @@ export function AccountGate({ children }) {
348358 {deviceSupport?.supported && !deviceSupport.device_status && (
349359 <p className="field-help" role="status">当前应用启动器需要更新,暂时无法检查快捷登录状态。请先用密码进入,并重新安装完整的 Cage 应用。</p>
350360 )}
351删除: {creating && deviceSupport?.supported && deviceSupport.device_status && (
361新增: {(localDesktop() || (creating && deviceSupport?.supported && deviceSupport.device_status)) && (
352362 <label className="account-device-option check-line">
353删除: <input type="checkbox" checked={rememberLogin} onChange={(e) => setRememberLogin(e.target.checked)} />
354删除: <span><strong>记住登录</strong><small>下次打开直接进入。手动锁定后仍需验证。</small></span>
363新增: <input type="checkbox" checked={rememberThisDevice} onChange={(e) => setRememberLogin(e.target.checked)} />
364新增: <span><strong>{localDesktop() ? "记住我" : "记住登录"}</strong><small>{localDesktop() ? "信任此电脑,下次用当前系统用户打开时直接进入。手动锁定仍需验证。" : "下次打开直接进入。手动锁定后仍需验证。"}</small></span>
355365 </label>
356366 )}
357367 {!creating && deviceSupport?.supported && credentialPresent(deviceSupport.device_status?.biometric) && account.devices?.biometric && (
@@ -367,7 +377,7 @@ export function AccountGate({ children }) {
367377 )}
368378 <button
369379 className="primary account-submit"
370删除: disabled={busy || !password || (creating && (!username.trim() || (nativeAvailable() && deviceSupport === null)))}
380新增: disabled={busy || !password || (creating && (!username.trim() || (!localDesktop() && nativeAvailable() && deviceSupport === null)))}
371381 >
372382 {busy ? "正在解锁…" : creating ? isRemoteClient() ? "创建云端账户" : "创建本地账户" : "解锁 Cage"}
373383 </button>
@@ -481,7 +491,7 @@ export function AccountMenu({ onSettings, onConfirm, onStatus, busy }) {
481491 onSettings("account");
482492 }}
483493 >
484删除: <Settings2 size={16} />
494新增: <Settings size={16} />
485495 设置
486496 </button>
487497 {account.trusted_local ? <button role="menuitem" onClick={() => { setOpen(false); onSettings("account"); }}>
@@ -711,6 +721,7 @@ export function AccountSettings({ busy: environmentBusy, onDirty }) {
711721
712722function TrustedDeviceSettings() {
713723 const { account, refresh } = useAccount();
724新增: const enabled = Boolean(account.trusted_login || account.devices?.automatic);
714725 const [password, setPassword] = useState("");
715726 const [message, setMessage] = useState("");
716727 const [busy, setBusy] = useState(false);
@@ -718,7 +729,7 @@ function TrustedDeviceSettings() {
718729 event.preventDefault();
719730 setBusy(true); setMessage("");
720731 try {
721删除: await trustedLogin(account.trusted_login ? "disable" : "enable", password);
732新增: await trustedLogin(enabled ? "disable" : "enable", password);
722733 setPassword("");
723734 await refresh();
724735 } catch (error) { setMessage(error.message); }
@@ -726,10 +737,10 @@ function TrustedDeviceSettings() {
726737 };
727738 return <form onSubmit={update}>
728739 <fieldset disabled={busy}>
729删除: <h4>信任此电脑</h4>
730删除: <p className="field-help">{account.trusted_login ? "已开启本机自动登录。手动锁定仍需验证,退出账户会撤销信任。" : "验证一次账户密码,下次用当前系统用户打开时自动进入。"}</p>
731删除: {!account.trusted_login && <PasswordField label="验证账户密码" value={password} onChange={setPassword} autoComplete="current-password" />}
732删除: <button className="quiet-button" disabled={!account.trusted_login && !password}>{account.trusted_login ? "关闭本机信任" : "信任此电脑"}</button>
740新增: <h4>记住我</h4>
741新增: <p className="field-help">{enabled ? "已信任此电脑,下次用当前系统用户打开时自动进入。手动锁定仍需验证,退出账户会撤销信任。" : "验证一次账户密码,信任此电脑,下次用当前系统用户打开时自动进入。"}</p>
742新增: {!enabled && <PasswordField label="验证账户密码" value={password} onChange={setPassword} autoComplete="current-password" />}
743新增: <button className="quiet-button" disabled={!enabled && !password}>{enabled ? "关闭记住我" : "信任此电脑"}</button>
733744 {message && <p className="account-error" role="alert">{message}</p>}
734745 </fieldset>
735746 </form>;
@@ -763,11 +774,11 @@ function AccountDeviceSettings() {
763774 };
764775 return <section className="account-device-settings" aria-label="登录与解锁">
765776 <h4>登录与解锁</h4>
766删除: <label className="account-device-option check-line">
777新增: {!localDesktop() && <label className="account-device-option check-line">
767778 <input type="checkbox" checked={Boolean(account.devices?.automatic) && states.automatic === "available"} disabled={busy || states.automatic === "unavailable"}
768779 onChange={(event) => change("automatic", event.target.checked)} />
769780 <span><strong>记住登录</strong><small>{description("automatic", "重新打开直接进入。手动锁定后仍需指纹或密码。")}</small></span>
770删除: </label>
781新增: </label>}
771782 <label className="account-device-option check-line">
772783 <input type="checkbox" checked={Boolean(account.devices?.biometric) && credentialPresent(states.biometric)} disabled={busy || states.biometric === "unavailable" || (!deviceSupport.biometric_available && !credentialPresent(states.biometric))}
773784 onChange={(event) => change("biometric", event.target.checked)} />
修改ui/src/api.js+28 −16看文件
@@ -1,9 +1,10 @@
11import { reportDiagnostic } from "./diagnostics.mjs";
2删除:import { assertConnection, connectionHeaders, getClientContext } from "./client-context.mjs";
2新增:import { httpErrorMessage, connectionErrorMessage, operationName, nativeFailureMessage } from "./error-message.mjs";
3新增:import { assertConnection, connectionHeaders, getClientContext, isProjectSharesPath } from "./client-context.mjs";
34let sessionRenewal;
4删除:async function responseError(response) {
5新增:async function responseError(response, path, method = "GET") {
56 const error = new Error(
6删除: (await response.text()).trim() || "连接未完成,请重试",
7新增: httpErrorMessage(path, response.status, await response.text(), response.headers.get("Content-Type") || "", method),
78 );
89 error.status = response.status;
910 return error;
@@ -22,7 +23,7 @@ async function renewSession() {
2223 headers: { "Content-Type": "application/json" },
2324 body: JSON.stringify({ token: entry.hash.slice(1) }),
2425 });
25删除: if (!response.ok) throw await responseError(response);
26新增: if (!response.ok) throw await responseError(response, "/session");
2627 })().finally(() => {
2728 sessionRenewal = null;
2829 });
@@ -38,7 +39,7 @@ export async function api(path, body, method) {
3839 };
3940 const send = async () => {
4041 try { return await fetch("/api" + path, options); }
41删除: catch (error) { reportDiagnostic("frontend", error); throw error; }
42新增: catch (error) { reportDiagnostic("frontend", error); throw new Error(connectionErrorMessage(path, options.method), { cause: error }); }
4243 };
4344 let response = await send();
4445 // Authentication fails before a handler runs, so retrying this rejected
@@ -48,9 +49,11 @@ export async function api(path, body, method) {
4849 response = await send();
4950 }
5051 if (response.status === 423 && !path.startsWith("/client/")) window.dispatchEvent(new Event("cage-account-locked"));
51删除: if (!response.ok) throw await responseError(response);
52删除: const value = await response.json();
53删除: if (path !== "/session" && !path.startsWith("/client/")) assertConnection(connection);
52新增: if (!response.ok) throw await responseError(response, path, options.method);
53新增: let value;
54新增: try { value = await response.json(); }
55新增: catch (error) { reportDiagnostic("frontend", error); throw new Error(`${operationName(path, options.method)}失败:后台返回的结果格式无效。请重新连接;仍出现时在设置中导出诊断包。`, { cause: error }); }
56新增: if (path !== "/session" && (!path.startsWith("/client/") || isProjectSharesPath(path))) assertConnection(connection);
5457 return value;
5558}
5659export async function uploadFile(path, file, { signal, onProgress } = {}) {
@@ -65,17 +68,19 @@ export async function uploadFile(path, file, { signal, onProgress } = {}) {
6568 request.setRequestHeader("Content-Type", "application/octet-stream");
6669 for (const [name, value] of Object.entries(headers)) request.setRequestHeader(name, value);
6770 request.upload.onprogress = event => onProgress?.(event.loaded, event.total || file.size);
68删除: request.onerror = () => { cleanup(); reject(new Error("文件传递中断,请重试")); };
71新增: request.onerror = () => { cleanup(); reject(new Error("上传文件失败:与 Cage 后台的连接中断。请恢复连接后核对目标是否已收到文件,再重新选择文件。")); };
6972 request.onabort = () => { cleanup(); reject(new DOMException("上传已取消", "AbortError")); };
7073 request.onload = () => {
7174 cleanup();
7275 if (request.status === 423) window.dispatchEvent(new Event("cage-account-locked"));
7376 if (request.status !== 200) {
74删除: const error = new Error(request.responseText.trim() || "文件传递未完成");
77新增: const error = new Error(httpErrorMessage(path, request.status, request.responseText, request.getResponseHeader("Content-Type") || ""));
7578 error.status = request.status; reject(error); return;
7679 }
77删除: try { assertConnection(connection); resolve(JSON.parse(request.responseText)); }
78删除: catch { reject(new Error("文件传递响应无效")); }
80新增: try { assertConnection(connection); }
81新增: catch (error) { reject(error); return; }
82新增: try { resolve(JSON.parse(request.responseText)); }
83新增: catch { reject(new Error("上传文件后未收到有效确认。请先核对目标是否已收到文件,避免重复上传;仍失败时导出诊断包。")); }
7984 };
8085 signal?.addEventListener("abort", abort, { once: true });
8186 request.send(file);
@@ -87,8 +92,9 @@ export async function uploadFile(path, file, { signal, onProgress } = {}) {
8792 return send();
8893 }
8994}
90删除:export const nativeAvailable = () =>
91删除: Boolean(window.webkit?.messageHandlers?.cage);
95新增:const nativeBridge = () =>
96新增: window.cageNativeBridge || window.webkit?.messageHandlers?.cage;
97新增:export const nativeAvailable = () => Boolean(nativeBridge());
9298export async function native(action, extra = {}) {
9399 const connection = getClientContext().connection_id;
94100 if (action === "quitNow" && getClientContext().mode === "local" && !getClientContext().client_only) {
@@ -96,11 +102,17 @@ export async function native(action, extra = {}) {
96102 catch (error) { if (error.status !== 423) throw error; }
97103 }
98104 try {
99删除: const result = await window.webkit.messageHandlers.cage.postMessage({ action, ...extra, connection_id: connection });
105新增: const result = await nativeBridge().postMessage({ action, ...extra, connection_id: connection });
100106 assertConnection(connection);
101107 return result;
102108 }
103删除: catch (error) { reportDiagnostic("frontend", error); throw error; }
109新增: catch (error) {
110新增: reportDiagnostic("frontend", error);
111新增: const original = error?.message || String(error);
112新增: const message = nativeFailureMessage(action, original);
113新增: if (message === original) throw error;
114新增: throw new Error(message, { cause: error });
115新增: }
104116}
105117export const readClipboard = () =>
106118 nativeAvailable() ? native("clipboardRead") : navigator.clipboard.readText();
修改ui/src/api.test.mjs+15 −1看文件
@@ -16,7 +16,7 @@ test("address input retains loopback inside guest and rejects active schemes", (
1616 assert.throws(() => normalizeURL("file:///etc/passwd"));
1717});
1818
19删除:import { api } from "./api.js";
19新增:import { api, native, nativeAvailable } from "./api.js";
2020function nativeRuntime(t, fetcher, bridge) {
2121 const saved = {
2222 fetch: globalThis.fetch,
@@ -37,6 +37,20 @@ function nativeRuntime(t, fetcher, bridge) {
3737}
3838const json = (data, status = 200) =>
3939 new Response(JSON.stringify(data), { status });
40新增:test("Linux native calls survive WebKit's transient messageHandlers objects", async (t) => {
41新增: const calls = [];
42新增: nativeRuntime(t, () => { throw Error("unexpected request"); }, () => {});
43新增: Object.defineProperty(window, "webkit", {
44新增: get: () => ({ messageHandlers: {} }),
45新增: });
46新增: window.cageNativeBridge = {
47新增: postMessage: async (request) => { calls.push(request); return "clipboard text"; },
48新增: };
49新增: assert.equal(nativeAvailable(), true);
50新增: assert.equal(await native("clipboardRead"), "clipboard text");
51新增: assert.equal(calls.length, 1);
52新增: assert.equal(calls[0].action, "clipboardRead");
53新增:});
4054test("expired concurrent requests renew once and accept the rejected stop exactly once", async (t) => {
4155 let authorized = false,
4256 renewals = 0,
修改ui/src/app-updates.jsx+22 −9看文件
@@ -9,6 +9,9 @@ const retryInterval = 5 * 60 * 1000;
99export function useAppUpdates() {
1010 const [state, setState] = useState({ phase: "idle", message: "" });
1111 const [startupFailure, setStartupFailure] = useState("");
12新增: const [retryClock, setRetryClock] = useState(Date.now);
13新增: const retryAt = Date.parse(state.retryAt || "");
14新增: const coolingDown = state.phase === "failed" && retryAt > Date.now();
1215 const current = useRef(state);
1316 current.current = state;
1417 const requestPending = useRef(false);
@@ -16,6 +19,7 @@ export function useAppUpdates() {
1619 const available = nativeAvailable();
1720 const run = useCallback(async (operation) => {
1821 if (!available || requestPending.current || activePhases.has(current.current.phase)) return;
22新增: if (["check", "install"].includes(operation) && Date.parse(current.current.retryAt || "") > Date.now()) return;
1923 requestPending.current = true;
2024 if (operation === "check") lastCheck.current = Date.now();
2125 if (operation === "install") setState(previous => ({ ...previous, phase: "checking" }));
@@ -27,6 +31,12 @@ export function useAppUpdates() {
2731 } finally { requestPending.current = false; }
2832 }, [available]);
2933
34新增: useEffect(() => {
35新增: if (!coolingDown) return;
36新增: const timer = setTimeout(() => setRetryClock(Date.now()), Math.min(60000, retryAt - Date.now()));
37新增: return () => clearTimeout(timer);
38新增: }, [coolingDown, retryAt, retryClock]);
39新增:
3040 useEffect(() => {
3141 if (!available) return;
3242 let live = true;
@@ -36,8 +46,10 @@ export function useAppUpdates() {
3646 const check = () => {
3747 if (document.visibilityState === "hidden" || window.cageWindowVisible === false) return;
3848 const phase = current.current.phase;
39删除: const interval = phase === "failed" ? retryInterval : checkInterval;
40删除: if (["idle", "current", "failed", "available"].includes(phase) && Date.now() - lastCheck.current >= interval) void run("check");
49新增: const interval = ["failed", "waiting"].includes(phase) ? retryInterval : checkInterval;
50新增: const deadline = phase === "failed" && Number.isFinite(Date.parse(current.current.retryAt || ""))
51新增: ? Date.parse(current.current.retryAt) : lastCheck.current + interval;
52新增: if (["idle", "current", "failed", "waiting", "available"].includes(phase) && Date.now() >= deadline) void run("check");
4153 };
4254 window.addEventListener("cage-app-update", receive);
4355 window.addEventListener("focus", check);
@@ -49,7 +61,7 @@ export function useAppUpdates() {
4961 if (!live) return;
5062 if (next?.phase === "failed") setStartupFailure(next.message || "上次应用更新未完成");
5163 if (next?.phase) { current.current = next; setState(next); }
52删除: if (!next || ["idle", "current", "failed"].includes(next.phase)) void run("check");
64新增: if (!next || ["idle", "current", "failed", "waiting"].includes(next.phase)) void run("check");
5365 } catch (error) {
5466 if (live) setState({ phase: "failed", message: error.message, retryable: true });
5567 }
@@ -69,11 +81,11 @@ export function useAppUpdates() {
6981 const timer = setTimeout(() => setStartupFailure(""), 8000);
7082 return () => clearTimeout(timer);
7183 }, [startupFailure]);
72删除: return { state, run, available, startupFailure };
84新增: return { state, run, available, startupFailure, coolingDown };
7385}
7486
7587export function AppUpdateButton({ updates }) {
76删除: const { state, run, available, startupFailure } = updates;
88新增: const { state, run, available, startupFailure, coolingDown } = updates;
7789 const busy = activePhases.has(state.phase);
7890 const failed = state.phase === "failed";
7991 const visible = state.latestVersion && ["available", "ready", "failed", ...activePhases].includes(state.phase);
@@ -100,8 +112,9 @@ export function AppUpdateButton({ updates }) {
100112 : state.phase === "verifying" || state.phase === "downloaded" ? "正在验证更新"
101113 : state.phase === "installing" ? "正在安装更新,完成后自动重启"
102114 : state.phase === "checking" ? "正在准备更新"
103删除: : failed ? "重试更新" : "下载更新";
104删除: const hint = failed ? `${state.message || "更新未完成"},点击重试`
115新增: : coolingDown ? "等待重试更新" : failed ? "重试更新" : "下载更新";
116新增: const hint = coolingDown ? `${state.message || "更新源请求受限"},可于 ${new Date(state.retryAt).toLocaleString()} 后重试`
117新增: : failed ? `${state.message || "更新未完成"},点击重试`
105118 : busy ? label : `更新至 ${state.latestVersion}。请先保存工作,点击后将自动停止环境、安装并重启。`;
106119 const circumference = 2 * Math.PI * 15;
107120 return (
@@ -110,7 +123,7 @@ export function AppUpdateButton({ updates }) {
110123 className={`app-update-button${busy ? " busy" : ""}${failed ? " failed" : ""}`}
111124 aria-label={label}
112125 title={hint}
113删除: disabled={busy}
126新增: disabled={busy || coolingDown}
114127 onClick={() => { setFailure(""); void run("install"); }}
115128 >
116129 {busy ? (
@@ -126,7 +139,7 @@ export function AppUpdateButton({ updates }) {
126139 </>
127140 ) : failed ? <RefreshCw size={20} /> : <ArrowDownToLine size={20} />}
128141 </button>}
129删除: {(failure || startupFailure) && <div className="app-update-error" role="alert">{failure || startupFailure}{visible ? "。可点击更新按钮重试。" : ""}</div>}
142新增: {(failure || startupFailure) && <div className="app-update-error" role="alert">{failure || startupFailure}{visible ? coolingDown ? "。请等待更新源恢复后重试。" : "。可点击更新按钮重试。" : ""}</div>}
130143 </>
131144 );
132145}
修改ui/src/audio-output.js+8 −2看文件
@@ -3,8 +3,9 @@ import { runtimeSocketURL } from "./client-context.mjs";
33import workletURL from "./audio-worklet.js?url&no-inline";
44
55export class AudioOutput {
6删除: constructor(onState) {
6新增: constructor(onState, onError = () => {}) {
77 this.onState = onState;
8新增: this.onError = onError;
89 this.active = false;
910 this.volume = 1;
1011 this.generation = 0;
@@ -17,6 +18,7 @@ export class AudioOutput {
1718 this.disconnect();
1819 this.context?.suspend().catch(() => {});
1920 this.onState("idle");
21新增: this.onError("");
2022 }
2123 }
2224 setVolume(value) {
@@ -84,6 +86,7 @@ export class AudioOutput {
8486 const format = await api("/audio");
8587 if (!live()) return;
8688 if (format.format !== "s16le" || format.sample_rate !== 48000 || format.channels !== 2) throw new Error("声音格式不兼容");
89新增: this.onError("");
8790 const socket = new WebSocket(runtimeSocketURL("/audio"));
8891 socket.binaryType = "arraybuffer";
8992 this.socket = socket;
@@ -104,7 +107,10 @@ export class AudioOutput {
104107 socket.onclose = reconnect;
105108 socket.onerror = () => socket.close();
106109 this.opening = false;
107删除: } catch { reconnect(); }
110新增: } catch (error) {
111新增: if (live()) this.onError(error.message || "声音连接未能建立,请重试");
112新增: reconnect();
113新增: }
108114 }
109115 close() {
110116 this.disposed = true;
修改ui/src/audio.jsx+32 −11看文件
@@ -12,9 +12,10 @@ function savedAudio() {
1212export function useAudioOutput(enabled) {
1313 const [preferences, setPreferences] = useState(savedAudio);
1414 const [state, setState] = useState("idle");
15新增: const [error, setError] = useState("");
1516 const player = useRef();
1617 useEffect(() => {
17删除: const output = new AudioOutput(setState);
18新增: const output = new AudioOutput(setState, setError);
1819 player.current = output;
1920 const activate = () => output.activate();
2021 window.addEventListener("pointerdown", activate, true);
@@ -32,28 +33,48 @@ export function useAudioOutput(enabled) {
3233 try { localStorage.setItem("cage.audio", JSON.stringify(preferences)); } catch { /* Playback also works without storage. */ }
3334 }, [enabled, preferences]);
3435 const toggle = () => {
35删除: if (state === "blocked" && !preferences.muted && preferences.volume > 0) {
36删除: player.current?.activate();
37删除: return;
38删除: }
3936 const muted = !preferences.muted && preferences.volume > 0;
4037 setPreferences({ ...preferences, muted, volume: preferences.volume || 1 });
4138 player.current?.setActive(enabled && !muted);
4239 };
43删除: return { enabled, state, ...preferences, toggle, volumeChange: volume => {
40新增: return { enabled, state, error, ...preferences, toggle, volumeChange: volume => {
4441 setPreferences({ muted: false, volume });
4542 player.current?.setActive(enabled && volume > 0);
4643 } };
4744}
4845
4946export function AudioControls({ audio }) {
47新增: const [open, setOpen] = useState(false);
48新增: const controls = useRef(null);
49新增: const keyboardOpened = useRef(false);
50新增: const pressingSpeaker = useRef(false);
51新增: useEffect(() => {
52新增: if (!open) return;
53新增: const dismiss = event => {
54新增: if (!controls.current?.contains(event.target)) setOpen(false);
55新增: };
56新增: document.addEventListener("pointerdown", dismiss);
57新增: return () => document.removeEventListener("pointerdown", dismiss);
58新增: }, [open]);
59新增: useEffect(() => {
60新增: if (!audio.enabled) setOpen(false);
61新增: }, [audio.enabled]);
5062 const silent = audio.muted || audio.volume === 0;
51删除: const label = !audio.enabled ? "环境声音:未启动" : silent ? "取消静音" : audio.state === "blocked" ? "启用声音" : audio.state === "unsupported" ? "当前窗口不支持声音播放" : audio.state === "disconnected" ? "声音连接中断,正在重连" : "静音";
52删除: return <div className="audio-controls">
53删除: <button onClick={audio.toggle} disabled={!audio.enabled} aria-label={label} title={label} aria-pressed={silent}>
63新增: const label = !audio.enabled ? "环境声音:未启动" : !open ? "打开音量控制" : silent ? "取消静音" : "静音";
64新增: const status = audio.error || (audio.state === "unsupported" ? "当前窗口不支持声音播放" : audio.state === "disconnected" ? "声音连接中断,正在重连" : "");
65新增: return <div className="audio-controls" ref={controls}
66新增: onPointerLeave={event => { pressingSpeaker.current = false; if (event.pointerType !== "touch") setOpen(false); }}
67新增: onBlur={event => { if (!pressingSpeaker.current && !event.currentTarget.contains(event.relatedTarget)) setOpen(false); }}
68新增: onKeyDown={event => { if (event.key === "Escape" && open) { event.stopPropagation(); setOpen(false); controls.current?.querySelector("button")?.focus(); } }}>
69新增: <button onPointerDown={() => { pressingSpeaker.current = true; }} onPointerCancel={() => { pressingSpeaker.current = false; }} onClick={event => { pressingSpeaker.current = false; if (open) audio.toggle(); else { keyboardOpened.current = event.detail === 0; setOpen(true); } }} disabled={!audio.enabled} aria-label={label} title={status ? `${label}(${status})` : label} aria-expanded={open} aria-pressed={open ? silent : undefined}>
5470 {silent ? <VolumeX size={15} /> : <Volume2 size={15} />}
55删除: {audio.state === "blocked" && !silent && audio.enabled && <span>启用声音</span>}
5671 </button>
57删除: <input type="range" aria-label="环境音量" title={`环境音量 ${Math.round(audio.volume * 100)}%`} min="0" max="100" step="1" value={Math.round(audio.volume * 100)} disabled={!audio.enabled} onChange={e => audio.volumeChange(Number(e.target.value) / 100)} />
72新增: {open && <div className="audio-volume-panel">
73新增: <input type="range" aria-label="环境音量" title={`环境音量 ${Math.round(audio.volume * 100)}%`} min="0" max="100" step="1" value={Math.round(audio.volume * 100)} style={{ "--volume-level": `${Math.round(audio.volume * 100)}%` }} disabled={!audio.enabled} autoFocus={keyboardOpened.current} onChange={e => audio.volumeChange(Number(e.target.value) / 100)} onKeyDown={event => {
74新增: const value = Math.round(audio.volume * 100);
75新增: const next = { ArrowUp: value + 1, ArrowRight: value + 1, ArrowDown: value - 1, ArrowLeft: value - 1, Home: 0, End: 100, PageUp: value + 10, PageDown: value - 10 }[event.key];
76新增: if (next !== undefined) { event.preventDefault(); audio.volumeChange(Math.max(0, Math.min(100, next)) / 100); }
77新增: }} />
78新增: </div>}
5879 </div>;
5980}
新增ui/src/browser-cookies.jsx+87 −0看文件
@@ -0,0 +1,87 @@
1新增:import React, { useEffect, useRef, useState } from "react";
2新增:import { ArrowLeft, RefreshCw, Trash2 } from "lucide-react";
3新增:import { api } from "./api";
4新增:import { InlineSelect } from "./inline-select";
5新增:
6新增:export function BrowserCookies({ tab, onClose }) {
7新增: const [scope, setScope] = useState(/^https?:/.test(tab.url) ? "site" : "all");
8新增: const [query, setQuery] = useState("");
9新增: const [page, setPage] = useState(0);
10新增: const [revision, setRevision] = useState(0);
11新增: const [data, setData] = useState(null);
12新增: const [value, setValue] = useState(null);
13新增: const [error, setError] = useState("");
14新增: const [loading, setLoading] = useState(true);
15新增: const [busy, setBusy] = useState(false);
16新增: const [confirmClear, setConfirmClear] = useState(false);
17新增: const generation = useRef(0), search = useRef(null), operation = useRef(false);
18新增: useEffect(() => { search.current?.focus(); }, []);
19新增: useEffect(() => {
20新增: const version = ++generation.current;
21新增: setLoading(true); setData(null); setValue(null); setError(""); setConfirmClear(false);
22新增: api("/browser/cookies", { id: tab.id, url: tab.url, mode: "list", scope, query, page })
23新增: .then(result => { if (version === generation.current) setData(result); })
24新增: .catch(error => { if (version === generation.current) setError(error.message); })
25新增: .finally(() => { if (version === generation.current) setLoading(false); });
26新增: return () => { generation.current++; };
27新增: }, [tab.id, scope, query, page, revision]);
28新增: const run = async (mode, cookieKey) => {
29新增: if (operation.current || loading) return;
30新增: operation.current = true; setBusy(true); setError("");
31新增: const version = generation.current;
32新增: try {
33新增: const result = await api("/browser/cookies", { id: tab.id, url: tab.url, mode, scope, query, page, cookieKey });
34新增: if (version !== generation.current) return;
35新增: if (mode === "details") setValue({ key: cookieKey, value: result.value });
36新增: else { setData(result); setValue(null); setConfirmClear(false); }
37新增: } catch (error) {
38新增: if (version === generation.current) setError(error.message);
39新增: } finally { operation.current = false; setBusy(false); }
40新增: };
41新增: return <section className="browser-cookies" aria-label="Cookie 管理" onKeyDown={event => {
42新增: if (event.key === "Escape") { event.stopPropagation(); onClose(); }
43新增: }}>
44新增: <div className="cookie-heading">
45新增: <button className="icon-button" aria-label="关闭 Cookie 管理" onClick={onClose}><ArrowLeft size={15} /></button>
46新增: <strong>Cookie 管理</strong><span>{tab.incognito ? "无痕会话" : "普通会话"}</span>
47新增: <button className="icon-button" aria-label="刷新 Cookie" disabled={busy || loading}
48新增: onClick={() => setRevision(revision + 1)}><RefreshCw size={15} /></button>
49新增: </div>
50新增: <div className="cookie-toolbar">
51新增: <InlineSelect aria-label="Cookie 网站范围" value={scope} disabled={busy} onValueChange={next => { setScope(next); setPage(0); }}>
52新增: <option value="site" disabled={!/^https?:/.test(tab.url)}>当前网站</option><option value="all">所有网站</option>
53新增: </InlineSelect>
54新增: <input ref={search} aria-label="搜索 Cookie" placeholder="搜索网站或 Cookie 名称" maxLength={200}
55新增: value={query} disabled={busy} onChange={event => { setQuery(event.target.value); setPage(0); }} />
56新增: <button disabled={busy || loading || !data} onClick={() => setConfirmClear(!confirmClear)}>
57新增: <Trash2 size={14} />清空{scope === "site" ? "当前网站" : "所有网站"}
58新增: </button>
59新增: </div>
60新增: {confirmClear && <div className="cookie-confirm" role="alert">
61新增: <span>清空{scope === "site" ? data?.hostname : "此" + (tab.incognito ? "无痕" : "普通") + "会话所有网站"}的 Cookie?搜索条件不限制清空范围,网站可能需要重新登录。</span>
62新增: <button disabled={busy} onClick={() => run("clear")}>确认清空</button>
63新增: <button disabled={busy} onClick={() => setConfirmClear(false)}>取消</button>
64新增: </div>}
65新增: {error && <p className="cookie-error" role="alert">{error}</p>}
66新增: <div className="cookie-list" aria-busy={busy || loading}>
67新增: {loading ? <p>正在读取 Cookie…</p> : data?.cookies.length === 0 ? <p>没有匹配的 Cookie。</p> : data?.cookies.map(cookie =>
68新增: <article className="cookie-record" key={cookie.key}>
69新增: <div className="cookie-record-heading"><strong>{cookie.name || "(空名称)"}</strong>
70新增: <button disabled={busy} onClick={() => value?.key === cookie.key ? setValue(null) : run("details", cookie.key)}>
71新增: {value?.key === cookie.key ? "隐藏值" : "查看值"}</button>
72新增: <button disabled={busy || cookie.partitionKeyOpaque} aria-label={`删除 Cookie ${cookie.name}`}
73新增: title={cookie.partitionKeyOpaque ? "此分区 Cookie 需要清空所有网站" : "删除此 Cookie"}
74新增: onClick={() => run("delete", cookie.key)}><Trash2 size={14} /></button></div>
75新增: <div className="cookie-metadata">{cookie.domain} · 路径 {cookie.path} · {cookie.size} B</div>
76新增: <div className="cookie-metadata">{cookie.session ? "会话结束时过期" : `过期:${new Date(cookie.expires * 1000).toLocaleString()}`}
77新增: {cookie.secure && " · Secure"}{cookie.httpOnly && " · HttpOnly"}{cookie.sameSite && ` · SameSite=${cookie.sameSite}`}
78新增: {(cookie.partitionKey || cookie.partitionKeyOpaque) && ` · 分区:${cookie.partitionKey?.topLevelSite || "不透明"}`}</div>
79新增: {value?.key === cookie.key && <pre className="cookie-value">{value.value || "(空值)"}</pre>}
80新增: </article>)}
81新增: </div>
82新增: {data && <div className="cookie-pagination"><span>共 {data.total} 条 · 第 {data.page + 1} 页</span>
83新增: <button disabled={busy || loading || data.page === 0} onClick={() => setPage(data.page - 1)}>上一页</button>
84新增: <button disabled={busy || loading || (data.page + 1) * 50 >= data.total} onClick={() => setPage(data.page + 1)}>下一页</button>
85新增: </div>}
86新增: </section>;
87新增:}
修改ui/src/browser-downloads.jsx+298 −95看文件
@@ -1,9 +1,25 @@
1删除:import React, { useEffect, useRef, useState } from "react";
1新增:import React, {
2新增: useEffect,
3新增: useId,
4新增: useLayoutEffect,
5新增: useRef,
6新增: useState,
7新增:} from "react";
28import { createPortal } from "react-dom";
3删除:import { ArrowDownToLine, CircleAlert } from "lucide-react";
9新增:import {
10新增: ArrowDownToLine,
11新增: CircleAlert,
12新增: File,
13新增: FolderOpen,
14新增: Save,
15新增: X,
16新增:} from "lucide-react";
417import { api, native, nativeAvailable } from "./api";
5删除:import { isRemoteClient, runtimeURL } from "./client-context.mjs";
6删除:import { Modal } from "./views";
18新增:import {
19新增: getClientContext,
20新增: isRemoteClient,
21新增: runtimeURL,
22新增:} from "./client-context.mjs";
723
824export function useDownloadNotifications(
925 downloads = [],
@@ -17,23 +33,37 @@ export function useDownloadNotifications(
1733 queue = useRef(Promise.resolve());
1834 useEffect(() => {
1935 for (const item of downloads) {
20删除: if (["downloading", "saving"].includes(item.state) ||
21删除: (item.target === "desktop" && Date.parse(item.startedAt) >= mountedAt.current))
36新增: if (
37新增: ["downloading", "saving"].includes(item.state) ||
38新增: (item.target === "desktop" &&
39新增: Date.parse(item.startedAt) >= mountedAt.current)
40新增: )
2241 observed.current.add(item.id);
23删除: if (item.state === "failed" && previous.current.get(item.id) !== "failed")
42新增: if (item.state === "failed" && previous.current.get(item.id)?.state !== "failed")
2443 onStatus(
2544 `“${item.name}”未能保存:${item.error || "请在下载列表中重试"}`,
2645 );
27删除: if (item.target === "desktop" && observed.current.has(item.id) && previous.current.get(item.id) !== item.state) {
28删除: if (item.state === "downloading") onStatus(`正在下载“${item.name}”,可在侧栏“下载”查看`);
29删除: if (item.state === "saved") onStatus(`“${item.name}”已保存到默认工作区的 Downloads`);
46新增: if (
47新增: item.target === "desktop" &&
48新增: observed.current.has(item.id) &&
49新增: previous.current.get(item.id)?.state !== item.state
50新增: ) {
51新增: if (item.state === "downloading")
52新增: onStatus(`正在下载“${item.name}”,可在侧栏“下载”查看`);
53新增: if (item.state === "saved")
54新增: onStatus(`“${item.name}”已保存到默认工作区的 Downloads`);
3055 }
56新增: if (item.openError && previous.current.get(item.id)?.openError !== item.openError)
57新增: onStatus(`“${item.name}”${item.openError}`);
3158 if (
3259 nativeAvailable() &&
3360 !uploading &&
3461 observed.current.has(item.id) &&
3562 !prompted.current.has(item.id) &&
36删除: (item.state === "saved" || (item.target !== "desktop" && item.state === "failed" && item.retryable))
63新增: (item.state === "saved" ||
64新增: (item.target !== "desktop" &&
65新增: item.state === "failed" &&
66新增: item.retryable))
3767 ) {
3868 prompted.current.add(item.id);
3969 queue.current = queue.current
@@ -41,35 +71,59 @@ export function useDownloadNotifications(
4171 .catch((error) => onStatus(error.message));
4272 }
4373 }
44删除: previous.current = new Map(downloads.map((item) => [item.id, item.state]));
74新增: previous.current = new Map(downloads.map((item) => [item.id, { state: item.state, openError: item.openError }]));
4575 }, [downloads, uploading]);
4676}
4777
48删除:export function useDesktopFiles(ready) {
78新增:export function useDesktopFiles(ready, onStatus) {
79新增: const connection = getClientContext().connection_id;
4980 const [files, setFiles] = useState({ uploads: [], downloads: [] });
81新增: const status = useRef(onStatus);
82新增: status.current = onStatus;
5083 useEffect(() => {
51删除: if (!ready) { setFiles({ uploads: [], downloads: [] }); return; }
52删除: let disposed = false, timer;
84新增: if (!ready) {
85新增: setFiles({ uploads: [], downloads: [] });
86新增: return;
87新增: }
88新增: let disposed = false,
89新增: timer,
90新增: failures = 0;
5391 const poll = async () => {
5492 try {
5593 const value = await api("/input/files/desktop/requests");
56删除: if (!disposed) setFiles({ uploads: value.uploads || [], downloads: value.downloads || [] });
57删除: } catch {
94新增: failures = 0;
95新增: if (!disposed)
96新增: setFiles({
97新增: uploads: value.uploads || [],
98新增: downloads: value.downloads || [],
99新增: });
100新增:
101新增: } catch (error) {
58102 // Closing Desktop invalidates its outstanding file choosers.
59删除: if (!disposed) setFiles((previous) => ({ ...previous, uploads: [] }));
103新增: if (!disposed) {
104新增: setFiles((previous) => ({ ...previous, uploads: [] }));
105新增: if (failures === 0 && error.status !== 409)
106新增: status.current?.(error.message);
107新增: failures++;
108新增: }
60109 }
61删除: if (!disposed) timer = setTimeout(poll, 1500);
110新增: if (!disposed) timer = setTimeout(poll, Math.min(1500 * 2 ** Math.min(failures, 4), 15000));
62111 };
63112 void poll();
64删除: return () => { disposed = true; clearTimeout(timer); };
65删除: }, [ready]);
113新增: return () => {
114新增: disposed = true;
115新增: clearTimeout(timer);
116新增: };
117新增: }, [ready, connection]);
66118 return files;
67119}
68120
69121async function saveDownload(item) {
70122 if (!nativeAvailable()) {
71123 const link = document.createElement("a");
72删除: link.href = runtimeURL(`/browser/files/downloads/${encodeURIComponent(item.id)}/content`);
124新增: link.href = runtimeURL(
125新增: `/browser/files/downloads/${encodeURIComponent(item.id)}/content`,
126新增: );
73127 link.download = item.name;
74128 link.click();
75129 return;
@@ -90,11 +144,65 @@ export function BrowserDownloads({
90144 ready,
91145 onStatus,
92146 sidebar = false,
147新增: menu = false,
148新增: anchorRef,
93149}) {
94150 const remote = isRemoteClient();
151新增: const panelId = useId();
152新增: const trigger = useRef(),
153新增: panel = useRef();
95154 const [open, setOpen] = useState(false),
96155 [retrying, setRetrying] = useState("");
97156 const [saved, setSaved] = useState([]);
157新增: useLayoutEffect(() => {
158新增: if (!open) return;
159新增: const content = panel.current;
160新增: if (!content) return;
161新增: const anchor = anchorRef?.current || trigger.current;
162新增: const restoreFocus = () => {
163新增: setOpen(false);
164新增: anchor?.focus();
165新增: };
166新增: const position = () => {
167新增: const toolbar = anchor?.closest(".navigation-row");
168新增: const bounds = toolbar?.getBoundingClientRect();
169新增: const width = content.getBoundingClientRect().width;
170新增: const top = Math.min(
171新增: bounds ? bounds.bottom + 8 : 56,
172新增: Math.max(12, window.innerHeight - 160),
173新增: );
174新增: content.style.top = `${top}px`;
175新增: content.style.left = `${Math.max(12, Math.min((bounds?.right || window.innerWidth) - width - 12, window.innerWidth - width - 12))}px`;
176新增: content.style.maxHeight = `${Math.max(0, window.innerHeight - top - 12)}px`;
177新增: };
178新增: position();
179新增: content.querySelector("button")?.focus();
180新增: const dismiss = (event) => {
181新增: if (
182新增: !content.contains(event.target) &&
183新增: !anchor?.contains(event.target)
184新增: )
185新增: setOpen(false);
186新增: };
187新增: const key = (event) => {
188新增: if (event.key !== "Escape") return;
189新增: event.preventDefault();
190新增: event.stopPropagation();
191新增: restoreFocus();
192新增: };
193新增: document.addEventListener("pointerdown", dismiss);
194新增: document.addEventListener("focusin", dismiss);
195新增: document.addEventListener("keydown", key, true);
196新增: document.addEventListener("cage-close-modal", restoreFocus);
197新增: window.addEventListener("resize", position);
198新增: return () => {
199新增: document.removeEventListener("pointerdown", dismiss);
200新增: document.removeEventListener("focusin", dismiss);
201新增: document.removeEventListener("keydown", key, true);
202新增: document.removeEventListener("cage-close-modal", restoreFocus);
203新增: window.removeEventListener("resize", position);
204新增: };
205新增: }, [open, anchorRef]);
98206 useEffect(() => {
99207 const refresh = () =>
100208 api("/browser/files/saved")
@@ -107,13 +215,20 @@ export function BrowserDownloads({
107215 const items = downloads.map((item) => {
108216 const local = saved.find((entry) => entry.id === item.id);
109217 return local
110删除: ? { ...item, ...local, localSaved: true, state: "saved", retryable: false, error: "" }
218新增: ? {
219新增: ...item,
220新增: ...local,
221新增: localSaved: true,
222新增: state: "saved",
223新增: retryable: false,
224新增: error: "",
225新增: }
111226 : item;
112227 });
113228 for (const item of saved)
114229 if (!items.some((entry) => entry.id === item.id))
115230 items.push({ ...item, localSaved: true, state: "saved" });
116删除: const failed = items.some((item) => item.state === "failed");
231新增: const failed = items.some((item) => item.state === "failed" || item.openError);
117232 const labels = {
118233 downloading: "正在下载",
119234 saving: remote ? "正在保存到云端" : "正在保存到本机",
@@ -124,101 +239,189 @@ export function BrowserDownloads({
124239 return (
125240 <>
126241 <button
242新增: ref={trigger}
127243 className={
128删除: sidebar ? "sidebar-link" : "icon-button browser-download-button"
244新增: sidebar
245新增: ? "sidebar-link"
246新增: : menu
247新增: ? "browser-menu-item browser-download-button"
248新增: : "icon-button browser-download-button"
129249 }
250新增: role={menu ? "menuitem" : undefined}
130251 aria-label={sidebar ? "下载文件" : "浏览器下载"}
131删除: title={failed ? "有下载未能保存,点击查看" : "下载文件"}
132删除: onClick={() => setOpen(true)}
252新增: aria-haspopup="dialog"
253新增: aria-expanded={open}
254新增: aria-controls={open ? panelId : undefined}
255新增: title={failed ? "有下载需要处理,点击查看" : "下载文件"}
256新增: onClick={() => setOpen((value) => !value)}
133257 >
134删除: {failed ? <CircleAlert size={16} /> : <ArrowDownToLine size={16} />}
135删除: {sidebar && "下载"}
258新增: {sidebar && failed ? <CircleAlert size={16} /> : <ArrowDownToLine size={16} />}
259新增: {failed && !sidebar && !menu && <span className="browser-download-warning" aria-hidden="true" />}
260新增: {(sidebar || menu) && <span>下载</span>}
136261 </button>
137262 {open &&
138263 createPortal(
139删除: <Modal title="下载文件" onClose={() => setOpen(false)}>
264新增: <section
265新增: ref={panel}
266新增: id={panelId}
267新增: className="browser-download-panel"
268新增: role="dialog"
269新增: aria-label="下载文件"
270新增: data-browser-dialog
271新增: >
272新增: <header className="browser-download-heading">
273新增: <h2>下载</h2>
274新增: <button
275新增: className="icon-button"
276新增: aria-label="关闭面板"
277新增: title="关闭下载"
278新增: onClick={() => {
279新增: setOpen(false);
280新增: (anchorRef?.current || trigger.current)?.focus();
281新增: }}
282新增: >
283新增: <X size={17} />
284新增: </button>
285新增: </header>
140286 <div className="browser-download-list">
141287 {!items.length && (
142删除: <p>
143删除: 暂无下载。下载完成后可另存为到本机;取消时,原文件仍保留在{remote ? "云端" : ""}默认工作区的
144删除: Downloads 文件夹。
145删除: </p>
288新增: <div className="browser-download-empty">
289新增: <ArrowDownToLine size={28} />
290新增: <strong>暂无下载</strong>
291新增: <p>下载的文件会显示在这里。</p>
292新增: </div>
146293 )}
147294 {items.map((item) => (
148295 <article key={item.id} className="browser-download-item">
149删除: <strong>{item.name}</strong>
150删除: <p>
151删除: {item.localSaved ? "已保存到本机" : labels[item.state] || "状态待确认"}
152删除: {item.state === "downloading" &&
153删除: item.totalBytes > 0 &&
154删除: ` · ${Math.min(100, Math.floor((item.receivedBytes / item.totalBytes) * 100))}%`}
155删除: </p>
156删除: {item.path && <p className="download-path">{remote ? item.localSaved ? "本机:" : "云端:" : ""}{item.path}</p>}
157删除: {item.error && <p role="status">{item.error}</p>}
158删除: {(item.state === "saved" || (item.target !== "desktop" && item.retryable)) && (
159删除: <div className="download-actions">
160删除: <button
161删除: disabled={Boolean(retrying)}
162删除: onClick={async () => {
163删除: setRetrying(item.id);
164删除: try {
165删除: await saveDownload(item);
166删除: } catch (error) {
167删除: onStatus(error.message);
168删除: } finally {
169删除: setRetrying("");
170删除: }
171删除: }}
172删除: >
173删除: {retrying === item.id ? "正在保存…" : "另存为…"}
174删除: </button>
175删除: {nativeAvailable() &&
176删除: item.state === "saved" &&
177删除: (!remote || item.localSaved) &&
178删除: [
179删除: ["open", "打开文件"],
180删除: ["reveal", "在文件夹中显示"],
181删除: ].map(([operation, label]) => (
296新增: <File
297新增: size={22}
298新增: className="browser-download-file-icon"
299新增: aria-hidden="true"
300新增: />
301新增: <div className="browser-download-content">
302新增: <strong title={item.name}>{item.name}</strong>
303新增: <p className="download-status">
304新增: <span className="download-state">
305新增: {item.localSaved
306新增: ? "已保存到本机"
307新增: : labels[item.state] || "状态待确认"}
308新增: {item.state === "downloading" &&
309新增: item.totalBytes > 0 &&
310新增: ` · ${Math.min(100, Math.floor((item.receivedBytes / item.totalBytes) * 100))}%`}
311新增: </span>
312新增: {item.path && (
313新增: <span className="download-path" title={item.path}>
314新增: {remote
315新增: ? item.localSaved
316新增: ? "本机:"
317新增: : "云端:"
318新增: : ""}
319新增: {item.path}
320新增: </span>
321新增: )}
322新增: </p>
323新增: {item.state === "downloading" && (
324新增: <progress
325新增: aria-label={`${item.name} 下载进度`}
326新增: value={
327新增: item.totalBytes > 0 ? item.receivedBytes : undefined
328新增: }
329新增: max={item.totalBytes > 0 ? item.totalBytes : 1}
330新增: />
331新增: )}
332新增: {item.error && <p role="status">{item.error}</p>}
333新增: {item.openError && <p role="status">{item.openError}</p>}
334新增: {(item.state === "saved" || item.retryable) && (
335新增: <div className="download-actions">
336新增: {(item.state === "saved" ||
337新增: item.target !== "desktop") && (
182338 <button
183删除: key={operation}
339新增: className="download-text-action"
340新增: disabled={Boolean(retrying)}
184341 onClick={async () => {
342新增: setRetrying(item.id);
185343 try {
186删除: await native("browserDownloadAction", {
187删除: operation,
188删除: id: item.id,
189删除: });
344新增: await saveDownload(item);
190345 } catch (error) {
191346 onStatus(error.message);
347新增: } finally {
348新增: setRetrying("");
192349 }
193350 }}
194351 >
195删除: {label}
352新增: <Save size={13} />
353新增: {retrying === item.id ? "正在保存…" : "另存为…"}
196354 </button>
197删除: ))}
198删除: </div>
199删除: )}
200删除: {item.retryable && (
201删除: <button
202删除: disabled={!ready || Boolean(retrying)}
203删除: onClick={async () => {
204删除: setRetrying(item.id);
205删除: try {
206删除: await api(item.target === "desktop" ? "/input/files/download-retry" : "/browser/download-retry",
207删除: { id: item.id, ...(item.target === "desktop" ? { target: "desktop" } : {}) });
208删除: } catch (error) {
209删除: onStatus(error.message);
210删除: } finally {
211删除: setRetrying("");
212删除: }
213删除: }}
214删除: >
215删除: {retrying === item.id ? "正在重试…" : "重试保存"}
216删除: </button>
217删除: )}
355新增: )}
356新增: {nativeAvailable() &&
357新增: item.state === "saved" &&
358新增: (!remote || item.localSaved) &&
359新增: [
360新增: ["open", "打开文件"],
361新增: ["reveal", "在文件夹中显示"],
362新增: ].map(([operation, label]) => (
363新增: <button
364新增: className={
365新增: operation === "open"
366新增: ? "download-text-action"
367新增: : "icon-button download-reveal"
368新增: }
369新增: key={operation}
370新增: aria-label={label}
371新增: title={label}
372新增: onClick={async () => {
373新增: try {
374新增: await native("browserDownloadAction", {
375新增: operation,
376新增: id: item.id,
377新增: });
378新增: } catch (error) {
379新增: onStatus(error.message);
380新增: }
381新增: }}
382新增: >
383新增: {operation === "reveal" ? (
384新增: <FolderOpen size={16} />
385新增: ) : (
386新增: label
387新增: )}
388新增: </button>
389新增: ))}
390新增: {item.retryable && (
391新增: <button
392新增: className="download-text-action"
393新增: disabled={!ready || Boolean(retrying)}
394新增: onClick={async () => {
395新增: setRetrying(item.id);
396新增: try {
397新增: await api(
398新增: item.target === "desktop"
399新增: ? "/input/files/download-retry"
400新增: : "/browser/download-retry",
401新增: {
402新增: id: item.id,
403新增: ...(item.target === "desktop"
404新增: ? { target: "desktop" }
405新增: : {}),
406新增: },
407新增: );
408新增: } catch (error) {
409新增: onStatus(error.message);
410新增: } finally {
411新增: setRetrying("");
412新增: }
413新增: }}
414新增: >
415新增: {retrying === item.id ? "正在重试…" : "重试保存"}
416新增: </button>
417新增: )}
418新增: </div>
419新增: )}
420新增: </div>
218421 </article>
219422 ))}
220423 </div>
221删除: </Modal>,
424新增: </section>,
222425 document.body,
223426 )}
224427 </>
新增ui/src/browser-extensions.jsx+157 −0看文件
@@ -0,0 +1,157 @@
1新增:import React, { useEffect, useRef, useState } from 'react';
2新增:import { Download, ExternalLink, FolderInput, Puzzle, RefreshCw, Trash2, Upload, X } from 'lucide-react';
3新增:import { api, uploadFile } from './api';
4新增:import { assertConnection, getClientContext } from './client-context.mjs';
5新增:import { InlineSelect } from './inline-select';
6新增:
7新增:function Permissions({ item, expanded = false }) {
8新增: const permissions = [...(item.permissions || []), ...(item.hostPermissions || [])];
9新增: return <details className="extension-permissions" open={expanded || undefined}><summary>权限与网站访问{permissions.length ? `(${permissions.length})` : ''}</summary>
10新增: {permissions.length ? <ul>{permissions.map((value, index) => <li key={index}>{value}</li>)}</ul> : <p>未声明额外权限。</p>}</details>;
11新增:}
12新增:
13新增:function LocalExtensionImport({ existing, onUpdated, onClose }) {
14新增: const [profiles, setProfiles] = useState(null), [profileID, setProfileID] = useState('');
15新增: const [selected, setSelected] = useState(new Set()), [results, setResults] = useState({});
16新增: const [busy, setBusy] = useState(false), [error, setError] = useState('');
17新增: const alive = useRef(true);
18新增: useEffect(() => {
19新增: api('/client/browser-extensions').then(data => { if (alive.current) { setProfiles(data.profiles); setProfileID(data.profiles[0]?.id || ''); } })
20新增: .catch(error => { if (alive.current) setError(error.message); });
21新增: return () => { alive.current = false; };
22新增: }, []);
23新增: const profile = profiles?.find(item => item.id === profileID);
24新增: const installed = new Set(existing.map(item => item.source));
25新增: const completed = Object.values(results).some(value => value.startsWith('已导入'));
26新增: const eligible = item => item.compatible && !installed.has(`${profileID}:${item.id}`);
27新增: const importCount = profile?.extensions.filter(item => selected.has(item.id) && eligible(item)).length || 0;
28新增: const choose = value => { setProfileID(value); setSelected(new Set()); setResults({}); setError(''); };
29新增: const importSelected = async () => {
30新增: if (busy || !profile) return;
31新增: const connection = getClientContext().connection_id;
32新增: setBusy(true); setError('');
33新增: for (const item of profile.extensions.filter(item => selected.has(item.id) && eligible(item))) {
34新增: let pending;
35新增: try {
36新增: assertConnection(connection);
37新增: if (!alive.current) break;
38新增: setResults(previous => ({ ...previous, [item.id]: '正在导入…' }));
39新增: const response = await fetch('/api/client/browser-extensions', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ profile: profileID, id: item.id, version: item.version }) });
40新增: if (!response.ok) throw new Error((await response.text()).trim());
41新增: const file = new File([await response.blob()], item.id + '.zip', { type: 'application/zip' });
42新增: assertConnection(connection);
43新增: if (!alive.current) break;
44新增: pending = await uploadFile('/browser/extensions/upload', file);
45新增: assertConnection(connection);
46新增: if (!alive.current) throw new Error('导入已停止');
47新增: const next = await api('/browser/extensions', { mode: 'install', session: pending.session, target: `${profileID}:${item.id}`, enabled: item.state_known && item.enabled });
48新增: pending = null;
49新增: if (alive.current) { onUpdated(next.items); setResults(previous => ({ ...previous, [item.id]: item.state_known && item.enabled ? '已导入并启用' : '已导入,保持停用' })); }
50新增: } catch (error) {
51新增: if (pending && getClientContext().connection_id === connection) await api('/browser/extensions', { mode: 'cancel', session: pending.session }).catch(() => {});
52新增: if (alive.current) setResults(previous => ({ ...previous, [item.id]: '导入失败:' + error.message }));
53新增: if (getClientContext().connection_id !== connection) break;
54新增: }
55新增: }
56新增: if (alive.current) setBusy(false);
57新增: };
58新增: return <section className="extension-import" aria-label="从本机导入扩展">
59新增: <div className="browser-setting-heading"><h3>从本机浏览器导入</h3><button className="icon-button" aria-label="关闭本机导入" disabled={busy} onClick={onClose}><X size={16} /></button></div>
60新增: <p>一次复制所选扩展及启停状态。浏览器账户、Cookie 和扩展登录数据保留在本机浏览器中。</p>
61新增: {error && <p className="browser-settings-error" role="alert">{error}</p>}
62新增: {!profiles && !error && <p role="status">正在查找本机浏览器配置…</p>}
63新增: {profiles?.length === 0 && <p>未找到 Edge、Chrome、Brave 或 Chromium 的扩展配置。</p>}
64新增: {Boolean(profiles?.length) && <>
65新增: <label className="browser-setting-field">本机浏览器配置<InlineSelect aria-label="本机浏览器配置" value={profileID} disabled={busy} onValueChange={choose}>
66新增: {profiles.map(item => <option value={item.id} key={item.id}>{item.browser} · {item.name}</option>)}
67新增: </InlineSelect></label>
68新增: <div className="extension-import-actions"><button disabled={busy} onClick={() => setSelected(new Set(profile?.extensions.filter(eligible).map(item => item.id)))}>选择全部兼容扩展</button>
69新增: {completed && !busy && !importCount ? <button className="primary" onClick={onClose}>完成并关闭</button> : <button className="primary" disabled={busy || !importCount} onClick={importSelected}><Download size={15} />{busy ? '正在导入…' : `导入所选扩展(${importCount})`}</button>}</div>
70新增: {!profile?.extensions.length && <p>此配置没有可读取的扩展。</p>}
71新增: {profile?.extensions.map(item => <article className="extension-import-row" key={item.id}>
72新增: <label><input type="checkbox" disabled={busy || !eligible(item)} checked={selected.has(item.id)} onChange={event => setSelected(previous => { const next = new Set(previous); if (event.target.checked) next.add(item.id); else next.delete(item.id); return next; })} />
73新增: <strong>{item.name}</strong><span>{item.version}</span></label>
74新增: <p className="extension-import-state" role={results[item.id] ? 'status' : undefined}>{results[item.id] || (!item.compatible ? '不支持此扩展版本,仅支持 Manifest V3' : installed.has(`${profileID}:${item.id}`) ? '已导入' : !item.state_known ? '未能读取启停状态,导入后停用' : item.enabled ? '本机已启用' : '本机已停用')}</p>
75新增: {item.compatible && !item.identity_preserved && <p>此扩展的标识可能变化,依赖浏览器身份或授权的功能可能需要重新配置。</p>}
76新增: <Permissions item={item} />
77新增: </article>)}
78新增: </>}
79新增: </section>;
80新增:}
81新增:
82新增:export function BrowserExtensions({ onOpenPage, onInternal, onConfirm }) {
83新增: const [items, setItems] = useState(null), [error, setError] = useState(''), [busy, setBusy] = useState('');
84新增: const [preview, setPreview] = useState(null), [importing, setImporting] = useState(false);
85新增: const file = useRef(), alive = useRef(true), pending = useRef(null);
86新增: const connection = useRef(getClientContext().connection_id);
87新增: const load = async () => {
88新增: setError('');
89新增: try { const result = await api('/browser/extensions', { mode: 'list' }); if (alive.current) setItems(result.items); }
90新增: catch (error) { if (alive.current) setError(error.message); }
91新增: };
92新增: useEffect(() => {
93新增: void load();
94新增: return () => { alive.current = false; if (pending.current && getClientContext().connection_id === connection.current) void api('/browser/extensions', { mode: 'cancel', session: pending.current }).catch(() => {}); };
95新增: }, []);
96新增: const select = async event => {
97新增: const selected = event.target.files?.[0]; event.target.value = '';
98新增: if (!selected) return;
99新增: if (selected.size > 32 << 20) { setError('扩展 ZIP 不能超过 32 MB'); return; }
100新增: setBusy('upload'); setError('');
101新增: try {
102新增: const result = await uploadFile('/browser/extensions/upload', selected);
103新增: if (!alive.current) { if (getClientContext().connection_id === connection.current) await api('/browser/extensions', { mode: 'cancel', session: result.session }); return; }
104新增: pending.current = result.session; setPreview(result);
105新增: } catch (error) { if (alive.current) setError(error.message); }
106新增: finally { if (alive.current) setBusy(''); }
107新增: };
108新增: const act = async (mode, id) => {
109新增: if (busy) return;
110新增: if (mode === 'remove' && !(await onConfirm({ title: '移除此扩展?', body: '扩展将从 Cage 浏览器中移除。本机 Edge 或 Chrome 中的扩展保持原状。', confirm: '移除扩展' }))) return;
111新增: setBusy(id || mode); setError('');
112新增: try {
113新增: const result = await api('/browser/extensions', { mode, id, ...(mode === 'install' ? { session: preview.session } : {}) });
114新增: if (mode === 'install' || mode === 'cancel') { pending.current = null; setPreview(null); }
115新增: if (result.native) await onInternal('extensions', result.id);
116新增: else if (result.id && result.url) await onOpenPage(result);
117新增: else if (result.items) setItems(result.items);
118新增: } catch (error) { setError(error.message); }
119新增: finally { setBusy(''); }
120新增: };
121新增: const cancel = async () => {
122新增: setBusy('cancel'); setError('');
123新增: try { await api('/browser/extensions', { mode: 'cancel', session: preview.session }); pending.current = null; setPreview(null); }
124新增: catch (error) { setError(error.message); }
125新增: finally { setBusy(''); }
126新增: };
127新增: return <div className="browser-extensions">
128新增: <div className="browser-setting-actions">
129新增: <button className="primary" disabled={Boolean(busy || preview)} onClick={() => file.current?.click()}><Upload size={15} />添加 ZIP 扩展</button>
130新增: <button disabled={Boolean(busy || preview)} onClick={() => setImporting(true)}><FolderInput size={15} />从本机导入</button>
131新增: <button aria-label="刷新扩展" disabled={Boolean(busy)} onClick={load}><RefreshCw size={15} /></button>
132新增: </div>
133新增: <input ref={file} type="file" accept=".zip,application/zip" hidden onChange={select} aria-label="选择扩展 ZIP" />
134新增: <p>支持 Chromium Manifest V3 扩展。扩展运行在 Cage 环境中,并按声明的权限访问网站。</p>
135新增: {error && <p className="browser-settings-error" role="alert">{error}</p>}
136新增: {busy === 'upload' && <p role="status">正在读取扩展包…</p>}
137新增: {preview && <section className="extension-install-preview" aria-label="确认扩展安装">
138新增: <h3>确认安装 {preview.name}</h3><p>版本 {preview.version}</p><p>{preview.description}</p>
139新增: <Permissions item={preview} expanded />
140新增: <div className="browser-setting-actions"><button className="primary" disabled={Boolean(busy)} onClick={() => act('install')}>安装扩展</button><button disabled={Boolean(busy)} onClick={cancel}>取消</button></div>
141新增: </section>}
142新增: {importing && <LocalExtensionImport existing={items || []} onUpdated={setItems} onClose={() => setImporting(false)} />}
143新增: <div className="browser-setting-heading"><h3>已安装的扩展{items ? `(${items.length})` : ''}</h3></div>
144新增: {items === null && !error ? <p role="status">正在读取扩展…</p> : items?.length === 0 ? <div className="extension-empty"><Puzzle size={28} /><strong>让浏览器更合用</strong><p>添加扩展,或从本机浏览器导入已有扩展。</p></div> : items?.map(item => <article className="extension-item" key={item.id}>
145新增: <div className="browser-setting-heading"><div><strong>{item.name}</strong><span className="extension-version">{item.version}</span></div>
146新增: <label className="extension-enable"><input type="checkbox" aria-label={`启用 ${item.name}`} checked={Boolean(item.enabled)} disabled={Boolean(busy) || item.mayDisable === false} onChange={() => act(item.enabled ? 'disable' : 'enable', item.id)} />{item.enabled ? '已启用' : '已停用'}</label></div>
147新增: {item.description && <p>{item.description}</p>}{item.error && <p role="alert" className="browser-settings-error">{item.error}</p>}
148新增: <Permissions item={item} />
149新增: <div className="extension-item-footer"><span>{item.id}</span><div className="browser-setting-actions">
150新增: {item.optionsUrl && <button disabled={Boolean(busy) || !item.enabled} onClick={() => act('options', item.id)}>扩展选项</button>}
151新增: <button disabled={Boolean(busy) || item.mayDisable === false} onClick={() => act('remove', item.id)}><Trash2 size={14} />{item.managed ? '移除' : '管理'}</button>
152新增: </div></div>
153新增: </article>)}
154新增: <div className="browser-settings-links"><button onClick={() => onInternal('extensions')}><ExternalLink size={15} />Chromium 扩展管理</button>
155新增: <button onClick={() => onOpenPage({ url: 'https://chromewebstore.google.com/', kind: 'web' })}><ExternalLink size={15} />打开扩展商店</button></div>
156新增: </div>;
157新增:}
修改ui/src/browser-favorites.jsx+13 −6看文件
@@ -16,7 +16,7 @@ import { Modal } from "./views";
1616
1717// The saved page is primary, folder context secondary, management actions quiet.
1818// Reuse paper/strong/muted/line tokens, 8/12/16px spacing and existing modal forms.
19删除:export function BrowserFavorites({ current, ready, onOpen, shortcuts = true }) {
19新增:export function BrowserFavorites({ current, ready, onOpen, shortcuts = true, menu = false, returnFocusRef }) {
2020 const [data, setData] = useState(null);
2121 const [open, setOpen] = useState(false);
2222 const [editor, setEditor] = useState(null);
@@ -99,9 +99,9 @@ export function BrowserFavorites({ current, ready, onOpen, shortcuts = true }) {
9999 document.addEventListener("keydown", key);
100100 return () => {
101101 document.removeEventListener("keydown", key);
102删除: toggle.current?.focus();
102新增: (returnFocusRef?.current || toggle.current)?.focus();
103103 };
104删除: }, [open]);
104新增: }, [open, returnFocusRef]);
105105 const mutation = async (body) => {
106106 const next = await api("/favorites", body);
107107 setData(next);
@@ -171,23 +171,30 @@ export function BrowserFavorites({ current, ready, onOpen, shortcuts = true }) {
171171 <>
172172 <div className="favorites-actions">
173173 <button
174删除: className={`icon-button favorite-star ${favorite ? "saved" : ""}`}
174新增: className={`${menu ? "browser-menu-item" : "icon-button"} favorite-star ${favorite ? "saved" : ""}`}
175新增: role={menu ? "menuitem" : undefined}
175176 aria-label={favorite ? "编辑此页收藏" : "收藏此页"}
176177 title={shortcut(favorite ? "编辑此页收藏 ⌘D" : "收藏此页 ⌘D")}
177178 disabled={!canSave || !data}
178删除: onClick={addCurrent}
179新增: onClick={(event) => {
180新增: event.currentTarget.focus();
181新增: addCurrent();
182新增: }}
179183 >
180184 <Star size={17} fill={favorite ? "currentColor" : "none"} />
185新增: {menu && <span>{favorite ? "编辑此页收藏" : "收藏此页"}</span>}
181186 </button>
182187 <button
183188 ref={toggle}
184删除: className="icon-button"
189新增: className={menu ? "browser-menu-item" : "icon-button"}
190新增: role={menu ? "menuitem" : undefined}
185191 aria-label="收藏夹"
186192 title={shortcut("收藏夹 ⌘⇧O")}
187193 aria-expanded={open}
188194 onClick={() => (open ? setOpen(false) : show())}
189195 >
190196 <Folder size={17} />
197新增: {menu && <span>收藏夹</span>}
191198 </button>
192199 </div>
193200 {open &&
新增ui/src/browser-settings.css+88 −0看文件
@@ -0,0 +1,88 @@
1新增:.browser-settings-menu-row { margin-top: 4px; padding-top: 4px; border-top: 1px solid var(--line); }
2新增:.browser-settings-page { position: absolute; inset: 0; display: flex; flex-direction: column; overflow: auto; background: var(--paper); color: var(--strong); font-size: 1rem; }
3新增:.browser-settings-top { display: flex; flex: none; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 16px; padding: 24px 28px 20px; border-bottom: 1px solid var(--line); }
4新增:.browser-settings-top h1 { font-size: 1.7rem; margin: 0; letter-spacing: -.025em; }
5新增:.browser-settings-search { display: flex; align-items: center; gap: 8px; width: min(330px, 100%); border: 1px solid var(--line); border-radius: 6px; padding: 0 10px; color: var(--muted); background: var(--paper); }
6新增:.browser-settings-search input { width: 100%; min-width: 0; border: 0; background: transparent; padding: 9px 0; color: var(--strong); font: inherit; outline-offset: 3px; }
7新增:.browser-settings-layout { display: flex; align-items: flex-start; min-height: 0; flex: 1; }
8新增:.browser-settings-nav { width: 190px; flex: none; display: grid; gap: 3px; padding: 18px 10px; position: sticky; top: 0; }
9新增:.browser-settings-nav button { display: flex; align-items: center; gap: 10px; padding: 11px 12px; border: 0; background: transparent; text-align: left; color: var(--muted); border-radius: 6px; font: inherit; transition: background 120ms, color 120ms; }
10新增:.browser-settings-nav button svg { flex: none; }
11新增:.browser-settings-nav button[aria-current="page"] { background: var(--selected); color: var(--strong); font-weight: 600; }
12新增:.browser-settings-nav button:hover { background: var(--hover); color: var(--strong); }
13新增:.settings-unsaved-dot { width: 6px; height: 6px; border-radius: 50%; background: var(--focus); margin-left: auto; }
14新增:.browser-settings-content { min-width: 0; width: min(100%, 820px); padding: 28px 32px 48px; }
15新增:.browser-settings-section { min-width: 0; margin-bottom: 36px; animation: browser-settings-enter 140ms ease-out; }
16新增:.browser-settings-section h2 { font-size: 1.5rem; font-weight: 600; margin: 0 0 12px; letter-spacing: -.025em; }
17新增:.browser-settings-section h3 { font-size: 1rem; margin: 0; font-weight: 600; }
18新增:.browser-settings-section p { margin: 9px 0 16px; color: var(--muted); line-height: 1.65; overflow-wrap: anywhere; }
19新增:.browser-setting-form { margin-top: 28px; display: grid; gap: 12px; }
20新增:.browser-setting-field { display: grid; gap: 10px; min-width: 0; font-weight: 600; }
21新增:.browser-setting-field input, .browser-setting-field .inline-select { width: 100%; min-width: 0; font-weight: 400; }
22新增:.browser-setting-field input { padding: 10px 12px; font: inherit; background: var(--paper); color: var(--strong); border: 1px solid var(--line); border-radius: 6px; }
23新增:.browser-setting-actions, .browser-settings-links, .extension-import-actions { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; }
24新增:.browser-setting-actions button, .browser-settings-links button, .extension-import-actions button { display: inline-flex; align-items: center; justify-content: center; gap: 7px; padding: 9px 12px; min-height: 36px; font-size: inherit; }
25新增:.browser-setting-actions [role="status"] { color: var(--muted); }
26新增:.browser-setting-row { display: flex; align-items: flex-start; justify-content: space-between; flex-wrap: wrap; gap: 16px; padding: 22px 0; border-bottom: 1px solid var(--line); margin-bottom: 18px; }
27新增:.browser-setting-row > div { flex: 1 1 170px; }
28新增:.browser-setting-row > .inline-select { flex: 0 1 170px; min-width: 140px; }
29新增:.browser-setting-row p { margin-bottom: 0; }
30新增:.browser-settings-error { color: var(--danger, #b42318) !important; }
31新增:.browser-settings-links { border-top: 1px solid var(--line); padding-top: 18px; margin-top: 28px; }
32新增:.browser-settings-links button { color: var(--strong); }
33新增:.browser-settings-no-results { padding: 28px 0; }
34新增:.browser-setting-heading { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin: 20px 0 12px; }
35新增:.browser-setting-heading > div { min-width: 0; overflow-wrap: anywhere; }
36新增:.browser-settings-section .browser-cookies { margin: 0; font-size: 1rem; border: 0; border-radius: 0; padding: 0; }
37新增:.browser-settings-section .cookie-list { max-height: 300px; }
38新增:.browser-settings-section .cookie-toolbar { gap: 8px; }
39新增:.extension-item, .extension-install-preview, .extension-import { border: 1px solid var(--line); border-radius: 8px; padding: 18px; margin-top: 16px; min-width: 0; }
40新增:.extension-item .browser-setting-heading { margin-top: 0; flex-wrap: wrap; }
41新增:.extension-version { display: inline-block; margin-left: 9px; color: var(--muted); font-size: .92rem; }
42新增:.extension-enable { display: inline-flex; align-items: center; gap: 7px; color: var(--muted); white-space: nowrap; }
43新增:.extension-enable input, .extension-import-row input { accent-color: var(--focus); width: 16px; height: 16px; flex: none; }
44新增:.extension-permissions { margin: 12px 0; color: var(--muted); }
45新增:.extension-permissions summary { cursor: pointer; color: var(--strong); padding: 4px 0; }
46新增:.extension-permissions ul { margin: 8px 0; padding-left: 22px; max-height: 180px; overflow: auto; overflow-wrap: anywhere; line-height: 1.6; }
47新增:.extension-item-footer { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 12px; }
48新增:.extension-item-footer > span { font-size: .85rem; color: var(--muted); overflow-wrap: anywhere; }
49新增:.extension-empty { display: grid; justify-items: start; gap: 12px; padding: 24px 0 12px; color: var(--muted); }
50新增:.extension-empty strong { color: var(--strong); font-size: 1.15rem; }
51新增:.extension-empty p { margin: 0; }
52新增:.extension-import .browser-setting-heading { margin-top: 0; }
53新增:.extension-import-actions { justify-content: space-between; margin: 18px 0; }
54新增:.extension-import-row { border-top: 1px solid var(--line); padding-top: 16px; margin-top: 16px; }
55新增:.extension-import-row > label { display: flex; align-items: flex-start; flex-wrap: wrap; gap: 8px; overflow-wrap: anywhere; }
56新增:.extension-import-row > label > span { color: var(--muted); }
57新增:.extension-import-row p { margin-bottom: 8px; }
58新增:@keyframes browser-settings-enter { from { opacity: 0; transform: translateY(3px); } to { opacity: 1; transform: none; } }
59新增:@media (max-width: 1000px) {
60新增: .browser-settings-top { padding: 20px; }
61新增: .browser-settings-nav { width: 156px; padding: 16px 8px; }
62新增: .browser-settings-nav button { padding: 10px 8px; gap: 7px; }
63新增: .browser-settings-content { padding: 24px 20px 36px; }
64新增:}
65新增:@media (prefers-reduced-motion: reduce) {
66新增: .browser-settings-section { animation: none; }
67新增: .browser-settings-nav button { transition: none; }
68新增:}
69新增:/* Browser settings also fit beside Cage's sidebar and vertical browser tabs. */
70新增:.browser-lane { container: cage-browser / inline-size; }
71新增:.browser-settings-nav button { justify-content: flex-start; white-space: normal; }
72新增:@container cage-browser (max-width: 760px) {
73新增: .browser-settings-layout { display: block; }
74新增: .browser-settings-nav { width: 100%; display: flex; flex-wrap: wrap; gap: 4px; padding: 12px 16px; position: static; border-bottom: 1px solid var(--line); }
75新增: .browser-settings-nav button { padding: 8px 10px; max-width: 100%; }
76新增: .browser-settings-content { width: 100%; padding: 22px 20px 36px; }
77新增: .browser-settings-top { padding: 18px 20px; }
78新增: .browser-settings-search { min-width: 0; }
79新增:}
80新增:.browser-settings-compact-nav { display: none; }
81新增:@container cage-browser (max-width: 450px) {
82新增: .browser-settings-nav { display: none; }
83新增: .browser-settings-compact-nav { display: block; padding: 12px 20px; border-bottom: 1px solid var(--line); }
84新增: .browser-settings-compact-nav > .inline-select { width: 100%; }
85新增: .browser-settings-top { padding: 12px 20px; gap: 12px; }
86新增: .browser-settings-top h1 { font-size: 1.35rem; }
87新增: .browser-settings-content { padding-top: 18px; }
88新增:}
新增ui/src/browser-settings.jsx+70 −0看文件
@@ -0,0 +1,70 @@
1新增:import React, { useEffect, useState } from 'react';
2新增:import { Globe2, Info, LayoutPanelLeft, Puzzle, Search, ShieldCheck, ExternalLink } from 'lucide-react';
3新增:import { api } from './api';
4新增:import { InlineSelect } from './inline-select';
5新增:import { BrowserCookies } from './browser-cookies';
6新增:import { BrowserExtensions } from './browser-extensions';
7新增:import './browser-settings.css';
8新增:
9新增:const sections = [
10新增: { id: 'general', title: '新标签页', icon: Globe2, search: '启动 新标签页 主页 默认 地址 网址' },
11新增: { id: 'appearance', title: '外观', icon: LayoutPanelLeft, search: '外观 标签栏 布局 横排 竖排' },
12新增: { id: 'privacy', title: '隐私与网站数据', icon: ShieldCheck, search: '隐私 cookie 网站数据 权限 清除 浏览记录' },
13新增: { id: 'extensions', title: '扩展', icon: Puzzle, search: '扩展 插件 管理 安装 导入 edge chrome' },
14新增: { id: 'about', title: '关于浏览器', icon: Info, search: '关于 浏览器 chromium 版本' },
15新增:];
16新增:export function BrowserSettingsPage({ tab, tabs, currentHome, layout, onLayoutChange, onSaved, onInternal, onOpenPage, onConfirm, onSectionChange }) {
17新增: const [section, setSection] = useState(tab.url.split('#')[1] || 'general'), [query, setQuery] = useState('');
18新增: const [home, setHome] = useState(currentHome || 'https://www.bing.com/'), [savedHome, setSavedHome] = useState(currentHome || 'https://www.bing.com/');
19新增: const [saving, setSaving] = useState(false), [error, setError] = useState(''), [saved, setSaved] = useState(false);
20新增: const [loading, setLoading] = useState(true);
21新增: const [cookieSession, setCookieSession] = useState('normal');
22新增: const [info, setInfo] = useState(null);
23新增: useEffect(() => { let live = true; api('/browser/info', {}).then(value => { if (live) setInfo(value); }).catch(() => { if (live) setInfo({ error: true }); }); return () => { live = false; }; }, []);
24新增: useEffect(() => { const next = tab.url.split('#')[1]; if (sections.some(item => item.id === next)) { setSection(next); setQuery(''); } }, [tab.url]);
25新增: useEffect(() => {
26新增: let live = true;
27新增: api('/browser/preferences').then(result => { if (live) { setHome(result.browser_home_url); setSavedHome(result.browser_home_url); } }).catch(error => { if (live) setError(error.message); }).finally(() => { if (live) setLoading(false); });
28新增: return () => { live = false; };
29新增: }, []);
30新增: const changeSection = id => { setSection(id); setQuery(''); onSectionChange?.(id); };
31新增: const save = async event => {
32新增: event.preventDefault(); setSaving(true); setError(''); setSaved(false);
33新增: try { const result = await api('/browser/preferences', { browser_home_url: home }); setHome(result.browser_home_url); setSavedHome(result.browser_home_url); setSaved(true); onSaved(result); }
34新增: catch (error) { setError(error.message); }
35新增: finally { setSaving(false); }
36新增: };
37新增: const privateTab = tabs.find(item => item.incognito && !item.login);
38新增: const cookieTab = cookieSession === 'private' && privateTab ? privateTab : tab;
39新增: const visible = query.trim() ? sections.filter(item => `${item.title} ${item.search}`.toLowerCase().includes(query.trim().toLowerCase())) : sections.filter(item => item.id === section);
40新增: return <section className="browser-settings-page" aria-label="浏览器设置">
41新增: <header className="browser-settings-top"><h1>设置</h1><label className="browser-settings-search"><Search size={16} /><input aria-label="搜索浏览器设置" placeholder="搜索设置" value={query} onChange={event => setQuery(event.target.value)} /></label></header>
42新增: <div className="browser-settings-layout">
43新增: <nav className="browser-settings-nav" aria-label="浏览器设置分类">{sections.map(({ id, title, icon: Icon }) => <button key={id} aria-label={title} aria-description={id === 'general' && home !== savedHome ? '有未保存的更改' : undefined} aria-current={!query && section === id ? 'page' : undefined} onClick={() => changeSection(id)}><Icon size={17} /><span>{title}</span>{id === 'general' && home !== savedHome && <span className="settings-unsaved-dot" title="有未保存的更改" />}</button>)}</nav>
44新增: <div className="browser-settings-compact-nav"><InlineSelect aria-label="浏览器设置分类" value={section} onValueChange={changeSection}>
45新增: {sections.map(item => <option value={item.id} key={item.id}>{item.title}</option>)}
46新增: </InlineSelect></div>
47新增: <div className="browser-settings-content">
48新增: {visible.length === 0 && <div className="browser-settings-no-results"><Search size={24} /><h2>没有找到相关设置</h2><p>试试“标签页”“Cookie”或“扩展”。</p></div>}
49新增: {visible.map(item => <section key={item.id} className="browser-settings-section" aria-label={item.title}>
50新增: <h2>{item.title}</h2>
51新增: {item.id === 'general' && <><p>设置打开新网页时访问的网站。</p><form className="browser-setting-form" onSubmit={save}>
52新增: <label className="browser-setting-field">新标签页地址<input type="url" aria-label="新标签页地址" required maxLength={8192} value={home} disabled={saving || loading} spellCheck="false" autoComplete="off" onChange={event => { setHome(event.target.value); setSaved(false); }} /></label>
53新增: <p>普通标签与无痕标签使用同一默认地址。保存后,新建网页立即生效。</p>
54新增: <div className="browser-setting-actions"><button className="primary" disabled={saving || loading || home === savedHome}>{saving ? '正在保存…' : '保存地址'}</button>{saved && <span role="status">已保存</span>}</div>
55新增: {error && <p className="browser-settings-error" role="alert">{error}</p>}
56新增: </form></>}
57新增: {item.id === 'appearance' && <><p>调整网页与文件编辑器的标签栏。</p><div className="browser-setting-row"><div><h3>标签栏布局</h3><p>立即生效,保存在本机。</p></div><InlineSelect aria-label="标签栏布局" value={layout} onValueChange={onLayoutChange}><option value="horizontal">横排(顶部)</option><option value="vertical">竖排(左侧)</option></InlineSelect></div><p>浏览器设置页跟随 Cage 当前的字体与配色。</p></>}
58新增: {item.id === 'privacy' && <><p>管理网站保存在当前浏览会话中的数据和访问权限。</p>
59新增: <div className="browser-setting-row"><div><h3>Cookie 与登录状态</h3><p>普通会话与无痕会话分别管理。</p></div><InlineSelect aria-label="Cookie 浏览会话" value={cookieSession} onValueChange={setCookieSession}><option value="normal">普通会话</option><option value="private" disabled={!privateTab}>无痕会话</option></InlineSelect></div>
60新增: <BrowserCookies key={cookieTab.id} tab={cookieTab} onClose={() => changeSection('general')} />
61新增: <div className="browser-settings-links"><button onClick={() => onInternal('permissions')}><ExternalLink size={15} />网站权限</button><button onClick={() => onInternal('clear')}><ExternalLink size={15} />清除普通会话浏览数据</button></div>
62新增: </>}
63新增: {item.id === 'extensions' && <><p>添加与管理 Cage 浏览器使用的扩展。</p><BrowserExtensions onInternal={onInternal} onOpenPage={onOpenPage} onConfirm={onConfirm} /></>}
64新增: {item.id === 'about' && <><p>Cage 浏览器由环境内的 Chromium 承载。网页、扩展和网站数据随当前 Cage 环境保存。</p><div className="browser-setting-row"><div><h3>浏览器引擎</h3><p>{info?.product || (info?.error ? '版本信息暂时不可用' : '正在读取版本…')}</p></div></div><p>下载文件通过 Cage 保存到默认工作区的 Downloads,可从下载面板另存为。</p></>}
65新增:
66新增: </section>)}
67新增: </div>
68新增: </div>
69新增: </section>;
70新增:}
修改ui/src/claude-accounts.css+12 −0看文件
@@ -28,6 +28,18 @@
2828 min-width: 0;
2929}
3030.claude-add-profile { gap: 8px; }
31新增:.claude-scheduling { margin-bottom: 12px; }
32新增:.claude-scheduling > summary { cursor: pointer; padding: 8px 0; }
33新增:.claude-scheduling[open] { max-height: 45vh; overflow-y: auto; padding-bottom: 8px; }
34新增:.claude-scheduling > label + label { margin-top: 10px; }
35新增:.claude-scheduling > label { display: grid; gap: 5px; font-size: .85rem; }
36新增:.claude-account-order { max-height: 7rem; overflow: auto; }
37新增:.claude-account-order > div { display: flex; gap: 8px; align-items: center; margin-top: 5px; }
38新增:.claude-account-order span { flex: 1; overflow-wrap: anywhere; }
39新增:.claude-handoff-group { display: flex; align-items: end; gap: 8px; margin: 12px 0; }
40新增:.claude-handoff-group label { display: grid; flex: 1; min-width: 0; font-size: .8rem; gap: 4px; }
41新增:.claude-handoff-group input { width: 100%; min-width: 0; }
42新增:.claude-handoff-group button { flex: none; }
3143.claude-profile-rename input { min-width: 0; flex: 1; }
3244.claude-add-profile button { min-height: 40px; flex: none; }
3345.claude-profiles .account-error, .claude-profile-note { margin: 7px 0 0; font-size: 0.85rem; }
修改ui/src/claude-accounts.jsx+47 −4看文件
@@ -1,6 +1,7 @@
11import React, { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
22import { Check, Pencil, Plus, RefreshCw, TerminalSquare, Timer } from "lucide-react";
33import { api } from "./api";
4新增:import { InlineSelect } from "./inline-select";
45import crabIcon from "./claude-account-crab.svg";
56import "./claude-accounts.css";
67
@@ -36,7 +37,7 @@ export function useClaudeAccounts() {
3637 return { accounts: registry?.accounts ?? null, detected: registry?.detected,
3738 detectionStatus: registry?.detection_status, detectionError: registry?.detection_error,
3839 usageRunning: registry?.usage_panel_running, usageUnavailable: registry?.usage_unavailable_reason,
39删除: loginNotice: registry?.login_notice, error, load };
40新增: scheduling: registry?.scheduling || {mode:"balanced",switch_policy:"ask"}, loginNotice: registry?.login_notice, error, load };
4041}
4142
4243const statusLabels = {
@@ -48,6 +49,17 @@ const localTimestamp = new Intl.DateTimeFormat(undefined, {
4849});
4950const timeLabel = (seconds) => localTimestamp.format(seconds * 1000);
5051
52新增:const usageUpdatedAt = (profile) => Math.max(profile.quota?.five_hour?.observed_at || 0,
53新增: profile.quota?.seven_day?.observed_at || 0) || profile.usage_checked_at || 0;
54新增:const ageUnit = (elapsed) => elapsed < 3600 ? 60 : elapsed < 86400 ? 3600 : 86400;
55新增:function relativeTimeLabel(seconds, now) {
56新增: const elapsed = Math.max(0, now - seconds);
57新增: if (elapsed < 60) return "刚刚";
58新增: if (elapsed < 3600) return `${Math.floor(elapsed / 60)}分钟前`;
59新增: if (elapsed < 86400) return `${Math.floor(elapsed / 3600)}小时前`;
60新增: return `${Math.floor(elapsed / 86400)}天前`;
61新增:}
62新增:
5163const QuotaTime = createContext(0);
5264
5365// All rows share a clock. Only quota readings subscribe; a tick doesn't render
@@ -64,6 +76,12 @@ function QuotaClock({ accounts, children }) {
6476 setNow(seconds);
6577 let delay = Infinity;
6678 for (const account of accounts || []) {
79新增: const updated = usageUpdatedAt(account);
80新增: if (updated > 0) {
81新增: const elapsed = Math.max(0, seconds - updated);
82新增: const unit = ageUnit(elapsed);
83新增: delay = Math.min(delay, unit - elapsed % unit);
84新增: }
6785 for (const window of [account.quota?.five_hour, account.quota?.seven_day]) {
6886 const left = window?.resets_at - seconds;
6987 if (left > 0) delay = Math.min(delay, left <= 60 ? 1 : (left - 1) % 60 + 1);
@@ -160,11 +178,12 @@ function ProfileUsage({ quota, state }) {
160178}
161179
162180function UsageNote({ profile, state }) {
163删除: const latestReading = Math.max(profile.quota?.five_hour?.observed_at || 0, profile.quota?.seven_day?.observed_at || 0);
181新增: const now = useContext(QuotaTime);
182新增: const updated = usageUpdatedAt(profile);
164183 return <small className="claude-quota-age">
165184 <span>{usageLabels[state] || "暂无额度信息"}</span>
166删除: {profile.usage_checked_at > 0 && <span>上次查询 {timeLabel(profile.usage_checked_at)}</span>}
167删除: {latestReading > 0 && <span>最近读数 {timeLabel(latestReading)}</span>}
185新增: {updated > 0 && <span>最近更新 <time dateTime={new Date(updated * 1000).toISOString()} title={timeLabel(updated)}>
186新增: {relativeTimeLabel(updated, now)}</time></span>}
168187 </small>;
169188}
170189
@@ -197,6 +216,7 @@ function DetectedProfile({ profile, usageEnvironment, busy, join, perform, chang
197216function ProfileCard({ profile, environment, usageEnvironment, busy, active, defaultActive, perform, change, login, cancelDraft }) {
198217 const [renaming, setRenaming] = useState(false);
199218 const [label, setLabel] = useState("");
219新增: const [group, setGroup] = useState(profile.handoff_group || "");
200220 const displayName = profile.label || profile.email;
201221 const fromTerminal = profile.source === "default";
202222 const savedLabel = label.trim() || profile.email;
@@ -233,6 +253,10 @@ function ProfileCard({ profile, environment, usageEnvironment, busy, active, def
233253 </label>
234254 </div>
235255 <ProfileUsage quota={profile.quota} state={usage.state} />
256新增: <form className="claude-handoff-group" onSubmit={event => { event.preventDefault(); perform(() => change({action:"update",id:profile.id,handoff_group:group})); }}>
257新增: <label>接续分组<input aria-label={`${displayName} 的接续分组`} value={group} maxLength={32} placeholder="未分组,不跨账号接续" onChange={event => setGroup(event.target.value)} /></label>
258新增: <button disabled={busy || group === (profile.handoff_group || "")}>保存分组</button>
259新增: </form>
236260 {active > 0 && <p className="claude-profile-note">{active} 个终端仍在运行{!fromTerminal && ",关闭后可重新登录"}</p>}
237261 {!fromTerminal && defaultActive > 0 && <p className="field-help">
238262 其中 {defaultActive} 个工作终端仍使用普通终端的登录。若普通终端已换号,请重新打开这些会话确认身份。
@@ -327,6 +351,25 @@ export function ClaudeAccountsPanel({ store, running, environmentBusy, tabs, log
327351 <h3>Claude 账号</h3>
328352 <p>将普通终端已登录的订阅加入调度,或单独登录一个新账号。新建 Claude 终端时自动分配。</p>
329353 </div>
354新增: <details className="claude-scheduling">
355新增: <summary>调度设置 · {store.scheduling.mode === "sequential" ? "顺序优先" : "均衡分配"}</summary>
356新增: <label>新会话分配<InlineSelect aria-label="新会话分配" value={store.scheduling.mode} disabled={busy}
357新增: onValueChange={mode => perform(() => load({action:"scheduling",scheduling:{...store.scheduling,mode}}))}>
358新增: <option value="balanced">均衡分配</option><option value="sequential">按列表顺序优先</option>
359新增: </InlineSelect></label>
360新增: <label>新会话切换授权<InlineSelect aria-label="新会话切换授权" value={store.scheduling.switch_policy} disabled={busy}
361新增: onValueChange={switch_policy => perform(() => load({action:"scheduling",scheduling:{...store.scheduling,switch_policy}}))}>
362新增: <option value="ask">每次询问</option><option value="allow">额度耗尽后自动接续</option><option value="wait">始终等待原账号</option>
363新增: </InlineSelect></label>
364新增: <p className="field-help">已有会话保持原账号和授权。自动接续只在限额已确认、原任务可安全停止且目标账号属于同一接续分组时进行;跨账号可能重建缓存。</p>
365新增: {store.scheduling.mode === "sequential" && accounts?.length > 1 && <div className="claude-account-order" aria-label="账号优先顺序">
366新增: {accounts.map((profile,index) => <div key={profile.id}><span>{index+1}. {profile.label || profile.email}</span>
367新增: <button disabled={busy || index===0} aria-label={`提高 ${profile.label} 的优先级`} onClick={() => {
368新增: const order=accounts.map(a=>a.id); [order[index-1],order[index]]=[order[index],order[index-1]];
369新增: perform(() => load({action:"scheduling",scheduling:store.scheduling,order}));
370新增: }}>上移</button></div>)}
371新增: </div>}
372新增: </details>
330373 <div className="claude-add-profile">
331374 <button className="primary" disabled={busy || environmentBusy || !!environment}
332375 onClick={() => perform(() => login())}><Plus size={16} />登录新账号</button>
修改ui/src/claude-desktop.jsx+79 −65看文件
@@ -10,11 +10,84 @@ import {
1010import { BrowserUploads } from "./browser-uploads";
1111import { ProjectDialog } from "./project-dialog";
1212import { api } from "./api";
13新增:import { SafetyMessage } from "./safety-message";
1314import { RemoteView } from "./views";
1415import "./claude-desktop.css";
1516
1617const desktopZooms = [0.75, 0.9, 1, 1.1, 1.25, 1.5];
1718
19新增:export function useDesktopZoom() {
20新增: const [zoom, setZoom] = useState(() => {
21新增: try {
22新增: const value = Number(localStorage.getItem("cage-desktop-zoom"));
23新增: return desktopZooms.includes(value) ? value : 1;
24新增: } catch { return 1; }
25新增: });
26新增: return [zoom, setZoom];
27新增:}
28新增:
29新增:export function DesktopToolbar({ desktop, platform, zoom, setZoom, onConfirm, onStop, busy, refresh, sidebarCollapsed, onExpand, children }) {
30新增: return (
31新增: <header className="claude-desktop-toolbar">
32新增: {sidebarCollapsed && (
33新增: <button
34新增: className="icon-button"
35新增: aria-label="展开侧栏"
36新增: onClick={onExpand}
37新增: >
38新增: <PanelLeftOpen size={17} />
39新增: </button>
40新增: )}
41新增: <Monitor size={18} />
42新增: <strong>Claude Desktop</strong>
43新增: <span className="desktop-version">
44新增: {desktop?.version ? `v${desktop.version}` : platform}
45新增: </span>
46新增: <span className="desktop-toolbar-spacer" />
47新增: {children}
48新增: {desktop?.running && (
49新增: <label className="desktop-display-size">
50新增: 显示大小
51新增: <InlineSelect aria-label="Desktop 显示大小" value={zoom} onValueChange={(next) => {
52新增: const value = Number(next);
53新增: setZoom(value);
54新增: try { localStorage.setItem("cage-desktop-zoom", String(value)); } catch { /* Session-only preference. */ }
55新增: }}>
56新增: {desktopZooms.map((value) => <option key={value} value={value}>{Math.round(value * 100)}%{value === 1 ? "(默认)" : ""}</option>)}
57新增: </InlineSelect>
58新增: </label>
59新增: )}
60新增: {desktop?.running && (
61新增: <button
62新增: className="quiet-button"
63新增: disabled={busy}
64新增: onClick={async () => {
65新增: if (
66新增: await onConfirm({
67新增: title: "关闭 Claude Desktop?",
68新增: body: "请先保存应用内的工作。浏览器和 Cage 终端会继续运行。",
69新增: confirm: "关闭应用",
70新增: })
71新增: )
72新增: onStop();
73新增: }}
74新增: >
75新增: <Power size={15} />
76新增: 关闭应用
77新增: </button>
78新增: )}
79新增: <button
80新增: className="icon-button"
81新增: aria-label="刷新 Claude Desktop 状态"
82新增: disabled={busy}
83新增: onClick={refresh}
84新增: >
85新增: <RefreshCw size={15} />
86新增: </button>
87新增: </header>
88新增: );
89新增:}
90新增:
1891export function ClaudeDesktop({
1992 uploads = [],
2093 status,
@@ -30,12 +103,7 @@ export function ClaudeDesktop({
30103}) {
31104 const [closedChooser, setClosedChooser] = useState("");
32105 const directoryRequest = uploads.find((item) => item.directory && item.id !== closedChooser);
33删除: const [zoom, setZoom] = useState(() => {
34删除: try {
35删除: const value = Number(localStorage.getItem("cage-desktop-zoom"));
36删除: return desktopZooms.includes(value) ? value : 1;
37删除: } catch { return 1; }
38删除: });
106新增: const [zoom, setZoom] = useDesktopZoom();
39107 const [desktop, setDesktop] = useState(null);
40108 const [error, setError] = useState("");
41109 const [statusError, setStatusError] = useState("");
@@ -113,71 +181,17 @@ export function ClaudeDesktop({
113181 await onProjectOpened(workspace);
114182 }}
115183 />}
116删除: <header className="claude-desktop-toolbar">
117删除: {sidebarCollapsed && (
118删除: <button
119删除: className="icon-button"
120删除: aria-label="展开侧栏"
121删除: onClick={onExpand}
122删除: >
123删除: <PanelLeftOpen size={17} />
124删除: </button>
125删除: )}
126删除: <Monitor size={18} />
127删除: <strong>Claude Desktop</strong>
128删除: <span className="desktop-version">
129删除: {desktop?.version ? `v${desktop.version}` : "Linux"}
130删除: </span>
131删除: <span className="desktop-toolbar-spacer" />
132删除: {desktop?.running && (
133删除: <label className="desktop-display-size">
134删除: 显示大小
135删除: <InlineSelect aria-label="Desktop 显示大小" value={zoom} onValueChange={(next) => {
136删除: const value = Number(next);
137删除: setZoom(value);
138删除: try { localStorage.setItem("cage-desktop-zoom", String(value)); } catch { /* Session-only preference. */ }
139删除: }}>
140删除: {desktopZooms.map((value) => <option key={value} value={value}>{Math.round(value * 100)}%{value === 1 ? "(默认)" : ""}</option>)}
141删除: </InlineSelect>
142删除: </label>
143删除: )}
144删除: {desktop?.running && (
145删除: <button
146删除: className="quiet-button"
147删除: disabled={busy}
148删除: onClick={async () => {
149删除: if (
150删除: await onConfirm({
151删除: title: "关闭 Claude Desktop?",
152删除: body: "请先保存应用内的工作。浏览器和 Cage 终端会继续运行。",
153删除: confirm: "关闭应用",
154删除: })
155删除: )
156删除: run("stop");
157删除: }}
158删除: >
159删除: <Power size={15} />
160删除: 关闭应用
161删除: </button>
162删除: )}
163删除: <button
164删除: className="icon-button"
165删除: aria-label="刷新 Claude Desktop 状态"
166删除: disabled={busy}
167删除: onClick={refresh}
168删除: >
169删除: <RefreshCw size={15} />
170删除: </button>
171删除: </header>
184新增: <DesktopToolbar desktop={desktop} platform={status.guest_system === "windows-11" ? "Windows" : "Linux"} zoom={zoom} setZoom={setZoom}
185新增: onConfirm={onConfirm} onStop={() => run("stop")} busy={busy} refresh={refresh} sidebarCollapsed={sidebarCollapsed} onExpand={onExpand} />
172186 {(error || statusError || desktop?.failed) && (
173187 <div className="connection-banner" role="alert">
174删除: {error || statusError || (desktop?.failure_reason === "oom-kill"
188新增: <SafetyMessage message={error || statusError || (desktop?.failure_reason === "oom-kill"
175189 ? "环境内存不足,Claude Desktop 已被系统关闭。请在设置中检查计算资源后重新打开。"
176删除: : "Claude Desktop 未能启动,可重试打开或修复安装。")}
190新增: : "Claude Desktop 未能启动,可重试打开或修复安装。")} />
177191 <button onClick={onDetails}>操作详情</button>
178192 </div>
179193 )}
180删除: {desktop?.running && desktop.managed === false && <div className="connection-banner" role="status">当前应用尚未接入 Cage 账户解锁。请先保存并关闭应用,再重新打开。</div>}
194新增: {desktop?.running && desktop.managed === false && !desktop.native_user_session && <div className="connection-banner" role="status">当前应用尚未接入 Cage 账户解锁。请先保存并关闭应用,再重新打开。</div>}
181195 {busy && ownJob && (
182196 <div className="desktop-progress" role="status">
183197 <RefreshCw size={16} className="spin" />
新增ui/src/cli-sessions.css+76 −0看文件
@@ -0,0 +1,76 @@
1新增:.sidebar-tab > .sidebar-session {
2新增: display: flex; align-items: center; justify-content: flex-start; flex: 1; min-width: 0; gap: 7px;
3新增: padding: 8px; border: 0; background: transparent; color: inherit;
4新增: text-align: left; font-size: .9286rem;
5新增:}
6新增:.sidebar-session > span { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
7新增:.sidebar-session > svg { flex: none; color: var(--muted); }
8新增:.settings-content.settings-content--archives { padding: 32px clamp(24px, 4vw, 64px); }
9新增:.archived-sessions { display: grid; gap: 28px; min-width: 0; width: 100%; max-width: 1120px; margin-inline: auto; }
10新增:.archived-sessions :is(h2,h3,h4,p) { margin: 0; }
11新增:.archive-page-title { display: none; }
12新增:.archive-toolbar { display: grid; grid-template-columns: minmax(180px, 2.2fr) minmax(120px, 1fr) minmax(130px, 1.1fr); gap: 10px; align-items: start; }
13新增:.archive-search { display: flex; align-items: center; gap: 10px; min-width: 0; border: 1px solid var(--line); border-radius: 24px; padding: 0 15px; color: var(--muted); }
14新增:.archive-search > svg { flex: none; }
15新增:.archive-toolbar .archive-search input, .settings-content .archive-toolbar .archive-search input {
16新增: width: 100%; min-width: 0; height: 42px; padding: 0; margin: 0; border: 0; border-radius: 0; background: transparent; color: var(--ink); font: inherit; font-size: 14px; box-shadow: none;
17新增:}
18新增:.archive-search:focus-within { outline: 2px solid var(--focus); outline-offset: 2px; }
19新增:.archive-search input:focus-visible { outline: none; }
20新增:.archive-search input::placeholder { color: var(--muted); opacity: .7; }
21新增:.archive-toolbar .inline-select { display: flex; width: 100%; font-size: 14px; }
22新增:.archive-toolbar .inline-select-trigger, .settings-content .archive-toolbar .inline-select-trigger {
23新增: display: flex; align-items: center; width: 100%; height: 44px; padding: 0 12px; border: 1px solid var(--line); border-radius: 11px; color: var(--muted); background: transparent; font: inherit;
24新增:}
25新增:.archive-filter-label { display: flex; align-items: center; gap: 9px; min-width: 0; }
26新增:.archive-filter-label > span { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
27新增:.archive-toolbar .inline-select-trigger[aria-expanded="true"] .archive-filter-label svg { transform: none; }
28新增:.archive-toolbar .inline-select-list { font-size: 13px; border-radius: 9px; }
29新增:.archive-toolbar .inline-select-list [role="option"] { padding: 9px; }
30新增:.archive-project { display: grid; gap: 14px; min-width: 0; }
31新增:.archive-project-heading { display: flex; align-items: center; gap: 10px; padding-inline: 2px; color: var(--muted); }
32新增:.archive-project-heading > svg { flex: none; }
33新增:.archive-project-heading h3 { min-width: 0; flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 15px; font-weight: 600; }
34新增:.archive-project-heading > span { font-size: 13px; white-space: nowrap; }
35新增:.archive-project-list { border: 1px solid var(--line); border-radius: 16px; padding: 0 20px; }
36新增:.archive-bulk-toolbar { display: flex; align-items: center; flex-wrap: wrap; gap: 12px; }
37新增:.archive-bulk-toolbar > .archived-session-actions { margin-left: auto; }
38新增:.archive-bulk-note { flex-basis: 100%; }
39新增:.archived-sessions .archive-selection { display: inline-flex; flex-direction: row; align-items: center; justify-content: center; flex: none; gap: 8px; margin: 0; min-height: 34px; color: var(--ink); font-size: 13px; cursor: pointer; }
40新增:.archived-sessions .archive-selection input { width: 16px; height: 16px; margin: 0; flex: none; accent-color: var(--accent, var(--focus)); cursor: pointer; }
41新增:.archive-selection input:focus-visible { outline: 2px solid var(--focus); outline-offset: 3px; }
42新增:.archive-selection:has(input:disabled) { opacity: .5; cursor: default; }
43新增:.archive-selection input:disabled { cursor: default; }
44新增:.archived-session:has(.archive-selection input:checked) .archived-session-title h4 { color: var(--accent, var(--focus)); }
45新增:.archived-session { display: grid; gap: 12px; padding: 16px 0; }
46新增:.archived-session + .archived-session { border-top: 1px solid var(--line); }
47新增:.archived-session-row { display: flex; align-items: center; gap: 16px; min-height: 42px; }
48新增:.archived-session-title { min-width: 0; flex: 1; display: grid; gap: 5px; }
49新增:.archived-sessions .archived-session-title h4 { margin: 0; font-size: 15px; font-weight: 550; overflow-wrap: anywhere; line-height: 1.5; }
50新增:.archived-session-title time, .archive-note { color: var(--muted); font-size: 13px; overflow-wrap: anywhere; line-height: 1.5; }
51新增:.archived-session-actions { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; flex: none; }
52新增:.archive-icon-button { display: inline-flex; align-items: center; justify-content: center; width: 34px; min-height: 34px; padding: 0; border: 0; border-radius: 9px; background: transparent; color: var(--muted); }
53新增:.archive-icon-button:hover { background: var(--hover, var(--soft)); color: var(--danger, var(--error)); }
54新增:.archive-restore { min-height: 34px; padding: 6px 12px; border: 0; border-radius: 10px; background: var(--hover, var(--soft)); color: var(--ink); font: inherit; font-size: 13px; font-weight: 550; white-space: nowrap; }
55新增:.archive-restore:hover { background: var(--selected); }
56新增:.archive-button { display: inline-flex; align-items: center; justify-content: center; gap: 7px; min-height: 36px;
57新增: padding: 7px 12px; background: transparent; color: inherit; border: 1px solid var(--line); border-radius: 8px; font: inherit; font-size: 13px; }
58新增:.archive-button:hover { background: var(--selected); }
59新增:.archive-confirm { display: grid; gap: 12px; padding: 14px; border: 1px solid var(--line); border-radius: 9px; font-size: 14px; line-height: 1.6; }
60新增:.archive-delete, .archive-error { color: var(--danger, var(--error, #b54137)); }
61新增:.phone-workspace .archive-button { min-height: 44px; }
62新增:.mobile-session-settings .archive-page-title { display: block; font-size: 20px; }
63新增:@media (max-width: 650px) {
64新增: .archive-toolbar { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); }
65新增: .archive-search { grid-column: 1 / -1; }
66新增: .archived-sessions { gap: 24px; }
67新增: .archive-project-list { padding: 0 12px; border-radius: 13px; }
68新增: .archive-bulk-toolbar { gap: 8px 12px; }
69新增: .archive-bulk-toolbar > .archived-session-actions { width: 100%; margin-left: 0; gap: 8px; }
70新增: .archived-sessions .archive-selection { min-height: 44px; }
71新增: .archived-session-row { gap: 8px; }
72新增: .archive-icon-button { width: 32px; min-height: 44px; }
73新增: .archive-restore { padding: 7px 9px; min-height: 38px; }
74新增: .archived-session-actions { gap: 3px; }
75新增: .archived-session-title time { font-size: 11px; }
76新增:}
新增ui/src/cli-sessions.jsx+208 −0看文件
@@ -0,0 +1,208 @@
1新增:import React, { useEffect, useRef, useState } from "react";
2新增:import { Folder, ListFilter, RefreshCw, Search, Trash2 } from "lucide-react";
3新增:import { api } from "./api";
4新增:import { InlineSelect } from "./inline-select";
5新增:import "./cli-sessions.css";
6新增:
7新增:export const desktopSessionRequest = (path, options = {}) => api("/cli" + path, options.body);
8新增:export const sessionsChanged = () => window.dispatchEvent(new Event("cage-cli-sessions-changed"));
9新增:const archiveDate = new Intl.DateTimeFormat("zh-CN", {year:"numeric",month:"long",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:false});
10新增:const projectLabel = path => path.replaceAll("\\", "/").split("/").filter(Boolean).at(-1) || path;
11新增:const archiveFilters = {all:"全部会话",pinned:"已置顶",deleting:"删除未完成"};
12新增:
13新增:function ArchiveSelection({ items, selected, onToggle, disabled, label, children }) {
14新增: const input = useRef(null);
15新增: const count = items.filter(item => selected.has(item.id)).length;
16新增: useEffect(() => { input.current.indeterminate = count > 0 && count < items.length; }, [count, items.length]);
17新增: return <label className="archive-selection check-line">
18新增: <input ref={input} type="checkbox" aria-label={label} checked={items.length > 0 && count === items.length}
19新增: disabled={disabled} onChange={() => onToggle(items)} />
20新增: {children && <span>{children}</span>}
21新增: </label>;
22新增:}
23新增:
24新增:export function useCLISessions(enabled, visible) {
25新增: const [sessions, setSessions] = useState([]);
26新增: const [error, setError] = useState("");
27新增: const [loading, setLoading] = useState(false);
28新增: const [revision, setRevision] = useState(0);
29新增: const refresh = () => { setLoading(true); setRevision(value => value + 1); };
30新增: useEffect(() => {
31新增: window.addEventListener("cage-cli-sessions-changed", refresh);
32新增: return () => window.removeEventListener("cage-cli-sessions-changed", refresh);
33新增: }, []);
34新增: useEffect(() => {
35新增: if (!enabled || !visible) { setLoading(false); return; }
36新增: let live = true, timer;
37新增: const load = async () => {
38新增: setLoading(true);
39新增: try {
40新增: const result = await desktopSessionRequest("/sessions");
41新增: if (!live) return;
42新增: setSessions((result.sessions || []).map(session => result.notice ? { ...session, active: false } : session));
43新增: setError(result.notice || "");
44新增: } catch (error) {
45新增: if (live) {
46新增: setError(error.message);
47新增: setSessions(previous => previous.map(session => ({ ...session, active: false })));
48新增: }
49新增: } finally { if (live) setLoading(false); }
50新增: if (live) timer = setTimeout(load, 5000);
51新增: };
52新增: void load();
53新增: return () => { live = false; clearTimeout(timer); };
54新增: }, [enabled, visible, revision]);
55新增: return { sessions, error, loading, refresh };
56新增:}
57新增:
58新增:export function ArchivedSessions({ request = desktopSessionRequest, ready, onRestored }) {
59新增: const [sessions, setSessions] = useState(null);
60新增: const [error, setError] = useState("");
61新增: const [readError, setReadError] = useState("");
62新增: const [busy, setBusy] = useState(false);
63新增: const [confirming, setConfirming] = useState("");
64新增: const [revision, setRevision] = useState(0);
65新增: const [query, setQuery] = useState("");
66新增: const [filter, setFilter] = useState("all");
67新增: const [project, setProject] = useState("");
68新增: const [selected, setSelected] = useState(new Set());
69新增: const [bulkConfirm, setBulkConfirm] = useState(null);
70新增: const [resultMessage, setResultMessage] = useState("");
71新增: const [progress, setProgress] = useState(null);
72新增: useEffect(() => {
73新增: let live = true, timer;
74新增: const load = async () => {
75新增: try {
76新增: const result = await request("/sessions?archived=true");
77新增: if (live) {
78新增: const list = result.sessions || [];
79新增: setSessions(list); setReadError(result.notice || "");
80新增: setSelected(previous => new Set([...previous].filter(id => list.some(session => session.id === id))));
81新增: }
82新增: } catch (error) { if (live) setReadError(error.message); }
83新增: if (live) timer = setTimeout(load, 5000);
84新增: };
85新增: if (!busy) void load();
86新增: return () => { live = false; clearTimeout(timer); };
87新增: }, [request, revision, busy]);
88新增: const change = async (items, operation) => {
89新增: if (busy) return;
90新增: setBusy(true); setError(""); setResultMessage("");
91新增: setProgress({done:0, total:items.length});
92新增: const completed = new Set(), failures = [];
93新增: try {
94新增: for (const session of items) {
95新增: try {
96新增: await request("/sessions/" + session.id + "/" + operation, {body:operation === "purge" ? {confirm:true} : {}});
97新增: completed.add(session.id);
98新增: } catch (error) { failures.push({session, message:error.message}); }
99新增: setProgress({done:completed.size + failures.length, total:items.length});
100新增: }
101新增: setSessions(list => list.filter(item => !completed.has(item.id)));
102新增: setSelected(previous => new Set([...previous].filter(id => !completed.has(id))));
103新增: if (completed.size) {
104新增: setConfirming("");
105新增: setResultMessage(`已${operation === "restore" ? "取消归档" : "永久删除"} ${completed.size} 个会话。`);
106新增: sessionsChanged();
107新增: }
108新增: setBulkConfirm(null);
109新增: if (failures.length) setError(`${failures.length} 个会话处理失败:${failures.map(({session,message}) => `“${session.title || "新会话"}”:${message}`).join(";")}`);
110新增: if (operation === "restore") for (const id of completed) onRestored?.(id);
111新增: } finally { setBusy(false); setProgress(null); }
112新增: };
113新增: const resetSelection = (setter, value) => {
114新增: setter(value); setSelected(new Set()); setBulkConfirm(null); setConfirming(""); setResultMessage("");
115新增: };
116新增: const toggleSelection = items => {
117新增: const all = items.every(item => selected.has(item.id));
118新增: setSelected(previous => {
119新增: const next = new Set(previous);
120新增: for (const item of items) { if (all) next.delete(item.id); else next.add(item.id); }
121新增: return next;
122新增: });
123新增: setBulkConfirm(null); setConfirming(""); setResultMessage("");
124新增: };
125新增: const projects = [...new Set(sessions?.map(session => session.workspace) || [])];
126新增: const selectedProject = projects.includes(project) ? project : "";
127新增: const search = query.trim().toLocaleLowerCase();
128新增: const groups = new Map();
129新增: for (const session of sessions || []) {
130新增: if (selectedProject && session.workspace !== selectedProject) continue;
131新增: if (filter === "pinned" && !session.pinned || filter === "deleting" && !session.deleting) continue;
132新增: if (search && !(session.title + " " + session.workspace).toLocaleLowerCase().includes(search)) continue;
133新增: if (!groups.has(session.workspace)) groups.set(session.workspace, []);
134新增: groups.get(session.workspace).push(session);
135新增: }
136新增: const visible = [...groups.values()].flat();
137新增: const selectedItems = visible.filter(session => selected.has(session.id));
138新增: const hasDeleting = selectedItems.some(session => session.deleting);
139新增: return <section className="archived-sessions" aria-label="已归档会话">
140新增: <h2 className="archive-page-title">已归档会话</h2>
141新增: <div className="archive-toolbar">
142新增: <div className="archive-search"><Search size={18} aria-hidden="true" />
143新增: <input type="search" aria-label="搜索已归档的会话" placeholder="搜索已归档的会话" value={query} disabled={busy} onChange={event => resetSelection(setQuery, event.target.value)} />
144新增: </div>
145新增: <InlineSelect aria-label="会话筛选" value={filter} disabled={busy} onValueChange={value => resetSelection(setFilter, value)}
146新增: displayLabel={<span className="archive-filter-label"><ListFilter size={17}/><span>{archiveFilters[filter]}</span></span>}>
147新增: {Object.entries(archiveFilters).map(([value,label]) => <option key={value} value={value}>{label}</option>)}
148新增: </InlineSelect>
149新增: <InlineSelect aria-label="项目筛选" value={selectedProject} disabled={busy} onValueChange={value => resetSelection(setProject, value)}
150新增: displayLabel={<span className="archive-filter-label"><Folder size={17}/><span>{selectedProject ? projectLabel(selectedProject) : "所有项目"}</span></span>}>
151新增: <option value="">所有项目</option>
152新增: {projects.map(path => <option key={path} value={path}>{projects.some(other => other !== path && projectLabel(other) === projectLabel(path)) ? path : projectLabel(path)}</option>)}
153新增: </InlineSelect>
154新增: </div>
155新增: {visible.length > 0 && <div className="archive-bulk-toolbar" role="group" aria-label="批量处理会话">
156新增: <ArchiveSelection items={visible} selected={selected} onToggle={toggleSelection} disabled={busy} label="全选当前筛选结果">全选</ArchiveSelection>
157新增: <span className="archive-note">已选择 {selectedItems.length} 个会话</span>
158新增: <div className="archived-session-actions">
159新增: <button className="archive-button" disabled={busy || !selectedItems.length} onClick={() => resetSelection(setSelected, new Set())}>清空选择</button>
160新增: <button className="archive-restore" disabled={busy || !selectedItems.length || hasDeleting} onClick={() => change(selectedItems, "restore")}>批量取消归档</button>
161新增: <button className="archive-button archive-delete" disabled={busy || !ready || !selectedItems.length} onClick={() => { setConfirming(""); setBulkConfirm(selectedItems); }}>批量删除</button>
162新增: </div>
163新增: {hasDeleting && <p className="archive-note archive-bulk-note">所选会话包含删除未完成项,请取消选择这些会话后再取消归档。</p>}
164新增: </div>}
165新增: {progress && <p role="status" className="archive-note">正在处理 {progress.done} / {progress.total} 个会话…</p>}
166新增: {resultMessage && <p role="status" className="archive-note">{resultMessage}</p>}
167新增: {bulkConfirm && <div className="archive-confirm" role="group" aria-label="确认批量永久删除会话">
168新增: <p>永久删除所选的 {bulkConfirm.length} 个会话及其 Claude Code 原始对话和子代理记录?此操作无法撤销。</p>
169新增: <div className="archived-session-actions"><button className="archive-button" disabled={busy} onClick={() => setBulkConfirm(null)}>取消</button>
170新增: <button className="archive-button archive-delete" disabled={busy || !ready} onClick={() => change(bulkConfirm, "purge")}>永久删除所选会话</button></div>
171新增: </div>}
172新增: {(error || readError) && <div role="alert" className="archive-error">{error || readError}
173新增: {readError && <button className="archive-button" onClick={() => setRevision(value => value + 1)} disabled={busy}>重新读取</button>}
174新增: </div>}
175新增: {!sessions && !readError && <p role="status">正在读取…</p>}
176新增: {sessions?.length === 0 && <p className="archive-note">暂无已归档会话。</p>}
177新增: {Boolean(sessions?.length) && !groups.size && <p className="archive-note">没有符合筛选条件的已归档会话。</p>}
178新增: {[...groups].map(([path,items]) => <section className="archive-project" key={path} aria-label={projectLabel(path) + "的已归档会话"}>
179新增: <header className="archive-project-heading">
180新增: <ArchiveSelection items={items} selected={selected} onToggle={toggleSelection} disabled={busy} label={`全选项目 ${path} 的当前筛选结果`} />
181新增: <Folder size={18}/><h3 title={path}>{projectLabel(path)}</h3><span>{items.length} 个会话</span></header>
182新增: <div className="archive-project-list">{items.map(session => {
183新增: const date = new Date(session.updated_at);
184新增: return <article className="archived-session" key={session.id}>
185新增: <div className="archived-session-row">
186新增: <ArchiveSelection items={[session]} selected={selected} onToggle={toggleSelection} disabled={busy} label={`选择会话 ${session.title || "新会话"}`} />
187新增: <div className="archived-session-title"><h4>{session.title || "新会话"}</h4>
188新增: {!Number.isNaN(date.valueOf()) && <time dateTime={session.updated_at}>{archiveDate.format(date)}</time>}
189新增: </div>
190新增: <div className="archived-session-actions">
191新增: <button className="archive-icon-button" aria-label={session.deleting ? "重试删除" : "删除会话"} title={session.deleting ? "重试删除" : "删除会话"}
192新增: disabled={busy || !ready} onClick={() => { setBulkConfirm(null); session.deleting ? change([session], "purge") : setConfirming(session.id); }}>
193新增: {session.deleting ? <RefreshCw size={16}/> : <Trash2 size={16}/>}</button>
194新增: <button className="archive-restore" disabled={busy || session.deleting} onClick={() => change([session], "restore")}>取消归档</button>
195新增: </div>
196新增: </div>
197新增: {session.deleting && <p className="archive-note">永久删除尚未完成,连接恢复后可重试。</p>}
198新增: {confirming === session.id && <div className="archive-confirm" role="group" aria-label="确认永久删除会话">
199新增: <p>永久删除“{session.title || "新会话"}”及其 Claude Code 原始对话和子代理记录?此操作无法撤销。</p>
200新增: <div className="archived-session-actions"><button className="archive-button" disabled={busy} onClick={() => setConfirming("")}>取消</button>
201新增: <button className="archive-button archive-delete" disabled={busy || !ready} onClick={() => change([session], "purge")}>永久删除</button></div>
202新增: </div>}
203新增: </article>;
204新增: })}</div>
205新增: </section>)}
206新增: {!ready && <p className="archive-note">启动主机环境后可以永久删除 Claude Code 原始记录。</p>}
207新增: </section>;
208新增:}
修改ui/src/client-context.mjs+3 −1看文件
@@ -16,10 +16,12 @@ export function assertConnection(connectionID) {
1616}
1717
1818export function connectionHeaders(path, context = current) {
19删除: if (path === "/session" || path.startsWith("/client/")) return {};
19新增: if (path === "/session" || (path.startsWith("/client/") && !isProjectSharesPath(path))) return {};
2020 return { "X-Cage-Connection": context.connection_id || "disconnected" };
2121}
2222
23新增:export const isProjectSharesPath = (path) => path === "/client/project-shares" || path.startsWith("/client/project-shares/");
24新增:
2325export function runtimeURL(path, context = current) {
2426 const url = new URL("/api" + path, globalThis.location?.origin || "http://localhost");
2527 url.searchParams.set("connection", context.connection_id || "disconnected");
修改ui/src/diagnostics.jsx+2 −2看文件
@@ -37,13 +37,13 @@ export function DiagnosticSettings() {
3737 };
3838 return <section className="settings-group" aria-label="日志与诊断">
3939 <h3>日志与诊断</h3>
40删除: <p className="footnote">自动记录应用故障并脱敏,保留 14 天,容量预算 50 MiB({remote ? "服务器" : "本机"}上限 40 MiB、环境服务预算 10 MiB)。不收集终端内容、项目文件或完整配置。</p>
40新增: <p className="footnote">自动记录应用故障并脱敏,保留 14 天。每个后台日志上限 40 MiB,环境服务预算 10 MiB。诊断包会同时收集桌面连接与当前环境的记录,最大 96 MiB。采集范围限于故障日志与运行状态。</p>
4141 {info && <p className="footnote">{remote ? "服务器" : "本机"}日志 {(info.bytes / 1024 / 1024).toFixed(1)} MiB · {info.files} 个文件</p>}
4242 <button className="secondary-button" disabled={busy} onClick={save}>
4343 {busy ? <LoaderCircle size={14} className="spin" /> : <ArrowDownToLine size={14} />}
4444 {busy ? "正在导出…" : remote ? "导出服务器诊断包" : "导出诊断包"}
4545 </button>
46删除: <p className="footnote">{remote ? "诊断包包含当前云端主机的脱敏日志、版本和收集状态,需要保持远程连接。导出后保存在你选择的本机位置。" : "诊断包包含脱敏日志、版本和收集状态;环境离线时仍可导出本机记录。只保存在你选择的位置。"}</p>
46新增: <p className="footnote">{remote ? "诊断包包含本机界面与当前云端主机的脱敏日志、版本和收集状态,需要保持远程连接。导出后保存在你选择的本机位置。" : "诊断包包含界面与环境的脱敏日志、版本和收集状态,环境离线时仍可导出本机记录。只保存在你选择的位置。"}</p>
4747 {notice && <p role="status">{notice}</p>}
4848 {error && <p role="alert" className="error-message">{error}</p>}
4949 </section>;
修改ui/src/environment-storage.jsx+3 −2看文件
@@ -1,6 +1,7 @@
11import React, { useEffect, useState } from "react";
22import { FolderOpen } from "lucide-react";
33import { api, native, nativeAvailable } from "./api";
4新增:import { SafetyMessage } from "./safety-message";
45
56export function EnvironmentStorage({ status, onConfirm }) {
67 const [location, setLocation] = useState(null);
@@ -56,7 +57,7 @@ export function EnvironmentStorage({ status, onConfirm }) {
5657 };
5758 return <section className="environment-versions environment-storage" aria-label="本机环境存储">
5859 <h4>本机环境存储</h4>
59删除: <p className="field-help">Linux 镜像、下载缓存和虚拟磁盘可以放在另一块本地磁盘。项目文件保存在各自的项目文件夹。</p>
60新增: <p className="field-help">系统镜像、下载缓存和虚拟磁盘可以放在另一块本地磁盘。项目文件保存在各自的项目文件夹。</p>
6061 <div className="setting-summary-row"><span>当前环境目录</span><strong>{location?.directory || "正在读取…"}</strong></div>
6162 {location?.backup && <p className="field-help">迁移前的备份保存在 <code>{location.backup}</code>。确认新环境能正常启动、文件和登录状态齐全后,可自行清理备份。</p>}
6263 <label>新存储位置
@@ -70,6 +71,6 @@ export function EnvironmentStorage({ status, onConfirm }) {
7071 </button>
7172 </div>
7273 {job?.kind === "storage" && job.running && <p role="status" className="field-help">{job.message}</p>}
73删除: {error && <p role="alert" className="error-message">{error}</p>}
74新增: {error && <p role="alert" className="error-message"><SafetyMessage message={error} /></p>}
7475 </section>;
7576}
修改ui/src/environment-versions.jsx+10 −5看文件
@@ -1,5 +1,6 @@
11import React, { useEffect, useState } from "react";
22import { api } from "./api";
3新增:import { SafetyMessage } from "./safety-message";
34
45export function EnvironmentVersions({ status, onConfirm }) {
56 const [data, setData] = useState(null), [error, setError] = useState(""), [loading, setLoading] = useState(false), [starting, setStarting] = useState(false);
@@ -22,7 +23,9 @@ export function EnvironmentVersions({ status, onConfirm }) {
2223 const update = async (tools) => {
2324 if (!(await onConfirm({
2425 title: tools ? "更新环境工具?" : "更新环境组件?",
25删除: body: "请先保存浏览器和编辑器中的内容。浏览器、编辑器会短暂重启,编辑器内的终端可能结束;工作台终端、项目文件和登录状态会保留。",
26新增: body: data?.maintenance?.native
27新增: ? "请先保存内容并结束正在运行的终端和 Claude Code 轮次。更新会重启浏览器、编辑器和文件共享连接,聊天历史、项目文件与登录资料会保留。" + (data.maintenance.guest_system === "windows-11" ? "请在系统提示中确认主机管理授权,并验证已绑定客机的管理员账户。" : "")
28新增: : "请先保存浏览器和编辑器中的内容。浏览器、编辑器会短暂重启,编辑器内的终端可能结束;工作台终端、项目文件和登录状态会保留。",
2629 confirm: tools ? "更新工具" : "更新组件",
2730 }))) return;
2831 setStarting(true); setError("");
@@ -31,7 +34,7 @@ export function EnvironmentVersions({ status, onConfirm }) {
3134 finally { setStarting(false); }
3235 };
3336 const componentLabels = { current: "已同步", update_required: "需要更新", stopped: "环境已停止", unknown: "暂时无法确认" };
34删除: const toolNames = { chromium: "浏览器", code_server: "文件编辑器", claude: "Claude Code", mise: "工具版本管理器", proxy: "代理核心" };
37新增: const toolNames = { chromium: "浏览器", code_server: "文件编辑器", claude: "Claude Code", mise: "工具版本管理器", node: "Node.js", python: "Python", git: "Git", proxy: "代理核心" };
3538 return (
3639 <section className="environment-versions" aria-label="环境版本">
3740 <h4>版本与组件</h4>
@@ -39,15 +42,17 @@ export function EnvironmentVersions({ status, onConfirm }) {
3942 <div className="setting-summary-row"><span>环境组件</span><strong>{componentLabels[data?.components?.status] || (loading ? "正在读取…" : "暂时无法确认")}</strong></div>
4043 {data?.tools && <table className="environment-tool-table">
4144 <thead><tr><th>工具</th><th>当前版本</th><th>受管版本</th></tr></thead>
42删除: <tbody>{Object.entries(toolNames).map(([key, name]) => <tr key={key}><td>{name}</td><td>{data.tools[key]?.current || "—"}</td><td>{data.tools[key]?.required || "—"}</td></tr>)}</tbody>
45新增: <tbody>{Object.entries(toolNames).filter(([key]) => data.tools[key]).map(([key, name]) => <tr key={key}><td>{name}</td><td>{data.tools[key]?.current || "—"}</td><td>{data.tools[key]?.required || "—"}</td></tr>)}</tbody>
4346 </table>}
44删除: {(error || data?.error) && <p role="alert" className="error-message">{error || data.error}</p>}
47新增: {(error || data?.error) && <p role="alert" className="error-message"><SafetyMessage message={error || data.error} /></p>}
4548 <div className="environment-version-actions">
4649 <button disabled={loading || busy} onClick={refresh}>{loading ? "正在读取…" : "刷新版本"}</button>
4750 {data?.components?.update_required && <button className="primary" disabled={busy || !status.vm_running} onClick={() => update(false)}>更新环境组件</button>}
4851 <button disabled={busy || !data?.tools_update_allowed} onClick={() => update(true)}>更新环境工具</button>
4952 </div>
50删除: <p className="field-help">组件更新保留虚拟磁盘与终端。工具更新需先启动环境并同步组件,依赖通过已选代理下载;无需放行业务网络,也不会自动恢复已暂停的外网。</p>
53新增: <p className="field-help">{data?.maintenance?.native
54新增: ? "原生组件更新前需结束运行中的终端与 Claude Code 轮次。系统磁盘、项目和账户资料保留,已暂停的外网继续保持暂停。工具包由主机准备并校验后传入客机。"
55新增: : "组件更新保留虚拟磁盘与终端。工具更新需先启动环境并同步组件,依赖通过已选代理下载;无需放行业务网络,也不会自动恢复已暂停的外网。"}</p>
5156 </section>
5257 );
5358}
新增ui/src/error-message.mjs+59 −0看文件
@@ -0,0 +1,59 @@
1新增:export function operationName(path = "", method = "GET") {
2新增: const reading = method === "GET";
3新增: if (path.startsWith("/api/mobile/cli")) return reading ? "读取会话消息" : "提交会话操作";
4新增: if (path.startsWith("/api/mobile/browser")) return "连接电脑上的浏览器";
5新增: if (path.startsWith("/api/mobile/desktop")) return "连接电脑上的 Claude Desktop";
6新增: if (path.startsWith("/environment/resources")) return reading ? "读取资源配置" : "应用资源配置";
7新增: if (path === "/environment/initialization") return reading ? "读取初始化进度" : "保存初始化状态";
8新增: if (path.startsWith("/environment/versions")) return "读取环境组件版本";
9新增: if (path.startsWith("/environment/")) return "更新环境";
10新增: if (path.startsWith("/input/files") || path.startsWith("/browser/files")) return "传递文件";
11新增: if (path.startsWith("/tailscale")) return reading ? "读取 Tailscale 状态" : "操作 Tailscale";
12新增: if (path.startsWith("/browser")) return "操作浏览器";
13新增: if (path.startsWith("/proxy")) return reading ? "读取代理设置" : "应用代理设置";
14新增: if (path.startsWith("/safety")) return "检查联网条件";
15新增: if (path.startsWith("/settings/probe")) return "验证代理出口";
16新增: if (path.startsWith("/settings")) return reading ? "读取设置" : "保存设置";
17新增: if (path.startsWith("/diagnostics/export")) return "导出诊断日志";
18新增: if (path.startsWith("/diagnostics")) return "读取诊断日志";
19新增: if (path.startsWith("/projects")) return "连接项目目录";
20新增: if (path.startsWith("/account")) return "处理账户操作";
21新增: if (path.startsWith("/claude-desktop")) return "操作 Claude Desktop";
22新增: if (path.startsWith("/terminals")) return "连接终端";
23新增: if (path === "/start") return "启动环境";
24新增: if (path === "/stop") return "停止环境";
25新增: return "连接 Cage 工作台";
26新增:}
27新增:
28新增:export function httpErrorMessage(path, status, text = "", contentType = "", method = "GET") {
29新增: // Proxy HTML pages, stack traces and untranslated runtime errors are not UI
30新增: // explanations. Preserve short Chinese messages supplied by Cage itself.
31新增: const message = text.trim();
32新增: if (contentType.startsWith("text/plain") && message.length <= 2000 && /\p{Script=Han}/u.test(message) && !/<(?:html|body|script|!doctype)\b/i.test(message)) return message;
33新增: const action = operationName(path, method);
34新增: const reasons = {
35新增: 400: "后台没有接受这次请求。请核对填写的内容;仍失败时在设置中导出诊断包。",
36新增: 401: "工作台登录会话已失效。请重新连接 Cage,再发起这次操作。",
37新增: 403: "后台拒绝了这次访问。请从 Cage 应用重新打开工作台。",
38新增: 404: "当前后台没有提供所需功能。请确认应用与后台已完成更新。",
39新增: 409: "环境状态已变化或另一个操作尚未结束。请刷新状态并等待当前操作完成。",
40新增: 413: "文件或请求内容超过允许大小。请缩小文件或分批处理。",
41新增: 423: "Cage 已锁定。请先解锁账户,再发起这次操作。",
42新增: 429: "请求过于频繁。请等待片刻,避免连续点击。",
43新增: 500: "后台处理请求时出错。请在设置中导出诊断包,并附上刚才执行的操作。",
44新增: 502: "后台未能连接环境内的服务。请确认环境已启动,再检查环境组件状态。",
45新增: 503: "后台服务尚未就绪或正在重启。请等待连接恢复后再操作。",
46新增: 504: "等待后台响应超时。请检查环境负载,恢复连接后核对操作是否已生效。",
47新增: };
48新增: return `${action}失败(HTTP ${status}):${reasons[status] || "尚未取得可识别的原因。请在设置中导出诊断包。"}`;
49新增:}
50新增:
51新增:export function connectionErrorMessage(path, method = "GET") {
52新增: return `${operationName(path, method)}失败:工作台与 Cage 后台的连接已中断。请点击重新连接;若刚才正在保存或上传,恢复后先核对结果再重试。`;
53新增:}
54新增:
55新增:export function nativeFailureMessage(action, message = "") {
56新增: if (/\p{Script=Han}/u.test(message) && !["文件操作失败", "原生操作超时,请重试", "操作失败"].includes(message)) return message;
57新增: const names = { chooseFolder: "选择本机文件夹", chooseUploadFiles: "选择上传文件", uploadHostFiles: "上传本机文件", openHostPath: "打开本机文件", exportDiagnostics: "导出诊断包", appUpdate: "检查或安装应用更新", clipboardRead: "读取剪贴板", clipboardWrite: "写入剪贴板", refreshSession: "恢复工作台登录会话" };
58新增: return `${names[action] || "执行本机操作"}失败:${/timeout|超时/i.test(message) ? "等待本机组件响应超时" : "本机组件没有返回可识别的原因"}。请重新连接 Cage;仍失败时在设置中导出诊断包。`;
59新增:}
新增ui/src/error-message.test.mjs+23 −0看文件
@@ -0,0 +1,23 @@
1新增:import test from "node:test";
2新增:import assert from "node:assert/strict";
3新增:import { httpErrorMessage, connectionErrorMessage, nativeFailureMessage } from "./error-message.mjs";
4新增:
5新增:test("HTTP failures name the operation and avoid upstream HTML or opaque runtime output", () => {
6新增: for (const [status, reason] of [[401, "登录会话"], [409, "操作"], [413, "大小"], [503, "尚未就绪"], [504, "超时"]]) {
7新增: const message = httpErrorMessage("/environment/resources", status, "<html>token=private</html>", "text/html");
8新增: assert.match(message, /资源配置/);
9新增: assert.ok(message.includes(reason));
10新增: assert.ok(!message.includes("private"));
11新增: }
12新增: const specific = "上传窗口已关闭,请重新点击网页上传按钮";
13新增: assert.equal(httpErrorMessage("/input/files", 409, specific, "text/plain; charset=utf-8"), specific);
14新增: assert.match(connectionErrorMessage("/input/files"), /传递文件.*连接已中断.*核对结果/);
15新增:});
16新增:
17新增:test("native errors retain precise rules and explain opaque failures in context", () => {
18新增: assert.match(nativeFailureMessage("exportDiagnostics", "Native operation timeout"), /导出诊断包.*超时/);
19新增: assert.match(nativeFailureMessage("uploadHostFiles", "operation failed token=private"), /上传本机文件失败.*可识别的原因/);
20新增: assert.ok(!nativeFailureMessage("uploadHostFiles", "operation failed token=private").includes("private"));
21新增: const rule = "请选择本机项目中的文件";
22新增: assert.equal(nativeFailureMessage("uploadHostFiles", rule), rule);
23新增:});
修改ui/src/exit-policy.jsx+21 −16看文件
@@ -4,7 +4,7 @@ import { Globe2, LoaderCircle } from "lucide-react";
44import { canonicalExitPolicy } from "./safety-state.mjs";
55
66const countries =
7删除: "US GB CA DE FR NL SE FI IE CH AU NZ JP SG KR HK TW CN IN BR".split(" ");
7新增: "US GB CA DE FR NL SE FI IE CH AU NZ JP SG KR HK MO TW IN BR".split(" ");
88const names = new Intl.DisplayNames(["zh-CN"], { type: "region" });
99
1010export function ExitPolicyFields({
@@ -24,10 +24,10 @@ export function ExitPolicyFields({
2424 : {
2525 ...policy,
2626 country_code: observation.country_code || "",
27删除: ...(policy.scope === "city"
27新增: ...(policy.scope === "city" || policy.scope === "region"
2828 ? {
2929 region: observation.region || "",
30删除: city: observation.city || "",
30新增: ...(policy.scope === "city" ? { city: observation.city || "" } : {}),
3131 }
3232 : {}),
3333 },
@@ -36,7 +36,7 @@ export function ExitPolicyFields({
3636 <>
3737 <div className="section-title">
3838 <h3>IP 变化规则</h3>
39删除: <p>按保存的规则判断出口变化,允许范围内的动态 IP 可以继续使用。</p>
39新增: <p>中国大陆出口禁止放行;静态 IP 和不限地区也必须确认出口国家。</p>
4040 </div>
4141 <label className="toggle-row">
4242 <span>
@@ -72,8 +72,9 @@ export function ExitPolicyFields({
7272 onValueChange={(next) => update("scope", next)}
7373 >
7474 <option value="city">同一城市</option>
75新增: <option value="region">同一州/省</option>
7576 <option value="country">同一国家/地区</option>
76删除: <option value="any">不限地区</option>
77新增: <option value="any">不限地区(中国大陆除外)</option>
7778 </InlineSelect>
7879 </label>
7980 {policy.scope !== "any" && (
@@ -97,7 +98,7 @@ export function ExitPolicyFields({
9798 ))}
9899 </InlineSelect>
99100 </label>
100删除: {policy.scope === "city" && (
101新增: {(policy.scope === "city" || policy.scope === "region") && (
101102 <div className="field-row">
102103 <label>
103104 所属州/省
@@ -107,20 +108,24 @@ export function ExitPolicyFields({
107108 placeholder="例如 California"
108109 />
109110 </label>
110删除: <label>
111删除: 允许的城市
112删除: <input
113删除: value={policy.city}
114删除: onChange={(e) => update("city", e.target.value)}
115删除: placeholder="例如 Los Angeles"
116删除: />
117删除: </label>
111新增: {policy.scope === "city" && (
112新增: <label>
113新增: 允许的城市
114新增: <input
115新增: value={policy.city}
116新增: onChange={(e) => update("city", e.target.value)}
117新增: placeholder="例如 Los Angeles"
118新增: />
119新增: </label>
120新增: )}
118121 </div>
119122 )}
120123 <p className="field-help">
121124 {policy.scope === "city"
122125 ? "城市同时匹配所属国家和州/省。名称以定位结果为准,建议使用检测结果填写。"
123删除: : "建议先检测出口,再使用检测到的国家/地区填写。"}
126新增: : policy.scope === "region"
127新增: ? "州/省同时匹配所属国家,包括日本的都道府县。名称以检测结果为准。"
128新增: : "建议先检测出口,再使用检测到的国家/地区填写。"}
124129 </p>
125130 </>
126131 )}
@@ -159,7 +164,7 @@ export function ExitPolicyFields({
159164 </div>
160165 )}
161166 <p className="footnote">
162删除: 已有绑定会保留,重检和重启不会自动更换基准。超出范围或无法确认受限地区时暂停外网,离线终端和文件仍可使用。
167新增: 已有绑定会保留,重检和重启不会自动更换基准。命中大陆网段、定位为中国大陆、无法确认出口地区或超出保存范围时暂停外网,离线终端和文件仍可使用。
163168 </p>
164169 <p className="field-help">
165170 范围依据 IP 数据库的近似定位。后台约每 30
修改ui/src/file-transfer.js+3 −3看文件
@@ -1,16 +1,16 @@
11import { api, native, uploadFile } from "./api";
22
3删除:export const shellFilePaths = (paths) => paths.map(path => `'${path.replaceAll("'", "'\\''")}'`).join(" ") + " ";
3新增:export const shellFilePaths = (paths) => paths.map(path => `'${path.replaceAll("'", /^[A-Za-z]:\\/.test(path) ? "''" : "'\\''")}'`).join(" ") + " ";
44
55// Both native selection handles and browser File objects use the same guest
66// upload window. A failed batch is canceled before it can be delivered.
7删除:export async function sendFiles(content, target, id, { valid = () => true, onProgress } = {}) {
7新增:export async function sendFiles(content, target, id, { valid = () => true, onProgress, windowTarget } = {}) {
88 const check = () => { if (!valid()) throw new Error("文件接收目标已切换,请返回原位置重试"); };
99 check();
1010 const files = content.files || [];
1111 if (!content.fileSelection && (!files.length || files.length > 100 || files.some(file => file.size > 2 * 1024 ** 3)))
1212 throw new Error("每个文件不能超过 2 GB;一次最多 100 个文件。");
13删除: const request = await api("/input/files/start", { target, id, kind: content.kind || "paste", x: content.x, y: content.y });
13新增: const request = await api("/input/files/start", { target, id, kind: content.kind || "paste", x: content.x, y: content.y, pid: windowTarget?.pid, window: windowTarget?.window });
1414 const paths = [];
1515 try {
1616 check();
修改ui/src/file-transfer.test.mjs+6 −0看文件
@@ -48,3 +48,9 @@ test("native copied files consume an opaque selection handle for the original de
4848 assert.equal(f.calls[1][1].id, "upload-id");
4949 assert.equal(result.paths[0], "/home/cage/attachments/video.mp4");
5050});
51新增:
52新增:test("attachment paths preserve apostrophes in both PowerShell and POSIX shells", () => {
53新增: const f = fixture();
54新增: assert.equal(f.shellFilePaths(["C:\\Users\\Cage\\O'Brien.txt"]), "'C:\\Users\\Cage\\O''Brien.txt' ");
55新增: assert.equal(f.shellFilePaths(["/home/cage/O'Brien.txt"]), "'/home/cage/O'\\''Brien.txt' ");
56新增:});
修改ui/src/guest-system-icon.jsx+1 −1看文件
@@ -1,6 +1,6 @@
11import React from "react";
22
3删除:const labels = { macos: "macOS", "windows-11": "Windows", "debian-13": "Linux" };
3新增:const labels = { macos: "macOS", "windows-11": "Windows", "debian-12": "Debian", "debian-13": "Linux", "ubuntu-22.04": "Ubuntu", "ubuntu-24.04": "Ubuntu" };
44
55export function GuestSystemIcon({ system }) {
66 const label = labels[system];
新增ui/src/guest-system-picker.css+16 −0看文件
@@ -0,0 +1,16 @@
1新增:.guest-system-picker {
2新增: display: grid;
3新增: grid-template-columns: auto minmax(0, 1fr);
4新增: gap: 12px;
5新增: align-items: baseline;
6新增: padding: 0 16px 12px;
7新增: color: var(--ink);
8新增:}
9新增:.guest-system-picker > span:first-child { color: var(--muted); }
10新增:.guest-install-fields { grid-column: 1 / -1; display: grid; gap: 9px; min-width: 0; }
11新增:.guest-install-fields small { color: var(--muted); overflow-wrap: anywhere; }
12新增:.guest-install-fields label { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; }
13新增:.guest-install-fields label input:not([type="checkbox"]) { flex: 1; min-width: 10rem; }
14新增:.guest-install-fields button { justify-self: start; }
15新增:.guest-install-fields > div { display: flex; flex-wrap: wrap; gap: 8px; }
16新增:.host-clone-summary { padding: 12px; border: 1px solid var(--line); border-radius: 10px; }
新增ui/src/guest-system-picker.jsx+153 −0看文件
@@ -0,0 +1,153 @@
1新增:import React, { useEffect, useRef, useState } from "react";
2新增:import { api, native } from "./api";
3新增:import { InlineSelect } from "./inline-select";
4新增:import "./guest-system-picker.css";
5新增:
6新增:const names = { "debian-12": "Debian 12", "debian-13": "Debian 13", "ubuntu-22.04": "Ubuntu 22.04", "ubuntu-24.04": "Ubuntu 24.04", macos: "macOS", "windows-11": "Windows 11" };
7新增:const editions = { Professional: "专业版", ProfessionalN: "专业版 N", Enterprise: "企业版", EnterpriseN: "企业版 N", Education: "教育版", EducationN: "教育版 N", Core: "家庭版", CoreSingleLanguage: "家庭单语言版" };
8新增:const languages = { "zh-CN": "简体中文", "zh-TW": "繁体中文", "en-US": "英语(美国)" };
9新增:
10新增:export function HostCloneSummary({ pending, onChange }) {
11新增: const [result, setResult] = useState(null);
12新增: const [error, setError] = useState("");
13新增: const [attempt, retry] = useState(0);
14新增: useEffect(() => {
15新增: let active = true;
16新增: api("/environment/guest-systems/clone").then((next) => {
17新增: if (!active) return;
18新增: setResult(next);
19新增: onChange((current) => current?.clone ? { ...current, clone_key: next.key, clone_ready: next.enough_space } : current);
20新增: }).catch((failure) => { if (active) setError(failure.message); });
21新增: return () => { active = false; };
22新增: }, [attempt, onChange]);
23新增: if (error) return <div className="guest-install-fields" role="alert"><small>{error}</small>
24新增: <button type="button" onClick={() => { setError(""); retry((value) => value + 1); }}>重新检测并匹配</button></div>;
25新增: if (!result) return <small className="guest-install-fields" role="status">正在检测本机系统版本并匹配官方镜像…</small>;
26新增: const plan = result.plan;
27新增: const host = plan.host;
28新增: const download = result.download_bytes > 0 ? `${(result.download_bytes / 1e9).toFixed(2)} GB` : "";
29新增: const source = host.system === "macos" ? "Apple" : host.system === "windows-11" ? "微软" : "发行版官方源";
30新增: const cached = Boolean(plan.path || result.download_bytes === 0 && plan.bytes > 0);
31新增: return <div className="guest-install-fields host-clone-summary" aria-live="polite">
32新增: <strong>将安装:{names[host.system]} {host.system === "windows-11" ? `${host.version} · ${editions[host.edition] || host.edition} · ${languages[host.language] || host.language}` : host.system === "macos" ? host.version : ""}</strong>
33新增: <small>{pending ? "沿用首次选择的系统镜像,继续安装独立客机。" : "根据本机系统版本匹配官方镜像,安装到独立客机中。"}</small>
34新增: {host.build && <small>{pending ? "首次检测的本机构建号" : "本机构建号"} {host.build} · 镜像构建号 {plan.build}</small>}
35新增: {host.system === "windows-11" && host.build !== plan.build && <small>Windows 的发行版本、版本类型和语言与本机一致,补丁版本有所不同。</small>}
36新增: <small>本机的应用、个人文件和登录状态不会复制;客机中的工具、账户和文件会持续保存。</small>
37新增: <small>{cached ? "已找到匹配的本地镜像,校验后直接使用,无需重新下载系统镜像。" : `从 ${source} 下载官方系统镜像,${download ? `预计还需下载 ${download}` : "下载大小将在连接后显示"}。`}</small>
38新增: <small>{result.installation_started ? "继续使用原虚拟磁盘,保留已有安装进度。" : `至少需要 ${result.minimum_free_gib} GiB 可用空间,虚拟磁盘按实际使用增长。`}浏览器、编辑器等工作台组件按需下载。</small>
39新增: {!result.enough_space && <small role="alert">当前可用 {result.free_gib} GiB,请在存储设置中选择空间充足的位置,再重新检查。</small>}
40新增: {!pending && <button type="button" onClick={() => {
41新增: setResult(null);
42新增: onChange((current) => current?.clone ? { ...current, clone_key: "", clone_ready: false } : current);
43新增: retry((value) => value + 1);
44新增: }}>重新检测并匹配</button>}
45新增: </div>;
46新增:}
47新增:
48新增:export function GuestSystemPicker({ system, onChange, preserveOnUnmount = false, deferMatch = false }) {
49新增: const [view, setView] = useState(null);
50新增: const [error, setError] = useState("");
51新增: const [attempt, retry] = useState(0);
52新增: const activated = useRef(false);
53新增: useEffect(() => {
54新增: if (!system?.activate || activated.current) return;
55新增: activated.current = true;
56新增: api("/environment/guest-systems/activate",{}).then(() => native("reconnect")).catch(e => setError(e.message));
57新增: }, [system?.activate]);
58新增: useEffect(() => {
59新增: let active = true;
60新增: setError("");
61新增: api("/environment/guest-systems").then((next) => {
62新增: if (!active) return;
63新增: setView(next);
64新增: if (next.fresh || next.pending) {
65新增: onChange(current => !next.pending && current && !current.pending ? current : ({ guest_system: next.pending?.system || "debian-13", media: next.pending?.media || "",
66新增: sha256: next.pending?.sha256 || "", editor_terms: Boolean(next.pending?.editor_terms),
67新增: clone: Boolean(next.pending?.source && !next.pending?.source_kind), clone_key: "", clone_ready: false,
68新增: activate: next.activate, pending: Boolean(next.pending) }));
69新增: } else onChange(null);
70新增: }).catch((e) => {
71新增: if (!active) return;
72新增: if (e.status === 403 || e.status === 404) onChange(null);
73新增: else setError(e.message);
74新增: });
75新增: return () => { active = false; if (!preserveOnUnmount) onChange(undefined); };
76新增: }, [onChange, attempt, preserveOnUnmount]);
77新增: if (!view || !system) return error ? <div className="guest-system-picker"><span role="alert">{error}</span>
78新增: <button type="button" onClick={() => retry((n) => n + 1)}>重新检查安装选项</button></div> : null;
79新增: const os = system.guest_system;
80新增: const change = (changes) => onChange((current) => current?.guest_system === os ? { ...current, ...changes } : current);
81新增: async function choose() {
82新增: try {
83新增: const path = await native("chooseGuestMedia");
84新增: if (path) change({ media: path });
85新增: } catch (e) { setError(e.message); }
86新增: }
87新增: async function reference(kind) {
88新增: try { await native("guestInstallReference", { kind }); }
89新增: catch (e) { setError(e.message); }
90新增: }
91新增: return (
92新增: <div className="guest-system-picker">
93新增: <span>客户机系统</span>
94新增: {view.system || view.linux_systems?.length ? <InlineSelect aria-label="客户机系统" value={system.clone ? "host" : os} disabled={system.pending}
95新增: onValueChange={(value) => onChange({ guest_system: value === "host" ? view.system : value, clone: value === "host", clone_key: "", clone_ready: false, media: "", sha256: "", editor_terms: false })}>
96新增: {Boolean(view.system) && <option value="host" disabled={!view.available}>自动匹配本机系统版本{view.available ? "" : "(暂不可用)"}</option>}
97新增: <option value="debian-13">Debian 13</option>
98新增: {(view.linux_systems || []).map((id) => <option key={id} value={id}>{names[id]}</option>)}
99新增: {["macos", "windows-11"].includes(view.system) && <option value={view.system} disabled={!view.available}>{names[view.system]}{view.available ? "" : "(暂不可用)"}</option>}
100新增: </InlineSelect> : <strong>Debian 13</strong>}
101新增: {system.clone && !system.activate && (deferMatch ? <small className="guest-install-fields">Cage 会检测本机系统版本。配置代理后匹配官方镜像,并显示下载量与空间要求。</small> : <HostCloneSummary pending={system.pending} onChange={onChange} />)}
102新增: {!system.clone && os !== "debian-13" && !system.activate && <div className="guest-install-fields">
103新增: {os === "ubuntu-22.04" ? <>
104新增: <small>从 Ubuntu 官方源下载 Ubuntu 22.04 LTS 镜像,并校验 SHA-256。Cage 按主机架构选择 ARM64 或 x86_64。</small>
105新增: <small>自动安装开发工具、浏览器和编辑器。客机账户、文件和登录状态保存在独立的持久虚拟磁盘中。</small>
106新增: <small>至少需要 17 GiB 可用空间。失败后可继续原安装,不会改用其他系统或覆盖已有环境。</small>
107新增: </> : os === "macos" ? <>
108新增: <small>{system.media || "将从 Apple 下载 macOS 26.5.2(19.77 GB),并创建 64 GiB 稀疏虚拟磁盘。"}</small>
109新增: {!system.pending && <div>
110新增: <button type="button" onClick={choose}>选择本机 IPSW</button>
111新增: {system.media && <button type="button" onClick={() => change({ media: "" })}>改为下载</button>}
112新增: </div>}
113新增: <small>客机账户和独立密码由 Cage 自动准备并加密保管,启动时自动登录。</small>
114新增: </> : <>
115新增: <small>Windows 11 x64 需要 Hyper-V 和至少 64 GiB 可用磁盘空间。宿主安装开发组件时需要同一 Windows 账户的管理员权限。完成 Windows 安装后,通过客机管理员确认一次,Cage 会创建专用普通账户并重启客机。</small>
116新增: {!system.pending && <div>
117新增: <button type="button" onClick={() => reference("windows-media")}>从微软下载 ISO</button>
118新增: <button type="button" onClick={choose}>选择本机 ISO</button>
119新增: </div>}
120新增: {system.media && <small>{system.media}</small>}
121新增: <label>ISO 的 SHA-256<input value={system.sha256} readOnly={system.pending} spellCheck={false}
122新增: onChange={(e) => change({ sha256: e.target.value.trim() })} placeholder="微软公布的 64 位十六进制摘要" /></label>
123新增: <button type="button" onClick={() => reference("editor-license")}>阅读 Microsoft VS Code Server 许可条款</button>
124新增: <label><input type="checkbox" checked={system.editor_terms} disabled={system.pending}
125新增: onChange={(e) => change({ editor_terms: e.target.checked })} />我接受上述编辑器许可条款</label>
126新增: </>}
127新增: </div>}
128新增: {system.clone && os === "windows-11" && <div className="guest-install-fields">
129新增: <small>安装时需要你确认 Windows 管理员授权,Cage 随后自动安装系统并创建独立客机账户。</small>
130新增: <button type="button" onClick={() => reference("editor-license")}>阅读 Microsoft VS Code Server 许可条款</button>
131新增: <label><input type="checkbox" checked={system.editor_terms} disabled={system.pending}
132新增: onChange={(e) => change({ editor_terms: e.target.checked })} />我接受上述编辑器许可条款</label>
133新增: </div>}
134新增: {view.reason && !view.available && <small className="guest-install-fields">{view.reason}</small>}
135新增: {view.reselect && <button type="button" className="guest-install-fields" onClick={async () => {
136新增: try {
137新增: await api("/environment/guest-systems", { id: view.pending.id }, "DELETE");
138新增: setView(await api("/environment/guest-systems"));
139新增: onChange({ guest_system: "debian-13", media: "", sha256: "", editor_terms: false });
140新增: } catch (e) { setError(e.message); }
141新增: }}>重新选择系统或镜像</button>}
142新增: {system.activate && <small className="guest-install-fields">客机已安装,可以打开工作台。</small>}
143新增: {error && <p role="alert" className="guest-install-fields">{error}</p>}
144新增: </div>
145新增: );
146新增:}
147新增:
148新增:export function validGuestChoice(value) {
149新增: if (value?.clone && !value.activate) return Boolean(value.clone_key && value.clone_ready && (value.guest_system !== "windows-11" || value.editor_terms));
150新增: if (!value || value.activate || value.guest_system === "debian-13" || value.guest_system === "ubuntu-22.04") return true;
151新增: if (value.guest_system === "macos") return true;
152新增: return value.media && /^[a-f\d]{64}$/i.test(value.sha256) && value.editor_terms;
153新增:}
修改ui/src/image-transfer.js+35 −2看文件
@@ -86,5 +86,38 @@ export async function readClipboardContent() {
8686 return { text: await navigator.clipboard.readText() };
8787}
8888
89删除:export const sendImage = (payload, target, id) =>
90删除: api("/input/image", { ...payload, target, id });
89新增:export function prepareClipboardPaste(target, id, { windowTarget, valid = () => true } = {}) {
90新增: let disposed = false, sent = false;
91新增: const destination = { target, id, pid: windowTarget?.pid, window: windowTarget?.window };
92新增: const check = () => {
93新增: if (disposed || !valid()) throw new Error("图片接收位置已切换,请重新粘贴");
94新增: };
95新增: const prepared = api("/input/paste/start", destination).then(result => {
96新增: if (result?.available !== true || typeof result.transfer !== "string" && typeof result.context !== "string")
97新增: throw new Error("客机尚未确认图片接收位置,请同步环境组件后重试");
98新增: return { transfer: result.transfer, context: result.context };
99新增: });
100新增: // The clipboard can turn out to contain text or files. The image-specific
101新增: // preparation error is observed only when this gesture supplies an image.
102新增: void prepared.catch(() => {});
103新增: const dispose = () => {
104新增: if (disposed) return;
105新增: disposed = true;
106新增: void prepared.then(binding => api("/input/paste/cancel", { ...destination, ...binding })).catch(() => {});
107新增: };
108新增: return {
109新增: async send(payload) {
110新增: check();
111新增: const binding = await prepared;
112新增: check();
113新增: if (sent) throw new Error("本次图片已经提交,请核对接收结果");
114新增: sent = true;
115新增: try { return await api(typeof payload.text === "string" ? "/input/text" : "/input/image", { ...payload, ...destination, ...binding }); }
116新增: finally { dispose(); }
117新增: },
118新增: dispose,
119新增: };
120新增:}
121新增:
122新增:export const sendImage = (payload, target, id, options = {}) =>
123新增: (options.prepared || prepareClipboardPaste(target, id, options)).send(payload);
新增ui/src/initialization.css+47 −0看文件
@@ -0,0 +1,47 @@
1新增:.initialization { height: 100%; min-height: 0; overflow: auto; background: var(--paper); color: var(--ink); }
2新增:.initialization-brand { display: flex; align-items: center; gap: 10px; padding: 24px 32px; }
3新增:.initialization-brand img { width: 28px; height: 28px; }
4新增:.initialization-brand strong { font-size: 18px; color: var(--strong); }
5新增:.initialization-brand > span { margin-left: 8px; color: var(--muted); font-size: 14px; }
6新增:.initialization-content { width: min(720px, calc(100% - 64px)); margin: 32px auto 60px; line-height: 1.65; animation: initialization-enter 180ms ease-out; }
7新增:.initialization-steps { display: flex; gap: 24px; list-style: none; padding: 0; margin: 0 0 36px; color: var(--muted); font-size: 14px; }
8新增:.initialization-steps li { display: flex; align-items: center; gap: 8px; }
9新增:.initialization-steps li > span { display: grid; place-items: center; width: 26px; height: 26px; border: 1px solid var(--line); border-radius: 50%; flex: none; transition: background 150ms; }
10新增:.initialization-steps [aria-current] { color: var(--strong); font-weight: 550; }
11新增:.initialization-steps [aria-current] > span { background: var(--strong); color: var(--paper); border-color: var(--strong); }
12新增:.initialization-title { margin-bottom: 28px; }
13新增:.initialization h1 { font-size: 28px; line-height: 1.3; font-weight: 550; letter-spacing: -.4px; margin: 0 0 12px; color: var(--strong); }
14新增:.initialization-title > p { margin: 0; color: var(--muted); font-size: 15px; }
15新增:.initialization-stage { animation: initialization-enter 160ms ease-out; }
16新增:.initialization .guest-system-picker { padding: 0; margin-bottom: 28px; font-size: 15px; }
17新增:.initialization .guest-install-fields small { font-size: 14px; line-height: 1.65; }
18新增:.initialization .host-clone-summary { padding: 18px; gap: 10px; background: var(--chrome); }
19新增:.initialization .environment-storage { padding-top: 22px; border-top: 1px solid var(--line); }
20新增:.initialization .environment-storage > h4 { font-size: 16px; margin: 0 0 8px; }
21新增:.initialization .field-help { color: var(--muted); font-size: 14px; }
22新增:.initialization .environment-storage label { display: grid; gap: 8px; margin: 16px 0 10px; }
23新增:.initialization .environment-storage input { width: 100%; box-sizing: border-box; min-height: 40px; border: 1px solid var(--line); border-radius: 8px; padding: 8px 12px; background: var(--input); color: var(--ink); font: inherit; }
24新增:.initialization .setting-summary-row { display: flex; gap: 12px; flex-wrap: wrap; font-size: 14px; }
25新增:.initialization .setting-summary-row strong { font-weight: 500; overflow-wrap: anywhere; }
26新增:.initialization .proxy-manager { margin: 0; }
27新增:.initialization-actions { display: flex; justify-content: space-between; gap: 16px; align-items: center; padding-top: 24px; margin-top: 28px; border-top: 1px solid var(--line); }
28新增:.initialization-actions button { min-height: 40px; }
29新增:.initialization button { transition: background 150ms, transform 100ms; }
30新增:.initialization button:active:not(:disabled) { transform: translateY(1px); }
31新增:.initialization button:focus-visible { outline: 2px solid var(--focus); outline-offset: 3px; }
32新增:.initialization-support { display: flex; gap: 20px; flex-wrap: wrap; margin-top: 20px; color: var(--muted); }
33新增:.initialization .settings-group { margin-top: 22px; }
34新增:.initialization-notice { padding: 16px; margin: 16px 0; border: 1px solid var(--line); border-radius: 10px; overflow-wrap: anywhere; }
35新增:.initialization-notice h2 { font-size: 17px; margin: 0 0 8px; }
36新增:.initialization-notice button { margin-top: 10px; margin-right: 10px; }
37新增:.initialization-notice pre, .initialization .job-log { white-space: pre-wrap; overflow-wrap: anywhere; font-size: 13px; }
38新增:.initialization-operation { padding: 24px; background: var(--chrome); border-radius: 12px; }
39新增:.initialization-operation p { margin: 8px 0 16px; }
40新增:.initialization-recovery { display: flex; gap: 12px; flex-wrap: wrap; margin-top: 20px; }
41新增:.initialization-ready { padding: 30px 24px; border-radius: 12px; background: var(--chrome); text-align: center; }
42新增:.initialization-ready svg { color: var(--success); }
43新增:.initialization-ready h2 { margin: 12px 0; font-size: 20px; }
44新增:.initialization-ready p, .initialization-network { color: var(--muted); font-size: 14px; }
45新增:@keyframes initialization-enter { from { opacity: 0; transform: translateY(5px); } to { opacity: 1; transform: none; } }
46新增:@media (max-width: 600px) { .initialization-brand { padding: 18px 20px; } .initialization-content { width: calc(100% - 40px); margin-top: 20px; } .initialization-steps { gap: 12px; flex-wrap: wrap; font-size: 13px; margin-bottom: 26px; } .initialization h1 { font-size: 25px; } .initialization .guest-system-picker { grid-template-columns: 1fr; } .initialization .storage-actions { flex-wrap: wrap; } }
47新增:@media (prefers-reduced-motion: reduce) { .initialization-content, .initialization-stage { animation: none; } .initialization button { transition: none; } }
新增ui/src/initialization.jsx+210 −0看文件
@@ -0,0 +1,210 @@
1新增:import React, { useEffect, useRef, useState } from "react";
2新增:import { Check, ChevronLeft, LoaderCircle, ShieldCheck } from "lucide-react";
3新增:import { api, native, nativeAvailable } from "./api";
4新增:import { isRemoteClient } from "./client-context.mjs";
5新增:import { useAccount } from "./account";
6新增:import { GuestSystemPicker, HostCloneSummary, validGuestChoice } from "./guest-system-picker";
7新增:import { EnvironmentStorage } from "./environment-storage";
8新增:import { ProxySettings } from "./proxy-settings";
9新增:import { SetupProgress } from "./setup-progress";
10新增:import { DiagnosticSettings } from "./diagnostics.jsx";
11新增:import { MacOSFirstSetup } from "./macos-first-setup";
12新增:import { Modal } from "./modal";
13新增:import { SafetyMessage } from "./safety-message";
14新增:import { needsProxySetup } from "./onboarding-state.mjs";
15新增:import { networkState } from "./safety-state.mjs";
16新增:import { useSSHNavigation } from "./remote-hosts";
17新增:import logo from "./logo.png";
18新增:import "./initialization.css";
19新增:
20新增:const steps = [["system", "系统与存储"], ["proxy", "网络代理"], ["install", "安装与检查"]];
21新增:
22新增:function InitializationFrame({ children }) {
23新增: return <main className="initialization"><header className="initialization-brand"><img src={logo} alt="" /><strong>Cage</strong><span>首次设置</span></header>{children}</main>;
24新增:}
25新增:
26新增:export function InitializationGate({ children }) {
27新增: const { account } = useAccount();
28新增: const [state, setState] = useState(null);
29新增: const [error, setError] = useState("");
30新增: const [attempt, retry] = useState(0);
31新增: const remote = isRemoteClient();
32新增: useEffect(() => {
33新增: if (remote) return;
34新增: let live = true;
35新增: setError("");
36新增: (async () => {
37新增: const next = await api("/environment/initialization");
38新增: if (next.required && !next.tracked && !next.started && !account?.initial_mac_setup) await api("/environment/initialization", { action: "begin" });
39新增: if (live) setState(next);
40新增: })().catch(error => { if (live) setError(error.message); });
41新增: return () => { live = false; };
42新增: }, [remote, attempt, account?.initial_mac_setup]);
43新增: if (remote) return children;
44新增: if (account?.initial_mac_setup) return <MacOSFirstSetup />;
45新增: if (error) return <InitializationFrame><section className="initialization-content"><h1>继续准备 Cage</h1><p role="alert"><SafetyMessage message={error} /></p><button className="primary" onClick={() => retry(value => value + 1)}>重新连接</button><DiagnosticSettings /></section></InitializationFrame>;
46新增: if (!state) return <InitializationFrame><section className="initialization-content"><h1>正在读取环境状态</h1><p role="status"><LoaderCircle size={18} className="spin" />正在检查已有配置和安装进度…</p></section></InitializationFrame>;
47新增: return state.required ? <Initialization initial={state} onComplete={() => setState({ required: false })} /> : children;
48新增:}
49新增:
50新增:function Initialization({ initial, onComplete }) {
51新增: const { account, refresh } = useAccount();
52新增: const navigation = useSSHNavigation();
53新增: const [step, setStep] = useState(initial.started || account?.guest_system ? "install" : "system");
54新增: const [status, setStatus] = useState(null);
55新增: const [proxy, setProxy] = useState(null);
56新增: const [choice, setChoice] = useState(undefined);
57新增: const [pending, setPending] = useState(null);
58新增: const [submitting, setSubmitting] = useState(false);
59新增: const [error, setError] = useState("");
60新增: const [connectionError, setConnectionError] = useState("");
61新增: const [git, setGit] = useState(null);
62新增: const [details, setDetails] = useState(false);
63新增: const [help, setHelp] = useState(false);
64新增: const [dialog, setDialog] = useState(null);
65新增: const [proxyDirty, setProxyDirty] = useState(false);
66新增: const alive = useRef(true);
67新增: const pollNow = useRef(null);
68新增: const activation = useRef(false);
69新增: const actionPending = useRef(false);
70新增: const job = status?.job || {};
71新增: const busy = submitting || Boolean(job.running);
72新增: const network = networkState(status);
73新增: const ready = Boolean(status?.ready && status.vm_running && !busy && !job.error && network.mode === "open");
74新增: const confirm = options => new Promise(resolve => setDialog({ ...options, resolve }));
75新增: const settleDialog = value => { dialog?.resolve(value); setDialog(null); };
76新增:
77新增: useEffect(() => {
78新增: alive.current = true;
79新增: let timer, polling = false;
80新增: async function poll() {
81新增: if (polling || !alive.current) return;
82新增: clearTimeout(timer);
83新增: polling = true;
84新增: try {
85新增: const next = await api("/status");
86新增: if (!alive.current) return;
87新增: setStatus(next);
88新增: setConnectionError("");
89新增: const results = await Promise.allSettled([
90新增: api("/proxy"),
91新增: account?.guest_system ? Promise.resolve(null) : api("/environment/guest-systems"),
92新增: ]);
93新增: if (!alive.current) return;
94新增: if (results[0].status === "fulfilled") setProxy(results[0].value);
95新增: else setConnectionError(results[0].reason.message);
96新增: if (results[1].status === "fulfilled") {
97新增: const install = results[1].value;
98新增: setPending(install?.pending || null);
99新增: if (install?.activate && !activation.current) {
100新增: activation.current = true;
101新增: setStep("install");
102新增: try {
103新增: await api("/environment/guest-systems/activate", {});
104新增: await native("reconnect");
105新增: } catch (error) {
106新增: activation.current = false;
107新增: if (alive.current) setError(error.message);
108新增: }
109新增: }
110新增: } else setConnectionError(results[1].reason.message);
111新增: if (next.job?.running && ["start", "guest-install", "safety"].includes(next.job.kind)) setStep("install");
112新增: } catch (error) { if (alive.current) setConnectionError(error.message); }
113新增: finally {
114新增: polling = false;
115新增: if (alive.current) timer = setTimeout(poll, 1200);
116新增: }
117新增: }
118新增: pollNow.current = poll;
119新增: poll();
120新增: if (nativeAvailable()) native("workbenchReady").catch(() => {});
121新增: window.cageNativeAction = async action => { if (action === "quit") await native("quitNow"); };
122新增: return () => { alive.current = false; clearTimeout(timer); pollNow.current = null; delete window.cageNativeAction; };
123新增: }, [account?.guest_system]);
124新增:
125新增: async function run(operation) {
126新增: if (actionPending.current) return;
127新增: actionPending.current = true;
128新增: setSubmitting(true); setError("");
129新增: try { await operation(); }
130新增: catch (error) { if (alive.current) setError(error.message); }
131新增: finally { actionPending.current = false; if (alive.current) { setSubmitting(false); pollNow.current?.(); } }
132新增: }
133新增: function startOptions() {
134新增: if (account?.guest_system) return {};
135新增: if (pending) return { guest_system: pending.system };
136新增: if (!choice) return job.setup_progress?.system ? { guest_system: job.setup_progress.system } : {};
137新增: return { guest_system: choice.guest_system, media: choice.media, sha256: choice.sha256, clone_key: choice.clone_key, editor_terms: choice.editor_terms };
138新增: }
139新增: async function install() {
140新增: if (needsProxySetup(null, status, proxy)) { setError("请先选择并应用代理节点。"); setStep("proxy"); return; }
141新增: await run(async () => {
142新增: const check = await api("/host/git");
143新增: if (!check.ready) { setGit(check); return; }
144新增: await api("/environment/initialization", { action: "install" });
145新增: const accepted = await api("/start", startOptions());
146新增: if (!alive.current) return;
147新增: setGit(null); setStep("install");
148新增: setStatus(current => ({ ...current, job: { ...accepted, running: true, kind: accepted.kind || "start", message: accepted.message || "正在准备客机环境…" } }));
149新增: });
150新增: }
151新增: async function enableGit() {
152新增: await run(async () => { const next = await api("/host/git", { confirm: true }); setGit(next.ready ? null : next); });
153新增: }
154新增: async function stop() {
155新增: if (!await confirm({ title: "停止当前安装?", body: "安装进度、已下载文件和虚拟磁盘会保留。你可以在此界面继续安装。", confirm: "停止安装" })) return;
156新增: await run(async () => { const accepted = await api("/stop", {}); setStatus(current => ({ ...current, job: { ...accepted, running: true } })); });
157新增: }
158新增: async function enter() {
159新增: await run(async () => { await api("/environment/initialization", { action: "complete" }); await refresh(); if (alive.current) onComplete(); });
160新增: }
161新增: async function checkNetwork() {
162新增: await run(async () => {
163新增: const accepted = await api("/safety/check", {});
164新增: setStatus(current => ({ ...current, job: { ...accepted, running: true, kind: "safety", message: "正在检查代理出口和环境隔离…" } }));
165新增: });
166新增: }
167新增: async function back() {
168新增: if (step === "proxy" && proxyDirty && !await confirm({ title: "放弃尚未应用的代理修改?", body: "已经保存并应用的代理会保留,当前未应用的表单修改会丢弃。", confirm: "放弃修改" })) return;
169新增: setProxyDirty(false);
170新增: setStep(step === "install" ? "proxy" : "system");
171新增: }
172新增: const failed = Boolean(job.error || error);
173新增: const progress = job.setup_progress && { ...job, setup_progress: job.setup_progress };
174新增: const title = step === "system" ? "为 Cage 准备独立环境" : step === "proxy" ? "连接你的网络代理" : ready ? "Cage 已准备就绪" : failed ? "继续完成环境安装" : busy ? "正在准备你的环境" : "安装并检查客机环境";
175新增: const index = steps.findIndex(([key]) => key === step);
176新增: return <InitializationFrame>
177新增: <section className="initialization-content">
178新增: <ol className="initialization-steps" aria-label="初始化步骤">{steps.map(([key, label], position) => <li key={key} aria-current={step === key ? "step" : undefined}><span>{position < index ? <Check size={14} /> : position + 1}</span>{label}</li>)}</ol>
179新增: <div className="initialization-title"><h1>{title}</h1><p>{step === "system" ? "选择客机系统和存储位置。初始化完成后,再进入工作台。" : step === "proxy" ? "系统镜像与开发工具通过所选代理下载。配置会保留供环境日常使用。" : ready ? "系统、开发组件和网络检查均已完成,可以进入工作台开始使用。" : "下载、安装、必要授权和检查都在这里完成。中断后可以继续原任务。"}</p></div>
180新增: {connectionError && <div className="initialization-notice" role="alert"><SafetyMessage message={connectionError} /><button onClick={() => pollNow.current?.()}>重新连接</button></div>}
181新增: {!status ? <p role="status"><LoaderCircle size={18} className="spin" />正在读取安装状态…</p> : <>
182新增: <div className="initialization-stage" key={step}>
183新增: {step === "system" && <>
184新增: <GuestSystemPicker system={choice} onChange={setChoice} preserveOnUnmount deferMatch />
185新增: <EnvironmentStorage status={status} onConfirm={confirm} />
186新增: </>}
187新增: {step === "proxy" && <><ProxySettings initializing status={status} onConfirm={confirm} onDirty={setProxyDirty} onApplied={async () => { setProxy(await api("/proxy")); pollNow.current?.(); }} />{choice?.clone && !needsProxySetup(null, status, proxy) && <HostCloneSummary pending={choice.pending} onChange={setChoice} />}</>}
188新增: {step === "install" && (ready ? <div className="initialization-ready"><ShieldCheck size={36} /><h2>环境已就绪</h2><p>独立客机已安装,工具、文件和登录状态会持续保存。以后打开 Cage 可直接进入工作台。</p></div> : <>
189新增: {progress ? <SetupProgress job={progress} onDetails={() => setDetails(true)} onStop={stop} onRetry={install} disconnected={Boolean(connectionError) || submitting} /> : <div className="initialization-operation" role="status">{busy && <LoaderCircle size={22} className="spin" />}<p>{job.message || (status.vm_running ? "请完成客机连接和网络检查。" : "准备继续原安装,已有文件和磁盘会保留。")}</p>{!busy && !job.error && <button className="primary" disabled={Boolean(connectionError)} onClick={install}>{status.ready ? "重新启动并检查" : "继续安装"}</button>}{busy && <button onClick={stop} disabled={submitting}>停止安装</button>}</div>}
190新增: {job.error && !progress && <div className="initialization-notice" role="alert"><SafetyMessage message={job.error} /><button className="primary" disabled={busy || Boolean(connectionError)} onClick={install}>继续安装</button></div>}
191新增: {status.ready && network.mode !== "open" && !busy && <div className="initialization-network"><p>{status.network_error || status.safety?.error || "客机已经连接,请完成网络和隔离检查后进入工作台。"}</p><button className="primary" disabled={Boolean(connectionError)} onClick={checkNetwork}>运行网络与隔离检查</button></div>}
192新增: <div className="initialization-recovery"><button onClick={() => setStep("proxy")} disabled={busy}>检查代理配置</button>{!progress && <button onClick={() => setDetails(true)}>查看操作详情</button>}</div>
193新增: </>)}
194新增: </div>
195新增: {git && <section className="initialization-notice" aria-label="Git 安全保护"><h2>安装前,保护本机 Git</h2><p>{git.message}</p>{git.can_enable && <><p>启用后,Git 会忽略未经你明确指定的裸仓库。该操作会修改当前用户的全局设置,影响本机其他 Git 工具,普通项目保持原有操作。</p><pre>git config --global safe.bareRepository explicit</pre><button className="primary" disabled={busy} onClick={enableGit}>启用 Git 保护</button></>}<button disabled={busy} onClick={install}>重新检查并安装</button></section>}
196新增: {error && <p className="initialization-notice" role="alert"><SafetyMessage message={error} /></p>}
197新增: <footer className="initialization-actions">
198新增: {step === "system" ? <span /> : <button className="text-button" disabled={busy} onClick={back}><ChevronLeft size={16} />上一步</button>}
199新增: {step === "system" && <button className="primary" disabled={busy || choice === undefined || (!choice?.clone && !validGuestChoice(choice)) || choice?.clone && choice.guest_system === "windows-11" && !choice.editor_terms || Boolean(connectionError)} onClick={() => setStep("proxy")}>下一步:配置代理</button>}
200新增: {step === "proxy" && <button className="primary" disabled={busy || proxyDirty || !account?.guest_system && !pending && !validGuestChoice(choice) || needsProxySetup(null, status, proxy) || Boolean(connectionError)} onClick={install}>{submitting ? <LoaderCircle size={16} className="spin" /> : null}开始安装</button>}
201新增: {step === "install" && ready && <button className="primary" disabled={submitting || Boolean(connectionError)} onClick={enter}>进入工作台</button>}
202新增: </footer>
203新增: </>}
204新增: <div className="initialization-support"><button className="text-button" aria-expanded={help} onClick={() => setHelp(!help)}>日志与诊断</button>{navigation && !busy && <button className="text-button" onClick={() => navigation.open()}>只连接 SSH 主机</button>}</div>
205新增: {help && <DiagnosticSettings />}
206新增: </section>
207新增: {details && <Modal title="初始化操作详情" onClose={() => setDetails(false)}><div className="modal-body"><pre className="job-log">{job.log || job.message || "暂无操作记录"}</pre></div></Modal>}
208新增: {dialog && <Modal title={dialog.title} onClose={() => settleDialog(false)} footer={<><button onClick={() => settleDialog(false)}>取消</button><button className="primary" onClick={() => settleDialog(true)}>{dialog.confirm}</button></>}><div className="modal-body"><p>{dialog.body}</p></div></Modal>}
209新增: </InitializationFrame>;
210新增:}
修改ui/src/inline-select.jsx+2 −1看文件
@@ -9,6 +9,7 @@ export function InlineSelect({
99 onValueChange,
1010 disabled,
1111 editable = false,
12新增: displayLabel,
1213 ...props
1314}) {
1415 const id = useId();
@@ -148,7 +149,7 @@ export function InlineSelect({
148149 open ? setOpen(false) : show();
149150 }}
150151 >
151删除: <span>{selected?.label || value}</span>
152新增: <span>{displayLabel ?? selected?.label ?? value}</span>
152153 <ChevronDown size={14} aria-hidden="true" />
153154 </button>
154155 )}
新增ui/src/macos-claude-window.css+5 −0看文件
@@ -0,0 +1,5 @@
1新增:.mac-claude { height: 100%; display: flex; flex-direction: column; min-height: 0; }
2新增:.mac-claude p { margin: 10px 16px; }
3新增:.mac-claude-frame { flex: 1; min-height: 0; min-width: 0; overflow: hidden; background: var(--paper); display: flex; align-items: center; justify-content: center; position: relative; container-type: size; }
4新增:.mac-claude-frame img { display: block; max-width: 100%; max-height: 100%; width: min(100%, calc(var(--frame-width, 600px) * var(--desktop-zoom, 1)), calc(100cqh * var(--frame-aspect, 1))); height: auto; object-fit: contain; user-select: none; }
5新增:.mac-claude-typing { position: absolute; width: 1px; height: 1px; bottom: 0; left: 0; opacity: 0; }
新增ui/src/macos-claude-window.jsx+312 −0看文件
@@ -0,0 +1,312 @@
1新增:import React, { useEffect, useImperativeHandle, useLayoutEffect, useRef, useState } from "react";
2新增:import { DesktopToolbar, useDesktopZoom } from "./claude-desktop";
3新增:import { MacOSLogin } from "./macos-login";
4新增:import { api, native, nativeAvailable } from "./api";
5新增:import { BrowserUploads } from "./browser-uploads";
6新增:import { sendFiles } from "./file-transfer";
7新增:import { prepareClipboardPaste, sendImage } from "./image-transfer";
8新增:import { installRemoteInput } from "./remote-input";
9新增:import { createMacWindowInput } from "./macos-window-input.mjs";
10新增:import { copyGuestText } from "./shared-clipboard.mjs";
11新增:import { useWindowVisibility } from "./window-visibility";
12新增:import { createMacWindowConnection } from "./macos-window-connection.mjs";
13新增:import { createMacFrameConnection } from "./macos-frame-connection.mjs";
14新增:import "./macos-claude-window.css";
15新增:
16新增:const messages = {
17新增: requires_gui_login: "请先登录并解锁虚拟 Mac 的图形账户。",
18新增: screen_recording_permission: "请在虚拟 Mac 的系统授权中,允许 Cage Guest Window 录制屏幕。",
19新增: accessibility_permission: "要操作窗口,请允许虚拟 Mac 中的 Cage Guest Window 使用辅助功能。",
20新增: not_running: "请打开虚拟 Mac 中的 Claude Desktop。",
21新增: no_visible_window: "Claude 尚未显示窗口,请重新打开应用。",
22新增: identity_error: "虚拟 Mac 中的应用未通过 Anthropic 签名检查。",
23新增: window_changed: "Claude 的活动窗口已变化,请打开应用并在新画面中重试。",
24新增: unknown_action: "客机窗口输入组件需要更新,请在环境设置中更新组件后重试。",
25新增: input_connection_required: "窗口输入需要重新连接,请恢复画面后重试。",
26新增: input_owned_by_another_view: "另一个连接正在操作此窗口,请等待它释放按键或拖动。",
27新增:};
28新增:
29新增:async function windowRequest(action, fields = {}, connection) {
30新增: const result = connection ? await connection.request(action, fields) : await api("/macos/claude/window", { action, ...fields });
31新增: if (result.error) {
32新增: const error = new Error(messages[result.error] || "未能读取或操作虚拟 Mac 中的应用窗口。");
33新增: error.code = result.error;
34新增: throw error;
35新增: }
36新增: return result;
37新增:}
38新增:
39新增:// Fixed-size native sign-in sheets stay at their real text size. Extend a
40新增:// uniform window background across the pane without scaling those pixels.
41新增:function matchWindowBackground(img, pane, canvasRef) {
42新增: if (!pane) return;
43新增: if (img.clientWidth >= pane.clientWidth - 1 && img.clientHeight >= pane.clientHeight - 1) return;
44新增: if (!canvasRef.current) {
45新增: canvasRef.current = document.createElement("canvas");
46新增: canvasRef.current.width = 4;
47新增: canvasRef.current.height = 1;
48新增: }
49新增: const canvas = canvasRef.current;
50新增: const ctx = canvas.getContext("2d", {willReadFrequently:true});
51新增: if (!ctx) return;
52新增: const w = img.naturalWidth, h = img.naturalHeight;
53新增: if (w < 16 || h < 16) return;
54新增: [[8,8],[w-9,8],[8,h-9],[w-9,h-9]].forEach(([x,y],i) =>
55新增: ctx.drawImage(img,x,y,1,1,i,0,1,1));
56新增: const pixels = ctx.getImageData(0,0,4,1).data;
57新增: const uniform = pixels.every((value, index) => Math.abs(value - pixels[index % 4]) <= 4);
58新增: pane.style.backgroundColor = uniform && pixels[3] === 255 ? `rgb(${pixels[0]}, ${pixels[1]}, ${pixels[2]})` : "";
59新增:}
60新增:
61新增:export function MacOSClaudeWindow({ visible, keyboard = "mac", remoteRef, sidebarCollapsed, onExpand, onConfirm, uploads = [], onStatus = () => {}, onFallback = () => {} }) {
62新增: const windowVisible = useWindowVisibility();
63新增: const screenVisible = visible && windowVisible;
64新增: const connection = useRef(null);
65新增: const [inputChannel, setInputChannel] = useState(null);
66新增: const frameConnection = useRef(null);
67新增: const request = (action, fields) => windowRequest(action, fields, connection.current);
68新增: const [zoom, setZoom] = useDesktopZoom();
69新增: const [state, setState] = useState(null);
70新增: const [error, setError] = useState("");
71新增: const [fileError, setFileError] = useState("");
72新增: const [transferring, setTransferring] = useState(false);
73新增: const [revision, refresh] = useState(0);
74新增: const [image, setImage] = useState(null);
75新增: const frame = useRef(null);
76新增: const surface = useRef(null);
77新增: const controls = useRef(null);
78新增: const current = useRef(null);
79新增: current.current = { screenVisible, keyboard, input: state?.input, onStatus, onFallback };
80新增: const pane = useRef(null);
81新增: const backgroundSample = useRef(null);
82新增: const viewport = useRef(null);
83新增: useLayoutEffect(() => {
84新增: const element = pane.current;
85新增: if (!visible || !element) return;
86新增: const measure = () => {
87新增: const { width, height } = element.getBoundingClientRect();
88新增: viewport.current = width > 0 && height > 0 ? {
89新增: width: Math.min(2560, Math.max(320, Math.round(width / zoom))),
90新增: height: Math.min(1600, Math.max(240, Math.round(height / zoom))),
91新增: } : null;
92新增: frameConnection.current?.resize(viewport.current);
93新增: };
94新增: measure();
95新增: const observer = new ResizeObserver(measure);
96新增: observer.observe(element);
97新增: return () => { observer.disconnect(); viewport.current = null; };
98新增: }, [visible, zoom]);
99新增: const picker = useRef(null);
100新增: const pickerTarget = useRef(null);
101新增: const generation = useRef(0);
102新增: const launched = useRef(false);
103新增:
104新增: useEffect(() => {
105新增: if (!screenVisible) return;
106新增: const epoch = ++generation.current;
107新增: let timer;
108新增: let current, nextStatus = 0, after = "", captureSize = "", checkFrame = true;
109新增: const live = () => generation.current === epoch;
110新增: function receiveFrame(next) {
111新增: if (!live()) return;
112新增: if (frame.current?.window !== next.window || frame.current?.pid !== next.pid || frame.current?.geometry !== next.geometry) frame.current = null;
113新增: setImage({
114新增: src: next.src || `data:${next.mime === "image/jpeg" ? "image/jpeg" : "image/png"};base64,${next.image}`,
115新增: window: next.window, pid: next.pid,
116新增: geometry: next.geometry, width: next.contentWidth, height: next.contentHeight,
117新增: acknowledge: next.acknowledge,
118新增: });
119新增: setError("");
120新增: }
121新增: async function poll() {
122新增: let delay = 2200;
123新增: try {
124新增: if (!current || Date.now() >= nextStatus) {
125新增: current = await request("status");
126新增: checkFrame = true;
127新增: nextStatus = Date.now() + 2200;
128新增: if (live() && current.persistent && !connection.current) {
129新增: connection.current = createMacWindowConnection();
130新增: setInputChannel(connection.current);
131新增: }
132新增: }
133新增: if (!live()) return;
134新增: setState(current);
135新增: // Opening this tab focuses the signed guest application. A background
136新增: // Electron window can still be captured but cannot receive targeted input.
137新增: if (current.installed && !launched.current) {
138新增: launched.current = true;
139新增: await request("launch");
140新增: nextStatus = 0;
141新增: delay = 100;
142新增: return;
143新增: }
144新增: if (current.running && current.screen) {
145新增: if (current.push_frames && viewport.current) {
146新增: if (!frameConnection.current) {
147新增: frameConnection.current = createMacFrameConnection(receiveFrame, reason => {
148新增: if (!live()) return;
149新增: frameConnection.current = null;
150新增: nextStatus = 0;
151新增: frame.current = null;
152新增: setImage(null);
153新增: setError(messages[reason] || "未能读取虚拟 Mac 的窗口画面,请重新连接。");
154新增: });
155新增: }
156新增: frameConnection.current.resize(viewport.current);
157新增: return;
158新增: }
159新增: const nextSize = JSON.stringify(viewport.current);
160新增: if (nextSize !== captureSize) { after = ""; captureSize = nextSize; }
161新增: const next = await request("frame", viewport.current ? {
162新增: after, refresh: checkFrame,
163新增: ...viewport.current, scale: Math.max(1, Math.min(2, window.devicePixelRatio || 1)),
164新增: } : {});
165新增: if (!live()) return;
166新增: checkFrame = false;
167新增: delay = current.persistent ? 50 : 350;
168新增: if (next.unchanged) return;
169新增: after = next.sequence || "";
170新增: receiveFrame(next);
171新增: } else { frameConnection.current?.close(); frameConnection.current = null; frame.current = null; setImage(null); }
172新增: setError("");
173新增: } catch (e) {
174新增: if (!live()) return;
175新增: connection.current?.close(); connection.current = null;
176新增: setInputChannel(null);
177新增: frameConnection.current?.close(); frameConnection.current = null;
178新增: current = null; after = "";
179新增: if (live()) { frame.current = null; setImage(null); setError(e.message); }
180新增: } finally { if (live()) timer = setTimeout(poll, delay); }
181新增: }
182新增: poll();
183新增: return () => {
184新增: generation.current++; clearTimeout(timer); frame.current = null;
185新增: connection.current?.close(); connection.current = null;
186新增: setInputChannel(null);
187新增: frameConnection.current?.close(); frameConnection.current = null;
188新增: };
189新增: }, [screenVisible, revision]);
190新增:
191新增: async function action(name) {
192新增: try { if (name === "stop") launched.current = true; await request(name); setError(""); refresh((n) => n + 1); }
193新增: catch (e) { setError(e.message); }
194新增: }
195新增: useImperativeHandle(remoteRef, () => ({
196新增: focus: () => controls.current?.transport.focus(),
197新增: edit: command => controls.current?.input.focused() ? controls.current.input.edit(command) : false,
198新增: copy: () => controls.current?.input.copy(),
199新增: paste: () => controls.current?.input.readAndPaste(),
200新增: pasteText: text => controls.current?.input.paste(text),
201新增: transfer: () => onFallback("", "可在此使用本机复制、粘贴。"),
202新增: }));
203新增:
204新增: useEffect(() => {
205新增: if (!screenVisible || !state?.input || !surface.current || !pane.current || (state.persistent && !inputChannel)) return;
206新增: const inputRequest = (action, fields) => windowRequest(action, fields, inputChannel);
207新增: const transport = createMacWindowInput({
208新增: element: surface.current,
209新增: frame: () => frame.current,
210新增: active: () => Boolean(current.current.screenVisible && current.current.input && frame.current),
211新增: request: inputRequest,
212新增: onError: setError,
213新增: });
214新增: const preparePaste = () => {
215新增: const lease = { target: transport.target(), epoch: generation.current, transport };
216新增: return Object.assign(prepareClipboardPaste("desktop", "", { windowTarget: lease.target, valid: () => transport.valid(lease.target) }), { lease });
217新增: };
218新增: const input = installRemoteInput(transport, pane.current, {
219新增: mode: () => current.current.keyboard,
220新增: guestPlatform: () => "darwin",
221新增: systemClipboard: () => true,
222新增: copyText: (sendCopy, valid) => copyGuestText({ request: value => api("/clipboard/copy", value), sendCopy, valid }),
223新增: surface: () => surface.current,
224新增: inputLabel: "向 Claude Desktop 输入",
225新增: tabId: () => frame.current ? `${frame.current.pid}:${frame.current.window}:${frame.current.geometry}` : "",
226新增: isActive: () => Boolean(current.current.screenVisible && current.current.input && frame.current),
227新增: onStatus: text => current.current.onStatus(text),
228新增: onFallback: (...values) => current.current.onFallback(...values),
229新增: insertText: text => transport.send("text", { text }),
230新增: caretRect: session => inputRequest("ime", { ...frame.current, mode: "status", session }).catch(error => {
231新增: if (error.code === "unknown_action") setError(error.message);
232新增: return { available: false };
233新增: }),
234新增: insertComposition: (_, value) => transport.send("ime", value).then(result => {
235新增: if (value.mode !== "cancel" && !result.available) throw new Error("输入位置已变化,请重新输入");
236新增: return result;
237新增: }),
238新增: preparePaste,
239新增: pasteContent: (content, prepared) => receive(content, prepared?.lease || { target: transport.target(), epoch: generation.current, transport }, prepared),
240新增: });
241新增: controls.current = { transport, input };
242新增: return () => {
243新增: input.dispose(); transport.dispose();
244新增: if (controls.current?.transport === transport) controls.current = null;
245新增: };
246新增: }, [screenVisible, state?.input, state?.persistent, inputChannel, image?.geometry, image?.pid, image?.window]);
247新增:
248新增: function receive(content, lease, prepared) {
249新增: const target = lease?.target || frame.current;
250新增: const epoch = lease?.epoch ?? generation.current;
251新增: const transport = lease?.transport || controls.current?.transport;
252新增: const valid = () => target && epoch === generation.current && transport?.valid(target);
253新增: const ready = Promise.resolve(content).then(value => ({ value }), error => ({ error }));
254新增: if (!transport) { prepared?.dispose(); return Promise.reject(new Error("窗口尚未连接,请稍后重试")); }
255新增: return transport.run(async () => {
256新增: const { value, error } = await ready;
257新增: if (error) throw error;
258新增: if (!valid()) throw new Error("Claude 窗口已切换,请回到原窗口重新传递附件");
259新增: setFileError(""); setTransferring(true);
260新增: if (value.files || value.fileSelection) {
261新增: await sendFiles(value, "desktop", "", { valid, windowTarget: target, onProgress: (loaded, total) => onStatus(total ? `正在传递附件 · ${Math.floor(loaded * 100 / total)}%` : "正在传递附件…") });
262新增: } else if (value.png) {
263新增: await sendImage(value, "desktop", "", { prepared });
264新增: } else if (value.text) {
265新增: await request("text", { ...target, text: value.text });
266新增: }
267新增: if (valid()) onStatus(value.text ? "已粘贴" : "附件已交给 Claude Desktop,请在应用中确认上传结果");
268新增: }).finally(() => { prepared?.dispose(); setTransferring(false); });
269新增: }
270新增: const fileFailure = error => { setFileError(error.message); onStatus(error.message); };
271新增: async function chooseFiles() {
272新增: const lease = { target: frame.current, epoch: generation.current, transport: controls.current?.transport };
273新增: if (!nativeAvailable()) { pickerTarget.current = lease; picker.current?.click(); return; }
274新增: try {
275新增: const selected = await native("chooseUploadFiles", { multiple: true });
276新增: if (!selected.canceled) await receive({ fileSelection: selected.fileSelection, kind: "paste" }, lease);
277新增: } catch (error) { fileFailure(error); }
278新增: }
279新增: if (!visible) return null;
280新增: return <section className="claude-desktop-view mac-claude" aria-label="虚拟 Mac 中的 Claude Desktop">
281新增: <BrowserUploads requests={uploads} onStatus={onStatus} />
282新增: <DesktopToolbar desktop={state} platform="macOS" zoom={zoom} setZoom={setZoom} onConfirm={onConfirm}
283新增: onStop={() => action("stop")} refresh={() => refresh(n => n+1)} sidebarCollapsed={sidebarCollapsed} onExpand={onExpand}>
284新增: <MacOSLogin />
285新增: <button disabled={!state?.input || !image || transferring} onClick={() => void chooseFiles()}>添加附件</button>
286新增: <input ref={picker} type="file" multiple hidden aria-label="选择 Claude 附件" onChange={event => { const files = Array.from(event.target.files || []); event.target.value = ""; if (files.length) void receive({ files, kind: "paste" }, pickerTarget.current || undefined).catch(fileFailure); }} />
287新增: {(!state?.running || error) && <button onClick={() => action("launch")} disabled={!state?.installed}>{state?.running ? "重新连接应用" : "打开应用"}</button>}
288新增: {state?.installed && !state.screen && <button onClick={() => action("request-screen")}>授权窗口画面</button>}
289新增: {state?.installed && !state.input && <button onClick={() => action("request-input")}>授权键鼠</button>}
290新增: </DesktopToolbar>
291新增: {error && <p role="alert">{error}</p>}
292新增: {fileError && <p role="alert">{fileError}</p>}
293新增: {state && !state.installed && <p>此虚拟 Mac 尚未安装官方 Claude Desktop。</p>}
294新增: {state?.running && !state.screen && <p>{messages.screen_recording_permission}</p>}
295新增: {state?.running && state.screen && !state.input && <p>{messages.accessibility_permission}</p>}
296新增: <div ref={pane} className="mac-claude-frame" style={{ "--desktop-zoom": zoom }}>
297新增: {image && <img ref={surface} key={image.geometry || `${image.pid}-${image.window}`} alt="Claude Desktop 客机窗口" src={image.src} draggable={false}
298新增: onLoad={e => {
299新增: const img = e.currentTarget;
300新增: const width = image.width || img.naturalWidth;
301新增: const height = image.height || img.naturalHeight;
302新增: img.style.setProperty("--frame-width", width + "px");
303新增: img.style.setProperty("--frame-aspect", width / height);
304新增: frame.current = { window: image.window, pid: image.pid, geometry: image.geometry };
305新增: matchWindowBackground(img, pane.current, backgroundSample);
306新增: image.acknowledge?.();
307新增: }}
308新增: onError={() => { frameConnection.current?.close(); frameConnection.current = null; frame.current = null; setImage(null); setError("窗口画面无法解码,请重新连接。"); }}
309新增: />}
310新增: </div>
311新增: </section>;
312新增:}
新增ui/src/macos-first-setup.jsx+107 −0看文件
@@ -0,0 +1,107 @@
1新增:import React, { useEffect, useRef, useState } from "react";
2新增:import { api, native, nativeAvailable } from "./api";
3新增:import { useAccount } from "./account";
4新增:import { MacOSLogin } from "./macos-login";
5新增:import { DiagnosticSettings } from "./diagnostics.jsx";
6新增:
7新增:const steps = [["screen", "窗口录制"], ["input", "辅助功能"], ["projects", "文件系统扩展"]];
8新增:
9新增:export function MacOSFirstSetup() {
10新增: const { account, refresh } = useAccount();
11新增: const loginName = account?.macos_guest_user || "cage";
12新增: const [state, setState] = useState(null);
13新增: const [permissions, setPermissions] = useState({});
14新增: const [error, setError] = useState("");
15新增: const [completionFailed, setCompletionFailed] = useState(false);
16新增: const [busy, setBusy] = useState(false);
17新增: const [diagnostics, setDiagnostics] = useState(false);
18新增: const started = useRef(false);
19新增: const finished = useRef(false);
20新增: const requested = useRef("");
21新增: useEffect(() => {
22新增: let active = true, timer;
23新增: async function poll() {
24新增: try {
25新增: const next = await api("/status");
26新增: if (!active) return;
27新增: setState(next);
28新增: if (!next.vm_running && !next.job?.running && !next.job?.error && !started.current) {
29新增: started.current = true;
30新增: await api("/start", {guest_system:"macos"});
31新增: }
32新增: let measured = {};
33新增: if (next.ready) {
34新增: try { measured = await api("/macos/first-setup", {action:"permissions"}); }
35新增: catch { /* OS login and Setup Assistant run before the permission helper. */ }
36新增: }
37新增: if (active) setPermissions(measured);
38新增: const pending = steps.find(([id]) => !measured[id]);
39新增: if (active && measured.managed_credential && pending && requested.current !== pending[0]) {
40新增: requested.current = pending[0];
41新增: try { await api("/macos/first-setup",{action:pending[0]}); }
42新增: catch (e) { if (active) setError(e.message); }
43新增: }
44新增: if (active && steps.every(([id]) => measured[id]) && !finished.current) {
45新增: finished.current = true;
46新增: try {
47新增: const result = await api("/macos/first-setup", {action:"finish"});
48新增: if (result.error) throw new Error(result.error);
49新增: if (active) await refresh();
50新增: } catch (e) {
51新增: if (active) { setCompletionFailed(true); setError(e.message); }
52新增: }
53新增: }
54新增: } catch (e) { if (active) setError(e.message); }
55新增: if (active) timer = setTimeout(poll, 2000);
56新增: }
57新增: poll();
58新增: window.cageNativeAction = async command => {
59新增: if (command === "closeTab") document.dispatchEvent(new Event("cage-close-modal"));
60新增: if (command === "quit") await native("quitNow");
61新增: };
62新增: window.cageEditAction = () => false;
63新增: if (nativeAvailable()) native("workbenchReady").catch(() => {});
64新增: return () => { active = false; clearTimeout(timer); delete window.cageNativeAction; delete window.cageEditAction; };
65新增: }, []);
66新增: async function act(action) {
67新增: if (busy) return;
68新增: setBusy(true); setError("");
69新增: try {
70新增: if (action === "start") await api("/start", {guest_system:"macos"});
71新增: else {
72新增: const result = await api("/macos/first-setup", {action});
73新增: if (result.error) throw new Error(result.error);
74新增: if (action === "finish") { await refresh(); setCompletionFailed(false); }
75新增: }
76新增: } catch (e) {
77新增: if (action === "finish") setCompletionFailed(true);
78新增: setError(e.message);
79新增: }
80新增: finally { setBusy(false); }
81新增: }
82新增: const controls = <>{steps.map(([id, label]) => <button key={id} disabled={busy || !state?.ready}
83新增: onClick={() => act(id)}>{label}{permissions[id] && " ✓"}</button>)}
84新增: </>;
85新增: const progress = !state?.ready ? "正在等待虚拟 Mac 就绪;启动后再打开客机系统设置。" :
86新增: steps.every(([id]) => permissions[id]) ? completionFailed ? "授权已通过,请点击重试完成设置。" : "授权已通过,正在进入工作台…" :
87新增: `请确认:${steps.filter(([id]) => !permissions[id]).map(([, label]) => label).join("、")}。Cage 会自动检查并继续。`;
88新增: return <main className="welcome mac-first-setup"><section className="welcome-content">
89新增: <h1>正在准备虚拟 Mac</h1>
90新增: <p>Cage 会自动登录、配置并检查环境。首次使用只需确认下面的系统权限;这些操作都在虚拟 Mac 内完成。</p>
91新增: <ol>
92新增: <li>在 Cage 打开的「窗口录制」「辅助功能」设置里允许 <strong>Cage Guest Window</strong>。如果提示「退出并重新打开」,按提示操作。需要重新定位时,点击同名按钮。</li>
93新增: <li>点击「文件系统扩展」,在客机设置中同时打开 <strong>macFUSE</strong> 和 <strong>macFUSE (local)</strong>。Cage 会自动验证并进入工作台。</li>
94新增: </ol>
95新增: <p>授权时若要求管理员,用户名填 <strong>cagesetup</strong>,点选系统密码框后点击「填写授权密码」,再确认授权。辅助功能尚未开启时,可用「查看授权密码」。此管理员在完成后自动停用。</p>
96新增: {!state?.vm_running && <button className="primary" disabled={busy || !state || state.job?.running} onClick={() => act("start")}>启动虚拟 Mac</button>}
97新增: {state?.vm_running && <MacOSLogin initialSetup autoOpen={Boolean(permissions.managed_credential)} managedCredential={permissions.managed_credential} disabled={!state.ready} setupActions={controls}
98新增: setupHint={`Cage 自动登录 ${loginName}。管理员授权用 cagesetup;打开两个 macFUSE 开关后会自动继续。`}
99新增: setupStatus={error || progress} setupError={Boolean(error)} />}
100新增: <div className="welcome-shortcuts">{controls}</div>
101新增: <p role="status">{progress}</p>
102新增: {(completionFailed || error) && <button className="primary" disabled={busy || !steps.every(([id]) => permissions[id])} onClick={() => act("finish")}>重试完成设置</button>}
103新增: {(error || (!state?.ready && state?.job?.error)) && <p role="alert">{error || state.job.error}</p>}
104新增: <button className="text-button" onClick={() => setDiagnostics(!diagnostics)}>日志与诊断</button>
105新增: {diagnostics && <DiagnosticSettings />}
106新增: </section></main>;
107新增:}
新增ui/src/macos-frame-connection.mjs+62 −0看文件
@@ -0,0 +1,62 @@
1新增:import { runtimeSocketURL } from "./client-context.mjs";
2新增:
3新增:export function createMacFrameConnection(onFrame, onError) {
4新增: const socket = new WebSocket(runtimeSocketURL("/macos/claude/frames"));
5新增: socket.binaryType = "arraybuffer";
6新增: const urls = new Set();
7新增: let configuration, size = "", revision = 0, latestURL = "", closed = false;
8新增: const close = () => {
9新增: closed = true;
10新增: socket.close();
11新增: for (const url of urls) URL.revokeObjectURL(url);
12新增: urls.clear();
13新增: };
14新增: const fail = (reason = "window_unavailable") => {
15新增: if (closed) return;
16新增: close();
17新增: onError(reason);
18新增: };
19新增: socket.addEventListener("open", () => {
20新增: if (configuration) socket.send(JSON.stringify(configuration));
21新增: });
22新增: socket.addEventListener("error", () => fail());
23新增: socket.addEventListener("close", () => fail());
24新增: socket.addEventListener("message", event => {
25新增: if (closed) return;
26新增: try {
27新增: const data = event.data;
28新增: if (!(data instanceof ArrayBuffer) || data.byteLength < 4) throw new Error();
29新增: const length = new DataView(data).getUint32(0);
30新增: if (!length || length > 16384 || 4 + length > data.byteLength) throw new Error();
31新增: const header = JSON.parse(new TextDecoder().decode(new Uint8Array(data, 4, length)));
32新增: if (header.imageLength !== data.byteLength - 4 - length) throw new Error();
33新增: if (header.revision !== revision) return;
34新增: if (header.error) { fail(header.error); return; }
35新增: if (!["image/png", "image/jpeg"].includes(header.mime) || !header.imageLength || !header.sequence) throw new Error();
36新增: const src = URL.createObjectURL(new Blob([new Uint8Array(data, 4 + length)], { type: header.mime }));
37新增: urls.add(src);
38新增: latestURL = src;
39新增: let acknowledged = false;
40新增: onFrame({ ...header, src, acknowledge() {
41新增: if (closed || acknowledged || latestURL !== src) return;
42新增: acknowledged = true;
43新增: for (const previous of urls) {
44新增: if (previous !== src) { URL.revokeObjectURL(previous); urls.delete(previous); }
45新增: }
46新增: if (socket.readyState === WebSocket.OPEN) socket.send(JSON.stringify({ ack: header.sequence }));
47新增: } });
48新增: } catch { fail(); }
49新增: });
50新增: return {
51新增: resize(viewport) {
52新增: if (closed || !viewport) return;
53新增: const next = { ...viewport, scale: Math.max(1, Math.min(2, window.devicePixelRatio || 1)) };
54新增: const key = JSON.stringify(next);
55新增: if (key === size) return;
56新增: size = key;
57新增: configuration = { ...next, revision: ++revision };
58新增: if (socket.readyState === WebSocket.OPEN) socket.send(JSON.stringify(configuration));
59新增: },
60新增: close,
61新增: };
62新增:}
新增ui/src/macos-login.css+138 −0看文件
@@ -0,0 +1,138 @@
1新增:.mac-login-fullscreen {
2新增: position: fixed;
3新增: inset: 0;
4新增: z-index: 10000;
5新增: isolation: isolate;
6新增: background: #131519;
7新增: color: white;
8新增:}
9新增:.mac-login-panel { position: absolute; inset: 0; }
10新增:.mac-login-fullscreen[data-mode="login"] {
11新增: display: grid;
12新增: place-items: center;
13新增: padding: 16px;
14新增: background: #0008;
15新增:}
16新增:[data-mode="login"] .mac-login-panel {
17新增: position: relative;
18新增: inset: auto;
19新增: width: min(680px, 100%);
20新增: height: min(560px, calc(100dvh - 32px));
21新增: overflow: hidden;
22新增: border: 1px solid #ffffff32;
23新增: border-radius: 16px;
24新增: background: #17191e;
25新增: box-shadow: 0 24px 80px #0006;
26新增: display: flex;
27新增: flex-direction: column;
28新增:}
29新增:.mac-login-heading { padding: 20px 20px 12px; }
30新增:.mac-login-heading h2 { margin: 0; color: #fff; font-size: 18px; line-height: 1.4; }
31新增:.mac-login-heading p { margin: 6px 0 0; color: #ffffffb3; font-size: 13px; line-height: 1.5; }
32新增:.mac-login-stage {
33新增: position: absolute;
34新增: inset: 0;
35新增: overflow: auto;
36新增: overscroll-behavior: contain;
37新增: outline: none;
38新增: touch-action: none;
39新增:}
40新增:.mac-login-canvas {
41新增: display: grid;
42新增: place-items: center;
43新增: user-select: none;
44新增: -webkit-user-select: none;
45新增:}
46新增:.mac-login-canvas img {
47新增: display: block;
48新增: max-width: none;
49新增: max-height: none;
50新增: -webkit-user-drag: none;
51新增:}
52新增:.mac-login-stage[data-zoom="account"] .mac-login-canvas { cursor: grab; }
53新增:.mac-login-stage[data-zoom="account"]:active .mac-login-canvas { cursor: grabbing; }
54新增:.mac-login-tools {
55新增: position: absolute;
56新增: top: max(12px, env(safe-area-inset-top));
57新增: left: max(12px, env(safe-area-inset-left));
58新增: z-index: 1;
59新增: display: flex;
60新增: gap: 2px;
61新增: padding: 4px;
62新增: border: 1px solid #ffffff32;
63新增: border-radius: 12px;
64新增: background: #17191eee;
65新增: box-shadow: 0 2px 10px #0003;
66新增:}
67新增:.mac-login-tools button {
68新增: display: inline-flex;
69新增: align-items: center;
70新增: justify-content: center;
71新增: gap: 6px;
72新增: min-height: 32px;
73新增: margin: 0;
74新增: padding: 4px 10px;
75新增: color: #fff;
76新增: font: inherit;
77新增: font-size: 13px;
78新增: line-height: 1.2;
79新增: white-space: nowrap;
80新增: background: transparent;
81新增: border: 0;
82新增: border-radius: 8px;
83新增:}
84新增:.mac-login-tools button:hover,
85新增:.mac-login-tools button[aria-pressed="true"] { background: #ffffff24; }
86新增:.mac-login-tools button:focus-visible { outline: 2px solid #fff; outline-offset: -2px; }
87新增:.mac-login-status {
88新增: position: absolute;
89新增: top: 55px;
90新增: left: 12px;
91新增: max-width: calc(100% - 24px);
92新增: color: #fff;
93新增: background: #17191eee;
94新增: border-radius: 8px;
95新增: padding: 8px 12px;
96新增: font-size: 13px;
97新增:}
98新增:/* WebKit's Edit > Paste needs an editable first responder. Input is forwarded
99新增: to the guest one key at a time; the field never holds the guest password. */
100新增:.mac-login-keyboard {
101新增: position: absolute;
102新增: left: 0;
103新增: top: 0;
104新增: width: 1px;
105新增: height: 1px;
106新增: padding: 0;
107新增: margin: 0;
108新增: border: 0;
109新增: opacity: 0;
110新增: pointer-events: none;
111新增:}
112新增:
113新增:.mac-login-tools { max-width: calc(100% - 24px); flex-wrap: wrap; }
114新增:[data-mode="login"] .mac-login-tools {
115新增: position: relative;
116新增: top: auto;
117新增: left: auto;
118新增: align-self: flex-start;
119新增: flex-shrink: 0;
120新增: margin: 0 12px 12px;
121新增: box-shadow: none;
122新增:}
123新增:[data-mode="login"] .mac-login-stage {
124新增: position: relative;
125新增: flex: 1;
126新增: min-height: 0;
127新增: overflow: hidden;
128新增:}
129新增:[data-mode="login"] .mac-login-status { top: auto; bottom: 40px; }
130新增:.mac-login-help { margin: 0; padding: 10px 16px; color: #ffffffb3; font-size: 12px; line-height: 1.5; text-align: center; }
131新增:.mac-login-password { display: inline-flex; align-items: center; padding: 4px 8px; font-family: monospace; overflow-wrap: anywhere; }
132新增:.mac-setup-hint { position: absolute; bottom: 12px; left: 12px; z-index: 1; max-width: calc(100% - 24px); margin: 0; padding: 8px 12px; border-radius: 8px; color: #fff; background: #17191eee; font-size: 13px; pointer-events: none; }
133新增:.mac-first-setup { align-items: safe center; }
134新增:.mac-first-setup .welcome-content { width: min(100%, 700px); text-align: left; }
135新增:.mac-first-setup ol { padding-left: 24px; line-height: 1.6; }
136新增:.mac-first-setup li + li { margin-top: 10px; }
137新增:.mac-setup-hint p { margin: 0; }
138新增:.mac-setup-hint p + p { margin-top: 4px; }
新增ui/src/macos-login.jsx+370 −0看文件
@@ -0,0 +1,370 @@
1新增:import React, { useEffect, useLayoutEffect, useRef, useState } from "react";
2新增:import { createPortal } from "react-dom";
3新增:import { ArrowLeft, Maximize, ZoomIn } from "lucide-react";
4新增:import { api } from "./api";
5新增:import "./macos-login.css";
6新增:
7新增:// DOM physical codes and the matching ANSI key codes expected by the Apple VM keyboard.
8新增:const keys = {
9新增: KeyA: 0,
10新增: KeyS: 1,
11新增: KeyD: 2,
12新增: KeyF: 3,
13新增: KeyH: 4,
14新增: KeyG: 5,
15新增: KeyZ: 6,
16新增: KeyX: 7,
17新增: KeyC: 8,
18新增: KeyV: 9,
19新增: KeyB: 11,
20新增: KeyQ: 12,
21新增: KeyW: 13,
22新增: KeyE: 14,
23新增: KeyR: 15,
24新增: KeyY: 16,
25新增: KeyT: 17,
26新增: Digit1: 18,
27新增: Digit2: 19,
28新增: Digit3: 20,
29新增: Digit4: 21,
30新增: Digit6: 22,
31新增: Digit5: 23,
32新增: Equal: 24,
33新增: Digit9: 25,
34新增: Digit7: 26,
35新增: Minus: 27,
36新增: Digit8: 28,
37新增: Digit0: 29,
38新增: BracketRight: 30,
39新增: KeyO: 31,
40新增: KeyU: 32,
41新增: BracketLeft: 33,
42新增: KeyI: 34,
43新增: KeyP: 35,
44新增: Enter: 36,
45新增: KeyL: 37,
46新增: KeyJ: 38,
47新增: Quote: 39,
48新增: KeyK: 40,
49新增: Semicolon: 41,
50新增: Backslash: 42,
51新增: Comma: 43,
52新增: Slash: 44,
53新增: KeyN: 45,
54新增: KeyM: 46,
55新增: Period: 47,
56新增: Tab: 48,
57新增: Space: 49,
58新增: Backquote: 50,
59新增: Backspace: 51,
60新增: Escape: 53,
61新增:};
62新增:const charKeys = {};
63新增:for (const [name, code] of Object.entries(keys)) {
64新增: if (name.startsWith("Key")) {
65新增: charKeys[name.slice(-1).toLowerCase()] = [code, false];
66新增: charKeys[name.slice(-1)] = [code, true];
67新增: }
68新增: if (name.startsWith("Digit")) charKeys[name.slice(-1)] = [code, false];
69新增:}
70新增:for (const [code, pair] of Object.entries({ Digit1:"1!", Digit2:"2@", Digit3:"3#", Digit4:"4$", Digit5:"5%", Digit6:"6^", Digit7:"7&", Digit8:"8*", Digit9:"9(", Digit0:"0)", Minus:"-_", Equal:"=+", BracketLeft:"[{", BracketRight:"]}", Backslash:"\\|", Semicolon:";:", Quote:"'\"", Comma:",<", Period:".>", Slash:"/?", Backquote:"`~", Space:" " })) {
71新增: [...pair].forEach((ch, i) => { charKeys[ch] = [keys[code], i === 1]; });
72新增:}
73新增:const setupKeys = {ArrowLeft:123, ArrowRight:124, ArrowDown:125, ArrowUp:126, PageUp:116, PageDown:121};
74新增:// Apple receives logical view coordinates; Retina PNGs may have more pixels.
75新增:const guestWidth = 1024;
76新增:const guestHeight = 640;
77新增:
78新增:function closeSession(session, endpoint) {
79新增: if (session) api(endpoint, { action: "close", session }).catch(() => {});
80新增:}
81新增:
82新增:export function MacOSLogin({ disabled, initialSetup = false, setupActions, setupHint, setupStatus, setupError, autoOpen = false, managedCredential = false }) {
83新增: const endpoint = initialSetup ? "/macos/first-setup" : "/macos/login";
84新增: const [opened, setOpened] = useState(false);
85新增: const [session, setSession] = useState("");
86新增: const [frame, setFrame] = useState("");
87新增: const [message, setMessage] = useState("");
88新增: const [authorizationPassword, setAuthorizationPassword] = useState("");
89新增: const [zoomed, setZoomed] = useState(!initialSetup);
90新增: const [size, setSize] = useState({ width: 0, height: 0 });
91新增: const [aspect, setAspect] = useState(guestWidth / guestHeight);
92新增: const lease = useRef(null);
93新增: const chain = useRef(Promise.resolve());
94新增: const stage = useRef(null);
95新增: const keyboard = useRef(null);
96新增: const imageRef = useRef(null);
97新增: const back = useRef(null);
98新增: const opener = useRef(null);
99新增: const drag = useRef(null);
100新增: const dragged = useRef(false);
101新增: const autoOpened = useRef(false);
102新增:
103新增: const fitWidth = Math.min(size.width, size.height * aspect);
104新增: // Keep a 320 × 200 logical region around the account controls visible.
105新增: const imageWidth = !zoomed ? fitWidth : initialSetup ? fitWidth * 2 :
106新增: Math.min(size.width * guestWidth / 320, size.height * aspect * guestHeight / 200);
107新增: const imageHeight = imageWidth / aspect;
108新增: const hasFrame = Boolean(frame);
109新增:
110新增: function end(show = "") {
111新增: if (!lease.current) return;
112新增: const old = lease.current;
113新增: lease.current = null;
114新增: closeSession(old.session, endpoint);
115新增: setOpened(false);
116新增: setSession("");
117新增: setFrame("");
118新增: setAuthorizationPassword("");
119新增: setMessage(show);
120新增: }
121新增:
122新增: async function open() {
123新增: if (lease.current) return;
124新增: const next = { session: "" };
125新增: lease.current = next;
126新增: chain.current = Promise.resolve();
127新增: setMessage("");
128新增: setZoomed(!initialSetup);
129新增: setOpened(true);
130新增: try {
131新增: const r = await api(endpoint, { action: "open" });
132新增: if (lease.current !== next) {
133新增: closeSession(r.session, endpoint);
134新增: return;
135新增: }
136新增: if (!r.session) throw new Error(r.error || "暂时无法打开客机登录界面");
137新增: next.session = r.session;
138新增: setSession(r.session);
139新增: } catch (e) {
140新增: if (lease.current === next) end(e.message);
141新增: }
142新增: }
143新增:
144新增: useEffect(() => {
145新增: if (autoOpen && !disabled && !autoOpened.current) {
146新增: autoOpened.current = true;
147新增: open();
148新增: }
149新增: }, [autoOpen, disabled]);
150新增:
151新增: useEffect(() => {
152新增: if (!authorizationPassword) return;
153新增: const timer = setTimeout(() => setAuthorizationPassword(""),30000);
154新增: return () => clearTimeout(timer);
155新增: }, [authorizationPassword]);
156新增:
157新增: useEffect(() => () => {
158新增: if (lease.current) {
159新增: closeSession(lease.current.session, endpoint);
160新增: lease.current = null;
161新增: }
162新增: }, []);
163新增:
164新增: useLayoutEffect(() => {
165新增: if (!opened) return;
166新增: const control = stage.current;
167新增: const app = document.getElementById("root");
168新增: const wasInert = app?.inert;
169新增: const overflow = document.body.style.overflow;
170新增: if (app) app.inert = true;
171新增: document.body.style.overflow = "hidden";
172新增: const trigger = opener.current;
173新增: keyboard.current?.focus({ preventScroll: true });
174新增: const dismiss = () => end();
175新增: document.addEventListener("cage-close-modal", dismiss);
176新增: function measure() {
177新增: const { width, height } = control.getBoundingClientRect();
178新增: setSize((old) => old.width === width && old.height === height ? old : { width, height });
179新增: }
180新增: measure();
181新增: const observer = new ResizeObserver(measure);
182新增: observer.observe(control);
183新增: return () => {
184新增: observer.disconnect();
185新增: document.removeEventListener("cage-close-modal", dismiss);
186新增: document.body.style.overflow = overflow;
187新增: if (app) app.inert = wasInert;
188新增: if (trigger?.isConnected) trigger.focus({ preventScroll: true });
189新增: };
190新增: }, [opened]);
191新增:
192新增: // The account choices and password field sit near the bottom of loginwindow.
193新增: useLayoutEffect(() => {
194新增: if (!opened || !stage.current) return;
195新增: stage.current.scrollLeft = zoomed ? Math.max(0, (imageWidth - size.width) / 2) : 0;
196新增: stage.current.scrollTop = zoomed ? Math.max(0, imageHeight * 0.85 - size.height * 0.5) : 0;
197新增: }, [opened, hasFrame, zoomed, imageWidth, imageHeight, size.width, size.height]);
198新增:
199新增: useEffect(() => {
200新增: if (!session) return;
201新增: let timer;
202新增: let alive = true;
203新增: const poll = async () => {
204新增: try {
205新增: const r = await api(endpoint, { action: "frame", session });
206新增: if (!alive || lease.current?.session !== session) return;
207新增: if (r.closed) return end();
208新增: if (r.image) setFrame(`data:${r.mime === "image/jpeg" ? "image/jpeg" : "image/png"};base64,${r.image}`);
209新增: if (r.error) setMessage(r.error);
210新增: timer = setTimeout(poll, 550);
211新增: } catch (e) {
212新增: if (alive && lease.current?.session === session) end(e.message);
213新增: }
214新增: };
215新增: poll();
216新增: return () => { alive = false; clearTimeout(timer); };
217新增: }, [session]);
218新增:
219新增: function enqueue(action, data) {
220新增: const owner = lease.current;
221新增: if (!owner?.session) return;
222新增: chain.current = chain.current.then(async () => {
223新增: if (lease.current !== owner) return;
224新增: const r = await api(endpoint, { action, session: owner.session, ...data });
225新增: if (lease.current !== owner) return;
226新增: if (r.closed) end();
227新增: else if (r.error) setMessage(r.error);
228新增: }).catch((e) => { if (lease.current === owner) end(e.message); });
229新增: }
230新增:
231新增: function sendClick(e) {
232新增: if (dragged.current || e.button !== 0) return;
233新增: const rect = imageRef.current?.getBoundingClientRect();
234新增: if (!rect || !rect.width || !rect.height || e.clientX < rect.left || e.clientX >= rect.right ||
235新增: e.clientY < rect.top || e.clientY >= rect.bottom) return;
236新增: keyboard.current?.focus({ preventScroll: true });
237新增: enqueue("click", {
238新增: x: Math.floor((e.clientX - rect.left) * guestWidth / rect.width),
239新增: y: Math.floor((e.clientY - rect.top) * guestHeight / rect.height),
240新增: });
241新增: }
242新增:
243新增: function guestKey(e) {
244新增: const code = keys[e.code] ?? (initialSetup ? setupKeys[e.code] : undefined);
245新增: if (e.metaKey || e.ctrlKey || e.altKey || code === undefined) return;
246新增: e.preventDefault();
247新增: enqueue("key", { code, shift: e.shiftKey });
248新增: }
249新增:
250新增: useEffect(() => {
251新增: const element = stage.current;
252新增: if (!opened || !initialSetup || !element) return;
253新增: const scroll = (event) => {
254新增: const rect = imageRef.current?.getBoundingClientRect();
255新增: if (!rect?.width || !rect.height || event.clientX < rect.left || event.clientX >= rect.right ||
256新增: event.clientY < rect.top || event.clientY >= rect.bottom) return;
257新增: event.preventDefault();
258新增: const unit = event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? rect.height : 1;
259新增: const bounded = (delta, scale) => Math.max(-512, Math.min(512, Math.round(delta * unit * scale)));
260新增: enqueue("scroll", {
261新增: x: Math.floor((event.clientX - rect.left) * guestWidth / rect.width),
262新增: y: Math.floor((event.clientY - rect.top) * guestHeight / rect.height),
263新增: delta_x: bounded(event.deltaX, guestWidth / rect.width),
264新增: delta_y: bounded(event.deltaY, guestHeight / rect.height),
265新增: });
266新增: };
267新增: element.addEventListener("wheel", scroll, { passive: false });
268新增: return () => element.removeEventListener("wheel", scroll);
269新增: }, [opened, initialSetup, session]);
270新增:
271新增: function changeZoom(zoom) {
272新增: setZoomed(zoom);
273新增: keyboard.current?.focus({ preventScroll: true });
274新增: }
275新增:
276新增: return <>
277新增: <button ref={opener} disabled={disabled || opened} onClick={open}>{initialSetup ? "打开客机系统设置" : "登录客机账户"}</button>
278新增: {!opened && message && <span role="status">{message}</span>}
279新增: {opened && createPortal(
280新增: <div className="mac-login-fullscreen" data-mode={initialSetup ? "setup" : "login"} role="dialog" aria-modal="true" aria-label={initialSetup ? "首次设置虚拟 Mac" : "登录虚拟 Mac"}
281新增: onKeyDownCapture={(e) => {
282新增: if (e.key === "F6") {
283新增: e.preventDefault();
284新增: (document.activeElement === keyboard.current ? back.current : keyboard.current)?.focus({ preventScroll: true });
285新增: } else if (e.key === "Tab" && e.shiftKey && e.target === back.current) {
286新增: e.preventDefault();
287新增: keyboard.current?.focus({ preventScroll: true });
288新增: } else if (e.key === "Escape" && (e.shiftKey || e.target !== keyboard.current)) {
289新增: e.preventDefault();
290新增: end();
291新增: }
292新增: }}>
293新增: <div className="mac-login-panel">
294新增: {!initialSetup && <header className="mac-login-heading">
295新增: <h2>登录 macOS 客机</h2>
296新增: <p>输入客机账户密码,按回车登录。</p>
297新增: </header>}
298新增: <div className="mac-login-tools" role="toolbar" aria-label="画面工具">
299新增: <button ref={back} onClick={() => end()}><ArrowLeft size={16} aria-hidden="true" />{initialSetup ? "返回设置指引" : "返回工作台"}</button>
300新增: <button aria-pressed={!zoomed} onClick={() => changeZoom(false)}><Maximize size={16} aria-hidden="true" />{initialSetup ? "适配" : "完整画面"}</button>
301新增: <button aria-pressed={zoomed} onClick={() => changeZoom(true)}><ZoomIn size={16} aria-hidden="true" />{initialSetup ? "放大" : "登录区域"}</button>
302新增: {initialSetup && setupActions}
303新增: {initialSetup && managedCredential && <button disabled={!session} onClick={() => enqueue("fill-password",{})}>填写授权密码</button>}
304新增: {(!initialSetup || managedCredential) && <button onClick={async () => {
305新增: try { const result = await api(endpoint,{action:"show-password"}); setAuthorizationPassword(result.password); }
306新增: catch (e) { setMessage(e.message); }
307新增: }}>{initialSetup ? "查看授权密码" : "查看客机密码"}</button>}
308新增: {authorizationPassword && <span className="mac-login-password">{authorizationPassword}<button onClick={() => setAuthorizationPassword("")}>隐藏</button></span>}
309新增: </div>
310新增: {initialSetup && setupHint && <div className="mac-setup-hint">
311新增: <p>{setupHint}</p>
312新增: <p role={setupError ? "alert" : "status"}>{setupStatus} 查看完整步骤或进入工作台时,点击「返回设置指引」。</p>
313新增: </div>}
314新增: <input ref={keyboard} className="mac-login-keyboard" type="text" autoComplete="off" autoCapitalize="none"
315新增: autoCorrect="off" spellCheck={false}
316新增: aria-label="客机登录键盘。按 F6 切换工具栏,按 Shift 加 Escape 返回工作台。"
317新增: onKeyDown={guestKey}
318新增: onBeforeInput={(e) => e.preventDefault()}
319新增: onInput={(e) => { e.currentTarget.value = ""; }}
320新增: onPaste={(e) => {
321新增: e.preventDefault();
322新增: const text = e.clipboardData.getData("text/plain");
323新增: if (text.length > 256 || [...text].some((c) => !charKeys[c])) {
324新增: setMessage("请用键盘输入该密码。");
325新增: return;
326新增: }
327新增: for (const c of text) {
328新增: const [code, shift] = charKeys[c];
329新增: enqueue("key", { code, shift });
330新增: }
331新增: }} />
332新增: <div ref={stage} className="mac-login-stage" data-zoom={zoomed ? "account" : "fit"}
333新增: onPointerDown={(e) => {
334新增: keyboard.current?.focus({ preventScroll: true });
335新增: dragged.current = false;
336新增: if (!zoomed || e.button !== 0 || !e.isPrimary) return;
337新增: const el = e.currentTarget;
338新增: drag.current = { id: e.pointerId, x: e.clientX, y: e.clientY, left: el.scrollLeft, top: el.scrollTop };
339新增: }}
340新增: onPointerMove={(e) => {
341新增: const start = drag.current;
342新增: if (!start || start.id !== e.pointerId || !(e.buttons & 1)) return;
343新增: const dx = e.clientX - start.x, dy = e.clientY - start.y;
344新增: if (!dragged.current && Math.hypot(dx, dy) < 5) return;
345新增: dragged.current = true;
346新增: const el = e.currentTarget;
347新增: if (!el.hasPointerCapture(e.pointerId)) el.setPointerCapture(e.pointerId);
348新增: el.scrollLeft = start.left - dx;
349新增: el.scrollTop = start.top - dy;
350新增: }}
351新增: onPointerUp={() => { drag.current = null; }}
352新增: onPointerCancel={() => { drag.current = null; dragged.current = true; }}>
353新增: {frame && <div className="mac-login-canvas" style={{
354新增: width: Math.max(size.width, imageWidth), height: Math.max(size.height, imageHeight),
355新增: }}>
356新增: <img ref={imageRef} alt={initialSetup ? "Apple 客机首次系统设置" : "Apple 客机登录屏幕"} draggable={false} src={frame}
357新增: style={{ width: imageWidth, height: imageHeight }}
358新增: onLoad={(e) => {
359新增: if (e.currentTarget.naturalHeight) setAspect(e.currentTarget.naturalWidth / e.currentTarget.naturalHeight);
360新增: }} onClick={sendClick} />
361新增: </div>}
362新增: </div>
363新增: {(message || !frame) && <p className="mac-login-status" role={message ? "alert" : "status"}>
364新增: {message || (initialSetup ? "正在读取客机首次设置画面…" : "正在确认客机登录画面…")}
365新增: </p>}
366新增: {!initialSetup && <p className="mac-login-help">拖动画面可查看其他账户或提示</p>}
367新增: </div>
368新增: </div>, document.body)}
369新增: </>;
370新增:}
新增ui/src/macos-project-approval.css+13 −0看文件
@@ -0,0 +1,13 @@
1新增:.macos-approval-frame {
2新增: display: block;
3新增: max-width: 100%;
4新增: max-height: 60vh;
5新增: width: auto;
6新增: height: auto;
7新增: margin: 0 auto;
8新增: cursor: pointer;
9新增:}
10新增:.macos-approval-path {
11新增: overflow-wrap: anywhere;
12新增: color: var(--muted);
13新增:}
新增ui/src/macos-project-approval.jsx+141 −0看文件
@@ -0,0 +1,141 @@
1新增:import React, { useEffect, useRef, useState } from "react";
2新增:import { api } from "./api";
3新增:import { Modal } from "./modal";
4新增:import "./macos-project-approval.css";
5新增:
6新增:const permissionMessages = {
7新增: project_screen_permission: "无法显示文件夹授权窗口。请在虚拟 Mac 的“系统设置 → 隐私与安全性 → 屏幕与系统音频录制”中允许 Cage Guest Window,并按系统提示重新打开助手。",
8新增: accessibility_permission: "无法点击文件夹授权窗口。请在虚拟 Mac 的“系统设置 → 隐私与安全性 → 辅助功能”中允许 Cage Guest Window,然后重试。",
9新增: requires_gui_login: "请先登录并解锁虚拟 Mac 的普通账户,然后重新打开项目。",
10新增:};
11新增:
12新增:export function MacOSProjectApproval({ pending, onCheck, onClose }) {
13新增: const [frame, setFrame] = useState(null),
14新增: [notice, setNotice] = useState("");
15新增: const [busy, setBusy] = useState(false);
16新增: const [actionError, setActionError] = useState("");
17新增: const active = useRef(false),
18新增: inFlight = useRef(null);
19新增: const call = (action, fields = {}) =>
20新增: api("/macos/project-approval", {
21新增: workspace: pending.workspace,
22新增: grant: pending.grant,
23新增: action,
24新增: ...fields,
25新增: });
26新增:
27新增: useEffect(() => {
28新增: let live = true,
29新增: timer;
30新增: async function poll() {
31新增: if (!active.current) {
32新增: try {
33新增: const request = call("frame");
34新增: inFlight.current = request;
35新增: const result = await request;
36新增: if (live && !active.current) {
37新增: const valid = Boolean(
38新增: !result.error &&
39新增: result.image &&
40新增: result.window &&
41新增: result.pid &&
42新增: result.nonce,
43新增: );
44新增: setFrame(valid ? result : null);
45新增: setNotice(
46新增: valid
47新增: ? ""
48新增: : permissionMessages[result.error] || "等待虚拟 Mac 的项目授权窗口。已允许此文件夹时,可以直接验证授权。",
49新增: );
50新增: }
51新增: } catch (e) {
52新增: if (live && !active.current) {
53新增: setFrame(null);
54新增: setNotice(e.message);
55新增: }
56新增: } finally {
57新增: inFlight.current = null;
58新增: }
59新增: }
60新增: if (live) timer = setTimeout(poll, 650);
61新增: }
62新增: setFrame(null);
63新增: setActionError("");
64新增: poll();
65新增: return () => {
66新增: live = false;
67新增: clearTimeout(timer);
68新增: };
69新增: }, [pending.workspace, pending.grant]);
70新增:
71新增: async function act(fn) {
72新增: if (active.current) return;
73新增: active.current = true;
74新增: setBusy(true);
75新增: setActionError("");
76新增: try {
77新增: await inFlight.current?.catch(() => {});
78新增: await fn();
79新增: } catch (e) {
80新增: setFrame(null);
81新增: setActionError(e.message);
82新增: } finally {
83新增: active.current = false;
84新增: setBusy(false);
85新增: }
86新增: }
87新增: const cancel = () =>
88新增: act(async () => {
89新增: await call("cancel");
90新增: onClose();
91新增: });
92新增: const click = (event) => {
93新增: if (!frame) return;
94新增: const rect = event.currentTarget.getBoundingClientRect();
95新增: const x = (event.clientX - rect.left) / rect.width,
96新增: y = (event.clientY - rect.top) / rect.height;
97新增: if (!(x >= 0 && x < 1 && y >= 0 && y < 1)) return;
98新增: void act(async () => {
99新增: const result = await call("click", {
100新增: window: frame.window,
101新增: pid: frame.pid,
102新增: nonce: frame.nonce,
103新增: x,
104新增: y,
105新增: });
106新增: setFrame(null);
107新增: if (result.error) throw new Error(permissionMessages[result.error] || "客机授权窗口已变化,请等待新画面。");
108新增: await onCheck();
109新增: });
110新增: };
111新增: return (
112新增: <Modal
113新增: title="允许客机访问所选项目"
114新增: onClose={busy ? undefined : cancel}
115新增: footer={
116新增: <>
117新增: <button disabled={busy} onClick={cancel}>
118新增: 取消
119新增: </button>
120新增: <button disabled={busy} onClick={() => act(onCheck)}>
121新增: 验证授权
122新增: </button>
123新增: </>
124新增: }
125新增: >
126新增: <p>在下方的 macOS 授权窗口中确认所选项目。</p>
127新增: <p className="macos-approval-path">{pending.workspace}</p>
128新增: {frame && (
129新增: <img
130新增: src={"data:image/png;base64," + frame.image}
131新增: alt="虚拟 Mac 的当前项目授权窗口"
132新增: onClick={click}
133新增: className="macos-approval-frame"
134新增: draggable={false}
135新增: />
136新增: )}
137新增: {notice && <p role="status">{notice}</p>}
138新增: {actionError && <p role="alert">{actionError}</p>}
139新增: </Modal>
140新增: );
141新增:}
新增ui/src/macos-window-connection.mjs+43 −0看文件
@@ -0,0 +1,43 @@
1新增:import { runtimeSocketURL } from "./client-context.mjs";
2新增:
3新增:export function createMacWindowConnection() {
4新增: const socket = new WebSocket(runtimeSocketURL("/macos/claude/connection"));
5新增: const pending = new Map();
6新增: let nextID = 0;
7新增: let closed = false;
8新增: let readyResolve, readyReject;
9新增: const ready = new Promise((resolve, reject) => { readyResolve = resolve; readyReject = reject; });
10新增: // A connection can close before its first request starts waiting.
11新增: ready.catch(() => {});
12新增: const fail = () => {
13新增: closed = true;
14新增: const error = new Error("虚拟 Mac 的窗口连接已关闭,请重新连接。");
15新增: readyReject(error);
16新增: for (const request of pending.values()) request.reject(error);
17新增: pending.clear();
18新增: };
19新增: socket.addEventListener("open", readyResolve);
20新增: socket.addEventListener("error", fail);
21新增: socket.addEventListener("close", fail);
22新增: socket.addEventListener("message", event => {
23新增: try {
24新增: const message = JSON.parse(event.data);
25新增: const request = pending.get(message.id);
26新增: if (!request) return;
27新增: pending.delete(message.id);
28新增: request.resolve(message.result);
29新增: } catch { fail(); socket.close(); }
30新增: });
31新增: return {
32新增: async request(action, fields = {}) {
33新增: await ready;
34新增: if (closed) throw new Error("虚拟 Mac 的窗口连接已关闭,请重新连接。");
35新增: const id = ++nextID;
36新增: return new Promise((resolve, reject) => {
37新增: pending.set(id, { resolve, reject });
38新增: socket.send(JSON.stringify({ id, request: { action, ...fields } }));
39新增: });
40新增: },
41新增: close() { fail(); socket.close(); },
42新增: };
43新增:}
新增ui/src/macos-window-input.mjs+141 −0看文件
@@ -0,0 +1,141 @@
1新增:const identity = frame => frame && `${frame.pid}:${frame.window}:${frame.geometry || ""}`;
2新增:const modifiers = keys => ({
3新增: shift: keys.has("ShiftLeft") || keys.has("ShiftRight"),
4新增: control: keys.has("ControlLeft") || keys.has("ControlRight"),
5新增: alt: keys.has("AltLeft") || keys.has("AltRight"),
6新增: command: keys.has("MetaLeft") || keys.has("MetaRight"),
7新增:});
8新增:
9新增:export function createMacWindowInput({ element, frame, active, request, onError, eventWindow = window }) {
10新增: let keyboard, disposed = false, queued, pending = 0, move, drag, lastClick;
11新增: const keys = new Set(), listeners = [];
12新增: const run = action => {
13新增: if (disposed) return Promise.reject(new Error("窗口输入连接已关闭"));
14新增: if (pending >= 128) return Promise.reject(new Error("窗口输入等待过多,请重新连接"));
15新增: pending++;
16新增: const result = (queued || Promise.resolve()).then(async () => {
17新增: if (disposed) throw new Error("窗口输入连接已关闭");
18新增: try { return await action(); }
19新增: catch (error) {
20新增: keys.clear();
21新增: await request("input-reset").catch(() => {});
22新增: throw error;
23新增: }
24新增: });
25新增: queued = result;
26新增: const finish = () => {
27新增: pending--;
28新增: if (queued === result) queued = undefined;
29新增: };
30新增: result.then(finish, finish);
31新增: return result;
32新增: };
33新增: const valid = target => !disposed && active() && identity(target) === identity(frame());
34新增: const send = (action, fields, target = frame()) => run(() => {
35新增: if (!target || !valid(target)) throw new Error("输入窗口已变化,请重新操作");
36新增: return request(action, { ...target, ...fields });
37新增: });
38新增: const report = promise => { void promise.catch(error => { if (!disposed) onError(error.message); }); };
39新增: const on = (target, name, callback, options) => {
40新增: target.addEventListener(name, callback, options);
41新增: listeners.push(() => target.removeEventListener(name, callback, options));
42新增: };
43新增: const point = event => {
44新增: const box = element.getBoundingClientRect();
45新增: return {
46新增: x: Math.max(0, Math.min(1 - Number.EPSILON, (event.clientX - box.left) / box.width)),
47新增: y: Math.max(0, Math.min(1 - Number.EPSILON, (event.clientY - box.top) / box.height)),
48新增: };
49新增: };
50新增: const focus = () => keyboard?.focus({ preventScroll: true });
51新增: const key = (symbol, code, down, target) => {
52新增: if (!target || !valid(target)) throw new Error("输入窗口已变化,请重新操作");
53新增: if (down) keys.add(code); else keys.delete(code);
54新增: const character = symbol >= 0x01000000 ? symbol & 0x00ffffff : symbol;
55新增: const name = character >= 32 && character < 0xff00 ? String.fromCodePoint(character) : code;
56新增: return request("key", { ...target, code, key: name, down, ...modifiers(keys) });
57新增: };
58新增: on(element, "pointerdown", event => {
59新增: if (!active() || !frame() || ![0, 1, 2].includes(event.button)) return;
60新增: if (drag && drag.pointer !== event.pointerId) return;
61新增: event.preventDefault(); focus(); move = undefined;
62新增: const now = event.timeStamp;
63新增: const nearby = lastClick && lastClick.button === event.button && now - lastClick.time < 500 &&
64新增: Math.abs(lastClick.x - event.clientX) < 4 && Math.abs(lastClick.y - event.clientY) < 4;
65新增: const clicks = Math.min(3, event.detail || (nearby ? lastClick.count + 1 : 1));
66新增: lastClick = { button: event.button, x: event.clientX, y: event.clientY, count: clicks, time: now };
67新增: drag ||= { pointer: event.pointerId, target: { ...frame() }, buttons: 0 };
68新增: drag.buttons = event.buttons;
69新增: element.setPointerCapture(event.pointerId);
70新增: report(send("pointer", { phase: "down", button: event.button, buttons: event.buttons, clicks, ...point(event),
71新增: shift: event.shiftKey, control: event.ctrlKey, alt: event.altKey, command: event.metaKey }, drag.target));
72新增: });
73新增: on(element, "pointermove", event => {
74新增: if (!active() || !frame() || (drag && drag.pointer !== event.pointerId)) return;
75新增: const target = drag?.target || { ...frame() };
76新增: const fields = { phase: "move", buttons: event.buttons, ...point(event),
77新增: shift: event.shiftKey, control: event.ctrlKey, alt: event.altKey, command: event.metaKey };
78新增: if (move) { move.fields = fields; return; }
79新增: const entry = { fields };
80新增: move = entry;
81新增: report(run(() => {
82新增: if (move === entry) move = undefined;
83新增: if (!valid(target)) throw new Error("输入窗口已变化,请重新操作");
84新增: return request("pointer", { ...target, ...entry.fields });
85新增: }));
86新增: });
87新增: on(element, "pointerup", event => {
88新增: if (!drag || drag.pointer !== event.pointerId) return;
89新增: event.preventDefault(); move = undefined;
90新增: const target = drag.target;
91新增: drag.buttons = event.buttons;
92新增: if (!event.buttons) {
93新增: drag = undefined;
94新增: if (element.hasPointerCapture(event.pointerId)) element.releasePointerCapture(event.pointerId);
95新增: }
96新增: report(send("pointer", { phase: "up", button: event.button, buttons: event.buttons, clicks: lastClick?.count || 1,
97新增: ...point(event), shift: event.shiftKey, control: event.ctrlKey, alt: event.altKey, command: event.metaKey }, target));
98新增: });
99新增: const reset = () => {
100新增: if (disposed) return;
101新增: move = undefined; keys.clear();
102新增: const hadInput = Boolean(drag || keyboard);
103新增: const pointer = drag?.pointer;
104新增: drag = undefined;
105新增: if (pointer !== undefined && element.hasPointerCapture(pointer)) element.releasePointerCapture(pointer);
106新增: if (hadInput) report(run(() => { keys.clear(); return request("input-reset"); }));
107新增: };
108新增: on(element, "pointercancel", reset);
109新增: on(element, "lostpointercapture", () => { if (drag) reset(); });
110新增: on(element, "contextmenu", event => event.preventDefault());
111新增: on(element, "wheel", event => {
112新增: if (!active()) return;
113新增: event.preventDefault();
114新增: report(send("scroll", { ...point(event), delta: Math.max(-1200, Math.min(1200, event.deltaY)),
115新增: deltaX: Math.max(-1200, Math.min(1200, event.deltaX)) }));
116新增: }, { passive: false });
117新增: on(eventWindow, "blur", reset);
118新增:
119新增: return {
120新增: events: new EventTarget(), run, send, valid,
121新增: target: () => frame() && { ...frame() },
122新增: setKeyboardTarget(target) { keyboard = target; keyboard?.classList.add("mac-claude-typing"); },
123新增: focus,
124新增: pasteText: text => send("text", { text }),
125新增: sendKey(symbol, code, down) {
126新增: const target = frame() && { ...frame() };
127新增: report(run(() => key(symbol, code, down, target)));
128新增: },
129新增: runKeyAction(action) {
130新增: const target = frame() && { ...frame() };
131新增: return run(() => action((...fields) => key(...fields, target)));
132新增: },
133新增: dispose() {
134新增: if (disposed) return;
135新增: disposed = true; move = undefined; keys.clear(); drag = undefined;
136新增: void request("input-reset").catch(() => {});
137新增: listeners.forEach(remove => remove());
138新增: keyboard = undefined;
139新增: },
140新增: };
141新增:}
新增ui/src/macos-window-input.test.mjs+153 −0看文件
@@ -0,0 +1,153 @@
1新增:import test from "node:test";
2新增:import assert from "node:assert/strict";
3新增:import { createMacWindowInput } from "./macos-window-input.mjs";
4新增:
5新增:function fixture() {
6新增: let current = { pid: 23, window: 70, geometry: "geometry-1" }, visible = true;
7新增: const calls = [], errors = [], captured = new Set(), eventWindow = new EventTarget();
8新增: const element = Object.assign(new EventTarget(), {
9新增: getBoundingClientRect: () => ({ left: 20, top: 30, width: 400, height: 300 }),
10新增: setPointerCapture: id => captured.add(id),
11新增: hasPointerCapture: id => captured.has(id),
12新增: releasePointerCapture(id) {
13新增: captured.delete(id);
14新增: element.dispatchEvent(new Event("lostpointercapture"));
15新增: },
16新增: });
17新增: const input = createMacWindowInput({
18新增: element, frame: () => current, active: () => visible,
19新增: request: async (action, fields) => { calls.push({ action, ...fields }); return { ok: true }; },
20新增: onError: error => errors.push(error), eventWindow,
21新增: });
22新增: input.setKeyboardTarget({ focus() {}, classList: { add() {} } });
23新增: const pointer = (type, fields = {}) => {
24新增: const event = new Event(type, { cancelable: true });
25新增: Object.assign(event, {
26新增: pointerId: 1, button: 0, buttons: type === "pointerup" ? 0 : 1,
27新增: clientX: 120, clientY: 105, detail: 1,
28新增: shiftKey: false, ctrlKey: false, altKey: false, metaKey: false, ...fields,
29新增: });
30新增: element.dispatchEvent(event);
31新增: return event;
32新增: };
33新增: return { input, calls, errors, captured, eventWindow, element, pointer,
34新增: changeTarget: () => { current = { ...current, geometry: "geometry-2" }; },
35新增: hide: () => { visible = false; },
36新增: };
37新增:}
38新增:
39新增:test("native window drag preserves down/move/up and coalesces only adjacent moves", async () => {
40新增: const f = fixture();
41新增: let release;
42新增: const gate = f.input.run(() => new Promise(resolve => { release = resolve; }));
43新增: await Promise.resolve();
44新增: try {
45新增: assert.equal(f.pointer("pointerdown").defaultPrevented, true);
46新增: f.pointer("pointermove", { clientX: 180 });
47新增: f.pointer("pointermove", { clientX: 300 });
48新增: f.pointer("pointerdown", { pointerId: 2 });
49新增: f.pointer("pointerup", { clientX: 900, clientY: -40 });
50新增: release();
51新增: await gate;
52新增: await f.input.run(() => {});
53新增: assert.deepEqual(f.calls.map(call => call.phase), ["down", "move", "up"]);
54新增: assert.deepEqual(f.calls.map(call => call.x), [0.25, 0.7, 1 - Number.EPSILON]);
55新增: assert.equal(f.calls[2].y, 0);
56新增: assert(f.calls.every(call => call.pid === 23 && call.window === 70 && call.geometry === "geometry-1"));
57新增: assert.equal(f.captured.size, 0);
58新增: assert.deepEqual(f.errors, []);
59新增: } finally { f.input.dispose(); }
60新增:});
61新增:
62新增:test("native window forwards right button, double click and horizontal scroll", async () => {
63新增: const f = fixture();
64新增: try {
65新增: f.pointer("pointerdown", { button: 2, buttons: 2 });
66新增: f.pointer("pointerup", { button: 2 });
67新增: f.pointer("pointerdown", { detail: 2 });
68新增: f.pointer("pointerup", { detail: 2 });
69新增: f.pointer("wheel", { deltaX: 54, deltaY: -2000 });
70新增: await f.input.run(() => {});
71新增: assert.deepEqual(f.calls.slice(0, 4).map(call => [call.phase, call.button, call.clicks]), [
72新增: ["down", 2, 1], ["up", 2, 1], ["down", 0, 2], ["up", 0, 2],
73新增: ]);
74新增: assert.equal(f.calls[4].deltaX, 54);
75新增: assert.equal(f.calls[4].delta, -1200);
76新增: assert.equal(f.pointer("contextmenu").defaultPrevented, true);
77新增: } finally { f.input.dispose(); }
78新增:});
79新增:
80新增:test("cancelled pointer capture resets held input before new keys", async () => {
81新增: const f = fixture();
82新增: try {
83新增: f.input.sendKey(0xffeb, "MetaLeft", true);
84新增: f.pointer("pointerdown");
85新增: f.pointer("pointercancel");
86新增: f.input.sendKey(97, "KeyA", true);
87新增: await f.input.run(() => {});
88新增: assert.equal(f.captured.size, 0);
89新增: assert.deepEqual(f.calls.map(call => call.action), ["key", "pointer", "input-reset", "key"]);
90新增: assert.equal(f.calls.at(-1).command, false);
91新增: } finally { f.input.dispose(); }
92新增:});
93新增:
94新增:test("queued native paste sends its chord before a following Enter", async () => {
95新增: const f = fixture();
96新增: let release;
97新增: const clipboard = new Promise(resolve => { release = resolve; });
98新增: try {
99新增: const paste = f.input.runKeyAction(async sendKey => {
100新增: await clipboard;
101新增: for (const key of [[0xffeb, "MetaLeft", true], [118, "KeyV", true], [118, "KeyV", false], [0xffeb, "MetaLeft", false]])
102新增: await sendKey(...key);
103新增: });
104新增: f.input.sendKey(0xff0d, "Enter", true);
105新增: f.input.sendKey(0xff0d, "Enter", false);
106新增: await Promise.resolve();
107新增: assert.deepEqual(f.calls, []);
108新增: release();
109新增: await paste;
110新增: await f.input.run(() => {});
111新增: assert.deepEqual(f.calls.map(call => [call.code, call.down]), [
112新增: ["MetaLeft", true], ["KeyV", true], ["KeyV", false], ["MetaLeft", false], ["Enter", true], ["Enter", false],
113新增: ]);
114新增: } finally { f.input.dispose(); }
115新增:});
116新增:
117新增:test("a failed paste cancels already queued Enter and recovers for new input", async () => {
118新增: const f = fixture();
119新增: let fail;
120新增: const clipboard = new Promise((_, reject) => { fail = reject; });
121新增: try {
122新增: const paste = f.input.runKeyAction(async () => { await clipboard; });
123新增: f.input.sendKey(0xff0d, "Enter", true);
124新增: const drained = f.input.run(() => {});
125新增: fail(new Error("fixture clipboard failed"));
126新增: await assert.rejects(paste, /fixture clipboard failed/);
127新增: await assert.rejects(drained, /fixture clipboard failed/);
128新增: assert.deepEqual(f.calls.map(call => call.action), ["input-reset"]);
129新增: f.input.sendKey(97, "KeyA", true);
130新增: await f.input.run(() => {});
131新增: assert.equal(f.calls.at(-1).code, "KeyA");
132新增: } finally { f.input.dispose(); }
133新增:});
134新增:
135新增:test("a frame change rejects queued input and disposal releases only its connection", async () => {
136新增: const f = fixture();
137新增: let release;
138新增: const gate = f.input.run(() => new Promise(resolve => { release = resolve; }));
139新增: await Promise.resolve();
140新增: f.input.sendKey(97, "KeyA", true);
141新增: const drained = f.input.run(() => {});
142新增: f.changeTarget();
143新增: release();
144新增: await gate;
145新增: await assert.rejects(drained, /输入窗口已变化/);
146新增: assert.deepEqual(f.calls.map(call => call.action), ["input-reset"]);
147新增: f.input.dispose();
148新增: const count = f.calls.length;
149新增: f.pointer("pointerdown");
150新增: f.eventWindow.dispatchEvent(new Event("blur"));
151新增: await assert.rejects(f.input.run(() => {}), /连接已关闭/);
152新增: assert.equal(f.calls.length, count);
153新增:});
修改ui/src/main.jsx+354 −90看文件
@@ -16,21 +16,30 @@ import {
1616 X,
1717} from "lucide-react";
1818import { api, normalizeURL, native, nativeAvailable } from "./api";
19删除:import { clientKeyboard, clientStorageKey, isRemoteClient, runtimeURL } from "./client-context.mjs";
19新增:import { clientKeyboard, clientStorageKey, getClientContext, isRemoteClient, runtimeURL, runtimeSocketURL } from "./client-context.mjs";
20新增:import { shareClipboard } from "./shared-clipboard.mjs";
2021import { RemoteView, TerminalView, Modal } from "./views";
2122import { usePasswordVault } from "./password-vault";
2223import { SettingsPanel } from "./settings";
2324import { SetupProgress } from "./setup-progress";
25新增:import { GuestSystemPicker, validGuestChoice } from "./guest-system-picker";
2426import { AppearanceProvider } from "./appearance";
2527import { EnvironmentShield } from "./environment-shield";
28新增:import { TailscalePanel } from "./tailscale";
2629import { WorkspaceSidebar } from "./workspace-sidebar";
30新增:import { useCLISessions, sessionsChanged } from "./cli-sessions";
2731import { TerminalMenu } from "./terminal-menu";
32新增:import { MacOSFirstSetup } from "./macos-first-setup";
33新增:import { InitializationGate } from "./initialization";
34新增:import { MacOSLogin } from "./macos-login";
35新增:import { MacOSClaudeWindow } from "./macos-claude-window";
2836import { ClaudeDesktop } from "./claude-desktop";
2937import { useClaudeAccounts } from "./claude-accounts";
3038import { AccountProvider, AccountGate, useAccount } from "./account";
31删除:import { BrowserHeader, TerminalHeader, ExpandSidebar, ExpandPane } from "./pane-headers";
39新增:import { BrowserHeader, BrowserTabRail, TerminalHeader, ExpandSidebar, ExpandPane } from "./pane-headers";
3240import { BrowserDownloads, useDownloadNotifications, useDesktopFiles } from "./browser-downloads";
3341import { BrowserUploads } from "./browser-uploads";
42新增:import { BrowserSettingsPage } from "./browser-settings";
3443import { AudioControls, useAudioOutput } from "./audio";
3544import { ProjectDialog } from "./project-dialog";
3645import {
@@ -42,6 +51,7 @@ import {
4251 tabName,
4352} from "./workspace-state.mjs";
4453import { SafetyPanel } from "./safety";
54新增:import { SafetyChecklistContext, SafetyMessage } from "./safety-message";
4555import { networkState, isGuestLocalURL } from "./safety-state.mjs";
4656import { needsProxySetup } from "./onboarding-state.mjs";
4757import { HostGitPreparation } from "./host-git";
@@ -53,6 +63,8 @@ import { stopAndExit } from "./quit";
5363
5464function App() {
5565 const { account } = useAccount();
66新增: const macGuest = account?.guest_system === "macos";
67新增: const nativeGuestLabel = {macos: "macOS", "windows-11": "Windows"}[account?.guest_system];
5668 const [, refreshClientPreferences] = useState(0);
5769 useEffect(() => {
5870 const refresh = () => refreshClientPreferences((value) => value + 1);
@@ -60,8 +72,10 @@ function App() {
6072 return () => window.removeEventListener("cage-client-preferences", refresh);
6173 }, []);
6274 const claudeProfiles = useClaudeAccounts();
75新增: const [tailscaleOpen, setTailscaleOpen] = useState(false);
6376 const [desktopOpen, setDesktopOpen] = useState(false);
6477 const [terminalChoice, setTerminalChoice] = useState(null);
78新增: const [openingSession, setOpeningSession] = useState("");
6579 const terminalTrigger = useRef(null);
6680 const appUpdates = useAppUpdates();
6781 const [recoveringEditor, setRecoveringEditor] = useState(false);
@@ -74,21 +88,28 @@ function App() {
7488 [tabs, setTabs] = useState([]),
7589 [layout, setLayout] = useState(() => ({ active: localStorage.getItem(clientStorageKey("cage-active")) || "" })),
7690 [browser, setBrowser] = useState({ tabs: [] }),
91新增: [browserSettingsRevision, setBrowserSettingsRevision] = useState(0),
7792 [settingsOpen, setSettingsOpen] = useState(false),
78删除: [hostGitOpen, setHostGitOpen] = useState(false),
93新增: [startOptions, setStartOptions] = useState(null),
94新增: [guestSystem, setGuestSystem] = useState(undefined),
7995 [startRequest, setStartRequest] = useState(null),
8096 [settingsSection, setSettingsSection] = useState("keyboard"),
8197 [home, setHome] = useState(true),
8298 [sidebarCollapsed, setSidebarCollapsed] = useState(
8399 readLocal(clientStorageKey("cage-sidebar-collapsed"), false),
84100 ),
101新增: [browserTabLayout, setBrowserTabLayout] = useState(
102新增: readLocal(clientStorageKey("cage-browser-tab-layout"), "horizontal"),
103新增: ),
85104 [selectedProject, setSelectedProject] = useState(""),
86105 [savedTabs, setSavedTabs] = useState(readLocal(clientStorageKey("cage-tab-layout"), {})),
106新增: [privateTabMetadata, setPrivateTabMetadata] = useState({}),
87107 [projectDialog, setProjectDialog] = useState(null),
88108 [rename, setRename] = useState(null),
89109 [toast, setToast] = useState(""),
90110 [fatal, setFatal] = useState(""),
91111 [connectionError, setConnectionError] = useState(""),
112新增: [browserError, setBrowserError] = useState(""),
92113 [dialog, setDialog] = useState(null),
93114 [transfer, setTransfer] = useState(null),
94115 [details, setDetails] = useState(false),
@@ -96,6 +117,7 @@ function App() {
96117 [quitting, setQuitting] = useState(null);
97118 // Keep feedback continuous until polling observes the accepted start job.
98119 const clientStatus = serverStatus && { ...serverStatus, keyboard: clientKeyboard(serverStatus.keyboard) };
120新增: const hostGitOpen = startOptions !== null;
99121 const status = clientStatus && (hostGitOpen || startRequest)
100122 ? { ...clientStatus, job: { running: true, kind: "start", message: hostGitOpen
101123 ? isRemoteClient() ? "正在检查云端主机 Git 安全保护…" : "正在检查本机 Git 安全保护…" : "正在启动 Cage 环境…" } }
@@ -124,6 +146,7 @@ function App() {
124146 busy = Boolean(status?.job?.running),
125147 showHome = !desktopOpen && (home || !status?.vm_running || !current);
126148 const setupProgress = status?.job?.setup_progress && (busy || status.job.error);
149新增: const cliSessions = useCLISessions(Boolean(status && !busy), windowVisible);
127150 const other = tabs.find(tab => tab.id === layout.other);
128151 const split = Boolean(other && current && !showHome && !desktopOpen);
129152 const panes = !split ? [current].filter(Boolean)
@@ -140,6 +163,32 @@ function App() {
140163 const liveBrowser = webPanes.find(tab => tab.id === browser.active) || webPanes[0];
141164 const liveBrowserVisible = !desktopOpen && !showHome && status?.ready &&
142165 liveBrowser && splitReady && (!split || browser.active === liveBrowser.id);
166新增: const viewBeforeBrowser = useRef(null);
167新增: const browserDismissed = useRef(false);
168新增: const browserVisible = !desktopOpen && !showHome && webPanes.length > 0;
169新增: const browserWasVisible = useRef(false);
170新增: useEffect(() => {
171新增: // Preserve the return destination until the last tab's removal is handled,
172新增: // including removals received through events or fallback polling.
173新增: if (browserWasVisible.current && !tabs.some(tab => tab.kind !== "terminal")) closeBrowser();
174新增: else if (!browserVisible) viewBeforeBrowser.current = {
175新增: layout, home: showHome, desktopOpen, selectedProject,
176新增: };
177新增: browserWasVisible.current = browserVisible;
178新增: }, [browserVisible, layout, showHome, desktopOpen, selectedProject, tabs]);
179新增: const closeBrowser = () => {
180新增: const previous = viewBeforeBrowser.current;
181新增: browserDismissed.current = true;
182新增: const available = id => tabs.some(tab => tab.id === id);
183新增: const restored = previous?.layout;
184新增: const id = [restored?.active, restored?.other].find(available);
185新增: setLayout(id ? { ...restored, active: id,
186新增: other: restored.other !== id && available(restored.other) ? restored.other : undefined,
187新增: } : { active });
188新增: setHome(Boolean(previous?.home || !previous?.desktopOpen && !id));
189新增: setDesktopOpen(Boolean(previous?.desktopOpen));
190新增: if (previous?.selectedProject) setSelectedProject(previous.selectedProject);
191新增: };
143192 const splitQueue = useRef(Promise.resolve());
144193 const requestedSplit = useRef(false);
145194 const nativeSplitRef = useRef(null);
@@ -158,7 +207,9 @@ function App() {
158207 if (!cancelled) setBrowser(previous => ({ ...previous, split: result.split }));
159208 } catch {
160209 if (!cancelled) {
161删除: setToast("无法调整浏览器分屏。请确认环境组件已更新,两个网页属于同一浏览器配置,且客机 Chromium 为 155 或更高版本。");
210新增: setToast(tabs.some(tab => [leftId, rightId].includes(tab.id) && tab.incognito)
211新增: ? "无痕标签可与终端分屏;两个网页分屏目前仅支持普通标签。"
212新增: : "无法调整浏览器分屏。请确认环境组件已更新,两个网页属于同一浏览器配置,且客机 Chromium 为 155 或更高版本。");
162213 setLayout(previous => ({ active: previous.active }));
163214 }
164215 }
@@ -191,11 +242,14 @@ function App() {
191242 if (finishedLogins) claudeProfiles.load();
192243 }, [finishedLogins, claudeProfiles.load]);
193244 const audio = useAudioOutput(running && !status?.environment_update_required && !connectionError);
245新增: useEffect(() => {
246新增: if (audio.error) setToast(audio.error);
247新增: }, [audio.error]);
194248 const projects = status?.projects || [];
195249 const workspace = selectedProject || status?.workspace;
196250 const contentWorkspace =
197251 terminal && !showHome ? current.workspace : workspace;
198删除: const setupProxy = needsProxySetup(settings, status, proxy);
252新增: const setupProxy = !nativeGuestLabel && needsProxySetup(settings, status, proxy);
199253 const network = connectionError
200254 ? { mode: "unknown", label: "外网状态待确认" }
201255 : networkState(status);
@@ -217,7 +271,18 @@ function App() {
217271 ? status?.environment_update_required ? "环境待更新" : "浏览器待恢复"
218272 : "已停止";
219273 const notify = (text) => setToast(text);
220删除: const desktopFiles = useDesktopFiles(Boolean(status?.ready));
274新增: const clipboardConnection = getClientContext().connection_id;
275新增: useEffect(() => {
276新增: if (!status?.ready || !nativeAvailable()) return;
277新增: const clipboard = shareClipboard({
278新增: connect: () => new WebSocket(runtimeSocketURL("/clipboard")), native,
279新增: onStatus: setToast,
280新增: setActive: active => { window.cageSharedClipboardActive = active; },
281新增: });
282新增: window.cageSyncClipboard = () => clipboard.sync();
283新增: return () => { clipboard.dispose(); delete window.cageSyncClipboard; };
284新增: }, [status?.ready, clipboardConnection]);
285新增: const desktopFiles = useDesktopFiles(Boolean(status?.ready), notify);
221286 const downloads = [...(browser.downloads || []), ...desktopFiles.downloads];
222287 useDownloadNotifications(downloads, notify, Boolean(browser.uploads?.length || desktopFiles.uploads.length));
223288 const refreshSettings = async () => {
@@ -235,11 +300,13 @@ function App() {
235300 setSettingsOpen(true);
236301 };
237302 const select = async (id, focusContent = true) => {
303新增: const tab = tabs.find((t) => t.id === id);
304新增: if (tab && tab.kind !== "terminal") browserDismissed.current = false;
238305 setDesktopOpen(false);
239306 setHome(false);
240删除: setActive(id);
241删除: localStorage.setItem(clientStorageKey("cage-active"), id);
242删除: const tab = tabs.find((t) => t.id === id);
307新增: if (tab?.kind === "browser-settings") setLayout({ active: id });
308新增: else setActive(id);
309新增: if (!tab?.incognito) localStorage.setItem(clientStorageKey("cage-active"), id);
243310 if (tab?.kind === "terminal") setSelectedProject(tab.workspace);
244311 if (tab && tab.kind !== "terminal") {
245312 try {
@@ -257,7 +324,8 @@ function App() {
257324 const box = workspaceBox.current?.getBoundingClientRect();
258325 if (!box || busy || !running || desktopOpen || tabs.length < 2 ||
259326 document.elementFromPoint(x, y)?.closest(".chrome") ||
260删除: !tabs.some(tab => tab.id === id) || x < box.left || x > box.right ||
327新增: !tabs.some(tab => tab.id === id) || tabs.find(tab => tab.id === id)?.kind === "browser-settings" ||
328新增: current?.kind === "browser-settings" || x < box.left || x > box.right ||
261329 y < box.top || y > box.bottom) return null;
262330 return x < box.left + box.width * (dualBrowser && nativeSplit?.fraction || 0.5) ? "left" : "right";
263331 };
@@ -286,10 +354,12 @@ function App() {
286354 };
287355 const openBrowserPage = async (
288356 url = settings?.browser_home_url || "https://www.bing.com/",
357新增: incognito = Boolean(current?.incognito),
289358 ) => {
290删除: setDesktopOpen(false);
291删除: const result = await action("/browser/new", { url });
359新增: browserDismissed.current = false;
360新增: const result = await action("/browser/new", { url, incognito });
292361 if (result) {
362新增: setDesktopOpen(false);
293363 setHome(false);
294364 setTabs((list) =>
295365 list.some((t) => t.id === result.id)
@@ -298,6 +368,7 @@ function App() {
298368 ...list,
299369 {
300370 id: result.id,
371新增: incognito,
301372 kind: "web",
302373 url,
303374 title: "新标签页",
@@ -309,6 +380,24 @@ function App() {
309380 return result;
310381 };
311382 const newPage = () => openBrowserPage();
383新增: const showBrowserResult = result => {
384新增: if (!result?.id) return;
385新增: browserDismissed.current = false;
386新增: setDesktopOpen(false); setHome(false);
387新增: setTabs(previous => previous.some(tab => tab.id === result.id)
388新增: ? previous.map(tab => tab.id === result.id ? { ...tab, ...result } : tab)
389新增: : [...previous, result]);
390新增: setLayout({ active: result.id });
391新增: };
392新增: const openBrowserSettings = async (section = "general") => {
393新增: const result = await action("/browser/settings", { mode: section });
394新增: if (result) showBrowserResult(result);
395新增: };
396新增: const openInternalPage = async (mode, id) => {
397新增: const result = await action("/browser/internal-page", { mode, id });
398新增: if (result) showBrowserResult(result);
399新增: };
400新增: const openSettingsPageResult = result => result.id ? showBrowserResult(result) : openBrowserPage(result.url, false);
312401 const openBrowser = () => {
313402 const tab =
314403 tabs.find(
@@ -328,19 +417,51 @@ function App() {
328417 workspace: path, kind,
329418 ...(loginAccountId && { claude_account_id: loginAccountId }),
330419 });
420新增: showTerminal(result);
421新增: sessionsChanged();
422新增: if (kind === "claude" && result.claude_account_id &&
423新增: !claudeProfiles.accounts?.some((profile) => profile.id === result.claude_account_id)) {
424新增: claudeProfiles.load();
425新增: }
426新增: };
427新增: const showTerminal = result => {
331428 const tab = {
332429 ...result, id: "terminal:" + result.id, sessionId: result.id,
333430 terminalKind: result.kind, kind: "terminal",
334431 };
335删除: setTabs((list) => [...list.filter((t) => t.id !== tab.id), tab]);
432新增: setTabs((list) => [...list.filter((t) => t.id !== tab.id && (!tab.cli_session_id || t.cli_session_id !== tab.cli_session_id)), tab]);
336433 setSelectedProject(result.workspace);
337434 setDesktopOpen(false);
338435 setHome(false);
339436 setActive(tab.id);
340删除: if (kind === "claude" && result.claude_account_id &&
341删除: !claudeProfiles.accounts?.some((profile) => profile.id === result.claude_account_id)) {
342删除: claudeProfiles.load();
343删除: }
437新增: };
438新增: const openSessionTerminal = async session => {
439新增: if (openingSession) return;
440新增: setOpeningSession(session.id);
441新增: try {
442新增: const view = await api("/cli/sessions/" + session.id + "/open", {});
443新增: const terminals = await api("/terminals");
444新增: const terminal = terminals.find(item => item.id === view.desktop_terminal_id && item.cli_session_id === session.id);
445新增: if (!terminal) throw new Error("终端状态已变化,请重新打开会话");
446新增: showTerminal(terminal);
447新增: sessionsChanged();
448新增: } catch (error) { notify(error.message); }
449新增: finally { setOpeningSession(""); }
450新增: };
451新增: const archiveSession = async (session, anchor) => {
452新增: if (!(await confirm({title:"归档这段会话?", body:"归档会关闭关联终端。历史将保留,可从设置中的已归档会话恢复。", confirm:"归档会话", anchor}))) return;
453新增: try {
454新增: await api("/cli/sessions/" + session.id + "/archive", {});
455新增: setTabs(list => list.filter(tab => tab.cli_session_id !== session.id));
456新增: sessionsChanged();
457新增: refreshStatus.current?.();
458新增: } catch (error) { notify(error.message); }
459新增: };
460新增: const pinSession = async session => {
461新增: try {
462新增: await api("/cli/sessions/" + session.id + "/metadata", {pinned:!session.pinned});
463新增: sessionsChanged();
464新增: } catch (error) { notify(error.message); }
344465 };
345466 const newTerminalHere = (event) =>
346467 newTerminal(contentWorkspace, event?.currentTarget?.tagName === "BUTTON"
@@ -351,10 +472,11 @@ function App() {
351472 onSelect={(kind) => createTerminal(terminalChoice.path, kind).catch((e) => notify(e.message))} />
352473 );
353474 const openEditor = async (path = workspace) => {
354删除: setDesktopOpen(false);
355删除: setHome(false);
475新增: browserDismissed.current = false;
356476 const result = await action("/browser/editor", { workspace: path });
357477 if (result) {
478新增: setDesktopOpen(false);
479新增: setHome(false);
358480 setTabs((list) =>
359481 list.some((t) => t.id === result.id)
360482 ? list
@@ -372,7 +494,8 @@ function App() {
372494 setActive(result.id);
373495 }
374496 };
375删除: const closeTab = async (tab) => {
497新增: const closeTab = async (tab, anchor) => {
498新增: if (tab.cli_session_id) return archiveSession({id:tab.cli_session_id, title:tab.title}, anchor);
376499 if (tab.kind === "terminal") {
377500 if (
378501 !tab.closed &&
@@ -402,6 +525,13 @@ function App() {
402525 if (!(await action("/browser/close", { id: tab.id }))) return;
403526 }
404527 setTabs((list) => list.filter((t) => t.id !== tab.id));
528新增: if (tab.incognito) setPrivateTabMetadata(previous => Object.fromEntries(Object.entries(previous).map(([key, value]) => [key,
529新增: Object.fromEntries(Object.entries(value).filter(([id]) => id !== tab.id).map(([id, item]) =>
530新增: [id, id === "order" ? item.filter(id => id !== tab.id) : item])),
531新增: ])));
532新增: // The browser visibility effect restores the previous view for an empty
533新增: // browser. Do not overwrite it when a close response follows its event.
534新增: if (tab.kind !== "terminal" && !tabs.some(item => item.id !== tab.id && item.kind !== "terminal")) return;
405535 if (split && (tab.id === active || tab.id === other.id)) {
406536 const remaining = tab.id === active ? other.id : active;
407537 setLayout({ active: remaining });
@@ -420,6 +550,8 @@ function App() {
420550 };
421551 const navigate = async (id, address) => {
422552 try {
553新增: const internal = /^cage:\/\/settings(?:#(general|appearance|privacy|extensions|about))?\/?$/.exec(address.trim());
554新增: if (internal) { await openBrowserSettings(internal[1] || "general"); return; }
423555 const url = normalizeURL(address);
424556 if (network.mode !== "open" && !isGuestLocalURL(url)) {
425557 setSafetyOpen(true);
@@ -488,16 +620,38 @@ function App() {
488620 ) {
489621 lastJob.current = next.job.id;
490622 await refreshSettings();
623新增: if (next.job.kind === "guest-install" && !next.job.error) {
624新增: const install = await api("/environment/guest-systems");
625新增: if (live && install.activate) setGuestSystem(previous => ({ ...previous, activate:true }));
626新增: }
491627 if (next.job.error) notify(next.job.error);
492628 }
493629 if (next.ready) {
494630 const fetchBrowser = !browserStreamReady.current || !initialized.current;
495631 const [browserResult, t] = await Promise.all([
496删除: fetchBrowser ? api("/browser/tabs") : null,
632新增: fetchBrowser ? api("/browser/tabs").then(result => {
633新增: if (live) setBrowserError("");
634新增: return result;
635新增: }).catch(error => {
636新增: if (live) setBrowserError(error.message);
637新增: return null;
638新增: }) : null,
497639 api("/terminals"),
498640 ]);
499641 if (!live) return;
500642 const b = browserResult || browserSnapshot.current;
643新增: const legacyMetadata = readLocal(clientStorageKey("cage-tab-layout"), {})[next.environment_directory || next.workspace] || {};
644新增: for (const item of t) {
645新增: const saved = legacyMetadata["terminal:" + item.id];
646新增: if (!item.cli_session_id || item.metadata_set || !saved || (!saved.title && !saved.pinned)) continue;
647新增: try {
648新增: const updated = await api("/terminals/" + item.id + "/metadata", {
649新增: ...(saved.title ? {title:saved.title} : {}), pinned:Boolean(saved.pinned),
650新增: });
651新增: Object.assign(item, {title:updated.title, custom_title:updated.custom_title, pinned:updated.pinned, metadata_set:true});
652新增: } catch { /* Keep the existing local label until the host accepts it. */ }
653新增: }
654新增: if (!live) return;
501655 browserSnapshot.current = b;
502656 setBrowser(b);
503657 const all = [
@@ -519,17 +673,18 @@ function App() {
519673 ...all.filter((item) => !previous.some((p) => p.id === item.id)),
520674 ];
521675 });
522删除: if (initialized.current && b.active && b.active !== activeRef.current && !browserIds.current.has(b.active)) {
676新增: if (!browserDismissed.current && initialized.current && b.active && b.active !== activeRef.current && !browserIds.current.has(b.active)) {
523677 setDesktopOpen(false);
524678 setHome(false);
525679 }
526680 if (
527681 !activeRef.current ||
528682 !all.some((item) => item.id === activeRef.current) ||
529删除: (initialized.current &&
683新增: (!browserDismissed.current && initialized.current &&
530684 b.active &&
531685 !browserIds.current.has(b.active))
532686 ) {
687新增: if (browserDismissed.current && !all.some(item => item.id === activeRef.current)) setHome(true);
533688 // Let split reconciliation promote the remaining pane on close.
534689 if (!layoutRef.current.other || all.some(item => item.id === activeRef.current))
535690 setActive(b.active || all[0]?.id || "");
@@ -601,6 +756,7 @@ function App() {
601756 stream.onerror = () => { browserStreamReady.current = false; };
602757 stream.onmessage = (event) => {
603758 const b = JSON.parse(event.data);
759新增: setBrowserError("");
604760 if (b.desktopFocus === true) {
605761 setDesktopOpen(true);
606762 setHome(false);
@@ -624,13 +780,13 @@ function App() {
624780 ...b.tabs.filter((t) => !previous.some((p) => p.id === t.id)),
625781 ];
626782 });
627删除: if (b.active && b.focus) {
783新增: if (!browserDismissed.current && b.active && b.focus) {
628784 setDesktopOpen(false);
629785 setHome(false);
630786 }
631787 if (
632788 b.active &&
633删除: (b.focus ||
789新增: ((!browserDismissed.current && b.focus) ||
634790 !activeRef.current ||
635791 (!layoutRef.current.other && !activeRef.current.startsWith("terminal:")))
636792 )
@@ -649,8 +805,8 @@ function App() {
649805 (current?.title && current.title !== "新标签页"
650806 ? current.title + " · "
651807 : "") + "Cage";
652删除: if (active) localStorage.setItem(clientStorageKey("cage-active"), active);
653删除: }, [current?.url, current?.title, active]);
808新增: if (active && !current?.incognito) localStorage.setItem(clientStorageKey("cage-active"), active);
809新增: }, [current?.url, current?.title, current?.incognito, active]);
654810 useEffect(() => {
655811 if (!toast) return;
656812 const timer = setTimeout(() => setToast(""), 4500);
@@ -660,7 +816,7 @@ function App() {
660816 const key = (event) => {
661817 if (document.querySelector("[data-environment-dialog]") || !primaryModifier(event)) return;
662818 const k = event.key.toLowerCase();
663删除: if (document.querySelector("[data-browser-dialog]")) {
819新增: if (document.querySelector("[data-browser-dialog], .mac-login-fullscreen")) {
664820 if (k === "w") {
665821 event.preventDefault();
666822 event.stopImmediatePropagation();
@@ -713,6 +869,7 @@ function App() {
713869 return;
714870 }
715871 if (k === "t" && !event.shiftKey) handle = newPage;
872新增: if (k === "n" && event.shiftKey) handle = () => openBrowserPage(undefined, true);
716873 if (k === "d") handle = () => document.dispatchEvent(new Event("cage-add-favorite"));
717874 if (k === "enter" && event.shiftKey) handle = newTerminalHere;
718875 if (k === "l")
@@ -749,6 +906,7 @@ function App() {
749906 };
750907 window.addEventListener("keydown", key, true);
751908 window.cageEditAction = (command) => {
909新增: if (document.querySelector(".mac-login-fullscreen")) return false;
752910 if (
753911 settingsOpen ||
754912 transfer ||
@@ -766,6 +924,10 @@ function App() {
766924 return remote.current?.edit(command) || false;
767925 };
768926 window.cageNativeAction = async (command) => {
927新增: if (document.querySelector(".mac-login-fullscreen")) {
928新增: if (command === "closeTab" || command === "quit") document.dispatchEvent(new Event("cage-close-modal"));
929新增: if (command !== "quit") return;
930新增: }
769931 if (document.querySelector("[data-environment-dialog]")) {
770932 if (command === "closeTab") document.dispatchEvent(new Event("cage-close-modal"));
771933 return;
@@ -800,7 +962,7 @@ function App() {
800962 if (command === "newTerminal" && status?.vm_running)
801963 await newTerminalHere();
802964 if (command === "closeTab") {
803删除: if (document.querySelector("[data-browser-dialog]")) {
965新增: if (document.querySelector("[data-browser-dialog], .mac-login-fullscreen")) {
804966 document.dispatchEvent(new Event("cage-close-modal"));
805967 return;
806968 }
@@ -874,7 +1036,12 @@ function App() {
8741036 ]);
8751037 const project = projectName(contentWorkspace, status?.environment_directory);
8761038 const tabLayoutKey = status?.environment_directory || status?.workspace;
877删除: const metadata = savedTabs[tabLayoutKey] || {};
1039新增: const metadata = { ...(savedTabs[tabLayoutKey] || {}), ...(privateTabMetadata[tabLayoutKey] || {}) };
1040新增: for (const tab of tabs) {
1041新增: if (tab.cli_session_id && tab.metadata_set) metadata[tab.id] = {
1042新增: ...metadata[tab.id], title:tab.custom_title || tab.title, pinned:Boolean(tab.pinned),
1043新增: };
1044新增: }
8781045 const claudeLabels = new Map(claudeProfiles.accounts?.map((account) => [account.id, account.label || account.email]));
8791046 const claudeNumbers = new Map(claudeProfiles.accounts?.map((account, index) => [account.id, index + 1]));
8801047 const terminalAccountName = (tab) => claudeLabels.get(tab.claude_account_id) ||
@@ -891,12 +1058,24 @@ function App() {
8911058 )
8921059 : dualBrowser ? browserTabs.filter(tab => current.id === rightId ? tab.id === rightId : tab.id !== rightId) : browserTabs;
8931060 const renameTab = (tab) =>
894删除: setRename({ id: tab.id, title: tabName(tab, metadata, project) });
895删除: const pinTab = (id) =>
1061新增: setRename({ id: tab.id, title: tabName({ ...tab, incognito: false }, metadata, project) });
1062新增: const updateSharedMetadata = async (tab, changes) => {
1063新增: const updated = await api("/terminals/" + tab.sessionId + "/metadata", changes);
1064新增: setTabs(list => list.map(item => item.id === tab.id ? {
1065新增: ...item, title:updated.title, custom_title:updated.custom_title, pinned:updated.pinned, metadata_set:true,
1066新增: } : item));
1067新增: };
1068新增: const pinTab = (id) => {
1069新增: const tab = tabs.find(tab => tab.id === id);
1070新增: if (tab?.cli_session_id) {
1071新增: void updateSharedMetadata(tab, {pinned:!metadata[id]?.pinned}).catch(error => notify(error.message));
1072新增: return;
1073新增: }
8961074 changeTabMetadata({
8971075 ...metadata,
8981076 [id]: { ...metadata[id], pinned: !metadata[id]?.pinned },
8991077 });
1078新增: };
9001079 const persist = (key, value, setter) => {
9011080 try {
9021081 localStorage.setItem(clientStorageKey(key), JSON.stringify(value));
@@ -905,12 +1084,21 @@ function App() {
9051084 notify("未能保存界面偏好,请检查本地存储空间。");
9061085 }
9071086 };
908删除: const changeTabMetadata = (next) =>
1087新增: const changeTabMetadata = (next) => {
1088新增: const currentPrivateIDs = new Set(tabs.filter(tab => tab.incognito).map(tab => tab.id));
1089新增: const privateIDs = new Set([...currentPrivateIDs, ...Object.keys(privateTabMetadata[tabLayoutKey] || {}).filter(id => id !== "order" && id !== "sessionOrder")]);
1090新增: const persistent = Object.fromEntries(Object.entries(next).filter(([id]) => !privateIDs.has(id)));
1091新增: if (next.order) persistent.order = next.order.filter(id => !privateIDs.has(id) && tabs.some(tab => tab.id === id));
1092新增: setPrivateTabMetadata(previous => ({ ...previous, [tabLayoutKey]: {
1093新增: ...Object.fromEntries(Object.entries(next).filter(([id]) => currentPrivateIDs.has(id))),
1094新增: ...(next.order ? { order: next.order } : {}),
1095新增: } }));
9091096 persist(
9101097 "cage-tab-layout",
911删除: { ...savedTabs, [tabLayoutKey]: next },
1098新增: { ...savedTabs, [tabLayoutKey]: persistent },
9121099 setSavedTabs,
9131100 );
1101新增: };
9141102 const reorder = (from, to, scopeOrder) => {
9151103 if (scopeOrder) {
9161104 const ids = new Set(scopeOrder);
@@ -972,29 +1160,31 @@ function App() {
9721160 const paneTabs = tab => !dualBrowser ? browserTabs : browserTabs.filter(item =>
9731161 item.id === tab.id || (tab.id === leftId && item.id !== rightId));
9741162 const browserHeader = tab => <BrowserHeader vault={passwordVault} onManageVault={() => openSettings("vault")} tab={tab} tabs={paneTabs(tab)} metadata={metadata}
1163新增: vertical={browserTabLayout === "vertical"}
9751164 ready={status.ready} busy={busy} focused={active === tab.id} compact={split} splitDrag={splitDrag}
9761165 sidebarButton={sidebarButton(paneSide(tab.id))} exitButton={expandButton(tab)}
9771166 triggerRef={tab.id === active ? terminalTrigger : undefined}
9781167 location={split ? `heading-${tab.id}` : "heading"} menu={terminalMenuAt(split ? `heading-${tab.id}` : "heading")}
979删除: back={browser.split?.history?.[tab.id]?.back ?? (tab.id === browser.active && browser.back)}
980删除: forward={browser.split?.history?.[tab.id]?.forward ?? (tab.id === browser.active && browser.forward)}
1168新增: back={tab.kind !== "browser-settings" && (browser.split?.history?.[tab.id]?.back ?? (tab.id === browser.active && browser.back))}
1169新增: forward={tab.kind !== "browser-settings" && (browser.split?.history?.[tab.id]?.forward ?? (tab.id === browser.active && browser.forward))}
9811170 action={action} onSelect={select} onClose={closeTab} onRename={renameTab} onPin={pinTab} onReorder={reorder}
9821171 onNew={newPage} onNavigate={address => navigate(tab.id, address)} onOpen={openBrowserPage}
983删除: downloads={downloads} onStatus={notify} onRemote={async command => {
984删除: if (browser.active !== tab.id) await select(tab.id, false);
985删除: if (activeRef.current === tab.id) remote.current?.[command]();
986删除: }}
1172新增: onNewPrivate={() => openBrowserPage(undefined, true)} onNewRegular={() => openBrowserPage(undefined, false)}
1173新增: onSettings={openBrowserSettings}
1174新增: onReload={() => tab.kind === "browser-settings" ? setBrowserSettingsRevision(value => value + 1) : action("/browser/reload", { id: tab.id })}
1175新增: onCloseBrowser={!dualBrowser || tab.id === rightId ? closeBrowser : undefined}
1176新增: downloads={downloads} onStatus={notify}
9871177 onEditor={() => openEditor(tab.workspace || workspace)} recoveringEditor={recoveringEditor}
9881178 onRecover={() => recoverEditor(tab)} />;
9891179 const dialogs = (
9901180 <>
9911181 {hostGitOpen && (
9921182 <HostGitPreparation
993删除: onClose={() => setHostGitOpen(false)}
1183新增: onClose={() => setStartOptions(null)}
9941184 onReady={async () => {
9951185 setStartRequest({ id: null });
996删除: setHostGitOpen(false);
997删除: const result = await action("/start");
1186新增: setStartOptions(null);
1187新增: const result = await action("/start", startOptions);
9981188 setStartRequest(result ? { id: result.id } : null);
9991189 if (result) refreshStatus.current?.();
10001190 }}
@@ -1003,6 +1193,7 @@ function App() {
10031193 {dialog && (
10041194 <Modal
10051195 title={dialog.title}
1196新增: anchor={dialog.anchor}
10061197 onClose={() => finishDialog(false)}
10071198 footer={
10081199 <>
@@ -1100,6 +1291,7 @@ function App() {
11001291 </>
11011292 );
11021293 return (
1294新增: <SafetyChecklistContext.Provider value={() => setSafetyOpen(true)}>
11031295 <div className={`app ${sidebarCollapsed ? "sidebar-collapsed" : ""}`}>
11041296 <div
11051297 className="workbench-shell"
@@ -1110,10 +1302,20 @@ function App() {
11101302 downloadAction={<BrowserDownloads sidebar downloads={downloads} ready={status.ready && !busy} onStatus={notify} />}
11111303 updateAction={<AppUpdateButton updates={appUpdates} />}
11121304 workspace={selectedProject || status.workspace}
1113删除: guestSystem={account?.guest_system || status.guest_system || "debian-13"}
1305新增: guestSystem={account?.guest_system || status.guest_system || guestSystem?.guest_system || "debian-13"}
11141306 defaultWorkspace={status.environment_directory}
11151307 projects={projects}
11161308 tabs={displayTabs}
1309新增: sessions={cliSessions.sessions.map(session => ({ ...session,
1310新增: claudeAccountNumber: claudeNumbers.get(session.account_id) }))}
1311新增: sessionError={cliSessions.error}
1312新增: sessionRefreshing={cliSessions.loading}
1313新增: onSessionRefresh={cliSessions.refresh}
1314新增: onSessionOpen={openSessionTerminal}
1315新增: openingSession={openingSession}
1316新增: onSessionArchive={archiveSession}
1317新增: onSessionPin={pinSession}
1318新增: onSessionRename={session => setRename({id:session.id, title:session.title, session:true})}
11171319 saved={metadata}
11181320 active={active}
11191321 home={showHome}
@@ -1130,10 +1332,13 @@ function App() {
11301332 onPin={pinTab}
11311333 splitDrag={splitDrag}
11321334 onReorder={reorder}
1335新增: onSessionReorder={(path, order) => changeTabMetadata({ ...metadata,
1336新增: sessionOrder: { ...metadata.sessionOrder, [path]: order } })}
11331337 onProjectSelect={setSelectedProject}
11341338 onNewTerminal={newTerminal}
11351339 terminalMenuAt={terminalMenuAt}
11361340 onBrowser={openBrowser}
1341新增: onTailscale={() => setTailscaleOpen(true)}
11371342 desktopOpen={desktopOpen}
11381343 onClaudeWeb={() => openBrowserPage("https://claude.ai/")}
11391344 onClaudeDesktop={() => { setHome(false); setDesktopOpen(true); }}
@@ -1149,6 +1354,10 @@ function App() {
11491354 )}
11501355 <div className="workbench-main">
11511356 {showHome && terminalHeader(null)}
1357新增: {browserError && running && !connectionError && <div className="connection-banner" role="status">
1358新增: <span>客机浏览器暂时无法连接。{browserError}</span>
1359新增: <button onClick={() => refreshStatus.current?.()}>重试</button>
1360新增: </div>}
11521361 {connectionError && (
11531362 <div className="connection-banner" role="alert">
11541363 工作台连接中断,后台状态暂时未知。
@@ -1164,7 +1373,10 @@ function App() {
11641373 <main className={`workspace ${split ? "workspace-split" : ""}`} ref={workspaceBox}
11651374 style={{ "--split-left": `${100 * (dualBrowser && nativeSplit?.fraction || 0.5)}%` }}>
11661375 {dropSide && <div aria-hidden="true" className={`split-drop split-${dropSide}`}>{dropSide === "left" ? "放到左侧" : "放到右侧"}</div>}
1167删除: {desktopOpen && <ClaudeDesktop
1376新增: {desktopOpen && macGuest && <MacOSClaudeWindow uploads={desktopFiles.uploads} keyboard={status.keyboard} remoteRef={remote}
1377新增: onStatus={notify} onFallback={(text, message) => setTransfer({ text, message })} visible={!settingsOpen} onConfirm={confirm}
1378新增: sidebarCollapsed={sidebarCollapsed} onExpand={() => persist("cage-sidebar-collapsed", false, setSidebarCollapsed)} />}
1379新增: {desktopOpen && !macGuest && <ClaudeDesktop
11681380 uploads={desktopFiles.uploads}
11691381 onProjectOpened={() => refreshStatus.current?.()}
11701382 status={status} visible={!settingsOpen} remoteRef={remote}
@@ -1182,7 +1394,12 @@ function App() {
11821394 {(status.vm_running || terminal) && (
11831395 <>
11841396 {!desktopOpen && !showHome && webPanes.length > 0 && (
1185删除: <section className={`pane-lane browser-lane ${dualBrowser ? "" : "split-" + paneSide(webPanes[0].id)}`}>
1397新增: <section className={`pane-lane browser-lane ${browserTabLayout === "vertical" ? "vertical-browser" : ""} ${dualBrowser ? "" : "split-" + paneSide(webPanes[0].id)}`}>
1398新增: {browserTabLayout === "vertical" && <BrowserTabRail tabs={browserTabs} metadata={metadata}
1399新增: active={liveBrowser?.id} ready={status.ready} busy={busy} splitDrag={splitDrag}
1400新增: sidebarButton={sidebarButton(paneSide(webPanes[0].id))}
1401新增: onSelect={select} onClose={closeTab} onRename={renameTab} onPin={pinTab} onReorder={reorder}
1402新增: onNew={newPage} />}
11861403 <div className="browser-headers">{webPanes.map(tab =>
11871404 <div key={paneSide(tab.id) || "single"} className="browser-header-cell" data-focused={active === tab.id}
11881405 onPointerDownCapture={() => focusHeader(tab)} onFocusCapture={() => focusHeader(tab)}>
@@ -1191,15 +1408,23 @@ function App() {
11911408 <div className="pane-body" onPointerDownCapture={() => {
11921409 if (!dualBrowser && liveBrowser?.id !== active) focusHeader(liveBrowser);
11931410 }}>
1194删除: {status.ready && <RemoteView ref={remote} visible={Boolean(liveBrowserVisible && !settingsOpen)}
1411新增: {status.ready && liveBrowser?.kind === "browser-settings" && <BrowserSettingsPage
1412新增: key={`${liveBrowser.id}:${browserSettingsRevision}`} tab={liveBrowser} tabs={tabs}
1413新增: currentHome={settings.browser_home_url} layout={browserTabLayout}
1414新增: onLayoutChange={value => persist("cage-browser-tab-layout", value, setBrowserTabLayout)}
1415新增: onSectionChange={openBrowserSettings}
1416新增: onSaved={next => setSettings(previous => ({ ...previous, ...next }))}
1417新增: onInternal={openInternalPage} onOpenPage={openSettingsPageResult} onConfirm={confirm} />}
1418新增: {status.ready && <RemoteView ref={remote} visible={Boolean(liveBrowserVisible && !settingsOpen && liveBrowser?.kind !== "browser-settings")}
11951419 copyScope={webPanes.map(tab => `${tab.id}:${tab.document || ""}`).join("|")}
11961420 focused={dualBrowser || liveBrowser?.id === active} keyboard={status.keyboard}
1421新增: guestPlatform={status.guest_system} systemClipboard={browser.capabilities?.systemClipboard !== false}
11971422 tabId={liveBrowser?.id} onStatus={notify}
11981423 onFallback={(text, message) => setTransfer({ text, message })} />}
11991424 {!status.ready && <div className="view-overlay">
12001425 <RefreshCw /><h3>浏览器连接暂时不可用</h3>
12011426 <p>环境和终端仍可运行;恢复浏览器不会停止现有终端。</p>
1202删除: <button className="primary" disabled={busy} onClick={() => setHostGitOpen(true)}>恢复浏览器</button>
1427新增: <button className="primary" disabled={busy} onClick={() => setStartOptions({})}>恢复浏览器</button>
12031428 </div>}
12041429 {status.ready && !splitReady && <div className="view-overlay">正在调整浏览器布局…</div>}
12051430 </div>
@@ -1222,6 +1447,7 @@ function App() {
12221447 visible={visible && !settingsOpen}
12231448 focused={active === tab.id}
12241449 onStatus={notify}
1450新增: onAccountChanged={view => { if (view?.desktop_terminal_id && view.desktop_terminal_id !== tab.sessionId) void openSessionTerminal({id:tab.cli_session_id}); }}
12251451 />
12261452 </div>
12271453 </section>;
@@ -1235,7 +1461,7 @@ function App() {
12351461 {setupProgress ? <>
12361462 <h1>{status.job.error ? "环境安装未完成" : "正在安装 Cage 环境"}</h1>
12371463 <SetupProgress job={status.job} onDetails={() => setDetails(true)}
1238删除: onStop={stop} onRetry={() => setHostGitOpen(true)} disconnected={Boolean(connectionError)} />
1464新增: onStop={stop} onRetry={() => setStartOptions(status.job.kind === "guest-install" ? { guest_system: status.job.setup_progress.system } : {})} disconnected={Boolean(connectionError)} />
12391465 </> : <>
12401466 <h1>
12411467 {busy
@@ -1255,19 +1481,19 @@ function App() {
12551481 : "先启动 Cage 环境"}
12561482 </h1>
12571483 <p className="welcome-subtitle">
1258删除: {busy
1484新增: <SafetyMessage message={busy
12591485 ? status.job.message
12601486 : running
12611487 ? !status.ready
1262删除: ? "浏览器连接尚未就绪,可以恢复连接或继续使用终端。"
1488新增: ? status.environment_update_error || "浏览器连接尚未就绪,可以恢复连接或继续使用终端。"
12631489 : network.mode === "open"
12641490 ? "环境已连接,网络检查通过。可以浏览网页或打开本地项目。"
12651491 : `${network.label}。终端与本地文件仍可使用。`
12661492 : setupProxy
12671493 ? "先连接你的代理,再启动浏览器、终端和编辑器。无需安装额外的代理软件。"
1268删除: : "准备独立的浏览器和终端,完成网络检查后开始工作。"}
1494新增: : "准备独立的浏览器和终端,完成网络检查后开始工作。"} />
12691495 </p>
1270删除: {!running && (
1496新增: {!running && !nativeGuestLabel && (
12711497 <ol className="onboarding-steps" aria-label="开始使用 Cage">
12721498 {["配置代理", "启动环境", "开始工作"].map(
12731499 (label, index) => (
@@ -1299,11 +1525,12 @@ function App() {
12991525 ? runtimeLabel
13001526 : setupProxy
13011527 ? "自备代理订阅、YAML 配置或节点"
1302删除: : "代理已配置,首次启动会下载开发环境"}
1528新增: : nativeGuestLabel ? `${nativeGuestLabel} 客机已安装` : "代理已配置,首次启动会下载开发环境"}
13031529 </small>
13041530 </span>
13051531 </div>
1306删除: {!running && status.local_vm_storage && !isRemoteClient() && <button className="storage-entry text-button" disabled={busy} onClick={() => openSettings("project")}>选择环境存储位置</button>}
1532新增: {!busy && !running && !account?.guest_system && status.local_vm_storage && !isRemoteClient() && <GuestSystemPicker system={guestSystem} onChange={setGuestSystem} />}
1533新增: {!running && !nativeGuestLabel && status.local_vm_storage && !isRemoteClient() && <button className="storage-entry text-button" disabled={busy} onClick={() => openSettings("project")}>选择环境存储位置</button>}
13071534 <div className="start-project-footer">
13081535 <span>
13091536 <i className={`status-dot ${network.mode}`} />
@@ -1318,11 +1545,18 @@ function App() {
13181545 <button
13191546 className="primary"
13201547 data-terminal-location="start"
1321删除: disabled={busy || Boolean(connectionError)}
1548新增: disabled={busy || Boolean(connectionError) || (!running && !setupProxy &&
1549新增: ((!account?.guest_system && status.local_vm_storage && !isRemoteClient() && guestSystem === undefined) || !validGuestChoice(guestSystem)))}
13221550 onClick={(event) => {
1323删除: if (!running && setupProxy) openSettings("network");
1551新增: if (!running && guestSystem?.activate) {
1552新增: api("/environment/guest-systems/activate", {}).then(() => native("reconnect")).catch((e) => setToast(e.message));
1553新增: } else if (!running && setupProxy) openSettings("network");
13241554 else if (!running || !status.ready)
1325删除: setHostGitOpen(true);
1555新增: setStartOptions(!running && guestSystem?.guest_system === "debian-13" && !guestSystem.clone ? { guest_system: "debian-13" } : !running && guestSystem ? {
1556新增: guest_system: guestSystem.guest_system, media: guestSystem.media, sha256: guestSystem.sha256,
1557新增: clone_key: guestSystem.clone_key,
1558新增: editor_terms: guestSystem.editor_terms,
1559新增: } : {});
13261560 else if (status.environment_workspace)
13271561 setProjectDialog({ path: "" });
13281562 else newTerminal(workspace, event.currentTarget);
@@ -1346,7 +1580,8 @@ function App() {
13461580 : !running
13471581 ? setupProxy
13481582 ? "配置网络与代理"
1349删除: : "启动 Cage 环境"
1583新增: : guestSystem?.activate ? "打开工作台" : guestSystem?.pending ? "继续安装" :
1584新增: guestSystem && guestSystem.guest_system !== "debian-13" ? "安装客户机" : "启动 Cage 环境"
13501585 : !status.ready
13511586 ? "恢复浏览器"
13521587 : status.environment_workspace
@@ -1358,6 +1593,7 @@ function App() {
13581593 </div>
13591594 {running && (
13601595 <div className="welcome-shortcuts">
1596新增: {macGuest && <MacOSLogin disabled={!status.ready || busy} />}
13611597 <button onClick={newTerminalHere} data-terminal-location="shortcuts" aria-haspopup="menu" disabled={busy}>
13621598 <TerminalSquare size={16} />
13631599 新建终端
@@ -1372,11 +1608,11 @@ function App() {
13721608 </div>
13731609 )}
13741610 {terminalMenuAt("shortcuts")}
1375删除: {!running && (
1611新增: {!running && !nativeGuestLabel && (
13761612 <p className="welcome-hint">
13771613 {setupProxy
13781614 ? "Cage 不提供代理或 Claude 账户。连接后,在 Cage 内完成 Claude 登录。"
1379删除: : "首次启动需要下载 Linux 镜像和开发工具,请保持网络连接。可在操作详情中查看进度,失败后可以重试。"}
1615新增: : "首次安装时可在操作详情中查看下载和配置进度;中断后可以继续安装。"}
13801616 </p>
13811617 )}
13821618 {running && status.ready && (
@@ -1396,9 +1632,10 @@ function App() {
13961632 <ul className="project-connection-errors">
13971633 {status.project_errors.map(({ path, message }) => (
13981634 <li key={path}>
1399删除: <strong>{projectName(path)}</strong>
1635新增: <strong>{projectName(path, status.environment_directory)}</strong>
14001636 <span className="project-error-path">{path}</span>
14011637 <p>{message}</p>
1638新增: <button disabled={!status.ready || busy} onClick={() => setProjectDialog({ path })}>连接项目</button>
14021639 </li>
14031640 ))}
14041641 </ul>
@@ -1407,8 +1644,8 @@ function App() {
14071644 )}
14081645 {!setupProgress && status.job?.error && (
14091646 <div className="start-error" role="alert">
1410删除: <strong>本次操作未完成</strong>
1411删除: <p>{status.job.error}</p>
1647新增: <strong>{status.job.message || "本次操作未完成"}</strong>
1648新增: <p><SafetyMessage message={status.job.error} /></p>
14121649 {status.can_restore && (
14131650 <button
14141651 className="text-button"
@@ -1471,14 +1708,14 @@ function App() {
14711708 <span className="status-spacer" />
14721709 <AudioControls audio={audio} />
14731710 <span className="status-feedback" role="status">
1474删除: {toast ||
1711新增: <SafetyMessage message={toast ||
14751712 (busy
14761713 ? status.job.message
14771714 : running
14781715 ? status.ready
14791716 ? isRemoteClient() ? "文件保存在云端" : "文件与本机同步"
14801717 : "环境运行中 · 浏览器待恢复"
1481删除: : "")}
1718新增: : "")} />
14821719 </span>
14831720 {status.job?.log && (
14841721 <button title="操作详情" onClick={() => setDetails(true)}>
@@ -1512,6 +1749,13 @@ function App() {
15121749 onConfirm={confirm}
15131750 />
15141751 )}
1752新增: {tailscaleOpen && <TailscalePanel status={status} onClose={() => setTailscaleOpen(false)}
1753新增: onConfirm={confirm} onInstall={async () => {
1754新增: const nativeGuest = ["macos", "windows-11"].includes(status.guest_system);
1755新增: if (nativeGuest && !await confirm({ title: "更新环境组件?", body: "更新会重新连接浏览器和显示组件,请先保存工作。设备身份、公钥和个人数据保留。", confirm: "更新组件" })) return;
1756新增: await action(nativeGuest ? "/environment/update" : "/tailscale/install", {});
1757新增: }}
1758新增: onOpenBrowser={async url => { const result = await openBrowserPage(url, false); if (result) setTailscaleOpen(false); }} />}
15151759 {projectDialog && (
15161760 <ProjectDialog
15171761 current={settings}
@@ -1543,9 +1787,24 @@ function App() {
15431787 <form
15441788 className="modal-body project-form"
15451789 id="rename-tab"
1546删除: onSubmit={(event) => {
1790新增: onSubmit={async (event) => {
15471791 event.preventDefault();
15481792 if (!rename.title.trim()) return;
1793新增: if (rename.session) {
1794新增: try {
1795新增: await api("/cli/sessions/" + rename.id + "/metadata", {title:rename.title.trim()});
1796新增: sessionsChanged(); setRename(null);
1797新增: } catch (error) { notify(error.message); }
1798新增: return;
1799新增: }
1800新增: const tab = tabs.find(tab => tab.id === rename.id);
1801新增: if (tab?.cli_session_id) {
1802新增: try {
1803新增: await updateSharedMetadata(tab, {title:rename.title.trim()});
1804新增: setRename(null);
1805新增: } catch (error) { notify(error.message); }
1806新增: return;
1807新增: }
15491808 changeTabMetadata({
15501809 ...metadata,
15511810 [rename.id]: {
@@ -1569,26 +1828,6 @@ function App() {
15691828 </form>
15701829 </Modal>
15711830 )}
1572删除: {safetyOpen && (
1573删除: <SafetyPanel
1574删除: status={
1575删除: connectionError
1576删除: ? {
1577删除: ...status,
1578删除: safety: {
1579删除: ...status.safety,
1580删除: gate: null,
1581删除: error: "控制服务连接中断,无法确认当前外网状态",
1582删除: },
1583删除: }
1584删除: : status
1585删除: }
1586删除: onClose={() => setSafetyOpen(false)}
1587删除: onSettings={openSettings}
1588删除: onOpenPage={openBrowserPage}
1589删除: onConfirm={confirm}
1590删除: />
1591删除: )}
15921831 {transfer && (
15931832 <Modal
15941833 title="文本传递"
@@ -1625,18 +1864,43 @@ function App() {
16251864 {details && (
16261865 <Modal title="操作详情" wide onClose={() => setDetails(false)}>
16271866 <div className="modal-body">
1628删除: <p>{status.job.message}</p>
1867新增: <p><SafetyMessage message={status.job.message} /></p>
16291868 {status.job.error && (
1630删除: <div className="error-message">{status.job.error}</div>
1869新增: <div className="error-message"><SafetyMessage message={status.job.error} /></div>
16311870 )}
16321871 <pre className="job-log">{status.job.log || "暂无日志"}</pre>
16331872 </div>
16341873 </Modal>
16351874 )}
1875新增: {safetyOpen && (
1876新增: <SafetyPanel
1877新增: status={
1878新增: connectionError
1879新增: ? {
1880新增: ...status,
1881新增: safety: {
1882新增: ...status.safety,
1883新增: gate: null,
1884新增: error: "控制服务连接中断,无法确认当前外网状态",
1885新增: },
1886新增: }
1887新增: : status
1888新增: }
1889新增: onClose={() => setSafetyOpen(false)}
1890新增: onSettings={openSettings}
1891新增: onOpenPage={openBrowserPage}
1892新增: onConfirm={confirm}
1893新增: />
1894新增: )}
16361895 {dialogs}
16371896 </div>
1897新增: </SafetyChecklistContext.Provider>
16381898 );
16391899}
1900新增:function GuestWorkspace() {
1901新增: const { account } = useAccount();
1902新增: return account?.initial_mac_setup ? <MacOSFirstSetup /> : <InitializationGate><App /></InitializationGate>;
1903新增:}
16401904export default function Workbench() {
1641删除: return <AccountProvider><AppearanceProvider><AccountGate><App /></AccountGate></AppearanceProvider></AccountProvider>;
1905新增: return <AccountProvider><AppearanceProvider><AccountGate><GuestWorkspace /></AccountGate></AppearanceProvider></AccountProvider>;
16421906}
新增ui/src/mobile-cli/browser-session.mjs+299 −0看文件
@@ -0,0 +1,299 @@
1新增:import { browserRequest, desktopRequest } from "./transport.mjs";
2新增:
3新增:const clamp = (value, low, high) => Math.max(low, Math.min(high, value));
4新增:export function viewportSize(element) {
5新增: return {
6新增: width: clamp(Math.round(element.clientWidth), 240, 1440),
7新增: height: clamp(Math.round(element.clientHeight), 160, 1600),
8新增: };
9新增:}
10新增:
11新增:export function framePoint(rect, frame, x, y) {
12新增: const width = frame.content_width || frame.width;
13新增: const height = frame.content_height || frame.height;
14新增: const scale = Math.min(rect.width / width, rect.height / height);
15新增: if (!(scale > 0)) return null;
16新增: const left = rect.left + (rect.width - width * scale) / 2;
17新增: const top = rect.top + (rect.height - height * scale) / 2;
18新增: const px = Math.floor((x - left) / scale);
19新增: const py = Math.floor((y - top) / scale);
20新增: return px >= 0 && px < width && py >= 0 && py < height ? {x: px, y: py, scale} : null;
21新增:}
22新增:
23新增:// Only frame reads repeat. One input or resize is followed by a fresh frame
24新增:// before the next input is accepted. A failed write is never replayed.
25新增:export function connectDisplay(stage, update, id, start, tool, initialURL) {
26新增: const desktop = tool === "desktop";
27新增: const request = desktop ? desktopRequest : browserRequest;
28新增: const toolName = desktop ? "Claude Desktop" : "远程浏览器";
29新增: let waitingSince = 0, homeNotice = "";
30新增: const base = "/" + id;
31新增: let alive = true, visible = true, opened = false, opening = true, writing = false;
32新增: let frame = null, read, timer, paused = false, mayExist = false;
33新增: let generation = 0, actionFrame = false, quietReads = 0, writeType = "";
34新增: let pixelRatioSupported = false;
35新增: const displaySize = () => ({...viewportSize(stage),
36新增: ...(pixelRatioSupported ? {pixel_ratio:clamp(window.devicePixelRatio || 1, 1, 8)} : {})});
37新增: const needsResize = size => frame && (frame.width !== size.width || frame.height !== size.height ||
38新增: (pixelRatioSupported && frame.requested_pixel_ratio !== size.pixel_ratio));
39新增: let queuedScroll = null, scrollTimer;
40新增: // Only untransmitted displacement lives in this queue. A scroll is taken
41新增: // out before sending; neither an interrupted write nor an old document replays it.
42新增: function cancelScroll() {
43新增: clearTimeout(scrollTimer); scrollTimer = null; queuedScroll = null;
44新增: }
45新增: let awaitingResizeFrame = false, pendingAddress = null;
46新增: const lifetime = new AbortController();
47新增: function discardAddress() {
48新增: awaitingResizeFrame = false;
49新增: pendingAddress?.resolve(false);
50新增: pendingAddress = null;
51新增: }
52新增: const closeRemote = () => {
53新增: if (mayExist) void request(base + "/close", {body: {}, keepalive: true}).catch(() => {});
54新增: };
55新增: const publish = (state) => { if (alive && visible) update(homeNotice && state.frame ? {...state, homeNotice} : state); };
56新增: const cancelRead = () => { clearTimeout(timer); read?.abort(); read = null; };
57新增: function failure(error, operation) {
58新增: discardAddress(); cancelScroll();
59新增: frame = null;
60新增: paused = true;
61新增: if (!desktop && operation === "frame" && error.status === 503) opened = mayExist = false;
62新增: const reopen = !opened || [401, 404, 410, 423].includes(error.status) || (error.status === 403 && operation !== "action");
63新增: const message = error.status === 404 && !opened ? "这台电脑尚不支持" + toolName + ",请更新电脑端 Cage。" :
64新增: error.message;
65新增: publish({error: message, uncertain: operation === "action" && !error.status, reopen});
66新增: }
67新增: const sameSurface = (first, second) => first && second && first.document === second.document &&
68新增: first.width === second.width && first.height === second.height &&
69新增: first.content_width === second.content_width && first.content_height === second.content_height;
70新增: function finishFrame(changed, fromAction = false) {
71新增: awaitingResizeFrame = false;
72新增: if (pendingAddress) {
73新增: const {url, resolve} = pendingAddress;
74新增: pendingAddress = null;
75新增: void send({type:"navigate", url}, frame).then(resolve);
76新增: return;
77新增: }
78新增: if (changed || fromAction) publish({frame, busy:false});
79新增: const size = displaySize();
80新增: if (needsResize(size)) {
81新增: cancelScroll();
82新增: timer = setTimeout(resize, 0);
83新增: return;
84新增: }
85新增: if (queuedScroll && !sameSurface(queuedScroll.expected, frame)) cancelScroll();
86新增: if (queuedScroll) { flushScroll(); return; }
87新增: quietReads = changed || fromAction ? 0 : Math.min(5, quietReads + 1);
88新增: // The first follow-up catches delayed paint after an input. Stable pages
89新增: // use conditional reads and progressively return to the idle cadence.
90新增: const delay = desktop ? 450 : [90, 180, 380, 800, 1500, 2500][quietReads];
91新增: timer = setTimeout(readFrame, delay);
92新增: }
93新增: async function decodeFrame(next, valid) {
94新增: if (next?.id !== id || typeof next.image !== "string" || !next.image ||
95新增: typeof next.document !== "string" || !Number.isInteger(next.width) || next.width <= 0 ||
96新增: !Number.isInteger(next.height) || next.height <= 0) throw new Error("主机返回的画面无效。");
97新增: if ((next.content_width !== undefined || next.content_height !== undefined) &&
98新增: (!Number.isFinite(next.content_width) || next.content_width <= 0 ||
99新增: !Number.isFinite(next.content_height) || next.content_height <= 0)) throw new Error("主机返回的画面尺寸无效。");
100新增: const src = "data:image/jpeg;base64," + next.image;
101新增: const changed = frame?.image !== src || !sameSurface(frame, next) || frame.focus !== next.focus ||
102新增: frame.url !== next.url || frame.title !== next.title || frame.password !== next.password || frame.window !== next.window || frame.shared !== next.shared ||
103新增: frame.login_supported !== next.login_supported || frame.content_width !== next.content_width || frame.content_height !== next.content_height;
104新增: if (frame?.image !== src) {
105新增: const image = new Image();
106新增: image.src = src;
107新增: await image.decode();
108新增: }
109新增: if (!valid()) return null;
110新增: if (next.url && next.url !== "about:blank") homeNotice = "";
111新增: if (!desktop && next.action_frame === true) actionFrame = true;
112新增: pixelRatioSupported = desktop && next.pixel_ratio_supported === true;
113新增: waitingSince = 0;
114新增: frame = {...next, image:src};
115新增: return changed;
116新增: }
117新增: async function readFrame() {
118新增: if (!alive || !visible || !opened || paused || writing || read) return;
119新增: const controller = new AbortController();
120新增: read = controller;
121新增: const valid = () => read === controller && !controller.signal.aborted && alive && visible && !paused;
122新增: const known = frame;
123新增: const tag = actionFrame && /^[a-f0-9]{32}$/.test(known?.frame_tag || "") ? known.frame_tag : "";
124新增: try {
125新增: const next = await request(base + "/frame" + (tag ? "?after=" + tag : ""), {signal:controller.signal});
126新增: if (!valid()) return;
127新增: let changed = false;
128新增: if (next?.unchanged === true) {
129新增: if (!tag || frame !== known || next.id !== id || next.frame_tag !== tag) throw new Error("远程画面的版本不匹配,请重新读取。");
130新增: } else {
131新增: changed = await decodeFrame(next, valid);
132新增: if (changed === null) return;
133新增: }
134新增: read = null;
135新增: finishFrame(changed);
136新增: } catch (error) {
137新增: if (valid()) {
138新增: if (error.status === 425 && (!waitingSince || Date.now() - waitingSince < 90000)) {
139新增: waitingSince ||= Date.now();
140新增: frame = null;
141新增: publish({waiting:true});
142新增: timer = setTimeout(readFrame, 1000);
143新增: } else {
144新增: failure(error, "frame");
145新增: }
146新增: }
147新增: } finally {
148新增: if (read === controller) read = null;
149新增: }
150新增: }
151新增: function canSend(expected, focus) {
152新增: return alive && visible && !writing && !paused && frame && expected &&
153新增: sameSurface(frame, expected) &&
154新增: (!focus || focus === frame.focus);
155新增: }
156新增: async function send(payload, expected, operation = "action") {
157新增: if (!canSend(expected, payload.focus)) return false;
158新增: if (["navigate","back","forward","reload"].includes(payload.type)) homeNotice = "";
159新增: if (payload.type !== "scroll") cancelScroll();
160新增: cancelRead();
161新增: const current = generation;
162新增: const valid = () => alive && visible && !paused && current === generation;
163新增: writing = true; writeType = payload.type;
164新增: if (operation === "resize") awaitingResizeFrame = true;
165新增: publish({frame, busy:true});
166新增: let feedback = false;
167新增: try {
168新增: const body = {...payload, document:expected.document};
169新增: if (actionFrame) body.return_frame = true;
170新增: const result = await request(base + "/action", {body, signal:lifetime.signal});
171新增: if (!valid()) return false;
172新增: if (actionFrame && result?.image) {
173新增: feedback = await decodeFrame(result, valid) !== null;
174新增: } else {
175新增: if (result?.id !== id) throw new Error("主机未确认这次操作,请重新读取画面。");
176新增: frame = null;
177新增: }
178新增: return valid();
179新增: } catch (error) {
180新增: if (valid()) failure(error, operation);
181新增: return false;
182新增: } finally {
183新增: writing = false; writeType = "";
184新增: if (alive && visible && !paused) {
185新增: if (feedback && valid()) finishFrame(true, true);
186新增: else void readFrame();
187新增: }
188新增: }
189新增: }
190新增: function flushScroll() {
191新增: clearTimeout(scrollTimer); scrollTimer = null;
192新增: if (!queuedScroll || writing || !frame || paused || !alive || !visible) return;
193新增: const next = queuedScroll;
194新增: if (!sameSurface(next.expected, frame)) { cancelScroll(); return; }
195新增: const dx = clamp(next.dx, -3200, 3200), dy = clamp(next.dy, -3200, 3200);
196新增: next.dx -= dx; next.dy -= dy;
197新增: if (!next.dx && !next.dy) queuedScroll = null;
198新增: void send({type:"scroll", x:next.x, y:next.y, dx, dy}, frame);
199新增: }
200新增: function scroll(expected, {x,y,dx,dy}) {
201新增: if (desktop || !alive || !visible || paused || !opened || (!dx && !dy) ||
202新增: (writing && writeType !== "scroll") || (frame && !sameSurface(expected, frame))) return;
203新增: if (!queuedScroll || queuedScroll.x !== x || queuedScroll.y !== y || !sameSurface(queuedScroll.expected, expected)) {
204新增: queuedScroll = {expected, x, y, dx:0, dy:0};
205新增: }
206新增: queuedScroll.dx += dx; queuedScroll.dy += dy;
207新增: if (!queuedScroll.dx && !queuedScroll.dy) { cancelScroll(); return; }
208新增: // Coalesce moves within one display tick. Ongoing writes drain the still
209新增: // unsent movement once their next authenticated frame is available.
210新增: if (!scrollTimer) scrollTimer = setTimeout(() => {scrollTimer = null; flushScroll();}, 16);
211新增: }
212新增: function resize() {
213新增: if (!frame || !alive || !visible || writing || paused) return;
214新增: const size = displaySize();
215新增: if (needsResize(size)) {
216新增: void send({type: "resize", ...size}, frame, "resize");
217新增: }
218新增: }
219新增: async function open() {
220新增: try {
221新增: const body = {id, ...viewportSize(stage)};
222新增: if (tool === "browser" && initialURL) body.url = initialURL;
223新增: if (tool === "claude") body.url = "https://claude.ai/";
224新增: const result = await request("/open", {body});
225新增: if (result?.id !== id) throw new Error("主机未确认这次画面连接。");
226新增: if (tool === "browser" && typeof result.home_notice === "string") homeNotice = result.home_notice;
227新增: actionFrame = !desktop && result.action_frame === true;
228新增: opened = true; mayExist = true;
229新增: void readFrame();
230新增: } catch (error) {
231新增: mayExist = !error.status || error.status >= 500;
232新增: if (alive) failure(error, "open");
233新增: } finally {
234新增: opening = false;
235新增: if (!alive) void closeRemote();
236新增: }
237新增: }
238新增: const observer = new ResizeObserver(() => {
239新增: // Rotation/keyboard animations can report several intermediate sizes.
240新增: clearTimeout(resizeTimer);
241新增: resizeTimer = setTimeout(resize, 160);
242新增: });
243新增: let resizeTimer;
244新增: observer.observe(stage);
245新增: if (start) {
246新增: void open();
247新增: } else {
248新增: // History navigation or a page reload resumes the known session by read.
249新增: // A new host browser always requires another explicit open gesture.
250新增: opened = true; opening = false; mayExist = true;
251新增: void readFrame();
252新增: }
253新增: return {
254新增: send, canSend, scroll, cancelScroll,
255新增: async navigate(url) {
256新增: if (!alive || !visible || !opened || paused) throw new Error("请先恢复远程画面,再前往网址。");
257新增: if (awaitingResizeFrame && !pendingAddress) {
258新增: return new Promise(resolve => {pendingAddress = {url, resolve};});
259新增: }
260新增: if (writing || !frame || pendingAddress) throw new Error("上一项操作尚未完成,请稍后再次前往。");
261新增: return send({type: "navigate", url}, frame);
262新增: },
263新增: offline() {
264新增: if (!alive) return;
265新增: generation++; cancelRead(); clearTimeout(resizeTimer);
266新增: failure(new Error("网络已断开,恢复后请重新读取画面。"), writing && writeType !== "resize" ? "action" : "frame");
267新增: },
268新增: refresh() {
269新增: if (!opened || !alive || !visible) return;
270新增: paused = false; waitingSince = 0;
271新增: publish({});
272新增: void readFrame();
273新增: },
274新增: visibility(active) {
275新增: if (active === visible) return;
276新增: visible = active;
277新增: if (!visible) {
278新增: generation++; cancelScroll(); discardAddress();
279新增: cancelRead(); clearTimeout(resizeTimer); frame = null;
280新增: if (alive) update({});
281新增: } else if (alive) {
282新增: if (!opened && !opening) publish({error: "远程画面未连接。", reopen: true});
283新增: else if (paused) publish({error: "请重新读取远程画面。", reopen: !opened});
284新增: else void readFrame();
285新增: }
286新增: },
287新增: close() {
288新增: if (!alive) return;
289新增: alive = false; generation++; cancelScroll();
290新增: discardAddress();
291新增: cancelRead(); clearTimeout(resizeTimer); observer.disconnect();
292新增: frame = null;
293新增: lifetime.abort();
294新增: // If opening is still in flight, its finally sends close after the
295新增: // server has processed open. An early close could miss the new session.
296新增: if (!opening) void closeRemote();
297新增: },
298新增: };
299新增:}
新增ui/src/mobile-cli/device-navigation.mjs+11 −0看文件
@@ -0,0 +1,11 @@
1新增:export function deviceCommand(action, fields = {}) {
2新增: const message = { action, ...fields };
3新增: if (window.webkit?.messageHandlers?.cageDevices) {
4新增: window.webkit.messageHandlers.cageDevices.postMessage(message);
5新增: return true;
6新增: } else if (window.CageDevices?.postMessage) {
7新增: window.CageDevices.postMessage(JSON.stringify(message));
8新增: return true;
9新增: }
10新增: return false;
11新增:}
新增ui/src/mobile-cli/inline-select.jsx+95 −0看文件
@@ -0,0 +1,95 @@
1新增:import React, { useEffect, useId, useRef, useState } from "react";
2新增:import { Check, ChevronDown } from "lucide-react";
3新增:
4新增:// Options follow the trigger in normal flow and keep the combobox focused.
5新增:export function InlineSelect({ label, value, options, onChange, onLongPress, footer, disabled, icon }) {
6新增: const id = useId();
7新增: const root = useRef(null);
8新增: const trigger = useRef(null);
9新增: const hold = useRef(null);
10新增: const held = useRef(false);
11新增: const origin = useRef(null);
12新增: const [open, setOpen] = useState(false);
13新增: const [cursor, setCursor] = useState(value);
14新增: const selected = options.find(item => item.value === value);
15新增: const visible = open && !disabled;
16新增: const cancelHold = () => { clearTimeout(hold.current); hold.current = null; };
17新增: useEffect(() => {
18新增: if (!visible) return;
19新增: const outside = event => { if (!root.current.contains(event.target)) setOpen(false); };
20新增: // Let the outside click reach its target before the inline list reflows.
21新增: document.addEventListener("click", outside, true);
22新增: return () => document.removeEventListener("click", outside, true);
23新增: }, [visible]);
24新增: useEffect(() => () => clearTimeout(hold.current), []);
25新增: const choose = item => {
26新增: setOpen(false);
27新增: trigger.current.focus();
28新增: onChange(item.value);
29新增: };
30新增: const requestDisconnect = item => {
31新增: if (!onLongPress) return;
32新增: held.current = true;
33新增: setOpen(false);
34新增: onLongPress(item.value);
35新增: };
36新增: const press = (event, item) => {
37新增: cancelHold();
38新增: held.current = false;
39新增: origin.current = { x: event.clientX, y: event.clientY };
40新增: if (onLongPress && event.button === 0) hold.current = setTimeout(() => requestDisconnect(item), 550);
41新增: };
42新增: const keys = event => {
43新增: if (event.nativeEvent.isComposing) return;
44新增: const index = Math.max(0, options.findIndex(item => item.value === cursor));
45新增: if (event.key === "Escape") {event.preventDefault(); setOpen(false);}
46新增: else if (event.key === "Tab") setOpen(false);
47新增: else if (["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) {
48新增: event.preventDefault();
49新增: const next = event.key === "Home" ? 0 : event.key === "End" ? options.length - 1
50新增: : Math.max(0, Math.min(options.length - 1, index + (visible ? (event.key === "ArrowUp" ? -1 : 1) : 0)));
51新增: setCursor(options[next]?.value); setOpen(true);
52新增: } else if (event.key === "Enter" || event.key === " ") {
53新增: event.preventDefault();
54新增: if (visible) {const item = options.find(item => item.value === cursor); if (item) choose(item);}
55新增: else {setCursor(value); setOpen(true);}
56新增: } else if (onLongPress && event.key === "F10" && event.shiftKey) {
57新增: event.preventDefault();
58新增: const item = options.find(item => item.value === (visible ? cursor : value));
59新增: if (item) requestDisconnect(item);
60新增: }
61新增: };
62新增: const pointerHandlers = item => ({
63新增: onPointerDown: event => press(event, item),
64新增: onPointerUp: cancelHold,
65新增: onPointerCancel: cancelHold,
66新增: onPointerLeave: cancelHold,
67新增: onPointerMove: event => {
68新增: if (origin.current && Math.hypot(event.clientX - origin.current.x, event.clientY - origin.current.y) > 10) cancelHold();
69新增: },
70新增: onContextMenu: event => {
71新增: if (onLongPress) {event.preventDefault(); cancelHold(); if (!held.current) requestDisconnect(item);}
72新增: },
73新增: });
74新增: return <div className="inline-select" ref={root}>
75新增: <button type="button" className="inline-select-trigger" ref={trigger} role="combobox" aria-label={label}
76新增: aria-haspopup="listbox" aria-expanded={visible} aria-controls={visible ? id : undefined}
77新增: aria-activedescendant={visible ? id + "-" + options.findIndex(item => item.value === cursor) : undefined}
78新增: aria-describedby={footer ? id + "-hint" : undefined} disabled={disabled} onKeyDown={keys}
79新增: {...(selected ? pointerHandlers(selected) : {})}
80新增: onClick={() => {if (held.current) {held.current = false; return;} setCursor(value); setOpen(!visible);}}>
81新增: {icon}<span>{selected?.label || label}</span><ChevronDown size={14} aria-hidden="true" />
82新增: </button>
83新增: {visible && <div className="inline-select-popover">
84新增: <div className="inline-select-options" role="listbox" id={id} aria-label={label + "选项"}>
85新增: {options.map((item, index) => <div key={item.value} role="option" id={id + "-" + index}
86新增: aria-selected={item.value === value} data-active={item.value === cursor || undefined}
87新增: {...pointerHandlers(item)} onMouseDown={event => event.preventDefault()}
88新增: onClick={() => {if (held.current) {held.current = false; return;} choose(item);}}>
89新增: <span>{item.optionLabel || item.label}</span>{item.value === value && <Check size={15} aria-hidden="true" />}
90新增: </div>)}
91新增: </div>
92新增: {footer && <p className="inline-select-hint" id={id + "-hint"}>{footer}</p>}
93新增: </div>}
94新增: </div>;
95新增:}
新增ui/src/mobile-cli/main.jsx+582 −0看文件

改动太大,不在线显示。

新增ui/src/mobile-cli/mobile.css+209 −0看文件

改动太大,不在线显示。

新增ui/src/mobile-cli/phone-favorites.jsx+118 −0看文件

改动太大,不在线显示。

新增ui/src/mobile-cli/remote-browser.css+45 −0看文件

改动太大,不在线显示。

新增ui/src/mobile-cli/remote-browser.jsx+286 −0看文件

改动太大,不在线显示。

新增ui/src/mobile-cli/session-recovery.mjs+42 −0看文件

改动太大,不在线显示。

新增ui/src/mobile-cli/session-row.jsx+94 −0看文件

改动太大,不在线显示。

新增ui/src/mobile-cli/transcript-media.jsx+156 −0看文件

改动太大,不在线显示。

新增ui/src/mobile-cli/transcript.css+248 −0看文件

改动太大,不在线显示。

新增ui/src/mobile-cli/transcript.jsx+304 −0看文件

改动太大,不在线显示。

新增ui/src/mobile-cli/transport.mjs+47 −0看文件

改动太大,不在线显示。

新增ui/src/mobile-cli/workspace-drawer.jsx+98 −0看文件

改动太大,不在线显示。

新增ui/src/mobile-pair-settings.jsx+238 −0看文件

改动太大,不在线显示。

新增ui/src/mobile-session-recovery.test.mjs+52 −0看文件

改动太大,不在线显示。

修改ui/src/modal.jsx+35 −4看文件

改动太大,不在线显示。

修改ui/src/pane-headers.jsx+96 −70看文件

改动太大,不在线显示。

修改ui/src/password-vault.jsx+4 −3看文件

改动太大,不在线显示。

修改ui/src/project-dialog.jsx+76 −12看文件

改动太大,不在线显示。

修改ui/src/proxy-settings.jsx+59 −60看文件

改动太大,不在线显示。

新增ui/src/proxy-yaml-input.jsx+210 −0看文件

改动太大,不在线显示。

修改ui/src/proxy.css+124 −0看文件

改动太大,不在线显示。

修改ui/src/remote-display.mjs+9 −7看文件

改动太大,不在线显示。

修改ui/src/remote-display.test.mjs+16 −0看文件

改动太大,不在线显示。

修改ui/src/remote-input.js+155 −77看文件

改动太大,不在线显示。

修改ui/src/remote-input.test.mjs+153 −6看文件

改动太大,不在线显示。

修改ui/src/resources.jsx+48 −16看文件

改动太大,不在线显示。

新增ui/src/safety-message.jsx+15 −0看文件

改动太大,不在线显示。

修改ui/src/safety-state.mjs+4 −0看文件

改动太大,不在线显示。

修改ui/src/safety-state.test.mjs+13 −0看文件

改动太大,不在线显示。

修改ui/src/safety.jsx+8 −2看文件

改动太大,不在线显示。

新增ui/src/session-account.css+8 −0看文件

改动太大,不在线显示。

新增ui/src/session-account.jsx+70 −0看文件

改动太大,不在线显示。

新增ui/src/session-order.mjs+25 −0看文件

改动太大,不在线显示。

新增ui/src/session-order.test.mjs+28 −0看文件

改动太大,不在线显示。

修改ui/src/settings.jsx+33 −25看文件

改动太大,不在线显示。

修改ui/src/setup-progress.jsx+6 −3看文件

改动太大,不在线显示。

新增ui/src/shared-clipboard.mjs+183 −0看文件

改动太大,不在线显示。

新增ui/src/shared-clipboard.test.mjs+307 −0看文件

改动太大,不在线显示。

修改ui/src/style.css+381 −34看文件

改动太大,不在线显示。

新增ui/src/tailscale.css+19 −0看文件

改动太大,不在线显示。

新增ui/src/tailscale.jsx+94 −0看文件

改动太大,不在线显示。

修改ui/src/views.jsx+122 −26看文件

改动太大,不在线显示。

修改ui/src/workspace-sidebar.jsx+69 −23看文件

改动太大,不在线显示。

修改ui/src/workspace-state.mjs+18 −5看文件

改动太大,不在线显示。

修改ui/src/workspace-tabs.jsx+32 −16看文件

改动太大,不在线显示。

新增ui/vendor/novnc/core/cage-browser-display.js+57 −0看文件

改动太大,不在线显示。

修改ui/vendor/novnc/core/rfb.js+7 −1看文件

改动太大,不在线显示。

修改ui/vendor/novnc/core/util/browser.js+10 −3看文件

改动太大,不在线显示。

修改ui/vite.config.js+5 −1看文件

改动太大,不在线显示。