diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md index fa61c3ae..78c4c20a 100644 --- a/docs/TROUBLESHOOTING.md +++ b/docs/TROUBLESHOOTING.md @@ -48,9 +48,11 @@ If the browser-backed checks fail in CI or a container, install Chromium during The error message says `ghostty-web crashed while it replayed this session's output.` The Chromium page of the `ghostty-web` renderer died while it replayed the event log. `screenshot` (also with `--renderer libghostty-vt`, because its screenshot replays the log in a `ghostty-web` page) and `snapshot --renderer ghostty-web` fail with `REPLAY_ERROR` (exit `10`, `retryable: false`), on a live session and on an exited one. `record export --format webm` fails with `EXPORT_ERROR` (exit `7`). The message ends with the Playwright text, `(page.evaluate: Target crashed)`. -One known cause is a bug in ghostty-web 0.4.0. After a full reset (`ESC c`), `CSI ? 47 h` and `CSI ? 1047 h` show the old cells on the alternate screen. Output over a cell that holds a combining mark or another grapheme cluster then crashes the page. The shortest input has 12 bytes: `a`, U+0301, `ESC c`, `ESC [ ? 4 7 h` and `o`. `CSI ? 1049 h` is not affected. +The crash is a bug in the WASM module of ghostty-web 0.4.0. Several different inputs trigger it. Some need no reset, no resize and no alternate screen: a plain print of many lines that hold combining marks also crashes the page. -Running the command again does not help, because each run replays the same log and the page crashes again. The session itself keeps running, and the host stays up. A render `wait` with `--renderer ghostty-web` stops with the same error after 10 failed polls. These commands do not use the page, so they still work on such a session: +One known cause is [coder/ghostty-web#215](https://github.com/coder/ghostty-web/issues/215). After a full reset (`ESC c`), `CSI ? 47 h` and `CSI ? 1047 h` show the old cells on the alternate screen. Output over a cell that holds a combining mark or another grapheme cluster then crashes the page. The shortest input has 12 bytes: `a`, U+0301, `ESC c`, `ESC [ ? 4 7 h` and `o`. `CSI ? 1049 h` is not affected. + +Running the command again does not help, because each run replays the same log and the page crashes again. The session itself keeps running, and the host stays up. A render `wait` with `--renderer ghostty-web` stops at the first crash with the same error. These commands do not use the page, so they still work on such a session: - `snapshot` and `wait` with the `libghostty-vt` renderer, which is the default when its native package is available - `record export --format svg` and `record export --format asciicast` diff --git a/docs/USAGE.md b/docs/USAGE.md index fc1547e6..248fe64b 100644 --- a/docs/USAGE.md +++ b/docs/USAGE.md @@ -152,7 +152,7 @@ On timeout, a standalone `wait` exits `11` and prints an error envelope: `ok: fa A render wait reads the session's event log. When that log has stopped at its limit (see [the event log limit](TROUBLESHOOTING.md#a-recording-ends-early-or-an-export-names-the-event-log-limit)), a timed-out render wait adds `The event log stopped at seq 41 (byte limit), so output after it is not seen.` to its message, with and without `--json`, and `error.details.eventLogStop` holds `{ "reason": "bytes", "seq": 41 }`. The host reports the stop with its timeout result, so a wait that times out at the moment the log stops names it too. A `batch` `wait` step adds the same sentence to its message. On an exited session, `wait` replays the stored log, and a wait that the replayed screen does not satisfy fails with `REPLAY_ERROR`. Its message ends with the same sentence, and `error.details.eventLogStop` carries the same facts. `reason` is `unknown` when the stop marker names no limit, and the sentence then reads `(reason unknown)`. `--idle-ms` and `--exit` waits do not read the log, so they add nothing. A wait that matches is not changed. -`WAIT_TIMEOUT` only means that the timeout ran out. When 10 render polls in a row fail (about 3 s, for example because the renderer cannot start), a render `wait` stops with the renderer's error instead, also with `--timeout 0`: the same `error.code` and exit code that `snapshot` gives for that failure, usually `RPC_ERROR` (exit `9`, `retryable: true`), and no `result`. A `batch` `wait` step fails with that code, and its step record has no `timedOut`. Fewer failed polls in a row are retried. +`WAIT_TIMEOUT` only means that the timeout ran out. When 10 render polls in a row fail (about 3 s, for example because the renderer cannot start), a render `wait` stops with the renderer's error instead, also with `--timeout 0`: the same `error.code` and exit code that `snapshot` gives for that failure, usually `RPC_ERROR` (exit `9`, `retryable: true`), and no `result`. A `batch` `wait` step fails with that code, and its step record has no `timedOut`. Fewer failed polls in a row are retried. The one failure that is not retried is a crash of the `ghostty-web` page: the `wait` stops at the first crash with `REPLAY_ERROR` (exit `10`, `retryable: false`), as `snapshot` does. ### Echo-Match @@ -259,7 +259,7 @@ The Wait Baseline fixes stale-match only. It does **not** fix echo-match: a whol ## Screenshots And Recording Exports -Screenshots and WebM export use the `ghostty-web` reference visual renderer through Playwright/Chromium. When its page crashes during a replay, the error message says `ghostty-web crashed` and names a known cause (see [Troubleshooting](TROUBLESHOOTING.md#a-command-says-ghostty-web-crashed)). +Screenshots and WebM export use the `ghostty-web` reference visual renderer through Playwright/Chromium. When its page crashes during a replay, the error message says `ghostty-web crashed`, says that several inputs do this and names one known cause (see [Troubleshooting](TROUBLESHOOTING.md#a-command-says-ghostty-web-crashed)). Semantic `snapshot`, screen-hash, and render-backed `wait` paths prefer `libghostty-vt` when the optional native package is available and fall back to `ghostty-web` otherwise. Run `doctor --json` first in new environments. On a session that has printed nothing yet, `snapshot` returns an empty screen of the session's size and `screenshot` returns a blank image. `record export` gives a header-only asciicast, a blank WebM or a blank SVG of the session's size, with `durationMs: 0`. An animated SVG of such a session reports `durationMs: 1000`, the hold of its one blank frame. All of them report `capturedAtSeq: -1`, and the default files are named `screenshot--1-.png`, `recording--1-.` and `recording--1-svg-[-animated].svg`. diff --git a/src/cli/commands/README.md b/src/cli/commands/README.md index a0e2ed1e..32881de3 100644 --- a/src/cli/commands/README.md +++ b/src/cli/commands/README.md @@ -34,7 +34,7 @@ This directory holds one handler module per agent-tty CLI command. `src/cli/main - `wait` rejects a mix of legacy flags (`--exit`, `--idle-ms`) and render flags. `--text` and `--regex` are mutually exclusive. The default timeout is `DEFAULT_WAIT_TIMEOUT_MS` (30,000 ms), which the `main.ts` help text names. An `--idle-ms` at or above the effective timeout (explicit or default), or a `--screen-stable-ms` whose `screenStableMinimumMs` is not shorter than it, throws `INVALID_DURATION`. `--timeout 0` skips the check. [wait.ts:runWaitCommand] [wait.ts:assertWindowFitsTimeout] [main.ts:main] - A timed-out `wait` throws `WAIT_TIMEOUT` with the wait result attached, so its error envelope keeps `result`. Without `--json`, and only when the wait lasted its whole timeout (`timeoutMs > 0`, measured by the CLI), the message names the timeout and, for the default, how to change it. With `--json`, the message stays `Wait timed out before its condition was met.` The host sends `eventLogStop` with the result of a render wait that timed out. When it does, in both modes the message ends with `The event log stopped at seq (), so output after it is not seen.` and `details.eventLogStop` carries `{ reason, seq }`. The CLI never rereads the event log for a wait. `--idle-ms` and `--exit` waits carry no stop. When the host is unreachable, `wait` replays the stored log. A wait that the replayed screen does not satisfy fails with `REPLAY_ERROR`, and its message and `details.eventLogStop` carry the stop that `findEventLogStop` finds in the replayed events. [wait.ts:throwIfTimedOut] [wait.ts:timeoutMessage] [wait.ts:buildOfflineRenderWaitResult] - `snapshot` and `screenshot` try the live RPC only when the manifest status is `running`. They fall back to offline replay only on `HOST_UNREACHABLE` and rethrow other errors. [snapshot.ts:runSnapshotCommand] [screenshot.ts:runScreenshotCommand] -- `record export` accepts only the formats in `RecordExportFormatSchema` (`asciicast`, `webm`, `svg`). `--animate` needs `svg`, and `svg` refuses `--timing`. An event log over the size limit fails with `EXPORT_ERROR` in every format, a message that names the log size and the limit, and `eventLogBytes` and `maxEventLogBytes` in `details`. A `webm` replay whose renderer makes no progress for the stall window fails with `EXPORT_ERROR`, a message that names the window and the last event that the replay reached, and `stallWindowMs`, `lastSeq` and `timingMode` in `details`. A `GhosttyWebCrashedError` from a WebM export fails with `EXPORT_ERROR` and adds its message to the fixed message. [record-export.ts:runRecordExportCommand] +- `record export` accepts only the formats in `RecordExportFormatSchema` (`asciicast`, `webm`, `svg`). `--animate` needs `svg`, and `svg` refuses `--timing`. An event log over the size limit fails with `EXPORT_ERROR` in every format, a message that names the log size and the limit, and `eventLogBytes` and `maxEventLogBytes` in `details`. A `webm` replay whose renderer makes no progress for the stall window fails with `EXPORT_ERROR`, a message that names the window and the last event that the replay reached, and `stallWindowMs`, `lastSeq` and `timingMode` in `details`. Any other failure of an export fails with `EXPORT_ERROR` and a message that ends with the cause, cut to its first line and at most 300 characters (`summarizeError`). A `GhosttyWebCrashedError` from a WebM export fails with `EXPORT_ERROR` and adds its message to the fixed message. [record-export.ts:runRecordExportCommand] - `batch` parses the whole plan with `parseBatchPlan` before it resolves the session target. [batch.ts:runBatchCommand] - `create` polls readiness with an `inspect` RPC every `READINESS_POLL_INTERVAL_MS` (100 ms) for as long as the host process that it spawned runs (`hostRuns`). A probe that fails with `HOST_UNREACHABLE`, `HOST_TIMEOUT` or an `RPC_ERROR` whose cause is `EPIPE` (the host closed its server as the probe connected, as a host does whose program has already exited) counts as not ready yet (`isClosedByHost`). `create` rethrows that last error as soon as the host process has exited, and after `READINESS_DEADLINE_MS` (30 s) in any case. Any other error ends the wait at once. It checks the host process before it reads the manifest, so a session that exited before the host did is a result, not an error. [create.ts:waitForReadyHost] - `doctor` reports the `node-runtime` check as failed when the Node version is outside the `engines.node` range of `package.json`. It keeps running the other checks, reports `ok: false` and sets `process.exitCode = 1`. [doctor.ts:runNodeRuntimeCheck] [doctor.ts:runDoctorCommand] diff --git a/src/cli/commands/record-export.ts b/src/cli/commands/record-export.ts index 1bebc8ec..5fd43e51 100644 --- a/src/cli/commands/record-export.ts +++ b/src/cli/commands/record-export.ts @@ -60,6 +60,7 @@ import { } from '../../storage/outputPath.js'; import { eventLogPath, manifestPath } from '../../storage/sessionPaths.js'; import { invariant } from '../../util/assert.js'; +import { summarizeError } from '../../util/errorSummary.js'; import { loadPackageMetadata } from '../../util/packageMetadata.js'; const RecordExportFormatSchema = z.enum(['asciicast', 'webm', 'svg']); @@ -617,10 +618,12 @@ export async function runRecordExportCommand( }); } + const reason = + error instanceof GhosttyWebCrashedError + ? `. ${error.message}` + : `: ${summarizeError(error)}`; throw makeCliError(ERROR_CODES.EXPORT_ERROR, { - message: `Failed to export session "${options.sessionId}" as ${format}.${ - error instanceof GhosttyWebCrashedError ? ` ${error.message}` : '' - }`, + message: `Failed to export session "${options.sessionId}" as ${format}${reason}`, details: { sessionId: options.sessionId, format, diff --git a/src/host/README.md b/src/host/README.md index 58940e81..a5496296 100644 --- a/src/host/README.md +++ b/src/host/README.md @@ -11,7 +11,7 @@ - `normalizeExitSignal(signal)` maps a PTY exit signal number to a string, or `null` for `null` and 0. [hostMain.ts:normalizeExitSignal] - `isSessionCommandable(state)` and `assertSessionCommandable(state)` check that the session status is commandable. The assert throws `SESSION_NOT_RUNNING`. [hostMain.ts:isSessionCommandable] [hostMain.ts:assertSessionCommandable] - `resolveHostRendererName(input?)` picks the renderer name from the input, then `AGENT_TTY_HOST_RENDERER`, then `AGENT_TTY_RENDERER`, then `DEFAULT_RENDERER_NAME` (from `src/renderer/names.ts`). It throws `INVALID_INPUT` for an unknown renderer name. [hostMain.ts:resolveHostRendererName] -- `MAX_CONSECUTIVE_POLL_FAILURES` (10) is the number of failed polls in a row after which a `waitForRender` wait rejects with the last poll error. A `CliError` keeps its code. The RPC server sends any other error as an RPC error, which the CLI reports as `RPC_ERROR`. [hostMain.ts:MAX_CONSECUTIVE_POLL_FAILURES] +- `MAX_CONSECUTIVE_POLL_FAILURES` (10) is the number of failed polls in a row after which a `waitForRender` wait rejects with the last poll error. Every failure of a poll counts, for example a browser that does not launch, because the next poll can pass. The one exception is the error of a crashed ghostty-web page (`isReplayCrashError`): the next poll replays the same output into a new page and crashes it again, so the wait rejects with that error at the first poll, with code `REPLAY_ERROR`, as a live `snapshot` does. [renderer.ts:isReplayCrashError] A `CliError` keeps its code. The RPC server sends any other error as an RPC error, which the CLI reports as `RPC_ERROR`. [hostMain.ts:MAX_CONSECUTIVE_POLL_FAILURES] - `allocateSession(config, launch)` validates an `AllocateConfig`, creates the session directory, calls `launch(sessionId)`, writes `host.json` for the launched host when `captureHost` can read it, and writes the first `running` manifest with the returned PID as `hostPid`. It returns an `AllocateResult` with `sessionId` and `sessionDirectory`. [lifecycle.ts:allocateSession] [lifecycle.ts:AllocateConfig] [lifecycle.ts:AllocateResult] - `launchHost(config)` spawns the host process for a `LaunchHostConfig` and returns a `LaunchedHost`: its PID and a `stop()` that sends the host SIGTERM through the `ChildProcess` handle, and nothing once the host has exited. `create` calls it from the `launch` callback of `allocateSession`, and calls `stop()` on any error after `allocateSession` returned, such as a give-up on the host. [lifecycle.ts:launchHost] [lifecycle.ts:LaunchHostConfig] [lifecycle.ts:LaunchedHost] [src/cli/commands/create.ts:runCreateCommand] - `removeSocketDirectoryIfEmpty(socketFile)` removes the Home's socket directory with `rmdir`. A directory that still holds a socket (`ENOTEMPTY` or `EEXIST`) or is already gone (`ENOENT`) stays as it is. `destroySession` and `reconcileSession` call it after they unlink a socket. The host's shutdown and `doctor`'s socket check call `removeSocketDirectoryBestEffort`, which logs any other `rmdir` error at debug level instead of throwing it. [lifecycle.ts:removeSocketDirectoryIfEmpty] [lifecycle.ts:removeSocketDirectoryBestEffort] diff --git a/src/host/hostMain.ts b/src/host/hostMain.ts index ffcb8ae8..35c36c99 100644 --- a/src/host/hostMain.ts +++ b/src/host/hostMain.ts @@ -24,7 +24,7 @@ import { writeProgramRecord, } from './programGroup.js'; import { buildReplayInput } from './replay.js'; -import { HostRendererManager } from './renderer.js'; +import { HostRendererManager, isReplayCrashError } from './renderer.js'; import { RpcServer, type MethodHandler } from './rpcServer.js'; import { RunCompletionCoordinator, @@ -1173,7 +1173,14 @@ export async function runHost( } consecutiveFailures += 1; - if (consecutiveFailures >= MAX_CONSECUTIVE_POLL_FAILURES) { + // Another poll replays the same output into a new page, so a + // crash of the ghostty-web page ends the wait at once. Any other + // failure can pass (a browser that fails to launch under load), + // so those get MAX_CONSECUTIVE_POLL_FAILURES polls in a row. + if ( + isReplayCrashError(pollError) || + consecutiveFailures >= MAX_CONSECUTIVE_POLL_FAILURES + ) { reject( pollError instanceof Error ? pollError diff --git a/src/host/renderer.ts b/src/host/renderer.ts index efa7abc3..1700540a 100644 --- a/src/host/renderer.ts +++ b/src/host/renderer.ts @@ -1,6 +1,7 @@ import { mkdirSync } from 'node:fs'; import { dirname, isAbsolute, relative, resolve, sep } from 'node:path'; +import { CliError } from '../cli/errors.js'; import { ERROR_CODES, makeCliError } from '../protocol/errors.js'; import type { RendererBackend } from '../renderer/backend.js'; import type { RendererName } from '../renderer/names.js'; @@ -43,6 +44,17 @@ function rethrowCrashAsReplayError(error: unknown): never { throw error; } +// True for the error that `withBackend` throws when a ghostty-web page +// crashed. The same output crashes the page again on every later call, so a +// caller that retries a failed call must not retry this one. +export function isReplayCrashError(error: unknown): boolean { + return ( + error instanceof CliError && + error.code === ERROR_CODES.REPLAY_ERROR && + error.cause instanceof GhosttyWebCrashedError + ); +} + function assertAbsolutePath(pathValue: string, label: string): void { assertNonEmptyString(pathValue, label); invariant(isAbsolute(pathValue), `${label} must be an absolute path`); diff --git a/src/renderer/ghosttyWeb/README.md b/src/renderer/ghosttyWeb/README.md index 0c3007f5..37e57da1 100644 --- a/src/renderer/ghosttyWeb/README.md +++ b/src/renderer/ghosttyWeb/README.md @@ -13,7 +13,7 @@ This directory holds the `ghostty-web` reference renderer. `GhosttyWebBackend` s - `screenshot(outputPath, options?)` returns a `ScreenshotResult` with `sha256`, `renderProfileHash` and `missingGlyphs` [backend.ts:GhosttyWebBackend.screenshot]. - `recordedMissingGlyphs()` returns the boxed code points of every frame that `replayWithTiming()` painted [backend.ts:GhosttyWebBackend.recordedMissingGlyphs]. - `finalizeVideo(outputPath)`, `getVisibleText()` and `dispose()` [backend.ts:GhosttyWebBackend.finalizeVideo]. -- `GhosttyWebCrashedError` [crashError.ts:GhosttyWebCrashedError] is re-exported by [index.ts:GhosttyWebCrashedError]. Its message explains a known ghostty-web 0.4.0 fault (RIS, then `?47h` or `?1047h`, then output over a grapheme cluster) and ends with the text of the page error. Its `cause` is that page error. `describeReplayFailure(error)` returns it for a page error that says `Target crashed`, and returns every other error as it is [crashError.ts:describeReplayFailure]. +- `GhosttyWebCrashedError` [crashError.ts:GhosttyWebCrashedError] is re-exported by [index.ts:GhosttyWebCrashedError]. Its message says that the page crashed in the WASM module of ghostty-web 0.4.0 and that several different inputs do this. It names the fault of coder/ghostty-web#215 (RIS, then `?47h` or `?1047h`, then output over a grapheme cluster) as one known cause, not as the cause, and it ends with the text of the page error. Its `cause` is that page error. `describeReplayFailure(error)` returns it for a page error that says `Target crashed`, and returns every other error as it is [crashError.ts:describeReplayFailure]. - `assembleCanonicalLine`, `stripTrailingAsciiSpaces` and type `GhosttyDecodedColumn` are re-exported from `harnessDecoding.ts` [backend.ts:GhosttyDecodedColumn]. - Harness snapshot types: `GhosttyHarnessVisibleLine`, `GhosttyHarnessSnapshotCell`, `GhosttyHarnessRichLine`, `GhosttyHarnessSnapshot` and `GhosttyDecodedColumn` [harnessDecoding.ts:GhosttyHarnessSnapshot]. - `missingGlyphs.ts`: `GlyphCheck.forProfile(profile)` returns a check, or `null` when the font stack does not start with a bundled font. `screen(page, grid)` takes one grapheme string per viewport cell and returns the boxed code points with their cells. `graphemes(page, graphemes, complete)` returns the boxed code points of a set of graphemes, without cells. A grapheme is a candidate unless one bundled family covers all of it in every face, also after NFC or NFD normalization. The spaces that HarfBuzz draws blank (U+00A0, U+2000-U+200A, U+202F, U+205F, U+3000) count as covered. Each candidate is probed whole, plus one probe text per code point that no bundled face has (a combining mark on its base). `probeUsedFonts(page, font, texts)` asks Chromium through CDP `CSS.getPlatformFontsForNode` which fonts draw each text, one block-level hidden span per text [missingGlyphs.ts:GlyphCheck]. diff --git a/src/renderer/ghosttyWeb/crashError.ts b/src/renderer/ghosttyWeb/crashError.ts index 92b23fcf..e67fbf7a 100644 --- a/src/renderer/ghosttyWeb/crashError.ts +++ b/src/renderer/ghosttyWeb/crashError.ts @@ -1,14 +1,21 @@ -// The ghostty-web page crashed while it replayed output. The cause that we -// know: ghostty-web 0.4.0 keeps the old cells on the alternate screen when -// `?47h` or `?1047h` follows a full reset (RIS, `ESC c`). Output over a cell -// that holds a combining mark or another grapheme cluster then makes the WASM -// module fault, and Chromium kills the page ("Target crashed"). The shortest -// input is `a`, U+0301, `ESC c`, `ESC [ ? 4 7 h`, `o`. Upstream issue: +// The ghostty-web page crashed while it replayed output. Chromium reports it +// as "Target crashed". ghostty-web 0.4.0 has more than one WASM fault that does +// this ("memory access out of bounds" in the WASM module), and different +// inputs reach them. A crash that has no reset, no resize and no alternate +// screen is known (a plain print of many lines that hold combining marks). So +// the message must not name one input as the cause. +// +// One known input: after a full reset (RIS, `ESC c`), ghostty-web 0.4.0 keeps +// the old cells on the alternate screen when `?47h` or `?1047h` follows. +// Output over a cell that holds a combining mark or another grapheme cluster +// then faults the WASM module. The shortest input is `a`, U+0301, `ESC c`, +// `ESC [ ? 4 7 h`, `o`. Upstream issue: // https://github.com/coder/ghostty-web/issues/215. No ghostty-web release has -// a fix yet. When one closes it, remove this error, or invert the tests that -// carry a KNOWN-BUG header, and bump the version that the message names. +// a fix for any of the faults yet. When a release fixes them, remove this +// error, or invert the tests that carry a KNOWN-BUG header, and bump the +// version that the message names. const CRASH_EXPLANATION = - "ghostty-web crashed while it replayed this session's output. One known cause is a ghostty-web 0.4.0 bug: after a full reset (ESC c), the alternate screen (?47h or ?1047h) keeps the old cells, and output over a combining mark or other grapheme cluster there crashes the page. The libghostty-vt renderer and `record export --format svg` are not affected."; + "ghostty-web crashed while it replayed this session's output. This is a bug in the WASM module of ghostty-web 0.4.0, which several different inputs trigger. One known cause is https://github.com/coder/ghostty-web/issues/215 (a full reset, ESC c, then ?47h or ?1047h, then output over a combining mark or other grapheme cluster). The default libghostty-vt renderer (`snapshot` and `wait`), `record export --format svg` and `record export --format asciicast` do not use ghostty-web."; const PAGE_CRASH_PATTERN = /Target crashed/u; diff --git a/src/replay/README.md b/src/replay/README.md index e23fcddb..33dc3bbe 100644 --- a/src/replay/README.md +++ b/src/replay/README.md @@ -15,7 +15,7 @@ - `run` must be a function. `sessionDir` must be a non-empty absolute path. The session ID is `basename(sessionDir)` and must be non-empty. [offlineReplay.ts:withOfflineReplayRenderer] [offlineReplay.ts:getSessionId] - The manifest must exist. A missing manifest fails an `invariant`. [offlineReplay.ts:withOfflineReplayRenderer] - The default renderer is `DEFAULT_RENDERER_NAME`, checked with `resolveRendererName` (both from `src/renderer/names.ts`). The default profile is `'reference-dark'`, resolved with `resolveProfile` (from `src/renderer/profiles.ts`). The default backend factory is `createRendererBackend` (from `src/renderer/registry.ts`). [offlineReplay.ts:withOfflineReplayRenderer] [offlineReplay.ts:createBackend] -- A missing event log counts as zero events. Other event-log read errors, replay-input errors, profile errors and boot or replay errors become a `CliError` with code `REPLAY_ERROR` (from `src/protocol/errors.ts`). When the cause is a `GhosttyWebCrashedError`, its message follows the fixed message. A `GhosttyWebCrashedError` that the callback throws gets the same code and message too: the libghostty-vt screenshot boots a ghostty-web page inside the callback [offlineReplay.ts:withOfflineReplayRenderer]. A live host gives the same code for the same crash (`src/host/renderer.ts`). A log over the size limit gives a message that names its size and the limit, with `eventLogPath`, `eventLogBytes` and `maxEventLogBytes` in `details`. [offlineReplay.ts:readOfflineReplayInput] [offlineReplay.ts:withOfflineReplayRenderer] +- A missing event log counts as zero events. Other event-log read errors, replay-input errors, profile errors and boot or replay errors become a `CliError` with code `REPLAY_ERROR` (from `src/protocol/errors.ts`). The message of a `GhosttyWebCrashedError` follows the fixed message after a period. The message of any other boot or replay error follows it after a colon, cut to its first line and at most `MAX_ERROR_SUMMARY_CHARS` (300) characters by `summarizeError` (`src/util/errorSummary.ts`), so it holds no stack frame. A `GhosttyWebCrashedError` that the callback throws gets the same code and message too: the libghostty-vt screenshot boots a ghostty-web page inside the callback [offlineReplay.ts:withOfflineReplayRenderer]. A live host gives the same code for the same crash (`src/host/renderer.ts`). A log over the size limit gives a message that names its size and the limit, with `eventLogPath`, `eventLogBytes` and `maxEventLogBytes` in `details`. [offlineReplay.ts:readOfflineReplayInput] [offlineReplay.ts:withOfflineReplayRenderer] - `backend.replayTo` always runs, also for an empty Event Log (`targetSeq` -1). [offlineReplay.ts:withOfflineReplayRenderer] - After the backend is created, `backend.dispose()` runs in a `finally` block, on success and on failure. [offlineReplay.ts:withOfflineReplayRenderer] - `captureGridFrames` gives one blank frame with `capturedAtSeq` -1 for an empty event log and boots no backend. Mode `final` ignores event timing. Mode `timeline` fails with `EXPORT_ERROR` when any event has an earlier timestamp than the event before it. It also fails with `EXPORT_ERROR` when the `libghostty-vt` backend cannot boot, or when the retained cells pass `defaultMaxGridCells` of the V8 heap limit (at most `MAX_ANIMATED_GRID_CELLS`). [gridFrames.ts:captureGridFrames] diff --git a/src/replay/offlineReplay.ts b/src/replay/offlineReplay.ts index a9f78beb..f942a756 100644 --- a/src/replay/offlineReplay.ts +++ b/src/replay/offlineReplay.ts @@ -21,6 +21,7 @@ import type { RenderProfileConfig, ReplayInput } from '../renderer/types.js'; import { readManifestIfExists } from '../storage/manifests.js'; import { eventLogPath, manifestPath } from '../storage/sessionPaths.js'; import { invariant } from '../util/assert.js'; +import { summarizeError } from '../util/errorSummary.js'; export interface OfflineReplayDeps { backendFactory?: ( @@ -132,11 +133,15 @@ async function readOfflineReplayInput( } } +// The message names the failure that stopped the renderer, so a person does not +// need the stack. A crash of the ghostty-web page carries its own explanation. function replayRendererError(sessionId: string, error: unknown): CliError { + const reason = + error instanceof GhosttyWebCrashedError + ? `. ${error.message}` + : `: ${summarizeError(error)}`; return makeCliError(ERROR_CODES.REPLAY_ERROR, { - message: `Failed to boot or replay renderer for session ${sessionId}.${ - error instanceof GhosttyWebCrashedError ? ` ${error.message}` : '' - }`, + message: `Failed to boot or replay renderer for session ${sessionId}${reason}`, cause: error, }); } diff --git a/src/util/README.md b/src/util/README.md index 1cd93a17..71580d49 100644 --- a/src/util/README.md +++ b/src/util/README.md @@ -17,6 +17,7 @@ Small shared helpers that the rest of `src/` imports: fail-fast assertions, abor - `loadPackageMetadata()` and `PackageMetadata`: `{ name, version }` from the root `package.json`. `loadSupportedNodeRange()`: its `engines.node` range. [packageMetadata.ts:loadPackageMetadata] [packageMetadata.ts:loadSupportedNodeRange] - `satisfiesNodeRange(version, range)`: true when the Node version meets every space-separated `>=x[.y[.z]]` and ` line.replace(/\s+/gu, ' ').trim()) + .find((line) => line.length > 0); + const summary = + firstLine ?? (error instanceof Error ? error.name : 'unknown error'); + if (summary.length <= MAX_ERROR_SUMMARY_CHARS) { + return summary; + } + const kept = summary.slice(0, MAX_ERROR_SUMMARY_CHARS - ELLIPSIS.length); + // Do not cut a surrogate pair in half. + const lastCode = kept.charCodeAt(kept.length - 1); + const whole = + lastCode >= 0xd800 && lastCode <= 0xdbff ? kept.slice(0, -1) : kept; + return `${whole}${ELLIPSIS}`; +} diff --git a/test/fixtures/inject-replay-failure.ts b/test/fixtures/inject-replay-failure.ts new file mode 100644 index 00000000..ff737a0f --- /dev/null +++ b/test/fixtures/inject-replay-failure.ts @@ -0,0 +1,58 @@ +import { appendFileSync } from 'node:fs'; +import process from 'node:process'; + +// Makes every ghostty-web replay of the process fail, and counts the calls +// that the host makes to its renderer. It runs in the host and in a CLI +// process alike. +// AGENT_TTY_TEST_RENDER_CALL_LOG= appends one line to the file for +// each `HostRendererManager.withBackend` call, before it runs. A render +// poll of `wait` is one call. +// AGENT_TTY_TEST_REPLAY_FAILURE=crash rejects each `replayTo` and +// `replayWithTiming` call with the error of a crashed page +// (`GhosttyWebCrashedError`). +// AGENT_TTY_TEST_REPLAY_FAILURE=plain rejects each of those calls with the +// error that Playwright gives for a thrown RangeError: the cause on the +// first line, then the stack frames. +// Without them a call runs as it does without the fixture. +const { register } = await import('tsx/esm/api'); +register(); +const { GhosttyWebBackend, GhosttyWebCrashedError } = + await import('../../src/renderer/ghosttyWeb/index.js'); +const { HostRendererManager } = await import('../../src/host/renderer.js'); + +const callLog = process.env.AGENT_TTY_TEST_RENDER_CALL_LOG; +const failure = process.env.AGENT_TTY_TEST_REPLAY_FAILURE; + +if (callLog !== undefined) { + // oxlint-disable-next-line typescript/unbound-method -- the patch below calls it with original.apply(this, ...). + const original = HostRendererManager.prototype.withBackend; + HostRendererManager.prototype.withBackend = function ( + this: unknown, + ...args: unknown[] + ) { + appendFileSync(callLog, 'withBackend\n'); + return (original as (...rest: unknown[]) => unknown).apply(this, args); + } as typeof original; +} + +function replayFailure(): Error { + if (failure === 'crash') { + return new GhosttyWebCrashedError( + new Error('page.evaluate: Target crashed '), + ); + } + return new Error( + [ + 'page.evaluate: RangeError: offset is out of bounds', + ' at Terminal.write (http://127.0.0.1:1/assets/ghostty-web.js:1:1)', + ' at writeBatch (http://127.0.0.1:1/index.html:2:2)', + ].join('\n'), + ); +} + +if (failure === 'crash' || failure === 'plain') { + for (const method of ['replayTo', 'replayWithTiming'] as const) { + GhosttyWebBackend.prototype[method] = (() => + Promise.reject(replayFailure())) as never; + } +} diff --git a/test/integration/ghostty-web-crash.test.ts b/test/integration/ghostty-web-crash.test.ts index 5a6cbc77..be96c3e3 100644 --- a/test/integration/ghostty-web-crash.test.ts +++ b/test/integration/ghostty-web-crash.test.ts @@ -1,12 +1,13 @@ -// KNOWN-BUG TESTS. They pin how agent-tty reports a ghostty-web 0.4.0 fault -// (see src/renderer/ghosttyWeb/crashError.ts). Upstream issue: +// KNOWN-BUG TESTS. They pin how agent-tty reports ghostty-web 0.4.0 faults +// (see src/renderer/ghosttyWeb/crashError.ts). Upstream issue of one of them: // https://github.com/coder/ghostty-web/issues/215. When a ghostty-web release -// fixes it and agent-tty upgrades to it, delete this file, or invert it to +// fixes them and agent-tty upgrades to it, delete this file, or invert it to // expect a screenshot. -import { mkdtemp, realpath } from 'node:fs/promises'; +import { mkdtemp, readFile, realpath } from 'node:fs/promises'; import { tmpdir } from 'node:os'; -import { join } from 'node:path'; +import { join, resolve } from 'node:path'; import process from 'node:process'; +import { pathToFileURL } from 'node:url'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; @@ -27,6 +28,10 @@ const CLI_TIMEOUT_MS = 60_000; const CRASH_OUTPUT = 'a\\u0301\\u001bc\\u001b[?47ho'; const WRITE_CRASH_OUTPUT = `process.stdout.write('${CRASH_OUTPUT}');`; const hasLibghosttyVt = (await probeLibghosttyVt()).available; +// 693 lines of five combining marks and 75 plain columns. It has no reset, no +// resize and no alternate screen, and it crashes the page too. +const WRITE_PRINT_CRASH_OUTPUT = + "process.stdout.write(('e\\u0301'.repeat(5) + 'abcdefghij'.repeat(7) + 'abcde' + '\\r\\n').repeat(693));"; const CRASH_EXPLANATION = "ghostty-web crashed while it replayed this session's output."; @@ -92,6 +97,79 @@ describe.skipIf(process.platform !== 'linux')( expect(envelope.result.visibleLines[0]?.text).toBe('o'); }); + // Counts the host's calls to its renderer, one for each render poll. + function renderCallLogEnv(renderCallLog: string): Record { + const preload = pathToFileURL( + resolve('test/fixtures/inject-replay-failure.ts'), + ); + return { + NODE_OPTIONS: [ + process.env.NODE_OPTIONS ?? '', + `--import=${preload.href}`, + ].join(' '), + AGENT_TTY_TEST_RENDER_CALL_LOG: renderCallLog, + }; + } + + async function countRenderCalls(renderCallLog: string): Promise { + const text = await readFile(renderCallLog, 'utf8').catch(() => ''); + return text.split('\n').filter((line) => line.length > 0).length; + } + + it('names the crash of an input that has no reset, and ends a live ghostty-web wait at it', async () => { + const renderCallLog = join(testHome, 'render-calls.log'); + sessionId = createSession( + testHome, + [ + process.execPath, + '-e', + `${WRITE_PRINT_CRASH_OUTPUT} process.stdin.resume();`, + ], + { env: renderCallLogEnv(renderCallLog) }, + ); + const env = { AGENT_TTY_HOME: testHome }; + + const snapshot = runCli( + ['snapshot', sessionId, '--renderer', 'ghostty-web', '--json'], + env, + CLI_TIMEOUT_MS, + ); + expect(snapshot.status).toBe(10); + const snapshotError = parseError(snapshot.stdout); + expect(snapshotError.code).toBe('REPLAY_ERROR'); + expect(snapshotError.message).toContain(CRASH_EXPLANATION); + expect(snapshotError.message).toContain('several different inputs'); + expect(snapshotError.message).toContain( + 'https://github.com/coder/ghostty-web/issues/215', + ); + expect(snapshotError.message).toContain('Target crashed'); + + // The wait gives the same error as the snapshot. It does not poll the + // crashing page again: each poll replays the log into a new page. + const callsBeforeWait = await countRenderCalls(renderCallLog); + const waited = runCli( + [ + 'wait', + sessionId, + '--renderer', + 'ghostty-web', + '--text', + 'NEVER', + '--timeout', + '60000', + '--json', + ], + env, + CLI_TIMEOUT_MS, + ); + expect(waited.status).toBe(10); + const waitError = parseError(waited.stdout); + expect(waitError.code).toBe('REPLAY_ERROR'); + expect(waitError.retryable).toBe(false); + expect(waitError.message).toBe(snapshotError.message); + expect((await countRenderCalls(renderCallLog)) - callsBeforeWait).toBe(1); + }); + it('names the crash in the replay and export errors of an exited session', () => { sessionId = createSession(testHome, [ process.execPath, diff --git a/test/integration/renderer-failure-cause.test.ts b/test/integration/renderer-failure-cause.test.ts new file mode 100644 index 00000000..5520ef51 --- /dev/null +++ b/test/integration/renderer-failure-cause.test.ts @@ -0,0 +1,135 @@ +import { mkdtemp, realpath } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import process from 'node:process'; +import { pathToFileURL } from 'node:url'; + +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; + +import { + cleanupHome, + createSession, + destroySession, + runCli, +} from '../helpers.js'; + +const CLI_TIMEOUT_MS = 60_000; +// The fixture makes each ghostty-web replay fail with the error that Playwright +// gives for a RangeError of the page: the cause, then stack frames. +const CAUSE = 'page.evaluate: RangeError: offset is out of bounds'; + +interface ErrorEnvelope { + ok: false; + error: { code: string; message: string; retryable: boolean }; +} + +function parseError(stdout: string): ErrorEnvelope['error'] { + const envelope = JSON.parse(stdout) as ErrorEnvelope; + expect(envelope.ok).toBe(false); + return envelope.error; +} + +// A failure of the ghostty-web renderer that is not a page crash must name its +// cause in the message of the error, for every command that replays the log of +// a session that has exited. +describe('cause of a ghostty-web failure on an exited session', () => { + let testHome = ''; + let sessionId = ''; + let env: Record = {}; + + beforeAll(async () => { + // oxfmt-ignore + testHome = await realpath(await mkdtemp(join(tmpdir(), 'agent-tty-failure-cause-'))); + sessionId = createSession(testHome, ['/bin/sh', '-c', 'echo done']); + const exited = runCli( + ['wait', sessionId, '--exit', '--timeout', '20000', '--json'], + { AGENT_TTY_HOME: testHome }, + CLI_TIMEOUT_MS, + ); + expect(exited.status).toBe(0); + + const preload = pathToFileURL( + resolve('test/fixtures/inject-replay-failure.ts'), + ); + env = { + AGENT_TTY_HOME: testHome, + NODE_OPTIONS: [ + process.env.NODE_OPTIONS ?? '', + `--import=${preload.href}`, + ].join(' '), + AGENT_TTY_TEST_REPLAY_FAILURE: 'plain', + }; + }, 120_000); + + afterAll(async () => { + destroySession(testHome, sessionId); + await cleanupHome(testHome); + sessionId = ''; + testHome = ''; + }); + + it.each([ + ['snapshot', ['snapshot', '--renderer', 'ghostty-web']], + ['screenshot', ['screenshot', '--renderer', 'ghostty-web']], + [ + 'wait', + [ + 'wait', + '--renderer', + 'ghostty-web', + '--text', + 'NEVER', + '--timeout', + '0', + ], + ], + ])( + 'names the cause in the REPLAY_ERROR of an offline %s', + { timeout: 120_000 }, + (_name, args) => { + const [command, ...rest] = args; + const result = runCli( + [command as string, sessionId, ...rest, '--json'], + env, + CLI_TIMEOUT_MS, + ); + + expect(result.status, result.stderr).toBe(10); + const error = parseError(result.stdout); + expect(error.code).toBe('REPLAY_ERROR'); + expect(error.retryable).toBe(false); + // The message ends at the cause: it holds no stack frame. + expect(error.message).toBe( + `Failed to boot or replay renderer for session ${sessionId}: ${CAUSE}`, + ); + }, + ); + + it( + 'names the cause in the EXPORT_ERROR of a WebM export', + { timeout: 120_000 }, + () => { + const result = runCli( + [ + 'record', + 'export', + sessionId, + '--format', + 'webm', + '--out', + join(testHome, 'failed.webm'), + '--json', + ], + env, + CLI_TIMEOUT_MS, + ); + + expect(result.status, result.stderr).toBe(7); + const error = parseError(result.stdout); + expect(error.code).toBe('EXPORT_ERROR'); + expect(error.message).toBe( + `Failed to export session "${sessionId}" as webm: ${CAUSE}`, + ); + }, + ); +}); diff --git a/test/integration/wait-render.test.ts b/test/integration/wait-render.test.ts index 8ee02a5d..6db34da3 100644 --- a/test/integration/wait-render.test.ts +++ b/test/integration/wait-render.test.ts @@ -1,4 +1,4 @@ -import { mkdtemp, realpath } from 'node:fs/promises'; +import { mkdtemp, readFile, realpath } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join, resolve } from 'node:path'; import process from 'node:process'; @@ -6,6 +6,7 @@ import { pathToFileURL } from 'node:url'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { MAX_CONSECUTIVE_POLL_FAILURES } from '../../src/host/hostMain.js'; import { sendRpc } from '../../src/host/rpcClient.js'; import type { SnapshotResult, @@ -611,6 +612,104 @@ describe('wait render integration', { timeout: 120_000 }, () => { } }); + // The fixture makes each ghostty-web replay of the host fail and counts the + // host's calls to its renderer. Each render poll is one call. + function injectedReplayFailureEnv( + failure: 'crash' | 'plain', + renderCallLog: string, + ): Record { + const preload = pathToFileURL( + resolve('test/fixtures/inject-replay-failure.ts'), + ); + return { + NODE_OPTIONS: [ + process.env.NODE_OPTIONS ?? '', + `--import=${preload.href}`, + ].join(' '), + AGENT_TTY_TEST_REPLAY_FAILURE: failure, + AGENT_TTY_TEST_RENDER_CALL_LOG: renderCallLog, + }; + } + + async function countRenderCalls(renderCallLog: string): Promise { + const text = await readFile(renderCallLog, 'utf8').catch(() => ''); + return text.split('\n').filter((line) => line.length > 0).length; + } + + it('ends a render wait at the first poll that crashes the ghostty-web page', async () => { + const renderCallLog = join(testHome, 'crash-render-calls.log'); + const crashedSessionId = createSession(testHome, undefined, { + env: injectedReplayFailureEnv('crash', renderCallLog), + }); + try { + const result = runCli( + [ + '--renderer', + 'ghostty-web', + 'wait', + crashedSessionId, + '--text', + 'NEVER', + '--timeout', + '60000', + '--json', + ], + { AGENT_TTY_HOME: testHome }, + 90_000, + ); + + expect(result.exitCode, result.stderr).toBe(10); + const envelope = JSON.parse(result.stdout) as ErrorEnvelope & { + result?: unknown; + }; + expect(envelope.error).toMatchObject({ + code: 'REPLAY_ERROR', + retryable: false, + }); + expect(envelope.error.message).toContain( + "ghostty-web crashed while it replayed this session's output.", + ); + expect(envelope).not.toHaveProperty('result'); + // The wait does not poll again after the crash. + expect(await countRenderCalls(renderCallLog)).toBe(1); + } finally { + destroySession(testHome, crashedSessionId); + } + }); + + it('retries a render poll that fails for another reason until the cap', async () => { + const renderCallLog = join(testHome, 'plain-render-calls.log'); + const failingSessionId = createSession(testHome, undefined, { + env: injectedReplayFailureEnv('plain', renderCallLog), + }); + try { + const result = runCli( + [ + '--renderer', + 'ghostty-web', + 'wait', + failingSessionId, + '--text', + 'NEVER', + '--timeout', + '60000', + '--json', + ], + { AGENT_TTY_HOME: testHome }, + 90_000, + ); + + expect(result.exitCode, result.stderr).toBe(9); + const envelope = JSON.parse(result.stdout) as ErrorEnvelope; + expect(envelope.error.code).toBe('RPC_ERROR'); + expect(await countRenderCalls(renderCallLog)).toBe( + MAX_CONSECUTIVE_POLL_FAILURES, + ); + } finally { + destroySession(testHome, failingSessionId); + } + }); + it('keeps polling through fewer failed render polls than the cap and matches', () => { const marker = 'renderer-recovered'; const recoveringSessionId = createSession( diff --git a/test/unit/commands/record-export.test.ts b/test/unit/commands/record-export.test.ts index 0d366c00..1d15a45e 100644 --- a/test/unit/commands/record-export.test.ts +++ b/test/unit/commands/record-export.test.ts @@ -1736,9 +1736,40 @@ describe('record export command', () => { expect((failure as { cause?: unknown }).cause).toBe(stall); }); - it('keeps the generic message for other WebM export failures', async () => { + it('names the cause of other WebM export failures', async () => { mocks.recordingFilename.mockReturnValue('recording-1-webm.webm'); - mocks.generateWebmExport.mockRejectedValue(new Error('replay failed')); + const replayError = new Error('replay failed'); + mocks.generateWebmExport.mockRejectedValue(replayError); + + const failure: unknown = await runRecordExportCommand({ + context: TEST_CONTEXT, + json: true, + sessionId: 'session-01', + format: 'webm', + }).then( + () => undefined, + (error: unknown) => error, + ); + + expect(failure).toMatchObject({ + code: ERROR_CODES.EXPORT_ERROR, + message: 'Failed to export session "session-01" as webm: replay failed', + cause: replayError, + }); + expect(mocks.generateWebmExport).toHaveBeenCalledTimes(1); + }); + + // Playwright puts the stack after the cause of a page error. + it('keeps the first line of a WebM export failure and leaves out its stack', async () => { + mocks.recordingFilename.mockReturnValue('recording-1-webm.webm'); + mocks.generateWebmExport.mockRejectedValue( + new Error( + [ + 'page.evaluate: RangeError: offset is out of bounds', + ' at Terminal.write (http://127.0.0.1:41233/assets/ghostty-web.js:1:2)', + ].join('\n'), + ), + ); await expect( runRecordExportCommand({ @@ -1749,12 +1780,12 @@ describe('record export command', () => { }), ).rejects.toMatchObject({ code: ERROR_CODES.EXPORT_ERROR, - message: 'Failed to export session "session-01" as webm.', + message: + 'Failed to export session "session-01" as webm: page.evaluate: RangeError: offset is out of bounds', }); - expect(mocks.generateWebmExport).toHaveBeenCalledTimes(1); }); - it('keeps the generic message for other event log read failures', async () => { + it('names the cause of other event log read failures', async () => { mocks.readEventLogRecords.mockRejectedValue(new Error('EIO')); await expect( @@ -1766,7 +1797,7 @@ describe('record export command', () => { }), ).rejects.toMatchObject({ code: ERROR_CODES.EXPORT_ERROR, - message: 'Failed to export session "session-01" as asciicast.', + message: 'Failed to export session "session-01" as asciicast: EIO', }); }); diff --git a/test/unit/host/renderer.test.ts b/test/unit/host/renderer.test.ts index de48c9fd..7e477ab6 100644 --- a/test/unit/host/renderer.test.ts +++ b/test/unit/host/renderer.test.ts @@ -5,8 +5,12 @@ import { setImmediate as setImmediatePromise } from 'node:timers/promises'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { HostRendererManager } from '../../../src/host/renderer.js'; +import { + HostRendererManager, + isReplayCrashError, +} from '../../../src/host/renderer.js'; import { CliError } from '../../../src/cli/errors.js'; +import { ERROR_CODES, makeCliError } from '../../../src/protocol/errors.js'; import { GhosttyWebCrashedError } from '../../../src/renderer/ghosttyWeb/index.js'; import type { RendererBackend } from '../../../src/renderer/backend.js'; import { iterateInRangeReplayEvents } from '../../../src/renderer/replayEvents.js'; @@ -347,6 +351,45 @@ describe('HostRendererManager', () => { }); }); + // `waitForRender` ends its poll loop at this error and retries every other. + it('tells the error of a crashed page from every other poll failure', async () => { + const manager = new HostRendererManager({ + sessionId: 'session-01', + sessionDir, + backendFactory, + }); + const crash = new GhosttyWebCrashedError( + new Error('page.evaluate: Target crashed '), + ); + backendFactory.mockImplementationOnce(() => { + const backend = createFakeBackend(); + backend.replayTo = vi.fn( + (): Promise => Promise.reject(crash), + ); + backends.push(backend); + return backend; + }); + const crashFailure: unknown = await manager + .getBackend('ghostty-web', createProfile(), createReplayInput()) + .catch((error: unknown) => error); + + expect(isReplayCrashError(crashFailure)).toBe(true); + // The errors of the other ways in which a poll fails. + expect(isReplayCrashError(crash)).toBe(false); + expect( + isReplayCrashError(new Error('page.evaluate: Target crashed ')), + ).toBe(false); + expect( + isReplayCrashError( + makeCliError(ERROR_CODES.REPLAY_ERROR, { message: 'replay failed' }), + ), + ).toBe(false); + expect( + isReplayCrashError(makeCliError(ERROR_CODES.RPC_ERROR, { cause: crash })), + ).toBe(false); + expect(isReplayCrashError('Target crashed')).toBe(false); + }); + it('passes every other renderer failure through unchanged', async () => { const manager = new HostRendererManager({ sessionId: 'session-01', diff --git a/test/unit/renderer/ghosttyWebCrash.test.ts b/test/unit/renderer/ghosttyWebCrash.test.ts index 90cb6fdc..10c685d2 100644 --- a/test/unit/renderer/ghosttyWebCrash.test.ts +++ b/test/unit/renderer/ghosttyWebCrash.test.ts @@ -56,6 +56,27 @@ describe('describeReplayFailure', () => { expect(crash.message).toContain('(page.evaluate: Target crashed)'); }); + // The message must be true for every crash. An input without a full reset + // crashes the page too, so the reset of + // https://github.com/coder/ghostty-web/issues/215 is one known cause and + // not the cause. + it('names the issue as one known cause and says that other inputs crash the page', () => { + const crash = describeReplayFailure(CRASHED) as GhosttyWebCrashedError; + + expect(crash.message).toContain( + 'One known cause is https://github.com/coder/ghostty-web/issues/215', + ); + expect(crash.message).toContain('several different inputs'); + }); + + it('names the commands that do not use ghostty-web', () => { + const crash = describeReplayFailure(CRASHED) as GhosttyWebCrashedError; + + expect(crash.message).toContain('libghostty-vt'); + expect(crash.message).toContain('`record export --format svg`'); + expect(crash.message).toContain('`record export --format asciicast`'); + }); + // Real Playwright and harness messages that are not a crash. A looser // pattern (`/Target/`, `/crash/i`, `/crashed/`, or one that adds the // closed-page text) would call them one and release a healthy page. diff --git a/test/unit/replay/offlineReplay.test.ts b/test/unit/replay/offlineReplay.test.ts index b65142ab..bb8997a6 100644 --- a/test/unit/replay/offlineReplay.test.ts +++ b/test/unit/replay/offlineReplay.test.ts @@ -20,6 +20,7 @@ import { eventLogPath, manifestPath, } from '../../../src/storage/sessionPaths.js'; +import { MAX_ERROR_SUMMARY_CHARS } from '../../../src/util/errorSummary.js'; interface OfflineReplayRunContext { manifest: SessionRecord; @@ -683,11 +684,10 @@ describe('withOfflineReplayRenderer', () => { expect(backend.disposed).toBe(true); }); - it('wraps replayTo errors as REPLAY_ERROR and disposes the backend', async () => { - const { sessionDir } = await createSessionFixture(); - const backend = createMockBackend({ - replayError: new Error('replay failed'), - }); + it('wraps replayTo errors as REPLAY_ERROR that names the cause, and disposes the backend', async () => { + const { sessionDir, sessionId } = await createSessionFixture(); + const replayError = new Error('replay failed'); + const backend = createMockBackend({ replayError }); const replayPromise = withOfflineReplayRenderer( { sessionDir }, @@ -698,12 +698,60 @@ describe('withOfflineReplayRenderer', () => { await expect(replayPromise).rejects.toBeInstanceOf(CliError); await expect(replayPromise).rejects.toMatchObject({ code: ERROR_CODES.REPLAY_ERROR, + message: `Failed to boot or replay renderer for session ${sessionId}: replay failed`, + cause: replayError, }); expect(backend.booted).toBe(true); expect(backend.replayedInput?.targetSeq).toBe(2); expect(backend.disposed).toBe(true); }); + // Playwright puts the stack after the cause. It is long, and it names source + // files, so the message keeps the first line only. + it('leaves the stack of a replay error out of the message', async () => { + const { sessionDir, sessionId } = await createSessionFixture(); + const replayError = new Error( + [ + 'page.evaluate: RangeError: offset is out of bounds', + ' at Terminal.write (http://127.0.0.1:41233/assets/ghostty-web.js:1:2)', + ].join('\n'), + ); + const backend = createMockBackend({ replayError }); + + const failure = await withOfflineReplayRenderer( + { sessionDir }, + () => Promise.resolve('unreachable'), + { backendFactory: () => backend }, + ).catch((error: unknown) => error); + + expect(failure).toBeInstanceOf(CliError); + expect((failure as CliError).message).toBe( + `Failed to boot or replay renderer for session ${sessionId}: page.evaluate: RangeError: offset is out of bounds`, + ); + }); + + it('bounds the length of the cause of a replay error', async () => { + const { sessionDir, sessionId } = await createSessionFixture(); + const backend = createMockBackend({ + replayError: new Error(`page.evaluate: RangeError: ${'x'.repeat(2000)}`), + }); + + const failure = await withOfflineReplayRenderer( + { sessionDir }, + () => Promise.resolve('unreachable'), + { backendFactory: () => backend }, + ).catch((error: unknown) => error); + + expect(failure).toBeInstanceOf(CliError); + const { message } = failure as CliError; + const prefix = `Failed to boot or replay renderer for session ${sessionId}: `; + expect(message.startsWith(`${prefix}page.evaluate: RangeError: xxx`)).toBe( + true, + ); + expect(message.endsWith('…')).toBe(true); + expect(message).toHaveLength(prefix.length + MAX_ERROR_SUMMARY_CHARS); + }); + it('defaults replay state to the last event seq when no custom target is provided', async () => { const expectedEvents: EventRecord[] = Array.from( { length: 6 }, @@ -754,8 +802,8 @@ describe('withOfflineReplayRenderer', () => { expect(backend.disposed).toBe(true); }); - it('wraps backend boot failures as REPLAY_ERROR and disposes the backend', async () => { - const { sessionDir } = await createSessionFixture(); + it('wraps backend boot failures as REPLAY_ERROR that names the cause, and disposes the backend', async () => { + const { sessionDir, sessionId } = await createSessionFixture(); const backend = createMockBackend({ bootError: new Error('boot failed') }); const replayPromise = withOfflineReplayRenderer( @@ -767,6 +815,7 @@ describe('withOfflineReplayRenderer', () => { await expect(replayPromise).rejects.toBeInstanceOf(CliError); await expect(replayPromise).rejects.toMatchObject({ code: ERROR_CODES.REPLAY_ERROR, + message: `Failed to boot or replay renderer for session ${sessionId}: boot failed`, }); expect(backend.booted).toBe(true); expect(backend.disposed).toBe(true); diff --git a/test/unit/util/errorSummary.test.ts b/test/unit/util/errorSummary.test.ts new file mode 100644 index 00000000..cc89dca2 --- /dev/null +++ b/test/unit/util/errorSummary.test.ts @@ -0,0 +1,65 @@ +import { describe, expect, it } from 'vitest'; + +import { + MAX_ERROR_SUMMARY_CHARS, + summarizeError, +} from '../../../src/util/errorSummary.js'; + +describe('summarizeError', () => { + it('gives the message of an error', () => { + expect(summarizeError(new Error('boot failed'))).toBe('boot failed'); + }); + + it('keeps the first line and drops the stack frames and the call log', () => { + const error = new Error( + [ + 'page.evaluate: RangeError: offset is out of bounds', + ' at Terminal.write (http://127.0.0.1:41233/assets/ghostty-web.js:1:2)', + ' at writeBatch (file:///home/user/agent-tty/index.html:2:3)', + ].join('\n'), + ); + + expect(summarizeError(error)).toBe( + 'page.evaluate: RangeError: offset is out of bounds', + ); + }); + + it('skips blank lines before the first line and collapses whitespace', () => { + expect( + summarizeError(new Error('\r\n \n page\t crashed badly \n')), + ).toBe('page crashed badly'); + }); + + it('cuts a long line to the limit and ends it with an ellipsis', () => { + const summary = summarizeError(new Error('x'.repeat(5000))); + + expect(summary).toHaveLength(MAX_ERROR_SUMMARY_CHARS); + expect(summary).toBe(`${'x'.repeat(MAX_ERROR_SUMMARY_CHARS - 1)}…`); + }); + + it('keeps a line that is exactly at the limit', () => { + const line = 'y'.repeat(MAX_ERROR_SUMMARY_CHARS); + + expect(summarizeError(new Error(line))).toBe(line); + }); + + it('does not cut a surrogate pair in half', () => { + // The pair starts at the last character that the cut would keep. + const text = `${'z'.repeat(MAX_ERROR_SUMMARY_CHARS - 2)}😀😀`; + + const summary = summarizeError(new Error(text)); + + expect(summary).toBe(`${'z'.repeat(MAX_ERROR_SUMMARY_CHARS - 2)}…`); + expect(summary).not.toMatch(/[\ud800-\udbff](?![\udc00-\udfff])/u); + }); + + it('gives the name of an error without a message', () => { + expect(summarizeError(new RangeError(''))).toBe('RangeError'); + }); + + it('gives the text of a value that is not an error', () => { + expect(summarizeError('plain text\nsecond line')).toBe('plain text'); + expect(summarizeError(42)).toBe('42'); + expect(summarizeError(undefined)).toBe('undefined'); + }); +});