Open History to see the last commit
1import {
2 DESKTOP_UPDATE_IN_PROGRESS_MARKER_FILE,
3 DESKTOP_UPDATE_IN_PROGRESS_TTL_MS,
4} from "@t3tools/contracts";
5import * as Context from "effect/Context";
6import * as Deferred from "effect/Deferred";
7import * as Duration from "effect/Duration";
8import * as Effect from "effect/Effect";
9import * as Exit from "effect/Exit";
10import * as FiberHandle from "effect/FiberHandle";
11import * as Layer from "effect/Layer";
12import * as Option from "effect/Option";
13import * as Path from "effect/Path";
14import * as Schedule from "effect/Schedule";
15import * as Schema from "effect/Schema";
16import * as Scope from "effect/Scope";
17import * as SubscriptionRef from "effect/SubscriptionRef";
18import * as SynchronizedRef from "effect/SynchronizedRef";
19
20import * as FileSystem from "effect/FileSystem";
21import { HttpClient } from "effect/http";
22import { ChildProcessSpawner } from "effect/process";
23
24import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
25import * as DesktopBackendManager from "./DesktopBackendManager.ts";
26import * as DesktopHomeOwner from "./DesktopHomeOwner.ts";
27import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
28import * as DesktopObservability from "../app/DesktopObservability.ts";
29import * as DesktopState from "../app/DesktopState.ts";
30import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
31import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
32import * as DesktopBrowserHost from "../preview/DesktopBrowserHost.ts";
33import * as DesktopWindow from "../window/DesktopWindow.ts";
34import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
35import * as ElectronDialog from "../electron/ElectronDialog.ts";
36import * as ElectronApp from "../electron/ElectronApp.ts";
37
38const { logWarning: logBackendPoolWarning } =
39 DesktopObservability.makeComponentLogger("desktop-backend-pool");
40
41const decodeServerRuntime = Schema.decodeUnknownEffect(
42 Schema.fromJsonString(Schema.Struct({ pid: Schema.Number, port: Schema.Number })),
43);
44
45export type BackendInstanceId = DesktopBackendManager.BackendInstanceId;
46export const BackendInstanceId = DesktopBackendManager.BackendInstanceId;
47export const PRIMARY_INSTANCE_ID = DesktopBackendManager.PRIMARY_INSTANCE_ID;
48export type DesktopBackendInstance = DesktopBackendManager.DesktopBackendInstance;
49export type BackendInstanceSpec = DesktopBackendManager.BackendInstanceSpec;
50
51export class DesktopBackendPoolInstanceAlreadyRegisteredError extends Schema.TaggedError<DesktopBackendPoolInstanceAlreadyRegisteredError>()(
52 "DesktopBackendPoolInstanceAlreadyRegisteredError",
53 {
54 id: Schema.String,
55 },
56) {
57 override get message() {
58 return `Backend instance "${this.id}" is already registered in the pool.`;
59 }
60}
61
62export class DesktopBackendPoolCannotUnregisterPrimaryError extends Schema.TaggedError<DesktopBackendPoolCannotUnregisterPrimaryError>()(
63 "DesktopBackendPoolCannotUnregisterPrimaryError",
64 {},
65) {
66 override get message() {
67 return "Refusing to unregister the primary backend from the pool.";
68 }
69}
70
71export class DesktopBackendPool extends Context.Service<
72 DesktopBackendPool,
73 {
74 readonly get: (id: BackendInstanceId) => Effect.Effect<Option.Option<DesktopBackendInstance>>;
75 readonly list: Effect.Effect<readonly DesktopBackendInstance[]>;
76 readonly primary: Effect.Effect<DesktopBackendInstance>;
77 readonly register: (
78 spec: BackendInstanceSpec,
79 ) => Effect.Effect<DesktopBackendInstance, DesktopBackendPoolInstanceAlreadyRegisteredError>;
80 readonly unregister: (
81 id: BackendInstanceId,
82 ) => Effect.Effect<void, DesktopBackendPoolCannotUnregisterPrimaryError>;
83 }
84>()("@t3tools/desktop/backend/DesktopBackendPool") {}
85
86export type BackendInstanceFactoryRequirements =
87 | FileSystem.FileSystem
88 | ChildProcessSpawner.ChildProcessSpawner
89 | HttpClient.HttpClient
90 | DesktopObservability.DesktopBackendOutputLogFactory
91 | DesktopTelemetryPublisher.DesktopTelemetryPublisher
92 | DesktopBrowserHost.DesktopBrowserHost
93 | DesktopWslEnvironment.DesktopWslEnvironment;
94
95interface ActiveRegisteredInstance {
96 readonly _tag: "Active";
97 readonly instance: DesktopBackendInstance;
98 readonly scope: Option.Option<Scope.Closeable>;
99}
100
101interface ClosingRegisteredInstance {
102 readonly _tag: "Closing";
103 readonly done: Deferred.Deferred<void>;
104}
105
106type RegisteredInstance = ActiveRegisteredInstance | ClosingRegisteredInstance;
107
108type RegisterAction =
109 | { readonly _tag: "Registered"; readonly instance: DesktopBackendInstance }
110 | { readonly _tag: "Wait"; readonly done: Deferred.Deferred<void> };
111
112type UnregisterAction =
113 | { readonly _tag: "Absent" }
114 | { readonly _tag: "Wait"; readonly done: Deferred.Deferred<void> }
115 | { readonly _tag: "Close"; readonly entry: ActiveRegisteredInstance };
116
117export const layer = Layer.effect(
118 DesktopBackendPool,
119 Effect.gen(function* () {
120 const environment = yield* DesktopEnvironment.DesktopEnvironment;
121 const fileSystem = yield* FileSystem.FileSystem;
122 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
123 const desktopWindow = yield* DesktopWindow.DesktopWindow;
124 const electronDialog = yield* ElectronDialog.ElectronDialog;
125 const electronApp = yield* ElectronApp.ElectronApp;
126 const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
127 const { primaryBackendStartup } = yield* DesktopState.DesktopState;
128 // Parent instance scopes to the pool so shutdown runs stop finalizers before the OS kills backends.
129 const layerScope = yield* Scope.Scope;
130 const factoryContext = yield* Effect.context<BackendInstanceFactoryRequirements>();
131 const homeOwnerContext = yield* Effect.context<
132 FileSystem.FileSystem | Path.Path | DesktopEnvironment.DesktopEnvironment
133 >();
134
135 const updateMarkerPath = environment.path.join(
136 environment.baseDir,
137 "runtime",
138 DESKTOP_UPDATE_IN_PROGRESS_MARKER_FILE,
139 );
140 const serverRuntimePath = environment.path.join(environment.stateDir, "server-runtime.json");
141 // The server publishes its runtime after HTTP readiness. Until then an SSH launcher
142 // finds nothing to adopt, so dropping the marker earlier lets it start a competing server.
143 const releaseUpdateMarker = Effect.fn("desktop.backendPool.releaseUpdateMarker")(function* (
144 httpBaseUrl: URL,
145 pid: number,
146 ) {
147 const marker = yield* fileSystem.readFileString(updateMarkerPath).pipe(Effect.option);
148 if (Option.isNone(marker)) {
149 return;
150 }
151 yield* fileSystem.readFileString(serverRuntimePath).pipe(
152 Effect.flatMap(decodeServerRuntime),
153 Effect.map((runtime) => runtime.pid === pid && runtime.port === Number(httpBaseUrl.port)),
154 Effect.orElseSucceed(() => false),
155 Effect.repeat({
156 until: (published) => published,
157 schedule: Schedule.spaced(Duration.millis(100)),
158 }),
159 Effect.timeoutOption(Duration.millis(DESKTOP_UPDATE_IN_PROGRESS_TTL_MS)),
160 );
161 // A later update may have replaced the marker; that handoff is not ours to end.
162 const current = yield* fileSystem.readFileString(updateMarkerPath).pipe(Effect.option);
163 if (Option.isSome(current) && current.value === marker.value) {
164 yield* fileSystem.remove(updateMarkerPath, { force: true }).pipe(Effect.ignore);
165 }
166 });
167 // One wait at a time: each run's shutdown or readiness ends the previous run's wait.
168 const updateMarkerWait = yield* FiberHandle.make<void>();
169
170 // The main window loads during startup and reads the primary endpoint once; a Windows fallback
171 // before the first readiness replaces the WSL endpoint it read.
172 let primaryWasReady = false;
173 let reloadMainOnReady = false;
174 const reloadStaleMain = Effect.suspend(() => {
175 primaryWasReady = true;
176 if (!reloadMainOnReady) return Effect.void;
177 reloadMainOnReady = false;
178 return desktopWindow.runMainContentsCommand("reload");
179 });
180
181 // Persist fatal Windows fallbacks; transient transport failures must preserve the user's WSL preference.
182 const handlePrimaryPreflightFailure = Effect.fn("desktop.backendPool.primaryPreflightFailed")(
183 function* (failure: DesktopBackendManager.PreflightFailure) {
184 const { reason, fatal } = failure;
185 if (!primaryWasReady) reloadMainOnReady = true;
186 if (!fatal) {
187 yield* logBackendPoolWarning(
188 "primary WSL preflight retry window exhausted; using Windows for this launch",
189 { reason },
190 );
191 yield* electronDialog.showErrorBox(
192 "WSL backend is still unavailable",
193 `${reason}\n\nT3 Code will use the Windows backend for this launch and retry WSL the next time the app starts.`,
194 );
195 yield* appSettings.applyWslWindowsFallbackInMemory;
196 return true;
197 }
198
199 yield* logBackendPoolWarning("primary WSL preflight failed; falling back to Windows", {
200 reason,
201 });
202 yield* electronDialog.showErrorBox(
203 "WSL backend couldn't start",
204 `${reason}\n\nFalling back to the Windows backend so T3 Code can open. Re-enable the WSL backend from Settings > Sharing & access once the WSL distro is fixed.`,
205 );
206 // Clear wslOnly too so enabling WSL cannot restore a failed mode.
207 // Keep the in-memory fallback if persistence fails.
208 yield* appSettings.applyWslWindowsFallback.pipe(
209 Effect.catch((error) =>
210 logBackendPoolWarning(
211 "failed to persist Windows fallback after WSL preflight failure",
212 {
213 error: error.message,
214 },
215 ).pipe(Effect.andThen(appSettings.applyWslWindowsFallbackInMemory)),
216 ),
217 );
218 return true;
219 },
220 );
221
222 const primary = yield* DesktopBackendManager.makeBackendInstance({
223 id: DesktopBackendManager.PRIMARY_INSTANCE_ID,
224 // Resolve lazily: startup loads persisted settings after pool initialization.
225 label: configuration.resolvePrimaryLabel,
226 configResolve: configuration.resolvePrimary,
227 // Absorb window errors so readiness can reset restartAttempt.
228 onReady: (httpBaseUrl, pid) =>
229 FiberHandle.run(updateMarkerWait, releaseUpdateMarker(httpBaseUrl, pid)).pipe(
230 Effect.andThen(reloadStaleMain),
231 Effect.andThen(desktopWindow.handleBackendReady(httpBaseUrl)),
232 // Only once the main window exists, so the recovery window never closes into nothing.
233 Effect.andThen(SubscriptionRef.set(primaryBackendStartup, { _tag: "Ready" })),
234 Effect.catch((error) =>
235 logBackendPoolWarning("failed to open main window after backend readiness", {
236 error: error.message,
237 }),
238 ),
239 ),
240 onStartupFailure: (failure) =>
241 SubscriptionRef.set(primaryBackendStartup, { _tag: "Failing", ...failure }),
242 onShutdown: () =>
243 FiberHandle.clear(updateMarkerWait).pipe(
244 Effect.andThen(desktopWindow.handleBackendNotReady),
245 ),
246 onPreflightFailed: handlePrimaryPreflightFailure,
247 onStateDirOwned: () =>
248 DesktopHomeOwner.readLiveHomeOwner().pipe(
249 Effect.flatMap((owner) =>
250 electronDialog.showErrorBox(
251 "This T3 home is unavailable",
252 DesktopHomeOwner.homeOwnedMessage(owner),
253 ),
254 ),
255 Effect.provideContext(homeOwnerContext),
256 Effect.andThen(electronApp.quit),
257 ),
258 });
259
260 const instancesRef = yield* SynchronizedRef.make<
261 ReadonlyMap<BackendInstanceId, RegisteredInstance>
262 >(
263 new Map([
264 [
265 DesktopBackendManager.PRIMARY_INSTANCE_ID,
266 { _tag: "Active", instance: primary, scope: Option.none() },
267 ],
268 ]),
269 );
270
271 const register: DesktopBackendPool["Service"]["register"] = (spec) =>
272 Effect.suspend(() =>
273 SynchronizedRef.modifyEffect(
274 instancesRef,
275 (
276 current,
277 ): Effect.Effect<
278 readonly [RegisterAction, ReadonlyMap<BackendInstanceId, RegisteredInstance>],
279 DesktopBackendPoolInstanceAlreadyRegisteredError
280 > => {
281 const existing = current.get(spec.id);
282 if (existing?._tag === "Active") {
283 return Effect.fail(
284 new DesktopBackendPoolInstanceAlreadyRegisteredError({ id: spec.id }),
285 );
286 }
287 if (existing?._tag === "Closing") {
288 return Effect.succeed([
289 { _tag: "Wait", done: existing.done } as const,
290 current,
291 ] as const);
292 }
293 return Effect.gen(function* () {
294 // Provide the child Scope last so the captured pool Scope cannot shadow it and orphan stop/restart finalizers.
295 const instanceScope = yield* Scope.fork(layerScope, "sequential");
296 const instance = yield* DesktopBackendManager.makeBackendInstance(spec).pipe(
297 Scope.provide(instanceScope),
298 Effect.provide(factoryContext),
299 );
300 const next = new Map(current);
301 next.set(spec.id, {
302 _tag: "Active",
303 instance,
304 scope: Option.some(instanceScope),
305 });
306 return [
307 { _tag: "Registered", instance } as const,
308 next as ReadonlyMap<BackendInstanceId, RegisteredInstance>,
309 ] as const;
310 });
311 },
312 ).pipe(
313 Effect.flatMap((result) =>
314 result._tag === "Registered"
315 ? Effect.succeed(result.instance)
316 : Deferred.await(result.done).pipe(Effect.andThen(register(spec))),
317 ),
318 ),
319 );
320
321 const unregister: DesktopBackendPool["Service"]["unregister"] = Effect.fn(
322 "DesktopBackendPool.unregister",
323 )(function* (id) {
324 if (id === DesktopBackendManager.PRIMARY_INSTANCE_ID) {
325 return yield* new DesktopBackendPoolCannotUnregisterPrimaryError();
326 }
327 const done = yield* Deferred.make<void>();
328 const action = yield* SynchronizedRef.modifyEffect(
329 instancesRef,
330 (
331 current,
332 ): Effect.Effect<
333 readonly [UnregisterAction, ReadonlyMap<BackendInstanceId, RegisteredInstance>]
334 > => {
335 const entry = current.get(id);
336 if (entry === undefined) {
337 return Effect.succeed([{ _tag: "Absent" } as const, current] as const);
338 }
339 if (entry._tag === "Closing") {
340 return Effect.succeed([{ _tag: "Wait", done: entry.done } as const, current] as const);
341 }
342 const next = new Map(current);
343 next.set(id, { _tag: "Closing", done });
344 return Effect.succeed([
345 { _tag: "Close", entry } as const,
346 next as ReadonlyMap<BackendInstanceId, RegisteredInstance>,
347 ] as const);
348 },
349 );
350
351 if (action._tag === "Absent") return;
352 if (action._tag === "Wait") {
353 yield* Deferred.await(action.done);
354 return;
355 }
356
357 const finish = SynchronizedRef.modifyEffect(instancesRef, (current) => {
358 const closing = current.get(id);
359 if (closing?._tag !== "Closing" || closing.done !== done) {
360 return Effect.succeed([undefined, current] as const);
361 }
362 const next = new Map(current);
363 next.delete(id);
364 return Effect.succeed([
365 undefined,
366 next as ReadonlyMap<BackendInstanceId, RegisteredInstance>,
367 ] as const);
368 }).pipe(Effect.andThen(Deferred.succeed(done, undefined)), Effect.asVoid);
369 yield* Option.match(action.entry.scope, {
370 onNone: () => Effect.void,
371 onSome: (scope) => Scope.close(scope, Exit.void).pipe(Effect.ignore),
372 }).pipe(Effect.ensuring(finish));
373 });
374
375 return DesktopBackendPool.of({
376 get: Effect.fn("DesktopBackendPool.get")(function (id) {
377 return SynchronizedRef.get(instancesRef).pipe(
378 Effect.map((instances) => {
379 const entry = instances.get(id);
380 return entry?._tag === "Active" ? Option.some(entry.instance) : Option.none();
381 }),
382 );
383 }),
384 list: SynchronizedRef.get(instancesRef).pipe(
385 Effect.map((instances) =>
386 Array.from(instances.values()).flatMap((entry) =>
387 entry._tag === "Active" ? [entry.instance] : [],
388 ),
389 ),
390 ),
391 primary: Effect.succeed(primary),
392 register,
393 unregister,
394 });
395 }),
396);
397
398export const layerTest = (
399 instances: readonly DesktopBackendInstance[],
400): Layer.Layer<DesktopBackendPool> =>
401 Layer.effect(
402 DesktopBackendPool,
403 Effect.gen(function* () {
404 if (instances.length === 0) {
405 return yield* Effect.die("DesktopBackendPool.layerTest requires at least one instance");
406 }
407 const byId = new Map<BackendInstanceId, DesktopBackendInstance>(
408 instances.map((instance) => [instance.id, instance] as const),
409 );
410 const primary = instances[0]!;
411 return DesktopBackendPool.of({
412 get: Effect.fn("DesktopBackendPool.get")(function (id) {
413 return Effect.succeed(Option.fromNullishOr(byId.get(id)));
414 }),
415 list: Effect.succeed(Array.from(byId.values())),
416 primary: Effect.succeed(primary),
417 register: Effect.fn("DesktopBackendPool.register")(function () {
418 return Effect.die("DesktopBackendPool.layerTest does not support register");
419 }),
420 unregister: Effect.fn("DesktopBackendPool.unregister")(function () {
421 return Effect.die("DesktopBackendPool.layerTest does not support unregister");
422 }),
423 });
424 }),
425 );