跳到主要内容

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

提交记录

同步主线 CI 修复并保留后台退出诊断

合入隔离 CLI 归档夹具、空闲后台状态探测交接等待和安装后统一原生验收。Windows 日志仅新增输出白名单内的 prepareExit 与 prepareStatus,保留原验收条件。 归档与后台更新回归经 race 连续三次通过,PowerShell smoke 报告契约通过,WinForms 构建无警告,Windows/Linux 工作台测试交叉编译通过。两台 Windows 实机当前离线,原生安装复验由 CI 执行。

作者
Lee-xeo
时间
2026/11/09 23:27
提交
008726e
这个版本的全部文件

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

修改desktop/windows/MainWindow.cs+6 −2看文件
@@ -223,6 +223,8 @@ internal sealed class MainWindow : Form
223223 using var shutdown = CancellationTokenSource.CreateLinkedTokenSource(lifetime.Token);
224224 shutdown.CancelAfter(TimeSpan.FromSeconds(20));
225225 var errors = new List<string>();
226新增: int? prepareExit = null;
227新增: string? prepareStatus = null;
226228 if (failure != null) errors.Add(failure);
227229 try
228230 {
@@ -242,6 +244,8 @@ internal sealed class MainWindow : Form
242244 {
243245 if (nativeBridgeReady) smokePhase = "stopping_backend";
244246 var (exit, data) = await Backend.Json(["prepare-update", "--json"], shutdown.Token, TimeSpan.FromSeconds(20));
247新增: prepareExit = exit;
248新增: prepareStatus = data.Text("status") is "prepared" or "stop_required" or "error" ? data.Text("status") : "unexpected";
245249 if (exit != 0 || data.Text("status") != "prepared") throw new IOException("自检结束时无法确认后台已停止");
246250 await Task.WhenAll(controllers.Select(process => process.WaitForExitAsync(shutdown.Token)));
247251 }
@@ -257,7 +261,7 @@ internal sealed class MainWindow : Form
257261 environment.BrowserProcessExited += BrowserExited;
258262 try
259263 {
260删除: if (nativeBridgeReady) smokePhase = "stopping_browser";
264新增: if (nativeBridgeReady && errors.Count == 0) smokePhase = "stopping_browser";
261265 web.Dispose();
262266 await exited.Task.WaitAsync(shutdown.Token);
263267 }
@@ -269,7 +273,7 @@ internal sealed class MainWindow : Form
269273 if (nativeBridgeReady && errors.Count == 0) smokePhase = "completed";
270274 File.WriteAllText(Program.SmokeOutput, JsonSerializer.Serialize(new {
271275 success = nativeBridgeReady && errors.Count == 0, nativeBridgeReady, version = AppUpdater.Version,
272删除: phase = smokePhase, nativeStatus = message.Text, errors, page,
276新增: phase = smokePhase, nativeStatus = message.Text, prepareExit, prepareStatus, errors, page,
273277 pageURL, webviewVersion,
274278 windowBounds = Bounds, workingArea = Screen.FromHandle(Handle).WorkingArea, deviceDpi = DeviceDpi,
275279 nativeMenuBar = MainMenuStrip != null,
修改internal/workbench/cli_channel_test.go+14 −1看文件
@@ -137,7 +137,20 @@ func TestImportedCLIUUIDIsIndependentOfPublicSessionID(t *testing.T) {
137137func TestArchivedCLIHistoryIsNotRediscovered(t *testing.T) {
138138 s, id, project := metadataFixture(t)
139139 home, _ := filepath.EvalSymlinks(t.TempDir())
140删除: mobileTestSSH(t, s, home, []string{"HOME=" + home, "PATH=/usr/bin:/bin:/usr/local/bin", "CLAUDE_CONFIG_DIR=" + filepath.Join(home, ".claude")})
140新增: bin := filepath.Join(home, "bin")
141新增: if err := os.MkdirAll(bin, 0700); err != nil {
142新增: t.Fatal(err)
143新增: }
144新增: // This archived history has no live CLI process. Keep the real discovery
145新增: // helper and SSH path independent of a developer's installed Claude CLI.
146新增: cli := "#!/bin/sh\n[ \"$#\" -eq 2 ] && [ \"$1\" = agents ] && [ \"$2\" = --json ] || exit 64\nprintf '[]\\n'\n"
147新增: if err := os.WriteFile(filepath.Join(bin, "claude"), []byte(cli), 0700); err != nil {
148新增: t.Fatal(err)
149新增: }
150新增: if err := os.WriteFile(filepath.Join(home, ".bash_profile"), []byte("export PATH="+shellescape.Quote(bin)+":/usr/bin:/bin\n"), 0600); err != nil {
151新增: t.Fatal(err)
152新增: }
153新增: mobileTestSSH(t, s, home, []string{"HOME=" + home, "PATH=" + bin + ":/usr/bin:/bin", "CLAUDE_CONFIG_DIR=" + filepath.Join(home, ".claude")})
141154 record, err := s.mobileCLI.record(s.profile, id)
142155 if err != nil {
143156 t.Fatal(err)
修改internal/workbench/control_lifecycle_test.go+68 −0看文件
@@ -194,3 +194,71 @@ func TestPrepareUpdateDoesNotAcceptUnresponsiveLockedController(t *testing.T) {
194194 t.Fatal("locked offline service accepted as safe to replace")
195195 }
196196}
197新增:
198新增:func TestPrepareUpdateWaitsForRoutineProbeAndPreservesActiveWork(t *testing.T) {
199新增: for _, activeJob := range []bool{false, true} {
200新增: t.Run(strconv.FormatBool(activeJob), func(t *testing.T) {
201新增: s := testServer(t)
202新增: var err error
203新增: s.identity, err = currentController()
204新增: if err != nil {
205新增: t.Fatal(err)
206新增: }
207新增: lock, err := openControllerLock(s.profile, os.O_CREATE|os.O_RDWR)
208新增: if err != nil {
209新增: t.Fatal(err)
210新增: }
211新增: defer lock.Close()
212新增: if err := lockController(lock); err != nil {
213新增: t.Fatal(err)
214新增: }
215新增: defer unlockController(lock)
216新增: var stopped atomic.Bool
217新增: shutdownDone := make(chan struct{})
218新增: s.shutdown = func() {
219新增: stopped.Store(true)
220新增: _ = unlockController(lock)
221新增: close(shutdownDone)
222新增: }
223新增: server := httptest.NewServer(s.handler())
224新增: defer server.Close()
225新增: _, portString, _ := net.SplitHostPort(server.Listener.Addr().String())
226新增: port, _ := strconv.Atoi(portString)
227新增: s.origin = "http://localhost:" + portString
228新增: if err := writePrivate(filepath.Join(s.profile, "control.json"), controlFile{Port: port, Token: s.token, PID: os.Getpid(), Controller: s.identity}); err != nil {
229新增: t.Fatal(err)
230新增: }
231新增: if activeJob {
232新增: s.setJobForTest(Job{ID: "active", Running: true})
233新增: }
234新增: // The first handoff reaches a real occupied operation lock. A
235新增: // routine probe releases it without creating a user job or VM.
236新增: s.op.Lock()
237新增: released := make(chan struct{})
238新增: go func() {
239新增: time.Sleep(100 * time.Millisecond)
240新增: s.op.Unlock()
241新增: close(released)
242新增: }()
243新增: result, err := PrepareUpdate(s.configPath, false)
244新增: <-released
245新增: if result.Status == "prepared" {
246新增: select {
247新增: case <-shutdownDone:
248新增: case <-time.After(time.Second):
249新增: t.Fatal("prepared update did not finish shutting down")
250新增: }
251新增: }
252新增: if err != nil {
253新增: t.Fatal(err)
254新增: }
255新增: if activeJob {
256新增: if result.Status != "stop_required" || stopped.Load() {
257新增: t.Fatalf("active work was not preserved: %+v stopped=%v", result, stopped.Load())
258新增: }
259新增: } else if result.Status != "prepared" || !stopped.Load() {
260新增: t.Fatalf("routine probe prevented idle update: %+v stopped=%v", result, stopped.Load())
261新增: }
262新增: })
263新增: }
264新增:}
修改internal/workbench/desktop.go+27 −7看文件
@@ -276,15 +276,35 @@ func PrepareUpdate(configPath string, stop bool) (DesktopResult, error) {
276276 return DesktopResult{Status: "prepared"}, nil
277277 }
278278 if c.launch.Controller.Protocol == controlProtocol {
279删除: status, err := c.call("POST", "/api/handoff", map[string]string{"token": c.record.Token}, nil)
280删除: if err != nil {
281删除: return DesktopResult{}, err
282删除: }
283删除: if status == http.StatusOK {
284删除: if err = c.waitForExit(); err != nil {
279新增: // Routine status probes also hold the operation lock. Retry briefly.
280新增: // every request still checks running jobs, terminals and VM ownership.
281新增: handoffCtx, cancelHandoff := context.WithTimeout(ctx, 3*time.Second)
282新增: defer cancelHandoff()
283新增: conflicted := false
284新增: handoff:
285新增: for {
286新增: status, err := c.callContext(handoffCtx, "POST", "/api/handoff", map[string]string{"token": c.record.Token}, nil)
287新增: if err != nil {
288新增: if conflicted && handoffCtx.Err() != nil {
289新增: break
290新增: }
285291 return DesktopResult{}, err
286292 }
287删除: return DesktopResult{Status: "prepared"}, nil
293新增: if status == http.StatusOK {
294新增: if err = c.waitForExit(); err != nil {
295新增: return DesktopResult{}, err
296新增: }
297新增: return DesktopResult{Status: "prepared"}, nil
298新增: }
299新增: if status != http.StatusConflict {
300新增: break
301新增: }
302新增: conflicted = true
303新增: select {
304新增: case <-handoffCtx.Done():
305新增: break handoff
306新增: case <-time.After(50 * time.Millisecond):
307新增: }
288308 }
289309 }
290310 return DesktopResult{Status: "stop_required", Message: "请保存文件后确认停止环境并安装更新。终端任务会结束,项目和登录状态会保留。"}, nil
修改scripts/test-windows-install.ps1+8 −12看文件
@@ -5,7 +5,6 @@ param([Parameter(Mandatory)][string]$Installer)
55. (Join-Path $PSScriptRoot 'windows-common.ps1')
66if (-not $IsWindows) { throw 'Installation smoke tests must run on Windows.' }
77$target = Join-Path $env:LOCALAPPDATA ('Programs/Cage-test-' + [guid]::NewGuid().ToString('N'))
8删除:$report = Join-Path ([IO.Path]::GetTempPath()) ('cage-smoke-' + [guid]::NewGuid().ToString('N') + '.json')
98$savedKey = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\ClaudeCage'
109if (Test-Path $savedKey) { throw 'Use a disposable Windows user without an existing Cage installation.' }
1110$fixture = Join-Path $PSScriptRoot 'personal-data-fixture.mjs'
@@ -74,17 +73,10 @@ Invoke-BuildTool (Join-Path $target 'resources/cage.exe') @('verify-web-assets')
7473Invoke-BuildTool (Join-Path $target 'resources/mihomo.exe') @('-v')
7574Invoke-BuildTool (Join-Path $target 'resources/runtime/qemu/qemu-system-x86_64.exe') @('--version')
7675Invoke-BuildTool (Join-Path $target 'resources/runtime/openssh/ssh.exe') @('-V')
77删除:$savedProfile = $env:CLAUDE_CAGE_CONFIG
78删除:try {
79删除: # The UI test owns a separate profile; the installer must preserve the
80删除: # pre-existing default profile without asking the app to parse test bytes.
81删除: $env:CLAUDE_CAGE_CONFIG = Join-Path ([IO.Path]::GetTempPath()) ('cage-ui-profile-' + [guid]::NewGuid().ToString('N') + '/config.json')
82删除: $window = Start-Process -FilePath (Join-Path $target 'Cage.exe') -ArgumentList @('--smoke-test', "`"$report`"") -PassThru
83删除: if (-not $window.WaitForExit(180000)) { throw 'Cage WebView2/workbench smoke test timed out.' }
84删除: if ($window.ExitCode -ne 0 -or -not (Test-Path -LiteralPath $report)) { throw "Cage desktop smoke test failed ($($window.ExitCode))." }
85删除:} finally { $env:CLAUDE_CAGE_CONFIG = $savedProfile }
76新增:# Use the same isolated profile, process lifetime and retained diagnostics as
77新增:# build acceptance. The pre-existing default profile holds preservation markers.
78新增:Assert-WindowsWorkbench -AppDirectory $target
8679Assert-PersonalData
87删除:Get-Content -LiteralPath $report
8880# A locked installed executable must fail before replacing the installation.
8981$before = (Get-FileHash -LiteralPath (Join-Path $target 'Cage.exe') -Algorithm SHA256).Hash
9082$locked = [IO.File]::Open((Join-Path $target 'Cage.exe'), [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::Read)
@@ -109,11 +101,15 @@ Assert-PersonalData
109101$uninstall = Start-Process -FilePath (Join-Path $target 'Uninstall.exe') -ArgumentList @('/S') -PassThru
110102if (-not $uninstall.WaitForExit(120000) -or $uninstall.ExitCode -ne 0) { throw 'Uninstall failed.' }
111103# NSIS may relaunch its uninstaller from TEMP so that it can delete the original.
104新增:# The launcher can disappear before the worker clears registration and shortcuts.
112105$deadline = [DateTime]::UtcNow.AddSeconds(120)
113删除:while ((Test-Path -LiteralPath (Join-Path $target 'Uninstall.exe')) -and [DateTime]::UtcNow -lt $deadline) { Start-Sleep -Milliseconds 200 }
106新增:while (((Test-Path -LiteralPath $target) -or (Test-Path $savedKey) -or
107新增: (Test-Path -LiteralPath $desktopShortcut) -or (Test-Path -LiteralPath $startMenuDirectory)) -and
108新增: [DateTime]::UtcNow -lt $deadline) { Start-Sleep -Milliseconds 200 }
114109if (Test-Path -LiteralPath (Join-Path $target 'Cage.exe')) { throw 'Uninstall left Cage.exe behind.' }
115110if (Test-Path -LiteralPath (Join-Path $target 'Uninstall.exe')) { throw 'Uninstall left its launcher behind.' }
116111if (Test-Path -LiteralPath $target) { throw 'Uninstall left packaged files or directories that would block installation into the same folder.' }
112新增:if (Test-Path $savedKey) { throw 'Uninstall left the Cage registration behind.' }
117113Assert-PersonalData
118114Assert-Shortcuts $false $false
119115Write-Host 'Install, WebView2 workbench, reinstall, uninstall and user-data preservation passed. VM startup was not tested.'
修改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')) {