Open History to see the last commit
1import type { DesktopBridge, DesktopUpdateState } from "@t3tools/contracts";
2
3const FALLBACK_TRIAGE_COMMAND = "npx t3 triage";
4const DOWNLOAD_URL = "https://t3.codes/download";
5const ISSUE_URL = "https://github.com/pingdotgg/t3code/issues/new";
6const LAST_FAILURE_KEY = "t3code:boot-failed-at";
7const REPEAT_FAILURE_MS = 5 * 60_000;
8const MAX_CAUSES = 3;
9const MAX_ERROR_CHARS = 6_000;
10const COPY_BLOCKED = "Copy was blocked. The text is selected so you can copy it manually.";
11const UPDATE_DOWNLOAD_FAILED = "The update download failed. Try Download update again.";
12const UPDATE_INSTALL_FAILED = "The update install failed. Try Restart to update again.";
13
14/** The Windows launcher is a `.cmd` run from PowerShell, which needs `&` to run a quoted path. */
15function launcherCommand(launcherPath: string) {
16 if (launcherPath.endsWith(".cmd")) {
17 return /^[\w:\\.-]+$/.test(launcherPath)
18 ? launcherPath
19 : `& '${launcherPath.replace(/['\u2018\u2019\u201A\u201B]/g, "$&$&")}'`;
20 }
21 return /^[\w@%+=:,./-]+$/.test(launcherPath)
22 ? launcherPath
23 : `'${launcherPath.replaceAll("'", `'"'"'`)}'`;
24}
25
26/** Desktop can run its bundled launcher without Node; everything else falls back to npx. */
27export async function resolveTriageCommand(bridge: DesktopBridge | undefined) {
28 try {
29 const state = await bridge?.cliCommand.getState();
30 // Windows reports onPath from its PATH entry alone; only an existing launcher proves it runs.
31 if (state?.launcherPath) {
32 return state.onPath ? "t3 triage" : `${launcherCommand(state.launcherPath)} triage`;
33 }
34 } catch (error) {
35 console.warn("Could not read the desktop CLI state.", error);
36 }
37 return FALLBACK_TRIAGE_COMMAND;
38}
39
40/** The update button only appears when the desktop updater has a newer build to offer. */
41export function updateActionFor(state: DesktopUpdateState | null | undefined) {
42 switch (state?.status) {
43 case "available":
44 return { kind: "download" } as const;
45 case "downloading":
46 return { kind: "downloading", percent: Math.round(state.downloadPercent ?? 0) } as const;
47 case "downloaded":
48 return { kind: "install" } as const;
49 default:
50 return null;
51 }
52}
53
54function safeString(value: unknown) {
55 try {
56 return String(value);
57 } catch {
58 return "";
59 }
60}
61
62function describeOne(value: unknown) {
63 if (value instanceof Error) {
64 const header = value.message ? `${value.name}: ${value.message}` : value.name;
65 // V8 stacks start with the header; Safari and Firefox stacks do not.
66 const stack = typeof value.stack === "string" ? value.stack : "";
67 return stack === header || stack.startsWith(`${header}\n`)
68 ? stack
69 : [header, stack].filter(Boolean).join("\n");
70 }
71 if (typeof value === "string") return value;
72 try {
73 return JSON.stringify(value) ?? safeString(value);
74 } catch {
75 return safeString(value);
76 }
77}
78
79/** Hosts can name private machines, and pairing tokens live in query strings and hashes. */
80function redact(text: string) {
81 return text
82 .replace(/\b[a-z][\w+.-]*:\/\/[^\s/?#'"()]+/gi, "")
83 .replace(/[?#][^\s'"()]*=[^\s'"()]*?((?::\d+){1,2})?(?=[\s'"()]|$)/g, "$1");
84}
85
86export interface BootErrorEnvironment {
87 readonly version: string;
88 readonly channel: string;
89 readonly surface: "desktop" | "web";
90 readonly platform: string;
91 readonly userAgent: string;
92 readonly time: string;
93}
94
95/** Plain text that is shown and copied as-is, so users see exactly what they share. */
96export function buildErrorReport(error: unknown, environment: BootErrorEnvironment) {
97 const parts: Array<string> = [];
98 const seen = new Set<unknown>();
99 let current = error;
100 while (current != null && !seen.has(current) && parts.length <= MAX_CAUSES) {
101 seen.add(current);
102 const text = describeOne(current);
103 parts.push(parts.length === 0 ? text : `Caused by: ${text}`);
104 current = current instanceof Error ? current.cause : undefined;
105 }
106 let details = redact(parts.join("\n") || "(no error message)");
107 if (details.length > MAX_ERROR_CHARS) {
108 let end = MAX_ERROR_CHARS;
109 const last = details.charCodeAt(end - 1);
110 if (last >= 0xd800 && last <= 0xdbff) end -= 1;
111 details = `${details.slice(0, end)}\n[truncated]`;
112 }
113 return [
114 details,
115 "",
116 `Version: ${environment.version}`,
117 `Channel: ${environment.channel}`,
118 `Surface: ${environment.surface}`,
119 `Platform: ${environment.platform}`,
120 `User agent: ${environment.userAgent}`,
121 `Time: ${environment.time}`,
122 ].join("\n");
123}
124
125function clientPlatform(bridge: DesktopBridge | undefined) {
126 try {
127 return bridge?.getClientPlatform() ?? navigator.platform;
128 } catch {
129 return navigator.platform;
130 }
131}
132
133function readEnvironment(bridge: DesktopBridge | undefined): BootErrorEnvironment {
134 const version = import.meta.env.APP_VERSION;
135 return {
136 version,
137 channel:
138 import.meta.env.VITE_RELEASE_CHANNEL || /-(nightly|preview)\./.exec(version)?.[1] || "stable",
139 surface: bridge ? "desktop" : "web",
140 platform: clientPlatform(bridge),
141 userAgent: navigator.userAgent,
142 time: new Date().toISOString(),
143 };
144}
145
146/** Opens More options by default when startup already failed in this tab a moment ago. */
147function isRepeatFailure(now: number) {
148 try {
149 const previous = Number(sessionStorage.getItem(LAST_FAILURE_KEY));
150 sessionStorage.setItem(LAST_FAILURE_KEY, String(now));
151 return now - previous < REPEAT_FAILURE_MS;
152 } catch {
153 return false;
154 }
155}
156
157const icon = (paths: string) =>
158 `<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${paths}</svg>`;
159const COPY_ICON = icon(
160 '<rect width="14" height="14" x="8" y="8" rx="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/>',
161);
162const CHECK_ICON = icon('<path d="M20 6 9 17l-5-5"/>');
163
164function element<K extends keyof HTMLElementTagNameMap>(
165 tag: K,
166 props: Partial<HTMLElementTagNameMap[K]> = {},
167 children: ReadonlyArray<Node | string> = [],
168) {
169 const node = Object.assign(document.createElement(tag), props);
170 node.append(...children);
171 return node;
172}
173
174function selectContents(target: HTMLElement) {
175 const range = document.createRange();
176 range.selectNodeContents(target);
177 const selection = window.getSelection();
178 selection?.removeAllRanges();
179 selection?.addRange(range);
180}
181
182function copySelection() {
183 try {
184 return document.execCommand("copy");
185 } catch {
186 return false;
187 }
188}
189
190/** Plain http has no Clipboard API, but the legacy copy command still works on a selection. */
191function copyText(target: HTMLElement, onCopied: () => void, onBlocked: (hint: string) => void) {
192 const fallback = () => {
193 selectContents(target);
194 if (copySelection()) return onCopied();
195 onBlocked(
196 /Mac|iPhone|iPad/.test(navigator.platform) ? "Press ⌘C to copy" : "Press Ctrl+C to copy",
197 );
198 };
199 const clipboard = window.isSecureContext ? navigator.clipboard : undefined;
200 if (typeof clipboard?.writeText !== "function") return fallback();
201 clipboard.writeText(target.textContent ?? "").then(onCopied, fallback);
202}
203
204function mountUpdateButton(
205 bridge: DesktopBridge,
206 button: HTMLButtonElement,
207 note: HTMLParagraphElement,
208 announce: (text: string) => void,
209) {
210 let action: ReturnType<typeof updateActionFor> = null;
211 const render = (state: DesktopUpdateState) => {
212 action = updateActionFor(state);
213 button.hidden = action === null;
214 // aria-disabled keeps keyboard focus on the button while the download runs.
215 button.setAttribute("aria-disabled", String(action?.kind === "downloading"));
216 if (action?.kind === "download") button.textContent = "Download update";
217 if (action?.kind === "downloading")
218 button.textContent = `Downloading update (${action.percent}%)`;
219 if (action?.kind === "install") button.textContent = "Restart to update";
220 const failure = !action
221 ? ""
222 : state.errorContext === "download"
223 ? UPDATE_DOWNLOAD_FAILED
224 : state.errorContext === "install"
225 ? UPDATE_INSTALL_FAILED
226 : "";
227 if (failure === note.textContent) return;
228 note.textContent = failure;
229 note.hidden = !failure;
230 if (failure) announce(failure);
231 };
232 button.addEventListener("click", () => {
233 const run =
234 action?.kind === "install"
235 ? bridge.installUpdate()
236 : action?.kind === "download"
237 ? bridge.downloadUpdate()
238 : undefined;
239 run?.then(
240 (result) => render(result.state),
241 (error: unknown) => console.warn("Could not update T3 Code.", error),
242 );
243 });
244 // A pushed state is newer than the initial read, so the read must not overwrite it.
245 let pushed = false;
246 try {
247 bridge.onUpdateState((state) => {
248 pushed = true;
249 render(state);
250 });
251 bridge.getUpdateState().then(
252 (state) => pushed || render(state),
253 (error: unknown) => console.warn("Could not read the desktop update state.", error),
254 );
255 } catch (error) {
256 console.warn("Could not read the desktop update state.", error);
257 }
258}
259
260export function showBootError(error: unknown) {
261 console.error("T3 Code failed to start.", error);
262 const bootShell = document.getElementById("boot-shell");
263 if (!bootShell) return;
264
265 const bridge = window.desktopBridge;
266 const environment = readEnvironment(bridge);
267 const offline = !bridge && navigator.onLine === false;
268
269 const status = element("span", { className: "boot-error-sr" });
270 status.setAttribute("aria-live", "polite");
271 // Clearing first makes screen readers announce a repeated message.
272 let announcement: ReturnType<typeof setTimeout> | undefined;
273 const announce = (text: string) => {
274 clearTimeout(announcement);
275 status.textContent = "";
276 announcement = setTimeout(() => (status.textContent = text), 100);
277 };
278
279 const message = element("div", {}, [
280 element("h1", { textContent: "T3 Code failed to start" }),
281 element("p", {
282 textContent: offline
283 ? "This browser appears to be offline. Check the connection, then reload."
284 : "We are not sure why. Try a reload first.",
285 }),
286 ]);
287 message.setAttribute("role", "alert");
288
289 const reload = element("button", {
290 id: "boot-error-reload",
291 type: "button",
292 textContent: "Reload",
293 });
294 reload.addEventListener("click", () => window.location.reload());
295 const update = element("button", { id: "boot-error-update", type: "button", hidden: true });
296 const updateNote = element("p", { id: "boot-error-update-note", hidden: true });
297 if (bridge) mountUpdateButton(bridge, update, updateNote, announce);
298
299 const command = element("code", { textContent: FALLBACK_TRIAGE_COMMAND });
300 const copyCommand = element("button", {
301 className: "boot-error-icon",
302 type: "button",
303 // oxlint-disable-next-line t3code/no-untranslated-copy -- boot failure page renders before the i18n runtime loads
304 title: "Copy command",
305 innerHTML: COPY_ICON,
306 });
307 // oxlint-disable-next-line t3code/no-untranslated-copy -- boot failure page renders before the i18n runtime loads
308 copyCommand.setAttribute("aria-label", "Copy command");
309 copyCommand.addEventListener("click", () =>
310 copyText(
311 command,
312 () => {
313 copyCommand.innerHTML = CHECK_ICON;
314 copyCommand.title = "Copied";
315 // oxlint-disable-next-line t3code/no-untranslated-copy -- boot failure page renders before the i18n runtime loads
316 copyCommand.setAttribute("aria-label", "Copied");
317 // oxlint-disable-next-line t3code/no-untranslated-copy -- boot failure page renders before the i18n runtime loads
318 announce("Copied to clipboard.");
319 },
320 (hint) => {
321 copyCommand.textContent = hint;
322 copyCommand.title = hint;
323 copyCommand.setAttribute("aria-label", hint);
324 announce(COPY_BLOCKED);
325 },
326 ),
327 );
328 void resolveTriageCommand(bridge).then((value) => (command.textContent = value));
329
330 let report = "(no error message)";
331 try {
332 report = buildErrorReport(error, environment);
333 } catch (reportError) {
334 console.warn("Could not describe the startup error.", reportError);
335 }
336 const details = element("pre", { id: "boot-error-details", tabIndex: 0, textContent: report });
337 const copyDetails = element("button", { type: "button", textContent: "Copy error details" });
338 copyDetails.addEventListener("click", () =>
339 copyText(
340 details,
341 () => {
342 copyDetails.textContent = "Copied";
343 // oxlint-disable-next-line t3code/no-untranslated-copy -- boot failure page renders before the i18n runtime loads
344 announce("Copied to clipboard.");
345 },
346 (hint) => {
347 copyDetails.textContent = hint;
348 announce(COPY_BLOCKED);
349 },
350 ),
351 );
352
353 const issue = new URL(ISSUE_URL);
354 issue.searchParams.set("template", "bug_report.yml");
355 issue.searchParams.set("title", "T3 Code failed to start");
356 issue.searchParams.set("area", "apps/web");
357 issue.searchParams.set("version", `${environment.version} (${environment.channel})`);
358 issue.searchParams.set("environment", `${environment.surface}, ${environment.platform}`);
359 const link = (href: string, textContent: string) =>
360 element("a", { href, textContent, target: "_blank", rel: "noreferrer" });
361 const nightly = environment.channel === "nightly";
362
363 const more = element("details", { open: isRepeatFailure(Date.now()) }, [
364 element("summary", { textContent: "More options if it keeps failing" }),
365 ...(bridge
366 ? [
367 link(
368 nightly ? `${DOWNLOAD_URL}?channel=nightly` : DOWNLOAD_URL,
369 nightly
370 ? "Download and reinstall the latest nightly build"
371 : "Download and reinstall T3 Code",
372 ),
373 ]
374 : []),
375 element("div", {}, [
376 element("p", {
377 textContent:
378 "Run this on the computer that runs T3 Code. Your agent can check the local logs and help you file a bug report.",
379 }),
380 element("div", { id: "boot-error-command" }, [command, copyCommand]),
381 ]),
382 element("div", {}, [
383 details,
384 element("p", {
385 textContent: "Details may include local file paths and names. Check before sharing.",
386 }),
387 element("div", { id: "boot-error-report" }, [
388 copyDetails,
389 link(issue.href, "File a bug report on GitHub"),
390 ]),
391 ]),
392 ]);
393
394 bootShell.replaceChildren(
395 element("div", { id: "boot-error" }, [
396 message,
397 element("div", { id: "boot-error-actions" }, [reload, update]),
398 updateNote,
399 more,
400 status,
401 ]),
402 );
403}