跳到主要内容

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

提交记录
修改CONTRIBUTING.md+2 −0看文件
@@ -79,6 +79,8 @@ go test github.com/containers/gvisor-tap-vsock/pkg/services/dns \
7979
8080建议使用独立测试配置和非敏感测试项目,避免将开发验证写入日常环境。启动前的 Git 保护检查属于主机状态:单独指定 Cage 配置目录不会隔离全局 Git 设置,测试修改路径时应使用隔离的测试用户目录。应用必须先解释影响,用户明确确认后才将 `safe.bareRepository` 设置为 `explicit`,并在复检通过后启动环境;读取状态不得修改 Git 配置。真实网络验证应区分代理连通、环境放行、浏览器访问、Claude 授权与模型请求,不能互相替代。
8181
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新增:
8284## 开发诊断
8385
8486配置与状态默认在 `~/.claude-cage/`。`CLAUDE_CAGE_CONFIG` 可以指向另一份私有配置,其父目录拥有独立状态。配置文件权限为 `0600`;不要把该目录作为共享项目或提交到 Git。
修改VERSION+1 −1看文件
@@ -1 +1 @@
1删除:0.1.3-alpha.2
1新增:0.1.4-alpha
修改cmd/cage/main.go+125 −3看文件
@@ -15,10 +15,16 @@ import (
1515 "github.com/sylvinus/agent-vm/internal/appupdate"
1616 "github.com/sylvinus/agent-vm/internal/cage"
1717 "github.com/sylvinus/agent-vm/internal/cli"
18新增: "github.com/sylvinus/agent-vm/internal/diagnostics"
1819 "github.com/sylvinus/agent-vm/internal/host"
1920 "github.com/sylvinus/agent-vm/internal/limaembed"
2021 "github.com/sylvinus/agent-vm/internal/managedproxy"
2122 "github.com/sylvinus/agent-vm/internal/workbench"
23新增: "io"
24新增: "os/signal"
25新增: "runtime/debug"
26新增: "sync"
27新增: "syscall"
2228)
2329
2430const help = `Claude Cage — local isolated Claude development
@@ -39,13 +45,26 @@ cage claude Run Claude Code in the shared environment
3945cage stop Stop the shared Cage environment
4046cage list List this cage profile's VMs
4147cage doctor Diagnose the VM
48新增:cage diagnostics --json PATH.zip Export a redacted diagnostic bundle
4249
4350Configuration: ~/.claude-cage/config.json (override CLAUDE_CAGE_CONFIG).
4451Each configuration directory is an independent cage profile.
4552Only explicitly opened project folders are shared. No host Claude credentials are imported.
4653`
4754
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新增:}
4968func run() int {
5069 // Apply this before desktop/serve dispatch: the control service and every
5170 // child process must keep Cage's isolation even when launched from a shell
@@ -74,6 +93,42 @@ func run() int {
7493 if err != nil {
7594 return fail(err)
7695 }
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新增: }
77132 if args[0] == "app-update" {
78133 return appupdate.Run(path, args[1:], os.Stdout)
79134 }
@@ -83,6 +138,7 @@ func run() int {
83138 }
84139 result, err := workbench.UploadHostFiles(path, args[2], args[3], args[4:])
85140 if err != nil {
141新增: diagnostics.Log("error", "command", err.Error())
86142 _ = json.NewEncoder(os.Stdout).Encode(map[string]string{"status": "error", "message": err.Error()})
87143 return 1
88144 }
@@ -99,6 +155,7 @@ func run() int {
99155 }
100156 result, err := workbench.BrowserFile(path, args[2], args[3], destination)
101157 if err != nil {
158新增: diagnostics.Log("error", "command", err.Error())
102159 _ = json.NewEncoder(os.Stdout).Encode(map[string]string{"status": "error", "message": err.Error()})
103160 return 1
104161 }
@@ -129,6 +186,7 @@ func run() int {
129186 entry, err := workbench.Desktop(path, options)
130187 if err != nil {
131188 if returnJSON {
189新增: diagnostics.Log("error", "command", err.Error())
132190 _ = json.NewEncoder(os.Stdout).Encode(map[string]string{"status": "error", "message": err.Error()})
133191 return 1
134192 }
@@ -163,6 +221,7 @@ func run() int {
163221 result, err := workbench.PrepareUpdate(path, stop)
164222 if err != nil {
165223 if returnJSON {
224新增: diagnostics.Log("error", "command", err.Error())
166225 _ = json.NewEncoder(os.Stdout).Encode(map[string]string{"status": "error", "message": err.Error()})
167226 return 1
168227 }
@@ -275,7 +334,8 @@ func run() int {
275334 if err = os.WriteFile(filepath.Join(state, "setup.sh"), []byte(cage.GuestSetup), 0600); err != nil {
276335 return fail(err)
277336 }
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:]...)
279339 }
280340 if args[0] == "up" || args[0] == "login" {
281341 result := cli.Main([]string{"run", "true"}, cli.Stdio())
@@ -317,7 +377,11 @@ func runGuestServiceStart(script string, stdio cli.IO, invoke func([]string, cli
317377 return invoke([]string{"run", "bash", "-s"}, stdio)
318378}
319379
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新增:}
321385
322386func openWorkbench(address string) error {
323387 if runtime.GOOS == "windows" {
@@ -329,3 +393,61 @@ func openWorkbench(address string) error {
329393 }
330394 return exec.Command(command, address).Run()
331395}
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新增:}
修改desktop/Cage.swift+32 −3看文件
@@ -2,10 +2,22 @@ import Cocoa
22import WebKit
33import UniformTypeIdentifiers
44
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新增:
516@main
617final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNavigationDelegate, WKUIDelegate, WKScriptMessageHandlerWithReply {
718 private var window: NSWindow!
819 private var webView: WKWebView!
20新增: private var nativeInput: CageNativeInput!
921 private var accountDeviceBusy = false
1022 private var expectedPort = 0
1123 private var allowQuit = false
@@ -27,6 +39,7 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga
2739 }
2840
2941 static func main() {
42新增: NSSetUncaughtExceptionHandler { exception in CageDiagnostics.record("Uncaught native exception: \(exception.name.rawValue): \(exception.reason ?? "")\n\(exception.callStackSymbols.joined(separator: "\n"))") }
3043 let app = NSApplication.shared
3144 let delegate = CageApp()
3245 app.delegate = delegate
@@ -50,6 +63,7 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga
5063 let config = WKWebViewConfiguration()
5164 config.websiteDataStore = .default()
5265 config.userContentController.addScriptMessageHandler(self, contentWorld: .page, name: "cage")
66新增: config.userContentController.addUserScript(WKUserScript(source: "window.cageNativeIMEAvailable = true;", injectionTime: .atDocumentStart, forMainFrameOnly: true))
5367 webView = WKWebView(frame: .zero, configuration: config)
5468 webView.navigationDelegate = self
5569 webView.uiDelegate = self
@@ -65,6 +79,9 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga
6579 backdrop.state = .followsWindowActiveState
6680 content.addSubview(backdrop)
6781 content.addSubview(webView)
82新增: nativeInput = CageNativeInput(frame: .zero)
83新增: nativeInput.configure(web: webView)
84新增: content.addSubview(nativeInput)
6885 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)])
6986 loading = NSTextField(labelWithString: "正在启动 Cage 工作台…")
7087 loading.font = NSFont.systemFont(ofSize: 16, weight: .medium)
@@ -92,6 +109,7 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga
92109 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)])
93110 applyAppearance(appearance)
94111 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")) }
95113 guard let data = try? JSONSerialization.data(withJSONObject: state), let json = String(data: data, encoding: .utf8) else { return }
96114 self?.webView.evaluateJavaScript("window.dispatchEvent(new CustomEvent('cage-app-update',{detail:\(json)}));", completionHandler: nil)
97115 }, 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
241259 let data = output.fileHandleForReading.readDataToEndOfFile(); process.waitUntilExit()
242260 guard data.count <= 65536, let result = try JSONSerialization.jsonObject(with: data) as? [String:Any] else { throw CageUpdateError("文件操作未返回有效结果") }
243261 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) } }
245263 }
246264 }
247265 private func rememberFiles(_ urls: [URL]) throws -> [String: Any] {
@@ -259,7 +277,7 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga
259277 fileSelections[id] = (urls.map(\.path), now.addingTimeInterval(600))
260278 return ["fileSelection": id, "count": urls.count]
261279 }
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 }
263281 private func applyAppearance(_ value: [String:Any]) {
264282 let mode = value["mode"] as? String ?? "system"
265283 NSApp.appearance = mode == "system" ? nil : NSAppearance(named: mode == "dark" ? .darkAqua : .aqua)
@@ -273,7 +291,7 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga
273291 }
274292 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() }
275293 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() }
277295 func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
278296 guard let url = navigationAction.request.url, url.scheme == "http", url.host == "localhost", url.port == expectedPort else { decisionHandler(.cancel); return }
279297 decisionHandler(.allow)
@@ -282,6 +300,8 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga
282300 let origin = message.frameInfo.securityOrigin
283301 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 }
284302 switch action {
303新增: case "remoteInput":
304新增: replyHandler(nativeInput.handle(body), nil)
285305 case "accountDevice":
286306 guard !controllerNeedsUpdate, !accountDeviceBusy,
287307 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
301321 }
302322 }
303323 }
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新增: }
304333 case "workbenchReady":
305334 guard !controllerNeedsUpdate else { replyHandler(nil,"后台版本尚未同步,更新未完成"); return }
306335 appUpdater?.markLaunchReady()
新增desktop/NativeInput.swift+174 −0看文件
@@ -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新增:}
新增desktop/NativeInputTests.swift+42 −0看文件
@@ -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新增:}
修改desktop/linux/cage-desktop.c+47 −6看文件
@@ -8,6 +8,8 @@
88#include <string.h>
99#include <stdlib.h>
1010#include <sys/stat.h>
11新增:#include <math.h>
12新增:#include "native-input.h"
1113
1214#ifndef CAGE_VERSION
1315#define CAGE_VERSION "development"
@@ -60,6 +62,28 @@ static char *quote(const char *value) {
6062 json_node_free(node);
6163 return result;
6264}
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新增:}
6387static gboolean valid_workbench(const char *raw, int expected_port, gboolean entry) {
6488 if (!raw) return FALSE;
6589 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
111135 if (g_subprocess_communicate_utf8_finish(G_SUBPROCESS(source), result, &output, NULL, &error)) {
112136 if (!output || strlen(output) > 65536 || !json_parser_load_from_data(parser, output, -1, NULL) ||
113137 !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/。");
115139 } else {
116140 object = json_node_get_object(json_parser_get_root(parser));
117141 if (!g_subprocess_get_successful(command->process)) {
118142 const char *message = text_member(object, "message");
119143 g_set_error_literal(&error, G_IO_ERROR, G_IO_ERROR_FAILED,
120删除: *message ? message : "Cage 后台操作失败,请查看 control.log。");
144新增: *message ? message : "Cage 后台操作失败,请查看 logs/。");
121145 }
122146 }
123147 }
@@ -188,6 +212,7 @@ static gboolean quit_idle(gpointer data) {
188212 return G_SOURCE_REMOVE;
189213}
190214static void show_error(const char *message) {
215新增: diagnostic_event(message);
191216 gtk_label_set_text(GTK_LABEL(app.status), message);
192217 gtk_stack_set_visible_child_name(GTK_STACK(app.stack), "status");
193218 gtk_widget_show(app.retry);
@@ -219,8 +244,9 @@ static char *choose_file(GtkFileChooserAction kind, const char *title, const cha
219244 }
220245 if (kind != GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER) {
221246 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");
224250 gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(dialog), filter);
225251 }
226252 char *path = gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT
@@ -494,7 +520,20 @@ static gboolean bridge_received(WebKitUserContentManager *manager, JSCValue *val
494520 JsonObject *request = json_node_get_object(request_node);
495521 const char *name = text_member(request, "action");
496522 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")) {
498537 if (app.needs_update) reply_error(reply, "后台版本尚未同步,更新未完成。");
499538 else {
500539 app.ready = TRUE;
@@ -673,7 +712,7 @@ static void install_bridge(void) {
673712 char *token = quote(app.token);
674713 char *code = g_strdup_printf(
675714 "(()=>{'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{"
677716 "const transport=window.webkit.messageHandlers.cageTransport;const token=%s;"
678717 "const cage=Object.freeze({postMessage(request){return transport.postMessage({token,request});}});"
679718 "Object.defineProperty(window.webkit.messageHandlers,'cage',{value:cage,writable:false,configurable:false});"
@@ -869,6 +908,7 @@ static void create_window(void) {
869908 g_signal_connect(app.content, "script-message-with-reply-received::cageTransport", G_CALLBACK(bridge_received), NULL);
870909 webkit_user_content_manager_register_script_message_handler_with_reply(app.content, "cageTransport", NULL);
871910 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);
872912 g_object_unref(context);
873913 WebKitSettings *web_settings = webkit_web_view_get_settings(app.web);
874914 webkit_settings_set_enable_developer_extras(web_settings, FALSE);
@@ -958,6 +998,7 @@ int main(int argc, char **argv) {
958998 app.profile = configured && *configured ? g_canonicalize_filename(configured, NULL)
959999 : g_build_filename(g_get_home_dir(), ".claude-cage", "config.json", NULL);
9601000 g_setenv("CLAUDE_CAGE_CONFIG", app.profile, TRUE);
1001新增: g_log_set_default_handler(diagnostic_glib, NULL);
9611002 if (!prepare_web_storage()) {
9621003 g_printerr("无法创建 Cage 私有界面数据目录,请检查配置目录的所有者、权限或符号链接。\n");
9631004 return 1;
新增desktop/linux/native-input.h+132 −0看文件
@@ -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新增:}
修改desktop/windows/Backend.cs+14 −0看文件
@@ -63,6 +63,20 @@ internal static class Backend
6363 var buffer = new char[4096];
6464 while (await reader.ReadAsync(buffer.AsMemory(), token) > 0) { }
6565 }
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新增: }
6680 public static string Text(this JsonElement data, string name) =>
6781 data.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String ? value.GetString()! : "";
6882}
修改desktop/windows/MainWindow.cs+20 −1看文件
@@ -7,6 +7,7 @@ namespace Cage.Windows;
77internal sealed class MainWindow : Form
88{
99 private WebView2 web = new() { Dock = DockStyle.Fill, Visible = false };
10新增: private readonly NativeInput nativeInput;
1011 private readonly Label message = new() { AutoSize = true, MaximumSize = new Size(720, 0), Text = "正在启动 Cage 工作台…", Margin = new Padding(12) };
1112 private readonly FlowLayoutPanel status = new() { Dock = DockStyle.Fill, FlowDirection = FlowDirection.TopDown, Padding = new Padding(48), WrapContents = false };
1213 private readonly Button retry = new() { Text = "重试连接", AutoSize = true, Visible = false };
@@ -21,6 +22,7 @@ internal sealed class MainWindow : Form
2122
2223 public MainWindow()
2324 {
25新增: nativeInput = new NativeInput(value => Script("window.dispatchEvent(new CustomEvent('cage-native-input',{detail:" + JsonSerializer.Serialize(value) + "}));"));
2426 Text = "Cage"; Width = 1280; Height = 850; MinimumSize = new Size(820, 580);
2527 StartPosition = FormStartPosition.CenterScreen; BackColor = Color.FromArgb(247, 247, 247);
2628 Icon = Icon.ExtractAssociatedIcon(Environment.ProcessPath!) ?? SystemIcons.Application;
@@ -40,6 +42,7 @@ internal sealed class MainWindow : Form
4042 menus.Items.AddRange([file, settings, help]); MainMenuStrip = menus;
4143 status.Controls.AddRange([message, retry, existing, complete]);
4244 Controls.Add(web); Controls.Add(status); Controls.Add(menus);
45新增: Controls.Add(nativeInput);
4346 retry.Click += async (_, _) => {
4447 if (webFailed || web.CoreWebView2 == null) await Initialize(true); else await Bootstrap();
4548 };
@@ -79,7 +82,10 @@ internal sealed class MainWindow : Form
7982 }
8083 private void Action(string name) => Script("window.cageNativeAction?.(" + JsonSerializer.Serialize(name) + ")");
8184 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新增: }
8389 private async void Script(string script)
8490 {
8591 if (web.CoreWebView2 == null || IsDisposed) return;
@@ -89,6 +95,7 @@ internal sealed class MainWindow : Form
8995 }
9096 private void Error(string text)
9197 {
98新增: _ = Backend.Report(text);
9299 message.Text = text; status.Show(); status.BringToFront(); retry.Show(); web.Hide();
93100 }
94101
@@ -214,6 +221,16 @@ internal sealed class MainWindow : Form
214221 object? result;
215222 switch (request.Text("action"))
216223 {
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;
217234 case "workbenchReady":
218235 if (controllerNeedsUpdate) throw new IOException("后台版本尚未同步,更新未完成");
219236 updater.MarkReady(); result = true; _ = CompleteSmoke(); break;
@@ -317,6 +334,7 @@ internal sealed class MainWindow : Form
317334 }
318335 catch (Exception error)
319336 {
337新增: _ = Backend.Report(error.ToString());
320338 if (id.Length != 0 && !IsDisposed) web.CoreWebView2.PostWebMessageAsJson(JsonSerializer.Serialize(new { id, error = error.Message }));
321339 }
322340 }
@@ -324,6 +342,7 @@ internal sealed class MainWindow : Form
324342 private const string BridgeScript = """
325343 (() => {
326344 if (window !== window.top || location.protocol !== 'http:' || location.hostname !== 'localhost') return;
345新增: window.cageNativeIMEAvailable = true;
327346 const pending = new Map();
328347 chrome.webview.addEventListener('message', ({data}) => {
329348 const item = pending.get(data.id); if (!item) return;
新增desktop/windows/NativeInput.cs+207 −0看文件
@@ -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新增:}
修改desktop/windows/Program.cs+7 −0看文件
@@ -19,6 +19,13 @@ internal static class Program
1919 if (File.Exists(output)) File.Delete(output);
2020 }
2121 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());
2229 ApplicationConfiguration.Initialize();
2330 if (RuntimeInformation.OSArchitecture != Architecture.X64 || Environment.OSVersion.Version.Build < 19045)
2431 {
修改docs/README.md+4 −0看文件
@@ -13,6 +13,7 @@
1313| 升级应用、更新环境工具或卸载 | [升级与卸载](getting-started.md#升级与卸载) |
1414| 查看首个内测版本的能力与验收范围 | [0.1.0-alpha.1 发行说明](releases/0.1.0-alpha.1.md) |
1515| 排查下载、启动、联网与授权问题 | [常见问题与恢复](troubleshooting.md) |
16新增:| 导出故障日志并了解自动清理 | [导出诊断包](troubleshooting.md#导出诊断包) |
1617| 报告隔离或凭据安全问题 | [安全报告](../SECURITY.md) |
1718
1819## 开发与发布
@@ -21,8 +22,11 @@
2122|---|---|
2223| 从源码构建、修改和验证代码 | [参与开发](../CONTRIBUTING.md) |
2324| 理解工作台、浏览器与后台的职责 | [工作台设计](design/workbench.md) |
25新增:| 评估主机输入法、原位拼音与候选窗跟随 | [原生输入法研究](research/2026-11-04-native-ime.md) |
2426| 定位作业、终端、浏览器连接与退出流程的代码 | [控制服务职责](design/control-service.md) |
2527| 理解网络检查、暂停与恢复 | [网络检查设计](design/network-checks.md) |
28新增:| 理解内存回收、CPU 上限与压力后的联网恢复 | [计算资源](design/resources.md) |
29新增:| 理解日志脱敏、清理与诊断接口 | [日志与诊断](design/diagnostics.md) |
2630| 理解节点配置、代理核心与凭据归属 | [内置代理设计](design/managed-proxy.md) |
2731| 构建签名、公证的 macOS 安装包 | [发布 macOS 安装包](releasing.md) |
2832| 构建 Windows 安装包与执行平台验收 | [Windows 构建与验收](windows.md#维护者构建与验收) |
新增docs/design/diagnostics.md+62 −0看文件
@@ -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新增:客机日志配置随环境组件更新部署。已有运行环境需先保存浏览器和编辑器中的修改,再使用现有的组件更新流程;应用不会为启用日志而静默重启环境。
修改docs/design/network-checks.md+2 −0看文件
@@ -54,6 +54,8 @@ VM 外出站控制由 hostagent 持有。新实例默认关闭外网,guest 内
5454
5555全面检查报告最多有效 24 小时。配置变化、VM 重启和新一轮检查会使旧授权失效;检测过程中产生的旧报告不能重新打开已经关闭的网络。后台监测不自行重复故障演练。
5656
57新增:临时观察失败、代理探测失败或授权续期失败后,环境先保持离线,再由独立恢复任务重新执行完整检查;全部关键项通过后恢复联网。失败采用最长五分钟的退避,已知内存压力持续时延后重检。恢复绑定当前 VM、配置、授权代次和人工暂停序号,手动暂停、停止或新检查会使旧请求作废;已确认的配置不匹配不会作为临时故障恢复。见[计算资源与压力恢复](resources.md)。
58新增:
5759暂停不进入普通任务队列,会立即取消检查和后台监测,再关闭出站。放行和续期与暂停串行核对,已撤销的检查不能重新放行。停止环境可取消正在启动或检查的任务;被取消任务的完成消息不会覆盖停止结果。工作台为启动任务记录私有停止标记,分离运行的 hostagent 在初始化前及运行中读取该标记,避免取消后的后台启动继续拉起 VM。标记绑定单个任务,不影响下一次启动。
5860
5961人工暂停意图和暂停序号保存在私有 `network-intent.json`,控制服务启动监测前恢复;后台重启、订阅定期刷新和网卡恢复不会解除暂停。记录缺失时无法判断旧配置的暂停意图,因此默认关闭,等待用户明确恢复;损坏或无法读取时同样保持关闭并提示原因。启动、重检、恢复或应用环境配置,以及手动应用代理配置,可请求恢复;恢复必须先成功保存,且不能覆盖请求提交之后发生的暂停。暂停保存失败仍会撤销当前放行并报错,恢复保存失败也保持关闭。
新增docs/design/resources.md+57 −0看文件
@@ -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):压缩块设备、动态创建和交换区启用。
修改docs/design/workbench.md+16 −0看文件
@@ -65,12 +65,28 @@ Desktop 使用编码用户 `cage`、独立的 X11 显示 `:78` 与按需启动
6565
6666项目旁的加号、终端工具栏与新建终端快捷键均打开类型选择框。普通终端提供 shell;Claude 终端在所选项目中新建交互 shell,并运行设置中的启动命令,默认 `claude`。命令支持参数及单行 shell 表达式,仅在客机执行;退出 Claude 后返回 shell。命令保存在私有 `workbench.json` 的 `claude_terminal_command` 字段,留空恢复默认,拒绝换行、NUL 和超过 4096 字节的输入。保存不重启环境,也不修改现有终端;刷新或重连不会重复执行启动命令。
6767
68新增:浏览器将 `claude://` 链接成功转交给正在运行的 Claude Desktop 后,工作台自动显示 Claude Desktop。转交失败时保持当前页面;该通知只表示应用接收了链接,登录是否成功由 Claude 自身显示。客机打开链接的脚本通过浏览器服务的认证接口 `/desktop-focus` 发送通知,现有浏览器事件流以 `desktopFocus: true` 传递一次切换请求。通知不包含回调链接和登录凭据,不保存在浏览器状态中,重连或普通状态更新不会重新触发切换。三个主机平台共用此链路。
69新增:
6870应用状态与操作由 `/api/claude-desktop`、`/api/claude-desktop/{install,start,stop}` 提供;安装和启动沿用工作台异步任务。`POST /api/terminals` 的 `kind` 可为 `shell` 或 `claude`,省略时保持普通终端行为。原始启动命令不从新建终端请求接收,只读取已保存偏好。
6971
7072Desktop 默认按内容区域的逻辑像素显示,窗口尺寸和侧栏变化会同步调整虚拟屏幕。工具栏的“显示大小”提供 75%、90%、100%、110%、125% 和 150%,默认 100%;较小的值可显示更多内容,较大的值放大文字和控件。偏好保存在当前工作台的本机存储中,调整立即生效,保持应用和画面连接。
7173
74新增:尺寸调整与其他客机控制脚本共用 SSH 执行入口,在客机内明确使用 `/bin/bash --noprofile --norc -c`。SSH 登录仍经过用户的默认 shell,控制脚本的重定向和错误处理由 Bash 执行,避免 zsh 中的 mise 初始化状态使尺寸锁创建提前返回失败。脚本整体经过 shell 引号转义,三个主机平台共用同一执行方式。
75新增:
7276应用以 `--force-device-scale-factor=2` 启动;虚拟屏幕宽高为内容区域的 CSS 尺寸乘以 `2 / 显示大小`,noVNC 将画面等比适配回内容区域。虚拟屏幕每边最多 8192 像素,超过上限时按同一比例缩减宽高。尺寸提交串行执行,快速调整窗口时以最新尺寸为准;失败后最多自动重试三次,持续失败显示“重试调整”。macOS、Windows 与 Linux 共用此显示链路。应用启动缩放参数在下次打开应用时生效,工具栏的显示大小无需重启。
7377
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新增:
7490## 声音输出
7591
7692浏览器、Claude Desktop 和环境内其他程序的声音通过工作台在本机播放,输出设备由本机系统选择。底部提供静音和音量控制,偏好保存在当前工作台的本地存储中。首次播放如果受到 WebView 自动播放限制,点击页面或“启用声音”即可继续。切换标签、项目或设置页保持声音;静音、停止环境、锁定账户及退出应用关闭播放连接,重新连接从当前声音开始。
新增docs/research/2026-11-04-native-ime.md+80 −0看文件
@@ -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 中的适用范围仍需实测。
修改docs/troubleshooting.md+19 −1看文件
@@ -2,6 +2,14 @@
22
33先找到你当前遇到的现象。修复后优先使用页面中的重试、重检或恢复入口;删除配置会丢失诊断线索,也可能影响虚拟磁盘,不作为常规排障步骤。
44
5新增:## 任务退出 137 或重任务后内部断网
6新增:
7新增:137 通常表示进程被强制终止,单凭退出码不能判断是否内存不足。到“设置 → 环境与恢复 → 计算资源”查看本次环境启动后的 OOM 计数、内存上限和用量,再导出诊断日志。OOM 计数增加可确认客机曾因内存不足终止进程;没有增加时还需排查超时、任务取消或其他强制终止来源。
8新增:
9新增:自动资源管理会在启动容量内增长和回收内存。运行中的旧环境如仍使用较小上限,可以先保存内容,再点击“重启并应用自动资源配置”;重启会结束运行中的命令。达到上限后应降低渲染或编译并行量,自动管理无法让有限内存承载无限任务。
10新增:
11新增:重任务可能让客机或浏览器无法及时响应联网检查,触发 Cage 收回内部外网授权。恢复任务会自动进行完整复检,检查全部通过才恢复;手动暂停不会自动解除。网络仍未恢复时,查看具体失败项、所选代理和出口规则,不要仅凭断网现象判断主机网络故障。资源指标与平台范围见[计算资源说明](design/resources.md)。
12新增:
513## 下载或安装受阻
614
715**GitHub 显示 404,或看不到安装包。** 仓库与公开发布的附件无需仓库授权。从[项目主页](https://lee-xeo.github.io/Claude-Cage/#download)点击“下载应用”并选择平台,检查网络与链接是否完整。macOS 使用 `.dmg`,Windows 使用 `.exe` 安装器,Debian/Ubuntu Linux 使用 `.deb`。Release 中的源码压缩包用于开发,不能当作安装包使用;尚无公开安装包的平台会提供安装与构建说明。
@@ -75,6 +83,8 @@ Cage 需要先选择自己的代理。首次首页点击“配置网络与代理
7583
7684先将右上角“显示大小”设为 100%,窗口和侧栏变化时画面会自动适配。若需要更多内容空间,可选择 90% 或 75%。出现“画面尺寸未能同步”时点击“重试调整”;仍未恢复时保存工作、关闭 Claude Desktop 后重新打开,使当前环境的应用缩放参数生效。
7785
86新增:旧构建的尺寸控制脚本可能受到客机 zsh 中 mise 初始化的影响,持续返回尺寸调整失败。此时需要使用包含控制脚本修正的 Cage 构建。该修正兼容已有客机配置,在控制入口明确选择脚本解释器。复现条件和验证范围见[尺寸调整排查记录](test-reports/2026-11-04-desktop-resize/README.md)。
87新增:
7888## Claude 登录或请求失败
7989
8090Cage 不自动读取主机上的 Claude 登录。请在 Cage 终端运行 `claude`,按提示在 Cage 浏览器中完成授权;需要手动打开时复制完整授权链接到 Cage 地址栏。
@@ -101,8 +111,16 @@ Cage 不自动读取主机上的 Claude 登录。请在 Cage 终端运行 `claud
101111
102112节点列表、当前选择和实际出口统一由 Cage 的代理管理器维护。未配置、未应用或核心停止时,外网保持关闭。若列表与实际联网状态不一致,请在诊断页重新应用当前节点并检查报告;不要修改生成的本地出口地址或启动其他代理程序占用 Cage 端口。
103113
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新增:
104122## 提交问题时提供什么
105123
106删除:在 [GitHub Issues](https://github.com/Lee-xeo/Claude-Cage/issues) 提供 Cage 版本、操作系统版本、处理器架构、操作步骤、期望结果、实际错误及发生阶段。可以附裁剪后的状态截图或经过检查的日志片段。
124新增:在 [GitHub Issues](https://github.com/Lee-xeo/Claude-Cage/issues) 提供 Cage 版本、操作系统版本、处理器架构、操作步骤、期望结果、实际错误及发生阶段。可以附裁剪后的状态截图或经过检查的诊断包。
107125
108126不要上传整个 `~/.claude-cage/`、完整代理配置、订阅链接、账户令牌、授权 URL、项目内容或未检查的诊断输出。网络报告可能包含出口 IP,截图也可能包含项目路径,分享前请按需要遮盖。涉及凭据泄露或隔离绕过的问题,请先使用仓库提供的私密安全报告入口。
修改internal/cage/browser-agent.mjs+14 −2看文件
@@ -6,6 +6,7 @@ import { readFileSync, writeFileSync, mkdirSync, existsSync, rmSync, constants }
66import { open } from "node:fs/promises";
77import http from "node:http";
88import { auditBrowser } from "./browser-audit.mjs";
9新增:import { nativeInput } from "./native-input.mjs";
910import { DownloadManager } from "./browser-downloads.mjs";
1011import { UploadManager, uploadLimit } from "./browser-uploads.mjs";
1112import { timingSafeEqual } from "node:crypto";
@@ -323,9 +324,9 @@ function publicState() {
323324 })),
324325 };
325326}
326删除:function broadcastState(focus = false) {
327新增:function broadcastState(focus = false, desktopFocus = false) {
327328 const payload =
328删除: "data: " + JSON.stringify({ ...publicState(), focus }) + "\n\n";
329新增: "data: " + JSON.stringify({ ...publicState(), focus, desktopFocus }) + "\n\n";
329330 for (const stream of events) stream.write(payload);
330331}
331332setInterval(() => {
@@ -461,6 +462,11 @@ const server = http.createServer(async (req, res) => {
461462 if (text.length > (req.url === "/paste-image" ? 28 * 1024 * 1024 : 65536)) throw new Error("Request too large");
462463 }
463464 const input = JSON.parse(text || "{}");
465新增: if (req.url === "/desktop-focus") {
466新增: broadcastState(false, true);
467新增: res.end('{"ok":true}');
468新增: return;
469新增: }
464470 if (req.url === "/upload-start" || req.url === "/upload-finish") {
465471 const result = await mutate(async () => {
466472 const tabId = req.url === "/upload-start" ? input.id : uploads.request(input.id).tabId;
@@ -500,6 +506,12 @@ const server = http.createServer(async (req, res) => {
500506 if (req.url === "/new") return newTab(input.url || undefined);
501507 if (req.url === "/editor") return editor(input.workspace || config.workspace);
502508 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新增: }
503515 const id = input.id || activeId;
504516 if (!targets.has(id)) throw new Error("Tab no longer exists");
505517 switch (req.url) {
修改internal/cage/claude-desktop-install.sh+1 −1看文件
@@ -12,7 +12,7 @@ printf '正在准备安装依赖…\n'
1212sudo env DEBIAN_FRONTEND=noninteractive APT_CONFIG="${CAGE_APT_CONFIG:-/dev/null}" apt-get -o DPkg::Lock::Timeout=60 update </dev/null
1313# Satisfy the vendor's kde-cli-tools | ... | libglib2.0-bin dependency before
1414# 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
1616temporary=$(mktemp -d)
1717trap 'rm -rf "$temporary"' EXIT
1818printf '正在验证 Anthropic 安装源…\n'
修改internal/cage/claude-desktop-session.sh+1 −1看文件
@@ -56,7 +56,7 @@ for i in $(seq 1 100); do
5656done
5757test -S "$XDG_RUNTIME_DIR/files.sock"
5858export 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 &
6060app_pid=$!
6161# The service becomes ready only after the application has opened a window.
6262for i in $(seq 1 200); do
修改internal/cage/claude_desktop.go+3 −2看文件
@@ -28,7 +28,7 @@ func ClaudeDesktopInstallScript() string {
2828// Provisioning is independent of the browser and never restarts it. Desktop
2929// services are deliberately not enabled at boot: the user opens the app.
3030func ClaudeDesktopProvisionScript() string {
31删除: return "set -euo pipefail\n" + fileInputScript() +
31新增: return "set -euo pipefail\n" + nativeInputScript() + fileInputScript() +
3232 "sudo install -d -m 0755 /etc/claude-cage\n" +
3333 "sudo tee /usr/local/bin/cage-claude-session >/dev/null <<'CAGE_CLAUDE_SESSION'\n" + claudeDesktopSession + "\nCAGE_CLAUDE_SESSION\n" +
3434 "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
5656EnvironmentFile=/etc/claude-cage/environment
5757RuntimeDirectory=cage-desktop
5858RuntimeDirectoryMode=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
6061KillMode=control-group
6162TimeoutStartSec=45
6263TimeoutStopSec=20
修改internal/cage/claude_desktop_test.go+78 −0看文件
@@ -1,6 +1,9 @@
11package cage
22
33import (
4新增: "encoding/json"
5新增: "net/http"
6新增: "net/http/httptest"
47 "os"
58 "os/exec"
69 "path/filepath"
@@ -8,6 +11,81 @@ import (
811 "testing"
912)
1013
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新增:
1189func TestClaudeDesktopInstallerRejectsUntrustedKey(t *testing.T) {
1290 dir := t.TempDir()
1391 commands := map[string]string{
修改internal/cage/guest-audio.sh+2 −1看文件
@@ -29,7 +29,8 @@ Environment=PULSE_RUNTIME_PATH=/run/cage-audio/runtime
2929Environment=PULSE_STATE_PATH=/run/cage-audio/state
3030RuntimeDirectory=cage-audio
3131RuntimeDirectoryMode=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
3334Restart=on-failure
3435RestartSec=1
3536TimeoutStopSec=5
新增internal/cage/guest-memory.sh+39 −0看文件
@@ -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
修改internal/cage/guest-open.sh+9 −4看文件
@@ -1,13 +1,18 @@
11#!/bin/sh
22set -eu
33case "${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" ;;
611 *) echo 'Only HTTP(S) browser URLs and Claude desktop callbacks are accepted.' >&2; exit 2;;
712esac
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'
914import {readFileSync} from 'node:fs';
1015const {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]}:{})});
1217if(!response.ok)process.exit(1);
1318NODE
修改internal/cage/guest-services.sh+14 −8看文件
@@ -3,8 +3,8 @@
33if systemctl is-active --quiet cage-webvnc; then
44 sudo systemctl stop cage-webvnc
55fi
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
88fi
99sudo install -d -m 0755 /etc/claude-cage /usr/local/lib
1010sudo tee /usr/local/bin/cage-editor-start >/dev/null <<'SCRIPT'
@@ -22,7 +22,8 @@ User=cage
2222WorkingDirectory=/home/cage
2323Environment=HOME=/home/cage
2424EnvironmentFile=/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
2627Restart=on-failure
2728RestartSec=2
2829TimeoutStopSec=15
@@ -47,7 +48,8 @@ Description=Claude Cage virtual browser display
4748[Service]
4849User=cage-browser
4950ExecStartPre=/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
5153Restart=on-failure
5254UNIT
5355sudo tee /etc/claude-cage/openbox.xml >/dev/null <<'WINDOW_CONFIG'
@@ -67,7 +69,8 @@ After=cage-display.service
6769[Service]
6870User=cage-browser
6971Environment=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
7174Restart=on-failure
7275UNIT
7376sudo tee /etc/systemd/system/cage-browser.service >/dev/null <<'UNIT'
@@ -79,7 +82,8 @@ After=cage-display.service cage-window-manager.service
7982User=cage-browser
8083Environment=DISPLAY=:77
8184EnvironmentFile=/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
8387# Let the controller close Chromium and flush its tabs and profile before
8488# systemd terminates any remaining child processes.
8589KillMode=mixed
@@ -93,7 +97,8 @@ Requires=cage-display.service
9397After=cage-display.service
9498[Service]
9599User=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
97102Restart=on-failure
98103RestartSec=2
99104UNIT
@@ -104,7 +109,8 @@ Requires=cage-vnc.service
104109After=cage-vnc.service
105110[Service]
106111User=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
108114Restart=on-failure
109115UNIT
110116sudo systemctl daemon-reload
修改internal/cage/guest.go+40 −2看文件
@@ -9,6 +9,7 @@ import (
99 "strings"
1010 "sync"
1111
12新增: "github.com/sylvinus/agent-vm/internal/diagnostics"
1213 "github.com/sylvinus/agent-vm/internal/version"
1314)
1415
@@ -21,6 +22,9 @@ var guestServices string
2122//go:embed guest-audio.sh
2223var guestAudio string
2324
25新增://go:embed guest-memory.sh
26新增:var guestMemory string
27新增:
2428//go:embed novnc-patch.py
2529var novncPatch string
2630
@@ -51,16 +55,32 @@ var imageInput string
5155//go:embed desktop-files.py
5256var desktopFiles string
5357
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新增:
5474func fileInputScript() string {
5575 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"
5676}
5777
5878func 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"
6080}
6181
6282func 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'
6484from pathlib import Path
6585import re
6686p = Path("/usr/share/novnc/vnc.html")
@@ -163,3 +183,21 @@ func (m GuestManifest) Current() bool {
163183 required := RequiredGuestManifest()
164184 return m.Protocol == required.Protocol && m.Revision == required.Revision
165185}
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新增:}
新增internal/cage/native-ime-session.sh+72 −0看文件
@@ -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"
新增internal/cage/native-ime.py+327 −0看文件
@@ -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()
新增internal/cage/native-input.mjs+50 −0看文件
@@ -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新增:}
修改internal/cage/novnc-patch.py+14 −0看文件
@@ -140,6 +140,14 @@ replace_once(''' sendKey(keysym, code, down) {
140140replace_once(''' this.sendKey(keysym, code, true);
141141 this.sendKey(keysym, code, false);''', ''' this._cageSendKey(keysym, code, true);
142142 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];''')
143151replace_once(''' _sendMouse(x, y, mask) {''', ''' _sendMouse(x, y, mask) {
144152 if (this._cageInputChain) {
145153 this._cageQueueInput(() => this._cageSendMouse(x, y, mask));
@@ -168,10 +176,16 @@ replace_once(''' if (!(flags & (1<<31))) {
168176 if (payload.startsWith('cage-input-')) return true;
169177 const job = this._cagePasteJob;
170178 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);
171184 this._cageSendKey(0xffe3, 'ControlLeft', true);
172185 this._cageSendKey(0x76, 'KeyV', true);
173186 this._cageSendKey(0x76, 'KeyV', false);
174187 this._cageSendKey(0xffe3, 'ControlLeft', false);
188新增: for (const [code, sym] of modifiers) this._cageSendKey(sym, code, true);
175189 job.phase = 'keys';
176190 RFB.messages.clientFence(this._sock, (1 << 31) | 1, job.id + '-keys');
177191 return true;
新增internal/cage/resources.go+323 −0看文件
@@ -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新增:}
新增internal/cage/resources_test.go+108 −0看文件
@@ -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新增:}
修改internal/cli/setup.go+9 −2看文件
@@ -12,6 +12,7 @@ import (
1212
1313 agentvm "github.com/sylvinus/agent-vm"
1414 "github.com/sylvinus/agent-vm/internal/cage"
15新增: "github.com/sylvinus/agent-vm/internal/diagnostics"
1516 "github.com/sylvinus/agent-vm/internal/env"
1617 "github.com/sylvinus/agent-vm/internal/host"
1718 "github.com/sylvinus/agent-vm/internal/state"
@@ -431,7 +432,13 @@ func (e *app) buildBase(ctx context.Context, in install, disk, memory, cpus int)
431432 return 1
432433 }
433434 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新增: }
435442 if err != nil {
436443 fmt.Fprintf(e.io.Stderr, "Error: %v\n", err)
437444 return 1
@@ -445,7 +452,7 @@ func (e *app) buildBase(ctx context.Context, in install, disk, memory, cpus int)
445452 win.Close()
446453 if err != nil {
447454 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) == "" {
449456 fmt.Fprint(e.io.Stderr, ui.Tail(logPath, 20))
450457 }
451458 return false
新增internal/diagnostics/diagnostics_test.go+269 −0看文件
@@ -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新增:}
新增internal/diagnostics/export.go+80 −0看文件
@@ -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新增:}
新增internal/diagnostics/guest.go+50 −0看文件
@@ -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 }
新增internal/diagnostics/legacy.go+61 −0看文件
@@ -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新增:}
新增internal/diagnostics/lock_unix.go+11 −0看文件
@@ -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) }
新增internal/diagnostics/lock_windows.go+13 −0看文件
@@ -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新增:}
新增internal/diagnostics/redact.go+33 −0看文件
@@ -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新增:}
新增internal/diagnostics/store.go+234 −0看文件
@@ -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新增:}
新增internal/diagnostics/stream.go+79 −0看文件
@@ -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新增:}
新增internal/host/memory_darwin.go+9 −0看文件
@@ -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新增:}
新增internal/host/memory_linux.go+29 −0看文件
@@ -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新增:}
新增internal/host/memory_other.go+5 −0看文件
@@ -0,0 +1,5 @@
1新增://go:build !darwin && !linux && !windows
2新增:
3新增:package host
4新增:
5新增:func MemoryPressure() bool { return false }
新增internal/host/memory_windows.go+8 −0看文件
@@ -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新增:}
修改internal/limaembed/limaembed.go+24 −0看文件
@@ -4,6 +4,7 @@
44package limaembed
55
66import (
7新增: "context"
78 "os"
89 "path/filepath"
910 "runtime"
@@ -12,15 +13,20 @@ import (
1213 "github.com/sirupsen/logrus"
1314 "github.com/spf13/cobra"
1415
16新增: "github.com/docker/go-units"
1517 "github.com/lima-vm/lima/v2/pkg/debugutil"
18新增: "github.com/lima-vm/lima/v2/pkg/driver"
1619 "github.com/lima-vm/lima/v2/pkg/driver/external/server"
1720 "github.com/lima-vm/lima/v2/pkg/envutil"
21新增: "github.com/lima-vm/lima/v2/pkg/hostagent"
1822 "github.com/lima-vm/lima/v2/pkg/hostagent/dns"
23新增: "github.com/lima-vm/lima/v2/pkg/limatype"
1924 "github.com/lima-vm/lima/v2/pkg/networks/usernet"
2025 "github.com/lima-vm/lima/v2/pkg/osutil"
2126 "github.com/lima-vm/sshocker/pkg/reversesshfs"
2227
2328 "github.com/sylvinus/agent-vm/internal/cage"
29新增: "github.com/sylvinus/agent-vm/internal/diagnostics"
2430 "github.com/sylvinus/agent-vm/internal/guard"
2531 "github.com/sylvinus/agent-vm/internal/netguard"
2632 "github.com/sylvinus/agent-vm/internal/state"
@@ -40,6 +46,20 @@ func Run(args []string) bool {
4046 if i == len(args) || args[i] != "hostagent" {
4147 return false
4248 }
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新增: }
4363 if runtime.GOOS == "windows" {
4464 windowsPath()
4565 }
@@ -127,6 +147,10 @@ func Run(args []string) bool {
127147 // Its events, as limactl's, and a notice for each port it forwards. The
128148 // instance is the last argument.
129149 root.SetOut(newEventWatch(os.Stdout, args[len(args)-1]))
150新增: if diagnosticStream != nil {
151新增: root.SetErr(diagnosticStream)
152新增: }
153新增:
130154 err = root.Execute()
131155 if stopJobWatch != nil {
132156 stopJobWatch()
修改internal/managedproxy/core.go+14 −6看文件
@@ -18,6 +18,7 @@ import (
1818 "strconv"
1919 "time"
2020
21新增: "github.com/sylvinus/agent-vm/internal/diagnostics"
2122 "github.com/sylvinus/agent-vm/internal/host"
2223)
2324
@@ -69,8 +70,10 @@ func Validate(ctx context.Context, profile string, s Store) error {
6970 defer cancel()
7071 cmd := exec.CommandContext(ctx, core, "-t", "-d", dir, "-f", f.Name())
7172 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 {
7477 return errors.New("代理核心拒绝该配置,请检查节点协议和参数;原配置已保留")
7578 }
7679 return nil
@@ -178,7 +181,7 @@ func Start(ctx context.Context, profile string, s Store) error {
178181 return errors.New("Cage 代理端口已被占用,请更换独立端口")
179182 }
180183 l.Close()
181删除: core, err := CorePath()
184新增: _, err = CorePath()
182185 if err != nil {
183186 return err
184187 }
@@ -200,12 +203,17 @@ func Start(ctx context.Context, profile string, s Store) error {
200203 return err
201204 }
202205 _ = 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 {
205208 return err
206209 }
210新增: configPath := os.Getenv("CLAUDE_CAGE_CONFIG")
211新增: if configPath == "" {
212新增: configPath = filepath.Join(profile, "config.json")
213新增: }
207214 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新增:
209217 if err = Write(servicePath(profile), []byte(plist)); err != nil {
210218 return err
211219 }
修改internal/managedproxy/platform_linux.go+12 −10看文件
@@ -14,6 +14,7 @@ import (
1414 "syscall"
1515 "time"
1616
17新增: "github.com/sylvinus/agent-vm/internal/diagnostics"
1718 "github.com/sylvinus/agent-vm/internal/host"
1819 "golang.org/x/sys/unix"
1920)
@@ -197,19 +198,13 @@ func startLinuxCore(ctx context.Context, profile string, s Store) error {
197198 return err
198199 }
199200 _ = 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新增:
209203 cmd := exec.Command(core, "-d", Dir(profile), "-f", path)
210204 cmd.Env, cmd.Stdout, cmd.Stderr = coreEnvironment(Dir(profile)), log, log
211205 cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
212206 if err := cmd.Start(); err != nil {
207新增: _ = log.Close()
213208 return err
214209 }
215210 record, err := identifyLinuxCore(cmd.Process.Pid)
@@ -226,7 +221,14 @@ func startLinuxCore(ctx context.Context, profile string, s Store) error {
226221 return err
227222 }
228223 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新增: }()
230232 ticker := time.NewTicker(100 * time.Millisecond)
231233 defer ticker.Stop()
232234 timeout := time.NewTimer(15 * time.Second)
修改internal/managedproxy/platform_windows.go+11 −10看文件
@@ -13,6 +13,7 @@ import (
1313 "syscall"
1414 "time"
1515
16新增: "github.com/sylvinus/agent-vm/internal/diagnostics"
1617 "github.com/sylvinus/agent-vm/internal/host"
1718 "golang.org/x/sys/windows"
1819)
@@ -150,19 +151,13 @@ func startWindowsCore(ctx context.Context, profile string, s Store) error {
150151 return err
151152 }
152153 _ = 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新增:
162156 cmd := exec.Command(core, "-d", Dir(profile), "-f", path)
163157 cmd.Env, cmd.Stdout, cmd.Stderr = coreEnvironment(Dir(profile)), log, log
164158 cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true, CreationFlags: windows.CREATE_NEW_PROCESS_GROUP | windows.DETACHED_PROCESS}
165159 if err := cmd.Start(); err != nil {
160新增: _ = log.Close()
166161 return err
167162 }
168163 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 {
184179 _ = cmd.Wait()
185180 return err
186181 }
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新增: }()
188189 ticker := time.NewTicker(100 * time.Millisecond)
189190 defer ticker.Stop()
190191 timeout := time.NewTimer(15 * time.Second)
修改internal/vm/lima.go+5 −1看文件
@@ -496,7 +496,11 @@ func (l *Lima) Start(ctx context.Context, name string, log io.Writer) error {
496496 }
497497 // Here, so that VMs made before it get it too; nothing is written when
498498 // 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 {
500504 return err
501505 }
502506 if inst, err = l.inspect(ctx, name); err != nil {
修改internal/workbench/browser_http.go+24 −0看文件
@@ -43,6 +43,30 @@ func (s *Server) browser(w http.ResponseWriter, r *http.Request) {
4343 _, _ = w.Write(data)
4444}
4545
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新增:
4670func (s *Server) browserEvents(w http.ResponseWriter, r *http.Request) {
4771 body, err := s.subscribeBrowser(r.Context())
4872 if err != nil {
修改internal/workbench/browser_service.go+40 −6看文件
@@ -16,12 +16,19 @@ var (
1616type browserInputError struct{ error }
1717
1818type 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"`
2532}
2633
2734func (s *Server) browserClient() *browserClient {
@@ -57,6 +64,21 @@ func (s *Server) browserAction(ctx context.Context, action string, input *browse
5764 if action == "insert-text" && (input.ID == "" || input.Text == "" || len(input.Text) > 8192) {
5865 return nil, browserInputError{errors.New("输入文字或目标标签无效")}
5966 }
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新增: }
6082 if action == "new" && input.URL == "" {
6183 s.mu.Lock()
6284 input.URL = browserHomeURL(s.preferences)
@@ -94,6 +116,18 @@ func (s *Server) browserAction(ctx context.Context, action string, input *browse
94116 return data, err
95117}
96118
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新增:
97131func (s *Server) subscribeBrowser(ctx context.Context) (io.ReadCloser, error) {
98132 s.mu.Lock()
99133 ready, token := s.ready, s.credentials.Token
修改internal/workbench/browser_text_test.go+67 −0看文件
@@ -47,3 +47,70 @@ func TestBrowserTextRequiresSessionAndExplicitTarget(t *testing.T) {
4747 t.Fatal("valid input rejected", w.Code, w.Body.String())
4848 }
4949}
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新增:}
修改internal/workbench/claude_desktop.go+8 −6看文件
@@ -15,11 +15,12 @@ import (
1515)
1616
1717type 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"`
2324}
2425
2526const claudeDesktopSnapshot = `python3 - <<'CAGE_DESKTOP_STATE'
@@ -30,7 +31,8 @@ def run(*args):
3031package=run('dpkg-query','-W','-f=${Status}\n${Version}','claude-desktop').splitlines()
3132installed=bool(package and package[0]=='install ok installed')
3233state=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 ''}))
3436CAGE_DESKTOP_STATE`
3537
3638func (s *Server) claudeDesktopStatus(w http.ResponseWriter, r *http.Request) {
修改internal/workbench/claude_desktop_test.go+36 −1看文件
@@ -1,6 +1,41 @@
11package workbench
22
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新增:}
439
540func TestClaudeDesktopControlBoundary(t *testing.T) {
641 s := testServer(t)
修改internal/workbench/desktop.go+1 −7看文件
@@ -329,15 +329,9 @@ func startController(configPath string) error {
329329 if err != nil {
330330 return err
331331 }
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")
338333 cmd.Dir = profile
339334 cmd.Env = append(os.Environ(), cage.ConfigEnv+"="+configPath)
340删除: cmd.Stdout, cmd.Stderr = log, log
341335 detachController(cmd)
342336 if err = cmd.Start(); err != nil {
343337 return err
新增internal/workbench/diagnostics.go+201 −0看文件
@@ -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新增:}
新增internal/workbench/diagnostics_test.go+158 −0看文件
@@ -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新增:}
修改internal/workbench/job_manager_test.go+2 −2看文件
@@ -250,14 +250,14 @@ func TestJobManagerFinalizationAndOutput(t *testing.T) {
250250 _, err := manager.submit(&operation, "stop", 0, nil, func() error {
251251 return errors.New("account could not be locked")
252252 }, func() error {
253删除: _, _ = manager.execution().Write([]byte(strings.Repeat("a", 25000) + "tail"))
253新增: _, _ = manager.execution().Write([]byte(strings.Repeat("a\n", 12500) + "tail"))
254254 return nil
255255 })
256256 if err != nil {
257257 t.Fatal(err)
258258 }
259259 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") {
261261 t.Fatalf("finalization error or bounded log lost: %+v", state)
262262 }
263263}
修改internal/workbench/jobs.go+30 −4看文件
@@ -3,6 +3,9 @@ package workbench
33import (
44 "context"
55 "errors"
6新增: "fmt"
7新增: "github.com/sylvinus/agent-vm/internal/diagnostics"
8新增: "runtime/debug"
69 "sync"
710)
811
@@ -67,6 +70,15 @@ func (m *jobManager) submit(operation sync.Locker, kind string, pauseVersion uin
6770 m.afterSuccess = afterSuccess
6871 m.state = Job{ID: randomToken()[:12], Kind: kind, Running: true, Message: "正在准备…"}
6972 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")
7082 m.workers.Add(1)
7183 go func() {
7284 defer m.workers.Done()
@@ -85,7 +97,15 @@ func (m *jobManager) submit(operation sync.Locker, kind string, pauseVersion uin
8597 }
8698 m.active = execution
8799 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新增: }()
89109 m.mu.Lock()
90110 defer m.mu.Unlock()
91111 m.finishLocked(execution, err)
@@ -94,6 +114,9 @@ func (m *jobManager) submit(operation sync.Locker, kind string, pauseVersion uin
94114}
95115
96116func (m *jobManager) finishLocked(execution *jobExecution, err error) {
117新增: if execution.log != nil {
118新增: _ = execution.log.Close()
119新增: }
97120 if m.active == execution {
98121 m.active = nil
99122 }
@@ -111,11 +134,14 @@ func (m *jobManager) finishLocked(execution *jobExecution, err error) {
111134 switch {
112135 case errors.Is(err, context.Canceled):
113136 m.state.Message = "已取消"
137新增: diagnostics.Log("info", "task", m.state.Kind+" canceled")
114138 case err != nil:
115139 m.state.Error = err.Error()
116140 m.state.Message = "操作未完成"
141新增: diagnostics.Log("error", "task", m.state.Kind+": "+err.Error())
117142 default:
118143 m.state.Message = "已完成"
144新增: diagnostics.Log("info", "task", m.state.Kind+" completed")
119145 }
120146}
121147
@@ -165,6 +191,7 @@ type jobExecution struct {
165191 id string
166192 ctx context.Context
167193 pauseVersion uint64
194新增: log *diagnostics.Stream
168195}
169196
170197func (e *jobExecution) message(message string) {
@@ -179,9 +206,8 @@ func (e *jobExecution) Write(data []byte) (int, error) {
179206 e.owner.mu.Lock()
180207 defer e.owner.mu.Unlock()
181208 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)
185211 }
186212 }
187213 return len(data), nil
修改internal/workbench/lifecycle.go+17 −1看文件
@@ -7,6 +7,7 @@ import (
77 "path/filepath"
88 "time"
99
10新增: "github.com/sylvinus/agent-vm/internal/diagnostics"
1011 "github.com/sylvinus/agent-vm/internal/managedproxy"
1112)
1213
@@ -33,8 +34,23 @@ func (s *Server) startMonitors() {
3334 return
3435 }
3536 ctx := s.lifetimeContextLocked()
36删除: s.monitors.Add(2)
37新增: s.monitors.Add(3)
3738 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新增: }()
3854 go func() {
3955 defer s.monitors.Done()
4056 s.monitor(ctx)
新增internal/workbench/network_recovery.go+127 −0看文件
@@ -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新增:}
新增internal/workbench/network_recovery_test.go+112 −0看文件
@@ -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新增:}
新增internal/workbench/resources.go+65 −0看文件
@@ -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新增:}
修改internal/workbench/runtime.go+9 −3看文件
@@ -11,6 +11,8 @@ import (
1111 "path/filepath"
1212 "time"
1313
14新增: "al.essio.dev/pkg/shellescape"
15新增:
1416 "github.com/sylvinus/agent-vm/internal/cage"
1517 "github.com/sylvinus/agent-vm/internal/managedproxy"
1618 "github.com/sylvinus/agent-vm/internal/vmname"
@@ -51,7 +53,10 @@ func (s *Server) sshCommandOptions(ctx context.Context, maintenance bool, args .
5153}
5254func (s *Server) guest(ctx context.Context, script string) ([]byte, error) {
5355 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)
5560 pipe, err := cmd.StdoutPipe()
5661 if err != nil {
5762 return nil, err
@@ -220,7 +225,7 @@ func (s *Server) startEnvironment(syncTimezone bool) error {
220225 s.publishGate(state)
221226 return nil
222227 }
223删除: return s.runSafetyCheck()
228新增: return s.checkNetworkIfWanted()
224229 }
225230 }
226231 s.setMessage("正在重启环境以加载 VM 外网络门槛…")
@@ -302,7 +307,7 @@ func (s *Server) startEnvironment(syncTimezone bool) error {
302307 return s.operationContext().Err()
303308 }
304309 if err = s.attach(); err == nil {
305删除: return s.runSafetyCheck()
310新增: return s.checkNetworkIfWanted()
306311 }
307312 time.Sleep(time.Second)
308313 }
@@ -446,6 +451,7 @@ func (s *Server) monitorNetwork(ctx context.Context) {
446451 s.monitorProxyInterface()
447452 s.checkProxyHealth()
448453 s.monitorSafety()
454新增: s.recoverNetwork()
449455 s.refreshProxySubscriptions()
450456 s.op.Unlock()
451457 }
新增internal/workbench/runtime_shell_test.go+130 −0看文件
@@ -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新增:}
修改internal/workbench/safety.go+23 −1看文件
@@ -107,6 +107,7 @@ func (s *Server) revokeNetworkNow(reason string, pause bool) error {
107107 var intentErr error
108108 s.mu.Lock()
109109 if pause {
110新增: s.recovery = networkRecovery{}
110111 s.networkPaused = true
111112 s.safety.pauseVersion++
112113 intentErr = s.saveNetworkIntentLocked(true)
@@ -575,9 +576,18 @@ func (s *Server) monitorSafety() {
575576 }
576577 s.publishGate(state)
577578 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新增: }
578587 return
579588 }
580589 var issue string
590新增: var recoverable bool
581591 cfg, err := loadConfig(s.configPath)
582592 if err != nil || cfg.Fingerprint() != state.Configuration {
583593 issue = "配置与运行环境不一致,请应用设置并重新检测"
@@ -592,6 +602,7 @@ func (s *Server) monitorSafety() {
592602 ip, err = cage.ProbeExitIP(ctx, cfg)
593603 if err != nil {
594604 issue = "当前无法经指定代理确认出口,外网已暂停"
605新增: recoverable = true
595606 } else {
596607 result, message := s.checkExitPolicy(ctx, cfg, ip)
597608 if result != cage.CheckPassed {
@@ -603,19 +614,25 @@ func (s *Server) monitorSafety() {
603614 guest, e := s.guestObservation(ctx, map[string]any{"stage": "environment"})
604615 if e != nil || !guestSettingsMatch(guest, cfg) {
605616 issue = "系统时区或语言的运行状态无法确认,请重新检测"
617新增: recoverable = e != nil
606618 }
607619 }
608620 if issue == "" {
609621 browser, e := s.browserObservation(ctx, cfg, false)
610622 if e != nil || !browserSettingsMatch(browser, cfg) {
611623 issue = "浏览器时区或语言的运行状态无法确认,请重新检测"
624新增: recoverable = e != nil
612625 }
613626 }
614删除: s.finishSafetyMonitor(ctx, client, state, ip, issue)
627新增: s.finishSafetyObservation(ctx, client, state, ip, issue, recoverable)
615628}
616629
617630// Recheck the user operation and configuration at the actual lease write.
618631func (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) {
619636 s.safetyOp.Lock()
620637 defer s.safetyOp.Unlock()
621638 s.mu.Lock()
@@ -627,11 +644,15 @@ func (s *Server) finishSafetyMonitor(ctx context.Context, client *cage.GateClien
627644 current, e := loadConfig(s.configPath)
628645 if e != nil || current.Fingerprint() != state.Configuration {
629646 issue = "运行配置已变化,请重新应用设置"
647新增: recoverable = false
630648 }
631649 if issue != "" {
632650 closed, e := client.Close(context.Background(), issue)
633651 if e == nil {
634652 s.publishGate(closed)
653新增: if recoverable {
654新增: s.scheduleNetworkRecovery(closed)
655新增: }
635656 }
636657 s.mu.Lock()
637658 s.safety.Error = issue
@@ -645,6 +666,7 @@ func (s *Server) finishSafetyMonitor(ctx context.Context, client *cage.GateClien
645666 closed, e := client.Close(context.Background(), "运行监测未能续期,请重新检测")
646667 if e == nil {
647668 s.publishGate(closed)
669新增: s.scheduleNetworkRecovery(closed)
648670 }
649671 s.mu.Lock()
650672 s.safety.Error = "运行监测未能续期,请重新检测"
修改internal/workbench/server.go+43 −2看文件
@@ -10,15 +10,18 @@ import (
1010 "errors"
1111 "fmt"
1212 "github.com/sylvinus/agent-vm/internal/cage"
13新增: "github.com/sylvinus/agent-vm/internal/diagnostics"
1314 "github.com/sylvinus/agent-vm/internal/host"
1415 "github.com/sylvinus/agent-vm/internal/vmname"
1516 "io"
1617 "io/fs"
18新增: "log"
1719 "net"
1820 "net/http"
1921 "net/url"
2022 "os"
2123 "path/filepath"
24新增: "runtime/debug"
2225 "strings"
2326 "sync"
2427 "time"
@@ -44,6 +47,10 @@ type Server struct {
4447 closing bool
4548 shutdown func()
4649 favoritesMu sync.Mutex
50新增: diagnosticMu sync.Mutex
51新增: diagnosticRateMu sync.Mutex
52新增: diagnosticWindow time.Time
53新增: diagnosticCount int
4754 tickets map[string]time.Time
4855 browserControl *browserClient
4956 op sync.Mutex
@@ -60,6 +67,7 @@ type Server struct {
6067 projectShares map[string]*projectShare
6168 projectErrors []projectShareError
6269 safety safetyState
70新增: recovery networkRecovery
6371 locations map[string]Location
6472 monitorCancel context.CancelFunc
6573 safetyOp sync.Mutex
@@ -86,6 +94,14 @@ func equalSecret(a, b string) bool {
8694 return len(a) > 0 && subtle.ConstantTimeCompare([]byte(a), []byte(b)) == 1
8795}
8896func 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") }()
89105 profile := filepath.Dir(configPath)
90106 if err := host.EnsurePrivateDir(profile); err != nil {
91107 return err
@@ -98,6 +114,9 @@ func Serve(configPath string) (returned error) {
98114 if err = lockController(lock); err != nil {
99115 return errors.New("此配置已有工作台服务正在运行")
100116 }
117新增: if err := store.ImportLegacy(filepath.Dir(configPath)); err != nil {
118新增: diagnostics.Log("warn", "diagnostics", "legacy log import failed: "+err.Error())
119新增: }
101120 exe, err := os.Executable()
102121 if err != nil {
103122 return err
@@ -154,7 +173,9 @@ func Serve(configPath string) (returned error) {
154173 _ = s.closeProxyGate("网络保持暂停,请手动恢复后再联网")
155174 }
156175 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}
158179 defer server.Close()
159180 shutdownDone := make(chan struct{})
160181 s.shutdown = func() {
@@ -197,11 +218,17 @@ func (s *Server) handler() http.Handler {
197218 jsonReply(w, map[string]bool{"ok": true})
198219 })
199220 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)
200225 mux.HandleFunc("GET /api/account", s.accountStatus)
201226 mux.HandleFunc("POST /api/account/{action}", s.accountAction)
202227 mux.HandleFunc("GET /api/settings", s.getSettings)
203228 mux.HandleFunc("POST /api/projects/open", s.openProject)
204229 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)
205232 mux.HandleFunc("POST /api/environment/update", s.updateEnvironment)
206233 mux.HandleFunc("POST /api/environment/tools", s.updateEnvironmentTools)
207234 mux.HandleFunc("GET /api/host/git", s.hostGit)
@@ -290,7 +317,7 @@ func (s *Server) handler() http.Handler {
290317 r = r.WithContext(ctx)
291318 accountRoute := r.URL.Path == "/api/account" || strings.HasPrefix(r.URL.Path, "/api/account/")
292319 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") {
294321 epoch, unlocked := s.account.access()
295322 if !unlocked {
296323 http.Error(w, "Cage 已锁定,请先登录", http.StatusLocked)
@@ -302,6 +329,19 @@ func (s *Server) handler() http.Handler {
302329 r = r.WithContext(ctx)
303330 }
304331 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新增: }()
305345 mux.ServeHTTP(w, r)
306346 })
307347}
@@ -332,6 +372,7 @@ func jsonReply(w http.ResponseWriter, v any) {
332372 _ = json.NewEncoder(w).Encode(v)
333373}
334374func requestError(w http.ResponseWriter, err error) {
375新增: diagnostics.Log("error", "api", err.Error())
335376 http.Error(w, err.Error(), http.StatusBadRequest)
336377}
337378func (s *Server) status(w http.ResponseWriter, r *http.Request) {
修改patches/README.md+1 −0看文件
@@ -51,6 +51,7 @@ It runs inside the Lima hostagent, which with vz also runs the VM: a panic there
5151| `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. |
5252| `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. |
5353| `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. |
5455| `sshocker/0001-rooted-server-readonly-names` | lima-vm/sshocker | fork branch `readonly-names` | The builtin server serves only the mounted directory, and `ReadonlyNames`. |
5556| `sshocker/0002-expect-remove` | lima-vm/sshocker | fork branch `expect-remove` | `ExpectRemove`, for 0002 of Lima. |
5657| `sshocker/0003-append-fix` | lima-vm/sshocker | not sent | Bug 1. Tests `TestRootedOpenAppend`, `TestRootedOpenMode`. No pkg/sftp dependency: send first. |
新增patches/lima/0012-dynamic-memory.patch+378 −0看文件
@@ -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新增:+}
修改scripts/build-app.sh+1 −1看文件
@@ -37,7 +37,7 @@ install_stage=''
3737trap 'rm -rf "$build_stage"; if [[ -n "$install_stage" ]]; then rm -rf "$install_stage"; fi' EXIT
3838bundle="$build_stage/Cage.app"
3939mkdir -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"
4141swiftc -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"
4242cp _output/bin/cage "$bundle/Contents/Resources/cage"
4343cp _output/proxy-core/mihomo "$bundle/Contents/Resources/mihomo"
新增third_party/lima/pkg/driver/memory.go+12 −0看文件
@@ -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新增:}
新增third_party/lima/pkg/driver/qemu/memory.go+81 −0看文件
@@ -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新增:}
新增third_party/lima/pkg/driver/qemu/memory_test.go+89 −0看文件
@@ -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新增:}
修改third_party/lima/pkg/driver/qemu/qemu.go+4 −0看文件
@@ -525,6 +525,10 @@ func Cmdline(ctx context.Context, cfg Config) (exe string, args []string, err er
525525 }
526526 memBytes = adjustMemBytesDarwinARM64HVF(memBytes, accel)
527527 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新增: }
528532
529533 if *y.MountType == limatype.VIRTIOFS {
530534 args = appendArgsIfNoConflict(args, "-object",
新增third_party/lima/pkg/driver/vz/memory_darwin.go+43 −0看文件
@@ -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新增:}
修改third_party/lima/pkg/hostagent/hostagent.go+3 −0看文件
@@ -448,6 +448,9 @@ func (a *HostAgent) Run(ctx context.Context) error {
448448 if err := a.driver.AdditionalSetupForSSH(ctx); err != nil {
449449 return err
450450 }
451新增: stopResources := a.startResourceManager(ctx)
452新增: defer stopResources()
453新增: a.cleanUp(func() error { stopResources(); return nil })
451454
452455 // WSL instance SSH address isn't known until after VM start
453456 if a.driver.Info(ctx).Features.DynamicSSHAddress {
新增third_party/lima/pkg/hostagent/resources.go+59 −0看文件
@@ -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新增:}
新增third_party/lima/pkg/hostagent/resources_unix.go+10 −0看文件
@@ -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) {}
新增third_party/lima/pkg/hostagent/resources_windows.go+13 −0看文件
@@ -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新增:}
修改ui/package-lock.json+2 −2看文件
@@ -1,12 +1,12 @@
11{
22 "name": "cage-workbench",
3删除: "version": "0.1.3-alpha.2",
3新增: "version": "0.1.4-alpha",
44 "lockfileVersion": 3,
55 "requires": true,
66 "packages": {
77 "": {
88 "name": "cage-workbench",
9删除: "version": "0.1.3-alpha.2",
9新增: "version": "0.1.4-alpha",
1010 "dependencies": {
1111 "@xterm/addon-fit": "0.11.0",
1212 "@xterm/xterm": "6.0.0",
修改ui/package.json+1 −1看文件
@@ -1,7 +1,7 @@
11{
22 "name": "cage-workbench",
33 "private": true,
4删除: "version": "0.1.3-alpha.2",
4新增: "version": "0.1.4-alpha",
55 "type": "module",
66 "scripts": {
77 "prepare-vnc": "node scripts/prepare-vnc.mjs",
新增ui/scripts/desktop-focus-smoke.mjs+43 −0看文件
@@ -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新增:}
新增ui/scripts/desktop-memory-smoke.mjs+40 −0看文件
@@ -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(); }
新增ui/scripts/diagnostics-smoke.mjs+68 −0看文件
@@ -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新增:}
修改ui/scripts/remote-input-smoke.mjs+110 −1看文件
@@ -35,6 +35,7 @@ try {
3535 "_cageSendKey",
3636 "_cageQueueInput",
3737 "_handleKeyEvent",
38新增: "_handleServerFenceMsg",
3839 "cageSetKeyboardTarget",
3940 "focus",
4041 "blur",
@@ -61,6 +62,9 @@ try {
6162 value & 255,
6263 );
6364 },
65新增: sQpushString(value) {
66新增: bytes.push(...new TextEncoder().encode(value));
67新增: },
6468 flush() {
6569 packets.push(bytes);
6670 bytes = [];
@@ -84,18 +88,53 @@ try {
8488 rfb,
8589 packets,
8690 texts,
91新增: compositions: [],
8792 input: install(),
8893 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新增: },
89119 setActive: (value) => {
90120 active = value;
91121 },
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新增: },
92131 };
93132 rfb.focus();
94133 });
95134 const target = page.getByLabel("Cage 网页输入");
96135 const keys = () =>
97136 page.evaluate(() =>
98删除: probe.packets.map((p) => {
137新增: probe.packets.filter(p => p[0] !== 248).map((p) => {
99138 if (p.length !== 8 || p[0] !== 4)
100139 throw new Error("Unexpected RFB key packet");
101140 return {
@@ -137,9 +176,31 @@ try {
137176 );
138177 assert.equal(await target.inputValue(), "");
139178 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();
140190 // Exercise Chromium's composition implementation as well as the explicit
141191 // cross-engine event sequences below. This still does not use macOS Pinyin.
142192 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();
143204 await cdp.send("Input.imeSetComposition", {
144205 text: "nihao",
145206 selectionStart: 5,
@@ -267,6 +328,47 @@ try {
267328 [98],
268329 );
269330 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();
270372 await page.evaluate(() => {
271373 const oldTarget = document.activeElement;
272374 probe.input.dispose();
@@ -289,6 +391,13 @@ try {
289391 checks: [
290392 "real noVNC keyboard and RFB encoding",
291393 "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",
292401 "Chromium IME engine commit",
293402 "composition default action",
294403 "candidate suppression",
修改ui/src/api.js+9 −3看文件
@@ -1,3 +1,4 @@
1新增:import { reportDiagnostic } from "./diagnostics.mjs";
12let sessionRenewal;
23async function responseError(response) {
34 const error = new Error(
@@ -33,12 +34,16 @@ export async function api(path, body, method) {
3334 headers: body === undefined ? {} : { "Content-Type": "application/json" },
3435 body: body === undefined ? undefined : JSON.stringify(body),
3536 };
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();
3742 // Authentication fails before a handler runs, so retrying this rejected
3843 // request once does not repeat an accepted mutation.
3944 if (response.status === 401 && path !== "/session" && nativeAvailable()) {
4045 await renewSession();
41删除: response = await fetch("/api" + path, options);
46新增: response = await send();
4247 }
4348 if (response.status === 423) window.dispatchEvent(new Event("cage-account-locked"));
4449 if (!response.ok) throw await responseError(response);
@@ -82,7 +87,8 @@ export async function native(action, extra = {}) {
8287 try { await api("/account/suspend", {}); }
8388 catch (error) { if (error.status !== 423) throw error; }
8489 }
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; }
8692}
8793export const readClipboard = () =>
8894 nativeAvailable() ? native("clipboardRead") : navigator.clipboard.readText();
修改ui/src/claude-desktop.jsx+7 −3看文件
@@ -37,6 +37,7 @@ export function ClaudeDesktop({
3737 });
3838 const [desktop, setDesktop] = useState(null);
3939 const [error, setError] = useState("");
40新增: const [statusError, setStatusError] = useState("");
4041 const [submitting, setSubmitting] = useState(false);
4142 const [jobID, setJobID] = useState("");
4243 const opened = useRef(false);
@@ -46,9 +47,10 @@ export function ClaudeDesktop({
4647 try {
4748 const value = await api("/claude-desktop");
4849 setDesktop(value);
50新增: setStatusError("");
4951 return value;
5052 } catch (e) {
51删除: setError(e.message);
53新增: setStatusError(e.message);
5254 return null;
5355 }
5456 };
@@ -177,9 +179,11 @@ export function ClaudeDesktop({
177179 <RefreshCw size={15} />
178180 </button>
179181 </header>
180删除: {(error || desktop?.failed) && (
182新增: {(error || statusError || desktop?.failed) && (
181183 <div className="connection-banner" role="alert">
182删除: {error || "Claude Desktop 未能启动,可重试打开或修复安装。"}
184新增: {error || statusError || (desktop?.failure_reason === "oom-kill"
185新增: ? "环境内存不足,Claude Desktop 已被系统关闭。请在设置中检查计算资源后重新打开。"
186新增: : "Claude Desktop 未能启动,可重试打开或修复安装。")}
183187 <button onClick={onDetails}>操作详情</button>
184188 </div>
185189 )}
新增ui/src/diagnostics.jsx+63 −0看文件
@@ -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新增:}
新增ui/src/diagnostics.mjs+49 −0看文件
@@ -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新增:}
新增ui/src/diagnostics.test.mjs+33 −0看文件
@@ -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新增:});
修改ui/src/main.jsx+11 −1看文件
@@ -1,3 +1,5 @@
1新增:import { installDiagnostics } from "./diagnostics.mjs";
2新增:import { DiagnosticBoundary } from "./diagnostics.jsx";
13import { shortcut, primaryModifier } from "./platform.mjs";
24import logo from "./logo.png";
35import React, { useEffect, useRef, useState } from "react";
@@ -478,6 +480,11 @@ function App() {
478480 stream.onerror = () => { browserStreamReady.current = false; };
479481 stream.onmessage = (event) => {
480482 const b = JSON.parse(event.data);
483新增: if (b.desktopFocus === true) {
484新增: setDesktopOpen(true);
485新增: setHome(false);
486新增: setSettingsOpen(false);
487新增: }
481488 browserSnapshot.current = b;
482489 setBrowser((previous) => ({ ...previous, ...b }));
483490 setTabs((previous) => {
@@ -1676,12 +1683,15 @@ function App() {
16761683 </div>
16771684 );
16781685}
1686新增:installDiagnostics();
16791687createRoot(document.getElementById("root")).render(
1688新增: <DiagnosticBoundary>
16801689 <AccountProvider>
16811690 <AppearanceProvider>
16821691 <AccountGate><App /></AccountGate>
16831692 </AppearanceProvider>
1684删除: </AccountProvider>,
1693新增: </AccountProvider>
1694新增: </DiagnosticBoundary>,
16851695);
16861696
16871697// A launcher can reopen an existing window with a fresh one-use ticket.
修改ui/src/remote-input.js+180 −15看文件
@@ -1,5 +1,5 @@
11import { getKeycode, getKeysym } from "../.generated/novnc/core/input/util.js";
2删除:import { writeClipboard, nativeAvailable } from "./api";
2新增:import { writeClipboard, nativeAvailable, native } from "./api";
33import {
44 readClipboardContent,
55 transferFiles,
@@ -11,7 +11,7 @@ import {
1111export function installRemoteInput(
1212 rfb,
1313 container,
14删除: { mode, onStatus, onFallback, isActive, insertText, pasteContent },
14新增: { mode, onStatus, onFallback, isActive, insertText, insertComposition, caretRect, tabId: getTargetId = () => "", pasteContent },
1515) {
1616 const listeners = [],
1717 handled = new Set(),
@@ -22,11 +22,22 @@ export function installRemoteInput(
2222 copyTimer,
2323 pending = 0,
2424 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,
2535 disposed = false;
2636 const target = document.createElement("textarea");
2737 target.setAttribute("aria-label", "Cage 网页输入");
2838 target.setAttribute("autocomplete", "off");
2939 target.setAttribute("autocapitalize", "off");
40新增: target.setAttribute("wrap", "off");
3041 target.spellcheck = false;
3142 target.className = "remote-text-input";
3243 target.style.cssText = "position:fixed;left:0;top:0";
@@ -38,19 +49,77 @@ export function installRemoteInput(
3849 };
3950 const focused = () =>
4051 isActive() &&
41删除: (container.contains(document.activeElement) ||
52新增: (nativeOwned || container.contains(document.activeElement) ||
4253 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新增: };
4375 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);
47105 };
106新增: if (caretRect) caretTimer = setTimeout(pollCaret, 0);
48107 const bounds = container.getBoundingClientRect();
49108 position(bounds.left + 12, bounds.top + 12);
50109 on(
51110 container,
52111 "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新增: },
54123 true,
55124 );
56125 const commit = (text) => {
@@ -61,19 +130,63 @@ export function installRemoteInput(
61130 if (!disposed) onStatus("文字输入未完成,请重新连接画面后重试");
62131 });
63132 };
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新增: };
64144 const resetComposition = () => {
65145 composing = false;
146新增: compositionTarget = "";
147新增: compositionSession = "";
66148 target.value = "";
67149 };
68删除: on(target, "compositionstart", () => {
150新增: const startComposition = () => {
69151 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();
70164 });
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新增: }
73170 resetComposition();
74删除: });
171新增: void syncCaret();
172新增: };
173新增: on(target, "compositionend", (event) => endComposition(event.data || ""));
75174 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新增: }
77190 // WebKit may deliver the final input after compositionend. That text has
78191 // already been sent. Input without composition covers emoji and dictation.
79192 if (
@@ -84,7 +197,39 @@ export function installRemoteInput(
84197 commit(target.value);
85198 target.value = "";
86199 });
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新增: });
88233 const say = (text) => {
89234 if (!disposed) onStatus(text);
90235 };
@@ -177,8 +322,8 @@ export function installRemoteInput(
177322 event.keyCode === 229 ||
178323 ["Process", "Dead"].includes(event.key)
179324 ) {
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.
182327 event.stopImmediatePropagation();
183328 return;
184329 }
@@ -259,6 +404,20 @@ export function installRemoteInput(
259404 }
260405 }
261406 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新增: }
262421 },
263422 true,
264423 );
@@ -281,6 +440,8 @@ export function installRemoteInput(
281440 (focused() && mode() === "mac" && event.key === "Meta")
282441 )
283442 event.stopImmediatePropagation();
443新增: else if (focused() && !composing && caretRect)
444新增: setTimeout(() => void syncCaret(), 35);
284445 },
285446 true,
286447 );
@@ -338,8 +499,12 @@ export function installRemoteInput(
338499 return true;
339500 },
340501 dispose() {
502新增: if (composing && compositionSession)
503新增: queueComposition({ mode: "cancel", text: "", selectionStart: 0, selectionEnd: 0 });
341504 disposed = true;
505新增: deactivateNative();
342506 clearTimeout(copyTimer);
507新增: clearTimeout(caretTimer);
343508 release();
344509 listeners.forEach((remove) => remove());
345510 rfb.cageSetKeyboardTarget(null);
修改ui/src/remote-input.test.mjs+77 −2看文件
@@ -2,13 +2,14 @@ import test from "node:test";
22import assert from "node:assert/strict";
33import { readFileSync } from "node:fs";
44import vm from "node:vm";
5新增:import { webcrypto } from "node:crypto";
56const source = readFileSync(
67 new URL("./remote-input.js", import.meta.url),
78 "utf8",
89)
910 .replace(/^import[\s\S]*?;\n/gm, "")
1011 .replace("export function installRemoteInput", "function installRemoteInput");
11删除:function fixture(native = false) {
12新增:function fixture(native = false, browserComposition = false) {
1213 const doc = new EventTarget(),
1314 win = new EventTarget(),
1415 canvas = {},
@@ -16,10 +17,12 @@ function fixture(native = false) {
1617 keys = [],
1718 pastes = [],
1819 texts = [],
20新增: compositions = [],
1921 writes = [],
2022 statuses = [];
2123 let reads = 0,
22删除: mode = "mac";
24新增: mode = "mac",
25新增: currentTabId = "tab-1";
2326 doc.activeElement = canvas;
2427 doc.body = { append() {} };
2528 const target = Object.assign(new EventTarget(), {
@@ -56,6 +59,7 @@ function fixture(native = false) {
5659 Map,
5760 Set,
5861 console,
62新增: crypto: webcrypto,
5963 readClipboardContent: async () => {
6064 reads++;
6165 return { text: "中文🙂" };
@@ -78,6 +82,7 @@ function fixture(native = false) {
7882 const controller = install(
7983 rfb,
8084 Object.assign(new EventTarget(), {
85新增: querySelector: () => null,
8186 contains: (element) => element === canvas || element === target,
8287 append() {},
8388 getBoundingClientRect: () => ({ left: 0, top: 0 }),
@@ -90,6 +95,14 @@ function fixture(native = false) {
9095 insertText: async (text) => {
9196 texts.push(text);
9297 },
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,
93106 pasteContent: async (content) => {
94107 const value = await content;
95108 if (rfb.target) pastes.push(value.png || value.text);
@@ -117,6 +130,7 @@ function fixture(native = false) {
117130 keys,
118131 pastes,
119132 texts,
133新增: compositions,
120134 writes,
121135 statuses,
122136 controller,
@@ -126,6 +140,9 @@ function fixture(native = false) {
126140 setMode: (value) => {
127141 mode = value;
128142 },
143新增: setTabId: (value) => {
144新增: currentTabId = value;
145新增: },
129146 reads: () => reads,
130147 };
131148}
@@ -215,6 +232,46 @@ test("host IME receives composition keys and sends only committed Unicode in ord
215232 assert.equal(f.rfb.target, null);
216233});
217234
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新增:
218275test("cancelled and disconnected compositions do not insert text", () => {
219276 const f = fixture();
220277 f.rfb.focus();
@@ -241,6 +298,24 @@ test("text input without a composition supports emoji and clears the host buffer
241298 f.controller.dispose();
242299 }
243300});
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新增:});
244319test("local fields and native keyboard mode do not acquire mapped shortcuts", () => {
245320 const f = fixture();
246321 try {
新增ui/src/resources.jsx+55 −0看文件
@@ -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新增:}
修改ui/src/settings.jsx+4 −0看文件
@@ -19,6 +19,8 @@ import { ProxySettings } from "./proxy-settings";
1919import { ExitPolicyFields } from "./exit-policy";
2020import { canonicalExitPolicy } from "./safety-state.mjs";
2121import { EnvironmentVersions } from "./environment-versions";
22新增:import { ResourceSettings } from "./resources";
23新增:import { DiagnosticSettings } from "./diagnostics.jsx";
2224import { AccountSettings } from "./account";
2325const sections = [
2426 ["account", "账户", UserRound],
@@ -560,6 +562,8 @@ export function SettingsPanel({
560562 切换项目只改变新终端和文件编辑器的起始位置;已有终端、网页和登录态会保留。
561563 </p>
562564 <EnvironmentVersions status={status} onConfirm={onConfirm} />
565新增: <ResourceSettings status={status} onConfirm={onConfirm} />
566新增: <DiagnosticSettings />
563567 {status.can_restore && (
564568 <button
565569 className="text-button"
修改ui/src/views.jsx+16 −0看文件
@@ -118,6 +118,22 @@ export const RemoteView = forwardRef(function RemoteView(
118118 return api("/browser/insert-text", { id, text });
119119 });
120120 },
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新增: },
121137 mode: () => current.current.keyboard,
122138 isActive: () => current.current.visible,
123139 onStatus: (t) => current.current.onStatus(t),
修改www/package-lock.json+2 −2看文件
@@ -1,12 +1,12 @@
11{
22 "name": "claude-cage-website",
3删除: "version": "0.1.3-alpha.2",
3新增: "version": "0.1.4-alpha",
44 "lockfileVersion": 3,
55 "requires": true,
66 "packages": {
77 "": {
88 "name": "claude-cage-website",
9删除: "version": "0.1.3-alpha.2",
9新增: "version": "0.1.4-alpha",
1010 "license": "MIT",
1111 "dependencies": {
1212 "@fontsource-variable/inter": "^5.3.0",
修改www/package.json+1 −1看文件
@@ -1,7 +1,7 @@
11{
22 "name": "claude-cage-website",
33 "type": "module",
4删除: "version": "0.1.3-alpha.2",
4新增: "version": "0.1.4-alpha",
55 "private": true,
66 "description": "Claude Cage project website and macOS, Windows and Linux downloads",
77 "license": "MIT",