Skip to content

fix(tui): wrap the live work log instead of clipping it - #3004

Closed
kovtcharov wants to merge 3 commits into
amd:mainfrom
kovtcharov:claudia/task-8d828a85
Closed

kovtcharov wants to merge 3 commits into
amd:mainfrom
kovtcharov:claudia/task-8d828a85

Conversation

@kovtcharov

Copy link
Copy Markdown
Contributor

While the agent works a turn, the TUI's live work log was clipping each line to the pane width, so the user lost the tail — and for the lines that carry a reason or a remedy, the tail IS the remedy. A shell command showed its first flags and stopped; a failed tool call showed permission denied writing to… and cut off before the sentence saying what to do about it. Turns run 25-160s, so this log is most of what a user looks at while they wait. It wraps now instead of truncating, and the region is no taller than it was before: the height ceiling is unchanged, so a wrapped line costs older history, never height — on a 12-row terminal the log still gets two rows.

For the branches touching the same file

claudia/task-34b41d95 (responsive TUI width) and claudia/task-2a0113e3 (Claude model picker) both edit chat/model.go. What moved here, so their rebase is cheap:

  • logWidth() — signature and return value unchanged (m.width - 6, capped at narrationWidth, floor 16). Its meaning changed: it is now a wrap measure, not a clip budget. Making it track the terminal instead of capping at 74 composes with this as-is — rows get wider and fewer, and no other call site needs to know.
  • wrapForPane, wrapProse, answerWidth, cardWidth: not touched. I reused the existing wrap rather than adding a third path, so a width change there flows through both the transcript and the work log.
  • renderActivityItem() — signature unchanged, (item, live, elapsed) []string; internals rewritten to wrap and return several rows per action. renderLiveRegion() — its height-trim loop was rewritten. updateViewport() — one line: it now calls liveRegionView() instead of renderLiveRegion().
  • New symbols in model.go: wrapLog, hardBreak, splitAtWidth, clipTail, clipRows, liveRegionView; consts logHeadRows, logDetailRows, elapsedReserve; field ChatModel.logPeakRows (reset in startTurn and requestCancel).
  • Assumption worth knowing: the live row reserves elapsedReserve = 8 columns for the spinner's trailing clock, so anything that changes what trails that row has to move with it.

Test plan

  • cd tui && go build ./... && go vet ./... && go test ./... — note ./test/... fails on an unrelated daemon start-lock in some environments; go test ./internal/... is the part this change affects.
  • cd tui && go test ./internal/ui/chat/ -run 'TestWorkLog|TestWrapLog|TestOneLongAction|TestRepeatCounter' -v — table-driven at 60x12, 80x24, 100x40 and 200x50: the tail survives on both event dialects and both failure paths, the region stays within its height budget and under half the viewport, no row exceeds the terminal width, one long action cannot fill the region, and the height never shrinks mid-turn.
  • Eyeball it live: run the TUI, ask for something that shells out (gh issue list … --jq …), confirm the command reads to its end and the log stays under half the pane. Resize to ~12 rows mid-turn and confirm the transcript is still readable.

A long line in the agent's work log lost its tail. A shell command showed
up to its first flags and stopped; a failed tool call showed "permission
denied writing to..." and cut off before the sentence that says what to do
about it. Turns run 25-160s, so this log is most of what a user looks at
while they wait, and the clipped half was routinely the actionable half.

The lines wrap now, reusing the transcript's own wrap (components.WrapText)
rather than a third wrapping path. The region's height ceiling is unchanged
- still min(workLogMaxRows, viewport/2) - so a wrapped line costs older
HISTORY, never height: on a 12-row terminal the log still gets two rows.
Per-action row caps stop one 300-character command from spending the whole
region on itself, and what those caps do cut ends in an ellipsis.

Three things fell out of doing it properly:

- WrapText only breaks on spaces, so a URL or a Windows path - the lines
  most likely to run long - had no break to wrap at and overran the pane.
  Rows wider than the measure are now hard-broken at a column boundary.
- Text was being cut to one row's width at CAPTURE time, before the
  renderer ever saw it: at 74 columns for a narration, at 66 for a tool
  error's own message, at 60 on the legacy transport. Those bounds now sit
  where the renderer can still use them, so the wrap decides where a line
  ends. A tool error keeps its second line, which is where the remedy is.
