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

window.ts

308 lines12.7 KB

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