@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 392 lines 13.2 KB
Raw
1 // @effect-diagnostics nodeBuiltinImport:off -- Event-driven fake of the portal transport.
2 import * as NodeEvents from "node:events";
3 import { DBusError, Message, MessageType, Variant, type MessageBus } from "dbus-next";
4 import { afterEach, expect, it, vi } from "vite-plus/test";
5 import { PortalCaptureShortcut, portalShortcutTrigger } from "./PortalCaptureShortcut.ts";
6
7 const chord = {
8 key: "2",
9 modKey: true,
10 ctrlKey: false,
11 altKey: false,
12 shiftKey: true,
13 metaKey: false,
14 };
15 const root = "/org/freedesktop/portal/desktop";
16 const portal = "org.freedesktop.portal.GlobalShortcuts";
17 const clients: PortalCaptureShortcut[] = [];
18 type Shortcut = [string, { description?: Variant<string>; trigger_description?: Variant<string> }];
19
20 class FakeBus extends NodeEvents.EventEmitter {
21 calls: Message[] = [];
22 sends: Message[] = [];
23 disconnect = vi.fn();
24 registryError: Error | undefined;
25 version = 2;
26 autoBind = true;
27 actualLabel = "Ctrl+Shift+2";
28 bindStatus = 0;
29 session = "";
30 requestPath = "";
31 boundId = "";
32 foreignHandle = false;
33 owner = ":1.2";
34
35 send(message: Message) {
36 this.sends.push(message);
37 }
38 signal(
39 iface: string,
40 member: string,
41 path: string,
42 body: unknown[],
43 sender = this.owner,
44 signature = "",
45 ) {
46 this.emit(
47 "message",
48 new Message({
49 type: MessageType.SIGNAL,
50 sender,
51 interface: iface,
52 member,
53 path,
54 body,
55 signature,
56 }),
57 );
58 }
59 response(path: string, status: number, results: Record<string, Variant<unknown>>) {
60 this.signal("org.freedesktop.portal.Request", "Response", path, [status, results]);
61 }
62 respondBind(status = this.bindStatus) {
63 this.response(this.requestPath, status, {
64 shortcuts: new Variant("a(sa{sv})", [
65 [
66 this.boundId,
67 {
68 description: new Variant("s", "Capture a window"),
69 trigger_description: new Variant("s", this.actualLabel),
70 },
71 ],
72 ]),
73 });
74 }
75 activate(id = this.boundId, session = this.session, sender = this.owner) {
76 this.signal(portal, "Activated", root, [session, id, 1, {}], sender, "osta{sv}");
77 }
78 async call(message: Message) {
79 this.calls.push(message);
80 const reply = (body: unknown[] = []) =>
81 new Message({
82 type: MessageType.METHOD_RETURN,
83 replySerial: "1",
84 destination: ":1.23",
85 body,
86 });
87 if (message.member === "Register") {
88 if (this.registryError) throw this.registryError;
89 return reply();
90 }
91 if (message.member === "GetNameOwner") return reply([this.owner]);
92 if (message.member === "Get") return reply([new Variant("u", this.version)]);
93 if (message.member === "AddMatch" || message.member === "ConfigureShortcuts") return reply();
94 const options = message.body.at(-1) as Record<string, Variant<string>>;
95 const path = `${root}/request/1_23/${options.handle_token!.value}`;
96 if (message.member === "CreateSession") {
97 this.session = `${root}/session/1_23/${options.session_handle_token!.value}`;
98 this.response(path, 0, {
99 session_handle: new Variant(
100 "s",
101 this.foreignHandle ? `${root}/session/9_9/other` : this.session,
102 ),
103 });
104 } else if (message.member === "BindShortcuts") {
105 this.boundId = (message.body[1] as Shortcut[])[0]![0];
106 this.requestPath = path;
107 this.emit("bind");
108 if (this.autoBind) this.respondBind();
109 } else throw new Error(`Unexpected call: ${message.member}`);
110 return reply([path]);
111 }
112 }
113
114 function start(bus = new FakeBus(), shortcut = chord, managedByHyprland = false) {
115 const capture = vi.fn();
116 const changed = vi.fn();
117 const client = new PortalCaptureShortcut(
118 "com.t3tools.T3Code",
119 shortcut,
120 capture,
121 changed,
122 bus as unknown as MessageBus,
123 managedByHyprland,
124 );
125 clients.push(client);
126 return { bus, client, capture, changed };
127 }
128
129 afterEach(() => {
130 for (const client of clients.splice(0)) client.close();
131 vi.useRealTimers();
132 vi.unstubAllEnvs();
133 });
134
135 it("accepts Hyprland's action-only binding without claiming the keys are reserved", async () => {
136 const bus = new FakeBus();
137 bus.actualLabel = "";
138 const { client, capture } = start(bus, chord, true);
139 await client.ready;
140 expect(client.state).toMatchObject({
141 shortcutRegistered: false,
142 shortcutActionRegistered: true,
143 shortcutPending: false,
144 shortcutCanRetry: false,
145 });
146 expect(bus.boundId).toBe("capture-window");
147 expect(bus.calls.find((call) => call.member === "BindShortcuts")?.body[1]).toEqual([
148 ["capture-window", { description: new Variant("s", "Capture a window") }],
149 ]);
150 bus.activate("wrong");
151 bus.activate(bus.boundId, bus.session, ":1.999");
152 expect(capture).not.toHaveBeenCalled();
153 bus.activate();
154 expect(capture).toHaveBeenCalledOnce();
155 await expect(client.configure()).rejects.toThrow("Hyprland config");
156 bus.signal(portal, "ShortcutsChanged", root, [bus.session, []]);
157 bus.activate();
158 expect(capture).toHaveBeenCalledOnce();
159 expect(client.state.shortcutActionRegistered).toBe(false);
160 });
161
162 it.each([
163 ["2", "CTRL+SHIFT+2"],
164 ["f12", "CTRL+SHIFT+F12"],
165 ["pageup", "CTRL+SHIFT+Page_Up"],
166 ["+", "CTRL+SHIFT+plus"],
167 ["arrowleft", "CTRL+SHIFT+Left"],
168 [" ", "CTRL+SHIFT+space"],
169 ])("encodes %s as an XDG shortcut", (key, expected) => {
170 expect(portalShortcutTrigger({ ...chord, key })).toBe(expected);
171 });
172 it("normalizes Ctrl/Mod and rejects unsupported keys before requesting access", () => {
173 expect(portalShortcutTrigger({ ...chord, ctrlKey: true, metaKey: true })).toBe(
174 "CTRL+SHIFT+LOGO+2",
175 );
176 expect(() => portalShortcutTrigger({ ...chord, key: "unknown-key" })).toThrow("isn't supported");
177 });
178
179 it("does not call submission approval, then reads the actual assigned shortcut", async () => {
180 const bus = new FakeBus();
181 bus.autoBind = false;
182 bus.actualLabel = "Ctrl+Shift+7";
183 const binding = NodeEvents.EventEmitter.once(bus, "bind");
184 const { client } = start(bus);
185 await binding;
186 expect(client.state.shortcutRegistered).toBe(false);
187 expect(client.state.shortcutPending).toBe(true);
188 bus.respondBind();
189 await client.ready;
190 expect(client.state).toMatchObject({
191 shortcutRegistered: true,
192 shortcutPending: false,
193 shortcutLabel: "Ctrl+Shift+7",
194 });
195 });
196
197 it("binds only the requested shortcut with a stable ID across sessions", async () => {
198 const first = start();
199 await first.client.ready;
200 first.client.close();
201 const { bus, client, capture } = start();
202 await client.ready;
203 expect(bus.boundId).toBe(first.bus.boundId);
204 const binds = bus.calls.filter((call) => call.member === "BindShortcuts");
205 expect(binds).toHaveLength(1);
206 expect(binds[0]!.body[1]).toEqual([
207 [
208 bus.boundId,
209 {
210 description: new Variant("s", "Capture a window"),
211 preferred_trigger: new Variant("s", "CTRL+SHIFT+2"),
212 },
213 ],
214 ]);
215 bus.activate();
216 expect(capture).toHaveBeenCalledOnce();
217 expect(bus.calls[0]?.member).toBe("Register");
218 });
219
220 it("ignores other shortcuts, sessions, and forged activations", async () => {
221 const { bus, client, capture } = start();
222 await client.ready;
223 bus.activate("stale-shortcut");
224 bus.activate(bus.boundId, `${root}/session/9_9/other`);
225 bus.activate(bus.boundId, bus.session, ":1.999");
226 expect(capture).not.toHaveBeenCalled();
227 bus.activate();
228 expect(capture).toHaveBeenCalledOnce();
229 });
230
231 it("replaces a binding without restarting the application and stops the old callback", async () => {
232 const first = start();
233 await first.client.ready;
234 first.client.close();
235 const next = start(new FakeBus(), { ...chord, key: "8" });
236 await next.client.ready;
237 expect(next.bus.boundId).not.toBe(first.bus.boundId);
238 expect(next.bus.calls.find((call) => call.member === "BindShortcuts")?.body[1]).toEqual([
239 [
240 next.bus.boundId,
241 {
242 description: new Variant("s", "Capture a window"),
243 preferred_trigger: new Variant("s", "CTRL+SHIFT+8"),
244 },
245 ],
246 ]);
247 first.bus.activate();
248 next.bus.activate();
249 expect(first.capture).not.toHaveBeenCalled();
250 expect(next.capture).toHaveBeenCalledOnce();
251 expect(
252 first.bus.sends.some(
253 (message) =>
254 message.interface === "org.freedesktop.portal.Session" && message.member === "Close",
255 ),
256 ).toBe(true);
257 });
258
259 it.each([1, 2])(
260 "reports denied/cancelled response %s and offers the desktop permissions UI",
261 async (status) => {
262 const bus = new FakeBus();
263 bus.bindStatus = status;
264 const { client, capture } = start(bus);
265 await client.ready;
266 expect(client.state.shortcutRegistered).toBe(false);
267 expect(client.state.shortcutPending).toBe(false);
268 expect(client.state.shortcutCanRetry).toBe(true);
269 expect(client.state.shortcutMessage).toContain("wasn't granted");
270 bus.activate();
271 expect(capture).not.toHaveBeenCalled();
272 await client.configure();
273 expect(bus.calls.at(-1)?.member).toBe("ConfigureShortcuts");
274 },
275 );
276
277 it("treats a remembered empty binding as unassigned, then observes desktop-side edits", async () => {
278 const bus = new FakeBus();
279 bus.actualLabel = "";
280 const { client, capture } = start(bus);
281 await client.ready;
282 expect(client.state.shortcutRegistered).toBe(false);
283 bus.activate();
284 expect(capture).not.toHaveBeenCalled();
285 bus.signal(portal, "ShortcutsChanged", root, [
286 bus.session,
287 [[bus.boundId, { trigger_description: new Variant("s", "Meta+F12") }]],
288 ]);
289 expect(client.state.shortcutLabel).toBe("Meta+F12");
290 expect(client.state.shortcutRegistered).toBe(true);
291 bus.activate();
292 expect(capture).toHaveBeenCalledOnce();
293 });
294
295 it("captures on older portals without offering an unsupported permission dialog", async () => {
296 const bus = new FakeBus();
297 bus.version = 1;
298 const { client, capture } = start(bus);
299 await client.ready;
300 expect(client.state).toMatchObject({ shortcutRegistered: true, shortcutCanRetry: false });
301 bus.activate();
302 expect(capture).toHaveBeenCalledOnce();
303 bus.signal(portal, "ShortcutsChanged", root, [bus.session, []]);
304 expect(client.state).toMatchObject({
305 shortcutRegistered: false,
306 shortcutCanRetry: false,
307 shortcutMessage: "No shortcut is assigned. Choose one in your desktop's shortcut settings.",
308 });
309 bus.signal("org.freedesktop.portal.Session", "Closed", bus.session, []);
310 expect(client.hasSession).toBe(false);
311 expect(client.state.shortcutCanRetry).toBe(true);
312 });
313
314 it("closes an outstanding consent request and ignores its late response", async () => {
315 const bus = new FakeBus();
316 bus.autoBind = false;
317 const binding = NodeEvents.EventEmitter.once(bus, "bind");
318 const { client, capture, changed } = start(bus);
319 await binding;
320 client.close();
321 bus.respondBind();
322 await client.ready;
323 bus.activate();
324 expect(capture).not.toHaveBeenCalled();
325 expect(changed).not.toHaveBeenCalled();
326 expect(bus.sends.filter((message) => message.member === "Close")).toHaveLength(2);
327 expect(bus.disconnect).toHaveBeenCalledOnce();
328 });
329
330 it("handles a disappearing portal without keeping a false registered state", async () => {
331 const { bus, client } = start();
332 await client.ready;
333 bus.signal(
334 "org.freedesktop.DBus",
335 "NameOwnerChanged",
336 "/org/freedesktop/DBus",
337 ["org.freedesktop.portal.Desktop", ":1.2", ""],
338 "org.freedesktop.DBus",
339 );
340 expect(client.state.shortcutRegistered).toBe(false);
341 expect(client.state.shortcutMessage).toContain("restarted");
342 expect(client.hasSession).toBe(false);
343 expect(bus.disconnect).not.toHaveBeenCalled();
344 await vi.waitFor(() => expect(client.state.shortcutRegistered).toBe(true));
345 expect(bus.calls.filter((call) => call.member === "CreateSession")).toHaveLength(2);
346 });
347
348 it("binds a new session when the portal restarts", async () => {
349 const { bus, client, capture } = start(new FakeBus(), chord, true);
350 await client.ready;
351 const ownerChanged = (from: string, to: string) =>
352 bus.signal(
353 "org.freedesktop.DBus",
354 "NameOwnerChanged",
355 "/org/freedesktop/DBus",
356 ["org.freedesktop.portal.Desktop", from, to],
357 "org.freedesktop.DBus",
358 );
359 ownerChanged(":1.2", "");
360 bus.owner = ":1.3";
361 ownerChanged("", ":1.3");
362 await vi.waitFor(() => expect(client.state.shortcutActionRegistered).toBe(true));
363 expect(bus.calls.filter((call) => call.member === "CreateSession")).toHaveLength(2);
364 bus.activate();
365 expect(capture).toHaveBeenCalledOnce();
366 });
367
368 it("accepts old portals without Registry but does not ignore permission denial", async () => {
369 const bus = new FakeBus();
370 bus.registryError = new DBusError("org.freedesktop.DBus.Error.UnknownMethod", "Old portal");
371 const first = start(bus);
372 await first.client.ready;
373 expect(first.client.state.shortcutRegistered).toBe(true);
374 const denied = new FakeBus();
375 denied.registryError = new DBusError(
376 "org.freedesktop.portal.Error.NotAllowed",
377 "App is not allowed",
378 );
379 const second = start(denied);
380 await second.client.ready;
381 expect(second.client.state.shortcutRegistered).toBe(false);
382 expect(denied.calls.some((call) => call.member === "CreateSession")).toBe(false);
383 });
384
385 it("rejects a foreign session without trying to close someone else's session", async () => {
386 const bus = new FakeBus();
387 bus.foreignHandle = true;
388 const { client } = start(bus);
389 await client.ready;
390 expect(client.state.shortcutRegistered).toBe(false);
391 expect(bus.sends.some((message) => message.path.includes("9_9"))).toBe(false);
392 });