Open History to see the last commit
1import {
2 ContextMenuItemSchema,
3 DesktopAppBrandingSchema,
4 DesktopEnvironmentBootstrapSchema,
5 DesktopThemeSchema,
6 PickFolderOptionsSchema,
7 PRIMARY_LOCAL_ENVIRONMENT_ID,
8 type DesktopEnvironmentBootstrap,
9} from "@t3tools/contracts";
10import * as Effect from "effect/Effect";
11import * as Option from "effect/Option";
12import * as Schema from "effect/Schema";
13
14import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts";
15import * as DesktopLocalEnvironmentAuth from "../../backend/DesktopLocalEnvironmentAuth.ts";
16import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts";
17import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts";
18import * as DesktopWslBackend from "../../wsl/DesktopWslBackend.ts";
19import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts";
20import * as ElectronDialog from "../../electron/ElectronDialog.ts";
21import * as ElectronMenu from "../../electron/ElectronMenu.ts";
22import * as ElectronShell from "../../electron/ElectronShell.ts";
23import * as ElectronTheme from "../../electron/ElectronTheme.ts";
24import * as ElectronWindow from "../../electron/ElectronWindow.ts";
25import * as IpcChannels from "../channels.ts";
26import * as DesktopIpc from "../DesktopIpc.ts";
27import {
28 extractDistroFromUncPath,
29 resolveWslPickFolderDefaultPath,
30 wslUncPathToLinuxPath,
31} from "../../wsl/wslPathParsing.ts";
32
33const ContextMenuPosition = Schema.Struct({
34 x: Schema.Number,
35 y: Schema.Number,
36});
37
38const ContextMenuInput = Schema.Struct({
39 items: Schema.Array(ContextMenuItemSchema),
40 position: Schema.optionalKey(ContextMenuPosition),
41});
42
43function toWebSocketBaseUrl(httpBaseUrl: URL): string {
44 const url = new URL(httpBaseUrl.href);
45 url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
46 return url.href;
47}
48
49export const getAppBranding = DesktopIpc.makeSyncIpcMethod({
50 channel: IpcChannels.GET_APP_BRANDING_CHANNEL,
51 result: Schema.NullOr(DesktopAppBrandingSchema),
52 handler: Effect.fn("desktop.ipc.window.getAppBranding")(function* () {
53 const environment = yield* DesktopEnvironment.DesktopEnvironment;
54 return environment.branding;
55 }),
56});
57
58export const getWindowFullscreenState = DesktopIpc.makeSyncIpcMethod({
59 channel: IpcChannels.GET_WINDOW_FULLSCREEN_STATE_CHANNEL,
60 result: Schema.Boolean,
61 handler: Effect.fn("desktop.ipc.window.getWindowFullscreenState")(function* () {
62 const electronWindow = yield* ElectronWindow.ElectronWindow;
63 const window = yield* electronWindow.currentMainOrFirst;
64 return Option.isSome(window) && window.value.isFullScreen();
65 }),
66});
67
68export const getLocalEnvironmentBootstraps = DesktopIpc.makeSyncIpcMethod({
69 channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL,
70 result: Schema.Array(DesktopEnvironmentBootstrapSchema),
71 handler: Effect.fn("desktop.ipc.window.getLocalEnvironmentBootstraps")(function* () {
72 const pool = yield* DesktopBackendPool.DesktopBackendPool;
73 const instances = yield* pool.list;
74 const bootstraps: DesktopEnvironmentBootstrap[] = [];
75 for (const instance of instances) {
76 const isPrimary = instance.id === PRIMARY_LOCAL_ENVIRONMENT_ID;
77 const config = yield* instance.currentConfig;
78 const snapshot = yield* instance.snapshot;
79 // A secondary backend (e.g. a parallel WSL backend) that hasn't produced
80 // a config yet (mid-registration, before its first start cycle) or that
81 // is retrying a *transient* preflight failure (WSL VM still booting, a
82 // not-yet-built linux server entry) is not listening on a port. We
83 // surface it as a *pending* bootstrap (null endpoints, no token) so the
84 // renderer can show a "Connecting…" indicator while it retries — null
85 // endpoints keep the renderer from dialing the dead port, avoiding the
86 // needless /api/auth/bootstrap/bearer error cycles a real endpoint would
87 // trigger.
88 if (Option.isNone(config) || Option.isSome(config.value.preflightFailure)) {
89 // Skip the primary (same-origin, no "connecting" affordance) and skip a
90 // secondary whose preflight failed *fatally* (no node, wrong version,
91 // missing build tools): it has stopped retrying, so an indefinite
92 // "Connecting…" would be misleading — its error is surfaced by the
93 // WSL-state UI instead.
94 const fatalPreflight =
95 Option.isSome(config) &&
96 Option.isSome(config.value.preflightFailure) &&
97 config.value.preflightFailure.value.fatal;
98 const stoppedPreflight =
99 Option.isSome(config) &&
100 Option.isSome(config.value.preflightFailure) &&
101 (!snapshot.desiredRunning || !snapshot.restartScheduled);
102 if (isPrimary || fatalPreflight || stoppedPreflight) continue;
103 bootstraps.push({
104 id: instance.id,
105 label: yield* instance.label,
106 runningDistro: null,
107 httpBaseUrl: null,
108 wsBaseUrl: null,
109 });
110 continue;
111 }
112 const { bootstrap, httpBaseUrl } = config.value;
113 const runningDistro = config.value.runningDistro ?? null;
114 bootstraps.push({
115 id: instance.id,
116 label: runningDistro === null ? yield* instance.label : `WSL (${runningDistro})`,
117 runningDistro,
118 httpBaseUrl: httpBaseUrl.href,
119 wsBaseUrl: toWebSocketBaseUrl(httpBaseUrl),
120 ...(bootstrap.desktopBootstrapToken
121 ? { bootstrapToken: bootstrap.desktopBootstrapToken }
122 : {}),
123 });
124 }
125 return bootstraps;
126 }),
127});
128
129// Pull the distro selection out of a backend instance id like
130// "wsl:ubuntu". Returns null for "wsl:default", which is the sentinel
131// for "track the user's WSL default distro" and maps to the
132// wslEnv-derived default at picker time.
133function extractWslDistroFromEnvironmentId(envId: string): string | null {
134 if (!envId.startsWith(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX)) {
135 return null;
136 }
137 const suffix = envId.slice(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX.length);
138 return suffix === "default" || suffix.length === 0 ? null : suffix;
139}
140
141export const getLocalEnvironmentBearerToken = DesktopIpc.makeIpcMethod({
142 channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL,
143 payload: Schema.Void,
144 result: Schema.String,
145 handler: Effect.fn("desktop.ipc.window.getLocalEnvironmentBearerToken")(function* () {
146 const localAuth = yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth;
147 return yield* localAuth.getBearerToken;
148 }),
149});
150
151export const pickFolder = DesktopIpc.makeIpcMethod({
152 channel: IpcChannels.PICK_FOLDER_CHANNEL,
153 payload: Schema.UndefinedOr(PickFolderOptionsSchema),
154 result: Schema.NullOr(Schema.String),
155 handler: Effect.fn("desktop.ipc.window.pickFolder")(function* (options) {
156 const dialog = yield* ElectronDialog.ElectronDialog;
157 const electronWindow = yield* ElectronWindow.ElectronWindow;
158 const environment = yield* DesktopEnvironment.DesktopEnvironment;
159 const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
160 const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
161 // Three picker modes:
162 // - targetEnvironmentId omitted: default to the primary picker. Keeps
163 // the historical behavior unchanged for users who never enabled the
164 // WSL backend, and is what unfamiliar callers should get out of the
165 // box.
166 // - targetEnvironmentId starts with "wsl:": route to the WSL picker
167 // using the distro encoded in the id (or the user's selected
168 // wslDistro when the id is the "wsl:default" sentinel).
169 // - anything else (incl. PRIMARY_LOCAL_ENVIRONMENT_ID): primary picker.
170 const targetId = options?.targetEnvironmentId;
171 const wslDistroFromTarget =
172 targetId !== undefined && targetId.startsWith(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX)
173 ? extractWslDistroFromEnvironmentId(targetId)
174 : null;
175 const useWsl =
176 targetId !== undefined &&
177 targetId !== PRIMARY_LOCAL_ENVIRONMENT_ID &&
178 targetId.startsWith(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX);
179 const settings = yield* appSettings.get;
180 // Fall back to the persisted wslDistro when the id is the
181 // "wsl:default" sentinel; the orchestrator uses the same fallback
182 // for the actual backend.
183 const wslDistro = useWsl ? (wslDistroFromTarget ?? settings.wslDistro) : null;
184 const defaultPath = useWsl
185 ? Option.fromNullishOr(
186 resolveWslPickFolderDefaultPath(
187 options,
188 { distro: wslDistro },
189 yield* wslEnvironment.listDistros,
190 Option.getOrNull(yield* wslEnvironment.getUserHome(wslDistro)),
191 ),
192 )
193 : environment.resolvePickFolderDefaultPath(options);
194 const selectedPath = yield* dialog.pickFolder({
195 owner: yield* electronWindow.focusedMainOrFirst,
196 defaultPath,
197 });
198 if (Option.isNone(selectedPath)) {
199 return null;
200 }
201 if (!useWsl) {
202 return selectedPath.value;
203 }
204
205 const linuxUncPath = wslUncPathToLinuxPath(selectedPath.value);
206 if (linuxUncPath !== null) {
207 return linuxUncPath;
208 }
209
210 const converted = yield* wslEnvironment.windowsToWslPath(
211 extractDistroFromUncPath(selectedPath.value) ?? wslDistro,
212 selectedPath.value,
213 );
214 return Option.getOrElse(converted, () => selectedPath.value);
215 }),
216});
217
218export const confirm = DesktopIpc.makeIpcMethod({
219 channel: IpcChannels.CONFIRM_CHANNEL,
220 payload: Schema.String,
221 result: Schema.Boolean,
222 handler: Effect.fn("desktop.ipc.window.confirm")(function* (message) {
223 const dialog = yield* ElectronDialog.ElectronDialog;
224 const electronWindow = yield* ElectronWindow.ElectronWindow;
225 return yield* electronWindow.focusedMainOrFirst.pipe(
226 Effect.flatMap((owner) => dialog.confirm({ owner, message })),
227 );
228 }),
229});
230
231export const setTheme = DesktopIpc.makeIpcMethod({
232 channel: IpcChannels.SET_THEME_CHANNEL,
233 payload: DesktopThemeSchema,
234 result: Schema.Void,
235 handler: Effect.fn("desktop.ipc.window.setTheme")(function* (theme) {
236 const electronTheme = yield* ElectronTheme.ElectronTheme;
237 yield* electronTheme.setSource(theme);
238 }),
239});
240
241export const showContextMenu = DesktopIpc.makeIpcMethod({
242 channel: IpcChannels.CONTEXT_MENU_CHANNEL,
243 payload: ContextMenuInput,
244 result: Schema.NullOr(Schema.String),
245 handler: Effect.fn("desktop.ipc.window.showContextMenu")(function* (input) {
246 const electronMenu = yield* ElectronMenu.ElectronMenu;
247 const electronWindow = yield* ElectronWindow.ElectronWindow;
248 const window = yield* electronWindow.focusedMainOrFirst;
249 if (Option.isNone(window)) {
250 return null;
251 }
252
253 const selectedItemId = yield* electronMenu.showContextMenu({
254 window: window.value,
255 items: input.items,
256 position: Option.fromNullishOr(input.position),
257 });
258 return Option.getOrNull(selectedItemId);
259 }),
260});
261
262export const openExternal = DesktopIpc.makeIpcMethod({
263 channel: IpcChannels.OPEN_EXTERNAL_CHANNEL,
264 payload: Schema.String,
265 result: Schema.Boolean,
266 handler: Effect.fn("desktop.ipc.window.openExternal")(function* (url) {
267 const shell = yield* ElectronShell.ElectronShell;
268 return yield* shell.openExternal(url);
269 }),
270});