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";
10import { msg } from "gt-i18n";
11
12import * as ElectronApp from "../electron/ElectronApp.ts";
13import * as ElectronShell from "../electron/ElectronShell.ts";
14import * as ElectronTheme from "../electron/ElectronTheme.ts";
15import * as ElectronWindow from "../electron/ElectronWindow.ts";
16import { m } from "../i18n/messages.ts";
17import * as DesktopUpdates from "../updates/DesktopUpdates.ts";
18import type { BackendStartupFailure } from "../backend/DesktopBackendManager.ts";
19import * as DesktopEnvironment from "./DesktopEnvironment.ts";
20import * as DesktopObservability from "./DesktopObservability.ts";
21import * as DesktopState from "./DesktopState.ts";
22
23const RELEASES_URL = "https://github.com/pingdotgg/t3code/releases";
24const LAST_STARTED_VERSION_FILE = "desktop-last-started-version";
25// Buttons are plain links to this host; will-navigate cancels them and runs the action.
26const ACTION_ORIGIN = "https://startup-recovery.invalid";
27
28const { logInfo, logWarning } = DesktopObservability.makeComponentLogger(
29 "desktop-startup-recovery",
30);
31
32export type StartupRecoveryOffer =
33 | { readonly _tag: "Checking" }
34 | { readonly _tag: "Update"; readonly version: string }
35 | { readonly _tag: "Downloading"; readonly version: string; readonly percent: number | null }
36 | { readonly _tag: "Reinstall"; readonly version: string }
37 | { readonly _tag: "Releases" }
38 | { readonly _tag: "ManagedPolicy" };
39
40const STARTUP_RECOVERY_ACTIONS = ["update", "reinstall", "releases", "copy", "quit"] as const;
41type StartupRecoveryAction = (typeof STARTUP_RECOVERY_ACTIONS)[number];
42
43/** Prefer a newer build, then the last build that started on this machine, then the releases page. */
44export function resolveStartupRecoveryOffer(
45 update: DesktopUpdateState,
46 lastStartedVersion: string | null,
47 managedPolicy = false,
48): StartupRecoveryOffer {
49 if (update.status === "downloading" && update.availableVersion !== null) {
50 return {
51 _tag: "Downloading",
52 version: update.availableVersion,
53 percent: update.downloadPercent,
54 };
55 }
56 const updateVersion =
57 update.downloadedVersion ?? (update.status === "available" ? update.availableVersion : null);
58 // A version that already failed to apply here would loop through install and relaunch.
59 if (updateVersion !== null && updateVersion !== update.notAppliedVersion) {
60 return { _tag: "Update", version: updateVersion };
61 }
62 // A newer release can know a key this one refuses; an older one or the releases page cannot help.
63 if (managedPolicy) return { _tag: "ManagedPolicy" };
64 if (update.enabled && (update.status === "idle" || update.status === "checking")) {
65 return { _tag: "Checking" };
66 }
67 if (lastStartedVersion !== null && lastStartedVersion !== update.currentVersion) {
68 return { _tag: "Reinstall", version: lastStartedVersion };
69 }
70 return { _tag: "Releases" };
71}
72
73const escapeHtml = (value: string) =>
74 value.replace(
75 /[&<>"']/g,
76 (char) =>
77 ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[char] ?? char,
78 );
79
80const actionLink = (action: StartupRecoveryAction, label: string, primary = false) =>
81 `<a class="button${primary ? " primary" : ""}" href="${ACTION_ORIGIN}/${action}">${escapeHtml(label)}</a>`;
82
83function describeOffer(offer: StartupRecoveryOffer): { text: string; action: string } {
84 switch (offer._tag) {
85 case "Checking":
86 return { text: m(msg("Checking for a newer version…")), action: "" };
87 case "Update":
88 return {
89 text: m(msg`Version ${{ version: offer.version }} is available. It can contain a fix.`),
90 action: actionLink("update", m(msg`Update to ${{ version: offer.version }}`), true),
91 };
92 case "Downloading":
93 return {
94 text:
95 offer.percent === null
96 ? m(
97 msg`Downloading ${{ version: offer.version }}. T3 Code restarts when the download is done.`,
98 )
99 : m(
100 msg`Downloading ${{ version: offer.version }} (${{ percent: String(Math.floor(offer.percent / 10) * 10) }}%). T3 Code restarts when the download is done.`,
101 ),
102 action: "",
103 };
104 case "Reinstall":
105 return {
106 text: m(
107 msg`Version ${{ version: offer.version }} started correctly on this computer. Download it and install it to go back.`,
108 ),
109 action: actionLink("reinstall", m(msg`Download ${{ version: offer.version }}`), true),
110 };
111 case "Releases":
112 return {
113 text: m(msg("Get a different version from the releases page.")),
114 action: actionLink("releases", m(msg("Open releases")), true),
115 };
116 case "ManagedPolicy":
117 return {
118 text: m(
119 msg(
120 "Your organization's managed policy stopped T3 Code from starting. Send the details below to your IT administrator.",
121 ),
122 ),
123 action: "",
124 };
125 }
126}
127
128function buildStartupRecoveryHtml(input: {
129 readonly appVersion: string;
130 readonly failure: BackendStartupFailure;
131 readonly offer: StartupRecoveryOffer;
132 readonly logDir: string;
133}): string {
134 const offer = describeOffer(input.offer);
135 const output = input.failure.output.trim();
136 const title = escapeHtml(m(msg("T3 Code could not start")));
137 return `<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'"><title>${title}</title><style>
138:root{color-scheme:light dark;--bg:#fff;--fg:#111;--muted:#666;--line:#ddd;--code:#f4f4f4}
139@media (prefers-color-scheme:dark){:root{--bg:#000;--fg:#fff;--muted:#999;--line:#333;--code:#111}}
140html,body{margin:0;height:100%;background:var(--bg);color:var(--fg)}
141body{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}
142h1{font-size:18px;margin:0}p{margin:0}.muted{color:var(--muted)}
143.actions{display:flex;gap:8px;flex-wrap:wrap}
144.button{color:var(--fg);text-decoration:none;border:1px solid var(--line);border-radius:6px;padding:6px 12px}
145.button.primary{background:var(--fg);color:var(--bg);border-color:var(--fg)}
146pre{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}
147</style></head><body>
148<h1>${title}</h1>
149<p>${escapeHtml(input.failure.reason)}</p>
150<p>${escapeHtml(offer.text)}</p>
151<div class="actions">${offer.action}${actionLink("copy", m(msg("Copy details")))}${actionLink("quit", m(msg({ context: "button, quits the app" })`Quit`))}</div>
152<pre>${escapeHtml(output.length > 0 ? output : m(msg("The server wrote no output.")))}</pre>
153<p class="muted">${escapeHtml(m(msg`Version ${{ version: input.appVersion }}. T3 Code tries again in the background. Logs: ${{ logDir: input.logDir }}`))}</p>
154</body></html>`;
155}
156
157/** Shows a self-contained error window while the primary backend fails to start, so a broken release still opens. */
158export const listen: Effect.Effect<
159 void,
160 never,
161 | DesktopState.DesktopState
162 | DesktopUpdates.DesktopUpdates
163 | DesktopEnvironment.DesktopEnvironment
164 | ElectronApp.ElectronApp
165 | ElectronShell.ElectronShell
166 | ElectronTheme.ElectronTheme
167 | ElectronWindow.ElectronWindow
168 | FileSystem.FileSystem
169 | Scope.Scope
170> = Effect.gen(function* () {
171 const { primaryBackendStartup, quitting } = yield* DesktopState.DesktopState;
172 const updates = yield* DesktopUpdates.DesktopUpdates;
173 const environment = yield* DesktopEnvironment.DesktopEnvironment;
174 const electronApp = yield* ElectronApp.ElectronApp;
175 const electronShell = yield* ElectronShell.ElectronShell;
176 const electronTheme = yield* ElectronTheme.ElectronTheme;
177 const electronWindow = yield* ElectronWindow.ElectronWindow;
178 const fileSystem = yield* FileSystem.FileSystem;
179 const runFork = Effect.runForkWith(yield* Effect.context<never>());
180
181 const lastStartedVersionPath = environment.path.join(
182 environment.stateDir,
183 LAST_STARTED_VERSION_FILE,
184 );
185 const lastStartedVersion = yield* fileSystem.readFileString(lastStartedVersionPath).pipe(
186 Effect.map((text) => text.trim() || null),
187 Effect.orElseSucceed(() => null),
188 );
189
190 const windowRef = yield* Ref.make(Option.none<Electron.BrowserWindow>());
191 // The failure that opened the window; later restarts do not reload its details.
192 const failureRef = yield* Ref.make(Option.none<BackendStartupFailure>());
193 const renderedHtmlRef = yield* Ref.make("");
194 const checkedRef = yield* Ref.make(false);
195 let backendHasStarted = false;
196 const { latest, changes: updateChanges } = yield* updates.subscribe;
197 const updateStateRef = yield* Ref.make(latest);
198
199 const offer = Effect.all([Ref.get(updateStateRef), Ref.get(failureRef)]).pipe(
200 Effect.map(([state, failure]) =>
201 resolveStartupRecoveryOffer(
202 state,
203 lastStartedVersion,
204 Option.exists(failure, ({ managedPolicy }) => managedPolicy),
205 ),
206 ),
207 );
208
209 const render = Effect.gen(function* () {
210 const window = yield* Ref.get(windowRef);
211 const failure = yield* Ref.get(failureRef);
212 if (Option.isNone(window) || Option.isNone(failure) || window.value.isDestroyed()) return;
213 const html = buildStartupRecoveryHtml({
214 appVersion: environment.appVersion,
215 failure: failure.value,
216 offer: yield* offer,
217 logDir: environment.logDir,
218 });
219 if ((yield* Ref.getAndSet(renderedHtmlRef, html)) === html) return;
220 void window.value.loadURL(`data:text/html;charset=utf-8,${encodeURIComponent(html)}`);
221 });
222
223 const runAction = Effect.fn("desktop.startupRecovery.runAction")(function* (
224 action: StartupRecoveryAction,
225 ) {
226 yield* logInfo("startup recovery action", { action });
227 const current = yield* offer;
228 switch (action) {
229 case "update": {
230 if (current._tag !== "Update") return;
231 let { downloadedVersion } = yield* updates.getState;
232 if (downloadedVersion === null) {
233 // The download re-checks first, so it can fetch a newer build than the one offered.
234 const download = yield* updates.download;
235 if (!download.completed) return;
236 downloadedVersion = download.state.downloadedVersion;
237 }
238 if (downloadedVersion === null) return;
239 yield* updates.installPrepared(downloadedVersion);
240 return;
241 }
242 case "reinstall":
243 if (current._tag === "Reinstall") {
244 yield* electronShell.openExternal(`${RELEASES_URL}/tag/v${current.version}`);
245 }
246 return;
247 case "releases":
248 yield* electronShell.openExternal(RELEASES_URL);
249 return;
250 case "copy": {
251 const failure = yield* Ref.get(failureRef);
252 if (Option.isNone(failure)) return;
253 yield* electronShell.copyText(
254 `T3 Code ${environment.appVersion} (${environment.platform} ${environment.processArch}) could not start.\n${failure.value.reason}\n\n${failure.value.output}`,
255 );
256 return;
257 }
258 case "quit":
259 yield* electronApp.quit;
260 return;
261 }
262 });
263
264 const show = Effect.fn("desktop.startupRecovery.show")(
265 function* () {
266 if (yield* Ref.get(quitting)) return;
267 // A visible boot shell still needs recovery if the backend has never started.
268 const main = yield* electronWindow.main;
269 if (
270 backendHasStarted &&
271 Option.isSome(main) &&
272 !main.value.isDestroyed() &&
273 main.value.isVisible()
274 )
275 return;
276 const existing = yield* Ref.get(windowRef);
277 if (Option.isSome(existing) && !existing.value.isDestroyed()) {
278 yield* electronWindow.reveal(existing.value);
279 return;
280 }
281 const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
282 const window = yield* electronWindow.create(
283 {
284 width: 640,
285 height: 480,
286 minWidth: 420,
287 minHeight: 320,
288 show: false,
289 title: m(msg("T3 Code could not start")),
290 autoHideMenuBar: true,
291 backgroundColor: shouldUseDarkColors ? "#000000" : "#ffffff",
292 webPreferences: {
293 contextIsolation: true,
294 nodeIntegration: false,
295 sandbox: true,
296 javascript: false,
297 },
298 },
299 { auxiliary: true },
300 );
301 window.webContents.setWindowOpenHandler(() => ({ action: "deny" }));
302 window.webContents.on("will-navigate", (event, url) => {
303 event.preventDefault();
304 const action = STARTUP_RECOVERY_ACTIONS.find((name) => url === `${ACTION_ORIGIN}/${name}`);
305 if (action !== undefined) runFork(runAction(action));
306 });
307 window.once("ready-to-show", () => {
308 if (!window.isDestroyed()) window.show();
309 });
310 window.once("closed", () => {
311 runFork(
312 Ref.set(windowRef, Option.none()).pipe(Effect.andThen(Ref.set(renderedHtmlRef, ""))),
313 );
314 });
315 yield* Ref.set(windowRef, Option.some(window));
316 yield* render;
317 yield* logInfo("startup recovery window shown");
318 },
319 Effect.catch((error) =>
320 logWarning("could not show startup recovery", { errorTag: error._tag }),
321 ),
322 );
323
324 const close = Effect.gen(function* () {
325 const window = yield* Ref.getAndSet(windowRef, Option.none());
326 if (Option.isSome(window) && !window.value.isDestroyed()) window.value.close();
327 });
328
329 const closeWhenMainReady = Effect.gen(function* () {
330 if ((yield* SubscriptionRef.get(primaryBackendStartup))._tag !== "Ready") return;
331 const main = yield* electronWindow.main;
332 if (Option.isSome(main) && !main.value.isDestroyed() && main.value.isVisible()) yield* close;
333 });
334
335 yield* electronApp.on(
336 "browser-window-created",
337 (_event: Electron.Event, window: Electron.BrowserWindow) => {
338 window.on("show", () => runFork(closeWhenMainReady));
339 },
340 );
341
342 const rememberStartedVersion = Effect.gen(function* () {
343 if (lastStartedVersion === environment.appVersion) return;
344 yield* fileSystem.writeFileString(lastStartedVersionPath, environment.appVersion);
345 }).pipe(
346 Effect.catch((error) =>
347 logWarning("could not record the started version", { errorTag: error._tag }),
348 ),
349 );
350
351 yield* updateChanges.pipe(
352 Stream.runForEach((state) => Ref.set(updateStateRef, state).pipe(Effect.andThen(render))),
353 Effect.forkScoped,
354 );
355
356 yield* SubscriptionRef.changes(primaryBackendStartup).pipe(
357 Stream.runForEach(
358 Effect.fn("desktop.startupRecovery.onStartupChange")(function* (startup) {
359 if (startup._tag === "Ready") {
360 backendHasStarted = true;
361 yield* Ref.set(failureRef, Option.none());
362 yield* closeWhenMainReady;
363 yield* rememberStartedVersion;
364 return;
365 }
366 if (startup._tag !== "Failing") return;
367 if (Option.isSome(yield* Ref.get(failureRef))) return;
368 const { _tag, ...failure } = startup;
369 yield* Ref.set(failureRef, Option.some(failure));
370 // The backend manager already logs each failure's reason.
371 yield* logWarning("primary backend failing to start");
372 yield* show();
373 if (!(yield* Ref.getAndSet(checkedRef, true))) {
374 yield* updates.check("startup-recovery").pipe(Effect.forkScoped);
375 }
376 }),
377 ),
378 Effect.catchCause((cause) =>
379 Effect.logWarning("startup recovery stopped", cause).pipe(
380 Effect.annotateLogs({ component: "desktop-startup-recovery" }),
381 ),
382 ),
383 Effect.forkScoped,
384 );
385
386 // macOS keeps running with no windows; the Dock icon must bring the error back.
387 yield* electronApp.on("activate", () => {
388 runFork(
389 Ref.get(failureRef).pipe(
390 Effect.flatMap((failure) => (Option.isSome(failure) ? show() : Effect.void)),
391 ),
392 );
393 });
394});