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 { installDesktopIpcHandlers } from "../ipc/DesktopIpcHandlers.ts";
13import * as DesktopAppIdentity from "./DesktopAppIdentity.ts";
14import * as DesktopClerk from "./DesktopClerk.ts";
15import * as DesktopApplicationMenu from "../window/DesktopApplicationMenu.ts";
16import * as DesktopWindow from "../window/DesktopWindow.ts";
17import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
18import * as DesktopEnvironment from "./DesktopEnvironment.ts";
19import * as DesktopLifecycle from "./DesktopLifecycle.ts";
20import * as DesktopObservability from "./DesktopObservability.ts";
21import * as DesktopShutdown from "./DesktopShutdown.ts";
22import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
23import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
24import * as DesktopClientSettings from "../settings/DesktopClientSettings.ts";
25import * as DesktopShellEnvironment from "../shell/DesktopShellEnvironment.ts";
26import * as DesktopState from "./DesktopState.ts";
27import * as DesktopUpdates from "../updates/DesktopUpdates.ts";
28import * as DesktopWslBackend from "../wsl/DesktopWslBackend.ts";
29import {
30 configureCuaDriverServerEnvironment,
31 disableCuaDriverServerEnvironment,
32} from "../cua/CuaDriverServerEnvironment.ts";
33
34const DEFAULT_DESKTOP_BACKEND_PORT = 3773;
35const MAX_TCP_PORT = 65_535;
36const DESKTOP_BACKEND_PORT_PROBE_HOSTS = ["127.0.0.1", "0.0.0.0", "::"] as const;
37
38const makeDesktopRunId = Crypto.Crypto.pipe(
39 Effect.flatMap((crypto) => crypto.randomUUIDv4),
40 Effect.map((value) => value.replaceAll("-", "").slice(0, 12)),
41);
42
43export class DesktopBackendPortUnavailableError extends Schema.TaggedErrorClass<DesktopBackendPortUnavailableError>()(
44 "DesktopBackendPortUnavailableError",
45 {
46 startPort: Schema.Int,
47 maxPort: Schema.Int,
48 hosts: Schema.Array(Schema.String),
49 },
50) {
51 override get message(): string {
52 return `No desktop backend port is available on hosts ${this.hosts.join(", ")} between ${this.startPort} and ${this.maxPort}.`;
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
71const resolveDesktopBackendPort = Effect.fn("resolveDesktopBackendPort")(function* (
72 configuredPort: Option.Option<number>,
73) {
74 if (Option.isSome(configuredPort)) {
75 return {
76 port: configuredPort.value,
77 selectedByScan: false,
78 } as const;
79 }
80
81 const net = yield* NetService.NetService;
82 for (let port = DEFAULT_DESKTOP_BACKEND_PORT; port <= MAX_TCP_PORT; port += 1) {
83 let availableOnEveryHost = true;
84
85 for (const host of DESKTOP_BACKEND_PORT_PROBE_HOSTS) {
86 if (!(yield* net.canListenOnHost(port, host))) {
87 availableOnEveryHost = false;
88 break;
89 }
90 }
91
92 if (availableOnEveryHost) {
93 return {
94 port,
95 selectedByScan: true,
96 } as const;
97 }
98 }
99
100 return yield* new DesktopBackendPortUnavailableError({
101 startPort: DEFAULT_DESKTOP_BACKEND_PORT,
102 maxPort: MAX_TCP_PORT,
103 hosts: DESKTOP_BACKEND_PORT_PROBE_HOSTS,
104 });
105});
106
107const handleFatalStartupError = Effect.fn("desktop.startup.handleFatalStartupError")(function* (
108 stage: string,
109 error: unknown,
110): Effect.fn.Return<
111 void,
112 never,
113 | DesktopShutdown.DesktopShutdown
114 | DesktopState.DesktopState
115 | ElectronApp.ElectronApp
116 | ElectronDialog.ElectronDialog
117> {
118 const shutdown = yield* DesktopShutdown.DesktopShutdown;
119 const state = yield* DesktopState.DesktopState;
120 const electronApp = yield* ElectronApp.ElectronApp;
121 const electronDialog = yield* ElectronDialog.ElectronDialog;
122 const message = error instanceof Error ? error.message : String(error);
123 const detail =
124 error instanceof Error && typeof error.stack === "string" ? `\n${error.stack}` : "";
125 yield* logStartupError("fatal startup error", {
126 stage,
127 message,
128 ...(detail.length > 0 ? { detail } : {}),
129 });
130 const wasQuitting = yield* Ref.getAndSet(state.quitting, true);
131 if (!wasQuitting) {
132 yield* electronDialog.showErrorBox(
133 "T3 Code failed to start",
134 `Stage: ${stage}\n${message}${detail}`,
135 );
136 }
137 yield* shutdown.request;
138 yield* electronApp.quit;
139});
140
141const fatalStartupCause = <E>(stage: string, cause: Cause.Cause<E>) =>
142 handleFatalStartupError(stage, Cause.pretty(cause)).pipe(Effect.andThen(Effect.failCause(cause)));
143
144const bootstrap = Effect.gen(function* () {
145 const pool = yield* DesktopBackendPool.DesktopBackendPool;
146 const primaryBackend = yield* pool.primary;
147 const state = yield* DesktopState.DesktopState;
148 const environment = yield* DesktopEnvironment.DesktopEnvironment;
149 const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
150 const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
151 const wslBackend = yield* DesktopWslBackend.DesktopWslBackend;
152 const desktopWindow = yield* DesktopWindow.DesktopWindow;
153 yield* logBootstrapInfo("bootstrap start");
154
155 if (environment.isDevelopment && Option.isNone(environment.configuredBackendPort)) {
156 return yield* new DesktopDevelopmentBackendPortRequiredError();
157 }
158
159 const backendPortSelection = yield* resolveDesktopBackendPort(environment.configuredBackendPort);
160 const backendPort = backendPortSelection.port;
161 yield* logBootstrapInfo(
162 backendPortSelection.selectedByScan
163 ? "selected backend port via sequential scan"
164 : "using configured backend port",
165 {
166 port: backendPort,
167 ...(backendPortSelection.selectedByScan ? { startPort: DEFAULT_DESKTOP_BACKEND_PORT } : {}),
168 },
169 );
170
171 const settings = yield* desktopSettings.get;
172 if (settings.serverExposureMode !== environment.defaultDesktopSettings.serverExposureMode) {
173 yield* logBootstrapInfo("bootstrap restoring persisted server exposure mode", {
174 mode: settings.serverExposureMode,
175 });
176 }
177 const serverExposureState = yield* serverExposure.configureFromSettings({ port: backendPort });
178 const backendConfig = yield* serverExposure.backendConfig;
179 const electronProtocol = yield* ElectronProtocol.ElectronProtocol;
180 const rendererTarget = environment.isDevelopment
181 ? Option.getOrThrow(environment.devServerUrl)
182 : backendConfig.httpBaseUrl;
183 yield* electronProtocol.registerDesktopProtocol({
184 scheme: ElectronProtocol.getDesktopScheme(environment.isDevelopment),
185 targetOrigin: rendererTarget,
186 backendOrigin: backendConfig.httpBaseUrl,
187 clerkFrontendApiHostname: DesktopClerk.desktopClerkFrontendApiHostname,
188 });
189 yield* logBootstrapInfo("bootstrap resolved backend endpoint", {
190 baseUrl: backendConfig.httpBaseUrl.href,
191 });
192 if (serverExposureState.endpointUrl) {
193 yield* logBootstrapInfo("bootstrap enabled network access", {
194 endpointUrl: serverExposureState.endpointUrl,
195 });
196 } else if (settings.serverExposureMode === "network-accessible") {
197 yield* logBootstrapWarning(
198 "bootstrap fell back to local-only because no advertised network host was available",
199 );
200 }
201
202 yield* installDesktopIpcHandlers();
203 yield* logBootstrapInfo("bootstrap ipc handlers registered");
204
205 if (!(yield* Ref.get(state.quitting))) {
206 // In wsl-only mode the renderer is served by the WSL backend, which can be
207 // slow to cold-boot — show a "Connecting to WSL" splash immediately so the
208 // app feels responsive instead of presenting no window until WSL is ready.
209 // (Dual mode opens fast off the Windows primary, so no splash there.)
210 if (settings.wslOnly === true && settings.wslBackendEnabled === true) {
211 yield* desktopWindow.showConnectingSplash;
212 }
213 yield* primaryBackend.start;
214 yield* logBootstrapInfo("bootstrap backend start requested");
215 // Bring up the WSL backend if the user previously enabled it. The
216 // primary is already starting; reconcile fires off the WSL register
217 // in parallel rather than blocking primary readiness on a possibly
218 // slow first wsl.exe spawn.
219 yield* Effect.forkScoped(wslBackend.reconcile);
220 }
221}).pipe(Effect.withSpan("desktop.bootstrap"));
222
223const startup = Effect.gen(function* () {
224 const appIdentity = yield* DesktopAppIdentity.DesktopAppIdentity;
225 const applicationMenu = yield* DesktopApplicationMenu.DesktopApplicationMenu;
226 const electronApp = yield* ElectronApp.ElectronApp;
227 const electronDialog = yield* ElectronDialog.ElectronDialog;
228 const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
229 const clerk = yield* DesktopClerk.DesktopClerk;
230 const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
231 const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
232 const clientSettings = yield* DesktopClientSettings.DesktopClientSettings;
233 const updates = yield* DesktopUpdates.DesktopUpdates;
234 const environment = yield* DesktopEnvironment.DesktopEnvironment;
235
236 yield* shellEnvironment.installIntoProcess;
237 const userDataPath = yield* appIdentity.resolveUserDataPath;
238 yield* electronApp.setPath("userData", userDataPath);
239 yield* logStartupInfo("runtime logging configured", { logDir: environment.logDir });
240 yield* desktopSettings.load;
241
242 if (environment.platform === "linux") {
243 yield* electronApp.appendCommandLineSwitch("class", environment.linuxWmClass);
244 }
245
246 yield* appIdentity.configure;
247 yield* lifecycle.register;
248 yield* clerk.configure;
249
250 yield* electronApp.whenReady.pipe(
251 Effect.withSpan("desktop.electron.whenReady"),
252 Effect.catchCause((cause) => fatalStartupCause("whenReady", cause)),
253 );
254 yield* logStartupInfo("app ready");
255 const cuaEnabled = Option.match(yield* clientSettings.get, {
256 onNone: () => false,
257 onSome: (settings) => settings.enableCua,
258 });
259 if (cuaEnabled) {
260 const continueWithoutCua = Effect.fn("desktop.continueWithoutCua")(function* (
261 context: Readonly<Record<string, string>>,
262 ) {
263 yield* disableCuaDriverServerEnvironment();
264 yield* logStartupError("embedded cua-driver failed to configure", context);
265 yield* electronDialog
266 .showMessageBox({
267 type: "error",
268 title: "Computer use unavailable",
269 message: "Cua could not start.",
270 detail:
271 "T3 Code will continue without computer use. Check the logs, then restart to try again.",
272 buttons: ["Continue"],
273 })
274 .pipe(Effect.ignore);
275 });
276 yield* configureCuaDriverServerEnvironment(
277 environment.appUserModelId,
278 environment.platform,
279 environment.isPackaged ? environment.resourcesPath : undefined,
280 ).pipe(
281 Effect.catchTags({
282 CuaDriverConfigurationError: (error) =>
283 continueWithoutCua({ modulePath: error.modulePath, cause: String(error.cause) }),
284 CuaDriverNotConfiguredError: () => continueWithoutCua({}),
285 }),
286 );
287 } else {
288 yield* disableCuaDriverServerEnvironment();
289 }
290 yield* appIdentity.configure;
291 yield* applicationMenu.configure;
292 yield* updates.configure;
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"));