Open History to see the last commit
1import {
2 ContextMenuItemSchema,
3 DesktopAppBrandingSchema,
4 DesktopEnvironmentBootstrapSchema,
5 DesktopThemeSchema,
6 EDITORS,
7 EditorId,
8 PickedThemeFileSchema,
9 PickFolderOptionsSchema,
10 PRIMARY_LOCAL_ENVIRONMENT_ID,
11 REMOTE_CAPABLE_EDITOR_IDS,
12 SystemSettingsPaneSchema,
13 type DesktopEnvironmentBootstrap,
14 type PickedThemeFile,
15} from "@t3tools/contracts";
16import { WORKSPACE_IMAGE_PREVIEW_EXTENSIONS } from "@t3tools/shared/filePreview";
17import { isCommandAvailable } from "@t3tools/shared/shell";
18import * as NodeOS from "node:os";
19import * as FileSystem from "effect/FileSystem";
20import * as Path from "effect/Path";
21import * as Effect from "effect/Effect";
22import * as Option from "effect/Option";
23import * as Schema from "effect/Schema";
24
25import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts";
26import * as DesktopLocalEnvironmentAuth from "../../backend/DesktopLocalEnvironmentAuth.ts";
27import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts";
28import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts";
29import * as DesktopWslBackend from "../../wsl/DesktopWslBackend.ts";
30import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts";
31import * as ElectronApp from "../../electron/ElectronApp.ts";
32import * as ElectronDialog from "../../electron/ElectronDialog.ts";
33import * as ElectronMenu from "../../electron/ElectronMenu.ts";
34import * as ElectronShell from "../../electron/ElectronShell.ts";
35import * as ElectronTheme from "../../electron/ElectronTheme.ts";
36import * as ElectronWindow from "../../electron/ElectronWindow.ts";
37import * as Electron from "electron";
38import * as MacPermissions from "../../permissions/MacPermissions.ts";
39import { safariPermissionCheck } from "../../preview/BrowserImport/SafariPermission.ts";
40import * as IpcChannels from "../channels.ts";
41import * as DesktopIpc from "../DesktopIpc.ts";
42import {
43 extractDistroFromUncPath,
44 resolveWslPickFolderDefaultPath,
45 wslUncPathToLinuxPath,
46} from "../../wsl/wslPathParsing.ts";
47
48const ContextMenuPosition = Schema.Struct({
49 x: Schema.Number,
50 y: Schema.Number,
51});
52
53const ContextMenuInput = Schema.Struct({
54 items: Schema.Array(ContextMenuItemSchema),
55 position: Schema.optionalKey(ContextMenuPosition),
56});
57
58function toWebSocketBaseUrl(httpBaseUrl: URL): string {
59 const url = new URL(httpBaseUrl.href);
60 url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
61 return url.href;
62}
63
64export const getAppBranding = DesktopIpc.makeSyncIpcMethod({
65 channel: IpcChannels.GET_APP_BRANDING_CHANNEL,
66 result: Schema.NullOr(DesktopAppBrandingSchema),
67 handler: Effect.fn("desktop.ipc.window.getAppBranding")(function* () {
68 const environment = yield* DesktopEnvironment.DesktopEnvironment;
69 return environment.branding;
70 }),
71});
72
73export const getSystemLocale = DesktopIpc.makeSyncIpcMethod({
74 channel: IpcChannels.GET_SYSTEM_LOCALE_CHANNEL,
75 result: Schema.String,
76 handler: Effect.fn("desktop.ipc.window.getSystemLocale")(function* () {
77 const electronApp = yield* ElectronApp.ElectronApp;
78 return yield* electronApp.systemLocale;
79 }),
80});
81
82export const getWindowFullscreenState = DesktopIpc.makeSyncIpcMethod({
83 channel: IpcChannels.GET_WINDOW_FULLSCREEN_STATE_CHANNEL,
84 result: Schema.Boolean,
85 handler: Effect.fn("desktop.ipc.window.getWindowFullscreenState")(function* () {
86 const electronWindow = yield* ElectronWindow.ElectronWindow;
87 const window = yield* electronWindow.currentMainOrFirst;
88 return Option.isSome(window) && window.value.isFullScreen();
89 }),
90});
91
92export const getLocalEnvironmentBootstraps = DesktopIpc.makeSyncIpcMethod({
93 channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL,
94 result: Schema.Array(DesktopEnvironmentBootstrapSchema),
95 handler: Effect.fn("desktop.ipc.window.getLocalEnvironmentBootstraps")(function* () {
96 const pool = yield* DesktopBackendPool.DesktopBackendPool;
97 const instances = yield* pool.list;
98 const bootstraps: DesktopEnvironmentBootstrap[] = [];
99 for (const instance of instances) {
100 const isPrimary = instance.id === PRIMARY_LOCAL_ENVIRONMENT_ID;
101 const config = yield* instance.currentConfig;
102 const snapshot = yield* instance.snapshot;
103 // A secondary backend (e.g. a parallel WSL backend) that hasn't produced
104 // a config yet (mid-registration, before its first start cycle) or that
105 // is retrying a *transient* preflight failure (WSL VM still booting, a
106 // not-yet-built linux server entry) is not listening on a port. We
107 // surface it as a *pending* bootstrap (null endpoints, no token) so the
108 // renderer can show a "Connecting…" indicator while it retries — null
109 // endpoints keep the renderer from dialing the dead port, avoiding the
110 // needless /api/auth/bootstrap/bearer error cycles a real endpoint would
111 // trigger.
112 if (Option.isNone(config) || Option.isSome(config.value.preflightFailure)) {
113 // Skip the primary (same-origin, no "connecting" affordance) and skip a
114 // secondary whose preflight failed *fatally* (no node, wrong version,
115 // missing build tools): it has stopped retrying, so an indefinite
116 // "Connecting…" would be misleading — its error is surfaced by the
117 // WSL-state UI instead.
118 const fatalPreflight =
119 Option.isSome(config) &&
120 Option.isSome(config.value.preflightFailure) &&
121 config.value.preflightFailure.value.fatal;
122 const stoppedPreflight =
123 Option.isSome(config) &&
124 Option.isSome(config.value.preflightFailure) &&
125 (!snapshot.desiredRunning || !snapshot.restartScheduled);
126 if (isPrimary || fatalPreflight || stoppedPreflight) continue;
127 bootstraps.push({
128 id: instance.id,
129 label: yield* instance.label,
130 runningDistro: null,
131 httpBaseUrl: null,
132 wsBaseUrl: null,
133 });
134 continue;
135 }
136 const { bootstrap, httpBaseUrl } = config.value;
137 const runningDistro = config.value.runningDistro ?? null;
138 bootstraps.push({
139 id: instance.id,
140 label: runningDistro === null ? yield* instance.label : `WSL (${runningDistro})`,
141 runningDistro,
142 httpBaseUrl: httpBaseUrl.href,
143 wsBaseUrl: toWebSocketBaseUrl(httpBaseUrl),
144 ...(bootstrap.desktopBootstrapToken
145 ? { bootstrapToken: bootstrap.desktopBootstrapToken }
146 : {}),
147 });
148 }
149 return bootstraps;
150 }),
151});
152
153// Pull the distro selection out of a backend instance id like
154// "wsl:ubuntu". Returns null for "wsl:default", which is the sentinel
155// for "track the user's WSL default distro" and maps to the
156// wslEnv-derived default at picker time.
157function extractWslDistroFromEnvironmentId(envId: string): string | null {
158 if (!envId.startsWith(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX)) {
159 return null;
160 }
161 const suffix = envId.slice(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX.length);
162 return suffix === "default" || suffix.length === 0 ? null : suffix;
163}
164
165export const getLocalEnvironmentBearerToken = DesktopIpc.makeIpcMethod({
166 channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL,
167 payload: Schema.Void,
168 result: Schema.String,
169 handler: Effect.fn("desktop.ipc.window.getLocalEnvironmentBearerToken")(function* () {
170 const localAuth = yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth;
171 return yield* localAuth.getBearerToken;
172 }),
173});
174
175export const pickFolder = DesktopIpc.makeIpcMethod({
176 channel: IpcChannels.PICK_FOLDER_CHANNEL,
177 payload: Schema.UndefinedOr(PickFolderOptionsSchema),
178 result: Schema.NullOr(Schema.String),
179 handler: Effect.fn("desktop.ipc.window.pickFolder")(function* (options) {
180 const dialog = yield* ElectronDialog.ElectronDialog;
181 const electronWindow = yield* ElectronWindow.ElectronWindow;
182 const environment = yield* DesktopEnvironment.DesktopEnvironment;
183 const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
184 const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
185 const settings = yield* appSettings.get;
186 // A picked path only means something to a backend on this machine.
187 if (!settings.localEnvironmentEnabled) {
188 return null;
189 }
190 // Three picker modes:
191 // - targetEnvironmentId omitted: default to the primary picker. Keeps
192 // the historical behavior unchanged for users who never enabled the
193 // WSL backend, and is what unfamiliar callers should get out of the
194 // box.
195 // - targetEnvironmentId starts with "wsl:": route to the WSL picker
196 // using the distro encoded in the id (or the user's selected
197 // wslDistro when the id is the "wsl:default" sentinel).
198 // - anything else (incl. PRIMARY_LOCAL_ENVIRONMENT_ID): primary picker.
199 const targetId = options?.targetEnvironmentId;
200 const wslDistroFromTarget =
201 targetId !== undefined && targetId.startsWith(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX)
202 ? extractWslDistroFromEnvironmentId(targetId)
203 : null;
204 const useWsl =
205 targetId !== undefined &&
206 targetId !== PRIMARY_LOCAL_ENVIRONMENT_ID &&
207 targetId.startsWith(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX);
208 // Fall back to the persisted wslDistro when the id is the
209 // "wsl:default" sentinel; the orchestrator uses the same fallback
210 // for the actual backend.
211 const wslDistro = useWsl ? (wslDistroFromTarget ?? settings.wslDistro) : null;
212 const defaultPath = useWsl
213 ? Option.fromNullishOr(
214 resolveWslPickFolderDefaultPath(
215 options,
216 { distro: wslDistro },
217 yield* wslEnvironment.listDistros,
218 Option.getOrNull(yield* wslEnvironment.getUserHome(wslDistro)),
219 ),
220 )
221 : environment.resolvePickFolderDefaultPath(options);
222 const selectedPath = yield* dialog.pickFolder({
223 owner: yield* electronWindow.focusedMainOrFirst,
224 defaultPath,
225 });
226 if (Option.isNone(selectedPath)) {
227 return null;
228 }
229 if (!useWsl) {
230 return selectedPath.value;
231 }
232
233 const linuxUncPath = wslUncPathToLinuxPath(selectedPath.value);
234 if (linuxUncPath !== null) {
235 return linuxUncPath;
236 }
237
238 const converted = yield* wslEnvironment.windowsToWslPath(
239 extractDistroFromUncPath(selectedPath.value) ?? wslDistro,
240 selectedPath.value,
241 );
242 return Option.getOrElse(converted, () => selectedPath.value);
243 }),
244});
245
246export const pickProjectFavicon = DesktopIpc.makeIpcMethod({
247 channel: IpcChannels.PICK_PROJECT_FAVICON_CHANNEL,
248 payload: Schema.UndefinedOr(Schema.String),
249 result: Schema.NullOr(Schema.String),
250 handler: Effect.fn("desktop.ipc.window.pickProjectFavicon")(function* (initialPath) {
251 const dialog = yield* ElectronDialog.ElectronDialog;
252 const electronWindow = yield* ElectronWindow.ElectronWindow;
253 const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
254 if (!(yield* appSettings.get).localEnvironmentEnabled) {
255 return null;
256 }
257 const paths = yield* dialog.pickFiles({
258 owner: yield* electronWindow.focusedMainOrFirst,
259 defaultPath: Option.fromNullishOr(initialPath),
260 multiple: false,
261 filters: [
262 {
263 name: "Images",
264 extensions: WORKSPACE_IMAGE_PREVIEW_EXTENSIONS.map((extension) => extension.slice(1)),
265 },
266 ],
267 });
268 return paths[0] ?? null;
269 }),
270});
271
272export const setTheme = DesktopIpc.makeIpcMethod({
273 channel: IpcChannels.SET_THEME_CHANNEL,
274 payload: DesktopThemeSchema,
275 result: Schema.Void,
276 handler: Effect.fn("desktop.ipc.window.setTheme")(function* (theme) {
277 const electronTheme = yield* ElectronTheme.ElectronTheme;
278 yield* electronTheme.setSource(theme);
279 }),
280});
281
282export const showContextMenu = DesktopIpc.makeIpcMethod({
283 channel: IpcChannels.CONTEXT_MENU_CHANNEL,
284 payload: ContextMenuInput,
285 result: Schema.NullOr(Schema.String),
286 handler: Effect.fn("desktop.ipc.window.showContextMenu")(function* (input) {
287 const electronMenu = yield* ElectronMenu.ElectronMenu;
288 const electronWindow = yield* ElectronWindow.ElectronWindow;
289 const window = yield* electronWindow.focusedMainOrFirst;
290 if (Option.isNone(window)) {
291 return null;
292 }
293
294 const selectedItemId = yield* electronMenu.showContextMenu({
295 window: window.value,
296 items: input.items,
297 position: Option.fromNullishOr(input.position),
298 });
299 return Option.getOrNull(selectedItemId);
300 }),
301});
302
303export const openExternal = DesktopIpc.makeIpcMethod({
304 channel: IpcChannels.OPEN_EXTERNAL_CHANNEL,
305 payload: Schema.String,
306 result: Schema.Boolean,
307 handler: Effect.fn("desktop.ipc.window.openExternal")(function* (url) {
308 const shell = yield* ElectronShell.ElectronShell;
309 return yield* shell.openExternal(url);
310 }),
311});
312
313export const openSystemSettings = DesktopIpc.makeIpcMethod({
314 channel: IpcChannels.OPEN_SYSTEM_SETTINGS_CHANNEL,
315 payload: SystemSettingsPaneSchema,
316 result: Schema.Boolean,
317 handler: Effect.fn("desktop.ipc.window.openSystemSettings")(function* (pane) {
318 const shell = yield* ElectronShell.ElectronShell;
319 const environment = yield* DesktopEnvironment.DesktopEnvironment;
320 if (environment.platform !== "darwin") return false;
321 const owner = Electron.BrowserWindow.getFocusedWindow();
322 const opened = yield* shell.openSystemSettings(pane);
323 if (opened && environment.isPackaged) {
324 const permissions = yield* MacPermissions.MacPermissions;
325 const isGranted = yield* safariPermissionCheck;
326 yield* permissions.showHelper(pane, owner, isGranted);
327 }
328 return opened;
329 }),
330});
331
332export const probeRemoteEditors = DesktopIpc.makeIpcMethod({
333 channel: IpcChannels.PROBE_REMOTE_EDITORS_CHANNEL,
334 payload: Schema.Undefined,
335 result: Schema.Array(EditorId),
336 // Probes THIS machine (where the renderer runs) for remote-capable editor
337 // CLIs, unlike the server's probe which walks the environment host's PATH.
338 // A Finder-launched app can miss PATH entries; an empty result makes the
339 // renderer fall back to VS Code only, so that fails soft.
340 handler: Effect.fn("desktop.ipc.window.probeRemoteEditors")(function* () {
341 const available: Array<EditorId> = [];
342 for (const editorId of REMOTE_CAPABLE_EDITOR_IDS) {
343 const commands = EDITORS.find((editor) => editor.id === editorId)?.commands;
344 if (!commands) continue;
345 for (const command of commands) {
346 if (yield* isCommandAvailable(command, { env: process.env })) {
347 available.push(editorId);
348 break;
349 }
350 }
351 }
352 return available;
353 }),
354});
355
356export const pasteAsText = DesktopIpc.makeIpcMethod({
357 channel: IpcChannels.PASTE_AS_TEXT_CHANNEL,
358 payload: Schema.Undefined,
359 result: Schema.Void,
360 handler: Effect.fn("desktop.ipc.window.pasteAsText")(function* (_input, event) {
361 const electronWindow = yield* ElectronWindow.ElectronWindow;
362 const window = yield* electronWindow.main;
363 if (
364 event === undefined ||
365 Option.isNone(window) ||
366 window.value.isDestroyed() ||
367 window.value.webContents.id !== event.sender.id
368 ) {
369 return;
370 }
371 const focused = Electron.webContents.getFocusedWebContents();
372 if (
373 focused &&
374 !focused.isDestroyed() &&
375 Electron.BrowserWindow.fromWebContents(focused) === window.value
376 ) {
377 focused.paste();
378 }
379 }),
380});
381
382/** Theme files are a few KB; anything larger returns empty text and lets the
383 * renderer reject it by size without the contents ever crossing the bridge. */
384const PICKED_THEME_FILE_MAX_BYTES = 256 * 1024;
385
386export const pickThemeFiles = DesktopIpc.makeIpcMethod({
387 channel: IpcChannels.PICK_THEME_FILES_CHANNEL,
388 payload: Schema.Undefined,
389 result: Schema.NullOr(Schema.Array(PickedThemeFileSchema)),
390 handler: Effect.fn("desktop.ipc.window.pickThemeFiles")(function* () {
391 const dialog = yield* ElectronDialog.ElectronDialog;
392 const electronWindow = yield* ElectronWindow.ElectronWindow;
393 const fileSystem = yield* FileSystem.FileSystem;
394 const path = yield* Path.Path;
395 // The VS Code extensions directory is the same dotfolder on Windows,
396 // macOS, and Linux; when it is missing the picker opens wherever the
397 // platform would by default.
398 const extensionsDir = path.join(NodeOS.homedir(), ".vscode", "extensions");
399 const defaultPath = yield* fileSystem
400 .exists(extensionsDir)
401 .pipe(Effect.orElseSucceed(() => false));
402 const paths = yield* dialog.pickFiles({
403 owner: yield* electronWindow.focusedMainOrFirst,
404 defaultPath: defaultPath ? Option.some(extensionsDir) : Option.none(),
405 filters: [{ name: "JSON", extensions: ["json"] }],
406 multiple: true,
407 });
408 if (paths.length === 0) {
409 return null;
410 }
411 return yield* Effect.forEach(paths, (filePath) => {
412 const name = path.basename(filePath);
413 return Effect.gen(function* () {
414 const info = yield* fileSystem.stat(filePath);
415 const size = Number(info.size);
416 if (size > PICKED_THEME_FILE_MAX_BYTES) {
417 return { name, size, text: "" } satisfies PickedThemeFile;
418 }
419 const text = yield* fileSystem.readFileString(filePath);
420 return { name, size, text } satisfies PickedThemeFile;
421 }).pipe(
422 // An unreadable file degrades to an entry the renderer reports.
423 Effect.orElseSucceed((): PickedThemeFile => ({ name, size: 0, text: "" })),
424 );
425 });
426 }),
427});
428
429export const checkSystemPermission = DesktopIpc.makeIpcMethod({
430 channel: IpcChannels.CHECK_SYSTEM_PERMISSION_CHANNEL,
431 payload: SystemSettingsPaneSchema,
432 result: Schema.Boolean,
433 handler: Effect.fn("desktop.ipc.window.checkSystemPermission")(function* () {
434 const environment = yield* DesktopEnvironment.DesktopEnvironment;
435 if (environment.platform !== "darwin") return false;
436 const check = yield* safariPermissionCheck;
437 return yield* Effect.promise(check);
438 }),
439});