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