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