Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

window.ts

381 lines15.4 KB

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