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