跳到主要内容

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

提交记录
修改cmd/cage-client/main.go+2 −0看文件
@@ -16,6 +16,7 @@ import (
1616
1717 "github.com/sylvinus/agent-vm/internal/cage"
1818 "github.com/sylvinus/agent-vm/internal/diagnostics"
19新增: "github.com/sylvinus/agent-vm/internal/host"
1920 "github.com/sylvinus/agent-vm/internal/version"
2021 "github.com/sylvinus/agent-vm/internal/workbench"
2122)
@@ -153,6 +154,7 @@ func relay(config string) error {
153154 defer out.Close()
154155 defer stderr.Close()
155156 cmd.Stdout, cmd.Stderr = out, stderr
157新增: host.HideCommandWindow(cmd)
156158 if err := cmd.Start(); err != nil {
157159 return err
158160 }
修改cmd/cage/main.go+1 −0看文件
@@ -586,6 +586,7 @@ func relay(configPath, kind string) int {
586586 stderr := store.Stream(source, "error")
587587 defer stderr.Close()
588588 cmd.Stdout, cmd.Stderr = out, stderr
589新增: host.HideCommandWindow(cmd)
589590 if err := cmd.Start(); err != nil {
590591 return fail(err)
591592 }
修改docs/troubleshooting.md+1 −0看文件
@@ -134,6 +134,7 @@ Cage 不自动读取主机上的 Claude 登录。请在 Cage 终端运行 `claud
134134| 网页复制按钮显示成功,本机粘贴仍是旧内容 | 保持网页和 Cage 窗口在前台重试。已有页面若改写了复制 API,可刷新后再试;复杂 DOM 选区、图片、富文本或超长文字可使用复制快捷键及“文本传递”面板。 |
135135| 停止后旧终端不见了 | 停止虚拟机会结束进程。磁盘和登录态保留,但需要新建终端。 |
136136| 关掉窗口后任务还在运行 | 关闭窗口保留环境;需要结束时选择“停止环境并退出”。 |
137新增:| 已在命令行关闭 Cage 后台,桌面窗口还开着 | 从应用菜单选择“退出 Cage”(Windows 也可使用托盘菜单)。若提示无法确认环境状态,选择“仅退出桌面应用”。重新连接后可查看环境和任务状态。 |
137138| 修改设置后无法正常使用 | “设置 → 环境与恢复”可恢复上一份配置;此操作需要停止并重启环境,已结束的终端不能恢复。 |
138139
139140## 页面与出口状态
修改docs/windows.md+1 −1看文件
@@ -37,7 +37,7 @@ DISM /Online /Enable-Feature /FeatureName:HypervisorPlatform /All
3737
3838Windows 快捷键以 `Ctrl` 为主:`Ctrl+O` 打开项目、`Ctrl+T` 新建网页、`Ctrl+L` 定位地址栏、`Ctrl+W` 关闭标签,`Ctrl+Shift+Enter` 新建终端。终端使用 `Ctrl+Shift+C/V` 复制粘贴,`Ctrl+C` 中断命令。网页和编辑器采用 Linux 的 Ctrl 组合键。
3939
40删除:关闭窗口会保留环境与后台任务,可从托盘图标重新打开;停止环境或选择停止后退出会结束终端。重新打开应用可连接仍运行的会话。
40新增:从开始菜单打开 Cage 时,完整版和轻量客户端的后台服务都会静默启动。关闭工作台窗口会保留环境与后台任务,可从托盘图标重新打开。要退出桌面程序,在托盘菜单选择“退出 Cage”。本机环境仍在运行时,可以选择保留任务或停止环境;停止环境会结束其中的终端。
4141
4242浏览器上传通过本机文件选择窗口选取文件;下载完成可用 Windows“另存为”选择位置。侧栏“下载”提供打开文件、在资源管理器中显示与再次另存为,取消保存窗口时保留默认 Downloads 中的文件。操作与限制见[浏览器上传与下载](getting-started.md#浏览器上传与下载)。
4343
修改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/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/browser_file_desktop.go+1 −1看文件
@@ -213,7 +213,7 @@ func BrowserFileForConnection(configPath, connectionID, action, id, destination
213213 }
214214 cmd = exec.Command("gio", "open", path)
215215 }
216删除: hideCommand(cmd)
216新增: host.HideCommandWindow(cmd)
217217 if err = cmd.Run(); err != nil {
218218 return result, errors.New("无法打开文件,请通过显示的位置手动查看")
219219 }
修改internal/workbench/platform_unix.go+0 −1看文件
@@ -22,7 +22,6 @@ func processExists(pid int) bool {
2222}
2323func terminateLegacy(pid int) error { return syscall.Kill(pid, syscall.SIGTERM) }
2424func detachController(cmd *exec.Cmd) { cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true} }
25删除:func hideCommand(cmd *exec.Cmd) {}
2625func sshExecutable() string { return "/usr/bin/ssh" }
2726func sshEnvironment() []string {
2827 return []string{"PATH=/usr/bin:/bin:/usr/sbin:/sbin", "LANG=C", "LC_ALL=C", "TERM=xterm-256color"}
修改internal/workbench/platform_windows.go+0 −3看文件
@@ -34,9 +34,6 @@ func terminateLegacy(pid int) error {
3434func detachController(cmd *exec.Cmd) {
3535 cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true, CreationFlags: windows.CREATE_NEW_PROCESS_GROUP | windows.DETACHED_PROCESS}
3636}
37删除:func hideCommand(cmd *exec.Cmd) {
38删除: cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true, CreationFlags: windows.CREATE_NO_WINDOW}
39删除:}
4037func sshExecutable() string {
4138 exe, _ := os.Executable()
4239 bundled := filepath.Join(filepath.Dir(exe), "runtime", "openssh", "ssh.exe")
修改internal/workbench/runtime.go+3 −2看文件
@@ -15,6 +15,7 @@ import (
1515
1616 "github.com/sylvinus/agent-vm/internal/cage"
1717 "github.com/sylvinus/agent-vm/internal/containerenv"
18新增: "github.com/sylvinus/agent-vm/internal/host"
1819 "github.com/sylvinus/agent-vm/internal/managedproxy"
1920)
2021
@@ -68,7 +69,7 @@ func (s *Server) sshCommandOptions(ctx context.Context, maintenance bool, args .
6869 base = append(base, args...)
6970 cmd := exec.CommandContext(ctx, sshExecutable(), base...)
7071 cmd.Env = sshEnvironment()
71删除: hideCommand(cmd)
72新增: host.HideCommandWindow(cmd)
7273 return cmd
7374}
7475func (s *Server) guest(ctx context.Context, script string) ([]byte, error) {
@@ -203,7 +204,7 @@ func (s *Server) runCage(args ...string) error {
203204 defer cancel()
204205 }
205206 cmd := exec.CommandContext(ctx, s.exe, args...)
206删除: hideCommand(cmd)
207新增: host.HideCommandWindow(cmd)
207208 cmd.Dir = s.environmentDir()
208209 if cmd.Dir == "" {
209210 cmd.Dir = s.profile
新增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看文件
@@ -213,15 +213,6 @@ export function AccountGate({ children }) {
213213 setBusy(true);
214214 deviceAction("unlock", "automatic").catch((e) => setError(e.message)).finally(() => setBusy(false));
215215 }, [account?.unlocked, account?.devices?.automatic, account?.require_authentication, deviceSupport]);
216删除: useEffect(() => {
217删除: if (account?.unlocked) return;
218删除: window.cageNativeAction = async (action) => {
219删除: if (action === "quit") await native("quitNow");
220删除: };
221删除: return () => {
222删除: delete window.cageNativeAction;
223删除: };
224删除: }, [account?.unlocked]);
225216 if (account?.unlocked) return children;
226217 const creating = account && !account.exists;
227218 const submit = async (event) => {
修改ui/src/api.js+30 −5看文件
@@ -1,6 +1,7 @@
11import { reportDiagnostic } from "./diagnostics.mjs";
22import { assertConnection, connectionHeaders, getClientContext } from "./client-context.mjs";
33let sessionRenewal;
4新增:class WorkbenchUnreachable extends Error {}
45async function responseError(response) {
56 const error = new Error(
67 (await response.text()).trim() || "连接未完成,请重试",
@@ -38,7 +39,11 @@ export async function api(path, body, method) {
3839 };
3940 const send = async () => {
4041 try { return await fetch("/api" + path, options); }
41删除: catch (error) { reportDiagnostic("frontend", error); throw error; }
42新增: catch (error) {
43新增: reportDiagnostic("frontend", error);
44新增: if (error instanceof TypeError) throw new WorkbenchUnreachable(error.message, { cause: error });
45新增: throw error;
46新增: }
4247 };
4348 let response = await send();
4449 // Authentication fails before a handler runs, so retrying this rejected
@@ -89,11 +94,31 @@ export async function uploadFile(path, file, { signal, onProgress } = {}) {
8994}
9095export const nativeAvailable = () =>
9196 Boolean(window.webkit?.messageHandlers?.cage);
97新增:const lostLocalView = (context) =>
98新增: context.desktop_gateway && context.mode === "local" &&
99新增: context.connection?.state === "failed" && context.connection.error_code === "connection_lost";
100新增:
101新增:async function suspendBeforeQuit(context) {
102新增: if (context.mode !== "local" || context.client_only || lostLocalView(context)) return;
103新增: try {
104新增: await api("/account/suspend", {});
105新增: } catch (error) {
106新增: if (error.status === 423) return;
107新增: // The first request after CLI shutdown can fail before the next context poll.
108新增: if (context.desktop_gateway && [409, 502].includes(error.status)) {
109新增: const latest = await api("/client/context");
110新增: if (latest.connection_id === context.connection_id && lostLocalView(latest)) return;
111新增: }
112新增: throw error;
113新增: }
114新增:}
92115export async function native(action, extra = {}) {
93删除: const connection = getClientContext().connection_id;
94删除: if (action === "quitNow" && getClientContext().mode === "local" && !getClientContext().client_only) {
95删除: try { await api("/account/suspend", {}); }
96删除: catch (error) { if (error.status !== 423) throw error; }
116新增: const context = getClientContext();
117新增: const connection = context.connection_id;
118新增: if (action === "quitNow") {
119新增: try { await suspendBeforeQuit(context); }
120新增: catch (error) { if (!(error instanceof WorkbenchUnreachable)) throw error; }
121新增: assertConnection(connection);
97122 }
98123 try {
99124 const result = await window.webkit.messageHandlers.cage.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+74 −0看文件
@@ -52,6 +52,80 @@ 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("a reachable local controller must lock or report already locked before quit", async (t) => {
107新增: environment(t);
108新增: setClientContext(localGateway("connected"));
109新增: window.dispatchEvent = () => {};
110新增: const calls = [];
111新增: let status = 500;
112新增: globalThis.fetch = async (path) => {
113新增: calls.push(path);
114新增: if (path === "/api/client/context") return Response.json(localGateway("connected"));
115新增: return Response.json({}, { status });
116新增: };
117新增: window.webkit.messageHandlers.cage.postMessage = ({ action }) => calls.push(action);
118新增: for (status of [500, 409, 502]) {
119新增: await assert.rejects(native("quitNow"), { status });
120新增: assert.ok(!calls.includes("quitNow"));
121新增: }
122新增: for (status of [200, 423]) {
123新增: calls.length = 0;
124新增: await native("quitNow");
125新增: assert.deepEqual(calls, ["/api/account/suspend", "quitNow"]);
126新增: }
127新增:});
128新增:
55129test("an account device operation retains its host generation and rejects a late result", async (t) => {
56130 environment(t);
57131 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/main.jsx+12 −2看文件
@@ -764,7 +764,7 @@ function App() {
764764 return terminalControls.current.get(current.id)?.edit(command) || false;
765765 return remote.current?.edit(command) || false;
766766 };
767删除: window.cageNativeAction = async (command) => {
767新增: window.cageWorkbenchAction = async (command) => {
768768 if (document.querySelector("[data-environment-dialog]")) {
769769 if (command === "closeTab") document.dispatchEvent(new Event("cage-close-modal"));
770770 return;
@@ -830,6 +830,15 @@ function App() {
830830 await native("quitNow");
831831 return;
832832 }
833新增: if (connectionError || fatal) {
834新增: setDialog({
835新增: title: "退出 Cage",
836新增: body: "工作台连接已中断,暂时无法确认环境状态。仍在运行的后台任务会继续。",
837新增: confirm: "仅退出桌面应用",
838新增: resolve: (confirmed) => confirmed && native("quitNow"),
839新增: });
840新增: return;
841新增: }
833842 setDialog({
834843 title: "退出 Cage",
835844 body: "退出前请保存文件和设置。可以保留环境,让后台任务继续运行;下次打开会重新连接。",
@@ -847,7 +856,7 @@ function App() {
847856 };
848857 return () => {
849858 window.removeEventListener("keydown", key, true);
850删除: delete window.cageNativeAction;
859新增: delete window.cageWorkbenchAction;
851860 delete window.cageEditAction;
852861 };
853862 }, [
@@ -863,6 +872,7 @@ function App() {
863872 busy,
864873 active,
865874 connectionError,
875新增: fatal,
866876 projectDialog,
867877 rename,
868878 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;