跳到主要内容

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

提交记录
修改internal/workbench/session_metadata.go+8 −2看文件
@@ -69,10 +69,16 @@ func (s *Server) updateSessionMetadata(id string, input sessionMetadataInput, re
6969
7070// Archive state belongs to the shared catalog and survives terminal exits.
7171func (s *Server) setSessionArchived(id string, archived bool, requestContext context.Context) error {
72删除: if !s.op.TryLock() {
73删除: return errTerminalBusy
72新增: if requestContext != nil && requestContext.Err() != nil {
73新增: return requestContext.Err()
7474 }
75新增: // Serialize with terminal creation and teardown, but let an explicit archive
76新增: // wait for background network probes instead of rejecting the user's click.
77新增: s.op.Lock()
7578 defer s.op.Unlock()
79新增: if requestContext != nil && requestContext.Err() != nil {
80新增: return requestContext.Err()
81新增: }
7682 s.conversationMu.Lock()
7783 defer s.conversationMu.Unlock()
7884 m := &s.mobileCLI
修改internal/workbench/session_metadata_test.go+131 −0看文件
@@ -1,16 +1,147 @@
11package workbench
22
33import (
4新增: "context"
45 "encoding/json"
6新增: "errors"
57 "net/http"
8新增: "net/http/httptest"
69 "os"
10新增: "os/exec"
711 "path/filepath"
812 "strings"
13新增: "sync"
14新增: "sync/atomic"
915 "testing"
16新增: "time"
1017
1118 "github.com/google/uuid"
1219)
1320
21新增:func TestSessionArchiveContentionInBrowser(t *testing.T) {
22新增: if os.Getenv("CAGE_TEST_ARCHIVE_BROWSER") == "" {
23新增: t.Skip("set CAGE_TEST_ARCHIVE_BROWSER after building the UI to test with real archive handlers")
24新增: }
25新增: s, id, project := metadataFixture(t)
26新增: record, _ := s.mobileCLI.record(s.profile, id)
27新增: record.Title = "软件宣传视频制作"
28新增: if err := writePrivate(mobileRecordPath(s.profile, id), record); err != nil {
29新增: t.Fatal(err)
30新增: }
31新增: s.op.Lock()
32新增: var releaseOnce sync.Once
33新增: release := func() { releaseOnce.Do(s.op.Unlock) }
34新增: defer release()
35新增: var archives atomic.Int32
36新增: handler := s.handler()
37新增: host := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
38新增: if r.URL.Path == "/fixture/release-operation" {
39新增: release()
40新增: jsonReply(w, map[string]bool{"ok": true})
41新增: return
42新增: }
43新增: if r.URL.Path == "/api/cli/sessions/"+id+"/archive" {
44新增: archives.Add(1)
45新增: }
46新增: handler.ServeHTTP(w, r)
47新增: }))
48新增: defer host.Close()
49新增: // Release a blocked request before httptest waits for its handler at cleanup.
50新增: defer release()
51新增: s.origin = host.URL
52新增: input, _ := json.Marshal(map[string]string{
53新增: "origin": host.URL, "cookie": s.cookieName() + "=" + s.session,
54新增: "id": id, "workspace": project, "title": record.Title,
55新增: })
56新增: ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
57新增: defer cancel()
58新增: driver := exec.CommandContext(ctx, "node", "../../ui/scripts/archive-contention-smoke.mjs")
59新增: driver.Env = append(os.Environ(), "CAGE_TEST_BROWSER="+os.Getenv("CAGE_TEST_ARCHIVE_BROWSER"))
60新增: driver.Stdin = strings.NewReader(string(input))
61新增: if output, err := driver.CombinedOutput(); err != nil {
62新增: t.Fatalf("browser: %v\n%s", err, output)
63新增: } else {
64新增: t.Log(string(output))
65新增: }
66新增: if archives.Load() != 1 {
67新增: t.Fatalf("archive submissions: %d", archives.Load())
68新增: }
69新增: s.mobileCLI = mobileCLIStore{}
70新增: restored, err := s.mobileCLI.record(s.profile, id)
71新增: if err != nil || !restored.Archived || restored.Deleted {
72新增: t.Fatal("UI archive was not durable", restored, err)
73新增: }
74新增:}
75新增:
76新增:func TestSessionArchiveWaitsForEnvironmentOperation(t *testing.T) {
77新增: for _, route := range []string{"/api/cli/sessions/", "/api/mobile/cli/sessions/"} {
78新增: t.Run(route, func(t *testing.T) {
79新增: s, id, project := metadataFixture(t)
80新增: // Network monitoring holds this lock even when the UI reports no job.
81新增: s.op.Lock()
82新增: locked := true
83新增: defer func() {
84新增: if locked {
85新增: s.op.Unlock()
86新增: }
87新增: }()
88新增: done := make(chan *httptest.ResponseRecorder, 1)
89新增: go func() { done <- request(s, "POST", route+id+"/archive", s.origin, `{}`, true) }()
90新增: select {
91新增: case response := <-done:
92新增: t.Fatalf("archive rejected during background operation: %d %s", response.Code, response.Body.String())
93新增: case <-time.After(100 * time.Millisecond):
94新增: }
95新增: s.op.Unlock()
96新增: locked = false
97新增: select {
98新增: case response := <-done:
99新增: if response.Code != http.StatusOK {
100新增: t.Fatal(response.Code, response.Body.String())
101新增: }
102新增: case <-time.After(3 * time.Second):
103新增: t.Fatal("archive did not finish after background operation released the lock")
104新增: }
105新增: if len(s.terminals.snapshot()) != 0 {
106新增: t.Fatal("archive left its terminal visible")
107新增: }
108新增: s.mobileCLI = mobileCLIStore{}
109新增: active, err := s.mobileCLI.summaries(s.profile, map[string]bool{project: true}, false)
110新增: if err != nil || len(active) != 0 {
111新增: t.Fatal("archived session remained active after reload", active, err)
112新增: }
113新增: archived, err := s.mobileCLI.summaries(s.profile, map[string]bool{project: true}, true)
114新增: if err != nil || len(archived) != 1 || archived[0].ID != id {
115新增: t.Fatal("archived history was not retained", archived, err)
116新增: }
117新增: })
118新增: }
119新增:}
120新增:
121新增:func TestSessionArchiveDoesNotApplyCancelledRequest(t *testing.T) {
122新增: s, id, _ := metadataFixture(t)
123新增: ctx, cancel := context.WithCancel(context.Background())
124新增: defer cancel()
125新增: s.op.Lock()
126新增: done := make(chan error, 1)
127新增: go func() { done <- s.setSessionArchived(id, true, ctx) }()
128新增: select {
129新增: case err := <-done:
130新增: s.op.Unlock()
131新增: t.Fatalf("archive did not wait for the operation: %v", err)
132新增: case <-time.After(100 * time.Millisecond):
133新增: }
134新增: cancel()
135新增: s.op.Unlock()
136新增: if err := <-done; !errors.Is(err, context.Canceled) {
137新增: t.Fatalf("cancelled archive: %v", err)
138新增: }
139新增: record, err := s.mobileCLI.record(s.profile, id)
140新增: if err != nil || record.Archived || len(s.terminals.snapshot()) != 1 {
141新增: t.Fatal("cancelled archive changed the session", record, err)
142新增: }
143新增:}
144新增:
14145func metadataFixture(t *testing.T) (*Server, string, string) {
15146 t.Helper()
16147 s := testServer(t)
新增ui/scripts/archive-contention-smoke.mjs+54 −0看文件
@@ -0,0 +1,54 @@
1新增:// Real archive/catalog/terminal handlers; only unrelated workbench services use fixtures.
2新增:import assert from "node:assert/strict";
3新增:import { createWorkbench } from "./workbench-fixture.mjs";
4新增:
5新增:let input = "";
6新增:for await (const chunk of process.stdin) input += chunk;
7新增:const fixture = JSON.parse(input);
8新增:const forward = async route => {
9新增: const request = route.request();
10新增: const url = new URL(request.url());
11新增: const response = await fetch(fixture.origin + url.pathname + url.search, {
12新增: method: request.method(),
13新增: headers: { Origin: fixture.origin, Cookie: fixture.cookie, "Content-Type": "application/json" },
14新增: body: request.postData() || undefined,
15新增: });
16新增: return route.fulfill({ status: response.status, contentType: response.headers.get("Content-Type"), body: await response.text() });
17新增:};
18新增:const { page, browser, errors } = await createWorkbench({
19新增: url: process.env.CAGE_UI_URL || fixture.origin,
20新增: cliRequest: forward,
21新增: beforeNavigate: async (page, state) => {
22新增: state.settings.workspace = fixture.workspace;
23新增: Object.assign(state.status, { ready: true, vm_running: true, projects: [fixture.workspace], environment_directory: fixture.workspace });
24新增: await page.route("**/api/terminals", forward);
25新增: },
26新增:});
27新增:try {
28新增: const actions = page.getByRole("group", { name: `${fixture.title} 的操作`, exact: true, includeHidden: true });
29新增: await page.locator(".sidebar-tab").filter({ has: actions }).hover();
30新增: await actions.getByRole("button", { name: "归档", exact: true }).hover();
31新增: await actions.locator(".terminal-action-label").filter({ hasText: /^归档$/ }).click();
32新增: const dialog = page.getByRole("dialog", { name: "归档这段会话?", exact: true });
33新增: await dialog.getByRole("button", { name: "归档会话", exact: true }).click();
34新增: const pending = dialog.getByRole("button", { name: "正在归档…", exact: true });
35新增: await pending.waitFor();
36新增: assert.equal(await pending.isDisabled(), true);
37新增: await page.keyboard.press("Enter");
38新增: await page.keyboard.press("Escape");
39新增: assert.equal(await dialog.isVisible(), true);
40新增: await fetch(fixture.origin + "/fixture/release-operation", { method: "POST" });
41新增: await dialog.waitFor({ state: "hidden" });
42新增: await actions.waitFor({ state: "hidden" });
43新增: // Reload fetches the durable catalog again through the real backend.
44新增: const reloadedSessions = page.waitForResponse(response => new URL(response.url()).pathname === "/api/cli/sessions");
45新增: await page.reload();
46新增: await page.getByRole("button", { name: "打开浏览器", exact: true }).waitFor();
47新增: await reloadedSessions;
48新增: assert.equal(await actions.count(), 0);
49新增: assert.deepEqual(errors, []);
50新增: console.log(`${process.env.CAGE_TEST_BROWSER}: UI archive waited for the environment operation, submitted once, removed the row, retained history and survived reload`);
51新增:} finally {
52新增: await fetch(fixture.origin + "/fixture/release-operation", { method: "POST" });
53新增: await browser.close();
54新增:}
修改ui/scripts/archive-position-smoke.mjs+27 −3看文件
@@ -14,6 +14,8 @@ const sessions = Array.from({ length: 18 }, (_, i) => ({
1414}));
1515const evidence = [];
1616let failArchive = false;
17新增:let holdArchive = false, releaseArchive;
18新增:let archiveRequests = 0;
1719let archived = 0;
1820const dialog = page.getByRole("dialog", { name: "归档这段会话?", exact: true });
1921const actions = title => page.getByRole("group", { name: `${title} 的操作`, exact: true, includeHidden: true });
@@ -28,7 +30,9 @@ const open = async title => {
2830try {
2931 await page.route("**/api/cli/sessions", route => route.fulfill({ json: { sessions } }));
3032 await page.route("**/api/cli/sessions/*/archive", async route => {
31删除: if (failArchive) return route.fulfill({ status: 500, contentType: "text/plain", body: "测试:归档暂时失败" });
33新增: archiveRequests++;
34新增: if (holdArchive) await new Promise(resolve => { releaseArchive = resolve; });
35新增: if (failArchive) return route.fulfill({ status: 400, contentType: "text/plain", body: "环境正在执行其他操作" });
3236 const id = route.request().url().split("/").at(-2);
3337 sessions.splice(sessions.findIndex(session => session.id === id), 1);
3438 state.terminals = state.terminals.filter(terminal => terminal.cli_session_id !== id);
@@ -41,6 +45,16 @@ try {
4145 await page.getByRole("tab", { name: sessions[0].title, exact: true }).waitFor();
4246 await page.getByRole("button", { name: sessions.at(-1).title, exact: true }).waitFor();
4347 await mkdir(output, { recursive: true });
48新增: // A user can click the visible action text as well as its icon. Locator
49新增: // clicks on the icon alone hid the inert text beside the old buttons.
50新增: const firstActions = actions(sessions[0].title);
51新增: await page.locator(".sidebar-tab").filter({ has: firstActions }).hover();
52新增: await firstActions.getByRole("button", { name: "归档", exact: true }).hover();
53新增: await page.screenshot({ path: `${output}/${engine}-archive-label.png` });
54新增: await firstActions.locator(".terminal-action-label").filter({ hasText: /^归档$/ }).click();
55新增: await dialog.waitFor({ timeout: 2000 });
56新增: await dialog.getByRole("button", { name: "取消", exact: true }).click();
57新增: assert.equal(archived, 0, "action text bypassed archive confirmation");
4458 for (const width of [1280, 820]) {
4559 await page.setViewportSize({ width, height: 850 });
4660 const trigger = await open(sessions[0].title);
@@ -82,11 +96,21 @@ try {
8296 await open(sessions[0].title);
8397 failArchive = true;
8498 await dialog.getByRole("button", { name: "归档会话", exact: true }).click();
85删除: await page.getByRole("status").filter({ hasText: "归档暂时失败" }).waitFor();
99新增: await dialog.getByRole("alert").filter({ hasText: "环境正在执行其他操作" }).waitFor();
86100 assert.equal(archived, 0, "failed archive removed a session");
87101 failArchive = false;
88删除: await open(sessions[0].title);
102新增: holdArchive = true;
89103 await dialog.getByRole("button", { name: "归档会话", exact: true }).press("Enter");
104新增: await dialog.getByRole("button", { name: "正在归档…", exact: true }).waitFor();
105新增: assert.equal(await dialog.getByRole("button", { name: "取消", exact: true }).isDisabled(), true);
106新增: assert.equal(await dialog.getByRole("button", { name: "正在归档…", exact: true }).isDisabled(), true);
107新增: const pendingRequests = archiveRequests;
108新增: await page.keyboard.press("Enter");
109新增: await page.keyboard.press("Escape");
110新增: assert.equal(await dialog.isVisible(), true, "pending archive was dismissed");
111新增: assert.equal(archiveRequests, pendingRequests, "pending archive was submitted twice");
112新增: await page.screenshot({ path: `${output}/${engine}-pending.png` });
113新增: releaseArchive(); holdArchive = false;
90114 await actions("正在处理的会话").waitFor({ state: "hidden" });
91115 assert.equal(archived, 1, "confirm should archive exactly once");
92116 await open(last);
修改ui/src/main.jsx+26 −19看文件
@@ -483,13 +483,14 @@ function App() {
483483 }
484484 };
485485 const archiveSession = async (session, anchor) => {
486删除: if (!(await confirm({title:"归档这段会话?", body:"归档会关闭关联终端。历史将保留,可从设置中的已归档会话恢复。", confirm:"归档会话", anchor}))) return;
487删除: try {
488删除: await api("/cli/sessions/" + session.id + "/archive", {});
489删除: setTabs(list => list.filter(tab => tab.cli_session_id !== session.id));
490删除: sessionsChanged();
491删除: refreshStatus.current?.();
492删除: } catch (error) { notify(error.message); }
486新增: await confirm({title:"归档这段会话?", body:"归档会关闭关联终端。历史将保留,可从设置中的已归档会话恢复。", confirm:"归档会话", pendingLabel:"正在归档…", anchor,
487新增: submit: async () => {
488新增: await api("/cli/sessions/" + session.id + "/archive", {});
489新增: setTabs(list => list.filter(tab => tab.cli_session_id !== session.id));
490新增: sessionsChanged();
491新增: refreshStatus.current?.();
492新增: },
493新增: });
493494 };
494495 const pinSession = async session => {
495496 try {
@@ -862,9 +863,7 @@ function App() {
862863 if (k === "w") {
863864 event.preventDefault();
864865 event.stopImmediatePropagation();
865删除: const resolve = dialog.resolve;
866删除: setDialog(null);
867删除: resolve(false);
866新增: void finishDialog(false);
868867 }
869868 return;
870869 }
@@ -1005,9 +1004,7 @@ function App() {
10051004 return;
10061005 }
10071006 if (dialog) {
1008删除: const resolve = dialog.resolve;
1009删除: setDialog(null);
1010删除: resolve(false);
1007新增: void finishDialog(false);
10111008 } else if (
10121009 settingsOpen ||
10131010 transfer ||
@@ -1170,7 +1167,16 @@ function App() {
11701167 useEffect(() => {
11711168 if (status?.workspace) setSelectedProject(status.workspace);
11721169 }, [status?.workspace]);
1173删除: const finishDialog = (value) => {
1170新增: const finishDialog = async (value) => {
1171新增: if (!dialog || dialog.pending) return;
1172新增: if (value === true && dialog.submit) {
1173新增: setDialog({ ...dialog, pending: true, error: "" });
1174新增: try { await dialog.submit(); }
1175新增: catch (error) {
1176新增: setDialog({ ...dialog, pending: false, error: error.message });
1177新增: return;
1178新增: }
1179新增: }
11741180 const resolve = dialog.resolve;
11751181 setDialog(null);
11761182 resolve(value);
@@ -1242,23 +1248,24 @@ function App() {
12421248 <Modal
12431249 title={dialog.title}
12441250 anchor={dialog.anchor}
1245删除: onClose={() => finishDialog(false)}
1251新增: onClose={dialog.pending ? undefined : () => finishDialog(false)}
12461252 footer={
12471253 <>
1248删除: <button onClick={() => finishDialog(false)}>取消</button>
1254新增: <button disabled={dialog.pending} onClick={() => finishDialog(false)}>取消</button>
12491255 {dialog.secondary && (
1250删除: <button onClick={() => finishDialog("secondary")}>
1256新增: <button disabled={dialog.pending} onClick={() => finishDialog("secondary")}>
12511257 {dialog.secondary}
12521258 </button>
12531259 )}
1254删除: <button className="primary" onClick={() => finishDialog(true)}>
1255删除: {dialog.confirm}
1260新增: <button className="primary" disabled={dialog.pending} onClick={() => finishDialog(true)}>
1261新增: {dialog.pending ? dialog.pendingLabel : dialog.confirm}
12561262 </button>
12571263 </>
12581264 }
12591265 >
12601266 <div className="modal-body">
12611267 <p>{dialog.body}</p>
1268新增: {dialog.error && <div className="error-message" role="alert">{dialog.error}</div>}
12621269 </div>
12631270 </Modal>
12641271 )}
修改ui/src/style.css+7 −6看文件
@@ -1582,8 +1582,10 @@ svg {
15821582 transform: none;
15831583}
15841584.terminal-row-actions > button {
1585删除: flex: 0 0 25px;
1586删除: width: 25px;
1585新增: flex: 0 0 auto;
1586新增: width: auto;
1587新增: min-width: 25px;
1588新增: gap: 4px;
15871589 min-height: 26px;
15881590 height: 26px;
15891591 padding: 0;
@@ -1598,14 +1600,13 @@ svg {
15981600}
15991601.terminal-action-label {
16001602 display: none;
1601删除: order: -1;
1602删除: margin-inline: 2px 4px;
1603新增: margin-left: 4px;
16031604 color: var(--muted);
16041605 font-size: 0.7857rem;
16051606 white-space: nowrap;
16061607}
1607删除:.terminal-row-actions > button:hover + .terminal-action-label,
1608删除:.terminal-row-actions:not(:has(> button:hover)) > button:focus-visible + .terminal-action-label {
1608新增:.terminal-row-actions > button:hover .terminal-action-label,
1609新增:.terminal-row-actions:not(:has(> button:hover)) > button:focus-visible .terminal-action-label {
16091610 display: block;
16101611}
16111612@media (prefers-reduced-motion: reduce) {
修改ui/src/workspace-tabs.jsx+3 −5看文件
@@ -32,12 +32,10 @@ export function TabIcon({ kind, favicon, agent, accountNumber, size = 16 }) {
3232
3333function TerminalAction({ label, icon: Icon, disabled, onClick }) {
3434 return (
35删除: <>
36删除: <button className="icon-button" aria-label={label} disabled={disabled} onClick={onClick}>
37删除: <Icon size={14} />
38删除: </button>
35新增: <button className="icon-button" aria-label={label} disabled={disabled} onClick={onClick}>
3936 <span className="terminal-action-label" aria-hidden="true">{label}</span>
40删除: </>
37新增: <Icon size={14} />
38新增: </button>
4139 );
4240}
4341