Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

DesktopApp.ts

355 lines14.3 KB

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