跳到主要内容

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

浏览文件

windows_cli_channel_test.py

129 行 · 8.4 KB历史下载
1"""Native Windows smoke: real private socket, MCP and hook entry points.
2
3Run with the staged uv Python. This uses only its own temporary profile and
4never reads an existing Claude login or sends a model request.
5"""
6import concurrent.futures
7import importlib.util
8import json
9import os
10from pathlib import Path
11import queue
12import subprocess
13import sys
14import tempfile
15import threading
16import unittest
17import uuid
18
19
20@unittest.skipUnless(sys.platform == 'win32', 'requires native Windows Python')
21class NativeChannelTests(unittest.TestCase):
22 def test_live_snapshot_is_readable_by_another_native_process_and_cleaned(self):
23 spec=importlib.util.spec_from_file_location('windows_snapshot_identity',Path(__file__).with_name('mobile_cli_identity.py'))
24 identity=importlib.util.module_from_spec(spec);spec.loader.exec_module(identity)
25 from unittest.mock import patch
26 with tempfile.TemporaryDirectory(prefix='cage-ccs-snapshot-') as folder:
27 file=tempfile.NamedTemporaryFile(dir=folder,suffix='.settings.json',delete=False)
28 try:
29 payload={'env':{'ANTHROPIC_API_KEY':'fixture-only'},'model':'fixture-model','permissions':{'deny':['Bash(fixture)']}}
30 with patch.object(identity,'managed_settings',return_value=[]):
31 identity.freeze_settings({'CLAUDE_CONFIG_DIR':folder},payload,file)
32 self.assertFalse(os.get_inheritable(file.fileno()))
33 result=subprocess.run([sys.executable,'-X','utf8','-I','-c','import json,sys;v=json.load(open(sys.argv[1],encoding="utf-8"));assert v["model"]=="fixture-model";assert v["permissions"]["deny"]==["Bash(fixture)"]',file.name],capture_output=True,timeout=5)
34 self.assertEqual(result.returncode,0)
35 finally:file.close();Path(file.name).unlink()
36 self.assertEqual(list(Path(folder).iterdir()),[])
37 def test_native_mcp_and_hooks_preserve_receipt_and_permission(self):
38 source = Path(__file__).with_name('cli_channel.py').resolve()
39 with tempfile.TemporaryDirectory(prefix='cage-cli-native-') as temporary:
40 home = Path(temporary).resolve()
41 connection = str(uuid.uuid4())
42 state_root = home / 'channels'
43 folder = state_root / connection
44 folder.mkdir(parents=True)
45 env = {**os.environ, 'USERPROFILE':str(home), 'CAGE_CLI_STATE_ROOT':str(state_root),
46 'CAGE_CLI_ACCOUNT_ROOT':str(home/'accounts'), 'CAGE_CLI_SHARED_ROOT':str(home/'shared')}
47 (folder/'state.json').write_text(json.dumps({'cli_id':connection,'config':str(home/'.claude'),
48 'workspace':str(home/'project'),'pid':os.getpid(),'busy':False,'closed':False}),encoding='utf-8')
49 child = subprocess.Popen([sys.executable,'-X','utf8','-I',str(source),'serve',connection],
50 env=env,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True,encoding='utf-8')
51 lines = queue.Queue()
52 reader = threading.Thread(target=lambda:[lines.put(json.loads(line)) for line in child.stdout],daemon=True)
53 reader.start()
54 def send(value):
55 child.stdin.write(json.dumps({'jsonrpc':'2.0',**value})+'\n');child.stdin.flush()
56 def invoke(mode,value):
57 result=subprocess.run([sys.executable,'-X','utf8','-I',str(source),mode,'-' if mode=='rpc' else connection],
58 env=env,input=json.dumps(value),text=True,encoding='utf-8',capture_output=True,timeout=5,check=True)
59 return json.loads(result.stdout)
60 def rpc(**fields): return invoke('rpc',{'cli_id':connection,'connection':connection,**fields})
61 try:
62 send({'id':1,'method':'initialize','params':{'protocolVersion':'2024-11-05'}})
63 self.assertIn('claude/channel/permission',lines.get(timeout=5)['result']['capabilities']['experimental'])
64 send({'method':'notifications/initialized'})
65 request=str(uuid.uuid4());text='中文🙂\n保留 </channel> 原文'
66 with concurrent.futures.ThreadPoolExecutor(2) as workers:
67 replies=list(workers.map(lambda _:rpc(action='send',request_id=request,text=text),range(2)))
68 self.assertEqual(replies,[{'ok':True},{'ok':True}])
69 event=lines.get(timeout=5)
70 self.assertEqual(event['params']['content'],text)
71 self.assertEqual(event['params']['meta']['cage_request'],request)
72 with self.assertRaises(queue.Empty):lines.get(timeout=.1)
73 self.assertIn('error',rpc(action='send',request_id=request,text='changed'))
74 invoke('hook',{'hook_event_name':'UserPromptSubmit','session_id':connection,'cwd':str(home/'project')})
75 state=json.loads((folder/'state.json').read_text(encoding='utf-8'))
76 self.assertTrue(state['busy']);self.assertEqual(state['requests'][request],__import__('hashlib').sha256(text.encode()).hexdigest())
77 send({'method':'notifications/claude/channel/permission_request','params':{'request_id':'native-proof','tool_name':'PowerShell','input_preview':'{"command":"Get-Date"}'}})
78 import time
79 until=time.monotonic()+3
80 while time.monotonic()<until:
81 state=json.loads((folder/'state.json').read_text(encoding='utf-8'))
82 if state.get('approvals'):break
83 time.sleep(.01)
84 approval=state['approvals'][0]['id']
85 self.assertEqual(rpc(action='approve',approval_id=approval,allow=False),{'ok':True})
86 self.assertEqual(lines.get(timeout=5)['params'],{'request_id':'native-proof','behavior':'deny'})
87 self.assertIn('error',rpc(action='approve',approval_id=approval,allow=True))
88 invoke('hook',{'hook_event_name':'Stop','session_id':connection})
89 self.assertFalse(json.loads((folder/'state.json').read_text(encoding='utf-8'))['busy'])
90 finally:
91 child.stdin.close()
92 try:child.wait(timeout=5)
93 except subprocess.TimeoutExpired:child.kill();child.wait()
94 reader.join(timeout=1);child.stdout.close();child.stderr.close()
95 self.assertEqual(child.returncode,0)
96 self.assertIsNone(json.loads((folder/'state.json').read_text(encoding='utf-8'))['channel_pid'])
97
98 def test_process_probe_does_not_signal_an_unrelated_native_process(self):
99 source=Path(__file__).with_name('windows_cli_platform.py')
100 spec=importlib.util.spec_from_file_location('windows_cli_platform_test',source)
101 platform=importlib.util.module_from_spec(spec);spec.loader.exec_module(platform)
102 self.assertTrue(platform.process_live(os.getpid()))
103 self.assertTrue(platform.process_fingerprint(os.getpid()))
104 from unittest.mock import patch
105 with patch.dict(os.environ,{'CAGE_CLI_BINARY':str(Path(sys.executable).with_name('claude.exe'))}):
106 with self.assertRaises(ValueError):platform.terminate_cli(os.getpid())
107 self.assertTrue(platform.process_live(os.getpid()))
108
109 def test_native_child_job_closes_only_its_tree(self):
110 source=Path(__file__).with_name('windows_cli_platform.py')
111 spec=importlib.util.spec_from_file_location('windows_cli_job_test',source)
112 platform=importlib.util.module_from_spec(spec);spec.loader.exec_module(platform)
113 with tempfile.TemporaryDirectory(prefix='cage-cli-job-') as temporary:
114 marker=Path(temporary)/'child-pid'
115 script='import subprocess,sys,time,pathlib; child=subprocess.Popen([sys.executable,"-c","import time;time.sleep(60)"]);pathlib.Path(sys.argv[1]).write_text(str(child.pid));time.sleep(60)'
116 process=platform.CliProcess([sys.executable,'-X','utf8','-c',script,str(marker)],dict(os.environ))
117 try:
118 import time
119 until=time.monotonic()+5
120 while time.monotonic()<until and not marker.exists():time.sleep(.02)
121 descendant=int(marker.read_text())
122 self.assertTrue(platform.process_live(descendant))
123 finally:process.close()
124 until=time.monotonic()+5
125 while time.monotonic()<until and platform.process_live(descendant):time.sleep(.02)
126 self.assertFalse(platform.process_live(descendant));self.assertTrue(platform.process_live(os.getpid()))
127
128
129if __name__=='__main__':unittest.main()