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 DesktopAppActivation from "./DesktopAppActivation.ts";
15import * as DesktopAppIdentity from "./DesktopAppIdentity.ts";
16import * as DesktopClerk from "./DesktopClerk.ts";
17import * as DesktopApplicationMenu from "../window/DesktopApplicationMenu.ts";
18import * as DesktopWindow from "../window/DesktopWindow.ts";
19import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
20import * as DesktopEnvironment from "./DesktopEnvironment.ts";
21import * as DesktopLifecycle from "./DesktopLifecycle.ts";
22import * as DesktopLinuxUrlHandler from "./DesktopLinuxUrlHandler.ts";
23import * as DesktopObservability from "./DesktopObservability.ts";
24import * as DesktopPreReadyPlatform from "./DesktopPreReadyPlatform.ts";
25import * as DesktopShutdown from "./DesktopShutdown.ts";
26import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
27import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
28import * as DesktopShellEnvironment from "../shell/DesktopShellEnvironment.ts";
29import * as DesktopState from "./DesktopState.ts";
30import * as DesktopRemoteUpdates from "../updates/DesktopRemoteUpdates.ts";
31import * as DesktopUpdates from "../updates/DesktopUpdates.ts";
32import * as DesktopWslBackend from "../wsl/DesktopWslBackend.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
144const bootstrap = Effect.gen(function* () {
145 const pool = yield* DesktopBackendPool.DesktopBackendPool;
146 const primaryBackend = yield* pool.primary;
147 const state = yield* DesktopState.DesktopState;
148 const environment = yield* DesktopEnvironment.DesktopEnvironment;
149 const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
150 const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
151 const wslBackend = yield* DesktopWslBackend.DesktopWslBackend;
152 const desktopWindow = yield* DesktopWindow.DesktopWindow;
153 const appActivation = yield* DesktopAppActivation.DesktopAppActivation;
154 yield* logBootstrapInfo("bootstrap start");
155
156 if (environment.isDevelopment && Option.isNone(environment.configuredBackendPort)) {
157 return yield* new DesktopDevelopmentBackendPortRequiredError();
158 }
159
160 const backendPortSelection = yield* resolveDesktopBackendPort(environment.configuredBackendPort);
161 const backendPort = backendPortSelection.port;
162 yield* logBootstrapInfo(
163 backendPortSelection.selectedByScan
164 ? "selected backend port via sequential scan"
165 : "using configured backend port",
166 {
167 port: backendPort,
168 ...(backendPortSelection.selectedByScan ? { startPort: DEFAULT_DESKTOP_BACKEND_PORT } : {}),
169 },
170 );
171
172 const settings = yield* desktopSettings.get;
173 if (settings.serverExposureMode !== environment.defaultDesktopSettings.serverExposureMode) {
174 yield* logBootstrapInfo("bootstrap restoring persisted server exposure mode", {
175 mode: settings.serverExposureMode,
176 });
177 }
178 const serverExposureState = yield* serverExposure.configureFromSettings({ port: backendPort });
179 const backendConfig = yield* serverExposure.backendConfig;
180 const electronProtocol = yield* ElectronProtocol.ElectronProtocol;
181 const rendererTarget = environment.isDevelopment
182 ? Option.getOrThrow(environment.devServerUrl)
183 : backendConfig.httpBaseUrl;
184 yield* electronProtocol.registerDesktopProtocol({
185 scheme: ElectronProtocol.getDesktopScheme(environment.isDevelopment),
186 targetOrigin: rendererTarget,
187 backendOrigin: backendConfig.httpBaseUrl,
188 clerkFrontendApiHostname: DesktopClerk.desktopClerkFrontendApiHostname,
189 });
190 yield* logBootstrapInfo("bootstrap resolved backend endpoint", {
191 baseUrl: backendConfig.httpBaseUrl.href,
192 });
193 if (serverExposureState.endpointUrl) {
194 yield* logBootstrapInfo("bootstrap enabled network access", {
195 endpointUrl: serverExposureState.endpointUrl,
196 });
197 } else if (
198 settings.serverExposureMode === "network-accessible" &&
199 serverExposureState.mode === "local-only"
200 ) {
201 yield* logBootstrapWarning(
202 "bootstrap fell back to local-only because no advertised network host was available",
203 );
204 }
205
206 yield* installDesktopIpcHandlers();
207 yield* logBootstrapInfo("bootstrap ipc handlers registered");
208
209 if (!(yield* Ref.get(state.quitting))) {
210 // In wsl-only mode the renderer is served by the WSL backend, which can be
211 // slow to cold-boot — show a "Connecting to WSL" splash immediately so the
212 // app feels responsive instead of presenting no window until WSL is ready.
213 // (Dual mode opens fast off the Windows primary, so no splash there.)
214 if (settings.wslOnly === true && settings.wslBackendEnabled === true) {
215 yield* desktopWindow.showConnectingSplash;
216 }
217 yield* primaryBackend.start;
218 yield* logBootstrapInfo("bootstrap backend start requested");
219 yield* appActivation.start.pipe(
220 Effect.tap(() => logBootstrapInfo("desktop app control socket ready")),
221 Effect.catch((error) => logStartupError("desktop app control socket unavailable", { error })),
222 );
223 // Bring up the WSL backend if the user previously enabled it. The
224 // primary is already starting; reconcile fires off the WSL register
225 // in parallel rather than blocking primary readiness on a possibly
226 // slow first wsl.exe spawn.
227 yield* Effect.forkScoped(wslBackend.reconcile);
228 }
229}).pipe(Effect.withSpan("desktop.bootstrap"));
230
231const startup = Effect.gen(function* () {
232 const appIdentity = yield* DesktopAppIdentity.DesktopAppIdentity;
233 const applicationMenu = yield* DesktopApplicationMenu.DesktopApplicationMenu;
234 const electronApp = yield* ElectronApp.ElectronApp;
235 const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
236 const linuxUrlHandler = yield* DesktopLinuxUrlHandler.DesktopLinuxUrlHandler;
237 const clerk = yield* DesktopClerk.DesktopClerk;
238 const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
239 const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
240 const preReadyElectronOptions = yield* DesktopPreReadyPlatform.DesktopPreReadyElectronOptions;
241 const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
242 const updates = yield* DesktopUpdates.DesktopUpdates;
243 const environment = yield* DesktopEnvironment.DesktopEnvironment;
244
245 yield* shellEnvironment.installIntoProcess;
246 const hasCommandLinePasswordStore =
247 preReadyElectronOptions.linuxPasswordStoreCommandLine !== null;
248 const linuxElectronOptions =
249 environment.platform === "linux" && !hasCommandLinePasswordStore
250 ? DesktopPreReadyPlatform.resolveEarlyLinuxElectronOptionsFromProcess()
251 : preReadyElectronOptions.linux;
252 if (linuxElectronOptions !== null && !hasCommandLinePasswordStore) {
253 if (
254 linuxElectronOptions.passwordStore !== null ||
255 preReadyElectronOptions.linux?.passwordStore !== null
256 ) {
257 yield* electronApp.removeCommandLineSwitch("password-store");
258 }
259 if (linuxElectronOptions.passwordStore !== null) {
260 yield* electronApp.appendCommandLineSwitch(
261 "password-store",
262 linuxElectronOptions.passwordStore,
263 );
264 }
265 }
266 const userDataPath = yield* appIdentity.resolveUserDataPath;
267 yield* electronApp.setPath("userData", userDataPath);
268 yield* logStartupInfo("runtime logging configured", { logDir: environment.logDir });
269 yield* desktopSettings.load;
270
271 if (linuxElectronOptions !== null) {
272 yield* logStartupInfo("linux password store configured", {
273 passwordStore: hasCommandLinePasswordStore
274 ? "command-line"
275 : (linuxElectronOptions.passwordStore ?? "electron-default"),
276 xdgCurrentDesktop: process.env.XDG_CURRENT_DESKTOP ?? null,
277 xdgSessionDesktop: process.env.XDG_SESSION_DESKTOP ?? null,
278 });
279 }
280
281 yield* appIdentity.configure;
282 yield* lifecycle.register;
283 yield* clerk.configure;
284
285 yield* electronApp.whenReady.pipe(
286 Effect.withSpan("desktop.electron.whenReady"),
287 Effect.catchCause((cause) => fatalStartupCause("whenReady", cause)),
288 );
289 yield* logStartupInfo("app ready");
290 if (environment.platform === "linux") {
291 const selectedBackend = yield* safeStorage.selectedStorageBackend;
292 yield* logStartupInfo("safe storage ready", {
293 backend: Option.getOrElse(selectedBackend, () => "unknown"),
294 });
295 }
296 yield* appIdentity.configure;
297 yield* applicationMenu.configure;
298 yield* updates.configure;
299 yield* DesktopRemoteUpdates.listen;
300 yield* linuxUrlHandler.register;
301 yield* bootstrap.pipe(Effect.catchCause((cause) => fatalStartupCause("bootstrap", cause)));
302}).pipe(Effect.withSpan("desktop.startup"));
303
304const scopedProgram = Effect.scoped(
305 Effect.gen(function* () {
306 const runId = yield* makeDesktopRunId;
307 yield* Effect.annotateLogsScoped({ scope: "desktop", runId });
308 yield* Effect.annotateCurrentSpan({ scope: "desktop", runId });
309
310 const shutdown = yield* DesktopShutdown.DesktopShutdown;
311
312 yield* Effect.addFinalizer(() =>
313 Effect.gen(function* () {
314 const pool = yield* DesktopBackendPool.DesktopBackendPool;
315 // Stop every backend in the pool, not just the primary. The
316 // electronApp.quit() path can race ahead of the layer-scope
317 // cascade, so leaving the WSL instance for its parent scope
318 // finalizer means it gets hard-killed by the OS instead of
319 // receiving SIGTERM + grace. Stops run concurrently.
320 const instances = yield* pool.list;
321 yield* Effect.forEach(instances, (instance) => instance.stop(), {
322 concurrency: "unbounded",
323 });
324 }).pipe(Effect.ensuring(shutdown.markComplete)),
325 );
326
327 yield* startup;
328 yield* shutdown.awaitRequest;
329 }),
330);
331
332export const program = scopedProgram.pipe(Effect.withSpan("desktop.app"));