@devries-cameron20 / t3code Mirror · read-only / commits / 3087e60fa4
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 14:30 UTC

fix(desktop): a broken release opens an error window instead of hanging (#25903)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Theo Browne committed Oct 27, 2026 at 05:18 UTC 3087e60fa49b518cf3efb1000be727cc19085516
11 files changed +562 -12
apps/desktop/src/app/DesktopApp.ts
+2
@@ -29,6 +29,7 @@ import * as DesktopShutdown from "./DesktopShutdown.ts";
29 import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
30 import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
31 import * as DesktopShellEnvironment from "../shell/DesktopShellEnvironment.ts";
32 +import * as DesktopStartupRecovery from "./DesktopStartupRecovery.ts";
33 import * as DesktopState from "./DesktopState.ts";
34 import * as DesktopRemoteUpdates from "../updates/DesktopRemoteUpdates.ts";
35 import * as DesktopUpdates from "../updates/DesktopUpdates.ts";
@@ -325,6 +326,7 @@ const startup = Effect.gen(function* () {
326 yield* applicationMenu.configure;
327 yield* updates.configure;
328 yield* DesktopRemoteUpdates.listen;
329 + yield* DesktopStartupRecovery.listen;
330 yield* linuxUrlHandler.register;
331 yield* bootstrap.pipe(Effect.catchCause((cause) => fatalStartupCause("bootstrap", cause)));
332 }).pipe(Effect.withSpan("desktop.startup"));
apps/desktop/src/app/DesktopStartupRecovery.test.ts new
+70
@@ -0,0 +1,70 @@
1 +import type { DesktopUpdateState } from "@t3tools/contracts";
2 +import { describe, expect, it } from "vite-plus/test";
3 +
4 +import { createInitialDesktopUpdateState } from "../updates/updateMachine.ts";
5 +import { resolveStartupRecoveryOffer } from "./DesktopStartupRecovery.ts";
6 +
7 +const updateState = (patch: Partial<DesktopUpdateState>): DesktopUpdateState => ({
8 + ...createInitialDesktopUpdateState(
9 + "0.1.3",
10 + { hostArch: "arm64", appArch: "arm64", runningUnderArm64Translation: false },
11 + "latest",
12 + ),
13 + enabled: true,
14 + ...patch,
15 +});
16 +
17 +describe("resolveStartupRecoveryOffer", () => {
18 + it("offers a newer version before going back", () => {
19 + expect(
20 + resolveStartupRecoveryOffer(
21 + updateState({ status: "available", availableVersion: "0.1.4" }),
22 + "0.1.2",
23 + ),
24 + ).toEqual({ _tag: "Update", version: "0.1.4" });
25 + });
26 +
27 + it("offers a retained download after a later check fails", () => {
28 + expect(
29 + resolveStartupRecoveryOffer(
30 + updateState({ status: "error", errorContext: "check", downloadedVersion: "0.1.4" }),
31 + null,
32 + ),
33 + ).toEqual({ _tag: "Update", version: "0.1.4" });
34 + });
35 +
36 + it("waits for the update check before offering to go back", () => {
37 + expect(resolveStartupRecoveryOffer(updateState({ status: "checking" }), "0.1.2")).toEqual({
38 + _tag: "Checking",
39 + });
40 + });
41 +
42 + it("offers the last version that started when no update exists", () => {
43 + expect(resolveStartupRecoveryOffer(updateState({ status: "up-to-date" }), "0.1.2")).toEqual({
44 + _tag: "Reinstall",
45 + version: "0.1.2",
46 + });
47 + });
48 +
49 + it("does not offer an update that already failed to apply here", () => {
50 + expect(
51 + resolveStartupRecoveryOffer(
52 + updateState({
53 + status: "downloaded",
54 + downloadedVersion: "0.1.4",
55 + notAppliedVersion: "0.1.4",
56 + }),
57 + "0.1.2",
58 + ),
59 + ).toEqual({ _tag: "Reinstall", version: "0.1.2" });
60 + });
61 +
62 + it("falls back to the releases page when this version never started", () => {
63 + expect(resolveStartupRecoveryOffer(updateState({ status: "disabled" }), "0.1.3")).toEqual({
64 + _tag: "Releases",
65 + });
66 + expect(resolveStartupRecoveryOffer(updateState({ status: "up-to-date" }), null)).toEqual({
67 + _tag: "Releases",
68 + });
69 + });
70 +});
apps/desktop/src/app/DesktopStartupRecovery.ts new
+338
@@ -0,0 +1,338 @@
1 +import type { DesktopUpdateState } from "@t3tools/contracts";
2 +import * as Effect from "effect/Effect";
3 +import * as FileSystem from "effect/FileSystem";
4 +import * as Option from "effect/Option";
5 +import * as Ref from "effect/Ref";
6 +import type * as Scope from "effect/Scope";
7 +import * as Stream from "effect/Stream";
8 +import * as SubscriptionRef from "effect/SubscriptionRef";
9 +import type * as Electron from "electron";
10 +
11 +import * as ElectronApp from "../electron/ElectronApp.ts";
12 +import * as ElectronShell from "../electron/ElectronShell.ts";
13 +import * as ElectronTheme from "../electron/ElectronTheme.ts";
14 +import * as ElectronWindow from "../electron/ElectronWindow.ts";
15 +import * as DesktopUpdates from "../updates/DesktopUpdates.ts";
16 +import type { BackendStartupFailure } from "../backend/DesktopBackendManager.ts";
17 +import * as DesktopEnvironment from "./DesktopEnvironment.ts";
18 +import * as DesktopObservability from "./DesktopObservability.ts";
19 +import * as DesktopState from "./DesktopState.ts";
20 +
21 +const RELEASES_URL = "https://github.com/pingdotgg/t3code/releases";
22 +const LAST_STARTED_VERSION_FILE = "desktop-last-started-version";
23 +// Buttons are plain links to this host; will-navigate cancels them and runs the action.
24 +const ACTION_ORIGIN = "https://startup-recovery.invalid";
25 +
26 +const { logInfo, logWarning } = DesktopObservability.makeComponentLogger(
27 + "desktop-startup-recovery",
28 +);
29 +
30 +export type StartupRecoveryOffer =
31 + | { readonly _tag: "Checking" }
32 + | { readonly _tag: "Update"; readonly version: string }
33 + | { readonly _tag: "Downloading"; readonly version: string; readonly percent: number | null }
34 + | { readonly _tag: "Reinstall"; readonly version: string }
35 + | { readonly _tag: "Releases" };
36 +
37 +const STARTUP_RECOVERY_ACTIONS = ["update", "reinstall", "releases", "copy", "quit"] as const;
38 +type StartupRecoveryAction = (typeof STARTUP_RECOVERY_ACTIONS)[number];
39 +
40 +/** Prefer a newer build, then the last build that started on this machine, then the releases page. */
41 +export function resolveStartupRecoveryOffer(
42 + update: DesktopUpdateState,
43 + lastStartedVersion: string | null,
44 +): StartupRecoveryOffer {
45 + if (update.status === "downloading" && update.availableVersion !== null) {
46 + return {
47 + _tag: "Downloading",
48 + version: update.availableVersion,
49 + percent: update.downloadPercent,
50 + };
51 + }
52 + const updateVersion =
53 + update.downloadedVersion ?? (update.status === "available" ? update.availableVersion : null);
54 + // A version that already failed to apply here would loop through install and relaunch.
55 + if (updateVersion !== null && updateVersion !== update.notAppliedVersion) {
56 + return { _tag: "Update", version: updateVersion };
57 + }
58 + if (update.enabled && (update.status === "idle" || update.status === "checking")) {
59 + return { _tag: "Checking" };
60 + }
61 + if (lastStartedVersion !== null && lastStartedVersion !== update.currentVersion) {
62 + return { _tag: "Reinstall", version: lastStartedVersion };
63 + }
64 + return { _tag: "Releases" };
65 +}
66 +
67 +const escapeHtml = (value: string) =>
68 + value.replace(
69 + /[&<>"']/g,
70 + (char) =>
71 + ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[char] ?? char,
72 + );
73 +
74 +const actionLink = (action: StartupRecoveryAction, label: string, primary = false) =>
75 + `<a class="button${primary ? " primary" : ""}" href="${ACTION_ORIGIN}/${action}">${escapeHtml(label)}</a>`;
76 +
77 +function describeOffer(offer: StartupRecoveryOffer): { text: string; action: string } {
78 + switch (offer._tag) {
79 + case "Checking":
80 + return { text: "Checking for a newer version…", action: "" };
81 + case "Update":
82 + return {
83 + text: `Version ${offer.version} is available. It can contain a fix.`,
84 + action: actionLink("update", `Update to ${offer.version}`, true),
85 + };
86 + case "Downloading":
87 + return {
88 + text: `Downloading ${offer.version}${offer.percent === null ? "" : ` (${Math.floor(offer.percent / 10) * 10}%)`}. T3 Code restarts when the download is done.`,
89 + action: "",
90 + };
91 + case "Reinstall":
92 + return {
93 + text: `Version ${offer.version} started correctly on this computer. Download it and install it to go back.`,
94 + action: actionLink("reinstall", `Download ${offer.version}`, true),
95 + };
96 + case "Releases":
97 + return {
98 + text: "Get a different version from the releases page.",
99 + action: actionLink("releases", "Open releases", true),
100 + };
101 + }
102 +}
103 +
104 +function buildStartupRecoveryHtml(input: {
105 + readonly appVersion: string;
106 + readonly failure: BackendStartupFailure;
107 + readonly offer: StartupRecoveryOffer;
108 + readonly logDir: string;
109 +}): string {
110 + const offer = describeOffer(input.offer);
111 + const output = input.failure.output.trim();
112 + return `<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'"><title>T3 Code could not start</title><style>
113 +:root{color-scheme:light dark;--bg:#fff;--fg:#111;--muted:#666;--line:#ddd;--code:#f4f4f4}
114 +@media (prefers-color-scheme:dark){:root{--bg:#000;--fg:#fff;--muted:#999;--line:#333;--code:#111}}
115 +html,body{margin:0;height:100%;background:var(--bg);color:var(--fg)}
116 +body{font:13px/1.5 system-ui,-apple-system,'Segoe UI',sans-serif;padding:28px;box-sizing:border-box;display:flex;flex-direction:column;gap:14px}
117 +h1{font-size:18px;margin:0}p{margin:0}.muted{color:var(--muted)}
118 +.actions{display:flex;gap:8px;flex-wrap:wrap}
119 +.button{color:var(--fg);text-decoration:none;border:1px solid var(--line);border-radius:6px;padding:6px 12px}
120 +.button.primary{background:var(--fg);color:var(--bg);border-color:var(--fg)}
121 +pre{flex:1;min-height:60px;margin:0;overflow:auto;background:var(--code);border:1px solid var(--line);border-radius:6px;padding:10px;font:11px/1.4 ui-monospace,Menlo,Consolas,monospace;white-space:pre-wrap;word-break:break-word}
122 +</style></head><body>
123 +<h1>T3 Code could not start</h1>
124 +<p>${escapeHtml(input.failure.reason)}</p>
125 +<p>${escapeHtml(offer.text)}</p>
126 +<div class="actions">${offer.action}${actionLink("copy", "Copy details")}${actionLink("quit", "Quit")}</div>
127 +<pre>${escapeHtml(output.length > 0 ? output : "The server wrote no output.")}</pre>
128 +<p class="muted">Version ${escapeHtml(input.appVersion)}. T3 Code tries again in the background. Logs: ${escapeHtml(input.logDir)}</p>
129 +</body></html>`;
130 +}
131 +
132 +/** Shows a self-contained error window while the primary backend fails to start, so a broken release still opens. */
133 +export const listen: Effect.Effect<
134 + void,
135 + never,
136 + | DesktopState.DesktopState
137 + | DesktopUpdates.DesktopUpdates
138 + | DesktopEnvironment.DesktopEnvironment
139 + | ElectronApp.ElectronApp
140 + | ElectronShell.ElectronShell
141 + | ElectronTheme.ElectronTheme
142 + | ElectronWindow.ElectronWindow
143 + | FileSystem.FileSystem
144 + | Scope.Scope
145 +> = Effect.gen(function* () {
146 + const { primaryBackendStartup, quitting } = yield* DesktopState.DesktopState;
147 + const updates = yield* DesktopUpdates.DesktopUpdates;
148 + const environment = yield* DesktopEnvironment.DesktopEnvironment;
149 + const electronApp = yield* ElectronApp.ElectronApp;
150 + const electronShell = yield* ElectronShell.ElectronShell;
151 + const electronTheme = yield* ElectronTheme.ElectronTheme;
152 + const electronWindow = yield* ElectronWindow.ElectronWindow;
153 + const fileSystem = yield* FileSystem.FileSystem;
154 + const runFork = Effect.runForkWith(yield* Effect.context<never>());
155 +
156 + const lastStartedVersionPath = environment.path.join(
157 + environment.stateDir,
158 + LAST_STARTED_VERSION_FILE,
159 + );
160 + const lastStartedVersion = yield* fileSystem.readFileString(lastStartedVersionPath).pipe(
161 + Effect.map((text) => text.trim() || null),
162 + Effect.orElseSucceed(() => null),
163 + );
164 +
165 + const windowRef = yield* Ref.make(Option.none<Electron.BrowserWindow>());
166 + // The failure that opened the window; later restarts do not reload its details.
167 + const failureRef = yield* Ref.make(Option.none<BackendStartupFailure>());
168 + const renderedHtmlRef = yield* Ref.make("");
169 + const checkedRef = yield* Ref.make(false);
170 + const { latest, changes: updateChanges } = yield* updates.subscribe;
171 + const updateStateRef = yield* Ref.make(latest);
172 +
173 + const offer = Ref.get(updateStateRef).pipe(
174 + Effect.map((state) => resolveStartupRecoveryOffer(state, lastStartedVersion)),
175 + );
176 +
177 + const render = Effect.gen(function* () {
178 + const window = yield* Ref.get(windowRef);
179 + const failure = yield* Ref.get(failureRef);
180 + if (Option.isNone(window) || Option.isNone(failure) || window.value.isDestroyed()) return;
181 + const html = buildStartupRecoveryHtml({
182 + appVersion: environment.appVersion,
183 + failure: failure.value,
184 + offer: yield* offer,
185 + logDir: environment.logDir,
186 + });
187 + if ((yield* Ref.getAndSet(renderedHtmlRef, html)) === html) return;
188 + void window.value.loadURL(`data:text/html;charset=utf-8,${encodeURIComponent(html)}`);
189 + });
190 +
191 + const runAction = Effect.fn("desktop.startupRecovery.runAction")(function* (
192 + action: StartupRecoveryAction,
193 + ) {
194 + yield* logInfo("startup recovery action", { action });
195 + const current = yield* offer;
196 + switch (action) {
197 + case "update": {
198 + if (current._tag !== "Update") return;
199 + const state = yield* updates.getState;
200 + if (state.downloadedVersion === null) {
201 + const download = yield* updates.download;
202 + if (!download.completed) return;
203 + }
204 + // Waits for a running background check; plain install would refuse.
205 + yield* updates.installPrepared(current.version);
206 + return;
207 + }
208 + case "reinstall":
209 + if (current._tag === "Reinstall") {
210 + yield* electronShell.openExternal(`${RELEASES_URL}/tag/v${current.version}`);
211 + }
212 + return;
213 + case "releases":
214 + yield* electronShell.openExternal(RELEASES_URL);
215 + return;
216 + case "copy": {
217 + const failure = yield* Ref.get(failureRef);
218 + if (Option.isNone(failure)) return;
219 + yield* electronShell.copyText(
220 + `T3 Code ${environment.appVersion} (${environment.platform} ${environment.processArch}) could not start.\n${failure.value.reason}\n\n${failure.value.output}`,
221 + );
222 + return;
223 + }
224 + case "quit":
225 + yield* electronApp.quit;
226 + return;
227 + }
228 + });
229 +
230 + const show = Effect.fn("desktop.startupRecovery.show")(
231 + function* () {
232 + 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;
235 + const existing = yield* Ref.get(windowRef);
236 + if (Option.isSome(existing) && !existing.value.isDestroyed()) {
237 + yield* electronWindow.reveal(existing.value);
238 + return;
239 + }
240 + const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
241 + const window = yield* electronWindow.create(
242 + {
243 + width: 640,
244 + height: 480,
245 + minWidth: 420,
246 + minHeight: 320,
247 + show: false,
248 + title: "T3 Code could not start",
249 + autoHideMenuBar: true,
250 + backgroundColor: shouldUseDarkColors ? "#000000" : "#ffffff",
251 + webPreferences: {
252 + contextIsolation: true,
253 + nodeIntegration: false,
254 + sandbox: true,
255 + javascript: false,
256 + },
257 + },
258 + { auxiliary: true },
259 + );
260 + window.webContents.setWindowOpenHandler(() => ({ action: "deny" }));
261 + window.webContents.on("will-navigate", (event, url) => {
262 + event.preventDefault();
263 + const action = STARTUP_RECOVERY_ACTIONS.find((name) => url === `${ACTION_ORIGIN}/${name}`);
264 + if (action !== undefined) runFork(runAction(action));
265 + });
266 + window.once("ready-to-show", () => {
267 + if (!window.isDestroyed()) window.show();
268 + });
269 + window.once("closed", () => {
270 + runFork(
271 + Ref.set(windowRef, Option.none()).pipe(Effect.andThen(Ref.set(renderedHtmlRef, ""))),
272 + );
273 + });
274 + yield* Ref.set(windowRef, Option.some(window));
275 + yield* render;
276 + yield* logInfo("startup recovery window shown");
277 + },
278 + Effect.catch((error) =>
279 + logWarning("could not show startup recovery", { errorTag: error._tag }),
280 + ),
281 + );
282 +
283 + const close = Effect.gen(function* () {
284 + const window = yield* Ref.getAndSet(windowRef, Option.none());
285 + if (Option.isSome(window) && !window.value.isDestroyed()) window.value.close();
286 + });
287 +
288 + const rememberStartedVersion = Effect.gen(function* () {
289 + if (lastStartedVersion === environment.appVersion) return;
290 + yield* fileSystem.writeFileString(lastStartedVersionPath, environment.appVersion);
291 + }).pipe(
292 + Effect.catch((error) =>
293 + logWarning("could not record the started version", { errorTag: error._tag }),
294 + ),
295 + );
296 +
297 + yield* updateChanges.pipe(
298 + Stream.runForEach((state) => Ref.set(updateStateRef, state).pipe(Effect.andThen(render))),
299 + Effect.forkScoped,
300 + );
301 +
302 + yield* SubscriptionRef.changes(primaryBackendStartup).pipe(
303 + Stream.runForEach(
304 + Effect.fn("desktop.startupRecovery.onStartupChange")(function* (startup) {
305 + if (startup._tag === "Ready") {
306 + yield* Ref.set(failureRef, Option.none());
307 + yield* close;
308 + yield* rememberStartedVersion;
309 + return;
310 + }
311 + if (startup._tag !== "Failing") return;
312 + if (Option.isSome(yield* Ref.get(failureRef))) return;
313 + yield* Ref.set(failureRef, Option.some({ reason: startup.reason, output: startup.output }));
314 + // The backend manager already logs each failure's reason.
315 + yield* logWarning("primary backend failing to start");
316 + yield* show();
317 + if (!(yield* Ref.getAndSet(checkedRef, true))) {
318 + yield* updates.check("startup-recovery").pipe(Effect.forkScoped);
319 + }
320 + }),
321 + ),
322 + Effect.catchCause((cause) =>
323 + Effect.logWarning("startup recovery stopped", cause).pipe(
324 + Effect.annotateLogs({ component: "desktop-startup-recovery" }),
325 + ),
326 + ),
327 + Effect.forkScoped,
328 + );
329 +
330 + // macOS keeps running with no windows; the Dock icon must bring the error back.
331 + yield* electronApp.on("activate", () => {
332 + runFork(
333 + Ref.get(failureRef).pipe(
334 + Effect.flatMap((failure) => (Option.isSome(failure) ? show() : Effect.void)),
335 + ),
336 + );
337 + });
338 +});
apps/desktop/src/app/DesktopState.ts
+11
@@ -2,18 +2,29 @@ import * as Context from "effect/Context";
2 import * as Effect from "effect/Effect";
3 import * as Layer from "effect/Layer";
4 import * as Ref from "effect/Ref";
5 +import * as SubscriptionRef from "effect/SubscriptionRef";
6 +
7 +import type { BackendStartupFailure } from "../backend/DesktopBackendManager.ts";
8 +
9 +/** Startup health of the primary local backend, read by the startup recovery window. */
10 +export type PrimaryBackendStartup =
11 + | { readonly _tag: "Starting" }
12 + | { readonly _tag: "Ready" }
13 + | ({ readonly _tag: "Failing" } & BackendStartupFailure);
14
15 export class DesktopState extends Context.Service<
16 DesktopState,
17 {
18 readonly backendReady: Ref.Ref<boolean>;
19 readonly quitting: Ref.Ref<boolean>;
20 + readonly primaryBackendStartup: SubscriptionRef.SubscriptionRef<PrimaryBackendStartup>;
21 }
22 >()("@t3tools/desktop/app/DesktopState") {}
23
24 const make = Effect.all({
25 backendReady: Ref.make(false),
26 quitting: Ref.make(false),
27 + primaryBackendStartup: SubscriptionRef.make<PrimaryBackendStartup>({ _tag: "Starting" }),
28 });
29
30 export const layer = Layer.effect(DesktopState, make);
apps/desktop/src/backend/DesktopBackendManager.test.ts
+56
@@ -123,6 +123,9 @@ interface MakeInstanceInput {
123 readonly onReady?: Effect.Effect<void>;
124 readonly onShutdown?: Effect.Effect<void>;
125 readonly onStateDirOwned?: Effect.Effect<void>;
126 + readonly onStartupFailure?: (
127 + failure: DesktopBackendManager.BackendStartupFailure,
128 + ) => Effect.Effect<void>;
129 readonly onPreflightFailed?: (
130 failure: DesktopBackendManager.PreflightFailure,
131 ) => Effect.Effect<boolean>;
@@ -182,6 +185,7 @@ function makeTestInstance(input: MakeInstanceInput) {
185 ...(input.onShutdown ? { onShutdown: () => input.onShutdown! } : {}),
186 ...(input.onStateDirOwned ? { onStateDirOwned: () => input.onStateDirOwned! } : {}),
187 ...(input.onPreflightFailed ? { onPreflightFailed: input.onPreflightFailed } : {}),
188 + ...(input.onStartupFailure ? { onStartupFailure: input.onStartupFailure } : {}),
189 });
190
191 return instance.pipe(Effect.provide(layerServices));
@@ -575,4 +579,56 @@ describe("DesktopBackendManager", () => {
579 }).pipe(Effect.provide(TestClock.layer())),
580 ),
581 );
582 +
583 + it.effect("reports a crash loop with the server output on the third restart", () =>
584 + Effect.scoped(
585 + Effect.gen(function* () {
586 + const message = "Error: Cannot find module 'zod/v4' in /Users/René";
587 + let exitCount = 0;
588 + const firstExit = yield* Deferred.make<void>();
589 + const reports = yield* Queue.unbounded<{
590 + readonly exitCount: number;
591 + readonly failure: DesktopBackendManager.BackendStartupFailure;
592 + }>();
593 + const instance = yield* makeTestInstance({
594 + spawnerLayer: Layer.succeed(
595 + ChildProcessSpawner.ChildProcessSpawner,
596 + ChildProcessSpawner.make(() =>
597 + Effect.succeed(
598 + makeProcess({
599 + // "é" split across chunks must not decode as U+FFFD, and the 4,000-char cut
600 + // lands inside the emoji's surrogate pair.
601 + stderr: Stream.make(
602 + new TextEncoder().encode(
603 + `😀${"x".repeat(3_999 - message.length)}${message.slice(0, -1)}`,
604 + ),
605 + new Uint8Array([0xc3]),
606 + new Uint8Array([0xa9]),
607 + ),
608 + exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),
609 + }),
610 + ),
611 + ),
612 + ),
613 + httpClientLayer: layerHttpClient(() => Effect.never),
614 + backendOutputLog: {
615 + persistFailure: () => {
616 + exitCount += 1;
617 + return Deferred.succeed(firstExit, undefined).pipe(Effect.asVoid);
618 + },
619 + },
620 + onStartupFailure: (failure) =>
621 + Queue.offer(reports, { exitCount, failure }).pipe(Effect.asVoid),
622 + });
623 + yield* instance.start;
624 + yield* Deferred.await(firstExit);
625 + yield* TestClock.adjust(Duration.minutes(1));
626 + const { exitCount: exitsWhenReported, failure } = yield* Queue.take(reports);
627 + assert.equal(exitsWhenReported, 3);
628 + assert.equal(failure.reason, "The server could not start (code=1).");
629 + assert.isTrue(failure.output.endsWith(message));
630 + assert.isTrue(failure.output.isWellFormed());
631 + }).pipe(Effect.provide(TestClock.layer())),
632 + ),
633 + );
634 });
apps/desktop/src/backend/DesktopBackendManager.ts
+40 -9
@@ -41,6 +41,9 @@ const DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT = Duration.seconds(1);
41 const DEFAULT_BACKEND_TERMINATE_GRACE = Duration.seconds(5);
42 const DEFAULT_BACKEND_OUTPUT_DRAIN_TIMEOUT = Duration.seconds(5);
43 const BACKEND_READINESS_PATH = "/.well-known/t3/environment";
44 +// Three restarts without readiness is about 2 s of backoff: past a blip, early enough to help.
45 +const STARTUP_FAILURE_RESTART_ATTEMPTS = 3;
46 +const STARTUP_FAILURE_OUTPUT_CHARS = 4_000;
47 const { logWarning: logBackendProcessWarning } =
48 DesktopObservability.makeComponentLogger("desktop-backend-process");
49
@@ -217,6 +220,12 @@ export const PRIMARY_INSTANCE_ID: BackendInstanceId = BackendInstanceId(
220 PRIMARY_LOCAL_ENVIRONMENT_ID,
221 );
222
223 +export interface BackendStartupFailure {
224 + readonly reason: string;
225 + /** Tail of the last run's stdout and stderr. */
226 + readonly output: string;
227 +}
228 +
229 export interface DesktopBackendInstance {
230 readonly id: BackendInstanceId;
231 readonly label: Effect.Effect<string>;
@@ -236,6 +245,8 @@ export interface BackendInstanceSpec {
245 readonly onShutdown?: () => Effect.Effect<void>;
246 readonly onPreflightFailed?: (failure: PreflightFailure) => Effect.Effect<boolean>;
247 readonly onStateDirOwned?: () => Effect.Effect<void>;
248 + /** Fires on each repeated crash or readiness timeout until the backend becomes ready. */
249 + readonly onStartupFailure?: (failure: BackendStartupFailure) => Effect.Effect<void>;
250 }
251
252 interface ActiveBackendRun {
@@ -619,6 +630,14 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
630 const httpClient = yield* HttpClient.HttpClient;
631 const state = yield* Ref.make(initialState);
632 const mutex = yield* Semaphore.make(1);
633 + const outputTail = yield* Ref.make("");
634 + // One streaming decoder per stream keeps UTF-8 characters split across chunks intact.
635 + const makeOutputDecoders = () => ({ stdout: new TextDecoder(), stderr: new TextDecoder() });
636 + let outputDecoders = makeOutputDecoders();
637 + const reportStartupFailure = (reason: string) =>
638 + Ref.get(outputTail).pipe(
639 + Effect.flatMap((output) => spec.onStartupFailure?.({ reason, output }) ?? Effect.void),
640 + );
641
642 const { logWarning: logInstanceWarning, logError: logInstanceError } =
643 DesktopObservability.makeComponentLogger(`desktop-backend-instance:${spec.id}`);
@@ -875,6 +894,8 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
894 ...run,
895 pid: Option.some(pid),
896 }));
897 + yield* Ref.set(outputTail, "");
898 + outputDecoders = makeOutputDecoders();
899 yield* backendOutputLog.beginSession({
900 details: `pid=${pid} port=${config.value.bootstrap.port} cwd=${config.value.cwd}`,
901 });
@@ -923,9 +944,16 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
944 yield* backendOutputLog.persistFailureSnapshot({
945 details: error.message,
946 });
947 + yield* reportStartupFailure("The server started but did not become ready in time.");
948 },
949 ),
928 - onOutput: (streamName, chunk) => backendOutputLog.writeOutputChunk(streamName, chunk),
950 + onOutput: (streamName, chunk) =>
951 + Ref.update(outputTail, (tail) =>
952 + // A cut through a surrogate pair would make encodeURIComponent throw when rendering.
953 + (tail + outputDecoders[streamName].decode(chunk, { stream: true }))
954 + .slice(-STARTUP_FAILURE_OUTPUT_CHARS)
955 + .toWellFormed(),
956 + ).pipe(Effect.andThen(backendOutputLog.writeOutputChunk(streamName, chunk))),
957 }).pipe(
958 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
959 Effect.provideService(HttpClient.HttpClient, httpClient),
@@ -951,26 +979,29 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (
979 ) {
980 const scheduled = yield* Ref.modify(state, (latest) => {
981 if (!latest.desiredRunning || Option.isSome(latest.restartFiber)) {
954 - return [Option.none<Duration.Duration>(), latest] as const;
982 + return [Option.none<{ delay: Duration.Duration; attempt: number }>(), latest] as const;
983 }
984
957 - const delay = calculateRestartDelay(latest.restartAttempt);
985 + const attempt = latest.restartAttempt + 1;
986 return [
959 - Option.some(delay),
960 - {
961 - ...latest,
962 - restartAttempt: latest.restartAttempt + 1,
963 - },
987 + Option.some({ delay: calculateRestartDelay(latest.restartAttempt), attempt }),
988 + { ...latest, restartAttempt: attempt },
989 ] as const;
990 });
991
992 yield* Option.match(scheduled, {
993 onNone: () => Effect.void,
969 - onSome: Effect.fn("desktop.backendInstance.scheduleRestartFiber")(function* (delay) {
994 + onSome: Effect.fn("desktop.backendInstance.scheduleRestartFiber")(function* ({
995 + delay,
996 + attempt,
997 + }) {
998 yield* logInstanceError("backend exited unexpectedly; restart scheduled", {
999 reason,
1000 delayMs: Duration.toMillis(delay),
1001 });
1002 + if (attempt >= STARTUP_FAILURE_RESTART_ATTEMPTS) {
1003 + yield* reportStartupFailure(`The server could not start (${reason}).`);
1004 + }
1005 const restartFiber = yield* Effect.forkIn(
1006 Effect.sleep(delay).pipe(
1007 Effect.andThen(
apps/desktop/src/backend/DesktopBackendPool.test.ts
+2
@@ -9,6 +9,7 @@ import { HttpClient } from "effect/http";
9 import { ChildProcessSpawner } from "effect/process";
10
11 import * as DesktopObservability from "../app/DesktopObservability.ts";
12 +import * as DesktopState from "../app/DesktopState.ts";
13 import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
14 import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
15 import * as DesktopBrowserHost from "../preview/DesktopBrowserHost.ts";
@@ -62,6 +63,7 @@ function layerPool(labelRef: Ref.Ref<string>): Layer.Layer<DesktopBackendPool.De
63 currentBootstrapToken: Effect.die("unexpected bootstrap token read"),
64 } satisfies DesktopBackendConfiguration.DesktopBackendConfiguration["Service"]),
65 DesktopAppSettings.layerTest(),
66 + DesktopState.layer,
67 DesktopWslEnvironment.layerTest(),
68 ElectronDialog.layer,
69 ElectronApp.layer,
apps/desktop/src/backend/DesktopBackendPool.ts
+7
@@ -6,6 +6,7 @@ import * as Layer from "effect/Layer";
6 import * as Option from "effect/Option";
7 import * as Schema from "effect/Schema";
8 import * as Scope from "effect/Scope";
9 +import * as SubscriptionRef from "effect/SubscriptionRef";
10 import * as SynchronizedRef from "effect/SynchronizedRef";
11
12 import * as FileSystem from "effect/FileSystem";
@@ -15,6 +16,7 @@ import { ChildProcessSpawner } from "effect/process";
16 import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
17 import * as DesktopBackendManager from "./DesktopBackendManager.ts";
18 import * as DesktopObservability from "../app/DesktopObservability.ts";
19 +import * as DesktopState from "../app/DesktopState.ts";
20 import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
21 import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
22 import * as DesktopBrowserHost from "../preview/DesktopBrowserHost.ts";
@@ -106,6 +108,7 @@ export const layer = Layer.effect(
108 const electronDialog = yield* ElectronDialog.ElectronDialog;
109 const electronApp = yield* ElectronApp.ElectronApp;
110 const appSettings = yield* DesktopAppSettings.DesktopAppSettings;
111 + const { primaryBackendStartup } = yield* DesktopState.DesktopState;
112 // Parent instance scopes to the pool so shutdown runs stop finalizers before the OS kills backends.
113 const layerScope = yield* Scope.Scope;
114 const factoryContext = yield* Effect.context<BackendInstanceFactoryRequirements>();
@@ -158,12 +161,16 @@ export const layer = Layer.effect(
161 // Absorb window errors so readiness can reset restartAttempt.
162 onReady: (httpBaseUrl) =>
163 desktopWindow.handleBackendReady(httpBaseUrl).pipe(
164 + // Only once the main window exists, so the recovery window never closes into nothing.
165 + Effect.andThen(SubscriptionRef.set(primaryBackendStartup, { _tag: "Ready" })),
166 Effect.catch((error) =>
167 logBackendPoolWarning("failed to open main window after backend readiness", {
168 error: error.message,
169 }),
170 ),
171 ),
172 + onStartupFailure: (failure) =>
173 + SubscriptionRef.set(primaryBackendStartup, { _tag: "Failing", ...failure }),
174 onShutdown: () => desktopWindow.handleBackendNotReady,
175 onPreflightFailed: handlePrimaryPreflightFailure,
176 onStateDirOwned: () =>
apps/desktop/src/electron/ElectronWindow.test.ts
+16
@@ -162,4 +162,20 @@ describe("ElectronWindow", () => {
162 assert.equal(vi.mocked(laterWindow.destroy).mock.calls.length, 1);
163 }).pipe(Effect.provide(layerTest)),
164 );
165 +
166 + it.effect("never falls back to an auxiliary window as the main window", () =>
167 + Effect.gen(function* () {
168 + const electronWindow = yield* ElectronWindow.ElectronWindow;
169 + const auxiliary = yield* electronWindow.create({}, { auxiliary: true });
170 + const ordinary = { isDestroyed: () => false } as unknown as Electron.BrowserWindow;
171 + Object.assign(auxiliary, { isDestroyed: () => false });
172 +
173 + getAllWindowsMock.mockReturnValue([auxiliary]);
174 + assert.isTrue((yield* electronWindow.currentMainOrFirst)._tag === "None");
175 +
176 + getAllWindowsMock.mockReturnValue([auxiliary, ordinary]);
177 + const current = yield* electronWindow.currentMainOrFirst;
178 + assert.isTrue(current._tag === "Some" && current.value === ordinary);
179 + }).pipe(Effect.provide(layerTest)),
180 + );
181 });
apps/desktop/src/electron/ElectronWindow.ts
+12 -3
@@ -109,8 +109,10 @@ export class ElectronWindowOperationError extends Schema.TaggedError<ElectronWin
109 export class ElectronWindow extends Context.Service<
110 ElectronWindow,
111 {
112 + /** Auxiliary windows are never returned as the main-or-first fallback. */
113 readonly create: (
114 options: Electron.BrowserWindowConstructorOptions,
115 + behavior?: { readonly auxiliary?: boolean },
116 ) => Effect.Effect<Electron.BrowserWindow, ElectronWindowCreateError>;
117 readonly main: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
118 readonly currentMainOrFirst: Effect.Effect<Option.Option<Electron.BrowserWindow>>;
@@ -141,6 +143,7 @@ export const make = Effect.gen(function* () {
143 const captureRevealWindows = new Set<number>();
144 yield* Effect.addFinalizer(() => Effect.sync(() => windowsForegroundFocus?.close()));
145 const mainWindowRef = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
146 + const auxiliaryWindows = new WeakSet<Electron.BrowserWindow>();
147
148 const listWindows = Effect.try({
149 try: () => Electron.BrowserWindow.getAllWindows(),
@@ -181,7 +184,9 @@ export const make = Effect.gen(function* () {
184 return main;
185 }
186
184 - const first = Option.fromNullishOr((yield* listWindows)[0] ?? null);
187 + const first = Option.fromNullishOr(
188 + (yield* listWindows).find((window) => !auxiliaryWindows.has(window)) ?? null,
189 + );
190 if (Option.isNone(first) || (yield* isWindowDestroyed(first.value))) {
191 return Option.none<Electron.BrowserWindow>();
192 }
@@ -207,7 +212,7 @@ export const make = Effect.gen(function* () {
212 });
213
214 return ElectronWindow.of({
210 - create: Effect.fn("ElectronWindow.create")(function (options) {
215 + create: Effect.fn("ElectronWindow.create")(function (options, behavior) {
216 const webPreferences = options.webPreferences;
217 const diagnosticOptions = {
218 title: options.title ?? null,
@@ -232,7 +237,11 @@ export const make = Effect.gen(function* () {
237 } satisfies typeof ElectronWindowCreateOptions.Type;
238
239 return Effect.try({
235 - try: () => new Electron.BrowserWindow(options),
240 + try: () => {
241 + const window = new Electron.BrowserWindow(options);
242 + if (behavior?.auxiliary === true) auxiliaryWindows.add(window);
243 + return window;
244 + },
245 catch: (cause) => new ElectronWindowCreateError({ options: diagnosticOptions, cause }),
246 });
247 }),
docs/user/updating.md
+8
@@ -111,6 +111,14 @@ Only one server can use a T3 home directory at a time. If startup reports that
111 another server owns it, stop that server before retrying, or use a separate home
112 directory and pair with the running server.
113
114 +## If the desktop app does not start
115 +
116 +If the desktop app's server keeps failing at startup, T3 Code shows a "T3 Code
117 +could not start" window instead of the app. If a newer version is available,
118 +choose **Update** to install it. If not, the window links to the last version
119 +that started on your computer. Download and install it to go back. Use **Copy
120 +details** to include the error in a bug report.
121 +
122 ## Update providers
123
124 **Settings → Providers** shows provider updates for the selected environment.