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