提交记录修改.github/workflows/linux-build.yml+1 −0看文件
修改.github/workflows/macos-build.yml+2 −0看文件
修改desktop/AccountDevice.swift+44 −8看文件
新增desktop/AccountDeviceTests.swift+47 −0看文件
修改desktop/linux/cage-desktop.c+13 −9看文件
修改desktop/windows/MainWindow.cs+3 −0看文件
修改docs/design/workbench.md+4 −0看文件
修改docs/troubleshooting.md+6 −0看文件
修改internal/cage/claude_desktop.go+11 −0看文件
修改internal/cage/claude_desktop_test.go+70 −64看文件
新增internal/cage/desktop-downloads.py+174 −0看文件
新增internal/cage/desktop-downloads.test.py+202 −0看文件
修改internal/cage/desktop-files.py+30 −8看文件
修改internal/cage/guest-open.sh+10 −1看文件
修改internal/cage/guest.go+6 −1看文件
修改internal/workbench/environment_versions_test.go+5 −0看文件
修改internal/workbench/file_input.go+39 −2看文件
修改internal/workbench/file_input_test.go+53 −0看文件
新增scripts/test-account-device.sh+31 −0看文件
修改ui/scripts/account-device-smoke.mjs+83 −6看文件
修改ui/scripts/browser-files-smoke.mjs+4 −4看文件
新增ui/scripts/desktop-downloads-smoke.mjs+56 −0看文件
修改ui/scripts/recovery-ui-smoke.mjs+1 −1看文件
修改ui/src/account.jsx+52 −17看文件
修改ui/src/app-updates.jsx+1 −1看文件
修改ui/src/browser-downloads.jsx+34 −6看文件
修改ui/src/claude-desktop.jsx+1 −12看文件
修改ui/src/main.jsx+7 −4看文件
修改ui/src/style.css+2 −2看文件
| @@ -76,6 +76,7 @@ jobs: | ||
| 76 | 76 | chown -R cage:cage "$GITHUB_WORKSPACE" |
| 77 | 77 | runuser -u cage -- go test ./internal/... ./cmd/... |
| 78 | 78 | runuser -u cage -- go vet ./internal/managedproxy ./internal/workbench ./cmd/cage |
| 79 | 新增: runuser -u cage -- env UV_CACHE_DIR=/home/cage/.cache/uv uv run --no-project --python 3.11 internal/cage/desktop-downloads.test.py | |
| 79 | 80 | - name: Install, render native workbench, reinstall and remove |
| 80 | 81 | run: | |
| 81 | 82 | runuser -u cage -- bwrap --unshare-user --unshare-pid --ro-bind / / --proc /proc --dev /dev -- true |
| @@ -73,6 +73,8 @@ jobs: | ||
| 73 | 73 | go vet ./cmd/cage ./internal/cage ./internal/managedproxy ./internal/workbench |
| 74 | 74 | - name: Native application updater |
| 75 | 75 | run: bash scripts/test-app-updates.sh |
| 76 | 新增: - name: Native account credential status | |
| 77 | 新增: run: bash scripts/test-account-device.sh | |
| 76 | 78 | - name: Patched networking and shared files |
| 77 | 79 | run: go test github.com/containers/gvisor-tap-vsock/pkg/services/dns github.com/lima-vm/lima/v2/pkg/hostagent/dns github.com/lima-vm/lima/v2/pkg/networks/usernet github.com/lima-vm/sshocker/pkg/reversesshfs |
| 78 | 80 | - name: Dependency licenses |
| @@ -19,7 +19,6 @@ final class CageAccountDevice: NSObject, URLSessionTaskDelegate, @unchecked Send | ||
| 19 | 19 | }() |
| 20 | 20 | private let base: URL |
| 21 | 21 | private let ticket: String |
| 22 | 删除: private static let service = "io.github.lee-xeo.claude-cage.account" | |
| 23 | 22 | |
| 24 | 23 | init(entry: URL) throws { |
| 25 | 24 | guard entry.scheme == "http", entry.host == "localhost", let ticket = entry.fragment, !ticket.isEmpty else { throw CageAccountError("本地账户连接无效") } |
| @@ -43,6 +42,10 @@ final class CageAccountDevice: NSObject, URLSessionTaskDelegate, @unchecked Send | ||
| 43 | 42 | guard let value = try JSONSerialization.jsonObject(with: data) as? [String: Any] else { throw CageAccountError("本地账户响应无效") } |
| 44 | 43 | return value |
| 45 | 44 | } |
| 45 | 新增:} | |
| 46 | 新增: | |
| 47 | 新增:enum CageAccountKeychain { | |
| 48 | 新增: private static let service = "io.github.lee-xeo.claude-cage.account" | |
| 46 | 49 | private static func query(binding: String, kind: String) -> [String: Any] { |
| 47 | 50 | var result: [String: Any] = [kSecClass as String: kSecClassGenericPassword, |
| 48 | 51 | kSecAttrService as String: service, |
| @@ -53,13 +56,14 @@ final class CageAccountDevice: NSObject, URLSessionTaskDelegate, @unchecked Send | ||
| 53 | 56 | } |
| 54 | 57 | return result |
| 55 | 58 | } |
| 56 | 删除: private static func remove(binding: String, kind: String) throws { | |
| 59 | 新增: static func remove(binding: String, kind: String) throws { | |
| 57 | 60 | let status = SecItemDelete(query(binding: binding, kind: kind) as CFDictionary) |
| 58 | 61 | guard status == errSecSuccess || status == errSecItemNotFound else { throw CageAccountError("无法移除本机钥匙串记录,请重试") } |
| 59 | 62 | } |
| 60 | 删除: private static func store(_ credential: [String: Any], binding: String, kind: String) throws { | |
| 63 | 新增: static func store(_ credential: [String: Any], binding: String, kind: String) throws { | |
| 61 | 64 | var item = query(binding: binding, kind: kind) |
| 62 | 65 | item[kSecValueData as String] = try JSONSerialization.data(withJSONObject: credential) |
| 66 | 新增: if let id = credential["id"] as? String { item[kSecAttrGeneric as String] = Data(id.utf8) } | |
| 63 | 67 | item[kSecAttrLabel as String] = kind == "biometric" ? "Cage 指纹解锁" : "Cage 记住登录" |
| 64 | 68 | if kind == "biometric" { |
| 65 | 69 | var error: Unmanaged<CFError>? |
| @@ -70,7 +74,32 @@ final class CageAccountDevice: NSObject, URLSessionTaskDelegate, @unchecked Send | ||
| 70 | 74 | let status = SecItemAdd(item as CFDictionary, nil) |
| 71 | 75 | guard status == errSecSuccess else { throw CageAccountError("macOS 未能保存快捷登录凭据(\(status)),密码登录仍然可用") } |
| 72 | 76 | } |
| 73 | 删除: private static func read(binding: String, kind: String) throws -> [String: Any] { | |
| 77 | 新增: // Inspect metadata only. Status checks must not read the secret or ask for | |
| 78 | 新增: // Touch ID, and must never search credentials belonging to another path. | |
| 79 | 新增: static func status(binding: String, kind: String, expectedID: String?) -> String { | |
| 80 | 新增: guard let expectedID else { return "disabled" } | |
| 81 | 新增: var item = query(binding: binding, kind: kind) | |
| 82 | 新增: item[kSecReturnAttributes as String] = true | |
| 83 | 新增: item[kSecMatchLimit as String] = kSecMatchLimitOne | |
| 84 | 新增: let context = LAContext() | |
| 85 | 新增: context.interactionNotAllowed = true | |
| 86 | 新增: item[kSecUseAuthenticationContext as String] = context | |
| 87 | 新增: var result: CFTypeRef? | |
| 88 | 新增: let status = SecItemCopyMatching(item as CFDictionary, &result) | |
| 89 | 新增: return availability(status: status, attributes: result as? [String: Any], expectedID: expectedID, kind: kind) | |
| 90 | 新增: } | |
| 91 | 新增: static func availability(status: OSStatus, attributes: [String: Any]?, expectedID: String, kind: String) -> String { | |
| 92 | 新增: if status == errSecItemNotFound { return "missing" } | |
| 93 | 新增: // A protected item can require Touch ID even to return attributes. | |
| 94 | 新增: // Preserve its explicit unlock button without claiming it is verified. | |
| 95 | 新增: if kind == "biometric" && status == errSecInteractionNotAllowed { return "authentication_required" } | |
| 96 | 新增: guard status == errSecSuccess, let attributes else { return "unavailable" } | |
| 97 | 新增: // Older entries have no ID metadata. They remain usable at their | |
| 98 | 新增: // original binding; unlock still validates the ID in the secret. | |
| 99 | 新增: if let id = attributes[kSecAttrGeneric as String] as? Data, id != Data(expectedID.utf8) { return "missing" } | |
| 100 | 新增: return "available" | |
| 101 | 新增: } | |
| 102 | 新增: static func read(binding: String, kind: String) throws -> [String: Any] { | |
| 74 | 103 | var item = query(binding: binding, kind: kind) |
| 75 | 104 | item[kSecReturnData as String] = true; item[kSecMatchLimit as String] = kSecMatchLimitOne |
| 76 | 105 | let context = LAContext() |
| @@ -89,6 +118,9 @@ final class CageAccountDevice: NSObject, URLSessionTaskDelegate, @unchecked Send | ||
| 89 | 118 | let value = try JSONSerialization.jsonObject(with: data) as? [String: Any] else { throw CageAccountError("快捷登录不可用,请使用密码解锁后重新开启") } |
| 90 | 119 | return value |
| 91 | 120 | } |
| 121 | 新增:} | |
| 122 | 新增: | |
| 123 | 新增:extension CageAccountDevice { | |
| 92 | 124 | func handle(operation: String, kind: String?) async throws -> [String: Any] { |
| 93 | 125 | defer { session.invalidateAndCancel() } |
| 94 | 126 | _ = try await call("@session", ["token": ticket]) |
| @@ -97,26 +129,30 @@ final class CageAccountDevice: NSObject, URLSessionTaskDelegate, @unchecked Send | ||
| 97 | 129 | let context = LAContext() |
| 98 | 130 | let biometricAvailable = context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) |
| 99 | 131 | if operation == "status" { |
| 100 | 删除: return ["supported": true, "biometric_available": biometricAvailable] | |
| 132 | 新增: let devices = account["devices"] as? [String: String] ?? [:] | |
| 133 | 新增: let states = Dictionary(uniqueKeysWithValues: ["automatic", "biometric"].map { kind in | |
| 134 | 新增: (kind, CageAccountKeychain.status(binding: binding, kind: kind, expectedID: devices[kind])) | |
| 135 | 新增: }) | |
| 136 | 新增: return ["supported": true, "biometric_available": biometricAvailable, "device_status": states] | |
| 101 | 137 | } |
| 102 | 138 | guard let kind, ["automatic", "biometric"].contains(kind) else { throw CageAccountError("快捷登录类型无效") } |
| 103 | 139 | switch operation { |
| 104 | 140 | case "enable": |
| 105 | 141 | if kind == "biometric" && !biometricAvailable { throw CageAccountError("请先在 macOS 系统设置中设置 Touch ID") } |
| 106 | 142 | let credential = try await call("/device-enroll", ["kind": kind]) |
| 107 | 删除: do { try Self.store(credential, binding: binding, kind: kind) } | |
| 143 | 新增: do { try CageAccountKeychain.store(credential, binding: binding, kind: kind) } | |
| 108 | 144 | catch { |
| 109 | 145 | _ = try? await call("/device-revoke", ["kind": kind]) |
| 110 | 146 | throw error |
| 111 | 147 | } |
| 112 | 148 | case "disable": |
| 113 | 149 | _ = try await call("/device-revoke", ["kind": kind]) |
| 114 | 删除: try Self.remove(binding: binding, kind: kind) | |
| 150 | 新增: try CageAccountKeychain.remove(binding: binding, kind: kind) | |
| 115 | 151 | case "unlock": |
| 116 | 152 | // Check persisted manual-lock state before touching the Keychain. |
| 117 | 153 | if kind == "automatic" && account["require_authentication"] as? Bool == true { throw CageAccountError("Cage 已手动锁定,请使用指纹或密码") } |
| 118 | 154 | guard let devices = account["devices"] as? [String: String], let expectedID = devices[kind] else { throw CageAccountError("请先使用密码登录,再开启快捷登录") } |
| 119 | 删除: let credential = try Self.read(binding: binding, kind: kind) | |
| 155 | 新增: let credential = try CageAccountKeychain.read(binding: binding, kind: kind) | |
| 120 | 156 | guard credential["id"] as? String == expectedID else { throw CageAccountError("快捷登录授权已失效,请使用密码") } |
| 121 | 157 | _ = try await call("/device-unlock", ["kind": kind, "credential": credential]) |
| 122 | 158 | default: throw CageAccountError("快捷登录操作无效") |
| @@ -0,0 +1,47 @@ | ||
| 1 | 新增:import Foundation | |
| 2 | 新增:import Security | |
| 3 | 新增:import LocalAuthentication | |
| 4 | 新增: | |
| 5 | 新增:@main | |
| 6 | 新增:enum AccountDeviceTests { | |
| 7 | 新增: static func check(_ value: Bool, line: UInt = #line) throws { | |
| 8 | 新增: if !value { throw CageAccountError("AccountDeviceTests failed at line \(line)") } | |
| 9 | 新增: } | |
| 10 | 新增: static func main() throws { | |
| 11 | 新增: let source = "cage-account-test-" + UUID().uuidString | |
| 12 | 新增: let destination = "cage-account-test-" + UUID().uuidString | |
| 13 | 新增: let credential = ["id": UUID().uuidString, "secret": UUID().uuidString] | |
| 14 | 新增: let kinds = CommandLine.arguments.contains("--biometric") ? ["automatic", "biometric"] : ["automatic"] | |
| 15 | 新增: for kind in kinds { | |
| 16 | 新增: defer { | |
| 17 | 新增: try? CageAccountKeychain.remove(binding: source, kind: kind) | |
| 18 | 新增: try? CageAccountKeychain.remove(binding: destination, kind: kind) | |
| 19 | 新增: } | |
| 20 | 新增: let present = kind == "biometric" ? ["available", "authentication_required"] : ["available"] | |
| 21 | 新增: try CageAccountKeychain.store(credential, binding: source, kind: kind) | |
| 22 | 新增: try check(present.contains(CageAccountKeychain.status(binding: source, kind: kind, expectedID: credential["id"]))) | |
| 23 | 新增: // The same server record at a new directory must not inherit the | |
| 24 | 新增: // old path's enrollment. Checking metadata must not prompt. | |
| 25 | 新增: try check(CageAccountKeychain.status(binding: destination, kind: kind, expectedID: credential["id"]) == "missing") | |
| 26 | 新增: let mismatched = CageAccountKeychain.status(binding: source, kind: kind, expectedID: "other-id") | |
| 27 | 新增: try check(mismatched == "missing" || (kind == "biometric" && mismatched == "authentication_required")) | |
| 28 | 新增: try check(CageAccountKeychain.status(binding: source, kind: kind, expectedID: nil) == "disabled") | |
| 29 | 新增: try CageAccountKeychain.store(credential, binding: destination, kind: kind) | |
| 30 | 新增: try check(present.contains(CageAccountKeychain.status(binding: destination, kind: kind, expectedID: credential["id"]))) | |
| 31 | 新增: if kind == "automatic" { | |
| 32 | 新增: let read = try CageAccountKeychain.read(binding: destination, kind: kind) | |
| 33 | 新增: try check(read["id"] as? String == credential["id"]) | |
| 34 | 新增: try check(read["secret"] as? String == credential["secret"]) | |
| 35 | 新增: } | |
| 36 | 新增: try CageAccountKeychain.remove(binding: destination, kind: kind) | |
| 37 | 新增: try check(CageAccountKeychain.status(binding: destination, kind: kind, expectedID: credential["id"]) == "missing") | |
| 38 | 新增: print("PASS: \(kind) binding, migration, metadata/authentication status, re-enrollment and removal") | |
| 39 | 新增: } | |
| 40 | 新增: // A legacy item without ID metadata remains compatible at its binding. | |
| 41 | 新增: try check(CageAccountKeychain.availability(status: errSecSuccess, attributes: [:], expectedID: "legacy", kind: "automatic") == "available") | |
| 42 | 新增: for error in [errSecInteractionNotAllowed, errSecNotAvailable, errSecMissingEntitlement, errSecAuthFailed, errSecUserCanceled] { | |
| 43 | 新增: try check(CageAccountKeychain.availability(status: error, attributes: nil, expectedID: "id", kind: "automatic") == "unavailable") | |
| 44 | 新增: } | |
| 45 | 新增: print("PASS: legacy metadata and transient/permission errors are not treated as missing credentials") | |
| 46 | 新增: } | |
| 47 | 新增:} | |
| @@ -446,7 +446,9 @@ static void smoke_evaluated(GObject *source, GAsyncResult *result, gpointer data | ||
| 446 | 446 | GError *error = NULL; |
| 447 | 447 | JSCValue *value = webkit_web_view_call_async_javascript_function_finish(WEBKIT_WEB_VIEW(source), result, &error); |
| 448 | 448 | if (!value || error || !jsc_value_is_object(value)) { |
| 449 | 删除: g_printerr("Linux smoke: authenticated workbench verification failed.\n"); | |
| 449 | 新增: g_printerr("Linux smoke: authenticated workbench verification failed (error domain=%s, code=%d, object=%d).\n", | |
| 450 | 新增: error ? g_quark_to_string(error->domain) : "none", error ? error->code : 0, | |
| 451 | 新增: value ? jsc_value_is_object(value) : FALSE); | |
| 450 | 452 | g_clear_error(&error); g_clear_object(&value); |
| 451 | 453 | g_application_quit(G_APPLICATION(app.application)); |
| 452 | 454 | return; |
| @@ -466,7 +468,7 @@ static void smoke_evaluated(GObject *source, GAsyncResult *result, gpointer data | ||
| 466 | 468 | webkit_web_view_get_snapshot(app.web, WEBKIT_SNAPSHOT_REGION_VISIBLE, WEBKIT_SNAPSHOT_OPTIONS_NONE, |
| 467 | 469 | NULL, smoke_snapshot, report); |
| 468 | 470 | } else { |
| 469 | 删除: g_printerr("Linux smoke: workbench evidence was incomplete.\n"); | |
| 471 | 新增: g_printerr("Linux smoke: workbench evidence was incomplete: %s\n", json ? json : "null"); | |
| 470 | 472 | g_application_quit(G_APPLICATION(app.application)); |
| 471 | 473 | } |
| 472 | 474 | g_free(json); g_object_unref(parser); g_object_unref(value); |
| @@ -476,23 +478,25 @@ static gboolean start_smoke(gpointer data) { | ||
| 476 | 478 | char *phase = quote(app.storage_phase ? app.storage_phase : ""); |
| 477 | 479 | char *marker = quote(app.storage_marker ? app.storage_marker : ""); |
| 478 | 480 | char *body = g_strdup_printf( |
| 481 | 新增: "let stage='storage';try{" | |
| 479 | 482 | "const phase=%s,marker=%s;const storageKey='cage-linux-smoke-persistence';" |
| 480 | 483 | "if(phase==='seed')localStorage.setItem(storageKey,marker);" |
| 481 | 484 | "const storageMarkerMatched=!phase||localStorage.getItem(storageKey)===marker;" |
| 482 | 485 | "if(phase==='verify'&&storageMarkerMatched)localStorage.removeItem(storageKey);" |
| 483 | 删除: "const bridge=window.webkit.messageHandlers.cage;" | |
| 486 | 新增: "stage='bridge';const bridge=window.webkit.messageHandlers.cage;" | |
| 484 | 487 | "let unauthenticatedBridgeDenied=false;try{await window.webkit.messageHandlers.cageTransport.postMessage({token:'invalid',request:{action:'clipboardRead'}});}catch{unauthenticatedBridgeDenied=true;}" |
| 485 | 删除: "const native=await bridge.postMessage({action:'accountDevice',operation:'status'});" | |
| 486 | 删除: "const update=await bridge.postMessage({action:'appUpdate',operation:'status'});" | |
| 487 | 删除: "const accountResponse=await fetch('/api/account');const account=await accountResponse.json();" | |
| 488 | 删除: "const stateResponse=await fetch('/api/status');const state=await stateResponse.json();" | |
| 489 | 删除: "const settingsResponse=await fetch('/api/settings');await settingsResponse.json();" | |
| 488 | 新增: "stage='account-device';const native=await bridge.postMessage({action:'accountDevice',operation:'status'});" | |
| 489 | 新增: "stage='app-update';const update=await bridge.postMessage({action:'appUpdate',operation:'status'});" | |
| 490 | 新增: "stage='account';const accountResponse=await fetch('/api/account');const account=await accountResponse.json();" | |
| 491 | 新增: "stage='status';const stateResponse=await fetch('/api/status');const state=await stateResponse.json();" | |
| 492 | 新增: "stage='settings';const settingsResponse=await fetch('/api/settings');await settingsResponse.json();" | |
| 490 | 493 | "const root=document.getElementById('root');" |
| 491 | 494 | "const rendered=!!root&&root.innerText.trim().length>40&&root.querySelectorAll('button').length>3;" |
| 492 | 495 | "const success=rendered&&accountResponse.ok&&account.unlocked===true&&stateResponse.ok&&settingsResponse.ok&&native.supported===false&&update.phase==='manual'&&unauthenticatedBridgeDenied&&storageMarkerMatched;" |
| 493 | 496 | "return {success,nativeBridgeReady:true,authenticated:accountResponse.ok,accountUnlocked:account.unlocked===true," |
| 494 | 497 | "workbenchRendered:rendered,workbenchReadyAcknowledged:true,statusReceived:stateResponse.ok,settingsReceived:settingsResponse.ok,unauthenticatedBridgeDenied," |
| 495 | 删除: "storageMarkerMatched,localStoragePersisted:phase==='verify'&&storageMarkerMatched};", phase, marker); | |
| 498 | 新增: "storageMarkerMatched,localStoragePersisted:phase==='verify'&&storageMarkerMatched};" | |
| 499 | 新增: "}catch(error){return {success:false,stage,errorName:error.name};}", phase, marker); | |
| 496 | 500 | webkit_web_view_call_async_javascript_function(app.web, body, -1, NULL, NULL, NULL, NULL, smoke_evaluated, NULL); |
| 497 | 501 | g_free(body); g_free(phase); g_free(marker); |
| 498 | 502 | return G_SOURCE_REMOVE; |
| @@ -322,6 +322,9 @@ internal sealed class MainWindow : Form | ||
| 322 | 322 | BackColor = ColorTranslator.FromHtml(background); web.DefaultBackgroundColor = BackColor; |
| 323 | 323 | web.CoreWebView2.Profile.PreferredColorScheme = mode == "dark" ? CoreWebView2PreferredColorScheme.Dark : mode == "light" ? CoreWebView2PreferredColorScheme.Light : CoreWebView2PreferredColorScheme.Auto; |
| 324 | 324 | result = true; break; |
| 325 | 新增: case "accountDevice": | |
| 326 | 新增: if (request.Text("operation") != "status") throw new InvalidDataException("此平台暂不支持快捷登录"); | |
| 327 | 新增: result = new { supported = false }; break; | |
| 325 | 328 | case "refreshSession": |
| 326 | 329 | var (exit, data) = await Backend.Json(controllerNeedsUpdate ? ["desktop", "--json", "--existing"] : ["desktop", "--json"], lifetime.Token); |
| 327 | 330 | if (exit != 0) throw new IOException("工作台会话恢复失败"); |
| @@ -16,6 +16,8 @@ macOS 的“登录与解锁”提供记住登录与 Touch ID 两项开关。首 | ||
| 16 | 16 | |
| 17 | 17 | 每种快捷登录使用独立随机凭据包装同一个内部密钥。原生启动器通过受认证的本机接口交换凭据,网页只获得状态;后端不接受指纹成功的布尔值作为解锁依据。自动登录凭据保存在本机登录钥匙串,访问受应用代码签名控制;指纹凭据存入 Data Protection Keychain 并使用 `biometryCurrentSet`,必须通过系统指纹验证才能读取。指纹变化、取消、钥匙串不可用时保留密码入口。带指纹功能的构建需要匹配应用标识的 Developer ID 描述文件,构建可通过 `CAGE_PROVISIONING_PROFILE` 指定;缺少系统授权时不会改为不受保护的指纹凭据。 |
| 18 | 18 | |
| 19 | 新增:快捷登录开关同时依据账户授权记录与当前目录对应的钥匙串状态。凭据缺失或可检查的凭据标识不匹配时,开关显示为未开启,登录页停止自动尝试并提示使用密码后重新开启。目录迁移不会搜索或转移原目录的凭据。检查过程不读取解锁密钥、不弹出认证窗口、不撤销授权;钥匙串暂时不可访问时显示检查失败并允许重试。受指纹保护的记录可能需要认证才能检查属性,此时保留 Touch ID 入口,凭据标识仍在实际解锁时核验。开启、关闭、失败及账户目录或授权变化后重新检查状态。Windows 和 Linux 返回不支持快捷登录,公共界面保留密码入口。 | |
| 20 | 新增: | |
| 19 | 21 | 密码保险箱随本地账户解锁和锁定,提供网站密码保存、选择填充与再次验证后的查看和复制。数据归属、浏览器校验及恢复条件见[密码保险箱设计](password-vault.md)。 |
| 20 | 22 | |
| 21 | 23 | ## 主界面 |
| @@ -215,6 +217,8 @@ macOS、Windows、Linux 的 `clipboardReadContent` 原生操作在明确粘贴 | ||
| 215 | 217 | |
| 216 | 218 | Claude Desktop 的私有 D-Bus 会话运行 `org.freedesktop.portal.FileChooser` 服务;应用启动时要求版本 3 的文件选择接口。工作台读取待选请求,再调用本机选择器;选择结果经现有 SSH 通道传入会话专用 Unix socket,成功后向原调用者返回客机文件 URI,取消时返回取消响应。普通文件选择通过上传副本传递;文件夹请求打开 Cage 的统一项目选择器,直接选择已有项目,或通过“添加本机项目…”完成目录授权与动态共享。Claude 只消费已授权项目,不保存另一份共享列表,也不修改 Cage 当前项目或其他消费者的会话。项目打开、重新连接和目录交付与环境启停共用操作锁。共享完成后,控制服务检查所选目录已在项目列表中,再按主机平台映射为客机路径并返回文件 URI。取消选择返回取消响应,未授权或未挂载的目录不能交给应用。上传副本保留到 Desktop 图形会话重建,以支持应用延后读取,不扩大主机目录共享范围。 |
| 217 | 219 | |
| 220 | 新增:Claude Desktop 的 `SaveFile` 请求先取得客机私有下载位置。Chromium 下载在临时文件重命名后完成;直接导出在实际写入并关闭文件后完成。创建空占位文件不算下载成功。完成文件使用浏览器已有的原子复制规则发布到默认工作区的 Downloads,再进入同一个下载列表和三平台本机另存为窗口。取消另存为保留默认位置,文件不会自动打开。下载失败显示原因;已完整写入的源文件可重试保存,进程重启后未确认完整的下载需要重新发起。Desktop 私有下载记录保存在编码用户的持久目录,只公开最近 50 条结束记录;源文件保留,以兼容应用再次读取保存位置。工作台仅接受默认工作区 Downloads 下经过文件名校验的完成记录,不接受客机提供的任意主机路径,也不把浏览器控制凭据交给 Desktop。 | |
| 221 | 新增: | |
| 218 | 222 | 编辑器由独立系统服务监督,进程异常退出时自动重新启动。工作台的编辑器恢复操作只重启该服务并重新加载项目页面,保留 VM、浏览器和工作台终端。迁移旧版编辑器时,先核对用户、安装目录、Cage 私有配置和监听参数;无法确认身份的进程不自动停止。 |
| 219 | 223 | |
| 220 | 224 | ## 作业与后台监测 |
| @@ -26,6 +26,12 @@ | ||
| 26 | 26 | |
| 27 | 27 | 保留当前目录和原目录,检查原目录是否同时包含 `account.json`、`favorites.json` 及 `state/`。不要创建新账户、清空配置或仅复制账户文件;浏览器历史、网站登录状态及其他环境文件还依赖同一套虚拟磁盘。迁移前保存工作并停止两套环境与后台,完整备份后再迁移;账户文件中的快捷登录绑定与原路径关联,迁移后可能需要用原密码解锁并重新开启快捷登录。找不到原文件时,应从备份恢复并排查删除原因。 |
| 28 | 28 | |
| 29 | 新增:## 迁移后快捷登录需要重新开启 | |
| 30 | 新增: | |
| 31 | 新增:快捷登录凭据绑定账户所在目录。目录迁移后,若新路径没有对应的系统钥匙串记录,登录页会提示凭据缺失并保留密码入口;“设置 → 账户 → 登录与解锁”中的对应开关显示为未开启,可直接开启,无需先关闭。原目录的凭据和个人数据保持不变。 | |
| 32 | 新增: | |
| 33 | 新增:若显示“暂时无法检查系统钥匙串”,先用密码解锁,待系统钥匙串恢复可用后点击“重新检查快捷登录”。这类检查失败会保留授权记录,不会要求重建账户。 | |
| 34 | 新增: | |
| 29 | 35 | ## 启动前的 Git 检查未通过 |
| 30 | 36 | |
| 31 | 37 | 点击“启动 Cage 环境”后,Cage 会先检查本机的 Git。确认未安装 Git 时会继续,不要求为使用 Cage 安装开发工具;已安装的 Git 需要启用裸仓库保护。 |
| @@ -40,6 +40,17 @@ func ClaudeDesktopProvisionScript() string { | ||
| 40 | 40 | "sudo chmod 0755 /usr/local/bin/cage-claude-session /usr/local/bin/cage-claude-open /usr/local/bin/cage-claude-start\n" + guestOpenScript() + ` |
| 41 | 41 | printf 'cage-browser ALL=(cage) NOPASSWD: /usr/local/bin/cage-claude-open *\n' | sudo tee /etc/sudoers.d/cage-claude-desktop >/dev/null |
| 42 | 42 | sudo chmod 0440 /etc/sudoers.d/cage-claude-desktop |
| 43 | 新增:sudo python3 - <<'CAGE_DESKTOP_DOWNLOAD_CONFIG' | |
| 44 | 新增:import json, os | |
| 45 | 新增:from pathlib import Path | |
| 46 | 新增:source = Path('/etc/claude-cage/browser-control.json') | |
| 47 | 新增:if source.exists(): | |
| 48 | 新增: with source.open() as config: | |
| 49 | 新增: workspace = json.load(config)['workspace'] | |
| 50 | 新增: destination = Path('/etc/claude-cage/desktop-downloads.json') | |
| 51 | 新增: destination.write_text(json.dumps({'workspace': workspace})) | |
| 52 | 新增: os.chmod(destination, 0o644) | |
| 53 | 新增:CAGE_DESKTOP_DOWNLOAD_CONFIG | |
| 43 | 54 | sudo tee /etc/claude-cage/desktop-openbox.xml >/dev/null <<'CAGE_CLAUDE_WINDOWS' |
| 44 | 55 | <?xml version="1.0" encoding="UTF-8"?> |
| 45 | 56 | <openbox_config xmlns="http://openbox.org/3.4/rc"> |
| @@ -16,76 +16,82 @@ func TestDesktopCallbackFocusAfterHandoff(t *testing.T) { | ||
| 16 | 16 | if err != nil { |
| 17 | 17 | t.Skip("node unavailable") |
| 18 | 18 | } |
| 19 | 删除: for _, tc := range []struct { | |
| 20 | 删除: name, url, path, login string | |
| 21 | 删除: fail bool | |
| 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}, | |
| 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}, | |
| 28 | 删除: } { | |
| 29 | 删除: t.Run(tc.name, func(t *testing.T) { | |
| 30 | 删除: dir := t.TempDir() | |
| 31 | 删除: type request struct{ Path, Auth, URL, Login string } | |
| 32 | 删除: requests := make(chan request, 2) | |
| 33 | 删除: server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
| 34 | 删除: var body struct { | |
| 35 | 删除: URL string `json:"url"` | |
| 36 | 删除: Login string `json:"login"` | |
| 19 | 新增: for _, identity := range []string{"cage", "cage-browser"} { | |
| 20 | 新增: for _, tc := range []struct { | |
| 21 | 新增: name, url, path, login string | |
| 22 | 新增: fail bool | |
| 23 | 新增: }{ | |
| 24 | 新增: {"callback", "claude://login?code=private-test-value", "/desktop-focus", "", false}, | |
| 25 | 新增: {"failed-callback", "claude://login?code=private-test-value", "", "", true}, | |
| 26 | 新增: {"web-link", "https://example.com/login", "/new", "", false}, | |
| 27 | 新增: {"cli-login", "https://claude.ai/oauth/authorize?state=private-test-value", "/login-open", "1234567890abcdef", false}, | |
| 28 | 新增: {"finish-cli-login", "--finish-login", "/login-finish", "1234567890abcdef", false}, | |
| 29 | 新增: } { | |
| 30 | 新增: t.Run(identity+"/"+tc.name, func(t *testing.T) { | |
| 31 | 新增: dir := t.TempDir() | |
| 32 | 新增: type request struct{ Path, Auth, URL, Login string } | |
| 33 | 新增: requests := make(chan request, 2) | |
| 34 | 新增: server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
| 35 | 新增: var body struct { | |
| 36 | 新增: URL string `json:"url"` | |
| 37 | 新增: Login string `json:"login"` | |
| 38 | 新增: } | |
| 39 | 新增: _ = json.NewDecoder(r.Body).Decode(&body) | |
| 40 | 新增: requests <- request{r.URL.Path, r.Header.Get("Authorization"), body.URL, body.Login} | |
| 41 | 新增: w.Write([]byte(`{"ok":true}`)) | |
| 42 | 新增: })) | |
| 43 | 新增: defer server.Close() | |
| 44 | 新增: config := filepath.Join(dir, "control.json") | |
| 45 | 新增: if err := os.WriteFile(config, []byte(`{"token":"test-only"}`), 0600); err != nil { | |
| 46 | 新增: t.Fatal(err) | |
| 37 | 47 | } |
| 38 | 删除: _ = json.NewDecoder(r.Body).Decode(&body) | |
| 39 | 删除: requests <- request{r.URL.Path, r.Header.Get("Authorization"), body.URL, body.Login} | |
| 40 | 删除: w.Write([]byte(`{"ok":true}`)) | |
| 41 | 删除: })) | |
| 42 | 删除: defer server.Close() | |
| 43 | 删除: config := filepath.Join(dir, "control.json") | |
| 44 | 删除: if err := os.WriteFile(config, []byte(`{"token":"test-only"}`), 0600); err != nil { | |
| 45 | 删除: t.Fatal(err) | |
| 46 | 删除: } | |
| 47 | 删除: // Preserve the production shell flow; sudo only substitutes the two | |
| 48 | 删除: // guest identities and the app. Node performs the real HTTP request. | |
| 49 | 删除: sudo := "#!/bin/sh\nshift\nuser=$1\nshift\nif [ \"$user\" = cage ]; then exit \"$CALLBACK_EXIT\"; fi\nshift\nexec \"$TEST_NODE\" \"$@\"\n" | |
| 50 | 删除: if err := os.WriteFile(filepath.Join(dir, "sudo"), []byte(sudo), 0755); err != nil { | |
| 51 | 删除: t.Fatal(err) | |
| 52 | 删除: } | |
| 53 | 删除: script := strings.ReplaceAll(guestOpen, "/etc/claude-cage/browser-control.json", config) | |
| 54 | 删除: script = strings.ReplaceAll(script, "http://127.0.0.1:18500", server.URL) | |
| 55 | 删除: code := "0" | |
| 56 | 删除: if tc.fail { | |
| 57 | 删除: code = "1" | |
| 58 | 删除: } | |
| 59 | 删除: cmd := exec.Command("sh", "-c", script, "cage-open", tc.url) | |
| 60 | 删除: cmd.Env = append(os.Environ(), "PATH="+dir+":"+os.Getenv("PATH"), "TEST_NODE="+node, "CALLBACK_EXIT="+code, "CAGE_CLAUDE_LOGIN="+tc.login) | |
| 61 | 删除: out, err := cmd.CombinedOutput() | |
| 62 | 删除: if tc.fail { | |
| 63 | 删除: if err == nil { | |
| 64 | 删除: t.Fatal("failed handoff reported success") | |
| 48 | 新增: // Preserve the production shell flow; sudo only substitutes the two | |
| 49 | 新增: // guest identities and the app. Node performs the real HTTP request. | |
| 50 | 新增: sudo := "#!/bin/sh\nshift\nuser=$1\nshift\nif [ \"$user\" = cage ]; then exit \"$CALLBACK_EXIT\"; fi\nif [ \"$TEST_IDENTITY\" = cage-browser ]; then echo 'sudo denied' >&2; exit 1; fi\nshift\nexec \"$TEST_NODE\" \"$@\"\n" | |
| 51 | 新增: if err := os.WriteFile(filepath.Join(dir, "sudo"), []byte(sudo), 0755); err != nil { | |
| 52 | 新增: t.Fatal(err) | |
| 53 | 新增: } | |
| 54 | 新增: if err := os.WriteFile(filepath.Join(dir, "id"), []byte("#!/bin/sh\nprintf '%s\\n' \"$TEST_IDENTITY\"\n"), 0755); err != nil { | |
| 55 | 新增: t.Fatal(err) | |
| 56 | 新增: } | |
| 57 | 新增: script := strings.ReplaceAll(guestOpen, "/etc/claude-cage/browser-control.json", config) | |
| 58 | 新增: script = strings.ReplaceAll(script, "http://127.0.0.1:18500", server.URL) | |
| 59 | 新增: script = strings.ReplaceAll(script, "/usr/bin/node", "\"$TEST_NODE\"") | |
| 60 | 新增: code := "0" | |
| 61 | 新增: if tc.fail { | |
| 62 | 新增: code = "1" | |
| 63 | 新增: } | |
| 64 | 新增: cmd := exec.Command("sh", "-c", script, "cage-open", tc.url) | |
| 65 | 新增: cmd.Env = append(os.Environ(), "PATH="+dir+":"+os.Getenv("PATH"), "TEST_NODE="+node, "TEST_IDENTITY="+identity, "CALLBACK_EXIT="+code, "CAGE_CLAUDE_LOGIN="+tc.login) | |
| 66 | 新增: out, err := cmd.CombinedOutput() | |
| 67 | 新增: if tc.fail { | |
| 68 | 新增: if err == nil { | |
| 69 | 新增: t.Fatal("failed handoff reported success") | |
| 70 | 新增: } | |
| 71 | 新增: select { | |
| 72 | 新增: case r := <-requests: | |
| 73 | 新增: t.Fatalf("failed handoff emitted focus: %+v", r) | |
| 74 | 新增: default: | |
| 75 | 新增: } | |
| 76 | 新增: return | |
| 77 | 新增: } | |
| 78 | 新增: if err != nil { | |
| 79 | 新增: t.Fatalf("%v: %s", err, out) | |
| 65 | 80 | } |
| 66 | 81 | select { |
| 67 | 82 | case r := <-requests: |
| 68 | 删除: t.Fatalf("failed handoff emitted focus: %+v", r) | |
| 83 | 新增: wantURL := "" | |
| 84 | 新增: if tc.path == "/new" || tc.path == "/login-open" { | |
| 85 | 新增: wantURL = tc.url | |
| 86 | 新增: } | |
| 87 | 新增: if r.Path != tc.path || r.Auth != "Bearer test-only" || r.URL != wantURL || r.Login != tc.login { | |
| 88 | 新增: t.Fatalf("unexpected request: %+v", r) | |
| 89 | 新增: } | |
| 69 | 90 | default: |
| 91 | 新增: t.Fatal("handoff notification missing") | |
| 70 | 92 | } |
| 71 | 删除: return | |
| 72 | 删除: } | |
| 73 | 删除: if err != nil { | |
| 74 | 删除: t.Fatalf("%v: %s", err, out) | |
| 75 | 删除: } | |
| 76 | 删除: select { | |
| 77 | 删除: case r := <-requests: | |
| 78 | 删除: wantURL := "" | |
| 79 | 删除: if tc.path == "/new" || tc.path == "/login-open" { | |
| 80 | 删除: wantURL = tc.url | |
| 81 | 删除: } | |
| 82 | 删除: if r.Path != tc.path || r.Auth != "Bearer test-only" || r.URL != wantURL || r.Login != tc.login { | |
| 83 | 删除: t.Fatalf("unexpected request: %+v", r) | |
| 84 | 删除: } | |
| 85 | 删除: default: | |
| 86 | 删除: t.Fatal("handoff notification missing") | |
| 87 | 删除: } | |
| 88 | 删除: }) | |
| 93 | 新增: }) | |
| 94 | 新增: } | |
| 89 | 95 | } |
| 90 | 96 | } |
| 91 | 97 | |
| @@ -0,0 +1,174 @@ | ||
| 1 | 新增:"""SaveFile destinations and completed Desktop exports (runs as cage, never root).""" | |
| 2 | 新增:import ctypes as C | |
| 3 | 新增:from datetime import datetime, timezone | |
| 4 | 新增:from importlib.machinery import SourceFileLoader | |
| 5 | 新增:import json | |
| 6 | 新增:import os | |
| 7 | 新增:from pathlib import Path | |
| 8 | 新增:import re | |
| 9 | 新增:import select | |
| 10 | 新增:import stat | |
| 11 | 新增:import struct | |
| 12 | 新增:import threading | |
| 13 | 新增:import uuid | |
| 14 | 新增: | |
| 15 | 新增: | |
| 16 | 新增:def valid_name(name): | |
| 17 | 新增: return (isinstance(name, str) and bool(name) and len(name.encode()) <= 255 | |
| 18 | 新增: and name not in ('.', '..') and not re.search(r'[/\\\x00-\x1f]', name)) | |
| 19 | 新增: | |
| 20 | 新增: | |
| 21 | 新增:class Downloads: | |
| 22 | 新增: def __init__(self, directory, workspace, copier): | |
| 23 | 新增: self.directory, self.workspace, self.copier = Path(directory), workspace, copier | |
| 24 | 新增: self.directory.mkdir(parents=True, exist_ok=True, mode=0o700) | |
| 25 | 新增: self.manifest = self.directory / 'state.json' | |
| 26 | 新增: self.lock = threading.RLock() | |
| 27 | 新增: self.copy_lock = threading.Lock() | |
| 28 | 新增: self.records = {} | |
| 29 | 新增: try: | |
| 30 | 新增: if self.manifest.stat().st_size > 1024 * 1024: | |
| 31 | 新增: raise ValueError('下载记录过大') | |
| 32 | 新增: records = json.loads(self.manifest.read_text()) | |
| 33 | 新增: for item in records[-100:]: | |
| 34 | 新增: if (not re.fullmatch(r'[a-f0-9-]{36}', item['id']) or not valid_name(item['name']) | |
| 35 | 新增: or not valid_name(item['sourceName'])): | |
| 36 | 新增: continue | |
| 37 | 新增: if item['state'] in ('downloading', 'saving'): | |
| 38 | 新增: item.update(state='failed', error='下载或保存被中断;已完整写入的文件可重试保存。') | |
| 39 | 新增: item['retryable'] = bool(item.get('complete') and self.source(item).is_file() | |
| 40 | 新增: and item['state'] == 'failed') | |
| 41 | 新增: self.records[item['id']] = item | |
| 42 | 新增: except (OSError, ValueError, TypeError, KeyError): | |
| 43 | 新增: self.records = {} | |
| 44 | 新增: | |
| 45 | 新增: def source(self, item): | |
| 46 | 新增: return self.directory / item['id'] / item['sourceName'] | |
| 47 | 新增: | |
| 48 | 新增: def persist(self): | |
| 49 | 新增: finished = [key for key, item in self.records.items() if item['state'] in ('saved', 'failed', 'canceled')] | |
| 50 | 新增: for key in finished[:-50]: | |
| 51 | 新增: del self.records[key] | |
| 52 | 新增: temporary = self.manifest.with_suffix('.tmp') | |
| 53 | 新增: with temporary.open('w') as output: | |
| 54 | 新增: os.chmod(temporary, 0o600) | |
| 55 | 新增: json.dump(list(self.records.values()), output, ensure_ascii=False) | |
| 56 | 新增: output.flush() | |
| 57 | 新增: os.fsync(output.fileno()) | |
| 58 | 新增: temporary.replace(self.manifest) | |
| 59 | 新增: | |
| 60 | 新增: def snapshot(self): | |
| 61 | 新增: with self.lock: | |
| 62 | 新增: return [{key: value for key, value in item.items() if key not in ('sourceName', 'complete')} | |
| 63 | 新增: for item in reversed(list(self.records.values()))] | |
| 64 | 新增: | |
| 65 | 新增: def begin(self, name): | |
| 66 | 新增: if not valid_name(name): | |
| 67 | 新增: raise ValueError('下载文件名无效') | |
| 68 | 新增: with self.lock: | |
| 69 | 新增: if sum(item['state'] in ('downloading', 'saving') for item in self.records.values()) >= 50: | |
| 70 | 新增: raise ValueError('同时下载的文件过多,请等待下载完成') | |
| 71 | 新增: key = str(uuid.uuid4()) | |
| 72 | 新增: folder = self.directory / key | |
| 73 | 新增: folder.mkdir(mode=0o700) | |
| 74 | 新增: # Watch before handing the URI to Chromium, including very small exports. | |
| 75 | 新增: libc = C.CDLL(None, use_errno=True) | |
| 76 | 新增: fd = libc.inotify_init1(os.O_CLOEXEC | os.O_NONBLOCK) | |
| 77 | 新增: if fd < 0: | |
| 78 | 新增: raise OSError(C.get_errno(), '无法监听下载完成') | |
| 79 | 新增: watch = libc.inotify_add_watch(fd, os.fsencode(folder), 0x2 | 0x8 | 0x80 | 0x200) | |
| 80 | 新增: if watch < 0: | |
| 81 | 新增: os.close(fd) | |
| 82 | 新增: raise OSError(C.get_errno(), '无法监听下载目录') | |
| 83 | 新增: item = dict(id=key, name=name, sourceName=name, state='downloading', target='desktop', | |
| 84 | 新增: startedAt=datetime.now(timezone.utc).isoformat(), complete=False, retryable=False) | |
| 85 | 新增: self.records[key] = item | |
| 86 | 新增: try: | |
| 87 | 新增: self.persist() | |
| 88 | 新增: except Exception: | |
| 89 | 新增: del self.records[key] | |
| 90 | 新增: os.close(fd) | |
| 91 | 新增: raise | |
| 92 | 新增: threading.Thread(target=self.watch, args=(item, fd), daemon=True).start() | |
| 93 | 新增: return str(self.source(item)) | |
| 94 | 新增: | |
| 95 | 新增: def watch(self, item, fd): | |
| 96 | 新增: wrote_target = False | |
| 97 | 新增: try: | |
| 98 | 新增: while True: | |
| 99 | 新增: if not select.select([fd], [], [], 1800)[0]: | |
| 100 | 新增: raise ValueError('长时间未收到完整文件,请从原应用重新下载') | |
| 101 | 新增: data = os.read(fd, 65536) | |
| 102 | 新增: offset = 0 | |
| 103 | 新增: while offset + 16 <= len(data): | |
| 104 | 新增: _, mask, _, length = struct.unpack_from('iIII', data, offset) | |
| 105 | 新增: name = os.fsdecode(data[offset + 16:offset + 16 + length].split(b'\0')[0]) | |
| 106 | 新增: offset += 16 + length | |
| 107 | 新增: if mask & 0x4000: # IN_Q_OVERFLOW: never infer completion from size stability. | |
| 108 | 新增: raise ValueError('下载完成通知丢失,请重新下载') | |
| 109 | 新增: if name == item['sourceName'] + '.crdownload' and mask & 0x200: | |
| 110 | 新增: with self.lock: | |
| 111 | 新增: item.update(state='canceled', retryable=False) | |
| 112 | 新增: self.persist() | |
| 113 | 新增: return | |
| 114 | 新增: if name == item['sourceName'] and mask & 0x2: | |
| 115 | 新增: wrote_target = True | |
| 116 | 新增: # Chromium first reserves the final name with an empty file, | |
| 117 | 新增: # then writes .crdownload and renames it. Its initial close | |
| 118 | 新增: # is not completion. A direct exporter must actually write. | |
| 119 | 新增: if name == item['sourceName'] and (mask & 0x80 or (mask & 0x8 and wrote_target)): | |
| 120 | 新增: with self.lock: | |
| 121 | 新增: item.update(complete=True, state='saving') | |
| 122 | 新增: self.persist() | |
| 123 | 新增: self.save(item) | |
| 124 | 新增: return | |
| 125 | 新增: except Exception as error: | |
| 126 | 新增: self.failed(item, error) | |
| 127 | 新增: finally: | |
| 128 | 新增: os.close(fd) | |
| 129 | 新增: | |
| 130 | 新增: def failed(self, item, error): | |
| 131 | 新增: with self.lock: | |
| 132 | 新增: item.update(state='failed', error=str(error)[:300], | |
| 133 | 新增: retryable=bool(item['complete'] and self.source(item).is_file())) | |
| 134 | 新增: try: | |
| 135 | 新增: self.persist() | |
| 136 | 新增: except OSError: | |
| 137 | 新增: item['error'] = '无法保存下载记录,请检查客机可用空间' | |
| 138 | 新增: | |
| 139 | 新增: def save(self, item): | |
| 140 | 新增: try: | |
| 141 | 新增: with self.copy_lock: | |
| 142 | 新增: source = os.open(self.source(item), os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) | |
| 143 | 新增: try: | |
| 144 | 新增: info = os.fstat(source) | |
| 145 | 新增: if not stat.S_ISREG(info.st_mode): | |
| 146 | 新增: raise ValueError('下载源文件无效') | |
| 147 | 新增: result = self.copier(source, info.st_size, self.workspace, item['sourceName']) | |
| 148 | 新增: finally: | |
| 149 | 新增: os.close(source) | |
| 150 | 新增: with self.lock: | |
| 151 | 新增: item.update(state='saved', path=result['path'], name=result['name'], | |
| 152 | 新增: receivedBytes=result['bytes'], totalBytes=result['bytes'], retryable=False) | |
| 153 | 新增: item.pop('error', None) | |
| 154 | 新增: self.persist() | |
| 155 | 新增: # Retain the private source: applications may reuse a SaveFile URI. | |
| 156 | 新增: except Exception as error: | |
| 157 | 新增: self.failed(item, error) | |
| 158 | 新增: | |
| 159 | 新增: def retry(self, key): | |
| 160 | 新增: with self.lock: | |
| 161 | 新增: item = self.records.get(key) | |
| 162 | 新增: if not item or item['state'] != 'failed' or not item['retryable']: | |
| 163 | 新增: raise ValueError('完整下载源文件不可用,请重新下载') | |
| 164 | 新增: item.update(state='saving', retryable=False) | |
| 165 | 新增: self.persist() | |
| 166 | 新增: threading.Thread(target=self.save, args=(item,), daemon=True).start() | |
| 167 | 新增: return {'ok': True} | |
| 168 | 新增: | |
| 169 | 新增: | |
| 170 | 新增:def create_downloads(): | |
| 171 | 新增: helper = SourceFileLoader('cage_download_copy', '/usr/local/bin/cage-save-download').load_module() | |
| 172 | 新增: with open('/etc/claude-cage/desktop-downloads.json') as config: | |
| 173 | 新增: workspace = json.load(config)['workspace'] | |
| 174 | 新增: return Downloads(Path.home() / '.local/share/cage/desktop-downloads', workspace, helper.copy_to_workspace) | |
| @@ -0,0 +1,202 @@ | ||
| 1 | 新增:import importlib.util | |
| 2 | 新增:import json | |
| 3 | 新增:import os | |
| 4 | 新增:from pathlib import Path | |
| 5 | 新增:import sys | |
| 6 | 新增:import tempfile | |
| 7 | 新增:import threading | |
| 8 | 新增:import unittest | |
| 9 | 新增: | |
| 10 | 新增: | |
| 11 | 新增:def load(name, filename): | |
| 12 | 新增: spec = importlib.util.spec_from_file_location(name, Path(__file__).with_name(filename)) | |
| 13 | 新增: module = importlib.util.module_from_spec(spec) | |
| 14 | 新增: spec.loader.exec_module(module) | |
| 15 | 新增: return module | |
| 16 | 新增: | |
| 17 | 新增: | |
| 18 | 新增:downloads = load('downloads', 'desktop-downloads.py') | |
| 19 | 新增:copy = load('copy_download', 'save-download.py') | |
| 20 | 新增: | |
| 21 | 新增: | |
| 22 | 新增:@unittest.skipUnless(sys.platform == 'linux', 'inotify is supplied by the Linux guest') | |
| 23 | 新增:class DesktopDownloadsTests(unittest.TestCase): | |
| 24 | 新增: def setUp(self): | |
| 25 | 新增: self.temp = tempfile.TemporaryDirectory() | |
| 26 | 新增: self.addCleanup(self.temp.cleanup) | |
| 27 | 新增: self.root = Path(self.temp.name) | |
| 28 | 新增: self.workspace = self.root / 'shared' | |
| 29 | 新增: self.workspace.mkdir() | |
| 30 | 新增: self.finished = threading.Event() | |
| 31 | 新增: self.manager = downloads.Downloads(self.root / 'private', str(self.workspace), copy.copy_to_workspace) | |
| 32 | 新增: original = self.manager.persist | |
| 33 | 新增: def persist(): | |
| 34 | 新增: original() | |
| 35 | 新增: if self.manager.records and list(self.manager.records.values())[-1]['state'] in ('saved', 'failed', 'canceled'): | |
| 36 | 新增: self.finished.set() | |
| 37 | 新增: self.manager.persist = persist | |
| 38 | 新增: | |
| 39 | 新增: def wait(self): | |
| 40 | 新增: self.assertTrue(self.finished.wait(5), self.manager.snapshot()) | |
| 41 | 新增: return self.manager.snapshot()[0] | |
| 42 | 新增: | |
| 43 | 新增: def test_chromium_partial_is_not_published_until_final_rename(self): | |
| 44 | 新增: target = Path(self.manager.begin('视频 #+%.mp4')) | |
| 45 | 新增: target.write_bytes(b'') # Chromium reserves the destination first. | |
| 46 | 新增: temporary = target.with_name(target.name + '.crdownload') | |
| 47 | 新增: temporary.write_bytes(b'partial') | |
| 48 | 新增: self.assertFalse(self.finished.wait(.1)) | |
| 49 | 新增: self.assertEqual(self.manager.snapshot()[0]['state'], 'downloading') | |
| 50 | 新增: self.assertFalse((self.workspace / 'Downloads').exists()) | |
| 51 | 新增: with temporary.open('ab') as output: | |
| 52 | 新增: output.write(b' complete') | |
| 53 | 新增: temporary.rename(target) | |
| 54 | 新增: item = self.wait() | |
| 55 | 新增: self.assertEqual(item['state'], 'saved') | |
| 56 | 新增: self.assertEqual(Path(item['path']).read_bytes(), b'partial complete') | |
| 57 | 新增: | |
| 58 | 新增: def test_direct_export_waits_for_close_and_preserves_existing_file(self): | |
| 59 | 新增: (self.workspace / 'Downloads').mkdir() | |
| 60 | 新增: (self.workspace / 'Downloads' / 'video.mp4').write_bytes(b'original') | |
| 61 | 新增: target = Path(self.manager.begin('video.mp4')) | |
| 62 | 新增: with target.open('wb') as output: | |
| 63 | 新增: output.write(b'export') | |
| 64 | 新增: output.flush() | |
| 65 | 新增: self.assertFalse(self.finished.wait(.1)) | |
| 66 | 新增: item = self.wait() | |
| 67 | 新增: self.assertEqual(item['name'], 'video (1).mp4') | |
| 68 | 新增: self.assertEqual(Path(item['path']).read_bytes(), b'export') | |
| 69 | 新增: self.assertEqual((self.workspace / 'Downloads' / 'video.mp4').read_bytes(), b'original') | |
| 70 | 新增: | |
| 71 | 新增: def test_cancel_discards_partial_and_empty_download_completes_by_rename(self): | |
| 72 | 新增: target = Path(self.manager.begin('canceled.mp4')) | |
| 73 | 新增: temporary = target.with_name(target.name + '.crdownload') | |
| 74 | 新增: temporary.write_bytes(b'partial') | |
| 75 | 新增: temporary.unlink() | |
| 76 | 新增: self.assertEqual(self.wait()['state'], 'canceled') | |
| 77 | 新增: self.assertFalse((self.workspace / 'Downloads').exists()) | |
| 78 | 新增: self.finished.clear() | |
| 79 | 新增: target = Path(self.manager.begin('empty.txt')) | |
| 80 | 新增: temporary = target.with_name(target.name + '.crdownload') | |
| 81 | 新增: temporary.write_bytes(b'') | |
| 82 | 新增: temporary.rename(target) | |
| 83 | 新增: item = self.wait() | |
| 84 | 新增: self.assertEqual(item['state'], 'saved') | |
| 85 | 新增: self.assertEqual(Path(item['path']).read_bytes(), b'') | |
| 86 | 新增: | |
| 87 | 新增: def test_failed_copy_can_retry_after_restart_but_incomplete_cannot(self): | |
| 88 | 新增: def fail(*args): | |
| 89 | 新增: raise OSError('test disk full') | |
| 90 | 新增: self.manager.copier = fail | |
| 91 | 新增: target = Path(self.manager.begin('retry.mp4')) | |
| 92 | 新增: target.write_bytes(bytes(range(256)) * 1024) | |
| 93 | 新增: item = self.wait() | |
| 94 | 新增: self.assertEqual(item['state'], 'failed') | |
| 95 | 新增: self.assertTrue(item['retryable']) | |
| 96 | 新增: restored = downloads.Downloads(self.manager.directory, str(self.workspace), copy.copy_to_workspace) | |
| 97 | 新增: restored.save(restored.records[item['id']]) | |
| 98 | 新增: self.assertEqual(restored.snapshot()[0]['state'], 'saved') | |
| 99 | 新增: self.assertEqual(Path(restored.snapshot()[0]['path']).read_bytes(), target.read_bytes()) | |
| 100 | 新增: # A crash while Chromium is still writing must never promote partial data. | |
| 101 | 新增: records = json.loads(restored.manifest.read_text()) | |
| 102 | 新增: records[0].update(state='downloading', complete=False) | |
| 103 | 新增: restored.manifest.write_text(json.dumps(records)) | |
| 104 | 新增: interrupted = downloads.Downloads(self.manager.directory, str(self.workspace), copy.copy_to_workspace) | |
| 105 | 新增: self.assertFalse(interrupted.snapshot()[0]['retryable']) | |
| 106 | 新增: with self.assertRaises(ValueError): interrupted.retry(item['id']) | |
| 107 | 新增: | |
| 108 | 新增: def test_invalid_names_and_symlinks_never_copy_arbitrary_files(self): | |
| 109 | 新增: for name in ['', '..', '../secret', 'a/b', 'a\\b', 'a\x00b', 'a\nb']: | |
| 110 | 新增: with self.assertRaises(ValueError): self.manager.begin(name) | |
| 111 | 新增: secret = self.root / 'secret' | |
| 112 | 新增: secret.write_bytes(b'private') | |
| 113 | 新增: target = Path(self.manager.begin('link.mp4')) | |
| 114 | 新增: temporary = target.with_name('link.tmp') | |
| 115 | 新增: temporary.symlink_to(secret) | |
| 116 | 新增: temporary.rename(target) | |
| 117 | 新增: self.assertEqual(self.wait()['state'], 'failed') | |
| 118 | 新增: self.assertFalse((self.workspace / 'Downloads').exists()) | |
| 119 | 新增: | |
| 120 | 新增: @unittest.skipUnless(os.environ.get('DBUS_SESSION_BUS_ADDRESS'), 'run under dbus-run-session') | |
| 121 | 新增: def test_real_portal_savefile_response_and_cancel_openfile(self): | |
| 122 | 新增: import gi | |
| 123 | 新增: gi.require_version('Gio', '2.0') | |
| 124 | 新增: from gi.repository import Gio, GLib | |
| 125 | 新增: files = load('desktop_files', 'desktop-files.py') | |
| 126 | 新增: broker = files.Broker(self.root / 'uploads', downloads=self.manager) | |
| 127 | 新增: portal = files.Portal(broker) | |
| 128 | 新增: broker.deliver = portal.deliver | |
| 129 | 新增: threading.Thread(target=portal.run, daemon=True).start() | |
| 130 | 新增: client = Gio.DBusConnection.new_for_address_sync(os.environ['DBUS_SESSION_BUS_ADDRESS'], | |
| 131 | 新增: Gio.DBusConnectionFlags.AUTHENTICATION_CLIENT | Gio.DBusConnectionFlags.MESSAGE_BUS_CONNECTION, None, None) | |
| 132 | 新增: responses, received = [], threading.Event() | |
| 133 | 新增: def response(_connection, _sender, _path, _interface, _signal, parameters): | |
| 134 | 新增: responses.append(parameters.unpack()) | |
| 135 | 新增: received.set() | |
| 136 | 新增: client.signal_subscribe(None, 'org.freedesktop.portal.Request', 'Response', None, None, | |
| 137 | 新增: Gio.DBusSignalFlags.NONE, response) | |
| 138 | 新增: result = client.call_sync('org.freedesktop.portal.Desktop', files.ROOT, files.PORTAL, 'SaveFile', | |
| 139 | 新增: GLib.Variant('(ssa{sv})', ('', '保存视频', {'current_name': GLib.Variant('s', '真实视频.mp4'), | |
| 140 | 新增: 'handle_token': GLib.Variant('s', 'save_probe')})), | |
| 141 | 新增: GLib.VariantType.new('(o)'), Gio.DBusCallFlags.NONE, 5000, None) | |
| 142 | 新增: self.assertTrue(result.unpack()[0].endswith('/save_probe')) | |
| 143 | 新增: self.assertTrue(received.wait(5)) | |
| 144 | 新增: self.assertEqual(responses[0][0], 0) | |
| 145 | 新增: from urllib.parse import unquote, urlsplit | |
| 146 | 新增: target = Path(unquote(urlsplit(responses[0][1]['uris'][0]).path)) | |
| 147 | 新增: target.write_bytes(b'real dbus export') | |
| 148 | 新增: self.assertEqual(Path(self.wait()['path']).read_bytes(), b'real dbus export') | |
| 149 | 新增: received.clear() | |
| 150 | 新增: client.call_sync('org.freedesktop.portal.Desktop', files.ROOT, files.PORTAL, 'OpenFile', | |
| 151 | 新增: GLib.Variant('(ssa{sv})', ('', '打开文件', {'handle_token': GLib.Variant('s', 'open_probe')})), | |
| 152 | 新增: GLib.VariantType.new('(o)'), Gio.DBusCallFlags.NONE, 5000, None) | |
| 153 | 新增: request = broker.snapshot()['uploads'][0] | |
| 154 | 新增: broker.cancel(request['id']) | |
| 155 | 新增: self.assertTrue(received.wait(5)) | |
| 156 | 新增: self.assertEqual(responses[-1][0], 1) | |
| 157 | 新增: | |
| 158 | 新增: if os.environ.get('CAGE_TEST_CHROMIUM'): | |
| 159 | 新增: # Real Chromium uses the same portal backend as Electron. Do not set | |
| 160 | 新增: # CDP download behavior: it would bypass the broken SaveFile entry. | |
| 161 | 新增: from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer | |
| 162 | 新增: import subprocess | |
| 163 | 新增: payload = bytes(range(256)) * 8192 | |
| 164 | 新增: class DownloadHandler(BaseHTTPRequestHandler): | |
| 165 | 新增: def log_message(self, *_): pass | |
| 166 | 新增: def do_GET(self): | |
| 167 | 新增: self.send_response(200) | |
| 168 | 新增: self.send_header('Content-Type', 'video/mp4') | |
| 169 | 新增: self.send_header('Content-Disposition', 'attachment; filename="chromium-video.mp4"') | |
| 170 | 新增: self.send_header('Content-Length', str(len(payload))) | |
| 171 | 新增: self.end_headers() | |
| 172 | 新增: self.wfile.write(payload) | |
| 173 | 新增: server = ThreadingHTTPServer(('127.0.0.1', 0), DownloadHandler) | |
| 174 | 新增: threading.Thread(target=server.serve_forever, daemon=True).start() | |
| 175 | 新增: profile = self.root / 'chromium' | |
| 176 | 新增: (profile / 'Default').mkdir(parents=True) | |
| 177 | 新增: (profile / 'Default/Preferences').write_text(json.dumps({'download': {'prompt_for_download': True}})) | |
| 178 | 新增: self.finished.clear() | |
| 179 | 新增: log = (self.root / 'chromium.log').open('w+') | |
| 180 | 新增: process = subprocess.Popen(['/usr/bin/chromium', f'--user-data-dir={profile}', '--no-first-run', | |
| 181 | 新增: '--no-default-browser-check', '--disable-background-networking', '--disable-gpu', '--password-store=basic', | |
| 182 | 新增: '--xdg-portal-required-version=3', f'http://127.0.0.1:{server.server_port}/video'], | |
| 183 | 新增: env={**os.environ, 'GTK_USE_PORTAL': '1'}, stdout=log, stderr=log) | |
| 184 | 新增: try: | |
| 185 | 新增: if not self.finished.wait(20): | |
| 186 | 新增: log.seek(0) | |
| 187 | 新增: self.fail('Chromium SaveFile did not complete: ' + log.read()[-3000:]) | |
| 188 | 新增: item = self.manager.snapshot()[0] | |
| 189 | 新增: self.assertEqual(item['name'], 'chromium-video.mp4') | |
| 190 | 新增: self.assertEqual(item['state'], 'saved', item) | |
| 191 | 新增: self.assertEqual(Path(item['path']).read_bytes(), payload) | |
| 192 | 新增: finally: | |
| 193 | 新增: process.terminate() | |
| 194 | 新增: try: process.wait(timeout=5) | |
| 195 | 新增: except subprocess.TimeoutExpired: process.kill(); process.wait() | |
| 196 | 新增: log.close() | |
| 197 | 新增: server.shutdown() | |
| 198 | 新增: server.server_close() | |
| 199 | 新增: | |
| 200 | 新增: | |
| 201 | 新增:if __name__ == '__main__': | |
| 202 | 新增: unittest.main() | |
| @@ -22,15 +22,16 @@ ROOT = '/org/freedesktop/portal/desktop' | ||
| 22 | 22 | |
| 23 | 23 | |
| 24 | 24 | class Broker: |
| 25 | 删除: def __init__(self, directory, deliver=lambda request, paths: None): | |
| 25 | 新增: def __init__(self, directory, deliver=lambda request, paths: None, downloads=None): | |
| 26 | 26 | self.directory = Path(directory) |
| 27 | 27 | self.directory.mkdir(parents=True, exist_ok=True, mode=0o700) |
| 28 | 28 | self.deliver = deliver |
| 29 | 新增: self.downloads = downloads | |
| 29 | 30 | self.requests = {} |
| 30 | 31 | self.lock = threading.RLock() |
| 31 | 32 | |
| 32 | 33 | def start(self, kind='paste', multiple=True, **metadata): |
| 33 | 删除: if kind not in ('paste', 'drop', 'chooser'): | |
| 34 | 新增: if kind not in ('paste', 'drop', 'chooser', 'save'): | |
| 34 | 35 | raise ValueError('文件传递方式无效') |
| 35 | 36 | with self.lock: |
| 36 | 37 | if len(self.requests) >= 32: |
| @@ -45,7 +46,8 @@ class Broker: | ||
| 45 | 46 | return {'uploads': [dict(id=r['id'], multiple=r['multiple'], |
| 46 | 47 | title=r.get('title', ''), target='desktop', |
| 47 | 48 | directory=r.get('directory', False)) |
| 48 | 删除: for r in self.requests.values() if r['kind'] == 'chooser']} | |
| 49 | 新增: for r in self.requests.values() if r['kind'] == 'chooser'], | |
| 50 | 新增: 'downloads': self.downloads.snapshot() if self.downloads else []} | |
| 49 | 51 | |
| 50 | 52 | def get(self, key): |
| 51 | 53 | if key not in self.requests: |
| @@ -112,7 +114,7 @@ class Broker: | ||
| 112 | 114 | def cancel(self, key, respond=True): |
| 113 | 115 | with self.lock: |
| 114 | 116 | request = self.requests.pop(key, None) |
| 115 | 删除: if request and respond and request['kind'] == 'chooser': | |
| 117 | 新增: if request and respond and request['kind'] in ('chooser', 'save'): | |
| 116 | 118 | self.deliver(request, None) |
| 117 | 119 | shutil.rmtree(self.directory / key, ignore_errors=True) |
| 118 | 120 | return {'ok': True} |
| @@ -198,6 +200,8 @@ class Handler(BaseHTTPRequestHandler): | ||
| 198 | 200 | result = broker.cancel(key) |
| 199 | 201 | elif route.path == '/directory': |
| 200 | 202 | result = broker.choose_directory(value.get('id', ''), value.get('path', '')) |
| 203 | 新增: elif route.path == '/download-retry' and broker.downloads: | |
| 204 | 新增: result = broker.downloads.retry(value.get('id', '')) | |
| 201 | 205 | else: |
| 202 | 206 | raise ValueError('文件操作无效') |
| 203 | 207 | else: |
| @@ -233,6 +237,8 @@ class Portal: | ||
| 233 | 237 | <property name="version" type="u" access="read"/> |
| 234 | 238 | <method name="OpenFile"><arg type="s" direction="in"/><arg type="s" direction="in"/> |
| 235 | 239 | <arg type="a{sv}" direction="in"/><arg type="o" direction="out"/></method> |
| 240 | 新增: <method name="SaveFile"><arg type="s" direction="in"/><arg type="s" direction="in"/> | |
| 241 | 新增: <arg type="a{sv}" direction="in"/><arg type="o" direction="out"/></method> | |
| 236 | 242 | </interface><interface name="org.freedesktop.portal.Request"> |
| 237 | 243 | <method name="Close"/><signal name="Response"><arg type="u"/><arg type="a{sv}"/></signal> |
| 238 | 244 | </interface></node>''' |
| @@ -333,14 +339,28 @@ class Portal: | ||
| 333 | 339 | if not object_id: |
| 334 | 340 | raise ValueError('文件窗口无法打开') |
| 335 | 341 | self.objects[handle] = object_id |
| 342 | 新增: key = None | |
| 336 | 343 | try: |
| 337 | 删除: self.broker.start('chooser', self.option(options, 'multiple', False) and not directory, | |
| 344 | 新增: saving = method == b'SaveFile' | |
| 345 | 新增: key = self.broker.start('save' if saving else 'chooser', self.option(options, 'multiple', False) and not directory, | |
| 338 | 346 | directory=directory, |
| 339 | 删除: handle=handle, sender=sender.decode(), title=self.string(title, None).decode()) | |
| 347 | 新增: handle=handle, sender=sender.decode(), title=self.string(title, None).decode())['id'] | |
| 348 | 新增: if saving: | |
| 349 | 新增: if not self.broker.downloads: | |
| 350 | 新增: raise ValueError('下载服务不可用') | |
| 351 | 新增: destination = self.broker.downloads.begin(self.option(options, 'current_name', 'download')) | |
| 340 | 352 | except Exception: |
| 341 | 353 | self.unregister(self.connection, self.objects.pop(handle)) |
| 354 | 新增: if key: | |
| 355 | 新增: self.broker.cancel(key, respond=False) | |
| 342 | 356 | raise |
| 343 | 357 | self.reply(invocation, self.tuple(self.new_path(handle.encode()))) |
| 358 | 新增: if saving: | |
| 359 | 新增: # The user already requested a download. Stage bytes privately; | |
| 360 | 新增: # the host save dialog is offered only after the writer finishes. | |
| 361 | 新增: request = self.broker.get(key) | |
| 362 | 新增: self.deliver(request, [destination]) | |
| 363 | 新增: del self.broker.requests[key] | |
| 344 | 364 | finally: |
| 345 | 365 | self.unref(title) |
| 346 | 366 | self.unref(options) |
| @@ -353,7 +373,7 @@ class Portal: | ||
| 353 | 373 | self.unregister(self.connection, object_id) |
| 354 | 374 | |
| 355 | 375 | def deliver(self, request, paths): |
| 356 | 删除: if request['kind'] != 'chooser': | |
| 376 | 新增: if request['kind'] not in ('chooser', 'save'): | |
| 357 | 377 | paste_files(paths) |
| 358 | 378 | return |
| 359 | 379 | entries = [] |
| @@ -455,7 +475,9 @@ def main(): | ||
| 455 | 475 | runtime = Path(os.environ['XDG_RUNTIME_DIR']) |
| 456 | 476 | directory = runtime / 'uploads' |
| 457 | 477 | shutil.rmtree(directory, ignore_errors=True) |
| 458 | 删除: broker = Broker(directory) | |
| 478 | 新增: from importlib.machinery import SourceFileLoader | |
| 479 | 新增: downloads = SourceFileLoader('cage_desktop_downloads', '/usr/local/lib/cage-desktop-downloads.py').load_module() | |
| 480 | 新增: broker = Broker(directory, downloads=downloads.create_downloads()) | |
| 459 | 481 | portal = Portal(broker) |
| 460 | 482 | broker.deliver = portal.deliver |
| 461 | 483 | socket = runtime / 'files.sock' |
| @@ -21,7 +21,16 @@ case "${1:-}" in | ||
| 21 | 21 | *) echo 'Only HTTP(S) browser URLs and Claude desktop callbacks are accepted.' >&2; exit 2;; |
| 22 | 22 | esac |
| 23 | 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 ' | |
| 24 | 新增:browser_request() { | |
| 25 | 新增: # Chromium already runs as cage-browser, whose sudo rules intentionally do | |
| 26 | 新增: # not allow running arbitrary commands (even as itself). | |
| 27 | 新增: if [ "$(id -un)" = cage-browser ]; then | |
| 28 | 新增: /usr/bin/node "$@" | |
| 29 | 新增: else | |
| 30 | 新增: sudo -u cage-browser /usr/bin/node "$@" | |
| 31 | 新增: fi | |
| 32 | 新增:} | |
| 33 | 新增:printf '%s' "${2:-}" | browser_request --input-type=module -e ' | |
| 25 | 34 | import {readFileSync} from "node:fs"; |
| 26 | 35 | const {token}=JSON.parse(readFileSync("/etc/claude-cage/browser-control.json","utf8")); |
| 27 | 36 | 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]})}); |
| @@ -95,6 +95,9 @@ var imageInput string | ||
| 95 | 95 | //go:embed desktop-files.py |
| 96 | 96 | var desktopFiles string |
| 97 | 97 | |
| 98 | 新增://go:embed desktop-downloads.py | |
| 99 | 新增:var desktopDownloads string | |
| 100 | 新增: | |
| 98 | 101 | //go:embed native-ime.py |
| 99 | 102 | var nativeIME string |
| 100 | 103 | |
| @@ -112,7 +115,9 @@ func nativeInputScript() string { | ||
| 112 | 115 | } |
| 113 | 116 | |
| 114 | 117 | func fileInputScript() string { |
| 115 | 删除: return "\nsudo tee /usr/local/bin/cage-desktop-files >/dev/null <<'CAGE_DESKTOP_FILES'\n" + desktopFiles + "\nCAGE_DESKTOP_FILES\nsudo chmod 0755 /usr/local/bin/cage-desktop-files\n" | |
| 118 | 新增: return "\nsudo tee /usr/local/bin/cage-desktop-files >/dev/null <<'CAGE_DESKTOP_FILES'\n" + desktopFiles + "\nCAGE_DESKTOP_FILES\nsudo chmod 0755 /usr/local/bin/cage-desktop-files\n" + | |
| 119 | 新增: "sudo tee /usr/local/lib/cage-desktop-downloads.py >/dev/null <<'CAGE_DESKTOP_DOWNLOADS'\n" + desktopDownloads + "\nCAGE_DESKTOP_DOWNLOADS\n" + | |
| 120 | 新增: "sudo tee /usr/local/bin/cage-save-download >/dev/null <<'CAGE_DESKTOP_DOWNLOAD_COPY'\n" + saveDownload + "\nCAGE_DESKTOP_DOWNLOAD_COPY\nsudo chmod 0755 /usr/local/bin/cage-save-download\n" | |
| 116 | 121 | } |
| 117 | 122 | |
| 118 | 123 | func imageInputScript() string { |
| @@ -72,6 +72,11 @@ func TestToolUpdateLeaseHonorsPauseStopAndConfigurationAtRenewal(t *testing.T) { | ||
| 72 | 72 | t.Fatal(err) |
| 73 | 73 | } |
| 74 | 74 | before := gate.Status() |
| 75 | 新增: // Windows can grant and renew within the same wall-clock tick. | |
| 76 | 新增: // Advance past the grant tick before requiring a later deadline. | |
| 77 | 新增: for !time.Now().Add(cage.GateLease).After(before.Until) { | |
| 78 | 新增: time.Sleep(time.Millisecond) | |
| 79 | 新增: } | |
| 75 | 80 | switch condition { |
| 76 | 81 | case "paused": |
| 77 | 82 | if err := s.pauseNetworkNow("test user pause"); err != nil { |
| @@ -8,6 +8,7 @@ import ( | ||
| 8 | 8 | "io" |
| 9 | 9 | "net/http" |
| 10 | 10 | "net/url" |
| 11 | 新增: "path/filepath" | |
| 11 | 12 | "regexp" |
| 12 | 13 | "strings" |
| 13 | 14 | "time" |
| @@ -89,7 +90,7 @@ func (s *Server) fileInputAction(w http.ResponseWriter, r *http.Request) { | ||
| 89 | 90 | return |
| 90 | 91 | } |
| 91 | 92 | action := r.PathValue("action") |
| 92 | 删除: if action != "start" && action != "finish" && action != "cancel" && action != "directory" { | |
| 93 | 新增: if action != "start" && action != "finish" && action != "cancel" && action != "directory" && action != "download-retry" { | |
| 93 | 94 | http.NotFound(w, r) |
| 94 | 95 | return |
| 95 | 96 | } |
| @@ -105,7 +106,7 @@ func (s *Server) fileInputAction(w http.ResponseWriter, r *http.Request) { | ||
| 105 | 106 | http.Error(w, "文件传递方式无效", 400) |
| 106 | 107 | return |
| 107 | 108 | } |
| 108 | 删除: if action == "directory" && input.Target != "desktop" { | |
| 109 | 新增: if (action == "directory" || action == "download-retry") && input.Target != "desktop" { | |
| 109 | 110 | http.Error(w, "文件夹目标无效", 400) |
| 110 | 111 | return |
| 111 | 112 | } |
| @@ -172,9 +173,45 @@ func (s *Server) desktopFileRequests(w http.ResponseWriter, r *http.Request) { | ||
| 172 | 173 | requestError(w, err) |
| 173 | 174 | return |
| 174 | 175 | } |
| 176 | 新增: if err = s.rememberDesktopDownloads(result); err != nil { | |
| 177 | 新增: requestError(w, err) | |
| 178 | 新增: return | |
| 179 | 新增: } | |
| 175 | 180 | jsonReply(w, result) |
| 176 | 181 | } |
| 177 | 182 | |
| 183 | 新增:// Register completed exports before the UI can ask a native bridge to save them. | |
| 184 | 新增:// Guest paths are never accepted as arbitrary host paths. | |
| 185 | 新增:func (s *Server) rememberDesktopDownloads(result map[string]any) error { | |
| 186 | 新增: items, _ := result["downloads"].([]any) | |
| 187 | 新增: for _, value := range items { | |
| 188 | 新增: item, ok := value.(map[string]any) | |
| 189 | 新增: if !ok { | |
| 190 | 新增: return errors.New("Desktop 下载记录无效") | |
| 191 | 新增: } | |
| 192 | 新增: id, _ := item["id"].(string) | |
| 193 | 新增: name, _ := item["name"].(string) | |
| 194 | 新增: if !browserFileID.MatchString(id) || !browserFileName(name) { | |
| 195 | 新增: return errors.New("Desktop 下载记录无效") | |
| 196 | 新增: } | |
| 197 | 新增: item["target"] = "desktop" | |
| 198 | 新增: if item["state"] != "saved" { | |
| 199 | 新增: delete(item, "path") | |
| 200 | 新增: continue | |
| 201 | 新增: } | |
| 202 | 新增: root := s.environmentDir() | |
| 203 | 新增: if item["path"] != strings.TrimRight(guestPath(root), "/")+"/Downloads/"+name { | |
| 204 | 新增: return errors.New("Desktop 下载保存位置无效") | |
| 205 | 新增: } | |
| 206 | 新增: path := filepath.Join(root, "Downloads", name) | |
| 207 | 新增: if err := rememberDownload(s.profile, SavedDownload{ID: id, Name: name, Path: path}, true); err != nil { | |
| 208 | 新增: return err | |
| 209 | 新增: } | |
| 210 | 新增: item["path"] = path | |
| 211 | 新增: } | |
| 212 | 新增: return nil | |
| 213 | 新增:} | |
| 214 | 新增: | |
| 178 | 215 | func (s *Server) fileInputUpload(w http.ResponseWriter, r *http.Request) { |
| 179 | 216 | target, id, name := r.PathValue("target"), r.PathValue("id"), r.URL.Query().Get("name") |
| 180 | 217 | if !validFileTargetID(target, id) || !browserFileName(name) { |
| @@ -4,6 +4,8 @@ import ( | ||
| 4 | 4 | "encoding/json" |
| 5 | 5 | "io" |
| 6 | 6 | "net/http" |
| 7 | 新增: "os" | |
| 8 | 新增: "path/filepath" | |
| 7 | 9 | "strings" |
| 8 | 10 | "testing" |
| 9 | 11 | ) |
| @@ -38,6 +40,57 @@ func TestFileInputBrowserGestureAuthorizationAndTarget(t *testing.T) { | ||
| 38 | 40 | } |
| 39 | 41 | } |
| 40 | 42 | |
| 43 | 新增:func TestDesktopDownloadsRegisterOnlyCompletedFilesInSharedDownloadDirectory(t *testing.T) { | |
| 44 | 新增: s := testServer(t) | |
| 45 | 新增: name := "视频.mp4" | |
| 46 | 新增: item := map[string]any{"id": testBrowserFileID, "name": name, "state": "saved", | |
| 47 | 新增: "path": strings.TrimRight(guestPath(s.environmentDir()), "/") + "/Downloads/" + name} | |
| 48 | 新增: result := map[string]any{"downloads": []any{item}} | |
| 49 | 新增: if err := s.rememberDesktopDownloads(result); err != nil { | |
| 50 | 新增: t.Fatal(err) | |
| 51 | 新增: } | |
| 52 | 新增: saved, err := readSavedDownload(s.profile, testBrowserFileID) | |
| 53 | 新增: if err != nil || saved.Path != filepath.Join(s.environmentDir(), "Downloads", name) { | |
| 54 | 新增: t.Fatal(saved, err) | |
| 55 | 新增: } | |
| 56 | 新增: // A user-chosen host destination must survive later guest polling. | |
| 57 | 新增: saved.Path = filepath.Join(t.TempDir(), name) | |
| 58 | 新增: if err := rememberDownload(s.profile, saved, false); err != nil { | |
| 59 | 新增: t.Fatal(err) | |
| 60 | 新增: } | |
| 61 | 新增: item["path"] = strings.TrimRight(guestPath(s.environmentDir()), "/") + "/Downloads/" + name | |
| 62 | 新增: if err := s.rememberDesktopDownloads(result); err != nil { | |
| 63 | 新增: t.Fatal(err) | |
| 64 | 新增: } | |
| 65 | 新增: again, _ := readSavedDownload(s.profile, testBrowserFileID) | |
| 66 | 新增: if again.Path != saved.Path { | |
| 67 | 新增: t.Fatal("poll replaced user destination", again) | |
| 68 | 新增: } | |
| 69 | 新增: for _, path := range []string{"/etc/passwd", strings.TrimRight(guestPath(s.environmentDir()), "/") + "/Downloads/../secret"} { | |
| 70 | 新增: item["path"] = path | |
| 71 | 新增: if s.rememberDesktopDownloads(result) == nil { | |
| 72 | 新增: t.Fatal("untrusted path accepted", path) | |
| 73 | 新增: } | |
| 74 | 新增: } | |
| 75 | 新增: item["name"] = "../secret" | |
| 76 | 新增: if s.rememberDesktopDownloads(result) == nil { | |
| 77 | 新增: t.Fatal("path-like name accepted") | |
| 78 | 新增: } | |
| 79 | 新增: item["name"], item["state"] = name, "downloading" | |
| 80 | 新增: if err := os.Remove(savedDownloadPath(s.profile, testBrowserFileID)); err != nil { | |
| 81 | 新增: t.Fatal(err) | |
| 82 | 新增: } | |
| 83 | 新增: if err := s.rememberDesktopDownloads(result); err != nil { | |
| 84 | 新增: t.Fatal(err) | |
| 85 | 新增: } | |
| 86 | 新增: if _, err := readSavedDownload(s.profile, testBrowserFileID); err == nil { | |
| 87 | 新增: t.Fatal("partial file registered") | |
| 88 | 新增: } | |
| 89 | 新增: if _, exists := item["path"]; exists { | |
| 90 | 新增: t.Fatal("partial host path leaked") | |
| 91 | 新增: } | |
| 92 | 新增:} | |
| 93 | 新增: | |
| 41 | 94 | func TestFileInputTerminalRequiresOriginalLiveSession(t *testing.T) { |
| 42 | 95 | s := testServer(t) |
| 43 | 96 | s.ready = true |
| @@ -0,0 +1,31 @@ | ||
| 1 | 新增:#!/usr/bin/env bash | |
| 2 | 新增:set -euo pipefail | |
| 3 | 新增:cd "$(dirname "$0")/.." | |
| 4 | 新增:temporary="$(mktemp -d)" | |
| 5 | 新增:trap 'rm -rf "$temporary"' EXIT | |
| 6 | 新增:binary="$temporary/account-device-tests" | |
| 7 | 新增:case "${1:-}" in | |
| 8 | 新增: '') ;; | |
| 9 | 新增: --biometric) | |
| 10 | 新增: : "${CAGE_SIGNING_IDENTITY:?Biometric tests require a Developer ID identity}" | |
| 11 | 新增: : "${CAGE_PROVISIONING_PROFILE:?Biometric tests require a provisioning profile}" | |
| 12 | 新增: bundle="$temporary/Cage.app" | |
| 13 | 新增: mkdir -p "$bundle/Contents/MacOS" | |
| 14 | 新增: cp "$CAGE_PROVISIONING_PROFILE" "$bundle/Contents/embedded.provisionprofile" | |
| 15 | 新增: cat > "$bundle/Contents/Info.plist" <<'PLIST' | |
| 16 | 新增:<?xml version="1.0" encoding="UTF-8"?><plist version="1.0"><dict><key>CFBundleIdentifier</key><string>io.github.lee-xeo.claude-cage</string><key>CFBundleExecutable</key><string>Cage</string><key>CFBundlePackageType</key><string>APPL</string></dict></plist> | |
| 17 | 新增:PLIST | |
| 18 | 新增: binary="$bundle/Contents/MacOS/Cage" | |
| 19 | 新增: ;; | |
| 20 | 新增: *) echo 'Usage: scripts/test-account-device.sh [--biometric]' >&2; exit 2 ;; | |
| 21 | 新增:esac | |
| 22 | 新增:swiftc -O -parse-as-library -framework Security -framework LocalAuthentication \ | |
| 23 | 新增: desktop/AccountDevice.swift desktop/AccountDeviceTests.swift -o "$binary" | |
| 24 | 新增:if [[ "${1:-}" == --biometric ]]; then | |
| 25 | 新增: codesign --force --sign "$CAGE_SIGNING_IDENTITY" --timestamp=none "$binary" | |
| 26 | 新增: signing_team="$(codesign -dv --verbose=4 "$binary" 2>&1 | sed -n 's/^TeamIdentifier=//p')" | |
| 27 | 新增: bash scripts/prepare-account-signing.sh "$CAGE_PROVISIONING_PROFILE" "$signing_team" "$temporary/account.entitlements" | |
| 28 | 新增: codesign --force --sign "$CAGE_SIGNING_IDENTITY" --options runtime --timestamp=none \ | |
| 29 | 新增: --entitlements "$temporary/account.entitlements" "$bundle" | |
| 30 | 新增:fi | |
| 31 | 新增:"$binary" "$@" | |
| @@ -3,14 +3,26 @@ import {createWorkbench} from './workbench-fixture.mjs'; | ||
| 3 | 3 | let fixture; |
| 4 | 4 | const calls=[]; |
| 5 | 5 | let cancelBiometric=false; |
| 6 | 新增:let unavailable=false, supported=true, legacyLauncher=false, failEnrollment=false, sequence=0; | |
| 7 | 新增:const keychain=new Map(); | |
| 6 | 8 | fixture=await createWorkbench({nativeRequest:async(body)=>{ |
| 7 | 9 | if(body.action!=='accountDevice')return null; |
| 8 | 删除: const {operation,kind}=body;calls.push({operation,kind}); | |
| 9 | 删除: if(operation==='status')return {supported:true,biometric_available:true}; | |
| 10 | 删除: const a=fixture.state.account;a.devices ||= {}; | |
| 11 | 删除: if(operation==='enable')a.devices[kind]='fixture-'+kind; | |
| 12 | 删除: if(operation==='disable')delete a.devices[kind]; | |
| 10 | 新增: const {operation,kind}=body; | |
| 11 | 新增: const a=fixture?.state.account || {};a.devices ||= {}; | |
| 12 | 新增: const binding=a.device_binding || 'original-directory'; | |
| 13 | 新增: calls.push({operation,kind,binding}); | |
| 14 | 新增: if(operation==='status'&&legacyLauncher)return {supported:true,biometric_available:true}; | |
| 15 | 新增: if(operation==='status')return {supported,biometric_available:true,device_status:Object.fromEntries(['automatic','biometric'].map(k=>[ | |
| 16 | 新增: k,!a.devices[k]?'disabled':unavailable?'unavailable':keychain.get(binding+'.'+k)===a.devices[k]?(k==='biometric'?'authentication_required':'available'):'missing', | |
| 17 | 新增: ]))}; | |
| 18 | 新增: if(operation==='enable'){ | |
| 19 | 新增: a.devices[kind]='fixture-'+kind+'-'+(++sequence); | |
| 20 | 新增: if(failEnrollment){delete a.devices[kind];throw Error('钥匙串保存失败');} | |
| 21 | 新增: keychain.set(binding+'.'+kind,a.devices[kind]); | |
| 22 | 新增: } | |
| 23 | 新增: if(operation==='disable'){delete a.devices[kind];keychain.delete(binding+'.'+kind);} | |
| 13 | 24 | if(operation==='unlock'){ |
| 25 | 新增: assert.equal(keychain.get(binding+'.'+kind),a.devices[kind],'attempted unlock with missing credentials'); | |
| 14 | 26 | if(kind==='biometric'&&cancelBiometric)throw Error('已取消指纹验证,可继续使用密码'); |
| 15 | 27 | if(kind==='automatic'&&a.require_authentication)throw Error('手动锁定'); |
| 16 | 28 | a.unlocked=true;a.require_authentication=false; |
| @@ -54,11 +66,76 @@ try { | ||
| 54 | 66 | assert.equal(state.account.unlocked,false); |
| 55 | 67 | await page.screenshot({path:'.oil-ui/local-account/shots/touch-id-fallback.png'}); |
| 56 | 68 | cancelBiometric=false;await page.getByRole('button',{name:'使用 Touch ID 解锁',exact:true}).click();await menu().waitFor(); |
| 69 | 新增: | |
| 70 | 新增: // Copying the account directory preserves server IDs but not native bindings. | |
| 71 | 新增: // Stop the old page first, just as directory migration requires stopping Cage. | |
| 72 | 新增: const workbenchURL=page.url(); | |
| 73 | 新增: await page.goto('about:blank'); | |
| 74 | 新增: const oldDevices=structuredClone(state.account.devices); | |
| 75 | 新增: const unlocksBeforeMigration=calls.filter(x=>x.operation==='unlock').length; | |
| 76 | 新增: Object.assign(state.account,{device_binding:'migrated-directory',unlocked:false,require_authentication:false}); | |
| 77 | 新增: await page.goto(workbenchURL); | |
| 78 | 新增: await page.getByRole('status').filter({hasText:'当前目录的快捷登录凭据缺失'}).waitFor(); | |
| 79 | 新增: assert.equal(calls.filter(x=>x.operation==='unlock').length,unlocksBeforeMigration,JSON.stringify(calls)); | |
| 80 | 新增: assert.equal(await page.getByRole('button',{name:'使用 Touch ID 解锁',exact:true}).count(),0); | |
| 81 | 新增: await page.reload();await page.getByRole('status').filter({hasText:'当前目录的快捷登录凭据缺失'}).waitFor(); | |
| 82 | 新增: assert.equal(calls.filter(x=>x.operation==='unlock').length,unlocksBeforeMigration,'reopen retried invalid enrollment'); | |
| 83 | 新增: await page.getByLabel('账户密码',{exact:true}).fill('fixture-password'); | |
| 84 | 新增: await page.getByRole('button',{name:'解锁 Cage',exact:true}).click();await menu().waitFor(); | |
| 85 | 新增: await menu().click();await page.getByRole('menuitem',{name:'设置',exact:true}).click(); | |
| 86 | 新增: await page.getByText('当前目录的凭据缺失或已失效,请重新开启。',{exact:true}).first().waitFor(); | |
| 87 | 新增: assert.equal(await automatic.isChecked(),false);assert.equal(await biometric.isChecked(),false); | |
| 88 | 新增: assert.deepEqual(state.account.devices,oldDevices,'checking status mutated authorization'); | |
| 89 | 新增: await page.locator('.account-device-settings').screenshot({path:'.oil-ui/local-account/shots/device-migrated.png'}); | |
| 90 | 新增: failEnrollment=true;await automatic.click();await page.getByRole('alert').filter({hasText:'钥匙串保存失败'}).waitFor(); | |
| 91 | 新增: await automatic.waitFor();assert.equal(await automatic.isChecked(),false);assert.equal(state.account.devices.automatic,undefined); | |
| 92 | 新增: failEnrollment=false;await automatic.click();await page.getByRole('status').filter({hasText:'已开启'}).waitFor(); | |
| 93 | 新增: await page.waitForFunction(()=>document.querySelector('.account-device-settings input')?.checked); | |
| 94 | 新增: await biometric.click();await page.getByRole('status').filter({hasText:'已开启'}).waitFor(); | |
| 95 | 新增: await page.waitForFunction(()=>[...document.querySelectorAll('.account-device-settings input')].every(e=>e.checked)); | |
| 96 | 新增: assert.equal(keychain.get('original-directory.automatic'),oldDevices.automatic,'repair touched original binding'); | |
| 97 | 新增: state.account.unlocked=false;await page.reload();await menu().waitFor(); | |
| 98 | 新增: assert.equal(calls.filter(x=>x.operation==='unlock').length,unlocksBeforeMigration+1,'repaired enrollment did not unlock'); | |
| 99 | 新增: | |
| 100 | 新增: // A temporarily inaccessible Keychain is not missing enrollment. | |
| 101 | 新增: unavailable=true;await page.reload();await menu().click();await page.getByRole('menuitem',{name:'设置',exact:true}).click(); | |
| 102 | 新增: await page.getByRole('button',{name:'重新检查快捷登录'}).waitFor(); | |
| 103 | 新增: assert.equal(await automatic.isChecked(),false);assert.equal(await automatic.isDisabled(),true); | |
| 104 | 新增: const savedDevices=structuredClone(state.account.devices); | |
| 105 | 新增: unavailable=false;await page.getByRole('button',{name:'重新检查快捷登录'}).click(); | |
| 106 | 新增: await page.waitForFunction(()=>document.querySelector('.account-device-settings input')?.checked); | |
| 107 | 新增: assert.deepEqual(state.account.devices,savedDevices); | |
| 108 | 新增: // An older launcher can save credentials but cannot report their availability. | |
| 109 | 新增: // Do not present unchecked toggles that repeatedly re-enroll successfully. | |
| 110 | 新增: legacyLauncher=true;await page.reload();await menu().click();await page.getByRole('menuitem',{name:'设置',exact:true}).click(); | |
| 111 | 新增: await page.getByRole('status').filter({hasText:'当前应用启动器需要更新'}).waitFor(); | |
| 112 | 新增: assert.equal(await automatic.count(),0);assert.equal(await biometric.count(),0); | |
| 113 | 新增: assert.deepEqual(state.account.devices,savedDevices); | |
| 114 | 新增: legacyLauncher=false; | |
| 115 | 新增: // Linux/Windows expose no native quick-login capability even with copied records. | |
| 116 | 新增: supported=false;state.account.unlocked=false;await page.reload(); | |
| 117 | 新增: await page.getByLabel('账户密码',{exact:true}).waitFor(); | |
| 118 | 新增: assert.equal(await page.getByRole('button',{name:'使用 Touch ID 解锁',exact:true}).count(),0); | |
| 119 | 新增: assert.equal(calls.filter(x=>x.operation==='unlock').length,unlocksBeforeMigration+1); | |
| 120 | 新增: await page.getByLabel('账户密码',{exact:true}).fill('fixture-password'); | |
| 121 | 新增: await page.getByRole('button',{name:'解锁 Cage',exact:true}).click();await menu().waitFor(); | |
| 122 | 新增: await menu().click();await page.getByRole('menuitem',{name:'设置',exact:true}).click(); | |
| 123 | 新增: assert.equal(await automatic.count(),0); | |
| 124 | 新增: supported=true;await page.reload();await menu().waitFor(); | |
| 125 | 新增: // A locked response from a restarted controller invalidates cached availability | |
| 126 | 新增: // before the refreshed account (with a different binding) reaches the page. | |
| 127 | 新增: const beforeRestart=calls.filter(x=>x.operation==='unlock').length; | |
| 128 | 新增: Object.assign(state.account,{device_binding:'restarted-directory',unlocked:false,require_authentication:false}); | |
| 129 | 新增: await page.evaluate(()=>window.dispatchEvent(new Event('cage-account-locked'))); | |
| 130 | 新增: await page.getByRole('status').filter({hasText:'当前目录的快捷登录凭据缺失'}).waitFor(); | |
| 131 | 新增: assert.equal(calls.filter(x=>x.operation==='unlock').length,beforeRestart,'locked response reused old availability'); | |
| 132 | 新增: await page.getByLabel('账户密码',{exact:true}).fill('fixture-password'); | |
| 133 | 新增: await page.getByRole('button',{name:'解锁 Cage',exact:true}).click();await menu().waitFor(); | |
| 57 | 134 | await menu().click();await page.getByRole('menuitem',{name:'退出账户',exact:true}).click(); |
| 58 | 135 | await page.getByRole('dialog').getByRole('button',{name:'停止环境并退出账户',exact:true}).click(); |
| 59 | 136 | await page.getByRole('region',{name:'解锁 Cage',exact:true}).waitFor();await page.reload(); |
| 60 | 137 | await page.getByLabel('账户密码',{exact:true}).waitFor();assert.deepEqual(state.account.devices,{}); |
| 61 | 138 | assert.equal(await page.getByRole('button',{name:'使用 Touch ID 解锁',exact:true}).count(),0); |
| 62 | 139 | assert.deepEqual(errors,[]); |
| 63 | 删除: console.log('PASS: enrollment, automatic reopen, persistent manual lock, biometric cancellation/fallback, biometric unlock and logout revocation'); | |
| 140 | 新增: console.log('PASS: enrollment, reopen, manual lock, cancellation, migration, repair, failed save, temporary Keychain failure, unsupported platforms and logout'); | |
| 64 | 141 | }finally{await browser.close();} |
| @@ -78,7 +78,7 @@ try { | ||
| 78 | 78 | await page.getByRole("button", { name: "浏览器下载", exact: true }).click(); |
| 79 | 79 | await page.getByText("正在下载", { exact: false }).waitFor(); |
| 80 | 80 | await page |
| 81 | 删除: .getByRole("dialog", { name: "浏览器下载" }) | |
| 81 | 新增: .getByRole("dialog", { name: "下载文件" }) | |
| 82 | 82 | .getByRole("button", { name: "关闭面板" }) |
| 83 | 83 | .click(); |
| 84 | 84 | selections = [{ id: chooser, tabId: "tab-1", multiple: true }]; |
| @@ -104,7 +104,7 @@ try { | ||
| 104 | 104 | .getByText("/Users/test/Downloads/视频.mp4", { exact: true }) |
| 105 | 105 | .waitFor(); |
| 106 | 106 | await page |
| 107 | 删除: .getByRole("dialog", { name: "浏览器下载" }) | |
| 107 | 新增: .getByRole("dialog", { name: "下载文件" }) | |
| 108 | 108 | .getByRole("button", { name: "打开文件", exact: true }) |
| 109 | 109 | .click(); |
| 110 | 110 | await page |
| @@ -129,7 +129,7 @@ try { | ||
| 129 | 129 | "web UI must not send arbitrary host paths", |
| 130 | 130 | ); |
| 131 | 131 | await page |
| 132 | 删除: .getByRole("dialog", { name: "浏览器下载" }) | |
| 132 | 新增: .getByRole("dialog", { name: "下载文件" }) | |
| 133 | 133 | .getByRole("button", { name: "关闭面板" }) |
| 134 | 134 | .click(); |
| 135 | 135 | selections = [{ id: "a8af5851-5837-45ca-a820-1a2565bc7ec6", tabId: "tab-1", multiple: false }]; |
| @@ -151,7 +151,7 @@ try { | ||
| 151 | 151 | .getByText("/Users/test/Downloads/视频.mp4", { exact: true }) |
| 152 | 152 | .waitFor(); |
| 153 | 153 | await page |
| 154 | 删除: .getByRole("dialog", { name: "浏览器下载" }) | |
| 154 | 新增: .getByRole("dialog", { name: "下载文件" }) | |
| 155 | 155 | .getByRole("button", { name: "打开文件", exact: true }) |
| 156 | 156 | .click(); |
| 157 | 157 | await poll( |
| @@ -0,0 +1,56 @@ | ||
| 1 | 新增:import assert from "node:assert/strict"; | |
| 2 | 新增:import { createWorkbench } from "./workbench-fixture.mjs"; | |
| 3 | 新增: | |
| 4 | 新增:const id = "ef88f909-6ac3-4839-b45d-a9569f34d4ab"; | |
| 5 | 新增:let downloads = [], saved = [], calls = []; | |
| 6 | 新增:const fixture = await createWorkbench({ nativeRequest: async (body) => { | |
| 7 | 新增: if (["saveBrowserDownload", "browserDownloadAction"].includes(body.action)) calls.push(body); | |
| 8 | 新增: if (body.action === "saveBrowserDownload") return { canceled: true }; | |
| 9 | 新增: return { ok: true }; | |
| 10 | 新增:} }); | |
| 11 | 新增:const { browser, page, state, errors } = fixture; | |
| 12 | 新增:await page.route("**/api/input/files/desktop/requests", (route) => route.fulfill({ json: { uploads: [], downloads } })); | |
| 13 | 新增:await page.route("**/api/browser/files/saved", (route) => route.fulfill({ json: saved })); | |
| 14 | 新增:let retries = 0; | |
| 15 | 新增:await page.route("**/api/input/files/download-retry", async (route) => { | |
| 16 | 新增: assert.deepEqual(route.request().postDataJSON(), { id, target: "desktop" }); | |
| 17 | 新增: retries++; | |
| 18 | 新增: await route.fulfill({ json: { ok: true } }); | |
| 19 | 新增:}); | |
| 20 | 新增:const waitFor = async (predicate) => { | |
| 21 | 新增: for (let count = 0; count < 120; count++) { | |
| 22 | 新增: if (predicate()) return; | |
| 23 | 新增: await new Promise((resolve) => setTimeout(resolve, 50)); | |
| 24 | 新增: } | |
| 25 | 新增: throw new Error("Desktop download UI did not reach expected state"); | |
| 26 | 新增:}; | |
| 27 | 新增:try { | |
| 28 | 新增: state.status.ready = true; | |
| 29 | 新增: state.status.vm_running = true; | |
| 30 | 新增: await page.reload(); | |
| 31 | 新增: await page.getByRole("button", { name: "下载文件", exact: true }).waitFor(); | |
| 32 | 新增: // A tiny export can finish between polls; it must still offer Save As. | |
| 33 | 新增: const item = { id, name: "桌面视频.mp4", state: "saved", target: "desktop", | |
| 34 | 新增: startedAt: new Date(Date.now() + 5).toISOString(), path: "/Users/test/Cage/Downloads/桌面视频.mp4" }; | |
| 35 | 新增: saved = [{ id, name: item.name, path: item.path }]; | |
| 36 | 新增: downloads = [item]; | |
| 37 | 新增: await waitFor(() => calls.some((call) => call.action === "saveBrowserDownload")); | |
| 38 | 新增: await page.getByRole("button", { name: "下载文件", exact: true }).click(); | |
| 39 | 新增: const dialog = page.getByRole("dialog", { name: "下载文件" }); | |
| 40 | 新增: await dialog.getByText(item.path, { exact: true }).waitFor(); | |
| 41 | 新增: await dialog.getByRole("button", { name: "在文件夹中显示", exact: true }).click(); | |
| 42 | 新增: await waitFor(() => calls.some((call) => call.action === "browserDownloadAction" && call.id === id)); | |
| 43 | 新增: await page.reload(); | |
| 44 | 新增: await page.getByRole("button", { name: "下载文件", exact: true }).click(); | |
| 45 | 新增: await dialog.getByText(item.path, { exact: true }).waitFor(); | |
| 46 | 新增: assert.equal(calls.filter((call) => call.action === "saveBrowserDownload").length, 1, "history reopened a save dialog"); | |
| 47 | 新增: saved = []; | |
| 48 | 新增: downloads = [{ ...item, state: "failed", retryable: true, path: "", error: "共享目录暂时不可写" }]; | |
| 49 | 新增: await page.reload(); | |
| 50 | 新增: await page.getByRole("button", { name: "下载文件", exact: true }).click(); | |
| 51 | 新增: await dialog.getByRole("button", { name: "重试保存", exact: true }).click(); | |
| 52 | 新增: await waitFor(() => retries === 1); | |
| 53 | 新增: assert.equal(await dialog.getByRole("button", { name: "另存为…", exact: true }).count(), 0); | |
| 54 | 新增: assert.deepEqual(errors, []); | |
| 55 | 新增: console.log("PASS: Desktop instant export, native Save As cancel retains fallback, reveal, history does not reprompt, failed export uses Desktop retry"); | |
| 56 | 新增:} finally { await browser.close(); } | |
| @@ -62,7 +62,7 @@ try { | ||
| 62 | 62 | await page.getByText("已保存到本机", { exact: true }).waitFor(); |
| 63 | 63 | assert.equal(retries, 1); |
| 64 | 64 | await page.screenshot({ path: fileURLToPath(new URL("download-recovery.png", output)) }); |
| 65 | 删除: await page.getByRole("dialog", { name: "浏览器下载" }).getByRole("button", { name: "关闭面板" }).click(); | |
| 65 | 新增: await page.getByRole("dialog", { name: "下载文件" }).getByRole("button", { name: "关闭面板" }).click(); | |
| 66 | 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(); |
| @@ -23,11 +23,14 @@ import "./account.css"; | ||
| 23 | 23 | |
| 24 | 24 | const AccountContext = createContext(null); |
| 25 | 25 | export const useAccount = () => useContext(AccountContext); |
| 26 | 新增:const credentialPresent = (status) => status === "available" || status === "authentication_required"; | |
| 26 | 27 | |
| 27 | 28 | export function AccountProvider({ children }) { |
| 28 | 29 | const [account, setAccount] = useState(null); |
| 29 | 30 | const [error, setError] = useState(""); |
| 30 | 删除: const [deviceSupport, setDeviceSupport] = useState(null); | |
| 31 | 新增: const [deviceCheck, setDeviceCheck] = useState(null); | |
| 32 | 新增: const deviceKey = JSON.stringify([account?.device_binding, account?.devices?.automatic, account?.devices?.biometric]); | |
| 33 | 新增: const deviceSupport = deviceCheck?.key === deviceKey ? deviceCheck.value : null; | |
| 31 | 34 | const [deviceNotice, setDeviceNotice] = useState(""); |
| 32 | 35 | const sequence = useRef(0); |
| 33 | 36 | const refresh = async () => { |
| @@ -52,16 +55,23 @@ export function AccountProvider({ children }) { | ||
| 52 | 55 | }; |
| 53 | 56 | useEffect(() => { |
| 54 | 57 | if (!account || deviceSupport !== null) return; |
| 55 | 删除: if (!nativeAvailable()) { setDeviceSupport({ supported: false }); return; } | |
| 58 | 新增: if (!nativeAvailable()) { setDeviceCheck({ key: deviceKey, value: { supported: false } }); return; } | |
| 56 | 59 | let live = true; |
| 57 | 60 | native("accountDevice", { operation: "status" }) |
| 58 | 删除: .then((value) => { if (live) setDeviceSupport(value || { supported: false }); }) | |
| 59 | 删除: .catch(() => { if (live) setDeviceSupport({ supported: false }); }); | |
| 61 | 新增: .then((value) => { if (live) setDeviceCheck({ key: deviceKey, value: value || { supported: false } }); }) | |
| 62 | 新增: .catch(() => { if (live) setDeviceCheck({ key: deviceKey, value: { supported: false } }); }); | |
| 60 | 63 | return () => { live = false; }; |
| 61 | 删除: }, [Boolean(account), deviceSupport]); | |
| 64 | 新增: }, [Boolean(account), deviceKey, deviceSupport]); | |
| 62 | 65 | const deviceAction = async (operation, kind) => { |
| 63 | 删除: await native("accountDevice", { operation, kind }); | |
| 64 | 删除: return refresh(); | |
| 66 | 新增: if (!deviceSupport?.device_status) throw new Error("当前应用启动器需要更新,请重新安装完整的 Cage 应用后再设置快捷登录。"); | |
| 67 | 新增: try { | |
| 68 | 新增: await native("accountDevice", { operation, kind }); | |
| 69 | 新增: } finally { | |
| 70 | 新增: // Failed enrollment may have revoked its server record. Reconcile both | |
| 71 | 新增: // sides after failures too, including a credential removed while open. | |
| 72 | 新增: await refresh(); | |
| 73 | 新增: setDeviceCheck(null); | |
| 74 | 新增: } | |
| 65 | 75 | }; |
| 66 | 76 | useEffect(() => { |
| 67 | 77 | let live = true, |
| @@ -87,6 +97,9 @@ export function AccountProvider({ children }) { | ||
| 87 | 97 | } |
| 88 | 98 | }; |
| 89 | 99 | const locked = () => { |
| 100 | 新增: // A 423 can follow a controller restart or directory change. Do not | |
| 101 | 新增: // auto-unlock using the previous account's cached Keychain status. | |
| 102 | 新增: setDeviceCheck(null); | |
| 90 | 103 | setAccount((previous) => |
| 91 | 104 | previous ? { ...previous, unlocked: false } : previous, |
| 92 | 105 | ); |
| @@ -102,7 +115,7 @@ export function AccountProvider({ children }) { | ||
| 102 | 115 | }; |
| 103 | 116 | }, []); |
| 104 | 117 | return ( |
| 105 | 删除: <AccountContext.Provider value={{ account, error, refresh, act, deviceSupport, deviceAction, deviceNotice, setDeviceNotice }}> | |
| 118 | 新增: <AccountContext.Provider value={{ account, error, refresh, act, deviceSupport, deviceAction, deviceNotice, setDeviceNotice, recheckDevices: () => setDeviceCheck(null) }}> | |
| 106 | 119 | {children} |
| 107 | 120 | </AccountContext.Provider> |
| 108 | 121 | ); |
| @@ -176,7 +189,7 @@ export function AccountGate({ children }) { | ||
| 176 | 189 | }, [Boolean(account), account?.unlocked, connectionError]); |
| 177 | 190 | useEffect(() => { |
| 178 | 191 | const id = account?.devices?.automatic; |
| 179 | 删除: if (!id || account.unlocked || account.require_authentication || !deviceSupport?.supported || automaticAttempt.current === id) return; | |
| 192 | 新增: if (!id || account.unlocked || account.require_authentication || !deviceSupport?.supported || deviceSupport.device_status?.automatic !== "available" || automaticAttempt.current === id) return; | |
| 180 | 193 | automaticAttempt.current = id; |
| 181 | 194 | setBusy(true); |
| 182 | 195 | deviceAction("unlock", "automatic").catch((e) => setError(e.message)).finally(() => setBusy(false)); |
| @@ -210,7 +223,7 @@ export function AccountGate({ children }) { | ||
| 210 | 223 | ); |
| 211 | 224 | setPassword(""); |
| 212 | 225 | setConfirmation(""); |
| 213 | 删除: if (creating && rememberLogin && deviceSupport?.supported) { | |
| 226 | 新增: if (creating && rememberLogin && deviceSupport?.supported && deviceSupport.device_status) { | |
| 214 | 227 | try { await deviceAction("enable", "automatic"); } |
| 215 | 228 | catch (e) { setDeviceNotice(`账户已创建,记住登录未能开启:${e.message}。可在「设置 → 账户」中重试。`); } |
| 216 | 229 | } |
| @@ -291,13 +304,22 @@ export function AccountGate({ children }) { | ||
| 291 | 304 | {error || connectionError} |
| 292 | 305 | </p> |
| 293 | 306 | )} |
| 294 | 删除: {creating && deviceSupport?.supported && ( | |
| 307 | 新增: {!creating && Object.values(deviceSupport?.device_status || {}).includes("missing") && ( | |
| 308 | 新增: <p className="field-help" role="status">当前目录的快捷登录凭据缺失或已失效。请用密码解锁,再到「设置 → 账户 → 登录与解锁」重新开启。</p> | |
| 309 | 新增: )} | |
| 310 | 新增: {!creating && Object.values(deviceSupport?.device_status || {}).includes("unavailable") && ( | |
| 311 | 新增: <p className="field-help" role="status">暂时无法检查系统钥匙串,请先用密码解锁。快捷登录授权记录已保留。</p> | |
| 312 | 新增: )} | |
| 313 | 新增: {deviceSupport?.supported && !deviceSupport.device_status && ( | |
| 314 | 新增: <p className="field-help" role="status">当前应用启动器需要更新,暂时无法检查快捷登录状态。请先用密码进入,并重新安装完整的 Cage 应用。</p> | |
| 315 | 新增: )} | |
| 316 | 新增: {creating && deviceSupport?.supported && deviceSupport.device_status && ( | |
| 295 | 317 | <label className="account-device-option check-line"> |
| 296 | 318 | <input type="checkbox" checked={rememberLogin} onChange={(e) => setRememberLogin(e.target.checked)} /> |
| 297 | 319 | <span><strong>记住登录</strong><small>下次打开直接进入。手动锁定后仍需验证。</small></span> |
| 298 | 320 | </label> |
| 299 | 321 | )} |
| 300 | 删除: {!creating && deviceSupport?.supported && account.devices?.biometric && ( | |
| 322 | 新增: {!creating && deviceSupport?.supported && credentialPresent(deviceSupport.device_status?.biometric) && account.devices?.biometric && ( | |
| 301 | 323 | <button type="button" className="quiet-button account-submit" disabled={busy} |
| 302 | 324 | onClick={async () => { |
| 303 | 325 | setBusy(true); setError(""); |
| @@ -643,11 +665,23 @@ export function AccountSettings({ busy: environmentBusy, onDirty }) { | ||
| 643 | 665 | } |
| 644 | 666 | |
| 645 | 667 | function AccountDeviceSettings() { |
| 646 | 删除: const { account, deviceSupport, deviceAction } = useAccount(); | |
| 668 | 新增: const { account, deviceSupport, deviceAction, recheckDevices } = useAccount(); | |
| 647 | 669 | const [busy, setBusy] = useState(false); |
| 648 | 670 | const [error, setError] = useState(""); |
| 649 | 671 | const [message, setMessage] = useState(""); |
| 650 | 672 | if (!deviceSupport?.supported) return null; |
| 673 | 新增: if (!deviceSupport.device_status) return <section className="account-device-settings" aria-label="登录与解锁"> | |
| 674 | 新增: <h4>登录与解锁</h4> | |
| 675 | 新增: <p className="field-help" role="status">当前应用启动器需要更新,无法检查快捷登录状态。请重新安装完整的 Cage 应用后再设置;现有授权已保留。</p> | |
| 676 | 新增: </section>; | |
| 677 | 新增: const states = deviceSupport.device_status || {}; | |
| 678 | 新增: const description = (kind, fallback) => states[kind] === "missing" | |
| 679 | 新增: ? "当前目录的凭据缺失或已失效,请重新开启。" | |
| 680 | 新增: : states[kind] === "unavailable" | |
| 681 | 新增: ? "暂时无法检查系统钥匙串,授权记录已保留。请稍后重新检查。" | |
| 682 | 新增: : states[kind] === "authentication_required" | |
| 683 | 新增: ? "凭据需要通过 Touch ID 验证,解锁时会请求指纹。" | |
| 684 | 新增: : fallback; | |
| 651 | 685 | const change = async (kind, enabled) => { |
| 652 | 686 | setBusy(true); setError(""); setMessage(""); |
| 653 | 687 | try { |
| @@ -659,15 +693,16 @@ function AccountDeviceSettings() { | ||
| 659 | 693 | return <section className="account-device-settings" aria-label="登录与解锁"> |
| 660 | 694 | <h4>登录与解锁</h4> |
| 661 | 695 | <label className="account-device-option check-line"> |
| 662 | 删除: <input type="checkbox" checked={Boolean(account.devices?.automatic)} disabled={busy} | |
| 696 | 新增: <input type="checkbox" checked={Boolean(account.devices?.automatic) && states.automatic === "available"} disabled={busy || states.automatic === "unavailable"} | |
| 663 | 697 | onChange={(event) => change("automatic", event.target.checked)} /> |
| 664 | 删除: <span><strong>记住登录</strong><small>重新打开直接进入。手动锁定后仍需指纹或密码。</small></span> | |
| 698 | 新增: <span><strong>记住登录</strong><small>{description("automatic", "重新打开直接进入。手动锁定后仍需指纹或密码。")}</small></span> | |
| 665 | 699 | </label> |
| 666 | 700 | <label className="account-device-option check-line"> |
| 667 | 删除: <input type="checkbox" checked={Boolean(account.devices?.biometric)} disabled={busy || (!deviceSupport.biometric_available && !account.devices?.biometric)} | |
| 701 | 新增: <input type="checkbox" checked={Boolean(account.devices?.biometric) && credentialPresent(states.biometric)} disabled={busy || states.biometric === "unavailable" || (!deviceSupport.biometric_available && !credentialPresent(states.biometric))} | |
| 668 | 702 | onChange={(event) => change("biometric", event.target.checked)} /> |
| 669 | 删除: <span><strong>使用 Touch ID 解锁</strong><small>{deviceSupport.biometric_available ? "手动锁定后,通过系统指纹验证进入。" : "请先在 macOS 系统设置中设置 Touch ID。"}</small></span> | |
| 703 | 新增: <span><strong>使用 Touch ID 解锁</strong><small>{description("biometric", deviceSupport.biometric_available ? "手动锁定后,通过系统指纹验证进入。" : "请先在 macOS 系统设置中设置 Touch ID。")}</small></span> | |
| 670 | 704 | </label> |
| 705 | 新增: {Object.values(states).includes("unavailable") && <button type="button" className="quiet-button" disabled={busy} onClick={recheckDevices}>重新检查快捷登录</button>} | |
| 671 | 706 | <p className="field-help">退出账户会撤销本机快捷登录授权。密码始终可以用于解锁。</p> |
| 672 | 707 | {error && <p className="account-error" role="alert">{error}</p>} |
| 673 | 708 | {message && <p className="account-saved" role="status">{message}</p>} |
| @@ -124,7 +124,7 @@ export function AppUpdateButton({ updates }) { | ||
| 124 | 124 | </svg> |
| 125 | 125 | {downloading && percent !== null && <span className="app-update-percent">{percent}%</span>} |
| 126 | 126 | </> |
| 127 | 删除: ) : failed ? <RefreshCw size={20} /> : <ArrowDownToLine size={22} />} | |
| 127 | 新增: ) : failed ? <RefreshCw size={20} /> : <ArrowDownToLine size={20} />} | |
| 128 | 128 | </button>} |
| 129 | 129 | {(failure || startupFailure) && <div className="app-update-error" role="alert">{failure || startupFailure}{visible ? "。可点击更新按钮重试。" : ""}</div>} |
| 130 | 130 | </> |
| @@ -10,23 +10,29 @@ export function useDownloadNotifications( | ||
| 10 | 10 | uploading = false, |
| 11 | 11 | ) { |
| 12 | 12 | const previous = useRef(new Map()); |
| 13 | 新增: const mountedAt = useRef(Date.now()); | |
| 13 | 14 | const observed = useRef(new Set()), |
| 14 | 15 | prompted = useRef(new Set()), |
| 15 | 16 | queue = useRef(Promise.resolve()); |
| 16 | 17 | useEffect(() => { |
| 17 | 18 | for (const item of downloads) { |
| 18 | 删除: if (["downloading", "saving"].includes(item.state)) | |
| 19 | 新增: if (["downloading", "saving"].includes(item.state) || | |
| 20 | 新增: (item.target === "desktop" && Date.parse(item.startedAt) >= mountedAt.current)) | |
| 19 | 21 | observed.current.add(item.id); |
| 20 | 22 | if (item.state === "failed" && previous.current.get(item.id) !== "failed") |
| 21 | 23 | onStatus( |
| 22 | 24 | `“${item.name}”未能保存:${item.error || "请在下载列表中重试"}`, |
| 23 | 25 | ); |
| 26 | 新增: if (item.target === "desktop" && observed.current.has(item.id) && previous.current.get(item.id) !== item.state) { | |
| 27 | 新增: if (item.state === "downloading") onStatus(`正在下载“${item.name}”,可在侧栏“下载”查看`); | |
| 28 | 新增: if (item.state === "saved") onStatus(`“${item.name}”已保存到默认工作区的 Downloads`); | |
| 29 | 新增: } | |
| 24 | 30 | if ( |
| 25 | 31 | nativeAvailable() && |
| 26 | 32 | !uploading && |
| 27 | 33 | observed.current.has(item.id) && |
| 28 | 34 | !prompted.current.has(item.id) && |
| 29 | 删除: (item.state === "saved" || (item.state === "failed" && item.retryable)) | |
| 35 | 新增: (item.state === "saved" || (item.target !== "desktop" && item.state === "failed" && item.retryable)) | |
| 30 | 36 | ) { |
| 31 | 37 | prompted.current.add(item.id); |
| 32 | 38 | queue.current = queue.current |
| @@ -38,6 +44,27 @@ export function useDownloadNotifications( | ||
| 38 | 44 | }, [downloads, uploading]); |
| 39 | 45 | } |
| 40 | 46 | |
| 47 | 新增:export function useDesktopFiles(ready) { | |
| 48 | 新增: const [files, setFiles] = useState({ uploads: [], downloads: [] }); | |
| 49 | 新增: useEffect(() => { | |
| 50 | 新增: if (!ready) { setFiles({ uploads: [], downloads: [] }); return; } | |
| 51 | 新增: let disposed = false, timer; | |
| 52 | 新增: const poll = async () => { | |
| 53 | 新增: try { | |
| 54 | 新增: const value = await api("/input/files/desktop/requests"); | |
| 55 | 新增: if (!disposed) setFiles({ uploads: value.uploads || [], downloads: value.downloads || [] }); | |
| 56 | 新增: } catch { | |
| 57 | 新增: // Closing Desktop invalidates its outstanding file choosers. | |
| 58 | 新增: if (!disposed) setFiles((previous) => ({ ...previous, uploads: [] })); | |
| 59 | 新增: } | |
| 60 | 新增: if (!disposed) timer = setTimeout(poll, 1500); | |
| 61 | 新增: }; | |
| 62 | 新增: void poll(); | |
| 63 | 新增: return () => { disposed = true; clearTimeout(timer); }; | |
| 64 | 新增: }, [ready]); | |
| 65 | 新增: return files; | |
| 66 | 新增:} | |
| 67 | 新增: | |
| 41 | 68 | async function saveDownload(item) { |
| 42 | 69 | if (!nativeAvailable()) { |
| 43 | 70 | const link = document.createElement("a"); |
| @@ -99,7 +126,7 @@ export function BrowserDownloads({ | ||
| 99 | 126 | sidebar ? "sidebar-link" : "icon-button browser-download-button" |
| 100 | 127 | } |
| 101 | 128 | aria-label={sidebar ? "下载文件" : "浏览器下载"} |
| 102 | 删除: title={failed ? "有下载未能保存,点击查看" : "浏览器下载"} | |
| 129 | 新增: title={failed ? "有下载未能保存,点击查看" : "下载文件"} | |
| 103 | 130 | onClick={() => setOpen(true)} |
| 104 | 131 | > |
| 105 | 132 | {failed ? <CircleAlert size={16} /> : <ArrowDownToLine size={16} />} |
| @@ -107,7 +134,7 @@ export function BrowserDownloads({ | ||
| 107 | 134 | </button> |
| 108 | 135 | {open && |
| 109 | 136 | createPortal( |
| 110 | 删除: <Modal title="浏览器下载" onClose={() => setOpen(false)}> | |
| 137 | 新增: <Modal title="下载文件" onClose={() => setOpen(false)}> | |
| 111 | 138 | <div className="browser-download-list"> |
| 112 | 139 | {!items.length && ( |
| 113 | 140 | <p> |
| @@ -126,7 +153,7 @@ export function BrowserDownloads({ | ||
| 126 | 153 | </p> |
| 127 | 154 | {item.path && <p className="download-path">{item.path}</p>} |
| 128 | 155 | {item.error && <p role="status">{item.error}</p>} |
| 129 | 删除: {(item.state === "saved" || item.retryable) && ( | |
| 156 | 新增: {(item.state === "saved" || (item.target !== "desktop" && item.retryable)) && ( | |
| 130 | 157 | <div className="download-actions"> |
| 131 | 158 | <button |
| 132 | 159 | disabled={Boolean(retrying)} |
| @@ -173,7 +200,8 @@ export function BrowserDownloads({ | ||
| 173 | 200 | onClick={async () => { |
| 174 | 201 | setRetrying(item.id); |
| 175 | 202 | try { |
| 176 | 删除: await api("/browser/download-retry", { id: item.id }); | |
| 203 | 新增: await api(item.target === "desktop" ? "/input/files/download-retry" : "/browser/download-retry", | |
| 204 | 新增: { id: item.id, ...(item.target === "desktop" ? { target: "desktop" } : {}) }); | |
| 177 | 205 | } catch (error) { |
| 178 | 206 | onStatus(error.message); |
| 179 | 207 | } finally { |
| @@ -16,6 +16,7 @@ import "./claude-desktop.css"; | ||
| 16 | 16 | const desktopZooms = [0.75, 0.9, 1, 1.1, 1.25, 1.5]; |
| 17 | 17 | |
| 18 | 18 | export function ClaudeDesktop({ |
| 19 | 新增: uploads = [], | |
| 19 | 20 | status, |
| 20 | 21 | onProjectOpened, |
| 21 | 22 | visible, |
| @@ -27,7 +28,6 @@ export function ClaudeDesktop({ | ||
| 27 | 28 | onExpand, |
| 28 | 29 | sidebarCollapsed, |
| 29 | 30 | }) { |
| 30 | 删除: const [uploads, setUploads] = useState([]); | |
| 31 | 31 | const [closedChooser, setClosedChooser] = useState(""); |
| 32 | 32 | const directoryRequest = uploads.find((item) => item.directory && item.id !== closedChooser); |
| 33 | 33 | const [zoom, setZoom] = useState(() => { |
| @@ -67,17 +67,6 @@ export function ClaudeDesktop({ | ||
| 67 | 67 | setSubmitting(false); |
| 68 | 68 | } |
| 69 | 69 | }; |
| 70 | 删除: useEffect(() => { | |
| 71 | 删除: if (!visible || !desktop?.running || !status.ready) { setUploads([]); return; } | |
| 72 | 删除: let disposed = false; | |
| 73 | 删除: const poll = async () => { | |
| 74 | 删除: try { const value = await api("/input/files/desktop/requests"); if (!disposed) setUploads(value.uploads || []); } | |
| 75 | 删除: catch { if (!disposed) setUploads([]); } | |
| 76 | 删除: }; | |
| 77 | 删除: void poll(); | |
| 78 | 删除: const timer = setInterval(poll, 1500); | |
| 79 | 删除: return () => { disposed = true; clearInterval(timer); }; | |
| 80 | 删除: }, [visible, desktop?.running, status.ready]); | |
| 81 | 70 | useEffect(() => { |
| 82 | 71 | if (!status.vm_running || status.job?.running) return; |
| 83 | 72 | let disposed = false; |
| @@ -30,7 +30,7 @@ import { ClaudeDesktop } from "./claude-desktop"; | ||
| 30 | 30 | import { useClaudeAccounts } from "./claude-accounts"; |
| 31 | 31 | import { AccountProvider, AccountGate } from "./account"; |
| 32 | 32 | import { BrowserHeader, TerminalHeader, ExpandSidebar, ExpandPane } from "./pane-headers"; |
| 33 | 删除:import { BrowserDownloads, useDownloadNotifications } from "./browser-downloads"; | |
| 33 | 新增:import { BrowserDownloads, useDownloadNotifications, useDesktopFiles } from "./browser-downloads"; | |
| 34 | 34 | import { BrowserUploads } from "./browser-uploads"; |
| 35 | 35 | import { AudioControls, useAudioOutput } from "./audio"; |
| 36 | 36 | import { ProjectDialog } from "./project-dialog"; |
| @@ -210,7 +210,9 @@ function App() { | ||
| 210 | 210 | ? status?.environment_update_required ? "环境待更新" : "浏览器待恢复" |
| 211 | 211 | : "已停止"; |
| 212 | 212 | const notify = (text) => setToast(text); |
| 213 | 删除: useDownloadNotifications(browser.downloads, notify, Boolean(browser.uploads?.length)); | |
| 213 | 新增: const desktopFiles = useDesktopFiles(Boolean(status?.ready)); | |
| 214 | 新增: const downloads = [...(browser.downloads || []), ...desktopFiles.downloads]; | |
| 215 | 新增: useDownloadNotifications(downloads, notify, Boolean(browser.uploads?.length || desktopFiles.uploads.length)); | |
| 214 | 216 | const refreshSettings = async () => { |
| 215 | 217 | const results = await Promise.allSettled([api("/settings"), api("/proxy")]); |
| 216 | 218 | if (results[0].status === "fulfilled") setSettings(results[0].value); |
| @@ -962,7 +964,7 @@ function App() { | ||
| 962 | 964 | forward={browser.split?.history?.[tab.id]?.forward ?? (tab.id === browser.active && browser.forward)} |
| 963 | 965 | action={action} onSelect={select} onClose={closeTab} onRename={renameTab} onPin={pinTab} onReorder={reorder} |
| 964 | 966 | onNew={newPage} onNavigate={address => navigate(tab.id, address)} onOpen={openBrowserPage} |
| 965 | 删除: downloads={browser.downloads} onStatus={notify} onRemote={async command => { | |
| 967 | 新增: downloads={downloads} onStatus={notify} onRemote={async command => { | |
| 966 | 968 | if (browser.active !== tab.id) await select(tab.id, false); |
| 967 | 969 | if (activeRef.current === tab.id) remote.current?.[command](); |
| 968 | 970 | }} |
| @@ -1089,7 +1091,7 @@ function App() { | ||
| 1089 | 1091 | > |
| 1090 | 1092 | {!sidebarCollapsed && ( |
| 1091 | 1093 | <WorkspaceSidebar |
| 1092 | 删除: downloadAction={<BrowserDownloads sidebar downloads={browser.downloads} ready={status.ready && !busy} onStatus={notify} />} | |
| 1094 | 新增: downloadAction={<BrowserDownloads sidebar downloads={downloads} ready={status.ready && !busy} onStatus={notify} />} | |
| 1093 | 1095 | updateAction={<AppUpdateButton updates={appUpdates} />} |
| 1094 | 1096 | workspace={selectedProject || status.workspace} |
| 1095 | 1097 | defaultWorkspace={status.environment_directory} |
| @@ -1146,6 +1148,7 @@ function App() { | ||
| 1146 | 1148 | style={{ "--split-left": `${100 * (dualBrowser && nativeSplit?.fraction || 0.5)}%` }}> |
| 1147 | 1149 | {dropSide && <div aria-hidden="true" className={`split-drop split-${dropSide}`}>{dropSide === "left" ? "放到左侧" : "放到右侧"}</div>} |
| 1148 | 1150 | {desktopOpen && <ClaudeDesktop |
| 1151 | 新增: uploads={desktopFiles.uploads} | |
| 1149 | 1152 | onProjectOpened={() => refreshStatus.current?.()} |
| 1150 | 1153 | status={status} visible={!settingsOpen} remoteRef={remote} |
| 1151 | 1154 | onStatus={notify} onFallback={(text, message) => setTransfer({ text, message })} |
| @@ -491,14 +491,14 @@ button.large { | ||
| 491 | 491 | } |
| 492 | 492 | .sidebar-footer-actions > .sidebar-link { flex: 1; min-width: 0; } |
| 493 | 493 | .app-update-button { |
| 494 | 删除: position: relative; flex: 0 0 36px; width: 36px; height: 36px; padding: 0; | |
| 494 | 新增: position: relative; flex: 0 0 32px; width: 32px; height: 32px; min-height: 32px; padding: 0; | |
| 495 | 495 | display: grid; place-items: center; border: 0; border-radius: 50%; |
| 496 | 496 | background: #b78a00; color: #fff; cursor: pointer; |
| 497 | 497 | } |
| 498 | 498 | .app-update-button:hover:not(:disabled) { background: #a17900; } |
| 499 | 499 | .app-update-button:focus-visible { outline: 2px solid var(--ink); outline-offset: 3px; } |
| 500 | 500 | .app-update-button:disabled { opacity: 1; cursor: progress; } |
| 501 | 删除:.app-update-ring { position: absolute; inset: 0; width: 36px; height: 36px; transform: rotate(-90deg); } | |
| 501 | 新增:.app-update-ring { position: absolute; inset: 0; width: 100%; height: 100%; transform: rotate(-90deg); } | |
| 502 | 502 | .app-update-ring circle { fill: none; stroke-width: 2; } |
| 503 | 503 | .app-update-ring-track { stroke: #ffffff40; } |
| 504 | 504 | .app-update-ring-value { stroke: currentColor; stroke-linecap: round; transition: stroke-dashoffset 0.18s linear; } |

