提交记录修改.github/workflows/linux-build.yml+1 −0看文件
修改.github/workflows/macos-build.yml+2 −1看文件
修改.gitignore+1 −0看文件
修改AGENTS.md+8 −0看文件
修改CONTRIBUTING.md+2 −0看文件
修改VERSION+1 −1看文件
修改desktop/Cage.swift+1 −0看文件
修改desktop/UpdateInstaller.swift+1 −0看文件
修改desktop/Updates.swift+14 −2看文件
修改desktop/UpdatesTests.swift+45 −1看文件
修改desktop/windows.tests/Program.cs+9 −1看文件
修改docs/README.md+2 −0看文件
新增docs/design/password-vault.md+52 −0看文件
修改docs/design/workbench.md+42 −11看文件
修改docs/getting-started.md+27 −7看文件
新增docs/research/2026-11-03-windows-privacy-guard-comparison.md+56 −0看文件
新增docs/research/2026-11-04-claude-account-pool.md+31 −0看文件
新增docs/research/2026-11-04-notarization-upload.md+60 −0看文件
新增docs/research/2026-11-04-windows-code-signing.md+45 −0看文件
修改docs/troubleshooting.md+8 −0看文件
修改internal/cage/browser-agent.mjs+185 −7看文件
新增internal/cage/browser-clipboard.mjs+592 −0看文件
新增internal/cage/browser-clipboard.test.mjs+207 −0看文件
新增internal/cage/browser-login.mjs+53 −0看文件
新增internal/cage/browser-login.test.mjs+29 −0看文件
新增internal/cage/browser-vault.mjs+200 −0看文件
新增internal/cage/claude-account.py+413 −0看文件
新增internal/cage/claude-account.test.py+253 −0看文件
修改internal/cage/claude_desktop.go+5 −1看文件
修改internal/cage/claude_desktop_test.go+14 −11看文件
修改internal/cage/guest-open.sh+17 −6看文件
修改internal/cage/guest-services.sh+4 −0看文件
修改internal/cage/guest.go+42 −2看文件
新增internal/cage/split-extension/control.html+1 −0看文件
新增internal/cage/split-extension/control.js+86 −0看文件
新增internal/cage/split-extension/manifest.json+6 −0看文件
修改internal/workbench/account.go+6 −0看文件
修改internal/workbench/account_store.go+2 −0看文件
新增internal/workbench/browser_copy_test.go+44 −0看文件
修改internal/workbench/browser_http.go+1 −1看文件
修改internal/workbench/browser_service.go+5 −0看文件
修改internal/workbench/browser_workspaces.go+7 −1看文件
修改internal/workbench/browser_workspaces_test.go+15 −1看文件
新增internal/workbench/claude_accounts.go+522 −0看文件
新增internal/workbench/claude_accounts_discovery.go+239 −0看文件
新增internal/workbench/claude_accounts_discovery_test.go+323 −0看文件
新增internal/workbench/claude_accounts_http.go+364 −0看文件
新增internal/workbench/claude_accounts_test.go+262 −0看文件
新增internal/workbench/claude_accounts_usage.go+296 −0看文件
新增internal/workbench/claude_accounts_usage_test.go+359 −0看文件
修改internal/workbench/claude_terminal_test.go+97 −0看文件
修改internal/workbench/server.go+6 −0看文件
修改internal/workbench/terminal_service.go+171 −14看文件
修改internal/workbench/terminal_service_test.go+4 −0看文件
修改internal/workbench/terminal_session.go+35 −17看文件
新增internal/workbench/vault_http.go+240 −0看文件
新增internal/workbench/vault_store.go+180 −0看文件
新增internal/workbench/vault_test.go+193 −0看文件
新增promo/README.md+37 −0看文件
新增promo/index.html+591 −0看文件
新增promo/package-lock.json+1120 −0看文件
新增promo/package.json+15 −0看文件
新增promo/promo.js+679 −0看文件
新增promo/render.mjs+158 −0看文件
新增promo/soundtrack.mjs+302 −0看文件
新增promo/timeline.js+99 −0看文件
新增scripts/browser-clipboard-smoke.mjs+319 −0看文件
修改scripts/browser-controls-smoke.mjs+5 −3看文件
新增scripts/browser-metadata-smoke.mjs+295 −0看文件
新增scripts/browser-vault-smoke.mjs+107 −0看文件
修改scripts/ci-windows-build.ps1+1 −0看文件
新增scripts/favicon-extension-smoke.mjs+145 −0看文件
新增scripts/personal-data-fixture.mjs+53 −0看文件
修改scripts/test-linux-install.sh+10 −3看文件
修改scripts/test-windows-install.ps1+20 −10看文件
新增scripts/vault-controller-smoke.mjs+84 −0看文件
新增scripts/vault-service-smoke.mjs+85 −0看文件
修改ui/package-lock.json+2 −2看文件
修改ui/package.json+1 −1看文件
修改ui/scripts/account-device-smoke.mjs+3 −3看文件
修改ui/scripts/account-smoke.mjs+31 −4看文件
修改ui/scripts/appearance-smoke.mjs+3 −2看文件
修改ui/scripts/browser-chrome-smoke.mjs+11 −5看文件
新增ui/scripts/browser-metadata-smoke.mjs+112 −0看文件
修改ui/scripts/builtin-theme-smoke.mjs+11 −9看文件
新增ui/scripts/claude-accounts-smoke.mjs+415 −0看文件
修改ui/scripts/claude-desktop-smoke.mjs+4 −4看文件
修改ui/scripts/desktop-focus-smoke.mjs+2 −1看文件
修改ui/scripts/display-resolution-smoke.mjs+27 −8看文件
修改ui/scripts/environment-smoke.mjs+1 −1看文件
修改ui/scripts/manual-region-smoke.mjs+5 −5看文件
新增ui/scripts/password-vault-smoke.mjs+135 −0看文件
修改ui/scripts/recovery-ui-smoke.mjs+1 −1看文件
修改ui/scripts/rfb-wire-fixture.mjs+38 −2看文件
新增ui/scripts/split-tabs-smoke.mjs+99 −0看文件
新增ui/scripts/terminal-copy-smoke.mjs+75 −0看文件
修改ui/scripts/theme-smoke.mjs+6 −7看文件
修改ui/scripts/workbench-fixture.mjs+10 −1看文件
修改ui/scripts/workbench-smoke.mjs+45 −12看文件
修改ui/src/account.css+12 −13看文件
修改ui/src/account.jsx+20 −20看文件
修改ui/src/appearance-settings.jsx+30 −33看文件
修改ui/src/appearance.css+3 −5看文件
修改ui/src/browser-favorites.jsx+12 −11看文件
新增ui/src/claude-account-crab.svg+4 −0看文件
新增ui/src/claude-accounts.css+227 −0看文件
新增ui/src/claude-accounts.jsx+361 −0看文件
修改ui/src/claude-desktop.css+22 −6看文件
修改ui/src/claude-desktop.jsx+4 −3看文件
修改ui/src/exit-policy.jsx+11 −10看文件
新增ui/src/inline-select.css+46 −0看文件
新增ui/src/inline-select.jsx+196 −0看文件
修改ui/src/main.jsx+261 −354看文件
新增ui/src/pane-headers.jsx+242 −0看文件
新增ui/src/password-vault.css+32 −0看文件
新增ui/src/password-vault.jsx+162 −0看文件
修改ui/src/proxy-settings.jsx+14 −11看文件
修改ui/src/proxy.css+2 −2看文件
修改ui/src/remote-display.mjs+2 −2看文件
修改ui/src/remote-display.test.mjs+1 −0看文件
修改ui/src/remote-input.js+42 −2看文件
修改ui/src/remote-input.test.mjs+89 −4看文件
修改ui/src/settings.jsx+35 −16看文件
修改ui/src/style.css+134 −88看文件
修改ui/src/terminal-menu.jsx+4 −19看文件
修改ui/src/views.jsx+46 −23看文件
修改ui/src/workspace-sidebar.jsx+20 −28看文件
修改ui/src/workspace-state.mjs+24 −2看文件
修改ui/src/workspace-tabs.jsx+118 −106看文件
修改www/package-lock.json+2 −2看文件
修改www/package.json+1 −1看文件
| @@ -70,6 +70,7 @@ jobs: | ||
| 70 | 70 | bash scripts/package-linux.sh --skip-build |
| 71 | 71 | npm test --prefix ui |
| 72 | 72 | npm run --prefix ui lint |
| 73 | 新增: node --test internal/cage/browser-clipboard.test.mjs | |
| 73 | 74 | - name: Linux executable tests as an ordinary user |
| 74 | 75 | run: | |
| 75 | 76 | chown -R cage:cage "$GITHUB_WORKSPACE" |
| @@ -62,7 +62,8 @@ jobs: | ||
| 62 | 62 | run: | |
| 63 | 63 | npm run --prefix ui lint |
| 64 | 64 | npm test --prefix ui |
| 65 | 删除: node --test internal/cage/clipboard.test.cjs internal/cage/browser-audit.test.mjs internal/cage/browser-downloads.test.mjs internal/cage/browser-uploads.test.mjs | |
| 65 | 新增: node --test internal/cage/clipboard.test.cjs internal/cage/browser-audit.test.mjs internal/cage/browser-downloads.test.mjs internal/cage/browser-uploads.test.mjs internal/cage/browser-login.test.mjs internal/cage/browser-clipboard.test.mjs | |
| 66 | 新增: uv run internal/cage/claude-account.test.py | |
| 66 | 67 | uv run internal/cage/save-download.test.py |
| 67 | 68 | uv run internal/cage/editor-migrate.test.py |
| 68 | 69 | - name: Go tests and vet |
| @@ -24,3 +24,4 @@ dist | ||
| 24 | 24 | *.p8 |
| 25 | 25 | *.p12 |
| 26 | 26 | *.keychain-db |
| 27 | 新增:/promo/out/ | |
| @@ -6,6 +6,14 @@ | ||
| 6 | 6 | - 修改原生桥、启动与退出、权限、快捷键、更新或打包流程时,核对三个平台的对应实现。平台专属代码按实际需要修改,共用代码应继续兼容三个平台。 |
| 7 | 7 | - 同步维护受影响的说明与构建配置,按改动影响执行相应平台验证。无法实测的项目明确记录;不能把单平台通过写成三平台通过,也不能默默遗漏其他平台。 |
| 8 | 8 | |
| 9 | 新增:## 个人数据保留 | |
| 10 | 新增: | |
| 11 | 新增:- 安装、重装、更新、失败回滚及卸载仅管理应用文件,保留账户、收藏、配置、历史、登录凭据、项目与持久虚拟机磁盘;不得通过重建账户或初始化个人目录解决更新问题。 | |
| 12 | 新增:- 默认数据目录固定为用户主目录下的 `.claude-cage`,不得随版本号、安装位置或构建目录变化。显式指定配置路径时,启动与更新助手应传递同一个绝对路径。 | |
| 13 | 新增:- 开发和安装测试使用各自独立的临时目录,不得把用户正在使用的配置目录当作可清理的测试数据。目录名包含 `qa` 或 `test` 不能作为删除依据。 | |
| 14 | 新增:- 迁移个人目录前确认相关后台和虚拟机已停止,保留可恢复的完整备份;核对账户、收藏、持久磁盘及依赖旧路径的文件。 | |
| 15 | 新增:- 涉及安装或更新的改动,使用隔离数据验证安装、更新失败、重装与卸载后的数据保留;macOS 同时验证回滚。各平台未实测的范围必须说明。 | |
| 16 | 新增: | |
| 9 | 17 | ## 版本与发布 |
| 10 | 18 | |
| 11 | 19 | - 默认只完成用户要求的修改、验证和交付。完成开发、构建测试包、提交或推送代码,都不自动授权升级版本号或发版。 |
| @@ -73,6 +73,8 @@ go test github.com/containers/gvisor-tap-vsock/pkg/services/dns \ | ||
| 73 | 73 | |
| 74 | 74 | 修改浏览器启动或控制逻辑时,在 Linux 客机的独立 X 显示中运行 `DISPLAY=:183 node scripts/browser-controls-smoke.mjs`。该检查使用临时配置和真实控制器,验证人工浏览标记、标签与导航、重启后的页面及 Cookie 恢复,并检查未认证请求和跨来源请求仍被拒绝。 |
| 75 | 75 | |
| 76 | 新增:修改网站图标或网页复制时,运行 `node --test internal/cage/browser-clipboard.test.mjs`、`node scripts/browser-clipboard-smoke.mjs`、`node scripts/favicon-extension-smoke.mjs` 和 `node scripts/browser-metadata-smoke.mjs`。后两项通过 `CAGE_TEST_BROWSER_PATH` 指定支持扩展的 Chromium,复制脚本使用隔离 headless 剪贴板。生产控制器测试只适配路径、监听端口和 headless 模式,完整 Linux 客机会话仍需上述独立显示测试。前端开发服务启动后,运行 `node ui/scripts/browser-metadata-smoke.mjs` 验证图标、复制事件、RFB 消息和焦点隔离;该脚本用记录替身接收原生剪贴板写入。Playwright 模块与前端地址可分别通过 `CAGE_PLAYWRIGHT_MODULE`、`CAGE_UI_URL` 指定。 | |
| 77 | 新增: | |
| 76 | 78 | 修改更新或恢复界面时,运行 `node ui/scripts/recovery-ui-smoke.mjs`;修改画面可见性时,运行 `node ui/scripts/remote-visibility-smoke.mjs`。两者需要可用的 Playwright 和已启动的前端开发服务,可通过 `CAGE_UI_URL` 指定地址;测试使用隔离接口,后者还使用真实 RFB 握手与帧验证停止和恢复,不连接日常 VM。修改原生更新流程时运行 `bash scripts/test-app-updates.sh`,正式签名、公证及真实安装仍须单独验收。组件清单、固定工具安装器和网络续租回归已包含在上述 Go 包测试中,无需重复执行一套独立命令。 |
| 77 | 79 | |
| 78 | 80 | 修改上游源码时,保持 `patches/` 与 `third_party/` 一致,并按 `patches/README.md` 核对同步方式。UI 改动需要在实际 App 中验证状态、失败恢复和关键交互;编译通过不能证明登录、联网或用户操作已成功。 |
| @@ -1 +1 @@ | ||
| 1 | 删除:0.1.4-alpha | |
| 1 | 新增:0.1.5-alpha | |
| @@ -39,6 +39,7 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga | ||
| 39 | 39 | } |
| 40 | 40 | |
| 41 | 41 | static func main() { |
| 42 | 新增: CageProfile.pinEnvironment() | |
| 42 | 43 | NSSetUncaughtExceptionHandler { exception in CageDiagnostics.record("Uncaught native exception: \(exception.name.rawValue): \(exception.reason ?? "")\n\(exception.callStackSymbols.joined(separator: "\n"))") } |
| 43 | 44 | let app = NSApplication.shared |
| 44 | 45 | let delegate = CageApp() |
| @@ -10,6 +10,7 @@ final class CageUpdateInstaller: NSObject, NSApplicationDelegate { | ||
| 10 | 10 | private var originalVersion = "" |
| 11 | 11 | |
| 12 | 12 | static func main() { |
| 13 | 新增: CageProfile.pinEnvironment() | |
| 13 | 14 | let app = NSApplication.shared |
| 14 | 15 | let delegate = CageUpdateInstaller(); app.delegate = delegate |
| 15 | 16 | app.setActivationPolicy(.accessory) |
| @@ -5,6 +5,19 @@ import Darwin | ||
| 5 | 5 | |
| 6 | 6 | let cageUpdateBundleID = "io.github.lee-xeo.claude-cage" |
| 7 | 7 | |
| 8 | 新增:enum CageProfile { | |
| 9 | 新增: static func configURL() -> URL { | |
| 10 | 新增: if let path = ProcessInfo.processInfo.environment["CLAUDE_CAGE_CONFIG"], !path.isEmpty { | |
| 11 | 新增: return URL(fileURLWithPath: path).standardizedFileURL | |
| 12 | 新增: } | |
| 13 | 新增: return FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".claude-cage/config.json") | |
| 14 | 新增: } | |
| 15 | 新增: | |
| 16 | 新增: // Every helper and relaunched app inherits the same absolute profile, even | |
| 17 | 新增: // when its working directory differs from the original launch directory. | |
| 18 | 新增: static func pinEnvironment() { setenv("CLAUDE_CAGE_CONFIG", configURL().path, 1) } | |
| 19 | 新增:} | |
| 20 | 新增: | |
| 8 | 21 | final class CageUpdateValidation { |
| 9 | 22 | private let lock = NSLock() |
| 10 | 23 | private let completion = DispatchGroup() |
| @@ -245,8 +258,7 @@ final class CageAppUpdater { | ||
| 245 | 258 | init(bundleURL: URL, onChange: @escaping ([String: Any]) -> Void, quit: @escaping () -> Void, reconnect: @escaping () -> Void) { |
| 246 | 259 | self.bundleURL = bundleURL.resolvingSymlinksInPath() |
| 247 | 260 | self.onChange = onChange; self.quit = quit; self.reconnect = reconnect |
| 248 | 删除: let path = ProcessInfo.processInfo.environment["CLAUDE_CAGE_CONFIG"] ?? FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".claude-cage/config.json").path | |
| 249 | 删除: root = URL(fileURLWithPath: path).deletingLastPathComponent().appendingPathComponent("updates", isDirectory: true) | |
| 261 | 新增: root = CageProfile.configURL().deletingLastPathComponent().appendingPathComponent("updates", isDirectory: true) | |
| 250 | 262 | let version = Bundle(url: bundleURL)?.object(forInfoDictionaryKey: "CageVersion") as? String ?? "开发版本" |
| 251 | 263 | state = ["phase": "idle", "currentVersion": version, "message": ""] |
| 252 | 264 | if let data = try? Data(contentsOf: root.appendingPathComponent("last-result.json")), data.count < 16384, |
| @@ -22,6 +22,46 @@ enum UpdatesTests { | ||
| 22 | 22 | let root = FileManager.default.temporaryDirectory.appendingPathComponent("cage-updates-test-" + UUID().uuidString) |
| 23 | 23 | try CageUpdateFiles.privateDirectory(root) |
| 24 | 24 | defer { try? FileManager.default.removeItem(at: root) } |
| 25 | 新增: do { | |
| 26 | 新增: let saved = ProcessInfo.processInfo.environment["CLAUDE_CAGE_CONFIG"] | |
| 27 | 新增: let directory = FileManager.default.currentDirectoryPath | |
| 28 | 新增: defer { | |
| 29 | 新增: _ = FileManager.default.changeCurrentDirectoryPath(directory) | |
| 30 | 新增: if let saved { setenv("CLAUDE_CAGE_CONFIG", saved, 1) } else { unsetenv("CLAUDE_CAGE_CONFIG") } | |
| 31 | 新增: } | |
| 32 | 新增: setenv("CLAUDE_CAGE_CONFIG", "", 1) | |
| 33 | 新增: try expect(CageProfile.configURL() == FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".claude-cage/config.json"), "empty profile agrees with backend default") | |
| 34 | 新增: try expect(FileManager.default.changeCurrentDirectoryPath(root.path), "enter isolated launch directory") | |
| 35 | 新增: let launchDirectory = FileManager.default.currentDirectoryPath | |
| 36 | 新增: setenv("CLAUDE_CAGE_CONFIG", "selected profile/config.json", 1) | |
| 37 | 新增: CageProfile.pinEnvironment() | |
| 38 | 新增: let pinned = CageProfile.configURL() | |
| 39 | 新增: try expect(pinned.path == launchDirectory + "/selected profile/config.json", "relative profile pinned at launch") | |
| 40 | 新增: try expect(FileManager.default.changeCurrentDirectoryPath(directory), "simulate helper working directory") | |
| 41 | 新增: try expect(CageProfile.configURL() == pinned, "helper keeps original profile after cwd changes") | |
| 42 | 新增: let inherited = try CageUpdateFiles.run("/bin/sh", ["-c", "printf '%s' \"$CLAUDE_CAGE_CONFIG\""]) | |
| 43 | 新增: try expect(String(data: inherited, encoding: .utf8) == pinned.path, "actual child process inherits absolute profile") | |
| 44 | 新增: } | |
| 45 | 新增: let personalFiles = [ | |
| 46 | 新增: "account.json", "favorites.json", "projects.json", "appearance.json", "workbench.json", | |
| 47 | 新增: "state/lima/persistent/disk", "webview/data/Local Storage/leveldb/000001.log", | |
| 48 | 新增: "workspace/project.txt" | |
| 49 | 新增: ] | |
| 50 | 新增: let profile = root.appendingPathComponent("profile") | |
| 51 | 新增: var personalData: [String: Data] = [:] | |
| 52 | 新增: for name in personalFiles { | |
| 53 | 新增: let file = profile.appendingPathComponent(name) | |
| 54 | 新增: try CageUpdateFiles.privateDirectory(file.deletingLastPathComponent()) | |
| 55 | 新增: let bytes = Data("Keep \(name): 历史、收藏和登录状态\n\0".utf8) | |
| 56 | 新增: try CageUpdateFiles.write(bytes, to: file) | |
| 57 | 新增: personalData[name] = bytes | |
| 58 | 新增: } | |
| 59 | 新增: func verifyPersonalData() throws { | |
| 60 | 新增: for (name, expected) in personalData { | |
| 61 | 新增: let actual = try Data(contentsOf: profile.appendingPathComponent(name)) | |
| 62 | 新增: try expect(actual == expected, "application replacement or rollback changed personal data: \(name)") | |
| 63 | 新增: } | |
| 64 | 新增: } | |
| 25 | 65 | // Exercise the production lipo invocation against a real Mach-O binary. |
| 26 | 66 | // lipo consumes every argument after -verify_arch as an architecture. |
| 27 | 67 | try CageUpdateFiles.verifyArchitecture(URL(fileURLWithPath: CommandLine.arguments[0])) |
| @@ -46,7 +86,9 @@ enum UpdatesTests { | ||
| 46 | 86 | let marker = try String(contentsOf: $0.appendingPathComponent("marker"), encoding: .utf8) |
| 47 | 87 | try expect(marker == "new", "new content reaches final install path") |
| 48 | 88 | } |
| 89 | 新增: try verifyPersonalData() | |
| 49 | 90 | try CageUpdateFiles.restore(backup: backup, target: old, manager: .default) |
| 91 | 新增: try verifyPersonalData() | |
| 50 | 92 | let restored = try String(contentsOf: old.appendingPathComponent("marker"), encoding: .utf8) |
| 51 | 93 | try expect(restored == "old", "launch failure can restore original") |
| 52 | 94 | try CageUpdateFiles.privateDirectory(next) |
| @@ -56,6 +98,7 @@ enum UpdatesTests { | ||
| 56 | 98 | } |
| 57 | 99 | let rollback = try String(contentsOf: old.appendingPathComponent("marker"), encoding: .utf8) |
| 58 | 100 | try expect(rollback == "old", "failed validation leaves original installed") |
| 101 | 新增: try verifyPersonalData() | |
| 59 | 102 | try CageUpdateFiles.privateDirectory(next) |
| 60 | 103 | try Data("invalid-after-replace".utf8).write(to: next.appendingPathComponent("marker")) |
| 61 | 104 | var replaced = false |
| @@ -70,6 +113,7 @@ enum UpdatesTests { | ||
| 70 | 113 | let retainedBackup = try String(contentsOf: backup.appendingPathComponent("marker"), encoding: .utf8) |
| 71 | 114 | try expect(failedTarget == "invalid-after-replace" && retainedBackup == "old", "double failure must retain the original backup and report the changed target") |
| 72 | 115 | try CageUpdateFiles.restore(backup: backup, target: old, manager: .default) |
| 116 | 新增: try verifyPersonalData() | |
| 73 | 117 | try rejects("unsigned application refused") { _ = try CageUpdateFiles.signingInfo(old, bundle: true) } |
| 74 | 118 | |
| 75 | 119 | // A real child that ignores SIGTERM must not keep cancellation pending. |
| @@ -137,6 +181,6 @@ enum UpdatesTests { | ||
| 137 | 181 | try rejects("real signature tampering refused") { _ = try CageUpdateFiles.signingInfo(tampered, bundle: true, expectedTeam: team) } |
| 138 | 182 | print("PASS: real App architecture and Developer ID signature, wrong publisher, and tampered App checks") |
| 139 | 183 | } |
| 140 | 删除: print("PASS: versions, private files, containment, replacement/double-failure rollback, process cancellation, and temporary image cleanup") | |
| 184 | 新增: print("PASS: absolute profile inheritance, personal data preservation, versions, containment, replacement/double-failure rollback, process cancellation, and temporary image cleanup") | |
| 141 | 185 | } |
| 142 | 186 | } |
| @@ -5,6 +5,7 @@ using Cage.Windows; | ||
| 5 | 5 | if (args is ["prepare-update", "--json", "--stop"]) |
| 6 | 6 | { |
| 7 | 7 | File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "controller-invoked"), Environment.ProcessId.ToString()); |
| 8 | 新增: File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "profile-invoked"), Environment.GetEnvironmentVariable("CLAUDE_CAGE_CONFIG") ?? "missing"); | |
| 8 | 9 | if (File.Exists(Path.Combine(AppContext.BaseDirectory, "broken-backend"))) |
| 9 | 10 | { |
| 10 | 11 | Console.WriteLine("{\"status\":\"failed\"}"); Environment.Exit(7); |
| @@ -44,8 +45,11 @@ Console.WriteLine($"Windows update/bridge policy: {assertions} assertions passed | ||
| 44 | 45 | |
| 45 | 46 | var integration = Path.Combine(Path.GetTempPath(), "cage-recovery-" + Guid.NewGuid()); |
| 46 | 47 | Directory.CreateDirectory(integration); |
| 48 | 新增:var savedProfile = Environment.GetEnvironmentVariable("CLAUDE_CAGE_CONFIG"); | |
| 47 | 49 | try |
| 48 | 50 | { |
| 51 | 新增: var selectedProfile = Path.Combine(integration, "selected profile", "config.json"); | |
| 52 | 新增: Environment.SetEnvironmentVariable("CLAUDE_CAGE_CONFIG", Path.GetRelativePath(Environment.CurrentDirectory, selectedProfile)); | |
| 49 | 53 | var backup = Path.Combine(integration, "old application"); |
| 50 | 54 | var candidate = Path.Combine(integration, "new application"); |
| 51 | 55 | void InstallFixture(string app, bool broken) |
| @@ -62,6 +66,7 @@ try | ||
| 62 | 66 | await UpdateRecovery.PrepareRollback(backup); |
| 63 | 67 | Check(File.Exists(Path.Combine(backup, "resources", "controller-invoked")), "recovery did not execute the old backend"); |
| 64 | 68 | Check(!File.Exists(Path.Combine(candidate, "resources", "controller-invoked")), "recovery executed the broken candidate backend"); |
| 69 | 新增: Check(File.ReadAllText(Path.Combine(backup, "resources", "profile-invoked")) == selectedProfile, "recovery child switched away from the original relative profile"); | |
| 65 | 70 | File.WriteAllText(Path.Combine(backup, "resources", "running-environment"), "still running"); |
| 66 | 71 | var rejected = false; |
| 67 | 72 | try { await UpdateRecovery.PrepareRollback(backup); } catch (IOException) { rejected = true; } |
| @@ -89,4 +94,7 @@ try | ||
| 89 | 94 | } |
| 90 | 95 | Console.WriteLine($"Windows recovery integration: {assertions - 22} assertions passed; actual child process and filesystem failures exercised."); |
| 91 | 96 | } |
| 92 | 删除:finally { Directory.Delete(integration, true); } | |
| 97 | 新增:finally { | |
| 98 | 新增: Environment.SetEnvironmentVariable("CLAUDE_CAGE_CONFIG", savedProfile); | |
| 99 | 新增: Directory.Delete(integration, true); | |
| 100 | 新增:} | |
| @@ -22,6 +22,8 @@ | ||
| 22 | 22 | |---|---| |
| 23 | 23 | | 从源码构建、修改和验证代码 | [参与开发](../CONTRIBUTING.md) | |
| 24 | 24 | | 理解工作台、浏览器与后台的职责 | [工作台设计](design/workbench.md) | |
| 25 | 新增:| 保存网站账号密码,了解本地加密与填充范围 | [使用密码保险箱](getting-started.md#保存网站账号密码) · [密码保险箱设计](design/password-vault.md) | | |
| 26 | 新增:| 将多个订阅用于新建的 Claude Code 终端,了解调度、额度与 Desktop 的适用范围 | [账号面板](design/workbench.md#claude-code-账号面板) · [调研与集成取舍](research/2026-11-04-claude-account-pool.md) | | |
| 25 | 27 | | 评估主机输入法、原位拼音与候选窗跟随 | [原生输入法研究](research/2026-11-04-native-ime.md) | |
| 26 | 28 | | 定位作业、终端、浏览器连接与退出流程的代码 | [控制服务职责](design/control-service.md) | |
| 27 | 29 | | 理解网络检查、暂停与恢复 | [网络检查设计](design/network-checks.md) | |
| @@ -0,0 +1,52 @@ | ||
| 1 | 新增:# 密码保险箱 | |
| 2 | 新增: | |
| 3 | 新增:密码保险箱为 Cage 浏览器保存网站账号密码。用户提交登录表单后,在 Cage 的浏览器工具区确认保存;再次访问同一网站时,展开“密码”,选择账号填入表单,再自行提交登录。保存提示不代表网站已验证密码,用户应先确认登录成功。相同网站和用户名对应一条记录,密码变化时提示更新,同一网站可以保存多个账号。 | |
| 4 | 新增: | |
| 5 | 新增:## 使用与锁定 | |
| 6 | 新增: | |
| 7 | 新增:设置中的“密码保险箱”提供搜索、手动添加、编辑、删除及恢复网站保存提示。虚拟机未启动时仍可管理密码。编辑已有记录时,密码留空表示保留原密码;查看和复制明文均需再次输入 Cage 账户密码。明文显示在 30 秒后、窗口失焦或页面隐藏时关闭。复制使用现有三平台剪贴板桥,复制后的内容由系统剪贴板管理。 | |
| 8 | 新增: | |
| 9 | 新增:保险箱与 Cage 共用解锁状态,包括已启用的记住登录和指纹解锁。手动锁定后,主机拒绝密码库接口,并取消已授权的在途请求。退出账户和控制服务关闭沿用账户锁定流程。每次解锁产生新的浏览器授权标识,上一轮的候选记录与填充请求不能跨解锁继续使用。 | |
| 10 | 新增: | |
| 11 | 新增:浏览器的账号列表在页面内展开并占据布局空间。键盘 Tab 可以移动到账号,Enter 填充,Escape 收起列表并把焦点移回触发按钮。保存提示支持保存、暂不保存和此网站不再提示;拒绝提示的站点可以在设置中恢复。 | |
| 12 | 新增: | |
| 13 | 新增:## 数据归属与保护 | |
| 14 | 新增: | |
| 15 | 新增:主机控制服务拥有密码库,文件为当前配置目录中的 `password-vault.json`,默认位于 `~/.claude-cage`。所有记录及拒绝提示的网站整体使用 AES-256-GCM 加密,随机 nonce,每次保存原子替换文件。使用账户内部密钥通过带用途标识的 HMAC-SHA256 派生保险箱密钥;用户修改 Cage 密码时仍包装同一个账户内部密钥,已有密码库无需重新加密。文件访问权限沿用主机私有文件实现,Windows 使用相应 ACL。 | |
| 16 | 新增: | |
| 17 | 新增:主机按请求解密,事务与账户锁定共用互斥锁,完成后不保留密码库缓存。列表只返回网站、用户名、记录标识与更新时间。查看密码时再次验证不会改变账户解锁周期,也不会重新启用自动登录。解密、格式或权限检查失败时拒绝修改原文件。 | |
| 18 | 新增: | |
| 19 | 新增:密码库文件与 `account.json` 必须一起备份,并保留可用的 Cage 账户密码;单独复制密码库不能恢复账号。安装、更新和卸载保留配置目录,本功能不迁移或清理个人数据。密码库没有云同步、在线找回或独立主密码。 | |
| 20 | 新增: | |
| 21 | 新增:客机浏览器只短期持有用户提交的待保存密码以及本次选择填入的密码。主机不会将密码库文件、完整账号列表或保险箱派生密钥发送给客机。账户内部密钥的既有 Desktop 密钥环用途见[工作台账户设计](workbench.md#本地账户与锁定)。保险箱依赖现有主机与客机的访问边界;它不防止已取得主机账户权限的程序读取运行中数据,也不阻止当前网页读取已填入它的密码。 | |
| 22 | 新增: | |
| 23 | 新增:## 浏览器接入 | |
| 24 | 新增: | |
| 25 | 新增:macOS、Windows、Linux 使用同一份 Go 接口、React 界面及客机 Chromium 模块。原生窗口继续使用已有账户和剪贴板能力,没有新增平台专属密钥库。客机设置 Chromium 的 `PasswordManagerEnabled=false` 策略,关闭原生密码管理器的新增保存;按 Chromium 策略语义,原有密码记录保留且可能继续填充,不自动迁移或删除。客机模块进入现有环境组件指纹,旧环境需要完成组件更新后使用网页保存与填充。 | |
| 26 | 新增: | |
| 27 | 新增:网页表单识别和填充在 Chromium 独立脚本环境中运行,通过私有 CDP 管道连接浏览器控制器。网页主脚本无法直接调用保存绑定。控制器只接受所跟踪顶层框架的绑定事件,且只从活动标签接收可信提交、登录按钮点击或输入框中的 Enter。表单提交前读取本次值,以支持提交后立即跳转的网站。浏览器不会判断服务端登录是否成功。 | |
| 28 | 新增: | |
| 29 | 新增:仅支持 HTTPS 顶层页面。匹配使用完整 origin,包含协议、主机与非默认端口,不跨子域自动共享。填充绑定到所选账号、活动标签和当前文档随机标识;在实际写入输入框前再次检查 origin 与文档标识。导航后旧请求失效,不自动提交。常见的先填邮箱、再填密码页面可以在同 origin 内短期关联用户名;HTTP、iframe、封闭 Shadow DOM、验证码和 Passkey 不在自动识别范围。Claude 账号面板的临时授权上下文沿用其独立生命周期,不参与密码捕获。 | |
| 30 | 新增: | |
| 31 | 新增:主机在已解锁的工作台中每两秒请求浏览器状态,为捕获授予 6.5 秒有效期。断连、关闭工作台或停止刷新后授权到期,客机清除候选;显式锁定同时尝试立即撤销。每个标签最多一条候选,总量最多八条,最长保留两分钟,关闭标签也清除。普通标签列表、事件流和诊断日志不携带密码。密码候选只通过专用认证接口进入主机,给前端的保存提示已移除密码。 | |
| 32 | 新增: | |
| 33 | 新增:## 接口与实现入口 | |
| 34 | 新增: | |
| 35 | 新增:| 接口 | 行为 | | |
| 36 | 新增:|---|---| | |
| 37 | 新增:| `GET /api/vault` | 已解锁账户的记录摘要及拒绝提示列表 | | |
| 38 | 新增:| `POST /api/vault` | `save`、`delete`、`unblock`;`reveal` 额外验证 `account_password` | | |
| 39 | 新增:| `POST /api/vault/browser` | `status`、`save`、`never`、`dismiss`、`fill` | | |
| 40 | 新增:| 客机 `POST /vault` | 现有 Bearer 认证下的短期捕获与定向填充,不向网页开放 | | |
| 41 | 新增: | |
| 42 | 新增:主机实现见 `internal/workbench/vault_store.go`、`vault_http.go`。网页识别与文档校验见 `internal/cage/browser-vault.mjs`。界面见 `ui/src/password-vault.jsx`。原生保存策略依据为 Chromium 的 [PasswordManagerEnabled 定义](https://raw.githubusercontent.com/chromium/chromium/main/components/policy/resources/templates/policy_definitions/PasswordManager/PasswordManagerEnabled.yaml)。协议依据为 Chromium 的 [Page 独立脚本环境](https://chromedevtools.github.io/devtools-protocol/tot/Page/)与 [Runtime 绑定](https://chromedevtools.github.io/devtools-protocol/tot/Runtime/)。 | |
| 43 | 新增: | |
| 44 | 新增:## 验证入口 | |
| 45 | 新增: | |
| 46 | 新增:- `go test ./internal/workbench -run TestVault`:加密、锁定、账户改密、重开、损坏保护、网站规范化、再次验证和接口脱敏。 | |
| 47 | 新增:- `node scripts/browser-vault-smoke.mjs`:真实 Chromium 中的识别、填充、跨站与导航检查。 | |
| 48 | 新增:- `node scripts/vault-controller-smoke.mjs`:隔离 HTTPS 站点通过生产控制器和私有 CDP 管道验证捕获、填充、接口认证及导航与锁定。通过 `CAGE_TEST_BROWSER_PATH` 指定测试 Chromium,仅测试适配器忽略临时站点证书。 | |
| 49 | 新增:- `node ui/scripts/password-vault-smoke.mjs`:设置、保存提示和键盘布局交互。 | |
| 50 | 新增:- `node scripts/vault-service-smoke.mjs`:真实界面连接隔离 Go 服务,验证加密落盘、后台重启及锁定;先构建 `_output/vault-qa/cage`。 | |
| 51 | 新增: | |
| 52 | 新增:浏览器脚本使用 `CAGE_PLAYWRIGHT_MODULE` 指定现有 Playwright 安装。所有测试只使用临时配置和虚构网站,不连接用户的邮箱或个人密码库。平台编译结果与原生系统实测范围分别记录在本地验收报告中。 | |
| @@ -4,7 +4,7 @@ Cage 面向在本机项目中编码的用户。主界面管理本地项目、网 | ||
| 4 | 4 | |
| 5 | 5 | ## 本地账户与锁定 |
| 6 | 6 | |
| 7 | 删除:每份 Cage 配置只有一个本地账户,与同一个持久环境关联。首次使用设置用户名和密码,随后通过密码解锁;左下角显示头像和用户名,菜单提供账户设置、应用设置、锁定与退出账户。头像接受不超过 2 MB 的 PNG/JPEG,在本机居中裁切为 128×128 PNG,资料和密码分别保存。 | |
| 7 | 新增:每份 Cage 配置只有一个本地账户,与同一个持久环境关联。首次使用设置用户名和密码,随后通过密码解锁;左下角显示头像和用户名,菜单提供“设置”“锁定 Cage”和“退出账户”。从该菜单打开设置时默认显示“账户”,可在同一页切换到其他设置分组。头像接受不超过 2 MB 的 PNG/JPEG,在本机居中裁切为 128×128 PNG,资料和密码分别保存。 | |
| 8 | 8 | |
| 9 | 9 | “锁定 Cage”关闭工作台的终端与画面连接,保留后台进程;重新解锁恢复连接。“退出账户”先停止环境,成功后清除驻留解锁材料。停止失败时保留登录状态并报告错误。退出应用清除内存中的解锁材料,后台任务继续运行;启用记住登录后,再次打开可自动进入。锁定不会撤销运行中应用已持有的令牌。 |
| 10 | 10 | |
| @@ -16,24 +16,27 @@ macOS 的“登录与解锁”提供记住登录与 Touch ID 两项开关。首 | ||
| 16 | 16 | |
| 17 | 17 | 每种快捷登录使用独立随机凭据包装同一个内部密钥。原生启动器通过受认证的本机接口交换凭据,网页只获得状态;后端不接受指纹成功的布尔值作为解锁依据。自动登录凭据保存在本机登录钥匙串,访问受应用代码签名控制;指纹凭据存入 Data Protection Keychain 并使用 `biometryCurrentSet`,必须通过系统指纹验证才能读取。指纹变化、取消、钥匙串不可用时保留密码入口。带指纹功能的构建需要匹配应用标识的 Developer ID 描述文件,构建可通过 `CAGE_PROVISIONING_PROFILE` 指定;缺少系统授权时不会改为不受保护的指纹凭据。 |
| 18 | 18 | |
| 19 | 新增:密码保险箱随本地账户解锁和锁定,提供网站密码保存、选择填充与再次验证后的查看和复制。数据归属、浏览器校验及恢复条件见[密码保险箱设计](password-vault.md)。 | |
| 20 | 新增: | |
| 19 | 21 | ## 主界面 |
| 20 | 22 | |
| 21 | 删除:Cage 只使用一个持久环境,VM、账户登录态、开发工具和家目录在所有项目间共享。项目对应实际共享的文件夹,左侧项目列表直接读取控制服务保存的目录,包含默认工作区;每个目录下只列出在该目录创建的终端。目录旁的加号直接新建终端,折叠目录不影响其中的进程。 | |
| 23 | 新增:Cage 只使用一个持久环境,VM、账户登录态、开发工具和家目录在所有项目间共享。项目对应实际共享的文件夹,左侧项目列表直接读取控制服务保存的目录,包含默认工作区;每个目录下只列出在该目录创建的终端。折叠目录不影响其中的终端进程。 | |
| 22 | 24 | |
| 23 | 25 | 浏览器是独立的应用入口,网页使用内容区顶部的横向标签栏,不归属于项目。点击左侧“浏览器”返回仍在运行的浏览页面,顶部加号与 ⌘T 新建网页。文件编辑器页也在顶部标签栏显示,并在标题中标明打开的目录;打开项目与切换终端均不关闭已有网页。终端内容区显示所属目录及终端名称。 |
| 24 | 26 | |
| 27 | 新增:网页标签及标签搜索列表显示 Chromium 已取得的网站图标。客机扩展通过原生图标缓存读取 32×32 PNG,每个图标最多 8192 字符,再随标签状态传给工作台。图标缺失或解码失败时显示地球。图标请求沿用 Chromium 对网页的图片加载策略,页面内路由变化保留图标,网页更换图标后更新显示。 | |
| 28 | 新增: | |
| 25 | 29 | ```text |
| 26 | 30 | ┌──────────────────┬──────────────────────────────────────┐ |
| 27 | 31 | │ Cage │ 网页 A × │ 网页 B × │ 文件 · A × │ + │ |
| 28 | 32 | │ 工作台 ├──────────────────────────────────────┤ |
| 29 | 33 | │ 浏览器 │ ← → ↻ 地址栏 │ |
| 30 | 删除:│ 打开项目 ├──────────────────────────────────────┤ | |
| 31 | 删除:│ 项目文件 │ │ | |
| 34 | 新增:│ 下载 ├──────────────────────────────────────┤ | |
| 32 | 35 | │ │ │ |
| 33 | 36 | │ 项目 + │ 当前工作内容 │ |
| 34 | 删除:│ ▾ 项目 A + │ │ | |
| 37 | 新增:│ ▾ 项目 A ↗ >_ │ │ | |
| 35 | 38 | │ 终端 1 │ │ |
| 36 | 删除:│ ▾ 项目 B + │ │ | |
| 39 | 新增:│ ▾ 项目 B ↗ >_ │ │ | |
| 37 | 40 | │ 终端 2 │ │ |
| 38 | 41 | │ │ │ |
| 39 | 42 | │ 运行状态 ├──────────────────────────────────────┤ |
| @@ -43,14 +46,18 @@ Cage 只使用一个持久环境,VM、账户登录态、开发工具和家目 | ||
| 43 | 46 | |
| 44 | 47 | 未启动时,主界面提供“启动 Cage 环境”,无需选择项目。每份配置只创建和使用一个持久 VM;默认工作区通常为 `~/.claude-cage-workspace`。环境就绪后可直接使用浏览器和终端,再按需打开本地文件夹。重新打开应用继续连接同一环境。 |
| 45 | 48 | |
| 46 | 删除:打开项目时,主机通过已有受目录约束的 SFTP 实现,把用户选定的文件夹动态挂载到当前 VM:macOS 使用同名路径,Windows 的 `C:\Users\name\project` 映射为 `/c/Users/name/project`。项目 A 切换到 B 后,A 的共享目录、终端进程、浏览器和编辑器页保持运行。目录旁的加号始终在对应目录新建终端;终端工具栏在该终端所属目录创建新会话,项目文件入口使用当前选择的目录。明确打开的目录继续保留,并在环境重启时恢复共享。所有项目处于同一环境,可以访问其中已共享的目录、工具和账号。 | |
| 49 | 新增:打开项目时,主机通过已有受目录约束的 SFTP 实现,把用户选定的文件夹动态挂载到当前 VM:macOS 使用同名路径,Windows 的 `C:\Users\name\project` 映射为 `/c/Users/name/project`。项目 A 切换到 B 后,A 的共享目录、终端进程、浏览器和编辑器页保持运行。每个项目行右侧有两个按钮:打开图标在 code-server 中打开该目录,终端图标在该目录新建终端。终端工具栏则在当前终端所属目录创建新会话。明确打开的目录继续保留,并在环境重启时恢复共享。所有项目处于同一环境,可以访问其中已共享的目录、工具和账号。 | |
| 47 | 50 | |
| 48 | 51 | VM 身份固定保存在主机私有的 `environment.json`;最后打开的项目保存在 `workbench.json`,明确打开的目录保存于 `projects.json`。控制服务通过 `/api/status` 的 `projects` 返回完整目录列表,不设最近使用条数限制。Cage 与 Claude Desktop 的项目选择器直接读取同一份 `projects` 列表,支持选择已有项目和明确添加本机目录。`POST /api/projects/open` 由项目系统处理:`add` 表示用户明确添加目录,普通消费者请求只接受已授权目录;`activate` 仅用于保存 Cage 当前项目。接口返回规范化后的主机路径,消费者通过既有映射取得客机路径。终端与编辑器创建请求可携带 `workspace`,只接受默认目录、当前目录及已保存的项目目录;省略时沿用最后打开的项目。前端的目录选择不修改共享授权,也不影响浏览器。首次升级优先保留原有环境的虚拟磁盘;历史其他 VM 不自动删除。项目切换不改变环境身份,也不触发代理探测、网络重检或环境重启。网络与系统配置的修改继续按既有流程验证并重启。 |
| 49 | 52 | |
| 50 | 删除:标签支持重命名、置顶、拖动排序和关闭。浏览器标签通过右键或 Shift+F10 打开操作菜单,终端通过行末菜单管理。重命名只改变显示名称;置顶标签排列在各自列表前方,拖动调整同一列表内部的顺序。名称、置顶与顺序保存在本地。⌘1–9 与 ⌘⇧[ / ] 按当前列表的显示顺序切换:浏览器中切换顶部网页,终端中切换同目录的终端。关闭当前网页后激活相邻浏览器页。刷新后重新连接仍存活的终端与浏览器,已结束的进程不因标签恢复而重新启动。 | |
| 53 | 新增:标签支持重命名、置顶、拖动排序和关闭。浏览器标签通过右键或 Shift+F10 打开操作菜单。鼠标移入侧栏终端行或键盘焦点进入该行时,右侧显示置顶、重命名和删除按钮。重命名只改变显示名称;置顶标签排列在各自列表前方,拖动调整同一列表内部的顺序。名称、置顶与顺序保存在本地。⌘1–9 与 ⌘⇧[ / ] 按当前列表的显示顺序切换:浏览器中切换顶部网页,终端中切换同目录的终端。关闭当前网页后激活相邻浏览器页。刷新后重新连接仍存活的终端与浏览器,已结束的进程不因标签恢复而重新启动。 | |
| 51 | 54 | |
| 52 | 55 | 浏览器标签栏与新建按钮垂直居中,标签总宽度随内容区调整,不显示横向滚动条。空间充足时标签最大宽度为 220px;拥挤时当前标签优先保留标题空间,其他标签平分剩余宽度。极窄标签保留可点击位置和悬停标题,右侧搜索入口可按名称或网址查找所有页面。指针拖动时标签跟随移动,相邻标签实时让位;松手保存顺序,Esc 或指针取消恢复原顺序。置顶和普通标签分别在各自分组内排序。 |
| 53 | 56 | |
| 57 | 新增:打开至少两个标签后,可将顶部的网页或编辑器标签、侧栏的终端标签拖到内容区。左半区或右半区高亮时松手,标签会在该侧打开。拖动时按 Esc 可取消。每一侧保留自己的页眉。网页有标签栏和地址栏,终端页眉显示项目、会话名和会话操作,终端标签统一在侧栏管理。点击某一侧的“退出分屏”可放大该侧并保留两个标签。关闭一侧的标签后,另一侧恢复为单页。 | |
| 58 | 新增: | |
| 59 | 新增:两个网页并排时,客机 Chromium 将原有标签组成原生分屏。两页分别按自己的可用宽度排版,都能直接点击、滚动和输入。拖动两页之间的分隔线可调整宽度。工作台通过一条远程画面连接显示整个浏览器窗口,地址栏、快捷键、输入法和剪贴板操作跟随当前标签。双网页分屏要求客机 Chromium 155 或更高版本,且两个标签能够在同一浏览器配置中打开。网页与终端并排时,浏览器只占自己的一侧。两个终端并排时,各自按面板尺寸调整行列,切换焦点沿用原终端会话。 | |
| 60 | 新增: | |
| 54 | 61 | 地址栏右侧星标与 ⌘D 打开当前网页的收藏编辑框,收藏夹按钮与 ⌘⇧O 打开收藏面板。收藏支持名称、HTTP(S) 地址、单层收藏夹分组、搜索、移动和删除;删除收藏夹将其中的收藏移至未分类。打开收藏通过现有浏览器新建页接口进入 VM,不在主机执行收藏网址。文件编辑器与内部浏览器页面不提供收藏。 |
| 55 | 62 | |
| 56 | 63 | 收藏由主机控制服务保存在当前配置目录的私有 `favorites.json`,Unix 权限为 `0600`,Windows 使用仅当前用户与 SYSTEM 可访问的显式 DACL;所有项目共用,应用和控制服务重启后保留,不与 Chromium 或外部浏览器同步。`GET /api/favorites` 返回 `items` 与 `folders`;`POST /api/favorites` 通过 `save`、`delete`、`save_folder`、`delete_folder` 操作单条记录,沿用工作台认证与来源校验。修改在专用互斥锁下读取最新文件并原子写入,避免并发新增覆盖其他窗口的收藏。保存失败保留编辑输入,读取失败不覆盖原文件。收藏操作不更改 VM、网络或共享目录状态。 |
| @@ -63,18 +70,34 @@ VM 身份固定保存在主机私有的 `environment.json`;最后打开的项 | ||
| 63 | 70 | |
| 64 | 71 | Desktop 使用编码用户 `cage`、独立的 X11 显示 `:78` 与按需启动的 systemd 服务。虚拟屏幕、窗口管理器、会话总线和应用属于同一服务,停止服务时一起回收。现有浏览器保持使用 `cage-browser` 和 `:77`。Desktop 的 VNC 只监听客机私有 Unix socket,经当前环境的 SSH 标准输入输出通道连接工作台,不创建可被自动转发的 TCP 监听端口。工作台沿用认证与来源校验,网页脚本无法调用应用控制接口。浏览器的 `claude://` 回调仅交给正在运行的官方应用;其他外部协议不由该入口执行。系统密钥环保存应用登录状态,由 Cage 使用账户内部密钥自动创建和解锁。Claude 自身的账号登录仍由用户完成。 |
| 65 | 72 | |
| 66 | 删除:项目旁的加号、终端工具栏与新建终端快捷键均打开类型选择框。普通终端提供 shell;Claude 终端在所选项目中新建交互 shell,并运行设置中的启动命令,默认 `claude`。命令支持参数及单行 shell 表达式,仅在客机执行;退出 Claude 后返回 shell。命令保存在私有 `workbench.json` 的 `claude_terminal_command` 字段,留空恢复默认,拒绝换行、NUL 和超过 4096 字节的输入。保存不重启环境,也不修改现有终端;刷新或重连不会重复执行启动命令。 | |
| 73 | 新增:项目行的终端图标、终端工具栏与新建终端快捷键均打开类型选择框。普通终端提供 shell;Claude 终端在所选项目中新建交互 shell,并运行设置中的启动命令,默认 `claude`。命令支持参数及单行 shell 表达式,仅在客机执行;退出 Claude 后返回 shell。命令保存在私有 `workbench.json` 的 `claude_terminal_command` 字段,留空恢复默认,拒绝换行、NUL 和超过 4096 字节的输入。保存不重启环境,也不修改现有终端;刷新或重连不会重复执行启动命令。 | |
| 67 | 74 | |
| 68 | 75 | 浏览器将 `claude://` 链接成功转交给正在运行的 Claude Desktop 后,工作台自动显示 Claude Desktop。转交失败时保持当前页面;该通知只表示应用接收了链接,登录是否成功由 Claude 自身显示。客机打开链接的脚本通过浏览器服务的认证接口 `/desktop-focus` 发送通知,现有浏览器事件流以 `desktopFocus: true` 传递一次切换请求。通知不包含回调链接和登录凭据,不保存在浏览器状态中,重连或普通状态更新不会重新触发切换。三个主机平台共用此链路。 |
| 69 | 76 | |
| 70 | 删除:应用状态与操作由 `/api/claude-desktop`、`/api/claude-desktop/{install,start,stop}` 提供;安装和启动沿用工作台异步任务。`POST /api/terminals` 的 `kind` 可为 `shell` 或 `claude`,省略时保持普通终端行为。原始启动命令不从新建终端请求接收,只读取已保存偏好。 | |
| 77 | 新增:应用状态与操作由 `/api/claude-desktop`、`/api/claude-desktop/{install,start,stop}` 提供。安装和启动沿用工作台异步任务。终端创建接口 `POST /api/terminals` 接受普通终端、Claude 终端和账号面板发起的官方登录终端(`shell`、`claude`、`claude-login`)。省略类型时打开普通终端。Claude 启动命令只读取已保存的偏好。 | |
| 71 | 78 | |
| 72 | 删除:Desktop 默认按内容区域的逻辑像素显示,窗口尺寸和侧栏变化会同步调整虚拟屏幕。工具栏的“显示大小”提供 75%、90%、100%、110%、125% 和 150%,默认 100%;较小的值可显示更多内容,较大的值放大文字和控件。偏好保存在当前工作台的本机存储中,调整立即生效,保持应用和画面连接。 | |
| 79 | 新增:Desktop 默认按内容区域的逻辑像素显示,窗口尺寸和侧栏变化会同步调整虚拟屏幕。工具栏的“显示大小”提供 75%、90%、100%、110%、125% 和 150%,默认 100%;较小的值可显示更多内容,较大的值放大文字和控件。选项在按钮下方浮出,展开和收起时工具栏高度与桌面区域尺寸保持不变。偏好保存在当前工作台的本机存储中,调整立即生效,保持应用和画面连接。 | |
| 73 | 80 | |
| 74 | 81 | 尺寸调整与其他客机控制脚本共用 SSH 执行入口,在客机内明确使用 `/bin/bash --noprofile --norc -c`。SSH 登录仍经过用户的默认 shell,控制脚本的重定向和错误处理由 Bash 执行,避免 zsh 中的 mise 初始化状态使尺寸锁创建提前返回失败。脚本整体经过 shell 引号转义,三个主机平台共用同一执行方式。 |
| 75 | 82 | |
| 76 | 83 | 应用以 `--force-device-scale-factor=2` 启动;虚拟屏幕宽高为内容区域的 CSS 尺寸乘以 `2 / 显示大小`,noVNC 将画面等比适配回内容区域。虚拟屏幕每边最多 8192 像素,超过上限时按同一比例缩减宽高。尺寸提交串行执行,快速调整窗口时以最新尺寸为准;失败后最多自动重试三次,持续失败显示“重试调整”。macOS、Windows 与 Linux 共用此显示链路。应用启动缩放参数在下次打开应用时生效,工具栏的显示大小无需重启。 |
| 77 | 84 | |
| 85 | 新增:## Claude Code 账号面板 | |
| 86 | 新增: | |
| 87 | 新增:“设置 → Claude 账号”有两个入口。环境就绪后,Cage 在客机用户的主目录调用官方 CLI 检查默认登录。检测到订阅时展示邮箱,用户点击“加入调度”后,新的工作台终端才可按账号池策略分配到该身份。加入时会重新核对邮箱和组织,避免用户看到 A 时点击,实际加入的却是 B。没有任何已登记账号时,旧的 Claude 终端入口继续沿用环境原有登录。 | |
| 88 | 新增: | |
| 89 | 新增:“登录新账号”使用独立的配置目录打开官方登录终端,用户在临时浏览器中完成授权。成功后按邮箱登记,无需预填名称,后续可以设置备注。工作台只记录身份和额度摘要,订阅凭据由 CLI 自行管理。 | |
| 90 | 新增: | |
| 91 | 新增:默认目录同一时间只代表一种身份。从 A 改成 B 后,A 的原记录不再用于分配新终端,旧终端仍标记其启动时的账号,B 不继承 A 的参与状态或额度。已有 CLI 进程如何处理外部登录变化由 CLI 决定,继续使用前应确认身份。独立登录各有自己的目录,同时保留多个订阅时更适合使用这个入口。Desktop 的登录不参与发现和调度。 | |
| 92 | 新增: | |
| 93 | 新增:把一个账号暂停后,它的现有终端可以继续工作或断开后重连,下一次新建终端会从余下的账号中选择。所有账号停用、登录失效或额度窗口用尽时,创建会显示原因。已有安装在尚未添加任何账号时继续使用旧配置目录。账号暂停不执行登出,也不删除历史。 | |
| 94 | 新增: | |
| 95 | 新增:每个账号以 Claude Code 的像素角色 Clawd 标识。卡片内的 `5h` 和 `7d` 分别显示已用百分比和距重置的时间。打开账号面板会启动一次额度查询,短时间内重复打开可复用最近的检查。点击“检查状态”会立即检查指定账号。同一身份的并发请求共用在途查询,账号较多时限制并发。列表轮询和倒计时本身不向 Claude 发起新查询。 | |
| 96 | 新增: | |
| 97 | 新增:额度由官方 CLI 的 `/usage` 控制接口提供,命令只查询用量,不发送模型提示。账号身份在查询前后分别核验,身份改变时丢弃本次结果。上次查询时间与每个窗口最近读到数值的时间分开记录。只有一个窗口返回时,另一个保留上次读数。没有数据、查询失败或环境离线时显示相应原因。窗口已过重置时间的旧值只能作为历史参考,不能代表新窗口的用量。受管会话的状态行仍可补充额度读数。账号列表独立滚动,添加入口保持可见。 | |
| 98 | 新增: | |
| 99 | 新增:调度绑定于新建的工作台终端。Cage 重连时复用原进程,不会将一段对话或未完成的工具调用自动搬到另一个订阅。同一项目五分钟内重开,负载和额度接近时优先复用原账号。会话历史按 CLI 配置目录保存,`--continue` 在本次分配的目录中找对话。复用普通终端默认登录也会沿用该目录的历史。独立命令行和绕过受管启动器的自定义命令不参与调度。[数据来源与集成取舍](../research/2026-11-04-claude-account-pool.md) | |
| 100 | 新增: | |
| 78 | 101 | ## 主机输入法 |
| 79 | 102 | |
| 80 | 103 | 浏览器与 Claude Desktop 共用主机输入法接入:主机负责拼音和候选词,客机应用在自己的输入框内绘制组合文字。选词确认、更新和取消分别传递;普通按键与文字传递共用 noVNC 输入队列,确认后的回车必须等待文字提交完成。全角问号 `?`、逗号等直接产生的字符走文字通道,避免有限的 X11 按键映射丢失字符。Desktop 的兼容粘贴路径会暂时释放远端已按下的修饰键,完成 Ctrl+V 后恢复,保证按住 Shift 输入问号时行为正确。 |
| @@ -154,6 +177,14 @@ Chromium 通过继承的私有调试管道接受标签与导航命令,不开 | ||
| 154 | 177 | |
| 155 | 178 | 虚拟显示由 Xtigervnc 提供,直接监听仅限 guest 私有 Unix socket;X0tigervnc 负责文本剪贴板与显示传输。轻量窗口管理器让 kiosk Chromium 随显示区域调整,不提供桌面壳。工作台通过浏览器控制器调整显示模式,以 2 倍像素呈现;画面连接断开时按有上限的间隔重试,不因此重启 VM 或终端。 |
| 156 | 179 | |
| 180 | 新增:### 网页复制按钮 | |
| 181 | 新增: | |
| 182 | 新增:用户在 Cage 浏览器点击复制按钮时,客机观察该页面原生复制 API 的完成结果,将这次操作的纯文本传给本机。支持 `Clipboard.writeText`、单项 `Clipboard.write` 的 `text/plain`,以及 `execCommand('copy')` 中明确设置的文本和普通输入框的选中文字。需要浏览器确认用户激活,页面、工作台画面和本机窗口均须处于当前焦点。文字上限为 65536 个 UTF-16 码元;富文本、图片和无法确认准确文字的 DOM 选区通过现有复制快捷键或文本传递面板处理。 | |
| 183 | 新增: | |
| 184 | 新增:工作台在鼠标输入发送前通过 RFB 输入队列确认客机已收到 `/copy-context` 的随机操作标识。复制 API 开始时保存该标识,完成后在当前 `/events` 连接发送一次 `clipboard` 命名事件,数据为 `{id,text,context}`。工作台失焦、切换页面或重连会撤销旧标识,因此切回同一标签也不会接受旧操作的迟到结果。 | |
| 185 | 新增: | |
| 186 | 新增:复制内容不写入标签快照或持久存储,重连不会重复发送。主机转发保持原文,工作台核对来源标签、操作标识和输入焦点后调用三平台共用的 `clipboardWrite` 原生接口。普通点击、拖选或无关的 RFB 剪贴板通知不能授权这条写入路径。已有网页如果改写了观察所需的浏览器 API,当前文档会跳过安装,刷新后在页面脚本之前安装。 | |
| 187 | 新增: | |
| 157 | 188 | ### 图片与文件输入 |
| 158 | 189 | |
| 159 | 190 | 工作内容区接受本机截图、复制的文件和文件拖入,地址栏及设置表单保留本地输入行为。截图使用图片粘贴;文件保留原名与字节,单个上限 2 GB,一次最多 100 个。网页拖入交给落点,文件粘贴按当前焦点模拟拖入;Desktop 将文件放入私有图形会话剪贴板并请求当前输入位置粘贴,目标须支持文件附件。终端接收经过 shell 引号处理的客机文件路径,不自动提交命令。 |
| @@ -24,7 +24,7 @@ | ||
| 24 | 24 | |
| 25 | 25 | 无需先安装开发工具或 Clash。签名、公证和平台验证情况以该安装包的 Release 说明为准。如果系统拒绝打开,先按[安装问题](troubleshooting.md#下载或安装受阻)核对版本与来源。下述代理、环境和项目操作共用。 |
| 26 | 26 | |
| 27 | 删除:首次打开时创建一个本地账户:设置用户名和至少 8 个字符的密码。Mac 首次创建时默认勾选“记住登录”,可取消勾选;之后也可在账户设置关闭,关闭后的选择会保留。账户只用于本机 Cage;左下角头像菜单的“账户设置”可更换头像、用户名和密码。请妥善保存密码,首版没有在线找回。它不替代 Claude 账号,也不会加密项目文件或整个虚拟磁盘。 | |
| 27 | 新增:首次打开时创建一个本地账户:设置用户名和至少 8 个字符的密码。Mac 首次创建时默认勾选“记住登录”,可取消勾选;之后也可在“设置 → 账户”中关闭,关闭后的选择会保留。账户只用于本机 Cage;从左下角头像菜单打开“设置”,即可在“账户”中更换头像、用户名和密码。请妥善保存密码,首版没有在线找回。它不替代 Claude 账号,也不会加密项目文件或整个虚拟磁盘。 | |
| 28 | 28 | |
| 29 | 29 | ## 2. 导入并选择代理 |
| 30 | 30 | |
| @@ -58,11 +58,17 @@ HTTP/SOCKS5 服务可通过“订阅 → 添加来源 → 手动节点”录入 | ||
| 58 | 58 | |
| 59 | 59 | ## 4. 打开项目并开始工作 |
| 60 | 60 | |
| 61 | 删除:点击“打开项目”,选择已有项目,或点击“添加本机项目…”选择主机上的项目文件夹。新终端和文件编辑器将从这个目录开始工作;首次试用也可保留默认工作区。 | |
| 61 | 新增:点击左侧“项目”标题旁的加号,选择已有项目,或点击“添加本机项目…”选择主机上的项目文件夹。新终端和文件编辑器将从这个目录开始工作;首次试用也可保留默认工作区。 | |
| 62 | 62 | |
| 63 | 删除:在项目旁点击“+”,选择“新建 Claude 终端”,Cage 会在该项目中自动运行 `claude`。也可选择普通终端,手动输入命令。“设置 → 通用 → Claude 终端启动命令”可添加参数,例如 `claude --continue`;保存后只影响新建的 Claude 终端,退出 Claude 后仍可继续使用 shell。 | |
| 63 | 新增:点击项目右侧的终端图标,选择“新建 Claude 终端”,Cage 会在该项目中自动运行 `claude`。也可选择普通终端,手动输入命令。“设置 → 通用 → Claude 终端启动命令”可添加参数,例如 `claude --continue`;保存后只影响新建的 Claude 终端,退出 Claude 后仍可继续使用 shell。 | |
| 64 | 64 | |
| 65 | 删除:按 Claude Code 的提示,在 Cage 浏览器中完成自己的账户授权。主机已有的 Claude 登录、浏览器用户目录和 SSH 密钥不会自动导入。如果授权链接没有自动打开,可复制完整链接到 Cage 浏览器地址栏;链接可能包含一次性授权信息,不要发到 Issue 中。 | |
| 65 | 新增:打开“设置 → Claude 账号”。如果你已在 Cage 普通终端用 Claude Code 登录订阅,环境就绪后,页面会显示默认终端检测到的邮箱。点击“加入调度”即可复用这份登录。设备上的 Claude Desktop、网页和 Mac 系统终端有各自的登录,面板只检查 Cage 客机里的 Claude Code。 | |
| 66 | 新增: | |
| 67 | 新增:要添加另一个订阅,点击“登录新账号”,在临时浏览器窗口完成官方授权。Cage 为这次登录分配独立目录,成功后按邮箱登记并参与调度,也可以再改备注。取消登录不会增加一个可调度账号。以后点击项目右侧的终端图标新建 Claude 终端,标签会显示它分配到的账号。 | |
| 68 | 新增: | |
| 69 | 新增:如果普通终端原先登录 A,后来登录 B,Cage 会停止把默认目录分配给 A。B 需要单独点击“加入调度”。要让 A 和 B 长期同时在线,可以保留一份默认登录,再用“登录新账号”为另一个账号建立独立登录。 | |
| 70 | 新增: | |
| 71 | 新增:关闭某个账号的“参与自动分配”只影响之后新建的终端,正在使用该账号的会话可以继续。打开账号面板时,Cage 会向客机里的官方 Claude Code 查询五小时和七天额度。点击卡片的“检查状态”可立即重查该账号,无需先发一条模型消息。某个窗口没有返回读数时,面板会说明结果,并保留该窗口上一次的百分比和读取时间。[账号调度与额度说明](design/workbench.md#claude-code-账号面板) | |
| 66 | 72 | |
| 67 | 73 | 可以先让 Claude 读取项目并解释一个文件,确认模型请求正常,再让它在测试文件中完成一个小修改。通过“浏览文件”查看内容,并在主机上确认同一文件的变化。首次使用前请备份重要项目。 |
| 68 | 74 | |
| @@ -82,13 +88,21 @@ Desktop 的画面会随 Cage 窗口和侧栏自动调整。右上角“显示大 | ||
| 82 | 88 | |
| 83 | 89 | ### 锁定与退出账户 |
| 84 | 90 | |
| 85 | 删除:左下角头像菜单中的“锁定 Cage”隐藏工作台并要求重新输入密码,正在运行的 Claude、终端和环境任务继续运行。“退出账户”会先提醒保存文件,再停止环境并锁定凭据。仅退出应用时后台任务继续运行。“账户设置 → 登录与解锁”可开启“记住登录”,下次打开直接进入;手动锁定后仍需密码或 Touch ID,重新打开也不会跳过验证。Mac 已设置 Touch ID 时,可开启指纹解锁。退出账户会撤销本机快捷登录授权。 | |
| 91 | 新增:左下角头像菜单中的“锁定 Cage”隐藏工作台并要求重新输入密码,正在运行的 Claude、终端和环境任务继续运行。“退出账户”会先提醒保存文件,再停止环境并锁定凭据。仅退出应用时后台任务继续运行。“设置 → 账户 → 登录与解锁”可开启“记住登录”,下次打开直接进入;手动锁定后仍需密码或 Touch ID,重新打开也不会跳过验证。Mac 已设置 Touch ID 时,可开启指纹解锁。退出账户会撤销本机快捷登录授权。 | |
| 92 | 新增: | |
| 93 | 新增:### 保存网站账号密码 | |
| 94 | 新增: | |
| 95 | 新增:在 Cage 浏览器中提交邮箱等网站的登录表单后,浏览器工具区会提示保存账号密码。先确认网站登录成功,再点击“保存密码”;密码变化时可选择“更新密码”。“此网站不再提示”只关闭该网站的保存提示。 | |
| 96 | 新增: | |
| 97 | 新增:再次打开同一网站时,展开浏览器工具区的“密码”,选择账号填入登录框,再自行提交。当前支持 HTTPS 顶层页面的常见表单;嵌入框架、验证码和 Passkey 不自动处理。旧环境如果提示密码功能不可用,先到“设置 → 环境与恢复”更新环境组件。 | |
| 98 | 新增: | |
| 99 | 新增:在“设置 → 密码保险箱”中可以搜索、添加、编辑、删除记录,或恢复某网站的保存提示。查看、复制密码需要再次输入 Cage 账户密码。保险箱随 Cage 一起解锁和锁定;已启用记住登录时,也会随之解锁。密码只保存在本机,备份时需同时保留配置目录中的账户文件与密码库,具体边界见[密码保险箱设计](design/password-vault.md)。 | |
| 86 | 100 | |
| 87 | 101 | ### 项目、标签与文件 |
| 88 | 102 | |
| 89 | 删除:左侧“项目”列出默认工作区和明确打开的文件夹,列表由 Cage 保存,重新打开应用后仍可看到。点击目录旁的加号,在该目录中新建终端;已有终端始终留在创建它的目录下。所有项目共用一个持久环境,工具、账户和 Linux 文件系统也相互共享。已打开的目录在环境启动时恢复连接。 | |
| 103 | 新增:左侧“项目”列出默认工作区和明确打开的文件夹,列表由 Cage 保存,重新打开应用后仍可看到。每个项目右侧有两个图标。点击打开图标(↗)可在 code-server 中编辑该目录的文件。点击终端图标(>_)可选择终端类型,在该目录新建终端。已有终端始终留在创建它的目录下。所有项目共用一个持久环境,工具、账户和 Linux 文件系统也相互共享。已打开的目录在环境启动时恢复连接。 | |
| 90 | 104 | |
| 91 | 删除:浏览器独立于项目,网页和文件编辑器使用顶部标签页;切换项目不会关闭或迁移网页。终端通过行末菜单管理,浏览器标签可通过右键或 Shift+F10 打开菜单,支持重命名、置顶和关闭。拖动可调整同一列表内的顺序,刷新后保留。⌘1–9 切换当前浏览器的页面或当前目录的终端。 | |
| 105 | 新增:浏览器独立于项目,网页和文件编辑器使用顶部标签页;切换项目不会关闭或迁移网页。将鼠标移入终端行,或用键盘聚焦该行,即可在右侧置顶、重命名或删除终端。浏览器标签可通过右键或 Shift+F10 打开操作菜单。拖动可调整同一列表内的顺序,刷新后保留。⌘1–9 切换当前浏览器的页面或当前目录的终端。 | |
| 92 | 106 | |
| 93 | 107 | 标签较多时会自动缩短,当前页面的标签保留更多标题空间。拖动时其他标签即时让位,松手保存顺序,Esc 取消;置顶标签在置顶分组内排序。右侧向下箭头可以搜索已打开的页面。 |
| 94 | 108 | |
| @@ -124,6 +138,8 @@ Windows 和 Linux 默认采用 Ctrl 按键习惯,工作台快捷键中的 `⌘ | ||
| 124 | 138 | |
| 125 | 139 | 复制粘贴支持纯文本、中文、多行和 emoji。先点击目标输入框,再使用快捷键或工具栏按钮;普通浏览器限制剪贴板权限时,可用“文本传递”面板。Cage 仅在主动复制或粘贴时访问本机剪贴板,不持续轮询。 |
| 126 | 140 | |
| 141 | 新增:Cage 浏览器中的网页复制按钮也可同步纯文本到本机。点击后保持当前网页和 Cage 窗口处于前台,出现“已复制到本机”即可在其他应用粘贴。如果网页采用不受支持的旧式复制方式,或复制期间切换了标签、输入位置或窗口,可重新复制,或使用复制快捷键和“文本传递”面板。 | |
| 142 | 新增: | |
| 127 | 143 | 本机截图可以粘贴到 Cage。视频、文档和图片文件可以直接拖入工作内容区,也可以先在本机文件管理器中复制,再到 Cage 粘贴。文件保留原始名称与内容,包括 GIF 动画;单文件最多 2 GB,一次最多 100 个。网页拖入会交给落点,文件粘贴会交给当前输入位置,目标网页须支持附件拖入;Claude Desktop 须先点击支持附件的输入位置。终端把文件保存到客机附件目录并插入带引号的路径,供 Claude Code 等工具读取,不自动执行命令。 |
| 128 | 144 | |
| 129 | 145 | 截图粘贴上限为 20 MB、4000 万像素。Cage 通过本机与客机的控制通道传递附件,不借助外部存储服务;目标网页或应用可以按自身行为上传。终端附件保留到用户自行删除,Desktop 的上传副本保留到图形会话重建。切换目标或断开连接后,尚未发送的输入会取消。使用旧环境时,先按应用提示更新环境组件。 |
| @@ -186,6 +202,10 @@ Cage 使用轻量 Linux 虚拟机,没有完整桌面。浏览器与编辑器 | ||
| 186 | 202 | |
| 187 | 203 | 首次安装请下载公开 Release 的 DMG。应用内更新用于后续版本升级。 |
| 188 | 204 | |
| 205 | 新增:安装、重装、更新和卸载均保留个人数据。macOS、Windows 和 Linux 默认使用用户主目录下的 `~/.claude-cage/`:本地账户、收藏和设置保存在该目录,浏览器历史、网站登录状态和环境内文件保存在其中的持久虚拟磁盘。更换应用安装位置不会更换默认数据目录;通过 `CLAUDE_CAGE_CONFIG` 指定其他配置时,应始终使用同一配置。终端窗口的临时输出和正在运行的进程不属于磁盘备份。 | |
| 206 | 新增: | |
| 207 | 新增:已创建过账户却再次出现创建页面时,先按[账户与数据目录检查](troubleshooting.md#已有账户却再次显示创建账户)核对目录,不要创建新账户或删除旧配置。 | |
| 208 | 新增: | |
| 189 | 209 | 应用会在启动后自动检查更新,运行期间每六小时重查;检查失败后每五分钟重试,隐藏窗口期间暂停检查。没有新版时不显示更新入口。有新版时,左下角显示金色圆形下载按钮;请先保存文件并结束运行中的任务,再点击一次。按钮会显示环形下载进度和百分比,下载校验完成后自动停止环境、安装并重启,不再弹出确认框。应用更新会结束工作台终端,保留项目、配置、虚拟磁盘和登录状态。失败时显示原因,点击原按钮可重试。 |
| 190 | 210 | |
| 191 | 211 | macOS 的 `0.1.3-alpha.1` 及更早公开版本存在本机更新校验错误。遇到“本机更新验证未完成”时,请保存文件、停止环境并退出 Cage,从官方 Release 下载 `0.1.3-alpha.2` 或更新的 DMG,替换原来的应用一次;已有项目和数据会保留。修复版之后可使用应用内更新。 |
| @@ -0,0 +1,56 @@ | ||
| 1 | 新增:# Windows Privacy Guard 与 Cage 的比较 | |
| 2 | 新增: | |
| 3 | 新增:本文供 Cage 维护者判断产品差异与可借鉴的能力。核查日期:2026-11-03。外部项目固定到提交 `cf7e6ed14736b8f9762a10bb3e94ee6f40cac797`;Cage 依据当前工作区,HEAD 为 `7090ecf5a3464b46d6b05442e456d929839889fe`,包含尚未提交的在途修改。本次阅读文档和关键源码,没有部署外部项目、执行其脚本或进行两产品的运行性能与泄露对照测试。 | |
| 4 | 新增: | |
| 5 | 新增:## 阅读版:用户会遇到什么差别 | |
| 6 | 新增: | |
| 7 | 新增:Cage 的主要优势是把浏览器、终端和开发工具放进统一的隔离环境,并在环境外控制网络。Windows Privacy Guard 的主要优势是保留 Windows 原生使用方式,提供定向登录清理、应用联网保护和独立浏览器入口。两者都有失败关闭和证据过期机制;虚拟机隔离与浏览器抗追踪需要分别评价。 | |
| 8 | 新增: | |
| 9 | 新增:例如,让 Claude 调用 Python 下载依赖时,Cage 内新进程继续经过相同的虚拟机出口。Windows 应用保护要检查这个 Python 进程是否属于防火墙登记范围,不能从 Claude 主程序通过验收推导整个工具链都已受保护。此判断来自两边的约束对象:应用身份与虚拟机网络,见下文源码证据。 | |
| 10 | 新增: | |
| 11 | 新增:| 用户关心的方面 | Windows Privacy Guard | Cage 当前实现与边界 | | |
| 12 | 新增:|---|---|---| | |
| 13 | 新增:| 日常工作方式 | Windows 上的 Claude 桌面应用、独立 Edge/Brave 配置;通过启动器、后台服务和面板协作 | 同一窗口管理 Linux 终端、浏览器、编辑器及 Linux 桌面应用;需要虚拟化和额外磁盘、内存,具体开销未对测 | | |
| 14 | 新增:| 本机文件与登录资料 | 定向清理 Claude 登录残留;独立浏览器配置不复制普通浏览器登录。项目未建立通用的宿主文件隔离边界 | 主机目录按授权共享,宿主登录与密钥不自动导入。共享文件仍可被修改、删除;所有项目共用一个环境 | | |
| 15 | 新增:| 网络保护范围 | 防火墙按登记的可执行文件/包身份限制出口;手动浏览器另有代理参数、偏好和进程检查,不承诺按浏览器配置文件实现内核隔离 | 在虚拟机外约束客机业务流量,不依赖应用是否遵循代理环境变量;宿主应用不属于这个范围 | | |
| 16 | 新增:| DNS、UDP、IPv6 | 有作用域 DNS、WebRTC 偏好、Windows 内核规则。某入口的策略通过不能替代其他入口的实包验证 | 客机业务 DNS 经同一代理;公网 UDP、IPv6、ICMP 拒绝。代理自身启动解析与业务 DNS 分别说明 | | |
| 17 | 新增:| 时区与语言 | 当前手动浏览器快照要求 Windows 系统为丹佛时区、浏览器英语;准备工具不会自动修改整机时区 | 改虚拟机内时区、语言和浏览器偏好,宿主可保持原设置;可按出口建议配置 | | |
| 18 | 新增:| 浏览器抗追踪 | Brave 入口采用浏览器原生隐私功能;日常手动入口不连接调试协议 | Chromium 通过私有调试管道管理标签。已隔离宿主环境,但未建立与 Brave 原生指纹随机化等价的能力 | | |
| 19 | 新增:| 部署与维护 | 可构建源码、Skill 和面板;依赖用户准备多个组件,缺少通用的完整安装事务 | 应用集成工作台与代理管理。macOS、Windows、Linux 的实测范围不同,不能概括为三平台全面验收 | | |
| 20 | 新增: | |
| 21 | 新增:外部能力与限制依据:[后端说明](https://github.com/SWL-1229/claude-windows-privacy-guard/blob/cf7e6ed14736b8f9762a10bb3e94ee6f40cac797/backend/README.md)、[手动浏览器说明](https://github.com/SWL-1229/claude-windows-privacy-guard/blob/cf7e6ed14736b8f9762a10bb3e94ee6f40cac797/references/manual-browsers.md)、[定向清理与项目范围](https://github.com/SWL-1229/claude-windows-privacy-guard/blob/cf7e6ed14736b8f9762a10bb3e94ee6f40cac797/README.md)。Cage 依据:[工作台设计](../design/workbench.md)、[网络检查](../design/network-checks.md)、[内置代理](../design/managed-proxy.md)。 | |
| 22 | 新增: | |
| 23 | 新增:### 截图能够支持的结论 | |
| 24 | 新增: | |
| 25 | 新增:外部项目的截图记录了维护者某次出口、DNS、WebRTC、时区和语言的结果。项目明确说明这些图片来自不同阶段与浏览器。面板的 36 条 WFP 规则核验属于内核策略身份与条件检查,没有宣称同时完成 UDP/IPv6 正负实包对照。语言评分 57→23 和 Brave 的 B 级均来自第三方检测,不能作为两产品整体安全性或账号风险的排名。[截图与限定条件](https://github.com/SWL-1229/claude-windows-privacy-guard/blob/cf7e6ed14736b8f9762a10bb3e94ee6f40cac797/docs/before-after.md) | |
| 26 | 新增: | |
| 27 | 新增:Cage 保留中文字体与 Emoji 字体以支持正常使用,因此也不应把消除这些字体信号作为安全验收目标。虚拟机使网页接触客机环境,但客机自身的浏览器、字体、渲染和持久登录仍可形成关联信号。Brave 对部分可指纹化值进行随机化的机制,与运行在虚拟机中的 Chromium 是不同能力;具体效果仍需同条件测试。[Brave 机制说明](https://brave.com/privacy-updates/3-fingerprint-randomization/) | |
| 28 | 新增: | |
| 29 | 新增:### 出口监测的实际取舍 | |
| 30 | 新增: | |
| 31 | 新增:外部网关将出口许可设为 4 秒,并有高频本地检查和出口采样;Cage 的放行租约为 90 秒,运行监测约每 30 秒检查一次。外部实现更强调证据新鲜度,代价可能是探测成本和网络抖动时的暂停,这属于代码推断,尚未做体验对照。它还实现了无新结果时保留连接但暂停转发的限时分支,不能把 4 秒理解为所有连接一律立即关闭。[外部网关源码](https://github.com/SWL-1229/claude-windows-privacy-guard/blob/cf7e6ed14736b8f9762a10bb3e94ee6f40cac797/backend/source/guard.py#L47-L64) | |
| 32 | 新增: | |
| 33 | 新增:两边都无法仅凭周期探测保证代理服务商每条连接使用相同出口。Cage 的 90 秒租约也不表示代理断线后会直连;实际转发没有直连回退。两种失败需要分开:代理不可用,以及代理仍可用但出口在两次采样间改变。[Cage 网络约束](../design/network-checks.md) | |
| 34 | 新增: | |
| 35 | 新增:### 建议 | |
| 36 | 新增: | |
| 37 | 新增:1. 保留 Cage 的统一虚拟机边界。它覆盖任意客机工具的方式更适合开发工作台,且可保留宿主原有时区、浏览器和登录状态。 | |
| 38 | 新增:2. 借鉴外部项目的证据展示:分别显示配置读回、运行时约束、实际流量测试及其时间与范围。Cage 已有对应分层设计,可进一步检查界面是否足够清楚。 | |
| 39 | 新增:3. 将浏览器抗追踪作为独立评估项。如评估 Brave,应在相同代理、相同站点和相同使用任务下比较兼容性、关联信号与资源开销;不能仅凭一次评分决定替换浏览器。 | |
| 40 | 新增:4. 复核出口异常发现时间与误暂停之间的平衡,先测故障行为和探测成本,再决定是否调整周期,不直接照搬 4 秒参数。 | |
| 41 | 新增: | |
| 42 | 新增:这些是后续建议,本次没有改变产品设计、配置或运行中的环境。Cage 的平台文档记录了 Windows 11 单台实体机验收,以及 Linux 云端/软件模拟验证;Windows 10、Linux KVM 与部分真实业务路径仍有未测项。[Windows 范围](../windows.md)、[Linux 范围](../linux.md) | |
| 43 | 新增: | |
| 44 | 新增:## 证据版:关键实现位置 | |
| 45 | 新增: | |
| 46 | 新增:| 结论 | 外部项目源码 | Cage 当前工作区 | | |
| 47 | 新增:|---|---|---| | |
| 48 | 新增:| 按应用身份限制与按 VM 限制的区别 | [ClaudeWfpGuard.cs:195](https://github.com/SWL-1229/claude-windows-privacy-guard/blob/cf7e6ed14736b8f9762a10bb3e94ee6f40cac797/backend/source/wfp/ClaudeWfpGuard.cs#L195):身份条件与四类拒绝规则 | `internal/cage/egress.go:24`、`:49`;`internal/vm/networkconfined.go:18`:拒绝不经受控网络的驱动与额外网卡 | | |
| 49 | 新增:| 业务 DNS 不走宿主解析回退 | [install-scoped-dns.ps1](https://github.com/SWL-1229/claude-windows-privacy-guard/blob/cf7e6ed14736b8f9762a10bb3e94ee6f40cac797/backend/source/dns/install-scoped-dns.ps1):指定域的 NRPT 定向 | `internal/cage/egress.go:131`:经同一代理发送 DNS;代理启动解析边界另见设计文档 | | |
| 50 | 新增:| 短期放行证据 | [guard.py:47](https://github.com/SWL-1229/claude-windows-privacy-guard/blob/cf7e6ed14736b8f9762a10bb3e94ee6f40cac797/backend/source/guard.py#L47):4 秒许可及无结果暂停 | `internal/cage/gate.go:21`:90 秒;`internal/workbench/safety.go:553`:约 30 秒监测间隔 | | |
| 51 | 新增:| 浏览器原生偏好与调试管道 | [brave_browser_policy.py:17](https://github.com/SWL-1229/claude-windows-privacy-guard/blob/cf7e6ed14736b8f9762a10bb3e94ee6f40cac797/backend/source/brave_browser_policy.py#L17):读回 WebRTC 偏好;同文件 `arguments` 定义启动参数 | `internal/cage/browser-agent.mjs:37`:Chromium 私有调试管道、关闭 AutomationControlled 标记与 QUIC;这些选项不能证明没有可检测特征 | | |
| 52 | 新增:| 系统时区归属 | [brave_browser_policy.py:13](https://github.com/SWL-1229/claude-windows-privacy-guard/blob/cf7e6ed14736b8f9762a10bb3e94ee6f40cac797/backend/source/brave_browser_policy.py#L13) 与手动浏览器说明:固定 Denver/Windows 时区要求 | `internal/cage/guest-env.sh:3`:设置客机时区;`:9`:客机进程环境 | | |
| 53 | 新增:| 中文字体保留 | [before-after.md](https://github.com/SWL-1229/claude-windows-privacy-guard/blob/cf7e6ed14736b8f9762a10bb3e94ee6f40cac797/docs/before-after.md):说明仍存在中文字体与 Emoji 信号 | `internal/cage/guest-setup.sh:3`:安装 Noto CJK 与 Emoji 字体 | | |
| 54 | 新增:| 项目之间共用环境 | 外部项目没有提供通用项目 VM 隔离机制 | `docs/design/workbench.md:44`、`:46`:单持久 VM 与已授权项目共享;不能宣传为项目之间隔离 | | |
| 55 | 新增: | |
| 56 | 新增:本次核对用于比较机制与交付范围,不构成完整安全审计。源码存在、维护者截图、离线测试、当前机器真实运行验证是不同证据等级。 | |
| @@ -0,0 +1,31 @@ | ||
| 1 | 新增:# Claude Code 多账号与订阅额度 | |
| 2 | 新增: | |
| 3 | 新增:核对日期为 2026 年 11 月 5 日。Cage 的账号面板管理用户本人可以使用的订阅。用户可以同时打开两个项目终端,查看各自使用的账号,也可以暂停一个账号接收新终端。账号的登录、模型请求和续期均由客机里的官方 Claude Code 处理。 | |
| 4 | 新增: | |
| 5 | 新增:## 两个现有工具的取舍 | |
| 6 | 新增: | |
| 7 | 新增:| 工具及模式 | 用户能做什么 | Cage 的选择 | | |
| 8 | 新增:| --- | --- | --- | | |
| 9 | 新增:| CC Switch v4.0.25,隔离终端 | 在独立配置目录中并行使用多个账号。另有更换全局登录的模式,据项目说明,进行中的会话也可能改用新账号。订阅账号不参加它的代理故障转移。 | 借鉴独立目录。Cage 在创建终端时完成分配,暂停账号后原终端仍属于它。[项目说明](https://github.com/farion1231/cc-switch/blob/v4.0.25/docs/guides/claude-official-accounts-guide-zh.md) | | |
| 10 | 新增:| CCS v8.10.0,原生账号 | 为工作和个人账号分开登录,配置目录和默认会话历史各自独立。 | 每个账号保留官方 CLI 的独立配置和历史。Cage 共用同一 VM、项目文件和网络出口。[原生账号说明](https://docs.ccs.kaitran.ca/providers/concepts/claude-accounts) | | |
| 11 | 新增:| CCS,代理号池 | 另行配置代理凭据,按请求路由。提供会话粘性、账号冷却和流开始前的故障转移。 | 订阅路径在官方 CLI 创建会话时分配,不接管请求流,工具执行途中不会由 Cage 自动重放。[号池说明](https://docs.ccs.kaitran.ca/features/pool) · [路由源码](https://github.com/kaitranntt/ccs/blob/v8.10.0/src/cliproxy/routing/routing-strategy.ts) | | |
| 12 | 新增: | |
| 13 | 新增:CC Switch 和 CCS 的额度功能中都能找到读取订阅凭据、调用 OAuth 用量端点的代码。这个端点不是本方案面向 Cage 的公开额度接口。Anthropic 允许用户在原版 Claude Code 中自己登录,也明确限制第三方收集或中转订阅令牌、代表用户用订阅凭据路由请求。产品内运行官方 CLI 还须遵守有关商业条款、保留原版认证方式和由用户直接结算的条件。[CC Switch 用量源码](https://github.com/farion1231/cc-switch/blob/v4.0.25/src-tauri/src/services/subscription.rs) · [CCS 用量源码](https://github.com/kaitranntt/ccs/blob/v8.10.0/src/web-server/usage/native-quota-collector.ts) · [Anthropic 对产品集成与认证的说明](https://code.claude.com/docs/en/legal-and-compliance) | |
| 14 | 新增: | |
| 15 | 新增:## 登录与存储 | |
| 16 | 新增: | |
| 17 | 新增:一个 Cage 本地账户解锁整份工作台,可以在一个 Linux 客机中管理多个 CLI 登录。主机保存名称、订阅身份摘要、是否参与调度和最近用量。面板中的新登录各有一个固定的配置目录。普通终端的默认登录则引用原目录,Cage 单独核对邮箱和组织,发现身份后需用户选择加入调度。CLI 自己把登录状态写入该目录,用户在临时浏览器中完成官方授权。认证页面的 Cookie 与日常浏览器隔离,授权参数不出现在工作台标签元数据或最近网址中。操作系统用户相同的客机程序仍处于同一信任边界,不能把配置目录当作不同租户之间的安全隔离。[官方多账号认证](https://code.claude.com/docs/en/authentication#log-in-with-multiple-accounts) · [凭据存储](https://code.claude.com/docs/en/authentication#credential-management) | |
| 18 | 新增: | |
| 19 | 新增:桌面应用有自己的账号登录。官方文档明确区分 CLI 和 Desktop 的认证配置。网页或桌面端的账号菜单可以在同邮箱绑定的个人和团队组织之间切换。未查到让外部程序给 Desktop 的每段对话指定个人 Pro 登录的受支持接口。Cage 当前也只管理一个 Desktop 服务与密钥环。首版把调度范围限定在工作台新建的 Claude Code 终端。普通 shell、独立命令行、Desktop 和网页继续使用各自的登录。[Claude Code 认证](https://code.claude.com/docs/en/authentication#credential-management) · [官方账号切换说明](https://support.claude.com/en/articles/13189465-log-in-to-your-claude-account) · [Cage 工作台](../design/workbench.md) | |
| 20 | 新增: | |
| 21 | 新增:## 调度和缓存 | |
| 22 | 新增: | |
| 23 | 新增:终端 A 已经在改文件时,即使用户停用其账号,或服务端报告额度用完,Cage 都保留 A 的进程、项目和登录目录。已有连接重连原终端。只有新建终端才在可用账号间分配。这也避免了把已执行的文件编辑、测试或 shell 命令再运行一次。终端关闭后,Claude 的历史仍在该账号的目录。关闭终端或停止 VM 和暂时断开查看有不同结果。 | |
| 24 | 新增: | |
| 25 | 新增:配置目录隔离本地历史,服务端自己管理提示缓存。同一账号、相同模型和稳定的提示前缀有利于缓存复用,跨账号继续一段对话不能承诺缓存命中。新项目开新会话,也不该因为选到同一账号就展示“缓存已命中”。需要验证时可以观察官方状态行提供的缓存读取量,以及支持版本的主会话命中率。订阅的额度无须通过主动发送模型请求来探测。[Claude Code 缓存字段](https://code.claude.com/docs/en/statusline#prompt-cache-fields) · [Claude API 的缓存边界](https://platform.claude.com/docs/en/build-with-claude/prompt-caching#cache-storage-and-sharing) | |
| 26 | 新增: | |
| 27 | 新增:## 额度能看到什么 | |
| 28 | 新增: | |
| 29 | 新增:Pro 账号的五小时和七天窗口分别显示用量。账号面板通过客机里的官方 Claude Code 主动查询 `/usage` 的结构化数据,会话状态行作为补充。控制请求 `get_usage` 支持只取订阅额度,跳过本地历史分析。该结构在官方 SDK 中仍标为实验性,字段缺失时应保留旧读数并说明结果。CLI 确认登录和能否取回用量是两个独立结果;有百分比但无重置时间时,只能显示百分比。其他设备也使用同一订阅,查到的数值可能来自 CLI 的近期缓存。[Claude Code 用量查询](https://code.claude.com/docs/en/costs#using-the-usage-command) · [官方 SDK 0.3.314 类型定义](https://unpkg.com/@anthropic-ai/[email protected]/sdk.d.ts) · [状态行字段](https://code.claude.com/docs/en/statusline#available-data) | |
| 30 | 新增: | |
| 31 | 新增:调度先排除已暂停、身份不可用和仍在耗尽窗口内的账号。可分配的账号中优先选占用终端较少的,再比较有时效的额度,负载相同、余量接近时,优先沿用这个项目最近五分钟分配到的账号。其余平手情形按轮次分配。五分钟是本地调度偏好,不代表服务端缓存的寿命。已登录但暂时查不到额度的账号仍可分配终端。没有任何可用账号时向用户说明原因。不回退到隐藏账号、付费 API 或其他出口。零个账号记录的已有安装继续走原终端入口,原有个人数据不需搬迁。独立新登录经官方身份确认后才计入账号池。旧版留下的未绑定草稿仍可以撤销。 | |
| @@ -0,0 +1,60 @@ | ||
| 1 | 新增:# 公证上传超时:原因与可用路径 | |
| 2 | 新增: | |
| 3 | 新增:供 Cage 发行维护者排查本次 `v0.1.4-alpha` 发布使用。查询与验证日期:2026-11-04。 | |
| 4 | 新增: | |
| 5 | 新增:## 结论 | |
| 6 | 新增: | |
| 7 | 新增:当前主机代理数据路径的上传吞吐过低,导致 `notarytool` 的 S3 请求在分片传完前超时。换用标准 S3 客户端后,经同一代理仍慢;仅让该客户端显式直连 S3,原始 App ZIP 在 22.18 秒上传成功,Apple 随后返回 Accepted,审核日志无问题。DMG 同样在 24.51 秒上传成功并获 Accepted。 | |
| 8 | 新增: | |
| 9 | 新增:这组对照支持定位到本次代理数据路径;尚未区分代理核心、节点、节点上游和本机到节点之间的具体瓶颈,不能据此认定 `notarytool` 分片实现存在缺陷,也不能推广为所有代理都不可用。 | |
| 10 | 新增: | |
| 11 | 新增:## 对照证据 | |
| 12 | 新增: | |
| 13 | 新增:所有实验保留原始安装包与签名,使用相同主机。未修改 Cage 环境出口规则。 | |
| 14 | 新增: | |
| 15 | 新增:| 对照 | 上传方式 | 结果 | | |
| 16 | 新增:|---|---|---| | |
| 17 | 新增:| GitHub,1 MiB 相同附件 | 当前主机代理 | 33.08 秒,服务端确认收到 | | |
| 18 | 新增:| GitHub,1 MiB 相同附件 | 仅该命令直连 | 4.56 秒,服务端确认收到 | | |
| 19 | 新增:| App ZIP,50,070,047 字节 | 官方 REST + boto3 单次 PUT,沿用代理 | 468.92 秒仍只读出约 10.35 MB;停止该对照 | | |
| 20 | 新增:| 相同 App ZIP | 相同客户端、单次 PUT,仅 S3 `Config(proxies={})` | 22.18 秒,S3 HTTP 200,Content-MD5 校验通过,ETag 与 MD5 一致 | | |
| 21 | 新增:| 签名 DMG,55,297,096 字节 | 官方 REST + 显式直连单次 PUT | 24.51 秒,S3 确认上传,Apple Accepted | | |
| 22 | 新增: | |
| 23 | 新增:App ZIP 的 SHA-256:`df21bcac8abf9f6027fbaa7bb33723482d8e0a675a6e8652734144c884a7dfd3`。App 公证 ID:`7221e51e-8f1f-4b98-9e49-41a1609d1e09`;DMG 公证 ID:`7cfcb1a9-1791-4cc0-9b49-52b410e26256`。这些产物对应首个候选提交 `670b537`;用户随后要求纳入主分支的两项修复,最终发行产物须重新构建与公证。 | |
| 24 | 新增: | |
| 25 | 新增:本机过程证据在 `docs/test-reports/2026-11-04-release/` 与忽略目录 `_output/notary-debug/`;包含原始测量、服务端确认、公证状态和审核日志。后者不进入公开附件。 | |
| 26 | 新增: | |
| 27 | 新增:## 为什么总表现为分片超时 | |
| 28 | 新增: | |
| 29 | 新增:本机工具为 `notarytool 1.1.2 (41)`。详细日志显示,认证和创建提交返回 HTTP 200,随后工具使用 5 MB 分片,错误发生在 S3 上传阶段,历史错误中的 `completedParts` 为空。API 中的 In Progress 只表示已登记提交,不能证明文件已经完整上传。 | |
| 30 | 新增: | |
| 31 | 新增:命令帮助将 `--timeout` 定义为等待公证结果的期限,它不延长上传请求。工具二进制还包含独立配置 `nt-upload-connection-timeout`;受控实验设为 900 秒后,日志明确确认该值,但上传仍慢,因此停止实验并恢复原先不存在的配置。具体默认上传期限未核定。 | |
| 32 | 新增: | |
| 33 | 新增:标准客户端经代理能持续传出超过 5 MB,证明不存在已证实的“文件传到 5 MB 就被拒绝”的硬限制;在慢链路上,原生工具的单次请求期限更早暴露了问题。传出字节数也不能代替 S3 成功响应。 | |
| 34 | 新增: | |
| 35 | 新增:## 本次采用的替代流程 | |
| 36 | 新增: | |
| 37 | 新增:1. 使用已有本机 App Store Connect API 密钥,生成短期 JWT,仅向 Apple 认证。 | |
| 38 | 新增:2. 将待上传文件的 SHA-256 和名称提交给官方 Notary API,取得该次提交的临时 S3 凭据。 | |
| 39 | 新增:3. 以标准 boto3 单次 PUT 上传同一文件,显式限定本次 S3 客户端的网络路径,提供 Content-Length 与 Content-MD5。收到 S3 HTTP 200 后才记录上传完成。 | |
| 40 | 新增:4. 查询同一个提交 ID,等待 Accepted 并取得审核日志;不通过重复提交轮询状态。 | |
| 41 | 新增:5. 使用系统 `stapler` 附加票据,核对 Developer ID、票据、Gatekeeper 和包内版本,然后生成公开校验清单。 | |
| 42 | 新增: | |
| 43 | 新增:私钥只在本机读取;临时 AWS 凭据不落盘,不写入 GitHub,不放入公开日志。主机和 Cage 的代理开关、节点选择与出口策略保持原状。本次仅改变维护者发行上传客户端的传输路径。凭据、私有路径与签名上传链接不得加入研究正文或公开发行物。 | |
| 44 | 新增: | |
| 45 | 新增:## 一手依据 | |
| 46 | 新增: | |
| 47 | 新增:- [Apple:通过 Web 提交公证](https://developer.apple.com/documentation/notaryapi/submitting-software-for-notarization-over-the-web):支持直接使用 REST API 与标准 S3 客户端,创建提交和上传文件是两个步骤,返回的 S3 凭据有时效。 | |
| 48 | 新增:- [Apple:Submit Software](https://developer.apple.com/documentation/notaryapi/submit-software):提交名称与 SHA-256 对应待上传的精确文件。 | |
| 49 | 新增:- [Apple:自定义公证流程](https://developer.apple.com/documentation/security/customizing-the-notarization-workflow):说明上传、查询、日志与默认 S3 加速端点。 | |
| 50 | 新增:- [AWS:boto3 配置](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/configuration.html):客户端 `Config.proxies` 优先于环境变量。 | |
| 51 | 新增:- [AWS:S3 分片边界](https://docs.aws.amazon.com/AmazonS3/latest/userguide/qfacts.html):普通分片最低 5 MiB,最后一个分片例外;缩小到任意 KB 不能作为通用修复。 | |
| 52 | 新增:- 本机 `xcrun notarytool submit --help`、工具字符串、详细运行日志及实际上传回执:用于核验本机行为。隐藏配置仅用于受控诊断,不作为持久发行配置。 | |
| 53 | 新增: | |
| 54 | 新增:## 最终发行结果 | |
| 55 | 新增: | |
| 56 | 新增:用户要求将主分支后续两项修复一并纳入。最终版本来自 `11d44cabde8e3f560a364a818fa3d63bded658d3`,三平台 CI 全通过;新的 App 上传 21.98 秒、DMG 上传 18.89 秒,两者均获 Accepted,审核日志无问题。最终 App 公证 ID `3d9c5d7c-6b20-4fcc-8969-eee36711db32`,DMG 公证 ID `129453c5-04fd-446d-9bf8-17f753663d50`。 | |
| 57 | 新增: | |
| 58 | 新增:[公开 v0.1.4-alpha](https://github.com/Lee-xeo/Claude-Cage/releases/tag/v0.1.4-alpha) 已发布,[官网](https://lee-xeo.github.io/Claude-Cage/) 已更新。[最终公开验证与部署](https://github.com/Lee-xeo/Claude-Cage/actions/runs/41848921422) 完成三平台安装包的匿名下载、摘要校验,以及 macOS 签名、公证、票据与 Gatekeeper。Windows 使用明确授权的未签名预览包。主机代理选择和临时工具设置均已恢复。 | |
| 59 | 新增: | |
| 60 | 新增:GitHub 匿名元数据接口另发生额度耗尽;发布验证脚本现对指定版本使用公开 SHA256SUMS 与附件响应作为备用清单来源,拒绝任意路径、重复项、错误版本和缺失附件,并继续完整匿名下载验证。该维护改动为 `3ea7973`,不改变已发行应用的源码或字节。 | |
| @@ -0,0 +1,45 @@ | ||
| 1 | 新增:# Cage Windows 代码签名选择 | |
| 2 | 新增: | |
| 3 | 新增:本文供 Cage 维护者选择签名服务、估算费用并定位接入工作。核查日期为 2026-11-04;源码依据当前工作区,HEAD 为 `aebefa5`,包含其他尚未提交的修改。本文只记录调研结果,未购买证书、提交申请、改变签名实现或发布应用。 | |
| 4 | 新增: | |
| 5 | 新增:## 阅读版:安装者会看到什么 | |
| 6 | 新增: | |
| 7 | 新增:公开可信代码签名使 Windows 能验证发布者身份以及文件是否被修改。签名后的新软件仍可能出现 SmartScreen 提示,需要逐步积累信誉;微软明确说明 EV 证书也不再自动获得跳过提示的待遇。自签证书适用于受控测试环境,不能直接解决公众下载时的信任问题。[微软签名选项](https://learn.microsoft.com/en-us/windows/apps/package-and-deploy/code-signing-options)、[SmartScreen 说明](https://learn.microsoft.com/en-us/windows/apps/package-and-deploy/smartscreen-reputation) | |
| 8 | 新增: | |
| 9 | 新增:申请主体决定安装界面显示的发布者:个人证书显示经过验证的个人姓名,组织证书显示组织名称。SSL.com 提供无需注册公司的 IV 个人代码签名证书;具体地区的身份材料能否受理,须由签发方确认。[SSL.com IV 产品](https://www.ssl.com/products/software-integrity/code-signing/iv/) | |
| 10 | 新增: | |
| 11 | 新增:### 可选择的服务 | |
| 12 | 新增: | |
| 13 | 新增:| 方案 | 申请条件与费用 | Cage 的选择条件 | | |
| 14 | 新增:|---|---|---| | |
| 15 | 新增:| 微软 Artifact Signing(原 Trusted Signing) | 个人目前限美国、加拿大;组织支持地区包含美国、加拿大、欧盟、英国、澳大利亚、新西兰、日本、韩国、新加坡、瑞士、挪威、以色列,未列中国大陆。基础套餐 $9.99/月,含 5,000 次签名 | 有符合条件的主体时评估;更换 Azure 部署区域不能代替身份资格 | | |
| 16 | 新增:| SSL.com IV + eSigner | IV 单年证书标价 $129;云签名最低 $20/月,含 20 次,或年付 $180 含 240 次。证书费另计 | 个人希望使用自己的姓名、通过 CI 签名时的候选;需先确认大陆身份受理、最终报价及续签规则 | | |
| 17 | 新增:| SignPath Foundation 免费开源签名 | 要求 OSI 开源许可证、持续维护、已有发布、满足签名政策、构建来源和团队角色要求;证书签发给 SignPath Foundation | Cage 的 MIT 许可证满足其中一项;完整依赖、随附运行时和构建流程仍须审核,不能据此认定已符合全部条件 | | |
| 18 | 新增: | |
| 19 | 新增:表中信息分别来自[微软资格要求](https://learn.microsoft.com/en-us/azure/artifact-signing/quickstart)、[微软价格](https://azure.microsoft.com/en-in/products/artifact-signing)、[SSL.com 证书价格](https://www.ssl.com/products/software-integrity/code-signing/iv/)、[eSigner 价格](https://www.ssl.com/guide/esigner-pricing-for-code-signing/)、[SignPath 条款](https://signpath.org/terms.html)。价格以实际结算为准,不含可能的税费和汇率变化。以 IV 单年证书加 eSigner 年付最低套餐估算,挂牌合计为 $309/年;这不是已确认可受理的报价。 | |
| 20 | 新增: | |
| 21 | 新增:### 从申请到可用的步骤 | |
| 22 | 新增: | |
| 23 | 新增:1. 确定个人或组织申请,以及用户安装时应看到的发布者身份。 | |
| 24 | 新增:2. 确认签发方接受该主体所在地区的材料。个人准备政府签发的身份证明,其他身份、地址及联系方式材料按签发方要求提交;组织按其验证清单准备材料。身份证明应在签发方的验证入口提交。[SSL.com 验证要求](https://www.ssl.com/faqs/ssl-ov-validation-requirements/) | |
| 25 | 新增:3. 选择云签名或兼容的硬件令牌。公开可信 OV/IV 代码签名私钥受硬件保护,不能默认会拿到可导出的 PFX 私钥文件。云签名更适合 Cage 现有的 GitHub 托管构建流程。[SSL.com 私钥存储要求](https://www.ssl.com/guide/esigner-pricing-for-code-signing/) | |
| 26 | 新增:4. 接入签名服务,完成应用、后端、卸载器和安装器签名及时间戳;签名后再计算下载摘要。 | |
| 27 | 新增:5. 在 Windows 验证签名信任、首次安装、保留数据的覆盖安装,以及两个签名版本之间的应用内更新。现有未签名版本仍需手动安装首个签名版本,见 [Windows 更新规则](../windows.md#更新与卸载)。 | |
| 28 | 新增: | |
| 29 | 新增:SignPath 还要求不能以项目证书直接给其他项目的独立二进制签名,但允许在签名安装包中包含未签名的上游开源二进制。Cage 当前会对随附的 Mihomo 可执行文件加签,申请时须明确处理这一差异,并核对 WebView2 等随附组件是否符合其 System Libraries 例外。[SignPath 签名范围与许可条件](https://signpath.org/terms.html) | |
| 30 | 新增: | |
| 31 | 新增:## 证据版:Cage 接入范围 | |
| 32 | 新增: | |
| 33 | 新增:| 当前行为 | 实现位置 | 接入时须处理的事项 | | |
| 34 | 新增:|---|---|---| | |
| 35 | 新增:| Windows CI 从 Secret 还原 PFX、导入当前用户证书库 | `scripts/ci-windows-build.ps1:21`;`.github/workflows/windows-build.yml:104` | 按所选服务改用云签名认证或硬件提供程序;PFX 上传方式不能作为新证书的默认接入假设 | | |
| 36 | 新增:| 使用证书指纹调用 SignTool,并添加 SHA-256 时间戳及验证签名 | `scripts/windows-common.ps1:94` | 保留签名验证,按服务要求配置调用方式和时间戳端点 | | |
| 37 | 新增:| 对窗口程序、后端、Mihomo 加签 | `scripts/build-windows.ps1:127` | 核对签名范围与服务条款;普通构建不消耗生产签名配额 | | |
| 38 | 新增:| NSIS 构建时对卸载器加签;打包后对安装器加签 | `packaging/windows/Cage.nsi:44`;`scripts/package-windows.ps1:68` | 接入必须覆盖卸载器签名命令,不能只替换安装器最后一步 | | |
| 39 | 新增:| 更新器验证 Windows 信任,并比较当前程序与更新包的发布者公钥摘要 | `desktop/windows/Authenticode.cs:25`、`:32`、`:37` | 服务切换、换钥、证书续签时验证升级连续性;同名发布者不足以通过该检查 | | |
| 40 | 新增: | |
| 41 | 新增:按当前流程,每个完整签名构建包含 5 个签名对象,最低 20 次/月套餐理论上覆盖 4 次完整构建,重试和额外测试另计。此计数来自脚本,不代表签名服务对失败、重试或批次请求的最终计费规则。 | |
| 42 | 新增: | |
| 43 | 新增:微软 Artifact Signing 使用短期证书并自动管理证书与密钥生命周期。若选择该服务,须核对不同签名日期的公钥是否相同,并处理 Cage 当前公钥固定规则与轮换之间的关系;不能仅凭一次安装成功认定后续更新可用。[微软证书管理](https://learn.microsoft.com/en-us/azure/artifact-signing/concept-certificate-management) | |
| 44 | 新增: | |
| 45 | 新增:本次没有修改打包流程、接口或数据格式,因此 macOS 和 Linux 无实现变更。Windows 云签名、硬件签名及签名版本升级均未实测。后续实现需同步检查共用发行就绪检查、三平台工作流及说明,继续保留明确发版触发点。 | |
| @@ -20,6 +20,12 @@ | ||
| 20 | 20 | |
| 21 | 21 | **提示缺少代理核心。** 完整应用随附 Mihomo。重新安装对应平台的完整安装包,不要只拷贝其中的命令行文件。源码构建者按[贡献指南](../CONTRIBUTING.md)构建整个应用。 |
| 22 | 22 | |
| 23 | 新增:## 已有账户却再次显示创建账户 | |
| 24 | 新增: | |
| 25 | 新增:创建页面表示当前配置目录没有账户文件。先确认是否通过另一套配置启动:macOS、Windows 和 Linux 默认读取用户主目录下的 `.claude-cage/config.json`;`CLAUDE_CAGE_CONFIG` 可以指定另一套独立配置。开发启动与已安装应用使用不同目录时,原账户和数据可能仍在原目录。 | |
| 26 | 新增: | |
| 27 | 新增:保留当前目录和原目录,检查原目录是否同时包含 `account.json`、`favorites.json` 及 `state/`。不要创建新账户、清空配置或仅复制账户文件;浏览器历史、网站登录状态及其他环境文件还依赖同一套虚拟磁盘。迁移前保存工作并停止两套环境与后台,完整备份后再迁移;账户文件中的快捷登录绑定与原路径关联,迁移后可能需要用原密码解锁并重新开启快捷登录。找不到原文件时,应从备份恢复并排查删除原因。 | |
| 28 | 新增: | |
| 23 | 29 | ## 启动前的 Git 检查未通过 |
| 24 | 30 | |
| 25 | 31 | 点击“启动 Cage 环境”后,Cage 会先检查本机的 Git。确认未安装 Git 时会继续,不要求为使用 Cage 安装开发工具;已安装的 Git 需要启用裸仓库保护。 |
| @@ -102,7 +108,9 @@ Cage 不自动读取主机上的 Claude 登录。请在 Cage 终端运行 `claud | ||
| 102 | 108 | | 现象 | 处理方式 | |
| 103 | 109 | |---|---| |
| 104 | 110 | | `Ctrl+C` 没有复制 | 终端中它表示中断命令。选中文本后,macOS 用 `⌘C`,Windows/Linux 用 `Ctrl+Shift+C` 复制。 | |
| 111 | 新增:| 在终端里拖选后复制,主机仍粘贴出旧内容 | 有些终端程序会接管鼠标。macOS 按住 `Option` 拖选,松开后按 `⌘C`。Windows/Linux 按住 `Shift` 拖选,松开后按 `Ctrl+Shift+C`。 | | |
| 105 | 112 | | 粘贴无效 | 先点击目标输入框,再粘贴。普通浏览器可使用“文本传递”面板;只支持纯文本。 | |
| 113 | 新增:| 网页复制按钮显示成功,本机粘贴仍是旧内容 | 保持网页和 Cage 窗口在前台重试。已有页面若改写了复制 API,可刷新后再试;复杂 DOM 选区、图片、富文本或超长文字可使用复制快捷键及“文本传递”面板。 | | |
| 106 | 114 | | 停止后旧终端不见了 | 停止虚拟机会结束进程。磁盘和登录态保留,但需要新建终端。 | |
| 107 | 115 | | 关掉窗口后任务还在运行 | 关闭窗口保留环境;需要结束时选择“停止环境并退出”。 | |
| 108 | 116 | | 修改设置后无法正常使用 | “设置 → 环境与恢复”可恢复上一份配置;此操作需要停止并重启环境,已结束的终端不能恢复。 | |
| @@ -6,10 +6,13 @@ import { readFileSync, writeFileSync, mkdirSync, existsSync, rmSync, constants } | ||
| 6 | 6 | import { open } from "node:fs/promises"; |
| 7 | 7 | import http from "node:http"; |
| 8 | 8 | import { auditBrowser } from "./browser-audit.mjs"; |
| 9 | 新增:import { BrowserVault } from "./browser-vault.mjs"; | |
| 10 | 新增:import { LoginBrowser } from "./browser-login.mjs"; | |
| 11 | 新增:import { BrowserClipboard } from "./browser-clipboard.mjs"; | |
| 9 | 12 | import { nativeInput } from "./native-input.mjs"; |
| 10 | 13 | import { DownloadManager } from "./browser-downloads.mjs"; |
| 11 | 14 | import { UploadManager, uploadLimit } from "./browser-uploads.mjs"; |
| 12 | 删除:import { timingSafeEqual } from "node:crypto"; | |
| 15 | 新增:import { createHash, timingSafeEqual } from "node:crypto"; | |
| 13 | 16 | |
| 14 | 17 | const config = JSON.parse( |
| 15 | 18 | readFileSync("/etc/claude-cage/browser-control.json", "utf8"), |
| @@ -26,7 +29,7 @@ try { | ||
| 26 | 29 | } catch {} |
| 27 | 30 | function rememberSelection() { |
| 28 | 31 | const tab = targets.get(activeId); |
| 29 | 删除: if (tab) | |
| 32 | 新增: if (tab && !tab.login) | |
| 30 | 33 | try { |
| 31 | 34 | writeFileSync(selectionFile, JSON.stringify({ url: tab.url }), { |
| 32 | 35 | mode: 0o600, |
| @@ -35,7 +38,15 @@ function rememberSelection() { | ||
| 35 | 38 | } |
| 36 | 39 | const downloadPath = "/home/cage-browser/Downloads"; |
| 37 | 40 | mkdirSync(downloadPath, { recursive: true }); |
| 41 | 新增:const splitDirectory = "/usr/local/lib/cage-split"; | |
| 42 | 新增:const extensionId = createHash("sha256").update(splitDirectory).digest("hex").slice(0, 32) | |
| 43 | 新增: .replace(/./g, c => String.fromCharCode(97 + parseInt(c, 16))); | |
| 44 | 新增:const splitURL = `chrome-extension://${extensionId}/control.html`; | |
| 45 | 新增:let splitView = null, splitSession, splitOpening, resizeTimer; | |
| 46 | 新增:const favicons = new Map(), faviconRequests = new Map(), documents = new Map(); | |
| 47 | 新增: | |
| 38 | 48 | const flags = [ |
| 49 | 新增: `--load-extension=${splitDirectory}`, | |
| 39 | 50 | "--user-data-dir=/home/cage-browser/profile", |
| 40 | 51 | "--remote-debugging-pipe", |
| 41 | 52 | // The pipe manages tabs for a human-operated browser. Keep it private while |
| @@ -63,9 +74,16 @@ let sequence = 0, | ||
| 63 | 74 | let shuttingDown = false; |
| 64 | 75 | const events = new Set(); |
| 65 | 76 | const auditContexts = new Set(); |
| 77 | 新增:const loginBrowser = new LoginBrowser(cdp); | |
| 66 | 78 | const pending = new Map(), |
| 67 | 79 | targets = new Map(), |
| 68 | 80 | sessions = new Map(); |
| 81 | 新增:const browserClipboard = new BrowserClipboard(cdp, ({ id, text, context }) => { | |
| 82 | 新增: if (id !== activeId || !targets.has(id)) return; | |
| 83 | 新增: const payload = "event: clipboard\ndata: " + JSON.stringify({ id, text, context }) + "\n\n"; | |
| 84 | 新增: for (const stream of events) stream.write(payload); | |
| 85 | 新增:}); | |
| 86 | 新增:const vault = new BrowserVault({ cdp, active: () => activeId, tab: id => targets.get(id) }); | |
| 69 | 87 | const downloads = new DownloadManager({ |
| 70 | 88 | directory: "/home/cage-browser", |
| 71 | 89 | changed: () => broadcastState(), |
| @@ -124,15 +142,33 @@ chrome.stdio[4].on("data", (chunk) => { | ||
| 124 | 142 | : call.resolve(event.result); |
| 125 | 143 | continue; |
| 126 | 144 | } |
| 145 | 新增: vault.event(event); | |
| 127 | 146 | const p = event.params || {}; |
| 147 | 新增: browserClipboard.event(event); | |
| 148 | 新增: if (event.sessionId === splitSession && event.method === "Runtime.bindingCalled" && | |
| 149 | 新增: p.name === "cageFaviconChanged") refreshFavicon(p.payload); | |
| 150 | 新增: if (event.sessionId === splitSession && event.method === "Runtime.bindingCalled" && | |
| 151 | 新增: p.name === "cagePaneActivated" && splitView && | |
| 152 | 新增: [splitView.left, splitView.right].includes(p.payload) && p.payload !== activeId) { | |
| 153 | 新增: activeId = p.payload; | |
| 154 | 新增: rememberSelection(); | |
| 155 | 新增: broadcastState(true); | |
| 156 | 新增: } | |
| 157 | 新增: if (event.sessionId === splitSession && event.method === "Runtime.bindingCalled" && | |
| 158 | 新增: p.name === "cagePaneSeparated" && splitView && [splitView.left, splitView.right].includes(p.payload)) { | |
| 159 | 新增: splitView = null; | |
| 160 | 新增: broadcastState(); | |
| 161 | 新增: } | |
| 162 | 新增: if (splitView && ["Page.frameResized", "Page.frameNavigated", "Page.navigatedWithinDocument"].includes(event.method)) | |
| 163 | 新增: scheduleSplitMeasure(); | |
| 128 | 164 | if ( |
| 129 | 165 | event.method === "Target.targetCreated" || |
| 130 | 166 | event.method === "Target.targetInfoChanged" |
| 131 | 167 | ) { |
| 132 | 168 | const t = p.targetInfo; |
| 133 | 删除: if (t.type === "page" && !auditContexts.has(t.browserContextId)) { | |
| 169 | 新增: if (t.type === "page" && t.url !== splitURL && !auditContexts.has(t.browserContextId)) { | |
| 134 | 170 | const fresh = !targets.has(t.targetId); |
| 135 | 删除: targets.set(t.targetId, t); | |
| 171 | 新增: targets.set(t.targetId, loginBrowser.tab(t, targets.get(t.targetId))); | |
| 136 | 172 | if (fresh) void session(t.targetId).catch(() => {}); |
| 137 | 173 | if (t.targetId === activeId) rememberSelection(); |
| 138 | 174 | broadcastState(); |
| @@ -143,7 +179,13 @@ chrome.stdio[4].on("data", (chunk) => { | ||
| 143 | 179 | } |
| 144 | 180 | if (event.method === "Target.targetDestroyed") { |
| 145 | 181 | if (!targets.has(p.targetId)) continue; |
| 182 | 新增: vault.remove(p.targetId); | |
| 146 | 183 | targets.delete(p.targetId); |
| 184 | 新增: browserClipboard.detachTab(p.targetId); | |
| 185 | 新增: favicons.delete(p.targetId); | |
| 186 | 新增: documents.delete(p.targetId); | |
| 187 | 新增: faviconRequests.delete(p.targetId); | |
| 188 | 新增: if (splitView && [splitView.left, splitView.right].includes(p.targetId)) splitView = null; | |
| 147 | 189 | uploads.cancelTab(p.targetId); |
| 148 | 190 | for (const [sid, tab] of uploadSessions) if (tab === p.targetId) uploadSessions.delete(sid); |
| 149 | 191 | sessions.delete(p.targetId); |
| @@ -157,6 +199,13 @@ chrome.stdio[4].on("data", (chunk) => { | ||
| 157 | 199 | downloads.begin(p.guid, p.suggestedFilename); |
| 158 | 200 | if (event.method === "Browser.downloadProgress") downloads.progress(p); |
| 159 | 201 | const uploadTab = uploadSessions.get(event.sessionId); |
| 202 | 新增: if (uploadTab && event.method === "Page.frameNavigated" && !p.frame?.parentId) { | |
| 203 | 新增: documents.set(uploadTab, p.frame.loaderId); | |
| 204 | 新增: favicons.delete(uploadTab); | |
| 205 | 新增: faviconRequests.delete(uploadTab); | |
| 206 | 新增: broadcastState(); | |
| 207 | 新增: } | |
| 208 | 新增: if (uploadTab && event.method === "Page.loadEventFired") refreshFavicon(uploadTab); | |
| 160 | 209 | if (uploadTab && event.method === "Page.fileChooserOpened") |
| 161 | 210 | void uploads.opened(uploadTab, event.sessionId, p).catch(() => {}); |
| 162 | 211 | if (uploadTab && event.method === "Page.frameNavigated" && !p.frame?.parentId) |
| @@ -185,11 +234,109 @@ async function session(id) { | ||
| 185 | 234 | uploadSessions.set(r.sessionId, id); |
| 186 | 235 | await cdp("Page.enable", {}, r.sessionId); |
| 187 | 236 | await cdp("Page.setInterceptFileChooserDialog", { enabled: true }, r.sessionId); |
| 237 | 新增: await browserClipboard.attach(r.sessionId, id).then(result => { | |
| 238 | 新增: if (result?.skipped.length) console.warn("Browser copy observer skipped a modified or replaced document; reload the page to enable copy buttons."); | |
| 239 | 新增: }).catch(() => console.warn("Browser copy observer unavailable for this page.")); | |
| 240 | 新增: await vault.attach(id, r.sessionId).catch(() => {}); | |
| 188 | 241 | return r.sessionId; |
| 189 | 242 | }).catch(error => { sessions.delete(id); throw error; }), |
| 190 | 243 | ); |
| 191 | 244 | return sessions.get(id); |
| 192 | 245 | } |
| 246 | 新增:function scheduleSplitMeasure() { | |
| 247 | 新增: clearTimeout(resizeTimer); | |
| 248 | 新增: resizeTimer = setTimeout(async () => { | |
| 249 | 新增: const pair = splitView; | |
| 250 | 新增: if (!pair) return; | |
| 251 | 新增: try { | |
| 252 | 新增: const pages = await Promise.all([pair.left, pair.right].map(async id => { | |
| 253 | 新增: const sid = await session(id); | |
| 254 | 新增: const [metrics, history] = await Promise.all([ | |
| 255 | 新增: cdp("Page.getLayoutMetrics", {}, sid), cdp("Page.getNavigationHistory", {}, sid), | |
| 256 | 新增: ]); | |
| 257 | 新增: return { width: metrics.cssLayoutViewport.clientWidth, back: history.currentIndex > 0, | |
| 258 | 新增: forward: history.currentIndex < history.entries.length - 1 }; | |
| 259 | 新增: })); | |
| 260 | 新增: if (pair !== splitView) return; | |
| 261 | 新增: const fraction = pages[0].width / (pages[0].width + pages[1].width); | |
| 262 | 新增: if (fraction > 0 && fraction < 1) pair.fraction = fraction; | |
| 263 | 新增: pair.history = Object.fromEntries([pair.left, pair.right].map((id, index) => | |
| 264 | 新增: [id, { back: pages[index].back, forward: pages[index].forward }])); | |
| 265 | 新增: broadcastState(); | |
| 266 | 新增: } catch { /* A closing tab may already have lost its renderer. */ } | |
| 267 | 新增: }, 80); | |
| 268 | 新增:} | |
| 269 | 新增: | |
| 270 | 新增:async function splitController() { | |
| 271 | 新增: if (splitSession) return splitSession; | |
| 272 | 新增: if (splitOpening) return splitOpening; | |
| 273 | 新增: splitOpening = openSplitController().finally(() => { splitOpening = null; }); | |
| 274 | 新增: return splitOpening; | |
| 275 | 新增:} | |
| 276 | 新增: | |
| 277 | 新增:async function openSplitController() { | |
| 278 | 新增: const { targetId } = await cdp("Target.createTarget", { url: splitURL, hidden: true, background: true }); | |
| 279 | 新增: try { | |
| 280 | 新增: const { sessionId } = await cdp("Target.attachToTarget", { targetId, flatten: true }); | |
| 281 | 新增: await cdp("Runtime.enable", {}, sessionId); | |
| 282 | 新增: await cdp("Runtime.addBinding", { name: "cagePaneActivated" }, sessionId); | |
| 283 | 新增: await cdp("Runtime.addBinding", { name: "cagePaneSeparated" }, sessionId); | |
| 284 | 新增: await cdp("Runtime.addBinding", { name: "cageFaviconChanged" }, sessionId); | |
| 285 | 新增: const loaded = await cdp("Runtime.evaluate", { awaitPromise: true, returnByValue: true, | |
| 286 | 新增: expression: `new Promise(resolve => { | |
| 287 | 新增: const ready = () => resolve(typeof setCageSplit === "function"); | |
| 288 | 新增: document.readyState !== "complete" ? addEventListener("DOMContentLoaded", ready, { once: true }) : ready(); | |
| 289 | 新增: })` }, sessionId); | |
| 290 | 新增: if (!loaded.result.value) throw new Error("Split controller unavailable"); | |
| 291 | 新增: splitSession = sessionId; | |
| 292 | 新增: for (const id of targets.keys()) refreshFavicon(id); | |
| 293 | 新增: return sessionId; | |
| 294 | 新增: } catch (error) { | |
| 295 | 新增: await cdp("Target.closeTarget", { targetId }).catch(() => {}); | |
| 296 | 新增: throw error; | |
| 297 | 新增: } | |
| 298 | 新增:} | |
| 299 | 新增: | |
| 300 | 新增:function refreshFavicon(id) { | |
| 301 | 新增: if (!targets.has(id) || !splitSession) return; | |
| 302 | 新增: const request = {}; | |
| 303 | 新增: faviconRequests.set(id, request); | |
| 304 | 新增: void cdp("Runtime.evaluate", { | |
| 305 | 新增: expression: `readCageFavicon(${JSON.stringify(id)})`, awaitPromise: true, returnByValue: true, | |
| 306 | 新增: }, splitSession).then(({ result }) => { | |
| 307 | 新增: if (faviconRequests.get(id) !== request) return; | |
| 308 | 新增: const icon = result.value; | |
| 309 | 新增: if (!icon || icon.url !== targets.get(id)?.url || typeof icon.favicon !== "string" || | |
| 310 | 新增: icon.favicon.length > 8192 || (icon.favicon && !/^data:image\/png;base64,[A-Za-z0-9+/=]+$/.test(icon.favicon))) return; | |
| 311 | 新增: if ((favicons.get(id) || "") === icon.favicon) return; | |
| 312 | 新增: favicons.set(id, icon.favicon); | |
| 313 | 新增: broadcastState(); | |
| 314 | 新增: }).catch(() => {}).finally(() => { | |
| 315 | 新增: if (faviconRequests.get(id) === request) faviconRequests.delete(id); | |
| 316 | 新增: }); | |
| 317 | 新增:} | |
| 318 | 新增: | |
| 319 | 新增:async function setSplit({ left, right, id }) { | |
| 320 | 新增: if (left && (!targets.has(left) || !targets.has(right) || left === right || | |
| 321 | 新增: ![left, right].includes(id))) throw new Error("Invalid split tabs"); | |
| 322 | 新增: const sid = await splitController(); | |
| 323 | 新增: const result = await cdp("Runtime.evaluate", { awaitPromise: true, returnByValue: true, | |
| 324 | 新增: expression: `setCageSplit(${JSON.stringify(left || "")}, ${JSON.stringify(right || "")})`, | |
| 325 | 新增: }, sid); | |
| 326 | 新增: splitView = null; | |
| 327 | 新增: if (result.exceptionDetails) { | |
| 328 | 新增: broadcastState(); | |
| 329 | 新增: throw new Error("Cannot split these Chromium tabs"); | |
| 330 | 新增: } | |
| 331 | 新增: if (left) { | |
| 332 | 新增: splitView = { left, right, fraction: 0.5 }; | |
| 333 | 新增: scheduleSplitMeasure(); | |
| 334 | 新增: } | |
| 335 | 新增: if (id && targets.has(id)) await activate(id); | |
| 336 | 新增: else broadcastState(); | |
| 337 | 新增: return { split: splitView }; | |
| 338 | 新增:} | |
| 339 | 新增: | |
| 193 | 340 | async function activate(id, focus = false) { |
| 194 | 341 | if (!targets.has(id)) throw new Error("Tab no longer exists"); |
| 195 | 342 | // Restored background tabs may have no live renderer until activated. |
| @@ -278,7 +425,8 @@ async function restartEditor(workspace) { | ||
| 278 | 425 | async function tabState() { |
| 279 | 426 | const { targetInfos } = await cdp("Target.getTargets"); |
| 280 | 427 | for (const tab of targetInfos) |
| 281 | 删除: if (tab.type === "page" && !auditContexts.has(tab.browserContextId)) targets.set(tab.targetId, tab); | |
| 428 | 新增: if (tab.type === "page" && tab.url !== splitURL && !auditContexts.has(tab.browserContextId)) | |
| 429 | 新增: targets.set(tab.targetId, loginBrowser.tab(tab, targets.get(tab.targetId))); | |
| 282 | 430 | let back = false, |
| 283 | 431 | forward = false; |
| 284 | 432 | if (activeId && targets.has(activeId)) { |
| @@ -295,6 +443,7 @@ async function tabState() { | ||
| 295 | 443 | return { ...publicState(), back, forward }; |
| 296 | 444 | } |
| 297 | 445 | function displayTitle(tab) { |
| 446 | 新增: if (tab.login) return "账号授权"; | |
| 298 | 447 | if (tab.url === "about:blank") return "新标签页"; |
| 299 | 448 | const title = tab.title; |
| 300 | 449 | if ( |
| @@ -313,12 +462,15 @@ function displayTitle(tab) { | ||
| 313 | 462 | function publicState() { |
| 314 | 463 | return { |
| 315 | 464 | active: activeId, |
| 465 | 新增: split: splitView, | |
| 316 | 466 | downloads: downloads.snapshot(), |
| 317 | 467 | uploads: uploads.snapshot(), |
| 318 | 468 | tabs: [...targets.values()].map((t) => ({ |
| 319 | 469 | id: t.targetId, |
| 320 | 470 | title: displayTitle(t), |
| 321 | 471 | url: t.url, |
| 472 | 新增: document: documents.get(t.targetId) || "", | |
| 473 | 新增: favicon: favicons.get(t.targetId) || "", | |
| 322 | 474 | kind: t.url.startsWith("http://127.0.0.1:18080/") ? "editor" : "web", |
| 323 | 475 | workspace: t.url.startsWith("http://127.0.0.1:18080/") ? new URL(t.url).searchParams.get("folder") || config.workspace : undefined, |
| 324 | 476 | })), |
| @@ -337,7 +489,7 @@ async function resizeDisplay(width, height) { | ||
| 337 | 489 | if ( |
| 338 | 490 | !Number.isInteger(width) || |
| 339 | 491 | !Number.isInteger(height) || |
| 340 | 删除: width < 640 || | |
| 492 | 新增: width < 320 || | |
| 341 | 493 | height < 480 || |
| 342 | 494 | width > 8192 || |
| 343 | 495 | height > 8192 |
| @@ -488,6 +640,20 @@ const server = http.createServer(async (req, res) => { | ||
| 488 | 640 | return; |
| 489 | 641 | } |
| 490 | 642 | const result = await mutate(async () => { |
| 643 | 新增: if (req.url === "/vault") { | |
| 644 | 新增: try { return await vault.request(input); } | |
| 645 | 新增: catch (error) { return { vaultError: error.message }; } | |
| 646 | 新增: } | |
| 647 | 新增: if (req.url === "/login-open") { | |
| 648 | 新增: return loginBrowser.open(input.login, input.url, async tab => { | |
| 649 | 新增: if (!targets.has(tab.targetId)) targets.set(tab.targetId, loginBrowser.tab(tab)); | |
| 650 | 新增: await activate(tab.targetId, true); | |
| 651 | 新增: }); | |
| 652 | 新增: } | |
| 653 | 新增: if (req.url === "/login-finish") { | |
| 654 | 新增: await loginBrowser.finish(input.login); | |
| 655 | 新增: return { ok: true }; | |
| 656 | 新增: } | |
| 491 | 657 | if (req.url === "/homepage") { |
| 492 | 658 | const url = checkedURL(input.url); |
| 493 | 659 | if (url === "about:blank") throw new Error("Homepage must be an HTTP(S) URL"); |
| @@ -501,6 +667,7 @@ const server = http.createServer(async (req, res) => { | ||
| 501 | 667 | } |
| 502 | 668 | return { ok: true }; |
| 503 | 669 | } |
| 670 | 新增: if (req.url === "/split") return setSplit(input); | |
| 504 | 671 | if (req.url === "/resize") |
| 505 | 672 | return resizeDisplay(input.width, input.height); |
| 506 | 673 | if (req.url === "/new") return newTab(input.url || undefined); |
| @@ -515,6 +682,16 @@ const server = http.createServer(async (req, res) => { | ||
| 515 | 682 | const id = input.id || activeId; |
| 516 | 683 | if (!targets.has(id)) throw new Error("Tab no longer exists"); |
| 517 | 684 | switch (req.url) { |
| 685 | 新增: case "/copy-context": { | |
| 686 | 新增: if (!/^[a-f0-9]{32}$/.test(input.context || "") || id !== activeId) | |
| 687 | 新增: throw new Error("Copy target changed"); | |
| 688 | 新增: const ids = splitView ? [splitView.left, splitView.right] : [id]; | |
| 689 | 新增: for (const tab of ids) { | |
| 690 | 新增: await session(tab); | |
| 691 | 新增: await browserClipboard.setContext(tab, input.context); | |
| 692 | 新增: } | |
| 693 | 新增: break; | |
| 694 | 新增: } | |
| 518 | 695 | case "/paste-image": |
| 519 | 696 | if (input.id !== activeId) throw new Error("Image target changed"); |
| 520 | 697 | await pasteImage(input.png); |
| @@ -572,7 +749,7 @@ server.listen(18500, "127.0.0.1"); | ||
| 572 | 749 | await cdp("Target.setDiscoverTargets", { discover: true }); |
| 573 | 750 | const { targetInfos } = await cdp("Target.getTargets"); |
| 574 | 751 | for (const t of targetInfos) |
| 575 | 删除: if (t.type === "page") targets.set(t.targetId, t); | |
| 752 | 新增: if (t.type === "page" && t.url !== splitURL) targets.set(t.targetId, t); | |
| 576 | 753 | await cdp("Browser.setDownloadBehavior", { |
| 577 | 754 | behavior: "allowAndName", |
| 578 | 755 | downloadPath, |
| @@ -584,6 +761,7 @@ server.listen(18500, "127.0.0.1"); | ||
| 584 | 761 | [...targets.values()].find((t) => t.url === restoreURL)?.targetId || |
| 585 | 762 | [...targets.keys()][0], |
| 586 | 763 | ); |
| 764 | 新增: await setSplit({}).catch(() => {}); | |
| 587 | 765 | ready = true; |
| 588 | 766 | })().catch(error => { |
| 589 | 767 | console.error("Browser startup failed:", error.message); |
| @@ -0,0 +1,592 @@ | ||
| 1 | 新增:import { randomBytes } from "node:crypto"; | |
| 2 | 新增: | |
| 3 | 新增:// This runs before site scripts, in each new document's main world. The binding | |
| 4 | 新增:// and token stay in the closure. Existing documents expose only captured | |
| 5 | 新增:// function references to CDP for native-code verification before installation. | |
| 6 | 新增:function prepareCopies(bindingName, token, contextSetter, limit) { | |
| 7 | 新增: const emit = globalThis[bindingName]; | |
| 8 | 新增: delete globalThis[bindingName]; | |
| 9 | 新增: if (typeof emit !== "function") return; | |
| 10 | 新增: const apply = Reflect.apply; | |
| 11 | 新增: const define = Object.defineProperty; | |
| 12 | 新增: const descriptor = Object.getOwnPropertyDescriptor; | |
| 13 | 新增: const stringify = JSON.stringify; | |
| 14 | 新增: const string = String; | |
| 15 | 新增: const then = Promise.prototype.then; | |
| 16 | 新增: const hasFocus = Document.prototype.hasFocus; | |
| 17 | 新增: const visibility = descriptor(Document.prototype, "visibilityState").get; | |
| 18 | 新增: const activated = descriptor(UserActivation.prototype, "isActive").get; | |
| 19 | 新增: const userActivation = descriptor(Navigator.prototype, "userActivation").get; | |
| 20 | 新增: const addListener = EventTarget.prototype.addEventListener; | |
| 21 | 新增: const prevented = descriptor(Event.prototype, "defaultPrevented").get; | |
| 22 | 新增: const clipboardData = descriptor( | |
| 23 | 新增: ClipboardEvent.prototype, | |
| 24 | 新增: "clipboardData", | |
| 25 | 新增: ).get; | |
| 26 | 新增: const blobText = Blob.prototype.text; | |
| 27 | 新增: const lower = String.prototype.toLowerCase; | |
| 28 | 新增: const exec = Document.prototype.execCommand; | |
| 29 | 新增: const setData = DataTransfer.prototype.setData; | |
| 30 | 新增: const clearData = DataTransfer.prototype.clearData; | |
| 31 | 新增: const writeText = globalThis.Clipboard?.prototype.writeText; | |
| 32 | 新增: const write = globalThis.Clipboard?.prototype.write; | |
| 33 | 新增: const iterator = Symbol.iterator; | |
| 34 | 新增: const getType = globalThis.ClipboardItem?.prototype.getType; | |
| 35 | 新增: const clipboardPrototype = globalThis.Clipboard?.prototype; | |
| 36 | 新增: const transferPrototype = DataTransfer.prototype; | |
| 37 | 新增: const documentPrototype = Document.prototype; | |
| 38 | 新增: const activeElement = descriptor(Document.prototype, "activeElement").get; | |
| 39 | 新增: const shadowActiveElement = descriptor( | |
| 40 | 新增: ShadowRoot.prototype, | |
| 41 | 新增: "activeElement", | |
| 42 | 新增: ).get; | |
| 43 | 新增: const shadowRoot = descriptor(Element.prototype, "shadowRoot").get; | |
| 44 | 新增: const tagName = descriptor(Element.prototype, "tagName").get; | |
| 45 | 新增: const inputType = descriptor(HTMLInputElement.prototype, "type").get; | |
| 46 | 新增: const inputStart = descriptor( | |
| 47 | 新增: HTMLInputElement.prototype, | |
| 48 | 新增: "selectionStart", | |
| 49 | 新增: ).get; | |
| 50 | 新增: const inputEnd = descriptor(HTMLInputElement.prototype, "selectionEnd").get; | |
| 51 | 新增: const textareaStart = descriptor( | |
| 52 | 新增: HTMLTextAreaElement.prototype, | |
| 53 | 新增: "selectionStart", | |
| 54 | 新增: ).get; | |
| 55 | 新增: const textareaEnd = descriptor( | |
| 56 | 新增: HTMLTextAreaElement.prototype, | |
| 57 | 新增: "selectionEnd", | |
| 58 | 新增: ).get; | |
| 59 | 新增: const getSelection = Document.prototype.getSelection; | |
| 60 | 新增: const selectionText = Selection.prototype.toString; | |
| 61 | 新增: const nativeFunctions = { | |
| 62 | 新增: "": emit, | |
| 63 | 新增: apply, | |
| 64 | 新增: defineProperty: define, | |
| 65 | 新增: getOwnPropertyDescriptor: descriptor, | |
| 66 | 新增: stringify, | |
| 67 | 新增: String: string, | |
| 68 | 新增: then, | |
| 69 | 新增: hasFocus, | |
| 70 | 新增: "get visibilityState": visibility, | |
| 71 | 新增: "get isActive": activated, | |
| 72 | 新增: "get userActivation": userActivation, | |
| 73 | 新增: addEventListener: addListener, | |
| 74 | 新增: "get defaultPrevented": prevented, | |
| 75 | 新增: "get clipboardData": clipboardData, | |
| 76 | 新增: text: blobText, | |
| 77 | 新增: toLowerCase: lower, | |
| 78 | 新增: execCommand: exec, | |
| 79 | 新增: setData, | |
| 80 | 新增: clearData, | |
| 81 | 新增: Symbol, | |
| 82 | 新增: writeText, | |
| 83 | 新增: write, | |
| 84 | 新增: getType, | |
| 85 | 新增: "get activeElement": activeElement, | |
| 86 | 新增: "get activeElement#shadow": shadowActiveElement, | |
| 87 | 新增: "get shadowRoot": shadowRoot, | |
| 88 | 新增: "get tagName": tagName, | |
| 89 | 新增: "get type": inputType, | |
| 90 | 新增: "get selectionStart#input": inputStart, | |
| 91 | 新增: "get selectionEnd#input": inputEnd, | |
| 92 | 新增: "get selectionStart#textarea": textareaStart, | |
| 93 | 新增: "get selectionEnd#textarea": textareaEnd, | |
| 94 | 新增: getSelection, | |
| 95 | 新增: toString: selectionText, | |
| 96 | 新增: }; | |
| 97 | 新增: const plain = (value) => { | |
| 98 | 新增: const type = apply(lower, value, []); | |
| 99 | 新增: return type === "text" || type === "text/plain"; | |
| 100 | 新增: }; | |
| 101 | 新增: return { | |
| 102 | 新增: nativeFunctions, | |
| 103 | 新增: install() { | |
| 104 | 新增: const activation = apply(userActivation, navigator, []); | |
| 105 | 新增: let epoch = 0; | |
| 106 | 新增: let operation; | |
| 107 | 新增: let context = ""; | |
| 108 | 新增: // Only future copies use a newly supplied host interaction context. | |
| 109 | 新增: define(globalThis, contextSetter, { | |
| 110 | 新增: value: function (value) { | |
| 111 | 新增: if (typeof value === "string" && value.length <= 64) context = value; | |
| 112 | 新增: }, | |
| 113 | 新增: }); | |
| 114 | 新增: const current = () => | |
| 115 | 新增: apply(hasFocus, document, []) && | |
| 116 | 新增: apply(visibility, document, []) === "visible"; | |
| 117 | 新增: const begin = () => | |
| 118 | 新增: context && current() && apply(activated, activation, []) | |
| 119 | 新增: ? { epoch, context } | |
| 120 | 新增: : null; | |
| 121 | 新增: const selectedControlText = () => { | |
| 122 | 新增: let element = apply(activeElement, document, []); | |
| 123 | 新增: let root; | |
| 124 | 新增: while (element && (root = apply(shadowRoot, element, []))) | |
| 125 | 新增: element = apply(shadowActiveElement, root, []); | |
| 126 | 新增: if (!element) return; | |
| 127 | 新增: const tag = apply(tagName, element, []); | |
| 128 | 新增: if (tag !== "TEXTAREA" && tag !== "INPUT") return; | |
| 129 | 新增: if (tag === "INPUT") { | |
| 130 | 新增: const type = apply(inputType, element, []); | |
| 131 | 新增: if ( | |
| 132 | 新增: type !== "text" && | |
| 133 | 新增: type !== "search" && | |
| 134 | 新增: type !== "url" && | |
| 135 | 新增: type !== "tel" | |
| 136 | 新增: ) | |
| 137 | 新增: return; | |
| 138 | 新增: } | |
| 139 | 新增: const start = apply( | |
| 140 | 新增: tag === "INPUT" ? inputStart : textareaStart, | |
| 141 | 新增: element, | |
| 142 | 新增: [], | |
| 143 | 新增: ); | |
| 144 | 新增: const end = apply( | |
| 145 | 新增: tag === "INPUT" ? inputEnd : textareaEnd, | |
| 146 | 新增: element, | |
| 147 | 新增: [], | |
| 148 | 新增: ); | |
| 149 | 新增: if (start === null || end <= start) return; | |
| 150 | 新增: const selection = apply(getSelection, document, []); | |
| 151 | 新增: return selection && apply(selectionText, selection, []); | |
| 152 | 新增: }; | |
| 153 | 新增: const send = (text, started) => { | |
| 154 | 新增: if ( | |
| 155 | 新增: started === null || | |
| 156 | 新增: epoch !== started.epoch || | |
| 157 | 新增: !current() || | |
| 158 | 新增: typeof text !== "string" || | |
| 159 | 新增: text.length > limit | |
| 160 | 新增: ) | |
| 161 | 新增: return; | |
| 162 | 新增: emit( | |
| 163 | 新增: '{"token":"' + | |
| 164 | 新增: token + | |
| 165 | 新增: '","context":' + | |
| 166 | 新增: stringify(started.context) + | |
| 167 | 新增: ',"text":' + | |
| 168 | 新增: stringify(text) + | |
| 169 | 新增: "}", | |
| 170 | 新增: ); | |
| 171 | 新增: }; | |
| 172 | 新增: const watch = (promise, text, started) => { | |
| 173 | 新增: // Observe the captured native promise without trusting site-modified then(). | |
| 174 | 新增: apply(then, promise, [ | |
| 175 | 新增: () => { | |
| 176 | 新增: send(text, started); | |
| 177 | 新增: }, | |
| 178 | 新增: () => {}, | |
| 179 | 新增: ]); | |
| 180 | 新增: return promise; | |
| 181 | 新增: }; | |
| 182 | 新增: const cancel = () => { | |
| 183 | 新增: epoch++; | |
| 184 | 新增: }; | |
| 185 | 新增: apply(addListener, window, ["blur", cancel, true]); | |
| 186 | 新增: apply(addListener, window, ["pagehide", cancel, true]); | |
| 187 | 新增: apply(addListener, document, [ | |
| 188 | 新增: "visibilitychange", | |
| 189 | 新增: () => { | |
| 190 | 新增: epoch++; | |
| 191 | 新增: }, | |
| 192 | 新增: true, | |
| 193 | 新增: ]); | |
| 194 | 新增: | |
| 195 | 新增: if (writeText) { | |
| 196 | 新增: define(clipboardPrototype, "writeText", { | |
| 197 | 新增: configurable: true, | |
| 198 | 新增: writable: true, | |
| 199 | 新增: value: function (value) { | |
| 200 | 新增: if (!arguments.length || typeof value === "symbol") | |
| 201 | 新增: return apply(writeText, this, arguments); | |
| 202 | 新增: const started = begin(); | |
| 203 | 新增: // Pass the same converted string to Chromium and the observer. | |
| 204 | 新增: const text = string(value); | |
| 205 | 新增: return watch(apply(writeText, this, [text]), text, started); | |
| 206 | 新增: }, | |
| 207 | 新增: }); | |
| 208 | 新增: if (write && getType) | |
| 209 | 新增: define(clipboardPrototype, "write", { | |
| 210 | 新增: configurable: true, | |
| 211 | 新增: writable: true, | |
| 212 | 新增: value: function (value) { | |
| 213 | 新增: const started = begin(); | |
| 214 | 新增: let items; | |
| 215 | 新增: try { | |
| 216 | 新增: items = [...value]; | |
| 217 | 新增: } catch { | |
| 218 | 新增: return apply(write, this, arguments); | |
| 219 | 新增: } | |
| 220 | 新增: define(items, iterator, { | |
| 221 | 新增: value: function () { | |
| 222 | 新增: let index = 0; | |
| 223 | 新增: return { | |
| 224 | 新增: next: () => | |
| 225 | 新增: index < items.length | |
| 226 | 新增: ? { value: items[index++], done: false } | |
| 227 | 新增: : { done: true }, | |
| 228 | 新增: }; | |
| 229 | 新增: }, | |
| 230 | 新增: }); | |
| 231 | 新增: const promise = apply(write, this, [items]); | |
| 232 | 新增: if (started === null || items.length !== 1) return promise; | |
| 233 | 新增: let text, | |
| 234 | 新增: written = false; | |
| 235 | 新增: const completed = () => { | |
| 236 | 新增: if (written && typeof text === "string") send(text, started); | |
| 237 | 新增: }; | |
| 238 | 新增: try { | |
| 239 | 新增: apply(then, apply(getType, items[0], ["text/plain"]), [ | |
| 240 | 新增: (blob) => { | |
| 241 | 新增: apply(then, apply(blobText, blob, []), [ | |
| 242 | 新增: (value) => { | |
| 243 | 新增: text = value; | |
| 244 | 新增: completed(); | |
| 245 | 新增: }, | |
| 246 | 新增: () => {}, | |
| 247 | 新增: ]); | |
| 248 | 新增: }, | |
| 249 | 新增: () => {}, | |
| 250 | 新增: ]); | |
| 251 | 新增: } catch { | |
| 252 | 新增: return promise; | |
| 253 | 新增: } | |
| 254 | 新增: apply(then, promise, [ | |
| 255 | 新增: () => { | |
| 256 | 新增: written = true; | |
| 257 | 新增: completed(); | |
| 258 | 新增: }, | |
| 259 | 新增: () => {}, | |
| 260 | 新增: ]); | |
| 261 | 新增: return promise; | |
| 262 | 新增: }, | |
| 263 | 新增: }); | |
| 264 | 新增: } | |
| 265 | 新增: | |
| 266 | 新增: define(transferPrototype, "setData", { | |
| 267 | 新增: configurable: true, | |
| 268 | 新增: writable: true, | |
| 269 | 新增: value: function (format, value) { | |
| 270 | 新增: if ( | |
| 271 | 新增: arguments.length < 2 || | |
| 272 | 新增: typeof format === "symbol" || | |
| 273 | 新增: typeof value === "symbol" | |
| 274 | 新增: ) | |
| 275 | 新增: return apply(setData, this, arguments); | |
| 276 | 新增: const type = string(format); | |
| 277 | 新增: const text = string(value); | |
| 278 | 新增: const result = apply(setData, this, [type, text]); | |
| 279 | 新增: if (operation?.data === this && plain(type)) operation.text = text; | |
| 280 | 新增: return result; | |
| 281 | 新增: }, | |
| 282 | 新增: }); | |
| 283 | 新增: define(transferPrototype, "clearData", { | |
| 284 | 新增: configurable: true, | |
| 285 | 新增: writable: true, | |
| 286 | 新增: value: function (format) { | |
| 287 | 新增: if (typeof format === "symbol") | |
| 288 | 新增: return apply(clearData, this, arguments); | |
| 289 | 新增: const type = format === undefined ? undefined : string(format); | |
| 290 | 新增: const result = apply( | |
| 291 | 新增: clearData, | |
| 292 | 新增: this, | |
| 293 | 新增: type === undefined ? [] : [type], | |
| 294 | 新增: ); | |
| 295 | 新增: if (operation?.data === this && (type === undefined || plain(type))) | |
| 296 | 新增: operation.text = undefined; | |
| 297 | 新增: return result; | |
| 298 | 新增: }, | |
| 299 | 新增: }); | |
| 300 | 新增: apply(addListener, document, [ | |
| 301 | 新增: "copy", | |
| 302 | 新增: (event) => { | |
| 303 | 新增: if (operation && event.isTrusted) { | |
| 304 | 新增: operation.event = event; | |
| 305 | 新增: operation.data = apply(clipboardData, event, []); | |
| 306 | 新增: } | |
| 307 | 新增: }, | |
| 308 | 新增: true, | |
| 309 | 新增: ]); | |
| 310 | 新增: define(documentPrototype, "execCommand", { | |
| 311 | 新增: configurable: true, | |
| 312 | 新增: writable: true, | |
| 313 | 新增: value: function (command, ...args) { | |
| 314 | 新增: if (!arguments.length || typeof command === "symbol") | |
| 315 | 新增: return apply(exec, this, arguments); | |
| 316 | 新增: const name = string(command); | |
| 317 | 新增: if (apply(lower, name, []) !== "copy" || this !== document) | |
| 318 | 新增: return apply(exec, this, [name, ...args]); | |
| 319 | 新增: const parent = operation; | |
| 320 | 新增: const copy = { started: begin() }; | |
| 321 | 新增: operation = copy; | |
| 322 | 新增: let result; | |
| 323 | 新增: try { | |
| 324 | 新增: result = apply(exec, this, [name, ...args]); | |
| 325 | 新增: } finally { | |
| 326 | 新增: operation = parent; | |
| 327 | 新增: } | |
| 328 | 新增: if (result && copy.event) { | |
| 329 | 新增: if (apply(prevented, copy.event, [])) send(copy.text, copy.started); | |
| 330 | 新增: else { | |
| 331 | 新增: // Chromium's default DOM copy may add image alt text or transform | |
| 332 | 新增: // whitespace. Text controls have an exact selection representation. | |
| 333 | 新增: const text = selectedControlText(); | |
| 334 | 新增: if (text) send(text, copy.started); | |
| 335 | 新增: } | |
| 336 | 新增: } | |
| 337 | 新增: return result; | |
| 338 | 新增: }, | |
| 339 | 新增: }); | |
| 340 | 新增: }, | |
| 341 | 新增: }; | |
| 342 | 新增:} | |
| 343 | 新增: | |
| 344 | 新增:export class BrowserClipboard { | |
| 345 | 新增: constructor(cdp, onCopy) { | |
| 346 | 新增: this.cdp = cdp; | |
| 347 | 新增: this.onCopy = onCopy; | |
| 348 | 新增: this.sessions = new Map(); | |
| 349 | 新增: this.copyContexts = new Map(); | |
| 350 | 新增: } | |
| 351 | 新增: | |
| 352 | 新增: async attach(sessionId, tabId) { | |
| 353 | 新增: if (this.sessions.has(sessionId)) return this.sessions.get(sessionId).ready; | |
| 354 | 新增: const state = { | |
| 355 | 新增: tabId, | |
| 356 | 新增: contexts: new Map(), | |
| 357 | 新增: name: "cageCopy" + randomBytes(16).toString("hex"), | |
| 358 | 新增: token: randomBytes(32).toString("hex"), | |
| 359 | 新增: contextSetter: "cageCopyContext" + randomBytes(16).toString("hex"), | |
| 360 | 新增: }; | |
| 361 | 新增: this.sessions.set(sessionId, state); | |
| 362 | 新增: state.ready = this.#install(sessionId, state); | |
| 363 | 新增: return state.ready; | |
| 364 | 新增: } | |
| 365 | 新增: | |
| 366 | 新增: async #install(sessionId, state) { | |
| 367 | 新增: const { tabId } = state; | |
| 368 | 新增: try { | |
| 369 | 新增: await this.cdp("Page.enable", {}, sessionId); | |
| 370 | 新增: await this.cdp("Runtime.enable", {}, sessionId); | |
| 371 | 新增: await this.cdp("Runtime.addBinding", { name: state.name }, sessionId); | |
| 372 | 新增: const source = `(${prepareCopies})(${JSON.stringify(state.name)},${JSON.stringify(state.token)},${JSON.stringify(state.contextSetter)},65536)`; | |
| 373 | 新增: await this.cdp( | |
| 374 | 新增: "Page.addScriptToEvaluateOnNewDocument", | |
| 375 | 新增: { source: `(${source})?.install()` }, | |
| 376 | 新增: sessionId, | |
| 377 | 新增: ); | |
| 378 | 新增: const skipped = []; | |
| 379 | 新增: for (const contextId of state.contexts.keys()) { | |
| 380 | 新增: const group = "cage-clipboard-" + randomBytes(8).toString("hex"); | |
| 381 | 新增: try { | |
| 382 | 新增: const prepared = await this.cdp( | |
| 383 | 新增: "Runtime.evaluate", | |
| 384 | 新增: { expression: source, contextId, objectGroup: group }, | |
| 385 | 新增: sessionId, | |
| 386 | 新增: ); | |
| 387 | 新增: if (prepared.exceptionDetails) { | |
| 388 | 新增: skipped.push({ | |
| 389 | 新增: contextId, | |
| 390 | 新增: reason: "Clipboard APIs unavailable or modified", | |
| 391 | 新增: }); | |
| 392 | 新增: continue; | |
| 393 | 新增: } | |
| 394 | 新增: if (!prepared.result?.objectId) continue; | |
| 395 | 新增: const properties = await this.cdp( | |
| 396 | 新增: "Runtime.getProperties", | |
| 397 | 新增: { objectId: prepared.result.objectId, ownProperties: true }, | |
| 398 | 新增: sessionId, | |
| 399 | 新增: ); | |
| 400 | 新增: const functions = properties.result.find( | |
| 401 | 新增: (p) => p.name === "nativeFunctions", | |
| 402 | 新增: )?.value?.objectId; | |
| 403 | 新增: if (!functions) continue; | |
| 404 | 新增: const refs = await this.cdp( | |
| 405 | 新增: "Runtime.getProperties", | |
| 406 | 新增: { objectId: functions, ownProperties: true }, | |
| 407 | 新增: sessionId, | |
| 408 | 新增: ); | |
| 409 | 新增: const modified = refs.result.find( | |
| 410 | 新增: (p) => | |
| 411 | 新增: !( | |
| 412 | 新增: ["writeText", "write", "getType"].includes(p.name) && | |
| 413 | 新增: p.value?.type === "undefined" | |
| 414 | 新增: ) && | |
| 415 | 新增: (p.value?.type !== "function" || | |
| 416 | 新增: p.value.description !== | |
| 417 | 新增: `function ${p.name.split("#", 1)[0]}() { [native code] }`), | |
| 418 | 新增: ); | |
| 419 | 新增: if (modified) { | |
| 420 | 新增: skipped.push({ | |
| 421 | 新增: contextId, | |
| 422 | 新增: reason: `Modified ${modified.name || "binding"}`, | |
| 423 | 新增: }); | |
| 424 | 新增: continue; | |
| 425 | 新增: } | |
| 426 | 新增: const binding = await this.cdp( | |
| 427 | 新增: "Runtime.getProperties", | |
| 428 | 新增: { | |
| 429 | 新增: objectId: refs.result.find((p) => p.name === "").value.objectId, | |
| 430 | 新增: ownProperties: true, | |
| 431 | 新增: }, | |
| 432 | 新增: sessionId, | |
| 433 | 新增: ); | |
| 434 | 新增: if ( | |
| 435 | 新增: binding.internalProperties?.some( | |
| 436 | 新增: (p) => p.name === "[[TargetFunction]]", | |
| 437 | 新增: ) | |
| 438 | 新增: ) { | |
| 439 | 新增: skipped.push({ contextId, reason: "Modified binding" }); | |
| 440 | 新增: continue; | |
| 441 | 新增: } | |
| 442 | 新增: const result = await this.cdp( | |
| 443 | 新增: "Runtime.callFunctionOn", | |
| 444 | 新增: { | |
| 445 | 新增: objectId: prepared.result.objectId, | |
| 446 | 新增: functionDeclaration: "function() { this.install(); }", | |
| 447 | 新增: }, | |
| 448 | 新增: sessionId, | |
| 449 | 新增: ); | |
| 450 | 新增: if (result.exceptionDetails) | |
| 451 | 新增: skipped.push({ | |
| 452 | 新增: contextId, | |
| 453 | 新增: reason: "Clipboard observer installation failed", | |
| 454 | 新增: }); | |
| 455 | 新增: } catch { | |
| 456 | 新增: skipped.push({ | |
| 457 | 新增: contextId, | |
| 458 | 新增: reason: "Document changed during clipboard observer installation", | |
| 459 | 新增: }); | |
| 460 | 新增: } finally { | |
| 461 | 新增: await this.cdp( | |
| 462 | 新增: "Runtime.releaseObjectGroup", | |
| 463 | 新增: { objectGroup: group }, | |
| 464 | 新增: sessionId, | |
| 465 | 新增: ).catch(() => {}); | |
| 466 | 新增: } | |
| 467 | 新增: } | |
| 468 | 新增: await this.cdp( | |
| 469 | 新增: "Target.setAutoAttach", | |
| 470 | 新增: { | |
| 471 | 新增: autoAttach: true, | |
| 472 | 新增: waitForDebuggerOnStart: false, | |
| 473 | 新增: flatten: true, | |
| 474 | 新增: filter: [{ type: "iframe" }, { exclude: true }], | |
| 475 | 新增: }, | |
| 476 | 新增: sessionId, | |
| 477 | 新增: ); | |
| 478 | 新增: if (this.copyContexts.has(tabId)) | |
| 479 | 新增: await this.#applyContext( | |
| 480 | 新增: sessionId, | |
| 481 | 新增: state, | |
| 482 | 新增: this.copyContexts.get(tabId), | |
| 483 | 新增: ); | |
| 484 | 新增: return { skipped }; | |
| 485 | 新增: } catch (error) { | |
| 486 | 新增: this.sessions.delete(sessionId); | |
| 487 | 新增: throw error; | |
| 488 | 新增: } | |
| 489 | 新增: } | |
| 490 | 新增: | |
| 491 | 新增: async setContext(id, context) { | |
| 492 | 新增: if (typeof context !== "string" || context.length > 64) | |
| 493 | 新增: throw new Error("Invalid clipboard context"); | |
| 494 | 新增: this.copyContexts.set(id, context); | |
| 495 | 新增: const applied = new Set(); | |
| 496 | 新增: for (;;) { | |
| 497 | 新增: const sessions = [...this.sessions].filter( | |
| 498 | 新增: ([, state]) => state.tabId === id && !applied.has(state), | |
| 499 | 新增: ); | |
| 500 | 新增: if (!sessions.length) return; | |
| 501 | 新增: await Promise.all( | |
| 502 | 新增: sessions.map(async ([sessionId, state]) => { | |
| 503 | 新增: await state.ready; | |
| 504 | 新增: if (this.sessions.get(sessionId) === state) | |
| 505 | 新增: await this.#applyContext(sessionId, state, context); | |
| 506 | 新增: applied.add(state); | |
| 507 | 新增: }), | |
| 508 | 新增: ); | |
| 509 | 新增: // Auto-attach may discover nested frames while an earlier frame installs. | |
| 510 | 新增: } | |
| 511 | 新增: } | |
| 512 | 新增: | |
| 513 | 新增: async #applyContext(sessionId, state, context) { | |
| 514 | 新增: const updates = []; | |
| 515 | 新增: for (const contextId of state.contexts.keys()) { | |
| 516 | 新增: updates.push( | |
| 517 | 新增: this.cdp( | |
| 518 | 新增: "Runtime.evaluate", | |
| 519 | 新增: { | |
| 520 | 新增: expression: `globalThis[${JSON.stringify(state.contextSetter)}]?.(${JSON.stringify(context)})`, | |
| 521 | 新增: contextId, | |
| 522 | 新增: }, | |
| 523 | 新增: sessionId, | |
| 524 | 新增: ).catch(() => {}), | |
| 525 | 新增: ); | |
| 526 | 新增: } | |
| 527 | 新增: await Promise.all(updates); | |
| 528 | 新增: } | |
| 529 | 新增: | |
| 530 | 新增: event(event) { | |
| 531 | 新增: const state = this.sessions.get(event.sessionId); | |
| 532 | 新增: if (!state) return; | |
| 533 | 新增: const p = event.params || {}; | |
| 534 | 新增: if ( | |
| 535 | 新增: event.method === "Target.attachedToTarget" && | |
| 536 | 新增: p.targetInfo?.type === "iframe" | |
| 537 | 新增: ) { | |
| 538 | 新增: void this.attach(p.sessionId, state.tabId).catch(() => {}); | |
| 539 | 新增: } else if (event.method === "Target.detachedFromTarget") { | |
| 540 | 新增: this.sessions.delete(p.sessionId); | |
| 541 | 新增: } else if (event.method === "Runtime.executionContextCreated") { | |
| 542 | 新增: if (p.context?.auxData?.isDefault) | |
| 543 | 新增: state.contexts.set(p.context.id, p.context.auxData.frameId); | |
| 544 | 新增: } else if (event.method === "Runtime.executionContextDestroyed") { | |
| 545 | 新增: state.contexts.delete(p.executionContextId); | |
| 546 | 新增: } else if (event.method === "Runtime.executionContextsCleared") { | |
| 547 | 新增: state.contexts.clear(); | |
| 548 | 新增: } else if ( | |
| 549 | 新增: event.method === "Page.frameDetached" || | |
| 550 | 新增: event.method === "Page.frameNavigated" | |
| 551 | 新增: ) { | |
| 552 | 新增: const id = p.frameId || p.frame?.id; | |
| 553 | 新增: for (const [context, frame] of state.contexts) | |
| 554 | 新增: if (frame === id) state.contexts.delete(context); | |
| 555 | 新增: } else if ( | |
| 556 | 新增: event.method === "Runtime.bindingCalled" && | |
| 557 | 新增: p.name === state.name && | |
| 558 | 新增: state.contexts.has(p.executionContextId) | |
| 559 | 新增: ) { | |
| 560 | 新增: if ( | |
| 561 | 新增: typeof p.payload !== "string" || | |
| 562 | 新增: p.payload.length > 6 * (65536 + 64) + 200 | |
| 563 | 新增: ) | |
| 564 | 新增: return; | |
| 565 | 新增: let value; | |
| 566 | 新增: try { | |
| 567 | 新增: value = JSON.parse(p.payload); | |
| 568 | 新增: } catch { | |
| 569 | 新增: return; | |
| 570 | 新增: } | |
| 571 | 新增: if ( | |
| 572 | 新增: value?.token !== state.token || | |
| 573 | 新增: typeof value.context !== "string" || | |
| 574 | 新增: value.context.length > 64 || | |
| 575 | 新增: typeof value.text !== "string" || | |
| 576 | 新增: value.text.length > 65536 | |
| 577 | 新增: ) | |
| 578 | 新增: return; | |
| 579 | 新增: this.onCopy({ | |
| 580 | 新增: id: state.tabId, | |
| 581 | 新增: text: value.text, | |
| 582 | 新增: context: value.context, | |
| 583 | 新增: }); | |
| 584 | 新增: } | |
| 585 | 新增: } | |
| 586 | 新增: | |
| 587 | 新增: detachTab(id) { | |
| 588 | 新增: this.copyContexts.delete(id); | |
| 589 | 新增: for (const [session, state] of this.sessions) | |
| 590 | 新增: if (state.tabId === id) this.sessions.delete(session); | |
| 591 | 新增: } | |
| 592 | 新增:} | |
| @@ -0,0 +1,207 @@ | ||
| 1 | 新增:import test from "node:test"; | |
| 2 | 新增:import assert from "node:assert/strict"; | |
| 3 | 新增:import { BrowserClipboard } from "./browser-clipboard.mjs"; | |
| 4 | 新增: | |
| 5 | 新增:test("clipboard events require a live default context and private binding token", async () => { | |
| 6 | 新增: const copies = []; | |
| 7 | 新增: const observer = new BrowserClipboard( | |
| 8 | 新增: async () => ({}), | |
| 9 | 新增: (value) => copies.push(value), | |
| 10 | 新增: ); | |
| 11 | 新增: await observer.attach("session", "tab"); | |
| 12 | 新增: const state = observer.sessions.get("session"); | |
| 13 | 新增: const event = (method, params) => | |
| 14 | 新增: observer.event({ sessionId: "session", method, params }); | |
| 15 | 新增: const copied = ( | |
| 16 | 新增: text, | |
| 17 | 新增: token = state.token, | |
| 18 | 新增: executionContextId = 3, | |
| 19 | 新增: context = "context-a", | |
| 20 | 新增: ) => | |
| 21 | 新增: event("Runtime.bindingCalled", { | |
| 22 | 新增: name: state.name, | |
| 23 | 新增: executionContextId, | |
| 24 | 新增: payload: JSON.stringify({ token, text, context }), | |
| 25 | 新增: }); | |
| 26 | 新增: copied("before context"); | |
| 27 | 新增: event("Runtime.executionContextCreated", { | |
| 28 | 新增: context: { id: 3, auxData: { isDefault: true, frameId: "frame" } }, | |
| 29 | 新增: }); | |
| 30 | 新增: event("Runtime.executionContextCreated", { | |
| 31 | 新增: context: { id: 4, auxData: { isDefault: false, frameId: "frame" } }, | |
| 32 | 新增: }); | |
| 33 | 新增: copied("forged", "wrong token"); | |
| 34 | 新增: copied("isolated", state.token, 4); | |
| 35 | 新增: copied("x".repeat(65537)); | |
| 36 | 新增: copied("invalid context", state.token, 3, null); | |
| 37 | 新增: copied("invalid context", state.token, 3, "x".repeat(65)); | |
| 38 | 新增: copied("exact🙂"); | |
| 39 | 新增: assert.deepEqual(copies, [ | |
| 40 | 新增: { id: "tab", text: "exact🙂", context: "context-a" }, | |
| 41 | 新增: ]); | |
| 42 | 新增: event("Page.frameNavigated", { frame: { id: "frame" } }); | |
| 43 | 新增: copied("old document"); | |
| 44 | 新增: event("Runtime.executionContextCreated", { | |
| 45 | 新增: context: { id: 5, auxData: { isDefault: true, frameId: "frame" } }, | |
| 46 | 新增: }); | |
| 47 | 新增: copied("new document", state.token, 5); | |
| 48 | 新增: observer.detachTab("tab"); | |
| 49 | 新增: copied("closed tab", state.token, 5); | |
| 50 | 新增: assert.deepEqual( | |
| 51 | 新增: copies.map((value) => value.text), | |
| 52 | 新增: ["exact🙂", "new document"], | |
| 53 | 新增: ); | |
| 54 | 新增:}); | |
| 55 | 新增: | |
| 56 | 新增:test("host copy context reaches every existing frame and newly attached child", async () => { | |
| 57 | 新增: const calls = []; | |
| 58 | 新增: const observer = new BrowserClipboard( | |
| 59 | 新增: async (method, params, sessionId) => { | |
| 60 | 新增: calls.push({ method, params, sessionId }); | |
| 61 | 新增: if (method === "Runtime.enable" && sessionId === "child") | |
| 62 | 新增: observer.event({ | |
| 63 | 新增: sessionId, | |
| 64 | 新增: method: "Runtime.executionContextCreated", | |
| 65 | 新增: params: { | |
| 66 | 新增: context: { | |
| 67 | 新增: id: 3, | |
| 68 | 新增: auxData: { isDefault: true, frameId: "cross-process-frame" }, | |
| 69 | 新增: }, | |
| 70 | 新增: }, | |
| 71 | 新增: }); | |
| 72 | 新增: return {}; | |
| 73 | 新增: }, | |
| 74 | 新增: () => {}, | |
| 75 | 新增: ); | |
| 76 | 新增: await observer.attach("root", "tab"); | |
| 77 | 新增: observer.event({ | |
| 78 | 新增: sessionId: "root", | |
| 79 | 新增: method: "Runtime.executionContextCreated", | |
| 80 | 新增: params: { | |
| 81 | 新增: context: { id: 1, auxData: { isDefault: true, frameId: "root-frame" } }, | |
| 82 | 新增: }, | |
| 83 | 新增: }); | |
| 84 | 新增: await observer.setContext("tab", "context-a"); | |
| 85 | 新增: observer.sessions.get("root").contexts.set(2, "same-process-frame"); | |
| 86 | 新增: await observer.attach("child", "tab"); | |
| 87 | 新增: assert.ok( | |
| 88 | 新增: calls.some( | |
| 89 | 新增: (call) => | |
| 90 | 新增: call.sessionId === "child" && | |
| 91 | 新增: call.method === "Runtime.evaluate" && | |
| 92 | 新增: call.params.expression.includes('"context-a"'), | |
| 93 | 新增: ), | |
| 94 | 新增: ); | |
| 95 | 新增: const before = calls.length; | |
| 96 | 新增: await observer.setContext("tab", "context-b"); | |
| 97 | 新增: const updates = calls | |
| 98 | 新增: .slice(before) | |
| 99 | 新增: .filter((call) => call.method === "Runtime.evaluate"); | |
| 100 | 新增: assert.deepEqual( | |
| 101 | 新增: updates.map((call) => [call.sessionId, call.params.contextId]), | |
| 102 | 新增: [ | |
| 103 | 新增: ["root", 1], | |
| 104 | 新增: ["root", 2], | |
| 105 | 新增: ["child", 3], | |
| 106 | 新增: ], | |
| 107 | 新增: ); | |
| 108 | 新增: assert.ok( | |
| 109 | 新增: updates.every((call) => call.params.expression.includes('"context-b"')), | |
| 110 | 新增: ); | |
| 111 | 新增: observer.detachTab("tab"); | |
| 112 | 新增: assert.equal(observer.copyContexts.has("tab"), false); | |
| 113 | 新增: assert.equal(observer.sessions.size, 0); | |
| 114 | 新增:}); | |
| 115 | 新增: | |
| 116 | 新增:test("failed setup removes the session and allows retry", async () => { | |
| 117 | 新增: let fail = true; | |
| 118 | 新增: const observer = new BrowserClipboard( | |
| 119 | 新增: async () => { | |
| 120 | 新增: if (fail) throw new Error("CDP unavailable"); | |
| 121 | 新增: return {}; | |
| 122 | 新增: }, | |
| 123 | 新增: () => {}, | |
| 124 | 新增: ); | |
| 125 | 新增: await assert.rejects(observer.attach("s", "t"), /CDP unavailable/); | |
| 126 | 新增: assert.equal(observer.sessions.size, 0); | |
| 127 | 新增: fail = false; | |
| 128 | 新增: assert.deepEqual(await observer.attach("s", "t"), { skipped: [] }); | |
| 129 | 新增:}); | |
| 130 | 新增: | |
| 131 | 新增:test("copy context waits for pending frame installation and frames discovered during the wait", async () => { | |
| 132 | 新增: const calls = []; | |
| 133 | 新增: const gates = new Map(); | |
| 134 | 新增: for (const id of ["child", "nested"]) { | |
| 135 | 新增: let release, entered; | |
| 136 | 新增: const pending = new Promise((resolve) => { | |
| 137 | 新增: release = resolve; | |
| 138 | 新增: }); | |
| 139 | 新增: const reached = new Promise((resolve) => { | |
| 140 | 新增: entered = resolve; | |
| 141 | 新增: }); | |
| 142 | 新增: gates.set(id, { pending, reached, release, entered }); | |
| 143 | 新增: } | |
| 144 | 新增: const observer = new BrowserClipboard( | |
| 145 | 新增: async (method, params, sessionId) => { | |
| 146 | 新增: calls.push({ method, params, sessionId }); | |
| 147 | 新增: if (method === "Runtime.enable") | |
| 148 | 新增: observer.event({ | |
| 149 | 新增: sessionId, | |
| 150 | 新增: method: "Runtime.executionContextCreated", | |
| 151 | 新增: params: { | |
| 152 | 新增: context: { | |
| 153 | 新增: id: 1, | |
| 154 | 新增: auxData: { isDefault: true, frameId: sessionId + "-frame" }, | |
| 155 | 新增: }, | |
| 156 | 新增: }, | |
| 157 | 新增: }); | |
| 158 | 新增: if ( | |
| 159 | 新增: method === "Page.addScriptToEvaluateOnNewDocument" && | |
| 160 | 新增: gates.has(sessionId) | |
| 161 | 新增: ) { | |
| 162 | 新增: gates.get(sessionId).entered(); | |
| 163 | 新增: await gates.get(sessionId).pending; | |
| 164 | 新增: } | |
| 165 | 新增: return {}; | |
| 166 | 新增: }, | |
| 167 | 新增: () => {}, | |
| 168 | 新增: ); | |
| 169 | 新增: await observer.attach("root", "tab"); | |
| 170 | 新增: const child = observer.attach("child", "tab"); | |
| 171 | 新增: await gates.get("child").reached; | |
| 172 | 新增: let completed = false; | |
| 173 | 新增: const update = observer.setContext("tab", "context-a").then(() => { | |
| 174 | 新增: completed = true; | |
| 175 | 新增: }); | |
| 176 | 新增: await new Promise((resolve) => setImmediate(resolve)); | |
| 177 | 新增: assert.equal(completed, false, "the handshake must wait for the child hook"); | |
| 178 | 新增: assert.equal( | |
| 179 | 新增: calls.some( | |
| 180 | 新增: (call) => | |
| 181 | 新增: call.sessionId === "child" && call.method === "Runtime.evaluate", | |
| 182 | 新增: ), | |
| 183 | 新增: false, | |
| 184 | 新增: ); | |
| 185 | 新增: const nested = observer.attach("nested", "tab"); | |
| 186 | 新增: await gates.get("nested").reached; | |
| 187 | 新增: gates.get("child").release(); | |
| 188 | 新增: await child; | |
| 189 | 新增: await new Promise((resolve) => setImmediate(resolve)); | |
| 190 | 新增: assert.equal( | |
| 191 | 新增: completed, | |
| 192 | 新增: false, | |
| 193 | 新增: "the handshake must include a newly discovered frame", | |
| 194 | 新增: ); | |
| 195 | 新增: gates.get("nested").release(); | |
| 196 | 新增: await Promise.all([nested, update]); | |
| 197 | 新增: assert.equal(completed, true); | |
| 198 | 新增: for (const id of ["child", "nested"]) | |
| 199 | 新增: assert.ok( | |
| 200 | 新增: calls.some( | |
| 201 | 新增: (call) => | |
| 202 | 新增: call.sessionId === id && | |
| 203 | 新增: call.method === "Runtime.evaluate" && | |
| 204 | 新增: call.params.expression.includes('"context-a"'), | |
| 205 | 新增: ), | |
| 206 | 新增: ); | |
| 207 | 新增:}); | |
| @@ -0,0 +1,53 @@ | ||
| 1 | 新增:// The browser owns these ephemeral cookies. Only the origin of a login page | |
| 2 | 新增:// may enter the workbench tab list, including for popups and redirects. | |
| 3 | 新增:export class LoginBrowser { | |
| 4 | 新增: constructor(cdp) { | |
| 5 | 新增: this.cdp = cdp; | |
| 6 | 新增: this.contexts = new Map(); | |
| 7 | 新增: } | |
| 8 | 新增: | |
| 9 | 新增: tab(raw, previous) { | |
| 10 | 新增: if (!previous?.login && !this.contexts.has(raw.browserContextId)) return raw; | |
| 11 | 新增: let origin = "about:blank"; | |
| 12 | 新增: try { | |
| 13 | 新增: const url = new URL(raw.url); | |
| 14 | 新增: if (["https:", "http:"].includes(url.protocol)) origin = url.origin; | |
| 15 | 新增: } catch {} | |
| 16 | 新增: return { ...raw, login: true, url: origin, title: "账号授权" }; | |
| 17 | 新增: } | |
| 18 | 新增: | |
| 19 | 新增: async open(login, address, activate) { | |
| 20 | 新增: if (typeof login !== "string" || !/^[a-f0-9-]{16,64}$/.test(login)) throw new Error("登录任务无效"); | |
| 21 | 新增: const url = new URL(address); | |
| 22 | 新增: if (url.protocol !== "https:" || url.username || url.password || | |
| 23 | 新增: !["claude.ai", "claude.com", "console.anthropic.com", "platform.claude.com", "platform.anthropic.com"].includes(url.hostname)) | |
| 24 | 新增: throw new Error("仅可打开官方登录地址"); | |
| 25 | 新增: await this.finish(login); | |
| 26 | 新增: const { browserContextId } = await this.cdp("Target.createBrowserContext", { disposeOnDetach: true }); | |
| 27 | 新增: const expiry = setTimeout(() => this.close(browserContextId).catch(() => {}), 15 * 60_000); | |
| 28 | 新增: expiry.unref(); | |
| 29 | 新增: this.contexts.set(browserContextId, { login, expiry }); | |
| 30 | 新增: try { | |
| 31 | 新增: const { targetId } = await this.cdp("Target.createTarget", { browserContextId, url: url.href, newWindow: true }); | |
| 32 | 新增: await activate({ targetId, browserContextId, type: "page", url: url.href }); | |
| 33 | 新增: return { id: targetId }; | |
| 34 | 新增: } catch { | |
| 35 | 新增: await this.close(browserContextId); | |
| 36 | 新增: throw new Error("临时登录页面未能打开"); | |
| 37 | 新增: } | |
| 38 | 新增: } | |
| 39 | 新增: | |
| 40 | 新增: async finish(login) { | |
| 41 | 新增: for (const [id, entry] of this.contexts) { | |
| 42 | 新增: if (entry.login === login) await this.close(id); | |
| 43 | 新增: } | |
| 44 | 新增: } | |
| 45 | 新增: | |
| 46 | 新增: async close(id) { | |
| 47 | 新增: const entry = this.contexts.get(id); | |
| 48 | 新增: if (!entry) return; | |
| 49 | 新增: await this.cdp("Target.disposeBrowserContext", { browserContextId: id }); | |
| 50 | 新增: clearTimeout(entry.expiry); | |
| 51 | 新增: this.contexts.delete(id); | |
| 52 | 新增: } | |
| 53 | 新增:} | |
| @@ -0,0 +1,29 @@ | ||
| 1 | 新增:import assert from "node:assert/strict"; | |
| 2 | 新增:import test from "node:test"; | |
| 3 | 新增:import { LoginBrowser } from "./browser-login.mjs"; | |
| 4 | 新增: | |
| 5 | 新增:test("login redirects and popups stay private, closing one login leaves the other open", async () => { | |
| 6 | 新增: const closed = []; | |
| 7 | 新增: let contexts = 0; | |
| 8 | 新增: const browser = new LoginBrowser(async (method, params) => { | |
| 9 | 新增: if (method === "Target.createBrowserContext") return { browserContextId: String(++contexts) }; | |
| 10 | 新增: if (method === "Target.createTarget") return { targetId: "tab-" + params.browserContextId }; | |
| 11 | 新增: if (method === "Target.disposeBrowserContext") closed.push(params.browserContextId); | |
| 12 | 新增: }); | |
| 13 | 新增: const page = { url: "https://claude.ai/oauth/authorize?state=secret", title: "secret" }; | |
| 14 | 新增: assert.equal(browser.tab(page), page); | |
| 15 | 新增: for (const id of ["a", "b"]) { | |
| 16 | 新增: await browser.open(id.repeat(24), page.url, async tab => { | |
| 17 | 新增: assert.equal(browser.tab(tab).url, "https://claude.ai"); | |
| 18 | 新增: }); | |
| 19 | 新增: } | |
| 20 | 新增: const popup = { ...page, targetId: "popup", browserContextId: "1", url: "http://localhost:9123/callback?code=secret" }; | |
| 21 | 新增: const privateTab = browser.tab(popup); | |
| 22 | 新增: assert.equal(privateTab.title, "账号授权"); | |
| 23 | 新增: assert.equal(privateTab.url, "http://localhost:9123"); | |
| 24 | 新增: await browser.finish("a".repeat(24)); | |
| 25 | 新增: assert.deepEqual(closed, ["1"]); | |
| 26 | 新增: assert.equal(browser.tab(popup, privateTab).url, privateTab.url); | |
| 27 | 新增: await browser.finish("b".repeat(24)); | |
| 28 | 新增: assert.deepEqual(closed, ["1", "2"]); | |
| 29 | 新增:}); | |
| @@ -0,0 +1,200 @@ | ||
| 1 | 新增:import { randomUUID } from "node:crypto"; | |
| 2 | 新增: | |
| 3 | 新增:const world = "cage-password-vault"; | |
| 4 | 新增:const binding = "cageVaultSubmitted"; | |
| 5 | 新增: | |
| 6 | 新增:// This function executes in an isolated world. Page scripts cannot invoke its | |
| 7 | 新增:// binding or replace its built-ins. Only the top document participates. | |
| 8 | 新增:export function vaultPage() { | |
| 9 | 新增: if (window !== window.top || globalThis.cageVault) return; | |
| 10 | 新增: const visible = el => el instanceof HTMLInputElement && !el.disabled && !el.readOnly && | |
| 11 | 新增: el.type !== "hidden" && el.getClientRects().length > 0 && getComputedStyle(el).visibility !== "hidden"; | |
| 12 | 新增: const fields = root => [...root.querySelectorAll("input")].filter(visible); | |
| 13 | 新增: const username = list => list.find(el => el.autocomplete === "username") || | |
| 14 | 新增: list.find(el => el.type === "email") || list.find(el => | |
| 15 | 新增: ["text", "tel"].includes(el.type) && !/one-time-code|otp|search|captcha/i.test(`${el.autocomplete} ${el.name} ${el.id}`)); | |
| 16 | 新增: const state = globalThis.cageVault = { | |
| 17 | 新增: document: crypto.randomUUID(), deadline: 0, lease: "", previousUsername: "", previousAt: 0, | |
| 18 | 新增: fill(value) { | |
| 19 | 新增: if (Date.now() >= state.deadline || value.lease !== state.lease || location.origin !== value.origin || | |
| 20 | 新增: location.protocol !== "https:" || value.document !== state.document) return false; | |
| 21 | 新增: const list = fields(document); | |
| 22 | 新增: const passwords = list.filter(el => el.type === "password" && el.autocomplete !== "new-password"); | |
| 23 | 新增: // Multiple independent forms require the user to focus the intended one. | |
| 24 | 新增: let password = passwords.includes(document.activeElement) ? document.activeElement : null; | |
| 25 | 新增: if (!password && document.activeElement?.form) password = passwords.find(el => el.form === document.activeElement.form); | |
| 26 | 新增: if (!password && passwords.length === 1) password = passwords[0]; | |
| 27 | 新增: if (!password && passwords.length > 1) return false; | |
| 28 | 新增: const user = username(password?.form ? fields(password.form) : list); | |
| 29 | 新增: if (!password && !user) return false; | |
| 30 | 新增: const set = (el, text) => { | |
| 31 | 新增: Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value").set.call(el, text); | |
| 32 | 新增: el.dispatchEvent(new Event("input", { bubbles: true })); | |
| 33 | 新增: el.dispatchEvent(new Event("change", { bubbles: true })); | |
| 34 | 新增: }; | |
| 35 | 新增: if (user) set(user, value.username); | |
| 36 | 新增: if (password) set(password, value.password); | |
| 37 | 新增: state.previousUsername = value.username; | |
| 38 | 新增: state.previousAt = Date.now(); | |
| 39 | 新增: (password || user).focus(); | |
| 40 | 新增: return true; | |
| 41 | 新增: }, | |
| 42 | 新增: }; | |
| 43 | 新增: let last = "", lastAt = 0; | |
| 44 | 新增: function capture(root) { | |
| 45 | 新增: if (location.protocol !== "https:" || Date.now() >= state.deadline) return; | |
| 46 | 新增: const list = fields(root || document), user = username(list); | |
| 47 | 新增: if (user?.value) { state.previousUsername = user.value; state.previousAt = Date.now(); } | |
| 48 | 新增: const passwords = list.filter(el => el.type === "password" && el.value); | |
| 49 | 新增: const password = passwords.at(-1)?.value || ""; | |
| 50 | 新增: if (!password && !user?.value) return; | |
| 51 | 新增: const account = user?.value || (Date.now() - state.previousAt < 120000 ? state.previousUsername : ""); | |
| 52 | 新增: if (password.length > 8192 || account.length > 1024) return; | |
| 53 | 新增: const payload = JSON.stringify({ origin: location.origin, username: account, password, | |
| 54 | 新增: document: state.document, lease: state.lease }); | |
| 55 | 新增: // Avoid duplicate submit/click notifications without retaining a password. | |
| 56 | 新增: const signature = `${state.document}:${account}:${password.length}`; | |
| 57 | 新增: if (signature === last && Date.now() - lastAt < 800) return; | |
| 58 | 新增: last = signature; lastAt = Date.now(); | |
| 59 | 新增: globalThis.cageVaultSubmitted(payload); | |
| 60 | 新增: } | |
| 61 | 新增: document.addEventListener("submit", event => { if (event.isTrusted) capture(event.target); }, true); | |
| 62 | 新增: document.addEventListener("click", event => { | |
| 63 | 新增: if (!event.isTrusted) return; | |
| 64 | 新增: const button = event.target.closest?.("button, input[type=submit], [role=button]"); | |
| 65 | 新增: if (!button) return; | |
| 66 | 新增: const label = `${button.textContent || ""} ${button.value || ""} ${button.getAttribute("aria-label") || ""}`; | |
| 67 | 新增: if (button.type === "submit" || /log\s*in|sign\s*in|登录|登入|下一步|继续|next|continue|修改密码|保存密码|change password/i.test(label)) capture(button.form || document); | |
| 68 | 新增: }, true); | |
| 69 | 新增: document.addEventListener("keydown", event => { | |
| 70 | 新增: if (event.isTrusted && event.key === "Enter" && event.target instanceof HTMLInputElement) | |
| 71 | 新增: capture(event.target.form || document); | |
| 72 | 新增: }, true); | |
| 73 | 新增:} | |
| 74 | 新增:const source = `(${vaultPage.toString()})()`; | |
| 75 | 新增: | |
| 76 | 新增:export class BrowserVault { | |
| 77 | 新增: constructor({ cdp, active, tab, now = () => Date.now() }) { | |
| 78 | 新增: Object.assign(this, { cdp, active, tab, now }); | |
| 79 | 新增: this.sessions = new Map(); | |
| 80 | 新增: this.pending = new Map(); | |
| 81 | 新增: this.usernames = new Map(); | |
| 82 | 新增: this.lease = ""; | |
| 83 | 新增: this.deadline = 0; | |
| 84 | 新增: this.blocked = []; | |
| 85 | 新增: this.timer = setInterval(() => this.prune(), 1000); | |
| 86 | 新增: this.timer.unref(); | |
| 87 | 新增: } | |
| 88 | 新增: prune() { | |
| 89 | 新增: if (this.now() >= this.deadline) { this.pending.clear(); this.usernames.clear(); this.lease = ""; } | |
| 90 | 新增: for (const [id, item] of this.usernames) if (this.now() >= item.expires) this.usernames.delete(id); | |
| 91 | 新增: for (const [id, item] of this.pending) if (this.now() >= item.expires) this.pending.delete(id); | |
| 92 | 新增: } | |
| 93 | 新增: async attach(tab, sid) { | |
| 94 | 新增: if (this.tab(tab)?.login) return; | |
| 95 | 新增: const entry = { tab, sid, top: "", contexts: new Map() }; | |
| 96 | 新增: this.sessions.set(sid, entry); | |
| 97 | 新增: await this.cdp("Runtime.enable", {}, sid); | |
| 98 | 新增: const { frameTree } = await this.cdp("Page.getFrameTree", {}, sid); | |
| 99 | 新增: entry.top = frameTree.frame.id; | |
| 100 | 新增: await this.cdp("Runtime.addBinding", { name: binding, executionContextName: world }, sid); | |
| 101 | 新增: await this.cdp("Page.addScriptToEvaluateOnNewDocument", { source, worldName: world }, sid); | |
| 102 | 新增: const { executionContextId } = await this.cdp("Page.createIsolatedWorld", { frameId: entry.top, worldName: world }, sid); | |
| 103 | 新增: entry.contexts.set(executionContextId, entry.top); | |
| 104 | 新增: await this.cdp("Runtime.evaluate", { expression: source, contextId: executionContextId }, sid); | |
| 105 | 新增: } | |
| 106 | 新增: remove(tab) { | |
| 107 | 新增: this.usernames.delete(tab); | |
| 108 | 新增: for (const [sid, value] of this.sessions) if (value.tab === tab) this.sessions.delete(sid); | |
| 109 | 新增: for (const [id, value] of this.pending) if (value.tab === tab) this.pending.delete(id); | |
| 110 | 新增: } | |
| 111 | 新增: event(event) { | |
| 112 | 新增: const entry = this.sessions.get(event.sessionId); | |
| 113 | 新增: if (!entry) return; | |
| 114 | 新增: const p = event.params || {}; | |
| 115 | 新增: if (event.method === "Runtime.executionContextCreated" && p.context.name === world) | |
| 116 | 新增: entry.contexts.set(p.context.id, p.context.auxData?.frameId); | |
| 117 | 新增: if (event.method === "Runtime.executionContextDestroyed") entry.contexts.delete(p.executionContextId); | |
| 118 | 新增: if (event.method === "Runtime.executionContextsCleared") entry.contexts.clear(); | |
| 119 | 新增: if (event.method === "Page.frameNavigated" && !p.frame.parentId) entry.top = p.frame.id; | |
| 120 | 新增: if (event.method !== "Runtime.bindingCalled" || p.name !== binding || | |
| 121 | 新增: entry.contexts.get(p.executionContextId) !== entry.top) return; | |
| 122 | 新增: this.prune(); | |
| 123 | 新增: if (!this.lease || entry.tab !== this.active() || this.tab(entry.tab)?.login || p.payload.length > 16000) return; | |
| 124 | 新增: try { | |
| 125 | 新增: const value = JSON.parse(p.payload); | |
| 126 | 新增: const origin = new URL(value.origin).origin; | |
| 127 | 新增: if (!origin.startsWith("https://") || origin !== value.origin || value.lease !== this.lease || | |
| 128 | 新增: typeof value.password !== "string" || value.password.length > 8192 || | |
| 129 | 新增: typeof value.username !== "string" || value.username.length > 1024 || this.blocked.includes(origin)) return; | |
| 130 | 新增: if (value.username) this.usernames.set(entry.tab, { origin, username: value.username, expires: this.now() + 120000 }); | |
| 131 | 新增: if (!value.password) return; | |
| 132 | 新增: const previous = this.usernames.get(entry.tab); | |
| 133 | 新增: if (!value.username && previous?.origin === origin) value.username = previous.username; | |
| 134 | 新增: // The context's security origin is additionally checked inside the page; | |
| 135 | 新增: // the binding is available only to our isolated-world code. | |
| 136 | 新增: for (const [id, old] of this.pending) if (old.tab === entry.tab) this.pending.delete(id); | |
| 137 | 新增: const id = randomUUID(); | |
| 138 | 新增: this.pending.set(id, { id, tab: entry.tab, origin, username: value.username, | |
| 139 | 新增: password: value.password, expires: this.now() + 120000 }); | |
| 140 | 新增: while (this.pending.size > 8) this.pending.delete(this.pending.keys().next().value); | |
| 141 | 新增: } catch {} | |
| 142 | 新增: } | |
| 143 | 新增: context(entry) { | |
| 144 | 新增: return [...entry.contexts].find(([, frame]) => frame === entry.top)?.[0]; | |
| 145 | 新增: } | |
| 146 | 新增: async evaluate(entry, expression) { | |
| 147 | 新增: const contextId = this.context(entry); | |
| 148 | 新增: if (!contextId) throw new Error("登录页面已变化,请稍后重试"); | |
| 149 | 新增: const result = await this.cdp("Runtime.evaluate", { expression, contextId, returnByValue: true }, entry.sid); | |
| 150 | 新增: if (result.exceptionDetails) throw new Error("网页未能处理密码操作"); | |
| 151 | 新增: return result.result?.value; | |
| 152 | 新增: } | |
| 153 | 新增: async request(input) { | |
| 154 | 新增: this.prune(); | |
| 155 | 新增: if (input.action === "lock") { | |
| 156 | 新增: if (input.lease === this.lease) { this.pending.clear(); this.usernames.clear(); this.lease = ""; this.deadline = 0; } | |
| 157 | 新增: return { ok: true }; | |
| 158 | 新增: } | |
| 159 | 新增: if (input.action === "status") { | |
| 160 | 新增: if (!/^[a-f0-9]{64}$/.test(input.lease)) throw new Error("解锁状态无效"); | |
| 161 | 新增: if (this.lease !== input.lease) { this.pending.clear(); this.usernames.clear(); } | |
| 162 | 新增: this.lease = input.lease; | |
| 163 | 新增: this.deadline = this.now() + 6500; | |
| 164 | 新增: this.blocked = Array.isArray(input.blocked) ? input.blocked : []; | |
| 165 | 新增: for (const [id, value] of this.pending) if (this.blocked.includes(value.origin)) this.pending.delete(id); | |
| 166 | 新增: const result = { available: true, origin: "", document: "", candidates: [], entries: [] }; | |
| 167 | 新增: await Promise.all([...this.sessions.values()].map(async entry => { | |
| 168 | 新增: try { | |
| 169 | 新增: const value = await this.evaluate(entry, `(() => { | |
| 170 | 新增: const v = globalThis.cageVault; | |
| 171 | 新增: if (!v || location.protocol !== 'https:') return null; | |
| 172 | 新增: if (v.lease !== ${JSON.stringify(this.lease)}) { v.previousUsername = ""; v.previousAt = 0; } | |
| 173 | 新增: v.lease = ${JSON.stringify(this.lease)}; v.deadline = Date.now() + 6500; | |
| 174 | 新增: return {origin: location.origin, document: v.document}; | |
| 175 | 新增: })()`); | |
| 176 | 新增: if (value && entry.tab === input.tab && entry.tab === this.active() && !this.tab(entry.tab)?.login) | |
| 177 | 新增: Object.assign(result, value); | |
| 178 | 新增: } catch {} | |
| 179 | 新增: })); | |
| 180 | 新增: result.candidates = [...this.pending.values()].map(({ expires, ...value }) => value); | |
| 181 | 新增: return result; | |
| 182 | 新增: } | |
| 183 | 新增: if (!this.lease || input.lease !== this.lease) throw new Error("保险箱已锁定,请重试"); | |
| 184 | 新增: if (input.action === "candidate") { | |
| 185 | 新增: const value = this.pending.get(input.candidate); | |
| 186 | 新增: if (!value) throw new Error("登录记录已过期,请重新登录"); | |
| 187 | 新增: return value; | |
| 188 | 新增: } | |
| 189 | 新增: if (input.action === "dismiss") { this.pending.delete(input.candidate); return { ok: true }; } | |
| 190 | 新增: if (input.action === "fill") { | |
| 191 | 新增: const entry = [...this.sessions.values()].find(value => value.tab === input.tab); | |
| 192 | 新增: if (!entry || input.tab !== this.active() || this.tab(input.tab)?.login) throw new Error("当前网页已切换"); | |
| 193 | 新增: const filled = await this.evaluate(entry, `globalThis.cageVault?.fill(${JSON.stringify(input)}) === true`); | |
| 194 | 新增: if (filled) this.usernames.set(entry.tab, { origin: input.origin, username: input.username, expires: this.now() + 120000 }); | |
| 195 | 新增: if (!filled) throw new Error("未找到可填写的登录框,或页面已变化"); | |
| 196 | 新增: return { ok: true }; | |
| 197 | 新增: } | |
| 198 | 新增: throw new Error("密码操作无效"); | |
| 199 | 新增: } | |
| 200 | 新增:} | |
| @@ -0,0 +1,413 @@ | ||
| 1 | 新增:#!/usr/bin/python3 | |
| 2 | 新增:"""Launch the official guest CLI and export only its subscription status fields.""" | |
| 3 | 新增:import fcntl | |
| 4 | 新增:from datetime import datetime | |
| 5 | 新增:import hashlib | |
| 6 | 新增:import json | |
| 7 | 新增:import os | |
| 8 | 新增:from pathlib import Path | |
| 9 | 新增:import re | |
| 10 | 新增:import shutil | |
| 11 | 新增:import signal | |
| 12 | 新增:import subprocess | |
| 13 | 新增:import sys | |
| 14 | 新增:import tempfile | |
| 15 | 新增:import time | |
| 16 | 新增: | |
| 17 | 新增: | |
| 18 | 新增:SHIM = "/usr/local/lib/cage-claude-bin" | |
| 19 | 新增:OPEN = "/usr/local/bin/cage-open" | |
| 20 | 新增:HELPER = "/usr/local/bin/cage-claude-account" | |
| 21 | 新增:DEFAULT = "default" | |
| 22 | 新增: | |
| 23 | 新增: | |
| 24 | 新增:def profile(account_id): | |
| 25 | 新增: if account_id != DEFAULT and not re.fullmatch("[0-9a-f]{24}", account_id): | |
| 26 | 新增: raise ValueError("invalid account ID") | |
| 27 | 新增: return Path.home() / ".local/share/cage/claude-accounts" / account_id | |
| 28 | 新增: | |
| 29 | 新增: | |
| 30 | 新增:def config_directory(base): | |
| 31 | 新增: return Path.home() / ".claude" if base.name == DEFAULT else base / "config" | |
| 32 | 新增: | |
| 33 | 新增: | |
| 34 | 新增:def cli_environment(base): | |
| 35 | 新增: env = os.environ.copy() | |
| 36 | 新增: # Executing the real binary must never recurse into the terminal's claude shim. | |
| 37 | 新增: path = [p for p in env.get("PATH", os.defpath).split(os.pathsep) if p and p != SHIM] | |
| 38 | 新增: env["PATH"] = os.pathsep.join([str(Path.home() / ".local/bin"), *path]) | |
| 39 | 新增: if base.name == DEFAULT: | |
| 40 | 新增: # Let Claude resolve its normal ~/.claude.json and ~/.claude itself. | |
| 41 | 新增: # Preserve provider variables: an API-authenticated shell is not a | |
| 42 | 新增: # signed-in default subscription, even if a previous login exists. | |
| 43 | 新增: return env | |
| 44 | 新增: env["CLAUDE_CONFIG_DIR"] = str(config_directory(base)) | |
| 45 | 新增: for name in ("ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_BASE_URL", | |
| 46 | 新增: "CLAUDE_CODE_OAUTH_TOKEN", "CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX", | |
| 47 | 新增: "CLAUDE_CODE_USE_FOUNDRY", "CLAUDE_CODE_USE_GATEWAY"): | |
| 48 | 新增: env.pop(name, None) | |
| 49 | 新增: return env | |
| 50 | 新增: | |
| 51 | 新增: | |
| 52 | 新增:def identity(binary, env, cwd, settings=(), timeout=10): | |
| 53 | 新增: result = subprocess.run([binary, *settings, "auth", "status"], cwd=cwd, env=env, timeout=timeout, | |
| 54 | 新增: stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) | |
| 55 | 新增: # Exit code 1 with JSON is the CLI's documented logged-out response. Any | |
| 56 | 新增: # other failure (including missing JSON) must not sign a known user out. | |
| 57 | 新增: data = json.loads(result.stdout) | |
| 58 | 新增: reported_dir = data.get("configDirectory") | |
| 59 | 新增: correct_dir = isinstance(reported_dir, str) and Path(reported_dir) == Path(env.get("CLAUDE_CONFIG_DIR") or Path.home() / ".claude") | |
| 60 | 新增: if result.returncode not in (0, 1) or not correct_dir: | |
| 61 | 新增: raise ValueError("unexpected auth status") | |
| 62 | 新增: ok = (result.returncode == 0 and data.get("loggedIn") is True and data.get("authMethod") == "claude.ai" | |
| 63 | 新增: and data.get("apiProvider") == "firstParty") | |
| 64 | 新增: if not ok: | |
| 65 | 新增: return {"logged_in": False} | |
| 66 | 新增: return {"logged_in": True, "email": data.get("email"), "organization": data.get("orgId") or data.get("orgName"), | |
| 67 | 新增: "plan": data.get("subscriptionType")} | |
| 68 | 新增: | |
| 69 | 新增: | |
| 70 | 新增:def subject(summary): | |
| 71 | 新增: if not summary.get("logged_in") or not summary.get("email"): | |
| 72 | 新增: return None | |
| 73 | 新增: email = summary["email"].strip().lower() | |
| 74 | 新增: organization = (summary.get("organization") or "").strip() | |
| 75 | 新增: return hashlib.sha256(f"{email}\n{organization}".encode()).hexdigest() | |
| 76 | 新增: | |
| 77 | 新增: | |
| 78 | 新增:def json_file(path): | |
| 79 | 新增: try: | |
| 80 | 新增: return json.loads(path.read_text()) | |
| 81 | 新增: except FileNotFoundError: | |
| 82 | 新增: return {} | |
| 83 | 新增: | |
| 84 | 新增: | |
| 85 | 新增:def valid_window(data, now): | |
| 86 | 新增: if not isinstance(data, dict): | |
| 87 | 新增: return None | |
| 88 | 新增: used, reset = data.get("used_percentage"), data.get("resets_at") | |
| 89 | 新增: if type(used) not in (int, float) or not 0 <= used <= 100: | |
| 90 | 新增: return None | |
| 91 | 新增: if type(reset) != int or (reset != 0 and reset <= now): | |
| 92 | 新增: return None | |
| 93 | 新增: return {"used_percentage": used, "resets_at": reset} | |
| 94 | 新增: | |
| 95 | 新增: | |
| 96 | 新增:def read_quota(base): | |
| 97 | 新增: try: | |
| 98 | 新增: stored = json_file(base / "quota.json") | |
| 99 | 新增: except (ValueError, OSError): | |
| 100 | 新增: return None | |
| 101 | 新增: if not isinstance(stored, dict): | |
| 102 | 新增: return None | |
| 103 | 新增: digest = stored.get("identity", "") | |
| 104 | 新增: seen = stored.get("observed_at") | |
| 105 | 新增: now = int(time.time()) | |
| 106 | 新增: if not isinstance(digest, str) or not re.fullmatch("[a-f0-9]{64}", digest) or type(seen) != int or not 0 < seen <= now: | |
| 107 | 新增: return None | |
| 108 | 新增: result = {} | |
| 109 | 新增: for key in ("five_hour", "seven_day"): | |
| 110 | 新增: window = valid_window(stored.get(key), now) | |
| 111 | 新增: if window: | |
| 112 | 新增: window_seen = stored[key].get("observed_at", seen) | |
| 113 | 新增: if type(window_seen) == int and 0 < window_seen <= now: | |
| 114 | 新增: result[key] = {**window, "observed_at": window_seen} | |
| 115 | 新增: if result: | |
| 116 | 新增: return {**result, "identity": digest, "observed_at": seen} | |
| 117 | 新增: return None | |
| 118 | 新增: | |
| 119 | 新增: | |
| 120 | 新增:def save_usage(base, data, expected, confirm_subject, query_started=None, deadline=None): | |
| 121 | 新增: rate = data.get("rate_limits") | |
| 122 | 新增: if not isinstance(rate, dict): | |
| 123 | 新增: return | |
| 124 | 新增: now = int(time.time()) | |
| 125 | 新增: with (base / "quota.lock").open("a") as lock: | |
| 126 | 新增: if deadline is None: | |
| 127 | 新增: fcntl.flock(lock, fcntl.LOCK_EX) | |
| 128 | 新增: else: | |
| 129 | 新增: while True: | |
| 130 | 新增: try: | |
| 131 | 新增: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) | |
| 132 | 新增: break | |
| 133 | 新增: except BlockingIOError: | |
| 134 | 新增: if time.monotonic() >= deadline: | |
| 135 | 新增: raise TimeoutError("usage cache busy") | |
| 136 | 新增: time.sleep(.05) | |
| 137 | 新增: path = base / "quota.json" | |
| 138 | 新增: previous = read_quota(base) or {} | |
| 139 | 新增: if previous.get("identity") != expected: | |
| 140 | 新增: previous = {} | |
| 141 | 新增: windows = {} | |
| 142 | 新增: changed = False | |
| 143 | 新增: for key in ("five_hour", "seven_day"): | |
| 144 | 新增: old = previous.get(key) | |
| 145 | 新增: new = valid_window(rate.get(key), now) | |
| 146 | 新增: # A redraw of an older terminal must not roll back the more recent | |
| 147 | 新增: # account window observed in another conversation. | |
| 148 | 新增: redraw = query_started is None and old and new and all(old[field] == new[field] for field in ("resets_at", "used_percentage")) | |
| 149 | 新增: older = old and new and (0 < new["resets_at"] < old["resets_at"] or | |
| 150 | 新增: (query_started is None and old["resets_at"] == new["resets_at"] and new["used_percentage"] < old["used_percentage"])) | |
| 151 | 新增: if old and (not new or redraw or older or (query_started is not None and old["observed_at"] > query_started)): | |
| 152 | 新增: windows[key] = old | |
| 153 | 新增: elif new: | |
| 154 | 新增: windows[key] = {**new, "observed_at": now} | |
| 155 | 新增: changed = True | |
| 156 | 新增: # A user can run /login in an open Claude process. Ask the CLI for | |
| 157 | 新增: # its identity on changed readings only; never infer it from a path. | |
| 158 | 新增: if changed and expected and confirm_subject() == expected: | |
| 159 | 新增: windows["observed_at"] = now | |
| 160 | 新增: windows["identity"] = expected | |
| 161 | 新增: with tempfile.NamedTemporaryFile(mode="w", dir=base, delete=False) as tmp: | |
| 162 | 新增: json.dump(windows, tmp, separators=(",", ":")) | |
| 163 | 新增: os.replace(tmp.name, path) | |
| 164 | 新增: | |
| 165 | 新增: | |
| 166 | 新增:def reported_window(percent, stamp, now): | |
| 167 | 新增: reset = 0 | |
| 168 | 新增: if stamp is not None: | |
| 169 | 新增: try: | |
| 170 | 新增: dt = datetime.fromisoformat(stamp.replace("Z", "+00:00")) | |
| 171 | 新增: if dt.tzinfo is None: | |
| 172 | 新增: return None | |
| 173 | 新增: reset = int(dt.timestamp()) | |
| 174 | 新增: except (AttributeError, ValueError, OverflowError): | |
| 175 | 新增: return None | |
| 176 | 新增: return valid_window({"used_percentage": percent, "resets_at": reset}, now) | |
| 177 | 新增: | |
| 178 | 新增: | |
| 179 | 新增:def usage_windows(raw, now): | |
| 180 | 新增: # SDKControlGetUsageResponse is the structured /usage report. The input | |
| 181 | 新增: # contains one control request and no user prompt or generate request. | |
| 182 | 新增: report = None | |
| 183 | 新增: for line in raw.splitlines(): | |
| 184 | 新增: message = json.loads(line) | |
| 185 | 新增: if message.get("type") in ("user", "assistant"): | |
| 186 | 新增: raise ValueError("unexpected conversation during usage query") | |
| 187 | 新增: if message.get("type") == "result" and (message.get("is_error") or message.get("num_turns") != 0): | |
| 188 | 新增: raise ValueError("unexpected inference result") | |
| 189 | 新增: if message.get("type") == "control_response": | |
| 190 | 新增: response = message.get("response") or {} | |
| 191 | 新增: if response.get("request_id") == "quota": | |
| 192 | 新增: if report is not None or response.get("subtype") != "success": | |
| 193 | 新增: raise ValueError("failed usage response") | |
| 194 | 新增: report = response.get("response") | |
| 195 | 新增: if not isinstance(report, dict) or type(report.get("rate_limits_available")) is not bool: | |
| 196 | 新增: raise ValueError("missing structured usage response") | |
| 197 | 新增: session = report.get("session") | |
| 198 | 新增: if not isinstance(session, dict) or session.get("total_cost_usd") != 0 or session.get("model_usage"): | |
| 199 | 新增: raise ValueError("unexpected model use") | |
| 200 | 新增: if not report["rate_limits_available"]: | |
| 201 | 新增: return False, {} | |
| 202 | 新增: rate = report.get("rate_limits") or {} | |
| 203 | 新增: windows = {} | |
| 204 | 新增: for key in ("five_hour", "seven_day"): | |
| 205 | 新增: meter = rate.get(key) | |
| 206 | 新增: if isinstance(meter, dict): | |
| 207 | 新增: reading = reported_window(meter.get("utilization"), meter.get("resets_at"), now) | |
| 208 | 新增: if reading: | |
| 209 | 新增: windows[key] = reading | |
| 210 | 新增: # Some servers supply the unscoped windows in limits[] instead. A | |
| 211 | 新增: # model-specific quota never substitutes for an account's weekly window. | |
| 212 | 新增: candidates = {"session": "five_hour", "weekly_all": "seven_day"} | |
| 213 | 新增: rows = {} | |
| 214 | 新增: ambiguous = set() | |
| 215 | 新增: for row in rate.get("limits") or (): | |
| 216 | 新增: if not isinstance(row, dict): | |
| 217 | 新增: continue | |
| 218 | 新增: key = candidates.get(row.get("kind")) | |
| 219 | 新增: if not key or key in windows or key in ambiguous: | |
| 220 | 新增: continue | |
| 221 | 新增: reading = reported_window(row.get("percent"), row.get("resets_at"), now) | |
| 222 | 新增: if reading and key in rows and rows[key] != reading: | |
| 223 | 新增: ambiguous.add(key) | |
| 224 | 新增: del rows[key] | |
| 225 | 新增: elif reading: | |
| 226 | 新增: rows[key] = reading | |
| 227 | 新增: return True, {**rows, **windows} | |
| 228 | 新增: | |
| 229 | 新增: | |
| 230 | 新增:def changed_identity(): | |
| 231 | 新增: return {"logged_in": False, "usage_status": "identity_changed", "usage_checked_at": int(time.time())} | |
| 232 | 新增: | |
| 233 | 新增: | |
| 234 | 新增:def invoke_usage(binary, env, cwd, options, timeout): | |
| 235 | 新增: command = [binary, *options, "-p", "--input-format", "stream-json", "--verbose", "--output-format", "stream-json", | |
| 236 | 新增: "--no-session-persistence", "--strict-mcp-config", "--tools", ""] | |
| 237 | 新增: request = {"type": "control_request", "request_id": "quota", "request": {"subtype": "get_usage", "skip_behaviors": True}} | |
| 238 | 新增: result = subprocess.run(command, cwd=cwd, env=env, timeout=timeout, input=(json.dumps(request) + "\n").encode(), | |
| 239 | 新增: stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) | |
| 240 | 新增: if result.returncode != 0 or len(result.stdout) > (2 << 20): | |
| 241 | 新增: raise ValueError("usage command failed") | |
| 242 | 新增: return usage_windows(result.stdout, int(time.time())) | |
| 243 | 新增: | |
| 244 | 新增: | |
| 245 | 新增:def query_usage(binary, env, base, expected): | |
| 246 | 新增: if not expected or not re.fullmatch("[a-f0-9]{64}", expected): | |
| 247 | 新增: raise ValueError("missing expected account") | |
| 248 | 新增: deadline = time.monotonic() + 12 | |
| 249 | 新增: started = int(time.time()) | |
| 250 | 新增: status = "error" | |
| 251 | 新增: summary = {} | |
| 252 | 新增: options = ["--setting-sources", "user", "--settings", '{"disableAllHooks":true}'] | |
| 253 | 新增: with tempfile.TemporaryDirectory(prefix="cage-claude-usage-") as cwd: | |
| 254 | 新增: try: | |
| 255 | 新增: summary = identity(binary, env, cwd, options, timeout=4) | |
| 256 | 新增: if subject(summary) != expected: | |
| 257 | 新增: return changed_identity() | |
| 258 | 新增: # Reserve time to recheck the actual identity after the command. | |
| 259 | 新增: timeout = min(8, deadline - time.monotonic() - 2) | |
| 260 | 新增: try: | |
| 261 | 新增: available, windows = invoke_usage(binary, env, cwd, options, max(.1, timeout)) | |
| 262 | 新增: except (OSError, ValueError, TypeError, AttributeError, subprocess.SubprocessError): | |
| 263 | 新增: windows = None | |
| 264 | 新增: after = identity(binary, env, cwd, options, timeout=max(.1, min(4, deadline - time.monotonic()))) | |
| 265 | 新增: if subject(after) != expected: | |
| 266 | 新增: return changed_identity() | |
| 267 | 新增: summary = after | |
| 268 | 新增: if windows: | |
| 269 | 新增: base.mkdir(mode=0o700, parents=True, exist_ok=True) | |
| 270 | 新增: save_usage(base, {"rate_limits": windows}, expected, lambda: expected, started, deadline) | |
| 271 | 新增: if windows is not None: | |
| 272 | 新增: status = {0: "unavailable", 1: "partial", 2: "reported"}[len(windows)] if available else "not_applicable" | |
| 273 | 新增: except (OSError, ValueError, TypeError, AttributeError, subprocess.SubprocessError): | |
| 274 | 新增: # The CLI can print project/account data even on failure. | |
| 275 | 新增: # The host needs a reason category and only verified window data. | |
| 276 | 新增: pass | |
| 277 | 新增: if subject(summary) == expected: | |
| 278 | 新增: previous = read_quota(base) | |
| 279 | 新增: if previous and previous["identity"] == expected: | |
| 280 | 新增: summary["quota"] = previous | |
| 281 | 新增: if status == "unavailable": | |
| 282 | 新增: status = "cached" | |
| 283 | 新增: summary.update(usage_status=status, usage_checked_at=int(time.time())) | |
| 284 | 新增: return summary | |
| 285 | 新增: | |
| 286 | 新增: | |
| 287 | 新增:def has_status_line(base): | |
| 288 | 新增: # Preserve existing user, project and managed status lines, including an | |
| 289 | 新增: # explicit disable. If a settings file is unreadable, defer to Claude. | |
| 290 | 新增: paths = [config_directory(base) / "settings.json", Path("/etc/claude-code/managed-settings.json")] | |
| 291 | 新增: paths.extend(Path("/etc/claude-code/managed-settings.d").glob("*.json")) | |
| 292 | 新增: for folder in (Path.cwd(), *Path.cwd().parents): | |
| 293 | 新增: paths += [folder / ".claude/settings.json", folder / ".claude/settings.local.json"] | |
| 294 | 新增: for path in paths: | |
| 295 | 新增: try: | |
| 296 | 新增: settings = json_file(path) | |
| 297 | 新增: if not isinstance(settings, dict) or "statusLine" in settings or settings.get("allowManagedHooksOnly"): | |
| 298 | 新增: return True | |
| 299 | 新增: except (OSError, ValueError): | |
| 300 | 新增: return True | |
| 301 | 新增: return False | |
| 302 | 新增: | |
| 303 | 新增: | |
| 304 | 新增:def settings_flags(args): | |
| 305 | 新增: flags = [] | |
| 306 | 新增: iterator = iter(args) | |
| 307 | 新增: for arg in iterator: | |
| 308 | 新增: if arg == "--": | |
| 309 | 新增: break | |
| 310 | 新增: key, equals, _ = arg.partition("=") | |
| 311 | 新增: if key in ("--settings", "--setting-sources"): | |
| 312 | 新增: flags.append(arg) | |
| 313 | 新增: if not equals: | |
| 314 | 新增: value = next(iterator, None) | |
| 315 | 新增: if value is None: | |
| 316 | 新增: raise ValueError("missing CLI setting") | |
| 317 | 新增: flags.append(value) | |
| 318 | 新增: return flags | |
| 319 | 新增: | |
| 320 | 新增: | |
| 321 | 新增:def main(args): | |
| 322 | 新增: mode, account_id, *rest = args | |
| 323 | 新增: if mode == "quotas": | |
| 324 | 新增: result = {} | |
| 325 | 新增: for candidate in [account_id, *rest]: | |
| 326 | 新增: quota = read_quota(profile(candidate)) | |
| 327 | 新增: if quota: | |
| 328 | 新增: result[candidate] = quota | |
| 329 | 新增: print(json.dumps(result)) | |
| 330 | 新增: return 0 | |
| 331 | 新增: base = profile(account_id) | |
| 332 | 新增: if account_id == DEFAULT and mode == "login": | |
| 333 | 新增: raise ValueError("new logins require a private profile") | |
| 334 | 新增: if mode in ("usage", "snapshot") and account_id == DEFAULT and not config_directory(base).is_dir(): | |
| 335 | 新增: print(json.dumps(changed_identity() if mode == "usage" else {"logged_in": False})) | |
| 336 | 新增: return 0 | |
| 337 | 新增: original_umask = os.umask(0o077) | |
| 338 | 新增: if account_id != DEFAULT: | |
| 339 | 新增: config_directory(base).mkdir(mode=0o700, parents=True, exist_ok=True) | |
| 340 | 新增: elif mode == "statusline": | |
| 341 | 新增: base.mkdir(mode=0o700, parents=True, exist_ok=True) | |
| 342 | 新增: env = cli_environment(base) | |
| 343 | 新增: if account_id == DEFAULT: | |
| 344 | 新增: directory = env.get("CLAUDE_CONFIG_DIR") or str(config_directory(base)) | |
| 345 | 新增: endpoint = env.get("ANTHROPIC_BASE_URL", "").rstrip("/") | |
| 346 | 新增: if Path(directory) != config_directory(base) or endpoint not in ("", "https://api.anthropic.com"): | |
| 347 | 新增: if mode in ("snapshot", "usage"): | |
| 348 | 新增: print(json.dumps(changed_identity() if mode == "usage" else {"logged_in": False})) | |
| 349 | 新增: return 0 | |
| 350 | 新增: raise ValueError("not the default subscription configuration") | |
| 351 | 新增: binary = shutil.which("claude", path=env["PATH"]) | |
| 352 | 新增: if not binary: | |
| 353 | 新增: raise ValueError("Claude is not installed") | |
| 354 | 新增: if mode == "usage": | |
| 355 | 新增: if len(rest) != 1: | |
| 356 | 新增: raise ValueError("usage requires an expected account") | |
| 357 | 新增: print(json.dumps(query_usage(binary, env, base, rest[0]))) | |
| 358 | 新增: return 0 | |
| 359 | 新增: expected = env.get("CAGE_CLAUDE_SUBJECT") | |
| 360 | 新增: if mode == "statusline": | |
| 361 | 新增: raw = sys.stdin.buffer.read((1 << 20) + 1) | |
| 362 | 新增: if len(raw) <= 1 << 20: | |
| 363 | 新增: save_usage(base, json.loads(raw), expected, lambda: subject(identity(binary, env, Path.cwd()))) | |
| 364 | 新增: print("Cage · Claude") | |
| 365 | 新增: return 0 | |
| 366 | 新增: if mode == "snapshot": | |
| 367 | 新增: summary = identity(binary, env, Path.home()) | |
| 368 | 新增: quota = read_quota(base) | |
| 369 | 新增: if quota and quota["identity"] == subject(summary): | |
| 370 | 新增: summary["quota"] = quota | |
| 371 | 新增: print(json.dumps(summary)) | |
| 372 | 新增: return 0 | |
| 373 | 新增: if mode == "login": | |
| 374 | 新增: env.update(BROWSER=OPEN, CAGE_CLAUDE_LOGIN=account_id) | |
| 375 | 新增: # Set the handler before spawning so SSH/window closure also disposes | |
| 376 | 新增: # the ephemeral browser and its cookies. | |
| 377 | 新增: def interrupted(_signum, _frame): | |
| 378 | 新增: raise KeyboardInterrupt() | |
| 379 | 新增: signal.signal(signal.SIGHUP, interrupted) | |
| 380 | 新增: signal.signal(signal.SIGTERM, interrupted) | |
| 381 | 新增: try: | |
| 382 | 新增: (base / "quota.json").unlink(missing_ok=True) | |
| 383 | 新增: return subprocess.call([binary, "auth", "login", "--claudeai"], cwd=Path.home(), env=env) | |
| 384 | 新增: finally: | |
| 385 | 新增: subprocess.run([OPEN, "--finish-login"], env=env, timeout=8, check=False, | |
| 386 | 新增: stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) | |
| 387 | 新增: if mode == "run": | |
| 388 | 新增: # Profile/project settings can override inherited authentication. Check | |
| 389 | 新增: # the actual CLI method in the project before launching the conversation. | |
| 390 | 新增: options = settings_flags(rest) | |
| 391 | 新增: if not expected or subject(identity(binary, env, Path.cwd(), options)) != expected: | |
| 392 | 新增: print("此项目未使用所选 Claude 订阅。请检查项目配置和账号登录状态。", file=sys.stderr) | |
| 393 | 新增: return 1 | |
| 394 | 新增: flags = [] | |
| 395 | 新增: if not options and not has_status_line(base): | |
| 396 | 新增: settings = {"statusLine": {"type": "command", "command": f"{HELPER} statusline {account_id}"}} | |
| 397 | 新增: flags = ["--settings", json.dumps(settings, separators=(",", ":"))] | |
| 398 | 新增: # The private profile is ready. Claude and its tools must create files | |
| 399 | 新增: # in the shared project using the user's usual umask. | |
| 400 | 新增: os.umask(original_umask) | |
| 401 | 新增: os.execve(binary, [binary, *flags, *rest], env) | |
| 402 | 新增: raise ValueError("unknown operation") | |
| 403 | 新增: | |
| 404 | 新增: | |
| 405 | 新增:if __name__ == "__main__": | |
| 406 | 新增: try: | |
| 407 | 新增: sys.exit(main(sys.argv[1:])) | |
| 408 | 新增: except KeyboardInterrupt: | |
| 409 | 新增: sys.exit(130) | |
| 410 | 新增: except (OSError, ValueError, subprocess.SubprocessError, TypeError): | |
| 411 | 新增: # No raw CLI output, paths, credentials or callback URLs go to logs. | |
| 412 | 新增: print("无法读取 Claude 订阅状态或启动官方 CLI,请检查环境组件与登录状态。", file=sys.stderr) | |
| 413 | 新增: sys.exit(1) | |
| @@ -0,0 +1,253 @@ | ||
| 1 | 新增:import hashlib | |
| 2 | 新增:from datetime import datetime, timezone | |
| 3 | 新增:import importlib.util | |
| 4 | 新增:import json | |
| 5 | 新增:import os | |
| 6 | 新增:from pathlib import Path | |
| 7 | 新增:import subprocess | |
| 8 | 新增:import sys | |
| 9 | 新增:import tempfile | |
| 10 | 新增:import time | |
| 11 | 新增:import unittest | |
| 12 | 新增:from unittest.mock import patch | |
| 13 | 新增: | |
| 14 | 新增:sys.dont_write_bytecode = True | |
| 15 | 新增:source = Path(__file__).with_name("claude-account.py") | |
| 16 | 新增:spec = importlib.util.spec_from_file_location("account", source) | |
| 17 | 新增:helper = importlib.util.module_from_spec(spec) | |
| 18 | 新增:spec.loader.exec_module(helper) | |
| 19 | 新增:FIRST = "1" * 24 | |
| 20 | 新增:SECOND = "2" * 24 | |
| 21 | 新增: | |
| 22 | 新增: | |
| 23 | 新增:class ClaudeAccountTests(unittest.TestCase): | |
| 24 | 新增: def setUp(self): | |
| 25 | 新增: tmp = tempfile.TemporaryDirectory() | |
| 26 | 新增: self.addCleanup(tmp.cleanup) | |
| 27 | 新增: self.home = Path(tmp.name) | |
| 28 | 新增: fake = self.home / ".local/bin/claude" | |
| 29 | 新增: fake.parent.mkdir(parents=True) | |
| 30 | 新增: # Emulate the documented status shape of the official CLI. Its response | |
| 31 | 新增: # deliberately includes fields that must never cross the guest boundary. | |
| 32 | 新增: fake.write_text("""#!/bin/sh | |
| 33 | 新增:if [ "$1" = auth ] && [ "$2" = status ]; then | |
| 34 | 新增: method=claude.ai; if [ -n "$ANTHROPIC_API_KEY" ]; then method=api_key; fi | |
| 35 | 新增: printf '{"configDirectory":"%s","authMethod":"%s","apiProvider":"%s","loggedIn":true,"email":"%s","orgId":"test-org","subscriptionType":"pro","access_token":"must-not-appear"}' "${TEST_CONFIG_RESULT:-${CLAUDE_CONFIG_DIR:-$HOME/.claude}}" "$method" "${TEST_PROVIDER:-firstParty}" "$TEST_EMAIL" | |
| 36 | 新增: exit 0 | |
| 37 | 新增:fi | |
| 38 | 新增:printf '%s\\n' "$@" | |
| 39 | 新增:""") | |
| 40 | 新增: fake.chmod(0o700) | |
| 41 | 新增: self.email = "[email protected]" | |
| 42 | 新增: self.subject = hashlib.sha256((self.email + "\ntest-org").encode()).hexdigest() | |
| 43 | 新增: self.env = {"HOME": str(self.home), "PATH": os.defpath, "TEST_EMAIL": self.email, | |
| 44 | 新增: "CAGE_CLAUDE_SUBJECT": self.subject, "PYTHONDONTWRITEBYTECODE": "1"} | |
| 45 | 新增: | |
| 46 | 新增: def run_helper(self, mode, account, *args, data=None, env=None, check=True): | |
| 47 | 新增: return subprocess.run([sys.executable, str(source), mode, account, *args], env=env or self.env, | |
| 48 | 新增: cwd=self.home, input=json.dumps(data) if data else None, text=True, | |
| 49 | 新增: capture_output=True, check=check) | |
| 50 | 新增: | |
| 51 | 新增: def test_isolated_cli_snapshot_and_subject_bound_quota(self): | |
| 52 | 新增: reset = int(time.time()) + 3600 | |
| 53 | 新增: window = {"used_percentage": 73.4, "resets_at": reset} | |
| 54 | 新增: payload = {"rate_limits": {"five_hour": window, "private": "must-not-appear"}, | |
| 55 | 新增: "last_assistant_message": "must-not-appear"} | |
| 56 | 新增: self.run_helper("statusline", FIRST, data=payload) | |
| 57 | 新增: snapshot = self.run_helper("snapshot", FIRST).stdout | |
| 58 | 新增: self.assertNotIn("must-not-appear", snapshot) | |
| 59 | 新增: window = json.loads(snapshot)["quota"]["five_hour"] | |
| 60 | 新增: self.assertEqual(window["used_percentage"], 73.4) | |
| 61 | 新增: self.assertGreater(window["observed_at"], 0) | |
| 62 | 新增: self.assertNotIn("quota", json.loads(self.run_helper("snapshot", SECOND).stdout)) | |
| 63 | 新增: batch = json.loads(self.run_helper("quotas", FIRST, SECOND).stdout) | |
| 64 | 新增: self.assertEqual(list(batch), [FIRST]) | |
| 65 | 新增: self.assertEqual(set(batch[FIRST]), {"identity", "observed_at", "five_hour"}) | |
| 66 | 新增: self.assertEqual(batch[FIRST]["identity"], self.subject) | |
| 67 | 新增: # A later redraw by an older terminal cannot undo a consumed window. | |
| 68 | 新增: payload["rate_limits"]["five_hour"] = {**window, "used_percentage": 2} | |
| 69 | 新增: self.run_helper("statusline", FIRST, data=payload) | |
| 70 | 新增: self.assertEqual(json.loads(self.run_helper("quotas", FIRST).stdout)[FIRST]["five_hour"], window) | |
| 71 | 新增: # An interactive /login changes the credential while the old session is alive. | |
| 72 | 新增: other_env = {**self.env, "TEST_EMAIL": "[email protected]"} | |
| 73 | 新增: payload["rate_limits"]["five_hour"] = {**window, "used_percentage": 99} | |
| 74 | 新增: self.run_helper("statusline", FIRST, data=payload, env=other_env) | |
| 75 | 新增: self.assertNotIn("quota", json.loads(self.run_helper("snapshot", FIRST, env=other_env).stdout)) | |
| 76 | 新增: self.assertEqual(json.loads(self.run_helper("quotas", FIRST).stdout)[FIRST]["five_hour"], window) | |
| 77 | 新增: self.assertNotEqual(self.run_helper("run", FIRST, env=other_env, check=False).returncode, 0) | |
| 78 | 新增: self.assertNotEqual(self.run_helper("quotas", "../outside", check=False).returncode, 0) | |
| 79 | 新增: | |
| 80 | 新增: def test_missing_window_keeps_its_observation_time(self): | |
| 81 | 新增: now = int(time.time()) | |
| 82 | 新增: with patch.dict(os.environ, self.env): | |
| 83 | 新增: base = helper.profile(FIRST) | |
| 84 | 新增: base.mkdir(parents=True) | |
| 85 | 新增: week = {"used_percentage": 40, "resets_at": now + 86400} | |
| 86 | 新增: # Legacy snapshot: its timestamp applied to both windows. | |
| 87 | 新增: (base / "quota.json").write_text(json.dumps({ | |
| 88 | 新增: "identity": self.subject, "observed_at": now - 3600, "seven_day": week, | |
| 89 | 新增: })) | |
| 90 | 新增: helper.save_usage(base, {"rate_limits": {"five_hour": { | |
| 91 | 新增: "used_percentage": 20, "resets_at": now + 18000, | |
| 92 | 新增: }}}, self.subject, lambda: self.subject) | |
| 93 | 新增: quota = helper.read_quota(base) | |
| 94 | 新增: self.assertEqual(quota["seven_day"]["observed_at"], now - 3600) | |
| 95 | 新增: self.assertGreaterEqual(quota["five_hour"]["observed_at"], now) | |
| 96 | 新增: | |
| 97 | 新增: def test_cli_arguments_and_existing_statusline(self): | |
| 98 | 新增: args = self.run_helper("run", FIRST, "--model", "sonnet").stdout.splitlines() | |
| 99 | 新增: self.assertEqual(args[-2:], ["--model", "sonnet"]) | |
| 100 | 新增: self.assertIn("statusline " + FIRST, json.loads(args[1])["statusLine"]["command"]) | |
| 101 | 新增: config = self.home / ".local/share/cage/claude-accounts" / FIRST / "config" | |
| 102 | 新增: original = '{"statusLine":{"type":"command","command":"my-original-status"}}' | |
| 103 | 新增: (config / "settings.json").write_text(original) | |
| 104 | 新增: args = self.run_helper("run", FIRST, "--model", "sonnet").stdout.splitlines() | |
| 105 | 新增: self.assertEqual(args, ["--model", "sonnet"]) | |
| 106 | 新增: self.assertEqual((config / "settings.json").read_text(), original) | |
| 107 | 新增: | |
| 108 | 新增: def test_default_reuses_the_existing_configuration_and_pin(self): | |
| 109 | 新增: home_config = self.home / ".claude" | |
| 110 | 新增: self.assertEqual(json.loads(self.run_helper("snapshot", "default").stdout), {"logged_in": False}) | |
| 111 | 新增: self.assertFalse(home_config.exists()) | |
| 112 | 新增: home_config.mkdir() | |
| 113 | 新增: history = home_config / "example-history" | |
| 114 | 新增: history.write_text("previous conversation") | |
| 115 | 新增: snap = lambda env: json.loads(self.run_helper("snapshot", "default", env=env).stdout) | |
| 116 | 新增: self.assertEqual(snap(self.env)["email"], self.email) | |
| 117 | 新增: self.assertFalse((self.home / ".local/share/cage/claude-accounts/default").exists()) | |
| 118 | 新增: payload = {"rate_limits": {"five_hour": {"used_percentage": 10, "resets_at": int(time.time()) + 3600}}} | |
| 119 | 新增: self.run_helper("statusline", "default", data=payload) | |
| 120 | 新增: self.assertIn("quota", snap(self.env)) | |
| 121 | 新增: changed = {**self.env, "TEST_EMAIL": "[email protected]"} | |
| 122 | 新增: self.assertNotIn("quota", snap(changed)) | |
| 123 | 新增: self.assertNotEqual(self.run_helper("run", "default", env=changed, check=False).returncode, 0) | |
| 124 | 新增: # Re-observing a different identity in an old process may not assign B's | |
| 125 | 新增: # quota to A, nor change the underlying config or history. | |
| 126 | 新增: payload["rate_limits"]["five_hour"]["used_percentage"] = 99 | |
| 127 | 新增: self.run_helper("statusline", "default", env=changed, data=payload) | |
| 128 | 新增: self.assertEqual(snap(self.env)["quota"]["five_hour"]["used_percentage"], 10) | |
| 129 | 新增: self.assertNotEqual(self.run_helper("login", "default", check=False).returncode, 0) | |
| 130 | 新增: self.assertEqual(history.read_text(), "previous conversation") | |
| 131 | 新增: for override in ({"ANTHROPIC_API_KEY": "fixture-api-key"}, {"CLAUDE_CONFIG_DIR": str(self.home / "different")}, | |
| 132 | 新增: {"ANTHROPIC_BASE_URL": "https://example.test"}, {"TEST_PROVIDER": "gateway"}): | |
| 133 | 新增: self.assertEqual(snap({**self.env, **override}), {"logged_in": False}) | |
| 134 | 新增: unknown = self.run_helper("snapshot", "default", env={**self.env, "TEST_CONFIG_RESULT": str(self.home / "different")}, check=False) | |
| 135 | 新增: self.assertNotEqual(unknown.returncode, 0) | |
| 136 | 新增: | |
| 137 | 新增: def test_cancel_login_closes_browser_even_when_cli_fails(self): | |
| 138 | 新增: env = {**self.env} | |
| 139 | 新增: with patch.dict(os.environ, env, clear=True), patch.object(helper, "OPEN", "/bin/true"), \ | |
| 140 | 新增: patch.object(helper.subprocess, "call", side_effect=KeyboardInterrupt), \ | |
| 141 | 新增: patch.object(helper.subprocess, "run") as run: | |
| 142 | 新增: with self.assertRaises(KeyboardInterrupt): | |
| 143 | 新增: helper.main(["login", FIRST]) | |
| 144 | 新增: self.assertEqual(run.call_args.args[0], ["/bin/true", "--finish-login"]) | |
| 145 | 新增: self.assertEqual(run.call_args.kwargs["env"]["CAGE_CLAUDE_LOGIN"], FIRST) | |
| 146 | 新增: | |
| 147 | 新增: def install_usage_fixture(self): | |
| 148 | 新增: cli = self.home / ".local/bin/claude" | |
| 149 | 新增: cli.write_text("#!" + sys.executable + "\n" + """import json, os, sys | |
| 150 | 新增:from pathlib import Path | |
| 151 | 新增:home = Path.home() | |
| 152 | 新增:args = sys.argv[1:] | |
| 153 | 新增:def log(text): | |
| 154 | 新增: with (home / 'calls').open('a') as output: output.write(text + '\\n') | |
| 155 | 新增:if args[-2:] == ['auth','status']: | |
| 156 | 新增: log('auth') | |
| 157 | 新增: email = os.environ['TEST_EMAIL'] | |
| 158 | 新增: if (home / 'swapped').exists(): | |
| 159 | 新增: email = '[email protected]' | |
| 160 | 新增: print(json.dumps({'authMethod':'claude.ai','apiProvider':'firstParty','loggedIn':True, | |
| 161 | 新增: 'configDirectory':os.environ.get('CLAUDE_CONFIG_DIR',str(home/'.claude')), | |
| 162 | 新增: 'email':email,'orgId':'test-org','subscriptionType':'pro'})) | |
| 163 | 新增:elif '-p' in args: | |
| 164 | 新增: request = json.loads(sys.stdin.read()) | |
| 165 | 新增: assert request == {'type':'control_request','request_id':'quota','request':{'subtype':'get_usage','skip_behaviors':True}} | |
| 166 | 新增: assert '--no-session-persistence' in args and '--strict-mcp-config' in args and '--verbose' in args | |
| 167 | 新增: assert args[args.index('--output-format') + 1] == 'stream-json' | |
| 168 | 新增: assert args[args.index('--input-format') + 1] == 'stream-json' | |
| 169 | 新增: assert args[args.index('--tools') + 1] == '' | |
| 170 | 新增: assert json.loads(args[args.index('--settings')+1])['disableAllHooks'] is True | |
| 171 | 新增: assert Path.cwd() != home and not Path.cwd().is_relative_to(home) | |
| 172 | 新增: log('usage') | |
| 173 | 新增: if os.environ.get('SWAP') == '1': | |
| 174 | 新增: (home / 'swapped').touch() | |
| 175 | 新增: data = {'rate_limits_available':os.environ.get('AVAILABLE') != 'false', | |
| 176 | 新增: 'rate_limits':{'limits':json.loads(os.environ['ROWS']), **json.loads(os.environ.get('LEGACY','{}'))}, | |
| 177 | 新增: 'session':{'total_cost_usd':0,'model_usage':{}}, 'private':'private-raw-output'} | |
| 178 | 新增: print(json.dumps({'type':'control_response','response':{'request_id':'quota','subtype':'success','response':data}})) | |
| 179 | 新增: if os.environ.get('TURNS'): | |
| 180 | 新增: print(json.dumps({'type':'result','num_turns':int(os.environ['TURNS']),'is_error':False})) | |
| 181 | 新增: sys.exit(int(os.environ.get('EXIT','0'))) | |
| 182 | 新增:else: | |
| 183 | 新增: sys.exit(7) | |
| 184 | 新增:""") | |
| 185 | 新增: cli.chmod(0o700) | |
| 186 | 新增: | |
| 187 | 新增: def test_official_usage_windows_are_subject_bound_and_independently_cached(self): | |
| 188 | 新增: self.install_usage_fixture() | |
| 189 | 新增: reset = int(time.time()) + 18000 | |
| 190 | 新增: date = datetime.fromtimestamp(reset, timezone.utc).isoformat() | |
| 191 | 新增: weekly = {"kind": "weekly_all", "percent": 34.5, "resets_at": date} | |
| 192 | 新增: session = {"kind": "session", "percent": 0, "resets_at": None} | |
| 193 | 新增: def query(rows, account="default", **extra): | |
| 194 | 新增: env = {**self.env, "ROWS": json.dumps(rows), **extra} | |
| 195 | 新增: result = self.run_helper("usage", account, self.subject, env=env) | |
| 196 | 新增: self.assertNotIn("private-raw-output", result.stdout + result.stderr) | |
| 197 | 新增: return json.loads(result.stdout) | |
| 198 | 新增: (self.home / ".claude").mkdir() | |
| 199 | 新增: first = query([weekly, session, {"kind":"weekly_scoped","percent":99,"resets_at":date}]) | |
| 200 | 新增: self.assertEqual(first["usage_status"], "reported") | |
| 201 | 新增: self.assertEqual(first["quota"]["seven_day"]["resets_at"], reset) | |
| 202 | 新增: self.assertEqual(first["quota"]["five_hour"]["used_percentage"], 0) | |
| 203 | 新增: self.assertEqual(first["quota"]["five_hour"]["resets_at"], 0) | |
| 204 | 新增: # A passive redraw doesn't refresh either age. A completed control | |
| 205 | 新增: # query refreshes only the window actually returned by the CLI. | |
| 206 | 新增: path = self.home / ".local/share/cage/claude-accounts/default/quota.json" | |
| 207 | 新增: stored = json.loads(path.read_text()) | |
| 208 | 新增: old = int(time.time()) - 300 | |
| 209 | 新增: stored["observed_at"] = stored["five_hour"]["observed_at"] = stored["seven_day"]["observed_at"] = old | |
| 210 | 新增: path.write_text(json.dumps(stored)) | |
| 211 | 新增: self.run_helper("statusline", "default", data={"rate_limits": { | |
| 212 | 新增: "five_hour": stored["five_hour"], "seven_day": stored["seven_day"], | |
| 213 | 新增: }}) | |
| 214 | 新增: self.assertEqual(json.loads(path.read_text()), stored) | |
| 215 | 新增: partial = query([weekly]) | |
| 216 | 新增: self.assertEqual(partial["usage_status"], "partial") | |
| 217 | 新增: self.assertGreater(partial["usage_checked_at"], old) | |
| 218 | 新增: self.assertEqual(partial["quota"]["five_hour"]["observed_at"], old) | |
| 219 | 新增: self.assertGreater(partial["quota"]["seven_day"]["observed_at"], old) | |
| 220 | 新增: stored = json.loads(path.read_text()) | |
| 221 | 新增: self.assertEqual(query([], FIRST)["usage_status"], "unavailable") | |
| 222 | 新增: self.assertEqual(query(None)["usage_status"], "cached") | |
| 223 | 新增: self.assertEqual(query(None, AVAILABLE="false")["usage_status"], "not_applicable") | |
| 224 | 新增: self.assertEqual(query([weekly], EXIT="1")["usage_status"], "error") | |
| 225 | 新增: self.assertEqual(query([weekly], TURNS="1")["usage_status"], "error") | |
| 226 | 新增: self.assertEqual(json.loads(path.read_text()), stored) | |
| 227 | 新增: changed = query([dict(session, percent=91)], SWAP="1") | |
| 228 | 新增: self.assertEqual(changed["usage_status"], "identity_changed") | |
| 229 | 新增: self.assertNotIn("quota", changed) | |
| 230 | 新增: self.assertEqual(json.loads(path.read_text()), stored) | |
| 231 | 新增: calls = self.home / "calls" | |
| 232 | 新增: calls.write_text("") | |
| 233 | 新增: self.assertEqual(query([weekly])["usage_status"], "identity_changed") | |
| 234 | 新增: self.assertEqual(calls.read_text().splitlines(), ["auth"]) | |
| 235 | 新增: | |
| 236 | 新增: def test_legacy_control_windows_and_row_fallback(self): | |
| 237 | 新增: self.install_usage_fixture() | |
| 238 | 新增: now = int(time.time()) | |
| 239 | 新增: stamp = datetime.fromtimestamp(now + 3600, timezone.utc).isoformat() | |
| 240 | 新增: legacy = {"five_hour":{"utilization":45.5,"resets_at":stamp}, "seven_day":{"utilization":None,"resets_at":stamp}, | |
| 241 | 新增: "seven_day_sonnet":{"utilization":98,"resets_at":stamp}} | |
| 242 | 新增: rows = [{"kind":"session","percent":12,"resets_at":stamp},{"kind":"weekly_all","percent":67,"resets_at":None}] | |
| 243 | 新增: env = {**self.env,"ROWS":json.dumps(rows),"LEGACY":json.dumps(legacy)} | |
| 244 | 新增: observed = json.loads(self.run_helper("usage", FIRST, self.subject, env=env).stdout) | |
| 245 | 新增: self.assertEqual(observed["usage_status"], "reported") | |
| 246 | 新增: self.assertEqual(observed["quota"]["five_hour"]["used_percentage"], 45.5) | |
| 247 | 新增: self.assertEqual(observed["quota"]["five_hour"]["resets_at"], now + 3600) | |
| 248 | 新增: self.assertEqual(observed["quota"]["seven_day"]["used_percentage"], 67) | |
| 249 | 新增: self.assertEqual(observed["quota"]["seven_day"]["resets_at"], 0) | |
| 250 | 新增: | |
| 251 | 新增: | |
| 252 | 新增:if __name__ == "__main__": | |
| 253 | 新增: unittest.main() | |
| @@ -17,8 +17,12 @@ var claudeDesktopStart string | ||
| 17 | 17 | //go:embed guest-open.sh |
| 18 | 18 | var guestOpen string |
| 19 | 19 | |
| 20 | 新增://go:embed browser-login.mjs | |
| 21 | 新增:var browserLogin string | |
| 22 | 新增: | |
| 20 | 23 | func guestOpenScript() string { |
| 21 | 删除: return "sudo tee /usr/local/bin/cage-open >/dev/null <<'CAGE_OPEN_URL'\n" + guestOpen + "\nCAGE_OPEN_URL\nsudo chmod 0755 /usr/local/bin/cage-open\nsudo ln -sf /usr/local/bin/cage-open /usr/local/bin/xdg-open\n" | |
| 24 | 新增: return "sudo tee /usr/local/lib/browser-login.mjs >/dev/null <<'CAGE_BROWSER_LOGIN'\n" + browserLogin + "\nCAGE_BROWSER_LOGIN\n" + | |
| 25 | 新增: "sudo tee /usr/local/bin/cage-open >/dev/null <<'CAGE_OPEN_URL'\n" + guestOpen + "\nCAGE_OPEN_URL\nsudo chmod 0755 /usr/local/bin/cage-open\nsudo ln -sf /usr/local/bin/cage-open /usr/local/bin/xdg-open\n" | |
| 22 | 26 | } |
| 23 | 27 | |
| 24 | 28 | func ClaudeDesktopInstallScript() string { |
| @@ -17,23 +17,26 @@ func TestDesktopCallbackFocusAfterHandoff(t *testing.T) { | ||
| 17 | 17 | t.Skip("node unavailable") |
| 18 | 18 | } |
| 19 | 19 | for _, tc := range []struct { |
| 20 | 删除: name, url, path string | |
| 21 | 删除: fail bool | |
| 20 | 新增: name, url, path, login string | |
| 21 | 新增: fail bool | |
| 22 | 22 | }{ |
| 23 | 删除: {"callback", "claude://login?code=private-test-value", "/desktop-focus", false}, | |
| 24 | 删除: {"failed-callback", "claude://login?code=private-test-value", "", true}, | |
| 25 | 删除: {"web-link", "https://example.com/login", "/new", false}, | |
| 23 | 新增: {"callback", "claude://login?code=private-test-value", "/desktop-focus", "", false}, | |
| 24 | 新增: {"failed-callback", "claude://login?code=private-test-value", "", "", true}, | |
| 25 | 新增: {"web-link", "https://example.com/login", "/new", "", false}, | |
| 26 | 新增: {"cli-login", "https://claude.ai/oauth/authorize?state=private-test-value", "/login-open", "1234567890abcdef", false}, | |
| 27 | 新增: {"finish-cli-login", "--finish-login", "/login-finish", "1234567890abcdef", false}, | |
| 26 | 28 | } { |
| 27 | 29 | t.Run(tc.name, func(t *testing.T) { |
| 28 | 30 | dir := t.TempDir() |
| 29 | 删除: type request struct{ Path, Auth, URL string } | |
| 31 | 新增: type request struct{ Path, Auth, URL, Login string } | |
| 30 | 32 | requests := make(chan request, 2) |
| 31 | 33 | server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 32 | 34 | var body struct { |
| 33 | 删除: URL string `json:"url"` | |
| 35 | 新增: URL string `json:"url"` | |
| 36 | 新增: Login string `json:"login"` | |
| 34 | 37 | } |
| 35 | 38 | _ = json.NewDecoder(r.Body).Decode(&body) |
| 36 | 删除: requests <- request{r.URL.Path, r.Header.Get("Authorization"), body.URL} | |
| 39 | 新增: requests <- request{r.URL.Path, r.Header.Get("Authorization"), body.URL, body.Login} | |
| 37 | 40 | w.Write([]byte(`{"ok":true}`)) |
| 38 | 41 | })) |
| 39 | 42 | defer server.Close() |
| @@ -54,7 +57,7 @@ func TestDesktopCallbackFocusAfterHandoff(t *testing.T) { | ||
| 54 | 57 | code = "1" |
| 55 | 58 | } |
| 56 | 59 | cmd := exec.Command("sh", "-c", script, "cage-open", tc.url) |
| 57 | 删除: cmd.Env = append(os.Environ(), "PATH="+dir+":"+os.Getenv("PATH"), "TEST_NODE="+node, "CALLBACK_EXIT="+code) | |
| 60 | 新增: cmd.Env = append(os.Environ(), "PATH="+dir+":"+os.Getenv("PATH"), "TEST_NODE="+node, "CALLBACK_EXIT="+code, "CAGE_CLAUDE_LOGIN="+tc.login) | |
| 58 | 61 | out, err := cmd.CombinedOutput() |
| 59 | 62 | if tc.fail { |
| 60 | 63 | if err == nil { |
| @@ -73,10 +76,10 @@ func TestDesktopCallbackFocusAfterHandoff(t *testing.T) { | ||
| 73 | 76 | select { |
| 74 | 77 | case r := <-requests: |
| 75 | 78 | wantURL := "" |
| 76 | 删除: if tc.path == "/new" { | |
| 79 | 新增: if tc.path == "/new" || tc.path == "/login-open" { | |
| 77 | 80 | wantURL = tc.url |
| 78 | 81 | } |
| 79 | 删除: if r.Path != tc.path || r.Auth != "Bearer test-only" || r.URL != wantURL { | |
| 82 | 新增: if r.Path != tc.path || r.Auth != "Bearer test-only" || r.URL != wantURL || r.Login != tc.login { | |
| 80 | 83 | t.Fatalf("unexpected request: %+v", r) |
| 81 | 84 | } |
| 82 | 85 | default: |
| @@ -1,18 +1,29 @@ | ||
| 1 | 1 | #!/bin/sh |
| 2 | 2 | set -eu |
| 3 | 3 | case "${1:-}" in |
| 4 | 新增: --finish-login) | |
| 5 | 新增: [ -n "${CAGE_CLAUDE_LOGIN:-}" ] || exit 2 | |
| 6 | 新增: set -- /login-finish "" "$CAGE_CLAUDE_LOGIN" | |
| 7 | 新增: ;; | |
| 4 | 8 | claude://*) |
| 5 | 9 | sudo -u cage /usr/local/bin/cage-claude-open "$1" |
| 6 | 10 | # Publish focus only after the running application accepted the handoff. |
| 7 | 11 | # The browser service never receives the login URL or its credentials. |
| 8 | 12 | set -- /desktop-focus |
| 9 | 13 | ;; |
| 10 | 删除: http://*|https://*|about:blank) set -- /new "$1" ;; | |
| 14 | 新增: http://*|https://*|about:blank) | |
| 15 | 新增: if [ -n "${CAGE_CLAUDE_LOGIN:-}" ]; then | |
| 16 | 新增: set -- /login-open "$1" "$CAGE_CLAUDE_LOGIN" | |
| 17 | 新增: else | |
| 18 | 新增: set -- /new "$1" | |
| 19 | 新增: fi | |
| 20 | 新增: ;; | |
| 11 | 21 | *) echo 'Only HTTP(S) browser URLs and Claude desktop callbacks are accepted.' >&2; exit 2;; |
| 12 | 22 | esac |
| 13 | 删除:exec sudo -u cage-browser /usr/bin/node --input-type=module - "$@" <<'NODE' | |
| 14 | 删除:import {readFileSync} from 'node:fs'; | |
| 15 | 删除:const {token}=JSON.parse(readFileSync('/etc/claude-cage/browser-control.json','utf8')); | |
| 16 | 删除:const response=await fetch('http://127.0.0.1:18500'+process.argv[2],{method:'POST',headers:{Authorization:'Bearer '+token,'Content-Type':'application/json'},body:JSON.stringify(process.argv[2]==='/new'?{url:process.argv[3]}:{})}); | |
| 23 | 新增:# sudo records its arguments in the system journal. Send the URL on stdin. | |
| 24 | 新增:printf '%s' "${2:-}" | sudo -u cage-browser /usr/bin/node --input-type=module -e ' | |
| 25 | 新增:import {readFileSync} from "node:fs"; | |
| 26 | 新增:const {token}=JSON.parse(readFileSync("/etc/claude-cage/browser-control.json","utf8")); | |
| 27 | 新增:const response=await fetch("http://127.0.0.1:18500"+process.argv[1],{method:"POST",headers:{Authorization:"Bearer "+token,"Content-Type":"application/json"},body:JSON.stringify({url:readFileSync(0,"utf8"),login:process.argv[2]})}); | |
| 17 | 28 | if(!response.ok)process.exit(1); |
| 18 | 删除:NODE | |
| 29 | 新增:' "$1" "${3:-}" | |
| @@ -7,6 +7,10 @@ if ! command -v X0tigervnc >/dev/null || ! command -v Xtigervnc >/dev/null || ! | ||
| 7 | 7 | sudo env DEBIAN_FRONTEND=noninteractive APT_CONFIG="${CAGE_APT_CONFIG:-/dev/null}" apt-get install -y --no-install-recommends tigervnc-standalone-server tigervnc-scraping-server tigervnc-tools openbox x11-xserver-utils xdotool libgtk-3-0 ibus ibus-gtk3 gir1.2-ibus-1.0 python3-gi |
| 8 | 8 | fi |
| 9 | 9 | sudo install -d -m 0755 /etc/claude-cage /usr/local/lib |
| 10 | 新增:# New website passwords belong to the host vault. Keep existing browser data. | |
| 11 | 新增:sudo install -d -m 0755 /etc/chromium/policies/managed | |
| 12 | 新增:printf '%s\n' '{"PasswordManagerEnabled":false}' | sudo tee /etc/chromium/policies/managed/cage-password-vault.json >/dev/null | |
| 13 | 新增:sudo chmod 0644 /etc/chromium/policies/managed/cage-password-vault.json | |
| 10 | 14 | sudo tee /usr/local/bin/cage-editor-start >/dev/null <<'SCRIPT' |
| 11 | 15 | #!/bin/sh |
| 12 | 16 | set -eu |
| @@ -19,6 +19,20 @@ var guestDependencies string | ||
| 19 | 19 | //go:embed guest-services.sh |
| 20 | 20 | var guestServices string |
| 21 | 21 | |
| 22 | 新增://go:embed claude-account.py | |
| 23 | 新增:var claudeAccountHelper string | |
| 24 | 新增: | |
| 25 | 新增:func claudeAccountScript() string { | |
| 26 | 新增: return "sudo tee /usr/local/bin/cage-claude-account >/dev/null <<'CAGE_CLAUDE_ACCOUNT'\n" + claudeAccountHelper + "\nCAGE_CLAUDE_ACCOUNT\nsudo chmod 0755 /usr/local/bin/cage-claude-account\n" + | |
| 27 | 新增: `sudo install -d -m 0755 /usr/local/lib/cage-claude-bin | |
| 28 | 新增:sudo tee /usr/local/lib/cage-claude-bin/claude >/dev/null <<'CAGE_CLAUDE_SHIM' | |
| 29 | 新增:#!/bin/sh | |
| 30 | 新增:exec /usr/local/bin/cage-claude-account run "$CAGE_CLAUDE_ACCOUNT_ID" "$@" | |
| 31 | 新增:CAGE_CLAUDE_SHIM | |
| 32 | 新增:sudo chmod 0755 /usr/local/lib/cage-claude-bin/claude | |
| 33 | 新增:` | |
| 34 | 新增:} | |
| 35 | 新增: | |
| 22 | 36 | //go:embed guest-audio.sh |
| 23 | 37 | var guestAudio string |
| 24 | 38 | |
| @@ -31,9 +45,35 @@ var novncPatch string | ||
| 31 | 45 | //go:embed clipboard.js |
| 32 | 46 | var clipboardJS string |
| 33 | 47 | |
| 48 | 新增://go:embed browser-vault.mjs | |
| 49 | 新增:var browserVault string | |
| 50 | 新增: | |
| 34 | 51 | //go:embed browser-agent.mjs |
| 35 | 52 | var browserAgent string |
| 36 | 53 | |
| 54 | 新增://go:embed browser-clipboard.mjs | |
| 55 | 新增:var browserClipboard string | |
| 56 | 新增: | |
| 57 | 新增://go:embed split-extension/manifest.json | |
| 58 | 新增:var splitManifest string | |
| 59 | 新增: | |
| 60 | 新增://go:embed split-extension/control.html | |
| 61 | 新增:var splitPage string | |
| 62 | 新增: | |
| 63 | 新增://go:embed split-extension/control.js | |
| 64 | 新增:var splitControl string | |
| 65 | 新增: | |
| 66 | 新增:func splitExtensionScript() string { | |
| 67 | 新增: return "sudo install -d -m 0755 /usr/local/lib/cage-split\n" + | |
| 68 | 新增: "sudo tee /usr/local/lib/cage-split/manifest.json >/dev/null <<'CAGE_MANIFEST'\n" + splitManifest + "\nCAGE_MANIFEST\n" + | |
| 69 | 新增: "sudo tee /usr/local/lib/cage-split/control.html >/dev/null <<'CAGE_HTML'\n" + splitPage + "\nCAGE_HTML\n" + | |
| 70 | 新增: "sudo tee /usr/local/lib/cage-split/control.js >/dev/null <<'CAGE_CONTROL'\n" + splitControl + "\nCAGE_CONTROL\n" | |
| 71 | 新增:} | |
| 72 | 新增: | |
| 73 | 新增:func browserClipboardScript() string { | |
| 74 | 新增: return "sudo tee /usr/local/lib/browser-clipboard.mjs >/dev/null <<'CAGE_BROWSER_CLIPBOARD'\n" + browserClipboard + "\nCAGE_BROWSER_CLIPBOARD\n" | |
| 75 | 新增:} | |
| 76 | 新增: | |
| 37 | 77 | //go:embed browser-audit.mjs |
| 38 | 78 | var browserAudit string |
| 39 | 79 | |
| @@ -80,7 +120,7 @@ func imageInputScript() string { | ||
| 80 | 120 | } |
| 81 | 121 | |
| 82 | 122 | func browserServices() string { |
| 83 | 删除: return guestMemory + "\n" + guestDiagnostics() + guestAudio + "\n" + guestOpenScript() + imageInputScript() + "\nsudo tee /usr/local/lib/browser-uploads.mjs >/dev/null <<'CAGE_BROWSER_UPLOADS'\n" + browserUploads + "\nCAGE_BROWSER_UPLOADS\n" + guestServices + "\nsudo tee /usr/local/lib/browser-downloads.mjs >/dev/null <<'CAGE_BROWSER_DOWNLOADS'\n" + browserDownloads + "\nCAGE_BROWSER_DOWNLOADS\n" + "\nsudo tee /usr/local/bin/cage-editor-migrate >/dev/null <<'CAGE_EDITOR_MIGRATE'\n" + editorMigrate + "\nCAGE_EDITOR_MIGRATE\nsudo chmod 0755 /usr/local/bin/cage-editor-migrate\n" + "\nsudo tee /usr/local/lib/browser-audit.mjs >/dev/null <<'CAGE_BROWSER_AUDIT'\n" + browserAudit + "\nCAGE_BROWSER_AUDIT\n" + "\nsudo tee /usr/local/lib/cage-browser-agent.mjs >/dev/null <<'CAGE_BROWSER_AGENT'\n" + browserAgent + "\nCAGE_BROWSER_AGENT\n" + "sudo tee /usr/local/bin/cage-save-download >/dev/null <<'CAGE_DOWNLOAD_HELPER'\n" + saveDownload + "\nCAGE_DOWNLOAD_HELPER\nsudo chmod 0755 /usr/local/bin/cage-save-download\nprintf 'cage-browser ALL=(root) NOPASSWD: /usr/local/bin/cage-save-download *\\n' | sudo tee /etc/sudoers.d/cage-download >/dev/null\nsudo chmod 0440 /etc/sudoers.d/cage-download\n" + "\nsudo python3 - <<'CAGE_NOVNC_PATCH'\n" + novncPatch + "\nCAGE_NOVNC_PATCH\n" + "\nsudo tee /usr/share/novnc/cage-clipboard.js >/dev/null <<'CAGE_CLIPBOARD_JS'\n" + clipboardJS + "\nCAGE_CLIPBOARD_JS\n" + `sudo python3 - <<'PYCODE' | |
| 123 | 新增: return "\nsudo tee /usr/local/lib/browser-vault.mjs >/dev/null <<'CAGE_BROWSER_VAULT'\n" + browserVault + "\nCAGE_BROWSER_VAULT\n" + guestMemory + "\n" + guestDiagnostics() + guestAudio + "\n" + guestOpenScript() + splitExtensionScript() + browserClipboardScript() + imageInputScript() + "\nsudo tee /usr/local/lib/browser-uploads.mjs >/dev/null <<'CAGE_BROWSER_UPLOADS'\n" + browserUploads + "\nCAGE_BROWSER_UPLOADS\n" + guestServices + "\nsudo tee /usr/local/lib/browser-downloads.mjs >/dev/null <<'CAGE_BROWSER_DOWNLOADS'\n" + browserDownloads + "\nCAGE_BROWSER_DOWNLOADS\n" + "\nsudo tee /usr/local/bin/cage-editor-migrate >/dev/null <<'CAGE_EDITOR_MIGRATE'\n" + editorMigrate + "\nCAGE_EDITOR_MIGRATE\nsudo chmod 0755 /usr/local/bin/cage-editor-migrate\n" + "\nsudo tee /usr/local/lib/browser-audit.mjs >/dev/null <<'CAGE_BROWSER_AUDIT'\n" + browserAudit + "\nCAGE_BROWSER_AUDIT\n" + "\nsudo tee /usr/local/lib/cage-browser-agent.mjs >/dev/null <<'CAGE_BROWSER_AGENT'\n" + browserAgent + "\nCAGE_BROWSER_AGENT\n" + "sudo tee /usr/local/bin/cage-save-download >/dev/null <<'CAGE_DOWNLOAD_HELPER'\n" + saveDownload + "\nCAGE_DOWNLOAD_HELPER\nsudo chmod 0755 /usr/local/bin/cage-save-download\nprintf 'cage-browser ALL=(root) NOPASSWD: /usr/local/bin/cage-save-download *\\n' | sudo tee /etc/sudoers.d/cage-download >/dev/null\nsudo chmod 0440 /etc/sudoers.d/cage-download\n" + "\nsudo python3 - <<'CAGE_NOVNC_PATCH'\n" + novncPatch + "\nCAGE_NOVNC_PATCH\n" + "\nsudo tee /usr/share/novnc/cage-clipboard.js >/dev/null <<'CAGE_CLIPBOARD_JS'\n" + clipboardJS + "\nCAGE_CLIPBOARD_JS\n" + `sudo python3 - <<'PYCODE' | |
| 84 | 124 | from pathlib import Path |
| 85 | 125 | import re |
| 86 | 126 | p = Path("/usr/share/novnc/vnc.html") |
| @@ -156,7 +196,7 @@ func (c Config) StartScript() string { | ||
| 156 | 196 | } |
| 157 | 197 | |
| 158 | 198 | func componentStartScript() string { |
| 159 | 删除: return browserServices() + "\nsudo tee /etc/claude-cage/editor-theme.json >/dev/null <<'CAGE_EDITOR_THEME'\n" + editorTheme + "\nCAGE_EDITOR_THEME\nif systemctl is-active --quiet cage-editor.service; then sudo systemctl stop cage-editor.service; fi\n" + guestStart | |
| 199 | 新增: return claudeAccountScript() + browserServices() + "\nsudo tee /etc/claude-cage/editor-theme.json >/dev/null <<'CAGE_EDITOR_THEME'\n" + editorTheme + "\nCAGE_EDITOR_THEME\nif systemctl is-active --quiet cage-editor.service; then sudo systemctl stop cage-editor.service; fi\n" + guestStart | |
| 160 | 200 | } |
| 161 | 201 | |
| 162 | 202 | func markGuestStart(body string) string { |
| @@ -0,0 +1 @@ | ||
| 1 | 新增:<!doctype html><meta charset="utf-8"><title>Cage</title><script defer src="control.js"></script> | |
| @@ -0,0 +1,86 @@ | ||
| 1 | 新增:// This extension page is opened as a hidden CDP target by the guest controller. | |
| 2 | 新增:// The debugger permission maps CDP target IDs to Chrome tab IDs. We never | |
| 3 | 新增:// attach a debugger through the extension or accept messages from webpages. | |
| 4 | 新增:const targetsByTab = new Map(); | |
| 5 | 新增:let managedSplit; | |
| 6 | 新增:const faviconVersions = new Map(); | |
| 7 | 新增:chrome.tabs.onUpdated.addListener((tabId, changes) => { | |
| 8 | 新增: if (!("favIconUrl" in changes || "url" in changes || changes.status === "complete")) return; | |
| 9 | 新增: faviconVersions.set(tabId, (faviconVersions.get(tabId) || 0) + 1); | |
| 10 | 新增: void chrome.debugger.getTargets().then(targets => { | |
| 11 | 新增: const target = targets.find(item => item.tabId === tabId); | |
| 12 | 新增: if (target) globalThis.cageFaviconChanged?.(target.id); | |
| 13 | 新增: }).catch(() => {}); | |
| 14 | 新增:}); | |
| 15 | 新增:chrome.tabs.onRemoved.addListener(tabId => faviconVersions.delete(tabId)); | |
| 16 | 新增: | |
| 17 | 新增:// Read Chromium's decoded favicon cache. The extension never requests a site's | |
| 18 | 新增:// icon URL, so its permissions cannot bypass the webpage's image policy. | |
| 19 | 新增:globalThis.readCageFavicon = async function (targetId) { | |
| 20 | 新增: try { | |
| 21 | 新增: const targets = await chrome.debugger.getTargets(); | |
| 22 | 新增: const tabId = targets.find(target => target.id === targetId)?.tabId; | |
| 23 | 新增: if (tabId == null) return null; | |
| 24 | 新增: const tab = await chrome.tabs.get(tabId); | |
| 25 | 新增: const version = faviconVersions.get(tabId); | |
| 26 | 新增: if (!/^https?:/.test(tab.url || "") || !tab.favIconUrl) return { url: tab.url, favicon: "" }; | |
| 27 | 新增: const source = new URL(chrome.runtime.getURL("/_favicon/")); | |
| 28 | 新增: source.searchParams.set("pageUrl", tab.url); | |
| 29 | 新增: source.searchParams.set("size", "32"); | |
| 30 | 新增: source.searchParams.set("version", String(version || 0)); | |
| 31 | 新增: const image = new Image(); | |
| 32 | 新增: image.src = source.href; | |
| 33 | 新增: await image.decode(); | |
| 34 | 新增: const current = await chrome.tabs.get(tabId); | |
| 35 | 新增: if (current.url !== tab.url || current.favIconUrl !== tab.favIconUrl || faviconVersions.get(tabId) !== version) return null; | |
| 36 | 新增: const canvas = document.createElement("canvas"); | |
| 37 | 新增: canvas.width = canvas.height = 32; | |
| 38 | 新增: canvas.getContext("2d").drawImage(image, 0, 0, 32, 32); | |
| 39 | 新增: const favicon = canvas.toDataURL("image/png"); | |
| 40 | 新增: return { url: tab.url, favicon: favicon.length <= 8192 ? favicon : "" }; | |
| 41 | 新增: } catch { | |
| 42 | 新增: return null; | |
| 43 | 新增: } | |
| 44 | 新增:}; | |
| 45 | 新增: | |
| 46 | 新增:chrome.tabs.onActivated.addListener(({ tabId }) => { | |
| 47 | 新增: const target = targetsByTab.get(tabId); | |
| 48 | 新增: if (target) globalThis.cagePaneActivated?.(target); | |
| 49 | 新增:}); | |
| 50 | 新增: | |
| 51 | 新增:chrome.tabs.onUpdated.addListener((id, changes) => { | |
| 52 | 新增: const target = targetsByTab.get(id); | |
| 53 | 新增: if (target && "splitViewId" in changes && changes.splitViewId !== managedSplit) { | |
| 54 | 新增: targetsByTab.clear(); | |
| 55 | 新增: managedSplit = null; | |
| 56 | 新增: globalThis.cagePaneSeparated?.(target); | |
| 57 | 新增: } | |
| 58 | 新增:}); | |
| 59 | 新增: | |
| 60 | 新增:globalThis.setCageSplit = async function (left, right) { | |
| 61 | 新增: if (!chrome.tabs.createSplit) throw new Error("Chromium 155 or later is required"); | |
| 62 | 新增: const targets = await chrome.debugger.getTargets(); | |
| 63 | 新增: const findTab = id => targets.find(t => t.id === id)?.tabId; | |
| 64 | 新增: const pair = left ? await Promise.all([left, right].map(id => chrome.tabs.get(findTab(id)))) : []; | |
| 65 | 新增: if (pair.length && pair[0].incognito !== pair[1].incognito) throw new Error("Separate browser profiles"); | |
| 66 | 新增: targetsByTab.clear(); | |
| 67 | 新增: const affected = new Set(pair.map(tab => tab.splitViewId)); | |
| 68 | 新增: if (managedSplit != null) affected.add(managedSplit); | |
| 69 | 新增: if (!pair.length && managedSplit == null) { | |
| 70 | 新增: // Chromium can restore the foreground split before Cage reconnects. | |
| 71 | 新增: const [active] = await chrome.tabs.query({ active: true, lastFocusedWindow: true }); | |
| 72 | 新增: if (active) affected.add(active.splitViewId); | |
| 73 | 新增: } | |
| 74 | 新增: const open = await chrome.tabs.query({}); | |
| 75 | 新增: for (const id of affected) | |
| 76 | 新增: if (id >= 0 && open.some(tab => tab.splitViewId === id)) await chrome.tabs.unsplit(id); | |
| 77 | 新增: managedSplit = null; | |
| 78 | 新增: if (!pair.length) return; | |
| 79 | 新增: const [a, b] = pair; | |
| 80 | 新增: const index = a.index + (b.windowId === a.windowId && b.index < a.index ? 0 : 1); | |
| 81 | 新增: if (a.windowId !== b.windowId || b.index !== index) | |
| 82 | 新增: await chrome.tabs.move(b.id, { windowId: a.windowId, index }); | |
| 83 | 新增: managedSplit = await chrome.tabs.createSplit([a.id, b.id]); | |
| 84 | 新增: targetsByTab.set(a.id, left); | |
| 85 | 新增: targetsByTab.set(b.id, right); | |
| 86 | 新增:}; | |
| @@ -0,0 +1,6 @@ | ||
| 1 | 新增:{ | |
| 2 | 新增: "manifest_version": 3, | |
| 3 | 新增: "name": "Cage browser panes", | |
| 4 | 新增: "version": "1.0", | |
| 5 | 新增: "permissions": ["debugger", "tabs", "favicon"] | |
| 6 | 新增:} | |
| @@ -38,6 +38,9 @@ func (s *Server) accountAction(w http.ResponseWriter, r *http.Request) { | ||
| 38 | 38 | if !readJSON(w, r, &input, 3<<20) { |
| 39 | 39 | return |
| 40 | 40 | } |
| 41 | 新增: s.account.mu.Lock() | |
| 42 | 新增: vaultLease := s.account.vaultLease | |
| 43 | 新增: s.account.mu.Unlock() | |
| 41 | 44 | var err error |
| 42 | 45 | switch action { |
| 43 | 46 | case "create": |
| @@ -79,5 +82,8 @@ func (s *Server) accountAction(w http.ResponseWriter, r *http.Request) { | ||
| 79 | 82 | requestError(w, err) |
| 80 | 83 | return |
| 81 | 84 | } |
| 85 | 新增: if action == "lock" || action == "suspend" { | |
| 86 | 新增: s.clearBrowserVault(vaultLease) | |
| 87 | 新增: } | |
| 82 | 88 | s.accountStatus(w, r) |
| 83 | 89 | } |
| @@ -39,6 +39,7 @@ type localAccount struct { | ||
| 39 | 39 | path string |
| 40 | 40 | record *accountRecord |
| 41 | 41 | key []byte |
| 42 | 新增: vaultLease string | |
| 42 | 43 | epoch context.Context |
| 43 | 44 | cancel context.CancelFunc |
| 44 | 45 | nextAttempt time.Time |
| @@ -167,6 +168,7 @@ func (a *localAccount) setKey(key []byte) { | ||
| 167 | 168 | } |
| 168 | 169 | clear(a.key) |
| 169 | 170 | a.key = key |
| 171 | 新增: a.vaultLease = randomToken() | |
| 170 | 172 | a.epoch, a.cancel = context.WithCancel(context.Background()) |
| 171 | 173 | } |
| 172 | 174 | |
| @@ -0,0 +1,44 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "encoding/json" | |
| 5 | 新增: "io" | |
| 6 | 新增: "net/http" | |
| 7 | 新增: "strings" | |
| 8 | 新增: "testing" | |
| 9 | 新增:) | |
| 10 | 新增: | |
| 11 | 新增:func TestBrowserCopyContextUsesAuthenticatedGuestRoute(t *testing.T) { | |
| 12 | 新增: s := testServer(t) | |
| 13 | 新增: s.ready, s.credentials.Token = true, "private-test-token" | |
| 14 | 新增: calls := 0 | |
| 15 | 新增: s.browserControl = browserClientForTest(t, s, browserTransport(func(r *http.Request) (*http.Response, error) { | |
| 16 | 新增: calls++ | |
| 17 | 新增: if r.Method != http.MethodPost || r.URL.Path != "/copy-context" || r.Header.Get("Authorization") != "Bearer private-test-token" { | |
| 18 | 新增: t.Fatalf("unexpected copy route: %s %s", r.Method, r.URL.Path) | |
| 19 | 新增: } | |
| 20 | 新增: var input browserInput | |
| 21 | 新增: if err := json.NewDecoder(r.Body).Decode(&input); err != nil { | |
| 22 | 新增: t.Fatal(err) | |
| 23 | 新增: } | |
| 24 | 新增: if input.ID != "tab" || input.Context != strings.Repeat("a", 32) { | |
| 25 | 新增: t.Fatal("copy context or tab was lost") | |
| 26 | 新增: } | |
| 27 | 新增: return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader(`{"ok":true}`))}, nil | |
| 28 | 新增: })) | |
| 29 | 新增: body := `{"id":"tab","context":"` + strings.Repeat("a", 32) + `"}` | |
| 30 | 新增: if response := request(s, "POST", "/api/browser/copy-context", s.origin, body, true); response.Code != http.StatusOK { | |
| 31 | 新增: t.Fatalf("copy context: %d %s", response.Code, response.Body.String()) | |
| 32 | 新增: } | |
| 33 | 新增: for _, body := range []string{`{"id":"tab"}`, `{"context":"invalid"}`} { | |
| 34 | 新增: if response := request(s, "POST", "/api/browser/copy-context", s.origin, body, true); response.Code != http.StatusBadRequest { | |
| 35 | 新增: t.Fatalf("invalid copy context accepted: %d", response.Code) | |
| 36 | 新增: } | |
| 37 | 新增: } | |
| 38 | 新增: if response := request(s, "POST", "/api/browser/copy-context", s.origin, body, false); response.Code != http.StatusUnauthorized { | |
| 39 | 新增: t.Fatalf("unauthenticated copy context accepted: %d", response.Code) | |
| 40 | 新增: } | |
| 41 | 新增: if calls != 1 { | |
| 42 | 新增: t.Fatalf("rejected request reached guest: %d calls", calls) | |
| 43 | 新增: } | |
| 44 | 新增:} | |
| @@ -12,7 +12,7 @@ func (s *Server) browser(w http.ResponseWriter, r *http.Request) { | ||
| 12 | 12 | action = "tabs" |
| 13 | 13 | } |
| 14 | 14 | switch action { |
| 15 | 删除: case "tabs", "new", "activate", "close", "navigate", "back", "forward", "reload", "editor", "editor-restart", "download-retry", "upload-finish", "upload-cancel", "resize", "insert-text": | |
| 15 | 新增: case "tabs", "split", "new", "activate", "close", "navigate", "back", "forward", "reload", "editor", "editor-restart", "download-retry", "upload-finish", "upload-cancel", "resize", "insert-text", "copy-context": | |
| 16 | 16 | default: |
| 17 | 17 | http.NotFound(w, r) |
| 18 | 18 | return |
| @@ -16,6 +16,8 @@ var ( | ||
| 16 | 16 | type browserInputError struct{ error } |
| 17 | 17 | |
| 18 | 18 | type browserInput struct { |
| 19 | 新增: Left string `json:"left,omitempty"` | |
| 20 | 新增: Right string `json:"right,omitempty"` | |
| 19 | 21 | ID string `json:"id"` |
| 20 | 22 | URL string `json:"url"` |
| 21 | 23 | Width int `json:"width,omitempty"` |
| @@ -61,6 +63,9 @@ func (s *Server) browserAction(ctx context.Context, action string, input *browse | ||
| 61 | 63 | var body []byte |
| 62 | 64 | if input != nil { |
| 63 | 65 | method = http.MethodPost |
| 66 | 新增: if action == "copy-context" && (input.ID == "" || !validInputToken(input.Context)) { | |
| 67 | 新增: return nil, browserInputError{errors.New("复制操作或目标标签无效")} | |
| 68 | 新增: } | |
| 64 | 69 | if action == "insert-text" && (input.ID == "" || input.Text == "" || len(input.Text) > 8192) { |
| 65 | 70 | return nil, browserInputError{errors.New("输入文字或目标标签无效")} |
| 66 | 71 | } |
| @@ -93,12 +93,17 @@ func (s *Server) writeBrowserEvents(ctx context.Context, w http.ResponseWriter, | ||
| 93 | 93 | scanner := bufio.NewScanner(body) |
| 94 | 94 | scanner.Buffer(make([]byte, 16<<10), (1<<20)+16) |
| 95 | 95 | controller := http.NewResponseController(w) |
| 96 | 新增: eventName := "" | |
| 96 | 97 | for scanner.Scan() { |
| 97 | 98 | if err := ctx.Err(); err != nil { |
| 98 | 99 | return err |
| 99 | 100 | } |
| 100 | 101 | line := scanner.Bytes() |
| 101 | 删除: if bytes.HasPrefix(line, []byte("data: ")) { | |
| 102 | 新增: if bytes.HasPrefix(line, []byte("event: ")) { | |
| 103 | 新增: eventName = string(line[len("event: "):]) | |
| 104 | 新增: } | |
| 105 | 新增: // Clipboard notifications are one-shot payloads, not tab snapshots. | |
| 106 | 新增: if bytes.HasPrefix(line, []byte("data: ")) && eventName != "clipboard" { | |
| 102 | 107 | mapped, err := s.browserStateForHost(line[len("data: "):]) |
| 103 | 108 | if err != nil { |
| 104 | 109 | return err |
| @@ -116,6 +121,7 @@ func (s *Server) writeBrowserEvents(ctx context.Context, w http.ResponseWriter, | ||
| 116 | 121 | return err |
| 117 | 122 | } |
| 118 | 123 | if len(line) == 0 { |
| 124 | 新增: eventName = "" | |
| 119 | 125 | if err := controller.Flush(); err != nil { |
| 120 | 126 | return err |
| 121 | 127 | } |
| @@ -36,7 +36,7 @@ func TestBrowserEditorWorkspaceRESTUsesAuthorizedWindowsProjects(t *testing.T) { | ||
| 36 | 36 | snapshot := `{"active":"first","downloads":[{"id":"download","url":"https://example.test/a"}],"tabs":[` + |
| 37 | 37 | `{"id":"first","kind":"editor","workspace":"/c/Users/甲 用户/项目 一","url":"http://127.0.0.1:18080/?folder=%2Fc%2FUsers%2F甲%20用户%2F项目%20一"},` + |
| 38 | 38 | `{"id":"second","kind":"editor","workspace":"/d/跨盘 项目/two","url":"http://127.0.0.1:18080/?folder=%2Fd%2F跨盘%20项目%2Ftwo"},` + |
| 39 | 删除: `{"id":"web","kind":"web","workspace":"/c/Users/甲 用户/项目 一","url":"https://example.test/"},` + | |
| 39 | 新增: `{"id":"web","kind":"web","favicon":"data:image/png;base64,aWNvbg==","workspace":"/c/Users/甲 用户/项目 一","url":"https://example.test/"},` + | |
| 40 | 40 | `{"id":"unshared","kind":"editor","workspace":"/e/private","url":"http://127.0.0.1:18080/?folder=%2Fe%2Fprivate"}]}` |
| 41 | 41 | s.browserControl = browserClientForTest(t, s, browserTransport(func(r *http.Request) (*http.Response, error) { |
| 42 | 42 | if r.Method != "GET" || r.URL.Path != "/tabs" || r.Header.Get("Authorization") != "Bearer private-test-token" { |
| @@ -79,6 +79,20 @@ func TestBrowserEditorWorkspaceRESTUsesAuthorizedWindowsProjects(t *testing.T) { | ||
| 79 | 79 | if !reflect.DeepEqual(event, got) { |
| 80 | 80 | t.Fatal("SSE and REST expose different editor workspaces") |
| 81 | 81 | } |
| 82 | 新增: copyFrame := "event: clipboard\ndata: {\"id\":\"web\",\"text\":\"复制🙂\\n第二行\",\"context\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}\n\n" | |
| 83 | 新增: stream = httptest.NewRecorder() | |
| 84 | 新增: if err := s.writeBrowserEvents(context.Background(), stream, strings.NewReader(copyFrame+"data: "+snapshot+"\n\n")); err != nil { | |
| 85 | 新增: t.Fatal(err) | |
| 86 | 新增: } | |
| 87 | 新增: if !strings.HasPrefix(stream.Body.String(), copyFrame) { | |
| 88 | 新增: t.Fatal("clipboard event was changed or treated as a Windows tab snapshot") | |
| 89 | 新增: } | |
| 90 | 新增: if err := json.Unmarshal([]byte(strings.TrimSpace(strings.TrimPrefix(stream.Body.String()[len(copyFrame):], "data: "))), &event); err != nil { | |
| 91 | 新增: t.Fatal(err) | |
| 92 | 新增: } | |
| 93 | 新增: if !reflect.DeepEqual(event, got) { | |
| 94 | 新增: t.Fatal("clipboard event prevented the next snapshot from mapping Windows workspaces") | |
| 95 | 新增: } | |
| 82 | 96 | } |
| 83 | 97 | |
| 84 | 98 | type browserGrantReader struct { |
| @@ -0,0 +1,522 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "crypto/sha256" | |
| 6 | 新增: "encoding/hex" | |
| 7 | 新增: "encoding/json" | |
| 8 | 新增: "errors" | |
| 9 | 新增: "math" | |
| 10 | 新增: "net/mail" | |
| 11 | 新增: "os" | |
| 12 | 新增: "path/filepath" | |
| 13 | 新增: "slices" | |
| 14 | 新增: "strings" | |
| 15 | 新增: "sync" | |
| 16 | 新增: "time" | |
| 17 | 新增: "unicode" | |
| 18 | 新增: "unicode/utf8" | |
| 19 | 新增:) | |
| 20 | 新增: | |
| 21 | 新增:// A profile ID selects a guest CLI configuration directory. Only public status | |
| 22 | 新增:// fields enter this registry; the official CLI owns authentication in the VM. | |
| 23 | 新增:type claudeAccount struct { | |
| 24 | 新增: ID string `json:"id"` | |
| 25 | 新增: Label string `json:"label"` | |
| 26 | 新增: Source string `json:"source"` | |
| 27 | 新增: ProfileID string `json:"profile_id,omitempty"` | |
| 28 | 新增: Enabled bool `json:"enabled"` | |
| 29 | 新增: Status string `json:"status"` | |
| 30 | 新增: Email string `json:"email,omitempty"` | |
| 31 | 新增: Organization string `json:"organization,omitempty"` | |
| 32 | 新增: Plan string `json:"plan,omitempty"` | |
| 33 | 新增: Quota *claudeQuota `json:"quota,omitempty"` | |
| 34 | 新增: CheckedAt int64 `json:"checked_at,omitempty"` | |
| 35 | 新增: UsageStatus string `json:"usage_status,omitempty"` | |
| 36 | 新增: UsageCheckedAt int64 `json:"usage_checked_at,omitempty"` | |
| 37 | 新增: UsageChecking bool `json:"usage_checking,omitempty"` | |
| 38 | 新增:} | |
| 39 | 新增: | |
| 40 | 新增:type claudeQuota struct { | |
| 41 | 新增: FiveHour *claudeWindow `json:"five_hour,omitempty"` | |
| 42 | 新增: SevenDay *claudeWindow `json:"seven_day,omitempty"` | |
| 43 | 新增: ObservedAt int64 `json:"observed_at"` | |
| 44 | 新增:} | |
| 45 | 新增: | |
| 46 | 新增:type claudeWindow struct { | |
| 47 | 新增: UsedPercentage float64 `json:"used_percentage"` | |
| 48 | 新增: ResetsAt int64 `json:"resets_at"` | |
| 49 | 新增: ObservedAt int64 `json:"observed_at,omitempty"` | |
| 50 | 新增:} | |
| 51 | 新增: | |
| 52 | 新增:type claudeGuestSnapshot struct { | |
| 53 | 新增: UsageStatus string `json:"usage_status,omitempty"` | |
| 54 | 新增: UsageCheckedAt int64 `json:"usage_checked_at,omitempty"` | |
| 55 | 新增: LoggedIn bool `json:"logged_in"` | |
| 56 | 新增: Email string `json:"email"` | |
| 57 | 新增: Organization string `json:"organization"` | |
| 58 | 新增: Plan string `json:"plan"` | |
| 59 | 新增: Quota *claudeQuota `json:"quota"` | |
| 60 | 新增:} | |
| 61 | 新增: | |
| 62 | 新增:type claudeAccountList struct { | |
| 63 | 新增: Accounts []claudeAccount `json:"accounts"` | |
| 64 | 新增: PendingLogin string `json:"pending_login,omitempty"` | |
| 65 | 新增:} | |
| 66 | 新增: | |
| 67 | 新增:type claudeAccountManager struct { | |
| 68 | 新增: usageProbe func(context.Context, string, string) (claudeGuestSnapshot, error) | |
| 69 | 新增: usageActive map[string]*claudeUsageCall | |
| 70 | 新增: panelRunning bool | |
| 71 | 新增: panelUntil time.Time | |
| 72 | 新增: detectedUsage map[string]*claudeAccount | |
| 73 | 新增: defaultGate chan struct{} | |
| 74 | 新增: loginNotice string | |
| 75 | 新增: defaultChecked time.Time | |
| 76 | 新增: defaultReading claudeGuestSnapshot | |
| 77 | 新增: defaultError error | |
| 78 | 新增: probe func(context.Context, string) (claudeGuestSnapshot, error) | |
| 79 | 新增: mu sync.Mutex | |
| 80 | 新增: lastPick string | |
| 81 | 新增: recent map[string]claudeProjectPick | |
| 82 | 新增: refreshing map[string]*claudeRefresh | |
| 83 | 新增: attempted map[string]time.Time | |
| 84 | 新增:} | |
| 85 | 新增: | |
| 86 | 新增:type claudeRefresh struct { | |
| 87 | 新增: done chan struct{} | |
| 88 | 新增: err error | |
| 89 | 新增:} | |
| 90 | 新增: | |
| 91 | 新增:const claudeQuotaFresh = 15 * time.Minute | |
| 92 | 新增: | |
| 93 | 新增:func validClaudeID(id string) bool { | |
| 94 | 新增: _, err := hex.DecodeString(id) | |
| 95 | 新增: return len(id) == 24 && err == nil && strings.ToLower(id) == id | |
| 96 | 新增:} | |
| 97 | 新增: | |
| 98 | 新增:func (s *Server) loadClaudeAccounts() (claudeAccountList, error) { | |
| 99 | 新增: list := claudeAccountList{Accounts: []claudeAccount{}} | |
| 100 | 新增: data, err := os.ReadFile(filepath.Join(s.profile, "claude-accounts.json")) | |
| 101 | 新增: if os.IsNotExist(err) { | |
| 102 | 新增: return list, nil | |
| 103 | 新增: } | |
| 104 | 新增: if err != nil || json.Unmarshal(data, &list) != nil || list.Accounts == nil { | |
| 105 | 新增: return list, errors.New("Claude 账号文件无法读取,请检查配置目录或恢复备份") | |
| 106 | 新增: } | |
| 107 | 新增: ids := make(map[string]bool) | |
| 108 | 新增: profiles := make(map[string]bool) | |
| 109 | 新增: for i := range list.Accounts { | |
| 110 | 新增: a := &list.Accounts[i] | |
| 111 | 新增: if a.Source == "" { | |
| 112 | 新增: a.Source = "managed" | |
| 113 | 新增: } | |
| 114 | 新增: if !validClaudeID(a.ID) || ids[a.ID] || a.Source != "managed" && a.Source != "default" || a.Source == "default" && (a.Email == "" || a.ProfileID != "") || a.ProfileID != "" && !validClaudeID(a.ProfileID) { | |
| 115 | 新增: return list, errors.New("Claude 账号文件含无效或重复的记录,请从备份恢复") | |
| 116 | 新增: } | |
| 117 | 新增: ids[a.ID] = true | |
| 118 | 新增: if a.Source == "managed" { | |
| 119 | 新增: if profiles[a.guestID()] { | |
| 120 | 新增: return list, errors.New("多个账号引用了同一个独立登录目录,请从备份恢复") | |
| 121 | 新增: } | |
| 122 | 新增: profiles[a.guestID()] = true | |
| 123 | 新增: } | |
| 124 | 新增: } | |
| 125 | 新增: if list.PendingLogin != "" && (!validClaudeID(list.PendingLogin) || ids[list.PendingLogin] || profiles[list.PendingLogin]) { | |
| 126 | 新增: return list, errors.New("Claude 登录记录损坏,请恢复备份") | |
| 127 | 新增: } | |
| 128 | 新增: return list, nil | |
| 129 | 新增:} | |
| 130 | 新增: | |
| 131 | 新增:func (s *Server) saveClaudeAccounts(list claudeAccountList) error { | |
| 132 | 新增: if err := writePrivate(filepath.Join(s.profile, "claude-accounts.json"), list); err != nil { | |
| 133 | 新增: return errors.New("Claude 账号设置未保存,请检查配置目录权限和磁盘空间") | |
| 134 | 新增: } | |
| 135 | 新增: return nil | |
| 136 | 新增:} | |
| 137 | 新增: | |
| 138 | 新增:func (a claudeAccount) guestID() string { | |
| 139 | 新增: if a.Source == "default" { | |
| 140 | 新增: return "default" | |
| 141 | 新增: } | |
| 142 | 新增: if a.ProfileID != "" { | |
| 143 | 新增: return a.ProfileID | |
| 144 | 新增: } | |
| 145 | 新增: return a.ID | |
| 146 | 新增:} | |
| 147 | 新增: | |
| 148 | 新增:func (list claudeAccountList) find(id string) *claudeAccount { | |
| 149 | 新增: for i := range list.Accounts { | |
| 150 | 新增: if list.Accounts[i].ID == id { | |
| 151 | 新增: return &list.Accounts[i] | |
| 152 | 新增: } | |
| 153 | 新增: } | |
| 154 | 新增: return nil | |
| 155 | 新增:} | |
| 156 | 新增: | |
| 157 | 新增:func validClaudeLabel(label string) bool { | |
| 158 | 新增: return label != "" && utf8.RuneCountInString(label) <= 64 && strings.IndexFunc(label, unicode.IsControl) < 0 | |
| 159 | 新增:} | |
| 160 | 新增: | |
| 161 | 新增:func (list *claudeAccountList) change(input claudeAccountInput) error { | |
| 162 | 新增: label := strings.TrimSpace(input.Label) | |
| 163 | 新增: if input.Action != "update" { | |
| 164 | 新增: return errors.New("未知 Claude 账号操作") | |
| 165 | 新增: } | |
| 166 | 新增: a := list.find(input.ID) | |
| 167 | 新增: if a == nil { | |
| 168 | 新增: return errors.New("未找到 Claude 账号,请刷新面板") | |
| 169 | 新增: } | |
| 170 | 新增: if input.Label != "" { | |
| 171 | 新增: if !validClaudeLabel(label) && (label == "" || label != a.Email) { | |
| 172 | 新增: return errors.New("备注最多 64 个字符,不能含控制字符") | |
| 173 | 新增: } | |
| 174 | 新增: a.Label = label | |
| 175 | 新增: } | |
| 176 | 新增: if input.Enabled != nil { | |
| 177 | 新增: a.Enabled = *input.Enabled | |
| 178 | 新增: } | |
| 179 | 新增: return nil | |
| 180 | 新增:} | |
| 181 | 新增: | |
| 182 | 新增:func (r claudeGuestSnapshot) email() string { | |
| 183 | 新增: email := strings.ToLower(strings.TrimSpace(r.Email)) | |
| 184 | 新增: mailbox, err := mail.ParseAddress(email) | |
| 185 | 新增: if !r.LoggedIn || err != nil || mailbox.Address != email { | |
| 186 | 新增: return "" | |
| 187 | 新增: } | |
| 188 | 新增: return email | |
| 189 | 新增:} | |
| 190 | 新增: | |
| 191 | 新增:func (r claudeGuestSnapshot) subject() string { | |
| 192 | 新增: if email := r.email(); email != "" { | |
| 193 | 新增: return claudeIdentityHash(email, r.Organization) | |
| 194 | 新增: } | |
| 195 | 新增: return "" | |
| 196 | 新增:} | |
| 197 | 新增: | |
| 198 | 新增:func validClaudeWindow(w *claudeWindow) bool { | |
| 199 | 新增: return w != nil && !math.IsNaN(w.UsedPercentage) && w.UsedPercentage >= 0 && w.UsedPercentage <= 100 && w.ResetsAt >= 0 | |
| 200 | 新增:} | |
| 201 | 新增: | |
| 202 | 新增:// A missing reading cannot invalidate an existing reading, or make an old | |
| 203 | 新增:// reading fresh. Never attach a previous identity's quota to a new identity. | |
| 204 | 新增:func (list claudeAccountList) observe(id string, observed claudeGuestSnapshot, now time.Time) error { | |
| 205 | 新增: a := list.find(id) | |
| 206 | 新增: if a == nil { | |
| 207 | 新增: return errors.New("未找到 Claude 账号") | |
| 208 | 新增: } | |
| 209 | 新增: a.CheckedAt = now.Unix() | |
| 210 | 新增: email := observed.email() | |
| 211 | 新增: if email == "" { | |
| 212 | 新增: a.Status = "signed_out" | |
| 213 | 新增: return nil | |
| 214 | 新增: } | |
| 215 | 新增: organization := strings.TrimSpace(observed.Organization) | |
| 216 | 新增: if a.Email != "" && (!strings.EqualFold(a.Email, email) || a.Organization != organization) { | |
| 217 | 新增: a.Status = "changed" | |
| 218 | 新增: return nil | |
| 219 | 新增: } | |
| 220 | 新增: for _, other := range list.Accounts { | |
| 221 | 新增: if other.ID != id && strings.EqualFold(other.Email, email) && other.Organization == organization { | |
| 222 | 新增: a.Status = "duplicate" | |
| 223 | 新增: return nil | |
| 224 | 新增: } | |
| 225 | 新增: } | |
| 226 | 新增: a.Status, a.Email, a.Organization, a.Plan = "ready", email, organization, observed.Plan | |
| 227 | 新增: a.mergeQuota(observed.Quota, now) | |
| 228 | 新增: return nil | |
| 229 | 新增:} | |
| 230 | 新增: | |
| 231 | 新增:func (a *claudeAccount) mergeQuota(q *claudeQuota, now time.Time) bool { | |
| 232 | 新增: if q == nil || q.ObservedAt <= 0 || q.ObservedAt > now.Unix() { | |
| 233 | 新增: return false | |
| 234 | 新增: } | |
| 235 | 新增: next := claudeQuota{} | |
| 236 | 新增: if a.Quota != nil { | |
| 237 | 新增: next = *a.Quota | |
| 238 | 新增: } | |
| 239 | 新增: merge := func(old, reading *claudeWindow) *claudeWindow { | |
| 240 | 新增: if !validClaudeWindow(reading) { | |
| 241 | 新增: return old | |
| 242 | 新增: } | |
| 243 | 新增: window := *reading | |
| 244 | 新增: if window.ObservedAt == 0 { | |
| 245 | 新增: window.ObservedAt = q.ObservedAt | |
| 246 | 新增: } | |
| 247 | 新增: if window.ObservedAt < 0 || window.ObservedAt > q.ObservedAt || old != nil && old.ObservedAt > window.ObservedAt { | |
| 248 | 新增: return old | |
| 249 | 新增: } | |
| 250 | 新增: if old != nil && window == *old { | |
| 251 | 新增: return old | |
| 252 | 新增: } | |
| 253 | 新增: return &window | |
| 254 | 新增: } | |
| 255 | 新增: next.FiveHour = merge(next.FiveHour, q.FiveHour) | |
| 256 | 新增: next.SevenDay = merge(next.SevenDay, q.SevenDay) | |
| 257 | 新增: if next.FiveHour == nil && next.SevenDay == nil || a.Quota != nil && next == *a.Quota { | |
| 258 | 新增: return false | |
| 259 | 新增: } | |
| 260 | 新增: next.ObservedAt = max(next.ObservedAt, q.ObservedAt) | |
| 261 | 新增: a.Quota = &next | |
| 262 | 新增: return true | |
| 263 | 新增:} | |
| 264 | 新增: | |
| 265 | 新增:func claudeIdentityHash(email, organization string) string { | |
| 266 | 新增: digest := sha256.Sum256([]byte(strings.ToLower(strings.TrimSpace(email)) + "\n" + strings.TrimSpace(organization))) | |
| 267 | 新增: return hex.EncodeToString(digest[:]) | |
| 268 | 新增:} | |
| 269 | 新增: | |
| 270 | 新增:// A fully used window still blocks new sessions until its actual reset, even | |
| 271 | 新增:// if the snapshot is stale. An expired or unreported window stays unknown. | |
| 272 | 新增:func (a claudeAccount) headroom(now time.Time) (float64, bool) { | |
| 273 | 新增: if a.Quota == nil { | |
| 274 | 新增: return -1, true | |
| 275 | 新增: } | |
| 276 | 新增: least := -1.0 | |
| 277 | 新增: for _, w := range []*claudeWindow{a.Quota.FiveHour, a.Quota.SevenDay} { | |
| 278 | 新增: if !validClaudeWindow(w) || w.ResetsAt > 0 && w.ResetsAt <= now.Unix() { | |
| 279 | 新增: continue | |
| 280 | 新增: } | |
| 281 | 新增: fresh := now.Sub(time.Unix(w.ObservedAt, 0)) <= claudeQuotaFresh | |
| 282 | 新增: if w.UsedPercentage >= 100 && (w.ResetsAt > now.Unix() || fresh) { | |
| 283 | 新增: return 0, false | |
| 284 | 新增: } | |
| 285 | 新增: if fresh { | |
| 286 | 新增: remaining := 100 - w.UsedPercentage | |
| 287 | 新增: if least < 0 || remaining < least { | |
| 288 | 新增: least = remaining | |
| 289 | 新增: } | |
| 290 | 新增: } | |
| 291 | 新增: } | |
| 292 | 新增: return least, true | |
| 293 | 新增:} | |
| 294 | 新增: | |
| 295 | 新增:// A selection carries the identity verified for this launch. The caller | |
| 296 | 新增:// must not replace Subject or GuestID by looking the record up again. | |
| 297 | 新增:type claudeSelection struct{ ID, GuestID, Subject string } | |
| 298 | 新增: | |
| 299 | 新增:func (s *Server) selectClaudeAccount(requestedID string, login bool, workspace string) (claudeSelection, error) { | |
| 300 | 新增: var empty claudeSelection | |
| 301 | 新增: if !login && requestedID != "" && requestedID != "auto" { | |
| 302 | 新增: return empty, errors.New("Claude 终端会自动分配账号") | |
| 303 | 新增: } | |
| 304 | 新增: m := &s.claudeAccounts | |
| 305 | 新增: m.mu.Lock() | |
| 306 | 新增: list, err := s.loadClaudeAccounts() | |
| 307 | 新增: if err == nil && list.PendingLogin != "" && requestedID == "" && !s.claudeLoginActive(list.PendingLogin) { | |
| 308 | 新增: m.mu.Unlock() | |
| 309 | 新增: // Restore a successful login from before a controller restart or lock | |
| 310 | 新增: // before a new login could write into the same guest directory. | |
| 311 | 新增: if epoch, ok := s.account.access(); ok { | |
| 312 | 新增: if probeErr := s.recoverClaudePending(epoch, list.PendingLogin, login); login && probeErr != nil { | |
| 313 | 新增: return empty, probeErr | |
| 314 | 新增: } | |
| 315 | 新增: } | |
| 316 | 新增: m.mu.Lock() | |
| 317 | 新增: list, err = s.loadClaudeAccounts() | |
| 318 | 新增: } | |
| 319 | 新增: if err == nil && login { | |
| 320 | 新增: if requestedID == "" { | |
| 321 | 新增: if list.PendingLogin == "" { | |
| 322 | 新增: list.PendingLogin = randomToken()[:24] | |
| 323 | 新增: m.loginNotice = "" | |
| 324 | 新增: err = s.saveClaudeAccounts(list) | |
| 325 | 新增: } | |
| 326 | 新增: requestedID = list.PendingLogin | |
| 327 | 新增: } else if a := list.find(requestedID); a == nil || a.Source != "managed" { | |
| 328 | 新增: err = errors.New("请在普通终端管理环境的默认登录") | |
| 329 | 新增: } | |
| 330 | 新增: } | |
| 331 | 新增: m.mu.Unlock() | |
| 332 | 新增: if err != nil { | |
| 333 | 新增: return empty, err | |
| 334 | 新增: } | |
| 335 | 新增: if login { | |
| 336 | 新增: guestID := requestedID | |
| 337 | 新增: if a := list.find(requestedID); a != nil { | |
| 338 | 新增: guestID = a.guestID() | |
| 339 | 新增: } | |
| 340 | 新增: return claudeSelection{ID: requestedID, GuestID: guestID}, nil | |
| 341 | 新增: } | |
| 342 | 新增: if len(list.Accounts) == 0 { | |
| 343 | 新增: return empty, nil | |
| 344 | 新增: } | |
| 345 | 新增: return s.allocateClaudeAccount(list, workspace, s.readClaudeGuestQuotas) | |
| 346 | 新增:} | |
| 347 | 新增: | |
| 348 | 新增:type claudeGuestQuota struct { | |
| 349 | 新增: claudeQuota | |
| 350 | 新增: Identity string `json:"identity"` | |
| 351 | 新增:} | |
| 352 | 新增: | |
| 353 | 新增:func (s *Server) readClaudeGuestQuotas(ctx context.Context, ids []string) (map[string]claudeGuestQuota, error) { | |
| 354 | 新增: for _, id := range ids { | |
| 355 | 新增: if !validClaudeID(id) { | |
| 356 | 新增: return nil, errors.New("Claude 账号 ID 无效") | |
| 357 | 新增: } | |
| 358 | 新增: } | |
| 359 | 新增: // s.guest bounds its output to 64 KiB. Even a large pool uses one | |
| 360 | 新增: // server-controlled deadline; keep completed chunks when a later one fails. | |
| 361 | 新增: readings := make(map[string]claudeGuestQuota) | |
| 362 | 新增: for chunk := range slices.Chunk(ids, 96) { | |
| 363 | 新增: data, err := s.guest(ctx, "exec /usr/local/bin/cage-claude-account quotas "+strings.Join(chunk, " ")) | |
| 364 | 新增: if err != nil { | |
| 365 | 新增: return readings, err | |
| 366 | 新增: } | |
| 367 | 新增: if err := json.Unmarshal(data, &readings); err != nil { | |
| 368 | 新增: return readings, err | |
| 369 | 新增: } | |
| 370 | 新增: } | |
| 371 | 新增: return readings, nil | |
| 372 | 新增:} | |
| 373 | 新增: | |
| 374 | 新增:// The status line may have written a newer reading while the account panel | |
| 375 | 新增:// was closed. Fetch only its small local files in one SSH command. The guest | |
| 376 | 新增:// does not start the CLI, read tokens, or contact Anthropic for this read. | |
| 377 | 新增:func (s *Server) allocateClaudeAccount(previous claudeAccountList, workspace string, read func(context.Context, []string) (map[string]claudeGuestQuota, error)) (claudeSelection, error) { | |
| 378 | 新增: var empty claudeSelection | |
| 379 | 新增: epoch, unlocked := s.account.access() | |
| 380 | 新增: if !unlocked { | |
| 381 | 新增: return empty, errors.New("Cage 已锁定,请先解锁") | |
| 382 | 新增: } | |
| 383 | 新增: var ids []string | |
| 384 | 新增: checkDefault := false | |
| 385 | 新增: for _, a := range previous.Accounts { | |
| 386 | 新增: if a.Source == "default" { | |
| 387 | 新增: checkDefault = checkDefault || a.Enabled | |
| 388 | 新增: } else if a.Enabled && a.Status == "ready" { | |
| 389 | 新增: ids = append(ids, a.guestID()) | |
| 390 | 新增: } | |
| 391 | 新增: } | |
| 392 | 新增: var readings map[string]claudeGuestQuota | |
| 393 | 新增: if len(ids) > 0 { | |
| 394 | 新增: ctx, cancel := context.WithTimeout(epoch, 4*time.Second) | |
| 395 | 新增: readings, _ = read(ctx, ids) // Retain the last snapshot when SSH is unavailable. | |
| 396 | 新增: cancel() | |
| 397 | 新增: } | |
| 398 | 新增: defaultSubject := "" | |
| 399 | 新增: if checkDefault { | |
| 400 | 新增: if reading, _, err := s.inspectClaudeDefault(epoch, true); err == nil { | |
| 401 | 新增: defaultSubject = reading.subject() | |
| 402 | 新增: } | |
| 403 | 新增: } | |
| 404 | 新增: m := &s.claudeAccounts | |
| 405 | 新增: m.mu.Lock() | |
| 406 | 新增: defer m.mu.Unlock() | |
| 407 | 新增: if epoch.Err() != nil { | |
| 408 | 新增: return empty, errors.New("Cage 已锁定,请先解锁") | |
| 409 | 新增: } | |
| 410 | 新增: list, err := s.loadClaudeAccounts() | |
| 411 | 新增: if err != nil { | |
| 412 | 新增: return empty, err | |
| 413 | 新增: } | |
| 414 | 新增: now := time.Now() | |
| 415 | 新增: updated := false | |
| 416 | 新增: for i := range list.Accounts { | |
| 417 | 新增: a := &list.Accounts[i] | |
| 418 | 新增: q, ok := readings[a.guestID()] | |
| 419 | 新增: if a.Enabled && a.Status == "ready" && ok && q.Identity == claudeIdentityHash(a.Email, a.Organization) { | |
| 420 | 新增: if a.mergeQuota(&q.claudeQuota, now) { | |
| 421 | 新增: updated = true | |
| 422 | 新增: } | |
| 423 | 新增: } | |
| 424 | 新增: } | |
| 425 | 新增: if updated { | |
| 426 | 新增: if err = s.saveClaudeAccounts(list); err != nil { | |
| 427 | 新增: return empty, err | |
| 428 | 新增: } | |
| 429 | 新增: } | |
| 430 | 新增: active := make(map[string]int) | |
| 431 | 新增: logins := make(map[string]bool) | |
| 432 | 新增: for _, session := range s.terminals.snapshot() { | |
| 433 | 新增: if session["closed"] == true { | |
| 434 | 新增: continue | |
| 435 | 新增: } | |
| 436 | 新增: id, _ := session["claude_account_id"].(string) | |
| 437 | 新增: if session["kind"] == "claude-login" { | |
| 438 | 新增: logins[id] = true | |
| 439 | 新增: } else { | |
| 440 | 新增: active[id]++ | |
| 441 | 新增: } | |
| 442 | 新增: } | |
| 443 | 新增: recent := m.recent[workspace] | |
| 444 | 新增: preferred := "" | |
| 445 | 新增: if now.Sub(recent.at) < claudeProjectAffinity { | |
| 446 | 新增: preferred = recent.id | |
| 447 | 新增: } | |
| 448 | 新增: // Only a positively verified matching default profile can be admitted. | |
| 449 | 新增: for i := range list.Accounts { | |
| 450 | 新增: a := &list.Accounts[i] | |
| 451 | 新增: if a.Source == "default" && (defaultSubject == "" || defaultSubject != claudeIdentityHash(a.Email, a.Organization)) { | |
| 452 | 新增: a.Enabled = false // local selection view, not the persisted preference | |
| 453 | 新增: } | |
| 454 | 新增: } | |
| 455 | 新增: selected := pickClaudeAccount(list, active, logins, m.lastPick, preferred, now) | |
| 456 | 新增: if selected == "" { | |
| 457 | 新增: return empty, errors.New("暂无可分配的 Claude 账号。请在账号面板检查登录、参与状态和额度重置时间") | |
| 458 | 新增: } | |
| 459 | 新增: a := list.find(selected) | |
| 460 | 新增: return claudeSelection{ID: selected, GuestID: a.guestID(), Subject: claudeIdentityHash(a.Email, a.Organization)}, nil | |
| 461 | 新增:} | |
| 462 | 新增: | |
| 463 | 新增:// Start at the account following the last allocation. Among eligible accounts, | |
| 464 | 新增:// prefer fewer live sessions, then the largest known remaining minimum window. | |
| 465 | 新增:func pickClaudeAccount(list claudeAccountList, active map[string]int, logins map[string]bool, last, preferred string, now time.Time) string { | |
| 466 | 新增: start := slices.IndexFunc(list.Accounts, func(a claudeAccount) bool { return a.ID == last }) + 1 | |
| 467 | 新增: best := "" | |
| 468 | 新增: var bestActive int | |
| 469 | 新增: var bestRoom float64 | |
| 470 | 新增: for offset := range list.Accounts { | |
| 471 | 新增: a := list.Accounts[(start+offset)%len(list.Accounts)] | |
| 472 | 新增: if !a.Enabled || a.Status != "ready" || logins[a.ID] { | |
| 473 | 新增: continue | |
| 474 | 新增: } | |
| 475 | 新增: room, eligible := a.headroom(now) | |
| 476 | 新增: if eligible && (best == "" || active[a.ID] < bestActive || active[a.ID] == bestActive && room > bestRoom) { | |
| 477 | 新增: best, bestActive, bestRoom = a.ID, active[a.ID], room | |
| 478 | 新增: } | |
| 479 | 新增: } | |
| 480 | 新增: // Keep a recent project's profile only when it has the same load and | |
| 481 | 新增: // comparable headroom (both unknown, or within five percentage points). | |
| 482 | 新增: if a := list.find(preferred); a != nil && a.Enabled && a.Status == "ready" && !logins[a.ID] && active[a.ID] == bestActive { | |
| 483 | 新增: room, ok := a.headroom(now) | |
| 484 | 新增: if ok && (room == bestRoom || room >= 0 && bestRoom-room <= min(5, bestRoom*0.1)) { | |
| 485 | 新增: return a.ID | |
| 486 | 新增: } | |
| 487 | 新增: } | |
| 488 | 新增: return best | |
| 489 | 新增:} | |
| 490 | 新增: | |
| 491 | 新增:type claudeProjectPick struct { | |
| 492 | 新增: id string | |
| 493 | 新增: at time.Time | |
| 494 | 新增:} | |
| 495 | 新增: | |
| 496 | 新增:const claudeProjectAffinity = 5 * time.Minute | |
| 497 | 新增: | |
| 498 | 新增:func (s *Server) noteClaudeSelection(id, workspace string) { | |
| 499 | 新增: m := &s.claudeAccounts | |
| 500 | 新增: m.mu.Lock() | |
| 501 | 新增: defer m.mu.Unlock() | |
| 502 | 新增: m.lastPick = id | |
| 503 | 新增: if workspace == "" { | |
| 504 | 新增: return | |
| 505 | 新增: } | |
| 506 | 新增: if m.recent == nil { | |
| 507 | 新增: m.recent = make(map[string]claudeProjectPick) | |
| 508 | 新增: } | |
| 509 | 新增: now := time.Now() | |
| 510 | 新增: var oldest string | |
| 511 | 新增: for path, pick := range m.recent { | |
| 512 | 新增: if now.Sub(pick.at) >= claudeProjectAffinity { | |
| 513 | 新增: delete(m.recent, path) | |
| 514 | 新增: } else if oldest == "" || pick.at.Before(m.recent[oldest].at) { | |
| 515 | 新增: oldest = path | |
| 516 | 新增: } | |
| 517 | 新增: } | |
| 518 | 新增: m.recent[workspace] = claudeProjectPick{id: id, at: now} | |
| 519 | 新增: if len(m.recent) > 64 { | |
| 520 | 新增: delete(m.recent, oldest) | |
| 521 | 新增: } | |
| 522 | 新增:} | |
| @@ -0,0 +1,239 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "errors" | |
| 6 | 新增: "strings" | |
| 7 | 新增: "time" | |
| 8 | 新增:) | |
| 9 | 新增: | |
| 10 | 新增:// The guest default directory is one mutable login slot. Every identity joined | |
| 11 | 新增:// from it has its own registry ID, participation setting, and quota history. | |
| 12 | 新增:type claudeDetected struct { | |
| 13 | 新增: Identity string `json:"identity"` | |
| 14 | 新增: Email string `json:"email"` | |
| 15 | 新增: Organization string `json:"organization,omitempty"` | |
| 16 | 新增: Plan string `json:"plan,omitempty"` | |
| 17 | 新增: Quota *claudeQuota `json:"quota,omitempty"` | |
| 18 | 新增: CheckedAt int64 `json:"checked_at"` | |
| 19 | 新增: UsageStatus string `json:"usage_status,omitempty"` | |
| 20 | 新增: UsageCheckedAt int64 `json:"usage_checked_at,omitempty"` | |
| 21 | 新增: UsageChecking bool `json:"usage_checking,omitempty"` | |
| 22 | 新增:} | |
| 23 | 新增: | |
| 24 | 新增:type claudePanel struct { | |
| 25 | 新增: UsagePanelRunning bool `json:"usage_panel_running"` | |
| 26 | 新增: UsageUnavailableReason string `json:"usage_unavailable_reason,omitempty"` | |
| 27 | 新增: Accounts []claudeAccount `json:"accounts"` | |
| 28 | 新增: Detected *claudeDetected `json:"detected,omitempty"` | |
| 29 | 新增: DetectionStatus string `json:"detection_status"` | |
| 30 | 新增: DetectionError string `json:"detection_error,omitempty"` | |
| 31 | 新增: LoginNotice string `json:"login_notice,omitempty"` | |
| 32 | 新增:} | |
| 33 | 新增: | |
| 34 | 新增:func (s *Server) probeClaude(ctx context.Context, guestID string) (claudeGuestSnapshot, error) { | |
| 35 | 新增: if probe := s.claudeAccounts.probe; probe != nil { | |
| 36 | 新增: return probe(ctx, guestID) | |
| 37 | 新增: } | |
| 38 | 新增: return s.readClaudeGuestSnapshot(ctx, guestID) | |
| 39 | 新增:} | |
| 40 | 新增: | |
| 41 | 新增:func (list claudeAccountList) bySubject(subject string) *claudeAccount { | |
| 42 | 新增: if subject == "" { | |
| 43 | 新增: return nil | |
| 44 | 新增: } | |
| 45 | 新增: for i := range list.Accounts { | |
| 46 | 新增: a := &list.Accounts[i] | |
| 47 | 新增: if a.Email != "" && claudeIdentityHash(a.Email, a.Organization) == subject { | |
| 48 | 新增: return a | |
| 49 | 新增: } | |
| 50 | 新增: } | |
| 51 | 新增: return nil | |
| 52 | 新增:} | |
| 53 | 新增: | |
| 54 | 新增:// Panel reads coalesce for 20 seconds. A join or a launch verifies the | |
| 55 | 新增:// identity again. The timeout covers both waiting for a probe and running it. | |
| 56 | 新增:func (s *Server) inspectClaudeDefault(parent context.Context, force bool) (claudeGuestSnapshot, time.Time, error) { | |
| 57 | 新增: var empty claudeGuestSnapshot | |
| 58 | 新增: epoch, unlocked := s.account.access() | |
| 59 | 新增: if !unlocked { | |
| 60 | 新增: return empty, time.Time{}, errors.New("Cage 已锁定,请先解锁") | |
| 61 | 新增: } | |
| 62 | 新增: ctx, cancel := context.WithTimeout(parent, 8*time.Second) | |
| 63 | 新增: stop := context.AfterFunc(epoch, cancel) | |
| 64 | 新增: defer func() { stop(); cancel() }() | |
| 65 | 新增: m := &s.claudeAccounts | |
| 66 | 新增: m.mu.Lock() | |
| 67 | 新增: if m.defaultGate == nil { | |
| 68 | 新增: m.defaultGate = make(chan struct{}, 1) | |
| 69 | 新增: } | |
| 70 | 新增: gate := m.defaultGate | |
| 71 | 新增: m.mu.Unlock() | |
| 72 | 新增: select { | |
| 73 | 新增: case gate <- struct{}{}: | |
| 74 | 新增: defer func() { <-gate }() | |
| 75 | 新增: case <-ctx.Done(): | |
| 76 | 新增: return empty, time.Time{}, errors.New("默认登录检查未完成,请重试") | |
| 77 | 新增: } | |
| 78 | 新增: m.mu.Lock() | |
| 79 | 新增: if !force && time.Since(m.defaultChecked) < 20*time.Second { | |
| 80 | 新增: reading, checked, err := m.defaultReading, m.defaultChecked, m.defaultError | |
| 81 | 新增: m.mu.Unlock() | |
| 82 | 新增: return reading, checked, err | |
| 83 | 新增: } | |
| 84 | 新增: m.mu.Unlock() | |
| 85 | 新增: reading, err := s.probeClaude(ctx, "default") | |
| 86 | 新增: now := time.Now() | |
| 87 | 新增: m.mu.Lock() | |
| 88 | 新增: defer m.mu.Unlock() | |
| 89 | 新增: if ctx.Err() != nil || epoch.Err() != nil || err != nil { | |
| 90 | 新增: reading = empty | |
| 91 | 新增: err = errors.New("暂时无法读取环境的默认登录,请确认 Claude Code 和环境组件可用后重试") | |
| 92 | 新增: } else { | |
| 93 | 新增: list, loadErr := s.loadClaudeAccounts() | |
| 94 | 新增: if loadErr != nil { | |
| 95 | 新增: err = loadErr | |
| 96 | 新增: } else { | |
| 97 | 新增: if subject := reading.subject(); subject != "" && list.bySubject(subject) == nil { | |
| 98 | 新增: m.rememberDetected(subject, reading, now) | |
| 99 | 新增: } | |
| 100 | 新增: changed := false | |
| 101 | 新增: for i := range list.Accounts { | |
| 102 | 新增: a := &list.Accounts[i] | |
| 103 | 新增: if a.Source != "default" { | |
| 104 | 新增: continue | |
| 105 | 新增: } | |
| 106 | 新增: if err = list.observe(a.ID, reading, now); err != nil { | |
| 107 | 新增: break | |
| 108 | 新增: } | |
| 109 | 新增: changed = true | |
| 110 | 新增: } | |
| 111 | 新增: if changed && err == nil { | |
| 112 | 新增: err = s.saveClaudeAccounts(list) | |
| 113 | 新增: } | |
| 114 | 新增: } | |
| 115 | 新增: } | |
| 116 | 新增: m.defaultReading, m.defaultChecked, m.defaultError = reading, now, err | |
| 117 | 新增: if epoch.Err() != nil || parent.Err() != nil { | |
| 118 | 新增: m.defaultChecked = time.Time{} | |
| 119 | 新增: } | |
| 120 | 新增: return reading, now, err | |
| 121 | 新增:} | |
| 122 | 新增: | |
| 123 | 新增:// Keep a small, process-local history for unjoined identities. Switching the | |
| 124 | 新增:// default login cannot expose another identity's readings or erase a recent | |
| 125 | 新增:// observation when the same user returns to the default directory. | |
| 126 | 新增:func (m *claudeAccountManager) rememberDetected(subject string, reading claudeGuestSnapshot, now time.Time) { | |
| 127 | 新增: if m.detectedUsage == nil { | |
| 128 | 新增: m.detectedUsage = make(map[string]*claudeAccount) | |
| 129 | 新增: } | |
| 130 | 新增: a := m.detectedUsage[subject] | |
| 131 | 新增: if a == nil { | |
| 132 | 新增: if len(m.detectedUsage) >= 16 { | |
| 133 | 新增: oldest := "" | |
| 134 | 新增: for key, entry := range m.detectedUsage { | |
| 135 | 新增: if oldest == "" || entry.CheckedAt < m.detectedUsage[oldest].CheckedAt { | |
| 136 | 新增: oldest = key | |
| 137 | 新增: } | |
| 138 | 新增: } | |
| 139 | 新增: delete(m.detectedUsage, oldest) | |
| 140 | 新增: } | |
| 141 | 新增: a = &claudeAccount{Email: reading.email(), Organization: reading.Organization} | |
| 142 | 新增: m.detectedUsage[subject] = a | |
| 143 | 新增: } | |
| 144 | 新增: a.CheckedAt = now.Unix() | |
| 145 | 新增: a.mergeQuota(reading.Quota, now) | |
| 146 | 新增:} | |
| 147 | 新增: | |
| 148 | 新增:func (s *Server) joinClaudeDefault(ctx context.Context, expected string) error { | |
| 149 | 新增: reading, now, err := s.inspectClaudeDefault(ctx, true) | |
| 150 | 新增: if err != nil { | |
| 151 | 新增: return err | |
| 152 | 新增: } | |
| 153 | 新增: if expected == "" || expected != reading.subject() { | |
| 154 | 新增: return errors.New("环境中的登录身份已经变化,请刷新后确认要加入的账号") | |
| 155 | 新增: } | |
| 156 | 新增: m := &s.claudeAccounts | |
| 157 | 新增: m.mu.Lock() | |
| 158 | 新增: defer m.mu.Unlock() | |
| 159 | 新增: // Another completed discovery may have already observed a new identity. | |
| 160 | 新增: if m.defaultReading.subject() != expected || m.defaultError != nil || ctx.Err() != nil { | |
| 161 | 新增: return errors.New("默认登录状态已变化,请刷新后重试") | |
| 162 | 新增: } | |
| 163 | 新增: list, err := s.loadClaudeAccounts() | |
| 164 | 新增: if err != nil { | |
| 165 | 新增: return err | |
| 166 | 新增: } | |
| 167 | 新增: if list.bySubject(expected) != nil { | |
| 168 | 新增: return nil | |
| 169 | 新增: } | |
| 170 | 新增: id := randomToken()[:24] | |
| 171 | 新增: list.Accounts = append(list.Accounts, claudeAccount{ID: id, Source: "default", Label: reading.email(), Enabled: true}) | |
| 172 | 新增: if err := list.observe(id, reading, now); err != nil { | |
| 173 | 新增: return err | |
| 174 | 新增: } | |
| 175 | 新增: if cached := m.detectedUsage[expected]; cached != nil { | |
| 176 | 新增: a := list.find(id) | |
| 177 | 新增: a.mergeQuota(cached.Quota, now) | |
| 178 | 新增: a.UsageCheckedAt, a.UsageStatus = cached.UsageCheckedAt, cached.UsageStatus | |
| 179 | 新增: } | |
| 180 | 新增: return s.saveClaudeAccounts(list) | |
| 181 | 新增:} | |
| 182 | 新增: | |
| 183 | 新增:func (s *Server) claudePanelView(ctx context.Context) (claudePanel, claudeAccountList, error) { | |
| 184 | 新增: s.mu.Lock() | |
| 185 | 新增: ready, update := s.ready, s.guestUpdateRequired | |
| 186 | 新增: s.mu.Unlock() | |
| 187 | 新增: view := claudePanel{DetectionStatus: "offline"} | |
| 188 | 新增: if unavailable := s.usageAvailability(); unavailable != nil { | |
| 189 | 新增: view.UsageUnavailableReason = unavailable.Error() | |
| 190 | 新增: } | |
| 191 | 新增: var reading claudeGuestSnapshot | |
| 192 | 新增: var checked time.Time | |
| 193 | 新增: if update { | |
| 194 | 新增: view.DetectionStatus = "update_required" | |
| 195 | 新增: view.DetectionError = "请同步环境组件后再检测普通终端的登录" | |
| 196 | 新增: } else if ready { | |
| 197 | 新增: var err error | |
| 198 | 新增: reading, checked, err = s.inspectClaudeDefault(ctx, false) | |
| 199 | 新增: if err != nil { | |
| 200 | 新增: view.DetectionStatus, view.DetectionError = "unavailable", err.Error() | |
| 201 | 新增: } else if reading.subject() == "" { | |
| 202 | 新增: view.DetectionStatus = "signed_out" | |
| 203 | 新增: } else { | |
| 204 | 新增: view.DetectionStatus = "ready" | |
| 205 | 新增: } | |
| 206 | 新增: } | |
| 207 | 新增: m := &s.claudeAccounts | |
| 208 | 新增: m.mu.Lock() | |
| 209 | 新增: list, err := s.loadClaudeAccounts() | |
| 210 | 新增: m.mu.Unlock() | |
| 211 | 新增: if err != nil { | |
| 212 | 新增: return view, list, err | |
| 213 | 新增: } | |
| 214 | 新增: if ready && !update && list.PendingLogin != "" && !s.claudeLoginActive(list.PendingLogin) { | |
| 215 | 新增: _ = s.recoverClaudePending(ctx, list.PendingLogin, false) | |
| 216 | 新增: } | |
| 217 | 新增: m.mu.Lock() | |
| 218 | 新增: defer m.mu.Unlock() | |
| 219 | 新增: list, err = s.loadClaudeAccounts() | |
| 220 | 新增: if err != nil { | |
| 221 | 新增: return view, list, err | |
| 222 | 新增: } | |
| 223 | 新增: view.Accounts, view.LoginNotice = list.Accounts, m.loginNotice | |
| 224 | 新增: view.UsagePanelRunning = m.panelRunning | |
| 225 | 新增: if subject := reading.subject(); view.DetectionStatus == "ready" && list.bySubject(subject) == nil { | |
| 226 | 新增: view.Detected = &claudeDetected{Identity: subject, Email: reading.email(), Organization: strings.TrimSpace(reading.Organization), Plan: reading.Plan, Quota: reading.Quota, CheckedAt: checked.Unix()} | |
| 227 | 新增: } | |
| 228 | 新增: for i := range view.Accounts { | |
| 229 | 新增: a := &view.Accounts[i] | |
| 230 | 新增: a.UsageChecking = m.usageActive[claudeIdentityHash(a.Email, a.Organization)] != nil | |
| 231 | 新增: } | |
| 232 | 新增: if d := view.Detected; d != nil { | |
| 233 | 新增: if stored := m.detectedUsage[d.Identity]; stored != nil { | |
| 234 | 新增: d.Quota, d.UsageCheckedAt, d.UsageStatus = stored.Quota, stored.UsageCheckedAt, stored.UsageStatus | |
| 235 | 新增: } | |
| 236 | 新增: d.UsageChecking = m.usageActive[d.Identity] != nil | |
| 237 | 新增: } | |
| 238 | 新增: return view, list, nil | |
| 239 | 新增:} | |
| @@ -0,0 +1,323 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "encoding/json" | |
| 6 | 新增: "errors" | |
| 7 | 新增: "net/http" | |
| 8 | 新增: "os" | |
| 9 | 新增: "path/filepath" | |
| 10 | 新增: "strings" | |
| 11 | 新增: "sync" | |
| 12 | 新增: "sync/atomic" | |
| 13 | 新增: "testing" | |
| 14 | 新增: "time" | |
| 15 | 新增:) | |
| 16 | 新增: | |
| 17 | 新增:func TestClaudeDefaultDiscoveryJoinAndLiveIdentity(t *testing.T) { | |
| 18 | 新增: s := testServer(t) | |
| 19 | 新增: s.ready = true | |
| 20 | 新增: at := time.Now().Unix() | |
| 21 | 新增: a := claudeGuestSnapshot{LoggedIn: true, Email: "[email protected]", Organization: "personal", Quota: &claudeQuota{ObservedAt: at, FiveHour: &claudeWindow{UsedPercentage: 37, ResetsAt: at + 300}}} | |
| 22 | 新增: b := claudeGuestSnapshot{LoggedIn: true, Email: "[email protected]", Organization: "work"} | |
| 23 | 新增: current := a | |
| 24 | 新增: var unavailable bool | |
| 25 | 新增: var probes int | |
| 26 | 新增: s.claudeAccounts.probe = func(_ context.Context, id string) (claudeGuestSnapshot, error) { | |
| 27 | 新增: if id != "default" { | |
| 28 | 新增: t.Errorf("unexpected probe %q", id) | |
| 29 | 新增: } | |
| 30 | 新增: probes++ | |
| 31 | 新增: if unavailable { | |
| 32 | 新增: return claudeGuestSnapshot{}, errors.New("SSH unavailable") | |
| 33 | 新增: } | |
| 34 | 新增: return current, nil | |
| 35 | 新增: } | |
| 36 | 新增: panel := func() claudePanel { | |
| 37 | 新增: t.Helper() | |
| 38 | 新增: w := request(s, "GET", "/api/claude-accounts", "", "", true) | |
| 39 | 新增: var v claudePanel | |
| 40 | 新增: if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &v) != nil { | |
| 41 | 新增: t.Fatal(w.Code, w.Body) | |
| 42 | 新增: } | |
| 43 | 新增: return v | |
| 44 | 新增: } | |
| 45 | 新增: join := func(person claudeGuestSnapshot, status int) { | |
| 46 | 新增: t.Helper() | |
| 47 | 新增: w := request(s, "POST", "/api/claude-accounts", s.origin, `{"action":"join","identity":"`+person.subject()+`"}`, true) | |
| 48 | 新增: if w.Code != status { | |
| 49 | 新增: t.Fatalf("join got %d, want %d (%s)", w.Code, status, w.Body) | |
| 50 | 新增: } | |
| 51 | 新增: } | |
| 52 | 新增: if v := panel(); v.DetectionStatus != "ready" || v.Detected == nil || v.Detected.Email != a.Email || len(v.Accounts) != 0 { | |
| 53 | 新增: t.Fatal(v) | |
| 54 | 新增: } | |
| 55 | 新增: _ = panel() | |
| 56 | 新增: if probes != 1 { | |
| 57 | 新增: t.Fatal("panel did not cache initial probe", probes) | |
| 58 | 新增: } | |
| 59 | 新增: if _, err := os.Stat(filepath.Join(s.profile, "claude-accounts.json")); !os.IsNotExist(err) { | |
| 60 | 新增: t.Fatal("discovery enrolled or wrote an identity") | |
| 61 | 新增: } | |
| 62 | 新增: current = b | |
| 63 | 新增: join(a, 409) | |
| 64 | 新增: current = a | |
| 65 | 新增: join(a, 200) | |
| 66 | 新增: choice, err := s.selectClaudeAccount("", false, "/p") | |
| 67 | 新增: if err != nil || choice.Subject != a.subject() || choice.GuestID != "default" || !validClaudeID(choice.ID) { | |
| 68 | 新增: t.Fatal(choice, err) | |
| 69 | 新增: } | |
| 70 | 新增: current = b | |
| 71 | 新增: if _, err = s.selectClaudeAccount("", false, "/p"); err == nil { | |
| 72 | 新增: t.Fatal("selected a default identity that was no longer present") | |
| 73 | 新增: } | |
| 74 | 新增: if v := panel(); v.Detected == nil || v.Detected.Identity != b.subject() || len(v.Accounts) != 1 || v.Accounts[0].Status != "changed" { | |
| 75 | 新增: t.Fatal(v) | |
| 76 | 新增: } | |
| 77 | 新增: join(b, 200) | |
| 78 | 新增: joined, err := s.selectClaudeAccount("", false, "/p") | |
| 79 | 新增: if err != nil || joined.ID == choice.ID || joined.Subject != b.subject() || choice.Subject != a.subject() { | |
| 80 | 新增: t.Fatalf("selection lost the original snapshot: %+v %+v %v", choice, joined, err) | |
| 81 | 新增: } | |
| 82 | 新增: if v := panel(); v.Detected != nil || len(v.Accounts) != 2 || v.Accounts[1].Quota != nil { | |
| 83 | 新增: t.Fatalf("inherited A's quota or registered B twice: %+v", v) | |
| 84 | 新增: } | |
| 85 | 新增: unavailable = true | |
| 86 | 新增: if _, err = s.selectClaudeAccount("", false, "/p"); err == nil { | |
| 87 | 新增: t.Fatal("stale default identity passed a failed live check") | |
| 88 | 新增: } | |
| 89 | 新增: if v := panel(); v.DetectionStatus != "unavailable" || v.DetectionError == "" || v.Detected != nil { | |
| 90 | 新增: t.Fatal(v) | |
| 91 | 新增: } | |
| 92 | 新增: if _, err = s.selectClaudeAccount(choice.ID, true, ""); err == nil { | |
| 93 | 新增: t.Fatal("login tool could mutate default credentials") | |
| 94 | 新增: } | |
| 95 | 新增:} | |
| 96 | 新增: | |
| 97 | 新增:func TestClaudeDefaultManagedDuplicateAndFallback(t *testing.T) { | |
| 98 | 新增: s := testServer(t) | |
| 99 | 新增: read := claudeGuestSnapshot{LoggedIn: true, Email: "[email protected]", Organization: "team"} | |
| 100 | 新增: s.claudeAccounts.probe = func(context.Context, string) (claudeGuestSnapshot, error) { return read, nil } | |
| 101 | 新增: list := claudeAccountList{Accounts: []claudeAccount{ | |
| 102 | 新增: {ID: strings.Repeat("a", 24), Source: "managed", Email: read.Email, Organization: read.Organization, Enabled: true, Status: "ready"}, | |
| 103 | 新增: {ID: strings.Repeat("b", 24), Source: "default", Email: "[email protected]", Organization: "team", Enabled: true, Status: "ready"}, | |
| 104 | 新增: }} | |
| 105 | 新增: if err := s.saveClaudeAccounts(list); err != nil { | |
| 106 | 新增: t.Fatal(err) | |
| 107 | 新增: } | |
| 108 | 新增: s.ready = true | |
| 109 | 新增: v, _, err := s.claudePanelView(context.Background()) | |
| 110 | 新增: if err != nil || v.Detected != nil || v.Accounts[1].Status != "changed" { | |
| 111 | 新增: t.Fatal(v, err) | |
| 112 | 新增: } | |
| 113 | 新增: if err = s.joinClaudeDefault(context.Background(), read.subject()); err != nil { | |
| 114 | 新增: t.Fatal(err) | |
| 115 | 新增: } | |
| 116 | 新增: noReadings := func(context.Context, []string) (map[string]claudeGuestQuota, error) { return nil, nil } | |
| 117 | 新增: selection, err := s.allocateClaudeAccount(list, "", noReadings) | |
| 118 | 新增: if err != nil || selection.ID != list.Accounts[0].ID || selection.GuestID != selection.ID || selection.Subject != read.subject() { | |
| 119 | 新增: t.Fatal(selection, err) | |
| 120 | 新增: } | |
| 121 | 新增: got, _ := s.loadClaudeAccounts() | |
| 122 | 新增: if len(got.Accounts) != 2 { | |
| 123 | 新增: t.Fatal("second copy of the same subscribed identity") | |
| 124 | 新增: } | |
| 125 | 新增:} | |
| 126 | 新增: | |
| 127 | 新增:func TestClaudeOneStepLoginSurvivesLockAndRestart(t *testing.T) { | |
| 128 | 新增: s := testServer(t) | |
| 129 | 新增: var current claudeGuestSnapshot | |
| 130 | 新增: s.claudeAccounts.probe = func(context.Context, string) (claudeGuestSnapshot, error) { return current, nil } | |
| 131 | 新增: // The first request only reserves a private directory for the official CLI. | |
| 132 | 新增: login, err := s.selectClaudeAccount("", true, "") | |
| 133 | 新增: if err != nil || !validClaudeID(login.ID) || login.GuestID != login.ID { | |
| 134 | 新增: t.Fatal(login, err) | |
| 135 | 新增: } | |
| 136 | 新增: retry, err := s.selectClaudeAccount("", true, "") | |
| 137 | 新增: if err != nil || login != retry { | |
| 138 | 新增: t.Fatal("retry created another profile", login, retry, err) | |
| 139 | 新增: } | |
| 140 | 新增: list, _ := s.loadClaudeAccounts() | |
| 141 | 新增: if len(list.Accounts) != 0 || list.PendingLogin != login.ID { | |
| 142 | 新增: t.Fatal("pending attempt exposed an account") | |
| 143 | 新增: } | |
| 144 | 新增: if legacy, err := s.selectClaudeAccount("", false, ""); err != nil || legacy.ID != "" { | |
| 145 | 新增: t.Fatal("pending login blocked existing workflow", legacy, err) | |
| 146 | 新增: } | |
| 147 | 新增: s.account.lock() | |
| 148 | 新增: current = claudeGuestSnapshot{LoggedIn: true, Email: "[email protected]", Organization: "work", Plan: "pro"} | |
| 149 | 新增: if err = s.confirmClaudeLogin(context.Background(), login.ID); err == nil { | |
| 150 | 新增: t.Fatal("registered while locked") | |
| 151 | 新增: } | |
| 152 | 新增: s.account.setKey(make([]byte, 32)) | |
| 153 | 新增: restarted := &Server{profile: s.profile, account: s.account, ready: true} | |
| 154 | 新增: restarted.claudeAccounts.probe = func(_ context.Context, id string) (claudeGuestSnapshot, error) { | |
| 155 | 新增: if id == "default" { | |
| 156 | 新增: return claudeGuestSnapshot{}, nil | |
| 157 | 新增: } | |
| 158 | 新增: if id != login.ID { | |
| 159 | 新增: t.Fatal("opened wrong profile", id) | |
| 160 | 新增: } | |
| 161 | 新增: return current, nil | |
| 162 | 新增: } | |
| 163 | 新增: v, _, err := restarted.claudePanelView(context.Background()) | |
| 164 | 新增: if err != nil || len(v.Accounts) != 1 || v.Accounts[0].ID != login.ID || v.Accounts[0].Label != current.Email || !v.Accounts[0].Enabled || v.Accounts[0].Status != "ready" || v.Accounts[0].Source != "managed" { | |
| 165 | 新增: t.Fatalf("successful login was not recovered: %+v %v", v, err) | |
| 166 | 新增: } | |
| 167 | 新增: list, _ = restarted.loadClaudeAccounts() | |
| 168 | 新增: if list.PendingLogin != "" { | |
| 169 | 新增: t.Fatal("finished enrollment retained pending marker") | |
| 170 | 新增: } | |
| 171 | 新增: if err = restarted.confirmClaudeLogin(context.Background(), login.ID); err != nil { | |
| 172 | 新增: t.Fatal(err) | |
| 173 | 新增: } | |
| 174 | 新增: list, _ = restarted.loadClaudeAccounts() | |
| 175 | 新增: if len(list.Accounts) != 1 { | |
| 176 | 新增: t.Fatal("repeated completion registered twice") | |
| 177 | 新增: } | |
| 178 | 新增:} | |
| 179 | 新增: | |
| 180 | 新增:func TestClaudeUnsuccessfulLoginAndDuplicateStayOutsidePool(t *testing.T) { | |
| 181 | 新增: s := testServer(t) | |
| 182 | 新增: var current claudeGuestSnapshot | |
| 183 | 新增: s.claudeAccounts.probe = func(context.Context, string) (claudeGuestSnapshot, error) { return current, nil } | |
| 184 | 新增: login, err := s.selectClaudeAccount("", true, "") | |
| 185 | 新增: if err != nil { | |
| 186 | 新增: t.Fatal(err) | |
| 187 | 新增: } | |
| 188 | 新增: if err = s.confirmClaudeLogin(context.Background(), login.ID); err != nil { | |
| 189 | 新增: t.Fatal(err) | |
| 190 | 新增: } | |
| 191 | 新增: list, _ := s.loadClaudeAccounts() | |
| 192 | 新增: if len(list.Accounts) != 0 || list.PendingLogin != "" { | |
| 193 | 新增: t.Fatalf("cancelled login became a profile: %+v", list) | |
| 194 | 新增: } | |
| 195 | 新增: current = claudeGuestSnapshot{LoggedIn: true, Email: "[email protected]"} | |
| 196 | 新增: original := strings.Repeat("1", 24) | |
| 197 | 新增: list.Accounts = append(list.Accounts, claudeAccount{ID: original, Source: "managed", Email: current.Email, Enabled: false, Status: "ready"}) | |
| 198 | 新增: if err = s.saveClaudeAccounts(list); err != nil { | |
| 199 | 新增: t.Fatal(err) | |
| 200 | 新增: } | |
| 201 | 新增: login, err = s.selectClaudeAccount("", true, "") | |
| 202 | 新增: if err != nil { | |
| 203 | 新增: t.Fatal(err) | |
| 204 | 新增: } | |
| 205 | 新增: if err = s.confirmClaudeLogin(context.Background(), login.ID); err != nil { | |
| 206 | 新增: t.Fatal(err) | |
| 207 | 新增: } | |
| 208 | 新增: list, _ = s.loadClaudeAccounts() | |
| 209 | 新增: if list.PendingLogin != "" || len(list.Accounts) != 1 || list.Accounts[0].Enabled || list.Accounts[0].ID != original { | |
| 210 | 新增: t.Fatal("duplicate login altered membership", list) | |
| 211 | 新增: } | |
| 212 | 新增:} | |
| 213 | 新增: | |
| 214 | 新增:func TestClaudeDefaultConcurrentDiscoverySingleProbe(t *testing.T) { | |
| 215 | 新增: s := testServer(t) | |
| 216 | 新增: s.ready = true | |
| 217 | 新增: var calls atomic.Int32 | |
| 218 | 新增: entered, release := make(chan struct{}), make(chan struct{}) | |
| 219 | 新增: s.claudeAccounts.probe = func(context.Context, string) (claudeGuestSnapshot, error) { | |
| 220 | 新增: if calls.Add(1) == 1 { | |
| 221 | 新增: close(entered) | |
| 222 | 新增: } | |
| 223 | 新增: <-release | |
| 224 | 新增: return claudeGuestSnapshot{}, nil | |
| 225 | 新增: } | |
| 226 | 新增: var wg sync.WaitGroup | |
| 227 | 新增: for range 2 { | |
| 228 | 新增: wg.Add(1) | |
| 229 | 新增: go func() { | |
| 230 | 新增: defer wg.Done() | |
| 231 | 新增: v, _, err := s.claudePanelView(context.Background()) | |
| 232 | 新增: if err != nil || v.DetectionStatus != "signed_out" { | |
| 233 | 新增: t.Error(v, err) | |
| 234 | 新增: } | |
| 235 | 新增: }() | |
| 236 | 新增: } | |
| 237 | 新增: <-entered | |
| 238 | 新增: close(release) | |
| 239 | 新增: wg.Wait() | |
| 240 | 新增: if calls.Load() != 1 { | |
| 241 | 新增: t.Fatal("concurrent panel refresh duplicated a guest probe") | |
| 242 | 新增: } | |
| 243 | 新增: s.guestUpdateRequired = true | |
| 244 | 新增: v, _, err := s.claudePanelView(context.Background()) | |
| 245 | 新增: if err != nil || v.DetectionStatus != "update_required" || v.DetectionError == "" { | |
| 246 | 新增: t.Fatal(v, err) | |
| 247 | 新增: } | |
| 248 | 新增: if w := request(s, "POST", "/api/claude-accounts", s.origin, `{"action":"create","label":"phantom"}`, true); w.Code == http.StatusOK { | |
| 249 | 新增: t.Fatal("registration without real login accepted") | |
| 250 | 新增: } | |
| 251 | 新增:} | |
| 252 | 新增: | |
| 253 | 新增:func TestClaudeIndependentLoginKeepsDefaultIdentityAndMakesBothAccountsAvailable(t *testing.T) { | |
| 254 | 新增: s := testServer(t) | |
| 255 | 新增: ctx := context.Background() | |
| 256 | 新增: a := claudeGuestSnapshot{LoggedIn: true, Email: "[email protected]", Organization: "home"} | |
| 257 | 新增: b := claudeGuestSnapshot{LoggedIn: true, Email: "[email protected]", Organization: "work"} | |
| 258 | 新增: current := a | |
| 259 | 新增: var independent string | |
| 260 | 新增: s.claudeAccounts.probe = func(_ context.Context, id string) (claudeGuestSnapshot, error) { | |
| 261 | 新增: switch id { | |
| 262 | 新增: case "default": | |
| 263 | 新增: return current, nil | |
| 264 | 新增: case independent: | |
| 265 | 新增: return a, nil | |
| 266 | 新增: default: | |
| 267 | 新增: return claudeGuestSnapshot{}, errors.New("wrong configuration directory") | |
| 268 | 新增: } | |
| 269 | 新增: } | |
| 270 | 新增: if err := s.joinClaudeDefault(ctx, a.subject()); err != nil { | |
| 271 | 新增: t.Fatal(err) | |
| 272 | 新增: } | |
| 273 | 新增: list, _ := s.loadClaudeAccounts() | |
| 274 | 新增: stable := list.bySubject(a.subject()).ID | |
| 275 | 新增: list.Accounts[0].Label, list.Accounts[0].Enabled = "个人空间", false | |
| 276 | 新增: if err := s.saveClaudeAccounts(list); err != nil { | |
| 277 | 新增: t.Fatal(err) | |
| 278 | 新增: } | |
| 279 | 新增: current = b | |
| 280 | 新增: if err := s.joinClaudeDefault(ctx, b.subject()); err != nil { | |
| 281 | 新增: t.Fatal(err) | |
| 282 | 新增: } | |
| 283 | 新增: next, err := s.selectClaudeAccount("", true, "") | |
| 284 | 新增: if err != nil { | |
| 285 | 新增: t.Fatal(err) | |
| 286 | 新增: } | |
| 287 | 新增: independent = next.GuestID | |
| 288 | 新增: if err = s.confirmClaudeLogin(ctx, next.ID); err != nil { | |
| 289 | 新增: t.Fatal(err) | |
| 290 | 新增: } | |
| 291 | 新增: if err = s.confirmClaudeLogin(ctx, next.ID); err != nil { | |
| 292 | 新增: t.Fatal("duplicate completion probed the wrong directory", err) | |
| 293 | 新增: } | |
| 294 | 新增: list, err = s.loadClaudeAccounts() | |
| 295 | 新增: old := list.find(stable) | |
| 296 | 新增: if err != nil || len(list.Accounts) != 2 || old == nil || old.Source != "managed" || old.ProfileID != independent || old.Enabled || old.Label != "个人空间" || old.Status != "ready" { | |
| 297 | 新增: t.Fatal(list, err) | |
| 298 | 新增: } | |
| 299 | 新增: // Re-enabling A must allow new work on both subscriptions simultaneously. | |
| 300 | 新增: old.Enabled = true | |
| 301 | 新增: if err = s.saveClaudeAccounts(list); err != nil { | |
| 302 | 新增: t.Fatal(err) | |
| 303 | 新增: } | |
| 304 | 新增: read := func(_ context.Context, ids []string) (map[string]claudeGuestQuota, error) { | |
| 305 | 新增: if len(ids) != 1 || ids[0] != independent { | |
| 306 | 新增: t.Errorf("wrong guest quota directories: %v", ids) | |
| 307 | 新增: } | |
| 308 | 新增: return nil, nil | |
| 309 | 新增: } | |
| 310 | 新增: first, err := s.allocateClaudeAccount(list, "", read) | |
| 311 | 新增: if err != nil || first.ID != stable || first.GuestID != independent || first.Subject != a.subject() { | |
| 312 | 新增: t.Fatal(first, err) | |
| 313 | 新增: } | |
| 314 | 新增: s.noteClaudeSelection(first.ID, "") | |
| 315 | 新增: second, err := s.allocateClaudeAccount(list, "", read) | |
| 316 | 新增: if err != nil || second.ID == stable || second.GuestID != "default" || second.Subject != b.subject() { | |
| 317 | 新增: t.Fatal(second, err) | |
| 318 | 新增: } | |
| 319 | 新增: again, err := s.selectClaudeAccount(stable, true, "") | |
| 320 | 新增: if err != nil || again.GuestID != independent { | |
| 321 | 新增: t.Fatal(again, err) | |
| 322 | 新增: } | |
| 323 | 新增:} | |
| @@ -0,0 +1,364 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "errors" | |
| 6 | 新增: "net/http" | |
| 7 | 新增: "slices" | |
| 8 | 新增: "time" | |
| 9 | 新增:) | |
| 10 | 新增: | |
| 11 | 新增:var errClaudeAccessLost = errors.New("Cage 已锁定,请先解锁") | |
| 12 | 新增: | |
| 13 | 新增:type claudeAccountInput struct { | |
| 14 | 新增: Action string `json:"action"` | |
| 15 | 新增: Identity string `json:"identity"` | |
| 16 | 新增: ID string `json:"id"` | |
| 17 | 新增: Label string `json:"label"` | |
| 18 | 新增: Enabled *bool `json:"enabled"` | |
| 19 | 新增:} | |
| 20 | 新增: | |
| 21 | 新增:func (s *Server) listClaudeAccounts(w http.ResponseWriter, r *http.Request) { | |
| 22 | 新增: if r.URL.Query().Get("panel") == "visible" { | |
| 23 | 新增: m := &s.claudeAccounts | |
| 24 | 新增: m.mu.Lock() | |
| 25 | 新增: if m.panelRunning { | |
| 26 | 新增: m.panelUntil = time.Now().Add(claudePanelLease) | |
| 27 | 新增: } | |
| 28 | 新增: m.mu.Unlock() | |
| 29 | 新增: } | |
| 30 | 新增: view, list, err := s.claudePanelView(r.Context()) | |
| 31 | 新增: if err != nil { | |
| 32 | 新增: requestError(w, err) | |
| 33 | 新增: return | |
| 34 | 新增: } | |
| 35 | 新增: jsonReply(w, view) | |
| 36 | 新增: s.pollClaudeAccounts(list) | |
| 37 | 新增:} | |
| 38 | 新增: | |
| 39 | 新增:func (s *Server) mutateClaudeAccounts(w http.ResponseWriter, r *http.Request) { | |
| 40 | 新增: var input claudeAccountInput | |
| 41 | 新增: if !readJSON(w, r, &input) { | |
| 42 | 新增: return | |
| 43 | 新增: } | |
| 44 | 新增: var err error | |
| 45 | 新增: switch input.Action { | |
| 46 | 新增: case "join": | |
| 47 | 新增: err = s.joinClaudeDefault(r.Context(), input.Identity) | |
| 48 | 新增: case "cancel": | |
| 49 | 新增: _, err = s.cancelClaudeDraft(input.ID) | |
| 50 | 新增: case "usage_panel": | |
| 51 | 新增: view, list, viewErr := s.claudePanelView(r.Context()) | |
| 52 | 新增: if viewErr != nil { | |
| 53 | 新增: requestError(w, viewErr) | |
| 54 | 新增: return | |
| 55 | 新增: } | |
| 56 | 新增: s.startClaudePanelUsage(list, view.Detected) | |
| 57 | 新增: m := &s.claudeAccounts | |
| 58 | 新增: m.mu.Lock() | |
| 59 | 新增: view.UsagePanelRunning = m.panelRunning | |
| 60 | 新增: m.mu.Unlock() | |
| 61 | 新增: jsonReply(w, view) | |
| 62 | 新增: return | |
| 63 | 新增: case "refresh", "refresh_default": | |
| 64 | 新增: err = s.refreshClaudeUsage(r.Context(), input) | |
| 65 | 新增: case "update": | |
| 66 | 新增: m := &s.claudeAccounts | |
| 67 | 新增: m.mu.Lock() | |
| 68 | 新增: list, loadErr := s.loadClaudeAccounts() | |
| 69 | 新增: err = loadErr | |
| 70 | 新增: if err == nil { | |
| 71 | 新增: err = list.change(input) | |
| 72 | 新增: } | |
| 73 | 新增: if err == nil { | |
| 74 | 新增: err = s.saveClaudeAccounts(list) | |
| 75 | 新增: } | |
| 76 | 新增: m.mu.Unlock() | |
| 77 | 新增: default: | |
| 78 | 新增: err = errors.New("未知 Claude 账号操作") | |
| 79 | 新增: } | |
| 80 | 新增: if err != nil { | |
| 81 | 新增: http.Error(w, err.Error(), http.StatusConflict) | |
| 82 | 新增: return | |
| 83 | 新增: } | |
| 84 | 新增: s.listClaudeAccounts(w, r) | |
| 85 | 新增:} | |
| 86 | 新增: | |
| 87 | 新增:// Terminal admission holds op through publication. Cancellation must not | |
| 88 | 新增:// remove a draft between selecting the login profile and publishing its PTY. | |
| 89 | 新增:func (s *Server) cancelClaudeDraft(id string) (claudeAccountList, error) { | |
| 90 | 新增: if !validClaudeID(id) { | |
| 91 | 新增: return claudeAccountList{}, errors.New("未找到待撤销的账号") | |
| 92 | 新增: } | |
| 93 | 新增: if !s.op.TryLock() { | |
| 94 | 新增: return claudeAccountList{}, errors.New("环境正在处理其他操作,请稍后重试") | |
| 95 | 新增: } | |
| 96 | 新增: defer s.op.Unlock() | |
| 97 | 新增: m := &s.claudeAccounts | |
| 98 | 新增: m.mu.Lock() | |
| 99 | 新增: defer m.mu.Unlock() | |
| 100 | 新增: list, err := s.loadClaudeAccounts() | |
| 101 | 新增: if err != nil { | |
| 102 | 新增: return list, err | |
| 103 | 新增: } | |
| 104 | 新增: a := list.find(id) | |
| 105 | 新增: if a == nil { | |
| 106 | 新增: return list, nil | |
| 107 | 新增: } | |
| 108 | 新增: if a.Email != "" { | |
| 109 | 新增: return list, errors.New("已绑定的账号可以暂停参与分配,不能撤销添加") | |
| 110 | 新增: } | |
| 111 | 新增: if m.refreshing[id] != nil { | |
| 112 | 新增: return list, errors.New("账号状态检查尚未结束,请稍后重试") | |
| 113 | 新增: } | |
| 114 | 新增: for _, session := range s.terminals.snapshot() { | |
| 115 | 新增: if session["claude_account_id"] == id && session["closed"] == false { | |
| 116 | 新增: return list, errors.New("请先结束该账号的登录或工作终端,再撤销添加") | |
| 117 | 新增: } | |
| 118 | 新增: } | |
| 119 | 新增: list.Accounts = slices.DeleteFunc(list.Accounts, func(a claudeAccount) bool { return a.ID == id }) | |
| 120 | 新增: err = s.saveClaudeAccounts(list) | |
| 121 | 新增: if err == nil { | |
| 122 | 新增: delete(m.attempted, id) | |
| 123 | 新增: } | |
| 124 | 新增: return list, err | |
| 125 | 新增:} | |
| 126 | 新增: | |
| 127 | 新增:func (s *Server) claudeLoginActive(id string) bool { | |
| 128 | 新增: for _, session := range s.terminals.snapshot() { | |
| 129 | 新增: if session["kind"] == "claude-login" && session["claude_account_id"] == id && session["closed"] == false { | |
| 130 | 新增: return true | |
| 131 | 新增: } | |
| 132 | 新增: } | |
| 133 | 新增: return false | |
| 134 | 新增:} | |
| 135 | 新增: | |
| 136 | 新增:func (s *Server) recoverClaudePending(ctx context.Context, id string, force bool) error { | |
| 137 | 新增: m := &s.claudeAccounts | |
| 138 | 新增: m.mu.Lock() | |
| 139 | 新增: recent := time.Since(m.attempted[id]) < time.Minute | |
| 140 | 新增: m.mu.Unlock() | |
| 141 | 新增: if !force && recent { | |
| 142 | 新增: return nil | |
| 143 | 新增: } | |
| 144 | 新增: return s.refreshClaudeAccount(ctx, id) | |
| 145 | 新增:} | |
| 146 | 新增: | |
| 147 | 新增:func (s *Server) pollClaudeAccounts(list claudeAccountList) { | |
| 148 | 新增: s.mu.Lock() | |
| 149 | 新增: ready := s.ready && !s.closing | |
| 150 | 新增: s.mu.Unlock() | |
| 151 | 新增: epoch, unlocked := s.account.access() | |
| 152 | 新增: if !unlocked || !ready || (len(list.Accounts) == 0 && list.PendingLogin == "") { | |
| 153 | 新增: return | |
| 154 | 新增: } | |
| 155 | 新增: now := time.Now() | |
| 156 | 新增: m := &s.claudeAccounts | |
| 157 | 新增: m.mu.Lock() | |
| 158 | 新增: if m.panelRunning || len(m.usageActive) > 0 || len(m.refreshing) > 0 { | |
| 159 | 新增: m.mu.Unlock() | |
| 160 | 新增: return | |
| 161 | 新增: } | |
| 162 | 新增: id := "" | |
| 163 | 新增: var oldest time.Time | |
| 164 | 新增: for _, a := range list.Accounts { | |
| 165 | 新增: attempt := m.attempted[a.ID] | |
| 166 | 新增: if m.usageActive[claudeIdentityHash(a.Email, a.Organization)] == nil && a.Source != "default" && a.Enabled && now.Sub(attempt) >= time.Minute && (id == "" || attempt.Before(oldest)) { | |
| 167 | 新增: id, oldest = a.ID, attempt | |
| 168 | 新增: } | |
| 169 | 新增: } | |
| 170 | 新增: if pending := list.PendingLogin; pending != "" && !s.claudeLoginActive(pending) { | |
| 171 | 新增: at := m.attempted[pending] | |
| 172 | 新增: if now.Sub(at) >= time.Minute && (id == "" || at.Before(oldest)) { | |
| 173 | 新增: id = pending | |
| 174 | 新增: } | |
| 175 | 新增: } | |
| 176 | 新增: if id == "" { | |
| 177 | 新增: m.mu.Unlock() | |
| 178 | 新增: return | |
| 179 | 新增: } | |
| 180 | 新增: guestID := id | |
| 181 | 新增: if a := list.find(id); a != nil { | |
| 182 | 新增: guestID = a.guestID() | |
| 183 | 新增: } | |
| 184 | 新增: call := m.claim(id) | |
| 185 | 新增: m.mu.Unlock() | |
| 186 | 新增: ctx, finish, err := s.beginActivity(epoch) | |
| 187 | 新增: if err != nil { | |
| 188 | 新增: m.finish(id, call, err) | |
| 189 | 新增: return | |
| 190 | 新增: } | |
| 191 | 新增: go func() { | |
| 192 | 新增: defer finish() | |
| 193 | 新增: s.runClaudeRefresh(ctx, id, guestID, call, false) | |
| 194 | 新增: }() | |
| 195 | 新增:} | |
| 196 | 新增: | |
| 197 | 新增:func (m *claudeAccountManager) claim(id string) *claudeRefresh { | |
| 198 | 新增: if m.refreshing == nil { | |
| 199 | 新增: m.refreshing = make(map[string]*claudeRefresh) | |
| 200 | 新增: m.attempted = make(map[string]time.Time) | |
| 201 | 新增: } | |
| 202 | 新增: m.attempted[id] = time.Now() | |
| 203 | 新增: call := &claudeRefresh{done: make(chan struct{})} | |
| 204 | 新增: m.refreshing[id] = call | |
| 205 | 新增: return call | |
| 206 | 新增:} | |
| 207 | 新增: | |
| 208 | 新增:func (m *claudeAccountManager) finish(id string, call *claudeRefresh, err error) { | |
| 209 | 新增: m.mu.Lock() | |
| 210 | 新增: defer m.mu.Unlock() | |
| 211 | 新增: if errors.Is(err, errClaudeAccessLost) { | |
| 212 | 新增: delete(m.attempted, id) | |
| 213 | 新增: } | |
| 214 | 新增: delete(m.refreshing, id) | |
| 215 | 新增: call.err = err | |
| 216 | 新增: close(call.done) | |
| 217 | 新增:} | |
| 218 | 新增: | |
| 219 | 新增:// A poll begun before login completed might have observed the previous | |
| 220 | 新增:// identity. Wait for it before requesting a post-login observation. | |
| 221 | 新增:func (s *Server) confirmClaudeLogin(ctx context.Context, id string) error { | |
| 222 | 新增: m := &s.claudeAccounts | |
| 223 | 新增: m.mu.Lock() | |
| 224 | 新增: list, err := s.loadClaudeAccounts() | |
| 225 | 新增: if err != nil { | |
| 226 | 新增: m.mu.Unlock() | |
| 227 | 新增: return err | |
| 228 | 新增: } | |
| 229 | 新增: for _, a := range list.Accounts { | |
| 230 | 新增: if a.ProfileID == id && id != "" { | |
| 231 | 新增: id = a.ID | |
| 232 | 新增: break | |
| 233 | 新增: } | |
| 234 | 新增: } | |
| 235 | 新增: prior := m.refreshing[id] | |
| 236 | 新增: m.mu.Unlock() | |
| 237 | 新增: if prior != nil { | |
| 238 | 新增: select { | |
| 239 | 新增: case <-ctx.Done(): | |
| 240 | 新增: return ctx.Err() | |
| 241 | 新增: case <-prior.done: | |
| 242 | 新增: } | |
| 243 | 新增: } | |
| 244 | 新增: return s.refreshClaude(ctx, id, true) | |
| 245 | 新增:} | |
| 246 | 新增: | |
| 247 | 新增:// Login completion, panel polls, and manual refreshes share one probe per | |
| 248 | 新增:// account. A cancelled waiter does not cancel another request's probe. | |
| 249 | 新增:func (s *Server) refreshClaudeAccount(ctx context.Context, id string) error { | |
| 250 | 新增: return s.refreshClaude(ctx, id, false) | |
| 251 | 新增:} | |
| 252 | 新增: | |
| 253 | 新增:func (s *Server) refreshClaude(ctx context.Context, id string, finished bool) error { | |
| 254 | 新增: m := &s.claudeAccounts | |
| 255 | 新增: m.mu.Lock() | |
| 256 | 新增: if call := m.refreshing[id]; call != nil { | |
| 257 | 新增: m.mu.Unlock() | |
| 258 | 新增: select { | |
| 259 | 新增: case <-ctx.Done(): | |
| 260 | 新增: return ctx.Err() | |
| 261 | 新增: case <-call.done: | |
| 262 | 新增: return call.err | |
| 263 | 新增: } | |
| 264 | 新增: } | |
| 265 | 新增: list, err := s.loadClaudeAccounts() | |
| 266 | 新增: if err == nil { | |
| 267 | 新增: if a := list.find(id); a != nil && a.Source == "default" { | |
| 268 | 新增: m.mu.Unlock() | |
| 269 | 新增: _, _, err := s.inspectClaudeDefault(ctx, true) | |
| 270 | 新增: return err | |
| 271 | 新增: } | |
| 272 | 新增: } | |
| 273 | 新增: if err == nil && list.find(id) == nil && (id == "" || list.PendingLogin != id) { | |
| 274 | 新增: err = errors.New("未找到 Claude 账号") | |
| 275 | 新增: } | |
| 276 | 新增: if err != nil { | |
| 277 | 新增: m.mu.Unlock() | |
| 278 | 新增: return err | |
| 279 | 新增: } | |
| 280 | 新增: guestID := id | |
| 281 | 新增: if a := list.find(id); a != nil { | |
| 282 | 新增: guestID = a.guestID() | |
| 283 | 新增: } | |
| 284 | 新增: call := m.claim(id) | |
| 285 | 新增: m.mu.Unlock() | |
| 286 | 新增: s.runClaudeRefresh(ctx, id, guestID, call, finished) | |
| 287 | 新增: return call.err | |
| 288 | 新增:} | |
| 289 | 新增: | |
| 290 | 新增:func (s *Server) runClaudeRefresh(parent context.Context, id, guestID string, call *claudeRefresh, finished bool) { | |
| 291 | 新增: m := &s.claudeAccounts | |
| 292 | 新增: var err error | |
| 293 | 新增: var notice string | |
| 294 | 新增: defer func() { m.finish(id, call, err) }() | |
| 295 | 新增: epoch, unlocked := s.account.access() | |
| 296 | 新增: if !unlocked { | |
| 297 | 新增: err = errClaudeAccessLost | |
| 298 | 新增: return | |
| 299 | 新增: } | |
| 300 | 新增: ctx, cancel := context.WithTimeout(parent, 20*time.Second) | |
| 301 | 新增: stop := context.AfterFunc(epoch, cancel) | |
| 302 | 新增: defer func() { stop(); cancel() }() | |
| 303 | 新增: reading, probeErr := s.probeClaude(ctx, guestID) | |
| 304 | 新增: if epoch.Err() != nil { | |
| 305 | 新增: err = errClaudeAccessLost | |
| 306 | 新增: return | |
| 307 | 新增: } | |
| 308 | 新增: if probeErr != nil { | |
| 309 | 新增: err = errors.New("无法读取账号状态,请确认环境已启动并检查 Claude Code") | |
| 310 | 新增: return | |
| 311 | 新增: } | |
| 312 | 新增: m.mu.Lock() | |
| 313 | 新增: defer m.mu.Unlock() | |
| 314 | 新增: if epoch.Err() != nil { | |
| 315 | 新增: err = errClaudeAccessLost | |
| 316 | 新增: return | |
| 317 | 新增: } | |
| 318 | 新增: if ctx.Err() != nil { | |
| 319 | 新增: err = errors.New("账号状态检查已取消") | |
| 320 | 新增: return | |
| 321 | 新增: } | |
| 322 | 新增: list, err := s.loadClaudeAccounts() | |
| 323 | 新增: if err == nil { | |
| 324 | 新增: if id != "" && id == list.PendingLogin { | |
| 325 | 新增: switch { | |
| 326 | 新增: case reading.subject() != "": | |
| 327 | 新增: if existing := list.bySubject(reading.subject()); existing != nil { | |
| 328 | 新增: if existing.Source == "default" { | |
| 329 | 新增: // Keep the identity and terminal labels stable while future | |
| 330 | 新增: // sessions use this independently authenticated directory. | |
| 331 | 新增: existing.Source, existing.ProfileID = "managed", id | |
| 332 | 新增: err = list.observe(existing.ID, reading, time.Now()) | |
| 333 | 新增: notice = "已为已有账号绑定独立登录,保留原备注和参与设置" | |
| 334 | 新增: } else { | |
| 335 | 新增: notice = "此登录身份已经在账号列表中" | |
| 336 | 新增: } | |
| 337 | 新增: } else { | |
| 338 | 新增: list.Accounts = append(list.Accounts, claudeAccount{ID: id, Source: "managed", Label: reading.email(), Enabled: true}) | |
| 339 | 新增: err = list.observe(id, reading, time.Now()) | |
| 340 | 新增: notice = "已将登录成功的 Claude 账号加入自动分配" | |
| 341 | 新增: } | |
| 342 | 新增: list.PendingLogin = "" | |
| 343 | 新增: case finished: | |
| 344 | 新增: notice = "本次登录未完成,没有添加账号" | |
| 345 | 新增: // A new attempt may already be entering this guest profile. | |
| 346 | 新增: // Keep its ID unless terminal admission is certainly idle. | |
| 347 | 新增: if s.op.TryLock() { | |
| 348 | 新增: if !s.claudeLoginActive(id) { | |
| 349 | 新增: list.PendingLogin = "" | |
| 350 | 新增: } | |
| 351 | 新增: s.op.Unlock() | |
| 352 | 新增: } | |
| 353 | 新增: } | |
| 354 | 新增: } else { | |
| 355 | 新增: err = list.observe(id, reading, time.Now()) | |
| 356 | 新增: } | |
| 357 | 新增: } | |
| 358 | 新增: if err == nil { | |
| 359 | 新增: err = s.saveClaudeAccounts(list) | |
| 360 | 新增: if err == nil && notice != "" { | |
| 361 | 新增: m.loginNotice = notice | |
| 362 | 新增: } | |
| 363 | 新增: } | |
| 364 | 新增:} | |
| @@ -0,0 +1,262 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "encoding/json" | |
| 6 | 新增: "errors" | |
| 7 | 新增: "net/http" | |
| 8 | 新增: "os" | |
| 9 | 新增: "path/filepath" | |
| 10 | 新增: "sort" | |
| 11 | 新增: "strings" | |
| 12 | 新增: "sync" | |
| 13 | 新增: "testing" | |
| 14 | 新增: "time" | |
| 15 | 新增:) | |
| 16 | 新增: | |
| 17 | 新增:func TestClaudeAccountPanelConcurrentWindowsAndLock(t *testing.T) { | |
| 18 | 新增: s := testServer(t) | |
| 19 | 新增: accountID := strings.Repeat("a", 24) | |
| 20 | 新增: list := claudeAccountList{Accounts: []claudeAccount{{ID: accountID, Label: "原名称", Enabled: true, Status: "ready"}}} | |
| 21 | 新增: if err := s.saveClaudeAccounts(list); err != nil { | |
| 22 | 新增: t.Fatal(err) | |
| 23 | 新增: } | |
| 24 | 新增: var wg sync.WaitGroup | |
| 25 | 新增: for _, mutation := range []string{`"label":"工作"`, `"enabled":false`} { | |
| 26 | 新增: wg.Add(1) | |
| 27 | 新增: go func(mutation string) { | |
| 28 | 新增: defer wg.Done() | |
| 29 | 新增: w := request(s, "POST", "/api/claude-accounts", s.origin, `{"action":"update","id":"`+accountID+`",`+mutation+`}`, true) | |
| 30 | 新增: if w.Code != http.StatusOK { | |
| 31 | 新增: t.Errorf("update: %d %s", w.Code, w.Body) | |
| 32 | 新增: } | |
| 33 | 新增: }(mutation) | |
| 34 | 新增: } | |
| 35 | 新增: wg.Wait() | |
| 36 | 新增: list, err := s.loadClaudeAccounts() | |
| 37 | 新增: if err != nil || len(list.Accounts) != 1 || list.Accounts[0].Enabled || list.Accounts[0].Label != "工作" { | |
| 38 | 新增: t.Fatalf("lost concurrent edit: %+v %v", list, err) | |
| 39 | 新增: } | |
| 40 | 新增: a := list.Accounts[0] | |
| 41 | 新增: w := request(s, "POST", "/api/claude-accounts", s.origin, `{"action":"update","id":"`+a.ID+`","label":"已归档","enabled":false}`, true) | |
| 42 | 新增: if w.Code != 200 { | |
| 43 | 新增: t.Fatal(w.Code, w.Body) | |
| 44 | 新增: } | |
| 45 | 新增: reopened := &Server{profile: s.profile} | |
| 46 | 新增: list, err = reopened.loadClaudeAccounts() | |
| 47 | 新增: if err != nil || list.Accounts[0].Enabled || list.Accounts[0].Label != "已归档" { | |
| 48 | 新增: t.Fatalf("updated settings did not persist: %+v %v", list, err) | |
| 49 | 新增: } | |
| 50 | 新增: w = request(s, "POST", "/api/claude-accounts", s.origin, `{"action":"update","id":"`+a.ID+`","enabled":true}`, true) | |
| 51 | 新增: if w.Code != 200 || !strings.Contains(w.Body.String(), `"enabled":true`) { | |
| 52 | 新增: t.Fatal(w.Code, w.Body) | |
| 53 | 新增: } | |
| 54 | 新增: s.account.lock() | |
| 55 | 新增: if w = request(s, "GET", "/api/claude-accounts", "", "", true); w.Code != http.StatusLocked { | |
| 56 | 新增: t.Fatal("locked Cage exposed account data", w.Code) | |
| 57 | 新增: } | |
| 58 | 新增:} | |
| 59 | 新增: | |
| 60 | 新增:func TestClaudeAccountOnlyEmptyRegistryFallsBack(t *testing.T) { | |
| 61 | 新增: s := testServer(t) | |
| 62 | 新增: if id, err := s.selectClaudeAccount("", false, ""); err != nil || id.ID != "" { | |
| 63 | 新增: t.Fatalf("existing user compatibility: %q %v", id, err) | |
| 64 | 新增: } | |
| 65 | 新增: list := claudeAccountList{Accounts: []claudeAccount{{ID: strings.Repeat("a", 24), Label: "A", Enabled: true, Status: "pending"}}} | |
| 66 | 新增: if err := s.saveClaudeAccounts(list); err != nil { | |
| 67 | 新增: t.Fatal(err) | |
| 68 | 新增: } | |
| 69 | 新增: if _, err := s.selectClaudeAccount("", false, ""); err == nil { | |
| 70 | 新增: t.Fatal("unsigned managed account silently switched to legacy") | |
| 71 | 新增: } | |
| 72 | 新增: list.Accounts[0].Enabled = false | |
| 73 | 新增: list.Accounts[0].Status = "ready" | |
| 74 | 新增: if err := s.saveClaudeAccounts(list); err != nil { | |
| 75 | 新增: t.Fatal(err) | |
| 76 | 新增: } | |
| 77 | 新增: if _, err := s.selectClaudeAccount("", false, ""); err == nil { | |
| 78 | 新增: t.Fatal("disabled pool silently switched to legacy") | |
| 79 | 新增: } | |
| 80 | 新增: if id, err := s.selectClaudeAccount(list.Accounts[0].ID, true, ""); err != nil || id.ID != list.Accounts[0].ID { | |
| 81 | 新增: t.Fatalf("cannot reauthenticate paused profile: %q %v", id, err) | |
| 82 | 新增: } | |
| 83 | 新增: if err := os.WriteFile(filepath.Join(s.profile, "claude-accounts.json"), []byte("{"), 0600); err != nil { | |
| 84 | 新增: t.Fatal(err) | |
| 85 | 新增: } | |
| 86 | 新增: if _, err := s.selectClaudeAccount("", false, ""); err == nil { | |
| 87 | 新增: t.Fatal("corrupt registry silently switched to legacy") | |
| 88 | 新增: } | |
| 89 | 新增:} | |
| 90 | 新增: | |
| 91 | 新增:func TestClaudeGuestIdentityAndPartialQuota(t *testing.T) { | |
| 92 | 新增: now := time.Unix(1700000000, 0) | |
| 93 | 新增: list := claudeAccountList{Accounts: []claudeAccount{{ID: "one"}, {ID: "two"}}} | |
| 94 | 新增: first := claudeGuestSnapshot{LoggedIn: true, Email: "[email protected]", Organization: "work", Quota: &claudeQuota{ | |
| 95 | 新增: FiveHour: &claudeWindow{UsedPercentage: 80, ResetsAt: now.Add(time.Hour).Unix()}, SevenDay: &claudeWindow{UsedPercentage: 100, ResetsAt: now.Add(48 * time.Hour).Unix()}, ObservedAt: now.Unix(), | |
| 96 | 新增: }} | |
| 97 | 新增: _ = list.observe("one", first, now) | |
| 98 | 新增: _ = list.observe("two", first, now) | |
| 99 | 新增: if list.Accounts[0].Status != "ready" || list.Accounts[1].Status != "duplicate" || list.Accounts[1].Quota != nil { | |
| 100 | 新增: t.Fatalf("same signed-in subscription counted twice: %+v", list) | |
| 101 | 新增: } | |
| 102 | 新增: first.Quota = &claudeQuota{FiveHour: &claudeWindow{UsedPercentage: 32, ResetsAt: now.Add(3 * time.Hour).Unix()}, ObservedAt: now.Add(time.Hour).Unix()} | |
| 103 | 新增: _ = list.observe("one", first, now.Add(time.Hour)) | |
| 104 | 新增: // A batched response can also carry an older weekly window together | |
| 105 | 新增: // with the new short-window timestamp. | |
| 106 | 新增: first.Quota.SevenDay = &claudeWindow{UsedPercentage: 100, ResetsAt: now.Add(48 * time.Hour).Unix(), ObservedAt: now.Unix()} | |
| 107 | 新增: _ = list.observe("one", first, now.Add(time.Hour)) | |
| 108 | 新增: if list.Accounts[0].Quota.SevenDay.ObservedAt != now.Unix() { | |
| 109 | 新增: t.Fatal("missing weekly window updated its timestamp") | |
| 110 | 新增: } | |
| 111 | 新增: if _, eligible := list.Accounts[0].headroom(now.Add(time.Hour)); eligible { | |
| 112 | 新增: t.Fatal("stale exhausted weekly window became available") | |
| 113 | 新增: } | |
| 114 | 新增: if score, eligible := list.Accounts[0].headroom(now.Add(49 * time.Hour)); !eligible || score != -1 { | |
| 115 | 新增: t.Fatal("reset became a fabricated live reading", score, eligible) | |
| 116 | 新增: } | |
| 117 | 新增: first.Email = "[email protected]" | |
| 118 | 新增: _ = list.observe("one", first, now.Add(time.Hour)) | |
| 119 | 新增: if list.Accounts[0].Status != "changed" || list.Accounts[0].Quota == nil || list.Accounts[0].Email != "[email protected]" { | |
| 120 | 新增: t.Fatal("silent replacement of a bound identity", list.Accounts[0]) | |
| 121 | 新增: } | |
| 122 | 新增:} | |
| 123 | 新增: | |
| 124 | 新增:func TestClaudeAllocationReadsGuestWithoutOpeningPanel(t *testing.T) { | |
| 125 | 新增: s := testServer(t) | |
| 126 | 新增: list := claudeAccountList{Accounts: []claudeAccount{ | |
| 127 | 新增: {ID: strings.Repeat("a", 24), Label: "A", Enabled: true, Status: "ready", Email: "[email protected]"}, | |
| 128 | 新增: {ID: strings.Repeat("b", 24), Label: "B", Enabled: true, Status: "ready", Email: "[email protected]"}, | |
| 129 | 新增: {ID: strings.Repeat("c", 24), Label: "C", Enabled: false, Status: "ready"}, | |
| 130 | 新增: }} | |
| 131 | 新增: if err := s.saveClaudeAccounts(list); err != nil { | |
| 132 | 新增: t.Fatal(err) | |
| 133 | 新增: } | |
| 134 | 新增: now := time.Now() | |
| 135 | 新增: var calls int | |
| 136 | 新增: read := func(ctx context.Context, ids []string) (map[string]claudeGuestQuota, error) { | |
| 137 | 新增: calls++ | |
| 138 | 新增: if !sort.StringsAreSorted(ids) || len(ids) != 2 { | |
| 139 | 新增: t.Fatalf("expected one batch of participating profiles: %v", ids) | |
| 140 | 新增: } | |
| 141 | 新增: q := claudeQuota{FiveHour: &claudeWindow{UsedPercentage: 100, ResetsAt: now.Add(time.Hour).Unix()}, ObservedAt: now.Unix()} | |
| 142 | 新增: return map[string]claudeGuestQuota{ | |
| 143 | 新增: ids[0]: {claudeQuota: q, Identity: claudeIdentityHash("[email protected]", "")}, | |
| 144 | 新增: ids[1]: {claudeQuota: q, Identity: claudeIdentityHash("[email protected]", "")}, | |
| 145 | 新增: }, nil | |
| 146 | 新增: } | |
| 147 | 新增: want := list.Accounts[1].ID | |
| 148 | 新增: id, err := s.allocateClaudeAccount(list, "", read) | |
| 149 | 新增: if err != nil || id.ID != want || calls != 1 { | |
| 150 | 新增: t.Fatalf("did not react to A's new quota or accepted another identity's reading: %q %v", id, err) | |
| 151 | 新增: } | |
| 152 | 新增: id, err = s.allocateClaudeAccount(list, "", func(context.Context, []string) (map[string]claudeGuestQuota, error) { | |
| 153 | 新增: return nil, errors.New("VM temporarily unavailable") | |
| 154 | 新增: }) | |
| 155 | 新增: if err != nil || id.ID != want { | |
| 156 | 新增: t.Fatalf("guest failure erased confirmed exhaustion: %q %v", id, err) | |
| 157 | 新增: } | |
| 158 | 新增: saved, _ := s.loadClaudeAccounts() | |
| 159 | 新增: if saved.Accounts[1].Quota != nil || saved.Accounts[0].Quota.FiveHour.UsedPercentage != 100 { | |
| 160 | 新增: t.Fatal("new observations did not persist with their source identity") | |
| 161 | 新增: } | |
| 162 | 新增:} | |
| 163 | 新增: | |
| 164 | 新增:func TestClaudeAccountRotationReservesActiveSessions(t *testing.T) { | |
| 165 | 新增: list := claudeAccountList{Accounts: []claudeAccount{{ID: "one", Enabled: true, Status: "ready"}, {ID: "two", Enabled: true, Status: "ready"}}} | |
| 166 | 新增: now := time.Now() | |
| 167 | 新增: if id := pickClaudeAccount(list, map[string]int{"one": 1}, nil, "two", "", now); id != "two" { | |
| 168 | 新增: t.Fatal("did not account for occupied terminal", id) | |
| 169 | 新增: } | |
| 170 | 新增: if id := pickClaudeAccount(list, nil, nil, "one", "", now); id != "two" { | |
| 171 | 新增: t.Fatal("equal profiles did not rotate", id) | |
| 172 | 新增: } | |
| 173 | 新增: if id := pickClaudeAccount(list, nil, map[string]bool{"two": true}, "one", "", now); id != "one" { | |
| 174 | 新增: t.Fatal("assigned profile currently signing in", id) | |
| 175 | 新增: } | |
| 176 | 新增:} | |
| 177 | 新增: | |
| 178 | 新增:func TestClaudeQuotaWireFormat(t *testing.T) { | |
| 179 | 新增: var q claudeGuestQuota | |
| 180 | 新增: if err := json.Unmarshal([]byte(`{"identity":"digest","five_hour":{"used_percentage":39,"resets_at":150},"observed_at":100}`), &q); err != nil || q.FiveHour == nil || q.FiveHour.UsedPercentage != 39 || q.Identity != "digest" { | |
| 181 | 新增: t.Fatalf("guest/host envelope mismatch: %+v %v", q, err) | |
| 182 | 新增: } | |
| 183 | 新增:} | |
| 184 | 新增: | |
| 185 | 新增:func TestClaudeProjectAffinityYieldsToAvailabilityAndLoad(t *testing.T) { | |
| 186 | 新增: s := testServer(t) | |
| 187 | 新增: list := claudeAccountList{Accounts: []claudeAccount{ | |
| 188 | 新增: {ID: strings.Repeat("a", 24), Enabled: true, Status: "ready"}, | |
| 189 | 新增: {ID: strings.Repeat("b", 24), Enabled: true, Status: "ready"}, | |
| 190 | 新增: }} | |
| 191 | 新增: if err := s.saveClaudeAccounts(list); err != nil { | |
| 192 | 新增: t.Fatal(err) | |
| 193 | 新增: } | |
| 194 | 新增: noReadings := func(context.Context, []string) (map[string]claudeGuestQuota, error) { return nil, nil } | |
| 195 | 新增: a, b := list.Accounts[0].ID, list.Accounts[1].ID | |
| 196 | 新增: s.noteClaudeSelection(a, "/project") | |
| 197 | 新增: check := func(project, want string) { | |
| 198 | 新增: t.Helper() | |
| 199 | 新增: if id, err := s.allocateClaudeAccount(list, project, noReadings); err != nil || id.ID != want { | |
| 200 | 新增: t.Fatalf("project %q selected %q, want %q (%v)", project, id, want, err) | |
| 201 | 新增: } | |
| 202 | 新增: } | |
| 203 | 新增: check("/project", a) | |
| 204 | 新增: check("/other", b) | |
| 205 | 新增: if id := pickClaudeAccount(list, map[string]int{a: 1}, nil, a, a, time.Now()); id != b { | |
| 206 | 新增: t.Fatal("affinity overrode a busier terminal", id) | |
| 207 | 新增: } | |
| 208 | 新增: list.Accounts[0].Enabled = false | |
| 209 | 新增: if err := s.saveClaudeAccounts(list); err != nil { | |
| 210 | 新增: t.Fatal(err) | |
| 211 | 新增: } | |
| 212 | 新增: check("/project", b) | |
| 213 | 新增: list.Accounts[0].Enabled = true | |
| 214 | 新增: if err := s.saveClaudeAccounts(list); err != nil { | |
| 215 | 新增: t.Fatal(err) | |
| 216 | 新增: } | |
| 217 | 新增: s.claudeAccounts.recent["/project"] = claudeProjectPick{id: a, at: time.Now().Add(-2 * claudeProjectAffinity)} | |
| 218 | 新增: check("/project", b) | |
| 219 | 新增:} | |
| 220 | 新增: | |
| 221 | 新增:func TestClaudeDraftCancellationRespectsAdmissionsAndBoundIdentities(t *testing.T) { | |
| 222 | 新增: s := testServer(t) | |
| 223 | 新增: draft := strings.Repeat("a", 24) | |
| 224 | 新增: list := claudeAccountList{Accounts: []claudeAccount{{ID: draft, Label: "新账号", Status: "pending", Enabled: true}}} | |
| 225 | 新增: if err := s.saveClaudeAccounts(list); err != nil { | |
| 226 | 新增: t.Fatal(err) | |
| 227 | 新增: } | |
| 228 | 新增: cancel := func(want int) { | |
| 229 | 新增: t.Helper() | |
| 230 | 新增: w := request(s, "POST", "/api/claude-accounts", s.origin, `{"action":"cancel","id":"`+draft+`"}`, true) | |
| 231 | 新增: if w.Code != want { | |
| 232 | 新增: t.Fatalf("cancel got %d, want %d: %s", w.Code, want, w.Body) | |
| 233 | 新增: } | |
| 234 | 新增: } | |
| 235 | 新增: // A login has selected its profile but not yet published its terminal. | |
| 236 | 新增: s.op.Lock() | |
| 237 | 新增: cancel(409) | |
| 238 | 新增: s.op.Unlock() | |
| 239 | 新增: s.terminals.sessions = map[string]*terminalSession{"login": {claudeAccountID: draft, kind: "claude-login"}} | |
| 240 | 新增: cancel(409) | |
| 241 | 新增: delete(s.terminals.sessions, "login") | |
| 242 | 新增: s.claudeAccounts.mu.Lock() | |
| 243 | 新增: poll := s.claudeAccounts.claim(draft) | |
| 244 | 新增: s.claudeAccounts.mu.Unlock() | |
| 245 | 新增: cancel(409) | |
| 246 | 新增: s.claudeAccounts.finish(draft, poll, nil) | |
| 247 | 新增: cancel(200) | |
| 248 | 新增: cancel(200) | |
| 249 | 新增: if id, err := s.selectClaudeAccount("", false, ""); err != nil || id.ID != "" { | |
| 250 | 新增: t.Fatalf("cancelling the last draft did not restore existing behavior: %q %v", id, err) | |
| 251 | 新增: } | |
| 252 | 新增: list.Accounts[0].Email = "[email protected]" | |
| 253 | 新增: list.Accounts[0].Status = "signed_out" | |
| 254 | 新增: if err := s.saveClaudeAccounts(list); err != nil { | |
| 255 | 新增: t.Fatal(err) | |
| 256 | 新增: } | |
| 257 | 新增: cancel(409) | |
| 258 | 新增: kept, _ := s.loadClaudeAccounts() | |
| 259 | 新增: if kept.find(draft) == nil { | |
| 260 | 新增: t.Fatal("cancellation removed a previously bound identity") | |
| 261 | 新增: } | |
| 262 | 新增:} | |
| @@ -0,0 +1,296 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "errors" | |
| 6 | 新增: "time" | |
| 7 | 新增:) | |
| 8 | 新增: | |
| 9 | 新增:const ( | |
| 10 | 新增: claudePanelLease = 30 * time.Second | |
| 11 | 新增: claudeUsageInterval = time.Minute | |
| 12 | 新增:) | |
| 13 | 新增: | |
| 14 | 新增:var errClaudeUsageBusy = errors.New("正在检查其他账号的额度,请稍后重试") | |
| 15 | 新增: | |
| 16 | 新增:func claudeUsageDue(checked int64) bool { | |
| 17 | 新增: return checked == 0 || time.Since(time.Unix(checked, 0)) >= claudeUsageInterval | |
| 18 | 新增:} | |
| 19 | 新增: | |
| 20 | 新增:type claudeUsageCall struct { | |
| 21 | 新增: done chan struct{} | |
| 22 | 新增: err error | |
| 23 | 新增:} | |
| 24 | 新增: | |
| 25 | 新增:type claudeUsageTarget struct { | |
| 26 | 新增: id, guest, subject string | |
| 27 | 新增:} | |
| 28 | 新增: | |
| 29 | 新增:// Only opening a visible account panel starts a batch. It uses one worker, | |
| 30 | 新增:// leaving one slot available for an explicit refresh. Reading panel snapshots | |
| 31 | 新增:// can keep an existing batch alive but never starts another one. | |
| 32 | 新增:func (s *Server) startClaudePanelUsage(list claudeAccountList, detected *claudeDetected) { | |
| 33 | 新增: if s.usageAvailability() != nil { | |
| 34 | 新增: return | |
| 35 | 新增: } | |
| 36 | 新增: epoch, unlocked := s.account.access() | |
| 37 | 新增: if !unlocked { | |
| 38 | 新增: return | |
| 39 | 新增: } | |
| 40 | 新增: m := &s.claudeAccounts | |
| 41 | 新增: m.mu.Lock() | |
| 42 | 新增: m.panelUntil = time.Now().Add(claudePanelLease) | |
| 43 | 新增: if m.panelRunning { | |
| 44 | 新增: m.mu.Unlock() | |
| 45 | 新增: return | |
| 46 | 新增: } | |
| 47 | 新增: var targets []claudeUsageTarget | |
| 48 | 新增: if detected != nil && claudeUsageDue(detected.UsageCheckedAt) { | |
| 49 | 新增: targets = append(targets, claudeUsageTarget{guest: "default", subject: detected.Identity}) | |
| 50 | 新增: } | |
| 51 | 新增: for _, a := range list.Accounts { | |
| 52 | 新增: if a.Status != "ready" || a.Email == "" || !claudeUsageDue(a.UsageCheckedAt) { | |
| 53 | 新增: continue | |
| 54 | 新增: } | |
| 55 | 新增: subject := claudeIdentityHash(a.Email, a.Organization) | |
| 56 | 新增: if a.Source == "default" && (m.defaultError != nil || m.defaultReading.subject() != subject) { | |
| 57 | 新增: continue | |
| 58 | 新增: } | |
| 59 | 新增: targets = append(targets, claudeUsageTarget{a.ID, a.guestID(), subject}) | |
| 60 | 新增: } | |
| 61 | 新增: if len(targets) == 0 { | |
| 62 | 新增: m.mu.Unlock() | |
| 63 | 新增: return | |
| 64 | 新增: } | |
| 65 | 新增: m.panelRunning = true | |
| 66 | 新增: m.mu.Unlock() | |
| 67 | 新增: ctx, finish, err := s.beginActivity(epoch) | |
| 68 | 新增: if err != nil { | |
| 69 | 新增: m.mu.Lock() | |
| 70 | 新增: m.panelRunning = false | |
| 71 | 新增: m.mu.Unlock() | |
| 72 | 新增: return | |
| 73 | 新增: } | |
| 74 | 新增: go func() { | |
| 75 | 新增: defer finish() | |
| 76 | 新增: defer func() { m.mu.Lock(); m.panelRunning = false; m.mu.Unlock() }() | |
| 77 | 新增: for i := 0; i < len(targets); { | |
| 78 | 新增: m.mu.Lock() | |
| 79 | 新增: visible := time.Now().Before(m.panelUntil) | |
| 80 | 新增: m.mu.Unlock() | |
| 81 | 新增: if !visible || ctx.Err() != nil || s.usageAvailability() != nil { | |
| 82 | 新增: return | |
| 83 | 新增: } | |
| 84 | 新增: if err := s.checkClaudeUsage(ctx, targets[i], true); !errors.Is(err, errClaudeUsageBusy) { | |
| 85 | 新增: i++ | |
| 86 | 新增: continue | |
| 87 | 新增: } | |
| 88 | 新增: m.mu.Lock() | |
| 89 | 新增: var done <-chan struct{} | |
| 90 | 新增: for _, call := range m.usageActive { | |
| 91 | 新增: done = call.done | |
| 92 | 新增: break | |
| 93 | 新增: } | |
| 94 | 新增: m.mu.Unlock() | |
| 95 | 新增: if done != nil { | |
| 96 | 新增: select { | |
| 97 | 新增: case <-ctx.Done(): | |
| 98 | 新增: return | |
| 99 | 新增: case <-done: | |
| 100 | 新增: } | |
| 101 | 新增: } | |
| 102 | 新增: } | |
| 103 | 新增: }() | |
| 104 | 新增:} | |
| 105 | 新增: | |
| 106 | 新增:func (s *Server) usageAvailability() error { | |
| 107 | 新增: s.mu.Lock() | |
| 108 | 新增: defer s.mu.Unlock() | |
| 109 | 新增: switch { | |
| 110 | 新增: case s.guestUpdateRequired: | |
| 111 | 新增: return errors.New("请先同步环境组件后再查询额度") | |
| 112 | 新增: case s.closing || !s.ready: | |
| 113 | 新增: return errors.New("请先启动 Cage 环境后再查询额度") | |
| 114 | 新增: case s.networkPaused: | |
| 115 | 新增: return errors.New("网络已暂停,恢复连接后可查询订阅额度") | |
| 116 | 新增: default: | |
| 117 | 新增: return nil | |
| 118 | 新增: } | |
| 119 | 新增:} | |
| 120 | 新增: | |
| 121 | 新增:func (s *Server) refreshClaudeUsage(ctx context.Context, input claudeAccountInput) error { | |
| 122 | 新增: if err := s.usageAvailability(); err != nil { | |
| 123 | 新增: return err | |
| 124 | 新增: } | |
| 125 | 新增: if input.Action == "refresh_default" { | |
| 126 | 新增: current, _, err := s.inspectClaudeDefault(ctx, true) | |
| 127 | 新增: if err != nil { | |
| 128 | 新增: return err | |
| 129 | 新增: } | |
| 130 | 新增: if input.Identity == "" || current.subject() != input.Identity { | |
| 131 | 新增: return errors.New("默认登录身份已经变化,请刷新账号面板") | |
| 132 | 新增: } | |
| 133 | 新增: return s.checkClaudeUsage(ctx, claudeUsageTarget{guest: "default", subject: input.Identity}, false) | |
| 134 | 新增: } | |
| 135 | 新增: m := &s.claudeAccounts | |
| 136 | 新增: m.mu.Lock() | |
| 137 | 新增: list, err := s.loadClaudeAccounts() | |
| 138 | 新增: m.mu.Unlock() | |
| 139 | 新增: if err != nil { | |
| 140 | 新增: return err | |
| 141 | 新增: } | |
| 142 | 新增: a := list.find(input.ID) | |
| 143 | 新增: if a == nil { | |
| 144 | 新增: return errors.New("未找到要检查的账号") | |
| 145 | 新增: } | |
| 146 | 新增: if a.Email == "" { | |
| 147 | 新增: if err = s.refreshClaudeAccount(ctx, input.ID); err != nil { | |
| 148 | 新增: return err | |
| 149 | 新增: } | |
| 150 | 新增: m.mu.Lock() | |
| 151 | 新增: list, err = s.loadClaudeAccounts() | |
| 152 | 新增: m.mu.Unlock() | |
| 153 | 新增: if err != nil { | |
| 154 | 新增: return err | |
| 155 | 新增: } | |
| 156 | 新增: a = list.find(input.ID) | |
| 157 | 新增: if a == nil || a.Email == "" { | |
| 158 | 新增: return errors.New("尚未检测到此账号的有效订阅登录") | |
| 159 | 新增: } | |
| 160 | 新增: } | |
| 161 | 新增: return s.checkClaudeUsage(ctx, claudeUsageTarget{a.ID, a.guestID(), claudeIdentityHash(a.Email, a.Organization)}, false) | |
| 162 | 新增:} | |
| 163 | 新增: | |
| 164 | 新增:func (s *Server) checkClaudeUsage(parent context.Context, target claudeUsageTarget, automatic bool) error { | |
| 165 | 新增: if err := s.usageAvailability(); err != nil { | |
| 166 | 新增: return err | |
| 167 | 新增: } | |
| 168 | 新增: epoch, unlocked := s.account.access() | |
| 169 | 新增: if !unlocked { | |
| 170 | 新增: return errClaudeAccessLost | |
| 171 | 新增: } | |
| 172 | 新增: ctx, cancel := context.WithTimeout(parent, 20*time.Second) | |
| 173 | 新增: stop := context.AfterFunc(epoch, cancel) | |
| 174 | 新增: defer func() { stop(); cancel() }() | |
| 175 | 新增: m := &s.claudeAccounts | |
| 176 | 新增: m.mu.Lock() | |
| 177 | 新增: if call := m.usageActive[target.subject]; call != nil { | |
| 178 | 新增: m.mu.Unlock() | |
| 179 | 新增: select { | |
| 180 | 新增: case <-ctx.Done(): | |
| 181 | 新增: return ctx.Err() | |
| 182 | 新增: case <-call.done: | |
| 183 | 新增: return call.err | |
| 184 | 新增: } | |
| 185 | 新增: } | |
| 186 | 新增: list, err := s.loadClaudeAccounts() | |
| 187 | 新增: if err != nil { | |
| 188 | 新增: m.mu.Unlock() | |
| 189 | 新增: return err | |
| 190 | 新增: } | |
| 191 | 新增: owner := s.usageOwner(list, target) | |
| 192 | 新增: if owner == nil { | |
| 193 | 新增: m.mu.Unlock() | |
| 194 | 新增: return errors.New("账号来源或身份已变化,请刷新面板") | |
| 195 | 新增: } | |
| 196 | 新增: if automatic && !claudeUsageDue(owner.UsageCheckedAt) { | |
| 197 | 新增: m.mu.Unlock() | |
| 198 | 新增: return nil | |
| 199 | 新增: } | |
| 200 | 新增: if len(m.usageActive) >= 2 { | |
| 201 | 新增: m.mu.Unlock() | |
| 202 | 新增: return errClaudeUsageBusy | |
| 203 | 新增: } | |
| 204 | 新增: if m.usageActive == nil { | |
| 205 | 新增: m.usageActive = make(map[string]*claudeUsageCall) | |
| 206 | 新增: } | |
| 207 | 新增: call := &claudeUsageCall{done: make(chan struct{})} | |
| 208 | 新增: m.usageActive[target.subject] = call | |
| 209 | 新增: m.mu.Unlock() | |
| 210 | 新增: defer func() { | |
| 211 | 新增: m.mu.Lock() | |
| 212 | 新增: delete(m.usageActive, target.subject) | |
| 213 | 新增: call.err = err | |
| 214 | 新增: close(call.done) | |
| 215 | 新增: m.mu.Unlock() | |
| 216 | 新增: }() | |
| 217 | 新增: probe := m.usageProbe | |
| 218 | 新增: if probe == nil { | |
| 219 | 新增: probe = s.readClaudeGuestUsage | |
| 220 | 新增: } | |
| 221 | 新增: reading, probeErr := probe(ctx, target.guest, target.subject) | |
| 222 | 新增: if epoch.Err() != nil { | |
| 223 | 新增: err = errClaudeAccessLost | |
| 224 | 新增: return err | |
| 225 | 新增: } | |
| 226 | 新增: if parent.Err() != nil { | |
| 227 | 新增: err = parent.Err() | |
| 228 | 新增: return err | |
| 229 | 新增: } | |
| 230 | 新增: if err = s.usageAvailability(); err != nil { | |
| 231 | 新增: return err | |
| 232 | 新增: } | |
| 233 | 新增: m.mu.Lock() | |
| 234 | 新增: defer m.mu.Unlock() | |
| 235 | 新增: if epoch.Err() != nil { | |
| 236 | 新增: err = errClaudeAccessLost | |
| 237 | 新增: return err | |
| 238 | 新增: } | |
| 239 | 新增: if parent.Err() != nil { | |
| 240 | 新增: err = parent.Err() | |
| 241 | 新增: return err | |
| 242 | 新增: } | |
| 243 | 新增: list, err = s.loadClaudeAccounts() | |
| 244 | 新增: if err != nil { | |
| 245 | 新增: return err | |
| 246 | 新增: } | |
| 247 | 新增: owner = s.usageOwner(list, target) | |
| 248 | 新增: if owner == nil { | |
| 249 | 新增: err = errors.New("账号来源或身份已变化,未记录此次额度") | |
| 250 | 新增: return err | |
| 251 | 新增: } | |
| 252 | 新增: now := time.Now() | |
| 253 | 新增: status := reading.UsageStatus | |
| 254 | 新增: switch { | |
| 255 | 新增: case probeErr != nil || status == "error": | |
| 256 | 新增: status = "error" | |
| 257 | 新增: case status == "identity_changed" || reading.subject() != target.subject: | |
| 258 | 新增: status = "identity_changed" | |
| 259 | 新增: owner.Status = "changed" | |
| 260 | 新增: if target.guest == "default" { | |
| 261 | 新增: m.defaultChecked = time.Time{} | |
| 262 | 新增: } | |
| 263 | 新增: case status == "reported" || status == "partial" || status == "cached": | |
| 264 | 新增: owner.mergeQuota(reading.Quota, now) | |
| 265 | 新增: case status == "unavailable" || status == "not_applicable": | |
| 266 | 新增: default: | |
| 267 | 新增: status = "error" | |
| 268 | 新增: } | |
| 269 | 新增: if status != "error" && status != "identity_changed" { | |
| 270 | 新增: owner.Status = "ready" | |
| 271 | 新增: if reading.Plan != "" { | |
| 272 | 新增: owner.Plan = reading.Plan | |
| 273 | 新增: } | |
| 274 | 新增: } | |
| 275 | 新增: owner.UsageStatus, owner.UsageCheckedAt = status, now.Unix() | |
| 276 | 新增: if target.id != "" || list.bySubject(target.subject) == owner { | |
| 277 | 新增: err = s.saveClaudeAccounts(list) | |
| 278 | 新增: } | |
| 279 | 新增: return err | |
| 280 | 新增:} | |
| 281 | 新增: | |
| 282 | 新增:// Under the manager lock, resolve only the original guest source and identity. | |
| 283 | 新增:// A discovered default identity has no disk record until the user joins it. | |
| 284 | 新增:func (s *Server) usageOwner(list claudeAccountList, target claudeUsageTarget) *claudeAccount { | |
| 285 | 新增: if a := list.bySubject(target.subject); a != nil { | |
| 286 | 新增: if a.guestID() == target.guest && (target.id == "" || target.id == a.ID) { | |
| 287 | 新增: return a | |
| 288 | 新增: } | |
| 289 | 新增: return nil | |
| 290 | 新增: } | |
| 291 | 新增: m := &s.claudeAccounts | |
| 292 | 新增: if target.id != "" || target.guest != "default" || m.defaultReading.subject() != target.subject { | |
| 293 | 新增: return nil | |
| 294 | 新增: } | |
| 295 | 新增: return m.detectedUsage[target.subject] | |
| 296 | 新增:} | |
| @@ -0,0 +1,359 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "encoding/json" | |
| 6 | 新增: "errors" | |
| 7 | 新增: "fmt" | |
| 8 | 新增: "net/http" | |
| 9 | 新增: "sync/atomic" | |
| 10 | 新增: "testing" | |
| 11 | 新增: "time" | |
| 12 | 新增:) | |
| 13 | 新增: | |
| 14 | 新增:func usageServer(t *testing.T, n int) (*Server, claudeAccountList) { | |
| 15 | 新增: t.Helper() | |
| 16 | 新增: s := testServer(t) | |
| 17 | 新增: s.ready = true | |
| 18 | 新增: t.Cleanup(func() { s.beginClose(); s.activities.Wait() }) | |
| 19 | 新增: list := claudeAccountList{Accounts: []claudeAccount{}} | |
| 20 | 新增: for i := 1; i <= n; i++ { | |
| 21 | 新增: id := fmt.Sprintf("%024x", i) | |
| 22 | 新增: list.Accounts = append(list.Accounts, claudeAccount{ID: id, Source: "managed", Status: "ready", Email: id + "@example.org", Enabled: true}) | |
| 23 | 新增: } | |
| 24 | 新增: if err := s.saveClaudeAccounts(list); err != nil { | |
| 25 | 新增: t.Fatal(err) | |
| 26 | 新增: } | |
| 27 | 新增: s.claudeAccounts.probe = func(_ context.Context, id string) (claudeGuestSnapshot, error) { | |
| 28 | 新增: if id == "default" { | |
| 29 | 新增: return claudeGuestSnapshot{}, nil | |
| 30 | 新增: } | |
| 31 | 新增: return claudeGuestSnapshot{LoggedIn: true, Email: id + "@example.org"}, nil | |
| 32 | 新增: } | |
| 33 | 新增: return s, list | |
| 34 | 新增:} | |
| 35 | 新增: | |
| 36 | 新增:func TestClaudeUsagePanelAndManualRefreshUseOfficialProbe(t *testing.T) { | |
| 37 | 新增: s, list := usageServer(t, 2) | |
| 38 | 新增: list.Accounts[1].Enabled = false // participation doesn't hide a subscription's quota. | |
| 39 | 新增: if err := s.saveClaudeAccounts(list); err != nil { | |
| 40 | 新增: t.Fatal(err) | |
| 41 | 新增: } | |
| 42 | 新增: var calls atomic.Int32 | |
| 43 | 新增: var mode atomic.Int32 | |
| 44 | 新增: now := time.Now().Unix() | |
| 45 | 新增: s.claudeAccounts.usageProbe = func(_ context.Context, id, subject string) (claudeGuestSnapshot, error) { | |
| 46 | 新增: calls.Add(1) | |
| 47 | 新增: email := id + "@example.org" | |
| 48 | 新增: if claudeIdentityHash(email, "") != subject { | |
| 49 | 新增: t.Errorf("missing or misbound expected identity") | |
| 50 | 新增: } | |
| 51 | 新增: r := claudeGuestSnapshot{LoggedIn: true, Email: email} | |
| 52 | 新增: switch mode.Load() { | |
| 53 | 新增: case 0: | |
| 54 | 新增: r.UsageStatus = "reported" | |
| 55 | 新增: r.Quota = &claudeQuota{ObservedAt: now - 120, FiveHour: &claudeWindow{UsedPercentage: 40, ResetsAt: now + 3600}, SevenDay: &claudeWindow{UsedPercentage: 61, ResetsAt: now + 86400}} | |
| 56 | 新增: case 1: | |
| 57 | 新增: r.UsageStatus = "partial" | |
| 58 | 新增: r.Quota = &claudeQuota{ObservedAt: now - 30, FiveHour: &claudeWindow{UsedPercentage: 45}} | |
| 59 | 新增: case 2: | |
| 60 | 新增: return claudeGuestSnapshot{}, errors.New("simulated guest failure") | |
| 61 | 新增: case 3: | |
| 62 | 新增: r.UsageStatus = "unavailable" | |
| 63 | 新增: case 4: | |
| 64 | 新增: r.UsageStatus = "cached" | |
| 65 | 新增: r.Quota = &claudeQuota{ObservedAt: now - 200, FiveHour: &claudeWindow{UsedPercentage: 7, ResetsAt: now + 3600}} | |
| 66 | 新增: case 6: | |
| 67 | 新增: r.UsageStatus = "not_applicable" | |
| 68 | 新增: case 5: | |
| 69 | 新增: r.UsageStatus = "reported" | |
| 70 | 新增: r.Email = "[email protected]" | |
| 71 | 新增: r.Quota = &claudeQuota{ObservedAt: now, FiveHour: &claudeWindow{UsedPercentage: 99, ResetsAt: now + 999}} | |
| 72 | 新增: } | |
| 73 | 新增: return r, nil | |
| 74 | 新增: } | |
| 75 | 新增: panel := func(method, path, body string) claudePanel { | |
| 76 | 新增: t.Helper() | |
| 77 | 新增: w := request(s, method, path, s.origin, body, true) | |
| 78 | 新增: var v claudePanel | |
| 79 | 新增: if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &v) != nil { | |
| 80 | 新增: t.Fatalf("status %d: %s", w.Code, w.Body) | |
| 81 | 新增: } | |
| 82 | 新增: s.activities.Wait() | |
| 83 | 新增: return v | |
| 84 | 新增: } | |
| 85 | 新增: panel("GET", "/api/claude-accounts", "") | |
| 86 | 新增: panel("GET", "/api/claude-accounts?panel=visible", "") | |
| 87 | 新增: if calls.Load() != 0 { | |
| 88 | 新增: t.Fatal("passive GET ran /usage") | |
| 89 | 新增: } | |
| 90 | 新增: panel("POST", "/api/claude-accounts", `{"action":"usage_panel"}`) | |
| 91 | 新增: if calls.Load() != 2 { | |
| 92 | 新增: t.Fatalf("opening a panel checked %d accounts", calls.Load()) | |
| 93 | 新增: } | |
| 94 | 新增: panel("POST", "/api/claude-accounts", `{"action":"usage_panel"}`) | |
| 95 | 新增: panel("GET", "/api/claude-accounts?panel=visible", "") | |
| 96 | 新增: if calls.Load() != 2 { | |
| 97 | 新增: t.Fatal("reopen/read amplified upstream traffic") | |
| 98 | 新增: } | |
| 99 | 新增: body := `{"action":"refresh","id":"` + list.Accounts[0].ID + `"}` | |
| 100 | 新增: for i, status := range []string{"partial", "error", "unavailable", "cached", "identity_changed", "not_applicable"} { | |
| 101 | 新增: mode.Store(int32(i + 1)) | |
| 102 | 新增: v := panel("POST", "/api/claude-accounts", body) | |
| 103 | 新增: a := v.Accounts[0] | |
| 104 | 新增: if a.UsageStatus != status || a.UsageCheckedAt < now || a.Quota.FiveHour.UsedPercentage != 45 || a.Quota.FiveHour.ObservedAt != now-30 || a.Quota.SevenDay.ObservedAt != now-120 || a.Quota.SevenDay.UsedPercentage != 61 { | |
| 105 | 新增: t.Fatalf("%s replaced the last valid observation: %+v %+v", status, a, a.Quota) | |
| 106 | 新增: } | |
| 107 | 新增: if v.Accounts[1].UsageStatus != "reported" || v.Accounts[1].Quota.FiveHour.UsedPercentage != 40 { | |
| 108 | 新增: t.Fatal("manual refresh affected unrelated account") | |
| 109 | 新增: } | |
| 110 | 新增: } | |
| 111 | 新增:} | |
| 112 | 新增: | |
| 113 | 新增:func TestClaudeUsageUnregisteredDefaultRequiresTheDisplayedIdentity(t *testing.T) { | |
| 114 | 新增: s, _ := usageServer(t, 0) | |
| 115 | 新增: a := claudeGuestSnapshot{LoggedIn: true, Email: "[email protected]", Organization: "team"} | |
| 116 | 新增: current := a | |
| 117 | 新增: s.claudeAccounts.probe = func(context.Context, string) (claudeGuestSnapshot, error) { return current, nil } | |
| 118 | 新增: calls := 0 | |
| 119 | 新增: s.claudeAccounts.usageProbe = func(_ context.Context, id, subject string) (claudeGuestSnapshot, error) { | |
| 120 | 新增: calls++ | |
| 121 | 新增: if id != "default" || subject != a.subject() { | |
| 122 | 新增: t.Error("unexpected default identity") | |
| 123 | 新增: } | |
| 124 | 新增: r := a | |
| 125 | 新增: r.UsageStatus = "partial" | |
| 126 | 新增: r.Quota = &claudeQuota{ObservedAt: time.Now().Unix() - 20, FiveHour: &claudeWindow{UsedPercentage: 58}} | |
| 127 | 新增: return r, nil | |
| 128 | 新增: } | |
| 129 | 新增: wOpen := request(s, "POST", "/api/claude-accounts", s.origin, `{"action":"usage_panel"}`, true) | |
| 130 | 新增: if wOpen.Code != 200 { | |
| 131 | 新增: t.Fatal(wOpen.Code, wOpen.Body) | |
| 132 | 新增: } | |
| 133 | 新增: s.activities.Wait() | |
| 134 | 新增: if calls != 1 { | |
| 135 | 新增: t.Fatal("panel did not proactively check detected, unregistered default") | |
| 136 | 新增: } | |
| 137 | 新增: body := `{"action":"refresh_default","identity":"` + a.subject() + `"}` | |
| 138 | 新增: w := request(s, "POST", "/api/claude-accounts", s.origin, body, true) | |
| 139 | 新增: var v claudePanel | |
| 140 | 新增: if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &v) != nil || len(v.Accounts) != 0 || v.Detected == nil || v.Detected.Quota == nil || v.Detected.Quota.FiveHour.UsedPercentage != 58 || v.Detected.UsageStatus != "partial" { | |
| 141 | 新增: t.Fatal(w.Code, w.Body.String()) | |
| 142 | 新增: } | |
| 143 | 新增: current = claudeGuestSnapshot{LoggedIn: true, Email: "[email protected]"} | |
| 144 | 新增: if w = request(s, "POST", "/api/claude-accounts", s.origin, body, true); w.Code != 409 || calls != 2 { | |
| 145 | 新增: t.Fatal("stale A triggered usage for B", w.Code, calls) | |
| 146 | 新增: } | |
| 147 | 新增: v, _, err := s.claudePanelView(context.Background()) | |
| 148 | 新增: if err != nil || v.Detected == nil || v.Detected.Quota != nil || v.Detected.UsageStatus != "" { | |
| 149 | 新增: t.Fatal("B inherited A's readings", v, err) | |
| 150 | 新增: } | |
| 151 | 新增: current = a | |
| 152 | 新增: if err := s.joinClaudeDefault(context.Background(), a.subject()); err != nil { | |
| 153 | 新增: t.Fatal(err) | |
| 154 | 新增: } | |
| 155 | 新增: saved, _ := s.loadClaudeAccounts() | |
| 156 | 新增: if saved.Accounts[0].Quota == nil || saved.Accounts[0].Quota.FiveHour.UsedPercentage != 58 || saved.Accounts[0].UsageStatus != "partial" { | |
| 157 | 新增: t.Fatal("joining lost this identity's last reading") | |
| 158 | 新增: } | |
| 159 | 新增:} | |
| 160 | 新增: | |
| 161 | 新增:func TestClaudeUsageBatchBoundedAndCancellable(t *testing.T) { | |
| 162 | 新增: for _, how := range []string{"lock", "stop"} { | |
| 163 | 新增: t.Run(how, func(t *testing.T) { | |
| 164 | 新增: s, list := usageServer(t, 40) | |
| 165 | 新增: entered := make(chan string, 40) | |
| 166 | 新增: release := make(chan struct{}) | |
| 167 | 新增: var calls atomic.Int32 | |
| 168 | 新增: s.claudeAccounts.usageProbe = func(ctx context.Context, id, subj string) (claudeGuestSnapshot, error) { | |
| 169 | 新增: calls.Add(1) | |
| 170 | 新增: entered <- id | |
| 171 | 新增: select { | |
| 172 | 新增: case <-ctx.Done(): | |
| 173 | 新增: return claudeGuestSnapshot{}, ctx.Err() | |
| 174 | 新增: case <-release: | |
| 175 | 新增: } | |
| 176 | 新增: return claudeGuestSnapshot{LoggedIn: true, Email: id + "@example.org", UsageStatus: "unavailable"}, nil | |
| 177 | 新增: } | |
| 178 | 新增: open := func() { | |
| 179 | 新增: w := request(s, "POST", "/api/claude-accounts", s.origin, `{"action":"usage_panel"}`, true) | |
| 180 | 新增: if w.Code != 200 { | |
| 181 | 新增: t.Fatal(w.Code, w.Body) | |
| 182 | 新增: } | |
| 183 | 新增: } | |
| 184 | 新增: open() | |
| 185 | 新增: if id := <-entered; id != list.Accounts[0].ID { | |
| 186 | 新增: t.Fatal("wrong account at queue start") | |
| 187 | 新增: } | |
| 188 | 新增: open() | |
| 189 | 新增: ctx, cancel := context.WithTimeout(context.Background(), 25*time.Millisecond) | |
| 190 | 新增: defer cancel() | |
| 191 | 新增: if err := s.refreshClaudeUsage(ctx, claudeAccountInput{Action: "refresh", ID: list.Accounts[0].ID}); !errors.Is(err, context.DeadlineExceeded) { | |
| 192 | 新增: t.Fatal("same-account check did not join existing call", err) | |
| 193 | 新增: } | |
| 194 | 新增: second := make(chan error, 1) | |
| 195 | 新增: go func() { | |
| 196 | 新增: second <- s.refreshClaudeUsage(context.Background(), claudeAccountInput{Action: "refresh", ID: list.Accounts[1].ID}) | |
| 197 | 新增: }() | |
| 198 | 新增: <-entered | |
| 199 | 新增: body := `{"action":"refresh","id":"` + list.Accounts[2].ID + `"}` | |
| 200 | 新增: if w := request(s, "POST", "/api/claude-accounts", s.origin, body, true); w.Code != http.StatusConflict { | |
| 201 | 新增: t.Fatal("per-account probes exceeded global limit", w.Code) | |
| 202 | 新增: } | |
| 203 | 新增: if how == "lock" { | |
| 204 | 新增: s.account.lock() | |
| 205 | 新增: } else { | |
| 206 | 新增: s.mu.Lock() | |
| 207 | 新增: s.ready = false | |
| 208 | 新增: s.mu.Unlock() | |
| 209 | 新增: } | |
| 210 | 新增: close(release) | |
| 211 | 新增: <-second | |
| 212 | 新增: s.activities.Wait() | |
| 213 | 新增: got, _ := s.loadClaudeAccounts() | |
| 214 | 新增: if calls.Load() != 2 { | |
| 215 | 新增: t.Fatalf("after %s, started %d commands", how, calls.Load()) | |
| 216 | 新增: } | |
| 217 | 新增: for _, a := range got.Accounts { | |
| 218 | 新增: if a.UsageCheckedAt != 0 { | |
| 219 | 新增: t.Fatal("wrote late results after", how) | |
| 220 | 新增: } | |
| 221 | 新增: } | |
| 222 | 新增: }) | |
| 223 | 新增: } | |
| 224 | 新增:} | |
| 225 | 新增: | |
| 226 | 新增:func TestClaudeUnknownResetOnlyBlocksWhileFresh(t *testing.T) { | |
| 227 | 新增: now := time.Now() | |
| 228 | 新增: a := claudeAccount{Quota: &claudeQuota{FiveHour: &claudeWindow{UsedPercentage: 100, ObservedAt: now.Unix()}}} | |
| 229 | 新增: if _, ok := a.headroom(now); ok { | |
| 230 | 新增: t.Fatal("ignored exhausted window without a known reset") | |
| 231 | 新增: } | |
| 232 | 新增: if room, ok := a.headroom(now.Add(claudeQuotaFresh + time.Second)); !ok || room != -1 { | |
| 233 | 新增: t.Fatal("treated missing reset as permanent exhaustion", room, ok) | |
| 234 | 新增: } | |
| 235 | 新增:} | |
| 236 | 新增: | |
| 237 | 新增:func TestClaudeUsageHiddenPanelStopsDispatching(t *testing.T) { | |
| 238 | 新增: s, _ := usageServer(t, 4) | |
| 239 | 新增: entered, release := make(chan struct{}), make(chan struct{}) | |
| 240 | 新增: var calls atomic.Int32 | |
| 241 | 新增: s.claudeAccounts.usageProbe = func(_ context.Context, id, subject string) (claudeGuestSnapshot, error) { | |
| 242 | 新增: if calls.Add(1) == 1 { | |
| 243 | 新增: close(entered) | |
| 244 | 新增: <-release | |
| 245 | 新增: } | |
| 246 | 新增: return claudeGuestSnapshot{LoggedIn: true, Email: id + "@example.org", UsageStatus: "unavailable"}, nil | |
| 247 | 新增: } | |
| 248 | 新增: w := request(s, "POST", "/api/claude-accounts", s.origin, `{"action":"usage_panel"}`, true) | |
| 249 | 新增: if w.Code != 200 { | |
| 250 | 新增: t.Fatal(w.Code, w.Body) | |
| 251 | 新增: } | |
| 252 | 新增: <-entered | |
| 253 | 新增: s.claudeAccounts.mu.Lock() | |
| 254 | 新增: s.claudeAccounts.panelUntil = time.Now().Add(-time.Second) | |
| 255 | 新增: s.claudeAccounts.mu.Unlock() | |
| 256 | 新增: // A workspace GET must neither renew the lease nor start another batch. | |
| 257 | 新增: w = request(s, "GET", "/api/claude-accounts", "", "", true) | |
| 258 | 新增: if w.Code != 200 { | |
| 259 | 新增: t.Fatal(w.Code, w.Body) | |
| 260 | 新增: } | |
| 261 | 新增: close(release) | |
| 262 | 新增: s.activities.Wait() | |
| 263 | 新增: if calls.Load() != 1 { | |
| 264 | 新增: t.Fatal("hidden panel kept issuing upstream queries", calls.Load()) | |
| 265 | 新增: } | |
| 266 | 新增:} | |
| 267 | 新增: | |
| 268 | 新增:func TestClaudeUsageKeepsExpiredHistoricalWindowsForBothSources(t *testing.T) { | |
| 269 | 新增: s, list := usageServer(t, 1) | |
| 270 | 新增: now := time.Now() | |
| 271 | 新增: history := &claudeQuota{ObservedAt: now.Add(-time.Hour).Unix(), FiveHour: &claudeWindow{UsedPercentage: 100, ResetsAt: now.Add(-time.Minute).Unix()}, SevenDay: &claudeWindow{UsedPercentage: 63, ResetsAt: now.Add(time.Hour).Unix()}} | |
| 272 | 新增: list.Accounts[0].mergeQuota(history, now) | |
| 273 | 新增: if err := s.saveClaudeAccounts(list); err != nil { | |
| 274 | 新增: t.Fatal(err) | |
| 275 | 新增: } | |
| 276 | 新增: candidate := claudeGuestSnapshot{LoggedIn: true, Email: "[email protected]", Quota: history} | |
| 277 | 新增: // Only a passive CLI snapshot has ever reported this unregistered account. | |
| 278 | 新增: s.claudeAccounts.probe = func(_ context.Context, id string) (claudeGuestSnapshot, error) { | |
| 279 | 新增: if id == "default" { | |
| 280 | 新增: return candidate, nil | |
| 281 | 新增: } | |
| 282 | 新增: return claudeGuestSnapshot{LoggedIn: true, Email: list.find(id).Email}, nil | |
| 283 | 新增: } | |
| 284 | 新增: if _, _, err := s.claudePanelView(context.Background()); err != nil { | |
| 285 | 新增: t.Fatal(err) | |
| 286 | 新增: } | |
| 287 | 新增: candidate.Quota = nil | |
| 288 | 新增: s.claudeAccounts.usageProbe = func(_ context.Context, id, expected string) (claudeGuestSnapshot, error) { | |
| 289 | 新增: if id == "default" { | |
| 290 | 新增: return claudeGuestSnapshot{LoggedIn: true, Email: candidate.Email, UsageStatus: "unavailable"}, nil | |
| 291 | 新增: } | |
| 292 | 新增: return claudeGuestSnapshot{LoggedIn: true, Email: list.find(id).Email, UsageStatus: "unavailable"}, nil | |
| 293 | 新增: } | |
| 294 | 新增: for _, body := range []string{`{"action":"refresh","id":"` + list.Accounts[0].ID + `"}`, `{"action":"refresh_default","identity":"` + candidate.subject() + `"}`} { | |
| 295 | 新增: w := request(s, "POST", "/api/claude-accounts", s.origin, body, true) | |
| 296 | 新增: if w.Code != 200 { | |
| 297 | 新增: t.Fatal(w.Code, w.Body) | |
| 298 | 新增: } | |
| 299 | 新增: s.activities.Wait() | |
| 300 | 新增: } | |
| 301 | 新增: view, _, err := s.claudePanelView(context.Background()) | |
| 302 | 新增: if err != nil || view.Detected == nil { | |
| 303 | 新增: t.Fatal(view, err) | |
| 304 | 新增: } | |
| 305 | 新增: for _, q := range []*claudeQuota{view.Accounts[0].Quota, view.Detected.Quota} { | |
| 306 | 新增: if q == nil || q.FiveHour == nil || q.SevenDay == nil || q.FiveHour.UsedPercentage != 100 || q.FiveHour.ObservedAt != history.ObservedAt || q.SevenDay.ObservedAt != history.ObservedAt { | |
| 307 | 新增: t.Fatal("missing read discarded or retimestamped historical quota", q) | |
| 308 | 新增: } | |
| 309 | 新增: if _, eligible := (claudeAccount{Quota: q}).headroom(now); !eligible { | |
| 310 | 新增: t.Fatal("closed 5h window still blocked allocation") | |
| 311 | 新增: } | |
| 312 | 新增: } | |
| 313 | 新增:} | |
| 314 | 新增: | |
| 315 | 新增:func TestClaudeUsageFailedBatchOnlyRetriesOnOpeningAfterDebounce(t *testing.T) { | |
| 316 | 新增: s, list := usageServer(t, 1) | |
| 317 | 新增: var calls atomic.Int32 | |
| 318 | 新增: s.claudeAccounts.usageProbe = func(context.Context, string, string) (claudeGuestSnapshot, error) { | |
| 319 | 新增: calls.Add(1) | |
| 320 | 新增: return claudeGuestSnapshot{}, errors.New("unavailable") | |
| 321 | 新增: } | |
| 322 | 新增: get := func() claudePanel { | |
| 323 | 新增: w := request(s, "GET", "/api/claude-accounts?panel=visible", "", "", true) | |
| 324 | 新增: s.activities.Wait() | |
| 325 | 新增: var v claudePanel | |
| 326 | 新增: if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &v) != nil { | |
| 327 | 新增: t.Fatal(w.Code, w.Body) | |
| 328 | 新增: } | |
| 329 | 新增: return v | |
| 330 | 新增: } | |
| 331 | 新增: open := func() claudePanel { | |
| 332 | 新增: w := request(s, "POST", "/api/claude-accounts", s.origin, `{"action":"usage_panel"}`, true) | |
| 333 | 新增: s.activities.Wait() | |
| 334 | 新增: var v claudePanel | |
| 335 | 新增: if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &v) != nil { | |
| 336 | 新增: t.Fatal(w.Code, w.Body) | |
| 337 | 新增: } | |
| 338 | 新增: return v | |
| 339 | 新增: } | |
| 340 | 新增: open() | |
| 341 | 新增: if v := get(); v.UsagePanelRunning || v.Accounts[0].UsageStatus != "error" || v.Accounts[0].UsageChecking { | |
| 342 | 新增: t.Fatal("failed batch never ended", v) | |
| 343 | 新增: } | |
| 344 | 新增: if v := open(); v.UsagePanelRunning || calls.Load() != 1 { | |
| 345 | 新增: t.Fatal("recent failure started an empty batch") | |
| 346 | 新增: } | |
| 347 | 新增: list, _ = s.loadClaudeAccounts() | |
| 348 | 新增: list.Accounts[0].UsageCheckedAt = time.Now().Add(-61 * time.Second).Unix() | |
| 349 | 新增: if err := s.saveClaudeAccounts(list); err != nil { | |
| 350 | 新增: t.Fatal(err) | |
| 351 | 新增: } | |
| 352 | 新增: if v := get(); v.UsagePanelRunning || calls.Load() != 1 { | |
| 353 | 新增: t.Fatal("ordinary visible poll restarted an expired failed batch") | |
| 354 | 新增: } | |
| 355 | 新增: open() | |
| 356 | 新增: if calls.Load() != 2 || get().UsagePanelRunning { | |
| 357 | 新增: t.Fatal("did not retry on the next real panel open") | |
| 358 | 新增: } | |
| 359 | 新增:} | |
| @@ -1,6 +1,7 @@ | ||
| 1 | 1 | package workbench |
| 2 | 2 | |
| 3 | 3 | import ( |
| 4 | 新增: "context" | |
| 4 | 5 | "os" |
| 5 | 6 | "os/exec" |
| 6 | 7 | "path/filepath" |
| @@ -66,3 +67,99 @@ func TestClaudeTerminalPreferenceValidationAndPersistence(t *testing.T) { | ||
| 66 | 67 | } |
| 67 | 68 | } |
| 68 | 69 | } |
| 70 | 新增: | |
| 71 | 新增:func TestClaudeLoginOutputNeverEntersReconnectHistory(t *testing.T) { | |
| 72 | 新增: var manager terminalManager | |
| 73 | 新增: t.Cleanup(manager.close) | |
| 74 | 新增: selection := claudeSelection{ID: "aaaaaaaaaaaaaaaaaaaaaaaa", GuestID: "aaaaaaaaaaaaaaaaaaaaaaaa"} | |
| 75 | 新增: session, err := manager.startSession(terminalChildCommand("echo"), "/project", "claude-login", selection, nil) | |
| 76 | 新增: if err != nil { | |
| 77 | 新增: t.Fatal(err) | |
| 78 | 新增: } | |
| 79 | 新增: view := session.subscribe() | |
| 80 | 新增: defer view.Close() | |
| 81 | 新增: if err = session.enqueueInput(context.Background(), terminalInputLine("private-login-code")); err != nil { | |
| 82 | 新增: t.Fatal(err) | |
| 83 | 新增: } | |
| 84 | 新增: readTerminalUntil(t, view, "child:private-login-code") | |
| 85 | 新增: observation := session.subscribe() | |
| 86 | 新增: defer observation.Close() | |
| 87 | 新增: if strings.Contains(string(observation.History), "private-login-code") || len(session.history) != 0 { | |
| 88 | 新增: t.Fatal("login output was retained for reconnect") | |
| 89 | 新增: } | |
| 90 | 新增: if session.summary()["claude_account_id"] != selection.ID || session.summary()["claude_account_source"] != "managed" { | |
| 91 | 新增: t.Fatal("terminal lost its original account binding") | |
| 92 | 新增: } | |
| 93 | 新增: if again, err := manager.existingClaudeLogin(session.claudeAccountID, true); err != nil || again != session { | |
| 94 | 新增: t.Fatal("repeated login did not reattach to the same PTY") | |
| 95 | 新增: } | |
| 96 | 新增: if _, err := manager.existingClaudeLogin(session.claudeAccountID, false); err == nil { | |
| 97 | 新增: t.Fatal("started a Claude terminal while its profile is changing identity") | |
| 98 | 新增: } | |
| 99 | 新增:} | |
| 100 | 新增: | |
| 101 | 新增:func TestManagedTerminalPreservesTheSelectedProfileInTheGuestShell(t *testing.T) { | |
| 102 | 新增: if runtime.GOOS == "windows" { | |
| 103 | 新增: t.Skip("guest Bash integration runs on Unix") | |
| 104 | 新增: } | |
| 105 | 新增: home := t.TempDir() | |
| 106 | 新增: const managed = "111111111111111111111111" | |
| 107 | 新增: for _, tc := range []struct{ guestID, want string }{ | |
| 108 | 新增: {"default", home + "/custom-config"}, | |
| 109 | 新增: {managed, home + "/.local/share/cage/claude-accounts/" + managed + "/config"}, | |
| 110 | 新增: } { | |
| 111 | 新增: work := t.TempDir() | |
| 112 | 新增: cmd := exec.Command("bash", "-c", managedClaudeTerminalScript(work, `printf '%s' "$CLAUDE_CONFIG_DIR/$CAGE_CLAUDE_ACCOUNT_ID/$CAGE_CLAUDE_SUBJECT" > observed`, tc.guestID, "expected", false)) | |
| 113 | 新增: cmd.Env = []string{"HOME=" + home, "PATH=" + os.Getenv("PATH"), "CLAUDE_CONFIG_DIR=" + home + "/custom-config"} | |
| 114 | 新增: cmd.Stdin = strings.NewReader("exit\n") | |
| 115 | 新增: if b, err := cmd.CombinedOutput(); err != nil { | |
| 116 | 新增: t.Fatalf("guest launch: %v: %s", err, b) | |
| 117 | 新增: } | |
| 118 | 新增: b, err := os.ReadFile(filepath.Join(work, "observed")) | |
| 119 | 新增: if err != nil || string(b) != tc.want+"/"+tc.guestID+"/expected" { | |
| 120 | 新增: t.Fatalf("profile override or subject lost: %s, %v", b, err) | |
| 121 | 新增: } | |
| 122 | 新增: } | |
| 123 | 新增:} | |
| 124 | 新增: | |
| 125 | 新增:func TestClaudeTerminalSourceSurvivesAdoptingAnIndependentProfile(t *testing.T) { | |
| 126 | 新增: var manager terminalManager | |
| 127 | 新增: t.Cleanup(manager.close) | |
| 128 | 新增: account := claudeSelection{ID: "aaaaaaaaaaaaaaaaaaaaaaaa", GuestID: "default"} | |
| 129 | 新增: original, err := manager.startSession(terminalChildCommand("echo"), "/project", "claude", account, nil) | |
| 130 | 新增: if err != nil { | |
| 131 | 新增: t.Fatal(err) | |
| 132 | 新增: } | |
| 133 | 新增: account.GuestID = "bbbbbbbbbbbbbbbbbbbbbbbb" | |
| 134 | 新增: adopted, err := manager.startSession(terminalChildCommand("echo"), "/project", "claude", account, nil) | |
| 135 | 新增: if err != nil { | |
| 136 | 新增: t.Fatal(err) | |
| 137 | 新增: } | |
| 138 | 新增: if original.summary()["claude_account_source"] != "default" || adopted.summary()["claude_account_source"] != "managed" || | |
| 139 | 新增: original.summary()["claude_account_id"] != adopted.summary()["claude_account_id"] { | |
| 140 | 新增: t.Fatal("adoption changed an existing terminal's account source") | |
| 141 | 新增: } | |
| 142 | 新增:} | |
| 143 | 新增: | |
| 144 | 新增:func TestDefaultClaudeProbeUsesRegularLoginEnvironment(t *testing.T) { | |
| 145 | 新增: if runtime.GOOS == "windows" { | |
| 146 | 新增: t.Skip("guest Bash integration runs on Unix") | |
| 147 | 新增: } | |
| 148 | 新增: home := t.TempDir() | |
| 149 | 新增: profile := "echo startup-banner\nexport CAGE_FIXTURE_AUTH=shell-route\n" | |
| 150 | 新增: if err := os.WriteFile(filepath.Join(home, ".bash_profile"), []byte(profile), 0600); err != nil { | |
| 151 | 新增: t.Fatal(err) | |
| 152 | 新增: } | |
| 153 | 新增: if err := os.WriteFile(filepath.Join(home, "show-environment"), []byte("#!/bin/sh\nprintf '%s' \"$CAGE_FIXTURE_AUTH|$PWD|$1|$2\"\n"), 0700); err != nil { | |
| 154 | 新增: t.Fatal(err) | |
| 155 | 新增: } | |
| 156 | 新增: script := strings.Replace(claudeSnapshotCommand("default"), "/usr/local/bin/cage-claude-account", `"$HOME/show-environment"`, 1) | |
| 157 | 新增: cmd := exec.Command("bash", "-c", script) | |
| 158 | 新增: cmd.Dir = t.TempDir() | |
| 159 | 新增: cmd.Env = []string{"HOME=" + home, "PATH=" + os.Getenv("PATH")} | |
| 160 | 新增: b, err := cmd.Output() | |
| 161 | 新增: realHome, _ := filepath.EvalSymlinks(home) | |
| 162 | 新增: if err != nil || (string(b) != "shell-route|"+home+"|snapshot|default" && string(b) != "shell-route|"+realHome+"|snapshot|default") { | |
| 163 | 新增: t.Fatalf("login env or guest JSON stream changed: %q, %v", b, err) | |
| 164 | 新增: } | |
| 165 | 新增:} | |
| @@ -46,6 +46,7 @@ type Server struct { | ||
| 46 | 46 | guestUpdateError string |
| 47 | 47 | closing bool |
| 48 | 48 | shutdown func() |
| 49 | 新增: claudeAccounts claudeAccountManager | |
| 49 | 50 | favoritesMu sync.Mutex |
| 50 | 51 | diagnosticMu sync.Mutex |
| 51 | 52 | diagnosticRateMu sync.Mutex |
| @@ -222,6 +223,11 @@ func (s *Server) handler() http.Handler { | ||
| 222 | 223 | mux.HandleFunc("GET /api/diagnostics", s.diagnosticStatus) |
| 223 | 224 | mux.HandleFunc("POST /api/diagnostics/events", s.diagnosticEvent) |
| 224 | 225 | mux.HandleFunc("GET /api/diagnostics/export", s.diagnosticExport) |
| 226 | 新增: mux.HandleFunc("GET /api/claude-accounts", s.listClaudeAccounts) | |
| 227 | 新增: mux.HandleFunc("POST /api/claude-accounts", s.mutateClaudeAccounts) | |
| 228 | 新增: mux.HandleFunc("GET /api/vault", s.vaultList) | |
| 229 | 新增: mux.HandleFunc("POST /api/vault", s.vaultMutation) | |
| 230 | 新增: mux.HandleFunc("POST /api/vault/browser", s.vaultBrowser) | |
| 225 | 231 | mux.HandleFunc("GET /api/account", s.accountStatus) |
| 226 | 232 | mux.HandleFunc("POST /api/account/{action}", s.accountAction) |
| 227 | 233 | mux.HandleFunc("GET /api/settings", s.getSettings) |
| @@ -1,10 +1,14 @@ | ||
| 1 | 1 | package workbench |
| 2 | 2 | |
| 3 | 3 | import ( |
| 4 | 新增: "context" | |
| 5 | 新增: "encoding/hex" | |
| 6 | 新增: "encoding/json" | |
| 4 | 7 | "errors" |
| 5 | 8 | "fmt" |
| 6 | 9 | "os/exec" |
| 7 | 10 | "sync" |
| 11 | 新增: "time" | |
| 8 | 12 | |
| 9 | 13 | "al.essio.dev/pkg/shellescape" |
| 10 | 14 | "github.com/sylvinus/agent-vm/internal/vmname" |
| @@ -19,8 +23,9 @@ var ( | ||
| 19 | 23 | ) |
| 20 | 24 | |
| 21 | 25 | type terminalRequest struct { |
| 22 | 删除: Workspace string `json:"workspace"` | |
| 23 | 删除: Kind string `json:"kind"` | |
| 26 | 新增: Workspace string `json:"workspace"` | |
| 27 | 新增: Kind string `json:"kind"` | |
| 28 | 新增: ClaudeAccountID string `json:"claude_account_id"` | |
| 24 | 29 | } |
| 25 | 30 | |
| 26 | 31 | // terminalManager owns host PTYs; subscriptions only borrow their output. The |
| @@ -34,7 +39,7 @@ type terminalManager struct { | ||
| 34 | 39 | workers sync.WaitGroup |
| 35 | 40 | } |
| 36 | 41 | |
| 37 | 删除:func (m *terminalManager) start(cmd *exec.Cmd, workspace, kind string) (*terminalSession, error) { | |
| 42 | 新增:func (m *terminalManager) startSession(cmd *exec.Cmd, workspace, kind string, selection claudeSelection, finished func()) (*terminalSession, error) { | |
| 38 | 43 | m.mu.Lock() |
| 39 | 44 | defer m.mu.Unlock() |
| 40 | 45 | if err := m.admissionErrorLocked(); err != nil { |
| @@ -48,15 +53,29 @@ func (m *terminalManager) start(cmd *exec.Cmd, workspace, kind string) (*termina | ||
| 48 | 53 | title := fmt.Sprintf("终端 %d", m.sequence) |
| 49 | 54 | if kind == "claude" { |
| 50 | 55 | title = fmt.Sprintf("Claude %d", m.sequence) |
| 56 | 新增: } else if kind == "claude-login" { | |
| 57 | 新增: title = "Claude 账号登录" | |
| 51 | 58 | } |
| 52 | 59 | session := newTerminalSession(file) |
| 53 | 60 | session.id, session.title, session.workspace, session.cmd = randomToken()[:16], title, workspace, cmd |
| 61 | 新增: session.kind, session.claudeAccountID = kind, selection.ID | |
| 62 | 新增: if selection.GuestID == "default" { | |
| 63 | 新增: session.claudeAccountSource = "default" | |
| 64 | 新增: } else if selection.ID != "" { | |
| 65 | 新增: session.claudeAccountSource = "managed" | |
| 66 | 新增: } | |
| 54 | 67 | if m.sessions == nil { |
| 55 | 68 | m.sessions = make(map[string]*terminalSession) |
| 56 | 69 | } |
| 57 | 70 | m.sessions[session.id] = session |
| 58 | 71 | m.workers.Add(1) |
| 59 | 删除: go func() { defer m.workers.Done(); session.run() }() | |
| 72 | 新增: go func() { | |
| 73 | 新增: defer m.workers.Done() | |
| 74 | 新增: session.run() | |
| 75 | 新增: if finished != nil { | |
| 76 | 新增: finished() | |
| 77 | 新增: } | |
| 78 | 新增: }() | |
| 60 | 79 | return session, nil |
| 61 | 80 | } |
| 62 | 81 | |
| @@ -113,13 +132,40 @@ func (m *terminalManager) get(id string) *terminalSession { | ||
| 113 | 132 | return m.sessions[id] |
| 114 | 133 | } |
| 115 | 134 | |
| 135 | 新增:// Reattaching a repeated login request must not create a second OAuth flow. | |
| 136 | 新增:// A profile can serve many normal terminals or a single exclusive login. | |
| 137 | 新增:func (m *terminalManager) existingClaudeLogin(id string, login bool) (*terminalSession, error) { | |
| 138 | 新增: m.mu.Lock() | |
| 139 | 新增: defer m.mu.Unlock() | |
| 140 | 新增: for _, session := range m.sessions { | |
| 141 | 新增: if session.claudeAccountID != id { | |
| 142 | 新增: continue | |
| 143 | 新增: } | |
| 144 | 新增: select { | |
| 145 | 新增: case <-session.done: | |
| 146 | 新增: continue | |
| 147 | 新增: default: | |
| 148 | 新增: } | |
| 149 | 新增: if session.kind == "claude-login" && login { | |
| 150 | 新增: return session, nil | |
| 151 | 新增: } | |
| 152 | 新增: if login || session.kind == "claude-login" { | |
| 153 | 新增: return nil, errors.New("请先结束此账号的登录或运行中的终端,再更改登录身份") | |
| 154 | 新增: } | |
| 155 | 新增: } | |
| 156 | 新增: return nil, nil | |
| 157 | 新增:} | |
| 158 | 新增: | |
| 116 | 159 | func (m *terminalManager) remove(id string) { |
| 117 | 160 | m.mu.Lock() |
| 118 | 161 | session := m.sessions[id] |
| 119 | 删除: delete(m.sessions, id) | |
| 120 | 162 | m.mu.Unlock() |
| 121 | 163 | if session != nil { |
| 164 | 新增: // Keep its Claude account reserved until the old PTY has exited. | |
| 122 | 165 | session.close() |
| 166 | 新增: m.mu.Lock() | |
| 167 | 新增: delete(m.sessions, id) | |
| 168 | 新增: m.mu.Unlock() | |
| 123 | 169 | } |
| 124 | 170 | } |
| 125 | 171 | |
| @@ -143,8 +189,7 @@ func (m *terminalManager) close() { | ||
| 143 | 189 | m.closed = true |
| 144 | 190 | m.mu.Unlock() |
| 145 | 191 | m.closeAll() |
| 146 | 删除: // A remove may already have taken a session out of the map while its | |
| 147 | 删除: // process is still exiting. Admission is sealed, so waiting is safe. | |
| 192 | 新增: // The final login-status observation also belongs to the session worker. | |
| 148 | 193 | m.workers.Wait() |
| 149 | 194 | } |
| 150 | 195 | |
| @@ -155,6 +200,7 @@ func (s *Server) createTerminal(input terminalRequest) (*terminalSession, error) | ||
| 155 | 200 | defer s.op.Unlock() |
| 156 | 201 | s.mu.Lock() |
| 157 | 202 | closing := s.closing |
| 203 | 新增: componentUpdate := s.guestUpdateRequired | |
| 158 | 204 | command := claudeTerminalCommand(s.preferences) |
| 159 | 205 | s.mu.Unlock() |
| 160 | 206 | if closing { |
| @@ -165,20 +211,131 @@ func (s *Server) createTerminal(input terminalRequest) (*terminalSession, error) | ||
| 165 | 211 | } |
| 166 | 212 | // Reject a full manager before opening project shares. start checks again |
| 167 | 213 | // atomically with process publication because shutdown can race this work. |
| 168 | 删除: if err := s.terminals.canStart(); err != nil { | |
| 169 | 删除: return nil, err | |
| 214 | 新增: if input.Kind != "claude-login" { | |
| 215 | 新增: if err := s.terminals.canStart(); err != nil { | |
| 216 | 新增: return nil, err | |
| 217 | 新增: } | |
| 170 | 218 | } |
| 171 | 删除: if input.Kind != "" && input.Kind != "shell" && input.Kind != "claude" { | |
| 219 | 新增: if input.Kind != "" && input.Kind != "shell" && input.Kind != "claude" && input.Kind != "claude-login" { | |
| 172 | 220 | return nil, errors.New("终端类型无效") |
| 173 | 221 | } |
| 174 | 删除: workspace, err := s.connectProject(input.Workspace, false) | |
| 175 | 删除: if err != nil { | |
| 176 | 删除: return nil, err | |
| 222 | 新增: managed := input.Kind == "claude" || input.Kind == "claude-login" | |
| 223 | 新增: if !managed && input.ClaudeAccountID != "" { | |
| 224 | 新增: return nil, errors.New("普通终端不能指定 Claude 账号") | |
| 225 | 新增: } | |
| 226 | 新增: // Login works even when the last project is disconnected or has moved. | |
| 227 | 新增: // It always runs from the guest home, without loading project settings. | |
| 228 | 新增: workspace := s.workspace() | |
| 229 | 新增: var err error | |
| 230 | 新增: if input.Kind != "claude-login" { | |
| 231 | 新增: workspace, err = s.connectProject(input.Workspace, false) | |
| 232 | 新增: if err != nil { | |
| 233 | 新增: return nil, err | |
| 234 | 新增: } | |
| 177 | 235 | } |
| 178 | 236 | name := vmname.Name(s.environmentDir()) |
| 179 | 237 | script := terminalScript(guestPath(workspace), input.Kind, command) |
| 238 | 新增: var selection claudeSelection | |
| 239 | 新增: var finished func() | |
| 240 | 新增: if managed { | |
| 241 | 新增: login := input.Kind == "claude-login" | |
| 242 | 新增: selection, err = s.selectClaudeAccount(input.ClaudeAccountID, login, workspace) | |
| 243 | 新增: if err != nil { | |
| 244 | 新增: return nil, err | |
| 245 | 新增: } | |
| 246 | 新增: if selection.ID != "" { | |
| 247 | 新增: if componentUpdate { | |
| 248 | 新增: return nil, errGuestUpdateRequired | |
| 249 | 新增: } | |
| 250 | 新增: if !validClaudeID(selection.ID) || !validClaudeGuestID(selection.GuestID) || (login && selection.GuestID == "default") { | |
| 251 | 新增: return nil, errors.New("Claude 账号 ID 无效") | |
| 252 | 新增: } | |
| 253 | 新增: if existing, conflict := s.terminals.existingClaudeLogin(selection.ID, login); existing != nil || conflict != nil { | |
| 254 | 新增: return existing, conflict | |
| 255 | 新增: } | |
| 256 | 新增: if !login && selection.Subject == "" { | |
| 257 | 新增: return nil, errors.New("Claude 账号状态已变化,请重试") | |
| 258 | 新增: } | |
| 259 | 新增: script = managedClaudeTerminalScript(guestPath(workspace), command, selection.GuestID, selection.Subject, login) | |
| 260 | 新增: if login { | |
| 261 | 新增: finished = func() { | |
| 262 | 新增: ctx, cancel := context.WithTimeout(s.lifetimeContext(), 12*time.Second) | |
| 263 | 新增: defer cancel() | |
| 264 | 新增: _ = s.confirmClaudeLogin(ctx, selection.ID) | |
| 265 | 新增: } | |
| 266 | 新增: } | |
| 267 | 新增: } | |
| 268 | 新增: } | |
| 180 | 269 | cmd := s.sshCommand(s.lifetimeContext(), "-tt", "lima-"+name, "--", script) |
| 181 | 删除: return s.terminals.start(cmd, workspace, input.Kind) | |
| 270 | 新增: session, err := s.terminals.startSession(cmd, workspace, input.Kind, selection, finished) | |
| 271 | 新增: if err == nil && input.Kind == "claude" && selection.ID != "" { | |
| 272 | 新增: s.noteClaudeSelection(selection.ID, workspace) | |
| 273 | 新增: } | |
| 274 | 新增: return session, err | |
| 275 | 新增:} | |
| 276 | 新增: | |
| 277 | 新增:func validClaudeGuestID(id string) bool { return id == "default" || validClaudeID(id) } | |
| 278 | 新增: | |
| 279 | 新增:func (s *Server) readClaudeGuestSnapshot(ctx context.Context, id string) (claudeGuestSnapshot, error) { | |
| 280 | 新增: return s.readClaudeGuestReport(ctx, id, claudeSnapshotCommand(id)) | |
| 281 | 新增:} | |
| 282 | 新增: | |
| 283 | 新增:func (s *Server) readClaudeGuestUsage(ctx context.Context, id, subject string) (claudeGuestSnapshot, error) { | |
| 284 | 新增: if _, err := hex.DecodeString(subject); err != nil || len(subject) != 64 { | |
| 285 | 新增: return claudeGuestSnapshot{}, errors.New("Claude 账号身份无效") | |
| 286 | 新增: } | |
| 287 | 新增: return s.readClaudeGuestReport(ctx, id, claudeGuestReportCommand(id, subject)) | |
| 288 | 新增:} | |
| 289 | 新增: | |
| 290 | 新增:func (s *Server) readClaudeGuestReport(ctx context.Context, id, command string) (claudeGuestSnapshot, error) { | |
| 291 | 新增: var snapshot claudeGuestSnapshot | |
| 292 | 新增: if !validClaudeGuestID(id) { | |
| 293 | 新增: return snapshot, errors.New("Claude 账号 ID 无效") | |
| 294 | 新增: } | |
| 295 | 新增: data, err := s.guest(ctx, command) | |
| 296 | 新增: if err != nil || json.Unmarshal(data, &snapshot) != nil { | |
| 297 | 新增: return snapshot, errors.New("无法读取账号状态,请确认环境已启动并同步环境组件") | |
| 298 | 新增: } | |
| 299 | 新增: return snapshot, nil | |
| 300 | 新增:} | |
| 301 | 新增: | |
| 302 | 新增:func claudeSnapshotCommand(id string) string { | |
| 303 | 新增: return claudeGuestReportCommand(id, "") | |
| 304 | 新增:} | |
| 305 | 新增: | |
| 306 | 新增:func claudeGuestReportCommand(id, subject string) string { | |
| 307 | 新增: command := "exec /usr/local/bin/cage-claude-account snapshot " + id | |
| 308 | 新增: if subject != "" { | |
| 309 | 新增: command = "exec /usr/local/bin/cage-claude-account usage " + id + " " + shellescape.Quote(subject) | |
| 310 | 新增: } | |
| 311 | 新增: if id == "default" { | |
| 312 | 新增: // Use the same login shell a regular terminal opens, including its | |
| 313 | 新增: // configured API/provider environment. Isolate startup banners from | |
| 314 | 新增: // the JSON output and keep the probe outside every shared project. | |
| 315 | 新增: command = `set -o pipefail; cd "$HOME" && env TERM=xterm-256color COLORTERM=truecolor CAGE_WORKBENCH=1 /bin/bash -lic ` + | |
| 316 | 新增: shellescape.Quote(`printf '\nCAGE_CLAUDE_SNAPSHOT '; `+command) + | |
| 317 | 新增: ` | sed -n 's/^CAGE_CLAUDE_SNAPSHOT //p'` | |
| 318 | 新增: } | |
| 319 | 新增: return command | |
| 320 | 新增:} | |
| 321 | 新增: | |
| 322 | 新增:func managedClaudeTerminalScript(workspace, command, accountID, subject string, login bool) string { | |
| 323 | 新增: if login { | |
| 324 | 新增: return "cd \"$HOME\" && exec /usr/local/bin/cage-claude-account login " + shellescape.Quote(accountID) | |
| 325 | 新增: } | |
| 326 | 新增: // The interactive shell still interprets the user's saved command and | |
| 327 | 新增: // remains useful when Claude exits. The shim scopes subsequent invocations | |
| 328 | 新增: // in this shell to the same official CLI profile. | |
| 329 | 新增: env := `export CAGE_CLAUDE_ACCOUNT_ID=` + shellescape.Quote(accountID) + | |
| 330 | 新增: ` CAGE_CLAUDE_SUBJECT=` + shellescape.Quote(subject) + "; " | |
| 331 | 新增: if accountID != "default" { | |
| 332 | 新增: env += `export CLAUDE_CONFIG_DIR="$HOME/.local/share/cage/claude-accounts/$CAGE_CLAUDE_ACCOUNT_ID/config"; ` | |
| 333 | 新增: } | |
| 334 | 新增: env += `export PATH="/usr/local/lib/cage-claude-bin:$PATH"; ` | |
| 335 | 新增: body := env + `eval "$CAGE_TERMINAL_COMMAND"; unset CAGE_TERMINAL_COMMAND; exec bash -i` | |
| 336 | 新增: return "cd " + shellescape.Quote(workspace) + | |
| 337 | 新增: " && exec env TERM=xterm-256color COLORTERM=truecolor CAGE_WORKBENCH=1 CAGE_TERMINAL_COMMAND=" + | |
| 338 | 新增: shellescape.Quote(command) + " bash -lic " + shellescape.Quote(body) | |
| 182 | 339 | } |
| 183 | 340 | |
| 184 | 341 | // The saved command is interpreted only by the guest's interactive shell. |
| @@ -15,6 +15,10 @@ import ( | ||
| 15 | 15 | "time" |
| 16 | 16 | ) |
| 17 | 17 | |
| 18 | 新增:func (m *terminalManager) start(cmd *exec.Cmd, workspace, kind string) (*terminalSession, error) { | |
| 19 | 新增: return m.startSession(cmd, workspace, kind, claudeSelection{}, nil) | |
| 20 | 新增:} | |
| 21 | 新增: | |
| 18 | 22 | // This subprocess uses the same platform PTY implementation as workbench SSH. |
| 19 | 23 | func TestTerminalServiceChild(t *testing.T) { |
| 20 | 24 | if os.Getenv("CAGE_TERMINAL_SERVICE_CHILD") != "1" { |
| @@ -19,18 +19,20 @@ type terminalPTY interface { | ||
| 19 | 19 | } |
| 20 | 20 | |
| 21 | 21 | type terminalSession struct { |
| 22 | 删除: mu sync.Mutex | |
| 23 | 删除: id, title string | |
| 24 | 删除: workspace string | |
| 25 | 删除: cmd *exec.Cmd | |
| 26 | 删除: file terminalPTY | |
| 27 | 删除: history []byte | |
| 28 | 删除: closed bool | |
| 29 | 删除: clients map[chan []byte]bool | |
| 30 | 删除: done chan struct{} | |
| 31 | 删除: inputs chan string | |
| 32 | 删除: stopping chan struct{} | |
| 33 | 删除: closeOnce sync.Once | |
| 22 | 新增: mu sync.Mutex | |
| 23 | 新增: id, title string | |
| 24 | 新增: workspace string | |
| 25 | 新增: kind, claudeAccountID string | |
| 26 | 新增: claudeAccountSource string | |
| 27 | 新增: cmd *exec.Cmd | |
| 28 | 新增: file terminalPTY | |
| 29 | 新增: history []byte | |
| 30 | 新增: closed bool | |
| 31 | 新增: clients map[chan []byte]bool | |
| 32 | 新增: done chan struct{} | |
| 33 | 新增: inputs chan string | |
| 34 | 新增: stopping chan struct{} | |
| 35 | 新增: closeOnce sync.Once | |
| 34 | 36 | } |
| 35 | 37 | |
| 36 | 38 | func newTerminalSession(file terminalPTY) *terminalSession { |
| @@ -40,7 +42,17 @@ func newTerminalSession(file terminalPTY) *terminalSession { | ||
| 40 | 42 | func (t *terminalSession) summary() map[string]any { |
| 41 | 43 | t.mu.Lock() |
| 42 | 44 | defer t.mu.Unlock() |
| 43 | 删除: return map[string]any{"id": t.id, "title": t.title, "closed": t.closed, "workspace": t.workspace} | |
| 45 | 新增: closed := t.closed | |
| 46 | 新增: if t.done != nil { | |
| 47 | 新增: select { | |
| 48 | 新增: case <-t.done: | |
| 49 | 新增: closed = true | |
| 50 | 新增: default: | |
| 51 | 新增: closed = false | |
| 52 | 新增: } | |
| 53 | 新增: } | |
| 54 | 新增: return map[string]any{"id": t.id, "title": t.title, "closed": closed, "workspace": t.workspace, "kind": t.kind, | |
| 55 | 新增: "claude_account_id": t.claudeAccountID, "claude_account_source": t.claudeAccountSource} | |
| 44 | 56 | } |
| 45 | 57 | |
| 46 | 58 | func (t *terminalSession) stopPTY() { |
| @@ -120,7 +132,11 @@ func (t *terminalSession) subscribe() *terminalSubscription { | ||
| 120 | 132 | } else { |
| 121 | 133 | t.clients[channel] = true |
| 122 | 134 | } |
| 123 | 删除: return &terminalSubscription{History: append([]byte(nil), t.history...), Output: channel, session: t, channel: channel} | |
| 135 | 新增: history := append([]byte(nil), t.history...) | |
| 136 | 新增: if t.kind == "claude-login" { | |
| 137 | 新增: history = []byte("请在 Cage 浏览器的临时登录页完成授权。若页面提供验证码,可返回此终端输入。\r\n") | |
| 138 | 新增: } | |
| 139 | 新增: return &terminalSubscription{History: history, Output: channel, session: t, channel: channel} | |
| 124 | 140 | } |
| 125 | 141 | |
| 126 | 142 | // Close detaches the viewer; the PTY and its process continue running. |
| @@ -163,9 +179,11 @@ func (t *terminalSession) read() { | ||
| 163 | 179 | if n > 0 { |
| 164 | 180 | chunk := append([]byte(nil), buffer[:n]...) |
| 165 | 181 | t.mu.Lock() |
| 166 | 删除: t.history = append(t.history, chunk...) | |
| 167 | 删除: if len(t.history) > 512<<10 { | |
| 168 | 删除: t.history = t.history[len(t.history)-(512<<10):] | |
| 182 | 新增: if t.kind != "claude-login" { | |
| 183 | 新增: t.history = append(t.history, chunk...) | |
| 184 | 新增: if len(t.history) > 512<<10 { | |
| 185 | 新增: t.history = t.history[len(t.history)-(512<<10):] | |
| 186 | 新增: } | |
| 169 | 187 | } |
| 170 | 188 | for channel := range t.clients { |
| 171 | 189 | select { |
| @@ -0,0 +1,240 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "encoding/json" | |
| 6 | 新增: "errors" | |
| 7 | 新增: "net/http" | |
| 8 | 新增: "slices" | |
| 9 | 新增: "time" | |
| 10 | 新增:) | |
| 11 | 新增: | |
| 12 | 新增:type vaultBrowserInput struct { | |
| 13 | 新增: Action string `json:"action"` | |
| 14 | 新增: Tab string `json:"tab"` | |
| 15 | 新增: ID string `json:"id"` | |
| 16 | 新增: Candidate string `json:"candidate"` | |
| 17 | 新增: Document string `json:"document"` | |
| 18 | 新增: Origin string `json:"origin"` | |
| 19 | 新增: Lease string `json:"lease,omitempty"` | |
| 20 | 新增: Username string `json:"username,omitempty"` | |
| 21 | 新增: Password string `json:"password,omitempty"` | |
| 22 | 新增: Blocked []string `json:"blocked,omitempty"` | |
| 23 | 新增:} | |
| 24 | 新增:type vaultCandidate struct { | |
| 25 | 新增: ID string `json:"id"` | |
| 26 | 新增: Tab string `json:"tab"` | |
| 27 | 新增: Origin string `json:"origin"` | |
| 28 | 新增: Username string `json:"username"` | |
| 29 | 新增: Password string `json:"password,omitempty"` | |
| 30 | 新增: Update bool `json:"update"` | |
| 31 | 新增:} | |
| 32 | 新增:type vaultBrowserState struct { | |
| 33 | 新增: Available bool `json:"available"` | |
| 34 | 新增: Origin string `json:"origin"` | |
| 35 | 新增: Document string `json:"document"` | |
| 36 | 新增: Candidates []vaultCandidate `json:"candidates"` | |
| 37 | 新增: Entries []vaultEntry `json:"entries"` | |
| 38 | 新增:} | |
| 39 | 新增: | |
| 40 | 新增:func (s *Server) vaultList(w http.ResponseWriter, r *http.Request) { | |
| 41 | 新增: var out vaultData | |
| 42 | 新增: err := s.account.withVault(r.Context(), false, func(db *vaultData) error { | |
| 43 | 新增: out = *db | |
| 44 | 新增: for i := range out.Entries { | |
| 45 | 新增: out.Entries[i].Password = "" | |
| 46 | 新增: } | |
| 47 | 新增: return nil | |
| 48 | 新增: }) | |
| 49 | 新增: if err != nil { | |
| 50 | 新增: requestError(w, err) | |
| 51 | 新增: return | |
| 52 | 新增: } | |
| 53 | 新增: jsonReply(w, out) | |
| 54 | 新增:} | |
| 55 | 新增:func (s *Server) vaultMutation(w http.ResponseWriter, r *http.Request) { | |
| 56 | 新增: var input struct { | |
| 57 | 新增: Action string `json:"action"` | |
| 58 | 新增: Entry vaultEntry `json:"entry"` | |
| 59 | 新增: ID string `json:"id"` | |
| 60 | 新增: Origin string `json:"origin"` | |
| 61 | 新增: AccountPassword string `json:"account_password"` | |
| 62 | 新增: } | |
| 63 | 新增: if !readJSON(w, r, &input, 32<<10) { | |
| 64 | 新增: return | |
| 65 | 新增: } | |
| 66 | 新增: if input.Action == "reveal" { | |
| 67 | 新增: if err := s.account.verifyVaultPassword(input.AccountPassword); err != nil { | |
| 68 | 新增: requestError(w, err) | |
| 69 | 新增: return | |
| 70 | 新增: } | |
| 71 | 新增: } | |
| 72 | 新增: result := map[string]any{"ok": true} | |
| 73 | 新增: err := s.account.withVault(r.Context(), input.Action != "reveal", func(db *vaultData) error { | |
| 74 | 新增: switch input.Action { | |
| 75 | 新增: case "save": | |
| 76 | 新增: return db.save(input.Entry) | |
| 77 | 新增: case "delete": | |
| 78 | 新增: db.Entries = slices.DeleteFunc(db.Entries, func(e vaultEntry) bool { return e.ID == input.ID }) | |
| 79 | 新增: case "unblock": | |
| 80 | 新增: db.Blocked = slices.DeleteFunc(db.Blocked, func(origin string) bool { return origin == input.Origin }) | |
| 81 | 新增: case "reveal": | |
| 82 | 新增: for _, entry := range db.Entries { | |
| 83 | 新增: if entry.ID == input.ID { | |
| 84 | 新增: result["password"] = entry.Password | |
| 85 | 新增: return nil | |
| 86 | 新增: } | |
| 87 | 新增: } | |
| 88 | 新增: return errors.New("密码记录不存在") | |
| 89 | 新增: default: | |
| 90 | 新增: return errors.New("密码保险箱操作无效") | |
| 91 | 新增: } | |
| 92 | 新增: return nil | |
| 93 | 新增: }) | |
| 94 | 新增: if err != nil { | |
| 95 | 新增: requestError(w, err) | |
| 96 | 新增: return | |
| 97 | 新增: } | |
| 98 | 新增: jsonReply(w, result) | |
| 99 | 新增:} | |
| 100 | 新增: | |
| 101 | 新增:func (s *Server) guestVault(ctx context.Context, input vaultBrowserInput, out any) error { | |
| 102 | 新增: s.mu.Lock() | |
| 103 | 新增: ready, token := s.ready, s.credentials.Token | |
| 104 | 新增: s.mu.Unlock() | |
| 105 | 新增: if !ready { | |
| 106 | 新增: return errBrowserNotReady | |
| 107 | 新增: } | |
| 108 | 新增: body, _ := json.Marshal(input) | |
| 109 | 新增: defer clear(body) | |
| 110 | 新增: data, err := s.guestAPI(ctx, token, http.MethodPost, "/vault", body) | |
| 111 | 新增: defer clear(data) | |
| 112 | 新增: if err != nil { | |
| 113 | 新增: return errors.New("浏览器密码功能暂不可用,请更新环境组件后重试") | |
| 114 | 新增: } | |
| 115 | 新增: var failure struct { | |
| 116 | 新增: Error string `json:"vaultError"` | |
| 117 | 新增: } | |
| 118 | 新增: if json.Unmarshal(data, &failure) == nil && failure.Error != "" { | |
| 119 | 新增: switch failure.Error { | |
| 120 | 新增: case "登录记录已过期,请重新登录", "当前网页已切换", "未找到可填写的登录框,或页面已变化", "保险箱已锁定,请重试", "登录页面已变化,请稍后重试": | |
| 121 | 新增: return errors.New(failure.Error) | |
| 122 | 新增: default: | |
| 123 | 新增: return errors.New("网页未能处理密码操作,请刷新后重试") | |
| 124 | 新增: } | |
| 125 | 新增: } | |
| 126 | 新增: if json.Unmarshal(data, out) != nil { | |
| 127 | 新增: return errors.New("浏览器密码响应无效") | |
| 128 | 新增: } | |
| 129 | 新增: return nil | |
| 130 | 新增:} | |
| 131 | 新增: | |
| 132 | 新增:func (s *Server) vaultBrowser(w http.ResponseWriter, r *http.Request) { | |
| 133 | 新增: var input vaultBrowserInput | |
| 134 | 新增: if !readJSON(w, r, &input, 16<<10) { | |
| 135 | 新增: return | |
| 136 | 新增: } | |
| 137 | 新增: // Passwords and origins used for fill always come from the host database. | |
| 138 | 新增: input.Password, input.Username, input.Origin, input.Lease, input.Blocked = "", "", "", "", nil | |
| 139 | 新增: s.account.mu.Lock() | |
| 140 | 新增: lease := s.account.vaultLease | |
| 141 | 新增: s.account.mu.Unlock() | |
| 142 | 新增: input.Lease = lease | |
| 143 | 新增: var result any = map[string]bool{"ok": true} | |
| 144 | 新增: err := s.account.withVault(r.Context(), input.Action == "save" || input.Action == "never", func(db *vaultData) error { | |
| 145 | 新增: if lease == "" || lease != s.account.vaultLease { | |
| 146 | 新增: return errors.New("请重新解锁后重试") | |
| 147 | 新增: } | |
| 148 | 新增: switch input.Action { | |
| 149 | 新增: case "status": | |
| 150 | 新增: input.Blocked = db.Blocked | |
| 151 | 新增: state := vaultBrowserState{Candidates: []vaultCandidate{}, Entries: []vaultEntry{}} | |
| 152 | 新增: if err := s.guestVault(r.Context(), input, &state); err != nil { | |
| 153 | 新增: result = map[string]any{"available": false, "message": err.Error(), "candidates": []vaultCandidate{}, "entries": []vaultEntry{}} | |
| 154 | 新增: return nil | |
| 155 | 新增: } | |
| 156 | 新增: pending := []vaultCandidate{} | |
| 157 | 新增: for _, candidate := range state.Candidates { | |
| 158 | 新增: if slices.Contains(db.Blocked, candidate.Origin) { | |
| 159 | 新增: continue | |
| 160 | 新增: } | |
| 161 | 新增: same := false | |
| 162 | 新增: for _, entry := range db.Entries { | |
| 163 | 新增: if entry.Origin == candidate.Origin && entry.Username == candidate.Username { | |
| 164 | 新增: candidate.Update = true | |
| 165 | 新增: same = entry.Password == candidate.Password | |
| 166 | 新增: } | |
| 167 | 新增: } | |
| 168 | 新增: candidate.Password = "" | |
| 169 | 新增: if !same { | |
| 170 | 新增: pending = append(pending, candidate) | |
| 171 | 新增: } | |
| 172 | 新增: } | |
| 173 | 新增: state.Candidates = pending | |
| 174 | 新增: state.Entries = []vaultEntry{} | |
| 175 | 新增: for _, entry := range db.Entries { | |
| 176 | 新增: if entry.Origin == state.Origin { | |
| 177 | 新增: entry.Password = "" | |
| 178 | 新增: state.Entries = append(state.Entries, entry) | |
| 179 | 新增: } | |
| 180 | 新增: } | |
| 181 | 新增: result = state | |
| 182 | 新增: case "fill": | |
| 183 | 新增: for _, entry := range db.Entries { | |
| 184 | 新增: if entry.ID == input.ID { | |
| 185 | 新增: input.Origin, input.Username, input.Password = entry.Origin, entry.Username, entry.Password | |
| 186 | 新增: var reply map[string]any | |
| 187 | 新增: return s.guestVault(r.Context(), input, &reply) | |
| 188 | 新增: } | |
| 189 | 新增: } | |
| 190 | 新增: return errors.New("密码记录不存在") | |
| 191 | 新增: case "save", "never": | |
| 192 | 新增: request := input | |
| 193 | 新增: request.Action = "candidate" | |
| 194 | 新增: var candidate vaultCandidate | |
| 195 | 新增: if err := s.guestVault(r.Context(), request, &candidate); err != nil { | |
| 196 | 新增: return err | |
| 197 | 新增: } | |
| 198 | 新增: origin, err := vaultOrigin(candidate.Origin) | |
| 199 | 新增: if err != nil || origin != candidate.Origin || candidate.ID != input.Candidate { | |
| 200 | 新增: return errors.New("登录记录已失效,请重新登录") | |
| 201 | 新增: } | |
| 202 | 新增: if input.Action == "never" { | |
| 203 | 新增: if !slices.Contains(db.Blocked, origin) { | |
| 204 | 新增: db.Blocked = append(db.Blocked, origin) | |
| 205 | 新增: } | |
| 206 | 新增: return nil | |
| 207 | 新增: } | |
| 208 | 新增: entry := vaultEntry{Origin: origin, Username: candidate.Username, Password: candidate.Password} | |
| 209 | 新增: for _, old := range db.Entries { | |
| 210 | 新增: if old.Origin == origin && old.Username == entry.Username { | |
| 211 | 新增: entry.ID = old.ID | |
| 212 | 新增: } | |
| 213 | 新增: } | |
| 214 | 新增: return db.save(entry) | |
| 215 | 新增: case "dismiss": | |
| 216 | 新增: var reply map[string]any | |
| 217 | 新增: return s.guestVault(r.Context(), input, &reply) | |
| 218 | 新增: default: | |
| 219 | 新增: return errors.New("密码保险箱操作无效") | |
| 220 | 新增: } | |
| 221 | 新增: return nil | |
| 222 | 新增: }) | |
| 223 | 新增: if err != nil { | |
| 224 | 新增: requestError(w, err) | |
| 225 | 新增: return | |
| 226 | 新增: } | |
| 227 | 新增: if input.Action == "save" || input.Action == "never" { | |
| 228 | 新增: input.Action = "dismiss" | |
| 229 | 新增: var ignored map[string]any | |
| 230 | 新增: _ = s.guestVault(r.Context(), input, &ignored) | |
| 231 | 新增: } | |
| 232 | 新增: jsonReply(w, result) | |
| 233 | 新增:} | |
| 234 | 新增: | |
| 235 | 新增:func (s *Server) clearBrowserVault(lease string) { | |
| 236 | 新增: ctx, cancel := context.WithTimeout(context.Background(), time.Second) | |
| 237 | 新增: defer cancel() | |
| 238 | 新增: var out map[string]any | |
| 239 | 新增: _ = s.guestVault(ctx, vaultBrowserInput{Action: "lock", Lease: lease}, &out) | |
| 240 | 新增:} | |
| @@ -0,0 +1,180 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "crypto/aes" | |
| 6 | 新增: "crypto/cipher" | |
| 7 | 新增: "crypto/hmac" | |
| 8 | 新增: "crypto/rand" | |
| 9 | 新增: "crypto/sha256" | |
| 10 | 新增: "encoding/json" | |
| 11 | 新增: "errors" | |
| 12 | 新增: "net/url" | |
| 13 | 新增: "os" | |
| 14 | 新增: "path/filepath" | |
| 15 | 新增: "slices" | |
| 16 | 新增: "strings" | |
| 17 | 新增: "time" | |
| 18 | 新增: | |
| 19 | 新增: "github.com/sylvinus/agent-vm/internal/host" | |
| 20 | 新增:) | |
| 21 | 新增: | |
| 22 | 新增:const vaultDomain = "Cage password vault v1" | |
| 23 | 新增:const vaultLimit = 4 << 20 | |
| 24 | 新增: | |
| 25 | 新增:type vaultEntry struct { | |
| 26 | 新增: ID string `json:"id"` | |
| 27 | 新增: Origin string `json:"origin"` | |
| 28 | 新增: Username string `json:"username"` | |
| 29 | 新增: Password string `json:"password,omitempty"` | |
| 30 | 新增: Updated string `json:"updated"` | |
| 31 | 新增:} | |
| 32 | 新增:type vaultData struct { | |
| 33 | 新增: Entries []vaultEntry `json:"entries"` | |
| 34 | 新增: Blocked []string `json:"blocked"` | |
| 35 | 新增:} | |
| 36 | 新增:type vaultEnvelope struct { | |
| 37 | 新增: Version int `json:"version"` | |
| 38 | 新增: Nonce []byte `json:"nonce"` | |
| 39 | 新增: Data []byte `json:"data"` | |
| 40 | 新增:} | |
| 41 | 新增: | |
| 42 | 新增:func vaultOrigin(raw string) (string, error) { | |
| 43 | 新增: u, err := url.Parse(raw) | |
| 44 | 新增: if err != nil || u.Scheme != "https" || u.Hostname() == "" || u.User != nil || strings.ContainsAny(raw, "\x00\r\n") || len(raw) > 4096 { | |
| 45 | 新增: return "", errors.New("密码保险箱只支持 HTTPS 网站地址") | |
| 46 | 新增: } | |
| 47 | 新增: host := strings.ToLower(u.Host) | |
| 48 | 新增: if u.Port() == "443" { | |
| 49 | 新增: host = strings.TrimSuffix(host, ":443") | |
| 50 | 新增: } | |
| 51 | 新增: return "https://" + host, nil | |
| 52 | 新增:} | |
| 53 | 新增: | |
| 54 | 新增:// The account mutex serializes vault transactions with lock/password changes. | |
| 55 | 新增:// No decrypted database or derived key is retained between requests. | |
| 56 | 新增:func (a *localAccount) withVault(ctx context.Context, mutate bool, fn func(*vaultData) error) error { | |
| 57 | 新增: a.mu.Lock() | |
| 58 | 新增: defer a.mu.Unlock() | |
| 59 | 新增: if len(a.key) != 32 || ctx.Err() != nil { | |
| 60 | 新增: return errors.New("请先解锁 Cage") | |
| 61 | 新增: } | |
| 62 | 新增: mac := hmac.New(sha256.New, a.key) | |
| 63 | 新增: mac.Write([]byte(vaultDomain)) | |
| 64 | 新增: key := mac.Sum(nil) | |
| 65 | 新增: defer clear(key) | |
| 66 | 新增: block, err := aes.NewCipher(key) | |
| 67 | 新增: if err != nil { | |
| 68 | 新增: return err | |
| 69 | 新增: } | |
| 70 | 新增: aead, err := cipher.NewGCM(block) | |
| 71 | 新增: if err != nil { | |
| 72 | 新增: return err | |
| 73 | 新增: } | |
| 74 | 新增: path := filepath.Join(filepath.Dir(a.path), "password-vault.json") | |
| 75 | 新增: db := vaultData{Entries: []vaultEntry{}, Blocked: []string{}} | |
| 76 | 新增: raw, err := os.ReadFile(path) | |
| 77 | 新增: if err != nil && !os.IsNotExist(err) { | |
| 78 | 新增: return errors.New("无法读取密码保险箱") | |
| 79 | 新增: } | |
| 80 | 新增: if err == nil { | |
| 81 | 新增: if host.CheckPrivateFile(path) != nil { | |
| 82 | 新增: return errors.New("密码保险箱文件权限不安全") | |
| 83 | 新增: } | |
| 84 | 新增: var sealed vaultEnvelope | |
| 85 | 新增: if len(raw) > vaultLimit*2 || json.Unmarshal(raw, &sealed) != nil || sealed.Version != 1 || len(sealed.Nonce) != aead.NonceSize() { | |
| 86 | 新增: return errors.New("密码保险箱损坏,请从备份恢复;现有文件未修改") | |
| 87 | 新增: } | |
| 88 | 新增: plain, err := aead.Open(nil, sealed.Nonce, sealed.Data, []byte(vaultDomain)) | |
| 89 | 新增: if err != nil { | |
| 90 | 新增: return errors.New("密码保险箱无法解密;现有文件未修改") | |
| 91 | 新增: } | |
| 92 | 新增: defer clear(plain) | |
| 93 | 新增: if len(plain) > vaultLimit || json.Unmarshal(plain, &db) != nil { | |
| 94 | 新增: return errors.New("密码保险箱内容无效;现有文件未修改") | |
| 95 | 新增: } | |
| 96 | 新增: } | |
| 97 | 新增: if err = fn(&db); err != nil { | |
| 98 | 新增: return err | |
| 99 | 新增: } | |
| 100 | 新增: if !mutate { | |
| 101 | 新增: return nil | |
| 102 | 新增: } | |
| 103 | 新增: if ctx.Err() != nil { | |
| 104 | 新增: return errors.New("操作已取消") | |
| 105 | 新增: } | |
| 106 | 新增: plain, err := json.Marshal(db) | |
| 107 | 新增: if err != nil { | |
| 108 | 新增: return err | |
| 109 | 新增: } | |
| 110 | 新增: defer clear(plain) | |
| 111 | 新增: if len(plain) > vaultLimit { | |
| 112 | 新增: return errors.New("密码保险箱已满,请删除不再使用的记录") | |
| 113 | 新增: } | |
| 114 | 新增: nonce := make([]byte, aead.NonceSize()) | |
| 115 | 新增: if _, err = rand.Read(nonce); err != nil { | |
| 116 | 新增: return err | |
| 117 | 新增: } | |
| 118 | 新增: if err = writePrivate(path, vaultEnvelope{1, nonce, aead.Seal(nil, nonce, plain, []byte(vaultDomain))}); err != nil { | |
| 119 | 新增: return errors.New("密码保险箱未能保存,请检查磁盘空间与权限") | |
| 120 | 新增: } | |
| 121 | 新增: return nil | |
| 122 | 新增:} | |
| 123 | 新增: | |
| 124 | 新增:func (db *vaultData) save(entry vaultEntry) error { | |
| 125 | 新增: origin, err := vaultOrigin(entry.Origin) | |
| 126 | 新增: if err != nil { | |
| 127 | 新增: return err | |
| 128 | 新增: } | |
| 129 | 新增: entry.Origin = origin | |
| 130 | 新增: if len(entry.Username) > 1024 || len(entry.Password) > 8192 || strings.ContainsAny(entry.Username, "\x00\r\n") { | |
| 131 | 新增: return errors.New("账号或密码过长或无效") | |
| 132 | 新增: } | |
| 133 | 新增: index := -1 | |
| 134 | 新增: for i, old := range db.Entries { | |
| 135 | 新增: if old.ID == entry.ID && entry.ID != "" { | |
| 136 | 新增: index = i | |
| 137 | 新增: } | |
| 138 | 新增: if old.Origin == origin && old.Username == entry.Username && old.ID != entry.ID { | |
| 139 | 新增: return errors.New("此网站已有同名账号,请编辑已有记录") | |
| 140 | 新增: } | |
| 141 | 新增: } | |
| 142 | 新增: if entry.ID != "" && index < 0 { | |
| 143 | 新增: return errors.New("密码记录不存在,请刷新后重试") | |
| 144 | 新增: } | |
| 145 | 新增: if index >= 0 && entry.Password == "" { | |
| 146 | 新增: entry.Password = db.Entries[index].Password | |
| 147 | 新增: } | |
| 148 | 新增: if entry.Password == "" { | |
| 149 | 新增: return errors.New("请输入密码") | |
| 150 | 新增: } | |
| 151 | 新增: entry.Updated = time.Now().UTC().Format(time.RFC3339) | |
| 152 | 新增: if index >= 0 { | |
| 153 | 新增: db.Entries[index] = entry | |
| 154 | 新增: } else { | |
| 155 | 新增: entry.ID = randomToken() | |
| 156 | 新增: db.Entries = append(db.Entries, entry) | |
| 157 | 新增: } | |
| 158 | 新增: db.Blocked = slices.DeleteFunc(db.Blocked, func(s string) bool { return s == origin }) | |
| 159 | 新增: return nil | |
| 160 | 新增:} | |
| 161 | 新增: | |
| 162 | 新增:// Reauthentication does not rotate the access epoch or enable automatic login. | |
| 163 | 新增:func (a *localAccount) verifyVaultPassword(password string) error { | |
| 164 | 新增: a.mu.Lock() | |
| 165 | 新增: defer a.mu.Unlock() | |
| 166 | 新增: if len(a.key) != 32 { | |
| 167 | 新增: return errors.New("请先解锁 Cage") | |
| 168 | 新增: } | |
| 169 | 新增: if time.Now().Before(a.nextAttempt) { | |
| 170 | 新增: return errors.New("请稍后再试") | |
| 171 | 新增: } | |
| 172 | 新增: key, err := openAccountKey(a.record, password) | |
| 173 | 新增: defer clear(key) | |
| 174 | 新增: if err != nil { | |
| 175 | 新增: a.nextAttempt = time.Now().Add(time.Second) | |
| 176 | 新增: return err | |
| 177 | 新增: } | |
| 178 | 新增: a.nextAttempt = time.Time{} | |
| 179 | 新增: return nil | |
| 180 | 新增:} | |
| @@ -0,0 +1,193 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "bytes" | |
| 5 | 新增: "context" | |
| 6 | 新增: "encoding/json" | |
| 7 | 新增: "net/http" | |
| 8 | 新增: "net/http/httptest" | |
| 9 | 新增: "os" | |
| 10 | 新增: "path/filepath" | |
| 11 | 新增: "strings" | |
| 12 | 新增: "testing" | |
| 13 | 新增: "time" | |
| 14 | 新增:) | |
| 15 | 新增: | |
| 16 | 新增:func TestVaultEncryptionLockReopenPasswordChangeAndCorruption(t *testing.T) { | |
| 17 | 新增: a := newTestAccount(t) | |
| 18 | 新增: ctx := context.Background() | |
| 19 | 新增: err := a.withVault(ctx, true, func(db *vaultData) error { | |
| 20 | 新增: return db.save(vaultEntry{Origin: "https://mail.example.com/login", Username: "[email protected]", Password: "secret-mail-password"}) | |
| 21 | 新增: }) | |
| 22 | 新增: if err != nil { | |
| 23 | 新增: t.Fatal(err) | |
| 24 | 新增: } | |
| 25 | 新增: path := filepath.Join(filepath.Dir(a.path), "password-vault.json") | |
| 26 | 新增: original, err := os.ReadFile(path) | |
| 27 | 新增: if err != nil { | |
| 28 | 新增: t.Fatal(err) | |
| 29 | 新增: } | |
| 30 | 新增: for _, plain := range []string{"[email protected]", "secret-mail-password", "mail.example.com"} { | |
| 31 | 新增: if bytes.Contains(original, []byte(plain)) { | |
| 32 | 新增: t.Fatal("plaintext persisted") | |
| 33 | 新增: } | |
| 34 | 新增: } | |
| 35 | 新增: if err = a.changePassword("initial-test-password", "changed-account-password"); err != nil { | |
| 36 | 新增: t.Fatal(err) | |
| 37 | 新增: } | |
| 38 | 新增: oldLease := a.vaultLease | |
| 39 | 新增: a.lock() | |
| 40 | 新增: if err = a.withVault(ctx, false, func(*vaultData) error { t.Fatal("locked callback executed"); return nil }); err == nil { | |
| 41 | 新增: t.Fatal("locked read accepted") | |
| 42 | 新增: } | |
| 43 | 新增: reopened, err := loadLocalAccount(filepath.Dir(a.path)) | |
| 44 | 新增: if err != nil { | |
| 45 | 新增: t.Fatal(err) | |
| 46 | 新增: } | |
| 47 | 新增: defer reopened.lock() | |
| 48 | 新增: if err = reopened.unlock("changed-account-password"); err != nil { | |
| 49 | 新增: t.Fatal(err) | |
| 50 | 新增: } | |
| 51 | 新增: if reopened.vaultLease == oldLease { | |
| 52 | 新增: t.Fatal("unlock reused browser lease") | |
| 53 | 新增: } | |
| 54 | 新增: err = reopened.withVault(ctx, false, func(db *vaultData) error { | |
| 55 | 新增: if len(db.Entries) != 1 || db.Entries[0].Password != "secret-mail-password" || db.Entries[0].Origin != "https://mail.example.com" { | |
| 56 | 新增: t.Fatalf("data lost after password change/reopen: count %d", len(db.Entries)) | |
| 57 | 新增: } | |
| 58 | 新增: return nil | |
| 59 | 新增: }) | |
| 60 | 新增: if err != nil { | |
| 61 | 新增: t.Fatal(err) | |
| 62 | 新增: } | |
| 63 | 新增: var envelope vaultEnvelope | |
| 64 | 新增: if json.Unmarshal(original, &envelope) != nil { | |
| 65 | 新增: t.Fatal("invalid envelope") | |
| 66 | 新增: } | |
| 67 | 新增: envelope.Data[0] ^= 1 | |
| 68 | 新增: corrupted, _ := json.Marshal(envelope) | |
| 69 | 新增: if err = os.WriteFile(path, corrupted, 0600); err != nil { | |
| 70 | 新增: t.Fatal(err) | |
| 71 | 新增: } | |
| 72 | 新增: if err = reopened.withVault(ctx, true, func(db *vaultData) error { return db.save(vaultEntry{Origin: "https://new.example", Password: "new"}) }); err == nil { | |
| 73 | 新增: t.Fatal("corrupt vault overwritten") | |
| 74 | 新增: } | |
| 75 | 新增: after, _ := os.ReadFile(path) | |
| 76 | 新增: if !bytes.Equal(corrupted, after) { | |
| 77 | 新增: t.Fatal("corrupt vault changed") | |
| 78 | 新增: } | |
| 79 | 新增:} | |
| 80 | 新增: | |
| 81 | 新增:func TestVaultAPIReauthenticationAndIsolation(t *testing.T) { | |
| 82 | 新增: s := testServer(t) | |
| 83 | 新增: s.account = newTestAccount(t) | |
| 84 | 新增: save := `{"action":"save","entry":{"origin":"https://mail.example.com","username":"[email protected]","password":"mail-secret"}}` | |
| 85 | 新增: w := request(s, "POST", "/api/vault", "https://evil.example", save, true) | |
| 86 | 新增: if w.Code != 403 { | |
| 87 | 新增: t.Fatalf("cross origin accepted: %d", w.Code) | |
| 88 | 新增: } | |
| 89 | 新增: w = request(s, "POST", "/api/vault", s.origin, save, true) | |
| 90 | 新增: if w.Code != 200 { | |
| 91 | 新增: t.Fatal(w.Code, w.Body.String()) | |
| 92 | 新增: } | |
| 93 | 新增: w = request(s, "GET", "/api/vault", s.origin, "", true) | |
| 94 | 新增: if w.Code != 200 || strings.Contains(w.Body.String(), "mail-secret") { | |
| 95 | 新增: t.Fatal("list leaks password", w.Code) | |
| 96 | 新增: } | |
| 97 | 新增: var db vaultData | |
| 98 | 新增: if json.Unmarshal(w.Body.Bytes(), &db) != nil || len(db.Entries) != 1 { | |
| 99 | 新增: t.Fatal("missing saved entry") | |
| 100 | 新增: } | |
| 101 | 新增: reveal := func(password string) *httptest.ResponseRecorder { | |
| 102 | 新增: b, _ := json.Marshal(map[string]string{"action": "reveal", "id": db.Entries[0].ID, "account_password": password}) | |
| 103 | 新增: return request(s, "POST", "/api/vault", s.origin, string(b), true) | |
| 104 | 新增: } | |
| 105 | 新增: if w = reveal("wrong"); w.Code == 200 || strings.Contains(w.Body.String(), "mail-secret") { | |
| 106 | 新增: t.Fatal("wrong password revealed") | |
| 107 | 新增: } | |
| 108 | 新增: s.account.nextAttempt = time.Time{} | |
| 109 | 新增: // testServer uses its own account password; match the fixture definition. | |
| 110 | 新增: if w = reveal("initial-test-password"); w.Code != 200 { | |
| 111 | 新增: t.Fatal(w.Code, w.Body.String()) | |
| 112 | 新增: } | |
| 113 | 新增: if !strings.Contains(w.Body.String(), "mail-secret") { | |
| 114 | 新增: t.Fatal("verified reveal missing") | |
| 115 | 新增: } | |
| 116 | 新增: s.account.lock() | |
| 117 | 新增: for _, path := range []string{"/api/vault", "/api/vault/browser"} { | |
| 118 | 新增: if w = request(s, "POST", path, s.origin, save, true); w.Code != http.StatusLocked { | |
| 119 | 新增: t.Fatal("locked endpoint accepted", path, w.Code) | |
| 120 | 新增: } | |
| 121 | 新增: } | |
| 122 | 新增:} | |
| 123 | 新增: | |
| 124 | 新增:func TestVaultBrowserNeverExposesCandidatePasswordAndUsesStoredOrigin(t *testing.T) { | |
| 125 | 新增: s := testServer(t) | |
| 126 | 新增: s.ready, s.credentials.Token = true, "vault-guest-test" | |
| 127 | 新增: var sent vaultBrowserInput | |
| 128 | 新增: guest := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
| 129 | 新增: if r.URL.Path != "/vault" || r.Header.Get("Authorization") != "Bearer vault-guest-test" { | |
| 130 | 新增: t.Error("wrong guest transport") | |
| 131 | 新增: } | |
| 132 | 新增: if json.NewDecoder(r.Body).Decode(&sent) != nil { | |
| 133 | 新增: t.Error("invalid body") | |
| 134 | 新增: } | |
| 135 | 新增: switch sent.Action { | |
| 136 | 新增: case "status": | |
| 137 | 新增: jsonReply(w, vaultBrowserState{Available: true, Origin: "https://mail.example.com", Document: "doc", Candidates: []vaultCandidate{{ID: "candidate", Origin: "https://mail.example.com", Username: "alice", Password: "site-secret"}}}) | |
| 138 | 新增: case "candidate": | |
| 139 | 新增: jsonReply(w, vaultCandidate{ID: "candidate", Origin: "https://mail.example.com", Username: "alice", Password: "site-secret"}) | |
| 140 | 新增: default: | |
| 141 | 新增: jsonReply(w, map[string]bool{"ok": true}) | |
| 142 | 新增: } | |
| 143 | 新增: })) | |
| 144 | 新增: defer guest.Close() | |
| 145 | 新增: s.browserControl = localBrowserClient(t, s.lifetimeContext(), guest) | |
| 146 | 新增: w := request(s, "POST", "/api/vault/browser", s.origin, `{"action":"status","tab":"tab"}`, true) | |
| 147 | 新增: if w.Code != 200 || strings.Contains(w.Body.String(), "site-secret") { | |
| 148 | 新增: t.Fatal("candidate leaked", w.Code) | |
| 149 | 新增: } | |
| 150 | 新增: w = request(s, "POST", "/api/vault/browser", s.origin, `{"action":"save","candidate":"candidate"}`, true) | |
| 151 | 新增: if w.Code != 200 { | |
| 152 | 新增: t.Fatal(w.Code, w.Body.String()) | |
| 153 | 新增: } | |
| 154 | 新增: w = request(s, "GET", "/api/vault", s.origin, "", true) | |
| 155 | 新增: var db vaultData | |
| 156 | 新增: if json.Unmarshal(w.Body.Bytes(), &db) != nil || len(db.Entries) != 1 { | |
| 157 | 新增: t.Fatal("candidate not saved") | |
| 158 | 新增: } | |
| 159 | 新增: b, _ := json.Marshal(map[string]string{"action": "fill", "id": db.Entries[0].ID, "tab": "tab", "document": "doc", "origin": "https://evil.example", "password": "injected", "lease": "forged"}) | |
| 160 | 新增: w = request(s, "POST", "/api/vault/browser", s.origin, string(b), true) | |
| 161 | 新增: if w.Code != 200 || sent.Origin != "https://mail.example.com" || sent.Password != "site-secret" || sent.Lease != s.account.vaultLease { | |
| 162 | 新增: t.Fatal("fill did not use stored credential") | |
| 163 | 新增: } | |
| 164 | 新增: w = request(s, "POST", "/api/vault/browser", s.origin, `{"action":"status","tab":"tab"}`, true) | |
| 165 | 新增: var state vaultBrowserState | |
| 166 | 新增: if json.Unmarshal(w.Body.Bytes(), &state) != nil || len(state.Candidates) != 0 { | |
| 167 | 新增: t.Fatal("identical credential prompted again") | |
| 168 | 新增: } | |
| 169 | 新增:} | |
| 170 | 新增: | |
| 171 | 新增:func TestVaultOriginAndDuplicateUpdate(t *testing.T) { | |
| 172 | 新增: db := vaultData{} | |
| 173 | 新增: for _, raw := range []string{"http://mail.example.com", "https://user:[email protected]", "file:///test", "https://"} { | |
| 174 | 新增: if db.save(vaultEntry{Origin: raw, Password: "secret"}) == nil { | |
| 175 | 新增: t.Fatal("invalid origin accepted", raw) | |
| 176 | 新增: } | |
| 177 | 新增: } | |
| 178 | 新增: if err := db.save(vaultEntry{Origin: "https://MAIL.example.com:443/login", Username: "alice", Password: "old"}); err != nil { | |
| 179 | 新增: t.Fatal(err) | |
| 180 | 新增: } | |
| 181 | 新增: if db.save(vaultEntry{Origin: "https://mail.example.com", Username: "alice", Password: "duplicate"}) == nil { | |
| 182 | 新增: t.Fatal("duplicate accepted") | |
| 183 | 新增: } | |
| 184 | 新增: if err := db.save(vaultEntry{ID: db.Entries[0].ID, Origin: "https://mail.example.com", Username: "alice"}); err != nil { | |
| 185 | 新增: t.Fatal(err) | |
| 186 | 新增: } | |
| 187 | 新增: if len(db.Entries) != 1 || db.Entries[0].Password != "old" { | |
| 188 | 新增: t.Fatal("blank edit lost existing password") | |
| 189 | 新增: } | |
| 190 | 新增: if err := db.save(vaultEntry{Origin: "https://mail.example.com", Username: "bob", Password: "other"}); err != nil { | |
| 191 | 新增: t.Fatal(err) | |
| 192 | 新增: } | |
| 193 | 新增:} | |
| @@ -0,0 +1,37 @@ | ||
| 1 | 新增:# Claude Cage 宣传片 | |
| 2 | 新增: | |
| 3 | 新增:一支 60 秒、1920×1080 / 60 fps 的宣传片,画面和配乐都由代码生成。 | |
| 4 | 新增: | |
| 5 | 新增:| 时间 | 段落 | 内容 | | |
| 6 | 新增:|---|---|---| | |
| 7 | 新增:| 0–14s | 痛点 | 四个硬切镜头:封号让钱和进度清零;VPS、指纹浏览器、远程 Mac mini 的月账单;全局代理把整台电脑拖下水;传统虚拟机又重又慢还得自己配。最后一句“就不能,简单一点吗?” | | |
| 8 | 新增:| 14–20s | 方案 | 像素 Logo 落笼,定位语“为 Claude 量身定制的轻量虚拟机”,开箱即用,只需配置自己的代理。 | | |
| 9 | 新增:| 19–44s | 三步上手 | 复刻应用界面:配置代理、时区跟随出口 → 11 项泄漏检查通过后才联网 → 在 Cage 里打开终端运行 `claude`,主机不开全局代理。 | | |
| 10 | 新增:| 44–50s | 卖点汇总 | 轻量开箱即用 · 自带泄漏审查 · 与主机隔离 · 开源接受审查。 | | |
| 11 | 新增:| 49–55s | 写给相遇 | 角色插画与“把 Claude 关起来,是为了更好地保护我们的相遇。” | | |
| 12 | 新增:| 55–60s | 片尾 | Logo、平台、主页与 GitHub 地址、非隶属声明。 | | |
| 13 | 新增: | |
| 14 | 新增:痛点里的账单金额、节点名和终端对话都是示意内容,改文案直接编辑 `index.html`。 | |
| 15 | 新增: | |
| 16 | 新增:## 文件 | |
| 17 | 新增: | |
| 18 | 新增:- `index.html`:舞台、各幕布局和样式。 | |
| 19 | 新增:- `promo.js`:每一帧都是时间的纯函数 `render(t)`,预览、拖动和导出看到的画面完全一致。 | |
| 20 | 新增:- `timeline.js`:画面与配乐共用的时间点,改节奏只改这里。 | |
| 21 | 新增:- `soundtrack.mjs`:按时间轴合成配乐与音效,输出 `out/soundtrack.wav`。 | |
| 22 | 新增:- `render.mjs`:本地静态服务 + 无头 Chrome 逐帧截图 + ffmpeg 编码。 | |
| 23 | 新增: | |
| 24 | 新增:## 使用 | |
| 25 | 新增: | |
| 26 | 新增:需要 Node.js 18+ 和本机的 Chrome、Chromium 或 Edge(macOS、Windows、Linux 的常见安装位置会自动查找,也可以用 `CHROME_PATH` 指定)。ffmpeg 由 `ffmpeg-static` 提供;如果 npm 提示安装脚本未授权,执行 `npm install-scripts approve ffmpeg-static` 后重新安装。 | |
| 27 | 新增: | |
| 28 | 新增:```bash | |
| 29 | 新增:cd promo | |
| 30 | 新增:npm install | |
| 31 | 新增:npm run preview # 打开打印出的地址实时预览:空格播放/暂停,←/→ 跳转,?t=12.5 定位 | |
| 32 | 新增:npm run render # 合成配乐并导出 out/claude-cage-promo.mp4 | |
| 33 | 新增:npm run render:draft # 960×540 / 30 fps 快速草稿 | |
| 34 | 新增:node render.mjs --frames 8.6,24,33 # 只导出这些时间点的 PNG | |
| 35 | 新增:``` | |
| 36 | 新增: | |
| 37 | 新增:页面使用 Google Fonts(Inter、Noto Sans SC、Noto Serif SC、JetBrains Mono),渲染时需要能访问字体服务;离线时会退回系统字体,排版会有轻微差异。 | |
| @@ -0,0 +1,591 @@ | ||
| 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" /> | |
| 6 | 新增:<title>Claude Cage · 宣传片</title> | |
| 7 | 新增:<link rel="preconnect" href="https://fonts.googleapis.com" /> | |
| 8 | 新增:<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> | |
| 9 | 新增:<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500;600&family=Noto+Sans+SC:wght@400;500;600;700&family=Noto+Serif+SC:wght@500;600;700&display=block" /> | |
| 10 | 新增:<style> | |
| 11 | 新增::root { | |
| 12 | 新增: --paper: #faf8f4; | |
| 13 | 新增: --ink: #2b2724; | |
| 14 | 新增: --muted: #7a726a; | |
| 15 | 新增: --line: #e7e2db; | |
| 16 | 新增: --accent: #b95032; | |
| 17 | 新增: --orange: #ef6f45; | |
| 18 | 新增: --night: #0f0d0c; | |
| 19 | 新增: --cream: #f3ebe1; | |
| 20 | 新增: --ok: #2f8a4c; | |
| 21 | 新增: --sans: "Inter", "PingFang SC", "Noto Sans SC", "Microsoft YaHei", sans-serif; | |
| 22 | 新增: --serif: "Noto Serif SC", "Songti SC", "Source Han Serif SC", serif; | |
| 23 | 新增: --mono: "JetBrains Mono", "SF Mono", "Menlo", "Noto Sans Mono CJK SC", monospace; | |
| 24 | 新增:} | |
| 25 | 新增:* { box-sizing: border-box; } | |
| 26 | 新增:html, body { margin: 0; height: 100%; background: #050404; overflow: hidden; } | |
| 27 | 新增:body { font-family: var(--sans); -webkit-font-smoothing: antialiased; font-synthesis: none; } | |
| 28 | 新增: | |
| 29 | 新增:/* ---------- stage ---------- */ | |
| 30 | 新增:#viewport { position: fixed; inset: 0; display: grid; place-items: center; } | |
| 31 | 新增:#stage { | |
| 32 | 新增: position: relative; width: 1920px; height: 1080px; overflow: hidden; | |
| 33 | 新增: background: var(--night); transform-origin: 0 0; flex: none; | |
| 34 | 新增:} | |
| 35 | 新增:.layer { position: absolute; inset: 0; will-change: opacity, transform; } | |
| 36 | 新增:.center { position: absolute; left: 0; right: 0; text-align: center; } | |
| 37 | 新增:.c { display: inline-block; white-space: pre; will-change: opacity, transform, filter; } | |
| 38 | 新增: | |
| 39 | 新增:#grain { | |
| 40 | 新增: position: absolute; inset: -200px; pointer-events: none; z-index: 50; mix-blend-mode: overlay; | |
| 41 | 新增: background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='260' height='260'><filter id='n'><feTurbulence type='fractalNoise' baseFrequency='.9' numOctaves='2' stitchTiles='stitch'/><feColorMatrix values='0 0 0 0 .5 0 0 0 0 .5 0 0 0 0 .5 0 0 0 .9 0'/></filter><rect width='100%' height='100%' filter='url(%23n)'/></svg>"); | |
| 42 | 新增: opacity: .35; | |
| 43 | 新增:} | |
| 44 | 新增:#vignette { position: absolute; inset: 0; pointer-events: none; z-index: 49; | |
| 45 | 新增: background: radial-gradient(ellipse 75% 70% at 50% 48%, transparent 55%, rgba(20,12,6,.22) 100%); } | |
| 46 | 新增: | |
| 47 | 新增:/* ---------- act 1 · the problem ---------- */ | |
| 48 | 新增:#night { background: radial-gradient(ellipse 70% 60% at 50% 55%, #1a1210 0%, #0c0908 70%); } | |
| 49 | 新增:#nightGlow { position: absolute; inset: 0; background: radial-gradient(ellipse 55% 45% at 50% 58%, rgba(255,80,50,.22), transparent 70%); opacity: 0; } | |
| 50 | 新增:#flash { position: absolute; inset: 0; background: #ffe6dc; opacity: 0; z-index: 3; pointer-events: none; } | |
| 51 | 新增:.beat { position: absolute; inset: 0; will-change: opacity, transform; } | |
| 52 | 新增:.kick { position: absolute; left: 0; right: 0; top: 92px; text-align: center; font: 600 19px/1 var(--mono); letter-spacing: .3em; color: #ff7a55; } | |
| 53 | 新增:.kick i { display: inline-block; width: 9px; height: 9px; border-radius: 50%; background: #ff5a36; margin-right: 14px; vertical-align: 2px; box-shadow: 0 0 0 5px rgba(255,90,54,.18); } | |
| 54 | 新增:.head { position: absolute; left: 0; right: 0; top: 140px; text-align: center; font: 700 70px/1.25 var(--sans); color: #f7f0e9; letter-spacing: -.005em; } | |
| 55 | 新增:.head em, .q em { font-style: normal; color: #ff6a45; } | |
| 56 | 新增:.dark-card { background: linear-gradient(180deg, rgba(56,46,42,.92), rgba(32,27,25,.92)); border: 1px solid rgba(255,240,225,.10); | |
| 57 | 新增: box-shadow: 0 40px 90px rgba(0,0,0,.6), inset 0 1px 0 rgba(255,255,255,.06); border-radius: 22px; color: #f4ece4; } | |
| 58 | 新增: | |
| 59 | 新增:/* beat 1 */ | |
| 60 | 新增:#alarm { position: absolute; left: 50%; top: 404px; width: 900px; margin-left: -450px; padding: 30px 32px; display: grid; grid-template-columns: 76px 1fr auto; gap: 24px; align-items: center; | |
| 61 | 新增: background: linear-gradient(180deg, #6b2a1d, #3d1912); border-color: rgba(255,140,100,.35); } | |
| 62 | 新增:#alarm .ico { width: 76px; height: 76px; border-radius: 18px; background: rgba(255,120,80,.22); color: #ffb391; display: grid; place-items: center; } | |
| 63 | 新增:#alarm .ico svg { width: 40px; height: 40px; } | |
| 64 | 新增:#alarm h4 { margin: 0 0 8px; font: 700 36px/1.2 var(--sans); } | |
| 65 | 新增:#alarm p { margin: 0; font: 400 21px/1.4 var(--sans); color: rgba(255,230,220,.66); } | |
| 66 | 新增:#alarm time { align-self: start; font: 400 17px/1 var(--sans); color: rgba(255,230,220,.5); padding-top: 8px; } | |
| 67 | 新增:#losses { position: absolute; left: 0; right: 0; top: 652px; display: flex; justify-content: center; gap: 24px; } | |
| 68 | 新增:.loss { width: 284px; padding: 26px 28px; border-radius: 18px; text-align: left; } | |
| 69 | 新增:.loss span { display: block; font: 500 19px/1 var(--sans); color: rgba(244,236,228,.5); text-decoration: line-through; text-decoration-color: rgba(255,106,69,.7); } | |
| 70 | 新增:.loss b { display: block; margin-top: 14px; font: 700 34px/1.1 var(--sans); color: #ff6a45; } | |
| 71 | 新增: | |
| 72 | 新增:/* beat 2 */ | |
| 73 | 新增:#receipt { position: absolute; left: 50%; top: 318px; width: 780px; margin-left: -390px; padding: 34px 44px 30px; background: #f3ece2; color: #2b2522; | |
| 74 | 新增: border-radius: 6px 6px 0 0; box-shadow: 0 50px 100px rgba(0,0,0,.55); font-family: var(--mono); } | |
| 75 | 新增:#receipt::after { content: ""; position: absolute; left: 0; right: 0; bottom: -18px; height: 18px; | |
| 76 | 新增: background: linear-gradient(-45deg, transparent 12px, #f3ece2 0) 0 0/24px 18px repeat-x, linear-gradient(45deg, transparent 12px, #f3ece2 0) 0 0/24px 18px repeat-x; } | |
| 77 | 新增:#receipt .rh { display: flex; justify-content: space-between; font: 600 18px/1 var(--mono); letter-spacing: .12em; color: #8a7f75; padding-bottom: 18px; border-bottom: 2px dashed #cfc4b7; } | |
| 78 | 新增:#receipt .rr { display: flex; justify-content: space-between; align-items: baseline; padding: 15px 0; font-size: 28px; border-bottom: 1px dashed #ddd3c7; } | |
| 79 | 新增:#receipt .rr span { font-family: var(--sans); font-weight: 500; } | |
| 80 | 新增:#receipt .rt { display: flex; justify-content: space-between; align-items: baseline; padding: 20px 0 6px; font: 700 34px/1 var(--mono); color: #c2401f; } | |
| 81 | 新增:#receipt .rt span { font-family: var(--sans); } | |
| 82 | 新增:#receipt .rn { margin-top: 12px; text-align: right; font: 600 22px/1.3 var(--serif); color: #c2401f; } | |
| 83 | 新增: | |
| 84 | 新增:/* beat 3 */ | |
| 85 | 新增:#wires { position: absolute; inset: 0; width: 1920px; height: 1080px; overflow: visible; } | |
| 86 | 新增:#wires path { fill: none; stroke: #ff6a45; stroke-width: 2.5; stroke-linecap: round; opacity: .75; } | |
| 87 | 新增:#pcLabel { position: absolute; left: 700px; top: 318px; width: 270px; font: 600 18px/1 var(--mono); letter-spacing: .2em; color: rgba(244,236,228,.45); text-align: center; } | |
| 88 | 新增:.app-chip { position: absolute; left: 700px; width: 270px; height: 78px; padding: 0 22px; display: flex; align-items: center; gap: 16px; font: 600 25px/1 var(--sans); border-radius: 16px; } | |
| 89 | 新增:.app-chip i { width: 36px; height: 36px; border-radius: 10px; display: block; flex: none; } | |
| 90 | 新增:.warn { position: absolute; right: 1260px; height: 50px; padding: 0 18px; display: flex; align-items: center; gap: 10px; border-radius: 12px; white-space: nowrap; | |
| 91 | 新增: background: rgba(255,90,54,.16); border: 1px solid rgba(255,106,69,.5); color: #ffb69c; font: 600 20px/1 var(--sans); } | |
| 92 | 新增:.warn svg { width: 20px; height: 20px; } | |
| 93 | 新增:#proxyNode { position: absolute; left: 1330px; top: 470px; width: 240px; height: 240px; margin: 0; border-radius: 50%; display: grid; place-content: center; text-align: center; | |
| 94 | 新增: background: radial-gradient(circle at 50% 40%, #4a2318, #2a1510); border: 2px solid rgba(255,106,69,.6); box-shadow: 0 0 80px rgba(255,90,54,.25); color: #fff; } | |
| 95 | 新增:#proxyNode b { font: 700 32px/1.2 var(--sans); } | |
| 96 | 新增:#proxyNode span { margin-top: 10px; font: 500 17px/1.3 var(--sans); color: rgba(255,220,205,.7); } | |
| 97 | 新增: | |
| 98 | 新增:/* beat 4 */ | |
| 99 | 新增:#vmWin { position: absolute; left: 50%; top: 332px; width: 1080px; margin-left: -540px; overflow: hidden; border-radius: 16px; } | |
| 100 | 新增:#vmWin .tb { height: 56px; display: flex; align-items: center; gap: 9px; padding: 0 20px; background: rgba(255,255,255,.05); border-bottom: 1px solid rgba(255,255,255,.07); font: 500 17px var(--sans); color: rgba(244,236,228,.6); } | |
| 101 | 新增:#vmWin .tb i { width: 12px; height: 12px; border-radius: 50%; background: #5b524d; display: block; } | |
| 102 | 新增:#vmWin .tb span { margin-left: 14px; } | |
| 103 | 新增:#vmWin .bd { padding: 34px 40px 38px; display: grid; gap: 28px; } | |
| 104 | 新增:.vm-row { display: grid; grid-template-columns: 1fr auto; gap: 14px 20px; align-items: baseline; font: 500 27px/1.2 var(--sans); } | |
| 105 | 新增:.vm-row small { font: 500 22px/1 var(--mono); color: rgba(244,236,228,.55); } | |
| 106 | 新增:.vm-bar { grid-column: 1 / -1; height: 14px; border-radius: 10px; background: rgba(255,255,255,.08); overflow: hidden; } | |
| 107 | 新增:.vm-bar i { display: block; height: 100%; border-radius: 10px; background: #d9cfc5; transform-origin: 0 50%; } | |
| 108 | 新增:#vmMemRow small { color: #ff8a66; } | |
| 109 | 新增:#vmTodo { display: flex; gap: 12px; flex-wrap: wrap; padding-top: 6px; border-top: 1px solid rgba(255,255,255,.07); } | |
| 110 | 新增:#vmTodo .lbl { width: 100%; font: 500 21px/1 var(--sans); color: rgba(244,236,228,.5); padding-top: 18px; } | |
| 111 | 新增:#vmTodo span { padding: 14px 22px; border-radius: 12px; border: 1px dashed rgba(244,236,228,.35); font: 500 24px/1 var(--sans); color: rgba(244,236,228,.85); } | |
| 112 | 新增: | |
| 113 | 新增:/* beat 5 */ | |
| 114 | 新增:.q { position: absolute; left: 0; right: 0; top: 476px; text-align: center; font: 700 104px/1.2 var(--sans); color: #f7f0e9; letter-spacing: .01em; } | |
| 115 | 新增: | |
| 116 | 新增:/* ---------- act 2 · room ---------- */ | |
| 117 | 新增:#room { background: var(--paper); } | |
| 118 | 新增:#roomLight { position: absolute; inset: 0; | |
| 119 | 新增: background: radial-gradient(ellipse 55% 50% at 50% 42%, #fffdf9 0%, rgba(255,253,249,0) 70%), | |
| 120 | 新增: radial-gradient(ellipse 80% 60% at 50% 110%, rgba(239,111,69,.10), transparent 70%); } | |
| 121 | 新增:#logoWrap { position: absolute; left: 50%; top: 178px; width: 270px; height: 270px; margin-left: -135px; } | |
| 122 | 新增:#logoWrap svg, .logo-svg { width: 100%; height: 100%; overflow: visible; } | |
| 123 | 新增:.logo-svg rect { transform-box: fill-box; transform-origin: center; shape-rendering: crispEdges; } | |
| 124 | 新增:#wordmark { top: 486px; font: 700 64px/1 var(--sans); letter-spacing: -.035em; color: var(--ink); } | |
| 125 | 新增:#roomPos { top: 600px; font: 700 62px/1.2 var(--sans); color: var(--ink); letter-spacing: -.005em; } | |
| 126 | 新增:#roomPos em { font-style: normal; color: var(--accent); } | |
| 127 | 新增:#roomSub { top: 708px; font: 500 30px/1.4 var(--sans); color: var(--muted); letter-spacing: .04em; } | |
| 128 | 新增:#roomSub em { font-style: normal; color: var(--ink); font-weight: 600; } | |
| 129 | 新增: | |
| 130 | 新增:/* ---------- act 3 · app ---------- */ | |
| 131 | 新增:#app { background: radial-gradient(ellipse 70% 60% at 50% 40%, #fffdfa, var(--paper) 70%), var(--paper); } | |
| 132 | 新增:#appFloor { position: absolute; left: 50%; top: 980px; width: 1600px; height: 160px; margin-left: -800px; | |
| 133 | 新增: background: radial-gradient(closest-side, rgba(90,60,30,.16), transparent); filter: blur(10px); } | |
| 134 | 新增:#capShade { position: absolute; left: 0; right: 0; top: 0; height: 250px; z-index: 4; pointer-events: none; | |
| 135 | 新增: background: linear-gradient(180deg, var(--paper) 0%, rgba(250,248,244,.96) 52%, rgba(250,248,244,0) 100%); } | |
| 136 | 新增:#caption { position: absolute; left: 112px; top: 54px; z-index: 5; display: flex; align-items: baseline; gap: 26px; | |
| 137 | 新增: padding: 0; } | |
| 138 | 新增:#caption .num { font: 600 22px/1 var(--mono); color: var(--accent); letter-spacing: .08em; position: relative; top: -6px; } | |
| 139 | 新增:#caption .txt { display: grid; gap: 10px; } | |
| 140 | 新增:#caption .title { font: 650 40px/1.1 var(--sans); color: var(--ink); letter-spacing: -.01em; } | |
| 141 | 新增:#caption .sub { font: 400 22px/1.3 var(--sans); color: var(--muted); letter-spacing: .01em; } | |
| 142 | 新增:#caption .slot { position: relative; height: 100px; width: 1500px; } | |
| 143 | 新增:#caption .cap { position: absolute; left: 0; top: 0; display: flex; gap: 26px; align-items: baseline; } | |
| 144 | 新增:#progressDots { position: absolute; right: 112px; top: 68px; z-index: 5; display: flex; gap: 10px; } | |
| 145 | 新增:#progressDots i { display: block; width: 34px; height: 4px; border-radius: 4px; background: #e4ddd4; overflow: hidden; position: relative; } | |
| 146 | 新增:#progressDots i b { position: absolute; inset: 0; background: var(--accent); transform-origin: 0 50%; transform: scaleX(0); } | |
| 147 | 新增: | |
| 148 | 新增:#cam { position: absolute; left: 0; top: 0; transform-origin: 0 0; will-change: transform; } | |
| 149 | 新增:#win { | |
| 150 | 新增: position: relative; width: 1280px; height: 760px; border-radius: 14px; overflow: hidden; background: #fff; | |
| 151 | 新增: box-shadow: 0 0 0 1px rgba(40,25,10,.09), 0 50px 120px -20px rgba(70,40,15,.28), 0 18px 40px -12px rgba(70,40,15,.18); | |
| 152 | 新增: font-size: 14px; color: #1f1d1b; | |
| 153 | 新增:} | |
| 154 | 新增:#win svg.i { width: 17px; height: 17px; fill: none; stroke: currentColor; stroke-width: 1.7; stroke-linecap: round; stroke-linejoin: round; flex: none; } | |
| 155 | 新增:.side { position: absolute; left: 0; top: 0; bottom: 0; width: 248px; background: #f7f6f4; border-right: 1px solid #ebe8e4; } | |
| 156 | 新增:.lights { position: absolute; left: 18px; top: 17px; display: flex; gap: 8px; } | |
| 157 | 新增:.lights i { width: 12px; height: 12px; border-radius: 50%; background: #ff5f57; box-shadow: inset 0 0 0 .5px rgba(0,0,0,.15); } | |
| 158 | 新增:.lights i:nth-child(2) { background: #febc2e; } .lights i:nth-child(3) { background: #28c840; } | |
| 159 | 新增:.brand { position: absolute; left: 18px; top: 46px; right: 16px; display: flex; align-items: center; gap: 10px; font: 650 18px/1 var(--sans); } | |
| 160 | 新增:.brand .mark { width: 22px; height: 22px; } | |
| 161 | 新增:.brand .collapse { margin-left: auto; color: #6c6763; } | |
| 162 | 新增:.nav { position: absolute; left: 12px; right: 12px; top: 88px; display: grid; gap: 2px; } | |
| 163 | 新增:.nav div, .proj div { display: flex; align-items: center; gap: 10px; height: 38px; padding: 0 12px; border-radius: 9px; color: #2a2724; } | |
| 164 | 新增:.nav .dim { color: #b4aea8; } | |
| 165 | 新增:.nav .on { background: #ebe9e6; } | |
| 166 | 新增:.nav kbd { margin-left: auto; font: 400 12px var(--sans); color: #9a948e; } | |
| 167 | 新增:.sec { position: absolute; left: 24px; right: 24px; top: 262px; display: flex; justify-content: space-between; color: #6c6763; font-size: 13px; } | |
| 168 | 新增:.proj { position: absolute; left: 12px; right: 12px; top: 292px; display: grid; gap: 2px; } | |
| 169 | 新增:.proj .child { padding-left: 34px; font-size: 13px; color: #8b8580; position: relative; } | |
| 170 | 新增:.proj .child .alt { position: absolute; left: 0; top: 0; height: 38px; width: 100%; padding-left: 12px; display: flex; align-items: center; gap: 9px; | |
| 171 | 新增: border-radius: 9px; color: #2a2724; background: #ebe9e6; font-size: 14px; } | |
| 172 | 新增:.side-foot { position: absolute; left: 12px; right: 12px; bottom: 12px; border-top: 1px solid #e6e2dd; padding-top: 10px; display: grid; gap: 2px; } | |
| 173 | 新增:.side-foot div { display: flex; align-items: center; gap: 10px; height: 36px; padding: 0 12px; font-size: 13.5px; color: #2a2724; } | |
| 174 | 新增:.side-foot .dot { width: 7px; height: 7px; border-radius: 50%; background: #b7b1ab; margin: 0 4px 0 2px; } | |
| 175 | 新增:.side-foot kbd { margin-left: auto; font: 400 12px var(--sans); color: #9a948e; } | |
| 176 | 新增:.side-foot .shield { margin-left: auto; color: #6c6763; } | |
| 177 | 新增:.main { position: absolute; left: 248px; right: 0; top: 0; bottom: 0; } | |
| 178 | 新增:.topbar { position: absolute; left: 0; right: 0; top: 0; height: 58px; display: flex; align-items: center; padding: 0 22px; gap: 10px; } | |
| 179 | 新增:.crumb { display: flex; align-items: center; gap: 10px; font-weight: 500; } | |
| 180 | 新增:.crumb .sep, .crumb .leaf { color: #2a2724; } | |
| 181 | 新增:.top-actions { margin-left: auto; display: flex; gap: 12px; align-items: center; color: #3c3936; } | |
| 182 | 新增:.pill { display: flex; align-items: center; gap: 7px; height: 32px; padding: 0 12px; border: 1px solid #e3dfda; border-radius: 9px; font-size: 13px; background: #fff; } | |
| 183 | 新增:.status { position: absolute; left: 0; right: 0; bottom: 0; height: 32px; border-top: 1px solid #ece9e5; display: flex; align-items: center; | |
| 184 | 新增: padding: 0 18px; gap: 0; font-size: 12px; color: #4a4642; background: #fff; } | |
| 185 | 新增:.status .it { display: flex; align-items: center; gap: 6px; padding: 0 12px; height: 16px; border-left: 1px solid #e3dfda; position: relative; } | |
| 186 | 新增:.status .it:first-child { border-left: 0; padding-left: 2px; } | |
| 187 | 新增:.status svg.i { width: 13px !important; height: 13px !important; } | |
| 188 | 新增:.status .right { margin-left: auto; display: flex; } | |
| 189 | 新增:.flip { position: relative; display: inline-block; overflow: hidden; height: 16px; line-height: 16px; vertical-align: top; } | |
| 190 | 新增:.flip span { display: block; white-space: nowrap; } | |
| 191 | 新增:.flip span + span { position: absolute; left: 0; top: 0; } | |
| 192 | 新增:.hl { position: absolute; inset: -6px -4px; border-radius: 7px; background: rgba(185,80,50,.10); box-shadow: 0 0 0 1.5px rgba(185,80,50,.45); opacity: 0; } | |
| 193 | 新增: | |
| 194 | 新增:/* hero (first run) */ | |
| 195 | 新增:.view { position: absolute; left: 0; right: 0; top: 58px; bottom: 32px; } | |
| 196 | 新增:.hero { text-align: center; } | |
| 197 | 新增:.hero .shield-big { width: 44px; height: 44px; margin: 74px auto 0; color: #232120; } | |
| 198 | 新增:#win .hero .shield-big svg.i { width: 44px; height: 44px; stroke-width: 1.5; } | |
| 199 | 新增:.hero h2 { margin: 18px 0 0; font: 700 34px/1.2 var(--sans); letter-spacing: -.01em; } | |
| 200 | 新增:.hero .lead { margin-top: 18px; color: #3c3936; font-size: 14.5px; } | |
| 201 | 新增:.steps { margin: 24px auto 0; display: flex; justify-content: center; gap: 26px; font-size: 13.5px; color: #3c3936; } | |
| 202 | 新增:.steps span { display: flex; align-items: center; gap: 8px; } | |
| 203 | 新增:.steps b { width: 22px; height: 22px; border-radius: 50%; border: 1px solid #cfcac4; display: grid; place-items: center; font: 500 12px var(--sans); position: relative; background: #fff; } | |
| 204 | 新增:.steps b.on { background: #1d1b1a; color: #fff; border-color: #1d1b1a; } | |
| 205 | 新增:.steps b.done { background: var(--ok); border-color: var(--ok); color: #fff; } | |
| 206 | 新增:.steps b svg.i { width: 13px !important; height: 13px !important; stroke-width: 2.4 !important; } | |
| 207 | 新增:.steps .strong { font-weight: 600; color: #1d1b1a; } | |
| 208 | 新增:.card { position: relative; width: 500px; margin: 26px auto 0; border: 1px solid #e3dfda; border-radius: 16px; padding: 22px 22px 18px; text-align: left; background: #fff; } | |
| 209 | 新增:.card .head { display: flex; gap: 14px; align-items: flex-start; } | |
| 210 | 新增:#win .card .head svg.i { width: 24px; height: 24px; margin-top: 4px; } | |
| 211 | 新增:.card .t { font: 600 15px/1.4 var(--sans); } | |
| 212 | 新增:.card .d { font-size: 12.5px; color: #6c6763; margin-top: 4px; } | |
| 213 | 新增:.card .row { margin-top: 22px; display: flex; align-items: center; justify-content: space-between; height: 38px; } | |
| 214 | 新增:.card .state { position: relative; font-size: 12.5px; color: #6c6763; height: 20px; width: 260px; } | |
| 215 | 新增:.card .state > div { position: absolute; left: 0; top: 0; display: flex; align-items: center; gap: 8px; white-space: nowrap; } | |
| 216 | 新增:.card .state i { width: 6px; height: 6px; border-radius: 50%; background: #b7b1ab; display: block; } | |
| 217 | 新增:.card .state .ready i { background: var(--ok); box-shadow: 0 0 0 3px rgba(47,138,76,.15); } | |
| 218 | 新增:.card .state .ready b { color: #1d1b1a; font-weight: 600; } | |
| 219 | 新增:.btn { position: relative; height: 38px; padding: 0 16px; border-radius: 9px; background: #1d1b1a; color: #fff; display: flex; align-items: center; gap: 8px; font-size: 13.5px; font-weight: 500; } | |
| 220 | 新增:.btn-swap { position: relative; width: 150px; height: 38px; } | |
| 221 | 新增:.btn-swap .btn { position: absolute; right: 0; top: 0; white-space: nowrap; } | |
| 222 | 新增:.hero .foot { margin-top: 26px; font-size: 12.5px; color: #3c3936; } | |
| 223 | 新增: | |
| 224 | 新增:/* proxy modal */ | |
| 225 | 新增:#modalShade { position: absolute; inset: 0; background: rgba(30,24,20,.18); } | |
| 226 | 新增:#modal { position: absolute; left: 50%; top: 92px; width: 560px; margin-left: -280px; background: #fff; border-radius: 16px; | |
| 227 | 新增: box-shadow: 0 0 0 1px rgba(0,0,0,.06), 0 40px 80px -10px rgba(40,25,10,.32); overflow: hidden; } | |
| 228 | 新增:#modal .mh { display: flex; align-items: center; justify-content: space-between; padding: 20px 22px 16px; border-bottom: 1px solid #efebe6; font: 650 18px var(--sans); } | |
| 229 | 新增:#modal .src { margin: 16px 22px 10px; display: flex; align-items: center; gap: 12px; padding: 12px 14px; border-radius: 11px; background: #f7f5f2; font-size: 13px; } | |
| 230 | 新增:#modal .src .tag { margin-left: auto; color: var(--ok); font-size: 12.5px; display: flex; align-items: center; gap: 5px; } | |
| 231 | 新增:#modal .lbl { margin: 14px 22px 6px; font-size: 12px; color: #8b8580; letter-spacing: .04em; } | |
| 232 | 新增:#modal .nodes { margin: 0 14px; display: grid; gap: 2px; } | |
| 233 | 新增:#modal .node { position: relative; display: flex; align-items: center; gap: 12px; height: 46px; padding: 0 12px; border-radius: 10px; font-size: 14px; } | |
| 234 | 新增:#modal .node .sel { position: absolute; inset: 0; border-radius: 10px; background: #f3f0ec; box-shadow: inset 0 0 0 1.5px #1d1b1a; opacity: 0; } | |
| 235 | 新增:#modal .node .radio { position: relative; width: 18px; height: 18px; border-radius: 50%; border: 1.5px solid #c9c3bc; display: grid; place-items: center; } | |
| 236 | 新增:#modal .node .radio i { width: 8px; height: 8px; border-radius: 50%; background: #1d1b1a; transform: scale(0); } | |
| 237 | 新增:#modal .node .ms { margin-left: auto; position: relative; font: 500 12.5px var(--mono); color: #6c6763; display: flex; align-items: center; gap: 8px; } | |
| 238 | 新增:#modal .node .ms em { width: 6px; height: 6px; border-radius: 50%; background: var(--ok); display: block; } | |
| 239 | 新增:#modal .node .ms em.warn { background: #d29a2e; } | |
| 240 | 新增:#modal .node > span { position: relative; } | |
| 241 | 新增:#modal .mf { margin-top: 14px; padding: 14px 22px; border-top: 1px solid #efebe6; display: flex; align-items: center; justify-content: space-between; font-size: 12.5px; color: #6c6763; } | |
| 242 | 新增: | |
| 243 | 新增:/* launch panel */ | |
| 244 | 新增:.launch { padding-top: 34px; } | |
| 245 | 新增:.panel { width: 820px; margin: 0 auto; border: 1px solid #e3dfda; border-radius: 16px; overflow: hidden; background: #fff; } | |
| 246 | 新增:.ph { display: flex; gap: 14px; align-items: center; padding: 20px 24px; border-bottom: 1px solid #efebe6; position: relative; } | |
| 247 | 新增:.ph .badge { position: relative; width: 44px; height: 44px; border-radius: 12px; background: #f4f1ed; display: grid; place-items: center; } | |
| 248 | 新增:#win .ph .badge svg.i { width: 24px; height: 24px; } | |
| 249 | 新增:.ph .badge .okb { position: absolute; inset: 0; border-radius: 12px; background: #e9f4ec; color: var(--ok); display: grid; place-items: center; opacity: 0; } | |
| 250 | 新增:.ph .tt { position: relative; height: 46px; flex: 1; } | |
| 251 | 新增:.ph .tt > div { position: absolute; left: 0; top: 0; } | |
| 252 | 新增:.ph .tt .a { font: 650 17px/1.4 var(--sans); } | |
| 253 | 新增:.ph .tt .b { font-size: 13px; color: #6c6763; margin-top: 3px; } | |
| 254 | 新增:.ph .count { font: 500 13px var(--mono); color: #6c6763; } | |
| 255 | 新增:.prog { padding: 14px 24px 6px; display: grid; gap: 10px; } | |
| 256 | 新增:.prog .p { display: grid; grid-template-columns: 20px 150px 1fr 54px; align-items: center; gap: 12px; font-size: 13px; height: 22px; } | |
| 257 | 新增:.prog .bar { height: 5px; border-radius: 5px; background: #efebe6; overflow: hidden; } | |
| 258 | 新增:.prog .bar i { display: block; height: 100%; background: #1d1b1a; transform-origin: 0 50%; transform: scaleX(0); } | |
| 259 | 新增:.prog .pct { font: 500 12px var(--mono); color: #8b8580; text-align: right; } | |
| 260 | 新增:.st { position: relative; width: 18px; height: 18px; } | |
| 261 | 新增:.st > * { position: absolute; inset: 0; } | |
| 262 | 新增:.st .spin { border-radius: 50%; border: 2px solid #e2ddd7; border-top-color: #1d1b1a; } | |
| 263 | 新增:.st .ok { border-radius: 50%; background: var(--ok); color: #fff; display: grid; place-items: center; transform: scale(0); } | |
| 264 | 新增:.st .ok svg.i { width: 11px !important; height: 11px !important; stroke-width: 3 !important; } | |
| 265 | 新增:.st .wait { border-radius: 50%; border: 2px solid #e8e4df; } | |
| 266 | 新增:.checks-h { padding: 14px 24px 8px; display: flex; justify-content: space-between; font-size: 12.5px; color: #8b8580; border-top: 1px solid #f2efeb; margin-top: 10px; } | |
| 267 | 新增:.checks { padding: 0 16px 16px; display: grid; grid-template-columns: 1fr 1fr; column-gap: 12px; row-gap: 2px; } | |
| 268 | 新增:.ck { display: flex; align-items: center; gap: 12px; height: 38px; padding: 0 10px; border-radius: 9px; font-size: 13.5px; position: relative; } | |
| 269 | 新增:.ck .res { margin-left: auto; position: relative; width: 60px; height: 16px; font-size: 12.5px; text-align: right; } | |
| 270 | 新增:.ck .res span { position: absolute; right: 0; top: 0; white-space: nowrap; } | |
| 271 | 新增:.ck .res .y { color: var(--ok); font-weight: 500; } | |
| 272 | 新增:.ck .res .n { color: #a39d97; } | |
| 273 | 新增:.ck .flash { position: absolute; inset: 0; border-radius: 9px; background: rgba(47,138,76,.08); opacity: 0; } | |
| 274 | 新增: | |
| 275 | 新增:/* terminal */ | |
| 276 | 新增:.term-bar { position: absolute; left: 0; right: 0; top: 0; height: 46px; border-top: 1px solid #efebe6; border-bottom: 1px solid #efebe6; display: flex; align-items: center; padding: 0 18px; gap: 10px; font: 400 13px var(--mono); color: #3c3936; } | |
| 277 | 新增:.term-bar .r { margin-left: auto; display: flex; align-items: center; gap: 14px; font: 400 12.5px var(--sans); } | |
| 278 | 新增:.term { position: absolute; left: 36px; right: 36px; top: 76px; bottom: 0; font: 400 14.5px/1.72 var(--mono); color: #23201e; } | |
| 279 | 新增:.term .ln, .cc { white-space: pre; } | |
| 280 | 新增:.term .acc { color: #9a4a2c; font-weight: 600; } | |
| 281 | 新增:.term .g { color: #6f8f3a; } | |
| 282 | 新增:.term .m { color: #8b8580; } | |
| 283 | 新增:.term .ln { height: 25px; } | |
| 284 | 新增:.caret { display: inline-block; width: 9px; height: 19px; background: #23201e; vertical-align: -4px; margin-left: 1px; } | |
| 285 | 新增:.cc { margin: 6px 0 8px; width: 560px; border: 1.5px solid #d97757; border-radius: 10px; padding: 10px 18px; line-height: 1.7; } | |
| 286 | 新增:.cc .w { color: #c25f3c; font-weight: 600; } | |
| 287 | 新增:.reply .dot { color: #23201e; } | |
| 288 | 新增:.reply .tool { font-weight: 600; } | |
| 289 | 新增: | |
| 290 | 新增:/* cursor */ | |
| 291 | 新增:#cursor { position: absolute; left: 0; top: 0; width: 26px; height: 26px; z-index: 30; pointer-events: none; will-change: transform; } | |
| 292 | 新增:#cursor svg { width: 26px; height: 26px; filter: drop-shadow(0 2px 3px rgba(0,0,0,.3)); } | |
| 293 | 新增:#ripple { position: absolute; left: 0; top: 0; width: 44px; height: 44px; margin: -22px 0 0 -22px; border-radius: 50%; border: 2px solid rgba(185,80,50,.55); z-index: 29; opacity: 0; } | |
| 294 | 新增: | |
| 295 | 新增:/* ---------- act 4 · perks ---------- */ | |
| 296 | 新增:#perks { background: radial-gradient(ellipse 70% 60% at 50% 40%, #fffdfa, var(--paper) 70%), var(--paper); } | |
| 297 | 新增:#perksHead { top: 196px; font: 700 66px/1.2 var(--sans); color: var(--ink); } | |
| 298 | 新增:#perksHead em { font-style: normal; color: var(--accent); } | |
| 299 | 新增:#perkRow { position: absolute; left: 0; right: 0; top: 400px; display: flex; justify-content: center; gap: 26px; } | |
| 300 | 新增:.perk { width: 380px; height: 350px; padding: 38px 34px; background: #fff; border-radius: 24px; box-shadow: 0 0 0 1px rgba(40,25,10,.07), 0 30px 70px -24px rgba(70,40,15,.22); } | |
| 301 | 新增:.perk .pi { width: 72px; height: 72px; border-radius: 18px; background: #f8ece6; color: var(--accent); display: grid; place-items: center; } | |
| 302 | 新增:.perk .pi svg { width: 40px !important; height: 40px !important; fill: none; stroke: currentColor; stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round; } | |
| 303 | 新增:.perk h3 { margin: 30px 0 14px; font: 700 34px/1.25 var(--sans); color: var(--ink); letter-spacing: -.01em; } | |
| 304 | 新增:.perk p { margin: 0; font: 400 22px/1.6 var(--sans); color: var(--muted); } | |
| 305 | 新增: | |
| 306 | 新增:/* ---------- act 5 · letter ---------- */ | |
| 307 | 新增:#letter { background: radial-gradient(ellipse 70% 80% at 30% 50%, #2b1d15 0%, #17110d 60%, #0e0a08 100%); } | |
| 308 | 新增:#art { position: absolute; left: 150px; top: 120px; width: 840px; height: 840px; overflow: hidden; border-radius: 6px; | |
| 309 | 新增: -webkit-mask-image: radial-gradient(ellipse 70% 70% at 50% 50%, #000 58%, transparent 100%); | |
| 310 | 新增: mask-image: radial-gradient(ellipse 70% 70% at 50% 50%, #000 58%, transparent 100%); } | |
| 311 | 新增:#art img { width: 100%; height: 100%; display: block; will-change: transform; } | |
| 312 | 新增:#artLight { position: absolute; inset: 0; background: linear-gradient(105deg, transparent 30%, rgba(255,210,160,.35) 48%, transparent 66%); mix-blend-mode: screen; } | |
| 313 | 新增:#letterText { position: absolute; left: 1090px; top: 360px; font-family: var(--serif); color: var(--cream); } | |
| 314 | 新增:#letterText .l { display: block; font-size: 58px; font-weight: 600; line-height: 1.75; letter-spacing: .05em; } | |
| 315 | 新增:#letterText .l em { font-style: normal; color: #f5a37c; } | |
| 316 | 新增:#letterKicker { position: absolute; left: 1094px; top: 300px; font: 500 18px/1 var(--mono); letter-spacing: .3em; color: rgba(243,235,225,.42); } | |
| 317 | 新增: | |
| 318 | 新增:/* ---------- act 6 · end ---------- */ | |
| 319 | 新增:#end { background: var(--paper); } | |
| 320 | 新增:#endLogo { position: absolute; left: 50%; top: 286px; width: 180px; height: 180px; margin-left: -90px; } | |
| 321 | 新增:#endWord { top: 500px; font: 700 84px/1 var(--sans); letter-spacing: -.035em; color: var(--ink); } | |
| 322 | 新增:#endSub { top: 612px; font: 500 30px/1.4 var(--serif); color: #4d4640; letter-spacing: .08em; } | |
| 323 | 新增:#endPlat { top: 702px; display: flex; justify-content: center; gap: 18px; font: 500 20px/1 var(--sans); color: var(--muted); } | |
| 324 | 新增:#endPlat span { padding: 10px 18px; border: 1px solid #e2dbd2; border-radius: 999px; background: #fff; } | |
| 325 | 新增:#endGit { top: 836px; font: 500 20px/1 var(--mono); color: #8d847b; letter-spacing: .02em; } | |
| 326 | 新增:#endUrl { top: 786px; font: 500 24px/1 var(--mono); color: var(--accent); letter-spacing: .02em; } | |
| 327 | 新增:#endNote { top: 978px; font: 400 15px/1.5 var(--sans); color: #a39b92; letter-spacing: .04em; } | |
| 328 | 新增: | |
| 329 | 新增:/* ---------- preview controls ---------- */ | |
| 330 | 新增:#controls { position: fixed; left: 0; right: 0; bottom: 0; padding: 14px 20px; display: flex; align-items: center; gap: 14px; | |
| 331 | 新增: background: linear-gradient(transparent, rgba(0,0,0,.75)); color: #eee; font: 500 13px var(--mono); z-index: 100; opacity: 0; transition: opacity .25s; } | |
| 332 | 新增:body:hover #controls { opacity: 1; } | |
| 333 | 新增:#controls button { all: unset; cursor: pointer; padding: 6px 12px; border-radius: 6px; background: rgba(255,255,255,.12); } | |
| 334 | 新增:#controls input { flex: 1; accent-color: #ef6f45; } | |
| 335 | 新增:body.render #controls { display: none; } | |
| 336 | 新增:</style> | |
| 337 | 新增:</head> | |
| 338 | 新增:<body> | |
| 339 | 新增:<div id="viewport"> | |
| 340 | 新增:<div id="stage"> | |
| 341 | 新增: | |
| 342 | 新增: <!-- ============ ACT 1 · THE PROBLEM ============ --> | |
| 343 | 新增: <section class="layer" id="night"> | |
| 344 | 新增: <div id="nightGlow"></div> | |
| 345 | 新增: | |
| 346 | 新增: <div class="beat" id="b1"> | |
| 347 | 新增: <div class="kick"><i></i>痛点 01 · 封号</div> | |
| 348 | 新增: <div class="head"><span data-split>一次封号,</span><em data-split>钱和进度一起清零。</em></div> | |
| 349 | 新增: <div id="alarm" class="dark-card"><div class="ico"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"><circle cx="12" cy="12" r="8.5"/><path d="M6 6l12 12"/></svg></div><div><h4>你的 Claude 账户已被停用</h4><p>检测到异常活动,账户已暂停使用。</p></div><time>刚刚</time></div> | |
| 350 | 新增: <div id="losses"> | |
| 351 | 新增: <div class="loss dark-card"><span>Max 订阅</span><b>$200 打水漂</b></div> | |
| 352 | 新增: <div class="loss dark-card"><span>API 余额</span><b>无法再用</b></div> | |
| 353 | 新增: <div class="loss dark-card"><span>手上的项目</span><b>被迫停摆</b></div> | |
| 354 | 新增: </div> | |
| 355 | 新增: </div> | |
| 356 | 新增: | |
| 357 | 新增: <div class="beat" id="b2"> | |
| 358 | 新增: <div class="kick"><i></i>痛点 02 · 折腾</div> | |
| 359 | 新增: <div class="head"><span data-split>VPS、指纹浏览器,</span><em data-split>甚至远程租 Mac mini。</em></div> | |
| 360 | 新增: <div id="receipt"> | |
| 361 | 新增: <div class="rh"><span>每月账单</span><span>只为用上 CLAUDE</span></div> | |
| 362 | 新增: <div class="rr"><span>海外 VPS</span><b>¥68 / 月</b></div> | |
| 363 | 新增: <div class="rr"><span>指纹浏览器</span><b>¥99 / 月</b></div> | |
| 364 | 新增: <div class="rr"><span>住宅 IP</span><b>¥120 / 月</b></div> | |
| 365 | 新增: <div class="rr"><span>远程租用 Mac mini</span><b>¥399 / 月</b></div> | |
| 366 | 新增: <div class="rt"><span>合计</span><b>¥686 / 月</b></div> | |
| 367 | 新增: <div class="rn">+ 无数个折腾到深夜的晚上</div> | |
| 368 | 新增: </div> | |
| 369 | 新增: </div> | |
| 370 | 新增: | |
| 371 | 新增: <div class="beat" id="b3"> | |
| 372 | 新增: <div class="kick"><i></i>痛点 03 · 网络</div> | |
| 373 | 新增: <div class="head"><span data-split>开着全局代理,</span><em data-split>整台电脑都跟着绕路。</em></div> | |
| 374 | 新增: <svg id="wires" viewBox="0 0 1920 1080"></svg> | |
| 375 | 新增: <div id="pcLabel">你的电脑</div> | |
| 376 | 新增: <div id="appChips"></div> | |
| 377 | 新增: <div id="proxyNode"><b>全局代理</b><span>所有流量<br />都走海外出口</span></div> | |
| 378 | 新增: </div> | |
| 379 | 新增: | |
| 380 | 新增: <div class="beat" id="b4"> | |
| 381 | 新增: <div class="kick"><i></i>痛点 04 · 虚拟机</div> | |
| 382 | 新增: <div class="head"><span data-split>换成传统虚拟机?</span><em data-split>又重又慢,还得自己配。</em></div> | |
| 383 | 新增: <div id="vmWin" class="dark-card"> | |
| 384 | 新增: <div class="tb"><i></i><i></i><i></i><span>虚拟机安装向导</span></div> | |
| 385 | 新增: <div class="bd"> | |
| 386 | 新增: <div class="vm-row"><span>ubuntu-24.04-desktop.iso</span><small id="vmEta">剩余 1 小时 52 分</small><div class="vm-bar"><i id="vmDl"></i></div></div> | |
| 387 | 新增: <div class="vm-row" id="vmMemRow"><span>分配内存</span><small id="vmMemTxt">4 GB / 16 GB</small><div class="vm-bar"><i id="vmMem"></i></div></div> | |
| 388 | 新增: <div id="vmTodo"><div class="lbl">装好之后,你还得自己配:</div><span>代理</span><span>时区与语言</span><span>浏览器指纹</span><span>Claude Code</span></div> | |
| 389 | 新增: </div> | |
| 390 | 新增: </div> | |
| 391 | 新增: </div> | |
| 392 | 新增: | |
| 393 | 新增: <div class="beat" id="b5"> | |
| 394 | 新增: <div class="q"><span data-split>就不能,</span><em data-split>简单一点吗?</em></div> | |
| 395 | 新增: </div> | |
| 396 | 新增: | |
| 397 | 新增: <div id="flash"></div> | |
| 398 | 新增: </section> | |
| 399 | 新增: | |
| 400 | 新增: <!-- ============ ACT 2 · ROOM ============ --> | |
| 401 | 新增: <section class="layer" id="room"> | |
| 402 | 新增: <div id="roomLight"></div> | |
| 403 | 新增: <div id="logoWrap"></div> | |
| 404 | 新增: <div class="center" id="wordmark" data-split>Claude Cage</div> | |
| 405 | 新增: <div class="center" id="roomPos"><span data-split>为 Claude 量身定制的</span><em data-split>轻量虚拟机</em></div> | |
| 406 | 新增: <div class="center" id="roomSub"><span data-split>开箱即用,一切都已备好。你只需要,</span><em data-split>配置自己的代理。</em></div> | |
| 407 | 新增: </section> | |
| 408 | 新增: | |
| 409 | 新增: <!-- ============ ACT 3 · APP ============ --> | |
| 410 | 新增: <section class="layer" id="app"> | |
| 411 | 新增: <div id="appFloor"></div> | |
| 412 | 新增: <div id="capShade"></div> | |
| 413 | 新增: <div id="caption"> | |
| 414 | 新增: <div class="slot"> | |
| 415 | 新增: <div class="cap" data-cap="0"><span class="num">01</span><div class="txt"><div class="title">你只需要:配置自己的代理</div><div class="sub">导入订阅,选个节点。时区和语言自动跟随出口 IP。</div></div></div> | |
| 416 | 新增: <div class="cap" data-cap="1"><span class="num">02</span><div class="txt"><div class="title">自带泄漏审查</div><div class="sub">11 项关键检查,有一项没过,环境就不连外网。</div></div></div> | |
| 417 | 新增: <div class="cap" data-cap="2"><span class="num">03</span><div class="txt"><div class="title">与主机隔离,日常照常用</div><div class="sub">终端、浏览器、编辑器都在 Cage 里。你的电脑不用开全局代理。</div></div></div> | |
| 418 | 新增: </div> | |
| 419 | 新增: </div> | |
| 420 | 新增: <div id="progressDots"><i><b></b></i><i><b></b></i><i><b></b></i></div> | |
| 421 | 新增: | |
| 422 | 新增: <div id="cam"> | |
| 423 | 新增: <div id="win"> | |
| 424 | 新增: <aside class="side"> | |
| 425 | 新增: <div class="lights"><i></i><i></i><i></i></div> | |
| 426 | 新增: <div class="brand"><svg class="mark logo-svg" viewBox="0 0 926 926" id="miniLogo"></svg>Cage<svg class="i collapse" viewBox="0 0 24 24"><rect x="3.5" y="4.5" width="17" height="15" rx="2.5"/><path d="M9 4.5v15M15 10l-2 2 2 2"/></svg></div> | |
| 427 | 新增: <div class="nav"> | |
| 428 | 新增: <div class="on" id="navHome"><svg class="i" viewBox="0 0 24 24"><path d="M3.5 10.5 12 3.5l8.5 7V20a1 1 0 0 1-1 1H15v-6H9v6H4.5a1 1 0 0 1-1-1z"/></svg>工作台</div> | |
| 429 | 新增: <div class="dim" data-enable><svg class="i" viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.5"/><path d="M3.5 12h17M12 3.5c2.6 2.6 3.6 5.3 3.6 8.5s-1 5.9-3.6 8.5c-2.6-2.6-3.6-5.3-3.6-8.5s1-5.9 3.6-8.5z"/></svg>浏览器</div> | |
| 430 | 新增: <div class="dim" data-enable><svg class="i" viewBox="0 0 24 24"><path d="M3.5 7A1.5 1.5 0 0 1 5 5.5h4l2 2.5h8a1.5 1.5 0 0 1 1.5 1.5v9A1.5 1.5 0 0 1 19 20H5a1.5 1.5 0 0 1-1.5-1.5z"/></svg>打开项目<kbd>⌘O</kbd></div> | |
| 431 | 新增: <div class="dim" data-enable><svg class="i" viewBox="0 0 24 24"><path d="M14 3.5H6.5a1 1 0 0 0-1 1v15a1 1 0 0 0 1 1h11a1 1 0 0 0 1-1V8z"/><path d="M14 3.5V8h4.5M10.5 12l-2 2 2 2M13.5 12l2 2-2 2"/></svg>项目文件<span style="color:#6c6763">↗</span></div> | |
| 432 | 新增: </div> | |
| 433 | 新增: <div class="sec"><span>项目</span><span>+</span></div> | |
| 434 | 新增: <div class="proj"> | |
| 435 | 新增: <div><svg class="i" viewBox="0 0 24 24" style="width:13px;height:13px"><path d="M6 9l6 6 6-6"/></svg><svg class="i" viewBox="0 0 24 24"><path d="M3.5 7A1.5 1.5 0 0 1 5 5.5h4l2 2.5h8a1.5 1.5 0 0 1 1.5 1.5v9A1.5 1.5 0 0 1 19 20H5a1.5 1.5 0 0 1-1.5-1.5z"/></svg><b style="font-weight:600">hello-cage</b><span style="margin-left:auto;color:#6c6763" id="projPlus">+</span></div> | |
| 436 | 新增: <div class="child"><span id="childHint">启动后可新建终端</span><div class="alt" id="childTerm"><svg class="i" viewBox="0 0 24 24"><rect x="3.5" y="4.5" width="17" height="15" rx="2.5"/><path d="M7.5 9.5l3 2.5-3 2.5M12.5 15h4"/></svg>开发终端<span style="margin-left:auto;color:#6c6763;letter-spacing:1px">···</span></div></div> | |
| 437 | 新增: </div> | |
| 438 | 新增: <div class="side-foot"> | |
| 439 | 新增: <div><i class="dot" id="envDot"></i><span class="flip" id="envFlip" style="width:120px"><span>已停止</span><span>启动中…</span><span>环境运行正常</span></span><svg class="i shield" viewBox="0 0 24 24"><path d="M12 3.5l7.5 2.8v5.6c0 4.3-3.2 7.6-7.5 8.6-4.3-1-7.5-4.3-7.5-8.6V6.3z"/></svg></div> | |
| 440 | 新增: <div><svg class="i" viewBox="0 0 24 24"><path d="M4 7.5h9M17 7.5h3M4 16.5h3M11 16.5h9"/><circle cx="15" cy="7.5" r="2"/><circle cx="9" cy="16.5" r="2"/></svg>设置<kbd>⌘,</kbd></div> | |
| 441 | 新增: </div> | |
| 442 | 新增: </aside> | |
| 443 | 新增: | |
| 444 | 新增: <div class="main"> | |
| 445 | 新增: <div class="topbar"> | |
| 446 | 新增: <div class="crumb"><svg class="i" viewBox="0 0 24 24"><path d="M3.5 7A1.5 1.5 0 0 1 5 5.5h4l2 2.5h8a1.5 1.5 0 0 1 1.5 1.5v9A1.5 1.5 0 0 1 19 20H5a1.5 1.5 0 0 1-1.5-1.5z"/></svg>hello-cage<span id="crumbLeaf" style="display:flex;gap:10px;align-items:center"><svg class="i" viewBox="0 0 24 24" style="width:14px;height:14px"><path d="M9 6l6 6-6 6"/></svg>开发终端</span></div> | |
| 447 | 新增: <div class="top-actions"><div class="pill"><svg class="i" viewBox="0 0 24 24" style="width:15px;height:15px"><path d="M14 3.5H6.5a1 1 0 0 0-1 1v15a1 1 0 0 0 1 1h11a1 1 0 0 0 1-1V8z"/><path d="M14 3.5V8h4.5M10.5 12l-2 2 2 2M13.5 12l2 2-2 2"/></svg>打开文件</div><svg class="i" viewBox="0 0 24 24"><rect x="3.5" y="4.5" width="17" height="15" rx="2.5"/><path d="M7.5 9.5l3 2.5-3 2.5M12.5 15h4"/></svg><svg class="i" viewBox="0 0 24 24" id="topX"><path d="M6.5 6.5l11 11M17.5 6.5l-11 11"/></svg></div> | |
| 448 | 新增: </div> | |
| 449 | 新增: | |
| 450 | 新增: <!-- first run --> | |
| 451 | 新增: <div class="view hero" id="viewHero"> | |
| 452 | 新增: <div class="shield-big"><svg class="i" viewBox="0 0 24 24"><path d="M12 3.5l7.5 2.8v5.6c0 4.3-3.2 7.6-7.5 8.6-4.3-1-7.5-4.3-7.5-8.6V6.3z"/></svg></div> | |
| 453 | 新增: <h2>为 Claude 准备独立工作区</h2> | |
| 454 | 新增: <div class="lead">先连接你的代理,再启动浏览器、终端和编辑器。无需安装额外的代理软件。</div> | |
| 455 | 新增: <div class="steps"> | |
| 456 | 新增: <span id="st1"><b class="on"><span class="n">1</span></b><span class="strong">配置代理</span></span> | |
| 457 | 新增: <span id="st2"><b><span class="n">2</span></b><span>启动环境</span></span> | |
| 458 | 新增: <span><b>3</b><span>开始工作</span></span> | |
| 459 | 新增: </div> | |
| 460 | 新增: <div class="card"> | |
| 461 | 新增: <div class="head"><svg class="i" viewBox="0 0 24 24"><path d="M12 3.5l7.5 2.8v5.6c0 4.3-3.2 7.6-7.5 8.6-4.3-1-7.5-4.3-7.5-8.6V6.3z"/></svg><div><div class="t">Cage 隔离环境</div><div class="d">自备代理订阅、YAML 配置或节点</div></div></div> | |
| 462 | 新增: <div class="row"> | |
| 463 | 新增: <div class="state"><div class="wait" id="stateWait"><i></i>等待配置代理</div><div class="ready" id="stateReady"><i></i>代理已就绪 · <b>美国 · 洛杉矶 01</b></div></div> | |
| 464 | 新增: <div class="btn-swap"> | |
| 465 | 新增: <div class="btn" id="btnProxy"><svg class="i" viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.5"/><path d="M3.5 12h17M12 3.5c2.6 2.6 3.6 5.3 3.6 8.5s-1 5.9-3.6 8.5c-2.6-2.6-3.6-5.3-3.6-8.5s1-5.9 3.6-8.5z"/></svg>配置网络与代理</div> | |
| 466 | 新增: <div class="btn" id="btnLaunch"><svg class="i" viewBox="0 0 24 24"><path d="M8 5.5v13l10.5-6.5z"/></svg>启动 Cage 环境</div> | |
| 467 | 新增: </div> | |
| 468 | 新增: </div> | |
| 469 | 新增: </div> | |
| 470 | 新增: <div class="foot">Cage 不提供代理或 Claude 账户。连接后,在 Cage 内完成 Claude 登录。</div> | |
| 471 | 新增: </div> | |
| 472 | 新增: | |
| 473 | 新增: <!-- launch --> | |
| 474 | 新增: <div class="view launch" id="viewLaunch"> | |
| 475 | 新增: <div class="panel"> | |
| 476 | 新增: <div class="ph"> | |
| 477 | 新增: <div class="badge"><svg class="i" viewBox="0 0 24 24"><path d="M12 3.5l7.5 2.8v5.6c0 4.3-3.2 7.6-7.5 8.6-4.3-1-7.5-4.3-7.5-8.6V6.3z"/></svg><div class="okb"><svg class="i" viewBox="0 0 24 24"><path d="M12 3.5l7.5 2.8v5.6c0 4.3-3.2 7.6-7.5 8.6-4.3-1-7.5-4.3-7.5-8.6V6.3z"/><path d="M8.8 12.2l2.2 2.2 4.3-4.6"/></svg></div></div> | |
| 478 | 新增: <div class="tt"> | |
| 479 | 新增: <div id="phBusy"><div class="a">正在启动 Cage 环境</div><div class="b">准备镜像与工具,然后核对网络和隔离。</div></div> | |
| 480 | 新增: <div id="phDone"><div class="a" style="color:#1f5f35">外网已放行</div><div class="b">关键检查已通过,后台继续核对出口规则与环境配置。</div></div> | |
| 481 | 新增: </div> | |
| 482 | 新增: <div class="count" id="ckCount">0 / 11</div> | |
| 483 | 新增: </div> | |
| 484 | 新增: <div class="prog"> | |
| 485 | 新增: <div class="p" data-p="0"><div class="st"><div class="wait"></div><div class="spin"></div><div class="ok"><svg class="i" viewBox="0 0 24 24"><path d="M5.5 12.5l4 4 9-9"/></svg></div></div><span>下载 Linux 镜像</span><div class="bar"><i></i></div><span class="pct">0%</span></div> | |
| 486 | 新增: <div class="p" data-p="1"><div class="st"><div class="wait"></div><div class="spin"></div><div class="ok"><svg class="i" viewBox="0 0 24 24"><path d="M5.5 12.5l4 4 9-9"/></svg></div></div><span>安装开发工具</span><div class="bar"><i></i></div><span class="pct">0%</span></div> | |
| 487 | 新增: </div> | |
| 488 | 新增: <div class="checks-h"><span>网络与隔离检查 · 关键项</span><span>失败时保持离线</span></div> | |
| 489 | 新增: <div class="checks" id="checks"></div> | |
| 490 | 新增: </div> | |
| 491 | 新增: </div> | |
| 492 | 新增: | |
| 493 | 新增: <!-- terminal --> | |
| 494 | 新增: <div class="view" id="viewTerm"> | |
| 495 | 新增: <div class="term-bar"><svg class="i" viewBox="0 0 24 24" style="width:15px;height:15px"><rect x="3.5" y="4.5" width="17" height="15" rx="2.5"/><path d="M7.5 9.5l3 2.5-3 2.5M12.5 15h4"/></svg>/workspace/hello-cage<div class="r"><span>Linux · bash</span><span>+ 新建终端</span></div></div> | |
| 496 | 新增: <div class="term" id="term"> | |
| 497 | 新增: <div class="ln"><span class="acc">Claude Cage</span> · hello-cage</div> | |
| 498 | 新增: <div class="ln"></div> | |
| 499 | 新增: <div class="ln">A separate Linux workspace. Your project, your tools.</div> | |
| 500 | 新增: <div class="ln"></div> | |
| 501 | 新增: <div class="ln"><span class="g">✓</span> Project folder shared: /workspace/hello-cage</div> | |
| 502 | 新增: <div class="ln"><span class="g">✓</span> Terminal ready</div> | |
| 503 | 新增: <div class="ln"></div> | |
| 504 | 新增: <div class="ln" id="cmdLine">$ <span id="cmdText"></span><i class="caret" id="caret1"></i></div> | |
| 505 | 新增: <div id="ccBlock"> | |
| 506 | 新增: <div class="cc"><span class="w">✻</span> Welcome to <b>Claude Code</b>!<br><span class="m"> cwd: /workspace/hello-cage</span></div> | |
| 507 | 新增: <div class="ln" id="promptLine"><span class="m">></span> <span id="promptText"></span><i class="caret" id="caret2"></i></div> | |
| 508 | 新增: <div class="reply" id="reply"> | |
| 509 | 新增: <div class="ln" data-r="0"><span class="dot">●</span> 我先看一下项目结构。</div> | |
| 510 | 新增: <div class="ln" data-r="1"><span class="g">●</span> <span class="tool">Read</span>(package.json)<span class="m"> ⎿ Read 18 lines</span></div> | |
| 511 | 新增: <div class="ln" data-r="2"><span class="g">●</span> <span class="tool">Write</span>(README.md)<span class="m"> ⎿ Wrote 42 lines</span></div> | |
| 512 | 新增: <div class="ln" data-r="3"><span class="dot">●</span> README 写好了:简介、安装方式和本地运行步骤都在里面。</div> | |
| 513 | 新增: </div> | |
| 514 | 新增: </div> | |
| 515 | 新增: </div> | |
| 516 | 新增: </div> | |
| 517 | 新增: | |
| 518 | 新增: <div class="status"> | |
| 519 | 新增: <div class="it" style="position:relative"><svg class="i" viewBox="0 0 24 24" id="netIco"><path d="M12 3.5l7.5 2.8v5.6c0 4.3-3.2 7.6-7.5 8.6-4.3-1-7.5-4.3-7.5-8.6V6.3z"/><path d="M8.8 12.2l2.2 2.2 4.3-4.6" id="netTick"/></svg><span class="flip" id="netFlip" style="width:56px"><span>网络检查</span><span style="color:#1f5f35">外网已放行</span></span></div> | |
| 520 | 新增: <div class="it"><div class="hl" id="hlProxy"></div><svg class="i" viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.5"/><path d="M3.5 12h17M12 3.5c2.6 2.6 3.6 5.3 3.6 8.5s-1 5.9-3.6 8.5c-2.6-2.6-3.6-5.3-3.6-8.5s1-5.9 3.6-8.5z"/></svg><span class="flip" id="proxyFlip" style="width:150px"><span>未选择代理</span><span>指定代理出口 · 洛杉矶 01</span></span></div> | |
| 521 | 新增: <div class="it"><div class="hl" id="hlTz"></div><span class="flip" id="tzFlip" style="width:172px"><span>Asia/Shanghai · 主机</span><span>America/Los_Angeles · 自动</span></span></div> | |
| 522 | 新增: <div class="it"><svg class="i" viewBox="0 0 24 24"><path d="M3 12h4l3-7 4 14 3-7h4"/></svg><span class="flip" id="latFlip" style="width:50px"><span>延迟 —</span><span>128 ms</span></span></div> | |
| 523 | 新增: <div class="right"><div class="it" id="syncIt">文件与本机同步</div><div class="it" id="stopIt"><svg class="i" viewBox="0 0 24 24"><path d="M12 3.5v8"/><path d="M6.6 6.8a7.5 7.5 0 1 0 10.8 0"/></svg>停止环境</div></div> | |
| 524 | 新增: </div> | |
| 525 | 新增: | |
| 526 | 新增: <div id="modalShade"></div> | |
| 527 | 新增: <div id="modal"> | |
| 528 | 新增: <div class="mh">网络与代理<svg class="i" viewBox="0 0 24 24"><path d="M6.5 6.5l11 11M17.5 6.5l-11 11"/></svg></div> | |
| 529 | 新增: <div class="src"><svg class="i" viewBox="0 0 24 24"><path d="M14 3.5H6.5a1 1 0 0 0-1 1v15a1 1 0 0 0 1 1h11a1 1 0 0 0 1-1V8z"/><path d="M14 3.5V8h4.5"/></svg><span><b style="font-weight:600">my-nodes.yaml</b> · Clash / Mihomo 订阅</span><span class="tag"><svg class="i" viewBox="0 0 24 24" style="width:14px;height:14px"><path d="M5.5 12.5l4 4 9-9"/></svg>已导入 24 个节点</span></div> | |
| 530 | 新增: <div class="lbl">节点</div> | |
| 531 | 新增: <div class="nodes" id="nodes"> | |
| 532 | 新增: <div class="node" id="nodeLA"><div class="sel"></div><div class="radio"><i></i></div><span>美国 · 洛杉矶 01</span><span class="ms"><em></em>128 ms</span></div> | |
| 533 | 新增: <div class="node"><div class="sel"></div><div class="radio"><i></i></div><span>美国 · 圣何塞 02</span><span class="ms"><em></em>141 ms</span></div> | |
| 534 | 新增: <div class="node"><div class="sel"></div><div class="radio"><i></i></div><span>日本 · 东京 03</span><span class="ms"><em></em>96 ms</span></div> | |
| 535 | 新增: <div class="node"><div class="sel"></div><div class="radio"><i></i></div><span>新加坡 04</span><span class="ms"><em></em>112 ms</span></div> | |
| 536 | 新增: <div class="node"><div class="sel"></div><div class="radio"><i></i></div><span>英国 · 伦敦 05</span><span class="ms"><em class="warn"></em>214 ms</span></div> | |
| 537 | 新增: </div> | |
| 538 | 新增: <div class="mf"><span>代理不可用时没有直连回退。</span><div class="btn" id="btnUse">使用此节点</div></div> | |
| 539 | 新增: </div> | |
| 540 | 新增: | |
| 541 | 新增: <div id="ripple"></div> | |
| 542 | 新增: <div id="cursor"><svg viewBox="0 0 26 26"><path d="M5 2.8v18.6l4.6-4.4 3 6.6 3.1-1.4-3-6.4h6.5z" fill="#111" stroke="#fff" stroke-width="1.6" stroke-linejoin="round"/></svg></div> | |
| 543 | 新增: </div> | |
| 544 | 新增: </div> | |
| 545 | 新增: </div> | |
| 546 | 新增: </section> | |
| 547 | 新增: | |
| 548 | 新增: <!-- ============ ACT 4 · PERKS ============ --> | |
| 549 | 新增: <section class="layer" id="perks"> | |
| 550 | 新增: <div class="center" id="perksHead"><span data-split>一切,</span><em data-split>都已经帮你做好了。</em></div> | |
| 551 | 新增: <div id="perkRow"> | |
| 552 | 新增: <div class="perk"><div class="pi"><svg viewBox="0 0 24 24"><path d="M12 3 20 7.5v9L12 21l-8-4.5v-9z"/><path d="M4 7.5l8 4.5 8-4.5M12 12v9"/></svg></div><h3>轻量,开箱即用</h3><p>一个桌面应用,装好终端、浏览器和编辑器。不用另装 Docker 或 Clash。</p></div> | |
| 553 | 新增: <div class="perk"><div class="pi"><svg viewBox="0 0 24 24"><path d="M12 3.5l7.5 2.8v5.6c0 4.3-3.2 7.6-7.5 8.6-4.3-1-7.5-4.3-7.5-8.6V6.3z"/><path d="M8.8 12.2l2.2 2.2 4.3-4.6"/></svg></div><h3>自带泄漏审查</h3><p>出口、DNS、时区、UDP、IPv6 等 11 项关键检查。有一项不过,就不联网。</p></div> | |
| 554 | 新增: <div class="perk"><div class="pi"><svg viewBox="0 0 24 24"><rect x="3.5" y="4.5" width="17" height="11.5" rx="1.5"/><path d="M2 19.5h20M9.5 10.2l1.8 1.8 3.3-3.4"/></svg></div><h3>与主机隔离</h3><p>Claude 的网络、指纹与登录都留在 Cage 里。你的电脑照常上网、照常工作。</p></div> | |
| 555 | 新增: <div class="perk"><div class="pi"><svg viewBox="0 0 24 24"><path d="M8.5 8 4.5 12l4 4M15.5 8l4 4-4 4M13.5 5.5l-3 13"/></svg></div><h3>开源,接受审查</h3><p>MIT 许可,代码全部公开。每一行都欢迎社区来看、来挑错。</p></div> | |
| 556 | 新增: </div> | |
| 557 | 新增: </section> | |
| 558 | 新增: | |
| 559 | 新增: <!-- ============ ACT 5 · LETTER ============ --> | |
| 560 | 新增: <section class="layer" id="letter"> | |
| 561 | 新增: <div id="art"><img src="../assets/claude-cage-character.png" alt="" /><div id="artLight"></div></div> | |
| 562 | 新增: <div id="letterKicker">CLAUDE CAGE</div> | |
| 563 | 新增: <div id="letterText"> | |
| 564 | 新增: <span class="l" data-split>把 Claude 关起来,</span> | |
| 565 | 新增: <span class="l" data-split>是为了更好地保护</span> | |
| 566 | 新增: <span class="l"><em data-split>我们的相遇。</em></span> | |
| 567 | 新增: </div> | |
| 568 | 新增: </section> | |
| 569 | 新增: | |
| 570 | 新增: <!-- ============ ACT 6 · END ============ --> | |
| 571 | 新增: <section class="layer" id="end"> | |
| 572 | 新增: <div id="endLogo"></div> | |
| 573 | 新增: <div class="center" id="endWord">Claude Cage</div> | |
| 574 | 新增: <div class="center" id="endSub">为 Claude 量身定制的轻量虚拟机</div> | |
| 575 | 新增: <div class="center" id="endPlat"><span>macOS</span><span>Windows</span><span>Linux</span></div> | |
| 576 | 新增: <div class="center" id="endUrl">lee-xeo.github.io/Claude-Cage</div> | |
| 577 | 新增: <div class="center" id="endGit">github.com/Lee-xeo/Claude-Cage</div> | |
| 578 | 新增: <div class="center" id="endNote">开源 · MIT 许可 · 欢迎社区审查 · 独立社区项目,与 Anthropic 无隶属关系</div> | |
| 579 | 新增: </section> | |
| 580 | 新增: | |
| 581 | 新增: <div id="vignette"></div> | |
| 582 | 新增: <div id="grain"></div> | |
| 583 | 新增:</div> | |
| 584 | 新增:</div> | |
| 585 | 新增: | |
| 586 | 新增:<div id="controls"><button id="play">播放</button><span id="tc">00.00</span><input id="scrub" type="range" min="0" step="0.01" /><button id="restart">重来</button></div> | |
| 587 | 新增: | |
| 588 | 新增:<script src="timeline.js"></script> | |
| 589 | 新增:<script src="promo.js"></script> | |
| 590 | 新增:</body> | |
| 591 | 新增:</html> | |
| @@ -0,0 +1,1120 @@ | ||
| 1 | 新增:{ | |
| 2 | 新增: "name": "claude-cage-promo", | |
| 3 | 新增: "lockfileVersion": 3, | |
| 4 | 新增: "requires": true, | |
| 5 | 新增: "packages": { | |
| 6 | 新增: "": { | |
| 7 | 新增: "name": "claude-cage-promo", | |
| 8 | 新增: "dependencies": { | |
| 9 | 新增: "ffmpeg-static": "^5.2.0", | |
| 10 | 新增: "puppeteer-core": "^24.0.0" | |
| 11 | 新增: } | |
| 12 | 新增: }, | |
| 13 | 新增: "node_modules/@derhuerst/http-basic": { | |
| 14 | 新增: "version": "8.2.4", | |
| 15 | 新增: "resolved": "https://registry.npmjs.org/@derhuerst/http-basic/-/http-basic-8.2.4.tgz", | |
| 16 | 新增: "integrity": "sha512-F9rL9k9Xjf5blCz8HsJRO4diy111cayL2vkY2XE4r4t3n0yPXVYy3KD3nJ1qbrSn9743UWSXH4IwuCa/HWlGFw==", | |
| 17 | 新增: "license": "MIT", | |
| 18 | 新增: "dependencies": { | |
| 19 | 新增: "caseless": "^0.12.0", | |
| 20 | 新增: "concat-stream": "^2.0.0", | |
| 21 | 新增: "http-response-object": "^3.0.1", | |
| 22 | 新增: "parse-cache-control": "^1.0.1" | |
| 23 | 新增: }, | |
| 24 | 新增: "engines": { | |
| 25 | 新增: "node": ">=6.0.0" | |
| 26 | 新增: } | |
| 27 | 新增: }, | |
| 28 | 新增: "node_modules/@puppeteer/browsers": { | |
| 29 | 新增: "version": "2.13.2", | |
| 30 | 新增: "resolved": "https://registry.npmjs.org/@puppeteer/browsers/-/browsers-2.13.2.tgz", | |
| 31 | 新增: "integrity": "sha512-5EUZSUIc37H6aIXyWO0Z4y8NlF8NnjgmqeQgOGiswAU7pY0HOo16ho4+alIWmSfdZnjqBRawMsP3I5YqLSn6kw==", | |
| 32 | 新增: "license": "Apache-2.0", | |
| 33 | 新增: "dependencies": { | |
| 34 | 新增: "debug": "^4.4.3", | |
| 35 | 新增: "extract-zip": "^2.0.1", | |
| 36 | 新增: "progress": "^2.0.3", | |
| 37 | 新增: "proxy-agent": "^6.5.0", | |
| 38 | 新增: "semver": "^7.7.4", | |
| 39 | 新增: "tar-fs": "^3.1.1", | |
| 40 | 新增: "yargs": "^17.7.2" | |
| 41 | 新增: }, | |
| 42 | 新增: "bin": { | |
| 43 | 新增: "browsers": "lib/cjs/main-cli.js" | |
| 44 | 新增: }, | |
| 45 | 新增: "engines": { | |
| 46 | 新增: "node": ">=18" | |
| 47 | 新增: } | |
| 48 | 新增: }, | |
| 49 | 新增: "node_modules/@tootallnate/quickjs-emscripten": { | |
| 50 | 新增: "version": "0.23.0", | |
| 51 | 新增: "resolved": "https://registry.npmjs.org/@tootallnate/quickjs-emscripten/-/quickjs-emscripten-0.23.0.tgz", | |
| 52 | 新增: "integrity": "sha512-C5Mc6rdnsaJDjO3UpGW/CQTHtCKaYlScZTly4JIu97Jxo/odCiH0ITnDXSJPTOrEKk/ycSZ0AOgTmkDtkOsvIA==", | |
| 53 | 新增: "license": "MIT" | |
| 54 | 新增: }, | |
| 55 | 新增: "node_modules/@types/node": { | |
| 56 | 新增: "version": "10.17.60", | |
| 57 | 新增: "resolved": "https://registry.npmjs.org/@types/node/-/node-10.17.60.tgz", | |
| 58 | 新增: "integrity": "sha512-F0KIgDJfy2nA3zMLmWGKxcH2ZVEtCZXHHdOQs2gSaQ27+lNeEfGxzkIw90aXswATX7AZ33tahPbzy6KAfUreVw==", | |
| 59 | 新增: "license": "MIT" | |
| 60 | 新增: }, | |
| 61 | 新增: "node_modules/@types/yauzl": { | |
| 62 | 新增: "version": "2.10.3", | |
| 63 | 新增: "resolved": "https://registry.npmjs.org/@types/yauzl/-/yauzl-2.10.3.tgz", | |
| 64 | 新增: "integrity": "sha512-oJoftv0LSuaDZE3Le4DbKX+KS9G36NzOeSap90UIK0yMA/NhKJhqlSGtNDORNRaIbQfzjXDrQa0ytJ6mNRGz/Q==", | |
| 65 | 新增: "license": "MIT", | |
| 66 | 新增: "optional": true, | |
| 67 | 新增: "dependencies": { | |
| 68 | 新增: "@types/node": "*" | |
| 69 | 新增: } | |
| 70 | 新增: }, | |
| 71 | 新增: "node_modules/agent-base": { | |
| 72 | 新增: "version": "6.0.2", | |
| 73 | 新增: "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", | |
| 74 | 新增: "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", | |
| 75 | 新增: "license": "MIT", | |
| 76 | 新增: "dependencies": { | |
| 77 | 新增: "debug": "4" | |
| 78 | 新增: }, | |
| 79 | 新增: "engines": { | |
| 80 | 新增: "node": ">= 6.0.0" | |
| 81 | 新增: } | |
| 82 | 新增: }, | |
| 83 | 新增: "node_modules/ansi-regex": { | |
| 84 | 新增: "version": "5.0.1", | |
| 85 | 新增: "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", | |
| 86 | 新增: "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", | |
| 87 | 新增: "license": "MIT", | |
| 88 | 新增: "engines": { | |
| 89 | 新增: "node": ">=8" | |
| 90 | 新增: } | |
| 91 | 新增: }, | |
| 92 | 新增: "node_modules/ansi-styles": { | |
| 93 | 新增: "version": "4.3.0", | |
| 94 | 新增: "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", | |
| 95 | 新增: "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", | |
| 96 | 新增: "license": "MIT", | |
| 97 | 新增: "dependencies": { | |
| 98 | 新增: "color-convert": "^2.0.1" | |
| 99 | 新增: }, | |
| 100 | 新增: "engines": { | |
| 101 | 新增: "node": ">=8" | |
| 102 | 新增: }, | |
| 103 | 新增: "funding": { | |
| 104 | 新增: "url": "https://github.com/chalk/ansi-styles?sponsor=1" | |
| 105 | 新增: } | |
| 106 | 新增: }, | |
| 107 | 新增: "node_modules/ast-types": { | |
| 108 | 新增: "version": "0.13.4", | |
| 109 | 新增: "resolved": "https://registry.npmjs.org/ast-types/-/ast-types-0.13.4.tgz", | |
| 110 | 新增: "integrity": "sha512-x1FCFnFifvYDDzTaLII71vG5uvDwgtmDTEVWAxrgeiR8VjMONcCXJx7E+USjDtHlwFmt9MysbqgF9b9Vjr6w+w==", | |
| 111 | 新增: "license": "MIT", | |
| 112 | 新增: "dependencies": { | |
| 113 | 新增: "tslib": "^2.0.1" | |
| 114 | 新增: }, | |
| 115 | 新增: "engines": { | |
| 116 | 新增: "node": ">=4" | |
| 117 | 新增: } | |
| 118 | 新增: }, | |
| 119 | 新增: "node_modules/b4a": { | |
| 120 | 新增: "version": "1.9.0", | |
| 121 | 新增: "resolved": "https://registry.npmjs.org/b4a/-/b4a-1.9.0.tgz", | |
| 122 | 新增: "integrity": "sha512-dpfcF9fDNR6++cthXR67iyhgqWy9CBouAvIWhIntzBG6cvK/cnIPiZQjBwi/ZqjjBEDGfoNDtmB0kTjroOJ3pQ==", | |
| 123 | 新增: "license": "Apache-2.0", | |
| 124 | 新增: "peerDependencies": { | |
| 125 | 新增: "react-native-b4a": "*" | |
| 126 | 新增: }, | |
| 127 | 新增: "peerDependenciesMeta": { | |
| 128 | 新增: "react-native-b4a": { | |
| 129 | 新增: "optional": true | |
| 130 | 新增: } | |
| 131 | 新增: } | |
| 132 | 新增: }, | |
| 133 | 新增: "node_modules/bare-events": { | |
| 134 | 新增: "version": "2.9.2", | |
| 135 | 新增: "resolved": "https://registry.npmjs.org/bare-events/-/bare-events-2.9.2.tgz", | |
| 136 | 新增: "integrity": "sha512-AIPKioV7/Y/8KfZ3AAhjPJxLLbY49S64Ym5DakZlUg75qQiTgUq9hEJoEwa4eUezPUlXRy/i5NpsKvo9jgKmoA==", | |
| 137 | 新增: "license": "Apache-2.0", | |
| 138 | 新增: "peerDependencies": { | |
| 139 | 新增: "bare-abort-controller": "*" | |
| 140 | 新增: }, | |
| 141 | 新增: "peerDependenciesMeta": { | |
| 142 | 新增: "bare-abort-controller": { | |
| 143 | 新增: "optional": true | |
| 144 | 新增: } | |
| 145 | 新增: } | |
| 146 | 新增: }, | |
| 147 | 新增: "node_modules/bare-fs": { | |
| 148 | 新增: "version": "4.8.4", | |
| 149 | 新增: "resolved": "https://registry.npmjs.org/bare-fs/-/bare-fs-4.8.4.tgz", | |
| 150 | 新增: "integrity": "sha512-MPC2eyrpbk3A873sK4y6rk+Iv4o2enxTjHZ8zH3HO0mjrpm5XjnguY2XmfidIsDV6vnjpbMBKUAJpV0ISD2SsQ==", | |
| 151 | 新增: "license": "Apache-2.0", | |
| 152 | 新增: "dependencies": { | |
| 153 | 新增: "bare-events": "^2.5.4", | |
| 154 | 新增: "bare-path": "^3.0.0", | |
| 155 | 新增: "bare-stream": "^2.6.4", | |
| 156 | 新增: "bare-url": "^2.2.2", | |
| 157 | 新增: "fast-fifo": "^1.3.2" | |
| 158 | 新增: }, | |
| 159 | 新增: "engines": { | |
| 160 | 新增: "bare": ">=1.28.0" | |
| 161 | 新增: }, | |
| 162 | 新增: "peerDependencies": { | |
| 163 | 新增: "bare-buffer": "*" | |
| 164 | 新增: }, | |
| 165 | 新增: "peerDependenciesMeta": { | |
| 166 | 新增: "bare-buffer": { | |
| 167 | 新增: "optional": true | |
| 168 | 新增: } | |
| 169 | 新增: } | |
| 170 | 新增: }, | |
| 171 | 新增: "node_modules/bare-path": { | |
| 172 | 新增: "version": "3.1.2", | |
| 173 | 新增: "resolved": "https://registry.npmjs.org/bare-path/-/bare-path-3.1.2.tgz", | |
| 174 | 新增: "integrity": "sha512-ZyKbsuuqK6Ag0K8pX6V5Txq6XeJRvY+wXucnFGRjiyVYP9YWDpIQugk/b+enRYrEYBJaqLzghRQpXPMR7341Nw==", | |
| 175 | 新增: "license": "Apache-2.0" | |
| 176 | 新增: }, | |
| 177 | 新增: "node_modules/bare-stream": { | |
| 178 | 新增: "version": "2.13.4", | |
| 179 | 新增: "resolved": "https://registry.npmjs.org/bare-stream/-/bare-stream-2.13.4.tgz", | |
| 180 | 新增: "integrity": "sha512-PcrQ8lVLbiJscNm1Kez+Yp4Gy4AHGcN1lzwjvf5NybWen7VvEgUfyfnXYJ2zNqWnzOfCb1Abq6lH8ti0syQszA==", | |
| 181 | 新增: "license": "Apache-2.0", | |
| 182 | 新增: "dependencies": { | |
| 183 | 新增: "b4a": "^1.8.1", | |
| 184 | 新增: "streamx": "^2.25.0", | |
| 185 | 新增: "teex": "^1.0.1" | |
| 186 | 新增: }, | |
| 187 | 新增: "peerDependencies": { | |
| 188 | 新增: "bare-abort-controller": "*", | |
| 189 | 新增: "bare-buffer": "*", | |
| 190 | 新增: "bare-events": "*" | |
| 191 | 新增: }, | |
| 192 | 新增: "peerDependenciesMeta": { | |
| 193 | 新增: "bare-abort-controller": { | |
| 194 | 新增: "optional": true | |
| 195 | 新增: }, | |
| 196 | 新增: "bare-buffer": { | |
| 197 | 新增: "optional": true | |
| 198 | 新增: }, | |
| 199 | 新增: "bare-events": { | |
| 200 | 新增: "optional": true | |
| 201 | 新增: } | |
| 202 | 新增: } | |
| 203 | 新增: }, | |
| 204 | 新增: "node_modules/bare-url": { | |
| 205 | 新增: "version": "2.5.5", | |
| 206 | 新增: "resolved": "https://registry.npmjs.org/bare-url/-/bare-url-2.5.5.tgz", | |
| 207 | 新增: "integrity": "sha512-iM9qJCruvpt2rPaLsrumVDru9pogI7PHziHIa9kTNRFt8C8HuSa+kI9kFezK+NvHEFnnz71rKGZ1EAilq/3V/Q==", | |
| 208 | 新增: "license": "Apache-2.0", | |
| 209 | 新增: "dependencies": { | |
| 210 | 新增: "bare-path": "^3.0.0" | |
| 211 | 新增: } | |
| 212 | 新增: }, | |
| 213 | 新增: "node_modules/basic-ftp": { | |
| 214 | 新增: "version": "5.3.1", | |
| 215 | 新增: "resolved": "https://registry.npmjs.org/basic-ftp/-/basic-ftp-5.3.1.tgz", | |
| 216 | 新增: "integrity": "sha512-bopVNp6ugyA150DDuZfPFdt1KZ5a94ZDiwX4hMgZDzF+GttD80lEy8kj98kbyhLXnPvhtIo93mdnLIjpCAeeOw==", | |
| 217 | 新增: "license": "MIT", | |
| 218 | 新增: "engines": { | |
| 219 | 新增: "node": ">=10.0.0" | |
| 220 | 新增: } | |
| 221 | 新增: }, | |
| 222 | 新增: "node_modules/buffer-crc32": { | |
| 223 | 新增: "version": "0.2.13", | |
| 224 | 新增: "resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.13.tgz", | |
| 225 | 新增: "integrity": "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ==", | |
| 226 | 新增: "license": "MIT", | |
| 227 | 新增: "engines": { | |
| 228 | 新增: "node": "*" | |
| 229 | 新增: } | |
| 230 | 新增: }, | |
| 231 | 新增: "node_modules/buffer-from": { | |
| 232 | 新增: "version": "1.1.2", | |
| 233 | 新增: "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", | |
| 234 | 新增: "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", | |
| 235 | 新增: "license": "MIT" | |
| 236 | 新增: }, | |
| 237 | 新增: "node_modules/caseless": { | |
| 238 | 新增: "version": "0.12.0", | |
| 239 | 新增: "resolved": "https://registry.npmjs.org/caseless/-/caseless-0.12.0.tgz", | |
| 240 | 新增: "integrity": "sha512-4tYFyifaFfGacoiObjJegolkwSU4xQNGbVgUiNYVUxbQ2x2lUsFvY4hVgVzGiIe6WLOPqycWXA40l+PWsxthUw==", | |
| 241 | 新增: "license": "Apache-2.0" | |
| 242 | 新增: }, | |
| 243 | 新增: "node_modules/chromium-bidi": { | |
| 244 | 新增: "version": "14.0.0", | |
| 245 | 新增: "resolved": "https://registry.npmjs.org/chromium-bidi/-/chromium-bidi-14.0.0.tgz", | |
| 246 | 新增: "integrity": "sha512-9gYlLtS6tStdRWzrtXaTMnqcM4dudNegMXJxkR0I/CXObHalYeYcAMPrL19eroNZHtJ8DQmu1E+ZNOYu/IXMXw==", | |
| 247 | 新增: "license": "Apache-2.0", | |
| 248 | 新增: "dependencies": { | |
| 249 | 新增: "mitt": "^3.0.1", | |
| 250 | 新增: "zod": "^3.24.1" | |
| 251 | 新增: }, | |
| 252 | 新增: "peerDependencies": { | |
| 253 | 新增: "devtools-protocol": "*" | |
| 254 | 新增: } | |
| 255 | 新增: }, | |
| 256 | 新增: "node_modules/cliui": { | |
| 257 | 新增: "version": "8.0.1", | |
| 258 | 新增: "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", | |
| 259 | 新增: "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", | |
| 260 | 新增: "license": "ISC", | |
| 261 | 新增: "dependencies": { | |
| 262 | 新增: "string-width": "^4.2.0", | |
| 263 | 新增: "strip-ansi": "^6.0.1", | |
| 264 | 新增: "wrap-ansi": "^7.0.0" | |
| 265 | 新增: }, | |
| 266 | 新增: "engines": { | |
| 267 | 新增: "node": ">=12" | |
| 268 | 新增: } | |
| 269 | 新增: }, | |
| 270 | 新增: "node_modules/color-convert": { | |
| 271 | 新增: "version": "2.0.1", | |
| 272 | 新增: "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", | |
| 273 | 新增: "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", | |
| 274 | 新增: "license": "MIT", | |
| 275 | 新增: "dependencies": { | |
| 276 | 新增: "color-name": "~1.1.4" | |
| 277 | 新增: }, | |
| 278 | 新增: "engines": { | |
| 279 | 新增: "node": ">=7.0.0" | |
| 280 | 新增: } | |
| 281 | 新增: }, | |
| 282 | 新增: "node_modules/color-name": { | |
| 283 | 新增: "version": "1.1.4", | |
| 284 | 新增: "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", | |
| 285 | 新增: "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", | |
| 286 | 新增: "license": "MIT" | |
| 287 | 新增: }, | |
| 288 | 新增: "node_modules/concat-stream": { | |
| 289 | 新增: "version": "2.0.0", | |
| 290 | 新增: "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-2.0.0.tgz", | |
| 291 | 新增: "integrity": "sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A==", | |
| 292 | 新增: "engines": [ | |
| 293 | 新增: "node >= 6.0" | |
| 294 | 新增: ], | |
| 295 | 新增: "license": "MIT", | |
| 296 | 新增: "dependencies": { | |
| 297 | 新增: "buffer-from": "^1.0.0", | |
| 298 | 新增: "inherits": "^2.0.3", | |
| 299 | 新增: "readable-stream": "^3.0.2", | |
| 300 | 新增: "typedarray": "^0.0.6" | |
| 301 | 新增: } | |
| 302 | 新增: }, | |
| 303 | 新增: "node_modules/data-uri-to-buffer": { | |
| 304 | 新增: "version": "6.0.2", | |
| 305 | 新增: "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-6.0.2.tgz", | |
| 306 | 新增: "integrity": "sha512-7hvf7/GW8e86rW0ptuwS3OcBGDjIi6SZva7hCyWC0yYry2cOPmLIjXAUHI6DK2HsnwJd9ifmt57i8eV2n4YNpw==", | |
| 307 | 新增: "license": "MIT", | |
| 308 | 新增: "engines": { | |
| 309 | 新增: "node": ">= 14" | |
| 310 | 新增: } | |
| 311 | 新增: }, | |
| 312 | 新增: "node_modules/debug": { | |
| 313 | 新增: "version": "4.4.3", | |
| 314 | 新增: "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", | |
| 315 | 新增: "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", | |
| 316 | 新增: "license": "MIT", | |
| 317 | 新增: "dependencies": { | |
| 318 | 新增: "ms": "^2.1.3" | |
| 319 | 新增: }, | |
| 320 | 新增: "engines": { | |
| 321 | 新增: "node": ">=6.0" | |
| 322 | 新增: }, | |
| 323 | 新增: "peerDependenciesMeta": { | |
| 324 | 新增: "supports-color": { | |
| 325 | 新增: "optional": true | |
| 326 | 新增: } | |
| 327 | 新增: } | |
| 328 | 新增: }, | |
| 329 | 新增: "node_modules/degenerator": { | |
| 330 | 新增: "version": "5.0.1", | |
| 331 | 新增: "resolved": "https://registry.npmjs.org/degenerator/-/degenerator-5.0.1.tgz", | |
| 332 | 新增: "integrity": "sha512-TllpMR/t0M5sqCXfj85i4XaAzxmS5tVA16dqvdkMwGmzI+dXLXnw3J+3Vdv7VKw+ThlTMboK6i9rnZ6Nntj5CQ==", | |
| 333 | 新增: "license": "MIT", | |
| 334 | 新增: "dependencies": { | |
| 335 | 新增: "ast-types": "^0.13.4", | |
| 336 | 新增: "escodegen": "^2.1.0", | |
| 337 | 新增: "esprima": "^4.0.1" | |
| 338 | 新增: }, | |
| 339 | 新增: "engines": { | |
| 340 | 新增: "node": ">= 14" | |
| 341 | 新增: } | |
| 342 | 新增: }, | |
| 343 | 新增: "node_modules/devtools-protocol": { | |
| 344 | 新增: "version": "0.0.1608973", | |
| 345 | 新增: "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.1608973.tgz", | |
| 346 | 新增: "integrity": "sha512-Tpm17fxYzt+J7VrGdc1k8YdRqS3YV7se/M6KeemEqvUbq/n7At1rWVuXMxQgpWkdwSdIEKYbU//Bve+Shm4YNQ==", | |
| 347 | 新增: "license": "BSD-3-Clause" | |
| 348 | 新增: }, | |
| 349 | 新增: "node_modules/emoji-regex": { | |
| 350 | 新增: "version": "8.0.0", | |
| 351 | 新增: "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", | |
| 352 | 新增: "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", | |
| 353 | 新增: "license": "MIT" | |
| 354 | 新增: }, | |
| 355 | 新增: "node_modules/end-of-stream": { | |
| 356 | 新增: "version": "1.4.5", | |
| 357 | 新增: "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz", | |
| 358 | 新增: "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==", | |
| 359 | 新增: "license": "MIT", | |
| 360 | 新增: "dependencies": { | |
| 361 | 新增: "once": "^1.4.0" | |
| 362 | 新增: } | |
| 363 | 新增: }, | |
| 364 | 新增: "node_modules/env-paths": { | |
| 365 | 新增: "version": "2.2.1", | |
| 366 | 新增: "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-2.2.1.tgz", | |
| 367 | 新增: "integrity": "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==", | |
| 368 | 新增: "license": "MIT", | |
| 369 | 新增: "engines": { | |
| 370 | 新增: "node": ">=6" | |
| 371 | 新增: } | |
| 372 | 新增: }, | |
| 373 | 新增: "node_modules/escalade": { | |
| 374 | 新增: "version": "3.2.0", | |
| 375 | 新增: "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", | |
| 376 | 新增: "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", | |
| 377 | 新增: "license": "MIT", | |
| 378 | 新增: "engines": { | |
| 379 | 新增: "node": ">=6" | |
| 380 | 新增: } | |
| 381 | 新增: }, | |
| 382 | 新增: "node_modules/escodegen": { | |
| 383 | 新增: "version": "2.1.0", | |
| 384 | 新增: "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-2.1.0.tgz", | |
| 385 | 新增: "integrity": "sha512-2NlIDTwUWJN0mRPQOdtQBzbUHvdGY2P1VXSyU83Q3xKxM7WHX2Ql8dKq782Q9TgQUNOLEzEYu9bzLNj1q88I5w==", | |
| 386 | 新增: "license": "BSD-2-Clause", | |
| 387 | 新增: "dependencies": { | |
| 388 | 新增: "esprima": "^4.0.1", | |
| 389 | 新增: "estraverse": "^5.2.0", | |
| 390 | 新增: "esutils": "^2.0.2" | |
| 391 | 新增: }, | |
| 392 | 新增: "bin": { | |
| 393 | 新增: "escodegen": "bin/escodegen.js", | |
| 394 | 新增: "esgenerate": "bin/esgenerate.js" | |
| 395 | 新增: }, | |
| 396 | 新增: "engines": { | |
| 397 | 新增: "node": ">=6.0" | |
| 398 | 新增: }, | |
| 399 | 新增: "optionalDependencies": { | |
| 400 | 新增: "source-map": "~0.6.1" | |
| 401 | 新增: } | |
| 402 | 新增: }, | |
| 403 | 新增: "node_modules/esprima": { | |
| 404 | 新增: "version": "4.0.1", | |
| 405 | 新增: "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", | |
| 406 | 新增: "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", | |
| 407 | 新增: "license": "BSD-2-Clause", | |
| 408 | 新增: "bin": { | |
| 409 | 新增: "esparse": "bin/esparse.js", | |
| 410 | 新增: "esvalidate": "bin/esvalidate.js" | |
| 411 | 新增: }, | |
| 412 | 新增: "engines": { | |
| 413 | 新增: "node": ">=4" | |
| 414 | 新增: } | |
| 415 | 新增: }, | |
| 416 | 新增: "node_modules/estraverse": { | |
| 417 | 新增: "version": "5.3.0", | |
| 418 | 新增: "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", | |
| 419 | 新增: "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", | |
| 420 | 新增: "license": "BSD-2-Clause", | |
| 421 | 新增: "engines": { | |
| 422 | 新增: "node": ">=4.0" | |
| 423 | 新增: } | |
| 424 | 新增: }, | |
| 425 | 新增: "node_modules/esutils": { | |
| 426 | 新增: "version": "2.0.3", | |
| 427 | 新增: "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", | |
| 428 | 新增: "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", | |
| 429 | 新增: "license": "BSD-2-Clause", | |
| 430 | 新增: "engines": { | |
| 431 | 新增: "node": ">=0.10.0" | |
| 432 | 新增: } | |
| 433 | 新增: }, | |
| 434 | 新增: "node_modules/events-universal": { | |
| 435 | 新增: "version": "1.0.1", | |
| 436 | 新增: "resolved": "https://registry.npmjs.org/events-universal/-/events-universal-1.0.1.tgz", | |
| 437 | 新增: "integrity": "sha512-LUd5euvbMLpwOF8m6ivPCbhQeSiYVNb8Vs0fQ8QjXo0JTkEHpz8pxdQf0gStltaPpw0Cca8b39KxvK9cfKRiAw==", | |
| 438 | 新增: "license": "Apache-2.0", | |
| 439 | 新增: "dependencies": { | |
| 440 | 新增: "bare-events": "^2.7.0" | |
| 441 | 新增: } | |
| 442 | 新增: }, | |
| 443 | 新增: "node_modules/extract-zip": { | |
| 444 | 新增: "version": "2.0.1", | |
| 445 | 新增: "resolved": "https://registry.npmjs.org/extract-zip/-/extract-zip-2.0.1.tgz", | |
| 446 | 新增: "integrity": "sha512-GDhU9ntwuKyGXdZBUgTIe+vXnWj0fppUEtMDL0+idd5Sta8TGpHssn/eusA9mrPr9qNDym6SxAYZjNvCn/9RBg==", | |
| 447 | 新增: "license": "BSD-2-Clause", | |
| 448 | 新增: "dependencies": { | |
| 449 | 新增: "debug": "^4.1.1", | |
| 450 | 新增: "get-stream": "^5.1.0", | |
| 451 | 新增: "yauzl": "^2.10.0" | |
| 452 | 新增: }, | |
| 453 | 新增: "bin": { | |
| 454 | 新增: "extract-zip": "cli.js" | |
| 455 | 新增: }, | |
| 456 | 新增: "engines": { | |
| 457 | 新增: "node": ">= 10.17.0" | |
| 458 | 新增: }, | |
| 459 | 新增: "optionalDependencies": { | |
| 460 | 新增: "@types/yauzl": "^2.9.1" | |
| 461 | 新增: } | |
| 462 | 新增: }, | |
| 463 | 新增: "node_modules/fast-fifo": { | |
| 464 | 新增: "version": "1.3.2", | |
| 465 | 新增: "resolved": "https://registry.npmjs.org/fast-fifo/-/fast-fifo-1.3.2.tgz", | |
| 466 | 新增: "integrity": "sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ==", | |
| 467 | 新增: "license": "MIT" | |
| 468 | 新增: }, | |
| 469 | 新增: "node_modules/fd-slicer": { | |
| 470 | 新增: "version": "1.1.0", | |
| 471 | 新增: "resolved": "https://registry.npmjs.org/fd-slicer/-/fd-slicer-1.1.0.tgz", | |
| 472 | 新增: "integrity": "sha512-cE1qsB/VwyQozZ+q1dGxR8LBYNZeofhEdUNGSMbQD3Gw2lAzX9Zb3uIU6Ebc/Fmyjo9AWWfnn0AUCHqtevs/8g==", | |
| 473 | 新增: "license": "MIT", | |
| 474 | 新增: "dependencies": { | |
| 475 | 新增: "pend": "~1.2.0" | |
| 476 | 新增: } | |
| 477 | 新增: }, | |
| 478 | 新增: "node_modules/ffmpeg-static": { | |
| 479 | 新增: "version": "5.3.0", | |
| 480 | 新增: "resolved": "https://registry.npmjs.org/ffmpeg-static/-/ffmpeg-static-5.3.0.tgz", | |
| 481 | 新增: "integrity": "sha512-H+K6sW6TiIX6VGend0KQwthe+kaceeH/luE8dIZyOP35ik7ahYojDuqlTV1bOrtEwl01sy2HFNGQfi5IDJvotg==", | |
| 482 | 新增: "hasInstallScript": true, | |
| 483 | 新增: "license": "GPL-3.0-or-later", | |
| 484 | 新增: "dependencies": { | |
| 485 | 新增: "@derhuerst/http-basic": "^8.2.0", | |
| 486 | 新增: "env-paths": "^2.2.0", | |
| 487 | 新增: "https-proxy-agent": "^5.0.0", | |
| 488 | 新增: "progress": "^2.0.3" | |
| 489 | 新增: }, | |
| 490 | 新增: "engines": { | |
| 491 | 新增: "node": ">=16" | |
| 492 | 新增: } | |
| 493 | 新增: }, | |
| 494 | 新增: "node_modules/get-caller-file": { | |
| 495 | 新增: "version": "2.0.5", | |
| 496 | 新增: "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", | |
| 497 | 新增: "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", | |
| 498 | 新增: "license": "ISC", | |
| 499 | 新增: "engines": { | |
| 500 | 新增: "node": "6.* || 8.* || >= 10.*" | |
| 501 | 新增: } | |
| 502 | 新增: }, | |
| 503 | 新增: "node_modules/get-stream": { | |
| 504 | 新增: "version": "5.2.0", | |
| 505 | 新增: "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.2.0.tgz", | |
| 506 | 新增: "integrity": "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA==", | |
| 507 | 新增: "license": "MIT", | |
| 508 | 新增: "dependencies": { | |
| 509 | 新增: "pump": "^3.0.0" | |
| 510 | 新增: }, | |
| 511 | 新增: "engines": { | |
| 512 | 新增: "node": ">=8" | |
| 513 | 新增: }, | |
| 514 | 新增: "funding": { | |
| 515 | 新增: "url": "https://github.com/sponsors/sindresorhus" | |
| 516 | 新增: } | |
| 517 | 新增: }, | |
| 518 | 新增: "node_modules/get-uri": { | |
| 519 | 新增: "version": "6.0.5", | |
| 520 | 新增: "resolved": "https://registry.npmjs.org/get-uri/-/get-uri-6.0.5.tgz", | |
| 521 | 新增: "integrity": "sha512-b1O07XYq8eRuVzBNgJLstU6FYc1tS6wnMtF1I1D9lE8LxZSOGZ7LhxN54yPP6mGw5f2CkXY2BQUL9Fx41qvcIg==", | |
| 522 | 新增: "license": "MIT", | |
| 523 | 新增: "dependencies": { | |
| 524 | 新增: "basic-ftp": "^5.0.2", | |
| 525 | 新增: "data-uri-to-buffer": "^6.0.2", | |
| 526 | 新增: "debug": "^4.3.4" | |
| 527 | 新增: }, | |
| 528 | 新增: "engines": { | |
| 529 | 新增: "node": ">= 14" | |
| 530 | 新增: } | |
| 531 | 新增: }, | |
| 532 | 新增: "node_modules/http-proxy-agent": { | |
| 533 | 新增: "version": "7.0.2", | |
| 534 | 新增: "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", | |
| 535 | 新增: "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==", | |
| 536 | 新增: "license": "MIT", | |
| 537 | 新增: "dependencies": { | |
| 538 | 新增: "agent-base": "^7.1.0", | |
| 539 | 新增: "debug": "^4.3.4" | |
| 540 | 新增: }, | |
| 541 | 新增: "engines": { | |
| 542 | 新增: "node": ">= 14" | |
| 543 | 新增: } | |
| 544 | 新增: }, | |
| 545 | 新增: "node_modules/http-proxy-agent/node_modules/agent-base": { | |
| 546 | 新增: "version": "7.1.4", | |
| 547 | 新增: "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", | |
| 548 | 新增: "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", | |
| 549 | 新增: "license": "MIT", | |
| 550 | 新增: "engines": { | |
| 551 | 新增: "node": ">= 14" | |
| 552 | 新增: } | |
| 553 | 新增: }, | |
| 554 | 新增: "node_modules/http-response-object": { | |
| 555 | 新增: "version": "3.0.2", | |
| 556 | 新增: "resolved": "https://registry.npmjs.org/http-response-object/-/http-response-object-3.0.2.tgz", | |
| 557 | 新增: "integrity": "sha512-bqX0XTF6fnXSQcEJ2Iuyr75yVakyjIDCqroJQ/aHfSdlM743Cwqoi2nDYMzLGWUcuTWGWy8AAvOKXTfiv6q9RA==", | |
| 558 | 新增: "license": "MIT", | |
| 559 | 新增: "dependencies": { | |
| 560 | 新增: "@types/node": "^10.0.3" | |
| 561 | 新增: } | |
| 562 | 新增: }, | |
| 563 | 新增: "node_modules/https-proxy-agent": { | |
| 564 | 新增: "version": "5.0.1", | |
| 565 | 新增: "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", | |
| 566 | 新增: "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", | |
| 567 | 新增: "license": "MIT", | |
| 568 | 新增: "dependencies": { | |
| 569 | 新增: "agent-base": "6", | |
| 570 | 新增: "debug": "4" | |
| 571 | 新增: }, | |
| 572 | 新增: "engines": { | |
| 573 | 新增: "node": ">= 6" | |
| 574 | 新增: } | |
| 575 | 新增: }, | |
| 576 | 新增: "node_modules/inherits": { | |
| 577 | 新增: "version": "2.0.4", | |
| 578 | 新增: "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", | |
| 579 | 新增: "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", | |
| 580 | 新增: "license": "ISC" | |
| 581 | 新增: }, | |
| 582 | 新增: "node_modules/ip-address": { | |
| 583 | 新增: "version": "10.7.6", | |
| 584 | 新增: "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.6.tgz", | |
| 585 | 新增: "integrity": "sha512-00LYkM6byILa9eQIx6qoaXCM40xTLd56AZ4vyaPW3YTyb49VZYPo5xsiAq4tuQ54GH4R7gVdYScJ1B7B77PuTg==", | |
| 586 | 新增: "license": "MIT", | |
| 587 | 新增: "engines": { | |
| 588 | 新增: "node": ">= 12" | |
| 589 | 新增: } | |
| 590 | 新增: }, | |
| 591 | 新增: "node_modules/is-fullwidth-code-point": { | |
| 592 | 新增: "version": "3.0.0", | |
| 593 | 新增: "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", | |
| 594 | 新增: "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", | |
| 595 | 新增: "license": "MIT", | |
| 596 | 新增: "engines": { | |
| 597 | 新增: "node": ">=8" | |
| 598 | 新增: } | |
| 599 | 新增: }, | |
| 600 | 新增: "node_modules/lru-cache": { | |
| 601 | 新增: "version": "7.18.3", | |
| 602 | 新增: "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-7.18.3.tgz", | |
| 603 | 新增: "integrity": "sha512-jumlc0BIUrS3qJGgIkWZsyfAM7NCWiBcCDhnd+3NNM5KbBmLTgHVfWBcg6W+rLUsIpzpERPsvwUP7CckAQSOoA==", | |
| 604 | 新增: "license": "ISC", | |
| 605 | 新增: "engines": { | |
| 606 | 新增: "node": ">=12" | |
| 607 | 新增: } | |
| 608 | 新增: }, | |
| 609 | 新增: "node_modules/mitt": { | |
| 610 | 新增: "version": "3.0.1", | |
| 611 | 新增: "resolved": "https://registry.npmjs.org/mitt/-/mitt-3.0.1.tgz", | |
| 612 | 新增: "integrity": "sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==", | |
| 613 | 新增: "license": "MIT" | |
| 614 | 新增: }, | |
| 615 | 新增: "node_modules/ms": { | |
| 616 | 新增: "version": "2.1.3", | |
| 617 | 新增: "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", | |
| 618 | 新增: "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", | |
| 619 | 新增: "license": "MIT" | |
| 620 | 新增: }, | |
| 621 | 新增: "node_modules/netmask": { | |
| 622 | 新增: "version": "2.1.1", | |
| 623 | 新增: "resolved": "https://registry.npmjs.org/netmask/-/netmask-2.1.1.tgz", | |
| 624 | 新增: "integrity": "sha512-eonl3sLUha+S1GzTPxychyhnUzKyeQkZ7jLjKrBagJgPla13F+uQ71HgpFefyHgqrjEbCPkDArxYsjY8/+gLKA==", | |
| 625 | 新增: "license": "MIT", | |
| 626 | 新增: "engines": { | |
| 627 | 新增: "node": ">= 0.4.0" | |
| 628 | 新增: } | |
| 629 | 新增: }, | |
| 630 | 新增: "node_modules/once": { | |
| 631 | 新增: "version": "1.4.0", | |
| 632 | 新增: "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", | |
| 633 | 新增: "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", | |
| 634 | 新增: "license": "ISC", | |
| 635 | 新增: "dependencies": { | |
| 636 | 新增: "wrappy": "1" | |
| 637 | 新增: } | |
| 638 | 新增: }, | |
| 639 | 新增: "node_modules/pac-proxy-agent": { | |
| 640 | 新增: "version": "7.2.0", | |
| 641 | 新增: "resolved": "https://registry.npmjs.org/pac-proxy-agent/-/pac-proxy-agent-7.2.0.tgz", | |
| 642 | 新增: "integrity": "sha512-TEB8ESquiLMc0lV8vcd5Ql/JAKAoyzHFXaStwjkzpOpC5Yv+pIzLfHvjTSdf3vpa2bMiUQrg9i6276yn8666aA==", | |
| 643 | 新增: "license": "MIT", | |
| 644 | 新增: "dependencies": { | |
| 645 | 新增: "@tootallnate/quickjs-emscripten": "^0.23.0", | |
| 646 | 新增: "agent-base": "^7.1.2", | |
| 647 | 新增: "debug": "^4.3.4", | |
| 648 | 新增: "get-uri": "^6.0.1", | |
| 649 | 新增: "http-proxy-agent": "^7.0.0", | |
| 650 | 新增: "https-proxy-agent": "^7.0.6", | |
| 651 | 新增: "pac-resolver": "^7.0.1", | |
| 652 | 新增: "socks-proxy-agent": "^8.0.5" | |
| 653 | 新增: }, | |
| 654 | 新增: "engines": { | |
| 655 | 新增: "node": ">= 14" | |
| 656 | 新增: } | |
| 657 | 新增: }, | |
| 658 | 新增: "node_modules/pac-proxy-agent/node_modules/agent-base": { | |
| 659 | 新增: "version": "7.1.4", | |
| 660 | 新增: "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", | |
| 661 | 新增: "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", | |
| 662 | 新增: "license": "MIT", | |
| 663 | 新增: "engines": { | |
| 664 | 新增: "node": ">= 14" | |
| 665 | 新增: } | |
| 666 | 新增: }, | |
| 667 | 新增: "node_modules/pac-proxy-agent/node_modules/https-proxy-agent": { | |
| 668 | 新增: "version": "7.0.6", | |
| 669 | 新增: "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", | |
| 670 | 新增: "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", | |
| 671 | 新增: "license": "MIT", | |
| 672 | 新增: "dependencies": { | |
| 673 | 新增: "agent-base": "^7.1.2", | |
| 674 | 新增: "debug": "4" | |
| 675 | 新增: }, | |
| 676 | 新增: "engines": { | |
| 677 | 新增: "node": ">= 14" | |
| 678 | 新增: } | |
| 679 | 新增: }, | |
| 680 | 新增: "node_modules/pac-resolver": { | |
| 681 | 新增: "version": "7.0.1", | |
| 682 | 新增: "resolved": "https://registry.npmjs.org/pac-resolver/-/pac-resolver-7.0.1.tgz", | |
| 683 | 新增: "integrity": "sha512-5NPgf87AT2STgwa2ntRMr45jTKrYBGkVU36yT0ig/n/GMAa3oPqhZfIQ2kMEimReg0+t9kZViDVZ83qfVUlckg==", | |
| 684 | 新增: "license": "MIT", | |
| 685 | 新增: "dependencies": { | |
| 686 | 新增: "degenerator": "^5.0.0", | |
| 687 | 新增: "netmask": "^2.0.2" | |
| 688 | 新增: }, | |
| 689 | 新增: "engines": { | |
| 690 | 新增: "node": ">= 14" | |
| 691 | 新增: } | |
| 692 | 新增: }, | |
| 693 | 新增: "node_modules/parse-cache-control": { | |
| 694 | 新增: "version": "1.0.1", | |
| 695 | 新增: "resolved": "https://registry.npmjs.org/parse-cache-control/-/parse-cache-control-1.0.1.tgz", | |
| 696 | 新增: "integrity": "sha512-60zvsJReQPX5/QP0Kzfd/VrpjScIQ7SHBW6bFCYfEP+fp0Eppr1SHhIO5nd1PjZtvclzSzES9D/p5nFJurwfWg==" | |
| 697 | 新增: }, | |
| 698 | 新增: "node_modules/pend": { | |
| 699 | 新增: "version": "1.2.0", | |
| 700 | 新增: "resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz", | |
| 701 | 新增: "integrity": "sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==", | |
| 702 | 新增: "license": "MIT" | |
| 703 | 新增: }, | |
| 704 | 新增: "node_modules/progress": { | |
| 705 | 新增: "version": "2.0.3", | |
| 706 | 新增: "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz", | |
| 707 | 新增: "integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==", | |
| 708 | 新增: "license": "MIT", | |
| 709 | 新增: "engines": { | |
| 710 | 新增: "node": ">=0.4.0" | |
| 711 | 新增: } | |
| 712 | 新增: }, | |
| 713 | 新增: "node_modules/proxy-agent": { | |
| 714 | 新增: "version": "6.5.0", | |
| 715 | 新增: "resolved": "https://registry.npmjs.org/proxy-agent/-/proxy-agent-6.5.0.tgz", | |
| 716 | 新增: "integrity": "sha512-TmatMXdr2KlRiA2CyDu8GqR8EjahTG3aY3nXjdzFyoZbmB8hrBsTyMezhULIXKnC0jpfjlmiZ3+EaCzoInSu/A==", | |
| 717 | 新增: "license": "MIT", | |
| 718 | 新增: "dependencies": { | |
| 719 | 新增: "agent-base": "^7.1.2", | |
| 720 | 新增: "debug": "^4.3.4", | |
| 721 | 新增: "http-proxy-agent": "^7.0.1", | |
| 722 | 新增: "https-proxy-agent": "^7.0.6", | |
| 723 | 新增: "lru-cache": "^7.14.1", | |
| 724 | 新增: "pac-proxy-agent": "^7.1.0", | |
| 725 | 新增: "proxy-from-env": "^1.1.0", | |
| 726 | 新增: "socks-proxy-agent": "^8.0.5" | |
| 727 | 新增: }, | |
| 728 | 新增: "engines": { | |
| 729 | 新增: "node": ">= 14" | |
| 730 | 新增: } | |
| 731 | 新增: }, | |
| 732 | 新增: "node_modules/proxy-agent/node_modules/agent-base": { | |
| 733 | 新增: "version": "7.1.4", | |
| 734 | 新增: "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", | |
| 735 | 新增: "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", | |
| 736 | 新增: "license": "MIT", | |
| 737 | 新增: "engines": { | |
| 738 | 新增: "node": ">= 14" | |
| 739 | 新增: } | |
| 740 | 新增: }, | |
| 741 | 新增: "node_modules/proxy-agent/node_modules/https-proxy-agent": { | |
| 742 | 新增: "version": "7.0.6", | |
| 743 | 新增: "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", | |
| 744 | 新增: "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", | |
| 745 | 新增: "license": "MIT", | |
| 746 | 新增: "dependencies": { | |
| 747 | 新增: "agent-base": "^7.1.2", | |
| 748 | 新增: "debug": "4" | |
| 749 | 新增: }, | |
| 750 | 新增: "engines": { | |
| 751 | 新增: "node": ">= 14" | |
| 752 | 新增: } | |
| 753 | 新增: }, | |
| 754 | 新增: "node_modules/proxy-from-env": { | |
| 755 | 新增: "version": "1.1.0", | |
| 756 | 新增: "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", | |
| 757 | 新增: "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==", | |
| 758 | 新增: "license": "MIT" | |
| 759 | 新增: }, | |
| 760 | 新增: "node_modules/pump": { | |
| 761 | 新增: "version": "3.0.4", | |
| 762 | 新增: "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz", | |
| 763 | 新增: "integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==", | |
| 764 | 新增: "license": "MIT", | |
| 765 | 新增: "dependencies": { | |
| 766 | 新增: "end-of-stream": "^1.1.0", | |
| 767 | 新增: "once": "^1.3.1" | |
| 768 | 新增: } | |
| 769 | 新增: }, | |
| 770 | 新增: "node_modules/puppeteer-core": { | |
| 771 | 新增: "version": "24.43.1", | |
| 772 | 新增: "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-24.43.1.tgz", | |
| 773 | 新增: "integrity": "sha512-T5ScUMAsmhdNbgDR41AGESYeS6V9MSgetkSnVhhW+gXvzC42VesKCn5ld87gAZDJ6vLHL9GkRvY9WtQWSnwFbw==", | |
| 774 | 新增: "license": "Apache-2.0", | |
| 775 | 新增: "dependencies": { | |
| 776 | 新增: "@puppeteer/browsers": "2.13.2", | |
| 777 | 新增: "chromium-bidi": "14.0.0", | |
| 778 | 新增: "debug": "^4.4.3", | |
| 779 | 新增: "devtools-protocol": "0.0.1608973", | |
| 780 | 新增: "typed-query-selector": "^2.12.2", | |
| 781 | 新增: "webdriver-bidi-protocol": "0.4.1", | |
| 782 | 新增: "ws": "^8.20.0" | |
| 783 | 新增: }, | |
| 784 | 新增: "engines": { | |
| 785 | 新增: "node": ">=18" | |
| 786 | 新增: } | |
| 787 | 新增: }, | |
| 788 | 新增: "node_modules/readable-stream": { | |
| 789 | 新增: "version": "3.6.2", | |
| 790 | 新增: "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", | |
| 791 | 新增: "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", | |
| 792 | 新增: "license": "MIT", | |
| 793 | 新增: "dependencies": { | |
| 794 | 新增: "inherits": "^2.0.3", | |
| 795 | 新增: "string_decoder": "^1.1.1", | |
| 796 | 新增: "util-deprecate": "^1.0.1" | |
| 797 | 新增: }, | |
| 798 | 新增: "engines": { | |
| 799 | 新增: "node": ">= 6" | |
| 800 | 新增: } | |
| 801 | 新增: }, | |
| 802 | 新增: "node_modules/require-directory": { | |
| 803 | 新增: "version": "2.1.1", | |
| 804 | 新增: "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", | |
| 805 | 新增: "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", | |
| 806 | 新增: "license": "MIT", | |
| 807 | 新增: "engines": { | |
| 808 | 新增: "node": ">=0.10.0" | |
| 809 | 新增: } | |
| 810 | 新增: }, | |
| 811 | 新增: "node_modules/safe-buffer": { | |
| 812 | 新增: "version": "5.2.1", | |
| 813 | 新增: "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", | |
| 814 | 新增: "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", | |
| 815 | 新增: "funding": [ | |
| 816 | 新增: { | |
| 817 | 新增: "type": "github", | |
| 818 | 新增: "url": "https://github.com/sponsors/feross" | |
| 819 | 新增: }, | |
| 820 | 新增: { | |
| 821 | 新增: "type": "patreon", | |
| 822 | 新增: "url": "https://www.patreon.com/feross" | |
| 823 | 新增: }, | |
| 824 | 新增: { | |
| 825 | 新增: "type": "consulting", | |
| 826 | 新增: "url": "https://feross.org/support" | |
| 827 | 新增: } | |
| 828 | 新增: ], | |
| 829 | 新增: "license": "MIT" | |
| 830 | 新增: }, | |
| 831 | 新增: "node_modules/semver": { | |
| 832 | 新增: "version": "7.8.6", | |
| 833 | 新增: "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", | |
| 834 | 新增: "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", | |
| 835 | 新增: "license": "ISC", | |
| 836 | 新增: "bin": { | |
| 837 | 新增: "semver": "bin/semver.js" | |
| 838 | 新增: }, | |
| 839 | 新增: "engines": { | |
| 840 | 新增: "node": ">=10" | |
| 841 | 新增: } | |
| 842 | 新增: }, | |
| 843 | 新增: "node_modules/smart-buffer": { | |
| 844 | 新增: "version": "4.2.0", | |
| 845 | 新增: "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz", | |
| 846 | 新增: "integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==", | |
| 847 | 新增: "license": "MIT", | |
| 848 | 新增: "engines": { | |
| 849 | 新增: "node": ">= 6.0.0", | |
| 850 | 新增: "npm": ">= 3.0.0" | |
| 851 | 新增: } | |
| 852 | 新增: }, | |
| 853 | 新增: "node_modules/socks": { | |
| 854 | 新增: "version": "2.8.10", | |
| 855 | 新增: "resolved": "https://registry.npmjs.org/socks/-/socks-2.8.10.tgz", | |
| 856 | 新增: "integrity": "sha512-e0VyvkVTwVYViNovRkZ9aodhxVlyoMn7eJhVUPxZ+eK9P/7CBkxvvsBOHqFPEH416726W8tLXXXjKwqgTErrCQ==", | |
| 857 | 新增: "license": "MIT", | |
| 858 | 新增: "dependencies": { | |
| 859 | 新增: "ip-address": "^10.1.1", | |
| 860 | 新增: "smart-buffer": "^4.2.0" | |
| 861 | 新增: }, | |
| 862 | 新增: "engines": { | |
| 863 | 新增: "node": ">= 10.0.0", | |
| 864 | 新增: "npm": ">= 3.0.0" | |
| 865 | 新增: } | |
| 866 | 新增: }, | |
| 867 | 新增: "node_modules/socks-proxy-agent": { | |
| 868 | 新增: "version": "8.0.5", | |
| 869 | 新增: "resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-8.0.5.tgz", | |
| 870 | 新增: "integrity": "sha512-HehCEsotFqbPW9sJ8WVYB6UbmIMv7kUUORIF2Nncq4VQvBfNBLibW9YZR5dlYCSUhwcD628pRllm7n+E+YTzJw==", | |
| 871 | 新增: "license": "MIT", | |
| 872 | 新增: "dependencies": { | |
| 873 | 新增: "agent-base": "^7.1.2", | |
| 874 | 新增: "debug": "^4.3.4", | |
| 875 | 新增: "socks": "^2.8.3" | |
| 876 | 新增: }, | |
| 877 | 新增: "engines": { | |
| 878 | 新增: "node": ">= 14" | |
| 879 | 新增: } | |
| 880 | 新增: }, | |
| 881 | 新增: "node_modules/socks-proxy-agent/node_modules/agent-base": { | |
| 882 | 新增: "version": "7.1.4", | |
| 883 | 新增: "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", | |
| 884 | 新增: "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", | |
| 885 | 新增: "license": "MIT", | |
| 886 | 新增: "engines": { | |
| 887 | 新增: "node": ">= 14" | |
| 888 | 新增: } | |
| 889 | 新增: }, | |
| 890 | 新增: "node_modules/source-map": { | |
| 891 | 新增: "version": "0.6.1", | |
| 892 | 新增: "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", | |
| 893 | 新增: "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", | |
| 894 | 新增: "license": "BSD-3-Clause", | |
| 895 | 新增: "optional": true, | |
| 896 | 新增: "engines": { | |
| 897 | 新增: "node": ">=0.10.0" | |
| 898 | 新增: } | |
| 899 | 新增: }, | |
| 900 | 新增: "node_modules/streamx": { | |
| 901 | 新增: "version": "2.28.1", | |
| 902 | 新增: "resolved": "https://registry.npmjs.org/streamx/-/streamx-2.28.1.tgz", | |
| 903 | 新增: "integrity": "sha512-zEzXb0s5Cds7tqMH6rhZ05lcJydCWiQPEwiNngVqzsxCc962vLY4Uw+mW7od8kDH258k2Uz/JrOkdIAAhSh9VA==", | |
| 904 | 新增: "license": "MIT", | |
| 905 | 新增: "dependencies": { | |
| 906 | 新增: "events-universal": "^1.0.0", | |
| 907 | 新增: "fast-fifo": "^1.3.2", | |
| 908 | 新增: "text-decoder": "^1.1.0" | |
| 909 | 新增: } | |
| 910 | 新增: }, | |
| 911 | 新增: "node_modules/string_decoder": { | |
| 912 | 新增: "version": "1.3.0", | |
| 913 | 新增: "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", | |
| 914 | 新增: "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", | |
| 915 | 新增: "license": "MIT", | |
| 916 | 新增: "dependencies": { | |
| 917 | 新增: "safe-buffer": "~5.2.0" | |
| 918 | 新增: } | |
| 919 | 新增: }, | |
| 920 | 新增: "node_modules/string-width": { | |
| 921 | 新增: "version": "4.2.3", | |
| 922 | 新增: "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", | |
| 923 | 新增: "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", | |
| 924 | 新增: "license": "MIT", | |
| 925 | 新增: "dependencies": { | |
| 926 | 新增: "emoji-regex": "^8.0.0", | |
| 927 | 新增: "is-fullwidth-code-point": "^3.0.0", | |
| 928 | 新增: "strip-ansi": "^6.0.1" | |
| 929 | 新增: }, | |
| 930 | 新增: "engines": { | |
| 931 | 新增: "node": ">=8" | |
| 932 | 新增: } | |
| 933 | 新增: }, | |
| 934 | 新增: "node_modules/strip-ansi": { | |
| 935 | 新增: "version": "6.0.1", | |
| 936 | 新增: "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", | |
| 937 | 新增: "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", | |
| 938 | 新增: "license": "MIT", | |
| 939 | 新增: "dependencies": { | |
| 940 | 新增: "ansi-regex": "^5.0.1" | |
| 941 | 新增: }, | |
| 942 | 新增: "engines": { | |
| 943 | 新增: "node": ">=8" | |
| 944 | 新增: } | |
| 945 | 新增: }, | |
| 946 | 新增: "node_modules/tar-fs": { | |
| 947 | 新增: "version": "3.1.3", | |
| 948 | 新增: "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-3.1.3.tgz", | |
| 949 | 新增: "integrity": "sha512-/hU4AXnIdZu+Gvl1pk0oI5f5HxWsCJRtY2aFaJdk9VvyL48DWU6iU5WAIPG+wIi1YvWA6eTJvIviP/tMAZZNwQ==", | |
| 950 | 新增: "license": "MIT", | |
| 951 | 新增: "dependencies": { | |
| 952 | 新增: "pump": "^3.0.0", | |
| 953 | 新增: "tar-stream": "^3.1.5" | |
| 954 | 新增: }, | |
| 955 | 新增: "optionalDependencies": { | |
| 956 | 新增: "bare-fs": "^4.0.1", | |
| 957 | 新增: "bare-path": "^3.0.0" | |
| 958 | 新增: } | |
| 959 | 新增: }, | |
| 960 | 新增: "node_modules/tar-stream": { | |
| 961 | 新增: "version": "3.2.2", | |
| 962 | 新增: "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-3.2.2.tgz", | |
| 963 | 新增: "integrity": "sha512-+8NeqHRjQWH9nYlwo2gamAMImZCVzI4UoEgDpWorBt9OEfppiZn+uSkskzQKPWIZyji/C8fpWO7u69G0DX0tbg==", | |
| 964 | 新增: "license": "MIT", | |
| 965 | 新增: "dependencies": { | |
| 966 | 新增: "b4a": "^1.9.0", | |
| 967 | 新增: "bare-fs": "^4.8.2", | |
| 968 | 新增: "fast-fifo": "^1.3.2", | |
| 969 | 新增: "streamx": "^2.28.1" | |
| 970 | 新增: } | |
| 971 | 新增: }, | |
| 972 | 新增: "node_modules/teex": { | |
| 973 | 新增: "version": "1.0.1", | |
| 974 | 新增: "resolved": "https://registry.npmjs.org/teex/-/teex-1.0.1.tgz", | |
| 975 | 新增: "integrity": "sha512-eYE6iEI62Ni1H8oIa7KlDU6uQBtqr4Eajni3wX7rpfXD8ysFx8z0+dri+KWEPWpBsxXfxu58x/0jvTVT1ekOSg==", | |
| 976 | 新增: "license": "MIT", | |
| 977 | 新增: "dependencies": { | |
| 978 | 新增: "streamx": "^2.12.5" | |
| 979 | 新增: } | |
| 980 | 新增: }, | |
| 981 | 新增: "node_modules/text-decoder": { | |
| 982 | 新增: "version": "1.2.7", | |
| 983 | 新增: "resolved": "https://registry.npmjs.org/text-decoder/-/text-decoder-1.2.7.tgz", | |
| 984 | 新增: "integrity": "sha512-vlLytXkeP4xvEq2otHeJfSQIRyWxo/oZGEbXrtEEF9Hnmrdly59sUbzZ/QgyWuLYHctCHxFF4tRQZNQ9k60ExQ==", | |
| 985 | 新增: "license": "Apache-2.0", | |
| 986 | 新增: "dependencies": { | |
| 987 | 新增: "b4a": "^1.6.4" | |
| 988 | 新增: } | |
| 989 | 新增: }, | |
| 990 | 新增: "node_modules/tslib": { | |
| 991 | 新增: "version": "2.9.1", | |
| 992 | 新增: "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz", | |
| 993 | 新增: "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==", | |
| 994 | 新增: "license": "0BSD" | |
| 995 | 新增: }, | |
| 996 | 新增: "node_modules/typed-query-selector": { | |
| 997 | 新增: "version": "2.12.3", | |
| 998 | 新增: "resolved": "https://registry.npmjs.org/typed-query-selector/-/typed-query-selector-2.12.3.tgz", | |
| 999 | 新增: "integrity": "sha512-/dtuMZyutHLlrxWhhC1uib00ELUr2dZ8C9B8YzZYsJmeE3V56OxRblrSM2UaF142pcMtak7ehZ6+poWGeehNIg==", | |
| 1000 | 新增: "license": "MIT" | |
| 1001 | 新增: }, | |
| 1002 | 新增: "node_modules/typedarray": { | |
| 1003 | 新增: "version": "0.0.6", | |
| 1004 | 新增: "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz", | |
| 1005 | 新增: "integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==", | |
| 1006 | 新增: "license": "MIT" | |
| 1007 | 新增: }, | |
| 1008 | 新增: "node_modules/util-deprecate": { | |
| 1009 | 新增: "version": "1.0.2", | |
| 1010 | 新增: "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", | |
| 1011 | 新增: "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", | |
| 1012 | 新增: "license": "MIT" | |
| 1013 | 新增: }, | |
| 1014 | 新增: "node_modules/webdriver-bidi-protocol": { | |
| 1015 | 新增: "version": "0.4.1", | |
| 1016 | 新增: "resolved": "https://registry.npmjs.org/webdriver-bidi-protocol/-/webdriver-bidi-protocol-0.4.1.tgz", | |
| 1017 | 新增: "integrity": "sha512-ARrjNjtWRRs2w4Tk7nqrf2gBI0QXWuOmMCx2hU+1jUt6d00MjMxURrhxhGbrsoiZKJrhTSTzbIrc554iKI10qw==", | |
| 1018 | 新增: "license": "Apache-2.0" | |
| 1019 | 新增: }, | |
| 1020 | 新增: "node_modules/wrap-ansi": { | |
| 1021 | 新增: "version": "7.0.0", | |
| 1022 | 新增: "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", | |
| 1023 | 新增: "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", | |
| 1024 | 新增: "license": "MIT", | |
| 1025 | 新增: "dependencies": { | |
| 1026 | 新增: "ansi-styles": "^4.0.0", | |
| 1027 | 新增: "string-width": "^4.1.0", | |
| 1028 | 新增: "strip-ansi": "^6.0.0" | |
| 1029 | 新增: }, | |
| 1030 | 新增: "engines": { | |
| 1031 | 新增: "node": ">=10" | |
| 1032 | 新增: }, | |
| 1033 | 新增: "funding": { | |
| 1034 | 新增: "url": "https://github.com/chalk/wrap-ansi?sponsor=1" | |
| 1035 | 新增: } | |
| 1036 | 新增: }, | |
| 1037 | 新增: "node_modules/wrappy": { | |
| 1038 | 新增: "version": "1.0.2", | |
| 1039 | 新增: "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", | |
| 1040 | 新增: "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", | |
| 1041 | 新增: "license": "ISC" | |
| 1042 | 新增: }, | |
| 1043 | 新增: "node_modules/ws": { | |
| 1044 | 新增: "version": "8.22.1", | |
| 1045 | 新增: "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.1.tgz", | |
| 1046 | 新增: "integrity": "sha512-oyL6OPYme/CmiFvNuGzeoxCJ4nOrZE2O1FwM9MWM1AsGri6nLXB2pg+lNA8aLeXMSav0J6eIVS1j6vUPzUtK9g==", | |
| 1047 | 新增: "license": "MIT", | |
| 1048 | 新增: "engines": { | |
| 1049 | 新增: "node": ">=10.0.0" | |
| 1050 | 新增: }, | |
| 1051 | 新增: "peerDependencies": { | |
| 1052 | 新增: "bufferutil": "^4.0.1", | |
| 1053 | 新增: "utf-8-validate": ">=5.0.2" | |
| 1054 | 新增: }, | |
| 1055 | 新增: "peerDependenciesMeta": { | |
| 1056 | 新增: "bufferutil": { | |
| 1057 | 新增: "optional": true | |
| 1058 | 新增: }, | |
| 1059 | 新增: "utf-8-validate": { | |
| 1060 | 新增: "optional": true | |
| 1061 | 新增: } | |
| 1062 | 新增: } | |
| 1063 | 新增: }, | |
| 1064 | 新增: "node_modules/y18n": { | |
| 1065 | 新增: "version": "5.0.8", | |
| 1066 | 新增: "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", | |
| 1067 | 新增: "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", | |
| 1068 | 新增: "license": "ISC", | |
| 1069 | 新增: "engines": { | |
| 1070 | 新增: "node": ">=10" | |
| 1071 | 新增: } | |
| 1072 | 新增: }, | |
| 1073 | 新增: "node_modules/yargs": { | |
| 1074 | 新增: "version": "17.7.3", | |
| 1075 | 新增: "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.3.tgz", | |
| 1076 | 新增: "integrity": "sha512-GZtjxm/J/4TSxuL3FNYjCmLktBTnIw/rVmKSIyKeYAZpmJB2ig9VauCC5xsa82GNKVKDAqpOn3KVzNt0zmrU0g==", | |
| 1077 | 新增: "license": "MIT", | |
| 1078 | 新增: "dependencies": { | |
| 1079 | 新增: "cliui": "^8.0.1", | |
| 1080 | 新增: "escalade": "^3.1.1", | |
| 1081 | 新增: "get-caller-file": "^2.0.5", | |
| 1082 | 新增: "require-directory": "^2.1.1", | |
| 1083 | 新增: "string-width": "^4.2.3", | |
| 1084 | 新增: "y18n": "^5.0.5", | |
| 1085 | 新增: "yargs-parser": "^21.1.1" | |
| 1086 | 新增: }, | |
| 1087 | 新增: "engines": { | |
| 1088 | 新增: "node": ">=12" | |
| 1089 | 新增: } | |
| 1090 | 新增: }, | |
| 1091 | 新增: "node_modules/yargs-parser": { | |
| 1092 | 新增: "version": "21.1.1", | |
| 1093 | 新增: "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", | |
| 1094 | 新增: "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", | |
| 1095 | 新增: "license": "ISC", | |
| 1096 | 新增: "engines": { | |
| 1097 | 新增: "node": ">=12" | |
| 1098 | 新增: } | |
| 1099 | 新增: }, | |
| 1100 | 新增: "node_modules/yauzl": { | |
| 1101 | 新增: "version": "2.10.0", | |
| 1102 | 新增: "resolved": "https://registry.npmjs.org/yauzl/-/yauzl-2.10.0.tgz", | |
| 1103 | 新增: "integrity": "sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g==", | |
| 1104 | 新增: "license": "MIT", | |
| 1105 | 新增: "dependencies": { | |
| 1106 | 新增: "buffer-crc32": "~0.2.3", | |
| 1107 | 新增: "fd-slicer": "~1.1.0" | |
| 1108 | 新增: } | |
| 1109 | 新增: }, | |
| 1110 | 新增: "node_modules/zod": { | |
| 1111 | 新增: "version": "3.25.76", | |
| 1112 | 新增: "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz", | |
| 1113 | 新增: "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==", | |
| 1114 | 新增: "license": "MIT", | |
| 1115 | 新增: "funding": { | |
| 1116 | 新增: "url": "https://github.com/sponsors/colinhacks" | |
| 1117 | 新增: } | |
| 1118 | 新增: } | |
| 1119 | 新增: } | |
| 1120 | 新增:} | |
| @@ -0,0 +1,15 @@ | ||
| 1 | 新增:{ | |
| 2 | 新增: "name": "claude-cage-promo", | |
| 3 | 新增: "private": true, | |
| 4 | 新增: "description": "Claude Cage promo video, rendered from code.", | |
| 5 | 新增: "scripts": { | |
| 6 | 新增: "preview": "node render.mjs --preview", | |
| 7 | 新增: "soundtrack": "node soundtrack.mjs", | |
| 8 | 新增: "render": "node soundtrack.mjs && node render.mjs", | |
| 9 | 新增: "render:draft": "node soundtrack.mjs && node render.mjs --fps 30 --scale 0.5" | |
| 10 | 新增: }, | |
| 11 | 新增: "dependencies": { | |
| 12 | 新增: "ffmpeg-static": "^5.2.0", | |
| 13 | 新增: "puppeteer-core": "^24.0.0" | |
| 14 | 新增: } | |
| 15 | 新增:} | |
| @@ -0,0 +1,679 @@ | ||
| 1 | 新增:/* Claude Cage promo · every frame is a pure function of time. | |
| 2 | 新增: * render(t) sets all styles from t, so preview playback, scrubbing and the | |
| 3 | 新增: * frame-by-frame export in render.mjs all show exactly the same picture. */ | |
| 4 | 新增:(() => { | |
| 5 | 新增: 'use strict'; | |
| 6 | 新增: const T = window.TL; | |
| 7 | 新增: const $ = (s, r = document) => r.querySelector(s); | |
| 8 | 新增: const $$ = (s, r = document) => [...r.querySelectorAll(s)]; | |
| 9 | 新增: | |
| 10 | 新增: // ---------- math ---------- | |
| 11 | 新增: const clamp = (x, a = 0, b = 1) => Math.min(b, Math.max(a, x)); | |
| 12 | 新增: const p = (t, a, b) => clamp((t - a) / (b - a)); | |
| 13 | 新增: const lerp = (a, b, k) => a + (b - a) * k; | |
| 14 | 新增: const E = { | |
| 15 | 新增: out: x => 1 - Math.pow(1 - x, 3), | |
| 16 | 新增: out5: x => 1 - Math.pow(1 - x, 5), | |
| 17 | 新增: in: x => x * x * x, | |
| 18 | 新增: io: x => (x < 0.5 ? 4 * x * x * x : 1 - Math.pow(-2 * x + 2, 3) / 2), | |
| 19 | 新增: sine: x => -(Math.cos(Math.PI * x) - 1) / 2, | |
| 20 | 新增: back: (x, s = 1.6) => 1 + (s + 1) * Math.pow(x - 1, 3) + s * Math.pow(x - 1, 2), | |
| 21 | 新增: }; | |
| 22 | 新增: // Fade in over [a, a+fi], fade out over [b-fo, b]. | |
| 23 | 新增: const win = (t, a, b, fi = 0.5, fo = 0.5) => Math.min(E.out(p(t, a, a + fi)), 1 - E.io(p(t, b - fo, b))); | |
| 24 | 新增: const hash = n => { const x = Math.sin(n * 127.1 + 311.7) * 43758.5453; return x - Math.floor(x); }; | |
| 25 | 新增: | |
| 26 | 新增: const css = (el, o) => { | |
| 27 | 新增: if (!el) return; | |
| 28 | 新增: const s = el.style; | |
| 29 | 新增: if (o.o !== undefined) { s.opacity = o.o.toFixed(4); s.visibility = o.o <= 0.001 ? 'hidden' : 'visible'; } | |
| 30 | 新增: if (o.tf !== undefined) s.transform = o.tf; | |
| 31 | 新增: if (o.f !== undefined) s.filter = o.f; | |
| 32 | 新增: }; | |
| 33 | 新增: const blur = v => (v > 0.05 ? `blur(${v.toFixed(2)}px)` : 'none'); | |
| 34 | 新增: | |
| 35 | 新增: // ---------- text ---------- | |
| 36 | 新增: function split(el) { | |
| 37 | 新增: const text = el.textContent; | |
| 38 | 新增: el.textContent = ''; | |
| 39 | 新增: el._chars = [...text].map(ch => { | |
| 40 | 新增: const s = document.createElement('span'); | |
| 41 | 新增: s.className = 'c'; | |
| 42 | 新增: s.textContent = ch; | |
| 43 | 新增: el.appendChild(s); | |
| 44 | 新增: return s; | |
| 45 | 新增: }); | |
| 46 | 新增: } | |
| 47 | 新增: function reveal(el, t, start, { stagger = 0.045, dur = 0.7, y = 18, b = 10 } = {}) { | |
| 48 | 新增: el._chars.forEach((c, i) => { | |
| 49 | 新增: const k = E.out(p(t, start + i * stagger, start + i * stagger + dur)); | |
| 50 | 新增: css(c, { o: k, tf: `translateY(${((1 - k) * y).toFixed(2)}px)`, f: blur((1 - k) * b) }); | |
| 51 | 新增: }); | |
| 52 | 新增: } | |
| 53 | 新增: const revealEnd = (el, start, { stagger = 0.045, dur = 0.7 } = {}) => start + (el._chars.length - 1) * stagger + dur; | |
| 54 | 新增: | |
| 55 | 新增: // A stack of labels that roll vertically at the given switch times. | |
| 56 | 新增: function flip(el, t, times, h = 18) { | |
| 57 | 新增: const spans = el._spans || (el._spans = [...el.children]); | |
| 58 | 新增: let v = 0; | |
| 59 | 新增: times.forEach(at => { v += E.io(p(t, at, at + 0.42)); }); | |
| 60 | 新增: spans.forEach((s, i) => { | |
| 61 | 新增: const d = i - v; | |
| 62 | 新增: s.style.position = 'absolute'; | |
| 63 | 新增: css(s, { o: clamp(1 - Math.abs(d) * 1.4), tf: `translateY(${(d * h).toFixed(2)}px)` }); | |
| 64 | 新增: }); | |
| 65 | 新增: } | |
| 66 | 新增: | |
| 67 | 新增: // ---------- pixel logo ---------- | |
| 68 | 新增: const SVGNS = 'http://www.w3.org/2000/svg'; | |
| 69 | 新增: const ORANGE = '#ef6f45', DARK = '#252321'; | |
| 70 | 新增: function rect(svg, x, y, w, h, fill) { | |
| 71 | 新增: const r = document.createElementNS(SVGNS, 'rect'); | |
| 72 | 新增: r.setAttribute('x', x); r.setAttribute('y', y); r.setAttribute('width', w); r.setAttribute('height', h); | |
| 73 | 新增: r.setAttribute('fill', fill); | |
| 74 | 新增: svg.appendChild(r); | |
| 75 | 新增: return r; | |
| 76 | 新增: } | |
| 77 | 新增: function buildLogo(svg) { | |
| 78 | 新增: svg.setAttribute('viewBox', '0 0 926 926'); | |
| 79 | 新增: const cells = []; | |
| 80 | 新增: const u = 46, bx = 187, by = 280; | |
| 81 | 新增: const add = (x, y, w, h) => cells.push({ el: rect(svg, x, y, w + 0.8, h + 0.8, ORANGE), cx: x + w / 2, cy: y + h / 2 }); | |
| 82 | 新增: for (let r = 0; r < 7; r++) for (let c = 0; c < 12; c++) add(bx + c * u, by + r * u, u, u); | |
| 83 | 新增: for (const r of [3, 4]) { add(bx - 69, by + r * u, 69, u); add(bx + 12 * u, by + r * u, 69, u); } | |
| 84 | 新增: for (const x of [230, 338, 535, 642]) { add(x, 602, 55, 40); add(x, 642, 55, 40); } | |
| 85 | 新增: cells.forEach((c, i) => { | |
| 86 | 新增: const d = Math.hypot(c.cx - 463, c.cy - 450) / 420; | |
| 87 | 新增: c.delay = d * 0.75 + hash(i) * 0.22; | |
| 88 | 新增: }); | |
| 89 | 新增: // Seamless body drawn once every pixel has landed. | |
| 90 | 新增: const solid = [ | |
| 91 | 新增: rect(svg, bx, by, 12 * u, 7 * u, ORANGE), rect(svg, bx - 69, by + 3 * u, 12 * u + 138, 2 * u, ORANGE), | |
| 92 | 新增: ...[230, 338, 535, 642].map(x => rect(svg, x, 600, 55, 82, ORANGE)), | |
| 93 | 新增: ]; | |
| 94 | 新增: const settle = Math.max(...cells.map(c => c.delay)) + 0.42; | |
| 95 | 新增: const eyes = [rect(svg, 338, 345, 51, 95, DARK), rect(svg, 537, 345, 51, 95, DARK)]; | |
| 96 | 新增: const frame = [ | |
| 97 | 新增: rect(svg, 35, 80, 855, 67, DARK), rect(svg, 35, 761, 855, 67, DARK), | |
| 98 | 新增: rect(svg, 35, 80, 65, 748, DARK), rect(svg, 825, 80, 65, 748, DARK), | |
| 99 | 新增: ]; | |
| 100 | 新增: const bars = [rect(svg, 268, 80, 54, 748, DARK), rect(svg, 604, 80, 54, 748, DARK)]; | |
| 101 | 新增: return { svg, cells, solid, settle, eyes, frame, bars }; | |
| 102 | 新增: } | |
| 103 | 新增: // Assemble the logo: pixels pop from the centre, the frame draws, two bars drop. | |
| 104 | 新增: function logoAt(L, t, { pixels, frame, bars, blink, speed = 1 }) { | |
| 105 | 新增: const whole = t >= pixels + L.settle * speed; | |
| 106 | 新增: L.solid.forEach(r => css(r, { o: whole ? 1 : 0 })); | |
| 107 | 新增: L.cells.forEach(c => { | |
| 108 | 新增: if (whole) { css(c.el, { o: 0 }); return; } | |
| 109 | 新增: const k = p(t, pixels + c.delay * speed, pixels + c.delay * speed + 0.42 * speed); | |
| 110 | 新增: const e = k >= 1 ? 1 : Math.max(0, E.back(k, 2.2)); | |
| 111 | 新增: css(c.el, { o: k > 0 ? 1 : 0, tf: `scale(${e.toFixed(4)})` }); | |
| 112 | 新增: }); | |
| 113 | 新增: const eye = E.back(p(t, pixels + 0.95 * speed, pixels + 1.3 * speed), 1.8); | |
| 114 | 新增: const bl = blink.reduce((m, b) => Math.min(m, 1 - Math.sin(Math.PI * p(t, b, b + 0.2)) * 0.92), 1); | |
| 115 | 新增: L.eyes.forEach(e => css(e, { o: eye > 0 ? 1 : 0, tf: `scaleY(${(Math.max(0, eye) * bl).toFixed(4)})` })); | |
| 116 | 新增: L.frame.forEach((r, i) => { | |
| 117 | 新增: const k = E.io(p(t, frame + (i >> 1) * 0.12, frame + (i >> 1) * 0.12 + 0.5 * speed)); | |
| 118 | 新增: css(r, { o: k > 0 ? 1 : 0, tf: i < 2 ? `scaleX(${k.toFixed(4)})` : `scaleY(${k.toFixed(4)})` }); | |
| 119 | 新增: }); | |
| 120 | 新增: L.bars.forEach((r, i) => { | |
| 121 | 新增: const k = p(t, bars[i], bars[i] + 0.34 * speed); | |
| 122 | 新增: const e = E.back(k, 1.1); | |
| 123 | 新增: css(r, { o: clamp(k * 10), tf: `translateY(${((1 - e) * -760).toFixed(2)}px)` }); | |
| 124 | 新增: }); | |
| 125 | 新增: } | |
| 126 | 新增: // Tiny landing bump for each bar. | |
| 127 | 新增: const barImpact = (t, bars) => bars.reduce((s, b) => s + Math.sin(Math.PI * p(t, b + 0.3, b + 0.5)) * 1, 0); | |
| 128 | 新增: | |
| 129 | 新增: // ---------- icons ---------- | |
| 130 | 新增: const ico = d => `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">${d}</svg>`; | |
| 131 | 新增: const WARN = '<path d="M12 3.5 2.8 19.5h18.4z"/><path d="M12 10v4M12 16.8v.2"/>'; | |
| 132 | 新增: const APPS = [ | |
| 133 | 新增: { n: '微信', c: '#3fb950', w: '异地登录提醒' }, | |
| 134 | 新增: { n: '网上银行', c: '#d7a03b', w: '安全验证失败' }, | |
| 135 | 新增: { n: '公司 VPN', c: '#5a8de0', w: '内网连不上' }, | |
| 136 | 新增: { n: '国内网站', c: '#9b7fe0', w: '打开变慢' }, | |
| 137 | 新增: { n: 'Claude', c: '#d97757', w: '时区与 IP 对不上' }, | |
| 138 | 新增: ]; | |
| 139 | 新增: | |
| 140 | 新增: const CHECKS = ['VM 外出站约束', '终端检测通道', 'DNS 与解析约束', '系统时区与语言', '浏览器时区与语言', '共享文件与宿主私有目录', | |
| 141 | 新增: '宿主管理接口', '代理故障关闭', 'UDP 出站约束', 'IPv6 出站约束', '出口符合已保存规则']; | |
| 142 | 新增: | |
| 143 | 新增: // ---------- build ---------- | |
| 144 | 新增: const els = {}; | |
| 145 | 新增: function build() { | |
| 146 | 新增: $$('[data-split]').forEach(split); | |
| 147 | 新增: | |
| 148 | 新增: const chips = $('#appChips'), wires = $('#wires'); | |
| 149 | 新增: els.apps = APPS.map((a, i) => { | |
| 150 | 新增: const y = 360 + i * 98; | |
| 151 | 新增: const chip = document.createElement('div'); | |
| 152 | 新增: chip.className = 'app-chip dark-card'; | |
| 153 | 新增: chip.style.top = y + 'px'; | |
| 154 | 新增: chip.innerHTML = `<i style="background:${a.c}"></i>${a.n}`; | |
| 155 | 新增: const warn = document.createElement('div'); | |
| 156 | 新增: warn.className = 'warn'; | |
| 157 | 新增: warn.style.top = (y + 14) + 'px'; | |
| 158 | 新增: warn.innerHTML = `${ico(WARN)}${a.w}`; | |
| 159 | 新增: chips.append(chip, warn); | |
| 160 | 新增: const y0 = y + 39; | |
| 161 | 新增: const path = document.createElementNS(SVGNS, 'path'); | |
| 162 | 新增: path.setAttribute('d', `M972 ${y0} C 1150 ${y0}, 1170 590, 1330 590`); | |
| 163 | 新增: const dot = document.createElementNS(SVGNS, 'circle'); | |
| 164 | 新增: dot.setAttribute('r', 6); | |
| 165 | 新增: dot.setAttribute('fill', '#ffb08f'); | |
| 166 | 新增: wires.append(path, dot); | |
| 167 | 新增: const len = path.getTotalLength(); | |
| 168 | 新增: path.style.strokeDasharray = `${len}`; | |
| 169 | 新增: return { chip, warn, path, dot, len }; | |
| 170 | 新增: }); | |
| 171 | 新增: | |
| 172 | 新增: const svgLogo = document.createElementNS(SVGNS, 'svg'); | |
| 173 | 新增: svgLogo.classList.add('logo-svg'); | |
| 174 | 新增: $('#logoWrap').appendChild(svgLogo); | |
| 175 | 新增: els.logo = buildLogo(svgLogo); | |
| 176 | 新增: const svgEnd = document.createElementNS(SVGNS, 'svg'); | |
| 177 | 新增: svgEnd.classList.add('logo-svg'); | |
| 178 | 新增: $('#endLogo').appendChild(svgEnd); | |
| 179 | 新增: els.endLogo = buildLogo(svgEnd); | |
| 180 | 新增: els.mini = buildLogo($('#miniLogo')); | |
| 181 | 新增: | |
| 182 | 新增: const box = $('#checks'); | |
| 183 | 新增: box.style.gridTemplateRows = 'repeat(6, 38px)'; | |
| 184 | 新增: box.style.gridAutoFlow = 'column'; | |
| 185 | 新增: els.checks = CHECKS.map(name => { | |
| 186 | 新增: const d = document.createElement('div'); | |
| 187 | 新增: d.className = 'ck'; | |
| 188 | 新增: d.innerHTML = `<div class="flash"></div><div class="st"><div class="wait"></div><div class="spin"></div><div class="ok"><svg class="i" viewBox="0 0 24 24"><path d="M5.5 12.5l4 4 9-9"/></svg></div></div><span>${name}</span><span class="res"><span class="n">检查中…</span><span class="y">通过</span></span>`; | |
| 189 | 新增: box.appendChild(d); | |
| 190 | 新增: return d; | |
| 191 | 新增: }); | |
| 192 | 新增: | |
| 193 | 新增: els.caps = $$('#caption .cap'); | |
| 194 | 新增: els.dots = $$('#progressDots b'); | |
| 195 | 新增: els.prog = $$('.prog .p'); | |
| 196 | 新增: els.replies = $$('#reply [data-r]'); | |
| 197 | 新增: els.termLines = $$('#term > .ln'); | |
| 198 | 新增: els.navEnable = $$('[data-enable]'); | |
| 199 | 新增: els.nodes = $$('#modal .node'); | |
| 200 | 新增: const last = els.replies[3]; | |
| 201 | 新增: last.lastChild.textContent = ''; | |
| 202 | 新增: els.lastReply = last.lastChild; | |
| 203 | 新增: } | |
| 204 | 新增: | |
| 205 | 新增: // Window-local position of an element's centre (offsets ignore transforms). | |
| 206 | 新增: const win0 = () => $('#win'); | |
| 207 | 新增: function center(el, dx = 0, dy = 0) { | |
| 208 | 新增: let x = 0, y = 0, n = el; | |
| 209 | 新增: const root = win0(); | |
| 210 | 新增: while (n && n !== root) { x += n.offsetLeft; y += n.offsetTop; n = n.offsetParent; } | |
| 211 | 新增: return [x + el.offsetWidth / 2 + dx, y + el.offsetHeight / 2 + dy]; | |
| 212 | 新增: } | |
| 213 | 新增: | |
| 214 | 新增: let cursorKeys, clicks; | |
| 215 | 新增: function measure() { | |
| 216 | 新增: const A = T.app; | |
| 217 | 新增: const proxy = center($('#btnProxy'), 10, 4); | |
| 218 | 新增: const launch = center($('#btnLaunch'), 6, 4); | |
| 219 | 新增: const node = center($('#nodeLA'), -120, 3); | |
| 220 | 新增: const use = center($('#btnUse'), 8, 4); | |
| 221 | 新增: const plus = center($('#projPlus'), 2, 3); | |
| 222 | 新增: // [time, x, y, opacity] | |
| 223 | 新增: cursorKeys = [ | |
| 224 | 新增: [20.6, 1120, 690, 0], [21.0, 1060, 620, 1], [21.55, ...proxy, 1], [21.9, ...proxy, 1], | |
| 225 | 新增: [23.25, ...node, 1], [23.6, ...node, 1], [24.15, ...use, 1], [24.5, use[0] + 20, use[1] + 30, 1], [24.8, use[0] + 60, use[1] + 90, 0], | |
| 226 | 新增: [27.3, 1060, 640, 0], [27.55, 1010, 600, 1], [27.98, ...launch, 1], [28.3, ...launch, 1], [28.7, launch[0] + 70, launch[1] + 80, 0], | |
| 227 | 新增: [34.4, 520, 520, 0], [34.6, 420, 420, 1], [34.82, ...plus, 1], [35.15, ...plus, 1], [35.5, plus[0] + 60, plus[1] + 60, 0], | |
| 228 | 新增: ]; | |
| 229 | 新增: cursorKeys.forEach(k => { k[0] += O; }); | |
| 230 | 新增: clicks = [[A.clickProxy, proxy], [A.clickNode, node], [A.clickUse, use], [A.clickLaunch, launch], [A.clickTerminal, plus]]; | |
| 231 | 新增: } | |
| 232 | 新增: | |
| 233 | 新增: // ---------- camera ---------- | |
| 234 | 新增: // [time, zoom, focusX, focusY, anchorX, anchorY] | |
| 235 | 新增: const O = T.app.rise - 19.0; // camera and cursor keys below are authored for a 19.0 s start | |
| 236 | 新增: const BASE = [1.15, 640, 380, 960, 600]; | |
| 237 | 新增: const CAM = [ | |
| 238 | 新增: [19.0, ...BASE], [21.75, ...BASE], | |
| 239 | 新增: [22.55, 1.42, 764, 322, 960, 616], [24.45, 1.42, 764, 322, 960, 616], | |
| 240 | 新增: [25.25, 1.8, 620, 742, 960, 880], [26.65, 1.8, 620, 742, 960, 880], | |
| 241 | 新增: [27.35, ...BASE], [30.15, ...BASE], | |
| 242 | 新增: [30.9, 1.4, 764, 410, 960, 612], [33.25, 1.4, 764, 410, 960, 612], | |
| 243 | 新增: [34.1, ...BASE], [36.4, ...BASE], | |
| 244 | 新增: [42.6, 1.34, 700, 330, 960, 612], | |
| 245 | 新增: ].map(([at, ...rest]) => [at + O, ...rest]); | |
| 246 | 新增: function camAt(t) { | |
| 247 | 新增: if (t <= CAM[0][0]) return CAM[0].slice(1); | |
| 248 | 新增: for (let i = 0; i < CAM.length - 1; i++) { | |
| 249 | 新增: const a = CAM[i], b = CAM[i + 1]; | |
| 250 | 新增: if (t <= b[0]) { | |
| 251 | 新增: const k = E.io(p(t, a[0], b[0])); | |
| 252 | 新增: return a.slice(1).map((v, j) => lerp(v, b[j + 1], k)); | |
| 253 | 新增: } | |
| 254 | 新增: } | |
| 255 | 新增: return CAM[CAM.length - 1].slice(1); | |
| 256 | 新增: } | |
| 257 | 新增: function cursorAt(t) { | |
| 258 | 新增: const K = cursorKeys; | |
| 259 | 新增: if (t <= K[0][0]) return K[0].slice(1); | |
| 260 | 新增: for (let i = 0; i < K.length - 1; i++) { | |
| 261 | 新增: const a = K[i], b = K[i + 1]; | |
| 262 | 新增: if (t <= b[0]) { | |
| 263 | 新增: const k = E.io(p(t, a[0], b[0])); | |
| 264 | 新增: return [lerp(a[1], b[1], k), lerp(a[2], b[2], k), lerp(a[3], b[3], k)]; | |
| 265 | 新增: } | |
| 266 | 新增: } | |
| 267 | 新增: return K[K.length - 1].slice(1); | |
| 268 | 新增: } | |
| 269 | 新增: | |
| 270 | 新增: // ---------- acts ---------- | |
| 271 | 新增: // Fast, punchy reveal for the problem headlines. | |
| 272 | 新增: const punch = (el, t, at) => reveal(el, t, at, { stagger: 0.022, dur: 0.38, y: 26, b: 8 }); | |
| 273 | 新增: const slam = (el, t, at, { from = 1.35, rot = 0, dur = 0.38 } = {}) => { | |
| 274 | 新增: const k = p(t, at, at + dur); | |
| 275 | 新增: const e = E.out5(k); | |
| 276 | 新增: css(el, { o: clamp(k * 5), tf: `scale(${lerp(from, 1, e).toFixed(4)}) rotate(${(rot * (1 - e * 0.6)).toFixed(2)}deg)`, f: blur((1 - clamp(k * 3)) * 10) }); | |
| 277 | 新增: }; | |
| 278 | 新增: | |
| 279 | 新增: function pain(t) { | |
| 280 | 新增: const P = T.pain; | |
| 281 | 新增: const layer = $('#night'); | |
| 282 | 新增: css(layer, { o: t < P.end ? 1 : 0 }); | |
| 283 | 新增: if (t >= P.end) return; | |
| 284 | 新增: | |
| 285 | 新增: // Hard cuts: every hit shakes the frame and flashes it for a few frames. | |
| 286 | 新增: const hits = [[P.slam, 1], [P.b2, 0.55], [P.b3, 0.55], [P.b4, 0.55], [P.vmMem, 0.45], ...P.losses.map(x => [x, 0.32]), [P.total, 0.3]]; | |
| 287 | 新增: let shake = 0, flash = 0; | |
| 288 | 新增: hits.forEach(([h, k]) => { | |
| 289 | 新增: const q = p(t, h, h + 0.35), f = p(t, h, h + 0.13); | |
| 290 | 新增: if (q > 0 && q < 1) shake = Math.max(shake, (1 - q) * k); | |
| 291 | 新增: if (f > 0 && f < 1) flash = Math.max(flash, (1 - f) * k); | |
| 292 | 新增: }); | |
| 293 | 新增: const sx = Math.sin(t * 97) * 12 * shake, sy = Math.cos(t * 83) * 8 * shake; | |
| 294 | 新增: css($('#flash'), { o: flash * 0.2 }); | |
| 295 | 新增: css($('#nightGlow'), { o: t < P.b5 ? 0.45 + shake * 0.8 : 0 }); | |
| 296 | 新增: | |
| 297 | 新增: const starts = [P.slam, P.b2, P.b3, P.b4, P.b5, P.end]; | |
| 298 | 新增: $$('#night .beat').forEach((b, i) => { | |
| 299 | 新增: const a = starts[i], z = starts[i + 1]; | |
| 300 | 新增: const k = E.out5(p(t, a, a + 0.4)); | |
| 301 | 新增: css(b, { o: t >= a && t < z ? 1 : 0, tf: `translate(${sx.toFixed(2)}px, ${sy.toFixed(2)}px) scale(${(lerp(1.05, 1, k) + Math.max(0, t - a) * 0.006).toFixed(4)})` }); | |
| 302 | 新增: const kick = b.querySelector('.kick'); | |
| 303 | 新增: if (kick) css(kick, { o: E.out(p(t, a + 0.05, a + 0.3)) }); | |
| 304 | 新增: const head = b.querySelector('.head'); | |
| 305 | 新增: if (head) { | |
| 306 | 新增: const at = i === 0 ? P.losses[2] + 0.2 : a + 0.12; | |
| 307 | 新增: punch(head.children[0], t, at); | |
| 308 | 新增: punch(head.children[1], t, at + 0.22); | |
| 309 | 新增: } | |
| 310 | 新增: }); | |
| 311 | 新增: | |
| 312 | 新增: // 01 · banned | |
| 313 | 新增: slam($('#alarm'), t, P.slam, { from: 1.5, dur: 0.42 }); | |
| 314 | 新增: $$('#losses .loss').forEach((el, i) => slam(el, t, P.losses[i], { from: 1.4, rot: [-3, 2, -2][i], dur: 0.3 })); | |
| 315 | 新增: | |
| 316 | 新增: // 02 · bills | |
| 317 | 新增: const rk = E.out5(p(t, P.b2, P.b2 + 0.5)); | |
| 318 | 新增: css($('#receipt'), { o: clamp(rk * 3), tf: `translateY(${((1 - rk) * 240 - Math.max(0, t - P.b2) * 6).toFixed(2)}px)` }); | |
| 319 | 新增: $$('#receipt .rr').forEach((el, i) => { | |
| 320 | 新增: const k = E.out5(p(t, P.rows[i], P.rows[i] + 0.25)); | |
| 321 | 新增: css(el, { o: k, tf: `translateX(${((1 - k) * -24).toFixed(2)}px)` }); | |
| 322 | 新增: }); | |
| 323 | 新增: slam($('#receipt .rt'), t, P.total, { from: 1.25, dur: 0.3 }); | |
| 324 | 新增: css($('#receipt .rn'), { o: E.out(p(t, P.total + 0.35, P.total + 0.7)) }); | |
| 325 | 新增: | |
| 326 | 新增: // 03 · the whole machine behind a global proxy | |
| 327 | 新增: css($('#pcLabel'), { o: E.out(p(t, P.b3 + 0.1, P.b3 + 0.4)) }); | |
| 328 | 新增: slam($('#proxyNode'), t, P.wires + 0.15, { from: 0.6, dur: 0.45 }); | |
| 329 | 新增: els.apps.forEach((a, i) => { | |
| 330 | 新增: const k = E.out5(p(t, P.b3 + 0.08 + i * 0.05, P.b3 + 0.4 + i * 0.05)); | |
| 331 | 新增: css(a.chip, { o: k, tf: `translateX(${((1 - k) * -30).toFixed(2)}px)` }); | |
| 332 | 新增: const w = E.io(p(t, P.wires + i * 0.06, P.wires + 0.5 + i * 0.06)); | |
| 333 | 新增: a.path.style.strokeDashoffset = `${(a.len * (1 - w)).toFixed(2)}`; | |
| 334 | 新增: const pt = a.path.getPointAtLength(((t * 0.55 + i * 0.21) % 1) * a.len); | |
| 335 | 新增: a.dot.setAttribute('cx', pt.x.toFixed(2)); | |
| 336 | 新增: a.dot.setAttribute('cy', pt.y.toFixed(2)); | |
| 337 | 新增: a.dot.style.opacity = w >= 1 ? 0.9 : 0; | |
| 338 | 新增: const at = P.tags[i]; | |
| 339 | 新增: const wk = Math.max(0, E.back(p(t, at, at + 0.35), 2)); | |
| 340 | 新增: css(a.warn, { o: clamp(p(t, at, at + 0.12) * 1), tf: `scale(${wk.toFixed(4)})` }); | |
| 341 | 新增: a.warn.style.transformOrigin = '100% 50%'; | |
| 342 | 新增: a.chip.style.borderColor = t > at ? 'rgba(255,106,69,.65)' : 'rgba(255,240,225,.10)'; | |
| 343 | 新增: }); | |
| 344 | 新增: | |
| 345 | 新增: // 04 · a heavy VM that still needs everything set up | |
| 346 | 新增: slam($('#vmWin'), t, P.vm, { from: 1.12, dur: 0.4 }); | |
| 347 | 新增: const dl = 0.11 + Math.max(0, t - P.vm) * 0.004; | |
| 348 | 新增: $('#vmDl').style.transform = `scaleX(${dl.toFixed(4)})`; | |
| 349 | 新增: $('#vmEta').textContent = t < P.vmMem ? '下载中 · 剩余 1 小时 52 分' : '下载中 · 剩余 2 小时 07 分'; | |
| 350 | 新增: const mem = E.out5(p(t, P.vmMem, P.vmMem + 0.45)); | |
| 351 | 新增: const memEl = $('#vmMem'); | |
| 352 | 新增: memEl.style.transform = `scaleX(${lerp(0.25, 0.93, mem).toFixed(4)})`; | |
| 353 | 新增: memEl.style.background = mem > 0.3 ? '#ff6a45' : '#d9cfc5'; | |
| 354 | 新增: $('#vmMemTxt').textContent = mem > 0.3 ? '14.9 GB / 16 GB · 主机开始卡顿' : '4 GB / 16 GB'; | |
| 355 | 新增: css($('#vmTodo .lbl'), { o: E.out(p(t, P.vmTodo[0] - 0.2, P.vmTodo[0] + 0.1)) }); | |
| 356 | 新增: $$('#vmTodo span').forEach((el, i) => slam(el, t, P.vmTodo[i], { from: 1.3, dur: 0.25 })); | |
| 357 | 新增: | |
| 358 | 新增: // and the question | |
| 359 | 新增: const [qa, qb] = $('#b5 .q').children; | |
| 360 | 新增: reveal(qa, t, P.b5 + 0.2, { stagger: 0.06, dur: 0.5, y: 20, b: 10 }); | |
| 361 | 新增: reveal(qb, t, P.b5 + 0.65, { stagger: 0.06, dur: 0.5, y: 20, b: 10 }); | |
| 362 | 新增: const qo = 1 - E.io(p(t, P.end - 0.35, P.end)); | |
| 363 | 新增: css($('#b5 .q'), { tf: `scale(${(1 + Math.max(0, t - P.b5) * 0.015).toFixed(4)})`, f: blur((1 - qo) * 14) }); | |
| 364 | 新增: } | |
| 365 | 新增: | |
| 366 | 新增: function room(t) { | |
| 367 | 新增: const R = T.room; | |
| 368 | 新增: const layer = $('#room'); | |
| 369 | 新增: const o = E.out(p(t, R.start, R.start + 0.45)); | |
| 370 | 新增: const gone = E.io(p(t, R.end - 0.6, R.end)); | |
| 371 | 新增: css(layer, { o: t >= R.end ? 0 : o }); | |
| 372 | 新增: if (t < R.start || t >= R.end) return; | |
| 373 | 新增: $('#roomLight').style.transform = `scale(${lerp(0.6, 1, E.out(p(t, R.start, R.start + 2.5))).toFixed(4)})`; | |
| 374 | 新增: | |
| 375 | 新增: logoAt(els.logo, t, { pixels: R.pixels, frame: R.frame, bars: R.bars, blink: [R.blink], speed: 0.7 }); | |
| 376 | 新增: const bump = barImpact(t, R.bars); | |
| 377 | 新增: const lift = E.io(p(t, R.end - 0.9, R.end)); | |
| 378 | 新增: css($('#logoWrap'), { o: 1 - gone, tf: `translateY(${(bump * 6 - lift * 40).toFixed(2)}px) scale(${(1 - lift * 0.06).toFixed(4)})` }); | |
| 379 | 新增: | |
| 380 | 新增: reveal($('#wordmark'), t, R.word, { stagger: 0.035, dur: 0.6 }); | |
| 381 | 新增: const [pa, pb] = $('#roomPos').children; | |
| 382 | 新增: reveal(pa, t, R.pos, { stagger: 0.035, dur: 0.6 }); | |
| 383 | 新增: reveal(pb, t, R.pos + 0.4, { stagger: 0.07, dur: 0.6, y: 24 }); | |
| 384 | 新增: const [sa, sb] = $('#roomSub').children; | |
| 385 | 新增: reveal(sa, t, R.sub, { stagger: 0.025, dur: 0.6, y: 10 }); | |
| 386 | 新增: reveal(sb, t, R.sub + 0.75, { stagger: 0.04, dur: 0.6, y: 10 }); | |
| 387 | 新增: ['#wordmark', '#roomPos', '#roomSub'].forEach(id => css($(id), { o: 1 - gone, tf: `translateY(${(-lift * 40).toFixed(2)}px)` })); | |
| 388 | 新增: } | |
| 389 | 新增: | |
| 390 | 新增: function app(t) { | |
| 391 | 新增: const A = T.app; | |
| 392 | 新增: const layer = $('#app'); | |
| 393 | 新增: const lo = E.out(p(t, A.rise - 0.3, A.rise + 0.4)) * (1 - E.io(p(t, A.out + 0.4, A.end))); | |
| 394 | 新增: css(layer, { o: lo }); | |
| 395 | 新增: if (lo <= 0) return; | |
| 396 | 新增: | |
| 397 | 新增: // captions + progress | |
| 398 | 新增: const capWin = [[A.step1, A.step2 - 0.2], [A.step2, A.step3 - 0.2], [A.step3, A.out]]; | |
| 399 | 新增: els.caps.forEach((c, i) => { | |
| 400 | 新增: const [a, b] = capWin[i]; | |
| 401 | 新增: const kin = E.out(p(t, a, a + 0.7)), kout = E.io(p(t, b - 0.35, b)); | |
| 402 | 新增: css(c, { o: kin * (1 - kout), tf: `translateY(${((1 - kin) * 22 - kout * 14).toFixed(2)}px)`, f: blur((1 - kin) * 8 + kout * 8) }); | |
| 403 | 新增: const [num, txt] = c.children; | |
| 404 | 新增: const k2 = E.out(p(t, a + 0.12, a + 0.9)); | |
| 405 | 新增: css(txt.lastChild, { o: k2, tf: `translateY(${((1 - k2) * 10).toFixed(2)}px)` }); | |
| 406 | 新增: els.dots[i].style.transform = `scaleX(${E.io(p(t, a, b)).toFixed(4)})`; | |
| 407 | 新增: }); | |
| 408 | 新增: css($('#progressDots'), { o: win(t, A.step1, A.out, 0.6, 0.4) }); | |
| 409 | 新增: | |
| 410 | 新增: // camera + window entrance / exit | |
| 411 | 新增: const [z, fx, fy, ax, ay] = camAt(t); | |
| 412 | 新增: const rise = E.out5(p(t, A.rise, A.rise + 1.3)); | |
| 413 | 新增: const exit = E.io(p(t, A.out, A.end)); | |
| 414 | 新增: const zz = z * lerp(0.94, 1, rise) * lerp(1, 0.9, exit); | |
| 415 | 新增: const tx = ax - fx * zz, ty = ay - fy * zz + (1 - rise) * 160 - exit * 20; | |
| 416 | 新增: css($('#cam'), { o: clamp(rise * 1.6) * (1 - exit), tf: `translate(${tx.toFixed(2)}px, ${ty.toFixed(2)}px) scale(${zz.toFixed(5)})`, f: blur(exit * 10) }); | |
| 417 | 新增: css($('#appFloor'), { o: rise * (1 - exit) * clamp(1 - (z - 1.15) * 3) }); | |
| 418 | 新增: css($('#capShade'), { o: clamp((z - 1.15) * 4) }); | |
| 419 | 新增: | |
| 420 | 新增: // --- step 1 · proxy --- | |
| 421 | 新增: const shade = win(t, A.modalOpen, A.modalClose + 0.35, 0.35, 0.35); | |
| 422 | 新增: css($('#modalShade'), { o: shade }); | |
| 423 | 新增: const mo = E.out(p(t, A.modalOpen, A.modalOpen + 0.45)), mc = E.io(p(t, A.modalClose, A.modalClose + 0.3)); | |
| 424 | 新增: css($('#modal'), { o: mo * (1 - mc), tf: `translateY(${((1 - mo) * 18 + mc * 10).toFixed(2)}px) scale(${(lerp(0.965, 1, mo) - mc * 0.02).toFixed(4)})` }); | |
| 425 | 新增: const sel = E.out(p(t, A.clickNode, A.clickNode + 0.25)); | |
| 426 | 新增: css(els.nodes[0].querySelector('.sel'), { o: sel }); | |
| 427 | 新增: els.nodes[0].querySelector('.radio').style.borderColor = sel > 0.5 ? '#1d1b1a' : '#c9c3bc'; | |
| 428 | 新增: els.nodes[0].querySelector('.radio i').style.transform = `scale(${Math.max(0, E.back(p(t, A.clickNode, A.clickNode + 0.3), 2)).toFixed(4)})`; | |
| 429 | 新增: els.nodes.forEach((n, i) => { css(n, { o: E.out(p(t, A.modalOpen + 0.15 + i * 0.06, A.modalOpen + 0.55 + i * 0.06)) }); }); | |
| 430 | 新增: | |
| 431 | 新增: const press = (at) => 1 - Math.sin(Math.PI * p(t, at - 0.02, at + 0.16)) * 0.05; | |
| 432 | 新增: const ready = E.io(p(t, A.modalClose + 0.4, A.modalClose + 0.75)); | |
| 433 | 新增: const swap = E.io(p(t, A.modalClose + 0.6, A.modalClose + 0.95)); | |
| 434 | 新增: css($('#stateWait'), { o: 1 - ready, tf: `translateY(${(-ready * 8).toFixed(2)}px)` }); | |
| 435 | 新增: css($('#stateReady'), { o: ready, tf: `translateY(${((1 - ready) * 8).toFixed(2)}px)` }); | |
| 436 | 新增: css($('#btnProxy'), { o: 1 - swap, tf: `scale(${press(A.clickProxy).toFixed(4)})` }); | |
| 437 | 新增: css($('#btnLaunch'), { o: swap, tf: `scale(${press(A.clickLaunch).toFixed(4)})` }); | |
| 438 | 新增: const s1 = $('#st1 b'), s2 = $('#st2 b'); | |
| 439 | 新增: const done1 = t > A.modalClose + 0.5, on2 = t > A.modalClose + 0.7; | |
| 440 | 新增: s1.className = done1 ? 'done' : 'on'; | |
| 441 | 新增: s1.innerHTML = done1 ? '<svg class="i" viewBox="0 0 24 24"><path d="M5.5 12.5l4 4 9-9"/></svg>' : '1'; | |
| 442 | 新增: s1.style.transform = `scale(${(1 + Math.sin(Math.PI * p(t, A.modalClose + 0.5, A.modalClose + 0.8)) * 0.18).toFixed(4)})`; | |
| 443 | 新增: s2.className = on2 ? 'on' : ''; | |
| 444 | 新增: $('#st1 > span:last-child').className = done1 ? '' : 'strong'; | |
| 445 | 新增: $('#st2 > span:last-child').className = on2 ? 'strong' : ''; | |
| 446 | 新增: | |
| 447 | 新增: flip($('#proxyFlip'), t, [A.tzFlip - 0.3], 16); | |
| 448 | 新增: flip($('#tzFlip'), t, [A.tzFlip], 16); | |
| 449 | 新增: css($('#hlProxy'), { o: win(t, A.tzFlip - 0.35, A.tzFlip + 0.75, 0.3, 0.5) }); | |
| 450 | 新增: css($('#hlTz'), { o: win(t, A.tzFlip - 0.05, A.tzFlip + 0.95, 0.3, 0.5) }); | |
| 451 | 新增: | |
| 452 | 新增: // --- step 2 · launch --- | |
| 453 | 新增: const toLaunch = E.io(p(t, A.launch + 0.12, A.launch + 0.55)); | |
| 454 | 新增: const heroOut = E.io(p(t, A.launch, A.launch + 0.25)); | |
| 455 | 新增: const toTerm = E.io(p(t, A.terminal, A.terminal + 0.4)); | |
| 456 | 新增: css($('#viewHero'), { o: 1 - heroOut, tf: `translateY(${(-heroOut * 14).toFixed(2)}px)` }); | |
| 457 | 新增: css($('#viewLaunch'), { o: toLaunch * (1 - toTerm), tf: `translateY(${((1 - toLaunch) * 16 - toTerm * 10).toFixed(2)}px)` }); | |
| 458 | 新增: | |
| 459 | 新增: const spin = `rotate(${(t * 420) % 360}deg)`; | |
| 460 | 新增: const stage = (row, start, end, label) => { | |
| 461 | 新增: const [wait, sp, ok] = row.querySelector('.st').children; | |
| 462 | 新增: const k = p(t, start, end); | |
| 463 | 新增: css(wait, { o: t < start ? 1 : 0 }); | |
| 464 | 新增: css(sp, { o: t >= start && k < 1 ? 1 : 0, tf: spin }); | |
| 465 | 新增: css(ok, { o: k >= 1 ? 1 : 0, tf: `scale(${Math.max(0, E.back(p(t, end, end + 0.3), 2)).toFixed(4)})` }); | |
| 466 | 新增: return k; | |
| 467 | 新增: }; | |
| 468 | 新增: els.prog.forEach((row, i) => { | |
| 469 | 新增: const [a, b] = i === 0 ? A.image : A.tools; | |
| 470 | 新增: const k = stage(row, a, b); | |
| 471 | 新增: const fill = i === 0 ? E.sine(k) : E.out(k); | |
| 472 | 新增: row.querySelector('.bar i').style.transform = `scaleX(${fill.toFixed(4)})`; | |
| 473 | 新增: row.querySelector('.pct').textContent = `${Math.round(fill * 100)}%`; | |
| 474 | 新增: }); | |
| 475 | 新增: let passed = 0; | |
| 476 | 新增: els.checks.forEach((row, i) => { | |
| 477 | 新增: const at = A.checks + 0.15 + i * A.checkStep; | |
| 478 | 新增: stage(row, A.checks, at); | |
| 479 | 新增: if (t >= at) passed++; | |
| 480 | 新增: const [n, y] = row.querySelector('.res').children; | |
| 481 | 新增: const k = E.out(p(t, at, at + 0.25)); | |
| 482 | 新增: css(n, { o: t < A.checks ? 0.5 : 1 - k }); | |
| 483 | 新增: css(y, { o: k, tf: `translateX(${((1 - k) * 6).toFixed(2)}px)` }); | |
| 484 | 新增: css(row.querySelector('.flash'), { o: Math.sin(Math.PI * p(t, at, at + 0.5)) }); | |
| 485 | 新增: }); | |
| 486 | 新增: const rel = E.out(p(t, A.released, A.released + 0.45)); | |
| 487 | 新增: $('#ckCount').textContent = passed === 11 ? '11 / 11 通过' : `${passed} / 11`; | |
| 488 | 新增: $('#ckCount').style.color = passed === 11 ? '#1f5f35' : '#6c6763'; | |
| 489 | 新增: css($('#phBusy'), { o: 1 - clamp(rel * 2.5), tf: `translateY(${(-rel * 16).toFixed(2)}px)`, f: blur(rel * 6) }); | |
| 490 | 新增: css($('#phDone'), { o: clamp(rel * 1.6 - 0.4), tf: `translateY(${((1 - rel) * 14).toFixed(2)}px)` }); | |
| 491 | 新增: css($('.ph .okb'), { o: rel, tf: `scale(${lerp(0.6, 1, Math.max(0, E.back(p(t, A.released, A.released + 0.45), 2))).toFixed(4)})` }); | |
| 492 | 新增: $('.ph').style.background = `rgba(47,138,76,${(0.07 * Math.sin(Math.PI * p(t, A.released, A.released + 1.2))).toFixed(4)})`; | |
| 493 | 新增: | |
| 494 | 新增: // sidebar + status bar follow the environment state | |
| 495 | 新增: flip($('#envFlip'), t, [A.launch, A.released], 18); | |
| 496 | 新增: $('#envDot').style.background = t > A.released ? '#2f8a4c' : t > A.launch ? '#d29a2e' : '#b7b1ab'; | |
| 497 | 新增: $('#envDot').style.boxShadow = t > A.released ? '0 0 0 3px rgba(47,138,76,.16)' : 'none'; | |
| 498 | 新增: flip($('#netFlip'), t, [A.released + 0.15], 16); | |
| 499 | 新增: flip($('#latFlip'), t, [A.released + 0.35], 16); | |
| 500 | 新增: const netOk = t > A.released + 0.15; | |
| 501 | 新增: $('#netIco').style.color = netOk ? '#2f8a4c' : '#4a4642'; | |
| 502 | 新增: $('#netTick').style.opacity = netOk ? 1 : 0; | |
| 503 | 新增: els.navEnable.forEach(n => { n.style.color = t > A.released ? '#2a2724' : '#b4aea8'; }); | |
| 504 | 新增: css($('#stopIt'), { o: t > A.launch ? 1 : 0.4 }); | |
| 505 | 新增: | |
| 506 | 新增: // --- step 3 · terminal --- | |
| 507 | 新增: css($('#viewTerm'), { o: toTerm }); | |
| 508 | 新增: const term = E.out(p(t, A.clickTerminal, A.clickTerminal + 0.3)); | |
| 509 | 新增: css($('#childHint'), { o: 1 - term }); | |
| 510 | 新增: css($('#childTerm'), { o: term }); | |
| 511 | 新增: $('#navHome').className = term > 0.5 ? '' : 'on'; | |
| 512 | 新增: css($('#crumbLeaf'), { o: toTerm }); | |
| 513 | 新增: css($('#syncIt'), { o: toTerm }); | |
| 514 | 新增: els.termLines.forEach((ln, i) => { | |
| 515 | 新增: const k = E.out(p(t, A.terminal + 0.1 + i * 0.05, A.terminal + 0.45 + i * 0.05)); | |
| 516 | 新增: css(ln, { o: k, tf: `translateY(${((1 - k) * 6).toFixed(2)}px)` }); | |
| 517 | 新增: }); | |
| 518 | 新增: const typed = (s, at, per) => s.slice(0, Math.max(0, Math.floor((t - at) / per) + 1) * (t >= at ? 1 : 0)); | |
| 519 | 新增: $('#cmdText').textContent = typed('claude', A.typeClaude, 0.1); | |
| 520 | 新增: const blinkOn = Math.floor(t * 2.2) % 2 === 0; | |
| 521 | 新增: css($('#caret1'), { o: t < A.enterClaude ? (t > A.typeClaude && t < A.typeClaude + 0.7 ? 1 : blinkOn ? 1 : 0) : 0 }); | |
| 522 | 新增: const cc = E.out(p(t, A.welcome, A.welcome + 0.5)); | |
| 523 | 新增: css($('#ccBlock'), { o: cc, tf: `translateY(${((1 - cc) * 10).toFixed(2)}px)` }); | |
| 524 | 新增: const prompt = '帮我给 hello-cage 写一份 README'; | |
| 525 | 新增: $('#promptText').textContent = typed(prompt, A.typePrompt, (A.enterPrompt - 0.2 - A.typePrompt) / prompt.length); | |
| 526 | 新增: css($('#caret2'), { o: t < A.enterPrompt ? (t > A.typePrompt ? 1 : blinkOn ? 1 : 0) : 0 }); | |
| 527 | 新增: els.replies.forEach((r, i) => { | |
| 528 | 新增: const k = E.out(p(t, A.reply[i], A.reply[i] + 0.35)); | |
| 529 | 新增: css(r, { o: k, tf: `translateY(${((1 - k) * 6).toFixed(2)}px)` }); | |
| 530 | 新增: }); | |
| 531 | 新增: const final = 'README 写好了:简介、安装方式和本地运行步骤都在里面。'; | |
| 532 | 新增: els.lastReply.textContent = ' ' + final.slice(0, Math.floor(p(t, A.reply[3], A.reply[3] + 1.1) * final.length)); | |
| 533 | 新增: | |
| 534 | 新增: // cursor + clicks | |
| 535 | 新增: const [cx, cy, co] = cursorAt(t); | |
| 536 | 新增: const pressK = clicks.reduce((m, [at]) => Math.max(m, Math.sin(Math.PI * p(t, at - 0.04, at + 0.14))), 0); | |
| 537 | 新增: css($('#cursor'), { o: co, tf: `translate(${(cx - 248 - 5).toFixed(2)}px, ${(cy - 3).toFixed(2)}px) scale(${(1 - pressK * 0.16).toFixed(4)})` }); | |
| 538 | 新增: let rip = null; | |
| 539 | 新增: clicks.forEach(([at, pos]) => { if (t >= at && t < at + 0.55) rip = [p(t, at, at + 0.55), pos]; }); | |
| 540 | 新增: if (rip) { | |
| 541 | 新增: const [k, [x, y]] = rip; | |
| 542 | 新增: css($('#ripple'), { o: (1 - k) * 0.9, tf: `translate(${(x - 248).toFixed(2)}px, ${y.toFixed(2)}px) scale(${lerp(0.3, 1.5, E.out(k)).toFixed(4)})` }); | |
| 543 | 新增: } else css($('#ripple'), { o: 0 }); | |
| 544 | 新增: } | |
| 545 | 新增: | |
| 546 | 新增: function perks(t) { | |
| 547 | 新增: const P = T.perks; | |
| 548 | 新增: const o = E.io(p(t, P.start, P.start + 0.6)) * (1 - E.io(p(t, P.out, P.end))); | |
| 549 | 新增: css($('#perks'), { o }); | |
| 550 | 新增: if (o <= 0) return; | |
| 551 | 新增: const [a, b] = $('#perksHead').children; | |
| 552 | 新增: reveal(a, t, P.head, { stagger: 0.05, dur: 0.6 }); | |
| 553 | 新增: reveal(b, t, P.head + 0.2, { stagger: 0.045, dur: 0.6 }); | |
| 554 | 新增: $$('#perkRow .perk').forEach((el, i) => { | |
| 555 | 新增: const k = E.out5(p(t, P.tiles[i], P.tiles[i] + 0.75)); | |
| 556 | 新增: css(el, { o: clamp(k * 1.5), tf: `translateY(${((1 - k) * 70).toFixed(2)}px)` }); | |
| 557 | 新增: el.querySelector('.pi').style.transform = `scale(${Math.max(0, E.back(p(t, P.tiles[i] + 0.15, P.tiles[i] + 0.55), 2.2)).toFixed(4)})`; | |
| 558 | 新增: }); | |
| 559 | 新增: const drift = p(t, P.start, P.end); | |
| 560 | 新增: $('#perkRow').style.transform = `translateY(${(-drift * 14).toFixed(2)}px)`; | |
| 561 | 新增: $('#perksHead').style.transform = `translateY(${(-drift * 8).toFixed(2)}px)`; | |
| 562 | 新增: } | |
| 563 | 新增: | |
| 564 | 新增: function letter(t) { | |
| 565 | 新增: const L = T.letter; | |
| 566 | 新增: const layer = $('#letter'); | |
| 567 | 新增: const o = E.io(p(t, L.start, L.start + 0.9)) * (1 - E.io(p(t, L.out, L.end))); | |
| 568 | 新增: css(layer, { o }); | |
| 569 | 新增: if (o <= 0) return; | |
| 570 | 新增: const img = $('#art img'); | |
| 571 | 新增: const k = p(t, L.start, L.end); | |
| 572 | 新增: img.style.transform = `scale(${lerp(1.12, 1.0, E.out(k)).toFixed(5)}) translate(${lerp(-10, 6, k).toFixed(2)}px, ${lerp(8, -4, k).toFixed(2)}px)`; | |
| 573 | 新增: const ar = E.out(p(t, L.start + 0.2, L.start + 1.8)); | |
| 574 | 新增: css($('#art'), { o: ar, f: blur((1 - ar) * 14) }); | |
| 575 | 新增: const sweep = E.io(p(t, L.start + 0.6, L.start + 3.2)); | |
| 576 | 新增: css($('#artLight'), { o: Math.sin(Math.PI * sweep) * 0.9, tf: `translateX(${lerp(-70, 70, sweep).toFixed(2)}%)` }); | |
| 577 | 新增: css($('#letterKicker'), { o: E.out(p(t, L.lines[0] - 0.6, L.lines[0] + 0.4)) * 1 }); | |
| 578 | 新增: const ls = $$('#letterText [data-split]'); | |
| 579 | 新增: ls.forEach((el, i) => reveal(el, t, L.lines[i], { stagger: 0.055, dur: 0.8, y: 14, b: 12 })); | |
| 580 | 新增: const drift = E.out(p(t, L.lines[0], L.end)); | |
| 581 | 新增: $('#letterText').style.transform = `translateY(${(-drift * 14).toFixed(2)}px)`; | |
| 582 | 新增: } | |
| 583 | 新增: | |
| 584 | 新增: function end(t) { | |
| 585 | 新增: const N = T.end; | |
| 586 | 新增: const layer = $('#end'); | |
| 587 | 新增: const o = E.io(p(t, N.start, N.start + 0.8)); | |
| 588 | 新增: css(layer, { o }); | |
| 589 | 新增: if (o <= 0) return; | |
| 590 | 新增: const a = N.start + 0.3; | |
| 591 | 新增: logoAt(els.endLogo, t, { pixels: a, frame: a + 0.55, bars: [a + 0.85, a + 1.0], blink: [N.blink], speed: 0.7 }); | |
| 592 | 新增: css($('#endLogo'), { tf: `translateY(${(barImpact(t, [a + 0.85, a + 1.0]) * 4).toFixed(2)}px)` }); | |
| 593 | 新增: const k = (d, dur = 0.8) => E.out(p(t, a + d, a + d + dur)); | |
| 594 | 新增: const rise = (el, d) => { const v = k(d); css(el, { o: v, tf: `translateY(${((1 - v) * 16).toFixed(2)}px)`, f: blur((1 - v) * 6) }); }; | |
| 595 | 新增: rise($('#endWord'), 1.2); | |
| 596 | 新增: rise($('#endSub'), 1.55); | |
| 597 | 新增: $$('#endPlat span').forEach((s, i) => rise(s, 1.95 + i * 0.12)); | |
| 598 | 新增: rise($('#endUrl'), 2.5); | |
| 599 | 新增: rise($('#endGit'), 2.75); | |
| 600 | 新增: rise($('#endNote'), 3.1); | |
| 601 | 新增: } | |
| 602 | 新增: | |
| 603 | 新增: function chrome(t, frame) { | |
| 604 | 新增: const dark = t < T.room.start + 0.4 || (t > T.letter.start + 0.4 && t < T.letter.out + 0.4); | |
| 605 | 新增: const g = $('#grain'); | |
| 606 | 新增: g.style.opacity = dark ? 0.55 : 0.3; | |
| 607 | 新增: g.style.transform = `translate(${Math.floor(hash(frame) * 200) - 100}px, ${Math.floor(hash(frame + 0.5) * 200) - 100}px)`; | |
| 608 | 新增: $('#vignette').style.opacity = dark ? 1 : 0.5; | |
| 609 | 新增: } | |
| 610 | 新增: | |
| 611 | 新增: function render(t) { | |
| 612 | 新增: t = clamp(t, 0, T.duration); | |
| 613 | 新增: pain(t); | |
| 614 | 新增: room(t); | |
| 615 | 新增: app(t); | |
| 616 | 新增: perks(t); | |
| 617 | 新增: letter(t); | |
| 618 | 新增: end(t); | |
| 619 | 新增: chrome(t, Math.round(t * T.fps)); | |
| 620 | 新增: } | |
| 621 | 新增: | |
| 622 | 新增: // ---------- boot ---------- | |
| 623 | 新增: const params = new URLSearchParams(location.search); | |
| 624 | 新增: const renderMode = params.has('render'); | |
| 625 | 新增: if (renderMode) document.body.classList.add('render'); | |
| 626 | 新增: | |
| 627 | 新增: function fit() { | |
| 628 | 新增: const stage = $('#stage'); | |
| 629 | 新增: const s = renderMode ? 1 : Math.min(innerWidth / T.width, innerHeight / T.height); | |
| 630 | 新增: stage.style.position = 'absolute'; | |
| 631 | 新增: stage.style.left = ((innerWidth - T.width * s) / 2) + 'px'; | |
| 632 | 新增: stage.style.top = ((innerHeight - T.height * s) / 2) + 'px'; | |
| 633 | 新增: stage.style.transform = `scale(${s})`; | |
| 634 | 新增: } | |
| 635 | 新增: | |
| 636 | 新增: build(); | |
| 637 | 新增: fit(); | |
| 638 | 新增: addEventListener('resize', fit); | |
| 639 | 新增: render(0); | |
| 640 | 新增: | |
| 641 | 新增: const ready = (async () => { | |
| 642 | 新增: await document.fonts.ready; | |
| 643 | 新增: const img = $('#art img'); | |
| 644 | 新增: if (!img.complete) await new Promise(r => { img.onload = img.onerror = r; }); | |
| 645 | 新增: try { await img.decode(); } catch { /* the frame still renders without the image */ } | |
| 646 | 新增: measure(); | |
| 647 | 新增: render(0); | |
| 648 | 新增: })(); | |
| 649 | 新增: | |
| 650 | 新增: window.__promo = { | |
| 651 | 新增: ready, | |
| 652 | 新增: duration: T.duration, | |
| 653 | 新增: fps: T.fps, | |
| 654 | 新增: seek: t => render(t), | |
| 655 | 新增: }; | |
| 656 | 新增: | |
| 657 | 新增: if (renderMode) return; | |
| 658 | 新增: | |
| 659 | 新增: // Preview player. | |
| 660 | 新增: let now = parseFloat(params.get('t') || '0'), playing = !params.has('t'), last = null; | |
| 661 | 新增: const scrub = $('#scrub'), tc = $('#tc'), play = $('#play'); | |
| 662 | 新增: scrub.max = T.duration; | |
| 663 | 新增: const show = () => { render(now); scrub.value = now; tc.textContent = now.toFixed(2).padStart(5, '0'); play.textContent = playing ? '暂停' : '播放'; }; | |
| 664 | 新增: const loop = ts => { | |
| 665 | 新增: if (playing && last !== null) { now += (ts - last) / 1000; if (now >= T.duration) { now = T.duration; playing = false; } } | |
| 666 | 新增: last = ts; | |
| 667 | 新增: show(); | |
| 668 | 新增: requestAnimationFrame(loop); | |
| 669 | 新增: }; | |
| 670 | 新增: ready.then(() => requestAnimationFrame(loop)); | |
| 671 | 新增: play.onclick = () => { if (now >= T.duration) now = 0; playing = !playing; }; | |
| 672 | 新增: $('#restart').onclick = () => { now = 0; playing = true; }; | |
| 673 | 新增: scrub.oninput = () => { now = parseFloat(scrub.value); playing = false; }; | |
| 674 | 新增: addEventListener('keydown', e => { | |
| 675 | 新增: if (e.code === 'Space') { e.preventDefault(); play.onclick(); } | |
| 676 | 新增: if (e.code === 'ArrowRight') { now = Math.min(T.duration, now + (e.shiftKey ? 0.1 : 1)); playing = false; } | |
| 677 | 新增: if (e.code === 'ArrowLeft') { now = Math.max(0, now - (e.shiftKey ? 0.1 : 1)); playing = false; } | |
| 678 | 新增: }); | |
| 679 | 新增:})(); | |
| @@ -0,0 +1,158 @@ | ||
| 1 | 新增:// Render the promo to MP4: serve the repo, step the page frame by frame in | |
| 2 | 新增:// headless Chrome, and pipe the frames plus the soundtrack into ffmpeg. | |
| 3 | 新增:// | |
| 4 | 新增:// node render.mjs full 1920×1080 @ 60 fps → out/claude-cage-promo.mp4 | |
| 5 | 新增:// node render.mjs --fps 30 --scale 0.5 quick draft | |
| 6 | 新增:// node render.mjs --frames 12,20.5,33 stills only → out/frame-*.png | |
| 7 | 新增:// node render.mjs --preview serve the page for live preview | |
| 8 | 新增:// | |
| 9 | 新增:// Chrome: set CHROME_PATH, otherwise the usual install locations on macOS, | |
| 10 | 新增:// Windows and Linux are tried. | |
| 11 | 新增:import { spawn } from 'node:child_process'; | |
| 12 | 新增:import { createReadStream, existsSync, mkdirSync, statSync } from 'node:fs'; | |
| 13 | 新增:import { createServer } from 'node:http'; | |
| 14 | 新增:import { createRequire } from 'node:module'; | |
| 15 | 新增:import { extname, join, normalize, resolve, sep } from 'node:path'; | |
| 16 | 新增:import { fileURLToPath } from 'node:url'; | |
| 17 | 新增: | |
| 18 | 新增:const require = createRequire(import.meta.url); | |
| 19 | 新增:const here = fileURLToPath(new URL('.', import.meta.url)); | |
| 20 | 新增:const root = resolve(here, '..'); | |
| 21 | 新增:const outDir = join(here, 'out'); | |
| 22 | 新增:const TL = require('./timeline.js'); | |
| 23 | 新增: | |
| 24 | 新增:const args = process.argv.slice(2); | |
| 25 | 新增:const opt = (name, fallback) => { | |
| 26 | 新增: const i = args.indexOf(`--${name}`); | |
| 27 | 新增: return i >= 0 ? args[i + 1] : fallback; | |
| 28 | 新增:}; | |
| 29 | 新增:const fps = Number(opt('fps', TL.fps)); | |
| 30 | 新增:const scale = Number(opt('scale', 1)); | |
| 31 | 新增:const output = resolve(opt('out', join(outDir, 'claude-cage-promo.mp4'))); | |
| 32 | 新增:const audio = resolve(opt('audio', join(outDir, 'soundtrack.wav'))); | |
| 33 | 新增: | |
| 34 | 新增:const TYPES = { | |
| 35 | 新增: '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8', | |
| 36 | 新增: '.css': 'text/css', '.png': 'image/png', '.jpg': 'image/jpeg', '.svg': 'image/svg+xml', '.json': 'application/json', | |
| 37 | 新增: '.mp4': 'video/mp4', '.wav': 'audio/wav', | |
| 38 | 新增:}; | |
| 39 | 新增: | |
| 40 | 新增:function serve(port = 0) { | |
| 41 | 新增: const server = createServer((req, res) => { | |
| 42 | 新增: const path = decodeURIComponent(new URL(req.url, 'http://x').pathname); | |
| 43 | 新增: const file = normalize(join(root, path.endsWith('/') ? path + 'index.html' : path)); | |
| 44 | 新增: if (!(file + sep).startsWith(root + sep) || !existsSync(file) || !statSync(file).isFile()) { | |
| 45 | 新增: res.writeHead(404).end('not found'); | |
| 46 | 新增: return; | |
| 47 | 新增: } | |
| 48 | 新增: res.writeHead(200, { 'content-type': TYPES[extname(file)] || 'application/octet-stream', 'cache-control': 'no-store' }); | |
| 49 | 新增: createReadStream(file).pipe(res); | |
| 50 | 新增: }); | |
| 51 | 新增: return new Promise(ok => server.listen(port, '127.0.0.1', () => ok(server))); | |
| 52 | 新增:} | |
| 53 | 新增: | |
| 54 | 新增:function findChrome() { | |
| 55 | 新增: if (process.env.CHROME_PATH) return process.env.CHROME_PATH; | |
| 56 | 新增: const pf = process.env.PROGRAMFILES || 'C:\\Program Files'; | |
| 57 | 新增: const pf86 = process.env['PROGRAMFILES(X86)'] || 'C:\\Program Files (x86)'; | |
| 58 | 新增: const local = process.env.LOCALAPPDATA || ''; | |
| 59 | 新增: const candidates = { | |
| 60 | 新增: darwin: [ | |
| 61 | 新增: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', | |
| 62 | 新增: '/Applications/Chromium.app/Contents/MacOS/Chromium', | |
| 63 | 新增: '/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge', | |
| 64 | 新增: ], | |
| 65 | 新增: win32: [ | |
| 66 | 新增: join(pf, 'Google\\Chrome\\Application\\chrome.exe'), | |
| 67 | 新增: join(pf86, 'Google\\Chrome\\Application\\chrome.exe'), | |
| 68 | 新增: join(local, 'Google\\Chrome\\Application\\chrome.exe'), | |
| 69 | 新增: join(pf86, 'Microsoft\\Edge\\Application\\msedge.exe'), | |
| 70 | 新增: join(pf, 'Microsoft\\Edge\\Application\\msedge.exe'), | |
| 71 | 新增: ], | |
| 72 | 新增: linux: ['/usr/bin/google-chrome', '/usr/bin/google-chrome-stable', '/usr/bin/chromium', '/usr/bin/chromium-browser', '/snap/bin/chromium'], | |
| 73 | 新增: }[process.platform] || []; | |
| 74 | 新增: const found = candidates.find(p => existsSync(p)); | |
| 75 | 新增: if (!found) throw new Error('Chrome not found. Set CHROME_PATH to a Chrome, Chromium or Edge executable.'); | |
| 76 | 新增: return found; | |
| 77 | 新增:} | |
| 78 | 新增: | |
| 79 | 新增:async function openPage(server) { | |
| 80 | 新增: const { default: puppeteer } = await import('puppeteer-core'); | |
| 81 | 新增: const browser = await puppeteer.launch({ | |
| 82 | 新增: executablePath: findChrome(), | |
| 83 | 新增: headless: true, | |
| 84 | 新增: args: ['--hide-scrollbars', '--force-color-profile=srgb', '--font-render-hinting=none', '--disable-lcd-text'], | |
| 85 | 新增: }); | |
| 86 | 新增: const page = await browser.newPage(); | |
| 87 | 新增: await page.setViewport({ width: TL.width, height: TL.height, deviceScaleFactor: scale }); | |
| 88 | 新增: const { port } = server.address(); | |
| 89 | 新增: page.on('pageerror', e => console.error('page error:', e.message)); | |
| 90 | 新增: await page.goto(`http://127.0.0.1:${port}/promo/index.html?render`, { waitUntil: 'networkidle0', timeout: 120000 }); | |
| 91 | 新增: await page.evaluate(() => window.__promo.ready); | |
| 92 | 新增: // Touch every act once so lazily loaded font subsets are in before frame 0. | |
| 93 | 新增: for (let t = 0; t < TL.duration; t += 0.5) await page.evaluate(x => window.__promo.seek(x), t); | |
| 94 | 新增: await page.evaluate(() => document.fonts.ready); | |
| 95 | 新增: return { browser, page }; | |
| 96 | 新增:} | |
| 97 | 新增: | |
| 98 | 新增:async function stills(times) { | |
| 99 | 新增: const server = await serve(); | |
| 100 | 新增: const { browser, page } = await openPage(server); | |
| 101 | 新增: mkdirSync(outDir, { recursive: true }); | |
| 102 | 新增: for (const t of times) { | |
| 103 | 新增: await page.evaluate(x => window.__promo.seek(x), t); | |
| 104 | 新增: const path = join(outDir, `frame-${t.toFixed(2)}.png`); | |
| 105 | 新增: await page.screenshot({ path, type: 'png' }); | |
| 106 | 新增: console.log(path); | |
| 107 | 新增: } | |
| 108 | 新增: await browser.close(); | |
| 109 | 新增: server.close(); | |
| 110 | 新增:} | |
| 111 | 新增: | |
| 112 | 新增:async function video() { | |
| 113 | 新增: const ffmpeg = require('ffmpeg-static'); | |
| 114 | 新增: const server = await serve(); | |
| 115 | 新增: const { browser, page } = await openPage(server); | |
| 116 | 新增: mkdirSync(outDir, { recursive: true }); | |
| 117 | 新增: const total = Math.round(TL.duration * fps); | |
| 118 | 新增: const hasAudio = existsSync(audio); | |
| 119 | 新增: if (!hasAudio) console.warn(`No soundtrack at ${audio}; run "node soundtrack.mjs" first. Rendering silent video.`); | |
| 120 | 新增: const w = Math.round(TL.width * scale), h = Math.round(TL.height * scale); | |
| 121 | 新增: const ff = spawn(ffmpeg, [ | |
| 122 | 新增: '-y', '-loglevel', 'error', | |
| 123 | 新增: '-f', 'image2pipe', '-c:v', 'mjpeg', '-framerate', String(fps), '-i', '-', | |
| 124 | 新增: ...(hasAudio ? ['-i', audio] : []), | |
| 125 | 新增: '-vf', `scale=${w}:${h}:flags=lanczos,format=yuv420p`, | |
| 126 | 新增: '-c:v', 'libx264', '-preset', scale < 1 ? 'veryfast' : 'slow', '-crf', '16', '-tune', 'animation', | |
| 127 | 新增: '-colorspace', 'bt709', '-color_primaries', 'bt709', '-color_trc', 'bt709', | |
| 128 | 新增: ...(hasAudio ? ['-c:a', 'aac', '-b:a', '256k', '-shortest'] : []), | |
| 129 | 新增: '-movflags', '+faststart', output, | |
| 130 | 新增: ], { stdio: ['pipe', 'inherit', 'inherit'] }); | |
| 131 | 新增: const done = new Promise((ok, fail) => ff.on('close', c => (c === 0 ? ok() : fail(new Error(`ffmpeg exited ${c}`))))); | |
| 132 | 新增: | |
| 133 | 新增: const started = Date.now(); | |
| 134 | 新增: for (let i = 0; i < total; i++) { | |
| 135 | 新增: await page.evaluate(x => window.__promo.seek(x), i / fps); | |
| 136 | 新增: const buf = await page.screenshot({ type: 'jpeg', quality: 96, optimizeForSpeed: false }); | |
| 137 | 新增: if (!ff.stdin.write(buf)) await new Promise(r => ff.stdin.once('drain', r)); | |
| 138 | 新增: if (i % fps === 0) { | |
| 139 | 新增: const s = (Date.now() - started) / 1000; | |
| 140 | 新增: process.stdout.write(`\r${i}/${total} frames · ${s.toFixed(0)}s elapsed · ~${((s / (i + 1)) * (total - i)).toFixed(0)}s left `); | |
| 141 | 新增: } | |
| 142 | 新增: } | |
| 143 | 新增: ff.stdin.end(); | |
| 144 | 新增: await done; | |
| 145 | 新增: await browser.close(); | |
| 146 | 新增: server.close(); | |
| 147 | 新增: console.log(`\n${output}`); | |
| 148 | 新增:} | |
| 149 | 新增: | |
| 150 | 新增:if (args.includes('--preview')) { | |
| 151 | 新增: const server = await serve(Number(opt('port', 4173))); | |
| 152 | 新增: console.log(`Preview: http://127.0.0.1:${server.address().port}/promo/index.html`); | |
| 153 | 新增: console.log('Space play/pause · ←/→ seek 1s (Shift: 0.1s) · ?t=12.5 opens paused at a time'); | |
| 154 | 新增:} else if (opt('frames')) { | |
| 155 | 新增: await stills(opt('frames').split(',').map(Number)); | |
| 156 | 新增:} else { | |
| 157 | 新增: await video(); | |
| 158 | 新增:} | |
| @@ -0,0 +1,302 @@ | ||
| 1 | 新增:// Synthesise the promo soundtrack from the shared timeline: a driving pulse and | |
| 2 | 新增:// hard impacts under the problem, a warm piano in D major once Cage appears, | |
| 3 | 新增:// UI foley that lands on every click, keystroke and passing check, and a quiet | |
| 4 | 新增:// melody under the closing lines. Writes out/soundtrack.wav (48 kHz, 16-bit). | |
| 5 | 新增:import { mkdirSync, writeFileSync } from 'node:fs'; | |
| 6 | 新增:import { createRequire } from 'node:module'; | |
| 7 | 新增:import { join } from 'node:path'; | |
| 8 | 新增:import { fileURLToPath } from 'node:url'; | |
| 9 | 新增: | |
| 10 | 新增:const require = createRequire(import.meta.url); | |
| 11 | 新增:const TL = require('./timeline.js'); | |
| 12 | 新增:const here = fileURLToPath(new URL('.', import.meta.url)); | |
| 13 | 新增: | |
| 14 | 新增:const SR = 48000; | |
| 15 | 新增:const N = Math.ceil(TL.duration * SR); | |
| 16 | 新增:const dry = [new Float32Array(N), new Float32Array(N)]; | |
| 17 | 新增:const wet = [new Float32Array(N), new Float32Array(N)]; // reverb send | |
| 18 | 新增: | |
| 19 | 新增:const mtof = m => 440 * Math.pow(2, (m - 69) / 12); | |
| 20 | 新增:let seed = 7; | |
| 21 | 新增:const rnd = () => { seed = (seed * 16807) % 2147483647; return seed / 2147483647; }; | |
| 22 | 新增: | |
| 23 | 新增:function put(i, l, r, send) { | |
| 24 | 新增: if (i < 0 || i >= N) return; | |
| 25 | 新增: dry[0][i] += l; dry[1][i] += r; | |
| 26 | 新增: wet[0][i] += l * send; wet[1][i] += r * send; | |
| 27 | 新增:} | |
| 28 | 新增:const panLR = pan => [Math.cos((pan + 1) * Math.PI / 4), Math.sin((pan + 1) * Math.PI / 4)]; | |
| 29 | 新增: | |
| 30 | 新增:// Sum of decaying partials, stepped with a rotation instead of Math.sin. | |
| 31 | 新增:function partials(t0, list, { attack = 0.004, pan = 0, send = 0.3, len }) { | |
| 32 | 新增: const [gl, gr] = panLR(pan); | |
| 33 | 新增: const start = Math.round(t0 * SR); | |
| 34 | 新增: const n = Math.min(Math.round(len * SR), N - start); | |
| 35 | 新增: if (n <= 0) return; | |
| 36 | 新增: const buf = new Float32Array(n); | |
| 37 | 新增: for (const { f, a, decay } of list) { | |
| 38 | 新增: if (f >= SR / 2.2) continue; | |
| 39 | 新增: const w = 2 * Math.PI * f / SR, cw = Math.cos(w), sw = Math.sin(w); | |
| 40 | 新增: let c = 1, s = 0, env = a; | |
| 41 | 新增: const k = Math.exp(-decay / SR); | |
| 42 | 新增: for (let i = 0; i < n; i++) { | |
| 43 | 新增: buf[i] += s * env; | |
| 44 | 新增: const nc = c * cw - s * sw; s = c * sw + s * cw; c = nc; | |
| 45 | 新增: env *= k; | |
| 46 | 新增: } | |
| 47 | 新增: } | |
| 48 | 新增: const atk = Math.max(1, Math.round(attack * SR)), rel = Math.round(0.08 * SR); | |
| 49 | 新增: for (let i = 0; i < n; i++) { | |
| 50 | 新增: let e = i < atk ? i / atk : 1; | |
| 51 | 新增: if (i > n - rel) e *= (n - i) / rel; | |
| 52 | 新增: put(start + i, buf[i] * e * gl, buf[i] * e * gr, send); | |
| 53 | 新增: } | |
| 54 | 新增:} | |
| 55 | 新增: | |
| 56 | 新增:function piano(t, m, vel = 0.5, { len = 5, pan, send = 0.38, bright = 1 } = {}) { | |
| 57 | 新增: const f0 = mtof(m); | |
| 58 | 新增: const list = []; | |
| 59 | 新增: for (let h = 1; h <= 9; h++) { | |
| 60 | 新增: const f = f0 * h * Math.sqrt(1 + 0.00015 * h * h); | |
| 61 | 新增: const a = vel * 0.22 * Math.pow(h, -1.25 - (1 - bright) * 0.6) * (h === 1 ? 1 : 0.9 + 0.2 * rnd()); | |
| 62 | 新增: list.push({ f, a, decay: 1.1 + h * 0.75 + f0 / 900 }); | |
| 63 | 新增: } | |
| 64 | 新增: // soft hammer | |
| 65 | 新增: list.push({ f: f0 * 0.5 * 1.002, a: vel * 0.02, decay: 2.5 }); | |
| 66 | 新增: partials(t, list, { attack: 0.006, pan: pan ?? clampPan((m - 62) / 30), send, len }); | |
| 67 | 新增:} | |
| 68 | 新增:const clampPan = x => Math.max(-0.6, Math.min(0.6, x)); | |
| 69 | 新增: | |
| 70 | 新增:function pad(t0, t1, notes, vol = 0.05, { fadeIn = 1.5, fadeOut = 1.5, cutoff = 1400, send = 0.6 } = {}) { | |
| 71 | 新增: const start = Math.round(t0 * SR), end = Math.min(N, Math.round(t1 * SR)); | |
| 72 | 新增: const a = 1 - Math.exp(-2 * Math.PI * cutoff / SR); | |
| 73 | 新增: notes.forEach((m, ni) => { | |
| 74 | 新增: const f0 = mtof(m); | |
| 75 | 新增: [-6, 0, 6].forEach((cents, vi) => { | |
| 76 | 新增: const f = f0 * Math.pow(2, cents / 1200); | |
| 77 | 新增: const [gl, gr] = panLR(vi === 0 ? -0.5 : vi === 2 ? 0.5 : 0); | |
| 78 | 新增: const H = Math.min(10, Math.floor(5000 / f)); | |
| 79 | 新增: const osc = []; | |
| 80 | 新增: for (let h = 1; h <= H; h++) { const w = 2 * Math.PI * f * h / SR; osc.push([Math.cos(w), Math.sin(w), Math.cos(h * vi + ni), Math.sin(h * vi + ni), 1 / h]); } | |
| 81 | 新增: let lp = 0; | |
| 82 | 新增: for (let i = start; i < end; i++) { | |
| 83 | 新增: let x = 0; | |
| 84 | 新增: for (const o of osc) { const nc = o[2] * o[0] - o[3] * o[1]; o[3] = o[2] * o[1] + o[3] * o[0]; o[2] = nc; x += o[3] * o[4]; } | |
| 85 | 新增: lp += a * (x - lp); | |
| 86 | 新增: const tt = (i - start) / SR, tl = (end - i) / SR; | |
| 87 | 新增: const e = Math.min(1, tt / fadeIn) * Math.min(1, tl / fadeOut); | |
| 88 | 新增: const g = lp * e * vol / notes.length; | |
| 89 | 新增: put(i, g * gl, g * gr, send); | |
| 90 | 新增: } | |
| 91 | 新增: }); | |
| 92 | 新增: }); | |
| 93 | 新增:} | |
| 94 | 新增: | |
| 95 | 新增:function sine(t, f, vol, decay, { f1 = f, glide = 0.05, pan = 0, send = 0.25, attack = 0.002 } = {}) { | |
| 96 | 新增: const [gl, gr] = panLR(pan); | |
| 97 | 新增: const start = Math.round(t * SR), n = Math.round(Math.min(3, 7 / decay) * SR); | |
| 98 | 新增: let ph = 0; | |
| 99 | 新增: for (let i = 0; i < n; i++) { | |
| 100 | 新增: const tt = i / SR; | |
| 101 | 新增: const fr = f1 + (f - f1) * Math.exp(-tt / glide); | |
| 102 | 新增: ph += 2 * Math.PI * fr / SR; | |
| 103 | 新增: const e = Math.min(1, tt / attack) * Math.exp(-tt * decay); | |
| 104 | 新增: const x = Math.sin(ph) * e * vol; | |
| 105 | 新增: put(start + i, x * gl, x * gr, send); | |
| 106 | 新增: } | |
| 107 | 新增:} | |
| 108 | 新增: | |
| 109 | 新增:function noise(t, len, vol, { lo = 400, hi = 6000, shape = x => Math.sin(Math.PI * x), pan = 0, send = 0.4 } = {}) { | |
| 110 | 新增: const [gl, gr] = panLR(pan); | |
| 111 | 新增: const start = Math.round(t * SR), n = Math.round(len * SR); | |
| 112 | 新增: let l1 = 0, l2 = 0; | |
| 113 | 新增: for (let i = 0; i < n; i++) { | |
| 114 | 新增: const k = i / n; | |
| 115 | 新增: const fc = lo + (hi - lo) * shape(k); | |
| 116 | 新增: const a = 1 - Math.exp(-2 * Math.PI * fc / SR); | |
| 117 | 新增: l1 += a * (rnd() * 2 - 1 - l1); | |
| 118 | 新增: l2 += (1 - Math.exp(-2 * Math.PI * lo * 0.5 / SR)) * (l1 - l2); | |
| 119 | 新增: const x = (l1 - l2) * shape(k) * vol; | |
| 120 | 新增: put(start + i, x * gl, x * gr, send); | |
| 121 | 新增: } | |
| 122 | 新增:} | |
| 123 | 新增: | |
| 124 | 新增:const click = (t, vol = 0.12, pan = 0.1) => { noise(t, 0.018, vol, { lo: 2500, hi: 7000, shape: x => 1 - x, pan, send: 0.08 }); sine(t, 1900, vol * 0.25, 120, { pan, send: 0.05 }); }; | |
| 125 | 新增:const key = (t, i) => { noise(t, 0.012, 0.05 + 0.02 * rnd(), { lo: 1800 + rnd() * 900, hi: 5000, shape: x => 1 - x, pan: -0.15 + rnd() * 0.3, send: 0.04 }); }; | |
| 126 | 新增:const tock = (t, vol = 0.35) => { sine(t, 180, vol, 14, { f1: 70, glide: 0.04, send: 0.2 }); noise(t, 0.03, vol * 0.25, { lo: 300, hi: 1200, shape: x => 1 - x, send: 0.1 }); }; | |
| 127 | 新增:const pip = (t, f = 2200, vol = 0.05) => sine(t, f, vol, 30, { send: 0.3 }); | |
| 128 | 新增:const bell = (t, m, vol) => { | |
| 129 | 新增: const f = mtof(m); | |
| 130 | 新增: partials(t, [[1, 1, 1.4], [2.76, 0.4, 3], [5.4, 0.18, 5], [8.93, 0.08, 7]].map(([r, a, d]) => ({ f: f * r, a: a * vol, decay: d })), { attack: 0.003, len: 4, send: 0.55, pan: clampPan((m - 74) / 20) }); | |
| 131 | 新增:}; | |
| 132 | 新增: | |
| 133 | 新增:// ---------- score ---------- | |
| 134 | 新增:const { pain: P, room: R, app: A, perks: K, letter: L, end: En } = TL; | |
| 135 | 新增: | |
| 136 | 新增:// Act 1 · the problem: a driving pulse, an impact on every cut, then silence. | |
| 137 | 新增:const kick = (t, vol) => { sine(t, 95, vol, 9, { f1: 42, glide: 0.035, send: 0.08 }); noise(t, 0.012, vol * 0.25, { lo: 1500, hi: 4000, shape: x => 1 - x, send: 0.02 }); }; | |
| 138 | 新增:const boom = (t, k) => { | |
| 139 | 新增: sine(t, 72, 0.36 * k, 2.6, { f1: 30, glide: 0.12, send: 0.35 }); | |
| 140 | 新增: noise(t, 0.6, 0.14 * k, { lo: 90, hi: 1600, shape: x => Math.pow(1 - x, 3), send: 0.55 }); | |
| 141 | 新增: noise(t, 0.04, 0.12 * k, { lo: 3000, hi: 9000, shape: x => 1 - x, send: 0.2 }); | |
| 142 | 新增:}; | |
| 143 | 新增:const stamp = (t, vol = 0.3) => { tock(t, vol); noise(t, 0.05, vol * 0.3, { lo: 800, hi: 5000, shape: x => 1 - x, send: 0.15 }); }; | |
| 144 | 新增:const bpm = 60 / 128; | |
| 145 | 新增:pad(0, P.b5 + 0.04, [26, 38, 45, 51], 0.05, { fadeIn: 0.4, fadeOut: 0.04, cutoff: 650, send: 0.45 }); | |
| 146 | 新增:for (let t = P.slam, i = 0; t < P.b5 - 0.05; t += bpm, i++) { | |
| 147 | 新增: const build = 0.55 + 0.45 * (t / P.b5); | |
| 148 | 新增: kick(t, 0.22 * build); | |
| 149 | 新增: sine(t, mtof(i % 8 === 6 ? 39 : 38), 0.05 * build, 6, { send: 0.1 }); | |
| 150 | 新增: noise(t + bpm / 2, 0.02, 0.035 * build, { lo: 5000, hi: 9000, shape: x => 1 - x, send: 0.05, pan: 0.3 }); | |
| 151 | 新增:} | |
| 152 | 新增:boom(P.slam, 1); | |
| 153 | 新增:sine(P.slam, mtof(69), 0.08, 1.6, { send: 0.5 }); | |
| 154 | 新增:sine(P.slam, mtof(70), 0.07, 1.6, { send: 0.5 }); | |
| 155 | 新增:[P.b2, P.b3, P.b4].forEach(t => boom(t, 0.7)); | |
| 156 | 新增:P.losses.forEach(t => stamp(t, 0.32)); | |
| 157 | 新增:P.rows.forEach(t => noise(t, 0.05, 0.06, { lo: 2500, hi: 6000, shape: x => 1 - x, send: 0.1 })); | |
| 158 | 新增:stamp(P.total, 0.4); sine(P.total, mtof(50), 0.08, 2, { send: 0.4 }); sine(P.total, mtof(51), 0.07, 2, { send: 0.4 }); | |
| 159 | 新增:noise(P.wires - 0.1, 0.6, 0.05, { lo: 400, hi: 5000, shape: x => x, send: 0.35 }); | |
| 160 | 新增:P.tags.forEach((t, i) => { sine(t, mtof(84), 0.05, 10, { pan: -0.3, send: 0.3 }); sine(t + 0.09, mtof(80), 0.05, 9, { pan: -0.3, send: 0.3 }); }); | |
| 161 | 新增:boom(P.vmMem, 0.45); | |
| 162 | 新增:sine(P.vmMem, 110, 0.06, 1.5, { send: 0.2 }); sine(P.vmMem, 116.5, 0.06, 1.5, { send: 0.2 }); // grinding beat | |
| 163 | 新增:P.vmTodo.forEach(t => stamp(t, 0.22)); | |
| 164 | 新增:// the question: a breath of silence, one low note, then a riser into the light | |
| 165 | 新增:piano(P.b5 + 0.2, 38, 0.5, { len: 2.5, bright: 0.5, send: 0.6 }); | |
| 166 | 新增:noise(P.end - 0.95, 0.95, 0.09, { lo: 300, hi: 9000, shape: x => x * x * x, send: 0.5 }); | |
| 167 | 新增:sine(P.end - 0.95, 900, 0.03, 0.4, { f1: 180, glide: 0.5, send: 0.6 }); | |
| 168 | 新增: | |
| 169 | 新增:// Act 2 · the answer: release into D major, pixels sparkle, bars land. | |
| 170 | 新增:pad(R.start - 0.05, K.out + 0.6, [50, 57, 62, 66], 0.05, { fadeIn: 1.2, fadeOut: 1.4, cutoff: 1500, send: 0.7 }); | |
| 171 | 新增:[26, 38, 50, 57, 62, 66, 69, 76].forEach((m, i) => piano(R.start + i * 0.03, m, 0.48 - i * 0.03, { len: 5, bright: 0.8, send: 0.55 })); | |
| 172 | 新增:bell(R.start, 86, 0.08); | |
| 173 | 新增:const sparkle = [86, 88, 90, 93, 95, 98]; | |
| 174 | 新增:for (let i = 0; i < 14; i++) pip(R.pixels + 0.04 + i * 0.05 + rnd() * 0.03, mtof(sparkle[Math.floor(rnd() * sparkle.length)]), 0.025 + rnd() * 0.015); | |
| 175 | 新增:noise(R.frame, 0.45, 0.035, { lo: 600, hi: 3500, send: 0.4 }); | |
| 176 | 新增:R.bars.forEach(b => tock(b + 0.24, 0.42)); | |
| 177 | 新增:pip(R.blink, 3100, 0.03); | |
| 178 | 新增:[62, 66, 69, 74].forEach((m, i) => piano(R.word + i * 0.04, m, 0.26, { len: 4 })); | |
| 179 | 新增:piano(R.pos + 0.4, 81, 0.3, { len: 4, bright: 0.9 }); | |
| 180 | 新增:piano(R.pos + 0.62, 86, 0.24, { len: 4, bright: 0.9 }); | |
| 181 | 新增:piano(R.sub + 0.75, 78, 0.26, { len: 4, bright: 0.9 }); | |
| 182 | 新增: | |
| 183 | 新增:// Act 3 · the app: an unhurried D-major arpeggio under the UI. | |
| 184 | 新增:const beat = 60 / 76, bar = beat * 4, arpStart = A.rise + 0.45; | |
| 185 | 新增:const chords = [ | |
| 186 | 新增: [38, [62, 66, 69]], [37, [61, 64, 69]], [35, [62, 66, 71]], [31, [62, 67, 71]], | |
| 187 | 新增: [42, [62, 66, 69]], [40, [62, 67, 71]], [33, [62, 64, 69]], [33, [61, 64, 69]], | |
| 188 | 新增:]; | |
| 189 | 新增:chords.forEach(([bass, [a, b, c]], ci) => { | |
| 190 | 新增: const t0 = arpStart + ci * bar; | |
| 191 | 新增: if (t0 > A.out) return; | |
| 192 | 新增: piano(t0, bass, 0.42, { len: bar + 0.6, bright: 0.5, send: 0.35 }); | |
| 193 | 新增: piano(t0 + beat * 2, bass + 7, 0.24, { len: bar, bright: 0.5, send: 0.35 }); | |
| 194 | 新增: const pat = [a, b + 12, c, a + 12, b, c + 12, a + 12, b + 12]; | |
| 195 | 新增: pat.forEach((m, k) => { | |
| 196 | 新增: const t = t0 + k * beat / 2; | |
| 197 | 新增: if (t > A.out + 0.3) return; | |
| 198 | 新增: piano(t, m, (k % 2 ? 0.16 : 0.22) * (k === 0 ? 1.2 : 1), { len: 2.6, send: 0.42 }); | |
| 199 | 新增: }); | |
| 200 | 新增:}); | |
| 201 | 新增:noise(A.modalOpen - 0.05, 0.35, 0.03, { lo: 500, hi: 3000, send: 0.3 }); | |
| 202 | 新增:noise(A.modalClose - 0.05, 0.3, 0.025, { lo: 500, hi: 2500, send: 0.3 }); | |
| 203 | 新增:[A.clickProxy, A.clickNode, A.clickUse, A.clickLaunch, A.clickTerminal].forEach(t => click(t)); | |
| 204 | 新增:pip(A.tzFlip - 0.3, 1600, 0.035); pip(A.tzFlip, 2000, 0.04); | |
| 205 | 新增:const scale = [74, 76, 78, 79, 81, 83, 85, 86, 88, 90, 91]; | |
| 206 | 新增:scale.forEach((m, i) => sine(A.checks + 0.15 + i * A.checkStep, mtof(m), 0.05, 7, { send: 0.45, pan: i < 6 ? -0.25 : 0.25 })); | |
| 207 | 新增:[74, 78, 81, 86].forEach((m, i) => bell(A.released + i * 0.05, m, 0.09)); | |
| 208 | 新增:for (let i = 0; i < 6; i++) key(A.typeClaude + i * 0.1, i); | |
| 209 | 新增:click(A.enterClaude, 0.1, -0.1); | |
| 210 | 新增:const promptLen = [...'帮我给 hello-cage 写一份 README'].length; | |
| 211 | 新增:const per = (A.enterPrompt - 0.2 - A.typePrompt) / promptLen; | |
| 212 | 新增:for (let i = 0; i < promptLen; i++) key(A.typePrompt + i * per, i); | |
| 213 | 新增:click(A.enterPrompt, 0.1, -0.1); | |
| 214 | 新增:A.reply.forEach(t => pip(t, 1250, 0.02)); | |
| 215 | 新增: | |
| 216 | 新增:// Act 4 · perks: a lift to G, one chime per card. | |
| 217 | 新增:piano(K.head, 31, 0.4, { len: 5, bright: 0.5, send: 0.45 }); | |
| 218 | 新增:[55, 59, 62, 67].forEach((m, i) => piano(K.head + 0.05 + i * 0.05, m, 0.2, { len: 4.5, send: 0.5 })); | |
| 219 | 新增:[74, 78, 81, 86].forEach((m, i) => bell(K.tiles[i], m, 0.07)); | |
| 220 | 新增:piano(K.tiles[3] + 1.2, 33, 0.32, { len: 4, bright: 0.5, send: 0.45 }); | |
| 221 | 新增:[57, 61, 64, 69].forEach((m, i) => piano(K.tiles[3] + 1.25 + i * 0.05, m, 0.16, { len: 3.5, send: 0.5 })); | |
| 222 | 新增: | |
| 223 | 新增:// Act 5 · the letter: chords breathe, a melody answers each line. | |
| 224 | 新增:noise(K.out, 1.0, 0.03, { lo: 300, hi: 2500, send: 0.7 }); | |
| 225 | 新增:pad(L.start - 0.2, En.start + 1.2, [43, 55, 59, 62, 66], 0.06, { fadeIn: 1.5, fadeOut: 1.4, cutoff: 1100, send: 0.75 }); | |
| 226 | 新增:const lchords = [[L.start, 31, [55, 59, 62, 66]], [L.lines[0], 42, [57, 62, 66]], [L.lines[1], 40, [55, 59, 62, 67]], [L.lines[2], 33, [57, 62, 64]], [L.lines[2] + 1.2, 33, [57, 61, 64]]]; | |
| 227 | 新增:lchords.forEach(([t, bass, notes]) => { | |
| 228 | 新增: piano(t, bass, 0.4, { len: 4.5, bright: 0.45, send: 0.5 }); | |
| 229 | 新增: notes.forEach((m, i) => piano(t + 0.06 + i * 0.07, m, 0.17, { len: 4, bright: 0.6, send: 0.55 })); | |
| 230 | 新增:}); | |
| 231 | 新增:[[0, 0, 81], [0, 0.45, 78], [1, 0, 79], [1, 0.45, 76], [2, 0, 76], [2, 0.45, 78], [2, 1.2, 76]].forEach(([li, dt, m]) => { | |
| 232 | 新增: piano(L.lines[li] + dt, m, 0.3, { len: 3.5, send: 0.55, bright: 0.9 }); | |
| 233 | 新增:}); | |
| 234 | 新增: | |
| 235 | 新增:// Act 6 · end card: resolve home, bars land, one last blink. | |
| 236 | 新增:[26, 38, 45, 54, 64, 69, 74].forEach((m, i) => piano(En.start + 0.05 + i * 0.06, m, 0.42 - i * 0.025, { len: 6.2, bright: 0.65, send: 0.6 })); | |
| 237 | 新增:pad(En.start, TL.duration, [38, 50, 57, 64, 66], 0.05, { fadeIn: 1.2, fadeOut: 3.2, cutoff: 1200, send: 0.8 }); | |
| 238 | 新增:const endA = En.start + 0.3; | |
| 239 | 新增:[endA + 0.85 + 0.24, endA + 1.0 + 0.24].forEach(t => tock(t, 0.22)); | |
| 240 | 新增:piano(endA + 2.5, 86, 0.16, { len: 4, send: 0.7 }); | |
| 241 | 新增:pip(En.blink, 3100, 0.03); | |
| 242 | 新增: | |
| 243 | 新增:// ---------- reverb (Freeverb) ---------- | |
| 244 | 新增:function freeverb(input, spread) { | |
| 245 | 新增: const s = SR / 44100; | |
| 246 | 新增: const combT = [1116, 1188, 1277, 1356, 1422, 1491, 1557, 1617].map(x => Math.round((x + spread) * s)); | |
| 247 | 新增: const apT = [556, 441, 341, 225].map(x => Math.round((x + spread) * s)); | |
| 248 | 新增: const out = new Float32Array(N); | |
| 249 | 新增: const room = 0.86, damp = 0.28; | |
| 250 | 新增: const combs = combT.map(n => ({ b: new Float32Array(n), i: 0, f: 0 })); | |
| 251 | 新增: const aps = apT.map(n => ({ b: new Float32Array(n), i: 0 })); | |
| 252 | 新增: for (let i = 0; i < N; i++) { | |
| 253 | 新增: const x = input[i] * 0.015; | |
| 254 | 新增: let y = 0; | |
| 255 | 新增: for (const c of combs) { | |
| 256 | 新增: const o = c.b[c.i]; | |
| 257 | 新增: c.f = o * (1 - damp) + c.f * damp; | |
| 258 | 新增: c.b[c.i] = x + c.f * room; | |
| 259 | 新增: if (++c.i >= c.b.length) c.i = 0; | |
| 260 | 新增: y += o; | |
| 261 | 新增: } | |
| 262 | 新增: for (const a of aps) { | |
| 263 | 新增: const o = a.b[a.i]; | |
| 264 | 新增: a.b[a.i] = y + o * 0.5; | |
| 265 | 新增: if (++a.i >= a.b.length) a.i = 0; | |
| 266 | 新增: y = o - y; | |
| 267 | 新增: } | |
| 268 | 新增: out[i] = y; | |
| 269 | 新增: } | |
| 270 | 新增: return out; | |
| 271 | 新增:} | |
| 272 | 新增:const rv = [freeverb(wet[0], 0), freeverb(wet[1], 23)]; | |
| 273 | 新增: | |
| 274 | 新增:// ---------- master ---------- | |
| 275 | 新增:const mix = [new Float32Array(N), new Float32Array(N)]; | |
| 276 | 新增:let peak = 0; | |
| 277 | 新增:for (let i = 0; i < N; i++) { | |
| 278 | 新增: for (let c = 0; c < 2; c++) { | |
| 279 | 新增: const v = dry[c][i] + rv[c][i] * 2.4 + rv[1 - c][i] * 0.4; | |
| 280 | 新增: mix[c][i] = v; | |
| 281 | 新增: peak = Math.max(peak, Math.abs(v)); | |
| 282 | 新增: } | |
| 283 | 新增:} | |
| 284 | 新增:const gain = 0.86 / peak; | |
| 285 | 新增:const pcm = Buffer.alloc(N * 4); | |
| 286 | 新增:for (let i = 0; i < N; i++) { | |
| 287 | 新增: const t = i / SR; | |
| 288 | 新增: const fade = Math.min(1, t / 0.05) * Math.min(1, (TL.duration - t) / 1.6); | |
| 289 | 新增: for (let c = 0; c < 2; c++) { | |
| 290 | 新增: const v = Math.tanh(mix[c][i] * gain * 1.1) * fade; | |
| 291 | 新增: pcm.writeInt16LE(Math.round(Math.max(-1, Math.min(1, v)) * 32767), i * 4 + c * 2); | |
| 292 | 新增: } | |
| 293 | 新增:} | |
| 294 | 新增:const header = Buffer.alloc(44); | |
| 295 | 新增:header.write('RIFF', 0); header.writeUInt32LE(36 + pcm.length, 4); header.write('WAVE', 8); | |
| 296 | 新增:header.write('fmt ', 12); header.writeUInt32LE(16, 16); header.writeUInt16LE(1, 20); header.writeUInt16LE(2, 22); | |
| 297 | 新增:header.writeUInt32LE(SR, 24); header.writeUInt32LE(SR * 4, 28); header.writeUInt16LE(4, 32); header.writeUInt16LE(16, 34); | |
| 298 | 新增:header.write('data', 36); header.writeUInt32LE(pcm.length, 40); | |
| 299 | 新增:mkdirSync(join(here, 'out'), { recursive: true }); | |
| 300 | 新增:const path = join(here, 'out', 'soundtrack.wav'); | |
| 301 | 新增:writeFileSync(path, Buffer.concat([header, pcm])); | |
| 302 | 新增:console.log(`${path} · ${TL.duration}s · peak gain ${gain.toFixed(2)}`); | |
| @@ -0,0 +1,99 @@ | ||
| 1 | 新增:// Shared timing for the promo page (promo.js) and the soundtrack (soundtrack.mjs). | |
| 2 | 新增:// All values are seconds from the start of the video. Loaded as a classic script | |
| 3 | 新增:// in the browser and through require() in Node. | |
| 4 | 新增:(function (root) { | |
| 5 | 新增: const TL = { | |
| 6 | 新增: duration: 60, | |
| 7 | 新增: fps: 60, | |
| 8 | 新增: width: 1920, | |
| 9 | 新增: height: 1080, | |
| 10 | 新增: | |
| 11 | 新增: // Act 1 · the problem, four hard-cut beats and a question. | |
| 12 | 新增: pain: { | |
| 13 | 新增: slam: 0.15, | |
| 14 | 新增: losses: [0.85, 1.15, 1.45], | |
| 15 | 新增: b2: 3.4, | |
| 16 | 新增: rows: [3.75, 4.05, 4.35, 4.65], | |
| 17 | 新增: total: 5.0, | |
| 18 | 新增: b3: 6.4, | |
| 19 | 新增: wires: 6.75, | |
| 20 | 新增: tags: [7.25, 7.55, 7.85, 8.15, 8.45], | |
| 21 | 新增: b4: 9.4, | |
| 22 | 新增: vm: 9.55, | |
| 23 | 新增: vmMem: 10.5, | |
| 24 | 新增: vmTodo: [10.9, 11.15, 11.4, 11.65], | |
| 25 | 新增: b5: 12.2, | |
| 26 | 新增: end: 13.75, | |
| 27 | 新增: }, | |
| 28 | 新增: | |
| 29 | 新增: // Act 2 · the answer. | |
| 30 | 新增: room: { | |
| 31 | 新增: start: 13.75, | |
| 32 | 新增: pixels: 14.0, | |
| 33 | 新增: frame: 14.65, | |
| 34 | 新增: bars: [15.0, 15.2], | |
| 35 | 新增: blink: 16.0, | |
| 36 | 新增: word: 15.55, | |
| 37 | 新增: pos: 16.1, | |
| 38 | 新增: sub: 16.75, | |
| 39 | 新增: end: 19.7, | |
| 40 | 新增: }, | |
| 41 | 新增: | |
| 42 | 新增: // Act 3 · three steps inside the app. | |
| 43 | 新增: app: { | |
| 44 | 新增: rise: 19.4, | |
| 45 | 新增: step1: 20.4, | |
| 46 | 新增: clickProxy: 22.1, | |
| 47 | 新增: modalOpen: 22.3, | |
| 48 | 新增: clickNode: 23.8, | |
| 49 | 新增: clickUse: 24.7, | |
| 50 | 新增: modalClose: 24.8, | |
| 51 | 新增: tzFlip: 26.15, | |
| 52 | 新增: step2: 27.6, | |
| 53 | 新增: clickLaunch: 28.5, | |
| 54 | 新增: launch: 28.6, | |
| 55 | 新增: image: [29.0, 30.0], | |
| 56 | 新增: tools: [30.0, 30.8], | |
| 57 | 新增: checks: 30.85, | |
| 58 | 新增: checkStep: 0.2, | |
| 59 | 新增: released: 33.25, | |
| 60 | 新增: step3: 34.8, | |
| 61 | 新增: clickTerminal: 35.25, | |
| 62 | 新增: terminal: 35.4, | |
| 63 | 新增: typeClaude: 36.2, | |
| 64 | 新增: enterClaude: 37.0, | |
| 65 | 新增: welcome: 37.2, | |
| 66 | 新增: typePrompt: 37.8, | |
| 67 | 新增: enterPrompt: 39.4, | |
| 68 | 新增: reply: [39.65, 40.3, 40.95, 41.7], | |
| 69 | 新增: out: 43.0, | |
| 70 | 新增: end: 44.0, | |
| 71 | 新增: }, | |
| 72 | 新增: | |
| 73 | 新增: // Act 4 · everything that comes in the box. | |
| 74 | 新增: perks: { | |
| 75 | 新增: start: 43.8, | |
| 76 | 新增: head: 44.1, | |
| 77 | 新增: tiles: [44.7, 44.95, 45.2, 45.45], | |
| 78 | 新增: out: 48.9, | |
| 79 | 新增: end: 49.5, | |
| 80 | 新增: }, | |
| 81 | 新增: | |
| 82 | 新增: // Act 5 · why the cage exists. | |
| 83 | 新增: letter: { | |
| 84 | 新增: start: 49.3, | |
| 85 | 新增: lines: [50.1, 51.0, 51.9], | |
| 86 | 新增: out: 54.0, | |
| 87 | 新增: end: 54.7, | |
| 88 | 新增: }, | |
| 89 | 新增: | |
| 90 | 新增: // Act 6 · end card. | |
| 91 | 新增: end: { | |
| 92 | 新增: start: 54.85, | |
| 93 | 新增: blink: 57.9, | |
| 94 | 新增: }, | |
| 95 | 新增: }; | |
| 96 | 新增: | |
| 97 | 新增: if (typeof module === 'object' && module.exports) module.exports = TL; | |
| 98 | 新增: else root.TL = TL; | |
| 99 | 新增:})(this); | |
| @@ -0,0 +1,319 @@ | ||
| 1 | 新增:// Uses Playwright's isolated Chromium headless shell and its process-local | |
| 2 | 新增:// clipboard. Do not substitute a headed browser or a running user profile. | |
| 3 | 新增:import assert from "node:assert/strict"; | |
| 4 | 新增:import http from "node:http"; | |
| 5 | 新增:import { createRequire } from "node:module"; | |
| 6 | 新增:import { randomUUID } from "node:crypto"; | |
| 7 | 新增:import { BrowserClipboard } from "../internal/cage/browser-clipboard.mjs"; | |
| 8 | 新增: | |
| 9 | 新增:const { chromium } = createRequire(import.meta.url)( | |
| 10 | 新增: process.env.CAGE_PLAYWRIGHT_MODULE || "playwright", | |
| 11 | 新增:); | |
| 12 | 新增:const site = http.createServer((request, response) => { | |
| 13 | 新增: response.setHeader("Content-Type", "text/html; charset=utf-8"); | |
| 14 | 新增: response.end(`<!doctype html><button id="copy">Copy</button><script> | |
| 15 | 新增: const originalWrite = navigator.clipboard.writeText.bind(navigator.clipboard); | |
| 16 | 新增: window.action = () => navigator.clipboard.writeText("中文🙂\\nexact text"); | |
| 17 | 新增: document.querySelector("button").onclick = () => { | |
| 18 | 新增: window.finished = false; | |
| 19 | 新增: Promise.resolve().then(() => action()).then(() => { finished = true; }, () => { finished = true; }); | |
| 20 | 新增: }; | |
| 21 | 新增: </script>`); | |
| 22 | 新增:}); | |
| 23 | 新增:await new Promise((resolve) => site.listen(0, "127.0.0.1", resolve)); | |
| 24 | 新增:const origin = `http://127.0.0.1:${site.address().port}`; | |
| 25 | 新增:const browser = await chromium.launch({ headless: true }); | |
| 26 | 新增:const context = await browser.newContext({ | |
| 27 | 新增: permissions: ["clipboard-read", "clipboard-write"], | |
| 28 | 新增:}); | |
| 29 | 新增:const copies = []; | |
| 30 | 新增:const sessions = new Map(); | |
| 31 | 新增:const pageIds = new WeakMap(); | |
| 32 | 新增:const observer = new BrowserClipboard( | |
| 33 | 新增: (method, params, id) => sessions.get(id).send(method, params), | |
| 34 | 新增: (copy) => copies.push(copy), | |
| 35 | 新增:); | |
| 36 | 新增:async function attach(page, id) { | |
| 37 | 新增: pageIds.set(page, id); | |
| 38 | 新增: const session = await context.newCDPSession(page); | |
| 39 | 新增: sessions.set(id, session); | |
| 40 | 新增: for (const method of [ | |
| 41 | 新增: "Runtime.executionContextCreated", | |
| 42 | 新增: "Runtime.executionContextDestroyed", | |
| 43 | 新增: "Runtime.executionContextsCleared", | |
| 44 | 新增: "Runtime.bindingCalled", | |
| 45 | 新增: "Page.frameNavigated", | |
| 46 | 新增: "Page.frameDetached", | |
| 47 | 新增: ]) | |
| 48 | 新增: session.on(method, (params) => | |
| 49 | 新增: observer.event({ method, params, sessionId: id }), | |
| 50 | 新增: ); | |
| 51 | 新增: await session.send("Page.enable"); | |
| 52 | 新增: return observer.attach(id, id); | |
| 53 | 新增:} | |
| 54 | 新增:async function click(page, expected) { | |
| 55 | 新增: const count = copies.length; | |
| 56 | 新增: await observer.setContext(pageIds.get(page), randomUUID()); | |
| 57 | 新增: await page.click("#copy"); | |
| 58 | 新增: await page.waitForFunction(() => window.finished); | |
| 59 | 新增: await page.waitForTimeout(50); | |
| 60 | 新增: assert.deepEqual( | |
| 61 | 新增: copies.slice(count).map((copy) => copy.text), | |
| 62 | 新增: expected, | |
| 63 | 新增: ); | |
| 64 | 新增:} | |
| 65 | 新增:try { | |
| 66 | 新增: const page = await context.newPage(); | |
| 67 | 新增: await page.goto(origin); | |
| 68 | 新增: assert.deepEqual(await attach(page, "existing"), { skipped: [] }); | |
| 69 | 新增: await observer.setContext("existing", randomUUID()); | |
| 70 | 新增: await sessions.get("existing").send("Runtime.evaluate", { | |
| 71 | 新增: expression: 'navigator.clipboard.writeText("background write")', | |
| 72 | 新增: awaitPromise: true, | |
| 73 | 新增: userGesture: false, | |
| 74 | 新增: }); | |
| 75 | 新增: await page.waitForTimeout(50); | |
| 76 | 新增: assert.deepEqual(copies, []); | |
| 77 | 新增: await click(page, ["中文🙂\nexact text"]); | |
| 78 | 新增: await page.reload(); | |
| 79 | 新增: await click(page, ["中文🙂\nexact text"]); | |
| 80 | 新增: | |
| 81 | 新增: await page.evaluate(() => { | |
| 82 | 新增: window.action = () => | |
| 83 | 新增: navigator.clipboard.write([ | |
| 84 | 新增: new ClipboardItem({ | |
| 85 | 新增: "text/plain": new Blob(["ClipboardItem🙂"], { type: "text/plain" }), | |
| 86 | 新增: }), | |
| 87 | 新增: ]); | |
| 88 | 新增: }); | |
| 89 | 新增: await click(page, ["ClipboardItem🙂"]); | |
| 90 | 新增: await page.evaluate(() => { | |
| 91 | 新增: document.addEventListener("copy", (event) => { | |
| 92 | 新增: event.clipboardData.setData("text/plain", "first value"); | |
| 93 | 新增: event.clipboardData.clearData("text/plain"); | |
| 94 | 新增: event.clipboardData.setData("text", "execCommand 精确文本"); | |
| 95 | 新增: event.preventDefault(); | |
| 96 | 新增: }); | |
| 97 | 新增: window.action = () => document.execCommand("copy"); | |
| 98 | 新增: }); | |
| 99 | 新增: await click(page, ["execCommand 精确文本"]); | |
| 100 | 新增: | |
| 101 | 新增: for (const mode of ["textarea", "input", "shadow", "password", "collapsed"]) { | |
| 102 | 新增: await page.reload(); | |
| 103 | 新增: const previousClipboard = await page.evaluate(() => | |
| 104 | 新增: navigator.clipboard.readText(), | |
| 105 | 新增: ); | |
| 106 | 新增: await page.evaluate((mode) => { | |
| 107 | 新增: window.action = () => { | |
| 108 | 新增: const field = document.createElement( | |
| 109 | 新增: mode === "input" || mode === "password" ? "input" : "textarea", | |
| 110 | 新增: ); | |
| 111 | 新增: if (mode === "password") field.type = "password"; | |
| 112 | 新增: field.value = "默认复制🙂\n保留\u00a0空格"; | |
| 113 | 新增: let parent = document.body; | |
| 114 | 新增: if (mode === "shadow") { | |
| 115 | 新增: const host = document.createElement("div"); | |
| 116 | 新增: document.body.append(host); | |
| 117 | 新增: parent = host.attachShadow({ mode: "open" }); | |
| 118 | 新增: } | |
| 119 | 新增: parent.append(field); | |
| 120 | 新增: field.select(); | |
| 121 | 新增: if (mode === "collapsed") field.setSelectionRange(0, 0); | |
| 122 | 新增: document.execCommand("copy"); | |
| 123 | 新增: field.remove(); | |
| 124 | 新增: }; | |
| 125 | 新增: }, mode); | |
| 126 | 新增: const expected = | |
| 127 | 新增: mode === "input" | |
| 128 | 新增: ? "默认复制🙂保留\u00a0空格" | |
| 129 | 新增: : "默认复制🙂\n保留\u00a0空格"; | |
| 130 | 新增: const exported = mode !== "password" && mode !== "collapsed"; | |
| 131 | 新增: await click(page, exported ? [expected] : []); | |
| 132 | 新增: assert.equal( | |
| 133 | 新增: await page.evaluate(() => navigator.clipboard.readText()), | |
| 134 | 新增: exported ? expected : previousClipboard, | |
| 135 | 新增: mode, | |
| 136 | 新增: ); | |
| 137 | 新增: } | |
| 138 | 新增: | |
| 139 | 新增: await page.reload(); | |
| 140 | 新增: await page.evaluate(() => { | |
| 141 | 新增: window.action = () => { | |
| 142 | 新增: const field = document.createElement("textarea"); | |
| 143 | 新增: field.value = "original selection"; | |
| 144 | 新增: const content = document.createElement("div"); | |
| 145 | 新增: content.innerHTML = 'a<img alt="image alternative">b'; | |
| 146 | 新增: document.body.append(field, content); | |
| 147 | 新增: field.select(); | |
| 148 | 新增: document.addEventListener( | |
| 149 | 新增: "copy", | |
| 150 | 新增: () => getSelection().selectAllChildren(content), | |
| 151 | 新增: { once: true }, | |
| 152 | 新增: ); | |
| 153 | 新增: document.execCommand("copy"); | |
| 154 | 新增: field.remove(); | |
| 155 | 新增: }; | |
| 156 | 新增: }); | |
| 157 | 新增: await click(page, []); | |
| 158 | 新增: assert.equal( | |
| 159 | 新增: await page.evaluate(() => navigator.clipboard.readText()), | |
| 160 | 新增: "aimage alternativeb", | |
| 161 | 新增: ); | |
| 162 | 新增: | |
| 163 | 新增: await page.reload(); | |
| 164 | 新增: await page.evaluate(() => { | |
| 165 | 新增: window.action = () => {}; | |
| 166 | 新增: }); | |
| 167 | 新增: await click(page, []); | |
| 168 | 新增: await page.evaluate(() => { | |
| 169 | 新增: window.action = () => | |
| 170 | 新增: document.dispatchEvent( | |
| 171 | 新增: new ClipboardEvent("copy", { | |
| 172 | 新增: clipboardData: new DataTransfer(), | |
| 173 | 新增: cancelable: true, | |
| 174 | 新增: }), | |
| 175 | 新增: ); | |
| 176 | 新增: }); | |
| 177 | 新增: await click(page, []); | |
| 178 | 新增: await page.evaluate(() => { | |
| 179 | 新增: window.action = () => | |
| 180 | 新增: navigator.clipboard.write([ | |
| 181 | 新增: new ClipboardItem({ | |
| 182 | 新增: "text/plain": new Blob(["must not escape"], { type: "text/plain" }), | |
| 183 | 新增: "application/x-cage-invalid": new Blob(["unsupported"], { | |
| 184 | 新增: type: "application/x-cage-invalid", | |
| 185 | 新增: }), | |
| 186 | 新增: }), | |
| 187 | 新增: ]); | |
| 188 | 新增: }); | |
| 189 | 新增: await click(page, []); | |
| 190 | 新增: | |
| 191 | 新增: // The observer must keep captured primitives when a site later patches them. | |
| 192 | 新增: await page.reload(); | |
| 193 | 新增: await page.evaluate(() => { | |
| 194 | 新增: window.action = () => | |
| 195 | 新增: navigator.clipboard.writeText("captured native success"); | |
| 196 | 新增: Function.prototype.call = () => { | |
| 197 | 新增: throw new Error("site patched call"); | |
| 198 | 新增: }; | |
| 199 | 新增: Document.prototype.hasFocus = () => false; | |
| 200 | 新增: JSON.stringify = () => '{"text":"forged"}'; | |
| 201 | 新增: Object.prototype.toJSON = () => ({ text: "forged" }); | |
| 202 | 新增: }); | |
| 203 | 新增: await click(page, ["captured native success"]); | |
| 204 | 新增: | |
| 205 | 新增: await page.reload(); | |
| 206 | 新增: const beforeBlur = copies.length; | |
| 207 | 新增: await page.evaluate(() => { | |
| 208 | 新增: window.action = () => | |
| 209 | 新增: navigator.clipboard.write([ | |
| 210 | 新增: new ClipboardItem({ | |
| 211 | 新增: "text/plain": new Promise((resolve) => { | |
| 212 | 新增: window.finishBlob = resolve; | |
| 213 | 新增: }), | |
| 214 | 新增: }), | |
| 215 | 新增: ]); | |
| 216 | 新增: }); | |
| 217 | 新增: await observer.setContext("existing", randomUUID()); | |
| 218 | 新增: await page.click("#copy"); | |
| 219 | 新增: await page.waitForFunction(() => typeof window.finishBlob === "function"); | |
| 220 | 新增: // Dispatching blur cancels authorization just as the native focus event does. | |
| 221 | 新增: // The workbench smoke separately exercises host focus and tab cancellation. | |
| 222 | 新增: await page.evaluate(() => { | |
| 223 | 新增: window.dispatchEvent(new Event("blur")); | |
| 224 | 新增: finishBlob(new Blob(["late clipboard"], { type: "text/plain" })); | |
| 225 | 新增: }); | |
| 226 | 新增: await page.waitForFunction(() => window.finished); | |
| 227 | 新增: await page.waitForTimeout(50); | |
| 228 | 新增: assert.equal(copies.length, beforeBlur); | |
| 229 | 新增: | |
| 230 | 新增: await page.reload(); | |
| 231 | 新增: await page.evaluate(() => { | |
| 232 | 新增: window.action = () => | |
| 233 | 新增: navigator.clipboard.write([ | |
| 234 | 新增: new ClipboardItem({ | |
| 235 | 新增: "text/plain": new Promise((resolve) => { | |
| 236 | 新增: window.finishBlob = resolve; | |
| 237 | 新增: }), | |
| 238 | 新增: }), | |
| 239 | 新增: ]); | |
| 240 | 新增: }); | |
| 241 | 新增: const contextA = randomUUID(), | |
| 242 | 新增: contextB = randomUUID(); | |
| 243 | 新增: await observer.setContext("existing", contextA); | |
| 244 | 新增: const beforeContextChange = copies.length; | |
| 245 | 新增: await page.click("#copy"); | |
| 246 | 新增: await page.waitForFunction(() => typeof window.finishBlob === "function"); | |
| 247 | 新增: await observer.setContext("existing", contextB); | |
| 248 | 新增: await page.evaluate(() => | |
| 249 | 新增: finishBlob(new Blob(["copy began in A"], { type: "text/plain" })), | |
| 250 | 新增: ); | |
| 251 | 新增: await page.waitForFunction(() => window.finished); | |
| 252 | 新增: await page.waitForTimeout(50); | |
| 253 | 新增: assert.deepEqual(copies.slice(beforeContextChange), [ | |
| 254 | 新增: { id: "existing", text: "copy began in A", context: contextA }, | |
| 255 | 新增: ]); | |
| 256 | 新增: | |
| 257 | 新增: const modified = await context.newPage(); | |
| 258 | 新增: await modified.goto(origin); | |
| 259 | 新增: await modified.evaluate(() => { | |
| 260 | 新增: Clipboard.prototype.writeText = () => Promise.resolve(); | |
| 261 | 新增: }); | |
| 262 | 新增: const result = await attach(modified, "modified"); | |
| 263 | 新增: assert.match(result.skipped[0]?.reason, /writeText/); | |
| 264 | 新增: await click(modified, []); | |
| 265 | 新增: await modified.reload(); | |
| 266 | 新增: await click(modified, ["中文🙂\nexact text"]); | |
| 267 | 新增: | |
| 268 | 新增: const poisoned = await context.newPage(); | |
| 269 | 新增: await poisoned.goto(origin); | |
| 270 | 新增: await poisoned.evaluate(() => { | |
| 271 | 新增: const originalDefine = Object.defineProperty; | |
| 272 | 新增: const originalWrite = Clipboard.prototype.writeText; | |
| 273 | 新增: Clipboard.prototype.writeText = () => Promise.resolve(); | |
| 274 | 新增: window.leakedReferenceTable = false; | |
| 275 | 新增: Object.defineProperty = (object, key, descriptor) => { | |
| 276 | 新增: if (object && Object.hasOwn(object, "apply")) { | |
| 277 | 新增: window.leakedReferenceTable = true; | |
| 278 | 新增: object.defineProperty = originalDefine; | |
| 279 | 新增: object.writeText = originalWrite; | |
| 280 | 新增: return object; | |
| 281 | 新增: } | |
| 282 | 新增: return originalDefine(object, key, descriptor); | |
| 283 | 新增: }; | |
| 284 | 新增: }); | |
| 285 | 新增: const poisonedResult = await attach(poisoned, "poisoned"); | |
| 286 | 新增: assert.match(poisonedResult.skipped[0]?.reason, /defineProperty/); | |
| 287 | 新增: assert.equal( | |
| 288 | 新增: await poisoned.evaluate(() => window.leakedReferenceTable), | |
| 289 | 新增: false, | |
| 290 | 新增: ); | |
| 291 | 新增: await click(poisoned, []); | |
| 292 | 新增: await poisoned.close(); | |
| 293 | 新增: | |
| 294 | 新增: await modified.evaluate(() => { | |
| 295 | 新增: const frame = document.createElement("iframe"); | |
| 296 | 新增: frame.src = "/frame"; | |
| 297 | 新增: document.body.append(frame); | |
| 298 | 新增: }); | |
| 299 | 新增: const frameCount = copies.length; | |
| 300 | 新增: const frameContext = randomUUID(); | |
| 301 | 新增: await modified.frameLocator("iframe").locator("#copy").waitFor(); | |
| 302 | 新增: await observer.setContext("modified", frameContext); | |
| 303 | 新增: await modified.frameLocator("iframe").locator("#copy").click(); | |
| 304 | 新增: await modified.waitForTimeout(100); | |
| 305 | 新增: assert.deepEqual(copies.slice(frameCount), [ | |
| 306 | 新增: { id: "modified", text: "中文🙂\nexact text", context: frameContext }, | |
| 307 | 新增: ]); | |
| 308 | 新增: | |
| 309 | 新增: await modified.evaluate(() => { | |
| 310 | 新增: window.action = () => navigator.clipboard.writeText("x".repeat(65537)); | |
| 311 | 新增: }); | |
| 312 | 新增: await click(modified, []); | |
| 313 | 新增: console.log( | |
| 314 | 新增: "PASS: existing and new documents, exact writeText/write/execCommand content, rejected and late writes, synthetic events, captured native functions, modified existing APIs, same-process frames and size bound", | |
| 315 | 新增: ); | |
| 316 | 新增:} finally { | |
| 317 | 新增: await browser.close(); | |
| 318 | 新增: await new Promise((resolve) => site.close(resolve)); | |
| 319 | 新增:} | |
| @@ -4,7 +4,7 @@ import assert from "node:assert/strict"; | ||
| 4 | 4 | import { spawn } from "node:child_process"; |
| 5 | 5 | import { randomBytes } from "node:crypto"; |
| 6 | 6 | import { once } from "node:events"; |
| 7 | 删除:import { mkdtemp, readFile, writeFile, copyFile, rm } from "node:fs/promises"; | |
| 7 | 新增:import { mkdtemp, readFile, writeFile, copyFile, cp, rm } from "node:fs/promises"; | |
| 8 | 8 | import http from "node:http"; |
| 9 | 9 | import { tmpdir } from "node:os"; |
| 10 | 10 | import { join } from "node:path"; |
| @@ -95,10 +95,12 @@ try { | ||
| 95 | 95 | assert.ok(source.includes(listen), "Update the isolated control-listener adapter"); |
| 96 | 96 | await writeFile(join(directory, "agent.mjs"), source |
| 97 | 97 | .replaceAll("/home/cage-browser", directory) |
| 98 | 新增: .replaceAll("/usr/local/lib/cage-split", join(directory, "split-extension")) | |
| 98 | 99 | .replace("/etc/claude-cage/browser-control.json", join(directory, "control.json")) |
| 99 | 100 | .replace(listen, 'server.listen(0, "127.0.0.1", () => console.log("CONTROL_PORT=" + server.address().port));')); |
| 100 | 删除: await copyFile(new URL("../internal/cage/browser-audit.mjs", import.meta.url), join(directory, "browser-audit.mjs")); | |
| 101 | 删除: await copyFile(new URL("../internal/cage/browser-downloads.mjs", import.meta.url), join(directory, "browser-downloads.mjs")); | |
| 101 | 新增: for (const name of ["browser-audit", "browser-downloads", "browser-uploads", "browser-login", "browser-vault", "browser-clipboard", "native-input"]) | |
| 102 | 新增: await copyFile(new URL(`../internal/cage/${name}.mjs`, import.meta.url), join(directory, `${name}.mjs`)); | |
| 103 | 新增: await cp(new URL("../internal/cage/split-extension", import.meta.url), join(directory, "split-extension"), { recursive: true }); | |
| 102 | 104 | await writeFile(join(directory, "control.json"), JSON.stringify({ token, workspace: directory })); |
| 103 | 105 | await writeFile(join(directory, "homepage.json"), JSON.stringify({ url: origin + "/first" })); |
| 104 | 106 | await start(); |
| @@ -0,0 +1,295 @@ | ||
| 1 | 新增:// Headless adapter for the production controller. Set CAGE_TEST_BROWSER_PATH | |
| 2 | 新增:// to a Chromium executable that supports unpacked extensions. All browser data | |
| 3 | 新增:// and the authenticated, private-pipe test controller live in a temporary folder. | |
| 4 | 新增:import assert from "node:assert/strict"; | |
| 5 | 新增:import { spawn } from "node:child_process"; | |
| 6 | 新增:import { randomBytes } from "node:crypto"; | |
| 7 | 新增:import { once } from "node:events"; | |
| 8 | 新增:import { cp, mkdtemp, readdir, readFile, realpath, rm, writeFile } from "node:fs/promises"; | |
| 9 | 新增:import http from "node:http"; | |
| 10 | 新增:import { tmpdir } from "node:os"; | |
| 11 | 新增:import { join, resolve } from "node:path"; | |
| 12 | 新增:import { setTimeout as delay } from "node:timers/promises"; | |
| 13 | 新增: | |
| 14 | 新增:assert.ok(process.env.CAGE_TEST_BROWSER_PATH, "Set CAGE_TEST_BROWSER_PATH to a local Chromium executable"); | |
| 15 | 新增:const executable = resolve(process.env.CAGE_TEST_BROWSER_PATH); | |
| 16 | 新增:const directory = await realpath(await mkdtemp(join(tmpdir(), "cage-browser-metadata-"))); | |
| 17 | 新增:const token = randomBytes(32).toString("hex"); | |
| 18 | 新增:const iconRequests = []; | |
| 19 | 新增:const icons = http.createServer((req, res) => { | |
| 20 | 新增: iconRequests.push(req.url); | |
| 21 | 新增: if (req.url === "/missing.svg") { res.writeHead(404); res.end(); return; } | |
| 22 | 新增: res.setHeader("Content-Type", "image/svg+xml"); | |
| 23 | 新增: const color = req.url === "/blue.svg" ? "blue" : "red"; | |
| 24 | 新增: res.end(`<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><path fill="${color}" d="M0 0h32v32H0z"/></svg>`); | |
| 25 | 新增:}); | |
| 26 | 新增:await new Promise(resolve => icons.listen(0, "127.0.0.1", resolve)); | |
| 27 | 新增:const iconOrigin = `http://127.0.0.1:${icons.address().port}`; | |
| 28 | 新增:const site = http.createServer((req, res) => { | |
| 29 | 新增: if (req.url === "/favicon.ico") { res.writeHead(404); res.end(); return; } | |
| 30 | 新增: res.setHeader("Content-Type", "text/html"); | |
| 31 | 新增: res.setHeader("Content-Security-Policy", req.url.startsWith("/blocked") | |
| 32 | 新增: ? "default-src 'none'; img-src 'none'; connect-src *" | |
| 33 | 新增: : "default-src 'none'; img-src *; connect-src 'none'; script-src 'unsafe-inline'; frame-src http://127.0.0.1:*"); | |
| 34 | 新增: const icon = req.url === "/missing" ? "missing" : req.url === "/blue" ? "blue" : "red"; | |
| 35 | 新增: const buttons = req.url === "/copy" ? `<button id="text">Copy text</button><button id="rich">Copy item</button><button id="legacy">Legacy copy</button><button id="plain">Ordinary click</button><textarea id="selection">selected clipboard fixture</textarea><button id="selected">Copy selection</button> | |
| 36 | 新增: <script> | |
| 37 | 新增: const text = 'production clipboard fixture'; | |
| 38 | 新增: document.getElementById('text').onclick = () => navigator.clipboard.writeText(text); | |
| 39 | 新增: document.getElementById('rich').onclick = () => navigator.clipboard.write([new ClipboardItem({'text/plain': new Blob(['clipboard item fixture'], {type:'text/plain'})})]); | |
| 40 | 新增: let customCopy = false; | |
| 41 | 新增: document.addEventListener('copy', event => { | |
| 42 | 新增: if (customCopy) { event.clipboardData.setData('text/plain', 'legacy clipboard fixture'); event.preventDefault(); } | |
| 43 | 新增: }); | |
| 44 | 新增: document.getElementById('legacy').onclick = () => { | |
| 45 | 新增: customCopy = true; | |
| 46 | 新增: try { document.execCommand('copy'); } finally { customCopy = false; } | |
| 47 | 新增: }; | |
| 48 | 新增: document.getElementById('selected').onclick = () => { | |
| 49 | 新增: document.getElementById('selection').select(); | |
| 50 | 新增: document.execCommand('copy'); | |
| 51 | 新增: }; | |
| 52 | 新增: </script>` : ""; | |
| 53 | 新增: 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}`); | |
| 55 | 新增:}); | |
| 56 | 新增:await new Promise(resolve => site.listen(0, "127.0.0.1", resolve)); | |
| 57 | 新增:const origin = `http://localhost:${site.address().port}`; | |
| 58 | 新增:let agent, control, stderr = "", snapshot, streamTask, streamError; | |
| 59 | 新增:const snapshots = [], clipboard = []; | |
| 60 | 新增:const streamController = new AbortController(); | |
| 61 | 新增: | |
| 62 | 新增:async function waitFor(read, label) { | |
| 63 | 新增: const deadline = Date.now() + 15000; | |
| 64 | 新增: while (Date.now() < deadline) { | |
| 65 | 新增: if (streamError) throw streamError; | |
| 66 | 新增: if (agent && agent.exitCode !== null) throw new Error(`Controller exited during ${label}: ${stderr}`); | |
| 67 | 新增: const result = await read(); | |
| 68 | 新增: if (result) return result; | |
| 69 | 新增: await delay(50); | |
| 70 | 新增: } | |
| 71 | 新增: throw new Error(`Timed out waiting for ${label}. Last snapshot: ${JSON.stringify(snapshot)}. Browser stderr: ${stderr}`); | |
| 72 | 新增:} | |
| 73 | 新增:async function api(path, body) { | |
| 74 | 新增: const response = await fetch(control + path, { | |
| 75 | 新增: method: body === undefined ? "GET" : "POST", | |
| 76 | 新增: headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" }, | |
| 77 | 新增: ...(body === undefined ? {} : { body: JSON.stringify(body) }), | |
| 78 | 新增: }); | |
| 79 | 新增: const result = await response.json(); | |
| 80 | 新增: assert.equal(response.status, 200, JSON.stringify(result)); | |
| 81 | 新增: return result; | |
| 82 | 新增:} | |
| 83 | 新增:async function evaluate(id, expression) { | |
| 84 | 新增: const result = await api("/__metadata-test/cdp", { | |
| 85 | 新增: id, method: "Runtime.evaluate", params: { expression, awaitPromise: true, returnByValue: true }, | |
| 86 | 新增: }); | |
| 87 | 新增: assert.equal(result.exceptionDetails, undefined, JSON.stringify(result.exceptionDetails)); | |
| 88 | 新增: return result.result.value; | |
| 89 | 新增:} | |
| 90 | 新增:async function click(id, selector) { | |
| 91 | 新增: const context = randomBytes(16).toString("hex"); | |
| 92 | 新增: await api("/copy-context", { id, context }); | |
| 93 | 新增: const point = await evaluate(id, `(() => { | |
| 94 | 新增: const rect = document.querySelector(${JSON.stringify(selector)}).getBoundingClientRect(); | |
| 95 | 新增: return { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 }; | |
| 96 | 新增: })()`); | |
| 97 | 新增: for (const type of ["mousePressed", "mouseReleased"]) | |
| 98 | 新增: await api("/__metadata-test/cdp", { id, method: "Input.dispatchMouseEvent", params: { type, ...point, button: "left", clickCount: 1 } }); | |
| 99 | 新增: return context; | |
| 100 | 新增:} | |
| 101 | 新增:async function listenEvents() { | |
| 102 | 新增: const response = await fetch(control + "/events", { | |
| 103 | 新增: headers: { Authorization: `Bearer ${token}` }, signal: streamController.signal, | |
| 104 | 新增: }); | |
| 105 | 新增: assert.equal(response.status, 200); | |
| 106 | 新增: streamTask = (async () => { | |
| 107 | 新增: const decoder = new TextDecoder(); | |
| 108 | 新增: let buffer = ""; | |
| 109 | 新增: for await (const chunk of response.body) { | |
| 110 | 新增: buffer += decoder.decode(chunk, { stream: true }); | |
| 111 | 新增: let end; | |
| 112 | 新增: while ((end = buffer.indexOf("\n\n")) !== -1) { | |
| 113 | 新增: const frame = buffer.slice(0, end); | |
| 114 | 新增: buffer = buffer.slice(end + 2); | |
| 115 | 新增: const lines = frame.split("\n"); | |
| 116 | 新增: const type = lines.find(line => line.startsWith("event:"))?.slice(6).trim() || "message"; | |
| 117 | 新增: const data = lines.filter(line => line.startsWith("data:")).map(line => line.slice(5).trimStart()).join("\n"); | |
| 118 | 新增: if (!data) continue; | |
| 119 | 新增: if (type === "clipboard") clipboard.push(JSON.parse(data)); | |
| 120 | 新增: else if (type === "message") { snapshot = JSON.parse(data); snapshots.push(snapshot); } | |
| 121 | 新增: } | |
| 122 | 新增: } | |
| 123 | 新增: })().catch(error => { if (!streamController.signal.aborted) streamError = error; }); | |
| 124 | 新增:} | |
| 125 | 新增:function tab(id) { return snapshot?.tabs.find(item => item.id === id); } | |
| 126 | 新增:function checkPNG(icon) { | |
| 127 | 新增: assert.match(icon, /^data:image\/png;base64,[A-Za-z0-9+/=]+$/); | |
| 128 | 新增: assert.ok(icon.length <= 8192); | |
| 129 | 新增: const bytes = Buffer.from(icon.split(",")[1], "base64"); | |
| 130 | 新增: assert.equal(bytes.readUInt32BE(16), 32); | |
| 131 | 新增: assert.equal(bytes.readUInt32BE(20), 32); | |
| 132 | 新增:} | |
| 133 | 新增: | |
| 134 | 新增:try { | |
| 135 | 新增: const sourceDirectory = new URL("../internal/cage/", import.meta.url); | |
| 136 | 新增: for (const name of await readdir(sourceDirectory)) | |
| 137 | 新增: if ((name.startsWith("browser-") && name.endsWith(".mjs")) || name === "native-input.mjs") | |
| 138 | 新增: await cp(new URL(name, sourceDirectory), join(directory, name)); | |
| 139 | 新增: await cp(new URL("split-extension", sourceDirectory), join(directory, "extension"), { recursive: true }); | |
| 140 | 新增: const source = await readFile(new URL("browser-agent.mjs", sourceDirectory), "utf8"); | |
| 141 | 新增: const listen = 'server.listen(18500, "127.0.0.1");'; | |
| 142 | 新增: const input = 'const input = JSON.parse(text || "{}");'; | |
| 143 | 新增: assert.ok(source.includes(listen) && source.includes(input), "Update the isolated controller adapter"); | |
| 144 | 新增: // The extra authenticated route only drives the real page through the existing | |
| 145 | 新增: // private CDP pipe. Production state, extension bindings and SSE are untouched. | |
| 146 | 新增: const testRoute = `${input} | |
| 147 | 新增: if (req.url === "/__metadata-test/cdp") { | |
| 148 | 新增: const sid = input.id ? await session(input.id) : input.sessionId; | |
| 149 | 新增: res.end(JSON.stringify(await cdp(input.method, input.params || {}, sid))); | |
| 150 | 新增: return; | |
| 151 | 新增: }`; | |
| 152 | 新增: const isolated = source | |
| 153 | 新增: .replaceAll("/home/cage-browser", directory) | |
| 154 | 新增: .replace("/etc/claude-cage/browser-control.json", join(directory, "control.json")) | |
| 155 | 新增: .replace("/usr/local/lib/cage-split", join(directory, "extension")) | |
| 156 | 新增: .replace('spawn("/usr/bin/chromium", flags', `spawn(${JSON.stringify(executable)}, flags`) | |
| 157 | 新增: .replace('"--kiosk",', '"--headless=new",') | |
| 158 | 新增: .replace(listen, 'server.listen(0, "127.0.0.1", () => console.log("CONTROL_PORT=" + server.address().port));') | |
| 159 | 新增: .replace(input, testRoute); | |
| 160 | 新增: await writeFile(join(directory, "browser-agent.mjs"), isolated); | |
| 161 | 新增: await writeFile(join(directory, "control.json"), JSON.stringify({ token, workspace: directory })); | |
| 162 | 新增: await writeFile(join(directory, "homepage.json"), JSON.stringify({ url: origin + "/red" })); | |
| 163 | 新增: agent = spawn(process.execPath, [join(directory, "browser-agent.mjs")], { stdio: ["ignore", "pipe", "pipe"] }); | |
| 164 | 新增: let output = ""; | |
| 165 | 新增: agent.stdout.on("data", chunk => { | |
| 166 | 新增: output += chunk; | |
| 167 | 新增: const match = output.match(/CONTROL_PORT=(\d+)/); | |
| 168 | 新增: if (match) control = `http://127.0.0.1:${match[1]}`; | |
| 169 | 新增: }); | |
| 170 | 新增: agent.stderr.on("data", chunk => { stderr = (stderr + chunk).slice(-4000); }); | |
| 171 | 新增: await waitFor(() => control, "control listener"); | |
| 172 | 新增: await waitFor(async () => (await fetch(control + "/health", { headers: { Authorization: `Bearer ${token}` } })).ok, "browser readiness"); | |
| 173 | 新增: await listenEvents(); | |
| 174 | 新增: const initial = await waitFor(() => snapshot?.tabs.find(item => item.url === origin + "/red" && item.favicon), "initial favicon via production SSE"); | |
| 175 | 新增: const id = initial.id, red = initial.favicon; | |
| 176 | 新增: checkPNG(red); | |
| 177 | 新增: assert.equal(await evaluate(id, "navigator.webdriver"), false); | |
| 178 | 新增: assert.equal((await api("/tabs")).tabs.find(item => item.id === id).favicon, red); | |
| 179 | 新增: | |
| 180 | 新增: await api("/navigate", { id, url: origin + "/blue" }); | |
| 181 | 新增: const blue = await waitFor(() => tab(id)?.url === origin + "/blue" && tab(id)?.favicon && tab(id).favicon !== red && tab(id).favicon, "full navigation favicon via SSE"); | |
| 182 | 新增: checkPNG(blue); | |
| 183 | 新增: await evaluate(id, "history.pushState({}, '', '/spa')"); | |
| 184 | 新增: await waitFor(() => tab(id)?.url === origin + "/spa" && tab(id)?.favicon === blue, "SPA route favicon via SSE"); | |
| 185 | 新增: await evaluate(id, `document.querySelector('link[rel="icon"]').href = ${JSON.stringify(iconOrigin + "/red.svg")}`); | |
| 186 | 新增: await waitFor(() => tab(id)?.favicon === red, "dynamic favicon via SSE"); | |
| 187 | 新增: | |
| 188 | 新增: const beforeBlocked = iconRequests.length; | |
| 189 | 新增: // Chromium may reuse a known same-site icon even after navigation. A new | |
| 190 | 新增: // origin separates that native cache behavior from the CSP network check. | |
| 191 | 新增: const uncachedOrigin = `http://127.0.0.1:${site.address().port}`; | |
| 192 | 新增: const blocked = await api("/new", { url: uncachedOrigin + "/blocked" }); | |
| 193 | 新增: await waitFor(() => tab(blocked.id)?.url === uncachedOrigin + "/blocked" && !tab(blocked.id)?.favicon, "CSP-blocked favicon fallback"); | |
| 194 | 新增: await waitFor(() => evaluate(blocked.id, "document.readyState === 'complete'"), "blocked page load"); | |
| 195 | 新增: await delay(300); | |
| 196 | 新增: assert.equal(iconRequests.length, beforeBlocked, "extension must not bypass img-src"); | |
| 197 | 新增: assert.equal(tab(blocked.id)?.favicon, ""); | |
| 198 | 新增: | |
| 199 | 新增: await api("/navigate", { id: blocked.id, url: uncachedOrigin + "/missing" }); | |
| 200 | 新增: await waitFor(() => iconRequests.includes("/missing.svg"), "failed favicon request"); | |
| 201 | 新增: await waitFor(() => tab(blocked.id)?.url === uncachedOrigin + "/missing" && !tab(blocked.id)?.favicon, "failed favicon fallback"); | |
| 202 | 新增: await api("/navigate", { id: blocked.id, url: uncachedOrigin + "/red" }); | |
| 203 | 新增: await waitFor(() => tab(blocked.id)?.url === uncachedOrigin + "/red" && tab(blocked.id)?.favicon === red, "favicon recovery after failed load"); | |
| 204 | 新增: | |
| 205 | 新增: const { targetInfos } = await api("/__metadata-test/cdp", { method: "Target.getTargets" }); | |
| 206 | 新增: assert.ok(targetInfos.some(item => item.url.startsWith("chrome-extension://") && item.url.endsWith("/control.html")), "real extension controller must exist"); | |
| 207 | 新增: assert.ok(snapshots.every(state => state.tabs.every(item => !item.url.startsWith("chrome-extension://"))), "hidden controller must never enter public snapshots"); | |
| 208 | 新增: assert.ok((await api("/tabs")).tabs.every(item => !item.url.startsWith("chrome-extension://"))); | |
| 209 | 新增: const copyTab = await api("/new", { url: origin + "/copy" }); | |
| 210 | 新增: await waitFor(() => evaluate(copyTab.id, "document.readyState === 'complete'"), "clipboard fixture load"); | |
| 211 | 新增: for (const [selector, expected] of [["#text", "production clipboard fixture"], ["#text", "production clipboard fixture"], | |
| 212 | 新增: ["#rich", "clipboard item fixture"], ["#legacy", "legacy clipboard fixture"], ["#selected", "selected clipboard fixture"]]) { | |
| 213 | 新增: const before = clipboard.length; | |
| 214 | 新增: const context = await click(copyTab.id, selector); | |
| 215 | 新增: await waitFor(() => clipboard.length > before, `${selector} copy through production SSE`); | |
| 216 | 新增: assert.deepEqual(clipboard.slice(before), [{ id: copyTab.id, text: expected, context }]); | |
| 217 | 新增: } | |
| 218 | 新增: const copied = clipboard.length; | |
| 219 | 新增: await click(copyTab.id, "#plain"); | |
| 220 | 新增: await delay(200); | |
| 221 | 新增: assert.equal(clipboard.length, copied, "ordinary clicks must not export clipboard text"); | |
| 222 | 新增: await api("/activate", { id }); | |
| 223 | 新增: await evaluate(copyTab.id, "navigator.clipboard.writeText('background copy').catch(() => {})"); | |
| 224 | 新增: await delay(200); | |
| 225 | 新增: assert.equal(clipboard.length, copied, "background tabs must not export clipboard text"); | |
| 226 | 新增: const frameTab = await api("/new", { url: origin + "/frame" }); | |
| 227 | 新增: const childURL = `http://127.0.0.1:${site.address().port}/copy`; | |
| 228 | 新增: const childTarget = await waitFor(async () => { | |
| 229 | 新增: const { targetInfos } = await api("/__metadata-test/cdp", { method: "Target.getTargets" }); | |
| 230 | 新增: return targetInfos.find(target => target.type === "iframe" && target.url === childURL); | |
| 231 | 新增: }, "real cross-site OOPIF target"); | |
| 232 | 新增: const { sessionId } = await api("/__metadata-test/cdp", { | |
| 233 | 新增: method: "Target.attachToTarget", params: { targetId: childTarget.targetId, flatten: true }, | |
| 234 | 新增: }); | |
| 235 | 新增: try { | |
| 236 | 新增: await waitFor(async () => { | |
| 237 | 新增: const result = await api("/__metadata-test/cdp", { sessionId, method: "Runtime.evaluate", params: { | |
| 238 | 新增: expression: "document.readyState === 'complete'", returnByValue: true, | |
| 239 | 新增: } }); | |
| 240 | 新增: return result.result.value; | |
| 241 | 新增: }, "OOPIF fixture load"); | |
| 242 | 新增: const { result } = await api("/__metadata-test/cdp", { sessionId, method: "Runtime.evaluate", params: { | |
| 243 | 新增: expression: `(() => { | |
| 244 | 新增: const rect = document.getElementById('text').getBoundingClientRect(); | |
| 245 | 新增: return { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 }; | |
| 246 | 新增: })()`, returnByValue: true, | |
| 247 | 新增: } }); | |
| 248 | 新增: const button = result.value; | |
| 249 | 新增: const frame = await evaluate(frameTab.id, `(() => { | |
| 250 | 新增: const element = document.getElementById('child'), rect = element.getBoundingClientRect(); | |
| 251 | 新增: return { x: rect.x + element.clientLeft, y: rect.y + element.clientTop }; | |
| 252 | 新增: })()`); | |
| 253 | 新增: const before = clipboard.length; | |
| 254 | 新增: const context = randomBytes(16).toString("hex"); | |
| 255 | 新增: await api("/copy-context", { id: frameTab.id, context }); | |
| 256 | 新增: for (const type of ["mousePressed", "mouseReleased"]) | |
| 257 | 新增: await api("/__metadata-test/cdp", { id: frameTab.id, method: "Input.dispatchMouseEvent", params: { | |
| 258 | 新增: type, x: frame.x + button.x, y: frame.y + button.y, button: "left", clickCount: 1, | |
| 259 | 新增: } }); | |
| 260 | 新增: await waitFor(() => clipboard.length > before, "OOPIF copy through production SSE"); | |
| 261 | 新增: assert.deepEqual(clipboard.slice(before), [{ id: frameTab.id, text: "production clipboard fixture", context }]); | |
| 262 | 新增: assert.ok(!snapshot.tabs.some(item => item.id === childTarget.targetId), "OOPIF must not become a workbench tab"); | |
| 263 | 新增: } finally { | |
| 264 | 新增: await api("/__metadata-test/cdp", { method: "Target.detachFromTarget", params: { sessionId } }); | |
| 265 | 新增: } | |
| 266 | 新增: assert.ok(!("clipboard" in await api("/tabs")), "clipboard events must not enter replayable snapshots"); | |
| 267 | 新增: const reconnectController = new AbortController(); | |
| 268 | 新增: const reconnect = await fetch(control + "/events", { | |
| 269 | 新增: headers: { Authorization: `Bearer ${token}` }, signal: reconnectController.signal, | |
| 270 | 新增: }); | |
| 271 | 新增: const reader = reconnect.body.getReader(); | |
| 272 | 新增: try { | |
| 273 | 新增: const { value } = await reader.read(); | |
| 274 | 新增: const firstFrame = new TextDecoder().decode(value); | |
| 275 | 新增: assert.match(firstFrame, /^data: /, "reconnect should start with the current browser snapshot"); | |
| 276 | 新增: assert.ok(!firstFrame.includes("event: clipboard"), "reconnecting must not replay an earlier copy"); | |
| 277 | 新增: assert.ok(!firstFrame.includes("legacy clipboard fixture")); | |
| 278 | 新增: } finally { | |
| 279 | 新增: reconnectController.abort(); | |
| 280 | 新增: await reader.cancel().catch(() => {}); | |
| 281 | 新增: } | |
| 282 | 新增: console.log("PASS: production controller headless adapter, initial/REST/SSE favicons, navigation, SPA, dynamic icons, native CSP, failed-load recovery, hidden extension target, copy APIs, selected-text copy and real cross-site OOPIF clipboard SSE"); | |
| 283 | 新增:} finally { | |
| 284 | 新增: streamController.abort(); | |
| 285 | 新增: await streamTask; | |
| 286 | 新增: if (agent && agent.exitCode === null) { | |
| 287 | 新增: const exited = once(agent, "exit"); | |
| 288 | 新增: agent.kill("SIGTERM"); | |
| 289 | 新增: const force = setTimeout(() => agent.kill("SIGKILL"), 5000); | |
| 290 | 新增: await exited; | |
| 291 | 新增: clearTimeout(force); | |
| 292 | 新增: } | |
| 293 | 新增: await Promise.all([new Promise(resolve => site.close(resolve)), new Promise(resolve => icons.close(resolve))]); | |
| 294 | 新增: await rm(directory, { recursive: true, force: true }); | |
| 295 | 新增:} | |
| @@ -0,0 +1,107 @@ | ||
| 1 | 新增:// Real Chromium, isolated profile, intercepted HTTPS fixtures; no personal sites. | |
| 2 | 新增:import assert from "node:assert/strict"; | |
| 3 | 新增:import { createRequire } from "node:module"; | |
| 4 | 新增:import { BrowserVault } from "../internal/cage/browser-vault.mjs"; | |
| 5 | 新增:const require = createRequire(import.meta.url); | |
| 6 | 新增:const { chromium } = require(process.env.CAGE_PLAYWRIGHT_MODULE || "playwright"); | |
| 7 | 新增:const browser = await chromium.launch({ headless: true }); | |
| 8 | 新增:const context = await browser.newContext(); | |
| 9 | 新增:const page = await context.newPage(); | |
| 10 | 新增:const html = `<form onsubmit="event.preventDefault()"><label>Email<input name="email" type="email" autocomplete="username"></label><label>Password<input name="pass" type="password" autocomplete="current-password"></label><button>Sign in</button></form>`; | |
| 11 | 新增:await context.route("**/*", route => { | |
| 12 | 新增: const pathname = new URL(route.request().url()).pathname; | |
| 13 | 新增: const body = pathname === "/username-step" ? `<form action="/password-step"><label>Email<input type="email" name="email" autocomplete="username"></label><button>Next</button></form>` | |
| 14 | 新增: : pathname === "/password-step" ? `<form onsubmit="event.preventDefault()"><label>Password<input type="password" autocomplete="current-password"></label><button>Sign in</button></form>` | |
| 15 | 新增: : pathname === "/framed" ? `<iframe src="https://frame.example.test/login"></iframe>` : html; | |
| 16 | 新增: return route.fulfill({ contentType: "text/html", body }); | |
| 17 | 新增:}); | |
| 18 | 新增:await page.goto("https://mail.example.test/login"); | |
| 19 | 新增:const session = await context.newCDPSession(page); | |
| 20 | 新增:const vault = new BrowserVault({ cdp: (method, args) => session.send(method, args), active: () => "tab", tab: () => ({}) }); | |
| 21 | 新增:for (const method of ["Runtime.executionContextCreated", "Runtime.executionContextDestroyed", "Runtime.executionContextsCleared", "Runtime.bindingCalled", "Page.frameNavigated"]) | |
| 22 | 新增: session.on(method, params => vault.event({ method, params, sessionId: "session" })); | |
| 23 | 新增:await session.send("Page.enable"); | |
| 24 | 新增:await vault.attach("tab", "session"); | |
| 25 | 新增:const lease = "a".repeat(64); | |
| 26 | 新增:const request = value => vault.request({ lease, tab: "tab", ...value }); | |
| 27 | 新增:const status = () => request({ action: "status" }); | |
| 28 | 新增:const waitCandidate = async () => { | |
| 29 | 新增: await assert.doesNotReject(async () => { | |
| 30 | 新增: for (let i = 0; i < 30 && !vault.pending.size; i++) await new Promise(resolve => setTimeout(resolve, 20)); | |
| 31 | 新增: assert.ok(vault.pending.size, "trusted submission produced no candidate"); | |
| 32 | 新增: }); | |
| 33 | 新增: return (await status()).candidates[0]; | |
| 34 | 新增:}; | |
| 35 | 新增:try { | |
| 36 | 新增: let state = await status(); | |
| 37 | 新增: assert.equal(state.origin, "https://mail.example.test"); | |
| 38 | 新增: assert.ok(state.document); | |
| 39 | 新增: assert.equal(await page.evaluate(() => typeof globalThis.cageVaultSubmitted), "undefined", "page gained vault binding"); | |
| 40 | 新增: await page.getByLabel("Email").fill("[email protected]"); | |
| 41 | 新增: await page.getByLabel("Password").fill("first-secret"); | |
| 42 | 新增: await page.evaluate(() => document.querySelector("form").dispatchEvent(new Event("submit", { bubbles: true }))); | |
| 43 | 新增: assert.equal(vault.pending.size, 0, "synthetic submission was captured"); | |
| 44 | 新增: await page.getByRole("button", { name: "Sign in" }).click(); | |
| 45 | 新增: let candidate = await waitCandidate(); | |
| 46 | 新增: assert.equal(candidate.password, "first-secret"); | |
| 47 | 新增: assert.equal(candidate.username, "[email protected]"); | |
| 48 | 新增: await request({ action: "dismiss", candidate: candidate.id }); | |
| 49 | 新增: await page.getByLabel("Email").fill(""); | |
| 50 | 新增: await page.getByLabel("Password").fill(""); | |
| 51 | 新增: await request({ action: "fill", document: state.document, origin: state.origin, username: "[email protected]", password: "second-secret" }); | |
| 52 | 新增: assert.equal(await page.getByLabel("Email").inputValue(), "[email protected]"); | |
| 53 | 新增: assert.equal(await page.getByLabel("Password").inputValue(), "second-secret"); | |
| 54 | 新增: await assert.rejects(request({ action: "fill", document: state.document, origin: "https://evil.test", username: "bad", password: "wrong" })); | |
| 55 | 新增: assert.equal(await page.getByLabel("Password").inputValue(), "second-secret"); | |
| 56 | 新增: await page.goto("https://mail.example.test/other"); | |
| 57 | 新增: await assert.rejects(request({ action: "fill", document: state.document, origin: state.origin, username: "bad", password: "wrong" })); | |
| 58 | 新增: state = await status(); | |
| 59 | 新增: await page.getByLabel("Email").fill("[email protected]"); | |
| 60 | 新增: await page.getByLabel("Password").fill("updated-secret"); | |
| 61 | 新增: await page.getByRole("button", { name: "Sign in" }).click(); | |
| 62 | 新增: candidate = await waitCandidate(); | |
| 63 | 新增: assert.equal(candidate.password, "updated-secret"); | |
| 64 | 新增: await request({ action: "lock" }); | |
| 65 | 新增: assert.equal(vault.pending.size, 0); | |
| 66 | 新增: await assert.rejects(request({ action: "candidate", candidate: candidate.id })); | |
| 67 | 新增: await page.getByRole("button", { name: "Sign in" }).click(); | |
| 68 | 新增: assert.equal(vault.pending.size, 0); | |
| 69 | 新增: const freshLease = "b".repeat(64); | |
| 70 | 新增: await vault.request({ action: "status", lease: freshLease, tab: "tab" }); | |
| 71 | 新增: assert.equal(vault.pending.size, 0); | |
| 72 | 新增: await vault.request({ action: "lock", lease }); | |
| 73 | 新增: assert.equal(vault.lease, freshLease, "late lock cleared new epoch"); | |
| 74 | 新增: await page.goto("http://plain.example.test/login"); | |
| 75 | 新增: state = await vault.request({ action: "status", lease: freshLease, tab: "tab" }); | |
| 76 | 新增: assert.equal(state.origin, ""); | |
| 77 | 新增: await page.getByLabel("Password").fill("must-not-capture"); | |
| 78 | 新增: await page.getByRole("button", { name: "Sign in" }).click(); | |
| 79 | 新增: assert.equal(vault.pending.size, 0); | |
| 80 | 新增: await page.goto("https://mail.example.test/login"); | |
| 81 | 新增: await vault.request({ action: "status", lease: freshLease, tab: "tab", blocked: ["https://mail.example.test"] }); | |
| 82 | 新增: await page.getByLabel("Password").fill("ignored-secret"); | |
| 83 | 新增: await page.getByRole("button", { name: "Sign in" }).click(); | |
| 84 | 新增: assert.equal(vault.pending.size, 0); | |
| 85 | 新增: await page.goto("https://mail.example.test/username-step"); | |
| 86 | 新增: await vault.request({ action: "status", lease: freshLease, tab: "tab", blocked: [] }); | |
| 87 | 新增: await page.getByLabel("Email").fill("[email protected]"); | |
| 88 | 新增: await page.getByRole("button", { name: "Next", exact: true }).click(); | |
| 89 | 新增: await page.waitForURL("**/password-step?*"); | |
| 90 | 新增: await vault.request({ action: "status", lease: freshLease, tab: "tab" }); | |
| 91 | 新增: await page.getByLabel("Password").fill("step-secret"); | |
| 92 | 新增: await page.getByRole("button", { name: "Sign in" }).click(); | |
| 93 | 新增: for (let i = 0; i < 30 && !vault.pending.size; i++) await new Promise(resolve => setTimeout(resolve, 20)); | |
| 94 | 新增: assert.equal([...vault.pending.values()][0]?.username, "[email protected]", "username lost across same-origin steps"); | |
| 95 | 新增: vault.deadline = 0; vault.prune(); | |
| 96 | 新增: assert.equal(vault.pending.size, 0, "expired lease retained password"); | |
| 97 | 新增: assert.equal(vault.usernames.size, 0); | |
| 98 | 新增: await page.goto("https://mail.example.test/framed"); | |
| 99 | 新增: await vault.request({ action: "status", lease: freshLease, tab: "tab" }); | |
| 100 | 新增: await page.frameLocator("iframe").getByLabel("Password").fill("frame-secret"); | |
| 101 | 新增: await page.frameLocator("iframe").getByRole("button", { name: "Sign in" }).click(); | |
| 102 | 新增: assert.equal(vault.pending.size, 0, "iframe credential was captured"); | |
| 103 | 新增: console.log("PASS: real Chromium capture, isolated binding, synthetic rejection, fill, exact origin, stale navigation, lock, lease, HTTP, blocked sites, multi-step login, lease expiry and iframe exclusion"); | |
| 104 | 新增:} finally { | |
| 105 | 新增: clearInterval(vault.timer); | |
| 106 | 新增: await browser.close(); | |
| 107 | 新增:} | |
| @@ -53,6 +53,7 @@ try { | ||
| 53 | 53 | & (Join-Path $PSScriptRoot 'install-nsis.ps1') -Destination $env:RUNNER_TEMP |
| 54 | 54 | $env:PATH = (Join-Path $env:RUNNER_TEMP 'nsis-3.13') + [IO.Path]::PathSeparator + $env:PATH |
| 55 | 55 | Invoke-BuildTool 'node' @('scripts/check-version.mjs') |
| 56 | 新增: Invoke-BuildTool 'node' @('--test', 'internal/cage/browser-clipboard.test.mjs') | |
| 56 | 57 | & (Join-Path $PSScriptRoot 'build-windows.ps1') -Release:$Release |
| 57 | 58 | Invoke-BuildTool 'dotnet' @('run', '--project', 'desktop/windows.tests/Cage.Windows.Tests.csproj') |
| 58 | 59 | Invoke-BuildTool 'go' @('test', './internal/workbench', './internal/appupdate', './internal/host', './internal/managedproxy', './internal/env', './internal/paths', './internal/mounts') |
| @@ -0,0 +1,145 @@ | ||
| 1 | 新增:import assert from "node:assert/strict"; | |
| 2 | 新增:import http from "node:http"; | |
| 3 | 新增:import { createHash } from "node:crypto"; | |
| 4 | 新增:import { mkdtemp, rm } from "node:fs/promises"; | |
| 5 | 新增:import { tmpdir } from "node:os"; | |
| 6 | 新增:import { join } from "node:path"; | |
| 7 | 新增:import { fileURLToPath } from "node:url"; | |
| 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 extension = fileURLToPath(new URL("../internal/cage/split-extension", import.meta.url)); | |
| 13 | 新增:const extensionId = createHash("sha256").update(extension).digest("hex").slice(0, 32) | |
| 14 | 新增: .replace(/./g, digit => String.fromCharCode(97 + parseInt(digit, 16))); | |
| 15 | 新增:const profile = await mkdtemp(join(tmpdir(), "cage-favicon-extension-")); | |
| 16 | 新增:const requests = []; | |
| 17 | 新增:const icons = http.createServer((req, res) => { | |
| 18 | 新增: requests.push(req.url); | |
| 19 | 新增: res.setHeader("Content-Type", "image/svg+xml"); | |
| 20 | 新增: const color = req.url.includes("blue") ? "blue" : "red"; | |
| 21 | 新增: res.end(`<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><path fill="${color}" d="M0 0h32v32H0z"/></svg>`); | |
| 22 | 新增:}); | |
| 23 | 新增:await new Promise(resolve => icons.listen(0, "127.0.0.1", resolve)); | |
| 24 | 新增:const iconOrigin = `http://127.0.0.1:${icons.address().port}`; | |
| 25 | 新增:const site = http.createServer((req, res) => { | |
| 26 | 新增: res.setHeader("Content-Type", "text/html"); | |
| 27 | 新增: res.setHeader("Content-Security-Policy", req.url.startsWith("/blocked") | |
| 28 | 新增: ? "default-src 'none'; img-src 'none'; connect-src *" | |
| 29 | 新增: : "default-src 'none'; img-src *; connect-src 'none'"); | |
| 30 | 新增: res.end(`<!doctype html><link rel="icon" href="${iconOrigin}/red.svg"><title>Favicon fixture</title>`); | |
| 31 | 新增:}); | |
| 32 | 新增:await new Promise(resolve => site.listen(0, "127.0.0.1", resolve)); | |
| 33 | 新增:const origin = `http://localhost:${site.address().port}`; | |
| 34 | 新增:const launch = () => chromium.launchPersistentContext(profile, { | |
| 35 | 新增: executablePath: process.env.CAGE_TEST_BROWSER_PATH, | |
| 36 | 新增: channel: "chromium", | |
| 37 | 新增: headless: true, | |
| 38 | 新增: args: [`--disable-extensions-except=${extension}`, `--load-extension=${extension}`, "--restore-last-session"], | |
| 39 | 新增:}); | |
| 40 | 新增:let context; | |
| 41 | 新增:async function waitFor(action, label) { | |
| 42 | 新增: const deadline = Date.now() + 10000; | |
| 43 | 新增: while (Date.now() < deadline) { | |
| 44 | 新增: const value = await action(); | |
| 45 | 新增: if (value) return value; | |
| 46 | 新增: await new Promise(resolve => setTimeout(resolve, 50)); | |
| 47 | 新增: } | |
| 48 | 新增: throw new Error(`Timed out waiting for ${label}`); | |
| 49 | 新增:} | |
| 50 | 新增:async function targetFor(page) { | |
| 51 | 新增: const session = await context.newCDPSession(page); | |
| 52 | 新增: const { targetInfo } = await session.send("Target.getTargetInfo"); | |
| 53 | 新增: await session.detach(); | |
| 54 | 新增: return targetInfo.targetId; | |
| 55 | 新增:} | |
| 56 | 新增:async function setupController() { | |
| 57 | 新增: const page = await context.newPage(); | |
| 58 | 新增: await page.goto(`chrome-extension://${extensionId}/control.html`); | |
| 59 | 新增: await page.evaluate(() => { | |
| 60 | 新增: globalThis.faviconEvents = []; | |
| 61 | 新增: globalThis.cageFaviconChanged = target => faviconEvents.push(target); | |
| 62 | 新增: }); | |
| 63 | 新增: return page; | |
| 64 | 新增:} | |
| 65 | 新增:async function read(page, target) { | |
| 66 | 新增: return page.evaluate(id => readCageFavicon(id), target); | |
| 67 | 新增:} | |
| 68 | 新增:try { | |
| 69 | 新增: context = await launch(); | |
| 70 | 新增: let controller = await setupController(); | |
| 71 | 新增: const blocked = await context.newPage(); | |
| 72 | 新增: await blocked.goto(origin + "/blocked"); | |
| 73 | 新增: const blockedTarget = await targetFor(blocked); | |
| 74 | 新增: assert.equal((await read(controller, blockedTarget)).favicon, "", "img-src denial must keep the fallback"); | |
| 75 | 新增: assert.deepEqual(requests, [], "controller must never load the blocked website icon"); | |
| 76 | 新增: | |
| 77 | 新增: const page = await context.newPage(); | |
| 78 | 新增: await page.goto(origin + "/allowed"); | |
| 79 | 新增: const target = await targetFor(page); | |
| 80 | 新增: const red = await waitFor(async () => (await read(controller, target))?.favicon, "native favicon despite connect-src denial"); | |
| 81 | 新增: assert.match(red, /^data:image\/png;base64,/); | |
| 82 | 新增: assert.ok(red.length <= 8192); | |
| 83 | 新增: const bytes = Buffer.from(red.split(",")[1], "base64"); | |
| 84 | 新增: assert.equal(bytes.readUInt32BE(16), 32); | |
| 85 | 新增: assert.equal(bytes.readUInt32BE(20), 32); | |
| 86 | 新增: const nativeRequestCount = requests.length; | |
| 87 | 新增: await read(controller, target); | |
| 88 | 新增: await read(controller, target); | |
| 89 | 新增: assert.equal(requests.length, nativeRequestCount, "cache reads must not request website resources"); | |
| 90 | 新增: await page.evaluate(() => history.pushState({}, "", "/next")); | |
| 91 | 新增: await waitFor(async () => (await read(controller, target))?.favicon === red, "favicon after SPA route change"); | |
| 92 | 新增: await controller.evaluate(() => { faviconEvents.length = 0; }); | |
| 93 | 新增: await page.evaluate(url => { document.querySelector('link[rel="icon"]').href = url; }, iconOrigin + "/blue.svg"); | |
| 94 | 新增: const blue = await waitFor(async () => { | |
| 95 | 新增: const result = await read(controller, target); | |
| 96 | 新增: return result?.favicon && result.favicon !== red && result.favicon; | |
| 97 | 新增: }, "dynamic favicon update"); | |
| 98 | 新增: await waitFor(() => controller.evaluate(id => faviconEvents.includes(id), target), "favicon invalidation binding"); | |
| 99 | 新增: assert.notEqual(blue, red); | |
| 100 | 新增: | |
| 101 | 新增: // Pause only decoding so real navigation and closure race the production reader. | |
| 102 | 新增: await controller.evaluate(id => { | |
| 103 | 新增: const decode = HTMLImageElement.prototype.decode; | |
| 104 | 新增: globalThis.originalFaviconDecode = decode; | |
| 105 | 新增: HTMLImageElement.prototype.decode = async function () { | |
| 106 | 新增: await decode.call(this); | |
| 107 | 新增: await new Promise(resolve => { globalThis.releaseFaviconDecode = resolve; }); | |
| 108 | 新增: }; | |
| 109 | 新增: globalThis.pendingFaviconRead = readCageFavicon(id); | |
| 110 | 新增: }, target); | |
| 111 | 新增: await controller.waitForFunction(() => typeof releaseFaviconDecode === "function"); | |
| 112 | 新增: await page.goto(origin + "/blocked-race"); | |
| 113 | 新增: await controller.evaluate(() => releaseFaviconDecode()); | |
| 114 | 新增: assert.equal(await controller.evaluate(() => pendingFaviconRead), null, "navigation cannot publish the previous document's icon"); | |
| 115 | 新增: await controller.evaluate(() => { HTMLImageElement.prototype.decode = originalFaviconDecode; }); | |
| 116 | 新增: await page.goto(origin + "/allowed"); | |
| 117 | 新增: await waitFor(async () => (await read(controller, target))?.favicon === red, "favicon after full navigation"); | |
| 118 | 新增: await controller.evaluate(id => { | |
| 119 | 新增: globalThis.releaseFaviconDecode = null; | |
| 120 | 新增: HTMLImageElement.prototype.decode = async function () { | |
| 121 | 新增: await originalFaviconDecode.call(this); | |
| 122 | 新增: await new Promise(resolve => { globalThis.releaseFaviconDecode = resolve; }); | |
| 123 | 新增: }; | |
| 124 | 新增: globalThis.pendingFaviconRead = readCageFavicon(id); | |
| 125 | 新增: }, target); | |
| 126 | 新增: await controller.waitForFunction(() => typeof releaseFaviconDecode === "function"); | |
| 127 | 新增: await page.close(); | |
| 128 | 新增: await controller.evaluate(() => releaseFaviconDecode()); | |
| 129 | 新增: assert.equal(await controller.evaluate(() => pendingFaviconRead), null, "a closed tab cannot publish a late icon"); | |
| 130 | 新增: assert.equal(await read(controller, target), null); | |
| 131 | 新增: const saved = await context.newPage(); | |
| 132 | 新增: await saved.goto(origin + "/restored"); | |
| 133 | 新增: await context.close(); | |
| 134 | 新增: | |
| 135 | 新增: context = await launch(); | |
| 136 | 新增: controller = await setupController(); | |
| 137 | 新增: const restored = await waitFor(async () => context.pages().find(tab => tab.url() === origin + "/restored"), "restored browser tab"); | |
| 138 | 新增: const restoredTarget = await targetFor(restored); | |
| 139 | 新增: await waitFor(async () => (await read(controller, restoredTarget))?.favicon === red, "restored tab favicon"); | |
| 140 | 新增: console.log("PASS: native Chromium icon cache, reciprocal CSP policies, cross-origin icons, 32px bounded PNG, SPA, dynamic updates, navigation/close races and session restoration"); | |
| 141 | 新增:} finally { | |
| 142 | 新增: await context?.close(); | |
| 143 | 新增: await Promise.all([new Promise(resolve => site.close(resolve)), new Promise(resolve => icons.close(resolve))]); | |
| 144 | 新增: await rm(profile, { recursive: true, force: true }); | |
| 145 | 新增:} | |
| @@ -0,0 +1,53 @@ | ||
| 1 | 新增:// Used only by disposable package-install test users. Never point seed at a | |
| 2 | 新增:// real profile: exclusive creation refuses to overwrite existing user files. | |
| 3 | 新增:import { createHash } from 'node:crypto'; | |
| 4 | 新增:import { mkdir, readFile, writeFile } from 'node:fs/promises'; | |
| 5 | 新增:import { dirname, join, resolve } from 'node:path'; | |
| 6 | 新增:import { pathToFileURL } from 'node:url'; | |
| 7 | 新增: | |
| 8 | 新增:const entries = [ | |
| 9 | 新增: '.claude-cage/config.json', | |
| 10 | 新增: '.claude-cage/environment.json', | |
| 11 | 新增: '.claude-cage/account.json', | |
| 12 | 新增: '.claude-cage/password-vault.json', | |
| 13 | 新增: '.claude-cage/favorites.json', | |
| 14 | 新增: '.claude-cage/projects.json', | |
| 15 | 新增: '.claude-cage/workbench.json', | |
| 16 | 新增: '.claude-cage/appearance.json', | |
| 17 | 新增: '.claude-cage/webview2/Default/Local Storage/leveldb/000001.log', | |
| 18 | 新增: '.claude-cage/webkit/data/WebsiteData/LocalStorage/storage.sqlite3', | |
| 19 | 新增: '.claude-cage/state/lima/persistent/disk', | |
| 20 | 新增: '.claude-cage-workspace/project.txt', | |
| 21 | 新增:]; | |
| 22 | 新增:const digest = (data) => createHash('sha256').update(data).digest('hex'); | |
| 23 | 新增: | |
| 24 | 新增:export async function seed(home, manifest) { | |
| 25 | 新增: const records = {}; | |
| 26 | 新增: for (const name of entries) { | |
| 27 | 新增: const path = join(home, name); | |
| 28 | 新增: await mkdir(dirname(path), { recursive: true, mode: 0o700 }); | |
| 29 | 新增: const bytes = Buffer.from(`Cage package test: preserve ${name}\n历史、收藏与登录数据\n\0\xff`, 'utf8'); | |
| 30 | 新增: await writeFile(path, bytes, { flag: 'wx', mode: 0o600 }); | |
| 31 | 新增: records[name] = digest(bytes); | |
| 32 | 新增: } | |
| 33 | 新增: await writeFile(manifest, JSON.stringify(records), { flag: 'wx', mode: 0o600 }); | |
| 34 | 新增:} | |
| 35 | 新增: | |
| 36 | 新增:export async function verify(home, manifest) { | |
| 37 | 新增: const records = JSON.parse(await readFile(manifest, 'utf8')); | |
| 38 | 新增: for (const [name, expected] of Object.entries(records)) { | |
| 39 | 新增: if (digest(await readFile(join(home, name))) !== expected) { | |
| 40 | 新增: throw new Error(`Installation changed personal data: ${name}`); | |
| 41 | 新增: } | |
| 42 | 新增: } | |
| 43 | 新增: return Object.keys(records).length; | |
| 44 | 新增:} | |
| 45 | 新增: | |
| 46 | 新增:if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) { | |
| 47 | 新增: const [operation, home, manifest] = process.argv.slice(2); | |
| 48 | 新增: if (!home || !manifest || !['seed', 'verify'].includes(operation)) { | |
| 49 | 新增: throw new Error('Usage: personal-data-fixture.mjs seed|verify TEST_HOME MANIFEST'); | |
| 50 | 新增: } | |
| 51 | 新增: if (operation === 'seed') await seed(home, manifest); | |
| 52 | 新增: else console.log(`PASS: ${await verify(home, manifest)} personal data files preserved byte for byte.`); | |
| 53 | 新增:} | |
| @@ -16,9 +16,14 @@ cleanup() { | ||
| 16 | 16 | } |
| 17 | 17 | trap cleanup EXIT |
| 18 | 18 | install -d -m 700 -o "$test_user" -g "$test_user" "$report_dir" "$test_home/.claude-cage" "$test_home/.claude-cage-workspace" |
| 19 | 删除:runuser -u "$test_user" -- sh -c 'printf "keep-profile\n" > "$1/.claude-cage/install-test-marker"; printf "keep-project\n" > "$1/.claude-cage-workspace/install-test-marker"' sh "$test_home" | |
| 19 | 新增:manifest="$report_dir/personal-data.json" | |
| 20 | 新增:runuser -u "$test_user" -- node "$PWD/scripts/personal-data-fixture.mjs" seed "$test_home" "$manifest" | |
| 21 | 新增:verify_personal_data() { | |
| 22 | 新增: runuser -u "$test_user" -- node "$PWD/scripts/personal-data-fixture.mjs" verify "$test_home" "$manifest" | |
| 23 | 新增:} | |
| 20 | 24 | export DEBIAN_FRONTEND=noninteractive |
| 21 | 25 | apt-get install --reinstall -y "$package" |
| 26 | 新增:verify_personal_data | |
| 22 | 27 | runuser -u "$test_user" -- /usr/lib/claude-cage/cage-desktop --self-test |
| 23 | 28 | runuser -u "$test_user" -- xvfb-run -a dbus-run-session -- node "$PWD/desktop/linux/test-smoke.mjs" /usr/lib/claude-cage/cage-desktop "$report_dir/first-install.json" |
| 24 | 29 | # Keep a real control service alive and confirm that preinst refuses replacement. |
| @@ -28,17 +33,19 @@ if dpkg -i "$package" > "$report_dir/running-upgrade.log" 2>&1; then | ||
| 28 | 33 | exit 1 |
| 29 | 34 | fi |
| 30 | 35 | grep -q 'Cage is running' "$report_dir/running-upgrade.log" |
| 36 | 新增:verify_personal_data | |
| 31 | 37 | if dpkg --remove claude-cage > "$report_dir/running-remove.log" 2>&1; then |
| 32 | 38 | echo 'FAIL: uninstaller removed a running Cage backend.' >&2 |
| 33 | 39 | exit 1 |
| 34 | 40 | fi |
| 35 | 41 | grep -q 'Cage is running' "$report_dir/running-remove.log" |
| 42 | 新增:verify_personal_data | |
| 36 | 43 | runuser -u "$test_user" -- env CLAUDE_CAGE_CONFIG="$profile" /usr/bin/claude-cage prepare-update --json > "$report_dir/guard-stop.json" |
| 37 | 44 | dpkg -i "$package" |
| 45 | 新增:verify_personal_data | |
| 38 | 46 | runuser -u "$test_user" -- xvfb-run -a dbus-run-session -- node "$PWD/desktop/linux/test-smoke.mjs" /usr/lib/claude-cage/cage-desktop "$report_dir/after-reinstall.json" |
| 39 | 47 | dpkg --remove claude-cage |
| 40 | 48 | [[ ! -e /usr/bin/cage-desktop && ! -e /usr/lib/claude-cage/cage ]] || { echo 'Uninstall left installed executables.' >&2; exit 1; } |
| 41 | 删除:[[ $(cat "$test_home/.claude-cage/install-test-marker") == keep-profile ]] | |
| 42 | 删除:[[ $(cat "$test_home/.claude-cage-workspace/install-test-marker") == keep-project ]] | |
| 49 | 新增:verify_personal_data | |
| 43 | 50 | printf '{"success":true,"install":true,"nativeWorkbench":true,"runningUpgradeRefused":true,"runningRemovalRefused":true,"reinstall":true,"uninstallPreservedData":true}\n' > "$report_dir/install.json" |
| 44 | 51 | printf 'PASS: package install, native workbench, running-update refusal, reinstall and data-preserving removal. Reports: %s\n' "$report_dir" |
| @@ -8,6 +8,12 @@ $target = Join-Path $env:LOCALAPPDATA ('Programs/Cage-test-' + [guid]::NewGuid() | ||
| 8 | 8 | $report = Join-Path ([IO.Path]::GetTempPath()) ('cage-smoke-' + [guid]::NewGuid().ToString('N') + '.json') |
| 9 | 9 | $savedKey = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\ClaudeCage' |
| 10 | 10 | if (Test-Path $savedKey) { throw 'Use a disposable Windows user without an existing Cage installation.' } |
| 11 | 新增:$fixture = Join-Path $PSScriptRoot 'personal-data-fixture.mjs' | |
| 12 | 新增:$manifest = Join-Path ([IO.Path]::GetTempPath()) ('cage-personal-data-' + [guid]::NewGuid().ToString('N') + '.json') | |
| 13 | 新增:Invoke-BuildTool 'node' @($fixture, 'seed', $env:USERPROFILE, $manifest) | |
| 14 | 新增:function Assert-PersonalData { | |
| 15 | 新增: Invoke-BuildTool 'node' @($fixture, 'verify', $env:USERPROFILE, $manifest) | |
| 16 | 新增:} | |
| 11 | 17 | function Run-Installer { |
| 12 | 18 | param([switch]$Update, [int]$ExpectedExitCode = 0) |
| 13 | 19 | $arguments = @('/S') |
| @@ -18,27 +24,32 @@ function Run-Installer { | ||
| 18 | 24 | if ($process.ExitCode -ne $ExpectedExitCode) { throw "Installer returned $($process.ExitCode), expected $ExpectedExitCode" } |
| 19 | 25 | } |
| 20 | 26 | Run-Installer |
| 27 | 新增:Assert-PersonalData | |
| 21 | 28 | if (-not (Test-Path -LiteralPath (Join-Path $target 'Cage.exe'))) { throw 'Installer did not create Cage.exe.' } |
| 22 | 29 | Invoke-BuildTool (Join-Path $target 'resources/cage.exe') @('--help') |
| 23 | 30 | Invoke-BuildTool (Join-Path $target 'resources/mihomo.exe') @('-v') |
| 24 | 31 | Invoke-BuildTool (Join-Path $target 'resources/runtime/qemu/qemu-system-x86_64.exe') @('--version') |
| 25 | 32 | Invoke-BuildTool (Join-Path $target 'resources/runtime/openssh/ssh.exe') @('-V') |
| 26 | 删除:$window = Start-Process -FilePath (Join-Path $target 'Cage.exe') -ArgumentList @('--smoke-test', "`"$report`"") -PassThru | |
| 27 | 删除:if (-not $window.WaitForExit(180000)) { throw 'Cage WebView2/workbench smoke test timed out.' } | |
| 28 | 删除:if ($window.ExitCode -ne 0 -or -not (Test-Path -LiteralPath $report)) { throw "Cage desktop smoke test failed ($($window.ExitCode))." } | |
| 33 | 新增:$savedProfile = $env:CLAUDE_CAGE_CONFIG | |
| 34 | 新增:try { | |
| 35 | 新增: # The UI test owns a separate profile; the installer must preserve the | |
| 36 | 新增: # pre-existing default profile without asking the app to parse test bytes. | |
| 37 | 新增: $env:CLAUDE_CAGE_CONFIG = Join-Path ([IO.Path]::GetTempPath()) ('cage-ui-profile-' + [guid]::NewGuid().ToString('N') + '/config.json') | |
| 38 | 新增: $window = Start-Process -FilePath (Join-Path $target 'Cage.exe') -ArgumentList @('--smoke-test', "`"$report`"") -PassThru | |
| 39 | 新增: if (-not $window.WaitForExit(180000)) { throw 'Cage WebView2/workbench smoke test timed out.' } | |
| 40 | 新增: if ($window.ExitCode -ne 0 -or -not (Test-Path -LiteralPath $report)) { throw "Cage desktop smoke test failed ($($window.ExitCode))." } | |
| 41 | 新增:} finally { $env:CLAUDE_CAGE_CONFIG = $savedProfile } | |
| 42 | 新增:Assert-PersonalData | |
| 29 | 43 | Get-Content -LiteralPath $report |
| 30 | 44 | # A locked installed executable must fail before replacing the installation. |
| 31 | 45 | $before = (Get-FileHash -LiteralPath (Join-Path $target 'Cage.exe') -Algorithm SHA256).Hash |
| 32 | 46 | $locked = [IO.File]::Open((Join-Path $target 'Cage.exe'), [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::Read) |
| 33 | 47 | try { Run-Installer -Update -ExpectedExitCode 2 } finally { $locked.Dispose() } |
| 48 | 新增:Assert-PersonalData | |
| 34 | 49 | if ((Get-FileHash -LiteralPath (Join-Path $target 'Cage.exe') -Algorithm SHA256).Hash -ne $before) { throw 'Failed update replaced the existing application.' } |
| 35 | 50 | # Reinstall through the real atomic replacement path. User data must survive. |
| 36 | 删除:$state = Join-Path $env:USERPROFILE '.claude-cage' | |
| 37 | 删除:New-Item -ItemType Directory -Path $state -Force | Out-Null | |
| 38 | 删除:$sentinel = Join-Path $state ('installer-test-' + [guid]::NewGuid().ToString('N')) | |
| 39 | 删除:[IO.File]::WriteAllText($sentinel, 'preserve') | |
| 40 | 51 | Run-Installer -Update |
| 41 | 删除:if ((Get-Content -LiteralPath $sentinel -Raw) -ne 'preserve') { throw 'Upgrade modified user data.' } | |
| 52 | 新增:Assert-PersonalData | |
| 42 | 53 | $uninstall = Start-Process -FilePath (Join-Path $target 'Uninstall.exe') -ArgumentList @('/S') -PassThru |
| 43 | 54 | if (-not $uninstall.WaitForExit(120000) -or $uninstall.ExitCode -ne 0) { throw 'Uninstall failed.' } |
| 44 | 55 | # NSIS may relaunch its uninstaller from TEMP so that it can delete the original. |
| @@ -46,6 +57,5 @@ $deadline = [DateTime]::UtcNow.AddSeconds(120) | ||
| 46 | 57 | while ((Test-Path -LiteralPath (Join-Path $target 'Uninstall.exe')) -and [DateTime]::UtcNow -lt $deadline) { Start-Sleep -Milliseconds 200 } |
| 47 | 58 | if (Test-Path -LiteralPath (Join-Path $target 'Cage.exe')) { throw 'Uninstall left Cage.exe behind.' } |
| 48 | 59 | if (Test-Path -LiteralPath (Join-Path $target 'Uninstall.exe')) { throw 'Uninstall left its launcher behind.' } |
| 49 | 删除:if ((Get-Content -LiteralPath $sentinel -Raw) -ne 'preserve') { throw 'Uninstall modified user data.' } | |
| 50 | 删除:Remove-Item -LiteralPath $sentinel | |
| 60 | 新增:Assert-PersonalData | |
| 51 | 61 | Write-Host 'Install, WebView2 workbench, reinstall, uninstall and user-data preservation passed. VM startup was not tested.' |
| @@ -0,0 +1,84 @@ | ||
| 1 | 新增:// Production controller and private CDP pipe, with a disposable local HTTPS site. | |
| 2 | 新增:// Only deployment paths, test certificate handling and the test CDP route differ. | |
| 3 | 新增:import assert from "node:assert/strict"; | |
| 4 | 新增:import { spawn, execFileSync } from "node:child_process"; | |
| 5 | 新增:import { once } from "node:events"; | |
| 6 | 新增:import { randomBytes } from "node:crypto"; | |
| 7 | 新增:import { cp, mkdtemp, readdir, readFile, realpath, rm, writeFile } from "node:fs/promises"; | |
| 8 | 新增:import https from "node:https"; | |
| 9 | 新增:import { tmpdir } from "node:os"; | |
| 10 | 新增:import { join } from "node:path"; | |
| 11 | 新增:import { setTimeout as delay } from "node:timers/promises"; | |
| 12 | 新增:assert.ok(process.env.CAGE_TEST_BROWSER_PATH, "Set CAGE_TEST_BROWSER_PATH to Chromium"); | |
| 13 | 新增:const dir = await realpath(await mkdtemp(join(tmpdir(), "cage-vault-controller-"))); | |
| 14 | 新增:const token = randomBytes(32).toString("hex"), lease = randomBytes(32).toString("hex"); | |
| 15 | 新增:execFileSync("openssl", ["req", "-x509", "-newkey", "rsa:2048", "-nodes", "-keyout", join(dir, "key.pem"), "-out", join(dir, "cert.pem"), "-days", "1", "-subj", "/CN=localhost"], { stdio: "ignore" }); | |
| 16 | 新增:const site = https.createServer({ key: await readFile(join(dir,"key.pem")), cert: await readFile(join(dir,"cert.pem")) }, (req,res) => { | |
| 17 | 新增: res.setHeader("Content-Type","text/html"); | |
| 18 | 新增: res.end('<title>Vault fixture</title><form onsubmit="event.preventDefault()"><label>Email<input id="user" autocomplete="username"></label><label>Password<input id="pass" type="password" autocomplete="current-password"></label><button>Sign in</button></form>'); | |
| 19 | 新增:}); | |
| 20 | 新增:await new Promise(resolve => site.listen(0, "127.0.0.1", resolve)); | |
| 21 | 新增:const origin = `https://127.0.0.1:${site.address().port}`; | |
| 22 | 新增:let agent, control, stderr = ""; | |
| 23 | 新增:async function waitFor(fn, label) { | |
| 24 | 新增: for (let i=0;i<150;i++) { if (agent?.exitCode !== null) throw new Error("Controller exited: " + stderr.slice(-1000)); const result=await fn(); if(result) return result; await delay(50); } | |
| 25 | 新增: throw new Error("Timed out: " + label); | |
| 26 | 新增:} | |
| 27 | 新增:async function api(path, input) { | |
| 28 | 新增: const res=await fetch(control+path,{method:input===undefined?"GET":"POST",headers:{Authorization:`Bearer ${token}`,"Content-Type":"application/json"},body:input===undefined?undefined:JSON.stringify(input)}); | |
| 29 | 新增: assert.equal(res.status,200); | |
| 30 | 新增: return res.json(); | |
| 31 | 新增:} | |
| 32 | 新增:const vault = input => api("/vault",{lease,...input}); | |
| 33 | 新增:async function evaluate(id, expression) { | |
| 34 | 新增: const result=await api("/__vault-test",{id,method:"Runtime.evaluate",params:{expression,returnByValue:true}}); | |
| 35 | 新增: assert.equal(result.exceptionDetails, undefined); | |
| 36 | 新增: return result.result.value; | |
| 37 | 新增:} | |
| 38 | 新增:try { | |
| 39 | 新增: const sourceDir=new URL("../internal/cage/",import.meta.url); | |
| 40 | 新增: for(const name of await readdir(sourceDir)) if ((name.startsWith("browser-")&&name.endsWith(".mjs"))||name==="native-input.mjs") await cp(new URL(name,sourceDir),join(dir,name)); | |
| 41 | 新增: await cp(new URL("split-extension",sourceDir),join(dir,"extension"),{recursive:true}); | |
| 42 | 新增: const original=await readFile(new URL("browser-agent.mjs",sourceDir),"utf8"); | |
| 43 | 新增: const marker='const input = JSON.parse(text || "{}");'; | |
| 44 | 新增: const adapted=original.replaceAll("/home/cage-browser",dir).replace("/etc/claude-cage/browser-control.json",join(dir,"control.json")) | |
| 45 | 新增: .replace("/usr/local/lib/cage-split",join(dir,"extension")) | |
| 46 | 新增: .replace('spawn("/usr/bin/chromium", flags',`spawn(${JSON.stringify(process.env.CAGE_TEST_BROWSER_PATH)}, flags`) | |
| 47 | 新增: .replace('"--kiosk",','"--headless=new", "--ignore-certificate-errors", "--disable-background-networking",') | |
| 48 | 新增: .replace('server.listen(18500, "127.0.0.1");','server.listen(0,"127.0.0.1",()=>console.log("PORT="+server.address().port));') | |
| 49 | 新增: .replace(marker,`${marker}\nif (req.url === "/__vault-test") { res.end(JSON.stringify(await cdp(input.method,input.params||{},await session(input.id)))); return; }`); | |
| 50 | 新增: assert.notEqual(adapted, original); | |
| 51 | 新增: await writeFile(join(dir,"browser-agent.mjs"),adapted); | |
| 52 | 新增: await writeFile(join(dir,"control.json"),JSON.stringify({token,workspace:dir})); | |
| 53 | 新增: await writeFile(join(dir,"homepage.json"),JSON.stringify({url:origin+"/login"})); | |
| 54 | 新增: agent=spawn(process.execPath,[join(dir,"browser-agent.mjs")],{stdio:["ignore","pipe","pipe"]}); | |
| 55 | 新增: agent.stdout.on("data",chunk=>{const match=chunk.toString().match(/PORT=(\d+)/);if(match)control="http://127.0.0.1:"+match[1];}); | |
| 56 | 新增: agent.stderr.on("data",chunk=>{stderr=(stderr+chunk).slice(-3000);}); | |
| 57 | 新增: await waitFor(()=>control,"listener"); | |
| 58 | 新增: await waitFor(async()=> (await fetch(control+"/health",{headers:{Authorization:`Bearer ${token}`}})).ok,"ready"); | |
| 59 | 新增: const tab=(await api("/tabs")).active; | |
| 60 | 新增: await waitFor(()=>evaluate(tab,"document.readyState === 'complete'"),"fixture"); | |
| 61 | 新增: const state=await vault({action:"status",tab}); | |
| 62 | 新增: assert.equal(state.origin,origin);assert.ok(state.document); | |
| 63 | 新增: await evaluate(tab,"document.getElementById('user').value='[email protected]';document.getElementById('pass').value='controller-secret'"); | |
| 64 | 新增: const point=await evaluate(tab,"(()=>{const r=document.querySelector('button').getBoundingClientRect();return {x:r.x+r.width/2,y:r.y+r.height/2}})()"); | |
| 65 | 新增: for(const type of ["mousePressed","mouseReleased"]) await api("/__vault-test",{id:tab,method:"Input.dispatchMouseEvent",params:{type,...point,button:"left",clickCount:1}}); | |
| 66 | 新增: const pending=await waitFor(async()=> (await vault({action:"status",tab})).candidates[0],"captured password"); | |
| 67 | 新增: assert.equal(pending.password,"controller-secret");assert.equal(pending.username,"[email protected]"); | |
| 68 | 新增: assert.ok(!JSON.stringify(await api("/tabs")).includes("controller-secret")); | |
| 69 | 新增: assert.equal((await fetch(control+"/vault",{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"})).status,401); | |
| 70 | 新增: assert.equal((await fetch(control+"/vault",{method:"POST",headers:{Authorization:`Bearer ${token}`,Origin:origin,"Content-Type":"application/json"},body:"{}"})).status,403); | |
| 71 | 新增: await evaluate(tab,"document.getElementById('user').value='';document.getElementById('pass').value=''"); | |
| 72 | 新增: assert.equal((await vault({action:"fill",tab,origin,document:state.document,username:"[email protected]",password:"selected-secret"})).ok,true); | |
| 73 | 新增: assert.equal(await evaluate(tab,"document.getElementById('pass').value"),"selected-secret"); | |
| 74 | 新增: await api("/navigate",{id:tab,url:origin+"/next"}); | |
| 75 | 新增: await waitFor(()=>evaluate(tab,"location.pathname === '/next' && document.readyState === 'complete'"),"navigation"); | |
| 76 | 新增: assert.ok((await vault({action:"fill",tab,origin,document:state.document,username:"stale",password:"stale"})).vaultError); | |
| 77 | 新增: await vault({action:"lock"}); | |
| 78 | 新增: assert.ok((await vault({action:"candidate",candidate:pending.id})).vaultError); | |
| 79 | 新增: console.log("PASS: production controller HTTPS capture/fill, private authentication, public-state redaction, navigation and lock"); | |
| 80 | 新增:} finally { | |
| 81 | 新增: if(agent?.exitCode===null){const exit=once(agent,"exit");agent.kill("SIGTERM");const timer=setTimeout(()=>agent.kill("SIGKILL"),5000);await exit;clearTimeout(timer);} | |
| 82 | 新增: await new Promise(resolve=>site.close(resolve)); | |
| 83 | 新增: await rm(dir,{recursive:true,force:true}); | |
| 84 | 新增:} | |
| @@ -0,0 +1,85 @@ | ||
| 1 | 新增:// Full UI -> real Go service -> encrypted disk round trip in a new temp profile. | |
| 2 | 新增:import assert from "node:assert/strict"; | |
| 3 | 新增:import fs from "node:fs/promises"; | |
| 4 | 新增:import os from "node:os"; | |
| 5 | 新增:import path from "node:path"; | |
| 6 | 新增:import { spawn } from "node:child_process"; | |
| 7 | 新增:import { createRequire } from "node:module"; | |
| 8 | 新增:import { fileURLToPath } from "node:url"; | |
| 9 | 新增:const require = createRequire(import.meta.url); | |
| 10 | 新增:const { chromium } = require(process.env.CAGE_PLAYWRIGHT_MODULE || "playwright"); | |
| 11 | 新增:const root = fileURLToPath(new URL("../", import.meta.url)); | |
| 12 | 新增:const profile = await fs.mkdtemp(path.join(os.tmpdir(), "cage-vault-e2e-")); | |
| 13 | 新增:await fs.writeFile(path.join(profile, "config.json"), JSON.stringify({ proxy_url: "socks5://127.0.0.1:1", dns_url: "https://1.1.1.1/dns-query", timezone: "Etc/UTC", locale: "en_US.UTF-8", browser_language: "en-US" }), { mode: 0o600 }); | |
| 14 | 新增:await fs.writeFile(path.join(profile, "workbench.json"), JSON.stringify({ workspace: path.join(profile, "workspace") }), { mode: 0o600 }); | |
| 15 | 新增:let service, browser, page; | |
| 16 | 新增:async function start() { | |
| 17 | 新增: await fs.rm(path.join(profile, "control.json"), { force: true }); | |
| 18 | 新增: service = spawn(path.join(root, "_output/vault-qa/cage"), ["serve"], { env: { ...process.env, CLAUDE_CAGE_CONFIG: path.join(profile, "config.json") }, stdio: "ignore" }); | |
| 19 | 新增: let control; | |
| 20 | 新增: for (let i = 0; i < 100; i++) { | |
| 21 | 新增: try { control = JSON.parse(await fs.readFile(path.join(profile, "control.json"), "utf8")); break; } | |
| 22 | 新增: catch { await new Promise(resolve => setTimeout(resolve, 100)); } | |
| 23 | 新增: } | |
| 24 | 新增: assert.ok(control, "isolated service did not start"); | |
| 25 | 新增: const origin = `http://localhost:${control.port}`; | |
| 26 | 新增: const response = await fetch(origin + "/api/launch", { method: "POST", headers: { Origin: origin, "Content-Type": "application/json" }, body: JSON.stringify({ token: control.token }) }); | |
| 27 | 新增: assert.ok(response.ok); | |
| 28 | 新增: return (await response.json()).url; | |
| 29 | 新增:} | |
| 30 | 新增:async function stop() { | |
| 31 | 新增: if (service && service.exitCode === null) await new Promise(resolve => { service.once("exit", resolve); service.kill("SIGTERM"); }); | |
| 32 | 新增:} | |
| 33 | 新增:try { | |
| 34 | 新增: browser = await chromium.launch({ headless: true }); | |
| 35 | 新增: page = await browser.newPage(); | |
| 36 | 新增: const errors = []; | |
| 37 | 新增: page.on("pageerror", error => errors.push(error.message)); | |
| 38 | 新增: await page.goto(await start()); | |
| 39 | 新增: await page.getByLabel("用户名", { exact: true }).fill("保险箱验证"); | |
| 40 | 新增: await page.getByLabel("设置密码", { exact: true }).fill("isolated-vault-account-password"); | |
| 41 | 新增: await page.getByLabel("确认密码", { exact: true }).fill("isolated-vault-account-password"); | |
| 42 | 新增: await page.getByRole("button", { name: "创建本地账户", exact: true }).click(); | |
| 43 | 新增: const openVault = async () => { | |
| 44 | 新增: await page.getByRole("button", { name: "设置", exact: true }).click(); | |
| 45 | 新增: await page.getByRole("navigation", { name: "设置分组" }).getByRole("button", { name: "密码保险箱", exact: true }).click(); | |
| 46 | 新增: await page.getByRole("heading", { name: "密码保险箱", exact: true }).waitFor(); | |
| 47 | 新增: }; | |
| 48 | 新增: await openVault(); | |
| 49 | 新增: await page.getByRole("button", { name: "添加密码", exact: true }).click(); | |
| 50 | 新增: await page.getByLabel("网站地址", { exact: true }).fill("https://mail.example.test/login"); | |
| 51 | 新增: await page.getByLabel("账号或邮箱").fill("[email protected]"); | |
| 52 | 新增: await page.getByLabel("网站密码", { exact: true }).fill("isolated-website-secret"); | |
| 53 | 新增: await page.getByRole("button", { name: "保存记录", exact: true }).click(); | |
| 54 | 新增: await page.getByRole("status").filter({ hasText: "密码记录已保存" }).waitFor(); | |
| 55 | 新增: const raw = await fs.readFile(path.join(profile, "password-vault.json"), "utf8"); | |
| 56 | 新增: for (const value of ["[email protected]", "isolated-website-secret", "mail.example.test"]) assert.ok(!raw.includes(value), "plaintext persisted"); | |
| 57 | 新增: const list = await page.evaluate(async () => (await fetch("/api/vault")).json()); | |
| 58 | 新增: assert.equal(list.entries[0].origin, "https://mail.example.test"); | |
| 59 | 新增: assert.equal(list.entries[0].password, undefined); | |
| 60 | 新增: await stop(); | |
| 61 | 新增: await page.goto(await start()); | |
| 62 | 新增: await page.getByLabel("账户密码", { exact: true }).fill("isolated-vault-account-password"); | |
| 63 | 新增: await page.getByRole("button", { name: "解锁 Cage", exact: true }).click(); | |
| 64 | 新增: await openVault(); | |
| 65 | 新增: await page.getByText("[email protected]", { exact: true }).waitFor(); | |
| 66 | 新增: await page.getByRole("button", { name: "查看密码", exact: true }).click(); | |
| 67 | 新增: await page.getByLabel("Cage 账户密码", { exact: true }).fill("isolated-vault-account-password"); | |
| 68 | 新增: await page.getByRole("button", { name: "验证并查看" }).click(); | |
| 69 | 新增: await page.getByLabel("已保存的网站密码").waitFor(); | |
| 70 | 新增: assert.equal(await page.getByLabel("已保存的网站密码").textContent(), "isolated-website-secret"); | |
| 71 | 新增: await page.getByRole("button", { name: "返回工作台", exact: true }).click(); | |
| 72 | 新增: await page.getByRole("button", { name: /^账户菜单,/ }).click(); | |
| 73 | 新增: await page.getByRole("menuitem", { name: /锁定 Cage/ }).click(); | |
| 74 | 新增: await page.getByRole("region", { name: "解锁 Cage", exact: true }).waitFor(); | |
| 75 | 新增: assert.equal(await page.evaluate(async () => (await fetch("/api/vault")).status), 423); | |
| 76 | 新增: assert.equal(await fs.readFile(path.join(profile, "password-vault.json"), "utf8"), raw, "restart/lock modified vault data"); | |
| 77 | 新增: assert.deepEqual(errors, []); | |
| 78 | 新增: console.log("PASS: real UI and Go service create/save, encrypted disk, redacted API, service restart, unlock/reveal, lock and data preservation"); | |
| 79 | 新增:} catch (error) { | |
| 80 | 新增: console.error((await page?.locator("body").innerText())?.slice(0, 3000)); | |
| 81 | 新增: throw error; | |
| 82 | 新增:} finally { | |
| 83 | 新增: await browser?.close(); await stop(); | |
| 84 | 新增: await fs.rm(profile, { recursive: true, force: true }); | |
| 85 | 新增:} | |
| @@ -1,12 +1,12 @@ | ||
| 1 | 1 | { |
| 2 | 2 | "name": "cage-workbench", |
| 3 | 删除: "version": "0.1.4-alpha", | |
| 3 | 新增: "version": "0.1.5-alpha", | |
| 4 | 4 | "lockfileVersion": 3, |
| 5 | 5 | "requires": true, |
| 6 | 6 | "packages": { |
| 7 | 7 | "": { |
| 8 | 8 | "name": "cage-workbench", |
| 9 | 删除: "version": "0.1.4-alpha", | |
| 9 | 新增: "version": "0.1.5-alpha", | |
| 10 | 10 | "dependencies": { |
| 11 | 11 | "@xterm/addon-fit": "0.11.0", |
| 12 | 12 | "@xterm/xterm": "6.0.0", |
| @@ -1,7 +1,7 @@ | ||
| 1 | 1 | { |
| 2 | 2 | "name": "cage-workbench", |
| 3 | 3 | "private": true, |
| 4 | 删除: "version": "0.1.4-alpha", | |
| 4 | 新增: "version": "0.1.5-alpha", | |
| 5 | 5 | "type": "module", |
| 6 | 6 | "scripts": { |
| 7 | 7 | "prepare-vnc": "node scripts/prepare-vnc.mjs", |
| @@ -28,7 +28,7 @@ try { | ||
| 28 | 28 | await page.getByLabel('设置密码',{exact:true}).fill('fixture-password'); |
| 29 | 29 | await page.getByLabel('确认密码',{exact:true}).fill('fixture-password'); |
| 30 | 30 | await page.getByRole('button',{name:'创建本地账户',exact:true}).click();await menu().waitFor(); |
| 31 | 删除: await menu().click();await page.getByRole('menuitem',{name:'账户设置',exact:true}).click(); | |
| 31 | 新增: await menu().click();await page.getByRole('menuitem',{name:'设置',exact:true}).click(); | |
| 32 | 32 | const automatic=page.getByRole('checkbox',{name:/记住登录/}); |
| 33 | 33 | const biometric=page.getByRole('checkbox',{name:/使用 Touch ID 解锁/}); |
| 34 | 34 | await page.waitForFunction(()=>document.querySelector('.account-device-settings input')?.checked); |
| @@ -39,9 +39,9 @@ try { | ||
| 39 | 39 | // A genuine reopen keeps enrollment but starts with a locked server. |
| 40 | 40 | state.account.unlocked=false;await page.reload();await menu().waitFor(); |
| 41 | 41 | assert.equal(calls.filter(x=>x.operation==='unlock'&&x.kind==='automatic').length,1); |
| 42 | 删除: await menu().click();await page.getByRole('menuitem',{name:'账户设置',exact:true}).click(); | |
| 42 | 新增: await menu().click();await page.getByRole('menuitem',{name:'设置',exact:true}).click(); | |
| 43 | 43 | await automatic.click();await page.getByRole('status').filter({hasText:'已关闭'}).waitFor(); |
| 44 | 删除: await page.reload();await menu().click();await page.getByRole('menuitem',{name:'账户设置',exact:true}).click(); | |
| 44 | 新增: await page.reload();await menu().click();await page.getByRole('menuitem',{name:'设置',exact:true}).click(); | |
| 45 | 45 | assert.equal(await automatic.isChecked(),false,'explicit opt-out was overridden'); |
| 46 | 46 | await automatic.click();await page.getByRole('status').filter({hasText:'已开启'}).waitFor(); |
| 47 | 47 | await page.getByRole('button',{name:'返回工作台',exact:true}).click(); |
| @@ -11,6 +11,27 @@ const {browser,page,state,errors} = await createWorkbench({nativeRequest: async | ||
| 11 | 11 | }}); |
| 12 | 12 | await page.exposeFunction('fixtureLaunchAcks', () => launchAcks); |
| 13 | 13 | const accountMenu = () => page.getByRole('button', { name: /^账户菜单,/ }); |
| 14 | 新增:async function checkMenuLayout() { | |
| 15 | 新增: const trigger = accountMenu(); | |
| 16 | 新增: const settings = page.getByRole('button', { name: '设置', exact: true }); | |
| 17 | 新增: const list = page.getByRole('menu', { name: '本地账户菜单' }); | |
| 18 | 新增: const projects = page.locator('.sidebar-scroll'); | |
| 19 | 新增: const before = await Promise.all([trigger.boundingBox(), settings.boundingBox(), projects.boundingBox()]); | |
| 20 | 新增: await trigger.click(); | |
| 21 | 新增: const menu = await list.boundingBox(); | |
| 22 | 新增: assert.ok(menu.y >= 0 && menu.y + menu.height <= before[0].y); | |
| 23 | 新增: assert.deepEqual(await trigger.boundingBox(), before[0]); | |
| 24 | 新增: assert.deepEqual(await settings.boundingBox(), before[1]); | |
| 25 | 新增: const projectBox = await projects.boundingBox(); | |
| 26 | 新增: assert.ok(projectBox.y + projectBox.height <= menu.y); | |
| 27 | 新增: assert.equal(await page.getByRole('menuitem', {name:'设置',exact:true}).evaluate(el => el === document.activeElement), true); | |
| 28 | 新增: await page.keyboard.press('ArrowDown'); | |
| 29 | 新增: assert.equal(await page.getByRole('menuitem', {name:/锁定 Cage/}).evaluate(el => el === document.activeElement), true); | |
| 30 | 新增: await page.keyboard.press('Escape'); | |
| 31 | 新增: await list.waitFor({state:'hidden'}); | |
| 32 | 新增: assert.equal(await trigger.evaluate(el => el === document.activeElement), true); | |
| 33 | 新增: assert.deepEqual(await projects.boundingBox(), before[2]); | |
| 34 | 新增:} | |
| 14 | 35 | try { |
| 15 | 36 | Object.assign(state.account, {exists:false,unlocked:false,username:''}); |
| 16 | 37 | const previousAcks = launchAcks; |
| @@ -23,10 +44,15 @@ try { | ||
| 23 | 44 | await page.getByLabel('确认密码',{exact:true}).fill('fixture-password'); |
| 24 | 45 | await page.getByRole('button',{name:'创建本地账户',exact:true}).click(); |
| 25 | 46 | await accountMenu().waitFor(); |
| 26 | 删除: await accountMenu().click(); | |
| 47 | 新增: await checkMenuLayout(); | |
| 48 | 新增: await accountMenu().press('Enter'); | |
| 27 | 49 | await page.screenshot({path:output+'menu.png'}); |
| 28 | 删除: await page.getByRole('menuitem',{name:'账户设置',exact:true}).click(); | |
| 50 | 新增: await page.keyboard.press('Enter'); | |
| 29 | 51 | await page.getByRole('heading',{name:'账户',exact:true}).waitFor(); |
| 52 | 新增: const groups = page.getByRole('navigation',{name:'设置分组'}); | |
| 53 | 新增: await groups.getByRole('button',{name:'通用',exact:true}).click(); | |
| 54 | 新增: await page.getByRole('heading',{name:'键盘习惯',exact:true}).waitFor(); | |
| 55 | 新增: await groups.getByRole('button',{name:'账户',exact:true}).click(); | |
| 30 | 56 | await page.getByLabel('用户名',{exact:true}).fill('山雀的工作室'); |
| 31 | 57 | await page.getByLabel('选择头像图片').setInputFiles(fileURLToPath(new URL('../src/logo.png',import.meta.url))); |
| 32 | 58 | state.failAccountSave=true; |
| @@ -49,7 +75,7 @@ try { | ||
| 49 | 75 | state.status.vm_running=true;state.status.ready=true; |
| 50 | 76 | await page.reload(); |
| 51 | 77 | await page.getByRole('button',{name:/^在 .* 新建终端$/}).click(); |
| 52 | 删除: await page.getByRole('button',{name:'新建普通终端',exact:true}).click(); | |
| 78 | 新增: await page.getByRole('menuitem',{name:'普通终端',exact:true}).click(); | |
| 53 | 79 | const ids=state.terminals.map(x=>x.id); |
| 54 | 80 | await accountMenu().click(); |
| 55 | 81 | await page.getByRole('menuitem',{name:/锁定 Cage/}).click(); |
| @@ -69,11 +95,12 @@ try { | ||
| 69 | 95 | await accountMenu().waitFor(); |
| 70 | 96 | assert.match(await accountMenu().getAttribute('aria-label'),/山雀的工作室/); |
| 71 | 97 | await accountMenu().click(); |
| 72 | 删除: await page.getByRole('menuitem',{name:'账户设置',exact:true}).click(); | |
| 98 | 新增: await page.getByRole('menuitem',{name:'设置',exact:true}).click(); | |
| 73 | 99 | assert.equal(await page.getByLabel('用户名',{exact:true}).inputValue(),'山雀的工作室'); |
| 74 | 100 | await page.setViewportSize({width:820,height:558}); |
| 75 | 101 | await page.screenshot({path:output+'settings-small.png'}); |
| 76 | 102 | await page.getByRole('button',{name:'返回工作台',exact:true}).click(); |
| 103 | 新增: await checkMenuLayout(); | |
| 77 | 104 | await accountMenu().click(); |
| 78 | 105 | await page.getByRole('menuitem',{name:'退出账户',exact:true}).click(); |
| 79 | 106 | await page.getByRole('dialog').getByRole('button',{name:'停止环境并退出账户',exact:true}).click(); |
| @@ -1,7 +1,7 @@ | ||
| 1 | 1 | import assert from "node:assert/strict"; |
| 2 | 2 | import fs from "node:fs/promises"; |
| 3 | 3 | import { fileURLToPath } from "node:url"; |
| 4 | 删除:import { createWorkbench } from "./workbench-fixture.mjs"; | |
| 4 | 新增:import { chooseInline, createWorkbench } from "./workbench-fixture.mjs"; | |
| 5 | 5 | const output = fileURLToPath( |
| 6 | 6 | new URL("../../docs/test-reports/2026-10-31-appearance/", import.meta.url), |
| 7 | 7 | ); |
| @@ -90,7 +90,7 @@ try { | ||
| 90 | 90 | .evaluate((el) => getComputedStyle(el).cursor), |
| 91 | 91 | "pointer", |
| 92 | 92 | ); |
| 93 | 删除: await page.getByLabel("减少动态效果", { exact: true }).selectOption("on"); | |
| 93 | 新增: await chooseInline(page.getByLabel("减少动态效果", { exact: true }), "on"); | |
| 94 | 94 | await saved(); |
| 95 | 95 | assert.equal( |
| 96 | 96 | await page.evaluate(() => document.documentElement.dataset.reducedMotion), |
| @@ -144,6 +144,7 @@ try { | ||
| 144 | 144 | .getByRole("button", { name: "新建终端", exact: true }) |
| 145 | 145 | .first() |
| 146 | 146 | .click(); |
| 147 | 新增: await page.getByRole("menuitem", { name: "普通终端", exact: true }).click(); | |
| 147 | 148 | await page.getByRole("tab", { name: "终端 1", exact: true }).waitFor(); |
| 148 | 149 | const count = state.terminalConnections; |
| 149 | 150 | await showAppearance(); |
| @@ -6,7 +6,7 @@ import os from "node:os"; | ||
| 6 | 6 | import path from "node:path"; |
| 7 | 7 | import { spawn } from "node:child_process"; |
| 8 | 8 | import { fileURLToPath } from "node:url"; |
| 9 | 删除:import { createWorkbench } from "./workbench-fixture.mjs"; | |
| 9 | 新增:import { chooseInline, createWorkbench } from "./workbench-fixture.mjs"; | |
| 10 | 10 | |
| 11 | 11 | const root = fileURLToPath(new URL("../../", import.meta.url)); |
| 12 | 12 | const output = path.join( |
| @@ -64,6 +64,13 @@ async function start() { | ||
| 64 | 64 | body: JSON.stringify({ token: new URL(url).hash.slice(1) }), |
| 65 | 65 | }); |
| 66 | 66 | cookie = session.headers.get("set-cookie").split(";")[0]; |
| 67 | 新增: const headers = { Origin: origin, Cookie: cookie, "Content-Type": "application/json" }; | |
| 68 | 新增: const account = await (await fetch(origin + "/api/account", { headers })).json(); | |
| 69 | 新增: const password = "favorites-fixture-only"; | |
| 70 | 新增: const unlocked = await fetch(origin + "/api/account/" + (account.exists ? "unlock" : "create"), { | |
| 71 | 新增: method: "POST", headers, body: JSON.stringify({ username: "收藏测试", password, confirm_password: password }), | |
| 72 | 新增: }); | |
| 73 | 新增: assert.ok(unlocked.ok, "the isolated favorites fixture requires an unlocked local account"); | |
| 67 | 74 | } |
| 68 | 75 | try { |
| 69 | 76 | await start(); |
| @@ -246,7 +253,7 @@ try { | ||
| 246 | 253 | await panel |
| 247 | 254 | .getByRole("button", { name: "编辑收藏 待重试的收藏", exact: true }) |
| 248 | 255 | .click(); |
| 249 | 删除: await page.getByLabel("保存到收藏夹", { exact: true }).selectOption(""); | |
| 256 | 新增: await chooseInline(page.getByLabel("保存到收藏夹", { exact: true }), ""); | |
| 250 | 257 | await page.getByRole("button", { name: "保存", exact: true }).click(); |
| 251 | 258 | await page |
| 252 | 259 | .getByRole("dialog", { name: "编辑收藏", exact: true }) |
| @@ -256,9 +263,8 @@ try { | ||
| 256 | 263 | ); |
| 257 | 264 | assert.equal(saved.items[0].folder_id, ""); |
| 258 | 265 | await page.getByLabel("搜索收藏", { exact: true }).fill(""); |
| 259 | 删除: await page | |
| 260 | 删除: .getByLabel("筛选收藏夹", { exact: true }) | |
| 261 | 删除: .selectOption(saved.folders[0].id); | |
| 266 | 新增: await chooseInline(page | |
| 267 | 新增: .getByLabel("筛选收藏夹", { exact: true }), saved.folders[0].id); | |
| 262 | 268 | await page.getByRole("button", { name: "重命名收藏夹", exact: true }).click(); |
| 263 | 269 | await page.getByLabel("收藏名称", { exact: true }).fill("常用资料"); |
| 264 | 270 | await page.getByRole("button", { name: "保存", exact: true }).click(); |
| @@ -0,0 +1,112 @@ | ||
| 1 | 新增:// Runs the shipped UI and RFB client with isolated guest events and a recording | |
| 2 | 新增:// native clipboard bridge. It never reads or changes the system clipboard. | |
| 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 writes = []; | |
| 8 | 新增:const display = await startDisplay(process.env.CAGE_UI_URL || "http://127.0.0.1:5198"); | |
| 9 | 新增:const { browser, page, state, errors } = await createWorkbench({ | |
| 10 | 新增: mockWebSockets: false, url: display.url, | |
| 11 | 新增: nativeRequest: body => { if (body.action === "clipboardWrite") writes.push(body.text); return true; }, | |
| 12 | 新增:}); | |
| 13 | 新增:await page.addInitScript(() => { | |
| 14 | 新增: window.EventSource = class extends EventTarget { | |
| 15 | 新增: constructor() { super(); window.metadataEvents = this; queueMicrotask(() => this.onopen?.()); } | |
| 16 | 新增: close() {} | |
| 17 | 新增: }; | |
| 18 | 新增:}); | |
| 19 | 新增:const sendState = () => page.evaluate(snapshot => { | |
| 20 | 新增: window.metadataEvents.onmessage({ data: JSON.stringify(snapshot) }); | |
| 21 | 新增:}, { tabs: state.tabs, active: state.active, downloads: [], uploads: [] }); | |
| 22 | 新增:const copyContext = () => state.requests.filter(item => item.path === "/browser/copy-context").at(-1)?.body.context; | |
| 23 | 新增:const copy = (id, text, context = copyContext()) => page.evaluate(value => { | |
| 24 | 新增: window.metadataEvents.dispatchEvent(new MessageEvent("clipboard", { data: JSON.stringify(value) })); | |
| 25 | 新增:}, { id, text, context }); | |
| 26 | 新增:const clickCanvas = async () => { | |
| 27 | 新增: const prepared = page.waitForResponse("**/api/browser/copy-context"); | |
| 28 | 新增: await page.locator(".remote-canvas canvas").click({ position: { x: 50, y: 50 } }); | |
| 29 | 新增: await prepared; | |
| 30 | 新增:}; | |
| 31 | 新增:const settle = () => page.waitForTimeout(100); | |
| 32 | 新增:try { | |
| 33 | 新增: state.status.ready = state.status.vm_running = true; | |
| 34 | 新增: state.active = "first"; | |
| 35 | 新增: const favicon = await page.evaluate(() => { | |
| 36 | 新增: const canvas = document.createElement("canvas"); | |
| 37 | 新增: canvas.width = canvas.height = 32; | |
| 38 | 新增: canvas.getContext("2d").fillRect(0, 0, 32, 32); | |
| 39 | 新增: return canvas.toDataURL("image/png"); | |
| 40 | 新增: }); | |
| 41 | 新增: state.tabs = [ | |
| 42 | 新增: { id: "first", kind: "web", title: "First site", url: "https://example.test/first", favicon }, | |
| 43 | 新增: { id: "second", kind: "web", title: "Second site", url: "https://example.test/second", favicon: "" }, | |
| 44 | 新增: ]; | |
| 45 | 新增: const unexpected = []; | |
| 46 | 新增: page.on("request", request => { if (new URL(request.url()).origin !== display.url) unexpected.push(request.url()); }); | |
| 47 | 新增: await page.reload(); | |
| 48 | 新增: await page.getByRole("button", { name: "打开浏览器", exact: true }).click(); | |
| 49 | 新增: await page.getByText("正在连接画面", { exact: true }).waitFor({ state: "hidden" }); | |
| 50 | 新增: const canvas = page.locator(".remote-canvas canvas"); | |
| 51 | 新增: await canvas.waitFor(); | |
| 52 | 新增: await page.waitForFunction(() => document.querySelector('[role="tab"] .tab-favicon')?.naturalWidth === 32); | |
| 53 | 新增: await page.getByRole("button", { name: "搜索标签页", exact: true }).click(); | |
| 54 | 新增: assert.equal(await page.locator(".all-tabs-results .tab-favicon").count(), 1); | |
| 55 | 新增: await page.keyboard.press("Escape"); | |
| 56 | 新增: | |
| 57 | 新增: await clickCanvas(); | |
| 58 | 新增: display.clipboard("unrelated guest update"); | |
| 59 | 新增: await settle(); | |
| 60 | 新增: assert.deepEqual(writes, [], "ordinary clicks must not authorize RFB clipboard writes"); | |
| 61 | 新增: await copy("first", "复制按钮的文字🙂"); | |
| 62 | 新增: await page.getByText("已复制到本机", { exact: true }).waitFor(); | |
| 63 | 新增: assert.deepEqual(writes, ["复制按钮的文字🙂"]); | |
| 64 | 新增: | |
| 65 | 新增: await page.getByRole("textbox", { name: "网页地址或搜索" }).click(); | |
| 66 | 新增: await copy("first", "late local input"); | |
| 67 | 新增: await settle(); | |
| 68 | 新增: assert.equal(writes.length, 1); | |
| 69 | 新增: await page.getByRole("tab", { name: "Second site", exact: true }).click(); | |
| 70 | 新增: await clickCanvas(); | |
| 71 | 新增: await copy("first", "late previous tab"); | |
| 72 | 新增: await settle(); | |
| 73 | 新增: assert.equal(writes.length, 1); | |
| 74 | 新增: await copy("second", "当前标签"); | |
| 75 | 新增: await settle(); | |
| 76 | 新增: assert.equal(writes.at(-1), "当前标签"); | |
| 77 | 新增: const oldContext = copyContext(); | |
| 78 | 新增: await page.getByRole("tab", { name: "First site", exact: true }).click(); | |
| 79 | 新增: await clickCanvas(); | |
| 80 | 新增: await page.getByRole("tab", { name: "Second site", exact: true }).click(); | |
| 81 | 新增: await clickCanvas(); | |
| 82 | 新增: assert.notEqual(copyContext(), oldContext); | |
| 83 | 新增: await copy("second", "late copy after tab round-trip", oldContext); | |
| 84 | 新增: await settle(); | |
| 85 | 新增: assert.equal(writes.length, 2); | |
| 86 | 新增: | |
| 87 | 新增: state.tabs[0].url += "#route"; | |
| 88 | 新增: await sendState(); | |
| 89 | 新增: assert.equal(await page.getByRole("tab", { name: "First site", exact: true }).locator("img").count(), 1); | |
| 90 | 新增: state.tabs[0].favicon = "data:image/png;base64,aW52YWxpZA=="; | |
| 91 | 新增: await sendState(); | |
| 92 | 新增: await page.getByRole("tab", { name: "First site", exact: true }).locator("img").waitFor({ state: "detached" }); | |
| 93 | 新增: state.tabs[0].favicon = "https://third-party.test/icon.png"; | |
| 94 | 新增: await sendState(); | |
| 95 | 新增: assert.equal(await page.getByRole("tab", { name: "First site", exact: true }).locator("img").count(), 0); | |
| 96 | 新增: await page.getByRole("button", { name: "工作台", exact: true }).click(); | |
| 97 | 新增: await copy("second", "hidden view"); | |
| 98 | 新增: await settle(); | |
| 99 | 新增: assert.equal(writes.length, 2); | |
| 100 | 新增: await page.getByRole("button", { name: "打开浏览器", exact: true }).click(); | |
| 101 | 新增: await page.getByText("正在连接画面", { exact: true }).waitFor({ state: "hidden" }); | |
| 102 | 新增: await clickCanvas(); | |
| 103 | 新增: await copy("second", "late copy after reconnect", oldContext); | |
| 104 | 新增: await settle(); | |
| 105 | 新增: assert.equal(writes.length, 2); | |
| 106 | 新增: assert.deepEqual(unexpected, []); | |
| 107 | 新增: assert.deepEqual(errors, []); | |
| 108 | 新增: console.log("PASS: tab/search favicons, SPA retention, broken icon fallback, no host icon requests, explicit copy events, unrelated RFB rejection, local focus/tab/hidden-view isolation"); | |
| 109 | 新增:} finally { | |
| 110 | 新增: await browser.close(); | |
| 111 | 新增: await display.close(); | |
| 112 | 新增:} | |
| @@ -1,7 +1,7 @@ | ||
| 1 | 1 | import assert from "node:assert/strict"; |
| 2 | 2 | import fs from "node:fs/promises"; |
| 3 | 3 | import { fileURLToPath } from "node:url"; |
| 4 | 删除:import { createWorkbench } from "./workbench-fixture.mjs"; | |
| 4 | 新增:import { chooseInline, createWorkbench } from "./workbench-fixture.mjs"; | |
| 5 | 5 | import { |
| 6 | 6 | presets, |
| 7 | 7 | themeCatalog, |
| @@ -34,11 +34,10 @@ const saved = () => | ||
| 34 | 34 | .filter({ hasText: "更改自动保存,即时生效" }) |
| 35 | 35 | .waitFor(); |
| 36 | 36 | const select = async (variant, id) => { |
| 37 | 删除: await page | |
| 37 | 新增: await chooseInline(page | |
| 38 | 38 | .getByLabel((variant === "light" ? "浅色" : "深色") + "主题预设", { |
| 39 | 39 | exact: true, |
| 40 | 删除: }) | |
| 41 | 删除: .selectOption(id); | |
| 40 | 新增: }), id); | |
| 42 | 41 | await saved(); |
| 43 | 42 | }; |
| 44 | 43 | const shot = async (name) => { |
| @@ -56,11 +55,14 @@ try { | ||
| 56 | 55 | (variant === "light" ? "浅色" : "深色") + "主题预设", |
| 57 | 56 | { exact: true }, |
| 58 | 57 | ); |
| 59 | 删除: assert.equal(await picker.locator("optgroup").count(), 4); | |
| 58 | 新增: await picker.click(); | |
| 59 | 新增: const list = page.getByRole("listbox"); | |
| 60 | 新增: assert.equal(await list.locator(".inline-select-group").count(), 4); | |
| 60 | 61 | assert.equal( |
| 61 | 删除: await picker.locator("option").count(), | |
| 62 | 新增: await list.getByRole("option").count(), | |
| 62 | 63 | Object.keys(presets[variant]).length, |
| 63 | 64 | ); |
| 65 | 新增: await picker.press("Escape"); | |
| 64 | 66 | // Every palette goes through the real picker, not just the model helper. |
| 65 | 67 | for (const id of Object.keys(presets[variant])) { |
| 66 | 68 | await select(variant, id); |
| @@ -146,11 +148,11 @@ try { | ||
| 146 | 148 | await page.reload(); |
| 147 | 149 | await open(); |
| 148 | 150 | assert.equal( |
| 149 | 删除: await page.getByLabel("浅色主题预设", { exact: true }).inputValue(), | |
| 151 | 新增: await page.getByLabel("浅色主题预设", { exact: true }).getAttribute("value"), | |
| 150 | 152 | "color-vision", |
| 151 | 153 | ); |
| 152 | 154 | assert.equal( |
| 153 | 删除: await page.getByLabel("已保存的主题", { exact: true }).inputValue(), | |
| 155 | 新增: await page.getByLabel("已保存的主题", { exact: true }).getAttribute("value"), | |
| 154 | 156 | state.appearance.customThemes[0].id, |
| 155 | 157 | ); |
| 156 | 158 | assert.ok(sameTheme(state.appearance, snapshot)); |
| @@ -173,7 +175,7 @@ try { | ||
| 173 | 175 | .getByRole("button", { name: "新建终端", exact: true }) |
| 174 | 176 | .first() |
| 175 | 177 | .click(); |
| 176 | 删除: await page.getByRole("button", { name: "新建普通终端", exact: true }).click(); | |
| 178 | 新增: await page.getByRole("menuitem", { name: "普通终端", exact: true }).click(); | |
| 177 | 179 | await page.getByRole("tab", { name: "终端 1", exact: true }).waitFor(); |
| 178 | 180 | await page.waitForFunction( |
| 179 | 181 | () => |
| @@ -0,0 +1,415 @@ | ||
| 1 | 新增:import assert from "node:assert/strict"; | |
| 2 | 新增:import { readFile } from "node:fs/promises"; | |
| 3 | 新增:import { createWorkbench } from "./workbench-fixture.mjs"; | |
| 4 | 新增: | |
| 5 | 新增:// Drives the shared workbench with an isolated account registry. No real credentials or VM. | |
| 6 | 新增:const { browser, page, state, errors } = await createWorkbench(); | |
| 7 | 新增:const profiles = []; | |
| 8 | 新增:const starts = []; | |
| 9 | 新增:let assignedProfile = 0; | |
| 10 | 新增:let failRefresh = false; | |
| 11 | 新增:let accountRequests = 0; | |
| 12 | 新增:const usageRequests = []; | |
| 13 | 新增:let heldRefresh = null; | |
| 14 | 新增:let offlineUsage = false; | |
| 15 | 新增:let panelWorker = false; | |
| 16 | 新增:let usageUnavailable = ""; | |
| 17 | 新增:let defaultLogin = null; | |
| 18 | 新增:let detectionError = ""; | |
| 19 | 新增:let lastLoginNotice = ""; | |
| 20 | 新增:const joins = []; | |
| 21 | 新增:const now = Math.floor(Date.now() / 1000); | |
| 22 | 新增:const openAccounts = async () => { | |
| 23 | 新增: await page.getByRole("button", { name: "设置", exact: true }).click(); | |
| 24 | 新增: await page.getByRole("button", { name: "Claude 账号", exact: true }).click(); | |
| 25 | 新增:}; | |
| 26 | 新增: | |
| 27 | 新增:async function checkLongAccountList() { | |
| 28 | 新增: const total = 40; | |
| 29 | 新增: for (let number = profiles.length + 1; number <= total; number++) { | |
| 30 | 新增: profiles.push({ | |
| 31 | 新增: id: "profile-" + number, label: "测试账号 " + number, enabled: true, status: "ready", | |
| 32 | 新增: email: `user.${number}@example.test`, plan: "Pro", | |
| 33 | 新增: quota: { observed_at: now, five_hour: { used_percentage: 28, resets_at: now + 6000 }, | |
| 34 | 新增: seven_day: { used_percentage: 64, resets_at: now + 200000 } }, | |
| 35 | 新增: }); | |
| 36 | 新增: } | |
| 37 | 新增: await openAccounts(); | |
| 38 | 新增: const list = page.getByRole("region", { name: "账号列表", exact: true }); | |
| 39 | 新增: const last = list.getByRole("article", { name: "测试账号 " + total, exact: true }); | |
| 40 | 新增: await last.waitFor({ state: "attached" }); | |
| 41 | 新增: assert.equal(await list.getByRole("article").count(), total); | |
| 42 | 新增: const header = page.getByRole("heading", { name: "Claude 账号", exact: true }); | |
| 43 | 新增: const add = page.getByRole("button", { name: "登录新账号", exact: true }); | |
| 44 | 新增: const headerY = (await header.boundingBox()).y; | |
| 45 | 新增: const addY = (await add.boundingBox()).y; | |
| 46 | 新增: assert.ok(headerY >= 0 && addY >= 0); | |
| 47 | 新增: assert.ok(await list.evaluate((el) => el.scrollHeight > el.clientHeight * 2 && el.clientHeight > 0)); | |
| 48 | 新增: await list.hover(); | |
| 49 | 新增: await page.mouse.wheel(0, 640); | |
| 50 | 新增: await page.waitForFunction((el) => el.scrollTop > 0, await list.elementHandle()); | |
| 51 | 新增: assert.ok(Math.abs((await header.boundingBox()).y - headerY) <= 1, "scrolling must not move the panel title"); | |
| 52 | 新增: assert.ok(Math.abs((await add.boundingBox()).y - addY) <= 1, "the add action must stay in view"); | |
| 53 | 新增: | |
| 54 | 新增: await add.focus(); | |
| 55 | 新增: const reachableControls = await list.locator("button:not(:disabled),input:not(:disabled),[tabindex='0']").count(); | |
| 56 | 新增: // On macOS, WebKit's all-controls traversal uses Option-Tab. | |
| 57 | 新增: const nextControl = process.platform === "darwin" && browser.browserType().name() === "webkit" ? "Alt+Tab" : "Tab"; | |
| 58 | 新增: let reached = false; | |
| 59 | 新增: for (let step = 0; step < reachableControls + 5; step++) { | |
| 60 | 新增: await page.keyboard.press(nextControl); | |
| 61 | 新增: if (await last.evaluate((row) => row.contains(document.activeElement))) { | |
| 62 | 新增: reached = true; | |
| 63 | 新增: break; | |
| 64 | 新增: } | |
| 65 | 新增: } | |
| 66 | 新增: assert.ok(reached, "tab navigation must reach a control in the last account"); | |
| 67 | 新增: const visibleFocus = await list.evaluate((el) => { | |
| 68 | 新增: const focused = document.activeElement.getBoundingClientRect(); | |
| 69 | 新增: const viewport = el.getBoundingClientRect(); | |
| 70 | 新增: return focused.top >= viewport.top - 1 && focused.bottom <= viewport.bottom + 1; | |
| 71 | 新增: }); | |
| 72 | 新增: assert.ok(visibleFocus, "the account list must scroll the focused control into view"); | |
| 73 | 新增: assert.ok(Math.abs((await add.boundingBox()).y - addY) <= 1); | |
| 74 | 新增: | |
| 75 | 新增: for (const width of [1280, 520, 375]) { | |
| 76 | 新增: await page.setViewportSize({ width, height: 700 }); | |
| 77 | 新增: const bounds = await list.evaluate((el) => ({ scroll: el.scrollWidth, client: el.clientWidth, | |
| 78 | 新增: document: document.documentElement.scrollWidth, viewport: window.innerWidth })); | |
| 79 | 新增: assert.ok(bounds.scroll <= bounds.client + 1 && bounds.document <= bounds.viewport + 1, | |
| 80 | 新增: `the account list must fit a ${width}px viewport horizontally: ${JSON.stringify(bounds)}`); | |
| 81 | 新增: const first = await last.getByRole("progressbar", { name: "5h 已用额度" }).boundingBox(); | |
| 82 | 新增: const second = await last.getByRole("progressbar", { name: "7d 已用额度" }).boundingBox(); | |
| 83 | 新增: assert.ok(first.width > 0 && Math.abs(first.x - second.x) <= 1 && Math.abs(first.width - second.width) <= 1, | |
| 84 | 新增: "5h and 7d progress bars must start and end at the same horizontal positions"); | |
| 85 | 新增: assert.ok(first.y + first.height <= second.y, "the two limits occupy separate rows"); | |
| 86 | 新增: } | |
| 87 | 新增: await page.getByRole("button", { name: "返回工作台", exact: true }).click(); | |
| 88 | 新增: await page.setViewportSize({ width: 1280, height: 850 }); | |
| 89 | 新增:} | |
| 90 | 新增: | |
| 91 | 新增:async function checkLocalCountdown() { | |
| 92 | 新增: const frozen = new Date("2030-01-01T08:00:00Z"); | |
| 93 | 新增: await page.clock.install({ time: new Date(+frozen - 60_000) }); | |
| 94 | 新增: await page.reload(); | |
| 95 | 新增: await page.getByRole("tab", { name: "终端 4 · 工作", exact: true }).waitFor(); | |
| 96 | 新增: await page.clock.pauseAt(frozen); | |
| 97 | 新增: const seconds = +frozen / 1000; | |
| 98 | 新增: profiles[0].quota = { observed_at: seconds, five_hour: { used_percentage: 28, observed_at: seconds - 900, resets_at: seconds + 5 }, | |
| 99 | 新增: seven_day: { used_percentage: 64, observed_at: seconds, resets_at: seconds + 7200 } }; | |
| 100 | 新增: await openAccounts(); | |
| 101 | 新增: const row = page.getByRole("article", { name: "工作", exact: true }); | |
| 102 | 新增: await row.getByText("5秒后", { exact: true }).waitFor(); | |
| 103 | 新增: await page.getByText("正在请求账号用量…").waitFor({ state: "hidden" }); | |
| 104 | 新增: const requestsBefore = accountRequests; | |
| 105 | 新增: const wavesBefore = usageRequests.filter((r) => r.action === "usage_panel").length; | |
| 106 | 新增: await page.clock.runFor(2000); | |
| 107 | 新增: await row.getByText("3秒后", { exact: true }).waitFor(); | |
| 108 | 新增: await page.clock.runFor(3000); | |
| 109 | 新增: await row.getByText("等待更新", { exact: true }).waitFor(); | |
| 110 | 新增: assert.equal(await row.getByText("28%", { exact: true }).count(), 0, "expired quota cannot remain current"); | |
| 111 | 新增: const expired = row.getByRole("group", { name: "5h 额度" }); | |
| 112 | 新增: assert.equal(await expired.getByRole("progressbar").count(), 0); | |
| 113 | 新增: const history = expired.getByText(/^上次 28% ·/); | |
| 114 | 新增: assert.equal(await history.locator("time").getAttribute("datetime"), new Date((seconds - 900) * 1000).toISOString()); | |
| 115 | 新增: await row.getByText("64%", { exact: true }).waitFor(); | |
| 116 | 新增: assert.equal(accountRequests, requestsBefore, "countdown ticks and expiry must not poll the account API"); | |
| 117 | 新增: const joinedBefore = joins.length; | |
| 118 | 新增: defaultLogin = { identity: "fresh-session", email: "[email protected]", plan: "Pro" }; | |
| 119 | 新增: await page.clock.runFor(8000); | |
| 120 | 新增: await page.getByRole("article", { name: defaultLogin.email }).getByRole("button", { name: "加入调度" }).waitFor(); | |
| 121 | 新增: assert.equal(joins.length, joinedBefore, "discovering a new default identity during polling cannot enroll it"); | |
| 122 | 新增: assert.equal(usageRequests.filter((r) => r.action === "usage_panel").length, wavesBefore, "12-second panel polling cannot start another usage query"); | |
| 123 | 新增: assert.ok(usageRequests.some((r) => !r.action && r.visible), "a visible panel keeps the existing queue alive via GET"); | |
| 124 | 新增:} | |
| 125 | 新增: | |
| 126 | 新增:async function checkUsagePanel() { | |
| 127 | 新增: const profile = profiles[0]; | |
| 128 | 新增: const waves = () => usageRequests.filter((r) => r.action === "usage_panel").length; | |
| 129 | 新增: const before = waves(); | |
| 130 | 新增: panelWorker = true; | |
| 131 | 新增: await openAccounts(); | |
| 132 | 新增: const row = page.getByRole("article", { name: profile.label, exact: true }); | |
| 133 | 新增: await page.getByText("正在查询账号用量…", { exact: true }).waitFor(); | |
| 134 | 新增: profile.usage_checking = true; | |
| 135 | 新增: await row.getByText("正在查询额度…").waitFor(); | |
| 136 | 新增: assert.equal(waves(), before + 1, "opening the panel initiates one real usage request"); | |
| 137 | 新增: assert.equal(await row.getByRole("button", { name: "检查状态" }).isEnabled(), false); | |
| 138 | 新增: panelWorker = false; | |
| 139 | 新增: Object.assign(profile, { usage_checking: false, usage_status: "cached", usage_checked_at: now }); | |
| 140 | 新增: await row.getByText("本次只有缓存读数").waitFor(); | |
| 141 | 新增: await row.getByText("23%", { exact: true }).waitFor(); | |
| 142 | 新增: await row.getByText("历史读数", { exact: true }).waitFor(); | |
| 143 | 新增: await page.setViewportSize({ width: 375, height: 700 }); | |
| 144 | 新增: const list = page.getByRole("region", { name: "账号列表", exact: true }); | |
| 145 | 新增: assert.ok(await list.evaluate((el) => el.scrollWidth <= el.clientWidth + 1), "window history fits the narrow account list"); | |
| 146 | 新增: await page.setViewportSize({ width: 1280, height: 850 }); | |
| 147 | 新增: assert.equal(waves(), before + 1, "polling the completed query does not start another query"); | |
| 148 | 新增: const back = page.getByRole("button", { name: "返回工作台", exact: true }); | |
| 149 | 新增: await back.click(); | |
| 150 | 新增: offlineUsage = true; | |
| 151 | 新增: await openAccounts(); | |
| 152 | 新增: await row.getByText("环境离线,无法查询").waitFor(); | |
| 153 | 新增: await row.getByText("23%", { exact: true }).waitFor(); | |
| 154 | 新增: assert.equal(await row.getByRole("button", { name: "检查状态" }).isEnabled(), false); | |
| 155 | 新增: await back.click(); | |
| 156 | 新增: offlineUsage = false; | |
| 157 | 新增: usageUnavailable = "网络已暂停,恢复连接后可查询订阅额度"; | |
| 158 | 新增: await openAccounts(); | |
| 159 | 新增: await page.getByText(usageUnavailable).waitFor(); | |
| 160 | 新增: assert.equal(await row.getByRole("button", { name: "检查状态" }).isEnabled(), false); | |
| 161 | 新增: assert.equal(await page.getByRole("button", { name: "登录新账号", exact: true }).isEnabled(), true); | |
| 162 | 新增: await back.click(); | |
| 163 | 新增: usageUnavailable = ""; | |
| 164 | 新增: profile.usage_status = "not_applicable"; | |
| 165 | 新增: await openAccounts(); | |
| 166 | 新增: await row.getByText("当前登录不提供订阅额度").waitFor(); | |
| 167 | 新增: await row.getByText("历史读数", { exact: true }).waitFor(); | |
| 168 | 新增: await back.click(); | |
| 169 | 新增: // An upstream probe failure is also a normal panel response, distinct from an HTTP transport error. | |
| 170 | 新增: profile.usage_status = "error"; | |
| 171 | 新增: profile.usage_checked_at = now; | |
| 172 | 新增: await openAccounts(); | |
| 173 | 新增: await row.getByText("额度查询失败").waitFor(); | |
| 174 | 新增: const failedFive = row.getByRole("group", { name: "5h 额度" }); | |
| 175 | 新增: assert.equal(await failedFive.locator("time").getAttribute("datetime"), new Date((now - 3600) * 1000).toISOString()); | |
| 176 | 新增: const failedWeek = row.getByRole("group", { name: "7d 额度" }); | |
| 177 | 新增: assert.equal(await failedWeek.getByRole("progressbar").count(), 0); | |
| 178 | 新增: assert.equal(await failedWeek.getByText(/^上次 100% ·/).locator("time").getAttribute("datetime"), new Date((now - 7200) * 1000).toISOString()); | |
| 179 | 新增: await back.click(); | |
| 180 | 新增:} | |
| 181 | 新增:try { | |
| 182 | 新增: await page.route("**/api/claude-accounts*", async (route) => { | |
| 183 | 新增: accountRequests++; | |
| 184 | 新增: const body = route.request().postDataJSON(); | |
| 185 | 新增: usageRequests.push({ ...body, visible: new URL(route.request().url()).searchParams.get("panel") === "visible" }); | |
| 186 | 新增: if (body) assert.ok(["join", "update", "refresh", "cancel", "refresh_default", "usage_panel"].includes(body.action)); | |
| 187 | 新增: if (body?.action === "join") { | |
| 188 | 新增: joins.push(body); | |
| 189 | 新增: if (!defaultLogin || body.identity !== defaultLogin.identity) | |
| 190 | 新增: return route.fulfill({ status: 409, body: "普通终端登录已改变,请确认当前身份" }); | |
| 191 | 新增: profiles.push({ id: "default-" + defaultLogin.identity, source: "default", label: defaultLogin.email, | |
| 192 | 新增: email: defaultLogin.email, plan: defaultLogin.plan, enabled: true, status: "ready" }); | |
| 193 | 新增: } | |
| 194 | 新增: if (body?.action === "cancel") { | |
| 195 | 新增: const index = profiles.findIndex((profile) => profile.id === body.id); | |
| 196 | 新增: assert.equal(index, 0); | |
| 197 | 新增: profiles.splice(index, 1); | |
| 198 | 新增: } | |
| 199 | 新增: if (body?.action === "update") Object.assign(profiles.find((a) => a.id === body.id), | |
| 200 | 新增: body.label !== undefined ? { label: body.label } : { enabled: body.enabled }); | |
| 201 | 新增: if (body?.action === "refresh" && failRefresh) | |
| 202 | 新增: return route.fulfill({ status: 503, body: "暂时无法检查登录" }); | |
| 203 | 新增: if (body?.action === "refresh" && heldRefresh) await heldRefresh.promise; | |
| 204 | 新增: if (body?.action === "refresh_default") { | |
| 205 | 新增: assert.equal(body.identity, defaultLogin?.identity); | |
| 206 | 新增: Object.assign(defaultLogin, { usage_status: "unavailable", usage_checked_at: now }); | |
| 207 | 新增: } | |
| 208 | 新增: return route.fulfill({ json: { accounts: profiles, detection_status: offlineUsage ? "offline" : detectionError ? "unavailable" : defaultLogin ? "ready" : "signed_out", | |
| 209 | 新增: detected: !detectionError && defaultLogin && !profiles.some((p) => p.email === defaultLogin.email) ? defaultLogin : undefined, | |
| 210 | 新增: detection_error: detectionError, login_notice: lastLoginNotice, usage_panel_running: panelWorker, | |
| 211 | 新增: usage_unavailable_reason: usageUnavailable } }); | |
| 212 | 新增: }); | |
| 213 | 新增: await page.route("**/api/terminals", async (route) => { | |
| 214 | 新增: const body = route.request().postDataJSON(); | |
| 215 | 新增: if (!body) return route.fulfill({ json: state.terminals }); | |
| 216 | 新增: starts.push(body); | |
| 217 | 新增: if (body.kind === "claude" && profiles.length && !profiles[assignedProfile].enabled) | |
| 218 | 新增: return route.fulfill({ status: 409, body: "没有可用 Claude 账号" }); | |
| 219 | 新增: const terminal = { id: String(starts.length), title: "终端 " + starts.length, kind: body.kind, | |
| 220 | 新增: workspace: body.workspace, claude_account_id: body.kind === "claude-login" ? body.claude_account_id || "one" | |
| 221 | 新增: : body.kind === "claude" ? profiles[assignedProfile]?.id : undefined, | |
| 222 | 新增: claude_account_source: body.kind === "claude-login" ? "managed" : profiles[assignedProfile]?.source }; | |
| 223 | 新增: state.terminals.push(terminal); | |
| 224 | 新增: return route.fulfill({ json: terminal }); | |
| 225 | 新增: }); | |
| 226 | 新增: state.status.vm_running = state.status.ready = true; | |
| 227 | 新增: await page.reload(); | |
| 228 | 新增: await page.getByRole("button", { name: /^在 .* 新建终端$/ }).waitFor(); | |
| 229 | 新增: assert.equal(usageRequests.filter((r) => r.action === "usage_panel").length, 0, "launching the workbench must not query subscription usage"); | |
| 230 | 新增: const plus = page.getByRole("button", { name: /^在 .* 新建终端$/ }); | |
| 231 | 新增: const launchClaude = async () => { | |
| 232 | 新增: await plus.click(); | |
| 233 | 新增: await page.getByRole("menuitem", { name: "Claude 终端", exact: true }).press("Enter"); | |
| 234 | 新增: }; | |
| 235 | 新增: const back = () => page.getByRole("button", { name: "返回工作台", exact: true }).click(); | |
| 236 | 新增: const profileCard = (label) => page.getByRole("article", { name: label, exact: true }); | |
| 237 | 新增: const rename = async (before, label) => { | |
| 238 | 新增: const row = profileCard(before); | |
| 239 | 新增: await row.getByRole("button", { name: "修改 " + before + " 的备注" }).click(); | |
| 240 | 新增: await row.getByRole("textbox", { name: "账号备注" }).fill(label); | |
| 241 | 新增: await row.getByRole("button", { name: "保存备注" }).click(); | |
| 242 | 新增: }; | |
| 243 | 新增: | |
| 244 | 新增: // Records created by the previous version keep their recovery actions. | |
| 245 | 新增: profiles.push({ id: "legacy", label: "草稿", status: "pending", enabled: true }); | |
| 246 | 新增: await openAccounts(); | |
| 247 | 新增: const draft = profileCard("草稿"); | |
| 248 | 新增: await draft.getByRole("button", { name: "撤销添加" }).click(); | |
| 249 | 新增: const confirmation = page.getByRole("dialog", { name: "撤销添加「草稿」?" }); | |
| 250 | 新增: await confirmation.getByText(/沿用环境原有的登录/).waitFor(); | |
| 251 | 新增: await confirmation.getByRole("button", { name: "取消", exact: true }).click(); | |
| 252 | 新增: assert.equal(profiles.length, 1); | |
| 253 | 新增: await draft.getByRole("button", { name: "撤销添加" }).click(); | |
| 254 | 新增: await confirmation.getByRole("button", { name: "撤销添加", exact: true }).click(); | |
| 255 | 新增: await page.getByText("尚无已加入调度的账号。").waitFor(); | |
| 256 | 新增: await page.getByText(/普通终端尚未登录 Claude 订阅/).waitFor(); | |
| 257 | 新增: await back(); | |
| 258 | 新增: await launchClaude(); | |
| 259 | 新增: await page.getByRole("tab", { name: "终端 1", exact: true }).waitFor(); | |
| 260 | 新增: assert.deepEqual(starts[0], { workspace: state.settings.workspace, kind: "claude" }); | |
| 261 | 新增: | |
| 262 | 新增: await openAccounts(); | |
| 263 | 新增: assert.equal(await page.getByRole("textbox", { name: "账号名称" }).count(), 0); | |
| 264 | 新增: await page.getByRole("button", { name: "登录新账号", exact: true }).click(); | |
| 265 | 新增: await page.getByRole("tab", { name: "终端 2 · 新账号登录", exact: true }).waitFor(); | |
| 266 | 新增: assert.deepEqual(starts[1], { workspace: state.settings.workspace, kind: "claude-login" }); | |
| 267 | 新增: assert.equal(profiles.length, 0, "opening a login terminal must not create a pool account"); | |
| 268 | 新增: state.terminals[1].closed = true; | |
| 269 | 新增: const email = "[email protected]"; | |
| 270 | 新增: profiles.push({ id: "one", status: "ready", label: email, email, plan: "Pro", enabled: true, source: "managed", | |
| 271 | 新增: quota: { observed_at: now, five_hour: { used_percentage: 0, observed_at: now - 3600, resets_at: now + 3600 }, | |
| 272 | 新增: seven_day: { used_percentage: 100, observed_at: now - 7200, resets_at: now - 80 } } }); | |
| 273 | 新增: lastLoginNotice = "已加入 " + email; | |
| 274 | 新增: await openAccounts(); | |
| 275 | 新增: await page.getByText(lastLoginNotice).waitFor(); | |
| 276 | 新增: await rename(email, "工作"); | |
| 277 | 新增: let card = profileCard("工作"); | |
| 278 | 新增: await card.getByText("0%", { exact: true }).waitFor(); | |
| 279 | 新增: await card.getByText("历史读数", { exact: true }).waitFor(); | |
| 280 | 新增: await card.getByText("等待更新", { exact: true }).waitFor(); | |
| 281 | 新增: assert.equal(await card.getByRole("button", { name: "撤销添加" }).count(), 0); | |
| 282 | 新增: await card.getByRole("checkbox", { name: "参与自动分配" }).click(); | |
| 283 | 新增: await card.getByRole("checkbox", { checked: false }).waitFor(); | |
| 284 | 新增: failRefresh = true; | |
| 285 | 新增: await card.getByRole("button", { name: "检查状态" }).click(); | |
| 286 | 新增: await page.getByRole("alert").filter({ hasText: "暂时无法检查登录" }).waitFor(); | |
| 287 | 新增: await card.getByText("额度查询失败").waitFor(); | |
| 288 | 新增: await card.getByText("0%", { exact: true }).waitFor(); | |
| 289 | 新增: assert.equal(await card.getByRole("group", { name: "5h 额度" }).locator("time").getAttribute("datetime"), new Date((now - 3600) * 1000).toISOString()); | |
| 290 | 新增: assert.equal(await card.getByRole("group", { name: "7d 额度" }).getByText(/^上次 100% ·/).locator("time").getAttribute("datetime"), new Date((now - 7200) * 1000).toISOString()); | |
| 291 | 新增: failRefresh = false; | |
| 292 | 新增: heldRefresh = Promise.withResolvers(); | |
| 293 | 新增: await card.getByRole("button", { name: "检查状态" }).click(); | |
| 294 | 新增: await card.getByText("正在查询额度…").waitFor(); | |
| 295 | 新增: assert.equal(await card.getByRole("button", { name: "检查状态" }).isEnabled(), false); | |
| 296 | 新增: assert.deepEqual(usageRequests.filter((r) => r.action === "refresh").at(-1), { action: "refresh", id: "one", visible: false }); | |
| 297 | 新增: // A partial result with an unknown reset is usable without inventing a countdown. | |
| 298 | 新增: Object.assign(profiles[0], { usage_status: "partial", usage_checked_at: now, | |
| 299 | 新增: quota: { five_hour: { used_percentage: 23, observed_at: now - 3600, resets_at: 0 }, | |
| 300 | 新增: seven_day: { used_percentage: 100, observed_at: now - 7200, resets_at: now - 80 }, observed_at: now - 3600 } }); | |
| 301 | 新增: heldRefresh.resolve(); | |
| 302 | 新增: await card.getByText("本次只返回了部分额度").waitFor(); | |
| 303 | 新增: await card.getByText("23%", { exact: true }).waitFor(); | |
| 304 | 新增: await card.getByText(/^读取于 /).waitFor(); | |
| 305 | 新增: await card.getByText("重置时间未知", { exact: true }).waitFor(); | |
| 306 | 新增: const oldWeek = card.getByRole("group", { name: "7d 额度" }).getByText(/^上次 100% ·/); | |
| 307 | 新增: 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)); | |
| 309 | 新增: heldRefresh = null; | |
| 310 | 新增: await back(); | |
| 311 | 新增: await launchClaude(); | |
| 312 | 新增: await page.getByText("没有可用 Claude 账号", { exact: true }).waitFor(); | |
| 313 | 新增: assert.equal(await page.getByRole("tab", { name: /^终端 / }).count(), 2); | |
| 314 | 新增: await openAccounts(); | |
| 315 | 新增: await card.getByRole("checkbox", { name: "参与自动分配" }).click(); | |
| 316 | 新增: await card.getByRole("checkbox", { checked: true }).waitFor(); | |
| 317 | 新增: await back(); | |
| 318 | 新增: await launchClaude(); | |
| 319 | 新增: await page.getByRole("tab", { name: "终端 4 · 工作", exact: true }).waitFor(); | |
| 320 | 新增: await page.getByText("Claude · 工作", { exact: true }).waitFor(); | |
| 321 | 新增: assert.deepEqual(starts.at(-1), { workspace: state.settings.workspace, kind: "claude" }); | |
| 322 | 新增: | |
| 323 | 新增: const identityA = { identity: "a-in-org", email: "[email protected]", organization: "Org", plan: "Pro" }; | |
| 324 | 新增: defaultLogin = identityA; | |
| 325 | 新增: await openAccounts(); | |
| 326 | 新增: assert.equal(await card.getByRole("button", { name: "重新登录" }).isEnabled(), false); | |
| 327 | 新增: const detectedA = profileCard(identityA.email); | |
| 328 | 新增: await detectedA.getByText(/已发现,未加入/).waitFor(); | |
| 329 | 新增: const clawd = await readFile(new URL("../src/claude-account-crab.svg", import.meta.url), "utf8"); | |
| 330 | 新增: assert.ok(await detectedA.locator("img").evaluate(async (img, source) => { | |
| 331 | 新增: await img.decode(); | |
| 332 | 新增: const shape = (svg) => { | |
| 333 | 新增: const root = new DOMParser().parseFromString(svg, "image/svg+xml").documentElement; | |
| 334 | 新增: return [root.getAttribute("viewBox"), root.getAttribute("fill"), ...Array.from(root.querySelectorAll("path"), (p) => p.getAttribute("d"))]; | |
| 335 | 新增: }; | |
| 336 | 新增: const data = /^data:image\/svg\+xml(;base64)?,(.*)$/s.exec(img.currentSrc); | |
| 337 | 新增: const rendered = data ? data[1] ? atob(data[2]) : decodeURIComponent(data[2]) : await (await fetch(img.currentSrc)).text(); | |
| 338 | 新增: return img.naturalWidth > 0 && JSON.stringify(shape(rendered)) === JSON.stringify(shape(source)); | |
| 339 | 新增: }, clawd), "the detected account renders the same Clawd artwork as managed accounts"); | |
| 340 | 新增: assert.equal(await detectedA.getByRole("checkbox").count(), 0); | |
| 341 | 新增: await page.setViewportSize({ width: 375, height: 700 }); | |
| 342 | 新增: const panelList = page.getByRole("region", { name: "账号列表", exact: true }); | |
| 343 | 新增: assert.ok(await panelList.evaluate((el) => el.scrollWidth <= el.clientWidth + 1), "detected identities fit on a narrow screen"); | |
| 344 | 新增: await page.setViewportSize({ width: 1280, height: 850 }); | |
| 345 | 新增: assert.equal(profiles.length, 1, "detected identity is not in the pool"); | |
| 346 | 新增: await detectedA.getByRole("button", { name: "检查状态" }).click(); | |
| 347 | 新增: await detectedA.getByText("本次未返回额度").waitFor(); | |
| 348 | 新增: assert.equal(await detectedA.getByText("暂无读数", { exact: true }).count(), 2); | |
| 349 | 新增: assert.deepEqual(usageRequests.filter((r) => r.action === "refresh_default").at(-1), { action: "refresh_default", identity: identityA.identity, visible: false }); | |
| 350 | 新增: await detectedA.getByRole("button", { name: "加入调度" }).click(); | |
| 351 | 新增: await detectedA.getByText("普通终端账号", { exact: true }).waitFor(); | |
| 352 | 新增: assert.deepEqual(joins.at(-1), { action: "join", identity: identityA.identity }); | |
| 353 | 新增: assert.equal(await detectedA.getByRole("button", { name: /登录/ }).count(), 0); | |
| 354 | 新增: await rename(identityA.email, "个人"); | |
| 355 | 新增: await profileCard("个人").waitFor(); | |
| 356 | 新增: await rename("个人", ""); | |
| 357 | 新增: await profileCard(identityA.email).waitFor(); | |
| 358 | 新增: await rename(identityA.email, "个人"); | |
| 359 | 新增: await back(); | |
| 360 | 新增: assignedProfile = 1; | |
| 361 | 新增: await launchClaude(); | |
| 362 | 新增: await page.getByRole("tab", { name: "终端 5 · 个人", exact: true }).waitFor(); | |
| 363 | 新增: defaultLogin = { identity: "b-in-org", email: "[email protected]", plan: "Pro" }; | |
| 364 | 新增: profiles[1].status = "changed"; | |
| 365 | 新增: profiles[1].quota = null; | |
| 366 | 新增: await openAccounts(); | |
| 367 | 新增: const nextIdentity = profileCard(defaultLogin.email); | |
| 368 | 新增: await nextIdentity.getByText(/未加入/).waitFor(); | |
| 369 | 新增: await profileCard("个人").getByText(/请重新打开工作会话确认身份/).waitFor(); | |
| 370 | 新增: assert.equal(await nextIdentity.getByRole("checkbox").count(), 0); | |
| 371 | 新增: assert.equal(profiles[1].email, identityA.email); | |
| 372 | 新增: // Identity changes again while this stale B card remains visible. | |
| 373 | 新增: defaultLogin = { identity: "c-in-org", email: "[email protected]", plan: "Pro" }; | |
| 374 | 新增: await nextIdentity.getByRole("button", { name: "加入调度" }).click(); | |
| 375 | 新增: await page.getByRole("alert").filter({ hasText: "普通终端登录已改变" }).waitFor(); | |
| 376 | 新增: await profileCard(defaultLogin.email).getByText(/未加入/).waitFor(); | |
| 377 | 新增: assert.equal(joins.at(-1).identity, "b-in-org"); | |
| 378 | 新增: assert.equal(profiles.length, 2); | |
| 379 | 新增: await back(); | |
| 380 | 新增: // Re-authenticating A independently updates its registry entry, not the source of an existing terminal. | |
| 381 | 新增: Object.assign(profiles[1], { source: "managed", status: "ready" }); | |
| 382 | 新增: await openAccounts(); | |
| 383 | 新增: await profileCard("个人").getByText(/仍使用普通终端的登录/).waitFor(); | |
| 384 | 新增: await back(); | |
| 385 | 新增: await page.getByRole("tab", { name: "终端 5 · 个人", exact: true }).click(); | |
| 386 | 新增: await page.getByText("Claude · 个人(启动时账号)", { exact: true }).waitFor(); | |
| 387 | 新增: await page.getByRole("tab", { name: "终端 4 · 工作", exact: true }).click(); | |
| 388 | 新增: await page.getByText("Claude · 工作", { exact: true }).waitFor(); | |
| 389 | 新增: assert.equal(starts.length, 5, "changing the environment identity must never replay a session"); | |
| 390 | 新增: detectionError = "无法读取普通终端状态"; | |
| 391 | 新增: await openAccounts(); | |
| 392 | 新增: await page.getByRole("alert").filter({ hasText: detectionError }).waitFor(); | |
| 393 | 新增: assert.equal(await page.getByText(/普通终端尚未登录 Claude 订阅/).count(), 0); | |
| 394 | 新增: await back(); | |
| 395 | 新增: detectionError = ""; | |
| 396 | 新增: defaultLogin = null; | |
| 397 | 新增: await page.reload(); | |
| 398 | 新增: await page.getByRole("tab", { name: "终端 4 · 工作", exact: true }).waitFor(); | |
| 399 | 新增: await page.getByRole("tab", { name: "终端 5 · 个人", exact: true }).waitFor(); | |
| 400 | 新增: state.terminals.find((t) => t.id === "4").closed = true; | |
| 401 | 新增: await openAccounts(); | |
| 402 | 新增: await card.getByRole("checkbox", { name: "参与自动分配" }).click(); | |
| 403 | 新增: await card.getByRole("checkbox", { checked: false }).waitFor(); | |
| 404 | 新增: await card.getByRole("button", { name: "重新登录" }).click(); | |
| 405 | 新增: await page.getByRole("tab", { name: "终端 6 · 工作", exact: true }).waitFor(); | |
| 406 | 新增: assert.deepEqual(starts.at(-1), { workspace: state.settings.workspace, kind: "claude-login", claude_account_id: "one" }); | |
| 407 | 新增: assert.ok(!state.requests.some((r) => r.path.startsWith("/claude-desktop") && r.method === "POST")); | |
| 408 | 新增: await checkUsagePanel(); | |
| 409 | 新增: await checkLongAccountList(); | |
| 410 | 新增: await checkLocalCountdown(); | |
| 411 | 新增: assert.deepEqual(errors, []); | |
| 412 | 新增: console.log("Claude account UI: independent login, explicit default enrollment, identity change, quota, terminal affinity, accessible scrolling and countdown passed."); | |
| 413 | 新增:} finally { | |
| 414 | 新增: await browser.close(); | |
| 415 | 新增:} | |
| @@ -110,14 +110,14 @@ try { | ||
| 110 | 110 | ); |
| 111 | 111 | await page.getByRole("button", { name: /^在 .* 新建终端$/ }).click(); |
| 112 | 112 | await page |
| 113 | 删除: .getByRole("dialog") | |
| 114 | 删除: .getByText("claude --continue --model sonnet", { exact: true }) | |
| 113 | 新增: .getByRole("menu") | |
| 114 | 新增: .getByRole("menuitem", { name: "Claude 终端", exact: true }) | |
| 115 | 115 | .waitFor(); |
| 116 | 116 | await page.screenshot({ |
| 117 | 117 | path: fileURLToPath(new URL("terminal-choice.png", output)), |
| 118 | 118 | }); |
| 119 | 119 | await page |
| 120 | 删除: .getByRole("button", { name: "新建 Claude 终端", exact: true }) | |
| 120 | 新增: .getByRole("menuitem", { name: "Claude 终端", exact: true }) | |
| 121 | 121 | .click(); |
| 122 | 122 | const terminalRequests = () => |
| 123 | 123 | state.requests.filter( |
| @@ -137,7 +137,7 @@ try { | ||
| 137 | 137 | "reconnect must not relaunch Claude", |
| 138 | 138 | ); |
| 139 | 139 | await page.getByRole("button", { name: /^在 .* 新建终端$/ }).click(); |
| 140 | 删除: await page.getByRole("button", { name: "新建普通终端", exact: true }).click(); | |
| 140 | 新增: await page.getByRole("menuitem", { name: "普通终端", exact: true }).click(); | |
| 141 | 141 | assert.equal(terminalRequests().at(-1).body.kind, "shell"); |
| 142 | 142 | await page.setViewportSize({ width: 820, height: 558 }); |
| 143 | 143 | await page |
| @@ -6,8 +6,9 @@ import { createWorkbench } from "./workbench-fixture.mjs"; | ||
| 6 | 6 | const { browser, page, state, errors } = await createWorkbench(); |
| 7 | 7 | try { |
| 8 | 8 | await page.addInitScript(() => { |
| 9 | 删除: window.EventSource = class { | |
| 9 | 新增: window.EventSource = class extends EventTarget { | |
| 10 | 10 | constructor() { |
| 11 | 新增: super(); | |
| 11 | 12 | window.testBrowserEvents = this; |
| 12 | 13 | queueMicrotask(() => this.onopen?.()); |
| 13 | 14 | } |
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | import assert from "node:assert/strict"; |
| 2 | 2 | import fs from "node:fs/promises"; |
| 3 | 删除:import { createWorkbench } from "./workbench-fixture.mjs"; | |
| 3 | 新增:import { chooseInline, createWorkbench } from "./workbench-fixture.mjs"; | |
| 4 | 4 | import { startDisplay } from "./rfb-wire-fixture.mjs"; |
| 5 | 5 | |
| 6 | 6 | const display = await startDisplay(process.env.CAGE_UI_URL || "http://127.0.0.1:5198", { frameInterval: 1000 }); |
| @@ -8,6 +8,7 @@ const { browser, page, state, errors } = await createWorkbench({ | ||
| 8 | 8 | mockWebSockets: false, url: display.url, viewport: { width: 1100, height: 800 }, |
| 9 | 9 | }); |
| 10 | 10 | page.setDefaultTimeout(10000); |
| 11 | 新增:const output = process.env.CAGE_DISPLAY_REPORT || "/tmp/cage-display-resolution"; | |
| 11 | 12 | const requests = [], actions = []; |
| 12 | 13 | let failResize = false; |
| 13 | 14 | const desktop = { installed: true, running: true, managed: true, version: "fixture" }; |
| @@ -46,13 +47,33 @@ try { | ||
| 46 | 47 | await matched(); |
| 47 | 48 | const connections = display.stats.connections; |
| 48 | 49 | const selector = page.getByLabel("Desktop 显示大小", { exact: true }); |
| 49 | 删除: await selector.selectOption("1.25"); | |
| 50 | 新增: const screen = page.locator(".desktop-screen"); | |
| 51 | 新增: const toolbar = page.locator(".claude-desktop-toolbar"); | |
| 52 | 新增: const toolbarBefore = await toolbar.boundingBox(); | |
| 53 | 新增: const before = await screen.boundingBox(); | |
| 54 | 新增: await selector.click(); | |
| 55 | 新增: await fs.mkdir(output, { recursive: true }); | |
| 56 | 新增: await page.screenshot({ path: output + "/display-size-open.png" }); | |
| 57 | 新增: const options = page.getByRole("listbox"); | |
| 58 | 新增: const bounds = await options.boundingBox(); | |
| 59 | 新增: const trigger = await selector.boundingBox(); | |
| 60 | 新增: assert.equal(bounds.x, trigger.x); | |
| 61 | 新增: assert.ok(bounds.y >= trigger.y + trigger.height && bounds.y + bounds.height > before.y); | |
| 62 | 新增: assert.deepEqual(await toolbar.boundingBox(), toolbarBefore); | |
| 63 | 新增: assert.deepEqual(await screen.boundingBox(), before); | |
| 64 | 新增: await selector.press("Escape"); | |
| 65 | 新增: await options.waitFor({ state: "hidden" }); | |
| 66 | 新增: assert.deepEqual(await screen.boundingBox(), before); | |
| 67 | 新增: await selector.press("Enter"); | |
| 68 | 新增: await selector.press("ArrowDown"); | |
| 69 | 新增: await selector.press("ArrowDown"); | |
| 70 | 新增: await selector.press("Enter"); | |
| 50 | 71 | await matched(1.25); |
| 51 | 删除: await selector.selectOption("0.75"); | |
| 72 | 新增: await chooseInline(selector, "0.75"); | |
| 52 | 73 | await matched(0.75); |
| 53 | 74 | assert.equal(display.stats.connections, connections, "zoom must preserve the active RFB connection"); |
| 54 | 75 | failResize = true; |
| 55 | 删除: await selector.selectOption("1.1"); | |
| 76 | 新增: await chooseInline(selector, "1.1"); | |
| 56 | 77 | await page.getByRole("alert").filter({ hasText: "画面尺寸未能同步" }).waitFor(); |
| 57 | 78 | failResize = false; |
| 58 | 79 | await matched(1.1); |
| @@ -62,15 +83,13 @@ try { | ||
| 62 | 83 | await page.reload(); |
| 63 | 84 | await page.getByRole("button", { name: "Claude Desktop", exact: true }).click(); |
| 64 | 85 | await matched(1.1); |
| 65 | 删除: assert.equal(await selector.inputValue(), "1.1", "zoom preference must survive reload"); | |
| 66 | 删除: await selector.selectOption("1"); | |
| 86 | 新增: assert.equal(await selector.getAttribute("value"), "1.1", "zoom preference must survive reload"); | |
| 87 | 新增: await chooseInline(selector, "1"); | |
| 67 | 88 | await matched(); |
| 68 | 89 | await page.setViewportSize({ width: 820, height: 558 }); |
| 69 | 90 | await matched(); |
| 70 | 91 | assert.deepEqual(actions, [], "display changes must not restart the application"); |
| 71 | 92 | assert.deepEqual(errors, []); |
| 72 | 删除: const output = process.env.CAGE_DISPLAY_REPORT || "/tmp/cage-display-resolution"; | |
| 73 | 删除: await fs.mkdir(output, { recursive: true }); | |
| 74 | 93 | await page.screenshot({ path: `${output}/small-window.png` }); |
| 75 | 94 | await fs.writeFile(`${output}/result.json`, JSON.stringify({ requests, rfb: display.stats, actions, errors }, null, 2)); |
| 76 | 95 | console.log("PASS: real RFB framebuffer follows viewport, sidebar and zoom; failure recovery, persistence, small window, no application restart"); |
| @@ -16,7 +16,7 @@ const shot = (name) => | ||
| 16 | 16 | }); |
| 17 | 17 | try { |
| 18 | 18 | assert.equal( |
| 19 | 删除: await page.getByRole("button", { name: /^打开项目/ }).isDisabled(), | |
| 19 | 新增: await page.getByRole("button", { name: "添加项目", exact: true }).isDisabled(), | |
| 20 | 20 | true, |
| 21 | 21 | ); |
| 22 | 22 | assert.equal( |
| @@ -1,7 +1,7 @@ | ||
| 1 | 1 | import assert from "node:assert/strict"; |
| 2 | 2 | import fs from "node:fs/promises"; |
| 3 | 3 | import { fileURLToPath } from "node:url"; |
| 4 | 删除:import { createWorkbench } from "./workbench-fixture.mjs"; | |
| 4 | 新增:import { chooseInline, createWorkbench } from "./workbench-fixture.mjs"; | |
| 5 | 5 | |
| 6 | 6 | const output = new URL("../../docs/test-reports/2026-11-01-manual-region/", import.meta.url); |
| 7 | 7 | await fs.mkdir(output, { recursive: true }); |
| @@ -22,8 +22,8 @@ try { | ||
| 22 | 22 | assert.equal(await page.getByRole("switch").nth(0).isChecked(), false); |
| 23 | 23 | assert.equal(await page.getByRole("switch").nth(1).isChecked(), false); |
| 24 | 24 | await page.getByLabel("系统时区", { exact: true }).fill("Asia/Tokyo"); |
| 25 | 删除: await page.getByLabel("系统语言").selectOption("ja_JP.UTF-8"); | |
| 26 | 删除: await page.getByLabel("网页首选语言").selectOption("ja-JP"); | |
| 25 | 新增: await chooseInline(page.getByRole("combobox", { name: "系统语言", exact: true }), "ja_JP.UTF-8"); | |
| 26 | 新增: await chooseInline(page.getByRole("combobox", { name: "网页首选语言", exact: true }), "ja-JP"); | |
| 27 | 27 | await page.getByText("国家、城市限制仍须检测出口所在地。", { exact: false }).waitFor(); |
| 28 | 28 | await page.screenshot({ path: fileURLToPath(new URL("manual-settings.png", output)) }); |
| 29 | 29 | await page.getByRole("button", { name: "保存设置", exact: true }).click(); |
| @@ -38,8 +38,8 @@ try { | ||
| 38 | 38 | await page.getByRole("button", { name: /^设置/ }).click(); |
| 39 | 39 | await page.getByRole("button", { name: "时区与语言", exact: true }).click(); |
| 40 | 40 | assert.equal(await page.getByLabel("系统时区", { exact: true }).inputValue(), "Asia/Tokyo"); |
| 41 | 删除: assert.equal(await page.getByLabel("系统语言").inputValue(), "ja_JP.UTF-8"); | |
| 42 | 删除: assert.equal(await page.getByLabel("网页首选语言").inputValue(), "ja-JP"); | |
| 41 | 新增: assert.equal(await page.getByRole("combobox", { name: "系统语言", exact: true }).getAttribute("value"), "ja_JP.UTF-8"); | |
| 42 | 新增: assert.equal(await page.getByRole("combobox", { name: "网页首选语言", exact: true }).getAttribute("value"), "ja-JP"); | |
| 43 | 43 | assert.equal(await page.getByRole("switch").nth(0).isChecked(), false); |
| 44 | 44 | assert.equal(await page.getByRole("switch").nth(1).isChecked(), false); |
| 45 | 45 | assert.deepEqual(errors, []); |
| @@ -0,0 +1,135 @@ | ||
| 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 | 新增:const output = fileURLToPath(new URL("../../docs/test-reports/2026-11-05-password-vault/", import.meta.url)); | |
| 6 | 新增:await fs.mkdir(output, { recursive: true }); | |
| 7 | 新增:let clipboard = ""; | |
| 8 | 新增:const { browser, page, state, errors } = await createWorkbench({ nativeRequest: async ({ action, text }) => { | |
| 9 | 新增: if (action === "clipboardWrite") { clipboard = text; return true; } | |
| 10 | 新增: return null; | |
| 11 | 新增:} }); | |
| 12 | 新增:let entries = [], blocked = [], candidate = null, filled = null, sequence = 0; | |
| 13 | 新增:await page.route("**/api/vault**", async route => { | |
| 14 | 新增: const req = route.request(), input = req.method() === "POST" ? req.postDataJSON() : {}; | |
| 15 | 新增: if (!state.account.unlocked) return route.fulfill({ status: 423, body: "Cage 已锁定" }); | |
| 16 | 新增: const redacted = value => { const { password, ...rest } = value; return rest; }; | |
| 17 | 新增: if (new URL(req.url()).pathname === "/api/vault/browser") { | |
| 18 | 新增: if (input.action === "status") return route.fulfill({ json: { | |
| 19 | 新增: available: true, origin: "https://mail.example.test", document: "fixture-document", | |
| 20 | 新增: entries: entries.filter(e => e.origin === "https://mail.example.test").map(redacted), | |
| 21 | 新增: candidates: candidate ? [{ ...redacted(candidate), update: entries.some(e => e.origin === candidate.origin && e.username === candidate.username) }] : [], | |
| 22 | 新增: } }); | |
| 23 | 新增: if (input.action === "fill") { assert.equal(input.document, "fixture-document"); filled = input.id; } | |
| 24 | 新增: if (input.action === "save") { | |
| 25 | 新增: const existing = entries.find(e => e.origin === candidate.origin && e.username === candidate.username); | |
| 26 | 新增: if (existing) existing.password = candidate.password; | |
| 27 | 新增: else entries.push({ ...candidate, id: `saved-${++sequence}` }); | |
| 28 | 新增: candidate = null; | |
| 29 | 新增: } | |
| 30 | 新增: if (input.action === "never") { blocked.push(candidate.origin); candidate = null; } | |
| 31 | 新增: if (input.action === "dismiss") candidate = null; | |
| 32 | 新增: return route.fulfill({ json: { ok: true } }); | |
| 33 | 新增: } | |
| 34 | 新增: if (req.method() === "GET") return route.fulfill({ json: { entries: entries.map(redacted), blocked } }); | |
| 35 | 新增: if (input.action === "save") { | |
| 36 | 新增: const entry = input.entry; | |
| 37 | 新增: const existing = entries.find(e => e.id === entry.id); | |
| 38 | 新增: if (existing) Object.assign(existing, entry, { password: entry.password || existing.password }); | |
| 39 | 新增: else entries.push({ ...entry, id: `saved-${++sequence}` }); | |
| 40 | 新增: } | |
| 41 | 新增: if (input.action === "reveal") { | |
| 42 | 新增: if (input.account_password !== state.accountPassword) return route.fulfill({ status: 400, body: "密码不正确" }); | |
| 43 | 新增: return route.fulfill({ json: { password: entries.find(e => e.id === input.id).password } }); | |
| 44 | 新增: } | |
| 45 | 新增: if (input.action === "delete") entries = entries.filter(e => e.id !== input.id); | |
| 46 | 新增: if (input.action === "unblock") blocked = blocked.filter(e => e !== input.origin); | |
| 47 | 新增: return route.fulfill({ json: { ok: true } }); | |
| 48 | 新增:}); | |
| 49 | 新增:const settings = async () => { | |
| 50 | 新增: await page.getByRole("button", { name: "设置", exact: true }).click(); | |
| 51 | 新增: await page.getByRole("navigation", { name: "设置分组" }).getByRole("button", { name: "密码保险箱", exact: true }).click(); | |
| 52 | 新增: await page.getByRole("heading", { name: "密码保险箱", exact: true }).waitFor(); | |
| 53 | 新增:}; | |
| 54 | 新增:try { | |
| 55 | 新增: await settings(); | |
| 56 | 新增: await page.getByText("还没有保存密码", { exact: true }).waitFor(); | |
| 57 | 新增: await page.getByRole("button", { name: "添加密码", exact: true }).click(); | |
| 58 | 新增: await page.getByLabel("网站地址", { exact: true }).fill("https://mail.example.test"); | |
| 59 | 新增: await page.getByLabel("账号或邮箱").fill("[email protected]"); | |
| 60 | 新增: await page.getByLabel("网站密码", { exact: true }).fill("fixture-mail-secret"); | |
| 61 | 新增: await page.getByRole("button", { name: "保存记录", exact: true }).click(); | |
| 62 | 新增: await page.getByRole("status").filter({ hasText: "密码记录已保存" }).waitFor(); | |
| 63 | 新增: assert.equal(entries.length, 1); | |
| 64 | 新增: assert.equal(await page.getByText("fixture-mail-secret", { exact: true }).count(), 0); | |
| 65 | 新增: await page.getByRole("button", { name: "查看密码", exact: true }).click(); | |
| 66 | 新增: await page.getByLabel("Cage 账户密码", { exact: true }).fill("wrong-password"); | |
| 67 | 新增: await page.getByRole("button", { name: "验证并查看" }).click(); | |
| 68 | 新增: await page.getByRole("alert").filter({ hasText: "密码不正确" }).waitFor(); | |
| 69 | 新增: assert.equal(await page.getByLabel("已保存的网站密码").count(), 0); | |
| 70 | 新增: await page.getByLabel("Cage 账户密码", { exact: true }).fill(state.accountPassword); | |
| 71 | 新增: await page.getByRole("button", { name: "验证并查看" }).click(); | |
| 72 | 新增: await page.getByLabel("已保存的网站密码").waitFor(); | |
| 73 | 新增: assert.equal(await page.getByLabel("已保存的网站密码").textContent(), "fixture-mail-secret"); | |
| 74 | 新增: await page.getByRole("button", { name: "隐藏密码" }).click(); | |
| 75 | 新增: await page.getByRole("button", { name: "复制密码", exact: true }).click(); | |
| 76 | 新增: await page.getByLabel("Cage 账户密码", { exact: true }).fill(state.accountPassword); | |
| 77 | 新增: await page.getByRole("button", { name: "验证并复制" }).click(); | |
| 78 | 新增: await page.getByRole("status").filter({ hasText: "密码已复制" }).waitFor(); | |
| 79 | 新增: assert.equal(clipboard, "fixture-mail-secret"); | |
| 80 | 新增: await page.getByRole("button", { name: "编辑", exact: true }).click(); | |
| 81 | 新增: await page.getByLabel("账号或邮箱").fill("[email protected]"); | |
| 82 | 新增: await page.getByRole("button", { name: "保存记录", exact: true }).click(); | |
| 83 | 新增: await page.getByRole("status").filter({ hasText: "密码记录已保存" }).waitFor(); | |
| 84 | 新增: assert.equal(entries[0].password, "fixture-mail-secret"); | |
| 85 | 新增: await page.getByLabel("搜索网站或账号").fill("missing"); | |
| 86 | 新增: await page.getByText("没有找到匹配的账号").waitFor(); | |
| 87 | 新增: await page.getByLabel("搜索网站或账号").fill(""); | |
| 88 | 新增: await page.screenshot({ path: output + "vault-settings.png" }); | |
| 89 | 新增: await page.setViewportSize({ width: 820, height: 558 }); | |
| 90 | 新增: await page.screenshot({ path: output + "vault-settings-small.png" }); | |
| 91 | 新增: assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true); | |
| 92 | 新增: await page.getByRole("button", { name: "返回工作台", exact: true }).click(); | |
| 93 | 新增: state.status.ready = true; state.status.vm_running = true; | |
| 94 | 新增: state.tabs = [{ id: "web-vault", title: "邮箱", kind: "web", url: "https://mail.example.test/login" }]; state.active = "web-vault"; | |
| 95 | 新增: await page.reload(); | |
| 96 | 新增: await page.getByRole("button", { name: "打开浏览器", exact: true }).click(); | |
| 97 | 新增: await page.getByRole("button", { name: /密码 · 1 个账号/ }).waitFor(); | |
| 98 | 新增: const trigger = page.getByRole("button", { name: /密码 · 1 个账号/ }); | |
| 99 | 新增: const before = await page.locator(".browser-chrome").boundingBox(); | |
| 100 | 新增: await trigger.press("Enter"); | |
| 101 | 新增: const picker = page.getByRole("region", { name: "当前网站的密码" }); | |
| 102 | 新增: await picker.waitFor(); | |
| 103 | 新增: const after = await page.locator(".browser-chrome").boundingBox(); | |
| 104 | 新增: assert.ok(after.height > before.height + 60, "password picker did not occupy layout space"); | |
| 105 | 新增: await picker.getByRole("button", { name: /[email protected]/ }).focus(); | |
| 106 | 新增: await page.keyboard.press("Enter"); | |
| 107 | 新增: await page.getByRole("status").filter({ hasText: "已填写" }).waitFor(); | |
| 108 | 新增: assert.equal(filled, entries[0].id); | |
| 109 | 新增: await trigger.press("Escape"); | |
| 110 | 新增: await picker.waitFor({ state: "hidden" }); | |
| 111 | 新增: assert.equal(Math.round((await page.locator(".browser-chrome").boundingBox()).height), Math.round(before.height)); | |
| 112 | 新增: candidate = { id: "pending", tab: "web-vault", origin: "https://mail.example.test", username: "[email protected]", password: "new-fixture-secret" }; | |
| 113 | 新增: await page.getByText("更新此账号的密码?", { exact: true }).waitFor(); | |
| 114 | 新增: await page.screenshot({ path: output + "vault-save-prompt.png" }); | |
| 115 | 新增: await page.getByRole("button", { name: "更新密码", exact: true }).click(); | |
| 116 | 新增: await page.getByRole("status").filter({ hasText: "密码已保存" }).waitFor(); | |
| 117 | 新增: assert.equal(entries[0].password, "new-fixture-secret"); | |
| 118 | 新增: candidate = { id: "ignored", tab: "web-vault", origin: "https://mail.example.test", username: "other", password: "ignored" }; | |
| 119 | 新增: await page.getByRole("button", { name: "此网站不再提示", exact: true }).click(); | |
| 120 | 新增: await page.getByRole("status").filter({ hasText: "不再提示保存" }).waitFor(); | |
| 121 | 新增: await settings(); | |
| 122 | 新增: await page.getByRole("button", { name: "恢复提示", exact: true }).click(); | |
| 123 | 新增: await page.getByRole("status").filter({ hasText: "已恢复" }).waitFor(); | |
| 124 | 新增: assert.deepEqual(blocked, []); | |
| 125 | 新增: await page.getByRole("button", { name: "删除", exact: true }).click(); | |
| 126 | 新增: await page.getByRole("button", { name: "删除密码", exact: true }).click(); | |
| 127 | 新增: await page.getByText("还没有保存密码", { exact: true }).waitFor(); | |
| 128 | 新增: await page.getByRole("button", { name: "返回工作台", exact: true }).click(); | |
| 129 | 新增: await page.getByRole("button", { name: /^账户菜单,/ }).click(); | |
| 130 | 新增: await page.getByRole("menuitem", { name: /锁定 Cage/ }).click(); | |
| 131 | 新增: await page.getByRole("region", { name: "解锁 Cage", exact: true }).waitFor(); | |
| 132 | 新增: assert.equal(await page.locator(".vault-browser").count(), 0); | |
| 133 | 新增: assert.deepEqual(errors, []); | |
| 134 | 新增: console.log("PASS: vault UI CRUD, search, reauthentication, clipboard, inline keyboard picker, save/update/never, lock and small viewport"); | |
| 135 | 新增:} finally { await browser.close(); } | |
| @@ -63,7 +63,7 @@ try { | ||
| 63 | 63 | assert.equal(retries, 1); |
| 64 | 64 | await page.screenshot({ path: fileURLToPath(new URL("download-recovery.png", output)) }); |
| 65 | 65 | await page.getByRole("dialog", { name: "浏览器下载" }).getByRole("button", { name: "关闭面板" }).click(); |
| 66 | 删除: await page.getByRole("button", { name: "项目文件", exact: true }).click(); | |
| 66 | 新增: await page.getByRole("button", { name: "打开 默认工作区 的编辑器", exact: true }).click(); | |
| 67 | 67 | await page.getByRole("button", { name: "恢复编辑器", exact: true }).click(); |
| 68 | 68 | await page.getByRole("dialog", { name: "重启编辑器?" }).getByRole("button", { name: "重启编辑器", exact: true }).click(); |
| 69 | 69 | await page.getByText("编辑器已恢复", { exact: true }).waitFor(); |
| @@ -7,6 +7,7 @@ export async function startDisplay(upstream, { frameInterval = 50 } = {}) { | ||
| 7 | 7 | const stats = { connections: 0, closed: 0, frames: 0 }; |
| 8 | 8 | const sockets = new Set(); |
| 9 | 9 | const displays = new Set(); |
| 10 | 新增: const clipboardWriters = new Set(); | |
| 10 | 11 | let width = 640, height = 480; |
| 11 | 12 | const server = http.createServer((req, res) => { |
| 12 | 13 | if (req.url.startsWith("/api/")) { |
| @@ -35,6 +36,13 @@ export async function startDisplay(upstream, { frameInterval = 50 } = {}) { | ||
| 35 | 36 | if (header.length === 10) header.writeBigUInt64BE(BigInt(length), 2); |
| 36 | 37 | socket.write(Buffer.concat([header, payload])); |
| 37 | 38 | }; |
| 39 | 新增: const clipboard = (text) => { | |
| 40 | 新增: const bytes = Buffer.from(text, "latin1"), message = Buffer.alloc(8 + bytes.length); | |
| 41 | 新增: message[0] = 3; | |
| 42 | 新增: message.writeUInt32BE(bytes.length, 4); | |
| 43 | 新增: bytes.copy(message, 8); | |
| 44 | 新增: send(message); | |
| 45 | 新增: }; | |
| 38 | 46 | let wire = Buffer.alloc(0), rfb = Buffer.alloc(0), phase = 0, timer, frame; |
| 39 | 47 | const makeFrame = () => { |
| 40 | 48 | frame = Buffer.alloc(16 + width * height * 4); |
| @@ -52,6 +60,7 @@ export async function startDisplay(upstream, { frameInterval = 50 } = {}) { | ||
| 52 | 60 | if (phase === 0 && rfb.length >= 12) { rfb = rfb.subarray(12); phase = 1; send(Buffer.from([1, 1])); } |
| 53 | 61 | if (phase === 1 && rfb.length >= 1) { rfb = rfb.subarray(1); phase = 2; send(Buffer.alloc(4)); } |
| 54 | 62 | if (phase === 2 && rfb.length >= 1) { |
| 63 | 新增: rfb = rfb.subarray(1); | |
| 55 | 64 | phase = 3; |
| 56 | 65 | const name = Buffer.from("Cage test display"); |
| 57 | 66 | const init = Buffer.alloc(24 + name.length); |
| @@ -60,15 +69,41 @@ export async function startDisplay(upstream, { frameInterval = 50 } = {}) { | ||
| 60 | 69 | for (const offset of [8, 10, 12]) init.writeUInt16BE(255, offset); |
| 61 | 70 | init.set([16, 8, 0], 14); |
| 62 | 71 | init.writeUInt32BE(name.length, 20); name.copy(init, 24); send(init); |
| 72 | 新增: const fence = Buffer.alloc(9); | |
| 73 | 新增: fence[0] = 248; | |
| 74 | 新增: fence.writeUInt32BE(0x80000000, 4); | |
| 75 | 新增: send(fence); | |
| 63 | 76 | makeFrame(); |
| 64 | 77 | displays.add(resize); |
| 78 | 新增: clipboardWriters.add(clipboard); | |
| 65 | 79 | timer = setInterval(() => { |
| 66 | 80 | if (socket.writableLength > frame.length * 2) return; |
| 67 | 81 | frame.fill(stats.frames % 255, 16); |
| 68 | 82 | send(frame); stats.frames++; |
| 69 | 83 | }, frameInterval); |
| 70 | 84 | } |
| 71 | 删除: if (phase === 3) rfb = Buffer.alloc(0); | |
| 85 | 新增: while (phase === 3 && rfb.length) { | |
| 86 | 新增: const type = rfb[0]; | |
| 87 | 新增: let length = { 0: 20, 3: 10, 4: 8, 5: 6, 150: 10 }[type]; | |
| 88 | 新增: if (type === 2) { | |
| 89 | 新增: if (rfb.length < 4) return; | |
| 90 | 新增: length = 4 + 4 * rfb.readUInt16BE(2); | |
| 91 | 新增: } else if (type === 6) { | |
| 92 | 新增: if (rfb.length < 8) return; | |
| 93 | 新增: length = 8 + Math.abs(rfb.readInt32BE(4)); | |
| 94 | 新增: } else if (type === 248) { | |
| 95 | 新增: if (rfb.length < 9) return; | |
| 96 | 新增: length = 9 + rfb[8]; | |
| 97 | 新增: } | |
| 98 | 新增: if (!length) { socket.destroy(); return; } | |
| 99 | 新增: if (rfb.length < length) return; | |
| 100 | 新增: if (type === 248 && (rfb.readUInt32BE(4) & 0x80000000)) { | |
| 101 | 新增: const response = Buffer.from(rfb.subarray(0, length)); | |
| 102 | 新增: response.writeUInt32BE(rfb.readUInt32BE(4) & 3, 4); | |
| 103 | 新增: send(response); | |
| 104 | 新增: } | |
| 105 | 新增: rfb = rfb.subarray(length); | |
| 106 | 新增: } | |
| 72 | 107 | }; |
| 73 | 108 | socket.on("data", (data) => { |
| 74 | 109 | wire = Buffer.concat([wire, data]); |
| @@ -89,13 +124,14 @@ export async function startDisplay(upstream, { frameInterval = 50 } = {}) { | ||
| 89 | 124 | } |
| 90 | 125 | }); |
| 91 | 126 | socket.on("error", () => {}); |
| 92 | 删除: socket.on("close", () => { clearInterval(timer); displays.delete(resize); sockets.delete(socket); stats.closed++; }); | |
| 127 | 新增: socket.on("close", () => { clearInterval(timer); displays.delete(resize); clipboardWriters.delete(clipboard); sockets.delete(socket); stats.closed++; }); | |
| 93 | 128 | send(Buffer.from("RFB 003.008\n")); |
| 94 | 129 | }); |
| 95 | 130 | await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); |
| 96 | 131 | return { |
| 97 | 132 | url: `http://127.0.0.1:${server.address().port}`, |
| 98 | 133 | stats, |
| 134 | 新增: clipboard(text) { for (const write of clipboardWriters) write(text); }, | |
| 99 | 135 | resize(size) { width = size.width; height = size.height; for (const resize of displays) resize(); }, |
| 100 | 136 | close: async () => { |
| 101 | 137 | for (const socket of sockets) socket.destroy(); |
| @@ -0,0 +1,99 @@ | ||
| 1 | 新增:// Exercise the actual pointer paths in an isolated workbench. | |
| 2 | 新增:import assert from "node:assert/strict"; | |
| 3 | 新增:import { createWorkbench } from "./workbench-fixture.mjs"; | |
| 4 | 新增: | |
| 5 | 新增:const { page, state, browser, errors } = await createWorkbench(); | |
| 6 | 新增:try { | |
| 7 | 新增: await page.getByRole("button", { name: "启动 Cage 环境", exact: true }).click(); | |
| 8 | 新增: await page.getByRole("heading", { name: "Cage 环境已就绪" }).waitFor(); | |
| 9 | 新增: await page.getByRole("button", { name: "打开浏览器", exact: true }).click(); | |
| 10 | 新增: await page.getByRole("tablist", { name: "浏览器标签页" }).waitFor(); | |
| 11 | 新增: await page.getByRole("button", { name: "新建网页", exact: true }).click(); | |
| 12 | 新增: const workspace = page.locator("main.workspace"); | |
| 13 | 新增: const tabs = page.locator(".browser-tabs [role=tab]"); | |
| 14 | 新增: const first = state.tabs[0].id; | |
| 15 | 新增: const second = state.tabs[1].id; | |
| 16 | 新增: async function drag(tab, fraction, cancel = false) { | |
| 17 | 新增: await tab.click({ trial: true }); | |
| 18 | 新增: const from = await tab.boundingBox(); | |
| 19 | 新增: const to = await workspace.boundingBox(); | |
| 20 | 新增: await page.mouse.move(from.x + from.width / 2, from.y + from.height / 2); | |
| 21 | 新增: await page.mouse.down(); | |
| 22 | 新增: await page.mouse.move(to.x + fraction * to.width, to.y + to.height / 2, { steps: 6 }); | |
| 23 | 新增: await workspace.locator(fraction < 0.5 ? ".split-drop.split-left" : ".split-drop.split-right").waitFor(); | |
| 24 | 新增: if (cancel) await page.keyboard.press("Escape"); | |
| 25 | 新增: await page.mouse.up(); | |
| 26 | 新增: await workspace.locator(".split-drop").waitFor({ state: "hidden" }); | |
| 27 | 新增: } | |
| 28 | 新增: | |
| 29 | 新增: // Reordering inside the strip must still work independently of pane drops. | |
| 30 | 新增: await page.waitForFunction(() => { | |
| 31 | 新增: const list = [...document.querySelectorAll(".browser-tab")]; | |
| 32 | 新增: return list.length === 2 && list.every(tab => tab.getBoundingClientRect().width >= 100); | |
| 33 | 新增: }); | |
| 34 | 新增: const start = await tabs.first().boundingBox(); | |
| 35 | 新增: const end = await tabs.last().boundingBox(); | |
| 36 | 新增: await page.mouse.move(start.x + start.width / 2, start.y + start.height / 2); | |
| 37 | 新增: await page.mouse.down(); | |
| 38 | 新增: await page.mouse.move(end.x + end.width - 3, end.y + end.height / 2, { steps: 10 }); | |
| 39 | 新增: await page.mouse.up(); | |
| 40 | 新增: await page.waitForFunction(id => document.querySelector(".browser-tab").dataset.tabId === id, second); | |
| 41 | 新增: const firstTab = page.locator(`.browser-tab[data-tab-id="${first}"] [role=tab]`); | |
| 42 | 新增: await drag(firstTab, 0.25, true); | |
| 43 | 新增: assert.equal(await workspace.locator(".browser-header-cell").count(), 1); | |
| 44 | 新增: await drag(firstTab, 0.75); | |
| 45 | 新增: const cells = workspace.locator(".browser-header-cell"); | |
| 46 | 新增: const left = cells.first(), right = cells.last(); | |
| 47 | 新增: await right.locator(`[data-browser-tab="${first}"]`).waitFor(); | |
| 48 | 新增: await left.locator(`[data-browser-tab="${second}"]`).waitFor(); | |
| 49 | 新增: await workspace.locator(".remote-view:not(.concealed)").waitFor(); | |
| 50 | 新增: const surface = await workspace.locator(".remote-view:not(.concealed)").boundingBox(); | |
| 51 | 新增: const box = await workspace.boundingBox(); | |
| 52 | 新增: assert.equal(Math.round(surface.width), Math.round(box.width)); | |
| 53 | 新增: assert.ok(state.split.left === second && state.split.right === first); | |
| 54 | 新增: const leftAddress = left.getByRole("textbox", { name: "网页地址或搜索" }); | |
| 55 | 新增: await leftAddress.fill("https://example.com/left"); | |
| 56 | 新增: await leftAddress.press("Enter"); | |
| 57 | 新增: assert.equal(state.requests.filter(r => r.path === "/browser/navigate").at(-1).body.id, second); | |
| 58 | 新增: assert.equal(await right.getByRole("textbox", { name: "网页地址或搜索" }).inputValue(), state.tabs.find(t => t.id === first).url); | |
| 59 | 新增: await left.getByRole("button", { name: "退出分屏" }).click(); | |
| 60 | 新增: assert.equal(await tabs.count(), 2); | |
| 61 | 新增: await page.waitForFunction(() => document.querySelectorAll(".browser-header-cell").length === 1); | |
| 62 | 新增: | |
| 63 | 新增: await drag(firstTab, 0.25); | |
| 64 | 新增: await left.locator(`[data-browser-tab="${first}"]`).waitFor(); | |
| 65 | 新增: await page.locator(`.browser-tab[data-tab-id="${first}"] .tab-close`).click(); | |
| 66 | 新增: await page.waitForFunction(() => !document.querySelector(".workspace-split")); | |
| 67 | 新增: await page.setViewportSize({ width: 820, height: 558 }); | |
| 68 | 新增: const term = { id: "split-term", title: "分屏终端", workspace: state.settings.workspace }; | |
| 69 | 新增: state.terminals.push(term); | |
| 70 | 新增: const terminal = page.getByRole("tab", { name: term.title, exact: true }); | |
| 71 | 新增: await terminal.waitFor(); | |
| 72 | 新增: const connections = state.terminalConnections; | |
| 73 | 新增: await drag(terminal, 0.75); | |
| 74 | 新增: const terminalRight = workspace.locator(".terminal-lane.split-right:visible"); | |
| 75 | 新增: await terminalRight.getByText(term.title, { exact: true }).waitFor(); | |
| 76 | 新增: const browserBox = await workspace.locator(".browser-lane .browser-chrome").boundingBox(); | |
| 77 | 新增: const terminalBox = await terminalRight.locator("header").boundingBox(); | |
| 78 | 新增: assert.ok(browserBox.x + browserBox.width <= terminalBox.x + 1); | |
| 79 | 新增: assert.ok((await terminalRight.locator(".terminal-view").boundingBox()).y < | |
| 80 | 新增: (await workspace.locator(".browser-lane .remote-view").boundingBox()).y); | |
| 81 | 新增: await workspace.locator(".browser-chrome .address-bar input").click(); | |
| 82 | 新增: await terminalRight.locator("textarea.xterm-helper-textarea").click({ force: true }); | |
| 83 | 新增: assert.equal(await workspace.locator(".browser-chrome").count(), 1); | |
| 84 | 新增: assert.equal(state.terminalConnections, connections); | |
| 85 | 新增: const secondTerm = { ...term, id: "split-term-2", title: "第二个终端" }; | |
| 86 | 新增: state.terminals.push(secondTerm); | |
| 87 | 新增: const secondTerminal = page.getByRole("tab", { name: secondTerm.title, exact: true }); | |
| 88 | 新增: await secondTerminal.waitFor(); | |
| 89 | 新增: await drag(secondTerminal, 0.25); | |
| 90 | 新增: await workspace.locator(".terminal-lane.split-left:visible").getByText(secondTerm.title, { exact: true }).waitFor(); | |
| 91 | 新增: await terminalRight.getByText(term.title, { exact: true }).waitFor(); | |
| 92 | 新增: assert.equal(await workspace.getByRole("tablist").count(), 0); | |
| 93 | 新增: assert.equal(await workspace.locator(".terminal-chrome:visible").count(), 2); | |
| 94 | 新增: assert.equal(await workspace.locator(".terminal-view:not(.concealed)").count(), 2); | |
| 95 | 新增: assert.deepEqual(errors, []); | |
| 96 | 新增: console.log("Passed: cancel, left/right drops, pane focus, native split, independent headers and navigation, exit, close and terminal continuity"); | |
| 97 | 新增:} finally { | |
| 98 | 新增: await browser.close(); | |
| 99 | 新增:} | |
| @@ -0,0 +1,75 @@ | ||
| 1 | 新增:import assert from "node:assert/strict"; | |
| 2 | 新增:import { createWorkbench } from "./workbench-fixture.mjs"; | |
| 3 | 新增: | |
| 4 | 新增:for (const platform of ["MacIntel", "Win32", "Linux x86_64"]) { | |
| 5 | 新增: const writes = [], inputs = []; | |
| 6 | 新增: const { browser, page, errors } = await createWorkbench({ | |
| 7 | 新增: mockWebSockets: false, | |
| 8 | 新增: nativeRequest({ action, text }) { | |
| 9 | 新增: if (action === "clipboardWrite") writes.push(text); | |
| 10 | 新增: }, | |
| 11 | 新增: }); | |
| 12 | 新增: try { | |
| 13 | 新增: let terminalSocket; | |
| 14 | 新增: const interrupted = Promise.withResolvers(); | |
| 15 | 新增: await page.addInitScript((platform) => { | |
| 16 | 新增: Object.defineProperty(navigator, "platform", { value: platform }); | |
| 17 | 新增: }, platform); | |
| 18 | 新增: await page.routeWebSocket("**/api/**", (socket) => { | |
| 19 | 新增: if (!socket.url().includes("/terminals/")) return socket.close(); | |
| 20 | 新增: terminalSocket = socket; | |
| 21 | 新增: socket.onMessage((message) => { | |
| 22 | 新增: const { type, data } = JSON.parse(message); | |
| 23 | 新增: if (type === "input") { | |
| 24 | 新增: inputs.push(data); | |
| 25 | 新增: if (data === "\x03") interrupted.resolve(); | |
| 26 | 新增: } | |
| 27 | 新增: }); | |
| 28 | 新增: socket.send(Buffer.from("CopyMe1234\r\n$ ")); | |
| 29 | 新增: }); | |
| 30 | 新增: await page.reload(); | |
| 31 | 新增: await page.getByRole("button", { name: "启动 Cage 环境", exact: true }).click(); | |
| 32 | 新增: await page.getByRole("button", { name: "新建终端", exact: true }).first().click(); | |
| 33 | 新增: await page.getByRole("menuitem", { name: "普通终端", exact: true }).click(); | |
| 34 | 新增: const line = await page.locator(".xterm-rows").getByText("CopyMe1234", { exact: true }).first().boundingBox(); | |
| 35 | 新增: const drag = async () => { | |
| 36 | 新增: await page.mouse.move(line.x + 1, line.y + line.height / 2); | |
| 37 | 新增: await page.mouse.down(); | |
| 38 | 新增: await page.mouse.move(line.x + line.width * 0.6, line.y + line.height / 2, { steps: 5 }); | |
| 39 | 新增: await page.mouse.up(); | |
| 40 | 新增: }; | |
| 41 | 新增: const mac = platform === "MacIntel"; | |
| 42 | 新增: const copy = () => page.keyboard.press(mac ? "Meta+c" : "Control+Shift+C"); | |
| 43 | 新增: await drag(); | |
| 44 | 新增: await copy(); | |
| 45 | 新增: await page.getByText("已复制终端选中文本", { exact: true }).waitFor(); | |
| 46 | 新增: assert.deepEqual(writes, ["CopyMe"]); | |
| 47 | 新增: | |
| 48 | 新增: terminalSocket.send(Buffer.from("\x1b[?1002h\x1b[?1006h")); | |
| 49 | 新增: await page.locator(".xterm.enable-mouse-events").waitFor(); | |
| 50 | 新增: await drag(); | |
| 51 | 新增: await copy(); | |
| 52 | 新增: await page.getByText(new RegExp(`请按住 ${mac ? "Option" : "Shift"} 拖选文字`)).waitFor(); | |
| 53 | 新增: assert.deepEqual(writes, ["CopyMe"]); | |
| 54 | 新增: assert.ok(inputs.some(data => data.startsWith("\x1b[<"))); | |
| 55 | 新增: | |
| 56 | 新增: const previousInputs = inputs.length; | |
| 57 | 新增: const modifier = mac ? "Alt" : "Shift"; | |
| 58 | 新增: await page.keyboard.down(modifier); | |
| 59 | 新增: await drag(); | |
| 60 | 新增: await page.keyboard.up(modifier); | |
| 61 | 新增: await copy(); | |
| 62 | 新增: await page.getByText("已复制终端选中文本", { exact: true }).waitFor(); | |
| 63 | 新增: assert.deepEqual(writes, ["CopyMe", "CopyMe"]); | |
| 64 | 新增: assert.equal(inputs.length, previousInputs); | |
| 65 | 新增: await page.keyboard.press("Control+c"); | |
| 66 | 新增: await Promise.race([ | |
| 67 | 新增: interrupted.promise, | |
| 68 | 新增: new Promise((_, reject) => setTimeout(() => reject(new Error("Ctrl+C 未传给终端")), 3000).unref()), | |
| 69 | 新增: ]); | |
| 70 | 新增: assert.deepEqual(errors, []); | |
| 71 | 新增: console.log(`${platform}: drag selection, mouse tracking, clipboard shortcut and Ctrl+C passed`); | |
| 72 | 新增: } finally { | |
| 73 | 新增: await browser.close(); | |
| 74 | 新增: } | |
| 75 | 新增:} | |
| @@ -1,7 +1,7 @@ | ||
| 1 | 1 | import assert from "node:assert/strict"; |
| 2 | 2 | import fs from "node:fs/promises"; |
| 3 | 3 | import { fileURLToPath } from "node:url"; |
| 4 | 删除:import { createWorkbench } from "./workbench-fixture.mjs"; | |
| 4 | 新增:import { chooseInline, createWorkbench } from "./workbench-fixture.mjs"; | |
| 5 | 5 | import { |
| 6 | 6 | themeDocument, |
| 7 | 7 | parseThemeDocument, |
| @@ -158,9 +158,8 @@ try { | ||
| 158 | 158 | await page.getByLabel("浅色主题背景", { exact: true }).inputValue(), |
| 159 | 159 | "#fafafa", |
| 160 | 160 | ); |
| 161 | 删除: await page | |
| 162 | 删除: .getByLabel("已保存的主题", { exact: true }) | |
| 163 | 删除: .selectOption(second.id); | |
| 161 | 新增: await chooseInline(page | |
| 162 | 新增: .getByLabel("已保存的主题", { exact: true }), second.id); | |
| 164 | 163 | await saved(); |
| 165 | 164 | assert.equal( |
| 166 | 165 | await page.getByLabel("浅色主题背景", { exact: true }).inputValue(), |
| @@ -172,9 +171,8 @@ try { | ||
| 172 | 171 | .click(); |
| 173 | 172 | await saved(); |
| 174 | 173 | assert.equal(state.appearance.customThemes.length, 2); |
| 175 | 删除: await page | |
| 176 | 删除: .getByLabel("已保存的主题", { exact: true }) | |
| 177 | 删除: .selectOption(second.id); | |
| 174 | 新增: await chooseInline(page | |
| 175 | 新增: .getByLabel("已保存的主题", { exact: true }), second.id); | |
| 178 | 176 | await saved(); |
| 179 | 177 | page.once("dialog", (dialog) => dialog.dismiss()); |
| 180 | 178 | await page.getByRole("button", { name: "删除", exact: true }).click(); |
| @@ -233,6 +231,7 @@ try { | ||
| 233 | 231 | .getByRole("button", { name: "新建终端", exact: true }) |
| 234 | 232 | .first() |
| 235 | 233 | .click(); |
| 234 | 新增: await page.getByRole("menuitem", { name: "普通终端", exact: true }).click(); | |
| 236 | 235 | await page.getByRole("tab", { name: "终端 1", exact: true }).waitFor(); |
| 237 | 236 | await page.waitForFunction(() => |
| 238 | 237 | [...document.querySelectorAll(".xterm-scrollable-element")].some( |
| @@ -259,7 +259,11 @@ export async function createWorkbench({ | ||
| 259 | 259 | state.status.ready = false; |
| 260 | 260 | state.status.vm_running = false; |
| 261 | 261 | } else if (path === "/browser/tabs") |
| 262 | 删除: result = { tabs: state.tabs, active: state.active }; | |
| 262 | 新增: result = { tabs: state.tabs, active: state.active, split: state.split || null }; | |
| 263 | 新增: else if (path === "/browser/split") { | |
| 264 | 新增: state.split = body.left ? { left: body.left, right: body.right, fraction: 0.5 } : null; | |
| 265 | 新增: result = { split: state.split }; | |
| 266 | 新增: } | |
| 263 | 267 | else if (path === "/browser/events") |
| 264 | 268 | return route.fulfill({ |
| 265 | 269 | contentType: "text/event-stream", |
| @@ -339,3 +343,8 @@ export async function createWorkbench({ | ||
| 339 | 343 | if (!startupFailure) await page.getByRole("heading", { name: "先启动 Cage 环境" }).waitFor(); |
| 340 | 344 | return { browser, context, page, state, errors }; |
| 341 | 345 | } |
| 346 | 新增: | |
| 347 | 新增:export async function chooseInline(picker, value) { | |
| 348 | 新增: await picker.click(); | |
| 349 | 新增: await picker.locator("..").getByRole("option").and(picker.page().locator(`[data-value=${JSON.stringify(String(value))}]`)).click(); | |
| 350 | 新增:} | |
| @@ -21,6 +21,8 @@ const settings = async () => { | ||
| 21 | 21 | const tabs = () => page.getByRole("tablist", { name: "浏览器标签页" }); |
| 22 | 22 | try { |
| 23 | 23 | await shot("main"); |
| 24 | 新增: const navigation = page.getByRole("navigation", { name: "主导航" }); | |
| 25 | 新增: assert.equal(await navigation.getByRole("button", { name: /打开项目|项目文件/ }).count(), 0); | |
| 24 | 26 | await page |
| 25 | 27 | .getByRole("button", { name: "启动 Cage 环境", exact: true }) |
| 26 | 28 | .click(); |
| @@ -28,8 +30,7 @@ try { | ||
| 28 | 30 | .getByRole("heading", { name: "Cage 环境已就绪", exact: true }) |
| 29 | 31 | .waitFor(); |
| 30 | 32 | await page |
| 31 | 删除: .getByRole("navigation", { name: "主导航" }) | |
| 32 | 删除: .getByRole("button", { name: /^打开项目/ }) | |
| 33 | 新增: .getByRole("button", { name: "添加项目", exact: true }) | |
| 33 | 34 | .click(); |
| 34 | 35 | await page.getByRole("button", { name: "添加本机项目…", exact: true }).click(); |
| 35 | 36 | await page.waitForFunction( |
| @@ -96,10 +97,27 @@ try { | ||
| 96 | 97 | .getByRole("button", { name: "新建终端", exact: true }) |
| 97 | 98 | .first() |
| 98 | 99 | .click(); |
| 99 | 删除: await page.getByRole("button", { name: "新建普通终端", exact: true }).click(); | |
| 100 | 新增: await page.getByRole("menuitem", { name: "普通终端", exact: true }).click(); | |
| 100 | 101 | await page.getByRole("tab", { name: "终端 1", exact: true }).waitFor(); |
| 101 | 删除: await page.getByRole("button", { name: "管理 终端 1", exact: true }).click(); | |
| 102 | 删除: await page.getByRole("menuitem", { name: "重命名标签" }).click(); | |
| 102 | 新增: const terminalHeader = page.locator("header.chrome"); | |
| 103 | 新增: assert.equal(await terminalHeader.locator(".navigation-row").count(), 0); | |
| 104 | 新增: assert.equal(await terminalHeader.getByRole("button", { name: "新建终端", exact: true }).count(), 1); | |
| 105 | 新增: assert.equal(await terminalHeader.getByRole("button", { name: "design-lab", exact: true }).getAttribute("title"), state.chosenFolder); | |
| 106 | 新增: const terminalTab = page.getByRole("tab", { name: "终端 1", exact: true }); | |
| 107 | 新增: const actions = page.getByRole("group", { name: "终端 1 的操作", exact: true }); | |
| 108 | 新增: await terminalTab.hover(); | |
| 109 | 新增: await actions.waitFor(); | |
| 110 | 新增: await page.getByRole("button", { name: "工作台", exact: true }).hover(); | |
| 111 | 新增: await actions.waitFor({ state: "hidden" }); | |
| 112 | 新增: await terminalTab.focus(); | |
| 113 | 新增: await page.keyboard.press("Tab"); | |
| 114 | 新增: assert.equal(await page.locator(":focus").getAttribute("aria-label"), "置顶"); | |
| 115 | 新增: await page.keyboard.press("Enter"); | |
| 116 | 新增: await actions.getByRole("button", { name: "取消置顶", exact: true }).click(); | |
| 117 | 新增: const renameButton = actions.getByRole("button", { name: "重命名", exact: true }); | |
| 118 | 新增: await renameButton.hover(); | |
| 119 | 新增: await actions.getByText("重命名", { exact: true }).waitFor(); | |
| 120 | 新增: await renameButton.click(); | |
| 103 | 121 | await page.getByLabel("标签名称").fill("开发终端"); |
| 104 | 122 | await page.getByRole("button", { name: "保存名称" }).click(); |
| 105 | 123 | await page.getByRole("tab", { name: "开发终端" }).waitFor(); |
| @@ -114,7 +132,7 @@ try { | ||
| 114 | 132 | .click({ button: "right" }); |
| 115 | 133 | await page.getByRole("menuitem", { name: "置顶标签", exact: true }).click(); |
| 116 | 134 | assert.equal(await tabs().getByRole("tab").first().innerText(), "本地预览"); |
| 117 | 删除: await page.getByRole("button", { name: "项目文件", exact: true }).click(); | |
| 135 | 新增: await page.getByRole("button", { name: "打开 design-lab 的编辑器", exact: true }).click(); | |
| 118 | 136 | await page |
| 119 | 137 | .getByRole("tab", { name: "文件 · design-lab", exact: true }) |
| 120 | 138 | .waitFor(); |
| @@ -256,8 +274,7 @@ try { | ||
| 256 | 274 | await page.keyboard.press("Escape"); |
| 257 | 275 | await page.getByRole("button", { name: "放弃修改", exact: true }).click(); |
| 258 | 276 | await page |
| 259 | 删除: .getByRole("navigation", { name: "主导航" }) | |
| 260 | 删除: .getByRole("button", { name: /^打开项目/ }) | |
| 277 | 新增: .getByRole("button", { name: "添加项目", exact: true }) | |
| 261 | 278 | .click(); |
| 262 | 279 | await page.getByRole("button", { name: "添加本机项目…", exact: true }).click(); |
| 263 | 280 | await page |
| @@ -281,7 +298,7 @@ try { | ||
| 281 | 298 | await page |
| 282 | 299 | .getByRole("button", { name: "在 another-project 新建终端", exact: true }) |
| 283 | 300 | .click(); |
| 284 | 删除: await page.getByRole("button", { name: "新建普通终端", exact: true }).click(); | |
| 301 | 新增: await page.getByRole("menuitem", { name: "普通终端", exact: true }).click(); | |
| 285 | 302 | await page |
| 286 | 303 | .getByRole("region", { name: "项目 another-project", exact: true }) |
| 287 | 304 | .getByRole("tab", { name: "终端 2", exact: true }) |
| @@ -293,7 +310,7 @@ try { | ||
| 293 | 310 | await page |
| 294 | 311 | .getByRole("button", { name: "在 design-lab 新建终端", exact: true }) |
| 295 | 312 | .click(); |
| 296 | 删除: await page.getByRole("button", { name: "新建普通终端", exact: true }).click(); | |
| 313 | 新增: await page.getByRole("menuitem", { name: "普通终端", exact: true }).click(); | |
| 297 | 314 | await page |
| 298 | 315 | .getByRole("region", { name: "项目 design-lab", exact: true }) |
| 299 | 316 | .getByRole("tab", { name: "终端 3", exact: true }) |
| @@ -310,14 +327,30 @@ try { | ||
| 310 | 327 | 3, |
| 311 | 328 | ); |
| 312 | 329 | assert.equal(await tabs().getByRole("tab").count(), 2); |
| 313 | 删除: await page.getByRole("button", { name: "项目文件", exact: true }).click(); | |
| 330 | 新增: await page.getByRole("button", { name: "打开 another-project 的编辑器", exact: true }).click(); | |
| 331 | 新增: await tabs().getByRole("tab", { name: "文件 · another-project", exact: true }).waitFor(); | |
| 332 | 新增: await page.getByRole("button", { name: "打开 design-lab 的编辑器", exact: true }).click(); | |
| 314 | 333 | await tabs() |
| 315 | 334 | .getByRole("tab", { name: "文件 · design-lab", exact: true }) |
| 316 | 335 | .waitFor(); |
| 317 | 删除: assert.equal(state.tabs.filter((tab) => tab.kind === "editor").length, 1); | |
| 336 | 新增: assert.equal(state.tabs.filter((tab) => tab.kind === "editor").length, 2); | |
| 337 | 新增: assert.equal(state.tabs.find((tab) => tab.id === state.active)?.workspace, state.chosenFolder); | |
| 318 | 338 | checks.push( |
| 319 | 339 | "两个项目终端各自归组、指定目录新建不受最后打开项目影响、浏览器与终端保持运行", |
| 320 | 340 | ); |
| 341 | 新增: const deleteTab = page.getByRole("tab", { name: "终端 3", exact: true }); | |
| 342 | 新增: const remove = page.getByRole("group", { name: "终端 3 的操作" }).getByRole("button", { name: "删除" }); | |
| 343 | 新增: await deleteTab.hover(); | |
| 344 | 新增: await remove.click(); | |
| 345 | 新增: const confirmClose = page.getByRole("dialog", { name: "关闭这个终端会话?" }); | |
| 346 | 新增: await confirmClose.getByRole("button", { name: "取消" }).click(); | |
| 347 | 新增: assert.equal(state.terminals.length, 3); | |
| 348 | 新增: await deleteTab.hover(); | |
| 349 | 新增: await remove.click(); | |
| 350 | 新增: await confirmClose.getByRole("button", { name: "关闭终端" }).click(); | |
| 351 | 新增: await deleteTab.waitFor({ state: "detached" }); | |
| 352 | 新增: assert.equal(state.terminals.length, 2); | |
| 353 | 新增: checks.push("终端行悬停展开、键盘置顶、重命名、取消和确认删除指定终端"); | |
| 321 | 354 | await page.getByRole("button", { name: "工作台", exact: true }).click(); |
| 322 | 355 | await shot("main-minimum"); |
| 323 | 356 | await page.getByRole("button", { name: "收起侧栏", exact: true }).click(); |
| @@ -162,14 +162,13 @@ | ||
| 162 | 162 | object-fit: cover; |
| 163 | 163 | } |
| 164 | 164 | .account-menu-root { |
| 165 | 删除: position: relative; | |
| 166 | 删除: flex: 1; | |
| 167 | 删除: min-width: 0; | |
| 165 | 新增: display: contents; | |
| 168 | 166 | } |
| 169 | 167 | .account-trigger { |
| 170 | 168 | border: 0; |
| 171 | 169 | background: transparent; |
| 172 | 删除: width: 100%; | |
| 170 | 新增: flex: 1; | |
| 171 | 新增: min-width: 0; | |
| 173 | 172 | display: flex; |
| 174 | 173 | align-items: center; |
| 175 | 174 | gap: 10px; |
| @@ -201,17 +200,14 @@ | ||
| 201 | 200 | color: var(--muted); |
| 202 | 201 | } |
| 203 | 202 | .account-menu { |
| 204 | 删除: position: absolute; | |
| 205 | 删除: bottom: calc(100% + 8px); | |
| 206 | 删除: left: 0; | |
| 207 | 删除: width: 224px; | |
| 208 | 删除: max-width: calc(100vw - 32px); | |
| 209 | 删除: padding: 6px; | |
| 203 | 新增: order: -1; | |
| 204 | 新增: flex: 0 0 100%; | |
| 205 | 新增: max-height: min(40vh, 240px); | |
| 206 | 新增: overflow-y: auto; | |
| 207 | 新增: padding: 4px; | |
| 210 | 208 | border: 1px solid var(--line); |
| 211 | 删除: border-radius: 12px; | |
| 209 | 新增: border-radius: 7px; | |
| 212 | 210 | background: var(--paper); |
| 213 | 删除: box-shadow: 0 8px 24px #00000012; | |
| 214 | 删除: z-index: 60; | |
| 215 | 211 | } |
| 216 | 212 | .account-menu-label { |
| 217 | 213 | padding: 8px 10px; |
| @@ -225,6 +221,7 @@ | ||
| 225 | 221 | border-radius: 6px; |
| 226 | 222 | display: flex; |
| 227 | 223 | align-items: center; |
| 224 | 新增: justify-content: flex-start; | |
| 228 | 225 | gap: 10px; |
| 229 | 226 | text-align: left; |
| 230 | 227 | background: transparent; |
| @@ -322,3 +319,5 @@ | ||
| 322 | 319 | .account-device-option span { display: flex; flex-direction: column; gap: 6px; } |
| 323 | 320 | .account-device-option strong { font-size: 14px; font-weight: 550; } |
| 324 | 321 | .account-device-option small { color: var(--muted); font-size: 12px; line-height: 1.6; } |
| 322 | 新增: | |
| 323 | 新增:.account-trigger[aria-expanded="false"] > svg { transform: rotate(180deg); } | |
| @@ -9,14 +9,13 @@ import React, { | ||
| 9 | 9 | import { |
| 10 | 10 | Camera, |
| 11 | 11 | Check, |
| 12 | 删除: ChevronUp, | |
| 12 | 新增: ChevronDown, | |
| 13 | 13 | Eye, |
| 14 | 14 | EyeOff, |
| 15 | 15 | Fingerprint, |
| 16 | 16 | LockKeyhole, |
| 17 | 17 | LogOut, |
| 18 | 18 | Settings2, |
| 19 | 删除: UserRound, | |
| 20 | 19 | } from "lucide-react"; |
| 21 | 20 | import { api, native, nativeAvailable } from "./api"; |
| 22 | 21 | import logo from "./logo.png"; |
| @@ -213,7 +212,7 @@ export function AccountGate({ children }) { | ||
| 213 | 212 | setConfirmation(""); |
| 214 | 213 | if (creating && rememberLogin && deviceSupport?.supported) { |
| 215 | 214 | try { await deviceAction("enable", "automatic"); } |
| 216 | 删除: catch (e) { setDeviceNotice(`账户已创建,记住登录未能开启:${e.message}。可在账户设置重试。`); } | |
| 215 | 新增: catch (e) { setDeviceNotice(`账户已创建,记住登录未能开启:${e.message}。可在「设置 → 账户」中重试。`); } | |
| 217 | 216 | } |
| 218 | 217 | } catch (e) { |
| 219 | 218 | setError(e.message); |
| @@ -357,17 +356,20 @@ export function AccountMenu({ onSettings, onConfirm, onStatus, busy }) { | ||
| 357 | 356 | const root = useRef(); |
| 358 | 357 | useEffect(() => { |
| 359 | 358 | if (!open) return; |
| 359 | 新增: root.current.querySelector('[role="menuitem"]').focus(); | |
| 360 | 360 | const dismiss = (event) => { |
| 361 | 361 | if ( |
| 362 | 362 | event.key === "Escape" || |
| 363 | 删除: (event.type === "pointerdown" && !root.current?.contains(event.target)) | |
| 364 | 删除: ) | |
| 363 | 新增: (event.type === "click" && !root.current?.contains(event.target)) | |
| 364 | 新增: ) { | |
| 365 | 新增: if (event.key === "Escape") root.current?.querySelector(".account-trigger")?.focus(); | |
| 365 | 366 | setOpen(false); |
| 367 | 新增: } | |
| 366 | 368 | }; |
| 367 | 删除: window.addEventListener("pointerdown", dismiss); | |
| 369 | 新增: window.addEventListener("click", dismiss); | |
| 368 | 370 | window.addEventListener("keydown", dismiss); |
| 369 | 371 | return () => { |
| 370 | 删除: window.removeEventListener("pointerdown", dismiss); | |
| 372 | 新增: window.removeEventListener("click", dismiss); | |
| 371 | 373 | window.removeEventListener("keydown", dismiss); |
| 372 | 374 | }; |
| 373 | 375 | }, [open]); |
| @@ -402,10 +404,18 @@ export function AccountMenu({ onSettings, onConfirm, onStatus, busy }) { | ||
| 402 | 404 | <strong>{account.username}</strong> |
| 403 | 405 | <small>本地账户</small> |
| 404 | 406 | </span> |
| 405 | 删除: <ChevronUp size={15} /> | |
| 407 | 新增: <ChevronDown size={15} /> | |
| 406 | 408 | </button> |
| 407 | 409 | {open && ( |
| 408 | 删除: <div className="account-menu" role="menu" aria-label="本地账户菜单"> | |
| 410 | 新增: <div className="account-menu" role="menu" aria-label="本地账户菜单" | |
| 411 | 新增: onKeyDown={(event) => { | |
| 412 | 新增: if (event.key !== "ArrowDown" && event.key !== "ArrowUp") return; | |
| 413 | 新增: event.preventDefault(); | |
| 414 | 新增: const items = [...event.currentTarget.querySelectorAll("button:enabled")]; | |
| 415 | 新增: const step = event.key === "ArrowDown" ? 1 : -1; | |
| 416 | 新增: items[(items.indexOf(event.target) + step + items.length) % items.length].focus(); | |
| 417 | 新增: }} | |
| 418 | 新增: > | |
| 409 | 419 | <div className="account-menu-label">你的 Cage</div> |
| 410 | 420 | <button |
| 411 | 421 | role="menuitem" |
| @@ -413,19 +423,9 @@ export function AccountMenu({ onSettings, onConfirm, onStatus, busy }) { | ||
| 413 | 423 | setOpen(false); |
| 414 | 424 | onSettings("account"); |
| 415 | 425 | }} |
| 416 | 删除: > | |
| 417 | 删除: <UserRound size={16} /> | |
| 418 | 删除: 账户设置 | |
| 419 | 删除: </button> | |
| 420 | 删除: <button | |
| 421 | 删除: role="menuitem" | |
| 422 | 删除: onClick={() => { | |
| 423 | 删除: setOpen(false); | |
| 424 | 删除: onSettings("keyboard"); | |
| 425 | 删除: }} | |
| 426 | 426 | > |
| 427 | 427 | <Settings2 size={16} /> |
| 428 | 删除: 应用设置 | |
| 428 | 新增: 设置 | |
| 429 | 429 | </button> |
| 430 | 430 | <div className="account-menu-divider" /> |
| 431 | 431 | <button role="menuitem" onClick={() => perform("lock")}> |
| @@ -1,3 +1,4 @@ | ||
| 1 | 新增:import { InlineSelect } from "./inline-select"; | |
| 1 | 2 | import React, { useEffect, useRef, useState } from "react"; |
| 2 | 3 | import { |
| 3 | 4 | Check, |
| @@ -146,11 +147,11 @@ function ThemeCard({ variant, value, active, onChange }) { | ||
| 146 | 147 | <div className="theme-card-heading"> |
| 147 | 148 | <strong>{label}</strong> |
| 148 | 149 | {active && <small>当前使用</small>} |
| 149 | 删除: <select | |
| 150 | 新增: <InlineSelect | |
| 150 | 151 | aria-label={label + "预设"} |
| 151 | 152 | value={value.preset} |
| 152 | 删除: onChange={(e) => | |
| 153 | 删除: onChange(applyThemePreset(value, variant, e.target.value)) | |
| 153 | 新增: onValueChange={(next) => | |
| 154 | 新增: onChange(applyThemePreset(value, variant, next)) | |
| 154 | 155 | } |
| 155 | 156 | > |
| 156 | 157 | {presetGroups.map((group) => ( |
| @@ -169,7 +170,7 @@ function ThemeCard({ variant, value, active, onChange }) { | ||
| 169 | 170 | {presetNames[value.preset] || "自定义"} |
| 170 | 171 | </option> |
| 171 | 172 | )} |
| 172 | 删除: </select> | |
| 173 | 新增: </InlineSelect> | |
| 173 | 174 | </div> |
| 174 | 175 | <div |
| 175 | 176 | className="theme-miniature" |
| @@ -315,27 +316,35 @@ function ThemeCard({ variant, value, active, onChange }) { | ||
| 315 | 316 | </label> |
| 316 | 317 | <label> |
| 317 | 318 | 界面字体 |
| 318 | 删除: <input | |
| 319 | 新增: <InlineSelect editable | |
| 319 | 320 | aria-label={label + "界面字体"} |
| 320 | 删除: list="ui-fonts" | |
| 321 | 321 | value={value.fonts.ui} |
| 322 | 322 | placeholder="系统默认" |
| 323 | 删除: onChange={(e) => | |
| 324 | 删除: patch({ fonts: { ...value.fonts, ui: e.target.value } }) | |
| 323 | 新增: onValueChange={(next) => | |
| 324 | 新增: patch({ fonts: { ...value.fonts, ui: next } }) | |
| 325 | 325 | } |
| 326 | 删除: /> | |
| 326 | 新增: > | |
| 327 | 新增: <option value="system-ui" /> | |
| 328 | 新增: <option value="PingFang SC" /> | |
| 329 | 新增: <option value="Helvetica Neue" /> | |
| 330 | 新增: <option value="Arial" /> | |
| 331 | 新增: </InlineSelect> | |
| 327 | 332 | </label> |
| 328 | 333 | <label> |
| 329 | 334 | 代码字体 |
| 330 | 删除: <input | |
| 335 | 新增: <InlineSelect editable | |
| 331 | 336 | aria-label={label + "代码字体"} |
| 332 | 删除: list="code-fonts" | |
| 333 | 337 | value={value.fonts.code} |
| 334 | 338 | placeholder="系统等宽字体" |
| 335 | 删除: onChange={(e) => | |
| 336 | 删除: patch({ fonts: { ...value.fonts, code: e.target.value } }) | |
| 339 | 新增: onValueChange={(next) => | |
| 340 | 新增: patch({ fonts: { ...value.fonts, code: next } }) | |
| 337 | 341 | } |
| 338 | 删除: /> | |
| 342 | 新增: > | |
| 343 | 新增: <option value="SF Mono" /> | |
| 344 | 新增: <option value="Menlo" /> | |
| 345 | 新增: <option value="Monaco" /> | |
| 346 | 新增: <option value="JetBrains Mono" /> | |
| 347 | 新增: </InlineSelect> | |
| 339 | 348 | </label> |
| 340 | 349 | <label className="appearance-switch"> |
| 341 | 350 | <span>半透明侧栏</span> |
| @@ -509,12 +518,12 @@ function ThemeLibrary({ appearance, update, saving, onError }) { | ||
| 509 | 518 | }} |
| 510 | 519 | /> |
| 511 | 520 | <div className="theme-library-fields"> |
| 512 | 删除: <select | |
| 521 | 新增: <InlineSelect | |
| 513 | 522 | aria-label="已保存的主题" |
| 514 | 523 | value={current?.id || ""} |
| 515 | 524 | disabled={busy || saving} |
| 516 | 删除: onChange={(e) => { | |
| 517 | 删除: const item = themes.find((theme) => theme.id === e.target.value); | |
| 525 | 新增: onValueChange={(next) => { | |
| 526 | 新增: const item = themes.find((theme) => theme.id === next); | |
| 518 | 527 | if (item) apply(item); |
| 519 | 528 | }} |
| 520 | 529 | > |
| @@ -527,7 +536,7 @@ function ThemeLibrary({ appearance, update, saving, onError }) { | ||
| 527 | 536 | {item.id === current?.id && dirty ? " · 已修改" : ""} |
| 528 | 537 | </option> |
| 529 | 538 | ))} |
| 530 | 删除: </select> | |
| 539 | 新增: </InlineSelect> | |
| 531 | 540 | <input |
| 532 | 541 | aria-label="主题名称" |
| 533 | 542 | placeholder="为当前配色命名" |
| @@ -733,15 +742,15 @@ export function AppearanceSettings() { | ||
| 733 | 742 | </label> |
| 734 | 743 | </SettingRow> |
| 735 | 744 | <SettingRow label="减少动态效果"> |
| 736 | 删除: <select | |
| 745 | 新增: <InlineSelect | |
| 737 | 746 | aria-label="减少动态效果" |
| 738 | 747 | value={appearance.reducedMotion} |
| 739 | 删除: onChange={(e) => patch({ reducedMotion: e.target.value })} | |
| 748 | 新增: onValueChange={(next) => patch({ reducedMotion: next })} | |
| 740 | 749 | > |
| 741 | 750 | <option value="system">跟随系统</option> |
| 742 | 751 | <option value="on">开启</option> |
| 743 | 752 | <option value="off">关闭</option> |
| 744 | 删除: </select> | |
| 753 | 新增: </InlineSelect> | |
| 745 | 754 | </SettingRow> |
| 746 | 755 | <div className="appearance-import"> |
| 747 | 756 | <div> |
| @@ -783,18 +792,6 @@ export function AppearanceSettings() { | ||
| 783 | 792 | {syncError || error} |
| 784 | 793 | </div> |
| 785 | 794 | )} |
| 786 | 删除: <datalist id="ui-fonts"> | |
| 787 | 删除: <option value="system-ui" /> | |
| 788 | 删除: <option value="PingFang SC" /> | |
| 789 | 删除: <option value="Helvetica Neue" /> | |
| 790 | 删除: <option value="Arial" /> | |
| 791 | 删除: </datalist> | |
| 792 | 删除: <datalist id="code-fonts"> | |
| 793 | 删除: <option value="SF Mono" /> | |
| 794 | 删除: <option value="Menlo" /> | |
| 795 | 删除: <option value="Monaco" /> | |
| 796 | 删除: <option value="JetBrains Mono" /> | |
| 797 | 删除: </datalist> | |
| 798 | 795 | </div> |
| 799 | 796 | ); |
| 800 | 797 | } |
| @@ -108,10 +108,9 @@ button.primary:hover:not(:disabled) { | ||
| 108 | 108 | font-size: 0.714rem; |
| 109 | 109 | color: var(--muted); |
| 110 | 110 | } |
| 111 | 删除:.theme-card-heading select { | |
| 111 | 新增:.theme-card-heading .inline-select { | |
| 112 | 112 | width: 100%; |
| 113 | 113 | margin-top: 4px; |
| 114 | 删除: height: 34px; | |
| 115 | 114 | font-size: 0.929rem; |
| 116 | 115 | } |
| 117 | 116 | .theme-miniature { |
| @@ -268,9 +267,8 @@ button.primary:hover:not(:disabled) { | ||
| 268 | 267 | height: 34px; |
| 269 | 268 | text-align: center; |
| 270 | 269 | } |
| 271 | 删除:.appearance-control select { | |
| 270 | 新增:.appearance-control .inline-select { | |
| 272 | 271 | min-width: 120px; |
| 273 | 删除: height: 34px; | |
| 274 | 272 | font-size: 0.929rem; |
| 275 | 273 | } |
| 276 | 274 | .appearance-sample { |
| @@ -378,7 +376,7 @@ button.primary:hover:not(:disabled) { | ||
| 378 | 376 | grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) auto; |
| 379 | 377 | gap: 8px; |
| 380 | 378 | } |
| 381 | 删除:.theme-library-fields select, | |
| 379 | 新增:.theme-library-fields .inline-select, | |
| 382 | 380 | .theme-library-fields input { |
| 383 | 381 | min-width: 0; |
| 384 | 382 | } |
| @@ -1,3 +1,4 @@ | ||
| 1 | 新增:import { InlineSelect } from "./inline-select"; | |
| 1 | 2 | import { shortcut } from "./platform.mjs"; |
| 2 | 3 | import React, { useEffect, useRef, useState } from "react"; |
| 3 | 4 | import { createPortal } from "react-dom"; |
| @@ -15,7 +16,7 @@ import { Modal } from "./views"; | ||
| 15 | 16 | |
| 16 | 17 | // The saved page is primary, folder context secondary, management actions quiet. |
| 17 | 18 | // Reuse paper/strong/muted/line tokens, 8/12/16px spacing and existing modal forms. |
| 18 | 删除:export function BrowserFavorites({ current, ready, onOpen }) { | |
| 19 | 新增:export function BrowserFavorites({ current, ready, onOpen, shortcuts = true }) { | |
| 19 | 20 | const [data, setData] = useState(null); |
| 20 | 21 | const [open, setOpen] = useState(false); |
| 21 | 22 | const [editor, setEditor] = useState(null); |
| @@ -63,13 +64,13 @@ export function BrowserFavorites({ current, ready, onOpen }) { | ||
| 63 | 64 | setOpen(true); |
| 64 | 65 | void load(); |
| 65 | 66 | }; |
| 66 | 删除: state.current = { open, editor, addCurrent, show }; | |
| 67 | 新增: state.current = { open, editor, addCurrent, show, shortcuts }; | |
| 67 | 68 | useEffect(() => { |
| 68 | 69 | void load(); |
| 69 | 70 | }, []); |
| 70 | 71 | useEffect(() => { |
| 71 | 删除: const add = () => state.current.addCurrent(); | |
| 72 | 删除: const show = () => state.current.show(); | |
| 72 | 新增: const add = () => state.current.shortcuts && state.current.addCurrent(); | |
| 73 | 新增: const show = () => state.current.shortcuts && state.current.show(); | |
| 73 | 74 | const close = () => { |
| 74 | 75 | if (!state.current.editor && !savingRef.current) setOpen(false); |
| 75 | 76 | }; |
| @@ -237,10 +238,10 @@ export function BrowserFavorites({ current, ready, onOpen }) { | ||
| 237 | 238 | /> |
| 238 | 239 | </label> |
| 239 | 240 | <div className="favorites-folder-select"> |
| 240 | 删除: <select | |
| 241 | 新增: <InlineSelect | |
| 241 | 242 | aria-label="筛选收藏夹" |
| 242 | 243 | value={folder} |
| 243 | 删除: onChange={(event) => setFolder(event.target.value)} | |
| 244 | 新增: onValueChange={(next) => setFolder(next)} | |
| 244 | 245 | > |
| 245 | 246 | <option value="all">全部收藏</option> |
| 246 | 247 | <option value="">未分类</option> |
| @@ -249,7 +250,7 @@ export function BrowserFavorites({ current, ready, onOpen }) { | ||
| 249 | 250 | {item.title} |
| 250 | 251 | </option> |
| 251 | 252 | ))} |
| 252 | 删除: </select> | |
| 253 | 新增: </InlineSelect> | |
| 253 | 254 | {selectedFolder && ( |
| 254 | 255 | <> |
| 255 | 256 | <button |
| @@ -424,14 +425,14 @@ export function BrowserFavorites({ current, ready, onOpen }) { | ||
| 424 | 425 | </label> |
| 425 | 426 | <label> |
| 426 | 427 | 收藏夹 |
| 427 | 删除: <select | |
| 428 | 新增: <InlineSelect | |
| 428 | 429 | aria-label="保存到收藏夹" |
| 429 | 430 | value={editor.folder_id} |
| 430 | 431 | disabled={Boolean(editor.newFolder)} |
| 431 | 删除: onChange={(event) => | |
| 432 | 新增: onValueChange={(next) => | |
| 432 | 433 | setEditor({ |
| 433 | 434 | ...editor, |
| 434 | 删除: folder_id: event.target.value, | |
| 435 | 新增: folder_id: next, | |
| 435 | 436 | }) |
| 436 | 437 | } |
| 437 | 438 | > |
| @@ -441,7 +442,7 @@ export function BrowserFavorites({ current, ready, onOpen }) { | ||
| 441 | 442 | {item.title} |
| 442 | 443 | </option> |
| 443 | 444 | ))} |
| 444 | 删除: </select> | |
| 445 | 新增: </InlineSelect> | |
| 445 | 446 | </label> |
| 446 | 447 | <label> |
| 447 | 448 | 新建收藏夹(可选) |
| @@ -0,0 +1,4 @@ | ||
| 1 | 新增:<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 10" fill="#D97757" shape-rendering="crispEdges"> | |
| 2 | 新增: <path fill-rule="evenodd" d="M2 0h12v4h2v2h-2v2H2V6H0V4h2z M4 2v2h1V2z M11 2v2h1V2z"/> | |
| 3 | 新增: <path d="M3 8h1v2H3z M5 8h1v2H5z M10 8h1v2h-1z M12 8h1v2h-1z"/> | |
| 4 | 新增:</svg> | |
| @@ -0,0 +1,227 @@ | ||
| 1 | 新增:.settings-content.settings-content--accounts { | |
| 2 | 新增: display: flex; | |
| 3 | 新增: flex-direction: column; | |
| 4 | 新增: padding-bottom: clamp(12px, 3vh, 28px); | |
| 5 | 新增:} | |
| 6 | 新增:.settings-content--accounts > .settings-fields:empty { display: none; } | |
| 7 | 新增:.claude-profiles { | |
| 8 | 新增: container-type: inline-size; | |
| 9 | 新增: --crab-coral: #cd745b; | |
| 10 | 新增: --quota-five: color-mix(in srgb, var(--crab-coral) 83%, var(--strong)); | |
| 11 | 新增: --quota-seven: color-mix(in srgb, #519489 82%, var(--strong)); | |
| 12 | 新增: width: 100%; | |
| 13 | 新增: max-width: 720px; | |
| 14 | 新增: min-width: 0; | |
| 15 | 新增: min-height: 0; | |
| 16 | 新增: flex: 1 0 0; | |
| 17 | 新增: display: flex; | |
| 18 | 新增: flex-direction: column; | |
| 19 | 新增: margin-inline: auto; | |
| 20 | 新增:} | |
| 21 | 新增:.claude-profiles > :not(.claude-profile-list) { flex: none; } | |
| 22 | 新增:.settings-content .claude-profiles .section-title { margin-bottom: 16px; } | |
| 23 | 新增:.claude-add-profile, .claude-profile-rename, .claude-profile-name, | |
| 24 | 新增:.claude-profile-actions, .claude-profile-meta { | |
| 25 | 新增: display: flex; | |
| 26 | 新增: align-items: center; | |
| 27 | 新增: gap: 8px; | |
| 28 | 新增: min-width: 0; | |
| 29 | 新增:} | |
| 30 | 新增:.claude-add-profile { gap: 8px; } | |
| 31 | 新增:.claude-profile-rename input { min-width: 0; flex: 1; } | |
| 32 | 新增:.claude-add-profile button { min-height: 40px; flex: none; } | |
| 33 | 新增:.claude-profiles .account-error, .claude-profile-note { margin: 7px 0 0; font-size: 0.85rem; } | |
| 34 | 新增:.claude-profile-note { color: var(--muted); } | |
| 35 | 新增:.claude-list-heading { | |
| 36 | 新增: display: flex; | |
| 37 | 新增: align-items: center; | |
| 38 | 新增: justify-content: space-between; | |
| 39 | 新增: margin: 23px 0 10px; | |
| 40 | 新增:} | |
| 41 | 新增:.settings-content .claude-list-heading h4 { | |
| 42 | 新增: display: flex; | |
| 43 | 新增: align-items: center; | |
| 44 | 新增: gap: 7px; | |
| 45 | 新增: margin: 0; | |
| 46 | 新增: font-size: 0.92rem; | |
| 47 | 新增: font-weight: 600; | |
| 48 | 新增:} | |
| 49 | 新增:.claude-list-heading h4 span { | |
| 50 | 新增: padding: 1px 7px; | |
| 51 | 新增: border-radius: 8px; | |
| 52 | 新增: background: var(--chrome); | |
| 53 | 新增: color: var(--muted); | |
| 54 | 新增: font: 500 0.8rem/1.45 var(--ui-font-family, sans-serif); | |
| 55 | 新增:} | |
| 56 | 新增:.claude-list-heading small, .claude-quota-age, .claude-profile-meta { | |
| 57 | 新增: color: var(--muted); | |
| 58 | 新增: font-size: 0.82rem; | |
| 59 | 新增:} | |
| 60 | 新增:.claude-profile-list { | |
| 61 | 新增: flex: 1 1 auto; | |
| 62 | 新增: /* Preserve a usable scroll area when large fonts or a short window need the outer pane to scroll. */ | |
| 63 | 新增: min-height: 6rem; | |
| 64 | 新增: overflow-y: auto; | |
| 65 | 新增: overscroll-behavior-y: contain; | |
| 66 | 新增: scrollbar-width: thin; | |
| 67 | 新增: scrollbar-color: var(--focus) transparent; | |
| 68 | 新增: scrollbar-gutter: stable; | |
| 69 | 新增: padding: 2px 4px 4px 1px; | |
| 70 | 新增:} | |
| 71 | 新增:.claude-profile-list:focus-visible { outline: 2px solid var(--focus); outline-offset: 1px; } | |
| 72 | 新增:.claude-profile { | |
| 73 | 新增: padding: 14px 16px 10px; | |
| 74 | 新增: margin-bottom: 9px; | |
| 75 | 新增: border: 1px solid var(--line); | |
| 76 | 新增: border-radius: 12px; | |
| 77 | 新增: background: var(--paper); | |
| 78 | 新增:} | |
| 79 | 新增:.claude-profile-heading { | |
| 80 | 新增: display: grid; | |
| 81 | 新增: grid-template-columns: auto minmax(0, 1fr) auto; | |
| 82 | 新增: align-items: center; | |
| 83 | 新增: column-gap: 10px; | |
| 84 | 新增:} | |
| 85 | 新增:.claude-profile-avatar { | |
| 86 | 新增: display: grid; | |
| 87 | 新增: place-items: center; | |
| 88 | 新增: width: 42px; | |
| 89 | 新增: height: 42px; | |
| 90 | 新增: border-radius: 13px; | |
| 91 | 新增: background: color-mix(in srgb, var(--crab-coral) 13%, var(--paper)); | |
| 92 | 新增:} | |
| 93 | 新增:.claude-profile-avatar img { width: 32px; height: auto; } | |
| 94 | 新增:.claude-profile[data-enabled="false"] .claude-profile-avatar { background: var(--chrome); } | |
| 95 | 新增:.claude-profile[data-enabled="false"] .claude-profile-avatar img { filter: saturate(0.45); } | |
| 96 | 新增:.claude-detected { border-style: dashed; } | |
| 97 | 新增:.claude-profile-source { font-size: 0.82rem; color: var(--muted); } | |
| 98 | 新增:@media (prefers-reduced-motion: no-preference) { | |
| 99 | 新增: .claude-profile-avatar img { transition: transform 160ms ease-out; } | |
| 100 | 新增: .claude-profile-avatar:hover img { transform: translateY(-2px); } | |
| 101 | 新增:} | |
| 102 | 新增:.claude-profile-identity { min-width: 0; } | |
| 103 | 新增:.claude-profile-name { gap: 6px; } | |
| 104 | 新增:.settings-content .claude-profiles .claude-profile h4 { | |
| 105 | 新增: min-width: 0; | |
| 106 | 新增: overflow: hidden; | |
| 107 | 新增: text-overflow: ellipsis; | |
| 108 | 新增: white-space: nowrap; | |
| 109 | 新增: margin: 0; | |
| 110 | 新增: font-size: 1.04rem; | |
| 111 | 新增: font-weight: 620; | |
| 112 | 新增: letter-spacing: normal; | |
| 113 | 新增:} | |
| 114 | 新增:.claude-profile-name .icon-button { width: 24px; height: 24px; flex: none; color: var(--muted); } | |
| 115 | 新增:.claude-profile-plan { | |
| 116 | 新增: max-width: 7em; | |
| 117 | 新增: overflow: hidden; | |
| 118 | 新增: text-overflow: ellipsis; | |
| 119 | 新增: white-space: nowrap; | |
| 120 | 新增: border-radius: 5px; | |
| 121 | 新增: padding: 1px 5px; | |
| 122 | 新增: background: var(--chrome); | |
| 123 | 新增: color: var(--ink); | |
| 124 | 新增: font-size: 0.74rem; | |
| 125 | 新增: font-weight: 550; | |
| 126 | 新增:} | |
| 127 | 新增:.claude-profile-meta { gap: 7px; margin-top: 2px; } | |
| 128 | 新增:.claude-profile-email { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } | |
| 129 | 新增:.claude-profile-status { display: inline-flex; align-items: center; gap: 4px; flex: none; } | |
| 130 | 新增:.claude-profile-status::before { | |
| 131 | 新增: content: ""; width: 5px; height: 5px; border-radius: 50%; background: var(--muted); | |
| 132 | 新增:} | |
| 133 | 新增:.claude-profile-status[data-ready="true"]::before { background: var(--success); } | |
| 134 | 新增:.claude-profile-heading .claude-participation { | |
| 135 | 新增: position: relative; | |
| 136 | 新增: display: inline-flex; | |
| 137 | 新增: align-items: center; | |
| 138 | 新增: gap: 6px; | |
| 139 | 新增: margin: 0; | |
| 140 | 新增: min-height: 28px; | |
| 141 | 新增: color: var(--muted); | |
| 142 | 新增: font-size: 0.81rem; | |
| 143 | 新增: cursor: pointer; | |
| 144 | 新增:} | |
| 145 | 新增:.claude-participation input { position: absolute; inset: 0; margin: 0; opacity: 0; width: 100%; height: 100%; cursor: inherit; } | |
| 146 | 新增:.claude-switch-track { width: 26px; height: 15px; border-radius: 9px; background: var(--muted); padding: 2px; } | |
| 147 | 新增:.claude-switch-track::before { | |
| 148 | 新增: content: ""; display: block; width: 11px; height: 11px; border-radius: 50%; background: var(--paper); | |
| 149 | 新增:} | |
| 150 | 新增:.claude-participation input:checked + .claude-switch-track { background: var(--quota-seven); } | |
| 151 | 新增:.claude-participation input:checked + .claude-switch-track::before { transform: translateX(11px); } | |
| 152 | 新增:.claude-participation input:focus-visible + .claude-switch-track { outline: 2px solid var(--focus); outline-offset: 3px; } | |
| 153 | 新增:.claude-participation:has(:disabled) { opacity: 0.6; cursor: default; } | |
| 154 | 新增:.claude-quota-grid { | |
| 155 | 新增: display: grid; | |
| 156 | 新增: grid-template-columns: auto minmax(2rem, 1fr) auto; | |
| 157 | 新增: align-items: center; | |
| 158 | 新增: gap: 7px 12px; | |
| 159 | 新增: margin: 13px 0 10px; | |
| 160 | 新增: font-size: 0.84rem; | |
| 161 | 新增: font-variant-numeric: tabular-nums; | |
| 162 | 新增:} | |
| 163 | 新增:.claude-quota-row { display: grid; grid-column: 1 / -1; grid-template-columns: subgrid; align-items: center; } | |
| 164 | 新增:.claude-quota-history { grid-column: 2 / -1; min-width: 0; color: var(--muted); font-size: 0.76rem; overflow-wrap: anywhere; } | |
| 165 | 新增:.claude-quota-period { color: var(--ink); font: 600 0.86rem/1.45 ui-monospace, monospace; } | |
| 166 | 新增:.claude-quota-row progress, .claude-quota-unknown { | |
| 167 | 新增: display: block; | |
| 168 | 新增: width: 100%; | |
| 169 | 新增: min-width: 0; | |
| 170 | 新增: height: 5px; | |
| 171 | 新增: border: 0; | |
| 172 | 新增: border-radius: 5px; | |
| 173 | 新增: overflow: hidden; | |
| 174 | 新增: appearance: none; | |
| 175 | 新增: background: var(--chrome-dark); | |
| 176 | 新增:} | |
| 177 | 新增:.claude-quota-row { --fill: var(--quota-five); } | |
| 178 | 新增:.claude-quota-row + .claude-quota-row { --fill: var(--quota-seven); } | |
| 179 | 新增:.claude-quota-row progress::-webkit-progress-bar { background: var(--chrome-dark); border-radius: 5px; } | |
| 180 | 新增:.claude-quota-row progress::-webkit-progress-value { background: var(--fill); border-radius: 5px; } | |
| 181 | 新增:.claude-quota-row progress::-moz-progress-bar { background: var(--fill); border-radius: 5px; } | |
| 182 | 新增:.claude-quota-unknown { background: repeating-linear-gradient(90deg, var(--line) 0 4px, transparent 4px 7px); } | |
| 183 | 新增:.claude-quota-reading { display: flex; align-items: baseline; justify-content: flex-end; gap: 7px; white-space: nowrap; } | |
| 184 | 新增:.claude-quota-reading strong { font-weight: 600; color: var(--strong); } | |
| 185 | 新增:.claude-quota-reset, .claude-quota-stale { color: var(--muted); } | |
| 186 | 新增:.claude-quota-stale { font-size: 0.73rem; } | |
| 187 | 新增:.claude-profile-actions { flex-wrap: wrap; gap: 3px 12px; border-top: 1px solid var(--line); padding-top: 6px; } | |
| 188 | 新增:.claude-profile-actions .quiet-button, .claude-profile-actions .text-button { | |
| 189 | 新增: background: transparent; border: 0; border-radius: 4px; padding: 3px 0; | |
| 190 | 新增: min-height: 26px; font-size: 0.82rem; color: var(--ink); | |
| 191 | 新增:} | |
| 192 | 新增:.claude-profile-actions .quiet-button:hover:enabled, .claude-profile-actions .text-button:hover:enabled { color: var(--strong); text-decoration: underline; } | |
| 193 | 新增:.claude-profile-actions .quiet-button { gap: 4px; } | |
| 194 | 新增:.claude-quota-age { margin-left: auto; display: flex; flex-wrap: wrap; gap: 2px 8px; font-variant-numeric: tabular-nums; } | |
| 195 | 新增:.claude-profile .field-help { margin: 7px 0; } | |
| 196 | 新增:.claude-profile-empty { text-align: center; border: 1px dashed var(--line); border-radius: 12px; padding: 28px 10px; } | |
| 197 | 新增:.claude-profile-empty img { width: 42px; } | |
| 198 | 新增:.claude-profile-empty p { margin: 6px 0; font-weight: 550; } | |
| 199 | 新增:.claude-profile-empty small { color: var(--muted); } | |
| 200 | 新增:.claude-tab-profile { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 48%; color: var(--muted); font-size: 0.78rem; } | |
| 201 | 新增:@container (max-width: 370px) { | |
| 202 | 新增: .claude-profile { padding: 11px 10px 8px; } | |
| 203 | 新增: .claude-profile-heading { column-gap: 6px; } | |
| 204 | 新增: .claude-profile-avatar { width: 32px; height: 32px; border-radius: 9px; } | |
| 205 | 新增: .claude-profile-avatar img { width: 28px; } | |
| 206 | 新增: .claude-quota-grid { column-gap: 6px; } | |
| 207 | 新增: .claude-quota-reading { gap: 4px; flex-wrap: wrap; max-width: 9em; } | |
| 208 | 新增: .claude-quota-age { margin-left: 0; width: 100%; } | |
| 209 | 新增: .claude-profile-heading:has(.claude-profile-rename) { grid-template-columns: minmax(0, 1fr) auto; } | |
| 210 | 新增: .claude-profile-heading:has(.claude-profile-rename) .claude-profile-avatar { display: none; } | |
| 211 | 新增: .claude-add-profile button { padding-inline: 7px; } | |
| 212 | 新增:} | |
| 213 | 新增:.claude-quota-reset { display: inline-flex; align-items: center; gap: 3px; } | |
| 214 | 新增:@container (max-width: 300px) { | |
| 215 | 新增: .claude-profile-heading { grid-template-columns: 28px minmax(0, 1fr) auto; row-gap: 2px; } | |
| 216 | 新增: .claude-profile-identity { display: contents; } | |
| 217 | 新增: .claude-profile-name { grid-area: 1 / 2 / 2 / -1; gap: 4px; } | |
| 218 | 新增: .claude-profile-meta { display: contents; } | |
| 219 | 新增: .claude-profile-status { grid-area: 2 / 1 / 3 / 3; } | |
| 220 | 新增: .claude-profile-email { grid-area: 3 / 1 / 4 / -1; } | |
| 221 | 新增: .claude-profile-heading .claude-participation { grid-area: 2 / 3; } | |
| 222 | 新增: .claude-profile-heading:has(.claude-profile-rename) { grid-template-columns: minmax(0, 1fr) auto; } | |
| 223 | 新增: .claude-profile-rename { grid-column: 1 / -1; } | |
| 224 | 新增: .claude-profile-heading:has(.claude-profile-rename) .claude-profile-status { grid-column: 1; } | |
| 225 | 新增: .claude-profile-heading:has(.claude-profile-rename) .claude-participation { grid-column: 2; } | |
| 226 | 新增: .claude-quota-reset svg { display: none; } | |
| 227 | 新增:} | |
| @@ -0,0 +1,361 @@ | ||
| 1 | 新增:import React, { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react"; | |
| 2 | 新增:import { Check, Pencil, Plus, RefreshCw, TerminalSquare, Timer } from "lucide-react"; | |
| 3 | 新增:import { api } from "./api"; | |
| 4 | 新增:import crabIcon from "./claude-account-crab.svg"; | |
| 5 | 新增:import "./claude-accounts.css"; | |
| 6 | 新增: | |
| 7 | 新增:// Ordinary reads never start an upstream usage query. | |
| 8 | 新增:export function useClaudeAccounts() { | |
| 9 | 新增: const [registry, setRegistry] = useState(null); | |
| 10 | 新增: const [error, setError] = useState(""); | |
| 11 | 新增: const generation = useRef(0); | |
| 12 | 新增: const pendingMutation = useRef(0); | |
| 13 | 新增: const polling = useRef(false); | |
| 14 | 新增: const load = useCallback(async (change, visiblePanel = false) => { | |
| 15 | 新增: if (!change && (pendingMutation.current || (visiblePanel && polling.current))) return; | |
| 16 | 新增: const request = ++generation.current; | |
| 17 | 新增: if (change) pendingMutation.current++; | |
| 18 | 新增: else if (visiblePanel) polling.current = true; | |
| 19 | 新增: try { | |
| 20 | 新增: const value = await api(visiblePanel ? "/claude-accounts?panel=visible" : "/claude-accounts", change); | |
| 21 | 新增: if (!Array.isArray(value?.accounts)) throw new Error("无法读取 Claude 账号列表"); | |
| 22 | 新增: if (generation.current === request) { | |
| 23 | 新增: setRegistry(value); | |
| 24 | 新增: setError(""); | |
| 25 | 新增: } | |
| 26 | 新增: return value.accounts; | |
| 27 | 新增: } catch (e) { | |
| 28 | 新增: if (generation.current === request) setError(e.message); | |
| 29 | 新增: if (change) throw e; | |
| 30 | 新增: } finally { | |
| 31 | 新增: if (change) pendingMutation.current--; | |
| 32 | 新增: else if (visiblePanel) polling.current = false; | |
| 33 | 新增: } | |
| 34 | 新增: }, []); | |
| 35 | 新增: useEffect(() => { load(); return () => { generation.current++; }; }, [load]); | |
| 36 | 新增: return { accounts: registry?.accounts ?? null, detected: registry?.detected, | |
| 37 | 新增: detectionStatus: registry?.detection_status, detectionError: registry?.detection_error, | |
| 38 | 新增: usageRunning: registry?.usage_panel_running, usageUnavailable: registry?.usage_unavailable_reason, | |
| 39 | 新增: loginNotice: registry?.login_notice, error, load }; | |
| 40 | 新增:} | |
| 41 | 新增: | |
| 42 | 新增:const statusLabels = { | |
| 43 | 新增: pending: "等待登录", ready: "已登录", signed_out: "需要登录", | |
| 44 | 新增: duplicate: "账号已在列表中", changed: "登录身份已改变", | |
| 45 | 新增:}; | |
| 46 | 新增:const localTimestamp = new Intl.DateTimeFormat(undefined, { | |
| 47 | 新增: month: "numeric", day: "numeric", hour: "2-digit", minute: "2-digit", | |
| 48 | 新增:}); | |
| 49 | 新增:const timeLabel = (seconds) => localTimestamp.format(seconds * 1000); | |
| 50 | 新增: | |
| 51 | 新增:const QuotaTime = createContext(0); | |
| 52 | 新增: | |
| 53 | 新增:// All rows share a clock. Only quota readings subscribe; a tick doesn't render | |
| 54 | 新增:// the account forms or fetch data. Sleep until the next visible unit changes. | |
| 55 | 新增:function QuotaClock({ accounts, children }) { | |
| 56 | 新增: const [now, setNow] = useState(() => Math.floor(Date.now() / 1000)); | |
| 57 | 新增: useEffect(() => { | |
| 58 | 新增: let timer; | |
| 59 | 新增: const update = () => { | |
| 60 | 新增: clearTimeout(timer); | |
| 61 | 新增: if (document.hidden) return; | |
| 62 | 新增: const millis = Date.now(); | |
| 63 | 新增: const seconds = Math.floor(millis / 1000); | |
| 64 | 新增: setNow(seconds); | |
| 65 | 新增: let delay = Infinity; | |
| 66 | 新增: for (const account of accounts || []) { | |
| 67 | 新增: for (const window of [account.quota?.five_hour, account.quota?.seven_day]) { | |
| 68 | 新增: const left = window?.resets_at - seconds; | |
| 69 | 新增: if (left > 0) delay = Math.min(delay, left <= 60 ? 1 : (left - 1) % 60 + 1); | |
| 70 | 新增: const seen = window?.observed_at; | |
| 71 | 新增: if (window && seen && seen + 901 > seconds) delay = Math.min(delay, seen + 901 - seconds); | |
| 72 | 新增: } | |
| 73 | 新增: } | |
| 74 | 新增: if (Number.isFinite(delay)) timer = setTimeout(update, delay * 1000 - millis % 1000); | |
| 75 | 新增: }; | |
| 76 | 新增: update(); | |
| 77 | 新增: document.addEventListener("visibilitychange", update); | |
| 78 | 新增: return () => { clearTimeout(timer); document.removeEventListener("visibilitychange", update); }; | |
| 79 | 新增: }, [accounts]); | |
| 80 | 新增: return <QuotaTime.Provider value={now}>{children}</QuotaTime.Provider>; | |
| 81 | 新增:} | |
| 82 | 新增: | |
| 83 | 新增:function resetCountdown(seconds) { | |
| 84 | 新增: if (seconds < 60) return `${seconds}秒后`; | |
| 85 | 新增: const minutes = Math.ceil(seconds / 60); | |
| 86 | 新增: if (minutes < 60) return `${minutes}分后`; | |
| 87 | 新增: const hours = Math.floor(minutes / 60); | |
| 88 | 新增: if (hours < 24) return `${hours}时 ${minutes % 60}分后`; | |
| 89 | 新增: return `${Math.floor(hours / 24)}天 ${hours % 24}时后`; | |
| 90 | 新增:} | |
| 91 | 新增: | |
| 92 | 新增:const usageLabels = { | |
| 93 | 新增: checking: "正在查询额度…", reported: "已获取额度", partial: "本次只返回了部分额度", | |
| 94 | 新增: cached: "本次只有缓存读数", unavailable: "本次未返回额度", error: "额度查询失败", | |
| 95 | 新增: not_applicable: "当前登录不提供订阅额度", | |
| 96 | 新增: identity_changed: "登录身份已改变,本次读数已丢弃", offline: "环境离线,无法查询", | |
| 97 | 新增: update_required: "需同步环境组件后才能查询", blocked: "暂时无法查询额度", | |
| 98 | 新增: signed_out: "登录后可查询额度", local: "已有会话读数", unknown: "尚未查询额度", | |
| 99 | 新增:}; | |
| 100 | 新增: | |
| 101 | 新增:function useUsageCheck(profile, environment, perform, change) { | |
| 102 | 新增: const [manual, setManual] = useState(null); | |
| 103 | 新增: const check = () => perform(async () => { | |
| 104 | 新增: setManual({ state: "checking" }); | |
| 105 | 新增: try { | |
| 106 | 新增: await change(profile.id ? { action: "refresh", id: profile.id } : | |
| 107 | 新增: { action: "refresh_default", identity: profile.identity }); | |
| 108 | 新增: setManual(null); | |
| 109 | 新增: } catch (e) { | |
| 110 | 新增: setManual({ state: "error", previousCheck: profile.usage_checked_at, previousStatus: profile.usage_status }); | |
| 111 | 新增: await change(); // A failed identity check can still change which default account the panel should show. | |
| 112 | 新增: throw e; | |
| 113 | 新增: } | |
| 114 | 新增: }); | |
| 115 | 新增: let state = profile.usage_status || (profile.quota ? "local" : "unknown"); | |
| 116 | 新增: if (profile.status === "changed" || profile.status === "duplicate") state = "identity_changed"; | |
| 117 | 新增: if (profile.status === "signed_out" || profile.status === "pending") state = "signed_out"; | |
| 118 | 新增: if (manual?.state === "error" && manual.previousCheck === profile.usage_checked_at && manual.previousStatus === profile.usage_status) state = "error"; | |
| 119 | 新增: if (profile.usage_checking || manual?.state === "checking") state = "checking"; | |
| 120 | 新增: if (environment) state = environment; | |
| 121 | 新增: return { state, check }; | |
| 122 | 新增:} | |
| 123 | 新增: | |
| 124 | 新增:function QuotaWindow({ label, snapshot, state }) { | |
| 125 | 新增: const now = useContext(QuotaTime); | |
| 126 | 新增: const reset = snapshot?.resets_at; | |
| 127 | 新增: const remaining = reset ? reset - now : null; | |
| 128 | 新增: const expired = remaining !== null && remaining <= 0; | |
| 129 | 新增: const hasReading = Number.isFinite(snapshot?.used_percentage); | |
| 130 | 新增: const known = !expired && hasReading; | |
| 131 | 新增: const lastSeen = snapshot?.observed_at; | |
| 132 | 新增: const stale = known && (!lastSeen || now - lastSeen > 15 * 60 || | |
| 133 | 新增: !["reported", "partial"].includes(state)); | |
| 134 | 新增: const countdown = expired ? "等待更新" : remaining !== null ? resetCountdown(remaining) : | |
| 135 | 新增: known ? "重置时间未知" : state === "checking" ? "查询中" : "暂无读数"; | |
| 136 | 新增: return <div className="claude-quota-row" role="group" aria-label={label + " 额度"}> | |
| 137 | 新增: <span className="claude-quota-period">{label}</span> | |
| 138 | 新增: {known | |
| 139 | 新增: ? <progress aria-label={label + " 已用额度"} value={snapshot.used_percentage} max={100} /> | |
| 140 | 新增: : <span className="claude-quota-unknown" aria-hidden="true" />} | |
| 141 | 新增: <div className="claude-quota-reading"> | |
| 142 | 新增: {stale && <span className="claude-quota-stale" title={lastSeen ? `历史读数 · ${timeLabel(lastSeen)}` : "历史读数"}>历史读数</span>} | |
| 143 | 新增: {known && <strong title={lastSeen ? `已用额度 · 读取于 ${timeLabel(lastSeen)}` : "已用额度"}>{snapshot.used_percentage}%</strong>} | |
| 144 | 新增: <span className="claude-quota-reset" title={reset ? `${timeLabel(reset)} 重置` : "尚无重置时间"}> | |
| 145 | 新增: {remaining > 0 && <Timer size={12} aria-hidden="true" />}{countdown} | |
| 146 | 新增: </span> | |
| 147 | 新增: </div> | |
| 148 | 新增: {hasReading && (expired || stale || state === "partial") && <small className="claude-quota-history"> | |
| 149 | 新增: {expired && `上次 ${snapshot.used_percentage}% · `} | |
| 150 | 新增: {lastSeen > 0 ? <>{!expired && "读取于 "}<time dateTime={new Date(lastSeen * 1000).toISOString()}>{timeLabel(lastSeen)}</time></> : "读数时间未知"} | |
| 151 | 新增: </small>} | |
| 152 | 新增: </div>; | |
| 153 | 新增:} | |
| 154 | 新增: | |
| 155 | 新增:function ProfileUsage({ quota, state }) { | |
| 156 | 新增: return <div className="claude-quota-grid"> | |
| 157 | 新增: <QuotaWindow label="5h" snapshot={quota?.five_hour} state={state} /> | |
| 158 | 新增: <QuotaWindow label="7d" snapshot={quota?.seven_day} state={state} /> | |
| 159 | 新增: </div>; | |
| 160 | 新增:} | |
| 161 | 新增: | |
| 162 | 新增:function UsageNote({ profile, state }) { | |
| 163 | 新增: const latestReading = Math.max(profile.quota?.five_hour?.observed_at || 0, profile.quota?.seven_day?.observed_at || 0); | |
| 164 | 新增: return <small className="claude-quota-age"> | |
| 165 | 新增: <span>{usageLabels[state] || "暂无额度信息"}</span> | |
| 166 | 新增: {profile.usage_checked_at > 0 && <span>上次查询 {timeLabel(profile.usage_checked_at)}</span>} | |
| 167 | 新增: {latestReading > 0 && <span>最近读数 {timeLabel(latestReading)}</span>} | |
| 168 | 新增: </small>; | |
| 169 | 新增:} | |
| 170 | 新增: | |
| 171 | 新增:function DetectedProfile({ profile, usageEnvironment, busy, join, perform, change }) { | |
| 172 | 新增: const usage = useUsageCheck(profile, usageEnvironment, perform, change); | |
| 173 | 新增: return <article className="claude-profile claude-detected" aria-label={profile.email}> | |
| 174 | 新增: <div className="claude-profile-heading"> | |
| 175 | 新增: <span className="claude-profile-avatar" aria-hidden="true"><img src={crabIcon} alt="" /></span> | |
| 176 | 新增: <div className="claude-profile-identity"> | |
| 177 | 新增: <div className="claude-profile-name"> | |
| 178 | 新增: <h4 title={profile.email}>{profile.email}</h4> | |
| 179 | 新增: {profile.plan && <span className="claude-profile-plan">{profile.plan}</span>} | |
| 180 | 新增: </div> | |
| 181 | 新增: <div className="claude-profile-meta"> | |
| 182 | 新增: <span className="claude-profile-status">普通终端 · 已发现,未加入</span> | |
| 183 | 新增: {profile.organization && <span className="claude-profile-email" title={profile.organization}>{profile.organization}</span>} | |
| 184 | 新增: </div> | |
| 185 | 新增: </div> | |
| 186 | 新增: </div> | |
| 187 | 新增: <ProfileUsage quota={profile.quota} state={usage.state} /> | |
| 188 | 新增: <div className="claude-profile-actions"> | |
| 189 | 新增: <button className="quiet-button" disabled={busy} onClick={join}><Plus size={14} />加入调度</button> | |
| 190 | 新增: <button className="quiet-button" disabled={busy || !!usageEnvironment || usage.state === "checking"} onClick={usage.check}> | |
| 191 | 新增: <RefreshCw size={14} />检查状态</button> | |
| 192 | 新增: <UsageNote profile={profile} state={usage.state} /> | |
| 193 | 新增: </div> | |
| 194 | 新增: </article>; | |
| 195 | 新增:} | |
| 196 | 新增: | |
| 197 | 新增:function ProfileCard({ profile, environment, usageEnvironment, busy, active, defaultActive, perform, change, login, cancelDraft }) { | |
| 198 | 新增: const [renaming, setRenaming] = useState(false); | |
| 199 | 新增: const [label, setLabel] = useState(""); | |
| 200 | 新增: const displayName = profile.label || profile.email; | |
| 201 | 新增: const fromTerminal = profile.source === "default"; | |
| 202 | 新增: const savedLabel = label.trim() || profile.email; | |
| 203 | 新增: const usage = useUsageCheck(profile, usageEnvironment, perform, change); | |
| 204 | 新增: return <article className="claude-profile" aria-label={displayName} data-enabled={profile.enabled}> | |
| 205 | 新增: <div className="claude-profile-heading"> | |
| 206 | 新增: <span className="claude-profile-avatar" aria-hidden="true"><img src={crabIcon} alt="" /></span> | |
| 207 | 新增: <div className="claude-profile-identity"> | |
| 208 | 新增: {renaming ? <form className="claude-profile-rename" onSubmit={(e) => { | |
| 209 | 新增: e.preventDefault(); | |
| 210 | 新增: perform(async () => { await change({ action: "update", id: profile.id, label: savedLabel }); setRenaming(false); }); | |
| 211 | 新增: }}> | |
| 212 | 新增: <input autoFocus aria-label="账号备注" maxLength={64} placeholder={profile.email || "账号名称"} value={label} onChange={(e) => setLabel(e.target.value)} /> | |
| 213 | 新增: <button disabled={busy || !savedLabel} aria-label="保存备注"><Check size={15} /></button> | |
| 214 | 新增: <button type="button" disabled={busy} onClick={() => setRenaming(false)}>取消</button> | |
| 215 | 新增: </form> : <div className="claude-profile-name"> | |
| 216 | 新增: <h4 title={displayName}>{displayName}</h4> | |
| 217 | 新增: {profile.plan && <span className="claude-profile-plan">{profile.plan}</span>} | |
| 218 | 新增: <button type="button" className="icon-button" disabled={busy} aria-label={`修改 ${displayName} 的备注`} | |
| 219 | 新增: onClick={() => { setLabel(profile.label === profile.email ? "" : profile.label || ""); setRenaming(true); }}><Pencil size={14} /></button> | |
| 220 | 新增: </div>} | |
| 221 | 新增: <div className="claude-profile-meta"> | |
| 222 | 新增: <span className="claude-profile-status" data-ready={profile.status === "ready"}>{statusLabels[profile.status] || "状态未知"}</span> | |
| 223 | 新增: {profile.email && <span className="claude-profile-email" title={[profile.email, profile.organization].filter(Boolean).join(" · ")}> | |
| 224 | 新增: {[profile.email !== displayName && profile.email, profile.organization].filter(Boolean).join(" · ")} | |
| 225 | 新增: </span>} | |
| 226 | 新增: </div> | |
| 227 | 新增: </div> | |
| 228 | 新增: <label className="check-line claude-participation"> | |
| 229 | 新增: <input type="checkbox" aria-label="参与自动分配" checked={profile.enabled} disabled={busy} | |
| 230 | 新增: onChange={(e) => { const enabled = e.target.checked; perform(() => change({ action: "update", id: profile.id, enabled })); }} /> | |
| 231 | 新增: <span className="claude-switch-track" aria-hidden="true" /> | |
| 232 | 新增: <span>{profile.enabled ? "参与分配" : "已暂停"}</span> | |
| 233 | 新增: </label> | |
| 234 | 新增: </div> | |
| 235 | 新增: <ProfileUsage quota={profile.quota} state={usage.state} /> | |
| 236 | 新增: {active > 0 && <p className="claude-profile-note">{active} 个终端仍在运行{!fromTerminal && ",关闭后可重新登录"}</p>} | |
| 237 | 新增: {!fromTerminal && defaultActive > 0 && <p className="field-help"> | |
| 238 | 新增: 其中 {defaultActive} 个工作终端仍使用普通终端的登录。若普通终端已换号,请重新打开这些会话确认身份。 | |
| 239 | 新增: </p>} | |
| 240 | 新增: {fromTerminal && ["changed", "signed_out"].includes(profile.status) && <p className="field-help"> | |
| 241 | 新增: {profile.status === "changed" ? "普通终端已换号,此账号暂不参与分配。新身份需单独加入。" : "普通终端已退出。要继续使用此账号,请先重新登录原身份。"} | |
| 242 | 新增: {active > 0 && " 原工作终端仍保留首次分配的标签。请重新打开工作会话确认身份。"} | |
| 243 | 新增: </p>} | |
| 244 | 新增: {!fromTerminal && profile.status === "changed" && <p className="field-help">请用原账号重新登录。若要使用新的身份,请点击「登录新账号」。</p>} | |
| 245 | 新增: {profile.status === "duplicate" && <p className="field-help">同一订阅只参与一次分配。请在此位置登录另一个账号。</p>} | |
| 246 | 新增: <div className="claude-profile-actions"> | |
| 247 | 新增: {fromTerminal ? <span className="claude-profile-source">普通终端账号</span> : | |
| 248 | 新增: <button className="quiet-button" disabled={busy || !!environment || active > 0} onClick={() => perform(() => login(profile.id))}> | |
| 249 | 新增: <TerminalSquare size={14} />{profile.status === "ready" ? "重新登录" : "打开登录终端"}</button>} | |
| 250 | 新增: <button className="quiet-button" disabled={busy || !!usageEnvironment || usage.state === "checking"} onClick={usage.check}> | |
| 251 | 新增: <RefreshCw size={14} />检查状态</button> | |
| 252 | 新增: {!fromTerminal && !profile.email && !active && ["pending", "signed_out", "duplicate"].includes(profile.status) && | |
| 253 | 新增: <button className="text-button" disabled={busy} onClick={() => perform(() => cancelDraft(profile))}>撤销添加</button>} | |
| 254 | 新增: <UsageNote profile={profile} state={usage.state} /> | |
| 255 | 新增: </div> | |
| 256 | 新增: </article>; | |
| 257 | 新增:} | |
| 258 | 新增: | |
| 259 | 新增:export function ClaudeAccountsPanel({ store, running, environmentBusy, tabs, login, onConfirm }) { | |
| 260 | 新增: const { accounts, detected, detectionStatus, detectionError, loginNotice, usageRunning, usageUnavailable, load, error } = store; | |
| 261 | 新增: const [busy, setBusy] = useState(false); | |
| 262 | 新增: const [requestingUsage, setRequestingUsage] = useState(false); | |
| 263 | 新增: const [actionError, setActionError] = useState(""); | |
| 264 | 新增: const visibleProfiles = useMemo(() => detected ? [detected, ...(accounts || [])] : accounts, [accounts, detected]); | |
| 265 | 新增: const environment = !running || detectionStatus === "offline" ? "offline" : | |
| 266 | 新增: detectionStatus === "update_required" ? "update_required" : ""; | |
| 267 | 新增: const usageEnvironment = environment || (usageUnavailable ? "blocked" : ""); | |
| 268 | 新增: const checking = !usageEnvironment && (usageRunning || visibleProfiles?.some((profile) => profile.usage_checking)); | |
| 269 | 新增: const activeCounts = useMemo(() => { | |
| 270 | 新增: const counts = new Map(); | |
| 271 | 新增: for (const tab of tabs) { | |
| 272 | 新增: if (!tab.claude_account_id || tab.closed) continue; | |
| 273 | 新增: const count = counts.get(tab.claude_account_id) || { all: 0, fromDefault: 0 }; | |
| 274 | 新增: count.all++; | |
| 275 | 新增: if (tab.claude_account_source === "default") count.fromDefault++; | |
| 276 | 新增: counts.set(tab.claude_account_id, count); | |
| 277 | 新增: } | |
| 278 | 新增: return counts; | |
| 279 | 新增: }, [tabs]); | |
| 280 | 新增: useEffect(() => { | |
| 281 | 新增: let requested = false, mounted = true; | |
| 282 | 新增: const openPanel = () => { | |
| 283 | 新增: if (requested || document.hidden) return; | |
| 284 | 新增: requested = true; | |
| 285 | 新增: setRequestingUsage(running); | |
| 286 | 新增: if (running) { | |
| 287 | 新增: load({ action: "usage_panel" }) | |
| 288 | 新增: .catch(() => {}) | |
| 289 | 新增: .finally(() => { if (mounted) setRequestingUsage(false); }); | |
| 290 | 新增: } else load(); | |
| 291 | 新增: }; | |
| 292 | 新增: openPanel(); | |
| 293 | 新增: document.addEventListener("visibilitychange", openPanel); | |
| 294 | 新增: return () => { mounted = false; document.removeEventListener("visibilitychange", openPanel); }; | |
| 295 | 新增: }, [load, running]); | |
| 296 | 新增: useEffect(() => { | |
| 297 | 新增: const timer = setInterval(() => { if (!document.hidden) load(undefined, true); }, checking ? 2000 : 12000); | |
| 298 | 新增: return () => clearInterval(timer); | |
| 299 | 新增: }, [load, checking]); | |
| 300 | 新增: const perform = async (operation) => { | |
| 301 | 新增: if (busy) return; | |
| 302 | 新增: setBusy(true); | |
| 303 | 新增: setActionError(""); | |
| 304 | 新增: try { await operation(); } | |
| 305 | 新增: catch (e) { setActionError(e.message); } | |
| 306 | 新增: finally { setBusy(false); } | |
| 307 | 新增: }; | |
| 308 | 新增: const cancelDraft = async (profile) => { | |
| 309 | 新增: const last = accounts.length === 1; | |
| 310 | 新增: if (await onConfirm({ title: `撤销添加「${profile.label}」?`, | |
| 311 | 新增: body: last | |
| 312 | 新增: ? "这是列表中的最后一个账号。撤销后,新建 Claude 终端会沿用环境原有的登录。虚拟机中的资料会保留。" | |
| 313 | 新增: : "此账号会从列表中移除,虚拟机中的资料会保留。", | |
| 314 | 新增: confirm: "撤销添加" })) { | |
| 315 | 新增: await load({ action: "cancel", id: profile.id }); | |
| 316 | 新增: } | |
| 317 | 新增: }; | |
| 318 | 新增: const joinDetected = async () => { | |
| 319 | 新增: try { await load({ action: "join", identity: detected.identity }); } | |
| 320 | 新增: catch (e) { | |
| 321 | 新增: await load(); // The identity shown when the user clicked may no longer be signed in. | |
| 322 | 新增: throw e; | |
| 323 | 新增: } | |
| 324 | 新增: }; | |
| 325 | 新增: return <section className="claude-profiles" aria-label="Claude 账号管理"> | |
| 326 | 新增: <div className="section-title"> | |
| 327 | 新增: <h3>Claude 账号</h3> | |
| 328 | 新增: <p>将普通终端已登录的订阅加入调度,或单独登录一个新账号。新建 Claude 终端时自动分配。</p> | |
| 329 | 新增: </div> | |
| 330 | 新增: <div className="claude-add-profile"> | |
| 331 | 新增: <button className="primary" disabled={busy || environmentBusy || !!environment} | |
| 332 | 新增: onClick={() => perform(() => login())}><Plus size={16} />登录新账号</button> | |
| 333 | 新增: </div> | |
| 334 | 新增: {(actionError || error) && <p className="account-error" role="alert">{actionError || error}</p>} | |
| 335 | 新增: {loginNotice && <p className="claude-profile-note" role="status">{loginNotice}</p>} | |
| 336 | 新增: {detectionError && <p className="account-error" role="alert">{detectionError}</p>} | |
| 337 | 新增: {usageUnavailable && !environment && <p className="claude-profile-note" role="status">{usageUnavailable}</p>} | |
| 338 | 新增: {!running ? <p className="claude-profile-note">启动 Cage 环境后可检测普通终端的登录,也可登录新账号。</p> : | |
| 339 | 新增: detectionStatus === "offline" ? <p className="claude-profile-note">工作环境就绪后可检测和登录账号。</p> : | |
| 340 | 新增: detectionStatus === "signed_out" && <p className="claude-profile-note">普通终端尚未登录 Claude 订阅。可在其中运行 <code>claude auth login</code>,登录后会在这里出现。</p>} | |
| 341 | 新增: <div className="claude-list-heading"> | |
| 342 | 新增: <h4>账号列表 <span>{visibleProfiles?.length ?? "—"}</span></h4> | |
| 343 | 新增: {requestingUsage || checking ? <small role="status">{requestingUsage ? "正在请求账号用量…" : "正在查询账号用量…"}</small> : | |
| 344 | 新增: accounts?.length > 0 && <small>{accounts.filter((a) => a.enabled).length} 个启用调度</small>} | |
| 345 | 新增: </div> | |
| 346 | 新增: <div className="claude-profile-list" role="region" aria-label="账号列表" tabIndex={0}> | |
| 347 | 新增: {accounts === null && !error && <p role="status">正在读取账号…</p>} | |
| 348 | 新增: {accounts?.length === 0 && !detected && <div className="claude-profile-empty"> | |
| 349 | 新增: <img src={crabIcon} alt="" /><p>尚无已加入调度的账号。</p><small>加入第一个账号前,新终端沿用环境原有的登录。</small> | |
| 350 | 新增: </div>} | |
| 351 | 新增: <QuotaClock accounts={visibleProfiles}> | |
| 352 | 新增: {detected && <DetectedProfile key={detected.identity} profile={detected} usageEnvironment={usageEnvironment} busy={busy || environmentBusy || !!environment} | |
| 353 | 新增: perform={perform} change={load} | |
| 354 | 新增: join={() => perform(joinDetected)} />} | |
| 355 | 新增: {accounts?.map((profile) => <ProfileCard key={profile.id} profile={profile} environment={environment} usageEnvironment={usageEnvironment} | |
| 356 | 新增: busy={busy || environmentBusy} perform={perform} change={load} login={login} cancelDraft={cancelDraft} | |
| 357 | 新增: active={activeCounts.get(profile.id)?.all || 0} defaultActive={activeCounts.get(profile.id)?.fromDefault || 0} />)} | |
| 358 | 新增: </QuotaClock> | |
| 359 | 新增: </div> | |
| 360 | 新增: </section>; | |
| 361 | 新增:} | |
| @@ -8,11 +8,17 @@ | ||
| 8 | 8 | .claude-desktop-toolbar { |
| 9 | 9 | display: flex; |
| 10 | 10 | align-items: center; |
| 11 | 删除: gap: 10px; | |
| 12 | 删除: padding: 12px 18px; | |
| 11 | 新增: flex-wrap: wrap; | |
| 12 | 新增: gap: 4px 8px; | |
| 13 | 新增: padding: 4px 12px; | |
| 13 | 14 | border-bottom: 1px solid var(--line); |
| 14 | 删除: background: var(--chrome); | |
| 15 | 删除: min-height: 55px; | |
| 15 | 新增: background: var(--toolbar); | |
| 16 | 新增: color: var(--toolbar-ink); | |
| 17 | 新增: min-height: var(--workbench-header-height); | |
| 18 | 新增:} | |
| 19 | 新增:.claude-desktop-toolbar > strong { | |
| 20 | 新增: font-size: 0.9286rem; | |
| 21 | 新增: font-weight: 500; | |
| 16 | 22 | } |
| 17 | 23 | .desktop-version, |
| 18 | 24 | .desktop-note { |
| @@ -29,7 +35,17 @@ | ||
| 29 | 35 | color: var(--muted); |
| 30 | 36 | font-size: 12px; |
| 31 | 37 | } |
| 32 | 删除:.desktop-display-size select { | |
| 38 | 新增:.desktop-display-size .inline-select { | |
| 39 | 新增: position: relative; | |
| 40 | 新增: width: 11.5em; | |
| 41 | 新增:} | |
| 42 | 新增:.desktop-display-size .inline-select-list { | |
| 43 | 新增: position: absolute; | |
| 44 | 新增: top: 100%; | |
| 45 | 新增: inset-inline: 0; | |
| 46 | 新增: z-index: 1; | |
| 47 | 新增:} | |
| 48 | 新增:.desktop-display-size .inline-select-trigger { | |
| 33 | 49 | width: auto; |
| 34 | 50 | padding: 5px 7px; |
| 35 | 51 | border: 1px solid var(--line); |
| @@ -40,7 +56,7 @@ | ||
| 40 | 56 | } |
| 41 | 57 | @media (max-width: 900px) { |
| 42 | 58 | .desktop-display-size { font-size: 0; } |
| 43 | 删除: .desktop-display-size select { font-size: 12px; } | |
| 59 | 新增: .desktop-display-size .inline-select { font-size: 12px; } | |
| 44 | 60 | } |
| 45 | 61 | .desktop-screen { |
| 46 | 62 | position: relative; |
| @@ -1,3 +1,4 @@ | ||
| 1 | 新增:import { InlineSelect } from "./inline-select"; | |
| 1 | 2 | import React, { useEffect, useRef, useState } from "react"; |
| 2 | 3 | import { |
| 3 | 4 | Download, |
| @@ -142,13 +143,13 @@ export function ClaudeDesktop({ | ||
| 142 | 143 | {desktop?.running && ( |
| 143 | 144 | <label className="desktop-display-size"> |
| 144 | 145 | 显示大小 |
| 145 | 删除: <select aria-label="Desktop 显示大小" value={zoom} onChange={(event) => { | |
| 146 | 删除: const value = Number(event.target.value); | |
| 146 | 新增: <InlineSelect aria-label="Desktop 显示大小" value={zoom} onValueChange={(next) => { | |
| 147 | 新增: const value = Number(next); | |
| 147 | 148 | setZoom(value); |
| 148 | 149 | try { localStorage.setItem("cage-desktop-zoom", String(value)); } catch { /* Session-only preference. */ } |
| 149 | 150 | }}> |
| 150 | 151 | {desktopZooms.map((value) => <option key={value} value={value}>{Math.round(value * 100)}%{value === 1 ? "(默认)" : ""}</option>)} |
| 151 | 删除: </select> | |
| 152 | 新增: </InlineSelect> | |
| 152 | 153 | </label> |
| 153 | 154 | )} |
| 154 | 155 | {desktop?.running && ( |
| @@ -1,3 +1,4 @@ | ||
| 1 | 新增:import { InlineSelect } from "./inline-select"; | |
| 1 | 2 | import React from "react"; |
| 2 | 3 | import { Globe2, LoaderCircle } from "lucide-react"; |
| 3 | 4 | import { canonicalExitPolicy } from "./safety-state.mjs"; |
| @@ -65,36 +66,36 @@ export function ExitPolicyFields({ | ||
| 65 | 66 | <> |
| 66 | 67 | <label> |
| 67 | 68 | 动态 IP 的允许范围 |
| 68 | 删除: <select | |
| 69 | 新增: <InlineSelect | |
| 70 | 新增: aria-label="动态 IP 的允许范围" | |
| 69 | 71 | value={policy.scope} |
| 70 | 删除: onChange={(e) => update("scope", e.target.value)} | |
| 72 | 新增: onValueChange={(next) => update("scope", next)} | |
| 71 | 73 | > |
| 72 | 74 | <option value="city">同一城市</option> |
| 73 | 75 | <option value="country">同一国家/地区</option> |
| 74 | 76 | <option value="any">不限地区</option> |
| 75 | 删除: </select> | |
| 77 | 新增: </InlineSelect> | |
| 76 | 78 | </label> |
| 77 | 79 | {policy.scope !== "any" && ( |
| 78 | 80 | <> |
| 79 | 81 | <label> |
| 80 | 82 | 允许的国家/地区代码 |
| 81 | 删除: <input | |
| 82 | 删除: list="cage-country-codes" | |
| 83 | 新增: <InlineSelect editable | |
| 84 | 新增: aria-label="允许的国家/地区代码" | |
| 83 | 85 | value={policy.country_code} |
| 84 | 删除: onChange={(e) => | |
| 85 | 删除: update("country_code", e.target.value.toUpperCase()) | |
| 86 | 新增: onValueChange={(next) => | |
| 87 | 新增: update("country_code", next.toUpperCase()) | |
| 86 | 88 | } |
| 87 | 89 | placeholder="例如 US;留空则在首次保存时绑定" |
| 88 | 90 | maxLength={2} |
| 89 | 91 | spellCheck="false" |
| 90 | 删除: /> | |
| 91 | 删除: <datalist id="cage-country-codes"> | |
| 92 | 新增: > | |
| 92 | 93 | {countries.map((code) => ( |
| 93 | 94 | <option key={code} value={code}> |
| 94 | 95 | {names.of(code)} |
| 95 | 96 | </option> |
| 96 | 97 | ))} |
| 97 | 删除: </datalist> | |
| 98 | 新增: </InlineSelect> | |
| 98 | 99 | </label> |
| 99 | 100 | {policy.scope === "city" && ( |
| 100 | 101 | <div className="field-row"> |
| @@ -0,0 +1,46 @@ | ||
| 1 | 新增:.inline-select { | |
| 2 | 新增: display: inline-flex; | |
| 3 | 新增: flex-direction: column; | |
| 4 | 新增: min-width: 0; | |
| 5 | 新增: max-width: 100%; | |
| 6 | 新增: color: var(--ink); | |
| 7 | 新增:} | |
| 8 | 新增:.inline-select-trigger { | |
| 9 | 新增: width: 100%; | |
| 10 | 新增: justify-content: space-between; | |
| 11 | 新增:} | |
| 12 | 新增:.inline-select-trigger > span { | |
| 13 | 新增: overflow: hidden; | |
| 14 | 新增: text-overflow: ellipsis; | |
| 15 | 新增:} | |
| 16 | 新增:.inline-select-trigger svg { flex: none; } | |
| 17 | 新增:.inline-select-trigger[aria-expanded="true"] svg { transform: rotate(180deg); } | |
| 18 | 新增:.inline-select-list { | |
| 19 | 新增: position: relative; | |
| 20 | 新增: display: grid; | |
| 21 | 新增: margin-top: 3px; | |
| 22 | 新增: padding: 3px; | |
| 23 | 新增: max-height: min(14rem, 32vh); | |
| 24 | 新增: overflow: auto; | |
| 25 | 新增: border: 1px solid var(--line); | |
| 26 | 新增: border-radius: 6px; | |
| 27 | 新增: background: var(--paper); | |
| 28 | 新增: color: var(--ink); | |
| 29 | 新增: font-size: inherit; | |
| 30 | 新增: font-weight: 400; | |
| 31 | 新增: text-align: start; | |
| 32 | 新增:} | |
| 33 | 新增:.inline-select-list [role="option"] { | |
| 34 | 新增: display: flex; | |
| 35 | 新增: align-items: center; | |
| 36 | 新增: justify-content: space-between; | |
| 37 | 新增: gap: 4px; | |
| 38 | 新增: padding: 5px 7px; | |
| 39 | 新增: border-radius: 4px; | |
| 40 | 新增: overflow-wrap: anywhere; | |
| 41 | 新增: cursor: var(--control-cursor, default); | |
| 42 | 新增:} | |
| 43 | 新增:.inline-select-list [aria-selected="true"] { background: var(--selected); } | |
| 44 | 新增:.inline-select-list [data-active], .inline-select-list [role="option"]:hover { outline: 1px solid var(--focus); outline-offset: -1px; } | |
| 45 | 新增:.inline-select-list [aria-disabled="true"] { color: var(--muted); } | |
| 46 | 新增:.inline-select-group { padding: 6px 7px 2px; color: var(--muted); font-size: .85em; } | |
| @@ -0,0 +1,196 @@ | ||
| 1 | 新增:import React, { Children, useEffect, useId, useRef, useState } from "react"; | |
| 2 | 新增:import { Check, ChevronDown } from "lucide-react"; | |
| 3 | 新增:import "./inline-select.css"; | |
| 4 | 新增: | |
| 5 | 新增:// Keep focus on the control while its list occupies space below it. | |
| 6 | 新增:export function InlineSelect({ | |
| 7 | 新增: children, | |
| 8 | 新增: value, | |
| 9 | 新增: onValueChange, | |
| 10 | 新增: disabled, | |
| 11 | 新增: editable = false, | |
| 12 | 新增: ...props | |
| 13 | 新增:}) { | |
| 14 | 新增: const id = useId(); | |
| 15 | 新增: const root = useRef(null); | |
| 16 | 新增: const control = useRef(null); | |
| 17 | 新增: const list = useRef(null); | |
| 18 | 新增: const [open, setOpen] = useState(false); | |
| 19 | 新增: const [cursor, setCursor] = useState(null); | |
| 20 | 新增: const options = Children.toArray(children).flatMap((child) => { | |
| 21 | 新增: const group = child.type === "optgroup" ? child.props.label : null; | |
| 22 | 新增: return (group ? Children.toArray(child.props.children) : [child]).map( | |
| 23 | 新增: ({ props: option }) => ({ | |
| 24 | 新增: value: String(option.value), | |
| 25 | 新增: label: | |
| 26 | 新增: Children.toArray(option.children).join("") || String(option.value), | |
| 27 | 新增: disabled: option.disabled, | |
| 28 | 新增: group, | |
| 29 | 新增: }), | |
| 30 | 新增: ); | |
| 31 | 新增: }); | |
| 32 | 新增: const selected = options.find((option) => option.value === String(value)); | |
| 33 | 新增: const filtered = | |
| 34 | 新增: editable && !selected && value | |
| 35 | 新增: ? options.filter((option) => | |
| 36 | 新增: (option.label + " " + option.value) | |
| 37 | 新增: .toLowerCase() | |
| 38 | 新增: .includes(value.toLowerCase()), | |
| 39 | 新增: ) | |
| 40 | 新增: : options; | |
| 41 | 新增: const visible = open && !disabled && filtered.length > 0; | |
| 42 | 新增: const active = filtered.findIndex( | |
| 43 | 新增: (item) => item.value === cursor && !item.disabled, | |
| 44 | 新增: ); | |
| 45 | 新增: useEffect(() => { | |
| 46 | 新增: if (visible && active >= 0) { | |
| 47 | 新增: const row = list.current.querySelector(`[data-index="${active}"]`); | |
| 48 | 新增: if (row.offsetTop < list.current.scrollTop) | |
| 49 | 新增: list.current.scrollTop = row.offsetTop; | |
| 50 | 新增: else if ( | |
| 51 | 新增: row.offsetTop + row.offsetHeight > | |
| 52 | 新增: list.current.scrollTop + list.current.clientHeight | |
| 53 | 新增: ) | |
| 54 | 新增: list.current.scrollTop = | |
| 55 | 新增: row.offsetTop + row.offsetHeight - list.current.clientHeight; | |
| 56 | 新增: } | |
| 57 | 新增: }, [visible, active]); | |
| 58 | 新增: useEffect(() => { | |
| 59 | 新增: if (!open) return; | |
| 60 | 新增: // Collapse after the outside click lands so reflow cannot move its target. | |
| 61 | 新增: const outside = (event) => { | |
| 62 | 新增: if (!root.current.contains(event.target)) setOpen(false); | |
| 63 | 新增: }; | |
| 64 | 新增: document.addEventListener("click", outside, true); | |
| 65 | 新增: return () => document.removeEventListener("click", outside, true); | |
| 66 | 新增: }, [open]); | |
| 67 | 新增: const show = () => { | |
| 68 | 新增: setCursor(selected?.value ?? null); | |
| 69 | 新增: setOpen(true); | |
| 70 | 新增: }; | |
| 71 | 新增: const choose = (item) => { | |
| 72 | 新增: if (item.disabled) return; | |
| 73 | 新增: control.current.focus(); | |
| 74 | 新增: setOpen(false); | |
| 75 | 新增: onValueChange(item.value); | |
| 76 | 新增: }; | |
| 77 | 新增: const keydown = (event) => { | |
| 78 | 新增: const key = event.key; | |
| 79 | 新增: if (event.nativeEvent.isComposing) return; | |
| 80 | 新增: if (key === "Tab") { | |
| 81 | 新增: setOpen(false); | |
| 82 | 新增: } else if (key === "Escape" && open) { | |
| 83 | 新增: event.preventDefault(); | |
| 84 | 新增: event.stopPropagation(); | |
| 85 | 新增: setOpen(false); | |
| 86 | 新增: } else if (key === "Enter" || (!editable && key === " ")) { | |
| 87 | 新增: if (editable && (!visible || active < 0)) return; | |
| 88 | 新增: event.preventDefault(); | |
| 89 | 新增: if (!visible) show(); | |
| 90 | 新增: else if (active >= 0) choose(filtered[active]); | |
| 91 | 新增: else setOpen(false); | |
| 92 | 新增: } else if ( | |
| 93 | 新增: ["ArrowUp", "ArrowDown"].includes(key) || | |
| 94 | 新增: (!editable && ["Home", "End"].includes(key)) | |
| 95 | 新增: ) { | |
| 96 | 新增: event.preventDefault(); | |
| 97 | 新增: const enabled = filtered.filter((item) => !item.disabled); | |
| 98 | 新增: const index = enabled.findIndex((item) => item.value === cursor); | |
| 99 | 新增: let next = | |
| 100 | 新增: key === "Home" | |
| 101 | 新增: ? 0 | |
| 102 | 新增: : key === "End" | |
| 103 | 新增: ? enabled.length - 1 | |
| 104 | 新增: : Math.min( | |
| 105 | 新增: enabled.length - 1, | |
| 106 | 新增: Math.max(0, index + (key === "ArrowUp" ? -1 : 1)), | |
| 107 | 新增: ); | |
| 108 | 新增: if (!visible && selected && key.startsWith("Arrow")) | |
| 109 | 新增: next = enabled.indexOf(selected); | |
| 110 | 新增: setCursor(enabled[next]?.value ?? null); | |
| 111 | 新增: setOpen(true); | |
| 112 | 新增: } | |
| 113 | 新增: }; | |
| 114 | 新增: const common = { | |
| 115 | 新增: ...props, | |
| 116 | 新增: ref: control, | |
| 117 | 新增: disabled, | |
| 118 | 新增: role: "combobox", | |
| 119 | 新增: "aria-expanded": visible, | |
| 120 | 新增: "aria-controls": visible ? id : undefined, | |
| 121 | 新增: "aria-activedescendant": | |
| 122 | 新增: visible && active >= 0 ? id + "-" + active : undefined, | |
| 123 | 新增: onKeyDown: keydown, | |
| 124 | 新增: }; | |
| 125 | 新增: return ( | |
| 126 | 新增: <span ref={root} className="inline-select"> | |
| 127 | 新增: {editable ? ( | |
| 128 | 新增: <input | |
| 129 | 新增: {...common} | |
| 130 | 新增: aria-autocomplete="list" | |
| 131 | 新增: autoComplete="off" | |
| 132 | 新增: value={value} | |
| 133 | 新增: onClick={show} | |
| 134 | 新增: onChange={(event) => { | |
| 135 | 新增: onValueChange(event.target.value); | |
| 136 | 新增: setCursor(null); | |
| 137 | 新增: setOpen(true); | |
| 138 | 新增: }} | |
| 139 | 新增: /> | |
| 140 | 新增: ) : ( | |
| 141 | 新增: <button | |
| 142 | 新增: {...common} | |
| 143 | 新增: type="button" | |
| 144 | 新增: value={value} | |
| 145 | 新增: className="inline-select-trigger" | |
| 146 | 新增: onClick={() => { | |
| 147 | 新增: control.current.focus(); | |
| 148 | 新增: open ? setOpen(false) : show(); | |
| 149 | 新增: }} | |
| 150 | 新增: > | |
| 151 | 新增: <span>{selected?.label || value}</span> | |
| 152 | 新增: <ChevronDown size={14} aria-hidden="true" /> | |
| 153 | 新增: </button> | |
| 154 | 新增: )} | |
| 155 | 新增: {visible && ( | |
| 156 | 新增: <span | |
| 157 | 新增: ref={list} | |
| 158 | 新增: id={id} | |
| 159 | 新增: role="listbox" | |
| 160 | 新增: aria-label={(props["aria-label"] || "") + "选项"} | |
| 161 | 新增: className="inline-select-list" | |
| 162 | 新增: onMouseDown={(event) => event.preventDefault()} | |
| 163 | 新增: onClick={(event) => event.preventDefault()} | |
| 164 | 新增: > | |
| 165 | 新增: {filtered.map((item, index) => ( | |
| 166 | 新增: <React.Fragment key={item.value}> | |
| 167 | 新增: {item.group && item.group !== filtered[index - 1]?.group && ( | |
| 168 | 新增: <span className="inline-select-group" aria-hidden="true"> | |
| 169 | 新增: {item.group} | |
| 170 | 新增: </span> | |
| 171 | 新增: )} | |
| 172 | 新增: <span | |
| 173 | 新增: role="option" | |
| 174 | 新增: id={id + "-" + index} | |
| 175 | 新增: data-index={index} | |
| 176 | 新增: data-value={item.value} | |
| 177 | 新增: data-active={index === active || undefined} | |
| 178 | 新增: aria-disabled={Boolean(item.disabled)} | |
| 179 | 新增: aria-selected={item === selected} | |
| 180 | 新增: onClick={() => choose(item)} | |
| 181 | 新增: > | |
| 182 | 新增: <span> | |
| 183 | 新增: {editable && item.label !== item.value | |
| 184 | 新增: ? item.value + " · " | |
| 185 | 新增: : ""} | |
| 186 | 新增: {item.label} | |
| 187 | 新增: </span> | |
| 188 | 新增: {item === selected && <Check size={14} aria-hidden="true" />} | |
| 189 | 新增: </span> | |
| 190 | 新增: </React.Fragment> | |
| 191 | 新增: ))} | |
| 192 | 新增: </span> | |
| 193 | 新增: )} | |
| 194 | 新增: </span> | |
| 195 | 新增: ); | |
| 196 | 新增:} | |
| @@ -5,10 +5,6 @@ import logo from "./logo.png"; | ||
| 5 | 5 | import React, { useEffect, useRef, useState } from "react"; |
| 6 | 6 | import { createRoot } from "react-dom/client"; |
| 7 | 7 | import { |
| 8 | 删除: ArrowLeft, | |
| 9 | 删除: ArrowRight, | |
| 10 | 删除: ArrowUpRight, | |
| 11 | 删除: Copy, | |
| 12 | 8 | Clock3, |
| 13 | 9 | FileCode2, |
| 14 | 10 | FolderOpen, |
| @@ -16,9 +12,6 @@ import { | ||
| 16 | 12 | LoaderCircle, |
| 17 | 13 | MapPin, |
| 18 | 14 | MoreHorizontal, |
| 19 | 删除: Plus, | |
| 20 | 删除: PanelLeftOpen, | |
| 21 | 删除: ChevronRight, | |
| 22 | 15 | Power, |
| 23 | 16 | RefreshCw, |
| 24 | 17 | Shield, |
| @@ -27,15 +20,16 @@ import { | ||
| 27 | 20 | } from "lucide-react"; |
| 28 | 21 | import { api, normalizeURL, native, nativeAvailable } from "./api"; |
| 29 | 22 | import { RemoteView, TerminalView, Modal } from "./views"; |
| 23 | 新增:import { usePasswordVault } from "./password-vault"; | |
| 30 | 24 | import { SettingsPanel } from "./settings"; |
| 31 | 25 | import { AppearanceProvider } from "./appearance"; |
| 32 | 26 | import { EnvironmentShield } from "./environment-shield"; |
| 33 | 27 | import { WorkspaceSidebar } from "./workspace-sidebar"; |
| 34 | 28 | import { TerminalMenu } from "./terminal-menu"; |
| 35 | 29 | import { ClaudeDesktop } from "./claude-desktop"; |
| 30 | 新增:import { useClaudeAccounts } from "./claude-accounts"; | |
| 36 | 31 | import { AccountProvider, AccountGate } from "./account"; |
| 37 | 删除:import { WorkspaceTabs } from "./workspace-tabs"; | |
| 38 | 删除:import { BrowserFavorites } from "./browser-favorites"; | |
| 32 | 新增:import { BrowserHeader, TerminalHeader, ExpandSidebar, ExpandPane } from "./pane-headers"; | |
| 39 | 33 | import { BrowserDownloads, useDownloadNotifications } from "./browser-downloads"; |
| 40 | 34 | import { BrowserUploads } from "./browser-uploads"; |
| 41 | 35 | import { AudioControls, useAudioOutput } from "./audio"; |
| @@ -43,6 +37,8 @@ import { ProjectDialog } from "./project-dialog"; | ||
| 43 | 37 | import { |
| 44 | 38 | readLocal, |
| 45 | 39 | orderedTabs, |
| 40 | 新增: focusTab, | |
| 41 | 新增: splitTab, | |
| 46 | 42 | projectName, |
| 47 | 43 | tabName, |
| 48 | 44 | } from "./workspace-state.mjs"; |
| @@ -58,6 +54,7 @@ import "./appearance.css"; | ||
| 58 | 54 | import { stopAndExit } from "./quit"; |
| 59 | 55 | |
| 60 | 56 | function App() { |
| 57 | 新增: const claudeProfiles = useClaudeAccounts(); | |
| 61 | 58 | const [desktopOpen, setDesktopOpen] = useState(false); |
| 62 | 59 | const [terminalChoice, setTerminalChoice] = useState(null); |
| 63 | 60 | const terminalTrigger = useRef(null); |
| @@ -70,9 +67,8 @@ function App() { | ||
| 70 | 67 | [settings, setSettings] = useState(null), |
| 71 | 68 | [proxy, setProxy] = useState(null), |
| 72 | 69 | [tabs, setTabs] = useState([]), |
| 73 | 删除: [active, setActive] = useState(localStorage.getItem("cage-active") || ""), | |
| 70 | 新增: [layout, setLayout] = useState(() => ({ active: localStorage.getItem("cage-active") || "" })), | |
| 74 | 71 | [browser, setBrowser] = useState({ tabs: [] }), |
| 75 | 删除: [address, setAddress] = useState(""), | |
| 76 | 72 | [settingsOpen, setSettingsOpen] = useState(false), |
| 77 | 73 | [hostGitOpen, setHostGitOpen] = useState(false), |
| 78 | 74 | [settingsSection, setSettingsSection] = useState("keyboard"), |
| @@ -92,9 +88,12 @@ function App() { | ||
| 92 | 88 | [details, setDetails] = useState(false), |
| 93 | 89 | [safetyOpen, setSafetyOpen] = useState(false), |
| 94 | 90 | [quitting, setQuitting] = useState(null); |
| 91 | 新增: const { active } = layout; | |
| 92 | 新增: const setActive = id => setLayout(previous => focusTab(previous, id)); | |
| 93 | 新增: const workspaceBox = useRef(null); | |
| 94 | 新增: const [dropSide, setDropSide] = useState(null); | |
| 95 | 95 | const terminalControls = useRef(new Map()); |
| 96 | 96 | const remote = useRef(), |
| 97 | 删除: addressField = useRef(), | |
| 98 | 97 | activeRef = useRef(active), |
| 99 | 98 | lastBrowserTab = useRef(""), |
| 100 | 99 | readyRef = useRef(false), |
| @@ -111,9 +110,73 @@ function App() { | ||
| 111 | 110 | const current = tabs.find((t) => t.id === active), |
| 112 | 111 | terminal = !desktopOpen && current?.kind === "terminal", |
| 113 | 112 | busy = Boolean(status?.job?.running), |
| 114 | 删除: showHome = !desktopOpen && (home || !status?.vm_running || !current), | |
| 115 | 删除: showRemote = !desktopOpen && status?.ready && !terminal && !showHome; | |
| 113 | 新增: showHome = !desktopOpen && (home || !status?.vm_running || !current); | |
| 114 | 新增: const other = tabs.find(tab => tab.id === layout.other); | |
| 115 | 新增: const split = Boolean(other && current && !showHome && !desktopOpen); | |
| 116 | 新增: const panes = !split ? [current].filter(Boolean) | |
| 117 | 新增: : layout.side === "left" ? [current, other] : [other, current]; | |
| 118 | 新增: const webPanes = panes.filter(tab => tab.kind !== "terminal"); | |
| 119 | 新增: const passwordVault = usePasswordVault(Boolean(status?.ready), browser.active); | |
| 120 | 新增: const dualBrowser = split && webPanes.length === 2; | |
| 121 | 新增: const leftId = dualBrowser ? panes[0].id : ""; | |
| 122 | 新增: const rightId = dualBrowser ? panes[1].id : ""; | |
| 123 | 新增: const nativeSplit = browser.split; | |
| 124 | 新增: const splitReady = dualBrowser | |
| 125 | 新增: ? nativeSplit?.left === leftId && nativeSplit?.right === rightId | |
| 126 | 新增: : !nativeSplit; | |
| 127 | 新增: const liveBrowser = webPanes.find(tab => tab.id === browser.active) || webPanes[0]; | |
| 128 | 新增: const liveBrowserVisible = !desktopOpen && !showHome && status?.ready && | |
| 129 | 新增: liveBrowser && splitReady && (!split || browser.active === liveBrowser.id); | |
| 130 | 新增: const splitQueue = useRef(Promise.resolve()); | |
| 131 | 新增: const requestedSplit = useRef(false); | |
| 132 | 新增: const nativeSplitRef = useRef(null); | |
| 133 | 新增: nativeSplitRef.current = nativeSplit; | |
| 134 | 新增: useEffect(() => { | |
| 135 | 新增: if (!status?.ready) { requestedSplit.current = false; return; } | |
| 136 | 新增: if (!leftId && !requestedSplit.current && !nativeSplitRef.current) return; | |
| 137 | 新增: requestedSplit.current = Boolean(leftId); | |
| 138 | 新增: let cancelled = false; | |
| 139 | 新增: const apply = async () => { | |
| 140 | 新增: if (cancelled) return; | |
| 141 | 新增: const id = activeRef.current; | |
| 142 | 新增: try { | |
| 143 | 新增: const result = await api("/browser/split", { left: leftId, right: rightId, | |
| 144 | 新增: id: leftId ? (id === rightId ? rightId : leftId) : id }); | |
| 145 | 新增: if (!cancelled) setBrowser(previous => ({ ...previous, split: result.split })); | |
| 146 | 新增: } catch { | |
| 147 | 新增: if (!cancelled) { | |
| 148 | 新增: setToast("无法调整浏览器分屏。请确认环境组件已更新,两个网页属于同一浏览器配置,且客机 Chromium 为 155 或更高版本。"); | |
| 149 | 新增: setLayout(previous => ({ active: previous.active })); | |
| 150 | 新增: } | |
| 151 | 新增: } | |
| 152 | 新增: }; | |
| 153 | 新增: splitQueue.current = splitQueue.current.then(apply); | |
| 154 | 新增: return () => { cancelled = true; }; | |
| 155 | 新增: }, [leftId, rightId, status?.ready, Boolean(!leftId && nativeSplit)]); | |
| 156 | 新增: const layoutRef = useRef(layout); | |
| 157 | 新增: layoutRef.current = layout; | |
| 158 | 新增: useEffect(() => { | |
| 159 | 新增: if (!layout.other) return; | |
| 160 | 新增: if (!status?.vm_running || !other || !current) { | |
| 161 | 新增: const survivor = current || other; | |
| 162 | 新增: setLayout({ active: survivor?.id || "" }); | |
| 163 | 新增: if (!current && survivor && survivor.kind !== "terminal" && status?.ready) { | |
| 164 | 新增: api("/browser/activate", { id: survivor.id }).catch(error => setToast(error.message)); | |
| 165 | 新增: } | |
| 166 | 新增: } | |
| 167 | 新增: }, [layout, other, current, status?.vm_running, status?.ready]); | |
| 168 | 新增: const paneSide = id => !split ? "" : id === active ? layout.side : | |
| 169 | 新增: layout.side === "left" ? "right" : "left"; | |
| 116 | 170 | const running = Boolean(status?.vm_running); |
| 171 | 新增: const mixedBrowserId = split && !dualBrowser ? webPanes[0]?.id : null; | |
| 172 | 新增: useEffect(() => { | |
| 173 | 新增: if (status?.ready && mixedBrowserId && mixedBrowserId !== browser.active) | |
| 174 | 新增: api("/browser/activate", { id: mixedBrowserId }).catch(error => setToast(error.message)); | |
| 175 | 新增: }, [mixedBrowserId, status?.ready, browser.active]); | |
| 176 | 新增: const finishedLogins = tabs.filter((tab) => tab.terminalKind === "claude-login" && tab.closed).map((tab) => tab.id).sort().join(","); | |
| 177 | 新增: useEffect(() => { | |
| 178 | 新增: if (finishedLogins) claudeProfiles.load(); | |
| 179 | 新增: }, [finishedLogins, claudeProfiles.load]); | |
| 117 | 180 | const audio = useAudioOutput(running && !status?.environment_update_required && !connectionError); |
| 118 | 181 | const projects = status?.projects || []; |
| 119 | 182 | const workspace = selectedProject || status?.workspace; |
| @@ -156,7 +219,7 @@ function App() { | ||
| 156 | 219 | setSettingsSection(section); |
| 157 | 220 | setSettingsOpen(true); |
| 158 | 221 | }; |
| 159 | 删除: const select = async (id) => { | |
| 222 | 新增: const select = async (id, focusContent = true) => { | |
| 160 | 223 | setDesktopOpen(false); |
| 161 | 224 | setHome(false); |
| 162 | 225 | setActive(id); |
| @@ -166,12 +229,38 @@ function App() { | ||
| 166 | 229 | if (tab && tab.kind !== "terminal") { |
| 167 | 230 | try { |
| 168 | 231 | await api("/browser/activate", { id }); |
| 169 | 删除: remote.current?.focus(); | |
| 232 | 新增: if (activeRef.current === id) { | |
| 233 | 新增: setBrowser(previous => ({ ...previous, active: id })); | |
| 234 | 新增: if (focusContent) remote.current?.focus(); | |
| 235 | 新增: } | |
| 170 | 236 | } catch (e) { |
| 171 | 237 | notify(e.message); |
| 172 | 238 | } |
| 173 | 239 | } |
| 174 | 240 | }; |
| 241 | 新增: const destination = (id, x, y) => { | |
| 242 | 新增: const box = workspaceBox.current?.getBoundingClientRect(); | |
| 243 | 新增: if (!box || busy || !running || desktopOpen || tabs.length < 2 || | |
| 244 | 新增: document.elementFromPoint(x, y)?.closest(".chrome") || | |
| 245 | 新增: !tabs.some(tab => tab.id === id) || x < box.left || x > box.right || | |
| 246 | 新增: y < box.top || y > box.bottom) return null; | |
| 247 | 新增: return x < box.left + box.width * (dualBrowser && nativeSplit?.fraction || 0.5) ? "left" : "right"; | |
| 248 | 新增: }; | |
| 249 | 新增: const splitDrag = { | |
| 250 | 新增: clear: () => setDropSide(null), | |
| 251 | 新增: hover(id, x, y) { | |
| 252 | 新增: const side = destination(id, x, y); | |
| 253 | 新增: setDropSide(side); | |
| 254 | 新增: return side; | |
| 255 | 新增: }, | |
| 256 | 新增: drop(id, x, y) { | |
| 257 | 新增: const side = destination(id, x, y); | |
| 258 | 新增: if (!side) return false; | |
| 259 | 新增: setLayout(previous => splitTab(previous, tabs, id, side)); | |
| 260 | 新增: void select(id); | |
| 261 | 新增: return true; | |
| 262 | 新增: }, | |
| 263 | 新增: }; | |
| 175 | 264 | const action = async (path, body = {}) => { |
| 176 | 265 | try { |
| 177 | 266 | return await api(path, body); |
| @@ -218,26 +307,34 @@ function App() { | ||
| 218 | 307 | setTerminalChoice((previous) => |
| 219 | 308 | previous?.anchor === anchor ? null : { path, anchor }, |
| 220 | 309 | ); |
| 221 | 删除: const createTerminal = async (path, kind) => { | |
| 310 | 新增: const createTerminal = async (path, kind, loginAccountId) => { | |
| 222 | 311 | setTerminalChoice(null); |
| 312 | 新增: const result = await api("/terminals", { | |
| 313 | 新增: workspace: path, kind, | |
| 314 | 新增: ...(loginAccountId && { claude_account_id: loginAccountId }), | |
| 315 | 新增: }); | |
| 316 | 新增: const tab = { | |
| 317 | 新增: ...result, id: "terminal:" + result.id, sessionId: result.id, | |
| 318 | 新增: terminalKind: result.kind, kind: "terminal", | |
| 319 | 新增: }; | |
| 320 | 新增: setTabs((list) => [...list.filter((t) => t.id !== tab.id), tab]); | |
| 321 | 新增: setSelectedProject(result.workspace); | |
| 223 | 322 | setDesktopOpen(false); |
| 224 | 323 | setHome(false); |
| 225 | 删除: const result = await action("/terminals", { workspace: path, kind }); | |
| 226 | 删除: if (result) { | |
| 227 | 删除: setSelectedProject(result.workspace); | |
| 228 | 删除: const tab = { | |
| 229 | 删除: ...result, | |
| 230 | 删除: id: "terminal:" + result.id, | |
| 231 | 删除: sessionId: result.id, | |
| 232 | 删除: kind: "terminal", | |
| 233 | 删除: }; | |
| 234 | 删除: setTabs((list) => [...list.filter((t) => t.id !== tab.id), tab]); | |
| 235 | 删除: setActive(tab.id); | |
| 324 | 新增: setActive(tab.id); | |
| 325 | 新增: if (kind === "claude" && result.claude_account_id && | |
| 326 | 新增: !claudeProfiles.accounts?.some((profile) => profile.id === result.claude_account_id)) { | |
| 327 | 新增: claudeProfiles.load(); | |
| 236 | 328 | } |
| 237 | 329 | }; |
| 238 | 330 | const newTerminalHere = (event) => |
| 239 | 331 | newTerminal(contentWorkspace, event?.currentTarget?.tagName === "BUTTON" |
| 240 | 332 | ? event.currentTarget : terminalTrigger.current); |
| 333 | 新增: const terminalMenuAt = (location) => terminalChoice?.anchor?.dataset.terminalLocation === location && ( | |
| 334 | 新增: <TerminalMenu choice={terminalChoice} busy={busy} | |
| 335 | 新增: onClose={() => setTerminalChoice(null)} | |
| 336 | 新增: onSelect={(kind) => createTerminal(terminalChoice.path, kind).catch((e) => notify(e.message))} /> | |
| 337 | 新增: ); | |
| 241 | 338 | const openEditor = async (path = workspace) => { |
| 242 | 339 | setDesktopOpen(false); |
| 243 | 340 | setHome(false); |
| @@ -290,7 +387,11 @@ function App() { | ||
| 290 | 387 | if (!(await action("/browser/close", { id: tab.id }))) return; |
| 291 | 388 | } |
| 292 | 389 | setTabs((list) => list.filter((t) => t.id !== tab.id)); |
| 293 | 删除: if (active === tab.id) { | |
| 390 | 新增: if (split && (tab.id === active || tab.id === other.id)) { | |
| 391 | 新增: const remaining = tab.id === active ? other.id : active; | |
| 392 | 新增: setLayout({ active: remaining }); | |
| 393 | 新增: await select(remaining); | |
| 394 | 新增: } else if (active === tab.id) { | |
| 294 | 395 | const group = displayTabs.filter((item) => |
| 295 | 396 | tab.kind === "terminal" |
| 296 | 397 | ? item.kind === "terminal" && item.workspace === tab.workspace |
| @@ -302,8 +403,7 @@ function App() { | ||
| 302 | 403 | else setActive(""); |
| 303 | 404 | } |
| 304 | 405 | }; |
| 305 | 删除: const navigate = async (e) => { | |
| 306 | 删除: e?.preventDefault(); | |
| 406 | 新增: const navigate = async (id, address) => { | |
| 307 | 407 | try { |
| 308 | 408 | const url = normalizeURL(address); |
| 309 | 409 | if (network.mode !== "open" && !isGuestLocalURL(url)) { |
| @@ -311,12 +411,7 @@ function App() { | ||
| 311 | 411 | notify("请先完成关键检查,再访问外部网站。"); |
| 312 | 412 | return; |
| 313 | 413 | } |
| 314 | 删除: if (current && current.kind !== "terminal") | |
| 315 | 删除: await action("/browser/navigate", { id: current.id, url }); | |
| 316 | 删除: else { | |
| 317 | 删除: const result = await action("/browser/new", { url }); | |
| 318 | 删除: if (result) setActive(result.id); | |
| 319 | 删除: } | |
| 414 | 新增: await action("/browser/navigate", { id, url }); | |
| 320 | 415 | remote.current?.focus(); |
| 321 | 416 | } catch (error) { |
| 322 | 417 | notify(error.message); |
| @@ -395,6 +490,7 @@ function App() { | ||
| 395 | 490 | ...item, |
| 396 | 491 | id: "terminal:" + item.id, |
| 397 | 492 | sessionId: item.id, |
| 493 | 新增: terminalKind: item.kind, | |
| 398 | 494 | kind: "terminal", |
| 399 | 495 | })), |
| 400 | 496 | ]; |
| @@ -414,7 +510,9 @@ function App() { | ||
| 414 | 510 | b.active && |
| 415 | 511 | !browserIds.current.has(b.active)) |
| 416 | 512 | ) { |
| 417 | 删除: setActive(b.active || all[0]?.id || ""); | |
| 513 | 新增: // Let split reconciliation promote the remaining pane on close. | |
| 514 | 新增: if (!layoutRef.current.other || all.some(item => item.id === activeRef.current)) | |
| 515 | 新增: setActive(b.active || all[0]?.id || ""); | |
| 418 | 516 | } |
| 419 | 517 | browserIds.current = new Set(b.tabs.map((item) => item.id)); |
| 420 | 518 | initialized.current = true; |
| @@ -476,6 +574,9 @@ function App() { | ||
| 476 | 574 | useEffect(() => { |
| 477 | 575 | if (!status?.ready) return; |
| 478 | 576 | const stream = new EventSource("/api/browser/events"); |
| 577 | 新增: stream.addEventListener("clipboard", (event) => { | |
| 578 | 新增: remote.current?.receiveCopy(JSON.parse(event.data)); | |
| 579 | 新增: }); | |
| 479 | 580 | stream.onopen = () => { browserStreamReady.current = true; }; |
| 480 | 581 | stream.onerror = () => { browserStreamReady.current = false; }; |
| 481 | 582 | stream.onmessage = (event) => { |
| @@ -485,6 +586,13 @@ function App() { | ||
| 485 | 586 | setHome(false); |
| 486 | 587 | setSettingsOpen(false); |
| 487 | 588 | } |
| 589 | 新增: const previousPair = browserSnapshot.current.split; | |
| 590 | 新增: const local = layoutRef.current; | |
| 591 | 新增: if (previousPair && !b.split && [local.active, local.other].includes(previousPair.left) && | |
| 592 | 新增: [local.active, local.other].includes(previousPair.right)) { | |
| 593 | 新增: const survivor = b.tabs.some(tab => tab.id === local.active) ? local.active : local.other; | |
| 594 | 新增: setLayout({ active: survivor }); | |
| 595 | 新增: } | |
| 488 | 596 | browserSnapshot.current = b; |
| 489 | 597 | setBrowser((previous) => ({ ...previous, ...b })); |
| 490 | 598 | setTabs((previous) => { |
| @@ -500,7 +608,7 @@ function App() { | ||
| 500 | 608 | b.active && |
| 501 | 609 | (b.focus || |
| 502 | 610 | !activeRef.current || |
| 503 | 删除: !activeRef.current.startsWith("terminal:")) | |
| 611 | 新增: (!layoutRef.current.other && !activeRef.current.startsWith("terminal:"))) | |
| 504 | 612 | ) |
| 505 | 613 | setActive(b.active); |
| 506 | 614 | browserIds.current = new Set(b.tabs.map((t) => t.id)); |
| @@ -513,11 +621,6 @@ function App() { | ||
| 513 | 621 | useEffect(() => { |
| 514 | 622 | if (current && current.kind !== "terminal") |
| 515 | 623 | lastBrowserTab.current = current.id; |
| 516 | 删除: if ( | |
| 517 | 删除: current?.kind !== "terminal" && | |
| 518 | 删除: document.activeElement !== addressField.current | |
| 519 | 删除: ) | |
| 520 | 删除: setAddress(current?.url === "about:blank" ? "" : current?.url || ""); | |
| 521 | 624 | document.title = |
| 522 | 625 | (current?.title && current.title !== "新标签页" |
| 523 | 626 | ? current.title + " · " |
| @@ -590,8 +693,9 @@ function App() { | ||
| 590 | 693 | if (k === "enter" && event.shiftKey) handle = newTerminalHere; |
| 591 | 694 | if (k === "l") |
| 592 | 695 | handle = () => { |
| 593 | 删除: addressField.current?.focus(); | |
| 594 | 删除: addressField.current?.select(); | |
| 696 | 新增: const input = [...document.querySelectorAll("[data-browser-tab]")].find(node => node.dataset.browserTab === active)?.querySelector(".address-bar input"); | |
| 697 | 新增: input?.focus(); | |
| 698 | 新增: input?.select(); | |
| 595 | 699 | }; |
| 596 | 700 | if (k === "w" && current && !desktopOpen) handle = () => closeTab(current); |
| 597 | 701 | if (/^[1-9]$/.test(k)) { |
| @@ -736,10 +840,14 @@ function App() { | ||
| 736 | 840 | desktopOpen, |
| 737 | 841 | terminalChoice, |
| 738 | 842 | ]); |
| 739 | 删除: const project = projectName(contentWorkspace); | |
| 843 | 新增: const project = projectName(contentWorkspace, status?.environment_directory); | |
| 740 | 844 | const tabLayoutKey = status?.environment_directory || status?.workspace; |
| 741 | 845 | const metadata = savedTabs[tabLayoutKey] || {}; |
| 742 | 删除: const displayTabs = orderedTabs(tabs, metadata); | |
| 846 | 新增: const claudeLabels = new Map(claudeProfiles.accounts?.map((account) => [account.id, account.label || account.email])); | |
| 847 | 新增: const terminalAccountName = (tab) => claudeLabels.get(tab.claude_account_id) || | |
| 848 | 新增: (tab.terminalKind === "claude-login" ? "新账号登录" : tab.claude_account_id ? "Claude 账号" : ""); | |
| 849 | 新增: const displayTabs = orderedTabs(tabs, metadata).map((tab) => | |
| 850 | 新增: tab.claude_account_id || tab.terminalKind === "claude-login" ? { ...tab, claudeLabel: terminalAccountName(tab) } : tab); | |
| 743 | 851 | const browserTabs = displayTabs.filter((tab) => tab.kind !== "terminal"); |
| 744 | 852 | const switchTabs = |
| 745 | 853 | terminal && !showHome |
| @@ -747,7 +855,7 @@ function App() { | ||
| 747 | 855 | (tab) => |
| 748 | 856 | tab.kind === "terminal" && tab.workspace === current.workspace, |
| 749 | 857 | ) |
| 750 | 删除: : browserTabs; | |
| 858 | 新增: : dualBrowser ? browserTabs.filter(tab => current.id === rightId ? tab.id === rightId : tab.id !== rightId) : browserTabs; | |
| 751 | 859 | const renameTab = (tab) => |
| 752 | 860 | setRename({ id: tab.id, title: tabName(tab, metadata, project) }); |
| 753 | 861 | const pinTab = (id) => |
| @@ -797,6 +905,54 @@ function App() { | ||
| 797 | 905 | setDialog(null); |
| 798 | 906 | resolve(value); |
| 799 | 907 | }; |
| 908 | 新增: const sidebarButton = side => sidebarCollapsed && side !== "right" && | |
| 909 | 新增: <ExpandSidebar onClick={() => persist("cage-sidebar-collapsed", false, setSidebarCollapsed)} />; | |
| 910 | 新增: const expandButton = tab => split && tab && <ExpandPane onClick={() => { | |
| 911 | 新增: setLayout({ active: tab.id }); | |
| 912 | 新增: void select(tab.id); | |
| 913 | 新增: }} />; | |
| 914 | 新增: const focusHeader = tab => { | |
| 915 | 新增: if (tab && tab.id !== activeRef.current) void select(tab.id, false); | |
| 916 | 新增: }; | |
| 917 | 新增: const terminalHeader = tab => { | |
| 918 | 新增: const path = tab?.workspace || workspace; | |
| 919 | 新增: const account = tab?.claude_account_id && terminalAccountName(tab); | |
| 920 | 新增: const detail = tab?.terminalKind === "claude-login" ? `登录 · ${account || "新账号"}` | |
| 921 | 新增: : account ? `Claude · ${account}${tab.claude_account_source === "default" ? "(启动时账号)" : ""}` : ""; | |
| 922 | 新增: const location = split && tab ? `heading-${tab.id}` : "heading"; | |
| 923 | 新增: return <TerminalHeader tab={tab} project={projectName(path, status?.environment_directory)} metadata={metadata} | |
| 924 | 新增: contentWorkspace={path} terminalDetail={detail} terminalDetailHint={tab?.claude_account_source === "default" | |
| 925 | 新增: ? "此终端按启动时的普通终端登录标记。若普通终端已换号,请重新打开工作会话确认身份。" : detail} | |
| 926 | 新增: ready={status.ready} running={running} busy={busy} onHome={() => setHome(true)} | |
| 927 | 新增: sidebarButton={sidebarButton(paneSide(tab?.id))} exitButton={expandButton(tab)} | |
| 928 | 新增: location={location} triggerRef={!tab || tab.id === active ? terminalTrigger : undefined} | |
| 929 | 新增: menu={terminalMenuAt(location)} onClose={() => closeTab(tab)} | |
| 930 | 新增: onEditor={() => openEditor(path)} onNew={event => newTerminal(path, event.currentTarget)} />; | |
| 931 | 新增: }; | |
| 932 | 新增: const recoverEditor = async tab => { | |
| 933 | 新增: if (!(await confirm({ title: "重启编辑器?", body: "请先保存文件。浏览器、终端和环境会继续运行。", confirm: "重启编辑器" }))) return; | |
| 934 | 新增: setRecoveringEditor(true); | |
| 935 | 新增: try { await api("/browser/editor-restart", { workspace: tab.workspace || workspace }); notify("编辑器已恢复"); } | |
| 936 | 新增: catch (error) { notify(error.message); } | |
| 937 | 新增: finally { setRecoveringEditor(false); } | |
| 938 | 新增: }; | |
| 939 | 新增: const paneTabs = tab => !dualBrowser ? browserTabs : browserTabs.filter(item => | |
| 940 | 新增: item.id === tab.id || (tab.id === leftId && item.id !== rightId)); | |
| 941 | 新增: const browserHeader = tab => <BrowserHeader vault={passwordVault} onManageVault={() => openSettings("vault")} tab={tab} tabs={paneTabs(tab)} metadata={metadata} | |
| 942 | 新增: ready={status.ready} busy={busy} focused={active === tab.id} compact={split} splitDrag={splitDrag} | |
| 943 | 新增: sidebarButton={sidebarButton(paneSide(tab.id))} exitButton={expandButton(tab)} | |
| 944 | 新增: triggerRef={tab.id === active ? terminalTrigger : undefined} | |
| 945 | 新增: location={split ? `heading-${tab.id}` : "heading"} menu={terminalMenuAt(split ? `heading-${tab.id}` : "heading")} | |
| 946 | 新增: back={browser.split?.history?.[tab.id]?.back ?? (tab.id === browser.active && browser.back)} | |
| 947 | 新增: forward={browser.split?.history?.[tab.id]?.forward ?? (tab.id === browser.active && browser.forward)} | |
| 948 | 新增: action={action} onSelect={select} onClose={closeTab} onRename={renameTab} onPin={pinTab} onReorder={reorder} | |
| 949 | 新增: onNew={newPage} onNavigate={address => navigate(tab.id, address)} onOpen={openBrowserPage} | |
| 950 | 新增: downloads={browser.downloads} onStatus={notify} onRemote={async command => { | |
| 951 | 新增: if (browser.active !== tab.id) await select(tab.id, false); | |
| 952 | 新增: if (activeRef.current === tab.id) remote.current?.[command](); | |
| 953 | 新增: }} | |
| 954 | 新增: onEditor={() => openEditor(tab.workspace || workspace)} recoveringEditor={recoveringEditor} | |
| 955 | 新增: onRecover={() => recoverEditor(tab)} />; | |
| 800 | 956 | const dialogs = ( |
| 801 | 957 | <> |
| 802 | 958 | {hostGitOpen && ( |
| @@ -935,9 +1091,11 @@ function App() { | ||
| 935 | 1091 | onClose={closeTab} |
| 936 | 1092 | onRename={renameTab} |
| 937 | 1093 | onPin={pinTab} |
| 1094 | 新增: splitDrag={splitDrag} | |
| 938 | 1095 | onReorder={reorder} |
| 939 | 1096 | onProjectSelect={setSelectedProject} |
| 940 | 1097 | onNewTerminal={newTerminal} |
| 1098 | 新增: terminalMenuAt={terminalMenuAt} | |
| 941 | 1099 | onBrowser={openBrowser} |
| 942 | 1100 | desktopOpen={desktopOpen} |
| 943 | 1101 | onClaudeWeb={() => openBrowserPage("https://claude.ai/")} |
| @@ -953,260 +1111,7 @@ function App() { | ||
| 953 | 1111 | /> |
| 954 | 1112 | )} |
| 955 | 1113 | <div className="workbench-main"> |
| 956 | 删除: {!desktopOpen && <header className="chrome"> | |
| 957 | 删除: {!showHome && !terminal ? ( | |
| 958 | 删除: <div className="browser-tab-bar"> | |
| 959 | 删除: {sidebarCollapsed && ( | |
| 960 | 删除: <button | |
| 961 | 删除: className="icon-button sidebar-expand" | |
| 962 | 删除: aria-label="展开侧栏" | |
| 963 | 删除: onClick={() => | |
| 964 | 删除: persist( | |
| 965 | 删除: "cage-sidebar-collapsed", | |
| 966 | 删除: false, | |
| 967 | 删除: setSidebarCollapsed, | |
| 968 | 删除: ) | |
| 969 | 删除: } | |
| 970 | 删除: > | |
| 971 | 删除: <img className="sidebar-expand-logo" src={logo} alt="" /> | |
| 972 | 删除: <PanelLeftOpen className="sidebar-expand-icon" size={18} /> | |
| 973 | 删除: </button> | |
| 974 | 删除: )} | |
| 975 | 删除: <WorkspaceTabs | |
| 976 | 删除: tabs={browserTabs} | |
| 977 | 删除: saved={metadata} | |
| 978 | 删除: active={active} | |
| 979 | 删除: label="浏览器标签页" | |
| 980 | 删除: horizontal | |
| 981 | 删除: busy={busy} | |
| 982 | 删除: ready={status.ready} | |
| 983 | 删除: onSelect={select} | |
| 984 | 删除: onClose={closeTab} | |
| 985 | 删除: onRename={renameTab} | |
| 986 | 删除: onPin={pinTab} | |
| 987 | 删除: onReorder={reorder} | |
| 988 | 删除: /> | |
| 989 | 删除: <button | |
| 990 | 删除: className="icon-button browser-new-tab" | |
| 991 | 删除: ref={terminalTrigger} | |
| 992 | 删除: aria-label="新建网页" | |
| 993 | 删除: title={shortcut("新建网页 ⌘T")} | |
| 994 | 删除: disabled={!status.ready || busy} | |
| 995 | 删除: onClick={newPage} | |
| 996 | 删除: > | |
| 997 | 删除: <Plus size={17} /> | |
| 998 | 删除: </button> | |
| 999 | 删除: </div> | |
| 1000 | 删除: ) : ( | |
| 1001 | 删除: <div className="content-heading"> | |
| 1002 | 删除: {sidebarCollapsed && ( | |
| 1003 | 删除: <button | |
| 1004 | 删除: className="icon-button sidebar-expand" | |
| 1005 | 删除: aria-label="展开侧栏" | |
| 1006 | 删除: title="展开侧栏" | |
| 1007 | 删除: onClick={() => | |
| 1008 | 删除: persist( | |
| 1009 | 删除: "cage-sidebar-collapsed", | |
| 1010 | 删除: false, | |
| 1011 | 删除: setSidebarCollapsed, | |
| 1012 | 删除: ) | |
| 1013 | 删除: } | |
| 1014 | 删除: > | |
| 1015 | 删除: <img className="sidebar-expand-logo" src={logo} alt="" /> | |
| 1016 | 删除: <PanelLeftOpen className="sidebar-expand-icon" size={18} /> | |
| 1017 | 删除: </button> | |
| 1018 | 删除: )} | |
| 1019 | 删除: <div className="content-breadcrumb"> | |
| 1020 | 删除: <button | |
| 1021 | 删除: onClick={() => setHome(true)} | |
| 1022 | 删除: title={contentWorkspace} | |
| 1023 | 删除: > | |
| 1024 | 删除: <FolderOpen size={15} /> | |
| 1025 | 删除: <span>{project}</span> | |
| 1026 | 删除: </button> | |
| 1027 | 删除: {!showHome && current && ( | |
| 1028 | 删除: <> | |
| 1029 | 删除: <ChevronRight size={13} /> | |
| 1030 | 删除: <span className="current-title"> | |
| 1031 | 删除: {tabName(current, metadata, project)} | |
| 1032 | 删除: </span> | |
| 1033 | 删除: </> | |
| 1034 | 删除: )} | |
| 1035 | 删除: </div> | |
| 1036 | 删除: <div className="heading-actions"> | |
| 1037 | 删除: <button | |
| 1038 | 删除: className="quiet-button" | |
| 1039 | 删除: onClick={() => openEditor(contentWorkspace)} | |
| 1040 | 删除: disabled={!status.ready || busy} | |
| 1041 | 删除: > | |
| 1042 | 删除: <FileCode2 size={15} /> | |
| 1043 | 删除: <span>打开文件</span> | |
| 1044 | 删除: </button> | |
| 1045 | 删除: <button | |
| 1046 | 删除: className="icon-button" | |
| 1047 | 删除: aria-label="新建终端" | |
| 1048 | 删除: aria-haspopup="menu" | |
| 1049 | 删除: ref={terminalTrigger} | |
| 1050 | 删除: title={shortcut("新建终端 ⌘⇧↵")} | |
| 1051 | 删除: onClick={newTerminalHere} | |
| 1052 | 删除: disabled={!running || busy} | |
| 1053 | 删除: > | |
| 1054 | 删除: <TerminalSquare size={17} /> | |
| 1055 | 删除: </button> | |
| 1056 | 删除: {current && !showHome && ( | |
| 1057 | 删除: <button | |
| 1058 | 删除: className="icon-button" | |
| 1059 | 删除: aria-label="关闭当前标签" | |
| 1060 | 删除: title={shortcut("关闭当前标签 ⌘W")} | |
| 1061 | 删除: onClick={() => closeTab(current)} | |
| 1062 | 删除: disabled={busy} | |
| 1063 | 删除: > | |
| 1064 | 删除: <X size={16} /> | |
| 1065 | 删除: </button> | |
| 1066 | 删除: )} | |
| 1067 | 删除: </div> | |
| 1068 | 删除: </div> | |
| 1069 | 删除: )} | |
| 1070 | 删除: {!showHome && ( | |
| 1071 | 删除: <div className="navigation-row"> | |
| 1072 | 删除: {!terminal ? ( | |
| 1073 | 删除: <> | |
| 1074 | 删除: <div className="nav-actions"> | |
| 1075 | 删除: <button | |
| 1076 | 删除: className="icon-button" | |
| 1077 | 删除: aria-label="后退" | |
| 1078 | 删除: disabled={!status.ready || !browser.back} | |
| 1079 | 删除: onClick={() => | |
| 1080 | 删除: action("/browser/back", { id: current?.id }) | |
| 1081 | 删除: } | |
| 1082 | 删除: > | |
| 1083 | 删除: <ArrowLeft size={17} /> | |
| 1084 | 删除: </button> | |
| 1085 | 删除: <button | |
| 1086 | 删除: className="icon-button" | |
| 1087 | 删除: aria-label="前进" | |
| 1088 | 删除: disabled={!status.ready || !browser.forward} | |
| 1089 | 删除: onClick={() => | |
| 1090 | 删除: action("/browser/forward", { id: current?.id }) | |
| 1091 | 删除: } | |
| 1092 | 删除: > | |
| 1093 | 删除: <ArrowRight size={17} /> | |
| 1094 | 删除: </button> | |
| 1095 | 删除: <button | |
| 1096 | 删除: className="icon-button" | |
| 1097 | 删除: aria-label="重新加载网页" | |
| 1098 | 删除: disabled={!showRemote} | |
| 1099 | 删除: onClick={() => | |
| 1100 | 删除: action("/browser/reload", { id: current?.id }) | |
| 1101 | 删除: } | |
| 1102 | 删除: > | |
| 1103 | 删除: <RefreshCw size={15} /> | |
| 1104 | 删除: </button> | |
| 1105 | 删除: </div> | |
| 1106 | 删除: <form className="address-bar" onSubmit={navigate}> | |
| 1107 | 删除: <Globe2 size={13} /> | |
| 1108 | 删除: <input | |
| 1109 | 删除: ref={addressField} | |
| 1110 | 删除: aria-label="网页地址或搜索" | |
| 1111 | 删除: value={address} | |
| 1112 | 删除: onChange={(e) => setAddress(e.target.value)} | |
| 1113 | 删除: onFocus={(e) => e.target.select()} | |
| 1114 | 删除: placeholder={ | |
| 1115 | 删除: status.ready | |
| 1116 | 删除: ? "输入网址或搜索,在 Cage 内打开" | |
| 1117 | 删除: : "启动环境后浏览网页" | |
| 1118 | 删除: } | |
| 1119 | 删除: disabled={!status.ready} | |
| 1120 | 删除: spellCheck="false" | |
| 1121 | 删除: /> | |
| 1122 | 删除: <button | |
| 1123 | 删除: className="address-go" | |
| 1124 | 删除: type="submit" | |
| 1125 | 删除: aria-label="打开地址" | |
| 1126 | 删除: disabled={!status.ready} | |
| 1127 | 删除: > | |
| 1128 | 删除: <ArrowUpRight size={15} /> | |
| 1129 | 删除: </button> | |
| 1130 | 删除: </form> | |
| 1131 | 删除: <BrowserFavorites current={current} ready={status.ready && !busy} onOpen={openBrowserPage} /> | |
| 1132 | 删除: <BrowserDownloads downloads={browser.downloads} ready={status.ready && !busy} onStatus={notify} /> | |
| 1133 | 删除: {current?.kind === "editor" && <button className="icon-button" aria-label="恢复编辑器" title="单独重启编辑器" disabled={!status.ready || busy || recoveringEditor} onClick={async () => { | |
| 1134 | 删除: if (!(await confirm({ title: "重启编辑器?", body: "请先保存文件。浏览器、终端和环境会继续运行。", confirm: "重启编辑器" }))) return; | |
| 1135 | 删除: setRecoveringEditor(true); | |
| 1136 | 删除: try { await api("/browser/editor-restart", { workspace: current.workspace || contentWorkspace }); notify("编辑器已恢复"); } | |
| 1137 | 删除: catch (error) { notify(error.message); } | |
| 1138 | 删除: finally { setRecoveringEditor(false); } | |
| 1139 | 删除: }}><RefreshCw size={15} className={recoveringEditor ? "spin" : ""} /></button>} | |
| 1140 | 删除: <div className="clipboard-actions"> | |
| 1141 | 删除: <button | |
| 1142 | 删除: className="icon-button" | |
| 1143 | 删除: aria-label="复制到本机" | |
| 1144 | 删除: title="复制到本机" | |
| 1145 | 删除: disabled={!showRemote} | |
| 1146 | 删除: onClick={() => remote.current?.copy()} | |
| 1147 | 删除: > | |
| 1148 | 删除: <Copy size={15} /> | |
| 1149 | 删除: </button> | |
| 1150 | 删除: <button | |
| 1151 | 删除: className="icon-button" | |
| 1152 | 删除: aria-label="粘贴到 Cage" | |
| 1153 | 删除: title="粘贴到 Cage" | |
| 1154 | 删除: disabled={!showRemote} | |
| 1155 | 删除: onClick={() => remote.current?.paste()} | |
| 1156 | 删除: > | |
| 1157 | 删除: <svg | |
| 1158 | 删除: width="15" | |
| 1159 | 删除: height="15" | |
| 1160 | 删除: viewBox="0 0 24 24" | |
| 1161 | 删除: fill="none" | |
| 1162 | 删除: stroke="currentColor" | |
| 1163 | 删除: strokeWidth="1.7" | |
| 1164 | 删除: > | |
| 1165 | 删除: <path d="M9 5H5v16h14V5h-4M9 3h6v4H9zM8 12h8M8 16h5" /> | |
| 1166 | 删除: </svg> | |
| 1167 | 删除: </button> | |
| 1168 | 删除: <button | |
| 1169 | 删除: className="icon-button" | |
| 1170 | 删除: aria-label="文本传递" | |
| 1171 | 删除: title="文本传递" | |
| 1172 | 删除: disabled={!showRemote} | |
| 1173 | 删除: onClick={() => remote.current?.transfer()} | |
| 1174 | 删除: > | |
| 1175 | 删除: <MoreHorizontal size={17} /> | |
| 1176 | 删除: </button> | |
| 1177 | 删除: </div> | |
| 1178 | 删除: </> | |
| 1179 | 删除: ) : ( | |
| 1180 | 删除: <> | |
| 1181 | 删除: <div className="terminal-path"> | |
| 1182 | 删除: <TerminalSquare size={15} /> | |
| 1183 | 删除: <span>{current?.workspace || status.workspace}</span> | |
| 1184 | 删除: <span className="terminal-kind">Linux · bash</span> | |
| 1185 | 删除: </div> | |
| 1186 | 删除: <button | |
| 1187 | 删除: className="text-button" | |
| 1188 | 删除: aria-haspopup="menu" | |
| 1189 | 删除: onClick={newTerminalHere} | |
| 1190 | 删除: disabled={busy} | |
| 1191 | 删除: > | |
| 1192 | 删除: <Plus size={15} /> | |
| 1193 | 删除: 新建终端 | |
| 1194 | 删除: </button> | |
| 1195 | 删除: </> | |
| 1196 | 删除: )} | |
| 1197 | 删除: <button | |
| 1198 | 删除: className="icon-button files-button" | |
| 1199 | 删除: title="打开文件编辑器" | |
| 1200 | 删除: aria-label="打开文件编辑器" | |
| 1201 | 删除: disabled={!status.ready || busy} | |
| 1202 | 删除: onClick={() => openEditor(contentWorkspace)} | |
| 1203 | 删除: > | |
| 1204 | 删除: <FileCode2 size={17} /> | |
| 1205 | 删除: </button> | |
| 1206 | 删除: </div> | |
| 1207 | 删除: )} | |
| 1208 | 删除: {busy && <div className="progress-line" />} | |
| 1209 | 删除: </header>} | |
| 1114 | 新增: {showHome && terminalHeader(null)} | |
| 1210 | 1115 | {connectionError && ( |
| 1211 | 1116 | <div className="connection-banner" role="alert"> |
| 1212 | 1117 | 工作台连接中断,后台状态暂时未知。 |
| @@ -1219,7 +1124,9 @@ function App() { | ||
| 1219 | 1124 | </button> |
| 1220 | 1125 | </div> |
| 1221 | 1126 | )} |
| 1222 | 删除: <main className="workspace"> | |
| 1127 | 新增: <main className={`workspace ${split ? "workspace-split" : ""}`} ref={workspaceBox} | |
| 1128 | 新增: style={{ "--split-left": `${100 * (dualBrowser && nativeSplit?.fraction || 0.5)}%` }}> | |
| 1129 | 新增: {dropSide && <div aria-hidden="true" className={`split-drop split-${dropSide}`}>{dropSide === "left" ? "放到左侧" : "放到右侧"}</div>} | |
| 1223 | 1130 | {desktopOpen && <ClaudeDesktop |
| 1224 | 1131 | onProjectOpened={() => refreshStatus.current?.()} |
| 1225 | 1132 | status={status} visible={!settingsOpen} remoteRef={remote} |
| @@ -1236,49 +1143,51 @@ function App() { | ||
| 1236 | 1143 | )} |
| 1237 | 1144 | {(status.vm_running || terminal) && ( |
| 1238 | 1145 | <> |
| 1239 | 删除: {status.ready && !desktopOpen ? ( | |
| 1240 | 删除: <RemoteView | |
| 1241 | 删除: ref={remote} | |
| 1242 | 删除: visible={Boolean(showRemote && !settingsOpen)} | |
| 1243 | 删除: keyboard={status.keyboard} | |
| 1244 | 删除: tabId={current?.id} | |
| 1245 | 删除: onStatus={notify} | |
| 1246 | 删除: onFallback={(text, message) => | |
| 1247 | 删除: setTransfer({ text, message }) | |
| 1248 | 删除: } | |
| 1249 | 删除: /> | |
| 1250 | 删除: ) : ( | |
| 1251 | 删除: !desktopOpen && !terminal && | |
| 1252 | 删除: !showHome && ( | |
| 1253 | 删除: <div className="view-overlay"> | |
| 1254 | 删除: <RefreshCw /> | |
| 1255 | 删除: <h3>浏览器连接暂时不可用</h3> | |
| 1256 | 删除: <p>环境和终端仍可运行;恢复浏览器不会停止现有终端。</p> | |
| 1257 | 删除: <button | |
| 1258 | 删除: className="primary" | |
| 1259 | 删除: disabled={busy} | |
| 1260 | 删除: onClick={() => setHostGitOpen(true)} | |
| 1261 | 删除: > | |
| 1262 | 删除: 恢复浏览器 | |
| 1263 | 删除: </button> | |
| 1146 | 新增: {!desktopOpen && !showHome && webPanes.length > 0 && ( | |
| 1147 | 新增: <section className={`pane-lane browser-lane ${dualBrowser ? "" : "split-" + paneSide(webPanes[0].id)}`}> | |
| 1148 | 新增: <div className="browser-headers">{webPanes.map(tab => | |
| 1149 | 新增: <div key={paneSide(tab.id) || "single"} className="browser-header-cell" data-focused={active === tab.id} | |
| 1150 | 新增: onPointerDownCapture={() => focusHeader(tab)} onFocusCapture={() => focusHeader(tab)}> | |
| 1151 | 新增: {browserHeader(tab)} | |
| 1152 | 新增: </div>)}</div> | |
| 1153 | 新增: <div className="pane-body" onPointerDownCapture={() => { | |
| 1154 | 新增: if (!dualBrowser && liveBrowser?.id !== active) focusHeader(liveBrowser); | |
| 1155 | 新增: }}> | |
| 1156 | 新增: {status.ready && <RemoteView ref={remote} visible={Boolean(liveBrowserVisible && !settingsOpen)} | |
| 1157 | 新增: copyScope={webPanes.map(tab => `${tab.id}:${tab.document || ""}`).join("|")} | |
| 1158 | 新增: focused={dualBrowser || liveBrowser?.id === active} keyboard={status.keyboard} | |
| 1159 | 新增: tabId={liveBrowser?.id} onStatus={notify} | |
| 1160 | 新增: onFallback={(text, message) => setTransfer({ text, message })} />} | |
| 1161 | 新增: {!status.ready && <div className="view-overlay"> | |
| 1162 | 新增: <RefreshCw /><h3>浏览器连接暂时不可用</h3> | |
| 1163 | 新增: <p>环境和终端仍可运行;恢复浏览器不会停止现有终端。</p> | |
| 1164 | 新增: <button className="primary" disabled={busy} onClick={() => setHostGitOpen(true)}>恢复浏览器</button> | |
| 1165 | 新增: </div>} | |
| 1166 | 新增: {status.ready && !splitReady && <div className="view-overlay">正在调整浏览器布局…</div>} | |
| 1264 | 1167 | </div> |
| 1265 | 删除: ) | |
| 1168 | 新增: </section> | |
| 1266 | 1169 | )} |
| 1267 | 删除: {tabs | |
| 1268 | 删除: .filter((t) => t.kind === "terminal") | |
| 1269 | 删除: .map((tab) => ( | |
| 1270 | 删除: <TerminalView | |
| 1271 | 删除: key={tab.id} | |
| 1272 | 删除: session={{ ...tab, id: tab.sessionId }} | |
| 1273 | 删除: onControls={(control) => | |
| 1274 | 删除: control | |
| 1275 | 删除: ? terminalControls.current.set(tab.id, control) | |
| 1276 | 删除: : terminalControls.current.delete(tab.id) | |
| 1277 | 删除: } | |
| 1278 | 删除: visible={!desktopOpen && active === tab.id && !showHome && !settingsOpen} | |
| 1279 | 删除: onStatus={notify} | |
| 1280 | 删除: /> | |
| 1281 | 删除: ))} | |
| 1170 | 新增: {tabs.filter(t => t.kind === "terminal").map(tab => { | |
| 1171 | 新增: const visible = !desktopOpen && !showHome && panes.some(pane => pane.id === tab.id); | |
| 1172 | 新增: return <section key={tab.id} className={`pane-lane terminal-lane split-${paneSide(tab.id)}`} | |
| 1173 | 新增: data-focused={active === tab.id} hidden={!visible} | |
| 1174 | 新增: onPointerDownCapture={() => focusHeader(tab)} onFocusCapture={() => focusHeader(tab)}> | |
| 1175 | 新增: {visible && terminalHeader(tab)} | |
| 1176 | 新增: <div className="pane-body"> | |
| 1177 | 新增: <TerminalView | |
| 1178 | 新增: session={{ ...tab, id: tab.sessionId }} | |
| 1179 | 新增: onControls={(control) => | |
| 1180 | 新增: control | |
| 1181 | 新增: ? terminalControls.current.set(tab.id, control) | |
| 1182 | 新增: : terminalControls.current.delete(tab.id) | |
| 1183 | 新增: } | |
| 1184 | 新增: visible={visible && !settingsOpen} | |
| 1185 | 新增: focused={active === tab.id} | |
| 1186 | 新增: onStatus={notify} | |
| 1187 | 新增: /> | |
| 1188 | 新增: </div> | |
| 1189 | 新增: </section>; | |
| 1190 | 新增: })} | |
| 1282 | 1191 | </> |
| 1283 | 1192 | )} |
| 1284 | 1193 | {showHome && ( |
| @@ -1362,6 +1271,7 @@ function App() { | ||
| 1362 | 1271 | </span> |
| 1363 | 1272 | <button |
| 1364 | 1273 | className="primary" |
| 1274 | 新增: data-terminal-location="start" | |
| 1365 | 1275 | disabled={busy || Boolean(connectionError)} |
| 1366 | 1276 | onClick={(event) => { |
| 1367 | 1277 | if (!running && setupProxy) openSettings("network"); |
| @@ -1398,10 +1308,11 @@ function App() { | ||
| 1398 | 1308 | : "新建终端"} |
| 1399 | 1309 | </button> |
| 1400 | 1310 | </div> |
| 1311 | 新增: {terminalMenuAt("start")} | |
| 1401 | 1312 | </div> |
| 1402 | 1313 | {running && ( |
| 1403 | 1314 | <div className="welcome-shortcuts"> |
| 1404 | 删除: <button onClick={newTerminalHere} aria-haspopup="menu" disabled={busy}> | |
| 1315 | 新增: <button onClick={newTerminalHere} data-terminal-location="shortcuts" aria-haspopup="menu" disabled={busy}> | |
| 1405 | 1316 | <TerminalSquare size={16} /> |
| 1406 | 1317 | 新建终端 |
| 1407 | 1318 | </button> |
| @@ -1414,6 +1325,7 @@ function App() { | ||
| 1414 | 1325 | </button> |
| 1415 | 1326 | </div> |
| 1416 | 1327 | )} |
| 1328 | 新增: {terminalMenuAt("shortcuts")} | |
| 1417 | 1329 | {!running && ( |
| 1418 | 1330 | <p className="welcome-hint"> |
| 1419 | 1331 | {setupProxy |
| @@ -1545,6 +1457,9 @@ function App() { | ||
| 1545 | 1457 | current={settings} |
| 1546 | 1458 | status={status} |
| 1547 | 1459 | initialSection={settingsSection} |
| 1460 | 新增: claudeProfiles={claudeProfiles} | |
| 1461 | 新增: terminalTabs={tabs} | |
| 1462 | 新增: onClaudeLogin={(id) => createTerminal(workspace, "claude-login", id)} | |
| 1548 | 1463 | onClose={() => setSettingsOpen(false)} |
| 1549 | 1464 | onSaved={refreshSettings} |
| 1550 | 1465 | onConfirm={confirm} |
| @@ -1559,14 +1474,6 @@ function App() { | ||
| 1559 | 1474 | onOpened={openedProject} |
| 1560 | 1475 | /> |
| 1561 | 1476 | )} |
| 1562 | 删除: {terminalChoice !== null && ( | |
| 1563 | 删除: <TerminalMenu | |
| 1564 | 删除: choice={terminalChoice} | |
| 1565 | 删除: busy={busy} | |
| 1566 | 删除: onClose={() => setTerminalChoice(null)} | |
| 1567 | 删除: onSelect={(kind) => createTerminal(terminalChoice.path, kind)} | |
| 1568 | 删除: /> | |
| 1569 | 删除: )} | |
| 1570 | 1477 | {rename && ( |
| 1571 | 1478 | <Modal |
| 1572 | 1479 | title="重命名标签" |
| @@ -0,0 +1,242 @@ | ||
| 1 | 新增:import React, { useEffect, useState } from "react"; | |
| 2 | 新增:import { ArrowLeft, ArrowRight, ArrowUpRight, ChevronRight, Copy, FileCode2, FolderOpen, | |
| 3 | 新增: Globe2, Maximize2, MoreHorizontal, PanelLeftOpen, Plus, RefreshCw, TerminalSquare, X } from "lucide-react"; | |
| 4 | 新增:import { BrowserVaultBar } from "./password-vault"; | |
| 5 | 新增:import { WorkspaceTabs } from "./workspace-tabs"; | |
| 6 | 新增:import { BrowserFavorites } from "./browser-favorites"; | |
| 7 | 新增:import { BrowserDownloads } from "./browser-downloads"; | |
| 8 | 新增:import { tabName } from "./workspace-state.mjs"; | |
| 9 | 新增:import { shortcut } from "./platform.mjs"; | |
| 10 | 新增:import logo from "./logo.png"; | |
| 11 | 新增: | |
| 12 | 新增:export const ExpandSidebar = ({ onClick }) => <button className="icon-button sidebar-expand" | |
| 13 | 新增: aria-label="展开侧栏" onClick={onClick}> | |
| 14 | 新增: <img className="sidebar-expand-logo" src={logo} alt="" /> | |
| 15 | 新增: <PanelLeftOpen className="sidebar-expand-icon" size={18} /> | |
| 16 | 新增:</button>; | |
| 17 | 新增: | |
| 18 | 新增:export const ExpandPane = ({ onClick }) => <button className="icon-button expand-pane" | |
| 19 | 新增: aria-label="退出分屏" title="在整个工作区显示此页" onClick={onClick}><Maximize2 size={14} /></button>; | |
| 20 | 新增: | |
| 21 | 新增:export function TerminalHeader({ tab, contentWorkspace, project, metadata, terminalDetail, terminalDetailHint, | |
| 22 | 新增: onHome, ready, running, busy, onEditor, onNew, onClose, sidebarButton, exitButton, location, triggerRef, menu }) { | |
| 23 | 新增: return <header className="chrome terminal-chrome"> | |
| 24 | 新增: <div className="content-heading"> | |
| 25 | 新增: {sidebarButton} | |
| 26 | 新增: <div className="content-breadcrumb"> | |
| 27 | 新增: <button | |
| 28 | 新增: onClick={onHome} | |
| 29 | 新增: title={contentWorkspace} | |
| 30 | 新增: > | |
| 31 | 新增: <FolderOpen size={15} /> | |
| 32 | 新增: <span>{project}</span> | |
| 33 | 新增: </button> | |
| 34 | 新增: {tab && ( | |
| 35 | 新增: <> | |
| 36 | 新增: <ChevronRight size={13} /> | |
| 37 | 新增: <span className="current-title" title={tabName(tab, metadata, project)}> | |
| 38 | 新增: {tabName(tab, metadata, project)} | |
| 39 | 新增: </span> | |
| 40 | 新增: {terminalDetail && <span className="terminal-detail" title={terminalDetailHint}>{terminalDetail}</span>} | |
| 41 | 新增: </> | |
| 42 | 新增: )} | |
| 43 | 新增: </div> | |
| 44 | 新增: <div className="heading-actions"> | |
| 45 | 新增: <button | |
| 46 | 新增: className="icon-button" | |
| 47 | 新增: aria-label="打开文件" | |
| 48 | 新增: title="打开文件" | |
| 49 | 新增: onClick={onEditor} | |
| 50 | 新增: disabled={!ready || busy} | |
| 51 | 新增: > | |
| 52 | 新增: <FileCode2 size={15} /> | |
| 53 | 新增: </button> | |
| 54 | 新增: <button | |
| 55 | 新增: className="icon-button" | |
| 56 | 新增: aria-label="新建终端" | |
| 57 | 新增: aria-haspopup="menu" | |
| 58 | 新增: data-terminal-location={location} | |
| 59 | 新增: ref={triggerRef} | |
| 60 | 新增: title={shortcut("新建终端 ⌘⇧↵")} | |
| 61 | 新增: onClick={onNew} | |
| 62 | 新增: disabled={!running || busy} | |
| 63 | 新增: > | |
| 64 | 新增: <TerminalSquare size={17} /> | |
| 65 | 新增: </button> | |
| 66 | 新增: {tab && ( | |
| 67 | 新增: <button | |
| 68 | 新增: className="icon-button" | |
| 69 | 新增: aria-label="关闭当前标签" | |
| 70 | 新增: title={shortcut("关闭当前标签 ⌘W")} | |
| 71 | 新增: onClick={onClose} | |
| 72 | 新增: disabled={busy} | |
| 73 | 新增: > | |
| 74 | 新增: <X size={16} /> | |
| 75 | 新增: </button> | |
| 76 | 新增: )} | |
| 77 | 新增: {exitButton} | |
| 78 | 新增: </div> | |
| 79 | 新增: </div> | |
| 80 | 新增: {menu} | |
| 81 | 新增: {busy && <div className="progress-line" />} | |
| 82 | 新增: </header>; | |
| 83 | 新增:} | |
| 84 | 新增: | |
| 85 | 新增:export function BrowserHeader({ vault, onManageVault, tab, tabs, metadata, ready, busy, focused, compact, triggerRef, | |
| 86 | 新增: sidebarButton, exitButton, splitDrag, onSelect, onClose, onRename, onPin, onReorder, onNew, | |
| 87 | 新增: location, menu, back, forward, action, onNavigate, onOpen, downloads, onStatus, onRemote, onEditor, onRecover, recoveringEditor }) { | |
| 88 | 新增: const [address, setAddress] = useState(""); | |
| 89 | 新增: const [toolsOpen, setToolsOpen] = useState(false); | |
| 90 | 新增: const url = tab.url === "about:blank" ? "" : tab.url || ""; | |
| 91 | 新增: useEffect(() => { setAddress(url); }, [tab.id, url]); | |
| 92 | 新增: return <header className={`chrome browser-chrome ${compact ? "split-chrome" : ""}`} data-browser-tab={tab.id}> | |
| 93 | 新增: <div className="browser-tab-bar"> | |
| 94 | 新增: {sidebarButton} | |
| 95 | 新增: <WorkspaceTabs | |
| 96 | 新增: tabs={tabs} | |
| 97 | 新增: saved={metadata} | |
| 98 | 新增: active={tab.id} | |
| 99 | 新增: label="浏览器标签页" | |
| 100 | 新增: horizontal | |
| 101 | 新增: busy={busy} | |
| 102 | 新增: ready={ready} | |
| 103 | 新增: onSelect={onSelect} | |
| 104 | 新增: onClose={onClose} | |
| 105 | 新增: onRename={onRename} | |
| 106 | 新增: onPin={onPin} | |
| 107 | 新增: splitDrag={splitDrag} | |
| 108 | 新增: onReorder={onReorder} | |
| 109 | 新增: /> | |
| 110 | 新增: <button | |
| 111 | 新增: className="icon-button browser-new-tab" | |
| 112 | 新增: ref={triggerRef} | |
| 113 | 新增: data-terminal-location={location} | |
| 114 | 新增: aria-label="新建网页" | |
| 115 | 新增: title={shortcut("新建网页 ⌘T")} | |
| 116 | 新增: disabled={!ready || busy} | |
| 117 | 新增: onClick={onNew} | |
| 118 | 新增: > | |
| 119 | 新增: <Plus size={17} /> | |
| 120 | 新增: </button> | |
| 121 | 新增: {exitButton} | |
| 122 | 新增: </div> | |
| 123 | 新增: <div className="navigation-row"> | |
| 124 | 新增: <div className="nav-actions"> | |
| 125 | 新增: <button | |
| 126 | 新增: className="icon-button" | |
| 127 | 新增: aria-label="后退" | |
| 128 | 新增: disabled={!ready || !back} | |
| 129 | 新增: onClick={() => | |
| 130 | 新增: action("/browser/back", { id: tab.id }) | |
| 131 | 新增: } | |
| 132 | 新增: > | |
| 133 | 新增: <ArrowLeft size={17} /> | |
| 134 | 新增: </button> | |
| 135 | 新增: <button | |
| 136 | 新增: className="icon-button" | |
| 137 | 新增: aria-label="前进" | |
| 138 | 新增: disabled={!ready || !forward} | |
| 139 | 新增: onClick={() => | |
| 140 | 新增: action("/browser/forward", { id: tab.id }) | |
| 141 | 新增: } | |
| 142 | 新增: > | |
| 143 | 新增: <ArrowRight size={17} /> | |
| 144 | 新增: </button> | |
| 145 | 新增: <button | |
| 146 | 新增: className="icon-button" | |
| 147 | 新增: aria-label="重新加载网页" | |
| 148 | 新增: disabled={!ready} | |
| 149 | 新增: onClick={() => | |
| 150 | 新增: action("/browser/reload", { id: tab.id }) | |
| 151 | 新增: } | |
| 152 | 新增: > | |
| 153 | 新增: <RefreshCw size={15} /> | |
| 154 | 新增: </button> | |
| 155 | 新增: </div> | |
| 156 | 新增: <form className="address-bar" onSubmit={event => { event.preventDefault(); onNavigate(address); }}> | |
| 157 | 新增: <Globe2 size={13} /> | |
| 158 | 新增: <input | |
| 159 | 新增: aria-label="网页地址或搜索" | |
| 160 | 新增: value={address} | |
| 161 | 新增: onChange={(e) => setAddress(e.target.value)} | |
| 162 | 新增: onFocus={(e) => e.target.select()} | |
| 163 | 新增: placeholder={ | |
| 164 | 新增: ready | |
| 165 | 新增: ? "输入网址或搜索,在 Cage 内打开" | |
| 166 | 新增: : "启动环境后浏览网页" | |
| 167 | 新增: } | |
| 168 | 新增: disabled={!ready} | |
| 169 | 新增: spellCheck="false" | |
| 170 | 新增: /> | |
| 171 | 新增: <button | |
| 172 | 新增: className="address-go" | |
| 173 | 新增: type="submit" | |
| 174 | 新增: aria-label="打开地址" | |
| 175 | 新增: disabled={!ready} | |
| 176 | 新增: > | |
| 177 | 新增: <ArrowUpRight size={15} /> | |
| 178 | 新增: </button> | |
| 179 | 新增: </form> | |
| 180 | 新增: {compact && <button className="icon-button" aria-label="更多网页工具" aria-expanded={toolsOpen} | |
| 181 | 新增: onClick={() => setToolsOpen(!toolsOpen)}><MoreHorizontal size={16} /></button>} | |
| 182 | 新增: <div className={`browser-tools ${toolsOpen ? "open" : ""}`}> | |
| 183 | 新增: <BrowserFavorites current={tab} shortcuts={focused} ready={ready && !busy} onOpen={onOpen} /> | |
| 184 | 新增: <BrowserDownloads downloads={downloads} ready={ready && !busy} onStatus={onStatus} /> | |
| 185 | 新增: {tab.kind === "editor" && <button className="icon-button" aria-label="恢复编辑器" title="单独重启编辑器" | |
| 186 | 新增: disabled={!ready || busy || recoveringEditor} onClick={onRecover}> | |
| 187 | 新增: <RefreshCw size={15} className={recoveringEditor ? "spin" : ""} /> | |
| 188 | 新增: </button>} | |
| 189 | 新增: <div className="clipboard-actions"> | |
| 190 | 新增: <button | |
| 191 | 新增: className="icon-button" | |
| 192 | 新增: aria-label="复制到本机" | |
| 193 | 新增: title="复制到本机" | |
| 194 | 新增: disabled={!ready} | |
| 195 | 新增: onClick={() => onRemote("copy")} | |
| 196 | 新增: > | |
| 197 | 新增: <Copy size={15} /> | |
| 198 | 新增: </button> | |
| 199 | 新增: <button | |
| 200 | 新增: className="icon-button" | |
| 201 | 新增: aria-label="粘贴到 Cage" | |
| 202 | 新增: title="粘贴到 Cage" | |
| 203 | 新增: disabled={!ready} | |
| 204 | 新增: onClick={() => onRemote("paste")} | |
| 205 | 新增: > | |
| 206 | 新增: <svg | |
| 207 | 新增: width="15" | |
| 208 | 新增: height="15" | |
| 209 | 新增: viewBox="0 0 24 24" | |
| 210 | 新增: fill="none" | |
| 211 | 新增: stroke="currentColor" | |
| 212 | 新增: strokeWidth="1.7" | |
| 213 | 新增: > | |
| 214 | 新增: <path d="M9 5H5v16h14V5h-4M9 3h6v4H9zM8 12h8M8 16h5" /> | |
| 215 | 新增: </svg> | |
| 216 | 新增: </button> | |
| 217 | 新增: <button | |
| 218 | 新增: className="icon-button" | |
| 219 | 新增: aria-label="文本传递" | |
| 220 | 新增: title="文本传递" | |
| 221 | 新增: disabled={!ready} | |
| 222 | 新增: onClick={() => onRemote("transfer")} | |
| 223 | 新增: > | |
| 224 | 新增: <MoreHorizontal size={17} /> | |
| 225 | 新增: </button> | |
| 226 | 新增: </div> | |
| 227 | 新增: <button | |
| 228 | 新增: className="icon-button files-button" | |
| 229 | 新增: title="打开文件编辑器" | |
| 230 | 新增: aria-label="打开文件编辑器" | |
| 231 | 新增: disabled={!ready || busy} | |
| 232 | 新增: onClick={onEditor} | |
| 233 | 新增: > | |
| 234 | 新增: <FileCode2 size={17} /> | |
| 235 | 新增: </button> | |
| 236 | 新增: </div> | |
| 237 | 新增: </div> | |
| 238 | 新增: {vault && tab.kind !== "editor" && <BrowserVaultBar tab={tab} vault={vault} ready={ready} onManage={onManageVault} />} | |
| 239 | 新增: {menu} | |
| 240 | 新增: {busy && <div className="progress-line" />} | |
| 241 | 新增: </header>; | |
| 242 | 新增:} | |
| @@ -0,0 +1,32 @@ | ||
| 1 | 新增:.vault-settings { max-width: 720px; } | |
| 2 | 新增:.vault-note { display: flex; align-items: flex-start; gap: 10px; padding: 12px 0 24px; color: var(--muted); font-size: 0.8571rem; line-height: 1.6; } | |
| 3 | 新增:.vault-note svg { flex: none; margin-top: 3px; } | |
| 4 | 新增:.vault-toolbar { display: flex; align-items: center; gap: 16px; margin-bottom: 16px; } | |
| 5 | 新增:.vault-toolbar .vault-search { flex: 1; margin-bottom: 0 !important; } | |
| 6 | 新增:.vault-search span, .vault-toolbar > button { display: flex; align-items: center; gap: 8px; } | |
| 7 | 新增:.vault-toolbar > button { margin-top: 24px; flex: none; } | |
| 8 | 新增:.vault-editor, .vault-entry { padding: 20px; border: 1px solid var(--line); border-radius: 8px; margin-bottom: 12px; background: var(--paper); overflow-wrap: anywhere; } | |
| 9 | 新增:.vault-editor h4 { margin-top: 0; } | |
| 10 | 新增:.vault-editor fieldset { border: 0; padding: 0; margin: 0; min-width: 0; } | |
| 11 | 新增:.vault-entry strong { font-size: 0.9286rem; font-weight: 600; } | |
| 12 | 新增:.vault-entry span { display: block; color: var(--muted); margin-top: 6px; } | |
| 13 | 新增:.vault-actions { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 16px; } | |
| 14 | 新增:.vault-actions button { font-size: 0.8571rem; } | |
| 15 | 新增:.vault-revealed { display: flex; align-items: center; gap: 12px; margin-top: 12px; } | |
| 16 | 新增:.vault-revealed output { overflow-wrap: anywhere; min-width: 0; font-family: var(--font-code, monospace); } | |
| 17 | 新增:.vault-empty { text-align: center; padding: 40px 16px; color: var(--muted); } | |
| 18 | 新增:.vault-empty p { color: var(--ink); } | |
| 19 | 新增:.vault-blocked { margin: 24px 0; } | |
| 20 | 新增:.vault-blocked > div { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin: 12px 0; overflow-wrap: anywhere; } | |
| 21 | 新增:.vault-browser { border-top: 1px solid var(--line); padding: 4px 14px; font-size: 0.7857rem; flex: none; } | |
| 22 | 新增:.vault-browser-heading { display: flex; align-items: center; flex-wrap: wrap; gap: 12px; min-height: 26px; } | |
| 23 | 新增:.vault-browser-heading button { display: inline-flex; align-items: center; gap: 6px; padding: 4px 0; } | |
| 24 | 新增:.vault-browser-heading > span { color: var(--muted); } | |
| 25 | 新增:.vault-save, .vault-picker { padding: 12px 0; overflow-wrap: anywhere; } | |
| 26 | 新增:.vault-save span, .vault-save small { display: block; margin-top: 6px; color: var(--muted); } | |
| 27 | 新增:.vault-save .vault-actions { margin-top: 10px; } | |
| 28 | 新增:.vault-picker p { margin: 0 0 12px; color: var(--muted); } | |
| 29 | 新增:.vault-account-choice { display: flex; justify-content: space-between; align-items: center; width: 100%; gap: 12px; padding: 10px 12px; margin-bottom: 8px; text-align: left; } | |
| 30 | 新增:.vault-account-choice span:first-child { overflow-wrap: anywhere; min-width: 0; } | |
| 31 | 新增:.vault-account-choice span:last-child { color: var(--muted); flex: none; font-size: 0.7857rem; } | |
| 32 | 新增:@media (max-width: 650px) { .vault-toolbar { align-items: stretch; flex-direction: column; gap: 8px; } .vault-toolbar > button { margin-top: 0; align-self: flex-start; } .vault-editor, .vault-entry { padding: 14px; } } | |
| @@ -0,0 +1,162 @@ | ||
| 1 | 新增:import React, { useEffect, useRef, useState } from "react"; | |
| 2 | 新增:import { KeyRound, Plus, Search, ShieldCheck } from "lucide-react"; | |
| 3 | 新增:import { api, writeClipboard } from "./api"; | |
| 4 | 新增:import "./password-vault.css"; | |
| 5 | 新增: | |
| 6 | 新增:const emptyBrowser = { available: false, entries: [], candidates: [] }; | |
| 7 | 新增:export function usePasswordVault(ready, tab) { | |
| 8 | 新增: const [state, setState] = useState(emptyBrowser); | |
| 9 | 新增: const refresh = useRef(null), mutation = useRef(0); | |
| 10 | 新增: useEffect(() => { | |
| 11 | 新增: let cancelled = false, timer, running = false; | |
| 12 | 新增: setState(emptyBrowser); | |
| 13 | 新增: const poll = async () => { | |
| 14 | 新增: if (running || cancelled || !ready) return; | |
| 15 | 新增: running = true; | |
| 16 | 新增: const revision = mutation.current; | |
| 17 | 新增: clearTimeout(timer); | |
| 18 | 新增: try { | |
| 19 | 新增: const value = await api("/vault/browser", { action: "status", tab }); | |
| 20 | 新增: if (!cancelled && revision === mutation.current) setState({ ...emptyBrowser, ...value, tab }); | |
| 21 | 新增: } catch (error) { | |
| 22 | 新增: if (!cancelled) setState({ ...emptyBrowser, message: error.message }); | |
| 23 | 新增: } finally { | |
| 24 | 新增: running = false; | |
| 25 | 新增: if (!cancelled && ready) timer = setTimeout(poll, 2000); | |
| 26 | 新增: } | |
| 27 | 新增: }; | |
| 28 | 新增: refresh.current = poll; | |
| 29 | 新增: void poll(); | |
| 30 | 新增: return () => { cancelled = true; clearTimeout(timer); refresh.current = null; }; | |
| 31 | 新增: }, [ready, tab]); | |
| 32 | 新增: const act = async input => { | |
| 33 | 新增: await api("/vault/browser", input); | |
| 34 | 新增: mutation.current++; | |
| 35 | 新增: if (input.candidate) setState(previous => ({ ...previous, candidates: previous.candidates.filter(value => value.id !== input.candidate) })); | |
| 36 | 新增: await refresh.current?.(); | |
| 37 | 新增: }; | |
| 38 | 新增: return { state, act }; | |
| 39 | 新增:} | |
| 40 | 新增: | |
| 41 | 新增:export function BrowserVaultBar({ tab, vault, onManage, ready }) { | |
| 42 | 新增: const [open, setOpen] = useState(false), [busy, setBusy] = useState(false), [message, setMessage] = useState(""); | |
| 43 | 新增: const { state, act } = vault; | |
| 44 | 新增: const entries = state.tab === tab.id ? state.entries : []; | |
| 45 | 新增: const candidate = state.candidates.find(value => value.tab === tab.id); | |
| 46 | 新增: useEffect(() => { setOpen(false); setMessage(""); }, [tab.id, tab.url]); | |
| 47 | 新增: const run = async (input, success) => { | |
| 48 | 新增: setBusy(true); setMessage(""); | |
| 49 | 新增: try { await act(input); setMessage(success); } | |
| 50 | 新增: catch (error) { setMessage(error.message); } | |
| 51 | 新增: finally { setBusy(false); } | |
| 52 | 新增: }; | |
| 53 | 新增: return <div className="vault-browser" onKeyDown={event => { | |
| 54 | 新增: if (event.key === "Escape" && open) { event.stopPropagation(); setOpen(false); event.currentTarget.querySelector("button").focus(); } | |
| 55 | 新增: }}> | |
| 56 | 新增: <div className="vault-browser-heading"> | |
| 57 | 新增: <button className="text-button" aria-expanded={open} onClick={() => setOpen(!open)}> | |
| 58 | 新增: <KeyRound size={14} /> 密码{entries.length ? ` · ${entries.length} 个账号` : ""} | |
| 59 | 新增: </button> | |
| 60 | 新增: {message && <span role="status">{message}</span>} | |
| 61 | 新增: </div> | |
| 62 | 新增: {candidate && <div className="vault-save" role="region" aria-label="保存网站密码"> | |
| 63 | 新增: <div><strong>{candidate.update ? "更新此账号的密码?" : "保存此账号密码?"}</strong> | |
| 64 | 新增: <span>{candidate.origin} · {candidate.username || "未填写用户名"}</span> | |
| 65 | 新增: <small>请确认网站登录成功后保存。</small></div> | |
| 66 | 新增: <div className="vault-actions"> | |
| 67 | 新增: <button className="primary" disabled={busy} onClick={() => run({ action: "save", candidate: candidate.id }, "密码已保存")}>{candidate.update ? "更新密码" : "保存密码"}</button> | |
| 68 | 新增: <button disabled={busy} onClick={() => run({ action: "dismiss", candidate: candidate.id }, "")}>暂不保存</button> | |
| 69 | 新增: <button className="text-button" disabled={busy} onClick={() => run({ action: "never", candidate: candidate.id }, "此网站不再提示保存")}>此网站不再提示</button> | |
| 70 | 新增: </div> | |
| 71 | 新增: </div>} | |
| 72 | 新增: {open && <div className="vault-picker" role="region" aria-label="当前网站的密码"> | |
| 73 | 新增: <p>{state.origin && state.tab === tab.id ? state.origin : "在 HTTPS 网站的登录页选择账号填充"}</p> | |
| 74 | 新增: {!ready ? <p>启动环境后可填写网站密码。</p> : !state.available ? <p>{state.message || "正在连接浏览器密码功能…"}</p> : | |
| 75 | 新增: entries.length ? entries.map(entry => <button className="vault-account-choice" key={entry.id} disabled={busy} | |
| 76 | 新增: onClick={() => run({ action: "fill", tab: tab.id, id: entry.id, document: state.document }, "已填写,请在网页中提交登录")}> | |
| 77 | 新增: <span>{entry.username || "未填写用户名"}</span><span>填入账号密码</span> | |
| 78 | 新增: </button>) : <p>此网站尚未保存账号密码。</p>} | |
| 79 | 新增: <button className="text-button" onClick={onManage}>管理密码保险箱</button> | |
| 80 | 新增: </div>} | |
| 81 | 新增: </div>; | |
| 82 | 新增:} | |
| 83 | 新增: | |
| 84 | 新增:const newEntry = () => ({ origin: "", username: "", password: "" }); | |
| 85 | 新增:export function PasswordVaultSettings({ onConfirm, onDirty }) { | |
| 86 | 新增: const [store, setStore] = useState({ entries: [], blocked: [] }); | |
| 87 | 新增: const [loading, setLoading] = useState(true), [busy, setBusy] = useState(false); | |
| 88 | 新增: const [search, setSearch] = useState(""), [draft, setDraft] = useState(null); | |
| 89 | 新增: const [verify, setVerify] = useState(null), [accountPassword, setAccountPassword] = useState(""); | |
| 90 | 新增: const [revealed, setRevealed] = useState(null), [error, setError] = useState(""), [message, setMessage] = useState(""); | |
| 91 | 新增: const alive = useRef(true); | |
| 92 | 新增: const refresh = async () => { | |
| 93 | 新增: const data = await api("/vault"); | |
| 94 | 新增: if (alive.current) setStore(data); | |
| 95 | 新增: }; | |
| 96 | 新增: useEffect(() => { | |
| 97 | 新增: alive.current = true; | |
| 98 | 新增: refresh().catch(error => { if (alive.current) setError(error.message); }).finally(() => { if (alive.current) setLoading(false); }); | |
| 99 | 新增: const clear = () => { setRevealed(null); setAccountPassword(""); }; | |
| 100 | 新增: window.addEventListener("blur", clear); | |
| 101 | 新增: document.addEventListener("visibilitychange", clear); | |
| 102 | 新增: return () => { alive.current = false; window.removeEventListener("blur", clear); document.removeEventListener("visibilitychange", clear); }; | |
| 103 | 新增: }, []); | |
| 104 | 新增: useEffect(() => { onDirty(Boolean(draft)); return () => onDirty(false); }, [draft, onDirty]); | |
| 105 | 新增: useEffect(() => { | |
| 106 | 新增: if (!revealed) return; | |
| 107 | 新增: const timer = setTimeout(() => setRevealed(null), 30000); | |
| 108 | 新增: return () => clearTimeout(timer); | |
| 109 | 新增: }, [revealed]); | |
| 110 | 新增: const run = async (input, success) => { | |
| 111 | 新增: setBusy(true); setError(""); setMessage(""); | |
| 112 | 新增: try { | |
| 113 | 新增: const result = await api("/vault", input); | |
| 114 | 新增: if (!alive.current) return; | |
| 115 | 新增: if (input.action === "reveal") { | |
| 116 | 新增: if (verify.mode === "copy") { await writeClipboard(result.password); setMessage("密码已复制到本机剪贴板"); } | |
| 117 | 新增: else setRevealed({ id: input.id, password: result.password }); | |
| 118 | 新增: setVerify(null); | |
| 119 | 新增: } else { setDraft(null); setRevealed(null); await refresh(); setMessage(success); } | |
| 120 | 新增: } catch (error) { if (alive.current) setError(error.message); } | |
| 121 | 新增: finally { if (alive.current) { setBusy(false); setAccountPassword(""); } } | |
| 122 | 新增: }; | |
| 123 | 新增: const askReveal = (entry, mode) => { setRevealed(null); setAccountPassword(""); setVerify({ entry, mode }); setError(""); }; | |
| 124 | 新增: const entries = store.entries.filter(entry => `${entry.origin} ${entry.username}`.toLowerCase().includes(search.toLowerCase())); | |
| 125 | 新增: return <section className="vault-settings"> | |
| 126 | 新增: <div className="section-title"><h3>密码保险箱</h3><p>账号密码加密保存在这台设备,随 Cage 一起解锁和锁定。</p></div> | |
| 127 | 新增: <div className="vault-note"><ShieldCheck size={17} /><span>查看或复制密码需要再次验证 Cage 账户密码。填充后由你提交登录。</span></div> | |
| 128 | 新增: {error && <p className="account-error" role="alert">{error}</p>} | |
| 129 | 新增: {message && <p role="status">{message}</p>} | |
| 130 | 新增: <div className="vault-toolbar"><label className="vault-search"><span><Search size={14} />搜索网站或账号</span> | |
| 131 | 新增: <input type="search" value={search} onChange={event => setSearch(event.target.value)} /></label> | |
| 132 | 新增: <button disabled={busy || Boolean(draft) || loading || Boolean(error && !store.entries.length)} onClick={() => { setDraft(newEntry()); setVerify(null); setRevealed(null); }}><Plus size={15} />添加密码</button></div> | |
| 133 | 新增: {draft && <form className="vault-editor" onSubmit={event => { event.preventDefault(); void run({ action: "save", entry: draft }, "密码记录已保存"); }}> | |
| 134 | 新增: <h4>{draft.id ? "编辑密码" : "添加密码"}</h4> | |
| 135 | 新增: <fieldset disabled={busy}> | |
| 136 | 新增: <label>网站地址<input type="url" required autoFocus placeholder="https://mail.example.com" value={draft.origin} onChange={event => setDraft({ ...draft, origin: event.target.value })} /></label> | |
| 137 | 新增: <label>账号或邮箱<input autoComplete="off" maxLength={1024} value={draft.username} onChange={event => setDraft({ ...draft, username: event.target.value })} /></label> | |
| 138 | 新增: <label>{draft.id ? "新密码(留空保留原密码)" : "网站密码"}<input type="password" autoComplete="new-password" required={!draft.id} maxLength={8192} value={draft.password || ""} onChange={event => setDraft({ ...draft, password: event.target.value })} /></label> | |
| 139 | 新增: <div className="vault-actions"><button className="primary" type="submit">保存记录</button><button type="button" onClick={() => setDraft(null)}>取消</button></div> | |
| 140 | 新增: </fieldset> | |
| 141 | 新增: </form>} | |
| 142 | 新增: {verify && <form className="vault-editor" onSubmit={event => { event.preventDefault(); void run({ action: "reveal", id: verify.entry.id, account_password: accountPassword }); }}> | |
| 143 | 新增: <h4>{verify.mode === "copy" ? "验证后复制密码" : "验证后查看密码"}</h4><p>{verify.entry.origin} · {verify.entry.username}</p> | |
| 144 | 新增: <label>Cage 账户密码<input type="password" autoComplete="off" autoFocus required maxLength={1024} value={accountPassword} onChange={event => setAccountPassword(event.target.value)} /></label> | |
| 145 | 新增: <div className="vault-actions"><button className="primary" disabled={busy} type="submit">验证并{verify.mode === "copy" ? "复制" : "查看"}</button> | |
| 146 | 新增: <button type="button" disabled={busy} onClick={() => { setVerify(null); setAccountPassword(""); }}>取消验证</button></div> | |
| 147 | 新增: </form>} | |
| 148 | 新增: {loading ? <p>正在读取密码保险箱…</p> : !entries.length ? <div className="vault-empty"><KeyRound size={24} /><p>{search ? "没有找到匹配的账号" : "还没有保存密码"}</p><small>网页登录后可以确认保存,也可以手动添加。</small></div> : | |
| 149 | 新增: <div className="vault-list">{entries.map(entry => <article className="vault-entry" key={entry.id}> | |
| 150 | 新增: <div><strong>{entry.origin}</strong><span>{entry.username || "未填写用户名"}</span></div> | |
| 151 | 新增: {revealed?.id === entry.id && <div className="vault-revealed"><output aria-label="已保存的网站密码">{revealed.password}</output><button onClick={() => setRevealed(null)}>隐藏密码</button></div>} | |
| 152 | 新增: <div className="vault-actions"> | |
| 153 | 新增: <button disabled={busy || Boolean(draft)} onClick={() => askReveal(entry, "view")}>查看密码</button> | |
| 154 | 新增: <button disabled={busy || Boolean(draft)} onClick={() => askReveal(entry, "copy")}>复制密码</button> | |
| 155 | 新增: <button disabled={busy || Boolean(draft)} onClick={() => { setDraft({ ...entry, password: "" }); setVerify(null); setRevealed(null); }}>编辑</button> | |
| 156 | 新增: <button disabled={busy || Boolean(draft)} onClick={async () => { if (await onConfirm({ title: "删除此密码?", body: `${entry.origin} · ${entry.username || "未填写用户名"}。删除后无法恢复。`, confirm: "删除密码" })) await run({ action: "delete", id: entry.id }, "密码记录已删除"); }}>删除</button> | |
| 157 | 新增: </div> | |
| 158 | 新增: </article>)}</div>} | |
| 159 | 新增: {store.blocked.length > 0 && <section className="vault-blocked"><h4>不再提示保存的网站</h4>{store.blocked.map(origin => <div key={origin}><span>{origin}</span><button disabled={busy} onClick={() => run({ action: "unblock", origin }, "已恢复此网站的保存提示")}>恢复提示</button></div>)}</section>} | |
| 160 | 新增: <p className="footnote">目前支持 HTTPS 顶层网页的常见登录表单。密码不会同步到其他设备;备份时需同时保留本地账户文件与密码库。</p> | |
| 161 | 新增: </section>; | |
| 162 | 新增:} | |
| @@ -1,3 +1,4 @@ | ||
| 1 | 新增:import { InlineSelect } from "./inline-select"; | |
| 1 | 2 | import React, { useEffect, useRef, useState } from "react"; |
| 2 | 3 | import { |
| 3 | 4 | Download, |
| @@ -315,10 +316,10 @@ export function ProxySettings({ status, onApplied, onConfirm }) { | ||
| 315 | 316 | placeholder="搜索节点、来源或协议" |
| 316 | 317 | /> |
| 317 | 318 | </label> |
| 318 | 删除: <select | |
| 319 | 新增: <InlineSelect | |
| 319 | 320 | aria-label="节点来源" |
| 320 | 321 | value={source} |
| 321 | 删除: onChange={(e) => setSource(e.target.value)} | |
| 322 | 新增: onValueChange={(next) => setSource(next)} | |
| 322 | 323 | > |
| 323 | 324 | <option value="">全部来源</option> |
| 324 | 325 | {proxy.sources.map((s) => ( |
| @@ -326,7 +327,7 @@ export function ProxySettings({ status, onApplied, onConfirm }) { | ||
| 326 | 327 | {s.name} |
| 327 | 328 | </option> |
| 328 | 329 | ))} |
| 329 | 删除: </select> | |
| 330 | 新增: </InlineSelect> | |
| 330 | 331 | <button |
| 331 | 332 | disabled={busy || !proxy.running || !nodes.length} |
| 332 | 333 | onClick={() => measure(nodes.map((n) => n.id))} |
| @@ -542,12 +543,13 @@ export function ProxySettings({ status, onApplied, onConfirm }) { | ||
| 542 | 543 | </label> |
| 543 | 544 | <label> |
| 544 | 545 | 自动更新间隔 |
| 545 | 删除: <select | |
| 546 | 新增: <InlineSelect | |
| 547 | 新增: aria-label="自动更新间隔" | |
| 546 | 548 | value={form.interval_hours} |
| 547 | 删除: onChange={(e) => | |
| 549 | 新增: onValueChange={(next) => | |
| 548 | 550 | setForm({ |
| 549 | 551 | ...form, |
| 550 | 删除: interval_hours: Number(e.target.value), | |
| 552 | 新增: interval_hours: Number(next), | |
| 551 | 553 | }) |
| 552 | 554 | } |
| 553 | 555 | > |
| @@ -562,7 +564,7 @@ export function ProxySettings({ status, onApplied, onConfirm }) { | ||
| 562 | 564 | {label} |
| 563 | 565 | </option> |
| 564 | 566 | ))} |
| 565 | 删除: </select> | |
| 567 | 新增: </InlineSelect> | |
| 566 | 568 | </label> |
| 567 | 569 | {!form.id && ( |
| 568 | 570 | <label className="check-line"> |
| @@ -645,15 +647,16 @@ export function ProxySettings({ status, onApplied, onConfirm }) { | ||
| 645 | 647 | </label> |
| 646 | 648 | <label> |
| 647 | 649 | 协议 |
| 648 | 删除: <select | |
| 650 | 新增: <InlineSelect | |
| 651 | 新增: aria-label="协议" | |
| 649 | 652 | value={manual.type} |
| 650 | 删除: onChange={(e) => | |
| 651 | 删除: setManual({ ...manual, type: e.target.value }) | |
| 653 | 新增: onValueChange={(next) => | |
| 654 | 新增: setManual({ ...manual, type: next }) | |
| 652 | 655 | } |
| 653 | 656 | > |
| 654 | 657 | <option value="socks5">SOCKS5</option> |
| 655 | 658 | <option value="http">HTTP CONNECT</option> |
| 656 | 删除: </select> | |
| 659 | 新增: </InlineSelect> | |
| 657 | 660 | </label> |
| 658 | 661 | </div> |
| 659 | 662 | <div className="field-row"> |
| @@ -70,7 +70,7 @@ | ||
| 70 | 70 | opacity: 0.65; |
| 71 | 71 | font-size: 12px; |
| 72 | 72 | } |
| 73 | 删除:.proxy-toolbar select { | |
| 73 | 新增:.proxy-toolbar .inline-select { | |
| 74 | 74 | max-width: 150px; |
| 75 | 75 | } |
| 76 | 76 | .settings-content label.proxy-search { |
| @@ -301,7 +301,7 @@ | ||
| 301 | 301 | .proxy-source { |
| 302 | 302 | align-items: flex-start; |
| 303 | 303 | } |
| 304 | 删除: .proxy-toolbar select { | |
| 304 | 新增: .proxy-toolbar .inline-select { | |
| 305 | 305 | max-width: 120px; |
| 306 | 306 | } |
| 307 | 307 | } |
| @@ -1,11 +1,11 @@ | ||
| 1 | 1 | // Guest applications render at 2x. Zoom changes their logical workspace size, |
| 2 | 2 | // while noVNC fits the resulting framebuffer into the available CSS area. |
| 3 | 3 | export function displayGeometry({ width, height }, { desktop = false, zoom = 1 } = {}) { |
| 4 | 删除: if (width < 320 || height < 240) return null; | |
| 4 | 新增: if (width < (desktop ? 320 : 160) || height < 240) return null; | |
| 5 | 5 | const ratio = 2 / zoom; |
| 6 | 6 | const limit = Math.min(1, 8192 / (width * ratio), 8192 / (height * ratio)); |
| 7 | 7 | return { |
| 8 | 删除: width: Math.max(desktop ? 320 : 640, Math.floor(width * ratio * limit)), | |
| 8 | 新增: width: Math.max(320, Math.floor(width * ratio * limit)), | |
| 9 | 9 | height: Math.max(desktop ? 240 : 480, Math.floor(height * ratio * limit)), |
| 10 | 10 | }; |
| 11 | 11 | } |
| @@ -7,6 +7,7 @@ test("normal size preserves logical pixels; zoom changes workspace, large displa | ||
| 7 | 7 | assert.deepEqual(displayGeometry({ width: 1000, height: 700 }, { desktop: true }), { width: 2000, height: 1400 }); |
| 8 | 8 | assert.deepEqual(displayGeometry({ width: 1000, height: 700 }, { desktop: true, zoom: 1.25 }), { width: 1600, height: 1120 }); |
| 9 | 9 | assert.deepEqual(displayGeometry({ width: 5000, height: 3000 }, { desktop: true }), { width: 8192, height: 4915 }); |
| 10 | 新增: assert.deepEqual(displayGeometry({ width: 286, height: 446 }), { width: 572, height: 892 }); | |
| 10 | 11 | assert.equal(displayGeometry({ width: 0, height: 700 }), null); |
| 11 | 12 | }); |
| 12 | 13 | |
| @@ -11,7 +11,7 @@ import { | ||
| 11 | 11 | export function installRemoteInput( |
| 12 | 12 | rfb, |
| 13 | 13 | container, |
| 14 | 删除: { mode, onStatus, onFallback, isActive, insertText, insertComposition, caretRect, tabId: getTargetId = () => "", pasteContent }, | |
| 14 | 新增: { mode, onStatus, onFallback, isActive, insertText, insertComposition, caretRect, tabId: getTargetId = () => "", pasteContent, setCopyContext }, | |
| 15 | 15 | ) { |
| 16 | 16 | const listeners = [], |
| 17 | 17 | handled = new Set(), |
| @@ -19,6 +19,7 @@ export function installRemoteInput( | ||
| 19 | 19 | remote = new Map(); |
| 20 | 20 | let lastText = "", |
| 21 | 21 | copyRequested = false, |
| 22 | 新增: copyContext = "", | |
| 22 | 23 | copyTimer, |
| 23 | 24 | pending = 0, |
| 24 | 25 | composing = false, |
| @@ -51,6 +52,19 @@ export function installRemoteInput( | ||
| 51 | 52 | isActive() && |
| 52 | 53 | (nativeOwned || container.contains(document.activeElement) || |
| 53 | 54 | document.activeElement === target); |
| 55 | 新增: const cancelCopy = () => { | |
| 56 | 新增: copyContext = ""; | |
| 57 | 新增: copyRequested = false; | |
| 58 | 新增: clearTimeout(copyTimer); | |
| 59 | 新增: }; | |
| 60 | 新增: const prepareCopy = () => { | |
| 61 | 新增: if (!setCopyContext || !isActive() || disposed) return; | |
| 62 | 新增: copyContext = crypto.randomUUID().replaceAll("-", ""); | |
| 63 | 新增: const context = copyContext; | |
| 64 | 新增: void setCopyContext(context, () => !disposed && isActive() && context === copyContext).catch(() => { | |
| 65 | 新增: if (copyContext === context) cancelCopy(); | |
| 66 | 新增: }); | |
| 67 | 新增: }; | |
| 54 | 68 | const deactivateNative = () => { |
| 55 | 69 | const owner = nativeOwner; |
| 56 | 70 | nativeOwned = false; |
| @@ -119,6 +133,7 @@ export function installRemoteInput( | ||
| 119 | 133 | target.blur(); |
| 120 | 134 | } |
| 121 | 135 | position(event.clientX, event.clientY); |
| 136 | 新增: if (event.isTrusted && event.button === 0) prepareCopy(); | |
| 122 | 137 | }, |
| 123 | 138 | true, |
| 124 | 139 | ); |
| @@ -203,8 +218,15 @@ export function installRemoteInput( | ||
| 203 | 218 | resetComposition(); |
| 204 | 219 | }); |
| 205 | 220 | on(document, "focusin", (event) => { |
| 221 | 新增: if (!container.contains(event.target)) cancelCopy(); | |
| 206 | 222 | if (nativeOwned && !container.contains(event.target)) deactivateNative(); |
| 207 | 223 | }); |
| 224 | 新增: on(document, "pointerdown", (event) => { | |
| 225 | 新增: if (!container.contains(event.target)) cancelCopy(); | |
| 226 | 新增: }, true); | |
| 227 | 新增: on(document, "visibilitychange", () => { | |
| 228 | 新增: if (document.visibilityState === "hidden") cancelCopy(); | |
| 229 | 新增: }); | |
| 208 | 230 | on(window, "cage-native-input", (event) => { |
| 209 | 231 | const value = event.detail; |
| 210 | 232 | if (disposed || !value || value.owner !== nativeOwner) return; |
| @@ -294,7 +316,7 @@ export function installRemoteInput( | ||
| 294 | 316 | }; |
| 295 | 317 | on(rfb, "clipboard", async (event) => { |
| 296 | 318 | lastText = event.detail.text; |
| 297 | 删除: if (!copyRequested) return; | |
| 319 | 新增: if (!copyRequested || !isActive()) return; | |
| 298 | 320 | copyRequested = false; |
| 299 | 321 | clearTimeout(copyTimer); |
| 300 | 322 | try { |
| @@ -305,6 +327,7 @@ export function installRemoteInput( | ||
| 305 | 327 | } |
| 306 | 328 | }); |
| 307 | 329 | const release = () => { |
| 330 | 新增: cancelCopy(); | |
| 308 | 331 | for (const [code, keysym] of remote) rfb.sendKey(keysym, code, false); |
| 309 | 332 | remote.clear(); |
| 310 | 333 | physical.clear(); |
| @@ -316,6 +339,8 @@ export function installRemoteInput( | ||
| 316 | 339 | "keydown", |
| 317 | 340 | (event) => { |
| 318 | 341 | if (!focused()) return; |
| 342 | 新增: if (event.isTrusted && (!copyContext || ["Enter", " ", "Tab"].includes(event.key) || | |
| 343 | 新增: event.ctrlKey || event.metaKey || event.altKey)) prepareCopy(); | |
| 319 | 344 | if ( |
| 320 | 345 | composing || |
| 321 | 346 | event.isComposing || |
| @@ -478,6 +503,21 @@ export function installRemoteInput( | ||
| 478 | 503 | }); |
| 479 | 504 | return { |
| 480 | 505 | copy, |
| 506 | 新增: cancelCopy, | |
| 507 | 新增: async receiveCopy({ id, text, context }) { | |
| 508 | 新增: const valid = () => !disposed && Boolean(copyContext) && context === copyContext && id === getTargetId() && focused() && | |
| 509 | 新增: document.visibilityState !== "hidden" && document.hasFocus(); | |
| 510 | 新增: if (typeof text !== "string" || text.length > 65536 || !valid()) return; | |
| 511 | 新增: lastText = text; | |
| 512 | 新增: copyRequested = false; | |
| 513 | 新增: clearTimeout(copyTimer); | |
| 514 | 新增: try { | |
| 515 | 新增: await writeClipboard(text); | |
| 516 | 新增: if (valid()) say("已复制到本机"); | |
| 517 | 新增: } catch { | |
| 518 | 新增: if (valid()) onFallback(text, "请在这里复制到本机。"); | |
| 519 | 新增: } | |
| 520 | 新增: }, | |
| 481 | 521 | readAndPaste, |
| 482 | 522 | paste, |
| 483 | 523 | text: () => lastText, |
| @@ -18,12 +18,14 @@ function fixture(native = false, browserComposition = false) { | ||
| 18 | 18 | pastes = [], |
| 19 | 19 | texts = [], |
| 20 | 20 | compositions = [], |
| 21 | 新增: copyContexts = [], | |
| 21 | 22 | writes = [], |
| 22 | 23 | statuses = []; |
| 23 | 24 | let reads = 0, |
| 24 | 25 | mode = "mac", |
| 25 | 26 | currentTabId = "tab-1"; |
| 26 | 27 | doc.activeElement = canvas; |
| 28 | 新增: doc.hasFocus = () => true; | |
| 27 | 29 | doc.body = { append() {} }; |
| 28 | 30 | const target = Object.assign(new EventTarget(), { |
| 29 | 31 | value: "", |
| @@ -79,19 +81,21 @@ function fixture(native = false, browserComposition = false) { | ||
| 79 | 81 | }, |
| 80 | 82 | }; |
| 81 | 83 | const install = vm.runInNewContext(source + "\ninstallRemoteInput;", context); |
| 82 | 删除: const controller = install( | |
| 83 | 删除: rfb, | |
| 84 | 删除: Object.assign(new EventTarget(), { | |
| 84 | 新增: const container = Object.assign(new EventTarget(), { | |
| 85 | 85 | querySelector: () => null, |
| 86 | 86 | contains: (element) => element === canvas || element === target, |
| 87 | 87 | append() {}, |
| 88 | 88 | getBoundingClientRect: () => ({ left: 0, top: 0 }), |
| 89 | 删除: }), | |
| 89 | 新增: }); | |
| 90 | 新增: const controller = install( | |
| 91 | 新增: rfb, | |
| 92 | 新增: container, | |
| 90 | 93 | { |
| 91 | 94 | mode: () => mode, |
| 92 | 95 | onStatus: (t) => statuses.push(t), |
| 93 | 96 | onFallback() {}, |
| 94 | 97 | isActive: () => true, |
| 98 | 新增: setCopyContext: async (context, valid) => { if (valid()) copyContexts.push(context); }, | |
| 95 | 99 | insertText: async (text) => { |
| 96 | 100 | texts.push(text); |
| 97 | 101 | }, |
| @@ -133,6 +137,13 @@ function fixture(native = false, browserComposition = false) { | ||
| 133 | 137 | compositions, |
| 134 | 138 | writes, |
| 135 | 139 | statuses, |
| 140 | 新增: armCopy: () => { | |
| 141 | 新增: const event = new Event("pointerdown"); | |
| 142 | 新增: Object.defineProperty(event, "isTrusted", { value: true }); | |
| 143 | 新增: Object.assign(event, { button: 0, clientX: 20, clientY: 20 }); | |
| 144 | 新增: container.dispatchEvent(event); | |
| 145 | 新增: return copyContexts.at(-1); | |
| 146 | 新增: }, | |
| 136 | 147 | controller, |
| 137 | 148 | key, |
| 138 | 149 | local, |
| @@ -386,6 +397,80 @@ test("a clipboard read finishing after disconnect is not pasted into a stale con | ||
| 386 | 397 | assert.equal(f.pastes.length, 0); |
| 387 | 398 | }); |
| 388 | 399 | |
| 400 | 新增:test("verified page copies only write to the host from the focused live tab", async () => { | |
| 401 | 新增: const f = fixture(); | |
| 402 | 新增: const context = f.armCopy(); | |
| 403 | 新增: const copy = (id = "tab-1", text = "实际复制的文字🙂") => f.controller.receiveCopy({ id, text, context }); | |
| 404 | 新增: try { | |
| 405 | 新增: await copy(); | |
| 406 | 新增: assert.deepEqual(f.writes, ["实际复制的文字🙂"]); | |
| 407 | 新增: await copy("other-tab"); | |
| 408 | 新增: f.doc.hasFocus = () => false; | |
| 409 | 新增: await copy(); | |
| 410 | 新增: f.doc.hasFocus = () => true; | |
| 411 | 新增: f.doc.visibilityState = "hidden"; | |
| 412 | 新增: await copy(); | |
| 413 | 新增: f.doc.visibilityState = "visible"; | |
| 414 | 新增: f.doc.activeElement = f.local; | |
| 415 | 新增: await copy(); | |
| 416 | 新增: f.doc.activeElement = f.target; | |
| 417 | 新增: await copy("tab-1", "x".repeat(65537)); | |
| 418 | 新增: assert.equal(f.writes.length, 1); | |
| 419 | 新增: f.controller.dispose(); | |
| 420 | 新增: await copy(); | |
| 421 | 新增: assert.equal(f.writes.length, 1); | |
| 422 | 新增: } finally { f.controller.dispose(); } | |
| 423 | 新增:}); | |
| 424 | 新增: | |
| 425 | 新增:test("copy results from before a focus or tab round-trip cannot write after returning", async () => { | |
| 426 | 新增: const f = fixture(); | |
| 427 | 新增: try { | |
| 428 | 新增: const context = f.armCopy(); | |
| 429 | 新增: const oldCopy = { id: "tab-1", text: "old pending copy", context }; | |
| 430 | 新增: f.win.dispatchEvent(new Event("blur")); | |
| 431 | 新增: const next = f.armCopy(); | |
| 432 | 新增: assert.notEqual(context, next); | |
| 433 | 新增: await f.controller.receiveCopy(oldCopy); | |
| 434 | 新增: f.setTabId("tab-2"); | |
| 435 | 新增: f.controller.cancelCopy(); | |
| 436 | 新增: f.setTabId("tab-1"); | |
| 437 | 新增: const latest = f.armCopy(); | |
| 438 | 新增: await f.controller.receiveCopy({ ...oldCopy, context: next }); | |
| 439 | 新增: assert.equal(f.writes.length, 0); | |
| 440 | 新增: await f.controller.receiveCopy({ ...oldCopy, text: "new copy", context: latest }); | |
| 441 | 新增: assert.deepEqual(f.writes, ["new copy"]); | |
| 442 | 新增: } finally { f.controller.dispose(); } | |
| 443 | 新增:}); | |
| 444 | 新增: | |
| 445 | 新增:test("clicking between split panes rejects earlier copies after returning", async () => { | |
| 446 | 新增: const f = fixture(); | |
| 447 | 新增: try { | |
| 448 | 新增: const leftContext = f.armCopy(); | |
| 449 | 新增: f.setTabId("tab-2"); | |
| 450 | 新增: const rightContext = f.armCopy(); | |
| 451 | 新增: f.setTabId("tab-1"); | |
| 452 | 新增: const currentContext = f.armCopy(); | |
| 453 | 新增: | |
| 454 | 新增: // Both panes share one input surface, so these clicks do not cause blur. | |
| 455 | 新增: await f.controller.receiveCopy({ id: "tab-1", text: "old left copy", context: leftContext }); | |
| 456 | 新增: await f.controller.receiveCopy({ id: "tab-2", text: "old right copy", context: rightContext }); | |
| 457 | 新增: assert.deepEqual(f.writes, []); | |
| 458 | 新增: await f.controller.receiveCopy({ id: "tab-1", text: "current left copy", context: currentContext }); | |
| 459 | 新增: assert.deepEqual(f.writes, ["current left copy"]); | |
| 460 | 新增: } finally { f.controller.dispose(); } | |
| 461 | 新增:}); | |
| 462 | 新增: | |
| 463 | 新增:test("an unrelated RFB clipboard update never authorizes a host write", async () => { | |
| 464 | 新增: const f = fixture(); | |
| 465 | 新增: try { | |
| 466 | 新增: const event = new Event("clipboard"); | |
| 467 | 新增: event.detail = { text: "unrelated guest application" }; | |
| 468 | 新增: f.rfb.dispatchEvent(event); | |
| 469 | 新增: await new Promise(resolve => setImmediate(resolve)); | |
| 470 | 新增: assert.equal(f.writes.length, 0); | |
| 471 | 新增: } finally { f.controller.dispose(); } | |
| 472 | 新增:}); | |
| 473 | 新增: | |
| 389 | 474 | test("malformed native Command letters retain clipboard and redo semantics", async () => { |
| 390 | 475 | const f = fixture(true); |
| 391 | 476 | try { |
| @@ -1,3 +1,6 @@ | ||
| 1 | 新增:import { PasswordVaultSettings } from "./password-vault"; | |
| 2 | 新增:import { KeyRound } from "lucide-react"; | |
| 3 | 新增:import { InlineSelect } from "./inline-select"; | |
| 1 | 4 | import { shortcut, usesControl } from "./platform.mjs"; |
| 2 | 5 | import React, { useEffect, useMemo, useRef, useState } from "react"; |
| 3 | 6 | import { |
| @@ -12,6 +15,7 @@ import { | ||
| 12 | 15 | SlidersHorizontal, |
| 13 | 16 | Palette, |
| 14 | 17 | UserRound, |
| 18 | 新增: UsersRound, | |
| 15 | 19 | } from "lucide-react"; |
| 16 | 20 | import { api } from "./api"; |
| 17 | 21 | import { AppearanceSettings } from "./appearance-settings"; |
| @@ -22,8 +26,11 @@ import { EnvironmentVersions } from "./environment-versions"; | ||
| 22 | 26 | import { ResourceSettings } from "./resources"; |
| 23 | 27 | import { DiagnosticSettings } from "./diagnostics.jsx"; |
| 24 | 28 | import { AccountSettings } from "./account"; |
| 29 | 新增:import { ClaudeAccountsPanel } from "./claude-accounts"; | |
| 25 | 30 | const sections = [ |
| 26 | 31 | ["account", "账户", UserRound], |
| 32 | 新增: ["vault", "密码保险箱", KeyRound], | |
| 33 | 新增: ["claude-accounts", "Claude 账号", UsersRound], | |
| 27 | 34 | ["keyboard", "通用", SlidersHorizontal], |
| 28 | 35 | ["appearance", "外观", Palette], |
| 29 | 36 | ["network", "网络与代理", Globe2], |
| @@ -37,6 +44,9 @@ export function SettingsPanel({ | ||
| 37 | 44 | onClose, |
| 38 | 45 | onSaved, |
| 39 | 46 | onConfirm, |
| 47 | 新增: claudeProfiles, | |
| 48 | 新增: terminalTabs, | |
| 49 | 新增: onClaudeLogin, | |
| 40 | 50 | initialSection = "keyboard", |
| 41 | 51 | }) { |
| 42 | 52 | const [accountDirty, setAccountDirty] = useState(false); |
| @@ -203,7 +213,7 @@ export function SettingsPanel({ | ||
| 203 | 213 | className={section === id ? "selected" : ""} |
| 204 | 214 | aria-current={section === id ? "page" : undefined} |
| 205 | 215 | onClick={async () => { |
| 206 | 删除: if (id !== section && accountDirty && !(await onConfirm({ title: "放弃尚未保存的账户修改?", body: "已保存的账户资料和密码保持不变。", confirm: "放弃修改" }))) return; | |
| 216 | 新增: if (id !== section && accountDirty && !(await onConfirm({ title: "放弃尚未保存的修改?", body: "已保存的资料和密码保持不变。", confirm: "放弃修改" }))) return; | |
| 207 | 217 | setSection(id); |
| 208 | 218 | }} |
| 209 | 219 | > |
| @@ -214,9 +224,17 @@ export function SettingsPanel({ | ||
| 214 | 224 | </nav> |
| 215 | 225 | </aside> |
| 216 | 226 | <div className="settings-main"> |
| 217 | 删除: <div className="settings-content" ref={contentRef}> | |
| 227 | 新增: <div className={section === "claude-accounts" ? "settings-content settings-content--accounts" : "settings-content"} ref={contentRef}> | |
| 218 | 228 | {section === "appearance" && <AppearanceSettings />} |
| 229 | 新增: {section === "vault" && <PasswordVaultSettings onConfirm={onConfirm} onDirty={setAccountDirty} />} | |
| 219 | 230 | {section === "account" && <AccountSettings busy={busy} onDirty={setAccountDirty} />} |
| 231 | 新增: {section === "claude-accounts" && <ClaudeAccountsPanel store={claudeProfiles} tabs={terminalTabs} onConfirm={onConfirm} | |
| 232 | 新增: running={status.vm_running} environmentBusy={busy} login={async (id) => { | |
| 233 | 新增: if (changed && !(await onConfirm({ title: "放弃尚未保存的设置并登录?", | |
| 234 | 新增: body: "打开登录终端会离开设置页。", confirm: "打开登录终端" }))) return; | |
| 235 | 新增: await onClaudeLogin(id); | |
| 236 | 新增: onClose(); | |
| 237 | 新增: }} />} | |
| 220 | 238 | <fieldset className="settings-fields" disabled={busy}> |
| 221 | 239 | {section === "network" && ( |
| 222 | 240 | <> |
| @@ -311,17 +329,16 @@ export function SettingsPanel({ | ||
| 311 | 329 | </label> |
| 312 | 330 | <label> |
| 313 | 331 | {draft.auto_timezone ? "将应用的时区" : "系统时区"} |
| 314 | 删除: <input | |
| 315 | 删除: list="cage-timezones" | |
| 332 | 新增: <InlineSelect editable | |
| 333 | 新增: aria-label={draft.auto_timezone ? "将应用的时区" : "系统时区"} | |
| 316 | 334 | value={draft.timezone} |
| 317 | 335 | disabled={draft.auto_timezone} |
| 318 | 删除: onChange={(e) => update("timezone", e.target.value)} | |
| 319 | 删除: /> | |
| 320 | 删除: <datalist id="cage-timezones"> | |
| 336 | 新增: onValueChange={(next) => update("timezone", next)} | |
| 337 | 新增: > | |
| 321 | 338 | {zones.map((zone) => ( |
| 322 | 339 | <option key={zone} value={zone} /> |
| 323 | 340 | ))} |
| 324 | 删除: </datalist> | |
| 341 | 新增: </InlineSelect> | |
| 325 | 342 | </label> |
| 326 | 343 | {draft.auto_timezone && ( |
| 327 | 344 | <div className="inline-info"> |
| @@ -373,10 +390,11 @@ export function SettingsPanel({ | ||
| 373 | 390 | )} |
| 374 | 391 | <label> |
| 375 | 392 | 系统语言 |
| 376 | 删除: <select | |
| 393 | 新增: <InlineSelect | |
| 394 | 新增: aria-label="系统语言" | |
| 377 | 395 | value={draft.locale} |
| 378 | 396 | disabled={draft.auto_language} |
| 379 | 删除: onChange={(e) => update("locale", e.target.value)} | |
| 397 | 新增: onValueChange={(next) => update("locale", next)} | |
| 380 | 398 | > |
| 381 | 399 | {[ |
| 382 | 400 | ["en_US.UTF-8", "English (United States)"], |
| @@ -400,14 +418,15 @@ export function SettingsPanel({ | ||
| 400 | 418 | ].includes(draft.locale) && ( |
| 401 | 419 | <option value={draft.locale}>{draft.locale}</option> |
| 402 | 420 | )} |
| 403 | 删除: </select> | |
| 421 | 新增: </InlineSelect> | |
| 404 | 422 | </label> |
| 405 | 423 | <label> |
| 406 | 424 | 网页首选语言 |
| 407 | 删除: <select | |
| 425 | 新增: <InlineSelect | |
| 426 | 新增: aria-label="网页首选语言" | |
| 408 | 427 | value={draft.browser_language} |
| 409 | 428 | disabled={draft.auto_language} |
| 410 | 删除: onChange={(e) => update("browser_language", e.target.value)} | |
| 429 | 新增: onValueChange={(next) => update("browser_language", next)} | |
| 411 | 430 | > |
| 412 | 431 | {[ |
| 413 | 432 | ["en-US", "English (United States)"], |
| @@ -433,7 +452,7 @@ export function SettingsPanel({ | ||
| 433 | 452 | {draft.browser_language} |
| 434 | 453 | </option> |
| 435 | 454 | )} |
| 436 | 删除: </select> | |
| 455 | 新增: </InlineSelect> | |
| 437 | 456 | </label> |
| 438 | 457 | <p className="footnote"> |
| 439 | 458 | 网页仍可按自己的规则选择语言。工作台界面使用中文。 |
| @@ -545,7 +564,7 @@ export function SettingsPanel({ | ||
| 545 | 564 | </strong> |
| 546 | 565 | </div> |
| 547 | 566 | <p className="field-help"> |
| 548 | 删除: 返回工作台,使用“打开项目”选择其他本地文件夹。 | |
| 567 | 新增: 点击侧栏“项目”标题旁的加号,可选择其他本地文件夹。 | |
| 549 | 568 | </p> |
| 550 | 569 | <div className="project-explanation"> |
| 551 | 570 | <FolderOpen size={22} /> |
| @@ -616,7 +635,7 @@ export function SettingsPanel({ | ||
| 616 | 635 | </div> |
| 617 | 636 | )} |
| 618 | 637 | </div> |
| 619 | 删除: {((section !== "appearance" && section !== "account") || changed) && ( | |
| 638 | 新增: {(!["appearance", "account", "claude-accounts", "vault"].includes(section) || changed) && ( | |
| 620 | 639 | <footer className="settings-footer"> |
| 621 | 640 | {" "} |
| 622 | 641 | <> |
| @@ -12,6 +12,7 @@ | ||
| 12 | 12 | |
| 13 | 13 | font-synthesis: none; |
| 14 | 14 | font-size: var(--ui-font-size, 14px); |
| 15 | 新增: --workbench-header-height: 40px; | |
| 15 | 16 | /* Quiet desktop chrome; the active work surface carries the visual emphasis. */ |
| 16 | 17 | --chrome: #f7f7f7; |
| 17 | 18 | --chrome-dark: #f0f0f0; |
| @@ -426,35 +427,6 @@ button.large { | ||
| 426 | 427 | .files-button:hover:not(:disabled) { |
| 427 | 428 | border-left: 1px solid var(--line); |
| 428 | 429 | } |
| 429 | 删除:.terminal-path { | |
| 430 | 删除: display: flex; | |
| 431 | 删除: align-items: center; | |
| 432 | 删除: gap: 9px; | |
| 433 | 删除: flex: 1; | |
| 434 | 删除: min-width: 0; | |
| 435 | 删除: font: | |
| 436 | 删除: 12px "SF Mono", | |
| 437 | 删除: Menlo, | |
| 438 | 删除: monospace; | |
| 439 | 删除: color: var(--ink); | |
| 440 | 删除:} | |
| 441 | 删除:.terminal-path > span:first-of-type { | |
| 442 | 删除: overflow: hidden; | |
| 443 | 删除: text-overflow: ellipsis; | |
| 444 | 删除: white-space: nowrap; | |
| 445 | 删除:} | |
| 446 | 删除:.terminal-kind { | |
| 447 | 删除: margin-left: auto; | |
| 448 | 删除: flex: none; | |
| 449 | 删除: font: | |
| 450 | 删除: 11px -apple-system, | |
| 451 | 删除: sans-serif; | |
| 452 | 删除: color: var(--ink); | |
| 453 | 删除:} | |
| 454 | 删除:.navigation-row > .text-button { | |
| 455 | 删除: color: var(--ink); | |
| 456 | 删除: font-size: 0.8571rem; | |
| 457 | 删除:} | |
| 458 | 430 | .progress-line { |
| 459 | 431 | position: absolute; |
| 460 | 432 | left: 0; |
| @@ -513,8 +485,9 @@ button.large { | ||
| 513 | 485 | } |
| 514 | 486 | .sidebar-footer-actions { |
| 515 | 487 | display: flex; |
| 488 | 新增: flex-wrap: wrap; | |
| 516 | 489 | align-items: center; |
| 517 | 删除: gap: 6px; | |
| 490 | 新增: gap: 3px 6px; | |
| 518 | 491 | } |
| 519 | 492 | .sidebar-footer-actions > .sidebar-link { flex: 1; min-width: 0; } |
| 520 | 493 | .app-update-button { |
| @@ -812,7 +785,7 @@ button.large { | ||
| 812 | 785 | color: var(--ink); |
| 813 | 786 | } |
| 814 | 787 | .settings-content input:not([type="checkbox"]):not([type="radio"]), |
| 815 | 删除:.settings-content select { | |
| 788 | 新增:.settings-content .inline-select-trigger { | |
| 816 | 789 | height: 36px; |
| 817 | 790 | border: 1px solid var(--line); |
| 818 | 791 | border-radius: 6px; |
| @@ -1140,7 +1113,7 @@ button.large { | ||
| 1140 | 1113 | /* Reading sizes remain comfortable at a normal 1280px workbench window. */ |
| 1141 | 1114 | .settings-content label:not(.check-line):not(.choice):not(.toggle-row), |
| 1142 | 1115 | .settings-content input:not([type="checkbox"]):not([type="radio"]), |
| 1143 | 删除:.settings-content select, | |
| 1116 | 新增:.settings-content .inline-select-trigger, | |
| 1144 | 1117 | .choice strong, |
| 1145 | 1118 | .toggle-row strong, |
| 1146 | 1119 | .settings-content h4, |
| @@ -1149,7 +1122,7 @@ button.large { | ||
| 1149 | 1122 | font-size: 1rem; |
| 1150 | 1123 | } |
| 1151 | 1124 | .settings-content input:not([type="checkbox"]):not([type="radio"]), |
| 1152 | 删除:.settings-content select { | |
| 1125 | 新增:.settings-content .inline-select-trigger { | |
| 1153 | 1126 | height: 39px; |
| 1154 | 1127 | } |
| 1155 | 1128 | .section-title h3 { |
| @@ -1216,7 +1189,8 @@ svg { | ||
| 1216 | 1189 | user-select: none; |
| 1217 | 1190 | } |
| 1218 | 1191 | .sidebar-top { |
| 1219 | 删除: height: 60px; | |
| 1192 | 新增: min-height: var(--workbench-header-height); | |
| 1193 | 新增: border-bottom: 1px solid var(--line); | |
| 1220 | 1194 | display: flex; |
| 1221 | 1195 | align-items: center; |
| 1222 | 1196 | justify-content: space-between; |
| @@ -1240,6 +1214,12 @@ svg { | ||
| 1240 | 1214 | gap: 3px; |
| 1241 | 1215 | padding: 0 0 24px; |
| 1242 | 1216 | } |
| 1217 | 新增:.workspace-sidebar:has(.account-menu) .sidebar-navigation { | |
| 1218 | 新增: overflow-y: auto; | |
| 1219 | 新增:} | |
| 1220 | 新增:.workspace-sidebar:has(.account-menu) .sidebar-scroll { | |
| 1221 | 新增: min-height: 4rem; | |
| 1222 | 新增:} | |
| 1243 | 1223 | .sidebar-link { |
| 1244 | 1224 | width: 100%; |
| 1245 | 1225 | min-height: 36px; |
| @@ -1377,21 +1357,59 @@ svg { | ||
| 1377 | 1357 | .tab-pin { |
| 1378 | 1358 | margin-left: auto; |
| 1379 | 1359 | } |
| 1360 | 新增:.tab-favicon { | |
| 1361 | 新增: flex: 0 0 auto; | |
| 1362 | 新增: object-fit: contain; | |
| 1363 | 新增:} | |
| 1380 | 1364 | .sidebar-tab.ended > button[role="tab"] { |
| 1381 | 1365 | color: var(--muted); |
| 1382 | 1366 | } |
| 1383 | 删除:.tab-more { | |
| 1384 | 删除: width: 24px; | |
| 1385 | 删除: height: 26px; | |
| 1386 | 删除: min-height: 26px; | |
| 1387 | 删除: margin-right: 3px; | |
| 1367 | 新增:.terminal-row-actions { | |
| 1368 | 新增: display: flex; | |
| 1369 | 新增: align-items: center; | |
| 1370 | 新增: visibility: hidden; | |
| 1371 | 新增: max-width: 0; | |
| 1372 | 新增: overflow: hidden; | |
| 1388 | 1373 | opacity: 0; |
| 1389 | 删除: color: var(--muted); | |
| 1374 | 新增: transform: translateX(10px); | |
| 1375 | 新增: transition: opacity 140ms ease, transform 140ms ease; | |
| 1390 | 1376 | } |
| 1391 | 删除:.sidebar-tab:hover .tab-more, | |
| 1392 | 删除:.sidebar-tab:focus-within .tab-more, | |
| 1393 | 删除:.sidebar-tab.active .tab-more { | |
| 1377 | 新增:.sidebar-tab:is(:hover, :focus-within) .terminal-row-actions { | |
| 1378 | 新增: visibility: visible; | |
| 1379 | 新增: max-width: none; | |
| 1380 | 新增: margin-right: 3px; | |
| 1394 | 1381 | opacity: 1; |
| 1382 | 新增: transform: none; | |
| 1383 | 新增:} | |
| 1384 | 新增:.terminal-row-actions > button { | |
| 1385 | 新增: flex: 0 0 25px; | |
| 1386 | 新增: width: 25px; | |
| 1387 | 新增: min-height: 26px; | |
| 1388 | 新增: height: 26px; | |
| 1389 | 新增: padding: 0; | |
| 1390 | 新增: color: var(--muted); | |
| 1391 | 新增:} | |
| 1392 | 新增:.terminal-row-actions > button:is(:hover, :focus-visible) { | |
| 1393 | 新增: background: var(--paper); | |
| 1394 | 新增: color: var(--strong); | |
| 1395 | 新增:} | |
| 1396 | 新增:.terminal-row-actions > button:focus-visible { | |
| 1397 | 新增: outline-offset: -2px; | |
| 1398 | 新增:} | |
| 1399 | 新增:.terminal-action-label { | |
| 1400 | 新增: display: none; | |
| 1401 | 新增: order: -1; | |
| 1402 | 新增: margin-inline: 2px 4px; | |
| 1403 | 新增: color: var(--muted); | |
| 1404 | 新增: font-size: 0.7857rem; | |
| 1405 | 新增: white-space: nowrap; | |
| 1406 | 新增:} | |
| 1407 | 新增:.terminal-row-actions > button:hover + .terminal-action-label, | |
| 1408 | 新增:.terminal-row-actions:not(:has(> button:hover)) > button:focus-visible + .terminal-action-label { | |
| 1409 | 新增: display: block; | |
| 1410 | 新增:} | |
| 1411 | 新增:@media (prefers-reduced-motion: reduce) { | |
| 1412 | 新增: .terminal-row-actions { transition: none; } | |
| 1395 | 1413 | } |
| 1396 | 1414 | .workspace-tab-menu { |
| 1397 | 1415 | position: fixed; |
| @@ -1411,14 +1429,15 @@ svg { | ||
| 1411 | 1429 | margin: 0; |
| 1412 | 1430 | } |
| 1413 | 1431 | .terminal-create-menu { |
| 1414 | 删除: position: fixed; | |
| 1415 | 删除: right: auto; | |
| 1432 | 新增: position: static; | |
| 1433 | 新增: width: min(100%, 184px); | |
| 1416 | 1434 | min-width: 0; |
| 1417 | 删除: width: 184px; | |
| 1418 | 删除: max-width: calc(100vw - 16px); | |
| 1419 | 删除: background: var(--paper); | |
| 1420 | 删除: box-shadow: 0 8px 24px #00000016; | |
| 1435 | 新增: margin: 3px 0; | |
| 1436 | 新增: box-shadow: none; | |
| 1421 | 1437 | } |
| 1438 | 新增:.sidebar-project > .terminal-create-menu, | |
| 1439 | 新增:.chrome > .terminal-create-menu { margin-inline-start: auto; } | |
| 1440 | 新增:.welcome-shortcuts + .terminal-create-menu { margin-inline: auto; } | |
| 1422 | 1441 | .terminal-create-menu button { |
| 1423 | 1442 | gap: 10px; |
| 1424 | 1443 | white-space: nowrap; |
| @@ -1466,17 +1485,18 @@ svg { | ||
| 1466 | 1485 | animation: pulse 1.4s infinite; |
| 1467 | 1486 | } |
| 1468 | 1487 | .content-heading { |
| 1469 | 删除: height: 60px; | |
| 1488 | 新增: min-height: var(--workbench-header-height); | |
| 1489 | 新增: border-bottom: 1px solid var(--line); | |
| 1470 | 1490 | display: flex; |
| 1471 | 1491 | align-items: center; |
| 1472 | 删除: gap: 12px; | |
| 1473 | 删除: padding: 0 24px; | |
| 1492 | 新增: gap: 8px; | |
| 1493 | 新增: padding: 0 12px; | |
| 1474 | 1494 | } |
| 1475 | 1495 | .content-breadcrumb { |
| 1476 | 1496 | display: flex; |
| 1477 | 1497 | align-items: center; |
| 1478 | 1498 | min-width: 0; |
| 1479 | 删除: gap: 10px; | |
| 1499 | 新增: gap: 6px; | |
| 1480 | 1500 | flex: 1; |
| 1481 | 1501 | font-size: 0.9286rem; |
| 1482 | 1502 | } |
| @@ -1488,7 +1508,7 @@ svg { | ||
| 1488 | 1508 | gap: 8px; |
| 1489 | 1509 | min-width: 0; |
| 1490 | 1510 | font-size: 0.9286rem; |
| 1491 | 删除: font-weight: 500; | |
| 1511 | 新增: font-weight: 400; | |
| 1492 | 1512 | max-width: 240px; |
| 1493 | 1513 | } |
| 1494 | 1514 | .content-breadcrumb span { |
| @@ -1499,13 +1519,21 @@ svg { | ||
| 1499 | 1519 | .content-breadcrumb > svg { |
| 1500 | 1520 | color: var(--muted); |
| 1501 | 1521 | } |
| 1522 | 新增:.content-breadcrumb svg { | |
| 1523 | 新增: flex: none; | |
| 1524 | 新增:} | |
| 1502 | 1525 | .current-title { |
| 1503 | 删除: color: var(--muted); | |
| 1526 | 新增: font-weight: 500; | |
| 1527 | 新增:} | |
| 1528 | 新增:.terminal-detail { | |
| 1529 | 新增: font-size: 0.8571rem; | |
| 1530 | 新增: opacity: 0.8; | |
| 1504 | 1531 | } |
| 1505 | 1532 | .heading-actions { |
| 1533 | 新增: flex: none; | |
| 1506 | 1534 | display: flex; |
| 1507 | 1535 | align-items: center; |
| 1508 | 删除: gap: 8px; | |
| 1536 | 新增: gap: 2px; | |
| 1509 | 1537 | } |
| 1510 | 1538 | .quiet-button { |
| 1511 | 1539 | min-height: 30px; |
| @@ -1514,17 +1542,10 @@ svg { | ||
| 1514 | 1542 | background: var(--paper); |
| 1515 | 1543 | } |
| 1516 | 1544 | .navigation-row { |
| 1517 | 删除: height: 44px; | |
| 1518 | 删除: padding: 0 18px; | |
| 1545 | 新增: height: var(--workbench-header-height); | |
| 1546 | 新增: padding: 0 12px; | |
| 1519 | 1547 | background: var(--paper); |
| 1520 | 1548 | } |
| 1521 | 删除:.terminal-path { | |
| 1522 | 删除: font-size: 0.8571rem; | |
| 1523 | 删除: color: var(--muted); | |
| 1524 | 删除:} | |
| 1525 | 删除:.terminal-kind { | |
| 1526 | 删除: font-size: 0.8571rem; | |
| 1527 | 删除:} | |
| 1528 | 1549 | .status-bar { |
| 1529 | 1550 | height: 32px; |
| 1530 | 1551 | background: var(--paper); |
| @@ -1856,14 +1877,14 @@ svg { | ||
| 1856 | 1877 | .settings-content { |
| 1857 | 1878 | flex: 1; |
| 1858 | 1879 | min-height: 0; |
| 1859 | 删除: padding: 56px max(40px, calc((100% - 720px) / 2)); | |
| 1880 | 新增: padding: 32px max(40px, calc((100% - 720px) / 2)); | |
| 1860 | 1881 | overflow: auto; |
| 1861 | 1882 | } |
| 1862 | 1883 | .settings-content .section-title { |
| 1863 | 删除: margin-bottom: 32px; | |
| 1884 | 新增: margin-bottom: 20px; | |
| 1864 | 1885 | } |
| 1865 | 1886 | .settings-content .section-title h3 { |
| 1866 | 删除: font-size: 1.7143rem; | |
| 1887 | 新增: font-size: 1.4286rem; | |
| 1867 | 1888 | font-weight: 600; |
| 1868 | 1889 | color: var(--strong); |
| 1869 | 1890 | margin-bottom: 10px; |
| @@ -1877,7 +1898,7 @@ svg { | ||
| 1877 | 1898 | margin: 28px 0 14px; |
| 1878 | 1899 | } |
| 1879 | 1900 | .settings-content input:not([type="checkbox"]):not([type="radio"]), |
| 1880 | 删除:.settings-content select { | |
| 1901 | 新增:.settings-content .inline-select-trigger { | |
| 1881 | 1902 | border-color: var(--line); |
| 1882 | 1903 | background: var(--paper); |
| 1883 | 1904 | height: 40px; |
| @@ -1950,9 +1971,6 @@ svg { | ||
| 1950 | 1971 | :root { |
| 1951 | 1972 | --sidebar-width: 224px; |
| 1952 | 1973 | } |
| 1953 | 删除: .content-heading { | |
| 1954 | 删除: padding: 0 16px; | |
| 1955 | 删除: } | |
| 1956 | 1974 | .content-breadcrumb > button { |
| 1957 | 1975 | max-width: 180px; |
| 1958 | 1976 | } |
| @@ -1961,14 +1979,11 @@ svg { | ||
| 1961 | 1979 | display: none; |
| 1962 | 1980 | } |
| 1963 | 1981 | .settings-content { |
| 1964 | 删除: padding: 40px 32px; | |
| 1982 | 新增: padding: 32px; | |
| 1965 | 1983 | } |
| 1966 | 1984 | .settings-footer { |
| 1967 | 1985 | padding: 16px 32px; |
| 1968 | 1986 | } |
| 1969 | 删除: .terminal-kind { | |
| 1970 | 删除: display: none; | |
| 1971 | 删除: } | |
| 1972 | 1987 | } |
| 1973 | 1988 | @media (max-width: 720px) { |
| 1974 | 1989 | :root { |
| @@ -1980,10 +1995,8 @@ svg { | ||
| 1980 | 1995 | .heading-actions { |
| 1981 | 1996 | gap: 2px; |
| 1982 | 1997 | } |
| 1983 | 删除: .heading-actions .quiet-button span, | |
| 1984 | 删除: .current-title, | |
| 1985 | 删除: .content-breadcrumb > svg { | |
| 1986 | 删除: display: none; | |
| 1998 | 新增: .content-breadcrumb:has(.current-title) > button { | |
| 1999 | 新增: max-width: 32%; | |
| 1987 | 2000 | } |
| 1988 | 2001 | .content-breadcrumb > button { |
| 1989 | 2002 | max-width: 145px; |
| @@ -2046,9 +2059,6 @@ svg { | ||
| 2046 | 2059 | .settings-content { |
| 2047 | 2060 | padding: 28px 16px; |
| 2048 | 2061 | } |
| 2049 | 删除: .settings-content .section-title h3 { | |
| 2050 | 删除: font-size: 1.4286rem; | |
| 2051 | 删除: } | |
| 2052 | 2062 | .back-to-workspace { |
| 2053 | 2063 | padding: 6px; |
| 2054 | 2064 | font-size: 0.8571rem; |
| @@ -2117,7 +2127,7 @@ svg { | ||
| 2117 | 2127 | gap: 4px; |
| 2118 | 2128 | min-width: 0; |
| 2119 | 2129 | padding: 4px 12px; |
| 2120 | 删除: height: 48px; | |
| 2130 | 新增: height: var(--workbench-header-height); | |
| 2121 | 2131 | background: var(--chrome); |
| 2122 | 2132 | } |
| 2123 | 2133 | .browser-tabs { |
| @@ -2199,7 +2209,16 @@ svg { | ||
| 2199 | 2209 | .browser-tab.sliver > [role="tab"]::after { content: ""; height: 14px; width: 2px; background: var(--muted); border-radius: 2px; opacity: .5; } |
| 2200 | 2210 | .browser-new-tab { order: 1; } |
| 2201 | 2211 | .browser-all-tabs { position: relative; order: 2; } |
| 2202 | 删除:.all-tabs-menu { right: 0; top: 36px; width: min(360px, calc(100vw - 32px)); } | |
| 2212 | 新增:.browser-tab-bar:has(.all-tabs-menu) { | |
| 2213 | 新增: display: grid; | |
| 2214 | 新增: grid-template-columns: minmax(0, 1fr) auto auto; | |
| 2215 | 新增: grid-template-rows: calc(var(--workbench-header-height) - 8px) auto; | |
| 2216 | 新增: height: auto; | |
| 2217 | 新增:} | |
| 2218 | 新增:.browser-tab-bar:has(.sidebar-expand):has(.all-tabs-menu) { grid-template-columns: auto minmax(0, 1fr) auto auto; } | |
| 2219 | 新增:.browser-all-tabs:has(.all-tabs-menu) { display: contents; } | |
| 2220 | 新增:.browser-all-tabs > .icon-button { order: 2; } | |
| 2221 | 新增:.all-tabs-menu { position: static; order: 3; grid-column: 1 / -1; justify-self: end; width: min(360px, 100%); box-shadow: none; } | |
| 2203 | 2222 | .all-tabs-menu input { width: 100%; margin-bottom: 8px; } |
| 2204 | 2223 | .all-tabs-results { max-height: min(440px, 65vh); overflow-y: auto; } |
| 2205 | 2224 | .all-tabs-results button { width: 100%; } |
| @@ -2221,14 +2240,14 @@ svg { | ||
| 2221 | 2240 | .favorites-panel h2 { margin: 0; flex: 1; font-size: 1.1429rem; font-weight: 600; color: var(--strong); } |
| 2222 | 2241 | .favorites-search { display: flex; align-items: center; gap: 8px; background: var(--chrome); padding: 0 8px; border-radius: 6px; } |
| 2223 | 2242 | .favorites-search input { width: 100%; min-width: 0; background: transparent; border: none; } |
| 2224 | 删除:.favorites-search input, .favorite-form input, .favorite-form select, .favorites-folder-select select, .all-tabs-menu input { | |
| 2243 | 新增:.favorites-search input, .favorite-form input, .favorite-form .inline-select-trigger, .favorites-folder-select .inline-select-trigger, .all-tabs-menu input { | |
| 2225 | 2244 | min-height: 34px; padding: 7px 8px; border: 1px solid var(--line); border-radius: 6px; |
| 2226 | 2245 | background: var(--input); color: var(--ink); font: inherit; |
| 2227 | 2246 | } |
| 2228 | 2247 | .favorites-search input { border: none; background: transparent; padding-inline: 0; } |
| 2229 | 2248 | .favorite-form { overflow-y: auto; } |
| 2230 | 2249 | .favorites-folder-select { display: flex; gap: 4px; align-items: center; } |
| 2231 | 删除:.favorites-folder-select select { flex: 1; min-width: 0; } | |
| 2250 | 新增:.favorites-folder-select .inline-select { flex: 1; min-width: 0; } | |
| 2232 | 2251 | .favorites-list { overflow-y: auto; min-height: 96px; } |
| 2233 | 2252 | .favorite-row { display: flex; align-items: center; border-radius: 6px; } |
| 2234 | 2253 | .favorite-row:hover { background: var(--hover); } |
| @@ -2243,7 +2262,7 @@ svg { | ||
| 2243 | 2262 | .favorites-empty span { font-size: 0.9286rem; } |
| 2244 | 2263 | .favorite-form { display: grid; gap: 16px; padding: 20px 24px; } |
| 2245 | 2264 | .favorite-form label { display: grid; gap: 8px; } |
| 2246 | 删除:.favorite-form input, .favorite-form select { width: 100%; min-width: 0; } | |
| 2265 | 新增:.favorite-form input, .favorite-form .inline-select-trigger { width: 100%; min-width: 0; } | |
| 2247 | 2266 | .favorites-error { color: var(--danger); white-space: normal; } |
| 2248 | 2267 | .favorites-error button { margin-top: 8px; } |
| 2249 | 2268 | .favorite-remove { margin-right: auto; } |
| @@ -2274,3 +2293,30 @@ svg { | ||
| 2274 | 2293 | @media (max-width: 1000px) { |
| 2275 | 2294 | .audio-controls input[type="range"] { width: 44px; } |
| 2276 | 2295 | } |
| 2296 | 新增: | |
| 2297 | 新增:.browser-tab-bar:has(.all-tabs-menu) .browser-tabs { max-width: 100%; } | |
| 2298 | 新增: | |
| 2299 | 新增:.browser-tab, .sidebar-tab { touch-action: none; user-select: none; } | |
| 2300 | 新增:.pane-lane { position: absolute; inset: 0; display: flex; flex-direction: column; min-width: 0; } | |
| 2301 | 新增:.pane-lane[hidden] { display: none; } | |
| 2302 | 新增:.pane-body { position: relative; flex: 1; min-height: 0; overflow: hidden; } | |
| 2303 | 新增:.workspace-split > .split-left, .split-drop.split-left { right: calc(100% - var(--split-left)); } | |
| 2304 | 新增:.workspace-split > .split-right, .split-drop.split-right { left: var(--split-left); } | |
| 2305 | 新增:.workspace-split > .pane-lane.split-right, .browser-header-cell + .browser-header-cell { border-left: 1px solid var(--line); } | |
| 2306 | 新增:.browser-headers { display: flex; min-width: 0; background: var(--chrome); } | |
| 2307 | 新增:.browser-header-cell { flex: 1; min-width: 0; } | |
| 2308 | 新增:.browser-header-cell:first-child:has(+ .browser-header-cell) { flex: 0 0 var(--split-left); } | |
| 2309 | 新增:.workspace-split .browser-header-cell[data-focused="true"] .browser-tab-bar, | |
| 2310 | 新增:.workspace-split .terminal-lane[data-focused="true"] .content-heading { box-shadow: inset 0 -2px var(--focus); } | |
| 2311 | 新增:.browser-tools { display: contents; } | |
| 2312 | 新增:.split-chrome .navigation-row { flex-wrap: wrap; height: auto; min-height: var(--workbench-header-height); gap: 3px; padding: 3px 6px; } | |
| 2313 | 新增:.split-chrome .browser-tab-bar, .workspace-split .content-heading { padding-inline: 6px; gap: 2px; } | |
| 2314 | 新增:.split-chrome .browser-tools { display: none; } | |
| 2315 | 新增:.split-chrome .browser-tools.open { display: flex; flex-wrap: wrap; gap: 4px; width: 100%; padding-block: 3px; } | |
| 2316 | 新增:.workspace-split .content-breadcrumb > button { max-width: 45%; } | |
| 2317 | 新增:.expand-pane { margin-left: auto; } | |
| 2318 | 新增:.split-drop { | |
| 2319 | 新增: position: absolute; inset: 0; z-index: 10; display: grid; place-items: center; | |
| 2320 | 新增: background: color-mix(in srgb, var(--accent) 15%, transparent); | |
| 2321 | 新增: border: 2px solid var(--accent); color: var(--accent); pointer-events: none; | |
| 2322 | 新增:} | |
| @@ -1,8 +1,6 @@ | ||
| 1 | 1 | import React, { useLayoutEffect, useRef } from "react"; |
| 2 | 删除:import { createPortal } from "react-dom"; | |
| 3 | 2 | import { Sparkles, TerminalSquare } from "lucide-react"; |
| 4 | 3 | |
| 5 | 删除:// Two equal actions (§2.8), grouped in the existing compact menu (§3.6). | |
| 6 | 4 | export function TerminalMenu({ choice, busy, onClose, onSelect }) { |
| 7 | 5 | const menu = useRef(null); |
| 8 | 6 | const close = useRef(onClose); |
| @@ -14,11 +12,6 @@ export function TerminalMenu({ choice, busy, onClose, onSelect }) { | ||
| 14 | 12 | close.current(); |
| 15 | 13 | return; |
| 16 | 14 | } |
| 17 | 删除: const rect = anchor.getBoundingClientRect(); | |
| 18 | 删除: const { width, height } = node.getBoundingClientRect(); | |
| 19 | 删除: node.style.left = `${Math.max(8, Math.min(rect.right - width, window.innerWidth - width - 8))}px`; | |
| 20 | 删除: node.style.top = `${Math.max(8, rect.bottom + height + 4 <= window.innerHeight - 8 | |
| 21 | 删除: ? rect.bottom + 4 : rect.top - height - 4)}px`; | |
| 22 | 15 | anchor.setAttribute("aria-expanded", "true"); |
| 23 | 16 | anchor.setAttribute("aria-controls", "terminal-create-menu"); |
| 24 | 17 | node.querySelector("button:not(:disabled)")?.focus(); |
| @@ -43,27 +36,20 @@ export function TerminalMenu({ choice, busy, onClose, onSelect }) { | ||
| 43 | 36 | items[next]?.focus(); |
| 44 | 37 | } |
| 45 | 38 | }; |
| 46 | 删除: const layoutChanged = (event) => { | |
| 47 | 删除: if (!node.contains(event.target)) dismiss(); | |
| 48 | 删除: }; | |
| 49 | 39 | const closeCommand = () => dismiss(true); |
| 50 | 删除: document.addEventListener("pointerdown", outside, true); | |
| 40 | 新增: document.addEventListener("click", outside, true); | |
| 51 | 41 | document.addEventListener("keydown", keydown, true); |
| 52 | 42 | document.addEventListener("cage-close-modal", closeCommand); |
| 53 | 删除: window.addEventListener("resize", layoutChanged); | |
| 54 | 删除: document.addEventListener("scroll", layoutChanged, true); | |
| 55 | 43 | return () => { |
| 56 | 44 | anchor.setAttribute("aria-expanded", "false"); |
| 57 | 45 | anchor.removeAttribute("aria-controls"); |
| 58 | 删除: document.removeEventListener("pointerdown", outside, true); | |
| 46 | 新增: document.removeEventListener("click", outside, true); | |
| 59 | 47 | document.removeEventListener("keydown", keydown, true); |
| 60 | 48 | document.removeEventListener("cage-close-modal", closeCommand); |
| 61 | 删除: window.removeEventListener("resize", layoutChanged); | |
| 62 | 删除: document.removeEventListener("scroll", layoutChanged, true); | |
| 63 | 49 | }; |
| 64 | 50 | }, [choice]); |
| 65 | 51 | |
| 66 | 删除: return createPortal( | |
| 52 | 新增: return ( | |
| 67 | 53 | <div ref={menu} id="terminal-create-menu" className="menu terminal-create-menu" role="menu" aria-label="新建终端"> |
| 68 | 54 | <button role="menuitem" disabled={busy} onClick={() => onSelect("shell")}> |
| 69 | 55 | <TerminalSquare size={16} />普通终端 |
| @@ -71,7 +57,6 @@ export function TerminalMenu({ choice, busy, onClose, onSelect }) { | ||
| 71 | 57 | <button role="menuitem" disabled={busy} onClick={() => onSelect("claude")}> |
| 72 | 58 | <Sparkles size={16} />Claude 终端 |
| 73 | 59 | </button> |
| 74 | 删除: </div>, | |
| 75 | 删除: document.body, | |
| 60 | 新增: </div> | |
| 76 | 61 | ); |
| 77 | 62 | } |
| @@ -1,4 +1,4 @@ | ||
| 1 | 删除:import { terminalModifier } from "./platform.mjs"; | |
| 1 | 新增:import { isMac, terminalModifier } from "./platform.mjs"; | |
| 2 | 2 | import React, { |
| 3 | 3 | useEffect, |
| 4 | 4 | useRef, |
| @@ -21,7 +21,7 @@ import { RefreshCw, Clipboard, ArrowUpRight } from "lucide-react"; | ||
| 21 | 21 | import "@xterm/xterm/css/xterm.css"; |
| 22 | 22 | |
| 23 | 23 | export const RemoteView = forwardRef(function RemoteView( |
| 24 | 删除: { visible, keyboard, tabId, onStatus, onFallback, desktop = false, zoom = 1 }, | |
| 24 | 新增: { visible, focused = true, keyboard, tabId, copyScope = tabId, onStatus, onFallback, desktop = false, zoom = 1 }, | |
| 25 | 25 | ref, |
| 26 | 26 | ) { |
| 27 | 27 | const windowVisible = useWindowVisibility(); |
| @@ -31,12 +31,13 @@ export const RemoteView = forwardRef(function RemoteView( | ||
| 31 | 31 | input = useRef(), |
| 32 | 32 | current = useRef({ visible, keyboard, onStatus, onFallback }), |
| 33 | 33 | displayResize = useRef(); |
| 34 | 删除: current.current = { visible: screenVisible, keyboard, tabId, onStatus, onFallback, zoom }; | |
| 34 | 新增: current.current = { visible: screenVisible && focused, keyboard, tabId, onStatus, onFallback, zoom }; | |
| 35 | 35 | const failures = useRef(0); |
| 36 | 36 | const [connection, setConnection] = useState("connecting"), |
| 37 | 37 | [attempt, setAttempt] = useState(0), |
| 38 | 38 | [sizeError, setSizeError] = useState(false); |
| 39 | 39 | useEffect(() => { displayResize.current?.update(); }, [zoom]); |
| 40 | 新增: useEffect(() => { input.current?.cancelCopy(); }, [copyScope]); | |
| 40 | 41 | useImperativeHandle(ref, () => ({ |
| 41 | 42 | focus: () => rfb.current?.focus(), |
| 42 | 43 | edit: (action) => |
| @@ -44,6 +45,7 @@ export const RemoteView = forwardRef(function RemoteView( | ||
| 44 | 45 | ? input.current?.edit(action) |
| 45 | 46 | : false, |
| 46 | 47 | copy: () => input.current?.copy(), |
| 48 | 新增: receiveCopy: (value) => input.current?.receiveCopy(value), | |
| 47 | 49 | paste: () => input.current?.readAndPaste(), |
| 48 | 50 | pasteText: (text) => input.current?.paste(text), |
| 49 | 51 | transfer: () => |
| @@ -98,6 +100,17 @@ export const RemoteView = forwardRef(function RemoteView( | ||
| 98 | 100 | resizeObserver.observe(box.current); |
| 99 | 101 | resize(); |
| 100 | 102 | input.current = installRemoteInput(client, box.current, { |
| 103 | 新增: setCopyContext: desktop ? undefined : (context, valid) => client.cageRunInput(async () => { | |
| 104 | 新增: if (!valid()) return; | |
| 105 | 新增: try { await api("/browser/copy-context", { id: current.current.tabId, context }); } | |
| 106 | 新增: catch { | |
| 107 | 新增: if (valid()) { | |
| 108 | 新增: input.current?.cancelCopy(); | |
| 109 | 新增: current.current.onStatus("复制按钮同步暂未就绪,可使用复制快捷键或文本传递"); | |
| 110 | 新增: } | |
| 111 | 新增: // A metadata failure must not cancel the user's queued click. | |
| 112 | 新增: } | |
| 113 | 新增: }), | |
| 101 | 114 | pasteContent: (content) => { |
| 102 | 115 | const id = current.current.tabId; |
| 103 | 116 | const valid = () => !disposed && current.current.visible && current.current.tabId === id; |
| @@ -139,7 +152,7 @@ export const RemoteView = forwardRef(function RemoteView( | ||
| 139 | 152 | onStatus: (t) => current.current.onStatus(t), |
| 140 | 153 | onFallback: (...args) => current.current.onFallback(...args), |
| 141 | 154 | }); |
| 142 | 删除: if (current.current.visible) client.focus(); | |
| 155 | 新增: if (current.current.visible && !document.activeElement?.closest(".chrome")) client.focus(); | |
| 143 | 156 | }); |
| 144 | 157 | client.addEventListener("disconnect", () => { |
| 145 | 158 | if (disposed) return; |
| @@ -170,11 +183,11 @@ export const RemoteView = forwardRef(function RemoteView( | ||
| 170 | 183 | }; |
| 171 | 184 | }, [attempt, screenVisible, desktop]); |
| 172 | 185 | useEffect(() => { |
| 173 | 删除: if (screenVisible && connection === "connected") { | |
| 174 | 删除: const t = setTimeout(() => rfb.current?.focus(), 80); | |
| 186 | 新增: if (focused && screenVisible && connection === "connected") { | |
| 187 | 新增: const t = setTimeout(() => { if (!document.activeElement?.closest(".chrome")) rfb.current?.focus(); }, 80); | |
| 175 | 188 | return () => clearTimeout(t); |
| 176 | 189 | } |
| 177 | 删除: }, [screenVisible, connection]); | |
| 190 | 新增: }, [focused, screenVisible, connection]); | |
| 178 | 191 | return ( |
| 179 | 192 | <div className={`remote-view ${visible ? "" : "concealed"}`}> |
| 180 | 193 | <div className="remote-canvas" ref={box} /> |
| @@ -205,7 +218,7 @@ export const RemoteView = forwardRef(function RemoteView( | ||
| 205 | 218 | ); |
| 206 | 219 | }); |
| 207 | 220 | |
| 208 | 删除:export function TerminalView({ session, visible, onStatus, onControls }) { | |
| 221 | 新增:export function TerminalView({ session, visible, focused = true, onStatus, onControls }) { | |
| 209 | 222 | const { appearance, theme, variant } = useAppearance(); |
| 210 | 223 | const box = useRef(), |
| 211 | 224 | instance = useRef(), |
| @@ -215,6 +228,8 @@ export function TerminalView({ session, visible, onStatus, onControls }) { | ||
| 215 | 228 | [attempt, setAttempt] = useState(0); |
| 216 | 229 | const visibleRef = useRef(visible); |
| 217 | 230 | visibleRef.current = visible; |
| 231 | 新增: const focusedRef = useRef(focused); | |
| 232 | 新增: focusedRef.current = focused; | |
| 218 | 233 | useEffect(() => { |
| 219 | 234 | let disposed = false, emittingPaste = false, inputChain = Promise.resolve(); |
| 220 | 235 | const enqueue = (action) => { |
| @@ -229,6 +244,7 @@ export function TerminalView({ session, visible, onStatus, onControls }) { | ||
| 229 | 244 | fontSize: appearance.codeFontSize, |
| 230 | 245 | lineHeight: 1.3, |
| 231 | 246 | cursorBlink: true, |
| 247 | 新增: macOptionClickForcesSelection: true, | |
| 232 | 248 | minimumContrastRatio: 4.5, |
| 233 | 249 | scrollback: 6000, |
| 234 | 250 | theme: terminalTheme(theme, variant), |
| @@ -260,7 +276,7 @@ export function TerminalView({ session, visible, onStatus, onControls }) { | ||
| 260 | 276 | ws.onopen = () => { |
| 261 | 277 | setConnected(true); |
| 262 | 278 | resize(); |
| 263 | 删除: if (visibleRef.current) terminal.focus(); | |
| 279 | 新增: if (visibleRef.current && focusedRef.current) terminal.focus(); | |
| 264 | 280 | }; |
| 265 | 281 | ws.onmessage = (event) => terminal.write(new Uint8Array(event.data)); |
| 266 | 282 | ws.onclose = () => setConnected(false); |
| @@ -279,17 +295,17 @@ export function TerminalView({ session, visible, onStatus, onControls }) { | ||
| 279 | 295 | void enqueue(async () => { |
| 280 | 296 | const { value, error } = await ready; |
| 281 | 297 | if (error) throw error; |
| 282 | 删除: if (disposed || !visibleRef.current || ws.readyState !== WebSocket.OPEN) throw new Error("终端已切换或断开,请重新粘贴"); | |
| 298 | 新增: if (disposed || !visibleRef.current || !focusedRef.current || ws.readyState !== WebSocket.OPEN) throw new Error("终端已切换或断开,请重新粘贴"); | |
| 283 | 299 | let text = value.text || ""; |
| 284 | 300 | if (value.files || value.fileSelection) { |
| 285 | 删除: const result = await sendFiles(value, "terminal", session.id, { valid: () => !disposed && visibleRef.current && ws.readyState === WebSocket.OPEN }); | |
| 301 | 新增: const result = await sendFiles(value, "terminal", session.id, { valid: () => !disposed && visibleRef.current && focusedRef.current && ws.readyState === WebSocket.OPEN }); | |
| 286 | 302 | text = shellFilePaths(result.paths); |
| 287 | 303 | } |
| 288 | 304 | if (value.png) { |
| 289 | 305 | const result = await sendImage(value, "terminal", session.id); |
| 290 | 306 | text = `'${result.path}' `; |
| 291 | 307 | } |
| 292 | 删除: if (disposed || !visibleRef.current) throw new Error("终端已切换,请回到原终端重新粘贴"); | |
| 308 | 新增: if (disposed || !visibleRef.current || !focusedRef.current) throw new Error("终端已切换,请回到原终端重新粘贴"); | |
| 293 | 309 | // Honor xterm's bracketed-paste mode without enqueuing behind this job. |
| 294 | 310 | emittingPaste = true; |
| 295 | 311 | try { terminal.paste(text); } finally { emittingPaste = false; } |
| @@ -317,14 +333,23 @@ export function TerminalView({ session, visible, onStatus, onControls }) { | ||
| 317 | 333 | host.addEventListener("paste", onPaste, true); |
| 318 | 334 | host.addEventListener("dragover", onDragOver); |
| 319 | 335 | host.addEventListener("drop", onDrop); |
| 336 | 新增: const copySelection = () => { | |
| 337 | 新增: const text = terminal.getSelection(); | |
| 338 | 新增: if (!text) { | |
| 339 | 新增: onStatus(terminal.modes.mouseTrackingMode === "none" | |
| 340 | 新增: ? "请先拖选要复制的终端文字" | |
| 341 | 新增: : `当前程序接管了鼠标。请按住 ${isMac ? "Option" : "Shift"} 拖选文字,再复制。`); | |
| 342 | 新增: return; | |
| 343 | 新增: } | |
| 344 | 新增: void writeClipboard(text) | |
| 345 | 新增: .then(() => onStatus("已复制终端选中文本")) | |
| 346 | 新增: .catch(() => onStatus("无法写入本机剪贴板")); | |
| 347 | 新增: }; | |
| 320 | 348 | onControls?.({ |
| 321 | 349 | edit(action) { |
| 322 | 350 | if (!box.current?.contains(document.activeElement)) return false; |
| 323 | 351 | if (action === "copy") { |
| 324 | 删除: if (terminal.hasSelection()) | |
| 325 | 删除: void writeClipboard(terminal.getSelection()).catch(() => | |
| 326 | 删除: onStatus("无法写入本机剪贴板"), | |
| 327 | 删除: ); | |
| 352 | 新增: copySelection(); | |
| 328 | 353 | return true; |
| 329 | 354 | } |
| 330 | 355 | if (action === "paste") { |
| @@ -343,10 +368,7 @@ export function TerminalView({ session, visible, onStatus, onControls }) { | ||
| 343 | 368 | const key = event.key.toLowerCase(); |
| 344 | 369 | if (key === "c") { |
| 345 | 370 | event.preventDefault(); |
| 346 | 删除: if (terminal.hasSelection()) | |
| 347 | 删除: writeClipboard(terminal.getSelection()) | |
| 348 | 删除: .then(() => onStatus("已复制终端选中文本")) | |
| 349 | 删除: .catch(() => onStatus("请使用右键菜单复制选中文本")); | |
| 371 | 新增: copySelection(); | |
| 350 | 372 | return false; |
| 351 | 373 | } |
| 352 | 374 | if (key === "v") { |
| @@ -389,13 +411,13 @@ export function TerminalView({ session, visible, onStatus, onControls }) { | ||
| 389 | 411 | useEffect(() => { |
| 390 | 412 | if (visible) { |
| 391 | 413 | fit.current?.fit(); |
| 392 | 删除: instance.current?.focus(); | |
| 414 | 新增: if (focused) instance.current?.focus(); | |
| 393 | 415 | const ws = socket.current, |
| 394 | 416 | t = instance.current; |
| 395 | 417 | if (ws?.readyState === WebSocket.OPEN && t) |
| 396 | 418 | ws.send(JSON.stringify({ type: "resize", cols: t.cols, rows: t.rows })); |
| 397 | 419 | } |
| 398 | 删除: }, [visible]); | |
| 420 | 新增: }, [visible, focused]); | |
| 399 | 421 | useEffect(() => { |
| 400 | 422 | if (!instance.current) return; |
| 401 | 423 | instance.current.options.theme = terminalTheme(theme, variant); |
| @@ -409,7 +431,7 @@ export function TerminalView({ session, visible, onStatus, onControls }) { | ||
| 409 | 431 | {!connected && ( |
| 410 | 432 | <div className="terminal-note"> |
| 411 | 433 | {session.closed |
| 412 | 删除: ? "终端会话已结束。可从项目旁的 + 新建终端。" | |
| 434 | 新增: ? "终端会话已结束。可点击项目右侧的终端图标新建终端。" | |
| 413 | 435 | : "正在连接终端…"} |
| 414 | 436 | {!session.closed && ( |
| 415 | 437 | <button onClick={() => setAttempt((v) => v + 1)}> |
| @@ -440,6 +462,7 @@ export function Modal({ title, children, onClose, wide = false, footer }) { | ||
| 440 | 462 | ) |
| 441 | 463 | return; |
| 442 | 464 | if (e.key === "Escape") { |
| 465 | 新增: if (e.target.closest('[role="combobox"][aria-expanded="true"]')) return; | |
| 443 | 466 | e.preventDefault(); |
| 444 | 467 | e.stopPropagation(); |
| 445 | 468 | closeRef.current?.(); |
| @@ -1,9 +1,8 @@ | ||
| 1 | 1 | import { shortcut } from "./platform.mjs"; |
| 2 | 2 | import React, { useEffect, useState } from "react"; |
| 3 | 3 | import { |
| 4 | 删除: ArrowUpRight, | |
| 4 | 新增: ExternalLink, | |
| 5 | 5 | ChevronDown, |
| 6 | 删除: FileCode2, | |
| 7 | 6 | FolderOpen, |
| 8 | 7 | Globe2, |
| 9 | 8 | Home, |
| @@ -12,6 +11,7 @@ import { | ||
| 12 | 11 | PanelLeftClose, |
| 13 | 12 | Plus, |
| 14 | 13 | Settings2, |
| 14 | 新增: SquareTerminal, | |
| 15 | 15 | } from "lucide-react"; |
| 16 | 16 | import { EnvironmentShield } from "./environment-shield"; |
| 17 | 17 | import logo from "./logo.png"; |
| @@ -40,7 +40,9 @@ export function WorkspaceSidebar({ | ||
| 40 | 40 | onRename, |
| 41 | 41 | onPin, |
| 42 | 42 | onReorder, |
| 43 | 新增: splitDrag, | |
| 43 | 44 | onNewTerminal, |
| 45 | 新增: terminalMenuAt, | |
| 44 | 46 | onBrowser, |
| 45 | 47 | downloadAction, |
| 46 | 48 | onClaudeWeb, |
| @@ -100,23 +102,6 @@ export function WorkspaceSidebar({ | ||
| 100 | 102 | <button className={`sidebar-link ${desktopOpen ? "selected" : ""}`} onClick={onClaudeDesktop} disabled={!running || busy} title="安装或打开 Claude Desktop"><Monitor size={17} />Claude Desktop</button> |
| 101 | 103 | </div> |
| 102 | 104 | {downloadAction} |
| 103 | 删除: <button | |
| 104 | 删除: className="sidebar-link" | |
| 105 | 删除: onClick={() => onOpenProject()} | |
| 106 | 删除: disabled={busy || !running} | |
| 107 | 删除: > | |
| 108 | 删除: <FolderOpen size={17} /> | |
| 109 | 删除: 打开项目<kbd>{shortcut("⌘O")}</kbd> | |
| 110 | 删除: </button> | |
| 111 | 删除: <button | |
| 112 | 删除: className="sidebar-link" | |
| 113 | 删除: onClick={() => onEditor()} | |
| 114 | 删除: disabled={!ready || busy} | |
| 115 | 删除: > | |
| 116 | 删除: <FileCode2 size={17} /> | |
| 117 | 删除: 项目文件 | |
| 118 | 删除: <ArrowUpRight size={14} className="navigation-trailing" /> | |
| 119 | 删除: </button> | |
| 120 | 105 | </nav> |
| 121 | 106 | <div className="sidebar-scroll"> |
| 122 | 107 | <div className="sidebar-section-heading"> |
| @@ -132,10 +117,7 @@ export function WorkspaceSidebar({ | ||
| 132 | 117 | </button> |
| 133 | 118 | </div> |
| 134 | 119 | {projects.map((path) => { |
| 135 | 删除: const project = | |
| 136 | 删除: path === defaultWorkspace && path.endsWith("-workspace") | |
| 137 | 删除: ? "默认工作区" | |
| 138 | 删除: : projectName(path); | |
| 120 | 新增: const project = projectName(path, defaultWorkspace); | |
| 139 | 121 | const terminals = tabs.filter( |
| 140 | 122 | (tab) => tab.kind === "terminal" && tab.workspace === path, |
| 141 | 123 | ); |
| @@ -168,11 +150,21 @@ export function WorkspaceSidebar({ | ||
| 168 | 150 | <FolderOpen size={16} /> |
| 169 | 151 | <span>{project}</span> |
| 170 | 152 | </button> |
| 153 | 新增: <button | |
| 154 | 新增: className="icon-button" | |
| 155 | 新增: aria-label={`打开 ${project} 的编辑器`} | |
| 156 | 新增: title="在 code-server 中打开项目目录" | |
| 157 | 新增: disabled={!ready || busy} | |
| 158 | 新增: onClick={() => onEditor(path)} | |
| 159 | 新增: > | |
| 160 | 新增: <ExternalLink size={15} /> | |
| 161 | 新增: </button> | |
| 171 | 162 | <button |
| 172 | 163 | className="icon-button" |
| 173 | 164 | aria-label={`在 ${project} 新建终端`} |
| 174 | 165 | title="新建终端" |
| 175 | 166 | aria-haspopup="menu" |
| 167 | 新增: data-terminal-location={path} | |
| 176 | 168 | disabled={!running || busy} |
| 177 | 169 | onClick={(event) => { |
| 178 | 170 | setCollapsed((previous) => ({ |
| @@ -182,9 +174,10 @@ export function WorkspaceSidebar({ | ||
| 182 | 174 | onNewTerminal(path, event.currentTarget); |
| 183 | 175 | }} |
| 184 | 176 | > |
| 185 | 删除: <Plus size={15} /> | |
| 177 | 新增: <SquareTerminal size={15} /> | |
| 186 | 178 | </button> |
| 187 | 179 | </div> |
| 180 | 新增: {terminalMenuAt(path)} | |
| 188 | 181 | <div |
| 189 | 182 | className={`project-children ${expanded ? "expanded" : ""}`} |
| 190 | 183 | inert={!expanded} |
| @@ -203,12 +196,11 @@ export function WorkspaceSidebar({ | ||
| 203 | 196 | onRename={onRename} |
| 204 | 197 | onPin={onPin} |
| 205 | 198 | onReorder={onReorder} |
| 199 | 新增: splitDrag={splitDrag} | |
| 206 | 200 | /> |
| 207 | 201 | )} |
| 208 | 删除: {!terminals.length && ( | |
| 209 | 删除: <p className="sidebar-empty"> | |
| 210 | 删除: {running ? "点击 + 新建终端" : "启动后可新建终端"} | |
| 211 | 删除: </p> | |
| 202 | 新增: {!terminals.length && !running && ( | |
| 203 | 新增: <p className="sidebar-empty">启动后可新建终端</p> | |
| 212 | 204 | )} |
| 213 | 205 | </div> |
| 214 | 206 | </div> |
| @@ -19,8 +19,10 @@ export function orderedTabs(tabs, saved) { | ||
| 19 | 19 | }); |
| 20 | 20 | } |
| 21 | 21 | |
| 22 | 删除:export const projectName = (path) => | |
| 23 | 删除: path?.split(/[\\/]/).filter(Boolean).at(-1) || "新项目"; | |
| 22 | 新增:export const projectName = (path, defaultWorkspace) => | |
| 23 | 新增: path === defaultWorkspace && path?.endsWith("-workspace") | |
| 24 | 新增: ? "默认工作区" | |
| 25 | 新增: : path?.split(/[\\/]/).filter(Boolean).at(-1) || "新项目"; | |
| 24 | 26 | |
| 25 | 27 | export function tabName(tab, saved, project) { |
| 26 | 28 | return ( |
| @@ -31,3 +33,23 @@ export function tabName(tab, saved, project) { | ||
| 31 | 33 | "新标签页" |
| 32 | 34 | ); |
| 33 | 35 | } |
| 36 | 新增: | |
| 37 | 新增:// The focused tab and its neighbour retain their screen positions on focus changes. | |
| 38 | 新增:export function focusTab(layout, id) { | |
| 39 | 新增: if (layout.active === id) return layout; | |
| 40 | 新增: if (!id) return { active: "" }; | |
| 41 | 新增: if (layout.other === id) | |
| 42 | 新增: return { active: id, other: layout.active, side: layout.side === "left" ? "right" : "left" }; | |
| 43 | 新增: if (layout.other && id.startsWith("terminal:") !== layout.active.startsWith("terminal:") && | |
| 44 | 新增: id.startsWith("terminal:") === layout.other.startsWith("terminal:")) | |
| 45 | 新增: return { ...focusTab(layout, layout.other), active: id }; | |
| 46 | 新增: return { ...layout, active: id }; | |
| 47 | 新增:} | |
| 48 | 新增: | |
| 49 | 新增:export function splitTab(layout, tabs, id, side) { | |
| 50 | 新增: if (!tabs.some(tab => tab.id === id)) return layout; | |
| 51 | 新增: const opposite = layout.side === side ? layout.other : layout.active; | |
| 52 | 新增: const other = [opposite, layout.other, layout.active, ...tabs.map(tab => tab.id)] | |
| 53 | 新增: .find(candidate => candidate !== id && tabs.some(tab => tab.id === candidate)); | |
| 54 | 新增: return other ? { active: id, other, side } : layout; | |
| 55 | 新增:} | |
| @@ -5,21 +5,35 @@ import { | ||
| 5 | 5 | FileCode2, |
| 6 | 6 | ChevronDown, |
| 7 | 7 | Globe2, |
| 8 | 删除: MoreHorizontal, | |
| 8 | 新增: Pencil, | |
| 9 | 9 | Pin, |
| 10 | 新增: PinOff, | |
| 10 | 11 | TerminalSquare, |
| 11 | 12 | X, |
| 12 | 13 | } from "lucide-react"; |
| 13 | 14 | import { tabName } from "./workspace-state.mjs"; |
| 14 | 15 | |
| 15 | 删除:export const TabIcon = ({ kind, size = 16 }) => | |
| 16 | 删除: kind === "terminal" ? ( | |
| 17 | 删除: <TerminalSquare size={size} /> | |
| 18 | 删除: ) : kind === "editor" ? ( | |
| 19 | 删除: <FileCode2 size={size} /> | |
| 20 | 删除: ) : ( | |
| 21 | 删除: <Globe2 size={size} /> | |
| 16 | 新增:export function TabIcon({ kind, favicon, size = 16 }) { | |
| 17 | 新增: const [failed, setFailed] = useState(""); | |
| 18 | 新增: if (kind === "terminal") return <TerminalSquare size={size} />; | |
| 19 | 新增: if (kind === "editor") return <FileCode2 size={size} />; | |
| 20 | 新增: if (typeof favicon === "string" && favicon.length <= 8192 && | |
| 21 | 新增: /^data:image\/png;base64,[A-Za-z0-9+/=]+$/.test(favicon) && failed !== favicon) | |
| 22 | 新增: return <img src={favicon} className="tab-favicon" alt="" width={size} height={size} | |
| 23 | 新增: draggable={false} onError={() => setFailed(favicon)} />; | |
| 24 | 新增: return <Globe2 size={size} />; | |
| 25 | 新增:} | |
| 26 | 新增: | |
| 27 | 新增:function TerminalAction({ label, icon: Icon, disabled, onClick }) { | |
| 28 | 新增: return ( | |
| 29 | 新增: <> | |
| 30 | 新增: <button className="icon-button" aria-label={label} disabled={disabled} onClick={onClick}> | |
| 31 | 新增: <Icon size={14} /> | |
| 32 | 新增: </button> | |
| 33 | 新增: <span className="terminal-action-label" aria-hidden="true">{label}</span> | |
| 34 | 新增: </> | |
| 22 | 35 | ); |
| 36 | 新增:} | |
| 23 | 37 | |
| 24 | 38 | // Active content carries the strongest emphasis; titles and actions use the |
| 25 | 39 | // existing paper/selected/muted tokens, 14px type and 8px spacing in both layouts. |
| @@ -36,9 +50,9 @@ export function WorkspaceTabs({ | ||
| 36 | 50 | onRename, |
| 37 | 51 | onPin, |
| 38 | 52 | onReorder, |
| 53 | 新增: splitDrag, | |
| 39 | 54 | }) { |
| 40 | 55 | const [menu, setMenu] = useState(null); |
| 41 | 删除: const [dragged, setDragged] = useState(null); | |
| 42 | 56 | const [drag, setDrag] = useState(null); |
| 43 | 57 | const [allOpen, setAllOpen] = useState(false); |
| 44 | 58 | const [query, setQuery] = useState(""); |
| @@ -73,13 +87,22 @@ export function WorkspaceTabs({ | ||
| 73 | 87 | .toLowerCase() |
| 74 | 88 | .includes(query.toLowerCase()), |
| 75 | 89 | ); |
| 76 | 删除: const finishDrag = (commit) => { | |
| 90 | 新增: const finishDrag = (commit, event) => { | |
| 77 | 91 | const current = pointer.current; |
| 78 | 92 | pointer.current = null; |
| 79 | 93 | setDrag(null); |
| 80 | 删除: if (current?.moved) { | |
| 81 | 删除: suppressClick.current = true; | |
| 82 | 删除: if (commit) onReorder(current.id, null, current.order); | |
| 94 | 新增: splitDrag.clear(); | |
| 95 | 新增: if (!current?.moved) return; | |
| 96 | 新增: suppressClick.current = true; | |
| 97 | 新增: if (!commit) return; | |
| 98 | 新增: const { clientX, clientY } = event; | |
| 99 | 新增: if (splitDrag.drop(current.id, clientX, clientY)) return; | |
| 100 | 新增: const over = document.elementFromPoint(clientX, clientY); | |
| 101 | 新增: if (!list.current?.contains(over)) return; | |
| 102 | 新增: if (horizontal) onReorder(current.id, null, current.order); | |
| 103 | 新增: else { | |
| 104 | 新增: const target = over?.closest("[data-tab-id]")?.dataset.tabId; | |
| 105 | 新增: if (target && target !== current.id) onReorder(current.id, target); | |
| 83 | 106 | } |
| 84 | 107 | }; |
| 85 | 108 | useEffect(() => { |
| @@ -93,46 +116,39 @@ export function WorkspaceTabs({ | ||
| 93 | 116 | document.addEventListener("keydown", cancel, true); |
| 94 | 117 | return () => document.removeEventListener("keydown", cancel, true); |
| 95 | 118 | }, [Boolean(drag)]); |
| 119 | 新增: useEffect(() => () => splitDrag.clear(), []); | |
| 96 | 120 | const startDrag = (event, tab) => { |
| 97 | 删除: if ( | |
| 98 | 删除: !horizontal || | |
| 99 | 删除: busy || | |
| 100 | 删除: !ready || | |
| 101 | 删除: event.button !== 0 || | |
| 102 | 删除: event.target.closest(".tab-close") | |
| 103 | 删除: ) | |
| 104 | 删除: return; | |
| 105 | 121 | suppressClick.current = false; |
| 106 | 删除: const items = [...list.current.children].map((node) => ({ | |
| 122 | 新增: if (busy || (!ready && tab.kind !== "terminal") || event.button !== 0 || | |
| 123 | 新增: !event.isPrimary || event.target.closest(".tab-close, .terminal-row-actions")) return; | |
| 124 | 新增: const items = [...list.current.querySelectorAll(":scope > [data-tab-id]")].map((node) => ({ | |
| 107 | 125 | id: node.dataset.tabId, |
| 108 | 126 | left: node.offsetLeft, |
| 109 | 127 | width: node.getBoundingClientRect().width, |
| 110 | 128 | })); |
| 111 | 删除: const group = items.filter( | |
| 112 | 删除: (item) => | |
| 113 | 删除: Boolean(saved[item.id]?.pinned) === Boolean(saved[tab.id]?.pinned), | |
| 114 | 删除: ); | |
| 129 | 新增: const group = items.filter(item => | |
| 130 | 新增: Boolean(saved[item.id]?.pinned) === Boolean(saved[tab.id]?.pinned)); | |
| 115 | 131 | pointer.current = { |
| 116 | 删除: id: tab.id, | |
| 117 | 删除: startX: event.clientX, | |
| 118 | 删除: items, | |
| 119 | 删除: group, | |
| 120 | 删除: order: items.map((item) => item.id), | |
| 121 | 删除: moved: false, | |
| 132 | 新增: id: tab.id, startX: event.clientX, startY: event.clientY, | |
| 133 | 新增: items, group, order: items.map(item => item.id), moved: false, | |
| 122 | 134 | }; |
| 135 | 新增: (event.target.closest("button") || event.currentTarget).setPointerCapture(event.pointerId); | |
| 123 | 136 | }; |
| 124 | 137 | const moveDrag = (event) => { |
| 125 | 138 | const current = pointer.current; |
| 126 | 139 | if (!current) return; |
| 127 | 删除: if (event.buttons === 0) { | |
| 128 | 删除: finishDrag(false); | |
| 129 | 删除: return; | |
| 130 | 删除: } | |
| 131 | 删除: const item = current.items.find((item) => item.id === current.id); | |
| 140 | 新增: if (!event.buttons) return finishDrag(false); | |
| 132 | 141 | let dx = event.clientX - current.startX; |
| 133 | 删除: if (!current.moved && Math.abs(dx) < 5) return; | |
| 134 | 删除: if (!current.moved) event.currentTarget.setPointerCapture(event.pointerId); | |
| 142 | 新增: if (!current.moved && Math.hypot(dx, event.clientY - current.startY) < 5) return; | |
| 135 | 143 | current.moved = true; |
| 144 | 新增: const dropSide = splitDrag.hover(current.id, event.clientX, event.clientY); | |
| 145 | 新增: if (!horizontal || dropSide) { | |
| 146 | 新增: setDrag({ id: current.id, offsets: {}, widths: {} }); | |
| 147 | 新增: return; | |
| 148 | 新增: } | |
| 149 | 新增: const item = current.items.find(item => item.id === current.id); | |
| 150 | 新增: // Clamp the tab's drawing to its group, but let the pointer cross the last tab's center. | |
| 151 | 新增: const center = item.left + item.width / 2 + dx; | |
| 136 | 152 | dx = Math.max( |
| 137 | 153 | current.group[0].left - item.left, |
| 138 | 154 | Math.min( |
| @@ -143,7 +159,6 @@ export function WorkspaceTabs({ | ||
| 143 | 159 | item.width, |
| 144 | 160 | ), |
| 145 | 161 | ); |
| 146 | 删除: const center = item.left + item.width / 2 + dx; | |
| 147 | 162 | const rest = current.group.filter((other) => other.id !== item.id); |
| 148 | 163 | const target = rest.filter( |
| 149 | 164 | (other) => center > other.left + other.width / 2, |
| @@ -171,6 +186,11 @@ export function WorkspaceTabs({ | ||
| 171 | 186 | }; |
| 172 | 187 | const showMenu = (tab, event) => { |
| 173 | 188 | event.preventDefault(); |
| 189 | 新增: if (!horizontal) { | |
| 190 | 新增: event.currentTarget.focus(); | |
| 191 | 新增: event.currentTarget.parentElement.querySelector(".terminal-row-actions button:not(:disabled)")?.focus(); | |
| 192 | 新增: return; | |
| 193 | 新增: } | |
| 174 | 194 | trigger.current = event.currentTarget; |
| 175 | 195 | const rect = event.currentTarget.getBoundingClientRect(); |
| 176 | 196 | setMenu({ |
| @@ -195,9 +215,52 @@ export function WorkspaceTabs({ | ||
| 195 | 215 | trigger.current?.focus(); |
| 196 | 216 | } |
| 197 | 217 | }; |
| 218 | 新增: const outside = (event) => { | |
| 219 | 新增: if (event.target.closest(".all-tabs-menu") || trigger.current?.contains(event.target)) return; | |
| 220 | 新增: setAllOpen(false); | |
| 221 | 新增: }; | |
| 198 | 222 | document.addEventListener("keydown", dismiss); |
| 199 | 删除: return () => document.removeEventListener("keydown", dismiss); | |
| 223 | 新增: document.addEventListener("click", outside, true); | |
| 224 | 新增: return () => { | |
| 225 | 新增: document.removeEventListener("keydown", dismiss); | |
| 226 | 新增: document.removeEventListener("click", outside, true); | |
| 227 | 新增: }; | |
| 200 | 228 | }, [menu, allOpen]); |
| 229 | 新增: const actions = menu && ( | |
| 230 | 新增: <div className="menu workspace-tab-menu" | |
| 231 | 新增: style={{ top: menu.top, left: menu.left }} | |
| 232 | 新增: role="menu" aria-label="标签操作"> | |
| 233 | 新增: <button | |
| 234 | 新增: role="menuitem" | |
| 235 | 新增: onClick={() => { | |
| 236 | 新增: setMenu(null); | |
| 237 | 新增: onRename(menu.tab); | |
| 238 | 新增: }} | |
| 239 | 新增: > | |
| 240 | 新增: 重命名标签 | |
| 241 | 新增: </button> | |
| 242 | 新增: <button | |
| 243 | 新增: role="menuitem" | |
| 244 | 新增: onClick={() => { | |
| 245 | 新增: setMenu(null); | |
| 246 | 新增: onPin(menu.tab.id); | |
| 247 | 新增: }} | |
| 248 | 新增: > | |
| 249 | 新增: <Pin size={14} /> | |
| 250 | 新增: {saved[menu.tab.id]?.pinned ? "取消置顶" : "置顶标签"} | |
| 251 | 新增: </button> | |
| 252 | 新增: <button | |
| 253 | 新增: role="menuitem" | |
| 254 | 新增: onClick={() => { | |
| 255 | 新增: setMenu(null); | |
| 256 | 新增: onClose(menu.tab); | |
| 257 | 新增: }} | |
| 258 | 新增: > | |
| 259 | 新增: <X size={15} /> | |
| 260 | 新增: 关闭标签<kbd>{shortcut("⌘W")}</kbd> | |
| 261 | 新增: </button> | |
| 262 | 新增: </div> | |
| 263 | 新增: ); | |
| 201 | 264 | return ( |
| 202 | 265 | <> |
| 203 | 266 | <div |
| @@ -239,7 +302,7 @@ export function WorkspaceTabs({ | ||
| 239 | 302 | } |
| 240 | 303 | onPointerDown={(event) => startDrag(event, tab)} |
| 241 | 304 | onPointerMove={moveDrag} |
| 242 | 删除: onPointerUp={() => finishDrag(true)} | |
| 305 | 新增: onPointerUp={(event) => finishDrag(true, event)} | |
| 243 | 306 | onPointerCancel={() => finishDrag(false)} |
| 244 | 307 | onLostPointerCapture={() => { |
| 245 | 308 | if (pointer.current) finishDrag(false); |
| @@ -251,25 +314,10 @@ export function WorkspaceTabs({ | ||
| 251 | 314 | suppressClick.current = false; |
| 252 | 315 | } |
| 253 | 316 | }} |
| 254 | 删除: draggable={!horizontal && !busy} | |
| 255 | 删除: onDragStart={(event) => { | |
| 256 | 删除: setDragged(tab.id); | |
| 257 | 删除: event.dataTransfer.setData("text/plain", tab.id); | |
| 258 | 删除: event.dataTransfer.effectAllowed = "move"; | |
| 259 | 删除: }} | |
| 260 | 删除: onDragOver={(event) => { | |
| 261 | 删除: if (dragged) event.preventDefault(); | |
| 262 | 删除: }} | |
| 263 | 删除: onDrop={(event) => { | |
| 264 | 删除: event.preventDefault(); | |
| 265 | 删除: if (dragged) onReorder(dragged, tab.id); | |
| 266 | 删除: setDragged(null); | |
| 267 | 删除: }} | |
| 268 | 删除: onDragEnd={() => setDragged(null)} | |
| 269 | 317 | > |
| 270 | 318 | <button |
| 271 | 319 | role="tab" |
| 272 | 删除: aria-label={title} | |
| 320 | 新增: aria-label={tab.claudeLabel ? `${title} · ${tab.claudeLabel}` : title} | |
| 273 | 321 | aria-selected={tab.id === active} |
| 274 | 322 | tabIndex={ |
| 275 | 323 | tab.id === active || |
| @@ -278,7 +326,7 @@ export function WorkspaceTabs({ | ||
| 278 | 326 | : -1 |
| 279 | 327 | } |
| 280 | 328 | disabled={!ready && tab.kind !== "terminal"} |
| 281 | 删除: title={tab.url ? `${title}\n${tab.url}` : title} | |
| 329 | 新增: title={tab.url ? `${title}\n${tab.url}` : tab.claudeLabel ? `${title} · ${tab.claudeLabel}` : title} | |
| 282 | 330 | onClick={() => onSelect(tab.id)} |
| 283 | 331 | onContextMenu={(event) => showMenu(tab, event)} |
| 284 | 332 | onKeyDown={(event) => { |
| @@ -303,8 +351,9 @@ export function WorkspaceTabs({ | ||
| 303 | 351 | onSelect(tabs[at].id); |
| 304 | 352 | }} |
| 305 | 353 | > |
| 306 | 删除: <TabIcon kind={tab.kind} size={15} /> | |
| 354 | 新增: <TabIcon kind={tab.kind} favicon={tab.favicon} size={15} /> | |
| 307 | 355 | <span>{title}</span> |
| 356 | 新增: {tab.claudeLabel && <small className="claude-tab-profile">{tab.claudeLabel}</small>} | |
| 308 | 357 | {saved[tab.id]?.pinned && <Pin size={11} className="tab-pin" />} |
| 309 | 358 | </button> |
| 310 | 359 | {horizontal ? ( |
| @@ -317,14 +366,12 @@ export function WorkspaceTabs({ | ||
| 317 | 366 | <X size={14} /> |
| 318 | 367 | </button> |
| 319 | 368 | ) : ( |
| 320 | 删除: <button | |
| 321 | 删除: className="tab-more icon-button" | |
| 322 | 删除: aria-label={`管理 ${title}`} | |
| 323 | 删除: onClick={(event) => showMenu(tab, event)} | |
| 324 | 删除: disabled={busy} | |
| 325 | 删除: > | |
| 326 | 删除: <MoreHorizontal size={15} /> | |
| 327 | 删除: </button> | |
| 369 | 新增: <div className="terminal-row-actions" role="group" aria-label={`${title} 的操作`}> | |
| 370 | 新增: <TerminalAction label={saved[tab.id]?.pinned ? "取消置顶" : "置顶"} | |
| 371 | 新增: icon={saved[tab.id]?.pinned ? PinOff : Pin} disabled={busy} onClick={() => onPin(tab.id)} /> | |
| 372 | 新增: <TerminalAction label="重命名" icon={Pencil} disabled={busy} onClick={() => onRename(tab)} /> | |
| 373 | 新增: <TerminalAction label="删除" icon={X} disabled={busy} onClick={() => onClose(tab)} /> | |
| 374 | 新增: </div> | |
| 328 | 375 | )} |
| 329 | 376 | </div> |
| 330 | 377 | ); |
| @@ -347,7 +394,7 @@ export function WorkspaceTabs({ | ||
| 347 | 394 | </button> |
| 348 | 395 | {allOpen && ( |
| 349 | 396 | <> |
| 350 | 删除: <div className="menu-dismiss" onClick={() => setAllOpen(false)} /> | |
| 397 | 新增: | |
| 351 | 398 | <div |
| 352 | 399 | className="menu all-tabs-menu" |
| 353 | 400 | role="dialog" |
| @@ -373,7 +420,7 @@ export function WorkspaceTabs({ | ||
| 373 | 420 | onSelect(tab.id); |
| 374 | 421 | }} |
| 375 | 422 | > |
| 376 | 删除: <TabIcon kind={tab.kind} /> | |
| 423 | 新增: <TabIcon kind={tab.kind} favicon={tab.favicon} /> | |
| 377 | 424 | <span>{tabName(tab, saved)}</span> |
| 378 | 425 | {tab.id === active && ( |
| 379 | 426 | <span className="current-tab-marker">当前</span> |
| @@ -390,42 +437,7 @@ export function WorkspaceTabs({ | ||
| 390 | 437 | createPortal( |
| 391 | 438 | <> |
| 392 | 439 | <div className="menu-dismiss" onClick={() => setMenu(null)} /> |
| 393 | 删除: <div | |
| 394 | 删除: className="menu workspace-tab-menu" | |
| 395 | 删除: style={{ top: menu.top, left: menu.left }} | |
| 396 | 删除: role="menu" | |
| 397 | 删除: aria-label="标签操作" | |
| 398 | 删除: > | |
| 399 | 删除: <button | |
| 400 | 删除: role="menuitem" | |
| 401 | 删除: onClick={() => { | |
| 402 | 删除: setMenu(null); | |
| 403 | 删除: onRename(menu.tab); | |
| 404 | 删除: }} | |
| 405 | 删除: > | |
| 406 | 删除: 重命名标签 | |
| 407 | 删除: </button> | |
| 408 | 删除: <button | |
| 409 | 删除: role="menuitem" | |
| 410 | 删除: onClick={() => { | |
| 411 | 删除: setMenu(null); | |
| 412 | 删除: onPin(menu.tab.id); | |
| 413 | 删除: }} | |
| 414 | 删除: > | |
| 415 | 删除: <Pin size={14} /> | |
| 416 | 删除: {saved[menu.tab.id]?.pinned ? "取消置顶" : "置顶标签"} | |
| 417 | 删除: </button> | |
| 418 | 删除: <button | |
| 419 | 删除: role="menuitem" | |
| 420 | 删除: onClick={() => { | |
| 421 | 删除: setMenu(null); | |
| 422 | 删除: onClose(menu.tab); | |
| 423 | 删除: }} | |
| 424 | 删除: > | |
| 425 | 删除: <X size={15} /> | |
| 426 | 删除: 关闭标签<kbd>{shortcut("⌘W")}</kbd> | |
| 427 | 删除: </button> | |
| 428 | 删除: </div> | |
| 440 | 新增: {actions} | |
| 429 | 441 | </>, |
| 430 | 442 | document.body, |
| 431 | 443 | )} |
| @@ -1,12 +1,12 @@ | ||
| 1 | 1 | { |
| 2 | 2 | "name": "claude-cage-website", |
| 3 | 删除: "version": "0.1.4-alpha", | |
| 3 | 新增: "version": "0.1.5-alpha", | |
| 4 | 4 | "lockfileVersion": 3, |
| 5 | 5 | "requires": true, |
| 6 | 6 | "packages": { |
| 7 | 7 | "": { |
| 8 | 8 | "name": "claude-cage-website", |
| 9 | 删除: "version": "0.1.4-alpha", | |
| 9 | 新增: "version": "0.1.5-alpha", | |
| 10 | 10 | "license": "MIT", |
| 11 | 11 | "dependencies": { |
| 12 | 12 | "@fontsource-variable/inter": "^5.3.0", |
| @@ -1,7 +1,7 @@ | ||
| 1 | 1 | { |
| 2 | 2 | "name": "claude-cage-website", |
| 3 | 3 | "type": "module", |
| 4 | 删除: "version": "0.1.4-alpha", | |
| 4 | 新增: "version": "0.1.5-alpha", | |
| 5 | 5 | "private": true, |
| 6 | 6 | "description": "Claude Cage project website and macOS, Windows and Linux downloads", |
| 7 | 7 | "license": "MIT", |

