Merge pull request #11 from Flysky701/codex/windows-background-quit
fix(windows): 静默启动后台并允许桌面在 CLI 断线后退出
- 作者
- Shihao Li
- 时间
- 2026/11/09 23:45
- 提交
- b5db6d1
这是一个合并提交,下面是和第一个上一提交相比的改动。
fix(windows): 静默启动后台并允许桌面在 CLI 断线后退出
这是一个合并提交,下面是和第一个上一提交相比的改动。
| @@ -17,6 +17,7 @@ import ( | ||
| 17 | 17 | "github.com/sylvinus/agent-vm/internal/agentcli" |
| 18 | 18 | "github.com/sylvinus/agent-vm/internal/cage" |
| 19 | 19 | "github.com/sylvinus/agent-vm/internal/diagnostics" |
| 20 | 新增: "github.com/sylvinus/agent-vm/internal/host" | |
| 20 | 21 | "github.com/sylvinus/agent-vm/internal/version" |
| 21 | 22 | "github.com/sylvinus/agent-vm/internal/workbench" |
| 22 | 23 | ) |
| @@ -179,6 +180,7 @@ func relay(config string) error { | ||
| 179 | 180 | defer out.Close() |
| 180 | 181 | defer stderr.Close() |
| 181 | 182 | cmd.Stdout, cmd.Stderr = out, stderr |
| 183 | 新增: host.HideCommandWindow(cmd) | |
| 182 | 184 | if err := cmd.Start(); err != nil { |
| 183 | 185 | return err |
| 184 | 186 | } |
| @@ -147,6 +147,7 @@ Cage 不自动读取主机上的 Claude 登录。请在 Cage 终端运行 `claud | ||
| 147 | 147 | | 网页复制按钮显示成功,本机粘贴仍是旧内容 | 保持网页和 Cage 窗口在前台重试。已有页面若改写了复制 API,可刷新后再试;复杂 DOM 选区、图片、富文本或超长文字可使用复制快捷键及“文本传递”面板。 | |
| 148 | 148 | | 停止后旧终端不见了 | 停止虚拟机会结束进程。磁盘和登录态保留,但需要新建终端。 | |
| 149 | 149 | | 关掉窗口后任务还在运行 | 关闭窗口保留环境;需要结束时选择“停止环境并退出”。 | |
| 150 | 新增:| 已在命令行关闭 Cage 后台,桌面窗口还开着 | 从应用菜单选择“退出 Cage”(Windows 也可使用托盘菜单)。若提示无法确认环境状态,选择“仅退出桌面应用”。重新连接后可查看环境和任务状态。 | | |
| 150 | 151 | | 修改设置后无法正常使用 | “设置 → 环境与恢复”可恢复上一份配置;此操作需要停止并重启环境,已结束的终端不能恢复。 | |
| 151 | 152 | |
| 152 | 153 | ## 页面与出口状态 |
| @@ -40,7 +40,7 @@ Windows 快捷键以 `Ctrl` 为主:`Ctrl+O` 打开项目、`Ctrl+T` 新建网 | ||
| 40 | 40 | |
| 41 | 41 | 窗口仅保留系统标题栏,工作台直接占据下方区域。文件、项目和设置操作使用工作台入口与快捷键;检查应用更新和版本信息可从托盘图标的右键菜单打开。窗口首次打开时按当前屏幕的可用区域居中,并适配 Windows 显示缩放。手动调整后的窗口尺寸和最大化状态会保存;换屏或降低分辨率时,窗口保持在当前屏幕内。后台启动与版本检测不显示命令行窗口。 |
| 42 | 42 | |
| 43 | 删除:关闭窗口会保留环境与后台任务,可从托盘图标重新打开;停止环境或选择停止后退出会结束终端。重新打开应用可连接仍运行的会话。 | |
| 43 | 新增:从开始菜单打开 Cage 时,完整版和轻量客户端的后台服务都会静默启动。关闭工作台窗口会保留环境与后台任务,可从托盘图标重新打开。要退出桌面程序,在托盘菜单选择“退出 Cage”。本机环境仍在运行时,可以选择保留任务或停止环境;停止环境会结束其中的终端。 | |
| 44 | 44 | |
| 45 | 45 | 浏览器上传通过本机文件选择窗口选取文件;下载完成可用 Windows“另存为”选择位置。侧栏“下载”提供打开文件、在资源管理器中显示与再次另存为,取消保存窗口时保留默认 Downloads 中的文件。操作与限制见[浏览器上传与下载](getting-started.md#浏览器上传与下载)。 |
| 46 | 46 | |
| @@ -2,5 +2,9 @@ | ||
| 2 | 2 | |
| 3 | 3 | package host |
| 4 | 4 | |
| 5 | 新增:import "os/exec" | |
| 6 | 新增: | |
| 7 | 新增:func HideCommandWindow(cmd *exec.Cmd) {} | |
| 8 | 新增: | |
| 5 | 9 | func ConfigureWindowsRuntime() error { return nil } |
| 6 | 10 | func windowsHypervisorReady() error { return nil } |
| @@ -3,14 +3,25 @@ package host | ||
| 3 | 3 | import ( |
| 4 | 4 | "fmt" |
| 5 | 5 | "os" |
| 6 | 新增: "os/exec" | |
| 6 | 7 | "path/filepath" |
| 7 | 8 | "runtime" |
| 8 | 9 | "strings" |
| 10 | 新增: "syscall" | |
| 9 | 11 | "unsafe" |
| 10 | 12 | |
| 11 | 13 | "golang.org/x/sys/windows" |
| 12 | 14 | ) |
| 13 | 15 | |
| 16 | 新增:// HideCommandWindow prevents a background console child from opening a terminal. | |
| 17 | 新增:func HideCommandWindow(cmd *exec.Cmd) { | |
| 18 | 新增: if cmd.SysProcAttr == nil { | |
| 19 | 新增: cmd.SysProcAttr = &syscall.SysProcAttr{} | |
| 20 | 新增: } | |
| 21 | 新增: cmd.SysProcAttr.HideWindow = true | |
| 22 | 新增: cmd.SysProcAttr.CreationFlags |= windows.CREATE_NO_WINDOW | |
| 23 | 新增:} | |
| 24 | 新增: | |
| 14 | 25 | // ConfigureWindowsRuntime uses only the runtime shipped next to cage.exe. |
| 15 | 26 | // The install does not modify the user's system PATH or SSH configuration. |
| 16 | 27 | func ConfigureWindowsRuntime() error { |
| @@ -0,0 +1,44 @@ | ||
| 1 | 新增:package host | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "fmt" | |
| 5 | 新增: "os" | |
| 6 | 新增: "os/exec" | |
| 7 | 新增: "strings" | |
| 8 | 新增: "syscall" | |
| 9 | 新增: "testing" | |
| 10 | 新增: | |
| 11 | 新增: "golang.org/x/sys/windows" | |
| 12 | 新增:) | |
| 13 | 新增: | |
| 14 | 新增:func TestHideCommandWindowPreservesProcessAttributes(t *testing.T) { | |
| 15 | 新增: attributes := &syscall.SysProcAttr{CreationFlags: windows.CREATE_NEW_PROCESS_GROUP} | |
| 16 | 新增: cmd := &exec.Cmd{SysProcAttr: attributes} | |
| 17 | 新增: HideCommandWindow(cmd) | |
| 18 | 新增: if cmd.SysProcAttr != attributes || !attributes.HideWindow || attributes.CreationFlags != windows.CREATE_NEW_PROCESS_GROUP|windows.CREATE_NO_WINDOW { | |
| 19 | 新增: t.Fatalf("background command attributes changed: %+v", cmd.SysProcAttr) | |
| 20 | 新增: } | |
| 21 | 新增:} | |
| 22 | 新增: | |
| 23 | 新增:func TestHiddenCommandHasNoConsoleAndCapturesOutput(t *testing.T) { | |
| 24 | 新增: executable, err := os.Executable() | |
| 25 | 新增: if err != nil { | |
| 26 | 新增: t.Fatal(err) | |
| 27 | 新增: } | |
| 28 | 新增: cmd := exec.Command(executable, "-test.run=^TestHiddenCommandChild$") | |
| 29 | 新增: cmd.Env = append(os.Environ(), "CAGE_HIDDEN_COMMAND_TEST=1") | |
| 30 | 新增: HideCommandWindow(cmd) | |
| 31 | 新增: output, err := cmd.CombinedOutput() | |
| 32 | 新增: if err != nil || !strings.Contains(string(output), "console=0") || !strings.Contains(string(output), "stderr-captured") { | |
| 33 | 新增: t.Fatalf("hidden child: %s, %v", output, err) | |
| 34 | 新增: } | |
| 35 | 新增:} | |
| 36 | 新增: | |
| 37 | 新增:func TestHiddenCommandChild(t *testing.T) { | |
| 38 | 新增: if os.Getenv("CAGE_HIDDEN_COMMAND_TEST") != "1" { | |
| 39 | 新增: return | |
| 40 | 新增: } | |
| 41 | 新增: window, _, _ := windows.NewLazySystemDLL("kernel32.dll").NewProc("GetConsoleWindow").Call() | |
| 42 | 新增: fmt.Printf("console=%d\n", window) | |
| 43 | 新增: fmt.Fprintln(os.Stderr, "stderr-captured") | |
| 44 | 新增:} | |
| @@ -7,7 +7,6 @@ import ( | ||
| 7 | 7 | "net/http" |
| 8 | 8 | "net/url" |
| 9 | 9 | "sync" |
| 10 | 删除: "syscall" | |
| 11 | 10 | "time" |
| 12 | 11 | ) |
| 13 | 12 | |
| @@ -27,7 +26,7 @@ func LocalSession(ctx context.Context, origin string, manifest PublicManifest, j | ||
| 27 | 26 | return nil, errors.New("本机服务地址已改变") |
| 28 | 27 | } |
| 29 | 28 | conn, err := dial.DialContext(ctx, "tcp4", endpoint) |
| 30 | 删除: if errors.Is(err, syscall.ECONNREFUSED) { | |
| 29 | 新增: if errors.Is(err, connectionRefused) { | |
| 31 | 30 | cancel() |
| 32 | 31 | } |
| 33 | 32 | return conn, err |
| @@ -0,0 +1,7 @@ | ||
| 1 | 新增://go:build !windows | |
| 2 | 新增: | |
| 3 | 新增:package remotehost | |
| 4 | 新增: | |
| 5 | 新增:import "syscall" | |
| 6 | 新增: | |
| 7 | 新增:const connectionRefused = syscall.ECONNREFUSED | |
| @@ -0,0 +1,6 @@ | ||
| 1 | 新增:package remotehost | |
| 2 | 新增: | |
| 3 | 新增:import "golang.org/x/sys/windows" | |
| 4 | 新增: | |
| 5 | 新增:// A refused TCP dial returns the Winsock error, not syscall.ECONNREFUSED. | |
| 6 | 新增:const connectionRefused = windows.WSAECONNREFUSED | |
| @@ -15,6 +15,8 @@ import ( | ||
| 15 | 15 | "runtime" |
| 16 | 16 | "strings" |
| 17 | 17 | "time" |
| 18 | 新增: | |
| 19 | 新增: "github.com/sylvinus/agent-vm/internal/host" | |
| 18 | 20 | ) |
| 19 | 21 | |
| 20 | 22 | type desktopFileOpen struct { |
| @@ -270,7 +272,7 @@ func openHostFile(path, action string) error { | ||
| 270 | 272 | defer cancel() |
| 271 | 273 | command := hostFileCommand(runtime.GOOS, path, action, info.IsDir()) |
| 272 | 274 | cmd := exec.CommandContext(ctx, command.Path, command.Args[1:]...) |
| 273 | 删除: hideCommand(cmd) | |
| 275 | 新增: host.HideCommandWindow(cmd) | |
| 274 | 276 | if err = cmd.Run(); err != nil { |
| 275 | 277 | if runtime.GOOS != "linux" || action != "reveal" { |
| 276 | 278 | return errors.New("无法打开本机文件或文件管理器,请检查默认应用和文件权限") |
| @@ -10,6 +10,7 @@ import ( | ||
| 10 | 10 | "time" |
| 11 | 11 | |
| 12 | 12 | "github.com/sylvinus/agent-vm/internal/cage" |
| 13 | 新增: "github.com/sylvinus/agent-vm/internal/host" | |
| 13 | 14 | "github.com/sylvinus/agent-vm/internal/managedproxy" |
| 14 | 15 | ) |
| 15 | 16 | |
| @@ -102,7 +103,7 @@ CAGE_VERSIONS`) | ||
| 102 | 103 | if core, err := managedproxy.CorePath(); err == nil { |
| 103 | 104 | probeCtx, done := context.WithTimeout(ctx, 2*time.Second) |
| 104 | 105 | cmd := exec.CommandContext(probeCtx, core, "-v") |
| 105 | 删除: hideCommand(cmd) | |
| 106 | 新增: host.HideCommandWindow(cmd) | |
| 106 | 107 | b, e := cmd.Output() |
| 107 | 108 | done() |
| 108 | 109 | if e == nil { |
| @@ -15,6 +15,7 @@ import ( | ||
| 15 | 15 | |
| 16 | 16 | "github.com/sylvinus/agent-vm/internal/cage" |
| 17 | 17 | "github.com/sylvinus/agent-vm/internal/guestos" |
| 18 | 新增: "github.com/sylvinus/agent-vm/internal/host" | |
| 18 | 19 | ) |
| 19 | 20 | |
| 20 | 21 | // Only the trusted local workbench can operate the native Mac. Each route |
| @@ -52,7 +53,7 @@ func (s *Server) macOSSSHCommand(ctx context.Context, args ...string) *exec.Cmd | ||
| 52 | 53 | } |
| 53 | 54 | cmd := exec.CommandContext(ctx, sshExecutable(), append(base, args...)...) |
| 54 | 55 | cmd.Env = sshEnvironment() |
| 55 | 删除: hideCommand(cmd) | |
| 56 | 新增: host.HideCommandWindow(cmd) | |
| 56 | 57 | return cmd |
| 57 | 58 | } |
| 58 | 59 | |
| @@ -14,6 +14,7 @@ import ( | ||
| 14 | 14 | "time" |
| 15 | 15 | |
| 16 | 16 | "github.com/sylvinus/agent-vm/internal/guestos" |
| 17 | 新增: "github.com/sylvinus/agent-vm/internal/host" | |
| 17 | 18 | ) |
| 18 | 19 | |
| 19 | 20 | // Only installer-created bindings carry this identity. A damaged binding stays |
| @@ -315,6 +316,6 @@ func (s *Server) macOSSetupAdminCommand(ctx context.Context) *exec.Cmd { | ||
| 315 | 316 | } |
| 316 | 317 | cmd := exec.CommandContext(ctx, sshExecutable(), append(args, "-T", "cage-macos", "--", "exec /usr/bin/sudo -S -p '' /usr/local/libexec/cage-finish-initial-setup < /Users/"+user+"/password")...) |
| 317 | 318 | cmd.Env = sshEnvironment() |
| 318 | 删除: hideCommand(cmd) | |
| 319 | 新增: host.HideCommandWindow(cmd) | |
| 319 | 320 | return cmd |
| 320 | 321 | } |
| @@ -15,6 +15,7 @@ import ( | ||
| 15 | 15 | |
| 16 | 16 | "al.essio.dev/pkg/shellescape" |
| 17 | 17 | "github.com/sylvinus/agent-vm/internal/guestos" |
| 18 | 新增: "github.com/sylvinus/agent-vm/internal/host" | |
| 18 | 19 | ) |
| 19 | 20 | |
| 20 | 21 | func (s *Server) syncMacGuestPassword(ctx context.Context) error { |
| @@ -50,7 +51,7 @@ func (s *Server) applyMacGuestPassword(ctx context.Context, id uuid.UUID, oldPas | ||
| 50 | 51 | command := func(ctx context.Context, script string) *exec.Cmd { |
| 51 | 52 | cmd := exec.CommandContext(ctx, sshExecutable(), append(append([]string{}, args...), "-T", "cage-macos", "--", "exec /bin/sh -ec "+shellescape.Quote(script))...) |
| 52 | 53 | cmd.Env = sshEnvironment() |
| 53 | 删除: hideCommand(cmd) | |
| 54 | 新增: host.HideCommandWindow(cmd) | |
| 54 | 55 | return cmd |
| 55 | 56 | } |
| 56 | 57 | // Use this build's helper so older managed guests can adopt the shared |
| @@ -24,7 +24,6 @@ func processExists(pid int) bool { | ||
| 24 | 24 | } |
| 25 | 25 | func terminateLegacy(pid int) error { return syscall.Kill(pid, syscall.SIGTERM) } |
| 26 | 26 | func detachController(cmd *exec.Cmd) { cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true} } |
| 27 | 删除:func hideCommand(cmd *exec.Cmd) {} | |
| 28 | 27 | func sshExecutable() string { return "/usr/bin/ssh" } |
| 29 | 28 | func sshEnvironment() []string { |
| 30 | 29 | return []string{"PATH=/usr/bin:/bin:/usr/sbin:/sbin", "LANG=C", "LC_ALL=C", "TERM=xterm-256color"} |
| @@ -35,9 +35,6 @@ func terminateLegacy(pid int) error { | ||
| 35 | 35 | func detachController(cmd *exec.Cmd) { |
| 36 | 36 | cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true, CreationFlags: windows.CREATE_NEW_PROCESS_GROUP | windows.CREATE_NO_WINDOW} |
| 37 | 37 | } |
| 38 | 删除:func hideCommand(cmd *exec.Cmd) { | |
| 39 | 删除: cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true, CreationFlags: windows.CREATE_NO_WINDOW} | |
| 40 | 删除:} | |
| 41 | 38 | func sshExecutable() string { |
| 42 | 39 | exe, _ := os.Executable() |
| 43 | 40 | bundled := filepath.Join(filepath.Dir(exe), "runtime", "openssh", "ssh.exe") |
| @@ -18,6 +18,7 @@ import ( | ||
| 18 | 18 | "github.com/sylvinus/agent-vm/internal/containerenv" |
| 19 | 19 | "github.com/sylvinus/agent-vm/internal/diagnostics" |
| 20 | 20 | "github.com/sylvinus/agent-vm/internal/guestos" |
| 21 | 新增: "github.com/sylvinus/agent-vm/internal/host" | |
| 21 | 22 | "github.com/sylvinus/agent-vm/internal/hostimage" |
| 22 | 23 | "github.com/sylvinus/agent-vm/internal/managedproxy" |
| 23 | 24 | ) |
| @@ -91,7 +92,7 @@ func (s *Server) sshCommandOptions(ctx context.Context, maintenance bool, args . | ||
| 91 | 92 | base = append(base, args...) |
| 92 | 93 | cmd := exec.CommandContext(ctx, sshExecutable(), base...) |
| 93 | 94 | cmd.Env = sshEnvironment() |
| 94 | 删除: hideCommand(cmd) | |
| 95 | 新增: host.HideCommandWindow(cmd) | |
| 95 | 96 | return cmd |
| 96 | 97 | } |
| 97 | 98 | func (s *Server) guest(ctx context.Context, script string) ([]byte, error) { |
| @@ -272,7 +273,7 @@ func (s *Server) runCage(args ...string) error { | ||
| 272 | 273 | defer cancel() |
| 273 | 274 | } |
| 274 | 275 | cmd := exec.CommandContext(ctx, s.exe, args...) |
| 275 | 删除: hideCommand(cmd) | |
| 276 | 新增: host.HideCommandWindow(cmd) | |
| 276 | 277 | cmd.Dir = s.environmentDir() |
| 277 | 278 | if cmd.Dir == "" { |
| 278 | 279 | cmd.Dir = s.profile |
| @@ -20,6 +20,7 @@ import ( | ||
| 20 | 20 | "github.com/containers/gvisor-tap-vsock/pkg/virtualnetwork" |
| 21 | 21 | "github.com/sylvinus/agent-vm/internal/cage" |
| 22 | 22 | "github.com/sylvinus/agent-vm/internal/guestos" |
| 23 | 新增: "github.com/sylvinus/agent-vm/internal/host" | |
| 23 | 24 | ) |
| 24 | 25 | |
| 25 | 26 | type windowsHostNetwork struct { |
| @@ -52,7 +53,7 @@ func (s *Server) startWindowsNetwork() error { | ||
| 52 | 53 | cmd.Env = append(os.Environ(), cage.ConfigEnv+"="+s.configPath) |
| 53 | 54 | cmd.Stdout = io.Discard |
| 54 | 55 | cmd.Stderr = io.Discard |
| 55 | 删除: hideCommand(cmd) | |
| 56 | 新增: host.HideCommandWindow(cmd) | |
| 56 | 57 | if err := cmd.Start(); err != nil { |
| 57 | 58 | cancel() |
| 58 | 59 | close(process.done) |
| @@ -48,6 +48,8 @@ function Assert-WindowsWorkbenchReport { | ||
| 48 | 48 | if ((Get-Item -LiteralPath $Report).Length -gt 65536) { throw 'Cage smoke report exceeds the bounded diagnostic size.' } |
| 49 | 49 | $result = Get-Content -LiteralPath $Report -Raw | ConvertFrom-Json -AsHashtable |
| 50 | 50 | $safe = @{ phase = ConvertTo-SmokeSafeText $result['phase']; nativeStatus = ConvertTo-SmokeSafeText $result['nativeStatus']; jsErrors = @() } |
| 51 | 新增: if ($result['prepareExit'] -is [int] -or $result['prepareExit'] -is [long]) { $safe.prepareExit = $result['prepareExit'] } | |
| 52 | 新增: if ($result['prepareStatus'] -in @('prepared', 'stop_required', 'error', 'unexpected')) { $safe.prepareStatus = $result['prepareStatus'] } | |
| 51 | 53 | if ($result['page'] -is [System.Collections.IDictionary] -and $result['page']['errors']) { |
| 52 | 54 | $safe.jsErrors = @($result['page']['errors'] | Select-Object -First 8 | ForEach-Object { |
| 53 | 55 | if ($_ -isnot [System.Collections.IDictionary]) { return } |
| @@ -31,6 +31,7 @@ try { | ||
| 31 | 31 | [IO.File]::WriteAllText($childScript, '[IO.File]::Copy($args[0],$args[1],$true); exit 17') |
| 32 | 32 | @{ |
| 33 | 33 | success = $false; nativeBridgeReady = $false; phase = 'loading_workbench' |
| 34 | 新增: prepareExit = 1; prepareStatus = 'stop_required' | |
| 34 | 35 | nativeStatus = 'failed http://localhost:1234/?token=private-token#private-fragment' |
| 35 | 36 | entryJSON = 'private-entry'; pageURL = 'http://localhost:1234/#private-launch' |
| 36 | 37 | page = @{ text = 'private-page-body'; errors = @( |
| @@ -52,7 +53,7 @@ try { | ||
| 52 | 53 | } 6>&1 |
| 53 | 54 | $text = ($captured | ForEach-Object { $_.ToString() }) -join "`n" |
| 54 | 55 | Assert-SmokeContract ($observedFailure -like '*loading_workbench*') 'Failure report was not parsed before rejecting its process exit.' |
| 55 | 删除: foreach ($expected in @('loading_workbench', 'module-load', '/missing.js', 'syntax error')) { | |
| 56 | 新增: foreach ($expected in @('loading_workbench', 'module-load', '/missing.js', 'syntax error', '"prepareExit":1', '"prepareStatus":"stop_required"')) { | |
| 56 | 57 | Assert-SmokeContract ($text.Contains($expected)) "Missing safe smoke evidence: $expected" |
| 57 | 58 | } |
| 58 | 59 | foreach ($private in @('private-token','private-fragment','private-query','private-entry','private-launch','private-page-body')) { |
| @@ -98,8 +98,13 @@ for (const [platform, system] of [["darwin", "macos"], ["windows", "windows-11"] | ||
| 98 | 98 | rejectComplete = false; |
| 99 | 99 | await page.getByRole("button", { name: "进入工作台", exact: true }).click(); |
| 100 | 100 | await page.getByRole("complementary", { name: "项目与终端" }).waitFor(); |
| 101 | 新增: await page.evaluate(() => window.cageNativeAction("settings")); | |
| 102 | 新增: await page.getByRole("region", { name: "设置", exact: true }).waitFor(); | |
| 101 | 103 | await page.reload(); |
| 102 | 104 | await page.getByRole("complementary", { name: "项目与终端" }).waitFor(); |
| 105 | 新增: await page.evaluate(() => window.cageNativeAction("quit")); | |
| 106 | 新增: const quitDialog = page.getByRole("dialog", { name: "退出 Cage", exact: true }); | |
| 107 | 新增: await quitDialog.getByRole("button", { name: "取消", exact: true }).click(); | |
| 103 | 108 | assert.equal(await page.getByRole("heading", { name: "为 Cage 准备独立环境" }).count(), 0); |
| 104 | 109 | assert.deepEqual(errors, []); |
| 105 | 110 | console.log(`PASS ${platform}: independent initialization, inline keyboard selection, back navigation, progress, refresh, retry, completion gate and reopen`); |
| @@ -72,6 +72,11 @@ for (const failure of ["http", "native"]) { | ||
| 72 | 72 | assert.ok(await retry.isVisible(), "checking permissions hid the completion retry"); |
| 73 | 73 | await retry.click(); |
| 74 | 74 | await page.getByRole("heading",{name:"正在准备虚拟 Mac"}).waitFor({state:"hidden"}); |
| 75 | 新增: await page.getByRole("complementary", { name: "项目与终端" }).waitFor(); | |
| 76 | 新增: await page.evaluate(() => window.cageNativeAction("settings")); | |
| 77 | 新增: await page.getByRole("region", { name: "设置", exact: true }).waitFor(); | |
| 78 | 新增: await page.evaluate(() => window.cageNativeAction("quit")); | |
| 79 | 新增: await page.getByRole("dialog", { name: "退出 Cage", exact: true }).getByRole("button", { name: "取消", exact: true }).click(); | |
| 75 | 80 | assert.equal(calls.filter(c=>c==="finish").length,2); |
| 76 | 81 | assert.equal(calls.filter(c=>c==="verify-projects").length,0); |
| 77 | 82 | assert.deepEqual(errors, []); |
| @@ -0,0 +1,51 @@ | ||
| 1 | 新增:import assert from "node:assert/strict"; | |
| 2 | 新增:import { createWorkbench } from "./workbench-fixture.mjs"; | |
| 3 | 新增: | |
| 4 | 新增:const calls = []; | |
| 5 | 新增:const view = { | |
| 6 | 新增: mode: "local", desktop_gateway: true, connection_id: "test-local-view", | |
| 7 | 新增: connection: { state: "connected" }, | |
| 8 | 新增:}; | |
| 9 | 新增:const { page, browser, errors } = await createWorkbench({ | |
| 10 | 新增: clientContext: view, | |
| 11 | 新增: nativeRequest: async (request) => { calls.push(request); return null; }, | |
| 12 | 新增:}); | |
| 13 | 新增:const quit = () => page.evaluate(() => window.cageNativeAction("quit")); | |
| 14 | 新增:const exits = () => calls.filter(({ action }) => action === "quitNow").length; | |
| 15 | 新增:const refused = (route) => route.abort("connectionrefused"); | |
| 16 | 新增:const stops = []; | |
| 17 | 新增:page.on("request", (request) => { | |
| 18 | 新增: if (new URL(request.url()).pathname === "/api/stop") stops.push(request); | |
| 19 | 新增:}); | |
| 20 | 新增:try { | |
| 21 | 新增: await page.exposeFunction("testDesktopExits", exits); | |
| 22 | 新增: // Lose the gateway while the workbench still shows the previous environment. | |
| 23 | 新增: await page.route("**/api/**", refused); | |
| 24 | 新增: await page.locator(".connection-banner").waitFor(); | |
| 25 | 新增: await quit(); | |
| 26 | 新增: const dialog = page.getByRole("dialog", { name: "退出 Cage" }); | |
| 27 | 新增: await dialog.getByRole("button", { name: "取消" }).click(); | |
| 28 | 新增: assert.equal(exits(), 0); | |
| 29 | 新增: await quit(); | |
| 30 | 新增: await dialog.getByRole("button", { name: "仅退出桌面应用" }).click(); | |
| 31 | 新增: await page.waitForFunction(async () => (await window.testDesktopExits()) === 1, null, { timeout: 5000 }); | |
| 32 | 新增: assert.equal(exits(), 1); | |
| 33 | 新增: | |
| 34 | 新增: // Initial context cannot be loaded on reopening the page. | |
| 35 | 新增: await page.reload(); | |
| 36 | 新增: await page.getByRole("alert").getByRole("button", { name: "重新连接" }).waitFor(); | |
| 37 | 新增: await quit(); | |
| 38 | 新增: assert.equal(exits(), 2); | |
| 39 | 新增: | |
| 40 | 新增: // Gateway is alive, but its selected CLI controller has exited. | |
| 41 | 新增: view.connection = { state: "failed", error_code: "connection_lost" }; | |
| 42 | 新增: await page.unroute("**/api/**", refused); | |
| 43 | 新增: await page.reload(); | |
| 44 | 新增: await page.getByRole("heading", { name: "重新连接本机工作台" }).waitFor(); | |
| 45 | 新增: await quit(); | |
| 46 | 新增: assert.equal(exits(), 3); | |
| 47 | 新增: assert.equal(stops.length, 0); | |
| 48 | 新增: assert.deepEqual(errors, []); | |
| 49 | 新增:} finally { | |
| 50 | 新增: await browser.close(); | |
| 51 | 新增:} | |
| @@ -244,15 +244,6 @@ export function AccountGate({ children }) { | ||
| 244 | 244 | setBusy(true); |
| 245 | 245 | deviceAction("unlock", "automatic").catch((e) => setError(e.message)).finally(() => setBusy(false)); |
| 246 | 246 | }, [account?.unlocked, account?.devices?.automatic, account?.require_authentication, deviceSupport]); |
| 247 | 删除: useEffect(() => { | |
| 248 | 删除: if (account?.unlocked) return; | |
| 249 | 删除: window.cageNativeAction = async (action) => { | |
| 250 | 删除: if (action === "quit") await native("quitNow"); | |
| 251 | 删除: }; | |
| 252 | 删除: return () => { | |
| 253 | 删除: delete window.cageNativeAction; | |
| 254 | 删除: }; | |
| 255 | 删除: }, [account?.unlocked]); | |
| 256 | 247 | if (account?.unlocked) return children; |
| 257 | 248 | const creating = account && !account.exists; |
| 258 | 249 | const rememberThisDevice = rememberLogin ?? Boolean(creating || account?.trusted_login || account?.devices?.automatic); |
| @@ -3,6 +3,7 @@ import { httpErrorMessage, connectionErrorMessage, operationName, nativeFailureM | ||
| 3 | 3 | import { assertConnection, connectionHeaders, getClientContext, isProjectSharesPath } from "./client-context.mjs"; |
| 4 | 4 | import { installAgentNativeConsumer } from "./agent-native.js"; |
| 5 | 5 | let sessionRenewal; |
| 6 | 新增:class WorkbenchUnreachable extends Error {} | |
| 6 | 7 | async function responseError(response, path, method = "GET") { |
| 7 | 8 | const error = new Error( |
| 8 | 9 | httpErrorMessage(path, response.status, await response.text(), response.headers.get("Content-Type") || "", method), |
| @@ -45,7 +46,9 @@ export async function api(path, body, method, headers = {}, { signal } = {}) { | ||
| 45 | 46 | catch (error) { |
| 46 | 47 | if (signal?.aborted) throw signal.reason; |
| 47 | 48 | reportDiagnostic("frontend", error); |
| 48 | 删除: throw new Error(connectionErrorMessage(path, options.method), { cause: error }); | |
| 49 | 新增: const message = connectionErrorMessage(path, options.method); | |
| 50 | 新增: if (error instanceof TypeError) throw new WorkbenchUnreachable(message, { cause: error }); | |
| 51 | 新增: throw new Error(message, { cause: error }); | |
| 49 | 52 | } |
| 50 | 53 | }; |
| 51 | 54 | let response = await send(); |
| @@ -102,11 +105,31 @@ export async function uploadFile(path, file, { signal, onProgress } = {}) { | ||
| 102 | 105 | const nativeBridge = () => |
| 103 | 106 | window.cageNativeBridge || window.webkit?.messageHandlers?.cage; |
| 104 | 107 | export const nativeAvailable = () => Boolean(nativeBridge()); |
| 108 | 新增:const lostLocalView = (context) => | |
| 109 | 新增: context.desktop_gateway && context.mode === "local" && | |
| 110 | 新增: context.connection?.state === "failed" && context.connection.error_code === "connection_lost"; | |
| 111 | 新增: | |
| 112 | 新增:async function suspendBeforeQuit(context) { | |
| 113 | 新增: if (context.mode !== "local" || context.client_only || lostLocalView(context)) return; | |
| 114 | 新增: try { | |
| 115 | 新增: await api("/account/suspend", {}); | |
| 116 | 新增: } catch (error) { | |
| 117 | 新增: if (error.status === 423) return; | |
| 118 | 新增: // The first request after CLI shutdown can fail before the next context poll. | |
| 119 | 新增: if (context.desktop_gateway && [409, 502].includes(error.status)) { | |
| 120 | 新增: const latest = await api("/client/context"); | |
| 121 | 新增: if (latest.connection_id === context.connection_id && lostLocalView(latest)) return; | |
| 122 | 新增: } | |
| 123 | 新增: throw error; | |
| 124 | 新增: } | |
| 125 | 新增:} | |
| 105 | 126 | export async function native(action, extra = {}) { |
| 106 | 删除: const connection = getClientContext().connection_id; | |
| 107 | 删除: if (action === "quitNow" && getClientContext().mode === "local" && !getClientContext().client_only) { | |
| 108 | 删除: try { await api("/account/suspend", {}); } | |
| 109 | 删除: catch (error) { if (error.status !== 423) throw error; } | |
| 127 | 新增: const context = getClientContext(); | |
| 128 | 新增: const connection = context.connection_id; | |
| 129 | 新增: if (action === "quitNow") { | |
| 130 | 新增: try { await suspendBeforeQuit(context); } | |
| 131 | 新增: catch (error) { if (!(error instanceof WorkbenchUnreachable)) throw error; } | |
| 132 | 新增: assertConnection(connection); | |
| 110 | 133 | } |
| 111 | 134 | try { |
| 112 | 135 | const result = await nativeBridge().postMessage({ action, ...extra, connection_id: connection }); |
| @@ -1,4 +1,4 @@ | ||
| 1 | 删除:let current = Object.freeze({ mode: "local", connection_id: "local" }); | |
| 1 | 新增:let current = Object.freeze({ mode: "none", connection_id: "" }); | |
| 2 | 2 | |
| 3 | 3 | export function setClientContext(value) { |
| 4 | 4 | current = Object.freeze({ ...value }); |
| @@ -52,6 +52,95 @@ test("quitting a remote client never suspends the cloud account", async (t) => { | ||
| 52 | 52 | assert.deepEqual(request, { action: "quitNow", connection_id: "first" }); |
| 53 | 53 | }); |
| 54 | 54 | |
| 55 | 新增:const localGateway = (state) => ({ | |
| 56 | 新增: mode: "local", desktop_gateway: true, connection_id: "local-view", | |
| 57 | 新增: connection: { state, error_code: state === "failed" ? "connection_lost" : "" }, | |
| 58 | 新增:}); | |
| 59 | 新增: | |
| 60 | 新增:test("quit still reaches the desktop after the selected CLI controller exits", async (t) => { | |
| 61 | 新增: environment(t); | |
| 62 | 新增: setClientContext(localGateway("connected")); | |
| 63 | 新增: const calls = []; | |
| 64 | 新增: let status; | |
| 65 | 新增: globalThis.fetch = async (path) => { | |
| 66 | 新增: calls.push(path); | |
| 67 | 新增: if (path === "/api/client/context") return Response.json(localGateway("failed")); | |
| 68 | 新增: return new Response("connection unavailable", { status }); | |
| 69 | 新增: }; | |
| 70 | 新增: window.webkit.messageHandlers.cage.postMessage = ({ action }) => calls.push(action); | |
| 71 | 新增: for (status of [502, 409]) { | |
| 72 | 新增: calls.length = 0; | |
| 73 | 新增: await native("quitNow"); | |
| 74 | 新增: assert.deepEqual(calls, ["/api/account/suspend", "/api/client/context", "quitNow"]); | |
| 75 | 新增: } | |
| 76 | 新增: calls.length = 0; | |
| 77 | 新增: setClientContext(localGateway("failed")); | |
| 78 | 新增: await native("quitNow"); | |
| 79 | 新增: assert.deepEqual(calls, ["quitNow"]); | |
| 80 | 新增:}); | |
| 81 | 新增: | |
| 82 | 新增:test("a disconnected view from another generation cannot authorize a pending quit", async (t) => { | |
| 83 | 新增: environment(t); | |
| 84 | 新增: setClientContext(localGateway("connected")); | |
| 85 | 新增: globalThis.fetch = async (path) => path === "/api/client/context" | |
| 86 | 新增: ? Response.json({ ...localGateway("failed"), connection_id: "replacement" }) | |
| 87 | 新增: : new Response("view changed", { status: 409 }); | |
| 88 | 新增: window.webkit.messageHandlers.cage.postMessage = () => assert.fail("stale quit"); | |
| 89 | 新增: await assert.rejects(native("quitNow"), { status: 409 }); | |
| 90 | 新增:}); | |
| 91 | 新增: | |
| 92 | 新增:test("quit still reaches the desktop when the CLI HTTP listener is gone", async (t) => { | |
| 93 | 新增: environment(t); | |
| 94 | 新增: setClientContext({ mode: "local", connection_id: "local" }); | |
| 95 | 新增: globalThis.fetch = async (path) => { | |
| 96 | 新增: if (path === "/api/diagnostics/events") return Response.json({}); | |
| 97 | 新增: assert.equal(path, "/api/account/suspend"); | |
| 98 | 新增: throw new TypeError("Failed to fetch"); | |
| 99 | 新增: }; | |
| 100 | 新增: const actions = []; | |
| 101 | 新增: window.webkit.messageHandlers.cage.postMessage = ({ action }) => actions.push(action); | |
| 102 | 新增: await native("quitNow"); | |
| 103 | 新增: assert.deepEqual(actions, ["quitNow"]); | |
| 104 | 新增:}); | |
| 105 | 新增: | |
| 106 | 新增:test("an offline quit cannot cross a connection change during account suspension", async (t) => { | |
| 107 | 新增: environment(t); | |
| 108 | 新增: setClientContext(localGateway("connected")); | |
| 109 | 新增: let failRequest; | |
| 110 | 新增: globalThis.fetch = (path) => { | |
| 111 | 新增: if (path === "/api/diagnostics/events") return Promise.resolve(Response.json({})); | |
| 112 | 新增: return new Promise((resolve, reject) => { failRequest = reject; }); | |
| 113 | 新增: }; | |
| 114 | 新增: window.webkit.messageHandlers.cage.postMessage = () => assert.fail("stale quit"); | |
| 115 | 新增: const quitting = native("quitNow"); | |
| 116 | 新增: setClientContext({ ...localGateway("connected"), connection_id: "replacement" }); | |
| 117 | 新增: failRequest(new TypeError("Failed to fetch")); | |
| 118 | 新增: await assert.rejects(quitting, { code: "connection_changed" }); | |
| 119 | 新增:}); | |
| 120 | 新增: | |
| 121 | 新增:test("a reachable local controller must lock or report already locked before quit", async (t) => { | |
| 122 | 新增: environment(t); | |
| 123 | 新增: setClientContext(localGateway("connected")); | |
| 124 | 新增: window.dispatchEvent = () => {}; | |
| 125 | 新增: const calls = []; | |
| 126 | 新增: let status = 500; | |
| 127 | 新增: globalThis.fetch = async (path) => { | |
| 128 | 新增: calls.push(path); | |
| 129 | 新增: if (path === "/api/client/context") return Response.json(localGateway("connected")); | |
| 130 | 新增: return Response.json({}, { status }); | |
| 131 | 新增: }; | |
| 132 | 新增: window.webkit.messageHandlers.cage.postMessage = ({ action }) => calls.push(action); | |
| 133 | 新增: for (status of [500, 409, 502]) { | |
| 134 | 新增: await assert.rejects(native("quitNow"), { status }); | |
| 135 | 新增: assert.ok(!calls.includes("quitNow")); | |
| 136 | 新增: } | |
| 137 | 新增: for (status of [200, 423]) { | |
| 138 | 新增: calls.length = 0; | |
| 139 | 新增: await native("quitNow"); | |
| 140 | 新增: assert.deepEqual(calls, ["/api/account/suspend", "quitNow"]); | |
| 141 | 新增: } | |
| 142 | 新增:}); | |
| 143 | 新增: | |
| 55 | 144 | test("an account device operation retains its host generation and rejects a late result", async (t) => { |
| 56 | 145 | environment(t); |
| 57 | 146 | let release; |
| @@ -3,11 +3,17 @@ import { createRoot } from "react-dom/client"; | ||
| 3 | 3 | import { installDiagnostics } from "./diagnostics.mjs"; |
| 4 | 4 | import { DiagnosticBoundary } from "./diagnostics.jsx"; |
| 5 | 5 | import { ClientRoot } from "./remote-hosts"; |
| 6 | 新增:import { native } from "./api"; | |
| 6 | 7 | import "./style.css"; |
| 7 | 8 | |
| 8 | 9 | const Workbench = lazy(() => import("./main.jsx")); |
| 9 | 10 | |
| 10 | 11 | installDiagnostics(); |
| 12 | 新增:// Keep the native menu usable while the workbench is loading or disconnected. | |
| 13 | 新增:window.cageNativeAction = (command) => { | |
| 14 | 新增: if (window.cageWorkbenchAction) return window.cageWorkbenchAction(command); | |
| 15 | 新增: if (command === "quit") return native("quitNow"); | |
| 16 | 新增:}; | |
| 11 | 17 | createRoot(document.getElementById("root")).render( |
| 12 | 18 | <DiagnosticBoundary> |
| 13 | 19 | <ClientRoot> |
| @@ -124,8 +124,8 @@ function Initialization({ initial, onComplete }) { | ||
| 124 | 124 | pollNow.current = poll; |
| 125 | 125 | poll(); |
| 126 | 126 | if (nativeAvailable()) native("workbenchReady").catch(() => {}); |
| 127 | 删除: window.cageNativeAction = async action => { if (action === "quit") await native("quitNow"); }; | |
| 128 | 删除: return () => { alive.current = false; clearTimeout(timer); pollNow.current = null; delete window.cageNativeAction; }; | |
| 127 | 新增: window.cageWorkbenchAction = async action => { if (action === "quit") await native("quitNow"); }; | |
| 128 | 新增: return () => { alive.current = false; clearTimeout(timer); pollNow.current = null; delete window.cageWorkbenchAction; }; | |
| 129 | 129 | }, [account?.guest_system]); |
| 130 | 130 | |
| 131 | 131 | async function run(operation) { |
| @@ -55,13 +55,13 @@ export function MacOSFirstSetup() { | ||
| 55 | 55 | if (active) timer = setTimeout(poll, 2000); |
| 56 | 56 | } |
| 57 | 57 | poll(); |
| 58 | 删除: window.cageNativeAction = async command => { | |
| 58 | 新增: window.cageWorkbenchAction = async command => { | |
| 59 | 59 | if (command === "closeTab") document.dispatchEvent(new Event("cage-close-modal")); |
| 60 | 60 | if (command === "quit") await native("quitNow"); |
| 61 | 61 | }; |
| 62 | 62 | window.cageEditAction = () => false; |
| 63 | 63 | if (nativeAvailable()) native("workbenchReady").catch(() => {}); |
| 64 | 删除: return () => { active = false; clearTimeout(timer); delete window.cageNativeAction; delete window.cageEditAction; }; | |
| 64 | 新增: return () => { active = false; clearTimeout(timer); delete window.cageWorkbenchAction; delete window.cageEditAction; }; | |
| 65 | 65 | }, []); |
| 66 | 66 | async function act(action) { |
| 67 | 67 | if (busy) return; |
| @@ -957,7 +957,7 @@ function App() { | ||
| 957 | 957 | return terminalControls.current.get(current.id)?.edit(command) || false; |
| 958 | 958 | return remote.current?.edit(command) || false; |
| 959 | 959 | }; |
| 960 | 删除: window.cageNativeAction = async (command) => { | |
| 960 | 新增: window.cageWorkbenchAction = async (command) => { | |
| 961 | 961 | if (document.querySelector(".mac-login-fullscreen")) { |
| 962 | 962 | if (command === "closeTab" || command === "quit") document.dispatchEvent(new Event("cage-close-modal")); |
| 963 | 963 | if (command !== "quit") return; |
| @@ -1031,6 +1031,15 @@ function App() { | ||
| 1031 | 1031 | await native("quitNow"); |
| 1032 | 1032 | return; |
| 1033 | 1033 | } |
| 1034 | 新增: if (connectionError || fatal) { | |
| 1035 | 新增: setDialog({ | |
| 1036 | 新增: title: "退出 Cage", | |
| 1037 | 新增: body: "工作台连接已中断,暂时无法确认环境状态。仍在运行的后台任务会继续。", | |
| 1038 | 新增: confirm: "仅退出桌面应用", | |
| 1039 | 新增: resolve: (confirmed) => confirmed && native("quitNow"), | |
| 1040 | 新增: }); | |
| 1041 | 新增: return; | |
| 1042 | 新增: } | |
| 1034 | 1043 | setDialog({ |
| 1035 | 1044 | title: "退出 Cage", |
| 1036 | 1045 | body: "退出前请保存文件和设置。可以保留环境,让后台任务继续运行;下次打开会重新连接。", |
| @@ -1048,7 +1057,7 @@ function App() { | ||
| 1048 | 1057 | }; |
| 1049 | 1058 | return () => { |
| 1050 | 1059 | window.removeEventListener("keydown", key, true); |
| 1051 | 删除: delete window.cageNativeAction; | |
| 1060 | 新增: delete window.cageWorkbenchAction; | |
| 1052 | 1061 | delete window.cageEditAction; |
| 1053 | 1062 | }; |
| 1054 | 1063 | }, [ |
| @@ -1064,6 +1073,7 @@ function App() { | ||
| 1064 | 1073 | busy, |
| 1065 | 1074 | active, |
| 1066 | 1075 | connectionError, |
| 1076 | 新增: fatal, | |
| 1067 | 1077 | projectDialog, |
| 1068 | 1078 | rename, |
| 1069 | 1079 | showHome, |
| @@ -229,14 +229,6 @@ function Environment({ context, refresh, children }) { | ||
| 229 | 229 | }) |
| 230 | 230 | .catch(() => {}); |
| 231 | 231 | } |
| 232 | 删除: if (ready) return; | |
| 233 | 删除: const action = async (name) => { | |
| 234 | 删除: if (name === "quit") await native("quitNow"); | |
| 235 | 删除: }; | |
| 236 | 删除: window.cageNativeAction = action; | |
| 237 | 删除: return () => { | |
| 238 | 删除: if (window.cageNativeAction === action) delete window.cageNativeAction; | |
| 239 | 删除: }; | |
| 240 | 232 | }, [ready, defaultLocal]); |
| 241 | 233 | const act = async (name, operation) => { |
| 242 | 234 | if (runningAction.current) return; |