The best way to control Claude Code, Codex and more from any computer or phone
fix(desktop): load the renderer while the backend starts (#28715)
Yash Singh committed
Nov 1, 2026 at 21:37 UTC
7a760a9a88662274f29b20ae812b3ae05fca9078
12 files changed
+419
-67
apps/desktop/src/app/DesktopApp.ts
+10
@@ -245,6 +245,16 @@ const bootstrap = Effect.gen(function* () {
245
}
246
yield* primaryBackend.start;
247
yield* logBootstrapInfo("bootstrap backend start requested");
248
+ // WSL-only fallback can change the primary endpoint before readiness.
249
+ const config = yield* primaryBackend.currentConfig;
250
+ if (
251
+ !environment.isDevelopment &&
252
+ !settings.wslOnly &&
253
+ Option.isSome(config) &&
254
+ Option.isNone(config.value.preflightFailure)
255
+ ) {
256
+ yield* desktopWindow.ensureMain;
257
+ }
258
yield* appActivation.start.pipe(
259
Effect.tap(() => logBootstrapInfo("desktop app control socket ready")),
260
Effect.catch((error) => logStartupError("desktop app control socket unavailable", { error })),
apps/desktop/src/app/DesktopStartupRecovery.test.ts
+131
-2
@@ -1,8 +1,23 @@
1
import type { DesktopUpdateState } from "@t3tools/contracts";
2
-import { describe, expect, it } from "vite-plus/test";
2
+import { describe, expect, it } from "@effect/vitest";
3
+import * as Deferred from "effect/Deferred";
4
+import * as Effect from "effect/Effect";
5
+import * as FileSystem from "effect/FileSystem";
6
+import * as Layer from "effect/Layer";
7
+import * as Option from "effect/Option";
8
+import * as Ref from "effect/Ref";
9
+import * as Stream from "effect/Stream";
10
+import * as SubscriptionRef from "effect/SubscriptionRef";
11
+import * as DesktopEnvironment from "./DesktopEnvironment.ts";
12
+import * as DesktopState from "./DesktopState.ts";
13
+import * as ElectronApp from "../electron/ElectronApp.ts";
14
+import * as ElectronShell from "../electron/ElectronShell.ts";
15
+import * as ElectronTheme from "../electron/ElectronTheme.ts";
16
+import * as ElectronWindow from "../electron/ElectronWindow.ts";
17
+import * as DesktopUpdates from "../updates/DesktopUpdates.ts";
18
19
import { createInitialDesktopUpdateState } from "../updates/updateMachine.ts";
5
-import { resolveStartupRecoveryOffer } from "./DesktopStartupRecovery.ts";
20
+import { listen, resolveStartupRecoveryOffer } from "./DesktopStartupRecovery.ts";
21
22
const updateState = (patch: Partial<DesktopUpdateState>): DesktopUpdateState => ({
23
...createInitialDesktopUpdateState(
@@ -68,3 +83,117 @@ describe("resolveStartupRecoveryOffer", () => {
83
});
84
});
85
});
86
+
87
+it.effect.each([
88
+ { visible: false, started: false, closeMain: false },
89
+ { visible: true, started: false, closeMain: false },
90
+ { visible: true, started: true, closeMain: false },
91
+ { visible: true, started: false, closeMain: true },
92
+])("closes recovery safely with closeMain=$closeMain", ({ visible, started, closeMain }) =>
93
+ Effect.scoped(
94
+ Effect.gen(function* () {
95
+ const checked = yield* Deferred.make<void>();
96
+ const remembered = yield* Deferred.make<void>();
97
+ const shouldRecover = !visible || !started;
98
+ const closed = Promise.withResolvers<void>();
99
+ const loaded: string[] = [];
100
+ const appListeners = new Map<string, (...args: readonly unknown[]) => void>();
101
+ const mainListeners = new Map<string, () => void>();
102
+ let closeCount = 0;
103
+ let mainVisible = visible;
104
+ const main = {
105
+ isDestroyed: () => false,
106
+ isVisible: () => mainVisible,
107
+ on: (event: string, listener: () => void) => mainListeners.set(event, listener),
108
+ once: (event: string, listener: () => void) => mainListeners.set(event, listener),
109
+ } as unknown as Electron.BrowserWindow;
110
+ const mainRef = yield* Ref.make(Option.some(main));
111
+ const recovery = {
112
+ isDestroyed: () => false,
113
+ close: () => {
114
+ closeCount++;
115
+ closed.resolve();
116
+ },
117
+ loadURL: (url: string) => {
118
+ loaded.push(url);
119
+ return Promise.resolve();
120
+ },
121
+ once: () => {},
122
+ webContents: { setWindowOpenHandler: () => {}, on: () => {} },
123
+ } as unknown as Electron.BrowserWindow;
124
+ const state = yield* DesktopState.DesktopState;
125
+ if (started) yield* SubscriptionRef.set(state.primaryBackendStartup, { _tag: "Ready" });
126
+ yield* listen.pipe(
127
+ Effect.provide(
128
+ Layer.mergeAll(
129
+ FileSystem.layerNoop({
130
+ readFileString: () => Effect.succeed("0.1.2"),
131
+ writeFileString: () => Deferred.succeed(remembered, undefined).pipe(Effect.asVoid),
132
+ }),
133
+ Layer.succeed(DesktopEnvironment.DesktopEnvironment, {
134
+ appVersion: "0.1.3",
135
+ stateDir: "/task/state",
136
+ logDir: "/task/logs",
137
+ path: { join: (...parts: string[]) => parts.join("/") },
138
+ } as unknown as DesktopEnvironment.DesktopEnvironment["Service"]),
139
+ Layer.succeed(ElectronApp.ElectronApp, {
140
+ on: (event: string, listener: (...args: readonly unknown[]) => void) =>
141
+ Effect.sync(() => {
142
+ appListeners.set(event, listener);
143
+ }),
144
+ } as unknown as ElectronApp.ElectronApp["Service"]),
145
+ Layer.succeed(
146
+ ElectronShell.ElectronShell,
147
+ {} as ElectronShell.ElectronShell["Service"],
148
+ ),
149
+ Layer.succeed(ElectronTheme.ElectronTheme, {
150
+ shouldUseDarkColors: Effect.succeed(false),
151
+ } as ElectronTheme.ElectronTheme["Service"]),
152
+ Layer.succeed(ElectronWindow.ElectronWindow, {
153
+ main: Ref.get(mainRef),
154
+ create: () => Effect.succeed(recovery),
155
+ } as unknown as ElectronWindow.ElectronWindow["Service"]),
156
+ Layer.succeed(DesktopUpdates.DesktopUpdates, {
157
+ subscribe: Effect.succeed({
158
+ latest: updateState({ status: "disabled" }),
159
+ changes: Stream.empty,
160
+ }),
161
+ check: () => Deferred.succeed(checked, undefined),
162
+ } as unknown as DesktopUpdates.DesktopUpdates["Service"]),
163
+ ),
164
+ ),
165
+ );
166
+ appListeners.get("browser-window-created")?.({}, main);
167
+ if (started) yield* Deferred.await(remembered);
168
+ yield* SubscriptionRef.set(state.primaryBackendStartup, {
169
+ _tag: "Failing",
170
+ reason: "Server failed before readiness",
171
+ output: "Failure details",
172
+ });
173
+ yield* Deferred.await(checked);
174
+ expect(loaded.length).toBe(shouldRecover ? 1 : 0);
175
+ if (shouldRecover) {
176
+ expect(decodeURIComponent(loaded[0]!)).toContain("Failure details");
177
+ if (closeMain) yield* Ref.set(mainRef, Option.none());
178
+ yield* SubscriptionRef.set(state.primaryBackendStartup, { _tag: "Ready" });
179
+ yield* Deferred.await(remembered);
180
+ if (closeMain || !visible) {
181
+ expect(closeCount).toBe(0);
182
+ if (closeMain) {
183
+ yield* Ref.set(mainRef, Option.some(main));
184
+ mainVisible = false;
185
+ appListeners.get("browser-window-created")?.({}, main);
186
+ }
187
+ mainListeners.get("ready-to-show")?.();
188
+ expect(closeCount).toBe(0);
189
+ mainVisible = true;
190
+ const show = mainListeners.get("show");
191
+ expect(show).toBeDefined();
192
+ show!();
193
+ }
194
+ yield* Effect.promise(() => closed.promise);
195
+ expect(closeCount).toBe(1);
196
+ }
197
+ }),
198
+ ).pipe(Effect.provide(DesktopState.layer)),
199
+);
apps/desktop/src/app/DesktopStartupRecovery.ts
+25
-3
@@ -167,6 +167,7 @@ export const listen: Effect.Effect<
167
const failureRef = yield* Ref.make(Option.none<BackendStartupFailure>());
168
const renderedHtmlRef = yield* Ref.make("");
169
const checkedRef = yield* Ref.make(false);
170
+ let backendHasStarted = false;
171
const { latest, changes: updateChanges } = yield* updates.subscribe;
172
const updateStateRef = yield* Ref.make(latest);
173
@@ -230,8 +231,15 @@ export const listen: Effect.Effect<
231
const show = Effect.fn("desktop.startupRecovery.show")(
232
function* () {
233
if (yield* Ref.get(quitting)) return;
233
- // A backend that crashes after the app opened is reported by the app itself.
234
- if (Option.isSome(yield* electronWindow.main)) return;
234
+ // A visible boot shell still needs recovery if the backend has never started.
235
+ const main = yield* electronWindow.main;
236
+ if (
237
+ backendHasStarted &&
238
+ Option.isSome(main) &&
239
+ !main.value.isDestroyed() &&
240
+ main.value.isVisible()
241
+ )
242
+ return;
243
const existing = yield* Ref.get(windowRef);
244
if (Option.isSome(existing) && !existing.value.isDestroyed()) {
245
yield* electronWindow.reveal(existing.value);
@@ -285,6 +293,19 @@ export const listen: Effect.Effect<
293
if (Option.isSome(window) && !window.value.isDestroyed()) window.value.close();
294
});
295
296
+ const closeWhenMainReady = Effect.gen(function* () {
297
+ if ((yield* SubscriptionRef.get(primaryBackendStartup))._tag !== "Ready") return;
298
+ const main = yield* electronWindow.main;
299
+ if (Option.isSome(main) && !main.value.isDestroyed() && main.value.isVisible()) yield* close;
300
+ });
301
+
302
+ yield* electronApp.on(
303
+ "browser-window-created",
304
+ (_event: Electron.Event, window: Electron.BrowserWindow) => {
305
+ window.on("show", () => runFork(closeWhenMainReady));
306
+ },
307
+ );
308
+
309
const rememberStartedVersion = Effect.gen(function* () {
310
if (lastStartedVersion === environment.appVersion) return;
311
yield* fileSystem.writeFileString(lastStartedVersionPath, environment.appVersion);
@@ -303,8 +324,9 @@ export const listen: Effect.Effect<
324
Stream.runForEach(
325
Effect.fn("desktop.startupRecovery.onStartupChange")(function* (startup) {
326
if (startup._tag === "Ready") {
327
+ backendHasStarted = true;
328
yield* Ref.set(failureRef, Option.none());
307
- yield* close;
329
+ yield* closeWhenMainReady;
330
yield* rememberStartedVersion;
331
return;
332
}
apps/desktop/src/app/DesktopWebLinks.test.ts
+6
@@ -4,6 +4,7 @@ import * as NodeEvents from "node:events";
4
import * as Effect from "effect/Effect";
5
import * as Layer from "effect/Layer";
6
7
+import * as DesktopWindow from "../window/DesktopWindow.ts";
8
import * as ElectronWindow from "../electron/ElectronWindow.ts";
9
import { WEB_LINK_OPEN_CHANNEL } from "../ipc/channels.ts";
10
import * as DesktopWebLinks from "./DesktopWebLinks.ts";
@@ -21,6 +22,11 @@ const makeWindow = () => {
22
const reload = () =>
23
webContents.emit("did-start-navigation", { isMainFrame: true, isSameDocument: false });
24
const layer = DesktopWebLinks.layer.pipe(
25
+ Layer.provide(
26
+ Layer.succeed(DesktopWindow.DesktopWindow, {
27
+ activate: Effect.sync(() => void revealed.push(window)),
28
+ } as unknown as DesktopWindow.DesktopWindow["Service"]),
29
+ ),
30
Layer.provide(
31
Layer.succeed(
32
ElectronWindow.ElectronWindow,
apps/desktop/src/app/DesktopWebLinks.ts
+3
-1
@@ -3,6 +3,7 @@ import * as Effect from "effect/Effect";
3
import * as Layer from "effect/Layer";
4
import * as Option from "effect/Option";
5
6
+import * as DesktopWindow from "../window/DesktopWindow.ts";
7
import * as ElectronWindow from "../electron/ElectronWindow.ts";
8
import { WEB_LINK_OPEN_CHANNEL } from "../ipc/channels.ts";
9
@@ -24,6 +25,7 @@ export class DesktopWebLinks extends Context.Service<
25
26
const make = Effect.gen(function* () {
27
const electronWindow = yield* ElectronWindow.ElectronWindow;
28
+ const desktopWindow = yield* DesktopWindow.DesktopWindow;
29
const pending: Array<string> = [];
30
let listening: Electron.WebContents | null = null;
31
let detachListening: (() => void) | null = null;
@@ -43,7 +45,7 @@ const make = Effect.gen(function* () {
45
return;
46
}
47
for (const url of pending.splice(0)) listening.send(WEB_LINK_OPEN_CHANNEL, url);
46
- yield* electronWindow.reveal(window.value);
48
+ yield* desktopWindow.activate.pipe(Effect.ignore);
49
});
50
51
const startListening = Effect.gen(function* () {
apps/desktop/src/backend/DesktopBackendManager.test.ts
+43
@@ -192,6 +192,49 @@ function makeTestInstance(input: MakeInstanceInput) {
192
}
193
194
describe("DesktopBackendManager", () => {
195
+ it.effect("notifies readiness waiters on HTTP readiness and stop without clock advancement", () =>
196
+ Effect.scoped(
197
+ Effect.gen(function* () {
198
+ const probe = yield* Deferred.make<void>();
199
+ const ready = yield* Deferred.make<void>();
200
+ const exit = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
201
+ const instance = yield* makeTestInstance({
202
+ spawnerLayer: Layer.succeed(
203
+ ChildProcessSpawner.ChildProcessSpawner,
204
+ ChildProcessSpawner.make(() =>
205
+ Effect.acquireRelease(
206
+ Effect.succeed(
207
+ makeProcess({
208
+ exitCode: Deferred.await(exit),
209
+ kill: () =>
210
+ Deferred.succeed(exit, ChildProcessSpawner.ExitCode(0)).pipe(Effect.asVoid),
211
+ }),
212
+ ),
213
+ () => Deferred.succeed(exit, ChildProcessSpawner.ExitCode(0)),
214
+ ),
215
+ ),
216
+ ),
217
+ httpClientLayer: Layer.succeed(
218
+ HttpClient.HttpClient,
219
+ HttpClient.make((request) =>
220
+ Deferred.succeed(probe, undefined).pipe(
221
+ Effect.andThen(Deferred.await(ready)),
222
+ Effect.as(HttpClientResponse.fromWeb(request, new Response("{}"))),
223
+ ),
224
+ ),
225
+ ),
226
+ });
227
+ yield* instance.start;
228
+ yield* Deferred.await(probe);
229
+ const waiter = yield* instance.waitForReady(Duration.seconds(15)).pipe(Effect.forkChild);
230
+ yield* Deferred.succeed(ready, undefined);
231
+ assert.isTrue(yield* Fiber.join(waiter));
232
+ yield* instance.stop();
233
+ assert.isFalse(yield* instance.waitForReady(Duration.seconds(15)));
234
+ }),
235
+ ),
236
+ );
237
+
238
it.effect("spawns the backend with fd3 bootstrap and fd4 telemetry", () =>
239
Effect.scoped(
240
Effect.gen(function* () {
apps/desktop/src/backend/DesktopBackendManager.ts
+36
-40
@@ -8,7 +8,7 @@ import * as FileSystem from "effect/FileSystem";
8
import * as Option from "effect/Option";
9
import * as PlatformError from "effect/PlatformError";
10
import * as Ref from "effect/Ref";
11
-import * as Schedule from "effect/Schedule";
11
+import * as SubscriptionRef from "effect/SubscriptionRef";
12
import * as Schema from "effect/Schema";
13
import * as Semaphore from "effect/Semaphore";
14
import * as Scope from "effect/Scope";
@@ -629,7 +629,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
629
const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
630
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
631
const httpClient = yield* HttpClient.HttpClient;
632
- const state = yield* Ref.make(initialState);
632
+ const state = yield* SubscriptionRef.make(initialState);
633
const mutex = yield* Semaphore.make(1);
634
const outputTail = yield* Ref.make("");
635
// One streaming decoder per stream keeps UTF-8 characters split across chunks intact.
@@ -644,9 +644,9 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
644
DesktopObservability.makeComponentLogger(`desktop-backend-instance:${spec.id}`);
645
646
const updateActiveRun = (runId: number, f: (run: ActiveBackendRun) => ActiveBackendRun) =>
647
- Ref.update(state, withActiveRun(runId, f));
647
+ SubscriptionRef.update(state, withActiveRun(runId, f));
648
649
- const snapshot = Ref.get(state).pipe(
649
+ const snapshot = SubscriptionRef.get(state).pipe(
650
Effect.map((current): DesktopBackendSnapshot => ({
651
desiredRunning: current.desiredRunning,
652
ready: current.ready,
@@ -655,10 +655,10 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
655
restartScheduled: Option.isSome(current.restartFiber),
656
})),
657
);
658
- const currentConfig = Ref.get(state).pipe(Effect.map((current) => current.config));
658
+ const currentConfig = SubscriptionRef.get(state).pipe(Effect.map((current) => current.config));
659
660
const cancelRestart = Effect.gen(function* () {
661
- const restartFiber = yield* Ref.modify(state, (current) => [
661
+ const restartFiber = yield* SubscriptionRef.modify(state, (current) => [
662
current.restartFiber,
663
{
664
...current,
@@ -675,10 +675,10 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
675
const start: Effect.Effect<void> = Effect.suspend(() =>
676
mutex.withPermits(1)(
677
Effect.gen(function* () {
678
- const current = yield* Ref.get(state);
678
+ const current = yield* SubscriptionRef.get(state);
679
if (Option.isSome(current.active)) {
680
if (!current.desiredRunning) {
681
- yield* Ref.update(state, (latest) => ({
681
+ yield* SubscriptionRef.update(state, (latest) => ({
682
...latest,
683
desiredRunning: true,
684
}));
@@ -688,7 +688,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
688
689
if (current.ready) {
690
yield* spec.onShutdown?.() ?? Effect.void;
691
- yield* Ref.update(state, (latest) =>
691
+ yield* SubscriptionRef.update(state, (latest) =>
692
latest.ready ? { ...latest, ready: false } : latest,
693
);
694
}
@@ -713,7 +713,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
713
const resetFatalPreflightCounter =
714
!current.desiredRunning && current.preflightFailureAttempt > 0;
715
yield* cancelRestart;
716
- yield* Ref.update(state, (latest) => ({
716
+ yield* SubscriptionRef.update(state, (latest) => ({
717
...latest,
718
desiredRunning: true,
719
ready: false,
@@ -725,7 +725,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
725
if (Option.isSome(preflightFailure)) {
726
const { reason, fatal, retryLimit } = preflightFailure.value;
727
if (!fatal && retryLimit === undefined) {
728
- yield* Ref.update(state, (latest) =>
728
+ yield* SubscriptionRef.update(state, (latest) =>
729
latest.preflightFailureAttempt === 0
730
? latest
731
: { ...latest, preflightFailureAttempt: 0 },
@@ -734,7 +734,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
734
return;
735
}
736
const attemptLimit = retryLimit ?? MAX_PREFLIGHT_FAILURE_ATTEMPTS;
737
- const attempt = yield* Ref.modify(state, (latest) => {
737
+ const attempt = yield* SubscriptionRef.modify(state, (latest) => {
738
const next = latest.preflightFailureAttempt + 1;
739
return [next, { ...latest, preflightFailureAttempt: next }] as const;
740
});
@@ -743,7 +743,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
743
reason,
744
attempt,
745
});
746
- yield* Ref.update(state, (latest) => ({
746
+ yield* SubscriptionRef.update(state, (latest) => ({
747
...latest,
748
desiredRunning: false,
749
ready: false,
@@ -761,7 +761,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
761
if (shouldRestart) {
762
yield* scheduleRestart(reason);
763
} else {
764
- yield* Ref.update(state, (latest) => ({
764
+ yield* SubscriptionRef.update(state, (latest) => ({
765
...latest,
766
desiredRunning: false,
767
ready: false,
@@ -772,7 +772,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
772
yield* scheduleRestart(reason);
773
return;
774
}
775
- yield* Ref.update(state, (latest) =>
775
+ yield* SubscriptionRef.update(state, (latest) =>
776
latest.preflightFailureAttempt === 0 ? latest : { ...latest, preflightFailureAttempt: 0 },
777
);
778
@@ -782,7 +782,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
782
}
783
784
const runScope = yield* Scope.make("sequential");
785
- const runId = yield* Ref.modify(state, (latest) => [
785
+ const runId = yield* SubscriptionRef.modify(state, (latest) => [
786
latest.nextRunId,
787
{
788
...latest,
@@ -806,7 +806,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
806
yield* mutex.withPermits(1)(
807
Effect.gen(function* () {
808
const { isCurrentRun, nextState, pid, exitObserved, stopRequested, wasReady } =
809
- yield* Ref.modify(
809
+ yield* SubscriptionRef.modify(
810
state,
811
(
812
latest,
@@ -873,7 +873,10 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
873
874
if (isCurrentRun && nextState.desiredRunning) {
875
if (stateDirOwned && !stopRequested) {
876
- yield* Ref.update(state, (latest) => ({ ...latest, desiredRunning: false }));
876
+ yield* SubscriptionRef.update(state, (latest) => ({
877
+ ...latest,
878
+ desiredRunning: false,
879
+ }));
880
yield* (spec.onStateDirOwned?.() ?? Effect.void).pipe(Effect.ignore);
881
return;
882
}
@@ -907,7 +910,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
910
exitObserved: true,
911
})),
912
onReady: Effect.fn("desktop.backendInstance.onReady")(function* () {
910
- const isCurrentRun = yield* Ref.modify(state, (latest) => {
913
+ const isCurrentRun = yield* SubscriptionRef.modify(state, (latest) => {
914
const activeRun = Option.getOrUndefined(latest.active);
915
if (activeRun?.id !== runId) {
916
return [false, latest] as const;
@@ -978,7 +981,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
981
const scheduleRestart = Effect.fn("desktop.backendInstance.scheduleRestart")(function* (
982
reason: string,
983
) {
981
- const scheduled = yield* Ref.modify(state, (latest) => {
984
+ const scheduled = yield* SubscriptionRef.modify(state, (latest) => {
985
if (!latest.desiredRunning || Option.isSome(latest.restartFiber)) {
986
return [Option.none<{ delay: Duration.Duration; attempt: number }>(), latest] as const;
987
}
@@ -1006,7 +1009,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
1009
const restartFiber = yield* Effect.forkIn(
1010
Effect.sleep(delay).pipe(
1011
Effect.andThen(
1009
- Ref.modify(state, (latest) => {
1012
+ SubscriptionRef.modify(state, (latest) => {
1013
const shouldRestart = latest.desiredRunning;
1014
return [
1015
shouldRestart,
@@ -1026,7 +1029,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
1029
),
1030
parentScope,
1031
);
1029
- yield* Ref.update(state, (latest) =>
1032
+ yield* SubscriptionRef.update(state, (latest) =>
1033
Option.isNone(latest.restartFiber)
1034
? {
1035
...latest,
@@ -1043,7 +1046,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
1046
}) {
1047
const { active, restartFiber, notifyShutdown } = yield* mutex.withPermits(1)(
1048
Effect.gen(function* () {
1046
- const result = yield* Ref.modify(state, (latest) => {
1049
+ const result = yield* SubscriptionRef.modify(state, (latest) => {
1050
const active = Option.map(latest.active, (run) =>
1051
run.exitObserved ? run : { ...run, stopRequested: true },
1052
);
@@ -1082,7 +1085,7 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
1085
return;
1086
}
1087
const cleanup = yield* mutex.withPermits(1)(
1085
- Ref.modify(
1088
+ SubscriptionRef.modify(
1089
state,
1090
(
1091
latest,
@@ -1130,23 +1133,16 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
1133
});
1134
});
1135
1133
- const waitForReady: (timeout: Duration.Duration) => Effect.Effect<boolean> = Effect.fn(
1134
- "DesktopBackendManager.waitForReady",
1135
- )(
1136
- function* (_timeout: Duration.Duration) {
1137
- const current = yield* Ref.get(state);
1138
- if (!current.desiredRunning) return { done: true, ready: false };
1139
- return current.ready ? { done: true, ready: true } : { done: false, ready: false };
1140
- },
1141
- (effect, timeout) =>
1142
- effect.pipe(
1143
- Effect.repeat({
1144
- until: (status) => status.done,
1145
- schedule: Schedule.spaced(Duration.millis(100)),
1146
- }),
1147
- Effect.map((status) => status.ready),
1136
+ const waitForReady = Effect.fn("DesktopBackendManager.waitForReady")(
1137
+ (timeout: Duration.Duration) =>
1138
+ SubscriptionRef.changes(state).pipe(
1139
+ Stream.filter((current) => current.ready || !current.desiredRunning),
1140
+ Stream.map((current) => current.ready),
1141
+ Stream.runHead,
1142
Effect.timeoutOption(timeout),
1149
- Effect.map(Option.getOrElse(() => false)),
1143
+ Effect.map(
1144
+ (result) => Option.isSome(result) && Option.getOrElse(result.value, () => false),
1145
+ ),
1146
),
1147
);
1148
apps/desktop/src/backend/DesktopLocalEnvironmentAuth.test.ts
+19
-2
@@ -1,4 +1,5 @@
1
import { assert, describe, it } from "@effect/vitest";
2
+import * as Deferred from "effect/Deferred";
3
import * as Duration from "effect/Duration";
4
import * as Effect from "effect/Effect";
5
import * as Fiber from "effect/Fiber";
@@ -40,6 +41,8 @@ describe("DesktopLocalEnvironmentAuth", () => {
41
it.effect("exchanges the desktop bootstrap credential only once", () =>
42
Effect.gen(function* () {
43
const requestCount = yield* Ref.make(0);
44
+ const waiting = yield* Deferred.make<void>();
45
+ const ready = yield* Deferred.make<boolean>();
46
const layerHttpClient = Layer.succeed(
47
HttpClient.HttpClient,
48
HttpClient.make((request) =>
@@ -68,6 +71,11 @@ describe("DesktopLocalEnvironmentAuth", () => {
71
id: PRIMARY_LOCAL_ENVIRONMENT_ID,
72
label: Effect.succeed("Windows"),
73
currentConfig: Effect.succeedSome(config),
74
+ waitForReady: (timeout: Duration.Duration) =>
75
+ Deferred.succeed(waiting, undefined).pipe(
76
+ Effect.andThen(Deferred.await(ready)),
77
+ Effect.timeout(timeout),
78
+ ),
79
},
80
]),
81
} as unknown as DesktopBackendPool.DesktopBackendPool["Service"]);
@@ -77,13 +85,20 @@ describe("DesktopLocalEnvironmentAuth", () => {
85
86
const [first, second] = yield* Effect.gen(function* () {
87
const auth = yield* DesktopLocalEnvironmentAuth.DesktopLocalEnvironmentAuth;
80
- return yield* Effect.all([auth.getBearerToken, auth.getBearerToken]);
88
+ const tokens = yield* Effect.all([auth.getBearerToken, auth.getBearerToken]).pipe(
89
+ Effect.forkChild,
90
+ );
91
+ yield* Deferred.await(waiting);
92
+ yield* TestClock.adjust(Duration.seconds(16));
93
+ assert.strictEqual(yield* Ref.get(requestCount), 0);
94
+ yield* Deferred.succeed(ready, true);
95
+ return yield* Fiber.join(tokens);
96
}).pipe(Effect.provide(layerTest));
97
98
assert.strictEqual(first, "desktop-bearer-token");
99
assert.strictEqual(second, "desktop-bearer-token");
100
assert.strictEqual(yield* Ref.get(requestCount), 1);
86
- }),
101
+ }).pipe(Effect.provide(TestClock.layer())),
102
);
103
104
it.effect(
@@ -120,6 +135,7 @@ describe("DesktopLocalEnvironmentAuth", () => {
135
{
136
id: PRIMARY_LOCAL_ENVIRONMENT_ID,
137
label: Effect.succeed("Windows"),
138
+ waitForReady: () => Effect.succeed(true),
139
currentConfig: Effect.succeedSome({
140
...config,
141
bootstrap: { ...config.bootstrap, desktopBootstrapSecret: "desktop-secret" },
@@ -167,6 +183,7 @@ describe("DesktopLocalEnvironmentAuth", () => {
183
id: PRIMARY_LOCAL_ENVIRONMENT_ID,
184
label: Effect.succeed("Windows"),
185
currentConfig: Effect.succeedSome(config),
186
+ waitForReady: () => Effect.succeed(true),
187
},
188
]),
189
} as unknown as DesktopBackendPool.DesktopBackendPool["Service"]);
apps/desktop/src/backend/DesktopLocalEnvironmentAuth.ts
+4
-1
@@ -80,7 +80,10 @@ export const make = Effect.gen(function* () {
80
81
const instances = yield* pool.list;
82
const primary = instances.find((instance) => instance.id === PRIMARY_LOCAL_ENVIRONMENT_ID);
83
- const configOption = primary === undefined ? Option.none() : yield* primary.currentConfig;
83
+ if (primary === undefined || !(yield* primary.waitForReady(Duration.infinity))) {
84
+ return yield* new DesktopLocalEnvironmentAuthBackendNotConfiguredError();
85
+ }
86
+ const configOption = yield* primary.currentConfig;
87
if (Option.isNone(configOption)) {
88
return yield* new DesktopLocalEnvironmentAuthBackendNotConfiguredError();
89
}
apps/desktop/src/window/DesktopWindow.test.ts
+77
@@ -549,6 +549,79 @@ describe("DesktopWindow", () => {
549
}),
550
);
551
552
+ it.effect.each(["before", "after"] as const)(
553
+ "keeps a closed startup window closed until activation %s backend readiness",
554
+ (activation) =>
555
+ Effect.gen(function* () {
556
+ const fake = makeFakeBrowserWindow();
557
+ const createCount = yield* Ref.make(0);
558
+ const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
559
+ yield* Effect.gen(function* () {
560
+ const windows = yield* DesktopWindow.DesktopWindow;
561
+ yield* windows.ensureMain;
562
+ fake.windowListeners.get("ready-to-show")?.();
563
+ fake.isDestroyed.mockReturnValue(true);
564
+ fake.windowListeners.get("closed")?.();
565
+ assert.isTrue(Option.isNone(yield* Ref.get(mainWindow)));
566
+ if (activation === "after") {
567
+ yield* windows.handleBackendReady(new URL("http://127.0.0.1:3773"));
568
+ assert.equal(yield* Ref.get(createCount), 1);
569
+ }
570
+ fake.isDestroyed.mockReturnValue(false);
571
+ yield* windows.activate;
572
+ assert.equal(yield* Ref.get(createCount), 2);
573
+ yield* windows.handleBackendReady(new URL("http://127.0.0.1:3773"));
574
+ assert.equal(yield* Ref.get(createCount), 2);
575
+ }).pipe(Effect.provide(layerTest({ window: fake.window, createCount, mainWindow })));
576
+ }),
577
+ );
578
+
579
+ it.effect.each(["renderer", "backend"] as const)(
580
+ "reveals the painted boot shell when %s becomes ready first",
581
+ (first) =>
582
+ Effect.gen(function* () {
583
+ const fake = makeFakeBrowserWindow();
584
+ const createCount = yield* Ref.make(0);
585
+ const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
586
+ const reveal = vi.fn();
587
+ const painted = Promise.withResolvers<void>();
588
+ yield* Effect.gen(function* () {
589
+ const windows = yield* DesktopWindow.DesktopWindow;
590
+ yield* windows.ensureMain;
591
+ assert.equal(fake.loadURL.mock.calls.length, 1);
592
+ yield* windows.activate;
593
+ yield* windows.revealOrCreateMain;
594
+ yield* windows.dispatchMenuAction("open-settings");
595
+ assert.equal(reveal.mock.calls.length, 0);
596
+ if (first === "backend") {
597
+ yield* windows.handleBackendReady(new URL("http://127.0.0.1:3773"));
598
+ assert.equal(reveal.mock.calls.length, 0);
599
+ }
600
+ fake.windowListeners.get("ready-to-show")?.();
601
+ yield* Effect.promise(() => painted.promise);
602
+ assert.equal(reveal.mock.calls.length, 1);
603
+ yield* windows.handleBackendReady(new URL("http://127.0.0.1:3773"));
604
+ assert.equal(yield* Ref.get(createCount), 1);
605
+ assert.equal(reveal.mock.calls.length, 1);
606
+ yield* windows.handleBackendNotReady;
607
+ yield* windows.activate;
608
+ assert.equal(reveal.mock.calls.length, 2);
609
+ }).pipe(
610
+ Effect.provide(
611
+ layerTest({
612
+ window: fake.window,
613
+ createCount,
614
+ mainWindow,
615
+ onReveal: () => {
616
+ reveal();
617
+ painted.resolve();
618
+ },
619
+ }),
620
+ ),
621
+ );
622
+ }),
623
+ );
624
+
625
it.effect("blocks only repeated Cmd+W input before it reaches the native window menu", () =>
626
Effect.gen(function* () {
627
const fakeWindow = makeFakeBrowserWindow();
@@ -1133,6 +1206,10 @@ describe("DesktopWindow", () => {
1206
yield* Effect.gen(function* () {
1207
const desktopWindow = yield* DesktopWindow.DesktopWindow;
1208
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
1209
+ fakeWindow.windowListeners.get("ready-to-show")?.();
1210
+ yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
1211
+ operations.length = 0;
1212
+ foreground = "Discord";
1213
yield* desktopWindow.dispatchSnapShotEvent({ type: "started", id: captureOne });
1214
assert.equal(foreground, "T3 Code");
1215
foreground = "Explorer";
apps/desktop/src/window/DesktopWindow.ts
+43
-16
@@ -5,6 +5,7 @@ import * as Fiber from "effect/Fiber";
5
import * as Layer from "effect/Layer";
6
import * as Option from "effect/Option";
7
import * as Ref from "effect/Ref";
8
+import * as Semaphore from "effect/Semaphore";
9
10
import * as Electron from "electron";
11
@@ -306,10 +307,17 @@ export const make = Effect.gen(function* () {
307
const electronApp = yield* ElectronApp.ElectronApp;
308
const rendererHistory = yield* DesktopRendererHistory.DesktopRendererHistory;
309
const backendReadyRef = yield* Ref.make(false);
310
+ let backendHasStarted = false;
311
+ let mainClosedDuringStartup = false;
312
const splashWindowRef = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
313
const context = yield* Effect.context<DesktopWindowRuntimeServices>();
314
const runFork = Effect.runForkWith(context);
315
const runPromise = Effect.runPromiseWith(context);
316
+ const mainWindowMutex = yield* Semaphore.make(1);
317
+ const pendingMainReveals = new WeakMap<Electron.BrowserWindow, Effect.Effect<void>>();
318
+ const revealMain = Effect.fn("desktop.window.revealMain")((window: Electron.BrowserWindow) =>
319
+ Effect.suspend(() => pendingMainReveals.get(window) ?? electronWindow.reveal(window)),
320
+ );
321
let flushMainWindowBounds: Effect.Effect<void> = Effect.void;
322
323
const dismissConnectingSplash = Effect.gen(function* () {
@@ -407,6 +415,7 @@ export const make = Effect.gen(function* () {
415
return Option.none();
416
}
417
418
+ pendingMainReveals.set(window, Effect.void);
419
yield* rendererHistory.register(window.webContents, { surface: "main" });
420
if (environment.platform === "darwin") {
421
window.setAutoHideCursor(false);
@@ -822,14 +831,27 @@ export const make = Effect.gen(function* () {
831
if (environment.platform === "linux") {
832
revealSubscribers.push((fire) => window.webContents.once("did-finish-load", fire));
833
}
834
+ let rendererReady = false;
835
+ let firstRevealComplete = false;
836
+ const revealWhenReady = Effect.gen(function* () {
837
+ if (
838
+ !rendererReady ||
839
+ firstRevealComplete ||
840
+ window.isDestroyed() ||
841
+ (yield* Ref.get(desktopState.quitting))
842
+ )
843
+ return;
844
+ firstRevealComplete = true;
845
+ pendingMainReveals.delete(window);
846
+ window.webContents.setBackgroundThrottling(true);
847
+ if (persistedSettings.mainWindowMaximized) window.maximize();
848
+ yield* electronWindow.reveal(window);
849
+ yield* dismissConnectingSplash;
850
+ });
851
+ pendingMainReveals.set(window, revealWhenReady);
852
bindFirstRevealTrigger(revealSubscribers, () => {
826
- if (!window.isDestroyed()) {
827
- window.webContents.setBackgroundThrottling(true);
828
- }
829
- if (persistedSettings.mainWindowMaximized) {
830
- window.maximize();
831
- }
832
- void runPromise(Effect.andThen(electronWindow.reveal(window), dismissConnectingSplash));
853
+ rendererReady = true;
854
+ void runPromise(revealWhenReady);
855
});
856
857
loadApplication();
@@ -838,6 +860,7 @@ export const make = Effect.gen(function* () {
860
}
861
862
window.on("closed", () => {
863
+ if (!backendHasStarted) mainClosedDuringStartup = true;
864
clearDevelopmentLoadRetry();
865
clearBoundsPersist();
866
void runPromise(electronWindow.clearMain(Option.some(window)));
@@ -850,6 +873,7 @@ export const make = Effect.gen(function* () {
873
const window = yield* createWindow();
874
if (Option.isSome(window)) {
875
yield* electronWindow.setMain(window.value);
876
+ mainClosedDuringStartup = false;
877
yield* logWindowInfo("main window created");
878
}
879
return window;
@@ -862,7 +886,7 @@ export const make = Effect.gen(function* () {
886
return existingWindow;
887
}
888
return yield* createMain;
865
- }).pipe(Effect.withSpan("desktop.window.ensureMain"));
889
+ }).pipe(mainWindowMutex.withPermits(1), Effect.withSpan("desktop.window.ensureMain"));
890
891
const requireWindow = (window: Option.Option<Electron.BrowserWindow>) =>
892
Option.match(window, {
@@ -872,7 +896,7 @@ export const make = Effect.gen(function* () {
896
897
const revealOrCreateMain = Effect.gen(function* () {
898
const window = yield* ensureMain.pipe(Effect.flatMap(requireWindow));
875
- yield* electronWindow.reveal(window);
899
+ yield* revealMain(window);
900
return window;
901
}).pipe(Effect.withSpan("desktop.window.revealOrCreateMain"));
902
@@ -884,9 +908,7 @@ export const make = Effect.gen(function* () {
908
const createMainIfBackendReady = Effect.gen(function* () {
909
if (yield* Ref.get(desktopState.quitting)) return;
910
if (yield* waitingForBackend) return;
887
- const existingWindow = yield* currentMainWindow;
888
- if (Option.isSome(existingWindow)) return;
889
- yield* createMain;
911
+ yield* ensureMain;
912
}).pipe(Effect.withSpan("desktop.window.createMainIfBackendReady"));
913
914
const showConnectingSplash = Effect.gen(function* () {
@@ -956,7 +978,7 @@ export const make = Effect.gen(function* () {
978
});
979
// Send before best-effort reveal; another process may refuse to yield foreground focus.
980
const dispatch = reveal
959
- ? send.pipe(Effect.andThen(electronWindow.reveal(targetWindow).pipe(Effect.ignoreCause)))
981
+ ? send.pipe(Effect.andThen(revealMain(targetWindow).pipe(Effect.ignoreCause)))
982
: send;
983
if (targetWindow.webContents.isLoadingMainFrame()) {
984
targetWindow.webContents.once("did-finish-load", () => void runPromise(dispatch));
@@ -971,7 +993,7 @@ export const make = Effect.gen(function* () {
993
revealOrCreateMain,
994
prepareCaptureReveal: Effect.gen(function* () {
995
const existingWindow = yield* currentMainWindow;
974
- if (Option.isSome(existingWindow)) {
996
+ if (Option.isSome(existingWindow) && !pendingMainReveals.has(existingWindow.value)) {
997
yield* electronWindow.prepareReveal(existingWindow.value);
998
}
999
}),
@@ -979,7 +1001,11 @@ export const make = Effect.gen(function* () {
1001
if (yield* Ref.get(desktopState.quitting)) return;
1002
const existingWindow = yield* currentMainWindow;
1003
if (Option.isSome(existingWindow)) {
982
- yield* electronWindow.reveal(existingWindow.value);
1004
+ yield* revealMain(existingWindow.value);
1005
+ return;
1006
+ }
1007
+ if (mainClosedDuringStartup) {
1008
+ yield* ensureMain;
1009
return;
1010
}
1011
const backendReady = yield* Ref.get(backendReadyRef);
@@ -995,9 +1021,10 @@ export const make = Effect.gen(function* () {
1021
createMainIfBackendReady,
1022
showConnectingSplash,
1023
handleBackendReady: Effect.fn("desktop.window.handleBackendReady")(function* (httpBaseUrl) {
1024
+ backendHasStarted = true;
1025
yield* Ref.set(backendReadyRef, true);
1026
yield* logWindowInfo("backend ready", { source: "http", url: httpBaseUrl.href });
1000
- yield* createMainIfBackendReady;
1027
+ if (!mainClosedDuringStartup) yield* createMainIfBackendReady;
1028
}),
1029
handleBackendNotReady: Ref.set(backendReadyRef, false).pipe(
1030
Effect.withSpan("desktop.window.handleBackendNotReady"),
apps/web/src/environments/primary/httpLayer.test.ts
+22
-2
@@ -1,11 +1,20 @@
1
import type { DesktopBridge } from "@t3tools/contracts";
2
import { afterEach, describe, expect, it, vi } from "@effect/vitest";
3
import * as Effect from "effect/Effect";
4
+import * as Fiber from "effect/Fiber";
5
import { HttpClient } from "effect/http";
6
7
import { __resetDesktopPrimaryAuthForTests } from "./desktopAuth";
8
import * as PrimaryEnvironmentHttpLayer from "./httpLayer";
9
10
+function createSignal<A>() {
11
+ let resolve!: (value: A) => void;
12
+ const promise = new Promise<A>((complete) => {
13
+ resolve = complete;
14
+ });
15
+ return { promise, resolve };
16
+}
17
+
18
describe("primary environment HTTP layer", { concurrent: false }, () => {
19
afterEach(() => {
20
__resetDesktopPrimaryAuthForTests();
@@ -36,6 +45,8 @@ describe("primary environment HTTP layer", { concurrent: false }, () => {
45
});
46
47
it.effect("uses bearer auth without cookies for desktop-managed primaries", () => {
48
+ const requested = createSignal<void>();
49
+ const bearerToken = createSignal<string>();
50
const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 200 }));
51
vi.stubGlobal("fetch", fetchMock);
52
Object.defineProperty(globalThis, "window", {
@@ -49,13 +60,22 @@ describe("primary environment HTTP layer", { concurrent: false }, () => {
60
wsBaseUrl: "ws://127.0.0.1:3773",
61
bootstrapToken: "desktop-bootstrap-token",
62
}),
52
- getLocalEnvironmentBearerToken: vi.fn().mockResolvedValue("desktop-bearer-token"),
63
+ getLocalEnvironmentBearerToken: () => {
64
+ requested.resolve(undefined);
65
+ return bearerToken.promise;
66
+ },
67
} as unknown as DesktopBridge,
68
},
69
});
70
71
return Effect.gen(function* () {
58
- yield* HttpClient.get("http://127.0.0.1:3773/api/connect/link-state");
72
+ const requestFiber = yield* HttpClient.get(
73
+ "http://127.0.0.1:3773/api/connect/link-state",
74
+ ).pipe(Effect.forkChild);
75
+ yield* Effect.promise(() => requested.promise);
76
+ expect(fetchMock).not.toHaveBeenCalled();
77
+ bearerToken.resolve("desktop-bearer-token");
78
+ yield* Fiber.join(requestFiber);
79
80
const request = new Request(fetchMock.mock.calls[0]?.[0], fetchMock.mock.calls[0]?.[1]);
81
expect(request.credentials).not.toBe("include");