跳到主要内容

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

提交记录
修改desktop/windows.tests/Program.cs+37 −0看文件
@@ -1,5 +1,12 @@
11using Cage.Windows;
22
3新增:if (args is ["smoke-wait", var smokeRelease])
4新增:{
5新增: using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(10));
6新增: while (!File.Exists(smokeRelease)) await Task.Delay(20, deadline.Token);
7新增: return;
8新增:}
9新增:
310if (args is ["app-update", "check" or "download"])
411{
512 File.AppendAllText(Path.Combine(Backend.Root, "retry-invocations"), "x");
@@ -175,6 +182,36 @@ try
175182 var executable = Path.Combine(nativeResources, "cage.exe");
176183 File.Copy(Environment.ProcessPath!, executable, true);
177184 if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(executable, File.GetUnixFileMode(Environment.ProcessPath!));
185新增: var release = Path.Combine(integration, "smoke-release");
186新增: using (var owned = System.Diagnostics.Process.Start(Backend.StartInfo(executable, "smoke-wait", release))!)
187新增: {
188新增: var record = Path.Combine(Backend.Root, "control.json");
189新增: Directory.CreateDirectory(Backend.Root);
190新增: var controllers = new List<System.Diagnostics.Process>();
191新增: try
192新增: {
193新增: File.WriteAllText(record, System.Text.Json.JsonSerializer.Serialize(new { pid = Environment.ProcessId }));
194新增: var foreignRejected = false;
195新增: try { Backend.CaptureSmokeControllers(); } catch (IOException) { foreignRejected = true; }
196新增: Check(foreignRejected, "smoke captured a controller outside its application executable");
197新增: File.WriteAllText(record, System.Text.Json.JsonSerializer.Serialize(new { pid = owned.Id }));
198新增: controllers = Backend.CaptureSmokeControllers();
199新增: Check(controllers.Count == 1 && !controllers[0].HasExited, "smoke did not pin its live controller");
200新增: var exit = controllers[0].WaitForExitAsync();
201新增: Check(!exit.IsCompleted, "smoke considered a still-running controller stopped");
202新增: File.WriteAllText(release, "release owned child");
203新增: await exit.WaitAsync(TimeSpan.FromSeconds(5));
204新增: Check(controllers[0].HasExited, "smoke did not observe actual controller exit");
205新增: }
206新增: finally
207新增: {
208新增: File.WriteAllText(release, "release owned child");
209新增: if (!owned.WaitForExit(5000)) { owned.Kill(); owned.WaitForExit(); }
210新增: foreach (var controller in controllers) controller.Dispose();
211新增: File.Delete(record);
212新增: }
213新增: }
214新增: Console.WriteLine("Windows smoke shutdown: actual controller handle pinned, foreign executable rejected, process exit observed.");
178215 var retryAt = DateTimeOffset.UtcNow.AddHours(1).ToString("yyyy-MM-dd'T'HH:mm:ss'Z'");
179216 Directory.CreateDirectory(Backend.Root);
180217 Environment.SetEnvironmentVariable("CAGE_UPDATE_RETRY_AT", retryAt);
修改desktop/windows/Backend.cs+30 −0看文件
@@ -13,6 +13,36 @@ internal static class Backend
1313 public static string Root => Path.GetDirectoryName(ConfigPath)!;
1414 public static string Executable => Path.Combine(AppContext.BaseDirectory, "resources", "cage.exe");
1515
16新增: public static List<Process> CaptureSmokeControllers()
17新增: {
18新增: var processes = new List<Process>();
19新增: try
20新增: {
21新增: foreach (var profile in new[] { Root, Path.Combine(Root, "desktop-entry") })
22新增: {
23新增: var record = Path.Combine(profile, "control.json");
24新增: if (!File.Exists(record)) continue;
25新增: using var data = JsonDocument.Parse(File.ReadAllText(record));
26新增: Process process;
27新增: try { process = Process.GetProcessById(data.RootElement.GetProperty("pid").GetInt32()); }
28新增: catch (ArgumentException) { continue; } // It already exited.
29新增: try
30新增: {
31新增: // Pin the actual process handle before requesting shutdown.
32新增: // A released profile lock alone does not release its image.
33新增: _ = process.SafeHandle;
34新增: if (process.HasExited) { process.Dispose(); continue; }
35新增: if (!string.Equals(Path.GetFullPath(process.MainModule!.FileName), Path.GetFullPath(Executable), StringComparison.OrdinalIgnoreCase))
36新增: throw new IOException("自检后台身份与当前应用不符,未等待其他程序");
37新增: processes.Add(process);
38新增: }
39新增: catch { process.Dispose(); throw; }
40新增: }
41新增: return processes;
42新增: }
43新增: catch { foreach (var process in processes) process.Dispose(); throw; }
44新增: }
45新增:
1646 public static ProcessStartInfo StartInfo(string executable, params string[] arguments)
1747 {
1848 var start = new ProcessStartInfo(executable) {
修改desktop/windows/MainWindow.cs+35 −7看文件
@@ -143,7 +143,7 @@ internal sealed class MainWindow : Form
143143 }
144144 private async void Script(string script)
145145 {
146删除: if (web.CoreWebView2 == null || IsDisposed) return;
146新增: if (web.IsDisposed || web.CoreWebView2 == null || IsDisposed) return;
147147 try { await web.ExecuteScriptAsync(script); }
148148 catch (InvalidOperationException) { }
149149 catch (System.Runtime.InteropServices.COMException) { }
@@ -217,6 +217,11 @@ internal sealed class MainWindow : Form
217217 if (Program.SmokeOutput == null || completingSmoke) return;
218218 completingSmoke = true;
219219 JsonElement? page = null;
220新增: var pageURL = web.Source?.GetLeftPart(UriPartial.Path);
221新增: var environment = web.CoreWebView2?.Environment;
222新增: var webviewVersion = environment?.BrowserVersionString;
223新增: using var shutdown = CancellationTokenSource.CreateLinkedTokenSource(lifetime.Token);
224新增: shutdown.CancelAfter(TimeSpan.FromSeconds(20));
220225 var errors = new List<string>();
221226 if (failure != null) errors.Add(failure);
222227 try
@@ -232,17 +237,40 @@ internal sealed class MainWindow : Form
232237 }
233238 catch (Exception error) { errors.Add("无法保存工作台画面:" + error.Message); }
234239 }
235删除: var (exit, data) = await Backend.Json(["prepare-update", "--json"], lifetime.Token, TimeSpan.FromSeconds(20));
236删除: if (exit != 0 || data.Text("status") != "prepared") throw new IOException("自检结束时无法确认后台已停止");
240新增: var controllers = Backend.CaptureSmokeControllers();
241新增: try
242新增: {
243新增: if (nativeBridgeReady) smokePhase = "stopping_backend";
244新增: var (exit, data) = await Backend.Json(["prepare-update", "--json"], shutdown.Token, TimeSpan.FromSeconds(20));
245新增: if (exit != 0 || data.Text("status") != "prepared") throw new IOException("自检结束时无法确认后台已停止");
246新增: await Task.WhenAll(controllers.Select(process => process.WaitForExitAsync(shutdown.Token)));
247新增: }
248新增: finally { foreach (var process in controllers) process.Dispose(); }
237249 }
238250 catch (Exception error) { errors.Add(error.Message); }
251新增: // WebView2 releases its processes asynchronously after Dispose. Its
252新增: // browser can retain the app's working directory until this event.
253新增: if (environment != null)
254新增: {
255新增: var exited = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
256新增: void BrowserExited(object? sender, CoreWebView2BrowserProcessExitedEventArgs args) => exited.TrySetResult();
257新增: environment.BrowserProcessExited += BrowserExited;
258新增: try
259新增: {
260新增: if (nativeBridgeReady) smokePhase = "stopping_browser";
261新增: web.Dispose();
262新增: await exited.Task.WaitAsync(shutdown.Token);
263新增: }
264新增: catch (Exception error) { errors.Add("自检浏览器尚未退出:" + error.Message); }
265新增: finally { environment.BrowserProcessExited -= BrowserExited; }
266新增: }
239267 try
240268 {
269新增: if (nativeBridgeReady && errors.Count == 0) smokePhase = "completed";
241270 File.WriteAllText(Program.SmokeOutput, JsonSerializer.Serialize(new {
242271 success = nativeBridgeReady && errors.Count == 0, nativeBridgeReady, version = AppUpdater.Version,
243272 phase = smokePhase, nativeStatus = message.Text, errors, page,
244删除: pageURL = web.Source?.GetLeftPart(UriPartial.Path),
245删除: webviewVersion = web.CoreWebView2?.Environment.BrowserVersionString,
273新增: pageURL, webviewVersion,
246274 windowBounds = Bounds, workingArea = Screen.FromHandle(Handle).WorkingArea, deviceDpi = DeviceDpi,
247275 nativeMenuBar = MainMenuStrip != null,
248276 }));
@@ -480,12 +508,12 @@ internal sealed class MainWindow : Form
480508 case "quitNow": result = true; allowQuit = true; BeginInvoke(Close); break;
481509 default: throw new InvalidDataException("未知原生操作");
482510 }
483删除: web.CoreWebView2.PostWebMessageAsJson(JsonSerializer.Serialize(new { id, result }));
511新增: if (!web.IsDisposed) web.CoreWebView2.PostWebMessageAsJson(JsonSerializer.Serialize(new { id, result }));
484512 }
485513 catch (Exception error)
486514 {
487515 _ = Backend.Report(error.ToString());
488删除: if (id.Length != 0 && !IsDisposed) web.CoreWebView2.PostWebMessageAsJson(JsonSerializer.Serialize(new { id, error = error.Message }));
516新增: if (id.Length != 0 && !IsDisposed && !web.IsDisposed) web.CoreWebView2.PostWebMessageAsJson(JsonSerializer.Serialize(new { id, error = error.Message }));
489517 }
490518 }
491519
修改internal/workbench/agent_transport_test.go+1 −1看文件
@@ -163,7 +163,7 @@ func TestAgentDesktopConfigurationUsesExplicitSelection(t *testing.T) {
163163 if err != nil {
164164 t.Fatal(err)
165165 }
166删除: if err := os.WriteFile(filepath.Join(filepath.Dir(path), "control.json"), record, 0600); err != nil {
166新增: if err := writePrivate(filepath.Join(filepath.Dir(path), "control.json"), json.RawMessage(record)); err != nil {
167167 t.Fatal(err)
168168 }
169169 lock, err := openControllerLock(filepath.Dir(path), os.O_CREATE|os.O_RDWR)
修改internal/workbench/diagnostics_guest_test.go+4 −0看文件
@@ -6,12 +6,16 @@ import (
66 "os"
77 "os/exec"
88 "path/filepath"
9新增: "runtime"
910 "strings"
1011 "testing"
1112 "time"
1213)
1314
1415func TestMacOSGuestDiagnosticCollectorBoundsAndFilters(t *testing.T) {
16新增: if runtime.GOOS == "windows" {
17新增: t.Skip("macOS guest collector requires POSIX directory descriptors and file ownership")
18新增: }
1519 if _, err := exec.LookPath("uv"); err != nil {
1620 t.Skip("uv is required for the guest collector")
1721 }
修改internal/workbench/macos_attachments_test.go+4 −0看文件
@@ -6,6 +6,7 @@ import (
66 "os"
77 "os/exec"
88 "path/filepath"
9新增: "runtime"
910 "strings"
1011 "testing"
1112
@@ -28,6 +29,9 @@ func TestMacOSAttachmentPathRejectsOtherUsersAndEscapes(t *testing.T) {
2829}
2930
3031func TestMacOSTerminalUsesSharedAttachmentReceiver(t *testing.T) {
32新增: if runtime.GOOS == "windows" {
33新增: t.Skip("shared macOS/Linux guest receiver requires POSIX UnixStreamServer")
34新增: }
3135 if _, err := exec.LookPath("uv"); err != nil {
3236 t.Skip("uv is required for the shared Python receiver")
3337 }
修改internal/workbench/macos_guest_test.go+2 −1看文件
@@ -9,6 +9,7 @@ import (
99 "os"
1010 "path/filepath"
1111 "slices"
12新增: "strconv"
1213 "strings"
1314 "testing"
1415
@@ -36,7 +37,7 @@ func TestMacOSConnectionIgnoresSSHConfigOverrides(t *testing.T) {
3637 t.Errorf("untrusted override %q used", value)
3738 }
3839 }
39删除: if !strings.Contains(strings.Join(cmd.Args, " "), filepath.Join(s.profile, "macos-known-hosts")) {
40新增: if !slices.Contains(cmd.Args, "UserKnownHostsFile="+strconv.Quote(filepath.Join(s.profile, "macos-known-hosts"))) {
4041 t.Fatal("missing profile-scoped host key")
4142 }
4243 for _, bad := range []string{"", "Port 0", "Port 65536", "Port 22\nPort 23", "Port 22 -o Anything"} {
修改scripts/ci-windows-build.ps1+13 −11看文件
@@ -66,18 +66,20 @@ try {
6666 '-GuestToolsDirectory', "$repository/_output/windows-amd64/app/resources/guest-os")
6767 }
6868 Invoke-BuildTool 'dotnet' @('run', '--project', 'desktop/windows.tests/Cage.Windows.Tests.csproj')
69删除: Invoke-BuildTool 'go' @('test', './internal/workbench', './internal/appupdate', './internal/host', './internal/managedproxy', './internal/env', './internal/paths', './internal/mounts')
70删除: # Exercise a second volume when the runner keeps its workspace and temp on different drives.
71删除: if ($env:GITHUB_WORKSPACE -and -not $env:CAGE_TEST_STORAGE_VOLUME -and
72删除: [IO.Path]::GetPathRoot($env:GITHUB_WORKSPACE) -ne [IO.Path]::GetPathRoot([IO.Path]::GetTempPath())) {
73删除: $env:CAGE_TEST_STORAGE_VOLUME = $env:GITHUB_WORKSPACE
69新增: Invoke-InIsolatedTestTemp {
70新增: Invoke-BuildTool 'go' @('test', './internal/workbench', './internal/appupdate', './internal/host', './internal/managedproxy', './internal/env', './internal/paths', './internal/mounts')
71新增: # Exercise a second volume when the runner keeps its workspace and temp on different drives.
72新增: if ($env:GITHUB_WORKSPACE -and -not $env:CAGE_TEST_STORAGE_VOLUME -and
73新增: [IO.Path]::GetPathRoot($env:GITHUB_WORKSPACE) -ne [IO.Path]::GetPathRoot([IO.Path]::GetTempPath())) {
74新增: $env:CAGE_TEST_STORAGE_VOLUME = $env:GITHUB_WORKSPACE
75新增: }
76新增: Invoke-BuildTool 'go' @('test', './internal/cage', '-run', 'Test(Storage|Gate|ProxyRevision|ConfigChange|JobStop|CONNECT|SOCKS|DNS|RejectHostLAN|Credentials|ProxyHostname|SafetyReport|Renew)')
77新增: Invoke-BuildTool 'go' @('test', './internal/vm', '-run', 'Test(NetworkConfined|WindowsQEMUIdentity)')
78新增: Invoke-BuildTool 'go' @('test', 'github.com/lima-vm/lima/v2/pkg/driver/qemu', '-run', 'Test(WindowsFirmwareArgument|WindowsPackagedFirmwareBeatsOldUserCopy|WHPXQEMU64Features|WindowsCPUResolution)$')
79新增: Invoke-BuildTool 'go' @('test', 'github.com/lima-vm/lima/v2/pkg/hostagent', '-run', '^TestResourceProbeCommand$')
80新增: Invoke-BuildTool 'go' @('test', 'github.com/lima-vm/lima/v2/pkg/networks/usernet', '-run', 'TestNetstackWindowsNativeSocketPaths')
81新增: Invoke-BuildTool 'go' @('vet', './cmd/cage', './internal/cage', './internal/workbench', './internal/appupdate', './internal/host')
7482 }
75删除: Invoke-BuildTool 'go' @('test', './internal/cage', '-run', 'Test(Storage|Gate|ProxyRevision|ConfigChange|JobStop|CONNECT|SOCKS|DNS|RejectHostLAN|Credentials|ProxyHostname|SafetyReport|Renew)')
76删除: Invoke-BuildTool 'go' @('test', './internal/vm', '-run', 'Test(NetworkConfined|WindowsQEMUIdentity)')
77删除: Invoke-BuildTool 'go' @('test', 'github.com/lima-vm/lima/v2/pkg/driver/qemu', '-run', 'Test(WindowsFirmwareArgument|WindowsPackagedFirmwareBeatsOldUserCopy|WHPXQEMU64Features|WindowsCPUResolution)$')
78删除: Invoke-BuildTool 'go' @('test', 'github.com/lima-vm/lima/v2/pkg/hostagent', '-run', '^TestResourceProbeCommand$')
79删除: Invoke-BuildTool 'go' @('test', 'github.com/lima-vm/lima/v2/pkg/networks/usernet', '-run', 'TestNetstackWindowsNativeSocketPaths')
80删除: Invoke-BuildTool 'go' @('vet', './cmd/cage', './internal/cage', './internal/workbench', './internal/appupdate', './internal/host')
8183 $packageArguments = @{ Release = $Release; SkipBuild = $true }
8284 if ($Release) { $packageArguments.QemuSourceArchive = $qemuSource }
8385 & (Join-Path $PSScriptRoot 'package-windows.ps1') @packageArguments
修改scripts/windows-common.ps1+16 −0看文件
@@ -14,6 +14,22 @@ function Get-WindowsWorkbenchTestBase {
1414 return [IO.Path]::GetTempPath()
1515}
1616
17新增:function Invoke-InIsolatedTestTemp {
18新增: param([Parameter(Mandatory)][scriptblock]$Checks)
19新增: # Windows' default temp is inside AppData, which must remain protected
20新增: # against project sharing. Put test projects in the runner's own temp.
21新增: $directory = Join-Path (Get-WindowsWorkbenchTestBase) ('cage-go-tests-' + [guid]::NewGuid().ToString('N'))
22新增: New-Item -ItemType Directory -Path $directory | Out-Null
23新增: $savedTemp = $env:TEMP; $savedTmp = $env:TMP
24新增: try {
25新增: $env:TEMP = $directory; $env:TMP = $directory
26新增: & $Checks
27新增: } finally {
28新增: $env:TEMP = $savedTemp; $env:TMP = $savedTmp
29新增: Remove-Item -LiteralPath $directory -Recurse -Force -ErrorAction SilentlyContinue
30新增: }
31新增:}
32新增:
1733function ConvertTo-SmokeSafeText {
1834 param($Value)
1935 if ($Value -isnot [string]) { return '' }
修改scripts/windows-workbench-smoke.test.ps1+16 −0看文件
@@ -7,6 +7,22 @@ function Assert-SmokeContract([bool]$Condition, [string]$Message) { if (-not $Co
77try {
88 $env:RUNNER_TEMP = Join-Path $directory 'runner-temp'
99 Assert-SmokeContract ((Get-WindowsWorkbenchTestBase) -eq [IO.Path]::GetFullPath($env:RUNNER_TEMP)) 'CI report directory ignores RUNNER_TEMP.'
10新增: $savedTemp = $env:TEMP; $savedTmp = $env:TMP
11新增: $envFile = Join-Path $directory 'child-env.json'
12新增: $envScript = Join-Path $directory 'child-env.ps1'
13新增: [IO.File]::WriteAllText($envScript, '@{temp=$env:TEMP;tmp=$env:TMP} | ConvertTo-Json | Set-Content -LiteralPath $args[0]')
14新增: $failed = $false
15新增: try {
16新增: Invoke-InIsolatedTestTemp {
17新增: Invoke-BuildTool (Get-Process -Id $PID).Path @('-NoProfile','-NonInteractive','-File',$envScript,$envFile)
18新增: throw 'injected test failure'
19新增: }
20新增: } catch { $failed = $_.Exception.Message -eq 'injected test failure' }
21新增: $childEnv = Get-Content -LiteralPath $envFile -Raw | ConvertFrom-Json
22新增: Assert-SmokeContract $failed 'Isolated test temp swallowed its test failure.'
23新增: Assert-SmokeContract ($childEnv.temp -eq $childEnv.tmp -and (Split-Path $childEnv.temp -Parent) -eq $env:RUNNER_TEMP) 'Child tests did not inherit the isolated runner temp.'
24新增: Assert-SmokeContract ($env:TEMP -eq $savedTemp -and $env:TMP -eq $savedTmp) 'Failed tests changed the caller temp environment.'
25新增: Assert-SmokeContract (-not (Test-Path -LiteralPath $childEnv.temp)) 'Owned test temp was not cleaned.'
1026 Remove-Item Env:RUNNER_TEMP -ErrorAction SilentlyContinue
1127 Assert-SmokeContract ((Get-WindowsWorkbenchTestBase) -eq [IO.Path]::GetTempPath()) 'Local report directory lost its OS temp fallback.'
1228 $report = Join-Path $directory 'smoke.json'