Open History to see the last commit
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 { PROJECT_FAVICON_EXTENSIONS } from "@t3tools/shared/projectFavicon";
17import { resolveEditorCommand } from "@t3tools/shared/editor";
18import * as HostProcess from "@t3tools/shared/HostProcess";
19import { isRelayTracingEnabled } from "@t3tools/shared/otelEnvironment";
20import * as FileSystem from "effect/FileSystem";
21import * as Path from "effect/Path";
22import * as Effect from "effect/Effect";
23import * as Option from "effect/Option";
24import * as Schema from "effect/Schema";
25
26import * as DesktopBackendConfiguration from "../../backend/DesktopBackendConfiguration.ts";
27import * as DesktopBackendPool from "../../backend/DesktopBackendPool.ts";
28import * as DesktopLocalEnvironmentAuth from "../../backend/DesktopLocalEnvironmentAuth.ts";
29import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts";
30import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts";
31import * as DesktopWslBackend from "../../wsl/DesktopWslBackend.ts";
32import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts";
33import * as ElectronApp from "../../electron/ElectronApp.ts";
34import * as ElectronDialog from "../../electron/ElectronDialog.ts";
35import * as ElectronMenu from "../../electron/ElectronMenu.ts";
36import * as ElectronShell from "../../electron/ElectronShell.ts";
37import * as ElectronTheme from "../../electron/ElectronTheme.ts";
38import * as ElectronWindow from "../../electron/ElectronWindow.ts";
39import * as Electron from "electron";
40import * as MacPermissions from "../../permissions/MacPermissions.ts";
41import { safariPermissionCheck } from "../../preview/BrowserImport/SafariPermission.ts";
42import * as IpcChannels from "../channels.ts";
43import * as DesktopIpc from "../DesktopIpc.ts";
44import {
45 extractDistroFromUncPath,
46 resolveWslPickFolderDefaultPath,
47 wslUncPathToLinuxPath,
48} from "../../wsl/wslPathParsing.ts";
49
50const ContextMenuPosition = Schema.Struct({
51 x: Schema.Number,
52 y: Schema.Number,
53});
54
55const ContextMenuInput = Schema.Struct({
56 items: Schema.Array(ContextMenuItemSchema),
57 position: Schema.optionalKey(ContextMenuPosition),
58});
59
60function toWebSocketBaseUrl(httpBaseUrl: URL): string {
61 const url = new URL(httpBaseUrl.href);
62 url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
63 return url.href;
64}
65
66export const getAppBranding = DesktopIpc.makeSyncIpcMethod({
67 channel: IpcChannels.GET_APP_BRANDING_CHANNEL,
68 result: Schema.NullOr(DesktopAppBrandingSchema),
69 handler: Effect.fn("desktop.ipc.window.getAppBranding")(function* () {
70 const environment = yield* DesktopEnvironment.DesktopEnvironment;
71 return environment.branding;
72 }),
73});
74
75export const getRelayTelemetryEnabled = DesktopIpc.makeSyncIpcMethod({
76 channel: IpcChannels.GET_RELAY_TELEMETRY_ENABLED_CHANNEL,
77 result: Schema.Boolean,
78 handler: Effect.fn("desktop.ipc.window.getRelayTelemetryEnabled")(function* () {
79 return isRelayTracingEnabled(yield* HostProcess.Environment);
80 }),
81});
82
83export const getSystemLocale = DesktopIpc.makeSyncIpcMethod({
84 channel: IpcChannels.GET_SYSTEM_LOCALE_CHANNEL,
85 result: Schema.String,
86 handler: Effect.fn("desktop.ipc.window.getSystemLocale")(function* () {
87 const electronApp = yield* ElectronApp.ElectronApp;
88 return yield* electronApp.systemLocale;
89 }),
90});
91
92export const getWindowFullscreenState = DesktopIpc.makeSyncIpcMethod({
93 channel: IpcChannels.GET_WINDOW_FULLSCREEN_STATE_CHANNEL,
94 result: Schema.Boolean,
95 handler: Effect.fn("desktop.ipc.window.getWindowFullscreenState")(function* () {
96 const electronWindow = yield* ElectronWindow.ElectronWindow;
97 const window = yield* electronWindow.currentMainOrFirst;
98 return Option.isSome(window) && window.value.isFullScreen();
99 }),
100});
101
102export const getLocalEnvironmentBootstraps = DesktopIpc.makeSyncIpcMethod({
103 channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL,
104 result: Schema.Array(DesktopEnvironmentBootstrapSchema),
105 handler: Effect.fn("desktop.ipc.window.getLocalEnvironmentBootstraps")(function* () {
106 const pool = yield* DesktopBackendPool.DesktopBackendPool;
107 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
108 const instances = yield* pool.list;
109 const bootstraps: DesktopEnvironmentBootstrap[] = [];
110 for (const instance of instances) {
111 const isPrimary = instance.id === PRIMARY_LOCAL_ENVIRONMENT_ID;
112 const config = yield* instance.currentConfig;
113 const snapshot = yield* instance.snapshot;
114 if (Option.isNone(config) || Option.isSome(config.value.preflightFailure)) {
115 const fatalPreflight =
116 Option.isSome(config) &&
117 Option.isSome(config.value.preflightFailure) &&
118 config.value.preflightFailure.value.fatal;
119 const stoppedPreflight =
120 Option.isSome(config) &&
121 Option.isSome(config.value.preflightFailure) &&
122 (!snapshot.desiredRunning || !snapshot.restartScheduled);
123 if (isPrimary || fatalPreflight || stoppedPreflight) continue;
124 bootstraps.push({
125 id: instance.id,
126 label: yield* instance.label,
127 runningDistro: null,
128 httpBaseUrl: null,
129 wsBaseUrl: null,
130 });
131 continue;
132 }
133 const { bootstrap, httpBaseUrl } = config.value;
134 const runningDistro = config.value.runningDistro ?? null;
135 bootstraps.push({
136 id: instance.id,
137 label: runningDistro === null ? yield* instance.label : `WSL (${runningDistro})`,
138 runningDistro,
139 httpBaseUrl: httpBaseUrl.href,
140 wsBaseUrl: toWebSocketBaseUrl(httpBaseUrl),
141 // Use the current window's derived token; the launch config's token may be stale.
142 ...(bootstrap.desktopBootstrapSecret
143 ? { bootstrapToken: yield* configuration.currentBootstrapToken }
144 : bootstrap.desktopBootstrapToken
145 ? { bootstrapToken: bootstrap.desktopBootstrapToken }
146 : {}),
147 });
148 }
149 return bootstraps;
150 }),
151});
152
153function extractWslDistroFromEnvironmentId(envId: string): string | null {
154 if (!envId.startsWith(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX)) {
155 return null;
156 }
157 const suffix = envId.slice(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX.length);
158 return suffix === "default" || suffix.length === 0 ? null : suffix;
159}
160
161export const getLocalEnvironmentBearerToken = DesktopIpc.makeIpcMethod({
162 channel: IpcChannels.GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL,
163 payload: Schema.Void,
164 result: Schema.String,
165 handler: Effect.fn("desktop.ipc.window.getLocalEnvironmentBearerToken")(function* () {
166 const localAuth = yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth;
167 return yield* localAuth.getBearerToken;
168 }),
169});
170
171export const pickFolder = DesktopIpc.makeIpcMethod({
172 channel: IpcChannels.PICK_FOLDER_CHANNEL,
173 payload: Schema.UndefinedOr(PickFolderOptionsSchema),
174 result: Schema.NullOr(Schema.String),
175 handler: Effect.fn("desktop.ipc.window.pickFolder")(function* (options) {
176 const dialog = yield* ElectronDialog.ElectronDialog;
177 const electronWindow = yield* ElectronWindow.ElectronWindow;
178 const environment = yield* DesktopEnvironment.DesktopEnvironment;
179 const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
180 const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
181 const settings = yield* appSettings.get;
182 // A picked path only means something to a backend on this machine.
183 if (!settings.localEnvironmentEnabled) {
184 return null;
185 }
186 const targetId = options?.targetEnvironmentId;
187 const wslDistroFromTarget =
188 targetId !== undefined && targetId.startsWith(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX)
189 ? extractWslDistroFromEnvironmentId(targetId)
190 : null;
191 const useWsl =
192 targetId !== undefined &&
193 targetId !== PRIMARY_LOCAL_ENVIRONMENT_ID &&
194 targetId.startsWith(DesktopWslBackend.WSL_INSTANCE_ID_PREFIX);
195 // Match the orchestrator's persisted distro fallback for wsl:default.
196 const wslDistro = useWsl ? (wslDistroFromTarget ?? settings.wslDistro) : null;
197 const defaultPath = useWsl
198 ? Option.fromNullishOr(
199 resolveWslPickFolderDefaultPath(
200 options,
201 { distro: wslDistro },
202 yield* wslEnvironment.listDistros,
203 Option.getOrNull(yield* wslEnvironment.getUserHome(wslDistro)),
204 ),
205 )
206 : environment.resolvePickFolderDefaultPath(options);
207 const selectedPath = yield* dialog.pickFolder({
208 owner: yield* electronWindow.focusedMainOrFirst,
209 defaultPath,
210 });
211 if (Option.isNone(selectedPath)) {
212 return null;
213 }
214 if (!useWsl) {
215 return selectedPath.value;
216 }
217
218 const linuxUncPath = wslUncPathToLinuxPath(selectedPath.value);
219 if (linuxUncPath !== null) {
220 return linuxUncPath;
221 }
222
223 const converted = yield* wslEnvironment.windowsToWslPath(
224 extractDistroFromUncPath(selectedPath.value) ?? wslDistro,
225 selectedPath.value,
226 );
227 return Option.getOrElse(converted, () => selectedPath.value);
228 }),
229});
230
231export const pickProjectFavicon = DesktopIpc.makeIpcMethod({
232 channel: IpcChannels.PICK_PROJECT_FAVICON_CHANNEL,
233 payload: Schema.UndefinedOr(Schema.String),
234 result: Schema.NullOr(Schema.String),
235 handler: Effect.fn("desktop.ipc.window.pickProjectFavicon")(function* (initialPath) {
236 const dialog = yield* ElectronDialog.ElectronDialog;
237 const electronWindow = yield* ElectronWindow.ElectronWindow;
238 const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
239 if (!(yield* appSettings.get).localEnvironmentEnabled) {
240 return null;
241 }
242 const paths = yield* dialog.pickFiles({
243 owner: yield* electronWindow.focusedMainOrFirst,
244 defaultPath: Option.fromNullishOr(initialPath),
245 multiple: false,
246 filters: [
247 {
248 name: "Images",
249 extensions: PROJECT_FAVICON_EXTENSIONS.map((extension) => extension.slice(1)),
250 },
251 ],
252 });
253 return paths[0] ?? null;
254 }),
255});
256
257export const setTheme = DesktopIpc.makeIpcMethod({
258 channel: IpcChannels.SET_THEME_CHANNEL,
259 payload: DesktopThemeSchema,
260 result: Schema.Void,
261 handler: Effect.fn("desktop.ipc.window.setTheme")(function* (theme) {
262 const electronTheme = yield* ElectronTheme.ElectronTheme;
263 yield* electronTheme.setSource(theme);
264 }),
265});
266
267export const showContextMenu = DesktopIpc.makeIpcMethod({
268 channel: IpcChannels.CONTEXT_MENU_CHANNEL,
269 payload: ContextMenuInput,
270 result: Schema.NullOr(Schema.String),
271 handler: Effect.fn("desktop.ipc.window.showContextMenu")(function* (input) {
272 const electronMenu = yield* ElectronMenu.ElectronMenu;
273 const electronWindow = yield* ElectronWindow.ElectronWindow;
274 const window = yield* electronWindow.focusedMainOrFirst;
275 if (Option.isNone(window)) {
276 return null;
277 }
278
279 const selectedItemId = yield* electronMenu.showContextMenu({
280 window: window.value,
281 items: input.items,
282 position: Option.fromNullishOr(input.position),
283 });
284 return Option.getOrNull(selectedItemId);
285 }),
286});
287
288export const openExternal = DesktopIpc.makeIpcMethod({
289 channel: IpcChannels.OPEN_EXTERNAL_CHANNEL,
290 payload: Schema.String,
291 result: Schema.Boolean,
292 handler: Effect.fn("desktop.ipc.window.openExternal")(function* (url) {
293 const shell = yield* ElectronShell.ElectronShell;
294 return yield* shell.openExternal(url);
295 }),
296});
297
298export const openSystemSettings = DesktopIpc.makeIpcMethod({
299 channel: IpcChannels.OPEN_SYSTEM_SETTINGS_CHANNEL,
300 payload: SystemSettingsPaneSchema,
301 result: Schema.Boolean,
302 handler: Effect.fn("desktop.ipc.window.openSystemSettings")(function* (pane) {
303 const shell = yield* ElectronShell.ElectronShell;
304 const environment = yield* DesktopEnvironment.DesktopEnvironment;
305 if (environment.platform !== "darwin") return false;
306 const owner = Electron.BrowserWindow.getFocusedWindow();
307 const opened = yield* shell.openSystemSettings(pane);
308 if (opened && environment.isPackaged) {
309 const permissions = yield* MacPermissions.MacPermissions;
310 const isGranted = yield* safariPermissionCheck;
311 yield* permissions.showHelper(pane, owner, isGranted);
312 }
313 return opened;
314 }),
315});
316
317export const probeRemoteEditors = DesktopIpc.makeIpcMethod({
318 channel: IpcChannels.PROBE_REMOTE_EDITORS_CHANNEL,
319 payload: Schema.Undefined,
320 result: Schema.Array(EditorId),
321 handler: Effect.fn("desktop.ipc.window.probeRemoteEditors")(function* () {
322 const available: Array<EditorId> = [];
323 const env = yield* HostProcess.Environment;
324 for (const editorId of REMOTE_CAPABLE_EDITOR_IDS) {
325 const editor = EDITORS.find((editor) => editor.id === editorId);
326 if (editor && Option.isSome(yield* resolveEditorCommand(editor, env))) {
327 available.push(editorId);
328 }
329 }
330 return available;
331 }),
332});
333
334export const pasteAsText = DesktopIpc.makeIpcMethod({
335 channel: IpcChannels.PASTE_AS_TEXT_CHANNEL,
336 payload: Schema.Undefined,
337 result: Schema.Void,
338 handler: Effect.fn("desktop.ipc.window.pasteAsText")(function* (_input, event) {
339 const electronWindow = yield* ElectronWindow.ElectronWindow;
340 const window = yield* electronWindow.main;
341 if (
342 event === undefined ||
343 Option.isNone(window) ||
344 window.value.isDestroyed() ||
345 window.value.webContents.id !== event.sender.id
346 ) {
347 return;
348 }
349 const focused = Electron.webContents.getFocusedWebContents();
350 if (
351 focused &&
352 !focused.isDestroyed() &&
353 Electron.BrowserWindow.fromWebContents(focused) === window.value
354 ) {
355 focused.paste();
356 }
357 }),
358});
359
360export const revealWindow = DesktopIpc.makeIpcMethod({
361 channel: IpcChannels.REVEAL_WINDOW_CHANNEL,
362 payload: Schema.Undefined,
363 result: Schema.Void,
364 handler: Effect.fn("desktop.ipc.window.revealWindow")(function* (_input, event) {
365 const electronWindow = yield* ElectronWindow.ElectronWindow;
366 const window = yield* electronWindow.main;
367 if (
368 event === undefined ||
369 Option.isNone(window) ||
370 window.value.webContents.id !== event.sender.id
371 ) {
372 return;
373 }
374 yield* electronWindow.reveal(window.value);
375 }),
376});
377
378const PICKED_THEME_FILE_MAX_BYTES = 256 * 1024;
379
380export const pickThemeFiles = DesktopIpc.makeIpcMethod({
381 channel: IpcChannels.PICK_THEME_FILES_CHANNEL,
382 payload: Schema.Undefined,
383 result: Schema.NullOr(Schema.Array(PickedThemeFileSchema)),
384 handler: Effect.fn("desktop.ipc.window.pickThemeFiles")(function* () {
385 const dialog = yield* ElectronDialog.ElectronDialog;
386 const electronWindow = yield* ElectronWindow.ElectronWindow;
387 const fileSystem = yield* FileSystem.FileSystem;
388 const path = yield* Path.Path;
389 const extensionsDir = path.join(yield* HostProcess.HomeDirectory, ".vscode", "extensions");
390 const defaultPath = yield* fileSystem
391 .exists(extensionsDir)
392 .pipe(Effect.orElseSucceed(() => false));
393 const paths = yield* dialog.pickFiles({
394 owner: yield* electronWindow.focusedMainOrFirst,
395 defaultPath: defaultPath ? Option.some(extensionsDir) : Option.none(),
396 filters: [{ name: "JSON", extensions: ["json"] }],
397 multiple: true,
398 });
399 if (paths.length === 0) {
400 return null;
401 }
402 return yield* Effect.forEach(paths, (filePath) => {
403 const name = path.basename(filePath);
404 return Effect.gen(function* () {
405 const info = yield* fileSystem.stat(filePath);
406 const size = Number(info.size);
407 if (size > PICKED_THEME_FILE_MAX_BYTES) {
408 return { name, size, text: "" } satisfies PickedThemeFile;
409 }
410 const text = yield* fileSystem.readFileString(filePath);
411 return { name, size, text } satisfies PickedThemeFile;
412 }).pipe(Effect.orElseSucceed((): PickedThemeFile => ({ name, size: 0, text: "" })));
413 });
414 }),
415});
416
417export const checkSystemPermission = DesktopIpc.makeIpcMethod({
418 channel: IpcChannels.CHECK_SYSTEM_PERMISSION_CHANNEL,
419 payload: SystemSettingsPaneSchema,
420 result: Schema.Boolean,
421 handler: Effect.fn("desktop.ipc.window.checkSystemPermission")(function* () {
422 const environment = yield* DesktopEnvironment.DesktopEnvironment;
423 if (environment.platform !== "darwin") return false;
424 const check = yield* safariPermissionCheck;
425 return yield* Effect.promise(check);
426 }),
427});