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