提交记录修改CONTRIBUTING.md+2 −0看文件
修改VERSION+1 −1看文件
修改cmd/cage/main.go+125 −3看文件
修改desktop/Cage.swift+32 −3看文件
新增desktop/NativeInput.swift+174 −0看文件
新增desktop/NativeInputTests.swift+42 −0看文件
修改desktop/linux/cage-desktop.c+47 −6看文件
新增desktop/linux/native-input.h+132 −0看文件
修改desktop/windows/Backend.cs+14 −0看文件
修改desktop/windows/MainWindow.cs+20 −1看文件
新增desktop/windows/NativeInput.cs+207 −0看文件
修改desktop/windows/Program.cs+7 −0看文件
修改docs/README.md+4 −0看文件
新增docs/design/diagnostics.md+62 −0看文件
修改docs/design/network-checks.md+2 −0看文件
新增docs/design/resources.md+57 −0看文件
修改docs/design/workbench.md+16 −0看文件
新增docs/research/2026-11-04-native-ime.md+80 −0看文件
修改docs/troubleshooting.md+19 −1看文件
修改internal/cage/browser-agent.mjs+14 −2看文件
修改internal/cage/claude-desktop-install.sh+1 −1看文件
修改internal/cage/claude-desktop-session.sh+1 −1看文件
修改internal/cage/claude_desktop.go+3 −2看文件
修改internal/cage/claude_desktop_test.go+78 −0看文件
修改internal/cage/guest-audio.sh+2 −1看文件
新增internal/cage/guest-memory.sh+39 −0看文件
修改internal/cage/guest-open.sh+9 −4看文件
修改internal/cage/guest-services.sh+14 −8看文件
修改internal/cage/guest.go+40 −2看文件
新增internal/cage/native-ime-session.sh+72 −0看文件
新增internal/cage/native-ime.py+327 −0看文件
新增internal/cage/native-input.mjs+50 −0看文件
修改internal/cage/novnc-patch.py+14 −0看文件
新增internal/cage/resources.go+323 −0看文件
新增internal/cage/resources_test.go+108 −0看文件
修改internal/cli/setup.go+9 −2看文件
新增internal/diagnostics/diagnostics_test.go+269 −0看文件
新增internal/diagnostics/export.go+80 −0看文件
新增internal/diagnostics/guest.go+50 −0看文件
新增internal/diagnostics/legacy.go+61 −0看文件
新增internal/diagnostics/lock_unix.go+11 −0看文件
新增internal/diagnostics/lock_windows.go+13 −0看文件
新增internal/diagnostics/redact.go+33 −0看文件
新增internal/diagnostics/store.go+234 −0看文件
新增internal/diagnostics/stream.go+79 −0看文件
新增internal/host/memory_darwin.go+9 −0看文件
新增internal/host/memory_linux.go+29 −0看文件
新增internal/host/memory_other.go+5 −0看文件
新增internal/host/memory_windows.go+8 −0看文件
修改internal/limaembed/limaembed.go+24 −0看文件
修改internal/managedproxy/core.go+14 −6看文件
修改internal/managedproxy/platform_linux.go+12 −10看文件
修改internal/managedproxy/platform_windows.go+11 −10看文件
修改internal/vm/lima.go+5 −1看文件
修改internal/workbench/browser_http.go+24 −0看文件
修改internal/workbench/browser_service.go+40 −6看文件
修改internal/workbench/browser_text_test.go+67 −0看文件
修改internal/workbench/claude_desktop.go+8 −6看文件
修改internal/workbench/claude_desktop_test.go+36 −1看文件
修改internal/workbench/desktop.go+1 −7看文件
新增internal/workbench/diagnostics.go+201 −0看文件
新增internal/workbench/diagnostics_test.go+158 −0看文件
修改internal/workbench/job_manager_test.go+2 −2看文件
修改internal/workbench/jobs.go+30 −4看文件
修改internal/workbench/lifecycle.go+17 −1看文件
新增internal/workbench/network_recovery.go+127 −0看文件
新增internal/workbench/network_recovery_test.go+112 −0看文件
新增internal/workbench/resources.go+65 −0看文件
修改internal/workbench/runtime.go+9 −3看文件
新增internal/workbench/runtime_shell_test.go+130 −0看文件
修改internal/workbench/safety.go+23 −1看文件
修改internal/workbench/server.go+43 −2看文件
修改patches/README.md+1 −0看文件
新增patches/lima/0012-dynamic-memory.patch+378 −0看文件
修改scripts/build-app.sh+1 −1看文件
新增third_party/lima/pkg/driver/memory.go+12 −0看文件
新增third_party/lima/pkg/driver/qemu/memory.go+81 −0看文件
新增third_party/lima/pkg/driver/qemu/memory_test.go+89 −0看文件
修改third_party/lima/pkg/driver/qemu/qemu.go+4 −0看文件
新增third_party/lima/pkg/driver/vz/memory_darwin.go+43 −0看文件
修改third_party/lima/pkg/hostagent/hostagent.go+3 −0看文件
新增third_party/lima/pkg/hostagent/resources.go+59 −0看文件
新增third_party/lima/pkg/hostagent/resources_unix.go+10 −0看文件
新增third_party/lima/pkg/hostagent/resources_windows.go+13 −0看文件
修改ui/package-lock.json+2 −2看文件
修改ui/package.json+1 −1看文件
新增ui/scripts/desktop-focus-smoke.mjs+43 −0看文件
新增ui/scripts/desktop-memory-smoke.mjs+40 −0看文件
新增ui/scripts/diagnostics-smoke.mjs+68 −0看文件
修改ui/scripts/remote-input-smoke.mjs+110 −1看文件
修改ui/src/api.js+9 −3看文件
修改ui/src/claude-desktop.jsx+7 −3看文件
新增ui/src/diagnostics.jsx+63 −0看文件
新增ui/src/diagnostics.mjs+49 −0看文件
新增ui/src/diagnostics.test.mjs+33 −0看文件
修改ui/src/main.jsx+11 −1看文件
修改ui/src/remote-input.js+180 −15看文件
修改ui/src/remote-input.test.mjs+77 −2看文件
新增ui/src/resources.jsx+55 −0看文件
修改ui/src/settings.jsx+4 −0看文件
修改ui/src/views.jsx+16 −0看文件
修改www/package-lock.json+2 −2看文件
修改www/package.json+1 −1看文件
| @@ -79,6 +79,8 @@ go test github.com/containers/gvisor-tap-vsock/pkg/services/dns \ | ||
| 79 | 79 | |
| 80 | 80 | 建议使用独立测试配置和非敏感测试项目,避免将开发验证写入日常环境。启动前的 Git 保护检查属于主机状态:单独指定 Cage 配置目录不会隔离全局 Git 设置,测试修改路径时应使用隔离的测试用户目录。应用必须先解释影响,用户明确确认后才将 `safe.bareRepository` 设置为 `explicit`,并在复检通过后启动环境;读取状态不得修改 Git 配置。真实网络验证应区分代理连通、环境放行、浏览器访问、Claude 授权与模型请求,不能互相替代。 |
| 81 | 81 | |
| 82 | 新增:修改日志、原生错误捕获或诊断导出时,执行 `go test -race ./internal/diagnostics ./internal/workbench ./internal/managedproxy ./internal/limaembed ./internal/cli`。构建工作台与 `cage` 后,用 `node ui/scripts/diagnostics-smoke.mjs /absolute/path/to/cage` 验证真实后台、界面下载、脱敏 ZIP 和离线导出;Playwright 路径可通过 `CAGE_PLAYWRIGHT_MODULE` 指定。三个平台的原生保存、取消和覆盖行为需要分别实测,客机日志 namespace 需要 Linux/systemd 验证。 | |
| 83 | 新增: | |
| 82 | 84 | ## 开发诊断 |
| 83 | 85 | |
| 84 | 86 | 配置与状态默认在 `~/.claude-cage/`。`CLAUDE_CAGE_CONFIG` 可以指向另一份私有配置,其父目录拥有独立状态。配置文件权限为 `0600`;不要把该目录作为共享项目或提交到 Git。 |
| @@ -1 +1 @@ | ||
| 1 | 删除:0.1.3-alpha.2 | |
| 1 | 新增:0.1.4-alpha | |
| @@ -15,10 +15,16 @@ import ( | ||
| 15 | 15 | "github.com/sylvinus/agent-vm/internal/appupdate" |
| 16 | 16 | "github.com/sylvinus/agent-vm/internal/cage" |
| 17 | 17 | "github.com/sylvinus/agent-vm/internal/cli" |
| 18 | 新增: "github.com/sylvinus/agent-vm/internal/diagnostics" | |
| 18 | 19 | "github.com/sylvinus/agent-vm/internal/host" |
| 19 | 20 | "github.com/sylvinus/agent-vm/internal/limaembed" |
| 20 | 21 | "github.com/sylvinus/agent-vm/internal/managedproxy" |
| 21 | 22 | "github.com/sylvinus/agent-vm/internal/workbench" |
| 23 | 新增: "io" | |
| 24 | 新增: "os/signal" | |
| 25 | 新增: "runtime/debug" | |
| 26 | 新增: "sync" | |
| 27 | 新增: "syscall" | |
| 22 | 28 | ) |
| 23 | 29 | |
| 24 | 30 | const help = `Claude Cage — local isolated Claude development |
| @@ -39,13 +45,26 @@ cage claude Run Claude Code in the shared environment | ||
| 39 | 45 | cage stop Stop the shared Cage environment |
| 40 | 46 | cage list List this cage profile's VMs |
| 41 | 47 | cage doctor Diagnose the VM |
| 48 | 新增:cage diagnostics --json PATH.zip Export a redacted diagnostic bundle | |
| 42 | 49 | |
| 43 | 50 | Configuration: ~/.claude-cage/config.json (override CLAUDE_CAGE_CONFIG). |
| 44 | 51 | Each configuration directory is an independent cage profile. |
| 45 | 52 | Only explicitly opened project folders are shared. No host Claude credentials are imported. |
| 46 | 53 | ` |
| 47 | 54 | |
| 48 | 删除:func main() { os.Exit(run()) } | |
| 55 | 新增:func main() { | |
| 56 | 新增: defer func() { | |
| 57 | 新增: if failure := recover(); failure != nil { | |
| 58 | 新增: diagnostics.Log("error", "command", fmt.Sprintf("panic: %v\n%s", failure, debug.Stack())) | |
| 59 | 新增: panic(failure) | |
| 60 | 新增: } | |
| 61 | 新增: }() | |
| 62 | 新增: code := run() | |
| 63 | 新增: if code != 0 { | |
| 64 | 新增: diagnostics.Log("error", "command", "operation exited unsuccessfully") | |
| 65 | 新增: } | |
| 66 | 新增: os.Exit(code) | |
| 67 | 新增:} | |
| 49 | 68 | func run() int { |
| 50 | 69 | // Apply this before desktop/serve dispatch: the control service and every |
| 51 | 70 | // child process must keep Cage's isolation even when launched from a shell |
| @@ -74,6 +93,42 @@ func run() int { | ||
| 74 | 93 | if err != nil { |
| 75 | 94 | return fail(err) |
| 76 | 95 | } |
| 96 | 新增: store := diagnostics.New(filepath.Dir(path)) | |
| 97 | 新增: diagnostics.SetDefault(store) | |
| 98 | 新增: if args[0] == "diagnostic-event" { | |
| 99 | 新增: var event struct { | |
| 100 | 新增: Source string `json:"source"` | |
| 101 | 新增: Message string `json:"message"` | |
| 102 | 新增: } | |
| 103 | 新增: if json.NewDecoder(io.LimitReader(os.Stdin, 32<<10)).Decode(&event) != nil { | |
| 104 | 新增: return 2 | |
| 105 | 新增: } | |
| 106 | 新增: if event.Source != "native" { | |
| 107 | 新增: return 2 | |
| 108 | 新增: } | |
| 109 | 新增: if err := store.Record("error", event.Source, event.Message); err != nil { | |
| 110 | 新增: return 1 | |
| 111 | 新增: } | |
| 112 | 新增: return 0 | |
| 113 | 新增: } | |
| 114 | 新增: if args[0] == "diagnostics" { | |
| 115 | 新增: if len(args) != 3 || args[1] != "--json" { | |
| 116 | 新增: return fail(fmt.Errorf("diagnostics --json /absolute/path.zip")) | |
| 117 | 新增: } | |
| 118 | 新增: if err := workbench.ExportDiagnostics(path, args[2]); err != nil { | |
| 119 | 新增: diagnostics.Log("error", "command", err.Error()) | |
| 120 | 新增: _ = json.NewEncoder(os.Stdout).Encode(map[string]string{"status": "error", "message": err.Error()}) | |
| 121 | 新增: return 1 | |
| 122 | 新增: } | |
| 123 | 新增: _ = json.NewEncoder(os.Stdout).Encode(map[string]string{"status": "ok"}) | |
| 124 | 新增: return 0 | |
| 125 | 新增: } | |
| 126 | 新增: if args[0] == "log-relay" { | |
| 127 | 新增: if len(args) != 2 { | |
| 128 | 新增: return 2 | |
| 129 | 新增: } | |
| 130 | 新增: return relay(path, args[1]) | |
| 131 | 新增: } | |
| 77 | 132 | if args[0] == "app-update" { |
| 78 | 133 | return appupdate.Run(path, args[1:], os.Stdout) |
| 79 | 134 | } |
| @@ -83,6 +138,7 @@ func run() int { | ||
| 83 | 138 | } |
| 84 | 139 | result, err := workbench.UploadHostFiles(path, args[2], args[3], args[4:]) |
| 85 | 140 | if err != nil { |
| 141 | 新增: diagnostics.Log("error", "command", err.Error()) | |
| 86 | 142 | _ = json.NewEncoder(os.Stdout).Encode(map[string]string{"status": "error", "message": err.Error()}) |
| 87 | 143 | return 1 |
| 88 | 144 | } |
| @@ -99,6 +155,7 @@ func run() int { | ||
| 99 | 155 | } |
| 100 | 156 | result, err := workbench.BrowserFile(path, args[2], args[3], destination) |
| 101 | 157 | if err != nil { |
| 158 | 新增: diagnostics.Log("error", "command", err.Error()) | |
| 102 | 159 | _ = json.NewEncoder(os.Stdout).Encode(map[string]string{"status": "error", "message": err.Error()}) |
| 103 | 160 | return 1 |
| 104 | 161 | } |
| @@ -129,6 +186,7 @@ func run() int { | ||
| 129 | 186 | entry, err := workbench.Desktop(path, options) |
| 130 | 187 | if err != nil { |
| 131 | 188 | if returnJSON { |
| 189 | 新增: diagnostics.Log("error", "command", err.Error()) | |
| 132 | 190 | _ = json.NewEncoder(os.Stdout).Encode(map[string]string{"status": "error", "message": err.Error()}) |
| 133 | 191 | return 1 |
| 134 | 192 | } |
| @@ -163,6 +221,7 @@ func run() int { | ||
| 163 | 221 | result, err := workbench.PrepareUpdate(path, stop) |
| 164 | 222 | if err != nil { |
| 165 | 223 | if returnJSON { |
| 224 | 新增: diagnostics.Log("error", "command", err.Error()) | |
| 166 | 225 | _ = json.NewEncoder(os.Stdout).Encode(map[string]string{"status": "error", "message": err.Error()}) |
| 167 | 226 | return 1 |
| 168 | 227 | } |
| @@ -275,7 +334,8 @@ func run() int { | ||
| 275 | 334 | if err = os.WriteFile(filepath.Join(state, "setup.sh"), []byte(cage.GuestSetup), 0600); err != nil { |
| 276 | 335 | return fail(err) |
| 277 | 336 | } |
| 278 | 删除: args = append([]string{"setup", "--memory", "4", "--cpus", "2", "--disk", "24", "--preinstall=node,python,chromium,claude,code-server"}, args[1:]...) | |
| 337 | 新增: memory, cpus := cage.ResourceLimits() | |
| 338 | 新增: args = append([]string{"setup", "--memory", fmt.Sprint(memory), "--cpus", fmt.Sprint(cpus), "--disk", "24", "--preinstall=node,python,chromium,claude,code-server"}, args[1:]...) | |
| 279 | 339 | } |
| 280 | 340 | if args[0] == "up" || args[0] == "login" { |
| 281 | 341 | result := cli.Main([]string{"run", "true"}, cli.Stdio()) |
| @@ -317,7 +377,11 @@ func runGuestServiceStart(script string, stdio cli.IO, invoke func([]string, cli | ||
| 317 | 377 | return invoke([]string{"run", "bash", "-s"}, stdio) |
| 318 | 378 | } |
| 319 | 379 | |
| 320 | 删除:func fail(err error) int { fmt.Fprintln(os.Stderr, strings.TrimSpace(err.Error())); return 1 } | |
| 380 | 新增:func fail(err error) int { | |
| 381 | 新增: diagnostics.Log("error", "command", err.Error()) | |
| 382 | 新增: fmt.Fprintln(os.Stderr, strings.TrimSpace(err.Error())) | |
| 383 | 新增: return 1 | |
| 384 | 新增:} | |
| 321 | 385 | |
| 322 | 386 | func openWorkbench(address string) error { |
| 323 | 387 | if runtime.GOOS == "windows" { |
| @@ -329,3 +393,61 @@ func openWorkbench(address string) error { | ||
| 329 | 393 | } |
| 330 | 394 | return exec.Command(command, address).Run() |
| 331 | 395 | } |
| 396 | 新增: | |
| 397 | 新增:// Relay owns stdout/stderr capture outside the child so a Go runtime panic or | |
| 398 | 新增:// abrupt child exit is recorded without ever persisting raw output. | |
| 399 | 新增:func relay(configPath, kind string) int { | |
| 400 | 新增: var cmd *exec.Cmd | |
| 401 | 新增: source := "controller" | |
| 402 | 新增: if kind == "controller" { | |
| 403 | 新增: exe, err := os.Executable() | |
| 404 | 新增: if err != nil { | |
| 405 | 新增: return fail(err) | |
| 406 | 新增: } | |
| 407 | 新增: cmd = exec.Command(exe, "serve") | |
| 408 | 新增: } else if kind == "proxy" { | |
| 409 | 新增: core, err := managedproxy.CorePath() | |
| 410 | 新增: if err != nil { | |
| 411 | 新增: return fail(err) | |
| 412 | 新增: } | |
| 413 | 新增: profile := filepath.Dir(configPath) | |
| 414 | 新增: cmd = exec.Command(core, "-d", managedproxy.Dir(profile), "-f", filepath.Join(managedproxy.Dir(profile), "config.yaml")) | |
| 415 | 新增: source = "proxy" | |
| 416 | 新增: } else { | |
| 417 | 新增: return 2 | |
| 418 | 新增: } | |
| 419 | 新增: cmd.Env = append(os.Environ(), cage.ConfigEnv+"="+configPath) | |
| 420 | 新增: store := diagnostics.New(filepath.Dir(configPath)) | |
| 421 | 新增: out := store.Stream(source, "info") | |
| 422 | 新增: defer out.Close() | |
| 423 | 新增: stderr := store.Stream(source, "error") | |
| 424 | 新增: defer stderr.Close() | |
| 425 | 新增: cmd.Stdout, cmd.Stderr = out, stderr | |
| 426 | 新增: if err := cmd.Start(); err != nil { | |
| 427 | 新增: return fail(err) | |
| 428 | 新增: } | |
| 429 | 新增: diagnostics.Log("info", source, "process started") | |
| 430 | 新增: signals := make(chan os.Signal, 1) | |
| 431 | 新增: signal.Notify(signals, os.Interrupt, syscall.SIGTERM) | |
| 432 | 新增: defer signal.Stop(signals) | |
| 433 | 新增: done := make(chan struct{}) | |
| 434 | 新增: var wg sync.WaitGroup | |
| 435 | 新增: wg.Add(1) | |
| 436 | 新增: go func() { | |
| 437 | 新增: defer wg.Done() | |
| 438 | 新增: select { | |
| 439 | 新增: case sig := <-signals: | |
| 440 | 新增: _ = cmd.Process.Signal(sig) | |
| 441 | 新增: case <-done: | |
| 442 | 新增: } | |
| 443 | 新增: }() | |
| 444 | 新增: err := cmd.Wait() | |
| 445 | 新增: close(done) | |
| 446 | 新增: wg.Wait() | |
| 447 | 新增: if err != nil { | |
| 448 | 新增: diagnostics.Log("error", source, "process exited: "+err.Error()) | |
| 449 | 新增: return 1 | |
| 450 | 新增: } | |
| 451 | 新增: diagnostics.Log("info", source, "process exited normally") | |
| 452 | 新增: return 0 | |
| 453 | 新增:} | |
| @@ -2,10 +2,22 @@ import Cocoa | ||
| 2 | 2 | import WebKit |
| 3 | 3 | import UniformTypeIdentifiers |
| 4 | 4 | |
| 5 | 新增:enum CageDiagnostics { | |
| 6 | 新增: static func record(_ message: String) { | |
| 7 | 新增: guard let executable = Bundle.main.url(forResource: "cage", withExtension: nil), | |
| 8 | 新增: let data = try? JSONSerialization.data(withJSONObject: ["source":"native", "message":String(message.prefix(4096))]) else { return } | |
| 9 | 新增: let process = Process(); process.executableURL = executable; process.arguments = ["diagnostic-event"] | |
| 10 | 新增: let input = Pipe(); process.standardInput = input | |
| 11 | 新增: process.standardOutput = FileHandle.nullDevice; process.standardError = FileHandle.nullDevice | |
| 12 | 新增: do { try process.run(); try input.fileHandleForWriting.write(contentsOf: data); try input.fileHandleForWriting.close() } catch { } | |
| 13 | 新增: } | |
| 14 | 新增:} | |
| 15 | 新增: | |
| 5 | 16 | @main |
| 6 | 17 | final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNavigationDelegate, WKUIDelegate, WKScriptMessageHandlerWithReply { |
| 7 | 18 | private var window: NSWindow! |
| 8 | 19 | private var webView: WKWebView! |
| 20 | 新增: private var nativeInput: CageNativeInput! | |
| 9 | 21 | private var accountDeviceBusy = false |
| 10 | 22 | private var expectedPort = 0 |
| 11 | 23 | private var allowQuit = false |
| @@ -27,6 +39,7 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga | ||
| 27 | 39 | } |
| 28 | 40 | |
| 29 | 41 | static func main() { |
| 42 | 新增: NSSetUncaughtExceptionHandler { exception in CageDiagnostics.record("Uncaught native exception: \(exception.name.rawValue): \(exception.reason ?? "")\n\(exception.callStackSymbols.joined(separator: "\n"))") } | |
| 30 | 43 | let app = NSApplication.shared |
| 31 | 44 | let delegate = CageApp() |
| 32 | 45 | app.delegate = delegate |
| @@ -50,6 +63,7 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga | ||
| 50 | 63 | let config = WKWebViewConfiguration() |
| 51 | 64 | config.websiteDataStore = .default() |
| 52 | 65 | config.userContentController.addScriptMessageHandler(self, contentWorld: .page, name: "cage") |
| 66 | 新增: config.userContentController.addUserScript(WKUserScript(source: "window.cageNativeIMEAvailable = true;", injectionTime: .atDocumentStart, forMainFrameOnly: true)) | |
| 53 | 67 | webView = WKWebView(frame: .zero, configuration: config) |
| 54 | 68 | webView.navigationDelegate = self |
| 55 | 69 | webView.uiDelegate = self |
| @@ -65,6 +79,9 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga | ||
| 65 | 79 | backdrop.state = .followsWindowActiveState |
| 66 | 80 | content.addSubview(backdrop) |
| 67 | 81 | content.addSubview(webView) |
| 82 | 新增: nativeInput = CageNativeInput(frame: .zero) | |
| 83 | 新增: nativeInput.configure(web: webView) | |
| 84 | 新增: content.addSubview(nativeInput) | |
| 68 | 85 | NSLayoutConstraint.activate([webView.leadingAnchor.constraint(equalTo: content.leadingAnchor), webView.trailingAnchor.constraint(equalTo: content.trailingAnchor), webView.topAnchor.constraint(equalTo: content.topAnchor), webView.bottomAnchor.constraint(equalTo: content.bottomAnchor)]) |
| 69 | 86 | loading = NSTextField(labelWithString: "正在启动 Cage 工作台…") |
| 70 | 87 | loading.font = NSFont.systemFont(ofSize: 16, weight: .medium) |
| @@ -92,6 +109,7 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga | ||
| 92 | 109 | NSLayoutConstraint.activate([existingEnvironmentButton.centerXAnchor.constraint(equalTo: content.centerXAnchor), existingEnvironmentButton.topAnchor.constraint(equalTo: retry.bottomAnchor, constant: 10), completeUpdateButton.centerXAnchor.constraint(equalTo: content.centerXAnchor), completeUpdateButton.topAnchor.constraint(equalTo: existingEnvironmentButton.bottomAnchor, constant: 10)]) |
| 93 | 110 | applyAppearance(appearance) |
| 94 | 111 | appUpdater = CageAppUpdater(bundleURL: Bundle.main.bundleURL, onChange: { [weak self] state in |
| 112 | 新增: if state["phase"] as? String == "failed" { CageDiagnostics.record("App update failed: " + (state["message"] as? String ?? "unknown error")) } | |
| 95 | 113 | guard let data = try? JSONSerialization.data(withJSONObject: state), let json = String(data: data, encoding: .utf8) else { return } |
| 96 | 114 | self?.webView.evaluateJavaScript("window.dispatchEvent(new CustomEvent('cage-app-update',{detail:\(json)}));", completionHandler: nil) |
| 97 | 115 | }, quit: { [weak self] in self?.allowQuit = true; NSApp.terminate(nil) }, reconnect: { [weak self] in self?.bootstrap() }) |
| @@ -241,7 +259,7 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga | ||
| 241 | 259 | let data = output.fileHandleForReading.readDataToEndOfFile(); process.waitUntilExit() |
| 242 | 260 | guard data.count <= 65536, let result = try JSONSerialization.jsonObject(with: data) as? [String:Any] else { throw CageUpdateError("文件操作未返回有效结果") } |
| 243 | 261 | DispatchQueue.main.async { reply(process.terminationStatus == 0 ? result : nil, process.terminationStatus == 0 ? nil : result["message"] as? String ?? "文件操作失败") } |
| 244 | 删除: } catch { DispatchQueue.main.async { reply(nil,error.localizedDescription) } } | |
| 262 | 新增: } catch { CageDiagnostics.record(error.localizedDescription); DispatchQueue.main.async { reply(nil,error.localizedDescription) } } | |
| 245 | 263 | } |
| 246 | 264 | } |
| 247 | 265 | private func rememberFiles(_ urls: [URL]) throws -> [String: Any] { |
| @@ -259,7 +277,7 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga | ||
| 259 | 277 | fileSelections[id] = (urls.map(\.path), now.addingTimeInterval(600)) |
| 260 | 278 | return ["fileSelection": id, "count": urls.count] |
| 261 | 279 | } |
| 262 | 删除: private func showError(_ text: String) { loading.stringValue = text; loading.isHidden = false; retry.isHidden = false; webView.isHidden = true } | |
| 280 | 新增: private func showError(_ text: String) { CageDiagnostics.record(text); loading.stringValue = text; loading.isHidden = false; retry.isHidden = false; webView.isHidden = true } | |
| 263 | 281 | private func applyAppearance(_ value: [String:Any]) { |
| 264 | 282 | let mode = value["mode"] as? String ?? "system" |
| 265 | 283 | NSApp.appearance = mode == "system" ? nil : NSAppearance(named: mode == "dark" ? .darkAqua : .aqua) |
| @@ -273,7 +291,7 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga | ||
| 273 | 291 | } |
| 274 | 292 | func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { loading.isHidden = true; retry.isHidden = true; completeUpdateButton.isHidden = true; existingEnvironmentButton.isHidden = true; webView.isHidden = false; window.makeFirstResponder(webView); publishWindowVisibility() } |
| 275 | 293 | func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { showError("无法连接工作台。后台任务不会因此自动结束。") } |
| 276 | 删除: func webViewWebContentProcessDidTerminate(_ webView: WKWebView) { bootstrap() } | |
| 294 | 新增: func webViewWebContentProcessDidTerminate(_ webView: WKWebView) { CageDiagnostics.record("WebKit content process terminated"); bootstrap() } | |
| 277 | 295 | func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { |
| 278 | 296 | guard let url = navigationAction.request.url, url.scheme == "http", url.host == "localhost", url.port == expectedPort else { decisionHandler(.cancel); return } |
| 279 | 297 | decisionHandler(.allow) |
| @@ -282,6 +300,8 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga | ||
| 282 | 300 | let origin = message.frameInfo.securityOrigin |
| 283 | 301 | guard message.frameInfo.isMainFrame, origin.protocol == "http", origin.host == "localhost", origin.port == expectedPort, let body = message.body as? [String:Any], let action = body["action"] as? String else { replyHandler(nil,"请求来源无效"); return } |
| 284 | 302 | switch action { |
| 303 | 新增: case "remoteInput": | |
| 304 | 新增: replyHandler(nativeInput.handle(body), nil) | |
| 285 | 305 | case "accountDevice": |
| 286 | 306 | guard !controllerNeedsUpdate, !accountDeviceBusy, |
| 287 | 307 | let operation = body["operation"] as? String, ["status", "enable", "disable", "unlock"].contains(operation) else { replyHandler(nil,"账户操作正在进行或后台需要更新,请稍后重试"); return } |
| @@ -301,6 +321,15 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga | ||
| 301 | 321 | } |
| 302 | 322 | } |
| 303 | 323 | } |
| 324 | 新增: case "exportDiagnostics": | |
| 325 | 新增: guard !nativeFilePanelOpen else { replyHandler(nil,"请先完成当前文件窗口"); return } | |
| 326 | 新增: let panel = NSSavePanel(); panel.title = "导出诊断包"; panel.nameFieldStringValue = "cage-diagnostics.zip" | |
| 327 | 新增: panel.allowedContentTypes = [.zip]; nativeFilePanelOpen = true | |
| 328 | 新增: panel.beginSheetModal(for: window) { response in | |
| 329 | 新增: self.nativeFilePanelOpen = false | |
| 330 | 新增: guard response == .OK, let url = panel.url else { replyHandler(["canceled":true],nil); return } | |
| 331 | 新增: self.fileCommand(["diagnostics", "--json", url.path], reply: replyHandler) | |
| 332 | 新增: } | |
| 304 | 333 | case "workbenchReady": |
| 305 | 334 | guard !controllerNeedsUpdate else { replyHandler(nil,"后台版本尚未同步,更新未完成"); return } |
| 306 | 335 | appUpdater?.markLaunchReady() |
| @@ -0,0 +1,174 @@ | ||
| 1 | 新增:import AppKit | |
| 2 | 新增:import WebKit | |
| 3 | 新增: | |
| 4 | 新增:// Owns only the host's marked text. The guest owns the document and selection. | |
| 5 | 新增:// The invisible NSView supplies the real remote caret to the input manager. | |
| 6 | 新增:final class CageNativeInput: NSView, NSTextInputClient { | |
| 7 | 新增: weak var web: WKWebView? | |
| 8 | 新增: var owner = "" | |
| 9 | 新增: private var marked = NSAttributedString(string: "") | |
| 10 | 新增: private var selection = NSRange(location: 0, length: 0) | |
| 11 | 新增: private var caret = NSRect.zero | |
| 12 | 新增: private var commandEvent: NSEvent? | |
| 13 | 新增: private var discarding = false | |
| 14 | 新增: private lazy var nativeContext = NSTextInputContext(client: self) | |
| 15 | 新增: | |
| 16 | 新增: override var acceptsFirstResponder: Bool { true } | |
| 17 | 新增: override var inputContext: NSTextInputContext? { nativeContext } | |
| 18 | 新增: override func hitTest(_ point: NSPoint) -> NSView? { nil } | |
| 19 | 新增: | |
| 20 | 新增: func configure(web: WKWebView) { self.web = web } | |
| 21 | 新增: | |
| 22 | 新增: func handle(_ body: [String: Any]) -> Bool { | |
| 23 | 新增: guard let operation = body["operation"] as? String, | |
| 24 | 新增: let requestedOwner = body["owner"] as? String, | |
| 25 | 新增: UUID(uuidString: requestedOwner) != nil else { return false } | |
| 26 | 新增: if operation == "activate" { | |
| 27 | 新增: if owner != requestedOwner { cancel(); owner = requestedOwner } | |
| 28 | 新增: updateCaret(body) | |
| 29 | 新增: return window?.makeFirstResponder(self) == true | |
| 30 | 新增: } | |
| 31 | 新增: guard owner == requestedOwner else { return false } | |
| 32 | 新增: switch operation { | |
| 33 | 新增: case "caret": updateCaret(body) | |
| 34 | 新增: case "cancel": cancel() | |
| 35 | 新增: case "deactivate": | |
| 36 | 新增: cancel() | |
| 37 | 新增: owner = "" | |
| 38 | 新增: if window?.firstResponder === self, let web { window?.makeFirstResponder(web) } | |
| 39 | 新增: default: return false | |
| 40 | 新增: } | |
| 41 | 新增: return true | |
| 42 | 新增: } | |
| 43 | 新增: | |
| 44 | 新增: private func updateCaret(_ body: [String: Any]) { | |
| 45 | 新增: guard let web, let x = body["x"] as? Double, let y = body["y"] as? Double, | |
| 46 | 新增: let height = body["height"] as? Double, | |
| 47 | 新增: x.isFinite, y.isFinite, height.isFinite, height > 0 else { return } | |
| 48 | 新增: // CSS starts at the top. WKWebView is normally flipped already; | |
| 49 | 新增: // converting its rect to window/screen coordinates performs that | |
| 50 | 新增: // inversion. Only unflipped views need an explicit local inversion. | |
| 51 | 新增: let localY = web.isFlipped ? y : web.bounds.height - y - height | |
| 52 | 新增: caret = web.convert(NSRect(x: x, y: localY, | |
| 53 | 新增: width: 0, height: height), to: nil) | |
| 54 | 新增: inputContext?.invalidateCharacterCoordinates() | |
| 55 | 新增: } | |
| 56 | 新增: | |
| 57 | 新增: private func emit(_ kind: String, _ values: [String: Any] = [:]) { | |
| 58 | 新增: guard !owner.isEmpty, let web else { return } | |
| 59 | 新增: var event = values | |
| 60 | 新增: event["owner"] = owner | |
| 61 | 新增: event["kind"] = kind | |
| 62 | 新增: guard let data = try? JSONSerialization.data(withJSONObject: event), | |
| 63 | 新增: let json = String(data: data, encoding: .utf8) else { return } | |
| 64 | 新增: web.evaluateJavaScript("window.dispatchEvent(new CustomEvent('cage-native-input',{detail:\(json)}));", completionHandler: nil) | |
| 65 | 新增: } | |
| 66 | 新增: | |
| 67 | 新增: private func clear() { | |
| 68 | 新增: marked = NSAttributedString(string: "") | |
| 69 | 新增: selection = NSRange(location: 0, length: 0) | |
| 70 | 新增: } | |
| 71 | 新增: | |
| 72 | 新增: private func cancel() { | |
| 73 | 新增: if hasMarkedText() { emit("compositionend", ["text": ""]) } | |
| 74 | 新增: clear() | |
| 75 | 新增: discarding = true | |
| 76 | 新增: inputContext?.discardMarkedText() | |
| 77 | 新增: discarding = false | |
| 78 | 新增: } | |
| 79 | 新增: | |
| 80 | 新增: override func resignFirstResponder() -> Bool { | |
| 81 | 新增: cancel() | |
| 82 | 新增: emit("deactivated") | |
| 83 | 新增: owner = "" | |
| 84 | 新增: return super.resignFirstResponder() | |
| 85 | 新增: } | |
| 86 | 新增: | |
| 87 | 新增: override func keyDown(with event: NSEvent) { | |
| 88 | 新增: if event.modifierFlags.contains(.command) { | |
| 89 | 新增: sendKey(event, down: true) | |
| 90 | 新增: return | |
| 91 | 新增: } | |
| 92 | 新增: commandEvent = event | |
| 93 | 新增: if inputContext?.handleEvent(event) != true { interpretKeyEvents([event]) } | |
| 94 | 新增: commandEvent = nil | |
| 95 | 新增: } | |
| 96 | 新增: override func keyUp(with event: NSEvent) { sendKey(event, down: false) } | |
| 97 | 新增: override func flagsChanged(with event: NSEvent) { | |
| 98 | 新增: let flags: [UInt16: NSEvent.ModifierFlags] = [54: .command, 55: .command, | |
| 99 | 新增: 56: .shift, 60: .shift, 58: .option, 61: .option, 59: .control, 62: .control] | |
| 100 | 新增: if let flag = flags[event.keyCode] { sendKey(event, down: event.modifierFlags.contains(flag)) } | |
| 101 | 新增: } | |
| 102 | 新增: | |
| 103 | 新增: private func sendKey(_ event: NSEvent, down: Bool, text: String? = nil) { | |
| 104 | 新增: let special: [UInt16: String] = [36:"Enter",48:"Tab",49:" ",51:"Backspace", | |
| 105 | 新增: 53:"Escape",54:"Meta",55:"Meta",56:"Shift",57:"CapsLock",58:"Alt",59:"Control", | |
| 106 | 新增: 60:"Shift",61:"Alt",62:"Control",115:"Home",116:"PageUp",117:"Delete", | |
| 107 | 新增: 119:"End",121:"PageDown",123:"ArrowLeft",124:"ArrowRight",125:"ArrowDown",126:"ArrowUp"] | |
| 108 | 新增: let letters: [UInt16: String] = [0:"A",1:"S",2:"D",3:"F",4:"H",5:"G",6:"Z",7:"X",8:"C",9:"V",11:"B",12:"Q",13:"W",14:"E",15:"R",16:"Y",17:"T",31:"O",32:"U",34:"I",35:"P",37:"L",38:"J",40:"K",45:"N",46:"M"] | |
| 109 | 新增: let codes: [UInt16: String] = [36:"Enter",48:"Tab",49:"Space",51:"Backspace",53:"Escape", | |
| 110 | 新增: 54:"MetaRight",55:"MetaLeft",56:"ShiftLeft",57:"CapsLock",58:"AltLeft",59:"ControlLeft", | |
| 111 | 新增: 60:"ShiftRight",61:"AltRight",62:"ControlRight",115:"Home",116:"PageUp",117:"Delete", | |
| 112 | 新增: 119:"End",121:"PageDown",123:"ArrowLeft",124:"ArrowRight",125:"ArrowDown",126:"ArrowUp", | |
| 113 | 新增: 18:"Digit1",19:"Digit2",20:"Digit3",21:"Digit4",22:"Digit6",23:"Digit5",25:"Digit9",26:"Digit7",28:"Digit8",29:"Digit0", | |
| 114 | 新增: 24:"Equal",27:"Minus",30:"BracketRight",33:"BracketLeft",39:"Quote",41:"Semicolon",42:"Backslash",43:"Comma",44:"Slash",47:"Period",50:"Backquote"] | |
| 115 | 新增: let key = text ?? special[event.keyCode] ?? event.charactersIgnoringModifiers ?? "Unidentified" | |
| 116 | 新增: let code = letters[event.keyCode].map { "Key" + $0 } ?? codes[event.keyCode] ?? "Unidentified" | |
| 117 | 新增: emit(down ? "keydown" : "keyup", ["key": key, "code": code, | |
| 118 | 新增: "metaKey":event.modifierFlags.contains(.command),"ctrlKey":event.modifierFlags.contains(.control), | |
| 119 | 新增: "altKey":event.modifierFlags.contains(.option),"shiftKey":event.modifierFlags.contains(.shift),"repeat":event.isARepeat, | |
| 120 | 新增: "modifierCapsLock":event.modifierFlags.contains(.capsLock),"textKey":text != nil]) | |
| 121 | 新增: } | |
| 122 | 新增: | |
| 123 | 新增: func hasMarkedText() -> Bool { marked.length > 0 } | |
| 124 | 新增: func markedRange() -> NSRange { hasMarkedText() ? NSRange(location: 0, length: marked.length) : NSRange(location: NSNotFound, length: 0) } | |
| 125 | 新增: func selectedRange() -> NSRange { selection } | |
| 126 | 新增: func validAttributesForMarkedText() -> [NSAttributedString.Key] { [.underlineStyle, .markedClauseSegment, .backgroundColor] } | |
| 127 | 新增: | |
| 128 | 新增: func setMarkedText(_ value: Any, selectedRange range: NSRange, replacementRange: NSRange) { | |
| 129 | 新增: guard !discarding else { return } | |
| 130 | 新增: let next = (value as? NSAttributedString) ?? NSAttributedString(string: value as? String ?? "") | |
| 131 | 新增: if next.length == 0 { | |
| 132 | 新增: if hasMarkedText() { clear(); emit("compositionend", ["text":""]) } | |
| 133 | 新增: return | |
| 134 | 新增: } | |
| 135 | 新增: if !hasMarkedText() { emit("compositionstart") } | |
| 136 | 新增: marked = next | |
| 137 | 新增: let start = min(range.location == NSNotFound ? marked.length : range.location, marked.length) | |
| 138 | 新增: selection = NSRange(location: start, length: min(range.length, marked.length - start)) | |
| 139 | 新增: emit("compositionupdate", ["text":marked.string,"selectionStart":selection.location,"selectionEnd":NSMaxRange(selection)]) | |
| 140 | 新增: } | |
| 141 | 新增: func unmarkText() { | |
| 142 | 新增: guard !discarding, hasMarkedText() else { return } | |
| 143 | 新增: let text = marked.string | |
| 144 | 新增: clear() | |
| 145 | 新增: emit("compositionend", ["text":text]) | |
| 146 | 新增: } | |
| 147 | 新增: func insertText(_ value: Any, replacementRange: NSRange) { | |
| 148 | 新增: guard !discarding else { return } | |
| 149 | 新增: let text = (value as? NSAttributedString)?.string ?? value as? String ?? "" | |
| 150 | 新增: let wasMarked = hasMarkedText() | |
| 151 | 新增: clear() | |
| 152 | 新增: if !wasMarked, text.utf16.count == 1, let scalar = text.unicodeScalars.first, | |
| 153 | 新增: scalar.value >= 32, scalar.value <= 126, let event = commandEvent { | |
| 154 | 新增: sendKey(event, down: true, text: text) | |
| 155 | 新增: return | |
| 156 | 新增: } | |
| 157 | 新增: emit(wasMarked ? "compositionend" : "input", ["text":text]) | |
| 158 | 新增: } | |
| 159 | 新增: override func doCommand(by selector: Selector) { | |
| 160 | 新增: if selector == #selector(NSResponder.cancelOperation(_:)), hasMarkedText() { cancel(); return } | |
| 161 | 新增: if let event = commandEvent { sendKey(event, down: true) } | |
| 162 | 新增: } | |
| 163 | 新增: func attributedSubstring(forProposedRange range: NSRange, actualRange: NSRangePointer?) -> NSAttributedString? { | |
| 164 | 新增: guard range.location != NSNotFound, range.location < marked.length else { return nil } | |
| 165 | 新增: let valid = NSIntersectionRange(range, NSRange(location: 0, length: marked.length)) | |
| 166 | 新增: actualRange?.pointee = valid | |
| 167 | 新增: return marked.attributedSubstring(from: valid) | |
| 168 | 新增: } | |
| 169 | 新增: func characterIndex(for point: NSPoint) -> Int { NSNotFound } | |
| 170 | 新增: func firstRect(forCharacterRange range: NSRange, actualRange: NSRangePointer?) -> NSRect { | |
| 171 | 新增: actualRange?.pointee = NSRange(location: selection.location, length: 0) | |
| 172 | 新增: return window?.convertToScreen(caret) ?? .zero | |
| 173 | 新增: } | |
| 174 | 新增:} | |
| @@ -0,0 +1,42 @@ | ||
| 1 | 新增:import AppKit | |
| 2 | 新增:import WebKit | |
| 3 | 新增: | |
| 4 | 新增:@main | |
| 5 | 新增:enum NativeInputTests { | |
| 6 | 新增: static func main() { | |
| 7 | 新增: let app = NSApplication.shared | |
| 8 | 新增: app.setActivationPolicy(.prohibited) | |
| 9 | 新增: let window = NSWindow(contentRect: NSRect(x: 120, y: 180, width: 900, height: 700), | |
| 10 | 新增: styleMask: [.titled, .resizable], backing: .buffered, defer: false) | |
| 11 | 新增: let web = WKWebView(frame: window.contentView!.bounds) | |
| 12 | 新增: window.contentView!.addSubview(web) | |
| 13 | 新增: let input = CageNativeInput(frame: .zero) | |
| 14 | 新增: input.configure(web: web) | |
| 15 | 新增: window.contentView!.addSubview(input) | |
| 16 | 新增: let owner = UUID().uuidString | |
| 17 | 新增: func check(_ x: Double, _ y: Double, _ height: Double) -> NSRect { | |
| 18 | 新增: precondition(input.handle(["operation":"activate", "owner":owner, | |
| 19 | 新增: "x":x, "y":y, "height":height])) | |
| 20 | 新增: let screen = input.firstRect(forCharacterRange: NSRange(location: 0, length: 0), actualRange: nil) | |
| 21 | 新增: let top = window.convertToScreen(web.convert(NSRect(x: x, y: 0, width: 0, height: 0), to: nil)).minY | |
| 22 | 新增: // Expected bounds measured from the real WebView top on screen. | |
| 23 | 新增: precondition(abs(screen.minX - (window.convertToScreen(web.convert(.zero, to:nil)).minX + x)) < 0.5) | |
| 24 | 新增: precondition(abs(screen.maxY - (top - y)) < 0.5, "candidate caret was vertically mirrored") | |
| 25 | 新增: precondition(abs(screen.height - height) < 0.5) | |
| 26 | 新增: return screen | |
| 27 | 新增: } | |
| 28 | 新增: precondition(web.isFlipped, "WKWebView coordinate contract changed") | |
| 29 | 新增: let upper = check(120, 80, 24) | |
| 30 | 新增: let lower = check(340, 580, 32) | |
| 31 | 新增: precondition(lower.minY < upper.minY, "moving the caret down must move candidates down") | |
| 32 | 新增: window.setFrameOrigin(NSPoint(x: 320, y: 280)) | |
| 33 | 新增: let moved = check(340, 580, 32) | |
| 34 | 新增: precondition(abs(moved.minX - lower.minX - 200) < 0.5) | |
| 35 | 新增: precondition(abs(moved.minY - lower.minY - 100) < 0.5) | |
| 36 | 新增: web.setFrameSize(NSSize(width: 1000, height: 800)) | |
| 37 | 新增: _ = check(500, 680, 38) | |
| 38 | 新增: precondition(!input.handle(["operation":"deactivate", "owner":UUID().uuidString])) | |
| 39 | 新增: precondition(input.handle(["operation":"deactivate", "owner":owner])) | |
| 40 | 新增: print("Native input coordinates: top, bottom, window movement, resize, and stale owner checks passed") | |
| 41 | 新增: } | |
| 42 | 新增:} | |
| @@ -8,6 +8,8 @@ | ||
| 8 | 8 | #include <string.h> |
| 9 | 9 | #include <stdlib.h> |
| 10 | 10 | #include <sys/stat.h> |
| 11 | 新增:#include <math.h> | |
| 12 | 新增:#include "native-input.h" | |
| 11 | 13 | |
| 12 | 14 | #ifndef CAGE_VERSION |
| 13 | 15 | #define CAGE_VERSION "development" |
| @@ -60,6 +62,28 @@ static char *quote(const char *value) { | ||
| 60 | 62 | json_node_free(node); |
| 61 | 63 | return result; |
| 62 | 64 | } |
| 65 | 新增:static void diagnostic_sent(GObject *source, GAsyncResult *result, gpointer data) { | |
| 66 | 新增: (void)data; | |
| 67 | 新增: g_subprocess_communicate_utf8_finish(G_SUBPROCESS(source), result, NULL, NULL, NULL); | |
| 68 | 新增:} | |
| 69 | 新增:static void diagnostic_event(const char *message) { | |
| 70 | 新增: if (!app.backend || !app.profile) return; | |
| 71 | 新增: GSubprocessLauncher *launcher = g_subprocess_launcher_new(G_SUBPROCESS_FLAGS_STDIN_PIPE | G_SUBPROCESS_FLAGS_STDOUT_SILENCE | G_SUBPROCESS_FLAGS_STDERR_SILENCE); | |
| 72 | 新增: g_subprocess_launcher_setenv(launcher, "CLAUDE_CAGE_CONFIG", app.profile, TRUE); | |
| 73 | 新增: GSubprocess *process = g_subprocess_launcher_spawn(launcher, NULL, app.backend, "diagnostic-event", NULL); | |
| 74 | 新增: g_object_unref(launcher); | |
| 75 | 新增: if (!process) return; | |
| 76 | 新增: char *limited = g_utf8_substring(message, 0, MIN(g_utf8_strlen(message, -1), 4096)); | |
| 77 | 新增: char *quoted = quote(limited); | |
| 78 | 新增: char *body = g_strdup_printf("{\"source\":\"native\",\"message\":%s}", quoted); | |
| 79 | 新增: g_subprocess_communicate_utf8_async(process, body, NULL, diagnostic_sent, NULL); | |
| 80 | 新增: g_object_unref(process); g_free(body); g_free(quoted); g_free(limited); | |
| 81 | 新增:} | |
| 82 | 新增:static void diagnostic_glib(const gchar *domain, GLogLevelFlags level, const gchar *message, gpointer data) { | |
| 83 | 新增: (void)data; | |
| 84 | 新增: if (level & (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING)) diagnostic_event(message); | |
| 85 | 新增: g_log_default_handler(domain, level, message, NULL); | |
| 86 | 新增:} | |
| 63 | 87 | static gboolean valid_workbench(const char *raw, int expected_port, gboolean entry) { |
| 64 | 88 | if (!raw) return FALSE; |
| 65 | 89 | GUri *uri = g_uri_parse(raw, G_URI_FLAGS_NONE, NULL); |
| @@ -111,13 +135,13 @@ static void command_finished(GObject *source, GAsyncResult *result, gpointer dat | ||
| 111 | 135 | if (g_subprocess_communicate_utf8_finish(G_SUBPROCESS(source), result, &output, NULL, &error)) { |
| 112 | 136 | if (!output || strlen(output) > 65536 || !json_parser_load_from_data(parser, output, -1, NULL) || |
| 113 | 137 | !JSON_NODE_HOLDS_OBJECT(json_parser_get_root(parser))) { |
| 114 | 删除: g_set_error_literal(&error, G_IO_ERROR, G_IO_ERROR_INVALID_DATA, "Cage 后台未返回有效状态,请查看私有配置中的 control.log。"); | |
| 138 | 新增: g_set_error_literal(&error, G_IO_ERROR, G_IO_ERROR_INVALID_DATA, "Cage 后台未返回有效状态,请查看私有配置中的 logs/。"); | |
| 115 | 139 | } else { |
| 116 | 140 | object = json_node_get_object(json_parser_get_root(parser)); |
| 117 | 141 | if (!g_subprocess_get_successful(command->process)) { |
| 118 | 142 | const char *message = text_member(object, "message"); |
| 119 | 143 | g_set_error_literal(&error, G_IO_ERROR, G_IO_ERROR_FAILED, |
| 120 | 删除: *message ? message : "Cage 后台操作失败,请查看 control.log。"); | |
| 144 | 新增: *message ? message : "Cage 后台操作失败,请查看 logs/。"); | |
| 121 | 145 | } |
| 122 | 146 | } |
| 123 | 147 | } |
| @@ -188,6 +212,7 @@ static gboolean quit_idle(gpointer data) { | ||
| 188 | 212 | return G_SOURCE_REMOVE; |
| 189 | 213 | } |
| 190 | 214 | static void show_error(const char *message) { |
| 215 | 新增: diagnostic_event(message); | |
| 191 | 216 | gtk_label_set_text(GTK_LABEL(app.status), message); |
| 192 | 217 | gtk_stack_set_visible_child_name(GTK_STACK(app.stack), "status"); |
| 193 | 218 | gtk_widget_show(app.retry); |
| @@ -219,8 +244,9 @@ static char *choose_file(GtkFileChooserAction kind, const char *title, const cha | ||
| 219 | 244 | } |
| 220 | 245 | if (kind != GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER) { |
| 221 | 246 | GtkFileFilter *filter = gtk_file_filter_new(); |
| 222 | 删除: gtk_file_filter_set_name(filter, "Cage 主题 (*.json)"); | |
| 223 | 删除: gtk_file_filter_add_pattern(filter, "*.json"); | |
| 247 | 新增: gboolean diagnostic = filename && g_str_has_suffix(filename, ".zip"); | |
| 248 | 新增: gtk_file_filter_set_name(filter, diagnostic ? "诊断包 (*.zip)" : "Cage 主题 (*.json)"); | |
| 249 | 新增: gtk_file_filter_add_pattern(filter, diagnostic ? "*.zip" : "*.json"); | |
| 224 | 250 | gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(dialog), filter); |
| 225 | 251 | } |
| 226 | 252 | char *path = gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT |
| @@ -494,7 +520,20 @@ static gboolean bridge_received(WebKitUserContentManager *manager, JSCValue *val | ||
| 494 | 520 | JsonObject *request = json_node_get_object(request_node); |
| 495 | 521 | const char *name = text_member(request, "action"); |
| 496 | 522 | JSCContext *context = jsc_value_get_context(value); |
| 497 | 删除: if (!strcmp(name, "workbenchReady")) { | |
| 523 | 新增: if (!strcmp(name, "remoteInput")) { | |
| 524 | 新增: reply_json(reply, context, input_handle(request) ? "true" : "false"); | |
| 525 | 新增: } else if (!strcmp(name, "exportDiagnostics")) { | |
| 526 | 新增: if (app.picker_open) reply_error(reply, "请先完成当前文件窗口。"); | |
| 527 | 新增: else { | |
| 528 | 新增: char *path = choose_file(GTK_FILE_CHOOSER_ACTION_SAVE, "导出诊断包", "cage-diagnostics.zip"); | |
| 529 | 新增: if (!path) reply_json(reply, context, "{\"canceled\":true}"); | |
| 530 | 新增: else { | |
| 531 | 新增: const char *args[] = {app.backend, "diagnostics", "--json", path, NULL}; | |
| 532 | 新增: backend_arguments(args, 60, browser_file_finished, pending_reply(reply, context)); | |
| 533 | 新增: g_free(path); | |
| 534 | 新增: } | |
| 535 | 新增: } | |
| 536 | 新增: } else if (!strcmp(name, "workbenchReady")) { | |
| 498 | 537 | if (app.needs_update) reply_error(reply, "后台版本尚未同步,更新未完成。"); |
| 499 | 538 | else { |
| 500 | 539 | app.ready = TRUE; |
| @@ -673,7 +712,7 @@ static void install_bridge(void) { | ||
| 673 | 712 | char *token = quote(app.token); |
| 674 | 713 | char *code = g_strdup_printf( |
| 675 | 714 | "(()=>{'use strict';window.cageLinuxBridgeInit='injected';if(window!==window.top||location.protocol!=='http:'||location.hostname!=='localhost'||location.port!=='%d')return;" |
| 676 | 删除: "window.cageLinuxBridgeInit='origin-valid';try{" | |
| 715 | 新增: "window.cageLinuxBridgeInit='origin-valid';window.cageNativeIMEAvailable=true;try{" | |
| 677 | 716 | "const transport=window.webkit.messageHandlers.cageTransport;const token=%s;" |
| 678 | 717 | "const cage=Object.freeze({postMessage(request){return transport.postMessage({token,request});}});" |
| 679 | 718 | "Object.defineProperty(window.webkit.messageHandlers,'cage',{value:cage,writable:false,configurable:false});" |
| @@ -869,6 +908,7 @@ static void create_window(void) { | ||
| 869 | 908 | g_signal_connect(app.content, "script-message-with-reply-received::cageTransport", G_CALLBACK(bridge_received), NULL); |
| 870 | 909 | webkit_user_content_manager_register_script_message_handler_with_reply(app.content, "cageTransport", NULL); |
| 871 | 910 | app.web = WEBKIT_WEB_VIEW(g_object_new(WEBKIT_TYPE_WEB_VIEW, "web-context", context, "user-content-manager", app.content, NULL)); |
| 911 | 新增: input_initialize(app.web); | |
| 872 | 912 | g_object_unref(context); |
| 873 | 913 | WebKitSettings *web_settings = webkit_web_view_get_settings(app.web); |
| 874 | 914 | webkit_settings_set_enable_developer_extras(web_settings, FALSE); |
| @@ -958,6 +998,7 @@ int main(int argc, char **argv) { | ||
| 958 | 998 | app.profile = configured && *configured ? g_canonicalize_filename(configured, NULL) |
| 959 | 999 | : g_build_filename(g_get_home_dir(), ".claude-cage", "config.json", NULL); |
| 960 | 1000 | g_setenv("CLAUDE_CAGE_CONFIG", app.profile, TRUE); |
| 1001 | 新增: g_log_set_default_handler(diagnostic_glib, NULL); | |
| 961 | 1002 | if (!prepare_web_storage()) { |
| 962 | 1003 | g_printerr("无法创建 Cage 私有界面数据目录,请检查配置目录的所有者、权限或符号链接。\n"); |
| 963 | 1004 | return 1; |
| @@ -0,0 +1,132 @@ | ||
| 1 | 新增:/* Host GTK input context. Guest text and surrounding content are never read. */ | |
| 2 | 新增:typedef struct { | |
| 3 | 新增: GtkIMContext *context; | |
| 4 | 新增: WebKitWebView *web; | |
| 5 | 新增: char *owner; | |
| 6 | 新增: gboolean composing, resetting; | |
| 7 | 新增: guint end_idle; | |
| 8 | 新增:} CageNativeInput; | |
| 9 | 新增: | |
| 10 | 新增:static CageNativeInput native_input; | |
| 11 | 新增: | |
| 12 | 新增:static void input_emit(const char *kind, const char *text, int start, int end) { | |
| 13 | 新增: if (!native_input.owner) return; | |
| 14 | 新增: JsonObject *event = json_object_new(); | |
| 15 | 新增: json_object_set_string_member(event, "owner", native_input.owner); | |
| 16 | 新增: json_object_set_string_member(event, "kind", kind); | |
| 17 | 新增: if (text) json_object_set_string_member(event, "text", text); | |
| 18 | 新增: json_object_set_int_member(event, "selectionStart", start); | |
| 19 | 新增: json_object_set_int_member(event, "selectionEnd", end); | |
| 20 | 新增: JsonNode *node = json_node_new(JSON_NODE_OBJECT); | |
| 21 | 新增: json_node_take_object(node, event); | |
| 22 | 新增: JsonGenerator *generator = json_generator_new(); | |
| 23 | 新增: json_generator_set_root(generator, node); | |
| 24 | 新增: char *json = json_generator_to_data(generator, NULL); | |
| 25 | 新增: char *script = g_strdup_printf("window.dispatchEvent(new CustomEvent('cage-native-input',{detail:%s}));", json); | |
| 26 | 新增: webkit_web_view_evaluate_javascript(native_input.web, script, -1, NULL, NULL, NULL, NULL, NULL); | |
| 27 | 新增: g_free(script); g_free(json); json_node_free(node); g_object_unref(generator); | |
| 28 | 新增:} | |
| 29 | 新增: | |
| 30 | 新增:static void input_cancel(void) { | |
| 31 | 新增: if (native_input.end_idle) { g_source_remove(native_input.end_idle); native_input.end_idle = 0; } | |
| 32 | 新增: if (native_input.composing) input_emit("compositionend", "", 0, 0); | |
| 33 | 新增: native_input.composing = FALSE; | |
| 34 | 新增: native_input.resetting = TRUE; | |
| 35 | 新增: gtk_im_context_reset(native_input.context); | |
| 36 | 新增: native_input.resetting = FALSE; | |
| 37 | 新增:} | |
| 38 | 新增: | |
| 39 | 新增:static int input_utf16_length(const char *text, int characters) { | |
| 40 | 新增: int length = 0; | |
| 41 | 新增: for (const char *p = text; *p && characters-- > 0; p = g_utf8_next_char(p)) | |
| 42 | 新增: length += g_utf8_get_char(p) > 0xffff ? 2 : 1; | |
| 43 | 新增: return length; | |
| 44 | 新增:} | |
| 45 | 新增: | |
| 46 | 新增:static void input_preedit(GtkIMContext *context, gpointer data) { | |
| 47 | 新增: (void)data; | |
| 48 | 新增: if (!native_input.owner || native_input.resetting) return; | |
| 49 | 新增: char *text = NULL; | |
| 50 | 新增: PangoAttrList *attributes = NULL; | |
| 51 | 新增: int cursor = 0; | |
| 52 | 新增: gtk_im_context_get_preedit_string(context, &text, &attributes, &cursor); | |
| 53 | 新增: if (text && *text) { | |
| 54 | 新增: if (native_input.end_idle) { g_source_remove(native_input.end_idle); native_input.end_idle = 0; } | |
| 55 | 新增: if (!native_input.composing) { native_input.composing = TRUE; input_emit("compositionstart", NULL, 0, 0); } | |
| 56 | 新增: int end = input_utf16_length(text, cursor); | |
| 57 | 新增: input_emit("compositionupdate", text, end, end); | |
| 58 | 新增: } else if (native_input.composing) { | |
| 59 | 新增: /* GTK sends an empty preedit before commit. preedit-end finalizes | |
| 60 | 新增: * cancellation after the synchronous commit signal has had a chance. */ | |
| 61 | 新增: } | |
| 62 | 新增: if (attributes) pango_attr_list_unref(attributes); | |
| 63 | 新增: g_free(text); | |
| 64 | 新增:} | |
| 65 | 新增: | |
| 66 | 新增:static gboolean input_preedit_ended(gpointer data) { | |
| 67 | 新增: (void)data; | |
| 68 | 新增: native_input.end_idle = 0; | |
| 69 | 新增: if (native_input.composing) { native_input.composing = FALSE; input_emit("compositionend", "", 0, 0); } | |
| 70 | 新增: return G_SOURCE_REMOVE; | |
| 71 | 新增:} | |
| 72 | 新增:static void input_preedit_end(GtkIMContext *context, gpointer data) { | |
| 73 | 新增: (void)context; (void)data; | |
| 74 | 新增: if (!native_input.end_idle) native_input.end_idle = g_idle_add(input_preedit_ended, NULL); | |
| 75 | 新增:} | |
| 76 | 新增:static void input_commit(GtkIMContext *context, const char *text, gpointer data) { | |
| 77 | 新增: (void)context; (void)data; | |
| 78 | 新增: if (!native_input.owner || native_input.resetting) return; | |
| 79 | 新增: if (native_input.end_idle) { g_source_remove(native_input.end_idle); native_input.end_idle = 0; } | |
| 80 | 新增: input_emit(native_input.composing ? "compositionend" : "input", text, 0, 0); | |
| 81 | 新增: native_input.composing = FALSE; | |
| 82 | 新增:} | |
| 83 | 新增:static gboolean input_key(GtkWidget *widget, GdkEventKey *event, gpointer data) { | |
| 84 | 新增: (void)widget; (void)data; | |
| 85 | 新增: return native_input.owner && gtk_im_context_filter_keypress(native_input.context, event); | |
| 86 | 新增:} | |
| 87 | 新增:static gboolean input_focus_out(GtkWidget *widget, GdkEventFocus *event, gpointer data) { | |
| 88 | 新增: (void)widget; (void)event; (void)data; | |
| 89 | 新增: if (native_input.owner) { | |
| 90 | 新增: input_cancel(); input_emit("deactivated", NULL, 0, 0); | |
| 91 | 新增: gtk_im_context_focus_out(native_input.context); | |
| 92 | 新增: g_clear_pointer(&native_input.owner, g_free); | |
| 93 | 新增: } | |
| 94 | 新增: return FALSE; | |
| 95 | 新增:} | |
| 96 | 新增: | |
| 97 | 新增:static void input_initialize(WebKitWebView *web) { | |
| 98 | 新增: native_input.web = web; | |
| 99 | 新增: native_input.context = gtk_im_multicontext_new(); | |
| 100 | 新增: gtk_im_context_set_use_preedit(native_input.context, TRUE); | |
| 101 | 新增: g_signal_connect(native_input.context, "preedit-changed", G_CALLBACK(input_preedit), NULL); | |
| 102 | 新增: g_signal_connect(native_input.context, "preedit-end", G_CALLBACK(input_preedit_end), NULL); | |
| 103 | 新增: g_signal_connect(native_input.context, "commit", G_CALLBACK(input_commit), NULL); | |
| 104 | 新增: g_signal_connect(web, "key-press-event", G_CALLBACK(input_key), NULL); | |
| 105 | 新增: g_signal_connect(web, "key-release-event", G_CALLBACK(input_key), NULL); | |
| 106 | 新增: g_signal_connect(web, "focus-out-event", G_CALLBACK(input_focus_out), NULL); | |
| 107 | 新增:} | |
| 108 | 新增: | |
| 109 | 新增:static gboolean input_handle(JsonObject *request) { | |
| 110 | 新增: const char *operation = json_object_has_member(request, "operation") ? json_object_get_string_member(request, "operation") : ""; | |
| 111 | 新增: const char *owner = json_object_has_member(request, "owner") ? json_object_get_string_member(request, "owner") : ""; | |
| 112 | 新增: if (!g_uuid_string_is_valid(owner)) return FALSE; | |
| 113 | 新增: if (!strcmp(operation, "activate")) { | |
| 114 | 新增: if (g_strcmp0(owner, native_input.owner)) { input_cancel(); g_free(native_input.owner); native_input.owner = g_strdup(owner); } | |
| 115 | 新增: gtk_im_context_set_client_window(native_input.context, gtk_widget_get_window(GTK_WIDGET(native_input.web))); | |
| 116 | 新增: gtk_im_context_focus_in(native_input.context); | |
| 117 | 新增: } else if (g_strcmp0(owner, native_input.owner)) return FALSE; | |
| 118 | 新增: if (!strcmp(operation, "activate") || !strcmp(operation, "caret")) { | |
| 119 | 新增: double scale = webkit_web_view_get_zoom_level(native_input.web); | |
| 120 | 新增: double x = json_object_get_double_member_with_default(request, "x", 0); | |
| 121 | 新增: double y = json_object_get_double_member_with_default(request, "y", 0); | |
| 122 | 新增: double height = json_object_get_double_member_with_default(request, "height", 24); | |
| 123 | 新增: if (!isfinite(x) || !isfinite(y) || !isfinite(height) || height <= 0 || fabs(x) > 32768 || fabs(y) > 32768 || height > 4096) return FALSE; | |
| 124 | 新增: GdkRectangle caret = {(int)(x * scale), (int)(y * scale), 0, MAX(1, (int)(height * scale))}; | |
| 125 | 新增: gtk_im_context_set_cursor_location(native_input.context, &caret); | |
| 126 | 新增: } else if (!strcmp(operation, "cancel")) input_cancel(); | |
| 127 | 新增: else if (!strcmp(operation, "deactivate")) { | |
| 128 | 新增: input_cancel(); gtk_im_context_focus_out(native_input.context); | |
| 129 | 新增: g_clear_pointer(&native_input.owner, g_free); | |
| 130 | 新增: } else return FALSE; | |
| 131 | 新增: return TRUE; | |
| 132 | 新增:} | |
| @@ -63,6 +63,20 @@ internal static class Backend | ||
| 63 | 63 | var buffer = new char[4096]; |
| 64 | 64 | while (await reader.ReadAsync(buffer.AsMemory(), token) > 0) { } |
| 65 | 65 | } |
| 66 | 新增: public static async Task Report(string message) | |
| 67 | 新增: { | |
| 68 | 新增: try | |
| 69 | 新增: { | |
| 70 | 新增: using var process = new Process { StartInfo = StartInfo(Executable, "diagnostic-event") }; | |
| 71 | 新增: process.StartInfo.RedirectStandardInput = true; | |
| 72 | 新增: if (!process.Start()) return; | |
| 73 | 新增: await process.StandardInput.WriteAsync(JsonSerializer.Serialize(new { source = "native", message = message[..Math.Min(message.Length, 4096)] })); | |
| 74 | 新增: process.StandardInput.Close(); | |
| 75 | 新增: using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5)); | |
| 76 | 新增: await process.WaitForExitAsync(timeout.Token); | |
| 77 | 新增: } | |
| 78 | 新增: catch (Exception) { /* Logging failure must not recurse or replace the original error. */ } | |
| 79 | 新增: } | |
| 66 | 80 | public static string Text(this JsonElement data, string name) => |
| 67 | 81 | data.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String ? value.GetString()! : ""; |
| 68 | 82 | } |
| @@ -7,6 +7,7 @@ namespace Cage.Windows; | ||
| 7 | 7 | internal sealed class MainWindow : Form |
| 8 | 8 | { |
| 9 | 9 | private WebView2 web = new() { Dock = DockStyle.Fill, Visible = false }; |
| 10 | 新增: private readonly NativeInput nativeInput; | |
| 10 | 11 | private readonly Label message = new() { AutoSize = true, MaximumSize = new Size(720, 0), Text = "正在启动 Cage 工作台…", Margin = new Padding(12) }; |
| 11 | 12 | private readonly FlowLayoutPanel status = new() { Dock = DockStyle.Fill, FlowDirection = FlowDirection.TopDown, Padding = new Padding(48), WrapContents = false }; |
| 12 | 13 | private readonly Button retry = new() { Text = "重试连接", AutoSize = true, Visible = false }; |
| @@ -21,6 +22,7 @@ internal sealed class MainWindow : Form | ||
| 21 | 22 | |
| 22 | 23 | public MainWindow() |
| 23 | 24 | { |
| 25 | 新增: nativeInput = new NativeInput(value => Script("window.dispatchEvent(new CustomEvent('cage-native-input',{detail:" + JsonSerializer.Serialize(value) + "}));")); | |
| 24 | 26 | Text = "Cage"; Width = 1280; Height = 850; MinimumSize = new Size(820, 580); |
| 25 | 27 | StartPosition = FormStartPosition.CenterScreen; BackColor = Color.FromArgb(247, 247, 247); |
| 26 | 28 | Icon = Icon.ExtractAssociatedIcon(Environment.ProcessPath!) ?? SystemIcons.Application; |
| @@ -40,6 +42,7 @@ internal sealed class MainWindow : Form | ||
| 40 | 42 | menus.Items.AddRange([file, settings, help]); MainMenuStrip = menus; |
| 41 | 43 | status.Controls.AddRange([message, retry, existing, complete]); |
| 42 | 44 | Controls.Add(web); Controls.Add(status); Controls.Add(menus); |
| 45 | 新增: Controls.Add(nativeInput); | |
| 43 | 46 | retry.Click += async (_, _) => { |
| 44 | 47 | if (webFailed || web.CoreWebView2 == null) await Initialize(true); else await Bootstrap(); |
| 45 | 48 | }; |
| @@ -79,7 +82,10 @@ internal sealed class MainWindow : Form | ||
| 79 | 82 | } |
| 80 | 83 | private void Action(string name) => Script("window.cageNativeAction?.(" + JsonSerializer.Serialize(name) + ")"); |
| 81 | 84 | private void PublishVisibility() => Script($"window.cageWindowVisible = {(Visible && WindowState != FormWindowState.Minimized ? "true" : "false")}; window.dispatchEvent(new Event('cage-window-visibility'));"); |
| 82 | 删除: private void PublishUpdate(Dictionary<string, object?> state) => Script("window.dispatchEvent(new CustomEvent('cage-app-update',{detail:" + JsonSerializer.Serialize(state) + "}));"); | |
| 85 | 新增: private void PublishUpdate(Dictionary<string, object?> state) { | |
| 86 | 新增: if (state.TryGetValue("phase", out var phase) && phase as string == "failed") _ = Backend.Report("App update failed: " + state.GetValueOrDefault("message")); | |
| 87 | 新增: Script("window.dispatchEvent(new CustomEvent('cage-app-update',{detail:" + JsonSerializer.Serialize(state) + "}));"); | |
| 88 | 新增: } | |
| 83 | 89 | private async void Script(string script) |
| 84 | 90 | { |
| 85 | 91 | if (web.CoreWebView2 == null || IsDisposed) return; |
| @@ -89,6 +95,7 @@ internal sealed class MainWindow : Form | ||
| 89 | 95 | } |
| 90 | 96 | private void Error(string text) |
| 91 | 97 | { |
| 98 | 新增: _ = Backend.Report(text); | |
| 92 | 99 | message.Text = text; status.Show(); status.BringToFront(); retry.Show(); web.Hide(); |
| 93 | 100 | } |
| 94 | 101 | |
| @@ -214,6 +221,16 @@ internal sealed class MainWindow : Form | ||
| 214 | 221 | object? result; |
| 215 | 222 | switch (request.Text("action")) |
| 216 | 223 | { |
| 224 | 新增: case "remoteInput": result = nativeInput.ProcessRequest(request, web, web.ZoomFactor); break; | |
| 225 | 新增: case "exportDiagnostics": | |
| 226 | 新增: using (var picker = new SaveFileDialog { Title = "导出诊断包", Filter = "诊断包 (*.zip)|*.zip", FileName = "cage-diagnostics.zip", DefaultExt = "zip", AddExtension = true }) | |
| 227 | 新增: { | |
| 228 | 新增: if (picker.ShowDialog(this) != DialogResult.OK) { result = new { canceled = true }; break; } | |
| 229 | 新增: var exported = await Backend.Json(["diagnostics", "--json", picker.FileName], lifetime.Token, TimeSpan.FromSeconds(60)); | |
| 230 | 新增: if (exported.Exit != 0) throw new IOException(exported.Data.Text("message")); | |
| 231 | 新增: result = exported.Data; | |
| 232 | 新增: } | |
| 233 | 新增: break; | |
| 217 | 234 | case "workbenchReady": |
| 218 | 235 | if (controllerNeedsUpdate) throw new IOException("后台版本尚未同步,更新未完成"); |
| 219 | 236 | updater.MarkReady(); result = true; _ = CompleteSmoke(); break; |
| @@ -317,6 +334,7 @@ internal sealed class MainWindow : Form | ||
| 317 | 334 | } |
| 318 | 335 | catch (Exception error) |
| 319 | 336 | { |
| 337 | 新增: _ = Backend.Report(error.ToString()); | |
| 320 | 338 | if (id.Length != 0 && !IsDisposed) web.CoreWebView2.PostWebMessageAsJson(JsonSerializer.Serialize(new { id, error = error.Message })); |
| 321 | 339 | } |
| 322 | 340 | } |
| @@ -324,6 +342,7 @@ internal sealed class MainWindow : Form | ||
| 324 | 342 | private const string BridgeScript = """ |
| 325 | 343 | (() => { |
| 326 | 344 | if (window !== window.top || location.protocol !== 'http:' || location.hostname !== 'localhost') return; |
| 345 | 新增: window.cageNativeIMEAvailable = true; | |
| 327 | 346 | const pending = new Map(); |
| 328 | 347 | chrome.webview.addEventListener('message', ({data}) => { |
| 329 | 348 | const item = pending.get(data.id); if (!item) return; |
| @@ -0,0 +1,207 @@ | ||
| 1 | 新增:using System.Runtime.InteropServices; | |
| 2 | 新增:using System.Text; | |
| 3 | 新增:using System.Text.Json; | |
| 4 | 新增: | |
| 5 | 新增:namespace Cage.Windows; | |
| 6 | 新增: | |
| 7 | 新增:// A real Win32 edit control supplies TSF/IMM the caret while Cage owns no | |
| 8 | 新增:// remote document text. Only this control's transient composition is read. | |
| 9 | 新增:internal sealed class NativeInput : TextBox | |
| 10 | 新增:{ | |
| 11 | 新增: private readonly Action<Dictionary<string, object?>> publish; | |
| 12 | 新增: private string owner = ""; | |
| 13 | 新增: private bool composing, resetting; | |
| 14 | 新增: private Keys lastKey; | |
| 15 | 新增: private bool repeating; | |
| 16 | 新增: private char? highSurrogate; | |
| 17 | 新增: | |
| 18 | 新增: internal NativeInput(Action<Dictionary<string, object?>> publish) | |
| 19 | 新增: { | |
| 20 | 新增: this.publish = publish; | |
| 21 | 新增: BorderStyle = BorderStyle.None; Multiline = true; TabStop = false; | |
| 22 | 新增: ImeMode = ImeMode.On; Visible = false; Size = new Size(1, 24); | |
| 23 | 新增: LostFocus += (_, _) => { | |
| 24 | 新增: Cancel(); Emit("deactivated"); owner = ""; Visible = false; | |
| 25 | 新增: }; | |
| 26 | 新增: } | |
| 27 | 新增: | |
| 28 | 新增: private void Emit(string kind, string? text = null, int start = 0, int end = 0) | |
| 29 | 新增: { | |
| 30 | 新增: if (owner.Length == 0) return; | |
| 31 | 新增: publish(new() { ["owner"] = owner, ["kind"] = kind, ["text"] = text, | |
| 32 | 新增: ["selectionStart"] = start, ["selectionEnd"] = end }); | |
| 33 | 新增: } | |
| 34 | 新增: | |
| 35 | 新增: internal bool ProcessRequest(JsonElement value, Control web, double zoom) | |
| 36 | 新增: { | |
| 37 | 新增: var requestedOwner = value.Text("owner"); | |
| 38 | 新增: if (!Guid.TryParse(requestedOwner, out _)) return false; | |
| 39 | 新增: var operation = value.Text("operation"); | |
| 40 | 新增: if (operation == "activate") | |
| 41 | 新增: { | |
| 42 | 新增: if (owner != requestedOwner) { Cancel(); owner = requestedOwner; } | |
| 43 | 新增: Visible = true; BringToFront(); | |
| 44 | 新增: } | |
| 45 | 新增: else if (owner != requestedOwner) return false; | |
| 46 | 新增: if (operation is "activate" or "caret") | |
| 47 | 新增: { | |
| 48 | 新增: if (!value.TryGetProperty("x", out var vx) || !vx.TryGetDouble(out var x) || | |
| 49 | 新增: !value.TryGetProperty("y", out var vy) || !vy.TryGetDouble(out var y) || | |
| 50 | 新增: !value.TryGetProperty("height", out var vh) || !vh.TryGetDouble(out var height) || | |
| 51 | 新增: !double.IsFinite(x) || !double.IsFinite(y) || !double.IsFinite(height) || | |
| 52 | 新增: Math.Abs(x) > 32768 || Math.Abs(y) > 32768 || height <= 0 || height > 4096) return false; | |
| 53 | 新增: var scale = web.DeviceDpi / 96.0 * zoom; | |
| 54 | 新增: var point = Parent!.PointToClient(web.PointToScreen(new Point((int)(x * scale), (int)(y * scale)))); | |
| 55 | 新增: Bounds = new Rectangle(point, new Size(1, Math.Max(1, (int)(height * scale)))); | |
| 56 | 新增: if (operation == "activate") Focus(); | |
| 57 | 新增: PositionCandidates(); | |
| 58 | 新增: } | |
| 59 | 新增: else if (operation == "cancel") Cancel(); | |
| 60 | 新增: else if (operation == "deactivate") { Cancel(); owner = ""; Visible = false; web.Focus(); } | |
| 61 | 新增: else return false; | |
| 62 | 新增: return true; | |
| 63 | 新增: } | |
| 64 | 新增: | |
| 65 | 新增: private void Cancel() | |
| 66 | 新增: { | |
| 67 | 新增: if (composing) Emit("compositionend", ""); | |
| 68 | 新增: composing = false; resetting = true; | |
| 69 | 新增: if (IsHandleCreated) | |
| 70 | 新增: { | |
| 71 | 新增: var context = ImmGetContext(Handle); | |
| 72 | 新增: if (context != IntPtr.Zero) { ImmNotifyIME(context, 0x15, 4, 0); ImmReleaseContext(Handle, context); } | |
| 73 | 新增: } | |
| 74 | 新增: Clear(); highSurrogate = null; resetting = false; | |
| 75 | 新增: } | |
| 76 | 新增: | |
| 77 | 新增: protected override bool IsInputKey(Keys keyData) => true; | |
| 78 | 新增: protected override bool ProcessCmdKey(ref Message msg, Keys keyData) | |
| 79 | 新增: { | |
| 80 | 新增: if (!composing && (keyData & (Keys.Control | Keys.Alt)) != 0) | |
| 81 | 新增: { | |
| 82 | 新增: Key(keyData & Keys.KeyCode, true); | |
| 83 | 新增: return true; | |
| 84 | 新增: } | |
| 85 | 新增: return base.ProcessCmdKey(ref msg, keyData); | |
| 86 | 新增: } | |
| 87 | 新增: protected override void OnKeyDown(KeyEventArgs e) | |
| 88 | 新增: { | |
| 89 | 新增: lastKey = e.KeyCode; | |
| 90 | 新增: if (!composing && (e.Control || e.Alt || IsCommand(e.KeyCode))) | |
| 91 | 新增: { Key(e.KeyCode, true); e.Handled = true; } | |
| 92 | 新增: } | |
| 93 | 新增: protected override void OnKeyUp(KeyEventArgs e) | |
| 94 | 新增: { Key(e.KeyCode, false); e.Handled = true; } | |
| 95 | 新增: protected override void OnKeyPress(KeyPressEventArgs e) | |
| 96 | 新增: { | |
| 97 | 新增: if (composing || resetting) return; | |
| 98 | 新增: e.Handled = true; | |
| 99 | 新增: if (char.IsHighSurrogate(e.KeyChar)) { highSurrogate = e.KeyChar; return; } | |
| 100 | 新增: if (char.IsLowSurrogate(e.KeyChar) && highSurrogate is char first) | |
| 101 | 新增: { Emit("input", new string([first, e.KeyChar])); highSurrogate = null; return; } | |
| 102 | 新增: highSurrogate = null; | |
| 103 | 新增: if (!char.IsControl(e.KeyChar)) | |
| 104 | 新增: { | |
| 105 | 新增: if (e.KeyChar <= 127) Key(lastKey, true, e.KeyChar.ToString()); | |
| 106 | 新增: else Emit("input", e.KeyChar.ToString()); | |
| 107 | 新增: } | |
| 108 | 新增: } | |
| 109 | 新增: protected override void OnTextChanged(EventArgs e) | |
| 110 | 新增: { | |
| 111 | 新增: base.OnTextChanged(e); | |
| 112 | 新增: if (!composing && !resetting && Text.Length > 0) Clear(); | |
| 113 | 新增: } | |
| 114 | 新增: private static bool IsCommand(Keys key) => key is Keys.Enter or Keys.Tab or Keys.Back or Keys.Delete or Keys.Escape or | |
| 115 | 新增: Keys.Left or Keys.Right or Keys.Up or Keys.Down or Keys.Home or Keys.End or Keys.PageUp or Keys.PageDown or | |
| 116 | 新增: Keys.ShiftKey or Keys.ControlKey or Keys.Menu or Keys.LWin or Keys.RWin or Keys.CapsLock || key >= Keys.F1 && key <= Keys.F24; | |
| 117 | 新增: | |
| 118 | 新增: private void Key(Keys key, bool down, string? text = null) | |
| 119 | 新增: { | |
| 120 | 新增: if (owner.Length == 0) return; | |
| 121 | 新增: var pair = key switch { | |
| 122 | 新增: Keys.Enter => ("Enter", "Enter"), Keys.Tab => ("Tab", "Tab"), Keys.Back => ("Backspace", "Backspace"), | |
| 123 | 新增: Keys.Delete => ("Delete", "Delete"), Keys.Escape => ("Escape", "Escape"), Keys.Left => ("ArrowLeft", "ArrowLeft"), | |
| 124 | 新增: Keys.Right => ("ArrowRight", "ArrowRight"), Keys.Up => ("ArrowUp", "ArrowUp"), Keys.Down => ("ArrowDown", "ArrowDown"), | |
| 125 | 新增: Keys.ShiftKey => ("Shift", "ShiftLeft"), Keys.ControlKey => ("Control", "ControlLeft"), Keys.Menu => ("Alt", "AltLeft"), | |
| 126 | 新增: Keys.LWin => ("Meta", "MetaLeft"), Keys.RWin => ("Meta", "MetaRight"), Keys.CapsLock => ("CapsLock", "CapsLock"), | |
| 127 | 新增: Keys.Home => ("Home", "Home"), Keys.End => ("End", "End"), Keys.PageUp => ("PageUp", "PageUp"), Keys.PageDown => ("PageDown", "PageDown"), | |
| 128 | 新增: _ when key >= Keys.A && key <= Keys.Z => (key.ToString().ToLowerInvariant(), "Key" + key), | |
| 129 | 新增: _ when key >= Keys.D0 && key <= Keys.D9 => (((int)key - (int)Keys.D0).ToString(), "Digit" + ((int)key - (int)Keys.D0)), | |
| 130 | 新增: _ when key >= Keys.F1 && key <= Keys.F24 => (key.ToString(), key.ToString()), | |
| 131 | 新增: _ => (text ?? "Unidentified", "Unidentified") | |
| 132 | 新增: }; | |
| 133 | 新增: publish(new() { ["owner"] = owner, ["kind"] = down ? "keydown" : "keyup", ["key"] = text ?? pair.Item1, | |
| 134 | 新增: ["code"] = pair.Item2, ["textKey"] = text != null, ["repeat"] = repeating, | |
| 135 | 新增: ["ctrlKey"] = (ModifierKeys & Keys.Control) != 0, ["altKey"] = (ModifierKeys & Keys.Alt) != 0, | |
| 136 | 新增: ["shiftKey"] = (ModifierKeys & Keys.Shift) != 0, ["metaKey"] = false }); | |
| 137 | 新增: } | |
| 138 | 新增: | |
| 139 | 新增: protected override void WndProc(ref Message message) | |
| 140 | 新增: { | |
| 141 | 新增: const int Start = 0x10d, End = 0x10e, Composition = 0x10f; | |
| 142 | 新增: bool committed = false; | |
| 143 | 新增: if (message.Msg == 0x100) repeating = ((long)message.LParam & (1L << 30)) != 0; | |
| 144 | 新增: if (!resetting && owner.Length > 0) | |
| 145 | 新增: { | |
| 146 | 新增: if (message.Msg == Start) { composing = true; Emit("compositionstart"); } | |
| 147 | 新增: if (message.Msg == Composition) | |
| 148 | 新增: { | |
| 149 | 新增: var context = ImmGetContext(Handle); | |
| 150 | 新增: if (context != IntPtr.Zero) | |
| 151 | 新增: { | |
| 152 | 新增: var flags = (int)message.LParam; | |
| 153 | 新增: if ((flags & 0x800) != 0) | |
| 154 | 新增: { | |
| 155 | 新增: Emit("compositionend", CompositionText(context, 0x800)); composing = false; | |
| 156 | 新增: committed = true; | |
| 157 | 新增: BeginInvoke(() => { if (!composing && !IsDisposed) Clear(); }); | |
| 158 | 新增: } | |
| 159 | 新增: if ((flags & 8) != 0) | |
| 160 | 新增: { | |
| 161 | 新增: if (!composing) { composing = true; Emit("compositionstart"); } | |
| 162 | 新增: var text = CompositionText(context, 8); | |
| 163 | 新增: var cursor = Math.Clamp(ImmGetCompositionString(context, 0x80, null, 0), 0, text.Length); | |
| 164 | 新增: Emit("compositionupdate", text, cursor, cursor); | |
| 165 | 新增: } | |
| 166 | 新增: ImmReleaseContext(Handle, context); | |
| 167 | 新增: } | |
| 168 | 新增: PositionCandidates(); | |
| 169 | 新增: } | |
| 170 | 新增: if (message.Msg == End && composing) { composing = false; Emit("compositionend", ""); } | |
| 171 | 新增: } | |
| 172 | 新增: // Cage already delivered RESULTSTR. DefWindowProc would turn it into | |
| 173 | 新增: // WM_IME_CHAR/WM_CHAR and send a second copy through OnKeyPress. | |
| 174 | 新增: if (committed) { message.Result = IntPtr.Zero; return; } | |
| 175 | 新增: // The control participates in native text services but paints no text. | |
| 176 | 新增: if (message.Msg == 0xf) { ValidateRect(Handle, IntPtr.Zero); message.Result = IntPtr.Zero; return; } | |
| 177 | 新增: base.WndProc(ref message); | |
| 178 | 新增: if (IsHandleCreated) HideCaret(Handle); | |
| 179 | 新增: } | |
| 180 | 新增: | |
| 181 | 新增: private static string CompositionText(IntPtr context, int index) | |
| 182 | 新增: { | |
| 183 | 新增: var length = ImmGetCompositionString(context, index, null, 0); | |
| 184 | 新增: if (length <= 0 || length > 16384) return ""; | |
| 185 | 新增: var bytes = new byte[length]; | |
| 186 | 新增: var count = ImmGetCompositionString(context, index, bytes, bytes.Length); | |
| 187 | 新增: return count > 0 ? Encoding.Unicode.GetString(bytes, 0, count) : ""; | |
| 188 | 新增: } | |
| 189 | 新增: private void PositionCandidates() | |
| 190 | 新增: { | |
| 191 | 新增: if (!IsHandleCreated) return; | |
| 192 | 新增: var context = ImmGetContext(Handle); | |
| 193 | 新增: if (context == IntPtr.Zero) return; | |
| 194 | 新增: var candidate = new Candidate { Style = 0x80, Point = new Point(0, Height), Area = new Rect { Bottom = Height, Right = 1 } }; | |
| 195 | 新增: ImmSetCandidateWindow(context, ref candidate); | |
| 196 | 新增: ImmReleaseContext(Handle, context); | |
| 197 | 新增: } | |
| 198 | 新增: [StructLayout(LayoutKind.Sequential)] private struct Rect { public int Left, Top, Right, Bottom; } | |
| 199 | 新增: [StructLayout(LayoutKind.Sequential)] private struct Candidate { public int Index, Style; public Point Point; public Rect Area; } | |
| 200 | 新增: [DllImport("imm32.dll")] private static extern IntPtr ImmGetContext(IntPtr window); | |
| 201 | 新增: [DllImport("imm32.dll")] private static extern bool ImmReleaseContext(IntPtr window, IntPtr context); | |
| 202 | 新增: [DllImport("imm32.dll", EntryPoint = "ImmGetCompositionStringW")] private static extern int ImmGetCompositionString(IntPtr context, int index, byte[]? data, int length); | |
| 203 | 新增: [DllImport("imm32.dll")] private static extern bool ImmSetCandidateWindow(IntPtr context, ref Candidate candidate); | |
| 204 | 新增: [DllImport("imm32.dll")] private static extern bool ImmNotifyIME(IntPtr context, int action, int index, int value); | |
| 205 | 新增: [DllImport("user32.dll")] private static extern bool HideCaret(IntPtr window); | |
| 206 | 新增: [DllImport("user32.dll")] private static extern bool ValidateRect(IntPtr window, IntPtr rect); | |
| 207 | 新增:} | |
| @@ -19,6 +19,13 @@ internal static class Program | ||
| 19 | 19 | if (File.Exists(output)) File.Delete(output); |
| 20 | 20 | } |
| 21 | 21 | else if (args.Length != 0) return 2; |
| 22 | 新增: AppDomain.CurrentDomain.UnhandledException += (_, e) => Backend.Report(e.ExceptionObject is Exception error ? error.ToString() : "Unhandled native exception").GetAwaiter().GetResult(); | |
| 23 | 新增: Application.ThreadException += (_, e) => { | |
| 24 | 新增: Backend.Report(e.Exception.ToString()).GetAwaiter().GetResult(); | |
| 25 | 新增: using var dialog = new ThreadExceptionDialog(e.Exception); | |
| 26 | 新增: if (dialog.ShowDialog() == DialogResult.Abort) Application.Exit(); | |
| 27 | 新增: }; | |
| 28 | 新增: TaskScheduler.UnobservedTaskException += (_, e) => _ = Backend.Report(e.Exception.ToString()); | |
| 22 | 29 | ApplicationConfiguration.Initialize(); |
| 23 | 30 | if (RuntimeInformation.OSArchitecture != Architecture.X64 || Environment.OSVersion.Version.Build < 19045) |
| 24 | 31 | { |
| @@ -13,6 +13,7 @@ | ||
| 13 | 13 | | 升级应用、更新环境工具或卸载 | [升级与卸载](getting-started.md#升级与卸载) | |
| 14 | 14 | | 查看首个内测版本的能力与验收范围 | [0.1.0-alpha.1 发行说明](releases/0.1.0-alpha.1.md) | |
| 15 | 15 | | 排查下载、启动、联网与授权问题 | [常见问题与恢复](troubleshooting.md) | |
| 16 | 新增:| 导出故障日志并了解自动清理 | [导出诊断包](troubleshooting.md#导出诊断包) | | |
| 16 | 17 | | 报告隔离或凭据安全问题 | [安全报告](../SECURITY.md) | |
| 17 | 18 | |
| 18 | 19 | ## 开发与发布 |
| @@ -21,8 +22,11 @@ | ||
| 21 | 22 | |---|---| |
| 22 | 23 | | 从源码构建、修改和验证代码 | [参与开发](../CONTRIBUTING.md) | |
| 23 | 24 | | 理解工作台、浏览器与后台的职责 | [工作台设计](design/workbench.md) | |
| 25 | 新增:| 评估主机输入法、原位拼音与候选窗跟随 | [原生输入法研究](research/2026-11-04-native-ime.md) | | |
| 24 | 26 | | 定位作业、终端、浏览器连接与退出流程的代码 | [控制服务职责](design/control-service.md) | |
| 25 | 27 | | 理解网络检查、暂停与恢复 | [网络检查设计](design/network-checks.md) | |
| 28 | 新增:| 理解内存回收、CPU 上限与压力后的联网恢复 | [计算资源](design/resources.md) | | |
| 29 | 新增:| 理解日志脱敏、清理与诊断接口 | [日志与诊断](design/diagnostics.md) | | |
| 26 | 30 | | 理解节点配置、代理核心与凭据归属 | [内置代理设计](design/managed-proxy.md) | |
| 27 | 31 | | 构建签名、公证的 macOS 安装包 | [发布 macOS 安装包](releasing.md) | |
| 28 | 32 | | 构建 Windows 安装包与执行平台验收 | [Windows 构建与验收](windows.md#维护者构建与验收) | |
| @@ -0,0 +1,62 @@ | ||
| 1 | 新增:# 日志与诊断包 | |
| 2 | 新增: | |
| 3 | 新增:Cage 将界面、后台、原生窗口和受管子进程的故障记录到本机,便于在故障发生后定位原因。用户从“设置 → 环境与恢复 → 日志与诊断”导出 ZIP;应用无法打开时可使用命令行。日志和诊断包均保存在本机,不自动上传。 | |
| 4 | 新增: | |
| 5 | 新增:## 收集范围 | |
| 6 | 新增: | |
| 7 | 新增:| 来源 | 记录内容 | | |
| 8 | 新增:|---|---| | |
| 9 | 新增:| 控制服务 | 启动、退出、标准输出、错误输出、异常堆栈 | | |
| 10 | 新增:| 后台任务 | 操作开始、完成、取消或失败,以及管理操作输出;界面保留末尾约 24 KB | | |
| 11 | 新增:| 工作台接口 | 错误状态与路由模板、主动返回的错误、处理器异常;不记录请求正文和认证头 | | |
| 12 | 新增:| 工作台界面 | 全局脚本异常、未处理的 Promise 拒绝、React 渲染异常、接口连接失败和原生调用失败 | | |
| 13 | 新增:| 原生窗口 | 启动、导航、WebView 进程异常、桥调用和更新失败;通过本机辅助程序写入同一存储 | | |
| 14 | 新增:| 内置代理 | 配置校验错误、运行输出和非正常退出 | | |
| 15 | 新增:| 虚拟机 | 主机代理的诊断输出,以及 Cage 浏览器、编辑器、显示、音频和 Desktop 服务输出 | | |
| 16 | 新增: | |
| 17 | 新增:终端输入输出、项目文件、剪贴板内容、请求正文、完整配置、浏览历史和登录数据库不作为诊断材料采集。底层虚拟机的串口文件、生命周期协议文件,以及第三方应用自行保存的日志不属于 Cage 诊断存储,也不自动收入诊断包。 | |
| 18 | 新增: | |
| 19 | 新增:## 脱敏与存储 | |
| 20 | 新增: | |
| 21 | 新增:主机日志使用私有配置目录下的 `logs/`,记录格式为 JSONL,包含 UTC 时间、级别、来源、消息和进程号。Unix 文件使用 `0600`、目录使用 `0700`;Windows 沿用仅当前用户与 SYSTEM 可访问的 DACL。 | |
| 22 | 新增: | |
| 23 | 新增:写入前遮盖凭据字段、认证与 Cookie 头、常见 API 密钥和令牌、私钥、网址、邮箱、IP 地址及常见本机文件路径。子进程输出先组合成完整行,再执行脱敏;跨多次写入的密钥仍按同一行处理。超过 24 KiB 的单行整行省略,私钥块整段省略。导出时再次脱敏。自动规则无法识别所有自由文本中的敏感信息,分享前仍应检查诊断包。 | |
| 24 | 新增: | |
| 25 | 新增:| 存储 | 保留与清理 | | |
| 26 | 新增:|---|---| | |
| 27 | 新增:| 本机统一日志 | 最多保留 14 天、总容量 40 MiB,单文件约 5 MiB;跨天或达到大小上限时轮转,优先删除最旧文件 | | |
| 28 | 新增:| 客机 Cage 服务日志 | 独立的 `cage` journal namespace,预算 10 MiB、保留 14 天;服务输出使用与主机相同的脱敏规则,再交给 journald | | |
| 29 | 新增: | |
| 30 | 新增:主机在服务启动、日志写入、查询容量、导出及每小时执行清理,多个进程通过系统文件锁协调写入和轮转。日志时间以文件中最早的事件校验,持续使用的小文件也会到期。应用关闭期间不运行清理,下一次启动时补清。客机由 journald 管理归档及清理,实际占用可能受活动 journal 文件和文件系统开销影响。 | |
| 31 | 新增: | |
| 32 | 新增:旧的后台、代理和安装日志在服务启动时迁入统一存储:只读取有限尾部,脱敏后删除原始文件;超过保留期限的旧文件直接清理。Cage 安装过程直接写入统一日志。上游 agent-vm 独立使用时保留其原有日志行为。 | |
| 33 | 新增: | |
| 34 | 新增:## 导出与故障恢复 | |
| 35 | 新增: | |
| 36 | 新增:三端桌面程序提供本机保存窗口,取消后不生成诊断包。保存先写同目录私有临时文件,完成校验后替换目标文件,失败时保留已有目标。普通浏览器使用文件下载。诊断包生成期间不修改环境或停止任务。 | |
| 37 | 新增: | |
| 38 | 新增:ZIP 只包含固定范围的文件: | |
| 39 | 新增: | |
| 40 | 新增:- `manifest.json`:格式版本、应用版本、操作系统、架构、Go 版本、日志策略和客机收集结果。 | |
| 41 | 新增:- `logs/*.jsonl`:仍在保留范围内的脱敏主机日志。 | |
| 42 | 新增:- `guest/services.log`:客机可访问时,收集最近 150 行 Cage 服务日志,最多 48 KiB。 | |
| 43 | 新增:- `README.txt`:内容范围与分享前检查说明。 | |
| 44 | 新增: | |
| 45 | 新增:客机收集设置超时;离线或读取失败时,诊断包仍包含主机日志,清单记录缺失原因。命令行入口为 `cage diagnostics --json /absolute/path/cage-diagnostics.zip`。它通过本机启动凭证连接控制服务;控制服务不可用或启动记录损坏时直接导出本机日志。 | |
| 46 | 新增: | |
| 47 | 新增:前端每分钟最多接受 20 条上报,队列最多 20 条,单条消息最多 4096 个字符。后台暂时断开时每 5 秒尝试补报;关闭或崩溃的页面无法保留内存队列。服务端每分钟最多接受 60 条界面上报。日志失败不替代原始错误,断电、磁盘不可写、强制终止等情形仍可能丢失最后一段记录。 | |
| 48 | 新增: | |
| 49 | 新增:## 接口与平台职责 | |
| 50 | 新增: | |
| 51 | 新增:| 入口 | 行为 | | |
| 52 | 新增:|---|---| | |
| 53 | 新增:| `GET /api/diagnostics` | 返回保留策略、本机容量及文件数 | | |
| 54 | 新增:| `POST /api/diagnostics/events` | 接受 `frontend`、`react` 来源;限制正文 32 KiB,不接收文件路径 | | |
| 55 | 新增:| `GET /api/diagnostics/export` | 返回完整 ZIP;同一服务只允许同时生成一份 | | |
| 56 | 新增:| 原生 `exportDiagnostics` | 本机保存窗口,再调用统一 CLI;网页不能指定任意保存路径 | | |
| 57 | 新增:| `cage diagnostic-event` | 从标准输入接收原生错误,写入前脱敏 | | |
| 58 | 新增:| `cage log-relay controller\|proxy` | 在子进程外收集输出,控制服务异常退出时仍能保存故障信息 | | |
| 59 | 新增: | |
| 60 | 新增:HTTP 入口沿用工作台的 Host、Origin、会话认证。诊断接口允许持有效工作台会话的锁定页面使用,使登录界面的异常也能记录;不返回账户、代理或项目配置。原生桥继续只接受当前工作台主框架。macOS 的 launchd 通过输出中继启动代理;Windows、Linux 在原有进程身份校验和停止流程下收集代理输出。 | |
| 61 | 新增: | |
| 62 | 新增:客机日志配置随环境组件更新部署。已有运行环境需先保存浏览器和编辑器中的修改,再使用现有的组件更新流程;应用不会为启用日志而静默重启环境。 | |
| @@ -54,6 +54,8 @@ VM 外出站控制由 hostagent 持有。新实例默认关闭外网,guest 内 | ||
| 54 | 54 | |
| 55 | 55 | 全面检查报告最多有效 24 小时。配置变化、VM 重启和新一轮检查会使旧授权失效;检测过程中产生的旧报告不能重新打开已经关闭的网络。后台监测不自行重复故障演练。 |
| 56 | 56 | |
| 57 | 新增:临时观察失败、代理探测失败或授权续期失败后,环境先保持离线,再由独立恢复任务重新执行完整检查;全部关键项通过后恢复联网。失败采用最长五分钟的退避,已知内存压力持续时延后重检。恢复绑定当前 VM、配置、授权代次和人工暂停序号,手动暂停、停止或新检查会使旧请求作废;已确认的配置不匹配不会作为临时故障恢复。见[计算资源与压力恢复](resources.md)。 | |
| 58 | 新增: | |
| 57 | 59 | 暂停不进入普通任务队列,会立即取消检查和后台监测,再关闭出站。放行和续期与暂停串行核对,已撤销的检查不能重新放行。停止环境可取消正在启动或检查的任务;被取消任务的完成消息不会覆盖停止结果。工作台为启动任务记录私有停止标记,分离运行的 hostagent 在初始化前及运行中读取该标记,避免取消后的后台启动继续拉起 VM。标记绑定单个任务,不影响下一次启动。 |
| 58 | 60 | |
| 59 | 61 | 人工暂停意图和暂停序号保存在私有 `network-intent.json`,控制服务启动监测前恢复;后台重启、订阅定期刷新和网卡恢复不会解除暂停。记录缺失时无法判断旧配置的暂停意图,因此默认关闭,等待用户明确恢复;损坏或无法读取时同样保持关闭并提示原因。启动、重检、恢复或应用环境配置,以及手动应用代理配置,可请求恢复;恢复必须先成功保存,且不能覆盖请求提交之后发生的暂停。暂停保存失败仍会撤销当前放行并报错,恢复保存失败也保持关闭。 |
| @@ -0,0 +1,57 @@ | ||
| 1 | 新增:# 计算资源与压力恢复 | |
| 2 | 新增: | |
| 3 | 新增:Cage 按环境内程序的需求调整可用内存。浏览器、编辑器、终端和渲染任务共享同一虚拟机;任务结束后,持续空闲的内存逐步归还主机。资源上限遵循主机份额政策,默认使用一半物理内存及一半逻辑 CPU;小内存机器的内存上限最低为 2 GiB,CPU 最低为一个核心。现有 `AGENT_VM_HOST_SHARE` 覆盖规则继续适用,无法读取主机配置时使用 4 GiB、2 CPU。 | |
| 4 | 新增: | |
| 5 | 新增:CPU 的实际使用时间由主机调度器按负载分配。配置的核心数约束最大并行度,空闲时无需持续占满这些核心。内存的启动容量、当前分配目标、客机可用容量和主机实际占用是不同指标;设置页分别展示上限和客机观测,主机活动监视器还包括虚拟化开销与系统内存管理的影响。 | |
| 6 | 新增: | |
| 7 | 新增:## 用户操作 | |
| 8 | 新增: | |
| 9 | 新增:“设置 → 环境与恢复 → 计算资源”显示自动上限、环境内存用量、当前可用容量、CPU 使用率及本次启动后的系统 OOM 终止计数。内存用量不含可回收缓存。采样失败显示未知,不以过期数据表示正常运行。 | |
| 10 | 新增: | |
| 11 | 新增:Claude Desktop 服务因 OOM 退出时,应用页直接显示内存不足及检查计算资源的提示。状态读取暂时失败与用户操作失败分别保存;下一次读取成功清除读取错误,操作失败仍保留供用户处理。 | |
| 12 | 新增: | |
| 13 | 新增:新环境及已停止环境在启动时应用主机份额。已经运行的环境保持原启动容量;需要提高容量或加载新控制逻辑时,用户点击“重启并应用自动资源配置”,确认保存后重启。正在运行的命令会结束,项目文件、虚拟磁盘和登录资料保留。重启不解除手动暂停网络的状态。 | |
| 14 | 新增: | |
| 15 | 新增:自动分配仍受主机容量限制。持续超出上限的任务可能失败;减少并行渲染、降低任务规模或使用内存更多的机器才会降低其实际资源需求。137 是常见的强制终止退出码,不能单独证明 OOM。诊断中出现同一时段 OOM 计数增加,才是客机发生内存不足终止的直接证据之一。 | |
| 16 | 新增: | |
| 17 | 新增:## 控制位置与平台 | |
| 18 | 新增: | |
| 19 | 新增:```text | |
| 20 | 新增:客机系统指标 → 虚拟机主机后台 → 内存分配目标 → 平台虚拟化设备 | |
| 21 | 新增: ↓ | |
| 22 | 新增: 私有状态与日志 → 工作台资源页面 | |
| 23 | 新增:``` | |
| 24 | 新增: | |
| 25 | 新增:资源循环属于虚拟机的主机后台,与 VM 同生共灭。关闭界面不会停止内存调节,停止 VM 前取消采样并等待控制循环结束。控制能力不暴露给客机,客机观测只能影响既定上限内的分配,不能修改主机份额或其他 VM。 | |
| 26 | 新增: | |
| 27 | 新增:| 平台 | 调整机制 | 当前边界 | | |
| 28 | 新增:|---|---|---| | |
| 29 | 新增:| macOS | Apple Virtualization 的传统 Virtio balloon | 目标不得超过启动容量;宿主处于严重内存压力时暂缓增长 | | |
| 30 | 新增:| Windows | QEMU balloon 命令,经本机 QMP socket | 同样受启动容量约束;采样子进程不弹出控制台 | | |
| 31 | 新增:| Linux | QEMU balloon 命令,经本机 QMP socket | 同样受启动容量约束;客机采用共同的 Linux 指标 | | |
| 32 | 新增: | |
| 33 | 新增:三平台共享策略、状态格式和设置界面;平台编译通过不能代替实机回收测量。Windows 当前运行独立 QEMU,WSL 的自动回收设置不适用于 Cage。 | |
| 34 | 新增: | |
| 35 | 新增:## 调整策略 | |
| 36 | 新增: | |
| 37 | 新增:后台约每两秒通过现有私有 SSH 通道读取内存、交换区、CPU、内存等待时间和 OOM 计数。单次读取限定三秒、16 KiB,不采集命令内容、项目文件或进程参数。 | |
| 38 | 新增: | |
| 39 | 新增:内存紧张时立即请求恢复到启动上限;一般增长保留至少 1 GiB 或活动内存四分之一的余量。只有余量持续充足 30 秒,才按每次 256 MiB 逐步回收。Linux balloon 计数用于确认上一次回收已经完成,并从客机用量中排除已经归还的页面;不同内核是否同步减少 MemTotal 不影响这一口径。最低目标为 2 GiB,且不超过本次启动上限。 | |
| 40 | 新增: | |
| 41 | 新增:采样失败停止缩容。在主机未出现严重压力时,恢复既定上限,以免客机缺内存到无法执行采样命令。主机严重内存压力优先限制继续增长,仍只回收客机有余量的部分。压缩交换区最多为启用时客机内存的四分之一、且不超过 2 GiB,实际使用时才消耗内存,用于缓冲突发申请;它不能增加物理内存,也不能保证任何任务都不会 OOM。内核不支持压缩交换区时保留资源控制并报告服务失败。 | |
| 42 | 新增: | |
| 43 | 新增:资源摘要保存在 VM 私有目录的 `cage-resources.json`,包括时间、进程标识、上限、目标和系统指标。超过十秒的摘要视为过期。目标调整和 OOM 计数增长写入统一脱敏日志。`GET /api/environment/resources` 返回资源状态;`POST` 提交明确的重启应用操作,沿用工作台认证和任务串行规则。 | |
| 44 | 新增: | |
| 45 | 新增:## 内部断网后的恢复 | |
| 46 | 新增: | |
| 47 | 新增:客机或浏览器无法响应联网监测时,现有出口授权仍会收回。连续监测失联导致授权到期也会关闭已有连接;资源优化不会放松出口、DNS、地区和配置检查。 | |
| 48 | 新增: | |
| 49 | 新增:临时观察失败、代理探测失败或授权续期失败后,后台等待并重新执行完整检查;全部必需项目通过后才恢复联网。失败采用逐步退避,间隔最长五分钟。已观测到资源压力时延后重检,避免额外检查争抢资源。 | |
| 50 | 新增: | |
| 51 | 新增:恢复请求绑定 VM 运行标识、配置、出口授权代次和人工暂停序号。排队期间发生手动暂停、停止、配置改变或另一轮检查,旧恢复请求作废。已读回的配置确实不匹配时,不将它作为临时超时自动恢复。人工暂停始终需要用户明确恢复。详细出口条件见[网络检查设计](network-checks.md)。 | |
| 52 | 新增: | |
| 53 | 新增:## 能力依据 | |
| 54 | 新增: | |
| 55 | 新增:- [Apple balloon 设备](https://developer.apple.com/documentation/virtualization/vzvirtiotraditionalmemoryballoondevice)及[目标容量约束](https://developer.apple.com/documentation/virtualization/vzvirtiotraditionalmemoryballoondevice/targetvirtualmachinememorysize):运行时调整需客机配合,且受启动容量限制。 | |
| 56 | 新增:- [QEMU balloon 观测](https://www.qemu.org/docs/master/interop/virtio-balloon-stats.html):客机驱动观测可能不可用或滞后,必须区分请求与实际状态。 | |
| 57 | 新增:- [Linux zram](https://docs.kernel.org/admin-guide/blockdev/zram.html):压缩块设备、动态创建和交换区启用。 | |
| @@ -65,12 +65,28 @@ Desktop 使用编码用户 `cage`、独立的 X11 显示 `:78` 与按需启动 | ||
| 65 | 65 | |
| 66 | 66 | 项目旁的加号、终端工具栏与新建终端快捷键均打开类型选择框。普通终端提供 shell;Claude 终端在所选项目中新建交互 shell,并运行设置中的启动命令,默认 `claude`。命令支持参数及单行 shell 表达式,仅在客机执行;退出 Claude 后返回 shell。命令保存在私有 `workbench.json` 的 `claude_terminal_command` 字段,留空恢复默认,拒绝换行、NUL 和超过 4096 字节的输入。保存不重启环境,也不修改现有终端;刷新或重连不会重复执行启动命令。 |
| 67 | 67 | |
| 68 | 新增:浏览器将 `claude://` 链接成功转交给正在运行的 Claude Desktop 后,工作台自动显示 Claude Desktop。转交失败时保持当前页面;该通知只表示应用接收了链接,登录是否成功由 Claude 自身显示。客机打开链接的脚本通过浏览器服务的认证接口 `/desktop-focus` 发送通知,现有浏览器事件流以 `desktopFocus: true` 传递一次切换请求。通知不包含回调链接和登录凭据,不保存在浏览器状态中,重连或普通状态更新不会重新触发切换。三个主机平台共用此链路。 | |
| 69 | 新增: | |
| 68 | 70 | 应用状态与操作由 `/api/claude-desktop`、`/api/claude-desktop/{install,start,stop}` 提供;安装和启动沿用工作台异步任务。`POST /api/terminals` 的 `kind` 可为 `shell` 或 `claude`,省略时保持普通终端行为。原始启动命令不从新建终端请求接收,只读取已保存偏好。 |
| 69 | 71 | |
| 70 | 72 | Desktop 默认按内容区域的逻辑像素显示,窗口尺寸和侧栏变化会同步调整虚拟屏幕。工具栏的“显示大小”提供 75%、90%、100%、110%、125% 和 150%,默认 100%;较小的值可显示更多内容,较大的值放大文字和控件。偏好保存在当前工作台的本机存储中,调整立即生效,保持应用和画面连接。 |
| 71 | 73 | |
| 74 | 新增:尺寸调整与其他客机控制脚本共用 SSH 执行入口,在客机内明确使用 `/bin/bash --noprofile --norc -c`。SSH 登录仍经过用户的默认 shell,控制脚本的重定向和错误处理由 Bash 执行,避免 zsh 中的 mise 初始化状态使尺寸锁创建提前返回失败。脚本整体经过 shell 引号转义,三个主机平台共用同一执行方式。 | |
| 75 | 新增: | |
| 72 | 76 | 应用以 `--force-device-scale-factor=2` 启动;虚拟屏幕宽高为内容区域的 CSS 尺寸乘以 `2 / 显示大小`,noVNC 将画面等比适配回内容区域。虚拟屏幕每边最多 8192 像素,超过上限时按同一比例缩减宽高。尺寸提交串行执行,快速调整窗口时以最新尺寸为准;失败后最多自动重试三次,持续失败显示“重试调整”。macOS、Windows 与 Linux 共用此显示链路。应用启动缩放参数在下次打开应用时生效,工具栏的显示大小无需重启。 |
| 73 | 77 | |
| 78 | 新增:## 主机输入法 | |
| 79 | 新增: | |
| 80 | 新增:浏览器与 Claude Desktop 共用主机输入法接入:主机负责拼音和候选词,客机应用在自己的输入框内绘制组合文字。选词确认、更新和取消分别传递;普通按键与文字传递共用 noVNC 输入队列,确认后的回车必须等待文字提交完成。全角问号 `?`、逗号等直接产生的字符走文字通道,避免有限的 X11 按键映射丢失字符。Desktop 的兼容粘贴路径会暂时释放远端已按下的修饰键,完成 Ctrl+V 后恢复,保证按住 Shift 输入问号时行为正确。 | |
| 81 | 新增: | |
| 82 | 新增:每个客机图形会话有独立的 IBus 输入桥与权限为 0600 的 Unix socket。浏览器的会话总线只允许 IBus portal 激活;Desktop 沿用自身的会话总线与密钥环。控制请求通过现有认证服务的 `POST /api/input` 进入,不增加网络监听端口。浏览器服务直接访问自己的输入桥,通过固定 sudo helper 把 Desktop 请求交给主用户的输入桥。文字不写入日志、诊断包或状态文件。 | |
| 83 | 新增: | |
| 84 | 新增:输入协议的 `target` 为 `browser` 或 `desktop`,`id` 为活动浏览器标签标识或 `desktop`;`mode` 为 `status`、`begin`、`update`、`commit`、`cancel`。开始组合时绑定客机输入上下文和随机组合会话标识,更新附带递增序号。选段范围采用 UTF-16,下游转换为 IBus 字符索引。目标失焦、标签切换、过期或重复的提交被拒绝;用户点击另一个输入框前先取消组合。程序主动改变焦点时,应用可能按自身原生规则确认已有组合文字,迟到的确认不会进入新输入框。 | |
| 85 | 新增: | |
| 86 | 新增:活动组合通过状态请求续期,断连后十秒内清理未确认文字。文字光标坐标来自客机输入上下文,按实际画布位置和像素比例转换;主机窗口移动由各平台原生坐标转换负责。macOS 使用 AppKit 文本客户端,Windows 使用 Win32 原生编辑控件与 IMM,Linux 使用 GTK 输入上下文。原生接入仅在当前远端输入框确认可用时启用;密码框、未完成组件更新的环境等继续使用已有的确认文字输入方式。 | |
| 87 | 新增: | |
| 88 | 新增:实现和验收范围见[输入法实施记录](../test-reports/2026-11-04-native-ime/progress.md)。三平台构建通过与真实系统输入法验收分别记录,不能互相替代。 | |
| 89 | 新增: | |
| 74 | 90 | ## 声音输出 |
| 75 | 91 | |
| 76 | 92 | 浏览器、Claude Desktop 和环境内其他程序的声音通过工作台在本机播放,输出设备由本机系统选择。底部提供静音和音量控制,偏好保存在当前工作台的本地存储中。首次播放如果受到 WebView 自动播放限制,点击页面或“启用声音”即可继续。切换标签、项目或设置页保持声音;静音、停止环境、锁定账户及退出应用关闭播放连接,重新连接从当前声音开始。 |
| @@ -0,0 +1,80 @@ | ||
| 1 | 新增:# 主机输入法与远端应用的原生输入体验 | |
| 2 | 新增: | |
| 3 | 新增:日期:2026-11-04。本文供维护者决定实现方向;先说明用户能获得什么,再列实验依据与需要接入的边界。 | |
| 4 | 新增: | |
| 5 | 新增:## 结论与用户体验 | |
| 6 | 新增: | |
| 7 | 新增:完整方案有可行路径:继续使用主机输入法、候选词和个人词库,让远端应用在自己的输入框内显示拼音、分词与组合文字,再把文字光标位置传回主机定位候选窗。 | |
| 8 | 新增: | |
| 9 | 新增:客机浏览器的关键链路已经通过独立实验。正式交付仍需实现三平台主机接入,并在 Claude Desktop 的真实编辑器中验收。可行性实验使用独立会话。后续实现和实际输入验收单独记录于[实施进度](../test-reports/2026-11-04-native-ime/progress.md),该记录区分源码接入、构建和真实输入体验。 | |
| 10 | 新增: | |
| 11 | 新增:例如输入 `ni'hao` 时,远端输入框应原位出现带组合标记的文字;选中“你好”后只确认一次。按取消键撤掉未确认文字;移动文字光标或跨行后,下一次输入的候选窗应出现在新的输入位置。主机上的地址栏、设置表单和终端继续由各自的本地输入控件处理。 | |
| 12 | 新增: | |
| 13 | 新增:## 已验证的部分 | |
| 14 | 新增: | |
| 15 | 新增:实验使用当前 Linux 客机的 Chromium 156.0.8078.73、GTK 3、IBus 1.5.32;独立显示、会话总线和临时用户目录。软件包仅通过 apt 下载、校验和解压,没有安装进系统。输入内容均为固定测试文字。后续图形实验限制在 700 MiB 内存的独立服务中,服务退出时回收全部进程。 | |
| 16 | 新增: | |
| 17 | 新增:| 问题 | 实验结果 | 含义 | | |
| 18 | 新增:|---|---|---| | |
| 19 | 新增:| 拼音能否由远端输入框原位绘制 | `prefix suffix` 的光标处显示 `prefix ni'haosuffix`,产生真实组合输入事件 | 不需要覆盖远端输入框,也不依赖剪贴板来显示组合文字 | | |
| 20 | 新增:| 确认时会不会重复输入 | 最终值为 `prefix 你好suffix` | 组合更新与提交可分别传递 | | |
| 21 | 新增:| 已有选区能否替换 | “你好”选区被确认后的“是”替换 | 应用自己的编辑器负责选区操作 | | |
| 22 | 新增:| 取消会不会留下拼音 | 撤销组合文字后恢复 `prefix 是suffix` | 本次无选区的取消场景通过;其他取消语义仍须验收 | | |
| 23 | 新增:| 富文本与 emoji | 富文本内原位组合,最终得到 `rich text中🙂` | 普通输入框与浏览器富文本均有基础支持 | | |
| 24 | 新增:| 光标坐标能否跨行变化 | 两个位置分别报告 `[242,734,0,54]`、`[302,790,0,52]` | 有实际文字位置数据,坐标需结合显示缩放转换 | | |
| 25 | 新增:| 第一次聚焦是否立即有坐标 | 初始坐标为空 | 不能把最近点击位置当作精确光标位置 | | |
| 26 | 新增:| 能否主动刷新坐标并避免字母重复 | 输入桥消费主机已处理的真实 `n` 按键,得到 `[332,614,0,52]`,原文仍为 `prefix suffix` | 值得采用“主机处理组合输入、客机消费相应按键”的同步方式 | | |
| 27 | 新增:| 密码框是否沿用相同处理 | 组合文字未出现在密码框,输入类型提示也未返回有效值 | 必须单独识别安全输入状态;不能仅依赖输入类型字段 | | |
| 28 | 新增: | |
| 29 | 新增:以上是客机输入链路实验。程序化聚焦和选区配合原生 X11 按键完成测试;没有冒充主机真实中文输入法的完整人工验收。结果、原型和重现方法见[实验记录](../test-reports/2026-11-04-native-ime/README.md)。 | |
| 30 | 新增: | |
| 31 | 新增:## 推荐的职责划分 | |
| 32 | 新增: | |
| 33 | 新增:主机输入法负责按键解释、候选词、选词、组合范围和确认。客机应用负责文本布局、选区替换及组合文字绘制。Cage 负责有顺序地传递组合输入,以及把客机坐标转换成主机屏幕坐标。 | |
| 34 | 新增: | |
| 35 | 新增:建议为浏览器用户和 Desktop 用户各自提供私有的 IBus 输入桥,与各自的显示和会话总线保持相同生命周期。控制通道沿已有认证服务与 SSH 传输,不创建公开端口。正式实现可以采用小型原生客机服务;实验中的 Python、GI 和完整 IBus 解压目录不代表产品必须引入同样的依赖集合。 | |
| 36 | 新增: | |
| 37 | 新增:现有 noVNC 链路继续承接画面、鼠标和普通按键。由主机输入法处理的按键进入组合会话后,由客机输入桥消费,促使应用刷新光标信息;组合文字通过输入法接口更新。这个顺序已在 Chromium 证明可行,生产实现还需验证候选翻页、修饰键、重复键和切换输入框时的并发行为。 | |
| 38 | 新增: | |
| 39 | 新增:三平台共用客机桥和输入会话协议;主机接入点分别验证: | |
| 40 | 新增: | |
| 41 | 新增:| 主机 | 推荐接入点 | 本轮证据与范围 | | |
| 42 | 新增:|---|---|---| | |
| 43 | 新增:| macOS | AppKit 原生文本输入客户端,提供组合文字、选区及字符屏幕矩形 | 官方接口契约已查证;本机 WKWebView 实测 `EditContext` 为 `undefined`,原生接入尚未实现 | | |
| 44 | 新增:| Windows | 原生文本输入控件或 TSF 文本存储,向系统提供文字范围的屏幕矩形 | 官方接口契约已查证;需要用实际 WebView2 宿主与系统输入法测试 | | |
| 45 | 新增:| Linux | 原生 GTK 输入上下文,接收组合文字和格式,设置候选窗定位 | 官方接口契约已查证;本轮客机 GTK 实验通过,主机 Cage 原生窗口尚未接入 | | |
| 46 | 新增: | |
| 47 | 新增:普通网页组合事件能提供文字更新,但不足以证明三平台的分词格式、替换范围和候选窗定位均满足完整目标。原生主机适配是推荐方向,三平台验收须分别完成。 | |
| 48 | 新增: | |
| 49 | 新增:## 必须在实现中保持的契约 | |
| 50 | 新增: | |
| 51 | 新增:- **输入目标与顺序。** 每次聚焦生成新的目标标识与组合会话,更新带递增序号;浏览器切标签、切应用、失焦和断连均终止旧会话。迟到的确认不得进入新的输入框。 | |
| 52 | 新增:- **确认语义。** 组合更新、确认和取消独立传递。普通按键路径与组合路径共用顺序,候选确认的回车不能又变成远端提交消息的回车。 | |
| 53 | 新增:- **字符范围。** 明确主机 UTF-16、IBus 字符索引和 UTF-8 字节偏移之间的转换,包含 emoji 与组合字符;不能直接复用字符串长度。 | |
| 54 | 新增:- **显示坐标。** 客机文字矩形转换时包含 2 倍显示像素、Desktop 缩放、画面适配、侧栏、窗口位置和主机屏幕缩放。零宽光标有效,零高或过期矩形不能当作可用定位。 | |
| 55 | 新增:- **输入格式。** 保留组合内的选中片段、光标位置和下划线;本次原型只发送整段下划线,尚未验证主机分词格式。 | |
| 56 | 新增:- **密码与数据范围。** 安全输入状态需要可靠识别。输入文字和周边内容不进入日志、诊断导出或持久存储;仅在活动输入会话中传递完成编辑所需的数据。 | |
| 57 | 新增:- **完成边界。** 接口成功应区分已收到、已交给活动输入上下文、已确认提交。失焦后不得盲目重试提交。 | |
| 58 | 新增: | |
| 59 | 新增:这些属于新的跨端输入契约,本文记录推荐方案,尚未把它们当作当前产品已实现的能力。 | |
| 60 | 新增: | |
| 61 | 新增:## 其他路线与未解决项 | |
| 62 | 新增: | |
| 63 | 新增:浏览器已有的调试控制通道可以发送组合文字;Linux 输入法桥则有机会让浏览器和 Desktop 共用同一套协议。Claude Desktop 4.4212.0 的隔离启动明确拒绝调试参数,应用资源校验也限制了替换测试资源,因此本轮没有通过调试通道测试其真实编辑器。正式实现应使用应用支持的 Linux 输入法入口,并在真实应用中验收。 | |
| 64 | 新增: | |
| 65 | 新增:辅助功能接口可作为补充坐标来源。实验中默认启用辅助功能状态仍未收到 Chromium 事件;显式开启渲染器辅助功能后收到普通输入框坐标与密码角色。富文本末尾部分事件返回零矩形,因此不能把该接口作为所有输入框精确定位的唯一依据。真实按键由输入桥消费的实验,为继续研究实时光标同步提供了更直接的路径。 | |
| 66 | 新增: | |
| 67 | 新增:本轮未覆盖主机真实中文输入法的候选翻页与分词格式、日本语/韩语、多显示器、不同缩放、编辑器自绘输入区域、切换焦点时的迟到提交、密码框完整行为,以及 Claude Desktop 真实输入框。要宣称“原生无感”,必须完成这些与产品支持范围相符的验收,不能只以 API 调用或客机实验通过为依据。 | |
| 68 | 新增: | |
| 69 | 新增:## 一手来源 | |
| 70 | 新增: | |
| 71 | 新增:以下资料查询日期均为 2026-11-04。实现方向是根据接口与本地实验作出的判断,不是资料对 Cage 的兼容承诺。 | |
| 72 | 新增: | |
| 73 | 新增:- [IBus Engine](https://ibus.github.io/docs/ibus-1.5/IBusEngine.html):组合文字、提交、光标位置和按键处理接口。 | |
| 74 | 新增:- [Chromium 的 GTK 输入上下文实现](https://github.com/chromium/chromium/blob/main/ui/gtk/input_method_context_impl_gtk.cc):组合文字及属性转换;光标位置在按键处理时传给 GTK,密码框使用简单输入上下文。 | |
| 75 | 新增:- [Chromium 的 Linux 输入方法实现](https://github.com/chromium/chromium/blob/main/ui/base/ime/linux/input_method_auralinux.cc):从应用文字客户端获取光标矩形,并传给输入上下文。 | |
| 76 | 新增:- [AppKit 文本输入客户端](https://developer.apple.com/documentation/appkit/nstextinputclient):组合文字、选区、替换范围和字符位置的主机契约。 | |
| 77 | 新增:- [Windows 文本范围位置接口](https://learn.microsoft.com/en-us/windows/win32/api/textstor/nf-textstor-itextstoreacp2-gettextext):文本范围的屏幕坐标契约。 | |
| 78 | 新增:- [GTK 输入上下文](https://docs.gtk.org/gtk3/class.IMContext.html)与[光标位置](https://docs.gtk.org/gtk3/method.IMContext.set_cursor_location.html):主机组合输入与候选窗定位接口。 | |
| 79 | 新增:- [EditContext 规范](https://www.w3.org/TR/edit-context/):由绘制者提供字符矩形的浏览器输入接口;本机是否具备能力以探针结果为准。 | |
| 80 | 新增:- [AT-SPI 字符矩形](https://gnome.pages.gitlab.gnome.org/at-spi2-core/libatspi/method.Text.get_character_extents.html):辅助功能坐标接口,其在 Cage 中的适用范围仍需实测。 | |
| @@ -2,6 +2,14 @@ | ||
| 2 | 2 | |
| 3 | 3 | 先找到你当前遇到的现象。修复后优先使用页面中的重试、重检或恢复入口;删除配置会丢失诊断线索,也可能影响虚拟磁盘,不作为常规排障步骤。 |
| 4 | 4 | |
| 5 | 新增:## 任务退出 137 或重任务后内部断网 | |
| 6 | 新增: | |
| 7 | 新增:137 通常表示进程被强制终止,单凭退出码不能判断是否内存不足。到“设置 → 环境与恢复 → 计算资源”查看本次环境启动后的 OOM 计数、内存上限和用量,再导出诊断日志。OOM 计数增加可确认客机曾因内存不足终止进程;没有增加时还需排查超时、任务取消或其他强制终止来源。 | |
| 8 | 新增: | |
| 9 | 新增:自动资源管理会在启动容量内增长和回收内存。运行中的旧环境如仍使用较小上限,可以先保存内容,再点击“重启并应用自动资源配置”;重启会结束运行中的命令。达到上限后应降低渲染或编译并行量,自动管理无法让有限内存承载无限任务。 | |
| 10 | 新增: | |
| 11 | 新增:重任务可能让客机或浏览器无法及时响应联网检查,触发 Cage 收回内部外网授权。恢复任务会自动进行完整复检,检查全部通过才恢复;手动暂停不会自动解除。网络仍未恢复时,查看具体失败项、所选代理和出口规则,不要仅凭断网现象判断主机网络故障。资源指标与平台范围见[计算资源说明](design/resources.md)。 | |
| 12 | 新增: | |
| 5 | 13 | ## 下载或安装受阻 |
| 6 | 14 | |
| 7 | 15 | **GitHub 显示 404,或看不到安装包。** 仓库与公开发布的附件无需仓库授权。从[项目主页](https://lee-xeo.github.io/Claude-Cage/#download)点击“下载应用”并选择平台,检查网络与链接是否完整。macOS 使用 `.dmg`,Windows 使用 `.exe` 安装器,Debian/Ubuntu Linux 使用 `.deb`。Release 中的源码压缩包用于开发,不能当作安装包使用;尚无公开安装包的平台会提供安装与构建说明。 |
| @@ -75,6 +83,8 @@ Cage 需要先选择自己的代理。首次首页点击“配置网络与代理 | ||
| 75 | 83 | |
| 76 | 84 | 先将右上角“显示大小”设为 100%,窗口和侧栏变化时画面会自动适配。若需要更多内容空间,可选择 90% 或 75%。出现“画面尺寸未能同步”时点击“重试调整”;仍未恢复时保存工作、关闭 Claude Desktop 后重新打开,使当前环境的应用缩放参数生效。 |
| 77 | 85 | |
| 86 | 新增:旧构建的尺寸控制脚本可能受到客机 zsh 中 mise 初始化的影响,持续返回尺寸调整失败。此时需要使用包含控制脚本修正的 Cage 构建。该修正兼容已有客机配置,在控制入口明确选择脚本解释器。复现条件和验证范围见[尺寸调整排查记录](test-reports/2026-11-04-desktop-resize/README.md)。 | |
| 87 | 新增: | |
| 78 | 88 | ## Claude 登录或请求失败 |
| 79 | 89 | |
| 80 | 90 | Cage 不自动读取主机上的 Claude 登录。请在 Cage 终端运行 `claude`,按提示在 Cage 浏览器中完成授权;需要手动打开时复制完整授权链接到 Cage 地址栏。 |
| @@ -101,8 +111,16 @@ Cage 不自动读取主机上的 Claude 登录。请在 Cage 终端运行 `claud | ||
| 101 | 111 | |
| 102 | 112 | 节点列表、当前选择和实际出口统一由 Cage 的代理管理器维护。未配置、未应用或核心停止时,外网保持关闭。若列表与实际联网状态不一致,请在诊断页重新应用当前节点并检查报告;不要修改生成的本地出口地址或启动其他代理程序占用 Cage 端口。 |
| 103 | 113 | |
| 114 | 新增:## 导出诊断包 | |
| 115 | 新增: | |
| 116 | 新增:打开“设置 → 环境与恢复 → 日志与诊断”,点击“导出诊断包”,选择本机保存位置。macOS、Windows 和 Linux 使用相同入口;环境停止时也能导出本机日志。诊断包不会自动上传。 | |
| 117 | 新增: | |
| 118 | 新增:日志写入前自动遮盖常见密码、令牌、认证头、网址、邮箱、IP 和本机路径;主机日志最多 40 MiB,客机 Cage 服务日志预算 10 MiB,最多保留 14 天。诊断包包含脱敏日志、版本和收集状态,不收集终端内容、项目文件或完整配置。已有环境的客机日志配置随环境组件更新生效。 | |
| 119 | 新增: | |
| 120 | 新增:若应用界面无法打开,可运行 `cage diagnostics --json /absolute/path/cage-diagnostics.zip`。macOS 应用内的命令位于 `Cage.app/Contents/Resources/cage`,Windows 位于安装目录的 `resources\cage.exe`,Linux 位于应用目录的 `cage`。控制服务无法连接时仍可导出本机日志;文件必须保存到本机的绝对路径。技术细节见[日志与诊断设计](design/diagnostics.md)。 | |
| 121 | 新增: | |
| 104 | 122 | ## 提交问题时提供什么 |
| 105 | 123 | |
| 106 | 删除:在 [GitHub Issues](https://github.com/Lee-xeo/Claude-Cage/issues) 提供 Cage 版本、操作系统版本、处理器架构、操作步骤、期望结果、实际错误及发生阶段。可以附裁剪后的状态截图或经过检查的日志片段。 | |
| 124 | 新增:在 [GitHub Issues](https://github.com/Lee-xeo/Claude-Cage/issues) 提供 Cage 版本、操作系统版本、处理器架构、操作步骤、期望结果、实际错误及发生阶段。可以附裁剪后的状态截图或经过检查的诊断包。 | |
| 107 | 125 | |
| 108 | 126 | 不要上传整个 `~/.claude-cage/`、完整代理配置、订阅链接、账户令牌、授权 URL、项目内容或未检查的诊断输出。网络报告可能包含出口 IP,截图也可能包含项目路径,分享前请按需要遮盖。涉及凭据泄露或隔离绕过的问题,请先使用仓库提供的私密安全报告入口。 |
| @@ -6,6 +6,7 @@ import { readFileSync, writeFileSync, mkdirSync, existsSync, rmSync, constants } | ||
| 6 | 6 | import { open } from "node:fs/promises"; |
| 7 | 7 | import http from "node:http"; |
| 8 | 8 | import { auditBrowser } from "./browser-audit.mjs"; |
| 9 | 新增:import { nativeInput } from "./native-input.mjs"; | |
| 9 | 10 | import { DownloadManager } from "./browser-downloads.mjs"; |
| 10 | 11 | import { UploadManager, uploadLimit } from "./browser-uploads.mjs"; |
| 11 | 12 | import { timingSafeEqual } from "node:crypto"; |
| @@ -323,9 +324,9 @@ function publicState() { | ||
| 323 | 324 | })), |
| 324 | 325 | }; |
| 325 | 326 | } |
| 326 | 删除:function broadcastState(focus = false) { | |
| 327 | 新增:function broadcastState(focus = false, desktopFocus = false) { | |
| 327 | 328 | const payload = |
| 328 | 删除: "data: " + JSON.stringify({ ...publicState(), focus }) + "\n\n"; | |
| 329 | 新增: "data: " + JSON.stringify({ ...publicState(), focus, desktopFocus }) + "\n\n"; | |
| 329 | 330 | for (const stream of events) stream.write(payload); |
| 330 | 331 | } |
| 331 | 332 | setInterval(() => { |
| @@ -461,6 +462,11 @@ const server = http.createServer(async (req, res) => { | ||
| 461 | 462 | if (text.length > (req.url === "/paste-image" ? 28 * 1024 * 1024 : 65536)) throw new Error("Request too large"); |
| 462 | 463 | } |
| 463 | 464 | const input = JSON.parse(text || "{}"); |
| 465 | 新增: if (req.url === "/desktop-focus") { | |
| 466 | 新增: broadcastState(false, true); | |
| 467 | 新增: res.end('{"ok":true}'); | |
| 468 | 新增: return; | |
| 469 | 新增: } | |
| 464 | 470 | if (req.url === "/upload-start" || req.url === "/upload-finish") { |
| 465 | 471 | const result = await mutate(async () => { |
| 466 | 472 | const tabId = req.url === "/upload-start" ? input.id : uploads.request(input.id).tabId; |
| @@ -500,6 +506,12 @@ const server = http.createServer(async (req, res) => { | ||
| 500 | 506 | if (req.url === "/new") return newTab(input.url || undefined); |
| 501 | 507 | if (req.url === "/editor") return editor(input.workspace || config.workspace); |
| 502 | 508 | if (req.url === "/editor-restart") return restartEditor(input.workspace); |
| 509 | 新增: if (req.url === "/ime") { | |
| 510 | 新增: if (!["browser", "desktop"].includes(input.target)) throw new Error("Input target is invalid"); | |
| 511 | 新增: if (input.target === "browser" && input.mode !== "cancel" && | |
| 512 | 新增: (input.id !== activeId || !targets.has(input.id))) throw new Error("Input target changed"); | |
| 513 | 新增: return nativeInput(input); | |
| 514 | 新增: } | |
| 503 | 515 | const id = input.id || activeId; |
| 504 | 516 | if (!targets.has(id)) throw new Error("Tab no longer exists"); |
| 505 | 517 | switch (req.url) { |
| @@ -12,7 +12,7 @@ printf '正在准备安装依赖…\n' | ||
| 12 | 12 | sudo env DEBIAN_FRONTEND=noninteractive APT_CONFIG="${CAGE_APT_CONFIG:-/dev/null}" apt-get -o DPkg::Lock::Timeout=60 update </dev/null |
| 13 | 13 | # Satisfy the vendor's kde-cli-tools | ... | libglib2.0-bin dependency before |
| 14 | 14 | # resolving Claude, so apt does not pull in a KDE/Qt desktop toolchain. |
| 15 | 删除:sudo env DEBIAN_FRONTEND=noninteractive APT_CONFIG="${CAGE_APT_CONFIG:-/dev/null}" apt-get -o DPkg::Lock::Timeout=60 install -y --no-install-recommends ca-certificates curl gnupg dbus-x11 xauth x11-utils x11-xserver-utils tigervnc-standalone-server tigervnc-scraping-server tigervnc-tools openbox gnome-keyring gcr bubblewrap socat openssh-client libglib2.0-bin </dev/null | |
| 15 | 新增:sudo env DEBIAN_FRONTEND=noninteractive APT_CONFIG="${CAGE_APT_CONFIG:-/dev/null}" apt-get -o DPkg::Lock::Timeout=60 install -y --no-install-recommends ca-certificates curl gnupg dbus-x11 xauth x11-utils x11-xserver-utils tigervnc-standalone-server tigervnc-scraping-server tigervnc-tools openbox gnome-keyring gcr bubblewrap socat openssh-client libglib2.0-bin ibus ibus-gtk3 gir1.2-ibus-1.0 python3-gi </dev/null | |
| 16 | 16 | temporary=$(mktemp -d) |
| 17 | 17 | trap 'rm -rf "$temporary"' EXIT |
| 18 | 18 | printf '正在验证 Anthropic 安装源…\n' |
| @@ -56,7 +56,7 @@ for i in $(seq 1 100); do | ||
| 56 | 56 | done |
| 57 | 57 | test -S "$XDG_RUNTIME_DIR/files.sock" |
| 58 | 58 | export GTK_USE_PORTAL=1 |
| 59 | 删除:claude-desktop --force-device-scale-factor=2 --xdg-portal-required-version=3 & | |
| 59 | 新增:/usr/local/bin/cage-input-session claude-desktop --force-device-scale-factor=2 --xdg-portal-required-version=3 & | |
| 60 | 60 | app_pid=$! |
| 61 | 61 | # The service becomes ready only after the application has opened a window. |
| 62 | 62 | for i in $(seq 1 200); do |
| @@ -28,7 +28,7 @@ func ClaudeDesktopInstallScript() string { | ||
| 28 | 28 | // Provisioning is independent of the browser and never restarts it. Desktop |
| 29 | 29 | // services are deliberately not enabled at boot: the user opens the app. |
| 30 | 30 | func ClaudeDesktopProvisionScript() string { |
| 31 | 删除: return "set -euo pipefail\n" + fileInputScript() + | |
| 31 | 新增: return "set -euo pipefail\n" + nativeInputScript() + fileInputScript() + | |
| 32 | 32 | "sudo install -d -m 0755 /etc/claude-cage\n" + |
| 33 | 33 | "sudo tee /usr/local/bin/cage-claude-session >/dev/null <<'CAGE_CLAUDE_SESSION'\n" + claudeDesktopSession + "\nCAGE_CLAUDE_SESSION\n" + |
| 34 | 34 | "sudo tee /usr/local/bin/cage-claude-open >/dev/null <<'CAGE_CLAUDE_OPEN'\n" + claudeDesktopOpen + "\nCAGE_CLAUDE_OPEN\n" + |
| @@ -56,7 +56,8 @@ Environment=HOME=/home/cage | ||
| 56 | 56 | EnvironmentFile=/etc/claude-cage/environment |
| 57 | 57 | RuntimeDirectory=cage-desktop |
| 58 | 58 | RuntimeDirectoryMode=0700 |
| 59 | 删除:ExecStart=/usr/local/bin/cage-claude-session | |
| 59 | 新增:ExecStart=/usr/local/bin/cage-log-run /usr/local/bin/cage-claude-session | |
| 60 | 新增:LogNamespace=cage | |
| 60 | 61 | KillMode=control-group |
| 61 | 62 | TimeoutStartSec=45 |
| 62 | 63 | TimeoutStopSec=20 |
| @@ -1,6 +1,9 @@ | ||
| 1 | 1 | package cage |
| 2 | 2 | |
| 3 | 3 | import ( |
| 4 | 新增: "encoding/json" | |
| 5 | 新增: "net/http" | |
| 6 | 新增: "net/http/httptest" | |
| 4 | 7 | "os" |
| 5 | 8 | "os/exec" |
| 6 | 9 | "path/filepath" |
| @@ -8,6 +11,81 @@ import ( | ||
| 8 | 11 | "testing" |
| 9 | 12 | ) |
| 10 | 13 | |
| 14 | 新增:func TestDesktopCallbackFocusAfterHandoff(t *testing.T) { | |
| 15 | 新增: node, err := exec.LookPath("node") | |
| 16 | 新增: if err != nil { | |
| 17 | 新增: t.Skip("node unavailable") | |
| 18 | 新增: } | |
| 19 | 新增: for _, tc := range []struct { | |
| 20 | 新增: name, url, path 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 | 新增: } { | |
| 27 | 新增: t.Run(tc.name, func(t *testing.T) { | |
| 28 | 新增: dir := t.TempDir() | |
| 29 | 新增: type request struct{ Path, Auth, URL string } | |
| 30 | 新增: requests := make(chan request, 2) | |
| 31 | 新增: server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
| 32 | 新增: var body struct { | |
| 33 | 新增: URL string `json:"url"` | |
| 34 | 新增: } | |
| 35 | 新增: _ = json.NewDecoder(r.Body).Decode(&body) | |
| 36 | 新增: requests <- request{r.URL.Path, r.Header.Get("Authorization"), body.URL} | |
| 37 | 新增: w.Write([]byte(`{"ok":true}`)) | |
| 38 | 新增: })) | |
| 39 | 新增: defer server.Close() | |
| 40 | 新增: config := filepath.Join(dir, "control.json") | |
| 41 | 新增: if err := os.WriteFile(config, []byte(`{"token":"test-only"}`), 0600); err != nil { | |
| 42 | 新增: t.Fatal(err) | |
| 43 | 新增: } | |
| 44 | 新增: // Preserve the production shell flow; sudo only substitutes the two | |
| 45 | 新增: // guest identities and the app. Node performs the real HTTP request. | |
| 46 | 新增: sudo := "#!/bin/sh\nshift\nuser=$1\nshift\nif [ \"$user\" = cage ]; then exit \"$CALLBACK_EXIT\"; fi\nshift\nexec \"$TEST_NODE\" \"$@\"\n" | |
| 47 | 新增: if err := os.WriteFile(filepath.Join(dir, "sudo"), []byte(sudo), 0755); err != nil { | |
| 48 | 新增: t.Fatal(err) | |
| 49 | 新增: } | |
| 50 | 新增: script := strings.ReplaceAll(guestOpen, "/etc/claude-cage/browser-control.json", config) | |
| 51 | 新增: script = strings.ReplaceAll(script, "http://127.0.0.1:18500", server.URL) | |
| 52 | 新增: code := "0" | |
| 53 | 新增: if tc.fail { | |
| 54 | 新增: code = "1" | |
| 55 | 新增: } | |
| 56 | 新增: cmd := exec.Command("sh", "-c", script, "cage-open", tc.url) | |
| 57 | 新增: cmd.Env = append(os.Environ(), "PATH="+dir+":"+os.Getenv("PATH"), "TEST_NODE="+node, "CALLBACK_EXIT="+code) | |
| 58 | 新增: out, err := cmd.CombinedOutput() | |
| 59 | 新增: if tc.fail { | |
| 60 | 新增: if err == nil { | |
| 61 | 新增: t.Fatal("failed handoff reported success") | |
| 62 | 新增: } | |
| 63 | 新增: select { | |
| 64 | 新增: case r := <-requests: | |
| 65 | 新增: t.Fatalf("failed handoff emitted focus: %+v", r) | |
| 66 | 新增: default: | |
| 67 | 新增: } | |
| 68 | 新增: return | |
| 69 | 新增: } | |
| 70 | 新增: if err != nil { | |
| 71 | 新增: t.Fatalf("%v: %s", err, out) | |
| 72 | 新增: } | |
| 73 | 新增: select { | |
| 74 | 新增: case r := <-requests: | |
| 75 | 新增: wantURL := "" | |
| 76 | 新增: if tc.path == "/new" { | |
| 77 | 新增: wantURL = tc.url | |
| 78 | 新增: } | |
| 79 | 新增: if r.Path != tc.path || r.Auth != "Bearer test-only" || r.URL != wantURL { | |
| 80 | 新增: t.Fatalf("unexpected request: %+v", r) | |
| 81 | 新增: } | |
| 82 | 新增: default: | |
| 83 | 新增: t.Fatal("handoff notification missing") | |
| 84 | 新增: } | |
| 85 | 新增: }) | |
| 86 | 新增: } | |
| 87 | 新增:} | |
| 88 | 新增: | |
| 11 | 89 | func TestClaudeDesktopInstallerRejectsUntrustedKey(t *testing.T) { |
| 12 | 90 | dir := t.TempDir() |
| 13 | 91 | commands := map[string]string{ |
| @@ -29,7 +29,8 @@ Environment=PULSE_RUNTIME_PATH=/run/cage-audio/runtime | ||
| 29 | 29 | Environment=PULSE_STATE_PATH=/run/cage-audio/state |
| 30 | 30 | RuntimeDirectory=cage-audio |
| 31 | 31 | RuntimeDirectoryMode=0750 |
| 32 | 删除:ExecStart=/usr/bin/pulseaudio -n --daemonize=no --exit-idle-time=-1 --disallow-exit --disallow-module-loading --disable-shm=true --realtime=no --high-priority=no --use-pid-file=no --file=/etc/claude-cage/audio.pa | |
| 32 | 新增:ExecStart=/usr/local/bin/cage-log-run /usr/bin/pulseaudio -n --daemonize=no --exit-idle-time=-1 --disallow-exit --disallow-module-loading --disable-shm=true --realtime=no --high-priority=no --use-pid-file=no --file=/etc/claude-cage/audio.pa | |
| 33 | 新增:LogNamespace=cage | |
| 33 | 34 | Restart=on-failure |
| 34 | 35 | RestartSec=1 |
| 35 | 36 | TimeoutStopSec=5 |
| @@ -0,0 +1,39 @@ | ||
| 1 | 新增:# A small compressed swap area absorbs short allocation bursts while the host | |
| 2 | 新增:# adjusts the balloon. It consumes RAM only as used and is bounded at 2 GiB. | |
| 3 | 新增:sudo tee /usr/local/bin/cage-memory-start >/dev/null <<'SCRIPT' | |
| 4 | 新增:#!/bin/sh | |
| 5 | 新增:set -eu | |
| 6 | 新增:if [ -f /run/cage-zram-device ]; then | |
| 7 | 新增: device=$(cat /run/cage-zram-device) | |
| 8 | 新增: if grep -q "^$device " /proc/swaps; then exit 0; fi | |
| 9 | 新增:fi | |
| 10 | 新增:modprobe zram | |
| 11 | 新增:number=$(cat /sys/class/zram-control/hot_add) | |
| 12 | 新增:device=/dev/zram$number | |
| 13 | 新增:cleanup() { echo "$number" > /sys/class/zram-control/hot_remove; } | |
| 14 | 新增:trap cleanup EXIT | |
| 15 | 新增:size=$(awk '/^MemTotal:/ { n=int($2*1024/4); if(n>2147483648)n=2147483648; printf "%.0f",n }' /proc/meminfo) | |
| 16 | 新增:echo "$size" > "/sys/block/zram$number/disksize" | |
| 17 | 新增:mkswap "$device" >/dev/null | |
| 18 | 新增:swapon -p 100 "$device" | |
| 19 | 新增:printf '%s\n' "$device" > /run/cage-zram-device | |
| 20 | 新增:trap - EXIT | |
| 21 | 新增:SCRIPT | |
| 22 | 新增:sudo chmod 0755 /usr/local/bin/cage-memory-start | |
| 23 | 新增:sudo tee /etc/systemd/system/cage-memory.service >/dev/null <<'UNIT' | |
| 24 | 新增:[Unit] | |
| 25 | 新增:Description=Cage compressed memory reserve | |
| 26 | 新增:After=systemd-modules-load.service | |
| 27 | 新增:Before=cage-browser.service cage-editor.service | |
| 28 | 新增:[Service] | |
| 29 | 新增:Type=oneshot | |
| 30 | 新增:RemainAfterExit=yes | |
| 31 | 新增:ExecStart=/usr/local/bin/cage-memory-start | |
| 32 | 新增:[Install] | |
| 33 | 新增:WantedBy=multi-user.target | |
| 34 | 新增:UNIT | |
| 35 | 新增:sudo systemctl daemon-reload | |
| 36 | 新增:sudo systemctl enable cage-memory.service >/dev/null | |
| 37 | 新增:if ! sudo systemctl start cage-memory.service; then | |
| 38 | 新增: printf 'Compressed memory reserve unavailable; automatic host memory management remains enabled.\n' >&2 | |
| 39 | 新增:fi | |
| @@ -1,13 +1,18 @@ | ||
| 1 | 1 | #!/bin/sh |
| 2 | 2 | set -eu |
| 3 | 3 | case "${1:-}" in |
| 4 | 删除: claude://*) exec sudo -u cage /usr/local/bin/cage-claude-open "$1" ;; | |
| 5 | 删除: http://*|https://*|about:blank) ;; | |
| 4 | 新增: claude://*) | |
| 5 | 新增: sudo -u cage /usr/local/bin/cage-claude-open "$1" | |
| 6 | 新增: # Publish focus only after the running application accepted the handoff. | |
| 7 | 新增: # The browser service never receives the login URL or its credentials. | |
| 8 | 新增: set -- /desktop-focus | |
| 9 | 新增: ;; | |
| 10 | 新增: http://*|https://*|about:blank) set -- /new "$1" ;; | |
| 6 | 11 | *) echo 'Only HTTP(S) browser URLs and Claude desktop callbacks are accepted.' >&2; exit 2;; |
| 7 | 12 | esac |
| 8 | 删除:exec sudo -u cage-browser /usr/bin/node --input-type=module - "$1" <<'NODE' | |
| 13 | 新增:exec sudo -u cage-browser /usr/bin/node --input-type=module - "$@" <<'NODE' | |
| 9 | 14 | import {readFileSync} from 'node:fs'; |
| 10 | 15 | const {token}=JSON.parse(readFileSync('/etc/claude-cage/browser-control.json','utf8')); |
| 11 | 删除:const response=await fetch('http://127.0.0.1:18500/new',{method:'POST',headers:{Authorization:'Bearer '+token,'Content-Type':'application/json'},body:JSON.stringify({url:process.argv[2]})}); | |
| 16 | 新增:const response=await fetch('http://127.0.0.1:18500'+process.argv[2],{method:'POST',headers:{Authorization:'Bearer '+token,'Content-Type':'application/json'},body:JSON.stringify(process.argv[2]==='/new'?{url:process.argv[3]}:{})}); | |
| 12 | 17 | if(!response.ok)process.exit(1); |
| 13 | 18 | NODE |
| @@ -3,8 +3,8 @@ | ||
| 3 | 3 | if systemctl is-active --quiet cage-webvnc; then |
| 4 | 4 | sudo systemctl stop cage-webvnc |
| 5 | 5 | fi |
| 6 | 删除:if ! command -v X0tigervnc >/dev/null || ! command -v Xtigervnc >/dev/null || ! command -v openbox >/dev/null || ! command -v xrandr >/dev/null || ! command -v xdotool >/dev/null; then | |
| 7 | 删除: sudo env DEBIAN_FRONTEND=noninteractive APT_CONFIG="${CAGE_APT_CONFIG:-/dev/null}" apt-get install -y --no-install-recommends tigervnc-standalone-server tigervnc-scraping-server tigervnc-tools openbox x11-xserver-utils xdotool libgtk-3-0 | |
| 6 | 新增:if ! command -v X0tigervnc >/dev/null || ! command -v Xtigervnc >/dev/null || ! command -v openbox >/dev/null || ! command -v xrandr >/dev/null || ! command -v xdotool >/dev/null || ! command -v ibus-daemon >/dev/null || ! /usr/bin/python3 -c 'import gi; gi.require_version("IBus", "1.0")' 2>/dev/null; then | |
| 7 | 新增: sudo env DEBIAN_FRONTEND=noninteractive APT_CONFIG="${CAGE_APT_CONFIG:-/dev/null}" apt-get install -y --no-install-recommends tigervnc-standalone-server tigervnc-scraping-server tigervnc-tools openbox x11-xserver-utils xdotool libgtk-3-0 ibus ibus-gtk3 gir1.2-ibus-1.0 python3-gi | |
| 8 | 8 | fi |
| 9 | 9 | sudo install -d -m 0755 /etc/claude-cage /usr/local/lib |
| 10 | 10 | sudo tee /usr/local/bin/cage-editor-start >/dev/null <<'SCRIPT' |
| @@ -22,7 +22,8 @@ User=cage | ||
| 22 | 22 | WorkingDirectory=/home/cage |
| 23 | 23 | Environment=HOME=/home/cage |
| 24 | 24 | EnvironmentFile=/etc/claude-cage/environment |
| 25 | 删除:ExecStart=/usr/local/bin/cage-editor-start | |
| 25 | 新增:ExecStart=/usr/local/bin/cage-log-run /usr/local/bin/cage-editor-start | |
| 26 | 新增:LogNamespace=cage | |
| 26 | 27 | Restart=on-failure |
| 27 | 28 | RestartSec=2 |
| 28 | 29 | TimeoutStopSec=15 |
| @@ -47,7 +48,8 @@ Description=Claude Cage virtual browser display | ||
| 47 | 48 | [Service] |
| 48 | 49 | User=cage-browser |
| 49 | 50 | ExecStartPre=/usr/bin/rm -f /home/cage-browser/.vnc/display.sock |
| 50 | 删除:ExecStart=/usr/bin/Xtigervnc :77 -geometry 2880x1800 -depth 24 -rfbport -1 -rfbunixpath /home/cage-browser/.vnc/display.sock -rfbunixmode 0600 -nolisten tcp -localhost -SecurityTypes VncAuth -PasswordFile /home/cage-browser/.vnc/passwd | |
| 51 | 新增:ExecStart=/usr/local/bin/cage-log-run /usr/bin/Xtigervnc :77 -geometry 2880x1800 -depth 24 -rfbport -1 -rfbunixpath /home/cage-browser/.vnc/display.sock -rfbunixmode 0600 -nolisten tcp -localhost -SecurityTypes VncAuth -PasswordFile /home/cage-browser/.vnc/passwd | |
| 52 | 新增:LogNamespace=cage | |
| 51 | 53 | Restart=on-failure |
| 52 | 54 | UNIT |
| 53 | 55 | sudo tee /etc/claude-cage/openbox.xml >/dev/null <<'WINDOW_CONFIG' |
| @@ -67,7 +69,8 @@ After=cage-display.service | ||
| 67 | 69 | [Service] |
| 68 | 70 | User=cage-browser |
| 69 | 71 | Environment=DISPLAY=:77 |
| 70 | 删除:ExecStart=/usr/bin/openbox --config-file /etc/claude-cage/openbox.xml | |
| 72 | 新增:ExecStart=/usr/local/bin/cage-log-run /usr/bin/openbox --config-file /etc/claude-cage/openbox.xml | |
| 73 | 新增:LogNamespace=cage | |
| 71 | 74 | Restart=on-failure |
| 72 | 75 | UNIT |
| 73 | 76 | sudo tee /etc/systemd/system/cage-browser.service >/dev/null <<'UNIT' |
| @@ -79,7 +82,8 @@ After=cage-display.service cage-window-manager.service | ||
| 79 | 82 | User=cage-browser |
| 80 | 83 | Environment=DISPLAY=:77 |
| 81 | 84 | EnvironmentFile=/etc/claude-cage/environment |
| 82 | 删除:ExecStart=/usr/bin/node /usr/local/lib/cage-browser-agent.mjs | |
| 85 | 新增:ExecStart=/usr/local/bin/cage-log-run /usr/local/bin/cage-input-session /usr/bin/node /usr/local/lib/cage-browser-agent.mjs | |
| 86 | 新增:LogNamespace=cage | |
| 83 | 87 | # Let the controller close Chromium and flush its tabs and profile before |
| 84 | 88 | # systemd terminates any remaining child processes. |
| 85 | 89 | KillMode=mixed |
| @@ -93,7 +97,8 @@ Requires=cage-display.service | ||
| 93 | 97 | After=cage-display.service |
| 94 | 98 | [Service] |
| 95 | 99 | User=cage-browser |
| 96 | 删除:ExecStart=/usr/bin/X0tigervnc -display :77 -rfbport 15900 -localhost -SecurityTypes VncAuth -PasswordFile /home/cage-browser/.vnc/passwd -AlwaysShared | |
| 100 | 新增:ExecStart=/usr/local/bin/cage-log-run /usr/bin/X0tigervnc -display :77 -rfbport 15900 -localhost -SecurityTypes VncAuth -PasswordFile /home/cage-browser/.vnc/passwd -AlwaysShared | |
| 101 | 新增:LogNamespace=cage | |
| 97 | 102 | Restart=on-failure |
| 98 | 103 | RestartSec=2 |
| 99 | 104 | UNIT |
| @@ -104,7 +109,8 @@ Requires=cage-vnc.service | ||
| 104 | 109 | After=cage-vnc.service |
| 105 | 110 | [Service] |
| 106 | 111 | User=cage-browser |
| 107 | 删除:ExecStart=/usr/bin/websockify --web=/usr/share/novnc 127.0.0.1:16080 127.0.0.1:15900 | |
| 112 | 新增:ExecStart=/usr/local/bin/cage-log-run /usr/bin/websockify --web=/usr/share/novnc 127.0.0.1:16080 127.0.0.1:15900 | |
| 113 | 新增:LogNamespace=cage | |
| 108 | 114 | Restart=on-failure |
| 109 | 115 | UNIT |
| 110 | 116 | sudo systemctl daemon-reload |
| @@ -9,6 +9,7 @@ import ( | ||
| 9 | 9 | "strings" |
| 10 | 10 | "sync" |
| 11 | 11 | |
| 12 | 新增: "github.com/sylvinus/agent-vm/internal/diagnostics" | |
| 12 | 13 | "github.com/sylvinus/agent-vm/internal/version" |
| 13 | 14 | ) |
| 14 | 15 | |
| @@ -21,6 +22,9 @@ var guestServices string | ||
| 21 | 22 | //go:embed guest-audio.sh |
| 22 | 23 | var guestAudio string |
| 23 | 24 | |
| 25 | 新增://go:embed guest-memory.sh | |
| 26 | 新增:var guestMemory string | |
| 27 | 新增: | |
| 24 | 28 | //go:embed novnc-patch.py |
| 25 | 29 | var novncPatch string |
| 26 | 30 | |
| @@ -51,16 +55,32 @@ var imageInput string | ||
| 51 | 55 | //go:embed desktop-files.py |
| 52 | 56 | var desktopFiles string |
| 53 | 57 | |
| 58 | 新增://go:embed native-ime.py | |
| 59 | 新增:var nativeIME string | |
| 60 | 新增: | |
| 61 | 新增://go:embed native-ime-session.sh | |
| 62 | 新增:var nativeIMESession string | |
| 63 | 新增: | |
| 64 | 新增://go:embed native-input.mjs | |
| 65 | 新增:var nativeInputClient string | |
| 66 | 新增: | |
| 67 | 新增:func nativeInputScript() string { | |
| 68 | 新增: return "\nsudo tee /usr/local/bin/cage-native-input >/dev/null <<'CAGE_NATIVE_INPUT'\n" + nativeIME + "\nCAGE_NATIVE_INPUT\nsudo chmod 0755 /usr/local/bin/cage-native-input\n" + | |
| 69 | 新增: "sudo tee /usr/local/bin/cage-input-session >/dev/null <<'CAGE_INPUT_SESSION'\n" + nativeIMESession + "\nCAGE_INPUT_SESSION\nsudo chmod 0755 /usr/local/bin/cage-input-session\n" + | |
| 70 | 新增: "sudo tee /usr/local/lib/native-input.mjs >/dev/null <<'CAGE_INPUT_CLIENT'\n" + nativeInputClient + "\nCAGE_INPUT_CLIENT\n" + | |
| 71 | 新增: "printf 'cage-browser ALL=(cage) NOPASSWD: /usr/local/bin/cage-native-input --request\\n' | sudo tee /etc/sudoers.d/cage-input >/dev/null\nsudo chmod 0440 /etc/sudoers.d/cage-input\n" | |
| 72 | 新增:} | |
| 73 | 新增: | |
| 54 | 74 | func fileInputScript() string { |
| 55 | 75 | 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" |
| 56 | 76 | } |
| 57 | 77 | |
| 58 | 78 | func imageInputScript() string { |
| 59 | 删除: return fileInputScript() + "\nsudo tee /usr/local/bin/cage-image-input >/dev/null <<'CAGE_IMAGE_INPUT'\n" + imageInput + "\nCAGE_IMAGE_INPUT\nsudo chmod 0755 /usr/local/bin/cage-image-input\n" | |
| 79 | 新增: return nativeInputScript() + fileInputScript() + "\nsudo tee /usr/local/bin/cage-image-input >/dev/null <<'CAGE_IMAGE_INPUT'\n" + imageInput + "\nCAGE_IMAGE_INPUT\nsudo chmod 0755 /usr/local/bin/cage-image-input\n" | |
| 60 | 80 | } |
| 61 | 81 | |
| 62 | 82 | func browserServices() string { |
| 63 | 删除: return guestAudio + "\n" + guestOpenScript() + imageInputScript() + "\nsudo tee /usr/local/lib/browser-uploads.mjs >/dev/null <<'CAGE_BROWSER_UPLOADS'\n" + browserUploads + "\nCAGE_BROWSER_UPLOADS\n" + guestServices + "\nsudo tee /usr/local/lib/browser-downloads.mjs >/dev/null <<'CAGE_BROWSER_DOWNLOADS'\n" + browserDownloads + "\nCAGE_BROWSER_DOWNLOADS\n" + "\nsudo tee /usr/local/bin/cage-editor-migrate >/dev/null <<'CAGE_EDITOR_MIGRATE'\n" + editorMigrate + "\nCAGE_EDITOR_MIGRATE\nsudo chmod 0755 /usr/local/bin/cage-editor-migrate\n" + "\nsudo tee /usr/local/lib/browser-audit.mjs >/dev/null <<'CAGE_BROWSER_AUDIT'\n" + browserAudit + "\nCAGE_BROWSER_AUDIT\n" + "\nsudo tee /usr/local/lib/cage-browser-agent.mjs >/dev/null <<'CAGE_BROWSER_AGENT'\n" + browserAgent + "\nCAGE_BROWSER_AGENT\n" + "sudo tee /usr/local/bin/cage-save-download >/dev/null <<'CAGE_DOWNLOAD_HELPER'\n" + saveDownload + "\nCAGE_DOWNLOAD_HELPER\nsudo chmod 0755 /usr/local/bin/cage-save-download\nprintf 'cage-browser ALL=(root) NOPASSWD: /usr/local/bin/cage-save-download *\\n' | sudo tee /etc/sudoers.d/cage-download >/dev/null\nsudo chmod 0440 /etc/sudoers.d/cage-download\n" + "\nsudo python3 - <<'CAGE_NOVNC_PATCH'\n" + novncPatch + "\nCAGE_NOVNC_PATCH\n" + "\nsudo tee /usr/share/novnc/cage-clipboard.js >/dev/null <<'CAGE_CLIPBOARD_JS'\n" + clipboardJS + "\nCAGE_CLIPBOARD_JS\n" + `sudo python3 - <<'PYCODE' | |
| 83 | 新增: return guestMemory + "\n" + guestDiagnostics() + guestAudio + "\n" + guestOpenScript() + imageInputScript() + "\nsudo tee /usr/local/lib/browser-uploads.mjs >/dev/null <<'CAGE_BROWSER_UPLOADS'\n" + browserUploads + "\nCAGE_BROWSER_UPLOADS\n" + guestServices + "\nsudo tee /usr/local/lib/browser-downloads.mjs >/dev/null <<'CAGE_BROWSER_DOWNLOADS'\n" + browserDownloads + "\nCAGE_BROWSER_DOWNLOADS\n" + "\nsudo tee /usr/local/bin/cage-editor-migrate >/dev/null <<'CAGE_EDITOR_MIGRATE'\n" + editorMigrate + "\nCAGE_EDITOR_MIGRATE\nsudo chmod 0755 /usr/local/bin/cage-editor-migrate\n" + "\nsudo tee /usr/local/lib/browser-audit.mjs >/dev/null <<'CAGE_BROWSER_AUDIT'\n" + browserAudit + "\nCAGE_BROWSER_AUDIT\n" + "\nsudo tee /usr/local/lib/cage-browser-agent.mjs >/dev/null <<'CAGE_BROWSER_AGENT'\n" + browserAgent + "\nCAGE_BROWSER_AGENT\n" + "sudo tee /usr/local/bin/cage-save-download >/dev/null <<'CAGE_DOWNLOAD_HELPER'\n" + saveDownload + "\nCAGE_DOWNLOAD_HELPER\nsudo chmod 0755 /usr/local/bin/cage-save-download\nprintf 'cage-browser ALL=(root) NOPASSWD: /usr/local/bin/cage-save-download *\\n' | sudo tee /etc/sudoers.d/cage-download >/dev/null\nsudo chmod 0440 /etc/sudoers.d/cage-download\n" + "\nsudo python3 - <<'CAGE_NOVNC_PATCH'\n" + novncPatch + "\nCAGE_NOVNC_PATCH\n" + "\nsudo tee /usr/share/novnc/cage-clipboard.js >/dev/null <<'CAGE_CLIPBOARD_JS'\n" + clipboardJS + "\nCAGE_CLIPBOARD_JS\n" + `sudo python3 - <<'PYCODE' | |
| 64 | 84 | from pathlib import Path |
| 65 | 85 | import re |
| 66 | 86 | p = Path("/usr/share/novnc/vnc.html") |
| @@ -163,3 +183,21 @@ func (m GuestManifest) Current() bool { | ||
| 163 | 183 | required := RequiredGuestManifest() |
| 164 | 184 | return m.Protocol == required.Protocol && m.Revision == required.Revision |
| 165 | 185 | } |
| 186 | 新增: | |
| 187 | 新增:func guestDiagnostics() string { | |
| 188 | 新增: return "sudo tee /usr/local/bin/cage-log-run >/dev/null <<'CAGE_LOG_RUN'\n" + diagnostics.GuestRunner() + "\nCAGE_LOG_RUN\nsudo chmod 0755 /usr/local/bin/cage-log-run\n" + `sudo install -d -m 0755 /etc/systemd/[email protected] | |
| 189 | 新增:sudo tee /etc/systemd/[email protected]/limits.conf >/dev/null <<'CAGE_JOURNAL' | |
| 190 | 新增:[Journal] | |
| 191 | 新增:Storage=persistent | |
| 192 | 新增:SystemMaxUse=10M | |
| 193 | 新增:SystemMaxFileSize=1M | |
| 194 | 新增:RuntimeMaxUse=10M | |
| 195 | 新增:RuntimeMaxFileSize=1M | |
| 196 | 新增:MaxRetentionSec=14day | |
| 197 | 新增:MaxFileSec=1day | |
| 198 | 新增:RateLimitIntervalSec=30s | |
| 199 | 新增:RateLimitBurst=200 | |
| 200 | 新增:CAGE_JOURNAL | |
| 201 | 新增:sudo systemctl try-restart [email protected] | |
| 202 | 新增:` | |
| 203 | 新增:} | |
| @@ -0,0 +1,72 @@ | ||
| 1 | 新增:#!/usr/bin/env bash | |
| 2 | 新增:set -euo pipefail | |
| 3 | 新增:# Existing environments can still open Desktop before their next maintenance | |
| 4 | 新增:# update installs IBus. Their established committed-text path remains usable. | |
| 5 | 新增:if ! command -v ibus-daemon >/dev/null || ! /usr/bin/python3 -c 'import gi; gi.require_version("IBus", "1.0")' 2>/dev/null; then | |
| 6 | 新增: exec "$@" | |
| 7 | 新增:fi | |
| 8 | 新增:umask 077 | |
| 9 | 新增:input_root="$HOME/.cache/cage-input" | |
| 10 | 新增:mkdir -p "$input_root" | |
| 11 | 新增:chmod 700 "$input_root" | |
| 12 | 新增:export IBUS_ADDRESS="unix:path=$input_root/bus" | |
| 13 | 新增:export GTK_IM_MODULE=ibus QT_IM_MODULE=ibus XMODIFIERS=@im=ibus | |
| 14 | 新增:bus_pid='' bridge_pid='' app_pid='' session_pid='' | |
| 15 | 新增:cleanup() { | |
| 16 | 新增: if [ -n "$app_pid" ]; then | |
| 17 | 新增: kill -TERM "$app_pid" 2>/dev/null || true | |
| 18 | 新增: # Let Node close Chromium and flush its profile before closing the buses. | |
| 19 | 新增: wait "$app_pid" 2>/dev/null || true | |
| 20 | 新增: fi | |
| 21 | 新增: for pid in "$bridge_pid" "$bus_pid" "$session_pid"; do | |
| 22 | 新增: if [ -n "$pid" ]; then kill -TERM "$pid" 2>/dev/null || true; fi | |
| 23 | 新增: done | |
| 24 | 新增: rm -f "$input_root/ready" "$input_root/input.sock" | |
| 25 | 新增:} | |
| 26 | 新增:trap cleanup EXIT | |
| 27 | 新增:trap 'exit 143' TERM | |
| 28 | 新增:trap 'exit 130' INT | |
| 29 | 新增:# GTK's IBus portal needs a shared session bus. For the browser, allow only | |
| 30 | 新增:# that service to activate, preserving its existing absence of a desktop | |
| 31 | 新增:# keyring/portal session. Desktop keeps its already-owned keyring bus. | |
| 32 | 新增:if [ -z "${DBUS_SESSION_BUS_ADDRESS:-}" ]; then | |
| 33 | 新增: mkdir -p "$input_root/services" | |
| 34 | 新增: cp /usr/share/dbus-1/services/org.freedesktop.portal.IBus.service "$input_root/services/" | |
| 35 | 新增: cat > "$input_root/session.conf" <<CONFIG | |
| 36 | 新增:<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN" "http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd"> | |
| 37 | 新增:<busconfig> | |
| 38 | 新增: <type>session</type><listen>unix:path=$input_root/session-bus</listen><auth>EXTERNAL</auth> | |
| 39 | 新增: <servicedir>$input_root/services</servicedir> | |
| 40 | 新增: <policy context="default"><allow send_destination="*"/><allow receive_sender="*"/><allow own="*"/></policy> | |
| 41 | 新增:</busconfig> | |
| 42 | 新增:CONFIG | |
| 43 | 新增: rm -f "$input_root/session-bus" | |
| 44 | 新增: dbus-daemon --nofork --config-file="$input_root/session.conf" >/dev/null 2>&1 & | |
| 45 | 新增: session_pid=$! | |
| 46 | 新增: for i in $(seq 1 100); do | |
| 47 | 新增: kill -0 "$session_pid" | |
| 48 | 新增: if [ -S "$input_root/session-bus" ]; then break; fi | |
| 49 | 新增: sleep .05 | |
| 50 | 新增: done | |
| 51 | 新增: test -S "$input_root/session-bus" | |
| 52 | 新增: export DBUS_SESSION_BUS_ADDRESS="unix:path=$input_root/session-bus" | |
| 53 | 新增:fi | |
| 54 | 新增:rm -f "$input_root/ready" "$input_root/bus" "$input_root/input.sock" | |
| 55 | 新增:ibus-daemon --single --panel=disable --config=disable --emoji-extension=disable --cache=none --address="$IBUS_ADDRESS" & | |
| 56 | 新增:bus_pid=$! | |
| 57 | 新增:for i in $(seq 1 100); do | |
| 58 | 新增: kill -0 "$bus_pid" | |
| 59 | 新增: if [ -S "$input_root/bus" ]; then break; fi | |
| 60 | 新增: sleep .05 | |
| 61 | 新增:done | |
| 62 | 新增:/usr/local/bin/cage-native-input & | |
| 63 | 新增:bridge_pid=$! | |
| 64 | 新增:for i in $(seq 1 100); do | |
| 65 | 新增: kill -0 "$bridge_pid" | |
| 66 | 新增: if [ -f "$input_root/ready" ]; then break; fi | |
| 67 | 新增: sleep .05 | |
| 68 | 新增:done | |
| 69 | 新增:test -f "$input_root/ready" | |
| 70 | 新增:"$@" & | |
| 71 | 新增:app_pid=$! | |
| 72 | 新增:wait "$app_pid" | |
| @@ -0,0 +1,327 @@ | ||
| 1 | 新增:#!/usr/bin/python3 | |
| 2 | 新增:"""Private IBus bridge. Text is transient and is never logged or persisted.""" | |
| 3 | 新增:import json | |
| 4 | 新增:import os | |
| 5 | 新增:from pathlib import Path | |
| 6 | 新增:import re | |
| 7 | 新增:import socket | |
| 8 | 新增:import sys | |
| 9 | 新增: | |
| 10 | 新增:directory = Path.home() / '.cache' / 'cage-input' | |
| 11 | 新增:socket_path = directory / 'input.sock' | |
| 12 | 新增:limit = 32768 | |
| 13 | 新增: | |
| 14 | 新增: | |
| 15 | 新增:def request(): | |
| 16 | 新增: data = sys.stdin.buffer.readline(limit + 1) | |
| 17 | 新增: if len(data) > limit or not data.endswith(b'\n'): | |
| 18 | 新增: raise ValueError('Invalid input request') | |
| 19 | 新增: with socket.socket(socket.AF_UNIX) as client: | |
| 20 | 新增: client.settimeout(3) | |
| 21 | 新增: client.connect(str(socket_path)) | |
| 22 | 新增: client.sendall(data) | |
| 23 | 新增: result = client.makefile('rb').readline(limit + 1) | |
| 24 | 新增: if len(result) > limit or not result.endswith(b'\n'): | |
| 25 | 新增: raise ValueError('Invalid input response') | |
| 26 | 新增: sys.stdout.buffer.write(result) | |
| 27 | 新增: | |
| 28 | 新增: | |
| 29 | 新增:if __name__ == '__main__' and sys.argv[1:] == ['--request']: | |
| 30 | 新增: try: | |
| 31 | 新增: request() | |
| 32 | 新增: except (OSError, ValueError): | |
| 33 | 新增: print('{"available":false}') | |
| 34 | 新增: sys.exit(0) | |
| 35 | 新增: | |
| 36 | 新增:import gi | |
| 37 | 新增:import secrets | |
| 38 | 新增:import socketserver | |
| 39 | 新增:import subprocess | |
| 40 | 新增:import threading | |
| 41 | 新增:import time | |
| 42 | 新增: | |
| 43 | 新增:gi.require_version('IBus', '1.0') | |
| 44 | 新增:from gi.repository import IBus, GLib | |
| 45 | 新增: | |
| 46 | 新增:IBus.init() | |
| 47 | 新增:active = None | |
| 48 | 新增:engines = [] | |
| 49 | 新增:probe_key = 0xffd5 # F24: consumed by this engine to refresh Chromium's caret. | |
| 50 | 新增: | |
| 51 | 新增: | |
| 52 | 新增:def prepare_probe(): | |
| 53 | 新增: # xdotool temporarily maps an absent keysym and immediately restores it. | |
| 54 | 新增: # GTK can then receive NoSymbol on later probes. Reserve one otherwise | |
| 55 | 新增: # empty keycode for this private virtual display's lifetime instead. | |
| 56 | 新增: try: | |
| 57 | 新增: mapping = subprocess.check_output(['xmodmap', '-pke'], text=True) | |
| 58 | 新增: empty = [] | |
| 59 | 新增: for line in mapping.splitlines(): | |
| 60 | 新增: match = re.fullmatch(r'keycode\s+(\d+)\s*=\s*(.*)', line) | |
| 61 | 新增: if not match: | |
| 62 | 新增: continue | |
| 63 | 新增: symbols = match[2].split() | |
| 64 | 新增: if symbols and symbols[0] == 'F24': | |
| 65 | 新增: return True | |
| 66 | 新增: if int(match[1]) >= 128 and not symbols: | |
| 67 | 新增: empty.append(int(match[1])) | |
| 68 | 新增: if not empty: | |
| 69 | 新增: return False | |
| 70 | 新增: subprocess.run(['xmodmap', '-e', f'keycode {max(empty)} = F24'], | |
| 71 | 新增: check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) | |
| 72 | 新增: return True | |
| 73 | 新增: except (OSError, subprocess.SubprocessError): | |
| 74 | 新增: return False | |
| 75 | 新增: | |
| 76 | 新增: | |
| 77 | 新增:probe_ready = prepare_probe() | |
| 78 | 新增: | |
| 79 | 新增: | |
| 80 | 新增:class Engine(IBus.Engine): | |
| 81 | 新增: __gtype_name__ = 'CageInputEngine' | |
| 82 | 新增: | |
| 83 | 新增: def __init__(self, **args): | |
| 84 | 新增: super().__init__(**args) | |
| 85 | 新增: self.context = '' | |
| 86 | 新增: self.session = '' | |
| 87 | 新增: self.sequence = -1 | |
| 88 | 新增: self.rect = None | |
| 89 | 新增: self.purpose = 0 | |
| 90 | 新增: self.probing = False | |
| 91 | 新增: self.probe_seen = False | |
| 92 | 新增: self.reachable = False | |
| 93 | 新增: self.updated = 0 | |
| 94 | 新增: | |
| 95 | 新增: def clear(self): | |
| 96 | 新增: self.update_preedit_text(IBus.Text.new_from_string(''), 0, False) | |
| 97 | 新增: self.session = '' | |
| 98 | 新增: self.sequence = -1 | |
| 99 | 新增: | |
| 100 | 新增: def do_focus_in(self): | |
| 101 | 新增: global active | |
| 102 | 新增: if active is not self: | |
| 103 | 新增: self.context = secrets.token_hex(16) | |
| 104 | 新增: self.rect = None | |
| 105 | 新增: self.reachable = False | |
| 106 | 新增: active = self | |
| 107 | 新增: | |
| 108 | 新增: def do_focus_in_id(self, path, client): | |
| 109 | 新增: # A single engine can be reused for different application fields. | |
| 110 | 新增: global active | |
| 111 | 新增: if self.context_path != str(path): | |
| 112 | 新增: self.clear() | |
| 113 | 新增: self.context = secrets.token_hex(16) | |
| 114 | 新增: self.rect = None | |
| 115 | 新增: self.context_path = str(path) | |
| 116 | 新增: self.do_focus_in() | |
| 117 | 新增: | |
| 118 | 新增: context_path = '' | |
| 119 | 新增: | |
| 120 | 新增: def do_focus_out(self): | |
| 121 | 新增: global active | |
| 122 | 新增: self.clear() | |
| 123 | 新增: self.rect = None | |
| 124 | 新增: self.probing = False | |
| 125 | 新增: self.reachable = False | |
| 126 | 新增: if active is self: | |
| 127 | 新增: active = None | |
| 128 | 新增: | |
| 129 | 新增: def do_focus_out_id(self, path): | |
| 130 | 新增: self.do_focus_out() | |
| 131 | 新增: | |
| 132 | 新增: def do_reset(self): | |
| 133 | 新增: self.clear() | |
| 134 | 新增: self.context = secrets.token_hex(16) | |
| 135 | 新增: self.reachable = False | |
| 136 | 新增: | |
| 137 | 新增: def do_set_cursor_location(self, x, y, width, height): | |
| 138 | 新增: self.rect = [x, y, width, height] | |
| 139 | 新增: | |
| 140 | 新增: def do_set_content_type(self, purpose, hints): | |
| 141 | 新增: self.purpose = int(purpose) | |
| 142 | 新增: | |
| 143 | 新增: def do_process_key_event(self, keyval, keycode, state): | |
| 144 | 新增: if self.probing and keyval == probe_key: | |
| 145 | 新增: self.probe_seen = True | |
| 146 | 新增: self.reachable = True | |
| 147 | 新增: return True | |
| 148 | 新增: return False | |
| 149 | 新增: | |
| 150 | 新增: | |
| 151 | 新增:bus = IBus.Bus() | |
| 152 | 新增:if not bus.is_connected(): | |
| 153 | 新增: raise RuntimeError('Private input bus unavailable') | |
| 154 | 新增: | |
| 155 | 新增: | |
| 156 | 新增:class Factory(IBus.Factory): | |
| 157 | 新增: def do_create_engine(self, name): | |
| 158 | 新增: engine = Engine(connection=bus.get_connection(), | |
| 159 | 新增: object_path='/org/freedesktop/IBus/Cage/' + str(len(engines)), | |
| 160 | 新增: has_focus_id=True) | |
| 161 | 新增: engines.append(engine) | |
| 162 | 新增: return engine | |
| 163 | 新增: | |
| 164 | 新增: | |
| 165 | 新增:factory = Factory(connection=bus.get_connection(), object_path=IBus.PATH_FACTORY) | |
| 166 | 新增:component = IBus.Component(name='org.freedesktop.IBus.Cage', description='Cage host input', | |
| 167 | 新增: version='1', license='MIT', author='Cage', homepage='', | |
| 168 | 新增: command_line='', textdomain='') | |
| 169 | 新增:component.add_engine(IBus.EngineDesc(name='cage-host', longname='Cage Host Input', | |
| 170 | 新增: description='Host input transport', language='en', | |
| 171 | 新增: license='MIT', author='Cage', icon='', layout='us')) | |
| 172 | 新增:if not bus.register_component(component): | |
| 173 | 新增: raise RuntimeError('Private input engine unavailable') | |
| 174 | 新增: | |
| 175 | 新增: | |
| 176 | 新增:def snapshot(engine): | |
| 177 | 新增: if engine is None or engine is not active or not engine.reachable or engine.purpose in (8, 9): | |
| 178 | 新增: return {'available': False} | |
| 179 | 新增: return {'available': True, 'context': engine.context, 'rect': engine.rect} | |
| 180 | 新增: | |
| 181 | 新增: | |
| 182 | 新增:def utf16_index(text, offset): | |
| 183 | 新增: if type(offset) is not int or offset < 0: | |
| 184 | 新增: raise ValueError('Invalid input range') | |
| 185 | 新增: data = text.encode('utf-16-le') | |
| 186 | 新增: if offset * 2 > len(data): | |
| 187 | 新增: raise ValueError('Invalid input range') | |
| 188 | 新增: return len(data[:offset * 2].decode('utf-16-le')) | |
| 189 | 新增: | |
| 190 | 新增: | |
| 191 | 新增:def apply(value): | |
| 192 | 新增: engine = active | |
| 193 | 新增: mode = value.get('mode') | |
| 194 | 新增: if mode == 'status': | |
| 195 | 新增: if engine is not None and engine.session and value.get('session') == engine.session: | |
| 196 | 新增: engine.updated = time.monotonic() | |
| 197 | 新增: return snapshot(engine) | |
| 198 | 新增: session = value.get('session', '') | |
| 199 | 新增: sequence = value.get('sequence') | |
| 200 | 新增: if not isinstance(session, str) or not re.fullmatch('[a-f0-9]{32}', session): | |
| 201 | 新增: raise ValueError('Invalid input session') | |
| 202 | 新增: if type(sequence) is not int or sequence < 0: | |
| 203 | 新增: raise ValueError('Invalid input sequence') | |
| 204 | 新增: if mode == 'cancel': | |
| 205 | 新增: # Cleanup can target an older field; it must never clear a newer session. | |
| 206 | 新增: for old in engines: | |
| 207 | 新增: if old.session == session and sequence > old.sequence: | |
| 208 | 新增: old.clear() | |
| 209 | 新增: return {'available': False} | |
| 210 | 新增: if not snapshot(engine)['available']: | |
| 211 | 新增: return {'available': False} | |
| 212 | 新增: if mode == 'begin': | |
| 213 | 新增: if value.get('context') != engine.context: | |
| 214 | 新增: raise ValueError('Input target changed') | |
| 215 | 新增: engine.clear() | |
| 216 | 新增: engine.session = session | |
| 217 | 新增: engine.sequence = sequence | |
| 218 | 新增: engine.updated = time.monotonic() | |
| 219 | 新增: return snapshot(engine) | |
| 220 | 新增: if engine.session != session or sequence <= engine.sequence: | |
| 221 | 新增: raise ValueError('Input session expired') | |
| 222 | 新增: text = value.get('text', '') | |
| 223 | 新增: if not isinstance(text, str) or len(text.encode('utf-8')) > 8192: | |
| 224 | 新增: raise ValueError('Input text too large') | |
| 225 | 新增: if mode == 'update': | |
| 226 | 新增: start = utf16_index(text, value.get('selectionStart', 0)) | |
| 227 | 新增: end = utf16_index(text, value.get('selectionEnd', 0)) | |
| 228 | 新增: if end < start: | |
| 229 | 新增: raise ValueError('Invalid input range') | |
| 230 | 新增: preedit = IBus.Text.new_from_string(text) | |
| 231 | 新增: preedit.append_attribute(IBus.AttrType.UNDERLINE, IBus.AttrUnderline.SINGLE, 0, len(text)) | |
| 232 | 新增: if end > start: | |
| 233 | 新增: preedit.append_attribute(IBus.AttrType.BACKGROUND, 0x3584e4, start, end) | |
| 234 | 新增: preedit.append_attribute(IBus.AttrType.FOREGROUND, 0xffffff, start, end) | |
| 235 | 新增: engine.update_preedit_text_with_mode(preedit, end, bool(text), IBus.PreeditFocusMode.CLEAR) | |
| 236 | 新增: engine.sequence = sequence | |
| 237 | 新增: engine.updated = time.monotonic() | |
| 238 | 新增: elif mode == 'commit': | |
| 239 | 新增: engine.clear() | |
| 240 | 新增: if text: | |
| 241 | 新增: engine.commit_text(IBus.Text.new_from_string(text)) | |
| 242 | 新增: else: | |
| 243 | 新增: raise ValueError('Invalid input mode') | |
| 244 | 新增: return snapshot(engine) | |
| 245 | 新增: | |
| 246 | 新增: | |
| 247 | 新增:class Handler(socketserver.StreamRequestHandler): | |
| 248 | 新增: def handle(self): | |
| 249 | 新增: self.connection.settimeout(3) | |
| 250 | 新增: try: | |
| 251 | 新增: line = self.rfile.readline(limit + 1) | |
| 252 | 新增: if len(line) > limit or not line.endswith(b'\n'): | |
| 253 | 新增: raise ValueError('Invalid input request') | |
| 254 | 新增: value = json.loads(line) | |
| 255 | 新增: if not isinstance(value, dict): | |
| 256 | 新增: raise ValueError('Invalid input request') | |
| 257 | 新增: done = threading.Event() | |
| 258 | 新增: result = {} | |
| 259 | 新增: | |
| 260 | 新增: def dispatch(): | |
| 261 | 新增: try: | |
| 262 | 新增: result.update(apply(value)) | |
| 263 | 新增: except UnicodeError: | |
| 264 | 新增: result.update(error='Invalid input range') | |
| 265 | 新增: except ValueError as error: | |
| 266 | 新增: # All ValueErrors above contain fixed protocol messages. | |
| 267 | 新增: # Never include an exception that can contain input text. | |
| 268 | 新增: result.update(error=str(error)) | |
| 269 | 新增: finally: | |
| 270 | 新增: done.set() | |
| 271 | 新增: return False | |
| 272 | 新增: | |
| 273 | 新增: def probe(): | |
| 274 | 新增: engine = active | |
| 275 | 新增: if probe_ready and value.get('mode') in ('status', 'begin') and engine is not None and engine.purpose not in (8, 9): | |
| 276 | 新增: engine.probing = True | |
| 277 | 新增: engine.probe_seen = False | |
| 278 | 新增: subprocess.Popen(['xdotool', 'key', '--delay', '0', 'F24'], | |
| 279 | 新增: stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) | |
| 280 | 新增: | |
| 281 | 新增: def finish(): | |
| 282 | 新增: engine.probing = False | |
| 283 | 新增: engine.reachable = engine.probe_seen and engine is active | |
| 284 | 新增: return dispatch() | |
| 285 | 新增: GLib.timeout_add(45, finish) | |
| 286 | 新增: else: | |
| 287 | 新增: dispatch() | |
| 288 | 新增: return False | |
| 289 | 新增: | |
| 290 | 新增: GLib.idle_add(probe) | |
| 291 | 新增: if not done.wait(2): | |
| 292 | 新增: result = {'error': 'Input bridge timed out'} | |
| 293 | 新增: self.wfile.write((json.dumps(result, separators=(',', ':')) + '\n').encode()) | |
| 294 | 新增: except (OSError, ValueError): | |
| 295 | 新增: pass | |
| 296 | 新增: | |
| 297 | 新增: | |
| 298 | 新增:class Server(socketserver.ThreadingUnixStreamServer): | |
| 299 | 新增: daemon_threads = True | |
| 300 | 新增: | |
| 301 | 新增: | |
| 302 | 新增:directory.mkdir(mode=0o700, parents=True, exist_ok=True) | |
| 303 | 新增:os.chmod(directory, 0o700) | |
| 304 | 新增:socket_path.unlink(missing_ok=True) | |
| 305 | 新增:server = Server(str(socket_path), Handler) | |
| 306 | 新增:os.chmod(socket_path, 0o600) | |
| 307 | 新增:threading.Thread(target=server.serve_forever, daemon=True).start() | |
| 308 | 新增: | |
| 309 | 新增: | |
| 310 | 新增:def activate(): | |
| 311 | 新增: def finish(source, result): | |
| 312 | 新增: if source.set_global_engine_async_finish(result): | |
| 313 | 新增: (directory / 'ready').touch(mode=0o600) | |
| 314 | 新增: bus.set_global_engine_async('cage-host', 10000, None, finish) | |
| 315 | 新增: return False | |
| 316 | 新增: | |
| 317 | 新增: | |
| 318 | 新增:def expire(): | |
| 319 | 新增: for engine in engines: | |
| 320 | 新增: if engine.session and time.monotonic() - engine.updated > 10: | |
| 321 | 新增: engine.clear() | |
| 322 | 新增: return True | |
| 323 | 新增: | |
| 324 | 新增: | |
| 325 | 新增:GLib.timeout_add(200, activate) | |
| 326 | 新增:GLib.timeout_add_seconds(1, expire) | |
| 327 | 新增:GLib.MainLoop().run() | |
| @@ -0,0 +1,50 @@ | ||
| 1 | 新增:import { createConnection } from "node:net"; | |
| 2 | 新增:import { spawn } from "node:child_process"; | |
| 3 | 新增: | |
| 4 | 新增:// Each display owns a private IBus socket. The browser can access Desktop's | |
| 5 | 新增:// bridge only through this fixed, sudo-authorized helper, with data on stdin. | |
| 6 | 新增:export function nativeInput(value) { | |
| 7 | 新增: return new Promise((resolve, reject) => { | |
| 8 | 新增: let data = ""; | |
| 9 | 新增: const finish = () => { | |
| 10 | 新增: try { | |
| 11 | 新增: const result = JSON.parse(data); | |
| 12 | 新增: if (result.error) throw new Error(result.error); | |
| 13 | 新增: resolve(result); | |
| 14 | 新增: } catch (error) { reject(error); } | |
| 15 | 新增: }; | |
| 16 | 新增: const unavailable = (error) => { | |
| 17 | 新增: if (value.mode === "status") resolve({ available: false }); | |
| 18 | 新增: else reject(error); | |
| 19 | 新增: }; | |
| 20 | 新增: const collect = (chunk) => { | |
| 21 | 新增: data += chunk; | |
| 22 | 新增: if (data.length > 32768) { | |
| 23 | 新增: channel.destroy(); | |
| 24 | 新增: reject(new Error("Input response too large")); | |
| 25 | 新增: } | |
| 26 | 新增: }; | |
| 27 | 新增: let channel; | |
| 28 | 新增: if (value.target === "desktop") { | |
| 29 | 新增: const child = spawn("/usr/bin/sudo", ["-n", "-H", "-u", "cage", "/usr/local/bin/cage-native-input", "--request"], { | |
| 30 | 新增: stdio: ["pipe", "pipe", "ignore"], timeout: 3500, | |
| 31 | 新增: }); | |
| 32 | 新增: channel = child.stdout; | |
| 33 | 新增: channel.on("data", collect); | |
| 34 | 新增: child.on("error", unavailable); | |
| 35 | 新增: child.stdin.on("error", unavailable); | |
| 36 | 新增: child.on("close", (code) => { | |
| 37 | 新增: if (code === 0) finish(); | |
| 38 | 新增: else unavailable(new Error("Desktop input bridge unavailable")); | |
| 39 | 新增: }); | |
| 40 | 新增: child.stdin.end(JSON.stringify(value) + "\n"); | |
| 41 | 新增: } else { | |
| 42 | 新增: channel = createConnection("/home/cage-browser/.cache/cage-input/input.sock"); | |
| 43 | 新增: channel.setTimeout(3000, () => channel.destroy(new Error("Input bridge timed out"))); | |
| 44 | 新增: channel.on("error", unavailable); | |
| 45 | 新增: channel.on("connect", () => channel.end(JSON.stringify(value) + "\n")); | |
| 46 | 新增: channel.on("data", collect); | |
| 47 | 新增: channel.on("end", finish); | |
| 48 | 新增: } | |
| 49 | 新增: }); | |
| 50 | 新增:} | |
| @@ -140,6 +140,14 @@ replace_once(''' sendKey(keysym, code, down) { | ||
| 140 | 140 | replace_once(''' this.sendKey(keysym, code, true); |
| 141 | 141 | this.sendKey(keysym, code, false);''', ''' this._cageSendKey(keysym, code, true); |
| 142 | 142 | this._cageSendKey(keysym, code, false);''') |
| 143 | 新增:replace_once(''' const scancode = XtScancode[code];''', ''' // Track modifiers when they actually reach the wire, including keys | |
| 144 | 新增: // waiting behind text transfers. Host key state may already be newer. | |
| 145 | 新增: if (keysym >= 0xffe1 && keysym <= 0xffee) { | |
| 146 | 新增: this._cageModifiers ||= new Map(); | |
| 147 | 新增: if (down) this._cageModifiers.set(code, keysym); | |
| 148 | 新增: else this._cageModifiers.delete(code); | |
| 149 | 新增: } | |
| 150 | 新增: const scancode = XtScancode[code];''') | |
| 143 | 151 | replace_once(''' _sendMouse(x, y, mask) {''', ''' _sendMouse(x, y, mask) { |
| 144 | 152 | if (this._cageInputChain) { |
| 145 | 153 | this._cageQueueInput(() => this._cageSendMouse(x, y, mask)); |
| @@ -168,10 +176,16 @@ replace_once(''' if (!(flags & (1<<31))) { | ||
| 168 | 176 | if (payload.startsWith('cage-input-')) return true; |
| 169 | 177 | const job = this._cagePasteJob; |
| 170 | 178 | if (job && job.phase === 'fence' && payload === job.id) { |
| 179 | 新增: // Punctuation can commit while Shift is still physically held. | |
| 180 | 新增: // Paste with a plain Ctrl+V, then restore the wire modifiers; | |
| 181 | 新增: // queued host key releases will follow in their normal order. | |
| 182 | 新增: const modifiers = [...(this._cageModifiers || [])]; | |
| 183 | 新增: for (const [code, sym] of modifiers) this._cageSendKey(sym, code, false); | |
| 171 | 184 | this._cageSendKey(0xffe3, 'ControlLeft', true); |
| 172 | 185 | this._cageSendKey(0x76, 'KeyV', true); |
| 173 | 186 | this._cageSendKey(0x76, 'KeyV', false); |
| 174 | 187 | this._cageSendKey(0xffe3, 'ControlLeft', false); |
| 188 | 新增: for (const [code, sym] of modifiers) this._cageSendKey(sym, code, true); | |
| 175 | 189 | job.phase = 'keys'; |
| 176 | 190 | RFB.messages.clientFence(this._sock, (1 << 31) | 1, job.id + '-keys'); |
| 177 | 191 | return true; |
| @@ -0,0 +1,323 @@ | ||
| 1 | 新增:package cage | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "encoding/json" | |
| 6 | 新增: "errors" | |
| 7 | 新增: "fmt" | |
| 8 | 新增: "io" | |
| 9 | 新增: "math" | |
| 10 | 新增: "os" | |
| 11 | 新增: "path/filepath" | |
| 12 | 新增: "strconv" | |
| 13 | 新增: "strings" | |
| 14 | 新增: "time" | |
| 15 | 新增: | |
| 16 | 新增: "github.com/sylvinus/agent-vm/internal/diagnostics" | |
| 17 | 新增: "github.com/sylvinus/agent-vm/internal/host" | |
| 18 | 新增:) | |
| 19 | 新增: | |
| 20 | 新增:// ResourceLimits keeps the existing host-share policy while replacing the fixed | |
| 21 | 新增:// 4 GiB / 2 CPU defaults. Zero hardware observations keep those legacy defaults. | |
| 22 | 新增:func ResourceLimits() (memoryGiB, cpus int) { | |
| 23 | 新增: memoryGiB, cpus = host.MemGiB(), host.CPUs() | |
| 24 | 新增: if memoryGiB <= 0 { | |
| 25 | 新增: memoryGiB = 4 | |
| 26 | 新增: } | |
| 27 | 新增: if cpus <= 0 { | |
| 28 | 新增: cpus = 2 | |
| 29 | 新增: } | |
| 30 | 新增: return host.Cap("memory", memoryGiB, io.Discard), host.Cap("cpus", cpus, io.Discard) | |
| 31 | 新增:} | |
| 32 | 新增: | |
| 33 | 新增:const resourceProbe = `LC_ALL=C; export LC_ALL | |
| 34 | 新增:awk '/^(MemTotal|MemAvailable|SwapTotal|SwapFree):/ {print $1,$2}' /proc/meminfo | |
| 35 | 新增:awk '/^(oom_kill|balloon_inflate|balloon_deflate) / {print $1,$2}' /proc/vmstat | |
| 36 | 新增:printf 'page_size '; getconf PAGESIZE | |
| 37 | 新增:cat /proc/pressure/memory | |
| 38 | 新增:head -n 1 /proc/stat | |
| 39 | 新增:printf 'boot '; cat /proc/sys/kernel/random/boot_id` | |
| 40 | 新增: | |
| 41 | 新增:type ResourceSample struct { | |
| 42 | 新增: Total uint64 `json:"total_bytes"` | |
| 43 | 新增: Available uint64 `json:"available_bytes"` | |
| 44 | 新增: SwapTotal uint64 `json:"swap_total_bytes"` | |
| 45 | 新增: SwapFree uint64 `json:"swap_free_bytes"` | |
| 46 | 新增: OOMKills uint64 `json:"oom_kills"` | |
| 47 | 新增: Balloon uint64 `json:"balloon_bytes"` | |
| 48 | 新增: Stall float64 `json:"memory_stall_percent"` | |
| 49 | 新增: Boot string `json:"boot_id"` | |
| 50 | 新增: cpuTotal, cpuIdle uint64 | |
| 51 | 新增:} | |
| 52 | 新增: | |
| 53 | 新增:func parseResources(data []byte) (ResourceSample, error) { | |
| 54 | 新增: var s ResourceSample | |
| 55 | 新增: var inflated, deflated, pageSize uint64 | |
| 56 | 新增: seen := map[string]bool{} | |
| 57 | 新增: for _, line := range strings.Split(string(data), "\n") { | |
| 58 | 新增: f := strings.Fields(line) | |
| 59 | 新增: if len(f) < 2 { | |
| 60 | 新增: continue | |
| 61 | 新增: } | |
| 62 | 新增: key := strings.TrimSuffix(f[0], ":") | |
| 63 | 新增: n, err := strconv.ParseUint(f[1], 10, 64) | |
| 64 | 新增: switch key { | |
| 65 | 新增: case "balloon_inflate", "balloon_deflate", "page_size": | |
| 66 | 新增: if err != nil || n > 1<<40 { | |
| 67 | 新增: return s, errors.New("invalid balloon observation") | |
| 68 | 新增: } | |
| 69 | 新增: if key == "balloon_inflate" { | |
| 70 | 新增: inflated = n | |
| 71 | 新增: } | |
| 72 | 新增: if key == "balloon_deflate" { | |
| 73 | 新增: deflated = n | |
| 74 | 新增: } | |
| 75 | 新增: if key == "page_size" { | |
| 76 | 新增: pageSize = n | |
| 77 | 新增: } | |
| 78 | 新增: case "MemTotal", "MemAvailable", "SwapTotal", "SwapFree", "oom_kill": | |
| 79 | 新增: if err != nil || n > 1<<40 { | |
| 80 | 新增: return s, errors.New("invalid guest resource observation") | |
| 81 | 新增: } | |
| 82 | 新增: seen[key] = true | |
| 83 | 新增: switch key { | |
| 84 | 新增: case "MemTotal": | |
| 85 | 新增: s.Total = n << 10 | |
| 86 | 新增: case "MemAvailable": | |
| 87 | 新增: s.Available = n << 10 | |
| 88 | 新增: case "SwapTotal": | |
| 89 | 新增: s.SwapTotal = n << 10 | |
| 90 | 新增: case "SwapFree": | |
| 91 | 新增: s.SwapFree = n << 10 | |
| 92 | 新增: case "oom_kill": | |
| 93 | 新增: s.OOMKills = n | |
| 94 | 新增: } | |
| 95 | 新增: case "some": | |
| 96 | 新增: for _, value := range f[1:] { | |
| 97 | 新增: if strings.HasPrefix(value, "avg10=") { | |
| 98 | 新增: s.Stall, _ = strconv.ParseFloat(strings.TrimPrefix(value, "avg10="), 64) | |
| 99 | 新增: } | |
| 100 | 新增: } | |
| 101 | 新增: case "boot": | |
| 102 | 新增: s.Boot = f[1] | |
| 103 | 新增: case "cpu": | |
| 104 | 新增: // guest/guest_nice are already included in user/nice. | |
| 105 | 新增: for i := 1; i < len(f) && i <= 8; i++ { | |
| 106 | 新增: v, e := strconv.ParseUint(f[i], 10, 64) | |
| 107 | 新增: if e != nil { | |
| 108 | 新增: return s, e | |
| 109 | 新增: } | |
| 110 | 新增: s.cpuTotal += v | |
| 111 | 新增: if i == 4 || i == 5 { | |
| 112 | 新增: s.cpuIdle += v | |
| 113 | 新增: } | |
| 114 | 新增: } | |
| 115 | 新增: } | |
| 116 | 新增: } | |
| 117 | 新增: if !seen["MemAvailable"] || !seen["oom_kill"] || s.Total < 256<<20 || s.Available > s.Total || s.SwapFree > s.SwapTotal || len(s.Boot) != 36 || math.IsNaN(s.Stall) || s.Stall < 0 || s.Stall > 100 { | |
| 118 | 新增: return s, errors.New("incomplete guest resource observation") | |
| 119 | 新增: } | |
| 120 | 新增: if inflated != 0 || deflated != 0 { | |
| 121 | 新增: if inflated < deflated || pageSize < 4096 || pageSize > 65536 || pageSize&(pageSize-1) != 0 { | |
| 122 | 新增: return s, errors.New("invalid balloon counters") | |
| 123 | 新增: } | |
| 124 | 新增: s.Balloon = (inflated - deflated) * pageSize | |
| 125 | 新增: } | |
| 126 | 新增: return s, nil | |
| 127 | 新增:} | |
| 128 | 新增: | |
| 129 | 新增:type ResourceStatus struct { | |
| 130 | 新增: Version int `json:"version"` | |
| 131 | 新增: PID int `json:"pid"` | |
| 132 | 新增: UpdatedAt time.Time `json:"updated_at"` | |
| 133 | 新增: ObservedAt time.Time `json:"observed_at"` | |
| 134 | 新增: Maximum uint64 `json:"maximum_bytes"` | |
| 135 | 新增: Target uint64 `json:"target_bytes"` | |
| 136 | 新增: CPUs int `json:"cpus"` | |
| 137 | 新增: CPUPercent float64 `json:"cpu_percent"` | |
| 138 | 新增: Guest *ResourceSample `json:"guest,omitempty"` | |
| 139 | 新增: Pressure bool `json:"pressure"` | |
| 140 | 新增: HostPressure bool `json:"host_pressure"` | |
| 141 | 新增: Error string `json:"error,omitempty"` | |
| 142 | 新增:} | |
| 143 | 新增: | |
| 144 | 新增:// memoryTarget grows immediately and reclaims only after sustained headroom. | |
| 145 | 新增:// The requested target is not a measurement of the guest or host's resident RAM. | |
| 146 | 新增:type memoryPolicy struct { | |
| 147 | 新增: maximum, target uint64 | |
| 148 | 新增: idleSince time.Time | |
| 149 | 新增:} | |
| 150 | 新增: | |
| 151 | 新增:func (p *memoryPolicy) next(now time.Time, s ResourceSample, hostPressure bool) uint64 { | |
| 152 | 新增: const mib = uint64(1 << 20) | |
| 153 | 新增: used := s.Total - s.Available + s.SwapTotal - s.SwapFree | |
| 154 | 新增: reserve := max(uint64(1<<30), used/4) | |
| 155 | 新增: // Kernel bookkeeping and balloon pages are absent from MemTotal. | |
| 156 | 新增: desired := min(p.maximum, max(min(uint64(2<<30), p.maximum), ((used+reserve+256*mib+255*mib)/(256*mib))*(256*mib))) | |
| 157 | 新增: pressure := s.Available < max(uint64(512*mib), s.Total/8) || s.Stall >= 1 | |
| 158 | 新增: if pressure || desired > p.target { | |
| 159 | 新增: p.idleSince = time.Time{} | |
| 160 | 新增: if hostPressure { | |
| 161 | 新增: return p.target | |
| 162 | 新增: } | |
| 163 | 新增: // A burst should not wait through several incremental allocations. | |
| 164 | 新增: if pressure { | |
| 165 | 新增: return p.maximum | |
| 166 | 新增: } | |
| 167 | 新增: return desired | |
| 168 | 新增: } | |
| 169 | 新增: if desired+512*mib > p.target { | |
| 170 | 新增: p.idleSince = time.Time{} | |
| 171 | 新增: return p.target | |
| 172 | 新增: } | |
| 173 | 新增: if p.idleSince.IsZero() { | |
| 174 | 新增: p.idleSince = now | |
| 175 | 新增: } | |
| 176 | 新增: if now.Sub(p.idleSince) < 30*time.Second { | |
| 177 | 新增: return p.target | |
| 178 | 新增: } | |
| 179 | 新增: // Never request another reclamation until the guest reflects the prior one. | |
| 180 | 新增: if s.Balloon < p.maximum-p.target { | |
| 181 | 新增: return p.target | |
| 182 | 新增: } | |
| 183 | 新增: return max(desired, p.target-256*mib) | |
| 184 | 新增:} | |
| 185 | 新增: | |
| 186 | 新增:// StartResourceManager belongs to the VM hostagent, so closing a window cannot | |
| 187 | 新增:// strand a small balloon target. stop joins the loop before the driver stops. | |
| 188 | 新增:func StartResourceManager(parent context.Context, dir string, maximum uint64, cpus int, read func(context.Context, string) ([]byte, error), set func(context.Context, uint64) error) func() { | |
| 189 | 新增: ctx, cancel := context.WithCancel(parent) | |
| 190 | 新增: done := make(chan struct{}) | |
| 191 | 新增: go func() { | |
| 192 | 新增: defer close(done) | |
| 193 | 新增: p := memoryPolicy{maximum: maximum, target: maximum} | |
| 194 | 新增: status := ResourceStatus{Version: 1, PID: os.Getpid(), Maximum: maximum, Target: maximum, CPUs: cpus} | |
| 195 | 新增: var previous ResourceSample | |
| 196 | 新增: var bootTotal uint64 | |
| 197 | 新增: var lastError string | |
| 198 | 新增: ticker := time.NewTicker(2 * time.Second) | |
| 199 | 新增: defer ticker.Stop() | |
| 200 | 新增: for { | |
| 201 | 新增: select { | |
| 202 | 新增: case <-ctx.Done(): | |
| 203 | 新增: return | |
| 204 | 新增: case <-ticker.C: | |
| 205 | 新增: } | |
| 206 | 新增: probeCtx, finish := context.WithTimeout(ctx, 3*time.Second) | |
| 207 | 新增: data, err := read(probeCtx, resourceProbe) | |
| 208 | 新增: finish() | |
| 209 | 新增: var sample ResourceSample | |
| 210 | 新增: if err == nil { | |
| 211 | 新增: sample, err = parseResources(data) | |
| 212 | 新增: if err == nil && sample.Total > maximum { | |
| 213 | 新增: err = errors.New("guest memory exceeds VM capacity") | |
| 214 | 新增: } | |
| 215 | 新增: if err == nil { | |
| 216 | 新增: if previous.Boot != sample.Boot { | |
| 217 | 新增: bootTotal = sample.Total | |
| 218 | 新增: } | |
| 219 | 新增: // Some Linux kernels keep MemTotal constant while balloon pages | |
| 220 | 新增: // count as used. Subtract them once, also accepting kernels that | |
| 221 | 新增: // reduce MemTotal. Balloon counters acknowledge each reclamation. | |
| 222 | 新增: if sample.Balloon >= bootTotal { | |
| 223 | 新增: err = errors.New("invalid balloon size") | |
| 224 | 新增: } else { | |
| 225 | 新增: sample.Total = min(sample.Total, bootTotal-sample.Balloon) | |
| 226 | 新增: if sample.Available > sample.Total { | |
| 227 | 新增: err = errors.New("inconsistent available memory") | |
| 228 | 新增: } | |
| 229 | 新增: } | |
| 230 | 新增: } | |
| 231 | 新增: } | |
| 232 | 新增: now := time.Now() | |
| 233 | 新增: status.UpdatedAt, status.HostPressure = now, host.MemoryPressure() | |
| 234 | 新增: target := p.target | |
| 235 | 新增: if err != nil { | |
| 236 | 新增: p.idleSince = time.Time{} | |
| 237 | 新增: status.Error = "资源采样暂时不可用,已暂停内存回收" | |
| 238 | 新增: // A stalled guest may itself be out of memory. Restore its budget | |
| 239 | 新增: // without relying on a command that needs guest RAM to execute. | |
| 240 | 新增: if !status.HostPressure { | |
| 241 | 新增: target = maximum | |
| 242 | 新增: } | |
| 243 | 新增: } else { | |
| 244 | 新增: status.Error = "" | |
| 245 | 新增: status.ObservedAt, status.Guest = now, &sample | |
| 246 | 新增: status.Pressure = sample.Available < max(uint64(512<<20), sample.Total/8) || sample.Stall >= 1 | |
| 247 | 新增: if previous.Boot == sample.Boot && sample.cpuTotal > previous.cpuTotal && sample.cpuIdle >= previous.cpuIdle { | |
| 248 | 新增: total, idle := sample.cpuTotal-previous.cpuTotal, sample.cpuIdle-previous.cpuIdle | |
| 249 | 新增: status.CPUPercent = 100 * float64(total-min(idle, total)) / float64(total) | |
| 250 | 新增: } | |
| 251 | 新增: if previous.Boot == sample.Boot && sample.OOMKills > previous.OOMKills { | |
| 252 | 新增: diagnostics.Log("warn", "resources", fmt.Sprintf("guest OOM kills increased by %d; available=%d target=%d maximum=%d", sample.OOMKills-previous.OOMKills, sample.Available, p.target, maximum)) | |
| 253 | 新增: } | |
| 254 | 新增: if previous.Boot != sample.Boot { | |
| 255 | 新增: p.idleSince = time.Time{} | |
| 256 | 新增: } | |
| 257 | 新增: target = p.next(now, sample, status.HostPressure) | |
| 258 | 新增: previous = sample | |
| 259 | 新增: } | |
| 260 | 新增: if ctx.Err() != nil { | |
| 261 | 新增: return | |
| 262 | 新增: } | |
| 263 | 新增: if target != p.target { | |
| 264 | 新增: changeCtx, finish := context.WithTimeout(ctx, 3*time.Second) | |
| 265 | 新增: e := set(changeCtx, target) | |
| 266 | 新增: finish() | |
| 267 | 新增: if e != nil { | |
| 268 | 新增: status.Error = "内存目标未能应用,保持当前配置" | |
| 269 | 新增: } else { | |
| 270 | 新增: p.target, status.Target = target, target | |
| 271 | 新增: diagnostics.Log("info", "resources", fmt.Sprintf("memory target=%d maximum=%d", target, maximum)) | |
| 272 | 新增: } | |
| 273 | 新增: } | |
| 274 | 新增: if status.Error != lastError { | |
| 275 | 新增: if status.Error != "" { | |
| 276 | 新增: diagnostics.Log("warn", "resources", status.Error) | |
| 277 | 新增: } | |
| 278 | 新增: lastError = status.Error | |
| 279 | 新增: } | |
| 280 | 新增: if e := writeResourceStatus(dir, status); e != nil && lastError != "status write failed" { | |
| 281 | 新增: diagnostics.Log("warn", "resources", "resource status write failed") | |
| 282 | 新增: lastError = "status write failed" | |
| 283 | 新增: } | |
| 284 | 新增: } | |
| 285 | 新增: }() | |
| 286 | 新增: return func() { cancel(); <-done } | |
| 287 | 新增:} | |
| 288 | 新增: | |
| 289 | 新增:func writeResourceStatus(dir string, status ResourceStatus) error { | |
| 290 | 新增: data, err := json.Marshal(status) | |
| 291 | 新增: if err != nil { | |
| 292 | 新增: return err | |
| 293 | 新增: } | |
| 294 | 新增: f, err := os.CreateTemp(dir, ".resources-*") | |
| 295 | 新增: if err != nil { | |
| 296 | 新增: return err | |
| 297 | 新增: } | |
| 298 | 新增: defer os.Remove(f.Name()) | |
| 299 | 新增: if err = host.ProtectFile(f.Name()); err != nil { | |
| 300 | 新增: f.Close() | |
| 301 | 新增: return err | |
| 302 | 新增: } | |
| 303 | 新增: _, err = f.Write(data) | |
| 304 | 新增: err = errors.Join(err, f.Close()) | |
| 305 | 新增: if err != nil { | |
| 306 | 新增: return err | |
| 307 | 新增: } | |
| 308 | 新增: return os.Rename(f.Name(), filepath.Join(dir, "cage-resources.json")) | |
| 309 | 新增:} | |
| 310 | 新增: | |
| 311 | 新增:func ReadResourceStatus(dir string) (ResourceStatus, error) { | |
| 312 | 新增: var status ResourceStatus | |
| 313 | 新增: f, err := os.Open(filepath.Join(dir, "cage-resources.json")) | |
| 314 | 新增: if err != nil { | |
| 315 | 新增: return status, err | |
| 316 | 新增: } | |
| 317 | 新增: defer f.Close() | |
| 318 | 新增: err = json.NewDecoder(io.LimitReader(f, 16384)).Decode(&status) | |
| 319 | 新增: if err == nil && (status.Version != 1 || time.Since(status.UpdatedAt) > 10*time.Second || time.Until(status.UpdatedAt) > 5*time.Second) { | |
| 320 | 新增: err = errors.New("resource observation expired") | |
| 321 | 新增: } | |
| 322 | 新增: return status, err | |
| 323 | 新增:} | |
| @@ -0,0 +1,108 @@ | ||
| 1 | 新增:package cage | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "fmt" | |
| 6 | 新增: "strings" | |
| 7 | 新增: "testing" | |
| 8 | 新增: "time" | |
| 9 | 新增: | |
| 10 | 新增: "github.com/sylvinus/agent-vm/internal/host" | |
| 11 | 新增:) | |
| 12 | 新增: | |
| 13 | 新增:func TestResourceLimitsUseExistingHostShare(t *testing.T) { | |
| 14 | 新增: oldMem, oldCPU := host.MemGiB, host.CPUs | |
| 15 | 新增: t.Cleanup(func() { host.MemGiB, host.CPUs = oldMem, oldCPU }) | |
| 16 | 新增: for _, tc := range []struct{ memory, cpu, wantMemory, wantCPU int }{{24, 10, 12, 5}, {8, 4, 4, 2}, {4, 2, 2, 1}, {0, 0, 4, 2}} { | |
| 17 | 新增: host.MemGiB = func() int { return tc.memory } | |
| 18 | 新增: host.CPUs = func() int { return tc.cpu } | |
| 19 | 新增: t.Setenv("AGENT_VM_HOST_SHARE", "2") | |
| 20 | 新增: memory, cpus := ResourceLimits() | |
| 21 | 新增: if memory != tc.wantMemory || cpus != tc.wantCPU { | |
| 22 | 新增: t.Fatal(tc, memory, cpus) | |
| 23 | 新增: } | |
| 24 | 新增: } | |
| 25 | 新增:} | |
| 26 | 新增: | |
| 27 | 新增:func TestMemoryPolicyBurstIdleAndHostPressure(t *testing.T) { | |
| 28 | 新增: now := time.Now() | |
| 29 | 新增: gib := uint64(1 << 30) | |
| 30 | 新增: p := memoryPolicy{maximum: 12 * gib, target: 4 * gib} | |
| 31 | 新增: busy := ResourceSample{Total: 4*gib - 128<<20, Available: 128 << 20} | |
| 32 | 新增: if got := p.next(now, busy, false); got != 12*gib { | |
| 33 | 新增: t.Fatalf("burst gets %d", got) | |
| 34 | 新增: } | |
| 35 | 新增: if got := p.next(now, busy, true); got != 4*gib { | |
| 36 | 新增: t.Fatalf("host pressure grows to %d", got) | |
| 37 | 新增: } | |
| 38 | 新增: p.target = p.maximum | |
| 39 | 新增: idle := ResourceSample{Total: 12*gib - 128<<20, Available: 10 * gib} | |
| 40 | 新增: if got := p.next(now, idle, false); got != p.maximum { | |
| 41 | 新增: t.Fatal("immediate shrink", got) | |
| 42 | 新增: } | |
| 43 | 新增: if got := p.next(now.Add(29*time.Second), idle, false); got != p.maximum { | |
| 44 | 新增: t.Fatal("premature shrink", got) | |
| 45 | 新增: } | |
| 46 | 新增: next := p.next(now.Add(31*time.Second), idle, false) | |
| 47 | 新增: if next != p.maximum-256<<20 { | |
| 48 | 新增: t.Fatalf("reclamation step %d", next) | |
| 49 | 新增: } | |
| 50 | 新增: p.target = next | |
| 51 | 新增: if got := p.next(now.Add(33*time.Second), idle, false); got != next { | |
| 52 | 新增: t.Fatal("repeated shrink before guest acknowledgement", got) | |
| 53 | 新增: } | |
| 54 | 新增: idle.Total -= 256 << 20 | |
| 55 | 新增: idle.Available -= 256 << 20 | |
| 56 | 新增: idle.Balloon = 256 << 20 | |
| 57 | 新增: if got := p.next(now.Add(35*time.Second), idle, false); got >= next { | |
| 58 | 新增: t.Fatal("no reclamation after acknowledgement", got) | |
| 59 | 新增: } | |
| 60 | 新增: // Repeated active workloads must reset the idle interval. | |
| 61 | 新增: p.next(now.Add(36*time.Second), busy, false) | |
| 62 | 新增: if got := p.next(now.Add(37*time.Second), idle, false); got != p.target { | |
| 63 | 新增: t.Fatal("shrunk after burst", got) | |
| 64 | 新增: } | |
| 65 | 新增:} | |
| 66 | 新增: | |
| 67 | 新增:func TestResourcesRejectIncompleteOrImpossibleObservation(t *testing.T) { | |
| 68 | 新增: valid := "MemTotal: 4000000\nMemAvailable: 2000000\nSwapTotal: 1000\nSwapFree: 500\noom_kill 3\nsome avg10=0.50 avg60=0.0 total=2\ncpu 10 0 5 20 2 0 0 0 0 0\nboot 12345678-1234-1234-1234-123456789012\n" | |
| 69 | 新增: s, err := parseResources([]byte(valid)) | |
| 70 | 新增: if err != nil || s.Available != 2000000<<10 || s.OOMKills != 3 || s.Stall != .5 { | |
| 71 | 新增: t.Fatal(s, err) | |
| 72 | 新增: } | |
| 73 | 新增: balloon, err := parseResources([]byte(valid + "balloon_inflate 131072\nballoon_deflate 65536\npage_size 4096\n")) | |
| 74 | 新增: if err != nil || balloon.Balloon != 256<<20 { | |
| 75 | 新增: t.Fatal("balloon acknowledgement lost", balloon, err) | |
| 76 | 新增: } | |
| 77 | 新增: for _, invalid := range []string{strings.Replace(valid, "MemAvailable: 2000000", "MemAvailable: 5000000", 1), strings.Replace(valid, "MemAvailable: 2000000\n", "", 1), strings.Replace(valid, "oom_kill 3\n", "", 1), strings.Replace(valid, "SwapFree: 500", "SwapFree: 1001", 1)} { | |
| 78 | 新增: if _, err := parseResources([]byte(invalid)); err == nil { | |
| 79 | 新增: t.Fatal("accepted invalid sample") | |
| 80 | 新增: } | |
| 81 | 新增: } | |
| 82 | 新增:} | |
| 83 | 新增: | |
| 84 | 新增:func TestResourceManagerCancellationAndFreshness(t *testing.T) { | |
| 85 | 新增: ctx, cancel := context.WithCancel(context.Background()) | |
| 86 | 新增: cancel() | |
| 87 | 新增: stop := StartResourceManager(ctx, t.TempDir(), 4<<30, 2, func(context.Context, string) ([]byte, error) { | |
| 88 | 新增: t.Error("read after cancellation") | |
| 89 | 新增: return nil, fmt.Errorf("unused") | |
| 90 | 新增: }, func(context.Context, uint64) error { t.Error("change after cancellation"); return nil }) | |
| 91 | 新增: done := make(chan struct{}) | |
| 92 | 新增: go func() { stop(); stop(); close(done) }() | |
| 93 | 新增: select { | |
| 94 | 新增: case <-done: | |
| 95 | 新增: case <-time.After(time.Second): | |
| 96 | 新增: t.Fatal("stop did not join") | |
| 97 | 新增: } | |
| 98 | 新增: dir := t.TempDir() | |
| 99 | 新增: for _, age := range []time.Duration{0, 11 * time.Second} { | |
| 100 | 新增: if err := writeResourceStatus(dir, ResourceStatus{Version: 1, UpdatedAt: time.Now().Add(-age)}); err != nil { | |
| 101 | 新增: t.Fatal(err) | |
| 102 | 新增: } | |
| 103 | 新增: _, err := ReadResourceStatus(dir) | |
| 104 | 新增: if (err != nil) != (age > 0) { | |
| 105 | 新增: t.Fatal(age, err) | |
| 106 | 新增: } | |
| 107 | 新增: } | |
| 108 | 新增:} | |
| @@ -12,6 +12,7 @@ import ( | ||
| 12 | 12 | |
| 13 | 13 | agentvm "github.com/sylvinus/agent-vm" |
| 14 | 14 | "github.com/sylvinus/agent-vm/internal/cage" |
| 15 | 新增: "github.com/sylvinus/agent-vm/internal/diagnostics" | |
| 15 | 16 | "github.com/sylvinus/agent-vm/internal/env" |
| 16 | 17 | "github.com/sylvinus/agent-vm/internal/host" |
| 17 | 18 | "github.com/sylvinus/agent-vm/internal/state" |
| @@ -431,7 +432,13 @@ func (e *app) buildBase(ctx context.Context, in install, disk, memory, cpus int) | ||
| 431 | 432 | return 1 |
| 432 | 433 | } |
| 433 | 434 | logPath := e.state.Path("setup.log") |
| 434 | 删除: log, err := os.Create(logPath) | |
| 435 | 新增: var log io.WriteCloser | |
| 436 | 新增: if configPath := os.Getenv(cage.ConfigEnv); configPath != "" { | |
| 437 | 新增: logPath = filepath.Join(filepath.Dir(configPath), "logs") | |
| 438 | 新增: log = diagnostics.New(filepath.Dir(configPath)).Stream("setup", "info") | |
| 439 | 新增: } else { | |
| 440 | 新增: log, err = os.Create(logPath) | |
| 441 | 新增: } | |
| 435 | 442 | if err != nil { |
| 436 | 443 | fmt.Fprintf(e.io.Stderr, "Error: %v\n", err) |
| 437 | 444 | return 1 |
| @@ -445,7 +452,7 @@ func (e *app) buildBase(ctx context.Context, in install, disk, memory, cpus int) | ||
| 445 | 452 | win.Close() |
| 446 | 453 | if err != nil { |
| 447 | 454 | fmt.Fprintf(log, "%v\n", err) |
| 448 | 删除: if f, ok := e.io.Stdout.(*os.File); ok && ui.IsTerminal(f) { | |
| 455 | 新增: if f, ok := e.io.Stdout.(*os.File); ok && ui.IsTerminal(f) && os.Getenv(cage.ConfigEnv) == "" { | |
| 449 | 456 | fmt.Fprint(e.io.Stderr, ui.Tail(logPath, 20)) |
| 450 | 457 | } |
| 451 | 458 | return false |
| @@ -0,0 +1,269 @@ | ||
| 1 | 新增:package diagnostics | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "archive/zip" | |
| 5 | 新增: "bytes" | |
| 6 | 新增: "encoding/json" | |
| 7 | 新增: "fmt" | |
| 8 | 新增: "io" | |
| 9 | 新增: "os" | |
| 10 | 新增: "os/exec" | |
| 11 | 新增: "path/filepath" | |
| 12 | 新增: "runtime" | |
| 13 | 新增: "strings" | |
| 14 | 新增: "sync" | |
| 15 | 新增: "testing" | |
| 16 | 新增: "time" | |
| 17 | 新增:) | |
| 18 | 新增: | |
| 19 | 新增:func readEvents(t *testing.T, s *Store) []Event { | |
| 20 | 新增: t.Helper() | |
| 21 | 新增: entries, err := s.files() | |
| 22 | 新增: if err != nil { | |
| 23 | 新增: t.Fatal(err) | |
| 24 | 新增: } | |
| 25 | 新增: var result []Event | |
| 26 | 新增: for _, entry := range entries { | |
| 27 | 新增: b, err := os.ReadFile(filepath.Join(s.dir, entry.Name())) | |
| 28 | 新增: if err != nil { | |
| 29 | 新增: t.Fatal(err) | |
| 30 | 新增: } | |
| 31 | 新增: for _, line := range bytes.Split(bytes.TrimSpace(b), []byte("\n")) { | |
| 32 | 新增: if len(line) == 0 { | |
| 33 | 新增: continue | |
| 34 | 新增: } | |
| 35 | 新增: var e Event | |
| 36 | 新增: if err := json.Unmarshal(line, &e); err != nil { | |
| 37 | 新增: t.Fatalf("corrupt event: %s: %v", line, err) | |
| 38 | 新增: } | |
| 39 | 新增: result = append(result, e) | |
| 40 | 新增: } | |
| 41 | 新增: } | |
| 42 | 新增: return result | |
| 43 | 新增:} | |
| 44 | 新增:func TestStreamRedactsSplitSecretsAndPrivateKeys(t *testing.T) { | |
| 45 | 新增: s := New(t.TempDir()) | |
| 46 | 新增: w := s.Stream("proxy", "error") | |
| 47 | 新增: input := "failure password=correct-horse token=split-secret https://user:[email protected]/path?q=secret\nAuthorization: Bearer sensitive-token\nCookie: session=first-secret; custom=second-secret\n-----BEGIN PRIVATE KEY-----\nbase64-private-material\n-----END PRIVATE KEY-----\n/home/alice/private/project.txt C:\\Users\\bob\\project\\secret.txt [email protected] 203.0.113.8\nrecovered\n" | |
| 48 | 新增: for _, b := range []byte(input) { | |
| 49 | 新增: _, _ = w.Write([]byte{b}) | |
| 50 | 新增: } | |
| 51 | 新增: _ = w.Close() | |
| 52 | 新增: var all string | |
| 53 | 新增: for _, e := range readEvents(t, s) { | |
| 54 | 新增: all += e.Message + "\n" | |
| 55 | 新增: } | |
| 56 | 新增: for _, secret := range []string{"correct-horse", "split-secret", "sensitive-token", "first-secret", "second-secret", "base64-private-material", "example.com", "alice", "bob", "203.0.113.8"} { | |
| 57 | 新增: if strings.Contains(all, secret) { | |
| 58 | 新增: t.Errorf("leaked %q: %s", secret, all) | |
| 59 | 新增: } | |
| 60 | 新增: } | |
| 61 | 新增: if !strings.Contains(all, "recovered") { | |
| 62 | 新增: t.Fatal("safe output lost") | |
| 63 | 新增: } | |
| 64 | 新增: long := s.Stream("task", "info") | |
| 65 | 新增: _, _ = long.Write([]byte(strings.Repeat("x", MaxMessage) + " token=too-long-secret\nnext line\n")) | |
| 66 | 新增: _ = long.Close() | |
| 67 | 新增: events := readEvents(t, s) | |
| 68 | 新增: if events[len(events)-1].Message != "next line" { | |
| 69 | 新增: t.Fatal("overlong line lost framing") | |
| 70 | 新增: } | |
| 71 | 新增:} | |
| 72 | 新增:func TestConcurrentRotationCapacityAndRetention(t *testing.T) { | |
| 73 | 新增: s := New(t.TempDir()) | |
| 74 | 新增: s.fileBytes = 1000 | |
| 75 | 新增: s.maxBytes = 3000 | |
| 76 | 新增: now := time.Now() | |
| 77 | 新增: s.now = func() time.Time { return now } | |
| 78 | 新增: var wg sync.WaitGroup | |
| 79 | 新增: for n := 0; n < 8; n++ { | |
| 80 | 新增: wg.Add(1) | |
| 81 | 新增: go func(n int) { | |
| 82 | 新增: defer wg.Done() | |
| 83 | 新增: for i := 0; i < 20; i++ { | |
| 84 | 新增: if err := s.Record("error", "test", fmt.Sprintf("worker %d message %d %s", n, i, strings.Repeat("safe ", 20))); err != nil { | |
| 85 | 新增: t.Error(err) | |
| 86 | 新增: } | |
| 87 | 新增: } | |
| 88 | 新增: }(n) | |
| 89 | 新增: } | |
| 90 | 新增: wg.Wait() | |
| 91 | 新增: if len(readEvents(t, s)) == 0 { | |
| 92 | 新增: t.Fatal("no events") | |
| 93 | 新增: } | |
| 94 | 新增: info, err := s.Info() | |
| 95 | 新增: if err != nil || info.Bytes > s.maxBytes || info.Files < 2 { | |
| 96 | 新增: t.Fatalf("invalid rotation: %+v %v", info, err) | |
| 97 | 新增: } | |
| 98 | 新增: sentinel := filepath.Join(s.dir, "user-file.txt") | |
| 99 | 新增: _ = os.WriteFile(sentinel, []byte("keep"), 0600) | |
| 100 | 新增: files, _ := s.files() | |
| 101 | 新增: for _, f := range files { | |
| 102 | 新增: _ = os.Chtimes(filepath.Join(s.dir, f.Name()), now.Add(-15*24*time.Hour), now.Add(-15*24*time.Hour)) | |
| 103 | 新增: } | |
| 104 | 新增: if err := s.Clean(); err != nil { | |
| 105 | 新增: t.Fatal(err) | |
| 106 | 新增: } | |
| 107 | 新增: info, _ = s.Info() | |
| 108 | 新增: if info.Bytes != 0 { | |
| 109 | 新增: t.Fatal("expired logs retained") | |
| 110 | 新增: } | |
| 111 | 新增: if _, err := os.Stat(sentinel); err != nil { | |
| 112 | 新增: t.Fatal("unrelated file deleted") | |
| 113 | 新增: } | |
| 114 | 新增:} | |
| 115 | 新增:func TestExportWhitelistAndRedaction(t *testing.T) { | |
| 116 | 新增: profile := t.TempDir() | |
| 117 | 新增: s := New(profile) | |
| 118 | 新增: if err := s.Record("error", "test", "password=export-secret failure"); err != nil { | |
| 119 | 新增: t.Fatal(err) | |
| 120 | 新增: } | |
| 121 | 新增: _ = os.WriteFile(filepath.Join(profile, "config.json"), []byte(`{"password":"must-not-export"}`), 0600) | |
| 122 | 新增: _ = os.WriteFile(filepath.Join(s.dir, "unknown.txt"), []byte("must-not-export"), 0600) | |
| 123 | 新增: var bundle bytes.Buffer | |
| 124 | 新增: if err := s.Export(&bundle, "test", []byte("token=guest-secret\nsafe guest"), "collected"); err != nil { | |
| 125 | 新增: t.Fatal(err) | |
| 126 | 新增: } | |
| 127 | 新增: archive, err := zip.NewReader(bytes.NewReader(bundle.Bytes()), int64(bundle.Len())) | |
| 128 | 新增: if err != nil { | |
| 129 | 新增: t.Fatal(err) | |
| 130 | 新增: } | |
| 131 | 新增: var names []string | |
| 132 | 新增: var content string | |
| 133 | 新增: for _, f := range archive.File { | |
| 134 | 新增: r, _ := f.Open() | |
| 135 | 新增: b, _ := io.ReadAll(r) | |
| 136 | 新增: r.Close() | |
| 137 | 新增: names = append(names, f.Name) | |
| 138 | 新增: content += string(b) | |
| 139 | 新增: } | |
| 140 | 新增: for _, secret := range []string{"export-secret", "must-not-export", "guest-secret"} { | |
| 141 | 新增: if strings.Contains(content, secret) { | |
| 142 | 新增: t.Errorf("export leaked %s", secret) | |
| 143 | 新增: } | |
| 144 | 新增: } | |
| 145 | 新增: if !strings.Contains(content, "safe guest") || len(names) != 4 { | |
| 146 | 新增: t.Fatalf("missing evidence: %v", names) | |
| 147 | 新增: } | |
| 148 | 新增:} | |
| 149 | 新增:func TestRefusesSymlinkForWriteAndExport(t *testing.T) { | |
| 150 | 新增: profile := t.TempDir() | |
| 151 | 新增: s := New(profile) | |
| 152 | 新增: if err := s.Clean(); err != nil { | |
| 153 | 新增: t.Fatal(err) | |
| 154 | 新增: } | |
| 155 | 新增: outside := filepath.Join(t.TempDir(), "private.txt") | |
| 156 | 新增: _ = os.WriteFile(outside, []byte("outside-secret"), 0600) | |
| 157 | 新增: if err := os.Symlink(outside, filepath.Join(s.dir, "events.jsonl")); err != nil { | |
| 158 | 新增: t.Skip(err) | |
| 159 | 新增: } | |
| 160 | 新增: if err := s.Record("error", "test", "hello"); err == nil { | |
| 161 | 新增: t.Fatal("followed symlink") | |
| 162 | 新增: } | |
| 163 | 新增: var bundle bytes.Buffer | |
| 164 | 新增: if err := s.Export(&bundle, "test", nil, "offline"); err != nil { | |
| 165 | 新增: t.Fatal(err) | |
| 166 | 新增: } | |
| 167 | 新增: if bytes.Contains(bundle.Bytes(), []byte("outside-secret")) { | |
| 168 | 新增: t.Fatal("included symlink") | |
| 169 | 新增: } | |
| 170 | 新增: b, _ := os.ReadFile(outside) | |
| 171 | 新增: if string(b) != "outside-secret" { | |
| 172 | 新增: t.Fatal("modified external file") | |
| 173 | 新增: } | |
| 174 | 新增:} | |
| 175 | 新增:func TestGuestRunnerSharesRedactionAndExitStatus(t *testing.T) { | |
| 176 | 新增: if runtime.GOOS == "windows" { | |
| 177 | 新增: t.Skip("guest runner executes on Linux; POSIX shell fixture") | |
| 178 | 新增: } | |
| 179 | 新增: if _, err := exec.LookPath("uv"); err != nil { | |
| 180 | 新增: t.Skip("uv unavailable") | |
| 181 | 新增: } | |
| 182 | 新增: script := filepath.Join(t.TempDir(), "runner.py") | |
| 183 | 新增: _ = os.WriteFile(script, []byte(GuestRunner()), 0600) | |
| 184 | 新增: cmd := exec.Command("uv", "run", "--no-project", "python", script, "/bin/sh", "-c", `printf 'Cookie: one=first-secret; two=second-secret\nhttps://user:[email protected]/secret\nsafe-line\n'; exit 7`) | |
| 185 | 新增: out, err := cmd.CombinedOutput() | |
| 186 | 新增: var exit *exec.ExitError | |
| 187 | 新增: if err == nil { | |
| 188 | 新增: t.Fatal("exit status lost") | |
| 189 | 新增: } else if !strings.Contains(err.Error(), "exit status 7") { | |
| 190 | 新增: t.Fatalf("runner failed: %s %v %v", out, err, exit) | |
| 191 | 新增: } | |
| 192 | 新增: if strings.Contains(string(out), "first-secret") || strings.Contains(string(out), "second-secret") || strings.Contains(string(out), "example.com") { | |
| 193 | 新增: t.Fatalf("guest leaked: %s", out) | |
| 194 | 新增: } | |
| 195 | 新增: if !strings.Contains(string(out), "safe-line") { | |
| 196 | 新增: t.Fatalf("guest output missing: %s", out) | |
| 197 | 新增: } | |
| 198 | 新增:} | |
| 199 | 新增:func TestLegacyImportBoundsAndRemovesOldLogs(t *testing.T) { | |
| 200 | 新增: profile := t.TempDir() | |
| 201 | 新增: path := filepath.Join(profile, "control.log") | |
| 202 | 新增: _ = os.WriteFile(path, []byte(strings.Repeat("discard ", 50000)+"\npassword=old-secret\nsafe legacy\n"), 0600) | |
| 203 | 新增: s := New(profile) | |
| 204 | 新增: if err := s.ImportLegacy(profile); err != nil { | |
| 205 | 新增: t.Fatal(err) | |
| 206 | 新增: } | |
| 207 | 新增: if _, err := os.Stat(path); !os.IsNotExist(err) { | |
| 208 | 新增: t.Fatal("raw legacy log retained") | |
| 209 | 新增: } | |
| 210 | 新增: events := readEvents(t, s) | |
| 211 | 新增: if len(events) != 2 || strings.Contains(events[0].Message, "old-secret") { | |
| 212 | 新增: t.Fatalf("invalid migration: %+v", events) | |
| 213 | 新增: } | |
| 214 | 新增:} | |
| 215 | 新增: | |
| 216 | 新增:func TestConcurrentProcessesShareOneLog(t *testing.T) { | |
| 217 | 新增: const flag = "CAGE_DIAGNOSTICS_PROCESS_TEST" | |
| 218 | 新增: if profile := os.Getenv(flag); profile != "" { | |
| 219 | 新增: s := New(profile) | |
| 220 | 新增: for i := 0; i < 20; i++ { | |
| 221 | 新增: if err := s.Record("info", "worker", fmt.Sprintf("event %d", i)); err != nil { | |
| 222 | 新增: t.Fatal(err) | |
| 223 | 新增: } | |
| 224 | 新增: } | |
| 225 | 新增: return | |
| 226 | 新增: } | |
| 227 | 新增: profile := t.TempDir() | |
| 228 | 新增: exe, err := os.Executable() | |
| 229 | 新增: if err != nil { | |
| 230 | 新增: t.Fatal(err) | |
| 231 | 新增: } | |
| 232 | 新增: var workers []*exec.Cmd | |
| 233 | 新增: for i := 0; i < 3; i++ { | |
| 234 | 新增: cmd := exec.Command(exe, "-test.run=^TestConcurrentProcessesShareOneLog$") | |
| 235 | 新增: cmd.Env = append(os.Environ(), flag+"="+profile) | |
| 236 | 新增: if err := cmd.Start(); err != nil { | |
| 237 | 新增: t.Fatal(err) | |
| 238 | 新增: } | |
| 239 | 新增: workers = append(workers, cmd) | |
| 240 | 新增: } | |
| 241 | 新增: for _, cmd := range workers { | |
| 242 | 新增: if err := cmd.Wait(); err != nil { | |
| 243 | 新增: t.Fatal(err) | |
| 244 | 新增: } | |
| 245 | 新增: } | |
| 246 | 新增: if events := readEvents(t, New(profile)); len(events) != 60 { | |
| 247 | 新增: t.Fatalf("cross-process records lost: %d", len(events)) | |
| 248 | 新增: } | |
| 249 | 新增:} | |
| 250 | 新增: | |
| 251 | 新增:func TestCrossDayRotatesSmallActiveFile(t *testing.T) { | |
| 252 | 新增: s := New(t.TempDir()) | |
| 253 | 新增: now := time.Now().UTC() | |
| 254 | 新增: s.now = func() time.Time { return now } | |
| 255 | 新增: if err := s.Record("info", "test", "first day"); err != nil { | |
| 256 | 新增: t.Fatal(err) | |
| 257 | 新增: } | |
| 258 | 新增: now = now.Add(24 * time.Hour) | |
| 259 | 新增: if err := s.Record("info", "test", "second day"); err != nil { | |
| 260 | 新增: t.Fatal(err) | |
| 261 | 新增: } | |
| 262 | 新增: files, err := s.files() | |
| 263 | 新增: if err != nil { | |
| 264 | 新增: t.Fatal(err) | |
| 265 | 新增: } | |
| 266 | 新增: if len(files) != 2 || len(readEvents(t, s)) != 2 { | |
| 267 | 新增: t.Fatal("small active file did not rotate across days") | |
| 268 | 新增: } | |
| 269 | 新增:} | |
| @@ -0,0 +1,80 @@ | ||
| 1 | 新增:package diagnostics | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "archive/zip" | |
| 5 | 新增: "bufio" | |
| 6 | 新增: "encoding/json" | |
| 7 | 新增: "io" | |
| 8 | 新增: "os" | |
| 9 | 新增: "path/filepath" | |
| 10 | 新增: "runtime" | |
| 11 | 新增: "time" | |
| 12 | 新增:) | |
| 13 | 新增: | |
| 14 | 新增:// Export accepts only an explicit metadata map and fixed-name supplements. It | |
| 15 | 新增:// never traverses the profile or includes configuration, projects or credentials. | |
| 16 | 新增:func (s *Store) Export(w io.Writer, version string, guest []byte, guestState string) error { | |
| 17 | 新增: return s.withLock(func() error { | |
| 18 | 新增: if err := s.cleanLocked(0); err != nil { | |
| 19 | 新增: return err | |
| 20 | 新增: } | |
| 21 | 新增: archive := zip.NewWriter(w) | |
| 22 | 新增: add := func(name string, b []byte) error { | |
| 23 | 新增: f, err := archive.Create(name) | |
| 24 | 新增: if err != nil { | |
| 25 | 新增: return err | |
| 26 | 新增: } | |
| 27 | 新增: _, err = f.Write(b) | |
| 28 | 新增: return err | |
| 29 | 新增: } | |
| 30 | 新增: meta, _ := json.MarshalIndent(map[string]any{"format": 1, "created_at": s.now().UTC().Format(time.RFC3339), "app_version": version, "os": runtime.GOOS, "arch": runtime.GOARCH, "go_version": runtime.Version(), "retention_days": RetentionDays, "host_max_bytes": MaxBytes, "guest_max_bytes": 10 << 20, "guest_collection": Redact(guestState)}, "", " ") | |
| 31 | 新增: if err := add("manifest.json", meta); err != nil { | |
| 32 | 新增: return err | |
| 33 | 新增: } | |
| 34 | 新增: if err := add("README.txt", []byte("Cage diagnostic bundle. Logs are redacted automatically. Review before sharing. No project files, terminal sessions, configuration or browser history are collected. Guest collection is best effort; see manifest.json.\n")); err != nil { | |
| 35 | 新增: return err | |
| 36 | 新增: } | |
| 37 | 新增: files, err := s.files() | |
| 38 | 新增: if err != nil { | |
| 39 | 新增: return err | |
| 40 | 新增: } | |
| 41 | 新增: for _, file := range files { | |
| 42 | 新增: path := filepath.Join(s.dir, file.Name()) | |
| 43 | 新增: f, err := privateFile(path, os.O_RDONLY) | |
| 44 | 新增: if err != nil { | |
| 45 | 新增: return err | |
| 46 | 新增: } | |
| 47 | 新增: target, err := archive.Create("logs/" + file.Name()) | |
| 48 | 新增: if err != nil { | |
| 49 | 新增: f.Close() | |
| 50 | 新增: return err | |
| 51 | 新增: } | |
| 52 | 新增: scan := bufio.NewScanner(io.LimitReader(f, s.fileBytes+MaxMessage*8)) | |
| 53 | 新增: scan.Buffer(make([]byte, 4096), MaxMessage*8) | |
| 54 | 新增: for scan.Scan() { | |
| 55 | 新增: var event Event | |
| 56 | 新增: if json.Unmarshal(scan.Bytes(), &event) != nil { | |
| 57 | 新增: continue | |
| 58 | 新增: } | |
| 59 | 新增: event.Message = Redact(event.Message) | |
| 60 | 新增: event.Source = Redact(event.Source) | |
| 61 | 新增: b, _ := json.Marshal(event) | |
| 62 | 新增: if _, err = target.Write(append(b, '\n')); err != nil { | |
| 63 | 新增: f.Close() | |
| 64 | 新增: return err | |
| 65 | 新增: } | |
| 66 | 新增: } | |
| 67 | 新增: scanErr := scan.Err() | |
| 68 | 新增: f.Close() | |
| 69 | 新增: if scanErr != nil { | |
| 70 | 新增: return scanErr | |
| 71 | 新增: } | |
| 72 | 新增: } | |
| 73 | 新增: if len(guest) > 0 { | |
| 74 | 新增: if err := add("guest/services.log", []byte(Redact(string(guest)))); err != nil { | |
| 75 | 新增: return err | |
| 76 | 新增: } | |
| 77 | 新增: } | |
| 78 | 新增: return archive.Close() | |
| 79 | 新增: }) | |
| 80 | 新增:} | |
| @@ -0,0 +1,50 @@ | ||
| 1 | 新增:package diagnostics | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "encoding/json" | |
| 5 | 新增: "strings" | |
| 6 | 新增:) | |
| 7 | 新增: | |
| 8 | 新增:// GuestRunner uses the same redaction expressions as the host, before journald | |
| 9 | 新增:// receives service output. stdin and systemd notify sockets remain inherited. | |
| 10 | 新增:func GuestRunner() string { | |
| 11 | 新增: rules := make([][2]string, 0, len(patterns)) | |
| 12 | 新增: for _, p := range patterns { | |
| 13 | 新增: rules = append(rules, [2]string{p.re.String(), strings.ReplaceAll(p.replacement, "${1}", `\g<1>`)}) | |
| 14 | 新增: } | |
| 15 | 新增: b, _ := json.Marshal(rules) | |
| 16 | 新增: return "#!/usr/bin/python3\n" + `import json, os, re, signal, subprocess, sys | |
| 17 | 新增:rules = [(re.compile(pattern), replacement) for pattern, replacement in json.loads(` + string(mustJSON(string(b))) + `)] | |
| 18 | 新增:child = subprocess.Popen(sys.argv[1:], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) | |
| 19 | 新增:def stop(sig, _frame): | |
| 20 | 新增: try: | |
| 21 | 新增: child.send_signal(sig) | |
| 22 | 新增: except ProcessLookupError: | |
| 23 | 新增: pass | |
| 24 | 新增:for sig in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP): | |
| 25 | 新增: signal.signal(sig, stop) | |
| 26 | 新增:private_key = False | |
| 27 | 新增:while True: | |
| 28 | 新增: data = child.stdout.readline(24577) | |
| 29 | 新增: if not data: | |
| 30 | 新增: break | |
| 31 | 新增: if len(data) > 24576: | |
| 32 | 新增: while data and not data.endswith(b'\n'): | |
| 33 | 新增: data = child.stdout.readline(24577) | |
| 34 | 新增: print('[oversized output line omitted]', flush=True) | |
| 35 | 新增: continue | |
| 36 | 新增: line = data.decode('utf-8', 'replace') | |
| 37 | 新增: if '-----BEGIN ' in line: | |
| 38 | 新增: private_key = True | |
| 39 | 新增: if private_key: | |
| 40 | 新增: if '-----END ' in line: | |
| 41 | 新增: private_key = False | |
| 42 | 新增: continue | |
| 43 | 新增: for pattern, replacement in rules: | |
| 44 | 新增: line = pattern.sub(lambda match: match.expand(replacement), line) | |
| 45 | 新增: print(line.rstrip(), flush=True) | |
| 46 | 新增:code = child.wait() | |
| 47 | 新增:sys.exit(code if code >= 0 else 128-code) | |
| 48 | 新增:` | |
| 49 | 新增:} | |
| 50 | 新增:func mustJSON(v string) []byte { b, _ := json.Marshal(v); return b } | |
| @@ -0,0 +1,61 @@ | ||
| 1 | 新增:package diagnostics | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "io" | |
| 5 | 新增: "os" | |
| 6 | 新增: "path/filepath" | |
| 7 | 新增:) | |
| 8 | 新增: | |
| 9 | 新增:// ImportLegacy consumes only the old Cage-owned logs. Limit reads so an old | |
| 10 | 新增:// unbounded file cannot exhaust memory; omit a partial first line at the tail. | |
| 11 | 新增:func (s *Store) ImportLegacy(profile string) error { | |
| 12 | 新增: paths := []string{"control.log", filepath.Join("proxy", "runtime.log"), filepath.Join("proxy", "validation.log"), filepath.Join("state", "setup.log")} | |
| 13 | 新增: for _, relative := range paths { | |
| 14 | 新增: path := filepath.Join(profile, relative) | |
| 15 | 新增: st, err := os.Lstat(path) | |
| 16 | 新增: if os.IsNotExist(err) { | |
| 17 | 新增: continue | |
| 18 | 新增: } | |
| 19 | 新增: if err != nil { | |
| 20 | 新增: return err | |
| 21 | 新增: } | |
| 22 | 新增: if !st.Mode().IsRegular() { | |
| 23 | 新增: continue | |
| 24 | 新增: } | |
| 25 | 新增: if s.now().Sub(st.ModTime()) > s.retention { | |
| 26 | 新增: if err := os.Remove(path); err != nil { | |
| 27 | 新增: return err | |
| 28 | 新增: } | |
| 29 | 新增: continue | |
| 30 | 新增: } | |
| 31 | 新增: f, err := os.Open(path) | |
| 32 | 新增: if err != nil { | |
| 33 | 新增: return err | |
| 34 | 新增: } | |
| 35 | 新增: const limit = 256 << 10 | |
| 36 | 新增: if st.Size() > limit { | |
| 37 | 新增: _, _ = f.Seek(st.Size()-limit, io.SeekStart) | |
| 38 | 新增: } | |
| 39 | 新增: r := io.LimitReader(f, limit) | |
| 40 | 新增: if st.Size() > limit { // Discard the cut line before framing secret values. | |
| 41 | 新增: var one [1]byte | |
| 42 | 新增: for { | |
| 43 | 新增: n, e := r.Read(one[:]) | |
| 44 | 新增: if n == 0 || e != nil || one[0] == '\n' { | |
| 45 | 新增: break | |
| 46 | 新增: } | |
| 47 | 新增: } | |
| 48 | 新增: } | |
| 49 | 新增: stream := s.Stream("legacy", "warn") | |
| 50 | 新增: _, err = io.Copy(stream, r) | |
| 51 | 新增: _ = stream.Close() | |
| 52 | 新增: f.Close() | |
| 53 | 新增: if err != nil { | |
| 54 | 新增: return err | |
| 55 | 新增: } | |
| 56 | 新增: if err = os.Remove(path); err != nil { | |
| 57 | 新增: return err | |
| 58 | 新增: } | |
| 59 | 新增: } | |
| 60 | 新增: return nil | |
| 61 | 新增:} | |
| @@ -0,0 +1,11 @@ | ||
| 1 | 新增://go:build !windows | |
| 2 | 新增: | |
| 3 | 新增:package diagnostics | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "golang.org/x/sys/unix" | |
| 7 | 新增: "os" | |
| 8 | 新增:) | |
| 9 | 新增: | |
| 10 | 新增:func lock(f *os.File) error { return unix.Flock(int(f.Fd()), unix.LOCK_EX) } | |
| 11 | 新增:func unlock(f *os.File) { _ = unix.Flock(int(f.Fd()), unix.LOCK_UN) } | |
| @@ -0,0 +1,13 @@ | ||
| 1 | 新增:package diagnostics | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "golang.org/x/sys/windows" | |
| 5 | 新增: "os" | |
| 6 | 新增:) | |
| 7 | 新增: | |
| 8 | 新增:func lock(f *os.File) error { | |
| 9 | 新增: return windows.LockFileEx(windows.Handle(f.Fd()), windows.LOCKFILE_EXCLUSIVE_LOCK, 0, 1, 0, new(windows.Overlapped)) | |
| 10 | 新增:} | |
| 11 | 新增:func unlock(f *os.File) { | |
| 12 | 新增: _ = windows.UnlockFileEx(windows.Handle(f.Fd()), 0, 1, 0, new(windows.Overlapped)) | |
| 13 | 新增:} | |
| @@ -0,0 +1,33 @@ | ||
| 1 | 新增:// Package diagnostics owns Cage's local, bounded diagnostic record. Never pass | |
| 2 | 新增:// terminal traffic, user files, request bodies or credential objects to it. | |
| 3 | 新增:package diagnostics | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "regexp" | |
| 7 | 新增: "strings" | |
| 8 | 新增:) | |
| 9 | 新增: | |
| 10 | 新增:var patterns = []struct { | |
| 11 | 新增: re *regexp.Regexp | |
| 12 | 新增: replacement string | |
| 13 | 新增:}{ | |
| 14 | 新增: {regexp.MustCompile(`\x1b\[[0-?]*[ -/]*[@-~]`), ""}, | |
| 15 | 新增: {regexp.MustCompile(`(?im)^(\s*(?:cookie|set-cookie|authorization|proxy-authorization)\s*[:=]).*$`), "${1} [redacted]"}, | |
| 16 | 新增: {regexp.MustCompile(`(?is)-----BEGIN [^-]*(?:PRIVATE KEY|CERTIFICATE)-----.*?(?:-----END [^-]+-----|$)`), "[redacted key]"}, | |
| 17 | 新增: {regexp.MustCompile(`(?i)\b[a-z][a-z0-9+.-]*://[^\s<>"'` + "`" + `]+`), "[url]"}, | |
| 18 | 新增: {regexp.MustCompile(`(?i)\b(?:Bearer|Basic)\s+[a-z0-9._~+/=-]+`), "[redacted authorization]"}, | |
| 19 | 新增: {regexp.MustCompile(`(?i)(["']?(?:password|passwd|pwd|token|access[_-]?token|refresh[_-]?token|id[_-]?token|api[_-]?key|apikey|secret|client[_-]?secret|authorization|proxy-authorization|cookie|set-cookie|auth|credential|subscription[_-]?url)["']?\s*[:=]\s*)(?:"[^"\r\n]*"|'[^'\r\n]*'|[^\s,;}]+)`), "${1}[redacted]"}, | |
| 20 | 新增: {regexp.MustCompile(`\b(?:sk-[A-Za-z0-9_-]{8,}|gh[pousr]_[A-Za-z0-9_]{12,}|github_pat_[A-Za-z0-9_]+|eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+)\b`), "[redacted token]"}, | |
| 21 | 新增: {regexp.MustCompile(`\b[a-fA-F0-9]{32,}\b`), "[redacted id]"}, | |
| 22 | 新增: {regexp.MustCompile(`(?i)[a-z]:[\\/][^\r\n"'<>:]+`), "[home path]"}, | |
| 23 | 新增: {regexp.MustCompile(`(?i)/(?:Users|home|Volumes|mnt|media|private|tmp|var|opt|Applications|usr|etc|run)/[^\r\n"'<>:]+`), "[home path]"}, | |
| 24 | 新增: {regexp.MustCompile(`[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}`), "[email]"}, | |
| 25 | 新增: {regexp.MustCompile(`\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b`), "[ip]"}, | |
| 26 | 新增:} | |
| 27 | 新增: | |
| 28 | 新增:func Redact(s string) string { | |
| 29 | 新增: for _, p := range patterns { | |
| 30 | 新增: s = p.re.ReplaceAllString(s, p.replacement) | |
| 31 | 新增: } | |
| 32 | 新增: return strings.ToValidUTF8(s, "�") | |
| 33 | 新增:} | |
| @@ -0,0 +1,234 @@ | ||
| 1 | 新增:package diagnostics | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "bufio" | |
| 5 | 新增: "encoding/json" | |
| 6 | 新增: "errors" | |
| 7 | 新增: "fmt" | |
| 8 | 新增: "io" | |
| 9 | 新增: "os" | |
| 10 | 新增: "path/filepath" | |
| 11 | 新增: "sort" | |
| 12 | 新增: "strings" | |
| 13 | 新增: "sync" | |
| 14 | 新增: "time" | |
| 15 | 新增: | |
| 16 | 新增: "github.com/sylvinus/agent-vm/internal/host" | |
| 17 | 新增:) | |
| 18 | 新增: | |
| 19 | 新增:const ( | |
| 20 | 新增: RetentionDays = 14 | |
| 21 | 新增: MaxBytes int64 = 40 << 20 | |
| 22 | 新增: FileBytes int64 = 5 << 20 | |
| 23 | 新增: MaxMessage = 24 << 10 | |
| 24 | 新增:) | |
| 25 | 新增: | |
| 26 | 新增:type Store struct { | |
| 27 | 新增: dir string | |
| 28 | 新增: maxBytes, fileBytes int64 | |
| 29 | 新增: retention time.Duration | |
| 30 | 新增: now func() time.Time | |
| 31 | 新增:} | |
| 32 | 新增: | |
| 33 | 新增:type Event struct { | |
| 34 | 新增: Time string `json:"time"` | |
| 35 | 新增: Level string `json:"level"` | |
| 36 | 新增: Source string `json:"source"` | |
| 37 | 新增: Message string `json:"message"` | |
| 38 | 新增: PID int `json:"pid"` | |
| 39 | 新增:} | |
| 40 | 新增: | |
| 41 | 新增:type Info struct { | |
| 42 | 新增: RetentionDays int `json:"retention_days"` | |
| 43 | 新增: MaxBytes int64 `json:"max_bytes"` | |
| 44 | 新增: GuestMaxBytes int64 `json:"guest_max_bytes"` | |
| 45 | 新增: Bytes int64 `json:"bytes"` | |
| 46 | 新增: Files int `json:"files"` | |
| 47 | 新增:} | |
| 48 | 新增: | |
| 49 | 新增:func New(profile string) *Store { | |
| 50 | 新增: return &Store{dir: filepath.Join(profile, "logs"), maxBytes: MaxBytes, fileBytes: FileBytes, retention: RetentionDays * 24 * time.Hour, now: time.Now} | |
| 51 | 新增:} | |
| 52 | 新增: | |
| 53 | 新增:// A process mutex also serializes callers on platforms whose file locks are | |
| 54 | 新增:// process scoped. The OS lock coordinates the controller and native helpers. | |
| 55 | 新增:var storeMu sync.Mutex | |
| 56 | 新增: | |
| 57 | 新增:func (s *Store) withLock(fn func() error) error { | |
| 58 | 新增: storeMu.Lock() | |
| 59 | 新增: defer storeMu.Unlock() | |
| 60 | 新增: if err := host.EnsurePrivateDir(s.dir); err != nil { | |
| 61 | 新增: return err | |
| 62 | 新增: } | |
| 63 | 新增: path := filepath.Join(s.dir, ".lock") | |
| 64 | 新增: f, err := privateFile(path, os.O_CREATE|os.O_RDWR) | |
| 65 | 新增: if err != nil { | |
| 66 | 新增: return err | |
| 67 | 新增: } | |
| 68 | 新增: defer f.Close() | |
| 69 | 新增: if err = lock(f); err != nil { | |
| 70 | 新增: return err | |
| 71 | 新增: } | |
| 72 | 新增: defer unlock(f) | |
| 73 | 新增: return fn() | |
| 74 | 新增:} | |
| 75 | 新增:func privateFile(path string, flags int) (*os.File, error) { | |
| 76 | 新增: if st, err := os.Lstat(path); err == nil { | |
| 77 | 新增: if !st.Mode().IsRegular() { | |
| 78 | 新增: return nil, errors.New("diagnostic file is not regular") | |
| 79 | 新增: } | |
| 80 | 新增: if err = host.CheckPrivateFile(path); err != nil { | |
| 81 | 新增: return nil, err | |
| 82 | 新增: } | |
| 83 | 新增: } else if !os.IsNotExist(err) { | |
| 84 | 新增: return nil, err | |
| 85 | 新增: } | |
| 86 | 新增: f, err := os.OpenFile(path, flags, 0600) | |
| 87 | 新增: if err == nil { | |
| 88 | 新增: err = host.ProtectFile(path) | |
| 89 | 新增: if err != nil { | |
| 90 | 新增: f.Close() | |
| 91 | 新增: return nil, err | |
| 92 | 新增: } | |
| 93 | 新增: } | |
| 94 | 新增: return f, err | |
| 95 | 新增:} | |
| 96 | 新增:func owned(name string) bool { | |
| 97 | 新增: return name == "events.jsonl" || strings.HasPrefix(name, "events-") && strings.HasSuffix(name, ".jsonl") | |
| 98 | 新增:} | |
| 99 | 新增:func (s *Store) files() ([]os.FileInfo, error) { | |
| 100 | 新增: entries, err := os.ReadDir(s.dir) | |
| 101 | 新增: if err != nil { | |
| 102 | 新增: return nil, err | |
| 103 | 新增: } | |
| 104 | 新增: var files []os.FileInfo | |
| 105 | 新增: for _, entry := range entries { | |
| 106 | 新增: if !owned(entry.Name()) { | |
| 107 | 新增: continue | |
| 108 | 新增: } | |
| 109 | 新增: info, err := entry.Info() | |
| 110 | 新增: if err != nil { | |
| 111 | 新增: if os.IsNotExist(err) { | |
| 112 | 新增: continue | |
| 113 | 新增: } | |
| 114 | 新增: return nil, err | |
| 115 | 新增: } | |
| 116 | 新增: if info.Mode().IsRegular() { | |
| 117 | 新增: files = append(files, info) | |
| 118 | 新增: } | |
| 119 | 新增: } | |
| 120 | 新增: sort.Slice(files, func(i, j int) bool { return files[i].ModTime().Before(files[j].ModTime()) }) | |
| 121 | 新增: return files, nil | |
| 122 | 新增:} | |
| 123 | 新增:func (s *Store) cleanLocked(reserve int64) error { | |
| 124 | 新增: files, err := s.files() | |
| 125 | 新增: if err != nil { | |
| 126 | 新增: return err | |
| 127 | 新增: } | |
| 128 | 新增: var size int64 | |
| 129 | 新增: var live []os.FileInfo | |
| 130 | 新增: for _, f := range files { | |
| 131 | 新增: born := f.ModTime() | |
| 132 | 新增: if first, err := privateFile(filepath.Join(s.dir, f.Name()), os.O_RDONLY); err == nil { | |
| 133 | 新增: line, _ := bufio.NewReader(io.LimitReader(first, MaxMessage*8)).ReadBytes('\n') | |
| 134 | 新增: first.Close() | |
| 135 | 新增: var event Event | |
| 136 | 新增: if json.Unmarshal(line, &event) == nil { | |
| 137 | 新增: if stamp, err := time.Parse(time.RFC3339Nano, event.Time); err == nil && stamp.Before(born) { | |
| 138 | 新增: born = stamp | |
| 139 | 新增: } | |
| 140 | 新增: } | |
| 141 | 新增: } | |
| 142 | 新增: if s.now().Sub(born) > s.retention { | |
| 143 | 新增: if err := os.Remove(filepath.Join(s.dir, f.Name())); err != nil { | |
| 144 | 新增: return err | |
| 145 | 新增: } | |
| 146 | 新增: } else { | |
| 147 | 新增: size += f.Size() | |
| 148 | 新增: live = append(live, f) | |
| 149 | 新增: } | |
| 150 | 新增: } | |
| 151 | 新增: for _, f := range live { | |
| 152 | 新增: if size+reserve <= s.maxBytes { | |
| 153 | 新增: break | |
| 154 | 新增: } | |
| 155 | 新增: if err := os.Remove(filepath.Join(s.dir, f.Name())); err != nil { | |
| 156 | 新增: return err | |
| 157 | 新增: } | |
| 158 | 新增: size -= f.Size() | |
| 159 | 新增: } | |
| 160 | 新增: return nil | |
| 161 | 新增:} | |
| 162 | 新增:func (s *Store) Clean() error { return s.withLock(func() error { return s.cleanLocked(0) }) } | |
| 163 | 新增:func (s *Store) Info() (info Info, err error) { | |
| 164 | 新增: info = Info{RetentionDays: RetentionDays, MaxBytes: s.maxBytes, GuestMaxBytes: 10 << 20} | |
| 165 | 新增: err = s.withLock(func() error { | |
| 166 | 新增: if err := s.cleanLocked(0); err != nil { | |
| 167 | 新增: return err | |
| 168 | 新增: } | |
| 169 | 新增: files, err := s.files() | |
| 170 | 新增: if err != nil { | |
| 171 | 新增: return err | |
| 172 | 新增: } | |
| 173 | 新增: for _, f := range files { | |
| 174 | 新增: info.Bytes += f.Size() | |
| 175 | 新增: info.Files++ | |
| 176 | 新增: } | |
| 177 | 新增: return nil | |
| 178 | 新增: }) | |
| 179 | 新增: return | |
| 180 | 新增:} | |
| 181 | 新增:func (s *Store) Record(level, source, message string) error { | |
| 182 | 新增: switch level { | |
| 183 | 新增: case "debug", "info", "warn", "error": | |
| 184 | 新增: default: | |
| 185 | 新增: level = "error" | |
| 186 | 新增: } | |
| 187 | 新增: // Redact before bounding: cutting a URL or key before redaction can expose a | |
| 188 | 新增: // prefix. Oversized lines are discarded in Stream, not split into fragments. | |
| 189 | 新增: message = Redact(message) | |
| 190 | 新增: if len(message) > MaxMessage { | |
| 191 | 新增: message = message[:MaxMessage] + " [truncated]" | |
| 192 | 新增: } | |
| 193 | 新增: source = Redact(source) | |
| 194 | 新增: if len(source) > 64 { | |
| 195 | 新增: source = "unknown" | |
| 196 | 新增: } | |
| 197 | 新增: b, err := json.Marshal(Event{Time: s.now().UTC().Format(time.RFC3339Nano), Level: level, Source: source, Message: message, PID: os.Getpid()}) | |
| 198 | 新增: if err != nil { | |
| 199 | 新增: return err | |
| 200 | 新增: } | |
| 201 | 新增: b = append(b, '\n') | |
| 202 | 新增: return s.withLock(func() error { | |
| 203 | 新增: if err := s.cleanLocked(int64(len(b))); err != nil { | |
| 204 | 新增: return err | |
| 205 | 新增: } | |
| 206 | 新增: path := filepath.Join(s.dir, "events.jsonl") | |
| 207 | 新增: if st, err := os.Lstat(path); err == nil && (st.Size()+int64(len(b)) > s.fileBytes || st.ModTime().UTC().Format("2006-01-02") != s.now().UTC().Format("2006-01-02")) { | |
| 208 | 新增: if !st.Mode().IsRegular() { | |
| 209 | 新增: return errors.New("diagnostic file is not regular") | |
| 210 | 新增: } | |
| 211 | 新增: next := filepath.Join(s.dir, fmt.Sprintf("events-%d-%d.jsonl", s.now().UnixNano(), os.Getpid())) | |
| 212 | 新增: if err := os.Rename(path, next); err != nil { | |
| 213 | 新增: return err | |
| 214 | 新增: } | |
| 215 | 新增: } | |
| 216 | 新增: f, err := privateFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND) | |
| 217 | 新增: if err != nil { | |
| 218 | 新增: return err | |
| 219 | 新增: } | |
| 220 | 新增: _, err = f.Write(b) | |
| 221 | 新增: return errors.Join(err, f.Close()) | |
| 222 | 新增: }) | |
| 223 | 新增:} | |
| 224 | 新增: | |
| 225 | 新增:var defaultMu sync.RWMutex | |
| 226 | 新增:var defaultStore *Store | |
| 227 | 新增: | |
| 228 | 新增:func SetDefault(s *Store) { defaultMu.Lock(); defaultStore = s; defaultMu.Unlock() } | |
| 229 | 新增:func Default() *Store { defaultMu.RLock(); defer defaultMu.RUnlock(); return defaultStore } | |
| 230 | 新增:func Log(level, source, message string) { | |
| 231 | 新增: if s := Default(); s != nil { | |
| 232 | 新增: _ = s.Record(level, source, message) | |
| 233 | 新增: } | |
| 234 | 新增:} | |
| @@ -0,0 +1,79 @@ | ||
| 1 | 新增:package diagnostics | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "bytes" | |
| 5 | 新增: "io" | |
| 6 | 新增: "sync" | |
| 7 | 新增:) | |
| 8 | 新增: | |
| 9 | 新增:// Stream frames arbitrary stdout/stderr writes before redacting. It never | |
| 10 | 新增:// writes a partial overlong line, so split credentials cannot leak at a bound. | |
| 11 | 新增:type Stream struct { | |
| 12 | 新增: mu sync.Mutex | |
| 13 | 新增: store *Store | |
| 14 | 新增: source, level string | |
| 15 | 新增: sink func(string) | |
| 16 | 新增: line []byte | |
| 17 | 新增: dropping, privateKey bool | |
| 18 | 新增:} | |
| 19 | 新增: | |
| 20 | 新增:func (s *Store) Stream(source, level string) *Stream { | |
| 21 | 新增: return &Stream{store: s, source: source, level: level} | |
| 22 | 新增:} | |
| 23 | 新增:func NewStream(store *Store, source, level string, sink func(string)) *Stream { | |
| 24 | 新增: return &Stream{store: store, source: source, level: level, sink: sink} | |
| 25 | 新增:} | |
| 26 | 新增:func (s *Stream) record(level, message string) { | |
| 27 | 新增: message = Redact(message) | |
| 28 | 新增: if s.sink != nil { | |
| 29 | 新增: s.sink(message + "\n") | |
| 30 | 新增: } | |
| 31 | 新增: if s.store != nil { | |
| 32 | 新增: _ = s.store.Record(level, s.source, message) | |
| 33 | 新增: } | |
| 34 | 新增:} | |
| 35 | 新增:func (s *Stream) emit() { | |
| 36 | 新增: line := string(s.line) | |
| 37 | 新增: if bytes.Contains(s.line, []byte("-----BEGIN ")) { | |
| 38 | 新增: s.privateKey = true | |
| 39 | 新增: } | |
| 40 | 新增: if s.privateKey { | |
| 41 | 新增: if bytes.Contains(s.line, []byte("-----END ")) { | |
| 42 | 新增: s.privateKey = false | |
| 43 | 新增: } | |
| 44 | 新增: } else if !s.dropping && len(s.line) > 0 { | |
| 45 | 新增: s.record(s.level, line) | |
| 46 | 新增: } | |
| 47 | 新增: if s.dropping { | |
| 48 | 新增: s.record("warn", "[oversized output line omitted]") | |
| 49 | 新增: } | |
| 50 | 新增: s.line = nil | |
| 51 | 新增: s.dropping = false | |
| 52 | 新增:} | |
| 53 | 新增:func (s *Stream) Write(p []byte) (int, error) { | |
| 54 | 新增: s.mu.Lock() | |
| 55 | 新增: defer s.mu.Unlock() | |
| 56 | 新增: for _, b := range p { | |
| 57 | 新增: if b == '\n' || b == '\r' { | |
| 58 | 新增: s.emit() | |
| 59 | 新增: continue | |
| 60 | 新增: } | |
| 61 | 新增: if s.dropping { | |
| 62 | 新增: continue | |
| 63 | 新增: } | |
| 64 | 新增: if len(s.line) >= MaxMessage { | |
| 65 | 新增: s.line = nil | |
| 66 | 新增: s.dropping = true | |
| 67 | 新增: continue | |
| 68 | 新增: } | |
| 69 | 新增: s.line = append(s.line, b) | |
| 70 | 新增: } | |
| 71 | 新增: return len(p), nil | |
| 72 | 新增:} | |
| 73 | 新增:func (s *Stream) Close() error { s.mu.Lock(); defer s.mu.Unlock(); s.emit(); return nil } | |
| 74 | 新增:func (s *Store) Capture(source, level string, r io.Reader) error { | |
| 75 | 新增: w := s.Stream(source, level) | |
| 76 | 新增: _, err := io.Copy(w, r) | |
| 77 | 新增: _ = w.Close() | |
| 78 | 新增: return err | |
| 79 | 新增:} | |
| @@ -0,0 +1,9 @@ | ||
| 1 | 新增:package host | |
| 2 | 新增: | |
| 3 | 新增:import "golang.org/x/sys/unix" | |
| 4 | 新增: | |
| 5 | 新增:// Free pages alone exclude reclaimable caches; use the kernel pressure signal. | |
| 6 | 新增:func MemoryPressure() bool { | |
| 7 | 新增: level, err := unix.SysctlUint32("kern.memorystatus_vm_pressure_level") | |
| 8 | 新增: return err == nil && level >= 4 | |
| 9 | 新增:} | |
| @@ -0,0 +1,29 @@ | ||
| 1 | 新增:package host | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "os" | |
| 5 | 新增: "strconv" | |
| 6 | 新增: "strings" | |
| 7 | 新增:) | |
| 8 | 新增: | |
| 9 | 新增:func MemoryPressure() bool { | |
| 10 | 新增: data, err := os.ReadFile("/proc/meminfo") | |
| 11 | 新增: if err != nil { | |
| 12 | 新增: return false | |
| 13 | 新增: } | |
| 14 | 新增: var total, available uint64 | |
| 15 | 新增: for _, line := range strings.Split(string(data), "\n") { | |
| 16 | 新增: f := strings.Fields(line) | |
| 17 | 新增: if len(f) < 2 { | |
| 18 | 新增: continue | |
| 19 | 新增: } | |
| 20 | 新增: v, _ := strconv.ParseUint(f[1], 10, 64) | |
| 21 | 新增: if f[0] == "MemTotal:" { | |
| 22 | 新增: total = v | |
| 23 | 新增: } | |
| 24 | 新增: if f[0] == "MemAvailable:" { | |
| 25 | 新增: available = v | |
| 26 | 新增: } | |
| 27 | 新增: } | |
| 28 | 新增: return total > 0 && available < total/10 | |
| 29 | 新增:} | |
| @@ -0,0 +1,5 @@ | ||
| 1 | 新增://go:build !darwin && !linux && !windows | |
| 2 | 新增: | |
| 3 | 新增:package host | |
| 4 | 新增: | |
| 5 | 新增:func MemoryPressure() bool { return false } | |
| @@ -0,0 +1,8 @@ | ||
| 1 | 新增:package host | |
| 2 | 新增: | |
| 3 | 新增:import "github.com/pbnjay/memory" | |
| 4 | 新增: | |
| 5 | 新增:func MemoryPressure() bool { | |
| 6 | 新增: total := memory.TotalMemory() | |
| 7 | 新增: return total > 0 && memory.FreeMemory() < total/10 | |
| 8 | 新增:} | |
| @@ -4,6 +4,7 @@ | ||
| 4 | 4 | package limaembed |
| 5 | 5 | |
| 6 | 6 | import ( |
| 7 | 新增: "context" | |
| 7 | 8 | "os" |
| 8 | 9 | "path/filepath" |
| 9 | 10 | "runtime" |
| @@ -12,15 +13,20 @@ import ( | ||
| 12 | 13 | "github.com/sirupsen/logrus" |
| 13 | 14 | "github.com/spf13/cobra" |
| 14 | 15 | |
| 16 | 新增: "github.com/docker/go-units" | |
| 15 | 17 | "github.com/lima-vm/lima/v2/pkg/debugutil" |
| 18 | 新增: "github.com/lima-vm/lima/v2/pkg/driver" | |
| 16 | 19 | "github.com/lima-vm/lima/v2/pkg/driver/external/server" |
| 17 | 20 | "github.com/lima-vm/lima/v2/pkg/envutil" |
| 21 | 新增: "github.com/lima-vm/lima/v2/pkg/hostagent" | |
| 18 | 22 | "github.com/lima-vm/lima/v2/pkg/hostagent/dns" |
| 23 | 新增: "github.com/lima-vm/lima/v2/pkg/limatype" | |
| 19 | 24 | "github.com/lima-vm/lima/v2/pkg/networks/usernet" |
| 20 | 25 | "github.com/lima-vm/lima/v2/pkg/osutil" |
| 21 | 26 | "github.com/lima-vm/sshocker/pkg/reversesshfs" |
| 22 | 27 | |
| 23 | 28 | "github.com/sylvinus/agent-vm/internal/cage" |
| 29 | 新增: "github.com/sylvinus/agent-vm/internal/diagnostics" | |
| 24 | 30 | "github.com/sylvinus/agent-vm/internal/guard" |
| 25 | 31 | "github.com/sylvinus/agent-vm/internal/netguard" |
| 26 | 32 | "github.com/sylvinus/agent-vm/internal/state" |
| @@ -40,6 +46,20 @@ func Run(args []string) bool { | ||
| 40 | 46 | if i == len(args) || args[i] != "hostagent" { |
| 41 | 47 | return false |
| 42 | 48 | } |
| 49 | 新增: var diagnosticStream *diagnostics.Stream | |
| 50 | 新增: if path := os.Getenv(cage.ConfigEnv); path != "" { | |
| 51 | 新增: hostagent.ManageResources = func(ctx context.Context, dir string, cfg *limatype.LimaYAML, balloon driver.MemoryBalloon, read func(context.Context, string) ([]byte, error)) func() { | |
| 52 | 新增: maximum, err := units.RAMInBytes(*cfg.Memory) | |
| 53 | 新增: if err != nil || *cfg.OS != limatype.LINUX { | |
| 54 | 新增: return func() {} | |
| 55 | 新增: } | |
| 56 | 新增: return cage.StartResourceManager(ctx, dir, uint64(maximum), *cfg.CPUs, read, balloon.SetMemoryTarget) | |
| 57 | 新增: } | |
| 58 | 新增: diagnosticStream = diagnostics.New(filepath.Dir(path)).Stream("vm-hostagent", "warn") | |
| 59 | 新增: diagnostics.SetDefault(diagnostics.New(filepath.Dir(path))) | |
| 60 | 新增: logrus.SetOutput(diagnosticStream) | |
| 61 | 新增: defer diagnosticStream.Close() | |
| 62 | 新增: } | |
| 43 | 63 | if runtime.GOOS == "windows" { |
| 44 | 64 | windowsPath() |
| 45 | 65 | } |
| @@ -127,6 +147,10 @@ func Run(args []string) bool { | ||
| 127 | 147 | // Its events, as limactl's, and a notice for each port it forwards. The |
| 128 | 148 | // instance is the last argument. |
| 129 | 149 | root.SetOut(newEventWatch(os.Stdout, args[len(args)-1])) |
| 150 | 新增: if diagnosticStream != nil { | |
| 151 | 新增: root.SetErr(diagnosticStream) | |
| 152 | 新增: } | |
| 153 | 新增: | |
| 130 | 154 | err = root.Execute() |
| 131 | 155 | if stopJobWatch != nil { |
| 132 | 156 | stopJobWatch() |
| @@ -18,6 +18,7 @@ import ( | ||
| 18 | 18 | "strconv" |
| 19 | 19 | "time" |
| 20 | 20 | |
| 21 | 新增: "github.com/sylvinus/agent-vm/internal/diagnostics" | |
| 21 | 22 | "github.com/sylvinus/agent-vm/internal/host" |
| 22 | 23 | ) |
| 23 | 24 | |
| @@ -69,8 +70,10 @@ func Validate(ctx context.Context, profile string, s Store) error { | ||
| 69 | 70 | defer cancel() |
| 70 | 71 | cmd := exec.CommandContext(ctx, core, "-t", "-d", dir, "-f", f.Name()) |
| 71 | 72 | cmd.Env = coreEnvironment(dir) |
| 72 | 删除: if output, e := cmd.CombinedOutput(); e != nil { | |
| 73 | 删除: _ = Write(filepath.Join(dir, "validation.log"), output) | |
| 73 | 新增: output := diagnostics.New(profile).Stream("proxy-validation", "error") | |
| 74 | 新增: defer output.Close() | |
| 75 | 新增: cmd.Stdout, cmd.Stderr = output, output | |
| 76 | 新增: if e := cmd.Run(); e != nil { | |
| 74 | 77 | return errors.New("代理核心拒绝该配置,请检查节点协议和参数;原配置已保留") |
| 75 | 78 | } |
| 76 | 79 | return nil |
| @@ -178,7 +181,7 @@ func Start(ctx context.Context, profile string, s Store) error { | ||
| 178 | 181 | return errors.New("Cage 代理端口已被占用,请更换独立端口") |
| 179 | 182 | } |
| 180 | 183 | l.Close() |
| 181 | 删除: core, err := CorePath() | |
| 184 | 新增: _, err = CorePath() | |
| 182 | 185 | if err != nil { |
| 183 | 186 | return err |
| 184 | 187 | } |
| @@ -200,12 +203,17 @@ func Start(ctx context.Context, profile string, s Store) error { | ||
| 200 | 203 | return err |
| 201 | 204 | } |
| 202 | 205 | _ = os.Remove(Socket(profile)) |
| 203 | 删除: log := filepath.Join(Dir(profile), "runtime.log") | |
| 204 | 删除: if err = Write(log, nil); err != nil { | |
| 206 | 新增: executable, err := os.Executable() | |
| 207 | 新增: if err != nil { | |
| 205 | 208 | return err |
| 206 | 209 | } |
| 210 | 新增: configPath := os.Getenv("CLAUDE_CAGE_CONFIG") | |
| 211 | 新增: if configPath == "" { | |
| 212 | 新增: configPath = filepath.Join(profile, "config.json") | |
| 213 | 新增: } | |
| 207 | 214 | escape := func(s string) string { var b bytes.Buffer; _ = xml.EscapeText(&b, []byte(s)); return b.String() } |
| 208 | 删除: plist := fmt.Sprintf(`<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict><key>Label</key><string>%s</string><key>ProgramArguments</key><array><string>%s</string><string>-d</string><string>%s</string><string>-f</string><string>%s</string></array><key>EnvironmentVariables</key><dict><key>HOME</key><string>%s</string><key>PATH</key><string>/usr/bin:/bin</string></dict><key>RunAtLoad</key><true/><key>StandardOutPath</key><string>%s</string><key>StandardErrorPath</key><string>%s</string></dict></plist>`, escape(label(profile)), escape(core), escape(Dir(profile)), escape(filepath.Join(Dir(profile), "config.yaml")), escape(Dir(profile)), escape(log), escape(log)) | |
| 215 | 新增: plist := fmt.Sprintf(`<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict><key>Label</key><string>%s</string><key>ProgramArguments</key><array><string>%s</string><string>log-relay</string><string>proxy</string></array><key>EnvironmentVariables</key><dict><key>HOME</key><string>%s</string><key>PATH</key><string>/usr/bin:/bin</string><key>CLAUDE_CAGE_CONFIG</key><string>%s</string></dict><key>RunAtLoad</key><true/></dict></plist>`, escape(label(profile)), escape(executable), escape(Dir(profile)), escape(configPath)) | |
| 216 | 新增: | |
| 209 | 217 | if err = Write(servicePath(profile), []byte(plist)); err != nil { |
| 210 | 218 | return err |
| 211 | 219 | } |
| @@ -14,6 +14,7 @@ import ( | ||
| 14 | 14 | "syscall" |
| 15 | 15 | "time" |
| 16 | 16 | |
| 17 | 新增: "github.com/sylvinus/agent-vm/internal/diagnostics" | |
| 17 | 18 | "github.com/sylvinus/agent-vm/internal/host" |
| 18 | 19 | "golang.org/x/sys/unix" |
| 19 | 20 | ) |
| @@ -197,19 +198,13 @@ func startLinuxCore(ctx context.Context, profile string, s Store) error { | ||
| 197 | 198 | return err |
| 198 | 199 | } |
| 199 | 200 | _ = os.Remove(Socket(profile)) |
| 200 | 删除: logPath := filepath.Join(Dir(profile), "runtime.log") | |
| 201 | 删除: if err := Write(logPath, nil); err != nil { | |
| 202 | 删除: return err | |
| 203 | 删除: } | |
| 204 | 删除: log, err := os.OpenFile(logPath, os.O_WRONLY|os.O_APPEND, 0600) | |
| 205 | 删除: if err != nil { | |
| 206 | 删除: return err | |
| 207 | 删除: } | |
| 208 | 删除: defer log.Close() | |
| 201 | 新增: log := diagnostics.New(profile).Stream("proxy", "warn") | |
| 202 | 新增: | |
| 209 | 203 | cmd := exec.Command(core, "-d", Dir(profile), "-f", path) |
| 210 | 204 | cmd.Env, cmd.Stdout, cmd.Stderr = coreEnvironment(Dir(profile)), log, log |
| 211 | 205 | cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true} |
| 212 | 206 | if err := cmd.Start(); err != nil { |
| 207 | 新增: _ = log.Close() | |
| 213 | 208 | return err |
| 214 | 209 | } |
| 215 | 210 | record, err := identifyLinuxCore(cmd.Process.Pid) |
| @@ -226,7 +221,14 @@ func startLinuxCore(ctx context.Context, profile string, s Store) error { | ||
| 226 | 221 | return err |
| 227 | 222 | } |
| 228 | 223 | exited := make(chan struct{}) |
| 229 | 删除: go func() { _ = cmd.Wait(); close(exited) }() | |
| 224 | 新增: go func() { | |
| 225 | 新增: err := cmd.Wait() | |
| 226 | 新增: _ = log.Close() | |
| 227 | 新增: if err != nil { | |
| 228 | 新增: _ = diagnostics.New(profile).Record("error", "proxy", "core exited: "+err.Error()) | |
| 229 | 新增: } | |
| 230 | 新增: close(exited) | |
| 231 | 新增: }() | |
| 230 | 232 | ticker := time.NewTicker(100 * time.Millisecond) |
| 231 | 233 | defer ticker.Stop() |
| 232 | 234 | timeout := time.NewTimer(15 * time.Second) |
| @@ -13,6 +13,7 @@ import ( | ||
| 13 | 13 | "syscall" |
| 14 | 14 | "time" |
| 15 | 15 | |
| 16 | 新增: "github.com/sylvinus/agent-vm/internal/diagnostics" | |
| 16 | 17 | "github.com/sylvinus/agent-vm/internal/host" |
| 17 | 18 | "golang.org/x/sys/windows" |
| 18 | 19 | ) |
| @@ -150,19 +151,13 @@ func startWindowsCore(ctx context.Context, profile string, s Store) error { | ||
| 150 | 151 | return err |
| 151 | 152 | } |
| 152 | 153 | _ = os.Remove(Socket(profile)) |
| 153 | 删除: logPath := filepath.Join(Dir(profile), "runtime.log") | |
| 154 | 删除: if err := Write(logPath, nil); err != nil { | |
| 155 | 删除: return err | |
| 156 | 删除: } | |
| 157 | 删除: log, err := os.OpenFile(logPath, os.O_WRONLY|os.O_APPEND, 0600) | |
| 158 | 删除: if err != nil { | |
| 159 | 删除: return err | |
| 160 | 删除: } | |
| 161 | 删除: defer log.Close() | |
| 154 | 新增: log := diagnostics.New(profile).Stream("proxy", "warn") | |
| 155 | 新增: | |
| 162 | 156 | cmd := exec.Command(core, "-d", Dir(profile), "-f", path) |
| 163 | 157 | cmd.Env, cmd.Stdout, cmd.Stderr = coreEnvironment(Dir(profile)), log, log |
| 164 | 158 | cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true, CreationFlags: windows.CREATE_NEW_PROCESS_GROUP | windows.DETACHED_PROCESS} |
| 165 | 159 | if err := cmd.Start(); err != nil { |
| 160 | 新增: _ = log.Close() | |
| 166 | 161 | return err |
| 167 | 162 | } |
| 168 | 163 | handle, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, uint32(cmd.Process.Pid)) |
| @@ -184,7 +179,13 @@ func startWindowsCore(ctx context.Context, profile string, s Store) error { | ||
| 184 | 179 | _ = cmd.Wait() |
| 185 | 180 | return err |
| 186 | 181 | } |
| 187 | 删除: go func() { _ = cmd.Wait() }() | |
| 182 | 新增: go func() { | |
| 183 | 新增: err := cmd.Wait() | |
| 184 | 新增: _ = log.Close() | |
| 185 | 新增: if err != nil { | |
| 186 | 新增: _ = diagnostics.New(profile).Record("error", "proxy", "core exited: "+err.Error()) | |
| 187 | 新增: } | |
| 188 | 新增: }() | |
| 188 | 189 | ticker := time.NewTicker(100 * time.Millisecond) |
| 189 | 190 | defer ticker.Stop() |
| 190 | 191 | timeout := time.NewTimer(15 * time.Second) |
| @@ -496,7 +496,11 @@ func (l *Lima) Start(ctx context.Context, name string, log io.Writer) error { | ||
| 496 | 496 | } |
| 497 | 497 | // Here, so that VMs made before it get it too; nothing is written when |
| 498 | 498 | // it is there already. |
| 499 | 删除: if err := l.Edit(ctx, name, Settings{noEphemeralPorts: true}); err != nil { | |
| 499 | 新增: settings := Settings{noEphemeralPorts: true} | |
| 500 | 新增: if os.Getenv(cage.ConfigEnv) != "" { | |
| 501 | 新增: settings.MemoryGiB, settings.CPUs = cage.ResourceLimits() | |
| 502 | 新增: } | |
| 503 | 新增: if err := l.Edit(ctx, name, settings); err != nil { | |
| 500 | 504 | return err |
| 501 | 505 | } |
| 502 | 506 | if inst, err = l.inspect(ctx, name); err != nil { |
| @@ -43,6 +43,30 @@ func (s *Server) browser(w http.ResponseWriter, r *http.Request) { | ||
| 43 | 43 | _, _ = w.Write(data) |
| 44 | 44 | } |
| 45 | 45 | |
| 46 | 新增:func (s *Server) remoteInput(w http.ResponseWriter, r *http.Request) { | |
| 47 | 新增: // The authenticated workbench endpoint shares browser transport with both | |
| 48 | 新增: // graphical sessions; it does not create another guest listener. | |
| 49 | 新增: var input browserInput | |
| 50 | 新增: if !readJSON(w, r, &input) { | |
| 51 | 新增: return | |
| 52 | 新增: } | |
| 53 | 新增: data, err := s.browserAction(r.Context(), "ime", &input) | |
| 54 | 新增: if err != nil { | |
| 55 | 新增: status := http.StatusBadGateway | |
| 56 | 新增: var inputError browserInputError | |
| 57 | 新增: if errors.As(err, &inputError) { | |
| 58 | 新增: status = http.StatusBadRequest | |
| 59 | 新增: } | |
| 60 | 新增: if errors.Is(err, errBrowserNotReady) { | |
| 61 | 新增: status = http.StatusConflict | |
| 62 | 新增: } | |
| 63 | 新增: http.Error(w, err.Error(), status) | |
| 64 | 新增: return | |
| 65 | 新增: } | |
| 66 | 新增: w.Header().Set("Content-Type", "application/json") | |
| 67 | 新增: _, _ = w.Write(data) | |
| 68 | 新增:} | |
| 69 | 新增: | |
| 46 | 70 | func (s *Server) browserEvents(w http.ResponseWriter, r *http.Request) { |
| 47 | 71 | body, err := s.subscribeBrowser(r.Context()) |
| 48 | 72 | if err != nil { |
| @@ -16,12 +16,19 @@ var ( | ||
| 16 | 16 | type browserInputError struct{ error } |
| 17 | 17 | |
| 18 | 18 | type browserInput struct { |
| 19 | 删除: ID string `json:"id"` | |
| 20 | 删除: URL string `json:"url"` | |
| 21 | 删除: Width int `json:"width,omitempty"` | |
| 22 | 删除: Height int `json:"height,omitempty"` | |
| 23 | 删除: Workspace string `json:"workspace,omitempty"` | |
| 24 | 删除: Text string `json:"text,omitempty"` | |
| 19 | 新增: ID string `json:"id"` | |
| 20 | 新增: URL string `json:"url"` | |
| 21 | 新增: Width int `json:"width,omitempty"` | |
| 22 | 新增: Height int `json:"height,omitempty"` | |
| 23 | 新增: Workspace string `json:"workspace,omitempty"` | |
| 24 | 新增: Text string `json:"text,omitempty"` | |
| 25 | 新增: Mode string `json:"mode,omitempty"` | |
| 26 | 新增: Target string `json:"target,omitempty"` | |
| 27 | 新增: Session string `json:"session,omitempty"` | |
| 28 | 新增: Context string `json:"context,omitempty"` | |
| 29 | 新增: Sequence int `json:"sequence"` | |
| 30 | 新增: SelectionStart int `json:"selectionStart,omitempty"` | |
| 31 | 新增: SelectionEnd int `json:"selectionEnd,omitempty"` | |
| 25 | 32 | } |
| 26 | 33 | |
| 27 | 34 | func (s *Server) browserClient() *browserClient { |
| @@ -57,6 +64,21 @@ func (s *Server) browserAction(ctx context.Context, action string, input *browse | ||
| 57 | 64 | if action == "insert-text" && (input.ID == "" || input.Text == "" || len(input.Text) > 8192) { |
| 58 | 65 | return nil, browserInputError{errors.New("输入文字或目标标签无效")} |
| 59 | 66 | } |
| 67 | 新增: if action == "ime" { | |
| 68 | 新增: selectionLimit := 0 | |
| 69 | 新增: for _, char := range input.Text { | |
| 70 | 新增: selectionLimit++ | |
| 71 | 新增: if char > 0xffff { | |
| 72 | 新增: selectionLimit++ | |
| 73 | 新增: } | |
| 74 | 新增: } | |
| 75 | 新增: validMode := input.Mode == "status" || input.Mode == "begin" || input.Mode == "update" || input.Mode == "commit" || input.Mode == "cancel" | |
| 76 | 新增: validTarget := input.Target == "browser" && input.ID != "" || input.Target == "desktop" && input.ID == "desktop" | |
| 77 | 新增: validSession := input.Mode == "status" || validInputToken(input.Session) | |
| 78 | 新增: if !validTarget || !validMode || !validSession || input.Mode == "begin" && !validInputToken(input.Context) || input.Sequence < 0 || len(input.Text) > 8192 || input.SelectionStart < 0 || input.SelectionEnd < input.SelectionStart || input.SelectionEnd > selectionLimit { | |
| 79 | 新增: return nil, browserInputError{errors.New("输入法组合状态无效")} | |
| 80 | 新增: } | |
| 81 | 新增: } | |
| 60 | 82 | if action == "new" && input.URL == "" { |
| 61 | 83 | s.mu.Lock() |
| 62 | 84 | input.URL = browserHomeURL(s.preferences) |
| @@ -94,6 +116,18 @@ func (s *Server) browserAction(ctx context.Context, action string, input *browse | ||
| 94 | 116 | return data, err |
| 95 | 117 | } |
| 96 | 118 | |
| 119 | 新增:func validInputToken(value string) bool { | |
| 120 | 新增: if len(value) != 32 { | |
| 121 | 新增: return false | |
| 122 | 新增: } | |
| 123 | 新增: for _, char := range value { | |
| 124 | 新增: if !(char >= '0' && char <= '9' || char >= 'a' && char <= 'f') { | |
| 125 | 新增: return false | |
| 126 | 新增: } | |
| 127 | 新增: } | |
| 128 | 新增: return true | |
| 129 | 新增:} | |
| 130 | 新增: | |
| 97 | 131 | func (s *Server) subscribeBrowser(ctx context.Context) (io.ReadCloser, error) { |
| 98 | 132 | s.mu.Lock() |
| 99 | 133 | ready, token := s.ready, s.credentials.Token |
| @@ -47,3 +47,70 @@ func TestBrowserTextRequiresSessionAndExplicitTarget(t *testing.T) { | ||
| 47 | 47 | t.Fatal("valid input rejected", w.Code, w.Body.String()) |
| 48 | 48 | } |
| 49 | 49 | } |
| 50 | 新增: | |
| 51 | 新增:func TestBrowserIMERequiresSessionAndValidSelection(t *testing.T) { | |
| 52 | 新增: s := testServer(t) | |
| 53 | 新增: s.ready = true | |
| 54 | 新增: s.credentials.Token = "guest-test-token" | |
| 55 | 新增: var requests []map[string]any | |
| 56 | 新增: s.browserControl = browserClientForTest(t, s, browserTransport(func(r *http.Request) (*http.Response, error) { | |
| 57 | 新增: if r.URL.Path != "/ime" || r.Header.Get("Authorization") != "Bearer guest-test-token" { | |
| 58 | 新增: t.Fatalf("wrong IME destination or authentication: %s", r.URL.Path) | |
| 59 | 新增: } | |
| 60 | 新增: var input map[string]any | |
| 61 | 新增: if err := json.NewDecoder(r.Body).Decode(&input); err != nil { | |
| 62 | 新增: t.Fatal(err) | |
| 63 | 新增: } | |
| 64 | 新增: requests = append(requests, input) | |
| 65 | 新增: return &http.Response{StatusCode: 200, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(`{"ok":true}`))}, nil | |
| 66 | 新增: })) | |
| 67 | 新增: path := "/api/input" | |
| 68 | 新增: valid := `{"target":"browser","session":"0123456789abcdef0123456789abcdef","id":"tab-1","mode":"update","text":"nihao","selectionStart":5,"selectionEnd":5}` | |
| 69 | 新增: if w := request(s, "POST", path, s.origin, valid, false); w.Code != 401 { | |
| 70 | 新增: t.Fatal("unauthenticated IME input accepted", w.Code) | |
| 71 | 新增: } | |
| 72 | 新增: if w := request(s, "POST", path, "https://example.com", valid, true); w.Code != 403 { | |
| 73 | 新增: t.Fatal("cross-origin IME input accepted", w.Code) | |
| 74 | 新增: } | |
| 75 | 新增: for _, body := range []string{ | |
| 76 | 新增: `{"target":"desktop","id":"tab-1","mode":"status"}`, | |
| 77 | 新增: `{"target":"browser","id":"tab-1","mode":"begin","session":"0123456789abcdef0123456789abcdef","context":"expired"}`, | |
| 78 | 新增: `{"target":"desktop","id":"desktop","mode":"commit","session":"invalid","text":"?"}`, | |
| 79 | 新增: `{"target":"browser","session":"0123456789abcdef0123456789abcdef","mode":"update","text":"n"}`, | |
| 80 | 新增: `{"target":"browser","session":"0123456789abcdef0123456789abcdef","id":"tab-1","mode":"unknown"}`, | |
| 81 | 新增: `{"target":"browser","session":"0123456789abcdef0123456789abcdef","id":"tab-1","mode":"update","text":"nihao","selectionStart":6,"selectionEnd":6}`, | |
| 82 | 新增: `{"target":"browser","session":"0123456789abcdef0123456789abcdef","id":"tab-1","mode":"update","text":"n","selectionStart":1,"selectionEnd":0}`, | |
| 83 | 新增: `{"target":"browser","session":"0123456789abcdef0123456789abcdef","id":"tab-1","mode":"update","text":"` + strings.Repeat("n", 8193) + `"}`, | |
| 84 | 新增: } { | |
| 85 | 新增: if w := request(s, "POST", path, s.origin, body, true); w.Code != 400 { | |
| 86 | 新增: t.Fatalf("invalid IME input accepted (%s): %d", body[:min(len(body), 80)], w.Code) | |
| 87 | 新增: } | |
| 88 | 新增: } | |
| 89 | 新增: if len(requests) != 0 { | |
| 90 | 新增: t.Fatal("rejected IME input reached guest") | |
| 91 | 新增: } | |
| 92 | 新增: for _, body := range []string{ | |
| 93 | 新增: valid, | |
| 94 | 新增: `{"target":"browser","session":"0123456789abcdef0123456789abcdef","id":"tab-1","mode":"commit","text":"你好","selectionStart":0,"selectionEnd":0}`, | |
| 95 | 新增: `{"target":"browser","session":"0123456789abcdef0123456789abcdef","id":"tab-1","mode":"cancel","text":"","selectionStart":0,"selectionEnd":0}`, | |
| 96 | 新增: } { | |
| 97 | 新增: if w := request(s, "POST", path, s.origin, body, true); w.Code != 200 { | |
| 98 | 新增: t.Fatalf("valid IME input rejected: %d %s", w.Code, w.Body.String()) | |
| 99 | 新增: } | |
| 100 | 新增: } | |
| 101 | 新增: if len(requests) != 3 || requests[0]["mode"] != "update" || requests[1]["text"] != "你好" || requests[2]["mode"] != "cancel" { | |
| 102 | 新增: t.Fatalf("IME update/commit/cancel order changed: %#v", requests) | |
| 103 | 新增: } | |
| 104 | 新增: for _, body := range []string{ | |
| 105 | 新增: `{"target":"desktop","id":"desktop","mode":"status"}`, | |
| 106 | 新增: `{"target":"desktop","id":"desktop","mode":"begin","session":"0123456789abcdef0123456789abcdef","context":"abcdef0123456789abcdef0123456789","sequence":0}`, | |
| 107 | 新增: `{"target":"desktop","id":"desktop","mode":"update","session":"0123456789abcdef0123456789abcdef","sequence":1,"text":"🙂n","selectionStart":2,"selectionEnd":3}`, | |
| 108 | 新增: } { | |
| 109 | 新增: if w := request(s, "POST", path, s.origin, body, true); w.Code != 200 { | |
| 110 | 新增: t.Fatalf("desktop input rejected: %d %s", w.Code, w.Body.String()) | |
| 111 | 新增: } | |
| 112 | 新增: } | |
| 113 | 新增: if requests[3]["target"] != "desktop" || requests[4]["context"] != "abcdef0123456789abcdef0123456789" || requests[4]["sequence"] != float64(0) || requests[5]["sequence"] != float64(1) || requests[5]["selectionEnd"] != float64(3) { | |
| 114 | 新增: t.Fatal("Desktop session or UTF-16 selection changed") | |
| 115 | 新增: } | |
| 116 | 新增:} | |
| @@ -15,11 +15,12 @@ import ( | ||
| 15 | 15 | ) |
| 16 | 16 | |
| 17 | 17 | type claudeDesktopState struct { |
| 18 | 删除: Installed bool `json:"installed"` | |
| 19 | 删除: Version string `json:"version"` | |
| 20 | 删除: Running bool `json:"running"` | |
| 21 | 删除: Failed bool `json:"failed"` | |
| 22 | 删除: Managed bool `json:"managed"` | |
| 18 | 新增: Installed bool `json:"installed"` | |
| 19 | 新增: Version string `json:"version"` | |
| 20 | 新增: Running bool `json:"running"` | |
| 21 | 新增: Failed bool `json:"failed"` | |
| 22 | 新增: Managed bool `json:"managed"` | |
| 23 | 新增: FailureReason string `json:"failure_reason,omitempty"` | |
| 23 | 24 | } |
| 24 | 25 | |
| 25 | 26 | const claudeDesktopSnapshot = `python3 - <<'CAGE_DESKTOP_STATE' |
| @@ -30,7 +31,8 @@ def run(*args): | ||
| 30 | 31 | package=run('dpkg-query','-W','-f=${Status}\n${Version}','claude-desktop').splitlines() |
| 31 | 32 | installed=bool(package and package[0]=='install ok installed') |
| 32 | 33 | state=run('systemctl','is-active','cage-claude-desktop.service') |
| 33 | 删除:print(json.dumps({'installed':installed,'version':package[1] if installed else '', 'running':state=='active','failed':state=='failed','managed':Path('/run/cage-desktop/keyring-ready').exists()})) | |
| 34 | 新增:result=run('systemctl','show','--property=Result','--value','cage-claude-desktop.service') if state=='failed' else '' | |
| 35 | 新增:print(json.dumps({'installed':installed,'version':package[1] if installed else '', 'running':state=='active','failed':state=='failed','managed':Path('/run/cage-desktop/keyring-ready').exists(),'failure_reason':'oom-kill' if result=='oom-kill' else ''})) | |
| 34 | 36 | CAGE_DESKTOP_STATE` |
| 35 | 37 | |
| 36 | 38 | func (s *Server) claudeDesktopStatus(w http.ResponseWriter, r *http.Request) { |
| @@ -1,6 +1,41 @@ | ||
| 1 | 1 | package workbench |
| 2 | 2 | |
| 3 | 删除:import "testing" | |
| 3 | 新增:import ( | |
| 4 | 新增: "encoding/json" | |
| 5 | 新增: "os" | |
| 6 | 新增: "os/exec" | |
| 7 | 新增: "path/filepath" | |
| 8 | 新增: "testing" | |
| 9 | 新增:) | |
| 10 | 新增: | |
| 11 | 新增:func TestClaudeDesktopSnapshotFailureReason(t *testing.T) { | |
| 12 | 新增: if _, err := exec.LookPath("python3"); err != nil { | |
| 13 | 新增: t.Skip("python3 unavailable") | |
| 14 | 新增: } | |
| 15 | 新增: dir := t.TempDir() | |
| 16 | 新增: for name, script := range map[string]string{ | |
| 17 | 新增: "dpkg-query": "#!/bin/sh\nprintf 'install ok installed\\n4.4212.0\\n'\n", | |
| 18 | 新增: "systemctl": "#!/bin/sh\nif [ \"$1\" = is-active ]; then printf '%s\\n' \"$TEST_ACTIVE\"; else printf '%s\\n' \"$TEST_RESULT\"; fi\n", | |
| 19 | 新增: } { | |
| 20 | 新增: if err := os.WriteFile(filepath.Join(dir, name), []byte(script), 0755); err != nil { | |
| 21 | 新增: t.Fatal(err) | |
| 22 | 新增: } | |
| 23 | 新增: } | |
| 24 | 新增: for _, tc := range []struct{ active, result, want string }{ | |
| 25 | 新增: {"failed", "oom-kill", "oom-kill"}, {"failed", "exit-code", ""}, {"active", "oom-kill", ""}, | |
| 26 | 新增: } { | |
| 27 | 新增: cmd := exec.Command("sh", "-c", claudeDesktopSnapshot) | |
| 28 | 新增: cmd.Env = append(os.Environ(), "PATH="+dir+":"+os.Getenv("PATH"), "TEST_ACTIVE="+tc.active, "TEST_RESULT="+tc.result) | |
| 29 | 新增: out, err := cmd.CombinedOutput() | |
| 30 | 新增: var state claudeDesktopState | |
| 31 | 新增: if err != nil || json.Unmarshal(out, &state) != nil { | |
| 32 | 新增: t.Fatalf("snapshot: %v %s", err, out) | |
| 33 | 新增: } | |
| 34 | 新增: if state.FailureReason != tc.want || state.Failed != (tc.active == "failed") || state.Running != (tc.active == "active") { | |
| 35 | 新增: t.Fatalf("%+v: %+v", tc, state) | |
| 36 | 新增: } | |
| 37 | 新增: } | |
| 38 | 新增:} | |
| 4 | 39 | |
| 5 | 40 | func TestClaudeDesktopControlBoundary(t *testing.T) { |
| 6 | 41 | s := testServer(t) |
| @@ -329,15 +329,9 @@ func startController(configPath string) error { | ||
| 329 | 329 | if err != nil { |
| 330 | 330 | return err |
| 331 | 331 | } |
| 332 | 删除: log, err := os.OpenFile(filepath.Join(profile, "control.log"), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600) | |
| 333 | 删除: if err != nil { | |
| 334 | 删除: return err | |
| 335 | 删除: } | |
| 336 | 删除: defer log.Close() | |
| 337 | 删除: cmd := exec.Command(exe, "serve") | |
| 332 | 新增: cmd := exec.Command(exe, "log-relay", "controller") | |
| 338 | 333 | cmd.Dir = profile |
| 339 | 334 | cmd.Env = append(os.Environ(), cage.ConfigEnv+"="+configPath) |
| 340 | 删除: cmd.Stdout, cmd.Stderr = log, log | |
| 341 | 335 | detachController(cmd) |
| 342 | 336 | if err = cmd.Start(); err != nil { |
| 343 | 337 | return err |
| @@ -0,0 +1,201 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "archive/zip" | |
| 5 | 新增: "bufio" | |
| 6 | 新增: "bytes" | |
| 7 | 新增: "context" | |
| 8 | 新增: "errors" | |
| 9 | 新增: "io" | |
| 10 | 新增: "net" | |
| 11 | 新增: "net/http" | |
| 12 | 新增: "net/url" | |
| 13 | 新增: "os" | |
| 14 | 新增: "path/filepath" | |
| 15 | 新增: "time" | |
| 16 | 新增: | |
| 17 | 新增: "github.com/sylvinus/agent-vm/internal/diagnostics" | |
| 18 | 新增: "github.com/sylvinus/agent-vm/internal/host" | |
| 19 | 新增: "github.com/sylvinus/agent-vm/internal/version" | |
| 20 | 新增:) | |
| 21 | 新增: | |
| 22 | 新增:func (s *Server) diagnosticStatus(w http.ResponseWriter, r *http.Request) { | |
| 23 | 新增: info, err := diagnostics.New(s.profile).Info() | |
| 24 | 新增: if err != nil { | |
| 25 | 新增: requestError(w, errors.New("无法读取诊断日志,请检查本机存储权限和剩余空间")) | |
| 26 | 新增: return | |
| 27 | 新增: } | |
| 28 | 新增: jsonReply(w, info) | |
| 29 | 新增:} | |
| 30 | 新增:func (s *Server) diagnosticEvent(w http.ResponseWriter, r *http.Request) { | |
| 31 | 新增: s.diagnosticRateMu.Lock() | |
| 32 | 新增: if time.Since(s.diagnosticWindow) > time.Minute { | |
| 33 | 新增: s.diagnosticWindow = time.Now() | |
| 34 | 新增: s.diagnosticCount = 0 | |
| 35 | 新增: } | |
| 36 | 新增: s.diagnosticCount++ | |
| 37 | 新增: permitted := s.diagnosticCount <= 60 | |
| 38 | 新增: s.diagnosticRateMu.Unlock() | |
| 39 | 新增: if !permitted { | |
| 40 | 新增: http.Error(w, "诊断上报过于频繁", http.StatusTooManyRequests) | |
| 41 | 新增: return | |
| 42 | 新增: } | |
| 43 | 新增: | |
| 44 | 新增: var event struct { | |
| 45 | 新增: Source string `json:"source"` | |
| 46 | 新增: Level string `json:"level"` | |
| 47 | 新增: Message string `json:"message"` | |
| 48 | 新增: } | |
| 49 | 新增: if !readJSON(w, r, &event, 32<<10) { | |
| 50 | 新增: return | |
| 51 | 新增: } | |
| 52 | 新增: if event.Source != "frontend" && event.Source != "react" { | |
| 53 | 新增: http.Error(w, "日志来源无效", 400) | |
| 54 | 新增: return | |
| 55 | 新增: } | |
| 56 | 新增: if err := diagnostics.New(s.profile).Record(event.Level, event.Source, event.Message); err != nil { | |
| 57 | 新增: http.Error(w, "诊断日志写入失败", 503) | |
| 58 | 新增: return | |
| 59 | 新增: } | |
| 60 | 新增: jsonReply(w, map[string]bool{"ok": true}) | |
| 61 | 新增:} | |
| 62 | 新增:func (s *Server) diagnosticExport(w http.ResponseWriter, r *http.Request) { | |
| 63 | 新增: if !s.diagnosticMu.TryLock() { | |
| 64 | 新增: http.Error(w, "正在导出另一份诊断包,请稍候", 409) | |
| 65 | 新增: return | |
| 66 | 新增: } | |
| 67 | 新增: defer s.diagnosticMu.Unlock() | |
| 68 | 新增: guestState := "environment unavailable" | |
| 69 | 新增: var guest []byte | |
| 70 | 新增: if s.vmRunning() { | |
| 71 | 新增: ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second) | |
| 72 | 新增: defer cancel() | |
| 73 | 新增: var err error | |
| 74 | 新增: guest, err = s.guest(ctx, `sudo python3 - <<'CAGE_DIAGNOSTIC_JOURNAL' | |
| 75 | 新增:import subprocess, sys | |
| 76 | 新增:result = subprocess.run(['journalctl','--namespace=cage','--no-pager','-o','short-iso','-n','150','--since','14 days ago'], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, timeout=5, check=True) | |
| 77 | 新增:data = result.stdout | |
| 78 | 新增:if len(data) > 49152: | |
| 79 | 新增: data = data[-49152:] | |
| 80 | 新增: data = data.partition(b'\n')[2] | |
| 81 | 新增:sys.stdout.buffer.write(data) | |
| 82 | 新增:CAGE_DIAGNOSTIC_JOURNAL`) | |
| 83 | 新增: if err != nil { | |
| 84 | 新增: guest = nil | |
| 85 | 新增: guestState = "guest collection failed" | |
| 86 | 新增: } else { | |
| 87 | 新增: guestState = "collected last 150 service lines (max 48 KiB)" | |
| 88 | 新增: } | |
| 89 | 新增: } | |
| 90 | 新增: var bundle bytes.Buffer | |
| 91 | 新增: if err := diagnostics.New(s.profile).Export(&bundle, version.Version, guest, guestState); err != nil { | |
| 92 | 新增: requestError(w, errors.New("诊断包生成失败,请检查存储权限和剩余空间")) | |
| 93 | 新增: return | |
| 94 | 新增: } | |
| 95 | 新增: w.Header().Set("Content-Type", "application/zip") | |
| 96 | 新增: w.Header().Set("Content-Disposition", `attachment; filename="cage-diagnostics.zip"`) | |
| 97 | 新增: _, _ = w.Write(bundle.Bytes()) | |
| 98 | 新增:} | |
| 99 | 新增: | |
| 100 | 新增:// ExportDiagnostics works without a running controller. A reachable | |
| 101 | 新增:// controller authenticates through the native launch ticket; offline recovery | |
| 102 | 新增:// exports host logs only. No raw configuration is exported. | |
| 103 | 新增:func ExportDiagnostics(configPath, destination string) error { | |
| 104 | 新增: if !filepath.IsAbs(destination) { | |
| 105 | 新增: return errors.New("请选择本机绝对保存路径") | |
| 106 | 新增: } | |
| 107 | 新增: profile := filepath.Dir(configPath) | |
| 108 | 新增: store := diagnostics.New(profile) | |
| 109 | 新增: dir := filepath.Dir(destination) | |
| 110 | 新增: f, err := os.CreateTemp(dir, ".cage-diagnostics-*.zip") | |
| 111 | 新增: if err != nil { | |
| 112 | 新增: return err | |
| 113 | 新增: } | |
| 114 | 新增: temp := f.Name() | |
| 115 | 新增: defer os.Remove(temp) | |
| 116 | 新增: if err = host.ProtectFile(temp); err != nil { | |
| 117 | 新增: f.Close() | |
| 118 | 新增: return err | |
| 119 | 新增: } | |
| 120 | 新增: export := func() error { | |
| 121 | 新增: c, e := connectController(profile) | |
| 122 | 新增: if e != nil { | |
| 123 | 新增: if e := store.ImportLegacy(profile); e != nil { | |
| 124 | 新增: return e | |
| 125 | 新增: } | |
| 126 | 新增: return store.Export(f, version.Version, nil, "controller unavailable or invalid; host logs only") | |
| 127 | 新增: } | |
| 128 | 新增: defer c.close() | |
| 129 | 新增: parsed, e := url.Parse(c.launch.URL) | |
| 130 | 新增: if e != nil { | |
| 131 | 新增: return e | |
| 132 | 新增: } | |
| 133 | 新增: ticket := parsed.Fragment | |
| 134 | 新增: code, e := c.call("POST", "/api/session", map[string]string{"token": ticket}, nil) | |
| 135 | 新增: if e != nil || code != 200 { | |
| 136 | 新增: return errors.New("无法创建诊断导出会话,请重新打开 Cage") | |
| 137 | 新增: } | |
| 138 | 新增: c.client.Timeout = 30 * time.Second | |
| 139 | 新增: req, _ := http.NewRequest("GET", c.origin+"/api/diagnostics/export", nil) | |
| 140 | 新增: response, e := c.client.Do(req) | |
| 141 | 新增: if e != nil { | |
| 142 | 新增: return e | |
| 143 | 新增: } | |
| 144 | 新增: defer response.Body.Close() | |
| 145 | 新增: if response.StatusCode != 200 { | |
| 146 | 新增: return errors.New("诊断包导出未完成,请重新打开 Cage 后重试") | |
| 147 | 新增: } | |
| 148 | 新增: if response.Header.Get("Content-Type") != "application/zip" { | |
| 149 | 新增: return errors.New("当前后台尚不支持诊断导出,请重启应用") | |
| 150 | 新增: } | |
| 151 | 新增: n, e := io.Copy(f, io.LimitReader(response.Body, (MaxDiagnosticBundle+1))) | |
| 152 | 新增: if n > MaxDiagnosticBundle { | |
| 153 | 新增: return errors.New("诊断包超过允许大小") | |
| 154 | 新增: } | |
| 155 | 新增: return e | |
| 156 | 新增: } | |
| 157 | 新增: err = export() | |
| 158 | 新增: if err == nil { | |
| 159 | 新增: err = f.Sync() | |
| 160 | 新增: } | |
| 161 | 新增: err = errors.Join(err, f.Close()) | |
| 162 | 新增: if err != nil { | |
| 163 | 新增: return err | |
| 164 | 新增: } | |
| 165 | 新增: archive, err := zip.OpenReader(temp) | |
| 166 | 新增: if err != nil { | |
| 167 | 新增: return errors.New("诊断包未完整生成,请重新导出") | |
| 168 | 新增: } | |
| 169 | 新增: _ = archive.Close() | |
| 170 | 新增: // Never follow a destination symlink or replace a directory. | |
| 171 | 新增: if st, e := os.Lstat(destination); e == nil && !st.Mode().IsRegular() { | |
| 172 | 新增: return errors.New("请选择普通文件作为保存位置") | |
| 173 | 新增: } | |
| 174 | 新增: return os.Rename(temp, destination) | |
| 175 | 新增:} | |
| 176 | 新增: | |
| 177 | 新增:const MaxDiagnosticBundle int64 = 48 << 20 | |
| 178 | 新增: | |
| 179 | 新增:// Preserve streaming and WebSocket behavior while observing error statuses. | |
| 180 | 新增:type diagnosticResponse struct { | |
| 181 | 新增: http.ResponseWriter | |
| 182 | 新增: status int | |
| 183 | 新增:} | |
| 184 | 新增: | |
| 185 | 新增:func (w *diagnosticResponse) Unwrap() http.ResponseWriter { return w.ResponseWriter } | |
| 186 | 新增:func (w *diagnosticResponse) WriteHeader(status int) { | |
| 187 | 新增: if w.status == 0 { | |
| 188 | 新增: w.status = status | |
| 189 | 新增: } | |
| 190 | 新增: w.ResponseWriter.WriteHeader(status) | |
| 191 | 新增:} | |
| 192 | 新增:func (w *diagnosticResponse) Write(b []byte) (int, error) { | |
| 193 | 新增: if w.status == 0 { | |
| 194 | 新增: w.status = 200 | |
| 195 | 新增: } | |
| 196 | 新增: return w.ResponseWriter.Write(b) | |
| 197 | 新增:} | |
| 198 | 新增:func (w *diagnosticResponse) Flush() { _ = http.NewResponseController(w.ResponseWriter).Flush() } | |
| 199 | 新增:func (w *diagnosticResponse) Hijack() (net.Conn, *bufio.ReadWriter, error) { | |
| 200 | 新增: return http.NewResponseController(w.ResponseWriter).Hijack() | |
| 201 | 新增:} | |
| @@ -0,0 +1,158 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "archive/zip" | |
| 5 | 新增: "bytes" | |
| 6 | 新增: "encoding/json" | |
| 7 | 新增: "io" | |
| 8 | 新增: "net/http" | |
| 9 | 新增: "os" | |
| 10 | 新增: "os/exec" | |
| 11 | 新增: "path/filepath" | |
| 12 | 新增: "strings" | |
| 13 | 新增: "sync" | |
| 14 | 新增: "testing" | |
| 15 | 新增: | |
| 16 | 新增: "github.com/sylvinus/agent-vm/internal/diagnostics" | |
| 17 | 新增:) | |
| 18 | 新增: | |
| 19 | 新增:func TestDiagnosticRoutesAuthenticateRedactAndExportWhenLocked(t *testing.T) { | |
| 20 | 新增: s := testServer(t) | |
| 21 | 新增: s.account.lock() | |
| 22 | 新增: for _, path := range []string{"/api/diagnostics", "/api/diagnostics/export"} { | |
| 23 | 新增: if w := request(s, "GET", path, "", "", false); w.Code != 401 { | |
| 24 | 新增: t.Fatalf("anonymous %s: %d", path, w.Code) | |
| 25 | 新增: } | |
| 26 | 新增: } | |
| 27 | 新增: body := `{"source":"frontend","level":"error","message":"token=sample-private-token https://user:[email protected]/secret Error: UI failed"}` | |
| 28 | 新增: if w := request(s, "POST", "/api/diagnostics/events", "http://evil.example", body, true); w.Code != 403 { | |
| 29 | 新增: t.Fatal("cross-origin event accepted") | |
| 30 | 新增: } | |
| 31 | 新增: if w := request(s, "POST", "/api/diagnostics/events", s.origin, body, true); w.Code != 200 { | |
| 32 | 新增: t.Fatalf("event rejected: %d %s", w.Code, w.Body.String()) | |
| 33 | 新增: } | |
| 34 | 新增: w := request(s, "GET", "/api/diagnostics/export", "", "", true) | |
| 35 | 新增: if w.Code != 200 || w.Header().Get("Content-Type") != "application/zip" { | |
| 36 | 新增: t.Fatalf("export failed: %d %s", w.Code, w.Body.String()) | |
| 37 | 新增: } | |
| 38 | 新增: archive, err := zip.NewReader(bytes.NewReader(w.Body.Bytes()), int64(w.Body.Len())) | |
| 39 | 新增: if err != nil { | |
| 40 | 新增: t.Fatal(err) | |
| 41 | 新增: } | |
| 42 | 新增: var content string | |
| 43 | 新增: for _, f := range archive.File { | |
| 44 | 新增: r, _ := f.Open() | |
| 45 | 新增: b, _ := io.ReadAll(r) | |
| 46 | 新增: r.Close() | |
| 47 | 新增: content += string(b) | |
| 48 | 新增: } | |
| 49 | 新增: if strings.Contains(content, "sample-private-token") || strings.Contains(content, "example.com") || !strings.Contains(content, "UI failed") { | |
| 50 | 新增: t.Fatalf("invalid exported content: %s", content) | |
| 51 | 新增: } | |
| 52 | 新增: // Invalid event sources cannot impersonate native/controller diagnostics. | |
| 53 | 新增: if w := request(s, "POST", "/api/diagnostics/events", s.origin, `{"source":"native","message":"spoof"}`, true); w.Code != 400 { | |
| 54 | 新增: t.Fatal("source spoof accepted") | |
| 55 | 新增: } | |
| 56 | 新增: if w := request(s, "POST", "/api/diagnostics/events", s.origin, `{"source":"frontend","message":"`+strings.Repeat("x", 33<<10)+`"}`, true); w.Code != 400 { | |
| 57 | 新增: t.Fatal("oversized event accepted") | |
| 58 | 新增: } | |
| 59 | 新增: for i := 0; i < 65; i++ { | |
| 60 | 新增: w = request(s, "POST", "/api/diagnostics/events", s.origin, body, true) | |
| 61 | 新增: } | |
| 62 | 新增: if w.Code != http.StatusTooManyRequests { | |
| 63 | 新增: t.Fatalf("no rate limit: %d", w.Code) | |
| 64 | 新增: } | |
| 65 | 新增:} | |
| 66 | 新增:func TestOfflineExportPreservesDestinationOnErrorAndNoArchiveSymlink(t *testing.T) { | |
| 67 | 新增: profile := t.TempDir() | |
| 68 | 新增: path := filepath.Join(profile, "config.json") | |
| 69 | 新增: output := filepath.Join(t.TempDir(), "bundle.zip") | |
| 70 | 新增: if err := diagnostics.New(profile).Record("error", "native", "password=offline-secret startup failed"); err != nil { | |
| 71 | 新增: t.Fatal(err) | |
| 72 | 新增: } | |
| 73 | 新增: if err := ExportDiagnostics(path, output); err != nil { | |
| 74 | 新增: t.Fatal(err) | |
| 75 | 新增: } | |
| 76 | 新增: archive, err := zip.OpenReader(output) | |
| 77 | 新增: if err != nil { | |
| 78 | 新增: t.Fatal(err) | |
| 79 | 新增: } | |
| 80 | 新增: archive.Close() | |
| 81 | 新增: original, _ := os.ReadFile(output) | |
| 82 | 新增: if err := ExportDiagnostics(path, "relative.zip"); err == nil { | |
| 83 | 新增: t.Fatal("relative destination accepted") | |
| 84 | 新增: } | |
| 85 | 新增: if err := os.Mkdir(filepath.Join(profile, "control.json"), 0700); err != nil { | |
| 86 | 新增: t.Fatal(err) | |
| 87 | 新增: } | |
| 88 | 新增: if err := ExportDiagnostics(path, output); err != nil { | |
| 89 | 新增: t.Fatal("corrupt controller record blocked offline recovery", err) | |
| 90 | 新增: } | |
| 91 | 新增: original, _ = os.ReadFile(output) | |
| 92 | 新增: if err := os.Rename(filepath.Join(profile, "logs"), filepath.Join(profile, "logs.saved")); err != nil { | |
| 93 | 新增: t.Fatal(err) | |
| 94 | 新增: } | |
| 95 | 新增: if err := os.WriteFile(filepath.Join(profile, "logs"), []byte("not a directory"), 0600); err != nil { | |
| 96 | 新增: t.Fatal(err) | |
| 97 | 新增: } | |
| 98 | 新增: if err := ExportDiagnostics(path, output); err == nil { | |
| 99 | 新增: t.Fatal("invalid log storage accepted") | |
| 100 | 新增: } | |
| 101 | 新增: got, _ := os.ReadFile(output) | |
| 102 | 新增: if !bytes.Equal(original, got) { | |
| 103 | 新增: t.Fatal("failed export overwrote destination") | |
| 104 | 新增: } | |
| 105 | 新增:} | |
| 106 | 新增:func TestTaskPanicRecordsFailureBeforeProcessExit(t *testing.T) { | |
| 107 | 新增: const flag = "CAGE_DIAGNOSTICS_PANIC_TEST" | |
| 108 | 新增: if profile := os.Getenv(flag); profile != "" { | |
| 109 | 新增: diagnostics.SetDefault(diagnostics.New(profile)) | |
| 110 | 新增: m := new(jobManager) | |
| 111 | 新增: var operation sync.Mutex | |
| 112 | 新增: _, err := m.submit(&operation, "test", 0, nil, nil, func() error { panic("token=panic-private-secret task broke") }) | |
| 113 | 新增: if err != nil { | |
| 114 | 新增: os.Exit(3) | |
| 115 | 新增: } | |
| 116 | 新增: select {} | |
| 117 | 新增: } | |
| 118 | 新增: profile := t.TempDir() | |
| 119 | 新增: exe, err := os.Executable() | |
| 120 | 新增: if err != nil { | |
| 121 | 新增: t.Fatal(err) | |
| 122 | 新增: } | |
| 123 | 新增: cmd := exec.Command(exe, "-test.run=^TestTaskPanicRecordsFailureBeforeProcessExit$") | |
| 124 | 新增: cmd.Env = append(os.Environ(), flag+"="+profile) | |
| 125 | 新增: if err := cmd.Run(); err == nil { | |
| 126 | 新增: t.Fatal("task panic unexpectedly kept process alive") | |
| 127 | 新增: } | |
| 128 | 新增: var bundle bytes.Buffer | |
| 129 | 新增: if err := diagnostics.New(profile).Export(&bundle, "test", nil, "offline"); err != nil { | |
| 130 | 新增: t.Fatal(err) | |
| 131 | 新增: } | |
| 132 | 新增: archive, _ := zip.NewReader(bytes.NewReader(bundle.Bytes()), int64(bundle.Len())) | |
| 133 | 新增: var messages string | |
| 134 | 新增: for _, f := range archive.File { | |
| 135 | 新增: r, _ := f.Open() | |
| 136 | 新增: b, _ := io.ReadAll(r) | |
| 137 | 新增: r.Close() | |
| 138 | 新增: messages += string(b) | |
| 139 | 新增: } | |
| 140 | 新增: if strings.Contains(messages, "panic-private-secret") || !strings.Contains(messages, "task broke") { | |
| 141 | 新增: t.Fatal("panic evidence missing or not redacted") | |
| 142 | 新增: } | |
| 143 | 新增:} | |
| 144 | 新增: | |
| 145 | 新增:func TestDiagnosticExportBusyAndManifest(t *testing.T) { | |
| 146 | 新增: s := testServer(t) | |
| 147 | 新增: s.diagnosticMu.Lock() | |
| 148 | 新增: w := request(s, "GET", "/api/diagnostics/export", "", "", true) | |
| 149 | 新增: s.diagnosticMu.Unlock() | |
| 150 | 新增: if w.Code != 409 { | |
| 151 | 新增: t.Fatal("parallel bundle generation allowed") | |
| 152 | 新增: } | |
| 153 | 新增: info := request(s, "GET", "/api/diagnostics", "", "", true) | |
| 154 | 新增: var v diagnostics.Info | |
| 155 | 新增: if json.Unmarshal(info.Body.Bytes(), &v) != nil || v.MaxBytes+v.GuestMaxBytes != 50<<20 || v.RetentionDays != 14 { | |
| 156 | 新增: t.Fatalf("policy unavailable: %s", info.Body.String()) | |
| 157 | 新增: } | |
| 158 | 新增:} | |
| @@ -250,14 +250,14 @@ func TestJobManagerFinalizationAndOutput(t *testing.T) { | ||
| 250 | 250 | _, err := manager.submit(&operation, "stop", 0, nil, func() error { |
| 251 | 251 | return errors.New("account could not be locked") |
| 252 | 252 | }, func() error { |
| 253 | 删除: _, _ = manager.execution().Write([]byte(strings.Repeat("a", 25000) + "tail")) | |
| 253 | 新增: _, _ = manager.execution().Write([]byte(strings.Repeat("a\n", 12500) + "tail")) | |
| 254 | 254 | return nil |
| 255 | 255 | }) |
| 256 | 256 | if err != nil { |
| 257 | 257 | t.Fatal(err) |
| 258 | 258 | } |
| 259 | 259 | state := awaitJobIdle(t, &manager) |
| 260 | 删除: if state.Error != "account could not be locked" || len(state.Log) != 24000 || !strings.HasSuffix(state.Log, "tail") { | |
| 260 | 新增: if state.Error != "account could not be locked" || len(state.Log) != 24000 || !strings.HasSuffix(state.Log, "tail\n") { | |
| 261 | 261 | t.Fatalf("finalization error or bounded log lost: %+v", state) |
| 262 | 262 | } |
| 263 | 263 | } |
| @@ -3,6 +3,9 @@ package workbench | ||
| 3 | 3 | import ( |
| 4 | 4 | "context" |
| 5 | 5 | "errors" |
| 6 | 新增: "fmt" | |
| 7 | 新增: "github.com/sylvinus/agent-vm/internal/diagnostics" | |
| 8 | 新增: "runtime/debug" | |
| 6 | 9 | "sync" |
| 7 | 10 | ) |
| 8 | 11 | |
| @@ -67,6 +70,15 @@ func (m *jobManager) submit(operation sync.Locker, kind string, pauseVersion uin | ||
| 67 | 70 | m.afterSuccess = afterSuccess |
| 68 | 71 | m.state = Job{ID: randomToken()[:12], Kind: kind, Running: true, Message: "正在准备…"} |
| 69 | 72 | execution := &jobExecution{owner: m, id: m.state.ID, ctx: ctx, pauseVersion: pauseVersion} |
| 73 | 新增: execution.log = diagnostics.NewStream(diagnostics.Default(), "task/"+kind, "info", func(line string) { | |
| 74 | 新增: if m.state.ID == execution.id { | |
| 75 | 新增: m.state.Log += line | |
| 76 | 新增: if len(m.state.Log) > 24000 { | |
| 77 | 新增: m.state.Log = m.state.Log[len(m.state.Log)-24000:] | |
| 78 | 新增: } | |
| 79 | 新增: } | |
| 80 | 新增: }) | |
| 81 | 新增: diagnostics.Log("info", "task", kind+" started") | |
| 70 | 82 | m.workers.Add(1) |
| 71 | 83 | go func() { |
| 72 | 84 | defer m.workers.Done() |
| @@ -85,7 +97,15 @@ func (m *jobManager) submit(operation sync.Locker, kind string, pauseVersion uin | ||
| 85 | 97 | } |
| 86 | 98 | m.active = execution |
| 87 | 99 | m.mu.Unlock() |
| 88 | 删除: err := run() | |
| 100 | 新增: err := func() (err error) { | |
| 101 | 新增: defer func() { | |
| 102 | 新增: if failure := recover(); failure != nil { | |
| 103 | 新增: diagnostics.Log("error", "task", fmt.Sprintf("panic: %v\n%s", failure, debug.Stack())) | |
| 104 | 新增: panic(failure) | |
| 105 | 新增: } | |
| 106 | 新增: }() | |
| 107 | 新增: return run() | |
| 108 | 新增: }() | |
| 89 | 109 | m.mu.Lock() |
| 90 | 110 | defer m.mu.Unlock() |
| 91 | 111 | m.finishLocked(execution, err) |
| @@ -94,6 +114,9 @@ func (m *jobManager) submit(operation sync.Locker, kind string, pauseVersion uin | ||
| 94 | 114 | } |
| 95 | 115 | |
| 96 | 116 | func (m *jobManager) finishLocked(execution *jobExecution, err error) { |
| 117 | 新增: if execution.log != nil { | |
| 118 | 新增: _ = execution.log.Close() | |
| 119 | 新增: } | |
| 97 | 120 | if m.active == execution { |
| 98 | 121 | m.active = nil |
| 99 | 122 | } |
| @@ -111,11 +134,14 @@ func (m *jobManager) finishLocked(execution *jobExecution, err error) { | ||
| 111 | 134 | switch { |
| 112 | 135 | case errors.Is(err, context.Canceled): |
| 113 | 136 | m.state.Message = "已取消" |
| 137 | 新增: diagnostics.Log("info", "task", m.state.Kind+" canceled") | |
| 114 | 138 | case err != nil: |
| 115 | 139 | m.state.Error = err.Error() |
| 116 | 140 | m.state.Message = "操作未完成" |
| 141 | 新增: diagnostics.Log("error", "task", m.state.Kind+": "+err.Error()) | |
| 117 | 142 | default: |
| 118 | 143 | m.state.Message = "已完成" |
| 144 | 新增: diagnostics.Log("info", "task", m.state.Kind+" completed") | |
| 119 | 145 | } |
| 120 | 146 | } |
| 121 | 147 | |
| @@ -165,6 +191,7 @@ type jobExecution struct { | ||
| 165 | 191 | id string |
| 166 | 192 | ctx context.Context |
| 167 | 193 | pauseVersion uint64 |
| 194 | 新增: log *diagnostics.Stream | |
| 168 | 195 | } |
| 169 | 196 | |
| 170 | 197 | func (e *jobExecution) message(message string) { |
| @@ -179,9 +206,8 @@ func (e *jobExecution) Write(data []byte) (int, error) { | ||
| 179 | 206 | e.owner.mu.Lock() |
| 180 | 207 | defer e.owner.mu.Unlock() |
| 181 | 208 | if e.id != "" && e.owner.state.ID == e.id && e.owner.state.Running { |
| 182 | 删除: e.owner.state.Log += string(data) | |
| 183 | 删除: if len(e.owner.state.Log) > 24000 { | |
| 184 | 删除: e.owner.state.Log = e.owner.state.Log[len(e.owner.state.Log)-24000:] | |
| 209 | 新增: if e.log != nil { | |
| 210 | 新增: _, _ = e.log.Write(data) | |
| 185 | 211 | } |
| 186 | 212 | } |
| 187 | 213 | return len(data), nil |
| @@ -7,6 +7,7 @@ import ( | ||
| 7 | 7 | "path/filepath" |
| 8 | 8 | "time" |
| 9 | 9 | |
| 10 | 新增: "github.com/sylvinus/agent-vm/internal/diagnostics" | |
| 10 | 11 | "github.com/sylvinus/agent-vm/internal/managedproxy" |
| 11 | 12 | ) |
| 12 | 13 | |
| @@ -33,8 +34,23 @@ func (s *Server) startMonitors() { | ||
| 33 | 34 | return |
| 34 | 35 | } |
| 35 | 36 | ctx := s.lifetimeContextLocked() |
| 36 | 删除: s.monitors.Add(2) | |
| 37 | 新增: s.monitors.Add(3) | |
| 37 | 38 | s.mu.Unlock() |
| 39 | 新增: go func() { | |
| 40 | 新增: defer s.monitors.Done() | |
| 41 | 新增: ticker := time.NewTicker(time.Hour) | |
| 42 | 新增: defer ticker.Stop() | |
| 43 | 新增: for { | |
| 44 | 新增: select { | |
| 45 | 新增: case <-ctx.Done(): | |
| 46 | 新增: return | |
| 47 | 新增: case <-ticker.C: | |
| 48 | 新增: if err := diagnostics.New(s.profile).Clean(); err != nil { | |
| 49 | 新增: diagnostics.Log("error", "diagnostics", "log cleanup failed: "+err.Error()) | |
| 50 | 新增: } | |
| 51 | 新增: } | |
| 52 | 新增: } | |
| 53 | 新增: }() | |
| 38 | 54 | go func() { |
| 39 | 55 | defer s.monitors.Done() |
| 40 | 56 | s.monitor(ctx) |
| @@ -0,0 +1,127 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "errors" | |
| 6 | 新增: "time" | |
| 7 | 新增: | |
| 8 | 新增: "github.com/sylvinus/agent-vm/internal/cage" | |
| 9 | 新增: "github.com/sylvinus/agent-vm/internal/diagnostics" | |
| 10 | 新增:) | |
| 11 | 新增: | |
| 12 | 新增:type networkRecovery struct { | |
| 13 | 新增: RunID, Configuration string | |
| 14 | 新增: PauseVersion uint64 | |
| 15 | 新增: Epoch uint64 | |
| 16 | 新增: Next time.Time | |
| 17 | 新增: Attempts int | |
| 18 | 新增:} | |
| 19 | 新增: | |
| 20 | 新增:func (s *Server) scheduleNetworkRecovery(state cage.GateStatus) { | |
| 21 | 新增: s.mu.Lock() | |
| 22 | 新增: defer s.mu.Unlock() | |
| 23 | 新增: if s.networkPaused || s.closing || state.Mode != cage.GateClosed || state.Report == nil { | |
| 24 | 新增: return | |
| 25 | 新增: } | |
| 26 | 新增: s.recovery = networkRecovery{RunID: state.RunID, Configuration: state.Configuration, Epoch: state.Epoch, PauseVersion: s.safety.pauseVersion, Next: time.Now().Add(15 * time.Second)} | |
| 27 | 新增: diagnostics.Log("warn", "network", "temporary monitoring failure; full recheck scheduled: "+state.Reason) | |
| 28 | 新增:} | |
| 29 | 新增: | |
| 30 | 新增:func recoveryMatches(r networkRecovery, state cage.GateStatus, configuration string, paused bool, generation uint64) bool { | |
| 31 | 新增: return r.RunID != "" && !paused && generation == r.PauseVersion && state.RunID == r.RunID && state.Configuration == r.Configuration && configuration == r.Configuration && state.Epoch == r.Epoch && state.Mode == cage.GateClosed | |
| 32 | 新增:} | |
| 33 | 新增: | |
| 34 | 新增:// Called with s.op held. Admission uses the ordinary job queue and never changes | |
| 35 | 新增:// saved network intent. The worker rechecks after acquiring s.op as well. | |
| 36 | 新增:func (s *Server) recoverNetwork() { | |
| 37 | 新增: s.mu.Lock() | |
| 38 | 新增: r := s.recovery | |
| 39 | 新增: blocked := s.closing || s.networkPaused || !s.ready || s.jobs.snapshot().Running || time.Now().Before(r.Next) | |
| 40 | 新增: s.mu.Unlock() | |
| 41 | 新增: if blocked || r.RunID == "" { | |
| 42 | 新增: return | |
| 43 | 新增: } | |
| 44 | 新增: // A healthy browser alone is insufficient when the guest remains under pressure. | |
| 45 | 新增: resources, err := cage.ReadResourceStatus(s.instanceDir()) | |
| 46 | 新增: if err == nil && (resources.Pressure || resources.HostPressure || resources.Error != "") { | |
| 47 | 新增: return | |
| 48 | 新增: } | |
| 49 | 新增: _, _ = s.submitJob("network-recovery", func() error { return s.runNetworkRecovery(r, s.runSafetyCheck) }) | |
| 50 | 新增:} | |
| 51 | 新增: | |
| 52 | 新增:func (s *Server) runNetworkRecovery(expected networkRecovery, recheck func() error) error { | |
| 53 | 新增: s.mu.Lock() | |
| 54 | 新增: stopped := s.closing || s.networkPaused || s.safety.pauseVersion != expected.PauseVersion | |
| 55 | 新增: if stopped { | |
| 56 | 新增: s.recovery = networkRecovery{} | |
| 57 | 新增: } | |
| 58 | 新增: s.mu.Unlock() | |
| 59 | 新增: if stopped { | |
| 60 | 新增: return context.Canceled | |
| 61 | 新增: } | |
| 62 | 新增: client, err := s.gateClient() | |
| 63 | 新增: if err != nil { | |
| 64 | 新增: return s.finishNetworkRecovery(expected, err) | |
| 65 | 新增: } | |
| 66 | 新增: ctx, cancel := context.WithTimeout(s.operationContext(), 5*time.Second) | |
| 67 | 新增: state, err := client.Status(ctx) | |
| 68 | 新增: cancel() | |
| 69 | 新增: if err != nil { | |
| 70 | 新增: return s.finishNetworkRecovery(expected, err) | |
| 71 | 新增: } | |
| 72 | 新增: cfg, err := loadConfig(s.configPath) | |
| 73 | 新增: if err != nil { | |
| 74 | 新增: return s.finishNetworkRecovery(expected, err) | |
| 75 | 新增: } | |
| 76 | 新增: s.mu.Lock() | |
| 77 | 新增: valid := !s.closing && s.recovery == expected && recoveryMatches(expected, state, cfg.Fingerprint(), s.networkPaused, s.safety.pauseVersion) | |
| 78 | 新增: if !valid { | |
| 79 | 新增: s.recovery = networkRecovery{} | |
| 80 | 新增: } | |
| 81 | 新增: s.mu.Unlock() | |
| 82 | 新增: if !valid { | |
| 83 | 新增: return context.Canceled | |
| 84 | 新增: } | |
| 85 | 新增: if err := s.operationContext().Err(); err != nil { | |
| 86 | 新增: return err | |
| 87 | 新增: } | |
| 88 | 新增: s.setMessage("正在重新检查环境与出口,通过后自动恢复联网…") | |
| 89 | 新增: err = recheck() | |
| 90 | 新增: return s.finishNetworkRecovery(expected, err) | |
| 91 | 新增:} | |
| 92 | 新增: | |
| 93 | 新增:func (s *Server) finishNetworkRecovery(expected networkRecovery, err error) error { | |
| 94 | 新增: // A failed full check changes the gate epoch. Keep that exact epoch for the | |
| 95 | 新增: // next attempt, while preserving user/configuration changes as cancellation. | |
| 96 | 新增: var current cage.GateStatus | |
| 97 | 新增: if err != nil { | |
| 98 | 新增: if client, e := s.gateClient(); e == nil { | |
| 99 | 新增: ctx, cancel := context.WithTimeout(s.lifetimeContext(), 3*time.Second) | |
| 100 | 新增: current, _ = client.Status(ctx) | |
| 101 | 新增: cancel() | |
| 102 | 新增: } | |
| 103 | 新增: } | |
| 104 | 新增: s.mu.Lock() | |
| 105 | 新增: defer s.mu.Unlock() | |
| 106 | 新增: if s.recovery != expected { | |
| 107 | 新增: return err | |
| 108 | 新增: } | |
| 109 | 新增: if err == nil || s.closing || s.networkPaused || s.safety.pauseVersion != expected.PauseVersion || errors.Is(err, context.Canceled) { | |
| 110 | 新增: s.recovery = networkRecovery{} | |
| 111 | 新增: if err == nil { | |
| 112 | 新增: s.networkError = "" | |
| 113 | 新增: s.safety.Error = "" | |
| 114 | 新增: } | |
| 115 | 新增: return err | |
| 116 | 新增: } | |
| 117 | 新增: if current.RunID != "" { | |
| 118 | 新增: if current.RunID != expected.RunID || current.Configuration != expected.Configuration || current.Mode != cage.GateClosed { | |
| 119 | 新增: s.recovery = networkRecovery{} | |
| 120 | 新增: return err | |
| 121 | 新增: } | |
| 122 | 新增: s.recovery.Epoch = current.Epoch | |
| 123 | 新增: } | |
| 124 | 新增: s.recovery.Attempts++ | |
| 125 | 新增: s.recovery.Next = time.Now().Add(time.Duration(min(300, 15<<min(s.recovery.Attempts, 5))) * time.Second) | |
| 126 | 新增: return err | |
| 127 | 新增:} | |
| @@ -0,0 +1,112 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "errors" | |
| 6 | 新增: "testing" | |
| 7 | 新增: "time" | |
| 8 | 新增: | |
| 9 | 新增: "github.com/sylvinus/agent-vm/internal/cage" | |
| 10 | 新增:) | |
| 11 | 新增: | |
| 12 | 新增:func failedMonitoringServer(t *testing.T) (*Server, *cage.EgressGate) { | |
| 13 | 新增: s, gate := grantedToolUpdateServer(t) | |
| 14 | 新增: s.setJobForTest(Job{}) | |
| 15 | 新增: client, err := s.gateClient() | |
| 16 | 新增: if err != nil { | |
| 17 | 新增: t.Fatal(err) | |
| 18 | 新增: } | |
| 19 | 新增: s.finishSafetyObservation(context.Background(), client, gate.Status(), "", "guest observation timed out", true) | |
| 20 | 新增: if gate.Status().Mode != cage.GateClosed || s.recovery.RunID == "" { | |
| 21 | 新增: t.Fatal("temporary failure did not revoke and schedule") | |
| 22 | 新增: } | |
| 23 | 新增: return s, gate | |
| 24 | 新增:} | |
| 25 | 新增: | |
| 26 | 新增:func TestNetworkRecoveryDoesNotReusePriorGrant(t *testing.T) { | |
| 27 | 新增: s, gate := failedMonitoringServer(t) | |
| 28 | 新增: expected := s.recovery | |
| 29 | 新增: called := false | |
| 30 | 新增: err := s.runNetworkRecovery(expected, func() error { | |
| 31 | 新增: called = true | |
| 32 | 新增: if gate.Status().Mode != cage.GateClosed { | |
| 33 | 新增: t.Fatal("opened before full check") | |
| 34 | 新增: } | |
| 35 | 新增: return errors.New("new full check failed") | |
| 36 | 新增: }) | |
| 37 | 新增: if !called || err == nil || gate.Status().Mode != cage.GateClosed || s.recovery.Attempts != 1 || !s.recovery.Next.After(time.Now().Add(20*time.Second)) { | |
| 38 | 新增: t.Fatal("failed check did not remain closed with backoff", err, s.recovery) | |
| 39 | 新增: } | |
| 40 | 新增:} | |
| 41 | 新增: | |
| 42 | 新增:func TestNetworkRecoveryHonorsInterveningChanges(t *testing.T) { | |
| 43 | 新增: for _, change := range []string{"pause", "configuration", "new-check", "stop"} { | |
| 44 | 新增: t.Run(change, func(t *testing.T) { | |
| 45 | 新增: s, gate := failedMonitoringServer(t) | |
| 46 | 新增: expected := s.recovery | |
| 47 | 新增: switch change { | |
| 48 | 新增: case "pause": | |
| 49 | 新增: if err := s.pauseNetworkNow("user pause"); err != nil { | |
| 50 | 新增: t.Fatal(err) | |
| 51 | 新增: } | |
| 52 | 新增: case "configuration": | |
| 53 | 新增: cfg, _ := loadConfig(s.configPath) | |
| 54 | 新增: cfg.Timezone = "Asia/Tokyo" | |
| 55 | 新增: if err := writePrivate(s.configPath, cfg); err != nil { | |
| 56 | 新增: t.Fatal(err) | |
| 57 | 新增: } | |
| 58 | 新增: case "new-check": | |
| 59 | 新增: if err := gate.BeginCheck(); err != nil { | |
| 60 | 新增: t.Fatal(err) | |
| 61 | 新增: } | |
| 62 | 新增: case "stop": | |
| 63 | 新增: s.closing = true | |
| 64 | 新增: } | |
| 65 | 新增: err := s.runNetworkRecovery(expected, func() error { t.Fatal("stale recovery ran"); return nil }) | |
| 66 | 新增: if !errors.Is(err, context.Canceled) { | |
| 67 | 新增: t.Fatal(err) | |
| 68 | 新增: } | |
| 69 | 新增: if s.recovery.RunID != "" { | |
| 70 | 新增: t.Fatal("stale recovery retained") | |
| 71 | 新增: } | |
| 72 | 新增: }) | |
| 73 | 新增: } | |
| 74 | 新增:} | |
| 75 | 新增: | |
| 76 | 新增:func TestNetworkRecoverySuccessfulFullCheckClearsRetry(t *testing.T) { | |
| 77 | 新增: s, gate := failedMonitoringServer(t) | |
| 78 | 新增: expected := s.recovery | |
| 79 | 新增: err := s.runNetworkRecovery(expected, func() error { | |
| 80 | 新增: if err := gate.BeginCheck(); err != nil { | |
| 81 | 新增: return err | |
| 82 | 新增: } | |
| 83 | 新增: state := gate.Status() | |
| 84 | 新增: report := *state.Report | |
| 85 | 新增: report.CheckID = state.CheckID | |
| 86 | 新增: report.ID = "fresh-recovery" | |
| 87 | 新增: report.CreatedAt = time.Now() | |
| 88 | 新增: for i := range report.Checks { | |
| 89 | 新增: report.Checks[i].CheckedAt = report.CreatedAt | |
| 90 | 新增: } | |
| 91 | 新增: return gate.Grant(report) | |
| 92 | 新增: }) | |
| 93 | 新增: if err != nil || gate.Status().Mode != cage.GateOpen || s.recovery.RunID != "" { | |
| 94 | 新增: t.Fatal(err, gate.Status().Mode, s.recovery) | |
| 95 | 新增: } | |
| 96 | 新增:} | |
| 97 | 新增: | |
| 98 | 新增:func TestConfigurationMismatchDoesNotScheduleRecovery(t *testing.T) { | |
| 99 | 新增: s, gate := grantedToolUpdateServer(t) | |
| 100 | 新增: s.setJobForTest(Job{}) | |
| 101 | 新增: state := gate.Status() | |
| 102 | 新增: cfg, _ := loadConfig(s.configPath) | |
| 103 | 新增: cfg.Timezone = "Asia/Tokyo" | |
| 104 | 新增: if err := writePrivate(s.configPath, cfg); err != nil { | |
| 105 | 新增: t.Fatal(err) | |
| 106 | 新增: } | |
| 107 | 新增: client, _ := s.gateClient() | |
| 108 | 新增: s.finishSafetyObservation(context.Background(), client, state, "", "guest observation timed out", true) | |
| 109 | 新增: if s.recovery.RunID != "" || gate.Status().Mode != cage.GateClosed { | |
| 110 | 新增: t.Fatal("configuration change got transient recovery") | |
| 111 | 新增: } | |
| 112 | 新增:} | |
| @@ -0,0 +1,65 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "net/http" | |
| 5 | 新增: "os" | |
| 6 | 新增: "path/filepath" | |
| 7 | 新增: | |
| 8 | 新增: "github.com/docker/go-units" | |
| 9 | 新增: "github.com/sylvinus/agent-vm/internal/cage" | |
| 10 | 新增: "github.com/sylvinus/agent-vm/internal/vmname" | |
| 11 | 新增: "go.yaml.in/yaml/v3" | |
| 12 | 新增:) | |
| 13 | 新增: | |
| 14 | 新增:func (s *Server) instanceDir() string { | |
| 15 | 新增: return filepath.Join(s.profile, "state", "lima", vmname.Name(s.environmentDir())) | |
| 16 | 新增:} | |
| 17 | 新增: | |
| 18 | 新增:func (s *Server) resourceStatus(w http.ResponseWriter, r *http.Request) { | |
| 19 | 新增: memory, cpus := cage.ResourceLimits() | |
| 20 | 新增: running := s.vmRunning() | |
| 21 | 新增: var configured struct { | |
| 22 | 新增: Memory string `yaml:"memory"` | |
| 23 | 新增: CPUs int `yaml:"cpus"` | |
| 24 | 新增: } | |
| 25 | 新增: if b, err := os.ReadFile(filepath.Join(s.instanceDir(), "lima.yaml")); err == nil { | |
| 26 | 新增: _ = yaml.Unmarshal(b, &configured) | |
| 27 | 新增: } | |
| 28 | 新增: maximum, _ := units.RAMInBytes(configured.Memory) | |
| 29 | 新增: var observation *cage.ResourceStatus | |
| 30 | 新增: status, err := cage.ReadResourceStatus(s.instanceDir()) | |
| 31 | 新增: if running && err == nil { | |
| 32 | 新增: observation = &status | |
| 33 | 新增: } | |
| 34 | 新增: jsonReply(w, map[string]any{ | |
| 35 | 新增: "running": running, "automatic": true, | |
| 36 | 新增: "recommended_memory_bytes": uint64(memory) << 30, "recommended_cpus": cpus, | |
| 37 | 新增: "configured_memory_bytes": maximum, "configured_cpus": configured.CPUs, | |
| 38 | 新增: "restart_required": running && (maximum != int64(memory)<<30 || configured.CPUs != cpus || observation == nil), | |
| 39 | 新增: "observation": observation, | |
| 40 | 新增: }) | |
| 41 | 新增:} | |
| 42 | 新增: | |
| 43 | 新增:func (s *Server) applyResources(w http.ResponseWriter, r *http.Request) { | |
| 44 | 新增: s.launch(w, "resources", func() error { | |
| 45 | 新增: if s.vmRunning() { | |
| 46 | 新增: if err := s.stopEnvironment(); err != nil { | |
| 47 | 新增: return err | |
| 48 | 新增: } | |
| 49 | 新增: } | |
| 50 | 新增: if err := s.operationContext().Err(); err != nil { | |
| 51 | 新增: return err | |
| 52 | 新增: } | |
| 53 | 新增: return s.startEnvironment(false) | |
| 54 | 新增: }) | |
| 55 | 新增:} | |
| 56 | 新增: | |
| 57 | 新增:func (s *Server) checkNetworkIfWanted() error { | |
| 58 | 新增: s.mu.Lock() | |
| 59 | 新增: paused := s.networkPaused | |
| 60 | 新增: s.mu.Unlock() | |
| 61 | 新增: if paused { | |
| 62 | 新增: return nil | |
| 63 | 新增: } | |
| 64 | 新增: return s.runSafetyCheck() | |
| 65 | 新增:} | |
| @@ -11,6 +11,8 @@ import ( | ||
| 11 | 11 | "path/filepath" |
| 12 | 12 | "time" |
| 13 | 13 | |
| 14 | 新增: "al.essio.dev/pkg/shellescape" | |
| 15 | 新增: | |
| 14 | 16 | "github.com/sylvinus/agent-vm/internal/cage" |
| 15 | 17 | "github.com/sylvinus/agent-vm/internal/managedproxy" |
| 16 | 18 | "github.com/sylvinus/agent-vm/internal/vmname" |
| @@ -51,7 +53,10 @@ func (s *Server) sshCommandOptions(ctx context.Context, maintenance bool, args . | ||
| 51 | 53 | } |
| 52 | 54 | func (s *Server) guest(ctx context.Context, script string) ([]byte, error) { |
| 53 | 55 | name := vmname.Name(s.environmentDir()) |
| 54 | 删除: cmd := s.sshCommand(ctx, "-T", "lima-"+name, "--", script) | |
| 56 | 新增: // SSH enters the user's default shell. Run control scripts in Bash so | |
| 57 | 新增: // zsh initialization cannot change their redirection or error behavior. | |
| 58 | 新增: command := "exec /bin/bash --noprofile --norc -c " + shellescape.Quote(script) | |
| 59 | 新增: cmd := s.sshCommand(ctx, "-T", "lima-"+name, "--", command) | |
| 55 | 60 | pipe, err := cmd.StdoutPipe() |
| 56 | 61 | if err != nil { |
| 57 | 62 | return nil, err |
| @@ -220,7 +225,7 @@ func (s *Server) startEnvironment(syncTimezone bool) error { | ||
| 220 | 225 | s.publishGate(state) |
| 221 | 226 | return nil |
| 222 | 227 | } |
| 223 | 删除: return s.runSafetyCheck() | |
| 228 | 新增: return s.checkNetworkIfWanted() | |
| 224 | 229 | } |
| 225 | 230 | } |
| 226 | 231 | s.setMessage("正在重启环境以加载 VM 外网络门槛…") |
| @@ -302,7 +307,7 @@ func (s *Server) startEnvironment(syncTimezone bool) error { | ||
| 302 | 307 | return s.operationContext().Err() |
| 303 | 308 | } |
| 304 | 309 | if err = s.attach(); err == nil { |
| 305 | 删除: return s.runSafetyCheck() | |
| 310 | 新增: return s.checkNetworkIfWanted() | |
| 306 | 311 | } |
| 307 | 312 | time.Sleep(time.Second) |
| 308 | 313 | } |
| @@ -446,6 +451,7 @@ func (s *Server) monitorNetwork(ctx context.Context) { | ||
| 446 | 451 | s.monitorProxyInterface() |
| 447 | 452 | s.checkProxyHealth() |
| 448 | 453 | s.monitorSafety() |
| 454 | 新增: s.recoverNetwork() | |
| 449 | 455 | s.refreshProxySubscriptions() |
| 450 | 456 | s.op.Unlock() |
| 451 | 457 | } |
| @@ -0,0 +1,130 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "crypto/ed25519" | |
| 6 | 新增: "crypto/rand" | |
| 7 | 新增: "errors" | |
| 8 | 新增: "fmt" | |
| 9 | 新增: "net" | |
| 10 | 新增: "os" | |
| 11 | 新增: "os/exec" | |
| 12 | 新增: "path/filepath" | |
| 13 | 新增: "testing" | |
| 14 | 新增: "time" | |
| 15 | 新增: | |
| 16 | 新增: "github.com/sylvinus/agent-vm/internal/vmname" | |
| 17 | 新增: "golang.org/x/crypto/ssh" | |
| 18 | 新增:) | |
| 19 | 新增: | |
| 20 | 新增:func TestGuestScriptWithZshMiseInitialization(t *testing.T) { | |
| 21 | 新增: zsh, err := exec.LookPath("zsh") | |
| 22 | 新增: if err != nil { | |
| 23 | 新增: t.Skip("zsh unavailable") | |
| 24 | 新增: } | |
| 25 | 新增: if _, err := os.Stat(sshExecutable()); err != nil { | |
| 26 | 新增: t.Skip("OpenSSH unavailable") | |
| 27 | 新增: } | |
| 28 | 新增: home := t.TempDir() | |
| 29 | 新增: // Reduced from mise 2026.10.25's default zsh activation. With this | |
| 30 | 新增: // initialization, zsh returns 1 for a later commandless exec redirection. | |
| 31 | 新增: init := `[ -n "$(declare -f command_not_found_handler)" ] && true | |
| 32 | 新增:command_not_found_handler() { return 127; } | |
| 33 | 新增:` | |
| 34 | 新增: if err := os.WriteFile(filepath.Join(home, ".zshenv"), []byte(init), 0600); err != nil { | |
| 35 | 新增: t.Fatal(err) | |
| 36 | 新增: } | |
| 37 | 新增: cases := []struct { | |
| 38 | 新增: name, script, output string | |
| 39 | 新增: fail bool | |
| 40 | 新增: }{ | |
| 41 | 新增: {"resize-lock", "set -eu\nexport DISPLAY=:78\nexec 9>\"$HOME/resize.lock\"\nprintf '%s\\n' \"single ' quote\" 'literal $HOME'\n", "single ' quote\nliteral $HOME\n", false}, | |
| 42 | 新增: {"script-failure", "printf before-failure\nexit 7\n", "", true}, | |
| 43 | 新增: } | |
| 44 | 新增: | |
| 45 | 新增: listener, err := net.Listen("tcp", "127.0.0.1:0") | |
| 46 | 新增: if err != nil { | |
| 47 | 新增: t.Fatal(err) | |
| 48 | 新增: } | |
| 49 | 新增: t.Cleanup(func() { listener.Close() }) | |
| 50 | 新增: _, key, err := ed25519.GenerateKey(rand.Reader) | |
| 51 | 新增: if err != nil { | |
| 52 | 新增: t.Fatal(err) | |
| 53 | 新增: } | |
| 54 | 新增: signer, err := ssh.NewSignerFromKey(key) | |
| 55 | 新增: if err != nil { | |
| 56 | 新增: t.Fatal(err) | |
| 57 | 新增: } | |
| 58 | 新增: config := &ssh.ServerConfig{NoClientAuth: true} | |
| 59 | 新增: config.AddHostKey(signer) | |
| 60 | 新增: // Exercise the production SSH command and stdout handling. Only the | |
| 61 | 新增: // remote machine is replaced by a local server running a real zsh. | |
| 62 | 新增: go func() { | |
| 63 | 新增: for range cases { | |
| 64 | 新增: conn, err := listener.Accept() | |
| 65 | 新增: if err != nil { | |
| 66 | 新增: return | |
| 67 | 新增: } | |
| 68 | 新增: server, channels, requests, err := ssh.NewServerConn(conn, config) | |
| 69 | 新增: if err != nil { | |
| 70 | 新增: conn.Close() | |
| 71 | 新增: continue | |
| 72 | 新增: } | |
| 73 | 新增: go ssh.DiscardRequests(requests) | |
| 74 | 新增: for incoming := range channels { | |
| 75 | 新增: channel, requests, err := incoming.Accept() | |
| 76 | 新增: if err != nil { | |
| 77 | 新增: break | |
| 78 | 新增: } | |
| 79 | 新增: for request := range requests { | |
| 80 | 新增: if request.Type != "exec" { | |
| 81 | 新增: request.Reply(false, nil) | |
| 82 | 新增: continue | |
| 83 | 新增: } | |
| 84 | 新增: var command struct{ Command string } | |
| 85 | 新增: if err := ssh.Unmarshal(request.Payload, &command); err != nil { | |
| 86 | 新增: request.Reply(false, nil) | |
| 87 | 新增: break | |
| 88 | 新增: } | |
| 89 | 新增: request.Reply(true, nil) | |
| 90 | 新增: cmd := exec.Command(zsh, "-c", command.Command) | |
| 91 | 新增: cmd.Dir = home | |
| 92 | 新增: cmd.Env = []string{"HOME=" + home, "ZDOTDIR=" + home, "PATH=/usr/bin:/bin"} | |
| 93 | 新增: cmd.Stdin, cmd.Stdout, cmd.Stderr = channel, channel, channel.Stderr() | |
| 94 | 新增: status := uint32(0) | |
| 95 | 新增: if err := cmd.Run(); err != nil { | |
| 96 | 新增: status = 1 | |
| 97 | 新增: var exit *exec.ExitError | |
| 98 | 新增: if errors.As(err, &exit) { | |
| 99 | 新增: status = uint32(exit.ExitCode()) | |
| 100 | 新增: } | |
| 101 | 新增: } | |
| 102 | 新增: channel.SendRequest("exit-status", false, ssh.Marshal(struct{ Status uint32 }{status})) | |
| 103 | 新增: break | |
| 104 | 新增: } | |
| 105 | 新增: channel.Close() | |
| 106 | 新增: break | |
| 107 | 新增: } | |
| 108 | 新增: server.Close() | |
| 109 | 新增: } | |
| 110 | 新增: }() | |
| 111 | 新增: s := testServer(t) | |
| 112 | 新增: dir := filepath.Join(s.profile, "state", "lima", vmname.Name(s.environmentDir())) | |
| 113 | 新增: if err := os.MkdirAll(dir, 0700); err != nil { | |
| 114 | 新增: t.Fatal(err) | |
| 115 | 新增: } | |
| 116 | 新增: clientConfig := fmt.Sprintf("Host *\n HostName 127.0.0.1\n Port %d\n User cage\n StrictHostKeyChecking no\n UserKnownHostsFile %s\n", listener.Addr().(*net.TCPAddr).Port, os.DevNull) | |
| 117 | 新增: if err := os.WriteFile(filepath.Join(dir, "ssh.config"), []byte(clientConfig), 0600); err != nil { | |
| 118 | 新增: t.Fatal(err) | |
| 119 | 新增: } | |
| 120 | 新增: for _, tc := range cases { | |
| 121 | 新增: t.Run(tc.name, func(t *testing.T) { | |
| 122 | 新增: ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) | |
| 123 | 新增: defer cancel() | |
| 124 | 新增: out, err := s.guest(ctx, tc.script) | |
| 125 | 新增: if (err != nil) != tc.fail || string(out) != tc.output { | |
| 126 | 新增: t.Fatalf("guest returned %q, %v", out, err) | |
| 127 | 新增: } | |
| 128 | 新增: }) | |
| 129 | 新增: } | |
| 130 | 新增:} | |
| @@ -107,6 +107,7 @@ func (s *Server) revokeNetworkNow(reason string, pause bool) error { | ||
| 107 | 107 | var intentErr error |
| 108 | 108 | s.mu.Lock() |
| 109 | 109 | if pause { |
| 110 | 新增: s.recovery = networkRecovery{} | |
| 110 | 111 | s.networkPaused = true |
| 111 | 112 | s.safety.pauseVersion++ |
| 112 | 113 | intentErr = s.saveNetworkIntentLocked(true) |
| @@ -575,9 +576,18 @@ func (s *Server) monitorSafety() { | ||
| 575 | 576 | } |
| 576 | 577 | s.publishGate(state) |
| 577 | 578 | if state.Mode != cage.GateOpen || state.Report == nil { |
| 579 | 新增: if state.Mode == cage.GateClosed && state.Reason == "检查或监测授权已到期" && state.Report != nil { | |
| 580 | 新增: s.mu.Lock() | |
| 581 | 新增: pending := s.recovery.RunID != "" | |
| 582 | 新增: s.mu.Unlock() | |
| 583 | 新增: if !pending { | |
| 584 | 新增: s.scheduleNetworkRecovery(state) | |
| 585 | 新增: } | |
| 586 | 新增: } | |
| 578 | 587 | return |
| 579 | 588 | } |
| 580 | 589 | var issue string |
| 590 | 新增: var recoverable bool | |
| 581 | 591 | cfg, err := loadConfig(s.configPath) |
| 582 | 592 | if err != nil || cfg.Fingerprint() != state.Configuration { |
| 583 | 593 | issue = "配置与运行环境不一致,请应用设置并重新检测" |
| @@ -592,6 +602,7 @@ func (s *Server) monitorSafety() { | ||
| 592 | 602 | ip, err = cage.ProbeExitIP(ctx, cfg) |
| 593 | 603 | if err != nil { |
| 594 | 604 | issue = "当前无法经指定代理确认出口,外网已暂停" |
| 605 | 新增: recoverable = true | |
| 595 | 606 | } else { |
| 596 | 607 | result, message := s.checkExitPolicy(ctx, cfg, ip) |
| 597 | 608 | if result != cage.CheckPassed { |
| @@ -603,19 +614,25 @@ func (s *Server) monitorSafety() { | ||
| 603 | 614 | guest, e := s.guestObservation(ctx, map[string]any{"stage": "environment"}) |
| 604 | 615 | if e != nil || !guestSettingsMatch(guest, cfg) { |
| 605 | 616 | issue = "系统时区或语言的运行状态无法确认,请重新检测" |
| 617 | 新增: recoverable = e != nil | |
| 606 | 618 | } |
| 607 | 619 | } |
| 608 | 620 | if issue == "" { |
| 609 | 621 | browser, e := s.browserObservation(ctx, cfg, false) |
| 610 | 622 | if e != nil || !browserSettingsMatch(browser, cfg) { |
| 611 | 623 | issue = "浏览器时区或语言的运行状态无法确认,请重新检测" |
| 624 | 新增: recoverable = e != nil | |
| 612 | 625 | } |
| 613 | 626 | } |
| 614 | 删除: s.finishSafetyMonitor(ctx, client, state, ip, issue) | |
| 627 | 新增: s.finishSafetyObservation(ctx, client, state, ip, issue, recoverable) | |
| 615 | 628 | } |
| 616 | 629 | |
| 617 | 630 | // Recheck the user operation and configuration at the actual lease write. |
| 618 | 631 | func (s *Server) finishSafetyMonitor(ctx context.Context, client *cage.GateClient, state cage.GateStatus, ip, issue string) { |
| 632 | 新增: s.finishSafetyObservation(ctx, client, state, ip, issue, false) | |
| 633 | 新增:} | |
| 634 | 新增: | |
| 635 | 新增:func (s *Server) finishSafetyObservation(ctx context.Context, client *cage.GateClient, state cage.GateStatus, ip, issue string, recoverable bool) { | |
| 619 | 636 | s.safetyOp.Lock() |
| 620 | 637 | defer s.safetyOp.Unlock() |
| 621 | 638 | s.mu.Lock() |
| @@ -627,11 +644,15 @@ func (s *Server) finishSafetyMonitor(ctx context.Context, client *cage.GateClien | ||
| 627 | 644 | current, e := loadConfig(s.configPath) |
| 628 | 645 | if e != nil || current.Fingerprint() != state.Configuration { |
| 629 | 646 | issue = "运行配置已变化,请重新应用设置" |
| 647 | 新增: recoverable = false | |
| 630 | 648 | } |
| 631 | 649 | if issue != "" { |
| 632 | 650 | closed, e := client.Close(context.Background(), issue) |
| 633 | 651 | if e == nil { |
| 634 | 652 | s.publishGate(closed) |
| 653 | 新增: if recoverable { | |
| 654 | 新增: s.scheduleNetworkRecovery(closed) | |
| 655 | 新增: } | |
| 635 | 656 | } |
| 636 | 657 | s.mu.Lock() |
| 637 | 658 | s.safety.Error = issue |
| @@ -645,6 +666,7 @@ func (s *Server) finishSafetyMonitor(ctx context.Context, client *cage.GateClien | ||
| 645 | 666 | closed, e := client.Close(context.Background(), "运行监测未能续期,请重新检测") |
| 646 | 667 | if e == nil { |
| 647 | 668 | s.publishGate(closed) |
| 669 | 新增: s.scheduleNetworkRecovery(closed) | |
| 648 | 670 | } |
| 649 | 671 | s.mu.Lock() |
| 650 | 672 | s.safety.Error = "运行监测未能续期,请重新检测" |
| @@ -10,15 +10,18 @@ import ( | ||
| 10 | 10 | "errors" |
| 11 | 11 | "fmt" |
| 12 | 12 | "github.com/sylvinus/agent-vm/internal/cage" |
| 13 | 新增: "github.com/sylvinus/agent-vm/internal/diagnostics" | |
| 13 | 14 | "github.com/sylvinus/agent-vm/internal/host" |
| 14 | 15 | "github.com/sylvinus/agent-vm/internal/vmname" |
| 15 | 16 | "io" |
| 16 | 17 | "io/fs" |
| 18 | 新增: "log" | |
| 17 | 19 | "net" |
| 18 | 20 | "net/http" |
| 19 | 21 | "net/url" |
| 20 | 22 | "os" |
| 21 | 23 | "path/filepath" |
| 24 | 新增: "runtime/debug" | |
| 22 | 25 | "strings" |
| 23 | 26 | "sync" |
| 24 | 27 | "time" |
| @@ -44,6 +47,10 @@ type Server struct { | ||
| 44 | 47 | closing bool |
| 45 | 48 | shutdown func() |
| 46 | 49 | favoritesMu sync.Mutex |
| 50 | 新增: diagnosticMu sync.Mutex | |
| 51 | 新增: diagnosticRateMu sync.Mutex | |
| 52 | 新增: diagnosticWindow time.Time | |
| 53 | 新增: diagnosticCount int | |
| 47 | 54 | tickets map[string]time.Time |
| 48 | 55 | browserControl *browserClient |
| 49 | 56 | op sync.Mutex |
| @@ -60,6 +67,7 @@ type Server struct { | ||
| 60 | 67 | projectShares map[string]*projectShare |
| 61 | 68 | projectErrors []projectShareError |
| 62 | 69 | safety safetyState |
| 70 | 新增: recovery networkRecovery | |
| 63 | 71 | locations map[string]Location |
| 64 | 72 | monitorCancel context.CancelFunc |
| 65 | 73 | safetyOp sync.Mutex |
| @@ -86,6 +94,14 @@ func equalSecret(a, b string) bool { | ||
| 86 | 94 | return len(a) > 0 && subtle.ConstantTimeCompare([]byte(a), []byte(b)) == 1 |
| 87 | 95 | } |
| 88 | 96 | func Serve(configPath string) (returned error) { |
| 97 | 新增: store := diagnostics.New(filepath.Dir(configPath)) | |
| 98 | 新增: diagnostics.SetDefault(store) | |
| 99 | 新增: if err := store.Clean(); err != nil { | |
| 100 | 新增: return err | |
| 101 | 新增: } | |
| 102 | 新增: | |
| 103 | 新增: diagnostics.Log("info", "controller", "service starting") | |
| 104 | 新增: defer func() { diagnostics.Log("info", "controller", "service stopped") }() | |
| 89 | 105 | profile := filepath.Dir(configPath) |
| 90 | 106 | if err := host.EnsurePrivateDir(profile); err != nil { |
| 91 | 107 | return err |
| @@ -98,6 +114,9 @@ func Serve(configPath string) (returned error) { | ||
| 98 | 114 | if err = lockController(lock); err != nil { |
| 99 | 115 | return errors.New("此配置已有工作台服务正在运行") |
| 100 | 116 | } |
| 117 | 新增: if err := store.ImportLegacy(filepath.Dir(configPath)); err != nil { | |
| 118 | 新增: diagnostics.Log("warn", "diagnostics", "legacy log import failed: "+err.Error()) | |
| 119 | 新增: } | |
| 101 | 120 | exe, err := os.Executable() |
| 102 | 121 | if err != nil { |
| 103 | 122 | return err |
| @@ -154,7 +173,9 @@ func Serve(configPath string) (returned error) { | ||
| 154 | 173 | _ = s.closeProxyGate("网络保持暂停,请手动恢复后再联网") |
| 155 | 174 | } |
| 156 | 175 | s.startMonitors() |
| 157 | 删除: server := &http.Server{Handler: s.handler(), ReadHeaderTimeout: 5 * time.Second, IdleTimeout: 60 * time.Second, MaxHeaderBytes: 16 << 10} | |
| 176 | 新增: serverErrors := store.Stream("http", "error") | |
| 177 | 新增: defer serverErrors.Close() | |
| 178 | 新增: server := &http.Server{ErrorLog: log.New(serverErrors, "", 0), Handler: s.handler(), ReadHeaderTimeout: 5 * time.Second, IdleTimeout: 60 * time.Second, MaxHeaderBytes: 16 << 10} | |
| 158 | 179 | defer server.Close() |
| 159 | 180 | shutdownDone := make(chan struct{}) |
| 160 | 181 | s.shutdown = func() { |
| @@ -197,11 +218,17 @@ func (s *Server) handler() http.Handler { | ||
| 197 | 218 | jsonReply(w, map[string]bool{"ok": true}) |
| 198 | 219 | }) |
| 199 | 220 | mux.HandleFunc("GET /api/status", s.status) |
| 221 | 新增: mux.HandleFunc("POST /api/input", s.remoteInput) | |
| 222 | 新增: mux.HandleFunc("GET /api/diagnostics", s.diagnosticStatus) | |
| 223 | 新增: mux.HandleFunc("POST /api/diagnostics/events", s.diagnosticEvent) | |
| 224 | 新增: mux.HandleFunc("GET /api/diagnostics/export", s.diagnosticExport) | |
| 200 | 225 | mux.HandleFunc("GET /api/account", s.accountStatus) |
| 201 | 226 | mux.HandleFunc("POST /api/account/{action}", s.accountAction) |
| 202 | 227 | mux.HandleFunc("GET /api/settings", s.getSettings) |
| 203 | 228 | mux.HandleFunc("POST /api/projects/open", s.openProject) |
| 204 | 229 | mux.HandleFunc("GET /api/environment/versions", s.environmentVersions) |
| 230 | 新增: mux.HandleFunc("GET /api/environment/resources", s.resourceStatus) | |
| 231 | 新增: mux.HandleFunc("POST /api/environment/resources", s.applyResources) | |
| 205 | 232 | mux.HandleFunc("POST /api/environment/update", s.updateEnvironment) |
| 206 | 233 | mux.HandleFunc("POST /api/environment/tools", s.updateEnvironmentTools) |
| 207 | 234 | mux.HandleFunc("GET /api/host/git", s.hostGit) |
| @@ -290,7 +317,7 @@ func (s *Server) handler() http.Handler { | ||
| 290 | 317 | r = r.WithContext(ctx) |
| 291 | 318 | accountRoute := r.URL.Path == "/api/account" || strings.HasPrefix(r.URL.Path, "/api/account/") |
| 292 | 319 | bootstrapRoute := r.URL.Path == "/api/session" || r.URL.Path == "/api/launch" || r.URL.Path == "/api/handoff" |
| 293 | 删除: if strings.HasPrefix(r.URL.Path, "/api/") && !accountRoute && !bootstrapRoute && !(r.Method == "GET" && r.URL.Path == "/api/appearance") { | |
| 320 | 新增: if strings.HasPrefix(r.URL.Path, "/api/") && !accountRoute && !bootstrapRoute && !strings.HasPrefix(r.URL.Path, "/api/diagnostics") && !(r.Method == "GET" && r.URL.Path == "/api/appearance") { | |
| 294 | 321 | epoch, unlocked := s.account.access() |
| 295 | 322 | if !unlocked { |
| 296 | 323 | http.Error(w, "Cage 已锁定,请先登录", http.StatusLocked) |
| @@ -302,6 +329,19 @@ func (s *Server) handler() http.Handler { | ||
| 302 | 329 | r = r.WithContext(ctx) |
| 303 | 330 | } |
| 304 | 331 | defer interruptHTTPOnCancel(w, r)() |
| 332 | 新增: response := &diagnosticResponse{ResponseWriter: w} | |
| 333 | 新增: w = response | |
| 334 | 新增: defer func() { | |
| 335 | 新增: if response.status >= 400 && r.URL.Path != "/api/diagnostics/events" { | |
| 336 | 新增: _ = diagnostics.New(s.profile).Record("warn", "http", fmt.Sprintf("%s %s returned %d", r.Method, r.Pattern, response.status)) | |
| 337 | 新增: } | |
| 338 | 新增: }() | |
| 339 | 新增: defer func() { | |
| 340 | 新增: if failure := recover(); failure != nil { | |
| 341 | 新增: diagnostics.Log("error", "http", fmt.Sprintf("handler panic: %v\n%s", failure, debug.Stack())) | |
| 342 | 新增: panic(failure) | |
| 343 | 新增: } | |
| 344 | 新增: }() | |
| 305 | 345 | mux.ServeHTTP(w, r) |
| 306 | 346 | }) |
| 307 | 347 | } |
| @@ -332,6 +372,7 @@ func jsonReply(w http.ResponseWriter, v any) { | ||
| 332 | 372 | _ = json.NewEncoder(w).Encode(v) |
| 333 | 373 | } |
| 334 | 374 | func requestError(w http.ResponseWriter, err error) { |
| 375 | 新增: diagnostics.Log("error", "api", err.Error()) | |
| 335 | 376 | http.Error(w, err.Error(), http.StatusBadRequest) |
| 336 | 377 | } |
| 337 | 378 | func (s *Server) status(w http.ResponseWriter, r *http.Request) { |
| @@ -51,6 +51,7 @@ It runs inside the Lima hostagent, which with vz also runs the VM: a panic there | ||
| 51 | 51 | | `lima/0008-qemu-dgram-netdev` | lima-vm/lima | not sent; the issue to open at QEMU is the patch's header | Bug 22: QEMU gets the netstack through a datagram socketpair (`-netdev dgram`, `GVisorNetstackOpts.DgramConn`), as vz does; the `socket` netdev, and its unix socket listener, only for a QEMU older than 7.2, and Windows (the `stream` netdev has the bug too). Tests `TestDgramConn`, `TestDgramPair`, `TestFdDgramTemplate`; the netdev choice is covered by agent-vm's e2e. | |
| 52 | 52 | | `lima/0009-start-channels-buffered` | lima-vm/lima | not sent | `StartWithPaths` left the losing goroutine of its race blocked on an unbuffered send, for as long as the program lives. No test: it starts a hostagent. | |
| 53 | 53 | | `lima/0011-windows-native-usernet-socket` | lima-vm/lima | not sent | Opens the per-instance network control endpoint with its native filesystem path. Constructing `unix://C:\\...` fails URL parsing on Windows. `TestNetstackWindowsNativeSocketPaths` connects to both control and QEMU AF_UNIX listeners on Windows. | |
| 54 | 新增:| `lima/0012-dynamic-memory` | lima-vm/lima | not sent | Adds an optional hostagent resource controller with bounded private SSH observations, VZ memory targets and deadline-bound QEMU balloon commands. Stops the controller before the VM and suppresses probe consoles on Windows. VZ borrowed device wrappers retain VM ownership instead of releasing it from a temporary Go finalizer. Protocol, cancellation and capacity checks are covered in `TestMemoryTargetQMPProtocolAndCancellation`; Cage owns the adaptive policy and live acceptance. | | |
| 54 | 55 | | `sshocker/0001-rooted-server-readonly-names` | lima-vm/sshocker | fork branch `readonly-names` | The builtin server serves only the mounted directory, and `ReadonlyNames`. | |
| 55 | 56 | | `sshocker/0002-expect-remove` | lima-vm/sshocker | fork branch `expect-remove` | `ExpectRemove`, for 0002 of Lima. | |
| 56 | 57 | | `sshocker/0003-append-fix` | lima-vm/sshocker | not sent | Bug 1. Tests `TestRootedOpenAppend`, `TestRootedOpenMode`. No pkg/sftp dependency: send first. | |
| @@ -0,0 +1,378 @@ | ||
| 1 | 新增:diff --git a/pkg/driver/qemu/qemu.go b/pkg/driver/qemu/qemu.go | |
| 2 | 新增:index bf55ddb..2dba8c5 100644 | |
| 3 | 新增:--- a/pkg/driver/qemu/qemu.go | |
| 4 | 新增:+++ b/pkg/driver/qemu/qemu.go | |
| 5 | 新增:@@ -525,6 +525,10 @@ func Cmdline(ctx context.Context, cfg Config) (exe string, args []string, err er | |
| 6 | 新增: } | |
| 7 | 新增: memBytes = adjustMemBytesDarwinARM64HVF(memBytes, accel) | |
| 8 | 新增: args = appendArgsIfNoConflict(args, "-m", strconv.Itoa(int(memBytes>>20))) | |
| 9 | 新增:+ // A balloon returns guest pages to the host without restarting the VM. | |
| 10 | 新增:+ if *y.OS == limatype.LINUX { | |
| 11 | 新增:+ args = append(args, "-device", "virtio-balloon") | |
| 12 | 新增:+ } | |
| 13 | 新增: | |
| 14 | 新增: if *y.MountType == limatype.VIRTIOFS { | |
| 15 | 新增: args = appendArgsIfNoConflict(args, "-object", | |
| 16 | 新增:diff --git a/pkg/hostagent/hostagent.go b/pkg/hostagent/hostagent.go | |
| 17 | 新增:index d1e8fa7..8b1fbc0 100644 | |
| 18 | 新增:--- a/pkg/hostagent/hostagent.go | |
| 19 | 新增:+++ b/pkg/hostagent/hostagent.go | |
| 20 | 新增:@@ -448,6 +448,9 @@ func (a *HostAgent) Run(ctx context.Context) error { | |
| 21 | 新增: if err := a.driver.AdditionalSetupForSSH(ctx); err != nil { | |
| 22 | 新增: return err | |
| 23 | 新增: } | |
| 24 | 新增:+ stopResources := a.startResourceManager(ctx) | |
| 25 | 新增:+ defer stopResources() | |
| 26 | 新增:+ a.cleanUp(func() error { stopResources(); return nil }) | |
| 27 | 新增: | |
| 28 | 新增: // WSL instance SSH address isn't known until after VM start | |
| 29 | 新增: if a.driver.Info(ctx).Features.DynamicSSHAddress { | |
| 30 | 新增:diff --git a/pkg/driver/memory.go b/pkg/driver/memory.go | |
| 31 | 新增:new file mode 100644 | |
| 32 | 新增:index 0000000..4fc8fbb | |
| 33 | 新增:--- /dev/null | |
| 34 | 新增:+++ b/pkg/driver/memory.go | |
| 35 | 新增:@@ -0,0 +1,12 @@ | |
| 36 | 新增:+// SPDX-FileCopyrightText: Copyright The Lima Authors | |
| 37 | 新增:+// SPDX-License-Identifier: Apache-2.0 | |
| 38 | 新增:+ | |
| 39 | 新增:+package driver | |
| 40 | 新增:+ | |
| 41 | 新增:+import "context" | |
| 42 | 新增:+ | |
| 43 | 新增:+// MemoryBalloon adjusts guest memory within the configured boot capacity. | |
| 44 | 新增:+// Acceptance is asynchronous; callers must observe the guest before reclaiming more. | |
| 45 | 新增:+type MemoryBalloon interface { | |
| 46 | 新增:+ SetMemoryTarget(context.Context, uint64) error | |
| 47 | 新增:+} | |
| 48 | 新增:diff --git a/pkg/driver/qemu/memory.go b/pkg/driver/qemu/memory.go | |
| 49 | 新增:new file mode 100644 | |
| 50 | 新增:index 0000000..cbd2ef6 | |
| 51 | 新增:--- /dev/null | |
| 52 | 新增:+++ b/pkg/driver/qemu/memory.go | |
| 53 | 新增:@@ -0,0 +1,81 @@ | |
| 54 | 新增:+// SPDX-FileCopyrightText: Copyright The Lima Authors | |
| 55 | 新增:+// SPDX-License-Identifier: Apache-2.0 | |
| 56 | 新增:+ | |
| 57 | 新增:+package qemu | |
| 58 | 新增:+ | |
| 59 | 新增:+import ( | |
| 60 | 新增:+ "context" | |
| 61 | 新增:+ "encoding/json" | |
| 62 | 新增:+ "errors" | |
| 63 | 新增:+ "fmt" | |
| 64 | 新增:+ "io" | |
| 65 | 新增:+ "net" | |
| 66 | 新增:+ "path/filepath" | |
| 67 | 新增:+ "time" | |
| 68 | 新增:+ | |
| 69 | 新增:+ "github.com/docker/go-units" | |
| 70 | 新增:+ "github.com/lima-vm/lima/v2/pkg/limatype/filenames" | |
| 71 | 新增:+) | |
| 72 | 新增:+ | |
| 73 | 新增:+func (l *LimaQemuDriver) SetMemoryTarget(ctx context.Context, target uint64) error { | |
| 74 | 新增:+ if err := ctx.Err(); err != nil { | |
| 75 | 新增:+ return err | |
| 76 | 新增:+ } | |
| 77 | 新增:+ maximum, err := units.RAMInBytes(*l.Instance.Config.Memory) | |
| 78 | 新增:+ if err != nil { | |
| 79 | 新增:+ return err | |
| 80 | 新增:+ } | |
| 81 | 新增:+ if target < 512<<20 || target > uint64(maximum) || target%(1<<20) != 0 { | |
| 82 | 新增:+ return errors.New("memory target is outside the VM capacity") | |
| 83 | 新增:+ } | |
| 84 | 新增:+ ctx, cancel := context.WithTimeout(ctx, 3*time.Second) | |
| 85 | 新增:+ defer cancel() | |
| 86 | 新增:+ conn, err := (&net.Dialer{}).DialContext(ctx, "unix", filepath.Join(l.Instance.Dir, filenames.QMPSock)) | |
| 87 | 新增:+ if err != nil { | |
| 88 | 新增:+ return err | |
| 89 | 新增:+ } | |
| 90 | 新增:+ defer conn.Close() | |
| 91 | 新增:+ stop := context.AfterFunc(ctx, func() { _ = conn.Close() }) | |
| 92 | 新增:+ defer stop() | |
| 93 | 新增:+ deadline, _ := ctx.Deadline() | |
| 94 | 新增:+ if err := conn.SetDeadline(deadline); err != nil { | |
| 95 | 新增:+ return err | |
| 96 | 新增:+ } | |
| 97 | 新增:+ decoder := json.NewDecoder(io.LimitReader(conn, 64<<10)) | |
| 98 | 新增:+ var greeting map[string]json.RawMessage | |
| 99 | 新增:+ if err := decoder.Decode(&greeting); err != nil { | |
| 100 | 新增:+ return err | |
| 101 | 新增:+ } | |
| 102 | 新增:+ if greeting["QMP"] == nil { | |
| 103 | 新增:+ return errors.New("invalid QMP greeting") | |
| 104 | 新增:+ } | |
| 105 | 新增:+ encoder := json.NewEncoder(conn) | |
| 106 | 新增:+ for i, command := range []string{"qmp_capabilities", "balloon"} { | |
| 107 | 新增:+ request := map[string]any{"execute": command, "id": i + 1} | |
| 108 | 新增:+ if command == "balloon" { | |
| 109 | 新增:+ request["arguments"] = map[string]uint64{"value": target} | |
| 110 | 新增:+ } | |
| 111 | 新增:+ if err := encoder.Encode(request); err != nil { | |
| 112 | 新增:+ return err | |
| 113 | 新增:+ } | |
| 114 | 新增:+ for { | |
| 115 | 新增:+ var response struct { | |
| 116 | 新增:+ ID int `json:"id"` | |
| 117 | 新增:+ Error *struct { | |
| 118 | 新增:+ Class string `json:"class"` | |
| 119 | 新增:+ } `json:"error"` | |
| 120 | 新增:+ } | |
| 121 | 新增:+ if err := decoder.Decode(&response); err != nil { | |
| 122 | 新增:+ return err | |
| 123 | 新增:+ } | |
| 124 | 新增:+ if response.ID != i+1 { | |
| 125 | 新增:+ continue | |
| 126 | 新增:+ } | |
| 127 | 新增:+ if response.Error != nil { | |
| 128 | 新增:+ return fmt.Errorf("QMP memory adjustment failed: %s", response.Error.Class) | |
| 129 | 新增:+ } | |
| 130 | 新增:+ break | |
| 131 | 新增:+ } | |
| 132 | 新增:+ } | |
| 133 | 新增:+ return nil | |
| 134 | 新增:+} | |
| 135 | 新增:diff --git a/pkg/driver/qemu/memory_test.go b/pkg/driver/qemu/memory_test.go | |
| 136 | 新增:new file mode 100644 | |
| 137 | 新增:index 0000000..97e13a7 | |
| 138 | 新增:--- /dev/null | |
| 139 | 新增:+++ b/pkg/driver/qemu/memory_test.go | |
| 140 | 新增:@@ -0,0 +1,89 @@ | |
| 141 | 新增:+// SPDX-FileCopyrightText: Copyright The Lima Authors | |
| 142 | 新增:+// SPDX-License-Identifier: Apache-2.0 | |
| 143 | 新增:+ | |
| 144 | 新增:+package qemu | |
| 145 | 新增:+ | |
| 146 | 新增:+import ( | |
| 147 | 新增:+ "context" | |
| 148 | 新增:+ "encoding/json" | |
| 149 | 新增:+ "net" | |
| 150 | 新增:+ "os" | |
| 151 | 新增:+ "path/filepath" | |
| 152 | 新增:+ "testing" | |
| 153 | 新增:+ "time" | |
| 154 | 新增:+ | |
| 155 | 新增:+ "github.com/lima-vm/lima/v2/pkg/limatype" | |
| 156 | 新增:+ "github.com/lima-vm/lima/v2/pkg/limatype/filenames" | |
| 157 | 新增:+) | |
| 158 | 新增:+ | |
| 159 | 新增:+func TestMemoryTargetQMPProtocolAndCancellation(t *testing.T) { | |
| 160 | 新增:+ for _, stall := range []bool{false, true} { | |
| 161 | 新增:+ t.Run(map[bool]string{false: "command", true: "cancelled"}[stall], func(t *testing.T) { | |
| 162 | 新增:+ dir, err := os.MkdirTemp("", "cqm-") | |
| 163 | 新增:+ if err != nil { | |
| 164 | 新增:+ t.Fatal(err) | |
| 165 | 新增:+ } | |
| 166 | 新增:+ defer os.RemoveAll(dir) | |
| 167 | 新增:+ memory := "4GiB" | |
| 168 | 新增:+ l := &LimaQemuDriver{Instance: &limatype.Instance{Dir: dir, Config: &limatype.LimaYAML{Memory: &memory}}} | |
| 169 | 新增:+ listener, err := net.Listen("unix", filepath.Join(dir, filenames.QMPSock)) | |
| 170 | 新增:+ if err != nil { | |
| 171 | 新增:+ t.Fatal(err) | |
| 172 | 新增:+ } | |
| 173 | 新增:+ defer listener.Close() | |
| 174 | 新增:+ done := make(chan error, 1) | |
| 175 | 新增:+ go func() { | |
| 176 | 新增:+ conn, e := listener.Accept() | |
| 177 | 新增:+ if e != nil { | |
| 178 | 新增:+ done <- e | |
| 179 | 新增:+ return | |
| 180 | 新增:+ } | |
| 181 | 新增:+ defer conn.Close() | |
| 182 | 新增:+ _ = conn.SetDeadline(time.Now().Add(time.Second)) | |
| 183 | 新增:+ if stall { | |
| 184 | 新增:+ var b [1]byte | |
| 185 | 新增:+ _, e = conn.Read(b[:]) | |
| 186 | 新增:+ done <- e | |
| 187 | 新增:+ return | |
| 188 | 新增:+ } | |
| 189 | 新增:+ enc, dec := json.NewEncoder(conn), json.NewDecoder(conn) | |
| 190 | 新增:+ _ = enc.Encode(map[string]any{"QMP": map[string]any{}}) | |
| 191 | 新增:+ for i := 1; i <= 2; i++ { | |
| 192 | 新增:+ var request struct { | |
| 193 | 新增:+ ID int `json:"id"` | |
| 194 | 新增:+ Execute string `json:"execute"` | |
| 195 | 新增:+ Arguments struct { | |
| 196 | 新增:+ Value uint64 `json:"value"` | |
| 197 | 新增:+ } `json:"arguments"` | |
| 198 | 新增:+ } | |
| 199 | 新增:+ if e = dec.Decode(&request); e != nil { | |
| 200 | 新增:+ done <- e | |
| 201 | 新增:+ return | |
| 202 | 新增:+ } | |
| 203 | 新增:+ if request.ID != i || (i == 1 && request.Execute != "qmp_capabilities") || (i == 2 && (request.Execute != "balloon" || request.Arguments.Value != 2<<30)) { | |
| 204 | 新增:+ t.Error("wrong QMP request", request) | |
| 205 | 新增:+ } | |
| 206 | 新增:+ _ = enc.Encode(map[string]any{"event": "BALLOON_CHANGE"}) | |
| 207 | 新增:+ _ = enc.Encode(map[string]any{"id": i, "return": map[string]any{}}) | |
| 208 | 新增:+ } | |
| 209 | 新增:+ done <- nil | |
| 210 | 新增:+ }() | |
| 211 | 新增:+ ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) | |
| 212 | 新增:+ defer cancel() | |
| 213 | 新增:+ started := time.Now() | |
| 214 | 新增:+ err = l.SetMemoryTarget(ctx, 2<<30) | |
| 215 | 新增:+ if (err != nil) != stall { | |
| 216 | 新增:+ t.Fatal("unexpected command result", err) | |
| 217 | 新增:+ } | |
| 218 | 新增:+ if time.Since(started) > time.Second { | |
| 219 | 新增:+ t.Fatal("deadline ignored") | |
| 220 | 新增:+ } | |
| 221 | 新增:+ if e := <-done; e != nil && !stall { | |
| 222 | 新增:+ t.Fatal(e) | |
| 223 | 新增:+ } | |
| 224 | 新增:+ if err := l.SetMemoryTarget(context.Background(), 5<<30); err == nil { | |
| 225 | 新增:+ t.Fatal("capacity exceeded") | |
| 226 | 新增:+ } | |
| 227 | 新增:+ }) | |
| 228 | 新增:+ } | |
| 229 | 新增:+} | |
| 230 | 新增:diff --git a/pkg/driver/vz/memory_darwin.go b/pkg/driver/vz/memory_darwin.go | |
| 231 | 新增:new file mode 100644 | |
| 232 | 新增:index 0000000..7f0c7e0 | |
| 233 | 新增:--- /dev/null | |
| 234 | 新增:+++ b/pkg/driver/vz/memory_darwin.go | |
| 235 | 新增:@@ -0,0 +1,43 @@ | |
| 236 | 新增:+//go:build darwin && !no_vz | |
| 237 | 新增:+ | |
| 238 | 新增:+// SPDX-FileCopyrightText: Copyright The Lima Authors | |
| 239 | 新增:+// SPDX-License-Identifier: Apache-2.0 | |
| 240 | 新增:+ | |
| 241 | 新增:+package vz | |
| 242 | 新增:+ | |
| 243 | 新增:+import ( | |
| 244 | 新增:+ "context" | |
| 245 | 新增:+ "errors" | |
| 246 | 新增:+ "runtime" | |
| 247 | 新增:+ | |
| 248 | 新增:+ "github.com/Code-Hex/vz/v3" | |
| 249 | 新增:+ "github.com/docker/go-units" | |
| 250 | 新增:+) | |
| 251 | 新增:+ | |
| 252 | 新增:+func (l *LimaVzDriver) SetMemoryTarget(ctx context.Context, target uint64) error { | |
| 253 | 新增:+ if err := ctx.Err(); err != nil { | |
| 254 | 新增:+ return err | |
| 255 | 新增:+ } | |
| 256 | 新增:+ maximum, err := units.RAMInBytes(*l.Instance.Config.Memory) | |
| 257 | 新增:+ if err != nil { | |
| 258 | 新增:+ return err | |
| 259 | 新增:+ } | |
| 260 | 新增:+ if target < 512<<20 || target > uint64(maximum) || target%(1<<20) != 0 { | |
| 261 | 新增:+ return errors.New("memory target is outside the VM capacity") | |
| 262 | 新增:+ } | |
| 263 | 新增:+ if l.machine == nil || l.machine.State() != vz.VirtualMachineStateRunning { | |
| 264 | 新增:+ return errors.New("VM is not running") | |
| 265 | 新增:+ } | |
| 266 | 新增:+ for _, device := range l.machine.MemoryBalloonDevices() { | |
| 267 | 新增:+ if balloon := vz.AsVirtioTraditionalMemoryBalloonDevice(device); balloon != nil { | |
| 268 | 新增:+ // go-vz v3.7.1 wraps a borrowed NSArray member without retaining it, | |
| 269 | 新增:+ // but installs a releasing finalizer. The VM owns this native device. | |
| 270 | 新增:+ // Do not let temporary wrappers release the VM's reference. | |
| 271 | 新增:+ runtime.SetFinalizer(balloon, nil) | |
| 272 | 新增:+ balloon.SetTargetVirtualMachineMemorySize(target) | |
| 273 | 新增:+ runtime.KeepAlive(l.machine) | |
| 274 | 新增:+ return nil | |
| 275 | 新增:+ } | |
| 276 | 新增:+ } | |
| 277 | 新增:+ return errors.New("memory balloon is unavailable") | |
| 278 | 新增:+} | |
| 279 | 新增:diff --git a/pkg/hostagent/resources.go b/pkg/hostagent/resources.go | |
| 280 | 新增:new file mode 100644 | |
| 281 | 新增:index 0000000..0fc1e79 | |
| 282 | 新增:--- /dev/null | |
| 283 | 新增:+++ b/pkg/hostagent/resources.go | |
| 284 | 新增:@@ -0,0 +1,59 @@ | |
| 285 | 新增:+// SPDX-FileCopyrightText: Copyright The Lima Authors | |
| 286 | 新增:+// SPDX-License-Identifier: Apache-2.0 | |
| 287 | 新增:+ | |
| 288 | 新增:+package hostagent | |
| 289 | 新增:+ | |
| 290 | 新增:+import ( | |
| 291 | 新增:+ "context" | |
| 292 | 新增:+ "errors" | |
| 293 | 新增:+ "io" | |
| 294 | 新增:+ "os/exec" | |
| 295 | 新增:+ "strconv" | |
| 296 | 新增:+ "sync" | |
| 297 | 新增:+ "time" | |
| 298 | 新增:+ | |
| 299 | 新增:+ "github.com/lima-vm/lima/v2/pkg/driver" | |
| 300 | 新增:+ "github.com/lima-vm/lima/v2/pkg/limatype" | |
| 301 | 新增:+) | |
| 302 | 新增:+ | |
| 303 | 新增:+// ManageResources is an optional embedding hook. It starts after the driver and | |
| 304 | 新增:+// stops before it. Guest observations use the existing private SSH transport. | |
| 305 | 新增:+var ManageResources func(context.Context, string, *limatype.LimaYAML, driver.MemoryBalloon, func(context.Context, string) ([]byte, error)) func() | |
| 306 | 新增:+ | |
| 307 | 新增:+func (a *HostAgent) startResourceManager(ctx context.Context) func() { | |
| 308 | 新增:+ if ManageResources == nil { | |
| 309 | 新增:+ return func() {} | |
| 310 | 新增:+ } | |
| 311 | 新增:+ d := a.driver | |
| 312 | 新增:+ if configured, ok := d.(*driver.ConfiguredDriver); ok { | |
| 313 | 新增:+ d = configured.Driver | |
| 314 | 新增:+ } | |
| 315 | 新增:+ balloon, ok := d.(driver.MemoryBalloon) | |
| 316 | 新增:+ if !ok { | |
| 317 | 新增:+ return func() {} | |
| 318 | 新增:+ } | |
| 319 | 新增:+ read := func(ctx context.Context, script string) ([]byte, error) { | |
| 320 | 新增:+ args := append([]string{}, a.sshConfig.Args()...) | |
| 321 | 新增:+ args = append(args, "-o", "ConnectTimeout=2", "-o", "ClearAllForwardings=yes", "-T", "-p", strconv.Itoa(a.sshLocalPort), a.instSSHAddress, "--", script) | |
| 322 | 新增:+ cmd := exec.CommandContext(ctx, a.sshConfig.Binary(), args...) | |
| 323 | 新增:+ hideResourceProbe(cmd) | |
| 324 | 新增:+ cmd.WaitDelay = time.Second | |
| 325 | 新增:+ pipe, err := cmd.StdoutPipe() | |
| 326 | 新增:+ if err != nil { | |
| 327 | 新增:+ return nil, err | |
| 328 | 新增:+ } | |
| 329 | 新增:+ if err = cmd.Start(); err != nil { | |
| 330 | 新增:+ return nil, err | |
| 331 | 新增:+ } | |
| 332 | 新增:+ out, readErr := io.ReadAll(io.LimitReader(pipe, 16385)) | |
| 333 | 新增:+ if readErr != nil || len(out) > 16384 { | |
| 334 | 新增:+ _ = cmd.Process.Kill() | |
| 335 | 新增:+ _ = cmd.Wait() | |
| 336 | 新增:+ return nil, errors.New("resource observation exceeded its limit") | |
| 337 | 新增:+ } | |
| 338 | 新增:+ return out, cmd.Wait() | |
| 339 | 新增:+ } | |
| 340 | 新增:+ stop := ManageResources(ctx, a.instDir, a.instConfig, balloon, read) | |
| 341 | 新增:+ var once sync.Once | |
| 342 | 新增:+ return func() { once.Do(stop) } | |
| 343 | 新增:+} | |
| 344 | 新增:diff --git a/pkg/hostagent/resources_unix.go b/pkg/hostagent/resources_unix.go | |
| 345 | 新增:new file mode 100644 | |
| 346 | 新增:index 0000000..7f2affb | |
| 347 | 新增:--- /dev/null | |
| 348 | 新增:+++ b/pkg/hostagent/resources_unix.go | |
| 349 | 新增:@@ -0,0 +1,10 @@ | |
| 350 | 新增:+//go:build !windows | |
| 351 | 新增:+ | |
| 352 | 新增:+// SPDX-FileCopyrightText: Copyright The Lima Authors | |
| 353 | 新增:+// SPDX-License-Identifier: Apache-2.0 | |
| 354 | 新增:+ | |
| 355 | 新增:+package hostagent | |
| 356 | 新增:+ | |
| 357 | 新增:+import "os/exec" | |
| 358 | 新增:+ | |
| 359 | 新增:+func hideResourceProbe(*exec.Cmd) {} | |
| 360 | 新增:diff --git a/pkg/hostagent/resources_windows.go b/pkg/hostagent/resources_windows.go | |
| 361 | 新增:new file mode 100644 | |
| 362 | 新增:index 0000000..e403dbe | |
| 363 | 新增:--- /dev/null | |
| 364 | 新增:+++ b/pkg/hostagent/resources_windows.go | |
| 365 | 新增:@@ -0,0 +1,13 @@ | |
| 366 | 新增:+// SPDX-FileCopyrightText: Copyright The Lima Authors | |
| 367 | 新增:+// SPDX-License-Identifier: Apache-2.0 | |
| 368 | 新增:+ | |
| 369 | 新增:+package hostagent | |
| 370 | 新增:+ | |
| 371 | 新增:+import ( | |
| 372 | 新增:+ "os/exec" | |
| 373 | 新增:+ "syscall" | |
| 374 | 新增:+) | |
| 375 | 新增:+ | |
| 376 | 新增:+func hideResourceProbe(cmd *exec.Cmd) { | |
| 377 | 新增:+ cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true, CreationFlags: 0x08000000} | |
| 378 | 新增:+} | |
| @@ -37,7 +37,7 @@ install_stage='' | ||
| 37 | 37 | trap 'rm -rf "$build_stage"; if [[ -n "$install_stage" ]]; then rm -rf "$install_stage"; fi' EXIT |
| 38 | 38 | bundle="$build_stage/Cage.app" |
| 39 | 39 | mkdir -p "$bundle/Contents/MacOS" "$bundle/Contents/Resources" |
| 40 | 删除:swiftc -O -target "$(uname -m)-apple-macosx14.0" -parse-as-library -framework Cocoa -framework WebKit -framework Security -framework LocalAuthentication desktop/Cage.swift desktop/Updates.swift desktop/AccountDevice.swift -o "$bundle/Contents/MacOS/Cage" | |
| 40 | 新增:swiftc -O -target "$(uname -m)-apple-macosx14.0" -parse-as-library -framework Cocoa -framework WebKit -framework Security -framework LocalAuthentication desktop/Cage.swift desktop/NativeInput.swift desktop/Updates.swift desktop/AccountDevice.swift -o "$bundle/Contents/MacOS/Cage" | |
| 41 | 41 | swiftc -O -target "$(uname -m)-apple-macosx14.0" -parse-as-library -framework Cocoa -framework Security desktop/Updates.swift desktop/UpdateInstaller.swift -o "$bundle/Contents/Resources/CageUpdateInstaller" |
| 42 | 42 | cp _output/bin/cage "$bundle/Contents/Resources/cage" |
| 43 | 43 | cp _output/proxy-core/mihomo "$bundle/Contents/Resources/mihomo" |
| @@ -0,0 +1,12 @@ | ||
| 1 | 新增:// SPDX-FileCopyrightText: Copyright The Lima Authors | |
| 2 | 新增:// SPDX-License-Identifier: Apache-2.0 | |
| 3 | 新增: | |
| 4 | 新增:package driver | |
| 5 | 新增: | |
| 6 | 新增:import "context" | |
| 7 | 新增: | |
| 8 | 新增:// MemoryBalloon adjusts guest memory within the configured boot capacity. | |
| 9 | 新增:// Acceptance is asynchronous; callers must observe the guest before reclaiming more. | |
| 10 | 新增:type MemoryBalloon interface { | |
| 11 | 新增: SetMemoryTarget(context.Context, uint64) error | |
| 12 | 新增:} | |
| @@ -0,0 +1,81 @@ | ||
| 1 | 新增:// SPDX-FileCopyrightText: Copyright The Lima Authors | |
| 2 | 新增:// SPDX-License-Identifier: Apache-2.0 | |
| 3 | 新增: | |
| 4 | 新增:package qemu | |
| 5 | 新增: | |
| 6 | 新增:import ( | |
| 7 | 新增: "context" | |
| 8 | 新增: "encoding/json" | |
| 9 | 新增: "errors" | |
| 10 | 新增: "fmt" | |
| 11 | 新增: "io" | |
| 12 | 新增: "net" | |
| 13 | 新增: "path/filepath" | |
| 14 | 新增: "time" | |
| 15 | 新增: | |
| 16 | 新增: "github.com/docker/go-units" | |
| 17 | 新增: "github.com/lima-vm/lima/v2/pkg/limatype/filenames" | |
| 18 | 新增:) | |
| 19 | 新增: | |
| 20 | 新增:func (l *LimaQemuDriver) SetMemoryTarget(ctx context.Context, target uint64) error { | |
| 21 | 新增: if err := ctx.Err(); err != nil { | |
| 22 | 新增: return err | |
| 23 | 新增: } | |
| 24 | 新增: maximum, err := units.RAMInBytes(*l.Instance.Config.Memory) | |
| 25 | 新增: if err != nil { | |
| 26 | 新增: return err | |
| 27 | 新增: } | |
| 28 | 新增: if target < 512<<20 || target > uint64(maximum) || target%(1<<20) != 0 { | |
| 29 | 新增: return errors.New("memory target is outside the VM capacity") | |
| 30 | 新增: } | |
| 31 | 新增: ctx, cancel := context.WithTimeout(ctx, 3*time.Second) | |
| 32 | 新增: defer cancel() | |
| 33 | 新增: conn, err := (&net.Dialer{}).DialContext(ctx, "unix", filepath.Join(l.Instance.Dir, filenames.QMPSock)) | |
| 34 | 新增: if err != nil { | |
| 35 | 新增: return err | |
| 36 | 新增: } | |
| 37 | 新增: defer conn.Close() | |
| 38 | 新增: stop := context.AfterFunc(ctx, func() { _ = conn.Close() }) | |
| 39 | 新增: defer stop() | |
| 40 | 新增: deadline, _ := ctx.Deadline() | |
| 41 | 新增: if err := conn.SetDeadline(deadline); err != nil { | |
| 42 | 新增: return err | |
| 43 | 新增: } | |
| 44 | 新增: decoder := json.NewDecoder(io.LimitReader(conn, 64<<10)) | |
| 45 | 新增: var greeting map[string]json.RawMessage | |
| 46 | 新增: if err := decoder.Decode(&greeting); err != nil { | |
| 47 | 新增: return err | |
| 48 | 新增: } | |
| 49 | 新增: if greeting["QMP"] == nil { | |
| 50 | 新增: return errors.New("invalid QMP greeting") | |
| 51 | 新增: } | |
| 52 | 新增: encoder := json.NewEncoder(conn) | |
| 53 | 新增: for i, command := range []string{"qmp_capabilities", "balloon"} { | |
| 54 | 新增: request := map[string]any{"execute": command, "id": i + 1} | |
| 55 | 新增: if command == "balloon" { | |
| 56 | 新增: request["arguments"] = map[string]uint64{"value": target} | |
| 57 | 新增: } | |
| 58 | 新增: if err := encoder.Encode(request); err != nil { | |
| 59 | 新增: return err | |
| 60 | 新增: } | |
| 61 | 新增: for { | |
| 62 | 新增: var response struct { | |
| 63 | 新增: ID int `json:"id"` | |
| 64 | 新增: Error *struct { | |
| 65 | 新增: Class string `json:"class"` | |
| 66 | 新增: } `json:"error"` | |
| 67 | 新增: } | |
| 68 | 新增: if err := decoder.Decode(&response); err != nil { | |
| 69 | 新增: return err | |
| 70 | 新增: } | |
| 71 | 新增: if response.ID != i+1 { | |
| 72 | 新增: continue | |
| 73 | 新增: } | |
| 74 | 新增: if response.Error != nil { | |
| 75 | 新增: return fmt.Errorf("QMP memory adjustment failed: %s", response.Error.Class) | |
| 76 | 新增: } | |
| 77 | 新增: break | |
| 78 | 新增: } | |
| 79 | 新增: } | |
| 80 | 新增: return nil | |
| 81 | 新增:} | |
| @@ -0,0 +1,89 @@ | ||
| 1 | 新增:// SPDX-FileCopyrightText: Copyright The Lima Authors | |
| 2 | 新增:// SPDX-License-Identifier: Apache-2.0 | |
| 3 | 新增: | |
| 4 | 新增:package qemu | |
| 5 | 新增: | |
| 6 | 新增:import ( | |
| 7 | 新增: "context" | |
| 8 | 新增: "encoding/json" | |
| 9 | 新增: "net" | |
| 10 | 新增: "os" | |
| 11 | 新增: "path/filepath" | |
| 12 | 新增: "testing" | |
| 13 | 新增: "time" | |
| 14 | 新增: | |
| 15 | 新增: "github.com/lima-vm/lima/v2/pkg/limatype" | |
| 16 | 新增: "github.com/lima-vm/lima/v2/pkg/limatype/filenames" | |
| 17 | 新增:) | |
| 18 | 新增: | |
| 19 | 新增:func TestMemoryTargetQMPProtocolAndCancellation(t *testing.T) { | |
| 20 | 新增: for _, stall := range []bool{false, true} { | |
| 21 | 新增: t.Run(map[bool]string{false: "command", true: "cancelled"}[stall], func(t *testing.T) { | |
| 22 | 新增: dir, err := os.MkdirTemp("", "cqm-") | |
| 23 | 新增: if err != nil { | |
| 24 | 新增: t.Fatal(err) | |
| 25 | 新增: } | |
| 26 | 新增: defer os.RemoveAll(dir) | |
| 27 | 新增: memory := "4GiB" | |
| 28 | 新增: l := &LimaQemuDriver{Instance: &limatype.Instance{Dir: dir, Config: &limatype.LimaYAML{Memory: &memory}}} | |
| 29 | 新增: listener, err := net.Listen("unix", filepath.Join(dir, filenames.QMPSock)) | |
| 30 | 新增: if err != nil { | |
| 31 | 新增: t.Fatal(err) | |
| 32 | 新增: } | |
| 33 | 新增: defer listener.Close() | |
| 34 | 新增: done := make(chan error, 1) | |
| 35 | 新增: go func() { | |
| 36 | 新增: conn, e := listener.Accept() | |
| 37 | 新增: if e != nil { | |
| 38 | 新增: done <- e | |
| 39 | 新增: return | |
| 40 | 新增: } | |
| 41 | 新增: defer conn.Close() | |
| 42 | 新增: _ = conn.SetDeadline(time.Now().Add(time.Second)) | |
| 43 | 新增: if stall { | |
| 44 | 新增: var b [1]byte | |
| 45 | 新增: _, e = conn.Read(b[:]) | |
| 46 | 新增: done <- e | |
| 47 | 新增: return | |
| 48 | 新增: } | |
| 49 | 新增: enc, dec := json.NewEncoder(conn), json.NewDecoder(conn) | |
| 50 | 新增: _ = enc.Encode(map[string]any{"QMP": map[string]any{}}) | |
| 51 | 新增: for i := 1; i <= 2; i++ { | |
| 52 | 新增: var request struct { | |
| 53 | 新增: ID int `json:"id"` | |
| 54 | 新增: Execute string `json:"execute"` | |
| 55 | 新增: Arguments struct { | |
| 56 | 新增: Value uint64 `json:"value"` | |
| 57 | 新增: } `json:"arguments"` | |
| 58 | 新增: } | |
| 59 | 新增: if e = dec.Decode(&request); e != nil { | |
| 60 | 新增: done <- e | |
| 61 | 新增: return | |
| 62 | 新增: } | |
| 63 | 新增: if request.ID != i || (i == 1 && request.Execute != "qmp_capabilities") || (i == 2 && (request.Execute != "balloon" || request.Arguments.Value != 2<<30)) { | |
| 64 | 新增: t.Error("wrong QMP request", request) | |
| 65 | 新增: } | |
| 66 | 新增: _ = enc.Encode(map[string]any{"event": "BALLOON_CHANGE"}) | |
| 67 | 新增: _ = enc.Encode(map[string]any{"id": i, "return": map[string]any{}}) | |
| 68 | 新增: } | |
| 69 | 新增: done <- nil | |
| 70 | 新增: }() | |
| 71 | 新增: ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) | |
| 72 | 新增: defer cancel() | |
| 73 | 新增: started := time.Now() | |
| 74 | 新增: err = l.SetMemoryTarget(ctx, 2<<30) | |
| 75 | 新增: if (err != nil) != stall { | |
| 76 | 新增: t.Fatal("unexpected command result", err) | |
| 77 | 新增: } | |
| 78 | 新增: if time.Since(started) > time.Second { | |
| 79 | 新增: t.Fatal("deadline ignored") | |
| 80 | 新增: } | |
| 81 | 新增: if e := <-done; e != nil && !stall { | |
| 82 | 新增: t.Fatal(e) | |
| 83 | 新增: } | |
| 84 | 新增: if err := l.SetMemoryTarget(context.Background(), 5<<30); err == nil { | |
| 85 | 新增: t.Fatal("capacity exceeded") | |
| 86 | 新增: } | |
| 87 | 新增: }) | |
| 88 | 新增: } | |
| 89 | 新增:} | |
| @@ -525,6 +525,10 @@ func Cmdline(ctx context.Context, cfg Config) (exe string, args []string, err er | ||
| 525 | 525 | } |
| 526 | 526 | memBytes = adjustMemBytesDarwinARM64HVF(memBytes, accel) |
| 527 | 527 | args = appendArgsIfNoConflict(args, "-m", strconv.Itoa(int(memBytes>>20))) |
| 528 | 新增: // A balloon returns guest pages to the host without restarting the VM. | |
| 529 | 新增: if *y.OS == limatype.LINUX { | |
| 530 | 新增: args = append(args, "-device", "virtio-balloon") | |
| 531 | 新增: } | |
| 528 | 532 | |
| 529 | 533 | if *y.MountType == limatype.VIRTIOFS { |
| 530 | 534 | args = appendArgsIfNoConflict(args, "-object", |
| @@ -0,0 +1,43 @@ | ||
| 1 | 新增://go:build darwin && !no_vz | |
| 2 | 新增: | |
| 3 | 新增:// SPDX-FileCopyrightText: Copyright The Lima Authors | |
| 4 | 新增:// SPDX-License-Identifier: Apache-2.0 | |
| 5 | 新增: | |
| 6 | 新增:package vz | |
| 7 | 新增: | |
| 8 | 新增:import ( | |
| 9 | 新增: "context" | |
| 10 | 新增: "errors" | |
| 11 | 新增: "runtime" | |
| 12 | 新增: | |
| 13 | 新增: "github.com/Code-Hex/vz/v3" | |
| 14 | 新增: "github.com/docker/go-units" | |
| 15 | 新增:) | |
| 16 | 新增: | |
| 17 | 新增:func (l *LimaVzDriver) SetMemoryTarget(ctx context.Context, target uint64) error { | |
| 18 | 新增: if err := ctx.Err(); err != nil { | |
| 19 | 新增: return err | |
| 20 | 新增: } | |
| 21 | 新增: maximum, err := units.RAMInBytes(*l.Instance.Config.Memory) | |
| 22 | 新增: if err != nil { | |
| 23 | 新增: return err | |
| 24 | 新增: } | |
| 25 | 新增: if target < 512<<20 || target > uint64(maximum) || target%(1<<20) != 0 { | |
| 26 | 新增: return errors.New("memory target is outside the VM capacity") | |
| 27 | 新增: } | |
| 28 | 新增: if l.machine == nil || l.machine.State() != vz.VirtualMachineStateRunning { | |
| 29 | 新增: return errors.New("VM is not running") | |
| 30 | 新增: } | |
| 31 | 新增: for _, device := range l.machine.MemoryBalloonDevices() { | |
| 32 | 新增: if balloon := vz.AsVirtioTraditionalMemoryBalloonDevice(device); balloon != nil { | |
| 33 | 新增: // go-vz v3.7.1 wraps a borrowed NSArray member without retaining it, | |
| 34 | 新增: // but installs a releasing finalizer. The VM owns this native device. | |
| 35 | 新增: // Do not let temporary wrappers release the VM's reference. | |
| 36 | 新增: runtime.SetFinalizer(balloon, nil) | |
| 37 | 新增: balloon.SetTargetVirtualMachineMemorySize(target) | |
| 38 | 新增: runtime.KeepAlive(l.machine) | |
| 39 | 新增: return nil | |
| 40 | 新增: } | |
| 41 | 新增: } | |
| 42 | 新增: return errors.New("memory balloon is unavailable") | |
| 43 | 新增:} | |
| @@ -448,6 +448,9 @@ func (a *HostAgent) Run(ctx context.Context) error { | ||
| 448 | 448 | if err := a.driver.AdditionalSetupForSSH(ctx); err != nil { |
| 449 | 449 | return err |
| 450 | 450 | } |
| 451 | 新增: stopResources := a.startResourceManager(ctx) | |
| 452 | 新增: defer stopResources() | |
| 453 | 新增: a.cleanUp(func() error { stopResources(); return nil }) | |
| 451 | 454 | |
| 452 | 455 | // WSL instance SSH address isn't known until after VM start |
| 453 | 456 | if a.driver.Info(ctx).Features.DynamicSSHAddress { |
| @@ -0,0 +1,59 @@ | ||
| 1 | 新增:// SPDX-FileCopyrightText: Copyright The Lima Authors | |
| 2 | 新增:// SPDX-License-Identifier: Apache-2.0 | |
| 3 | 新增: | |
| 4 | 新增:package hostagent | |
| 5 | 新增: | |
| 6 | 新增:import ( | |
| 7 | 新增: "context" | |
| 8 | 新增: "errors" | |
| 9 | 新增: "io" | |
| 10 | 新增: "os/exec" | |
| 11 | 新增: "strconv" | |
| 12 | 新增: "sync" | |
| 13 | 新增: "time" | |
| 14 | 新增: | |
| 15 | 新增: "github.com/lima-vm/lima/v2/pkg/driver" | |
| 16 | 新增: "github.com/lima-vm/lima/v2/pkg/limatype" | |
| 17 | 新增:) | |
| 18 | 新增: | |
| 19 | 新增:// ManageResources is an optional embedding hook. It starts after the driver and | |
| 20 | 新增:// stops before it. Guest observations use the existing private SSH transport. | |
| 21 | 新增:var ManageResources func(context.Context, string, *limatype.LimaYAML, driver.MemoryBalloon, func(context.Context, string) ([]byte, error)) func() | |
| 22 | 新增: | |
| 23 | 新增:func (a *HostAgent) startResourceManager(ctx context.Context) func() { | |
| 24 | 新增: if ManageResources == nil { | |
| 25 | 新增: return func() {} | |
| 26 | 新增: } | |
| 27 | 新增: d := a.driver | |
| 28 | 新增: if configured, ok := d.(*driver.ConfiguredDriver); ok { | |
| 29 | 新增: d = configured.Driver | |
| 30 | 新增: } | |
| 31 | 新增: balloon, ok := d.(driver.MemoryBalloon) | |
| 32 | 新增: if !ok { | |
| 33 | 新增: return func() {} | |
| 34 | 新增: } | |
| 35 | 新增: read := func(ctx context.Context, script string) ([]byte, error) { | |
| 36 | 新增: args := append([]string{}, a.sshConfig.Args()...) | |
| 37 | 新增: args = append(args, "-o", "ConnectTimeout=2", "-o", "ClearAllForwardings=yes", "-T", "-p", strconv.Itoa(a.sshLocalPort), a.instSSHAddress, "--", script) | |
| 38 | 新增: cmd := exec.CommandContext(ctx, a.sshConfig.Binary(), args...) | |
| 39 | 新增: hideResourceProbe(cmd) | |
| 40 | 新增: cmd.WaitDelay = time.Second | |
| 41 | 新增: pipe, err := cmd.StdoutPipe() | |
| 42 | 新增: if err != nil { | |
| 43 | 新增: return nil, err | |
| 44 | 新增: } | |
| 45 | 新增: if err = cmd.Start(); err != nil { | |
| 46 | 新增: return nil, err | |
| 47 | 新增: } | |
| 48 | 新增: out, readErr := io.ReadAll(io.LimitReader(pipe, 16385)) | |
| 49 | 新增: if readErr != nil || len(out) > 16384 { | |
| 50 | 新增: _ = cmd.Process.Kill() | |
| 51 | 新增: _ = cmd.Wait() | |
| 52 | 新增: return nil, errors.New("resource observation exceeded its limit") | |
| 53 | 新增: } | |
| 54 | 新增: return out, cmd.Wait() | |
| 55 | 新增: } | |
| 56 | 新增: stop := ManageResources(ctx, a.instDir, a.instConfig, balloon, read) | |
| 57 | 新增: var once sync.Once | |
| 58 | 新增: return func() { once.Do(stop) } | |
| 59 | 新增:} | |
| @@ -0,0 +1,10 @@ | ||
| 1 | 新增://go:build !windows | |
| 2 | 新增: | |
| 3 | 新增:// SPDX-FileCopyrightText: Copyright The Lima Authors | |
| 4 | 新增:// SPDX-License-Identifier: Apache-2.0 | |
| 5 | 新增: | |
| 6 | 新增:package hostagent | |
| 7 | 新增: | |
| 8 | 新增:import "os/exec" | |
| 9 | 新增: | |
| 10 | 新增:func hideResourceProbe(*exec.Cmd) {} | |
| @@ -0,0 +1,13 @@ | ||
| 1 | 新增:// SPDX-FileCopyrightText: Copyright The Lima Authors | |
| 2 | 新增:// SPDX-License-Identifier: Apache-2.0 | |
| 3 | 新增: | |
| 4 | 新增:package hostagent | |
| 5 | 新增: | |
| 6 | 新增:import ( | |
| 7 | 新增: "os/exec" | |
| 8 | 新增: "syscall" | |
| 9 | 新增:) | |
| 10 | 新增: | |
| 11 | 新增:func hideResourceProbe(cmd *exec.Cmd) { | |
| 12 | 新增: cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true, CreationFlags: 0x08000000} | |
| 13 | 新增:} | |
| @@ -1,12 +1,12 @@ | ||
| 1 | 1 | { |
| 2 | 2 | "name": "cage-workbench", |
| 3 | 删除: "version": "0.1.3-alpha.2", | |
| 3 | 新增: "version": "0.1.4-alpha", | |
| 4 | 4 | "lockfileVersion": 3, |
| 5 | 5 | "requires": true, |
| 6 | 6 | "packages": { |
| 7 | 7 | "": { |
| 8 | 8 | "name": "cage-workbench", |
| 9 | 删除: "version": "0.1.3-alpha.2", | |
| 9 | 新增: "version": "0.1.4-alpha", | |
| 10 | 10 | "dependencies": { |
| 11 | 11 | "@xterm/addon-fit": "0.11.0", |
| 12 | 12 | "@xterm/xterm": "6.0.0", |
| @@ -1,7 +1,7 @@ | ||
| 1 | 1 | { |
| 2 | 2 | "name": "cage-workbench", |
| 3 | 3 | "private": true, |
| 4 | 删除: "version": "0.1.3-alpha.2", | |
| 4 | 新增: "version": "0.1.4-alpha", | |
| 5 | 5 | "type": "module", |
| 6 | 6 | "scripts": { |
| 7 | 7 | "prepare-vnc": "node scripts/prepare-vnc.mjs", |
| @@ -0,0 +1,43 @@ | ||
| 1 | 新增:// Isolated UI test: notifications use the production SSE consumer, without | |
| 2 | 新增:// accessing the user's browser, login URL, or running desktop application. | |
| 3 | 新增:import assert from "node:assert/strict"; | |
| 4 | 新增:import { createWorkbench } from "./workbench-fixture.mjs"; | |
| 5 | 新增: | |
| 6 | 新增:const { browser, page, state, errors } = await createWorkbench(); | |
| 7 | 新增:try { | |
| 8 | 新增: await page.addInitScript(() => { | |
| 9 | 新增: window.EventSource = class { | |
| 10 | 新增: constructor() { | |
| 11 | 新增: window.testBrowserEvents = this; | |
| 12 | 新增: queueMicrotask(() => this.onopen?.()); | |
| 13 | 新增: } | |
| 14 | 新增: close() { if (window.testBrowserEvents === this) window.testBrowserEvents = null; } | |
| 15 | 新增: }; | |
| 16 | 新增: }); | |
| 17 | 新增: await page.route("**/api/claude-desktop", (route) => route.fulfill({ json: { | |
| 18 | 新增: installed: true, running: true, failed: false, managed: true, version: "fixture", | |
| 19 | 新增: } })); | |
| 20 | 新增: state.status.vm_running = true; | |
| 21 | 新增: state.status.ready = true; | |
| 22 | 新增: await page.reload(); | |
| 23 | 新增: await page.getByRole("button", { name: "打开浏览器", exact: true }).click(); | |
| 24 | 新增: await page.waitForFunction(() => Boolean(window.testBrowserEvents?.onmessage)); | |
| 25 | 新增: const notify = (desktopFocus) => page.evaluate((desktopFocus) => { | |
| 26 | 新增: window.testBrowserEvents.onmessage({ data: JSON.stringify({ | |
| 27 | 新增: tabs: [], active: "", downloads: [], uploads: [], desktopFocus, | |
| 28 | 新增: }) }); | |
| 29 | 新增: }, desktopFocus); | |
| 30 | 新增: await notify(true); | |
| 31 | 新增: await page.getByRole("region", { name: "Claude Desktop", exact: true }).waitFor(); | |
| 32 | 新增: await page.getByRole("button", { name: "关闭应用", exact: true }).waitFor(); | |
| 33 | 新增: assert.equal(state.requests.some((r) => r.path === "/claude-desktop/start"), false); | |
| 34 | 新增: await page.getByRole("button", { name: "打开浏览器", exact: true }).click(); | |
| 35 | 新增: await notify(false); | |
| 36 | 新增: await page.getByRole("region", { name: "Claude Desktop", exact: true }).waitFor({ state: "hidden" }); | |
| 37 | 新增: await notify(true); | |
| 38 | 新增: await page.getByRole("region", { name: "Claude Desktop", exact: true }).waitFor(); | |
| 39 | 新增: assert.deepEqual(errors, []); | |
| 40 | 新增: console.log("PASS: callback switches to the running desktop; ordinary snapshots do not reopen it; repeated callbacks work."); | |
| 41 | 新增:} finally { | |
| 42 | 新增: await browser.close(); | |
| 43 | 新增:} | |
| @@ -0,0 +1,40 @@ | ||
| 1 | 新增:import assert from "node:assert/strict"; | |
| 2 | 新增:import fs from "node:fs/promises"; | |
| 3 | 新增:import { createWorkbench } from "./workbench-fixture.mjs"; | |
| 4 | 新增: | |
| 5 | 新增:const output = new URL("../../docs/test-reports/2026-11-04-desktop-memory/", import.meta.url); | |
| 6 | 新增:await fs.mkdir(output, { recursive: true }); | |
| 7 | 新增:const { browser, page, state, errors } = await createWorkbench(); | |
| 8 | 新增:let unavailable = true; | |
| 9 | 新增:const desktop = { installed: true, running: false, failed: true, failure_reason: "oom-kill", version: "4.4212.0" }; | |
| 10 | 新增:await page.route("**/api/claude-desktop**", async route => { | |
| 11 | 新增: if (route.request().method() === "POST") { | |
| 12 | 新增: return route.fulfill({ status: 502, body: "测试:打开操作失败,请重试" }); | |
| 13 | 新增: } | |
| 14 | 新增: if (unavailable) return route.fulfill({ status: 502, body: "无法读取 Claude Desktop 状态,请重试" }); | |
| 15 | 新增: return route.fulfill({ json: desktop }); | |
| 16 | 新增:}); | |
| 17 | 新增:try { | |
| 18 | 新增: state.status.vm_running = true; | |
| 19 | 新增: state.status.ready = true; | |
| 20 | 新增: await page.reload(); | |
| 21 | 新增: await page.getByRole("button", { name: "Claude Desktop", exact: true }).click(); | |
| 22 | 新增: await page.getByRole("alert").filter({ hasText: "无法读取 Claude Desktop 状态" }).waitFor(); | |
| 23 | 新增: unavailable = false; | |
| 24 | 新增: await page.getByRole("button", { name: "刷新 Claude Desktop 状态", exact: true }).click(); | |
| 25 | 新增: await page.getByRole("alert").filter({ hasText: "环境内存不足" }).waitFor(); | |
| 26 | 新增: assert.equal(await page.getByText("无法读取 Claude Desktop 状态,请重试", { exact: true }).count(), 0); | |
| 27 | 新增: await page.screenshot({ path: new URL("oom-message.png", output).pathname }); | |
| 28 | 新增: desktop.failed = false; | |
| 29 | 新增: desktop.failure_reason = ""; | |
| 30 | 新增: await page.getByRole("button", { name: "刷新 Claude Desktop 状态", exact: true }).click(); | |
| 31 | 新增: await page.getByRole("alert").waitFor({ state: "hidden" }); | |
| 32 | 新增: await page.getByRole("button", { name: "打开 Claude Desktop", exact: true }).click(); | |
| 33 | 新增: await page.getByRole("alert").filter({ hasText: "打开操作失败" }).waitFor(); | |
| 34 | 新增: await page.getByRole("button", { name: "刷新 Claude Desktop 状态", exact: true }).click(); | |
| 35 | 新增: await page.getByRole("alert").filter({ hasText: "打开操作失败" }).waitFor(); | |
| 36 | 新增: assert.deepEqual(errors, []); | |
| 37 | 新增: const checks = ["status recovery clears stale read error", "OOM reason displayed", "healthy status clears OOM message", "status polling preserves failed user operation"]; | |
| 38 | 新增: await fs.writeFile(new URL("ui-checks.json", output), JSON.stringify({ complete: true, checks }, null, 2)); | |
| 39 | 新增: console.log(JSON.stringify({ complete: true, checks })); | |
| 40 | 新增:} finally { await browser.close(); } | |
| @@ -0,0 +1,68 @@ | ||
| 1 | 新增:import assert from "node:assert/strict"; | |
| 2 | 新增:import fs from "node:fs/promises"; | |
| 3 | 新增:import os from "node:os"; | |
| 4 | 新增:import path from "node:path"; | |
| 5 | 新增:import { execFile } from "node:child_process"; | |
| 6 | 新增:import { promisify } from "node:util"; | |
| 7 | 新增:import { createRequire } from "node:module"; | |
| 8 | 新增:const run = promisify(execFile); | |
| 9 | 新增:const cage = path.resolve(process.argv[2] || "_output/diagnostics-qa/cage-backend"); | |
| 10 | 新增:const require = createRequire(import.meta.url); | |
| 11 | 新增:const { chromium } = require(process.env.CAGE_PLAYWRIGHT_MODULE || "playwright"); | |
| 12 | 新增:const root = await fs.mkdtemp(path.join(os.tmpdir(), "cage-diagnostics-")); | |
| 13 | 新增:const profile = path.join(root, "profile"); | |
| 14 | 新增:const env = { ...process.env, CLAUDE_CAGE_CONFIG: path.join(profile, "config.json") }; | |
| 15 | 新增:let browser; | |
| 16 | 新增:const reportDirectory = path.resolve(process.env.CAGE_DIAGNOSTIC_REPORT || "docs/test-reports/2026-11-03-diagnostics"); | |
| 17 | 新增:await fs.mkdir(reportDirectory, { recursive: true }); | |
| 18 | 新增:try { | |
| 19 | 新增: const { stdout } = await run(cage, ["desktop", "--json"], { env }); | |
| 20 | 新增: const entry = JSON.parse(stdout); | |
| 21 | 新增: assert.equal(entry.status, "ready"); | |
| 22 | 新增: browser = await chromium.launch({ headless: true }); | |
| 23 | 新增: const page = await browser.newPage({ acceptDownloads: true, viewport: { width: 1280, height: 900 } }); | |
| 24 | 新增: await page.goto(entry.url); | |
| 25 | 新增: await page.getByLabel("用户名", { exact: true }).fill("诊断验证账户"); | |
| 26 | 新增: await page.getByLabel("设置密码", { exact: true }).fill("Test-only-password-8712"); | |
| 27 | 新增: await page.getByLabel("确认密码", { exact: true }).fill("Test-only-password-8712"); | |
| 28 | 新增: await page.getByRole("button", { name: "创建本地账户", exact: true }).click(); | |
| 29 | 新增: await page.getByRole("button", { name: "设置", exact: true }).click(); | |
| 30 | 新增: await page.getByRole("button", { name: "环境与恢复", exact: true }).click(); | |
| 31 | 新增: await page.getByRole("heading", { name: "日志与诊断" }).waitFor(); | |
| 32 | 新增: // Exercise browser event handlers, the actual authenticated endpoint and disk. | |
| 33 | 新增: await page.evaluate(() => { | |
| 34 | 新增: window.dispatchEvent(new ErrorEvent("error", { error: new Error("password=ui-private-secret diagnostic-ui-sentinel") })); | |
| 35 | 新增: window.dispatchEvent(new PromiseRejectionEvent("unhandledrejection", { promise: Promise.resolve(), reason: new Error("token=rejection-secret diagnostic-rejection-sentinel") })); | |
| 36 | 新增: }); | |
| 37 | 新增: await page.waitForResponse(response => response.url().endsWith("/api/diagnostics/events") && response.ok()); | |
| 38 | 新增: const downloaded = page.waitForEvent("download"); | |
| 39 | 新增: await page.getByRole("button", { name: "导出诊断包", exact: true }).click(); | |
| 40 | 新增: await (await downloaded).saveAs(path.join(root, "browser.zip")); | |
| 41 | 新增: await page.getByRole("status").filter({ hasText: "诊断包已下载" }).waitFor(); | |
| 42 | 新增: await page.screenshot({ path: path.join(reportDirectory, "settings.png") }); | |
| 43 | 新增: // Native hosts use the same CLI command after their save picker completes. | |
| 44 | 新增: const nativeOutput = path.join(root, "native.zip"); | |
| 45 | 新增: const saved = await run(cage, ["diagnostics", "--json", nativeOutput], { env }); | |
| 46 | 新增: assert.equal(JSON.parse(saved.stdout).status, "ok"); | |
| 47 | 新增: const checks = []; | |
| 48 | 新增: for (const filename of ["browser.zip", "native.zip"]) { | |
| 49 | 新增: const { stdout: contents } = await run("uv", ["run", "--no-project", "python", "-c", "import sys,zipfile,json; z=zipfile.ZipFile(sys.argv[1]); print(json.dumps({'names':z.namelist(),'text':'\\n'.join(z.read(n).decode() for n in z.namelist())}))", path.join(root, filename)]); | |
| 50 | 新增: const parsed = JSON.parse(contents); | |
| 51 | 新增: assert.match(parsed.text, /diagnostic-ui-sentinel/); | |
| 52 | 新增: assert.match(parsed.text, /diagnostic-rejection-sentinel/); | |
| 53 | 新增: for (const secret of ["ui-private-secret", "rejection-secret", "Test-only-password-8712"]) assert.ok(!parsed.text.includes(secret), `secret in ${filename}`); | |
| 54 | 新增: assert.ok(parsed.names.every(name => ["manifest.json", "README.txt"].includes(name) || name.startsWith("logs/"))); | |
| 55 | 新增: checks.push(`${filename}: valid redacted ZIP`); | |
| 56 | 新增: } | |
| 57 | 新增: // Stop only this isolated controller, then verify offline recovery export. | |
| 58 | 新增: await run(cage, ["prepare-update", "--json"], { env }); | |
| 59 | 新增: const offline = await run(cage, ["diagnostics", "--json", path.join(root, "offline.zip")], { env }); | |
| 60 | 新增: assert.equal(JSON.parse(offline.stdout).status, "ok"); | |
| 61 | 新增: checks.push("real browser settings export", "frontend error and rejection captured", "offline CLI export", "no user files/config/terminal content"); | |
| 62 | 新增: await fs.writeFile(path.join(reportDirectory, "browser-result.json"), JSON.stringify({ success: true, checks }, null, 2)); | |
| 63 | 新增: console.log(JSON.stringify({ success: true, checks })); | |
| 64 | 新增:} finally { | |
| 65 | 新增: await browser?.close(); | |
| 66 | 新增: await run(cage, ["prepare-update", "--json"], { env }).catch(() => {}); | |
| 67 | 新增: await fs.rm(root, { recursive: true, force: true }); | |
| 68 | 新增:} | |
| @@ -35,6 +35,7 @@ try { | ||
| 35 | 35 | "_cageSendKey", |
| 36 | 36 | "_cageQueueInput", |
| 37 | 37 | "_handleKeyEvent", |
| 38 | 新增: "_handleServerFenceMsg", | |
| 38 | 39 | "cageSetKeyboardTarget", |
| 39 | 40 | "focus", |
| 40 | 41 | "blur", |
| @@ -61,6 +62,9 @@ try { | ||
| 61 | 62 | value & 255, |
| 62 | 63 | ); |
| 63 | 64 | }, |
| 65 | 新增: sQpushString(value) { | |
| 66 | 新增: bytes.push(...new TextEncoder().encode(value)); | |
| 67 | 新增: }, | |
| 64 | 68 | flush() { |
| 65 | 69 | packets.push(bytes); |
| 66 | 70 | bytes = []; |
| @@ -84,18 +88,53 @@ try { | ||
| 84 | 88 | rfb, |
| 85 | 89 | packets, |
| 86 | 90 | texts, |
| 91 | 新增: compositions: [], | |
| 87 | 92 | input: install(), |
| 88 | 93 | install, |
| 94 | 新增: installComposition() { | |
| 95 | 新增: this.input.dispose(); | |
| 96 | 新增: options.tabId = () => "tab-1"; | |
| 97 | 新增: options.caretRect = async () => ({ available: true, context: "a".repeat(32), rect: [240, 120, 0, 24] }); | |
| 98 | 新增: options.insertComposition = (id, value) => rfb._cageQueueInput(async () => { | |
| 99 | 新增: this.compositions.push({ id, ...value }); | |
| 100 | 新增: if (value.mode === "commit") await new Promise(resolve => { this.finishComposition = resolve; }); | |
| 101 | 新增: }); | |
| 102 | 新增: const canvas = rfb._canvas; | |
| 103 | 新增: canvas.width = 1000; canvas.height = 500; | |
| 104 | 新增: canvas.style.cssText = "width:500px;height:250px;margin:40px"; | |
| 105 | 新增: this.input = install(); | |
| 106 | 新增: rfb.focus(); | |
| 107 | 新增: }, | |
| 108 | 新增: installNative() { | |
| 109 | 新增: this.input.dispose(); | |
| 110 | 新增: this.compositions.length = 0; | |
| 111 | 新增: this.nativeRequests = []; | |
| 112 | 新增: window.cageNativeIMEAvailable = true; | |
| 113 | 新增: window.webkit = { messageHandlers: { cage: { postMessage: async value => { | |
| 114 | 新增: this.nativeRequests.push(value); return true; | |
| 115 | 新增: } } } }; | |
| 116 | 新增: options.insertComposition = (id, value) => rfb._cageQueueInput(() => { this.compositions.push({ id, ...value }); }); | |
| 117 | 新增: this.input = install(); rfb.focus(); | |
| 118 | 新增: }, | |
| 89 | 119 | setActive: (value) => { |
| 90 | 120 | active = value; |
| 91 | 121 | }, |
| 122 | 新增: fence(payload) { | |
| 123 | 新增: const bytes = [0, 0, 0, 0, 0, 0, 0, payload.length, ...new TextEncoder().encode(payload)]; | |
| 124 | 新增: rfb._sock.rQwait = () => false; | |
| 125 | 新增: rfb._sock.rQskipBytes = (length) => bytes.splice(0, length); | |
| 126 | 新增: rfb._sock.rQshift32 = () => bytes.splice(0, 4).reduce((value, byte) => (value << 8) | byte, 0); | |
| 127 | 新增: rfb._sock.rQshift8 = () => bytes.shift(); | |
| 128 | 新增: rfb._sock.rQshiftStr = (length) => String.fromCharCode(...bytes.splice(0, length)); | |
| 129 | 新增: rfb._handleServerFenceMsg(); | |
| 130 | 新增: }, | |
| 92 | 131 | }; |
| 93 | 132 | rfb.focus(); |
| 94 | 133 | }); |
| 95 | 134 | const target = page.getByLabel("Cage 网页输入"); |
| 96 | 135 | const keys = () => |
| 97 | 136 | page.evaluate(() => |
| 98 | 删除: probe.packets.map((p) => { | |
| 137 | 新增: probe.packets.filter(p => p[0] !== 248).map((p) => { | |
| 99 | 138 | if (p.length !== 8 || p[0] !== 4) |
| 100 | 139 | throw new Error("Unexpected RFB key packet"); |
| 101 | 140 | return { |
| @@ -137,9 +176,31 @@ try { | ||
| 137 | 176 | ); |
| 138 | 177 | assert.equal(await target.inputValue(), ""); |
| 139 | 178 | await clear(); |
| 179 | 新增: await page.keyboard.down("Shift"); | |
| 180 | 新增: await page.evaluate(() => { | |
| 181 | 新增: probe.rfb._cagePasteJob = { id: "punctuation", phase: "fence", timer: setTimeout(() => {}, 1000), resolve() {} }; | |
| 182 | 新增: probe.fence("punctuation"); | |
| 183 | 新增: probe.fence("punctuation-keys"); | |
| 184 | 新增: }); | |
| 185 | 新增: await page.keyboard.up("Shift"); | |
| 186 | 新增: assert.deepEqual((await keys()).map(({ sym, down }) => [sym, down]), [ | |
| 187 | 新增: [0xffe1, 1], [0xffe1, 0], [0xffe3, 1], [0x76, 1], [0x76, 0], [0xffe3, 0], [0xffe1, 1], [0xffe1, 0], | |
| 188 | 新增: ], "Desktop text commit releases held Shift for Ctrl+V and restores it before the host release"); | |
| 189 | 新增: await clear(); | |
| 140 | 190 | // Exercise Chromium's composition implementation as well as the explicit |
| 141 | 191 | // cross-engine event sequences below. This still does not use macOS Pinyin. |
| 142 | 192 | const cdp = await page.context().newCDPSession(page); |
| 193 | 新增: for (const character of ["?", "?", ",", "。", "!"]) { | |
| 194 | 新增: await cdp.send("Input.dispatchKeyEvent", { type: "keyDown", key: character, code: "Slash", text: character }); | |
| 195 | 新增: await cdp.send("Input.dispatchKeyEvent", { type: "keyUp", key: character, code: "Slash" }); | |
| 196 | 新增: } | |
| 197 | 新增: assert.deepEqual(await texts(), ["?", "?", ",", "。", "!"]); | |
| 198 | 新增: assert.deepEqual(await keys(), [], "fullwidth punctuation must bypass X11 keysyms"); | |
| 199 | 新增: await clear(); | |
| 200 | 新增: await page.keyboard.press("Shift+?"); | |
| 201 | 新增: assert.deepEqual(await texts(), ["?"]); | |
| 202 | 新增: assert.deepEqual((await keys()).map(({ sym }) => sym), [0xffe1, 0xffe1], "only Shift is sent as a physical key"); | |
| 203 | 新增: await clear(); | |
| 143 | 204 | await cdp.send("Input.imeSetComposition", { |
| 144 | 205 | text: "nihao", |
| 145 | 206 | selectionStart: 5, |
| @@ -267,6 +328,47 @@ try { | ||
| 267 | 328 | [98], |
| 268 | 329 | ); |
| 269 | 330 | await clear(); |
| 331 | 新增: await page.evaluate(() => probe.installComposition()); | |
| 332 | 新增: await page.waitForFunction(() => { | |
| 333 | 新增: const box = probe.rfb._canvas.getBoundingClientRect(); | |
| 334 | 新增: return document.activeElement.style.left === `${box.left + 120}px`; | |
| 335 | 新增: }); | |
| 336 | 新增: const nativeCDP = await page.context().newCDPSession(page); | |
| 337 | 新增: await nativeCDP.send("Input.imeSetComposition", { text: "ni'hao", selectionStart: 6, selectionEnd: 6 }); | |
| 338 | 新增: await nativeCDP.send("Input.insertText", { text: "你好?" }); | |
| 339 | 新增: await page.waitForFunction(() => !!probe.finishComposition); | |
| 340 | 新增: await page.keyboard.press("Enter"); | |
| 341 | 新增: assert.deepEqual(await keys(), [], "Enter must wait behind the native composition commit"); | |
| 342 | 新增: const nativeMessages = await page.evaluate(() => probe.compositions); | |
| 343 | 新增: assert.equal(nativeMessages[0].mode, "begin"); | |
| 344 | 新增: assert.equal(nativeMessages.at(-1).mode, "commit"); | |
| 345 | 新增: assert.ok(nativeMessages.slice(1, -1).every(({ mode }) => mode === "update")); | |
| 346 | 新增: assert.ok(nativeMessages.some(({ text }) => text === "ni'hao")); | |
| 347 | 新增: assert.equal(nativeMessages.at(-1).text, "你好?"); | |
| 348 | 新增: assert.equal(new Set(nativeMessages.map(({ session }) => session)).size, 1); | |
| 349 | 新增: await page.evaluate(() => probe.finishComposition()); | |
| 350 | 新增: assert.deepEqual((await keys()).map(({ sym }) => sym), [0xff0d, 0xff0d]); | |
| 351 | 新增: await nativeCDP.detach(); | |
| 352 | 新增: await clear(); | |
| 353 | 新增: await page.evaluate(() => probe.installNative()); | |
| 354 | 新增: await page.waitForFunction(() => probe.nativeRequests.some(value => value.operation === "activate")); | |
| 355 | 新增: await page.evaluate(() => { | |
| 356 | 新增: const owner = probe.nativeRequests.find(value => value.operation === "activate").owner; | |
| 357 | 新增: const emit = value => window.dispatchEvent(new CustomEvent("cage-native-input", { detail: { owner, ...value } })); | |
| 358 | 新增: emit({kind:"compositionstart"}); | |
| 359 | 新增: emit({kind:"compositionupdate",text:"ni'hao",selectionStart:3,selectionEnd:6}); | |
| 360 | 新增: emit({kind:"compositionend",text:"你好"}); | |
| 361 | 新增: emit({kind:"input",text:"?"}); | |
| 362 | 新增: emit({kind:"keydown",key:"?",code:"Slash",textKey:true}); | |
| 363 | 新增: emit({kind:"keyup",key:"?",code:"Slash"}); | |
| 364 | 新增: window.dispatchEvent(new CustomEvent("cage-native-input", {detail:{owner:"stale",kind:"input",text:"误写"}})); | |
| 365 | 新增: }); | |
| 366 | 新增: assert.deepEqual((await page.evaluate(() => probe.compositions)).map(({mode})=>mode), ["begin","update","commit"]); | |
| 367 | 新增: assert.deepEqual(await texts(), ["?"], "native direct punctuation is committed exactly once"); | |
| 368 | 新增: assert.deepEqual((await keys()).map(({sym})=>sym), [63,63], "native ASCII punctuation keeps the key path without needing a DOM default action"); | |
| 369 | 新增: await page.getByLabel("本机地址栏").focus(); | |
| 370 | 新增: await page.waitForFunction(() => probe.nativeRequests.some(value => value.operation === "deactivate")); | |
| 371 | 新增: await clear(); | |
| 270 | 372 | await page.evaluate(() => { |
| 271 | 373 | const oldTarget = document.activeElement; |
| 272 | 374 | probe.input.dispose(); |
| @@ -289,6 +391,13 @@ try { | ||
| 289 | 391 | checks: [ |
| 290 | 392 | "real noVNC keyboard and RFB encoding", |
| 291 | 393 | "English input", |
| 394 | 新增: "fullwidth question mark and punctuation", | |
| 395 | 新增: "English question mark and modifier release", | |
| 396 | 新增: "Desktop paste while Shift is held", | |
| 397 | 新增: "shared composition begin, preedit and commit order", | |
| 398 | 新增: "candidate anchor maps the actual canvas bounds", | |
| 399 | 新增: "native host composition, punctuation and stale owner rejection", | |
| 400 | 新增: "native focus returns to local inputs", | |
| 292 | 401 | "Chromium IME engine commit", |
| 293 | 402 | "composition default action", |
| 294 | 403 | "candidate suppression", |
| @@ -1,3 +1,4 @@ | ||
| 1 | 新增:import { reportDiagnostic } from "./diagnostics.mjs"; | |
| 1 | 2 | let sessionRenewal; |
| 2 | 3 | async function responseError(response) { |
| 3 | 4 | const error = new Error( |
| @@ -33,12 +34,16 @@ export async function api(path, body, method) { | ||
| 33 | 34 | headers: body === undefined ? {} : { "Content-Type": "application/json" }, |
| 34 | 35 | body: body === undefined ? undefined : JSON.stringify(body), |
| 35 | 36 | }; |
| 36 | 删除: let response = await fetch("/api" + path, options); | |
| 37 | 新增: const send = async () => { | |
| 38 | 新增: try { return await fetch("/api" + path, options); } | |
| 39 | 新增: catch (error) { reportDiagnostic("frontend", error); throw error; } | |
| 40 | 新增: }; | |
| 41 | 新增: let response = await send(); | |
| 37 | 42 | // Authentication fails before a handler runs, so retrying this rejected |
| 38 | 43 | // request once does not repeat an accepted mutation. |
| 39 | 44 | if (response.status === 401 && path !== "/session" && nativeAvailable()) { |
| 40 | 45 | await renewSession(); |
| 41 | 删除: response = await fetch("/api" + path, options); | |
| 46 | 新增: response = await send(); | |
| 42 | 47 | } |
| 43 | 48 | if (response.status === 423) window.dispatchEvent(new Event("cage-account-locked")); |
| 44 | 49 | if (!response.ok) throw await responseError(response); |
| @@ -82,7 +87,8 @@ export async function native(action, extra = {}) { | ||
| 82 | 87 | try { await api("/account/suspend", {}); } |
| 83 | 88 | catch (error) { if (error.status !== 423) throw error; } |
| 84 | 89 | } |
| 85 | 删除: return window.webkit.messageHandlers.cage.postMessage({ action, ...extra }); | |
| 90 | 新增: try { return await window.webkit.messageHandlers.cage.postMessage({ action, ...extra }); } | |
| 91 | 新增: catch (error) { reportDiagnostic("frontend", error); throw error; } | |
| 86 | 92 | } |
| 87 | 93 | export const readClipboard = () => |
| 88 | 94 | nativeAvailable() ? native("clipboardRead") : navigator.clipboard.readText(); |
| @@ -37,6 +37,7 @@ export function ClaudeDesktop({ | ||
| 37 | 37 | }); |
| 38 | 38 | const [desktop, setDesktop] = useState(null); |
| 39 | 39 | const [error, setError] = useState(""); |
| 40 | 新增: const [statusError, setStatusError] = useState(""); | |
| 40 | 41 | const [submitting, setSubmitting] = useState(false); |
| 41 | 42 | const [jobID, setJobID] = useState(""); |
| 42 | 43 | const opened = useRef(false); |
| @@ -46,9 +47,10 @@ export function ClaudeDesktop({ | ||
| 46 | 47 | try { |
| 47 | 48 | const value = await api("/claude-desktop"); |
| 48 | 49 | setDesktop(value); |
| 50 | 新增: setStatusError(""); | |
| 49 | 51 | return value; |
| 50 | 52 | } catch (e) { |
| 51 | 删除: setError(e.message); | |
| 53 | 新增: setStatusError(e.message); | |
| 52 | 54 | return null; |
| 53 | 55 | } |
| 54 | 56 | }; |
| @@ -177,9 +179,11 @@ export function ClaudeDesktop({ | ||
| 177 | 179 | <RefreshCw size={15} /> |
| 178 | 180 | </button> |
| 179 | 181 | </header> |
| 180 | 删除: {(error || desktop?.failed) && ( | |
| 182 | 新增: {(error || statusError || desktop?.failed) && ( | |
| 181 | 183 | <div className="connection-banner" role="alert"> |
| 182 | 删除: {error || "Claude Desktop 未能启动,可重试打开或修复安装。"} | |
| 184 | 新增: {error || statusError || (desktop?.failure_reason === "oom-kill" | |
| 185 | 新增: ? "环境内存不足,Claude Desktop 已被系统关闭。请在设置中检查计算资源后重新打开。" | |
| 186 | 新增: : "Claude Desktop 未能启动,可重试打开或修复安装。")} | |
| 183 | 187 | <button onClick={onDetails}>操作详情</button> |
| 184 | 188 | </div> |
| 185 | 189 | )} |
| @@ -0,0 +1,63 @@ | ||
| 1 | 新增:import React, { useEffect, useState } from "react"; | |
| 2 | 新增:import { ArrowDownToLine, LoaderCircle } from "lucide-react"; | |
| 3 | 新增:import { api, native, nativeAvailable } from "./api"; | |
| 4 | 新增:import { reportDiagnostic } from "./diagnostics.mjs"; | |
| 5 | 新增: | |
| 6 | 新增:export function DiagnosticSettings() { | |
| 7 | 新增: const [info, setInfo] = useState(null); | |
| 8 | 新增: const [busy, setBusy] = useState(false); | |
| 9 | 新增: const [notice, setNotice] = useState(""); | |
| 10 | 新增: const [error, setError] = useState(""); | |
| 11 | 新增: useEffect(() => { | |
| 12 | 新增: let live = true; | |
| 13 | 新增: api("/diagnostics").then(value => { if (live) setInfo(value); }) | |
| 14 | 新增: .catch(error => { if (live) setError(error.message); }); | |
| 15 | 新增: return () => { live = false; }; | |
| 16 | 新增: }, []); | |
| 17 | 新增: const save = async () => { | |
| 18 | 新增: setBusy(true); setError(""); setNotice(""); | |
| 19 | 新增: try { | |
| 20 | 新增: if (nativeAvailable()) { | |
| 21 | 新增: const result = await native("exportDiagnostics"); | |
| 22 | 新增: if (!result?.canceled) setNotice("诊断包已保存。分享前请检查其中内容。"); | |
| 23 | 新增: } else { | |
| 24 | 新增: // Fetch before downloading so authentication or disk failures are shown. | |
| 25 | 新增: const response = await fetch("/api/diagnostics/export"); | |
| 26 | 新增: if (!response.ok) throw new Error((await response.text()).trim() || "诊断包导出失败"); | |
| 27 | 新增: if (!response.headers.get("content-type")?.startsWith("application/zip")) throw new Error("当前后台不支持诊断导出,请重新打开 Cage"); | |
| 28 | 新增: const url = URL.createObjectURL(await response.blob()); | |
| 29 | 新增: const link = document.createElement("a"); link.href = url; link.download = "cage-diagnostics.zip"; link.click(); | |
| 30 | 新增: setTimeout(() => URL.revokeObjectURL(url), 30_000); | |
| 31 | 新增: setNotice("诊断包已下载。分享前请检查其中内容。"); | |
| 32 | 新增: } | |
| 33 | 新增: } catch (error) { setError(error.message); } | |
| 34 | 新增: finally { setBusy(false); } | |
| 35 | 新增: }; | |
| 36 | 新增: return <section className="settings-group" aria-label="日志与诊断"> | |
| 37 | 新增: <h3>日志与诊断</h3> | |
| 38 | 新增: <p className="footnote">自动记录应用故障并脱敏,保留 14 天,容量预算 50 MiB(本机上限 40 MiB、环境服务预算 10 MiB)。不收集终端内容、项目文件或完整配置。</p> | |
| 39 | 新增: {info && <p className="footnote">本机日志 {(info.bytes / 1024 / 1024).toFixed(1)} MiB · {info.files} 个文件</p>} | |
| 40 | 新增: <button className="secondary-button" disabled={busy} onClick={save}> | |
| 41 | 新增: {busy ? <LoaderCircle size={14} className="spin" /> : <ArrowDownToLine size={14} />} | |
| 42 | 新增: {busy ? "正在导出…" : "导出诊断包"} | |
| 43 | 新增: </button> | |
| 44 | 新增: <p className="footnote">诊断包包含脱敏日志、版本和收集状态;环境离线时仍可导出本机记录。只保存在你选择的位置。</p> | |
| 45 | 新增: {notice && <p role="status">{notice}</p>} | |
| 46 | 新增: {error && <p role="alert" className="error-message">{error}</p>} | |
| 47 | 新增: </section>; | |
| 48 | 新增:} | |
| 49 | 新增: | |
| 50 | 新增:export class DiagnosticBoundary extends React.Component { | |
| 51 | 新增: state = { failed: false }; | |
| 52 | 新增: static getDerivedStateFromError() { return { failed: true }; } | |
| 53 | 新增: componentDidCatch(error, info) { reportDiagnostic("react", new Error(`${error.message}\n${error.stack || ""}\n${info.componentStack || ""}`)); } | |
| 54 | 新增: render() { | |
| 55 | 新增: if (!this.state.failed) return this.props.children; | |
| 56 | 新增: return <main style={{ padding: 32 }}> | |
| 57 | 新增: <h2>工作台显示遇到异常</h2> | |
| 58 | 新增: <p>后台任务仍可继续运行。可以导出诊断包,再重新加载界面。</p> | |
| 59 | 新增: <DiagnosticSettings /> | |
| 60 | 新增: <button className="primary-button" onClick={() => location.reload()}>重新加载界面</button> | |
| 61 | 新增: </main>; | |
| 62 | 新增: } | |
| 63 | 新增:} | |
| @@ -0,0 +1,49 @@ | ||
| 1 | 新增:// Error reports deliberately omit request bodies, arguments, page URLs and DOM. | |
| 2 | 新增:let windowStarted = 0; | |
| 3 | 新增:let sent = 0; | |
| 4 | 新增:const pending = []; | |
| 5 | 新增:let sending = false; | |
| 6 | 新增:let retryTimer; | |
| 7 | 新增:async function flush() { | |
| 8 | 新增: if (sending) return; | |
| 9 | 新增: clearTimeout(retryTimer); | |
| 10 | 新增: retryTimer = undefined; | |
| 11 | 新增: sending = true; | |
| 12 | 新增: try { | |
| 13 | 新增: while (pending.length) { | |
| 14 | 新增: const response = await fetch("/api/diagnostics/events", { | |
| 15 | 新增: method: "POST", headers: { "Content-Type": "application/json" }, | |
| 16 | 新增: body: JSON.stringify(pending[0]), | |
| 17 | 新增: }); | |
| 18 | 新增: if (!response.ok) break; | |
| 19 | 新增: pending.shift(); | |
| 20 | 新增: } | |
| 21 | 新增: } catch { /* Retry after the local controller or session recovers. */ } | |
| 22 | 新增: finally { | |
| 23 | 新增: sending = false; | |
| 24 | 新增: if (pending.length) { | |
| 25 | 新增: retryTimer = setTimeout(flush, 5000); | |
| 26 | 新增: retryTimer.unref?.(); | |
| 27 | 新增: } | |
| 28 | 新增: } | |
| 29 | 新增:} | |
| 30 | 新增:export function reportDiagnostic(source, error) { | |
| 31 | 新增: const now = Date.now(); | |
| 32 | 新增: if (now - windowStarted > 60_000) { windowStarted = now; sent = 0; } | |
| 33 | 新增: if (sent >= 20 || pending.length >= 20) return; | |
| 34 | 新增: sent++; | |
| 35 | 新增: let message; | |
| 36 | 新增: if (error instanceof Error) message = `${error.name}: ${error.message}\n${error.stack || ""}`; | |
| 37 | 新增: else if (typeof error === "string") message = error; | |
| 38 | 新增: else message = "异步操作发生异常,未收集原始对象"; | |
| 39 | 新增: // The backend redacts before persisting. Never report the report's own failure. | |
| 40 | 新增: pending.push({ source, level: "error", message: message.slice(0, 4096) }); | |
| 41 | 新增: void flush(); | |
| 42 | 新增:} | |
| 43 | 新增:export function installDiagnostics(target = window) { | |
| 44 | 新增: target.addEventListener("error", event => { | |
| 45 | 新增: if (event.error) reportDiagnostic("frontend", event.error); | |
| 46 | 新增: else reportDiagnostic("frontend", event.message || "界面资源加载失败"); | |
| 47 | 新增: }); | |
| 48 | 新增: target.addEventListener("unhandledrejection", event => reportDiagnostic("frontend", event.reason)); | |
| 49 | 新增:} | |
| @@ -0,0 +1,33 @@ | ||
| 1 | 新增:import test from "node:test"; | |
| 2 | 新增:import assert from "node:assert/strict"; | |
| 3 | 新增: | |
| 4 | 新增:test("reports retry after local controller failure, bound payloads, and omit arbitrary objects", async (t) => { | |
| 5 | 新增: const saved = { fetch: globalThis.fetch, setTimeout: globalThis.setTimeout, clearTimeout: globalThis.clearTimeout }; | |
| 6 | 新增: t.after(() => Object.assign(globalThis, saved)); | |
| 7 | 新增: const attempts = []; | |
| 8 | 新增: let retry; | |
| 9 | 新增: let online = false; | |
| 10 | 新增: globalThis.setTimeout = (fn) => { retry = fn; return { unref() {} }; }; | |
| 11 | 新增: globalThis.clearTimeout = () => {}; | |
| 12 | 新增: globalThis.fetch = async (path, options) => { | |
| 13 | 新增: assert.equal(path, "/api/diagnostics/events"); | |
| 14 | 新增: attempts.push(JSON.parse(options.body)); | |
| 15 | 新增: if (!online) throw new Error("controller offline"); | |
| 16 | 新增: return { ok: true }; | |
| 17 | 新增: }; | |
| 18 | 新增: const { reportDiagnostic } = await import("./diagnostics.mjs?report-test"); | |
| 19 | 新增: reportDiagnostic("frontend", new Error("failure " + "x".repeat(20_000))); | |
| 20 | 新增: await Promise.resolve(); await Promise.resolve(); | |
| 21 | 新增: assert.ok(retry, "failed reports were lost"); | |
| 22 | 新增: assert.ok(attempts[0].message.length <= 4096); | |
| 23 | 新增: online = true; | |
| 24 | 新增: await retry(); | |
| 25 | 新增: reportDiagnostic("frontend", { password: "never-serialize-objects" }); | |
| 26 | 新增: await Promise.resolve(); await Promise.resolve(); | |
| 27 | 新增: assert.equal(attempts.length, 3); | |
| 28 | 新增: assert.equal(attempts[0].message, attempts[1].message); | |
| 29 | 新增: assert.ok(!attempts[2].message.includes("never-serialize-objects")); | |
| 30 | 新增: for (let n = 0; n < 50; n++) reportDiagnostic("frontend", "repeated"); | |
| 31 | 新增: for (let n = 0; n < 30; n++) await Promise.resolve(); | |
| 32 | 新增: assert.equal(attempts.length, 21, "client rate limit must bound accepted events to 20 per minute"); | |
| 33 | 新增:}); | |
| @@ -1,3 +1,5 @@ | ||
| 1 | 新增:import { installDiagnostics } from "./diagnostics.mjs"; | |
| 2 | 新增:import { DiagnosticBoundary } from "./diagnostics.jsx"; | |
| 1 | 3 | import { shortcut, primaryModifier } from "./platform.mjs"; |
| 2 | 4 | import logo from "./logo.png"; |
| 3 | 5 | import React, { useEffect, useRef, useState } from "react"; |
| @@ -478,6 +480,11 @@ function App() { | ||
| 478 | 480 | stream.onerror = () => { browserStreamReady.current = false; }; |
| 479 | 481 | stream.onmessage = (event) => { |
| 480 | 482 | const b = JSON.parse(event.data); |
| 483 | 新增: if (b.desktopFocus === true) { | |
| 484 | 新增: setDesktopOpen(true); | |
| 485 | 新增: setHome(false); | |
| 486 | 新增: setSettingsOpen(false); | |
| 487 | 新增: } | |
| 481 | 488 | browserSnapshot.current = b; |
| 482 | 489 | setBrowser((previous) => ({ ...previous, ...b })); |
| 483 | 490 | setTabs((previous) => { |
| @@ -1676,12 +1683,15 @@ function App() { | ||
| 1676 | 1683 | </div> |
| 1677 | 1684 | ); |
| 1678 | 1685 | } |
| 1686 | 新增:installDiagnostics(); | |
| 1679 | 1687 | createRoot(document.getElementById("root")).render( |
| 1688 | 新增: <DiagnosticBoundary> | |
| 1680 | 1689 | <AccountProvider> |
| 1681 | 1690 | <AppearanceProvider> |
| 1682 | 1691 | <AccountGate><App /></AccountGate> |
| 1683 | 1692 | </AppearanceProvider> |
| 1684 | 删除: </AccountProvider>, | |
| 1693 | 新增: </AccountProvider> | |
| 1694 | 新增: </DiagnosticBoundary>, | |
| 1685 | 1695 | ); |
| 1686 | 1696 | |
| 1687 | 1697 | // A launcher can reopen an existing window with a fresh one-use ticket. |
| @@ -1,5 +1,5 @@ | ||
| 1 | 1 | import { getKeycode, getKeysym } from "../.generated/novnc/core/input/util.js"; |
| 2 | 删除:import { writeClipboard, nativeAvailable } from "./api"; | |
| 2 | 新增:import { writeClipboard, nativeAvailable, native } from "./api"; | |
| 3 | 3 | import { |
| 4 | 4 | readClipboardContent, |
| 5 | 5 | transferFiles, |
| @@ -11,7 +11,7 @@ import { | ||
| 11 | 11 | export function installRemoteInput( |
| 12 | 12 | rfb, |
| 13 | 13 | container, |
| 14 | 删除: { mode, onStatus, onFallback, isActive, insertText, pasteContent }, | |
| 14 | 新增: { mode, onStatus, onFallback, isActive, insertText, insertComposition, caretRect, tabId: getTargetId = () => "", pasteContent }, | |
| 15 | 15 | ) { |
| 16 | 16 | const listeners = [], |
| 17 | 17 | handled = new Set(), |
| @@ -22,11 +22,22 @@ export function installRemoteInput( | ||
| 22 | 22 | copyTimer, |
| 23 | 23 | pending = 0, |
| 24 | 24 | composing = false, |
| 25 | 新增: compositionTarget = "", | |
| 26 | 新增: compositionSession = "", | |
| 27 | 新增: compositionSequence = 0, | |
| 28 | 新增: caretState, | |
| 29 | 新增: caretTimer, | |
| 30 | 新增: caretPending = false, | |
| 31 | 新增: nativeOwner = "", | |
| 32 | 新增: nativeTarget = "", | |
| 33 | 新增: nativeOwned = false, | |
| 34 | 新增: nativeFailed = false, | |
| 25 | 35 | disposed = false; |
| 26 | 36 | const target = document.createElement("textarea"); |
| 27 | 37 | target.setAttribute("aria-label", "Cage 网页输入"); |
| 28 | 38 | target.setAttribute("autocomplete", "off"); |
| 29 | 39 | target.setAttribute("autocapitalize", "off"); |
| 40 | 新增: target.setAttribute("wrap", "off"); | |
| 30 | 41 | target.spellcheck = false; |
| 31 | 42 | target.className = "remote-text-input"; |
| 32 | 43 | target.style.cssText = "position:fixed;left:0;top:0"; |
| @@ -38,19 +49,77 @@ export function installRemoteInput( | ||
| 38 | 49 | }; |
| 39 | 50 | const focused = () => |
| 40 | 51 | isActive() && |
| 41 | 删除: (container.contains(document.activeElement) || | |
| 52 | 新增: (nativeOwned || container.contains(document.activeElement) || | |
| 42 | 53 | document.activeElement === target); |
| 54 | 新增: const deactivateNative = () => { | |
| 55 | 新增: const owner = nativeOwner; | |
| 56 | 新增: nativeOwned = false; | |
| 57 | 新增: nativeOwner = ""; | |
| 58 | 新增: nativeTarget = ""; | |
| 59 | 新增: if (owner) void native("remoteInput", { operation: "deactivate", owner }).catch(() => {}); | |
| 60 | 新增: }; | |
| 61 | 新增: const updateNative = (rect) => { | |
| 62 | 新增: if (nativeFailed || !window.cageNativeIMEAvailable || !nativeAvailable() || !focused()) return; | |
| 63 | 新增: if (!nativeOwned && composing) return; | |
| 64 | 新增: const operation = nativeOwned ? "caret" : "activate"; | |
| 65 | 新增: if (!nativeOwned) { nativeOwner = crypto.randomUUID(); nativeTarget = getTargetId(); nativeOwned = true; } | |
| 66 | 新增: const owner = nativeOwner; | |
| 67 | 新增: void native("remoteInput", { operation, owner, ...rect }).then((accepted) => { | |
| 68 | 新增: if (owner !== nativeOwner) return; | |
| 69 | 新增: if (!accepted || disposed) { | |
| 70 | 新增: deactivateNative(); | |
| 71 | 新增: nativeFailed = !accepted; | |
| 72 | 新增: } | |
| 73 | 新增: }).catch(() => { if (owner === nativeOwner) { deactivateNative(); nativeFailed = true; } }); | |
| 74 | 新增: }; | |
| 43 | 75 | const position = (x, y) => { |
| 44 | 删除: if (composing) return; | |
| 45 | 删除: target.style.left = `${Math.max(0, Math.min(x, window.innerWidth - 280))}px`; | |
| 46 | 删除: target.style.top = `${Math.max(0, Math.min(y, window.innerHeight - 36))}px`; | |
| 76 | 新增: target.style.left = `${Math.max(0, Math.min(x, window.innerWidth - 1))}px`; | |
| 77 | 新增: target.style.top = `${Math.max(0, Math.min(y, window.innerHeight - 24))}px`; | |
| 78 | 新增: }; | |
| 79 | 新增: const syncCaret = async () => { | |
| 80 | 新增: if (!caretRect || caretPending || disposed || !isActive()) return; | |
| 81 | 新增: caretPending = true; | |
| 82 | 新增: const id = getTargetId(); | |
| 83 | 新增: if (nativeOwned && nativeTarget !== id) deactivateNative(); | |
| 84 | 新增: try { | |
| 85 | 新增: const value = await caretRect(compositionSession); | |
| 86 | 新增: if (disposed || !isActive() || id !== getTargetId()) return; | |
| 87 | 新增: caretState = value?.available ? { ...value, target: id, time: Date.now() } : null; | |
| 88 | 新增: if (!value?.available) { deactivateNative(); return; } | |
| 89 | 新增: if (!value.rect || value.rect[3] <= 0) return; | |
| 90 | 新增: const canvas = container.querySelector("canvas"); | |
| 91 | 新增: if (!canvas?.width || !canvas.height) return; | |
| 92 | 新增: const bounds = canvas.getBoundingClientRect(); | |
| 93 | 新增: const height = Math.max(1, value.rect[3] / canvas.height * bounds.height); | |
| 94 | 新增: target.style.height = `${height}px`; | |
| 95 | 新增: target.style.lineHeight = `${height}px`; | |
| 96 | 新增: const x = bounds.left + (value.rect[0] / canvas.width) * bounds.width; | |
| 97 | 新增: const y = bounds.top + (value.rect[1] / canvas.height) * bounds.height; | |
| 98 | 新增: position(x, y); | |
| 99 | 新增: updateNative({ x, y, height }); | |
| 100 | 新增: } catch {} finally { caretPending = false; } | |
| 101 | 新增: }; | |
| 102 | 新增: const pollCaret = async () => { | |
| 103 | 新增: if (focused()) await syncCaret(); | |
| 104 | 新增: if (!disposed) caretTimer = setTimeout(pollCaret, 250); | |
| 47 | 105 | }; |
| 106 | 新增: if (caretRect) caretTimer = setTimeout(pollCaret, 0); | |
| 48 | 107 | const bounds = container.getBoundingClientRect(); |
| 49 | 108 | position(bounds.left + 12, bounds.top + 12); |
| 50 | 109 | on( |
| 51 | 110 | container, |
| 52 | 111 | "pointerdown", |
| 53 | 删除: (event) => position(event.clientX, event.clientY), | |
| 112 | 新增: (event) => { | |
| 113 | 新增: // Cancel before noVNC queues a click into another remote field. | |
| 114 | 新增: if (composing) { | |
| 115 | 新增: if (compositionSession) queueComposition({ mode: "cancel" }); | |
| 116 | 新增: resetComposition(); | |
| 117 | 新增: const owner = nativeOwner; | |
| 118 | 新增: if (owner) void native("remoteInput", { operation: "cancel", owner }).catch(() => {}); | |
| 119 | 新增: target.blur(); | |
| 120 | 新增: } | |
| 121 | 新增: position(event.clientX, event.clientY); | |
| 122 | 新增: }, | |
| 54 | 123 | true, |
| 55 | 124 | ); |
| 56 | 125 | const commit = (text) => { |
| @@ -61,19 +130,63 @@ export function installRemoteInput( | ||
| 61 | 130 | if (!disposed) onStatus("文字输入未完成,请重新连接画面后重试"); |
| 62 | 131 | }); |
| 63 | 132 | }; |
| 133 | 新增: const queueComposition = (value) => { | |
| 134 | 新增: const targetId = compositionTarget; | |
| 135 | 新增: if (!insertComposition || !compositionSession || !targetId || disposed || | |
| 136 | 新增: (!isActive() && value.mode !== "cancel")) return; | |
| 137 | 新增: // Reserve the shared RFB input queue in this event handler. Deferring this | |
| 138 | 新增: // call to another promise would let the next Enter overtake the commit. | |
| 139 | 新增: insertComposition(targetId, { session: compositionSession, sequence: compositionSequence++, ...value }).catch((error) => { | |
| 140 | 新增: if (!disposed && value.mode !== "cancel") | |
| 141 | 新增: say(error.message || "输入法组合文字未能同步"); | |
| 142 | 新增: }); | |
| 143 | 新增: }; | |
| 64 | 144 | const resetComposition = () => { |
| 65 | 145 | composing = false; |
| 146 | 新增: compositionTarget = ""; | |
| 147 | 新增: compositionSession = ""; | |
| 66 | 148 | target.value = ""; |
| 67 | 149 | }; |
| 68 | 删除: on(target, "compositionstart", () => { | |
| 150 | 新增: const startComposition = () => { | |
| 69 | 151 | composing = true; |
| 152 | 新增: compositionTarget = getTargetId(); | |
| 153 | 新增: if (insertComposition && caretState?.context && caretState.target === compositionTarget && | |
| 154 | 新增: Date.now() - caretState.time < 1000) { | |
| 155 | 新增: compositionSession = crypto.randomUUID().replaceAll("-", ""); | |
| 156 | 新增: compositionSequence = 0; | |
| 157 | 新增: queueComposition({ mode: "begin", context: caretState.context }); | |
| 158 | 新增: } | |
| 159 | 新增: void syncCaret(); | |
| 160 | 新增: }; | |
| 161 | 新增: on(target, "compositionstart", startComposition); | |
| 162 | 新增: on(target, "compositionupdate", () => { | |
| 163 | 新增: void syncCaret(); | |
| 70 | 164 | }); |
| 71 | 删除: on(target, "compositionend", (event) => { | |
| 72 | 删除: if (composing) commit(event.data || ""); | |
| 165 | 新增: const endComposition = (text) => { | |
| 166 | 新增: if (composing) { | |
| 167 | 新增: if (compositionSession) queueComposition({ mode: "commit", text, selectionStart: 0, selectionEnd: 0 }); | |
| 168 | 新增: else if (compositionTarget === getTargetId()) commit(text); | |
| 169 | 新增: } | |
| 73 | 170 | resetComposition(); |
| 74 | 删除: }); | |
| 171 | 新增: void syncCaret(); | |
| 172 | 新增: }; | |
| 173 | 新增: on(target, "compositionend", (event) => endComposition(event.data || "")); | |
| 75 | 174 | on(target, "input", (event) => { |
| 76 | 删除: if (composing || event.isComposing) return; | |
| 175 | 新增: if (document.activeElement !== target) { | |
| 176 | 新增: if (!composing) target.value = ""; | |
| 177 | 新增: return; | |
| 178 | 新增: } | |
| 179 | 新增: if (composing || event.isComposing) { | |
| 180 | 新增: if (compositionSession && ["insertCompositionText", "insertFromComposition"].includes(event.inputType)) { | |
| 181 | 新增: queueComposition({ | |
| 182 | 新增: mode: "update", | |
| 183 | 新增: text: target.value, | |
| 184 | 新增: selectionStart: target.selectionStart ?? target.value.length, | |
| 185 | 新增: selectionEnd: target.selectionEnd ?? target.value.length, | |
| 186 | 新增: }); | |
| 187 | 新增: } | |
| 188 | 新增: return; | |
| 189 | 新增: } | |
| 77 | 190 | // WebKit may deliver the final input after compositionend. That text has |
| 78 | 191 | // already been sent. Input without composition covers emoji and dictation. |
| 79 | 192 | if ( |
| @@ -84,7 +197,39 @@ export function installRemoteInput( | ||
| 84 | 197 | commit(target.value); |
| 85 | 198 | target.value = ""; |
| 86 | 199 | }); |
| 87 | 删除: on(target, "blur", resetComposition); | |
| 200 | 新增: on(target, "blur", () => { | |
| 201 | 新增: if (nativeOwned) return; | |
| 202 | 新增: if (composing && compositionSession) queueComposition({ mode: "cancel", text: "", selectionStart: 0, selectionEnd: 0 }); | |
| 203 | 新增: resetComposition(); | |
| 204 | 新增: }); | |
| 205 | 新增: on(document, "focusin", (event) => { | |
| 206 | 新增: if (nativeOwned && !container.contains(event.target)) deactivateNative(); | |
| 207 | 新增: }); | |
| 208 | 新增: on(window, "cage-native-input", (event) => { | |
| 209 | 新增: const value = event.detail; | |
| 210 | 新增: if (disposed || !value || value.owner !== nativeOwner) return; | |
| 211 | 新增: if (value.kind === "deactivated") { | |
| 212 | 新增: nativeOwned = false; | |
| 213 | 新增: nativeOwner = ""; | |
| 214 | 新增: if (composing && compositionSession) queueComposition({ mode: "cancel" }); | |
| 215 | 新增: resetComposition(); | |
| 216 | 新增: return; | |
| 217 | 新增: } | |
| 218 | 新增: if (!isActive() || nativeTarget !== getTargetId()) { deactivateNative(); return; } | |
| 219 | 新增: if (value.kind === "compositionstart") startComposition(); | |
| 220 | 新增: else if (value.kind === "compositionupdate" && composing) { | |
| 221 | 新增: queueComposition({ mode: "update", text: value.text, selectionStart: value.selectionStart, selectionEnd: value.selectionEnd }); | |
| 222 | 新增: } else if (value.kind === "compositionend") endComposition(value.text || ""); | |
| 223 | 新增: else if (value.kind === "input") commit(value.text); | |
| 224 | 新增: else if (["keydown", "keyup"].includes(value.kind)) { | |
| 225 | 新增: const key = new KeyboardEvent(value.kind, { ...value, bubbles: true, cancelable: true }); | |
| 226 | 新增: key.cageNativeTextKey = value.textKey; | |
| 227 | 新增: target.dispatchEvent(key); | |
| 228 | 新增: } | |
| 229 | 新增: }); | |
| 230 | 新增: on(container, "pointerup", () => { | |
| 231 | 新增: setTimeout(() => void syncCaret(), 50); | |
| 232 | 新增: }); | |
| 88 | 233 | const say = (text) => { |
| 89 | 234 | if (!disposed) onStatus(text); |
| 90 | 235 | }; |
| @@ -177,8 +322,8 @@ export function installRemoteInput( | ||
| 177 | 322 | event.keyCode === 229 || |
| 178 | 323 | ["Process", "Dead"].includes(event.key) |
| 179 | 324 | ) { |
| 180 | 删除: // Leave the default action to the host IME; noVNC must not cancel it | |
| 181 | 删除: // or send candidate navigation/confirmation keys into the guest. | |
| 325 | 新增: // Leave composition keys to the host IME. The guest receives the | |
| 326 | 新增: // composition text through the authenticated browser IME endpoint. | |
| 182 | 327 | event.stopImmediatePropagation(); |
| 183 | 328 | return; |
| 184 | 329 | } |
| @@ -259,6 +404,20 @@ export function installRemoteInput( | ||
| 259 | 404 | } |
| 260 | 405 | } |
| 261 | 406 | if (mapping && event.key === "Meta") event.stopImmediatePropagation(); |
| 407 | 新增: if (!event.metaKey && !event.ctrlKey && [...event.key].length === 1 && | |
| 408 | 新增: event.key.codePointAt(0) > 127) { | |
| 409 | 新增: // Fullwidth punctuation may arrive without a composition session. | |
| 410 | 新增: // Sending it as an X11 keysym can silently drop it in X0tigervnc. | |
| 411 | 新增: event.preventDefault(); | |
| 412 | 新增: event.stopImmediatePropagation(); | |
| 413 | 新增: handled.add(code); | |
| 414 | 新增: commit(event.key); | |
| 415 | 新增: } else if (!event.cageNativeTextKey && !event.metaKey && !event.ctrlKey && !event.altKey && | |
| 416 | 新增: event.key.length === 1 && /[^a-zA-Z0-9 ]/.test(event.key)) { | |
| 417 | 新增: // Let the host input method choose punctuation (e.g. ? -> ?). | |
| 418 | 新增: // The resulting input event carries the actual character to insert. | |
| 419 | 新增: event.stopImmediatePropagation(); | |
| 420 | 新增: } | |
| 262 | 421 | }, |
| 263 | 422 | true, |
| 264 | 423 | ); |
| @@ -281,6 +440,8 @@ export function installRemoteInput( | ||
| 281 | 440 | (focused() && mode() === "mac" && event.key === "Meta") |
| 282 | 441 | ) |
| 283 | 442 | event.stopImmediatePropagation(); |
| 443 | 新增: else if (focused() && !composing && caretRect) | |
| 444 | 新增: setTimeout(() => void syncCaret(), 35); | |
| 284 | 445 | }, |
| 285 | 446 | true, |
| 286 | 447 | ); |
| @@ -338,8 +499,12 @@ export function installRemoteInput( | ||
| 338 | 499 | return true; |
| 339 | 500 | }, |
| 340 | 501 | dispose() { |
| 502 | 新增: if (composing && compositionSession) | |
| 503 | 新增: queueComposition({ mode: "cancel", text: "", selectionStart: 0, selectionEnd: 0 }); | |
| 341 | 504 | disposed = true; |
| 505 | 新增: deactivateNative(); | |
| 342 | 506 | clearTimeout(copyTimer); |
| 507 | 新增: clearTimeout(caretTimer); | |
| 343 | 508 | release(); |
| 344 | 509 | listeners.forEach((remove) => remove()); |
| 345 | 510 | rfb.cageSetKeyboardTarget(null); |
| @@ -2,13 +2,14 @@ import test from "node:test"; | ||
| 2 | 2 | import assert from "node:assert/strict"; |
| 3 | 3 | import { readFileSync } from "node:fs"; |
| 4 | 4 | import vm from "node:vm"; |
| 5 | 新增:import { webcrypto } from "node:crypto"; | |
| 5 | 6 | const source = readFileSync( |
| 6 | 7 | new URL("./remote-input.js", import.meta.url), |
| 7 | 8 | "utf8", |
| 8 | 9 | ) |
| 9 | 10 | .replace(/^import[\s\S]*?;\n/gm, "") |
| 10 | 11 | .replace("export function installRemoteInput", "function installRemoteInput"); |
| 11 | 删除:function fixture(native = false) { | |
| 12 | 新增:function fixture(native = false, browserComposition = false) { | |
| 12 | 13 | const doc = new EventTarget(), |
| 13 | 14 | win = new EventTarget(), |
| 14 | 15 | canvas = {}, |
| @@ -16,10 +17,12 @@ function fixture(native = false) { | ||
| 16 | 17 | keys = [], |
| 17 | 18 | pastes = [], |
| 18 | 19 | texts = [], |
| 20 | 新增: compositions = [], | |
| 19 | 21 | writes = [], |
| 20 | 22 | statuses = []; |
| 21 | 23 | let reads = 0, |
| 22 | 删除: mode = "mac"; | |
| 24 | 新增: mode = "mac", | |
| 25 | 新增: currentTabId = "tab-1"; | |
| 23 | 26 | doc.activeElement = canvas; |
| 24 | 27 | doc.body = { append() {} }; |
| 25 | 28 | const target = Object.assign(new EventTarget(), { |
| @@ -56,6 +59,7 @@ function fixture(native = false) { | ||
| 56 | 59 | Map, |
| 57 | 60 | Set, |
| 58 | 61 | console, |
| 62 | 新增: crypto: webcrypto, | |
| 59 | 63 | readClipboardContent: async () => { |
| 60 | 64 | reads++; |
| 61 | 65 | return { text: "中文🙂" }; |
| @@ -78,6 +82,7 @@ function fixture(native = false) { | ||
| 78 | 82 | const controller = install( |
| 79 | 83 | rfb, |
| 80 | 84 | Object.assign(new EventTarget(), { |
| 85 | 新增: querySelector: () => null, | |
| 81 | 86 | contains: (element) => element === canvas || element === target, |
| 82 | 87 | append() {}, |
| 83 | 88 | getBoundingClientRect: () => ({ left: 0, top: 0 }), |
| @@ -90,6 +95,14 @@ function fixture(native = false) { | ||
| 90 | 95 | insertText: async (text) => { |
| 91 | 96 | texts.push(text); |
| 92 | 97 | }, |
| 98 | 新增: insertComposition: browserComposition ? async (id, value) => { | |
| 99 | 新增: if (id !== currentTabId) throw new Error("Input target changed"); | |
| 100 | 新增: compositions.push({ id, ...value }); | |
| 101 | 新增: } : null, | |
| 102 | 新增: tabId: () => currentTabId, | |
| 103 | 新增: caretRect: browserComposition ? async () => ({ | |
| 104 | 新增: available: true, context: "a".repeat(32), rect: [240, 120, 0, 24], | |
| 105 | 新增: }) : null, | |
| 93 | 106 | pasteContent: async (content) => { |
| 94 | 107 | const value = await content; |
| 95 | 108 | if (rfb.target) pastes.push(value.png || value.text); |
| @@ -117,6 +130,7 @@ function fixture(native = false) { | ||
| 117 | 130 | keys, |
| 118 | 131 | pastes, |
| 119 | 132 | texts, |
| 133 | 新增: compositions, | |
| 120 | 134 | writes, |
| 121 | 135 | statuses, |
| 122 | 136 | controller, |
| @@ -126,6 +140,9 @@ function fixture(native = false) { | ||
| 126 | 140 | setMode: (value) => { |
| 127 | 141 | mode = value; |
| 128 | 142 | }, |
| 143 | 新增: setTabId: (value) => { | |
| 144 | 新增: currentTabId = value; | |
| 145 | 新增: }, | |
| 129 | 146 | reads: () => reads, |
| 130 | 147 | }; |
| 131 | 148 | } |
| @@ -215,6 +232,46 @@ test("host IME receives composition keys and sends only committed Unicode in ord | ||
| 215 | 232 | assert.equal(f.rfb.target, null); |
| 216 | 233 | }); |
| 217 | 234 | |
| 235 | 新增:test("browser composition is forwarded as preedit, then committed separately", async () => { | |
| 236 | 新增: const f = fixture(false, true); | |
| 237 | 新增: await new Promise((resolve) => setTimeout(resolve, 5)); | |
| 238 | 新增: try { | |
| 239 | 新增: f.rfb.focus(); | |
| 240 | 新增: inputEvent(f, "compositionstart"); | |
| 241 | 新增: f.target.value = "nihao"; | |
| 242 | 新增: inputEvent(f, "compositionupdate", { data: "nihao" }); | |
| 243 | 新增: inputEvent(f, "input", { data: "nihao", inputType: "insertCompositionText", isComposing: true }); | |
| 244 | 新增: await Promise.resolve(); | |
| 245 | 新增: inputEvent(f, "compositionend", { data: "你好" }); | |
| 246 | 新增: await new Promise((resolve) => setImmediate(resolve)); | |
| 247 | 新增: assert.deepEqual(f.texts, []); | |
| 248 | 新增: assert.equal(f.compositions[0].mode, "begin"); | |
| 249 | 新增: assert.equal(new Set(f.compositions.map(value => value.session)).size, 1); | |
| 250 | 新增: assert.deepEqual(f.compositions.map(value => value.sequence), [0, 1, 2]); | |
| 251 | 新增: assert.deepEqual(JSON.parse(JSON.stringify(f.compositions.slice(1).map(({session, sequence, ...value}) => value))), [ | |
| 252 | 新增: { id: "tab-1", mode: "update", text: "nihao", selectionStart: 5, selectionEnd: 5 }, | |
| 253 | 新增: { id: "tab-1", mode: "commit", text: "你好", selectionStart: 0, selectionEnd: 0 }, | |
| 254 | 新增: ]); | |
| 255 | 新增: } finally { | |
| 256 | 新增: f.controller.dispose(); | |
| 257 | 新增: } | |
| 258 | 新增:}); | |
| 259 | 新增: | |
| 260 | 新增:test("queued composition stays bound to its original browser tab", async () => { | |
| 261 | 新增: const f = fixture(false, true); | |
| 262 | 新增: await new Promise((resolve) => setTimeout(resolve, 5)); | |
| 263 | 新增: f.rfb.focus(); | |
| 264 | 新增: inputEvent(f, "compositionstart"); | |
| 265 | 新增: f.target.value = "nihao"; | |
| 266 | 新增: inputEvent(f, "input", { data: "nihao", inputType: "insertCompositionText", isComposing: true }); | |
| 267 | 新增: f.setTabId("tab-2"); | |
| 268 | 新增: inputEvent(f, "compositionend", { data: "你好" }); | |
| 269 | 新增: await new Promise((resolve) => setImmediate(resolve)); | |
| 270 | 新增: assert.deepEqual(f.compositions.map(value => value.mode), ["begin", "update"]); | |
| 271 | 新增: assert.ok(f.statuses.includes("Input target changed")); | |
| 272 | 新增: f.controller.dispose(); | |
| 273 | 新增:}); | |
| 274 | 新增: | |
| 218 | 275 | test("cancelled and disconnected compositions do not insert text", () => { |
| 219 | 276 | const f = fixture(); |
| 220 | 277 | f.rfb.focus(); |
| @@ -241,6 +298,24 @@ test("text input without a composition supports emoji and clears the host buffer | ||
| 241 | 298 | f.controller.dispose(); |
| 242 | 299 | } |
| 243 | 300 | }); |
| 301 | 新增: | |
| 302 | 新增:test("fullwidth punctuation without composition uses text, while host punctuation keeps its default action", () => { | |
| 303 | 新增: const f = fixture(); | |
| 304 | 新增: try { | |
| 305 | 新增: f.rfb.focus(); | |
| 306 | 新增: for (const character of ["?", "?", ",", "。", "!", "🙂"]) { | |
| 307 | 新增: assert.equal(f.key("keydown", character, "Slash", { shiftKey: true }).defaultPrevented, true); | |
| 308 | 新增: f.key("keyup", character, "Slash"); | |
| 309 | 新增: } | |
| 310 | 新增: assert.deepEqual(f.texts, ["?", "?", ",", "。", "!", "🙂"]); | |
| 311 | 新增: assert.deepEqual(f.keys, []); | |
| 312 | 新增: assert.equal(f.key("keydown", "?", "Slash", { shiftKey: true }).defaultPrevented, false); | |
| 313 | 新增: f.target.value = "?"; | |
| 314 | 新增: inputEvent(f, "input", { data: "?", inputType: "insertText" }); | |
| 315 | 新增: assert.equal(f.texts.at(-1), "?"); | |
| 316 | 新增: assert.equal(f.key("keydown", "?", "Slash", { ctrlKey: true }).defaultPrevented, false); | |
| 317 | 新增: } finally { f.controller.dispose(); } | |
| 318 | 新增:}); | |
| 244 | 319 | test("local fields and native keyboard mode do not acquire mapped shortcuts", () => { |
| 245 | 320 | const f = fixture(); |
| 246 | 321 | try { |
| @@ -0,0 +1,55 @@ | ||
| 1 | 新增:import React, { useEffect, useState } from "react"; | |
| 2 | 新增:import { api } from "./api"; | |
| 3 | 新增: | |
| 4 | 新增:const gib = (bytes) => `${(bytes / 1073741824).toFixed(1)} GiB`; | |
| 5 | 新增: | |
| 6 | 新增:export function ResourceSettings({ status, onConfirm }) { | |
| 7 | 新增: const [data, setData] = useState(null); | |
| 8 | 新增: const [error, setError] = useState(""); | |
| 9 | 新增: const [starting, setStarting] = useState(false); | |
| 10 | 新增: useEffect(() => { | |
| 11 | 新增: let live = true; | |
| 12 | 新增: let timer; | |
| 13 | 新增: const refresh = async () => { | |
| 14 | 新增: try { | |
| 15 | 新增: const next = await api("/environment/resources"); | |
| 16 | 新增: if (live) { setData(next); setError(""); } | |
| 17 | 新增: } catch (e) { if (live) setError(e.message); } | |
| 18 | 新增: if (live) timer = setTimeout(refresh, 4000); | |
| 19 | 新增: }; | |
| 20 | 新增: refresh(); | |
| 21 | 新增: return () => { live = false; clearTimeout(timer); }; | |
| 22 | 新增: }, [status.vm_running, status.job?.running]); | |
| 23 | 新增: const apply = async () => { | |
| 24 | 新增: if (!(await onConfirm({ | |
| 25 | 新增: title: "重启并应用自动资源配置?", | |
| 26 | 新增: body: "正在运行的命令会结束,浏览器和编辑器会重启。请先保存内容;项目文件和登录数据保留。手动暂停的网络仍保持暂停。", | |
| 27 | 新增: confirm: "保存后重启", | |
| 28 | 新增: }))) return; | |
| 29 | 新增: setStarting(true); | |
| 30 | 新增: try { await api("/environment/resources", {}); } | |
| 31 | 新增: catch (e) { setError(e.message); } | |
| 32 | 新增: finally { setStarting(false); } | |
| 33 | 新增: }; | |
| 34 | 新增: const observation = data?.observation; | |
| 35 | 新增: const guest = observation?.guest; | |
| 36 | 新增: const fresh = observation && Date.now() - Date.parse(observation.observed_at) < 10000; | |
| 37 | 新增: return <section className="environment-versions" aria-label="计算资源"> | |
| 38 | 新增: <h4>计算资源 · 自动管理</h4> | |
| 39 | 新增: <p className="field-help">内存随程序需求增长,持续空闲后逐步归还主机。默认上限为主机资源的一半;CPU 按实际任务使用,上限表示可同时使用的逻辑核心数。</p> | |
| 40 | 新增: <div className="setting-summary-row"><span>自动内存上限</span><strong>{data ? gib(data.recommended_memory_bytes) : "正在读取…"}</strong></div> | |
| 41 | 新增: <div className="setting-summary-row"><span>自动 CPU 上限</span><strong>{data ? `${data.recommended_cpus} 个逻辑核心` : "—"}</strong></div> | |
| 42 | 新增: {data?.running && <> | |
| 43 | 新增: <div className="setting-summary-row"><span>本次启动的内存上限</span><strong>{gib(data.configured_memory_bytes)}</strong></div> | |
| 44 | 新增: <div className="setting-summary-row"><span>环境内存用量</span><strong>{fresh && guest ? gib(guest.total_bytes - guest.available_bytes) : "等待采样"}</strong></div> | |
| 45 | 新增: <div className="setting-summary-row"><span>环境当前可用内存总量</span><strong>{fresh && guest ? gib(guest.total_bytes) : "—"}</strong></div> | |
| 46 | 新增: <div className="setting-summary-row"><span>CPU 使用率</span><strong>{fresh ? `${observation.cpu_percent.toFixed(0)}% / ${observation.cpus} 个核心` : "—"}</strong></div> | |
| 47 | 新增: {fresh && guest?.oom_kills > 0 && <p className="field-help" role="status">本次环境启动后,系统因内存不足终止过 {guest.oom_kills} 个进程。请降低重任务的并行数量,或使用内存更多的主机。</p>} | |
| 48 | 新增: {(observation?.pressure || observation?.host_pressure) && <p className="field-help" role="status">{observation.host_pressure ? "主机内存紧张,暂缓扩大分配。" : "环境内存紧张,正在上限内增加可用内存。达到上限后请减少同时运行的任务。"}</p>} | |
| 49 | 新增: {data.restart_required && <button disabled={starting || status.job?.running} onClick={apply}>重启并应用自动资源配置</button>} | |
| 50 | 新增: </>} | |
| 51 | 新增: {!data?.running && data && <p className="field-help">下次启动环境时应用自动配置。</p>} | |
| 52 | 新增: {(error || observation?.error) && <p role="alert" className="error-message">{error || observation.error}</p>} | |
| 53 | 新增: <p className="field-help">内存用量不含可回收缓存;这些数值反映环境内部状态,主机活动监视器还会统计虚拟化开销。短时故障导致内部断网后,会自动重新检查,通过后恢复;手动暂停需手动恢复。</p> | |
| 54 | 新增: </section>; | |
| 55 | 新增:} | |
| @@ -19,6 +19,8 @@ import { ProxySettings } from "./proxy-settings"; | ||
| 19 | 19 | import { ExitPolicyFields } from "./exit-policy"; |
| 20 | 20 | import { canonicalExitPolicy } from "./safety-state.mjs"; |
| 21 | 21 | import { EnvironmentVersions } from "./environment-versions"; |
| 22 | 新增:import { ResourceSettings } from "./resources"; | |
| 23 | 新增:import { DiagnosticSettings } from "./diagnostics.jsx"; | |
| 22 | 24 | import { AccountSettings } from "./account"; |
| 23 | 25 | const sections = [ |
| 24 | 26 | ["account", "账户", UserRound], |
| @@ -560,6 +562,8 @@ export function SettingsPanel({ | ||
| 560 | 562 | 切换项目只改变新终端和文件编辑器的起始位置;已有终端、网页和登录态会保留。 |
| 561 | 563 | </p> |
| 562 | 564 | <EnvironmentVersions status={status} onConfirm={onConfirm} /> |
| 565 | 新增: <ResourceSettings status={status} onConfirm={onConfirm} /> | |
| 566 | 新增: <DiagnosticSettings /> | |
| 563 | 567 | {status.can_restore && ( |
| 564 | 568 | <button |
| 565 | 569 | className="text-button" |
| @@ -118,6 +118,22 @@ export const RemoteView = forwardRef(function RemoteView( | ||
| 118 | 118 | return api("/browser/insert-text", { id, text }); |
| 119 | 119 | }); |
| 120 | 120 | }, |
| 121 | 新增: insertComposition: (id, value) => client.cageRunInput(async () => { | |
| 122 | 新增: if (value.mode !== "cancel" && (disposed || !current.current.visible || | |
| 123 | 新增: (desktop ? "desktop" : current.current.tabId) !== id)) | |
| 124 | 新增: throw new Error("输入位置已切换,请重新输入"); | |
| 125 | 新增: const result = await api("/input", { target: desktop ? "desktop" : "browser", id, ...value }); | |
| 126 | 新增: if (value.mode !== "cancel" && !result.available) | |
| 127 | 新增: throw new Error("输入位置已失去焦点,请重新输入"); | |
| 128 | 新增: return result; | |
| 129 | 新增: }), | |
| 130 | 新增: tabId: () => desktop ? "desktop" : current.current.tabId, | |
| 131 | 新增: caretRect: async (session) => { | |
| 132 | 新增: const id = desktop ? "desktop" : current.current.tabId; | |
| 133 | 新增: const value = await api("/input", { target: desktop ? "desktop" : "browser", id, mode: "status", session }); | |
| 134 | 新增: return !disposed && current.current.visible && | |
| 135 | 新增: (desktop ? "desktop" : current.current.tabId) === id ? value : null; | |
| 136 | 新增: }, | |
| 121 | 137 | mode: () => current.current.keyboard, |
| 122 | 138 | isActive: () => current.current.visible, |
| 123 | 139 | onStatus: (t) => current.current.onStatus(t), |
| @@ -1,12 +1,12 @@ | ||
| 1 | 1 | { |
| 2 | 2 | "name": "claude-cage-website", |
| 3 | 删除: "version": "0.1.3-alpha.2", | |
| 3 | 新增: "version": "0.1.4-alpha", | |
| 4 | 4 | "lockfileVersion": 3, |
| 5 | 5 | "requires": true, |
| 6 | 6 | "packages": { |
| 7 | 7 | "": { |
| 8 | 8 | "name": "claude-cage-website", |
| 9 | 删除: "version": "0.1.3-alpha.2", | |
| 9 | 新增: "version": "0.1.4-alpha", | |
| 10 | 10 | "license": "MIT", |
| 11 | 11 | "dependencies": { |
| 12 | 12 | "@fontsource-variable/inter": "^5.3.0", |
| @@ -1,7 +1,7 @@ | ||
| 1 | 1 | { |
| 2 | 2 | "name": "claude-cage-website", |
| 3 | 3 | "type": "module", |
| 4 | 删除: "version": "0.1.3-alpha.2", | |
| 4 | 新增: "version": "0.1.4-alpha", | |
| 5 | 5 | "private": true, |
| 6 | 6 | "description": "Claude Cage project website and macOS, Windows and Linux downloads", |
| 7 | 7 | "license": "MIT", |

