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

main
ts 223 lines 7.99 KB
Raw
1 export interface WindowsForegroundApi {
2 readonly getCurrentThreadId: () => number;
3 readonly getForegroundWindow: () => bigint;
4 readonly getWindowClassName: (windowHandle: bigint) => string;
5 readonly getWindowThreadId: (windowHandle: bigint) => number;
6 readonly getWindowThreadAndProcessId: (windowHandle: bigint) => {
7 readonly threadId: number;
8 readonly processId: number;
9 };
10 readonly getWindowText: (windowHandle: bigint) => string;
11 readonly getWindowRect: (
12 windowHandle: bigint,
13 ) =>
14 | { readonly x: number; readonly y: number; readonly width: number; readonly height: number }
15 | undefined;
16 readonly getProcessImagePath: (processId: number) => string;
17 readonly isKeyDown: (virtualKey: number) => boolean;
18 readonly attachThreadInput: (
19 sourceThreadId: number,
20 targetThreadId: number,
21 attach: boolean,
22 ) => boolean;
23 readonly setForegroundWindow: (windowHandle: bigint) => boolean;
24 }
25
26 const WINDOWS_SHELL_HOSTED_WINDOW_CLASSES = new Set(["ApplicationFrameWindow"]);
27
28 function nativeWindowHandle(buffer: Buffer): bigint {
29 if (buffer.length === 8) return buffer.readBigUInt64LE();
30 if (buffer.length === 4) return BigInt(buffer.readUInt32LE());
31 throw new Error(`Unsupported Windows window handle size: ${String(buffer.length)} bytes.`);
32 }
33
34 export function activateWindowsForegroundWithApi(
35 handleBuffer: Buffer,
36 api: WindowsForegroundApi,
37 ): boolean {
38 const targetWindow = nativeWindowHandle(handleBuffer);
39 const foregroundWindow = api.getForegroundWindow();
40 if (targetWindow === foregroundWindow) return true;
41
42 const currentThreadId = api.getCurrentThreadId();
43 const foregroundThreadId = foregroundWindow === 0n ? 0 : api.getWindowThreadId(foregroundWindow);
44 const shouldAttach =
45 currentThreadId !== 0 && foregroundThreadId !== 0 && currentThreadId !== foregroundThreadId;
46 const attached = shouldAttach && api.attachThreadInput(currentThreadId, foregroundThreadId, true);
47
48 try {
49 return api.setForegroundWindow(targetWindow);
50 } finally {
51 if (attached) {
52 api.attachThreadInput(currentThreadId, foregroundThreadId, false);
53 }
54 }
55 }
56
57 function isWindowsShellHostedForegroundWithApi(api: WindowsForegroundApi): boolean {
58 const foregroundWindow = api.getForegroundWindow();
59 return (
60 foregroundWindow !== 0n &&
61 WINDOWS_SHELL_HOSTED_WINDOW_CLASSES.has(api.getWindowClassName(foregroundWindow))
62 );
63 }
64
65 let windowsForegroundApiPromise: Promise<WindowsForegroundApi> | undefined;
66
67 const PROCESS_QUERY_LIMITED_INFORMATION = 0x1000;
68
69 export function loadWindowsForegroundApi(): Promise<WindowsForegroundApi> {
70 windowsForegroundApiPromise ??= import("ffi-rs").then(({ DataType, load, open }) => {
71 const kernel32 = "t3-kernel32";
72 const user32 = "t3-user32";
73 open({ library: kernel32, path: "kernel32.dll" });
74 open({ library: user32, path: "user32.dll" });
75
76 return {
77 getCurrentThreadId: () =>
78 load({
79 library: kernel32,
80 funcName: "GetCurrentThreadId",
81 retType: DataType.U32,
82 paramsType: [],
83 paramsValue: [],
84 }),
85 getForegroundWindow: () =>
86 load({
87 library: user32,
88 funcName: "GetForegroundWindow",
89 retType: DataType.BigInt,
90 paramsType: [],
91 paramsValue: [],
92 }) as bigint,
93 getWindowClassName: (windowHandle) => {
94 const buffer = Buffer.alloc(512);
95 const length = load({
96 library: user32,
97 funcName: "GetClassNameW",
98 retType: DataType.I32,
99 paramsType: [DataType.BigInt, DataType.U8Array, DataType.I32],
100 paramsValue: [windowHandle, buffer, buffer.byteLength / 2],
101 });
102 return length > 0 ? buffer.subarray(0, length * 2).toString("utf16le") : "";
103 },
104 getWindowThreadId: (windowHandle) =>
105 load({
106 library: user32,
107 funcName: "GetWindowThreadProcessId",
108 retType: DataType.U32,
109 paramsType: [DataType.BigInt, DataType.BigInt],
110 paramsValue: [windowHandle, 0n],
111 }),
112 getWindowThreadAndProcessId: (windowHandle) => {
113 const out = Buffer.alloc(4);
114 const threadId = load({
115 library: user32,
116 funcName: "GetWindowThreadProcessId",
117 retType: DataType.U32,
118 paramsType: [DataType.BigInt, DataType.U8Array],
119 paramsValue: [windowHandle, out],
120 });
121 return { threadId, processId: out.readUInt32LE(0) };
122 },
123 getWindowText: (windowHandle) => {
124 const buffer = Buffer.alloc(2 * 1024);
125 const length = load({
126 library: user32,
127 funcName: "GetWindowTextW",
128 retType: DataType.I32,
129 paramsType: [DataType.BigInt, DataType.U8Array, DataType.I32],
130 paramsValue: [windowHandle, buffer, buffer.byteLength / 2],
131 });
132 return length > 0 ? buffer.subarray(0, length * 2).toString("utf16le") : "";
133 },
134 getWindowRect: (windowHandle) => {
135 const rect = Buffer.alloc(16);
136 const ok = load({
137 library: user32,
138 funcName: "GetWindowRect",
139 retType: DataType.Boolean,
140 paramsType: [DataType.BigInt, DataType.U8Array],
141 paramsValue: [windowHandle, rect],
142 });
143 if (!ok) return undefined;
144 const left = rect.readInt32LE(0);
145 const top = rect.readInt32LE(4);
146 return {
147 x: left,
148 y: top,
149 width: Math.max(0, rect.readInt32LE(8) - left),
150 height: Math.max(0, rect.readInt32LE(12) - top),
151 };
152 },
153 getProcessImagePath: (processId) => {
154 const handle = load({
155 library: kernel32,
156 funcName: "OpenProcess",
157 retType: DataType.BigInt,
158 paramsType: [DataType.U32, DataType.Boolean, DataType.U32],
159 paramsValue: [PROCESS_QUERY_LIMITED_INFORMATION, false, processId],
160 }) as bigint;
161 if (handle === 0n) return "";
162 try {
163 const buffer = Buffer.alloc(2 * 32_768);
164 const size = Buffer.alloc(4);
165 size.writeUInt32LE(buffer.byteLength / 2, 0);
166 const ok = load({
167 library: kernel32,
168 funcName: "QueryFullProcessImageNameW",
169 retType: DataType.Boolean,
170 paramsType: [DataType.BigInt, DataType.U32, DataType.U8Array, DataType.U8Array],
171 paramsValue: [handle, 0, buffer, size],
172 });
173 return ok ? buffer.subarray(0, size.readUInt32LE(0) * 2).toString("utf16le") : "";
174 } finally {
175 load({
176 library: kernel32,
177 funcName: "CloseHandle",
178 retType: DataType.Boolean,
179 paramsType: [DataType.BigInt],
180 paramsValue: [handle],
181 });
182 }
183 },
184 isKeyDown: (virtualKey) =>
185 (load({
186 library: user32,
187 funcName: "GetAsyncKeyState",
188 retType: DataType.I16,
189 paramsType: [DataType.I32],
190 paramsValue: [virtualKey],
191 }) &
192 0x8000) !==
193 0,
194 attachThreadInput: (sourceThreadId, targetThreadId, attach) =>
195 load({
196 library: user32,
197 funcName: "AttachThreadInput",
198 retType: DataType.Boolean,
199 paramsType: [DataType.U32, DataType.U32, DataType.Boolean],
200 paramsValue: [sourceThreadId, targetThreadId, attach],
201 }),
202 setForegroundWindow: (windowHandle) =>
203 load({
204 library: user32,
205 funcName: "SetForegroundWindow",
206 retType: DataType.Boolean,
207 paramsType: [DataType.BigInt],
208 paramsValue: [windowHandle],
209 }),
210 } satisfies WindowsForegroundApi;
211 });
212 return windowsForegroundApiPromise;
213 }
214
215 export async function activateWindowsForeground(handleBuffer: Buffer): Promise<void> {
216 const api = await loadWindowsForegroundApi();
217 if (activateWindowsForegroundWithApi(handleBuffer, api)) return;
218 throw new Error("Windows refused to activate the T3 Code window.");
219 }
220
221 export async function isWindowsShellHostedForeground(): Promise<boolean> {
222 return isWindowsShellHostedForegroundWithApi(await loadWindowsForegroundApi());
223 }