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

window.ts

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