跳到主要内容

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

提交记录

收尾跨平台存储恢复、客机权限与文件交互并修复私网组件升级

作者
Lee-xeo
时间
2026/11/09 17:48
提交
845df7b
上一个
3129681
这个版本的全部文件
修改.gitattributes+2 −0看文件
@@ -27,3 +27,5 @@
2727/third_party/** -text -whitespace
2828/patches/** -text -whitespace
2929/ui/vendor/** -text -whitespace
30新增:# Build patches retain the upstream context whitespace required by patch(1).
31新增:/scripts/guest-os/sshfs-openwith.patch -text -whitespace
修改.gitignore+3 −0看文件
@@ -81,3 +81,6 @@ __pycache__/
8181/packaging/nfpm.yaml
8282/ui/vendor/novnc/README.cage.md
8383/ui/vendor/novnc/vendor/pako/README.md
84新增:
85新增:# Unfinished local native file-open prototype, excluded from compilation.
86新增:/scripts/guest-os/guest-clipboard-windows/WindowsNativeOpen.cs.local
修改cmd/cage-client/main.go+5 −0看文件
@@ -123,6 +123,11 @@ func run(args []string) error {
123123 return errors.New("share-project --json --connection ID read|write DIRECTORY")
124124 }
125125 return printJSON(workbench.ShareNativeCloudProject(config, args[3], args[5], args[4] == "read"))
126新增: case "desktop-file":
127新增: if len(args) != 5 || args[1] != "--json" || args[2] != "--connection" || args[3] == "" {
128新增: return errors.New("desktop-file --json --connection ID REQUEST")
129新增: }
130新增: return printJSON(workbench.DesktopFileForConnection(config, args[3], args[4]))
126131 case "clipboard-files", "upload-files", "browser-file":
127132 if len(args) < 4 || args[1] != "--json" {
128133 return errors.New("invalid file command")
修改cmd/cage-guest-files/main.go+17 −20看文件
@@ -9,7 +9,6 @@ import (
99 "fmt"
1010 "io"
1111 "os"
12删除: "path/filepath"
1312
1413 "github.com/sylvinus/agent-vm/internal/clipboardfiles"
1514)
@@ -33,22 +32,30 @@ func run(args []string, input io.Reader, output io.Writer) error {
3332 }
3433 return json.NewEncoder(output).Encode(result)
3534 }
35新增: var store clipboardfiles.CacheStore
36新增: if args[0] != "export" {
37新增: var err error
38新增: store, err = clipboardfiles.UserCacheStore()
39新增: if err != nil {
40新增: return err
41新增: }
42新增: }
3643 if args[0] == "save" {
3744 if len(args) != 2 {
3845 return errors.New("file name required")
3946 }
40删除: path, err := clipboardfiles.Save(&framedInput{reader: input}, args[1])
47新增: selection, err := store.Save(&framedInput{reader: input}, args[1])
4148 if err != nil {
4249 return err
4350 }
44删除: return returnCachedPaths(output, []string{path})
51新增: return returnCachedSelection(output, store, selection)
4552 }
4653 if args[0] == "import" {
47删除: paths, err := clipboardfiles.Read(input)
54新增: selection, err := store.Read(input)
4855 if err != nil {
4956 return err
5057 }
51删除: return returnCachedPaths(output, paths)
58新增: return returnCachedSelection(output, store, selection)
5259 }
5360 var paths []string
5461 if len(args) == 2 && args[1] != "--paths-stdin" {
@@ -63,35 +70,25 @@ func run(args []string, input io.Reader, output io.Writer) error {
6370 }
6471 switch args[0] {
6572 case "link-cached":
66删除: linked, err := clipboardfiles.LinkCachedFiles(paths)
73新增: linked, err := store.LinkCachedFiles(paths)
6774 if err != nil {
6875 return err
6976 }
70删除: return returnCachedPaths(output, linked)
77新增: return returnCachedSelection(output, store, linked)
7178 case "export":
7279 return clipboardfiles.Write(output, paths)
7380 case "copy":
74删除: copied, err := clipboardfiles.Copy(paths)
81新增: copied, err := store.Copy(paths)
7582 if err != nil {
7683 return err
7784 }
78删除: return returnCachedPaths(output, copied)
85新增: return returnCachedSelection(output, store, copied)
7986 default:
8087 return errors.New("guest file operation invalid")
8188 }
8289}
8390
84删除:func returnCachedPaths(output io.Writer, paths []string) error {
85删除: store, err := clipboardfiles.UserCacheStore()
86删除: if err != nil {
87删除: _ = os.RemoveAll(filepath.Dir(paths[0]))
88删除: return err
89删除: }
90删除: selection, err := store.Register(paths)
91删除: if err != nil {
92删除: _ = os.RemoveAll(filepath.Dir(paths[0]))
93删除: return err
94删除: }
91新增:func returnCachedSelection(output io.Writer, store clipboardfiles.CacheStore, selection clipboardfiles.CachedSelection) error {
9592 if err := json.NewEncoder(output).Encode(selection); err != nil {
9693 _ = store.Release(selection.ID)
9794 return err
修改cmd/cage-hyperv-manager/main_windows.go+9 −2看文件
@@ -38,7 +38,7 @@ func main() {
3838 os.Exit(2)
3939 }
4040 err = guestos.RunWindowsHostManagerService(*binding)
41删除: case "prepare":
41新增: case "prepare", "binding":
4242 id, parseErr := uuid.Parse(*vm)
4343 if parseErr != nil || id == uuid.Nil || *hostSID == "" || *binding != "" || enrollmentFlags {
4444 os.Exit(2)
@@ -46,7 +46,14 @@ func main() {
4646 ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
4747 defer cancel()
4848 var record guestos.WindowsHostManagerBinding
49删除: record, err = guestos.PrepareWindowsHostManagerBinding(ctx, id, *hostSID)
49新增: if os.Args[1] == "binding" {
50新增: record, err = guestos.LoadWindowsHostManagerBinding(guestos.WindowsHostManagerBindingPath(id))
51新增: if err == nil && (record.VMID != id || record.HostSID != *hostSID) {
52新增: err = fmt.Errorf("binding_mismatch")
53新增: }
54新增: } else {
55新增: record, err = guestos.PrepareWindowsHostManagerBinding(ctx, id, *hostSID)
56新增: }
5057 if err == nil {
5158 err = json.NewEncoder(os.Stdout).Encode(record)
5259 }
修改cmd/cage/main.go+13 −1看文件
@@ -298,7 +298,7 @@ func run() int {
298298 return appupdate.Run(path, args[1:], os.Stdout)
299299 }
300300 connectionID := ""
301删除: if (args[0] == "clipboard-files" || args[0] == "upload-files" || args[0] == "browser-file" || args[0] == "share-project") && len(args) >= 3 && args[2] == "--connection" {
301新增: if (args[0] == "clipboard-files" || args[0] == "upload-files" || args[0] == "browser-file" || args[0] == "desktop-file" || args[0] == "share-project") && len(args) >= 3 && args[2] == "--connection" {
302302 if len(args) < 4 || args[3] == "" {
303303 return fail(fmt.Errorf("missing file connection identity"))
304304 }
@@ -317,6 +317,18 @@ func run() int {
317317 _ = json.NewEncoder(os.Stdout).Encode(result)
318318 return 0
319319 }
320新增: if args[0] == "desktop-file" {
321新增: if len(args) != 3 || args[1] != "--json" {
322新增: return fail(fmt.Errorf("desktop-file --json --connection ID REQUEST"))
323新增: }
324新增: result, err := workbench.DesktopFileForConnection(workbench.DesktopHelperConfig(path, connectionID), connectionID, args[2])
325新增: if err != nil {
326新增: _ = json.NewEncoder(os.Stdout).Encode(map[string]string{"status": "error", "message": err.Error()})
327新增: return 1
328新增: }
329新增: _ = json.NewEncoder(os.Stdout).Encode(result)
330新增: return 0
331新增: }
320332 if args[0] == "share-project" {
321333 if connectionID == "" || len(args) != 4 || args[1] != "--json" || (args[2] != "read" && args[2] != "write") {
322334 return fail(fmt.Errorf("share-project --json --connection ID read|write DIRECTORY"))
修改desktop/Cage.swift+11 −5看文件
@@ -281,11 +281,14 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga
281281 private func clipboardCacheCommand(_ action: String, id: String = "", reply: @escaping (Any?, String?) -> Void) {
282282 guard let data = try? JSONSerialization.data(withJSONObject: ["action": action, "cache_id": id]),
283283 let request = String(data: data, encoding: .utf8) else { reply(nil,"剪贴板缓存请求无效"); return }
284删除: fileCommand(["clipboard-files", "--json", "cache", request], reply: reply)
284新增: fileCommand(["clipboard-files", "--json", "cache", request], replyLimit: 30 << 20, seconds: 10, reply: reply)
285285 }
286286 private func watchClipboardCaches() {
287287 guard clipboardCacheTimer == nil else { return }
288288 clipboardCacheTimer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] _ in self?.collectClipboardCaches() }
289新增: restoreClipboardCaches()
290新增: }
291新增: private func restoreClipboardCaches() {
289292 clipboardCacheCommand("list") { result, _ in
290293 self.clipboardCacheLoaded = true
291294 for selection in (result as? [String:Any])?["selections"] as? [[String:Any]] ?? [] {
@@ -319,7 +322,7 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga
319322 if !referenced { releaseClipboardCache(id) }
320323 }
321324 }
322删除: private func fileCommand(_ arguments: [String], reply: @escaping (Any?, String?) -> Void) {
325新增: private func fileCommand(_ arguments: [String], replyLimit: Int = 65536, seconds: TimeInterval = 1800, reply: @escaping (Any?, String?) -> Void) {
323326 guard let executable = Bundle.main.url(forResource: "cage", withExtension: nil) else { reply(nil,"无法找到文件传递组件"); return }
324327 DispatchQueue.global(qos: .userInitiated).async {
325328 let process = Process(); process.executableURL = executable
@@ -328,10 +331,10 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga
328331 do {
329332 try process.run()
330333 let timeout = DispatchWorkItem { if process.isRunning { process.terminate() } }
331删除: DispatchQueue.global().asyncAfter(deadline: .now() + 1800, execute: timeout)
334新增: DispatchQueue.global().asyncAfter(deadline: .now() + seconds, execute: timeout)
332335 defer { timeout.cancel() }
333336 let data = output.fileHandleForReading.readDataToEndOfFile(); process.waitUntilExit()
334删除: guard data.count <= 65536, let result = try JSONSerialization.jsonObject(with: data) as? [String:Any] else { throw CageUpdateError("文件操作未返回有效结果") }
337新增: guard data.count <= replyLimit, let result = try JSONSerialization.jsonObject(with: data) as? [String:Any] else { throw CageUpdateError("文件操作未返回有效结果") }
335338 DispatchQueue.main.async { reply(process.terminationStatus == 0 ? result : nil, process.terminationStatus == 0 ? nil : result["message"] as? String ?? "文件操作失败") }
336339 } catch { CageDiagnostics.record(error.localizedDescription); DispatchQueue.main.async { reply(nil,error.localizedDescription) } }
337340 }
@@ -487,7 +490,7 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga
487490 }
488491 if let id = body["files"] as? String, UUID(uuidString:id) != nil {
489492 fileCommand(["clipboard-files","--json","--connection",body["connection_id"] as? String ?? "local","receive",id]) { result, error in
490删除: guard error == nil, let paths = (result as? [String:Any])?["paths"] as? [String] else { replyHandler(nil,error ?? "剪贴板文件读取失败"); return }
493新增: guard error == nil, let paths = (result as? [String:Any])?["paths"] as? [String] else { self.restoreClipboardCaches(); replyHandler(nil,error ?? "剪贴板文件读取失败"); return }
491494 let cache = (result as? [String:Any])?["cache_id"] as? String ?? ""
492495 if !cache.isEmpty { self.clipboardCopies[cache] = paths; self.clipboardPending.insert(cache) }
493496 write(paths.map { URL(fileURLWithPath:$0) }, cache)
@@ -552,6 +555,9 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga
552555 guard response == .OK, let url = panel.url else { replyHandler(["canceled":true],nil); return }
553556 self.browserFile("save",id:id,connection:body["connection_id"] as? String ?? "local",path:url.path,reply:replyHandler)
554557 }
558新增: case "desktopFileAction":
559新增: guard let id = body["id"] as? String, UUID(uuidString:id) != nil else { replyHandler(nil,"文件打开标识无效"); return }
560新增: fileCommand(["desktop-file", "--json", "--connection", body["connection_id"] as? String ?? "local", id], reply: replyHandler)
555561 case "browserDownloadAction":
556562 guard let id = body["id"] as? String, let operation = body["operation"] as? String, ["open","reveal"].contains(operation) else { replyHandler(nil,"下载操作无效"); return }
557563 browserFile(operation,id:id,connection:body["connection_id"] as? String ?? "local",reply:replyHandler)
修改desktop/linux/cage-desktop.c+16 −4看文件
@@ -62,6 +62,7 @@ typedef struct {
6262 GSubprocess *process;
6363 GCancellable *cancel;
6464 guint deadline;
65新增: gsize output_limit;
6566 BackendCallback callback;
6667 gpointer data;
6768} Command;
@@ -156,7 +157,7 @@ static void command_finished(GObject *source, GAsyncResult *result, gpointer dat
156157 JsonObject *object = NULL;
157158 if (command->deadline) g_source_remove(command->deadline);
158159 if (g_subprocess_communicate_utf8_finish(G_SUBPROCESS(source), result, &output, NULL, &error)) {
159删除: if (!output || strlen(output) > 65536 || !json_parser_load_from_data(parser, output, -1, NULL) ||
160新增: if (!output || strlen(output) > command->output_limit || !json_parser_load_from_data(parser, output, -1, NULL) ||
160161 !JSON_NODE_HOLDS_OBJECT(json_parser_get_root(parser))) {
161162 g_set_error_literal(&error, G_IO_ERROR, G_IO_ERROR_INVALID_DATA, "Cage 后台未返回有效状态,请查看私有配置中的 logs/。");
162163 } else {
@@ -176,7 +177,7 @@ static void command_finished(GObject *source, GAsyncResult *result, gpointer dat
176177 g_object_unref(command->cancel);
177178 g_free(command);
178179}
179删除:static void backend_arguments(const char *const *args, guint seconds, BackendCallback callback, gpointer data) {
180新增:static void backend_arguments_limited(const char *const *args, guint seconds, gsize output_limit, BackendCallback callback, gpointer data) {
180181 GError *error = NULL;
181182 GSubprocessLauncher *launcher = g_subprocess_launcher_new(G_SUBPROCESS_FLAGS_STDOUT_PIPE | G_SUBPROCESS_FLAGS_STDERR_SILENCE);
182183 g_subprocess_launcher_setenv(launcher, "CLAUDE_CAGE_CONFIG", app.profile, TRUE);
@@ -197,9 +198,13 @@ static void backend_arguments(const char *const *args, guint seconds, BackendCal
197198 command->cancel = g_cancellable_new();
198199 command->callback = callback;
199200 command->data = data;
201新增: command->output_limit = output_limit;
200202 command->deadline = g_timeout_add_seconds(seconds, command_timeout, command);
201203 g_subprocess_communicate_utf8_async(process, NULL, command->cancel, command_finished, command);
202204}
205新增:static void backend_arguments(const char *const *args, guint seconds, BackendCallback callback, gpointer data) {
206新增: backend_arguments_limited(args, seconds, 65536, callback, data);
207新增:}
203208static void backend(const char *action, const char *option, BackendCallback callback, gpointer data) {
204209 const char *args[] = {app.backend, action, "--json", option, NULL};
205210 backend_arguments(args, 180, callback, data);
@@ -456,7 +461,7 @@ static void clipboard_cache_command(const char *action, const char *id, BackendC
456461 char *quoted = quote(id ? id : "");
457462 char *request = g_strdup_printf("{\"action\":\"%s\",\"cache_id\":%s}", action, quoted);
458463 const char *args[] = {app.backend, "clipboard-files", "--json", "cache", request, NULL};
459删除: backend_arguments(args, 10, callback, data);
464新增: backend_arguments_limited(args, 10, 30 << 20, callback, data);
460465 g_free(request); g_free(quoted);
461466}
462467static void clipboard_cache_ignored(JsonObject *object, const GError *error, gpointer data) { (void)object; (void)error; (void)data; }
@@ -565,7 +570,7 @@ static void clipboard_sync_provide(GtkClipboard *clipboard, GtkSelectionData *se
565570static void clipboard_sync_clear(GtkClipboard *clipboard, gpointer data) { (void)clipboard; g_strfreev(data); }
566571static void clipboard_files_received(JsonObject *object, const GError *error, gpointer data) {
567572 PendingReply *pending = data;
568删除: if (error) { reply_error(pending->reply, error->message); pending_free(pending); return; }
573新增: if (error) { clipboard_cache_command("list", "", clipboard_cache_loaded_reply, NULL); reply_error(pending->reply, error->message); pending_free(pending); return; }
569574 clipboard_cache_watch(); clipboard_cache_remember(object, TRUE);
570575 const char *cache = text_member(object, "cache_id");
571576 if (pending->generation != clipboard_generation || pending->revision != clipboard_current_revision()) { clipboard_cache_release(cache, pending); return; }
@@ -763,6 +768,13 @@ static gboolean bridge_received(WebKitUserContentManager *manager, JSCValue *val
763768 reply_json(reply, context, state);
764769 g_free(state); g_free(version); g_free(message);
765770 }
771新增: } else if (!strcmp(name, "desktopFileAction")) {
772新增: const char *id = text_member(request, "id"), *connection = text_member(request, "connection_id");
773新增: if (!g_uuid_string_is_valid(id)) reply_error(reply, "文件打开标识无效。");
774新增: else {
775新增: const char *args[] = {app.backend,"desktop-file","--json","--connection",*connection ? connection : "local",id,NULL};
776新增: backend_arguments(args,1800,browser_file_finished,pending_reply(reply,context));
777新增: }
766778 } else if (!strcmp(name, "saveBrowserDownload") || !strcmp(name, "browserDownloadAction")) {
767779 const char *id = text_member(request, "id");
768780 const char *operation = !strcmp(name, "saveBrowserDownload") ? "save" : text_member(request, "operation");
修改desktop/windows/Backend.cs+8 −5看文件
@@ -28,10 +28,10 @@ internal static class Backend
2828 return start;
2929 }
3030
31删除: public static Task<(int Exit, JsonElement Data)> Json(string[] arguments, CancellationToken cancellation = default, TimeSpan? deadline = null) =>
32删除: JsonAt(Executable, arguments, cancellation, deadline);
31新增: public static Task<(int Exit, JsonElement Data)> Json(string[] arguments, CancellationToken cancellation = default, TimeSpan? deadline = null, int outputLimit = 65536) =>
32新增: JsonAt(Executable, arguments, cancellation, deadline, outputLimit);
3333
34删除: public static async Task<(int Exit, JsonElement Data)> JsonAt(string executable, string[] arguments, CancellationToken cancellation = default, TimeSpan? deadline = null)
34新增: public static async Task<(int Exit, JsonElement Data)> JsonAt(string executable, string[] arguments, CancellationToken cancellation = default, TimeSpan? deadline = null, int outputLimit = 65536)
3535 {
3636 using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellation);
3737 timeout.CancelAfter(deadline ?? TimeSpan.FromMinutes(3));
@@ -41,12 +41,15 @@ internal static class Backend
4141 try
4242 {
4343 var errors = Drain(process.StandardError, timeout.Token);
44删除: var text = await ReadLimited(process.StandardOutput, 65536, timeout.Token);
44新增: var text = await ReadLimited(process.StandardOutput, outputLimit, timeout.Token);
4545 await process.WaitForExitAsync(timeout.Token); await errors;
4646 try { return (process.ExitCode, JsonDocument.Parse(text).RootElement.Clone()); }
4747 catch (JsonException) { throw new IOException("Cage 后台未返回有效状态,请查看工作台日志"); }
4848 }
49删除: finally { if (!process.HasExited) process.Kill(); }
49新增: finally
50新增: {
51新增: if (!process.HasExited) { process.Kill(); await process.WaitForExitAsync(); }
52新增: }
5053 }
5154
5255 public static async Task<string> ReadLimited(StreamReader reader, int limit, CancellationToken token)
修改desktop/windows/MainWindow.cs+9 −0看文件
@@ -351,6 +351,15 @@ internal sealed class MainWindow : Form
351351 case "clipboardSyncRead": result = await SharedClipboard.Read(request, lifetime.Token); break;
352352 case "clipboardSyncWrite": result = await SharedClipboard.Write(request, lifetime.Token); break;
353353 case "clipboardSyncRelease": result = await SharedClipboard.Release(request, lifetime.Token); break;
354新增: case "desktopFileAction":
355新增: {
356新增: var fileRequestID = request.Text("id");
357新增: if (!Guid.TryParse(fileRequestID, out _)) throw new InvalidDataException("文件打开标识无效");
358新增: var connection = request.Text("connection_id");
359新增: var response = await Backend.Json(["desktop-file", "--json", "--connection", string.IsNullOrEmpty(connection) ? "local" : connection, fileRequestID], lifetime.Token, TimeSpan.FromMinutes(30));
360新增: if (response.Exit != 0) throw new IOException(response.Data.Text("message"));
361新增: result = response.Data; break;
362新增: }
354363 case "saveBrowserDownload":
355364 case "browserDownloadAction":
356365 {
修改desktop/windows/SharedClipboard.cs+12 −7看文件
@@ -33,7 +33,7 @@ internal static class SharedClipboard
3333 private static async Task<JsonElement> Cache(string action, string id = "")
3434 {
3535 var request = JsonSerializer.Serialize(new { action, cache_id = id });
36删除: var result = await Backend.Json(["clipboard-files", "--json", "cache", request], CancellationToken.None, TimeSpan.FromSeconds(10));
36新增: var result = await Backend.Json(["clipboard-files", "--json", "cache", request], CancellationToken.None, TimeSpan.FromSeconds(10), outputLimit: 30 << 20);
3737 if (result.Exit != 0) throw new IOException("clipboard_cache_operation_failed");
3838 return result.Data;
3939 }
@@ -60,10 +60,10 @@ internal static class SharedClipboard
6060 {
6161 if (!loaded)
6262 {
63删除: loaded = true;
6463 var result = await Cache("list");
6564 foreach (var item in result.GetProperty("selections").EnumerateArray())
6665 copies.TryAdd(item.Text("cache_id"), item.GetProperty("paths").EnumerateArray().Select(path => path.GetString()!).ToArray());
66新增: loaded = true;
6767 }
6868 foreach (var copy in copies.ToArray())
6969 {
@@ -127,17 +127,22 @@ internal static class SharedClipboard
127127
128128 public static async Task<object> Write(JsonElement request, CancellationToken token)
129129 {
130新增: _ = Revision;
130131 var currentGeneration = generation;
131132 string[]? paths = null;
132133 var cache = "";
133134 if (request.Text("files") is { Length: > 0 } id)
134135 {
135136 if (!Guid.TryParse(id, out _)) throw new InvalidDataException("剪贴板文件标识无效");
136删除: var response = await Backend.Json(["clipboard-files", "--json", "--connection", request.Text("connection_id"), "receive", id], token, TimeSpan.FromMinutes(30));
137删除: if (response.Exit != 0) throw new IOException(response.Data.Text("message"));
138删除: paths = response.Data.GetProperty("paths").EnumerateArray().Select(value => value.GetString()!).ToArray();
139删除: cache = response.Data.Text("cache_id");
140删除: if (cache.Length != 0) { copies[cache] = paths; pending.Add(cache); }
137新增: try
138新增: {
139新增: var response = await Backend.Json(["clipboard-files", "--json", "--connection", request.Text("connection_id"), "receive", id], token, TimeSpan.FromMinutes(30));
140新增: if (response.Exit != 0) throw new IOException(response.Data.Text("message"));
141新增: paths = response.Data.GetProperty("paths").EnumerateArray().Select(value => value.GetString()!).ToArray();
142新增: cache = response.Data.Text("cache_id");
143新增: if (cache.Length != 0) { copies[cache] = paths; pending.Add(cache); }
144新增: }
145新增: catch { loaded = false; throw; }
141146 }
142147 try
143148 {
修改docs/getting-started.md+2 −2看文件
@@ -23,7 +23,7 @@
2323| 平台 | 安装方式 |
2424|---|---|
2525| macOS | 下载 Apple Silicon `.dmg`,打开后将 Cage 拖入 Applications(应用程序),再从“应用程序”启动。 |
26删除:| Windows | 下载 x64 `.exe` 安装器,运行后从开始菜单打开 Cage。预览包会标明“未签名”,用于手动安装测试,不能自动安装更新。详见 [Windows 指南](windows.md)。 |
26新增:| Windows | 下载 x64 `.exe` 安装器,运行后从开始菜单打开 Cage。可信签名包支持校验发布者身份;旧版或单独标明“未签名”的预览包仅用于手动安装测试,不能自动安装更新。详见 [Windows 指南](windows.md)。 |
2727| Linux | 下载 x86_64 `.deb`,使用 `sudo apt install ./Cage-<版本>-linux-amd64.deb` 安装。缺少 QEMU、GTK、WebKitGTK、OpenSSH 等主机依赖时,APT 会从系统配置的软件源补齐,再从应用菜单打开 Cage。详见 [Linux 指南](linux.md)。 |
2828
2929无需先安装开发工具或 Clash。签名、公证和平台验证情况以该安装包的 Release 说明为准。如果系统拒绝打开,先按[安装问题](troubleshooting.md#下载或安装受阻)核对版本与来源。下述代理、环境和项目操作共用。
@@ -289,7 +289,7 @@ macOS 的 `0.1.3-alpha.1` 及更早公开版本存在本机更新校验错误。
289289
290290检查和下载使用已经应用并运行的所选代理,失败不会改用主机直连。自动安装要求当前 App 与新 App 使用相同发布者的 Developer ID 签名,且新包通过 Apple 验证;ad-hoc 开发构建不能自动安装。更新器使用公开的 GitHub Releases 接口,无需 GitHub 登录,也不读取浏览器会话。若提示更新源不可访问,先确认所选代理可用,再检查对应 Release 是否仍公开且附件完整;需要手动下载时使用同一公开 Release。实际安装、重启和恢复的验收范围以该版本说明为准。
291291
292删除:手动替换 App 前,保存文件并选择“停止环境并退出”。新 App 会核对后台版本;若出现“更新待完成”,可先打开现有环境保存文件,再选择“保存后停止环境并完成更新”。Alpha 版本间的兼容性和特殊迁移要求以对应 Release 说明为准。
292新增:手动替换 App 前,保存文件并选择“停止环境并退出”。新 App 会核对后台版本;若出现“更新待完成”,可先打开现有环境保存文件,再选择“保存后停止环境并完成更新”。预发行版本间的兼容性和特殊迁移要求以对应 Release 说明为准。
293293
294294“设置 → 环境与恢复”分别提供环境组件与工具更新,并显示实际版本。组件更新会重启浏览器和编辑器,保留 VM、磁盘和工作台独立终端;编辑器内的集成终端可能结束,操作前需要保存内容。依赖安装和工具更新使用所选代理,无需业务网络已经放行;工具更新采用当前 App 指定的最低版本,人工暂停外网不会被更新操作解除。替换 App 不等于已经升级全部 Linux 工具。
295295
修改docs/guide/guest-systems.md+9 −0看文件
@@ -33,6 +33,7 @@ keywords: 客机 客户机 克隆 本机 系统选择 macOS Windows Debian Ubunt
3333| Mac 本机版本匹配 | 真实首次创建、系统恢复、权限确认、项目双向读写、编辑器及冷启动持久性 | 官方 Claude 在线登录与完整工作流程;本轮创建验证保持客机外网关闭 |
3434| Windows 本机版本匹配 | 官方材料下载与校验、自动建机、首次启动、冷启动和测试文件保留 | 修复后的最终工作台登记与完整首次使用 |
3535| Linux 同发行版匹配 | 镜像身份、安装来源和模板;Ubuntu 22.04 容器中的原生窗口、重装与卸载数据保留,以及真实浏览器启动 | 完整 KVM 首装、项目共享、物理桌面输入和官方 Claude 登录 |
36新增:| 独立 Ubuntu 22.04 | Mac ARM64 真实安装、冷启动、项目共享、终端、浏览器、编辑器、中文输入、音频、剪贴板、Desktop 安装及欢迎页、网络暂停与代理中断、原磁盘持久化 | Windows WHPX / Linux KVM 实机首装,官方 Claude 登录和业务会话 |
3637
3738多账号、手机和原生 Desktop 文件操作还需各自的应用级检查,分别见[多账号与额度](accounts.md)、[手机连接](mobile.md)和[Claude Desktop](desktop.md)。
3839
@@ -136,3 +137,11 @@ macOS 默认工作区使用与其他项目相同的文件夹授权。主界面
136137手机用于连接电脑上的 Cage,接续 Claude Code 会话、处理工具审批和操作远程窗口,任务仍在电脑上运行。手机不会安装上述桌面客机系统;连接方式见[手机连接与远程会话](mobile.md)。
137138
138139macOS 客机的手机 Desktop 共享电脑 Cage 中的同一个 Claude 窗口和登录状态。需要通过外部浏览器登录 Claude 时,在电脑 Cage 中完成登录,手机随后继续使用该登录状态。虚拟 Mac 锁屏或切换系统账户后,原手机图形会话结束,需要登录原客机账户后重新打开。
140新增:
141新增:## 环境存储与项目恢复
142新增:
143新增:环境存储所在磁盘未连接或迁移尚未完成时,工作台会提示“环境存储需要恢复”。连接原磁盘后,在设置的项目与环境页面点击“重试恢复”;Windows 如提示系统助手需要修复,使用“修复系统助手并恢复”,完成系统授权后继续。恢复完成前不要另建环境或删除原虚拟磁盘。
144新增:
145新增:macOS 项目连接遇到权限问题时,按提示打开对应的文件共享、屏幕录制或辅助功能授权入口。完成授权并关闭维护窗口后,Cage 会重新检查项目连接。需要客机登录时,先登录并解锁普通账户,再重试项目。
146新增:
147新增:旧版默认项目若位于 Cage 配置目录中,升级后保留该目录中的文件与环境身份。请按设置页显示的旧目录找到项目,将其移至配置目录之外的专用项目文件夹后,再从工作台打开。
修改docs/guide/tailscale.md+1 −1看文件
@@ -12,7 +12,7 @@ keywords: Tailscale tailnet 设备 私网 SSH Web TCP 代理
1212
1313启动 Cage 环境,打开 Tailscale 面板,点击「连接并登录」。在打开的官方授权页面完成登录,然后重新打开 Tailscale 面板。连接成功后,可看到当前账号、网络名称、Cage 的私网地址与设备清单。网络要求设备审批时,面板显示「等待管理员批准」,由网络管理员在 Tailscale 管理台批准 Cage 后即可继续。
1414
15删除:Debian 环境首次使用时需点击「安装 Tailscale」。macOS 和 Windows 环境随客机组件提供,已有环境可按面板提示更新环境组件。
15新增:Debian 环境首次使用时需点击「安装 Tailscale」。macOS 和 Windows 环境随客机组件提供,已有环境可按面板提示更新环境组件。Linux 已安装的 Tailscale 也会随环境组件同步更新,设备身份和 SSH 公钥保留;尚未安装的环境继续按需安装。
1616
1717设备清单显示当前网络允许 Cage 发现的设备,在线设备排在前面,支持按名称、系统或私网地址搜索。清单为空时,先检查其他设备是否加入同一网络,以及网络的设备访问规则。
1818
修改docs/windows.md+2 −2看文件
@@ -25,7 +25,7 @@ DISM /Online /Enable-Feature /FeatureName:HypervisorPlatform /All
2525
2626## 安装并开始工作
2727
28删除:1. 在[项目主页](https://lee-xeo.github.io/Claude-Cage/#download)点击“下载应用”并选择 Windows,核对对应发行条目的 `SHA256SUMS`。签名安装包名为 `Cage-<版本>-windows-amd64-setup.exe`;当前公开预览包名为 `Cage-<版本>-windows-amd64-setup-unsigned.exe`,主页标明“预览版 · 未签名”。未签名包可能触发未知发布者提示,需手动安装和更新。
28新增:1. 在[项目主页](https://lee-xeo.github.io/Claude-Cage/#download)点击“下载应用”并选择 Windows,核对对应发行条目的 `SHA256SUMS`。签名安装包名为 `Cage-<版本>-windows-amd64-setup.exe`;单独标明未签名的开发预览包名为 `Cage-<版本>-windows-amd64-setup-unsigned.exe`。未签名包可能触发未知发布者提示,需手动安装和更新。
29292. 运行安装程序,选择安装位置。首次安装时,默认选择本地 D 盘的 `D:\Cage`;没有本地 D 盘时使用当前用户的 `%LOCALAPPDATA%\Programs\Cage`。已有安装沿用原目录,也可以手动选择其他位置。安装器随附 .NET 桌面运行组件、WebView2 安装程序、QEMU、OpenSSH 客户端和代理核心,无需另装 Go、Node.js 或 Clash。
30303. 在“快捷方式”页选择“添加桌面快捷方式”和“添加到开始菜单”。首次安装默认勾选两项,覆盖安装沿用上次选择,旧安装按已有快捷方式恢复选择。卸载会清理 Cage 创建的快捷方式。
31314. 从选中的快捷方式启动 Cage,选择客机系统。如果 C 盘空间有限,在工作台点击“选择环境存储位置”,选择其他磁盘的专用空文件夹,再导入代理并启动环境。镜像、工具和虚拟磁盘按所选系统准备;已有环境也可以从设置迁移。见[选盘与迁移步骤](getting-started.md#选择环境存储位置)和[客机系统指南](guide/guest-systems.md)。
@@ -60,7 +60,7 @@ Windows Hypervisor Platform 已启用时,QEMU 仍可能因嵌套虚拟化初
6060
6161当前开发构建在升级或强制结束后会自动检查旧连接记录及控制锁。旧锁空闲时修复其所有者和私有权限,再由新后台重建连接记录;真实后台持有的锁继续阻止接管。权限无法迁移时显示具体原因。请保留个人配置目录,不要通过删除账户或虚拟磁盘解决连接问题。点右上角 × 隐藏窗口并保留托盘,结束应用请使用“退出 Cage”;运行中的环境可选择保留运行或停止后退出。
6262
63删除:本地开发包已适配含中文的安装目录。启动时优先读取随附 QEMU 的 UEFI 固件,无需在用户目录另存副本。在默认虚拟 CPU 配置下,Cage 会向 Windows 虚拟机监控程序平台查询可用指令;Claude Code 需要客机提供 SSE4.2。自行指定了虚拟 CPU 型号的环境仍沿用该设置。这两项修复尚未进入公开的 `v0.1.5-alpha.2` 安装包。
63新增:Cage 支持含中文的安装目录。启动时优先读取随附 QEMU 的 UEFI 固件,无需在用户目录另存副本。在默认虚拟 CPU 配置下,Cage 会向 Windows 虚拟机监控程序平台查询可用指令;Claude Code 需要客机提供 SSE4.2。自行指定了虚拟 CPU 型号的环境仍沿用该设置。
6464
6565- 提示虚拟化不可用:检查 BIOS/UEFI 的虚拟化开关及 Windows 虚拟机监控程序平台,重启后再试。远程或嵌套虚拟机还需要外层宿主允许嵌套虚拟化。
6666- 提示缺少 WebView2:重新运行完整安装程序。不要从第三方站点下载同名 DLL。
修改internal/cage/browser-clipboard.mjs+61 −20看文件
@@ -3,7 +3,7 @@ import { randomBytes } from "node:crypto";
33// This runs before site scripts, in each new document's main world. The binding
44// and token stay in the closure. Existing documents expose only captured
55// function references to CDP for native-code verification before installation.
6删除:function prepareCopies(bindingName, token, contextSetter, limit) {
6新增:function prepareCopies(bindingName, token, contextSetter, limit, includeChanges) {
77 const emit = globalThis[bindingName];
88 delete globalThis[bindingName];
99 if (typeof emit !== "function") return;
@@ -58,6 +58,8 @@ function prepareCopies(bindingName, token, contextSetter, limit) {
5858 ).get;
5959 const getSelection = Document.prototype.getSelection;
6060 const selectionText = Selection.prototype.toString;
61新增: const selectionCollapsed = descriptor(Selection.prototype, "isCollapsed").get;
62新增: const schedule = globalThis.setTimeout;
6163 const nativeFunctions = {
6264 "": emit,
6365 apply,
@@ -93,6 +95,8 @@ function prepareCopies(bindingName, token, contextSetter, limit) {
9395 "get selectionEnd#textarea": textareaEnd,
9496 getSelection,
9597 toString: selectionText,
98新增: "get isCollapsed": selectionCollapsed,
99新增: setTimeout: schedule,
96100 };
97101 const plain = (value) => {
98102 const type = apply(lower, value, []);
@@ -118,11 +122,15 @@ function prepareCopies(bindingName, token, contextSetter, limit) {
118122 context && current() && apply(activated, activation, [])
119123 ? { epoch, context }
120124 : null;
121删除: const selectedControlText = () => {
125新增: const focusedElement = () => {
122126 let element = apply(activeElement, document, []);
123127 let root;
124128 while (element && (root = apply(shadowRoot, element, [])))
125129 element = apply(shadowActiveElement, root, []);
130新增: return element;
131新增: };
132新增: const selectedControlText = () => {
133新增: const element = focusedElement();
126134 if (!element) return;
127135 const tag = apply(tagName, element, []);
128136 if (tag !== "TEXTAREA" && tag !== "INPUT") return;
@@ -150,22 +158,39 @@ function prepareCopies(bindingName, token, contextSetter, limit) {
150158 const selection = apply(getSelection, document, []);
151159 return selection && apply(selectionText, selection, []);
152160 };
161新增: const hasCopySelection = () => {
162新增: const element = focusedElement();
163新增: if (!element) return false;
164新增: const tag = apply(tagName, element, []);
165新增: if (tag === "INPUT" || tag === "TEXTAREA") {
166新增: if (tag === "INPUT") {
167新增: const type = apply(inputType, element, []);
168新增: if (type !== "text" && type !== "search" && type !== "url" && type !== "tel") return false;
169新增: }
170新增: const start = apply(tag === "INPUT" ? inputStart : textareaStart, element, []);
171新增: const end = apply(tag === "INPUT" ? inputEnd : textareaEnd, element, []);
172新增: return start !== null && end > start;
173新增: }
174新增: const selection = apply(getSelection, document, []);
175新增: return selection && !apply(selectionCollapsed, selection, []);
176新增: };
153177 const send = (text, started) => {
154178 if (
155179 started === null ||
156180 epoch !== started.epoch ||
157181 !current() ||
158删除: typeof text !== "string" ||
159删除: text.length > limit
182新增: !includeChanges && (typeof text !== "string" || text.length > limit)
160183 )
161184 return;
185新增: const content = typeof text === "string" && text.length <= limit
186新增: ? ',"text":' + stringify(text)
187新增: : ',"changed":true';
162188 emit(
163189 '{"token":"' +
164190 token +
165191 '","context":' +
166192 stringify(started.context) +
167删除: ',"text":' +
168删除: stringify(text) +
193新增: content +
169194 "}",
170195 );
171196 };
@@ -229,7 +254,9 @@ function prepareCopies(bindingName, token, contextSetter, limit) {
229254 },
230255 });
231256 const promise = apply(write, this, [items]);
232删除: if (started === null || items.length !== 1) return promise;
257新增: if (started === null) return promise;
258新增: if (includeChanges) return watch(promise, undefined, started);
259新增: if (items.length !== 1) return promise;
233260 let text,
234261 written = false;
235262 const completed = () => {
@@ -297,16 +324,27 @@ function prepareCopies(bindingName, token, contextSetter, limit) {
297324 return result;
298325 },
299326 });
300删除: apply(addListener, document, [
301删除: "copy",
327新增: const copied =
302328 (event) => {
303删除: if (operation && event.isTrusted) {
329新增: if (!event.isTrusted) return;
330新增: if (operation && !operation.native) {
304331 operation.event = event;
305332 operation.data = apply(clipboardData, event, []);
333新增: } else if (includeChanges) {
334新增: const copy = { native: true, event, data: apply(clipboardData, event, []), started: begin(), selected: hasCopySelection() };
335新增: operation = copy;
336新增: // The default copy runs after the DOM event. A trusted no-selection
337新增: // or password-field event must never export an older clipboard.
338新增: apply(schedule, globalThis, [() => {
339新增: if (operation === copy) operation = undefined;
340新增: if (apply(prevented, event, [])) {
341新增: if (typeof copy.text === "string") send(copy.text, copy.started);
342新增: } else if (copy.selected) send(undefined, copy.started);
343新增: }, 0]);
306344 }
307删除: },
308删除: true,
309删除: ]);
345新增: };
346新增: apply(addListener, document, ["copy", copied, true]);
347新增: if (includeChanges) apply(addListener, document, ["cut", copied, true]);
310348 define(documentPrototype, "execCommand", {
311349 configurable: true,
312350 writable: true,
@@ -317,7 +355,7 @@ function prepareCopies(bindingName, token, contextSetter, limit) {
317355 if (apply(lower, name, []) !== "copy" || this !== document)
318356 return apply(exec, this, [name, ...args]);
319357 const parent = operation;
320删除: const copy = { started: begin() };
358新增: const copy = { started: begin(), selected: includeChanges && hasCopySelection() };
321359 operation = copy;
322360 let result;
323361 try {
@@ -326,12 +364,15 @@ function prepareCopies(bindingName, token, contextSetter, limit) {
326364 operation = parent;
327365 }
328366 if (result && copy.event) {
329删除: if (apply(prevented, copy.event, [])) send(copy.text, copy.started);
367新增: if (apply(prevented, copy.event, [])) {
368新增: if (typeof copy.text === "string") send(copy.text, copy.started);
369新增: }
330370 else {
331371 // Chromium's default DOM copy may add image alt text or transform
332372 // whitespace. Text controls have an exact selection representation.
333373 const text = selectedControlText();
334374 if (text) send(text, copy.started);
375新增: else if (copy.selected) send(undefined, copy.started);
335376 }
336377 }
337378 return result;
@@ -342,9 +383,10 @@ function prepareCopies(bindingName, token, contextSetter, limit) {
342383}
343384
344385export class BrowserClipboard {
345删除: constructor(cdp, onCopy) {
386新增: constructor(cdp, onCopy, { includeChanges = false } = {}) {
346387 this.cdp = cdp;
347388 this.onCopy = onCopy;
389新增: this.includeChanges = includeChanges;
348390 this.sessions = new Map();
349391 this.copyContexts = new Map();
350392 }
@@ -369,7 +411,7 @@ export class BrowserClipboard {
369411 await this.cdp("Page.enable", {}, sessionId);
370412 await this.cdp("Runtime.enable", {}, sessionId);
371413 await this.cdp("Runtime.addBinding", { name: state.name }, sessionId);
372删除: const source = `(${prepareCopies})(${JSON.stringify(state.name)},${JSON.stringify(state.token)},${JSON.stringify(state.contextSetter)},65536)`;
414新增: const source = `(${prepareCopies})(${JSON.stringify(state.name)},${JSON.stringify(state.token)},${JSON.stringify(state.contextSetter)},65536,${this.includeChanges})`;
373415 await this.cdp(
374416 "Page.addScriptToEvaluateOnNewDocument",
375417 { source: `(${source})?.install()` },
@@ -572,13 +614,12 @@ export class BrowserClipboard {
572614 value?.token !== state.token ||
573615 typeof value.context !== "string" ||
574616 value.context.length > 64 ||
575删除: typeof value.text !== "string" ||
576删除: value.text.length > 65536
617新增: !(typeof value.text === "string" && value.text.length <= 65536 || this.includeChanges && value.changed === true && value.text === undefined)
577618 )
578619 return;
579620 this.onCopy({
580621 id: state.tabId,
581删除: text: value.text,
622新增: ...(typeof value.text === "string" ? { text: value.text } : { changed: true }),
582623 context: value.context,
583624 });
584625 }
修改internal/cage/browser-clipboard.test.mjs+14 −0看文件
@@ -113,6 +113,20 @@ test("host copy context reaches every existing frame and newly attached child",
113113 assert.equal(observer.sessions.size, 0);
114114});
115115
116新增:test("private clipboard format notifications require an enabled receiver and the binding token", async () => {
117新增: for (const includeChanges of [false, true]) {
118新增: const copies = [];
119新增: const observer = new BrowserClipboard(async () => ({}), value => copies.push(value), { includeChanges });
120新增: await observer.attach("session", "tab");
121新增: const state = observer.sessions.get("session");
122新增: observer.event({ sessionId: "session", method: "Runtime.executionContextCreated", params: { context: { id: 1, auxData: { isDefault: true, frameId: "frame" } } } });
123新增: for (const token of ["wrong", state.token]) observer.event({ sessionId: "session", method: "Runtime.bindingCalled", params: {
124新增: name: state.name, executionContextId: 1, payload: JSON.stringify({ token, context: "gesture", changed: true }),
125新增: } });
126新增: assert.deepEqual(copies, includeChanges ? [{ id: "tab", context: "gesture", changed: true }] : []);
127新增: }
128新增:});
129新增:
116130test("failed setup removes the session and allows retry", async () => {
117131 let fail = true;
118132 const observer = new BrowserClipboard(
修改internal/cage/desktop-files.py+79 −3看文件
@@ -321,6 +321,13 @@ class Portal:
321321 <arg type="a{sv}" direction="in"/><arg type="o" direction="out"/></method>
322322 <method name="SaveFile"><arg type="s" direction="in"/><arg type="s" direction="in"/>
323323 <arg type="a{sv}" direction="in"/><arg type="o" direction="out"/></method>
324新增: </interface><interface name="org.freedesktop.portal.OpenURI">
325新增: <property name="version" type="u" access="read"/>
326新增: <method name="OpenDirectory"><arg type="s" direction="in"/><arg type="h" direction="in"/>
327新增: <arg type="a{sv}" direction="in"/><arg type="o" direction="out"/></method>
328新增: </interface><interface name="org.freedesktop.FileManager1">
329新增: <method name="ShowItems"><arg type="as" direction="in"/><arg type="s" direction="in"/></method>
330新增: <method name="ShowFolders"><arg type="as" direction="in"/><arg type="s" direction="in"/></method>
324331 </interface><interface name="org.freedesktop.portal.Request">
325332 <method name="Close"/><signal name="Response"><arg type="u"/><arg type="a{sv}"/></signal>
326333 </interface></node>'''
@@ -362,6 +369,17 @@ class Portal:
362369 self.unref(name_reply)
363370 if code_value != 1:
364371 raise RuntimeError('已有其他桌面文件选择服务')
372新增: name_reply = call(self.connection, b'org.freedesktop.DBus', b'/org/freedesktop/DBus', b'org.freedesktop.DBus',
373新增: b'RequestName', self.tuple(self.new_string(b'org.freedesktop.FileManager1'), self.new_uint(4)),
374新增: None, 0, 5000, None, None)
375新增: if not name_reply:
376新增: raise RuntimeError('本机文件打开服务无法注册')
377新增: code = self.child(name_reply, 0)
378新增: code_value = bind(self.glib, 'g_variant_get_uint32', u, p)(code)
379新增: self.unref(code)
380新增: self.unref(name_reply)
381新增: if code_value != 1:
382新增: raise RuntimeError('已有其他文件管理服务')
365383 self.reply = bind(self.gio, 'g_dbus_method_invocation_return_value', None, p, p)
366384 self.error = bind(self.gio, 'g_dbus_method_invocation_return_dbus_error', None, p, s, s)
367385 self.emit = bind(self.gio, 'g_dbus_connection_emit_signal', C.c_int, p, s, s, s, s, p, p)
@@ -378,6 +396,10 @@ class Portal:
378396 self.vtable = VTable(self.method_callback, self.property_callback, None)
379397 if not self.register(self.connection, ROOT.encode(), self.interface(self.node, PORTAL.encode()), C.byref(self.vtable), None, None, None):
380398 raise RuntimeError('桌面文件选择接口无法注册')
399新增: for object_path, interface in ((ROOT, 'org.freedesktop.portal.OpenURI'),
400新增: ('/org/freedesktop/FileManager1', 'org.freedesktop.FileManager1')):
401新增: if not self.register(self.connection, object_path.encode(), self.interface(self.node, interface.encode()), C.byref(self.vtable), None, None, None):
402新增: raise RuntimeError('本机文件打开接口无法注册')
381403 self.loop = bind(self.glib, 'g_main_loop_new', p, p, C.c_int)(None, False)
382404
383405 def tuple(self, *values):
@@ -401,6 +423,22 @@ class Portal:
401423
402424 def method(self, _connection, sender, path, _interface, method, parameters, invocation, _data):
403425 try:
426新增: if method in (b'ShowItems', b'ShowFolders'):
427新增: uris = self.child(parameters, 0)
428新增: try:
429新增: count = bind(self.glib, 'g_variant_n_children', C.c_size_t, C.c_void_p)(uris)
430新增: if count > 32:
431新增: raise ValueError('一次最多打开 32 个位置')
432新增: for index in range(count):
433新增: uri = self.child(uris, index)
434新增: try:
435新增: self.broker.open_path(self.string(uri, None).decode(), 'reveal' if method == b'ShowItems' else 'open')
436新增: finally:
437新增: self.unref(uri)
438新增: finally:
439新增: self.unref(uris)
440新增: self.reply(invocation, self.tuple())
441新增: return
404442 if method == b'Close':
405443 request = next((r for r in self.broker.requests.values() if r.get('handle') == path.decode() and r.get('sender') == sender.decode()), None)
406444 if request:
@@ -424,9 +462,24 @@ class Portal:
424462 key = None
425463 try:
426464 saving = method == b'SaveFile'
427删除: key = self.broker.start('save' if saving else 'chooser', self.option(options, 'multiple', False) and not directory,
428删除: directory=directory,
429删除: handle=handle, sender=sender.decode(), title=self.string(title, None).decode())['id']
465新增: if method == b'OpenDirectory':
466新增: # The handle belongs to the caller's D-Bus message, not
467新增: # to this service's file descriptor table.
468新增: message = bind(self.gio, 'g_dbus_method_invocation_get_message', C.c_void_p, C.c_void_p)(invocation)
469新增: descriptors = bind(self.gio, 'g_dbus_message_get_unix_fd_list', C.c_void_p, C.c_void_p)(message)
470新增: index = bind(self.glib, 'g_variant_get_handle', C.c_int, C.c_void_p)(title)
471新增: fd = bind(self.gio, 'g_unix_fd_list_get', C.c_int, C.c_void_p, C.c_int, C.c_void_p)(descriptors, index, None) if descriptors else -1
472新增: if fd < 0:
473新增: raise ValueError('文件位置无法读取')
474新增: try:
475新增: key = self.broker.open_path(os.readlink('/proc/self/fd/' + str(fd)), 'reveal',
476新增: handle=handle, sender=sender.decode())['id']
477新增: finally:
478新增: os.close(fd)
479新增: else:
480新增: key = self.broker.start('save' if saving else 'chooser', self.option(options, 'multiple', False) and not directory,
481新增: directory=directory,
482新增: handle=handle, sender=sender.decode(), title=self.string(title, None).decode())['id']
430483 if saving:
431484 if not self.broker.downloads:
432485 raise ValueError('下载服务不可用')
@@ -548,6 +601,29 @@ def clipboard(paths, expected_context=None):
548601
549602
550603def main():
604新增: if len(sys.argv) == 3 and sys.argv[1] == '--open':
605新增: import http.client
606新增: import socket
607新增: class Connection(http.client.HTTPConnection):
608新增: def connect(self):
609新增: self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
610新增: self.sock.settimeout(self.timeout)
611新增: self.sock.connect('/run/cage-desktop/files.sock')
612新增: client = Connection('localhost', timeout=5)
613新增: try:
614新增: # Electron's folder fallback invokes `xdg-open .` with the target
615新增: # directory as its cwd. Preserve the caller's cwd across the socket.
616新增: path = sys.argv[2]
617新增: if not path.startswith('file:'):
618新增: path = str(Path(path).resolve(strict=True))
619新增: client.request('POST', '/open', json.dumps({'path': path}), {'Content-Type': 'application/json'})
620新增: response = client.getresponse()
621新增: data = response.read()
622新增: if response.status != 200:
623新增: raise ValueError(data.decode())
624新增: finally:
625新增: client.close()
626新增: return
551627 if len(sys.argv) == 3 and sys.argv[1] == '--save-file':
552628 # Terminal attachments are independent of the graphical session.
553629 root = Path.home() / '.local/share/cage/attachments/files'
修改internal/cage/environment.go+59 −10看文件
@@ -2,20 +2,58 @@ package cage
22
33import (
44 "encoding/json"
5删除: "github.com/sylvinus/agent-vm/internal/paths"
5新增: "errors"
66 "os"
77 "path/filepath"
88 "strings"
99
10新增: "github.com/sylvinus/agent-vm/internal/paths"
1011 "github.com/sylvinus/agent-vm/internal/vmname"
1112)
1213
13删除:// EnvironmentDir is the stable VM anchor for this profile, independent of projects.
14删除:func EnvironmentDir(profile string) string {
15删除: var saved struct {
16删除: Directory string `json:"directory"`
14新增:type EnvironmentRecord struct {
15新增: Directory string `json:"directory"`
16新增: IdentityDirectory string `json:"identity_directory,omitempty"`
17新增:}
18新增:
19新增:func LoadEnvironmentRecord(profile string) (EnvironmentRecord, error) {
20新增: var saved EnvironmentRecord
21新增: data, err := os.ReadFile(filepath.Join(profile, "environment.json"))
22新增: if errors.Is(err, os.ErrNotExist) {
23新增: return saved, nil
24新增: }
25新增: if err != nil {
26新增: return saved, err
27新增: }
28新增: if json.Unmarshal(data, &saved) != nil || !filepath.IsAbs(saved.Directory) ||
29新增: saved.IdentityDirectory != "" && !filepath.IsAbs(saved.IdentityDirectory) {
30新增: return saved, errors.New("环境工作目录记录无效,请保留原配置并导出诊断记录")
1731 }
18删除: if b, err := os.ReadFile(filepath.Join(profile, "environment.json")); err == nil && json.Unmarshal(b, &saved) == nil && filepath.IsAbs(saved.Directory) {
32新增: return saved, nil
33新增:}
34新增:
35新增:// DefaultEnvironmentDir keeps generated workspaces outside the default profile,
36新增:// including independent profiles stored below that profile's directory.
37新增:func DefaultEnvironmentDir(profile string) string {
38新增: path := filepath.Clean(profile) + "-workspace"
39新增: if home, err := os.UserHomeDir(); err == nil {
40新增: defaultProfile := filepath.Join(home, ".claude-cage")
41新增: if !paths.Equal(profile, defaultProfile) && StorageContains(defaultProfile, profile) {
42新增: if relative, err := filepath.Rel(defaultProfile, profile); err == nil {
43新增: path = filepath.Join(defaultProfile+"-workspaces", relative)
44新增: }
45新增: }
46新增: }
47新增: if real, err := filepath.EvalSymlinks(path); err == nil {
48新增: return real
49新增: }
50新增: return path
51新增:}
52新增:
53新增:// EnvironmentDir is the default shared workspace, independent of the currently
54新增:// selected project. IdentityDirectory retains a legacy VM's naming input.
55新增:func EnvironmentDir(profile string) string {
56新增: if saved, err := LoadEnvironmentRecord(profile); err == nil && saved.Directory != "" {
1957 return saved.Directory
2058 }
2159 // CLI and desktop upgrades must retain the same existing virtual disk.
@@ -27,16 +65,27 @@ func EnvironmentDir(profile string) string {
2765 return legacy.Workspace
2866 }
2967 }
30删除: path := filepath.Clean(profile) + "-workspace"
31删除: if real, err := filepath.EvalSymlinks(path); err == nil {
32删除: return real
68新增: previous := filepath.Clean(profile) + "-workspace"
69新增: if _, err := os.Stat(filepath.Join(profile, "state", "lima", InstanceName(profile, previous), "lima.yaml")); err == nil {
70新增: return previous
3371 }
34删除: return path
72新增: return DefaultEnvironmentDir(profile)
73新增:}
74新增:
75新增:func EnvironmentIdentityDir(profile string) string {
76新增: if saved, err := LoadEnvironmentRecord(profile); err == nil && saved.IdentityDirectory != "" {
77新增: return saved.IdentityDirectory
78新增: }
79新增: return EnvironmentDir(profile)
3580}
3681
3782// InstanceName is shared by the controller and each Cage CLI subprocess.
3883// It uses the same spelling as the CLI's AbsDir, including Windows drives.
3984func InstanceName(profile, workspace string) string {
85新增: if saved, err := LoadEnvironmentRecord(profile); err == nil && saved.IdentityDirectory != "" &&
86新增: paths.Equal(paths.Host(filepath.Clean(workspace)), paths.Host(filepath.Clean(saved.Directory))) {
87新增: workspace = saved.IdentityDirectory
88新增: }
4089 home := filepath.Join(profile, "state", "lima")
4190 _, err := os.Stat(filepath.Join(profile, locationFile))
4291 logical := err == nil
修改internal/cage/guest-open.sh+5 −1看文件
@@ -18,7 +18,11 @@ case "${1:-}" in
1818 set -- /new "$1"
1919 fi
2020 ;;
21删除: *) echo 'Only HTTP(S) browser URLs and Claude desktop callbacks are accepted.' >&2; exit 2;;
21新增: *)
22新增: # File operations belong to the desktop session, never the browser control
23新增: # token. The host resolves them only within Cage project directories.
24新增: exec /usr/local/bin/cage-desktop-files --open "${1:-}"
25新增: ;;
2226esac
2327# sudo records its arguments in the system journal. Send the URL on stdin.
2428browser_request() {
修改internal/cage/shared-clipboard.py+55 −6看文件
@@ -36,6 +36,31 @@ class CacheRegistry:
3636 if not stat.S_ISDIR(info.st_mode) or info.st_uid != os.geteuid() or info.st_mode & 0o077:
3737 raise ValueError('Clipboard ownership directory is not private')
3838
39新增: def session_path(self, session):
40新增: if not isinstance(session, str) or not 1 <= len(session) <= 256 or any(c not in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-' for c in session):
41新增: raise ValueError('Invalid clipboard session')
42新增: return self.directory / ('session-' + session)
43新增:
44新增: def begin_session(self, session):
45新增: self.ensure_directory()
46新增: path = self.session_path(session)
47新增: with path.open('x') as output:
48新增: os.chmod(path, 0o600)
49新增: json.dump({'owner': os.getpid()}, output)
50新增:
51新增: def require_session(self, session):
52新增: try:
53新增: value = json.loads(self.session_path(session).read_text())
54新增: owner = value['owner']
55新增: if not isinstance(owner, int) or owner < 1:
56新增: raise ValueError('Invalid clipboard session owner')
57新增: os.kill(owner, 0)
58新增: except (OSError, ValueError, KeyError, TypeError) as error:
59新增: raise ValueError('Clipboard session changed') from error
60新增:
61新增: def end_session(self, session):
62新增: self.session_path(session).unlink(missing_ok=True)
63新增:
3964 def records(self):
4065 if not self.directory.exists():
4166 return []
@@ -55,7 +80,9 @@ class CacheRegistry:
5580 or not isinstance(paths, list) or not 1 <= len(paths) <= 100
5681 or any(not isinstance(item, str) or Path(item).parent != Path(directory) or os.path.normpath(item) != item for item in paths)
5782 or not isinstance(marker, str) or marker in ('', '.', '..') or Path(marker).name != marker
58删除: or not isinstance(record.get('session'), str) or not isinstance(record.get('retired'), bool)):
83新增: or not isinstance(record.get('session'), str) or not isinstance(record.get('retired'), bool)
84新增: or not isinstance(record.get('pending', False), bool)
85新增: or record.get('pending') and (not isinstance(record.get('producer'), int) or record['producer'] < 1)):
5986 raise ValueError('Invalid clipboard ownership record')
6087 records.append(record)
6188 return records
@@ -70,7 +97,7 @@ class CacheRegistry:
7097 finally:
7198 Path(temporary).unlink(missing_ok=True)
7299
73删除: def register(self, paths, session):
100新增: def register(self, paths, session, pending=False):
74101 root = Path(paths[0]).parent
75102 identity = uuid.uuid4().hex
76103 fd, marker = tempfile.mkstemp(dir=root, prefix='.cage-clipboard-owner-')
@@ -80,8 +107,10 @@ class CacheRegistry:
80107 lock = self.directory / (identity + '.lock')
81108 lock.touch(mode=0o600, exist_ok=False)
82109 try:
83删除: self.save({'id': identity, 'directory': str(root), 'marker': Path(marker).name,
84删除: 'paths': paths, 'session': session, 'retired': False})
110新增: record = {'id': identity, 'directory': str(root), 'marker': Path(marker).name,
111新增: 'paths': paths, 'session': session, 'retired': False, 'pending': pending, 'producer': os.getpid()}
112新增: self.save(record)
113新增: return record
85114 except BaseException:
86115 lock.unlink(missing_ok=True)
87116 raise
@@ -118,7 +147,13 @@ class CacheRegistry:
118147 def collect(self, selected, session):
119148 for record in self.records():
120149 root = Path(record['directory'])
121删除: if root.exists() and not record['retired'] and (not record['session'] or record['session'] == session):
150新增: if root.exists() and record.get('pending') and not record['retired']:
151新增: try:
152新增: os.kill(record['producer'], 0)
153新增: continue
154新增: except ProcessLookupError:
155新增: pass
156新增: if root.exists() and not record.get('pending') and not record['retired'] and (not record['session'] or record['session'] == session):
122157 continue
123158 if any(Path(path).is_relative_to(root) or root.is_relative_to(Path(path)) for path in selected):
124159 continue
@@ -182,13 +217,25 @@ def export_files(paths, output):
182217
183218
184219def import_files(source, session=''):
220新增: registry = CacheRegistry()
221新增: if session:
222新增: registry.require_session(session)
185223 root = Path(tempfile.mkdtemp(prefix='cage-clipboard-'))
224新增: record = None
186225 try:
226新增: record = registry.register([str(root / '.pending')], session, pending=True)
187227 paths = extract_files(source, root)
188删除: CacheRegistry().register(paths, session)
228新增: record['paths'] = paths
229新增: record['pending'] = False
230新增: registry.save(record)
231新增: if session:
232新增: registry.require_session(session)
189233 return paths
190234 except BaseException:
191235 shutil.rmtree(root)
236新增: if record:
237新增: (registry.directory / (record['id'] + '.json')).unlink(missing_ok=True)
238新增: (registry.directory / (record['id'] + '.lock')).unlink(missing_ok=True)
192239 raise
193240
194241
@@ -466,6 +513,7 @@ def bridge():
466513 session = str(uuid.uuid4())
467514 announced = None
468515 registry = CacheRegistry()
516新增: registry.begin_session(session)
469517 current_files = {}
470518 next_cache_check = 0
471519 cleanup_needed = True
@@ -598,6 +646,7 @@ def bridge():
598646 next_cache_check = time.monotonic() + 1
599647 finally:
600648 try:
649新增: registry.end_session(session)
601650 for record in registry.records():
602651 if record['session'] == session:
603652 registry.retire(record['paths'])
修改internal/cage/shared-clipboard.test.py+38 −3看文件
@@ -97,8 +97,9 @@ class CacheOwnershipTests(unittest.TestCase):
9797 clipboard.export_files(self.paths, source)
9898 source.seek(0)
9999 with patch.object(clipboard.tempfile, 'tempdir', str(self.root)):
100删除: paths = clipboard.import_files(source, 'import-session')
101100 registry = clipboard.CacheRegistry()
101新增: registry.begin_session('import-session')
102新增: paths = clipboard.import_files(source, 'import-session')
102103 self.assertEqual(registry.records()[0]['paths'], paths)
103104 registry.retire(paths)
104105 registry.collect([], 'import-session')
@@ -112,12 +113,46 @@ class CacheOwnershipTests(unittest.TestCase):
112113 entry.size = 1
113114 archive.addfile(entry, io.BytesIO(b'x'))
114115 source.seek(0)
115删除: before = set(self.root.iterdir())
116116 with patch.object(clipboard.tempfile, 'tempdir', str(self.root)):
117新增: clipboard.CacheRegistry().ensure_directory()
118新增: before = set(self.root.iterdir())
117119 with self.assertRaises(ValueError):
118删除: clipboard.import_files(source, 'import-session')
120新增: clipboard.import_files(source)
119121 self.assertEqual(set(self.root.iterdir()), before)
120122
123新增: def test_an_import_finishing_after_disconnect_releases_its_created_directory(self):
124新增: source = io.BytesIO()
125新增: clipboard.export_files(self.paths, source)
126新增: source.seek(0)
127新增: with patch.object(clipboard.tempfile, 'tempdir', str(self.root)):
128新增: registry = clipboard.CacheRegistry()
129新增: registry.begin_session('import-session')
130新增: original = clipboard.extract_files
131新增: created = []
132新增: def disconnected(stream, root):
133新增: created.append(root)
134新增: paths = original(stream, root)
135新增: registry.end_session('import-session')
136新增: return paths
137新增: with patch.object(clipboard, 'extract_files', side_effect=disconnected):
138新增: with self.assertRaises(ValueError):
139新增: clipboard.import_files(source, 'import-session')
140新增: self.assertFalse(created[0].exists())
141新增: registry.collect([], 'next-session')
142新增: self.assertEqual(registry.records(), [])
143新增: self.assertEqual(self.file.read_bytes(), b'complete copied bytes')
144新增:
145新增: def test_an_incomplete_copy_keeps_a_live_producer_and_reclaims_a_terminated_one(self):
146新增: record = self.registry.records()[0]
147新增: record['pending'] = True
148新增: self.registry.save(record)
149新增: self.registry.collect([], 'next-session')
150新增: self.assertTrue(self.cache.exists())
151新增: record['producer'] = 2147483647
152新增: self.registry.save(record)
153新增: self.registry.collect([], 'next-session')
154新增: self.assertFalse(self.cache.exists())
155新增:
121156
122157if __name__ == '__main__':
123158 unittest.main()
修改internal/cage/storage_runtime.go+7 −2看文件
@@ -56,11 +56,16 @@ func RecoverStorage(ctx context.Context, profile string, runtime StorageRuntime)
5656
5757// CopyStorage copies an additional runtime-owned directory into a fresh private
5858// directory. It uses the same sparse-file and digest verification as the move.
59删除:func CopyStorage(ctx context.Context, source, target string, report func(int64, int64)) error {
59新增:func CopyStorage(ctx context.Context, source, target string, excluded []string, report func(int64, int64)) error {
60新增: for _, path := range excluded {
61新增: if !filepath.IsAbs(path) || sameStoragePath(path, source) || !StorageContains(source, path) {
62新增: return errors.New("客机管理文件超出当前存储目录")
63新增: }
64新增: }
6065 if err := os.Mkdir(target, 0700); err != nil {
6166 return err
6267 }
63删除: return copyStorage(ctx, source, target, report)
68新增: return copyStorageExcluding(ctx, source, target, excluded, report)
6469}
6570
6671func CopyStorageFile(ctx context.Context, source, target string) error {
修改internal/cage/storage_windows.go+6 −0看文件
@@ -97,6 +97,12 @@ func linkStorage(link, target string) (err error) {
9797}
9898
9999func sparseStorageFile(f *os.File) error {
100新增: // Hyper-V virtual disks manage their own allocation. Adding an NTFS sparse
101新增: // attribute changes which Virtual Disk API open flags can mount the copy.
102新增: switch strings.ToLower(filepath.Ext(f.Name())) {
103新增: case ".vhd", ".vhdx", ".avhd", ".avhdx":
104新增: return nil
105新增: }
100106 var n uint32
101107 return windows.DeviceIoControl(windows.Handle(f.Fd()), windows.FSCTL_SET_SPARSE, nil, 0, nil, 0, &n, nil)
102108}
修改internal/cli/licenses_test.go+2 −1看文件
@@ -4,6 +4,7 @@ import (
44 "strings"
55 "testing"
66
7新增: agentvm "github.com/sylvinus/agent-vm"
78 "github.com/sylvinus/agent-vm/internal/vm/vmtest"
89)
910
@@ -17,7 +18,7 @@ func TestLicenses(t *testing.T) {
1718 // binary: Apache-2.0 (with Lima's NOTICE), BSD-2 and BSD-3 ones.
1819 for _, want := range []string{
1920 "MIT License", "Copyright (c) 2026 Sylvain Zimmer",
20删除: "third_party/ holds", "section 4(b)",
21新增: agentvm.Notice,
2122 "github.com/lima-vm/lima/v2 ./third_party/lima: LICENSE",
2223 "github.com/lima-vm/lima/v2 ./third_party/lima: NOTICE",
2324 "github.com/lima-vm/sshocker ./third_party/sshocker: LICENSE",
修改internal/clipboardfiles/ownership.go+3 −6看文件
@@ -262,7 +262,8 @@ func (store CacheStore) List() ([]CachedSelection, error) {
262262 if err != nil {
263263 return nil, err
264264 }
265删除: if record.Pending && !cacheOwnerAlive(record.Producer) || !record.Pending && (record.Published || !cacheOwnerAlive(record.Owner)) {
265新增: if record.Pending && !cacheOwnerAlive(record.Producer) || !record.Pending &&
266新增: (record.Published && record.Owner == os.Getppid() || !cacheOwnerAlive(record.Owner)) {
266267 selections = append(selections, record.CachedSelection)
267268 }
268269 }
@@ -313,13 +314,9 @@ func (store CacheStore) Release(id string) error {
313314 }
314315 }
315316 }
316删除: if err := root.Remove(record.Marker); err != nil {
317新增: if err := removeCacheDirectory(root, record); err != nil {
317318 return err
318319 }
319删除: if err := os.Remove(record.Directory); err != nil {
320删除: // A busy directory must retain its proof of ownership for a later retry.
321删除: return errors.Join(err, root.WriteFile(record.Marker, []byte(id), 0600))
322删除: }
323320 return os.Remove(path)
324321}
325322
修改internal/clipboardfiles/ownership_test.go+20 −0看文件
@@ -105,6 +105,26 @@ func TestCacheRejectsForeignOrMalformedIdentifiers(t *testing.T) {
105105 }
106106}
107107
108新增:func TestCacheRecoveryLeavesAnotherLiveNativeOwnerInControl(t *testing.T) {
109新增: store, selection := cacheFixture(t)
110新增: record, err := store.load(selection.ID)
111新增: if err != nil {
112新增: t.Fatal(err)
113新增: }
114新增: record.Published = true
115新增: record.Owner = os.Getpid()
116新增: if err := store.save(record); err != nil {
117新增: t.Fatal(err)
118新增: }
119新增: listed, err := store.List()
120新增: if err != nil || len(listed) != 0 {
121新增: t.Fatal("another live native owner's clipboard entered recovery", err)
122新增: }
123新增: if _, err := os.Stat(selection.Paths[0]); err != nil {
124新增: t.Fatal(err)
125新增: }
126新增:}
127新增:
108128func TestCacheConcurrentPublishCannotRecreateAReleasedReceipt(t *testing.T) {
109129 for range 20 {
110130 store, selection := cacheFixture(t)
修改internal/clipboardfiles/ownership_unix.go+11 −0看文件
@@ -3,10 +3,21 @@
33package clipboardfiles
44
55import (
6新增: "errors"
67 "os"
78 "syscall"
89)
910
11新增:func removeCacheDirectory(root *os.Root, record cacheRecord) error {
12新增: if err := root.Remove(record.Marker); err != nil {
13新增: return err
14新增: }
15新增: if err := os.Remove(record.Directory); err != nil {
16新增: return errors.Join(err, root.WriteFile(record.Marker, []byte(record.ID), 0600))
17新增: }
18新增: return nil
19新增:}
20新增:
1021func lockCacheStore(file *os.File) (func(), error) {
1122 if err := syscall.Flock(int(file.Fd()), syscall.LOCK_EX); err != nil {
1223 return nil, err
修改internal/clipboardfiles/ownership_windows.go+43 −0看文件
@@ -1,11 +1,54 @@
11package clipboardfiles
22
33import (
4新增: "errors"
45 "os"
6新增: "path/filepath"
57
68 "golang.org/x/sys/windows"
79)
810
11新增:func removeCacheDirectory(root *os.Root, record cacheRecord) error {
12新增: identity, err := root.Stat(".")
13新增: if err != nil {
14新增: return err
15新增: }
16新增: // os.Root denies delete sharing on Windows. Replace it with a handle that
17新增: // can remove this exact directory, and check its identity before deleting.
18新增: if err := root.Close(); err != nil {
19新增: return err
20新增: }
21新增: path, err := windows.UTF16PtrFromString(record.Directory)
22新增: if err != nil {
23新增: return err
24新增: }
25新增: handle, err := windows.CreateFile(path, windows.DELETE|windows.FILE_READ_ATTRIBUTES,
26新增: windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE, nil, windows.OPEN_EXISTING,
27新增: windows.FILE_FLAG_BACKUP_SEMANTICS|windows.FILE_FLAG_OPEN_REPARSE_POINT, 0)
28新增: if err != nil {
29新增: return err
30新增: }
31新增: file := os.NewFile(uintptr(handle), record.Directory)
32新增: defer file.Close()
33新增: current, err := file.Stat()
34新增: if err != nil || !current.IsDir() || current.Mode()&os.ModeSymlink != 0 || !os.SameFile(identity, current) {
35新增: return errors.New("clipboard cache directory identity changed")
36新增: }
37新增: marker := filepath.Join(record.Directory, record.Marker)
38新增: contents, err := os.ReadFile(marker)
39新增: if err != nil || string(contents) != record.ID {
40新增: return errors.New("clipboard cache creation record no longer matches")
41新增: }
42新增: if err := os.Remove(marker); err != nil {
43新增: return err
44新增: }
45新增: discard := byte(1)
46新增: if err := windows.SetFileInformationByHandle(handle, windows.FileDispositionInfo, &discard, 1); err != nil {
47新增: return errors.Join(err, os.WriteFile(marker, []byte(record.ID), 0600))
48新增: }
49新增: return nil
50新增:}
51新增:
952func lockCacheStore(file *os.File) (func(), error) {
1053 var overlapped windows.Overlapped
1154 if err := windows.LockFileEx(windows.Handle(file.Fd()), windows.LOCKFILE_EXCLUSIVE_LOCK, 0, 1, 0, &overlapped); err != nil {
修改internal/guestos/macos_login.go+26 −15看文件
@@ -4,21 +4,32 @@ package guestos
44// host file paths, clipboard contents, or global shortcuts are accepted. Only
55// the authenticated host may attach a stored password to fill-password.
66type MacLoginRequest struct {
7删除: Action string `json:"action"`
8删除: Session string `json:"session,omitempty"`
9删除: Setup bool `json:"initial_setup,omitempty"`
10删除: Code int `json:"code"`
11删除: Shift bool `json:"shift"`
12删除: X int `json:"x"`
13删除: Y int `json:"y"`
14删除: DeltaX int `json:"delta_x,omitempty"`
15删除: DeltaY int `json:"delta_y,omitempty"`
16删除: Password string `json:"password,omitempty"`
7新增: Action string `json:"action"`
8新增: Session string `json:"session,omitempty"`
9新增: Setup bool `json:"initial_setup,omitempty"`
10新增: Maintenance string `json:"maintenance,omitempty"`
11新增: Geometry string `json:"geometry,omitempty"`
12新增: Code int `json:"code"`
13新增: Shift bool `json:"shift"`
14新增: X int `json:"x"`
15新增: Y int `json:"y"`
16新增: DeltaX int `json:"delta_x,omitempty"`
17新增: DeltaY int `json:"delta_y,omitempty"`
18新增: Password string `json:"password,omitempty"`
1719}
1820type MacLoginReply struct {
19删除: MIME string `json:"mime,omitempty"`
20删除: Session string `json:"session,omitempty"`
21删除: Image []byte `json:"image,omitempty"`
22删除: Error string `json:"error,omitempty"`
23删除: Closed bool `json:"closed,omitempty"`
21新增: MIME string `json:"mime,omitempty"`
22新增: Session string `json:"session,omitempty"`
23新增: Image []byte `json:"image,omitempty"`
24新增: Error string `json:"error,omitempty"`
25新增: Closed bool `json:"closed,omitempty"`
26新增: Geometry string `json:"geometry,omitempty"`
27新增: Region []int `json:"region,omitempty"`
28新增: Recovery string `json:"recovery,omitempty"`
29新增: Administrator string `json:"administrator,omitempty"`
30新增: MaintenanceVersion int `json:"maintenance_version,omitempty"`
31新增:}
32新增:
33新增:func ValidMacMaintenancePurpose(value string) bool {
34新增: return value == "projects" || value == "screen" || value == "input"
2435}
修改internal/guestos/maintenance_windows.go+33 −0看文件
@@ -5,8 +5,10 @@ package guestos
55import (
66 "context"
77 "crypto/sha256"
8新增: "encoding/json"
89 "errors"
910 "fmt"
11新增: "io"
1012 "os"
1113 "os/exec"
1214 "path/filepath"
@@ -37,3 +39,34 @@ func WindowsMaintenanceCommand(ctx context.Context, profile, kit, manifest strin
3739 }
3840 return exec.CommandContext(ctx, filepath.Join(system, "WindowsPowerShell", "v1.0", "powershell.exe"), args...), nil
3941}
42新增:
43新增:// RepairWindowsHostManager uses the existing UAC maintenance entry point. It
44新增:// updates the fixed host service without requiring a running GUI guest.
45新增:func RepairWindowsHostManager(ctx context.Context, profile, kit string, stdout, stderr io.Writer) error {
46新增: manifest, err := RequiredNativeComponents(kit, Windows11)
47新增: if err != nil {
48新增: return err
49新增: }
50新增: file, err := os.CreateTemp(profile, "native-host-repair-*.json")
51新增: if err != nil {
52新增: return err
53新增: }
54新增: defer os.Remove(file.Name())
55新增: err = json.NewEncoder(file).Encode(manifest)
56新增: if err = errors.Join(err, file.Close()); err != nil {
57新增: return err
58新增: }
59新增: command, err := WindowsMaintenanceCommand(ctx, profile, kit, file.Name(), false)
60新增: if err != nil {
61新增: return err
62新增: }
63新增: command.Args = append(command.Args, "-HostOnly")
64新增: command.Stdout, command.Stderr = stdout, stderr
65新增: if err := command.Run(); err != nil {
66新增: if ctx.Err() != nil {
67新增: return ctx.Err()
68新增: }
69新增: return err
70新增: }
71新增: return nil
72新增:}
新增internal/guestos/maintenance_windows_test.go+57 −0看文件
@@ -0,0 +1,57 @@
1新增://go:build windows
2新增:
3新增:package guestos
4新增:
5新增:import (
6新增: "context"
7新增: "errors"
8新增: "os"
9新增: "os/exec"
10新增: "path/filepath"
11新增: "strings"
12新增: "testing"
13新增: "time"
14新增:
15新增: "github.com/sylvinus/agent-vm/internal/diagnostics"
16新增:)
17新增:
18新增:func TestWindowsHostRepairPreservesProcessOutput(t *testing.T) {
19新增: profile := t.TempDir()
20新增: if err := BindWindowsProfile(profile, windowsBindingFixture(profile)); err != nil {
21新增: t.Fatal(err)
22新增: }
23新增: kit := nativeManifestKit(t, Windows11)
24新增: script := `param([string]$Profile,[string]$ManifestPath,[string]$ManifestSHA256,[switch]$HostOnly)
25新增:$ErrorActionPreference='Stop'
26新增:[Console]::OutputEncoding=[Text.UTF8Encoding]::new($false)
27新增:if (!$HostOnly -or (Get-FileHash -LiteralPath $ManifestPath -Algorithm SHA256).Hash -ne $ManifestSHA256) { exit 38 }
28新增:Write-Output 'repair-fixture-stdout'
29新增:[Console]::Error.WriteLine('repair-fixture-service-registration-failed token=repair-fixture-secret')
30新增:exit 37
31新增:`
32新增: if err := os.WriteFile(filepath.Join(kit, "maintain-windows-workbench.ps1"), []byte(script), 0600); err != nil {
33新增: t.Fatal(err)
34新增: }
35新增: var stdout, stderr strings.Builder
36新增: out := diagnostics.NewStream(nil, "storage-recovery", "info", func(line string) { stdout.WriteString(line) })
37新增: errOut := diagnostics.NewStream(nil, "storage-recovery", "warn", func(line string) { stderr.WriteString(line) })
38新增: ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
39新增: defer cancel()
40新增: err := RepairWindowsHostManager(ctx, profile, kit, out, errOut)
41新增: _ = out.Close()
42新增: _ = errOut.Close()
43新增: var exit *exec.ExitError
44新增: if !errors.As(err, &exit) || exit.ExitCode() != 37 {
45新增: t.Fatalf("repair lost the original process result: %v", err)
46新增: }
47新增: if !strings.Contains(stdout.String(), "repair-fixture-stdout") || !strings.Contains(stderr.String(), "repair-fixture-service-registration-failed") {
48新增: t.Fatalf("repair output did not reach the shared diagnostic streams: stdout=%q stderr=%q", stdout.String(), stderr.String())
49新增: }
50新增: if strings.Contains(stderr.String(), "repair-fixture-secret") || !strings.Contains(stderr.String(), "[redacted]") {
51新增: t.Fatal("repair output bypassed diagnostic redaction")
52新增: }
53新增: remaining, err := filepath.Glob(filepath.Join(profile, "native-host-repair-*.json"))
54新增: if err != nil || len(remaining) != 0 {
55新增: t.Fatalf("repair manifest was retained after failure: %v %v", remaining, err)
56新增: }
57新增:}
新增internal/guestos/testdata/windows_storage.ps1+70 −0看文件
@@ -0,0 +1,70 @@
1新增:param([Parameter(Mandatory)][string]$Implementation)
2新增:$ErrorActionPreference='Stop'
3新增:$global:cageStorageVMID=[guid]'2a6f8208-3906-4e16-8233-2b9d28ecf7be'
4新增:$old=[pscustomobject]@{configuration="C:\Cage original\config";snapshots="C:\Cage original\snapshots";paging="C:\Cage original\paging"}
5新增:$next=[pscustomobject]@{configuration="C:\ProgramData\Cage\测试's\config";snapshots="C:\ProgramData\Cage\测试's\snapshots";paging="C:\ProgramData\Cage\测试's\paging"}
6新增:$source="C:\Cage original\system.vhdx"
7新增:$destination="D:\Cage 新位置's\system.vhdx"
8新增:function Reset-VM {
9新增: $global:cageStorageVM=[pscustomobject]@{Id=$global:cageStorageVMID;State='Off';Generation=2;ConfigurationLocation=$old.configuration;SnapshotFileLocation=$old.snapshots;SmartPagingFilePath=$old.paging}
10新增: $global:cageStorageDisk=[pscustomobject]@{Path=$source}
11新增: $global:cageStorageMoves=0
12新增: $global:cageStorageAttachments=0
13新增: $global:cageStorageFailMove=$false
14新增:}
15新增:function Get-VM { param([guid]$Id) if($Id -ne $global:cageStorageVMID){throw 'wrong_vm'};return $global:cageStorageVM }
16新增:function Get-VMNetworkAdapter { param($VM) if($VM.Id -ne $global:cageStorageVMID){throw 'wrong_vm'} }
17新增:function Get-VMFirmware { param($VM) [pscustomobject]@{SecureBoot='On'} }
18新增:function Get-VMSecurity { param($VM) [pscustomobject]@{TpmEnabled=$true} }
19新增:function Get-VMHardDiskDrive { param($VM) if($VM.Id -ne $global:cageStorageVMID){throw 'wrong_vm'};return $global:cageStorageDisk }
20新增:function Move-VMStorage {
21新增: param($VM,[string]$VirtualMachinePath,[string]$SnapshotFilePath,[string]$SmartPagingFilePath,[switch]$Confirm)
22新增: if($VM.Id -ne $global:cageStorageVMID -or $VM.State -ne 'Off'){throw 'unsafe_move'}
23新增: $global:cageStorageMoves++
24新增: if($VirtualMachinePath){$global:cageStorageVM.ConfigurationLocation=$VirtualMachinePath}
25新增: if($global:cageStorageFailMove){throw 'injected_metadata_failure'}
26新增: if($SnapshotFilePath){$global:cageStorageVM.SnapshotFileLocation=$SnapshotFilePath}
27新增: if($SmartPagingFilePath){$global:cageStorageVM.SmartPagingFilePath=$SmartPagingFilePath}
28新增:}
29新增:function Set-VMHardDiskDrive {
30新增: param($VMHardDiskDrive,[string]$Path)
31新增: if($global:cageStorageVM.State -notin @('Off','OffCritical') -or $VMHardDiskDrive -ne $global:cageStorageDisk){throw 'unsafe_attachment'}
32新增: $global:cageStorageAttachments++
33新增: $global:cageStorageDisk.Path=$Path
34新增: $global:cageStorageVM.State='Off'
35新增:}
36新增:function Invoke-Storage($Target,[string]$Disk) {
37新增: $inputData=[pscustomobject]@{vm_id=$global:cageStorageVMID.ToString('D');action='apply';old=$old;next=$next;target=$Target;old_disk=$source;source_disk=$source;new_disk=$destination;disk=$Disk}
38新增: & $Implementation | Out-Null
39新增:}
40新增:Reset-VM
41新增:Invoke-Storage $next $source
42新增:if($global:cageStorageMoves -ne 1 -or $global:cageStorageAttachments -ne 0){throw 'registration_not_prepared_before_copy'}
43新增:Invoke-Storage $next $destination
44新增:if($global:cageStorageVM.ConfigurationLocation -cne $next.configuration -or $global:cageStorageVM.SnapshotFileLocation -cne $next.snapshots -or $global:cageStorageVM.SmartPagingFilePath -cne $next.paging -or $global:cageStorageDisk.Path -cne $destination){throw 'incomplete_migration'}
45新增:if($global:cageStorageMoves -ne 1 -or $global:cageStorageAttachments -ne 1){throw 'unexpected_mutation_count'}
46新增:Invoke-Storage $next $destination
47新增:if($global:cageStorageMoves -ne 1 -or $global:cageStorageAttachments -ne 1){throw 'retry_repeated_mutations'}
48新增:$global:cageStorageVM.State='OffCritical'
49新增:Invoke-Storage $next $source
50新增:if($global:cageStorageVM.ConfigurationLocation -cne $next.configuration -or $global:cageStorageVM.SnapshotFileLocation -cne $next.snapshots -or $global:cageStorageDisk.Path -cne $source){throw 'offline_target_rollback_failed'}
51新增:
52新增:Reset-VM
53新增:$global:cageStorageFailMove=$true
54新增:$failed=$false
55新增:try{Invoke-Storage $next $destination}catch{$failed=$true}
56新增:if(!$failed -or $global:cageStorageVM.ConfigurationLocation -cne $next.configuration -or $global:cageStorageAttachments -ne 0){throw 'partial_failure_fixture_invalid'}
57新增:$global:cageStorageFailMove=$false
58新增:Invoke-Storage $next $source
59新增:if($global:cageStorageVM.ConfigurationLocation -cne $next.configuration -or $global:cageStorageDisk.Path -cne $source){throw 'partial_metadata_rollback_failed'}
60新增:
61新增:foreach($failure in @('running','foreign_disk','foreign_configuration')){
62新增: Reset-VM
63新增: if($failure -eq 'running'){$global:cageStorageVM.State='Running'}
64新增: if($failure -eq 'foreign_disk'){$global:cageStorageDisk.Path='C:\Another VM\private.vhdx'}
65新增: if($failure -eq 'foreign_configuration'){$global:cageStorageVM.ConfigurationLocation='C:\Another VM\config'}
66新增: $failed=$false
67新增: try{Invoke-Storage $next $destination}catch{$failed=$true}
68新增: if(!$failed -or $global:cageStorageMoves -ne 0 -or $global:cageStorageAttachments -ne 0){throw ('unsafe_state_accepted_'+$failure)}
69新增:}
70新增:Write-Output 'PASS fixed system registration, disk move, idempotence, offline target rollback, partial metadata recovery, running and unrelated VM state rejection'
修改internal/guestos/windows_host_manager_client_windows.go+43 −0看文件
@@ -43,6 +43,13 @@ func windowsHostManagerRequestCall(ctx context.Context, request windowsHostManag
4343 }
4444 connection, err := winio.DialPipeAccessImpLevel(connect, `\\.\pipe\Cage.HyperV.`+id.String(), 0x120003, level)
4545 finish()
46新增: if err != nil && ctx.Err() == nil {
47新增: if startErr := startRegisteredWindowsHostManager(id); startErr == nil {
48新增: retry, finish := context.WithTimeout(ctx, 10*time.Second)
49新增: connection, err = winio.DialPipeAccessImpLevel(retry, `\\.\pipe\Cage.HyperV.`+id.String(), 0x120003, level)
50新增: finish()
51新增: }
52新增: }
4653 if err != nil {
4754 if ctx.Err() != nil {
4855 return ctx.Err()
@@ -126,6 +133,10 @@ func verifyWindowsHostManagerPeer(connection net.Conn, id uuid.UUID) error {
126133 if windows.QueryServiceStatusEx(service, windows.SC_STATUS_PROCESS_INFO, (*byte)(unsafe.Pointer(&status)), uint32(unsafe.Sizeof(status)), &needed) != nil || status.ProcessId != pid || status.CurrentState != windows.SERVICE_RUNNING {
127134 return errors.New("Windows 系统管理通道不属于当前已登记服务")
128135 }
136新增: return verifyWindowsHostManagerService(service, id)
137新增:}
138新增:
139新增:func verifyWindowsHostManagerService(service windows.Handle, id uuid.UUID) error {
129140 binaryPath, account, err := windowsHostServiceConfig(service)
130141 if err != nil {
131142 return errors.New("Windows 系统管理服务配置无法核验")
@@ -161,6 +172,38 @@ func verifyWindowsHostManagerPeer(connection net.Conn, id uuid.UUID) error {
161172 return nil
162173}
163174
175新增:// Installation already grants the bound user SERVICE_START. Restoring that
176新增:// fixed service after a reboot does not grant VM discovery or service editing.
177新增:func startRegisteredWindowsHostManager(id uuid.UUID) error {
178新增: binding, err := LoadWindowsHostManagerBinding(WindowsHostManagerBindingPath(id))
179新增: if err != nil {
180新增: return err
181新增: }
182新增: user, err := windows.GetCurrentProcessToken().GetTokenUser()
183新增: if err != nil || user.User.Sid.String() != binding.HostSID {
184新增: return errors.New("unauthorized")
185新增: }
186新增: manager, err := windows.OpenSCManager(nil, nil, windows.SC_MANAGER_CONNECT)
187新增: if err != nil {
188新增: return err
189新增: }
190新增: defer windows.CloseServiceHandle(manager)
191新增: name, _ := windows.UTF16PtrFromString(WindowsHostManagerServiceName(id))
192新增: service, err := windows.OpenService(manager, name, windows.SERVICE_QUERY_CONFIG|windows.SERVICE_START)
193新增: if err != nil {
194新增: return err
195新增: }
196新增: defer windows.CloseServiceHandle(service)
197新增: if err = verifyWindowsHostManagerService(service, id); err != nil {
198新增: return err
199新增: }
200新增: err = windows.StartService(service, 0, nil)
201新增: if errors.Is(err, windows.ERROR_SERVICE_ALREADY_RUNNING) {
202新增: return nil
203新增: }
204新增: return err
205新增:}
206新增:
164207func windowsHostServiceConfig(service windows.Handle) (string, string, error) {
165208 // QUERY_SERVICE_CONFIG contains pointers into this native output buffer.
166209 // A variable-sized allocation stays on the heap when later Go calls grow
修改internal/guestos/windows_host_manager_server_windows.go+1 −1看文件
@@ -300,7 +300,7 @@ func (server *windowsHostManagerServer) request(ctx context.Context, request win
300300 }
301301 // Hold the verified inode across the operation. A same-user caller cannot
302302 // replace the VHDX path after validation while the SYSTEM operation runs.
303删除: lockedDisk, err := windows.CreateFile(name, windows.FILE_READ_ATTRIBUTES, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE, nil, windows.OPEN_EXISTING, windows.FILE_FLAG_OPEN_REPARSE_POINT, 0)
303新增: lockedDisk, err := windows.CreateFile(name, windows.GENERIC_READ, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE, nil, windows.OPEN_EXISTING, windows.FILE_FLAG_OPEN_REPARSE_POINT, 0)
304304 if err != nil {
305305 return nil, errors.New("vm_changed")
306306 }
修改internal/guestos/windows_host_manager_wire.go+3 −4看文件
@@ -38,7 +38,6 @@ type windowsHostStorageRequest struct {
3838 SourceVolume uint32 `json:"source_volume,omitempty"`
3939 SourceFileID uint64 `json:"source_file_id,omitempty"`
4040 Disk string `json:"disk,omitempty"`
41删除: Directory string `json:"directory,omitempty"`
4241}
4342
4443type windowsHostStorageState struct {
@@ -54,7 +53,7 @@ func validWindowsStorageID(id string) bool {
5453
5554func (r windowsHostStorageRequest) validate() error {
5655 if r.Action == "status" {
57删除: if r.ID == "" && r.SourceVolume == 0 && r.SourceFileID == 0 && r.Disk == "" && r.Directory == "" {
56新增: if r.ID == "" && r.SourceVolume == 0 && r.SourceFileID == 0 && r.Disk == "" {
5857 return nil
5958 }
6059 return errors.New("invalid_request")
@@ -64,11 +63,11 @@ func (r windowsHostStorageRequest) validate() error {
6463 }
6564 switch r.Action {
6665 case "begin", "commit", "rollback":
67删除: if r.Disk != "" || r.Directory != "" {
66新增: if r.Disk != "" {
6867 return errors.New("invalid_request")
6968 }
7069 case "attach":
71删除: if r.Disk == "" || r.Directory == "" || len(r.Disk) > 32700 || len(r.Directory) > 32700 || strings.ContainsAny(r.Disk+r.Directory, "\x00\r\n") {
70新增: if r.Disk == "" || len(r.Disk) > 32700 || strings.ContainsAny(r.Disk, "\x00\r\n") {
7271 return errors.New("invalid_request")
7372 }
7473 default:
修改internal/guestos/windows_host_storage_windows.go+65 −80看文件
@@ -20,28 +20,32 @@ import (
2020 "golang.org/x/sys/windows"
2121
2222 "github.com/sylvinus/agent-vm/internal/cage"
23删除: "github.com/sylvinus/agent-vm/internal/paths"
2423)
2524
2625//go:embed windows_storage.ps1
2726var windowsStorageScript string
2827
2928type windowsHostStorageJournal struct {
30删除: ID string `json:"id"`
31删除: Phase string `json:"phase"`
32删除: Before WindowsHostManagerBinding `json:"before"`
33删除: OldDisk string `json:"old_disk"`
34删除: OldLayout windowsVMStorageLayout `json:"old_layout"`
35删除: After *WindowsHostManagerBinding `json:"after,omitempty"`
36删除: NewLayout *windowsVMStorageLayout `json:"new_layout,omitempty"`
37删除: Directory windowsStorageDisk `json:"directory"`
38删除: Backup string `json:"backup"`
29新增: ID string `json:"id"`
30新增: Phase string `json:"phase"`
31新增: Before WindowsHostManagerBinding `json:"before"`
32新增: OldDisk string `json:"old_disk"`
33新增: OldLayout windowsVMStorageLayout `json:"old_layout"`
34新增: After *WindowsHostManagerBinding `json:"after,omitempty"`
35新增: NewLayout *windowsVMStorageLayout `json:"new_layout,omitempty"`
36新增: Backup string `json:"backup"`
37新增: RegistrationStarted bool `json:"registration_started,omitempty"`
3938}
4039
4140func (server *windowsHostManagerServer) storageJournalPath() string {
4241 return filepath.Join(filepath.Dir(WindowsHostManagerBindingPath(server.binding.VMID)), "storage.json")
4342}
4443
44新增:func (server *windowsHostManagerServer) storageRegistrationLayout() windowsVMStorageLayout {
45新增: root := filepath.Join(filepath.Dir(server.storageJournalPath()), "machine")
46新增: return windowsVMStorageLayout{Configuration: filepath.Join(root, "configuration"), Snapshots: filepath.Join(root, "snapshots"), Paging: filepath.Join(root, "paging")}
47新增:}
48新增:
4549func (server *windowsHostManagerServer) loadStorageJournal() (*windowsHostStorageJournal, error) {
4650 path := server.storageJournalPath()
4751 file, err := os.Open(path)
@@ -61,7 +65,12 @@ func (server *windowsHostManagerServer) loadStorageJournal() (*windowsHostStorag
6165 if decoder.Decode(&journal) != nil || decoder.Decode(new(any)) != io.EOF || !validWindowsStorageID(journal.ID) ||
6266 journal.Before.VMID != server.binding.VMID || journal.Before.HostSID != server.binding.HostSID ||
6367 journal.Phase != "pending" && journal.Phase != "commit" && journal.Phase != "rollback" ||
64删除: (journal.After == nil) != (journal.NewLayout == nil) {
68新增: journal.NewLayout == nil || *journal.NewLayout != server.storageRegistrationLayout() || journal.Backup != filepath.Join(filepath.Dir(path), "storage-backup-"+journal.ID) ||
69新增: journal.Before.DiskVolume == 0 || journal.Before.DiskFileID == 0 {
70新增: return nil, errors.New("binding_invalid")
71新增: }
72新增: if journal.After != nil && (journal.After.VMID != server.binding.VMID || journal.After.HostSID != server.binding.HostSID ||
73新增: journal.After.DiskVolume == 0 || journal.After.DiskFileID == 0) {
6574 return nil, errors.New("binding_invalid")
6675 }
6776 return &journal, nil
@@ -212,7 +221,8 @@ func (server *windowsHostManagerServer) storageRequest(ctx context.Context, inpu
212221 return nil, err
213222 }
214223 backup := filepath.Join(filepath.Dir(server.storageJournalPath()), "storage-backup-"+input.ID)
215删除: journal = &windowsHostStorageJournal{ID: input.ID, Phase: "pending", Before: server.binding, OldDisk: oldDisk, OldLayout: layout, Backup: backup}
224新增: registration := server.storageRegistrationLayout()
225新增: journal = &windowsHostStorageJournal{ID: input.ID, Phase: "pending", Before: server.binding, OldDisk: oldDisk, OldLayout: layout, NewLayout: &registration, Backup: backup}
216226 if err = managerWriteStorageJSON(server.storageJournalPath(), server.binding.HostSID, journal); err != nil {
217227 return nil, err
218228 }
@@ -225,6 +235,9 @@ func (server *windowsHostManagerServer) storageRequest(ctx context.Context, inpu
225235 if err := server.ensureStorageBackup(ctx, journal); err != nil {
226236 return nil, err
227237 }
238新增: if err := server.prepareStorageRegistration(ctx, journal); err != nil {
239新增: return nil, err
240新增: }
228241 case "attach":
229242 if err := server.attachStorage(ctx, journal, input, conn); err != nil {
230243 return nil, err
@@ -237,6 +250,30 @@ func (server *windowsHostManagerServer) storageRequest(ctx context.Context, inpu
237250 return server.storageState(journal, input.Action), nil
238251}
239252
253新增:// Registration belongs to the fixed system helper. Keeping it on the system
254新增:// volume lets rollback reattach the original VHDX even when the target volume
255新增:// disappears. VM identity and the exported recovery metadata remain available.
256新增:func (server *windowsHostManagerServer) prepareStorageRegistration(ctx context.Context, journal *windowsHostStorageJournal) error {
257新增: root := filepath.Dir(journal.NewLayout.Configuration)
258新增: if err := os.Mkdir(root, 0700); err == nil {
259新增: if err := managerProtectStoragePath(root, server.binding.HostSID); err != nil {
260新增: return err
261新增: }
262新增: } else if !errors.Is(err, os.ErrExist) {
263新增: return err
264新增: }
265新增: if err := managerProtected(root, server.binding.HostSID); err != nil {
266新增: return err
267新增: }
268新增: if !journal.RegistrationStarted {
269新增: journal.RegistrationStarted = true
270新增: if err := managerWriteStorageJSON(server.storageJournalPath(), server.binding.HostSID, journal); err != nil {
271新增: return err
272新增: }
273新增: }
274新增: return server.applyStorage(ctx, journal, journal.Before, *journal.NewLayout)
275新增:}
276新增:
240277func (server *windowsHostManagerServer) ensureStorageBackup(ctx context.Context, journal *windowsHostStorageJournal) error {
241278 complete := filepath.Join(journal.Backup, "cage-export-complete.json")
242279 if data, err := os.ReadFile(complete); err == nil && bytes.Equal(data, []byte(`{"id":"`+journal.ID+`"}`)) {
@@ -336,6 +373,7 @@ func managerPinStorageParents(path string) (func(), error) {
336373 for _, handle := range handles {
337374 windows.CloseHandle(handle)
338375 }
376新增: handles = nil
339377 }
340378 var parents []string
341379 for parent := filepath.Dir(path); ; parent = filepath.Dir(parent) {
@@ -351,7 +389,7 @@ func managerPinStorageParents(path string) (func(), error) {
351389 closeAll()
352390 return nil, err
353391 }
354删除: handle, err := windows.CreateFile(name, windows.FILE_READ_ATTRIBUTES, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE, nil, windows.OPEN_EXISTING, windows.FILE_FLAG_OPEN_REPARSE_POINT|windows.FILE_FLAG_BACKUP_SEMANTICS, 0)
392新增: handle, err := windows.CreateFile(name, windows.GENERIC_READ, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE, nil, windows.OPEN_EXISTING, windows.FILE_FLAG_OPEN_REPARSE_POINT|windows.FILE_FLAG_BACKUP_SEMANTICS, 0)
355393 if err != nil {
356394 closeAll()
357395 return nil, err
@@ -366,26 +404,6 @@ func managerPinStorageParents(path string) (func(), error) {
366404 return closeAll, nil
367405}
368406
369删除:func managerProtectVMMetadata(handle windows.Handle, sid string, release bool) error {
370删除: owner, access := "SY", "FRFX"
371删除: if release {
372删除: owner, access = sid, "FA"
373删除: }
374删除: sd, err := windows.SecurityDescriptorFromString("O:" + owner + "G:SYD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;" + access + ";;;" + sid + ")")
375删除: if err != nil {
376删除: return err
377删除: }
378删除: ownerSID, _, err := sd.Owner()
379删除: if err != nil {
380删除: return err
381删除: }
382删除: acl, _, err := sd.DACL()
383删除: if err != nil {
384删除: return err
385删除: }
386删除: return windows.SetSecurityInfo(handle, windows.SE_FILE_OBJECT, windows.OWNER_SECURITY_INFORMATION|windows.DACL_SECURITY_INFORMATION|windows.PROTECTED_DACL_SECURITY_INFORMATION, ownerSID, nil, acl, nil)
387删除:}
388删除:
389407func managerStorageObject(handle windows.Handle, directory bool) (windowsStorageDisk, error) {
390408 var value windowsStorageDisk
391409 var info windows.ByHandleFileInformation
@@ -430,6 +448,9 @@ func managerGrantVMDisk(handle windows.Handle, id uuid.UUID) error {
430448}
431449
432450func (server *windowsHostManagerServer) attachStorage(ctx context.Context, journal *windowsHostStorageJournal, input windowsHostStorageRequest, conn net.Conn) error {
451新增: if !journal.RegistrationStarted {
452新增: return errors.New("invalid_request")
453新增: }
433454 if err := server.ensureStorageBackup(ctx, journal); err != nil {
434455 return err
435456 }
@@ -443,40 +464,22 @@ func (server *windowsHostManagerServer) attachStorage(ctx context.Context, journ
443464 return err
444465 }
445466 defer diskParents()
446删除: dirHandle, directory, err := managerOpenStorageDestination(conn, input.Directory, server.binding.HostSID, true)
447删除: if err != nil {
448删除: return err
449删除: }
450删除: defer windows.CloseHandle(dirHandle)
451删除: directoryParents, err := managerPinStorageParents(directory.Path)
452删除: if err != nil {
453删除: return err
454删除: }
455删除: defer directoryParents()
456删除: if cage.StoragePathsOverlap(directory.Path, disk.Path) || disk.Volume == journal.Before.DiskVolume && disk.FileID == journal.Before.DiskFileID {
467新增: if disk.Volume == journal.Before.DiskVolume && disk.FileID == journal.Before.DiskFileID {
457468 return errors.New("invalid_request")
458469 }
459470 if journal.After == nil {
460删除: entries, err := os.ReadDir(directory.Path)
461删除: if err != nil || len(entries) != 0 {
462删除: return errors.New("destination_not_empty")
463删除: }
464471 after := journal.Before
465472 after.DiskPath, after.DiskVolume, after.DiskFileID = disk.Path, disk.Volume, disk.FileID
466删除: layout := windowsVMStorageLayout{Configuration: filepath.Join(directory.Path, "configuration"), Snapshots: filepath.Join(directory.Path, "snapshots"), Paging: filepath.Join(directory.Path, "paging")}
467删除: journal.After, journal.NewLayout, journal.Directory = &after, &layout, directory
473新增: journal.After = &after
468474 if err = managerWriteStorageJSON(server.storageJournalPath(), server.binding.HostSID, journal); err != nil {
469475 return err
470476 }
471删除: } else if journal.After.DiskPath != disk.Path || journal.After.DiskVolume != disk.Volume || journal.After.DiskFileID != disk.FileID || journal.Directory != directory {
477新增: } else if journal.After.DiskPath != disk.Path || journal.After.DiskVolume != disk.Volume || journal.After.DiskFileID != disk.FileID {
472478 return errors.New("vm_changed")
473479 }
474480 if err = managerGrantVMDisk(diskHandle, server.binding.VMID); err != nil {
475481 return err
476482 }
477删除: if err = managerProtectVMMetadata(dirHandle, server.binding.HostSID, false); err != nil {
478删除: return err
479删除: }
480483 if err = server.applyStorage(ctx, journal, *journal.After, *journal.NewLayout); err != nil {
481484 return err
482485 }
@@ -488,7 +491,7 @@ func (server *windowsHostManagerServer) applyStorage(ctx context.Context, journa
488491 if err != nil {
489492 return err
490493 }
491删除: handle, err := windows.CreateFile(name, windows.FILE_READ_ATTRIBUTES, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE, nil, windows.OPEN_EXISTING, windows.FILE_FLAG_OPEN_REPARSE_POINT, 0)
494新增: handle, err := windows.CreateFile(name, windows.GENERIC_READ, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE, nil, windows.OPEN_EXISTING, windows.FILE_FLAG_OPEN_REPARSE_POINT, 0)
492495 if err != nil {
493496 return err
494497 }
@@ -511,7 +514,11 @@ func (server *windowsHostManagerServer) applyStorage(ctx context.Context, journa
511514 var result struct {
512515 Applied bool `json:"applied"`
513516 }
514删除: if err = managerStorageCommand(ctx, server.binding.VMID, "apply", map[string]any{"old": journal.OldLayout, "next": journal.NewLayout, "target": layout, "old_disk": journal.OldDisk, "source_disk": journal.Before.DiskPath, "new_disk": journal.After.DiskPath, "disk": binding.DiskPath}, &result); err != nil || !result.Applied {
517新增: newDisk := journal.Before.DiskPath
518新增: if journal.After != nil {
519新增: newDisk = journal.After.DiskPath
520新增: }
521新增: if err = managerStorageCommand(ctx, server.binding.VMID, "apply", map[string]any{"old": journal.OldLayout, "next": journal.NewLayout, "target": layout, "old_disk": journal.OldDisk, "source_disk": journal.Before.DiskPath, "new_disk": newDisk, "disk": binding.DiskPath}, &result); err != nil || !result.Applied {
515522 return errors.Join(err, errors.New("storage_operation_failed"))
516523 }
517524 return managerRequireStopped(ctx, binding)
@@ -541,8 +548,8 @@ func (server *windowsHostManagerServer) finishStorage(ctx context.Context, journ
541548 return err
542549 }
543550 } else {
544删除: if journal.After != nil {
545删除: if err := server.applyStorage(ctx, journal, journal.Before, journal.OldLayout); err != nil {
551新增: if journal.RegistrationStarted {
552新增: if err := server.applyStorage(ctx, journal, journal.Before, *journal.NewLayout); err != nil {
546553 return err
547554 }
548555 } else if err := managerRequireStopped(ctx, journal.Before); err != nil {
@@ -551,28 +558,6 @@ func (server *windowsHostManagerServer) finishStorage(ctx context.Context, journ
551558 if err := server.saveStorageBinding(journal.Before); err != nil {
552559 return err
553560 }
554删除: if journal.After != nil {
555删除: // Return the verified metadata directory to its original owner after
556删除: // Hyper-V moves back. Cleanup then runs with that user's permissions.
557删除: real, err := paths.Resolve(journal.Directory.Path)
558删除: if err == nil && strings.EqualFold(real, journal.Directory.Path) {
559删除: name, _ := windows.UTF16PtrFromString(real)
560删除: handle, openErr := windows.CreateFile(name, windows.FILE_READ_ATTRIBUTES|windows.WRITE_DAC|windows.WRITE_OWNER, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE, nil, windows.OPEN_EXISTING, windows.FILE_FLAG_OPEN_REPARSE_POINT|windows.FILE_FLAG_BACKUP_SEMANTICS, 0)
561删除: if openErr != nil {
562删除: return openErr
563删除: }
564删除: defer windows.CloseHandle(handle)
565删除: identity, identityErr := managerStorageObject(handle, true)
566删除: if identityErr != nil || identity != journal.Directory {
567删除: return errors.New("vm_changed")
568删除: }
569删除: if err := managerProtectVMMetadata(handle, server.binding.HostSID, true); err != nil {
570删除: return err
571删除: }
572删除: } else if !errors.Is(err, os.ErrNotExist) {
573删除: return errors.New("vm_changed")
574删除: }
575删除: }
576561 }
577562 journal.Phase = action
578563 return managerWriteStorageJSON(server.storageJournalPath(), server.binding.HostSID, journal)
修改internal/guestos/windows_storage.go+27 −17看文件
@@ -18,6 +18,7 @@ type windowsStorageSnapshot struct {
1818 Profile WindowsProfile `json:"profile"`
1919 Instance string `json:"instance"`
2020 Disk windowsStorageDisk `json:"disk"`
21新增: Excluded []string `json:"excluded,omitempty"`
2122}
2223
2324type windowsStorageRuntime struct {
@@ -48,7 +49,7 @@ func (runtime *windowsStorageRuntime) Snapshot(ctx context.Context, source strin
4849 }
4950 state, err := runtime.call(ctx, binding.VMID, windowsHostStorageRequest{Action: "status"})
5051 if err != nil {
51删除: return snapshot, fmt.Errorf("请先更新或恢复 Windows 系统管理助手,再迁移环境存储:%w", err)
52新增: return snapshot, fmt.Errorf("请先在设置的环境页选择“同步环境组件”,完成 Windows 系统授权后再迁移:%w", err)
5253 }
5354 if state.Pending != "" {
5455 return snapshot, errors.New("这台 Windows 客机仍有待恢复的存储迁移,请打开发起迁移的原工作台")
@@ -57,7 +58,7 @@ func (runtime *windowsStorageRuntime) Snapshot(ctx context.Context, source strin
5758 if err != nil {
5859 return snapshot, err
5960 }
60删除: snapshot.State, err = json.Marshal(windowsStorageSnapshot{Profile: *binding, Instance: instance, Disk: state.Disk})
61新增: runtimeState := windowsStorageSnapshot{Profile: *binding, Instance: instance, Disk: state.Disk}
6162 if !cage.StorageContains(source, instance) {
6263 snapshot.Backups = append(snapshot.Backups, instance)
6364 }
@@ -74,9 +75,12 @@ func (runtime *windowsStorageRuntime) Snapshot(ctx context.Context, source strin
7475 }
7576 if cage.StorageContains(source, physical) && !cage.StorageContains(physical, state.Disk.Path) {
7677 snapshot.Excluded = append(snapshot.Excluded, physical)
78新增: } else if cage.StorageContains(instance, physical) && !cage.StorageContains(physical, state.Disk.Path) {
79新增: runtimeState.Excluded = append(runtimeState.Excluded, physical)
7780 }
7881 }
7982 }
83新增: snapshot.State, err = json.Marshal(runtimeState)
8084 return snapshot, err
8185}
8286
@@ -89,13 +93,13 @@ func windowsMoveSnapshot(move cage.StorageTransition) (windowsStorageSnapshot, e
8993 return snapshot, nil
9094}
9195
92删除:func (runtime *windowsStorageRuntime) action(ctx context.Context, move cage.StorageTransition, action, disk, directory string) error {
96新增:func (runtime *windowsStorageRuntime) action(ctx context.Context, move cage.StorageTransition, action, disk string) error {
9397 snapshot, err := windowsMoveSnapshot(move)
9498 if err != nil {
9599 return err
96100 }
97101 state, err := runtime.call(ctx, snapshot.Profile.VMID, windowsHostStorageRequest{Action: action, ID: move.ID,
98删除: SourceVolume: snapshot.Disk.Volume, SourceFileID: snapshot.Disk.FileID, Disk: disk, Directory: directory})
102新增: SourceVolume: snapshot.Disk.Volume, SourceFileID: snapshot.Disk.FileID, Disk: disk})
99103 if err != nil {
100104 return err
101105 }
@@ -110,7 +114,7 @@ func (runtime *windowsStorageRuntime) action(ctx context.Context, move cage.Stor
110114}
111115
112116func (runtime *windowsStorageRuntime) Begin(ctx context.Context, move cage.StorageTransition) error {
113删除: return runtime.action(ctx, move, "begin", "", "")
117新增: return runtime.action(ctx, move, "begin", "")
114118}
115119
116120func windowsMovedPath(value, source, target string) string {
@@ -126,25 +130,25 @@ func windowsMovedPath(value, source, target string) string {
126130
127131func (runtime *windowsStorageRuntime) movedProfile(move cage.StorageTransition, snapshot windowsStorageSnapshot) (WindowsProfile, string) {
128132 logical := filepath.Join(runtime.profile, "state")
129删除: instance := filepath.Join(logical, "windows-"+strings.ReplaceAll(snapshot.Profile.VMID.String(), "-", ""))
133新增: instance := filepath.Join(move.Destination, "windows-"+strings.ReplaceAll(snapshot.Profile.VMID.String(), "-", ""))
130134 if cage.StorageContains(move.Source, snapshot.Instance) {
131删除: instance = windowsMovedPath(snapshot.Instance, move.Source, logical)
135新增: instance = windowsMovedPath(snapshot.Instance, move.Source, move.Destination)
132136 }
133137 next := snapshot.Profile
134138 next.InstanceDirectory = instance
135139 remap := func(value string) string {
136140 value = windowsMovedPath(value, snapshot.Profile.InstanceDirectory, instance)
137141 value = windowsMovedPath(value, snapshot.Instance, instance)
138删除: return windowsMovedPath(value, move.Source, logical)
142新增: value = windowsMovedPath(value, move.Source, move.Destination)
143新增: return windowsMovedPath(value, logical, move.Destination)
139144 }
140145 next.RelayExecutable = remap(next.RelayExecutable)
141146 next.PairingFile = remap(next.PairingFile)
142147 next.NetworkPairingFile = remap(next.NetworkPairingFile)
143删除: physicalInstance := windowsMovedPath(instance, logical, move.Destination)
144删除: disk := windowsMovedPath(snapshot.Disk.Path, snapshot.Instance, physicalInstance)
148新增: disk := windowsMovedPath(snapshot.Disk.Path, snapshot.Instance, instance)
145149 disk = windowsMovedPath(disk, move.Source, move.Destination)
146150 if disk == snapshot.Disk.Path {
147删除: disk = filepath.Join(physicalInstance, filepath.Base(snapshot.Disk.Path))
151新增: disk = filepath.Join(instance, filepath.Base(snapshot.Disk.Path))
148152 }
149153 return next, disk
150154}
@@ -155,9 +159,9 @@ func (runtime *windowsStorageRuntime) Switch(ctx context.Context, move cage.Stor
155159 return err
156160 }
157161 next, disk := runtime.movedProfile(move, snapshot)
158删除: physicalInstance := windowsMovedPath(next.InstanceDirectory, filepath.Join(runtime.profile, "state"), move.Destination)
162新增: physicalInstance := next.InstanceDirectory
159163 if !cage.StorageContains(move.Source, snapshot.Instance) {
160删除: if err = cage.CopyStorage(ctx, snapshot.Instance, physicalInstance, nil); err != nil {
164新增: if err = cage.CopyStorage(ctx, snapshot.Instance, physicalInstance, snapshot.Excluded, nil); err != nil {
161165 return err
162166 }
163167 }
@@ -169,11 +173,17 @@ func (runtime *windowsStorageRuntime) Switch(ctx context.Context, move cage.Stor
169173 return err
170174 }
171175 }
172删除: directory := filepath.Join(move.Destination, "hyperv-"+snapshot.Profile.VMID.String()+"-"+move.ID)
173删除: if err = os.Mkdir(directory, 0700); err != nil {
176新增: if err = prepareWindowsStorageDisk(ctx, snapshot.Disk.Path, disk); err != nil {
174177 return err
175178 }
176删除: if err = runtime.action(ctx, move, "attach", disk, directory); err != nil {
179新增: for _, path := range []string{next.PairingFile, next.NetworkPairingFile} {
180新增: if path != "" && cage.StorageContains(move.Destination, path) {
181新增: if err = protectWindowsProfile(path); err != nil {
182新增: return err
183新增: }
184新增: }
185新增: }
186新增: if err = runtime.action(ctx, move, "attach", disk); err != nil {
177187 return err
178188 }
179189 return runtime.writeProfile(snapshot.Profile, next, next)
@@ -189,7 +199,7 @@ func (runtime *windowsStorageRuntime) Recover(ctx context.Context, move cage.Sto
189199 if committed {
190200 chosen, action = next, "commit"
191201 }
192删除: if err = runtime.action(ctx, move, action, "", ""); err != nil {
202新增: if err = runtime.action(ctx, move, action, ""); err != nil {
193203 return err
194204 }
195205 return runtime.writeProfile(snapshot.Profile, next, chosen)
修改internal/guestos/windows_storage.ps1+4 −2看文件
@@ -2,7 +2,9 @@ $ErrorActionPreference = 'Stop'
22$ProgressPreference = 'SilentlyContinue'
33$id = [guid]$inputData.vm_id
44$vm = Get-VM -Id $id
5删除:if ($vm.State -ne 'Off' -or $vm.Generation -ne 2 -or
5新增:$recoveringDisk = $inputData.action -eq 'apply' -and $inputData.disk -ieq $inputData.source_disk
6新增:$stopped = $vm.State -eq 'Off' -or ($recoveringDisk -and $vm.State -eq 'OffCritical')
7新增:if (!$stopped -or $vm.Generation -ne 2 -or
68 @(Get-VMNetworkAdapter -VM $vm).Count -ne 0 -or
79 (Get-VMFirmware -VM $vm).SecureBoot -ne 'On' -or !(Get-VMSecurity -VM $vm).TpmEnabled) {
810 throw 'vm_changed'
@@ -62,7 +64,7 @@ if ($move.Count) {
6264}
6365$vm = Get-VM -Id $id
6466$disks = @(Get-VMHardDiskDrive -VM $vm)
65删除:if ($vm.State -ne 'Off' -or $disks.Count -ne 1) { throw 'vm_changed' }
67新增:if (($vm.State -ne 'Off' -and !($recoveringDisk -and $vm.State -eq 'OffCritical')) -or $disks.Count -ne 1) { throw 'vm_changed' }
6668if ($disks[0].Path -ine $inputData.disk) {
6769 Set-VMHardDiskDrive -VMHardDiskDrive $disks[0] -Path ([string]$inputData.disk)
6870}
新增internal/guestos/windows_storage_disk_nonwindows_test.go+15 −0看文件
@@ -0,0 +1,15 @@
1新增://go:build !windows
2新增:
3新增:package guestos
4新增:
5新增:import (
6新增: "os"
7新增: "testing"
8新增:)
9新增:
10新增:func createWindowsStorageFixtureDisk(t *testing.T, path string) {
11新增: t.Helper()
12新增: if err := os.WriteFile(path, []byte("synthetic persistent disk data"), 0600); err != nil {
13新增: t.Fatal(err)
14新增: }
15新增:}
新增internal/guestos/windows_storage_disk_windows.go+246 −0看文件
@@ -0,0 +1,246 @@
1新增://go:build windows
2新增:
3新增:package guestos
4新增:
5新增:import (
6新增: "context"
7新增: "errors"
8新增: "fmt"
9新增: "os"
10新增: "path/filepath"
11新增: "runtime"
12新增: "unsafe"
13新增:
14新增: "golang.org/x/sys/windows"
15新增:)
16新增:
17新增:var storageVirtualDiskDLL = windows.NewLazySystemDLL("virtdisk.dll")
18新增:
19新增:type storageVirtualDiskType struct {
20新增: Device uint32
21新增: Vendor windows.GUID
22新增:}
23新增:
24新增:var storageVHDXType = storageVirtualDiskType{
25新增: Device: 3,
26新增: Vendor: windows.GUID{Data1: 0xec984aec, Data2: 0xa0f9, Data3: 0x47e9, Data4: [8]byte{0x90, 0x1f, 0x71, 0x41, 0x5a, 0x66, 0x34, 0x5b}},
27新增:}
28新增:
29新增:// CREATE_VIRTUAL_DISK_PARAMETERS version 2 has an eight-byte aligned union.
30新增:type storageVirtualDiskCreate struct {
31新增: Version uint32
32新增: _ uint32
33新增: Identifier windows.GUID
34新增: MaximumSize uint64
35新增: BlockSize uint32
36新增: SectorSize uint32
37新增: PhysicalSector uint32
38新增: ParentPath *uint16
39新增: SourcePath *uint16
40新增: OpenFlags uint32
41新增: ParentType storageVirtualDiskType
42新增: SourceType storageVirtualDiskType
43新增: Resiliency windows.GUID
44新增:}
45新增:
46新增:type storageVirtualDiskMetadata struct {
47新增: Subtype uint32
48新增: Identifier windows.GUID
49新增: VirtualSize uint64
50新增: BlockSize uint32
51新增: SectorSize uint32
52新增: PhysicalSector uint32
53新增:}
54新增:
55新增:func readWindowsStorageDisk(path string) (storageVirtualDiskMetadata, error) {
56新增: var metadata storageVirtualDiskMetadata
57新增: name, err := windows.UTF16PtrFromString(path)
58新增: if err != nil {
59新增: return metadata, err
60新增: }
61新增: parameters := struct {
62新增: Version uint32
63新增: InfoOnly int32
64新增: ReadOnly int32
65新增: Resiliency windows.GUID
66新增: }{Version: 2, InfoOnly: 1, ReadOnly: 1}
67新增: var handle windows.Handle
68新增: status, _, _ := storageVirtualDiskDLL.NewProc("OpenVirtualDisk").Call(
69新增: uintptr(unsafe.Pointer(&storageVHDXType)), uintptr(unsafe.Pointer(name)), 0, 0,
70新增: uintptr(unsafe.Pointer(&parameters)), uintptr(unsafe.Pointer(&handle)))
71新增: runtime.KeepAlive(name)
72新增: if status != 0 {
73新增: return metadata, fmt.Errorf("读取 Windows 客机磁盘失败:%w", windows.Errno(status))
74新增: }
75新增: defer windows.CloseHandle(handle)
76新增: for _, version := range []uint32{1, 2, 7, 10} {
77新增: information := struct {
78新增: Version uint32
79新增: _ uint32
80新增: Data [4]uint64
81新增: }{Version: version}
82新增: size, used := uint32(unsafe.Sizeof(information)), uint32(0)
83新增: status, _, _ = storageVirtualDiskDLL.NewProc("GetVirtualDiskInformation").Call(
84新增: uintptr(handle), uintptr(unsafe.Pointer(&size)), uintptr(unsafe.Pointer(&information)), uintptr(unsafe.Pointer(&used)))
85新增: if status != 0 {
86新增: return metadata, fmt.Errorf("读取 Windows 客机磁盘属性失败:%w", windows.Errno(status))
87新增: }
88新增: switch version {
89新增: case 1:
90新增: metadata.VirtualSize = information.Data[0]
91新增: metadata.BlockSize = uint32(information.Data[2])
92新增: metadata.SectorSize = uint32(information.Data[2] >> 32)
93新增: case 2:
94新增: metadata.Identifier = *(*windows.GUID)(unsafe.Pointer(&information.Data[0]))
95新增: case 7:
96新增: metadata.Subtype = uint32(information.Data[0])
97新增: case 10:
98新增: metadata.PhysicalSector = uint32(information.Data[0])
99新增: }
100新增: }
101新增: return metadata, nil
102新增:}
103新增:
104新增:// Cancellation must finish native I/O before its pinned OVERLAPPED, file
105新增:// handles, or source-disk protection can be released by the migration caller.
106新增:func createWindowsStorageDisk(ctx context.Context, path string, parameters *storageVirtualDiskCreate, flags uint32) (err error) {
107新增: if err := ctx.Err(); err != nil {
108新增: return err
109新增: }
110新增: name, err := windows.UTF16PtrFromString(path)
111新增: if err != nil {
112新增: return err
113新增: }
114新增: event, err := windows.CreateEvent(nil, 1, 0, nil)
115新增: if err != nil {
116新增: return err
117新增: }
118新增: defer windows.CloseHandle(event)
119新增: overlapped := &windows.Overlapped{HEvent: event}
120新增: var pinned runtime.Pinner
121新增: pinned.Pin(overlapped)
122新增: pinned.Pin(parameters)
123新增: pinned.Pin(name)
124新增: if parameters.SourcePath != nil {
125新增: pinned.Pin(parameters.SourcePath)
126新增: }
127新增: if parameters.ParentPath != nil {
128新增: pinned.Pin(parameters.ParentPath)
129新增: }
130新增: defer pinned.Unpin()
131新增: var handle windows.Handle
132新增: status, _, _ := storageVirtualDiskDLL.NewProc("CreateVirtualDisk").Call(
133新增: uintptr(unsafe.Pointer(&storageVHDXType)), uintptr(unsafe.Pointer(name)), 0, 0, uintptr(flags), 0,
134新增: uintptr(unsafe.Pointer(parameters)), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(&handle)))
135新增: if handle != 0 && handle != windows.InvalidHandle {
136新增: defer func() { err = errors.Join(err, windows.CloseHandle(handle)) }()
137新增: }
138新增: if status != 0 && status != uintptr(windows.ERROR_IO_PENDING) {
139新增: return fmt.Errorf("创建独立 Windows 客机磁盘失败:%w", windows.Errno(status))
140新增: }
141新增: if status == 0 {
142新增: return ctx.Err()
143新增: }
144新增: cancelDone := make(chan struct{})
145新增: var cancelErr error
146新增: stopCancel := context.AfterFunc(ctx, func() {
147新增: cancelErr = windows.CancelIoEx(handle, overlapped)
148新增: close(cancelDone)
149新增: })
150新增: wait, waitErr := windows.WaitForSingleObject(event, windows.INFINITE)
151新增: if !stopCancel() {
152新增: <-cancelDone
153新增: }
154新增: if waitErr != nil || wait != windows.WAIT_OBJECT_0 {
155新增: // A wait failure must still drain the operation before releasing memory.
156新增: _ = windows.CancelIoEx(handle, overlapped)
157新增: var transferred uint32
158新增: drainErr := windows.GetOverlappedResult(handle, overlapped, &transferred, true)
159新增: return errors.Join(fmt.Errorf("等待 Windows 磁盘复制完成失败 (%d)", wait), waitErr, drainErr)
160新增: }
161新增: if errors.Is(cancelErr, windows.ERROR_NOT_FOUND) {
162新增: cancelErr = nil // Completion can win the cancellation race.
163新增: }
164新增: if err := ctx.Err(); err != nil {
165新增: return errors.Join(err, cancelErr)
166新增: }
167新增: progress := struct {
168新增: Status uint32
169新增: Current, Total uint64
170新增: }{}
171新增: status, _, _ = storageVirtualDiskDLL.NewProc("GetVirtualDiskOperationProgress").Call(
172新增: uintptr(handle), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(&progress)))
173新增: if status != 0 {
174新增: return fmt.Errorf("查询 Windows 磁盘复制结果失败:%w", windows.Errno(status))
175新增: }
176新增: if progress.Status != 0 {
177新增: return fmt.Errorf("Windows 磁盘复制失败:%w", windows.Errno(progress.Status))
178新增: }
179新增: return nil
180新增:}
181新增:
182新增:func prepareWindowsStorageDisk(ctx context.Context, source, copied string) (err error) {
183新增: if err := ctx.Err(); err != nil {
184新增: return err
185新增: }
186新增: before, err := readWindowsStorageDisk(source)
187新增: if err != nil {
188新增: return err
189新增: }
190新增: if before.Subtype == 2 || before.Subtype == 3 {
191新增: return nil
192新增: }
193新增: if before.Subtype != 4 {
194新增: return fmt.Errorf("Windows 客机磁盘类型无效 (%d)", before.Subtype)
195新增: }
196新增: original, err := os.Stat(source)
197新增: if err != nil {
198新增: return err
199新增: }
200新增: destination, err := os.Stat(copied)
201新增: if err != nil {
202新增: return err
203新增: }
204新增: if os.SameFile(original, destination) {
205新增: return errors.New("独立磁盘副本与原磁盘必须使用不同文件")
206新增: }
207新增: folder, err := os.MkdirTemp(filepath.Dir(copied), ".windows-disk-*")
208新增: if err != nil {
209新增: return err
210新增: }
211新增: defer func() { err = errors.Join(err, os.RemoveAll(folder)) }()
212新增: path := filepath.Join(folder, "disk.vhdx")
213新增: name, err := windows.UTF16PtrFromString(source)
214新增: if err != nil {
215新增: return err
216新增: }
217新增: parameters := storageVirtualDiskCreate{
218新增: Version: 2, Identifier: before.Identifier, BlockSize: before.BlockSize,
219新增: SectorSize: before.SectorSize, PhysicalSector: before.PhysicalSector,
220新增: SourcePath: name, SourceType: storageVHDXType,
221新增: }
222新增: if err := createWindowsStorageDisk(ctx, path, &parameters, 0); err != nil {
223新增: return err
224新增: }
225新增: after, err := readWindowsStorageDisk(path)
226新增: if err != nil {
227新增: return err
228新增: }
229新增: expected := before
230新增: expected.Subtype = 3
231新增: if after != expected {
232新增: return errors.New("独立磁盘副本的标识或磁盘参数不一致")
233新增: }
234新增: if err := ctx.Err(); err != nil {
235新增: return err
236新增: }
237新增: from, err := windows.UTF16PtrFromString(path)
238新增: if err != nil {
239新增: return err
240新增: }
241新增: to, err := windows.UTF16PtrFromString(copied)
242新增: if err != nil {
243新增: return err
244新增: }
245新增: return windows.MoveFileEx(from, to, windows.MOVEFILE_REPLACE_EXISTING|windows.MOVEFILE_WRITE_THROUGH)
246新增:}
新增internal/guestos/windows_storage_disk_windows_test.go+299 −0看文件
@@ -0,0 +1,299 @@
1新增://go:build windows
2新增:
3新增:package guestos
4新增:
5新增:import (
6新增: "bytes"
7新增: "context"
8新增: "crypto/sha256"
9新增: "encoding/binary"
10新增: "errors"
11新增: "io"
12新增: "os"
13新增: "path/filepath"
14新增: "reflect"
15新增: "sync/atomic"
16新增: "testing"
17新增: "unsafe"
18新增:
19新增: "github.com/sylvinus/agent-vm/internal/cage"
20新增: "golang.org/x/sys/windows"
21新增:)
22新增:
23新增:func createWindowsStorageFixtureDisk(t *testing.T, path string) {
24新增: t.Helper()
25新增: createWindowsStorageTestDisk(t, path, "", 0)
26新增:}
27新增:
28新增:func createWindowsStorageTestDisk(t *testing.T, path, parent string, flags uint32) {
29新增: t.Helper()
30新增: if unsafe.Sizeof(storageVirtualDiskCreate{}) != 128 {
31新增: t.Fatal("unexpected native VHDX parameter layout")
32新增: }
33新增: parameters := storageVirtualDiskCreate{
34新增: Version: 2, MaximumSize: 8 << 20, BlockSize: 2 << 20,
35新增: SectorSize: 512, PhysicalSector: 4096,
36新增: }
37新增: if parent != "" {
38新增: var err error
39新增: parameters.ParentPath, err = windows.UTF16PtrFromString(parent)
40新增: if err != nil {
41新增: t.Fatal(err)
42新增: }
43新增: parameters.MaximumSize, parameters.ParentType = 0, storageVHDXType
44新增: }
45新增: if err := createWindowsStorageDisk(context.Background(), path, &parameters, flags); err != nil {
46新增: t.Fatal(err)
47新增: }
48新增:}
49新增:
50新增:func windowsStorageDiskDigest(t *testing.T, path string) [32]byte {
51新增: t.Helper()
52新增: file, err := os.Open(path)
53新增: if err != nil {
54新增: t.Fatal(err)
55新增: }
56新增: defer file.Close()
57新增: hash := sha256.New()
58新增: if _, err := io.Copy(hash, file); err != nil {
59新增: t.Fatal(err)
60新增: }
61新增: return [32]byte(hash.Sum(nil))
62新增:}
63新增:
64新增:func windowsStorageDiskEntries(t *testing.T, path string) []string {
65新增: t.Helper()
66新增: entries, err := os.ReadDir(path)
67新增: if err != nil {
68新增: t.Fatal(err)
69新增: }
70新增: names := make([]string, len(entries))
71新增: for index, entry := range entries {
72新增: names[index] = entry.Name()
73新增: }
74新增: return names
75新增:}
76新增:
77新增:func TestWindowsStorageDiskIndependentCopiesUntouched(t *testing.T) {
78新增: for _, test := range []struct {
79新增: name string
80新增: flags uint32
81新增: }{{"dynamic", 0}, {"fixed", 1}} {
82新增: t.Run(test.name, func(t *testing.T) {
83新增: root := t.TempDir()
84新增: source, copied := filepath.Join(root, "source.vhdx"), filepath.Join(root, "copied.vhdx")
85新增: createWindowsStorageTestDisk(t, source, "", test.flags)
86新增: digest := windowsStorageDiskDigest(t, source)
87新增: if err := cage.CopyStorageFile(context.Background(), source, copied); err != nil {
88新增: t.Fatal(err)
89新增: }
90新增: if err := prepareWindowsStorageDisk(context.Background(), source, copied); err != nil {
91新增: t.Fatal(err)
92新增: }
93新增: if windowsStorageDiskDigest(t, source) != digest || windowsStorageDiskDigest(t, copied) != digest {
94新增: t.Fatal("standalone disk bytes changed")
95新增: }
96新增: if _, err := readWindowsStorageDisk(copied); err != nil {
97新增: t.Fatal("copied VHDX could not open with native flags NONE", err)
98新增: }
99新增: })
100新增: }
101新增:}
102新增:
103新增:// These fixtures modify only payload blocks and BAT entries of freshly created
104新增:// VHDX files. A fully present differencing block does not require a bitmap.
105新增:func windowsStorageDiskPayload(t *testing.T, file *os.File, block uint64) (int64, uint64) {
106新增: t.Helper()
107新增: table := make([]byte, 64<<10)
108新增: if _, err := file.ReadAt(table, 192<<10); err != nil {
109新增: t.Fatal(err)
110新增: }
111新增: if string(table[:4]) != "regi" || binary.LittleEndian.Uint32(table[8:]) > 2047 {
112新增: t.Fatal("invalid VHDX region table")
113新增: }
114新增: bat := []byte{0x66, 0x77, 0xc2, 0x2d, 0x23, 0xf6, 0x00, 0x42, 0x9d, 0x64, 0x11, 0x5e, 0x9b, 0xfd, 0x4a, 0x08}
115新增: for index := uint32(0); index < binary.LittleEndian.Uint32(table[8:]); index++ {
116新增: entry := table[16+int(index)*32:]
117新增: if bytes.Equal(entry[:16], bat) {
118新增: position := int64(binary.LittleEndian.Uint64(entry[16:])) + int64(block*8)
119新增: var value [8]byte
120新增: if _, err := file.ReadAt(value[:], position); err != nil {
121新增: t.Fatal(err)
122新增: }
123新增: return position, binary.LittleEndian.Uint64(value[:])
124新增: }
125新增: }
126新增: t.Fatal("VHDX BAT region missing")
127新增: return 0, 0
128新增:}
129新增:
130新增:func writeWindowsStorageDiskPayload(t *testing.T, path string, block uint64, data []byte) {
131新增: t.Helper()
132新增: file, err := os.OpenFile(path, os.O_RDWR, 0)
133新增: if err != nil {
134新增: t.Fatal(err)
135新增: }
136新增: defer file.Close()
137新增: position, value := windowsStorageDiskPayload(t, file, block)
138新增: offset := value & ^uint64((1<<20)-1)
139新增: if value&7 != 6 {
140新增: info, err := file.Stat()
141新增: if err != nil {
142新增: t.Fatal(err)
143新增: }
144新增: offset = uint64(info.Size()+(1<<20)-1) & ^uint64((1<<20)-1)
145新增: }
146新增: if _, err := file.WriteAt(data, int64(offset)); err != nil {
147新增: t.Fatal(err)
148新增: }
149新增: var entry [8]byte
150新增: binary.LittleEndian.PutUint64(entry[:], offset|6)
151新增: if _, err := file.WriteAt(entry[:], position); err != nil {
152新增: t.Fatal(err)
153新增: }
154新增: if err := file.Sync(); err != nil {
155新增: t.Fatal(err)
156新增: }
157新增:}
158新增:
159新增:func readWindowsStorageDiskPayload(t *testing.T, path string, block uint64) []byte {
160新增: t.Helper()
161新增: file, err := os.Open(path)
162新增: if err != nil {
163新增: t.Fatal(err)
164新增: }
165新增: defer file.Close()
166新增: _, value := windowsStorageDiskPayload(t, file, block)
167新增: if value&7 != 6 {
168新增: t.Fatal("materialized VHDX block is not fully present", block, value&7)
169新增: }
170新增: data := make([]byte, 2<<20)
171新增: if _, err := file.ReadAt(data, int64(value & ^uint64((1<<20)-1))); err != nil {
172新增: t.Fatal(err)
173新增: }
174新增: return data
175新增:}
176新增:
177新增:func windowsStorageDifferencingFixture(t *testing.T) (root, parent, source, copied string, parentData, childData []byte) {
178新增: t.Helper()
179新增: root = t.TempDir()
180新增: parent, source, copied = filepath.Join(root, "parent.vhdx"), filepath.Join(root, "child.vhdx"), filepath.Join(root, "copied.vhdx")
181新增: createWindowsStorageTestDisk(t, parent, "", 1)
182新增: parentData, childData = make([]byte, 2<<20), make([]byte, 2<<20)
183新增: copy(parentData[4096:], []byte("parent inherited user data"))
184新增: copy(childData[8192:], []byte("child changed user data"))
185新增: writeWindowsStorageDiskPayload(t, parent, 0, parentData)
186新增: createWindowsStorageTestDisk(t, source, parent, 0)
187新增: writeWindowsStorageDiskPayload(t, source, 1, childData)
188新增: if err := cage.CopyStorageFile(context.Background(), source, copied); err != nil {
189新增: t.Fatal(err)
190新增: }
191新增: return
192新增:}
193新增:
194新增:func TestWindowsStorageDiskDifferencingCopyIndependent(t *testing.T) {
195新增: root, parent, source, copied, parentData, childData := windowsStorageDifferencingFixture(t)
196新增: beforeEntries := windowsStorageDiskEntries(t, root)
197新增: sourceHash, parentHash := windowsStorageDiskDigest(t, source), windowsStorageDiskDigest(t, parent)
198新增: before, err := readWindowsStorageDisk(source)
199新增: if err != nil {
200新增: t.Fatal(err)
201新增: }
202新增: if err := prepareWindowsStorageDisk(context.Background(), source, copied); err != nil {
203新增: t.Fatal(err)
204新增: }
205新增: after, err := readWindowsStorageDisk(copied)
206新增: if err != nil || before.Subtype != 4 || after.Subtype != 3 || after.Identifier != before.Identifier {
207新增: t.Fatal("differencing disk identity was lost", before, after, err)
208新增: }
209新增: if !bytes.Equal(readWindowsStorageDiskPayload(t, copied, 0), parentData) || !bytes.Equal(readWindowsStorageDiskPayload(t, copied, 1), childData) {
210新增: t.Fatal("materialization changed logical disk data")
211新增: }
212新增: if sourceHash != windowsStorageDiskDigest(t, source) || parentHash != windowsStorageDiskDigest(t, parent) {
213新增: t.Fatal("materialization modified original disk chain")
214新增: }
215新增: if !reflect.DeepEqual(beforeEntries, windowsStorageDiskEntries(t, root)) {
216新增: t.Fatal("materialization left temporary files")
217新增: }
218新增: moved := parent + ".moved"
219新增: if err := os.Rename(parent, moved); err != nil {
220新增: t.Fatal(err)
221新增: }
222新增: defer func() {
223新增: if err := os.Rename(moved, parent); err != nil {
224新增: t.Error(err)
225新增: }
226新增: }()
227新增: if _, err := readWindowsStorageDisk(source); err == nil {
228新增: t.Fatal("missing-parent fixture still opened")
229新增: }
230新增: if _, err := readWindowsStorageDisk(copied); err != nil {
231新增: t.Fatal("materialized disk retained original parent dependency", err)
232新增: }
233新增:}
234新增:
235新增:// The context cancels when the production function registers native-I/O
236新增:// cancellation, after CreateVirtualDisk has returned ERROR_IO_PENDING.
237新增:type windowsStorageCancelAtWait struct {
238新增: context.Context
239新增: done chan struct{}
240新增: cancelled atomic.Bool
241新增:}
242新增:
243新增:func (ctx *windowsStorageCancelAtWait) Done() <-chan struct{} { return ctx.done }
244新增:func (ctx *windowsStorageCancelAtWait) Err() error {
245新增: if ctx.cancelled.Load() {
246新增: return context.Canceled
247新增: }
248新增: return nil
249新增:}
250新增:func (ctx *windowsStorageCancelAtWait) AfterFunc(callback func()) func() bool {
251新增: ctx.cancelled.Store(true)
252新增: close(ctx.done)
253新增: go callback()
254新增: return func() bool { return false }
255新增:}
256新增:
257新增:func TestWindowsStorageDiskCancellationAndReplacementFailure(t *testing.T) {
258新增: for _, mode := range []string{"cancel_before_start", "cancel_native_copy", "replacement_denied"} {
259新增: t.Run(mode, func(t *testing.T) {
260新增: root, parent, source, copied, _, _ := windowsStorageDifferencingFixture(t)
261新增: entries := windowsStorageDiskEntries(t, root)
262新增: sourceHash, copiedHash, parentHash := windowsStorageDiskDigest(t, source), windowsStorageDiskDigest(t, copied), windowsStorageDiskDigest(t, parent)
263新增: ctx := context.Background()
264新增: if mode == "cancel_before_start" {
265新增: cancelled, cancel := context.WithCancel(ctx)
266新增: cancel()
267新增: ctx = cancelled
268新增: }
269新增: if mode == "cancel_native_copy" {
270新增: ctx = &windowsStorageCancelAtWait{Context: ctx, done: make(chan struct{})}
271新增: }
272新增: if mode == "replacement_denied" {
273新增: name, err := windows.UTF16PtrFromString(copied)
274新增: if err != nil {
275新增: t.Fatal(err)
276新增: }
277新增: handle, err := windows.CreateFile(name, windows.GENERIC_READ, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE, nil, windows.OPEN_EXISTING, 0, 0)
278新增: if err != nil {
279新增: t.Fatal(err)
280新增: }
281新增: defer windows.CloseHandle(handle)
282新增: }
283新增: err := prepareWindowsStorageDisk(ctx, source, copied)
284新增: if mode == "replacement_denied" {
285新增: if !errors.Is(err, windows.ERROR_SHARING_VIOLATION) && !errors.Is(err, windows.ERROR_ACCESS_DENIED) {
286新增: t.Fatal("replacement failure was not reported", err)
287新增: }
288新增: } else if !errors.Is(err, context.Canceled) {
289新增: t.Fatal("native disk cancellation was not reported", err)
290新增: }
291新增: if windowsStorageDiskDigest(t, source) != sourceHash || windowsStorageDiskDigest(t, copied) != copiedHash || windowsStorageDiskDigest(t, parent) != parentHash {
292新增: t.Fatal("failed materialization modified a retained disk")
293新增: }
294新增: if !reflect.DeepEqual(entries, windowsStorageDiskEntries(t, root)) {
295新增: t.Fatal("failed materialization left temporary files")
296新增: }
297新增: })
298新增: }
299新增:}
修改internal/guestos/windows_storage_nonwindows.go+9 −0看文件
@@ -5,6 +5,7 @@ package guestos
55import (
66 "context"
77 "errors"
8新增: "io"
89 "os"
910 "path/filepath"
1011
@@ -15,6 +16,14 @@ func windowsHostStorage(context.Context, uuid.UUID, windowsHostStorageRequest) (
1516 return windowsHostStorageState{}, errors.New("Windows 客机存储迁移需要 Windows Hyper-V 主机")
1617}
1718
19新增:func WindowsPrivateStoragePaths() []string { return nil }
20新增:
21新增:func prepareWindowsStorageDisk(context.Context, string, string) error { return nil }
22新增:
23新增:func RepairWindowsHostManager(context.Context, string, string, io.Writer, io.Writer) error {
24新增: return errors.New("Windows 系统助手需要在原 Windows 主机上恢复")
25新增:}
26新增:
1827func replaceWindowsStorageProfile(path string, data []byte) error {
1928 file, err := os.CreateTemp(filepath.Dir(path), ".windows-storage-*")
2029 if err != nil {
新增internal/guestos/windows_storage_script_test.go+32 −0看文件
@@ -0,0 +1,32 @@
1新增:package guestos
2新增:
3新增:import (
4新增: "os/exec"
5新增: "path/filepath"
6新增: "runtime"
7新增: "testing"
8新增:)
9新增:
10新增:func TestWindowsStoragePowerShellTransition(t *testing.T) {
11新增: command := "pwsh"
12新增: if runtime.GOOS == "windows" {
13新增: command = "powershell.exe"
14新增: }
15新增: powershell, err := exec.LookPath(command)
16新增: if err != nil {
17新增: t.Skip("requires PowerShell for the native storage command contract")
18新增: }
19新增: source, err := filepath.Abs("windows_storage.ps1")
20新增: if err != nil {
21新增: t.Fatal(err)
22新增: }
23新增: test, err := filepath.Abs(filepath.Join("testdata", "windows_storage.ps1"))
24新增: if err != nil {
25新增: t.Fatal(err)
26新增: }
27新增: output, err := exec.Command(powershell, "-NoLogo", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", test, "-Implementation", source).CombinedOutput()
28新增: if err != nil {
29新增: t.Fatalf("native storage contract: %v\n%s", err, output)
30新增: }
31新增: t.Log(string(output))
32新增:}
新增internal/guestos/windows_storage_test.go+245 −0看文件
@@ -0,0 +1,245 @@
1新增:package guestos
2新增:
3新增:import (
4新增: "bytes"
5新增: "context"
6新增: "errors"
7新增: "os"
8新增: "path/filepath"
9新增: "reflect"
10新增: "testing"
11新增:
12新增: "github.com/google/uuid"
13新增: "github.com/sylvinus/agent-vm/internal/cage"
14新增:)
15新增:
16新增:type windowsStorageBrokerFixture struct {
17新增: t *testing.T
18新增: vm uuid.UUID
19新增: disk windowsStorageDisk
20新增: layout *windowsVMStorageLayout
21新增: before windowsStorageDisk
22新增: pending string
23新增: events []string
24新增: failAttach bool
25新增: failRecovery bool
26新增:}
27新增:
28新增:func (broker *windowsStorageBrokerFixture) call(_ context.Context, id uuid.UUID, input windowsHostStorageRequest) (windowsHostStorageState, error) {
29新增: broker.t.Helper()
30新增: if id != broker.vm || input.validate() != nil {
31新增: broker.t.Fatal("invalid fixed-VM request", input)
32新增: }
33新增: broker.events = append(broker.events, input.Action)
34新增: switch input.Action {
35新增: case "status":
36新增: return windowsHostStorageState{Disk: broker.disk, Pending: broker.pending, Layout: broker.layout}, nil
37新增: case "begin":
38新增: broker.before, broker.pending = broker.disk, input.ID
39新增: case "attach":
40新增: if input.ID != broker.pending {
41新增: broker.t.Fatal("attachment lost migration identity")
42新增: }
43新增: old, err := os.ReadFile(broker.before.Path)
44新增: if err != nil {
45新增: broker.t.Fatal(err)
46新增: }
47新增: copied, err := os.ReadFile(input.Disk)
48新增: if err != nil || !bytes.Equal(old, copied) {
49新增: broker.t.Fatal("runtime attached unverified disk bytes", err)
50新增: }
51新增: broker.disk = windowsStorageDisk{Path: input.Disk, Volume: 2, FileID: broker.before.FileID + 1}
52新增: if broker.failAttach {
53新增: return windowsHostStorageState{}, errors.New("response lost after attachment")
54新增: }
55新增: case "commit", "rollback":
56新增: if broker.failRecovery {
57新增: return windowsHostStorageState{}, errors.New("helper unavailable during recovery")
58新增: }
59新增: if input.Action == "rollback" {
60新增: if _, err := os.Stat(broker.before.Path); err != nil {
61新增: broker.t.Fatal("old stable directory was not restored before VM rollback", err)
62新增: }
63新增: if _, err := os.Stat(broker.disk.Path); err != nil {
64新增: broker.t.Fatal("new disk deleted before VM rollback", err)
65新增: }
66新增: broker.disk = broker.before
67新增: }
68新增: broker.pending = ""
69新增: }
70新增: return windowsHostStorageState{Disk: broker.disk, Pending: broker.pending, Outcome: input.Action}, nil
71新增:}
72新增:
73新增:func windowsStorageFixture(t *testing.T, external bool) (string, *windowsStorageRuntime, *windowsStorageBrokerFixture, WindowsProfile) {
74新增: t.Helper()
75新增: root, err := filepath.EvalSymlinks(t.TempDir())
76新增: if err != nil {
77新增: t.Fatal(err)
78新增: }
79新增: profile := filepath.Join(root, "profile")
80新增: instance := filepath.Join(profile, "state", "windows-existing")
81新增: if external {
82新增: instance = filepath.Join(root, "existing VM outside profile")
83新增: }
84新增: if err := os.MkdirAll(instance, 0700); err != nil {
85新增: t.Fatal(err)
86新增: }
87新增: if err := os.MkdirAll(profile, 0700); err != nil {
88新增: t.Fatal(err)
89新增: }
90新增: binding := windowsBindingFixture(profile)
91新增: binding.InstanceDirectory = instance
92新增: binding.RelayExecutable = filepath.Join(instance, "relay.exe")
93新增: binding.PairingFile = filepath.Join(instance, "pairing.dpapi")
94新增: binding.NetworkPairingFile = filepath.Join(instance, "network.dpapi")
95新增: for _, path := range []string{binding.RelayExecutable, binding.PairingFile, binding.NetworkPairingFile} {
96新增: if err := os.WriteFile(path, []byte("synthetic pairing bytes"), 0600); err != nil {
97新增: t.Fatal(err)
98新增: }
99新增: }
100新增: disk := filepath.Join(instance, "system.vhdx")
101新增: createWindowsStorageFixtureDisk(t, disk)
102新增: if err := BindWindowsProfile(profile, binding); err != nil {
103新增: t.Fatal(err)
104新增: }
105新增: broker := &windowsStorageBrokerFixture{t: t, vm: binding.VMID, disk: windowsStorageDisk{Path: disk, Volume: 1, FileID: 11}}
106新增: return profile, &windowsStorageRuntime{profile: profile, call: broker.call}, broker, binding
107新增:}
108新增:
109新增:func TestWindowsStorageMigrationPreservesPairingAndPriorDisks(t *testing.T) {
110新增: for _, external := range []bool{false, true} {
111新增: name := "managed_instance"
112新增: if external {
113新增: name = "existing_external_instance"
114新增: }
115新增: t.Run(name, func(t *testing.T) {
116新增: profile, runtime, broker, original := windowsStorageFixture(t, external)
117新增: originalDisk, err := os.ReadFile(broker.disk.Path)
118新增: if err != nil {
119新增: t.Fatal(err)
120新增: }
121新增: for attempt := 0; attempt < 2; attempt++ {
122新增: location, err := cage.GetStorageLocation(profile)
123新增: if err != nil || !location.HasEnvironment {
124新增: t.Fatal("Windows environment not detected", location, err)
125新增: }
126新增: target := filepath.Join(t.TempDir(), "环境存储")
127新增: moved, err := cage.MoveStorageWithRuntime(context.Background(), profile, target, location, runtime, nil)
128新增: if err != nil {
129新增: t.Fatal(err)
130新增: }
131新增: actual, err := LoadWindowsProfile(profile)
132新增: if err != nil || actual == nil || actual.VMID != original.VMID || actual.GUIUserSID != original.GUIUserSID {
133新增: t.Fatal("migration changed VM or GUI identity", err)
134新增: }
135新增: for _, path := range []string{actual.RelayExecutable, actual.PairingFile, actual.NetworkPairingFile} {
136新增: data, err := os.ReadFile(path)
137新增: if err != nil || string(data) != "synthetic pairing bytes" {
138新增: t.Fatal("pairing changed or lost its stable path", path, err)
139新增: }
140新增: }
141新增: if broker.pending != "" || !moved.Custom || moved.Backup == "" {
142新增: t.Fatal("migration did not finish or retain backup", moved, broker.pending)
143新增: }
144新增: if data, err := os.ReadFile(broker.disk.Path); err != nil || !bytes.Equal(data, originalDisk) {
145新增: t.Fatal("new disk unavailable", err)
146新增: }
147新增: if external && attempt == 0 {
148新增: private, err := cage.StoragePrivatePaths(profile)
149新增: if err != nil {
150新增: t.Fatal(err)
151新增: }
152新增: found := false
153新增: for _, path := range private {
154新增: found = found || path == original.InstanceDirectory
155新增: }
156新增: if !found {
157新增: t.Fatal("external retained disk lost private-data protection", private)
158新增: }
159新增: }
160新增: }
161新增: if !reflect.DeepEqual(broker.events, []string{"status", "begin", "attach", "commit", "status", "begin", "attach", "commit"}) {
162新增: t.Fatal(broker.events)
163新增: }
164新增: })
165新增: }
166新增:}
167新增:
168新增:func TestWindowsStorageAttachmentFailureRollsBackAndRetries(t *testing.T) {
169新增: profile, runtime, broker, original := windowsStorageFixture(t, false)
170新增: location, err := cage.GetStorageLocation(profile)
171新增: if err != nil {
172新增: t.Fatal(err)
173新增: }
174新增: target := filepath.Join(t.TempDir(), "destination")
175新增: broker.failAttach, broker.failRecovery = true, true
176新增: if _, err := cage.MoveStorageWithRuntime(context.Background(), profile, target, location, runtime, nil); err == nil {
177新增: t.Fatal("lost native response treated as success")
178新增: }
179新增: if _, err := os.Stat(broker.disk.Path); err != nil {
180新增: t.Fatal("unresolved native disk was removed", err)
181新增: }
182新增: if _, err := cage.GetStorageLocation(profile); !errors.Is(err, cage.ErrStorageRuntimeRecovery) {
183新增: t.Fatal("shared loader bypassed native recovery", err)
184新增: }
185新增: broker.failRecovery = false
186新增: if err := cage.RecoverStorage(context.Background(), profile, runtime); err != nil {
187新增: t.Fatal(err)
188新增: }
189新增: actual, err := LoadWindowsProfile(profile)
190新增: if err != nil || actual == nil || *actual != original {
191新增: t.Fatal("rollback changed original pairing", err)
192新增: }
193新增: if _, err := os.Stat(filepath.Join(target, "state")); !errors.Is(err, os.ErrNotExist) {
194新增: t.Fatal("resolved failed copy not removed", err)
195新增: }
196新增: broker.failAttach = false
197新增: if _, err := cage.MoveStorageWithRuntime(context.Background(), profile, target, location, runtime, nil); err != nil {
198新增: t.Fatal("retry failed", err)
199新增: }
200新增:}
201新增:
202新增:func TestWindowsStorageCannotUseFilesystemOnlyMove(t *testing.T) {
203新增: profile, _, _, _ := windowsStorageFixture(t, false)
204新增: location, err := cage.GetStorageLocation(profile)
205新增: if err != nil {
206新增: t.Fatal(err)
207新增: }
208新增: target := filepath.Join(t.TempDir(), "destination")
209新增: if _, err := cage.MoveStorage(context.Background(), profile, target, location, nil); err == nil {
210新增: t.Fatal("filesystem migration left registered VM bound to its old inode")
211新增: }
212新增: if _, err := os.Stat(target); !errors.Is(err, os.ErrNotExist) {
213新增: t.Fatal("rejected move touched destination", err)
214新增: }
215新增:}
216新增:
217新增:func TestWindowsStorageExternalMetadataIsOwnedByHyperV(t *testing.T) {
218新增: profile, runtime, broker, original := windowsStorageFixture(t, true)
219新增: metadata := filepath.Join(original.InstanceDirectory, "Virtual Machines")
220新增: if err := os.Mkdir(metadata, 0700); err != nil {
221新增: t.Fatal(err)
222新增: }
223新增: if err := os.WriteFile(filepath.Join(metadata, original.VMID.String()+".vmcx"), []byte("Hyper-V managed configuration"), 0600); err != nil {
224新增: t.Fatal(err)
225新增: }
226新增: if err := os.Chmod(metadata, 0000); err != nil {
227新增: t.Fatal(err)
228新增: }
229新增: t.Cleanup(func() { _ = os.Chmod(metadata, 0700) })
230新增: broker.layout = &windowsVMStorageLayout{Configuration: original.InstanceDirectory, Snapshots: original.InstanceDirectory, Paging: original.InstanceDirectory}
231新增: location, err := cage.GetStorageLocation(profile)
232新增: if err != nil {
233新增: t.Fatal(err)
234新增: }
235新增: if _, err := cage.MoveStorageWithRuntime(context.Background(), profile, filepath.Join(t.TempDir(), "target"), location, runtime, nil); err != nil {
236新增: t.Fatal("ordinary cold copy traversed native metadata", err)
237新增: }
238新增: next, err := LoadWindowsProfile(profile)
239新增: if err != nil {
240新增: t.Fatal(err)
241新增: }
242新增: if _, err := os.Stat(filepath.Join(next.InstanceDirectory, "Virtual Machines")); !errors.Is(err, os.ErrNotExist) {
243新增: t.Fatal("unregistered metadata duplicate copied into user storage", err)
244新增: }
245新增:}
修改internal/guestos/windows_storage_windows.go+4 −0看文件
@@ -18,6 +18,10 @@ func windowsHostStorage(ctx context.Context, id uuid.UUID, input windowsHostStor
1818 return state, err
1919}
2020
21新增:func WindowsPrivateStoragePaths() []string {
22新增: return []string{filepath.Join(managerKnownFolder(windows.FOLDERID_ProgramData), "Cage", "HyperVManager")}
23新增:}
24新增:
2125func replaceWindowsStorageProfile(path string, data []byte) error {
2226 file, err := os.CreateTemp(filepath.Dir(path), ".windows-storage-*")
2327 if err != nil {
新增internal/guestos/windows_storage_windows_test.go+173 −0看文件
@@ -0,0 +1,173 @@
1新增://go:build windows
2新增:
3新增:package guestos
4新增:
5新增:import (
6新增: "context"
7新增: "errors"
8新增: "net"
9新增: "os"
10新增: "path/filepath"
11新增: "testing"
12新增: "time"
13新增:
14新增: "github.com/Microsoft/go-winio"
15新增: "github.com/google/uuid"
16新增: "github.com/sylvinus/agent-vm/internal/cage"
17新增: "golang.org/x/sys/windows"
18新增:)
19新增:
20新增:func storagePipeFixture(t *testing.T, impersonation winio.PipeImpLevel, run func(net.Conn, string)) {
21新增: t.Helper()
22新增: user, err := windows.GetCurrentProcessToken().GetTokenUser()
23新增: if err != nil {
24新增: t.Fatal(err)
25新增: }
26新增: sid := user.User.Sid.String()
27新增: name := `\\.\pipe\Cage.StorageTest.` + uuid.NewString()
28新增: listener, err := winio.ListenPipe(name, &winio.PipeConfig{SecurityDescriptor: "D:P(A;;GA;;;" + sid + ")"})
29新增: if err != nil {
30新增: t.Fatal(err)
31新增: }
32新增: defer listener.Close()
33新增: done := make(chan struct{})
34新增: go func() {
35新增: defer close(done)
36新增: connection, err := listener.Accept()
37新增: if err != nil {
38新增: t.Error(err)
39新增: return
40新增: }
41新增: defer connection.Close()
42新增: var request [1]byte
43新增: if _, err := connection.Read(request[:]); err != nil {
44新增: t.Error(err)
45新增: return
46新增: }
47新增: run(connection, sid)
48新增: }()
49新增: ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
50新增: defer cancel()
51新增: client, err := winio.DialPipeAccessImpLevel(ctx, name, 0x120003, impersonation)
52新增: if err != nil {
53新增: t.Fatal(err)
54新增: }
55新增: defer client.Close()
56新增: if _, err := client.Write([]byte("x")); err != nil {
57新增: t.Fatal(err)
58新增: }
59新增: select {
60新增: case <-done:
61新增: case <-ctx.Done():
62新增: t.Fatal("private storage pipe test timed out")
63新增: }
64新增:}
65新增:
66新增:func TestWindowsStorageDestinationUsesCallerAccess(t *testing.T) {
67新增: root := t.TempDir()
68新增: path := filepath.Join(root, "system.vhdx")
69新增: if err := os.WriteFile(path, []byte("synthetic VHDX identity"), 0600); err != nil {
70新增: t.Fatal(err)
71新增: }
72新增: if err := protectWindowsProfile(path); err != nil {
73新增: t.Fatal(err)
74新增: }
75新增: storagePipeFixture(t, winio.PipeImpLevelImpersonation, func(connection net.Conn, sid string) {
76新增: handle, identity, err := managerOpenStorageDestination(connection, path, sid, false)
77新增: if err != nil {
78新增: t.Error(err)
79新增: return
80新增: }
81新增: defer windows.CloseHandle(handle)
82新增: volume, id, err := managerDiskIdentity(path)
83新增: if err != nil || identity.Volume != volume || identity.FileID != id {
84新增: t.Error("destination object identity changed", err)
85新增: }
86新增: if err := os.Rename(path, path+".replaced"); err == nil {
87新增: t.Error("verified disk was replaceable during privileged operation")
88新增: }
89新增: if _, _, err := managerOpenStorageDestination(connection, path, "S-1-5-21-1-2-3-999", false); err == nil {
90新增: t.Error("different user gained destination authority")
91新增: }
92新增: })
93新增: storagePipeFixture(t, winio.PipeImpLevelIdentification, func(connection net.Conn, sid string) {
94新增: if handle, _, err := managerOpenStorageDestination(connection, path, sid, false); err == nil {
95新增: windows.CloseHandle(handle)
96新增: t.Error("identity-only pipe was used for a privileged destination open")
97新增: }
98新增: })
99新增: user, err := windows.GetCurrentProcessToken().GetTokenUser()
100新增: if err != nil {
101新增: t.Fatal(err)
102新增: }
103新增: sd, err := windows.SecurityDescriptorFromString("D:P(D;;FW;;;" + user.User.Sid.String() + ")(A;;FR;;;" + user.User.Sid.String() + ")(A;;FA;;;SY)(A;;FA;;;BA)")
104新增: if err != nil {
105新增: t.Fatal(err)
106新增: }
107新增: acl, _, err := sd.DACL()
108新增: if err != nil {
109新增: t.Fatal(err)
110新增: }
111新增: if err := windows.SetNamedSecurityInfo(path, windows.SE_FILE_OBJECT, windows.DACL_SECURITY_INFORMATION|windows.PROTECTED_DACL_SECURITY_INFORMATION, nil, nil, acl, nil); err != nil {
112新增: t.Fatal(err)
113新增: }
114新增: t.Cleanup(func() { _ = protectWindowsProfile(path) })
115新增: storagePipeFixture(t, winio.PipeImpLevelImpersonation, func(connection net.Conn, sid string) {
116新增: if handle, _, err := managerOpenStorageDestination(connection, path, sid, false); err == nil {
117新增: windows.CloseHandle(handle)
118新增: t.Error("read-only caller selected a disk for privileged mutation")
119新增: }
120新增: })
121新增:}
122新增:
123新增:func TestWindowsStoragePinsDirectoryIdentity(t *testing.T) {
124新增: root := t.TempDir()
125新增: parent := filepath.Join(root, "parent")
126新增: if err := os.Mkdir(parent, 0700); err != nil {
127新增: t.Fatal(err)
128新增: }
129新增: path := filepath.Join(parent, "system.vhdx")
130新增: if err := os.WriteFile(path, []byte("disk"), 0600); err != nil {
131新增: t.Fatal(err)
132新增: }
133新增: closeParents, err := managerPinStorageParents(path)
134新增: if err != nil {
135新增: t.Fatal(err)
136新增: }
137新增: defer closeParents()
138新增: if err := os.Rename(parent, parent+"-renamed"); err == nil {
139新增: t.Fatal("ancestor could be replaced while VM storage paths were pinned")
140新增: }
141新增: closeParents()
142新增: if err := os.Rename(parent, parent+"-renamed"); err != nil {
143新增: t.Fatal("parent pin leaked after operation", err)
144新增: }
145新增:}
146新增:
147新增:func TestWindowsStorageCopiedPairingKeepsProtectedACL(t *testing.T) {
148新增: profile, runtime, _, _ := windowsStorageFixture(t, false)
149新增: before, err := cage.GetStorageLocation(profile)
150新增: if err != nil {
151新增: t.Fatal(err)
152新增: }
153新增: if _, err := cage.MoveStorageWithRuntime(context.Background(), profile, filepath.Join(t.TempDir(), "new"), before, runtime, nil); err != nil {
154新增: t.Fatal(err)
155新增: }
156新增: binding, err := LoadWindowsProfile(profile)
157新增: if err != nil {
158新增: t.Fatal(err)
159新增: }
160新增: for _, path := range []string{binding.PairingFile, binding.NetworkPairingFile} {
161新增: sd, err := windows.GetNamedSecurityInfo(path, windows.SE_FILE_OBJECT, windows.DACL_SECURITY_INFORMATION)
162新增: if err != nil {
163新增: t.Fatal(err)
164新增: }
165新增: control, _, err := sd.Control()
166新增: if err != nil || control&windows.SE_DACL_PROTECTED == 0 {
167新增: t.Fatal("copied pairing is rejected by production PrivateFile", path, err)
168新增: }
169新增: if _, err := os.Stat(path); errors.Is(err, os.ErrNotExist) {
170新增: t.Fatal("pairing disappeared after migration")
171新增: }
172新增: }
173新增:}
修改internal/maclogin/bridge.h+2 −0看文件
@@ -4,6 +4,8 @@ void cageLoginLoop(void *machine);
44void cageLoginStop(void);
55void cageLoginEnable(bool enabled);
66void *cageLoginImage(int *size);
7新增:void *cageLoginImageRegion(int x, int y, int width, int height, int *size);
78bool cageLoginClick(int x, int y);
89bool cageLoginScroll(int x, int y, int deltaX, int deltaY);
910bool cageLoginKey(int code, bool shift);
11新增:bool cageLoginSelectAll(void);
修改internal/maclogin/bridge_darwin.m+41 −0看文件
@@ -46,6 +46,30 @@ void *cageLoginImage(int *size) {
4646 });
4747 return copy;
4848}
49新增:void *cageLoginImageRegion(int x, int y, int width, int height, int *size) {
50新增: if (x < 0 || y < 0 || width <= 0 || height <= 0 || x + width > 1024 || y + height > 640) return NULL;
51新增: __block void *copy = NULL;
52新增: dispatch_sync(dispatch_get_main_queue(), ^{
53新增: @autoreleasepool {
54新增: NSData *frame = [loginView snapshotJPEG];
55新增: if (!frame.length) return;
56新增: NSBitmapImageRep *source = [NSBitmapImageRep imageRepWithData:frame];
57新增: if (!source.CGImage) return;
58新增: CGRect region = CGRectMake(x * source.pixelsWide / 1024.0, y * source.pixelsHigh / 640.0,
59新增: width * source.pixelsWide / 1024.0, height * source.pixelsHigh / 640.0);
60新增: CGImageRef cropped = CGImageCreateWithImageInRect(source.CGImage, region);
61新增: if (!cropped) return;
62新增: NSBitmapImageRep *output = [[NSBitmapImageRep alloc] initWithCGImage:cropped];
63新增: CGImageRelease(cropped);
64新增: NSData *image = [output representationUsingType:NSBitmapImageFileTypeJPEG properties:@{NSImageCompressionFactor:@0.92}];
65新增: if (image.length && image.length <= (4<<20)) {
66新增: copy = malloc(image.length);
67新增: if (copy) { memcpy(copy, image.bytes, image.length); *size = (int)image.length; }
68新增: }
69新增: }
70新增: });
71新增: return copy;
72新增:}
4973bool cageLoginClick(int x, int y) {
5074 __block BOOL ok = NO;
5175 dispatch_sync(dispatch_get_main_queue(), ^{ ok = [loginView clickAtX:x * scanWidth / 1024.0 y:y * scanHeight / 640.0]; });
@@ -74,6 +98,23 @@ bool cageLoginKey(int code, bool shift) {
7498 });
7599 return ok;
76100}
101新增:bool cageLoginSelectAll(void) {
102新增: __block BOOL ok = NO;
103新增: dispatch_sync(dispatch_get_main_queue(), ^{
104新增: if (!loginView) return;
105新增: NSEventModifierFlags command = NSEventModifierFlagCommand | NX_DEVICELCMDKEYMASK;
106新增: NSEvent *(^event)(NSEventType, int, NSEventModifierFlags) = ^NSEvent *(NSEventType kind, int key, NSEventModifierFlags flags) {
107新增: return [NSEvent keyEventWithType:kind location:NSZeroPoint modifierFlags:flags timestamp:NSProcessInfo.processInfo.systemUptime
108新增: windowNumber:0 context:nil characters:@"" charactersIgnoringModifiers:@"" isARepeat:NO keyCode:(unsigned short)key];
109新增: };
110新增: [loginView sendKey:event(NSEventTypeFlagsChanged,55,command)];
111新增: [loginView sendKey:event(NSEventTypeKeyDown,55,command)];
112新增: ok = [loginView sendKey:event(NSEventTypeKeyDown,0,command)] && [loginView sendKey:event(NSEventTypeKeyUp,0,command)];
113新增: [loginView sendKey:event(NSEventTypeKeyUp,55,0)];
114新增: [loginView sendKey:event(NSEventTypeFlagsChanged,55,0)];
115新增: });
116新增: return ok;
117新增:}
77118bool cageLoginScroll(int x, int y, int deltaX, int deltaY) {
78119 __block BOOL ok = NO;
79120 dispatch_sync(dispatch_get_main_queue(), ^{
新增internal/maclogin/guest_probe_darwin_arm64.go+48 −0看文件
@@ -0,0 +1,48 @@
1新增://go:build darwin && arm64 && cgo && !no_vz
2新增:
3新增:package maclogin
4新增:
5新增:import (
6新增: "context"
7新增: "os/exec"
8新增:
9新增: "al.essio.dev/pkg/shellescape"
10新增: "github.com/sylvinus/agent-vm/internal/guestos"
11新增:)
12新增:
13新增:// Read authorization state from the installed, root-owned executable. The
14新增:// ordinary GUI user's writable socket and shell startup files are not trusted
15新增:// to identify a destination for an administrator password.
16新增:func guestGUIProbeCommand(ctx context.Context, profile, administrator, user string, arguments ...string) (*exec.Cmd, error) {
17新增: args, err := guestos.MacOSSSHArgs(profile, administrator)
18新增: if err != nil {
19新增: return nil, err
20新增: }
21新增: rootScript := `set -eu
22新增:app='/Applications/Cage Guest Window.app'
23新增:for file in "$app" "$app/Contents" "$app/Contents/MacOS" "$app/Contents/MacOS/CageGuestWindow"; do
24新增: test ! -L "$file" && test "$(/usr/bin/stat -f %u "$file")" = 0 || exit 72
25新增: mode=$(/usr/bin/stat -f %Lp "$file")
26新增: test "$((0$mode & 022))" = 0 || exit 72
27新增:done
28新增:/usr/bin/codesign --verify --strict -R '=identifier "dev.cage.GuestClaudeWindow"' "$app" || exit 72
29新增:uid=$(/usr/bin/id -u ` + shellescape.Quote(user) + `)
30新增:test "$(/usr/bin/stat -f %u /dev/console)" = "$uid" || exit 73
31新增:exec /bin/launchctl asuser "$uid" /usr/bin/sudo -Hu ` + shellescape.Quote(user) + ` /usr/bin/env -i HOME=` + shellescape.Quote("/Users/"+user) + ` PATH=/usr/bin:/bin ` +
32新增: shellescape.QuoteCommand(append([]string{"/Applications/Cage Guest Window.app/Contents/MacOS/CageGuestWindow"}, arguments...))
33新增: // An askpass helper keeps SSH stdin available to the probe. Its private
34新增: // script contains only the existing credential's path, and is removed when
35新增: // this invocation ends. Credentials remain inside the guest.
36新增: loginScript := `set -eu
37新增:umask 077
38新增:probe_dir=$(/usr/bin/mktemp -d ` + shellescape.Quote("/Users/"+administrator+"/.cage-probe.XXXXXXXX") + `)
39新增:trap '/bin/rm -f "$probe_dir/askpass"; /bin/rmdir "$probe_dir"' EXIT
40新增:trap 'exit 1' HUP INT TERM
41新增:/usr/bin/printf '%s\n' '#!/bin/sh' ` + shellescape.Quote("exec /bin/cat "+shellescape.Quote("/Users/"+administrator+"/password")) + ` > "$probe_dir/askpass"
42新增:/bin/chmod 700 "$probe_dir/askpass"
43新增:SUDO_ASKPASS="$probe_dir/askpass" /usr/bin/sudo -A -p '' /bin/sh -c ` + shellescape.Quote(rootScript)
44新增: command := "exec /bin/sh -c " + shellescape.Quote(loginScript)
45新增: cmd := exec.CommandContext(ctx, "/usr/bin/ssh", append(args, "-T", "cage-macos", "--", command)...)
46新增: cmd.Env = []string{"PATH=/usr/bin:/bin", "LC_ALL=C"}
47新增: return cmd, nil
48新增:}
修改internal/maclogin/login_darwin_arm64.go+45 −39看文件
@@ -58,14 +58,26 @@ type request = guestos.MacLoginRequest
5858type reply = guestos.MacLoginReply
5959
6060type loginSession struct {
61删除: profile string
62删除: token string
63删除: expires time.Time
64删除: screenID string
65删除: setup bool
61新增: profile string
62新增: token string
63新增: expires time.Time
64新增: screenID string
65新增: setup bool
66新增: maintenance string
67新增: maintenanceFrame string
68新增: maintenanceMachineID string
69新增: maintenanceAdministrator string
70新增: passwordSelection passwordSelection
6671}
6772
6873func (s *loginSession) currentScreen() string {
74新增: if s.maintenance != "" {
75新增: surface, err := s.maintenanceProbe(false)
76新增: if err != nil {
77新增: return ""
78新增: }
79新增: return "maintenance-" + surface.Session
80新增: }
6981 // Check via the separate provisioning account. Guest development files
7082 // and the standard user's shell initialization cannot grant this view.
7183 bound, err := guestos.LoadMacOSProfile(s.profile)
@@ -78,7 +90,11 @@ func (s *loginSession) currentScreen() string {
7890 }
7991 return "setup-" + bound.SetupID
8092 }
81删除: args, err := guestos.MacOSSSHArgs(s.profile, "cage")
93新增: user, err := guestos.MacOSProvisionUser(s.profile)
94新增: if err != nil {
95新增: return ""
96新增: }
97新增: args, err := guestos.MacOSSSHArgs(s.profile, user)
8298 if err != nil {
8399 return ""
84100 }
@@ -114,9 +130,17 @@ func (s *loginSession) close() {
114130 s.token = ""
115131 s.screenID = ""
116132 s.setup = false
133新增: s.maintenance = ""
134新增: s.maintenanceFrame = ""
135新增: s.maintenanceMachineID = ""
136新增: s.maintenanceAdministrator = ""
137新增: s.passwordSelection = passwordSelection{}
117138}
118139
119140func (s *loginSession) handle(in request) reply {
141新增: if in.Maintenance != "" || (s.maintenance != "" && in.Action != "open") {
142新增: return s.handleMaintenance(in)
143新增: }
120144 if in.Action == "finish" && in.Setup {
121145 bound, err := guestos.LoadMacOSProfile(s.profile)
122146 if err != nil || bound == nil || bound.SetupID == "" {
@@ -152,14 +176,8 @@ func (s *loginSession) handle(in request) reply {
152176 }
153177 switch in.Action {
154178 case "fill-password":
155删除: sequence, valid := passwordKeys(in.Password)
156删除: if !s.setup || !valid || !s.authorizationDialog() {
157删除: return reply{Error: "请先打开系统授权对话框,并选中密码输入框"}
158删除: }
159删除: for _, key := range sequence {
160删除: if !bool(C.cageLoginKey(C.int(key.code), C.bool(key.shift))) {
161删除: return reply{Error: "授权密码未能填写,请重试"}
162删除: }
179新增: if err := s.fillSetupPassword(in.Password); err != nil {
180新增: return reply{Error: err.Error()}
163181 }
164182 case "frame":
165183 var n C.int
@@ -174,20 +192,22 @@ func (s *loginSession) handle(in request) reply {
174192 }
175193 return reply{Image: C.GoBytes(p, n), MIME: "image/jpeg"}
176194 case "click":
195新增: s.passwordSelection = passwordSelection{}
177196 if in.X < 0 || in.Y < 0 || in.X >= 1024 || in.Y >= 640 || !bool(C.cageLoginClick(C.int(in.X), C.int(in.Y))) {
178197 return reply{Error: "无效的登录位置"}
179198 }
199新增: if s.setup {
200新增: s.selectPasswordPosition(in.X, in.Y)
201新增: }
180202 case "key":
203新增: s.passwordSelection = passwordSelection{}
181204 // ANSI printable keys, Return, Tab, Escape and Backspace. No global shortcuts.
182205 setupNavigation := s.setup && (in.Code >= 123 && in.Code <= 126 || in.Code == 116 || in.Code == 121)
183206 if in.Code < 0 || (in.Code > 53 && !setupNavigation) || !bool(C.cageLoginKey(C.int(in.Code), C.bool(in.Shift))) {
184207 return reply{Error: "不支持此登录按键"}
185208 }
186删除: if in.Code == 36 && !s.setup {
187删除: s.close()
188删除: return reply{Closed: true}
189删除: }
190209 case "scroll":
210新增: s.passwordSelection = passwordSelection{}
191211 if !s.setup || in.X < 0 || in.Y < 0 || in.X >= 1024 || in.Y >= 640 ||
192212 in.DeltaX < -512 || in.DeltaX > 512 || in.DeltaY < -512 || in.DeltaY > 512 ||
193213 !bool(C.cageLoginScroll(C.int(in.X), C.int(in.Y), C.int(in.DeltaX), C.int(in.DeltaY))) {
@@ -199,26 +219,6 @@ func (s *loginSession) handle(in request) reply {
199219 return reply{}
200220}
201221
202删除:func (s *loginSession) authorizationDialog() bool {
203删除: ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
204删除: defer cancel()
205删除: bound, err := guestos.LoadMacOSProfile(s.profile)
206删除: if err != nil || bound == nil {
207删除: return false
208删除: }
209删除: args, err := guestos.MacOSSSHArgs(s.profile, bound.User)
210删除: if err != nil {
211删除: return false
212删除: }
213删除: cmd := exec.CommandContext(ctx, "/usr/bin/ssh", append(args, "-T", "cage-macos", "--", `printf '%s\n' '{"action":"setup-password-focus"}' | /usr/bin/nc -U "$HOME/Library/Caches/dev.cage.GuestClaudeWindow/window.sock"`)...)
214删除: cmd.Env = []string{"PATH=/usr/bin:/bin", "LC_ALL=C"}
215删除: data, err := cmd.Output()
216删除: var result struct {
217删除: Focused bool `json:"focused"`
218删除: }
219删除: return err == nil && json.Unmarshal(data, &result) == nil && result.Focused
220删除:}
221删除:
222222func run(ctx context.Context, machine *apple.VirtualMachine, dir string) error {
223223 if !driver.OwnsOffscreenView(dir) {
224224 return errors.New("invalid local macOS login view")
@@ -264,7 +264,13 @@ func run(ctx context.Context, machine *apple.VirtualMachine, dir string) error {
264264 _ = conn.SetDeadline(time.Now().Add(10 * time.Second))
265265 var input request
266266 if json.NewDecoder(io.LimitReader(conn, 4096)).Decode(&input) == nil {
267删除: _ = json.NewEncoder(conn).Encode(s.handle(input))
267新增: if input.Maintenance != "" {
268新增: _ = conn.SetDeadline(time.Now().Add(15 * time.Second))
269新增: }
270新增: result := s.handle(input)
271新增: if err := json.NewEncoder(conn).Encode(result); err != nil && result.Session != "" {
272新增: s.close()
273新增: }
268274 }
269275 _ = conn.Close()
270276 }
新增internal/maclogin/maintenance.go+81 −0看文件
@@ -0,0 +1,81 @@
1新增:package maclogin
2新增:
3新增:import (
4新增: "crypto/sha256"
5新增: "encoding/hex"
6新增: "encoding/json"
7新增: "math"
8新增: "time"
9新增:
10新增: "github.com/google/uuid"
11新增:)
12新增:
13新增:type maintenanceWindow struct {
14新增: Version int `json:"version"`
15新增: Session string `json:"session"`
16新增: User string `json:"user"`
17新增: PID int32 `json:"pid"`
18新增: Window uint32 `json:"window"`
19新增: Bundle string `json:"bundle"`
20新增: Rect [4]float64 `json:"rect"`
21新增: Display [4]float64 `json:"display"`
22新增: Error string `json:"error"`
23新增: PasswordFocused bool `json:"password_focused"`
24新增:}
25新增:
26新增:func (w maintenanceWindow) valid(user string) bool {
27新增: if w.Version != 1 || w.Error != "" || w.User != user || w.PID <= 0 || w.Window == 0 ||
28新增: (w.Bundle != "com.apple.systempreferences" && w.Bundle != "com.apple.authorizationhost") {
29新增: return false
30新增: }
31新增: id, err := uuid.Parse(w.Session)
32新增: if err != nil || id == uuid.Nil {
33新增: return false
34新增: }
35新增: for _, value := range append(w.Rect[:], w.Display[:]...) {
36新增: if math.IsNaN(value) || math.IsInf(value, 0) || math.Abs(value) > 32768 {
37新增: return false
38新增: }
39新增: }
40新增: return w.Display[2] > 0 && w.Display[3] > 0 && math.Abs(w.Display[2]/w.Display[3]-1.6) < 0.001 && w.Rect[2] >= 80 && w.Rect[3] >= 40 &&
41新增: w.Rect[0] >= w.Display[0] && w.Rect[1] >= w.Display[1] &&
42新增: w.Rect[0]+w.Rect[2] <= w.Display[0]+w.Display[2] && w.Rect[1]+w.Rect[3] <= w.Display[1]+w.Display[3]
43新增:}
44新增:
45新增:func (w maintenanceWindow) geometry() string {
46新增: w.PasswordFocused = false
47新增: data, _ := json.Marshal(w)
48新增: digest := sha256.Sum256(data)
49新增: return hex.EncodeToString(digest[:16])
50新增:}
51新增:
52新增:// Round inward so the image and accepted coordinates remain inside the window.
53新增:func (w maintenanceWindow) region() [4]int {
54新增: x := int(math.Ceil((w.Rect[0] - w.Display[0]) / w.Display[2] * 1024))
55新增: y := int(math.Ceil((w.Rect[1] - w.Display[1]) / w.Display[3] * 640))
56新增: right := int(math.Floor((w.Rect[0] + w.Rect[2] - w.Display[0]) / w.Display[2] * 1024))
57新增: bottom := int(math.Floor((w.Rect[1] + w.Rect[3] - w.Display[1]) / w.Display[3] * 640))
58新增: return [4]int{x, y, right - x, bottom - y}
59新增:}
60新增:
61新增:func (w maintenanceWindow) contains(x, y int) bool {
62新增: r := w.region()
63新增: return x >= r[0] && y >= r[1] && x < r[0]+r[2] && y < r[1]+r[3]
64新增:}
65新增:
66新增:func (selection *passwordSelection) selectMaintenance(window maintenanceWindow, target passwordTarget, user string, x, y int, now time.Time) {
67新增: *selection = passwordSelection{}
68新增: if target.valid(user) && target.SelectionRequired && window.geometry() == target.geometry() && target.contains(x, y) {
69新增: *selection = passwordSelection{Geometry: target.geometry(), X: x, Y: y, Clicked: now}
70新增: }
71新增:}
72新增:
73新增:func (selection *passwordSelection) consumeMaintenance(window maintenanceWindow, target passwordTarget, user string, now time.Time) (passwordSelection, bool) {
74新增: selected := *selection
75新增: *selection = passwordSelection{}
76新增: return selected, window.permitsPassword(target, selected, user, now)
77新增:}
78新增:
79新增:func (window maintenanceWindow) permitsPassword(target passwordTarget, selection passwordSelection, user string, now time.Time) bool {
80新增: return window.geometry() == target.geometry() && selection.permits(target, user, now)
81新增:}
新增internal/maclogin/maintenance_darwin_arm64.go+341 −0看文件
@@ -0,0 +1,341 @@
1新增://go:build darwin && arm64 && cgo && !no_vz
2新增:
3新增:package maclogin
4新增:
5新增:/*
6新增:#include "bridge.h"
7新增:*/
8新增:import "C"
9新增:
10新增:import (
11新增: "bufio"
12新增: "bytes"
13新增: "context"
14新增: "crypto/rand"
15新增: "crypto/subtle"
16新增: "encoding/json"
17新增: "errors"
18新增: "io"
19新增: "os/exec"
20新增: "strings"
21新增: "time"
22新增:
23新增: "al.essio.dev/pkg/shellescape"
24新增: "github.com/sylvinus/agent-vm/internal/guestos"
25新增:)
26新增:
27新增:func (s *loginSession) maintenanceCommand(ctx context.Context, operation string) (*exec.Cmd, string, error) {
28新增: open := operation == "--maintenance-open"
29新增: if !guestos.ValidMacMaintenancePurpose(s.maintenance) {
30新增: return nil, "", errors.New("维护用途无效")
31新增: }
32新增: bound, err := guestos.LoadMacOSProfile(s.profile)
33新增: if err != nil || bound == nil || bound.SetupID != "" {
34新增: return nil, "", errors.New("请先完成虚拟 Mac 的首次设置")
35新增: }
36新增: if open {
37新增: s.maintenanceMachineID = bound.MachineID
38新增: } else if s.maintenanceMachineID != bound.MachineID {
39新增: return nil, "", errors.New("虚拟 Mac 身份已变化,请重新打开维护画面")
40新增: }
41新增: user, err := guestos.MacOSProvisionUser(s.profile)
42新增: if err != nil {
43新增: return nil, "", err
44新增: }
45新增: if open {
46新增: s.maintenanceAdministrator = user
47新增: } else if s.maintenanceAdministrator != user {
48新增: return nil, "", errors.New("客机安装身份已变化,请重新打开维护画面")
49新增: }
50新增: cmd, err := guestGUIProbeCommand(ctx, s.profile, user, bound.User, operation, s.maintenance)
51新增: return cmd, bound.User, err
52新增:}
53新增:
54新增:func (s *loginSession) maintenanceProbe(open bool) (maintenanceWindow, error) {
55新增: var result maintenanceWindow
56新增: operation := "--maintenance-probe"
57新增: if open {
58新增: operation = "--maintenance-open"
59新增: }
60新增: ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second)
61新增: defer cancel()
62新增: cmd, user, err := s.maintenanceCommand(ctx, operation)
63新增: if err != nil {
64新增: return result, err
65新增: }
66新增: pipe, err := cmd.StdoutPipe()
67新增: if err != nil || cmd.Start() != nil {
68新增: result.Error = "component_update_required"
69新增: return result, errors.New("客机维护组件尚未连接,请更新环境组件后重试")
70新增: }
71新增: data, readErr := io.ReadAll(io.LimitReader(pipe, 8193))
72新增: if readErr != nil || len(data) > 8192 {
73新增: cancel()
74新增: }
75新增: if err = cmd.Wait(); err != nil {
76新增: var exit *exec.ExitError
77新增: if errors.As(err, &exit) && exit.ExitCode() == 73 {
78新增: result.Error = "requires_gui_login"
79新增: return result, errors.New("请先登录并解锁虚拟 Mac 的客机账户")
80新增: }
81新增: result.Error = "component_update_required"
82新增: return result, errors.New("客机维护组件需要更新,请在环境设置中更新组件")
83新增: }
84新增: if readErr != nil || len(data) > 8192 || json.Unmarshal(data, &result) != nil {
85新增: result.Error = "component_update_required"
86新增: return result, errors.New("客机维护组件需要更新,请在环境设置中更新组件")
87新增: }
88新增: if result.Error != "" {
89新增: message := "请保持系统设置或系统授权窗口位于客机前台,再重新打开维护画面"
90新增: if result.Error == "requires_gui_login" {
91新增: message = "请先登录并解锁虚拟 Mac 的客机账户"
92新增: } else if strings.Contains(result.Error, "obscured") {
93新增: message = "授权窗口被其他窗口遮挡,请关闭遮挡窗口后重新打开维护画面"
94新增: }
95新增: return result, errors.New(message)
96新增: }
97新增: if !open && !result.valid(user) {
98新增: return result, errors.New("客机授权窗口身份无法确认,请重新打开维护画面")
99新增: }
100新增: return result, nil
101新增:}
102新增:
103新增:func maintenanceFailure(surface maintenanceWindow, err error, closed bool) reply {
104新增: result := reply{Closed: closed, Error: err.Error()}
105新增: if surface.Error == "component_update_required" {
106新增: result.Recovery = "environment-update"
107新增: } else if surface.Error == "requires_gui_login" {
108新增: result.Recovery = "guest-login"
109新增: }
110新增: return result
111新增:}
112新增:
113新增:func (s *loginSession) handleMaintenance(in request) (result reply) {
114新增: defer func() { result.MaintenanceVersion = 1 }()
115新增: if in.Setup || !guestos.ValidMacMaintenancePurpose(in.Maintenance) || len(in.Geometry) > 64 {
116新增: return reply{Closed: true, Error: "维护用途无效"}
117新增: }
118新增: if in.Action == "open" {
119新增: s.close()
120新增: s.maintenance = in.Maintenance
121新增: surface, err := s.maintenanceProbe(true)
122新增: if err != nil {
123新增: s.close()
124新增: return maintenanceFailure(surface, err, true)
125新增: }
126新增: deadline := time.Now().Add(3 * time.Second)
127新增: for {
128新增: surface, err = s.maintenanceProbe(false)
129新增: if err == nil || time.Now().After(deadline) {
130新增: break
131新增: }
132新增: time.Sleep(100 * time.Millisecond)
133新增: }
134新增: if err != nil {
135新增: s.close()
136新增: return maintenanceFailure(surface, err, true)
137新增: }
138新增: s.token, s.screenID = rand.Text(), "maintenance-"+surface.Session
139新增: s.expires = time.Now().Add(5 * time.Minute)
140新增: C.cageLoginEnable(true)
141新增: return reply{Session: s.token, Administrator: s.maintenanceAdministrator}
142新增: }
143新增: if s.token == "" || s.maintenance != in.Maintenance || subtle.ConstantTimeCompare([]byte(in.Session), []byte(s.token)) != 1 {
144新增: return reply{Closed: true}
145新增: }
146新增: if in.Action == "close" || time.Now().After(s.expires) {
147新增: s.close()
148新增: return reply{Closed: true}
149新增: }
150新增: surface, err := s.maintenanceProbe(false)
151新增: if err != nil || s.screenID != "maintenance-"+surface.Session {
152新增: s.close()
153新增: if err == nil {
154新增: err = errors.New("客机登录会话已变化,请重新打开维护画面")
155新增: }
156新增: return maintenanceFailure(surface, err, true)
157新增: }
158新增: if in.Action == "frame" {
159新增: region := surface.region()
160新增: var size C.int
161新增: data := C.cageLoginImageRegion(C.int(region[0]), C.int(region[1]), C.int(region[2]), C.int(region[3]), &size)
162新增: if data == nil {
163新增: return reply{Error: "正在等待系统设置窗口画面"}
164新增: }
165新增: defer C.free(data)
166新增: after, err := s.maintenanceProbe(false)
167新增: if err != nil {
168新增: s.close()
169新增: return maintenanceFailure(after, err, true)
170新增: }
171新增: if after != surface {
172新增: return reply{Error: "授权窗口已变化,正在刷新画面"}
173新增: }
174新增: s.maintenanceFrame = surface.geometry()
175新增: return reply{Image: C.GoBytes(data, size), MIME: "image/jpeg", Geometry: s.maintenanceFrame, Region: region[:]}
176新增: }
177新增: if in.Geometry == "" || in.Geometry != s.maintenanceFrame || in.Geometry != surface.geometry() {
178新增: return reply{Error: "授权窗口已变化,请等待新画面后重试"}
179新增: }
180新增: switch in.Action {
181新增: case "fill-password":
182新增: if err := s.fillMaintenancePassword(surface); err != nil {
183新增: return reply{Closed: s.token == "", Error: err.Error()}
184新增: }
185新增: case "select-all":
186新增: s.passwordSelection = passwordSelection{}
187新增: if !bool(C.cageLoginSelectAll()) {
188新增: return reply{Error: "授权窗口尚未准备好"}
189新增: }
190新增: case "click":
191新增: s.passwordSelection = passwordSelection{}
192新增: if !surface.contains(in.X, in.Y) || !bool(C.cageLoginClick(C.int(in.X), C.int(in.Y))) {
193新增: return reply{Error: "点击位置超出当前授权窗口"}
194新增: }
195新增: if probe, err := s.openMaintenancePasswordProbe(); err == nil {
196新增: target, err := probe.target()
197新增: if err == nil {
198新增: s.passwordSelection.selectMaintenance(surface, target, probe.user, in.X, in.Y, time.Now())
199新增: }
200新增: probe.close()
201新增: }
202新增: case "key":
203新增: s.passwordSelection = passwordSelection{}
204新增: navigation := in.Code >= 123 && in.Code <= 126 || in.Code == 116 || in.Code == 121
205新增: if in.Code < 0 || (in.Code > 53 && !navigation) || !bool(C.cageLoginKey(C.int(in.Code), C.bool(in.Shift))) {
206新增: return reply{Error: "此按键不能用于授权窗口"}
207新增: }
208新增: case "scroll":
209新增: s.passwordSelection = passwordSelection{}
210新增: if !surface.contains(in.X, in.Y) || in.DeltaX < -512 || in.DeltaX > 512 || in.DeltaY < -512 || in.DeltaY > 512 ||
211新增: !bool(C.cageLoginScroll(C.int(in.X), C.int(in.Y), C.int(in.DeltaX), C.int(in.DeltaY))) {
212新增: return reply{Error: "滚动位置超出当前授权窗口"}
213新增: }
214新增: default:
215新增: return reply{Error: "维护操作无效"}
216新增: }
217新增: return reply{}
218新增:}
219新增:
220新增:func (s *loginSession) openMaintenancePasswordProbe() (*passwordProbe, error) {
221新增: ctx, cancel := context.WithTimeout(context.Background(), 7*time.Second)
222新增: command, user, err := s.maintenanceCommand(ctx, "--maintenance-password-probe")
223新增: if err != nil {
224新增: cancel()
225新增: return nil, err
226新增: }
227新增: input, err := command.StdinPipe()
228新增: if err != nil {
229新增: cancel()
230新增: return nil, err
231新增: }
232新增: output, err := command.StdoutPipe()
233新增: if err != nil {
234新增: input.Close()
235新增: cancel()
236新增: return nil, err
237新增: }
238新增: if err = command.Start(); err != nil {
239新增: input.Close()
240新增: output.Close()
241新增: cancel()
242新增: return nil, err
243新增: }
244新增: scanner := bufio.NewScanner(output)
245新增: scanner.Buffer(make([]byte, 4096), 32<<10)
246新增: return &passwordProbe{command: command, input: input, output: output, scanner: scanner, cancel: cancel, user: user}, nil
247新增:}
248新增:
249新增:func (s *loginSession) fillMaintenancePassword(window maintenanceWindow) error {
250新增: selected := s.passwordSelection
251新增: s.passwordSelection = passwordSelection{}
252新增: probe, err := s.openMaintenancePasswordProbe()
253新增: if err != nil {
254新增: return err
255新增: }
256新增: defer probe.close()
257新增: target, err := probe.target()
258新增: if err != nil {
259新增: return err
260新增: }
261新增: selection, permitted := selected.consumeMaintenance(window, target, probe.user, time.Now())
262新增: if !permitted {
263新增: return errors.New("请先选中系统授权窗口的密码框,再点击填写管理员密码")
264新增: }
265新增: password, err := s.maintenancePassword()
266新增: if err != nil {
267新增: return err
268新增: }
269新增: defer func() { clear(password) }()
270新增: sequence, valid := passwordKeys(string(bytes.TrimRight(password, "\r\n")))
271新增: if !valid {
272新增: return errors.New("安装管理员凭据格式无效,请检查安装记录")
273新增: }
274新增: check := func() error {
275新增: current, err := probe.target()
276新增: if err != nil {
277新增: return err
278新增: }
279新增: if time.Now().After(s.expires) || s.screenID != "maintenance-"+current.Session {
280新增: s.close()
281新增: return errors.New("客机授权会话已结束,请重新打开维护画面")
282新增: }
283新增: if !window.permitsPassword(current, selection, probe.user, time.Now()) {
284新增: return errors.New("系统授权窗口或密码框已变化,填写已停止,请重新选中密码框")
285新增: }
286新增: return nil
287新增: }
288新增: if err = check(); err != nil {
289新增: return err
290新增: }
291新增: if !target.Accessibility && !bool(C.cageLoginClick(C.int(selection.X), C.int(selection.Y))) {
292新增: return errors.New("所选密码框已变化,请重新点选")
293新增: }
294新增: if err = check(); err != nil {
295新增: return err
296新增: }
297新增: if !bool(C.cageLoginSelectAll()) {
298新增: return errors.New("系统密码框尚未准备好,请重试")
299新增: }
300新增: for _, key := range sequence {
301新增: if err = check(); err != nil {
302新增: return err
303新增: }
304新增: if !bool(C.cageLoginKey(C.int(key.code), C.bool(key.shift))) {
305新增: return errors.New("管理员密码未能填写,请重新选中密码框后重试")
306新增: }
307新增: }
308新增: return nil
309新增:}
310新增:
311新增:func (s *loginSession) maintenancePassword() ([]byte, error) {
312新增: user, err := guestos.MacOSProvisionUser(s.profile)
313新增: if err != nil || user != s.maintenanceAdministrator {
314新增: return nil, errors.New("客机安装身份已变化,请重新打开维护画面")
315新增: }
316新增: args, err := guestos.MacOSSSHArgs(s.profile, user)
317新增: if err != nil {
318新增: return nil, err
319新增: }
320新增: script := `set -eu; p=` + shellescape.Quote("/Users/"+user+"/password") + `
321新增:test ! -L "$p" && test "$(/usr/bin/stat -f %u "$p")" = "$(/usr/bin/id -u)"
322新增:mode=$(/usr/bin/stat -f %Lp "$p"); test "$((0$mode & 077))" = 0
323新增:exec /bin/cat "$p"`
324新增: ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
325新增: defer cancel()
326新增: cmd := exec.CommandContext(ctx, "/usr/bin/ssh", append(args, "-T", "cage-macos", "--", "exec /bin/sh -c "+shellescape.Quote(script))...)
327新增: cmd.Env = []string{"PATH=/usr/bin:/bin", "LC_ALL=C"}
328新增: pipe, err := cmd.StdoutPipe()
329新增: if err != nil || cmd.Start() != nil {
330新增: return nil, errors.New("安装管理员凭据暂时不可用")
331新增: }
332新增: data, readErr := io.ReadAll(io.LimitReader(pipe, 1025))
333新增: if readErr != nil || len(data) > 1024 {
334新增: cancel()
335新增: }
336新增: if err = cmd.Wait(); err != nil || readErr != nil || len(data) == 0 || len(data) > 1024 {
337新增: clear(data)
338新增: return nil, errors.New("安装管理员凭据不可用,请核对安装记录")
339新增: }
340新增: return data, nil
341新增:}
新增internal/maclogin/maintenance_test.go+128 −0看文件
@@ -0,0 +1,128 @@
1新增:package maclogin
2新增:
3新增:import (
4新增: "math"
5新增: "testing"
6新增: "time"
7新增:)
8新增:
9新增:func maintenanceFixture() maintenanceWindow {
10新增: return maintenanceWindow{Version: 1, Session: "607bceb6-c53f-4253-bad4-9c22b4ae7325", User: "trial", PID: 42, Window: 7,
11新增: Bundle: "com.apple.systempreferences", Rect: [4]float64{300, 150, 1200, 900}, Display: [4]float64{0, 0, 1920, 1200}}
12新增:}
13新增:
14新增:func TestMaintenanceWindowRequiresBoundIdentityAndVisibleRegion(t *testing.T) {
15新增: valid := maintenanceFixture()
16新增: if !valid.valid("trial") || valid.region() != [4]int{160, 80, 640, 480} {
17新增: t.Fatal("verified settings window was rejected")
18新增: }
19新增: for _, change := range []func(*maintenanceWindow){
20新增: func(w *maintenanceWindow) { w.User = "another-user" },
21新增: func(w *maintenanceWindow) { w.Version = 0 },
22新增: func(w *maintenanceWindow) { w.PID = 0 },
23新增: func(w *maintenanceWindow) { w.Window = 0 },
24新增: func(w *maintenanceWindow) { w.Bundle = "com.apple.finder" },
25新增: func(w *maintenanceWindow) { w.Bundle = "com.example.authorizationhost" },
26新增: func(w *maintenanceWindow) { w.Session = "" },
27新增: func(w *maintenanceWindow) { w.Error = "requires_gui_login" },
28新增: func(w *maintenanceWindow) { w.Error = "maintenance_window_obscured" },
29新增: func(w *maintenanceWindow) { w.Rect[0] = -1 },
30新增: func(w *maintenanceWindow) { w.Rect[2] = 80_000 },
31新增: func(w *maintenanceWindow) { w.Rect[3] = math.NaN() },
32新增: func(w *maintenanceWindow) { w.Display[2] = math.Inf(1) },
33新增: func(w *maintenanceWindow) { w.Display[3] = 1080 },
34新增: } {
35新增: invalid := valid
36新增: change(&invalid)
37新增: if invalid.valid("trial") {
38新增: t.Fatalf("accepted unverified maintenance target: %+v", invalid)
39新增: }
40新增: }
41新增: if !valid.contains(160, 80) || !valid.contains(799, 559) || valid.contains(159, 80) || valid.contains(800, 559) || valid.contains(160, 560) {
42新增: t.Fatal("maintenance input escaped the shown crop")
43新增: }
44新增:}
45新增:
46新增:func TestMaintenanceGeometryChangesWithWindowAndSession(t *testing.T) {
47新增: first := maintenanceFixture()
48新增: focused := first
49新增: focused.PasswordFocused = true
50新增: if focused.geometry() != first.geometry() {
51新增: t.Fatal("a click that focuses a field invalidated ordinary typing")
52新增: }
53新增: for _, change := range []func(*maintenanceWindow){
54新增: func(w *maintenanceWindow) { w.Window++ },
55新增: func(w *maintenanceWindow) { w.PID++ },
56新增: func(w *maintenanceWindow) { w.Rect[0]++ },
57新增: func(w *maintenanceWindow) { w.Session = "1e128373-fcb9-42fd-88b2-2a6ca58cf3a1" },
58新增: } {
59新增: next := first
60新增: change(&next)
61新增: if next.geometry() == first.geometry() {
62新增: t.Fatal("stale window input retained its authorization")
63新增: }
64新增: }
65新增:}
66新增:
67新增:func TestMaintenancePasswordSelectionWorksOnceBeforeAccessibility(t *testing.T) {
68新增: now := time.Now()
69新增: window := maintenanceFixture()
70新增: target := passwordTarget{maintenanceWindow: window, SelectionRequired: true}
71新增: var selection passwordSelection
72新增: if _, allowed := selection.consumeMaintenance(window, target, "trial", now); allowed {
73新增: t.Fatal("maintenance password accepted without the user's selection")
74新增: }
75新增: selection.selectMaintenance(window, target, "trial", 200, 200, now)
76新增: chosen, allowed := selection.consumeMaintenance(window, target, "trial", now.Add(time.Second))
77新增: if !allowed || !window.permitsPassword(target, chosen, "trial", now.Add(2*time.Second)) {
78新增: t.Fatal("AX-disabled maintenance could not use the selected Apple authorization panel")
79新增: }
80新增: if _, allowed := selection.consumeMaintenance(window, target, "trial", now.Add(2*time.Second)); allowed {
81新增: t.Fatal("the same manual password selection was consumed twice")
82新增: }
83新增: if window.permitsPassword(target, chosen, "trial", now.Add(31*time.Second)) {
84新增: t.Fatal("expired manual selection remained valid during password entry")
85新增: }
86新增:}
87新增:
88新增:func TestMaintenancePasswordRejectsChangedPanelAndSecureFocus(t *testing.T) {
89新增: now := time.Now()
90新增: window := maintenanceFixture()
91新增: target := passwordTarget{maintenanceWindow: window, SelectionRequired: true}
92新增: var selection passwordSelection
93新增: selection.selectMaintenance(window, target, "trial", 200, 200, now)
94新增: chosen, allowed := selection.consumeMaintenance(window, target, "trial", now)
95新增: if !allowed {
96新增: t.Fatal("could not establish the manual selection fixture")
97新增: }
98新增: for _, change := range []func(*passwordTarget){
99新增: func(w *passwordTarget) { w.SelectionRequired = false },
100新增: func(w *passwordTarget) { w.Window++ },
101新增: func(w *passwordTarget) { w.PID++ },
102新增: func(w *passwordTarget) { w.Rect[0]++ },
103新增: func(w *passwordTarget) { w.Session = "1e128373-fcb9-42fd-88b2-2a6ca58cf3a1" },
104新增: func(w *passwordTarget) { w.User = "another-user" },
105新增: func(w *passwordTarget) { w.Bundle = "com.apple.finder" },
106新增: func(w *passwordTarget) { w.Accessibility = true },
107新增: } {
108新增: changed := target
109新增: change(&changed)
110新增: if window.permitsPassword(changed, chosen, "trial", now.Add(time.Second)) {
111新增: t.Fatal("a changed panel, session or known non-password focus accepted password input")
112新增: }
113新增: }
114新增: ordinary := target
115新增: ordinary.SelectionRequired = false
116新增: selection.selectMaintenance(window, ordinary, "trial", 200, 200, now)
117新增: if _, allowed := selection.consumeMaintenance(window, ordinary, "trial", now); allowed {
118新增: t.Fatal("an ordinary System Settings window accepted manual password selection")
119新增: }
120新增: selection.selectMaintenance(window, target, "trial", 159, 80, now)
121新增: if _, allowed := selection.consumeMaintenance(window, target, "trial", now); allowed {
122新增: t.Fatal("a click outside the published window accepted password entry")
123新增: }
124新增: target.Accessibility, target.PasswordFocused = true, true
125新增: if _, allowed := selection.consumeMaintenance(window, target, "trial", now); !allowed {
126新增: t.Fatal("verified secure focus required an unnecessary manual selection")
127新增: }
128新增:}
新增internal/maclogin/maintenance_transport_darwin_arm64_test.go+41 −0看文件
@@ -0,0 +1,41 @@
1新增://go:build darwin && arm64 && cgo && !no_vz
2新增:
3新增:package maclogin
4新增:
5新增:import (
6新增: "bufio"
7新增: "bytes"
8新增: "encoding/json"
9新增: "testing"
10新增:)
11新增:
12新增:type passwordProbeInput struct{ bytes.Buffer }
13新增:
14新增:func (*passwordProbeInput) Close() error { return nil }
15新增:
16新增:func TestMaintenancePasswordProbeUsesFixedPrivateStreamRequest(t *testing.T) {
17新增: target := passwordTarget{maintenanceWindow: maintenanceFixture(), SelectionRequired: true}
18新增: first, err := json.Marshal(target)
19新增: if err != nil {
20新增: t.Fatal(err)
21新增: }
22新增: target.Window++
23新增: second, err := json.Marshal(target)
24新增: if err != nil {
25新增: t.Fatal(err)
26新增: }
27新增: input := &passwordProbeInput{}
28新增: output := append(append(append(first, '\n'), second...), '\n')
29新增: probe := passwordProbe{input: input, scanner: bufio.NewScanner(bytes.NewReader(output)), user: "trial"}
30新增: before, err := probe.target()
31新增: if err != nil || before.Accessibility || !before.SelectionRequired {
32新增: t.Fatal("private probe lost the AX-disabled authorization target")
33新增: }
34新增: after, err := probe.target()
35新增: if err != nil || before.geometry() == after.geometry() {
36新增: t.Fatal("per-key probe failed to observe a changed authorization panel")
37新增: }
38新增: if input.String() != "{\"action\":\"probe\"}\n{\"action\":\"probe\"}\n" {
39新增: t.Fatal("maintenance probe used a GUI socket command or extra request fields")
40新增: }
41新增:}
新增internal/maclogin/password_target.go+30 −0看文件
@@ -0,0 +1,30 @@
1新增:package maclogin
2新增:
3新增:import "time"
4新增:
5新增:type passwordTarget struct {
6新增: maintenanceWindow
7新增: Accessibility bool `json:"accessibility"`
8新增: SelectionRequired bool `json:"selection_required"`
9新增:}
10新增:
11新增:// Before Accessibility is granted, the user selects the input position in
12新增:// Apple's system panel. The host binds that click to the current GUI session
13新增:// and panel, and consumes it when the user requests password entry.
14新增:type passwordSelection struct {
15新增: Geometry string
16新增: X, Y int
17新增: Clicked time.Time
18新增:}
19新增:
20新增:func (selection passwordSelection) permits(target passwordTarget, user string, now time.Time) bool {
21新增: if !target.valid(user) {
22新增: return false
23新增: }
24新增: if target.Accessibility {
25新增: return target.PasswordFocused
26新增: }
27新增: return target.SelectionRequired && selection.Geometry == target.geometry() &&
28新增: now.Sub(selection.Clicked) >= 0 && now.Sub(selection.Clicked) <= 30*time.Second &&
29新增: target.contains(selection.X, selection.Y)
30新增:}
新增internal/maclogin/password_target_darwin_arm64.go+150 −0看文件
@@ -0,0 +1,150 @@
1新增://go:build darwin && arm64 && cgo && !no_vz
2新增:
3新增:package maclogin
4新增:
5新增:/*
6新增:#include "bridge.h"
7新增:*/
8新增:import "C"
9新增:
10新增:import (
11新增: "bufio"
12新增: "context"
13新增: "encoding/json"
14新增: "errors"
15新增: "io"
16新增: "os/exec"
17新增: "time"
18新增:
19新增: "github.com/sylvinus/agent-vm/internal/guestos"
20新增:)
21新增:
22新增:type passwordProbe struct {
23新增: command *exec.Cmd
24新增: input io.WriteCloser
25新增: output io.ReadCloser
26新增: scanner *bufio.Scanner
27新增: cancel context.CancelFunc
28新增: user string
29新增:}
30新增:
31新增:func (s *loginSession) openPasswordProbe() (*passwordProbe, error) {
32新增: bound, err := guestos.LoadMacOSProfile(s.profile)
33新增: if err != nil || bound == nil || bound.SetupID == "" {
34新增: return nil, errors.New("首次设置身份已变化,请重新打开授权画面")
35新增: }
36新增: administrator, err := guestos.MacOSProvisionUser(s.profile)
37新增: if err != nil {
38新增: return nil, err
39新增: }
40新增: ctx, cancel := context.WithTimeout(context.Background(), 7*time.Second)
41新增: command, err := guestGUIProbeCommand(ctx, s.profile, administrator, bound.User, "--setup-password-probe")
42新增: if err != nil {
43新增: cancel()
44新增: return nil, err
45新增: }
46新增: input, err := command.StdinPipe()
47新增: if err != nil {
48新增: cancel()
49新增: return nil, err
50新增: }
51新增: output, err := command.StdoutPipe()
52新增: if err != nil {
53新增: input.Close()
54新增: cancel()
55新增: return nil, err
56新增: }
57新增: if err = command.Start(); err != nil {
58新增: input.Close()
59新增: output.Close()
60新增: cancel()
61新增: return nil, err
62新增: }
63新增: scanner := bufio.NewScanner(output)
64新增: scanner.Buffer(make([]byte, 4096), 32<<10)
65新增: return &passwordProbe{command: command, input: input, output: output, scanner: scanner, cancel: cancel, user: bound.User}, nil
66新增:}
67新增:
68新增:func (probe *passwordProbe) close() {
69新增: probe.input.Close()
70新增: probe.output.Close()
71新增: probe.cancel()
72新增: _ = probe.command.Wait()
73新增:}
74新增:
75新增:func (probe *passwordProbe) target() (passwordTarget, error) {
76新增: var target passwordTarget
77新增: if _, err := io.WriteString(probe.input, "{\"action\":\"probe\"}\n"); err != nil {
78新增: return target, err
79新增: }
80新增: if !probe.scanner.Scan() {
81新增: return target, errors.New("无法确认系统授权窗口,请重新打开授权画面")
82新增: }
83新增: if json.Unmarshal(probe.scanner.Bytes(), &target) != nil || !target.valid(probe.user) {
84新增: return target, errors.New("请打开 Apple 系统授权窗口,再选中需要填写的密码框")
85新增: }
86新增: return target, nil
87新增:}
88新增:
89新增:func (s *loginSession) selectPasswordPosition(x, y int) {
90新增: s.passwordSelection = passwordSelection{}
91新增: probe, err := s.openPasswordProbe()
92新增: if err != nil {
93新增: return
94新增: }
95新增: defer probe.close()
96新增: target, err := probe.target()
97新增: if err == nil && target.SelectionRequired && target.contains(x, y) {
98新增: s.passwordSelection = passwordSelection{Geometry: target.geometry(), X: x, Y: y, Clicked: time.Now()}
99新增: }
100新增:}
101新增:
102新增:func (s *loginSession) fillSetupPassword(password string) error {
103新增: selection := s.passwordSelection
104新增: s.passwordSelection = passwordSelection{}
105新增: sequence, valid := passwordKeys(password)
106新增: if !s.setup || !valid {
107新增: return errors.New("首次设置凭据不可用,请重新打开授权画面")
108新增: }
109新增: probe, err := s.openPasswordProbe()
110新增: if err != nil {
111新增: return err
112新增: }
113新增: defer probe.close()
114新增: target, err := probe.target()
115新增: if err != nil {
116新增: return err
117新增: }
118新增: if !selection.permits(target, probe.user, time.Now()) {
119新增: return errors.New("请先点选系统授权窗口的密码框,再点击填写授权密码")
120新增: }
121新增: if !target.Accessibility && !bool(C.cageLoginClick(C.int(selection.X), C.int(selection.Y))) {
122新增: return errors.New("所选密码框已变化,请重新点选")
123新增: }
124新增: geometry := target.geometry()
125新增: check := func() error {
126新增: current, err := probe.target()
127新增: if err != nil {
128新增: return err
129新增: }
130新增: if current.geometry() != geometry || !selection.permits(current, probe.user, time.Now()) {
131新增: return errors.New("系统授权窗口或密码框已变化,填写已停止,请重新选择")
132新增: }
133新增: return nil
134新增: }
135新增: if err = check(); err != nil {
136新增: return err
137新增: }
138新增: if !bool(C.cageLoginSelectAll()) {
139新增: return errors.New("系统密码框尚未准备好,请重试")
140新增: }
141新增: for _, key := range sequence {
142新增: if err = check(); err != nil {
143新增: return err
144新增: }
145新增: if !bool(C.cageLoginKey(C.int(key.code), C.bool(key.shift))) {
146新增: return errors.New("授权密码未能填写,请重新选择密码框后重试")
147新增: }
148新增: }
149新增: return nil
150新增:}
新增internal/maclogin/password_target_test.go+53 −0看文件
@@ -0,0 +1,53 @@
1新增:package maclogin
2新增:
3新增:import (
4新增: "testing"
5新增: "time"
6新增:)
7新增:
8新增:func TestFirstAuthorizationUsesFreshSelectedSystemPanelBeforeAccessibility(t *testing.T) {
9新增: now := time.Now()
10新增: target := passwordTarget{maintenanceWindow: maintenanceFixture(), SelectionRequired: true}
11新增: selected := passwordSelection{Geometry: target.geometry(), X: 200, Y: 200, Clicked: now}
12新增: if !selected.permits(target, "trial", now.Add(time.Second)) {
13新增: t.Fatal("first authorization required the permission it is preparing")
14新增: }
15新增: for _, test := range []struct {
16新增: name string
17新增: change func(*passwordTarget, *passwordSelection)
18新增: }{
19新增: {"no selection", func(_ *passwordTarget, s *passwordSelection) { *s = passwordSelection{} }},
20新增: {"expired selection", func(_ *passwordTarget, s *passwordSelection) { s.Clicked = now.Add(-31 * time.Second) }},
21新增: {"future selection", func(_ *passwordTarget, s *passwordSelection) { s.Clicked = now.Add(time.Second) }},
22新增: {"outside panel", func(_ *passwordTarget, s *passwordSelection) { s.X = 159 }},
23新增: {"replaced window", func(w *passwordTarget, _ *passwordSelection) { w.Window++ }},
24新增: {"moved window", func(w *passwordTarget, _ *passwordSelection) { w.Rect[0]++ }},
25新增: {"another process", func(w *passwordTarget, _ *passwordSelection) { w.PID++ }},
26新增: {"another GUI session", func(w *passwordTarget, _ *passwordSelection) { w.Session = "1e128373-fcb9-42fd-88b2-2a6ca58cf3a1" }},
27新增: {"another app", func(w *passwordTarget, _ *passwordSelection) { w.Bundle = "com.apple.finder" }},
28新增: {"ordinary settings window", func(w *passwordTarget, _ *passwordSelection) { w.SelectionRequired = false }},
29新增: {"known non-password focus", func(w *passwordTarget, _ *passwordSelection) { w.Accessibility = true }},
30新增: } {
31新增: t.Run(test.name, func(t *testing.T) {
32新增: current, selection := target, selected
33新增: test.change(&current, &selection)
34新增: if selection.permits(current, "trial", now) {
35新增: t.Fatal("unverified password target accepted")
36新增: }
37新增: })
38新增: }
39新增:}
40新增:
41新增:func TestAuthorizedAccessibilityRequiresSecureFocusForBothAppleHosts(t *testing.T) {
42新增: for _, bundle := range []string{"com.apple.systempreferences", "com.apple.authorizationhost"} {
43新增: target := passwordTarget{maintenanceWindow: maintenanceFixture(), Accessibility: true}
44新增: target.Bundle, target.PasswordFocused = bundle, true
45新增: if !(passwordSelection{}).permits(target, "trial", time.Now()) {
46新增: t.Fatalf("verified secure field rejected in %s", bundle)
47新增: }
48新增: target.PasswordFocused = false
49新增: if (passwordSelection{}).permits(target, "trial", time.Now()) {
50新增: t.Fatal("non-password field accepted")
51新增: }
52新增: }
53新增:}
修改internal/workbench/browser_http.go+1 −1看文件
@@ -14,7 +14,7 @@ func (s *Server) browser(w http.ResponseWriter, r *http.Request) {
1414 action = "tabs"
1515 }
1616 switch action {
17删除: case "tabs", "split", "new", "activate", "close", "navigate", "back", "forward", "reload", "editor", "editor-restart", "download-retry", "upload-finish", "upload-cancel", "resize", "insert-text", "copy-context", "cookies", "settings", "extensions", "internal-page", "info":
17新增: case "tabs", "split", "new", "activate", "close", "navigate", "back", "forward", "reload", "editor", "editor-restart", "download-retry", "upload-finish", "upload-cancel", "resize", "insert-text", "copy-context", "copy", "cut", "cookies", "settings", "extensions", "internal-page", "info":
1818 default:
1919 http.NotFound(w, r)
2020 return
修改internal/workbench/browser_service.go+1 −1看文件
@@ -112,7 +112,7 @@ func (s *Server) browserAction(ctx context.Context, action string, input *browse
112112 ((input.Mode == "delete" || input.Mode == "details") && len(input.CookieKey) != 64)) {
113113 return nil, browserInputError{errors.New("Cookie 操作或目标标签无效")}
114114 }
115删除: if action == "copy-context" && (input.ID == "" || !validInputToken(input.Context)) {
115新增: if (action == "copy-context" || action == "copy" || action == "cut") && (input.ID == "" || !validInputToken(input.Context)) {
116116 return nil, browserInputError{errors.New("复制操作或目标标签无效")}
117117 }
118118 if action == "insert-text" && (input.ID == "" || input.Text == "" || len(input.Text) > 8192) {
修改internal/workbench/desktop_file_open.go+6 −7看文件
@@ -128,7 +128,12 @@ func (s *Server) desktopFileOpenAction(w http.ResponseWriter, r *http.Request) {
128128 guest, _ := result["path"].(string)
129129 action, _ := result["action"].(string)
130130 var target string
131删除: if download, _ := result["download_id"].(string); download != "" && (s.macosGuest != nil || s.windowsGuest != nil) {
131新增: download, _ := result["download_id"].(string)
132新增: if message, _ := result["error"].(string); message != "" {
133新增: err = errors.New(message)
134新增: } else if action != "open" && action != "reveal" {
135新增: err = errors.New("文件打开操作无效")
136新增: } else if download != "" && (s.macosGuest != nil || s.windowsGuest != nil) {
132137 var saved browserDownloadInfo
133138 saved, err = s.downloadInfo(ctx, download)
134139 if err == nil && saved.State != "saved" {
@@ -145,12 +150,6 @@ func (s *Server) desktopFileOpenAction(w http.ResponseWriter, r *http.Request) {
145150 target, err = s.resolveDesktopProjectFile(guest, projects)
146151 }
147152 }
148删除: if action != "open" && action != "reveal" {
149删除: err = errors.New("文件打开操作无效")
150删除: }
151删除: if message, _ := result["error"].(string); message != "" {
152删除: err = errors.New(message)
153删除: }
154153 if err != nil {
155154 body, _ = json.Marshal(map[string]string{"id": input.ID, "error": err.Error()})
156155 cleanup, cancelCleanup := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
修改internal/workbench/diagnostics.go+3 −1看文件
@@ -67,7 +67,9 @@ func (s *Server) diagnosticExport(w http.ResponseWriter, r *http.Request) {
6767 defer s.diagnosticMu.Unlock()
6868 guestState := "environment unavailable"
6969 var guest []byte
70删除: if s.vmRunning() {
70新增: if s.storageRecoveryStatus().Required {
71新增: guestState = "environment storage recovery pending"
72新增: } else if s.vmRunning() {
7173 ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second)
7274 defer cancel()
7375 var err error
修改internal/workbench/environment_test.go+60 −0看文件
@@ -1,8 +1,10 @@
11package workbench
22
33import (
4新增: "bytes"
45 "encoding/json"
56 "github.com/sylvinus/agent-vm/internal/cage"
7新增: "github.com/sylvinus/agent-vm/internal/guestos"
68 "io"
79 "net/http"
810 "os"
@@ -11,6 +13,64 @@ import (
1113 "testing"
1214)
1315
16新增:func TestEnvironmentUpgradeSeparatesPrivateLegacyWorkspaceFromVMIdentity(t *testing.T) {
17新增: home, err := filepath.EvalSymlinks(t.TempDir())
18新增: if err != nil {
19新增: t.Fatal(err)
20新增: }
21新增: t.Setenv("HOME", home)
22新增: t.Setenv("USERPROFILE", home)
23新增: for _, system := range []string{"linux", "macos", "windows"} {
24新增: t.Run(system, func(t *testing.T) {
25新增: s := testServer(t)
26新增: s.profile = filepath.Join(home, ".claude-cage", system)
27新增: legacy := s.profile + "-workspace"
28新增: selected := filepath.Join(home, "projects", system)
29新增: for _, path := range []string{s.profile, legacy, selected} {
30新增: if err := os.MkdirAll(path, 0700); err != nil {
31新增: t.Fatal(err)
32新增: }
33新增: }
34新增: s.preferences.Workspace = selected
35新增: if system == "macos" {
36新增: s.macosGuest = &guestos.MacOSProfile{Instance: "mac", User: "guest"}
37新增: } else if system == "windows" {
38新增: s.windowsGuest = &guestos.WindowsProfile{}
39新增: }
40新增: if err := writePrivate(filepath.Join(s.profile, "environment.json"), map[string]string{"directory": legacy}); err != nil {
41新增: t.Fatal(err)
42新增: }
43新增: identity := cage.InstanceName(s.profile, legacy)
44新增: disk := filepath.Join(s.profile, "state", "lima", identity, "disk")
45新增: if err := writePrivate(filepath.Join(filepath.Dir(disk), "lima.yaml"), map[string]string{}); err != nil {
46新增: t.Fatal(err)
47新增: }
48新增: original := []byte("persistent disk and existing project data")
49新增: for _, file := range []string{disk, filepath.Join(legacy, "project.txt"), filepath.Join(s.profile, "account.json")} {
50新增: if err := os.WriteFile(file, original, 0600); err != nil {
51新增: t.Fatal(err)
52新增: }
53新增: }
54新增: for restart := 0; restart < 2; restart++ {
55新增: if err := s.prepareEnvironment(); err != nil {
56新增: t.Fatal(err)
57新增: }
58新增: if s.environmentDir() != selected || s.workspace() != selected || cage.InstanceName(s.profile, selected) != identity {
59新增: t.Fatal("startup changed the VM identity or selected project")
60新增: }
61新增: if _, err := validateWorkspace(legacy, s.profile); err == nil {
62新增: t.Fatal("legacy location bypassed private-profile protection")
63新增: }
64新增: for _, file := range []string{disk, filepath.Join(legacy, "project.txt"), filepath.Join(s.profile, "account.json")} {
65新增: if data, err := os.ReadFile(file); err != nil || !bytes.Equal(data, original) {
66新增: t.Fatalf("startup changed existing personal data: %s %v", file, err)
67新增: }
68新增: }
69新增: }
70新增: })
71新增: }
72新增:}
73新增:
1474type browserTransport func(*http.Request) (*http.Response, error)
1575
1676func (f browserTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
修改internal/workbench/environment_versions.go+5 −0看文件
@@ -146,6 +146,11 @@ func (s *Server) synchronizeEnvironment() error {
146146 if err := s.closeProxyGate("正在更新环境组件,外网暂时关闭"); err != nil {
147147 return err
148148 }
149新增: // Publish the new guest-only binary before runCage restarts its controller;
150新增: // otherwise updated JavaScript would keep talking to the old protocol.
151新增: if err := s.refreshInstalledTailnet(); err != nil {
152新增: return err
153新增: }
149154 s.mu.Lock()
150155 s.ready = false
151156 s.guestUpdateRequired = true
修改internal/workbench/failure_message.go+9 −0看文件
@@ -20,6 +20,15 @@ func executionFailure(action string, err error, output string) error {
2020 patterns []string
2121 reason, next string
2222 }{
23新增: {[]string{"cage_windows_maintenance_authorization_canceled"}, "已取消 Windows 管理员授权", "请重新发起原操作,并在 Windows 系统授权窗口中确认。"},
24新增: {[]string{"cage_windows_maintenance_authorization"}, "Windows 管理员授权窗口未能打开", "请从本机 Cage 重新发起操作,并使用可完成管理员授权的 Windows 账户。"},
25新增: {[]string{"cage_windows_maintenance_validation"}, "Windows 环境绑定或组件清单未通过校验", "请重新发起原操作,组件包仍无法核验时重新安装完整 Cage 应用。"},
26新增: {[]string{"cage_windows_maintenance_host_manager"}, "Windows 系统管理助手安装未完成", "请重试修复系统助手,仍失败时检查系统服务或安全软件记录并导出诊断包。"},
27新增: {[]string{"cage_windows_maintenance_guest_connection"}, "Windows 客机连接未完成", "请启动并登录已绑定客机,使用该客机的管理员账户重试。"},
28新增: {[]string{"cage_windows_maintenance_guest_components"}, "Windows 客机组件安装未完成", "请保持原客机运行,重试同步环境组件,仍失败时导出诊断包。"},
29新增: {[]string{"cage_windows_maintenance_host_relay"}, "Windows 主机连接组件更新未完成", "请关闭占用连接组件的程序,再重试同步环境组件。"},
30新增: {[]string{"cage_windows_maintenance_package_preparation"}, "Windows 组件包准备未完成", "请检查应用目录和系统盘空间后重试,更新工具时同时检查已选代理。"},
31新增: {[]string{"cage_windows_maintenance_failed"}, "Windows 维护未完成", "请从 Cage 重新发起原操作,仍失败时导出诊断包。"},
2332 {[]string{"desktop file service state=failed"}, "Claude Desktop 的文件服务已经退出", "请从 Cage 重新打开 Claude Desktop;若应用反复退出,请在设置中查看资源用量并导出诊断包。"},
2433 {[]string{"curl: (7)", "connection refused"}, "目标服务没有接受连接", "请确认环境及所选代理已启动;文件传递时请重新打开接收文件的应用,再重试。"},
2534 {[]string{"no space left on device", "not enough space on the disk"}, "磁盘空间不足,无法继续写入", "请释放环境所在磁盘的空间后继续;不要删除 Cage 的个人数据目录。"},
修改internal/workbench/file_input.go+28 −2看文件
@@ -74,7 +74,7 @@ func (s *Server) guestFiles(ctx context.Context, target, method, path string, bo
7474 switch {
7575 case method == "GET" && parsed.Path == "/requests":
7676 input.Action = "files-poll"
77删除: case method == "POST" && (parsed.Path == "/start" || parsed.Path == "/finish" || parsed.Path == "/finish-image" || parsed.Path == "/cancel" || parsed.Path == "/directory" || parsed.Path == "/download-retry" || parsed.Path == "/open-claim" || parsed.Path == "/open-complete"):
77新增: case method == "POST" && (parsed.Path == "/start" || parsed.Path == "/finish" || parsed.Path == "/finish-image" || parsed.Path == "/cancel" || parsed.Path == "/directory" || parsed.Path == "/download-retry" || parsed.Path == "/download-ack" || parsed.Path == "/open-claim" || parsed.Path == "/open-complete"):
7878 input.Action = "files-" + strings.TrimPrefix(parsed.Path, "/")
7979 default:
8080 return nil, errors.New("虚拟 Mac 文件操作无效")
@@ -97,7 +97,7 @@ func (s *Server) guestFiles(ctx context.Context, target, method, path string, bo
9797 switch {
9898 case method == "GET" && parsed.Path == "/requests":
9999 action = "files-poll"
100删除: case method == "POST" && (parsed.Path == "/start" || parsed.Path == "/finish" || parsed.Path == "/finish-image" || parsed.Path == "/cancel" || parsed.Path == "/directory" || parsed.Path == "/download-retry" || parsed.Path == "/open-claim" || parsed.Path == "/open-complete"):
100新增: case method == "POST" && (parsed.Path == "/start" || parsed.Path == "/finish" || parsed.Path == "/finish-image" || parsed.Path == "/cancel" || parsed.Path == "/directory" || parsed.Path == "/download-retry" || parsed.Path == "/download-ack" || parsed.Path == "/open-claim" || parsed.Path == "/open-complete"):
101101 action = "files-" + strings.TrimPrefix(parsed.Path, "/")
102102 default:
103103 return nil, errors.New("Windows 原生文件选择框与桌面下载尚未接通")
@@ -316,9 +316,35 @@ func (s *Server) desktopFileRequests(w http.ResponseWriter, r *http.Request) {
316316 requestError(w, err)
317317 return
318318 }
319新增: s.acknowledgeDesktopDownloads(ctx, result)
319320 jsonReply(w, result)
320321}
321322
323新增:func (s *Server) acknowledgeDesktopDownloads(ctx context.Context, result map[string]any) {
324新增: if result["downloadAck"] != true || (s.macosGuest == nil && s.windowsGuest == nil) {
325新增: return
326新增: }
327新增: var ids []string
328新增: items, _ := result["downloads"].([]any)
329新增: for _, value := range items {
330新增: item, ok := value.(map[string]any)
331新增: if !ok || item["state"] != "saved" || item["acknowledged"] == true {
332新增: continue
333新增: }
334新增: id, _ := item["id"].(string)
335新增: ids = append(ids, id)
336新增: }
337新增: if len(ids) == 0 {
338新增: return
339新增: }
340新增: // rememberDesktopDownloads has resolved every saved state from its durable
341新增: // host receipt. A failed acknowledgment keeps the guest copy for the next poll.
342新增: body, _ := json.Marshal(map[string]any{"ids": ids})
343新增: if _, err := s.guestFiles(ctx, "desktop", "POST", "/download-ack", bytes.NewReader(body), ""); err != nil {
344新增: diagnostics.Log("warn", "desktop-files", "主机文件已保存,客机保留副本并等待下次确认:"+err.Error())
345新增: }
346新增:}
347新增:
322348// Register completed exports before the UI can ask a native bridge to save them.
323349// Guest paths are never accepted as arbitrary host paths.
324350func (s *Server) rememberDesktopDownloads(result map[string]any) error {
修改internal/workbench/image_input.go+3 −3看文件
@@ -36,7 +36,7 @@ func (s *Server) pasteInputStart(w http.ResponseWriter, r *http.Request) {
3636 return
3737 }
3838 if !s.fileTargetReady(input.Target, input.ID) {
39删除: http.Error(w, "图片接收位置已关闭,请重新点击输入框", http.StatusConflict)
39新增: http.Error(w, "粘贴接收位置已关闭,请重新点击输入框", http.StatusConflict)
4040 return
4141 }
4242 ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
@@ -50,7 +50,7 @@ func (s *Server) pasteInputStart(w http.ResponseWriter, r *http.Request) {
5050 result, err := s.guestFiles(ctx, "desktop", "POST", "/start", bytes.NewReader(body), "")
5151 id, _ := result["id"].(string)
5252 if err != nil || !browserFileID.MatchString(id) {
53删除: http.Error(w, "图片目标未能绑定,请重新点击输入框;旧客机需要先同步环境组件", http.StatusConflict)
53新增: http.Error(w, "粘贴目标未能绑定,请重新点击输入框。旧客机需要先同步环境组件", http.StatusConflict)
5454 return
5555 }
5656 jsonReply(w, map[string]any{"available": true, "transfer": id})
@@ -62,7 +62,7 @@ func (s *Server) pasteInputStart(w http.ResponseWriter, r *http.Request) {
6262 Transfer string `json:"transfer"`
6363 }
6464 if err != nil || json.Unmarshal(data, &result) != nil || !validInputToken(result.Transfer) {
65删除: http.Error(w, "图片目标未能绑定,请重新点击输入框;旧客机需要先同步环境组件", http.StatusConflict)
65新增: http.Error(w, "粘贴目标未能绑定,请重新点击输入框。旧客机需要先同步环境组件", http.StatusConflict)
6666 return
6767 }
6868 jsonReply(w, map[string]any{"available": true, "transfer": result.Transfer})
修改internal/workbench/initialization.go+1 −1看文件
@@ -26,7 +26,7 @@ type initializationView struct {
2626}
2727
2828func (s *Server) initializationState() (initializationView, error) {
29删除: if !s.localVMStorage() {
29新增: if !s.localVMStorage() || s.storageRecoveryStatus().Required {
3030 return initializationView{}, nil
3131 }
3232 data, err := os.ReadFile(filepath.Join(s.profile, "initialization.json"))
修改internal/workbench/jobs_service.go+9 −1看文件
@@ -1,6 +1,9 @@
11package workbench
22
3删除:import "context"
3新增:import (
4新增: "context"
5新增: "fmt"
6新增:)
47
58func (s *Server) busy() bool { return s.jobs.snapshot().Running }
69
@@ -12,6 +15,11 @@ func (s *Server) submitJob(kind string, run func() error) (Job, error) {
1215 s.mu.Unlock()
1316 return Job{}, errJobsClosed
1417 }
18新增: if s.storageRecoveryError != "" && kind != "storage-recovery" {
19新增: err := fmt.Errorf("环境存储待恢复,请在设置中恢复后继续。%s", s.storageRecoveryError)
20新增: s.mu.Unlock()
21新增: return Job{}, err
22新增: }
1523 var afterSuccess func() error
1624 if kind == "logout" {
1725 kind = "stop"
修改internal/workbench/macos_claude.go+1 −0看文件
@@ -56,6 +56,7 @@ type macOSWindowRequest struct {
5656 Wait bool `json:"wait,omitempty"`
5757 Binary bool `json:"binary,omitempty"`
5858 ID string `json:"id,omitempty"`
59新增: IDs []string `json:"ids,omitempty"`
5960 Kind string `json:"kind,omitempty"`
6061 Transfer string `json:"transfer,omitempty"`
6162 Sequence int `json:"sequence"`
修改internal/workbench/macos_guest.go+3 −1看文件
@@ -27,7 +27,7 @@ func macOSWorkbenchRoute(path string) bool {
2727 return id == "requests" || id == "open" || browserFileID.MatchString(id)
2828 }
2929 switch path {
30删除: case "/api/macos/first-setup", "/api/appearance/codex", "/api/macos/project-approval", "/api/macos/exit-policy", "/api/macos/login":
30新增: case "/api/macos/first-setup", "/api/appearance/codex", "/api/macos/project-approval", "/api/macos/exit-policy", "/api/macos/login", "/api/macos/maintenance":
3131 return true
3232 }
3333 return strings.HasPrefix(path, "/api/macos/claude/") || strings.HasPrefix(path, "/api/macos-browser/")
@@ -114,6 +114,8 @@ func (s *Server) attachMacOSGuest() error {
114114 if checkAfterReconnect {
115115 _, _ = s.submitJob("network-recovery", s.checkNetworkIfWanted)
116116 }
117新增: } else if err == nil && !s.macSetupPending() {
118新增: s.retryMacOSProjectShares(ctx)
117119 }
118120 return err
119121}
修改internal/workbench/macos_input_contract_test.go+2 −2看文件
@@ -82,7 +82,7 @@ func TestMacOSWindowInputRoutesPreserveCompositionSequence(t *testing.T) {
8282 for sequence, mode := range []string{"begin", "update", "commit"} {
8383 input := macOSWindowRequest{Action: "ime", PID: 42, Window: 7, Geometry: "geometry", Mode: mode,
8484 Context: strings.Repeat("a", 32), Session: strings.Repeat("b", 32), Sequence: sequence,
85删除: Project: "ungranted", PhoneToken: "ungranted", Path: "ungranted", Transfer: "ungranted", KeepAlive: true, Wait: true, Binary: true}
85新增: Project: "ungranted", PhoneToken: "ungranted", Path: "ungranted", Transfer: "ungranted", IDs: []string{"ungranted"}, KeepAlive: true, Wait: true, Binary: true}
8686 if mode == "commit" {
8787 input.Text = strings.Repeat("\x01", 8192)
8888 }
@@ -102,7 +102,7 @@ func TestMacOSWindowInputRoutesPreserveCompositionSequence(t *testing.T) {
102102 if actual.Sequence != sequence || actual.Session != input.Session || actual.Text != input.Text || actual.Geometry != input.Geometry {
103103 t.Fatalf("composition changed in transit for %s, sequence %d", mode, actual.Sequence)
104104 }
105删除: if actual.Project != "" || actual.Path != "" || actual.PhoneToken != "" || actual.Transfer != "" || actual.Wait || actual.Binary || actual.KeepAlive != keepAlive {
105新增: if actual.Project != "" || actual.Path != "" || actual.PhoneToken != "" || actual.Transfer != "" || actual.IDs != nil || actual.Wait || actual.Binary || actual.KeepAlive != keepAlive {
106106 t.Fatalf("public input retained privileged fields for %s", mode)
107107 }
108108 }
修改internal/workbench/macos_login.go+94 −3看文件
@@ -48,6 +48,65 @@ type macSetupPermissions struct {
4848 ManagedCredential bool `json:"managed_credential,omitempty"`
4949}
5050
51新增:type macLoginLease struct {
52新增: request guestos.MacLoginRequest
53新增: stopAccount func() bool
54新增: stopService func() bool
55新增:}
56新增:
57新增:func (l *macLoginLease) stop() {
58新增: if l == nil {
59新增: return
60新增: }
61新增: l.stopAccount()
62新增: l.stopService()
63新增:}
64新增:
65新增:func (s *Server) revokeMacLogin(session string) {
66新增: s.mu.Lock()
67新增: lease := s.macLoginLease
68新增: if lease == nil || lease.request.Session != session {
69新增: s.mu.Unlock()
70新增: return
71新增: }
72新增: s.macLoginLease = nil
73新增: s.mu.Unlock()
74新增: lease.stop()
75新增: connection, err := net.DialTimeout("unix", filepath.Join(s.instanceDir(), "cage-login.sock"), 2*time.Second)
76新增: if err != nil {
77新增: return
78新增: }
79新增: defer connection.Close()
80新增: _ = connection.SetWriteDeadline(time.Now().Add(2 * time.Second))
81新增: _ = json.NewEncoder(connection).Encode(lease.request)
82新增:}
83新增:
84新增:func (s *Server) trackMacLogin(epoch context.Context, input guestos.MacLoginRequest, result guestos.MacLoginReply) {
85新增: if input.Action == "open" && result.Session != "" {
86新增: lifetime := s.lifetimeContext()
87新增: lease := &macLoginLease{request: guestos.MacLoginRequest{Action: "close", Session: result.Session, Setup: input.Setup, Maintenance: input.Maintenance}}
88新增: s.mu.Lock()
89新增: previous := s.macLoginLease
90新增: s.macLoginLease = lease
91新增: lease.stopAccount = context.AfterFunc(epoch, func() { s.revokeMacLogin(result.Session) })
92新增: lease.stopService = context.AfterFunc(lifetime, func() { s.revokeMacLogin(result.Session) })
93新增: s.mu.Unlock()
94新增: previous.stop()
95新增: return
96新增: }
97新增: if input.Action == "close" || result.Closed {
98新增: s.mu.Lock()
99新增: lease := s.macLoginLease
100新增: if lease != nil && lease.request.Session == input.Session {
101新增: s.macLoginLease = nil
102新增: } else {
103新增: lease = nil
104新增: }
105新增: s.mu.Unlock()
106新增: lease.stop()
107新增: }
108新增:}
109新增:
51110func (s *Server) macSetupPermissions(ctx context.Context) (macSetupPermissions, error) {
52111 var status macSetupPermissions
53112 data, err := s.macOSWindowCall(ctx, macOSWindowRequest{Action: "setup-status"})
@@ -88,6 +147,20 @@ func (s *Server) macOSLoginWindow(w http.ResponseWriter, r *http.Request) {
88147 return
89148 }
90149 input.Setup = r.URL.Path == "/api/macos/first-setup"
150新增: if r.URL.Path == "/api/macos/maintenance" {
151新增: if !guestos.ValidMacMaintenancePurpose(input.Maintenance) {
152新增: http.Error(w, "请选择需要恢复的客机系统权限", http.StatusBadRequest)
153新增: return
154新增: }
155新增: switch input.Action {
156新增: case "open", "close", "frame", "click", "key", "scroll", "select-all", "fill-password":
157新增: default:
158新增: http.Error(w, "维护画面只接受窗口查看与局部输入", http.StatusBadRequest)
159新增: return
160新增: }
161新增: } else {
162新增: input.Maintenance = ""
163新增: }
91164 if input.Setup && !s.macSetupPending() {
92165 http.Error(w, "首次设置入口已关闭", http.StatusGone)
93166 return
@@ -191,7 +264,12 @@ func (s *Server) macOSLoginWindow(w http.ResponseWriter, r *http.Request) {
191264 http.Error(w, "无效的登录会话", 400)
192265 return
193266 }
194删除: ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second)
267新增: timeout := 8 * time.Second
268新增: if input.Maintenance != "" {
269新增: timeout = 15 * time.Second
270新增: }
271新增: epoch, _ := s.account.accessFor(true)
272新增: ctx, cancel := context.WithTimeout(r.Context(), timeout)
195273 defer cancel()
196274 var dial net.Dialer
197275 conn, err := dial.DialContext(ctx, "unix", filepath.Join(s.instanceDir(), "cage-login.sock"))
@@ -200,17 +278,30 @@ func (s *Server) macOSLoginWindow(w http.ResponseWriter, r *http.Request) {
200278 return
201279 }
202280 defer conn.Close()
203删除: _ = conn.SetDeadline(time.Now().Add(8 * time.Second))
281新增: stop := context.AfterFunc(ctx, func() { conn.Close() })
282新增: defer stop()
283新增: _ = conn.SetDeadline(time.Now().Add(timeout))
204284 var result guestos.MacLoginReply
205285 if json.NewEncoder(conn).Encode(input) != nil || json.NewDecoder(io.LimitReader(conn, 6<<20)).Decode(&result) != nil {
206286 http.Error(w, "客机登录界面无法响应", 503)
207287 return
208288 }
289新增: if input.Maintenance != "" && result.MaintenanceVersion != 1 {
290新增: result = guestos.MacLoginReply{Closed: true, Recovery: "environment-restart", Error: "虚拟 Mac 运行器需要重新加载。请保存工作,在环境设置中停止并重新启动虚拟 Mac,再打开授权设置。"}
291新增: }
292新增: s.trackMacLogin(epoch, input, result)
293新增: if input.Action == "open" && ctx.Err() != nil {
294新增: s.revokeMacLogin(result.Session)
295新增: return
296新增: }
209297 if input.Setup && input.Action == "finish" && result.Error == "" && !s.macSetupPending() {
210298 s.restoreProjectShares()
211299 }
212300 w.Header().Set("Cache-Control", "no-store")
213删除: jsonReply(w, result)
301新增: w.Header().Set("Content-Type", "application/json; charset=utf-8")
302新增: if err := json.NewEncoder(w).Encode(result); err != nil && input.Action == "open" {
303新增: s.revokeMacLogin(result.Session)
304新增: }
214305}
215306
216307func (s *Server) macOSSetupAdminCommand(ctx context.Context) *exec.Cmd {
新增internal/workbench/macos_maintenance_unix_test.go+158 −0看文件
@@ -0,0 +1,158 @@
1新增://go:build !windows
2新增:
3新增:package workbench
4新增:
5新增:import (
6新增: "encoding/json"
7新增: "io"
8新增: "net"
9新增: "net/http"
10新增: "net/http/httptest"
11新增: "os"
12新增: "path/filepath"
13新增: "strings"
14新增: "sync/atomic"
15新增: "testing"
16新增: "time"
17新增:
18新增: "github.com/sylvinus/agent-vm/internal/guestos"
19新增:)
20新增:
21新增:type disconnectedMacLoginResponse struct{ *httptest.ResponseRecorder }
22新增:
23新增:func (disconnectedMacLoginResponse) Write([]byte) (int, error) { return 0, io.ErrClosedPipe }
24新增:
25新增:func TestMacOSMaintenanceHTTPBoundaryAndRunnerUpgrade(t *testing.T) {
26新增: s := testServer(t)
27新增: profile, err := os.MkdirTemp("/tmp", "cage-maint-")
28新增: if err != nil {
29新增: t.Fatal(err)
30新增: }
31新增: defer os.RemoveAll(profile)
32新增: s.profile = profile
33新增: s.macosGuest = &guestos.MacOSProfile{Instance: "mac", User: "trial"}
34新增: s.ready = true
35新增: if err := os.MkdirAll(s.instanceDir(), 0700); err != nil {
36新增: t.Fatal(err)
37新增: }
38新增: listener, err := net.Listen("unix", filepath.Join(s.instanceDir(), "cage-login.sock"))
39新增: if err != nil {
40新增: t.Fatal(err)
41新增: }
42新增: requests := make(chan guestos.MacLoginRequest, 4)
43新增: var legacy atomic.Bool
44新增: done := make(chan struct{})
45新增: go func() {
46新增: defer close(done)
47新增: for {
48新增: connection, err := listener.Accept()
49新增: if err != nil {
50新增: return
51新增: }
52新增: var input guestos.MacLoginRequest
53新增: if json.NewDecoder(connection).Decode(&input) == nil {
54新增: requests <- input
55新增: response := guestos.MacLoginReply{MaintenanceVersion: 1, Session: "fixture-session"}
56新增: if legacy.Load() {
57新增: response = guestos.MacLoginReply{Closed: true}
58新增: }
59新增: _ = json.NewEncoder(connection).Encode(response)
60新增: }
61新增: _ = connection.Close()
62新增: }
63新增: }()
64新增: defer func() { listener.Close(); <-done }()
65新增: post := func(path, body string, trusted bool) *httptest.ResponseRecorder {
66新增: t.Helper()
67新增: request := httptest.NewRequest(http.MethodPost, s.origin+path, strings.NewReader(body))
68新增: request.Header.Set("Origin", s.origin)
69新增: request.Header.Set("Content-Type", "application/json")
70新增: request.AddCookie(&http.Cookie{Name: s.cookieName(), Value: s.session})
71新增: if trusted {
72新增: request.AddCookie(&http.Cookie{Name: s.cookieName() + "-desktop", Value: trustedViewProof(s.token)})
73新增: }
74新增: response := httptest.NewRecorder()
75新增: s.handler().ServeHTTP(response, request)
76新增: return response
77新增: }
78新增: body := `{"action":"fill-password","maintenance":"projects","session":"fixture-session","geometry":"verified-window","password":"untrusted-input","initial_setup":true}`
79新增: if response := post("/api/macos/maintenance", body, false); response.Code != http.StatusForbidden {
80新增: t.Fatalf("untrusted maintenance accepted: %d", response.Code)
81新增: }
82新增: if response := post("/api/macos/maintenance", body, true); response.Code != http.StatusOK {
83新增: t.Fatalf("trusted maintenance failed: %d %s", response.Code, response.Body.String())
84新增: }
85新增: input := <-requests
86新增: if input.Setup || input.Password != "" || input.Maintenance != "projects" || input.Geometry != "verified-window" || input.Action != "fill-password" {
87新增: t.Fatalf("maintenance boundary changed: action=%s purpose=%s setup=%v", input.Action, input.Maintenance, input.Setup)
88新增: }
89新增: for _, body := range []string{
90新增: `{"action":"open","maintenance":"desktop"}`,
91新增: `{"action":"show-password","maintenance":"projects"}`,
92新增: `{"action":"finish","maintenance":"projects"}`,
93新增: } {
94新增: if response := post("/api/macos/maintenance", body, true); response.Code != http.StatusBadRequest {
95新增: t.Fatalf("invalid maintenance request returned %d", response.Code)
96新增: }
97新增: }
98新增: if response := post("/api/macos/first-setup", `{"action":"open"}`, true); response.Code != http.StatusGone {
99新增: t.Fatalf("completed initial setup was reopened: %d", response.Code)
100新增: }
101新增: legacy.Store(true)
102新增: response := post("/api/macos/maintenance", `{"action":"open","maintenance":"projects"}`, true)
103新增: <-requests
104新增: var result guestos.MacLoginReply
105新增: if response.Code != http.StatusOK || json.Unmarshal(response.Body.Bytes(), &result) != nil || result.Recovery != "environment-restart" || !result.Closed {
106新增: t.Fatalf("old runner did not request a safe restart: %d %s", response.Code, response.Body.String())
107新增: }
108新增: legacy.Store(false)
109新增: if response := post("/api/macos/maintenance", `{"action":"open","maintenance":"projects"}`, true); response.Code != http.StatusOK {
110新增: t.Fatal("could not open the current maintenance runner")
111新增: }
112新增: <-requests
113新增: s.account.lock()
114新增: select {
115新增: case close := <-requests:
116新增: if close.Action != "close" || close.Session != "fixture-session" || close.Maintenance != "projects" {
117新增: t.Fatal("Cage lock did not revoke its maintenance session")
118新增: }
119新增: case <-time.After(3 * time.Second):
120新增: t.Fatal("Cage lock retained the maintenance view")
121新增: }
122新增:
123新增: // An open request can finish after the user locks and unlocks the workbench.
124新增: // Its lease must belong to the account epoch that admitted that request.
125新增: previousEpoch, _ := s.account.accessFor(true)
126新增: s.account.mu.Lock()
127新增: s.account.setKey(make([]byte, 32))
128新增: s.account.mu.Unlock()
129新增: s.trackMacLogin(previousEpoch,
130新增: guestos.MacLoginRequest{Action: "open", Maintenance: "projects"},
131新增: guestos.MacLoginReply{Session: "late-session"})
132新增: select {
133新增: case close := <-requests:
134新增: if close.Action != "close" || close.Session != "late-session" {
135新增: t.Fatal("a late open response attached to the new account epoch")
136新增: }
137新增: case <-time.After(3 * time.Second):
138新增: t.Fatal("a late open response retained its cancelled maintenance view")
139新增: }
140新增:
141新增: request := httptest.NewRequest(http.MethodPost, s.origin+"/api/macos/maintenance", strings.NewReader(`{"action":"open","maintenance":"projects"}`))
142新增: request.Header.Set("Origin", s.origin)
143新增: request.Header.Set("Content-Type", "application/json")
144新增: request.AddCookie(&http.Cookie{Name: s.cookieName(), Value: s.session})
145新增: request.AddCookie(&http.Cookie{Name: s.cookieName() + "-desktop", Value: trustedViewProof(s.token)})
146新增: s.handler().ServeHTTP(disconnectedMacLoginResponse{httptest.NewRecorder()}, request)
147新增: if open := <-requests; open.Action != "open" {
148新增: t.Fatal("disconnected response fixture did not open the maintenance view")
149新增: }
150新增: select {
151新增: case close := <-requests:
152新增: if close.Action != "close" || close.Session != "fixture-session" {
153新增: t.Fatal("a failed HTTP reply did not close its newly opened view")
154新增: }
155新增: case <-time.After(3 * time.Second):
156新增: t.Fatal("an undelivered HTTP response retained its maintenance view")
157新增: }
158新增:}
新增internal/workbench/macos_project_recovery_test.go+85 −0看文件
@@ -0,0 +1,85 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "bytes"
5新增: "encoding/json"
6新增: "net/http"
7新增: "net/http/httptest"
8新增: "strings"
9新增: "sync/atomic"
10新增: "testing"
11新增:
12新增: "golang.org/x/crypto/ssh"
13新增:)
14新增:
15新增:func TestMacOSProjectWaitsForLoginAndRestoresAutomatically(t *testing.T) {
16新增: var loggedIn atomic.Bool
17新增: guest := newMacWorkspaceGuest(t, func(channel ssh.Channel, command string) (uint32, bool) {
18新增: if strings.Contains(command, "/dev/console") && !loggedIn.Load() {
19新增: return 73, true
20新增: }
21新增: return 0, false
22新增: })
23新增: guest.approved.Store(true)
24新增: s := guest.s
25新增: s.restoreProjectShares()
26新增: if len(s.projectErrors) != 1 || s.projectErrors[0].Recovery != "guest-login" || len(s.projectShares) != 0 {
27新增: t.Fatalf("missing actionable login state: %+v", s.projectErrors)
28新增: }
29新增: data, _ := json.Marshal(map[string]any{"workspace": guest.hostPath, "add": false})
30新增: recorder := httptest.NewRecorder()
31新增: request := httptest.NewRequest(http.MethodPost, "/api/projects/open", bytes.NewReader(data))
32新增: request.Header.Set("Content-Type", "application/json")
33新增: s.openProject(recorder, request)
34新增: if recorder.Code != http.StatusBadRequest || recorder.Header().Get("X-Cage-Recovery") != "guest-login" {
35新增: t.Fatalf("project open lost its recovery action: %d %s", recorder.Code, recorder.Body.String())
36新增: }
37新增: s.retryMacOSProjectShares(t.Context())
38新增: if len(s.projectShares) != 0 {
39新增: t.Fatal("mount started before guest GUI login")
40新增: }
41新增: loggedIn.Store(true)
42新增: s.retryMacOSProjectShares(t.Context())
43新增: defer s.closeProjectShares()
44新增: if len(s.projectErrors) != 0 || s.projectShares[guest.hostPath] == nil {
45新增: t.Fatalf("login did not restore the saved project: %+v", s.projectErrors)
46新增: }
47新增:}
48新增:
49新增:func TestMacOSProjectPrepareReportsSpecificRecovery(t *testing.T) {
50新增: for _, sample := range []struct {
51新增: exit uint32
52新增: recovery string
53新增: }{
54新增: {73, "guest-login"}, {74, "environment-update"}, {76, "environment-restart"},
55新增: {77, "project-directory"}, {78, "project-directory"}, {79, "environment-update"}, {255, "project-retry"},
56新增: } {
57新增: t.Run(sample.recovery, func(t *testing.T) {
58新增: guest := newMacWorkspaceGuest(t, func(channel ssh.Channel, command string) (uint32, bool) {
59新增: if strings.Contains(command, "/dev/console") {
60新增: return sample.exit, true
61新增: }
62新增: return 0, false
63新增: })
64新增: guest.s.restoreProjectShares()
65新增: if len(guest.s.projectErrors) != 1 || guest.s.projectErrors[0].Recovery != sample.recovery {
66新增: t.Fatalf("exit %d: %+v", sample.exit, guest.s.projectErrors)
67新增: }
68新增: })
69新增: }
70新增:}
71新增:
72新增:func TestMacOSFailedUnsavedProjectDoesNotBecomeBackgroundGrant(t *testing.T) {
73新增: guest := newMacWorkspaceGuest(t, func(channel ssh.Channel, command string) (uint32, bool) {
74新增: if strings.Contains(command, "/dev/console") {
75新增: return 73, true
76新增: }
77新增: return 0, false
78新增: })
79新增: if _, err := guest.s.connectProject(t.TempDir(), true); err == nil {
80新增: t.Fatal("expected the guest login precondition")
81新增: }
82新增: if len(guest.s.projectErrors) != 0 || len(guest.s.projectShares) != 0 {
83新增: t.Fatal("an uncompleted new project was scheduled for background sharing")
84新增: }
85新增:}
修改internal/workbench/macos_projects.go+92 −17看文件
@@ -13,6 +13,7 @@ import (
1313 "time"
1414
1515 "github.com/google/uuid"
16新增: "github.com/sylvinus/agent-vm/internal/diagnostics"
1617
1718 "al.essio.dev/pkg/shellescape"
1819)
@@ -25,9 +26,27 @@ func macOSProjectPath(user, hostDirectory string) string {
2526// A mount which is ready in FSKit can still be unreadable by the guest app.
2627// Keep the live restricted connection while macOS waits for the user's folder
2728// approval; do not accept an APFS directory or a stale mount as this project.
28删除:var errMacOSProjectApproval = errors.New("请在虚拟 Mac 的项目授权窗口中选中此项目,然后重新打开")
29新增:var errMacOSProjectApproval = &projectShareError{Recovery: "project-approval", Message: "请在 Cage 显示的客机授权窗口中允许此项目,然后验证授权。"}
2930
3031const macProjectAgent = "/Applications/CageProjectAccess.app/Contents/MacOS/CageProjectAccess"
32新增:const macProjectLoginCheck = `test "$(/usr/bin/stat -f %u /dev/console)" = "$(/usr/bin/id -u)" && /bin/launchctl print "gui/$(/usr/bin/id -u)" >/dev/null 2>&1`
33新增:
34新增:func macOSProjectPrepareError(err error) error {
35新增: var exit *exec.ExitError
36新增: if errors.As(err, &exit) {
37新增: switch exit.ExitCode() {
38新增: case 73:
39新增: return &projectShareError{Recovery: "guest-login", Message: "请先登录虚拟 Mac 的客机账户。登录完成后,Cage 会自动连接项目。"}
40新增: case 74, 79:
41新增: return &projectShareError{Recovery: "environment-update", Message: "客机项目共享组件尚未就绪。请同步环境组件,完成后重新连接项目。"}
42新增: case 76:
43新增: return &projectShareError{Recovery: "environment-restart", Message: "此项目还保留着旧的客机挂载。请保存工作,在环境设置中停止并重新启动虚拟 Mac,再连接项目。"}
44新增: case 77, 78:
45新增: return &projectShareError{Recovery: "project-directory", Message: "客机的项目挂载位置包含文件、链接或权限异常。请先保留其中的文件,再通过诊断记录检查该位置。"}
46新增: }
47新增: }
48新增: return &projectShareError{Recovery: "project-retry", Message: "工作台暂时无法连接客机项目服务。连接恢复后会自动重试,也可以重新连接项目。"}
49新增:}
3150
3251func (s *Server) ensureMacOSProjectShare(hostDir string) error {
3352 ctx, cancel := context.WithTimeout(s.operationContext(), 18*time.Second)
@@ -86,27 +105,33 @@ func (s *Server) ensureMacOSProjectShare(hostDir string) error {
86105func (s *Server) startMacOSProjectShare(ctx context.Context, hostDir, guestDir string) (*projectShare, error) {
87106 folder := shellescape.Quote(guestDir)
88107
89删除: prepare := `set -e; test "$(/usr/bin/stat -f %u /dev/console)" = "$(/usr/bin/id -u)" || exit 73
90删除: /bin/launchctl print "gui/$(/usr/bin/id -u)" >/dev/null 2>&1 || exit 73
91删除: test -x /usr/local/libexec/cage-sshfs; test -x ` + macProjectAgent +
92删除: `; p=` + folder + `; if /sbin/mount | /usr/bin/grep -Fq " on $p ("; then exit 2; fi; for d in "$HOME/Cage" "$HOME/Cage/Projects" "$p"; do
93删除: test ! -L "$d"; if test ! -e "$d"; then /bin/mkdir -m 700 "$d"; fi; test -d "$d" && test -O "$d" || exit 1
94删除: done; test -z "$(/bin/ls -A "$p")"; /usr/bin/open -gj -a /Applications/CageProjectAccess.app`
95删除: _, err := s.guestControl(ctx, prepare, "macos-project-prepare")
108新增: prepare := `set -e; ` + macProjectLoginCheck + ` || exit 73
109新增: test -x /usr/local/libexec/cage-sshfs && test -x ` + macProjectAgent + ` || exit 74
110新增: p=` + folder + `; if /sbin/mount | /usr/bin/grep -Fq " on $p ("; then exit 76; fi; for d in "$HOME/Cage" "$HOME/Cage/Projects" "$p"; do
111新增: test ! -L "$d" || exit 77; if test ! -e "$d"; then /bin/mkdir -m 700 "$d" || exit 78; fi; test -d "$d" && test -O "$d" || exit 77
112新增: done; entries=$(/bin/ls -A "$p") || exit 78; test -z "$entries" || exit 77
113新增: /usr/bin/open -gj -a /Applications/CageProjectAccess.app || exit 79
114新增: if /usr/local/libexec/cage-sshfs --help 2>/dev/null | /usr/bin/grep -Fq 'cage_openwith='; then
115新增: printf '\nCAGE_SSHFS_OPENWITH\n'
116新增: fi`
117新增: capabilities, err := s.guestControl(ctx, prepare, "macos-project-prepare")
96118 if err != nil {
97删除: var exit *exec.ExitError
98删除: if errors.As(err, &exit) && exit.ExitCode() == 73 {
99删除: return nil, errors.New("请先在虚拟 Mac 中登录已绑定的普通账户,再重新打开项目")
100删除: }
101删除: return nil, errors.New("无法准备 macOS 实时挂载。请检查客机项目助手、SSHFS 及目标目录")
119新增: return nil, macOSProjectPrepareError(err)
102120 }
103121 command := "exec /usr/local/libexec/cage-sshfs " + shellescape.Quote(":"+filepath.ToSlash(hostDir)) + " " + folder +
104122 " -f -o slave,backend=fskit,nodev,nosuid,dir_cache=no"
105删除: conn, err := startProjectTransport(s.sshCommand(s.lifetimeContext(), "-T", s.sshTarget(), "--", command), hostDir)
123新增: if strings.Contains("\n"+string(capabilities)+"\n", "\nCAGE_SSHFS_OPENWITH\n") {
124新增: metadata := path.Join("/Users", s.macosGuest.User, "Library/Caches/dev.cage.GuestClaudeWindow/openwith.data")
125新增: command += " -o " + shellescape.Quote("cage_openwith="+metadata)
126新增: }
127新增: cmd := s.sshCommand(s.lifetimeContext(), "-T", s.sshTarget(), "--", command)
128新增: stderr := &fileControlStderr{}
129新增: cmd.Stderr = stderr
130新增: conn, err := startProjectTransport(cmd, hostDir)
106131 if err != nil {
107132 return nil, err
108133 }
109删除:
134新增: conn.stderr = stderr
110135 return conn, nil
111136}
112137
@@ -151,10 +176,60 @@ func (s *Server) probeMacOSProject(ctx context.Context, hostDir, guestDir string
151176 }
152177 select {
153178 case <-ctx.Done():
154删除: return errors.New("虚拟 Mac 的项目助手未能读回宿主项目文件")
179新增: return &projectShareError{Recovery: "project-retry", Message: "客机项目助手尚未确认此文件夹可用。请重新连接项目,持续失败时可查看诊断记录。"}
155180 case <-share.done:
156删除: return errors.New("macOS 实时挂载已断开,请检查客机文件系统扩展授权")
181新增: if share.stderr != nil && len(share.stderr.data) > 0 {
182新增: message := string(share.stderr.data)
183新增: _ = diagnostics.New(s.profile).Record("warn", "macos-project-mount", message)
184新增: if strings.Contains(strings.ToLower(message), "not enabled") {
185新增: return &projectShareError{Recovery: "filesystem-permission", Message: "虚拟 Mac 的文件系统扩展尚未启用。请在客机系统设置中同时启用 macFUSE 和 macFUSE (local),然后重新连接项目。"}
186新增: }
187新增: }
188新增: return &projectShareError{Recovery: "project-retry", Message: "客机文件共享连接已中断。Cage 会自动重试,持续失败时可查看诊断记录。"}
157189 case <-time.After(200 * time.Millisecond):
158190 }
159191 }
160192}
193新增:
194新增:// The existing lifecycle monitor retries only failed or ended project streams.
195新增:// A login check precedes retry so startup does not repeatedly open guest prompts.
196新增:func (s *Server) retryMacOSProjectShares(ctx context.Context) {
197新增: s.mu.Lock()
198新增: pending := make(map[string]bool)
199新增: waitingForLogin := false
200新增: waitingForFilesystem := false
201新增: for _, failure := range s.projectErrors {
202新增: if failure.Recovery == "guest-login" || failure.Recovery == "project-retry" || failure.Recovery == "filesystem-permission" {
203新增: pending[failure.Path] = true
204新增: waitingForLogin = waitingForLogin || failure.Recovery == "guest-login"
205新增: waitingForFilesystem = waitingForFilesystem || failure.Recovery == "filesystem-permission"
206新增: }
207新增: }
208新增: for path, share := range s.projectShares {
209新增: select {
210新增: case <-share.done:
211新增: pending[path] = true
212新增: default:
213新增: }
214新增: }
215新增: retryAt := s.macProjectsRetryAt
216新增: s.mu.Unlock()
217新增: if len(pending) == 0 || (!waitingForLogin && time.Now().Before(retryAt)) {
218新增: return
219新增: }
220新增: if _, err := s.guest(ctx, "set -e; "+macProjectLoginCheck+" || exit 73"); err != nil {
221新增: for path := range pending {
222新增: s.setProjectError(path, macOSProjectPrepareError(err))
223新增: }
224新增: return
225新增: }
226新增: s.mu.Lock()
227新增: s.macProjectsRetryAt = time.Now().Add(15 * time.Second)
228新增: s.mu.Unlock()
229新增: if waitingForFilesystem && s.checkMacOSSetupProjects(s.lifetimeContext()) != nil {
230新增: return
231新增: }
232新增: for path := range pending {
233新增: _ = s.ensureProjectShare(path)
234新增: }
235新增:}
修改internal/workbench/macos_window_connection.go+1 −0看文件
@@ -60,6 +60,7 @@ func macOSWindowClientRequest(input macOSWindowRequest, keepAlive bool) macOSWin
6060 input.Project, input.Nonce = "", ""
6161 input.Phone, input.PhoneToken = nil, ""
6262 input.Transfer, input.Path, input.Error = "", "", ""
63新增: input.IDs = nil
6364 input.Wait, input.Binary, input.KeepAlive = false, false, keepAlive
6465 if input.Action != "ime" {
6566 input.Sequence = 0
修改internal/workbench/macos_workspace_test.go+47 −0看文件
@@ -266,6 +266,53 @@ func (g *macWorkspaceGuest) execute(channel ssh.Channel, command string) uint32
266266 }
267267}
268268
269新增:func TestMacOSProjectOpenWithRequiresSSHFSCapability(t *testing.T) {
270新增: for _, capability := range []struct {
271新增: name string
272新增: output string
273新增: want bool
274新增: }{
275新增: {name: "legacy helper"},
276新增: {name: "supported helper", output: "\nCAGE_SSHFS_OPENWITH\n", want: true},
277新增: {name: "unrelated diagnostic", output: "unknown CAGE_SSHFS_OPENWITH option\n"},
278新增: } {
279新增: t.Run(capability.name, func(t *testing.T) {
280新增: mounts := make(chan string, 1)
281新增: guest := newMacWorkspaceGuest(t, func(channel ssh.Channel, command string) (uint32, bool) {
282新增: if strings.Contains(command, "CAGE_SSHFS_OPENWITH") {
283新增: fmt.Fprint(channel, capability.output)
284新增: return 0, true
285新增: }
286新增: if strings.HasPrefix(command, "exec /usr/local/libexec/cage-sshfs ") {
287新增: mounts <- command
288新增: }
289新增: return 0, false
290新增: })
291新增: guest.approved.Store(true)
292新增: if err := guest.s.ensureMacOSProjectShare(guest.hostPath); err != nil {
293新增: t.Fatal(err)
294新增: }
295新增: command := <-mounts
296新增: args, err := shellquote.Split(command)
297新增: if err != nil {
298新增: t.Fatal(err)
299新增: }
300新增: found := false
301新增: for _, arg := range args {
302新增: if strings.HasPrefix(arg, "cage_openwith=") {
303新增: found = true
304新增: if arg != "cage_openwith=/Users/cage/Library/Caches/dev.cage.GuestClaudeWindow/openwith.data" {
305新增: t.Fatalf("unexpected guest metadata path %q", arg)
306新增: }
307新增: }
308新增: }
309新增: if found != capability.want {
310新增: t.Fatalf("OpenWith option present = %v, want %v", found, capability.want)
311新增: }
312新增: })
313新增: }
314新增:}
315新增:
269316func TestMacOSDefaultWorkspaceUsesApprovedSharedProject(t *testing.T) {
270317 guest := newMacWorkspaceGuest(t)
271318 s := guest.s
修改internal/workbench/native_desktop_downloads.go+8 −0看文件
@@ -117,6 +117,14 @@ func desktopDownloadFailure(reason string) error {
117117 return errors.New("Claude Desktop 下载文件在传输中发生变化,请重新下载")
118118 case "desktop_download_unavailable", "desktop_download_transfer_invalid":
119119 return errors.New("Claude Desktop 下载文件已不可用,请确认客机已解锁后重新下载")
120新增: case "desktop_download_limit":
121新增: return errors.New("待保存的 Claude Desktop 文件过多,请先完成现有下载后重试")
122新增: case "file_open_target_changed":
123新增: return errors.New("文件或 Claude 窗口已变化,请回到原窗口重新打开文件")
124新增: case "file_open_request_invalid", "file_open_request_unavailable":
125新增: return errors.New("文件打开请求已失效,请确认客机已解锁后重新操作")
126新增: case "file_open_request_limit":
127新增: return errors.New("正在处理的文件打开请求过多,请稍后重试")
120128 default:
121129 return nil
122130 }
修改internal/workbench/native_desktop_downloads_test.go+83 −0看文件
@@ -41,6 +41,7 @@ func serveDesktopDownloadFixture(input io.Reader, output io.Writer, directory st
4141 for reader.Scan() {
4242 var request struct {
4343 Action, ID, Transfer string
44新增: IDs []string
4445 Sequence int
4546 KeepAlive bool
4647 }
@@ -62,6 +63,25 @@ func serveDesktopDownloadFixture(input io.Reader, output io.Writer, directory st
6263 switch request.Action {
6364 case "files-poll":
6465 reply = map[string]any{"available": true, "uploads": []any{}, "opens": []any{}, "downloads": []browserDownloadInfo{record}}
66新增: if _, err := os.Stat(filepath.Join(directory, "supports-ack")); err == nil {
67新增: var item map[string]any
68新增: _ = json.Unmarshal(data, &item)
69新增: _, err := os.Stat(filepath.Join(directory, "acknowledged"))
70新增: item["acknowledged"] = err == nil
71新增: reply = map[string]any{"available": true, "downloadAck": true, "downloads": []any{item}}
72新增: }
73新增: case "files-download-ack":
74新增: if len(request.IDs) != 1 || request.IDs[0] != record.ID {
75新增: return
76新增: }
77新增: if _, err := os.Stat(filepath.Join(directory, "fail-ack")); err == nil {
78新增: reply = map[string]string{"error": "desktop_download_manifest_failed"}
79新增: } else {
80新增: if os.WriteFile(filepath.Join(directory, "acknowledged"), nil, 0600) != nil {
81新增: return
82新增: }
83新增: reply = map[string]bool{"ok": true}
84新增: }
6585 case "files-download-open":
6686 if request.ID != record.ID {
6787 return
@@ -95,6 +115,69 @@ func serveDesktopDownloadFixture(input io.Reader, output io.Writer, directory st
95115 }
96116}
97117
118新增:func TestNativeDesktopDownloadAcknowledgesOnlySavedHostReceipts(t *testing.T) {
119新增: for _, system := range []string{"macos", "windows"} {
120新增: t.Run(system, func(t *testing.T) {
121新增: s, record, _, directory := nativeDesktopDownloadFixture(t, system)
122新增: poll := func() {
123新增: t.Helper()
124新增: response := windowsBrowserRequestForTest(s, http.MethodGet, "/api/input/files/desktop/requests", nil)
125新增: if response.Code != http.StatusOK {
126新增: t.Fatalf("poll failed: %d %s", response.Code, response.Body.String())
127新增: }
128新增: }
129新增: marker := func(name string) {
130新增: t.Helper()
131新增: if err := os.WriteFile(filepath.Join(directory, name), nil, 0600); err != nil {
132新增: t.Fatal(err)
133新增: }
134新增: }
135新增: ackCount := func() int {
136新增: t.Helper()
137新增: trace, err := os.ReadFile(filepath.Join(directory, "requests.jsonl"))
138新增: if err != nil {
139新增: t.Fatal(err)
140新增: }
141新增: return bytes.Count(trace, []byte(`"action":"files-download-ack"`))
142新增: }
143新增: marker("supports-ack")
144新增: poll()
145新增: if ackCount() != 0 {
146新增: t.Fatal("guest-only saved state acknowledged before a durable host copy")
147新增: }
148新增: if _, err := s.downloadInfo(t.Context(), record.ID); err != nil {
149新增: t.Fatal(err)
150新增: }
151新增: marker("fail-ack")
152新增: poll()
153新增: if ackCount() != 1 {
154新增: t.Fatal("saved host receipt was not acknowledged")
155新增: }
156新增: if saved, err := readSavedDownload(s.profile, record.ID); err != nil || saved.Path == "" {
157新增: t.Fatal("failed acknowledgment invalidated the host receipt", err)
158新增: }
159新增: if err := os.Remove(filepath.Join(directory, "fail-ack")); err != nil {
160新增: t.Fatal(err)
161新增: }
162新增: poll()
163新增: if ackCount() != 2 {
164新增: t.Fatal("failed acknowledgment was not retried")
165新增: }
166新增: poll()
167新增: if ackCount() != 2 {
168新增: t.Fatal("acknowledged guest record generated another acknowledgment")
169新增: }
170新增: if err := os.Remove(filepath.Join(directory, "supports-ack")); err != nil {
171新增: t.Fatal(err)
172新增: }
173新增: poll()
174新增: if ackCount() != 2 {
175新增: t.Fatal("legacy helper received an unsupported acknowledgment")
176新增: }
177新增: })
178新增: }
179新增:}
180新增:
98181func nativeDesktopDownloadFixture(t *testing.T, system string) (*Server, browserDownloadInfo, []byte, string) {
99182 t.Helper()
100183 directory := t.TempDir()
修改internal/workbench/native_routes.go+1 −0看文件
@@ -15,6 +15,7 @@ func nativeWorkbenchRoute(path string) bool {
1515 "/api/appearance", "/api/favorites", "/api/status", "/api/settings", "/api/settings/probe",
1616 "/api/start", "/api/stop", "/api/restore", "/api/host/git", "/api/projects/open", "/api/projects/directories",
1717 "/api/environment/initialization", "/api/environment/versions", "/api/environment/update", "/api/environment/tools", "/api/environment/resources", "/api/environment/storage",
18新增: "/api/environment/storage/recover",
1819 "/api/terminals", "/api/claude-accounts", "/api/cli/sessions", "/api/proxy", "/api/vault", "/api/vault/browser", "/api/client/browser-extensions",
1920 "/api/input", "/api/input/text", "/api/input/image", "/api/input/paste/start", "/api/input/paste/cancel", "/api/input/files/start", "/api/input/files/finish", "/api/input/files/cancel", "/api/input/files/directory", "/api/input/files/download-retry",
2021 "/api/vnc", "/api/vnc-credentials", "/api/audio", "/api/clipboard", "/api/clipboard/copy", "/api/clipboard/files",
新增internal/workbench/native_state_contract_test.go+73 −0看文件
@@ -0,0 +1,73 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "encoding/json"
5新增: "net/http"
6新增: "os"
7新增: "path/filepath"
8新增: "testing"
9新增:
10新增: "github.com/sylvinus/agent-vm/internal/guestos"
11新增:)
12新增:
13新增:func TestNativeStatusExposesMaintenanceFailureAndRestoreRoute(t *testing.T) {
14新增: for _, system := range []string{guestos.MacOS, guestos.Windows11} {
15新增: t.Run(system, func(t *testing.T) {
16新增: s := testServer(t)
17新增: if system == guestos.MacOS {
18新增: s.macosGuest = &guestos.MacOSProfile{Instance: "mac"}
19新增: } else {
20新增: s.windowsGuest = &guestos.WindowsProfile{}
21新增: }
22新增: cfg, err := loadConfig(s.configPath)
23新增: if err != nil {
24新增: t.Fatal(err)
25新增: }
26新增: previous := savedProfile{Config: cfg, Preferences: s.preferences}
27新增: previous.Preferences.Keyboard = "native"
28新增: if err := writePrivate(filepath.Join(s.profile, "previous-profile.json"), previous); err != nil {
29新增: t.Fatal(err)
30新增: }
31新增: s.guestUpdateRequired = true
32新增: s.guestUpdateError = "同步未完成,可保留原环境重试"
33新增: response := windowsBrowserRequestForTest(s, "GET", "/api/status", nil)
34新增: var state struct {
35新增: System string `json:"guest_system"`
36新增: CanRestore bool `json:"can_restore"`
37新增: UpdateRequired bool `json:"environment_update_required"`
38新增: UpdateError string `json:"environment_update_error"`
39新增: LocalStorage bool `json:"local_vm_storage"`
40新增: }
41新增: if response.Code != http.StatusOK || json.Unmarshal(response.Body.Bytes(), &state) != nil {
42新增: t.Fatal(response.Code, response.Body.String())
43新增: }
44新增: if state.System != system || !state.CanRestore || !state.UpdateRequired || state.UpdateError != s.guestUpdateError || !state.LocalStorage {
45新增: t.Fatalf("native state diverged from executable operations: %+v", state)
46新增: }
47新增: if storage := windowsBrowserRequestForTest(s, "GET", "/api/environment/storage", nil); storage.Code != http.StatusOK {
48新增: t.Fatal("advertised storage operation rejected by route", storage.Code, storage.Body.String())
49新增: }
50新增: response = windowsBrowserRequestForTest(s, "POST", "/api/restore", []byte(`{}`))
51新增: if response.Code != http.StatusOK {
52新增: t.Fatal("advertised restore rejected by native route", response.Code, response.Body.String())
53新增: }
54新增: job := awaitJobIdle(t, &s.jobs)
55新增: if job.Kind != "restore" {
56新增: t.Fatal("restore did not use the common operation", job)
57新增: }
58新增: var restored Preferences
59新增: data, err := os.ReadFile(filepath.Join(s.profile, "workbench.json"))
60新增: if err != nil {
61新增: t.Fatal(err)
62新增: }
63新增: if err := json.Unmarshal(data, &restored); err != nil {
64新增: t.Fatal(err)
65新增: }
66新增: if restored.Keyboard != "native" {
67新增: t.Fatal("normal restore route did not persist the prior preference")
68新增: }
69新增: // There is deliberately no VM in this fixture. Starting it may fail,
70新增: // after the requested configuration has reached its normal entry point.
71新增: })
72新增: }
73新增:}
修改internal/workbench/projects.go+37 −10看文件
@@ -90,6 +90,10 @@ func (s *Server) openProject(w http.ResponseWriter, r *http.Request) {
9090 }
9191 }
9292 if err != nil {
93新增: var failure *projectShareError
94新增: if errors.As(err, &failure) && failure.Recovery != "" {
95新增: w.Header().Set("X-Cage-Recovery", failure.Recovery)
96新增: }
9397 requestError(w, err)
9498 return
9599 }
@@ -132,6 +136,7 @@ type projectShare struct {
132136 approval string
133137 approvalTimer *time.Timer
134138 windowsProject *windowsProjectBinding
139新增: stderr *fileControlStderr
135140}
136141
137142func (p *projectShare) stop() {
@@ -193,15 +198,18 @@ func (s *Server) ensureProjectShare(path string) (returned error) {
193198 if closing {
194199 return errJobsClosed
195200 }
196删除: defer func() {
197删除: if returned == nil {
198删除: s.clearProjectError(path)
199删除: }
200删除: }()
201201 path, err := validateWorkspace(path, s.profile)
202202 if err != nil {
203203 return err
204204 }
205新增: defer func() {
206新增: if returned != nil {
207新增: if _, err := s.projectWorkspace(path); err != nil {
208新增: return
209新增: }
210新增: }
211新增: s.setProjectError(path, returned)
212新增: }()
205213 if s.windowsGuest != nil {
206214 return s.ensureWindowsProjectShare(path)
207215 }
@@ -280,19 +288,38 @@ type sharedProjects struct {
280288}
281289
282290type projectShareError struct {
283删除: Path string `json:"path"`
284删除: Message string `json:"message"`
291新增: Path string `json:"path"`
292新增: Message string `json:"message"`
293新增: Recovery string `json:"recovery,omitempty"`
294新增:}
295新增:
296新增:func (e *projectShareError) Error() string { return e.Message }
297新增:
298新增:func projectShareFailure(path string, err error) projectShareError {
299新增: value := projectShareError{Path: path, Message: err.Error()}
300新增: var failure *projectShareError
301新增: if errors.As(err, &failure) {
302新增: value.Recovery = failure.Recovery
303新增: }
304新增: return value
285305}
286306
287删除:func (s *Server) clearProjectError(path string) {
307新增:func (s *Server) setProjectError(path string, err error) {
288308 s.mu.Lock()
289309 defer s.mu.Unlock()
290310 for i, failure := range s.projectErrors {
291311 if failure.Path == path {
292删除: s.projectErrors = append(s.projectErrors[:i], s.projectErrors[i+1:]...)
312新增: if err == nil {
313新增: s.projectErrors = append(s.projectErrors[:i], s.projectErrors[i+1:]...)
314新增: } else {
315新增: s.projectErrors[i] = projectShareFailure(path, err)
316新增: }
293317 return
294318 }
295319 }
320新增: if err != nil {
321新增: s.projectErrors = append(s.projectErrors, projectShareFailure(path, err))
322新增: }
296323}
297324
298325// The saved directory grants are the project list. Include the default and
@@ -384,7 +411,7 @@ func (s *Server) restoreProjectShares() {
384411 var failures []projectShareError
385412 for _, path := range saved.Paths {
386413 if err := s.ensureProjectShare(path); err != nil {
387删除: failures = append(failures, projectShareError{Path: path, Message: err.Error()})
414新增: failures = append(failures, projectShareFailure(path, err))
388415 } else if err := s.rememberSharedProject(path); err != nil {
389416 failures = append(failures, projectShareError{Path: path, Message: "项目已连接,但未能保存项目记录:" + err.Error()})
390417 }
修改internal/workbench/readable_errors_test.go+33 −0看文件
@@ -2,6 +2,7 @@ package workbench
22
33import (
44 "context"
5新增: "errors"
56 "fmt"
67 "net/http"
78 "net/http/httptest"
@@ -9,6 +10,38 @@ import (
910 "testing"
1011)
1112
13新增:func TestWindowsMaintenanceFailureRetainsStageForBothJobs(t *testing.T) {
14新增: cause := errors.New("synthetic maintenance process failed")
15新增: for _, action := range []string{"修复 Windows 系统助手", "更新原生客机组件"} {
16新增: for _, test := range []struct {
17新增: phase, reason, next string
18新增: }{
19新增: {"AUTHORIZATION_CANCELED", "已取消 Windows 管理员授权", "系统授权窗口"},
20新增: {"AUTHORIZATION", "授权窗口未能打开", "本机 Cage"},
21新增: {"VALIDATION", "绑定或组件清单", "重新安装完整 Cage"},
22新增: {"HOST_MANAGER", "系统管理助手安装", "修复系统助手"},
23新增: {"GUEST_CONNECTION", "客机连接未完成", "管理员账户"},
24新增: {"GUEST_COMPONENTS", "客机组件安装", "同步环境组件"},
25新增: {"HOST_RELAY", "主机连接组件更新", "占用连接组件"},
26新增: {"PACKAGE_PREPARATION", "组件包准备", "系统盘空间"},
27新增: {"FAILED", "Windows 维护未完成", "导出诊断包"},
28新增: } {
29新增: t.Run(action+"/"+test.phase, func(t *testing.T) {
30新增: output := "CAGE_WINDOWS_MAINTENANCE_" + test.phase + " synthetic stage\naccess is denied token=private-stage-secret"
31新增: err := executionFailure(action, cause, output)
32新增: for _, want := range []string{action, test.reason, test.next} {
33新增: if !strings.Contains(err.Error(), want) {
34新增: t.Fatalf("lost maintenance stage or next action %q: %v", want, err)
35新增: }
36新增: }
37新增: if !errors.Is(err, cause) || strings.Contains(err.Error(), "private-stage-secret") {
38新增: t.Fatal("stage handling lost the cause or exposed arbitrary process output", err)
39新增: }
40新增: })
41新增: }
42新增: }
43新增:}
44新增:
1245func TestBrowserFailureExplainsOperationAndKnownCause(t *testing.T) {
1346 for _, tc := range []struct {
1447 status int
修改internal/workbench/remote_gateway.go+1 −1看文件
@@ -271,7 +271,7 @@ func (s *Server) routeRemote(w http.ResponseWriter, r *http.Request) bool {
271271 http.NotFound(w, r)
272272 return true
273273 }
274删除: if remote && r.URL.Path == "/api/environment/storage" {
274新增: if remote && (r.URL.Path == "/api/environment/storage" || r.URL.Path == "/api/environment/storage/recover") {
275275 http.Error(w, "请在虚拟机所在电脑上调整环境存储", http.StatusForbidden)
276276 return true
277277 }
修改internal/workbench/runtime.go+10 −0看文件
@@ -134,6 +134,9 @@ func (s *Server) guestControl(ctx context.Context, script, diagnosticSource stri
134134 return data, nil
135135}
136136func (s *Server) attach() error {
137新增: if err := s.requireStorageReady(); err != nil {
138新增: return err
139新增: }
137140 if s.windowsGuest != nil {
138141 return s.attachWindowsGuest()
139142 }
@@ -304,6 +307,9 @@ func (s *Server) runCage(args ...string) error {
304307 return nil
305308}
306309func (s *Server) startEnvironment(syncTimezone bool) error {
310新增: if err := s.requireStorageReady(); err != nil {
311新增: return err
312新增: }
307313 if s.macosGuest != nil {
308314 return s.startMacOSGuest()
309315 }
@@ -622,6 +628,10 @@ func (s *Server) apply(v savedProfile, validate bool) error {
622628func (s *Server) monitorNetworkTick() {
623629 timing := s.startMonitorTiming()
624630 defer s.recordMonitorTiming("network", timing)
631新增: if s.storageRecoveryStatus().Required {
632新增: timing.result = "storage_recovery_pending"
633新增: return
634新增: }
625635 if s.macSetupPending() {
626636 timing.result = "setup_pending"
627637 return
修改internal/workbench/runtime_failure_test.go+2 −0看文件
@@ -41,6 +41,8 @@ func TestRunCageExplainsCommonFailure(t *testing.T) {
4141 {"curl: (28) Operation timed out", "超时"},
4242 {"E: No space left on device", "空间不足"},
4343 {"curl: (60) certificate verify failed", "证书验证"},
44新增: {"CAGE_WINDOWS_MAINTENANCE_HOST_MANAGER synthetic stage token=private-error-secret", "系统管理助手安装未完成"},
45新增: {"CAGE_WINDOWS_MAINTENANCE_GUEST_CONNECTION synthetic stage token=private-error-secret", "客机连接未完成"},
4446 {"unrecognized failure token=private-error-secret", "退出码 7"},
4547 } {
4648 t.Run(tc.want, func(t *testing.T) {
修改internal/workbench/server.go+28 −6看文件
@@ -45,6 +45,8 @@ type Server struct {
4545 agentNativeQueue agentNativeQueue
4646 macSetupProjectsChecked time.Time
4747 macSetupProjectsAttempt time.Time
48新增: macProjectsRetryAt time.Time
49新增: macLoginLease *macLoginLease
4850 macosGuest *guestos.MacOSProfile
4951 macResources macOSResourceObserver
5052 windowsGuest *guestos.WindowsProfile
@@ -65,6 +67,7 @@ type Server struct {
6567 guestManifest *cage.GuestManifest
6668 guestUpdateRequired bool
6769 guestUpdateError string
70新增: storageRecoveryError string
6871 closing bool
6972 shutdown func()
7073 claudeAccounts claudeAccountManager
@@ -198,7 +201,7 @@ func serve(configPath string, clientOnly bool, fullConfigPath string) (returned
198201 defer s.remote.close()
199202 if workload {
200203 if err = guestos.RecoverWindowsStorage(context.Background(), profile); err != nil {
201删除: return err
204新增: s.failStorageRecovery(err)
202205 }
203206 s.macosGuest, err = guestos.LoadMacOSProfile(profile)
204207 if err != nil {
@@ -235,8 +238,13 @@ func serve(configPath string, clientOnly bool, fullConfigPath string) (returned
235238 s.preferences.AutoLanguage = false
236239 _ = json.Unmarshal(b, &s.preferences)
237240 }
238删除: if err = s.prepareEnvironment(); err != nil {
239删除: return err
241新增: if !s.storageRecoveryStatus().Required {
242新增: if err = s.prepareEnvironment(); err != nil {
243新增: if s.windowsGuest == nil {
244新增: return err
245新增: }
246新增: s.failStorageRecovery(err)
247新增: }
240248 }
241249 // Invalid intent keeps the gate paused and its error visible in status.
242250 s.restoreNetworkIntent()
@@ -382,6 +390,7 @@ func (s *Server) handler() http.Handler {
382390 mux.HandleFunc("POST /api/environment/guest-systems/activate", s.guestInstallation)
383391 mux.HandleFunc("GET /api/environment/storage", s.environmentStorage)
384392 mux.HandleFunc("POST /api/environment/storage", s.environmentStorage)
393新增: mux.HandleFunc("POST /api/environment/storage/recover", s.recoverEnvironmentStorage)
385394 mux.HandleFunc("GET /api/environment/resources", s.resourceStatus)
386395 mux.HandleFunc("POST /api/environment/resources", s.applyResources)
387396 mux.HandleFunc("POST /api/environment/update", s.updateEnvironment)
@@ -447,6 +456,7 @@ func (s *Server) handler() http.Handler {
447456 if s.macosGuest != nil {
448457 mux.HandleFunc("POST /api/macos/first-setup", s.macOSLoginWindow)
449458 mux.HandleFunc("POST /api/macos/login", s.macOSLoginWindow)
459新增: mux.HandleFunc("POST /api/macos/maintenance", s.macOSLoginWindow)
450460 s.registerMacOSClaudeRoutes(mux)
451461 s.registerMacOSBrowserRoutes(mux)
452462 mux.HandleFunc("POST /api/macos/project-approval", s.macOSProjectApproval)
@@ -581,6 +591,12 @@ func (s *Server) handler() http.Handler {
581591 panic(failure)
582592 }
583593 }()
594新增: if !storageRecoveryRoute(r) {
595新增: if err := s.requireStorageReady(); err != nil {
596新增: http.Error(w, err.Error(), http.StatusConflict)
597新增: return
598新增: }
599新增: }
584600 mux.ServeHTTP(w, r)
585601 })
586602}
@@ -615,7 +631,7 @@ func requestError(w http.ResponseWriter, err error) {
615631 http.Error(w, err.Error(), http.StatusBadRequest)
616632}
617633func (s *Server) status(w http.ResponseWriter, r *http.Request) {
618删除: if s.windowsGuest != nil {
634新增: if s.windowsGuest != nil && !s.storageRecoveryStatus().Required {
619635 s.refreshWindowsComponents()
620636 }
621637 projects, err := s.projectPaths()
@@ -637,8 +653,10 @@ func (s *Server) status(w http.ResponseWriter, r *http.Request) {
637653 view := map[string]any{
638654 "projects": projects, "ready": s.ready, "vm_running": running,
639655 "workspace": s.workspaceLocked(), "environment_workspace": s.workspaceLocked() == s.environmentDir(), "environment_directory": s.environmentDir(),
640删除: "local_vm_storage": s.localVMStorage(), "project_error": projectError, "project_errors": s.projectErrors,
641删除: "keyboard": s.preferences.Keyboard, "auto_timezone": s.preferences.AutoTimezone, "job": s.jobs.snapshot(),
656新增: "environment_identity_directory": cage.EnvironmentIdentityDir(s.profile),
657新增: "local_vm_storage": s.localVMStorage(), "project_error": projectError, "project_errors": s.projectErrors,
658新增: "storage_recovery": s.storageRecoveryStatusLocked(),
659新增: "keyboard": s.preferences.Keyboard, "auto_timezone": s.preferences.AutoTimezone, "job": s.jobs.snapshot(),
642660 "location": s.location, "network_error": s.currentNetworkErrorLocked(), "can_restore": e == nil,
643661 "safety": s.safety, "environment_update_required": s.guestUpdateRequired, "environment_update_error": s.guestUpdateError,
644662 }
@@ -810,6 +828,10 @@ func (s *Server) stop(w http.ResponseWriter, r *http.Request) {
810828}
811829
812830func (s *Server) requestStop(w http.ResponseWriter, logout bool) {
831新增: if err := s.requireStorageReady(); err != nil {
832新增: http.Error(w, err.Error(), http.StatusConflict)
833新增: return
834新增: }
813835 for _, name := range []string{cage.InstanceName(s.profile, s.environmentDir()), "base-building"} {
814836 if owner := cage.InstanceJobID(filepath.Join(s.profile, "state"), name); owner != "" {
815837 _ = cage.RequestJobStop(s.profile, owner)
修改internal/workbench/settings.go+29 −24看文件
@@ -54,24 +54,13 @@ func environmentWorkspace(profile string) string { return cage.EnvironmentDir(pr
5454func guestPath(path string) string { return paths.Guest(paths.Host(path)) }
5555
5656func (s *Server) prepareEnvironment() error {
57删除: if s.windowsGuest != nil {
58删除: path := s.environmentDir()
59删除: if err := os.MkdirAll(path, 0700); err != nil {
60删除: return err
61删除: }
62删除: if _, err := validateWorkspace(path, s.profile); err != nil {
63删除: return err
64删除: }
65删除: if err := writePrivate(filepath.Join(s.profile, "environment.json"), map[string]string{"directory": path}); err != nil {
66删除: return err
67删除: }
68删除: s.mu.Lock()
69删除: if s.preferences.Workspace == "" {
70删除: s.preferences.Workspace = s.environmentDir()
71删除: }
72删除: s.mu.Unlock()
73删除: return nil
57新增: record, err := cage.LoadEnvironmentRecord(s.profile)
58新增: if err != nil {
59新增: return err
7460 }
61新增: s.mu.Lock()
62新增: p := s.preferences
63新增: s.mu.Unlock()
7564 path := environmentWorkspace(s.profile)
7665 // Promote an existing installation's VM once, preserving its disk and login state.
7766 if _, err := os.Stat(filepath.Join(s.profile, "environment.json")); os.IsNotExist(err) {
@@ -85,17 +74,33 @@ func (s *Server) prepareEnvironment() error {
8574 if err := os.MkdirAll(path, 0700); err != nil {
8675 return err
8776 }
88删除: path, err := validateWorkspace(path, s.profile)
77新增: previous := path
78新增: path, err = validateWorkspace(path, s.profile)
8979 if err != nil {
90删除: return err
80新增: // Older independent profiles generated their default workspace inside
81新增: // the default profile. Keep its files and VM identity while selecting a
82新增: // shareable workspace through the same admission used for every project.
83新增: path, err = validateWorkspace(p.Workspace, s.profile)
84新增: if p.Workspace == "" || err != nil {
85新增: path = cage.DefaultEnvironmentDir(s.profile)
86新增: if err = os.MkdirAll(path, 0700); err != nil {
87新增: return err
88新增: }
89新增: path, err = validateWorkspace(path, s.profile)
90新增: if err != nil {
91新增: return err
92新增: }
93新增: }
94新增: if record.IdentityDirectory == "" {
95新增: record.IdentityDirectory = previous
96新增: }
9197 }
92删除: if err = writePrivate(filepath.Join(s.profile, "environment.json"), map[string]string{"directory": path}); err != nil {
98新增: record.Directory = path
99新增: if err = writePrivate(filepath.Join(s.profile, "environment.json"), record); err != nil {
93100 return err
94101 }
95删除: s.mu.Lock()
96删除: p := s.preferences
97删除: s.mu.Unlock()
98删除: if p.Workspace == "" {
102新增: if p.Workspace == "" || paths.Equal(paths.Host(p.Workspace), paths.Host(previous)) ||
103新增: record.IdentityDirectory != "" && paths.Equal(paths.Host(p.Workspace), paths.Host(record.IdentityDirectory)) {
99104 p.Workspace = path
100105 }
101106 if err := writePrivate(filepath.Join(s.profile, "workbench.json"), p); err != nil {
修改internal/workbench/shared_clipboard.go+8 −14看文件
@@ -9,7 +9,6 @@ import (
99 "io"
1010 "net/http"
1111 "net/url"
12删除: "os"
1312 "os/exec"
1413 "path/filepath"
1514 "slices"
@@ -494,8 +493,8 @@ func readClipboardArchive(input io.Reader) ([]string, error) {
494493
495494// A tar EOF only ends the archive, not the guest process. Drain the HTTP body
496495// before checking the producer's completion trailer or publishing local paths.
497删除:func receiveClipboardArchive(response *http.Response) ([]string, error) {
498删除: paths, err := readClipboardArchive(response.Body)
496新增:func receiveClipboardArchive(response *http.Response, cache clipboardfiles.CacheStore) (clipboardfiles.CachedSelection, error) {
497新增: selection, err := cache.Read(response.Body)
499498 if err == nil {
500499 _, err = io.Copy(io.Discard, response.Body)
501500 }
@@ -503,12 +502,12 @@ func receiveClipboardArchive(response *http.Response) ([]string, error) {
503502 err = errors.New("剪贴板文件传递中断,请重新复制")
504503 }
505504 if err != nil {
506删除: if len(paths) != 0 {
507删除: _ = os.RemoveAll(filepath.Dir(paths[0]))
505新增: if selection.ID != "" {
506新增: _ = cache.Release(selection.ID)
508507 }
509删除: return nil, err
508新增: return clipboardfiles.CachedSelection{}, err
510509 }
511删除: return paths, nil
510新增: return selection, nil
512511}
513512
514513// Native helpers stream bytes directly, keeping host paths out of the WebView.
@@ -571,16 +570,11 @@ func ClipboardFilesForConnection(configPath, connectionID, operation string, arg
571570 return nil, errors.New("剪贴板文件传递失败,请重新复制")
572571 }
573572 if method == "GET" {
574删除: paths, err := receiveClipboardArchive(response)
575删除: if err != nil {
576删除: return nil, err
577删除: }
578删除: selection, err := cache.Register(paths)
573新增: selection, err := receiveClipboardArchive(response, cache)
579574 if err != nil {
580删除: _ = os.RemoveAll(filepath.Dir(paths[0]))
581575 return nil, err
582576 }
583删除: return map[string]any{"paths": paths, "cache_id": selection.ID}, nil
577新增: return map[string]any{"paths": selection.Paths, "cache_id": selection.ID}, nil
584578 }
585579 var result map[string]any
586580 err = json.NewDecoder(io.LimitReader(response.Body, 65537)).Decode(&result)
修改internal/workbench/shared_clipboard_test.go+7 −3看文件
@@ -15,6 +15,7 @@ import (
1515 "time"
1616
1717 "github.com/gorilla/websocket"
18新增: "github.com/sylvinus/agent-vm/internal/clipboardfiles"
1819 "github.com/sylvinus/agent-vm/internal/guestos"
1920)
2021
@@ -94,12 +95,14 @@ func TestClipboardReceiveRequiresProducerCompletion(t *testing.T) {
9495 t.Fatal(err)
9596 }
9697 defer response.Body.Close()
97删除: paths, err := receiveClipboardArchive(response)
98新增: cache := clipboardfiles.CacheStore{Directory: filepath.Join(t.TempDir(), "records")}
99新增: selection, err := receiveClipboardArchive(response, cache)
100新增: paths := selection.Paths
98101 if status == "ok" {
99102 if err != nil || len(paths) != 1 {
100103 t.Fatalf("completed transfer failed: %v", err)
101104 }
102删除: defer os.RemoveAll(filepath.Dir(paths[0]))
105新增: defer cache.Release(selection.ID)
103106 data, _ := os.ReadFile(paths[0])
104107 if string(data) != "complete bytes" {
105108 t.Fatal("file content changed")
@@ -117,7 +120,8 @@ func TestClipboardReceiveRequiresProducerCompletion(t *testing.T) {
117120 }
118121 // Losing the connection before all file bytes arrive must not create a file.
119122 response := &http.Response{Body: io.NopCloser(bytes.NewReader(archive.Bytes()[:520])), Trailer: http.Header{"X-Cage-Clipboard-Status": {"ok"}}}
120删除: if paths, err := receiveClipboardArchive(response); err == nil || len(paths) != 0 {
123新增: cache := clipboardfiles.CacheStore{Directory: filepath.Join(t.TempDir(), "records")}
124新增: if selection, err := receiveClipboardArchive(response, cache); err == nil || len(selection.Paths) != 0 {
121125 t.Fatal("truncated archive succeeded")
122126 }
123127}
修改internal/workbench/storage.go+122 −3看文件
@@ -5,9 +5,12 @@ import (
55 "fmt"
66 "net/http"
77 "os"
8新增: "runtime"
9新增: "strings"
810
911 "github.com/sylvinus/agent-vm/internal/cage"
1012 "github.com/sylvinus/agent-vm/internal/containerenv"
13新增: "github.com/sylvinus/agent-vm/internal/diagnostics"
1114 "github.com/sylvinus/agent-vm/internal/guestos"
1215)
1316
@@ -15,18 +18,129 @@ func (s *Server) localVMStorage() bool {
1518 return !s.clientOnly && !containerenv.Configured(s.profile)
1619}
1720
21新增:type storageRecoveryView struct {
22新增: Required bool `json:"required"`
23新增: Error string `json:"error,omitempty"`
24新增: RepairAllowed bool `json:"repair_allowed"`
25新增:}
26新增:
27新增:func (s *Server) storageRecoveryStatusLocked() storageRecoveryView {
28新增: return storageRecoveryView{
29新增: Required: s.storageRecoveryError != "", Error: s.storageRecoveryError,
30新增: RepairAllowed: s.storageRecoveryError != "" && s.windowsGuest != nil && runtime.GOOS == "windows",
31新增: }
32新增:}
33新增:
34新增:func (s *Server) storageRecoveryStatus() storageRecoveryView {
35新增: s.mu.Lock()
36新增: defer s.mu.Unlock()
37新增: return s.storageRecoveryStatusLocked()
38新增:}
39新增:
40新增:func (s *Server) requireStorageReady() error {
41新增: state := s.storageRecoveryStatus()
42新增: if state.Required {
43新增: return fmt.Errorf("环境存储待恢复,请在设置中恢复后继续。%s", state.Error)
44新增: }
45新增: return nil
46新增:}
47新增:
48新增:func (s *Server) failStorageRecovery(err error) error {
49新增: s.mu.Lock()
50新增: s.storageRecoveryError = err.Error()
51新增: s.ready = false
52新增: s.mu.Unlock()
53新增: diagnostics.Log("error", "storage", "environment storage recovery failed: "+err.Error())
54新增: return err
55新增:}
56新增:
57新增:// Recovery keeps local account access and host diagnostics available. Guest
58新增:// reads can also create sessions, so admission names the host-only reads.
59新增:func storageRecoveryRoute(r *http.Request) bool {
60新增: path := r.URL.Path
61新增: if !strings.HasPrefix(path, "/api/") || strings.HasPrefix(path, "/api/account/") || strings.HasPrefix(path, "/api/diagnostics") {
62新增: return true
63新增: }
64新增: switch path {
65新增: case "/api/account", "/api/session", "/api/launch", "/api/handoff", "/api/remote/manifest", "/api/environment/storage/recover":
66新增: return true
67新增: }
68新增: if r.Method == http.MethodGet {
69新增: switch path {
70新增: case "/api/status", "/api/settings", "/api/appearance", "/api/favorites", "/api/proxy", "/api/agent/routes", "/api/environment/storage", "/api/environment/initialization":
71新增: return true
72新增: }
73新增: }
74新增: return false
75新增:}
76新增:
77新增:func (s *Server) recoverEnvironmentStorage(w http.ResponseWriter, r *http.Request) {
78新增: if !s.localVMStorage() {
79新增: http.Error(w, "请在虚拟机所在电脑上恢复环境存储", http.StatusConflict)
80新增: return
81新增: }
82新增: if !s.storageRecoveryStatus().Required {
83新增: http.Error(w, "当前环境存储无需恢复", http.StatusConflict)
84新增: return
85新增: }
86新增: var input struct {
87新增: Repair bool `json:"repair"`
88新增: }
89新增: if !readJSON(w, r, &input) {
90新增: return
91新增: }
92新增: s.launch(w, "storage-recovery", func() error {
93新增: if input.Repair {
94新增: s.setMessage("正在修复 Windows 系统助手,请完成系统授权…")
95新增: kit, _ := s.nativeComponentKit()
96新增: if err := guestos.RepairWindowsHostManager(s.operationContext(), s.profile, kit, s.jobs.execution(), s.jobs.execution()); err != nil {
97新增: return s.failStorageRecovery(executionFailure("修复 Windows 系统助手", err, s.jobs.snapshot().Log))
98新增: }
99新增: }
100新增: s.setMessage("正在恢复环境存储并检查数据位置…")
101新增: if err := guestos.RecoverWindowsStorage(s.operationContext(), s.profile); err != nil {
102新增: return s.failStorageRecovery(err)
103新增: }
104新增: if _, err := cage.GetStorageLocation(s.profile); err != nil {
105新增: return s.failStorageRecovery(err)
106新增: }
107新增: if s.windowsGuest != nil {
108新增: binding, err := guestos.LoadWindowsProfile(s.profile)
109新增: if err != nil {
110新增: return s.failStorageRecovery(err)
111新增: }
112新增: if binding == nil || binding.VMID != s.windowsGuest.VMID || binding.GUIUserSID != s.windowsGuest.GUIUserSID {
113新增: return s.failStorageRecovery(errors.New("Windows 客机绑定已改变,请重新打开原工作台后恢复"))
114新增: }
115新增: }
116新增: if err := s.prepareEnvironment(); err != nil {
117新增: return s.failStorageRecovery(err)
118新增: }
119新增: s.mu.Lock()
120新增: s.storageRecoveryError = ""
121新增: s.mu.Unlock()
122新增: s.setMessage("环境存储已恢复,可以启动环境")
123新增: return nil
124新增: })
125新增:}
126新增:
18127func (s *Server) environmentStorage(w http.ResponseWriter, r *http.Request) {
19128 if !s.localVMStorage() {
20129 http.Error(w, "仅本机虚拟机支持调整存储位置", http.StatusConflict)
21130 return
22131 }
23132 if r.Method == http.MethodGet {
24删除: if err := guestos.RecoverWindowsStorage(r.Context(), s.profile); err != nil {
25删除: requestError(w, err)
133新增: if recovery := s.storageRecoveryStatus(); recovery.Required {
134新增: jsonReply(w, map[string]any{"recovery": recovery})
26135 return
27136 }
28137 location, err := cage.GetStorageLocation(s.profile)
29138 if err != nil {
139新增: if errors.Is(err, cage.ErrStorageRuntimeRecovery) {
140新增: s.failStorageRecovery(err)
141新增: jsonReply(w, map[string]any{"recovery": s.storageRecoveryStatus()})
142新增: return
143新增: }
30144 requestError(w, err)
31145 return
32146 }
@@ -58,7 +172,7 @@ func (s *Server) environmentStorage(w http.ResponseWriter, r *http.Request) {
58172 }
59173 s.launch(w, "storage", func() error {
60174 if err := guestos.RecoverWindowsStorage(s.operationContext(), s.profile); err != nil {
61删除: return err
175新增: return s.failStorageRecovery(err)
62176 }
63177 current, err := cage.GetStorageLocation(s.profile)
64178 if err != nil {
@@ -89,6 +203,11 @@ func (s *Server) environmentStorage(w http.ResponseWriter, r *http.Request) {
89203 _, err = cage.MoveStorageWithRuntime(s.operationContext(), s.profile, input.Directory, current, runtime, func(copied, total int64) {
90204 s.setMessage(fmt.Sprintf("正在迁移环境数据 · %.1f / %.1f GiB", float64(copied)/(1<<30), float64(total)/(1<<30)))
91205 })
206新增: if err != nil {
207新增: if _, recoveryErr := cage.GetStorageLocation(s.profile); errors.Is(recoveryErr, cage.ErrStorageRuntimeRecovery) {
208新增: return s.failStorageRecovery(err)
209新增: }
210新增: }
92211 if errors.Is(err, os.ErrPermission) {
93212 return errors.New("无法写入所选存储目录。请在当前页面选择有写入权限的本地文件夹后重试,已有数据已保留")
94213 }
修改internal/workbench/storage_paths.go+2 −0看文件
@@ -6,6 +6,7 @@ import (
66 "path/filepath"
77
88 "github.com/sylvinus/agent-vm/internal/cage"
9新增: "github.com/sylvinus/agent-vm/internal/guestos"
910 "github.com/sylvinus/agent-vm/internal/mounts"
1011 "github.com/sylvinus/agent-vm/internal/paths"
1112)
@@ -40,6 +41,7 @@ func privateProjectDirectories(profile string) ([]string, error) {
4041 return nil, err
4142 }
4243 directories = append(directories, profile)
44新增: directories = append(directories, guestos.WindowsPrivateStoragePaths()...)
4345 for _, directory := range directories {
4446 physical, err := cage.StoragePhysicalPath(directory)
4547 if os.IsNotExist(err) {
新增internal/workbench/storage_recovery_test.go+406 −0看文件
@@ -0,0 +1,406 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "archive/zip"
5新增: "bytes"
6新增: "context"
7新增: "encoding/json"
8新增: "errors"
9新增: "fmt"
10新增: "io"
11新增: "net/http"
12新增: "net/http/cookiejar"
13新增: "net/url"
14新增: "os"
15新增: "os/exec"
16新增: "path/filepath"
17新增: "runtime"
18新增: "strings"
19新增: "testing"
20新增: "time"
21新增:
22新增: "github.com/google/uuid"
23新增: "github.com/sylvinus/agent-vm/internal/guestos"
24新增:)
25新增:
26新增:func storageRecoveryServer(t *testing.T) *Server {
27新增: t.Helper()
28新增: s := testServer(t)
29新增: workspace := filepath.Join(t.TempDir(), "workspace")
30新增: if err := writePrivate(filepath.Join(s.profile, "environment.json"), map[string]string{"directory": workspace}); err != nil {
31新增: t.Fatal(err)
32新增: }
33新增: instance := filepath.Join(s.profile, "state", "guest-os", "synthetic-vm")
34新增: if err := os.MkdirAll(instance, 0700); err != nil {
35新增: t.Fatal(err)
36新增: }
37新增: binding := guestos.WindowsProfile{
38新增: Version: 1, VMID: uuid.New(), GUIUserSID: "S-1-5-21-1-2-3-1001",
39新增: InstanceDirectory: instance, RelayExecutable: filepath.Join(instance, "missing-relay.exe"),
40新增: PairingFile: filepath.Join(instance, "synthetic-pairing.dpapi"),
41新增: }
42新增: if err := guestos.BindWindowsProfile(s.profile, binding); err != nil {
43新增: t.Fatal(err)
44新增: }
45新增: s.windowsGuest = &binding
46新增: return s
47新增:}
48新增:
49新增:func storageRecoveryJournal(t *testing.T, s *Server) string {
50新增: t.Helper()
51新增: id := strings.Repeat("a", 32)
52新增: target := filepath.Join(t.TempDir(), "destination")
53新增: journal := filepath.Join(s.profile, "environment-storage-pending.json")
54新增: if err := writePrivate(journal, map[string]any{
55新增: "Next": map[string]any{"Directory": target, "ID": id},
56新增: "Runtime": "windows-hyperv",
57新增: "Transition": map[string]any{
58新增: "id": id, "source": filepath.Join(s.profile, "state"),
59新增: "destination": filepath.Join(target, "state"), "backup": filepath.Join(s.profile, "state-backup-"+id),
60新增: "state": map[string]any{
61新增: "profile": s.windowsGuest, "instance": s.windowsGuest.InstanceDirectory,
62新增: "disk": map[string]any{"path": filepath.Join(s.windowsGuest.InstanceDirectory, "disk.vhdx"), "volume": 1, "file_id": 2},
63新增: },
64新增: },
65新增: }); err != nil {
66新增: t.Fatal(err)
67新增: }
68新增: return journal
69新增:}
70新增:
71新增:func TestStorageRecoveryKeepsHostAccessAndBlocksEnvironmentMutations(t *testing.T) {
72新增: s := storageRecoveryServer(t)
73新增: s.ready = true
74新增: s.windowsState.Running = true
75新增: s.networkIntentError = "synthetic independent network failure"
76新增: s.failStorageRecovery(errors.New("synthetic system manager unavailable"))
77新增: for _, endpoint := range []string{"/api/account", "/api/status", "/api/settings", "/api/environment/storage", "/api/environment/initialization", "/api/diagnostics", "/api/diagnostics/export"} {
78新增: response := windowsBrowserRequestForTest(s, http.MethodGet, endpoint, nil)
79新增: if response.Code != http.StatusOK {
80新增: t.Fatalf("host access %s returned %d %s", endpoint, response.Code, response.Body.String())
81新增: }
82新增: if endpoint == "/api/status" {
83新增: var view struct {
84新增: Ready bool `json:"ready"`
85新增: NetworkError string `json:"network_error"`
86新增: StorageRecovery storageRecoveryView `json:"storage_recovery"`
87新增: }
88新增: if err := json.Unmarshal(response.Body.Bytes(), &view); err != nil {
89新增: t.Fatal(err)
90新增: }
91新增: if view.Ready || !view.StorageRecovery.Required || view.StorageRecovery.Error != "synthetic system manager unavailable" || view.NetworkError != s.networkIntentError {
92新增: t.Fatal("recovery did not preserve the independent causes", view)
93新增: }
94新增: }
95新增: if endpoint == "/api/diagnostics/export" {
96新增: if _, err := zip.NewReader(bytes.NewReader(response.Body.Bytes()), int64(response.Body.Len())); err != nil {
97新增: t.Fatal("pending recovery prevented a valid diagnostic export", err)
98新增: }
99新增: }
100新增: }
101新增: for _, endpoint := range []string{
102新增: "/api/start", "/api/stop", "/api/settings", "/api/projects/open", "/api/environment/resources",
103新增: "/api/environment/storage", "/api/environment/update", "/api/environment/initialization",
104新增: "/api/browser/open", "/api/input", "/api/input/paste/start", "/api/clipboard/copy", "/api/account/logout",
105新增: } {
106新增: response := windowsBrowserRequestForTest(s, http.MethodPost, endpoint, []byte(`{}`))
107新增: if response.Code != http.StatusConflict || !strings.Contains(response.Body.String(), "synthetic system manager unavailable") {
108新增: t.Fatalf("mutation %s reached its receiver: %d %s", endpoint, response.Code, response.Body.String())
109新增: }
110新增: }
111新增: for _, endpoint := range []string{"/api/browser/state", "/api/vnc", "/api/terminals", "/api/audio"} {
112新增: if response := windowsBrowserRequestForTest(s, http.MethodGet, endpoint, nil); response.Code != http.StatusConflict {
113新增: t.Fatalf("guest session %s was admitted: %d", endpoint, response.Code)
114新增: }
115新增: }
116新增: if err := s.attachWindowsGuestContext(context.Background()); err == nil || !strings.Contains(err.Error(), "synthetic system manager unavailable") {
117新增: t.Fatal("periodic attach bypassed recovery", err)
118新增: }
119新增: if err := s.startWindowsGuest(); err == nil || !strings.Contains(err.Error(), "synthetic system manager unavailable") {
120新增: t.Fatal("direct start bypassed recovery", err)
121新增: }
122新增: if _, err := s.submitJob("network-recovery", func() error { t.Error("background mutation ran"); return nil }); err == nil {
123新增: t.Fatal("background job bypassed recovery")
124新增: }
125新增: s.monitorNetworkTick()
126新增: if s.jobs.snapshot().ID != "" {
127新增: t.Fatal("recovery gate created an environment job")
128新增: }
129新增:}
130新增:
131新增:func TestStorageRecoverySuccessfulRetryPreparesEnvironmentAndPreservesBinding(t *testing.T) {
132新增: s := storageRecoveryServer(t)
133新增: original, err := os.ReadFile(guestos.WindowsProfilePath(s.profile))
134新增: if err != nil {
135新增: t.Fatal(err)
136新增: }
137新增: s.failStorageRecovery(errors.New("previous attempt lost its helper connection"))
138新增: response := windowsBrowserRequestForTest(s, http.MethodPost, "/api/environment/storage/recover", []byte(`{}`))
139新增: if response.Code != http.StatusOK {
140新增: t.Fatal(response.Code, response.Body.String())
141新增: }
142新增: job := awaitJobIdle(t, &s.jobs)
143新增: if job.Error != "" || job.Kind != "storage-recovery" || s.storageRecoveryStatus().Required || s.ready {
144新增: t.Fatal("successful retry failed to restore admission without starting a VM", job, s.storageRecoveryStatus())
145新增: }
146新增: if info, err := os.Stat(s.environmentDir()); err != nil || !info.IsDir() {
147新增: t.Fatal("normal environment preparation did not run", err)
148新增: }
149新增: if current, err := os.ReadFile(guestos.WindowsProfilePath(s.profile)); err != nil || !bytes.Equal(current, original) {
150新增: t.Fatal("retry changed VM or pairing identity", err)
151新增: }
152新增: if response := windowsBrowserRequestForTest(s, http.MethodGet, "/api/environment/storage", nil); response.Code != http.StatusOK || !strings.Contains(response.Body.String(), `"directory"`) {
153新增: t.Fatal("recovered storage form remained unavailable", response.Code, response.Body.String())
154新增: }
155新增: admitted := false
156新增: if _, err := s.submitJob("start", func() error { admitted = true; return nil }); err != nil {
157新增: t.Fatal("successful recovery kept normal start admission closed", err)
158新增: }
159新增: awaitJobIdle(t, &s.jobs)
160新增: if !admitted {
161新增: t.Fatal("normal start was not executed")
162新增: }
163新增:}
164新增:
165新增:func TestStorageRecoveryFailureAndReadOnlyLocationPreserveJournal(t *testing.T) {
166新增: if runtime.GOOS == "windows" {
167新增: t.Skip("the synthetic native journal uses the non-Windows rejection without contacting a real Hyper-V service")
168新增: }
169新增: s := storageRecoveryServer(t)
170新增: journal := storageRecoveryJournal(t, s)
171新增: original, err := os.ReadFile(journal)
172新增: if err != nil {
173新增: t.Fatal(err)
174新增: }
175新增: response := windowsBrowserRequestForTest(s, http.MethodGet, "/api/environment/storage", nil)
176新增: if response.Code != http.StatusOK || !s.storageRecoveryStatus().Required {
177新增: t.Fatal("location did not expose native recovery", response.Code, response.Body.String())
178新增: }
179新增: for _, repair := range []bool{false, true} {
180新增: response = windowsBrowserRequestForTest(s, http.MethodPost, "/api/environment/storage/recover", []byte(fmt.Sprintf(`{"repair":%t}`, repair)))
181新增: if response.Code != http.StatusOK {
182新增: t.Fatal(response.Code, response.Body.String())
183新增: }
184新增: job := awaitJobIdle(t, &s.jobs)
185新增: state := s.storageRecoveryStatus()
186新增: if job.Error == "" || !state.Required || state.Error != job.Error || s.ready {
187新增: t.Fatal("failed recovery cleared the cause or resumed writes", repair, job, state)
188新增: }
189新增: if current, err := os.ReadFile(journal); err != nil || !bytes.Equal(current, original) {
190新增: t.Fatal("failed native recovery changed its durable ownership record", repair, err)
191新增: }
192新增: }
193新增:}
194新增:
195新增:func TestStorageRecoveryPreparationFailureKeepsWritesClosed(t *testing.T) {
196新增: s := storageRecoveryServer(t)
197新增: if err := os.WriteFile(s.environmentDir(), []byte("synthetic occupied workspace path"), 0600); err != nil {
198新增: t.Fatal(err)
199新增: }
200新增: s.failStorageRecovery(errors.New("previous native recovery failure"))
201新增: response := windowsBrowserRequestForTest(s, http.MethodPost, "/api/environment/storage/recover", []byte(`{}`))
202新增: if response.Code != http.StatusOK {
203新增: t.Fatal(response.Code, response.Body.String())
204新增: }
205新增: job := awaitJobIdle(t, &s.jobs)
206新增: if job.Error == "" || !s.storageRecoveryStatus().Required || s.ready {
207新增: t.Fatal("failed workspace preparation resumed environment writes", job)
208新增: }
209新增: if response := windowsBrowserRequestForTest(s, http.MethodPost, "/api/start", []byte(`{}`)); response.Code != http.StatusConflict {
210新增: t.Fatal("preparation failure opened start admission", response.Code)
211新增: }
212新增:}
213新增:
214新增:func TestStorageRecoveryRejectsChangedBindingAndKeepsAuthentication(t *testing.T) {
215新增: s := storageRecoveryServer(t)
216新增: s.failStorageRecovery(errors.New("synthetic pending migration"))
217新增: if response := request(s, http.MethodPost, "/api/environment/storage/recover", s.origin, `{}`, false); response.Code != http.StatusUnauthorized {
218新增: t.Fatal("unauthenticated recovery was admitted", response.Code)
219新增: }
220新增: if response := request(s, http.MethodPost, "/api/environment/storage/recover", s.origin, `{}`, true); response.Code != http.StatusForbidden {
221新增: t.Fatal("untrusted native recovery was admitted", response.Code)
222新增: }
223新增: s.account.lock()
224新增: if response := windowsBrowserRequestForTest(s, http.MethodPost, "/api/environment/storage/recover", []byte(`{}`)); response.Code != http.StatusLocked {
225新增: t.Fatal("locked account could recover storage", response.Code)
226新增: }
227新增: s.account.setKey(make([]byte, 32))
228新增: changed := *s.windowsGuest
229新增: changed.VMID = uuid.New()
230新增: if err := writePrivate(guestos.WindowsProfilePath(s.profile), changed); err != nil {
231新增: t.Fatal(err)
232新增: }
233新增: if response := windowsBrowserRequestForTest(s, http.MethodPost, "/api/environment/storage/recover", []byte(`{}`)); response.Code != http.StatusOK {
234新增: t.Fatal(response.Code, response.Body.String())
235新增: }
236新增: job := awaitJobIdle(t, &s.jobs)
237新增: if job.Error == "" || !s.storageRecoveryStatus().Required {
238新增: t.Fatal("recovery switched to an unrelated VM", job)
239新增: }
240新增: if _, err := os.Stat(s.environmentDir()); !errors.Is(err, os.ErrNotExist) {
241新增: t.Fatal("identity mismatch reached environment preparation", err)
242新增: }
243新增: local := testServer(t)
244新增: local.remote = newRemoteGateway(local.profile)
245新增: defer local.remote.manager.Close()
246新增: local.remote.setRemote(true)
247新增: if response := request(local, http.MethodPost, "/api/environment/storage/recover", local.origin, `{}`, true); response.Code != http.StatusForbidden {
248新增: t.Fatal("remote connection could dispatch local recovery", response.Code)
249新增: }
250新增:}
251新增:
252新增:func TestStorageRecoveryDoesNotCaptureUnrelatedNetworkFailure(t *testing.T) {
253新增: s := storageRecoveryServer(t)
254新增: s.networkIntentError = "synthetic proxy connection failure"
255新增: response := windowsBrowserRequestForTest(s, http.MethodGet, "/api/status", nil)
256新增: if response.Code != http.StatusOK || s.storageRecoveryStatus().Required || !strings.Contains(response.Body.String(), s.networkIntentError) {
257新增: t.Fatal("network failure became a storage failure", response.Code, response.Body.String())
258新增: }
259新增:}
260新增:
261新增:func TestStorageRecoveryProductionStartupKeepsLoginAndDiagnostics(t *testing.T) {
262新增: if runtime.GOOS == "windows" {
263新增: t.Skip("isolated production startup uses a non-Windows native rejection and never contacts Hyper-V")
264新增: }
265新增: const helper = "CAGE_TEST_STORAGE_RECOVERY_CONFIG"
266新增: if config := os.Getenv(helper); config != "" {
267新增: if err := Serve(config); err != nil {
268新增: t.Fatal(err)
269新增: }
270新增: return
271新增: }
272新增: for _, pending := range []bool{true, false} {
273新增: t.Run(fmt.Sprintf("native_pending=%t", pending), func(t *testing.T) {
274新增: testStorageRecoveryProductionStartup(t, pending)
275新增: })
276新增: }
277新增:}
278新增:
279新增:func testStorageRecoveryProductionStartup(t *testing.T, pending bool) {
280新增: s := storageRecoveryServer(t)
281新增: var journal string
282新增: var original []byte
283新增: if pending {
284新增: journal = storageRecoveryJournal(t, s)
285新增: var err error
286新增: original, err = os.ReadFile(journal)
287新增: if err != nil {
288新增: t.Fatal(err)
289新增: }
290新增: } else if err := os.WriteFile(s.environmentDir(), []byte("synthetic occupied workspace path"), 0600); err != nil {
291新增: t.Fatal(err)
292新增: }
293新增: if err := writePrivate(filepath.Join(s.profile, "initialization.json"), initializationRecord{Version: 1, Started: true}); err != nil {
294新增: t.Fatal(err)
295新增: }
296新增: account, err := loadLocalAccount(s.profile)
297新增: if err != nil {
298新增: t.Fatal(err)
299新增: }
300新增: if err := account.create("Storage QA", "synthetic-recovery-password", ""); err != nil {
301新增: t.Fatal(err)
302新增: }
303新增: account.lock()
304新增: ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
305新增: defer cancel()
306新增: command := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestStorageRecoveryProductionStartupKeepsLoginAndDiagnostics$", "-test.timeout=20s")
307新增: command.Env = append(os.Environ(), "CAGE_TEST_STORAGE_RECOVERY_CONFIG="+s.configPath)
308新增: var output bytes.Buffer
309新增: command.Stdout, command.Stderr = &output, &output
310新增: if err := command.Start(); err != nil {
311新增: t.Fatal(err)
312新增: }
313新增: done := make(chan error, 1)
314新增: go func() { done <- command.Wait() }()
315新增: finished := false
316新增: t.Cleanup(func() {
317新增: if !finished {
318新增: _ = command.Process.Kill()
319新增: <-done
320新增: }
321新增: if t.Failed() {
322新增: t.Log(output.String())
323新增: }
324新增: })
325新增: var control controlFile
326新增: deadline := time.Now().Add(5 * time.Second)
327新增: for time.Now().Before(deadline) {
328新增: data, err := os.ReadFile(filepath.Join(s.profile, "control.json"))
329新增: if err == nil && json.Unmarshal(data, &control) == nil && control.PID == command.Process.Pid {
330新增: break
331新增: }
332新增: select {
333新增: case err := <-done:
334新增: finished = true
335新增: t.Fatalf("storage recovery terminated the production workbench: %v", err)
336新增: default:
337新增: }
338新增: time.Sleep(10 * time.Millisecond)
339新增: }
340新增: if control.PID != command.Process.Pid {
341新增: t.Fatal("pending recovery did not publish a reachable workbench")
342新增: }
343新增: origin := fmt.Sprintf("http://localhost:%d", control.Port)
344新增: base, _ := url.Parse(origin)
345新增: jar, _ := cookiejar.New(nil)
346新增: jar.SetCookies(base, []*http.Cookie{{Name: cookieName + "_" + base.Port() + "-desktop", Value: trustedViewProof(control.Token), Path: "/"}})
347新增: client := &http.Client{Jar: jar, Timeout: 3 * time.Second}
348新增: call := func(method, path, body string, expected int) []byte {
349新增: t.Helper()
350新增: request, err := http.NewRequestWithContext(ctx, method, origin+path, strings.NewReader(body))
351新增: if err != nil {
352新增: t.Fatal(err)
353新增: }
354新增: request.Header.Set("Origin", origin)
355新增: request.Header.Set("Content-Type", "application/json")
356新增: response, err := client.Do(request)
357新增: if err != nil {
358新增: t.Fatal(err)
359新增: }
360新增: defer response.Body.Close()
361新增: data, err := io.ReadAll(io.LimitReader(response.Body, 1<<20))
362新增: if err != nil || response.StatusCode != expected {
363新增: t.Fatalf("%s %s returned %d %s (%v)", method, path, response.StatusCode, data, err)
364新增: }
365新增: return data
366新增: }
367新增: var launch launchResponse
368新增: if err := json.Unmarshal(call(http.MethodPost, "/api/launch", fmt.Sprintf(`{"token":%q}`, control.Token), http.StatusOK), &launch); err != nil {
369新增: t.Fatal(err)
370新增: }
371新增: entry, err := url.Parse(launch.URL)
372新增: if err != nil || entry.Fragment == "" {
373新增: t.Fatal("launcher did not issue a workbench ticket", err)
374新增: }
375新增: call(http.MethodPost, "/api/session", fmt.Sprintf(`{"token":%q}`, entry.Fragment), http.StatusOK)
376新增: call(http.MethodGet, "/api/account", "", http.StatusOK)
377新增: call(http.MethodGet, "/api/status", "", http.StatusLocked)
378新增: call(http.MethodPost, "/api/account/unlock", `{"password":"synthetic-recovery-password"}`, http.StatusOK)
379新增: var status struct {
380新增: Ready bool `json:"ready"`
381新增: Recovery storageRecoveryView `json:"storage_recovery"`
382新增: }
383新增: if err := json.Unmarshal(call(http.MethodGet, "/api/status", "", http.StatusOK), &status); err != nil || status.Ready || !status.Recovery.Required || status.Recovery.Error == "" || pending && !strings.Contains(status.Recovery.Error, "Hyper-V") {
384新增: t.Fatal("startup did not retain the actual native failure", status, err)
385新增: }
386新增: call(http.MethodGet, "/api/settings", "", http.StatusOK)
387新增: var initialization initializationView
388新增: if err := json.Unmarshal(call(http.MethodGet, "/api/environment/initialization", "", http.StatusOK), &initialization); err != nil || initialization.Required {
389新增: t.Fatal("old initialization record hid the storage recovery screen", initialization, err)
390新增: }
391新增: call(http.MethodPost, "/api/start", `{}`, http.StatusConflict)
392新增: bundle := call(http.MethodGet, "/api/diagnostics/export", "", http.StatusOK)
393新增: if _, err := zip.NewReader(bytes.NewReader(bundle), int64(len(bundle))); err != nil {
394新增: t.Fatal("live workbench did not export a valid diagnostic bundle", err)
395新增: }
396新增: if pending {
397新增: if current, err := os.ReadFile(journal); err != nil || !bytes.Equal(current, original) {
398新增: t.Fatal("workbench access changed the pending native transaction", err)
399新增: }
400新增: if _, err := os.Stat(s.environmentDir()); !errors.Is(err, os.ErrNotExist) {
401新增: t.Fatal("pending startup wrote environment data", err)
402新增: }
403新增: } else if current, err := os.ReadFile(s.environmentDir()); err != nil || string(current) != "synthetic occupied workspace path" {
404新增: t.Fatal("workspace preparation failure changed the occupied file", err)
405新增: }
406新增:}
修改internal/workbench/tailnet_install.go+19 −2看文件
@@ -8,9 +8,27 @@ import (
88 "errors"
99 "github.com/sylvinus/agent-vm/internal/tailnetassets"
1010 "io"
11新增: "strings"
1112 "time"
1213)
1314
15新增:// Stage beside the installed executable so a running node can finish on its old
16新增:// inode. Identity and user data live elsewhere and are never part of installation.
17新增:const tailnetInstallScript = `set -eu; tmp=$(mktemp /tmp/cage-tailnet.XXXXXX); stage=; trap 'rm -f "$tmp"; if test -n "$stage"; then sudo rm -f "$stage"; fi' EXIT; cat > "$tmp"; stage=$(sudo mktemp /usr/local/bin/.cage-tailnet.XXXXXX); sudo install -m 0755 "$tmp" "$stage"; sudo mv -f "$stage" /usr/local/bin/cage-tailnet; printf 'cage-browser ALL=(cage) NOPASSWD: /usr/local/bin/cage-tailnet\n' | sudo tee /etc/sudoers.d/cage-tailnet >/dev/null; sudo chmod 0440 /etc/sudoers.d/cage-tailnet`
18新增:
19新增:func (s *Server) refreshInstalledTailnet() error {
20新增: ctx, cancel := context.WithTimeout(s.operationContext(), 15*time.Second)
21新增: defer cancel()
22新增: installed, err := s.guest(ctx, "if test -x /usr/local/bin/cage-tailnet; then printf installed; fi")
23新增: if err != nil {
24新增: return err
25新增: }
26新增: if strings.TrimSpace(string(installed)) == "installed" {
27新增: return s.installTailnet()
28新增: }
29新增: return nil
30新增:}
31新增:
1432func (s *Server) installTailnet() error {
1533 if s.macosGuest != nil || s.windowsGuest != nil {
1634 return errTailnetNativeInstall
@@ -40,8 +58,7 @@ func (s *Server) installTailnet() error {
4058 return err
4159 }
4260 defer reader.Close()
43删除: script := `set -eu; tmp=$(mktemp /tmp/cage-tailnet.XXXXXX); trap 'rm -f "$tmp"' EXIT; cat > "$tmp"; sudo install -m 0755 "$tmp" /usr/local/bin/cage-tailnet; printf 'cage-browser ALL=(cage) NOPASSWD: /usr/local/bin/cage-tailnet\n' | sudo tee /etc/sudoers.d/cage-tailnet >/dev/null; sudo chmod 0440 /etc/sudoers.d/cage-tailnet`
44删除: cmd := s.sshCommand(ctx, "-T", s.sshTarget(), "--", "/bin/bash -c "+shellescape.Quote(script))
61新增: cmd := s.sshCommand(ctx, "-T", s.sshTarget(), "--", "/bin/bash -c "+shellescape.Quote(tailnetInstallScript))
4562 cmd.Stdin = reader
4663 cmd.Stdout = io.Discard
4764 cmd.Stderr = io.Discard
新增internal/workbench/tailnet_install_test.go+84 −0看文件
@@ -0,0 +1,84 @@
1新增:package workbench
2新增:
3新增:import (
4新增: "bytes"
5新增: "os"
6新增: "os/exec"
7新增: "path/filepath"
8新增: "strings"
9新增: "testing"
10新增:)
11新增:
12新增:func TestTailnetInstallAtomicallyReplacesRunningPayloadAndPreservesIdentity(t *testing.T) {
13新增: if os.PathSeparator != '/' {
14新增: t.Skip("guest installation executes on Unix")
15新增: }
16新增: root := t.TempDir()
17新增: bin := filepath.Join(root, "bin")
18新增: sudoers := filepath.Join(root, "sudoers")
19新增: if err := os.MkdirAll(bin, 0700); err != nil {
20新增: t.Fatal(err)
21新增: }
22新增: if err := os.MkdirAll(sudoers, 0700); err != nil {
23新增: t.Fatal(err)
24新增: }
25新增: old, err := os.ReadFile("/bin/sleep")
26新增: if err != nil {
27新增: t.Fatal(err)
28新增: }
29新增: executable := filepath.Join(bin, "cage-tailnet")
30新增: if err = os.WriteFile(executable, old, 0755); err != nil {
31新增: t.Fatal(err)
32新增: }
33新增: identity := filepath.Join(root, "identity.json")
34新增: if err = os.WriteFile(identity, []byte("saved-node-and-keys"), 0600); err != nil {
35新增: t.Fatal(err)
36新增: }
37新增: // This is a real open executable inode, rather than a mocked install result.
38新增: running := exec.Command(executable, "60")
39新增: if err = running.Start(); err != nil {
40新增: t.Fatal(err)
41新增: }
42新增: defer func() { _ = running.Process.Kill(); _ = running.Wait() }()
43新增: if err = os.WriteFile(filepath.Join(bin, "sudo"), []byte("#!/bin/sh\nexec \"$@\"\n"), 0755); err != nil {
44新增: t.Fatal(err)
45新增: }
46新增: script := strings.ReplaceAll(tailnetInstallScript, "/usr/local/bin", bin)
47新增: script = strings.ReplaceAll(script, "/etc/sudoers.d", sudoers)
48新增: fresh := []byte("#!/bin/sh\nprintf updated-tailnet\n")
49新增: install := exec.Command("/bin/bash", "-c", script)
50新增: install.Env = append(os.Environ(), "PATH="+bin+":/usr/bin:/bin")
51新增: install.Stdin = bytes.NewReader(fresh)
52新增: if output, err := install.CombinedOutput(); err != nil {
53新增: t.Fatalf("running binary replacement failed: %v %s", err, output)
54新增: }
55新增: output, err := exec.Command(executable).Output()
56新增: if err != nil || string(output) != "updated-tailnet" {
57新增: t.Fatalf("new process uses old payload: %q %v", output, err)
58新增: }
59新增: if data, err := os.ReadFile(identity); err != nil || string(data) != "saved-node-and-keys" {
60新增: t.Fatal("installation touched identity", err)
61新增: }
62新增: if entries, err := filepath.Glob(filepath.Join(bin, ".cage-tailnet.*")); err != nil || len(entries) != 0 {
63新增: t.Fatal("staged payload left behind", entries, err)
64新增: }
65新增: // A failed staged copy must leave the working binary and identity in place.
66新增: if err = os.WriteFile(filepath.Join(bin, "sudo"), []byte("#!/bin/sh\nif test \"$1\" = install; then exit 42; fi\nexec \"$@\"\n"), 0755); err != nil {
67新增: t.Fatal(err)
68新增: }
69新增: failed := exec.Command("/bin/bash", "-c", script)
70新增: failed.Env = install.Env
71新增: failed.Stdin = strings.NewReader("broken candidate")
72新增: if output, err := failed.CombinedOutput(); err == nil {
73新增: t.Fatalf("failed staged copy reported success: %s", output)
74新增: }
75新增: if actual, err := os.ReadFile(executable); err != nil || !bytes.Equal(actual, fresh) {
76新增: t.Fatal("failed installation replaced the working binary", err)
77新增: }
78新增: if actual, err := os.ReadFile(identity); err != nil || string(actual) != "saved-node-and-keys" {
79新增: t.Fatal("failed installation touched identity", err)
80新增: }
81新增: if entries, err := filepath.Glob(filepath.Join(bin, ".cage-tailnet.*")); err != nil || len(entries) != 0 {
82新增: t.Fatal("failed installation leaked its stage", entries, err)
83新增: }
84新增:}
修改internal/workbench/windows_browser.go+11 −1看文件
@@ -261,7 +261,7 @@ func (s *Server) nativeBrowserVNC(w http.ResponseWriter, r *http.Request) {
261261 client = newWindowsBrowserClient(ctx, s.profile)
262262 release = client.close
263263 }
264删除: defer release()
264新增: defer func() { release() }()
265265 var current windowsWindowFrame
266266 request := func(input map[string]any, output any) error {
267267 var data []byte
@@ -308,6 +308,16 @@ func (s *Server) nativeBrowserVNC(w http.ResponseWriter, r *http.Request) {
308308 http.Error(w, err.Error(), 409)
309309 return
310310 }
311新增: if s.macosGuest != nil {
312新增: owner := client
313新增: client, release = owner.viewer(ctx)
314新增: if client != owner {
315新增: if err := request(map[string]any{"action": "frame"}, &current); err != nil {
316新增: http.Error(w, err.Error(), 409)
317新增: return
318新增: }
319新增: }
320新增: }
311321 local, remote := net.Pipe()
312322 defer local.Close()
313323 done := make(chan struct{})
修改internal/workbench/windows_browser_client.go+13 −0看文件
@@ -43,6 +43,19 @@ func newWindowsBrowserClient(parent context.Context, profile string) *windowsBro
4343 }}
4444}
4545
46新增:// A modern guest service owns the browser. Its viewers use separate relay
47新增:// connections so cancellation also releases each viewer's held input.
48新增:func (c *windowsBrowserClient) viewer(parent context.Context) (*windowsBrowserClient, func()) {
49新增: c.mu.Lock()
50新增: defer c.mu.Unlock()
51新增: if c.ownsBrowser {
52新增: return c, func() {}
53新增: }
54新增: ctx, cancel := context.WithCancel(parent)
55新增: viewer := &windowsBrowserClient{ctx: ctx, cancel: cancel, start: c.start, ownsBrowser: true}
56新增: return viewer, viewer.close
57新增:}
58新增:
4659var windowsBrowserRoutes = map[string]bool{
4760 "tailnet": true, "health": true, "tabs": true, "events": true, "frame": true, "new": true, "activate": true, "close": true,
4861 "navigate": true, "back": true, "forward": true, "reload": true, "homepage": true, "resize": true,
修改internal/workbench/windows_browser_client_test.go+35 −0看文件
@@ -6,6 +6,7 @@ import (
66 "context"
77 "encoding/base64"
88 "encoding/json"
9新增: "fmt"
910 "io"
1011 "os"
1112 "os/exec"
@@ -115,6 +116,9 @@ func TestWindowsBrowserRelayHelper(t *testing.T) {
115116 }
116117 result = map[string]any{"data": base64.StdEncoding.EncodeToString(downloaded[start : start+remaining]), "sequence": request.Input.Sequence + 1, "eof": start+remaining == len(downloaded)}
117118 }
119新增: if os.Getenv("CAGE_BROWSER_PERSISTENT_FIXTURE") == "1" {
120新增: result.(map[string]any)["service"] = map[string]any{"version": 1, "persistent": true}
121新增: }
118122 data, _ := json.Marshal(result)
119123 _, _ = os.Stdout.Write(append(data, '\n'))
120124 }
@@ -216,3 +220,34 @@ func TestNativeBrowserEventsPreserveCopyContextAndSequence(t *testing.T) {
216220 }
217221 }
218222}
223新增:
224新增:func TestNativeBrowserViewerOwnershipUsesServiceCapability(t *testing.T) {
225新增: for _, persistent := range []bool{false, true} {
226新增: t.Run(fmt.Sprint(persistent), func(t *testing.T) {
227新增: client := fixtureWindowsBrowserClient(t)
228新增: client.ownsBrowser = true
229新增: start := client.start
230新增: client.start = func(ctx context.Context) (*exec.Cmd, error) {
231新增: cmd, err := start(ctx)
232新增: if persistent {
233新增: cmd.Env = append(cmd.Env, "CAGE_BROWSER_PERSISTENT_FIXTURE=1")
234新增: }
235新增: return cmd, err
236新增: }
237新增: if _, err := client.request(t.Context(), "GET", "/tabs", nil); err != nil {
238新增: t.Fatal(err)
239新增: }
240新增: viewer, release := client.viewer(t.Context())
241新增: if (viewer != client) != persistent {
242新增: t.Fatal("viewer ownership did not follow guest capability")
243新增: }
244新增: if _, err := viewer.request(t.Context(), "GET", "/tabs", nil); err != nil {
245新增: t.Fatal(err)
246新增: }
247新增: release()
248新增: if _, err := client.request(t.Context(), "GET", "/tabs", nil); err != nil {
249新增: t.Fatalf("closing a viewer closed the owning connection: %v", err)
250新增: }
251新增: })
252新增: }
253新增:}
修改internal/workbench/windows_clipboard_e2e_test.go+5 −2看文件
@@ -19,6 +19,7 @@ import (
1919 "time"
2020
2121 "github.com/gorilla/websocket"
22新增: "github.com/sylvinus/agent-vm/internal/clipboardfiles"
2223 "github.com/sylvinus/agent-vm/internal/guestos"
2324)
2425
@@ -120,11 +121,13 @@ func TestWindowsGuestClipboardWorkbench(t *testing.T) {
120121 if response.StatusCode != 200 {
121122 t.Fatal("public file export failed")
122123 }
123删除: paths, err := receiveClipboardArchive(response)
124新增: cache := clipboardfiles.CacheStore{Directory: filepath.Join(t.TempDir(), "clipboard-receipts")}
125新增: selection, err := receiveClipboardArchive(response, cache)
124126 if err != nil {
125127 t.Fatal(err)
126128 }
127删除: defer os.RemoveAll(filepath.Dir(paths[0]))
129新增: defer cache.Release(selection.ID)
130新增: paths := selection.Paths
128131 actual, err := os.ReadFile(filepath.Join(paths[0], "内容.bin"))
129132 if err != nil || !bytes.Equal(actual, content) {
130133 t.Fatal("public file bytes changed")
修改internal/workbench/windows_guest.go+14 −0看文件
@@ -132,9 +132,15 @@ func (s *Server) attachWindowsGuest() error {
132132}
133133
134134func (s *Server) attachWindowsGuestContext(parent context.Context) error {
135新增: if err := s.requireStorageReady(); err != nil {
136新增: return err
137新增: }
135138 ctx, cancel := context.WithTimeout(parent, 15*time.Second)
136139 defer cancel()
137140 state, err := s.windowsStatus(ctx)
141新增: if err == nil {
142新增: err = s.requireStorageReady()
143新增: }
138144 restartedNetwork := false
139145 if err == nil && s.windowsGuest.NetworkPairingFile != "" {
140146 // An alive helper alone does not prove its packet connection survived.
@@ -154,6 +160,11 @@ func (s *Server) attachWindowsGuestContext(parent context.Context) error {
154160 err = s.ensureProjectShare(s.environmentDir())
155161 }
156162 s.mu.Lock()
163新增: if s.storageRecoveryError != "" {
164新增: err = errors.New(s.storageRecoveryError)
165新增: s.mu.Unlock()
166新增: return err
167新增: }
157168 s.windowsState = state
158169 newlyReady := !s.ready && err == nil
159170 s.ready = err == nil
@@ -200,6 +211,9 @@ func waitWindowsBoot(ctx context.Context, interval time.Duration, attach func(co
200211}
201212
202213func (s *Server) startWindowsGuest() error {
214新增: if err := s.requireStorageReady(); err != nil {
215新增: return err
216新增: }
203217 if err := requireHostGit(s.operationContext()); err != nil {
204218 return err
205219 }
修改scripts/guest-os/build-macos-claude-window.sh+7 −1看文件
@@ -15,11 +15,17 @@ cat > "$app/Contents/Info.plist" <<'PLIST'
1515<key>CFBundleShortVersionString</key><string>1.0</string>
1616<key>CFBundleVersion</key><string>1</string>
1717<key>LSUIElement</key><true/>
18新增:<key>CFBundleDocumentTypes</key><array><dict>
19新增:<key>CFBundleTypeName</key><string>Cage project file</string>
20新增:<key>CFBundleTypeRole</key><string>Viewer</string>
21新增:<key>LSHandlerRank</key><string>None</string>
22新增:<key>LSItemContentTypes</key><array><string>public.data</string></array>
23新增:</dict></array>
1824</dict></plist>
1925PLIST
2026objects=$(mktemp -d)
2127trap 'rm -rf "$objects"' EXIT
2228xcrun clang -target arm64-apple-macos14.0 -Wall -Wextra -Werror -O2 -c "$src/macos-file-writers.c" -o "$objects/file-writers.o"
23删除:xcrun swiftc -parse-as-library -D GUEST_WINDOW_APP -O -target arm64-apple-macos14.0 "$src/../../desktop/MacKeyboard.swift" "$src/claude-window-macos.swift" "$src/macos-diagnostics.swift" "$src/macos-claude-window-app.swift" "$src/macos-window-input.swift" "$src/macos-project-panel.swift" "$src/macos-claude-canvas.swift" "$src/macos-window-stream.swift" "$src/macos-audio.swift" "$src/macos-gui-session.swift" "$src/macos-phone-desktop.swift" "$src/macos-desktop-files.swift" "$src/macos-desktop-downloads.swift" "$objects/file-writers.o" -o "$app/Contents/MacOS/CageGuestWindow"
29新增:xcrun swiftc -parse-as-library -D GUEST_WINDOW_APP -O -target arm64-apple-macos14.0 "$src/../../desktop/MacKeyboard.swift" "$src/claude-window-macos.swift" "$src/macos-diagnostics.swift" "$src/macos-claude-window-app.swift" "$src/macos-window-input.swift" "$src/macos-maintenance.swift" "$src/macos-setup-password.swift" "$src/macos-project-panel.swift" "$src/macos-claude-canvas.swift" "$src/macos-window-stream.swift" "$src/macos-audio.swift" "$src/macos-gui-session.swift" "$src/macos-phone-desktop.swift" "$src/macos-desktop-files.swift" "$src/macos-desktop-downloads.swift" "$src/macos-native-open.swift" "$objects/file-writers.o" -lbsm -o "$app/Contents/MacOS/CageGuestWindow"
2430codesign --force --sign "${CAGE_GUEST_SIGN_IDENTITY:-${CAGE_SIGNING_IDENTITY:--}}" --identifier dev.cage.GuestClaudeWindow "$app"
2531codesign --verify --strict "$app"
修改scripts/guest-os/build-macos-sshfs.sh+2 −0看文件
@@ -5,6 +5,7 @@ set -euo pipefail
55[[ $# == 2 && $(uname -sm) == 'Darwin arm64' ]] || { echo 'Usage: build-macos-sshfs.sh /absolute/macfuse-sdk/usr/local /absolute/cage-sshfs' >&2; exit 2; }
66sdk=$1
77output=$2
8新增:script_dir=$(cd "$(dirname "$0")" && pwd)
89[[ $sdk == /* && $output == /* && -f $sdk/include/fuse3/fuse.h && ! -e $output ]]
910src=$(mktemp -d)
1011trap 'rm -rf "$src"' EXIT
@@ -13,6 +14,7 @@ curl -fLsS --retry 2 "https://codeload.github.com/libfuse/sshfs/tar.gz/$commit"
1314cd "$src"
1415echo '9be20256ac841c6e5b4cd8aefbf57c325f93e9ff01f7c7691edfe9f02700338b sshfs.tgz' | shasum -a 256 -c - >/dev/null
1516tar xzf sshfs.tgz --strip-components 1
17新增:patch -p1 < "$script_dir/sshfs-openwith.patch"
1618cat > config.h <<'HEADER'
1719#define PACKAGE_VERSION "3.7.6"
1820#define IDMAP_DEFAULT "user"
修改scripts/guest-os/guest-clipboard-macos.swift+25 −5看文件
@@ -292,9 +292,12 @@ private final class ClipboardAgent: @unchecked Sendable {
292292 process.arguments = ["cache", String(data: try JSONSerialization.data(withJSONObject: ["action": action, "cache_id": id]), encoding: .utf8)!]
293293 process.standardInput = FileHandle.nullDevice; process.standardOutput = output; process.standardError = FileHandle.nullDevice
294294 try process.run()
295新增: let timeout = DispatchWorkItem { if process.isRunning { process.terminate() } }
296新增: DispatchQueue.global().asyncAfter(deadline: .now() + 10, execute: timeout)
297新增: defer { timeout.cancel() }
295298 let data = try output.fileHandleForReading.readToEnd() ?? Data()
296299 process.waitUntilExit()
297删除: guard process.terminationStatus == 0, data.count <= 1 << 20 else { throw ClipboardFailure("clipboard_cache_failed") }
300新增: guard process.terminationStatus == 0, data.count <= wireLimit else { throw ClipboardFailure("clipboard_cache_failed") }
298301 return try json(data)
299302 }
300303 private func rememberCopy(_ result: [String: Any], clipboard: Bool) {
@@ -365,17 +368,19 @@ private final class ClipboardAgent: @unchecked Sendable {
365368 }
366369 private func fileJSON(_ operation: String, values: [String]) throws -> [String] {
367370 let reader = UUID()
371新增: var recorded = false
368372 onGUI { fileReaders[reader] = values }
369删除: defer { onGUI { fileReaders.removeValue(forKey: reader); collectCopies() } }
373新增: defer { onGUI { fileReaders.removeValue(forKey: reader); if !recorded { copiesLoaded = false }; collectCopies() } }
370374 let input = Pipe()
371375 let (process, output, id, epoch) = try beginTransfer(operation, input: input.fileHandleForReading)
372删除: defer { try? input.fileHandleForWriting.close(); if process.isRunning { process.terminate() }; onGUI { _ = transfers.removeValue(forKey: id) } }
376新增: defer { try? input.fileHandleForWriting.close(); if process.isRunning { process.terminate() }; process.waitUntilExit(); onGUI { _ = transfers.removeValue(forKey: id) } }
373377 try input.fileHandleForWriting.write(contentsOf: JSONSerialization.data(withJSONObject: values)); try input.fileHandleForWriting.close()
374378 let data = try output.fileHandleForReading.readToEnd() ?? Data()
375379 guard data.count <= 65536 else { throw ClipboardFailure("invalid_files") }
376380 let response = try json(data)
377381 let result = try paths(response["paths"])
378382 onGUI { record(result, copied: true); rememberCopy(response, clipboard: operation == "copy") }
383新增: recorded = true
379384 do { try finishTransfer(process, id: id, epoch: epoch) }
380385 catch { onGUI { retireCopies(result) }; throw error }
381386 return result
@@ -530,18 +535,33 @@ private final class ClipboardAgent: @unchecked Sendable {
530535 }
531536 try writeAll(fd, jsonData(["ok": true]))
532537 case "import", "upload":
538新增: let capturedStreams = onGUI { Set(streams.values.map(ObjectIdentifier.init)) }
533539 let name = operation == "upload" ? request["name"] as? String : nil
534540 if operation == "upload" && (name == nil || name!.utf8.count > 255) { throw ClipboardFailure("invalid_files") }
535541 let input = Pipe()
536542 let (process, output, id, epoch) = try beginTransfer(operation == "upload" ? "save" : "import", input: input.fileHandleForReading, name: name)
537删除: defer { try? input.fileHandleForWriting.close(); if process.isRunning { process.terminate() }; onGUI { _ = transfers.removeValue(forKey: id) } }
543新增: var recorded = false
544新增: defer {
545新增: try? input.fileHandleForWriting.close()
546新增: if process.isRunning { process.terminate() }
547新增: process.waitUntilExit()
548新增: onGUI { transfers.removeValue(forKey: id); if !recorded { copiesLoaded = false }; collectCopies() }
549新增: }
538550 try reader.copy(to: input.fileHandleForWriting); try input.fileHandleForWriting.close()
539551 let data = try output.fileHandleForReading.readToEnd() ?? Data()
540552 guard data.count <= 65536 else { throw ClipboardFailure("invalid_files") }
541553 let response = try json(data)
542554 let imported = try paths(response["paths"])
543555 onGUI { record(imported, copied: true); rememberCopy(response, clipboard: operation == "import") }
544删除: do { try finishTransfer(process, id: id, epoch: epoch); try writeAll(fd, jsonData(["paths": imported])) }
556新增: recorded = true
557新增: do {
558新增: try finishTransfer(process, id: id, epoch: epoch)
559新增: try onGUI {
560新增: if operation == "import", !capturedStreams.isEmpty,
561新增: capturedStreams.isDisjoint(with: streams.values.map(ObjectIdentifier.init)) { throw ClipboardFailure("connection_closed") }
562新增: }
563新增: try writeAll(fd, jsonData(["paths": imported]))
564新增: }
545565 catch { onGUI { retireCopies(imported) }; throw error }
546566 case "export":
547567 let selected = try paths(request["paths"])
修改scripts/guest-os/guest-clipboard-windows/ClaudeWindowRpc.cs+3 −3看文件
@@ -189,7 +189,7 @@ internal static class ClaudeWindowRpc
189189 {
190190 if (!available()) throw new InvalidDataException("requires_gui_login");
191191 var action = value["action"]?.GetValue<string>() ?? "";
192删除: if (action is "files-download-open" or "files-download-read" or "files-download-close" or "files-download-retry")
192新增: if (action is "files-download-open" or "files-download-read" or "files-download-close" or "files-download-retry" or "files-download-ack")
193193 {
194194 await Protocol.Write(stream, WindowsDesktopDownloads.Read(value), token); continue;
195195 }
@@ -213,7 +213,7 @@ internal static class ClaudeWindowRpc
213213 }
214214 if(action=="files-poll" && executable is null)
215215 {
216删除: await Protocol.Write(stream,new JsonObject{["available"]=false,["uploads"]=new JsonArray(),["downloads"]=WindowsDesktopDownloads.Snapshot(),["opens"]=WindowsDesktopFiles.OpenSnapshot()},token);continue;
216新增: await Protocol.Write(stream,new JsonObject{["available"]=false,["uploads"]=new JsonArray(),["downloads"]=WindowsDesktopDownloads.Snapshot(),["opens"]=WindowsDesktopFiles.OpenSnapshot(),["downloadAck"]=true},token);continue;
217217 }
218218 if (executable is null) throw new InvalidDataException("desktop_not_installed");
219219 if (action == "start")
@@ -227,7 +227,7 @@ internal static class ClaudeWindowRpc
227227 try { found = Find(executable); }
228228 catch (InvalidDataException) { }
229229 if (found is null)
230删除: await Protocol.Write(stream,new JsonObject{["available"]=false,["uploads"]=new JsonArray(),["downloads"]=WindowsDesktopDownloads.Snapshot(),["opens"]=WindowsDesktopFiles.OpenSnapshot()},token);
230新增: await Protocol.Write(stream,new JsonObject{["available"]=false,["uploads"]=new JsonArray(),["downloads"]=WindowsDesktopDownloads.Snapshot(),["opens"]=WindowsDesktopFiles.OpenSnapshot(),["downloadAck"]=true},token);
231231 else
232232 {
233233 using var owner = found.Process;
修改scripts/guest-os/guest-clipboard-windows/ClipboardAgent.cs+26 −11看文件
@@ -268,7 +268,7 @@ internal sealed class ClipboardAgent : Control
268268 _ = child.StandardError.BaseStream.CopyToAsync(Stream.Null);
269269 using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(10));
270270 using var cancellation = timeout.Token.Register(() => { try { child.Kill(true); } catch { } });
271删除: var result = await Protocol.Read(child.StandardOutput.BaseStream, Protocol.PathLimit, timeout.Token) ?? throw new IOException("clipboard_cache_failed");
271新增: var result = await Protocol.Read(child.StandardOutput.BaseStream, Protocol.WireLimit, timeout.Token) ?? throw new IOException("clipboard_cache_failed");
272272 await child.WaitForExitAsync(timeout.Token);
273273 if (child.ExitCode != 0) throw new IOException("clipboard_cache_failed");
274274 return result;
@@ -281,13 +281,13 @@ internal sealed class ClipboardAgent : Control
281281 {
282282 if (!copiesLoaded)
283283 {
284删除: copiesLoaded = true;
285284 var previous = await Cache("list");
286285 foreach (var item in previous["selections"]!.AsArray())
287286 {
288287 var id = item!["cache_id"]!.GetValue<string>();
289288 copies.TryAdd(id, new CachedCopy(id, Protocol.Paths(item["paths"]), false));
290289 }
290新增: copiesLoaded = true;
291291 }
292292 foreach (var copy in copies.Values.ToArray())
293293 {
@@ -332,9 +332,10 @@ internal sealed class ClipboardAgent : Control
332332 var reader = Guid.NewGuid();
333333 if (paths != null) await GUI(() => { fileReaders[reader] = paths; return true; });
334334 string[]? created = null;
335新增: Process? child = null;
335336 try
336337 {
337删除: using var child = StartHelper(operation);
338新增: child = StartHelper(operation);
338339 using var cancellation = token.Register(() => { try { child.Kill(true); } catch { } });
339340 if (paths != null) await JsonSerializer.SerializeAsync(child.StandardInput.BaseStream, paths, cancellationToken: token);
340341 child.StandardInput.Close();
@@ -347,26 +348,40 @@ internal sealed class ClipboardAgent : Control
347348 }
348349 catch
349350 {
350删除: if (created != null) await GUI(() => { RetireCopies(created); return true; });
351新增: if (child != null && !child.HasExited) { child.Kill(true); await child.WaitForExitAsync(); }
352新增: await GUI(() => { if (created != null) RetireCopies(created); else copiesLoaded = false; return true; });
351353 throw;
352354 }
353删除: finally { await GUI(() => { fileReaders.Remove(reader); CollectCopies(); return true; }); }
355新增: finally { child?.Dispose(); await GUI(() => { fileReaders.Remove(reader); CollectCopies(); return true; }); }
354356 }
355357 internal async Task Import(Stream stream, CancellationToken token)
356358 {
359新增: var capturedSubscriber = await GUI(() => subscriber);
360新增: var capturedSession = SessionEpoch;
357361 using var child = StartHelper("import");
358362 using var cancellation = token.Register(() => { try { child.Kill(true); } catch { } });
359删除: await Protocol.ReceiveFrames(stream, child.StandardInput.BaseStream, token); child.StandardInput.Close();
360删除: var result = await Protocol.Read(child.StandardOutput.BaseStream, Protocol.PathLimit, token) ?? throw new IOException("file_helper_failed");
361删除: var paths = Protocol.Paths(result["paths"]);
362删除: await GUI(() => { RememberCopy(result); return true; });
363新增: string[]? paths = null;
363364 try
364365 {
366新增: await Protocol.ReceiveFrames(stream, child.StandardInput.BaseStream, token); child.StandardInput.Close();
367新增: var result = await Protocol.Read(child.StandardOutput.BaseStream, Protocol.PathLimit, token) ?? throw new IOException("file_helper_failed");
368新增: paths = Protocol.Paths(result["paths"]);
369新增: await GUI(() => { RememberCopy(result); return true; });
365370 await child.WaitForExitAsync(token);
366371 if (child.ExitCode != 0) throw new IOException("file_helper_failed");
367删除: await GUI(() => { SessionGuard.Assert(); Approve(paths); return true; });
372新增: await GUI(() => {
373新增: SessionGuard.Assert();
374新增: if (SessionEpoch != capturedSession || capturedSubscriber != null && subscriber != capturedSubscriber) throw new IOException("clipboard_session_changed");
375新增: Approve(paths); return true;
376新增: });
368377 await Protocol.Write(stream, new() { ["paths"] = JsonSerializer.SerializeToNode(paths) }, token);
369删除: } catch { await GUI(() => { RetireCopies(paths); return true; }); throw; }
378新增: }
379新增: catch
380新增: {
381新增: if (!child.HasExited) { child.Kill(true); await child.WaitForExitAsync(); }
382新增: await GUI(() => { if (paths != null) RetireCopies(paths); else copiesLoaded = false; CollectCopies(); return true; });
383新增: throw;
384新增: }
370385 }
371386 internal async Task Export(Stream stream, JsonNode? selection, CancellationToken token)
372387 {
修改scripts/guest-os/guest-clipboard-windows/WindowsDesktopDownloads.cs+117 −13看文件
@@ -19,13 +19,16 @@ internal static class WindowsDesktopDownloads
1919 public string Name { get; set; } = "";
2020 public string State { get; set; } = "downloading";
2121 public string Error { get; set; } = "";
22新增: public bool Acknowledged { get; set; }
23新增: public string? Identity { get; set; }
2224 public long Size { get; set; }
2325 public long Written { get; set; }
2426 public DateTimeOffset Started { get; set; } = DateTimeOffset.UtcNow;
2527 }
26删除: private sealed class Transfer(FileStream file, string session, long epoch)
28新增: private sealed class Transfer(FileStream file, string id, string session, long epoch)
2729 {
2830 internal readonly FileStream File = file;
31新增: internal readonly string ID = id;
2932 internal bool SessionValid => ClipboardAgent.Current is { SessionEventsRegistered: true } agent && agent.Session == session && agent.SessionEpoch == epoch;
3033 internal int Sequence;
3134 internal DateTimeOffset Used = DateTimeOffset.UtcNow;
@@ -33,6 +36,7 @@ internal static class WindowsDesktopDownloads
3336 private static readonly object Gate = new();
3437 private static readonly Dictionary<string, Download> Downloads = new();
3538 private static readonly Dictionary<string, Transfer> Transfers = new();
39新增: private static readonly HashSet<string> Watching = new();
3640 private static readonly System.Threading.Timer TransferExpiry = new(_ =>
3741 {
3842 lock (Gate)
@@ -48,6 +52,34 @@ internal static class WindowsDesktopDownloads
4852 private static string? directory;
4953 [DllImport("kernel32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]
5054 private static extern uint GetFinalPathNameByHandleW(SafeFileHandle handle, StringBuilder path, uint length, uint flags);
55新增: [StructLayout(LayoutKind.Sequential)]
56新增: private struct FileInformation
57新增: {
58新增: internal uint Attributes;
59新增: internal System.Runtime.InteropServices.ComTypes.FILETIME Creation, Access, Written;
60新增: internal uint Volume, SizeHigh, SizeLow, Links, IndexHigh, IndexLow;
61新增: }
62新增: [DllImport("kernel32.dll", SetLastError = true)]
63新增: [return: MarshalAs(UnmanagedType.Bool)]
64新增: private static extern bool GetFileInformationByHandle(SafeFileHandle handle, out FileInformation information);
65新增: [DllImport("kernel32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]
66新增: private static extern SafeFileHandle CreateFileW(string path, uint access, uint share, IntPtr security, uint creation, uint flags, IntPtr template);
67新增: [DllImport("kernel32.dll", SetLastError = true)]
68新增: [return: MarshalAs(UnmanagedType.Bool)]
69新增: private static extern bool SetFileInformationByHandle(SafeFileHandle handle, int kind, ref byte information, uint size);
70新增:
71新增: private static string FileIdentity(SafeFileHandle handle)
72新增: {
73新增: if (!GetFileInformationByHandle(handle, out var info)) throw new IOException("desktop_download_file_invalid");
74新增: return $"{info.Volume:x8}:{info.IndexHigh:x8}{info.IndexLow:x8}";
75新增: }
76新增:
77新增: private static bool MatchesPath(SafeFileHandle handle, string path)
78新增: {
79新增: var actual = new StringBuilder(32768);
80新增: var length = GetFinalPathNameByHandleW(handle, actual, (uint)actual.Capacity, 0);
81新增: return length > 0 && length < actual.Capacity && string.Equals(actual.ToString(), @"\\?\" + Path.GetFullPath(path), StringComparison.OrdinalIgnoreCase);
82新增: }
5183
5284 private static FileStream OpenSource(Download item)
5385 {
@@ -85,7 +117,8 @@ internal static class WindowsDesktopDownloads
85117 var info = new FileInfo(manifest);
86118 if (info.Attributes.HasFlag(FileAttributes.ReparsePoint) || info.Length > 1 << 20) throw new InvalidDataException("desktop_download_catalog_invalid");
87119 var saved = JsonSerializer.Deserialize<Download[]>(File.ReadAllBytes(manifest)) ?? [];
88删除: foreach (var item in saved.TakeLast(100))
120新增: if (saved.Length > 100) throw new InvalidDataException("desktop_download_catalog_invalid");
121新增: foreach (var item in saved)
89122 {
90123 if (!Guid.TryParseExact(item.ID, "D", out _) || !AttachmentsRpc.NameValid(item.Name)) continue;
91124 if (item.State == "downloading") { item.State = "failed"; item.Error = "保存过程被中断,请从 Claude Desktop 重新下载。"; }
@@ -104,7 +137,7 @@ internal static class WindowsDesktopDownloads
104137 {
105138 using (var stream = new FileStream(temporary, FileMode.CreateNew, FileAccess.Write, FileShare.None))
106139 {
107删除: JsonSerializer.Serialize(stream, Downloads.Values.TakeLast(100).ToArray());
140新增: JsonSerializer.Serialize(stream, Downloads.Values.ToArray());
108141 stream.Flush(true);
109142 }
110143 File.Move(temporary, file, true);
@@ -112,6 +145,51 @@ internal static class WindowsDesktopDownloads
112145 finally { if (File.Exists(temporary)) File.Delete(temporary); }
113146 }
114147
148新增: private static void RemoveSource(Download item)
149新增: {
150新增: var path = Source(item);
151新增: var folder = Path.GetDirectoryName(path)!;
152新增: using var parent = CreateFileW(folder, 0x10000 | 0x80, 1 | 2, IntPtr.Zero, 3, 0x02000000 | 0x00200000, IntPtr.Zero);
153新增: if (parent.IsInvalid && Marshal.GetLastWin32Error() is 2 or 3) return;
154新增: if (parent.IsInvalid || !MatchesPath(parent, folder) || !GetFileInformationByHandle(parent, out var parentInfo) ||
155新增: (parentInfo.Attributes & 0x410) != 0x10) throw new IOException("desktop_download_directory_invalid");
156新增: using (var file = CreateFileW(path, 0x80000000 | 0x10000, 1, IntPtr.Zero, 3, 0x00200000, IntPtr.Zero))
157新增: {
158新增: if (file.IsInvalid)
159新增: {
160新增: if (Marshal.GetLastWin32Error() is not (2 or 3)) throw new IOException("desktop_download_cleanup_failed");
161新增: }
162新增: else
163新增: {
164新增: if (item.State != "saved" || !MatchesPath(file, path) || !GetFileInformationByHandle(file, out var info) || (info.Attributes & 0x410) != 0 ||
165新增: FileIdentity(file) != item.Identity || ((long)info.SizeHigh << 32 | info.SizeLow) != item.Size ||
166新增: DateTime.FromFileTimeUtc((long)(uint)info.Written.dwHighDateTime << 32 | (uint)info.Written.dwLowDateTime).Ticks != item.Written)
167新增: throw new IOException("desktop_download_changed");
168新增: byte delete = 1;
169新增: if (!SetFileInformationByHandle(file, 4, ref delete, 1)) throw new IOException("desktop_download_cleanup_failed");
170新增: }
171新增: }
172新增: // The kernel removes this exact open directory only when it is empty.
173新增: // Unrecorded sibling files keep their directory and contents.
174新增: byte removeDirectory = 1;
175新增: var removed = SetFileInformationByHandle(parent, 4, ref removeDirectory, 1);
176新增: if (item.State == "failed" && !removed) throw new IOException("desktop_download_cleanup_failed");
177新增: }
178新增:
179新增: private static void MakeRoom()
180新增: {
181新增: if (Downloads.Count < 100) return;
182新增: foreach (var item in Downloads.Values.ToArray())
183新增: {
184新增: var eligible = (item.State == "saved" && item.Acknowledged) || (item.State == "failed" && !Watching.Contains(item.ID));
185新增: if (!eligible || Transfers.Values.Any(transfer => transfer.ID == item.ID)) continue;
186新增: try { RemoveSource(item); Downloads.Remove(item.ID); return; }
187新增: catch (IOException) { /* Retain changed, in-use, or unowned source receipts. */ }
188新增: catch (UnauthorizedAccessException) { }
189新增: }
190新增: throw new InvalidDataException("desktop_download_limit");
191新增: }
192新增:
115193 internal static string Reserve(string name, Action<string> submit)
116194 {
117195 if (!AttachmentsRpc.NameValid(name)) throw new InvalidDataException("desktop_download_name_invalid");
@@ -119,6 +197,7 @@ internal static class WindowsDesktopDownloads
119197 {
120198 DirectoryPath();
121199 if (Downloads.Values.Count(item => item.State == "downloading") >= 12) throw new InvalidDataException("desktop_download_limit");
200新增: MakeRoom();
122201 var item = new Download { ID = Guid.NewGuid().ToString("D"), Name = name };
123202 var folder = Path.GetDirectoryName(Source(item))!;
124203 Directory.CreateDirectory(folder);
@@ -129,18 +208,12 @@ internal static class WindowsDesktopDownloads
129208 watcher.Renamed += (_, eventArgs) => { if (eventArgs.Name == name) { Interlocked.Exchange(ref renamed, 1); changed.TrySetResult(); } };
130209 watcher.Error += (_, _) => changed.TrySetException(new InvalidDataException("desktop_download_watch_failed"));
131210 watcher.EnableRaisingEvents = true;
132删除: while (Downloads.Count >= 100)
133删除: {
134删除: var oldest = Downloads.Values.FirstOrDefault(value => value.State != "downloading");
135删除: if (oldest is null) break;
136删除: Downloads.Remove(oldest.ID);
137删除: }
211新增: Watching.Add(item.ID);
138212 Downloads.Add(item.ID, item);
139删除: Persist();
140删除: try { submit(Source(item)); }
213新增: try { Persist(); submit(Source(item)); }
141214 catch
142215 {
143删除: watcher.Dispose(); item.State = "failed"; item.Error = "客机保存窗口未接收文件位置,请重新下载。"; Persist(); throw;
216新增: watcher.Dispose(); Watching.Remove(item.ID); item.State = "failed"; item.Error = "客机保存窗口未接收文件位置,请重新下载。"; Persist(); throw;
144217 }
145218 _ = Task.Run(async () =>
146219 {
@@ -162,6 +235,7 @@ internal static class WindowsDesktopDownloads
162235 lock (Gate)
163236 {
164237 item.Size = source.Length; item.Written = File.GetLastWriteTimeUtc(Source(item)).Ticks;
238新增: item.Identity = FileIdentity(source.SafeFileHandle);
165239 item.State = "saved"; Persist();
166240 }
167241 return;
@@ -175,6 +249,7 @@ internal static class WindowsDesktopDownloads
175249 {
176250 lock (Gate) { item.State = "failed"; item.Error = "未能确认文件保存完成,请从 Claude Desktop 重新下载。"; Persist(); }
177251 }
252新增: finally { watcher.Dispose(); lock (Gate) Watching.Remove(item.ID); }
178253 }
179254 });
180255 return item.ID;
@@ -189,6 +264,7 @@ internal static class WindowsDesktopDownloads
189264 return new JsonArray(Downloads.Values.TakeLast(100).Reverse().Select(item => (JsonNode)new JsonObject
190265 {
191266 ["id"] = item.ID, ["name"] = item.Name, ["state"] = item.State, ["target"] = "desktop",
267新增: ["acknowledged"] = item.Acknowledged,
192268 ["receivedBytes"] = item.Size, ["totalBytes"] = item.Size, ["retryable"] = false,
193269 ["error"] = item.Error, ["startedAt"] = item.Started.ToString("O"),
194270 }).ToArray());
@@ -218,6 +294,34 @@ internal static class WindowsDesktopDownloads
218294 foreach (var pair in Transfers.ToArray())
219295 if (!pair.Value.SessionValid || DateTimeOffset.UtcNow - pair.Value.Used > TimeSpan.FromMinutes(2)) { pair.Value.File.Dispose(); Transfers.Remove(pair.Key); }
220296 var action = input["action"]?.GetValue<string>();
297新增: if (action == "files-download-ack")
298新增: {
299新增: var ids = input["ids"] as JsonArray;
300新增: if (ids is null || ids.Count > 100 || ids.Any(value => value is not JsonValue scalar || !scalar.TryGetValue<string>(out var id) || !Guid.TryParseExact(id, "D", out _)))
301新增: throw new InvalidDataException("desktop_download_ack_invalid");
302新增: var changed = new List<Download>();
303新增: try
304新增: {
305新增: foreach (var value in ids)
306新增: {
307新增: if (!Downloads.TryGetValue(value!.GetValue<string>(), out var item) || item.State != "saved" || item.Acknowledged) continue;
308新增: if (item.Identity is null)
309新增: {
310新增: try
311新增: {
312新增: using var file = OpenSource(item);
313新增: if (file.Length == item.Size && File.GetLastWriteTimeUtc(Source(item)).Ticks == item.Written) item.Identity = FileIdentity(file.SafeFileHandle);
314新增: }
315新增: catch (IOException) { }
316新增: catch (UnauthorizedAccessException) { }
317新增: }
318新增: item.Acknowledged = true; changed.Add(item);
319新增: }
320新增: if (changed.Count > 0) Persist();
321新增: }
322新增: catch { foreach (var item in changed) item.Acknowledged = false; throw; }
323新增: return new JsonObject { ["ok"] = true };
324新增: }
221325 if (action == "files-download-retry")
222326 {
223327 var id = input["id"]?.GetValue<string>() ?? "";
@@ -236,7 +340,7 @@ internal static class WindowsDesktopDownloads
236340 if (file.Length != item.Size || File.GetLastWriteTimeUtc(Source(item)).Ticks != item.Written)
237341 { file.Dispose(); throw new InvalidDataException("desktop_download_changed"); }
238342 var key = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)).ToLowerInvariant();
239删除: Transfers.Add(key, new Transfer(file, agent.Session, agent.SessionEpoch));
343新增: Transfers.Add(key, new Transfer(file, item.ID, agent.Session, agent.SessionEpoch));
240344 return new JsonObject { ["transfer"] = key, ["size"] = file.Length, ["name"] = item.Name };
241345 }
242346 var transfer = input["transfer"]?.GetValue<string>() ?? "";
修改scripts/guest-os/guest-clipboard-windows/WindowsDesktopFiles.cs+17 −5看文件
@@ -145,7 +145,7 @@ internal static class WindowsDesktopFiles
145145 {
146146 ["id"] = value.ID, ["target"] = "desktop", ["kind"] = "chooser", ["multiple"] = value.Multiple, ["directory"] = value.Directory,
147147 }).ToArray()),
148删除: ["downloads"] = WindowsDesktopDownloads.Snapshot(), ["opens"] = OpenSnapshot(),
148新增: ["downloads"] = WindowsDesktopDownloads.Snapshot(), ["downloadAck"] = true, ["opens"] = OpenSnapshot(),
149149 };
150150 }
151151 }
@@ -162,14 +162,26 @@ internal static class WindowsDesktopFiles
162162
163163 internal static void QueueOpen(string path, string action, Action validate)
164164 {
165删除: if (!Path.IsPathFullyQualified(path) || path.Length > 32767 || path.Contains('\0') || action is not ("open" or "reveal"))
165新增: QueueOpen([path], action, validate);
166新增: }
167新增:
168新增: internal static void QueueOpen(string[] paths, string action, Action validate)
169新增: {
170新增: if (paths.Length is < 1 or > 32 || action is not ("open" or "reveal") ||
171新增: paths.Any(path => string.IsNullOrEmpty(path) || !Path.IsPathFullyQualified(path) || path.Length > 32767 || path.Contains('\0')))
166172 throw new InvalidDataException("file_open_request_invalid");
173新增: var normalized = paths.Select(Path.GetFullPath).ToArray();
167174 lock (Gate)
168175 {
169删除: SessionGuard.Assert(); ExpireOpens(); validate();
176新增: SessionGuard.Assert(); ExpireOpens();
170177 var agent = ClipboardAgent.Current;
171删除: if (agent is null || !agent.SessionEventsRegistered || Opens.Count >= 32) throw new InvalidDataException("file_open_request_unavailable");
172删除: Opens.Add(Guid.NewGuid().ToString("D"), new OpenRequest(Path.GetFullPath(path), action, agent.Session, agent.SessionEpoch, validate));
178新增: if (agent is null || !agent.SessionEventsRegistered) throw new InvalidDataException("file_open_request_unavailable");
179新增: var epoch = agent.SessionEpoch;
180新增: validate();
181新增: if (ClipboardAgent.Current != agent || agent.SessionEpoch != epoch) throw new InvalidDataException("file_open_target_changed");
182新增: if (Opens.Count + normalized.Length > 32) throw new InvalidDataException("file_open_request_limit");
183新增: foreach (var path in normalized)
184新增: Opens.Add(Guid.NewGuid().ToString("D"), new OpenRequest(path, action, agent.Session, epoch, validate));
173185 }
174186 }
175187
修改scripts/guest-os/install-windows-host-manager.ps1+5 −3看文件
@@ -55,9 +55,11 @@ if($service){
5555 $existing=Get-CimInstance Win32_Service -Filter ("Name='"+$name+"'")
5656 if($existing.PathName -cne $binary -or $existing.StartName -notin @('LocalSystem','NT AUTHORITY\SYSTEM')){throw 'An unrelated service already uses this name.'}
5757}
58删除:# Verify the retained VM before stopping the existing helper. Prepare uses the
59删除:# checked protected copy in the installing administrator's token.
60删除:$raw=& $payload.FullName prepare --vm-id $VMId.ToString('D') --host-sid $HostSID
58新增:# Existing installations retain their protected authority and recovery journal.
59新增:# They can repair a stopped helper while its bound data volume is disconnected.
60新增:# Fresh registration verifies the actual VM using the protected payload copy.
61新增:$operation=if(Test-Path -LiteralPath $bindingPath){'binding'}else{'prepare'}
62新增:$raw=& $payload.FullName $operation --vm-id $VMId.ToString('D') --host-sid $HostSID
6163if($LASTEXITCODE -ne 0){throw 'The exact VM/disk binding could not be verified.'}
6264$binding=$raw|ConvertFrom-Json
6365if($binding.version -ne 1 -or [guid]$binding.vm_id -ne $VMId -or $binding.host_sid -cne $HostSID){throw 'The prepared manager binding does not match.'}
修改scripts/guest-os/macos-browser-service.mjs+7 −5看文件
@@ -111,11 +111,13 @@ export async function serveMacOSBrowser({ directory, dispatch, close, disconnect
111111 if (!stopping) stopping = (async () => {
112112 const closed = new Promise(resolve => server.close(resolve));
113113 for (const client of clients) client.destroy();
114删除: await close();
115删除: await queue;
116删除: await closed;
117删除: const current = await fs.lstat(address).catch(() => null);
118删除: if (current?.ino === owned.ino) await fs.unlink(address);
114新增: try { await close(); }
115新增: finally {
116新增: await closed;
117新增: await queue;
118新增: const current = await fs.lstat(address).catch(() => null);
119新增: if (current?.ino === owned.ino) await fs.unlink(address);
120新增: }
119121 })();
120122 return stopping;
121123 };
修改scripts/guest-os/macos-claude-window-app.swift+29 −15看文件
@@ -26,6 +26,7 @@ struct Request: Decodable {
2626 var refresh: Bool?
2727 var wait, binary: Bool?
2828 var id, kind: String?
29新增: var ids: [String]?
2930 var transfer: String?
3031 var sequence: Int?
3132 var path: String?
@@ -246,7 +247,7 @@ private func handle(_ input: Request, inputSession: MacWindowInputSession) async
246247 return await MacDesktopFiles.shared.cancel(input.id ?? "")
247248 case "files-poll":
248249 return try await MacDesktopFiles.shared.poll()
249删除: case "files-download-open", "files-download-read", "files-download-close", "files-download-retry":
250新增: case "files-download-open", "files-download-read", "files-download-close", "files-download-retry", "files-download-ack":
250251 return try MacDesktopDownloads.shared.read(input)
251252 case "files-open-claim", "files-open-complete":
252253 return try MacDesktopFiles.shared.openAction(input.id ?? "", complete: input.action == "files-open-complete")
@@ -255,20 +256,7 @@ private func handle(_ input: Request, inputSession: MacWindowInputSession) async
255256 case "setup-status":
256257 return ["screen": CGPreflightScreenCaptureAccess(), "input": AXIsProcessTrusted()]
257258 case "setup-password-focus":
258删除: guard AXIsProcessTrusted(), let app = NSWorkspace.shared.frontmostApplication,
259删除: app.bundleIdentifier == "com.apple.authorizationhost" else { return ["focused":false] }
260删除: var code: SecCode?
261删除: var rule: SecRequirement?
262删除: guard SecCodeCopyGuestWithAttributes(nil, [kSecGuestAttributePid as String:app.processIdentifier] as CFDictionary, [], &code) == errSecSuccess,
263删除: SecRequirementCreateWithString("anchor apple and identifier com.apple.authorizationhost" as CFString, [], &rule) == errSecSuccess,
264删除: let code, let rule, SecCodeCheckValidity(code, [], rule) == errSecSuccess else { return ["focused":false] }
265删除: var value: CFTypeRef?
266删除: let element = AXUIElementCreateApplication(app.processIdentifier)
267删除: guard AXUIElementCopyAttributeValue(element,kAXFocusedUIElementAttribute as CFString,&value) == .success,
268删除: let value, CFGetTypeID(value) == AXUIElementGetTypeID() else { return ["focused":false] }
269删除: var subrole: CFTypeRef?
270删除: guard AXUIElementCopyAttributeValue(value as! AXUIElement,kAXSubroleAttribute as CFString,&subrole) == .success else { return ["focused":false] }
271删除: return ["focused":subrole as? String == kAXSecureTextFieldSubrole]
259新增: return try MacSetupPassword.probe()
272260 case "setup-screen", "setup-input", "setup-projects":
273261 let pane: String
274262 if input.action == "setup-screen" {
@@ -453,6 +441,27 @@ private func respondConnection(_ fd: Int32, inputSession: MacWindowInputSession)
453441@main
454442struct ClaudeWindowService {
455443 static func main() {
444新增: let arguments = Array(CommandLine.arguments.dropFirst())
445新增: if arguments == ["--setup-password-probe"] { MacSetupPassword.runStream() }
446新增: if arguments.count == 2 && ["--maintenance-open", "--maintenance-probe", "--maintenance-password-probe"].contains(arguments[0]) {
447新增: if arguments[0] == "--maintenance-password-probe" { MacMaintenance.runPasswordProbe(purpose: arguments[1]) }
448新增: let result: [String: Any]
449新增: do { result = try MacMaintenance.run(arguments[0] == "--maintenance-open" ? "open" : "probe", purpose: arguments[1]) }
450新增: catch { result = ["error": (error as? Failure)?.message ?? "maintenance_unavailable"] }
451新增: if let data = try? JSONSerialization.data(withJSONObject: result) {
452新增: FileHandle.standardOutput.write(data)
453新增: FileHandle.standardOutput.write(Data([10]))
454新增: }
455新增: return
456新增: }
457新增: if CommandLine.arguments.dropFirst() == ["--setup-password-self-test"] {
458新增: do { try MacSetupPassword.selfTest(); return }
459新增: catch { fputs("macOS setup password self-test failed\n", stderr); exit(1) }
460新增: }
461新增: if CommandLine.arguments.dropFirst() == ["--native-open-self-test"] {
462新增: do { try MacNativeOpen.selfTest(); return }
463新增: catch { fputs("macOS native open self-test failed (\((error as? Failure)?.message ?? "unknown error"))\n", stderr); exit(1) }
464新增: }
456465 if CommandLine.arguments.dropFirst() == ["--phone-self-test"] {
457466 do { try MacPhoneDesktop.selfTest(); return }
458467 catch { fputs("macOS phone desktop self-test failed\n", stderr); exit(1) }
@@ -472,6 +481,11 @@ struct ClaudeWindowService {
472481 free(sockets)
473482 GuestDiagnostic.record("window", "started")
474483 NSApplication.shared.setActivationPolicy(.accessory)
484新增: MacNativeOpen.shared.install()
485新增: Task { @MainActor in
486新增: do { try await MacNativeOpen.shared.prepareMetadata() }
487新增: catch { GuestDiagnostic.record("files", (error as? Failure)?.message ?? "file_open_metadata_failed") }
488新增: }
475489 DispatchQueue.global(qos: .userInitiated).async {
476490 let connections = DispatchSemaphore(value: 16)
477491 while true {
修改scripts/guest-os/macos-desktop-downloads.swift+121 −4看文件
@@ -11,6 +11,10 @@ final class MacDesktopDownloads {
1111 let name: String
1212 var state = "downloading"
1313 var error = ""
14新增: var openError: String?
15新增: var acknowledged: Bool?
16新增: var device: UInt64?
17新增: var inode: UInt64?
1418 var size: Int64 = 0
1519 var modified: Int64 = 0
1620 var started = Date()
@@ -30,6 +34,8 @@ final class MacDesktopDownloads {
3034 private let baseDirectory: URL
3135 private var transferTimer: Timer?
3236 private let timestamp = ISO8601DateFormatter()
37新增: private var openMetadata: Data?
38新增: private var metadataBound = Set<String>()
3339
3440 init(directory: URL) { baseDirectory = directory }
3541 deinit {
@@ -59,7 +65,9 @@ final class MacDesktopDownloads {
5965 }
6066 let data = try Data(contentsOf: manifest, options: .mappedIfSafe)
6167 guard data.count <= 1 << 20 else { throw Failure(8, "desktop_download_catalog_invalid") }
62删除: records = try JSONDecoder().decode([Record].self, from: data).suffix(100).filter { UUID(uuidString: $0.id) != nil && Self.validName($0.name) }
68新增: let saved = try JSONDecoder().decode([Record].self, from: data)
69新增: guard saved.count <= 100 else { throw Failure(8, "desktop_download_catalog_invalid") }
70新增: records = saved.filter { UUID(uuidString: $0.id) != nil && Self.validName($0.name) }
6371 for index in records.indices where records[index].state == "downloading" {
6472 records[index].state = "failed"
6573 records[index].error = "保存过程被中断,请从 Claude Desktop 重新下载。"
@@ -71,7 +79,7 @@ final class MacDesktopDownloads {
7179 private func source(_ record: Record) throws -> URL { try directory().appendingPathComponent(record.id, isDirectory: true).appendingPathComponent(record.name) }
7280 private func persist() throws {
7381 let path = try directory().appendingPathComponent("downloads.json")
74删除: try JSONEncoder().encode(Array(records.suffix(100))).write(to: path, options: .atomic)
82新增: try JSONEncoder().encode(records).write(to: path, options: .atomic)
7583 try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: path.path)
7684 }
7785 private func openSource(_ record: Record) throws -> (Int32, stat) {
@@ -87,6 +95,86 @@ final class MacDesktopDownloads {
8795 }
8896 private func modified(_ info: stat) -> Int64 { Int64(info.st_mtimespec.tv_sec) * 1_000_000_000 + Int64(info.st_mtimespec.tv_nsec) }
8997
98新增: private func removeSource(_ record: Record) throws {
99新增: let path = try source(record)
100新增: let folder = path.deletingLastPathComponent().path
101新增: let parent = open(folder, O_RDONLY | O_DIRECTORY | O_NOFOLLOW)
102新增: if parent < 0 && errno == ENOENT { return }
103新增: guard parent >= 0 else { throw Failure(8, "desktop_download_cleanup_failed") }
104新增: defer { close(parent) }
105新增: var directoryInfo = stat(), actual = [CChar](repeating: 0, count: Int(MAXPATHLEN))
106新增: guard fstat(parent, &directoryInfo) == 0, directoryInfo.st_uid == getuid(),
107新增: fcntl(parent, F_GETPATH, &actual) == 0, String(cString: actual) == folder else { throw Failure(8, "desktop_download_directory_invalid") }
108新增: var info = stat()
109新增: let found = fstatat(parent, record.name, &info, AT_SYMLINK_NOFOLLOW)
110新增: if found != 0 && errno != ENOENT { throw Failure(8, "desktop_download_cleanup_failed") }
111新增: if found == 0 {
112新增: guard record.state == "saved", info.st_mode & S_IFMT == S_IFREG, info.st_uid == getuid(), info.st_size == record.size,
113新增: modified(info) == record.modified, record.device == UInt64(UInt32(bitPattern: info.st_dev)),
114新增: record.inode == UInt64(info.st_ino) else { throw Failure(8, "desktop_download_changed") }
115新增: guard unlinkat(parent, record.name, 0) == 0 else { throw Failure(8, "desktop_download_cleanup_failed") }
116新增: }
117新增: // rmdir preserves any unrecorded sibling, and the open parent prevents
118新增: // following a replacement directory while removing the recorded leaf.
119新增: var current = stat()
120新增: guard lstat(folder, &current) == 0, current.st_dev == directoryInfo.st_dev, current.st_ino == directoryInfo.st_ino else { throw Failure(8, "desktop_download_directory_invalid") }
121新增: let removed = rmdir(folder)
122新增: if record.state == "failed" && removed != 0 { throw Failure(8, "desktop_download_cleanup_failed") }
123新增: }
124新增:
125新增: private func makeRoom() throws {
126新增: expireTransfers()
127新增: guard records.count >= 100 else { return }
128新增: for record in records {
129新增: let eligible = (record.state == "saved" && record.acknowledged == true) || (record.state == "failed" && watches[record.id] == nil)
130新增: guard eligible, !transfers.values.contains(where: { $0.record.id == record.id }) else { continue }
131新增: do {
132新增: try removeSource(record)
133新增: records.removeAll { $0.id == record.id }
134新增: metadataBound.remove(record.id)
135新增: return
136新增: } catch { /* Keep the receipt when ownership, contents, or permissions changed. */ }
137新增: }
138新增: throw Failure(8, "desktop_download_limit")
139新增: }
140新增:
141新增: private func bindOpenMetadata(_ metadata: Data, fd: Int32, info: stat) throws {
142新增: let name = "com.apple.LaunchServices.OpenWith"
143新增: guard !metadata.isEmpty, metadata.count <= 1 << 20 else { throw Failure(8, "desktop_download_open_metadata_failed") }
144新增: if fgetxattr(fd, name, nil, 0, 0, 0) == metadata.count {
145新增: var current = Data(count: metadata.count)
146新增: let count = current.withUnsafeMutableBytes { fgetxattr(fd, name, $0.baseAddress, $0.count, 0, 0) }
147新增: if count == metadata.count && current == metadata { return }
148新增: }
149新增: let written = metadata.withUnsafeBytes { fsetxattr(fd, name, $0.baseAddress, $0.count, 0, 0) }
150新增: var current = Data(count: metadata.count), after = stat()
151新增: let count = current.withUnsafeMutableBytes { fgetxattr(fd, name, $0.baseAddress, $0.count, 0, 0) }
152新增: guard written == 0, count == metadata.count, current == metadata else { throw Failure(8, "desktop_download_open_metadata_failed") }
153新增: guard fstat(fd, &after) == 0, after.st_dev == info.st_dev, after.st_ino == info.st_ino,
154新增: after.st_size == info.st_size, modified(after) == modified(info) else { throw Failure(8, "desktop_download_changed") }
155新增: }
156新增:
157新增: private func refreshOpenMetadata() throws {
158新增: guard let metadata = MacNativeOpen.shared.openWithMetadata else { return }
159新增: if openMetadata != metadata { openMetadata = metadata; metadataBound.removeAll() }
160新增: var changed = false
161新增: for index in records.indices where records[index].state == "saved" && !metadataBound.contains(records[index].id) {
162新增: let previous = records[index].openError
163新增: do {
164新增: let (fd, info) = try openSource(records[index])
165新增: defer { close(fd) }
166新增: guard info.st_size == records[index].size, modified(info) == records[index].modified else { throw Failure(8, "desktop_download_changed") }
167新增: try bindOpenMetadata(metadata, fd: fd, info: info)
168新增: metadataBound.insert(records[index].id)
169新增: records[index].openError = nil
170新增: } catch {
171新增: records[index].openError = "文件打开关联未能完成,请在 Cage 下载列表中打开文件。"
172新增: }
173新增: changed = changed || previous != records[index].openError
174新增: }
175新增: if changed { try persist() }
176新增: }
177新增:
90178 private func expireTransfers() {
91179 let epoch = try? MacGUISession.shared.validate()
92180 for (key, transfer) in transfers where epoch != transfer.epoch || Date().timeIntervalSince(transfer.used) > 120 {
@@ -98,6 +186,7 @@ final class MacDesktopDownloads {
98186 func reserve(name: String, pid: Int32, submit: (String) async throws -> Void) async throws {
99187 _ = try directory()
100188 guard Self.validName(name), records.filter({ $0.state == "downloading" }).count < 12 else { throw Failure(8, "desktop_download_limit") }
189新增: try makeRoom()
101190 let record = Record(id: UUID().uuidString.lowercased(), name: name)
102191 let path = try source(record)
103192 try FileManager.default.createDirectory(at: path.deletingLastPathComponent(), withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700])
@@ -107,7 +196,6 @@ final class MacDesktopDownloads {
107196 else { self?.fail(record.id, message: "保存通知已中断,请从 Claude Desktop 重新下载。") }
108197 }
109198 }
110删除: while records.count >= 100, let oldest = records.firstIndex(where: { $0.state != "downloading" }) { records.remove(at: oldest) }
111199 records.append(record); watches[record.id] = watcher
112200 do { try persist(); try await submit(path.path) }
113201 catch { fail(record.id, message: "客机保存窗口未接收文件位置,请重新下载。"); throw error }
@@ -140,6 +228,12 @@ final class MacDesktopDownloads {
140228 defer { close(fd) }
141229 guard let index = records.firstIndex(where: { $0.id == id }) else { return }
142230 records[index].size = info.st_size; records[index].modified = modified(info); records[index].state = "saved"
231新增: records[index].device = UInt64(UInt32(bitPattern: info.st_dev)); records[index].inode = UInt64(info.st_ino)
232新增: if let metadata = MacNativeOpen.shared.openWithMetadata {
233新增: if openMetadata != metadata { openMetadata = metadata; metadataBound.removeAll() }
234新增: do { try bindOpenMetadata(metadata, fd: fd, info: info); metadataBound.insert(id) }
235新增: catch { records[index].openError = "文件打开关联未能完成,请在 Cage 下载列表中打开文件。" }
236新增: }
143237 try persist(); watches.removeValue(forKey: id)?.stop(); return
144238 }
145239 } catch { }
@@ -149,10 +243,12 @@ final class MacDesktopDownloads {
149243 }
150244 func snapshot() throws -> [[String: Any]] {
151245 _ = try directory()
246新增: try refreshOpenMetadata()
152247 return records.suffix(100).reversed().map { record in
153248 ["id": record.id, "name": record.name, "target": "desktop", "state": record.state,
249新增: "acknowledged": record.acknowledged ?? false,
154250 "receivedBytes": record.size, "totalBytes": record.size, "retryable": false,
155删除: "error": record.error, "startedAt": timestamp.string(from: record.started)]
251新增: "error": record.error, "openError": record.openError ?? "", "startedAt": timestamp.string(from: record.started)]
156252 }
157253 }
158254 func find(path: String) throws -> (id: String, directory: Bool)? {
@@ -170,6 +266,27 @@ final class MacDesktopDownloads {
170266 for (key, transfer) in transfers where transfer.epoch != epoch || Date().timeIntervalSince(transfer.used) > 120 {
171267 close(transfer.fd); transfers.removeValue(forKey: key)
172268 }
269新增: if input.action == "files-download-ack" {
270新增: guard let ids = input.ids, ids.count <= 100, ids.allSatisfy({ UUID(uuidString: $0) != nil }) else { throw Failure(8, "desktop_download_ack_invalid") }
271新增: let previous = records
272新增: var changed = false
273新增: do {
274新增: for index in records.indices where ids.contains(records[index].id) && records[index].state == "saved" && records[index].acknowledged != true {
275新增: if records[index].device == nil || records[index].inode == nil {
276新增: if let (fd, info) = try? openSource(records[index]) {
277新增: defer { close(fd) }
278新增: if info.st_size == records[index].size && modified(info) == records[index].modified {
279新增: records[index].device = UInt64(UInt32(bitPattern: info.st_dev)); records[index].inode = UInt64(info.st_ino)
280新增: }
281新增: }
282新增: }
283新增: records[index].acknowledged = true
284新增: changed = true
285新增: }
286新增: if changed { try persist() }
287新增: } catch { records = previous; throw error }
288新增: return ["ok": true]
289新增: }
173290 if input.action == "files-download-retry" {
174291 guard let record = records.first(where: { $0.id == input.id }), record.state == "saved" else { throw Failure(8, "desktop_download_incomplete") }
175292 let (fd, info) = try openSource(record)
修改scripts/guest-os/macos-desktop-files.swift+3 −3看文件
@@ -493,7 +493,7 @@ final class MacDesktopFiles {
493493 if !value.files.isEmpty { Task { _ = try? await clipboardRequest(["operation": "discard", "files": value.files]) } }
494494 }
495495 guard AXIsProcessTrusted(), let pid = try? claudePIDs().first else {
496删除: return ["available": false, "uploads": [], "downloads": try MacDesktopDownloads.shared.snapshot(), "opens": openSnapshot()]
496新增: return ["available": false, "uploads": [], "downloads": try MacDesktopDownloads.shared.snapshot(), "downloadAck": true, "opens": openSnapshot()]
497497 }
498498 if let (panel, field) = saveFilePanel(pid) {
499499 if savingPanel == nil || !CFEqual(savingPanel!, panel) {
@@ -509,7 +509,7 @@ final class MacDesktopFiles {
509509 batches.removeValue(forKey: id)
510510 if !value.files.isEmpty { Task { _ = try? await clipboardRequest(["operation": "discard", "files": value.files]) } }
511511 }
512删除: return ["available": true, "uploads": [], "downloads": try MacDesktopDownloads.shared.snapshot(), "opens": openSnapshot()]
512新增: return ["available": true, "uploads": [], "downloads": try MacDesktopDownloads.shared.snapshot(), "downloadAck": true, "opens": openSnapshot()]
513513 }
514514 let existing = batches.first { $0.value.pid == pid && $0.value.panel.map { CFEqual($0, panel) } == true }
515515 let id: String
@@ -519,7 +519,7 @@ final class MacDesktopFiles {
519519 id = UUID().uuidString.lowercased()
520520 batches[id] = Batch(pid: pid, window: 0, kind: "chooser", epoch: try MacGUISession.shared.validate(), panel: panel)
521521 }
522删除: return ["available": true, "uploads": [["id": id, "kind": "chooser", "multiple": true, "directory": false, "target": "desktop"]], "downloads": try MacDesktopDownloads.shared.snapshot(), "opens": openSnapshot()]
522新增: return ["available": true, "uploads": [["id": id, "kind": "chooser", "multiple": true, "directory": false, "target": "desktop"]], "downloads": try MacDesktopDownloads.shared.snapshot(), "downloadAck": true, "opens": openSnapshot()]
523523 }
524524
525525 func pasteImage(_ data: Data, window: SCWindow) async throws -> [String: Any] {
新增scripts/guest-os/macos-maintenance.swift+114 −0看文件
@@ -0,0 +1,114 @@
1新增:import AppKit
2新增:import IOKit
3新增:import Security
4新增:
5新增:// Invoked directly by the installation identity after verifying this bundle.
6新增:// Only Apple system settings and its authorization UI can supply a target.
7新增:@MainActor
8新增:enum MacMaintenance {
9新增: private static let applications: Set<String> = ["com.apple.systempreferences", "com.apple.authorizationhost"]
10新增: private static let panes = [
11新增: "projects": "x-apple.systempreferences:com.apple.LoginItems-Settings.extension",
12新增: "screen": "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture",
13新增: "input": "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility",
14新增: ]
15新增:
16新增: static func runPasswordProbe(purpose: String) -> Never {
17新增: guard panes[purpose] != nil else { exit(2) }
18新增: MacSetupPassword.runStream()
19新增: }
20新增:
21新增: private static func consoleSession() throws -> String {
22新增: try consoleUser()
23新增: let entry = IORegistryGetRootEntry(kIOMainPortDefault)
24新增: guard entry != 0 else { throw Failure(4, "requires_gui_login") }
25新增: defer { IOObjectRelease(entry) }
26新增: guard let property = IORegistryEntryCreateCFProperty(entry, "IOConsoleUsers" as CFString, kCFAllocatorDefault, 0)?.takeRetainedValue(),
27新增: let sessions = property as? [[String: Any]] else { throw Failure(4, "requires_gui_login") }
28新增: let active = sessions.filter { $0["kCGSSessionOnConsoleKey"] as? Bool == true }
29新增: guard active.count == 1, let current = active.first,
30新增: current["kCGSessionLoginDoneKey"] as? Bool == true,
31新增: current["CGSSessionScreenIsLocked"] as? Bool != true,
32新增: current["kCGSSessionUserIDKey"] as? UInt32 == getuid(),
33新增: current["kCGSSessionUserNameKey"] as? String == NSUserName(),
34新增: let session = current["CGSSessionUniqueSessionUUID"] as? String,
35新增: UUID(uuidString: session) != nil else { throw Failure(4, "requires_gui_login") }
36新增: return session
37新增: }
38新增:
39新增: private static func verified(_ app: NSRunningApplication) -> Bool {
40新增: guard let bundle = app.bundleIdentifier, applications.contains(bundle) else { return false }
41新增: var code: SecCode?, requirement: SecRequirement?
42新增: return SecRequirementCreateWithString("anchor apple and identifier \"\(bundle)\"" as CFString, [], &requirement) == errSecSuccess &&
43新增: SecCodeCopyGuestWithAttributes(nil, [kSecGuestAttributePid as String: app.processIdentifier] as CFDictionary, [], &code) == errSecSuccess &&
44新增: code != nil && requirement != nil && SecCodeCheckValidity(code!, [], requirement!) == errSecSuccess
45新增: }
46新增:
47新增: private static func passwordFocused(_ app: NSRunningApplication, window: CGRect) -> Bool {
48新增: guard let bundle = app.bundleIdentifier, applications.contains(bundle), AXIsProcessTrusted() else { return false }
49新增: let application = AXUIElementCreateApplication(app.processIdentifier)
50新增: AXUIElementSetMessagingTimeout(application, 0.5)
51新增: func attribute(_ element: AXUIElement, _ name: String) -> CFTypeRef? {
52新增: var value: CFTypeRef?
53新增: return AXUIElementCopyAttributeValue(element, name as CFString, &value) == .success ? value : nil
54新增: }
55新增: guard let value = attribute(application, kAXFocusedUIElementAttribute), CFGetTypeID(value) == AXUIElementGetTypeID() else { return false }
56新增: let field = value as! AXUIElement
57新增: var pid: pid_t = 0
58新增: guard AXUIElementGetPid(field, &pid) == .success, pid == app.processIdentifier,
59新增: attribute(field, kAXSubroleAttribute) as? String == kAXSecureTextFieldSubrole,
60新增: attribute(field, kAXEnabledAttribute) as? Bool == true,
61新增: let rawWindow = attribute(field, kAXWindowAttribute), CFGetTypeID(rawWindow) == AXUIElementGetTypeID() else { return false }
62新增: let owner = rawWindow as! AXUIElement
63新增: var origin = CGPoint.zero, size = CGSize.zero
64新增: guard let position = attribute(owner, kAXPositionAttribute), let extent = attribute(owner, kAXSizeAttribute),
65新增: CFGetTypeID(position) == AXValueGetTypeID(), CFGetTypeID(extent) == AXValueGetTypeID(),
66新增: AXValueGetValue(position as! AXValue, .cgPoint, &origin), AXValueGetValue(extent as! AXValue, .cgSize, &size) else { return false }
67新增: return abs(origin.x - window.minX) < 1 && abs(origin.y - window.minY) < 1 &&
68新增: abs(size.width - window.width) < 1 && abs(size.height - window.height) < 1
69新增: }
70新增:
71新增: static func run(_ operation: String, purpose: String) throws -> [String: Any] {
72新增: try requireGuest()
73新增: let session = try consoleSession()
74新增: guard let pane = panes[purpose] else { throw Failure(8, "maintenance_purpose_invalid") }
75新增: if operation == "open" {
76新增: if purpose == "projects" {
77新增: let configuration = NSWorkspace.OpenConfiguration()
78新增: configuration.activates = false
79新增: NSWorkspace.shared.openApplication(at: URL(fileURLWithPath: "/Applications/macFUSE.app"), configuration: configuration)
80新增: }
81新增: guard let url = URL(string: pane), NSWorkspace.shared.open(url) else { throw Failure(8, "maintenance_open_failed") }
82新增: return ["opened": true]
83新增: }
84新增: guard operation == "probe", let front = NSWorkspace.shared.frontmostApplication, verified(front) else {
85新增: throw Failure(7, "maintenance_foreground_changed")
86新增: }
87新增: guard let windows = CGWindowListCopyWindowInfo([.optionOnScreenOnly, .excludeDesktopElements], kCGNullWindowID) as? [[String: Any]] else {
88新增: throw Failure(7, "maintenance_window_unavailable")
89新增: }
90新增: let display = CGDisplayBounds(CGMainDisplayID())
91新增: var covering: [CGRect] = []
92新增: for window in windows {
93新增: guard let raw = window[kCGWindowBounds as String] as? [String: Any],
94新增: let bounds = CGRect(dictionaryRepresentation: raw as CFDictionary), bounds.width > 0, bounds.height > 0,
95新增: (window[kCGWindowAlpha as String] as? Double ?? 1) > 0 else { continue }
96新增: let owner = window[kCGWindowOwnerPID as String] as? Int32
97新增: if owner == front.processIdentifier && bounds.width >= 100 && bounds.height >= 60 {
98新增: let region = bounds.intersection(display)
99新增: guard !region.isNull, region.width >= 80, region.height >= 40,
100新增: !covering.contains(where: { $0.intersects(region) }),
101新增: let id = window[kCGWindowNumber as String] as? UInt32,
102新增: NSWorkspace.shared.frontmostApplication?.processIdentifier == front.processIdentifier,
103新增: try consoleSession() == session else { throw Failure(7, "maintenance_window_obscured") }
104新增: return ["version": 1, "session": session, "user": NSUserName(), "pid": front.processIdentifier,
105新增: "window": id, "bundle": front.bundleIdentifier!,
106新增: "password_focused": passwordFocused(front, window: bounds),
107新增: "rect": [region.minX, region.minY, region.width, region.height],
108新增: "display": [display.minX, display.minY, display.width, display.height]]
109新增: }
110新增: if owner != front.processIdentifier { covering.append(bounds) }
111新增: }
112新增: throw Failure(7, "maintenance_window_unavailable")
113新增: }
114新增:}
修改scripts/guest-os/macos-native-browser.mjs+5 −2看文件
@@ -1,4 +1,4 @@
1删除:// Started by Cage through the bound ordinary user's SSH connection.
1新增:// The bound guest user's LaunchAgent owns the browser. SSH callers attach as clients.
22import { installMacOSCLIBrowser } from "./macos-cli-browser.mjs";
33import { spawn } from "node:child_process";
44import { randomBytes } from "node:crypto";
@@ -120,7 +120,10 @@ if (process.argv[2] !== "--service") {
120120 let closeLogin;
121121 try { closeLogin = await installMacOSCLIBrowser(data, message => server.request(message)); }
122122 catch (error) { await server.close(); throw error; }
123删除: const shutdown = async () => { await server.close(); await closeLogin(); };
123新增: const shutdown = async () => {
124新增: try { await server.close(); }
125新增: finally { await closeLogin(); }
126新增: };
124127 process.once("SIGTERM", () => { void shutdown().catch(() => { process.exitCode = 1; }); });
125128 process.once("SIGINT", () => { void shutdown().catch(() => { process.exitCode = 1; }); });
126129}
新增scripts/guest-os/macos-native-open.swift+194 −0看文件
@@ -0,0 +1,194 @@
1新增:import AppKit
2新增:import ApplicationServices
3新增:import Carbon
4新增:import Security
5新增:import UniformTypeIdentifiers
6新增:
7新增:// These attributes come from the AppleEvent manager, never from the socket RPC.
8新增:struct MacOpenSender {
9新增: let audit: Data
10新增: let pid: pid_t
11新增:
12新增: init?(_ event: NSAppleEventDescriptor) {
13新增: guard let data = event.attributeDescriptor(forKeyword: AEKeyword(keySenderAuditTokenAttr))?.data,
14新增: data.count == MemoryLayout<audit_token_t>.size else { return nil }
15新增: var token = audit_token_t()
16新增: _ = withUnsafeMutableBytes(of: &token) { data.copyBytes(to: $0) }
17新增: let process = audit_token_to_pid(token)
18新增: guard process > 0, audit_token_to_euid(token) == geteuid(),
19新增: event.attributeDescriptor(forKeyword: AEKeyword(keySenderPIDAttr))?.int32Value == process else { return nil }
20新增: audit = data
21新增: pid = process
22新增: }
23新增:
24新增: func isOfficialClaude() -> Bool {
25新增: guard let application = NSRunningApplication(processIdentifier: pid), !application.isTerminated,
26新增: application.bundleIdentifier == "com.anthropic.claudefordesktop",
27新增: application.bundleURL?.resolvingSymlinksInPath() == URL(fileURLWithPath: "/Applications/Claude.app").resolvingSymlinksInPath(),
28新增: let requirement = try? claudeSigningRequirement() else { return false }
29新增: var code: SecCode?
30新增: guard SecCodeCopyGuestWithAttributes(nil, [kSecGuestAttributeAudit as String: audit] as CFDictionary, [], &code) == errSecSuccess,
31新增: let code else { return false }
32新增: return SecCodeCheckValidity(code, [], requirement) == errSecSuccess
33新增: }
34新增:}
35新增:
36新增:@MainActor
37新增:final class MacNativeOpen: NSObject {
38新增: static let shared = MacNativeOpen()
39新增: private(set) var openWithMetadata: Data?
40新增:
41新增: func install() {
42新增: NSAppleEventManager.shared().setEventHandler(self, andSelector: #selector(openDocuments(_:reply:)),
43新增: forEventClass: AEEventClass(kCoreEventClass), andEventID: AEEventID(kAEOpenDocuments))
44新增: }
45新增:
46新增: static func fileURLs(_ event: NSAppleEventDescriptor) throws -> [URL] {
47新增: guard let direct = event.paramDescriptor(forKeyword: AEKeyword(keyDirectObject)),
48新增: (1...32).contains(direct.numberOfItems) else { throw Failure(8, "file_open_request_invalid") }
49新增: return try (1...direct.numberOfItems).map { index in
50新增: guard let descriptor = direct.atIndex(index)?.coerce(toDescriptorType: DescType(typeFileURL)),
51新增: descriptor.data.count <= 98304,
52新增: let url = URL(dataRepresentation: descriptor.data, relativeTo: nil), url.isFileURL,
53新增: url.host == nil || url.host == "" || url.host == "localhost",
54新增: url.user == nil, url.password == nil, url.query == nil, url.fragment == nil,
55新增: let encodedPath = URLComponents(url: url, resolvingAgainstBaseURL: false)?.percentEncodedPath,
56新增: let decodedPath = encodedPath.removingPercentEncoding, !decodedPath.contains("\0"),
57新增: url.path.hasPrefix("/"), url.path.utf8.count <= 32768 else {
58新增: throw Failure(8, "file_open_request_invalid")
59新增: }
60新增: return url.standardizedFileURL
61新增: }
62新增: }
63新增:
64新增: static func selfTest() throws {
65新增: func event(_ values: [String]) -> NSAppleEventDescriptor {
66新增: let request = NSAppleEventDescriptor.appleEvent(withEventClass: AEEventClass(kCoreEventClass),
67新增: eventID: AEEventID(kAEOpenDocuments), targetDescriptor: nil,
68新增: returnID: AEReturnID(kAutoGenerateReturnID), transactionID: AETransactionID(kAnyTransactionID))
69新增: let list = NSAppleEventDescriptor.list()
70新增: for (index, value) in values.enumerated() {
71新增: list.insert(NSAppleEventDescriptor(descriptorType: DescType(typeFileURL), data: Data(value.utf8))!, at: index + 1)
72新增: }
73新增: request.setParam(list, forKeyword: AEKeyword(keyDirectObject))
74新增: return request
75新增: }
76新增: let valid = event(["file:///tmp/cage-open-self-test/a%20b.txt", "file://localhost/tmp/cage-open-self-test/c.txt"])
77新增: guard try fileURLs(valid).map(\.path) == ["/tmp/cage-open-self-test/a b.txt", "/tmp/cage-open-self-test/c.txt"],
78新增: MacOpenSender(valid) == nil else { throw Failure(8, "file_open_self_test_valid_paths") }
79新增: let invalid = [[], ["https://example.invalid/file"], ["file://example.invalid/tmp/a"],
80新增: ["file:///tmp/a?query=1"], ["file:///tmp/a#fragment"], ["file:///tmp/a%00b"],
81新增: Array(repeating: "file:///tmp/cage-open-self-test/a", count: 33)]
82新增: for (index, values) in invalid.enumerated() {
83新增: if (try? fileURLs(event(values))) != nil { throw Failure(8, "file_open_self_test_invalid_\(index)") }
84新增: }
85新增: guard try fileURLs(event(Array(repeating: "file:///tmp/cage-open-self-test/a", count: 32))).count == 32 else {
86新增: throw Failure(8, "file_open_self_test_failed")
87新增: }
88新增: valid.setAttribute(NSAppleEventDescriptor(int32: getpid()), forKeyword: AEKeyword(keySenderPIDAttr))
89新增: valid.setAttribute(NSAppleEventDescriptor(descriptorType: DescType(typeAuditToken), data: Data(repeating: 0, count: 32))!,
90新增: forKeyword: AEKeyword(keySenderAuditTokenAttr))
91新增: guard MacOpenSender(valid) == nil else { throw Failure(8, "file_open_self_test_failed") }
92新增: print("macOS native open parser and untrusted-event checks passed")
93新增: }
94新增:
95新增: private static func focusedWindow(_ pid: pid_t) -> AXUIElement? {
96新增: var value: CFTypeRef?
97新增: guard AXUIElementCopyAttributeValue(AXUIElementCreateApplication(pid), kAXFocusedWindowAttribute as CFString, &value) == .success,
98新增: let value, CFGetTypeID(value) == AXUIElementGetTypeID() else { return nil }
99新增: return (value as! AXUIElement)
100新增: }
101新增:
102新增: @objc private func openDocuments(_ event: NSAppleEventDescriptor, reply: NSAppleEventDescriptor) {
103新增: do {
104新增: let urls = try Self.fileURLs(event)
105新增: guard let sender = MacOpenSender(event), sender.isOfficialClaude() else {
106新增: for url in urls { try forwardToGuestApplication(url) }
107新增: return
108新增: }
109新增: let epoch = try MacGUISession.shared.validate()
110新增: guard AXIsProcessTrusted(), let window = Self.focusedWindow(sender.pid) else { throw Failure(7, "file_open_target_changed") }
111新增: let validate = {
112新增: try MacGUISession.shared.validate(epoch)
113新增: guard sender.isOfficialClaude(), let current = Self.focusedWindow(sender.pid), CFEqual(current, window) else {
114新增: throw Failure(7, "file_open_target_changed")
115新增: }
116新增: }
117新增: try MacDesktopFiles.shared.queueOpen(paths: urls.map(\.path), action: "open", validate: validate)
118新增: let restoreFocus = {
119新增: guard (try? validate()) != nil,
120新增: NSWorkspace.shared.frontmostApplication?.processIdentifier == getpid() else { return }
121新增: if NSRunningApplication(processIdentifier: sender.pid)?.activate(options: []) != true {
122新增: GuestDiagnostic.record("files", "file_open_focus_restore_failed")
123新增: }
124新增: }
125新增: restoreFocus()
126新增: DispatchQueue.main.async { restoreFocus() }
127新增: } catch {
128新增: let reason = (error as? Failure)?.message ?? "file_open_failed"
129新增: GuestDiagnostic.record("files", reason)
130新增: reply.setParam(NSAppleEventDescriptor(int32: Int32(errAEEventFailed)), forKeyword: AEKeyword(keyErrorNumber))
131新增: reply.setParam(NSAppleEventDescriptor(string: reason), forKeyword: AEKeyword(keyErrorString))
132新增: }
133新增: }
134新增:
135新增: private func forwardToGuestApplication(_ url: URL) throws {
136新增: let values = try url.resourceValues(forKeys: [.contentTypeKey, .isDirectoryKey])
137新增: let type = values.isDirectory == true ? UTType.folder : values.contentType ?? UTType.data
138新增: let current = Bundle.main.bundleURL.resolvingSymlinksInPath()
139新增: let preferred = NSWorkspace.shared.urlForApplication(toOpen: type)
140新增: let candidates = [preferred].compactMap { $0 } + NSWorkspace.shared.urlsForApplications(toOpen: type)
141新增: guard let target = candidates.first(where: {
142新增: $0.resolvingSymlinksInPath() != current && Bundle(url: $0)?.bundleIdentifier != Bundle.main.bundleIdentifier
143新增: }) else { throw Failure(8, "file_open_application_unavailable") }
144新增: // An explicit target avoids resolving this file's OpenWith attribute again.
145新增: let configuration = NSWorkspace.OpenConfiguration()
146新增: configuration.addsToRecentItems = false
147新增: NSWorkspace.shared.open([url], withApplicationAt: target, configuration: configuration) { _, error in
148新增: if error != nil { GuestDiagnostic.record("files", "file_open_application_failed") }
149新增: }
150新增: }
151新增:
152新增: func prepareMetadata() async throws {
153新增: let bundle = Bundle.main.bundleURL.resolvingSymlinksInPath()
154新增: guard bundle.path == "/Applications/Cage Guest Window.app", Bundle.main.bundleIdentifier == "dev.cage.GuestClaudeWindow",
155新增: LSRegisterURL(bundle as CFURL, true) == noErr else { throw Failure(8, "file_open_registration_failed") }
156新增: let cache = URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("Library/Caches/dev.cage.GuestClaudeWindow", isDirectory: true)
157新增: var attributes = stat()
158新增: guard lstat(cache.path, &attributes) == 0, attributes.st_mode & S_IFMT == S_IFDIR,
159新增: attributes.st_uid == geteuid(), attributes.st_mode & 0o077 == 0 else { throw Failure(8, "file_open_cache_invalid") }
160新增: let fixture = cache.appendingPathComponent("openwith-\(UUID().uuidString.lowercased()).txt")
161新增: let fd = open(fixture.path, O_CREAT | O_EXCL | O_WRONLY | O_NOFOLLOW, 0o600)
162新增: guard fd >= 0 else { throw Failure(8, "file_open_metadata_failed") }
163新增: close(fd)
164新增: defer { try? FileManager.default.removeItem(at: fixture) }
165新增: try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
166新增: NSWorkspace.shared.setDefaultApplication(at: bundle, toOpenFileAt: fixture) { error in
167新增: if let error { continuation.resume(throwing: error) }
168新增: else { continuation.resume() }
169新增: }
170新增: }
171新增: guard NSWorkspace.shared.urlForApplication(toOpen: fixture)?.resolvingSymlinksInPath() == bundle else {
172新增: throw Failure(8, "file_open_registration_failed")
173新增: }
174新增: let name = "com.apple.LaunchServices.OpenWith"
175新增: let length = getxattr(fixture.path, name, nil, 0, 0, XATTR_NOFOLLOW)
176新增: guard (1...8192).contains(length) else { throw Failure(8, "file_open_metadata_failed") }
177新增: var bytes = [UInt8](repeating: 0, count: length)
178新增: guard getxattr(fixture.path, name, &bytes, bytes.count, 0, XATTR_NOFOLLOW) == length else {
179新增: throw Failure(8, "file_open_metadata_failed")
180新增: }
181新增: let temporary = cache.appendingPathComponent("openwith-\(UUID().uuidString.lowercased()).data")
182新增: let output = open(temporary.path, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, 0o600)
183新增: guard output >= 0 else { throw Failure(8, "file_open_metadata_failed") }
184新增: let file = FileHandle(fileDescriptor: output, closeOnDealloc: true)
185新增: defer { try? FileManager.default.removeItem(at: temporary) }
186新增: try file.write(contentsOf: Data(bytes))
187新增: try file.synchronize()
188新增: try file.close()
189新增: guard rename(temporary.path, cache.appendingPathComponent("openwith.data").path) == 0 else {
190新增: throw Failure(8, "file_open_metadata_failed")
191新增: }
192新增: openWithMetadata = Data(bytes)
193新增: }
194新增:}
新增scripts/guest-os/macos-setup-password.swift+191 −0看文件
@@ -0,0 +1,191 @@
1新增:import AppKit
2新增:import IOKit
3新增:import Security
4新增:
5新增:@MainActor
6新增:enum MacSetupPassword {
7新增: private static func validateRequest(_ data: Data) throws {
8新增: guard data.count <= 4096, let value = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
9新增: value.isEmpty || (value.count == 1 && value["action"] as? String == "probe") else {
10新增: throw Failure(8, "setup_password_probe_request_invalid")
11新增: }
12新增: }
13新增:
14新增: nonisolated private static func nextLine() -> Data? {
15新增: var data = Data()
16新增: var oversized = false
17新增: while true {
18新增: let byte = fgetc(stdin)
19新增: if byte == EOF { return data.isEmpty && !oversized ? nil : (oversized ? Data() : data) }
20新增: if byte == 10 { return oversized ? Data() : data }
21新增: if data.count < 4096 { data.append(UInt8(byte)) }
22新增: else { oversized = true }
23新增: }
24新增: }
25新增:
26新增: static func runStream() -> Never {
27新增: _ = signal(SIGPIPE, SIG_IGN)
28新增: NSApplication.shared.setActivationPolicy(.prohibited)
29新增: DispatchQueue.global(qos: .userInitiated).async {
30新增: while let data = nextLine() {
31新增: let finished = DispatchSemaphore(value: 0)
32新增: DispatchQueue.main.async {
33新增: let response: [String: Any]
34新增: do {
35新增: try validateRequest(data)
36新增: response = try probe()
37新增: } catch { response = ["error": (error as? Failure)?.message ?? "setup_password_probe_failed"] }
38新增: do {
39新增: var encoded = try JSONSerialization.data(withJSONObject: response)
40新增: encoded.append(10)
41新增: try FileHandle.standardOutput.write(contentsOf: encoded)
42新增: } catch { exit(0) }
43新增: finished.signal()
44新增: }
45新增: finished.wait()
46新增: }
47新增: DispatchQueue.main.async { exit(0) }
48新增: }
49新增: NSApplication.shared.run()
50新增: exit(0)
51新增: }
52新增:
53新增: struct Window {
54新增: let id: UInt32
55新增: let pid: pid_t
56新增: let bounds: CGRect
57新增: let layer: Int
58新增: var systemSurface = false
59新增: }
60新增:
61新增: private static func signed(_ app: NSRunningApplication, bundle: String) -> Bool {
62新增: guard app.bundleIdentifier == bundle else { return false }
63新增: var code: SecCode?, requirement: SecRequirement?
64新增: return SecRequirementCreateWithString("anchor apple and identifier \"\(bundle)\"" as CFString, [], &requirement) == errSecSuccess &&
65新增: SecCodeCopyGuestWithAttributes(nil, [kSecGuestAttributePid as String: app.processIdentifier] as CFDictionary, [], &code) == errSecSuccess &&
66新增: code != nil && requirement != nil && SecCodeCheckValidity(code!, [], requirement!) == errSecSuccess
67新增: }
68新增:
69新增: private static func consoleSession() throws -> String {
70新增: try consoleUser()
71新增: let entry = IORegistryGetRootEntry(kIOMainPortDefault)
72新增: guard entry != 0 else { throw Failure(4, "requires_gui_login") }
73新增: defer { IOObjectRelease(entry) }
74新增: guard let property = IORegistryEntryCreateCFProperty(entry, "IOConsoleUsers" as CFString, kCFAllocatorDefault, 0)?.takeRetainedValue(),
75新增: let sessions = property as? [[String: Any]] else { throw Failure(4, "requires_gui_login") }
76新增: let active = sessions.filter { $0["kCGSSessionOnConsoleKey"] as? Bool == true }
77新增: guard active.count == 1, let current = active.first,
78新增: current["kCGSessionLoginDoneKey"] as? Bool == true,
79新增: current["CGSSessionScreenIsLocked"] as? Bool != true,
80新增: current["kCGSSessionUserIDKey"] as? UInt32 == getuid(),
81新增: current["kCGSSessionUserNameKey"] as? String == NSUserName(),
82新增: let session = current["CGSSessionUniqueSessionUUID"] as? String,
83新增: UUID(uuidString: session) != nil else { throw Failure(4, "requires_gui_login") }
84新增: return session
85新增: }
86新增:
87新增: static func select(windows: [Window], pid: pid_t, bundle: String, display: CGRect, accessibility: Bool) throws -> Window {
88新增: guard ["com.apple.systempreferences", "com.apple.authorizationhost"].contains(bundle),
89新增: let index = windows.firstIndex(where: { $0.pid == pid && $0.layer == 0 && $0.bounds.width >= 80 && $0.bounds.height >= 40 }) else {
90新增: throw Failure(7, "setup_password_window_unavailable")
91新增: }
92新增: let target = windows[index]
93新增: guard display.contains(target.bounds), target.id != 0 else { throw Failure(7, "setup_password_window_unavailable") }
94新增: if !accessibility && bundle == "com.apple.systempreferences" {
95新增: let parent = windows.dropFirst(index + 1).contains { window in
96新增: window.pid == pid && window.layer == 0 && window.bounds.contains(target.bounds) &&
97新增: window.bounds.width > target.bounds.width && window.bounds.height > target.bounds.height &&
98新增: target.bounds.width * target.bounds.height < window.bounds.width * window.bounds.height * 0.75
99新增: }
100新增: guard parent else { throw Failure(7, "setup_password_window_unavailable") }
101新增: }
102新增: for window in windows.prefix(index) where !window.systemSurface && window.bounds.intersects(target.bounds) {
103新增: throw Failure(7, "setup_password_window_obscured")
104新增: }
105新增: return target
106新增: }
107新增:
108新增: private static func passwordFocused(_ app: NSRunningApplication, window: CGRect) -> Bool {
109新增: let application = AXUIElementCreateApplication(app.processIdentifier)
110新增: AXUIElementSetMessagingTimeout(application, 0.25)
111新增: func attribute(_ element: AXUIElement, _ key: String) -> CFTypeRef? {
112新增: var value: CFTypeRef?
113新增: return AXUIElementCopyAttributeValue(element, key as CFString, &value) == .success ? value : nil
114新增: }
115新增: guard let value = attribute(application, kAXFocusedUIElementAttribute), CFGetTypeID(value) == AXUIElementGetTypeID() else { return false }
116新增: let field = value as! AXUIElement
117新增: var pid: pid_t = 0
118新增: guard AXUIElementGetPid(field, &pid) == .success, pid == app.processIdentifier,
119新增: attribute(field, kAXSubroleAttribute) as? String == kAXSecureTextFieldSubrole,
120新增: attribute(field, kAXEnabledAttribute) as? Bool == true,
121新增: let owner = attribute(field, kAXWindowAttribute), CFGetTypeID(owner) == AXUIElementGetTypeID() else { return false }
122新增: var origin = CGPoint.zero, size = CGSize.zero
123新增: guard let position = attribute(owner as! AXUIElement, kAXPositionAttribute), let extent = attribute(owner as! AXUIElement, kAXSizeAttribute),
124新增: CFGetTypeID(position) == AXValueGetTypeID(), CFGetTypeID(extent) == AXValueGetTypeID(),
125新增: AXValueGetValue(position as! AXValue, .cgPoint, &origin), AXValueGetValue(extent as! AXValue, .cgSize, &size) else { return false }
126新增: return abs(origin.x - window.minX) < 1 && abs(origin.y - window.minY) < 1 &&
127新增: abs(size.width - window.width) < 1 && abs(size.height - window.height) < 1
128新增: }
129新增:
130新增: static func probe() throws -> [String: Any] {
131新增: try requireGuest()
132新增: let session = try consoleSession()
133新增: guard let front = NSWorkspace.shared.frontmostApplication, let bundle = front.bundleIdentifier,
134新增: ["com.apple.systempreferences", "com.apple.authorizationhost"].contains(bundle), signed(front, bundle: bundle) else {
135新增: throw Failure(7, "setup_password_foreground_changed")
136新增: }
137新增: guard let raw = CGWindowListCopyWindowInfo([.optionOnScreenOnly, .excludeDesktopElements], kCGNullWindowID) as? [[String: Any]] else {
138新增: throw Failure(7, "setup_password_window_unavailable")
139新增: }
140新增: let display = CGDisplayBounds(CGMainDisplayID())
141新增: var trustedSurfaces: [pid_t: Bool] = [:]
142新增: let windows = raw.compactMap { item -> Window? in
143新增: guard let id = item[kCGWindowNumber as String] as? UInt32, let pid = item[kCGWindowOwnerPID as String] as? Int32,
144新增: let rectangle = item[kCGWindowBounds as String] as? [String: Any], let bounds = CGRect(dictionaryRepresentation: rectangle as CFDictionary),
145新增: bounds.width > 0, bounds.height > 0, (item[kCGWindowAlpha as String] as? Double ?? 1) > 0,
146新增: let layer = item[kCGWindowLayer as String] as? Int else { return nil }
147新增: var surface = false
148新增: if layer > 0, abs(bounds.minX - display.minX) < 1, abs(bounds.minY - display.minY) < 1,
149新增: abs(bounds.width - display.width) < 1, abs(bounds.height - display.height) < 1 {
150新增: if let cached = trustedSurfaces[pid] { surface = cached }
151新增: else {
152新增: if let app = NSRunningApplication(processIdentifier: pid), let owner = app.bundleIdentifier,
153新增: ["com.apple.dock", "com.apple.notificationcenterui"].contains(owner) { surface = signed(app, bundle: owner) }
154新增: trustedSurfaces[pid] = surface
155新增: }
156新增: }
157新增: return Window(id: id, pid: pid, bounds: bounds, layer: layer, systemSurface: surface)
158新增: }
159新增: let accessibility = AXIsProcessTrusted()
160新增: let target = try select(windows: windows, pid: front.processIdentifier, bundle: bundle, display: display, accessibility: accessibility)
161新增: let focused = accessibility && passwordFocused(front, window: target.bounds)
162新增: guard NSWorkspace.shared.frontmostApplication?.processIdentifier == front.processIdentifier,
163新增: try consoleSession() == session else { throw Failure(7, "setup_password_foreground_changed") }
164新增: return ["version": 1, "session": session, "user": NSUserName(), "pid": front.processIdentifier,
165新增: "window": target.id, "bundle": bundle, "rect": [target.bounds.minX, target.bounds.minY, target.bounds.width, target.bounds.height],
166新增: "display": [display.minX, display.minY, display.width, display.height], "accessibility": accessibility,
167新增: "password_focused": focused, "selection_required": !accessibility]
168新增: }
169新增:
170新增: static func selfTest() throws {
171新增: try validateRequest(Data("{}".utf8))
172新增: try validateRequest(Data("{\"action\":\"probe\"}".utf8))
173新增: for request in ["", "[]", "{\"action\":\"other\"}", "{\"action\":\"probe\",\"text\":\"test-secret\"}"] {
174新增: do { try validateRequest(Data(request.utf8)); throw Failure(1, "setup_password_test_request") }
175新增: catch let error as Failure where error.message == "setup_password_probe_request_invalid" { }
176新增: }
177新增: let display = CGRect(x: 0, y: 0, width: 1920, height: 1200)
178新增: let parent = Window(id: 38, pid: 2338, bounds: CGRect(x: 598, y: 258, width: 723, height: 625), layer: 0)
179新增: let panel = Window(id: 49, pid: 2338, bounds: CGRect(x: 830, y: 376, width: 260, height: 389), layer: 0)
180新增: let overlay = Window(id: 8, pid: 613, bounds: display, layer: 20, systemSurface: true)
181新增: guard try select(windows: [overlay, panel, parent], pid: panel.pid, bundle: "com.apple.systempreferences", display: display, accessibility: false).id == panel.id else { throw Failure(1, "setup_password_test_selection") }
182新增: let ordinary = Window(id: 9, pid: 999, bounds: panel.bounds, layer: 0)
183新增: for windows in [[parent], [ordinary, panel, parent], [Window(id: 9, pid: 999, bounds: display, layer: 20), panel, parent], [panel]] {
184新增: do { _ = try select(windows: windows, pid: panel.pid, bundle: "com.apple.systempreferences", display: display, accessibility: false); throw Failure(1, "setup_password_test_accepted_invalid") }
185新增: catch let error as Failure where error.code == 7 { }
186新增: }
187新增: guard try select(windows: [panel], pid: panel.pid, bundle: "com.apple.authorizationhost", display: display, accessibility: false).id == panel.id,
188新增: try select(windows: [parent], pid: panel.pid, bundle: "com.apple.systempreferences", display: display, accessibility: true).id == parent.id else { throw Failure(1, "setup_password_test_accessibility") }
189新增: print("macOS setup password window selection, system surfaces, obscuration and first-permission cases passed")
190新增: }
191新增:}
修改scripts/guest-os/maintain-windows-workbench.ps1+82 −13看文件
@@ -5,38 +5,82 @@ param(
55 [Parameter(Mandatory)][string]$ManifestPath,
66 [Parameter(Mandatory)][ValidatePattern('^[0-9A-Fa-f]{64}$')][string]$ManifestSHA256,
77 [switch]$Tools,
8新增: [switch]$HostOnly,
89 [string]$BindingSHA256,
910 [pscredential]$GuestAdministrator
1011)
1112$ErrorActionPreference='Stop'
1213$ProgressPreference='SilentlyContinue'
1314[Console]::OutputEncoding=[Text.UTF8Encoding]::new($false)
15新增:# Fixed process exits carry the failed stage across RunAs without a writable
16新增:# result file. The ordinary parent reports the same stage to the workbench.
17新增:$maintenanceFailures=@{
18新增: 1=@('FAILED','Windows 维护未完成。请从 Cage 重新发起原操作,仍失败时导出诊断包。')
19新增: 41=@('VALIDATION','Windows 环境绑定或组件清单未通过校验。请重新发起原操作,组件包仍无法核验时重新安装完整 Cage 应用。')
20新增: 42=@('HOST_MANAGER','Windows 系统管理助手安装未完成。请重试修复系统助手,仍失败时检查系统服务或安全软件记录并导出诊断包。')
21新增: 43=@('GUEST_CONNECTION','Windows 客机连接未完成。请启动并登录已绑定客机,使用该客机的管理员账户重试。')
22新增: 44=@('GUEST_COMPONENTS','Windows 客机组件安装未完成。请保持原客机运行,重试同步环境组件,仍失败时导出诊断包。')
23新增: 45=@('HOST_RELAY','Windows 主机连接组件更新未完成。请关闭占用连接组件的程序,再重试同步环境组件。')
24新增: 46=@('PACKAGE_PREPARATION','Windows 组件包准备未完成。请检查应用目录和系统盘空间后重试,更新工具时同时检查已选代理。')
25新增: 47=@('AUTHORIZATION','Windows 管理员授权窗口未能打开。请从本机 Cage 重新发起操作,并使用可完成管理员授权的 Windows 账户。')
26新增: 48=@('AUTHORIZATION_CANCELED','已取消 Windows 管理员授权。请重新发起原操作,并在 Windows 系统授权窗口中确认。')
27新增:}
28新增:$maintenanceExitCode=41
29新增:trap {
30新增: if ($maintenanceExitCode -eq 47) {
31新增: for ($cause=$_.Exception; $cause; $cause=$cause.InnerException) {
32新增: if ($cause -is [ComponentModel.Win32Exception] -and $cause.NativeErrorCode -eq 1223) { $maintenanceExitCode=48; break }
33新增: }
34新增: }
35新增: if (!$maintenanceFailures.ContainsKey($maintenanceExitCode)) { $maintenanceExitCode=1 }
36新增: $failure=$maintenanceFailures[$maintenanceExitCode]
37新增: [Console]::Error.WriteLine(('CAGE_WINDOWS_MAINTENANCE_'+$failure[0]+' '+$failure[1]))
38新增: [Console]::Error.WriteLine($_.Exception.Message)
39新增: exit $maintenanceExitCode
40新增:}
41新增:
42新增:function Invoke-CageMaintenanceElevation([string]$ScriptPath,[hashtable]$Parameters) {
43新增: $payload=[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes(($Parameters|ConvertTo-Json -Compress)))
44新增: $script=[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($ScriptPath))
45新增: $command='$ErrorActionPreference=''Stop'';$p=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('''+$payload+'''))|ConvertFrom-Json;$a=@{};$p.PSObject.Properties|ForEach-Object{$a[$_.Name]=$_.Value};$s=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('''+$script+'''));try{$global:LASTEXITCODE=0;& $s @a;exit $LASTEXITCODE}catch{Write-Error $_ -ErrorAction Continue;exit 1}'
46新增: $encoded=[Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($command))
47新增: $process=Start-Process -FilePath (Join-Path ([Environment]::GetFolderPath('System')) 'WindowsPowerShell/v1.0/powershell.exe') -ArgumentList @('-NoLogo','-NoProfile','-ExecutionPolicy','RemoteSigned','-EncodedCommand',$encoded) -Verb RunAs -PassThru
48新增: try {
49新增: # Retain the native handle before waiting. Windows PowerShell 5.1 can
50新增: # otherwise return a null ExitCode after a successful child exit.
51新增: $null=$process.Handle
52新增: $process.WaitForExit()
53新增: if ($null -eq $process.ExitCode) { throw '无法读取系统授权进程的退出状态,请重新发起操作。' }
54新增: return [int]$process.ExitCode
55新增: } finally { $process.Dispose() }
56新增:}
57新增:
1458$bindingPath=Join-Path $Profile 'windows-guest.json'
1559$item=Get-Item -LiteralPath $bindingPath -Force
1660if ($item -isnot [IO.FileInfo] -or $item.Length -gt 16384 -or $item.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw '已绑定的 Windows 环境记录无法核验。' }
1761$bindingHash=(Get-FileHash -LiteralPath $bindingPath -Algorithm SHA256).Hash
1862if ($BindingSHA256 -and $BindingSHA256 -ne $bindingHash) { throw 'Windows 环境绑定已变化,请重新发起更新。' }
1963if ((Get-FileHash -LiteralPath $ManifestPath -Algorithm SHA256).Hash -ne $ManifestSHA256) { throw '组件清单已变化,请重新发起更新。' }
64新增:$maintenanceExitCode=47
2065$identity=[Security.Principal.WindowsIdentity]::GetCurrent()
2166if (![Security.Principal.WindowsPrincipal]::new($identity).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
22删除: $parameters=@{Profile=$Profile;ManifestPath=$ManifestPath;ManifestSHA256=$ManifestSHA256;BindingSHA256=$bindingHash;Tools=[bool]$Tools}
23删除: $payload=[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes(($parameters|ConvertTo-Json -Compress)))
24删除: $script=[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($PSCommandPath))
25删除: $command='$ErrorActionPreference=''Stop'';$p=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('''+$payload+'''))|ConvertFrom-Json;$a=@{};$p.PSObject.Properties|ForEach-Object{$a[$_.Name]=$_.Value};$s=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('''+$script+'''));try{& $s @a;exit 0}catch{Write-Error $_;exit 1}'
26删除: $encoded=[Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($command))
27删除: $process=Start-Process -FilePath (Join-Path ([Environment]::GetFolderPath('System')) 'WindowsPowerShell/v1.0/powershell.exe') -ArgumentList @('-NoLogo','-NoProfile','-ExecutionPolicy','RemoteSigned','-EncodedCommand',$encoded) -Verb RunAs -PassThru
28删除: try {
29删除: $process.WaitForExit()
30删除: if ($process.ExitCode -ne 0) { throw 'Windows 组件更新未完成。系统磁盘和账户已保留,请在系统窗口查看原因后重试。' }
31删除: } finally { $process.Dispose() }
32删除: return
67新增: $parameters=@{Profile=$Profile;ManifestPath=$ManifestPath;ManifestSHA256=$ManifestSHA256;BindingSHA256=$bindingHash;Tools=[bool]$Tools;HostOnly=[bool]$HostOnly}
68新增: $maintenanceExitCode=Invoke-CageMaintenanceElevation -ScriptPath $PSCommandPath -Parameters $parameters
69新增: if ($maintenanceExitCode -ne 0) { throw '提升权限后的 Windows 维护进程未完成。' }
70新增: exit 0
3371}
72新增:$maintenanceExitCode=41
3473$binding=Get-Content -LiteralPath $bindingPath -Raw | ConvertFrom-Json
74新增:if ($binding.version -ne 1 -or [guid]$binding.vm_id -eq [guid]::Empty) { throw 'Windows 客机绑定无法核验。' }
75新增:if (!$HostOnly) {
76新增:$maintenanceExitCode=43
3577$vm=Hyper-V\Get-VM -Id ([guid]$binding.vm_id)
78新增:if ($vm.State -ne 'Running') { throw '请先启动并登录已绑定的 Windows 客机。' }
79新增:$maintenanceExitCode=41
3680$disks=@($vm | Hyper-V\Get-VMHardDiskDrive)
3781$pairDirectory=[IO.Path]::GetDirectoryName($binding.relay_executable)
3882$stagedPairDirectory=Join-Path $binding.instance_directory 'cage-workbench\pair'
39删除:if ($binding.version -ne 1 -or $vm.Id -eq [guid]::Empty -or $vm.State -ne 'Running' -or
83新增:if ($binding.version -ne 1 -or $vm.Id -eq [guid]::Empty -or
4084 $binding.gui_user_sid -notmatch '^S-1-5-21-' -or @(Hyper-V\Get-VMNetworkAdapter -VM $vm).Count -ne 0 -or
4185 $disks.Count -ne 1 -or $disks[0].Path -ine (Join-Path $binding.instance_directory 'system.vhdx') -or
4286 ($pairDirectory -ine $stagedPairDirectory -and $pairDirectory -ine $item.Directory.FullName) -or
@@ -47,6 +91,9 @@ if ($binding.version -ne 1 -or $vm.Id -eq [guid]::Empty -or $vm.State -ne 'Runni
4791for ($entry=Get-Item -LiteralPath $binding.relay_executable -Force; $entry; $entry=if ($entry -is [IO.FileInfo]) {$entry.Directory} else {$entry.Parent}) {
4892 if ($entry.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw '主机连接组件路径包含文件链接。' }
4993}
94新增:} else {
95新增: $vm=[pscustomobject]@{Id=[guid]$binding.vm_id}
96新增:}
5097$manifest=Get-Content -LiteralPath $ManifestPath -Raw | ConvertFrom-Json
5198if ($manifest.protocol -ne 1 -or $manifest.system -cne 'windows-11' -or $manifest.revision -notmatch '^[a-f0-9]{64}$' -or @($manifest.files).Count -notin 1..10000) { throw '原生组件清单无效。' }
5299$kit=[IO.Path]::GetFullPath($PSScriptRoot).TrimEnd('\')+'\'
@@ -55,6 +102,22 @@ foreach ($entry in $manifest.files) {
55102 if (!$source.StartsWith($kit,[StringComparison]::OrdinalIgnoreCase) -or (Get-Item -LiteralPath $source -Force).Attributes -band [IO.FileAttributes]::ReparsePoint -or
56103 (Get-FileHash -LiteralPath $source -Algorithm SHA256).Hash -ne $entry.sha256) { throw '应用组件包已变化,请重新安装完整 Cage 应用。' }
57104}
105新增:# The native host helper is part of the same checked component package. Update
106新增:# its fixed-VM service during the existing administrator-authorized maintenance.
107新增:# The protected registration supplies the original host user across UAC.
108新增:$managerBindingPath=Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) ('Cage\HyperVManager\'+$vm.Id.ToString('D')+'\binding.json')
109新增:$managerBindingFile=Get-Item -LiteralPath $managerBindingPath -Force
110新增:if ($managerBindingFile.Attributes -band [IO.FileAttributes]::ReparsePoint -or $managerBindingFile.Length -gt 65536) { throw 'Windows 管理助手的登记文件无法核验。' }
111新增:$managerBinding=Get-Content -LiteralPath $managerBindingPath -Raw | ConvertFrom-Json
112新增:if ([guid]$managerBinding.vm_id -ne $vm.Id -or $managerBinding.host_sid -notmatch '^S-1-(5-21|12-1)-(\d+-){3}\d+$') { throw 'Windows 管理助手的用户或客机身份不匹配。' }
113新增:$managerPayload=Join-Path $kit 'payload/Cage.HyperVManager.exe'
114新增:$maintenanceExitCode=42
115新增:& (Join-Path $kit 'install-windows-host-manager.ps1') -VMId $vm.Id -HostSID $managerBinding.host_sid -PayloadExecutable $managerPayload -PayloadSHA256 (Get-FileHash -LiteralPath $managerPayload -Algorithm SHA256).Hash -Confirm:$false | Out-Null
116新增:if ($HostOnly) {
117新增: Write-Output 'Windows 系统管理助手已恢复,可以继续恢复存储迁移。'
118新增: exit 0
119新增:}
120新增:$maintenanceExitCode=46
58121$work=Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) ('Cage\ComponentMaintenance\'+$vm.Id.ToString('D'))
59122for ($parent=$work; $parent; $parent=[IO.Path]::GetDirectoryName($parent)) {
60123 if ((Test-Path -LiteralPath $parent) -and (Get-Item -LiteralPath $parent -Force).Attributes -band [IO.FileAttributes]::ReparsePoint) { throw '组件维护目录包含文件链接。' }
@@ -107,6 +170,7 @@ try {
107170 & (Join-Path $env:SystemRoot 'System32/tar.exe') -a -cf (Join-Path $toolStage 'extras.zip') -C $bridge .
108171 if ($LASTEXITCODE) { throw '无法准备经过校验的环境工具包。' }
109172 }
173新增: $maintenanceExitCode=43
110174 if (!$GuestAdministrator) { $GuestAdministrator=Get-Credential -Message 'Cage:请输入当前 Windows 客机的管理员账户以更新组件。' }
111175 if (!$GuestAdministrator) { throw '已取消 Windows 组件更新。' }
112176 $session=New-PSSession -VMId $vm.Id -Credential $GuestAdministrator
@@ -120,6 +184,7 @@ try {
120184 Set-Acl -LiteralPath $path -AclObject $acl
121185 $path
122186 }
187新增: $maintenanceExitCode=44
123188 $archive=Join-Path $work ([guid]::NewGuid().ToString('N')+'.zip')
124189 try {
125190 $entries=@('files','native-components.json')
@@ -132,15 +197,17 @@ try {
132197 Copy-Item -LiteralPath (Join-Path $kit 'install-windows-workbench-components.ps1') -Destination $remote -ToSession $session
133198 Invoke-Command -Session $session -FilePath (Join-Path $kit 'update-windows-workbench-components.ps1') -ArgumentList $vm.Id,$binding.gui_user_sid,$remote,$hash,([bool]$Tools),($packages|ConvertTo-Json -Depth 6 -Compress),($cli|ConvertTo-Json -Depth 6 -Compress)
134199 # The host relay is an application file. Pairing bytes and the binding are retained.
200新增: $maintenanceExitCode=45
135201 $relayStage=$binding.relay_executable+'.'+[guid]::NewGuid().ToString('N')+'.tmp'
136202 try {
137203 Copy-Item -LiteralPath (Join-Path $files 'bridge/Cage.GuestClipboard.exe') -Destination $relayStage
138204 Set-Acl -LiteralPath $relayStage -AclObject (Get-Acl -LiteralPath $binding.relay_executable)
139205 [IO.File]::Replace($relayStage,$binding.relay_executable,[Management.Automation.Language.NullString]::Value)
140206 } finally { if (Test-Path -LiteralPath $relayStage) { Remove-Item -LiteralPath $relayStage } }
207新增: $maintenanceExitCode=41
141208 if (@(Hyper-V\Get-VMNetworkAdapter -VM (Hyper-V\Get-VM -Id $vm.Id)).Count -ne 0) { throw '更新期间客机网络配置发生变化。' }
209新增: $maintenanceExitCode=44
142210 $completed=$true
143删除: Write-Output 'Windows 客机组件已完成文件核验,已保留账户、项目和配对资料。'
144211} finally {
145212 if ($session) {
146213 if ($remote -and $completed) { Invoke-Command -Session $session -ArgumentList $remote -ScriptBlock { param($path) Remove-Item -LiteralPath $path -Recurse -Force } -ErrorAction Continue }
@@ -150,3 +217,5 @@ try {
150217 if (Test-Path -LiteralPath $stage) { Remove-Item -LiteralPath $stage -Recurse -Force }
151218 $lock.Dispose()
152219}
220新增:Write-Output 'Windows 客机组件已完成文件核验,已保留账户、项目和配对资料。'
221新增:exit 0
新增scripts/guest-os/maintain-windows-workbench.tests.ps1+140 −0看文件
@@ -0,0 +1,140 @@
1新增:#requires -Version 5.1
2新增:param([string]$Implementation=(Join-Path $PSScriptRoot 'maintain-windows-workbench.ps1'))
3新增:$ErrorActionPreference='Stop'
4新增:$source=[IO.File]::ReadAllText($Implementation)
5新增:$parseErrors=$null
6新增:$ast=[Management.Automation.Language.Parser]::ParseInput($source,[ref]$null,[ref]$parseErrors)
7新增:if ($parseErrors.Count) { throw $parseErrors[0] }
8新增:$bindingStart=$source.IndexOf('$bindingPath=Join-Path')
9新增:if ($bindingStart -lt 0) { throw 'Maintenance preflight entry missing.' }
10新增:$prelude=$source.Substring(0,$bindingStart)
11新增:$elevation=$ast.Find({param($node)
12新增: $node -is [Management.Automation.Language.IfStatementAst] -and $node.Clauses[0].Item1.Extent.Text.Contains('WindowsPrincipal')
13新增:},$true)
14新增:if (!$elevation) { throw 'Production elevation entry missing.' }
15新增:$elevationBody=$elevation.Clauses[0].Item2.Extent.Text
16新增:$elevationBody=$elevationBody.Substring(1,$elevationBody.Length-2).Replace('-ScriptPath $PSCommandPath','-ScriptPath $fixtureChild')
17新增:$hostOnly=$ast.Find({param($node)
18新增: $node -is [Management.Automation.Language.IfStatementAst] -and $node.Clauses[0].Item1.Extent.Text -eq '$HostOnly'
19新增:},$true)
20新增:if (!$hostOnly -or !$hostOnly.Extent.Text.Contains('exit 0') -or $hostOnly.Extent.Text.Contains('New-PSSession') -or $hostOnly.Extent.StartOffset -gt $source.IndexOf('Get-Credential -Message')) { throw 'HostOnly must finish after host installation.' }
21新增:
22新增:function Assert-Stage([string]$Command,[int]$Code) {
23新增: $offset=$source.IndexOf($Command)
24新增: if ($offset -lt 0) { throw "Stage receiver missing $Command" }
25新增: $assignments=@($ast.FindAll({param($node)
26新增: if ($node -isnot [Management.Automation.Language.AssignmentStatementAst] -or $node.Left.Extent.Text -ne '$maintenanceExitCode' -or $node.Right.Extent.Text -notmatch '^\d+$') { return $false }
27新增: for ($parent=$node.Parent; $parent; $parent=$parent.Parent) {
28新增: if ($parent -is [Management.Automation.Language.TrapStatementAst] -or $parent -is [Management.Automation.Language.FunctionDefinitionAst]) { return $false }
29新增: }
30新增: $true
31新增: },$true) | Where-Object {$_.Extent.StartOffset -lt $offset} | Sort-Object {$_.Extent.StartOffset})
32新增: if (!$assignments.Count -or [int]$assignments[-1].Right.Extent.Text -ne $Code) { throw "Wrong production failure stage for $Command" }
33新增:}
34新增:Assert-Stage 'Get-FileHash -LiteralPath $ManifestPath' 41
35新增:Assert-Stage "& (Join-Path `$kit 'install-windows-host-manager.ps1')" 42
36新增:Assert-Stage 'Get-PinnedPackage $spec.Value $cache' 46
37新增:Assert-Stage 'New-PSSession -VMId' 43
38新增:Assert-Stage "Invoke-Command -Session `$session -FilePath (Join-Path `$kit 'update-windows-workbench-components.ps1')" 44
39新增:Assert-Stage '[IO.File]::Replace' 45
40新增:
41新增:$shell=(Get-Process -Id $PID).Path
42新增:$temporary=Join-Path ([IO.Path]::GetTempPath()) ('cage-maintenance-feedback-'+[guid]::NewGuid().ToString('N'))
43新增:$null=New-Item -ItemType Directory -Path $temporary
44新增:$encoding=[Text.UTF8Encoding]::new($true)
45新增:function Quote-Literal([string]$Value) { "'"+$Value.Replace("'","''")+"'" }
46新增:function Run-Script([string]$Path,[hashtable]$Parameters) {
47新增: $payload=[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes(($Parameters|ConvertTo-Json -Compress)))
48新增: $command='$p=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('''+$payload+'''))|ConvertFrom-Json;$a=@{};$p.PSObject.Properties|ForEach-Object{$a[$_.Name]=$_.Value};& '+(Quote-Literal $Path)+' @a;exit $LASTEXITCODE'
49新增: $encoded=[Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($command))
50新增: $start=[Diagnostics.ProcessStartInfo]::new()
51新增: $start.FileName=$shell
52新增: $start.Arguments='-NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -EncodedCommand '+$encoded
53新增: $start.UseShellExecute=$false
54新增: $start.RedirectStandardOutput=$true
55新增: $start.RedirectStandardError=$true
56新增: $process=[Diagnostics.Process]::new()
57新增: $process.StartInfo=$start
58新增: try {
59新增: if (!$process.Start()) { throw 'Fixture process did not start.' }
60新增: $stdout=$process.StandardOutput.ReadToEndAsync()
61新增: $stderr=$process.StandardError.ReadToEndAsync()
62新增: if (!$process.WaitForExit(15000)) { $process.Kill(); throw 'Fixture process timed out.' }
63新增: [pscustomobject]@{Code=$process.ExitCode;Output=$stdout.GetAwaiter().GetResult();Error=$stderr.GetAwaiter().GetResult()}
64新增: } finally { $process.Dispose() }
65新增:}
66新增:
67新增:try {
68新增: $profile=Join-Path $temporary "profile's 中文"
69新增: $null=New-Item -ItemType Directory -Path $profile
70新增: $binding=Join-Path $profile 'windows-guest.json'
71新增: $manifest=Join-Path $temporary 'manifest.json'
72新增: [IO.File]::WriteAllText($binding,'{}',$encoding)
73新增: [IO.File]::WriteAllText($manifest,'{}',$encoding)
74新增: $parameters=@{Profile=$profile;ManifestPath=$manifest;ManifestSHA256=(Get-FileHash $manifest).Hash}
75新增: foreach ($name in @('binding','manifest')) {
76新增: $requestParameters=$parameters.Clone()
77新增: if ($name -eq 'binding') { $requestParameters.BindingSHA256='a'*64 } else { $requestParameters.ManifestSHA256='b'*64 }
78新增: $result=Run-Script $Implementation $requestParameters
79新增: if ($result.Code -ne 41 -or !$result.Error.Contains('CAGE_WINDOWS_MAINTENANCE_VALIDATION')) { throw "Real $name preflight lost its phase $($result | ConvertTo-Json -Compress)" }
80新增: }
81新增:
82新增: # The production RunAs block launches real isolated PowerShell children.
83新增: # Only the OS elevation call is replaced, so these tests require no UAC,
84新增: # VM, administrator credential or protected Windows directory.
85新增: $mock=@'
86新增:function Join-Path($Path,$ChildPath) {
87新增: if ($ChildPath -eq 'WindowsPowerShell/v1.0/powershell.exe') { return $fixtureShell }
88新增: Microsoft.PowerShell.Management\Join-Path -Path $Path -ChildPath $ChildPath
89新增:}
90新增:function Start-Process($FilePath,$ArgumentList,$Verb,[switch]$PassThru) {
91新增: if ($FilePath -ne $fixtureShell -or $Verb -ne 'RunAs' -or !$PassThru) { throw 'Incorrect elevation contract.' }
92新增: if ($fixtureCancel) { throw [InvalidOperationException]::new('synthetic nested launch error',[ComponentModel.Win32Exception]::new(1223)) }
93新增: if ($fixtureLaunchFailure) { throw [ComponentModel.Win32Exception]::new(5) }
94新增: Microsoft.PowerShell.Management\Start-Process -FilePath $FilePath -ArgumentList $ArgumentList -PassThru -NoNewWindow
95新增:}
96新增:'@
97新增: $cases=@(
98新增: @{Name='regular-success';Code=0;Phase='';HostOnly=$false;Tools=$true},
99新增: @{Name='host-success';Code=0;Phase='';HostOnly=$true;Tools=$false},
100新增: @{Name='validation';Code=41;Phase='VALIDATION';HostOnly=$true},
101新增: @{Name='manager';Code=42;Phase='HOST_MANAGER';HostOnly=$true},
102新增: @{Name='guest-connection';Code=43;Phase='GUEST_CONNECTION';HostOnly=$false},
103新增: @{Name='guest-components';Code=44;Phase='GUEST_COMPONENTS';HostOnly=$false},
104新增: @{Name='host-relay';Code=45;Phase='HOST_RELAY';HostOnly=$false},
105新增: @{Name='prepare-tools';Code=46;Phase='PACKAGE_PREPARATION';HostOnly=$false;Tools=$true},
106新增: @{Name='launch-failed';Code=47;Phase='AUTHORIZATION';HostOnly=$true;LaunchFailure=$true},
107新增: @{Name='uac-canceled';Code=48;Phase='AUTHORIZATION_CANCELED';HostOnly=$true;Cancel=$true},
108新增: @{Name='legacy-failed';Code=1;Phase='FAILED';HostOnly=$true;Legacy=$true},
109新增: @{Name='unknown-exit';Code=1;Phase='FAILED';HostOnly=$false;Unknown=$true}
110新增: )
111新增: foreach ($case in $cases) {
112新增: $child=Join-Path $temporary ($case.Name+"-child's 中文.ps1")
113新增: $expectedHost=([bool]$case.HostOnly).ToString().ToLowerInvariant()
114新增: $expectedTools=([bool]$case.Tools).ToString().ToLowerInvariant()
115新增: $childBody="`nif ([bool]`$HostOnly -ne `$$expectedHost -or [bool]`$Tools -ne `$$expectedTools -or `$GuestAdministrator -or `$BindingSHA256 -ne ('c'*64)) { exit 92 }`n"
116新增: if ($case.Unknown) { $childBody+='exit 77' }
117新增: elseif ($case.Legacy) { $childBody+='throw ''synthetic legacy error''' }
118新增: elseif ($case.Code -eq 0) {
119新增: $childBody+=$hostOnly.Extent.Text+"`nWrite-Output 'synthetic regular success'`nexit 0"
120新增: } else { $childBody+="`$maintenanceExitCode=$($case.Code)`nthrow 'synthetic stage error'" }
121新增: if ($case.Legacy) {
122新增: [IO.File]::WriteAllText($child,$ast.ParamBlock.Extent.Text+$childBody,$encoding)
123新增: } else { [IO.File]::WriteAllText($child,$prelude+$childBody,$encoding) }
124新增: $parentScript=Join-Path $temporary ($case.Name+'-parent.ps1')
125新增: $config="`n`$fixtureShell="+(Quote-Literal $shell)+"`n`$fixtureChild="+(Quote-Literal $child)+"`n`$fixtureCancel=`$"+([bool]$case.Cancel).ToString().ToLowerInvariant()+"`n`$fixtureLaunchFailure=`$"+([bool]$case.LaunchFailure).ToString().ToLowerInvariant()+"`n`$bindingHash='c'*64`n`$maintenanceExitCode=47`n"
126新增: $config+="`$GuestAdministrator=[pscredential]::new('synthetic-maintenance-user',(ConvertTo-SecureString 'synthetic-credential' -AsPlainText -Force))`n"
127新增: [IO.File]::WriteAllText($parentScript,$prelude+$config+$mock+"`n"+$elevationBody,$encoding)
128新增: $requestParameters=$parameters.Clone()
129新增: $requestParameters.HostOnly=[bool]$case.HostOnly
130新增: $requestParameters.Tools=[bool]$case.Tools
131新增: $result=Run-Script $parentScript $requestParameters
132新增: if ($result.Code -ne $case.Code -or ($case.Code -ne 0 -and !$result.Error.Contains('CAGE_WINDOWS_MAINTENANCE_'+$case.Phase))) {
133新增: throw "RunAs stage lost for $($case.Name) $($result | ConvertTo-Json -Compress)"
134新增: }
135新增: Write-Output ("Passed {0} with exit {1}" -f $case.Name,$result.Code)
136新增: }
137新增: Write-Output 'Passed real binding/manifest preflight, production stage ownership, HostOnly, regular Tools, explicit child exits, legacy errors and nested UAC cancellation (isolated processes, simulated elevation).'
138新增:} finally {
139新增: Remove-Item -LiteralPath $temporary -Recurse -Force
140新增:}
修改scripts/guest-os/native-component-manifest.pl+0 −0看文件

没有文字改动(可能只改了权限)。

新增scripts/guest-os/sshfs-openwith.patch+109 −0看文件
@@ -0,0 +1,109 @@
1新增:--- a/sshfs.c
2新增:+++ b/sshfs.c
3新增:@@ -324,6 +324,9 @@
4新增: };
5新增:
6新增: struct sshfs {
7新增:+#ifdef __APPLE__
8新增:+ char *cage_openwith;
9新增:+#endif
10新增: char *directport;
11新增: char *ssh_command;
12新增: char *sftp_server;
13新增:@@ -497,6 +500,9 @@
14新增: #define SSHFS_OPT(t, p, v) { t, offsetof(struct sshfs, p), v }
15新增:
16新增: static struct fuse_opt sshfs_opts[] = {
17新增:+#ifdef __APPLE__
18新增:+ SSHFS_OPT("cage_openwith=%s", cage_openwith, 0),
19新增:+#endif
20新增: SSHFS_OPT("directport=%s", directport, 0),
21新增: SSHFS_OPT("ssh_command=%s", ssh_command, 0),
22新增: SSHFS_OPT("sftp_server=%s", sftp_server, 0),
23新增:@@ -3829,7 +3835,76 @@
24新增: return 0;
25新增: }
26新增:
27新增:+#ifdef __APPLE__
28新增:+/* Present guest-local LaunchServices metadata without creating host xattrs
29新增:+ * or AppleDouble files in a shared project. The GUI helper publishes this
30新增:+ * opaque value with the supported NSWorkspace per-file association API. */
31新增:+static int cage_getxattr(const char *path, const char *name, char *value,
32新增:+ size_t size)
33新增:+{
34新增:+ if (!sshfs.cage_openwith || strcmp(name, "com.apple.LaunchServices.OpenWith"))
35新增:+ return -ENOTSUP;
36新增:+
37新增:+ struct stat target;
38新增:+ int status = sshfs_getattr(path, &target, NULL);
39新增:+ if (status != 0)
40新增:+ return status;
41新增:+ if (!S_ISREG(target.st_mode))
42新增:+ return -ENOATTR;
43新增:+
44新增:+ int fd = open(sshfs.cage_openwith, O_RDONLY | O_CLOEXEC | O_NOFOLLOW);
45新增:+ if (fd < 0)
46新增:+ return errno == ENOENT ? -ENOATTR : -errno;
47新增:+ struct stat st;
48新增:+ int result;
49新增:+ if (fstat(fd, &st) != 0) {
50新增:+ result = -errno;
51新增:+ } else if (!S_ISREG(st.st_mode) || st.st_size <= 0 || st.st_size > 65536) {
52新增:+ result = -EIO;
53新增:+ } else if (!size) {
54新增:+ result = (int)st.st_size;
55新增:+ } else if (size < (size_t)st.st_size) {
56新增:+ result = -ERANGE;
57新增:+ } else {
58新增:+ size_t copied = 0;
59新增:+ result = (int)st.st_size;
60新增:+ while (copied < (size_t)st.st_size) {
61新增:+ ssize_t count = read(fd, value + copied, (size_t)st.st_size - copied);
62新增:+ if (count < 0 && errno == EINTR)
63新增:+ continue;
64新增:+ if (count <= 0) {
65新增:+ result = count < 0 ? -errno : -EIO;
66新增:+ break;
67新增:+ }
68新增:+ copied += (size_t)count;
69新增:+ }
70新增:+ }
71新增:+ close(fd);
72新增:+ return result;
73新增:+}
74新增:+
75新增:+static int cage_listxattr(const char *path, char *list, size_t size)
76新增:+{
77新增:+ const char name[] = "com.apple.LaunchServices.OpenWith";
78新增:+ int available = cage_getxattr(path, name, NULL, 0);
79新增:+ if (available == -ENOATTR)
80新增:+ return 0;
81新增:+ if (available < 0)
82新增:+ return available;
83新增:+ if (!size)
84新增:+ return sizeof(name);
85新增:+ if (size < sizeof(name))
86新增:+ return -ERANGE;
87新增:+ memcpy(list, name, sizeof(name));
88新增:+ return sizeof(name);
89新增:+}
90新增:+#endif
91新增:+
92新增: static struct fuse_operations sshfs_oper = {
93新增:+#ifdef __APPLE__
94新增:+ .getxattr = cage_getxattr,
95新增:+ .listxattr = cage_listxattr,
96新增:+#endif
97新增: .init = sshfs_init,
98新增: .getattr = sshfs_getattr,
99新增: .access = sshfs_access,
100新增:@@ -3862,6 +3937,9 @@
101新增: {
102新增: printf(
103新增: "usage: %s [user@]host:[dir] mountpoint [options]\n"
104新增:+#ifdef __APPLE__
105新增:+" -o cage_openwith=FILE read guest-local file-opening metadata\n"
106新增:+#endif
107新增: "\n"
108新增: " -h --help print help\n"
109新增: " -V --version print version\n"
修改scripts/guest-os/tests/macos-browser-service.test.mjs+14 −3看文件
@@ -7,6 +7,7 @@ import { tmpdir } from "node:os";
77import path from "node:path";
88import { createInterface } from "node:readline";
99import { serveMacOSBrowser, relayMacOSBrowser } from "../macos-browser-service.mjs";
10新增:const unixService = process.platform === "win32" ? test.skip : test;
1011
1112async function fixture(t, dispatch) {
1213 const directory = await mkdtemp(path.join(tmpdir(), "cage-bs-"));
@@ -29,7 +30,7 @@ async function fixture(t, dispatch) {
2930 return { directory, connect, service, stopped: () => stopped };
3031}
3132
32删除:test("Mac browser connections retain owned state and publish service ownership", async t => {
33新增:unixService("Mac browser connections retain owned state and publish service ownership", async t => {
3334 let value = "";
3435 const f = await fixture(t, async request => {
3536 if (request.text !== undefined) value = request.text;
@@ -47,7 +48,7 @@ test("Mac browser connections retain owned state and publish service ownership",
4748 await assert.rejects(serveMacOSBrowser({ directory: f.directory, dispatch: async () => ({}), close: async () => {} }), /already running/);
4849});
4950
50删除:test("Mac browser service drops a disconnected caller's queued mutation", async t => {
51新增:unixService("Mac browser service drops a disconnected caller's queued mutation", async t => {
5152 let release, began;
5253 const started = new Promise(resolve => { began = resolve; });
5354 const wait = new Promise(resolve => { release = resolve; });
@@ -69,7 +70,7 @@ test("Mac browser service drops a disconnected caller's queued mutation", async
6970 assert.deepEqual(applied, ["first", "last"]);
7071});
7172
72删除:test("Mac browser service refuses insecure directories and unrelated socket paths", async t => {
73新增:unixService("Mac browser service refuses insecure directories and unrelated socket paths", async t => {
7374 const directory = await mkdtemp(path.join(tmpdir(), "cage-bs-"));
7475 t.after(() => rm(directory, { recursive: true, force: true }));
7576 await chmod(directory, 0o755);
@@ -80,3 +81,13 @@ test("Mac browser service refuses insecure directories and unrelated socket path
8081 await assert.rejects(serveMacOSBrowser({ directory, dispatch: async () => ({}), close: async () => {} }), /socket/);
8182 assert.equal((await stat(path.join(directory, "browser.sock"))).isFile(), true);
8283});
84新增:
85新增:unixService("Mac browser service releases its endpoint when owned browser shutdown fails", async t => {
86新增: const directory = await mkdtemp(path.join(tmpdir(), "cage-bs-"));
87新增: t.after(() => rm(directory, { recursive: true, force: true }));
88新增: const service = await serveMacOSBrowser({ directory, dispatch: async () => ({}), close: async () => { throw new Error("fixture shutdown failure"); } });
89新增: await assert.rejects(service.close(), /fixture shutdown failure/);
90新增: await assert.rejects(stat(path.join(directory, "browser.sock")), { code: "ENOENT" });
91新增: const replacement = await serveMacOSBrowser({ directory, dispatch: async () => ({}), close: async () => {} });
92新增: await replacement.close();
93新增:});
修改scripts/guest-os/tests/windows-browser.test.mjs+110 −1看文件
@@ -133,7 +133,7 @@ integration("actual Chromium tabs restore and project switching retains unsaved
133133 await assert.rejects(f.call("insert-text", { id: editor.id, text: "迟到输入" }), { code: "project_grant_unavailable" });
134134 }
135135});
136删除:integration("private editor connection applies only the issued alias's HTML defaults through loopback", async t => {
136新增:(process.env.CAGE_BROWSER_TEST_PLATFORM === "darwin" ? test.skip : integration)("Windows private editor connection applies only the issued alias's HTML defaults through loopback", async t => {
137137 const f = await fixture(t), project = "d".repeat(16), connection = "e".repeat(32);
138138 const url = new URL(f.url); url.hostname = project + ".cage-editor.localhost"; url.search = "?editor=" + project;
139139 const input = { workspace: project, connection, url: url.href, folder: f.root, trust_default: false };
@@ -451,6 +451,11 @@ macImages("Mac image preparation rejects a changed field before accepting bytes"
451451
452452macImages("Mac clipboard text uses one bounded transfer and one final insertion", async t => {
453453 const f = await fixture(t), one = await f.open();
454新增: await one.page.evaluate(() => {
455新增: document.querySelector("#first").addEventListener("paste", event => {
456新增: window.textPaste = { trusted: event.isTrusted, text: event.clipboardData.getData("text/plain") };
457新增: });
458新增: });
454459 await f.click(one.id, one.page, "#first");
455460 assert.equal(f.launchOptions().ignoreDefaultArgs.includes("--mute-audio"), true);
456461 const text = "中".repeat(Math.floor((2 << 20) / 3)) + "ab", bytes = Buffer.from(text);
@@ -466,11 +471,33 @@ macImages("Mac clipboard text uses one bounded transfer and one final insertion"
466471 const actual = await one.page.locator("#first").inputValue();
467472 assert.equal(Buffer.byteLength(actual), bytes.length);
468473 assert.equal(createHash("sha256").update(actual).digest("hex"), createHash("sha256").update(text).digest("hex"));
474新增: const pasted = await one.page.evaluate(() => window.textPaste);
475新增: assert.equal(pasted.trusted, true);
476新增: assert.equal(pasted.text, text);
469477 const tooLarge = await f.call("paste-start", { id: one.id });
470478 await assert.rejects(f.call("paste-chunk", { transfer: tooLarge.transfer, sequence: 0, length: bytes.length + 1, mime: "text/plain", data: "YQ==" }), /大小/);
471479});
472480
473481const macImagePaste = playwrightPath && executablePath && process.env.CAGE_BROWSER_TEST_PLATFORM === "darwin" && process.env.CAGE_BROWSER_TEST_PNG_PASTE === "1" ? test : test.skip;
482新增:integration("native paste preparation rejects a field switch inside a child frame", async t => {
483新增: const f = await fixture(t), one = await f.open();
484新增: for (const origin of [f.url, f.url.replace("127.0.0.1", "localhost")]) {
485新增: await one.page.evaluate(url => {
486新增: document.querySelector("#child")?.remove();
487新增: const frame = document.createElement("iframe"); frame.id = "child"; frame.src = url;
488新增: document.body.append(frame);
489新增: }, origin + "/child");
490新增: const child = one.page.frameLocator("#child");
491新增: await child.locator("#first").click();
492新增: const before = await f.call("focus-proof", {}, "GET");
493新增: const prepared = await f.call("paste-start", { id: one.id });
494新增: await child.locator("#second").focus();
495新增: const after = await f.call("focus-proof", {}, "GET");
496新增: assert.notEqual(after.focus, before.focus);
497新增: await assert.rejects(f.call("paste-chunk", { transfer: prepared.transfer, sequence: 0, mime: "text/plain", length: 1, data: "YQ==" }), /target changed/i);
498新增: }
499新增:});
500新增:
474501macImagePaste("Mac headless image transfer delivers an actual PNG paste event", async t => {
475502 const f = await fixture(t), one = await f.open();
476503 await one.page.evaluate(() => {
@@ -497,6 +524,88 @@ macImagePaste("Mac headless image transfer delivers an actual PNG paste event",
497524 await assert.rejects(f.call("image-finish", { transfer: prepared.transfer, sequence }), /已关闭|顺序/);
498525});
499526
527新增:async function readClipboardReference(f, copied) {
528新增: assert.match(copied.clipboard.id, /^[a-f0-9-]{36}$/);
529新增: const opened = await f.call("file-open", { direction: "download", id: copied.clipboard.id, tab: copied.id, context: copied.context, document: copied.document });
530新增: assert.equal(opened.mime, copied.clipboard.mime);
531新增: assert.equal(opened.size, copied.clipboard.size);
532新增: const chunks = [];
533新增: let sequence = 0, result;
534新增: do {
535新增: result = await f.call("file-read", { transfer: opened.transfer, sequence });
536新增: assert.equal(result.sequence, ++sequence);
537新增: chunks.push(Buffer.from(result.data, "base64"));
538新增: } while (!result.eof);
539新增: const bytes = Buffer.concat(chunks);
540新增: assert.equal(bytes.length, opened.size);
541新增: return bytes;
542新增:}
543新增:
544新增:macImagePaste("Mac webpage PNG copy exports a bound reference with the original pixels", async t => {
545新增: const f = await fixture(t), one = await f.open();
546新增: await one.page.evaluate(() => {
547新增: document.querySelector("#copy").onclick = async () => {
548新增: const canvas = document.createElement("canvas");
549新增: canvas.width = 8; canvas.height = 4;
550新增: const context = canvas.getContext("2d");
551新增: context.fillStyle = "#d82931"; context.fillRect(0, 0, 4, 4);
552新增: context.fillStyle = "#264dc6"; context.fillRect(4, 0, 4, 4);
553新增: const blob = await new Promise(resolve => canvas.toBlob(resolve, "image/png"));
554新增: await navigator.clipboard.write([new ClipboardItem({ "image/png": blob })]);
555新增: };
556新增: });
557新增: const context = "b".repeat(32);
558新增: await f.call("copy-context", { id: one.id, context });
559新增: await f.click(one.id, one.page, "#copy");
560新增: let copied;
561新增: for (let attempt = 0; attempt < 100 && !copied; attempt++) {
562新增: const state = await f.call("events", {}, "GET");
563新增: copied = state.events.find(event => event.type === "clipboard" && event.value.context === context)?.value;
564新增: if (!copied) await new Promise(resolve => setTimeout(resolve, 20));
565新增: }
566新增: assert.equal(copied?.clipboard?.mime, "image/png", JSON.stringify(copied));
567新增: assert.equal(copied.png, undefined);
568新增: assert.equal(copied.text, undefined);
569新增: assert.equal((await f.call("tabs", {}, "GET")).tabs.some(tab => tab.url.includes("cage-clipboard.localhost")), false);
570新增: await assert.rejects(f.call("file-open", { direction: "download", id: copied.clipboard.id }), { code: "copy_changed" });
571新增: const bytes = await readClipboardReference(f, copied);
572新增: const pixels = await one.page.evaluate(async encoded => {
573新增: const bytes = Uint8Array.from(atob(encoded), value => value.charCodeAt(0));
574新增: const bitmap = await createImageBitmap(new Blob([bytes], { type: "image/png" }));
575新增: const canvas = document.createElement("canvas"); canvas.width = bitmap.width; canvas.height = bitmap.height;
576新增: const context = canvas.getContext("2d"); context.drawImage(bitmap, 0, 0);
577新增: const result = { width: bitmap.width, height: bitmap.height, left: [...context.getImageData(1, 1, 1, 1).data], right: [...context.getImageData(6, 1, 1, 1).data] };
578新增: bitmap.close();
579新增: return result;
580新增: }, bytes.toString("base64"));
581新增: assert.deepEqual(pixels, { width: 8, height: 4, left: [216, 41, 49, 255], right: [38, 77, 198, 255] });
582新增: await f.call("copy-context", { id: one.id, context: "c".repeat(32) });
583新增: await assert.rejects(readClipboardReference(f, copied), { code: "copy_changed" });
584新增:});
585新增:
586新增:macImagePaste("Mac native copy and cut preserve 2 MiB UTF-8 text and reject superseded reads", async t => {
587新增: const f = await fixture(t), one = await f.open();
588新增: const text = "中".repeat(Math.floor((2 << 20) / 3)) + "ab";
589新增: await one.page.locator("#first").fill(text);
590新增: await one.page.locator("#first").selectText();
591新增: const copied = await f.call("copy", { id: one.id, context: "1".repeat(32) });
592新增: assert.equal(copied.clipboard.mime, "text/plain");
593新增: assert.equal(copied.clipboard.size, 2 << 20);
594新增: assert.equal((await readClipboardReference(f, copied)).toString("utf8"), text);
595新增: assert.equal(await one.page.locator("#first").inputValue(), text);
596新增: const opened = await f.call("file-open", { direction: "download", id: copied.clipboard.id, tab: copied.id, context: copied.context, document: copied.document });
597新增: const first = await f.call("file-read", { transfer: opened.transfer, sequence: 0 });
598新增: assert.equal(first.eof, false);
599新增: await f.call("copy-context", { id: one.id, context: "2".repeat(32) });
600新增: await assert.rejects(f.call("file-read", { transfer: opened.transfer, sequence: 1 }), { code: "copy_changed" });
601新增: const cut = await f.call("cut", { id: one.id, context: "3".repeat(32) });
602新增: assert.equal((await readClipboardReference(f, cut)).toString("utf8"), text);
603新增: assert.equal(await one.page.locator("#first").inputValue(), "");
604新增: const state = await f.call("events", {}, "GET");
605新增: assert.equal(state.events.some(event => event.type === "clipboard" && [copied.context, cut.context].includes(event.value.context)), false, "explicit copy results must have one consumer");
606新增: await assert.rejects(f.call("copy", { id: one.id, context: "4".repeat(32) }), { code: "copy_unavailable" });
607新增:});
608新增:
500609const nativeExtensions = playwrightPath && executablePath && process.env.CAGE_BROWSER_TEST_EXTENSIONS === "1" ? test : test.skip;
501610nativeExtensions("native extension preview, disabled import, activation and restart preserve the selected state", async t => {
502611 const f = await fixture(t), one = await f.open();
修改scripts/guest-os/windows-browser.mjs+200 −32看文件
@@ -1,7 +1,7 @@
11import { createTailnetClient } from "./tailnet-client.mjs";
22// The GUI-session broker owns this process. Playwright uses inherited DevTools
33// pipes; neither the controller nor DevTools opens a guest network listener.
4删除:import { randomBytes } from "node:crypto";
4新增:import { randomBytes, randomUUID } from "node:crypto";
55import { constants, createReadStream, existsSync } from "node:fs";
66import { mkdir, open, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
77import { homedir } from "node:os";
@@ -98,8 +98,8 @@ export function browserExecutable() {
9898 throw failure("browser_unavailable", "请先在 Windows 客机安装受支持的 Chrome 或 Edge");
9999}
100100
101删除:// Test dependencies are explicit. Production never falls back to headless mode,
102删除:// another OS, an arbitrary executable from PATH, or the user's existing profile.
101新增:// Tests provide their dependencies explicitly. Production uses the selected
102新增:// guest's browser mode, fixed executable, and Cage-owned profile.
103103export function createNativeBrowserService(options = {}) {
104104 const mac = options.platform === "darwin";
105105 const directory = options.directory ?? path.join(process.env.LOCALAPPDATA || path.join(homedir(), "AppData", "Local"), "Cage", "Browser");
@@ -113,6 +113,8 @@ export function createNativeBrowserService(options = {}) {
113113 const tabs = new Map(), byPage = new WeakMap(), sessions = new Map(), frameSessions = new WeakMap(), internalPages = new WeakSet();
114114 const captures = new Map();
115115 const events = [], transfers = new Map(), privateContexts = new Set(), editorConnections = new Map(), logins = new Map();
116新增: const clipboardCopies = new Map();
117新增: let clipboardHelper, copyVersion = 0, pendingCopy, copying;
116118 let eventSequence = 0, uploads, downloads, clipboard, pointer, composition, clipboardAvailable = false, cookieActions, extensions, controller, internalCreation, vault;
117119 let stateVersion = 0, snapshotVersion = -1, snapshotAt = 0, snapshotCache;
118120 let rfbTarget = "", rfbMask = 0, lastClick, rfbPointer;
@@ -125,6 +127,131 @@ export function createNativeBrowserService(options = {}) {
125127 events.push({ sequence: ++eventSequence, type, value });
126128 while (events.length > 64 || JSON.stringify(events).length > 350000) events.shift();
127129 }
130新增:
131新增: function invalidateCopies() {
132新增: copyVersion++;
133新增: pendingCopy = undefined;
134新增: for (const copy of clipboardCopies.values()) void rm(copy.file, { force: true }).catch(() => {});
135新增: clipboardCopies.clear();
136新增: }
137新增:
138新增: function copyTarget(proof) {
139新增: const tab = target(proof);
140新增: if (closing || tab.copyContext !== proof.context || proof.version !== copyVersion)
141新增: throw failure("copy_changed", "复制来源已切换,请重新复制");
142新增: return tab;
143新增: }
144新增:
145新增: async function privateClipboardPage() {
146新增: if (closing) throw failure("copy_unavailable", "浏览器已关闭");
147新增: if (!clipboardHelper) {
148新增: clipboardHelper = (async () => {
149新增: const isolated = await owner.newContext({ permissions: ["clipboard-read", "clipboard-write"] });
150新增: privateContexts.add(isolated);
151新增: isolated.on("close", () => { privateContexts.delete(isolated); clipboardHelper = undefined; });
152新增: try {
153新增: const page = await isolated.newPage();
154新增: await page.route("http://cage-clipboard.localhost/", route => route.fulfill({ contentType: "text/html", body: "<!doctype html><title>Cage clipboard</title>" }));
155新增: await page.goto("http://cage-clipboard.localhost/", { waitUntil: "domcontentloaded" });
156新增: return page;
157新增: } catch (error) { await isolated.close(); throw error; }
158新增: })();
159新增: }
160新增: return clipboardHelper;
161新增: }
162新增:
163新增: async function readPrivateClipboard() {
164新增: const helper = await privateClipboardPage();
165新增: const value = await helper.evaluate(async ({ imageLimit, textLimit }) => {
166新增: const items = await navigator.clipboard.read();
167新增: const mime = items.some(item => item.types.includes("image/png")) ? "image/png" : "text/plain";
168新增: const item = items.find(item => item.types.includes(mime));
169新增: if (!item) throw new Error("Clipboard format unavailable");
170新增: const blob = await item.getType(mime);
171新增: if (blob.size > (mime === "image/png" ? imageLimit : textLimit)) throw new Error("Clipboard size exceeded");
172新增: if (mime === "text/plain") return { text: await blob.text() };
173新增: return new Promise((resolve, reject) => {
174新增: const reader = new FileReader();
175新增: reader.onerror = reject;
176新增: reader.onload = () => resolve({ png: reader.result.slice(reader.result.indexOf(",") + 1) });
177新增: reader.readAsDataURL(blob);
178新增: });
179新增: }, { imageLimit, textLimit });
180新增: return value;
181新增: }
182新增:
183新增: async function copiedPayload(proof, value) {
184新增: copyTarget(proof);
185新增: const payload = { id: proof.id, context: proof.context, document: proof.document };
186新增: if (typeof value.text === "string" && Buffer.byteLength(value.text) <= textLimit && Buffer.byteLength(JSON.stringify(value.text)) <= chunkSize)
187新增: return { ...payload, text: value.text };
188新增: const mime = typeof value.text === "string" ? "text/plain" : "image/png";
189新增: const bytes = Buffer.from(mime === "text/plain" ? value.text : value.png, mime === "text/plain" ? "utf8" : "base64");
190新增: if (bytes.length > (mime === "text/plain" ? textLimit : imageLimit)) throw failure("copy_limit", "复制内容超过大小限制");
191新增: if (mime === "image/png" && (bytes.length < 33 || !bytes.subarray(0, 8).equals(Buffer.from([137,80,78,71,13,10,26,10])) || bytes.toString("ascii", 12, 16) !== "IHDR" ||
192新增: !bytes.readUInt32BE(16) || !bytes.readUInt32BE(20) || bytes.readUInt32BE(16) * bytes.readUInt32BE(20) > 40_000_000))
193新增: throw failure("copy_image_invalid", "复制的 PNG 图片无效");
194新增: const id = randomUUID(), file = path.join(uploadDirectory, "clipboard", id);
195新增: await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
196新增: await writeFile(file, bytes, { mode: 0o600, flag: "wx" });
197新增: try { copyTarget(proof); }
198新增: catch (error) { await rm(file, { force: true }); throw error; }
199新增: clipboardCopies.set(id, { ...proof, reference: id, file, mime, size: bytes.length, created: Date.now() });
200新增: return { ...payload, clipboard: { id, mime, size: bytes.length } };
201新增: }
202新增:
203新增: function observeCopy(value) {
204新增: if (closing) return;
205新增: const tab = tabs.get(value.id);
206新增: if (value.id !== active || tab?.copyContext !== value.context) return;
207新增: if (!mac) { emit("clipboard", { ...value, document: tab.document }); return; }
208新增: if (tab.explicitCopyContext === value.context) { tab.copyCompletion?.(value); return; }
209新增: invalidateCopies();
210新增: pendingCopy = { value, proof: { id: tab.id, context: value.context, document: tab.document, version: copyVersion } };
211新增: if (copying) return;
212新增: copying = (async () => {
213新增: while (pendingCopy) {
214新增: const current = pendingCopy;
215新增: pendingCopy = undefined;
216新增: try {
217新增: const value = current.value.changed ? await readPrivateClipboard() : current.value;
218新增: emit("clipboard", await copiedPayload(current.proof, value));
219新增: } catch {
220新增: try { copyTarget(current.proof); emit("clipboard", { id: current.proof.id, context: current.proof.context, document: current.proof.document, error: "copy_failed" }); }
221新增: catch {}
222新增: }
223新增: }
224新增: })().finally(() => { copying = undefined; });
225新增: }
226新增:
227新增: async function copyAction(tab, input, action, signal) {
228新增: if (!tokenPattern.test(input.context || "")) throw failure("invalid_input", "复制上下文无效");
229新增: const document = tab.document;
230新增: await privateClipboardPage();
231新增: await tab.page.bringToFront();
232新增: target({ id: tab.id, document });
233新增: invalidateCopies();
234新增: tab.copyContext = input.context;
235新增: tab.explicitCopyContext = input.context;
236新增: await clipboard.setContext(tab.id, input.context);
237新增: const proof = { id: tab.id, context: input.context, document, version: copyVersion };
238新增: let timeout;
239新增: const completed = new Promise((resolve, reject) => {
240新增: tab.copyCompletion = resolve;
241新增: timeout = setTimeout(() => reject(failure("copy_unavailable", "未收到新的复制内容,请重新选择后复制")), 5000);
242新增: });
243新增: completed.catch(() => {});
244新增: try {
245新增: signal?.throwIfAborted();
246新增: await tab.page.keyboard.press(action === "cut" ? "Meta+X" : "Meta+C");
247新增: await completed;
248新增: signal?.throwIfAborted();
249新增: copyTarget(proof);
250新增: const value = await readPrivateClipboard();
251新增: signal?.throwIfAborted();
252新增: return await copiedPayload(proof, value);
253新增: } finally { clearTimeout(timeout); tab.copyCompletion = undefined; }
254新增: }
128255 function remember() {
129256 if (!context || closing) return;
130257 const value = [...tabs.values()].filter(t => !t.incognito && !t.login && t.kind !== "editor").map(t => ({ id: t.id, url: t.page.url(), ...(t.kind === "browser-settings" ? { kind: t.kind, publicURL: t.publicURL } : {}) }));
@@ -243,6 +370,7 @@ export function createNativeBrowserService(options = {}) {
243370 page.on("close", () => {
244371 void stopCapture(page);
245372 tabs.delete(id); clipboard?.detachTab(id); uploads?.cancelTab(id);
373新增: if (active === id) invalidateCopies();
246374 if (vault) for (const [sid, entry] of vault.sessions) if (entry.tab === id) vault.sessions.delete(sid);
247375 if (active === id) active = [...tabs.keys()].at(-1) || "";
248376 if (pointer?.id === id) pointer = undefined;
@@ -253,6 +381,7 @@ export function createNativeBrowserService(options = {}) {
253381 });
254382 page.on("framenavigated", frame => {
255383 if (frame === page.mainFrame()) {
384新增: if (active === id) invalidateCopies();
256385 if (tab.kind !== "editor") {
257386 try {
258387 const address = new URL(page.url()), project = /^([a-f0-9]{16}(?:[a-f0-9]{8})?)\.cage-editor\.localhost$/.exec(address.hostname)?.[1];
@@ -353,10 +482,7 @@ export function createNativeBrowserService(options = {}) {
353482 context.setDefaultTimeout(7000); owner = context.browser();
354483 if (!owner) throw failure("browser_unavailable", "Windows 客机浏览器控制连接未就绪");
355484 browserCDP = await owner.newBrowserCDPSession();
356删除: clipboard = new modules.BrowserClipboard(cdp, value => {
357删除: const tab = tabs.get(value.id);
358删除: if (value.id === active && tab?.copyContext === value.context) emit("clipboard", { ...value, document: tab.document });
359删除: });
485新增: clipboard = new modules.BrowserClipboard(cdp, observeCopy, { includeChanges: mac });
360486 clipboardAvailable = true;
361487 if (modules.BrowserVault) vault = new modules.BrowserVault({ cdp, active: () => active, tab: id => { const tab = tabs.get(id); return tab ? { ...tab, url: tab.page.url() } : undefined; } });
362488 cookieActions = modules.browserCookies;
@@ -452,7 +578,7 @@ export function createNativeBrowserService(options = {}) {
452578 }
453579 async function activate(id) {
454580 const tab = tabs.get(id); if (!tab) throw failure("target_changed", "Tab no longer exists");
455删除: if (active !== id) { pointer = undefined; composition = undefined; tab.geometry = token(); }
581新增: if (active !== id) { invalidateCopies(); pointer = undefined; composition = undefined; tab.geometry = token(); }
456582 if (split && ![split.left, split.right].includes(id)) { split = undefined; await applyViewport(); }
457583 active = id; await tab.page.bringToFront(); changed(); return { ok: true };
458584 }
@@ -530,13 +656,28 @@ export function createNativeBrowserService(options = {}) {
530656 await syncNativeFrontTab();
531657 const tab = target({ id: active });
532658 const tree = await cdp("Page.getFrameTree", {}, tab.session);
533删除: const isolated = await cdp("Page.createIsolatedWorld", { frameId: tree.frameTree.frame.id, worldName: "cage-native-paste-proof" }, tab.session);
534删除: const result = await cdp("Runtime.evaluate", { expression: `(() => { let e=Object.getOwnPropertyDescriptor(Document.prototype,'activeElement').get.call(document); while(e){const root=Object.getOwnPropertyDescriptor(Element.prototype,'shadowRoot').get.call(e); if(!root)break; const next=Object.getOwnPropertyDescriptor(ShadowRoot.prototype,'activeElement').get.call(root);if(!next)break;e=next;}return e; })()`, contextId: isolated.executionContextId, objectGroup: "cage-paste-proof" }, tab.session);
535删除: try {
536删除: if (!result.result?.objectId) throw failure("target_changed", "Input target changed");
537删除: const node = await cdp("DOM.describeNode", { objectId: result.result.objectId }, tab.session);
538删除: return { focus: `${tab.document}:${isolated.executionContextId}:${node.node.backendNodeId}` };
539删除: } finally { await cdp("Runtime.releaseObjectGroup", { objectGroup: "cage-paste-proof" }, tab.session); }
659新增: const roots = new Map([[tree.frameTree.frame.id, tab.session]]);
660新增: for (const session of new Set(tab.page.frames().map(frame => frameSessions.get(frame)))) {
661新增: if (!session || session === tab.session) continue;
662新增: const child = await cdp("Page.getFrameTree", {}, session).catch(() => null);
663新增: if (child) roots.set(child.frameTree.frame.id, session);
664新增: }
665新增: const nodes = [], visited = new Set();
666新增: let frameId = tree.frameTree.frame.id, session = tab.session;
667新增: while (frameId) {
668新增: if (visited.has(frameId)) throw failure("target_changed", "Input target changed");
669新增: visited.add(frameId);
670新增: session = roots.get(frameId) || session;
671新增: const isolated = await cdp("Page.createIsolatedWorld", { frameId, worldName: "cage-native-paste-proof" }, session);
672新增: try {
673新增: const result = await cdp("Runtime.evaluate", { expression: `(() => { let e=Object.getOwnPropertyDescriptor(Document.prototype,'activeElement').get.call(document); while(e){const root=Object.getOwnPropertyDescriptor(Element.prototype,'shadowRoot').get.call(e); if(!root)break; const next=Object.getOwnPropertyDescriptor(ShadowRoot.prototype,'activeElement').get.call(root);if(!next)break;e=next;}return e; })()`, contextId: isolated.executionContextId, objectGroup: "cage-paste-proof" }, session);
674新增: if (!result.result?.objectId) throw failure("target_changed", "Input target changed");
675新增: const { node } = await cdp("DOM.describeNode", { objectId: result.result.objectId }, session);
676新增: nodes.push(`${frameId}:${isolated.executionContextId}:${node.backendNodeId}`);
677新增: frameId = node.frameId;
678新增: } finally { await cdp("Runtime.releaseObjectGroup", { objectGroup: "cage-paste-proof" }, session); }
679新增: }
680新增: return { focus: `${tab.document}:${nodes.join("/")}` };
540681 }
541682 function point(input, size = viewport) {
542683 if (![input.x, input.y].every(v => Number.isFinite(v) && v >= 0 && v <= 1)) throw failure("invalid_input", "指针位置无效");
@@ -604,6 +745,10 @@ export function createNativeBrowserService(options = {}) {
604745 const request = uploads.request(transfer.id), tab = tabs.get(request.tabId);
605746 if (request !== transfer.request || active !== request.tabId || tab?.document !== transfer.document) throw failure("target_changed", "文件接收网页已切换,请返回原网页重试");
606747 }
748新增: if (transfer.copy) {
749新增: copyTarget(transfer.copy);
750新增: if (clipboardCopies.get(transfer.copy.reference) !== transfer.copy) throw failure("copy_changed", "复制内容已过期,请重新复制");
751新增: }
607752 return transfer;
608753 }
609754 async function closeTransfer(id) {
@@ -621,6 +766,10 @@ export function createNativeBrowserService(options = {}) {
621766 input.mime && !["image/png", "text/plain"].includes(input.mime))
622767 throw failure("image_target_invalid", "图片目标或大小无效");
623768 const document = tab.document, geometry = tab.geometry;
769新增: if (mac) {
770新增: invalidateCopies(); tab.copyContext = "";
771新增: await clipboard.setContext(tab.id, "");
772新增: }
624773 const focus = await nativeFocusProof();
625774 signal?.throwIfAborted();
626775 if (target(input) !== tab || tab.document !== document || tab.geometry !== geometry) throw failure("image_target_changed", "Image target changed");
@@ -656,29 +805,29 @@ export function createNativeBrowserService(options = {}) {
656805 let text;
657806 if (transfer.mime === "text/plain") {
658807 text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
808新增: if (mac) {
809新增: const helper = await privateClipboardPage();
810新增: signal?.throwIfAborted();
811新增: await helper.evaluate(text => navigator.clipboard.writeText(text), text);
812新增: }
659813 } else {
660814 if (bytes.length < 33 || !bytes.subarray(0, 8).equals(Buffer.from([137,80,78,71,13,10,26,10])) || bytes.toString("ascii", 12, 16) !== "IHDR" ||
661815 !bytes.readUInt32BE(16) || !bytes.readUInt32BE(20) || bytes.readUInt32BE(16) * bytes.readUInt32BE(20) > 40_000_000)
662816 throw failure("image_invalid", "PNG 图片无效");
663817 // A private, local helper origin writes Chromium's clipboard. The site
664818 // receives an ordinary paste event without gaining clipboard permissions.
665删除: const isolated = await owner.newContext({ permissions: ["clipboard-write"] });
666删除: try {
667删除: const helper = await isolated.newPage();
668删除: await helper.route("http://cage-image.localhost/", route => route.fulfill({ contentType: "text/html", body: "<!doctype html><title>Cage image input</title>" }));
669删除: await helper.goto("http://cage-image.localhost/", { waitUntil: "domcontentloaded" });
670删除: signal?.throwIfAborted();
671删除: await helper.evaluate(async encoded => {
672删除: const bytes = Uint8Array.from(atob(encoded), value => value.charCodeAt(0));
673删除: await navigator.clipboard.write([new ClipboardItem({ "image/png": new Blob([bytes], { type: "image/png" }) })]);
674删除: }, bytes.toString("base64"));
675删除: } finally { await isolated.close(); }
819新增: const helper = await privateClipboardPage();
820新增: signal?.throwIfAborted();
821新增: await helper.evaluate(async encoded => {
822新增: const bytes = Uint8Array.from(atob(encoded), value => value.charCodeAt(0));
823新增: await navigator.clipboard.write([new ClipboardItem({ "image/png": new Blob([bytes], { type: "image/png" }) })]);
824新增: }, bytes.toString("base64"));
676825 }
677826 await tab.page.bringToFront();
678827 if (target({ id: transfer.id, document: transfer.document }) !== tab || tab.geometry !== transfer.geometry || (await nativeFocusProof()).focus !== transfer.focus)
679828 throw failure("image_target_changed", "Image target changed");
680829 signal?.throwIfAborted();
681删除: if (text !== undefined) await tab.page.keyboard.insertText(text);
830新增: if (text !== undefined && !mac) await tab.page.keyboard.insertText(text);
682831 else await tab.page.keyboard.press(mac ? "Meta+V" : "Control+V");
683832 transfers.delete(input.transfer);
684833 return { ok: true };
@@ -704,12 +853,21 @@ export function createNativeBrowserService(options = {}) {
704853 transfers.set(transferID, transfer); return { transfer: transferID };
705854 }
706855 if (input.direction === "download") {
707删除: const source = downloads.sourceFile(input.id), file = await open(source, constants.O_RDONLY | (constants.O_NOFOLLOW || 0));
856新增: const copy = clipboardCopies.get(input.id);
857新增: if (copy || input.context || input.document || input.tab) {
858新增: if (!copy || input.tab !== copy.id || input.context !== copy.context || input.document !== copy.document) throw failure("copy_changed", "复制来源已切换,请重新复制");
859新增: copyTarget(copy);
860新增: }
861新增: const source = copy ? copy.file : downloads.sourceFile(input.id), file = await open(source, constants.O_RDONLY | (constants.O_NOFOLLOW || 0));
708862 const info = await file.stat();
709863 if (!info.isFile()) { await file.close(); throw failure("download_unavailable", "下载文件不可用"); }
710删除: const record = downloads.snapshot().find(d => d.id === input.id);
711删除: transfers.set(transferID, { direction: "download", id: input.id, file, length: info.size, received: 0, sequence: 0, used: Date.now() });
712删除: return { transfer: transferID, size: info.size, name: record.name };
864新增: if (copy) {
865新增: try { copyTarget(copy); if (info.size !== copy.size) throw failure("copy_changed", "复制内容已变化"); }
866新增: catch (error) { await file.close(); throw error; }
867新增: }
868新增: const name = copy ? "clipboard." + (copy.mime === "image/png" ? "png" : "txt") : downloads.snapshot().find(d => d.id === input.id).name;
869新增: transfers.set(transferID, { direction: "download", id: input.id, copy, file, length: info.size, received: 0, sequence: 0, used: Date.now() });
870新增: return { transfer: transferID, size: info.size, name, ...(copy ? { mime: copy.mime } : {}) };
713871 }
714872 throw failure("invalid_input", "文件传递方向无效");
715873 }
@@ -730,6 +888,7 @@ export function createNativeBrowserService(options = {}) {
730888 }
731889 if (action === "file-read" && transfer.direction === "download") {
732890 const data = Buffer.alloc(chunkSize), { bytesRead } = await transfer.file.read(data, 0, data.length, transfer.received);
891新增: if (transfer.copy) checkTransfer(input);
733892 transfer.received += bytesRead; transfer.sequence++;
734893 const eof = transfer.received === transfer.length;
735894 if (!bytesRead && !eof) throw failure("download_unavailable", "下载文件没有完整返回");
@@ -1037,8 +1196,10 @@ export function createNativeBrowserService(options = {}) {
10371196 if (action === "forward") { await page.goForward({ waitUntil: "commit", timeout: 8000 }); return { ok: true }; }
10381197 if (action === "copy-context") {
10391198 if (!tokenPattern.test(input.context || "")) throw failure("invalid_input", "Copy target changed");
1199新增: if (tab.copyContext !== input.context) { invalidateCopies(); tab.explicitCopyContext = undefined; }
10401200 tab.copyContext = input.context; await clipboard.setContext(tab.id, input.context); return { ok: true };
10411201 }
1202新增: if (mac && (action === "copy" || action === "cut")) return copyAction(tab, input, action, signal);
10421203 if (action === "insert-text") {
10431204 if (typeof input.text !== "string" || !input.text || Buffer.byteLength(input.text) > 8192) throw failure("invalid_input", "Input target or text is invalid");
10441205 await page.bringToFront(); signal?.throwIfAborted(); await page.keyboard.insertText(input.text); return { ok: true };
@@ -1075,13 +1236,20 @@ export function createNativeBrowserService(options = {}) {
10751236 if (closing) return closing;
10761237 remember();
10771238 closing = (async () => {
1239新增: invalidateCopies();
10781240 for (const id of transfers.keys()) await closeTransfer(id);
1241新增: await copying;
10791242 for (const privateContext of privateContexts) await privateContext.close().catch(() => {});
10801243 for (const login of logins.values()) clearTimeout(login.expiry);
10811244 await persistQueue.catch(() => {}); await context?.close().catch(() => {});
10821245 })(); return closing;
10831246 }
1084删除: const expiry = setInterval(() => { for (const [id, t] of transfers) if (Date.now() - t.used > 120000) void closeTransfer(id); }, 10000);
1247新增: const expiry = setInterval(() => {
1248新增: for (const [id, t] of transfers) if (Date.now() - t.used > 120000) void closeTransfer(id);
1249新增: for (const [id, copy] of clipboardCopies) if (Date.now() - copy.created > 120000) {
1250新增: clipboardCopies.delete(id); void rm(copy.file, { force: true }).catch(() => {});
1251新增: }
1252新增: }, 10000);
10851253 expiry.unref();
10861254 return { request, releaseInput, close: async () => { tailnet.close(); clearInterval(expiry); await close(); } };
10871255}
修改scripts/package-macos.sh+6 −5看文件
@@ -40,18 +40,19 @@ cat > "$stage/安装说明 - Read Me.txt" <<'EOF'
4040Cage — 本机隔离编码工作区
4141
42421. 将 Cage.app 拖入 Applications(应用程序)。
43删除:2. 从应用程序打开 Cage;首次启动在“网络与代理”添加自己的 Clash/Mihomo YAML 订阅或配置。
44删除:3. 选择节点,启动 Cage 环境。首次需要下载 Linux 镜像和工具,请保持网络连接。
43新增:2. 从应用程序打开 Cage,设置本地账户,并按首次引导选择客机系统、存储位置和代理。
44新增:3. 添加自己的 Clash/Mihomo YAML 订阅或配置并选择节点,创建和启动环境。首次需下载系统镜像和工具,请保持网络连接。
45454. 打开项目或新建终端,输入 claude,并在 Cage 浏览器内登录自己的 Claude 账户。
4646
4747需要 Apple Silicon Mac、macOS 14 或更新版本。无需安装 Go、Node.js 或 Clash。
48删除:代理服务与 Claude 账户需自行准备。此版本为 Alpha。
48新增:代理服务与 Claude 账户需自行准备。具体版本与发布状态以发行说明为准。
4949共享项目中的文件修改会直接写回 Mac;请备份重要项目。
5050升级前请退出 Cage 并停止环境,再替换应用程序;配置与项目文件会保留。
5151
5252Drag Cage.app into Applications, then open it from Applications.
53删除:Add your own Clash/Mihomo YAML subscription or configuration, select a node,
54删除:and start the environment. Initial setup downloads Linux and developer tools.
53新增:Complete the local account and environment setup, add your own Clash/Mihomo
54新增:YAML subscription or configuration, select a node, and start the environment.
55新增:Initial setup downloads the selected guest system and developer tools.
5556Requires Apple Silicon and macOS 14+. Your own proxy and Claude account are required.
5657
5758入门 / Getting started:
修改ui/scripts/macos-default-workspace-smoke.mjs+23 −2看文件
@@ -10,6 +10,7 @@ const notice = "此历史会话仍使用原来的客机目录,文件保留在
1010let allowed = false;
1111let screenAllowed = false, frameReads = 0, frameReadsAtClick = 0;
1212const actions = [];
13新增:const maintenance = [];
1314const fixture = await createWorkbench({
1415 beforeNavigate: async (page, state) => {
1516 const panelImage = await page.evaluate(() => {
@@ -43,13 +44,22 @@ const fixture = await createWorkbench({
4344 ? { image: panelImage, window: 1, pid: 5, nonce: "fixture" }
4445 : { error: "project_screen_permission" } });
4546 });
47新增: await page.route("**/api/macos/maintenance", route => {
48新增: const request = route.request().postDataJSON();
49新增: maintenance.push(request);
50新增: if (request.action === "open") return route.fulfill({ json: { session: "permission-fixture", maintenance_version: 1 } });
51新增: if (request.action === "frame") return route.fulfill({ json: {
52新增: image: panelImage, mime: "image/png", geometry: "permission-window", region: [100, 80, 480, 260], maintenance_version: 1,
53新增: } });
54新增: return route.fulfill({ json: { maintenance_version: 1 } });
55新增: });
4656 await page.route("**/api/cli/sessions/*/account", route => route.fulfill({ json: { supported: false, candidates: [], session: {} } }));
4757 await page.routeWebSocket("**/api/terminals/**", socket => socket.send(Buffer.from("隔离测试终端\r\n/Users/cage/.local/share/cage/workspace $ ")));
4858 },
4959});
5060const { page, state, browser, errors } = fixture;
5161try {
52删除: await page.getByRole("button", { name: "连接项目", exact: true }).click();
62新增: await page.getByRole("button", { name: "重新连接项目", exact: true }).click();
5363 const project = page.getByRole("dialog", { name: "打开项目", exact: true });
5464 await project.waitFor();
5565 assert.equal(await project.getByRole("textbox", { name: "新项目文件夹", exact: true }).inputValue(), state.settings.workspace);
@@ -59,6 +69,12 @@ try {
5969 await permission.getByText(state.settings.workspace, { exact: true }).waitFor();
6070 await permission.getByRole("status").filter({ hasText: "屏幕与系统音频录制" }).waitFor();
6171 await page.screenshot({ path: join(output, "default-workspace-approval.png"), animations: "disabled" });
72新增: await permission.getByRole("button", { name: "打开客机授权设置", exact: true }).click();
73新增: const recovery = page.getByRole("dialog", { name: "恢复客机系统权限", exact: true });
74新增: await recovery.getByRole("img").waitFor();
75新增: assert.equal(maintenance.find(request => request.action === "open").maintenance, "screen");
76新增: await recovery.getByRole("button", { name: "返回工作台", exact: true }).click();
77新增: await recovery.waitFor({ state: "detached" });
6278 screenAllowed = true;
6379 await permission.getByRole("img").click();
6480 const inputError = permission.getByRole("alert").filter({ hasText: "辅助功能" });
@@ -66,6 +82,11 @@ try {
6682 await permission.getByRole("img").waitFor();
6783 assert.ok(frameReads > frameReadsAtClick, "next guest frame was fetched");
6884 assert.ok(await inputError.isVisible(), "polling must retain the failed click");
85新增: await permission.getByRole("button", { name: "打开客机授权设置", exact: true }).click();
86新增: await recovery.getByRole("img").waitFor();
87新增: assert.equal(maintenance.filter(request => request.action === "open").at(-1).maintenance, "input");
88新增: await recovery.getByRole("button", { name: "返回工作台", exact: true }).click();
89新增: await recovery.waitFor({ state: "detached" });
6990 allowed = true;
7091 await permission.getByRole("button", { name: "验证授权", exact: true }).click();
7192 await permission.waitFor({ state: "hidden" });
@@ -79,7 +100,7 @@ try {
79100 await page.getByRole("status").filter({ hasText: notice }).waitFor();
80101 await page.screenshot({ path: join(output, "default-workspace-legacy-notice.png"), animations: "disabled" });
81102 assert.deepEqual(errors, []);
82删除: const result = { passed: true, browser: browser.browserType().name(), actions, checks: ["default workspace reconnect opens existing project authorization", "missing screen permission shows the macOS settings path", "click permission error survives the next frame", "permission retry keeps the same host directory", "legacy guest-private workspace notice is visible in the terminal"] };
103新增: const result = { passed: true, browser: browser.browserType().name(), actions, checks: ["default workspace reconnect opens existing project authorization", "missing screen permission opens its restricted recovery view", "click permission error survives the next frame and opens input recovery", "permission retry keeps the same host directory", "legacy guest-private workspace notice is visible in the terminal"] };
83104 await writeFile(join(output, "result.json"), JSON.stringify(result, null, 2));
84105 console.log(JSON.stringify(result));
85106} finally { await browser.close(); }
修改ui/scripts/macos-login-fullscreen-smoke.mjs+74 −0看文件
@@ -95,6 +95,7 @@ for (const viewport of [{ width: 1280, height: 900 }, { width: 1920, height: 108
9595 assert.equal(inputs[1].x,Math.floor((x-pan.x)*1024/pan.width));
9696 assert.equal(inputs[1].y,Math.floor((y-pan.y)*640/pan.height));
9797 await input.press("Enter"); await waitInput(3); assert.equal(inputs[2].code,36);
98新增: assert.equal(await screen.isVisible(), true, "Return must wait for the guest to confirm login");
9899 await input.evaluate((el) => {
99100 const data=new DataTransfer(); data.setData("text/plain","Z7");
100101 el.dispatchEvent(new ClipboardEvent("paste",{bubbles:true,cancelable:true,clipboardData:data}));
@@ -121,3 +122,76 @@ for (const viewport of [{ width: 1280, height: 900 }, { width: 1920, height: 108
121122 console.log(`${viewport.width}×${viewport.height}: default login crop, compact panel, coordinate mapping, fit, pan, paste, native close and completion passed.`);
122123 } catch (error) { console.error("page:",(await page.locator("body").innerText()).slice(0,700), "errors:", errors); throw error; } finally { await browser.close(); }
123124}
125新增:
126新增:// Exercise the first-setup password button through the normal page entry.
127新增:// Frame polling must preserve an operation error until a user action succeeds.
128新增:{
129新增: let operationError = "请先点选系统授权窗口的密码框,再点击填写授权密码";
130新增: let frameError = "", frames = 0, latestFrame = "";
131新增: const fixture = await createWorkbench({
132新增: async beforeNavigate(page, state) {
133新增: Object.assign(state.account, {initial_mac_setup:true, guest_system:"macos", macos_guest_user:"cage"});
134新增: Object.assign(state.status, {ready:true, vm_running:true});
135新增: const images = await page.evaluate(() => {
136新增: const canvas = document.createElement("canvas");
137新增: canvas.width = 160; canvas.height = 100;
138新增: const paint = canvas.getContext("2d");
139新增: return ["#526482", "#627492"].map(color => {
140新增: paint.fillStyle = color; paint.fillRect(0, 0, canvas.width, canvas.height);
141新增: return canvas.toDataURL("image/png").split(",")[1];
142新增: });
143新增: });
144新增: await page.route("**/api/macos/first-setup", async route => {
145新增: const request = route.request().postDataJSON();
146新增: if (request.action === "permissions") return route.fulfill({json:{screen:false, input:false, projects:false, managed_credential:true}});
147新增: if (request.action === "open") return route.fulfill({json:{session:"error-persistence-fixture"}});
148新增: if (request.action === "frame") {
149新增: frames++;
150新增: if (frameError) return route.fulfill({json:{error:frameError}});
151新增: latestFrame = images[frames % images.length];
152新增: return route.fulfill({json:{image:latestFrame}});
153新增: }
154新增: if (request.action === "fill-password") {
155新增: assert.equal(request.password, undefined, "browser supplied a credential");
156新增: return route.fulfill({json:operationError ? {error:operationError} : {}});
157新增: }
158新增: return route.fulfill({json:{}});
159新增: });
160新增: },
161新增: });
162新增: const {page, browser, errors} = fixture;
163新增: try {
164新增: const screen = page.getByRole("dialog", {name:"首次设置虚拟 Mac"});
165新增: const fill = screen.getByRole("button", {name:"填写授权密码", exact:true});
166新增: await screen.getByRole("img").waitFor();
167新增: await fill.click();
168新增: await screen.getByRole("alert").filter({hasText:operationError}).waitFor();
169新增: const observed = frames;
170新增: for (let attempts = 0; frames < observed + 2 && attempts < 150; attempts++)
171新增: await new Promise(resolve => setTimeout(resolve, 20));
172新增: assert.ok(frames >= observed + 2, "frame polling stopped after an input error");
173新增: await page.waitForFunction(image => document.querySelector(".mac-login-canvas img")?.src.endsWith(image), latestFrame);
174新增: assert.equal(await screen.getByRole("alert").isVisible(), true, "a successful frame erased the password error");
175新增: assert.equal(await screen.getByRole("alert").innerText(), operationError);
176新增:
177新增: frameError = "授权画面暂时无法读取";
178新增: await page.waitForResponse(async response => response.url().endsWith("/api/macos/first-setup") &&
179新增: response.request().postDataJSON()?.action === "frame" && (await response.json()).error === frameError);
180新增: operationError = "";
181新增: await fill.click();
182新增: await screen.getByRole("alert").filter({hasText:frameError}).waitFor();
183新增: frameError = "";
184新增: await screen.getByRole("alert").waitFor({state:"hidden"});
185新增:
186新增: operationError = "系统授权窗口或密码框已变化,填写已停止,请重新选择";
187新增: await fill.click();
188新增: await screen.getByRole("alert").filter({hasText:operationError}).waitFor();
189新增: await screen.getByRole("button", {name:"返回设置指引"}).click();
190新增: await screen.waitFor({state:"detached"});
191新增: await page.getByRole("button", {name:"打开客机系统设置", exact:true}).click();
192新增: await screen.getByRole("img").waitFor();
193新增: assert.equal(await screen.getByRole("alert").count(), 0, "reopening retained an old operation error");
194新增: assert.deepEqual(errors, []);
195新增: console.log("First-setup password error persistence, independent frame recovery and close/reopen cleanup passed.");
196新增: } finally { await browser.close(); }
197新增:}
新增ui/scripts/macos-project-recovery-smoke.mjs+133 −0看文件
@@ -0,0 +1,133 @@
1新增:import assert from "node:assert/strict";
2新增:import { fileURLToPath } from "node:url";
3新增:import { createWorkbench } from "./workbench-fixture.mjs";
4新增:
5新增:const project = "/Users/fixture/Cage Projects/macOS 示例";
6新增:const calls = [];
7新增:let loggedIn = false, maintenanceClosed = false, geometry = "maintenance-frame-a", images;
8新增:const { page, browser, state, errors } = await createWorkbench({
9新增: viewport: { width: 1280, height: 900 },
10新增: async beforeNavigate(page, state) {
11新增: state.status.vm_running = state.status.ready = true;
12新增: state.account.guest_system = state.status.guest_system = "macos";
13新增: state.status.projects = [project];
14新增: state.status.workspace = state.settings.workspace = project;
15新增: state.status.project_error = "部分项目文件夹尚未连接,环境和浏览器可继续使用。";
16新增: state.status.project_errors = [{ path: project, recovery: "guest-login", message: "请先登录虚拟 Mac 的客机账户。登录完成后,Cage 会自动连接项目。" }];
17新增: images = await page.evaluate(() => {
18新增: const make = (width, height, color) => {
19新增: const canvas = document.createElement("canvas");
20新增: canvas.width = width; canvas.height = height;
21新增: const context = canvas.getContext("2d");
22新增: context.fillStyle = color; context.fillRect(0, 0, width, height);
23新增: context.fillStyle = "#fff"; context.font = "22px sans-serif";
24新增: context.fillText("Synthetic Apple authorization window", 20, 45);
25新增: return canvas.toDataURL("image/jpeg").split(",")[1];
26新增: };
27新增: return { login: make(1920, 1200, "#485570"), a: make(600, 400, "#334252"), b: make(480, 360, "#465835") };
28新增: });
29新增: await page.route("**/api/macos/login", route => {
30新增: const request = route.request().postDataJSON();
31新增: calls.push({ mode: "login", ...request });
32新增: if (request.action === "open") return route.fulfill({ json: { session: "login-fixture" } });
33新增: if (request.action === "close") return route.fulfill({ json: { closed: true } });
34新增: if (request.action === "frame") {
35新增: if (loggedIn) {
36新增: state.status.project_errors = []; state.status.project_error = "";
37新增: return route.fulfill({ json: { closed: true } });
38新增: }
39新增: return route.fulfill({ json: { image: images.login, mime: "image/jpeg" } });
40新增: }
41新增: return route.fulfill({ json: {} });
42新增: });
43新增: await page.route("**/api/projects/open", route => {
44新增: if (!loggedIn) return route.fulfill({ status: 400, contentType: "text/plain; charset=utf-8", headers: { "X-Cage-Recovery": "guest-login" }, body: "请先登录虚拟 Mac 的客机账户。" });
45新增: return route.fulfill({ json: { workspace: project } });
46新增: });
47新增: await page.route("**/api/macos/maintenance", route => {
48新增: const request = route.request().postDataJSON();
49新增: calls.push({ mode: "maintenance", ...request });
50新增: assert(["projects", "screen", "input"].includes(request.maintenance));
51新增: assert.equal(request.initial_setup, undefined);
52新增: assert.equal(request.password, undefined);
53新增: if (request.action === "open") return route.fulfill({ json: { session: "maintenance-fixture", maintenance_version: 1, administrator: "cageprovision" } });
54新增: if (request.action === "close") return route.fulfill({ json: { closed: true, maintenance_version: 1 } });
55新增: if (request.action === "frame") return route.fulfill({ json: maintenanceClosed
56新增: ? { closed: true, maintenance_version: 1, error: "客机前台应用已变化" }
57新增: : { image: geometry.endsWith("a") ? images.a : images.b, mime: "image/jpeg", geometry,
58新增: region: geometry.endsWith("a") ? [120, 90, 600, 400] : [240, 150, 480, 360], maintenance_version: 1 } });
59新增: return route.fulfill({ json: { maintenance_version: 1 } });
60新增: });
61新增: },
62新增:});
63新增:page.setDefaultTimeout(12000);
64新增:async function until(predicate) {
65新增: for (let attempt = 0; attempt < 150; attempt++) {
66新增: if (predicate()) return;
67新增: await page.waitForTimeout(20);
68新增: }
69新增: assert(predicate(), "expected recovery operation did not arrive");
70新增:}
71新增:try {
72新增: const failures = page.locator(".project-connection-errors");
73新增: await failures.getByRole("button", { name: "登录客机账户", exact: true }).click();
74新增: const login = page.getByRole("dialog", { name: "登录虚拟 Mac", exact: true });
75新增: await login.getByAltText("Apple 客机登录屏幕").waitFor();
76新增: await login.getByLabel(/^客机登录键盘/).press("Enter");
77新增: await until(() => calls.some(call => call.mode === "login" && call.action === "key" && call.code === 36));
78新增: assert(await login.isVisible(), "Return closed the view before macOS reported a completed login");
79新增: loggedIn = true;
80新增: await login.waitFor({ state: "detached" });
81新增: await failures.waitFor({ state: "detached" });
82新增:
83新增: state.status.project_error = "部分项目文件夹尚未连接,环境和浏览器可继续使用。";
84新增: state.status.project_errors = [{ path: project, recovery: "filesystem-permission", message: "虚拟 Mac 的文件系统扩展尚未启用。" }];
85新增: await page.reload();
86新增: await failures.getByRole("button", { name: "打开客机授权设置", exact: true }).click();
87新增: const maintenance = page.getByRole("dialog", { name: "恢复客机系统权限", exact: true });
88新增: const image = maintenance.getByAltText("客机系统设置或授权窗口");
89新增: await page.waitForFunction(() => document.querySelector('[data-mode="maintenance"] img')?.naturalWidth === 600);
90新增: const first = await image.boundingBox();
91新增: await image.click({ position: { x: first.width / 2, y: first.height / 2 } });
92新增: await until(() => calls.some(call => call.mode === "maintenance" && call.action === "click"));
93新增: const click = calls.find(call => call.mode === "maintenance" && call.action === "click");
94新增: assert.equal(click.geometry, "maintenance-frame-a");
95新增: assert(Math.abs(click.x - 420) <= 1 && Math.abs(click.y - 290) <= 1);
96新增: await maintenance.getByLabel(/^客机登录键盘/).press("Meta+a");
97新增: await maintenance.getByRole("button", { name: "填写管理员密码", exact: true }).click();
98新增: await until(() => calls.some(call => call.action === "select-all") && calls.some(call => call.action === "fill-password"));
99新增: assert(calls.filter(call => call.mode === "maintenance" && ["select-all", "fill-password"].includes(call.action))
100新增: .every(call => call.geometry === "maintenance-frame-a" && call.session === "maintenance-fixture"));
101新增: assert(!calls.some(call => call.mode === "maintenance" && call.action === "key" && call.code === 36), "password fill submitted authorization without the user");
102新增: await page.screenshot({ path: fileURLToPath(new URL("../../docs/test-reports/2026-11-09-architecture-fixes/evidence/mac-maintenance-ui.png", import.meta.url)) });
103新增:
104新增: geometry = "maintenance-frame-b";
105新增: await page.waitForFunction(() => document.querySelector('[data-mode="maintenance"] img')?.naturalWidth === 480);
106新增: const next = await image.boundingBox();
107新增: await image.click({ position: { x: next.width / 2, y: next.height / 2 } });
108新增: await until(() => calls.some(call => call.action === "click" && call.geometry === geometry));
109新增: const moved = calls.find(call => call.action === "click" && call.geometry === geometry);
110新增: assert(Math.abs(moved.x - 480) <= 1 && Math.abs(moved.y - 330) <= 1);
111新增: maintenanceClosed = true;
112新增: await maintenance.waitFor({ state: "detached" });
113新增: assert.equal(await page.locator('[data-mode="maintenance"] img').count(), 0);
114新增:
115新增: maintenanceClosed = false;
116新增: state.status.project_error = "";
117新增: state.status.project_errors = [];
118新增: await page.reload();
119新增: await page.getByRole("button", { name: "设置", exact: true }).click();
120新增: await page.getByRole("navigation", { name: "设置分组" }).getByRole("button", { name: "环境与恢复", exact: true }).click();
121新增: const permissions = page.getByRole("region", { name: "客机系统权限", exact: true });
122新增: for (const [label, purpose] of [["文件共享权限", "projects"], ["屏幕录制权限", "screen"], ["辅助功能权限", "input"]]) {
123新增: const start = calls.length;
124新增: await permissions.getByRole("button", { name: label, exact: true }).click();
125新增: await image.waitFor();
126新增: assert(calls.slice(start).some(call => call.action === "open" && call.maintenance === purpose));
127新增: await maintenance.getByRole("button", { name: "返回工作台", exact: true }).click();
128新增: await maintenance.waitFor({ state: "detached" });
129新增: await until(() => calls.slice(start).some(call => call.action === "close" && call.maintenance === purpose));
130新增: }
131新增: assert.deepEqual(errors, []);
132新增: console.log(JSON.stringify({ result: "PASS", browser: browser.version(), checks: ["actionable project login", "Return waits for macOS", "restored project removes warning", "separate maintenance purpose", "cropped window input coordinates", "published geometry binding", "explicit administrator fill intent without password data or submission", "geometry change rebinds crop", "foreground change removes maintenance image", "three permission recovery entries remain available without a project error"] }));
133新增:} finally { await browser.close(); }
新增ui/scripts/storage-recovery-smoke.mjs+97 −0看文件
@@ -0,0 +1,97 @@
1新增:import assert from "node:assert/strict";
2新增:import { createWorkbench } from "./workbench-fixture.mjs";
3新增:
4新增:let exports = 0;
5新增:const { browser, page, state, errors } = await createWorkbench({
6新增: viewport: { width: Number(process.env.CAGE_STORAGE_WIDTH || 1280), height: 850 },
7新增: clientContext: { mode: "local", connection_id: "local", client_platform: "windows", server_platform: "windows", connection: { state: "disconnected" } },
8新增: nativeRequest: async ({ action }) => {
9新增: if (action === "exportDiagnostics") { exports++; return { saved: true }; }
10新增: return null;
11新增: },
12新增:});
13新增:try {
14新增: const attempts = [];
15新增: let location = null;
16新增: state.account.guest_system = "windows-11";
17新增: state.account.unlocked = false;
18新增: state.account.require_authentication = true;
19新增: Object.assign(state.status, {
20新增: local_vm_storage: true, guest_system: "windows-11", ready: false, vm_running: false,
21新增: storage_recovery: { required: true, error: "系统管理服务尚未完成旧磁盘恢复", repair_allowed: true },
22新增: });
23新增: await page.route("**/api/environment/storage", route => {
24新增: assert.equal(route.request().method(), "GET", "pending recovery admitted a migration");
25新增: return route.fulfill({ json: location || { recovery: state.status.storage_recovery } });
26新增: });
27新增: await page.route("**/api/environment/storage/recover", route => {
28新增: attempts.push(route.request().postDataJSON());
29新增: state.status.job = {
30新增: id: `storage-recovery-${attempts.length}`, kind: "storage-recovery", running: true,
31新增: message: attempts.at(-1).repair ? "正在修复 Windows 系统助手,请完成系统授权…" : "正在恢复环境存储并检查数据位置…",
32新增: };
33新增: return route.fulfill({ json: state.status.job });
34新增: });
35新增: await page.route("**/api/diagnostics", route => route.fulfill({ json: { bytes: 2048, files: 2 } }));
36新增: await page.reload();
37新增: await page.getByRole("region", { name: "解锁 Cage", exact: true }).waitFor();
38新增: await page.getByLabel("账户密码", { exact: true }).fill("fixture-password");
39新增: await page.getByRole("button", { name: "解锁 Cage", exact: true }).click();
40新增: await page.getByRole("heading", { name: "环境存储需要恢复", exact: true }).waitFor();
41新增: assert.equal(await page.getByRole("button", { name: "启动 Cage 环境", exact: true }).count(), 0);
42新增: await page.getByRole("button", { name: "恢复环境存储", exact: true }).click();
43新增: const panel = page.getByRole("region", { name: "本机环境存储", exact: true });
44新增: const retry = panel.getByRole("button", { name: "重试恢复", exact: true });
45新增: const repair = panel.getByRole("button", { name: "修复系统助手并恢复", exact: true });
46新增: await retry.waitFor();
47新增: await panel.getByText(state.status.storage_recovery.error, { exact: true }).waitFor();
48新增: assert.equal(await panel.getByLabel("新存储位置").count(), 0);
49新增: assert.equal(await page.getByRole("region", { name: "环境版本", exact: true }).count(), 0);
50新增:
51新增: await retry.click();
52新增: await panel.getByRole("status").waitFor();
53新增: assert.deepEqual(attempts, [{ repair: false }]);
54新增: assert.equal(await retry.isDisabled(), true);
55新增: assert.equal(await repair.isDisabled(), true);
56新增: await retry.evaluate(button => { button.click(); button.click(); });
57新增: assert.equal(attempts.length, 1, "disabled recovery button submitted the same operation twice");
58新增: await page.getByRole("button", { name: "导出诊断包", exact: true }).click();
59新增: await page.getByText("诊断包已保存。分享前请检查其中内容。", { exact: true }).waitFor();
60新增: assert.equal(exports, 1, "recovery blocked diagnostic export");
61新增:
62新增: state.status.storage_recovery.error = "系统管理服务协议需要更新,旧磁盘仍待恢复";
63新增: state.status.job = { ...state.status.job, running: false, error: state.status.storage_recovery.error };
64新增: await panel.getByText(state.status.storage_recovery.error, { exact: true }).waitFor();
65新增: await page.waitForFunction(() => [...document.querySelectorAll(".environment-storage button")].every(button => !button.disabled));
66新增: await repair.click();
67新增: await panel.getByRole("status").waitFor();
68新增: assert.deepEqual(attempts, [{ repair: false }, { repair: true }]);
69新增: assert.equal(await retry.isDisabled(), true);
70新增: assert.equal(await repair.isDisabled(), true);
71新增: const geometry = await panel.evaluate(element => {
72新增: const actions = element.querySelector(".storage-actions").getBoundingClientRect();
73新增: const help = element.querySelector(".storage-repair-help").getBoundingClientRect();
74新增: const progress = element.querySelector('[role="status"]').getBoundingClientRect();
75新增: return { actionsBottom: actions.bottom, helpTop: help.top, progressTop: progress.top };
76新增: });
77新增: assert.ok(geometry.helpTop >= geometry.actionsBottom + 8, "repair instruction overlaps its controls");
78新增: assert.ok(geometry.progressTop >= geometry.actionsBottom + 8, "recovery progress overlaps its controls");
79新增: if (process.env.CAGE_STORAGE_SCREENSHOT) {
80新增: await panel.scrollIntoViewIfNeeded();
81新增: await page.screenshot({ path: process.env.CAGE_STORAGE_SCREENSHOT });
82新增: }
83新增: assert.equal(state.requests.filter(request => request.path === "/start").length, 0);
84新增:
85新增: location = { directory: "D:\\Cage 环境", has_environment: true, custom: true, backup: "C:\\Users\\demo\\.claude-cage\\state" };
86新增: state.status.storage_recovery = { required: false, repair_allowed: false };
87新增: state.status.job = { ...state.status.job, running: false, error: "", message: "环境存储已恢复,可以启动环境" };
88新增: await panel.getByText(location.directory, { exact: true }).waitFor();
89新增: await page.waitForFunction(() => !document.querySelector(".environment-storage input")?.disabled);
90新增: assert.equal(await retry.count(), 0);
91新增: await page.getByRole("button", { name: "返回工作台", exact: true }).first().click();
92新增: await page.getByRole("button", { name: "启动 Cage 环境", exact: true }).click();
93新增: await page.waitForFunction(() => document.querySelector(".welcome h1")?.textContent === "Cage 环境已就绪");
94新增: assert.equal(state.requests.filter(request => request.path === "/start").length, 1);
95新增: assert.deepEqual(errors, []);
96新增: console.log(`Storage recovery login, settings, failure cause, duplicate rejection, diagnostics, repair, preparation and normal start passed (${page.viewportSize().width}px)`);
97新增:} finally { await browser.close(); }
修改ui/src/api.js+1 −0看文件
@@ -8,6 +8,7 @@ async function responseError(response, path, method = "GET") {
88 httpErrorMessage(path, response.status, await response.text(), response.headers.get("Content-Type") || "", method),
99 );
1010 error.status = response.status;
11新增: error.recovery = response.headers.get("X-Cage-Recovery") || "";
1112 return error;
1213}
1314async function renewSession() {
修改ui/src/browser-downloads.jsx+22 −1看文件
@@ -16,6 +16,7 @@ import {
1616} from "lucide-react";
1717import { api, native, nativeAvailable } from "./api";
1818import {
19新增: assertConnection,
1920 getClientContext,
2021 isRemoteClient,
2122 runtimeURL,
@@ -88,6 +89,7 @@ export function useDesktopFiles(ready, onStatus) {
8889 let disposed = false,
8990 timer,
9091 failures = 0;
92新增: const handled = new Set();
9193 const poll = async () => {
9294 try {
9395 const value = await api("/input/files/desktop/requests");
@@ -97,7 +99,26 @@ export function useDesktopFiles(ready, onStatus) {
9799 uploads: value.uploads || [],
98100 downloads: value.downloads || [],
99101 });
100删除:
102新增: for (const request of value.opens || []) {
103新增: if (disposed || handled.has(request.id)) continue;
104新增: handled.add(request.id);
105新增: try {
106新增: assertConnection(connection);
107新增: if (!nativeAvailable()) {
108新增: await api("/input/files/desktop/open", {
109新增: id: request.id,
110新增: stage: "complete",
111新增: error: "请在 Cage 桌面应用中打开文件",
112新增: });
113新增: throw new Error(
114新增: "请在 Cage 桌面应用中打开文件,或从下载列表保存文件",
115新增: );
116新增: }
117新增: await native("desktopFileAction", { id: request.id });
118新增: } catch (error) {
119新增: if (!disposed) status.current?.(error.message);
120新增: }
121新增: }
101122 } catch (error) {
102123 // Closing Desktop invalidates its outstanding file choosers.
103124 if (!disposed) {
修改ui/src/environment-storage.jsx+33 −9看文件
@@ -10,25 +10,27 @@ export function EnvironmentStorage({ status, onConfirm }) {
1010 const [submitting, setSubmitting] = useState(false);
1111 const [error, setError] = useState("");
1212 const job = status.job;
13新增: const recovery = status.storage_recovery?.required ? status.storage_recovery : location?.recovery;
14新增: const storageJob = job?.kind === "storage" || job?.kind === "storage-recovery";
1315 const busy = submitting || Boolean(pending) || Boolean(job?.running);
1416 useEffect(() => {
1517 let live = true;
1618 if (pending && job?.id === pending.previousJob) return;
17删除: if (job?.kind === "storage" && job.running) return;
19新增: if (storageJob && job.running) return;
1820 api("/environment/storage").then((next) => {
1921 if (!live) return;
2022 setLocation(next);
2123 if (pending) {
2224 setPending(null);
2325 if (job?.id === pending.id && job.error) setError(job.error);
24删除: else if (job?.id === pending.id || next.directory === pending.path) { setDirectory(""); setError(""); }
26新增: else if (job?.id === pending.id || next.directory && next.directory === pending.path) { setDirectory(""); setError(""); }
2527 else setError("操作已结束,请核对当前环境目录后重试。");
2628 }
2729 }).catch((e) => {
2830 if (live) { setError(e.message); setPending(null); }
2931 });
3032 return () => { live = false; };
31删除: }, [pending, job?.id, job?.running]);
33新增: }, [pending, job?.id, job?.running, storageJob, status.storage_recovery?.required]);
3234
3335 const choose = async () => {
3436 setError("");
@@ -38,7 +40,7 @@ export function EnvironmentStorage({ status, onConfirm }) {
3840 } catch { setError("未能选择文件夹,请直接填写绝对路径。"); }
3941 };
4042 const apply = async () => {
41删除: if (!location || busy) return;
43新增: if (!location?.directory || busy || recovery?.required) return;
4244 const path = directory.trim();
4345 if (location.has_environment && !(await onConfirm({
4446 title: "迁移本机环境?",
@@ -55,22 +57,44 @@ export function EnvironmentStorage({ status, onConfirm }) {
5557 } catch (e) { setError(e.message); }
5658 finally { setSubmitting(false); }
5759 };
60新增: const recover = async (repair) => {
61新增: if (busy) return;
62新增: setSubmitting(true);
63新增: setError("");
64新增: try {
65新增: const accepted = await api("/environment/storage/recover", { repair });
66新增: setPending({ id: accepted.id, previousJob: job?.id });
67新增: } catch (e) { setError(e.message); }
68新增: finally { setSubmitting(false); }
69新增: };
5870 return <section className="environment-versions environment-storage" aria-label="本机环境存储">
5971 <h4>本机环境存储</h4>
72新增: {recovery?.required ? <>
73新增: <p className="field-help">环境存储需要恢复。请连接迁移使用的磁盘后重试。恢复完成后可以启动环境。</p>
74新增: <p role="alert" className="error-message"><SafetyMessage message={recovery.error} /></p>
75新增: <div className="storage-actions">
76新增: <button type="button" disabled={busy} onClick={() => recover(false)}>重试恢复</button>
77新增: {recovery.repair_allowed && <button type="button" disabled={busy} onClick={() => recover(true)}>修复系统助手并恢复</button>}
78新增: </div>
79新增: {recovery.repair_allowed && <p className="field-help storage-repair-help">修复系统助手需要 Windows 系统授权。完成后会继续恢复原环境。</p>}
80新增: </> : <>
6081 <p className="field-help">系统镜像、下载缓存和虚拟磁盘可以放在另一块本地磁盘。项目文件保存在各自的项目文件夹。</p>
6182 <div className="setting-summary-row"><span>当前环境目录</span><strong>{location?.directory || "正在读取…"}</strong></div>
83新增: {status.environment_identity_directory && status.environment_identity_directory !== status.environment_directory &&
84新增: <p className="field-help">升级前的默认项目文件位于 <code>{status.environment_identity_directory}</code>,当前默认项目位于 <code>{status.environment_directory}</code>。如需使用旧目录中的项目,请在主机文件管理器中将项目移到 Cage 配置目录之外,再从工作台打开。</p>}
6285 {location?.backup && <p className="field-help">迁移前的备份保存在 <code>{location.backup}</code>。确认新环境能正常启动、文件和登录状态齐全后,可自行清理备份。</p>}
6386 <label>新存储位置
6487 <input value={directory} onChange={(e) => { setDirectory(e.target.value); setError(""); }} spellCheck="false"
65删除: disabled={busy || !location} placeholder="本地磁盘上专用空文件夹的完整路径" />
88新增: disabled={busy || !location?.directory} placeholder="本地磁盘上专用空文件夹的完整路径" />
6689 </label>
6790 <div className="storage-actions">
68删除: {nativeAvailable() && <button type="button" disabled={busy || !location} onClick={choose}><FolderOpen size={15} />选择文件夹</button>}
69删除: <button type="button" disabled={busy || !location || !directory.trim() || directory.trim() === location.directory} onClick={apply}>
91新增: {nativeAvailable() && <button type="button" disabled={busy || !location?.directory} onClick={choose}><FolderOpen size={15} />选择文件夹</button>}
92新增: <button type="button" disabled={busy || !location?.directory || !directory.trim() || directory.trim() === location.directory} onClick={apply}>
7093 {location?.has_environment ? "迁移到此位置" : "使用此位置"}
7194 </button>
7295 </div>
73删除: {job?.kind === "storage" && job.running && <p role="status" className="field-help">{job.message}</p>}
74删除: {error && <p role="alert" className="error-message"><SafetyMessage message={error} /></p>}
96新增: </>}
97新增: {storageJob && job.running && <p role="status" className="field-help">{job.message}</p>}
98新增: {error && error !== recovery?.error && <p role="alert" className="error-message"><SafetyMessage message={error} /></p>}
7599 </section>;
76100}
修改ui/src/image-transfer.js+5 −5看文件
@@ -90,15 +90,15 @@ export function prepareClipboardPaste(target, id, { windowTarget, valid = () =>
9090 let disposed = false, sent = false;
9191 const destination = { target, id, pid: windowTarget?.pid, window: windowTarget?.window };
9292 const check = () => {
93删除: if (disposed || !valid()) throw new Error("图片接收位置已切换,请重新粘贴");
93新增: if (disposed || !valid()) throw new Error("粘贴接收位置已切换,请重新粘贴");
9494 };
9595 const prepared = api("/input/paste/start", destination).then(result => {
9696 if (result?.available !== true || typeof result.transfer !== "string" && typeof result.context !== "string")
97删除: throw new Error("客机尚未确认图片接收位置,请同步环境组件后重试");
97新增: throw new Error("客机尚未确认粘贴接收位置,请同步环境组件后重试");
9898 return { transfer: result.transfer, context: result.context };
9999 });
100删除: // The clipboard can turn out to contain text or files. The image-specific
101删除: // preparation error is observed only when this gesture supplies an image.
100新增: // Source reading starts independently. A sender using this binding observes
101新增: // preparation errors, and every content path disposes its preparation.
102102 void prepared.catch(() => {});
103103 const dispose = () => {
104104 if (disposed) return;
@@ -110,7 +110,7 @@ export function prepareClipboardPaste(target, id, { windowTarget, valid = () =>
110110 check();
111111 const binding = await prepared;
112112 check();
113删除: if (sent) throw new Error("本次图片已经提交,请核对接收结果");
113新增: if (sent) throw new Error("本次粘贴已经提交,请核对接收结果");
114114 sent = true;
115115 try { return await api(typeof payload.text === "string" ? "/input/text" : "/input/image", { ...payload, ...destination, ...binding }); }
116116 finally { dispose(); }
修改ui/src/macos-login.css+7 −0看文件
@@ -136,3 +136,10 @@
136136.mac-first-setup li + li { margin-top: 10px; }
137137.mac-setup-hint p { margin: 0; }
138138.mac-setup-hint p + p { margin-top: 4px; }
139新增:.mac-login-fullscreen[data-mode="maintenance"] { display: grid; place-items: center; padding: 16px; background: #0008; }
140新增:[data-mode="maintenance"] .mac-login-panel { position: relative; inset: auto; display: flex; flex-direction: column; width: min(1100px, 100%); height: min(900px, calc(100dvh - 32px)); overflow: hidden; border: 1px solid #ffffff32; border-radius: 16px; background: #17191e; }
141新增:[data-mode="maintenance"] .mac-login-tools { position: relative; inset: auto; align-self: flex-start; flex-shrink: 0; margin: 0 12px 8px; box-shadow: none; }
142新增:[data-mode="maintenance"] .mac-login-stage { position: relative; flex: 1; min-height: 0; overflow: hidden; }
143新增:[data-mode="maintenance"] .mac-setup-hint { position: relative; inset: auto; pointer-events: auto; margin: 0 12px 8px; }
144新增:[data-mode="maintenance"] .mac-login-status { position: relative; inset: auto; flex-shrink: 0; margin: 8px 12px; }
145新增:.project-recovery-actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
修改ui/src/macos-login.jsx+81 −42看文件
@@ -75,18 +75,23 @@ const setupKeys = {ArrowLeft:123, ArrowRight:124, ArrowDown:125, ArrowUp:126, Pa
7575const guestWidth = 1024;
7676const guestHeight = 640;
7777
78删除:function closeSession(session, endpoint) {
79删除: if (session) api(endpoint, { action: "close", session }).catch(() => {});
78新增:function closeSession(session, endpoint, maintenance) {
79新增: if (session) api(endpoint, { action: "close", session, ...(maintenance ? { maintenance } : {}) }).catch(() => {});
8080}
8181
82删除:export function MacOSLogin({ disabled, initialSetup = false, setupActions, setupHint, setupStatus, setupError, autoOpen = false, managedCredential = false }) {
83删除: const endpoint = initialSetup ? "/macos/first-setup" : "/macos/login";
82新增:export function MacOSLogin({ disabled, initialSetup = false, maintenance = "", label, setupActions, setupHint, setupStatus, setupError, autoOpen = false, managedCredential = false, onSessionClosed, onSettings }) {
83新增: const endpoint = initialSetup ? "/macos/first-setup" : maintenance ? "/macos/maintenance" : "/macos/login";
84新增: const scope = maintenance ? { maintenance } : {};
8485 const [opened, setOpened] = useState(false);
8586 const [session, setSession] = useState("");
8687 const [frame, setFrame] = useState("");
8788 const [message, setMessage] = useState("");
89新增: const [frameError, setFrameError] = useState("");
90新增: const [recovery, setRecovery] = useState("");
91新增: const [administrator, setAdministrator] = useState("");
92新增: const [frameTarget, setFrameTarget] = useState(null);
8893 const [authorizationPassword, setAuthorizationPassword] = useState("");
89删除: const [zoomed, setZoomed] = useState(!initialSetup);
94新增: const [zoomed, setZoomed] = useState(!initialSetup && !maintenance);
9095 const [size, setSize] = useState({ width: 0, height: 0 });
9196 const [aspect, setAspect] = useState(guestWidth / guestHeight);
9297 const lease = useRef(null);
@@ -99,24 +104,29 @@ export function MacOSLogin({ disabled, initialSetup = false, setupActions, setup
99104 const drag = useRef(null);
100105 const dragged = useRef(false);
101106 const autoOpened = useRef(false);
107新增: const shown = useRef({ region: [0, 0, guestWidth, guestHeight], geometry: "" });
102108
103109 const fitWidth = Math.min(size.width, size.height * aspect);
104110 // Keep a 320 × 200 logical region around the account controls visible.
105删除: const imageWidth = !zoomed ? fitWidth : initialSetup ? fitWidth * 2 :
111新增: const imageWidth = !zoomed ? fitWidth : initialSetup || maintenance ? fitWidth * 2 :
106112 Math.min(size.width * guestWidth / 320, size.height * aspect * guestHeight / 200);
107113 const imageHeight = imageWidth / aspect;
108114 const hasFrame = Boolean(frame);
115新增: const visibleMessage = message || frameError;
109116
110117 function end(show = "") {
111118 if (!lease.current) return;
112119 const old = lease.current;
113120 lease.current = null;
114删除: closeSession(old.session, endpoint);
121新增: closeSession(old.session, endpoint, maintenance);
115122 setOpened(false);
116123 setSession("");
117124 setFrame("");
125新增: setFrameTarget(null);
126新增: shown.current = { region: [0, 0, guestWidth, guestHeight], geometry: "" };
118127 setAuthorizationPassword("");
119128 setMessage(show);
129新增: setFrameError("");
120130 }
121131
122132 async function open() {
@@ -125,15 +135,18 @@ export function MacOSLogin({ disabled, initialSetup = false, setupActions, setup
125135 lease.current = next;
126136 chain.current = Promise.resolve();
127137 setMessage("");
128删除: setZoomed(!initialSetup);
138新增: setFrameError("");
139新增: setRecovery("");
140新增: setZoomed(!initialSetup && !maintenance);
129141 setOpened(true);
130142 try {
131删除: const r = await api(endpoint, { action: "open" });
143新增: const r = await api(endpoint, { action: "open", ...scope });
132144 if (lease.current !== next) {
133删除: closeSession(r.session, endpoint);
145新增: closeSession(r.session, endpoint, maintenance);
134146 return;
135147 }
136删除: if (!r.session) throw new Error(r.error || "暂时无法打开客机登录界面");
148新增: if (!r.session) { setRecovery(r.recovery || ""); throw new Error(r.error || "暂时无法打开客机登录界面"); }
149新增: setAdministrator(r.administrator || "");
137150 next.session = r.session;
138151 setSession(r.session);
139152 } catch (e) {
@@ -156,7 +169,7 @@ export function MacOSLogin({ disabled, initialSetup = false, setupActions, setup
156169
157170 useEffect(() => () => {
158171 if (lease.current) {
159删除: closeSession(lease.current.session, endpoint);
172新增: closeSession(lease.current.session, endpoint, maintenance);
160173 lease.current = null;
161174 }
162175 }, []);
@@ -193,7 +206,7 @@ export function MacOSLogin({ disabled, initialSetup = false, setupActions, setup
193206 useLayoutEffect(() => {
194207 if (!opened || !stage.current) return;
195208 stage.current.scrollLeft = zoomed ? Math.max(0, (imageWidth - size.width) / 2) : 0;
196删除: stage.current.scrollTop = zoomed ? Math.max(0, imageHeight * 0.85 - size.height * 0.5) : 0;
209新增: stage.current.scrollTop = zoomed ? Math.max(0, imageHeight * (maintenance ? 0.5 : 0.85) - size.height * 0.5) : 0;
197210 }, [opened, hasFrame, zoomed, imageWidth, imageHeight, size.width, size.height]);
198211
199212 useEffect(() => {
@@ -202,11 +215,17 @@ export function MacOSLogin({ disabled, initialSetup = false, setupActions, setup
202215 let alive = true;
203216 const poll = async () => {
204217 try {
205删除: const r = await api(endpoint, { action: "frame", session });
218新增: const r = await api(endpoint, { action: "frame", session, ...scope });
206219 if (!alive || lease.current?.session !== session) return;
207删除: if (r.closed) return end();
208删除: if (r.image) setFrame(`data:${r.mime === "image/jpeg" ? "image/jpeg" : "image/png"};base64,${r.image}`);
209删除: if (r.error) setMessage(r.error);
220新增: if (r.closed) { setRecovery(r.recovery || ""); end(r.error || ""); onSessionClosed?.(); return; }
221新增: if (r.image) {
222新增: if (maintenance && (!r.geometry || !Array.isArray(r.region) || r.region.length !== 4 || !r.region.every(Number.isInteger)))
223新增: throw new Error("客机维护画面缺少窗口定位,请更新组件后重试");
224新增: setFrameTarget(maintenance ? { geometry: r.geometry, region: r.region } : null);
225新增: setFrame(`data:${r.mime === "image/jpeg" ? "image/jpeg" : "image/png"};base64,${r.image}`);
226新增: setFrameError("");
227新增: }
228新增: if (r.error) setFrameError(r.error);
210229 timer = setTimeout(poll, 550);
211230 } catch (e) {
212231 if (alive && lease.current?.session === session) end(e.message);
@@ -219,12 +238,14 @@ export function MacOSLogin({ disabled, initialSetup = false, setupActions, setup
219238 function enqueue(action, data) {
220239 const owner = lease.current;
221240 if (!owner?.session) return;
241新增: const geometry = shown.current.geometry;
242新增: if (maintenance && !geometry) { setMessage("请等待授权窗口画面后再操作"); return; }
222243 chain.current = chain.current.then(async () => {
223244 if (lease.current !== owner) return;
224删除: const r = await api(endpoint, { action, session: owner.session, ...data });
245新增: const r = await api(endpoint, { action, session: owner.session, ...scope, ...(maintenance ? { geometry } : {}), ...data });
225246 if (lease.current !== owner) return;
226删除: if (r.closed) end();
227删除: else if (r.error) setMessage(r.error);
247新增: if (r.closed) { end(r.error || ""); onSessionClosed?.(); }
248新增: else setMessage(r.error || "");
228249 }).catch((e) => { if (lease.current === owner) end(e.message); });
229250 }
230251
@@ -234,14 +255,18 @@ export function MacOSLogin({ disabled, initialSetup = false, setupActions, setup
234255 if (!rect || !rect.width || !rect.height || e.clientX < rect.left || e.clientX >= rect.right ||
235256 e.clientY < rect.top || e.clientY >= rect.bottom) return;
236257 keyboard.current?.focus({ preventScroll: true });
258新增: const [x, y, width, height] = shown.current.region;
237259 enqueue("click", {
238删除: x: Math.floor((e.clientX - rect.left) * guestWidth / rect.width),
239删除: y: Math.floor((e.clientY - rect.top) * guestHeight / rect.height),
260新增: x: x + Math.floor((e.clientX - rect.left) * width / rect.width),
261新增: y: y + Math.floor((e.clientY - rect.top) * height / rect.height),
240262 });
241263 }
242264
243265 function guestKey(e) {
244删除: const code = keys[e.code] ?? (initialSetup ? setupKeys[e.code] : undefined);
266新增: if (maintenance && (e.metaKey || e.ctrlKey) && !e.altKey && e.code === "KeyA") {
267新增: e.preventDefault(); enqueue("select-all", {}); return;
268新增: }
269新增: const code = keys[e.code] ?? (initialSetup || maintenance ? setupKeys[e.code] : undefined);
245270 if (e.metaKey || e.ctrlKey || e.altKey || code === undefined) return;
246271 e.preventDefault();
247272 enqueue("key", { code, shift: e.shiftKey });
@@ -249,7 +274,7 @@ export function MacOSLogin({ disabled, initialSetup = false, setupActions, setup
249274
250275 useEffect(() => {
251276 const element = stage.current;
252删除: if (!opened || !initialSetup || !element) return;
277新增: if (!opened || (!initialSetup && !maintenance) || !element) return;
253278 const scroll = (event) => {
254279 const rect = imageRef.current?.getBoundingClientRect();
255280 if (!rect?.width || !rect.height || event.clientX < rect.left || event.clientX >= rect.right ||
@@ -257,16 +282,17 @@ export function MacOSLogin({ disabled, initialSetup = false, setupActions, setup
257282 event.preventDefault();
258283 const unit = event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? rect.height : 1;
259284 const bounded = (delta, scale) => Math.max(-512, Math.min(512, Math.round(delta * unit * scale)));
285新增: const [x, y, width, height] = shown.current.region;
260286 enqueue("scroll", {
261删除: x: Math.floor((event.clientX - rect.left) * guestWidth / rect.width),
262删除: y: Math.floor((event.clientY - rect.top) * guestHeight / rect.height),
263删除: delta_x: bounded(event.deltaX, guestWidth / rect.width),
264删除: delta_y: bounded(event.deltaY, guestHeight / rect.height),
287新增: x: x + Math.floor((event.clientX - rect.left) * width / rect.width),
288新增: y: y + Math.floor((event.clientY - rect.top) * height / rect.height),
289新增: delta_x: bounded(event.deltaX, width / rect.width),
290新增: delta_y: bounded(event.deltaY, height / rect.height),
265291 });
266292 };
267293 element.addEventListener("wheel", scroll, { passive: false });
268294 return () => element.removeEventListener("wheel", scroll);
269删除: }, [opened, initialSetup, session]);
295新增: }, [opened, initialSetup, maintenance, session]);
270296
271297 function changeZoom(zoom) {
272298 setZoomed(zoom);
@@ -274,10 +300,12 @@ export function MacOSLogin({ disabled, initialSetup = false, setupActions, setup
274300 }
275301
276302 return <>
277删除: <button ref={opener} disabled={disabled || opened} onClick={open}>{initialSetup ? "打开客机系统设置" : "登录客机账户"}</button>
303新增: <button type="button" ref={opener} disabled={disabled || opened} onClick={open}>{label || (initialSetup ? "打开客机系统设置" : maintenance ? "打开客机授权设置" : "登录客机账户")}</button>
278304 {!opened && message && <span role="status">{message}</span>}
305新增: {!opened && ["environment-update", "environment-restart"].includes(recovery) && onSettings &&
306新增: <button type="button" onClick={onSettings}>{recovery === "environment-update" ? "查看环境组件" : "打开环境设置"}</button>}
279307 {opened && createPortal(
280删除: <div className="mac-login-fullscreen" data-mode={initialSetup ? "setup" : "login"} role="dialog" aria-modal="true" aria-label={initialSetup ? "首次设置虚拟 Mac" : "登录虚拟 Mac"}
308新增: <div className="mac-login-fullscreen" data-mode={initialSetup ? "setup" : maintenance ? "maintenance" : "login"} role="dialog" aria-modal="true" aria-label={initialSetup ? "首次设置虚拟 Mac" : maintenance ? "恢复客机系统权限" : "登录虚拟 Mac"}
281309 onKeyDownCapture={(e) => {
282310 if (e.key === "F6") {
283311 e.preventDefault();
@@ -292,21 +320,31 @@ export function MacOSLogin({ disabled, initialSetup = false, setupActions, setup
292320 }}>
293321 <div className="mac-login-panel">
294322 {!initialSetup && <header className="mac-login-heading">
295删除: <h2>登录 macOS 客机</h2>
296删除: <p>输入客机账户密码,按回车登录。</p>
323新增: <h2>{maintenance ? "恢复客机系统权限" : "登录 macOS 客机"}</h2>
324新增: <p>{maintenance ? "在当前系统设置窗口中完成授权。切换到其他客机应用或锁定后,画面会结束。" : "输入客机账户密码,按回车登录。"}</p>
297325 </header>}
298326 <div className="mac-login-tools" role="toolbar" aria-label="画面工具">
299327 <button ref={back} onClick={() => end()}><ArrowLeft size={16} aria-hidden="true" />{initialSetup ? "返回设置指引" : "返回工作台"}</button>
300删除: <button aria-pressed={!zoomed} onClick={() => changeZoom(false)}><Maximize size={16} aria-hidden="true" />{initialSetup ? "适配" : "完整画面"}</button>
301删除: <button aria-pressed={zoomed} onClick={() => changeZoom(true)}><ZoomIn size={16} aria-hidden="true" />{initialSetup ? "放大" : "登录区域"}</button>
328新增: <button aria-pressed={!zoomed} onClick={() => changeZoom(false)}><Maximize size={16} aria-hidden="true" />{initialSetup || maintenance ? "适配" : "完整画面"}</button>
329新增: <button aria-pressed={zoomed} onClick={() => changeZoom(true)}><ZoomIn size={16} aria-hidden="true" />{initialSetup || maintenance ? "放大" : "登录区域"}</button>
302330 {initialSetup && setupActions}
303331 {initialSetup && managedCredential && <button disabled={!session} onClick={() => enqueue("fill-password",{})}>填写授权密码</button>}
304删除: {(!initialSetup || managedCredential) && <button onClick={async () => {
305删除: try { const result = await api(endpoint,{action:"show-password"}); setAuthorizationPassword(result.password); }
306删除: catch (e) { setMessage(e.message); }
332新增: {!maintenance && (!initialSetup || managedCredential) && <button onClick={async () => {
333新增: const owner = lease.current;
334新增: try {
335新增: const result = await api(endpoint,{action:"show-password"});
336新增: if (lease.current !== owner) return;
337新增: setAuthorizationPassword(result.password); setMessage("");
338新增: }
339新增: catch (e) { if (lease.current === owner) setMessage(e.message); }
307340 }}>{initialSetup ? "查看授权密码" : "查看客机密码"}</button>}
308341 {authorizationPassword && <span className="mac-login-password">{authorizationPassword}<button onClick={() => setAuthorizationPassword("")}>隐藏</button></span>}
309342 </div>
343新增: {maintenance && <div className="mac-setup-hint">
344新增: {maintenance === "projects" && <p>进入「文件系统扩展」,同时启用 macFUSE 和 macFUSE (local)。授权后 Cage 会自动检查并重新连接项目。</p>}
345新增: {administrator && <p>系统要求管理员时,用户名填写 {administrator}。选中系统授权窗口的密码框后,点击「填写管理员密码」,再由你确认授权。</p>}
346新增: {administrator && <button type="button" onClick={() => enqueue("fill-password", {})}>填写管理员密码</button>}
347新增: </div>}
310348 {initialSetup && setupHint && <div className="mac-setup-hint">
311349 <p>{setupHint}</p>
312350 <p role={setupError ? "alert" : "status"}>{setupStatus} 查看完整步骤或进入工作台时,点击「返回设置指引」。</p>
@@ -353,17 +391,18 @@ export function MacOSLogin({ disabled, initialSetup = false, setupActions, setup
353391 {frame && <div className="mac-login-canvas" style={{
354392 width: Math.max(size.width, imageWidth), height: Math.max(size.height, imageHeight),
355393 }}>
356删除: <img ref={imageRef} alt={initialSetup ? "Apple 客机首次系统设置" : "Apple 客机登录屏幕"} draggable={false} src={frame}
394新增: <img ref={imageRef} key={maintenance ? frameTarget?.geometry : undefined} alt={initialSetup ? "Apple 客机首次系统设置" : maintenance ? "客机系统设置或授权窗口" : "Apple 客机登录屏幕"} draggable={false} src={frame}
357395 style={{ width: imageWidth, height: imageHeight }}
358396 onLoad={(e) => {
359397 if (e.currentTarget.naturalHeight) setAspect(e.currentTarget.naturalWidth / e.currentTarget.naturalHeight);
398新增: if (maintenance && frameTarget) shown.current = frameTarget;
360399 }} onClick={sendClick} />
361400 </div>}
362401 </div>
363删除: {(message || !frame) && <p className="mac-login-status" role={message ? "alert" : "status"}>
364删除: {message || (initialSetup ? "正在读取客机首次设置画面…" : "正在确认客机登录画面…")}
402新增: {(visibleMessage || !frame) && <p className="mac-login-status" role={visibleMessage ? "alert" : "status"}>
403新增: {visibleMessage || (initialSetup ? "正在读取客机首次设置画面…" : maintenance ? "正在确认系统授权窗口…" : "正在确认客机登录画面…")}
365404 </p>}
366删除: {!initialSetup && <p className="mac-login-help">拖动画面可查看其他账户或提示</p>}
405新增: {!initialSetup && !maintenance && <p className="mac-login-help">拖动画面可查看其他账户或提示</p>}
367406 </div>
368407 </div>, document.body)}
369408 </>;
修改ui/src/macos-project-approval.jsx+7 −1看文件
@@ -1,6 +1,7 @@
11import React, { useEffect, useRef, useState } from "react";
22import { api } from "./api";
33import { Modal } from "./modal";
4新增:import { MacOSLogin } from "./macos-login";
45import "./macos-project-approval.css";
56
67const permissionMessages = {
@@ -9,11 +10,12 @@ const permissionMessages = {
910 requires_gui_login: "请先登录并解锁虚拟 Mac 的普通账户,然后重新打开项目。",
1011};
1112
12删除:export function MacOSProjectApproval({ pending, onCheck, onClose }) {
13新增:export function MacOSProjectApproval({ pending, onCheck, onClose, onSettings }) {
1314 const [frame, setFrame] = useState(null),
1415 [notice, setNotice] = useState("");
1516 const [busy, setBusy] = useState(false);
1617 const [actionError, setActionError] = useState("");
18新增: const [maintenance, setMaintenance] = useState("");
1719 const active = useRef(false),
1820 inFlight = useRef(null);
1921 const call = (action, fields = {}) =>
@@ -34,6 +36,8 @@ export function MacOSProjectApproval({ pending, onCheck, onClose }) {
3436 inFlight.current = request;
3537 const result = await request;
3638 if (live && !active.current) {
39新增: if (result.error === "project_screen_permission") setMaintenance("screen");
40新增: if (result.error === "accessibility_permission") setMaintenance("input");
3741 const valid = Boolean(
3842 !result.error &&
3943 result.image &&
@@ -104,6 +108,7 @@ export function MacOSProjectApproval({ pending, onCheck, onClose }) {
104108 y,
105109 });
106110 setFrame(null);
111新增: if (result.error === "accessibility_permission") setMaintenance("input");
107112 if (result.error) throw new Error(permissionMessages[result.error] || "客机授权窗口已变化,请等待新画面。");
108113 await onCheck();
109114 });
@@ -135,6 +140,7 @@ export function MacOSProjectApproval({ pending, onCheck, onClose }) {
135140 />
136141 )}
137142 {notice && <p role="status">{notice}</p>}
143新增: {maintenance && <MacOSLogin maintenance={maintenance} onSettings={onSettings} onSessionClosed={() => void act(onCheck)} />}
138144 {actionError && <p role="alert">{actionError}</p>}
139145 </Modal>
140146 );
修改ui/src/main.jsx+34 −13看文件
@@ -32,6 +32,7 @@ import { TerminalMenu } from "./terminal-menu";
3232import { InitializationGate } from "./initialization";
3333import { MacOSLogin } from "./macos-login";
3434import { MacOSClaudeWindow } from "./macos-claude-window";
35新增:import { ProjectRecovery } from "./project-recovery";
3536import { ClaudeDesktop } from "./claude-desktop";
3637import { useClaudeAccounts } from "./claude-accounts";
3738import { AccountProvider, AccountGate, useAccount } from "./account";
@@ -140,12 +141,21 @@ function App() {
140141 quitAfterStop = useRef(null);
141142 activeRef.current = active;
142143 readyRef.current = Boolean(status?.ready);
144新增: const storageRecovery = status?.storage_recovery?.required;
143145 const current = tabs.find((t) => t.id === active),
144146 terminal = !desktopOpen && current?.kind === "terminal",
145147 busy = Boolean(status?.job?.running),
146删除: showHome = !desktopOpen && (home || !status?.vm_running || !current);
148新增: showHome = storageRecovery || !desktopOpen && (home || !status?.vm_running || !current);
147149 const setupProgress = status?.job?.setup_progress && (busy || status.job.error);
148删除: const cliSessions = useCLISessions(Boolean(status && !busy), windowVisible);
150新增: const cliSessions = useCLISessions(Boolean(status && !busy && !storageRecovery), windowVisible);
151新增: useEffect(() => {
152新增: if (storageRecovery) {
153新增: setDesktopOpen(false);
154新增: setHome(true);
155新增: setStartOptions(null);
156新增: setStartRequest(null);
157新增: }
158新增: }, [storageRecovery]);
149159 const other = tabs.find(tab => tab.id === layout.other);
150160 const split = Boolean(other && current && !showHome && !desktopOpen);
151161 const panes = !split ? [current].filter(Boolean)
@@ -240,7 +250,7 @@ function App() {
240250 useEffect(() => {
241251 if (finishedLogins) claudeProfiles.load();
242252 }, [finishedLogins, claudeProfiles.load]);
243删除: const audio = useAudioOutput(running && !status?.environment_update_required && !connectionError);
253新增: const audio = useAudioOutput(running && !storageRecovery && !status?.environment_update_required && !connectionError);
244254 useEffect(() => {
245255 if (audio.error) setToast(audio.error);
246256 }, [audio.error]);
@@ -639,7 +649,7 @@ function App() {
639649 ]);
640650 if (!live) return;
641651 const b = browserResult || browserSnapshot.current;
642删除: const legacyMetadata = readLocal(clientStorageKey("cage-tab-layout"), {})[next.environment_directory || next.workspace] || {};
652新增: const legacyMetadata = readLocal(clientStorageKey("cage-tab-layout"), {})[next.environment_identity_directory || next.environment_directory || next.workspace] || {};
643653 for (const item of t) {
644654 const saved = legacyMetadata["terminal:" + item.id];
645655 if (!item.cli_session_id || item.metadata_set || !saved || (!saved.title && !saved.pinned)) continue;
@@ -940,6 +950,10 @@ function App() {
940950 if (!projectDialog && !rename && !dialog) openSettings();
941951 return;
942952 }
953新增: if (storageRecovery && ["openProject", "newTab", "newTerminal"].includes(command)) {
954新增: openSettings("project");
955新增: return;
956新增: }
943957 if (command === "openProject") {
944958 if (
945959 !busy &&
@@ -1034,7 +1048,7 @@ function App() {
10341048 terminalChoice,
10351049 ]);
10361050 const project = projectName(contentWorkspace, status?.environment_directory);
1037删除: const tabLayoutKey = status?.environment_directory || status?.workspace;
1051新增: const tabLayoutKey = status?.environment_identity_directory || status?.environment_directory || status?.workspace;
10381052 const metadata = { ...(savedTabs[tabLayoutKey] || {}), ...(privateTabMetadata[tabLayoutKey] || {}) };
10391053 for (const tab of tabs) {
10401054 if (tab.cli_session_id && tab.metadata_set) metadata[tab.id] = {
@@ -1318,7 +1332,7 @@ function App() {
13181332 saved={metadata}
13191333 active={active}
13201334 home={showHome}
1321删除: busy={busy}
1335新增: busy={busy || storageRecovery}
13221336 ready={status.ready}
13231337 running={running}
13241338 runtimeLabel={runtimeLabel}
@@ -1372,10 +1386,10 @@ function App() {
13721386 <main className={`workspace ${split ? "workspace-split" : ""}`} ref={workspaceBox}
13731387 style={{ "--split-left": `${100 * (dualBrowser && nativeSplit?.fraction || 0.5)}%` }}>
13741388 {dropSide && <div aria-hidden="true" className={`split-drop split-${dropSide}`}>{dropSide === "left" ? "放到左侧" : "放到右侧"}</div>}
1375删除: {desktopOpen && macGuest && <MacOSClaudeWindow uploads={desktopFiles.uploads} keyboard={status.keyboard} remoteRef={remote}
1389新增: {!storageRecovery && desktopOpen && macGuest && <MacOSClaudeWindow uploads={desktopFiles.uploads} keyboard={status.keyboard} remoteRef={remote}
13761390 onStatus={notify} onFallback={(text, message) => setTransfer({ text, message })} visible={!settingsOpen} onConfirm={confirm}
13771391 sidebarCollapsed={sidebarCollapsed} onExpand={() => persist("cage-sidebar-collapsed", false, setSidebarCollapsed)} />}
1378删除: {desktopOpen && !macGuest && <ClaudeDesktop
1392新增: {!storageRecovery && desktopOpen && !macGuest && <ClaudeDesktop
13791393 uploads={desktopFiles.uploads}
13801394 onProjectOpened={() => refreshStatus.current?.()}
13811395 status={status} visible={!settingsOpen} remoteRef={remote}
@@ -1390,7 +1404,7 @@ function App() {
13901404 <button onClick={() => openSettings("project")}>查看并更新</button>
13911405 </div>
13921406 )}
1393删除: {(status.vm_running || terminal) && (
1407新增: {!storageRecovery && (status.vm_running || terminal) && (
13941408 <>
13951409 {!desktopOpen && !showHome && webPanes.length > 0 && (
13961410 <section className={`pane-lane browser-lane ${browserTabLayout === "vertical" ? "vertical-browser" : ""} ${dualBrowser ? "" : "split-" + paneSide(webPanes[0].id)}`}>
@@ -1457,7 +1471,12 @@ function App() {
14571471 <div className="welcome">
14581472 <div className="welcome-content">
14591473 <img className="welcome-logo" src={logo} alt="Cage" />
1460删除: {setupProgress ? <>
1474新增: {storageRecovery ? <>
1475新增: <h1>环境存储需要恢复</h1>
1476新增: <p className="welcome-subtitle"><SafetyMessage message={status.storage_recovery.error} /></p>
1477新增: <p className="field-help">在设置中恢复环境存储后,再启动浏览器和终端。诊断包可以从同一页面导出。</p>
1478新增: <button className="primary" onClick={() => openSettings("project")}>恢复环境存储</button>
1479新增: </> : setupProgress ? <>
14611480 <h1>{status.job.error ? "环境安装未完成" : "正在安装 Cage 环境"}</h1>
14621481 <SetupProgress job={status.job} onDetails={() => setDetails(true)}
14631482 onStop={stop} onRetry={() => setStartOptions(status.job.kind === "guest-install" ? { guest_system: status.job.setup_progress.system } : {})} disconnected={Boolean(connectionError)} />
@@ -1629,19 +1648,20 @@ function App() {
16291648 <p>环境和浏览器可继续使用。</p>
16301649 {status.project_errors?.length ? (
16311650 <ul className="project-connection-errors">
1632删除: {status.project_errors.map(({ path, message }) => (
1651新增: {status.project_errors.map(({ path, message, recovery }) => (
16331652 <li key={path}>
16341653 <strong>{projectName(path, status.environment_directory)}</strong>
16351654 <span className="project-error-path">{path}</span>
16361655 <p>{message}</p>
1637删除: <button disabled={!status.ready || busy} onClick={() => setProjectDialog({ path })}>连接项目</button>
1656新增: <ProjectRecovery recovery={recovery} disabled={!status.ready || busy}
1657新增: onRetry={() => setProjectDialog({ path })} onSettings={() => openSettings("project")} />
16381658 </li>
16391659 ))}
16401660 </ul>
16411661 ) : <p>{status.project_error}</p>}
16421662 </div>
16431663 )}
1644删除: {!setupProgress && status.job?.error && (
1664新增: {!storageRecovery && !setupProgress && status.job?.error && (
16451665 <div className="start-error" role="alert">
16461666 <strong>{status.job.message || "本次操作未完成"}</strong>
16471667 <p><SafetyMessage message={status.job.error} /></p>
@@ -1761,6 +1781,7 @@ function App() {
17611781 status={status}
17621782 initialPath={projectDialog.path}
17631783 onClose={() => setProjectDialog(null)}
1784新增: onSettings={() => { setProjectDialog(null); openSettings("project"); }}
17641785 onOpened={openedProject}
17651786 />
17661787 )}
修改ui/src/project-dialog.jsx+9 −2看文件
@@ -5,6 +5,7 @@ import { api, native, nativeAvailable } from "./api";
55import { SafetyMessage } from "./safety-message";
66import { Modal } from "./views";
77import { MacOSProjectApproval } from "./macos-project-approval";
8新增:import { ProjectRecovery } from "./project-recovery";
89import { projectName, rememberClientProjectName } from "./workspace-state.mjs";
910import { getClientContext, isRemoteClient } from "./client-context.mjs";
1011
@@ -14,11 +15,13 @@ export function ProjectDialog({
1415 activate = true,
1516 onClose,
1617 onOpened,
18新增: onSettings,
1719}) {
1820 const projects = status.projects || [];
1921 const [adding, setAdding] = useState(Boolean(initialPath) || projects.length === 0);
2022 const [path, setPath] = useState(initialPath || status.workspace || projects[0] || "");
2123 const [error, setError] = useState("");
24新增: const [recovery, setRecovery] = useState("");
2225 const [pending, setPending] = useState(null);
2326 const [submitting, setSubmitting] = useState(false);
2427 const [directories, setDirectories] = useState(null);
@@ -91,10 +94,11 @@ export function ProjectDialog({
9194 else if (nativeAvailable()) void choose();
9295 };
9396 const open = async (event) => {
94删除: event.preventDefault();
97新增: event?.preventDefault();
9598 if (busy || sharing || !path.trim()) return;
9699 setSubmitting(true);
97100 setError("");
101新增: setRecovery("");
98102 try {
99103 const result = await api("/projects/open", {
100104 workspace: path.trim(),
@@ -105,11 +109,12 @@ export function ProjectDialog({
105109 else await onOpened(result.workspace);
106110 } catch (e) {
107111 setError(e.message);
112新增: setRecovery(e.recovery || "");
108113 } finally {
109114 setSubmitting(false);
110115 }
111116 };
112删除: if (pending) return <MacOSProjectApproval pending={pending} onClose={onClose} onCheck={async () => {
117新增: if (pending) return <MacOSProjectApproval pending={pending} onClose={onClose} onSettings={onSettings} onCheck={async () => {
113118 const result = await api("/projects/open", { workspace: pending.workspace, add: adding, activate });
114119 if (result.approval) {
115120 setPending({workspace: result.workspace, grant: result.approval});
@@ -219,6 +224,8 @@ export function ProjectDialog({
219224 {error && (
220225 <div className="error-message" role="alert">
221226 <SafetyMessage message={error} />
227新增: {recovery && <ProjectRecovery recovery={recovery} disabled={busy} onRetry={() => void open()}
228新增: onSettings={onSettings} onSessionClosed={() => void open()} />}
222229 </div>
223230 )}
224231 </form>
新增ui/src/project-recovery.jsx+15 −0看文件
@@ -0,0 +1,15 @@
1新增:import React from "react";
2新增:import { MacOSLogin } from "./macos-login";
3新增:
4新增:export function ProjectRecovery({ recovery, disabled, onRetry, onSettings, onSessionClosed }) {
5新增: return <div className="project-recovery-actions">
6新增: {recovery === "guest-login" && <MacOSLogin disabled={disabled} onSessionClosed={onSessionClosed} />}
7新增: {recovery === "filesystem-permission" && <MacOSLogin disabled={disabled} maintenance="projects"
8新增: onSessionClosed={onSessionClosed} onSettings={onSettings} />}
9新增: {["environment-update", "environment-restart"].includes(recovery) && onSettings &&
10新增: <button type="button" disabled={disabled} onClick={onSettings}>{recovery === "environment-update" ? "查看环境组件" : "打开环境设置"}</button>}
11新增: {recovery === "project-directory" && onSettings &&
12新增: <button type="button" disabled={disabled} onClick={onSettings}>查看诊断记录</button>}
13新增: <button type="button" disabled={disabled} onClick={onRetry}>{recovery === "project-approval" ? "完成项目授权" : "重新连接项目"}</button>
14新增: </div>;
15新增:}
修改ui/src/remote-input.js+15 −8看文件
@@ -313,12 +313,20 @@ export function installRemoteInput(
313313 await writeClipboard(content.text);
314314 }
315315 if (valid()) say("已复制到本机");
316删除: } catch {
316新增: } catch (error) {
317317 if (!valid()) return;
318318 if (typeof content.text === "string") onFallback(content.text, "请在这里复制到本机。");
319删除: else say("浏览器未允许写入图片剪贴板,请允许剪贴板访问后重试。");
319新增: else say(error.name === "NotAllowedError" ? "浏览器未允许写入图片剪贴板,请允许剪贴板访问后重试。" : error.message || "复制内容读取失败,请重试。");
320320 }
321321 };
322新增: const waitForCopy = () => {
323新增: if (!copyRequested) return;
324新增: clearTimeout(copyTimer);
325新增: copyTimer = setTimeout(() => {
326新增: copyRequested = false;
327新增: onFallback(lastText, "未收到新的选中文本,可在这里复制 Cage 剪贴板。");
328新增: }, 1600);
329新增: };
322330 const copy = (key = "c") => {
323331 if (disposed || !isActive()) return;
324332 copyRequested = true;
@@ -332,20 +340,19 @@ export function installRemoteInput(
332340 document.visibilityState !== "hidden" && document.hasFocus();
333341 return transport.runKeyAction(async sendKey => {
334342 const before = await caretRect?.();
335删除: const content = await copyText(async () => {
343新增: const sendCopy = async () => {
336344 if (!valid()) throw new Error("复制窗口已变化,请重新选择文本。");
337345 for (const value of shortcutKeys(key)) await sendKey(...value);
338删除: }, valid, { id, context, key });
346新增: };
347新增: const content = await copyText(sendCopy, valid, { id, context, key });
348新增: if (content === undefined) { await sendCopy(); waitForCopy(); return; }
339349 const after = await caretRect?.();
340350 if (before?.available && (!after?.available || before.context !== after.context)) throw new Error("复制位置已变化,请重新选择文本。");
341351 if (valid()) await receiveCopy({ ...content, id, context });
342352 }).catch(error => { if (valid()) say(error.message || "未收到新的选中文本,请重新选择后复制。"); });
343353 }
344354 chord(key);
345删除: copyTimer = setTimeout(() => {
346删除: copyRequested = false;
347删除: onFallback(lastText, "未收到新的选中文本,可在这里复制 Cage 剪贴板。");
348删除: }, 1600);
355新增: waitForCopy();
349356 };
350357 const paste = (text) => {
351358 if (disposed) return;
修改ui/src/remote-input.test.mjs+19 −0看文件
@@ -577,6 +577,25 @@ test("explicit desktop copy preserves the queued native copy keys", async () =>
577577 } finally { f.controller.dispose(); }
578578});
579579
580新增:test("a late browser capability can switch copying from native events to its private adapter", async () => {
581新增: let available = false;
582新增: const f = fixture(false, false, { copyText: () => available ? Promise.resolve({ text: "private copy" }) : undefined });
583新增: try {
584新增: await f.controller.copy();
585新增: assert.equal(f.keys.length, 4);
586新增: const event = new Event("clipboard");
587新增: event.detail = { text: "native event" };
588新增: f.rfb.dispatchEvent(event);
589新增: await new Promise(resolve => setImmediate(resolve));
590新增: assert.deepEqual(f.writes, ["native event"]);
591新增: available = true;
592新增: f.keys.length = 0;
593新增: await f.controller.copy();
594新增: assert.deepEqual(f.keys, []);
595新增: assert.deepEqual(f.writes, ["native event", "private copy"]);
596新增: } finally { f.controller.dispose(); }
597新增:});
598新增:
580599test("copied text supports two MiB in UTF-8 and rejects larger content", async () => {
581600 const f = fixture();
582601 try {
修改ui/src/settings.jsx+14 −4看文件
@@ -31,6 +31,7 @@ import { EnvironmentVersions } from "./environment-versions";
3131import { EnvironmentStorage } from "./environment-storage";
3232import { ResourceSettings } from "./resources";
3333import { DiagnosticSettings } from "./diagnostics.jsx";
34新增:import { MacOSLogin } from "./macos-login";
3435import { AccountSettings } from "./account";
3536import { ClaudeAccountsPanel } from "./claude-accounts";
3637const sections = [
@@ -94,7 +95,7 @@ export function SettingsPanel({
9495 : draft[k] !== current[k],
9596 );
9697 const busy =
97删除: Boolean(status.job?.running) || probing || submitting || Boolean(jobId);
98新增: Boolean(status.job?.running) || Boolean(status.storage_recovery?.required) || probing || submitting || Boolean(jobId);
9899 const update = (key, value) => {
99100 setDraft((p) => ({ ...p, [key]: value }));
100101 if (["dns_url"].includes(key)) setProbe(null);
@@ -251,7 +252,7 @@ export function SettingsPanel({
251252 await onClaudeLogin(id);
252253 onClose();
253254 }} />}
254删除: <fieldset className="settings-fields" disabled={busy}>
255新增: <fieldset className="settings-fields" disabled={busy && !(section === "project" && status.storage_recovery?.required)}>
255256 {section === "mobile" && (isRemoteClient()
256257 ? <section className="section-title"><h3>连接这台电脑</h3><p>请先切换到这台电脑的本机环境,再生成或管理手机配对码。</p></section>
257258 : <MobilePairSettings relay={draft.mobile_relay ?? ""} savedRelay={current.mobile_relay ?? ""} onChange={value => update("mobile_relay",value)} onConfirm={onConfirm} />)}
@@ -599,8 +600,17 @@ export function SettingsPanel({
599600 <p className="footnote">
600601 切换项目只改变新终端和文件编辑器的起始位置;已有终端、网页和登录态会保留。
601602 </p>
602删除: <EnvironmentVersions status={status} onConfirm={onConfirm} />
603删除: <ResourceSettings status={status} onConfirm={onConfirm} onDirtyChange={setResourceDirty} />
603新增: {!status.storage_recovery?.required && <EnvironmentVersions status={status} onConfirm={onConfirm} />}
604新增: {status.guest_system === "macos" && <section aria-label="客机系统权限">
605新增: <h4>客机系统权限</h4>
606新增: <p className="field-help">在受限的客机系统设置窗口中完成授权,Cage 会自动检查并重新连接项目。</p>
607新增: <div className="project-recovery-actions">
608新增: <MacOSLogin maintenance="projects" label="文件共享权限" disabled={!status.ready || busy} />
609新增: <MacOSLogin maintenance="screen" label="屏幕录制权限" disabled={!status.ready || busy} />
610新增: <MacOSLogin maintenance="input" label="辅助功能权限" disabled={!status.ready || busy} />
611新增: </div>
612新增: </section>}
613新增: {!status.storage_recovery?.required && <ResourceSettings status={status} onConfirm={onConfirm} onDirtyChange={setResourceDirty} />}
604614 <DiagnosticSettings />
605615 {status.can_restore && (
606616 <button
修改ui/src/style.css+1 −0看文件
@@ -2716,5 +2716,6 @@ svg {
27162716.environment-storage .field-help code { overflow-wrap: anywhere; }
27172717.environment-storage .storage-actions { display: flex; flex-wrap: wrap; gap: 8px; }
27182718.environment-storage .storage-actions button:disabled { opacity: 1; color: var(--muted); background: var(--chrome); }
2719新增:.environment-storage .storage-repair-help { margin: 8px 0 0; }
27192720.environment-storage > [role="status"] { margin: 12px 0 20px; overflow-wrap: anywhere; }
27202721.start-project-box .storage-entry { justify-self: start; margin: 0 16px 8px; }
修改ui/src/views.jsx+2 −1看文件
@@ -128,8 +128,9 @@ export const RemoteView = forwardRef(function RemoteView(
128128 }, container, {
129129 guestPlatform: () => current.current.guestPlatform,
130130 systemClipboard: () => current.current.systemClipboard,
131删除: copyText: !desktop && !current.current.systemClipboard
131新增: copyText: !desktop
132132 ? (_sendCopy, valid, { id, context, key }) => {
133新增: if (current.current.systemClipboard !== false) return undefined;
133134 if (!valid()) throw new Error("复制位置已切换,请重新复制");
134135 return api("/browser/" + (key === "x" ? "cut" : "copy"), { id, context });
135136 }