跳到主要内容

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

浏览文件

cli_channel_test.py

340 行 · 21.9 KB历史下载
1import concurrent.futures
2import importlib.util
3import io
4import json
5import os
6from pathlib import Path
7import select
8import subprocess
9import sys
10import tempfile
11import time
12import unittest
13import uuid
14from unittest.mock import patch
15
16sys.dont_write_bytecode = True
17source = Path(__file__).with_name("cli_channel.py").resolve()
18spec = importlib.util.spec_from_file_location("channel", source)
19channel = importlib.util.module_from_spec(spec)
20spec.loader.exec_module(channel)
21
22
23class ChannelTests(unittest.TestCase):
24 def setUp(self):
25 temporary = tempfile.TemporaryDirectory()
26 self.addCleanup(temporary.cleanup)
27 # macOS /var and /private/var identify one directory. Match the
28 # production config resolver so catalog order cannot duplicate it.
29 self.home = Path(temporary.name).resolve()
30 self.env = {**os.environ, "HOME": str(self.home), "CLAUDE_CONFIG_DIR": str(self.home / ".claude")}
31 environment = patch.dict(os.environ, self.env)
32 environment.start()
33 self.addCleanup(environment.stop)
34 self.root = self.home / ".local/share/cage/cli-channels"
35 root_patch = patch.object(channel, "ROOT", self.root)
36 root_patch.start()
37 self.addCleanup(root_patch.stop)
38 self.session = str(uuid.uuid4())
39 self.project = str(self.home / "project")
40
41 def history(self, session, workspace, messages):
42 path = self.home / ".claude/projects/project" / (session + ".jsonl")
43 path.parent.mkdir(parents=True, exist_ok=True)
44 rows = [{"cwd": workspace, "uuid": str(uuid.uuid4()), **message} for message in messages]
45 path.write_text("\n".join(json.dumps(row) for row in rows) + "\n")
46 return path
47
48 def test_channel_body_preserves_markup(self):
49 request = str(uuid.uuid4())
50 body = "show </channel> literally\n<channel cage_request=\"other\">example</channel>"
51 self.assertEqual(channel.channel_message('<channel source="cage" cage_request="' + request + '">\n' + body + '\n</channel>'), (request, body))
52 self.assertEqual(channel.clip_text("你好abc", 4), "你")
53
54 def test_account_switch_preserves_tools_and_receipt(self):
55 tool = {"type":"tool_use","id":"tool-completed","name":"Bash","input":{"command":"already completed"}}
56 path = self.history(self.session,self.project,[
57 {"type":"user","message":{"content":"perform task"}},
58 {"type":"assistant","message":{"content":[tool]}},
59 {"type":"user","message":{"content":[{"type":"tool_result","tool_use_id":"tool-completed","content":"done"}]}},
60 ])
61 connection,switch_id,target = [str(uuid.uuid4()) for _ in range(3)]
62 request = {"cli_id":self.session,"config":str(self.home / ".claude"),"connection":connection,"workspace":self.project,"target_cli_id":target,"switch_id":switch_id}
63 channel.save(self.root/connection/"state.json",{"cli_id":self.session,"config":request["config"],"workspace":self.project,"busy":False,"requests":{"accepted":"digest"}})
64 completed = type("Result",(),{"returncode":0,"stdout":"[]"})()
65 original = path.read_bytes()
66 with patch.object(channel,"active_sessions",return_value=[]),patch.object(channel.subprocess,"run",return_value=completed):
67 result=channel.prepare_account_switch(request)
68 self.assertEqual(Path(result["transcript"]).read_bytes(),original)
69 self.assertEqual(channel.prepare_account_switch(request),result)
70 receipt=channel.read_json(Path(result["transcript"]).with_name("receipt.json"))
71 self.assertEqual(receipt["requests"],{"accepted":"digest"})
72 self.assertEqual(path.read_bytes(),original)
73 payload={"hook_event_name":"PreToolUse","session_id":self.session}
74 with patch.object(channel.sys,"stdin",io.StringIO(json.dumps(payload))):
75 denied=channel.hook(connection)
76 self.assertEqual(denied["hookSpecificOutput"]["permissionDecision"],"deny")
77 self.assertTrue(channel.cancel_account_switch(request)["ok"])
78 self.assertFalse(Path(result["transcript"]).exists())
79 self.assertTrue(path.exists())
80
81 def test_account_switch_refuses_busy_and_unresolved_tools(self):
82 path=self.history(self.session,self.project,[{"type":"assistant","message":{"content":[{"type":"tool_use","id":"uncertain","name":"Bash","input":{}}]}}])
83 connection,switch_id,target=[str(uuid.uuid4()) for _ in range(3)]
84 request={"cli_id":self.session,"config":str(self.home/".claude"),"connection":connection,"workspace":self.project,"target_cli_id":target,"switch_id":switch_id}
85 state={"cli_id":self.session,"config":request["config"],"workspace":self.project,"busy":True}
86 channel.save(self.root/connection/"state.json",state)
87 with patch.object(channel.os,"kill") as kill:
88 with self.assertRaises(ValueError): channel.prepare_account_switch(request)
89 kill.assert_not_called()
90 state["busy"]=False
91 channel.save(self.root/connection/"state.json",state)
92 completed=type("Result",(),{"returncode":0,"stdout":"[]"})()
93 with patch.object(channel,"active_sessions",return_value=[]),patch.object(channel.subprocess,"run",return_value=completed):
94 with self.assertRaisesRegex(ValueError,"工具"): channel.prepare_account_switch(request)
95 self.assertTrue(path.exists())
96 self.assertFalse((self.root.parent/"cli-account-switches"/switch_id/"history.jsonl").exists())
97
98 def test_failure_hook_reports_kind_and_new_turn_clears_it(self):
99 payload={"hook_event_name":"StopFailure","session_id":self.session,"error":"rate_limit","error_details":"private upstream diagnostic"}
100 with patch.object(channel.sys,"stdin",io.StringIO(json.dumps(payload))):channel.hook(self.session)
101 state=channel.read_json(self.root/self.session/"state.json")
102 self.assertEqual(state["account_failure"],"rate_limit")
103 self.assertNotIn("private upstream",json.dumps(state))
104 with patch.object(channel.sys,"stdin",io.StringIO(json.dumps({**payload,"hook_event_name":"UserPromptSubmit"}))):channel.hook(self.session)
105 self.assertNotIn("account_failure",channel.read_json(self.root/self.session/"state.json"))
106
107 def test_first_display_delta_after_launch(self):
108 with channel.state_file(self.session) as state:
109 state["display"] = None
110 payload = {"hook_event_name":"MessageDisplay","session_id":self.session,"message_id":"reply","index":0,"delta":"hello"}
111 with patch.object(channel.sys,"stdin",io.StringIO(json.dumps(payload))):
112 channel.hook(self.session)
113 self.assertEqual(channel.read_json(self.root / self.session / "state.json")["display"]["text"],"hello")
114
115 def test_ready_channel_wins_over_a_newer_unready_duplicate(self):
116 config = str(channel.config_directory("default"))
117 ready, starting = str(uuid.uuid4()), str(uuid.uuid4())
118 channel.save(self.root / ready / "state.json", {"cli_id":self.session,"config":config,"pid":os.getpid(),"channel_pid":os.getpid(),"updated_at":1})
119 channel.save(self.root / starting / "state.json", {"cli_id":self.session,"config":config,"pid":os.getpid(),"channel_pid":None,"updated_at":2})
120 self.assertEqual(channel.connection_for(self.session,Path(config))[0],ready)
121
122 def test_launch_retains_pending_permission_mode(self):
123 config = str(channel.config_directory("default"))
124 channel.save(channel.handoff_receipt(config,self.session),{"resume_task":True,"permission_mode":"manual"})
125 connection = str(uuid.uuid4())
126 with patch.object(channel,"migrate_cage_policy"), patch.object(channel,"active_session",return_value=False), patch.object(channel.os,"execvpe") as execute:
127 channel.launch({"id":connection,"resume":self.session,"prefix":["claude"],"config":config})
128 self.assertEqual(execute.call_args.args[1][-2:],["--permission-mode","manual"])
129 self.assertTrue(channel.read_json(self.root / connection / "state.json")["resume_task"])
130
131 def test_handoff_preserves_executing_tools(self):
132 request = {"cli_id":self.session, "config":str(self.home / ".claude"), "workspace":self.project}
133 for status in ("busy", None):
134 rows = [{"sessionId":self.session, "pid":1234, "cwd":self.project, "status":status, "kind":"interactive"}]
135 with patch.object(channel, "active_sessions", return_value=rows), patch.object(channel.os, "kill") as kill:
136 self.assertTrue(channel.handoff_session(request)["running"])
137 kill.assert_not_called()
138
139 def test_handoff_rechecks_idle_identity_and_waits_for_exit(self):
140 request = {"cli_id":self.session, "config":str(self.home / ".claude"), "workspace":self.project}
141 row = {"sessionId":self.session, "pid":1234, "cwd":self.project, "status":"idle", "kind":"interactive"}
142 with patch.object(channel, "active_sessions", return_value=[row]), patch.object(channel, "live", return_value=False), patch.object(channel.os, "kill") as kill:
143 self.assertFalse(channel.handoff_session(request)["running"])
144 kill.assert_called_once_with(1234, channel.signal.SIGTERM)
145 with patch.object(channel, "active_sessions", side_effect=[[row], [{**row, "status":"busy"}]]), patch.object(channel.os, "kill") as kill:
146 self.assertTrue(channel.handoff_session(request)["running"])
147 kill.assert_not_called()
148
149 def test_handoff_waiting_task_requires_fresh_approval(self):
150 request = {"cli_id":self.session, "config":str(self.home / ".claude"), "workspace":self.project}
151 row = {"sessionId":self.session, "pid":1234, "cwd":self.project, "status":"waiting", "kind":"interactive"}
152 with patch.object(channel, "active_sessions", return_value=[row]), patch.object(channel, "live", return_value=False), patch.object(channel.os, "kill") as kill:
153 self.assertFalse(channel.handoff_session(request)["running"])
154 kill.assert_called_once_with(1234, channel.signal.SIGTERM)
155 self.assertTrue(channel.read_json(channel.handoff_receipt(request["config"], self.session))["resume_task"])
156 with patch.object(channel, "active_sessions", return_value=[{**row, "cwd":self.project + "-other"}]), patch.object(channel.os, "kill") as kill:
157 with self.assertRaises(ValueError): channel.handoff_session(request)
158 kill.assert_not_called()
159
160 @patch.object(channel, "running_sessions", return_value=[])
161 def test_catalog_activity_requires_live_busy_process(self, _registry):
162 self.history(self.session, self.project, [{"type":"user", "message":{"content":"hello"}}])
163 connection = str(uuid.uuid4())
164 with channel.state_file(connection) as state:
165 state.update(cli_id=self.session, config=str(self.home / ".claude"), workspace=self.project,
166 pid=os.getpid(), busy=True)
167 request = {"accounts":["default"], "workspaces":{self.project:self.project}}
168 item = channel.discover(request)[0]
169 self.assertTrue(item["active"])
170 self.assertTrue(item["running"])
171 self.assertTrue(channel.view(self.home / ".claude", self.session)["active"])
172 with channel.state_file(connection) as state:
173 state["busy"] = False
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")
177 with channel.state_file(connection) as state:
178 state.update(busy=True, closed=True)
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)))
199
200 def test_purge_removes_only_target_transcripts_and_retries(self):
201 target = self.history(self.session, self.project, [{"type":"user", "message":{"content":"delete this"}}])
202 other = self.history(str(uuid.uuid4()), self.project, [{"type":"user", "message":{"content":"keep this"}}])
203 child = target.parent / self.session / "subagents" / "agent-fixture.jsonl"
204 child.parent.mkdir(parents=True)
205 child.write_text("child history")
206 project_file = self.home / "project" / "main.py"
207 project_file.parent.mkdir()
208 project_file.write_text("project content")
209 request = {"cli_id":self.session, "account":"default", "workspace":self.project, "expect_history":True}
210 with patch.object(channel, "active_session", return_value=True):
211 with self.assertRaises(ValueError): channel.purge_session(request)
212 self.assertTrue(target.exists())
213 with patch.object(channel, "active_session", return_value=False):
214 with self.assertRaises(ValueError): channel.purge_session({**request, "workspace":self.project + "-other"})
215 self.assertTrue(channel.purge_session(request)["ok"])
216 self.assertTrue(channel.purge_session(request)["ok"])
217 self.assertFalse(target.exists())
218 self.assertFalse(child.parent.parent.exists())
219 self.assertTrue(other.exists())
220 self.assertEqual(project_file.read_text(), "project content")
221
222 def test_only_cage_default_policy_is_migrated(self):
223 policy = self.home / "managed-settings.json"
224 original = {"permissions": {"defaultMode": "bypassPermissions"}, "tui": "fullscreen"}
225 policy.write_text(json.dumps(original))
226 def path(value):
227 return policy if str(value) == "/etc/claude-code/managed-settings.json" else Path(value)
228 def migrate(args, **kwargs):
229 code = args[-1].replace("/etc/claude-code/managed-settings.json", str(policy))
230 exec(code, {"__name__": "migration_test"})
231 with patch.object(channel, "Path", path), patch.object(channel.sys, "platform", "linux"), patch.object(channel.subprocess, "run", side_effect=migrate) as run:
232 self.assertTrue(channel.migrate_cage_policy())
233 self.assertTrue(json.loads(policy.read_text())["channelsEnabled"])
234 backup = policy.with_name("managed-settings.json.cage-before-channels")
235 self.assertEqual(json.loads(backup.read_text()), original)
236 blocked = {**original, "channelsEnabled": False}
237 policy.write_text(json.dumps(blocked))
238 channel.migrate_cage_policy()
239 self.assertEqual(json.loads(policy.read_text()), blocked)
240 self.assertEqual(run.call_count, 1)
241
242 @patch.object(channel, "running_sessions", return_value=[])
243 def test_history_projects_and_channel_identity(self, _registry):
244 request = str(uuid.uuid4())
245 self.history(self.session, self.project + "/nested", [
246 {"type": "user", "message": {"content": "desktop question"}},
247 {"type": "assistant", "message": {"content": [{"type": "text", "text": "desktop answer"}]}},
248 {"type": "assistant", "message": {"model":"<synthetic>", "content": [{"type": "text", "text": "No response requested."}]}},
249 {"type": "user", "isMeta": True, "message": {"content": "system metadata"}},
250 {"type": "user", "isMeta": True, "message": {"content": '<channel source="cage" cage_request="' + request + '">\nphone question\n</channel>'}},
251 {"type": "user", "message": {"content": [{"type": "tool_result", "content": "private tool output"}]}},
252 {"type": "assistant", "message": {"content": [{"type": "text", "text": "phone answer"}]}},
253 ])
254 self.history(str(uuid.uuid4()), self.project + "-other", [{"type": "user", "message": {"content": "outside project"}}])
255 found = channel.discover({"accounts": ["default"], "workspaces": [self.project]})
256 self.assertEqual([item["cli_id"] for item in found], [self.session])
257 view = channel.view(channel.config_directory("default"), self.session)
258 self.assertFalse(view["can_send"])
259 self.assertEqual(len(view["turns"]), 2)
260 self.assertEqual(view["turns"][1]["id"], request)
261 self.assertEqual(view["turns"][1]["prompt"], "phone question")
262 self.assertEqual(view["turns"][1]["text"], "phone answer")
263 self.assertNotIn("private tool output", json.dumps(view))
264
265 def test_history_pairs_tool_only_rows_and_keeps_task_notice(self):
266 self.history(self.session, self.project, [
267 {"type": "user", "message": {"content": "run"}},
268 {"type": "assistant", "message": {"content": [
269 {"type": "tool_use", "id": "tool-1", "name": "Bash", "input": {"description": "检查结果", "command": "private-command"}},
270 {"type": "tool_use", "id": "tool-2", "name": "Read", "input": {"file_path": "result.md"}},
271 ]}},
272 {"type": "user", "message": {"content": [
273 {"type": "tool_result", "tool_use_id": "tool-2", "content": "private-output"},
274 {"type": "tool_result", "tool_use_id": "tool-1", "is_error": True},
275 ]}},
276 {"type": "user", "isMeta": True, "message": {"content": "<task-notification><summary>完成</summary></task-notification>"}},
277 ])
278 view = channel.view(channel.config_directory("default"), self.session)
279 self.assertEqual(len(view["turns"]), 2)
280 tools = view["turns"][0]["tools"]
281 self.assertEqual([(t["name"], t["status"], t["detail"]) for t in tools],
282 [("Bash", "failed", "检查结果"), ("Read", "completed", "result.md")])
283 self.assertTrue(view["turns"][1]["prompt"].startswith("<task-notification>"))
284 self.assertNotIn("private-", json.dumps(view))
285
286 def test_concurrent_send_and_stale_approval(self):
287 with channel.state_file(self.session) as state:
288 state.update(cli_id=self.session, config=str(channel.config_directory("default")), workspace=self.project, pid=os.getpid())
289 process = subprocess.Popen([sys.executable, "-I", str(source), "serve", self.session],
290 env=self.env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
291 def stop():
292 process.stdin.close()
293 try:
294 process.wait(timeout=5)
295 except subprocess.TimeoutExpired:
296 process.kill()
297 process.wait()
298 process.stdout.close()
299 process.stderr.close()
300 self.addCleanup(stop)
301 def event(message):
302 process.stdin.write(json.dumps({"jsonrpc": "2.0", **message}) + "\n")
303 process.stdin.flush()
304 event({"id": 1, "method": "initialize", "params": {"protocolVersion": "2024-11-05"}})
305 self.assertIn("claude/channel/permission", json.loads(process.stdout.readline())["result"]["capabilities"]["experimental"])
306 event({"method": "notifications/initialized"})
307 def rpc(**fields):
308 result = subprocess.run([sys.executable, "-I", str(source), "rpc", "-"], env=self.env, text=True,
309 input=json.dumps({"cli_id": self.session, "connection": self.session, **fields}), capture_output=True, check=True)
310 return json.loads(result.stdout)
311 request = str(uuid.uuid4())
312 with concurrent.futures.ThreadPoolExecutor(2) as workers:
313 replies = list(workers.map(lambda _: rpc(action="send", request_id=request, text="once"), range(2)))
314 self.assertEqual(replies, [{"ok": True}, {"ok": True}])
315 sent = json.loads(process.stdout.readline())
316 self.assertEqual(sent["params"]["meta"]["cage_request"], request)
317 self.assertFalse(select.select([process.stdout], [], [], 0.1)[0])
318 self.assertIn("error", rpc(action="send", request_id=request, text="changed"))
319 event({"method": "notifications/claude/channel/permission_request", "params": {
320 "request_id": "abcde", "tool_name": "Bash", "input_preview": '{"command":"echo test"}'}})
321 path = self.root / self.session / "state.json"
322 deadline = time.monotonic() + 3
323 while time.monotonic() < deadline and not channel.read_json(path).get("approvals"):
324 time.sleep(0.01)
325 approval = channel.read_json(path)["approvals"][0]
326 self.assertIn("error", rpc(action="approve", approval_id=str(uuid.uuid4()), allow=True))
327 self.assertEqual(rpc(action="approve", approval_id=approval["id"], allow=False), {"ok": True})
328 self.assertEqual(json.loads(process.stdout.readline())["params"], {"request_id": "abcde", "behavior": "deny"})
329 self.assertIn("error", rpc(action="approve", approval_id=approval["id"], allow=True))
330 with channel.state_file(self.session) as state:
331 state["resume_task"] = True
332 self.assertEqual(rpc(action="resume"), {"ok":True})
333 self.assertEqual(rpc(action="resume"), {"ok":True})
334 resumed = json.loads(process.stdout.readline())
335 self.assertEqual(resumed["params"]["meta"], {"cage_resume":"true"})
336 self.assertFalse(select.select([process.stdout], [], [], 0.1)[0], "resume was injected twice")
337
338
339if __name__ == "__main__":
340 unittest.main()