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

DesktopApp.ts

335 lines13.6 KB

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