- The old height trim dropped the NEWEST action when it alone exceeded the
  budget, so a wrapped command on a short terminal rendered an empty
  region. It is clipped to fit and marked instead.

The region's height is also held at each turn's peak. It grows as work
happens, which reads as progress, but shrinking dropped the transcript
above back down mid-sentence - and wrapping makes those swings bigger.

Covered by table-driven tests at 60x12, 80x24, 100x40 and 200x50: tail
survival on both event dialects and both failure paths, height within
budget and under half the viewport, no row wider than the terminal, one
long action unable to fill the region, and the height never shrinking
mid-turn.
@github-actions github-actions Bot added the tui Go terminal UI (gaia-tui) label Aug 19, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

The work log in the TUI used to cut every line at the pane edge, so the end of a long shell command — and the sentence at the end of a failure that tells you how to fix it — was simply thrown away. This PR makes those lines wrap onto a second and third row instead, caps how tall any one action can get, and holds the region's height steady so the transcript above doesn't jump around while you're reading it. The reasoning is sound and the height and width budgets still hold; I found nothing blocking.

Two things worth a look before merge, neither of them serious:

  • The fix was applied to the error path that goes through the typed-error classifier, but the other path — the one used when a tool doesn't declare a render card — still keeps only the first line of an error message. A multi-line error still loses its remedy there, which is the exact case this PR set out to fix.
  • While an action is still running, its wrapped rows are laid out 8 columns narrower than they need to be, to leave room for the elapsed clock that only sits on the first row. The visible effect is that a long command re-flows across its rows the moment it finishes.

Real-world evidence

None available in this run. No evidence-bundle.md was produced, and the shell was unavailable for the whole review, so I could not read the PR description, run go test ./internal/ui/chat/, or drive the TUI. The verdict rests on static review alone.

This is a user-visible surface, so the evidence that fits is a before/after capture of a turn with a long shell command and a failing tool, at two geometries — 80x24 and the 60x12 case the new clip-and-mark path exists for. If the PR description already carries that, treat this as satisfied.

🔍 Technical details

Issues found

🟢 The untyped error path still first-lines its message (tui/internal/ui/chat/narrate.go:233)

