跳到主要内容

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

提交记录

Linux 画面在无人操作时降低刷新率,操作时立即恢复

Chromium 与 Electron 的软件合成按虚拟显示的 RandR 刷新率出帧。新增的 显示调度在键鼠输入或窗口尺寸变化时保持 60 Hz,停止操作约 3 秒后降到 30 Hz,约 3 分钟后降到 20 Hz;渲染、抓屏、编码、传输和宿主解码随之减少, 分辨率与清晰度不变。浏览器与 Claude Desktop 两块显示共用同一脚本。 读取、判断与切换在一次 X server grab 内完成,不会把尺寸调整方刚设置的 画面改回旧尺寸;输入法的 F24 光标探测键不计为用户操作;调度退出时恢复 全速。缺少 python3-xlib 的环境保持原有 60 Hz。 Co-Authored-By: Claude <[email protected]>

作者
Lee-xeo
时间
2026/11/10 22:15
提交
d8d9c2a
上一个
206eec3
这个版本的全部文件
修改docs/guide/browser.md+2 −0看文件
@@ -15,6 +15,8 @@ keywords: Chromium 浏览器 设置 无痕 Cookie 扩展 插件 ZIP 收藏 新
1515
1616Linux 环境在最后一个浏览器查看窗口离开后,将浏览器窗口最小化,让后台网页采用 Chromium 的节流机制。返回浏览器时恢复原窗口和未保存的输入。多个工作台同时查看时,仍在查看的窗口继续显示。手机浏览器拥有独立会话。
1717
18新增:Linux 环境的浏览器和 Claude Desktop 画面按使用情况调整刷新率。操作键盘、鼠标或调整窗口时保持 60 Hz;停止操作约 3 秒后降到 30 Hz,约 3 分钟无操作后降到 20 Hz,再次操作时立即恢复。分辨率、字号和清晰度保持不变,网页动画与视频在无人操作时按较低帧率播放。此功能随环境组件更新启用,需要环境中的 `python3-xlib`:已安装 Claude Desktop 的环境直接生效,只使用浏览器的旧环境在下次更新环境工具后生效。
19新增:
1820新配置默认开启“设置 → 通用 → 优先流畅”。Linux 浏览器和 Claude Desktop 使用 1.5 倍渲染,字号与可见内容尺寸保持一致,比 2 倍渲染减少约 44% 的像素量。需要更清晰的细节时可关闭,画质设置在下次启动环境时生效。已有配置沿用原画质。
1921
2022地址栏右侧的下载按钮在右上角展开文件列表,可查看下载进度、另存为、打开文件或在文件夹中显示;保存失败时可重试。长列表在面板内滚动,点击外部或按 Esc 收起。侧栏“下载”也可打开此面板。
修改docs/guide/desktop.md+2 −0看文件
@@ -24,6 +24,8 @@ Chat 和 Code 在同一个官方应用内使用。需要额外虚拟机的 Cowor
2424
2525右上角“显示大小”默认 100%,调小可显示更多内容,调大可放大文字和控件。窗口、侧栏变化时画面自动适配;设置保存在本机。提示“画面尺寸未能同步”时点“重试调整”。
2626
27新增:Linux 环境的 Desktop 画面在无人操作时自动降低刷新率,操作时立即恢复 60 Hz,清晰度不变,详见[浏览器说明](browser.md#打开网页与浏览器设置)。
28新增:
2729滚动卡顿时到“设置 → 通用”开启“流畅画质”,保存并在下次启动环境后生效。它降低绘图像素密度,控件逻辑大小保留。性能还受主机 CPU、内存以及远程网络影响。
2830
2931## 复制与粘贴
修改internal/cage/browser-agent.mjs+5 −1看文件
@@ -651,7 +651,11 @@ async function resizeDisplay(width, height) {
651651 )
652652 throw new Error("Invalid display size");
653653 const name = `cage-${width}x${height}`;
654删除: if (displaySize === name) return { ok: true };
654新增: if (displaySize === name) {
655新增: // A viewer attaching at an unchanged size still restores the full rate.
656新增: await runFile("/usr/bin/xrandr", ["--output", "VNC-0", "--mode", name]).catch(() => {});
657新增: return { ok: true };
658新增: }
655659 const { stdout } = await runFile("/usr/bin/xrandr", ["--query"]);
656660 if (!stdout.includes(name)) {
657661 const rate = (((width + 32) * (height + 8) * 60) / 1000000).toFixed(3);
修改internal/cage/claude-desktop-session.sh+4 −0看文件
@@ -31,6 +31,10 @@ done
3131xdpyinfo -display "$DISPLAY" >/dev/null
3232openbox --config-file /etc/claude-cage/desktop-openbox.xml &
3333X0tigervnc -display "$DISPLAY" -rfbport -1 -rfbunixpath "$XDG_RUNTIME_DIR/vnc.sock" -rfbunixmode 0600 -SecurityTypes VncAuth -PasswordFile "$XDG_RUNTIME_DIR/vnc-password" -AlwaysShared &
34新增:# Lower the refresh rate of unattended animation. Optional on older guests.
35新增:if [ -x /usr/local/bin/cage-display-governor ]; then
36新增: /usr/local/bin/cage-display-governor &
37新增:fi
3438mkfifo -m 0600 "$XDG_RUNTIME_DIR/unlock"
3539gnome-keyring-daemon --unlock --components=secrets < "$XDG_RUNTIME_DIR/unlock" >/dev/null
3640rm "$XDG_RUNTIME_DIR/unlock"
修改internal/cage/claude_desktop.go+1 −1看文件
@@ -32,7 +32,7 @@ func ClaudeDesktopInstallScript() string {
3232// Provisioning is independent of the browser and never restarts it. Desktop
3333// services are deliberately not enabled at boot: the user opens the app.
3434func ClaudeDesktopProvisionScript() string {
35删除: return "set -euo pipefail\n" + sharedClipboardScript() + nativeInputScript() + fileInputScript() +
35新增: return "set -euo pipefail\n" + sharedClipboardScript() + nativeInputScript() + fileInputScript() + displayGovernorScript() +
3636 "sudo install -d -m 0755 /etc/claude-cage\n" +
3737 "sudo tee /usr/local/bin/cage-claude-session >/dev/null <<'CAGE_CLAUDE_SESSION'\n" + claudeDesktopSession + "\nCAGE_CLAUDE_SESSION\n" +
3838 "sudo tee /usr/local/bin/cage-claude-open >/dev/null <<'CAGE_CLAUDE_OPEN'\n" + claudeDesktopOpen + "\nCAGE_CLAUDE_OPEN\n" +
新增internal/cage/display-governor.py+263 −0看文件
@@ -0,0 +1,263 @@
1新增:#!/usr/bin/python3
2新增:"""Pace a Cage virtual display by what its viewer is doing.
3新增:
4新增:Chromium and Electron render in software here, and take their frame interval
5新增:from the display's RandR refresh rate. Rendering, capture, encoding, transport
6新增:and host decoding therefore all scale with that one number. Input restores the
7新增:full rate within a few frames; an unattended animation runs at a lower one.
8新增:"""
9新增:import os
10新增:import select
11新增:import signal
12新增:import struct
13新增:import sys
14新增:import time
15新增:
16新增:ACTIVE_RATE = 60
17新增:PASSIVE_RATE = 30
18新增:IDLE_RATE = 20
19新增:ACTIVE_HOLD = 3.0
20新增:IDLE_AFTER = 180.0
21新增:# Size owners name their modes cage-<w>x<h> and cage-phone-<w>x<h>, and remove
22新增:# only those. This prefix keeps the two sets of modes apart.
23新增:PREFIX = 'fps'
24新增:PROBE_KEYSYM = 0xffd5 # F24, injected by the input bridge to refresh a caret.
25新增:
26新增:
27新增:def target_rate(idle):
28新增: if idle < ACTIVE_HOLD:
29新增: return ACTIVE_RATE
30新增: if idle < IDLE_AFTER:
31新增: return PASSIVE_RATE
32新增: return IDLE_RATE
33新增:
34新增:
35新增:def next_change(idle):
36新增: """Seconds until the target rate changes without further input."""
37新增: if idle < ACTIVE_HOLD:
38新增: return ACTIVE_HOLD - idle
39新增: if idle < IDLE_AFTER:
40新增: return IDLE_AFTER - idle
41新增: return None
42新增:
43新增:
44新增:def mode_name(rate, width, height):
45新增: return f'{PREFIX}{rate}-{width}x{height}'
46新增:
47新增:
48新增:def governed(name):
49新增: rate, separator, size = name[len(PREFIX):].partition('-')
50新增: width, by, height = size.partition('x')
51新增: return name.startswith(PREFIX) and bool(separator and by) and rate.isdigit() and width.isdigit() and height.isdigit()
52新增:
53新增:
54新增:def mode_timing(rate, width, height):
55新增: # The same blanking the resize paths use for their 60 Hz modes.
56新增: return {
57新增: 'id': 0, 'width': width, 'height': height, 'dot_clock': (width + 32) * (height + 8) * rate,
58新增: 'h_sync_start': width + 8, 'h_sync_end': width + 16, 'h_total': width + 32, 'h_skew': 0,
59新增: 'v_sync_start': height + 1, 'v_sync_end': height + 2, 'v_total': height + 8,
60新增: 'name_length': len(mode_name(rate, width, height)), 'flags': 1 | 8, # +HSync -VSync
61新增: }
62新增:
63新增:
64新增:def raw_key(data):
65新增: """Keycode of an XInput2 raw key event: deviceid, time, then detail."""
66新增: return struct.unpack_from('=I', data, 6)[0] if isinstance(data, (bytes, bytearray)) and len(data) >= 10 else None
67新增:
68新增:
69新增:def choose_mode(rate, current, base, available):
70新增: """Mode to show `rate` at the current size, and the remembered base mode.
71新增:
72新增: The full rate returns to the mode its size owner selected, so an attended
73新增: display is configured exactly as it is without this governor.
74新增: """
75新增: name, width, height = current
76新增: if not governed(name):
77新增: base = current
78新增: if rate == ACTIVE_RATE and base is not None and base[1:] == (width, height) and base in available:
79新增: return base[0], base
80新增: return mode_name(rate, width, height), base
81新增:
82新增:
83新增:class Governor:
84新增: def __init__(self, connection, output='VNC-0'):
85新增: from Xlib.ext import randr, xinput
86新增: self.conn = connection
87新增: self.root = connection.screen().root
88新增: self.output_name = output
89新增: self.xinput = xinput
90新增: self.expected = None
91新增: self.base = None
92新增: self.probe_codes = None
93新增: # Requests without a reply report their errors here. A mode another
94新增: # client still uses is simply left in place.
95新增: connection.set_error_handler(lambda *_: None)
96新增: self.root.xrandr_select_input(randr.RRScreenChangeNotifyMask)
97新增: self.root.xinput_select_events([(xinput.AllMasterDevices,
98新增: xinput.RawKeyPressMask | xinput.RawButtonPressMask | xinput.RawMotionMask)])
99新增: connection.sync()
100新增:
101新增: def state(self):
102新增: resources = self.root.xrandr_get_screen_resources()
103新增: modes, position = {}, 0
104新增: for mode in resources.modes:
105新增: modes[mode.id] = (resources.mode_names[position:position + mode.name_length], mode.width, mode.height)
106新增: position += mode.name_length
107新增: for output in resources.outputs:
108新增: info = self.conn.xrandr_get_output_info(output, resources.config_timestamp)
109新增: if info.name == self.output_name and info.crtc:
110新增: crtc = self.conn.xrandr_get_crtc_info(info.crtc, resources.config_timestamp)
111新增: if crtc.mode in modes:
112新增: return resources, output, info, crtc, modes
113新增: return None
114新增:
115新增: def ensure_mode(self, rate, width, height):
116新增: state = self.state()
117新增: if state is None:
118新增: return
119新增: _, output, info, _, modes = state
120新增: name = mode_name(rate, width, height)
121新增: mode = next((key for key, value in modes.items() if value[0] == name), None)
122新增: if mode is None:
123新增: mode = self.root.xrandr_create_mode(mode_timing(rate, width, height), name).mode
124新增: if mode not in info.modes:
125新增: self.conn.xrandr_add_output_mode(output, mode)
126新增: self.conn.sync()
127新增:
128新增: def apply(self, rate):
129新增: """Show `rate` at the current size and report 'shown' or 'failed'.
130新增:
131新增: Reports 'foreign', leaving the display alone, when another client
132新增: changed the mode since the previous call: a viewer attached or resized.
133新增: """
134新增: from Xlib import error
135新增: created = False
136新增: while True:
137新增: # A size owner may change the mode at any moment. Deciding and
138新增: # switching inside one server grab cannot restore a stale size.
139新增: self.conn.grab_server()
140新增: try:
141新增: state = self.state()
142新增: if state is None:
143新增: return 'failed'
144新增: resources, output, info, crtc, modes = state
145新增: current = modes[crtc.mode]
146新增: foreign = self.expected is not None and current != self.expected
147新增: wanted, self.base = choose_mode(rate, current, self.base, set(modes.values()))
148新增: if foreign:
149新增: self.expected = current
150新增: return 'foreign'
151新增: target = next((key for key, value in modes.items() if value[0] == wanted and key in info.modes), None)
152新增: if wanted == current[0] or target is not None:
153新增: if wanted != current[0]:
154新增: reply = self.conn.xrandr_set_crtc_config(info.crtc, resources.config_timestamp, crtc.x, crtc.y,
155新增: target, crtc.rotation, crtc.outputs)
156新增: if reply.status != 0:
157新增: return 'failed'
158新增: self.expected = (wanted,) + current[1:]
159新增: for mode, (name, width, height) in modes.items():
160新增: # Modes of earlier sizes. Those of this size are reused.
161新增: if governed(name) and (width, height) != current[1:]:
162新增: if mode in info.modes:
163新增: self.conn.xrandr_delete_output_mode(output, mode)
164新增: self.conn.xrandr_destroy_mode(mode)
165新增: return 'shown'
166新增: except error.XError:
167新增: return 'failed'
168新增: finally:
169新增: self.conn.ungrab_server()
170新增: self.conn.sync()
171新增: if created:
172新增: return 'failed'
173新增: try:
174新增: self.ensure_mode(rate, *current[1:])
175新增: except error.XError:
176新增: return 'failed'
177新增: created = True
178新增:
179新增: def probe_key(self, code):
180新增: if self.probe_codes is None:
181新增: first = self.conn.display.info.min_keycode
182新增: count = self.conn.display.info.max_keycode - first + 1
183新增: self.probe_codes = {first + offset for offset, symbols in
184新增: enumerate(self.conn.get_keyboard_mapping(first, count))
185新增: if len(symbols) and symbols[0] == PROBE_KEYSYM}
186新增: return code in self.probe_codes
187新增:
188新增: def events(self):
189新增: """Whether the viewer acted, and whether the screen was reconfigured."""
190新增: from Xlib import X
191新增: from Xlib.ext import ge
192新增: acted = changed = False
193新增: while self.conn.pending_events():
194新增: event = self.conn.next_event()
195新增: if event.type == X.MappingNotify:
196新增: self.probe_codes = None
197新增: elif event.type != ge.GenericEventCode:
198新增: changed = True
199新增: elif event.evtype != self.xinput.RawKeyPress or not self.probe_key(raw_key(event.data)):
200新增: acted = True
201新增: return acted, changed
202新增:
203新增: def run(self, clock=time.monotonic):
204新增: last_input, shown = clock(), None
205新增: while True:
206新增: acted, changed = self.events()
207新增: if acted:
208新增: last_input = clock()
209新增: rate = target_rate(clock() - last_input)
210新增: # Continuous input at the full rate needs no display request.
211新增: if changed or rate != shown:
212新增: result = self.apply(rate)
213新增: if result == 'foreign':
214新增: last_input, rate = clock(), ACTIVE_RATE
215新增: result = self.apply(rate)
216新增: shown = rate if result == 'shown' else None
217新增: if acted:
218新增: # Input arrives in bursts; one wake-up covers each of them.
219新增: time.sleep(.25)
220新增: continue
221新增: if self.conn.pending_events():
222新增: continue
223新增: wait = next_change(clock() - last_input) if shown is not None else 5
224新增: select.select([self.conn.fileno()], [], [], None if wait is None else wait + .01)
225新增:
226新增:
227新增:def main():
228新增: try:
229新增: from Xlib import display
230新增: except ImportError:
231新增: # Optional: the display keeps its full rate until python3-xlib arrives.
232新增: print('display governor: python3-xlib is not installed', file=sys.stderr)
233新增: return 0
234新增: for attempt in range(40):
235新增: try:
236新增: connection = display.Display()
237新增: break
238新增: except Exception:
239新增: # Started together with its display, which may not listen yet.
240新增: if attempt == 39:
241新增: raise
242新增: time.sleep(.25)
243新增: if not connection.has_extension('RANDR') or not connection.has_extension('XInputExtension'):
244新增: # Without both extensions the display simply keeps its full rate.
245新增: print('display governor: RandR or XInput2 unavailable', file=sys.stderr)
246新增: return 0
247新增: connection.xinput_query_version()
248新增: governor = Governor(connection, os.environ.get('CAGE_DISPLAY_OUTPUT', 'VNC-0'))
249新增: signal.signal(signal.SIGTERM, lambda *_: sys.exit(0))
250新增: try:
251新增: governor.run()
252新增: finally:
253新增: # A stopped governor leaves the display at its full rate.
254新增: try:
255新增: if governor.apply(ACTIVE_RATE) == 'foreign':
256新增: governor.apply(ACTIVE_RATE)
257新增: except Exception:
258新增: pass
259新增: return 0
260新增:
261新增:
262新增:if __name__ == '__main__':
263新增: sys.exit(main())
新增internal/cage/display-governor.test.py+189 −0看文件
@@ -0,0 +1,189 @@
1新增:import importlib.util
2新增:import os
3新增:from pathlib import Path
4新增:import shutil
5新增:import struct
6新增:import subprocess
7新增:import sys
8新增:import tempfile
9新增:import time
10新增:import unittest
11新增:
12新增:spec = importlib.util.spec_from_file_location('display_governor', Path(__file__).with_name('display-governor.py'))
13新增:governor = importlib.util.module_from_spec(spec)
14新增:spec.loader.exec_module(governor)
15新增:
16新增:try:
17新增: from Xlib import X, display
18新增: from Xlib.ext import xtest
19新增:except ImportError:
20新增: display = None
21新增:
22新增:
23新增:class PolicyTests(unittest.TestCase):
24新增: def test_rate_follows_time_since_input(self):
25新增: self.assertEqual(governor.target_rate(0), 60)
26新增: self.assertEqual(governor.target_rate(2.9), 60)
27新增: self.assertEqual(governor.target_rate(3), 30)
28新增: self.assertEqual(governor.target_rate(179), 30)
29新增: self.assertEqual(governor.target_rate(180), 20)
30新增:
31新增: def test_wakes_exactly_at_the_next_change(self):
32新增: self.assertAlmostEqual(governor.next_change(1), 2)
33新增: self.assertAlmostEqual(governor.next_change(10), 170)
34新增: self.assertIsNone(governor.next_change(500))
35新增:
36新增: def test_only_its_own_modes_are_governed(self):
37新增: self.assertTrue(governor.governed('fps30-2339x1368'))
38新增: # Size owners keep, match and delete these names themselves.
39新增: for name in ('cage-2339x1368', 'cage-phone-800x600', '1600x1000', 'fps-1x2', 'fps30-1x', 'fps30', 'fpsx-1x2'):
40新增: self.assertFalse(governor.governed(name), name)
41新增:
42新增: def test_mode_has_the_requested_refresh_rate(self):
43新增: for rate in (20, 30, 60):
44新增: mode = governor.mode_timing(rate, 2339, 1368)
45新增: self.assertAlmostEqual(mode['dot_clock'] / (mode['h_total'] * mode['v_total']), rate)
46新增: self.assertEqual((mode['width'], mode['height']), (2339, 1368))
47新增: self.assertEqual(mode['name_length'], len(governor.mode_name(rate, 2339, 1368)))
48新增:
49新增: def test_full_rate_returns_to_the_size_owners_mode(self):
50新增: base = ('cage-800x600', 800, 600)
51新增: passive = ('fps30-800x600', 800, 600)
52新增: self.assertEqual(governor.choose_mode(30, base, None, {base}), ('fps30-800x600', base))
53新增: self.assertEqual(governor.choose_mode(60, passive, base, {base, passive}), ('cage-800x600', base))
54新增: self.assertEqual(governor.choose_mode(60, base, base, {base}), ('cage-800x600', base))
55新增:
56新增: def test_full_rate_never_restores_another_size(self):
57新增: stale = ('cage-800x600', 800, 600)
58新增: current = ('fps30-1024x768', 1024, 768)
59新增: self.assertEqual(governor.choose_mode(60, current, stale, {stale, current})[0], 'fps60-1024x768')
60新增: # The owner removed its mode while the display was passive.
61新增: self.assertEqual(governor.choose_mode(60, ('fps30-800x600', 800, 600), stale, set())[0], 'fps60-800x600')
62新增:
63新增: def test_raw_key_reads_the_keycode(self):
64新增: self.assertEqual(governor.raw_key(struct.pack('=HIIHHII', 3, 1234, 250, 3, 0, 0, 0)), 250)
65新增: self.assertIsNone(governor.raw_key(b'short'))
66新增: self.assertIsNone(governor.raw_key(None))
67新增:
68新增:
69新增:@unittest.skipUnless(display and shutil.which('Xtigervnc') and shutil.which('xrandr'), 'needs Xtigervnc, xrandr and python3-xlib')
70新增:class DisplayTests(unittest.TestCase):
71新增: """The governor against a private virtual display."""
72新增:
73新增: def setUp(self):
74新增: self.temp = tempfile.TemporaryDirectory(dir='/tmp')
75新增: self.addCleanup(self.temp.cleanup)
76新增: number = next(n for n in range(120, 200) if not os.path.exists(f'/tmp/.X11-unix/X{n}'))
77新增: self.env = dict(os.environ, DISPLAY=f':{number}')
78新增: self.env.pop('XAUTHORITY', None)
79新增: server = subprocess.Popen(['Xtigervnc', f':{number}', '-geometry', '800x600', '-depth', '24', '-rfbport', '-1',
80新增: '-rfbunixpath', self.temp.name + '/d.sock', '-nolisten', 'tcp', '-SecurityTypes', 'None'],
81新增: stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
82新增: self.addCleanup(server.wait)
83新增: self.addCleanup(server.terminate)
84新增: for attempt in range(100):
85新增: if os.path.exists(f'/tmp/.X11-unix/X{number}'):
86新增: break
87新增: time.sleep(.05)
88新增: else:
89新增: self.fail('virtual display did not start')
90新增: self.conn = display.Display(f':{number}')
91新增: self.addCleanup(self.conn.close)
92新增: self.root = self.conn.screen().root
93新增: script = (f'import importlib.util, sys\n'
94新增: f'spec = importlib.util.spec_from_file_location("g", {str(Path(__file__).with_name("display-governor.py"))!r})\n'
95新增: f'g = importlib.util.module_from_spec(spec); spec.loader.exec_module(g)\n'
96新增: f'g.ACTIVE_HOLD, g.IDLE_AFTER = .5, 1.5\nsys.exit(g.main())\n')
97新增: process = subprocess.Popen([sys.executable, '-c', script], env=self.env)
98新增: self.addCleanup(process.wait)
99新增: self.addCleanup(process.terminate)
100新增: self.process = process
101新增:
102新增: def current(self):
103新增: resources = self.root.xrandr_get_screen_resources()
104新增: output = self.conn.xrandr_get_output_info(resources.outputs[0], resources.config_timestamp)
105新增: crtc = self.conn.xrandr_get_crtc_info(output.crtc, resources.config_timestamp)
106新增: position = 0
107新增: for mode in resources.modes:
108新增: name = resources.mode_names[position:position + mode.name_length]
109新增: position += mode.name_length
110新增: if mode.id == crtc.mode:
111新增: return name, round(mode.dot_clock / (mode.h_total * mode.v_total)), (mode.width, mode.height)
112新增:
113新增: def modes(self):
114新增: return subprocess.check_output(['xrandr', '--query'], env=self.env, text=True)
115新增:
116新增: def wait(self, rate, size=(800, 600), timeout=4):
117新增: deadline = time.monotonic() + timeout
118新增: while time.monotonic() < deadline:
119新增: current = self.current()
120新增: if current[1:] == (rate, size):
121新增: return current[0]
122新增: time.sleep(.01)
123新增: self.fail(f'expected {rate} Hz at {size}, display shows {self.current()}')
124新增:
125新增: def resize(self, width, height):
126新增: # The sequence of the browser and Desktop resize paths.
127新增: name = f'cage-{width}x{height}'
128新增: if f' {name} ' not in self.modes():
129新增: subprocess.check_call(['xrandr', '--newmode', name, f'{(width + 32) * (height + 8) * 60 / 1000000:.3f}',
130新增: *map(str, (width, width + 8, width + 16, width + 32, height, height + 1, height + 2, height + 8)),
131新增: '+HSync', '-VSync'], env=self.env)
132新增: subprocess.check_call(['xrandr', '--addmode', 'VNC-0', name], env=self.env)
133新增: subprocess.check_call(['xrandr', '--output', 'VNC-0', '--mode', name], env=self.env)
134新增:
135新增: def test_unattended_display_slows_and_input_restores_it(self):
136新增: original = self.current()[0]
137新增: self.assertEqual(self.wait(30), 'fps30-800x600')
138新增: self.assertEqual(self.wait(20), 'fps20-800x600')
139新增: started = time.monotonic()
140新增: xtest.fake_input(self.conn, X.MotionNotify, x=40, y=40)
141新增: self.conn.sync()
142新增: self.assertEqual(self.wait(60), original)
143新增: self.assertLess(time.monotonic() - started, .5)
144新增: self.wait(30)
145新增: code = self.conn.keysym_to_keycode(0x61)
146新增: xtest.fake_input(self.conn, X.KeyPress, code)
147新增: xtest.fake_input(self.conn, X.KeyRelease, code)
148新增: self.conn.sync()
149新增: self.assertEqual(self.wait(60), original)
150新增:
151新增: def test_caret_probe_key_is_not_viewer_input(self):
152新增: subprocess.check_call(['xmodmap', '-e', 'keycode 250 = F24'], env=self.env)
153新增: self.wait(20)
154新增: for _ in range(3):
155新增: xtest.fake_input(self.conn, X.KeyPress, 250)
156新增: xtest.fake_input(self.conn, X.KeyRelease, 250)
157新增: self.conn.sync()
158新增: time.sleep(.2)
159新增: self.assertEqual(self.current()[1], 20)
160新增:
161新增: def test_resize_keeps_its_size_and_removes_earlier_modes(self):
162新增: self.wait(30)
163新增: self.resize(1024, 700)
164新增: self.assertEqual(self.wait(60, (1024, 700)), 'cage-1024x700')
165新增: self.assertEqual(self.wait(30, (1024, 700)), 'fps30-1024x700')
166新增: self.assertNotIn('fps30-800x600', self.modes())
167新增: self.assertNotIn('fps20-800x600', self.modes())
168新增: # A viewer attaching at the same size restores the full rate as well.
169新增: self.resize(1024, 700)
170新增: self.assertEqual(self.wait(60, (1024, 700)), 'cage-1024x700')
171新增: # Each step of a drag stays at the size its owner selected.
172新增: self.wait(30, (1024, 700))
173新增: for width in range(1030, 1100, 10):
174新增: self.resize(width, 700)
175新增: time.sleep(.05)
176新增: self.assertEqual(self.current()[1:], (60, (width, 700)))
177新增: self.assertEqual(self.wait(30, (1090, 700)), 'fps30-1090x700')
178新增: self.assertIsNone(self.process.poll())
179新增:
180新增: def test_stopping_restores_the_full_rate(self):
181新增: original = self.current()[0]
182新增: self.wait(30)
183新增: self.process.terminate()
184新增: self.assertEqual(self.process.wait(timeout=3), 0)
185新增: self.assertEqual(self.current()[:2], (original, 60))
186新增:
187新增:
188新增:if __name__ == '__main__':
189新增: unittest.main()
修改internal/cage/guest-services.sh+17 −1看文件
@@ -4,7 +4,7 @@ if systemctl is-active --quiet cage-webvnc; then
44 sudo systemctl stop cage-webvnc
55fi
66if ! command -v X0tigervnc >/dev/null || ! command -v Xtigervnc >/dev/null || ! command -v openbox >/dev/null || ! command -v xrandr >/dev/null || ! command -v xdotool >/dev/null || ! command -v ibus-daemon >/dev/null || ! /usr/bin/python3 -c 'import gi; gi.require_version("IBus", "1.0"); gi.require_version("Gtk", "3.0")' 2>/dev/null; then
7删除: sudo env DEBIAN_FRONTEND=noninteractive APT_CONFIG="${CAGE_APT_CONFIG:-/dev/null}" apt-get install -y --no-install-recommends tigervnc-standalone-server tigervnc-scraping-server tigervnc-tools openbox x11-xserver-utils xdotool libgtk-3-0 ibus ibus-gtk3 gir1.2-ibus-1.0 gir1.2-gtk-3.0 python3-gi
7新增: sudo env DEBIAN_FRONTEND=noninteractive APT_CONFIG="${CAGE_APT_CONFIG:-/dev/null}" apt-get install -y --no-install-recommends tigervnc-standalone-server tigervnc-scraping-server tigervnc-tools openbox x11-xserver-utils xdotool libgtk-3-0 ibus ibus-gtk3 gir1.2-ibus-1.0 gir1.2-gtk-3.0 python3-gi python3-xlib
88fi
99cage_novnc_root=/usr/share/novnc
1010if cage_is_ubuntu; then
@@ -58,6 +58,7 @@ fi
5858sudo tee /etc/systemd/system/cage-display.service >/dev/null <<'UNIT'
5959[Unit]
6060Description=Claude Cage virtual browser display
61新增:Wants=cage-display-governor.service
6162[Service]
6263User=cage-browser
6364ExecStartPre=/usr/bin/rm -f /home/cage-browser/.vnc/display.sock
@@ -103,6 +104,21 @@ KillMode=mixed
103104Restart=on-failure
104105RestartSec=2
105106UNIT
107新增:# Starts, restarts and stops with the display it paces. The display only
108新增:# wants it: a guest without python3-xlib keeps its full refresh rate.
109新增:sudo tee /etc/systemd/system/cage-display-governor.service >/dev/null <<'UNIT'
110新增:[Unit]
111新增:Description=Claude Cage browser display pacing
112新增:PartOf=cage-display.service
113新增:After=cage-display.service
114新增:[Service]
115新增:User=cage-browser
116新增:Environment=DISPLAY=:77
117新增:ExecStart=/usr/local/bin/cage-log-run /usr/local/bin/cage-display-governor
118新增:LogNamespace=cage
119新增:Restart=on-failure
120新增:RestartSec=5
121新增:UNIT
106122sudo tee /etc/systemd/system/cage-vnc.service >/dev/null <<'UNIT'
107123[Unit]
108124Description=Claude Cage browser screen
修改internal/cage/guest-setup.sh+1 −1看文件
@@ -1,6 +1,6 @@
11#!/usr/bin/env bash
22set -euo pipefail
3删除:sudo env DEBIAN_FRONTEND=noninteractive APT_CONFIG="${CAGE_APT_CONFIG:-/dev/null}" apt-get install -y --no-install-recommends locales tzdata tigervnc-standalone-server openbox x11-xserver-utils tigervnc-scraping-server tigervnc-tools novnc websockify fonts-noto-cjk fonts-noto-color-emoji
3新增:sudo env DEBIAN_FRONTEND=noninteractive APT_CONFIG="${CAGE_APT_CONFIG:-/dev/null}" apt-get install -y --no-install-recommends locales tzdata tigervnc-standalone-server openbox x11-xserver-utils tigervnc-scraping-server tigervnc-tools novnc websockify fonts-noto-cjk fonts-noto-color-emoji python3-xlib
44if ! id cage-browser >/dev/null 2>&1; then
55 sudo useradd --create-home --shell /bin/bash cage-browser
66fi
修改internal/cage/guest-start.sh+1 −0看文件
@@ -52,6 +52,7 @@ d.setdefault("profile", {})["password_manager_enabled"] = False
5252p.write_text(json.dumps(d))
5353PYCODE
5454sudo systemctl reset-failed cage-display cage-window-manager cage-browser cage-vnc cage-webvnc 2>/dev/null || true
55新增:sudo systemctl reset-failed cage-display-governor 2>/dev/null || true
5556sudo systemctl restart cage-display cage-window-manager cage-browser cage-vnc cage-webvnc
5657# Seed only appearance settings for a new editor profile. Existing preferences stay intact.
5758python3 - <<'PYEDITOR'
修改internal/cage/guest.go+9 −1看文件
@@ -67,6 +67,13 @@ var browserAgent string
6767//go:embed browser-visibility.mjs
6868var browserVisibility string
6969
70新增://go:embed display-governor.py
71新增:var displayGovernor string
72新增:
73新增:func displayGovernorScript() string {
74新增: return "sudo tee /usr/local/bin/cage-display-governor >/dev/null <<'CAGE_DISPLAY_GOVERNOR'\n" + displayGovernor + "\nCAGE_DISPLAY_GOVERNOR\nsudo chmod 0755 /usr/local/bin/cage-display-governor\n"
75新增:}
76新增:
7077//go:embed browser-phone.mjs
7178var phoneBrowser string
7279
@@ -172,7 +179,7 @@ func phoneBrowserScript() string {
172179}
173180
174181func browserServices() string {
175删除: return "sudo tee /usr/local/lib/cage-wait-services.py >/dev/null <<'CAGE_WAIT_SERVICES'\n" + guestWaitServices + "\nCAGE_WAIT_SERVICES\n" + toolVersions + "\n" + guestTools + "\n" + ubuntuBrowser + "\n" + tailnetClientScript() + "sudo tee /usr/local/lib/browser-visibility.mjs >/dev/null <<'CAGE_BROWSER_VISIBILITY'\n" + browserVisibility + "\nCAGE_BROWSER_VISIBILITY\n" + PhoneDesktopProvisionScript() + phoneBrowserScript() + "\nsudo tee /usr/local/lib/browser-extensions.mjs >/dev/null <<'CAGE_BROWSER_EXTENSIONS'\n" + browserExtensions + "\nCAGE_BROWSER_EXTENSIONS\n" + "\nsudo tee /usr/local/lib/browser-extension-archive.py >/dev/null <<'CAGE_EXTENSION_ARCHIVE'\n" + browserExtensionArchive + "\nCAGE_EXTENSION_ARCHIVE\n" + "\nsudo tee /usr/local/lib/browser-private.mjs >/dev/null <<'CAGE_BROWSER_PRIVATE'\n" + browserPrivate + "\nCAGE_BROWSER_PRIVATE\n" + "\nsudo tee /usr/local/lib/browser-cookies.mjs >/dev/null <<'CAGE_BROWSER_COOKIES'\n" + browserCookies + "\nCAGE_BROWSER_COOKIES\n" + "\nsudo tee /usr/local/lib/browser-vault.mjs >/dev/null <<'CAGE_BROWSER_VAULT'\n" + browserVault + "\nCAGE_BROWSER_VAULT\n" + guestMemory + "\n" + guestDiagnostics() + guestAudio + "\n" + guestOpenScript() + splitExtensionScript() + browserClipboardScript() + imageInputScript() + "\nsudo tee /usr/local/lib/browser-uploads.mjs >/dev/null <<'CAGE_BROWSER_UPLOADS'\n" + browserUploads + "\nCAGE_BROWSER_UPLOADS\n" + guestServices + "\nsudo tee /usr/local/lib/browser-downloads.mjs >/dev/null <<'CAGE_BROWSER_DOWNLOADS'\n" + browserDownloads + "\nCAGE_BROWSER_DOWNLOADS\n" + "\nsudo tee /usr/local/bin/cage-editor-migrate >/dev/null <<'CAGE_EDITOR_MIGRATE'\n" + editorMigrate + "\nCAGE_EDITOR_MIGRATE\nsudo chmod 0755 /usr/local/bin/cage-editor-migrate\n" + "\nsudo tee /usr/local/lib/browser-audit.mjs >/dev/null <<'CAGE_BROWSER_AUDIT'\n" + browserAudit + "\nCAGE_BROWSER_AUDIT\n" + "\nsudo tee /usr/local/lib/cage-browser-agent.mjs >/dev/null <<'CAGE_BROWSER_AGENT'\n" + browserAgent + "\nCAGE_BROWSER_AGENT\n" + "sudo tee /usr/local/bin/cage-save-download >/dev/null <<'CAGE_DOWNLOAD_HELPER'\n" + saveDownload + "\nCAGE_DOWNLOAD_HELPER\nsudo chmod 0755 /usr/local/bin/cage-save-download\nprintf 'cage-browser ALL=(root) NOPASSWD: /usr/local/bin/cage-save-download *\\n' | sudo tee /etc/sudoers.d/cage-download >/dev/null\nsudo chmod 0440 /etc/sudoers.d/cage-download\n" + "\nsudo python3 - \"$cage_novnc_root\" <<'CAGE_NOVNC_PATCH'\n" + novncPatch + "\nCAGE_NOVNC_PATCH\n" + "\nsudo tee \"$cage_novnc_root/cage-clipboard.js\" >/dev/null <<'CAGE_CLIPBOARD_JS'\n" + clipboardJS + "\nCAGE_CLIPBOARD_JS\n" + `sudo python3 - <<'PYCODE'
182新增: return "sudo tee /usr/local/lib/cage-wait-services.py >/dev/null <<'CAGE_WAIT_SERVICES'\n" + guestWaitServices + "\nCAGE_WAIT_SERVICES\n" + toolVersions + "\n" + guestTools + "\n" + ubuntuBrowser + "\n" + tailnetClientScript() + "sudo tee /usr/local/lib/browser-visibility.mjs >/dev/null <<'CAGE_BROWSER_VISIBILITY'\n" + browserVisibility + "\nCAGE_BROWSER_VISIBILITY\n" + displayGovernorScript() + PhoneDesktopProvisionScript() + phoneBrowserScript() + "\nsudo tee /usr/local/lib/browser-extensions.mjs >/dev/null <<'CAGE_BROWSER_EXTENSIONS'\n" + browserExtensions + "\nCAGE_BROWSER_EXTENSIONS\n" + "\nsudo tee /usr/local/lib/browser-extension-archive.py >/dev/null <<'CAGE_EXTENSION_ARCHIVE'\n" + browserExtensionArchive + "\nCAGE_EXTENSION_ARCHIVE\n" + "\nsudo tee /usr/local/lib/browser-private.mjs >/dev/null <<'CAGE_BROWSER_PRIVATE'\n" + browserPrivate + "\nCAGE_BROWSER_PRIVATE\n" + "\nsudo tee /usr/local/lib/browser-cookies.mjs >/dev/null <<'CAGE_BROWSER_COOKIES'\n" + browserCookies + "\nCAGE_BROWSER_COOKIES\n" + "\nsudo tee /usr/local/lib/browser-vault.mjs >/dev/null <<'CAGE_BROWSER_VAULT'\n" + browserVault + "\nCAGE_BROWSER_VAULT\n" + guestMemory + "\n" + guestDiagnostics() + guestAudio + "\n" + guestOpenScript() + splitExtensionScript() + browserClipboardScript() + imageInputScript() + "\nsudo tee /usr/local/lib/browser-uploads.mjs >/dev/null <<'CAGE_BROWSER_UPLOADS'\n" + browserUploads + "\nCAGE_BROWSER_UPLOADS\n" + guestServices + "\nsudo tee /usr/local/lib/browser-downloads.mjs >/dev/null <<'CAGE_BROWSER_DOWNLOADS'\n" + browserDownloads + "\nCAGE_BROWSER_DOWNLOADS\n" + "\nsudo tee /usr/local/bin/cage-editor-migrate >/dev/null <<'CAGE_EDITOR_MIGRATE'\n" + editorMigrate + "\nCAGE_EDITOR_MIGRATE\nsudo chmod 0755 /usr/local/bin/cage-editor-migrate\n" + "\nsudo tee /usr/local/lib/browser-audit.mjs >/dev/null <<'CAGE_BROWSER_AUDIT'\n" + browserAudit + "\nCAGE_BROWSER_AUDIT\n" + "\nsudo tee /usr/local/lib/cage-browser-agent.mjs >/dev/null <<'CAGE_BROWSER_AGENT'\n" + browserAgent + "\nCAGE_BROWSER_AGENT\n" + "sudo tee /usr/local/bin/cage-save-download >/dev/null <<'CAGE_DOWNLOAD_HELPER'\n" + saveDownload + "\nCAGE_DOWNLOAD_HELPER\nsudo chmod 0755 /usr/local/bin/cage-save-download\nprintf 'cage-browser ALL=(root) NOPASSWD: /usr/local/bin/cage-save-download *\\n' | sudo tee /etc/sudoers.d/cage-download >/dev/null\nsudo chmod 0440 /etc/sudoers.d/cage-download\n" + "\nsudo python3 - \"$cage_novnc_root\" <<'CAGE_NOVNC_PATCH'\n" + novncPatch + "\nCAGE_NOVNC_PATCH\n" + "\nsudo tee \"$cage_novnc_root/cage-clipboard.js\" >/dev/null <<'CAGE_CLIPBOARD_JS'\n" + clipboardJS + "\nCAGE_CLIPBOARD_JS\n" + `sudo python3 - <<'PYCODE'
176183from pathlib import Path
177184import re
178185p = Path("/usr/share/novnc/vnc.html")
@@ -259,6 +266,7 @@ sudo env DEBIAN_FRONTEND=noninteractive dpkg --configure -a </dev/null
259266` + APTBootstrapScript + ToolInstallPrelude() + `
260267sudo env DEBIAN_FRONTEND=noninteractive APT_CONFIG="${CAGE_APT_CONFIG:-/dev/null}" apt-get update </dev/null
261268cage_install_chromium
269新增:sudo env DEBIAN_FRONTEND=noninteractive APT_CONFIG="${CAGE_APT_CONFIG:-/dev/null}" apt-get install -y --no-install-recommends python3-xlib </dev/null || echo 'python3-xlib is unavailable; displays keep their full refresh rate.' >&2
262270cage_install_tool mise
263271cage_install_tool code-server
264272cage_install_tool claude