跳到主要内容

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

提交记录

降低输入光标同步在空闲时的开销

工作台原先每 250 毫秒读取一次远端输入光标。Linux Desktop 的每次读取 都要启动 sudo 与 Python,并注入一次探测按键,画面聚焦时持续占用客机 CPU。 读取节奏改为随操作自适应:键鼠、滚轮或输入法操作后的 3 秒内保持 250 毫秒,随后逐级放慢到 2 秒,再次操作时立即恢复;输入法组合接受最近 一个慢周期内的读取,客机仍会拒绝已变化的输入位置。三个客机系统共用 这一节奏。Linux Desktop 的连续请求改由一个常驻转发进程承载,空闲 10 秒 后退出,未能应答时回退到逐次请求。 Co-Authored-By: Claude <[email protected]>

作者
Lee-xeo
时间
2026/11/10 22:16
提交
35076be
上一个
d8d9c2a
这个版本的全部文件
修改internal/cage/guest.go+1 −1看文件
@@ -160,7 +160,7 @@ func nativeInputScript() string {
160160 return "\nsudo tee /usr/local/bin/cage-native-input >/dev/null <<'CAGE_NATIVE_INPUT'\n" + nativeIME + "\nCAGE_NATIVE_INPUT\nsudo chmod 0755 /usr/local/bin/cage-native-input\n" +
161161 "sudo tee /usr/local/bin/cage-input-session >/dev/null <<'CAGE_INPUT_SESSION'\n" + nativeIMESession + "\nCAGE_INPUT_SESSION\nsudo chmod 0755 /usr/local/bin/cage-input-session\n" +
162162 "sudo tee /usr/local/lib/native-input.mjs >/dev/null <<'CAGE_INPUT_CLIENT'\n" + nativeInputClient + "\nCAGE_INPUT_CLIENT\n" +
163删除: "printf 'cage-browser ALL=(cage) NOPASSWD: /usr/local/bin/cage-native-input --request\\n' | sudo tee /etc/sudoers.d/cage-input >/dev/null\nsudo chmod 0440 /etc/sudoers.d/cage-input\n"
163新增: "printf 'cage-browser ALL=(cage) NOPASSWD: /usr/local/bin/cage-native-input --request, /usr/local/bin/cage-native-input --relay\\n' | sudo tee /etc/sudoers.d/cage-input >/dev/null\nsudo chmod 0440 /etc/sudoers.d/cage-input\n"
164164}
165165
166166func fileInputScript() string {
修改internal/cage/native-ime.py+19 −1看文件
@@ -15,6 +15,8 @@ limit = 32768
1515
1616def request():
1717 data = sys.stdin.buffer.readline(limit + 1)
18新增: if not data:
19新增: raise EOFError
1820 if len(data) > limit or not data.endswith(b'\n'):
1921 raise ValueError('Invalid input request')
2022 with socket.socket(socket.AF_UNIX) as client:
@@ -25,15 +27,31 @@ def request():
2527 if len(result) > limit or not result.endswith(b'\n'):
2628 raise ValueError('Invalid input response')
2729 sys.stdout.buffer.write(result)
30新增: sys.stdout.buffer.flush()
2831
2932
3033if __name__ == '__main__' and sys.argv[1:] == ['--request']:
3134 try:
3235 request()
33删除: except (OSError, ValueError):
36新增: except (OSError, ValueError, EOFError):
3437 print('{"available":false}')
3538 sys.exit(0)
3639
40新增:if __name__ == '__main__' and sys.argv[1:] == ['--relay']:
41新增: # One authorized caller sends consecutive requests, one line each, without
42新增: # starting a process for every caret poll. Its closed pipe ends the relay.
43新增: while True:
44新增: try:
45新增: request()
46新增: except EOFError:
47新增: break
48新增: except OSError:
49新增: print('{"available":false}', flush=True)
50新增: except ValueError:
51新增: # The stream has no boundary to resume from.
52新增: sys.exit(1)
53新增: sys.exit(0)
54新增:
3755import gi
3856import secrets
3957import socketserver
修改internal/cage/native-input.mjs+61 −3看文件
@@ -1,6 +1,62 @@
11import { createConnection } from "node:net";
22import { spawn } from "node:child_process";
33
4新增:const helper = ["-n", "-H", "-u", "cage", "/usr/local/bin/cage-native-input"];
5新增:const responseLimit = 32768;
6新增:
7新增:// The caret is polled several times a second while Desktop has focus. One
8新增:// relay answers consecutive requests; it ends after a short idle period.
9新增:// A relay that never answered is not started again.
10新增:export function createDesktopRelay({ start = () => spawn("/usr/bin/sudo", [...helper, "--relay"], { stdio: ["pipe", "pipe", "ignore"] }), idle = 10000, timeout = 3500 } = {}) {
11新增: let current, answered = false, unusable = false;
12新增: const open = () => {
13新增: const relay = { child: start(), jobs: [], data: "", closed: false, timer: undefined };
14新增: const close = () => {
15新增: if (relay.closed) return;
16新增: relay.closed = true;
17新增: if (current === relay) current = undefined;
18新增: if (!answered) unusable = true;
19新增: clearTimeout(relay.timer);
20新增: for (const job of relay.jobs.splice(0)) { clearTimeout(job.timer); job.reject(new Error("Desktop input bridge unavailable")); }
21新增: relay.child.kill();
22新增: };
23新增: relay.close = close;
24新增: relay.child.stdout.setEncoding("utf8");
25新增: relay.child.stdout.on("data", (chunk) => {
26新增: relay.data += chunk;
27新增: for (let end; (end = relay.data.indexOf("\n")) >= 0;) {
28新增: const line = relay.data.slice(0, end), job = relay.jobs.shift();
29新增: relay.data = relay.data.slice(end + 1);
30新增: if (!job) return close();
31新增: clearTimeout(job.timer);
32新增: answered = true;
33新增: job.resolve(line);
34新增: }
35新增: if (relay.data.length > responseLimit) return close();
36新增: if (!relay.jobs.length) relay.timer = setTimeout(() => relay.child.stdin.end(), idle);
37新增: });
38新增: relay.child.on("error", close);
39新增: relay.child.on("close", close);
40新增: relay.child.stdin.on("error", close);
41新增: return relay;
42新增: };
43新增: return {
44新增: available: () => !unusable,
45新增: request(line) {
46新增: return new Promise((resolve, reject) => {
47新增: const relay = current && !current.closed && !current.child.stdin.writableEnded ? current : current = open();
48新增: clearTimeout(relay.timer);
49新增: // Answers arrive in request order. A stalled bridge ends the relay.
50新增: relay.jobs.push({ resolve, reject, timer: setTimeout(relay.close, timeout) });
51新增: relay.child.stdin.write(line);
52新增: });
53新增: },
54新增: close: () => current?.close(),
55新增: };
56新增:}
57新增:
58新增:const desktopRelay = createDesktopRelay();
59新增:
460// Each display owns a private IBus socket. The browser can access Desktop's
561// bridge only through this fixed, sudo-authorized helper, with data on stdin.
662export function nativeInput(value) {
@@ -19,14 +75,16 @@ export function nativeInput(value) {
1975 };
2076 const collect = (chunk) => {
2177 data += chunk;
22删除: if (data.length > 32768) {
78新增: if (data.length > responseLimit) {
2379 channel.destroy();
2480 reject(new Error("Input response too large"));
2581 }
2682 };
2783 let channel;
28删除: if (value.target === "desktop") {
29删除: const child = spawn("/usr/bin/sudo", ["-n", "-H", "-u", "cage", "/usr/local/bin/cage-native-input", "--request"], {
84新增: if (value.target === "desktop" && desktopRelay.available()) {
85新增: desktopRelay.request(JSON.stringify(value) + "\n").then((line) => { data = line; finish(); }, unavailable);
86新增: } else if (value.target === "desktop") {
87新增: const child = spawn("/usr/bin/sudo", [...helper, "--request"], {
3088 stdio: ["pipe", "pipe", "ignore"], timeout: 3500,
3189 });
3290 channel = child.stdout;
新增internal/cage/native-input.test.mjs+114 −0看文件
@@ -0,0 +1,114 @@
1新增:import assert from "node:assert/strict";
2新增:import { spawn } from "node:child_process";
3新增:import { EventEmitter } from "node:events";
4新增:import { mkdtempSync, mkdirSync, rmSync } from "node:fs";
5新增:import { createServer } from "node:net";
6新增:import { tmpdir } from "node:os";
7新增:import { join } from "node:path";
8新增:import { PassThrough } from "node:stream";
9新增:import { fileURLToPath } from "node:url";
10新增:import test from "node:test";
11新增:import { createDesktopRelay } from "./native-input.mjs";
12新增:
13新增:function fakeChild() {
14新增: const child = new EventEmitter();
15新增: child.stdin = new PassThrough();
16新增: child.stdout = new PassThrough();
17新增: child.killed = false;
18新增: child.kill = () => { child.killed = true; };
19新增: child.stdin.on("finish", () => child.emit("close", 0));
20新增: return child;
21新增:}
22新增:
23新增:test("one relay answers consecutive requests in order", async () => {
24新增: const children = [];
25新增: const relay = createDesktopRelay({ start: () => { const child = fakeChild(); children.push(child); return child; } });
26新增: const answers = Promise.all([relay.request('{"n":1}\n'), relay.request('{"n":2}\n')]);
27新增: assert.equal(children.length, 1);
28新增: assert.equal(children[0].stdin.read().toString(), '{"n":1}\n{"n":2}\n');
29新增: // Responses can arrive split or joined.
30新增: children[0].stdout.write('{"a":');
31新增: children[0].stdout.write('1}\n{"a":2}\n');
32新增: assert.deepEqual(await answers, ['{"a":1}', '{"a":2}']);
33新增: const third = relay.request('{"n":3}\n');
34新增: children[0].stdout.write('{"a":3}\n');
35新增: assert.equal(await third, '{"a":3}');
36新增: assert.equal(children.length, 1);
37新增: relay.close();
38新增:});
39新增:
40新增:test("an idle relay ends and the next request starts another", async () => {
41新增: const children = [];
42新增: const relay = createDesktopRelay({ start: () => { const child = fakeChild(); children.push(child); return child; }, idle: 20 });
43新增: const first = relay.request("a\n");
44新增: children[0].stdout.write("1\n");
45新增: await first;
46新增: await new Promise(resolve => children[0].once("close", resolve));
47新增: assert.equal(relay.available(), true);
48新增: const second = relay.request("b\n");
49新增: assert.equal(children.length, 2);
50新增: children[1].stdout.write("2\n");
51新增: assert.equal(await second, "2");
52新增: relay.close();
53新增:});
54新增:
55新增:test("a relay that never answered is not started again", async () => {
56新增: const children = [];
57新增: const relay = createDesktopRelay({ start: () => { const child = fakeChild(); children.push(child); return child; } });
58新增: const refused = relay.request("a\n");
59新增: children[0].emit("close", 1);
60新增: await assert.rejects(refused, /unavailable/);
61新增: assert.equal(relay.available(), false);
62新增:});
63新增:
64新增:test("a stalled bridge rejects every waiting request and ends the relay", async () => {
65新增: const children = [];
66新增: const relay = createDesktopRelay({ start: () => { const child = fakeChild(); children.push(child); return child; }, timeout: 20 });
67新增: const answered = relay.request("a\n");
68新增: children[0].stdout.write("1\n");
69新增: await answered;
70新增: await assert.rejects(Promise.all([relay.request("b\n"), relay.request("c\n")]), /unavailable/);
71新增: assert.equal(children[0].killed, true);
72新增: // It answered before, so a later request may try again.
73新增: assert.equal(relay.available(), true);
74新增:});
75新增:
76新增:test("an unrequested or oversized answer ends the relay", async () => {
77新增: const children = [];
78新增: const relay = createDesktopRelay({ start: () => { const child = fakeChild(); children.push(child); return child; } });
79新增: const first = relay.request("a\n");
80新增: children[0].stdout.write("1\nunrequested\n");
81新增: await first;
82新增: assert.equal(children[0].killed, true);
83新增: const second = relay.request("b\n");
84新增: children[1].stdout.write("x".repeat(40000));
85新增: await assert.rejects(second, /unavailable/);
86新增:});
87新增:
88新增:test("the helper relays each line to the input bridge until its pipe closes", { skip: process.platform === "win32" }, async () => {
89新增: const home = mkdtempSync(join(tmpdir(), "cage-input-"));
90新增: const seen = [];
91新增: const bridge = createServer((socket) => {
92新增: socket.once("data", (data) => { seen.push(data.toString()); socket.end(JSON.stringify({ echo: JSON.parse(data).n }) + "\n"); });
93新增: });
94新增: let relay;
95新增: try {
96新增: mkdirSync(join(home, ".cache/cage-input"), { recursive: true });
97新增: await new Promise(resolve => bridge.listen(join(home, ".cache/cage-input/input.sock"), resolve));
98新增: const start = () => spawn("python3", [fileURLToPath(new URL("./native-ime.py", import.meta.url)), "--relay"], { env: { ...process.env, HOME: home }, stdio: ["pipe", "pipe", "inherit"] });
99新增: const children = [];
100新增: relay = createDesktopRelay({ start: () => { const child = start(); children.push(child); return child; }, idle: 50 });
101新增: assert.deepEqual(await Promise.all([1, 2, 3].map(n => relay.request(JSON.stringify({ n }) + "\n"))), [1, 2, 3].map(n => JSON.stringify({ echo: n })));
102新增: assert.equal(seen.length, 3);
103新增: assert.equal(children.length, 1);
104新增: // An unreachable bridge is an ordinary unavailable answer.
105新增: await new Promise(resolve => bridge.close(resolve));
106新增: rmSync(join(home, ".cache/cage-input/input.sock"), { force: true });
107新增: assert.equal(await relay.request('{"n":4}\n'), '{"available":false}');
108新增: assert.equal(await new Promise(resolve => children[0].once("close", resolve)), 0);
109新增: } finally {
110新增: relay?.close();
111新增: bridge.close();
112新增: rmSync(home, { recursive: true, force: true });
113新增: }
114新增:});
新增ui/src/caret-poll.mjs+16 −0看文件
@@ -0,0 +1,16 @@
1新增:// Focus and the caret nearly always move because of the viewer's own input.
2新增:// Read them quickly while the viewer acts, and rarely once they stop: every
3新增:// reading is a round trip into the guest, and on Linux also a probe key.
4新增:export const caretPollFast = 250;
5新增:export const caretPollSlow = 2000;
6新增:
7新增:export function caretPollDelay(quiet) {
8新增: if (quiet < 3000) return caretPollFast;
9新增: if (quiet < 8000) return 500;
10新增: if (quiet < 20000) return 1000;
11新增: return caretPollSlow;
12新增:}
13新增:
14新增:// A composition may begin from the reading of the last slow interval. The
15新增:// guest still rejects a context that changed in the meantime.
16新增:export const caretFreshFor = caretPollSlow + 500;
新增ui/src/caret-poll.test.mjs+21 −0看文件
@@ -0,0 +1,21 @@
1新增:import test from "node:test";
2新增:import assert from "node:assert/strict";
3新增:import { caretPollDelay, caretPollFast, caretPollSlow, caretFreshFor } from "./caret-poll.mjs";
4新增:
5新增:test("caret polling is fast after input and backs off while the viewer is quiet", () => {
6新增: assert.equal(caretPollDelay(0), caretPollFast);
7新增: assert.equal(caretPollDelay(2999), caretPollFast);
8新增: assert.equal(caretPollDelay(3000), 500);
9新增: assert.equal(caretPollDelay(8000), 1000);
10新增: assert.equal(caretPollDelay(20000), caretPollSlow);
11新增: assert.equal(caretPollDelay(3600000), caretPollSlow);
12新增: let previous = 0;
13新增: for (let quiet = 0; quiet < 60000; quiet += 250) {
14新增: assert.ok(caretPollDelay(quiet) >= previous);
15新增: previous = caretPollDelay(quiet);
16新增: }
17新增:});
18新增:
19新增:test("a reading from the slowest interval can still begin a composition", () => {
20新增: assert.ok(caretFreshFor > caretPollSlow);
21新增:});
修改ui/src/remote-input.js+22 −2看文件
@@ -1,5 +1,6 @@
11import { getKeycode, getKeysym } from "../.generated/novnc/core/input/util.js";
22import { api, writeClipboard, nativeAvailable, native } from "./api";
3新增:import { caretPollDelay, caretPollFast, caretFreshFor } from "./caret-poll.mjs";
34import {
45 readClipboardContent,
56 transferFiles,
@@ -31,6 +32,8 @@ export function installRemoteInput(
3132 compositionSequence = 0,
3233 caretState,
3334 caretTimer,
35新增: caretWait = caretPollFast,
36新增: lastAction = Date.now(),
3437 caretPending = false,
3538 nativeOwner = "",
3639 nativeTarget = "",
@@ -132,15 +135,27 @@ export function installRemoteInput(
132135 };
133136 const pollCaret = async () => {
134137 if (focused()) await syncCaret();
135删除: if (!disposed) caretTimer = setTimeout(pollCaret, 250);
138新增: if (disposed) return;
139新增: caretWait = caretPollDelay(Date.now() - lastAction);
140新增: caretTimer = setTimeout(pollCaret, caretWait);
136141 };
137142 if (caretRect) caretTimer = setTimeout(pollCaret, 0);
143新增: const acted = () => {
144新增: lastAction = Date.now();
145新增: // A slow wait scheduled while the viewer was quiet must not delay the
146新增: // readings that follow their input.
147新增: if (!caretRect || disposed || caretWait <= caretPollFast) return;
148新增: clearTimeout(caretTimer);
149新增: caretWait = caretPollFast;
150新增: caretTimer = setTimeout(pollCaret, caretWait);
151新增: };
138152 const bounds = container.getBoundingClientRect();
139153 position(bounds.left + 12, bounds.top + 12);
140154 on(
141155 container,
142156 "pointerdown",
143157 (event) => {
158新增: acted();
144159 // Cancel before noVNC queues a click into another remote field.
145160 if (composing) {
146161 if (compositionSession) queueComposition({ mode: "cancel" });
@@ -180,10 +195,11 @@ export function installRemoteInput(
180195 target.value = "";
181196 };
182197 const startComposition = () => {
198新增: acted();
183199 composing = true;
184200 compositionTarget = getTargetId();
185201 if (insertComposition && caretState?.context && caretState.target === compositionTarget &&
186删除: Date.now() - caretState.time < 1000) {
202新增: Date.now() - caretState.time < caretFreshFor) {
187203 compositionSession = crypto.randomUUID().replaceAll("-", "");
188204 compositionSequence = 0;
189205 queueComposition({ mode: "begin", context: caretState.context });
@@ -268,8 +284,11 @@ export function installRemoteInput(
268284 }
269285 });
270286 on(container, "pointerup", () => {
287新增: acted();
271288 setTimeout(() => void syncCaret(), 50);
272289 });
290新增: // Scrolling moves the caret without moving focus.
291新增: on(container, "wheel", acted, { capture: true, passive: true });
273292 const say = (text) => {
274293 if (!disposed) onStatus(text);
275294 };
@@ -440,6 +459,7 @@ export function installRemoteInput(
440459 "keydown",
441460 (event) => {
442461 if (!focused()) return;
462新增: acted();
443463 if ((event.isTrusted || event.cageNativeInput) && (!copyContext || ["Enter", " ", "Tab"].includes(event.key) ||
444464 event.ctrlKey || event.metaKey || event.altKey)) prepareCopy();
445465 if (
修改ui/src/remote-input.test.mjs+78 −4看文件
@@ -3,6 +3,7 @@ import assert from "node:assert/strict";
33import { readFileSync } from "node:fs";
44import vm from "node:vm";
55import { webcrypto } from "node:crypto";
6新增:import { caretPollDelay, caretPollFast, caretFreshFor } from "./caret-poll.mjs";
67const source = readFileSync(
78 new URL("./remote-input.js", import.meta.url),
89 "utf8",
@@ -59,8 +60,12 @@ function fixture(native = false, browserComposition = false, options = {}) {
5960 const context = {
6061 document: doc,
6162 window: win,
62删除: setTimeout,
63删除: clearTimeout,
63新增: setTimeout: options.setTimeout || setTimeout,
64新增: clearTimeout: options.clearTimeout || clearTimeout,
65新增: Date: options.Date || Date,
66新增: caretPollDelay,
67新增: caretPollFast,
68新增: caretFreshFor,
6469 Promise,
6570 Map,
6671 Set,
@@ -125,9 +130,9 @@ function fixture(native = false, browserComposition = false, options = {}) {
125130 compositions.push({ id, ...value });
126131 } : null,
127132 tabId: () => currentTabId,
128删除: caretRect: browserComposition ? async () => ({
133新增: caretRect: browserComposition ? options.caretRect || (async () => ({
129134 available: true, context: "a".repeat(32), rect: [240, 120, 0, 24],
130删除: }) : null,
135新增: })) : null,
131136 pasteContent: async (content) => {
132137 const value = await content;
133138 if (rfb.target) pastes.push(value.png || value.text);
@@ -406,6 +411,75 @@ test("browser composition is forwarded as preedit, then committed separately", a
406411 }
407412});
408413
414新增:// Timers and the clock advance together, one due timer at a time.
415新增:function fakeClock() {
416新增: let now = 1_000_000, sequence = 0;
417新增: const timers = new Map();
418新增: return {
419新增: Date: { now: () => now },
420新增: setTimeout: (run, delay = 0) => { timers.set(++sequence, { at: now + delay, run }); return sequence; },
421新增: clearTimeout: (id) => { timers.delete(id); },
422新增: async advance(duration) {
423新增: const end = now + duration;
424新增: for (;;) {
425新增: const due = [...timers].filter(([, timer]) => timer.at <= end).sort((a, b) => a[1].at - b[1].at || a[0] - b[0])[0];
426新增: if (!due) break;
427新增: timers.delete(due[0]);
428新增: now = due[1].at;
429新增: due[1].run();
430新增: for (let turn = 0; turn < 8; turn++) await Promise.resolve();
431新增: }
432新增: now = end;
433新增: },
434新增: };
435新增:}
436新增:
437新增:test("caret readings back off while the viewer is quiet and resume with input", async () => {
438新增: const clock = fakeClock();
439新增: let readings = 0;
440新增: const f = fixture(false, true, { ...clock, caretRect: async () => {
441新增: readings++;
442新增: return { available: true, context: "a".repeat(32), rect: [240, 120, 0, 24] };
443新增: } });
444新增: try {
445新增: f.rfb.focus();
446新增: await clock.advance(2900);
447新增: assert.equal(readings, 12);
448新增: readings = 0;
449新增: // The earlier fixed interval read the caret 240 times in this minute.
450新增: await clock.advance(60000);
451新增: assert.ok(readings >= 30 && readings <= 50, `${readings} readings`);
452新增: readings = 0;
453新增: await clock.advance(1900);
454新增: assert.equal(readings, 1);
455新增: // Input reschedules a slow wait instead of waiting it out.
456新增: f.key("keydown", "a", "KeyA");
457新增: readings = 0;
458新增: await clock.advance(250);
459新增: assert.equal(readings, 1);
460新增: await clock.advance(1000);
461新增: assert.equal(readings, 5);
462新增: } finally {
463新增: f.controller.dispose();
464新增: }
465新增:});
466新增:
467新增:test("a composition begins from the last reading of a quiet viewer", async () => {
468新增: const clock = fakeClock();
469新增: const f = fixture(false, true, clock);
470新增: try {
471新增: f.rfb.focus();
472新增: await clock.advance(60000);
473新增: // Just before the next slow reading, the latest one is two seconds old.
474新增: await clock.advance(1900);
475新增: inputEvent(f, "compositionstart");
476新增: assert.equal(f.compositions[0]?.mode, "begin");
477新增: assert.equal(f.compositions[0].context, "a".repeat(32));
478新增: } finally {
479新增: f.controller.dispose();
480新增: }
481新增:});
482新增:
409483test("queued composition stays bound to its original browser tab", async () => {
410484 const f = fixture(false, true);
411485 await new Promise((resolve) => setTimeout(resolve, 5));