Open History to see the last commit
1import type { DesktopUpdateState } from "@t3tools/contracts";
2import * as Effect from "effect/Effect";
3import * as FileSystem from "effect/FileSystem";
4import * as Option from "effect/Option";
5import * as Ref from "effect/Ref";
6import type * as Scope from "effect/Scope";
7import * as Stream from "effect/Stream";
8import * as SubscriptionRef from "effect/SubscriptionRef";
9import type * as Electron from "electron";
10
11import * as ElectronApp from "../electron/ElectronApp.ts";
12import * as ElectronShell from "../electron/ElectronShell.ts";
13import * as ElectronTheme from "../electron/ElectronTheme.ts";
14import * as ElectronWindow from "../electron/ElectronWindow.ts";
15import * as DesktopUpdates from "../updates/DesktopUpdates.ts";
16import type { BackendStartupFailure } from "../backend/DesktopBackendManager.ts";
17import * as DesktopEnvironment from "./DesktopEnvironment.ts";
18import * as DesktopObservability from "./DesktopObservability.ts";
19import * as DesktopState from "./DesktopState.ts";
20
21const RELEASES_URL = "https://github.com/pingdotgg/t3code/releases";
22const LAST_STARTED_VERSION_FILE = "desktop-last-started-version";
23// Buttons are plain links to this host; will-navigate cancels them and runs the action.
24const ACTION_ORIGIN = "https://startup-recovery.invalid";
25
26const { logInfo, logWarning } = DesktopObservability.makeComponentLogger(
27 "desktop-startup-recovery",
28);
29
30export 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
37const STARTUP_RECOVERY_ACTIONS = ["update", "reinstall", "releases", "copy", "quit"] as const;
38type 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. */
41export 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
67const escapeHtml = (value: string) =>
68 value.replace(
69 /[&<>"']/g,
70 (char) =>
71 ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[char] ?? char,
72 );
73
74const actionLink = (action: StartupRecoveryAction, label: string, primary = false) =>
75 `<a class="button${primary ? " primary" : ""}" href="${ACTION_ORIGIN}/${action}">${escapeHtml(label)}</a>`;
76
77function 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
104function 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}}
115html,body{margin:0;height:100%;background:var(--bg);color:var(--fg)}
116body{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}
117h1{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)}
121pre{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. */
133export 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 let backendHasStarted = false;
171 const { latest, changes: updateChanges } = yield* updates.subscribe;
172 const updateStateRef = yield* Ref.make(latest);
173
174 const offer = Ref.get(updateStateRef).pipe(
175 Effect.map((state) => resolveStartupRecoveryOffer(state, lastStartedVersion)),
176 );
177
178 const render = Effect.gen(function* () {
179 const window = yield* Ref.get(windowRef);
180 const failure = yield* Ref.get(failureRef);
181 if (Option.isNone(window) || Option.isNone(failure) || window.value.isDestroyed()) return;
182 const html = buildStartupRecoveryHtml({
183 appVersion: environment.appVersion,
184 failure: failure.value,
185 offer: yield* offer,
186 logDir: environment.logDir,
187 });
188 if ((yield* Ref.getAndSet(renderedHtmlRef, html)) === html) return;
189 void window.value.loadURL(`data:text/html;charset=utf-8,${encodeURIComponent(html)}`);
190 });
191
192 const runAction = Effect.fn("desktop.startupRecovery.runAction")(function* (
193 action: StartupRecoveryAction,
194 ) {
195 yield* logInfo("startup recovery action", { action });
196 const current = yield* offer;
197 switch (action) {
198 case "update": {
199 if (current._tag !== "Update") return;
200 const state = yield* updates.getState;
201 if (state.downloadedVersion === null) {
202 const download = yield* updates.download;
203 if (!download.completed) return;
204 }
205 // Waits for a running background check; plain install would refuse.
206 yield* updates.installPrepared(current.version);
207 return;
208 }
209 case "reinstall":
210 if (current._tag === "Reinstall") {
211 yield* electronShell.openExternal(`${RELEASES_URL}/tag/v${current.version}`);
212 }
213 return;
214 case "releases":
215 yield* electronShell.openExternal(RELEASES_URL);
216 return;
217 case "copy": {
218 const failure = yield* Ref.get(failureRef);
219 if (Option.isNone(failure)) return;
220 yield* electronShell.copyText(
221 `T3 Code ${environment.appVersion} (${environment.platform} ${environment.processArch}) could not start.\n${failure.value.reason}\n\n${failure.value.output}`,
222 );
223 return;
224 }
225 case "quit":
226 yield* electronApp.quit;
227 return;
228 }
229 });
230
231 const show = Effect.fn("desktop.startupRecovery.show")(
232 function* () {
233 if (yield* Ref.get(quitting)) 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);
246 return;
247 }
248 const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
249 const window = yield* electronWindow.create(
250 {
251 width: 640,
252 height: 480,
253 minWidth: 420,
254 minHeight: 320,
255 show: false,
256 title: "T3 Code could not start",
257 autoHideMenuBar: true,
258 backgroundColor: shouldUseDarkColors ? "#000000" : "#ffffff",
259 webPreferences: {
260 contextIsolation: true,
261 nodeIntegration: false,
262 sandbox: true,
263 javascript: false,
264 },
265 },
266 { auxiliary: true },
267 );
268 window.webContents.setWindowOpenHandler(() => ({ action: "deny" }));
269 window.webContents.on("will-navigate", (event, url) => {
270 event.preventDefault();
271 const action = STARTUP_RECOVERY_ACTIONS.find((name) => url === `${ACTION_ORIGIN}/${name}`);
272 if (action !== undefined) runFork(runAction(action));
273 });
274 window.once("ready-to-show", () => {
275 if (!window.isDestroyed()) window.show();
276 });
277 window.once("closed", () => {
278 runFork(
279 Ref.set(windowRef, Option.none()).pipe(Effect.andThen(Ref.set(renderedHtmlRef, ""))),
280 );
281 });
282 yield* Ref.set(windowRef, Option.some(window));
283 yield* render;
284 yield* logInfo("startup recovery window shown");
285 },
286 Effect.catch((error) =>
287 logWarning("could not show startup recovery", { errorTag: error._tag }),
288 ),
289 );
290
291 const close = Effect.gen(function* () {
292 const window = yield* Ref.getAndSet(windowRef, Option.none());
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);
312 }).pipe(
313 Effect.catch((error) =>
314 logWarning("could not record the started version", { errorTag: error._tag }),
315 ),
316 );
317
318 yield* updateChanges.pipe(
319 Stream.runForEach((state) => Ref.set(updateStateRef, state).pipe(Effect.andThen(render))),
320 Effect.forkScoped,
321 );
322
323 yield* SubscriptionRef.changes(primaryBackendStartup).pipe(
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());
329 yield* closeWhenMainReady;
330 yield* rememberStartedVersion;
331 return;
332 }
333 if (startup._tag !== "Failing") return;
334 if (Option.isSome(yield* Ref.get(failureRef))) return;
335 yield* Ref.set(failureRef, Option.some({ reason: startup.reason, output: startup.output }));
336 // The backend manager already logs each failure's reason.
337 yield* logWarning("primary backend failing to start");
338 yield* show();
339 if (!(yield* Ref.getAndSet(checkedRef, true))) {
340 yield* updates.check("startup-recovery").pipe(Effect.forkScoped);
341 }
342 }),
343 ),
344 Effect.catchCause((cause) =>
345 Effect.logWarning("startup recovery stopped", cause).pipe(
346 Effect.annotateLogs({ component: "desktop-startup-recovery" }),
347 ),
348 ),
349 Effect.forkScoped,
350 );
351
352 // macOS keeps running with no windows; the Dock icon must bring the error back.
353 yield* electronApp.on("activate", () => {
354 runFork(
355 Ref.get(failureRef).pipe(
356 Effect.flatMap((failure) => (Option.isSome(failure) ? show() : Effect.void)),
357 ),
358 );
359 });
360});