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