TypeScript
fix(desktop): a broken release opens an error window instead of hanging (#25903)
Theo Browne3087e60fa49b
diff --git a/apps/desktop/src/app/DesktopApp.ts b/apps/desktop/src/app/DesktopApp.tsindex f57e709bca7..d49d2cdebb7 100644--- a/apps/desktop/src/app/DesktopApp.ts+++ b/apps/desktop/src/app/DesktopApp.ts@@ -29,6 +29,7 @@ import * as DesktopShutdown from "./DesktopShutdown.ts";import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";import * as DesktopShellEnvironment from "../shell/DesktopShellEnvironment.ts";+import * as DesktopStartupRecovery from "./DesktopStartupRecovery.ts";import * as DesktopState from "./DesktopState.ts";import * as DesktopRemoteUpdates from "../updates/DesktopRemoteUpdates.ts";import * as DesktopUpdates from "../updates/DesktopUpdates.ts";@@ -325,6 +326,7 @@ const startup = Effect.gen(function* () {yield* applicationMenu.configure;yield* updates.configure;yield* DesktopRemoteUpdates.listen;+ yield* DesktopStartupRecovery.listen;yield* linuxUrlHandler.register;yield* bootstrap.pipe(Effect.catchCause((cause) => fatalStartupCause("bootstrap", cause)));}).pipe(Effect.withSpan("desktop.startup"));diff --git a/apps/desktop/src/app/DesktopStartupRecovery.test.ts b/apps/desktop/src/app/DesktopStartupRecovery.test.tsnew file mode 100644index 00000000000..d8a0ef1a999--- /dev/null+++ b/apps/desktop/src/app/DesktopStartupRecovery.test.ts@@ -0,0 +1,70 @@+import type { DesktopUpdateState } from "@t3tools/contracts";+import { describe, expect, it } from "vite-plus/test";++import { createInitialDesktopUpdateState } from "../updates/updateMachine.ts";+import { resolveStartupRecoveryOffer } from "./DesktopStartupRecovery.ts";++const updateState = (patch: Partial<DesktopUpdateState>): DesktopUpdateState => ({+ ...createInitialDesktopUpdateState(+ "0.1.3",+ { hostArch: "arm64", appArch: "arm64", runningUnderArm64Translation: false },+ "latest",+ ),+ enabled: true,+ ...patch,+});++describe("resolveStartupRecoveryOffer", () => {+ it("offers a newer version before going back", () => {+ expect(+ resolveStartupRecoveryOffer(+ updateState({ status: "available", availableVersion: "0.1.4" }),+ "0.1.2",+ ),+ ).toEqual({ _tag: "Update", version: "0.1.4" });+ });++ it("offers a retained download after a later check fails", () => {+ expect(+ resolveStartupRecoveryOffer(+ updateState({ status: "error", errorContext: "check", downloadedVersion: "0.1.4" }),+ null,+ ),+ ).toEqual({ _tag: "Update", version: "0.1.4" });+ });++ it("waits for the update check before offering to go back", () => {+ expect(resolveStartupRecoveryOffer(updateState({ status: "checking" }), "0.1.2")).toEqual({+ _tag: "Checking",+ });+ });++ it("offers the last version that started when no update exists", () => {+ expect(resolveStartupRecoveryOffer(updateState({ status: "up-to-date" }), "0.1.2")).toEqual({+ _tag: "Reinstall",+ version: "0.1.2",+ });+ });++ it("does not offer an update that already failed to apply here", () => {+ expect(+ resolveStartupRecoveryOffer(+ updateState({+ status: "downloaded",+ downloadedVersion: "0.1.4",+ notAppliedVersion: "0.1.4",+ }),+ "0.1.2",+ ),+ ).toEqual({ _tag: "Reinstall", version: "0.1.2" });+ });++ it("falls back to the releases page when this version never started", () => {+ expect(resolveStartupRecoveryOffer(updateState({ status: "disabled" }), "0.1.3")).toEqual({+ _tag: "Releases",+ });+ expect(resolveStartupRecoveryOffer(updateState({ status: "up-to-date" }), null)).toEqual({+ _tag: "Releases",+ });+ });+});diff --git a/apps/desktop/src/app/DesktopStartupRecovery.ts b/apps/desktop/src/app/DesktopStartupRecovery.tsnew file mode 100644index 00000000000..4d2dbcfb144--- /dev/null+++ b/apps/desktop/src/app/DesktopStartupRecovery.ts@@ -0,0 +1,338 @@+import type { DesktopUpdateState } from "@t3tools/contracts";+import * as Effect from "effect/Effect";+import * as FileSystem from "effect/FileSystem";+import * as Option from "effect/Option";+import * as Ref from "effect/Ref";+import type * as Scope from "effect/Scope";+import * as Stream from "effect/Stream";+import * as SubscriptionRef from "effect/SubscriptionRef";+import type * as Electron from "electron";++import * as ElectronApp from "../electron/ElectronApp.ts";+import * as ElectronShell from "../electron/ElectronShell.ts";+import * as ElectronTheme from "../electron/ElectronTheme.ts";+import * as ElectronWindow from "../electron/ElectronWindow.ts";+import * as DesktopUpdates from "../updates/DesktopUpdates.ts";+import type { BackendStartupFailure } from "../backend/DesktopBackendManager.ts";+import * as DesktopEnvironment from "./DesktopEnvironment.ts";+import * as DesktopObservability from "./DesktopObservability.ts";+import * as DesktopState from "./DesktopState.ts";++const RELEASES_URL = "https://github.com/pingdotgg/t3code/releases";+const LAST_STARTED_VERSION_FILE = "desktop-last-started-version";+// Buttons are plain links to this host; will-navigate cancels them and runs the action.+const ACTION_ORIGIN = "https://startup-recovery.invalid";++const { logInfo, logWarning } = DesktopObservability.makeComponentLogger(+ "desktop-startup-recovery",+);++export type StartupRecoveryOffer =+ | { readonly _tag: "Checking" }+ | { readonly _tag: "Update"; readonly version: string }+ | { readonly _tag: "Downloading"; readonly version: string; readonly percent: number | null }+ | { readonly _tag: "Reinstall"; readonly version: string }+ | { readonly _tag: "Releases" };++const STARTUP_RECOVERY_ACTIONS = ["update", "reinstall", "releases", "copy", "quit"] as const;+type StartupRecoveryAction = (typeof STARTUP_RECOVERY_ACTIONS)[number];++/** Prefer a newer build, then the last build that started on this machine, then the releases page. */+export function resolveStartupRecoveryOffer(+ update: DesktopUpdateState,+ lastStartedVersion: string | null,+): StartupRecoveryOffer {+ if (update.status === "downloading" && update.availableVersion !== null) {+ return {+ _tag: "Downloading",+ version: update.availableVersion,+ percent: update.downloadPercent,+ };+ }+ const updateVersion =+ update.downloadedVersion ?? (update.status === "available" ? update.availableVersion : null);+ // A version that already failed to apply here would loop through install and relaunch.+ if (updateVersion !== null && updateVersion !== update.notAppliedVersion) {+ return { _tag: "Update", version: updateVersion };+ }+ if (update.enabled && (update.status === "idle" || update.status === "checking")) {+ return { _tag: "Checking" };+ }+ if (lastStartedVersion !== null && lastStartedVersion !== update.currentVersion) {+ return { _tag: "Reinstall", version: lastStartedVersion };+ }+ return { _tag: "Releases" };+}++const escapeHtml = (value: string) =>+ value.replace(+ /[&<>"']/g,+ (char) =>+ ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[char] ?? char,+ );++const actionLink = (action: StartupRecoveryAction, label: string, primary = false) =>+ `<a class="button${primary ? " primary" : ""}" href="${ACTION_ORIGIN}/${action}">${escapeHtml(label)}</a>`;++function describeOffer(offer: StartupRecoveryOffer): { text: string; action: string } {+ switch (offer._tag) {+ case "Checking":+ return { text: "Checking for a newer version…", action: "" };+ case "Update":+ return {+ text: `Version ${offer.version} is available. It can contain a fix.`,+ action: actionLink("update", `Update to ${offer.version}`, true),+ };+ case "Downloading":+ return {+ text: `Downloading ${offer.version}${offer.percent === null ? "" : ` (${Math.floor(offer.percent / 10) * 10}%)`}. T3 Code restarts when the download is done.`,+ action: "",+ };+ case "Reinstall":+ return {+ text: `Version ${offer.version} started correctly on this computer. Download it and install it to go back.`,+ action: actionLink("reinstall", `Download ${offer.version}`, true),+ };+ case "Releases":+ return {+ text: "Get a different version from the releases page.",+ action: actionLink("releases", "Open releases", true),+ };+ }+}++function buildStartupRecoveryHtml(input: {+ readonly appVersion: string;+ readonly failure: BackendStartupFailure;+ readonly offer: StartupRecoveryOffer;+ readonly logDir: string;+}): string {+ const offer = describeOffer(input.offer);+ const output = input.failure.output.trim();+ 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>+:root{color-scheme:light dark;--bg:#fff;--fg:#111;--muted:#666;--line:#ddd;--code:#f4f4f4}+@media (prefers-color-scheme:dark){:root{--bg:#000;--fg:#fff;--muted:#999;--line:#333;--code:#111}}+html,body{margin:0;height:100%;background:var(--bg);color:var(--fg)}+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}+h1{font-size:18px;margin:0}p{margin:0}.muted{color:var(--muted)}+.actions{display:flex;gap:8px;flex-wrap:wrap}+.button{color:var(--fg);text-decoration:none;border:1px solid var(--line);border-radius:6px;padding:6px 12px}+.button.primary{background:var(--fg);color:var(--bg);border-color:var(--fg)}+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}+</style></head><body>+<h1>T3 Code could not start</h1>+<p>${escapeHtml(input.failure.reason)}</p>+<p>${escapeHtml(offer.text)}</p>+<div class="actions">${offer.action}${actionLink("copy", "Copy details")}${actionLink("quit", "Quit")}</div>+<pre>${escapeHtml(output.length > 0 ? output : "The server wrote no output.")}</pre>+<p class="muted">Version ${escapeHtml(input.appVersion)}. T3 Code tries again in the background. Logs: ${escapeHtml(input.logDir)}</p>+</body></html>`;+}++/** Shows a self-contained error window while the primary backend fails to start, so a broken release still opens. */+export const listen: Effect.Effect<+ void,+ never,+ | DesktopState.DesktopState+ | DesktopUpdates.DesktopUpdates+ | DesktopEnvironment.DesktopEnvironment+ | ElectronApp.ElectronApp+ | ElectronShell.ElectronShell+ | ElectronTheme.ElectronTheme+ | ElectronWindow.ElectronWindow+ | FileSystem.FileSystem+ | Scope.Scope+> = Effect.gen(function* () {+ const { primaryBackendStartup, quitting } = yield* DesktopState.DesktopState;+ const updates = yield* DesktopUpdates.DesktopUpdates;+ const environment = yield* DesktopEnvironment.DesktopEnvironment;+ const electronApp = yield* ElectronApp.ElectronApp;+ const electronShell = yield* ElectronShell.ElectronShell;+ const electronTheme = yield* ElectronTheme.ElectronTheme;+ const electronWindow = yield* ElectronWindow.ElectronWindow;+ const fileSystem = yield* FileSystem.FileSystem;+ const runFork = Effect.runForkWith(yield* Effect.context<never>());++ const lastStartedVersionPath = environment.path.join(+ environment.stateDir,+ LAST_STARTED_VERSION_FILE,+ );+ const lastStartedVersion = yield* fileSystem.readFileString(lastStartedVersionPath).pipe(+ Effect.map((text) => text.trim() || null),+ Effect.orElseSucceed(() => null),+ );++ const windowRef = yield* Ref.make(Option.none<Electron.BrowserWindow>());+ // The failure that opened the window; later restarts do not reload its details.+ const failureRef = yield* Ref.make(Option.none<BackendStartupFailure>());+ const renderedHtmlRef = yield* Ref.make("");+ const checkedRef = yield* Ref.make(false);+ const { latest, changes: updateChanges } = yield* updates.subscribe;+ const updateStateRef = yield* Ref.make(latest);++ const offer = Ref.get(updateStateRef).pipe(+ Effect.map((state) => resolveStartupRecoveryOffer(state, lastStartedVersion)),+ );++ const render = Effect.gen(function* () {+ const window = yield* Ref.get(windowRef);+ const failure = yield* Ref.get(failureRef);+ if (Option.isNone(window) || Option.isNone(failure) || window.value.isDestroyed()) return;+ const html = buildStartupRecoveryHtml({+ appVersion: environment.appVersion,+ failure: failure.value,+ offer: yield* offer,+ logDir: environment.logDir,+ });+ if ((yield* Ref.getAndSet(renderedHtmlRef, html)) === html) return;+ void window.value.loadURL(`data:text/html;charset=utf-8,${encodeURIComponent(html)}`);+ });++ const runAction = Effect.fn("desktop.startupRecovery.runAction")(function* (+ action: StartupRecoveryAction,+ ) {+ yield* logInfo("startup recovery action", { action });+ const current = yield* offer;+ switch (action) {+ case "update": {+ if (current._tag !== "Update") return;+ const state = yield* updates.getState;+ if (state.downloadedVersion === null) {+ const download = yield* updates.download;+ if (!download.completed) return;+ }+ // Waits for a running background check; plain install would refuse.+ yield* updates.installPrepared(current.version);+ return;+ }+ case "reinstall":+ if (current._tag === "Reinstall") {+ yield* electronShell.openExternal(`${RELEASES_URL}/tag/v${current.version}`);+ }+ return;+ case "releases":+ yield* electronShell.openExternal(RELEASES_URL);+ return;+ case "copy": {+ const failure = yield* Ref.get(failureRef);+ if (Option.isNone(failure)) return;+ yield* electronShell.copyText(+ `T3 Code ${environment.appVersion} (${environment.platform} ${environment.processArch}) could not start.\n${failure.value.reason}\n\n${failure.value.output}`,+ );+ return;+ }+ case "quit":+ yield* electronApp.quit;+ return;+ }+ });++ const show = Effect.fn("desktop.startupRecovery.show")(+ function* () {+ if (yield* Ref.get(quitting)) return;+ // A backend that crashes after the app opened is reported by the app itself.+ if (Option.isSome(yield* electronWindow.main)) return;+ const existing = yield* Ref.get(windowRef);+ if (Option.isSome(existing) && !existing.value.isDestroyed()) {+ yield* electronWindow.reveal(existing.value);+ return;+ }+ const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;+ const window = yield* electronWindow.create(+ {+ width: 640,+ height: 480,+ minWidth: 420,+ minHeight: 320,+ show: false,+ title: "T3 Code could not start",+ autoHideMenuBar: true,+ backgroundColor: shouldUseDarkColors ? "#000000" : "#ffffff",+ webPreferences: {+ contextIsolation: true,+ nodeIntegration: false,+ sandbox: true,+ javascript: false,+ },+ },+ { auxiliary: true },+ );+ window.webContents.setWindowOpenHandler(() => ({ action: "deny" }));+ window.webContents.on("will-navigate", (event, url) => {+ event.preventDefault();+ const action = STARTUP_RECOVERY_ACTIONS.find((name) => url === `${ACTION_ORIGIN}/${name}`);+ if (action !== undefined) runFork(runAction(action));+ });+ window.once("ready-to-show", () => {+ if (!window.isDestroyed()) window.show();+ });+ window.once("closed", () => {+ runFork(+ Ref.set(windowRef, Option.none()).pipe(Effect.andThen(Ref.set(renderedHtmlRef, ""))),+ );+ });+ yield* Ref.set(windowRef, Option.some(window));+ yield* render;+ yield* logInfo("startup recovery window shown");+ },+ Effect.catch((error) =>+ logWarning("could not show startup recovery", { errorTag: error._tag }),+ ),+ );++ const close = Effect.gen(function* () {+ const window = yield* Ref.getAndSet(windowRef, Option.none());+ if (Option.isSome(window) && !window.value.isDestroyed()) window.value.close();+ });++ const rememberStartedVersion = Effect.gen(function* () {+ if (lastStartedVersion === environment.appVersion) return;+ yield* fileSystem.writeFileString(lastStartedVersionPath, environment.appVersion);+ }).pipe(+ Effect.catch((error) =>+ logWarning("could not record the started version", { errorTag: error._tag }),+ ),+ );++ yield* updateChanges.pipe(+ Stream.runForEach((state) => Ref.set(updateStateRef, state).pipe(Effect.andThen(render))),+ Effect.forkScoped,+ );++ yield* SubscriptionRef.changes(primaryBackendStartup).pipe(+ Stream.runForEach(+ Effect.fn("desktop.startupRecovery.onStartupChange")(function* (startup) {+ if (startup._tag === "Ready") {+ yield* Ref.set(failureRef, Option.none());+ yield* close;+ yield* rememberStartedVersion;+ return;+ }+ if (startup._tag !== "Failing") return;+ if (Option.isSome(yield* Ref.get(failureRef))) return;+ yield* Ref.set(failureRef, Option.some({ reason: startup.reason, output: startup.output }));+ // The backend manager already logs each failure's reason.+ yield* logWarning("primary backend failing to start");+ yield* show();+ if (!(yield* Ref.getAndSet(checkedRef, true))) {+ yield* updates.check("startup-recovery").pipe(Effect.forkScoped);+ }+ }),+ ),+ Effect.catchCause((cause) =>+ Effect.logWarning("startup recovery stopped", cause).pipe(+ Effect.annotateLogs({ component: "desktop-startup-recovery" }),+ ),+ ),+ Effect.forkScoped,+ );++ // macOS keeps running with no windows; the Dock icon must bring the error back.+ yield* electronApp.on("activate", () => {+ runFork(+ Ref.get(failureRef).pipe(+ Effect.flatMap((failure) => (Option.isSome(failure) ? show() : Effect.void)),+ ),+ );+ });+});diff --git a/apps/desktop/src/app/DesktopState.ts b/apps/desktop/src/app/DesktopState.tsindex cd2abe91065..3452fd13c08 100644--- a/apps/desktop/src/app/DesktopState.ts+++ b/apps/desktop/src/app/DesktopState.ts@@ -2,18 +2,29 @@ import * as Context from "effect/Context";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";import * as Ref from "effect/Ref";+import * as SubscriptionRef from "effect/SubscriptionRef";++import type { BackendStartupFailure } from "../backend/DesktopBackendManager.ts";++/** Startup health of the primary local backend, read by the startup recovery window. */+export type PrimaryBackendStartup =+ | { readonly _tag: "Starting" }+ | { readonly _tag: "Ready" }+ | ({ readonly _tag: "Failing" } & BackendStartupFailure);export class DesktopState extends Context.Service<DesktopState,{readonly backendReady: Ref.Ref<boolean>;readonly quitting: Ref.Ref<boolean>;+ readonly primaryBackendStartup: SubscriptionRef.SubscriptionRef<PrimaryBackendStartup>;}>()("@t3tools/desktop/app/DesktopState") {}const make = Effect.all({backendReady: Ref.make(false),quitting: Ref.make(false),+ primaryBackendStartup: SubscriptionRef.make<PrimaryBackendStartup>({ _tag: "Starting" }),});export const layer = Layer.effect(DesktopState, make);diff --git a/apps/desktop/src/backend/DesktopBackendManager.test.ts b/apps/desktop/src/backend/DesktopBackendManager.test.tsindex 7b15346a754..54fb312ec30 100644--- a/apps/desktop/src/backend/DesktopBackendManager.test.ts+++ b/apps/desktop/src/backend/DesktopBackendManager.test.ts@@ -123,6 +123,9 @@ interface MakeInstanceInput {readonly onReady?: Effect.Effect<void>;readonly onShutdown?: Effect.Effect<void>;readonly onStateDirOwned?: Effect.Effect<void>;+ readonly onStartupFailure?: (+ failure: DesktopBackendManager.BackendStartupFailure,+ ) => Effect.Effect<void>;readonly onPreflightFailed?: (failure: DesktopBackendManager.PreflightFailure,) => Effect.Effect<boolean>;@@ -182,6 +185,7 @@ function makeTestInstance(input: MakeInstanceInput) {...(input.onShutdown ? { onShutdown: () => input.onShutdown! } : {}),...(input.onStateDirOwned ? { onStateDirOwned: () => input.onStateDirOwned! } : {}),...(input.onPreflightFailed ? { onPreflightFailed: input.onPreflightFailed } : {}),+ ...(input.onStartupFailure ? { onStartupFailure: input.onStartupFailure } : {}),});return instance.pipe(Effect.provide(layerServices));@@ -575,4 +579,56 @@ describe("DesktopBackendManager", () => {}).pipe(Effect.provide(TestClock.layer())),),);++ it.effect("reports a crash loop with the server output on the third restart", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const message = "Error: Cannot find module 'zod/v4' in /Users/René";+ let exitCount = 0;+ const firstExit = yield* Deferred.make<void>();+ const reports = yield* Queue.unbounded<{+ readonly exitCount: number;+ readonly failure: DesktopBackendManager.BackendStartupFailure;+ }>();+ const instance = yield* makeTestInstance({+ spawnerLayer: Layer.succeed(+ ChildProcessSpawner.ChildProcessSpawner,+ ChildProcessSpawner.make(() =>+ Effect.succeed(+ makeProcess({+ // "é" split across chunks must not decode as U+FFFD, and the 4,000-char cut+ // lands inside the emoji's surrogate pair.+ stderr: Stream.make(+ new TextEncoder().encode(+ `😀${"x".repeat(3_999 - message.length)}${message.slice(0, -1)}`,+ ),+ new Uint8Array([0xc3]),+ new Uint8Array([0xa9]),+ ),+ exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),+ }),+ ),+ ),+ ),+ httpClientLayer: layerHttpClient(() => Effect.never),+ backendOutputLog: {+ persistFailure: () => {+ exitCount += 1;+ return Deferred.succeed(firstExit, undefined).pipe(Effect.asVoid);+ },+ },+ onStartupFailure: (failure) =>+ Queue.offer(reports, { exitCount, failure }).pipe(Effect.asVoid),+ });+ yield* instance.start;+ yield* Deferred.await(firstExit);+ yield* TestClock.adjust(Duration.minutes(1));+ const { exitCount: exitsWhenReported, failure } = yield* Queue.take(reports);+ assert.equal(exitsWhenReported, 3);+ assert.equal(failure.reason, "The server could not start (code=1).");+ assert.isTrue(failure.output.endsWith(message));+ assert.isTrue(failure.output.isWellFormed());+ }).pipe(Effect.provide(TestClock.layer())),+ ),+ );});diff --git a/apps/desktop/src/backend/DesktopBackendManager.ts b/apps/desktop/src/backend/DesktopBackendManager.tsindex 8b5e8045ed3..cbc0516509d 100644--- a/apps/desktop/src/backend/DesktopBackendManager.ts+++ b/apps/desktop/src/backend/DesktopBackendManager.ts@@ -41,6 +41,9 @@ const DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT = Duration.seconds(1);const DEFAULT_BACKEND_TERMINATE_GRACE = Duration.seconds(5);const DEFAULT_BACKEND_OUTPUT_DRAIN_TIMEOUT = Duration.seconds(5);const BACKEND_READINESS_PATH = "/.well-known/t3/environment";+// Three restarts without readiness is about 2 s of backoff: past a blip, early enough to help.+const STARTUP_FAILURE_RESTART_ATTEMPTS = 3;+const STARTUP_FAILURE_OUTPUT_CHARS = 4_000;const { logWarning: logBackendProcessWarning } =DesktopObservability.makeComponentLogger("desktop-backend-process");@@ -217,6 +220,12 @@ export const PRIMARY_INSTANCE_ID: BackendInstanceId = BackendInstanceId(PRIMARY_LOCAL_ENVIRONMENT_ID,);+export interface BackendStartupFailure {+ readonly reason: string;+ /** Tail of the last run's stdout and stderr. */+ readonly output: string;+}+export interface DesktopBackendInstance {readonly id: BackendInstanceId;readonly label: Effect.Effect<string>;@@ -236,6 +245,8 @@ export interface BackendInstanceSpec {readonly onShutdown?: () => Effect.Effect<void>;readonly onPreflightFailed?: (failure: PreflightFailure) => Effect.Effect<boolean>;readonly onStateDirOwned?: () => Effect.Effect<void>;+ /** Fires on each repeated crash or readiness timeout until the backend becomes ready. */+ readonly onStartupFailure?: (failure: BackendStartupFailure) => Effect.Effect<void>;}interface ActiveBackendRun {@@ -619,6 +630,14 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (const httpClient = yield* HttpClient.HttpClient;const state = yield* Ref.make(initialState);const mutex = yield* Semaphore.make(1);+ const outputTail = yield* Ref.make("");+ // One streaming decoder per stream keeps UTF-8 characters split across chunks intact.+ const makeOutputDecoders = () => ({ stdout: new TextDecoder(), stderr: new TextDecoder() });+ let outputDecoders = makeOutputDecoders();+ const reportStartupFailure = (reason: string) =>+ Ref.get(outputTail).pipe(+ Effect.flatMap((output) => spec.onStartupFailure?.({ reason, output }) ?? Effect.void),+ );const { logWarning: logInstanceWarning, logError: logInstanceError } =DesktopObservability.makeComponentLogger(`desktop-backend-instance:${spec.id}`);@@ -875,6 +894,8 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (...run,pid: Option.some(pid),}));+ yield* Ref.set(outputTail, "");+ outputDecoders = makeOutputDecoders();yield* backendOutputLog.beginSession({details: `pid=${pid} port=${config.value.bootstrap.port} cwd=${config.value.cwd}`,});@@ -923,9 +944,16 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* (yield* backendOutputLog.persistFailureSnapshot({details: error.message,});+ yield* reportStartupFailure("The server started but did not become ready in time.");},),- onOutput: (streamName, chunk) => backendOutputLog.writeOutputChunk(streamName, chunk),+ onOutput: (streamName, chunk) =>+ Ref.update(outputTail, (tail) =>+ // A cut through a surrogate pair would make encodeURIComponent throw when rendering.+ (tail + outputDecoders[streamName].decode(chunk, { stream: true }))+ .slice(-STARTUP_FAILURE_OUTPUT_CHARS)+ .toWellFormed(),+ ).pipe(Effect.andThen(backendOutputLog.writeOutputChunk(streamName, chunk))),}).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),Effect.provideService(HttpClient.HttpClient, httpClient),@@ -951,26 +979,29 @@ export const makeBackendInstance = Effect.fn("makeBackendInstance")(function* () {const scheduled = yield* Ref.modify(state, (latest) => {if (!latest.desiredRunning || Option.isSome(latest.restartFiber)) {- return [Option.none<Duration.Duration>(), latest] as const;+ return [Option.none<{ delay: Duration.Duration; attempt: number }>(), latest] as const;}- const delay = calculateRestartDelay(latest.restartAttempt);+ const attempt = latest.restartAttempt + 1;return [- Option.some(delay),- {- ...latest,- restartAttempt: latest.restartAttempt + 1,- },+ Option.some({ delay: calculateRestartDelay(latest.restartAttempt), attempt }),+ { ...latest, restartAttempt: attempt },] as const;});yield* Option.match(scheduled, {onNone: () => Effect.void,- onSome: Effect.fn("desktop.backendInstance.scheduleRestartFiber")(function* (delay) {+ onSome: Effect.fn("desktop.backendInstance.scheduleRestartFiber")(function* ({+ delay,+ attempt,+ }) {yield* logInstanceError("backend exited unexpectedly; restart scheduled", {reason,delayMs: Duration.toMillis(delay),});+ if (attempt >= STARTUP_FAILURE_RESTART_ATTEMPTS) {+ yield* reportStartupFailure(`The server could not start (${reason}).`);+ }const restartFiber = yield* Effect.forkIn(Effect.sleep(delay).pipe(Effect.andThen(diff --git a/apps/desktop/src/backend/DesktopBackendPool.test.ts b/apps/desktop/src/backend/DesktopBackendPool.test.tsindex 0583e8df217..2b2dd841ab5 100644--- a/apps/desktop/src/backend/DesktopBackendPool.test.ts+++ b/apps/desktop/src/backend/DesktopBackendPool.test.ts@@ -9,6 +9,7 @@ import { HttpClient } from "effect/http";import { ChildProcessSpawner } from "effect/process";import * as DesktopObservability from "../app/DesktopObservability.ts";+import * as DesktopState from "../app/DesktopState.ts";import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";import * as DesktopBrowserHost from "../preview/DesktopBrowserHost.ts";@@ -62,6 +63,7 @@ function layerPool(labelRef: Ref.Ref<string>): Layer.Layer<DesktopBackendPool.DecurrentBootstrapToken: Effect.die("unexpected bootstrap token read"),} satisfies DesktopBackendConfiguration.DesktopBackendConfiguration["Service"]),DesktopAppSettings.layerTest(),+ DesktopState.layer,DesktopWslEnvironment.layerTest(),ElectronDialog.layer,ElectronApp.layer,diff --git a/apps/desktop/src/backend/DesktopBackendPool.ts b/apps/desktop/src/backend/DesktopBackendPool.tsindex 094e1d211be..77a4aa998d7 100644--- a/apps/desktop/src/backend/DesktopBackendPool.ts+++ b/apps/desktop/src/backend/DesktopBackendPool.ts@@ -6,6 +6,7 @@ import * as Layer from "effect/Layer";import * as Option from "effect/Option";import * as Schema from "effect/Schema";import * as Scope from "effect/Scope";+import * as SubscriptionRef from "effect/SubscriptionRef";import * as SynchronizedRef from "effect/SynchronizedRef";import * as FileSystem from "effect/FileSystem";@@ -15,6 +16,7 @@ import { ChildProcessSpawner } from "effect/process";import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";import * as DesktopBackendManager from "./DesktopBackendManager.ts";import * as DesktopObservability from "../app/DesktopObservability.ts";+import * as DesktopState from "../app/DesktopState.ts";import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";import * as DesktopBrowserHost from "../preview/DesktopBrowserHost.ts";@@ -106,6 +108,7 @@ export const layer = Layer.effect(const electronDialog = yield* ElectronDialog.ElectronDialog;const electronApp = yield* ElectronApp.ElectronApp;const appSettings = yield* DesktopAppSettings.DesktopAppSettings;+ const { primaryBackendStartup } = yield* DesktopState.DesktopState;// Parent instance scopes to the pool so shutdown runs stop finalizers before the OS kills backends.const layerScope = yield* Scope.Scope;const factoryContext = yield* Effect.context<BackendInstanceFactoryRequirements>();@@ -158,12 +161,16 @@ export const layer = Layer.effect(// Absorb window errors so readiness can reset restartAttempt.onReady: (httpBaseUrl) =>desktopWindow.handleBackendReady(httpBaseUrl).pipe(+ // Only once the main window exists, so the recovery window never closes into nothing.+ Effect.andThen(SubscriptionRef.set(primaryBackendStartup, { _tag: "Ready" })),Effect.catch((error) =>logBackendPoolWarning("failed to open main window after backend readiness", {error: error.message,}),),),+ onStartupFailure: (failure) =>+ SubscriptionRef.set(primaryBackendStartup, { _tag: "Failing", ...failure }),onShutdown: () => desktopWindow.handleBackendNotReady,onPreflightFailed: handlePrimaryPreflightFailure,onStateDirOwned: () =>diff --git a/apps/desktop/src/electron/ElectronWindow.test.ts b/apps/desktop/src/electron/ElectronWindow.test.tsindex 4f17ca7e330..478d4901290 100644--- a/apps/desktop/src/electron/ElectronWindow.test.ts+++ b/apps/desktop/src/electron/ElectronWindow.test.ts@@ -162,4 +162,20 @@ describe("ElectronWindow", () => {assert.equal(vi.mocked(laterWindow.destroy).mock.calls.length, 1);}).pipe(Effect.provide(layerTest)),);++ it.effect("never falls back to an auxiliary window as the main window", () =>+ Effect.gen(function* () {+ const electronWindow = yield* ElectronWindow.ElectronWindow;+ const auxiliary = yield* electronWindow.create({}, { auxiliary: true });+ const ordinary = { isDestroyed: () => false } as unknown as Electron.BrowserWindow;+ Object.assign(auxiliary, { isDestroyed: () => false });++ getAllWindowsMock.mockReturnValue([auxiliary]);+ assert.isTrue((yield* electronWindow.currentMainOrFirst)._tag === "None");++ getAllWindowsMock.mockReturnValue([auxiliary, ordinary]);+ const current = yield* electronWindow.currentMainOrFirst;+ assert.isTrue(current._tag === "Some" && current.value === ordinary);+ }).pipe(Effect.provide(layerTest)),+ );});diff --git a/apps/desktop/src/electron/ElectronWindow.ts b/apps/desktop/src/electron/ElectronWindow.tsindex 35303ed935a..985f9c00775 100644--- a/apps/desktop/src/electron/ElectronWindow.ts+++ b/apps/desktop/src/electron/ElectronWindow.ts@@ -109,8 +109,10 @@ export class ElectronWindowOperationError extends Schema.TaggedError<ElectronWinexport class ElectronWindow extends Context.Service<ElectronWindow,{+ /** Auxiliary windows are never returned as the main-or-first fallback. */readonly create: (options: Electron.BrowserWindowConstructorOptions,+ behavior?: { readonly auxiliary?: boolean },) => Effect.Effect<Electron.BrowserWindow, ElectronWindowCreateError>;readonly main: Effect.Effect<Option.Option<Electron.BrowserWindow>>;readonly currentMainOrFirst: Effect.Effect<Option.Option<Electron.BrowserWindow>>;@@ -141,6 +143,7 @@ export const make = Effect.gen(function* () {const captureRevealWindows = new Set<number>();yield* Effect.addFinalizer(() => Effect.sync(() => windowsForegroundFocus?.close()));const mainWindowRef = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());+ const auxiliaryWindows = new WeakSet<Electron.BrowserWindow>();const listWindows = Effect.try({try: () => Electron.BrowserWindow.getAllWindows(),@@ -181,7 +184,9 @@ export const make = Effect.gen(function* () {return main;}- const first = Option.fromNullishOr((yield* listWindows)[0] ?? null);+ const first = Option.fromNullishOr(+ (yield* listWindows).find((window) => !auxiliaryWindows.has(window)) ?? null,+ );if (Option.isNone(first) || (yield* isWindowDestroyed(first.value))) {return Option.none<Electron.BrowserWindow>();}@@ -207,7 +212,7 @@ export const make = Effect.gen(function* () {});return ElectronWindow.of({- create: Effect.fn("ElectronWindow.create")(function (options) {+ create: Effect.fn("ElectronWindow.create")(function (options, behavior) {const webPreferences = options.webPreferences;const diagnosticOptions = {title: options.title ?? null,@@ -232,7 +237,11 @@ export const make = Effect.gen(function* () {} satisfies typeof ElectronWindowCreateOptions.Type;return Effect.try({- try: () => new Electron.BrowserWindow(options),+ try: () => {+ const window = new Electron.BrowserWindow(options);+ if (behavior?.auxiliary === true) auxiliaryWindows.add(window);+ return window;+ },catch: (cause) => new ElectronWindowCreateError({ options: diagnosticOptions, cause }),});}),diff --git a/docs/user/updating.md b/docs/user/updating.mdindex e00329023af..ad5d93b5759 100644--- a/docs/user/updating.md+++ b/docs/user/updating.md@@ -111,6 +111,14 @@ Only one server can use a T3 home directory at a time. If startup reports thatanother server owns it, stop that server before retrying, or use a separate homedirectory and pair with the running server.+## If the desktop app does not start++If the desktop app's server keeps failing at startup, T3 Code shows a "T3 Code+could not start" window instead of the app. If a newer version is available,+choose **Update** to install it. If not, the window links to the last version+that started on your computer. Download and install it to go back. Use **Copy+details** to include the error in a bug report.+## Update providers**Settings → Providers** shows provider updates for the selected environment.