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