提交记录修改internal/workbench/cli_channel.go+3 −0看文件
修改internal/workbench/cli_channel.py+13 −1看文件
修改internal/workbench/cli_channel_test.go+40 −0看文件
修改internal/workbench/cli_channel_test.py+30 −5看文件
修改internal/workbench/mobile_cli_store.go+3 −0看文件
修改internal/workbench/session_summary_accounts_test.go+25 −0看文件
修改ui/scripts/session-order-smoke.mjs+1 −0看文件
新增ui/scripts/sidebar-session-running-smoke.mjs+106 −0看文件
修改ui/src/api.js+7 −2看文件
修改ui/src/api.test.mjs+14 −0看文件
修改ui/src/cli-sessions.css+1 −0看文件
修改ui/src/cli-sessions.jsx+2 −2看文件
修改ui/src/main.jsx+31 −5看文件
修改ui/src/session-order.mjs+1 −0看文件
修改ui/src/session-order.test.mjs+10 −0看文件
修改ui/src/workspace-sidebar.jsx+2 −0看文件
修改ui/src/workspace-tabs.jsx+31 −14看文件
| @@ -195,6 +195,7 @@ func (s *Server) discoverTerminalConversations(ctx context.Context, paths []stri | ||
| 195 | 195 | m.mu.Lock() |
| 196 | 196 | defer m.mu.Unlock() |
| 197 | 197 | known := map[string]*mobileRecord{} |
| 198 | 新增: running := map[string]bool{} | |
| 198 | 199 | for id := range m.catalog { |
| 199 | 200 | record, err := m.record(s.profile, id) |
| 200 | 201 | if err != nil { |
| @@ -253,8 +254,10 @@ func (s *Server) discoverTerminalConversations(ctx context.Context, paths []stri | ||
| 253 | 254 | return err |
| 254 | 255 | } |
| 255 | 256 | m.catalog[record.ID] = record.summary() |
| 257 | 新增: running[record.ID] = running[record.ID] || item.Running | |
| 256 | 258 | known[record.CLIID] = record |
| 257 | 259 | } |
| 260 | 新增: m.running = running | |
| 258 | 261 | return nil |
| 259 | 262 | } |
| 260 | 263 | |
| @@ -309,6 +309,12 @@ def discover(request): | ||
| 309 | 309 | configs.add(state["config"]) |
| 310 | 310 | for config_name in configs: |
| 311 | 311 | 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 | |
| 312 | 318 | paths = sorted((config / "projects").glob("*/*.jsonl"), key=lambda p: p.stat().st_mtime, reverse=True) |
| 313 | 319 | found = set() |
| 314 | 320 | for path in paths: |
| @@ -324,6 +330,7 @@ def discover(request): | ||
| 324 | 330 | connection, state = connection_for(session_id, config) |
| 325 | 331 | item = {"cli_id": session_id, "config": config_name, "connection": connection, |
| 326 | 332 | "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")), | |
| 327 | 334 | "active": bool(live(state.get("pid")) and not state.get("closed") and (state.get("busy") or state.get("approvals")))} |
| 328 | 335 | found.add(session_id) |
| 329 | 336 | sessions.append(item) |
| @@ -334,6 +341,7 @@ def discover(request): | ||
| 334 | 341 | 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): |
| 335 | 342 | continue |
| 336 | 343 | item = view(config, session_id) |
| 344 | 新增: item["running"] = item["running"] or session_id in observed_running() | |
| 337 | 345 | item.pop("turns") |
| 338 | 346 | sessions.append(item) |
| 339 | 347 | return sessions |
| @@ -424,13 +432,17 @@ def active_session(session_id, config=""): | ||
| 424 | 432 | |
| 425 | 433 | |
| 426 | 434 | def 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=""): | |
| 427 | 439 | env = dict(os.environ) |
| 428 | 440 | if config: |
| 429 | 441 | env["CLAUDE_CONFIG_DIR"] = config |
| 430 | 442 | listing = subprocess.run(["claude", "agents", "--json"], env=env, capture_output=True, text=True, timeout=10) |
| 431 | 443 | if listing.returncode != 0: |
| 432 | 444 | 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"))] | |
| 434 | 446 | |
| 435 | 447 | |
| 436 | 448 | def handoff_session(request): |
| @@ -186,6 +186,46 @@ func TestArchivedCLIHistoryIsNotRediscovered(t *testing.T) { | ||
| 186 | 186 | } |
| 187 | 187 | } |
| 188 | 188 | |
| 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 | 新增: | |
| 189 | 229 | func sharedCLIWorkbench(t *testing.T) (*Server, string, *atomic.Bool) { |
| 190 | 230 | t.Helper() |
| 191 | 231 | binary, flags := os.Getenv("CAGE_TEST_CLAUDE_CLI"), os.Getenv("CAGE_TEST_CHANNEL_FEATURES") |
| @@ -157,21 +157,45 @@ class ChannelTests(unittest.TestCase): | ||
| 157 | 157 | with self.assertRaises(ValueError): channel.handoff_session(request) |
| 158 | 158 | kill.assert_not_called() |
| 159 | 159 | |
| 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): | |
| 161 | 162 | self.history(self.session, self.project, [{"type":"user", "message":{"content":"hello"}}]) |
| 162 | 163 | connection = str(uuid.uuid4()) |
| 163 | 164 | with channel.state_file(connection) as state: |
| 164 | 165 | state.update(cli_id=self.session, config=str(self.home / ".claude"), workspace=self.project, |
| 165 | 166 | pid=os.getpid(), busy=True) |
| 166 | 167 | 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"]) | |
| 168 | 171 | self.assertTrue(channel.view(self.home / ".claude", self.session)["active"]) |
| 169 | 172 | with channel.state_file(connection) as state: |
| 170 | 173 | 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") | |
| 172 | 177 | with channel.state_file(connection) as state: |
| 173 | 178 | 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))) | |
| 175 | 199 | |
| 176 | 200 | def test_purge_removes_only_target_transcripts_and_retries(self): |
| 177 | 201 | target = self.history(self.session, self.project, [{"type":"user", "message":{"content":"delete this"}}]) |
| @@ -215,7 +239,8 @@ class ChannelTests(unittest.TestCase): | ||
| 215 | 239 | self.assertEqual(json.loads(policy.read_text()), blocked) |
| 216 | 240 | self.assertEqual(run.call_count, 1) |
| 217 | 241 | |
| 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): | |
| 219 | 244 | request = str(uuid.uuid4()) |
| 220 | 245 | self.history(self.session, self.project + "/nested", [ |
| 221 | 246 | {"type": "user", "message": {"content": "desktop question"}}, |
| @@ -33,6 +33,7 @@ type mobileSummary struct { | ||
| 33 | 33 | CustomTitle string `json:"custom_title,omitempty"` |
| 34 | 34 | Pinned bool `json:"pinned"` |
| 35 | 35 | Active bool `json:"active"` |
| 36 | 新增: Running bool `json:"running"` | |
| 36 | 37 | MetadataSet bool `json:"metadata_set"` |
| 37 | 38 | Deleted bool `json:"deleted,omitempty"` |
| 38 | 39 | Archived bool `json:"archived,omitempty"` |
| @@ -133,6 +134,7 @@ type mobileCLIStore struct { | ||
| 133 | 134 | mu sync.Mutex |
| 134 | 135 | active map[string]*mobileRun |
| 135 | 136 | catalog map[string]mobileSummary |
| 137 | 新增: running map[string]bool // Fresh guest process observation, never restored from disk. | |
| 136 | 138 | generation string |
| 137 | 139 | } |
| 138 | 140 | |
| @@ -269,6 +271,7 @@ func (m *mobileCLIStore) summaries(profile string, granted map[string]bool, arch | ||
| 269 | 271 | summary = run.record.summary() |
| 270 | 272 | summary.Active = run.record.turnActive() |
| 271 | 273 | } |
| 274 | 新增: summary.Running = m.running[id] | |
| 272 | 275 | if granted[summary.Workspace] && !summary.Deleted && summary.Archived == archived { |
| 273 | 276 | if summary.CustomTitle != "" { |
| 274 | 277 | summary.Title = summary.CustomTitle |
| @@ -52,3 +52,28 @@ func TestSessionSummaryAccountAfterRestartAndSwitch(t *testing.T) { | ||
| 52 | 52 | store = &mobileCLIStore{} |
| 53 | 53 | check("second-account") |
| 54 | 54 | } |
| 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 | 新增:} | |
| @@ -13,6 +13,7 @@ const sessions = [ | ||
| 13 | 13 | const fixture = await createWorkbench({ url: process.env.CAGE_UI_URL || "http://127.0.0.1:5217", |
| 14 | 14 | cliRequest: async (route, path) => { |
| 15 | 15 | if (path === "/cli/sessions") return route.fulfill({json:{sessions}}); |
| 16 | 新增: if (path.endsWith("/account")) return route.fulfill({json:{session:{},supported:false,candidates:[]}}); | |
| 16 | 17 | const session = sessions.find(s => path.includes(s.id)); |
| 17 | 18 | if (path.endsWith("/open")) { |
| 18 | 19 | opens++; |
| @@ -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 | 新增:} | |
| @@ -32,16 +32,21 @@ async function renewSession() { | ||
| 32 | 32 | } |
| 33 | 33 | return sessionRenewal; |
| 34 | 34 | } |
| 35 | 删除:export async function api(path, body, method, headers = {}) { | |
| 35 | 新增:export async function api(path, body, method, headers = {}, { signal } = {}) { | |
| 36 | 36 | const connection = getClientContext().connection_id; |
| 37 | 37 | const options = { |
| 38 | 38 | method: method || (body === undefined ? "GET" : "POST"), |
| 39 | 39 | headers: { ...connectionHeaders(path), ...(body === undefined ? {} : { "Content-Type": "application/json" }), ...headers }, |
| 40 | 40 | body: body === undefined ? undefined : JSON.stringify(body), |
| 41 | 新增: signal, | |
| 41 | 42 | }; |
| 42 | 43 | const send = async () => { |
| 43 | 44 | 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 | 新增: } | |
| 45 | 50 | }; |
| 46 | 51 | let response = await send(); |
| 47 | 52 | // Authentication fails before a handler runs, so retrying this rejected |
| @@ -37,6 +37,20 @@ function nativeRuntime(t, fetcher, bridge) { | ||
| 37 | 37 | } |
| 38 | 38 | const json = (data, status = 200) => |
| 39 | 39 | 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 | 新增:}); | |
| 40 | 54 | test("Linux native calls survive WebKit's transient messageHandlers objects", async (t) => { |
| 41 | 55 | const calls = []; |
| 42 | 56 | nativeRuntime(t, () => { throw Error("unexpected request"); }, () => {}); |
| @@ -5,6 +5,7 @@ | ||
| 5 | 5 | } |
| 6 | 6 | .sidebar-session > span { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } |
| 7 | 7 | .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; } | |
| 8 | 9 | .settings-content.settings-content--archives { padding: 32px clamp(24px, 4vw, 64px); } |
| 9 | 10 | .archived-sessions { display: grid; gap: 28px; min-width: 0; width: 100%; max-width: 1120px; margin-inline: auto; } |
| 10 | 11 | .archived-sessions :is(h2,h3,h4,p) { margin: 0; } |
| @@ -39,12 +39,12 @@ export function useCLISessions(enabled, visible) { | ||
| 39 | 39 | try { |
| 40 | 40 | const result = await desktopSessionRequest("/sessions"); |
| 41 | 41 | 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)); | |
| 43 | 43 | setError(result.notice || ""); |
| 44 | 44 | } catch (error) { |
| 45 | 45 | if (live) { |
| 46 | 46 | setError(error.message); |
| 47 | 删除: setSessions(previous => previous.map(session => ({ ...session, active: false }))); | |
| 47 | 新增: setSessions(previous => previous.map(session => ({ ...session, active: false, running: false }))); | |
| 48 | 48 | } |
| 49 | 49 | } finally { if (live) setLoading(false); } |
| 50 | 50 | if (live) timer = setTimeout(load, 5000); |
| @@ -76,6 +76,13 @@ function App() { | ||
| 76 | 76 | const [desktopOpen, setDesktopOpen] = useState(false); |
| 77 | 77 | const [terminalChoice, setTerminalChoice] = useState(null); |
| 78 | 78 | 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 | 新增: }, []); | |
| 79 | 86 | const terminalTrigger = useRef(null); |
| 80 | 87 | const appUpdates = useAppUpdates(); |
| 81 | 88 | const [recoveringEditor, setRecoveringEditor] = useState(false); |
| @@ -445,17 +452,35 @@ function App() { | ||
| 445 | 452 | setActive(tab.id); |
| 446 | 453 | }; |
| 447 | 454 | 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; | |
| 449 | 461 | setOpeningSession(session.id); |
| 462 | 新增: setSessionOpenError(null); | |
| 463 | 新增: const timer = setTimeout(() => controller.abort(new Error("打开会话超时,历史已保留。请重新打开;若仍失败,请在设置中导出诊断包。")), 60000); | |
| 450 | 464 | 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; | |
| 453 | 468 | const terminal = terminals.find(item => item.id === view.desktop_terminal_id && item.cli_session_id === session.id); |
| 454 | 469 | if (!terminal) throw new Error("终端状态已变化,请重新打开会话"); |
| 455 | 470 | showTerminal(terminal); |
| 456 | 471 | 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 | 新增: } | |
| 459 | 484 | }; |
| 460 | 485 | const archiveSession = async (session, anchor) => { |
| 461 | 486 | if (!(await confirm({title:"归档这段会话?", body:"归档会关闭关联终端。历史将保留,可从设置中的已归档会话恢复。", confirm:"归档会话", anchor}))) return; |
| @@ -1326,6 +1351,7 @@ function App() { | ||
| 1326 | 1351 | onSessionRefresh={cliSessions.refresh} |
| 1327 | 1352 | onSessionOpen={openSessionTerminal} |
| 1328 | 1353 | openingSession={openingSession} |
| 1354 | 新增: sessionOpenError={sessionOpenError} | |
| 1329 | 1355 | onSessionArchive={archiveSession} |
| 1330 | 1356 | onSessionPin={pinSession} |
| 1331 | 1357 | onSessionRename={session => setRename({id:session.id, title:session.title, session:true})} |
| @@ -13,6 +13,7 @@ export function projectSessionRows(tabs, sessions, saved, manualOrder, baseline) | ||
| 13 | 13 | const session = sessions.find(session => session.id === tab.cli_session_id); |
| 14 | 14 | return { ...tab, claudeAccountNumber: session?.account_id ? session.claudeAccountNumber : tab.claudeAccountNumber, |
| 15 | 15 | sessionActive: Boolean(session?.active), |
| 16 | 新增: sessionRunningElsewhere: Boolean(tab.historySession && session?.running), | |
| 16 | 17 | sessionPinned: Boolean(session ? session.pinned : saved[tab.id]?.pinned) }; |
| 17 | 18 | }); |
| 18 | 19 | for (const row of rows) if (!baseline.has(sessionKey(row))) baseline.set(sessionKey(row), baseline.size); |
| @@ -8,6 +8,16 @@ const sessions = [ | ||
| 8 | 8 | { id: "three", title: "第三段" }, |
| 9 | 9 | ]; |
| 10 | 10 | const 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 | 新增:}); | |
| 11 | 21 | test("default activity, stable clicks and terminal attachment", () => { |
| 12 | 22 | const baseline = new Map(); |
| 13 | 23 | const initial = projectSessionRows([], sessions, {}, undefined, baseline); |
| @@ -38,6 +38,7 @@ export function WorkspaceSidebar({ | ||
| 38 | 38 | onSessionRefresh, |
| 39 | 39 | onSessionOpen, |
| 40 | 40 | openingSession, |
| 41 | 新增: sessionOpenError, | |
| 41 | 42 | onSessionArchive, |
| 42 | 43 | onSessionPin, |
| 43 | 44 | onSessionRename, |
| @@ -228,6 +229,7 @@ export function WorkspaceSidebar({ | ||
| 228 | 229 | tabs={rows} |
| 229 | 230 | saved={rowMetadata} |
| 230 | 231 | openingSession={openingSession} |
| 232 | 新增: sessionOpenError={sessionOpenError} | |
| 231 | 233 | active={home || desktopOpen ? "" : active} |
| 232 | 234 | label={`${project} 的终端`} |
| 233 | 235 | busy={busy} |
| @@ -59,6 +59,7 @@ export function WorkspaceTabs({ | ||
| 59 | 59 | onReorder, |
| 60 | 60 | splitDrag, |
| 61 | 61 | openingSession, |
| 62 | 新增: sessionOpenError, | |
| 62 | 63 | }) { |
| 63 | 64 | const [menu, setMenu] = useState(null); |
| 64 | 65 | const [drag, setDrag] = useState(null); |
| @@ -95,6 +96,9 @@ export function WorkspaceTabs({ | ||
| 95 | 96 | .toLowerCase() |
| 96 | 97 | .includes(query.toLowerCase()), |
| 97 | 98 | ); |
| 99 | 新增: const firstFocusable = tabs.findIndex(tab => tab.historySession | |
| 100 | 新增: ? !busy && openingSession !== tab.cli_session_id && !tab.sessionRunningElsewhere | |
| 101 | 新增: : ready || tab.kind === "terminal"); | |
| 98 | 102 | const finishDrag = (commit, event) => { |
| 99 | 103 | const current = pointer.current; |
| 100 | 104 | pointer.current = null; |
| @@ -293,10 +297,16 @@ export function WorkspaceTabs({ | ||
| 293 | 297 | > |
| 294 | 298 | {tabs.map((tab, index) => { |
| 295 | 299 | 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}`; | |
| 296 | 305 | return ( |
| 306 | 新增: <React.Fragment key={tab.id}> | |
| 297 | 307 | <div |
| 298 | 删除: key={tab.id} | |
| 299 | 308 | data-tab-id={tab.id} |
| 309 | 新增: title={runningElsewhere ? runningNotice : undefined} | |
| 300 | 310 | 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" : ""}`} |
| 301 | 311 | style={ |
| 302 | 312 | horizontal |
| @@ -326,17 +336,19 @@ export function WorkspaceTabs({ | ||
| 326 | 336 | <button |
| 327 | 337 | role={tab.historySession ? undefined : "tab"} |
| 328 | 338 | 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} | |
| 330 | 342 | aria-label={tab.claudeLabel ? `${title} · ${tab.claudeLabel}` : title} |
| 331 | 343 | aria-selected={tab.historySession ? undefined : tab.id === active} |
| 332 | 344 | tabIndex={ |
| 333 | 345 | tab.id === active || |
| 334 | 删除: (!tabs.some((t) => t.id === active) && index === 0) | |
| 346 | 新增: (!tabs.some((t) => t.id === active) && index === firstFocusable) | |
| 335 | 347 | ? 0 |
| 336 | 348 | : -1 |
| 337 | 349 | } |
| 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(" · ")} | |
| 340 | 352 | onClick={() => onSelect(tab.id)} |
| 341 | 353 | onContextMenu={(event) => showMenu(tab, event)} |
| 342 | 354 | onKeyDown={(event) => { |
| @@ -354,17 +366,20 @@ export function WorkspaceTabs({ | ||
| 354 | 366 | const next = horizontal ? "ArrowRight" : "ArrowDown"; |
| 355 | 367 | if (![prev, next, "Home", "End"].includes(event.key)) return; |
| 356 | 368 | 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[ | |
| 358 | 373 | event.key === "Home" |
| 359 | 374 | ? 0 |
| 360 | 375 | : event.key === "End" |
| 361 | 删除: ? tabs.length - 1 | |
| 362 | 删除: : (index + | |
| 376 | 新增: ? enabled.length - 1 | |
| 377 | 新增: : (from + | |
| 363 | 378 | (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); | |
| 368 | 383 | }} |
| 369 | 384 | > |
| 370 | 385 | <TabIcon kind={tab.kind} favicon={tab.favicon} size={15} |
| @@ -373,8 +388,8 @@ export function WorkspaceTabs({ | ||
| 373 | 388 | <span>{title}</span> |
| 374 | 389 | {tab.claudeLabel && <small className="claude-tab-profile">{tab.claudeLabel}</small>} |
| 375 | 390 | {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 ? "正在打开会话" : "会话正在运行"} />} | |
| 378 | 393 | </button> |
| 379 | 394 | {horizontal || vertical ? ( |
| 380 | 395 | <button |
| @@ -394,6 +409,8 @@ export function WorkspaceTabs({ | ||
| 394 | 409 | </div> |
| 395 | 410 | )} |
| 396 | 411 | </div> |
| 412 | 新增: {openError && <p id={errorID} className="sidebar-session-open-error" role="alert">{openError}</p>} | |
| 413 | 新增: </React.Fragment> | |
| 397 | 414 | ); |
| 398 | 415 | })} |
| 399 | 416 | </div> |

