Open History to see the last commit
1import * as Cause from "effect/Cause";
2import * as Duration from "effect/Duration";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import * as Option from "effect/Option";
6import * as Path from "effect/Path";
7import * as Ref from "effect/Ref";
8import * as Schema from "effect/Schema";
9
10import type { DesktopBackendMode as DesktopBackendModeValue } from "@t3tools/contracts";
11import * as NetService from "@t3tools/shared/Net";
12import * as Crypto from "effect/Crypto";
13import * as ElectronApp from "../electron/ElectronApp.ts";
14import * as ElectronDialog from "../electron/ElectronDialog.ts";
15import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
16import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
17import { installDesktopIpcHandlers } from "../ipc/DesktopIpcHandlers.ts";
18import * as DesktopAppActivation from "./DesktopAppActivation.ts";
19import * as DesktopAppIdentity from "./DesktopAppIdentity.ts";
20import * as DesktopBackendMode from "./DesktopBackendMode.ts";
21import * as DesktopClerk from "./DesktopClerk.ts";
22import * as DesktopApplicationMenu from "../window/DesktopApplicationMenu.ts";
23import * as DesktopWindow from "../window/DesktopWindow.ts";
24import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
25import * as DesktopEnvironment from "./DesktopEnvironment.ts";
26import * as DesktopLifecycle from "./DesktopLifecycle.ts";
27import * as DesktopLinuxUrlHandler from "./DesktopLinuxUrlHandler.ts";
28import * as DesktopObservability from "./DesktopObservability.ts";
29import * as DesktopPreReadyPlatform from "./DesktopPreReadyPlatform.ts";
30import * as DesktopRunningLocalServers from "./DesktopRunningLocalServers.ts";
31import * as DesktopShutdown from "./DesktopShutdown.ts";
32import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
33import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
34import * as DesktopShellEnvironment from "../shell/DesktopShellEnvironment.ts";
35import * as DesktopState from "./DesktopState.ts";
36import * as DesktopRemoteUpdates from "../updates/DesktopRemoteUpdates.ts";
37import * as DesktopUpdates from "../updates/DesktopUpdates.ts";
38import * as DesktopSnapShot from "../snapShot/DesktopSnapShot.ts";
39import * as DesktopWslBackend from "../wsl/DesktopWslBackend.ts";
40
41const DEFAULT_DESKTOP_BACKEND_PORT = 3773;
42const MAX_TCP_PORT = 65_535;
43const DESKTOP_BACKEND_PORT_PROBE_HOSTS = ["127.0.0.1", "0.0.0.0", "::"] as const;
44
45const makeDesktopRunId = Crypto.Crypto.pipe(
46 Effect.flatMap((crypto) => crypto.randomUUIDv4),
47 Effect.map((value) => value.replaceAll("-", "").slice(0, 12)),
48);
49
50export class DesktopBackendPortUnavailableError extends Schema.TaggedError<DesktopBackendPortUnavailableError>()(
51 "DesktopBackendPortUnavailableError",
52 {
53 startPort: Schema.Int,
54 maxPort: Schema.Int,
55 hosts: Schema.Array(Schema.String),
56 },
57) {
58 override get message(): string {
59 return `No desktop backend port is available on hosts ${this.hosts.join(", ")} between ${this.startPort} and ${this.maxPort}.`;
60 }
61}
62
63export class DesktopDevelopmentBackendPortRequiredError extends Schema.TaggedError<DesktopDevelopmentBackendPortRequiredError>()(
64 "DesktopDevelopmentBackendPortRequiredError",
65 {},
66) {
67 override get message(): string {
68 return "T3CODE_PORT is required in desktop development.";
69 }
70}
71
72export class DesktopRendererAssetsUnavailableError extends Schema.TaggedErrorClass<DesktopRendererAssetsUnavailableError>()(
73 "DesktopRendererAssetsUnavailableError",
74 {
75 candidates: Schema.Array(Schema.String),
76 },
77) {
78 override get message(): string {
79 return `The packaged desktop renderer was not found. Checked: ${this.candidates.join(", ")}.`;
80 }
81}
82
83const { logInfo: logBootstrapInfo, logWarning: logBootstrapWarning } =
84 DesktopObservability.makeComponentLogger("desktop-bootstrap");
85
86const { logInfo: logStartupInfo, logError: logStartupError } =
87 DesktopObservability.makeComponentLogger("desktop-startup");
88
89const resolveDesktopBackendPort = Effect.fn("resolveDesktopBackendPort")(function* (
90 configuredPort: Option.Option<number>,
91) {
92 if (Option.isSome(configuredPort)) {
93 return {
94 port: configuredPort.value,
95 selectedByScan: false,
96 } as const;
97 }
98
99 const net = yield* NetService.NetService;
100 for (let port = DEFAULT_DESKTOP_BACKEND_PORT; port <= MAX_TCP_PORT; port += 1) {
101 let availableOnEveryHost = true;
102
103 for (const host of DESKTOP_BACKEND_PORT_PROBE_HOSTS) {
104 if (!(yield* net.canListenOnHost(port, host))) {
105 availableOnEveryHost = false;
106 break;
107 }
108 }
109
110 if (availableOnEveryHost) {
111 return {
112 port,
113 selectedByScan: true,
114 } as const;
115 }
116 }
117
118 return yield* new DesktopBackendPortUnavailableError({
119 startPort: DEFAULT_DESKTOP_BACKEND_PORT,
120 maxPort: MAX_TCP_PORT,
121 hosts: DESKTOP_BACKEND_PORT_PROBE_HOSTS,
122 });
123});
124
125const handleFatalStartupError = Effect.fn("desktop.startup.handleFatalStartupError")(function* (
126 stage: string,
127 error: unknown,
128): Effect.fn.Return<
129 void,
130 never,
131 | DesktopShutdown.DesktopShutdown
132 | DesktopState.DesktopState
133 | ElectronApp.ElectronApp
134 | ElectronDialog.ElectronDialog
135> {
136 const shutdown = yield* DesktopShutdown.DesktopShutdown;
137 const state = yield* DesktopState.DesktopState;
138 const electronApp = yield* ElectronApp.ElectronApp;
139 const electronDialog = yield* ElectronDialog.ElectronDialog;
140 const message = error instanceof Error ? error.message : String(error);
141 const detail =
142 error instanceof Error && typeof error.stack === "string" ? `\n${error.stack}` : "";
143 yield* logStartupError("fatal startup error", {
144 stage,
145 message,
146 ...(detail.length > 0 ? { detail } : {}),
147 });
148 const wasQuitting = yield* Ref.getAndSet(state.quitting, true);
149 if (!wasQuitting) {
150 yield* electronDialog.showErrorBox(
151 "T3 Code failed to start",
152 `Stage: ${stage}\n${message}${detail}`,
153 );
154 }
155 yield* shutdown.request;
156 yield* electronApp.quit;
157});
158
159const fatalStartupCause = <E>(stage: string, cause: Cause.Cause<E>) =>
160 handleFatalStartupError(stage, Cause.pretty(cause)).pipe(Effect.andThen(Effect.failCause(cause)));
161
162export const stopAllPoolInstances = Effect.fn("desktop.app.stopAllPoolInstances")(
163 function* (): Effect.fn.Return<void, never, DesktopBackendPool.DesktopBackendPool> {
164 // Stop every backend in the pool with a timeout to guarantee the quit
165 // path makes progress even if a backend hangs during teardown.
166 const pool = yield* DesktopBackendPool.DesktopBackendPool;
167 const instances = yield* pool.list;
168 yield* Effect.forEach(
169 instances,
170 (instance) => instance.stop({ timeout: Duration.seconds(5) }),
171 { concurrency: "unbounded" },
172 );
173 },
174);
175
176export const latchDesktopBackendModeForStartup = Effect.fn(
177 "desktop.startup.latchDesktopBackendMode",
178)(function* (configuredMode: DesktopBackendModeValue) {
179 const backendMode = yield* DesktopBackendMode.DesktopBackendMode;
180 return yield* backendMode
181 .latch(configuredMode)
182 .pipe(Effect.catchCause((cause) => fatalStartupCause("backendMode", cause)));
183});
184
185export const handleClientOnlyRendererReady = <E extends { readonly message: string }>(
186 rendererReady: Effect.Effect<void, E>,
187): Effect.Effect<void, E> =>
188 rendererReady.pipe(
189 Effect.tapError((error) =>
190 logBootstrapWarning("failed to open main window after renderer readiness", {
191 error: error.message,
192 }),
193 ),
194 );
195
196const resolvePackagedClientRoot = Effect.fn("desktop.bootstrap.resolvePackagedClientRoot")(
197 function* (candidates: readonly string[]) {
198 const fileSystem = yield* FileSystem.FileSystem;
199 const path = yield* Path.Path;
200 for (const candidate of candidates) {
201 if (
202 yield* fileSystem
203 .exists(path.join(candidate, "index.html"))
204 .pipe(Effect.orElseSucceed(() => false))
205 ) {
206 return candidate;
207 }
208 }
209 return yield* new DesktopRendererAssetsUnavailableError({ candidates: [...candidates] });
210 },
211);
212const bootstrap = Effect.gen(function* () {
213 const launchMode = yield* DesktopBackendMode.DesktopBackendMode;
214 const state = yield* DesktopState.DesktopState;
215 const environment = yield* DesktopEnvironment.DesktopEnvironment;
216 const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
217 const desktopWindow = yield* DesktopWindow.DesktopWindow;
218 const snapShot = yield* DesktopSnapShot.DesktopSnapShot;
219 const appActivation = yield* DesktopAppActivation.DesktopAppActivation;
220 const electronProtocol = yield* ElectronProtocol.ElectronProtocol;
221 const backendMode = (yield* launchMode.get).effectiveMode;
222 yield* logBootstrapInfo("bootstrap start");
223
224 const settings = yield* desktopSettings.get;
225
226 if (backendMode === "client-only") {
227 if (environment.isDevelopment) {
228 yield* electronProtocol.registerDesktopProtocol({
229 scheme: ElectronProtocol.getDesktopScheme(true),
230 source: "proxy",
231 targetOrigin: Option.getOrThrow(environment.devServerUrl),
232 clerkFrontendApiHostname: DesktopClerk.desktopClerkFrontendApiHostname,
233 });
234 } else {
235 const staticRoot = yield* resolvePackagedClientRoot(environment.packagedClientRootCandidates);
236 yield* electronProtocol.registerDesktopProtocol({
237 scheme: ElectronProtocol.getDesktopScheme(false),
238 source: "static",
239 staticRoot,
240 clerkFrontendApiHostname: DesktopClerk.desktopClerkFrontendApiHostname,
241 });
242 yield* logBootstrapInfo("bootstrap resolved packaged renderer", { staticRoot });
243 }
244
245 yield* installDesktopIpcHandlers();
246 yield* logBootstrapInfo("bootstrap ipc handlers registered");
247 if (!(yield* Ref.get(state.quitting))) {
248 yield* appActivation.start.pipe(
249 Effect.tap(() => logBootstrapInfo("desktop app control socket ready")),
250 Effect.catch((error) =>
251 logStartupError("desktop app control socket unavailable", { error }),
252 ),
253 );
254 yield* handleClientOnlyRendererReady(desktopWindow.handleRendererReady);
255 }
256 return;
257 }
258
259 // The renderer is served from the bundled client (or Vite in development)
260 // rather than through the local backend, so the window can open without one.
261 yield* electronProtocol.registerDesktopProtocol({
262 scheme: ElectronProtocol.getDesktopScheme(environment.isDevelopment),
263 ...(environment.isDevelopment
264 ? { targetOrigin: Option.getOrThrow(environment.devServerUrl) }
265 : { assetDirectory: environment.clientAssetsDir }),
266 clerkFrontendApiHostname: DesktopClerk.desktopClerkFrontendApiHostname,
267 });
268 yield* installDesktopIpcHandlers();
269 yield* logBootstrapInfo("bootstrap ipc handlers registered");
270
271 yield* snapShot.initialize;
272
273 if (!settings.localEnvironmentEnabled) {
274 yield* logBootstrapInfo("bootstrap skipping local environment (disabled in settings)");
275 if (!(yield* Ref.get(state.quitting))) {
276 yield* desktopWindow.createMainIfBackendReady;
277 }
278 return;
279 }
280
281 if (environment.isDevelopment && Option.isNone(environment.configuredBackendPort)) {
282 return yield* new DesktopDevelopmentBackendPortRequiredError();
283 }
284
285 const pool = yield* DesktopBackendPool.DesktopBackendPool;
286 const primaryBackend = yield* pool.primary;
287 const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
288 const wslBackend = yield* DesktopWslBackend.DesktopWslBackend;
289 const backendPortSelection = yield* resolveDesktopBackendPort(environment.configuredBackendPort);
290 const backendPort = backendPortSelection.port;
291 yield* logBootstrapInfo(
292 backendPortSelection.selectedByScan
293 ? "selected backend port via sequential scan"
294 : "using configured backend port",
295 {
296 port: backendPort,
297 ...(backendPortSelection.selectedByScan ? { startPort: DEFAULT_DESKTOP_BACKEND_PORT } : {}),
298 },
299 );
300
301 if (settings.serverExposureMode !== environment.defaultDesktopSettings.serverExposureMode) {
302 yield* logBootstrapInfo("bootstrap restoring persisted server exposure mode", {
303 mode: settings.serverExposureMode,
304 });
305 }
306 const serverExposureState = yield* serverExposure.configureFromSettings({ port: backendPort });
307 const backendConfig = yield* serverExposure.backendConfig;
308 const rendererTarget = environment.isDevelopment
309 ? Option.getOrThrow(environment.devServerUrl)
310 : backendConfig.httpBaseUrl;
311 yield* electronProtocol.registerDesktopProtocol({
312 scheme: ElectronProtocol.getDesktopScheme(environment.isDevelopment),
313 source: "proxy",
314 targetOrigin: rendererTarget,
315 clerkFrontendApiHostname: DesktopClerk.desktopClerkFrontendApiHostname,
316 });
317 yield* logBootstrapInfo("bootstrap resolved backend endpoint", {
318 baseUrl: backendConfig.httpBaseUrl.href,
319 });
320 if (serverExposureState.endpointUrl) {
321 yield* logBootstrapInfo("bootstrap enabled network access", {
322 endpointUrl: serverExposureState.endpointUrl,
323 });
324 } else if (
325 settings.serverExposureMode === "network-accessible" &&
326 serverExposureState.mode === "local-only"
327 ) {
328 yield* logBootstrapWarning(
329 "bootstrap fell back to local-only because no advertised network host was available",
330 );
331 }
332
333 if (!(yield* Ref.get(state.quitting))) {
334 // The main window waits for the primary backend. In wsl-only mode that is
335 // the WSL backend, which can be slow to cold-boot — show a "Connecting to
336 // WSL" splash immediately so the app feels responsive instead of presenting
337 // no window until WSL is ready. (Dual mode opens fast off the Windows
338 // primary, so no splash there.)
339 if (settings.wslOnly === true && settings.wslBackendEnabled === true) {
340 yield* desktopWindow.showConnectingSplash;
341 }
342 yield* primaryBackend.start;
343 yield* logBootstrapInfo("bootstrap backend start requested");
344 yield* appActivation.start.pipe(
345 Effect.tap(() => logBootstrapInfo("desktop app control socket ready")),
346 Effect.catch((error) => logStartupError("desktop app control socket unavailable", { error })),
347 );
348 // Bring up the WSL backend if the user previously enabled it. The
349 // primary is already starting; reconcile fires off the WSL register
350 // in parallel rather than blocking primary readiness on a possibly
351 // slow first wsl.exe spawn.
352 yield* Effect.forkScoped(wslBackend.reconcile);
353 }
354}).pipe(Effect.withSpan("desktop.bootstrap"));
355
356const startup = Effect.gen(function* () {
357 const appIdentity = yield* DesktopAppIdentity.DesktopAppIdentity;
358 const applicationMenu = yield* DesktopApplicationMenu.DesktopApplicationMenu;
359 const electronApp = yield* ElectronApp.ElectronApp;
360 const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
361 const linuxUrlHandler = yield* DesktopLinuxUrlHandler.DesktopLinuxUrlHandler;
362 const clerk = yield* DesktopClerk.DesktopClerk;
363 const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
364 const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
365 const preReadyElectronOptions = yield* DesktopPreReadyPlatform.DesktopPreReadyElectronOptions;
366 const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
367 const updates = yield* DesktopUpdates.DesktopUpdates;
368 const environment = yield* DesktopEnvironment.DesktopEnvironment;
369
370 yield* shellEnvironment.installIntoProcess;
371 const hasCommandLinePasswordStore =
372 preReadyElectronOptions.linuxPasswordStoreCommandLine !== null;
373 const linuxElectronOptions =
374 environment.platform === "linux" && !hasCommandLinePasswordStore
375 ? DesktopPreReadyPlatform.resolveEarlyLinuxElectronOptionsFromProcess()
376 : preReadyElectronOptions.linux;
377 if (linuxElectronOptions !== null && !hasCommandLinePasswordStore) {
378 if (
379 linuxElectronOptions.passwordStore !== null ||
380 preReadyElectronOptions.linux?.passwordStore !== null
381 ) {
382 yield* electronApp.removeCommandLineSwitch("password-store");
383 }
384 if (linuxElectronOptions.passwordStore !== null) {
385 yield* electronApp.appendCommandLineSwitch(
386 "password-store",
387 linuxElectronOptions.passwordStore,
388 );
389 }
390 }
391 const userDataPath = yield* appIdentity.resolveUserDataPath;
392 yield* electronApp.setPath("userData", userDataPath);
393 yield* logStartupInfo("runtime logging configured", { logDir: environment.logDir });
394 const settings = yield* desktopSettings.load;
395 const latchedLaunchMode = yield* latchDesktopBackendModeForStartup(settings.backendMode);
396 const existingServer =
397 latchedLaunchMode.effectiveMode === "managed" && !environment.isDevelopment
398 ? (yield* (yield* DesktopRunningLocalServers.DesktopRunningLocalServers).discover).find(
399 (server) => server.variant === "userdata",
400 )
401 : undefined;
402 const backendMode = yield* DesktopBackendMode.DesktopBackendMode;
403 const launchMode = yield* backendMode.resolveExistingServer({
404 isDevelopment: environment.isDevelopment,
405 hasRunningUserdataServer: existingServer !== undefined,
406 });
407 yield* logStartupInfo("desktop backend mode selected", {
408 effectiveMode: launchMode.effectiveMode,
409 configuredMode: launchMode.configuredMode,
410 source: launchMode.source,
411 ...(launchMode.cliOverride === null ? {} : { cliOverride: launchMode.cliOverride }),
412 });
413 if (launchMode.source === "existing-server" && existingServer !== undefined) {
414 yield* logStartupInfo("using existing local server instead of starting managed backend", {
415 environmentId: existingServer.environmentId,
416 origin: existingServer.httpBaseUrl,
417 pid: existingServer.pid,
418 statePath: existingServer.statePath,
419 });
420 }
421
422 if (linuxElectronOptions !== null) {
423 yield* logStartupInfo("linux password store configured", {
424 passwordStore: hasCommandLinePasswordStore
425 ? "command-line"
426 : (linuxElectronOptions.passwordStore ?? "electron-default"),
427 xdgCurrentDesktop: process.env.XDG_CURRENT_DESKTOP ?? null,
428 xdgSessionDesktop: process.env.XDG_SESSION_DESKTOP ?? null,
429 });
430 }
431
432 yield* appIdentity.configure;
433 yield* lifecycle.register;
434 yield* clerk.configure;
435
436 yield* electronApp.whenReady.pipe(
437 Effect.withSpan("desktop.electron.whenReady"),
438 Effect.catchCause((cause) => fatalStartupCause("whenReady", cause)),
439 );
440 yield* logStartupInfo("app ready");
441 if (environment.platform === "linux") {
442 const selectedBackend = yield* safeStorage.selectedStorageBackend;
443 yield* logStartupInfo("safe storage ready", {
444 backend: Option.getOrElse(selectedBackend, () => "unknown"),
445 });
446 }
447 yield* appIdentity.configure;
448 yield* applicationMenu.configure;
449 yield* updates.configure;
450 yield* DesktopRemoteUpdates.listen;
451 yield* linuxUrlHandler.register;
452 yield* bootstrap.pipe(Effect.catchCause((cause) => fatalStartupCause("bootstrap", cause)));
453}).pipe(Effect.withSpan("desktop.startup"));
454
455const scopedProgram = Effect.scoped(
456 Effect.gen(function* () {
457 const runId = yield* makeDesktopRunId;
458 yield* Effect.annotateLogsScoped({ scope: "desktop", runId });
459 yield* Effect.annotateCurrentSpan({ scope: "desktop", runId });
460
461 const shutdown = yield* DesktopShutdown.DesktopShutdown;
462
463 yield* Effect.addFinalizer(() =>
464 Effect.gen(function* () {
465 const backendMode = yield* DesktopBackendMode.DesktopBackendMode;
466 if ((yield* backendMode.get).effectiveMode === "client-only") {
467 return;
468 }
469 // Stop every backend in the pool, not just the primary. The
470 // electronApp.quit() path can race ahead of the layer-scope
471 // cascade, so leaving the WSL instance for its parent scope
472 // finalizer means it gets hard-killed by the OS instead of
473 // receiving SIGTERM + grace.
474 yield* stopAllPoolInstances();
475 }).pipe(Effect.ensuring(shutdown.markComplete)),
476 );
477
478 yield* startup;
479 yield* shutdown.awaitRequest;
480 }),
481);
482
483export const program = scopedProgram.pipe(Effect.withSpan("desktop.app"));