Open History to see the last commit
1import {
2 ContextMenuItemSchema,
3 DesktopAppBrandingSchema,
4 DesktopEnvironmentBootstrapSchema,
5 DesktopMediaReadSchema,
6 DesktopThemeSchema,
7 EDITORS,
8 EditorId,
9 PickedThemeFileSchema,
10 PickFolderOptionsSchema,
11 PRIMARY_LOCAL_ENVIRONMENT_ID,
12 REMOTE_CAPABLE_EDITOR_IDS,
13 SystemSettingsPaneSchema,
14 type DesktopEnvironmentBootstrap,
15 type PickedThemeFile,
16} from "@t3tools/contracts";
17import { PROJECT_FAVICON_EXTENSIONS } from "@t3tools/shared/projectFavicon";
18import { resolveEditorCommand } from "@t3tools/shared/editor";
19import * as HostProcess from "@t3tools/shared/HostProcess";
20import { isRelayTracingEnabled } from "@t3tools/shared/otelEnvironment";
21import * as FileSystem from "effect/FileSystem";
22import * as Path from "effect/Path";
23import * as Effect from "effect/Effect";
24import * as Option from "effect/Option";
25import * as Schema from "effect/Schema";
26
27import * as DesktopBackendConfiguration from "../../backend/DesktopBackendConfiguration.ts";
28import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts";
29import * as DesktopLocalEnvironmentAuth from "../../backend/DesktopLocalEnvironmentAuth.ts";
30import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts";
31import * as DesktopManagedPolicy from "../../app/DesktopManagedPolicy.ts";
32import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts";
33import * as DesktopWslBackend from "../../wsl/DesktopWslBackend.ts";
34import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts";
35import * as ElectronApp from "../../electron/ElectronApp.ts";
36import * as ElectronDialog from "../../electron/ElectronDialog.ts";
37import * as ElectronMenu from "../../electron/ElectronMenu.ts";
38import * as ElectronShell from "../../electron/ElectronShell.ts";
39import * as ElectronTheme from "../../electron/ElectronTheme.ts";
40import * as ElectronWindow from "../../electron/ElectronWindow.ts";
41import * as Electron from "electron";
42import * as MacPermissions from "../../permissions/MacPermissions.ts";
43import { safariPermissionCheck } from "../../preview/BrowserImport/SafariPermission.ts";
44import * as IpcChannels from "../channels.ts";
45import * as DesktopIpc from "../DesktopIpc.ts";
46import {
47 extractDistroFromUncPath,
48 resolveWslPickFolderDefaultPath,
49 wslUncPathToLinuxPath,
50} from "../../wsl/wslPathParsing.ts";
51
52const ContextMenuPosition = Schema.Struct({
53 x: Schema.Number,
54 y: Schema.Number,
55});
56
57const ContextMenuInput = Schema.Struct({
58 items: Schema.Array(ContextMenuItemSchema),
59 position: Schema.optionalKey(ContextMenuPosition),
60});
61
62function toWebSocketBaseUrl(httpBaseUrl: URL): string {
63 const url = new URL(httpBaseUrl.href);
64 url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
65 return url.href;
66}
67
68export const getAppBranding = DesktopIpc.makeSyncIpcMethod({
69 channel: IpcChannels.GET_APP_BRANDING_CHANNEL,
70 result: Schema.NullOr(DesktopAppBrandingSchema),
71 handler: Effect.fn("desktop.ipc.window.getAppBranding")(function* () {
72 const environment = yield* DesktopEnvironment.DesktopEnvironment;
73 return environment.branding;
74 }),
75});
76
77/**
78 * Relay traces leave the machine, so a policy with `telemetry: false`, or one that cannot be read,
79 * stops them. Read once here: a sync IPC handler cannot wait on the filesystem.
80 */
81export const installRelayTelemetryEnabled = Effect.fn("desktop.ipc.window.installRelayTelemetry")(
82 function* () {
83 const ipc = yield* DesktopIpc.DesktopIpc;
84 const enabled =
85 isRelayTracingEnabled(yield* HostProcess.Environment) &&
86 (yield* (yield* DesktopManagedPolicy.DesktopManagedPolicy).read.pipe(
87 Effect.map((found) => found?.document.limits?.telemetry !== false),
88 Effect.orElseSucceed(() => false),
89 ));
90 yield* ipc.handleSync(
91 DesktopIpc.makeSyncIpcMethod({
92 channel: IpcChannels.GET_RELAY_TELEMETRY_ENABLED_CHANNEL,
93 result: Schema.Boolean,
94 handler: () => Effect.succeed(enabled),
95 }),
96 );
97 },
98);
99
100export const getSystemLocale = DesktopIpc.makeSyncIpcMethod({
101 channel: IpcChannels.GET_SYSTEM_LOCALE_CHANNEL,
102 result: Schema.String,
103 handler: Effect.fn("desktop.ipc.window.getSystemLocale")(function* () {
104 const electronApp = yield* ElectronApp.ElectronApp;
105 return yield* electronApp.systemLocale;
106 }),
107});
108
109export const getWindowFullscreenState = DesktopIpc.makeSyncIpcMethod({
110 channel: IpcChannels.GET_WINDOW_FULLSCREEN_STATE_CHANNEL,
111 result: Schema.Boolean,
112 handler: Effect.fn("desktop.ipc.window.getWindowFullscreenState")(function* () {
113 const electronWindow = yield* ElectronWindow.ElectronWindow;
114 const window = yield* electronWindow.currentMainOrFirst;
115 return Option.isSome(window) && window.value.isFullScreen();
116 }),
117});
118
119export const getLocalEnvironmentBootstraps = DesktopIpc.makeSyncIpcMethod({
120 channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL,
121 result: Schema.Array(DesktopEnvironmentBootstrapSchema),
122 handler: Effect.fn("desktop.ipc.window.getLocalEnvironmentBootstraps")(function* () {
123 const pool = yield* DesktopBackendPool.DesktopBackendPool;
124 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
125 const instances = yield* pool.list;
126 const bootstraps: DesktopEnvironmentBootstrap[] = [];
127 for (const instance of instances) {
128 const isPrimary = instance.id === PRIMARY_LOCAL_ENVIRONMENT_ID;
129 const config = yield* instance.currentConfig;
130 const snapshot = yield* instance.snapshot;
131 if (Option.isNone(config) || Option.isSome(config.value.preflightFailure)) {
132 const fatalPreflight =
133 Option.isSome(config) &&
134 Option.isSome(config.value.preflightFailure) &&
135 config.value.preflightFailure.value.fatal;
136 const stoppedPreflight =
137 Option.isSome(config) &&
138 Option.isSome(config.value.preflightFailure) &&
139 (!snapshot.desiredRunning || !snapshot.restartScheduled);
140 if (isPrimary || fatalPreflight || stoppedPreflight) continue;
141 bootstraps.push({
142 id: instance.id,
143 label: yield* instance.label,
144 runningDistro: null,
145 httpBaseUrl: null,
146 wsBaseUrl: null,
147 });
148 continue;
149 }
150 const { bootstrap, httpBaseUrl } = config.value;
151 const runningDistro = config.value.runningDistro ?? null;
152 bootstraps.push({
153 id: instance.id,
154 label: runningDistro === null ? yield* instance.label : `WSL (${runningDistro})`,
155 runningDistro,
156 httpBaseUrl: httpBaseUrl.href,
157 wsBaseUrl: toWebSocketBaseUrl(httpBaseUrl),
158 // Use the current window's derived token; the launch config's token may be stale.
159 ...(bootstrap.desktopBootstrapSecret
160 ? { bootstrapToken: yield* configuration.currentBootstrapToken }
161 : bootstrap.desktopBootstrapToken
162 ? { bootstrapToken: bootstrap.desktopBootstrapToken }
163 : {}),
164 });
165 }
166 return bootstraps;
167 }),
168});
169
170function extractWslDistroFromEnvironmentId(envId: string): string | null {
171 if (!envId.startsWith(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX)) {
172 return null;
173 }
174 const suffix = envId.slice(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX.length);
175 return suffix === "default" || suffix.length === 0 ? null : suffix;
176}
177
178export const getLocalEnvironmentBearerToken = DesktopIpc.makeIpcMethod({
179 channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL,
180 payload: Schema.Void,
181 result: Schema.String,
182 handler: Effect.fn("desktop.ipc.window.getLocalEnvironmentBearerToken")(function* () {
183 const localAuth = yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth;
184 return yield* localAuth.getBearerToken;
185 }),
186});
187
188export const pickFolder = DesktopIpc.makeIpcMethod({
189 channel: IpcChannels.PICK_FOLDER_CHANNEL,
190 payload: Schema.UndefinedOr(PickFolderOptionsSchema),
191 result: Schema.NullOr(Schema.String),
192 handler: Effect.fn("desktop.ipc.window.pickFolder")(function* (options) {
193 const dialog = yield* ElectronDialog.ElectronDialog;
194 const electronWindow = yield* ElectronWindow.ElectronWindow;
195 const environment = yield* DesktopEnvironment.DesktopEnvironment;
196 const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
197 const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
198 const settings = yield* appSettings.get;
199 // A picked path only means something to a backend on this machine.
200 if (!settings.localEnvironmentEnabled) {
201 return null;
202 }
203 const targetId = options?.targetEnvironmentId;
204 const wslDistroFromTarget =
205 targetId !== undefined && targetId.startsWith(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX)
206 ? extractWslDistroFromEnvironmentId(targetId)
207 : null;
208 const useWsl =
209 targetId !== undefined &&
210 targetId !== PRIMARY_LOCAL_ENVIRONMENT_ID &&
211 targetId.startsWith(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX);
212 // Match the orchestrator's persisted distro fallback for wsl:default.
213 const wslDistro = useWsl ? (wslDistroFromTarget ?? settings.wslDistro) : null;
214 const defaultPath = useWsl
215 ? Option.fromNullishOr(
216 resolveWslPickFolderDefaultPath(
217 options,
218 { distro: wslDistro },
219 yield* wslEnvironment.listDistros,
220 Option.getOrNull(yield* wslEnvironment.getUserHome(wslDistro)),
221 ),
222 )
223 : environment.resolvePickFolderDefaultPath(options);
224 const selectedPath = yield* dialog.pickFolder({
225 owner: yield* electronWindow.focusedMainOrFirst,
226 defaultPath,
227 });
228 if (Option.isNone(selectedPath)) {
229 return null;
230 }
231 if (!useWsl) {
232 return selectedPath.value;
233 }
234
235 const linuxUncPath = wslUncPathToLinuxPath(selectedPath.value);
236 if (linuxUncPath !== null) {
237 return linuxUncPath;
238 }
239
240 const converted = yield* wslEnvironment.windowsToWslPath(
241 extractDistroFromUncPath(selectedPath.value) ?? wslDistro,
242 selectedPath.value,
243 );
244 return Option.getOrElse(converted, () => selectedPath.value);
245 }),
246});
247
248export const pickProjectFavicon = DesktopIpc.makeIpcMethod({
249 channel: IpcChannels.PICK_PROJECT_FAVICON_CHANNEL,
250 payload: Schema.UndefinedOr(Schema.String),
251 result: Schema.NullOr(Schema.String),
252 handler: Effect.fn("desktop.ipc.window.pickProjectFavicon")(function* (initialPath) {
253 const dialog = yield* ElectronDialog.ElectronDialog;
254 const electronWindow = yield* ElectronWindow.ElectronWindow;
255 const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
256 if (!(yield* appSettings.get).localEnvironmentEnabled) {
257 return null;
258 }
259 const paths = yield* dialog.pickFiles({
260 owner: yield* electronWindow.focusedMainOrFirst,
261 defaultPath: Option.fromNullishOr(initialPath),
262 multiple: false,
263 filters: [
264 {
265 name: "Images",
266 extensions: PROJECT_FAVICON_EXTENSIONS.map((extension) => extension.slice(1)),
267 },
268 ],
269 });
270 return paths[0] ?? null;
271 }),
272});
273
274export const setTheme = DesktopIpc.makeIpcMethod({
275 channel: IpcChannels.SET_THEME_CHANNEL,
276 payload: DesktopThemeSchema,
277 result: Schema.Void,
278 handler: Effect.fn("desktop.ipc.window.setTheme")(function* (theme) {
279 const electronTheme = yield* ElectronTheme.ElectronTheme;
280 yield* electronTheme.setSource(theme);
281 }),
282});
283
284export const showContextMenu = DesktopIpc.makeIpcMethod({
285 channel: IpcChannels.CONTEXT_MENU_CHANNEL,
286 payload: ContextMenuInput,
287 result: Schema.NullOr(Schema.String),
288 handler: Effect.fn("desktop.ipc.window.showContextMenu")(function* (input) {
289 const electronMenu = yield* ElectronMenu.ElectronMenu;
290 const electronWindow = yield* ElectronWindow.ElectronWindow;
291 const window = yield* electronWindow.focusedMainOrFirst;
292 if (Option.isNone(window)) {
293 return null;
294 }
295
296 const selectedItemId = yield* electronMenu.showContextMenu({
297 window: window.value,
298 items: input.items,
299 position: Option.fromNullishOr(input.position),
300 });
301 return Option.getOrNull(selectedItemId);
302 }),
303});
304
305export const openExternal = DesktopIpc.makeIpcMethod({
306 channel: IpcChannels.OPEN_EXTERNAL_CHANNEL,
307 payload: Schema.String,
308 result: Schema.Boolean,
309 handler: Effect.fn("desktop.ipc.window.openExternal")(function* (url) {
310 const shell = yield* ElectronShell.ElectronShell;
311 return yield* shell.openExternal(url);
312 }),
313});
314
315const READ_MEDIA_MAX_BYTES = 256 * 1024 * 1024;
316
317// No URL field: media URLs can carry signed query tokens.
318class MediaReadError extends Schema.TaggedError<MediaReadError>()("MediaReadError", {
319 message: Schema.String,
320 cause: Schema.Defect(),
321}) {}
322
323// The renderer can display media it cannot fetch(); reading here keeps Save and Copy working for it.
324export const readMedia = DesktopIpc.makeIpcMethod({
325 channel: IpcChannels.READ_MEDIA_CHANNEL,
326 payload: Schema.String,
327 result: Schema.NullOr(DesktopMediaReadSchema),
328 handler: Effect.fn("desktop.ipc.window.readMedia")(function* (url, event) {
329 const window = yield* (yield* ElectronWindow.ElectronWindow).main;
330 if (
331 event === undefined ||
332 Option.isNone(window) ||
333 window.value.webContents.id !== event.sender.id ||
334 !/^https?:$/.test(URL.parse(url)?.protocol ?? "")
335 ) {
336 return null;
337 }
338 const session = window.value.webContents.session;
339 return yield* Effect.tryPromise({
340 try: async () => {
341 // Like an <img>, send the session's cookies.
342 const response = await session.fetch(url, { credentials: "include" });
343 const mimeType = response.headers.get("content-type") ?? "";
344 if (!response.ok || !response.body) {
345 await response.body?.cancel();
346 return { status: response.status, mimeType, data: new Uint8Array() };
347 }
348 // The whole body crosses IPC, so stop before a huge file can exhaust main-process memory.
349 const chunks: Uint8Array[] = [];
350 let size = 0;
351 for await (const chunk of response.body) {
352 size += chunk.byteLength;
353 if (size > READ_MEDIA_MAX_BYTES) {
354 return { status: 413, mimeType, data: new Uint8Array() };
355 }
356 chunks.push(chunk);
357 }
358 return { status: response.status, mimeType, data: Buffer.concat(chunks) };
359 },
360 catch: (cause) => new MediaReadError({ message: "Could not read media.", cause }),
361 }).pipe(Effect.orElseSucceed(() => null));
362 }),
363});
364
365export const openSystemSettings = DesktopIpc.makeIpcMethod({
366 channel: IpcChannels.OPEN_SYSTEM_SETTINGS_CHANNEL,
367 payload: SystemSettingsPaneSchema,
368 result: Schema.Boolean,
369 handler: Effect.fn("desktop.ipc.window.openSystemSettings")(function* (pane) {
370 const shell = yield* ElectronShell.ElectronShell;
371 const environment = yield* DesktopEnvironment.DesktopEnvironment;
372 if (environment.platform !== "darwin") return false;
373 const owner = Electron.BrowserWindow.getFocusedWindow();
374 const opened = yield* shell.openSystemSettings(pane);
375 if (opened && environment.isPackaged) {
376 const permissions = yield* MacPermissions.MacPermissions;
377 const isGranted = yield* safariPermissionCheck;
378 yield* permissions.showHelper(pane, owner, isGranted);
379 }
380 return opened;
381 }),
382});
383
384export const probeRemoteEditors = DesktopIpc.makeIpcMethod({
385 channel: IpcChannels.PROBE_REMOTE_EDITORS_CHANNEL,
386 payload: Schema.Undefined,
387 result: Schema.Array(EditorId),
388 handler: Effect.fn("desktop.ipc.window.probeRemoteEditors")(function* () {
389 const available: Array<EditorId> = [];
390 const env = yield* HostProcess.Environment;
391 for (const editorId of REMOTE_CAPABLE_EDITOR_IDS) {
392 const editor = EDITORS.find((editor) => editor.id === editorId);
393 if (editor && Option.isSome(yield* resolveEditorCommand(editor, env))) {
394 available.push(editorId);
395 }
396 }
397 return available;
398 }),
399});
400
401export const pasteAsText = DesktopIpc.makeIpcMethod({
402 channel: IpcChannels.PASTE_AS_TEXT_CHANNEL,
403 payload: Schema.Undefined,
404 result: Schema.Void,
405 handler: Effect.fn("desktop.ipc.window.pasteAsText")(function* (_input, event) {
406 const electronWindow = yield* ElectronWindow.ElectronWindow;
407 const window = yield* electronWindow.main;
408 if (
409 event === undefined ||
410 Option.isNone(window) ||
411 window.value.isDestroyed() ||
412 window.value.webContents.id !== event.sender.id
413 ) {
414 return;
415 }
416 const focused = Electron.webContents.getFocusedWebContents();
417 if (
418 focused &&
419 !focused.isDestroyed() &&
420 Electron.BrowserWindow.fromWebContents(focused) === window.value
421 ) {
422 focused.paste();
423 }
424 }),
425});
426
427export const revealWindow = DesktopIpc.makeIpcMethod({
428 channel: IpcChannels.REVEAL_WINDOW_CHANNEL,
429 payload: Schema.Undefined,
430 result: Schema.Void,
431 handler: Effect.fn("desktop.ipc.window.revealWindow")(function* (_input, event) {
432 const electronWindow = yield* ElectronWindow.ElectronWindow;
433 const window = yield* electronWindow.main;
434 if (
435 event === undefined ||
436 Option.isNone(window) ||
437 window.value.webContents.id !== event.sender.id
438 ) {
439 return;
440 }
441 yield* electronWindow.reveal(window.value);
442 }),
443});
444
445const PICKED_THEME_FILE_MAX_BYTES = 256 * 1024;
446
447export const pickThemeFiles = DesktopIpc.makeIpcMethod({
448 channel: IpcChannels.PICK_THEME_FILES_CHANNEL,
449 payload: Schema.Undefined,
450 result: Schema.NullOr(Schema.Array(PickedThemeFileSchema)),
451 handler: Effect.fn("desktop.ipc.window.pickThemeFiles")(function* () {
452 const dialog = yield* ElectronDialog.ElectronDialog;
453 const electronWindow = yield* ElectronWindow.ElectronWindow;
454 const fileSystem = yield* FileSystem.FileSystem;
455 const path = yield* Path.Path;
456 const extensionsDir = path.join(yield* HostProcess.HomeDirectory, ".vscode", "extensions");
457 const defaultPath = yield* fileSystem
458 .exists(extensionsDir)
459 .pipe(Effect.orElseSucceed(() => false));
460 const paths = yield* dialog.pickFiles({
461 owner: yield* electronWindow.focusedMainOrFirst,
462 defaultPath: defaultPath ? Option.some(extensionsDir) : Option.none(),
463 filters: [{ name: "JSON", extensions: ["json"] }],
464 multiple: true,
465 });
466 if (paths.length === 0) {
467 return null;
468 }
469 return yield* Effect.forEach(paths, (filePath) => {
470 const name = path.basename(filePath);
471 return Effect.gen(function* () {
472 const info = yield* fileSystem.stat(filePath);
473 const size = Number(info.size);
474 if (size > PICKED_THEME_FILE_MAX_BYTES) {
475 return { name, size, text: "" } satisfies PickedThemeFile;
476 }
477 const text = yield* fileSystem.readFileString(filePath);
478 return { name, size, text } satisfies PickedThemeFile;
479 }).pipe(Effect.orElseSucceed((): PickedThemeFile => ({ name, size: 0, text: "" })));
480 });
481 }),
482});
483
484export const checkSystemPermission = DesktopIpc.makeIpcMethod({
485 channel: IpcChannels.CHECK_SYSTEM_PERMISSION_CHANNEL,
486 payload: SystemSettingsPaneSchema,
487 result: Schema.Boolean,
488 handler: Effect.fn("desktop.ipc.window.checkSystemPermission")(function* () {
489 const environment = yield* DesktopEnvironment.DesktopEnvironment;
490 if (environment.platform !== "darwin") return false;
491 const check = yield* safariPermissionCheck;
492 return yield* Effect.promise(check);
493 }),
494});