failureDetail moved from firstLine to clean with the reasoning that "a tool's error message puts the remedy on its second line as often as not". toolResultDetail reads the same class of string out of data["message"]/["error"]/["detail"] and still calls firstLine, so the remedy is dropped before the wrap ever sees it. This is the path taken whenever the result has no render card — i.e. most tools. clean already collapses newlines to spaces, so the swap is safe, and markFailed's detailMax bound plus the 3-row cap keep the length in check.

		if msg := clean(firstStringOf(data, "message", "error", "detail", "display_message")); msg != "" {

(summary on line 229 is arguably fine as-is — a summary that spans lines is a different problem.)

🟢 A live action's continuation rows reserve room for a clock they don't carry (tui/internal/ui/chat/model.go:2298-2302)

headWidth -= elapsedReserve is applied to the whole wrap, but only rows[0] goes through renderLiveLine and gets the trailing clock; rows 1 and 2 are plain " " + style.Render(row) at full indent. So a running action wraps 8 columns early on every row, and hits the logHeadRows cut sooner than the same text does once the call completes and re-renders at full width. The user-visible symptom is a long command re-flowing across its rows at the moment it finishes.

Not worth contorting wrapLog's signature over, but a per-row measure (first row narrow, continuations full) would remove the jitter.

🟢 The clip marker lands after the elapsed clock (tui/internal/ui/chat/model.go:2173)

clipRows appends " …" to the last kept row. When the clipped group is the live one on a short terminal, that row is the live line, so it renders as ⠋ gaia --flag … 0:04 … — the ellipsis reads as belonging to the clock rather than to the text above it. Appending to the first row of the clipped group, or leaving the marker off a row that already ends in a clock, would read better. Purely cosmetic; the row still fits the width budget (worst case lands exactly on m.width).

Verified, not flagged

  • Height budgets hold. renderActivityItem can emit at most logHeadRows + logDetailRows (+2 dev rows), and the kept-counting loop plus the clipRows fallback keep the region at or under logRows() at every geometry, including the 12-row case where the budget is 2. The old trimming loop's groups[i+1:] could produce an empty region when nothing fit — the new kept == 0 branch is a genuine bug fix, not just a refactor.
  • Row widths stay inside the pane. Live row = 2 + 1 + 1 + (width-8) + 2 + clock, tool row = 4 + width, detail row = 4 + 2 + (width-2); with width = m.width - 6 all land at m.width - 2 or better.
  • No unterminated loops in hardBreak. splitAtWidth can only return an empty head if a single rune is wider than the measure, and wrapLog floors the measure at 8.
  • The peak-height hold can't strand blank rows. Every other m.activity = nil site (canonical.go:224,254, model.go:666,705,1196,1552,1582,1601,1612,1620) sets streaming = false first, so the region isn't drawn; only requestCancel clears the log with the turn still live, and it resets logPeakRows explicitly.
  • Padding sits above the streaming answer, not at the end of the buffer (updateViewport writes the answer after the live region). It keeps the transcript stable as intended; the cost is a 1–2 row gap between the log and the answer when trimming shrinks the region. Acceptable, and much smaller than the jump it prevents.
  • detailWidth has no remaining references; firstLine is still used, so nothing goes dead.

Strengths

  • The test file is the best part of this PR. A geometry table rather than one hard-coded 80x24, both transports (canonical and legacy) fed through the same assertion, the typed-error path exercised via a real Render-gated payload, and invariants asserted as properties (nothing wider than the terminal, nothing taller than logRows(), height never decreasing) rather than golden strings. TestWorkLogNeverRendersEmpty in particular tests the failure mode the old trimming loop actually had.
  • Wrapping is column-accurate throughout — ansi.StringWidth rather than len, and splitAtWidth never cuts mid-rune — and hardBreak covers the case WrapText structurally can't (a URL or Windows path with no spaces in it), which is exactly the shape that was losing its tail.
  • clipTail's off-by-one is deliberate and documented: rows arrive filled to the measure, so truncateRunes would hand them straight back unmarked. That's the kind of boundary a silent-cut bug hides in, and it has its own test case.

Review follow-ups on the wrap change, all in what the log actually shows:

- A cut on the live row put its ellipsis after the elapsed clock, where it
  read as part of the timer. The row budget now reaches renderActivityItem,
  so the cut is made in the text before the clock is ever appended - and the
  marker no longer spends two columns of the viewport's edge reserve.
- Only the live row carries the clock, but every wrapped row of that action
  was paying the eight columns it takes. Continuations use the full measure,
  which gives a long command back about two words a row.
- A long argument could push the words that follow it out of its own phrase:
  "Looking for <query> in your documents" rendered without "in your
  documents". The argument is budgeted against the template now.
- A tool error's second line survives on both error paths, not just the one
  that goes through a render card. A `summary` stays first-line-only: one
  that runs to several lines is a payload dump, not a sentence.
- The held height pads above the log rather than below, so the blank rows
  land in the space that already separates it from the transcript instead of
  opening a gap between the log and the answer streaming under it.

Each fix has a test that fails without it - verified by reverting the
behaviour and watching the test go red.
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve

Note: the gh CLI is unavailable in this runner (sandbox blocks /home/.mcp.json), so prior-review status could not be verified. Treating as a first review.

The work-log wrapping change is correct and well-tested. The fix to the trimming loop that previously produced an empty region when a single group exceeded the budget (TestWorkLogNeverRendersEmpty) is the right call, and liveRegionView's peak-height hold is a clean solution to the transcript-jump problem. No blocking issues found.

One thing worth a look (non-blocking): toolResultDetail now passes the raw firstStringOf(...) result directly into parts — previously firstLine() stripped newlines at capture time. Those newlines reach item.Detail and then markFailed/truncateRunes without sanitisation on the failureDetail path (canonical.go). In practice this is fine because renderActivityItem calls clean(item.Detail) before handing it to wrapLog, so the renderer always sanitises before display. But if item.Detail is ever consumed without going through renderActivityItem (e.g. serialised or logged), the raw newlines would survive. Worth keeping in mind for any future use of that field outside the renderer.

Everything else is solid: hardBreak is protected against the infinite-loop edge case (all width paths enforce >= 8), clipTail correctly handles the exactly-full-row case, wrapLogLead falls back cleanly when rest == "", and logPeakRows is properly zeroed in both requestCancel and startTurn. The test file is comprehensive and covers the cases that motivated the change.

🔍 Technical details

toolResultDetail / failureDetail path (narrate.go:242, canonical.go:517):

Old: firstLine(firstStringOf(...)) — newlines stripped at capture time.
New: firstStringOf(...) directly — multi-line content reaches item.Detail raw.

renderActivityItem applies clean(item.Detail) before rendering, so display is fine. The observation is only relevant if item.Detail is ever serialised or read outside the renderer. Not a bug today.

hardBreak infinite-loop guard: wrapLog clamps width to >= 8 before calling hardBreak, and splitAtWidth always advances at least one rune when width >= 2 (since no Unicode character has display width > 2 for normal text). No real risk.

Trimming loop correctness (model.go:2111-2157): The old loop accumulated rows += len(groups[i]) then broke on overflow, which would produce an empty groups slice when even the single newest group exceeded budget. The new kept counter breaks before accumulating, and the else if branch re-renders the overflowing action to budget rows — correct.

@itomek itomek self-assigned this Aug 21, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

The work log now wraps rather than clips, the height is held at its turn peak to prevent mid-read jumps, and the test suite covers the edge cases that motivated the change. No correctness issues found; two small suggestions below.

🟢 wrapLogLead has no dedicated unit test. The TrimPrefix-based remainder split is the right approach (the comment explains the invariant), but it's only exercised indirectly through renderActivityItem. A three-line unit test covering the lead < width case (first row on the narrow clock-reduced measure, remainder on the full measure) would lock the split logic down without adding much weight.

🟢 Vacuous suffix-position assertion in TestWrapLog. For the two cases where tc.suffix == "" and wantCut: true, the check strings.HasSuffix(last, strings.TrimSpace(tc.suffix)) simplifies to HasSuffix(last, ""), which is always true. The ellipsis check below it still catches the main property, but the suffix-position assertion verifies nothing for those cases.

🔍 Technical details

wrapLogLead unit test gap (model.go:381-396)

The function handles three distinct shapes: (a) text+suffix fits within lead → early return, (b) text alone wraps at lead, remainder handled by wrapLog, (c) text alone fills lead but no breakpoint exists (hardBreak split). Shape (c) is exercised by TestWorkLogWrapsRatherThanClipping/an unbroken token is broken by force but only at the level of the full rendered region. A targeted test like:

func TestWrapLogLead(t *testing.T) {
    // Short text fits on the narrowed first row.
    got := wrapLogLead("hello", " x2", 10, 74, 3)
    if got[0] != "hello x2" { t.Errorf(...) }

    // Long text: first row uses lead, rest uses full width.
    got = wrapLogLead(longShell, " x2", 60, 74, 3)
    if len(got) < 2 { t.Errorf("expected continuation row") }
    if strings.Contains(got[0], "x2") { t.Errorf("counter on first row, not last") }
}

would catch a regression in the TrimPrefix split without depending on the full rendering stack.

Vacuous HasSuffix check (worklogwrap_test.go:940-942)

For the "past the row cap" and "an exactly-full cut row" cases, tc.suffix is "" so strings.TrimSpace("") == "" and HasSuffix(anything, "") is unconditionally true. The check was written to verify the repeat counter ends up at the tail of the cut row — that only fires for the " x14" case. Moving those two no-suffix cases to a separate table with wantCut: true and dropping the HasSuffix check (keeping only the ellipsis check) would make the intent clearer.

@itomek itomek removed their assignment Aug 24, 2026
AmirF194 pushed a commit to AmirF194/gaia that referenced this pull request Aug 26, 2026
On a wide terminal the work log stopped drawing at the same column an
80-column terminal did, so every extra column of window was wasted on
the one thing a user stares at for a 25-160s turn. A 240-column window
now draws a 238-column tool line instead of 78. Prose is deliberately
excluded: an answer still lays out at 88 columns, because for a
paragraph the extra width just loses the eye on the carriage return,
while for a single row it is simply more of that row — and for the rows
whose tail carries the reason or the remedy, the tail is the point.

Stacked on amd#3005 and amd#3004, in that order. Until both merge, the diff
here shows their commits too; mine are the two on top.

<details>
<summary>🔍 Technical details</summary>

**Functions changed**

- `logWidth()` — dropped the `narrationWidth` (74) ceiling, so the
measure is `m.width - 6`, clamped to `m.width - logGutter` so the floor
of 16 cannot overrun a cramped window.
- `narrate.go` constants — `narrationWidth = 74` became
`widestLogMeasure`, derived from the widest window the TUI accepts
anywhere (`control/server.go`'s `"cols must be 20-500"`). amd#3004 already
derives `narrationMax`/`detailMax` from the row measure; that reasoning
is kept, but the basis has to be the widest window the text might
*later* be rendered into, since capture happens before any width is
known and the user can widen mid-turn.
- `devPayloadWidth` — same basis, for the same reason.
- `wrapLog()` — its floor raised any measure under 8 back to 8,
overriding the caller's budget, so a 20-column terminal drew a 21-column
row. A measure is what the caller can afford; floored at 1 now, never
raised.
- `renderLiveRegion()` — two rows went through no measure at all: the
"still working" hint (a fixed 50 columns) and the idle live line. The
latter is the *opening frame of every turn*, and `"Thinking about the
next step"` drew 39 columns, shearing anything narrower.
- `resize()` — releases amd#3004's peak-height hold on a **width** change.
A resize reflows the log, which it could not before this branch; holding
a peak measured at another width stranded blank rows for the rest of the
turn. Guarded on width so the composer growing a row does not release
it.
- `handleCanonicalEvent` — `setLiveStatus` was the one agent-supplied
string with no capture bound at all.

`answerWidth()`, `wrapForPane()`, `wrapProse()`, `cardWidth()` and
`answerMeasure` are unchanged. `answerMeasure` and `logWidth` now
cross-reference each other so the split reads as chosen rather than
overlooked.

**Assumptions about the other two branches**

- amd#3004 owns the wrapping. Its `wrapLog`, `logHeadRows`/`logDetailRows`,
`elapsedReserve` and `liveRegionView` are taken as-is. The two compose:
amd#3004 wraps a tail that does not fit, this makes it less likely to need
to. Rebased onto its current head (`54a80d3d`), including its own review
follow-up.
- amd#3005 touches disjoint parts of `model.go`.
- Verified rather than assumed: merging `amd#3005 → amd#3004 → this` onto
`9c89cb47` in a scratch worktree merges with no conflicts, builds, vets,
and passes.

**The root cause, for the record**

`logWidth` was the visible suspect but not the cause.
`toolNarration`/`toolResultDetail` cut text to 74/66 columns *when the
event arrived*, before any width was known, so widening the layout alone
would have shown nothing new. Capture bounds now exist only to stop a
runaway agent payload living in the model; layout decides what prints.
</details>

## Test plan

- [ ] `cd tui && go build ./... && go vet ./... && go test
./internal/...`
- [ ] `widthlayout_test.go` is table-driven over **24, 40, 60, 80, 120,
160 and 240** columns, plus a per-width sweep from the declared minimum
of 20 up. It asserts at every size that no rendered row exceeds the
terminal, that `logWidth` grows with the window, and that `answerWidth`
never exceeds 88.
- [ ] The cramped-terminal test **renders** every row type — idle, live,
wrapped, outcome, `--dev` payload, repeat counter — rather than checking
`logWidth`'s arithmetic. An earlier version did the arithmetic only, and
certified a property the rendered rows did not have.
- [ ] Every fix was confirmed by reverting it and watching the suite
fail: reverting the `wrapLog` floor gives `21 columns wide on a
20-column terminal`; reverting the idle-line measure gives `39 columns
wide on a 20-column terminal`.
- [ ] amd#3004's `worklogwrap_test.go` passes unchanged against the dynamic
measure — the check that the wrapping and the width work compose rather
than fight.
- [ ] `internal/control` passes, so the `resize_exceeds_terminal` guard
from amd#2932 is intact; that file is untouched.
- [ ] Eyeball on a wide window: run a turn with a long shell command and
confirm the log line runs to the window edge while the answer below it
stays at 88.

Not run: `tui/test` (daemon integration). It needs a live GAIA daemon
and the machine was running demos.

---------

Co-authored-by: Ovtcharov <[email protected]>
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

Closed as superseded: the live work log already wraps instead of clipping on current main (landed via #3026), verified by driving the TUI rather than by reading the diff.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

tui Go terminal UI (gaia-tui)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants