跳到主要内容

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

提交记录

修复 Windows Caps Lock 状态同步 (#29)

Windows 原生键盘事件携带 Caps Lock 状态,避免远端 noVNC 在本地已开启 Caps Lock 时补发关闭按键。保留现有按键映射,并补充原生回调与浏览器协议回归测试。 同时为 Windows 续期回归测试补充跨时钟刻度的等待条件,保留严格续期断言并增加失败期限日志;联网生产逻辑保持原有行为。 本地验证:18 组浏览器协议回归、39 项相关 Node 测试及 .NET 非 WinForms 回归通过;Windows 原生测试与生产项目交叉编译通过;相关 Go 测试带竞态检测连续 20 轮通过。Windows 2022/2025 原生键盘回归各 287 项通过。macOS 已携带同名字段,Linux 使用原始 WebKit 按键事件。实体键盘与真实远端输入仍需单独验收。 Co-authored-by: xiaokuanye <[email protected]>

作者
Monin
时间
2026/11/10 21:08
提交
a69c7d8
上一个
4dc32a4
这个版本的全部文件
修改desktop/windows.tests/Cage.Windows.Tests.csproj+11 −0看文件
@@ -4,6 +4,11 @@
44 <TargetFramework>net10.0</TargetFramework>
55 <Nullable>enable</Nullable>
66 <ImplicitUsings>enable</ImplicitUsings>
7新增: <WindowsNativeInputTests Condition="'$(WindowsNativeInputTests)' == '' and $([MSBuild]::IsOSPlatform('Windows'))">true</WindowsNativeInputTests>
8新增: </PropertyGroup>
9新增: <PropertyGroup Condition="'$(WindowsNativeInputTests)' == 'true'">
10新增: <TargetFramework>net10.0-windows</TargetFramework>
11新增: <UseWindowsForms>true</UseWindowsForms>
712 </PropertyGroup>
813 <ItemGroup>
914 <EmbeddedResource Include="../../packaging/windows/installation-files.ps1" LogicalName="Cage.InstallationFiles.ps1" />
@@ -16,4 +21,10 @@
1621 <Compile Include="../windows/Authenticode.cs" Link="Authenticode.cs" />
1722 <Compile Include="../windows/WindowLayout.cs" Link="WindowLayout.cs" />
1823 </ItemGroup>
24新增: <ItemGroup Condition="'$(WindowsNativeInputTests)' == 'true'">
25新增: <Compile Include="../windows/NativeInput.cs" Link="NativeInput.cs" />
26新增: </ItemGroup>
27新增: <ItemGroup Condition="'$(WindowsNativeInputTests)' != 'true'">
28新增: <Compile Remove="NativeInputTests.cs" />
29新增: </ItemGroup>
1930</Project>
新增desktop/windows.tests/NativeInputTests.cs+125 −0看文件
@@ -0,0 +1,125 @@
1新增:using System.ComponentModel;
2新增:using System.Reflection;
3新增:using System.Runtime.ExceptionServices;
4新增:using System.Runtime.InteropServices;
5新增:using System.Text.Json;
6新增:using Cage.Windows;
7新增:
8新增:internal static class NativeInputTests
9新增:{
10新增: // SetKeyboardState affects only this thread's input-state table. No SendInput,
11新增: // input-queue attachment, visible window, or keyboard LED changes are used.
12新增: internal static void Run()
13新增: {
14新增: Exception? failure = null;
15新增: var thread = new Thread(() => {
16新增: try { RunOnInputThread(); }
17新增: catch (Exception error) { failure = error; }
18新增: }) { IsBackground = true, Name = "Cage native input regression" };
19新增: thread.SetApartmentState(ApartmentState.STA);
20新增: thread.Start();
21新增: if (!thread.Join(TimeSpan.FromSeconds(15))) throw new TimeoutException("Native input regression did not complete");
22新增: if (failure != null) ExceptionDispatchInfo.Capture(failure).Throw();
23新增: }
24新增:
25新增: private static void RunOnInputThread()
26新增: {
27新增: var assertions = 0;
28新增: void Check(bool value, string message)
29新增: {
30新增: assertions++;
31新增: if (!value) throw new InvalidOperationException(message);
32新增: }
33新增:
34新增: var events = new List<Dictionary<string, object?>>();
35新增: using var host = new Form { ShowInTaskbar = false };
36新增: using var web = new Panel();
37新增: using var input = new NativeInput(events.Add);
38新增: host.Controls.Add(web);
39新增: host.Controls.Add(input);
40新增: var owner = Guid.NewGuid().ToString();
41新增: Check(input.ProcessRequest(JsonSerializer.SerializeToElement(new {
42新增: owner, operation = "activate", x = 0, y = 0, height = 24,
43新增: }), web, 1), "native input activation rejected");
44新增: Check(!host.Visible, "regression fixture must remain hidden");
45新增:
46新增: var down = typeof(NativeInput).GetMethod("OnKeyDown", BindingFlags.Instance | BindingFlags.NonPublic)!;
47新增: var press = typeof(NativeInput).GetMethod("OnKeyPress", BindingFlags.Instance | BindingFlags.NonPublic)!;
48新增: var up = typeof(NativeInput).GetMethod("OnKeyUp", BindingFlags.Instance | BindingFlags.NonPublic)!;
49新增: var original = new byte[256];
50新增: if (!GetKeyboardState(original)) throw new Win32Exception(Marshal.GetLastWin32Error());
51新增: try
52新增: {
53新增: foreach (var capsLock in new[] { false, true })
54新增: foreach (var shift in new[] { false, true })
55新增: {
56新增: var state = new byte[256];
57新增: state[(int)Keys.CapsLock] = (byte)(capsLock ? 1 : 0);
58新增: state[(int)Keys.ShiftKey] = state[(int)Keys.LShiftKey] = (byte)(shift ? 0x80 : 0);
59新增: if (!SetKeyboardState(state)) throw new Win32Exception(Marshal.GetLastWin32Error());
60新增: Check(Control.IsKeyLocked(Keys.CapsLock) == capsLock, "thread CapsLock fixture state was not applied");
61新增: Check(((Control.ModifierKeys & Keys.Shift) != 0) == shift, "thread Shift fixture state was not applied");
62新增:
63新增: void CheckEvent(int index, string kind, string key, string code, bool textKey)
64新增: {
65新增: var value = events[index];
66新增: Check(Equals(value["owner"], owner), "input owner changed");
67新增: Check(Equals(value["kind"], kind), "input event kind changed");
68新增: Check(Equals(value["key"], key), "input character or command changed");
69新增: Check(Equals(value["code"], code), "physical key code changed");
70新增: Check(Equals(value["textKey"], textKey), "text key classification changed");
71新增: Check(value.TryGetValue("modifierCapsLock", out var locked) && Equals(locked, capsLock),
72新增: $"CapsLock={capsLock}, Shift={shift}: {kind} {code} lost CapsLock state");
73新增: Check(Equals(value["shiftKey"], shift), "Shift state changed");
74新增: Check(Equals(value["ctrlKey"], false) && Equals(value["altKey"], false) && Equals(value["metaKey"], false),
75新增: "unpressed modifiers leaked into the event");
76新增: }
77新增:
78新增: // Invoke the actual production WinForms callbacks, including
79新增: // WM_CHAR's character payload rather than rebuilding Key() here.
80新增: events.Clear();
81新增: var modifiers = shift ? Keys.Shift : Keys.None;
82新增: var character = capsLock ^ shift ? 'A' : 'a';
83新增: down.Invoke(input, [new KeyEventArgs(Keys.A | modifiers)]);
84新增: Check(events.Count == 0, "printable keydown must wait for the character callback");
85新增: press.Invoke(input, [new KeyPressEventArgs(character)]);
86新增: up.Invoke(input, [new KeyEventArgs(Keys.A | modifiers)]);
87新增: Check(events.Count == 2, "printable key must produce one down/up pair");
88新增: CheckEvent(0, "keydown", character.ToString(), "KeyA", true);
89新增: CheckEvent(1, "keyup", "a", "KeyA", false);
90新增:
91新增: // Commands have no KeyPress callback. CapsLock transitions,
92新增: // navigation and Shift must all carry the same state snapshot.
93新增: foreach (var command in new[] {
94新增: (Keys.CapsLock, "CapsLock", "CapsLock"),
95新增: (Keys.Left, "ArrowLeft", "ArrowLeft"),
96新增: (Keys.ShiftKey, "Shift", "ShiftLeft"),
97新增: })
98新增: {
99新增: events.Clear();
100新增: down.Invoke(input, [new KeyEventArgs(command.Item1 | modifiers)]);
101新增: up.Invoke(input, [new KeyEventArgs(command.Item1 | modifiers)]);
102新增: Check(events.Count == 2, "command must produce one down/up pair");
103新增: CheckEvent(0, "keydown", command.Item2, command.Item3, false);
104新增: CheckEvent(1, "keyup", command.Item2, command.Item3, false);
105新增: }
106新增: }
107新增: }
108新增: finally
109新增: {
110新增: if (!SetKeyboardState(original)) throw new Win32Exception(Marshal.GetLastWin32Error());
111新增: }
112新增: var restored = new byte[256];
113新增: if (!GetKeyboardState(restored)) throw new Win32Exception(Marshal.GetLastWin32Error());
114新增: Check(original.SequenceEqual(restored), "test thread keyboard state was not restored");
115新增: Console.WriteLine($"Windows native input: {assertions} assertions passed; CapsLock on/off, Shift combinations, printable/command down/up, thread state restored.");
116新增: }
117新增:
118新增: [DllImport("user32.dll", SetLastError = true)]
119新增: [return: MarshalAs(UnmanagedType.Bool)]
120新增: private static extern bool GetKeyboardState([Out] byte[] state);
121新增:
122新增: [DllImport("user32.dll", SetLastError = true)]
123新增: [return: MarshalAs(UnmanagedType.Bool)]
124新增: private static extern bool SetKeyboardState(byte[] state);
125新增:}
修改desktop/windows.tests/Program.cs+4 −0看文件
@@ -29,6 +29,10 @@ if (args is ["prepare-update", "--json", "--stop"])
2929 return;
3030}
3131
32新增:#if WINDOWS
33新增:NativeInputTests.Run();
34新增:#endif
35新增:
3236var assertions = 0;
3337void Check(bool condition, string message) { assertions++; if (!condition) throw new Exception(message); }
3438void Reject(Action action, string message)
修改desktop/windows/NativeInput.cs+2 −1看文件
@@ -163,7 +163,8 @@ internal sealed class NativeInput : TextBox
163163 publish(new() { ["owner"] = owner, ["kind"] = down ? "keydown" : "keyup", ["key"] = text ?? pair.Item1,
164164 ["code"] = code, ["textKey"] = text != null, ["repeat"] = repeating,
165165 ["ctrlKey"] = (ModifierKeys & Keys.Control) != 0, ["altKey"] = (ModifierKeys & Keys.Alt) != 0,
166删除: ["shiftKey"] = (ModifierKeys & Keys.Shift) != 0, ["metaKey"] = false });
166新增: ["shiftKey"] = (ModifierKeys & Keys.Shift) != 0, ["metaKey"] = false,
167新增: ["modifierCapsLock"] = IsKeyLocked(Keys.CapsLock) });
167168 }
168169
169170 private void ReadKeyMessage(Message message)
修改internal/workbench/network_recovery_test.go+6 −1看文件
@@ -34,9 +34,14 @@ func TestExitProbeTimeoutKeepsExistingLeaseWithoutRenewing(t *testing.T) {
3434 if err != nil {
3535 t.Fatal(err)
3636 }
37新增: // Windows can grant and renew within the same wall-clock tick.
38新增: // Advance past the grant tick before requiring a later deadline.
39新增: for !time.Now().Add(cage.GateLease).After(before.Until) {
40新增: time.Sleep(time.Millisecond)
41新增: }
3742 s.finishSafetyMonitor(context.Background(), client, gate.Status(), "8.8.8.8", "")
3843 if !gate.Status().Until.After(before.Until) || s.safety.monitorError != "" {
39删除: t.Fatal("successful observation did not renew and clear the retry notice")
44新增: t.Fatalf("successful observation did not renew and clear the retry notice: before=%+v after=%+v monitorError=%q", before, gate.Status(), s.safety.monitorError)
4045 }
4146 s.safety.VerifiedAt = time.Now().Add(-time.Minute)
4247 gate.Close("检查或监测授权已到期")
新增ui/scripts/caps-lock-smoke.mjs+210 −0看文件
@@ -0,0 +1,210 @@
1新增:// Run `npm run prepare-vnc` in ui first. No Cage server or user session is used:
2新增:// every browser request is fulfilled from local UI modules or rejected.
3新增:// CAGE_PLAYWRIGHT_MODULE and CAGE_TEST_BROWSER_PATH select the test runtime.
4新增:import assert from "node:assert/strict";
5新增:import { readFile } from "node:fs/promises";
6新增:import { createRequire } from "node:module";
7新增:import { fileURLToPath } from "node:url";
8新增:import path from "node:path";
9新增:
10新增:const require = createRequire(import.meta.url);
11新增:const { chromium } = require(process.env.CAGE_PLAYWRIGHT_MODULE || "playwright");
12新增:const root = fileURLToPath(new URL("../", import.meta.url));
13新增:const origin = "http://127.0.0.1:51234";
14新增:const browser = await chromium.launch({
15新增: headless: true,
16新增: executablePath: process.env.CAGE_TEST_BROWSER_PATH,
17新增:});
18新增:const checks = [];
19新增:const problems = [];
20新增:
21新增:async function fixture(platform) {
22新增: const page = await browser.newPage();
23新增: page.on("pageerror", (error) => problems.push(error.message));
24新增: await page.addInitScript((value) => {
25新增: Object.defineProperty(navigator, "platform", { get: () => value });
26新增: // The fixture uses production RFB methods but never opens a socket.
27新增: window.WebSocket = class {
28新增: constructor() { throw new Error("Network sockets are forbidden in this fixture"); }
29新增: };
30新增: }, platform);
31新增: await page.route("**/*", async (route) => {
32新增: const url = new URL(route.request().url());
33新增: if (url.origin !== origin) {
34新增: problems.push(`Unexpected external request: ${url.origin}`);
35新增: await route.abort();
36新增: return;
37新增: }
38新增: if (url.pathname === "/caps-lock-smoke") {
39新增: await route.fulfill({ contentType: "text/html", body: '<div id="remote"><canvas width="1000" height="500" tabindex="-1"></canvas></div>' });
40新增: return;
41新增: }
42新增: const relative = decodeURIComponent(url.pathname).slice(1);
43新增: const file = path.resolve(root, relative);
44新增: if (!file.startsWith(root) || !/^(src|\.generated\/novnc)\//.test(relative)) {
45新增: problems.push(`Unexpected fixture request: ${url.pathname}`);
46新增: await route.abort();
47新增: return;
48新增: }
49新增: try {
50新增: const body = await readFile(path.extname(file) ? file : `${file}.js`);
51新增: await route.fulfill({ contentType: "text/javascript", body });
52新增: } catch (error) {
53新增: problems.push(`${url.pathname}: ${error.message}`);
54新增: await route.abort();
55新增: }
56新增: });
57新增: await page.goto(`${origin}/caps-lock-smoke`);
58新增: await page.evaluate(async (platform) => {
59新增: const [{ default: RFB }, { default: Keyboard }, { installRemoteInput }] = await Promise.all([
60新增: import("/.generated/novnc/core/rfb.js"),
61新增: import("/.generated/novnc/core/input/keyboard.js"),
62新增: import("/src/remote-input.js"),
63新增: ]);
64新增: const container = document.querySelector("#remote");
65新增: const rfb = new EventTarget();
66新增: for (const name of ["sendKey", "_cageSendKey", "_cageQueueInput", "_handleKeyEvent", "cageSetKeyboardTarget", "focus", "blur"])
67新增: rfb[name] = RFB.prototype[name].bind(rfb);
68新增: rfb._canvas = container.querySelector("canvas");
69新增: rfb._keyboard = new Keyboard(rfb._canvas);
70新增: rfb._rfbConnectionState = "connected";
71新增: rfb._remoteCapsLock = rfb._remoteNumLock = null;
72新增: let bytes = [];
73新增: const packets = [], observed = [], requests = [];
74新增: rfb._sock = {
75新增: sQpush8(value) { bytes.push(value); },
76新增: sQpush16(value) { bytes.push((value >> 8) & 255, value & 255); },
77新增: sQpush32(value) { bytes.push(value >>> 24, (value >> 16) & 255, (value >> 8) & 255, value & 255); },
78新增: flush() { packets.push(bytes); bytes = []; },
79新增: };
80新增: window.cageNativeIMEAvailable = true;
81新增: window.webkit = { messageHandlers: { cage: { postMessage: async (value) => {
82新增: if (value.action === "clipboardRevision") return 0;
83新增: if (value.action !== "remoteInput") throw new Error(`Unexpected native operation: ${value.action}`);
84新增: requests.push(value);
85新增: return true;
86新增: } } } };
87新增: const input = installRemoteInput({
88新增: events: rfb,
89新增: setKeyboardTarget: (target) => rfb.cageSetKeyboardTarget(target),
90新增: sendKey: (...key) => rfb.sendKey(...key),
91新增: focus: () => rfb.focus(),
92新增: pasteText() { throw new Error("ASCII key fixture must not use paste"); },
93新增: runKeyAction: (action) => rfb._cageQueueInput(() => action((...key) => rfb._cageSendKey(...key))),
94新增: }, container, {
95新增: mode: () => /mac/i.test(platform) ? "mac" : "native",
96新增: isActive: () => true,
97新增: tabId: () => "fixture-tab",
98新增: caretRect: async () => ({ available: true, context: "a".repeat(32), rect: [20, 20, 1, 24] }),
99新增: onStatus() {}, onFallback() {},
100新增: insertText() { throw new Error("ASCII key fixture must not use text insertion"); },
101新增: });
102新增: rfb.focus();
103新增: const target = container.querySelector("textarea");
104新增: target.addEventListener("keydown", (event) => {
105新增: observed.push({ key: event.key, caps: event.getModifierState("CapsLock"), shift: event.shiftKey });
106新增: }, true);
107新增: window.probe = {
108新增: requests, input,
109新增: run({ remoteCapsLock, qemu = false, sequence }) {
110新增: packets.length = 0;
111新增: observed.length = 0;
112新增: rfb._remoteCapsLock = remoteCapsLock;
113新增: rfb._remoteNumLock = null;
114新增: rfb._qemuExtKeyEventSupported = qemu;
115新增: const owner = requests.find((value) => value.operation === "activate").owner;
116新增: for (const value of sequence) {
117新增: if (Object.hasOwn(value, "feedback")) {
118新增: // A server LED-state reply arrives after the CapsLock press.
119新增: rfb._remoteCapsLock = value.feedback;
120新增: } else {
121新增: window.dispatchEvent(new CustomEvent("cage-native-input", { detail: { owner, ...value } }));
122新增: }
123新增: }
124新增: return {
125新增: observed,
126新增: keys: packets.map((packet) => ({
127新增: sym: ((packet[4] << 24) | (packet[5] << 16) | (packet[6] << 8) | packet[7]) >>> 0,
128新增: down: Boolean(packet[0] === 255 ? packet[3] : packet[1]),
129新增: protocol: packet[0] === 255 ? "qemu" : "rfb",
130新增: })),
131新增: };
132新增: },
133新增: };
134新增: }, platform);
135新增: await page.waitForFunction(() => probe.requests.some((value) => value.operation === "activate"));
136新增: return page;
137新增:}
138新增:
139新增:const keyPair = (key, code, caps, shift = false) => ["keydown", "keyup"].map((kind) => ({
140新增: kind, key, code, textKey: key.length === 1, shiftKey: shift,
141新增: ...(caps === undefined ? {} : { modifierCapsLock: caps }),
142新增:}));
143新增:const expectKeys = (result, expected, label, qemu) => {
144新增: assert.deepEqual(result.keys.map(({ sym, down }) => [sym, down]), expected, label);
145新增: assert.ok(result.keys.every(({ protocol }) => protocol === (qemu ? "qemu" : "rfb")), label);
146新增: checks.push(label);
147新增:};
148新增:const press = (sym) => [[sym, true], [sym, false]];
149新增:
150新增:try {
151新增: const windows = await fixture("Win32");
152新增: for (const qemu of [false, true]) {
153新增: const suffix = qemu ? "QEMU" : "RFB";
154新增: const run = (remoteCapsLock, sequence) => windows.evaluate((value) => probe.run(value), { remoteCapsLock, qemu, sequence });
155新增: const missing = await run(true, keyPair("A", "KeyA"));
156新增: assert.equal(missing.observed[0].caps, false, "Missing native state defaults to false in a real KeyboardEvent");
157新增: expectKeys(missing, [...press(0xffe5), ...press(65)], `negative control: omitted lock state wrongly toggles CapsLock (${suffix})`, qemu);
158新增:
159新增: const on = await run(true, keyPair("A", "KeyA", true));
160新增: assert.equal(on.observed[0].caps, true);
161新增: expectKeys(on, press(65), `Windows CapsLock on stays on (${suffix})`, qemu);
162新增: const off = await run(false, keyPair("a", "KeyA", false));
163新增: assert.equal(off.observed[0].caps, false);
164新增: expectKeys(off, press(97), `Windows CapsLock off stays off (${suffix})`, qemu);
165新增:
166新增: expectKeys(await run(false, keyPair("A", "KeyA", true)), [...press(0xffe5), ...press(65)],
167新增: `Windows local CapsLock on resynchronizes stale remote off (${suffix})`, qemu);
168新增: expectKeys(await run(true, keyPair("a", "KeyA", false)), [...press(0xffe5), ...press(97)],
169新增: `Windows local CapsLock off resynchronizes stale remote on (${suffix})`, qemu);
170新增:
171新增: expectKeys(await run(false, [
172新增: ...keyPair("CapsLock", "CapsLock", true), { feedback: true }, ...keyPair("A", "KeyA", true),
173新增: ...keyPair("CapsLock", "CapsLock", false), { feedback: false }, ...keyPair("a", "KeyA", false),
174新增: ]), [...press(0xffe5), ...press(65), ...press(0xffe5), ...press(97)],
175新增: `Windows CapsLock on/off sequence has no extra toggles after LED replies (${suffix})`, qemu);
176新增:
177新增: for (const caps of [false, true]) {
178新增: const letter = caps ? "a" : "A";
179新增: const shifted = await run(caps, [
180新增: { kind: "keydown", key: "Shift", code: "ShiftLeft", modifierCapsLock: caps, shiftKey: true },
181新增: ...keyPair(letter, "KeyA", caps, true),
182新增: { kind: "keyup", key: "Shift", code: "ShiftLeft", modifierCapsLock: caps, shiftKey: false },
183新增: ]);
184新增: assert.ok(shifted.observed.every((event) => event.caps === caps && event.shift));
185新增: expectKeys(shifted, [[0xffe1, true], ...press(letter.codePointAt(0)), [0xffe1, false]],
186新增: `Windows ${caps ? "CapsLock+Shift lowercase" : "Shift uppercase"} preserves modifiers (${suffix})`, qemu);
187新增: }
188新增: }
189新增: await windows.evaluate(() => probe.input.dispose());
190新增: await windows.close();
191新增:
192新增: const mac = await fixture("MacIntel");
193新增: for (const caps of [true, false]) {
194新增: const letter = caps ? "A" : "a";
195新增: const result = await mac.evaluate((value) => probe.run(value), { remoteCapsLock: caps, sequence: keyPair(letter, "KeyA", caps) });
196新增: assert.equal(result.observed[0].caps, caps);
197新增: expectKeys(result, press(letter.codePointAt(0)), `existing macOS native payload preserves CapsLock ${caps ? "on" : "off"}`, false);
198新增: }
199新增: await mac.evaluate(() => probe.input.dispose());
200新增: await mac.close();
201新增: assert.deepEqual(problems, [], "The fixture must have no page errors or unexpected requests");
202新增: console.log(JSON.stringify({
203新增: passed: true,
204新增: checks,
205新增: coverage: "Real Chromium KeyboardEvent, production installRemoteInput native-event bridge, noVNC keyboard, RFB lock synchronization, and final wire encoding; in-memory transport only.",
206新增: limitation: "Native Windows/GTK/AppKit event production, physical keyboard LED state, and remote X11 application behavior require separate runtime acceptance. Mac platform detection is simulated in Chromium, not WebKit.",
207新增: }, null, 2));
208新增:} finally {
209新增: await browser.close();
210新增:}