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