跳到主要内容

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

提交记录
修改internal/workbench/cli_channel.go+3 −0看文件
@@ -195,6 +195,7 @@ func (s *Server) discoverTerminalConversations(ctx context.Context, paths []stri
195195 m.mu.Lock()
196196 defer m.mu.Unlock()
197197 known := map[string]*mobileRecord{}
198新增: running := map[string]bool{}
198199 for id := range m.catalog {
199200 record, err := m.record(s.profile, id)
200201 if err != nil {
@@ -253,8 +254,10 @@ func (s *Server) discoverTerminalConversations(ctx context.Context, paths []stri
253254 return err
254255 }
255256 m.catalog[record.ID] = record.summary()
257新增: running[record.ID] = running[record.ID] || item.Running
256258 known[record.CLIID] = record
257259 }
260新增: m.running = running
258261 return nil
259262}
260263
修改internal/workbench/cli_channel.py+13 −1看文件
@@ -309,6 +309,12 @@ def discover(request):
309309 configs.add(state["config"])
310310 for config_name in configs:
311311 config = Path(config_name)
312新增: running_ids = None
313新增: def observed_running():
314新增: nonlocal running_ids
315新增: if running_ids is None:
316新增: running_ids = {row.get("sessionId") for row in running_sessions(config_name)}
317新增: return running_ids
312318 paths = sorted((config / "projects").glob("*/*.jsonl"), key=lambda p: p.stat().st_mtime, reverse=True)
313319 found = set()
314320 for path in paths:
@@ -324,6 +330,7 @@ def discover(request):
324330 connection, state = connection_for(session_id, config)
325331 item = {"cli_id": session_id, "config": config_name, "connection": connection,
326332 "workspace": workspace, "title": title or "Claude Code", "updated_at": path.stat().st_mtime,
333新增: "running": session_id in observed_running() or bool(live(state.get("pid")) and not state.get("closed")),
327334 "active": bool(live(state.get("pid")) and not state.get("closed") and (state.get("busy") or state.get("approvals")))}
328335 found.add(session_id)
329336 sessions.append(item)
@@ -334,6 +341,7 @@ def discover(request):
334341 if state.get("config") != config_name or not session_id or session_id in found or not any(workspace_within(workspace, root) for root in allowed):
335342 continue
336343 item = view(config, session_id)
344新增: item["running"] = item["running"] or session_id in observed_running()
337345 item.pop("turns")
338346 sessions.append(item)
339347 return sessions
@@ -424,13 +432,17 @@ def active_session(session_id, config=""):
424432
425433
426434def active_sessions(session_id, config=""):
435新增: return [row for row in running_sessions(config) if row.get("sessionId") == session_id]
436新增:
437新增:
438新增:def running_sessions(config=""):
427439 env = dict(os.environ)
428440 if config:
429441 env["CLAUDE_CONFIG_DIR"] = config
430442 listing = subprocess.run(["claude", "agents", "--json"], env=env, capture_output=True, text=True, timeout=10)
431443 if listing.returncode != 0:
432444 raise ValueError("无法检查原会话是否仍在运行")
433删除: return [row for row in json.loads(listing.stdout) if row.get("sessionId") == session_id and live(row.get("pid"))]
445新增: return [row for row in json.loads(listing.stdout) if live(row.get("pid"))]
434446
435447
436448def handoff_session(request):
修改internal/workbench/cli_channel_test.go+40 −0看文件
@@ -186,6 +186,46 @@ func TestArchivedCLIHistoryIsNotRediscovered(t *testing.T) {
186186 }
187187}
188188
189新增:func TestDiscoveryRunningStateUpdatesCatalogAndClearsMissingHistory(t *testing.T) {
190新增: s, id, project := metadataFixture(t)
191新增: home, _ := filepath.EvalSymlinks(t.TempDir())
192新增: mobileTestSSH(t, s, home, []string{"HOME=" + home, "PATH=/usr/bin:/bin:/usr/local/bin"})
193新增: record, err := s.mobileCLI.record(s.profile, id)
194新增: if err != nil {
195新增: t.Fatal(err)
196新增: }
197新增: if _, err := s.mobileCLI.summaries(s.profile, map[string]bool{project: true}, false); err != nil {
198新增: t.Fatal(err)
199新增: }
200新增: // Keep the host bootstrap and SSH path; substitute the guest's observation.
201新增: observation := filepath.Join(home, "observation.json")
202新增: helper := filepath.Join(home, ".local/share/cage/cli-channel-code", fmt.Sprintf("%x.py", sha256.Sum256([]byte(cliChannelHelper+cliResumePrompt+claudeAccountResumePrompt))))
203新增: if err := os.MkdirAll(filepath.Dir(helper), 0700); err != nil {
204新增: t.Fatal(err)
205新增: }
206新增: code := fmt.Sprintf("import json,sys\njson.load(sys.stdin)\nprint(open(%q).read())\n", observation)
207新增: if err := os.WriteFile(helper, []byte(code), 0600); err != nil {
208新增: t.Fatal(err)
209新增: }
210新增: s.ready = true
211新增: for _, phase := range []struct{ present, running bool }{{true, true}, {true, false}, {true, true}, {false, false}} {
212新增: found := []terminalConversation{}
213新增: if phase.present {
214新增: found = append(found, terminalConversation{CLIID: record.CLIID, Workspace: guestPath(project), Config: filepath.Join(home, ".claude"), Running: phase.running})
215新增: }
216新增: if err := writePrivate(observation, found); err != nil {
217新增: t.Fatal(err)
218新增: }
219新增: if err := s.discoverTerminalConversations(context.Background(), []string{project}); err != nil {
220新增: t.Fatal(err)
221新增: }
222新增: list, err := s.mobileCLI.summaries(s.profile, map[string]bool{project: true}, false)
223新增: if err != nil || len(list) != 1 || list[0].Running != phase.running {
224新增: t.Fatalf("phase %+v: summaries = %+v, error = %v", phase, list, err)
225新增: }
226新增: }
227新增:}
228新增:
189229func sharedCLIWorkbench(t *testing.T) (*Server, string, *atomic.Bool) {
190230 t.Helper()
191231 binary, flags := os.Getenv("CAGE_TEST_CLAUDE_CLI"), os.Getenv("CAGE_TEST_CHANNEL_FEATURES")
修改internal/workbench/cli_channel_test.py+30 −5看文件
@@ -157,21 +157,45 @@ class ChannelTests(unittest.TestCase):
157157 with self.assertRaises(ValueError): channel.handoff_session(request)
158158 kill.assert_not_called()
159159
160删除: def test_catalog_activity_requires_live_busy_process(self):
160新增: @patch.object(channel, "running_sessions", return_value=[])
161新增: def test_catalog_activity_requires_live_busy_process(self, _registry):
161162 self.history(self.session, self.project, [{"type":"user", "message":{"content":"hello"}}])
162163 connection = str(uuid.uuid4())
163164 with channel.state_file(connection) as state:
164165 state.update(cli_id=self.session, config=str(self.home / ".claude"), workspace=self.project,
165166 pid=os.getpid(), busy=True)
166167 request = {"accounts":["default"], "workspaces":{self.project:self.project}}
167删除: self.assertTrue(channel.discover(request)[0]["active"])
168新增: item = channel.discover(request)[0]
169新增: self.assertTrue(item["active"])
170新增: self.assertTrue(item["running"])
168171 self.assertTrue(channel.view(self.home / ".claude", self.session)["active"])
169172 with channel.state_file(connection) as state:
170173 state["busy"] = False
171删除: self.assertFalse(channel.discover(request)[0]["active"], "idle CLI was shown as active")
174新增: item = channel.discover(request)[0]
175新增: self.assertFalse(item["active"], "idle CLI was shown as active")
176新增: self.assertTrue(item["running"], "idle owned process was shown as stopped")
172177 with channel.state_file(connection) as state:
173178 state.update(busy=True, closed=True)
174删除: self.assertFalse(channel.discover(request)[0]["active"], "closed CLI retained activity")
179新增: item = channel.discover(request)[0]
180新增: self.assertFalse(item["active"], "closed CLI retained activity")
181新增: self.assertFalse(item["running"])
182新增:
183新增: def test_discovery_reports_external_idle_process_and_clears_after_exit(self):
184新增: self.history(self.session, self.project, [{"type":"user", "message":{"content":"hello"}}])
185新增: other = str(uuid.uuid4())
186新增: self.history(other, self.project, [{"type":"user", "message":{"content":"other"}}])
187新增: request = {"accounts":["default"], "workspaces":{self.project:self.project}}
188新增: registry = [{"sessionId": self.session, "pid": os.getpid(), "status":"idle"}]
189新增: completed = subprocess.CompletedProcess([], 0, json.dumps(registry), "")
190新增: with patch.object(channel.subprocess, "run", return_value=completed) as run:
191新增: found = {item["cli_id"]: item for item in channel.discover(request)}
192新增: self.assertTrue(found[self.session]["running"])
193新增: self.assertFalse(found[self.session]["active"])
194新增: self.assertFalse(found[other]["running"])
195新增: self.assertEqual(run.call_count, 1, "registry must be read once per config, not per history")
196新增: self.assertEqual(run.call_args.kwargs["env"]["CLAUDE_CONFIG_DIR"], str(self.home / ".claude"))
197新增: completed.stdout = "[]"
198新增: self.assertFalse(any(item["running"] for item in channel.discover(request)))
175199
176200 def test_purge_removes_only_target_transcripts_and_retries(self):
177201 target = self.history(self.session, self.project, [{"type":"user", "message":{"content":"delete this"}}])
@@ -215,7 +239,8 @@ class ChannelTests(unittest.TestCase):
215239 self.assertEqual(json.loads(policy.read_text()), blocked)
216240 self.assertEqual(run.call_count, 1)
217241
218删除: def test_history_projects_and_channel_identity(self):
242新增: @patch.object(channel, "running_sessions", return_value=[])
243新增: def test_history_projects_and_channel_identity(self, _registry):
219244 request = str(uuid.uuid4())
220245 self.history(self.session, self.project + "/nested", [
221246 {"type": "user", "message": {"content": "desktop question"}},
修改internal/workbench/mobile_cli_store.go+3 −0看文件
@@ -33,6 +33,7 @@ type mobileSummary struct {
3333 CustomTitle string `json:"custom_title,omitempty"`
3434 Pinned bool `json:"pinned"`
3535 Active bool `json:"active"`
36新增: Running bool `json:"running"`
3637 MetadataSet bool `json:"metadata_set"`
3738 Deleted bool `json:"deleted,omitempty"`
3839 Archived bool `json:"archived,omitempty"`
@@ -133,6 +134,7 @@ type mobileCLIStore struct {
133134 mu sync.Mutex
134135 active map[string]*mobileRun
135136 catalog map[string]mobileSummary
137新增: running map[string]bool // Fresh guest process observation, never restored from disk.
136138 generation string
137139}
138140
@@ -269,6 +271,7 @@ func (m *mobileCLIStore) summaries(profile string, granted map[string]bool, arch
269271 summary = run.record.summary()
270272 summary.Active = run.record.turnActive()
271273 }
274新增: summary.Running = m.running[id]
272275 if granted[summary.Workspace] && !summary.Deleted && summary.Archived == archived {
273276 if summary.CustomTitle != "" {
274277 summary.Title = summary.CustomTitle
修改internal/workbench/session_summary_accounts_test.go+25 −0看文件
@@ -52,3 +52,28 @@ func TestSessionSummaryAccountAfterRestartAndSwitch(t *testing.T) {
5252 store = &mobileCLIStore{}
5353 check("second-account")
5454}
55新增:
56新增:func TestSessionSummaryRunningRequiresFreshProcessObservation(t *testing.T) {
57新增: profile, workspace, id := t.TempDir(), t.TempDir(), uuid.NewString()
58新增: record := &mobileRecord{mobileSession: mobileSession{mobileSummary: mobileSummary{
59新增: ID: id, Workspace: workspace, Running: true,
60新增: }, Turns: []mobileTurn{}}, Terminal: true, CLIID: uuid.NewString()}
61新增: if err := writePrivate(mobileRecordPath(profile, id), record); err != nil {
62新增: t.Fatal(err)
63新增: }
64新增: store := &mobileCLIStore{}
65新增: check := func(want bool) {
66新增: t.Helper()
67新增: list, err := store.summaries(profile, map[string]bool{workspace: true}, false)
68新增: if err != nil || len(list) != 1 || list[0].Running != want {
69新增: t.Fatalf("running = %v, want %v; error = %v", list, want, err)
70新增: }
71新增: }
72新增: check(false) // Persisted activity cannot disable a session after restart.
73新增: store.running = map[string]bool{id: true}
74新增: check(true) // An idle external process is running even without a busy turn.
75新增: store.active = map[string]*mobileRun{id: {record: record}}
76新增: check(true)
77新增: store.running = map[string]bool{}
78新增: check(false)
79新增:}
修改ui/scripts/session-order-smoke.mjs+1 −0看文件
@@ -13,6 +13,7 @@ const sessions = [
1313const fixture = await createWorkbench({ url: process.env.CAGE_UI_URL || "http://127.0.0.1:5217",
1414 cliRequest: async (route, path) => {
1515 if (path === "/cli/sessions") return route.fulfill({json:{sessions}});
16新增: if (path.endsWith("/account")) return route.fulfill({json:{session:{},supported:false,candidates:[]}});
1617 const session = sessions.find(s => path.includes(s.id));
1718 if (path.endsWith("/open")) {
1819 opens++;
新增ui/scripts/sidebar-session-running-smoke.mjs+106 −0看文件
@@ -0,0 +1,106 @@
1新增:import assert from "node:assert/strict";
2新增:import { mkdir } from "node:fs/promises";
3新增:import { createWorkbench } from "./workbench-fixture.mjs";
4新增:
5新增:const output = process.env.CAGE_TEST_CAPTURE || "/tmp/cage-sidebar-session-running";
6新增:await mkdir(output, {recursive:true});
7新增:for (const platform of ["darwin", "windows", "linux"]) {
8新增: const sessions = [
9新增: {id:"external",title:"其他窗口中的会话",running:true},
10新增: {id:"owned",title:"Cage 中已打开的会话",running:true},
11新增: {id:"waiting",title:"等待打开的会话"},
12新增: {id:"available",title:"可以接续的会话"},
13新增: ];
14新增: const releases = [], opens = [];
15新增: let behavior = "hold", state;
16新增: const fixture = await createWorkbench({
17新增: url:process.env.CAGE_UI_URL || "http://127.0.0.1:5228",
18新增: clientContext:{mode:"local",connection_id:"local",client_platform:platform,server_platform:platform},
19新增: beforeNavigate:async (_page, value) => {
20新增: state = value;
21新增: state.status.ready = state.status.vm_running = true;
22新增: sessions.forEach(session=>{session.workspace=state.settings.workspace;});
23新增: state.terminals = [{id:"owned-terminal",kind:"claude",workspace:state.settings.workspace,title:sessions[1].title,cli_session_id:"owned"}];
24新增: },
25新增: cliRequest:async (route,path) => {
26新增: if (path === "/cli/sessions") return route.fulfill({json:{sessions}});
27新增: if (path.endsWith("/account")) return route.fulfill({json:{session:{},supported:false,candidates:[]}});
28新增: if (path.endsWith("/open")) {
29新增: const session = sessions.find(item=>path.includes("/"+item.id+"/"));
30新增: opens.push(session.id);
31新增: const mode = behavior;
32新增: if (mode === "hold") await new Promise(resolve=>releases.push(resolve));
33新增: if (mode === "error") return route.fulfill({status:409,contentType:"text/plain; charset=utf-8",body:"原会话仍在其他窗口运行,请先退出原会话"});
34新增: const terminal = {id:"terminal-"+session.id,kind:"claude",workspace:session.workspace,title:session.title,cli_session_id:session.id};
35新增: state.terminals.push(terminal);
36新增: return route.fulfill({json:{desktop_terminal_id:terminal.id}});
37新增: }
38新增: return route.fulfill({json:{}});
39新增: },
40新增: });
41新增: const {page,browser,errors} = fixture;
42新增: try {
43新增: const external = page.getByRole("button",{name:sessions[0].title,exact:true});
44新增: const waiting = page.getByRole("button",{name:sessions[2].title,exact:true});
45新增: const available = page.getByRole("button",{name:sessions[3].title,exact:true});
46新增: const owned = page.getByRole("tab",{name:sessions[1].title,exact:true});
47新增: await external.waitFor();
48新增: await owned.waitFor();
49新增: assert.equal(await external.isDisabled(),true,"external running history must be disabled before clicking");
50新增: await external.getByRole("img",{name:"其他窗口运行中",exact:true}).waitFor();
51新增: assert.match(await external.getAttribute("title"),/退出原会话/);
52新增: const box = await external.boundingBox();
53新增: await page.mouse.click(box.x+box.width/2,box.y+box.height/2);
54新增: assert.deepEqual(opens,[],"disabled external session sent an open request");
55新增: assert.equal(await owned.isEnabled(),true,"owned live terminal was disabled");
56新增: await owned.click();
57新增: await owned.press("ArrowDown");
58新增: assert.equal(await waiting.evaluate(element=>element===document.activeElement),true,"keyboard focus got stuck at a disabled session");
59新增: assert.equal(await available.isEnabled(),true);
60新增: await page.locator(".sidebar-scroll").screenshot({path:`${output}/${platform}-initial.png`});
61新增:
62新增: await waiting.click();
63新增: await waiting.getByRole("img",{name:"正在打开会话",exact:true}).waitFor();
64新增: assert.equal(await waiting.isDisabled(),true);
65新增: assert.equal(await available.isEnabled(),true,"unrelated history flickered disabled");
66新增: assert.equal(await owned.isEnabled(),true);
67新增: const sent = opens.length;
68新增: await page.mouse.click((await waiting.boundingBox()).x+20,(await waiting.boundingBox()).y+20);
69新增: assert.equal(opens.length,sent,"pending session sent a duplicate open");
70新增: behavior = "error";
71新增: await available.focus();
72新增: await page.keyboard.press("Enter");
73新增: const failure = page.getByRole("alert").filter({hasText:"原会话仍在其他窗口运行"});
74新增: await failure.waitFor();
75新增: assert.equal(await waiting.isEnabled(),true,"cancelled request kept its row disabled");
76新增: assert.equal(await available.isEnabled(),true,"failed open kept its row disabled");
77新增: releases.shift()();
78新增: await page.waitForFunction(id=>Boolean(document.querySelector(`[data-tab-id="${id}"]`)),"terminal:terminal-waiting");
79新增: assert.equal(await owned.getAttribute("aria-selected"),"true","a cancelled response stole focus");
80新增:
81新增: // Exit the external process, then refresh using the production list event.
82新增: sessions[0].running = false;
83新增: await page.evaluate(()=>window.dispatchEvent(new Event("cage-cli-sessions-changed")));
84新增: await page.waitForFunction(()=>document.querySelector('[aria-label="其他窗口中的会话"]')?.disabled === false);
85新增: assert.equal(await external.getByRole("img",{name:"其他窗口运行中"}).count(),0);
86新增: behavior = "success";
87新增: await external.click();
88新增: await page.getByRole("tab",{name:sessions[0].title,exact:true}).waitFor();
89新增: assert.equal(await failure.count(),0);
90新增:
91新增: // A lost receipt is bounded and leaves the same history available to retry.
92新增: behavior = "hold";
93新增: await page.clock.install();
94新增: await available.click();
95新增: await available.getByRole("img",{name:"正在打开会话",exact:true}).waitFor();
96新增: await page.clock.fastForward(60001);
97新增: await page.getByRole("alert").filter({hasText:"打开会话超时,历史已保留"}).waitFor();
98新增: assert.equal(await available.isEnabled(),true);
99新增: assert.deepEqual(errors,[]);
100新增: await page.locator(".sidebar-scroll").screenshot({path:`${output}/${platform}-timeout.png`});
101新增: console.log(`${platform}: initial disabled/spinner, owned terminal, isolated pending state, cancellation, error, exit/reopen and timeout passed`);
102新增: } finally {
103新增: releases.forEach(release=>release());
104新增: await browser.close();
105新增: }
106新增:}
修改ui/src/api.js+7 −2看文件
@@ -32,16 +32,21 @@ async function renewSession() {
3232 }
3333 return sessionRenewal;
3434}
35删除:export async function api(path, body, method, headers = {}) {
35新增:export async function api(path, body, method, headers = {}, { signal } = {}) {
3636 const connection = getClientContext().connection_id;
3737 const options = {
3838 method: method || (body === undefined ? "GET" : "POST"),
3939 headers: { ...connectionHeaders(path), ...(body === undefined ? {} : { "Content-Type": "application/json" }), ...headers },
4040 body: body === undefined ? undefined : JSON.stringify(body),
41新增: signal,
4142 };
4243 const send = async () => {
4344 try { return await fetch("/api" + path, options); }
44删除: catch (error) { reportDiagnostic("frontend", error); throw new Error(connectionErrorMessage(path, options.method), { cause: error }); }
45新增: catch (error) {
46新增: if (signal?.aborted) throw signal.reason;
47新增: reportDiagnostic("frontend", error);
48新增: throw new Error(connectionErrorMessage(path, options.method), { cause: error });
49新增: }
4550 };
4651 let response = await send();
4752 // Authentication fails before a handler runs, so retrying this rejected
修改ui/src/api.test.mjs+14 −0看文件
@@ -37,6 +37,20 @@ function nativeRuntime(t, fetcher, bridge) {
3737}
3838const json = (data, status = 200) =>
3939 new Response(JSON.stringify(data), { status });
40新增:test("aborted session opens preserve their cancellation reason and do not replay", async t => {
41新增: const controller = new AbortController();
42新增: const reason = new Error("打开会话超时");
43新增: let calls = 0;
44新增: nativeRuntime(t, async (_path, options) => {
45新增: calls++;
46新增: assert.equal(options.signal, controller.signal);
47新增: return new Promise((_, reject) => options.signal.addEventListener("abort", () => reject(options.signal.reason), {once:true}));
48新增: }, () => { throw new Error("unexpected renewal"); });
49新增: const pending = api("/cli/sessions/test/open", {}, undefined, {}, {signal:controller.signal});
50新增: controller.abort(reason);
51新增: await assert.rejects(pending, error => error === reason);
52新增: assert.equal(calls,1);
53新增:});
4054test("Linux native calls survive WebKit's transient messageHandlers objects", async (t) => {
4155 const calls = [];
4256 nativeRuntime(t, () => { throw Error("unexpected request"); }, () => {});
修改ui/src/cli-sessions.css+1 −0看文件
@@ -5,6 +5,7 @@
55}
66.sidebar-session > span { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
77.sidebar-session > svg { flex: none; color: var(--muted); }
8新增:.sidebar-session-open-error { margin: 2px 8px 10px; color: var(--muted); font-size: .8571rem; line-height: 1.5; overflow-wrap: anywhere; }
89.settings-content.settings-content--archives { padding: 32px clamp(24px, 4vw, 64px); }
910.archived-sessions { display: grid; gap: 28px; min-width: 0; width: 100%; max-width: 1120px; margin-inline: auto; }
1011.archived-sessions :is(h2,h3,h4,p) { margin: 0; }
修改ui/src/cli-sessions.jsx+2 −2看文件
@@ -39,12 +39,12 @@ export function useCLISessions(enabled, visible) {
3939 try {
4040 const result = await desktopSessionRequest("/sessions");
4141 if (!live) return;
42删除: setSessions((result.sessions || []).map(session => result.notice ? { ...session, active: false } : session));
42新增: setSessions((result.sessions || []).map(session => result.notice ? { ...session, active: false, running: false } : session));
4343 setError(result.notice || "");
4444 } catch (error) {
4545 if (live) {
4646 setError(error.message);
47删除: setSessions(previous => previous.map(session => ({ ...session, active: false })));
47新增: setSessions(previous => previous.map(session => ({ ...session, active: false, running: false })));
4848 }
4949 } finally { if (live) setLoading(false); }
5050 if (live) timer = setTimeout(load, 5000);
修改ui/src/main.jsx+31 −5看文件
@@ -76,6 +76,13 @@ function App() {
7676 const [desktopOpen, setDesktopOpen] = useState(false);
7777 const [terminalChoice, setTerminalChoice] = useState(null);
7878 const [openingSession, setOpeningSession] = useState("");
79新增: const [sessionOpenError, setSessionOpenError] = useState(null);
80新增: const sessionOpenRequest = useRef(null);
81新增: useEffect(() => () => {
82新增: const request = sessionOpenRequest.current;
83新增: sessionOpenRequest.current = null;
84新增: request?.controller.abort();
85新增: }, []);
7986 const terminalTrigger = useRef(null);
8087 const appUpdates = useAppUpdates();
8188 const [recoveringEditor, setRecoveringEditor] = useState(false);
@@ -445,17 +452,35 @@ function App() {
445452 setActive(tab.id);
446453 };
447454 const openSessionTerminal = async session => {
448删除: if (openingSession) return;
455新增: if (session.running) return;
456新增: if (sessionOpenRequest.current?.id === session.id) return;
457新增: sessionOpenRequest.current?.controller.abort();
458新增: const controller = new AbortController();
459新增: const request = { id: session.id, controller };
460新增: sessionOpenRequest.current = request;
449461 setOpeningSession(session.id);
462新增: setSessionOpenError(null);
463新增: const timer = setTimeout(() => controller.abort(new Error("打开会话超时,历史已保留。请重新打开;若仍失败,请在设置中导出诊断包。")), 60000);
450464 try {
451删除: const view = await api("/cli/sessions/" + session.id + "/open", {});
452删除: const terminals = await api("/terminals");
465新增: const view = await api("/cli/sessions/" + session.id + "/open", {}, undefined, {}, { signal: controller.signal });
466新增: const terminals = await api("/terminals", undefined, undefined, {}, { signal: controller.signal });
467新增: if (sessionOpenRequest.current !== request) return;
453468 const terminal = terminals.find(item => item.id === view.desktop_terminal_id && item.cli_session_id === session.id);
454469 if (!terminal) throw new Error("终端状态已变化,请重新打开会话");
455470 showTerminal(terminal);
456471 sessionsChanged();
457删除: } catch (error) { notify(error.message); }
458删除: finally { setOpeningSession(""); }
472新增: } catch (error) {
473新增: if (sessionOpenRequest.current === request && error.code !== "connection_changed") {
474新增: const message = (controller.signal.aborted ? controller.signal.reason : error).message;
475新增: setSessionOpenError({ id: session.id, message });
476新增: }
477新增: } finally {
478新增: clearTimeout(timer);
479新增: if (sessionOpenRequest.current === request) {
480新增: sessionOpenRequest.current = null;
481新增: setOpeningSession("");
482新增: }
483新增: }
459484 };
460485 const archiveSession = async (session, anchor) => {
461486 if (!(await confirm({title:"归档这段会话?", body:"归档会关闭关联终端。历史将保留,可从设置中的已归档会话恢复。", confirm:"归档会话", anchor}))) return;
@@ -1326,6 +1351,7 @@ function App() {
13261351 onSessionRefresh={cliSessions.refresh}
13271352 onSessionOpen={openSessionTerminal}
13281353 openingSession={openingSession}
1354新增: sessionOpenError={sessionOpenError}
13291355 onSessionArchive={archiveSession}
13301356 onSessionPin={pinSession}
13311357 onSessionRename={session => setRename({id:session.id, title:session.title, session:true})}
修改ui/src/session-order.mjs+1 −0看文件
@@ -13,6 +13,7 @@ export function projectSessionRows(tabs, sessions, saved, manualOrder, baseline)
1313 const session = sessions.find(session => session.id === tab.cli_session_id);
1414 return { ...tab, claudeAccountNumber: session?.account_id ? session.claudeAccountNumber : tab.claudeAccountNumber,
1515 sessionActive: Boolean(session?.active),
16新增: sessionRunningElsewhere: Boolean(tab.historySession && session?.running),
1617 sessionPinned: Boolean(session ? session.pinned : saved[tab.id]?.pinned) };
1718 });
1819 for (const row of rows) if (!baseline.has(sessionKey(row))) baseline.set(sessionKey(row), baseline.size);
修改ui/src/session-order.test.mjs+10 −0看文件
@@ -8,6 +8,16 @@ const sessions = [
88 { id: "three", title: "第三段" },
99];
1010const keys = rows => rows.map(sessionKey);
11新增:test("external running state blocks only history without an owned live terminal", () => {
12新增: const running = [{id:"external",running:true}, {id:"owned",running:true}, {id:"stopped",running:false}];
13新增: const tabs = [{id:"terminal:owned",cli_session_id:"owned"}, {id:"terminal:old",cli_session_id:"external",closed:true}];
14新增: const rows = projectSessionRows(tabs, running, {}, undefined, new Map());
15新增: assert.equal(rows.find(row=>row.cli_session_id==="external").sessionRunningElsewhere,true);
16新增: assert.equal(rows.find(row=>row.cli_session_id==="owned").sessionRunningElsewhere,false);
17新增: assert.equal(rows.find(row=>row.cli_session_id==="stopped").sessionRunningElsewhere,false);
18新增: const exited = projectSessionRows(tabs, running.map(session=>({...session,running:false})), {}, undefined, new Map());
19新增: assert.equal(exited.some(row=>row.sessionRunningElsewhere),false);
20新增:});
1121test("default activity, stable clicks and terminal attachment", () => {
1222 const baseline = new Map();
1323 const initial = projectSessionRows([], sessions, {}, undefined, baseline);
修改ui/src/workspace-sidebar.jsx+2 −0看文件
@@ -38,6 +38,7 @@ export function WorkspaceSidebar({
3838 onSessionRefresh,
3939 onSessionOpen,
4040 openingSession,
41新增: sessionOpenError,
4142 onSessionArchive,
4243 onSessionPin,
4344 onSessionRename,
@@ -228,6 +229,7 @@ export function WorkspaceSidebar({
228229 tabs={rows}
229230 saved={rowMetadata}
230231 openingSession={openingSession}
232新增: sessionOpenError={sessionOpenError}
231233 active={home || desktopOpen ? "" : active}
232234 label={`${project} 的终端`}
233235 busy={busy}
修改ui/src/workspace-tabs.jsx+31 −14看文件
@@ -59,6 +59,7 @@ export function WorkspaceTabs({
5959 onReorder,
6060 splitDrag,
6161 openingSession,
62新增: sessionOpenError,
6263}) {
6364 const [menu, setMenu] = useState(null);
6465 const [drag, setDrag] = useState(null);
@@ -95,6 +96,9 @@ export function WorkspaceTabs({
9596 .toLowerCase()
9697 .includes(query.toLowerCase()),
9798 );
99新增: const firstFocusable = tabs.findIndex(tab => tab.historySession
100新增: ? !busy && openingSession !== tab.cli_session_id && !tab.sessionRunningElsewhere
101新增: : ready || tab.kind === "terminal");
98102 const finishDrag = (commit, event) => {
99103 const current = pointer.current;
100104 pointer.current = null;
@@ -293,10 +297,16 @@ export function WorkspaceTabs({
293297 >
294298 {tabs.map((tab, index) => {
295299 const title = tabName(tab, saved);
300新增: const opening = Boolean(openingSession) && openingSession === tab.cli_session_id;
301新增: const runningElsewhere = tab.sessionRunningElsewhere;
302新增: const runningNotice = "其他窗口运行中,退出原会话后可在 Cage 接续";
303新增: const openError = tab.historySession && sessionOpenError?.id === tab.cli_session_id ? sessionOpenError.message : "";
304新增: const errorID = `session-open-error-${tab.cli_session_id}`;
296305 return (
306新增: <React.Fragment key={tab.id}>
297307 <div
298删除: key={tab.id}
299308 data-tab-id={tab.id}
309新增: title={runningElsewhere ? runningNotice : undefined}
300310 className={`${horizontal || vertical ? "browser-tab" : "sidebar-tab"} ${tab.id === active ? "active" : ""} ${tab.closed ? "ended" : ""} ${drag?.id === tab.id ? "dragging" : ""} ${horizontal && tabWidth(tab.id) < 96 ? "compact" : ""} ${horizontal && tabWidth(tab.id) < 40 ? "tiny" : ""} ${horizontal && tabWidth(tab.id) < 24 ? "sliver" : ""}`}
301311 style={
302312 horizontal
@@ -326,17 +336,19 @@ export function WorkspaceTabs({
326336 <button
327337 role={tab.historySession ? undefined : "tab"}
328338 className={tab.historySession ? "sidebar-session" : undefined}
329删除: aria-busy={openingSession && openingSession === tab.cli_session_id || undefined}
339新增: aria-busy={opening || undefined}
340新增: aria-describedby={openError ? errorID : undefined}
341新增: aria-description={runningElsewhere ? runningNotice : undefined}
330342 aria-label={tab.claudeLabel ? `${title} · ${tab.claudeLabel}` : title}
331343 aria-selected={tab.historySession ? undefined : tab.id === active}
332344 tabIndex={
333345 tab.id === active ||
334删除: (!tabs.some((t) => t.id === active) && index === 0)
346新增: (!tabs.some((t) => t.id === active) && index === firstFocusable)
335347 ? 0
336348 : -1
337349 }
338删除: disabled={tab.historySession ? busy || Boolean(openingSession) : !ready && tab.kind !== "terminal"}
339删除: title={tab.url ? `${title}\n${tab.url}` : [title, tab.claudeAccountNumber && `账号 ${tab.claudeAccountNumber}`, tab.claudeLabel].filter(Boolean).join(" · ")}
350新增: disabled={tab.historySession ? busy || opening || runningElsewhere : !ready && tab.kind !== "terminal"}
351新增: title={runningElsewhere ? `${title}\n${runningNotice}` : tab.url ? `${title}\n${tab.url}` : [title, tab.claudeAccountNumber && `账号 ${tab.claudeAccountNumber}`, tab.claudeLabel].filter(Boolean).join(" · ")}
340352 onClick={() => onSelect(tab.id)}
341353 onContextMenu={(event) => showMenu(tab, event)}
342354 onKeyDown={(event) => {
@@ -354,17 +366,20 @@ export function WorkspaceTabs({
354366 const next = horizontal ? "ArrowRight" : "ArrowDown";
355367 if (![prev, next, "Home", "End"].includes(event.key)) return;
356368 event.preventDefault();
357删除: const at =
369新增: const buttons = [...list.current.querySelectorAll('[role="tab"], .sidebar-session')];
370新增: const enabled = buttons.map((button, at) => ({button, at})).filter(item => !item.button.disabled);
371新增: const from = enabled.findIndex(item => item.at === index);
372新增: const target = enabled[
358373 event.key === "Home"
359374 ? 0
360375 : event.key === "End"
361删除: ? tabs.length - 1
362删除: : (index +
376新增: ? enabled.length - 1
377新增: : (from +
363378 (event.key === prev ? -1 : 1) +
364删除: tabs.length) %
365删除: tabs.length;
366删除: list.current.querySelectorAll('[role="tab"], .sidebar-session')[at]?.focus();
367删除: if (!tabs[at].historySession) onSelect(tabs[at].id, false);
379新增: enabled.length) %
380新增: enabled.length];
381新增: target?.button.focus();
382新增: if (target && !tabs[target.at].historySession) onSelect(tabs[target.at].id, false);
368383 }}
369384 >
370385 <TabIcon kind={tab.kind} favicon={tab.favicon} size={15}
@@ -373,8 +388,8 @@ export function WorkspaceTabs({
373388 <span>{title}</span>
374389 {tab.claudeLabel && <small className="claude-tab-profile">{tab.claudeLabel}</small>}
375390 {saved[tab.id]?.pinned && <Pin size={11} className="tab-pin" />}
376删除: {!horizontal && !vertical && (tab.sessionActive || openingSession === tab.cli_session_id) &&
377删除: <LoaderCircle size={13} className="spin session-activity" role="img" aria-label={tab.sessionActive ? "会话正在运行" : "正在打开会话"} />}
391新增: {!horizontal && !vertical && (runningElsewhere || tab.sessionActive || opening) &&
392新增: <LoaderCircle size={13} className="spin session-activity" role="img" aria-label={runningElsewhere ? "其他窗口运行中" : opening ? "正在打开会话" : "会话正在运行"} />}
378393 </button>
379394 {horizontal || vertical ? (
380395 <button
@@ -394,6 +409,8 @@ export function WorkspaceTabs({
394409 </div>
395410 )}
396411 </div>
412新增: {openError && <p id={errorID} className="sidebar-session-open-error" role="alert">{openError}</p>}
413新增: </React.Fragment>
397414 );
398415 })}
399416 </div>