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