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