@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 614 lines 24.2 KB
Raw
1 import {
2 ContextMenuItemSchema,
3 ContextMenuSource,
4 DesktopAppBrandingSchema,
5 DesktopEnvironmentBootstrapSchema,
6 DesktopMediaReadSchema,
7 DesktopThemeSchema,
8 EDITORS,
9 EditorId,
10 PickedThemeFileSchema,
11 PickFolderOptionsSchema,
12 PRIMARY_LOCAL_ENVIRONMENT_ID,
13 REMOTE_CAPABLE_EDITOR_IDS,
14 SystemSettingsPaneSchema,
15 type DesktopEnvironmentBootstrap,
16 type PickedThemeFile,
17 } from "@t3tools/contracts";
18 import { PROJECT_FAVICON_EXTENSIONS } from "@t3tools/shared/projectFavicon";
19 import { resolveEditorCommand } from "@t3tools/shared/editor";
20 import { withPathDirectoryListings } from "@t3tools/shared/shell";
21 import * as HostProcess from "@t3tools/shared/HostProcess";
22 import { isRelayTracingEnabled } from "@t3tools/shared/otelEnvironment";
23 import * as FileSystem from "effect/FileSystem";
24 import * as Path from "effect/Path";
25 import * as Effect from "effect/Effect";
26 import * as Option from "effect/Option";
27 import * as Schema from "effect/Schema";
28
29 import * as DesktopBackendConfiguration from "../../backend/DesktopBackendConfiguration.ts";
30 import * as DesktopBackendManager from "../../backend/DesktopBackendManager.ts";
31 import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts";
32 import * as DesktopLocalEnvironmentAuth from "../../backend/DesktopLocalEnvironmentAuth.ts";
33 import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts";
34 import * as DesktopManagedPolicy from "../../app/DesktopManagedPolicy.ts";
35 import * as DesktopPrimaryPaste from "../../app/DesktopPrimaryPaste.ts";
36 import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts";
37 import * as DesktopShellEnvironment from "../../shell/DesktopShellEnvironment.ts";
38 import * as DesktopWslBackend from "../../wsl/DesktopWslBackend.ts";
39 import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts";
40 import * as ElectronApp from "../../electron/ElectronApp.ts";
41 import * as ElectronAudio from "../../electron/ElectronAudio.ts";
42 import * as ElectronDialog from "../../electron/ElectronDialog.ts";
43 import * as ElectronMenu from "../../electron/ElectronMenu.ts";
44 import * as ElectronShell from "../../electron/ElectronShell.ts";
45 import * as ElectronTheme from "../../electron/ElectronTheme.ts";
46 import * as ElectronWindow from "../../electron/ElectronWindow.ts";
47 import * as Electron from "electron";
48 import { msg } from "gt-i18n";
49 import * as MacPermissions from "../../permissions/MacPermissions.ts";
50 import { safariPermissionCheck } from "../../preview/BrowserImport/SafariPermission.ts";
51 import { m } from "../../i18n/messages.ts";
52 import * as IpcChannels from "../channels.ts";
53 import * as DesktopIpc from "../DesktopIpc.ts";
54 import {
55 extractDistroFromUncPath,
56 resolveWslPickFolderDefaultPath,
57 wslUncPathToLinuxPath,
58 } from "../../wsl/wslPathParsing.ts";
59
60 const ContextMenuPosition = Schema.Struct({
61 x: Schema.Number,
62 y: Schema.Number,
63 });
64
65 const ContextMenuInput = Schema.Struct({
66 items: Schema.Array(ContextMenuItemSchema),
67 position: Schema.optionalKey(ContextMenuPosition),
68 source: Schema.optionalKey(ContextMenuSource),
69 });
70
71 function toWebSocketBaseUrl(httpBaseUrl: URL): string {
72 const url = new URL(httpBaseUrl.href);
73 url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
74 return url.href;
75 }
76
77 export const getAppBranding = DesktopIpc.makeSyncIpcMethod({
78 channel: IpcChannels.GET_APP_BRANDING_CHANNEL,
79 result: Schema.NullOr(DesktopAppBrandingSchema),
80 handler: Effect.fn("desktop.ipc.window.getAppBranding")(function* () {
81 const environment = yield* DesktopEnvironment.DesktopEnvironment;
82 return environment.branding;
83 }),
84 });
85
86 /**
87 * Relay traces leave the machine, so a policy with `telemetry: false`, or one that cannot be read,
88 * stops them. Read once here: a sync IPC handler cannot wait on the filesystem. Until the login
89 * shell's environment (which may opt out) is known, answer null so the renderer asks again.
90 */
91 export const installRelayTelemetryEnabled = Effect.fn("desktop.ipc.window.installRelayTelemetry")(
92 function* () {
93 const ipc = yield* DesktopIpc.DesktopIpc;
94 const env = yield* HostProcess.Environment;
95 const policyAllows = yield* (yield* DesktopManagedPolicy.DesktopManagedPolicy).read.pipe(
96 Effect.map((found) => found?.document.limits?.telemetry !== false),
97 Effect.orElseSucceed(() => false),
98 );
99 const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
100 yield* ipc.handleSync(
101 DesktopIpc.makeSyncIpcMethod({
102 channel: IpcChannels.GET_RELAY_TELEMETRY_ENABLED_CHANNEL,
103 result: Schema.NullOr(Schema.Boolean),
104 handler: () =>
105 shellEnvironment.discoveryFinished.pipe(
106 Effect.map((known) =>
107 !policyAllows || !isRelayTracingEnabled(env) ? false : known ? true : null,
108 ),
109 ),
110 }),
111 );
112 },
113 );
114
115 export const getSystemLocale = DesktopIpc.makeSyncIpcMethod({
116 channel: IpcChannels.GET_SYSTEM_LOCALE_CHANNEL,
117 result: Schema.String,
118 handler: Effect.fn("desktop.ipc.window.getSystemLocale")(function* () {
119 const electronApp = yield* ElectronApp.ElectronApp;
120 return yield* electronApp.systemLocale;
121 }),
122 });
123
124 export const getPrimaryPasteEnabled = DesktopIpc.makeSyncIpcMethod({
125 channel: IpcChannels.GET_PRIMARY_PASTE_ENABLED_CHANNEL,
126 result: Schema.Boolean,
127 handler: Effect.fn("desktop.ipc.window.getPrimaryPasteEnabled")(function* () {
128 const primaryPaste = yield* DesktopPrimaryPaste.DesktopPrimaryPaste;
129 return primaryPaste.enabled;
130 }),
131 });
132
133 export const getPreferredSystemLanguages = DesktopIpc.makeSyncIpcMethod({
134 channel: IpcChannels.GET_PREFERRED_SYSTEM_LANGUAGES_CHANNEL,
135 result: Schema.Array(Schema.String),
136 handler: Effect.fn("desktop.ipc.window.getPreferredSystemLanguages")(function* () {
137 const electronApp = yield* ElectronApp.ElectronApp;
138 return yield* electronApp.preferredSystemLanguages;
139 }),
140 });
141
142 export const getWindowFullscreenState = DesktopIpc.makeSyncIpcMethod({
143 channel: IpcChannels.GET_WINDOW_FULLSCREEN_STATE_CHANNEL,
144 result: Schema.Boolean,
145 handler: Effect.fn("desktop.ipc.window.getWindowFullscreenState")(function* () {
146 const electronWindow = yield* ElectronWindow.ElectronWindow;
147 const window = yield* electronWindow.currentMainOrFirst;
148 return Option.isSome(window) && window.value.isFullScreen();
149 }),
150 });
151
152 export const getLocalEnvironmentBootstraps = DesktopIpc.makeSyncIpcMethod({
153 channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL,
154 result: Schema.Array(DesktopEnvironmentBootstrapSchema),
155 handler: Effect.fn("desktop.ipc.window.getLocalEnvironmentBootstraps")(function* () {
156 const pool = yield* DesktopBackendPool.DesktopBackendPool;
157 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
158 const instances = yield* pool.list;
159 const bootstraps: DesktopEnvironmentBootstrap[] = [];
160 for (const instance of instances) {
161 const isPrimary = instance.id === PRIMARY_LOCAL_ENVIRONMENT_ID;
162 const config = yield* instance.currentConfig;
163 const snapshot = yield* instance.snapshot;
164 if (Option.isNone(config) || Option.isSome(config.value.preflightFailure)) {
165 const fatalPreflight =
166 Option.isSome(config) &&
167 Option.isSome(config.value.preflightFailure) &&
168 config.value.preflightFailure.value.fatal;
169 const stoppedPreflight =
170 Option.isSome(config) &&
171 Option.isSome(config.value.preflightFailure) &&
172 (!snapshot.desiredRunning || !snapshot.restartScheduled);
173 if (isPrimary || fatalPreflight || stoppedPreflight) continue;
174 bootstraps.push({
175 id: instance.id,
176 label: yield* instance.label,
177 runningDistro: null,
178 httpBaseUrl: null,
179 wsBaseUrl: null,
180 });
181 continue;
182 }
183 const { bootstrap, httpBaseUrl } = config.value;
184 const runningDistro = config.value.runningDistro ?? null;
185 bootstraps.push({
186 id: instance.id,
187 label: runningDistro === null ? yield* instance.label : `WSL (${runningDistro})`,
188 runningDistro,
189 httpBaseUrl: httpBaseUrl.href,
190 wsBaseUrl: toWebSocketBaseUrl(httpBaseUrl),
191 // Use the current window's derived token; the launch config's token may be stale.
192 ...(bootstrap.desktopBootstrapSecret
193 ? { bootstrapToken: yield* configuration.currentBootstrapToken }
194 : bootstrap.desktopBootstrapToken
195 ? { bootstrapToken: bootstrap.desktopBootstrapToken }
196 : {}),
197 });
198 }
199 return bootstraps;
200 }),
201 });
202
203 function extractWslDistroFromEnvironmentId(envId: string): string | null {
204 if (!envId.startsWith(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX)) {
205 return null;
206 }
207 const suffix = envId.slice(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX.length);
208 return suffix === "default" || suffix.length === 0 ? null : suffix;
209 }
210
211 export const getLocalEnvironmentBearerToken = DesktopIpc.makeIpcMethod({
212 channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL,
213 payload: Schema.Void,
214 result: Schema.String,
215 handler: Effect.fn("desktop.ipc.window.getLocalEnvironmentBearerToken")(function* () {
216 const localAuth = yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth;
217 return yield* localAuth.getBearerToken;
218 }),
219 });
220
221 // Ask the distro: its automount root is configurable, so /mnt/<drive> is only the default.
222 const windowsPathToWsl = Effect.fn("desktop.ipc.window.windowsPathToWsl")(function* (
223 distro: string | null,
224 windowsPath: string,
225 ) {
226 const linuxUncPath = wslUncPathToLinuxPath(windowsPath);
227 if (linuxUncPath !== null) return Option.some(linuxUncPath);
228 const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
229 return yield* wslEnvironment.windowsToWslPath(
230 extractDistroFromUncPath(windowsPath) ?? distro,
231 windowsPath,
232 );
233 });
234
235 export const pickFolder = DesktopIpc.makeIpcMethod({
236 channel: IpcChannels.PICK_FOLDER_CHANNEL,
237 payload: Schema.UndefinedOr(PickFolderOptionsSchema),
238 result: Schema.NullOr(Schema.String),
239 handler: Effect.fn("desktop.ipc.window.pickFolder")(function* (options) {
240 const dialog = yield* ElectronDialog.ElectronDialog;
241 const electronWindow = yield* ElectronWindow.ElectronWindow;
242 const environment = yield* DesktopEnvironment.DesktopEnvironment;
243 const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
244 const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
245 const settings = yield* appSettings.get;
246 // A picked path only means something to a backend on this machine.
247 if (!settings.localEnvironmentEnabled) {
248 return null;
249 }
250 const targetId = options?.targetEnvironmentId;
251 const wslDistroFromTarget =
252 targetId !== undefined && targetId.startsWith(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX)
253 ? extractWslDistroFromEnvironmentId(targetId)
254 : null;
255 const useWsl =
256 targetId !== undefined &&
257 targetId !== PRIMARY_LOCAL_ENVIRONMENT_ID &&
258 targetId.startsWith(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX);
259 // Match the orchestrator's persisted distro fallback for wsl:default.
260 const wslDistro = useWsl ? (wslDistroFromTarget ?? settings.wslDistro) : null;
261 const defaultPath = useWsl
262 ? Option.fromNullishOr(
263 resolveWslPickFolderDefaultPath(
264 options,
265 { distro: wslDistro },
266 yield* wslEnvironment.listDistros,
267 Option.getOrNull(yield* wslEnvironment.getUserHome(wslDistro)),
268 ),
269 )
270 : environment.resolvePickFolderDefaultPath(options);
271 const selectedPath = yield* dialog.pickFolder({
272 owner: yield* electronWindow.focusedMainOrFirst,
273 defaultPath,
274 });
275 if (Option.isNone(selectedPath)) {
276 return null;
277 }
278 if (!useWsl) {
279 return selectedPath.value;
280 }
281 const converted = yield* windowsPathToWsl(wslDistro, selectedPath.value);
282 return Option.getOrElse(converted, () => selectedPath.value);
283 }),
284 });
285
286 export const toLocalBackendPath = DesktopIpc.makeIpcMethod({
287 channel: IpcChannels.TO_LOCAL_BACKEND_PATH_CHANNEL,
288 payload: Schema.Struct({ backendId: Schema.String, path: Schema.String }),
289 result: Schema.NullOr(Schema.String),
290 handler: Effect.fn("desktop.ipc.window.toLocalBackendPath")(function* ({ backendId, path }) {
291 const pool = yield* DesktopBackendPool.DesktopBackendPool;
292 const instance = yield* pool.get(DesktopBackendManager.BackendInstanceId(backendId));
293 if (Option.isNone(instance)) return null;
294 const config = yield* instance.value.currentConfig;
295 if (Option.isNone(config) || Option.isSome(config.value.preflightFailure)) return null;
296 const { runningDistro } = config.value;
297 if (runningDistro === undefined) return path;
298 const uncDistro = extractDistroFromUncPath(path);
299 if (uncDistro !== null && uncDistro.toLowerCase() !== runningDistro.toLowerCase()) return null;
300 return Option.getOrNull(yield* windowsPathToWsl(runningDistro, path));
301 }),
302 });
303
304 export const pickProjectFavicon = DesktopIpc.makeIpcMethod({
305 channel: IpcChannels.PICK_PROJECT_FAVICON_CHANNEL,
306 payload: Schema.UndefinedOr(Schema.String),
307 result: Schema.NullOr(Schema.String),
308 handler: Effect.fn("desktop.ipc.window.pickProjectFavicon")(function* (initialPath) {
309 const dialog = yield* ElectronDialog.ElectronDialog;
310 const electronWindow = yield* ElectronWindow.ElectronWindow;
311 const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
312 if (!(yield* appSettings.get).localEnvironmentEnabled) {
313 return null;
314 }
315 const paths = yield* dialog.pickFiles({
316 owner: yield* electronWindow.focusedMainOrFirst,
317 defaultPath: Option.fromNullishOr(initialPath),
318 multiple: false,
319 filters: [
320 {
321 name: m(msg("Images")),
322 extensions: PROJECT_FAVICON_EXTENSIONS.map((extension) => extension.slice(1)),
323 },
324 ],
325 });
326 return paths[0] ?? null;
327 }),
328 });
329
330 export const setTheme = DesktopIpc.makeIpcMethod({
331 channel: IpcChannels.SET_THEME_CHANNEL,
332 payload: DesktopThemeSchema,
333 result: Schema.Void,
334 handler: Effect.fn("desktop.ipc.window.setTheme")(function* (theme) {
335 const electronTheme = yield* ElectronTheme.ElectronTheme;
336 yield* electronTheme.setSource(theme);
337 }),
338 });
339
340 export const showContextMenu = DesktopIpc.makeIpcMethod({
341 channel: IpcChannels.CONTEXT_MENU_CHANNEL,
342 payload: ContextMenuInput,
343 result: Schema.NullOr(Schema.String),
344 handler: Effect.fn("desktop.ipc.window.showContextMenu")(function* (input) {
345 const electronMenu = yield* ElectronMenu.ElectronMenu;
346 const electronWindow = yield* ElectronWindow.ElectronWindow;
347 const window = yield* electronWindow.focusedMainOrFirst;
348 if (Option.isNone(window)) {
349 return null;
350 }
351
352 const selectedItemId = yield* electronMenu.showContextMenu({
353 window: window.value,
354 items: input.items,
355 position: Option.fromNullishOr(input.position),
356 source: Option.fromNullishOr(input.source),
357 });
358 return Option.getOrNull(selectedItemId);
359 }),
360 });
361
362 export const openExternal = DesktopIpc.makeIpcMethod({
363 channel: IpcChannels.OPEN_EXTERNAL_CHANNEL,
364 payload: Schema.String,
365 result: Schema.Boolean,
366 handler: Effect.fn("desktop.ipc.window.openExternal")(function* (url) {
367 const shell = yield* ElectronShell.ElectronShell;
368 return yield* shell.openExternal(url);
369 }),
370 });
371
372 const READ_MEDIA_MAX_BYTES = 256 * 1024 * 1024;
373
374 // No URL field: media URLs can carry signed query tokens.
375 class MediaReadError extends Schema.TaggedError<MediaReadError>()("MediaReadError", {
376 message: Schema.String,
377 cause: Schema.Defect(),
378 }) {}
379
380 // The renderer can display media it cannot fetch(); reading here keeps Save and Copy working for it.
381 export const readMedia = DesktopIpc.makeIpcMethod({
382 channel: IpcChannels.READ_MEDIA_CHANNEL,
383 payload: Schema.String,
384 result: Schema.NullOr(DesktopMediaReadSchema),
385 handler: Effect.fn("desktop.ipc.window.readMedia")(function* (url, event) {
386 const window = yield* (yield* ElectronWindow.ElectronWindow).main;
387 if (
388 event === undefined ||
389 Option.isNone(window) ||
390 window.value.webContents.id !== event.sender.id ||
391 !/^https?:$/.test(URL.parse(url)?.protocol ?? "")
392 ) {
393 return null;
394 }
395 const session = window.value.webContents.session;
396 return yield* Effect.tryPromise({
397 try: async () => {
398 // Like an <img>, send the session's cookies.
399 const response = await session.fetch(url, { credentials: "include" });
400 const mimeType = response.headers.get("content-type") ?? "";
401 if (!response.ok || !response.body) {
402 await response.body?.cancel();
403 return { status: response.status, mimeType, data: new Uint8Array() };
404 }
405 // The whole body crosses IPC, so stop before a huge file can exhaust main-process memory.
406 const chunks: Uint8Array[] = [];
407 let size = 0;
408 for await (const chunk of response.body) {
409 size += chunk.byteLength;
410 if (size > READ_MEDIA_MAX_BYTES) {
411 return { status: 413, mimeType, data: new Uint8Array() };
412 }
413 chunks.push(chunk);
414 }
415 return { status: response.status, mimeType, data: Buffer.concat(chunks) };
416 },
417 catch: (cause) => new MediaReadError({ message: "Could not read media.", cause }),
418 }).pipe(Effect.orElseSucceed(() => null));
419 }),
420 });
421
422 export const openSystemSettings = DesktopIpc.makeIpcMethod({
423 channel: IpcChannels.OPEN_SYSTEM_SETTINGS_CHANNEL,
424 payload: SystemSettingsPaneSchema,
425 result: Schema.Boolean,
426 handler: Effect.fn("desktop.ipc.window.openSystemSettings")(function* (pane) {
427 const shell = yield* ElectronShell.ElectronShell;
428 const environment = yield* DesktopEnvironment.DesktopEnvironment;
429 if (environment.platform !== "darwin") return false;
430 const owner = Electron.BrowserWindow.getFocusedWindow();
431 const opened = yield* shell.openSystemSettings(pane);
432 if (opened && environment.isPackaged) {
433 const permissions = yield* MacPermissions.MacPermissions;
434 const isGranted = yield* safariPermissionCheck;
435 yield* permissions.showHelper(pane, owner, isGranted);
436 }
437 return opened;
438 }),
439 });
440
441 const REMOTE_EDITOR_PROBE_CONCURRENCY = 8;
442
443 export const probeRemoteEditors = DesktopIpc.makeIpcMethod({
444 channel: IpcChannels.PROBE_REMOTE_EDITORS_CHANNEL,
445 payload: Schema.Undefined,
446 result: Schema.Array(EditorId),
447 handler: Effect.fn("desktop.ipc.window.probeRemoteEditors")(function* () {
448 const env = yield* HostProcess.Environment;
449 // Shared listings stop each editor re-stating every PATH entry x PATHEXT candidate on Windows.
450 const resolved = yield* Effect.forEach(
451 REMOTE_CAPABLE_EDITOR_IDS,
452 (editorId) => {
453 const editor = EDITORS.find((editor) => editor.id === editorId);
454 return editor
455 ? resolveEditorCommand(editor, env).pipe(Effect.map(Option.isSome))
456 : Effect.succeed(false);
457 },
458 { concurrency: REMOTE_EDITOR_PROBE_CONCURRENCY },
459 ).pipe(withPathDirectoryListings);
460 return REMOTE_CAPABLE_EDITOR_IDS.filter((_, index) => resolved[index]);
461 }),
462 });
463
464 export const pasteAsText = DesktopIpc.makeIpcMethod({
465 channel: IpcChannels.PASTE_AS_TEXT_CHANNEL,
466 payload: Schema.Undefined,
467 result: Schema.Void,
468 handler: Effect.fn("desktop.ipc.window.pasteAsText")(function* (_input, event) {
469 const electronWindow = yield* ElectronWindow.ElectronWindow;
470 const window = yield* electronWindow.main;
471 if (
472 event === undefined ||
473 Option.isNone(window) ||
474 window.value.isDestroyed() ||
475 window.value.webContents.id !== event.sender.id
476 ) {
477 return;
478 }
479 const focused = Electron.webContents.getFocusedWebContents();
480 if (
481 focused &&
482 !focused.isDestroyed() &&
483 Electron.BrowserWindow.fromWebContents(focused) === window.value
484 ) {
485 focused.paste();
486 }
487 }),
488 });
489
490 export const revealWindow = DesktopIpc.makeIpcMethod({
491 channel: IpcChannels.REVEAL_WINDOW_CHANNEL,
492 payload: Schema.Undefined,
493 result: Schema.Void,
494 handler: Effect.fn("desktop.ipc.window.revealWindow")(function* (_input, event) {
495 const electronWindow = yield* ElectronWindow.ElectronWindow;
496 const window = yield* electronWindow.main;
497 if (
498 event === undefined ||
499 Option.isNone(window) ||
500 window.value.webContents.id !== event.sender.id
501 ) {
502 return;
503 }
504 yield* electronWindow.reveal(window.value);
505 }),
506 });
507
508 const htmlFullscreenStates = new WeakMap<
509 Electron.BrowserWindow,
510 { owned: boolean; leaving: boolean }
511 >();
512
513 const htmlFullscreenState = (window: Electron.BrowserWindow) => {
514 const existing = htmlFullscreenStates.get(window);
515 if (existing !== undefined) return existing;
516 const state = { owned: false, leaving: false };
517 window.on("leave-full-screen", () => {
518 // Leaving OS fullscreen any other way, such as F11, hands the window back to the user.
519 if (!state.leaving) state.owned = false;
520 state.leaving = false;
521 });
522 htmlFullscreenStates.set(window, state);
523 return state;
524 };
525
526 // The main window keeps HTML fullscreen inside itself so preview guests stay in their webview,
527 // so the app's own fullscreen elements, such as chat videos, take the screen here.
528 export const syncHtmlFullscreen = DesktopIpc.makeIpcMethod({
529 channel: IpcChannels.SYNC_HTML_FULLSCREEN_CHANNEL,
530 payload: Schema.Boolean,
531 result: Schema.Void,
532 handler: Effect.fn("desktop.ipc.window.syncHtmlFullscreen")(function* (fullscreen, event) {
533 const electronWindow = yield* ElectronWindow.ElectronWindow;
534 const main = yield* electronWindow.main;
535 if (
536 event === undefined ||
537 Option.isNone(main) ||
538 main.value.isDestroyed() ||
539 main.value.webContents.id !== event.sender.id
540 ) {
541 return;
542 }
543 const window = main.value;
544 const state = htmlFullscreenState(window);
545 if (fullscreen) {
546 // macOS reports fullscreen until its exit animation ends, and Electron queues the re-entry.
547 if (state.owned || (window.isFullScreen() && !state.leaving)) return;
548 state.owned = true;
549 window.setFullScreen(true);
550 } else if (state.owned) {
551 state.owned = false;
552 state.leaving = window.isFullScreen();
553 window.setFullScreen(false);
554 }
555 }),
556 });
557
558 const PICKED_THEME_FILE_MAX_BYTES = 256 * 1024;
559
560 export const pickThemeFiles = DesktopIpc.makeIpcMethod({
561 channel: IpcChannels.PICK_THEME_FILES_CHANNEL,
562 payload: Schema.Undefined,
563 result: Schema.NullOr(Schema.Array(PickedThemeFileSchema)),
564 handler: Effect.fn("desktop.ipc.window.pickThemeFiles")(function* () {
565 const dialog = yield* ElectronDialog.ElectronDialog;
566 const electronWindow = yield* ElectronWindow.ElectronWindow;
567 const fileSystem = yield* FileSystem.FileSystem;
568 const path = yield* Path.Path;
569 const extensionsDir = path.join(yield* HostProcess.HomeDirectory, ".vscode", "extensions");
570 const defaultPath = yield* fileSystem
571 .exists(extensionsDir)
572 .pipe(Effect.orElseSucceed(() => false));
573 const paths = yield* dialog.pickFiles({
574 owner: yield* electronWindow.focusedMainOrFirst,
575 defaultPath: defaultPath ? Option.some(extensionsDir) : Option.none(),
576 filters: [{ name: "JSON", extensions: ["json"] }],
577 multiple: true,
578 });
579 if (paths.length === 0) {
580 return null;
581 }
582 return yield* Effect.forEach(paths, (filePath) => {
583 const name = path.basename(filePath);
584 return Effect.gen(function* () {
585 const info = yield* fileSystem.stat(filePath);
586 const size = Number(info.size);
587 if (size > PICKED_THEME_FILE_MAX_BYTES) {
588 return { name, size, text: "" } satisfies PickedThemeFile;
589 }
590 const text = yield* fileSystem.readFileString(filePath);
591 return { name, size, text } satisfies PickedThemeFile;
592 }).pipe(Effect.orElseSucceed((): PickedThemeFile => ({ name, size: 0, text: "" })));
593 });
594 }),
595 });
596
597 export const checkSystemPermission = DesktopIpc.makeIpcMethod({
598 channel: IpcChannels.CHECK_SYSTEM_PERMISSION_CHANNEL,
599 payload: SystemSettingsPaneSchema,
600 result: Schema.Boolean,
601 handler: Effect.fn("desktop.ipc.window.checkSystemPermission")(function* () {
602 const environment = yield* DesktopEnvironment.DesktopEnvironment;
603 if (environment.platform !== "darwin") return false;
604 const check = yield* safariPermissionCheck;
605 return yield* Effect.promise(check);
606 }),
607 });
608
609 export const restartAudioService = DesktopIpc.makeIpcMethod({
610 channel: IpcChannels.RESTART_AUDIO_SERVICE_CHANNEL,
611 payload: Schema.Void,
612 result: Schema.Boolean,
613 handler: ElectronAudio.restart,
614 });