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