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

DesktopStartupRecovery.ts

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