@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 409 lines 14.5 KB
Raw
1 // @effect-diagnostics nodeBuiltinImport:off -- This desktop-only service resolves its bundled helper beside the Electron entrypoint.
2
3 import * as NodePath from "node:path";
4
5 import * as HostProcess from "@t3tools/shared/HostProcess";
6 import type * as Cause from "effect/Cause";
7 import * as Context from "effect/Context";
8 import * as Effect from "effect/Effect";
9 import * as Exit from "effect/Exit";
10 import * as Layer from "effect/Layer";
11 import * as Option from "effect/Option";
12 import * as Ref from "effect/Ref";
13 import * as Schema from "effect/Schema";
14
15 import * as Electron from "electron";
16
17 import {
18 activateWindowsForeground,
19 isWindowsShellHostedForeground,
20 loadWindowsForegroundApi,
21 } from "./WindowsForeground.ts";
22 import { startWindowsForegroundFocusThread } from "./WindowsForegroundFocusThread.ts";
23
24 function windowsForegroundFocusTarget(window: Electron.BrowserWindow) {
25 return {
26 windowId: window.id,
27 processId: process.pid,
28 title: window.getTitle(),
29 // xa11y reports physical desktop pixels on Windows; Electron bounds are DIPs.
30 bounds: Electron.screen.dipToScreenRect(window, window.getBounds()),
31 contentBounds: Electron.screen.dipToScreenRect(window, window.getContentBounds()),
32 };
33 }
34
35 async function isWindowsBrowserWindowForeground(window: Electron.BrowserWindow): Promise<boolean> {
36 const foreground = await loadWindowsForegroundApi()
37 .then((api) => api.getForegroundWindow())
38 .catch(() => undefined);
39 if (window.isDestroyed() || foreground === undefined || foreground === 0n) return false;
40 const handle = window.getNativeWindowHandle();
41 const hwnd = handle.length === 8 ? handle.readBigUInt64LE() : BigInt(handle.readUInt32LE());
42 return foreground === hwnd;
43 }
44
45 const ElectronWindowCreateOptions = Schema.Struct({
46 title: Schema.NullOr(Schema.String),
47 width: Schema.NullOr(Schema.Number),
48 height: Schema.NullOr(Schema.Number),
49 minWidth: Schema.NullOr(Schema.Number),
50 minHeight: Schema.NullOr(Schema.Number),
51 show: Schema.NullOr(Schema.Boolean),
52 modal: Schema.NullOr(Schema.Boolean),
53 frame: Schema.NullOr(Schema.Boolean),
54 transparent: Schema.NullOr(Schema.Boolean),
55 backgroundColor: Schema.NullOr(Schema.String),
56 webPreferences: Schema.Struct({
57 preload: Schema.NullOr(Schema.String),
58 partition: Schema.NullOr(Schema.String),
59 backgroundThrottling: Schema.NullOr(Schema.Boolean),
60 sandbox: Schema.NullOr(Schema.Boolean),
61 contextIsolation: Schema.NullOr(Schema.Boolean),
62 nodeIntegration: Schema.NullOr(Schema.Boolean),
63 webviewTag: Schema.NullOr(Schema.Boolean),
64 }),
65 });
66
67 const ElectronWindowOperation = Schema.Literals([
68 "list-windows",
69 "get-focused-window",
70 "inspect-window",
71 "reveal-window",
72 "send-window-message",
73 "destroy-window",
74 ]);
75
76 export class ElectronWindowCreateError extends Schema.TaggedError<ElectronWindowCreateError>()(
77 "ElectronWindowCreateError",
78 {
79 options: ElectronWindowCreateOptions,
80 cause: Schema.Defect(),
81 },
82 ) {
83 override get message(): string {
84 const title = this.options.title === null ? "" : ` "${this.options.title}"`;
85 const dimensions =
86 this.options.width === null || this.options.height === null
87 ? ""
88 : ` (${this.options.width}x${this.options.height})`;
89 return `Failed to create Electron BrowserWindow${title}${dimensions}.`;
90 }
91 }
92
93 export class ElectronWindowOperationError extends Schema.TaggedError<ElectronWindowOperationError>()(
94 "ElectronWindowOperationError",
95 {
96 operation: ElectronWindowOperation,
97 platform: Schema.String,
98 windowId: Schema.NullOr(Schema.Number),
99 channel: Schema.NullOr(Schema.String),
100 cause: Schema.Defect(),
101 },
102 ) {
103 override get message(): string {
104 const window = this.windowId === null ? "" : ` for window ${this.windowId}`;
105 const channel = this.channel === null ? "" : ` on channel ${JSON.stringify(this.channel)}`;
106 return `Electron window operation ${JSON.stringify(this.operation)} failed${window}${channel} on ${this.platform}.`;
107 }
108 }
109
110 export class ElectronWindow extends Context.Service<
111 ElectronWindow,
112 {
113 /** Auxiliary windows are never returned as the main-or-first fallback. */
114 readonly create: (
115 options: Electron.BrowserWindowConstructorOptions,
116 behavior?: { readonly auxiliary?: boolean },
117 ) => Effect.Effect<Electron.BrowserWindow, ElectronWindowCreateError>;
118 readonly main: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
119 readonly currentMainOrFirst: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
120 readonly focusedMainOrFirst: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
121 readonly setMain: (window: Electron.BrowserWindow) => Effect.Effect<void>;
122 readonly clearMain: (window: Option.Option<Electron.BrowserWindow>) => Effect.Effect<void>;
123 readonly prepareReveal: (window: Electron.BrowserWindow) => Effect.Effect<boolean>;
124 readonly reveal: (window: Electron.BrowserWindow) => Effect.Effect<void>;
125 readonly sendAll: (channel: string, ...args: readonly unknown[]) => Effect.Effect<void>;
126 readonly destroyAll: Effect.Effect<void>;
127 readonly syncAllAppearance: <E, R>(
128 sync: (
129 window: Electron.BrowserWindow,
130 appearance: { readonly titleBarOverlay: boolean },
131 ) => Effect.Effect<void, E, R>,
132 ) => Effect.Effect<void, E, R>;
133 }
134 >()("@t3tools/desktop/electron/ElectronWindow") {}
135
136 /** @public */
137 export const make = Effect.gen(function* () {
138 const platform = yield* HostProcess.Platform;
139 // Lazy-load native accessibility on capture reveal to avoid startup cost for other users.
140 let windowsForegroundFocus: ReturnType<typeof startWindowsForegroundFocusThread> | undefined;
141 const ensureWindowsForegroundFocus = () => {
142 windowsForegroundFocus ??= startWindowsForegroundFocusThread(
143 NodePath.join(__dirname, "electron", "WindowsForegroundFocusWorker.cjs"),
144 );
145 return windowsForegroundFocus;
146 };
147 const captureRevealWindows = new Set<number>();
148 yield* Effect.addFinalizer(() => Effect.sync(() => windowsForegroundFocus?.close()));
149 const mainWindowRef = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
150 const auxiliaryWindows = new WeakSet<Electron.BrowserWindow>();
151 const titleBarOverlayWindows = new WeakSet<Electron.BrowserWindow>();
152
153 const listWindows = Effect.try({
154 try: () => Electron.BrowserWindow.getAllWindows(),
155 catch: (cause) =>
156 new ElectronWindowOperationError({
157 operation: "list-windows",
158 platform,
159 windowId: null,
160 channel: null,
161 cause,
162 }),
163 }).pipe(Effect.orDie);
164
165 const isWindowDestroyed = (window: Electron.BrowserWindow) =>
166 Effect.try({
167 try: () => window.isDestroyed(),
168 catch: (cause) =>
169 new ElectronWindowOperationError({
170 operation: "inspect-window",
171 platform,
172 windowId: window.id,
173 channel: null,
174 cause,
175 }),
176 }).pipe(Effect.orDie);
177
178 const liveMain = Effect.gen(function* () {
179 const main = yield* Ref.get(mainWindowRef);
180 if (Option.isNone(main) || (yield* isWindowDestroyed(main.value))) {
181 return Option.none<Electron.BrowserWindow>();
182 }
183 return main;
184 });
185
186 const currentMainOrFirst = Effect.gen(function* () {
187 const main = yield* liveMain;
188 if (Option.isSome(main)) {
189 return main;
190 }
191
192 const first = Option.fromNullishOr(
193 (yield* listWindows).find((window) => !auxiliaryWindows.has(window)) ?? null,
194 );
195 if (Option.isNone(first) || (yield* isWindowDestroyed(first.value))) {
196 return Option.none<Electron.BrowserWindow>();
197 }
198 return first;
199 });
200
201 const focusedMainOrFirst = Effect.gen(function* () {
202 const focused = yield* Effect.try({
203 try: () => Option.fromNullishOr(Electron.BrowserWindow.getFocusedWindow() ?? null),
204 catch: (cause) =>
205 new ElectronWindowOperationError({
206 operation: "get-focused-window",
207 platform,
208 windowId: null,
209 channel: null,
210 cause,
211 }),
212 }).pipe(Effect.orDie);
213 if (Option.isSome(focused) && !(yield* isWindowDestroyed(focused.value))) {
214 return focused;
215 }
216 return yield* currentMainOrFirst;
217 });
218
219 return ElectronWindow.of({
220 create: Effect.fn("ElectronWindow.create")(function (options, behavior) {
221 const webPreferences = options.webPreferences;
222 const diagnosticOptions = {
223 title: options.title ?? null,
224 width: options.width ?? null,
225 height: options.height ?? null,
226 minWidth: options.minWidth ?? null,
227 minHeight: options.minHeight ?? null,
228 show: options.show ?? null,
229 modal: options.modal ?? null,
230 frame: options.frame ?? null,
231 transparent: options.transparent ?? null,
232 backgroundColor: options.backgroundColor ?? null,
233 webPreferences: {
234 preload: webPreferences?.preload ?? null,
235 partition: webPreferences?.partition ?? null,
236 backgroundThrottling: webPreferences?.backgroundThrottling ?? null,
237 sandbox: webPreferences?.sandbox ?? null,
238 contextIsolation: webPreferences?.contextIsolation ?? null,
239 nodeIntegration: webPreferences?.nodeIntegration ?? null,
240 webviewTag: webPreferences?.webviewTag ?? null,
241 },
242 } satisfies typeof ElectronWindowCreateOptions.Type;
243
244 return Effect.try({
245 try: () => {
246 const window = new Electron.BrowserWindow(options);
247 if (behavior?.auxiliary === true) auxiliaryWindows.add(window);
248 if (options.titleBarOverlay !== undefined && options.titleBarOverlay !== false) {
249 titleBarOverlayWindows.add(window);
250 }
251 return window;
252 },
253 catch: (cause) => new ElectronWindowCreateError({ options: diagnosticOptions, cause }),
254 });
255 }),
256 main: liveMain,
257 currentMainOrFirst,
258 focusedMainOrFirst,
259 setMain: Effect.fn("ElectronWindow.setMain")(function (window) {
260 return Ref.set(mainWindowRef, Option.some(window));
261 }),
262 clearMain: Effect.fn("ElectronWindow.clearMain")(function (window) {
263 return Ref.update(mainWindowRef, (current) => {
264 if (Option.isNone(current)) {
265 return current;
266 }
267 if (Option.isSome(window) && current.value !== window.value) {
268 return current;
269 }
270 return Option.none();
271 });
272 }),
273 prepareReveal: Effect.fn("ElectronWindow.prepareReveal")(function (window) {
274 return Effect.promise(async () => {
275 if (platform !== "win32" || window.isDestroyed()) {
276 return false;
277 }
278 captureRevealWindows.add(window.id);
279 return ensureWindowsForegroundFocus()
280 .prepare(windowsForegroundFocusTarget(window))
281 .catch(() => false);
282 });
283 }),
284 reveal: Effect.fn("ElectronWindow.reveal")(function (window) {
285 return Effect.tryPromise({
286 try: async () => {
287 if (window.isDestroyed()) {
288 return;
289 }
290
291 const captureReveal = platform === "win32" && captureRevealWindows.delete(window.id);
292 const shellHostedForeground =
293 captureReveal && (await isWindowsShellHostedForeground().catch(() => false));
294
295 if (window.isMinimized()) {
296 window.restore();
297 }
298
299 if (captureReveal) {
300 Electron.app.focus();
301 }
302
303 if (captureReveal || !window.isVisible()) {
304 window.show();
305 }
306
307 if (captureReveal) {
308 window.moveTop();
309 }
310
311 if (platform === "darwin") {
312 Electron.app.focus({ steal: true });
313 }
314
315 window.focus();
316
317 if (captureReveal) {
318 if (shellHostedForeground) {
319 await windowsForegroundFocus
320 ?.focus(windowsForegroundFocusTarget(window))
321 .catch(() => false);
322 }
323 try {
324 await activateWindowsForeground(window.getNativeWindowHandle());
325 } catch {
326 const needsFocus = !(await isWindowsBrowserWindowForeground(window));
327 if (needsFocus && !window.isDestroyed()) {
328 await windowsForegroundFocus
329 ?.focus(windowsForegroundFocusTarget(window))
330 .catch(() => false);
331 }
332 if (!window.isDestroyed()) {
333 await activateWindowsForeground(window.getNativeWindowHandle());
334 }
335 }
336 }
337 },
338 catch: (cause) =>
339 new ElectronWindowOperationError({
340 operation: "reveal-window",
341 platform,
342 windowId: window.id,
343 channel: null,
344 cause,
345 }),
346 }).pipe(Effect.orDie);
347 }),
348 sendAll:
349 /* Window broadcasts run for streamed updates; avoid a span per broadcast. */
350 Effect.fnUntraced(function* (channel, ...args) {
351 for (const window of yield* listWindows) {
352 if (yield* isWindowDestroyed(window)) {
353 continue;
354 }
355 yield* Effect.try({
356 try: () => window.webContents.send(channel, ...args),
357 catch: (cause) =>
358 new ElectronWindowOperationError({
359 operation: "send-window-message",
360 platform,
361 windowId: window.id,
362 channel,
363 cause,
364 }),
365 }).pipe(Effect.orDie);
366 }
367 }),
368 destroyAll: Effect.gen(function* () {
369 let firstFailure: Cause.Cause<never> | undefined;
370 for (const window of yield* listWindows) {
371 const exit = yield* Effect.exit(
372 Effect.try({
373 try: () => window.destroy(),
374 catch: (cause) =>
375 new ElectronWindowOperationError({
376 operation: "destroy-window",
377 platform,
378 windowId: window.id,
379 channel: null,
380 cause,
381 }),
382 }).pipe(Effect.orDie),
383 );
384 if (Exit.isFailure(exit)) {
385 firstFailure ??= exit.cause;
386 }
387 }
388 if (firstFailure !== undefined) {
389 return yield* Effect.failCause(firstFailure);
390 }
391 }),
392 syncAllAppearance: Effect.fn("desktop.electron.window.syncAllAppearance")(function* <E, R>(
393 sync: (
394 window: Electron.BrowserWindow,
395 appearance: { readonly titleBarOverlay: boolean },
396 ) => Effect.Effect<void, E, R>,
397 ) {
398 const windows = yield* listWindows;
399 for (const window of windows) {
400 if (yield* isWindowDestroyed(window)) {
401 continue;
402 }
403 yield* sync(window, { titleBarOverlay: titleBarOverlayWindows.has(window) });
404 }
405 }),
406 });
407 });
408
409 export const layer = Layer.effect(ElectronWindow, make);