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