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