Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat(frontend): unfold and copy a statement in the task-run log

zchpeterc653a91a6f16
diff --git a/docs/design/task-run-log-statement-unfold.md b/docs/design/task-run-log-statement-unfold.md
index 48e88c0900..f266ffc538 100644
--- a/docs/design/task-run-log-statement-unfold.md
+++ b/docs/design/task-run-log-statement-unfold.md
@@ -1,6 +1,6 @@
# Task-run log — a statement is a payload, not a line
-Status: proposal · 2026-09-11 (revised 2026-09-16)
+Status: proposal · 2026-09-11 (revised 2026-09-21)
The task-run log cuts every executed statement to 80 characters and appends `...`. For the
statements customers actually run — SDL, or a `CREATE TABLE` with a few hundred columns — the row
@@ -80,7 +80,8 @@ What follows from it:
the only thing that knows how much fits.
- The line is the news: the error when the command failed, the statement when it did not.
- Unfolding always reveals the statement, and so does copy. One meaning per control, on every row.
-- Whether a row starts unfolded says what the row is *for*, not how long it is.
+- Nothing starts unfolded. The row that explains the outcome is brought into view; opening it is
+ the reader's move, and a toggle never moves the line that was clicked.
## Decisions
@@ -92,7 +93,7 @@ key: string; // the entry's identity, not its position — see D14
detail: string; // the text the row shows
statement?: string; // the statement this row ran, as the sheet stored it
error?: string; // the error the command returned
-defaultOpen?: boolean // this is the row D4 picked; the mark D13 and D14 speak of
+marked?: boolean // the row D4 picked: the failure D13 brings into view
```
`key` is listed because its contents change even though the field does not. It is the only
@@ -106,18 +107,17 @@ types that carry status words rather than payloads (`BEGIN`, `Completed`, retry
`detail` alone, which is what makes `statement` and `error` the test for both controls below.
A failure whose statement could not be recovered — no `statement`, no usable `range`, or a sheet
-that came back partial — still gets marked, because the mark's first job is to say *this is the row
-that explains the outcome*, and D13 has to render and scroll to it or the error itself stays hidden
-behind *Load more*. What it does not get is a taller section: D8's cap answers to a block actually
-being on screen, not to the mark, and there is no block here. Opening such a row is a no-op, which
-is why D5 gives it no control to open with.
+that came back partial — still gets marked, because the mark's job is to say *this is the row that
+explains the outcome*, and D13 has to render and scroll to it or the error itself stays hidden
+behind *Load more*. What it does not get is a fold control: there is no block to reveal, so D5
+gives it nothing to open with.
-`defaultOpen` is the fourth, and it exists because the view cannot work it out. D4's pick is made
+`marked` is the fourth, and it exists because the view cannot work it out. D4's pick is made
across a whole execution context, and `SectionContent` sees one section at a time; nor can it infer
-the pick from `error`, since every transient failed attempt carries one and opening all of them is
-the thing D4 exists to prevent. So `buildSectionsFromEntries` decides and marks the row it chose,
-and everything downstream — D13's render window, D14's derived open set — reads that flag rather
-than re-deriving a judgement it lacks the inputs for.
+the pick from `error`, since every transient failed attempt carries one and surfacing the first of
+them is the thing D4 exists to prevent. So `buildSectionsFromEntries` decides and marks the row it
+chose, and D13's render window and scroll read that flag rather than re-deriving a judgement they
+lack the inputs for.
**D2 · Truncation moves to CSS.** The row's line renders under `truncate`; the 80-character
`substring` is deleted. A wide screen shows more of the statement and a narrow sheet shows less,
@@ -132,50 +132,57 @@ never anything else. Where it sits follows what it copies, because position is w
actually reads: in the row's right-hand cluster while the statement *is* the line, and in the
top-right corner of the unfolded block once the statement is a block, which is the placement every
code block on GitHub has already trained people to expect. A failed row's line is the error, so no
-copy button appears on it; that row's copy is in its block, which D4 opens by default. The error
+copy button appears on it; that row's copy is in its block, one click on the row away. The error
gets none: wanting an error in the clipboard is rare next to wanting the SQL, and it does not
justify a second control on the densest surface in the product — it stays selectable text, as it
is today. A row whose statement could not be recovered at all (no `statement`, no usable `range`,
or a sheet that came back partial) gets no copy button rather than a fallback to something else,
so the control never means two things. One meaning, one place: copy is the SQL, beside the SQL.
-**D4 · What unfolds by default says what the row is for.** A successful statement identifies
-*which* command ran; the reader scanning for the failure does not want it open, so it starts
-folded. A failed command is what the log was opened for, so it starts **unfolded**, with the error
-as its line and the statement that failed in the block beneath — but only the one that explains the
-outcome, which is not the same as every failed row. A run can hold several: on a lock timeout the
+**D4 · Nothing unfolds by default; the failure that explains the outcome is marked.** Every row
+starts folded, the failed one included. An earlier revision opened the failed command by default,
+on the reasoning that it is what the log was opened for, and in use that was wrong twice over. The
+pages that embed the viewer already show the failed task's statement directly above the log, so the
+block repeated it. And it made the reader's first act on a failed log a *fold* — of a row they had
+never opened, in a box whose cap D8 had raised and whose scroll D13 had moved — which is exactly the
+state in which a fold displaces the line being clicked (D16). The error is the news and it is
+always on the line; the statement is one click away.
+
+What the failure does get is the **mark**: D13 renders it past the *Load more* window and brings it
+into view. But only the failure that explains the outcome, which is not the same as every failed
+row. A run can hold several: on a lock timeout the
Postgres driver retries the whole command list up to `MaximumRetries`
(`backend/plugin/db/pg/pg.go:463-485`), re-logging every command on each attempt, so the same
-statement can fail three times and the run still succeed. Opening all of them would expand the same
-DDL three times over.
+statement can fail three times and the run still succeed. Marking all of them would bring the first
+attempt into view, not the outcome.
-So the rule is: **open the last failed command row in an execution context, and only when no
+So the rule is: **mark the last failed command row in an execution context, and only when no
command after it succeeded.** The context is the entry sequence `buildSectionsFromEntries` is
handed — one replica, one release file — and the test runs over that sequence *before* it is
grouped. It cannot be section-local: sections are typed groups, and `groupEntriesByType` starts a
new one whenever the entry type changes, while a retry emits a `RETRY_INFO` entry between attempts
and, in transaction mode, a rollback and a fresh begin as well. Every transient failure would
-therefore be the last failure in a section of its own, and all of them would open. Scanned across
-the context instead, a run that recovered has successful commands after its failure and opens
-nothing, while a run that really failed ends at the failure and opens exactly that row. Per
+therefore be the last failure in a section of its own, and all of them would be marked. Scanned across
+the context instead, a run that recovered has successful commands after its failure and marks
+nothing, while a run that really failed ends at the failure and marks exactly that row. Per
context, not per run, so a failure on one replica is never silenced by another replica's success.
A live log is a prefix of the finished one, so the test also treats a failure followed by a
`RETRY_INFO` entry as not terminal. The driver writes that marker before it re-runs
(`backend/plugin/db/driver.go:357-367`, called at `pg.go:470`), so the marker is the standing
signal that another attempt is coming; without it, the five-second poll
-(`useTaskRunLogData.ts:101`) landing between a failed attempt and its retry would open a failure
+(`useTaskRunLogData.ts:101`) landing between a failed attempt and its retry would mark a failure
that is about to be superseded. What remains is the ~200ms between the failure and the marker,
and that window is left open deliberately. A poll landing inside it — roughly one chance in
-twenty-five, and only for someone watching a retrying run live — opens a failure that the next
-poll folds again when the marker arrives and the mark moves off it, so the row can sit expanded for
-up to five seconds. Suppressing the mark while the run is still `RUNNING` would remove the flicker
-and take D14's entire point with it, since the case the mark exists for *is* a deploy watched from
+twenty-five, and only for someone watching a retrying run live — scrolls to a failure that the next
+poll unmarks when the marker arrives, so the view can rest on a superseded attempt for up to five
+seconds. Suppressing the mark while the run is still `RUNNING` would remove that and take the
+mark's point with it, since the case the mark exists for *is* a deploy watched from
the plan page that fails while you are looking at it. The transient state is not false either: that
command really did fail at that moment; it is only about to be tried again.
The test reads only the entries, which matters because `taskRunStatus` is an optional prop that the
changelog and revision pages do not pass. One guard uses it where it exists: when a caller passes a
-status of `DONE`, nothing is marked at all. That is cheap, it costs D14 nothing — D14 is about a run
+status of `DONE`, nothing is marked at all. That is cheap, it costs the live case nothing — that is a run
still `RUNNING` — and it covers the one shape the entries get wrong today. CockroachDB's autocommit
path logs a single `COMMAND_EXECUTE` outside its retry and a response *per attempt* from inside it
(`backend/plugin/db/cockroachdb/cockroachdb.go:485-503`), while the converter attaches the first
@@ -186,10 +193,9 @@ command that worked. The guard is opportunistic mitigation, not part of the rule
costs nothing where the prop already exists and it is not extended to where it does not. The
changelog and revision pages would need a success signal invented for them — a changelog's status
is not a task run's — to half-cover one engine's converter bug, and on those two pages that row
-**already** reads as a failure today, before this design touches it. Auto-opening makes a wrong row
-larger; it does not make it wrong. The converter fix below closes it on all four surfaces at once,
-which is why that is where it belongs. Everything else starts folded, and every row toggles either
-way.
+**already** reads as a failure today, before this design touches it. Scrolling to a wrong row makes
+it more prominent; it does not make it wrong. The converter fix below closes it on all four surfaces at once,
+which is why that is where it belongs.
**D5 · A row is foldable when unfolding would show something new.** There are two independent
reasons it would, and a row needs only one of them:
@@ -203,10 +209,10 @@ reasons it would, and a row needs only one of them:
The first is the one an implementation would most easily miss, and missing it sets a trap. A
terminal failure on something as short as `SELECT 1` satisfies neither of the other two — its
-statement has no newlines and its line, being the error, is never clamped — so the row would open
-by default under D4 and then, once the reader folded it, offer no way back: the statement and the
-copy button that lives with it are both inside the block. Fold once, lose the SQL. A row holding
-two payloads is always foldable.
+statement has no newlines and its line, being the error, is never clamped — so the row would get
+no control at all, and the statement and the copy button that lives with it, both inside the block,
+could never be reached — on exactly the row whose SQL the reader wants. A row holding two payloads
+is always foldable.
Neither covers the other. A three-line statement can collapse to a line that fits, and a one-line
statement can be far too wide; mockup E is the proof, where `SET statement_timeout TO '3600s';`
@@ -220,13 +226,12 @@ it on the rows where it matters — mockup D's row 6 is exactly that, a `COMMENT
its line and would unfold to itself.
A row that is open **and has a statement** is foldable — no measurement, no comparison. The
-statement clause is not decoration: a failure whose statement could not be recovered is still
-marked (D1) and so is nominally open, but it has no block, and an unqualified rule would hand it
-the chevron that D1 and D5 both promise it will not get. The exception exists to let a reader close
-a block that is on screen, so it reaches exactly as far as a block does. Beyond that it sounds like
+exception exists to let a reader close a block that is on screen, so it reaches exactly as far as a
+block does: an override outlives the poll it was made on, and a row whose statement can no longer
+be recovered has no block and gets no chevron. Beyond that it sounds like
a truism and is in fact the subtlest case here. A successful single-line statement qualifies only
by the clamp, and D10 has the block *replace* the line when it opens, so the thing the clamp was
-measured on no longer exists. Worse, opening raises D8's cap, which resizes the scroll box, which
+measured on no longer exists. Worse, opening a row in a box still below its cap grows the box, which
fires the very observer that would reclassify it — so the chevron would vanish from a row while it
sat expanded, and with it the way back, since the row's click target is gated on the same verdict.
You must always be able to close what you opened; the verdict is recomputed only for closed rows.
@@ -260,38 +265,50 @@ native markup: `no-native-control` in `frontend/scripts/check-ui-guideline.mjs`
`pnpm --dir frontend check` on a raw `<button>` in feature code. The chevron's slot is reserved on
every command row so the text column stays aligned.
-**D7 · Clicking the row toggles it — anywhere but the statement itself.** Click-anywhere is what
-makes the affordance usable at 12px, and it is the convention of every CI log, so the index, the
-timestamps, the glyph and the empty space all toggle. The statement does not, whether it is the
-clamped line or the unfolded block, because text a reader can select must not double as a button.
-
-A selection guard alone cannot carry that. It catches the drag — mouse-up at the end of a sweep,
-where the selection is already non-collapsed — but not the double-click, whose *first* click
-arrives with the selection still collapsed and would toggle the row, replacing the very text the
-second click was aiming at. Nothing observable at that moment distinguishes it from a single click,
-and waiting to find out would put a double-click delay on every toggle. Excluding the text removes
-the question instead of timing it.
-
-So: clicks inside a button are ignored (D6 owns those), clicks on the statement are ignored, a
-click that ends a selection is still ignored as a belt-and-braces guard for a drag that began on
-the metadata and finished over the text, and everything else toggles. Mouse convenience only —
-assistive technology sees D6's controls.
-
-**D8 · The section's cap rises while a block is on screen.** A 630px statement inside a 280px box is a
-keyhole. While any row in a section is unfolded, that section's scroll box is capped at
-`max(280px, 60vh)` instead of `ITEM_HEIGHT * MAX_VISIBLE_ITEMS`, and returns to the collapsed cap
-when the last row folds. Both halves matter: `60vh` is the honest unit for "how much of the screen
-may this take", and the `max()` floor keeps a short window from shrinking the box below its
-collapsed height. A run that failed therefore opens taller than one that did not, by way of D4,
-which is the right way round. The box still scrolls — a statement with a few hundred columns is
-taller than any cap worth setting — but it scrolls over most of a screen instead of over ten lines.
+**D7 · Clicking a row's line toggles it; the unfolded block does not.** Click-anywhere is what
+makes the affordance usable at 12px, and it is the convention of every CI log, so on a row that has
+a fold control the whole line toggles: the index, the timestamps, the glyph, the empty space, the
+clamped statement and the error. One rule, the same on every row that has a chevron — a reader does
+not have to learn which part of a line is live. The unfolded block is the exception. It is not a
+line but the content the line opened: a reader reads and selects from it, it can be hundreds of
+pixels tall, so a stray click would collapse what is being read, and the chevron sits beside it.
+
+That split also settles the double-click. A selection guard catches a drag, where the selection is
+already non-collapsed at mouse-up, but not a double-click, whose first click arrives collapsed and
+is indistinguishable from a single one at that instant. On the block, where selecting an identifier
+is the point and the first click would remove the very text being selected, exclusion answers it.
+On the clamped line the first click expands the row, which is what a click there meant anyway, and
+the word is still there in the block underneath.
+
+The error line pays a small, accepted price for the uniform rule. It has no copy button (D3), so it
+is taken by selecting it. A drag never toggles. A double- or triple-click selects as usual and also
+flips the block once, and in a section scrolled to its end that fold can shift the text under the
+pointer mid-gesture. D3 already judged wanting the error in the clipboard rare; a dead zone across
+the widest part of the row that matters most is the larger cost.
+
+So: clicks inside a button are ignored (D6 owns those), clicks inside the unfolded block are
+ignored, a click that ends a selection is ignored, and everything else toggles. A row that is not
+foldable (D5) has nothing to toggle, so its line is inert — including the error of a failure whose
+statement could not be recovered. Mouse convenience only — assistive technology sees D6's controls.
+
+**D8 · The section's height never changes because a row unfolds.** The scroll box is capped at
+`ITEM_HEIGHT * MAX_VISIBLE_ITEMS` — ten rows, 280px — whether or not a block is open, and a block
+taller than what remains scrolls inside it. An earlier revision raised the cap to `max(280px, 60vh)`
+while a block was on screen, so that a 630px statement would not be read through a keyhole. In use
+the cost was worse than the keyhole: a full box grew by 260px the moment a row was clicked, moving
+every section below it, and shrank again on the fold, which is where the page and the box's own
+scroll got clamped out from under the reader (D16). Layout stability wins: the box the reader
+scanned is the box they unfold in. Two things follow. The block's copy button is sticky to the top
+of the box while the block is in view (D10), so a statement taller than the box can still be
+copied from wherever the reader has scrolled to. And unfolding a row near the bottom of the box has
+to reveal what it opened, since the block lands below the box's visible edge — that is D16's job.
**D9 · The viewer owns one scroll context.** The unfolded block never gets its own `overflow` — it
grows to its natural height and the section scrolls, so nothing the viewer renders stacks a
scrollbar inside a scrollbar. It cannot claim the same for the page it sits on:
`DeployTaskRunHistorySheet` renders the viewer inside `SheetBody`, which is `overflow-y-auto`
(`components/ui/sheet.tsx:161-167`), so on that one surface the section's box has always sat inside
-an outer scroller, and D8's raised cap makes the inner region bigger. The nesting predates this
+an outer scroller, and an unfolded block now scrolls inside it. The nesting predates this
change and the sheet's `overscroll-contain` keeps it from chaining. Handing the scroll to the host
— no cap when the viewer is inside a sheet, `SheetBody` scrolling the expanded statement — would
remove it, at the price of a second layout mode for the viewer to carry, test, and keep consistent
@@ -302,14 +319,13 @@ mild, the mode would be permanent.
`whitespace-pre-wrap break-words` on the verbatim statement, in the row's mono face, on
`bg-background` inside a `border-block-border` block — the block is a framed content region, and
`docs/agents/frontend-ux.md:143-144` keeps `border-control-border` for controls — with D3's copy
-button in its top-right corner over padding wide enough to hold it, never over the SQL. That
-clearance is not decoration: the contract says text "must not overlap adjacent controls"
+button beside it, in a column of its own at the block's right edge. A column rather than an
+overlay because the contract says text "must not overlap adjacent controls"
(`frontend-ux.md:113-114`), and the rows D5 newly makes foldable are precisely the ones whose first
-wrapped line runs the full width of the block, so an overlay with no reserved padding would sit on
-top of the statement in the common case rather than a rare one. The block's right padding reserves
-the control's width plus the gap beside it; the text wraps before it
-corner — positioned inside the block's padding so it overlays rather than reflows the SQL, and
-visible for as long as the block is. On a successful row the block replaces the line, so one
+wrapped line runs the full width of the block. The button is `sticky` to the top of the section's
+scroll box: D8 keeps the box at ten rows, so a long statement scrolls under it, and a control pinned
+to the block's top corner would be gone before the reader reached the end of what they want to
+copy. It stays put for as long as any of the block is in view, and leaves with the block. On a successful row the block replaces the line, so one
statement is on screen at a time and the cluster's copy button gives way to the block's. On a
failed row the error keeps the line and the block sits beneath it, because both payloads are the
point. Either way the index, timestamps and status glyph stay pinned to the row's first line,
@@ -336,7 +352,7 @@ free with `CopyButton`. The fold control needs two new keys under `task-run.log-
accessible names, not visible labels, and land in `en-US` with the other locales falling back
until translated.
-**D13 · A row that opens by default has to be rendered, numbered and in view.** `SectionContent`
+**D13 · The marked row has to be rendered, numbered and in view.** `SectionContent`
renders only the first
`MAX_RENDERED_ITEMS` (50) entries of a section until *Load more* is pressed
(`SectionContent.tsx:29-32`). A migration whose 300th statement fails would therefore have D4 mark
@@ -349,8 +365,8 @@ Rendering the whole section would keep the promise too, but a section has no bou
can carry thousands of statements — and not having to render all of them is what the cap is for.
Rendering it is not the same as showing it. Fifty rows at 28px is roughly 1,400px of content above
-the marked row, inside a box capped at `max(280px, 60vh)` whose `scrollTop` starts at zero, so the
-row would be mounted, expanded and off-screen — the promise kept in the DOM and broken on the
+the marked row, inside a box capped at 280px whose `scrollTop` starts at zero, so the
+row would be mounted and off-screen — the promise kept in the DOM and broken on the
screen. When a row becomes the marked one, the section sets its own `scrollTop` to bring it into
view. Its own, not `scrollIntoView`, which would scroll the page under a reader who was looking at
something else. It fires once, when the mark lands on a row — and on mount, if a
@@ -364,16 +380,14 @@ pressed — pointing the reader at the wrong statement, which is worse than not
number shown is the item's index in the section, and the D13 regression test asserts that number,
not merely that the row rendered.
-**D14 · The open set follows the mark while the log is live.** The viewer polls a running task every
-five seconds (`useTaskRunLogData.ts:101`), and `section.items` changes without `datasetKey`
-changing. Applying D4's mark only when the component mounts would therefore miss the case the
-feature exists for — a deploy watched from the plan page, succeeding command by command, that then
-fails — because the failure arrives on a later poll into an already-mounted section, and nothing
-would open it. So the open set is derived rather than initialised: a row is open when it is marked
-or the reader opened it, and folded when the reader folded it. An explicit toggle outranks the mark
-for as long as the dataset lasts, so a failure the reader folded stays folded through the next
-poll, and a mark that moves off a row — a transient failure that turns out to have been retried —
-takes its auto-open with it.
+**D14 · The reader's folds are the only open state, and they outlive everything but the run.** The
+viewer polls a running task every five seconds (`useTaskRunLogData.ts:101`), and `section.items`
+changes without `datasetKey` changing. A row is open when the reader opened it and folded
+otherwise; nothing else writes that state, so a poll can neither open a row nor close one. The mark
+rides the same polls but touches only D13: a failure arriving on a later poll into an
+already-mounted section is rendered and scrolled to then, not only at mount, and a mark that moves
+off a row — a transient failure that turns out to have been retried — takes nothing with it,
+because it never opened anything.
They also cannot be keyed by the row's render key. That key is positional —
`` `${idPrefix ?? "section"}-${groupIndex}-${entryIndex}` `` (`model.ts:481`) — and both halves move
@@ -418,21 +432,20 @@ entries that already know their identity; they never mint one.
Those overrides cannot live in `SectionContent` either, because it is mounted conditionally: collapsing an
enclosing section unmounts it and reopening builds a fresh one (`TaskRunLogViewer.tsx:195-201`), and
a live run also swaps the sole-section rendering for the multi-section tree the moment a second
-entry type arrives. Either remount would discard the reader's folds and pop a marked failure back
-open on a dataset that never changed. The overrides therefore sit in `TaskRunLogViewer`, above the
+entry type arrives. Either remount would discard the reader's folds on a dataset that never
+changed. The overrides therefore sit in `TaskRunLogViewer`, above the
conditional mount, keyed by row and cleared when `taskRunName` changes — the same moment
`datasetKey` already clears `showAllItems`. `showAllItems` keeps its remount-local behavior;
re-hiding the tail of a long list on collapse is not a promise anyone made.
-It also stops at a collapsed ancestor, deliberately. The viewer already expands a section the
+The mark stops at a collapsed ancestor, deliberately. The viewer already expands a section the
moment its status turns to error — unless the reader collapsed that section themselves, which
`userCollapsedSections` records and honours (`useTaskRunLogSections.ts:234-247`), with the same
treatment for replicas and release files. A mark arriving into a section the reader has shut does
-not reopen it. Doing so would break the precedence this decision just established, where an
-explicit toggle outranks the mark, and it would override the reader at the one moment they have
-most clearly said what they want on screen. Nothing is hidden by this: a collapsed section still
+not reopen it. Doing so would override the reader at the one moment they have most clearly said
+what they want on screen. Nothing is hidden by this: a collapsed section still
carries its own status, so the header turns to the error glyph and says a failure is inside. When
-the reader opens it, the marked row is already unfolded and the section is already scrolled to it,
+the reader opens it, the section is already scrolled to the marked row,
because D13's scroll fires on mount whenever a marked row is present, not only when a mark lands on
a row that is already showing.
@@ -442,8 +455,8 @@ remounts the whole viewer and takes the overrides with it. That key is not an ac
comment above it says the remount exists "for a fresh disclosure state on the new phase", and it is
also what invalidates an in-flight `RUNNING` log request before it can be cached as complete.
Persisting overrides across it, in a module-level map keyed by task-run name, would work and would
-quietly undo that intent. And the behavior it produces is the one this doc wants anyway: the flip
-that reopens a folded failure is the flip to the phase where that failure is the outcome. So folds
+quietly undo that intent. A new phase is also a fair place to start clean: the terminal log is a
+different document from the one that was streaming. So folds
survive polls, section collapse and the sole-to-multi swap *within* a phase, and a new phase starts
fresh.
@@ -486,6 +499,37 @@ The UX contract already asks for right-aligned numerics in tables; these are the
different frame. This straightens the statement column too, which is the part of the fix that
improves the log as it stands today.
+**D16 · A toggle never moves the clicked line except to reveal what it opened, and folding puts it
+back.** With D8's cap fixed, a toggle changes only the box's scroll range: unfolding lengthens it,
+folding shortens it back to what it was. Two motions follow, and both are the reader's doing.
+
+Unfolding reveals. The marked row is usually the last one, and D13 parks it at the bottom of the
+box, so its block opens below the visible edge; a click that visibly changed nothing but the
+chevron would read as a click that did nothing. So the section scrolls itself by the least that
+shows the row: to its bottom edge when the row fits, and to its top edge — the line at the top of
+the box, the block filling the rest — when the row is taller than the box. The section's own
+scroll, never the page's: the block is clipped by the box, and a page scroll cannot reveal what is
+inside it, so scrolling the page would only move the log under the reader.
+
+Folding puts it back. The folded content is exactly the content before the unfold, so the box's
+scroll range is exactly what it was, and the browser's own clamp lands the line where it stood
+before the reveal — under the pointer when the reveal moved nothing, and back where it was clicked
+from when it did. Nothing compensates for this: a page scroll that kept the line under the pointer
+would slide the whole log up the page instead, which is the jump the fixed cap exists to remove.
+Row 38 of 38, at the bottom of a full box, goes to the top on unfold and comes back to the bottom
+on fold; the page does not move for either.
+
+An earlier revision compensated with the section's and then the page's scroll after every toggle.
+All three displacements it corrected — the cap dropping around the row, the section's scroll
+clamping when the cap rose, the page clamping when the box shrank on a full log — were caused by
+the cap moving, and left with it.
+
+One case is left, and accepted: a box still below its cap grows on unfold and shrinks on fold, and
+a reader who scrolls the page into that growth and then folds is clamped by the page, the way every
+disclosure at the bottom of a page is. Holding the line there would mean reserving the vacated
+height as blank space, state lingering on screen after the click that caused it. Recorded as the
+option and not taken.
+
## States
Mockups A–E are in the PR description. Product typography, spacing and semantic colors are taken
@@ -495,8 +539,8 @@ from the live component.
|---|---|---|
| A | Today | The 80-character cut, a failed row that is error-only, and the ragged left edge of D15 |
| B | Folded, hover | D2, D3, D5, D6, D11, D15 — one meaning per control, reserved slots, a straight column |
-| C | Unfolded | D8, D9, D10 — verbatim formatting, copy in the block, raised cap, one scrollbar |
-| D | A failed command | D1, D3, D4, D10 — the error keeps the line, the failed statement and its copy sit beneath it |
+| C | Unfolded | D9, D10 — verbatim formatting, copy in the block; the mockup's raised cap predates D8's revision, the box stays at ten rows |
+| D | A failed command, unfolded | D1, D3, D10 — the error keeps the line, the failed statement and its copy sit beneath it |
| E | Narrow container | D2 — the same rows in the deploy sheet, clamped by its width |
## Scope
@@ -506,10 +550,10 @@ Frontend only. The viewer is embedded by `DatabaseChangelogDetailPage`, `Revisio
| File | Change |
|---|---|
-| `task-run-log/types.ts` | `statement?`, `error?` and `defaultOpen?` on `DisplayItem` |
-| `task-run-log/model.ts` | Delete the `substring`; read the statement for failed commands too; return all the new fields; pick the auto-open row in `buildSectionsFromEntries`, over the whole entry sequence rather than per section; build `key` from the entry's identity instead of `idPrefix-groupIndex-entryIndex` (D14) |
+| `task-run-log/types.ts` | `statement?`, `error?` and `marked?` on `DisplayItem` |
+| `task-run-log/model.ts` | Delete the `substring`; read the statement for failed commands too; return all the new fields; pick the marked row in `buildSectionsFromEntries`, over the whole entry sequence rather than per section; build `key` from the entry's identity instead of `idPrefix-groupIndex-entryIndex` (D14) |
| `task-run-log/useTaskRunLogSections.ts` | The hook owns every builder call — flat, per-replica, release-file and orphan — so it forwards `taskRunStatus` into all of them; nothing else invokes the builders, and a guard that stops here is a guard that never runs |
-| `task-run-log/SectionContent.tsx` | Fold control, copy button, CSS clamp, default-open failed rows, the marked row rendered and scrolled to past the 50-item window, section cap, `ITEM_HEIGHT` 20 → 28, the reserved timestamp and index columns (D15), and one `ResizeObserver` on the scroll box deciding which rows are foldable (D5) |
+| `task-run-log/SectionContent.tsx` | Fold control, copy button, CSS clamp, the marked row rendered and scrolled to past the 50-item window, section cap, `ITEM_HEIGHT` 20 → 28, the reserved timestamp and index columns (D15), one `ResizeObserver` on the scroll box deciding which rows are foldable (D5), and the reveal on unfold (D16) |
| `task-run-log/TaskRunLogViewer.tsx` | The reader's fold overrides, held above the conditional mount and cleared with `taskRunName` (D14) |
| `locales/en-US.json` | Two accessible names |
@@ -520,14 +564,14 @@ behavior of this function:
statement past 80 characters is not truncated (regression); a failed command yields the error as
`detail` *and* the failed statement in `statement`, including when it has to come from `range`;
an entry with no statement yields `"-"` and no `statement`.
-- `model.test.ts` again for the auto-open pick, which is where the retry shape has to be locked
+- `model.test.ts` again for the mark, which is where the retry shape has to be locked
down: entries for two attempts separated by a `RETRY_INFO`, the first failing and the second
- succeeding, mark **no** row to open even though the failure is last in its own section; the same
+ succeeding, mark **no** row even though the failure is last in its own section; the same
entries with the second attempt failing mark only the second failure; a failure under one replica
is not silenced by another replica's success; and a `DONE` `taskRunStatus` marks nothing at all,
whatever the entries say.
-- `SectionContent`: a foldable row toggles and reports `aria-expanded`; a row marked to open starts
- unfolded and can be folded; a section of 60 entries whose marked failure is the last one renders
+- `SectionContent`: a foldable row toggles and reports `aria-expanded`; a marked row starts
+ folded like any other; a section of 60 entries whose marked failure is the last one renders
that row without pressing *Load more*, still reports the hidden count, **numbers it 60, not 51**,
and leaves the section scrolled to it rather than at the top (D13); copy receives the verbatim statement, never the line and never the error; a failed row
carries no copy button on its error line and one inside its block; a row with no recoverable
@@ -537,14 +581,28 @@ behavior of this function:
foldable anyway, and folding then unfolding it brings the statement and its copy button back; and
a clamped one-line statement **keeps** its chevron after opening — drive an observer callback
while it is open, which is what raising the cap does in the product, and assert the control
- survives and still closes the row; a marked failure with no recoverable statement is open yet
+ survives and still closes the row; a marked failure with no recoverable statement
carries no chevron and no row toggle.
- Collapsed ancestors (D14), same `datasetKey`: a failure arriving into a section the reader
- collapsed leaves it collapsed, and expanding it afterwards shows the marked row already unfolded
- and scrolled to.
-- Clicking (D7): a click on the index, the timestamp or the row's empty space toggles; a click on
- the clamped line or inside the unfolded block does not, so a double-click selects a word without
- the row moving under it.
+ collapsed leaves it collapsed, and expanding it afterwards shows the section already scrolled to
+ the marked row, which is still folded.
+- Clicking (D7): on a foldable row a click on the index, the timestamp, the empty space, the clamped
+ line or the error line toggles; a click inside the unfolded block does not, so an identifier can
+ be double-clicked there without the row moving; a click that ends a drag across the clamped line
+ or the error does not toggle; the line of a row that is not foldable does nothing, the error of a
+ failure with no recoverable statement included; and two clicks in quick succession on the clamped
+ line leave the row open, because the second lands on the block.
+- A fixed box (D8): the scroll box's cap is 280px before, during and after a row is unfolded, and
+ the block's copy button is a sticky sibling of the SQL rather than an overlay on it.
+- Revealing and putting back (D16): with the row's geometry stubbed, unfolding a row whose block
+ already fits scrolls nothing; unfolding one at the bottom of the box scrolls the section by
+ exactly the block's overflow, so the line moves up by that and no more; unfolding a row taller
+ than the box puts its line at the box's top; the page is never scrolled by either; folding
+ scrolls nothing itself, and a toggle in one section leaves another section's scroll alone. jsdom
+ has no layout, so the real motion is checked in a browser and in the journey below: a full
+ box keeps its height through unfold and fold, the last row's line goes to the top and comes
+ back, the page does not move, and the sticky copy button is still in view — and still copies the
+ whole statement — after the box has been scrolled to the end of a block taller than itself.
- `model.test.ts` for the marking edges: a failed command with neither `statement` nor a usable
`range` is still marked, so D13 renders and scrolls to its error, and no cap change follows
because it has no block.
@@ -562,9 +620,9 @@ behavior of this function:
section in two between polls. Asserting the key's stability is the point of the test — a version
of it that tolerated a changing key would be asserting the bug.
- Live updates (D14), all on an unchanged `datasetKey`: a section rerendered with a newly marked
- failure opens it without remounting; a row the reader folded stays folded when the next poll
- arrives; a row whose mark moves away folds again if the reader never touched it; a folded row is
- **still folded after collapsing and reopening its enclosing section**, and after the sole-section
+ failure scrolls to it without remounting and does not open it; a row the reader unfolded stays
+ unfolded when the next poll arrives, and when its mark moves away; an unfolded row is
+ **still unfolded after collapsing and reopening its enclosing section**, and after the sole-section
rendering gives way to the multi-section tree; and `taskRunName` changing clears those toggles,
as `datasetKey` already clears `showAllItems`.
diff --git a/frontend/src/components/task-run-log/SectionContent.test.tsx b/frontend/src/components/task-run-log/SectionContent.test.tsx
new file mode 100644
index 0000000000..67003a9d52
--- /dev/null
+++ b/frontend/src/components/task-run-log/SectionContent.test.tsx
@@ -0,0 +1,1280 @@
+import { CheckCircle2 } from "lucide-react";
+import { act, createElement, useState } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+import { TaskRunLogEntry_Type } from "@/types/proto-es/v1/rollout_service_pb";
+import { SectionContent } from "./SectionContent";
+import type { DisplayItem, Section } from "./types";
+
+(
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const mocks = vi.hoisted(() => ({
+ writeTextToClipboard: vi.fn(async (_text: string) => true),
+}));
+
+vi.mock("react-i18next", () => ({
+ initReactI18next: { type: "3rdParty", init: () => {} },
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock("@/lib/clipboard", () => ({
+ writeTextToClipboard: mocks.writeTextToClipboard,
+}));
+
+vi.mock("@/stores/app", () => ({
+ useAppStore: { getState: () => ({ notify: vi.fn() }) },
+}));
+
+const SHOW = "task-run.log-detail.show-full-statement";
+const HIDE = "task-run.log-detail.hide-full-statement";
+
+// jsdom has no layout, so the geometry the component reads is stubbed: a line
+// is as wide as its text, its box is `lineWidth`, and rows stack at ROW_HEIGHT.
+const CHAR_WIDTH = 7;
+const ROW_HEIGHT = 28;
+const layout = { lineWidth: 900 };
+
+const isLine = (element: HTMLElement) => element.dataset.logPayload === "line";
+
+const layoutStubs: Record<string, (this: HTMLElement) => number> = {
+ scrollWidth() {
+ return isLine(this) ? (this.textContent?.length ?? 0) * CHAR_WIDTH : 0;
+ },
+ clientWidth() {
+ return isLine(this) ? layout.lineWidth : 0;
+ },
+ clientHeight() {
+ return 10 * ROW_HEIGHT;
+ },
+ offsetHeight() {
+ return ROW_HEIGHT;
+ },
+ offsetTop() {
+ const siblings = Array.from(this.parentElement?.children ?? []);
+ return siblings.indexOf(this) * ROW_HEIGHT;
+ },
+};
+
+const resizeObservers: Array<() => void> = [];
+class FakeResizeObserver {
+ constructor(callback: ResizeObserverCallback) {
+ resizeObservers.push(() =>
+ callback([], this as unknown as ResizeObserver)
+ );
+ }
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+}
+
+const resizeTo = (lineWidth: number) => {
+ layout.lineWidth = lineWidth;
+ act(() => {
+ for (const notify of resizeObservers) notify();
+ });
+};
+
+let restoreLayout: Array<() => void> = [];
+
+beforeEach(() => {
+ layout.lineWidth = 900;
+ resizeObservers.length = 0;
+ mocks.writeTextToClipboard.mockClear();
+ vi.stubGlobal("ResizeObserver", FakeResizeObserver);
+ restoreLayout = Object.entries(layoutStubs).map(([property, get]) => {
+ const original = Object.getOwnPropertyDescriptor(
+ HTMLElement.prototype,
+ property
+ );
+ Object.defineProperty(HTMLElement.prototype, property, {
+ configurable: true,
+ get,
+ });
+ return () => {
+ if (original) {
+ Object.defineProperty(HTMLElement.prototype, property, original);
+ } else {
+ delete (HTMLElement.prototype as unknown as Record<string, unknown>)[
+ property
+ ];
+ }
+ };
+ });
+});
+
+afterEach(() => {
+ for (const restore of restoreLayout) restore();
+ vi.unstubAllGlobals();
+ window.getSelection()?.removeAllRanges();
+});
+
+const baseItem = (key: string): DisplayItem => ({
+ key,
+ time: "12:00:00.000",
+ timeMs: undefined,
+ relativeTime: "",
+ levelIndicator: "✓",
+ levelClass: "text-success",
+ detail: "",
+ detailClass: "text-control",
+});
+
+const ran = (
+ key: string,
+ statement: string,
+ extra: Partial<DisplayItem> = {}
+): DisplayItem => ({
+ ...baseItem(key),
+ statement,
+ detail: statement.trim().replace(/\s+/g, " "),
+ ...extra,
+});
+
+const failed = (
+ key: string,
+ statement: string | undefined,
+ error: string,
+ extra: Partial<DisplayItem> = {}
+): DisplayItem => ({
+ ...baseItem(key),
+ levelIndicator: "✗",
+ levelClass: "text-error",
+ detailClass: "text-error",
+ statement,
+ error,
+ detail: error,
+ ...extra,
+});
+
+const status = (key: string, detail: string): DisplayItem => ({
+ ...baseItem(key),
+ detail,
+});
+
+const sectionOf = (items: DisplayItem[]): Section => ({
+ id: "section-0",
+ type: TaskRunLogEntry_Type.COMMAND_EXECUTE,
+ label: "Command Execute",
+ status: "success",
+ statusIcon: CheckCircle2,
+ statusClass: "text-success",
+ duration: "2s",
+ entryCount: items.length,
+ items,
+});
+
+interface HarnessProps {
+ items: DisplayItem[];
+ datasetKey?: string;
+ // Folds the reader made before this SectionContent mounted.
+ initialOverrides?: ReadonlyMap<string, boolean>;
+}
+
+// The fold overrides live above SectionContent in the product, so the harness
+// owns them the same way.
+const Harness = ({
+ items,
+ datasetKey = "runs/1",
+ initialOverrides,
+}: HarnessProps) => {
+ const [overrides, setOverrides] = useState<ReadonlyMap<string, boolean>>(
+ () => initialOverrides ?? new Map()
+ );
+ return createElement(SectionContent, {
+ section: sectionOf(items),
+ datasetKey,
+ foldOverrides: overrides,
+ onFoldChange: (key: string, open: boolean) =>
+ setOverrides((previous) => new Map(previous).set(key, open)),
+ });
+};
+
+const mount = (props: HarnessProps, host: HTMLElement = document.body) => {
+ const container = document.createElement("div");
+ host.appendChild(container);
+ const root = createRoot(container);
+ const render = (next: HarnessProps) =>
+ act(() => {
+ root.render(createElement(Harness, next));
+ });
+ render(props);
+
+ const rows = () =>
+ Array.from(
+ container.querySelectorAll<HTMLElement>(
+ '[data-testid="task-run-log-row"]'
+ )
+ );
+ const rowOf = (text: string) => {
+ const row = rows().find((candidate) =>
+ candidate.textContent?.includes(text)
+ );
+ if (!row) throw new Error(`no row containing "${text}"`);
+ return row;
+ };
+ const within = (row: HTMLElement) => ({
+ fold: () =>
+ row.querySelector<HTMLButtonElement>(
+ `button[aria-label="${SHOW}"], button[aria-label="${HIDE}"]`
+ ),
+ copy: () =>
+ Array.from(
+ row.querySelectorAll<HTMLButtonElement>(
+ 'button[aria-label="common.copy"]'
+ )
+ ),
+ payload: (kind: "line" | "error" | "block") =>
+ row.querySelector<HTMLElement>(`[data-log-payload="${kind}"]`),
+ });
+
+ return {
+ container,
+ render,
+ rows,
+ rowOf,
+ within,
+ scrollBox: () => rows()[0]?.parentElement as HTMLElement,
+ unmount: () => {
+ act(() => root.unmount());
+ container.remove();
+ },
+ };
+};
+
+const click = (element: Element | null | undefined) => {
+ if (!element) throw new Error("nothing to click");
+ act(() => {
+ element.dispatchEvent(
+ new MouseEvent("click", { bubbles: true, cancelable: true })
+ );
+ });
+};
+
+const MULTI_LINE = "CREATE TABLE t (\n id bigint,\n name text\n);";
+const WIDE = `CREATE INDEX idx ON public.loan_application (${"customer_id, ".repeat(12)}id);`;
+
+describe("SectionContent folding", () => {
+ test("a foldable row toggles and reports aria-expanded", () => {
+ const view = mount({ items: [ran("a", MULTI_LINE)] });
+ const row = () => view.within(view.rowOf("CREATE TABLE"));
+
+ expect(row().fold()?.getAttribute("aria-expanded")).toBe("false");
+ expect(row().fold()?.getAttribute("aria-label")).toBe(SHOW);
+ expect(row().payload("block")).toBeNull();
+
+ click(row().fold());
+ expect(row().fold()?.getAttribute("aria-expanded")).toBe("true");
+ expect(row().fold()?.getAttribute("aria-label")).toBe(HIDE);
+ expect(row().payload("block")?.textContent).toContain(" id bigint,\n");
+ // The block takes the line's place: one statement on screen at a time.
+ expect(row().payload("line")).toBeNull();
+
+ click(row().fold());
+ expect(row().fold()?.getAttribute("aria-expanded")).toBe("false");
+ expect(row().payload("block")).toBeNull();
+ expect(row().payload("line")).not.toBeNull();
+
+ view.unmount();
+ });
+
+ test("a marked failure starts folded like any other row", () => {
+ const view = mount({
+ items: [failed("a", MULTI_LINE, "ERROR: exists", { marked: true })],
+ });
+ const row = () => view.within(view.rowOf("ERROR: exists"));
+
+ expect(row().fold()?.getAttribute("aria-expanded")).toBe("false");
+ expect(row().payload("block")).toBeNull();
+ expect(view.scrollBox().style.maxHeight).toBe("280px");
+
+ // Unfolded, both payloads are the point: the error keeps the line and the
+ // block sits beneath it.
+ click(row().fold());
+ expect(row().payload("error")?.textContent).toBe("ERROR: exists");
+ expect(row().payload("block")?.textContent).toContain("CREATE TABLE t (");
+
+ view.unmount();
+ });
+
+ test("the block shows the statement without the blank lines a split segment begins with", () => {
+ const view = mount({ items: [ran("a", `\n\n${MULTI_LINE}\n`)] });
+ const row = () => view.within(view.rowOf("CREATE TABLE"));
+
+ click(row().fold());
+ const block = row().payload("block");
+ expect(block?.textContent?.startsWith("CREATE TABLE t (\n id bigint,")).toBe(
+ true
+ );
+
+ view.unmount();
+ });
+});
+
+describe("SectionContent foldability", () => {
+ test("a single-line statement that fits has no fold control until its container clamps it", () => {
+ const view = mount({ items: [ran("a", "SET statement_timeout TO '3600s';")] });
+ const row = () => view.within(view.rowOf("SET statement_timeout"));
+
+ expect(row().fold()).toBeNull();
+
+ resizeTo(100);
+ expect(row().fold()).not.toBeNull();
+
+ resizeTo(900);
+ expect(row().fold()).toBeNull();
+
+ view.unmount();
+ });
+
+ test("a multi-line statement is foldable at any width", () => {
+ const view = mount({ items: [ran("a", MULTI_LINE)] });
+
+ expect(view.within(view.rowOf("CREATE TABLE")).fold()).not.toBeNull();
+
+ view.unmount();
+ });
+
+ test("whitespace around a one-line statement is nothing to unfold", () => {
+ const view = mount({ items: [ran("a", "\nSELECT 1;\n")] });
+
+ expect(view.within(view.rowOf("SELECT 1;")).fold()).toBeNull();
+
+ view.unmount();
+ });
+
+ test("a failed row is foldable however short its statement", () => {
+ const view = mount({ items: [failed("a", "SELECT 1", "ERROR: boom")] });
+ const row = () => view.within(view.rowOf("ERROR: boom"));
+
+ expect(row().fold()).not.toBeNull();
+ expect(row().copy()).toHaveLength(0);
+
+ click(row().fold());
+ expect(row().payload("block")?.textContent).toContain("SELECT 1");
+ expect(row().copy()).toHaveLength(1);
+
+ click(row().fold());
+ expect(row().payload("block")).toBeNull();
+ expect(row().fold()).not.toBeNull();
+
+ view.unmount();
+ });
+
+ test("a clamped one-line statement keeps its chevron while it is open", () => {
+ layout.lineWidth = 100;
+ const view = mount({ items: [ran("a", WIDE)] });
+ const row = () => view.within(view.rowOf("CREATE INDEX"));
+
+ click(row().fold());
+ expect(row().payload("line")).toBeNull();
+
+ // Opening raises the cap, which resizes the box, which fires the observer
+ // while the line it would measure is gone.
+ resizeTo(100);
+ expect(row().fold()?.getAttribute("aria-expanded")).toBe("true");
+
+ click(row().fold());
+ expect(row().payload("block")).toBeNull();
+ expect(row().fold()?.getAttribute("aria-expanded")).toBe("false");
+
+ view.unmount();
+ });
+
+ test("the fold control survives closing, so focus is not dropped", () => {
+ layout.lineWidth = 100;
+ const view = mount({ items: [ran("a", WIDE)] });
+ const row = () => view.within(view.rowOf("CREATE INDEX"));
+
+ click(row().fold());
+ const openControl = row().fold();
+ click(openControl);
+
+ expect(row().fold()).toBe(openControl);
+
+ view.unmount();
+ });
+
+ test("a row already open when the section remounts can still be closed", () => {
+ // Opened while its container clamped it; the section then collapsed and
+ // reopened wide, so nothing is left to measure the verdict from.
+ const view = mount({
+ items: [ran("a", "SELECT 1;")],
+ initialOverrides: new Map([["a", true]]),
+ });
+ const row = () => view.within(view.rowOf("SELECT 1;"));
+
+ expect(row().payload("block")).not.toBeNull();
+ expect(row().fold()?.getAttribute("aria-expanded")).toBe("true");
+
+ click(row().fold());
+ expect(row().payload("block")).toBeNull();
+ // Closed, it fits its line, so there is nothing left to unfold.
+ expect(row().fold()).toBeNull();
+
+ view.unmount();
+ });
+
+ test("a marked failure with no recoverable statement has no chevron and no row toggle", () => {
+ const view = mount({
+ items: [failed("a", undefined, "ERROR: boom", { marked: true })],
+ });
+ const row = view.rowOf("ERROR: boom");
+
+ expect(view.within(row).fold()).toBeNull();
+ expect(view.within(row).copy()).toHaveLength(0);
+ expect(view.scrollBox().style.maxHeight).toBe("280px");
+
+ click(row.firstElementChild);
+ expect(view.within(view.rowOf("ERROR: boom")).payload("block")).toBeNull();
+
+ view.unmount();
+ });
+
+ test("rows that carry status words get neither control but keep the slot", () => {
+ const view = mount({ items: [status("a", "BEGIN"), ran("b", MULTI_LINE)] });
+ const begin = view.rowOf("BEGIN");
+ const create = view.rowOf("CREATE TABLE");
+
+ expect(begin.querySelectorAll("button")).toHaveLength(0);
+ expect(begin.children).toHaveLength(create.children.length);
+
+ view.unmount();
+ });
+
+ test("a status row that failed gets neither control", () => {
+ const view = mount({
+ items: [
+ {
+ ...status("a", "ROLLBACK: connection reset"),
+ levelIndicator: "✗",
+ detailClass: "text-error",
+ },
+ ],
+ });
+ const row = view.rowOf("ROLLBACK");
+
+ expect(row.querySelectorAll("button")).toHaveLength(0);
+ click(row.firstElementChild);
+ expect(view.within(view.rowOf("ROLLBACK")).payload("block")).toBeNull();
+
+ view.unmount();
+ });
+
+ test("rows appended by a poll are measured without a resize", () => {
+ layout.lineWidth = 100;
+ const first = ran("a", `${WIDE} -- first`);
+ const view = mount({ items: [first] });
+ expect(view.within(view.rowOf("-- first")).fold()).not.toBeNull();
+
+ // A poll grows the capped box's scroll height, never its border box, so no
+ // observer fires for the new row.
+ view.render({ items: [first, ran("b", `${WIDE} -- second`)] });
+
+ expect(view.within(view.rowOf("-- second")).fold()).not.toBeNull();
+
+ view.unmount();
+ });
+
+ test("rows revealed by load more are measured too", () => {
+ layout.lineWidth = 100;
+ const view = mount({
+ items: Array.from({ length: 60 }, (_, index) =>
+ ran(`item-${index}`, `${WIDE} -- ${index}`)
+ ),
+ });
+
+ const loadMore = Array.from(view.container.querySelectorAll("button")).find(
+ (button) => button.textContent?.includes("common.load-more")
+ );
+ click(loadMore);
+
+ expect(view.rows()).toHaveLength(60);
+ expect(view.within(view.rowOf("-- 59")).fold()).not.toBeNull();
+
+ view.unmount();
+ });
+});
+
+describe("SectionContent copy", () => {
+ test("copy takes the verbatim statement, never the line", async () => {
+ const statement = `\n${MULTI_LINE}\n`;
+ const view = mount({ items: [ran("a", statement)] });
+ const row = () => view.within(view.rowOf("CREATE TABLE"));
+
+ expect(row().copy()).toHaveLength(1);
+ await act(async () => {
+ row().copy()[0]?.click();
+ });
+ expect(mocks.writeTextToClipboard).toHaveBeenLastCalledWith(statement);
+
+ // Unfolded, the cluster's button gives way to the block's.
+ click(row().fold());
+ expect(row().copy()).toHaveLength(1);
+ expect(row().payload("block")?.contains(row().copy()[0] ?? null)).toBe(true);
+ await act(async () => {
+ row().copy()[0]?.click();
+ });
+ expect(mocks.writeTextToClipboard).toHaveBeenLastCalledWith(statement);
+ expect(mocks.writeTextToClipboard).toHaveBeenCalledTimes(2);
+
+ view.unmount();
+ });
+
+ test("a statement that fits its line still offers copy", async () => {
+ const view = mount({ items: [ran("a", "SELECT 1;")] });
+ const row = view.within(view.rowOf("SELECT 1;"));
+
+ expect(row.fold()).toBeNull();
+ expect(row.copy()).toHaveLength(1);
+ await act(async () => {
+ row.copy()[0]?.click();
+ });
+ expect(mocks.writeTextToClipboard).toHaveBeenLastCalledWith("SELECT 1;");
+
+ view.unmount();
+ });
+
+ test("a failed row has no copy on its error line and one inside its block", async () => {
+ const view = mount({ items: [failed("a", MULTI_LINE, "ERROR: exists")] });
+ const row = () => view.within(view.rowOf("ERROR: exists"));
+
+ expect(row().copy()).toHaveLength(0);
+
+ click(row().fold());
+ expect(row().copy()).toHaveLength(1);
+ expect(row().payload("block")?.contains(row().copy()[0] ?? null)).toBe(true);
+ await act(async () => {
+ row().copy()[0]?.click();
+ });
+ expect(mocks.writeTextToClipboard).toHaveBeenLastCalledWith(MULTI_LINE);
+
+ view.unmount();
+ });
+
+ test("a row with no recoverable statement has no copy at all", () => {
+ const view = mount({
+ items: [status("a", "-"), failed("b", undefined, "ERROR: boom")],
+ });
+
+ expect(
+ view.container.querySelectorAll('button[aria-label="common.copy"]')
+ ).toHaveLength(0);
+
+ view.unmount();
+ });
+});
+
+describe("SectionContent row clicks", () => {
+ const openBlock = (view: ReturnType<typeof mount>) =>
+ view.within(view.rowOf("CREATE TABLE")).payload("block");
+
+ test("the index, the timestamp and the row's empty space toggle", () => {
+ const view = mount({
+ items: [ran("a", MULTI_LINE, { relativeTime: "+12ms" })],
+ });
+ const row = () => view.rowOf("CREATE TABLE");
+ const cell = (text: string) =>
+ Array.from(row().querySelectorAll("span")).find(
+ (span) => span.textContent === text
+ );
+
+ click(cell("1"));
+ expect(openBlock(view)).not.toBeNull();
+ click(cell("12:00:00.000"));
+ expect(openBlock(view)).toBeNull();
+ click(cell("+12ms"));
+ expect(openBlock(view)).not.toBeNull();
+ click(row());
+ expect(openBlock(view)).toBeNull();
+
+ view.unmount();
+ });
+
+ test("a click on the folded statement line unfolds the row", () => {
+ const view = mount({ items: [ran("a", MULTI_LINE)] });
+ const row = () => view.within(view.rowOf("CREATE TABLE"));
+
+ click(row().payload("line"));
+
+ expect(row().payload("block")?.textContent).toContain(" id bigint,\n");
+ expect(row().fold()?.getAttribute("aria-expanded")).toBe("true");
+
+ view.unmount();
+ });
+
+ test("a click inside the unfolded block does not fold it", () => {
+ const view = mount({ items: [ran("a", MULTI_LINE)] });
+ const row = () => view.within(view.rowOf("CREATE TABLE"));
+
+ click(row().fold());
+ click(row().payload("block"));
+
+ expect(row().payload("block")).not.toBeNull();
+
+ view.unmount();
+ });
+
+ test("two quick clicks on the clamped line leave the row open", () => {
+ const view = mount({ items: [ran("a", MULTI_LINE)] });
+ const row = () => view.within(view.rowOf("CREATE TABLE"));
+
+ // A double-click: the first click opens the row, which swaps the line for
+ // the block, so the second lands on the block.
+ click(row().payload("line"));
+ click(row().payload("block"));
+
+ expect(row().payload("block")).not.toBeNull();
+
+ view.unmount();
+ });
+
+ test("a drag across the clamped line does not unfold it", () => {
+ const view = mount({ items: [ran("a", MULTI_LINE)] });
+ const row = () => view.within(view.rowOf("CREATE TABLE"));
+
+ const range = document.createRange();
+ range.selectNodeContents(row().payload("line") as HTMLElement);
+ window.getSelection()?.addRange(range);
+ click(row().payload("line"));
+
+ expect(row().payload("block")).toBeNull();
+
+ view.unmount();
+ });
+
+ test("the line of a row with nothing to unfold ignores clicks", () => {
+ const view = mount({ items: [ran("a", "SELECT 1;")] });
+ const row = () => view.within(view.rowOf("SELECT 1;"));
+
+ click(row().payload("line"));
+
+ expect(row().payload("block")).toBeNull();
+
+ view.unmount();
+ });
+
+ test("the statement line is mouse convenience, not a control", () => {
+ const view = mount({ items: [ran("a", MULTI_LINE)] });
+ const row = view.rowOf("CREATE TABLE");
+ const line = view.within(row).payload("line");
+
+ expect(line?.getAttribute("role")).toBeNull();
+ expect(line?.getAttribute("tabindex")).toBeNull();
+ // Assistive technology reaches the row through its two buttons alone.
+ expect(
+ Array.from(row.querySelectorAll("[role], [tabindex], button")).map(
+ (element) => element.getAttribute("aria-label")
+ )
+ ).toEqual([SHOW, "common.copy"]);
+
+ view.unmount();
+ });
+
+ test("a click on the error line unfolds and folds a failed row", () => {
+ const view = mount({ items: [failed("a", MULTI_LINE, "ERROR: exists")] });
+ const row = () => view.within(view.rowOf("ERROR: exists"));
+
+ click(row().payload("error"));
+ expect(row().payload("block")?.textContent).toContain("CREATE TABLE t (");
+ expect(row().fold()?.getAttribute("aria-expanded")).toBe("true");
+ // The error keeps the line either way.
+ expect(row().payload("error")?.textContent).toBe("ERROR: exists");
+
+ click(row().payload("error"));
+ expect(row().payload("block")).toBeNull();
+
+ view.unmount();
+ });
+
+ test("a drag across the error line does not unfold the row", () => {
+ const view = mount({ items: [failed("a", MULTI_LINE, "ERROR: exists")] });
+ const row = () => view.within(view.rowOf("ERROR: exists"));
+
+ const range = document.createRange();
+ range.selectNodeContents(row().payload("error") as HTMLElement);
+ window.getSelection()?.addRange(range);
+ click(row().payload("error"));
+
+ expect(row().payload("block")).toBeNull();
+
+ view.unmount();
+ });
+
+ test("the error of a failure with no recoverable statement ignores clicks", () => {
+ const view = mount({
+ items: [failed("a", undefined, "ERROR: boom", { marked: true })],
+ });
+ const row = () => view.within(view.rowOf("ERROR: boom"));
+
+ click(row().payload("error"));
+
+ expect(row().payload("block")).toBeNull();
+ expect(row().fold()).toBeNull();
+
+ view.unmount();
+ });
+
+ test("copying does not toggle the row", async () => {
+ const view = mount({ items: [ran("a", MULTI_LINE)] });
+ const row = () => view.within(view.rowOf("CREATE TABLE"));
+
+ await act(async () => {
+ row().copy()[0]?.click();
+ });
+ expect(row().payload("block")).toBeNull();
+
+ view.unmount();
+ });
+
+ test("a click that ends a selection does not toggle", () => {
+ const view = mount({ items: [ran("a", MULTI_LINE)] });
+ const row = view.rowOf("CREATE TABLE");
+ const line = view.within(row).payload("line");
+
+ const range = document.createRange();
+ range.selectNodeContents(line as HTMLElement);
+ window.getSelection()?.addRange(range);
+
+ click(row.firstElementChild);
+ expect(view.within(view.rowOf("CREATE TABLE")).payload("block")).toBeNull();
+
+ view.unmount();
+ });
+});
+
+describe("SectionContent section height", () => {
+ test("the box keeps its ten-row cap while a block is on screen", () => {
+ const view = mount({ items: [ran("a", MULTI_LINE), ran("b", MULTI_LINE)] });
+ const folds = () => view.rows().map((row) => view.within(row).fold());
+
+ expect(view.scrollBox().style.maxHeight).toBe("280px");
+ click(folds()[0]);
+ click(folds()[1]);
+ expect(view.scrollBox().style.maxHeight).toBe("280px");
+ click(folds()[0]);
+ click(folds()[1]);
+ expect(view.scrollBox().style.maxHeight).toBe("280px");
+
+ view.unmount();
+ });
+
+ test("the block's copy button is a sticky sibling of the SQL, not an overlay on it", () => {
+ const view = mount({ items: [ran("a", MULTI_LINE)] });
+ const row = () => view.within(view.rowOf("CREATE TABLE"));
+
+ click(row().fold());
+ const block = row().payload("block") as HTMLElement;
+ const copy = row().copy()[0] as HTMLElement;
+ const holder = copy.closest("[data-log-copy]") as HTMLElement;
+
+ expect(holder.parentElement).toBe(block);
+ expect(holder.className).toContain("sticky");
+ expect(holder.className).not.toContain("absolute");
+ // The SQL is its own child, so the two never share a box.
+ expect(block.querySelector("[data-log-sql]")?.textContent).toContain(
+ "CREATE TABLE t ("
+ );
+
+ view.unmount();
+ });
+});
+
+describe("SectionContent render window", () => {
+ const sixty = (last: DisplayItem) => [
+ ...Array.from({ length: 59 }, (_, index) =>
+ ran(`item-${index}`, `SELECT ${index};`)
+ ),
+ last,
+ ];
+
+ test("renders a load more action for large sections", () => {
+ const items = sixty(ran("item-59", "SELECT 59;"));
+ const view = mount({ items });
+
+ expect(view.container.textContent).toContain("common.load-more");
+ expect(view.container.textContent).toContain("(10)");
+ expect(view.container.textContent).toContain("SELECT 0;");
+ expect(view.container.textContent).not.toContain("SELECT 59;");
+
+ const loadMore = Array.from(view.container.querySelectorAll("button")).find(
+ (button) => button.textContent?.includes("common.load-more")
+ );
+ click(loadMore);
+ expect(view.container.textContent).toContain("SELECT 59;");
+
+ view.render({ items, datasetKey: "runs/2" });
+ expect(view.container.textContent).toContain("common.load-more");
+ expect(view.container.textContent).not.toContain("SELECT 59;");
+
+ view.unmount();
+ });
+
+ test("a marked failure past the window is rendered, numbered and scrolled to", () => {
+ const view = mount({
+ items: sixty(
+ failed("item-59", "ALTER TABLE t ADD c int;", "ERROR: exists", {
+ marked: true,
+ })
+ ),
+ });
+
+ const marked = view.rowOf("ERROR: exists");
+ // Surfaced, not opened.
+ expect(view.within(marked).payload("block")).toBeNull();
+ expect(view.rows()).toHaveLength(51);
+ expect(view.container.textContent).toContain("(9)");
+ // Its index in the section, not its position in the sparse window.
+ expect(marked.firstElementChild?.textContent).toBe("60");
+ // 50 rows and the load-more button sit above it.
+ expect(view.scrollBox().scrollTop).toBe(51 * ROW_HEIGHT);
+
+ const loadMore = Array.from(view.container.querySelectorAll("button")).find(
+ (button) => button.textContent?.includes("common.load-more")
+ );
+ click(loadMore);
+ expect(view.rows()).toHaveLength(60);
+ expect(view.rowOf("ERROR: exists").firstElementChild?.textContent).toBe(
+ "60"
+ );
+ expect(view.rows().at(-1)).toBe(view.rowOf("ERROR: exists"));
+
+ view.unmount();
+ });
+
+ test("a marked row inside the window is rendered once, in place", () => {
+ const items = sixty(ran("item-59", "SELECT 59;"));
+ items[10] = failed("item-10", "SELECT 10;", "ERROR: boom", {
+ marked: true,
+ });
+ const view = mount({ items });
+
+ expect(view.rows()).toHaveLength(50);
+ expect(view.container.textContent).toContain("(10)");
+ const marked = view.rows().filter((row) =>
+ row.textContent?.includes("ERROR: boom")
+ );
+ expect(marked).toHaveLength(1);
+ expect(marked[0]?.firstElementChild?.textContent).toBe("11");
+
+ view.unmount();
+ });
+
+ test("a later poll does not scroll the reader back to the marked row", () => {
+ const items = sixty(
+ failed("item-59", "ALTER TABLE t ADD c int;", "ERROR: exists", {
+ marked: true,
+ })
+ );
+ const view = mount({ items });
+ expect(view.scrollBox().scrollTop).toBeGreaterThan(0);
+
+ view.scrollBox().scrollTop = 0;
+ view.render({ items: items.map((item) => ({ ...item })) });
+ expect(view.scrollBox().scrollTop).toBe(0);
+
+ view.unmount();
+ });
+});
+
+describe("SectionContent live updates", () => {
+ const block = (view: ReturnType<typeof mount>, text: string) =>
+ view.within(view.rowOf(text)).payload("block");
+
+ test("a newly marked failure is brought into view, not opened, without remounting", () => {
+ const commands = Array.from({ length: 59 }, (_, index) =>
+ ran(`item-${index}`, `SELECT ${index};`)
+ );
+ const view = mount({ items: [...commands, ran("last", "SELECT 59;")] });
+ const firstRow = view.rows()[0];
+ expect(view.scrollBox().scrollTop).toBe(0);
+
+ view.render({
+ items: [
+ ...commands,
+ failed("last", "SELECT 59;", "ERROR: boom", { marked: true }),
+ ],
+ });
+
+ expect(view.rows()[0]).toBe(firstRow);
+ expect(view.scrollBox().scrollTop).toBe(51 * ROW_HEIGHT);
+ expect(block(view, "ERROR: boom")).toBeNull();
+
+ view.unmount();
+ });
+
+ test("a row the reader unfolded stays unfolded when the next poll arrives", () => {
+ const item = () => failed("cmd", MULTI_LINE, "ERROR: exists", { marked: true });
+ const view = mount({ items: [item()] });
+
+ click(view.within(view.rowOf("ERROR: exists")).fold());
+ view.render({ items: [item(), status("next", "ROLLBACK")] });
+
+ expect(block(view, "ERROR: exists")).not.toBeNull();
+
+ view.unmount();
+ });
+
+ test("a row the reader unfolded stays unfolded when its mark moves away", () => {
+ const view = mount({
+ items: [failed("cmd", MULTI_LINE, "ERROR: exists", { marked: true })],
+ });
+
+ click(view.within(view.rowOf("ERROR: exists")).fold());
+ view.render({
+ items: [
+ failed("cmd", MULTI_LINE, "ERROR: exists"),
+ status("retry", "attempt 1/3"),
+ ],
+ });
+
+ expect(block(view, "ERROR: exists")).not.toBeNull();
+
+ view.unmount();
+ });
+
+ test("a poll never opens a row", () => {
+ const view = mount({ items: [ran("cmd", MULTI_LINE)] });
+
+ view.render({
+ items: [failed("cmd", MULTI_LINE, "ERROR: exists", { marked: true })],
+ });
+
+ expect(block(view, "ERROR: exists")).toBeNull();
+
+ view.unmount();
+ });
+});
+
+describe("SectionContent columns", () => {
+ const widths = (view: ReturnType<typeof mount>) => ({
+ index: view.scrollBox().style.getPropertyValue("--task-log-index-width"),
+ time: view.scrollBox().style.getPropertyValue("--task-log-time-width"),
+ });
+
+ test("a short section keeps the floors", () => {
+ const view = mount({
+ items: [ran("a", "SELECT 1;"), ran("b", "SELECT 2;", { relativeTime: "+12ms" })],
+ });
+
+ expect(widths(view)).toEqual({ index: "max(24px, 1ch)", time: "7ch" });
+
+ view.unmount();
+ });
+
+ test("the widest value sets the column for every row, including in the sparse window", () => {
+ const view = mount({
+ items: [
+ ...Array.from({ length: 999 }, (_, index) =>
+ ran(`item-${index}`, `SELECT ${index};`, { relativeTime: "+12ms" })
+ ),
+ failed("item-999", "SELECT 999;", "ERROR: boom", {
+ marked: true,
+ relativeTime: "+1234.56s",
+ }),
+ ],
+ });
+
+ // Rows 1-50 sit directly above row 1000.
+ expect(view.rows()).toHaveLength(51);
+ expect(widths(view)).toEqual({ index: "max(24px, 4ch)", time: "9ch" });
+
+ // No row carries a width of its own, so none can disagree with the rest.
+ for (const row of view.rows()) {
+ const [index, , relativeTime] = Array.from(row.children) as HTMLElement[];
+ expect(index?.className).toContain("w-(--task-log-index-width)");
+ expect(relativeTime?.className).toContain("w-(--task-log-time-width)");
+ expect(index?.getAttribute("style")).toBeNull();
+ expect(relativeTime?.getAttribute("style")).toBeNull();
+ }
+
+ view.unmount();
+ });
+
+ test("the relative-time column is kept when a row has no value", () => {
+ const view = mount({
+ items: [ran("a", "SELECT 1;"), ran("b", "SELECT 2;", { relativeTime: "+12ms" })],
+ });
+ const [first, second] = view.rows();
+
+ expect(first?.children).toHaveLength(second?.children.length ?? -1);
+
+ view.unmount();
+ });
+});
+
+describe("SectionContent revealing what a toggle opened", () => {
+ // jsdom lays nothing out, so this models the box as a 280px scroller over a
+ // stack of 28px rows: an open row is its line plus `blockHeight`, and the
+ // box's scroll range grows and shrinks with it, clamping like a browser's.
+ // The real motion is checked in a browser and in the e2e journey.
+ const BOX_HEIGHT = 280;
+ const BOX_TOP = 100;
+ const PAGE_START = 1000;
+ const geometry = { blockHeight: 0 };
+ let page: HTMLElement;
+ let restoreRect: () => void;
+
+ const pageDelta = () => page.scrollTop - PAGE_START;
+ const rect = (top: number, height: number) =>
+ ({ top, bottom: top + height, height }) as DOMRect;
+ const rowsOf = (box: HTMLElement) =>
+ Array.from(box.querySelectorAll<HTMLElement>('[data-testid="task-run-log-row"]'));
+ const rowHeight = (row: HTMLElement) =>
+ ROW_HEIGHT + (row.querySelector('[data-log-payload="block"]') ? geometry.blockHeight : 0);
+ const rowOffset = (row: HTMLElement) =>
+ rowsOf(row.parentElement as HTMLElement)
+ .slice(0, rowsOf(row.parentElement as HTMLElement).indexOf(row))
+ .reduce((sum, sibling) => sum + rowHeight(sibling), 0);
+ const contentHeight = (box: HTMLElement) =>
+ rowsOf(box).reduce((sum, row) => sum + rowHeight(row), 0);
+
+ const clampedScroll = (element: HTMLElement, max: () => number) => {
+ let value = 0;
+ Object.defineProperty(element, "scrollTop", {
+ configurable: true,
+ get: () => Math.max(0, Math.min(max(), value)),
+ set: (next: number) => {
+ value = Math.max(0, Math.min(max(), next));
+ },
+ });
+ };
+
+ beforeEach(() => {
+ geometry.blockHeight = 0;
+ page = document.createElement("div");
+ page.style.overflowY = "auto";
+ document.body.appendChild(page);
+ Object.defineProperty(page, "scrollHeight", { get: () => 5000 });
+ clampedScroll(page, () => 4000);
+ page.scrollTop = PAGE_START;
+
+ const original = HTMLElement.prototype.getBoundingClientRect;
+ HTMLElement.prototype.getBoundingClientRect = function (this: HTMLElement) {
+ if (this.dataset.testid === "task-run-log-row") {
+ const box = this.parentElement as HTMLElement;
+ return rect(
+ BOX_TOP + rowOffset(this) - box.scrollTop - pageDelta(),
+ rowHeight(this)
+ );
+ }
+ if (this.firstElementChild?.getAttribute("data-testid") === "task-run-log-row") {
+ return rect(
+ BOX_TOP - pageDelta(),
+ Math.min(BOX_HEIGHT, contentHeight(this))
+ );
+ }
+ return rect(0, 0);
+ };
+ restoreRect = () => {
+ HTMLElement.prototype.getBoundingClientRect = original;
+ };
+ });
+
+ afterEach(() => {
+ restoreRect();
+ page.remove();
+ });
+
+ // Twelve rows, the failure last: a full box with the marked row parked at
+ // its bottom, which is the shape a failed log arrives in.
+ const mountFullBox = (blockHeight: number) => {
+ geometry.blockHeight = blockHeight;
+ const view = mount(
+ {
+ items: [
+ ...Array.from({ length: 11 }, (_, index) =>
+ ran(`ok-${index}`, `SELECT ${index};`)
+ ),
+ failed("last", MULTI_LINE, "ERROR: exists", { marked: true }),
+ ],
+ },
+ page
+ );
+ const box = view.scrollBox();
+ clampedScroll(box, () =>
+ Math.max(0, contentHeight(box) - Math.min(BOX_HEIGHT, contentHeight(box)))
+ );
+ // D13 parks the marked row: the last row, so at the bottom of the box.
+ box.scrollTop = 12 * ROW_HEIGHT;
+ return view;
+ };
+ const lineTop = (view: ReturnType<typeof mount>) =>
+ view.rowOf("ERROR: exists").getBoundingClientRect().top;
+ const boxTop = (view: ReturnType<typeof mount>) =>
+ view.scrollBox().getBoundingClientRect().top;
+ const toggleByError = (view: ReturnType<typeof mount>) =>
+ click(view.within(view.rowOf("ERROR: exists")).payload("error"));
+
+ test("unfolding a row whose block already fits scrolls nothing", () => {
+ geometry.blockHeight = 60;
+ const view = mount(
+ { items: [ran("a", "SELECT 1;"), failed("b", MULTI_LINE, "ERROR: exists")] },
+ page
+ );
+ clampedScroll(view.scrollBox(), () => 0);
+ const before = lineTop(view);
+
+ toggleByError(view);
+
+ expect(view.scrollBox().scrollTop).toBe(0);
+ expect(lineTop(view)).toBe(before);
+ expect(page.scrollTop).toBe(PAGE_START);
+
+ view.unmount();
+ });
+
+ test("unfolding the bottom row scrolls the section by exactly the block's overflow", () => {
+ const view = mountFullBox(100);
+ const before = lineTop(view);
+ expect(before).toBe(boxTop(view) + 9 * ROW_HEIGHT);
+
+ const parked = 12 * ROW_HEIGHT - BOX_HEIGHT;
+ expect(view.scrollBox().scrollTop).toBe(parked);
+
+ toggleByError(view);
+
+ expect(view.scrollBox().scrollTop).toBe(parked + 100);
+ expect(lineTop(view)).toBe(before - 100);
+ expect(page.scrollTop).toBe(PAGE_START);
+
+ view.unmount();
+ });
+
+ test("unfolding a row taller than the box puts its line at the box's top", () => {
+ const view = mountFullBox(640);
+
+ toggleByError(view);
+
+ expect(lineTop(view)).toBe(boxTop(view));
+ expect(page.scrollTop).toBe(PAGE_START);
+
+ view.unmount();
+ });
+
+ test("folding scrolls nothing itself: the line comes back to where it was clicked from", () => {
+ const view = mountFullBox(640);
+ const before = lineTop(view);
+
+ toggleByError(view);
+ expect(lineTop(view)).toBe(boxTop(view));
+ toggleByError(view);
+
+ expect(view.within(view.rowOf("ERROR: exists")).payload("block")).toBeNull();
+ expect(lineTop(view)).toBe(before);
+ expect(page.scrollTop).toBe(PAGE_START);
+
+ view.unmount();
+ });
+
+ test("a reveal in one section leaves another section's scroll alone", () => {
+ geometry.blockHeight = 640;
+ const TwoSections = () => {
+ const [overrides, setOverrides] = useState<ReadonlyMap<string, boolean>>(
+ () => new Map()
+ );
+ const onFoldChange = (key: string, open: boolean) =>
+ setOverrides((previous) => new Map(previous).set(key, open));
+ const items = (prefix: string) => [
+ ...Array.from({ length: 11 }, (_, index) =>
+ ran(`${prefix}-${index}`, `SELECT ${index};`)
+ ),
+ failed(`${prefix}-last`, MULTI_LINE, `ERROR: ${prefix}`),
+ ];
+ return createElement(
+ "div",
+ null,
+ createElement(SectionContent, {
+ section: { ...sectionOf(items("first")), id: "section-0" },
+ foldOverrides: overrides,
+ onFoldChange,
+ }),
+ createElement(SectionContent, {
+ section: { ...sectionOf(items("second")), id: "section-1" },
+ foldOverrides: overrides,
+ onFoldChange,
+ })
+ );
+ };
+ const container = document.createElement("div");
+ page.appendChild(container);
+ const root = createRoot(container);
+ act(() => root.render(createElement(TwoSections)));
+ const rowOf = (text: string) =>
+ Array.from(
+ container.querySelectorAll<HTMLElement>('[data-testid="task-run-log-row"]')
+ ).find((row) => row.textContent?.includes(text)) as HTMLElement;
+ const firstBox = rowOf("ERROR: first").parentElement as HTMLElement;
+ clampedScroll(firstBox, () => contentHeight(firstBox) - BOX_HEIGHT);
+ firstBox.scrollTop = 40;
+
+ click(rowOf("ERROR: second").querySelector('[data-log-payload="error"]'));
+ expect(firstBox.scrollTop).toBe(40);
+
+ // The first section's own unfold is revealed once. If the reader then
+ // scrolls that row back out of view, a toggle elsewhere must not reveal it
+ // again.
+ click(rowOf("ERROR: first").querySelector('[data-log-payload="error"]'));
+ const revealed = firstBox.scrollTop;
+ expect(revealed).toBeGreaterThan(40);
+ firstBox.scrollTop = 40;
+ click(rowOf("ERROR: second").querySelector('[data-log-payload="error"]'));
+ expect(firstBox.scrollTop).toBe(40);
+
+ act(() => root.unmount());
+ container.remove();
+ });
+});
+
+describe("SectionContent time cell", () => {
+ const cell = (view: ReturnType<typeof mount>, text: string) =>
+ Array.from(view.container.querySelectorAll("span")).find(
+ (span) => span.textContent === text
+ );
+
+ test("offers the full date only for a line that has an instant", () => {
+ const view = mount({
+ items: [
+ { ...ran("timed", "SELECT 1;"), time: "12:00:00.000", timeMs: Date.UTC(2026, 2, 2, 12) },
+ { ...ran("untimed", "SELECT 2;"), time: "--:--:--.---", timeMs: undefined },
+ { ...ran("impossible", "SELECT 3;"), time: "12:00:02.000", timeMs: 8.64e15 + 1 },
+ ],
+ });
+
+ // A tooltip with nothing to say renders its children bare, so the trigger
+ // it wraps them in is what says whether the full date is on offer.
+ expect(cell(view, "12:00:00.000")?.firstElementChild).not.toBeNull();
+ expect(cell(view, "--:--:--.---")?.firstElementChild).toBeNull();
+ // Finite, and past the last instant there is: no reading, so no tooltip.
+ expect(cell(view, "12:00:02.000")?.firstElementChild).toBeNull();
+
+ view.unmount();
+ });
+
+ test("the offered date is the line's own instant", () => {
+ // Which instant, not merely that there is one: a tooltip built from the
+ // wrong time reads as plausibly as the right one. The zone is pinned to
+ // Asia/Shanghai in vitest.config.ts, so noon UTC reads as 8pm.
+ vi.useFakeTimers();
+ const view = mount({
+ items: [
+ { ...ran("timed", "SELECT 1;"), time: "20:00:00.000", timeMs: Date.UTC(2026, 2, 2, 12) },
+ ],
+ });
+
+ act(() => {
+ cell(view, "20:00:00.000")?.firstElementChild?.dispatchEvent(
+ new FocusEvent("focusin", { bubbles: true })
+ );
+ vi.advanceTimersByTime(200);
+ });
+
+ const overlay = document.getElementById("bb-react-layer-overlay");
+ expect(overlay?.textContent).toContain("Mar 2, 2026");
+ expect(overlay?.textContent).toContain("8:00:00");
+
+ view.unmount();
+ vi.useRealTimers();
+ });
+});
diff --git a/frontend/src/components/task-run-log/SectionContent.tsx b/frontend/src/components/task-run-log/SectionContent.tsx
index b7060a5c32..3b30e2d629 100644
--- a/frontend/src/components/task-run-log/SectionContent.tsx
+++ b/frontend/src/components/task-run-log/SectionContent.tsx
@@ -1,11 +1,22 @@
-import { useEffect, useState } from "react";
+import { ChevronDown, ChevronRight } from "lucide-react";
+import {
+ type CSSProperties,
+ type MouseEvent,
+ useCallback,
+ useEffect,
+ useLayoutEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
import { useTranslation } from "react-i18next";
import { FullDateTime } from "@/components/HumanizeTs";
import { Button } from "@/components/ui/button";
+import { CopyButton } from "@/components/ui/copy-button";
import { Tooltip } from "@/components/ui/tooltip";
import { cn } from "@/lib/utils";
import { displayableInstantMs } from "@/utils/datetime";
-import type { Section } from "./types";
+import type { DisplayItem, Section } from "./types";
// The full reading is offered only for an instant the formatters can render.
const fullTime = (timeMs: number | undefined) => {
@@ -15,77 +26,240 @@ const fullTime = (timeMs: number | undefined) => {
);
};
-const ITEM_HEIGHT = 20;
+// A row is an `xs` control (24px) inside `py-0.5`.
+const ITEM_HEIGHT = 28;
const MAX_VISIBLE_ITEMS = 10;
const MAX_RENDERED_ITEMS = 50;
+// Fixed: an unfolded block scrolls inside the box rather than growing it, so
+// the sections below never move when a row is toggled.
+const MAX_HEIGHT = `${MAX_VISIBLE_ITEMS * ITEM_HEIGHT}px`;
+const INDEX_COLUMN_MIN_WIDTH = "24px";
+// Fits every relative time below 100 seconds ("+99.99s").
+const RELATIVE_TIME_COLUMN_MIN_CHARS = 7;
export interface SectionContentProps {
section: Section;
indent?: boolean;
datasetKey?: string;
+ // The reader's explicit folds, by row key. Held by the viewer because this
+ // component unmounts whenever its enclosing section collapses.
+ foldOverrides: ReadonlyMap<string, boolean>;
+ onFoldChange: (key: string, open: boolean) => void;
}
+interface Row {
+ item: DisplayItem;
+ // Position in the section, which the sparse window below does not preserve.
+ index: number;
+}
+
+// Nothing opens by default: the reader's folds are the only open state.
+const isOpen = (
+ item: DisplayItem,
+ foldOverrides: ReadonlyMap<string, boolean>
+): boolean => foldOverrides.get(item.key) ?? false;
+
+// A statement recovered from a sheet range is a split segment, which usually
+// begins with the line break that followed the previous statement.
+const trimBlankEdges = (statement: string): string =>
+ statement.replace(/^(?:[ \t]*\r?\n)+/, "").trimEnd();
+
+// A ref callback's body: track the element until React detaches it.
+const register = (
+ elements: Map<string, HTMLElement>,
+ key: string,
+ element: HTMLElement
+) => {
+ elements.set(key, element);
+ return () => {
+ elements.delete(key);
+ };
+};
+
+// An unfolded row near the bottom of the box opens its block below the visible
+// edge, where a click would seem to have done nothing. Scroll the box by the
+// least that shows the row: to its bottom edge when it fits, to its top edge —
+// the line at the top, the block filling the rest — when it is taller than the
+// box. The box's own scroll only: the block is clipped by the box, so a page
+// scroll could not reveal it and would only move the log under the reader.
+// Folding needs nothing: the browser's clamp puts the line back where the
+// reveal took it from.
+const revealRow = (box: HTMLElement, row: HTMLElement) => {
+ const boxRect = box.getBoundingClientRect();
+ const rowRect = row.getBoundingClientRect();
+ const overflow = rowRect.bottom - boxRect.bottom;
+ const headroom = rowRect.top - boxRect.top;
+ box.scrollTop += Math.max(0, Math.min(overflow, headroom));
+};
+
+const sameKeys = (a: ReadonlySet<string>, b: ReadonlySet<string>): boolean => {
+ if (a.size !== b.size) return false;
+ for (const key of a) {
+ if (!b.has(key)) return false;
+ }
+ return true;
+};
+
export function SectionContent({
section,
indent = false,
datasetKey,
+ foldOverrides,
+ onFoldChange,
}: SectionContentProps) {
const { t } = useTranslation();
const [showAllItems, setShowAllItems] = useState(false);
+ const [clampedKeys, setClampedKeys] = useState<ReadonlySet<string>>(
+ () => new Set()
+ );
+ const boxRef = useRef<HTMLDivElement>(null);
+ const rowElements = useRef(new Map<string, HTMLElement>());
+ const lineElements = useRef(new Map<string, HTMLElement>());
+ const registerRow = useCallback(
+ (key: string, element: HTMLElement) =>
+ register(rowElements.current, key, element),
+ []
+ );
+ const registerLine = useCallback(
+ (key: string, element: HTMLElement) =>
+ register(lineElements.current, key, element),
+ []
+ );
useEffect(() => {
setShowAllItems(false);
}, [datasetKey, section.id]);
- const visibleItems =
- showAllItems || section.items.length <= MAX_RENDERED_ITEMS
- ? section.items
- : section.items.slice(0, MAX_RENDERED_ITEMS);
- const hiddenItemCount = section.items.length - visibleItems.length;
+ // The first MAX_RENDERED_ITEMS rows, plus the marked row when it falls
+ // outside them: a failure at statement 300 must not wait behind "Load more".
+ const { head, tail } = useMemo(() => {
+ const rows: Row[] = section.items.map((item, index) => ({ item, index }));
+ if (showAllItems || rows.length <= MAX_RENDERED_ITEMS) {
+ return { head: rows, tail: [] };
+ }
+ const marked = rows.find(
+ (row) => row.item.marked && row.index >= MAX_RENDERED_ITEMS
+ );
+ return {
+ head: rows.slice(0, MAX_RENDERED_ITEMS),
+ tail: marked ? [marked] : [],
+ };
+ }, [section.items, showAllItems]);
+ const hiddenItemCount = section.items.length - head.length - tail.length;
+
+ const markedKey = useMemo(
+ () => section.items.find((item) => item.marked)?.key,
+ [section.items]
+ );
+
+ // Which lines their width clamps. A row with no line to measure is open, and
+ // keeps its verdict: it lost the line by opening, and dropping the verdict
+ // would take away the control that closes it.
+ const measureClampedLines = useCallback(() => {
+ setClampedKeys((previous) => {
+ const next = new Set<string>();
+ for (const key of previous) {
+ if (!lineElements.current.has(key) && rowElements.current.has(key)) {
+ next.add(key);
+ }
+ }
+ for (const [key, line] of lineElements.current) {
+ if (line.scrollWidth > line.clientWidth) next.add(key);
+ }
+ return sameKeys(previous, next) ? previous : next;
+ });
+ }, []);
+
+ useLayoutEffect(() => {
+ const box = boxRef.current;
+ if (!box) return;
+ const observer = new ResizeObserver(measureClampedLines);
+ observer.observe(box);
+ return () => observer.disconnect();
+ }, [measureClampedLines]);
+
+ // The box is capped, so rows arriving by "Load more" or a poll grow its
+ // scroll height and never resize it: the observer alone would miss them.
+ // The dependencies are everything that changes which lines are rendered or
+ // how wide they are.
+ useLayoutEffect(() => {
+ measureClampedLines();
+ }, [measureClampedLines, head, tail, foldOverrides, indent]);
+
+ // The row the reader just unfolded, revealed by the layout effect below
+ // once its block is laid out and before it is painted.
+ const unfoldedKey = useRef<string | undefined>(undefined);
+ const handleToggle = useCallback(
+ (key: string, open: boolean) => {
+ unfoldedKey.current = open ? key : undefined;
+ onFoldChange(key, open);
+ },
+ [onFoldChange]
+ );
+ // foldOverrides changes for a toggle in any section; only the section that
+ // recorded the unfold acts on it.
+ useLayoutEffect(() => {
+ const key = unfoldedKey.current;
+ unfoldedKey.current = undefined;
+ const box = boxRef.current;
+ const row = key ? rowElements.current.get(key) : undefined;
+ if (box && row) revealRow(box, row);
+ }, [foldOverrides]);
+
+ // Bring the marked row into view once, when the mark lands on it or on mount.
+ // The box's own scrollTop: scrollIntoView would also scroll the page under a
+ // reader who is looking at something else.
+ useLayoutEffect(() => {
+ const box = boxRef.current;
+ const row = markedKey ? rowElements.current.get(markedKey) : undefined;
+ if (!box || !row) return;
+ const top = row.offsetTop;
+ const isInView =
+ top >= box.scrollTop &&
+ top + row.offsetHeight <= box.scrollTop + box.clientHeight;
+ if (!isInView) box.scrollTop = top;
+ }, [markedKey]);
+
+ const rendered = [...head, ...tail];
+ // Both numeric columns are sized once, from the widest value this section
+ // draws. A per-row minimum would let one wide row push its own statement
+ // right of its neighbours'.
+ const indexChars = String((rendered.at(-1)?.index ?? 0) + 1).length;
+ const relativeTimeChars = rendered.reduce(
+ (widest, { item }) => Math.max(widest, item.relativeTime.length),
+ RELATIVE_TIME_COLUMN_MIN_CHARS
+ );
+
+ const renderRow = ({ item, index }: Row) => {
+ const open = isOpen(item, foldOverrides);
+ return (
+ <LogRow
+ key={item.key}
+ item={item}
+ index={index}
+ indent={indent}
+ open={open}
+ isClamped={clampedKeys.has(item.key)}
+ onToggle={() => handleToggle(item.key, !open)}
+ registerRow={registerRow}
+ registerLine={registerLine}
+ />
+ );
+ };
return (
<div
- className="overflow-auto border-block-border border-t bg-control-bg/50"
- style={{ maxHeight: `${MAX_VISIBLE_ITEMS * ITEM_HEIGHT}px` }}
+ ref={boxRef}
+ className="relative overflow-auto border-block-border border-t bg-control-bg/50"
+ style={
+ {
+ maxHeight: MAX_HEIGHT,
+ "--task-log-index-width": `max(${INDEX_COLUMN_MIN_WIDTH}, ${indexChars}ch)`,
+ "--task-log-time-width": `${relativeTimeChars}ch`,
+ } as CSSProperties
+ }
>
- {visibleItems.map((item, index) => (
- <div
- key={item.key}
- className={cn(
- "flex items-start gap-x-2 py-0.5 hover:bg-control-bg",
- indent ? "px-6" : "px-3",
- index > 0 && "border-block-border border-t"
- )}
- >
- <span className="w-6 shrink-0 text-right text-control-placeholder tabular-nums">
- {index + 1}
- </span>
- <span className="shrink-0 text-control-placeholder tabular-nums">
- <Tooltip content={fullTime(item.timeMs)}>{item.time}</Tooltip>
- </span>
- {item.relativeTime ? (
- <span className="shrink-0 text-control-placeholder tabular-nums">
- {item.relativeTime}
- </span>
- ) : null}
- <span className={cn("shrink-0", item.levelClass)}>
- {item.levelIndicator}
- </span>
- <span className={cn("min-w-0 break-words", item.detailClass)}>
- {item.detail}
- </span>
- <span className="ml-auto flex shrink-0 items-center gap-x-2">
- {item.duration ? (
- <span className="text-info tabular-nums">{item.duration}</span>
- ) : null}
- {item.affectedRows !== undefined ? (
- <span className="text-control-placeholder">
- {item.affectedRows} {t("task.affected-rows")}
- </span>
- ) : null}
- </span>
- </div>
- ))}
+ {head.map(renderRow)}
{hiddenItemCount > 0 ? (
<Button
type="button"
@@ -98,6 +272,185 @@ export function SectionContent({
<span className="tabular-nums">({hiddenItemCount})</span>
</Button>
) : null}
+ {tail.map(renderRow)}
+ </div>
+ );
+}
+
+interface LogRowProps {
+ item: DisplayItem;
+ index: number;
+ indent: boolean;
+ open: boolean;
+ isClamped: boolean;
+ onToggle: () => void;
+ registerRow: (key: string, element: HTMLElement) => () => void;
+ registerLine: (key: string, element: HTMLElement) => () => void;
+}
+
+const TEXT_CELL = "shrink-0 py-1 tabular-nums";
+
+function LogRow({
+ item,
+ index,
+ indent,
+ open,
+ isClamped,
+ onToggle,
+ registerRow,
+ registerLine,
+}: LogRowProps) {
+ const { t } = useTranslation();
+ const { statement, error } = item;
+ const showBlock = open && statement !== undefined;
+ const hasBothPayloads = statement !== undefined && error !== undefined;
+ const lineIsStatement = statement !== undefined && error === undefined;
+ // Unfolding must show something the line does not. With both payloads the
+ // line is the error, so the statement is never on it. Otherwise the line is
+ // the statement, and hides either its formatting or what its width cut off.
+ // An open row always qualifies: what was opened must be closable, and its
+ // clamp verdict does not survive this component remounting.
+ const isFoldable =
+ hasBothPayloads ||
+ (lineIsStatement &&
+ (open || statement.trim() !== item.detail || isClamped));
+ const copyStatement = () => statement ?? "";
+
+ // The whole line toggles, the statement and the error included, so a reader
+ // never has to learn which part of a row is live. The unfolded block does
+ // not: it is the content being read and selected from, and a double-click's
+ // first click — indistinguishable from a single one — would remove the very
+ // text being selected.
+ const handleRowClick = (event: MouseEvent<HTMLDivElement>) => {
+ const target = event.target as Element;
+ if (target.closest("button, [data-log-payload='block']")) return;
+ // A click that ends a drag, e.g. a selection swept across the clamped line.
+ if (!(window.getSelection()?.isCollapsed ?? true)) return;
+ onToggle();
+ };
+
+ return (
+ <div
+ ref={(element) => (element ? registerRow(item.key, element) : undefined)}
+ data-testid="task-run-log-row"
+ className={cn(
+ "group flex items-start gap-x-2 py-0.5 hover:bg-control-bg",
+ indent ? "px-6" : "px-3",
+ index > 0 && "border-block-border border-t",
+ isFoldable && "cursor-pointer"
+ )}
+ onClick={isFoldable ? handleRowClick : undefined}
+ >
+ <span
+ className={cn(
+ TEXT_CELL,
+ "w-(--task-log-index-width) text-right text-control-placeholder"
+ )}
+ >
+ {index + 1}
+ </span>
+ <span className={cn(TEXT_CELL, "text-control-placeholder")}>
+ <Tooltip content={fullTime(item.timeMs)}>{item.time}</Tooltip>
+ </span>
+ <span
+ className={cn(
+ TEXT_CELL,
+ "w-(--task-log-time-width) text-right text-control-placeholder"
+ )}
+ >
+ {item.relativeTime}
+ </span>
+ <span className={cn(TEXT_CELL, item.levelClass)}>
+ {item.levelIndicator}
+ </span>
+ {/* Reserved on every row so the statement column stays straight. */}
+ <span className="flex w-6 shrink-0 justify-center">
+ {isFoldable ? (
+ <Button
+ type="button"
+ appearance="secondary"
+ size="xs"
+ className="px-1 text-control-light hover:bg-control-bg-hover hover:text-control"
+ aria-expanded={showBlock}
+ aria-label={
+ showBlock
+ ? t("task-run.log-detail.hide-full-statement")
+ : t("task-run.log-detail.show-full-statement")
+ }
+ onClick={onToggle}
+ >
+ {showBlock ? (
+ <ChevronDown className="size-3.5" />
+ ) : (
+ <ChevronRight className="size-3.5" />
+ )}
+ </Button>
+ ) : null}
+ </span>
+ <div className="flex min-w-0 flex-1 flex-col items-start">
+ {error !== undefined ? (
+ <span
+ data-log-payload="error"
+ className={cn("max-w-full py-1 break-words", item.detailClass)}
+ >
+ {item.detail}
+ </span>
+ ) : statement === undefined ? (
+ <span className={cn("max-w-full py-1 break-words", item.detailClass)}>
+ {item.detail}
+ </span>
+ ) : showBlock ? null : (
+ <span
+ ref={(element) =>
+ element ? registerLine(item.key, element) : undefined
+ }
+ data-log-payload="line"
+ className={cn("max-w-full truncate py-1", item.detailClass)}
+ >
+ {item.detail}
+ </span>
+ )}
+ {showBlock ? (
+ <div
+ data-log-payload="block"
+ className={cn(
+ "flex w-full cursor-text items-start gap-x-2 rounded-sm border border-block-border bg-background py-1 pr-1 pl-2.5 text-control",
+ error !== undefined ? "mb-1" : "my-1"
+ )}
+ >
+ <span
+ data-log-sql
+ className="min-w-0 flex-1 py-1 whitespace-pre-wrap break-words"
+ >
+ {trimBlankEdges(statement)}
+ </span>
+ {/* Sticky to the section's scroll box, so a statement taller than
+ the box keeps its copy control in reach while it scrolls. */}
+ <span data-log-copy className="sticky top-1 shrink-0">
+ <CopyButton
+ content={copyStatement}
+ className="bg-control-bg text-control-light hover:bg-control-bg-hover hover:text-control"
+ />
+ </span>
+ </div>
+ ) : null}
+ </div>
+ <span className="ml-auto flex shrink-0 items-center gap-x-2">
+ {lineIsStatement && !showBlock ? (
+ <CopyButton
+ content={copyStatement}
+ className="bg-control-bg-hover text-control-light opacity-0 hover:text-control focus-visible:opacity-100 group-hover:opacity-100 pointer-coarse:opacity-100"
+ />
+ ) : null}
+ {item.duration ? (
+ <span className="py-1 text-info tabular-nums">{item.duration}</span>
+ ) : null}
+ {item.affectedRows !== undefined ? (
+ <span className="py-1 text-control-placeholder">
+ {item.affectedRows} {t("task.affected-rows")}
+ </span>
+ ) : null}
+ </span>
</div>
);
}
diff --git a/frontend/src/components/task-run-log/TaskRunLogViewer.test.tsx b/frontend/src/components/task-run-log/TaskRunLogViewer.test.tsx
index 83de4f69c9..1df6740878 100644
--- a/frontend/src/components/task-run-log/TaskRunLogViewer.test.tsx
+++ b/frontend/src/components/task-run-log/TaskRunLogViewer.test.tsx
@@ -1,12 +1,19 @@
+import { create } from "@bufbuild/protobuf";
import { CheckCircle2 } from "lucide-react";
-import { act, createElement } from "react";
+import { act, createElement, useSyncExternalStore } from "react";
import { createRoot } from "react-dom/client";
import { beforeEach, describe, expect, test, vi } from "vitest";
-import { TaskRunLogEntry_Type } from "@/types/proto-es/v1/rollout_service_pb";
-import { SectionContent } from "./SectionContent";
+import {
+ TaskRun_Status,
+ type TaskRunLogEntry,
+ TaskRunLogEntry_Type,
+ TaskRunLogEntrySchema,
+} from "@/types/proto-es/v1/rollout_service_pb";
import { TaskRunLogViewer } from "./TaskRunLogViewer";
-import type { Section } from "./types";
-import type { UseTaskRunLogSectionsOptions } from "./useTaskRunLogSections";
+import type {
+ UseTaskRunLogSectionsOptions,
+ useTaskRunLogSections,
+} from "./useTaskRunLogSections";
(
globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
@@ -15,6 +22,9 @@ import type { UseTaskRunLogSectionsOptions } from "./useTaskRunLogSections";
const mocks = vi.hoisted(() => ({
useTaskRunLogData: vi.fn(),
useTaskRunLogSections: vi.fn(),
+ actualUseTaskRunLogSections: undefined as
+ | typeof useTaskRunLogSections
+ | undefined,
}));
vi.mock("react-i18next", () => ({
@@ -63,8 +73,16 @@ vi.mock("./useTaskRunLogData", () => ({
useTaskRunLogData: mocks.useTaskRunLogData,
}));
-vi.mock("./useTaskRunLogSections", () => ({
- useTaskRunLogSections: mocks.useTaskRunLogSections,
+vi.mock("./useTaskRunLogSections", async (importOriginal) => {
+ const actual =
+ await importOriginal<typeof import("./useTaskRunLogSections")>();
+ mocks.actualUseTaskRunLogSections = actual.useTaskRunLogSections;
+ return { useTaskRunLogSections: mocks.useTaskRunLogSections };
+});
+
+// CopyButton reaches the app store, whose import chain is not available here.
+vi.mock("@/stores/app", () => ({
+ useAppStore: { getState: () => ({ notify: vi.fn() }) },
}));
const createDefaultData = () => ({
@@ -285,160 +303,260 @@ describe("TaskRunLogViewer", () => {
unmount();
});
+});
- test("offers the full date only for a line that has an instant", () => {
- const item = (key: string, time: string, timeMs: number | undefined) => ({
- key,
- time,
- timeMs,
- relativeTime: "",
- levelIndicator: "\u2713",
- levelClass: "text-green-600",
- detail: `ROW ${key}`,
- detailClass: "text-gray-600",
+describe("TaskRunLogViewer row folds", () => {
+ const SHOW = "task-run.log-detail.show-full-statement";
+ const HIDE = "task-run.log-detail.hide-full-statement";
+ const STATEMENT = "ALTER TABLE t\n ADD COLUMN c int;";
+ const ROW_HEIGHT = 28;
+
+ const ts = (seconds: number) => ({ seconds: BigInt(seconds), nanos: 0 });
+ const transaction = (seconds: number) =>
+ create(TaskRunLogEntrySchema, {
+ type: TaskRunLogEntry_Type.TRANSACTION_CONTROL,
+ logTime: ts(seconds),
+ transactionControl: {},
});
- const section: Section = {
- id: "section-0",
+ const command = (seconds: number, error: string, replicaId = "") =>
+ create(TaskRunLogEntrySchema, {
type: TaskRunLogEntry_Type.COMMAND_EXECUTE,
- label: "Command Execute",
- status: "success",
- statusIcon: CheckCircle2,
- statusClass: "text-green-600",
- duration: "2s",
- entryCount: 3,
- items: [
- item("timed", "12:00:00.000", Date.UTC(2026, 2, 2, 12)),
- item("untimed", "--:--:--.---", undefined),
- item("impossible", "12:00:02.000", 8.64e15 + 1),
- ],
- };
+ logTime: ts(seconds),
+ replicaId,
+ commandExecute: {
+ logTime: ts(seconds),
+ statement: STATEMENT,
+ response: { logTime: ts(seconds + 1), error },
+ },
+ });
- const { container, unmount } = renderIntoContainer(
- createElement(SectionContent, { section, datasetKey: "runs/1" })
+ // The viewer is memoized and a poll changes no prop, so new entries have to
+ // arrive the way they do in the product: through the data hook's own state.
+ const log = {
+ entries: [] as TaskRunLogEntry[],
+ listeners: new Set<() => void>(),
+ };
+ const subscribe = (listener: () => void) => {
+ log.listeners.add(listener);
+ return () => log.listeners.delete(listener);
+ };
+
+ const mountViewer = (
+ entries: TaskRunLogEntry[],
+ props: { taskRunStatus?: TaskRun_Status } = {}
+ ) => {
+ log.entries = entries;
+ const view = renderIntoContainer(
+ createElement(TaskRunLogViewer, { taskRunName: "runs/1", ...props })
);
+ const poll = (next: TaskRunLogEntry[]) =>
+ act(() => {
+ log.entries = next;
+ for (const listener of log.listeners) listener();
+ });
+ const switchTo = (taskRunName: string) =>
+ act(() => {
+ view.root.render(
+ createElement(TaskRunLogViewer, { ...props, taskRunName })
+ );
+ });
+ const foldControl = () =>
+ view.container.querySelector<HTMLButtonElement>(
+ `button[aria-label="${SHOW}"], button[aria-label="${HIDE}"]`
+ );
+ const block = () =>
+ view.container.querySelector<HTMLElement>('[data-log-payload="block"]');
+ const sectionHeader = (label: string) => {
+ const header = Array.from(
+ view.container.querySelectorAll<HTMLButtonElement>(
+ "button[aria-expanded]"
+ )
+ ).find((button) => button.textContent?.includes(label));
+ if (!header) throw new Error(`no section header "${label}"`);
+ return header;
+ };
+ return { ...view, poll, switchTo, foldControl, block, sectionHeader };
+ };
- // A tooltip with nothing to say renders its children bare, so the trigger
- // it wraps them in is what says whether the full date is on offer.
- const cell = (text: string) =>
- Array.from(container.querySelectorAll("span")).find(
- (span) => span.textContent === text
+ const click = (element: Element | null) => {
+ if (!element) throw new Error("nothing to click");
+ act(() => {
+ element.dispatchEvent(
+ new MouseEvent("click", { bubbles: true, cancelable: true })
);
- const timed = cell("12:00:00.000");
- expect(timed).toBeDefined();
- expect(cell("--:--:--.---")?.firstElementChild).toBeNull();
- // Finite, and past the last instant there is: no reading, so no tooltip.
- expect(cell("12:00:02.000")?.firstElementChild).toBeNull();
+ });
+ };
- unmount();
- });
+ const commandSection = String(TaskRunLogEntry_Type.COMMAND_EXECUTE);
- test("the offered date is the line's own instant", () => {
- // Which instant, not merely that there is one: a tooltip built from the
- // wrong time reads as plausibly as the right one. The zone is pinned to
- // Asia/Shanghai in vitest.config.ts, so noon UTC reads as 8pm.
- vi.useFakeTimers();
- const section: Section = {
- id: "section-0",
- type: TaskRunLogEntry_Type.COMMAND_EXECUTE,
- label: "Command Execute",
- status: "success",
- statusIcon: CheckCircle2,
- statusClass: "text-green-600",
- duration: "2s",
- entryCount: 1,
- items: [
- {
- key: "timed",
- time: "20:00:00.000",
- timeMs: Date.UTC(2026, 2, 2, 12),
- relativeTime: "",
- levelIndicator: "\u2713",
- levelClass: "text-green-600",
- detail: "ROW",
- detailClass: "text-gray-600",
- },
- ],
- };
+ beforeEach(() => {
+ log.listeners.clear();
+ mocks.useTaskRunLogData.mockImplementation(() => ({
+ ...createDefaultData(),
+ entries: useSyncExternalStore(subscribe, () => log.entries),
+ }));
+ const actual = mocks.actualUseTaskRunLogSections;
+ if (!actual) throw new Error("the sections hook was never imported");
+ mocks.useTaskRunLogSections.mockImplementation(
+ (options: UseTaskRunLogSectionsOptions) =>
+ actual({ ...options, getSectionLabel: (type) => String(type) })
+ );
+ });
- const { container, unmount } = renderIntoContainer(
- createElement(SectionContent, { section, datasetKey: "runs/1" })
+ test("forwards the run's status to the section builder", () => {
+ const actual = mocks.actualUseTaskRunLogSections;
+ let forwarded: TaskRun_Status | undefined;
+ mocks.useTaskRunLogSections.mockImplementation(
+ (options: UseTaskRunLogSectionsOptions) => {
+ forwarded = options.taskRunStatus;
+ return actual?.({ ...options, getSectionLabel: (type) => String(type) });
+ }
);
- act(() => {
- Array.from(container.querySelectorAll("span"))
- .find((span) => span.textContent === "20:00:00.000")
- ?.firstElementChild?.dispatchEvent(
- new FocusEvent("focusin", { bubbles: true })
- );
- vi.advanceTimersByTime(200);
+ const view = mountViewer([command(1, "ERROR: exists")], {
+ taskRunStatus: TaskRun_Status.DONE,
});
- const overlay = document.getElementById("bb-react-layer-overlay");
- expect(overlay?.textContent).toContain("Mar 2, 2026");
- expect(overlay?.textContent).toContain("8:00:00");
+ expect(forwarded).toBe(TaskRun_Status.DONE);
- unmount();
- vi.useRealTimers();
+ view.unmount();
});
- test("renders a load more action for large sections", () => {
- const largeSection: Section = {
- id: "section-0",
- type: TaskRunLogEntry_Type.COMMAND_EXECUTE,
- label: "Command Execute",
- status: "success",
- statusIcon: CheckCircle2,
- statusClass: "text-green-600",
- duration: "2s",
- entryCount: 60,
- items: Array.from({ length: 60 }, (_, index) => ({
- key: `item-${index}`,
- time: `12:00:${String(index).padStart(2, "0")}.000`,
- timeMs: new Date("2026-03-02T12:00:00Z").getTime() + index * 1000,
- relativeTime: "",
- levelIndicator: "✓",
- levelClass: "text-green-600",
- detail: `ROW ${index}`,
- detailClass: "text-gray-600",
- })),
- };
+ test("a failed row starts folded, and one the reader unfolds stays so through collapsing its section", () => {
+ const view = mountViewer([
+ transaction(1),
+ command(2, "ERROR: exists"),
+ transaction(4),
+ ]);
+
+ expect(view.block()).toBeNull();
+ click(view.foldControl());
+ expect(view.block()).not.toBeNull();
+
+ click(view.sectionHeader(commandSection));
+ expect(view.foldControl()).toBeNull();
+ click(view.sectionHeader(commandSection));
+
+ expect(view.foldControl()?.getAttribute("aria-expanded")).toBe("true");
+ expect(view.block()).not.toBeNull();
+
+ view.unmount();
+ });
+
+ test("a row unfolded by clicking its statement stays unfolded through collapsing its section", () => {
+ const view = mountViewer([transaction(1), command(2, ""), transaction(4)]);
+ const line = () =>
+ view.container.querySelector<HTMLElement>('[data-log-payload="line"]');
+
+ click(view.sectionHeader(commandSection));
+ expect(view.block()).toBeNull();
+ click(line());
+ expect(view.block()?.textContent).toContain("ADD COLUMN c int;");
+
+ click(view.sectionHeader(commandSection));
+ expect(line()).toBeNull();
+ click(view.sectionHeader(commandSection));
+
+ expect(view.block()?.textContent).toContain("ADD COLUMN c int;");
+ expect(view.foldControl()?.getAttribute("aria-expanded")).toBe("true");
+
+ view.unmount();
+ });
- const { container, root, unmount } = renderIntoContainer(
- createElement(SectionContent, {
- section: largeSection,
- datasetKey: "runs/1",
- })
+ test("an unfolded row stays unfolded when the sole section gives way to the section tree", () => {
+ const view = mountViewer([command(2, "ERROR: exists")]);
+
+ expect(view.container.querySelector("button[aria-expanded]")).toBe(
+ view.foldControl()
);
+ click(view.foldControl());
+ expect(view.block()).not.toBeNull();
- expect(container.textContent).toContain("common.load-more");
- expect(container.textContent).toContain("ROW 0");
- expect(container.textContent).not.toContain("ROW 59");
+ view.poll([command(2, "ERROR: exists"), transaction(4)]);
- const loadMoreButton = Array.from(
- container.querySelectorAll("button")
- ).find((button) => button.textContent?.includes("common.load-more"));
- expect(loadMoreButton).toBeDefined();
+ expect(view.sectionHeader(commandSection)).toBeDefined();
+ expect(view.foldControl()?.getAttribute("aria-expanded")).toBe("true");
+ expect(view.block()).not.toBeNull();
- act(() => {
- loadMoreButton?.dispatchEvent(
- new MouseEvent("click", { bubbles: true, cancelable: true })
- );
- });
+ view.unmount();
+ });
- expect(container.textContent).toContain("ROW 59");
+ test("an unfolded row stays unfolded when a second replica appears", () => {
+ const view = mountViewer([command(2, "ERROR: exists", "replica-a")]);
- act(() => {
- root.render(
- createElement(SectionContent, {
- section: largeSection,
- datasetKey: "runs/2",
- })
- );
- });
+ click(view.foldControl());
+ expect(view.block()).not.toBeNull();
- expect(container.textContent).toContain("common.load-more");
- expect(container.textContent).not.toContain("ROW 59");
+ view.poll([
+ command(2, "ERROR: exists", "replica-a"),
+ command(6, "", "replica-b"),
+ ]);
- unmount();
+ expect(view.container.textContent).toContain(
+ "task-run.log-viewer.multiple-replicas-notice"
+ );
+ expect(view.block()?.textContent).toContain("ADD COLUMN c int;");
+
+ view.unmount();
+ });
+
+ test("a different task run starts with no folds", () => {
+ const view = mountViewer([command(2, "ERROR: exists")]);
+
+ click(view.foldControl());
+ expect(view.block()).not.toBeNull();
+
+ view.switchTo("runs/2");
+ expect(view.block()).toBeNull();
+
+ view.unmount();
+ });
+
+ test("a failure arriving into a collapsed section leaves it collapsed, then is scrolled to", () => {
+ const offsetTop = vi
+ .spyOn(HTMLElement.prototype, "offsetTop", "get")
+ .mockImplementation(function (this: HTMLElement) {
+ const siblings = Array.from(this.parentElement?.children ?? []);
+ return siblings.indexOf(this) * ROW_HEIGHT;
+ });
+ const offsetHeight = vi
+ .spyOn(HTMLElement.prototype, "offsetHeight", "get")
+ .mockReturnValue(ROW_HEIGHT);
+ const clientHeight = vi
+ .spyOn(HTMLElement.prototype, "clientHeight", "get")
+ .mockReturnValue(10 * ROW_HEIGHT);
+
+ const succeeded = Array.from({ length: 20 }, (_, index) =>
+ command(10 + index * 2, "")
+ );
+ const view = mountViewer([transaction(1), ...succeeded]);
+
+ // Opened, then shut, by the reader.
+ click(view.sectionHeader(commandSection));
+ click(view.sectionHeader(commandSection));
+ expect(
+ view.sectionHeader(commandSection).getAttribute("aria-expanded")
+ ).toBe("false");
+
+ view.poll([transaction(1), ...succeeded, command(60, "ERROR: exists")]);
+ expect(
+ view.sectionHeader(commandSection).getAttribute("aria-expanded")
+ ).toBe("false");
+ expect(view.block()).toBeNull();
+
+ click(view.sectionHeader(commandSection));
+ // Brought into view, and still folded: opening it is the reader's move.
+ const failedRow = Array.from(
+ view.container.querySelectorAll<HTMLElement>(
+ '[data-testid="task-run-log-row"]'
+ )
+ ).find((row) => row.textContent?.includes("ERROR: exists"));
+ expect(failedRow?.parentElement?.scrollTop).toBe(20 * ROW_HEIGHT);
+ expect(view.block()).toBeNull();
+
+ offsetTop.mockRestore();
+ offsetHeight.mockRestore();
+ clientHeight.mockRestore();
+ view.unmount();
});
});
diff --git a/frontend/src/components/task-run-log/TaskRunLogViewer.tsx b/frontend/src/components/task-run-log/TaskRunLogViewer.tsx
index 46b3c8aa4d..5d22743063 100644
--- a/frontend/src/components/task-run-log/TaskRunLogViewer.tsx
+++ b/frontend/src/components/task-run-log/TaskRunLogViewer.tsx
@@ -9,6 +9,7 @@ import {
import { memo, useCallback, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
+import { useSeededState } from "@/hooks/useSeededState";
import {
type TaskRun_Status,
TaskRunLogEntry_Type,
@@ -46,6 +47,19 @@ export const TaskRunLogViewer = memo(function TaskRunLogViewer({
active
);
+ // The reader's explicit row folds. They live here, above every conditional
+ // SectionContent mount, so collapsing a section or the sole-section layout
+ // giving way to the section tree does not discard them. A new run starts
+ // clean, as does a new phase: both deploy surfaces key this viewer on status.
+ const [foldOverrides, setFoldOverrides] = useSeededState<
+ ReadonlyMap<string, boolean>
+ >(taskRunName, () => new Map());
+ const handleFoldChange = useCallback(
+ (key: string, open: boolean) =>
+ setFoldOverrides((previous) => new Map(previous).set(key, open)),
+ [setFoldOverrides]
+ );
+
const getSectionLabel = useCallback(
(type: TaskRunLogEntry_Type) => {
const labelMap: Partial<Record<TaskRunLogEntry_Type, string>> = {
@@ -119,6 +133,7 @@ export const TaskRunLogViewer = memo(function TaskRunLogViewer({
getSectionLabel,
detailText,
datasetKey: taskRunName,
+ taskRunStatus,
});
const hasRenderableReleaseFiles =
@@ -164,7 +179,12 @@ export const TaskRunLogViewer = memo(function TaskRunLogViewer({
</span>
) : null}
</div>
- <SectionContent section={soleSection} datasetKey={taskRunName} />
+ <SectionContent
+ section={soleSection}
+ datasetKey={taskRunName}
+ foldOverrides={foldOverrides}
+ onFoldChange={handleFoldChange}
+ />
</div>
</div>
);
@@ -197,6 +217,8 @@ export const TaskRunLogViewer = memo(function TaskRunLogViewer({
section={section}
indent={indent}
datasetKey={taskRunName}
+ foldOverrides={foldOverrides}
+ onFoldChange={handleFoldChange}
/>
) : null}
</div>
diff --git a/frontend/src/components/task-run-log/model.test.ts b/frontend/src/components/task-run-log/model.test.ts
index 761ea57058..f66f0bf01b 100644
--- a/frontend/src/components/task-run-log/model.test.ts
+++ b/frontend/src/components/task-run-log/model.test.ts
@@ -3,13 +3,16 @@ import { act, createElement } from "react";
import { createRoot } from "react-dom/client";
import { describe, expect, test, vi } from "vitest";
import {
+ TaskRun_Status,
type TaskRunLogEntry,
TaskRunLogEntry_PriorBackup_PriorBackupDetail_ItemSchema,
TaskRunLogEntry_Type,
TaskRunLogEntrySchema,
} from "@/types/proto-es/v1/rollout_service_pb";
-import type { Sheet } from "@/types/proto-es/v1/sheet_service_pb";
+import { type Sheet, SheetSchema } from "@/types/proto-es/v1/sheet_service_pb";
import {
+ assignEntryKeys,
+ type BuildSectionsOptions,
buildReleaseFileGroups,
buildSectionsFromEntries,
groupEntriesByReleaseFile,
@@ -43,7 +46,88 @@ vi.mock("@/utils", () => ({
sheetNameOfTaskV1: () => "",
}));
-const ts = (seconds: number) => ({ seconds: BigInt(seconds), nanos: 0 });
+const ts = (seconds: number, nanos = 0) => ({
+ seconds: BigInt(seconds),
+ nanos,
+});
+
+const buildSections = (
+ entries: TaskRunLogEntry[],
+ options?: Partial<BuildSectionsOptions>
+) =>
+ buildSectionsFromEntries(entries, {
+ getSectionLabel: (type) => String(type),
+ entryKeys: assignEntryKeys(entries),
+ ...options,
+ });
+
+interface CommandOptions {
+ statement?: string;
+ range?: { start: number; end: number };
+ // Omit for a command still running; "" for one that succeeded.
+ error?: string;
+ replicaId?: string;
+ nanos?: number;
+}
+
+const command = (seconds: number, options: CommandOptions = {}) =>
+ create(TaskRunLogEntrySchema, {
+ type: TaskRunLogEntry_Type.COMMAND_EXECUTE,
+ logTime: ts(seconds, options.nanos),
+ replicaId: options.replicaId ?? "",
+ commandExecute: {
+ logTime: ts(seconds, options.nanos),
+ statement: options.statement ?? "",
+ range: options.range,
+ response:
+ options.error === undefined
+ ? undefined
+ : { logTime: ts(seconds + 1), error: options.error },
+ },
+ });
+
+const transaction = (seconds: number, replicaId = "") =>
+ create(TaskRunLogEntrySchema, {
+ type: TaskRunLogEntry_Type.TRANSACTION_CONTROL,
+ logTime: ts(seconds),
+ replicaId,
+ transactionControl: {},
+ });
+
+const retryMarker = (seconds: number, replicaId = "") =>
+ create(TaskRunLogEntrySchema, {
+ type: TaskRunLogEntry_Type.RETRY_INFO,
+ logTime: ts(seconds),
+ replicaId,
+ retryInfo: { error: "lock timeout", retryCount: 1, maximumRetries: 3 },
+ });
+
+const releaseFile = (
+ seconds: number,
+ version: string,
+ options: { replicaId?: string; nanos?: number } = {}
+) =>
+ create(TaskRunLogEntrySchema, {
+ type: TaskRunLogEntry_Type.RELEASE_FILE_EXECUTE,
+ logTime: ts(seconds, options.nanos),
+ replicaId: options.replicaId ?? "",
+ releaseFileExecute: { version, filePath: `${version}.sql` },
+ });
+
+const sheetOf = (content: string, contentSize?: number): Sheet => {
+ const bytes = new TextEncoder().encode(content);
+ return create(SheetSchema, {
+ content: bytes,
+ contentSize: BigInt(contentSize ?? bytes.byteLength),
+ });
+};
+
+const markedDetails = (
+ sections: { items: { marked?: boolean; detail: string }[] }[]
+) =>
+ sections.flatMap((section) =>
+ section.items.filter((item) => item.marked).map((item) => item.detail)
+ );
(
globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
).IS_REACT_ACT_ENVIRONMENT = true;
@@ -51,6 +135,7 @@ const ts = (seconds: number) => ({ seconds: BigInt(seconds), nanos: 0 });
interface HookHarnessProps {
entries: TaskRunLogEntry[];
datasetKey?: string;
+ taskRunStatus?: TaskRun_Status;
}
const createHookHarness = (initialProps: HookHarnessProps) => {
@@ -62,6 +147,7 @@ const createHookHarness = (initialProps: HookHarnessProps) => {
current = useTaskRunLogSections({
entries: props.entries,
datasetKey: props.datasetKey,
+ taskRunStatus: props.taskRunStatus,
getSectionLabel: (type) => String(type),
});
return null;
@@ -200,7 +286,10 @@ describe("task-run-log model", () => {
];
expect(hasReleaseFileMarkers(entries)).toBe(true);
- const groups = buildReleaseFileGroups(entries);
+ const groups = buildReleaseFileGroups(entries, {
+ getSectionLabel: (type) => String(type),
+ entryKeys: assignEntryKeys(entries),
+ });
expect(groups).toHaveLength(2);
expect(groups[0]).toMatchObject({
id: "file-0",
@@ -230,9 +319,7 @@ describe("task-run-log model", () => {
}),
];
- const sections = buildSectionsFromEntries(entries, {
- getSectionLabel: (type) => String(type),
- });
+ const sections = buildSections(entries);
expect(sections[0]?.status).toBe("running");
expect(sections[1]?.status).toBe("error");
@@ -241,20 +328,17 @@ describe("task-run-log model", () => {
test("gives a line with no log time no instant to show", () => {
// The line still reads as a row -- its time column says so -- but there is
// no instant behind it, and a zero would have been an instant.
- const sections = buildSectionsFromEntries(
- [
- create(TaskRunLogEntrySchema, {
- type: TaskRunLogEntry_Type.COMMAND_EXECUTE,
- logTime: ts(10),
- commandExecute: {},
- }),
- create(TaskRunLogEntrySchema, {
- type: TaskRunLogEntry_Type.COMMAND_EXECUTE,
- commandExecute: {},
- }),
- ],
- { getSectionLabel: (type) => String(type) }
- );
+ const sections = buildSections([
+ create(TaskRunLogEntrySchema, {
+ type: TaskRunLogEntry_Type.COMMAND_EXECUTE,
+ logTime: ts(10),
+ commandExecute: {},
+ }),
+ create(TaskRunLogEntrySchema, {
+ type: TaskRunLogEntry_Type.COMMAND_EXECUTE,
+ commandExecute: {},
+ }),
+ ]);
// Which line got which instant, not how many of each: one undefined and
// one number is also what swapping them produces.
@@ -296,10 +380,7 @@ describe("task-run-log model", () => {
}),
];
- const sections = buildSectionsFromEntries(entries, {
- getSectionLabel: (type) => String(type),
- detailText,
- });
+ const sections = buildSections(entries, { detailText });
expect(sections[0]?.status).toBe("success");
expect(sections[0]?.duration).toBe("3.0s");
@@ -362,10 +443,7 @@ describe("task-run-log model", () => {
}),
];
- const sections = buildSectionsFromEntries(entries, {
- getSectionLabel: (type) => String(type),
- detailText,
- });
+ const sections = buildSections(entries, { detailText });
expect(sections[0]?.items[0]?.detail).toBe("Completed");
expect(sections[1]?.items[0]?.detail).toBe("Completed (2 tables)");
@@ -426,6 +504,7 @@ describe("task-run-log model", () => {
const groups = buildReleaseFileGroups(entries, {
getSectionLabel: (type) => String(type),
+ entryKeys: assignEntryKeys(entries),
includeOrphanGroup: true,
});
expect(groups).toHaveLength(2);
@@ -519,3 +598,311 @@ describe("task-run-log model", () => {
hook.unmount();
});
});
+
+describe("command row payloads", () => {
+ const formatted =
+ "\nCREATE TABLE public.loan_application (\n id bigint PRIMARY KEY,\n application_no text NOT NULL\n);\n";
+
+ test("a multi-line statement yields a one-line detail and a verbatim statement", () => {
+ const item = buildSections([
+ command(1, { statement: formatted, error: "" }),
+ ])[0]?.items[0];
+
+ expect(item?.detail).toBe(
+ "CREATE TABLE public.loan_application ( id bigint PRIMARY KEY, application_no text NOT NULL );"
+ );
+ expect(item?.statement).toBe(formatted);
+ expect(item?.error).toBeUndefined();
+ });
+
+ test("a statement past 80 characters is not cut", () => {
+ const long = `SELECT ${"column_name, ".repeat(20)}1;`;
+ const item = buildSections([command(1, { statement: long, error: "" })])[0]
+ ?.items[0];
+
+ expect(long.length).toBeGreaterThan(80);
+ expect(item?.detail).toBe(long);
+ });
+
+ test("a failed command keeps the error as its line and still carries the statement", () => {
+ const item = buildSections([
+ command(1, { statement: formatted, error: "ERROR: relation exists" }),
+ ])[0]?.items[0];
+
+ expect(item?.detail).toBe("ERROR: relation exists");
+ expect(item?.error).toBe("ERROR: relation exists");
+ expect(item?.statement).toBe(formatted);
+ });
+
+ test("a failed command recovers its statement from the sheet range", () => {
+ const content = "SELECT 1;\nALTER TABLE t\n ADD COLUMN c int;";
+ const item = buildSections(
+ [
+ command(1, {
+ range: { start: 9, end: content.length },
+ error: "ERROR: column exists",
+ }),
+ ],
+ { sheet: sheetOf(content) }
+ )[0]?.items[0];
+
+ expect(item?.detail).toBe("ERROR: column exists");
+ expect(item?.statement).toBe("\nALTER TABLE t\n ADD COLUMN c int;");
+ });
+
+ test("an entry with no statement yields a dash and no payload", () => {
+ const item = buildSections([command(1, { error: "" })])[0]?.items[0];
+
+ expect(item?.detail).toBe("-");
+ expect(item?.statement).toBeUndefined();
+ expect(item?.error).toBeUndefined();
+ });
+
+ test("a range reaching past a partial sheet recovers nothing", () => {
+ const item = buildSections(
+ [command(1, { range: { start: 0, end: 40 }, error: "" })],
+ { sheet: sheetOf("SELECT 1;", 40) }
+ )[0]?.items[0];
+
+ expect(item?.detail).toBe("-");
+ expect(item?.statement).toBeUndefined();
+ });
+
+ test("entries that carry status words return the detail alone", () => {
+ const sections = buildSections([transaction(1), retryMarker(2)]);
+
+ for (const section of sections) {
+ expect(section.items[0]?.statement).toBeUndefined();
+ expect(section.items[0]?.error).toBeUndefined();
+ }
+ });
+});
+
+describe("the row that opens by default", () => {
+ const attempt = (start: number, error: string) => [
+ transaction(start),
+ command(start + 1, { statement: "ALTER TABLE t ADD COLUMN c int;", error }),
+ transaction(start + 3),
+ ];
+
+ test("a failure the driver retried successfully marks nothing", () => {
+ const sections = buildSections([
+ ...attempt(1, "lock timeout"),
+ retryMarker(5),
+ ...attempt(6, ""),
+ ]);
+
+ // The failure is the last entry of its own section, which is why the pick
+ // cannot be section-local.
+ expect(sections[1]?.items.at(-1)?.error).toBe("lock timeout");
+ expect(markedDetails(sections)).toEqual([]);
+ });
+
+ test("a retry that fails again marks only the last failure", () => {
+ const sections = buildSections([
+ ...attempt(1, "lock timeout"),
+ retryMarker(5),
+ ...attempt(6, "lock timeout again"),
+ ]);
+
+ expect(markedDetails(sections)).toEqual(["lock timeout again"]);
+ });
+
+ test("a live failure already followed by the retry marker is not terminal", () => {
+ const sections = buildSections([
+ ...attempt(1, "lock timeout"),
+ retryMarker(5),
+ ]);
+
+ expect(markedDetails(sections)).toEqual([]);
+ });
+
+ test("a failure followed by a command that succeeded marks nothing", () => {
+ // No retry marker here: the later success alone says the run moved on.
+ const sections = buildSections([
+ command(1, { statement: "SELECT 1;", error: "boom" }),
+ command(3, { statement: "SELECT 2;", error: "" }),
+ ]);
+
+ expect(markedDetails(sections)).toEqual([]);
+ });
+
+ test("a command still running after a failure does not supersede it", () => {
+ const sections = buildSections([
+ command(1, { statement: "SELECT 1;", error: "boom" }),
+ command(3, { statement: "SELECT 2;" }),
+ ]);
+
+ expect(markedDetails(sections)).toEqual(["boom"]);
+ });
+
+ test("a failure with nothing after it is marked", () => {
+ const sections = buildSections([
+ command(1, { statement: "SELECT 1;", error: "" }),
+ command(3, { statement: "SELECT 2;", error: "boom" }),
+ ]);
+
+ expect(markedDetails(sections)).toEqual(["boom"]);
+ });
+
+ test("a failure with no recoverable statement is still marked", () => {
+ const sections = buildSections([command(1, { error: "boom" })]);
+
+ expect(sections[0]?.items[0]).toMatchObject({
+ detail: "boom",
+ marked: true,
+ });
+ expect(sections[0]?.items[0]?.statement).toBeUndefined();
+ });
+
+ test("a DONE run marks nothing, whatever the entries say", () => {
+ const sections = buildSections(
+ [command(1, { statement: "SELECT 1;", error: "serialization failure" })],
+ { taskRunStatus: TaskRun_Status.DONE }
+ );
+
+ expect(markedDetails(sections)).toEqual([]);
+ });
+
+ test("one replica's success does not silence another replica's failure", () => {
+ const hook = createHookHarness({
+ entries: [
+ command(1, { statement: "SELECT 1;", error: "boom", replicaId: "a" }),
+ command(3, { statement: "SELECT 1;", error: "", replicaId: "b" }),
+ ],
+ datasetKey: "replicas",
+ });
+
+ const [first, second] = hook.getCurrent().replicaGroups;
+ expect(markedDetails(first?.sections ?? [])).toEqual(["boom"]);
+ expect(markedDetails(second?.sections ?? [])).toEqual([]);
+
+ hook.unmount();
+ });
+
+ test("the hook forwards a DONE status into every builder it calls", () => {
+ const failing = (replicaId: string) => [
+ command(1, { statement: "SELECT 0;", error: "orphan", replicaId }),
+ releaseFile(3, "v1", { replicaId }),
+ command(4, { statement: "SELECT 1;", error: "in file", replicaId }),
+ ];
+ const entries = [...failing("a"), ...failing("b")];
+ const allSections = (result: UseTaskRunLogSectionsResult) => [
+ ...result.sections,
+ ...result.releaseFileGroups.flatMap((group) => group.sections),
+ ...result.replicaGroups.flatMap((group) => [
+ ...group.sections,
+ ...group.releaseFileGroups.flatMap((fileGroup) => fileGroup.sections),
+ ]),
+ ];
+
+ const hook = createHookHarness({ entries, datasetKey: "done-guard" });
+ // Flat, release-file, orphan, per-replica orphan and per-replica file.
+ expect(
+ markedDetails(allSections(hook.getCurrent())).length
+ ).toBeGreaterThan(4);
+
+ hook.render({
+ entries,
+ datasetKey: "done-guard",
+ taskRunStatus: TaskRun_Status.DONE,
+ });
+ expect(markedDetails(allSections(hook.getCurrent()))).toEqual([]);
+
+ hook.unmount();
+ });
+});
+
+describe("row identity", () => {
+ // The SDL shape: the statement is logged instead of a range, so tied entries
+ // have no byte offset to tell them apart.
+ const tied = (statement: string) =>
+ command(5, { statement, error: "", nanos: 123456789, replicaId: "a" });
+
+ test("entries sharing a replica, a timestamp and a type get distinct keys", () => {
+ const items = buildSections([tied("SELECT 1;"), tied("SELECT 2;")])[0]
+ ?.items;
+
+ expect(items).toHaveLength(2);
+ expect(items?.[0]?.key).not.toBe(items?.[1]?.key);
+ });
+
+ test("tied entries in different release files get distinct keys", () => {
+ const entries = [
+ releaseFile(1, "v1"),
+ tied("SELECT 1;"),
+ releaseFile(5, "v2", { nanos: 123456789 }),
+ tied("SELECT 2;"),
+ ];
+ const groups = buildReleaseFileGroups(entries, {
+ getSectionLabel: (type) => String(type),
+ entryKeys: assignEntryKeys(entries),
+ });
+
+ expect(groups).toHaveLength(2);
+ const [first, second] = groups.map(
+ (group) => group.sections[0]?.items[0]?.key
+ );
+ expect(first).toBeDefined();
+ expect(first).not.toBe(second);
+ });
+
+ test("sub-millisecond log times are told apart", () => {
+ const items = buildSections([
+ command(5, { statement: "SELECT 1;", error: "", nanos: 100 }),
+ command(5, { statement: "SELECT 2;", error: "", nanos: 200 }),
+ ])[0]?.items;
+
+ expect(items?.[0]?.key).not.toBe(items?.[1]?.key);
+ expect(items?.[0]?.key.endsWith(":0")).toBe(true);
+ expect(items?.[1]?.key.endsWith(":0")).toBe(true);
+ });
+
+ test("a builder refuses entries that were never given a key", () => {
+ const stranger = command(1, { statement: "SELECT 1;", error: "" });
+
+ expect(() =>
+ buildSectionsFromEntries([stranger], {
+ getSectionLabel: (type) => String(type),
+ entryKeys: assignEntryKeys([]),
+ })
+ ).toThrow();
+ });
+
+ test("a row's key survives a second replica appearing", () => {
+ const first = () =>
+ command(1, { statement: "SELECT 1;", error: "", replicaId: "a" });
+ const hook = createHookHarness({ entries: [first()], datasetKey: "run" });
+ const before = hook.getCurrent().sections[0]?.items[0]?.key;
+
+ hook.render({
+ entries: [
+ first(),
+ command(3, { statement: "SELECT 1;", error: "", replicaId: "b" }),
+ ],
+ datasetKey: "run",
+ });
+
+ expect(hook.getCurrent().hasMultipleReplicas).toBe(true);
+ const after =
+ hook.getCurrent().replicaGroups[0]?.sections[0]?.items[0]?.key;
+ expect(before).toBeDefined();
+ expect(after).toBe(before);
+
+ hook.unmount();
+ });
+
+ test("a row's key survives a retry marker splitting its section", () => {
+ const commands = () => [
+ command(1, { statement: "SELECT 1;", error: "" }),
+ command(5, { statement: "SELECT 2;", error: "" }),
+ ];
+ const before = buildSections(commands());
+ expect(before).toHaveLength(1);
+
+ const after = buildSections([...commands(), retryMarker(3)]);
+ expect(after).toHaveLength(3);
+ expect(after[2]?.items[0]?.key).toBe(before[0]?.items[1]?.key);
+ expect(after[0]?.items[0]?.key).toBe(before[0]?.items[0]?.key);
+ });
+});
diff --git a/frontend/src/components/task-run-log/model.ts b/frontend/src/components/task-run-log/model.ts
index 72325f3d82..958902e9a9 100644
--- a/frontend/src/components/task-run-log/model.ts
+++ b/frontend/src/components/task-run-log/model.ts
@@ -3,6 +3,7 @@ import type { LucideIcon } from "lucide-react";
import { CheckCircle2, Circle, LoaderCircle, XCircle } from "lucide-react";
import type { TaskRunLogEntry } from "@/types/proto-es/v1/rollout_service_pb";
import {
+ TaskRun_Status,
TaskRunLogEntry_TransactionControl_Type,
TaskRunLogEntry_Type,
} from "@/types/proto-es/v1/rollout_service_pb";
@@ -26,24 +27,33 @@ const STATUS_CONFIG: Record<
pending: { icon: Circle, className: "text-control-placeholder" },
};
+// Row keys for one run, from assignEntryKeys.
+export type EntryKeys = ReadonlyMap<TaskRunLogEntry, string>;
+
export interface BuildSectionsOptions {
getSectionLabel: (type: TaskRunLogEntry_Type) => string;
+ // Assigned over the run's whole entry list. The builders only ever see a
+ // filtered slice of it, so they cannot assign keys themselves.
+ entryKeys: EntryKeys;
sheet?: Sheet;
sheetsMap?: Map<string, Sheet>;
idPrefix?: string;
forceError?: boolean;
fileVersion?: string;
detailText?: TaskRunLogDetailText;
+ taskRunStatus?: TaskRun_Status;
}
export interface BuildReleaseFileGroupsOptions {
getSectionLabel: (type: TaskRunLogEntry_Type) => string;
+ entryKeys: EntryKeys;
sheet?: Sheet;
sheetsMap?: Map<string, Sheet>;
idPrefix?: string;
forceError?: boolean;
detailText?: TaskRunLogDetailText;
includeOrphanGroup?: boolean;
+ taskRunStatus?: TaskRun_Status;
}
export interface TaskRunLogDetailText {
@@ -60,6 +70,36 @@ export const getTimestampMs = (timestamp?: Timestamp): number => {
return Number(timestamp.seconds) * 1000 + timestamp.nanos / 1000000;
};
+// A row's key is the entry's identity: replica, log time at full precision,
+// type, and an ordinal among the entries that tie on all three. task_run_log
+// has no primary key and rows may share a created_at, so time alone ties; the
+// API returns rows in append order, so a tie group's ordinals never shift.
+// Call this once with the run's complete entry list, before any filtering: an
+// ordinal counted over a slice restarts at zero and collides across slices.
+export const assignEntryKeys = (entries: TaskRunLogEntry[]): EntryKeys => {
+ const keys = new Map<TaskRunLogEntry, string>();
+ const tieCounts = new Map<string, number>();
+ for (const entry of entries) {
+ const seconds = entry.logTime?.seconds.toString() ?? "";
+ const nanos = entry.logTime?.nanos ?? 0;
+ const tieGroup = `${entry.replicaId}:${seconds}.${nanos}:${entry.type}`;
+ const ordinal = tieCounts.get(tieGroup) ?? 0;
+ tieCounts.set(tieGroup, ordinal + 1);
+ keys.set(entry, `${tieGroup}:${ordinal}`);
+ }
+ return keys;
+};
+
+const getEntryKey = (entryKeys: EntryKeys, entry: TaskRunLogEntry): string => {
+ const key = entryKeys.get(entry);
+ if (key === undefined) {
+ throw new Error(
+ "task-run log entry has no key; assignEntryKeys must cover every entry handed to a builder"
+ );
+ }
+ return key;
+};
+
export const formatTime = (timestamp?: Timestamp): string => {
if (!timestamp) return "--:--:--.---";
const date = new Date(getTimestampMs(timestamp));
@@ -139,13 +179,16 @@ export const isComplete = (entry: TaskRunLogEntry): boolean => {
}
};
+const sortEntriesByTime = (entries: TaskRunLogEntry[]): TaskRunLogEntry[] =>
+ [...entries].sort(
+ (a, b) => getTimestampMs(a.logTime) - getTimestampMs(b.logTime)
+ );
+
export const groupEntriesByType = (
entries: TaskRunLogEntry[]
): EntryGroup[] => {
if (entries.length === 0) return [];
- const sorted = [...entries].sort(
- (a, b) => getTimestampMs(a.logTime) - getTimestampMs(b.logTime)
- );
+ const sorted = sortEntriesByTime(entries);
const groups: EntryGroup[] = [];
let current: EntryGroup | undefined;
@@ -298,31 +341,46 @@ const extractStatementFromRange = (
}
}
if (!content) return undefined;
+ // A range reaching past the content means the sheet came back partial.
+ // subarray would clamp silently and pass a cut statement off as whole.
+ if (range.end > content.byteLength) return undefined;
const subarray = content.subarray(range.start, range.end);
return new TextDecoder().decode(subarray);
};
+interface EntryDetail {
+ detail: string;
+ statement?: string;
+ error?: string;
+}
+
+// The one-line form of a statement. Clamping to the row's width is CSS's job:
+// only the row knows how much fits.
+const collapseStatement = (statement: string): string =>
+ statement.trim().replace(/\s+/g, " ");
+
const getCommandExecuteDetail = (
entry: TaskRunLogEntry,
sheet: Sheet | undefined,
sheetsMap: Map<string, Sheet> | undefined,
fileVersion?: string
-): string => {
+): EntryDetail => {
const command = entry.commandExecute;
- if (!command) return "";
- if (command.response?.error) return command.response.error;
+ if (!command) return { detail: "" };
- const statement =
+ const recovered =
command.statement ||
(command.range
? extractStatementFromRange(command.range, sheet, sheetsMap, fileVersion)
: undefined);
- if (!statement) return "-";
+ const statement = recovered?.trim() ? recovered : undefined;
+ const error = command.response?.error || undefined;
- const normalized = statement.trim().replace(/\s+/g, " ");
- return normalized.length > 80
- ? `${normalized.substring(0, 80)}...`
- : normalized;
+ return {
+ detail: error ?? (statement ? collapseStatement(statement) : "-"),
+ statement,
+ error,
+ };
};
const getTransactionControlDetail = (
@@ -404,19 +462,15 @@ const getReleaseFileExecuteDetail = (entry: TaskRunLogEntry): string => {
: releaseFile.version;
};
-const getEntryDetail = (
+// Entries that carry status words rather than a payload.
+const getStatusDetail = (
entry: TaskRunLogEntry,
- sheet: Sheet | undefined,
- sheetsMap: Map<string, Sheet> | undefined,
- detailText: TaskRunLogDetailText | undefined,
- fileVersion?: string
+ detailText: TaskRunLogDetailText | undefined
): string => {
const runningByType = detailText?.runningByType;
const completed = detailText?.completed ?? "";
switch (entry.type) {
- case TaskRunLogEntry_Type.COMMAND_EXECUTE:
- return getCommandExecuteDetail(entry, sheet, sheetsMap, fileVersion);
case TaskRunLogEntry_Type.TRANSACTION_CONTROL:
return getTransactionControlDetail(entry, detailText);
case TaskRunLogEntry_Type.SCHEMA_DUMP:
@@ -454,6 +508,19 @@ const getEntryDetail = (
}
};
+const getEntryDetail = (
+ entry: TaskRunLogEntry,
+ sheet: Sheet | undefined,
+ sheetsMap: Map<string, Sheet> | undefined,
+ detailText: TaskRunLogDetailText | undefined,
+ fileVersion?: string
+): EntryDetail => {
+ if (entry.type === TaskRunLogEntry_Type.COMMAND_EXECUTE) {
+ return getCommandExecuteDetail(entry, sheet, sheetsMap, fileVersion);
+ }
+ return { detail: getStatusDetail(entry, detailText) };
+};
+
const getCommandDuration = (entry: TaskRunLogEntry): string | undefined => {
if (entry.type !== TaskRunLogEntry_Type.COMMAND_EXECUTE) return undefined;
const startMs = getTimestampMs(entry.commandExecute?.logTime);
@@ -464,28 +531,31 @@ const getCommandDuration = (entry: TaskRunLogEntry): string | undefined => {
const buildDisplayItems = (
entries: TaskRunLogEntry[],
- groupIndex: number,
startTime: number,
- sheet: Sheet | undefined,
- sheetsMap: Map<string, Sheet> | undefined,
- idPrefix: string | undefined,
- detailText: TaskRunLogDetailText | undefined,
- fileVersion?: string
+ markedEntry: TaskRunLogEntry | undefined,
+ options: BuildSectionsOptions
): DisplayItem[] => {
- return entries.map((entry, entryIndex) => {
+ return entries.map((entry) => {
const entryTime = getTimestampMs(entry.logTime);
const relativeMs = startTime > 0 ? entryTime - startTime : 0;
const entryHasError = hasError(entry);
return {
- key: `${idPrefix ?? "section"}-${groupIndex}-${entryIndex}`,
+ key: getEntryKey(options.entryKeys, entry),
time: formatTime(entry.logTime),
timeMs: entry.logTime ? entryTime : undefined,
relativeTime: relativeMs > 0 ? formatRelativeTime(relativeMs) : "",
levelIndicator: entryHasError ? "\u2717" : "\u2713",
levelClass: entryHasError ? "text-error" : "text-success",
- detail: getEntryDetail(entry, sheet, sheetsMap, detailText, fileVersion),
+ ...getEntryDetail(
+ entry,
+ options.sheet,
+ options.sheetsMap,
+ options.detailText,
+ options.fileVersion
+ ),
detailClass: entryHasError ? "text-error" : "text-control",
+ marked: entry === markedEntry || undefined,
affectedRows:
entry.type === TaskRunLogEntry_Type.COMMAND_EXECUTE
? Number(entry.commandExecute?.response?.affectedRows ?? 0) ||
@@ -496,6 +566,41 @@ const buildDisplayItems = (
});
};
+const commandFailed = (entry: TaskRunLogEntry): boolean =>
+ entry.type === TaskRunLogEntry_Type.COMMAND_EXECUTE && hasError(entry);
+
+const commandSucceeded = (entry: TaskRunLogEntry): boolean =>
+ entry.type === TaskRunLogEntry_Type.COMMAND_EXECUTE &&
+ isComplete(entry) &&
+ !hasError(entry);
+
+// The failure that explains the outcome of one execution context: the last
+// failed command, unless a later command succeeded or a retry marker follows
+// it. A lock timeout makes the driver re-run and re-log the whole command list,
+// and it writes the marker before each new attempt, so either one means the
+// failure was superseded. `sorted` must be the whole context, ungrouped:
+// grouping by type would leave every retried failure last in its own section.
+const pickMarkedEntry = (
+ sorted: TaskRunLogEntry[],
+ taskRunStatus: TaskRun_Status | undefined
+): TaskRunLogEntry | undefined => {
+ // Mitigation for a response the API drops (CockroachDB logs one per attempt
+ // and the converter keeps the first): a run that finished DONE has no
+ // failure to explain, whatever its entries claim.
+ if (taskRunStatus === TaskRun_Status.DONE) return undefined;
+
+ const lastFailedIndex = sorted.findLastIndex(commandFailed);
+ if (lastFailedIndex < 0) return undefined;
+ const superseded = sorted
+ .slice(lastFailedIndex + 1)
+ .some(
+ (entry) =>
+ entry.type === TaskRunLogEntry_Type.RETRY_INFO ||
+ commandSucceeded(entry)
+ );
+ return superseded ? undefined : sorted[lastFailedIndex];
+};
+
const calculateSectionStatus = (entries: TaskRunLogEntry[]): SectionStatus => {
if (entries.some(hasError)) return "error";
if (entries.every(isComplete)) return "success";
@@ -508,7 +613,10 @@ export const buildSectionsFromEntries = (
): Section[] => {
if (entries.length === 0) return [];
- return groupEntriesByType(entries).map((group, groupIndex) => {
+ const sorted = sortEntriesByTime(entries);
+ const markedEntry = pickMarkedEntry(sorted, options.taskRunStatus);
+
+ return groupEntriesByType(sorted).map((group, groupIndex) => {
let status = calculateSectionStatus(group.entries);
if (options.forceError && status === "running") {
status = "error";
@@ -540,26 +648,16 @@ export const buildSectionsFromEntries = (
? formatDuration(Math.max(durationMs, 0))
: "",
entryCount: group.entries.length,
- items: buildDisplayItems(
- group.entries,
- groupIndex,
- startTime,
- options.sheet,
- options.sheetsMap,
- options.idPrefix,
- options.detailText,
- options.fileVersion
- ),
+ items: buildDisplayItems(group.entries, startTime, markedEntry, options),
};
});
};
export const buildReleaseFileGroups = (
entries: TaskRunLogEntry[],
- options?: BuildReleaseFileGroupsOptions
+ options: BuildReleaseFileGroupsOptions
): ReleaseFileGroup[] => {
const buildOptions: BuildReleaseFileGroupsOptions = {
- getSectionLabel: (type) => String(type),
includeOrphanGroup: false,
...options,
};
diff --git a/frontend/src/components/task-run-log/types.ts b/frontend/src/components/task-run-log/types.ts
index 955505f6c4..00530d4909 100644
--- a/frontend/src/components/task-run-log/types.ts
+++ b/frontend/src/components/task-run-log/types.ts
@@ -7,6 +7,9 @@ import type {
export type SectionStatus = "success" | "error" | "running" | "pending";
export interface DisplayItem {
+ // The entry's identity, not its position: it must not change when a second
+ // replica appears or a retry marker regroups the sections, because the
+ // reader's folds are stored under it.
key: string;
/** Dense time-of-day; the date lives on the run header and in the tooltip. */
time: string;
@@ -15,8 +18,20 @@ export interface DisplayItem {
relativeTime: string;
levelIndicator: string;
levelClass: string;
+ // The one line the row shows: the error when the command failed, otherwise
+ // the statement collapsed to a single line.
detail: string;
detailClass: string;
+ // The statement this row ran, verbatim. Absent when it could not be
+ // recovered, and on entries that carry status words rather than a payload.
+ statement?: string;
+ // The error the command returned, verbatim.
+ error?: string;
+ // The failure that explains the outcome of its execution context: the view
+ // renders it past the "Load more" window and brings it into view. It does not
+ // open it. Picked across the whole context, so a view of one section cannot
+ // re-derive it.
+ marked?: boolean;
affectedRows?: number;
duration?: string;
}
diff --git a/frontend/src/components/task-run-log/useTaskRunLogSections.ts b/frontend/src/components/task-run-log/useTaskRunLogSections.ts
index 0d0fdada66..bb702c4f3b 100644
--- a/frontend/src/components/task-run-log/useTaskRunLogSections.ts
+++ b/frontend/src/components/task-run-log/useTaskRunLogSections.ts
@@ -1,11 +1,13 @@
import { useEffect, useMemo, useState } from "react";
import type {
+ TaskRun_Status,
TaskRunLogEntry,
TaskRunLogEntry_Type,
} from "@/types/proto-es/v1/rollout_service_pb";
import type { Sheet } from "@/types/proto-es/v1/sheet_service_pb";
import type { TaskRunLogDetailText } from "./model";
import {
+ assignEntryKeys,
buildReleaseFileGroups,
buildSectionsFromEntries,
getUniqueReplicaIds,
@@ -40,6 +42,8 @@ export interface UseTaskRunLogSectionsOptions {
getSectionLabel: (type: TaskRunLogEntry_Type) => string;
detailText?: TaskRunLogDetailText;
datasetKey?: string;
+ // Forwarded into every builder call below; see pickMarkedEntry.
+ taskRunStatus?: TaskRun_Status;
}
export interface UseTaskRunLogSectionsResult {
@@ -71,6 +75,7 @@ export const useTaskRunLogSections = ({
getSectionLabel,
detailText,
datasetKey,
+ taskRunStatus,
}: UseTaskRunLogSectionsOptions): UseTaskRunLogSectionsResult => {
const [expandedSections, setExpandedSections] = useState<Set<string>>(
() => new Set()
@@ -91,25 +96,49 @@ export const useTaskRunLogSections = ({
Set<string>
>(() => new Set());
+ // Every builder below sees a filtered slice of the run, so the keys are
+ // assigned here, over all of it.
+ const entryKeys = useMemo(() => assignEntryKeys(entries), [entries]);
+
const sections = useMemo(() => {
return buildSectionsFromEntries(entries, {
getSectionLabel,
+ entryKeys,
sheet,
sheetsMap,
detailText,
+ taskRunStatus,
});
- }, [detailText, entries, getSectionLabel, sheet, sheetsMap]);
+ }, [
+ detailText,
+ entries,
+ entryKeys,
+ getSectionLabel,
+ sheet,
+ sheetsMap,
+ taskRunStatus,
+ ]);
const releaseFileGroups = useMemo(() => {
if (!hasReleaseFileMarkers(entries)) return [];
return buildReleaseFileGroups(entries, {
getSectionLabel,
+ entryKeys,
sheet,
sheetsMap,
detailText,
includeOrphanGroup: true,
+ taskRunStatus,
});
- }, [detailText, entries, getSectionLabel, sheet, sheetsMap]);
+ }, [
+ detailText,
+ entries,
+ entryKeys,
+ getSectionLabel,
+ sheet,
+ sheetsMap,
+ taskRunStatus,
+ ]);
const replicaGroups = useMemo(() => {
const replicaIds = getUniqueReplicaIds(entries);
@@ -126,11 +155,13 @@ export const useTaskRunLogSections = ({
releaseFileGroups: [],
sections: buildSectionsFromEntries(replicaEntries, {
getSectionLabel,
+ entryKeys,
sheet,
sheetsMap,
idPrefix: replicaId,
forceError,
detailText,
+ taskRunStatus,
}),
};
}
@@ -143,26 +174,38 @@ export const useTaskRunLogSections = ({
replicaId,
releaseFileGroups: buildReleaseFileGroups(replicaEntries, {
getSectionLabel,
+ entryKeys,
sheet,
sheetsMap,
idPrefix: replicaId,
forceError,
detailText,
+ taskRunStatus,
}),
sections:
orphanGroup && orphanGroup.entries.length > 0
? buildSectionsFromEntries(orphanGroup.entries, {
getSectionLabel,
+ entryKeys,
sheet,
sheetsMap,
idPrefix: `${replicaId}-orphan`,
forceError,
detailText,
+ taskRunStatus,
})
: [],
};
});
- }, [detailText, entries, getSectionLabel, sheet, sheetsMap]);
+ }, [
+ detailText,
+ entries,
+ entryKeys,
+ getSectionLabel,
+ sheet,
+ sheetsMap,
+ taskRunStatus,
+ ]);
const hasReleaseFiles = useMemo(
() => hasReleaseFileMarkers(entries),
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 3a18f974ad..036bb143ee 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -3725,7 +3725,9 @@
"completed": "Completed",
"computing": "Computing...",
"dumping": "Dumping...",
+ "hide-full-statement": "Hide full statement",
"retry-attempt": "attempt {{current}}/{{max}}",
+ "show-full-statement": "Show full statement",
"syncing": "Syncing..."
},
"log-type": {
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index 744246cbf4..3cd41f19c2 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -3725,7 +3725,9 @@
"completed": "Completado",
"computing": "computación...",
"dumping": "dumping...",
+ "hide-full-statement": "Ocultar la declaración completa",
"retry-attempt": "intento {{current}}/{{max}}",
+ "show-full-statement": "Mostrar la declaración completa",
"syncing": "sincronizando..."
},
"log-type": {
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index a1ebd7fc36..cbd8493bcc 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -3725,7 +3725,9 @@
"completed": "完了しました",
"computing": "コンピューティング...",
"dumping": "ダンピング...",
+ "hide-full-statement": "ステートメント全体を非表示",
"retry-attempt": "試行 {{current}}/{{max}}",
+ "show-full-statement": "ステートメント全体を表示",
"syncing": "同期中..."
},
"log-type": {
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index 7ee148685e..10e901b17f 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -3725,7 +3725,9 @@
"completed": "Đã hoàn thành",
"computing": "tính toán...",
"dumping": "đang xuất...",
+ "hide-full-statement": "Ẩn toàn bộ câu lệnh",
"retry-attempt": "nỗ lực {{current}}/{{max}}",
+ "show-full-statement": "Hiển thị toàn bộ câu lệnh",
"syncing": "đang đồng bộ hóa..."
},
"log-type": {
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index ef8d9aa14a..a8aa5c1ac9 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -3725,7 +3725,9 @@
"completed": "已完成",
"computing": "计算中...",
"dumping": "导出中...",
+ "hide-full-statement": "隐藏完整语句",
"retry-attempt": "第 {{current}}/{{max}} 次尝试",
+ "show-full-statement": "显示完整语句",
"syncing": "同步中..."
},
"log-type": {
diff --git a/frontend/tests/e2e/plan-detail/plan-detail-tasks.spec.ts b/frontend/tests/e2e/plan-detail/plan-detail-tasks.spec.ts
index 96ed7171c6..ef59804033 100644
--- a/frontend/tests/e2e/plan-detail/plan-detail-tasks.spec.ts
+++ b/frontend/tests/e2e/plan-detail/plan-detail-tasks.spec.ts
@@ -192,3 +192,136 @@ test.describe("Expanded task statement preview is height-bounded, not clipped (B
).toBeLessThanOrEqual(300);
});
});
+
+test.describe("Failed task's log keeps the statement that failed (BYT-10168)", () => {
+ // The log used to cut every statement to 80 characters and, on a failed
+ // command, show the driver's error alone — so the row a reader opened the log
+ // for could not say which SQL produced it, and nothing could be copied.
+ // See docs/design/task-run-log-statement-unfold.md.
+ test("a full log keeps its height; the failure unfolds from its line, copies, and folds back into place", async () => {
+ test.setTimeout(180_000);
+ await sharedContext.grantPermissions(
+ ["clipboard-read", "clipboard-write"],
+ { origin: env.baseURL },
+ );
+
+ // Nine successes then the failure: ten rows fill the section's box, and
+ // the failing statement (16 lines, ~300px) is taller than the box on its
+ // own. Not longer: the create page's editor renders about 26 lines, and
+ // the plan helper checks the first line is still in view after insertion.
+ const stamp = Date.now();
+ const okColumn = (index: number) => `e2e_log_ok_${stamp}_${index}`;
+ const missingTable = `nonexistent_table_e2e_${stamp}`;
+ const failedLines = Array.from(
+ { length: 15 },
+ (_, index) => ` ADD COLUMN c${index + 1} TEXT${index === 14 ? ";" : ","}`,
+ );
+ await createPlanAndNavigate(
+ "E2E Task Log",
+ [
+ ...Array.from({ length: 9 }, (_, index) =>
+ `ALTER TABLE employee ADD COLUMN IF NOT EXISTS ${okColumn(index)} TEXT;`,
+ ),
+ `ALTER TABLE ${missingTable}`,
+ ...failedLines,
+ ].join("\n"),
+ );
+
+ await planPage.runTask();
+ await expect(page.getByText("Failed").first()).toBeVisible({
+ timeout: 30_000,
+ });
+
+ const rows = page.getByTestId("task-run-log-row");
+ const failedRow = rows.filter({ hasText: "does not exist" });
+ const rowText = (row: typeof failedRow) =>
+ row.evaluate((element) => element.textContent ?? "");
+ const failedSql = new RegExp(
+ `ALTER TABLE ${missingTable}\\s*\\n\\s*ADD COLUMN c1 TEXT,[\\s\\S]*ADD COLUMN c15 TEXT;`,
+ );
+ const box = failedRow.locator("xpath=..");
+ const boxHeight = () =>
+ box.evaluate((element) => element.getBoundingClientRect().height);
+ // Where the box sits on screen: unchanged means nothing around it moved,
+ // whichever container the page scrolls in.
+ const boxY = () => box.evaluate((element) => element.getBoundingClientRect().y);
+ const errorText = failedRow.getByText("does not exist");
+ const lineY = async () => (await errorText.boundingBox())?.y ?? Number.NaN;
+
+ // Nothing is unfolded for the reader: the failure shows its error, folded,
+ // and the section is scrolled to it — it is the tenth row, at the box's
+ // bottom.
+ await expect(failedRow).toBeVisible({ timeout: 30_000 });
+ await expect(failedRow).toContainText(`"${missingTable}" does not exist`);
+ const showFailed = failedRow.getByRole("button", {
+ name: "Show full statement",
+ });
+ await expect(showFailed).toHaveAttribute("aria-expanded", "false");
+ expect(await rowText(failedRow)).not.toMatch(failedSql);
+ await expect(rows).toHaveCount(10);
+ // The reader has scrolled the page to the failure; from here on nothing
+ // the toggles do may move it.
+ await failedRow.scrollIntoViewIfNeeded();
+ const fullBoxHeight = await boxHeight();
+ const parkedY = await lineY();
+ const boxYBefore = await boxY();
+
+ // Every line with a fold control toggles on click, the error included. The
+ // box does not grow: the statement that failed opens inside it, and since
+ // it is taller than the box the line goes to the box's top so the SQL can
+ // fill the rest.
+ await expect(errorText).toHaveCSS("cursor", "pointer");
+ await errorText.click();
+ const hideFailed = failedRow.getByRole("button", {
+ name: "Hide full statement",
+ });
+ await expect(hideFailed).toHaveAttribute("aria-expanded", "true");
+ await expect.poll(() => rowText(failedRow)).toMatch(failedSql);
+ expect(await boxHeight()).toBe(fullBoxHeight);
+ expect(await boxY()).toBe(boxYBefore);
+ expect(Math.abs((await lineY()) - boxYBefore)).toBeLessThanOrEqual(6);
+ const revealScroll = await box.evaluate((element) => element.scrollTop);
+
+ // Copy takes the SQL, never the error — and stays in reach: scrolled to the
+ // end of a block taller than the box, the button is still inside the box.
+ const copy = failedRow.getByRole("button", { name: "Copy" });
+ await box.evaluate((element) => {
+ element.scrollTop = element.scrollHeight;
+ });
+ const copyBox = await copy.boundingBox();
+ const boxBox = await box.boundingBox();
+ expect(copyBox).not.toBeNull();
+ expect(copyBox!.y).toBeGreaterThanOrEqual(boxBox!.y);
+ expect(copyBox!.y + copyBox!.height).toBeLessThanOrEqual(
+ boxBox!.y + boxBox!.height,
+ );
+ await copy.click();
+ const clipboard = () => page.evaluate(() => navigator.clipboard.readText());
+ await expect.poll(clipboard).toMatch(failedSql);
+ expect(await clipboard()).not.toContain("does not exist");
+
+ // Folding puts the line back where it was clicked from: the box keeps its
+ // height and its place on the page, and the row returns to the box's
+ // bottom.
+ await box.evaluate((element, top) => {
+ element.scrollTop = top;
+ }, revealScroll);
+ await errorText.click();
+ await expect(showFailed).toHaveAttribute("aria-expanded", "false");
+ await expect(failedRow).not.toContainText("ADD COLUMN c1 TEXT");
+ await expect(failedRow).toContainText("does not exist");
+ expect(await boxHeight()).toBe(fullBoxHeight);
+ expect(await boxY()).toBe(boxYBefore);
+ expect(Math.abs((await lineY()) - parkedY)).toBeLessThanOrEqual(1);
+
+ // A successful statement that fits its line has no fold control, and
+ // copies from the row.
+ const okRow = rows.filter({ hasText: okColumn(3) });
+ await expect(
+ okRow.getByRole("button", { name: "Show full statement" }),
+ ).toHaveCount(0);
+ await okRow.hover();
+ await okRow.getByRole("button", { name: "Copy" }).click();
+ await expect.poll(clipboard).toContain(okColumn(3));
+ });
+});