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

window.ts

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