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