Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

DesktopStartupRecovery.ts

338 lines13.9 KB

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" };
66​
67const escapeHtml = (value: string) =>
68 value.replace(
69 /[&<>"']/g,
70 (char) =>
71 ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[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 }
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>`;
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 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});