Open History to see the last commit
1import {
2 ContextMenuItemSchema,
3 DesktopAppBrandingSchema,
4 DesktopEnvironmentBootstrapSchema,
5 DesktopThemeSchema,
6 PickedThemeFileSchema,
7 PickFolderOptionsSchema,
8 PRIMARY_LOCAL_ENVIRONMENT_ID,
9 type DesktopEnvironmentBootstrap,
10 type PickedThemeFile,
11} from "@t3tools/contracts";
12import * as NodeOS from "node:os";
13import * as FileSystem from "effect/FileSystem";
14import * as Path from "effect/Path";
15import * as Effect from "effect/Effect";
16import * as Option from "effect/Option";
17import * as Schema from "effect/Schema";
18
19import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts";
20import * as DesktopLocalEnvironmentAuth from "../../backend/DesktopLocalEnvironmentAuth.ts";
21import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts";
22import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts";
23import * as DesktopWslBackend from "../../wsl/DesktopWslBackend.ts";
24import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts";
25import * as ElectronDialog from "../../electron/ElectronDialog.ts";
26import * as ElectronMenu from "../../electron/ElectronMenu.ts";
27import * as ElectronShell from "../../electron/ElectronShell.ts";
28import * as ElectronTheme from "../../electron/ElectronTheme.ts";
29import * as ElectronWindow from "../../electron/ElectronWindow.ts";
30import * as IpcChannels from "../channels.ts";
31import * as DesktopIpc from "../DesktopIpc.ts";
32import {
33 isSameWslDistro,
34 isValidDistroName,
35 parseWslUncPath,
36 resolveWslPickFolderDefaultPath,
37} from "../../wsl/wslPathParsing.ts";
38
39const ContextMenuPosition = Schema.Struct({
40 x: Schema.Number,
41 y: Schema.Number,
42});
43
44const ContextMenuInput = Schema.Struct({
45 items: Schema.Array(ContextMenuItemSchema),
46 position: Schema.optionalKey(ContextMenuPosition),
47});
48
49function toWebSocketBaseUrl(httpBaseUrl: URL): string {
50 const url = new URL(httpBaseUrl.href);
51 url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
52 return url.href;
53}
54
55export const getAppBranding = DesktopIpc.makeSyncIpcMethod({
56 channel: IpcChannels.GET_APP_BRANDING_CHANNEL,
57 result: Schema.NullOr(DesktopAppBrandingSchema),
58 handler: Effect.fn("desktop.ipc.window.getAppBranding")(function* () {
59 const environment = yield* DesktopEnvironment.DesktopEnvironment;
60 return environment.branding;
61 }),
62});
63
64export const getWindowFullscreenState = DesktopIpc.makeSyncIpcMethod({
65 channel: IpcChannels.GET_WINDOW_FULLSCREEN_STATE_CHANNEL,
66 result: Schema.Boolean,
67 handler: Effect.fn("desktop.ipc.window.getWindowFullscreenState")(function* () {
68 const electronWindow = yield* ElectronWindow.ElectronWindow;
69 const window = yield* electronWindow.currentMainOrFirst;
70 return Option.isSome(window) && window.value.isFullScreen();
71 }),
72});
73
74export const getLocalEnvironmentBootstraps = DesktopIpc.makeSyncIpcMethod({
75 channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL,
76 result: Schema.Array(DesktopEnvironmentBootstrapSchema),
77 handler: Effect.fn("desktop.ipc.window.getLocalEnvironmentBootstraps")(function* () {
78 const pool = yield* DesktopBackendPool.DesktopBackendPool;
79 const instances = yield* pool.list;
80 const bootstraps: DesktopEnvironmentBootstrap[] = [];
81 for (const instance of instances) {
82 const isPrimary = instance.id === PRIMARY_LOCAL_ENVIRONMENT_ID;
83 const config = yield* instance.currentConfig;
84 const snapshot = yield* instance.snapshot;
85 // A secondary backend (e.g. a parallel WSL backend) that hasn't produced
86 // a config yet (mid-registration, before its first start cycle) or that
87 // is retrying a *transient* preflight failure (WSL VM still booting, a
88 // not-yet-built linux server entry) is not listening on a port. We
89 // surface it as a *pending* bootstrap (null endpoints, no token) so the
90 // renderer can show a "Connecting…" indicator while it retries — null
91 // endpoints keep the renderer from dialing the dead port, avoiding the
92 // needless /api/auth/bootstrap/bearer error cycles a real endpoint would
93 // trigger.
94 if (Option.isNone(config) || Option.isSome(config.value.preflightFailure)) {
95 // Skip the primary (same-origin, no "connecting" affordance) and skip a
96 // secondary whose preflight failed *fatally* (no node, wrong version,
97 // missing build tools): it has stopped retrying, so an indefinite
98 // "Connecting…" would be misleading — its error is surfaced by the
99 // WSL-state UI instead.
100 const fatalPreflight =
101 Option.isSome(config) &&
102 Option.isSome(config.value.preflightFailure) &&
103 config.value.preflightFailure.value.fatal;
104 const stoppedPreflight =
105 Option.isSome(config) &&
106 Option.isSome(config.value.preflightFailure) &&
107 (!snapshot.desiredRunning || !snapshot.restartScheduled);
108 if (isPrimary || fatalPreflight || stoppedPreflight) continue;
109 bootstraps.push({
110 id: instance.id,
111 label: yield* instance.label,
112 runningDistro: null,
113 httpBaseUrl: null,
114 wsBaseUrl: null,
115 });
116 continue;
117 }
118 const { bootstrap, httpBaseUrl } = config.value;
119 const runningDistro = config.value.runningDistro ?? null;
120 bootstraps.push({
121 id: instance.id,
122 label: runningDistro === null ? yield* instance.label : `WSL (${runningDistro})`,
123 runningDistro,
124 httpBaseUrl: httpBaseUrl.href,
125 wsBaseUrl: toWebSocketBaseUrl(httpBaseUrl),
126 ...(bootstrap.desktopBootstrapToken
127 ? { bootstrapToken: bootstrap.desktopBootstrapToken }
128 : {}),
129 });
130 }
131 return bootstraps;
132 }),
133});
134
135// Pull an explicit distro selection out of a backend instance id like
136// "wsl:ubuntu". Returns null for "wsl:default": that sentinel must be
137// resolved from the concrete running backend before any filesystem operation.
138function extractWslDistroFromEnvironmentId(envId: string): string | null {
139 if (!envId.startsWith(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX)) {
140 return null;
141 }
142 const suffix = envId.slice(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX.length);
143 if (suffix === "default" || suffix.length === 0) {
144 return null;
145 }
146 return isValidDistroName(suffix) ? suffix : null;
147}
148
149const runningDistroFromInstance = Effect.fn("desktop.ipc.window.runningDistroFromInstance")(
150 function* (instance: DesktopBackendPool.DesktopBackendInstance) {
151 const config = yield* instance.currentConfig;
152 if (Option.isNone(config)) {
153 return null;
154 }
155 return config.value.runningDistro ?? null;
156 },
157);
158
159// Resolve a WSL picker target to the concrete distro already backing that
160// environment. This is deliberately runtime-first: a stable `wsl:default` id
161// must not be re-resolved against the Windows system default after its backend
162// has started, otherwise changing the default distro while the app is open can
163// make the picker and backend point at different filesystems. In WSL-only mode
164// the renderer still uses a synthetic `wsl:*` picker target while the actual
165// backend lives in the pool's `primary` instance, so consult that primary too.
166export const resolveWslPickerDistro = Effect.fn("desktop.ipc.window.resolveWslPickerDistro")(
167 function* (input: {
168 readonly targetEnvironmentId: string;
169 readonly configuredDistro: string | null;
170 readonly wslOnly: boolean;
171 }) {
172 const pool = yield* DesktopBackendPool.DesktopBackendPool;
173
174 // In WSL-only mode the target id is synthetic and the real backend is the
175 // primary instance. Prefer it even if a stale secondary still exists while
176 // a relaunch-triggering settings change is winding the old process down.
177 if (input.wslOnly) {
178 const primary = yield* pool.primary;
179 const runningDistro = yield* runningDistroFromInstance(primary);
180 if (runningDistro !== null) {
181 return runningDistro;
182 }
183 }
184
185 const targetInstance = yield* pool.get(
186 DesktopBackendPool.BackendInstanceId(input.targetEnvironmentId),
187 );
188 if (Option.isSome(targetInstance)) {
189 const runningDistro = yield* runningDistroFromInstance(targetInstance.value);
190 if (runningDistro !== null) {
191 return runningDistro;
192 }
193 }
194
195 return extractWslDistroFromEnvironmentId(input.targetEnvironmentId) ?? input.configuredDistro;
196 },
197);
198
199export type WslPickerSelectionResolution =
200 | { readonly _tag: "Success"; readonly linuxPath: string }
201 | {
202 readonly _tag: "CrossDistro";
203 readonly selectedDistro: string;
204 readonly targetDistro: string;
205 }
206 | { readonly _tag: "ConversionFailed"; readonly targetDistro: string };
207
208export const resolveWslPickerSelection = Effect.fn("desktop.ipc.window.resolveWslPickerSelection")(
209 function* (input: { readonly selectedPath: string; readonly targetDistro: string }) {
210 const parsedUnc = parseWslUncPath(input.selectedPath);
211 if (parsedUnc !== null) {
212 if (!isSameWslDistro(parsedUnc.distro, input.targetDistro)) {
213 return {
214 _tag: "CrossDistro",
215 selectedDistro: parsedUnc.distro,
216 targetDistro: input.targetDistro,
217 } as const;
218 }
219 return { _tag: "Success", linuxPath: parsedUnc.linuxPath } as const;
220 }
221
222 const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
223 const converted = yield* wslEnvironment.windowsToWslPath(
224 input.targetDistro,
225 input.selectedPath,
226 );
227 if (Option.isNone(converted) || !converted.value.startsWith("/")) {
228 return { _tag: "ConversionFailed", targetDistro: input.targetDistro } as const;
229 }
230 return { _tag: "Success", linuxPath: converted.value } as const;
231 },
232);
233
234export const getLocalEnvironmentBearerToken = DesktopIpc.makeIpcMethod({
235 channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL,
236 payload: Schema.Void,
237 result: Schema.String,
238 handler: Effect.fn("desktop.ipc.window.getLocalEnvironmentBearerToken")(function* () {
239 const localAuth = yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth;
240 return yield* localAuth.getBearerToken;
241 }),
242});
243
244export const pickFolder = DesktopIpc.makeIpcMethod({
245 channel: IpcChannels.PICK_FOLDER_CHANNEL,
246 payload: Schema.UndefinedOr(PickFolderOptionsSchema),
247 result: Schema.NullOr(Schema.String),
248 handler: Effect.fn("desktop.ipc.window.pickFolder")(function* (options) {
249 const dialog = yield* ElectronDialog.ElectronDialog;
250 const electronWindow = yield* ElectronWindow.ElectronWindow;
251 const environment = yield* DesktopEnvironment.DesktopEnvironment;
252 const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
253 const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
254 // Three picker modes:
255 // - targetEnvironmentId omitted: default to the primary picker. Keeps
256 // the historical behavior unchanged for users who never enabled the
257 // WSL backend, and is what unfamiliar callers should get out of the
258 // box.
259 // - targetEnvironmentId starts with "wsl:": route to the WSL picker
260 // using the distro encoded in the id (or the user's selected
261 // wslDistro when the id is the "wsl:default" sentinel).
262 // - anything else (incl. PRIMARY_LOCAL_ENVIRONMENT_ID): primary picker.
263 const targetId = options?.targetEnvironmentId;
264 const useWsl =
265 targetId !== undefined &&
266 targetId !== PRIMARY_LOCAL_ENVIRONMENT_ID &&
267 targetId.startsWith(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX);
268 const settings = yield* appSettings.get;
269 const wslDistro = useWsl
270 ? yield* resolveWslPickerDistro({
271 targetEnvironmentId: targetId,
272 configuredDistro: settings.wslDistro,
273 wslOnly: settings.wslOnly,
274 })
275 : null;
276
277 // An environment-specific WSL picker is only safe when its concrete distro
278 // is known. In particular, never silently re-resolve `wsl:default` here: if
279 // no running identity exists, there is no trustworthy filesystem target.
280 if (useWsl && wslDistro === null) {
281 yield* dialog.showErrorBox(
282 "WSL folder picker unavailable",
283 "T3 Code could not determine which WSL distribution backs this environment. Start or reconnect the WSL backend, then choose the folder again.",
284 );
285 return null;
286 }
287
288 const defaultPath = useWsl
289 ? Option.fromNullishOr(
290 resolveWslPickFolderDefaultPath(
291 options,
292 { distro: wslDistro },
293 yield* wslEnvironment.listDistros,
294 Option.getOrNull(yield* wslEnvironment.getUserHome(wslDistro)),
295 ),
296 )
297 : environment.resolvePickFolderDefaultPath(options);
298 const selectedPath = yield* dialog.pickFolder({
299 owner: yield* electronWindow.focusedMainOrFirst,
300 defaultPath,
301 });
302 if (Option.isNone(selectedPath)) {
303 return null;
304 }
305 if (!useWsl) {
306 return selectedPath.value;
307 }
308
309 // `useWsl` implies wslDistro is concrete because of the guard above.
310 const targetDistro = wslDistro!;
311 const resolution = yield* resolveWslPickerSelection({
312 selectedPath: selectedPath.value,
313 targetDistro,
314 });
315 switch (resolution._tag) {
316 case "Success":
317 return resolution.linuxPath;
318 case "CrossDistro":
319 yield* dialog.showErrorBox(
320 "Folder belongs to a different WSL distribution",
321 `The selected folder belongs to ${resolution.selectedDistro}, but this environment is running in ${resolution.targetDistro}. Choose a folder from ${resolution.targetDistro} instead.`,
322 );
323 return null;
324 case "ConversionFailed":
325 yield* dialog.showErrorBox(
326 "Could not convert folder path for WSL",
327 `T3 Code could not convert the selected Windows path for ${resolution.targetDistro}. Choose a folder inside \\\\wsl.localhost\\${resolution.targetDistro} or verify that the distribution is running.`,
328 );
329 return null;
330 }
331 }),
332});
333
334export const setTheme = DesktopIpc.makeIpcMethod({
335 channel: IpcChannels.SET_THEME_CHANNEL,
336 payload: DesktopThemeSchema,
337 result: Schema.Void,
338 handler: Effect.fn("desktop.ipc.window.setTheme")(function* (theme) {
339 const electronTheme = yield* ElectronTheme.ElectronTheme;
340 yield* electronTheme.setSource(theme);
341 }),
342});
343
344export const showContextMenu = DesktopIpc.makeIpcMethod({
345 channel: IpcChannels.CONTEXT_MENU_CHANNEL,
346 payload: ContextMenuInput,
347 result: Schema.NullOr(Schema.String),
348 handler: Effect.fn("desktop.ipc.window.showContextMenu")(function* (input) {
349 const electronMenu = yield* ElectronMenu.ElectronMenu;
350 const electronWindow = yield* ElectronWindow.ElectronWindow;
351 const window = yield* electronWindow.focusedMainOrFirst;
352 if (Option.isNone(window)) {
353 return null;
354 }
355
356 const selectedItemId = yield* electronMenu.showContextMenu({
357 window: window.value,
358 items: input.items,
359 position: Option.fromNullishOr(input.position),
360 });
361 return Option.getOrNull(selectedItemId);
362 }),
363});
364
365export const openExternal = DesktopIpc.makeIpcMethod({
366 channel: IpcChannels.OPEN_EXTERNAL_CHANNEL,
367 payload: Schema.String,
368 result: Schema.Boolean,
369 handler: Effect.fn("desktop.ipc.window.openExternal")(function* (url) {
370 const shell = yield* ElectronShell.ElectronShell;
371 return yield* shell.openExternal(url);
372 }),
373});
374
375/** Theme files are a few KB; anything larger returns empty text and lets the
376 * renderer reject it by size without the contents ever crossing the bridge. */
377const PICKED_THEME_FILE_MAX_BYTES = 256 * 1024;
378
379export const pickThemeFiles = DesktopIpc.makeIpcMethod({
380 channel: IpcChannels.PICK_THEME_FILES_CHANNEL,
381 payload: Schema.Undefined,
382 result: Schema.NullOr(Schema.Array(PickedThemeFileSchema)),
383 handler: Effect.fn("desktop.ipc.window.pickThemeFiles")(function* () {
384 const dialog = yield* ElectronDialog.ElectronDialog;
385 const electronWindow = yield* ElectronWindow.ElectronWindow;
386 const fileSystem = yield* FileSystem.FileSystem;
387 const path = yield* Path.Path;
388 // The VS Code extensions directory is the same dotfolder on Windows,
389 // macOS, and Linux; when it is missing the picker opens wherever the
390 // platform would by default.
391 const extensionsDir = path.join(NodeOS.homedir(), ".vscode", "extensions");
392 const defaultPath = yield* fileSystem
393 .exists(extensionsDir)
394 .pipe(Effect.orElseSucceed(() => false));
395 const paths = yield* dialog.pickFiles({
396 owner: yield* electronWindow.focusedMainOrFirst,
397 defaultPath: defaultPath ? Option.some(extensionsDir) : Option.none(),
398 filters: [{ name: "JSON", extensions: ["json"] }],
399 });
400 if (paths.length === 0) {
401 return null;
402 }
403 return yield* Effect.forEach(paths, (filePath) => {
404 const name = path.basename(filePath);
405 return Effect.gen(function* () {
406 const info = yield* fileSystem.stat(filePath);
407 const size = Number(info.size);
408 if (size > PICKED_THEME_FILE_MAX_BYTES) {
409 return { name, size, text: "" } satisfies PickedThemeFile;
410 }
411 const text = yield* fileSystem.readFileString(filePath);
412 return { name, size, text } satisfies PickedThemeFile;
413 }).pipe(
414 // An unreadable file degrades to an entry the renderer reports.
415 Effect.orElseSucceed((): PickedThemeFile => ({ name, size: 0, text: "" })),
416 );
417 });
418 }),
419});