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

DesktopApp.ts

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