跳到主要内容

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

提交记录

Merge pull request #11 from Flysky701/codex/windows-background-quit

fix(windows): 静默启动后台并允许桌面在 CLI 断线后退出

作者
Shihao Li
时间
2026/11/09 23:45
提交
b5db6d1
这个版本的全部文件

这是一个合并提交,下面是和第一个上一提交相比的改动。

修改cmd/cage-client/main.go+2 −0看文件
@@ -17,6 +17,7 @@ import (
1717 "github.com/sylvinus/agent-vm/internal/agentcli"
1818 "github.com/sylvinus/agent-vm/internal/cage"
1919 "github.com/sylvinus/agent-vm/internal/diagnostics"
20新增: "github.com/sylvinus/agent-vm/internal/host"
2021 "github.com/sylvinus/agent-vm/internal/version"
2122 "github.com/sylvinus/agent-vm/internal/workbench"
2223)
@@ -179,6 +180,7 @@ func relay(config string) error {
179180 defer out.Close()
180181 defer stderr.Close()
181182 cmd.Stdout, cmd.Stderr = out, stderr
183新增: host.HideCommandWindow(cmd)
182184 if err := cmd.Start(); err != nil {
183185 return err
184186 }
修改docs/troubleshooting.md+1 −0看文件
@@ -147,6 +147,7 @@ Cage 不自动读取主机上的 Claude 登录。请在 Cage 终端运行 `claud
147147| 网页复制按钮显示成功,本机粘贴仍是旧内容 | 保持网页和 Cage 窗口在前台重试。已有页面若改写了复制 API,可刷新后再试;复杂 DOM 选区、图片、富文本或超长文字可使用复制快捷键及“文本传递”面板。 |
148148| 停止后旧终端不见了 | 停止虚拟机会结束进程。磁盘和登录态保留,但需要新建终端。 |
149149| 关掉窗口后任务还在运行 | 关闭窗口保留环境;需要结束时选择“停止环境并退出”。 |
150新增:| 已在命令行关闭 Cage 后台,桌面窗口还开着 | 从应用菜单选择“退出 Cage”(Windows 也可使用托盘菜单)。若提示无法确认环境状态,选择“仅退出桌面应用”。重新连接后可查看环境和任务状态。 |
150151| 修改设置后无法正常使用 | “设置 → 环境与恢复”可恢复上一份配置;此操作需要停止并重启环境,已结束的终端不能恢复。 |
151152
152153## 页面与出口状态
修改docs/windows.md+1 −1看文件
@@ -40,7 +40,7 @@ Windows 快捷键以 `Ctrl` 为主:`Ctrl+O` 打开项目、`Ctrl+T` 新建网
4040
4141窗口仅保留系统标题栏,工作台直接占据下方区域。文件、项目和设置操作使用工作台入口与快捷键;检查应用更新和版本信息可从托盘图标的右键菜单打开。窗口首次打开时按当前屏幕的可用区域居中,并适配 Windows 显示缩放。手动调整后的窗口尺寸和最大化状态会保存;换屏或降低分辨率时,窗口保持在当前屏幕内。后台启动与版本检测不显示命令行窗口。
4242
43删除:关闭窗口会保留环境与后台任务,可从托盘图标重新打开;停止环境或选择停止后退出会结束终端。重新打开应用可连接仍运行的会话。
43新增:从开始菜单打开 Cage 时,完整版和轻量客户端的后台服务都会静默启动。关闭工作台窗口会保留环境与后台任务,可从托盘图标重新打开。要退出桌面程序,在托盘菜单选择“退出 Cage”。本机环境仍在运行时,可以选择保留任务或停止环境;停止环境会结束其中的终端。
4444
4545浏览器上传通过本机文件选择窗口选取文件;下载完成可用 Windows“另存为”选择位置。侧栏“下载”提供打开文件、在资源管理器中显示与再次另存为,取消保存窗口时保留默认 Downloads 中的文件。操作与限制见[浏览器上传与下载](getting-started.md#浏览器上传与下载)。
4646
修改internal/host/runtime_unix.go+4 −0看文件
@@ -2,5 +2,9 @@
22
33package host
44
5新增:import "os/exec"
6新增:
7新增:func HideCommandWindow(cmd *exec.Cmd) {}
8新增:
59func ConfigureWindowsRuntime() error { return nil }
610func windowsHypervisorReady() error { return nil }
修改internal/host/runtime_windows.go+11 −0看文件
@@ -3,14 +3,25 @@ package host
33import (
44 "fmt"
55 "os"
6新增: "os/exec"
67 "path/filepath"
78 "runtime"
89 "strings"
10新增: "syscall"
911 "unsafe"
1012
1113 "golang.org/x/sys/windows"
1214)
1315
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新增:
1425// ConfigureWindowsRuntime uses only the runtime shipped next to cage.exe.
1526// The install does not modify the user's system PATH or SSH configuration.
1627func ConfigureWindowsRuntime() error {
新增internal/host/runtime_windows_test.go+44 −0看文件
@@ -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新增:}
修改internal/remotehost/local_session.go+1 −2看文件
@@ -7,7 +7,6 @@ import (
77 "net/http"
88 "net/url"
99 "sync"
10删除: "syscall"
1110 "time"
1211)
1312
@@ -27,7 +26,7 @@ func LocalSession(ctx context.Context, origin string, manifest PublicManifest, j
2726 return nil, errors.New("本机服务地址已改变")
2827 }
2928 conn, err := dial.DialContext(ctx, "tcp4", endpoint)
30删除: if errors.Is(err, syscall.ECONNREFUSED) {
29新增: if errors.Is(err, connectionRefused) {
3130 cancel()
3231 }
3332 return conn, err
新增internal/remotehost/local_session_unix.go+7 −0看文件
@@ -0,0 +1,7 @@
1新增://go:build !windows
2新增:
3新增:package remotehost
4新增:
5新增:import "syscall"
6新增:
7新增:const connectionRefused = syscall.ECONNREFUSED
新增internal/remotehost/local_session_windows.go+6 −0看文件
@@ -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
修改internal/workbench/desktop_file_open.go+3 −1看文件
@@ -15,6 +15,8 @@ import (
1515 "runtime"
1616 "strings"
1717 "time"
18新增:
19新增: "github.com/sylvinus/agent-vm/internal/host"
1820)
1921
2022type desktopFileOpen struct {
@@ -270,7 +272,7 @@ func openHostFile(path, action string) error {
270272 defer cancel()
271273 command := hostFileCommand(runtime.GOOS, path, action, info.IsDir())
272274 cmd := exec.CommandContext(ctx, command.Path, command.Args[1:]...)
273删除: hideCommand(cmd)
275新增: host.HideCommandWindow(cmd)
274276 if err = cmd.Run(); err != nil {
275277 if runtime.GOOS != "linux" || action != "reveal" {
276278 return errors.New("无法打开本机文件或文件管理器,请检查默认应用和文件权限")
修改internal/workbench/environment_versions.go+2 −1看文件
@@ -10,6 +10,7 @@ import (
1010 "time"
1111
1212 "github.com/sylvinus/agent-vm/internal/cage"
13新增: "github.com/sylvinus/agent-vm/internal/host"
1314 "github.com/sylvinus/agent-vm/internal/managedproxy"
1415)
1516
@@ -102,7 +103,7 @@ CAGE_VERSIONS`)
102103 if core, err := managedproxy.CorePath(); err == nil {
103104 probeCtx, done := context.WithTimeout(ctx, 2*time.Second)
104105 cmd := exec.CommandContext(probeCtx, core, "-v")
105删除: hideCommand(cmd)
106新增: host.HideCommandWindow(cmd)
106107 b, e := cmd.Output()
107108 done()
108109 if e == nil {
修改internal/workbench/macos_guest.go+2 −1看文件
@@ -15,6 +15,7 @@ import (
1515
1616 "github.com/sylvinus/agent-vm/internal/cage"
1717 "github.com/sylvinus/agent-vm/internal/guestos"
18新增: "github.com/sylvinus/agent-vm/internal/host"
1819)
1920
2021// 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
5253 }
5354 cmd := exec.CommandContext(ctx, sshExecutable(), append(base, args...)...)
5455 cmd.Env = sshEnvironment()
55删除: hideCommand(cmd)
56新增: host.HideCommandWindow(cmd)
5657 return cmd
5758}
5859
修改internal/workbench/macos_login.go+2 −1看文件
@@ -14,6 +14,7 @@ import (
1414 "time"
1515
1616 "github.com/sylvinus/agent-vm/internal/guestos"
17新增: "github.com/sylvinus/agent-vm/internal/host"
1718)
1819
1920// Only installer-created bindings carry this identity. A damaged binding stays
@@ -315,6 +316,6 @@ func (s *Server) macOSSetupAdminCommand(ctx context.Context) *exec.Cmd {
315316 }
316317 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")...)
317318 cmd.Env = sshEnvironment()
318删除: hideCommand(cmd)
319新增: host.HideCommandWindow(cmd)
319320 return cmd
320321}
修改internal/workbench/macos_password_sync.go+2 −1看文件
@@ -15,6 +15,7 @@ import (
1515
1616 "al.essio.dev/pkg/shellescape"
1717 "github.com/sylvinus/agent-vm/internal/guestos"
18新增: "github.com/sylvinus/agent-vm/internal/host"
1819)
1920
2021func (s *Server) syncMacGuestPassword(ctx context.Context) error {
@@ -50,7 +51,7 @@ func (s *Server) applyMacGuestPassword(ctx context.Context, id uuid.UUID, oldPas
5051 command := func(ctx context.Context, script string) *exec.Cmd {
5152 cmd := exec.CommandContext(ctx, sshExecutable(), append(append([]string{}, args...), "-T", "cage-macos", "--", "exec /bin/sh -ec "+shellescape.Quote(script))...)
5253 cmd.Env = sshEnvironment()
53删除: hideCommand(cmd)
54新增: host.HideCommandWindow(cmd)
5455 return cmd
5556 }
5657 // Use this build's helper so older managed guests can adopt the shared
修改internal/workbench/platform_unix.go+0 −1看文件
@@ -24,7 +24,6 @@ func processExists(pid int) bool {
2424}
2525func terminateLegacy(pid int) error { return syscall.Kill(pid, syscall.SIGTERM) }
2626func detachController(cmd *exec.Cmd) { cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true} }
27删除:func hideCommand(cmd *exec.Cmd) {}
2827func sshExecutable() string { return "/usr/bin/ssh" }
2928func sshEnvironment() []string {
3029 return []string{"PATH=/usr/bin:/bin:/usr/sbin:/sbin", "LANG=C", "LC_ALL=C", "TERM=xterm-256color"}
修改internal/workbench/platform_windows.go+0 −3看文件
@@ -35,9 +35,6 @@ func terminateLegacy(pid int) error {
3535func detachController(cmd *exec.Cmd) {
3636 cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true, CreationFlags: windows.CREATE_NEW_PROCESS_GROUP | windows.CREATE_NO_WINDOW}
3737}
38删除:func hideCommand(cmd *exec.Cmd) {
39删除: cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true, CreationFlags: windows.CREATE_NO_WINDOW}
40删除:}
4138func sshExecutable() string {
4239 exe, _ := os.Executable()
4340 bundled := filepath.Join(filepath.Dir(exe), "runtime", "openssh", "ssh.exe")
修改internal/workbench/runtime.go+3 −2看文件
@@ -18,6 +18,7 @@ import (
1818 "github.com/sylvinus/agent-vm/internal/containerenv"
1919 "github.com/sylvinus/agent-vm/internal/diagnostics"
2020 "github.com/sylvinus/agent-vm/internal/guestos"
21新增: "github.com/sylvinus/agent-vm/internal/host"
2122 "github.com/sylvinus/agent-vm/internal/hostimage"
2223 "github.com/sylvinus/agent-vm/internal/managedproxy"
2324)
@@ -91,7 +92,7 @@ func (s *Server) sshCommandOptions(ctx context.Context, maintenance bool, args .
9192 base = append(base, args...)
9293 cmd := exec.CommandContext(ctx, sshExecutable(), base...)
9394 cmd.Env = sshEnvironment()
94删除: hideCommand(cmd)
95新增: host.HideCommandWindow(cmd)
9596 return cmd
9697}
9798func (s *Server) guest(ctx context.Context, script string) ([]byte, error) {
@@ -272,7 +273,7 @@ func (s *Server) runCage(args ...string) error {
272273 defer cancel()
273274 }
274275 cmd := exec.CommandContext(ctx, s.exe, args...)
275删除: hideCommand(cmd)
276新增: host.HideCommandWindow(cmd)
276277 cmd.Dir = s.environmentDir()
277278 if cmd.Dir == "" {
278279 cmd.Dir = s.profile
修改internal/workbench/windows_network.go+2 −1看文件
@@ -20,6 +20,7 @@ import (
2020 "github.com/containers/gvisor-tap-vsock/pkg/virtualnetwork"
2121 "github.com/sylvinus/agent-vm/internal/cage"
2222 "github.com/sylvinus/agent-vm/internal/guestos"
23新增: "github.com/sylvinus/agent-vm/internal/host"
2324)
2425
2526type windowsHostNetwork struct {
@@ -52,7 +53,7 @@ func (s *Server) startWindowsNetwork() error {
5253 cmd.Env = append(os.Environ(), cage.ConfigEnv+"="+s.configPath)
5354 cmd.Stdout = io.Discard
5455 cmd.Stderr = io.Discard
55删除: hideCommand(cmd)
56新增: host.HideCommandWindow(cmd)
5657 if err := cmd.Start(); err != nil {
5758 cancel()
5859 close(process.done)
修改scripts/windows-common.ps1+2 −0看文件
@@ -48,6 +48,8 @@ function Assert-WindowsWorkbenchReport {
4848 if ((Get-Item -LiteralPath $Report).Length -gt 65536) { throw 'Cage smoke report exceeds the bounded diagnostic size.' }
4949 $result = Get-Content -LiteralPath $Report -Raw | ConvertFrom-Json -AsHashtable
5050 $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'] }
5153 if ($result['page'] -is [System.Collections.IDictionary] -and $result['page']['errors']) {
5254 $safe.jsErrors = @($result['page']['errors'] | Select-Object -First 8 | ForEach-Object {
5355 if ($_ -isnot [System.Collections.IDictionary]) { return }
修改scripts/windows-workbench-smoke.test.ps1+2 −1看文件
@@ -31,6 +31,7 @@ try {
3131 [IO.File]::WriteAllText($childScript, '[IO.File]::Copy($args[0],$args[1],$true); exit 17')
3232 @{
3333 success = $false; nativeBridgeReady = $false; phase = 'loading_workbench'
34新增: prepareExit = 1; prepareStatus = 'stop_required'
3435 nativeStatus = 'failed http://localhost:1234/?token=private-token#private-fragment'
3536 entryJSON = 'private-entry'; pageURL = 'http://localhost:1234/#private-launch'
3637 page = @{ text = 'private-page-body'; errors = @(
@@ -52,7 +53,7 @@ try {
5253 } 6>&1
5354 $text = ($captured | ForEach-Object { $_.ToString() }) -join "`n"
5455 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"')) {
5657 Assert-SmokeContract ($text.Contains($expected)) "Missing safe smoke evidence: $expected"
5758 }
5859 foreach ($private in @('private-token','private-fragment','private-query','private-entry','private-launch','private-page-body')) {
修改ui/scripts/initialization-smoke.mjs+5 −0看文件
@@ -98,8 +98,13 @@ for (const [platform, system] of [["darwin", "macos"], ["windows", "windows-11"]
9898 rejectComplete = false;
9999 await page.getByRole("button", { name: "进入工作台", exact: true }).click();
100100 await page.getByRole("complementary", { name: "项目与终端" }).waitFor();
101新增: await page.evaluate(() => window.cageNativeAction("settings"));
102新增: await page.getByRole("region", { name: "设置", exact: true }).waitFor();
101103 await page.reload();
102104 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();
103108 assert.equal(await page.getByRole("heading", { name: "为 Cage 准备独立环境" }).count(), 0);
104109 assert.deepEqual(errors, []);
105110 console.log(`PASS ${platform}: independent initialization, inline keyboard selection, back navigation, progress, refresh, retry, completion gate and reopen`);
修改ui/scripts/macos-first-setup-smoke.mjs+5 −0看文件
@@ -72,6 +72,11 @@ for (const failure of ["http", "native"]) {
7272 assert.ok(await retry.isVisible(), "checking permissions hid the completion retry");
7373 await retry.click();
7474 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();
7580 assert.equal(calls.filter(c=>c==="finish").length,2);
7681 assert.equal(calls.filter(c=>c==="verify-projects").length,0);
7782 assert.deepEqual(errors, []);
新增ui/scripts/offline-quit-smoke.mjs+51 −0看文件
@@ -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新增:}
修改ui/src/account.jsx+0 −9看文件
@@ -244,15 +244,6 @@ export function AccountGate({ children }) {
244244 setBusy(true);
245245 deviceAction("unlock", "automatic").catch((e) => setError(e.message)).finally(() => setBusy(false));
246246 }, [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]);
256247 if (account?.unlocked) return children;
257248 const creating = account && !account.exists;
258249 const rememberThisDevice = rememberLogin ?? Boolean(creating || account?.trusted_login || account?.devices?.automatic);
修改ui/src/api.js+28 −5看文件
@@ -3,6 +3,7 @@ import { httpErrorMessage, connectionErrorMessage, operationName, nativeFailureM
33import { assertConnection, connectionHeaders, getClientContext, isProjectSharesPath } from "./client-context.mjs";
44import { installAgentNativeConsumer } from "./agent-native.js";
55let sessionRenewal;
6新增:class WorkbenchUnreachable extends Error {}
67async function responseError(response, path, method = "GET") {
78 const error = new Error(
89 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 } = {}) {
4546 catch (error) {
4647 if (signal?.aborted) throw signal.reason;
4748 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 });
4952 }
5053 };
5154 let response = await send();
@@ -102,11 +105,31 @@ export async function uploadFile(path, file, { signal, onProgress } = {}) {
102105const nativeBridge = () =>
103106 window.cageNativeBridge || window.webkit?.messageHandlers?.cage;
104107export 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新增:}
105126export 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);
110133 }
111134 try {
112135 const result = await nativeBridge().postMessage({ action, ...extra, connection_id: connection });
修改ui/src/client-context.mjs+1 −1看文件
@@ -1,4 +1,4 @@
1删除:let current = Object.freeze({ mode: "local", connection_id: "local" });
1新增:let current = Object.freeze({ mode: "none", connection_id: "" });
22
33export function setClientContext(value) {
44 current = Object.freeze({ ...value });
修改ui/src/client-context.test.mjs+89 −0看文件
@@ -52,6 +52,95 @@ test("quitting a remote client never suspends the cloud account", async (t) => {
5252 assert.deepEqual(request, { action: "quitNow", connection_id: "first" });
5353});
5454
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新增:
55144test("an account device operation retains its host generation and rejects a late result", async (t) => {
56145 environment(t);
57146 let release;
修改ui/src/desktop-entry.jsx+6 −0看文件
@@ -3,11 +3,17 @@ import { createRoot } from "react-dom/client";
33import { installDiagnostics } from "./diagnostics.mjs";
44import { DiagnosticBoundary } from "./diagnostics.jsx";
55import { ClientRoot } from "./remote-hosts";
6新增:import { native } from "./api";
67import "./style.css";
78
89const Workbench = lazy(() => import("./main.jsx"));
910
1011installDiagnostics();
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新增:};
1117createRoot(document.getElementById("root")).render(
1218 <DiagnosticBoundary>
1319 <ClientRoot>
修改ui/src/initialization.jsx+2 −2看文件
@@ -124,8 +124,8 @@ function Initialization({ initial, onComplete }) {
124124 pollNow.current = poll;
125125 poll();
126126 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; };
129129 }, [account?.guest_system]);
130130
131131 async function run(operation) {
修改ui/src/macos-first-setup.jsx+2 −2看文件
@@ -55,13 +55,13 @@ export function MacOSFirstSetup() {
5555 if (active) timer = setTimeout(poll, 2000);
5656 }
5757 poll();
58删除: window.cageNativeAction = async command => {
58新增: window.cageWorkbenchAction = async command => {
5959 if (command === "closeTab") document.dispatchEvent(new Event("cage-close-modal"));
6060 if (command === "quit") await native("quitNow");
6161 };
6262 window.cageEditAction = () => false;
6363 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; };
6565 }, []);
6666 async function act(action) {
6767 if (busy) return;
修改ui/src/main.jsx+12 −2看文件
@@ -957,7 +957,7 @@ function App() {
957957 return terminalControls.current.get(current.id)?.edit(command) || false;
958958 return remote.current?.edit(command) || false;
959959 };
960删除: window.cageNativeAction = async (command) => {
960新增: window.cageWorkbenchAction = async (command) => {
961961 if (document.querySelector(".mac-login-fullscreen")) {
962962 if (command === "closeTab" || command === "quit") document.dispatchEvent(new Event("cage-close-modal"));
963963 if (command !== "quit") return;
@@ -1031,6 +1031,15 @@ function App() {
10311031 await native("quitNow");
10321032 return;
10331033 }
1034新增: if (connectionError || fatal) {
1035新增: setDialog({
1036新增: title: "退出 Cage",
1037新增: body: "工作台连接已中断,暂时无法确认环境状态。仍在运行的后台任务会继续。",
1038新增: confirm: "仅退出桌面应用",
1039新增: resolve: (confirmed) => confirmed && native("quitNow"),
1040新增: });
1041新增: return;
1042新增: }
10341043 setDialog({
10351044 title: "退出 Cage",
10361045 body: "退出前请保存文件和设置。可以保留环境,让后台任务继续运行;下次打开会重新连接。",
@@ -1048,7 +1057,7 @@ function App() {
10481057 };
10491058 return () => {
10501059 window.removeEventListener("keydown", key, true);
1051删除: delete window.cageNativeAction;
1060新增: delete window.cageWorkbenchAction;
10521061 delete window.cageEditAction;
10531062 };
10541063 }, [
@@ -1064,6 +1073,7 @@ function App() {
10641073 busy,
10651074 active,
10661075 connectionError,
1076新增: fatal,
10671077 projectDialog,
10681078 rename,
10691079 showHome,
修改ui/src/remote-hosts.jsx+0 −8看文件
@@ -229,14 +229,6 @@ function Environment({ context, refresh, children }) {
229229 })
230230 .catch(() => {});
231231 }
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删除: };
240232 }, [ready, defaultLocal]);
241233 const act = async (name, operation) => {
242234 if (runningAction.current) return;