diff --git a/cmd/agentop/README.md b/cmd/agentop/README.md index 823b32163..76a7a4afc 100644 --- a/cmd/agentop/README.md +++ b/cmd/agentop/README.md @@ -563,7 +563,7 @@ agentop is for, and the others are surfaces you visit and leave. 4 14:23:09.40 out observe inference-parser claude-sonnet-5 ↑121.0kB api.anthropic.com ● connected 2.1 events/sec [/anthropic 2 matches] [sort: DURATION▼] - [↑↓] nav [b/f] page [↵] detail [c] columns [u] usage [s] hide passthru/skip [p] pause [/] search [n/N] next/prev [esc] back · [?] keys [q] quit + [b/f] page [↵] detail [c] columns [u] usage [/] search [n/N] next/prev [esc] back [?] keys [q] quit ``` Exchange 3 has no ↓ figure because there was nothing to count: @@ -706,9 +706,7 @@ agentop is for, and the others are surfaces you visit and leave. rows: ``` - window 5m 1h [all] 10-26 14:28 → 10-26 20:08 - 14:28 15:17 16:06 37m 39m 18:41 - model tools tok/s + window 5m 1h all ╷10-26 14:28 ╷15:17 ╷16:06 37m 10-26 20:08╷ model tools tok/s main agent ▂█▃▅▃██▁▄▃▁▃█▁▆▁▂▇█▂▁▁▂████████▁▁▅▁███▅▁ ┆ ▄▁ ┆ ▂▁▆▂▁███▄▁│ 1.6h 29m 85 Survey cortex egress da ▃▂▁ ┆ ┆ │ 4m 1m 92 @@ -757,8 +755,8 @@ agentop is for, and the others are surfaces you visit and leave. still running from earlier ("since 12:41:04"), each with its duration and its command, path or description; a cell with no tool names the request `↵` would open. `↵` opens the Events pane on the first event listed. `↑`/`↓` scroll the - agent rows, then the host rows, when they do not all fit; the footer offers - them only then. The pane refreshes at most once a second while the stream + agent rows, then the host rows, when they do not all fit; the `?` help lists + them, not the footer. The pane refreshes at most once a second while the stream delivers that session's events, and every ten seconds while a call is in flight with nothing new recorded. A failed fetch is retried after 1s, then 2s, 4s … up to 30s, and the first fetch of a visit waits up to 30s, since a @@ -784,7 +782,7 @@ agentop is for, and the others are surfaces you visit and leave. team2 1 default 1 - [↑↓/jk] nav [↵] open [L] localhost:47601 [r] reload [?] keys [q] quit + [↵] open [L] localhost:47601 [r] reload [/] search [?] keys [q] quit ``` Without `--kubernetes`, a running local Cortex is connected to directly and @@ -862,7 +860,6 @@ Layered on top of all of them: | `/` | any pane, and the key help | search what the pane shows, as in a text editor: every row stays, the matched characters are highlighted, and the cursor (or, in a text view, the view) jumps to the first match at or after where you pressed `/`, wrapping past the end, as you type. Case-insensitive substring of the text the pane displays: a table's columns that are turned on, at full width (a value cut to `…` matches in full, and so does a column the terminal had no room for); an exchange's or plugin's detail line by line, before it is wrapped; the key help's and the usage chart's lines as drawn. `deny` finds denied events because ACTION shows it. `Enter` keeps the place; `Esc` puts the place and the previous search back; `Enter` on an empty box clears the search. Each pane keeps its own search; the events pane's and an exchange's detail's last while you stay with one session (the detail's carries from exchange to exchange), and none is saved. On the events pane, `Tab` in the prompt turns on `[x] details`: then `Enter`, `n` and `N` find the next row whose detail view shows the query — in either half, every field, the exact capture too. The proxy finds the matches in one pass over memory and the archive (`GET /v1/sessions/{id}/search`), and agentop checks the summary rows it holds itself, so nothing is fetched. The footer counts the matches, and also the matches in events older than the ones agentop holds: Enter on the timeline's `▲` row loads those. A Cortex that predates the search says so in the footer | | `n` / `N` | any pane with a search, and the key help | next / previous match, wrapping at both ends; in a text view an off-screen match is scrolled to a third of the way down | | `x` | sessions, agents | erase the row under the cursor, in memory and on disk: the highlighted session, or every session of the highlighted agent — on *All agents*, every session this Cortex holds; that confirmation also shows the size on disk. Asks first, with the count; `y` erases, `n`/`esc` keeps. The cost ledger is kept. An agent still using a session brings it back with its next request. Refused — with the proxy's reason — anywhere but a loopback-only laptop install. Not in the footer; the `?` overlay names it | -| `s` | events | toggle hiding exchanges no plugin acted on (default: shown; an exchange is hidden only when no plugin acted on either half; the events footer shows the hidden count) | | `c` | events | open the column picker (`↑↓`/`jk` move, `space` toggle, `s` sort, `r` reset, `Esc`/`Enter`/`c` close); the selection and sort are saved on close | | `s` | column picker | sort by the column under the cursor: descending → ascending → chronological. Pressing it on a different column starts that column descending. `#` is not sortable — its order already *is* chronological | | `p` | any | pause/resume stream | @@ -1926,8 +1923,9 @@ when the match arrives with the fetch. `y` writes the half without its capture. `CTX(1M)` is a gauge, not a figure: how full the **conversation's** context was on its latest turn, against a fixed one-million-token window. The -brackets are the scale, drawn on every row, so a nearly-empty session reads -as empty-out-of-something rather than as a blank cell — and an em dash, which +fill is followed by a shaded `░` track for the rest of the window (`███▌░░░`), +so the scale shows on every row and a nearly-empty session reads as +empty-out-of-something rather than as a blank cell — and an em dash, which means *no context known*, stays distinguishable from the sliver a barely-used session gets. diff --git a/cmd/agentop/tui/agents_projects_test.go b/cmd/agentop/tui/agents_projects_test.go index 0e2de43d2..295f730f4 100644 --- a/cmd/agentop/tui/agents_projects_test.go +++ b/cmd/agentop/tui/agents_projects_test.go @@ -507,8 +507,8 @@ func TestAgentsProjects_FooterNamesTheFullLabel(t *testing.T) { deliver(m, pressCmd(m, enterKey)) onDesc(t, m, agentRowDesc{agent: projAgent, kind: agentRowProject, project: label}) got := m.helpView() - if !strings.Contains(got, sanitizeLabel(label)) || strings.Contains(got, "[space]") { - t.Errorf("footer %q; want %q and no [space]", got, sanitizeLabel(label)) + if !strings.HasPrefix(got, sanitizeLabel(label)+" [↵]") || strings.Contains(got, "[space]") { + t.Errorf("footer %q; want it to start with %q and no [space]", got, sanitizeLabel(label)) } if strings.Contains(got, "\x1b") { t.Errorf("footer carries a raw escape: %q", got) diff --git a/cmd/agentop/tui/app.go b/cmd/agentop/tui/app.go index dcfc07e1a..8c646ad35 100644 --- a/cmd/agentop/tui/app.go +++ b/cmd/agentop/tui/app.go @@ -648,16 +648,6 @@ type model struct { detailSearch *detailSearch detailSearchGen uint64 paused bool - // hideInactive toggles whether passthrough / skip-only messages are - // hidden from the events table. False (default) shows every message — - // the operator asked to see all network traffic, processed or not. - // Toggle with `s` to focus on plugin activity (deny/modify/allow/ - // observe). hiddenInactive is the count from the most recent - // rebuildEventsTable, surfaced in the footer so a filtered timeline - // doesn't read as data loss. - hideInactive bool - hiddenInactive int - // olderNotFetched is how many events a session holds that its snapshot did not // carry, reported by the server, keyed by session id. // @@ -665,9 +655,7 @@ type model struct { // whichever session was selected when the fetch started. A single field let a late // snapshot for an abandoned session describe the one on screen, and showed the // previous session's count in the window between selecting a session and its - // snapshot arriving. Beside hiddenInactive in spirit — both answer "is this the - // whole timeline?" — but that one is a filter the operator chose and this is a - // bound they did not. + // snapshot arriving. olderNotFetched map[string]int // paging holds the backward-paging state of any session the operator has walked off @@ -2586,7 +2574,7 @@ func (m *model) paneView() string { renderTitle(title), styleDim.Render(renderDivider(m.width)), body, - renderTrailingHints(footer, keys), + renderTrailingKeyBar(footer, keys, m.width), ) } if m.pane == panePods { @@ -2611,7 +2599,7 @@ func (m *model) paneView() string { renderTitle(title), styleDim.Render(renderDivider(m.width)), body, - renderTrailingHints(footer, keys), + renderTrailingKeyBar(footer, keys, m.width), ) } if m.width == 0 { diff --git a/cmd/agentop/tui/events_blocks.go b/cmd/agentop/tui/events_blocks.go index f7893fc21..f68e15520 100644 --- a/cmd/agentop/tui/events_blocks.go +++ b/cmd/agentop/tui/events_blocks.go @@ -19,9 +19,8 @@ import ( // a subagent's. type subagentBlock struct { id string - // rows indexes cellContexts, in arrival order, among the rows that passed the - // inactive filter — the same population the row loop renders, so the header's - // rollup counts what expanding would show. + // rows indexes cellContexts, in arrival order — the same population the row loop + // renders, so the header's rollup counts what expanding would show. rows []int // tokens and cost are the block's rollup, from the same readings the TOKENS // and COST cells sort by (rowTokens / rowCostUSD). A request whose response @@ -102,23 +101,18 @@ func (m *model) blockOpen(id string, subtask, searching bool) bool { return subtask } -// rowInactiveHidden is the hideInactive (`s` toggle) predicate, stated once so the -// row loop and collectSubagentBlocks filter the same population: a block's rollup -// must count the rows expanding it would show, and a second spelling of the -// predicate here would drift with the first edit to either. -func (m *model) rowInactiveHidden(ctxs []cellContext, partner map[int]int, j int) bool { - return m.hideInactive && eventInactive(ctxs[j].invs) && !partnerActive(ctxs, partner, j) +// rowQuiet reports whether row j is background traffic: no plugin acted on it or on its +// partner. An unbridged CONNECT has no invocations, so it is quiet unless a gate denied it. +func rowQuiet(ctxs []cellContext, partner map[int]int, j int) bool { + return eventInactive(ctxs[j].invs) && !partnerActive(ctxs, partner, j) } -// collectSubagentBlocks groups the rows that survive the inactive filter by their -// `subagent` field. Nil when no row names one, which is every session without -// Claude Code or Bob subagents — those rebuild exactly as before. -func (m *model) collectSubagentBlocks(ctxs []cellContext, partner map[int]int) map[string]*subagentBlock { +// collectSubagentBlocks groups the rows by their `subagent` field. Nil when no row +// names one, which is every session without Claude Code or Bob subagents — those +// rebuild exactly as before. +func (m *model) collectSubagentBlocks(ctxs []cellContext) map[string]*subagentBlock { var blocks map[string]*subagentBlock for j, cc := range ctxs { - if m.rowInactiveHidden(ctxs, partner, j) { - continue - } id := cc.row.event.Subagent if id == "" { continue diff --git a/cmd/agentop/tui/events_blocks_test.go b/cmd/agentop/tui/events_blocks_test.go index 88284f6a6..c4d82ccb5 100644 --- a/cmd/agentop/tui/events_blocks_test.go +++ b/cmd/agentop/tui/events_blocks_test.go @@ -453,58 +453,6 @@ func TestBlocks_CollapseStateIsPerSession(t *testing.T) { } } -// The block's population is the rows the pane would show: hideInactive hides a -// subagent's whole exchange, and a block with no surviving rows leaves no header -// behind — a header naming nothing is worse than no header, because it claims a -// subagent the filter just said produced nothing visible. -func TestBlocks_RollupFollowsTheInactiveFilter(t *testing.T) { - active := func(id, sub string, phase pipeline.SessionPhase) pipeline.SessionEvent { - return pipeline.SessionEvent{ - Direction: pipeline.Outbound, Phase: phase, Host: "ete", RequestID: id, Subagent: sub, - Invocations: &pipeline.Invocations{Outbound: []pipeline.Invocation{ - {Plugin: "inference-parser", Action: pipeline.ActionObserve}, - }}, - } - } - inactive := func(id, sub string, phase pipeline.SessionPhase) pipeline.SessionEvent { - return pipeline.SessionEvent{ - Direction: pipeline.Outbound, Phase: phase, Host: "ete", RequestID: id, Subagent: sub, - } - } - events := []pipeline.SessionEvent{ - active("m1", "", pipeline.SessionRequest), - active("a1", "a1", pipeline.SessionRequest), - // a1's response is inactive but kept: its partner is shown (an exchange - // hides whole or not at all). - inactive("a1", "a1", pipeline.SessionResponse), - active("m2", "", pipeline.SessionRequest), - // a2's whole exchange is inactive: no block, no header. - inactive("a2", "a2", pipeline.SessionRequest), - inactive("a2", "a2", pipeline.SessionResponse), - } - m := &model{selectedSess: "s", events: map[string][]pipeline.SessionEvent{"s": events}, hideInactive: true} - m.eventsTbl = newEventsTable() - m.rebuildEventsTable() - - if _, ok := m.subagentBlocks["a2"]; ok { - t.Fatal("a2 has a block despite every row being hidden") - } - // Rendered: m1, header(a1), m2 — collapsed by default, so the kept exchange - // sits behind the header rather than on screen. No a2 header anywhere. - if got := len(m.eventsTbl.Rows()); got != 3 { - t.Fatalf("rendered rows = %d, want 3", got) - } - for i, b := range m.headerRows { - if b.id == "a2" { - t.Errorf("header for a2 at row %d", i) - } - } - // a1's header counts what expanding it would show: the kept exchange, 1 msg. - if h := m.eventsTbl.Rows()[1][0]; !strings.Contains(h, "1 msg") { - t.Errorf("a1 header = %q, want the kept exchange counted", h) - } -} - // The Timeline's Enter names subagent rows as readily as the conversation's, and // a subagent's row inside a collapsed block is not on screen — the reveal must // open the block rather than wait forever for a row that cannot appear. diff --git a/cmd/agentop/tui/events_cell_styles_test.go b/cmd/agentop/tui/events_cell_styles_test.go index 8dfa42de0..8a4a76c81 100644 --- a/cmd/agentop/tui/events_cell_styles_test.go +++ b/cmd/agentop/tui/events_cell_styles_test.go @@ -47,6 +47,23 @@ func assertInk(t *testing.T, view, text string, c lipgloss.AdaptiveColor, name s } } +// assertLastInk checks the last SGR before the first text in s. Unlike assertInk it allows +// text between them, for cells of one ink that the table draws as one run. +func assertLastInk(t *testing.T, s, text string, c lipgloss.AdaptiveColor, name string) { + t.Helper() + i := strings.Index(s, text) + if i < 0 { + t.Fatalf("%q is not in %q", text, ansi.Strip(s)) + } + j := strings.LastIndex(s[:i], "\x1b[") + if j < 0 { + t.Fatalf("no SGR before %q", text) + } + if sgr := s[j:i]; !strings.Contains(sgr, fgSGR(c)) { + t.Errorf("%q: last SGR %q has no %s ink (%s)", text, sgr, name, fgSGR(c)) + } +} + // cellStylesEvents is a modify exchange answered 200, an exchange answered 503 and an // unbridged CONNECT, so the ACTION and STATUS cells hold one value of each group. func cellStylesEvents() []pipeline.SessionEvent { @@ -76,7 +93,8 @@ func TestEventsCellStyles_ByColumnID(t *testing.T) { assertInk(t, view, "503", colorError, "error") assertInk(t, view, "200", colorOK, "ok") assertInk(t, view, "modify", colorAccent, "accent") - assertInk(t, view, "tunnel", colorDim, "dim") + // The unbridged CONNECT is quiet (#2019 change 6), so its ACTION is muted, not dim. + assertInk(t, view, "tunnel", colorMuted, "muted") for _, line := range strings.Split(ansi.Strip(view), "\n") { if slices.Contains(strings.Fields(line), "out") { t.Errorf("DIR is hidden, but a row shows %q: %q", "out", line) @@ -97,9 +115,10 @@ func TestEventsCellStyles_ToolRows(t *testing.T) { t.Fatalf("DURATION = %q, want a running tool's ⋯ cell", dur) } view := m.eventsTbl.View() - assertInk(t, view, "┗⚒", colorTool, "tool") - assertInk(t, view, "Grep", colorTool, "tool") - assertInk(t, view, dur, colorTool, "tool") + assertLastInk(t, view, "┗", colorDim, "dim") + assertLastInk(t, view, "⚒", colorDim, "dim") + assertLastInk(t, view, "Grep", colorMuted, "muted") + assertLastInk(t, view, dur, colorWarn, "warn") assertInk(t, view, "running", colorWarn, "warn") } @@ -142,8 +161,8 @@ func TestEventsCellStyles_ToolRowsWithIndexHidden(t *testing.T) { if strings.Contains(ansi.Strip(view), "⚒") { t.Fatalf("# is hidden, but the view shows the tool mark:\n%s", ansi.Strip(view)) } - assertInk(t, view, "Grep", colorTool, "tool") - assertInk(t, view, dur, colorTool, "tool") + assertLastInk(t, view, "Grep", colorMuted, "muted") + assertLastInk(t, view, dur, colorWarn, "warn") } // A block header is accent when # is the only column: one visible column makes every row one @@ -157,3 +176,269 @@ func TestEventsCellStyles_BlockRowAccentOneColumn(t *testing.T) { // The # column is narrow, so the header's label is cut to "─ …". assertInk(t, view, "─ …", colorAccent, "accent") } + +// rowFg is the foreground the events hook gives each cell of row r, keyed by column id. +func rowFg(m *model, r int) map[eventColumnID]lipgloss.TerminalColor { + cols, _ := layoutColumns(m.eventColumns, m.eventColWidths, m.width) + rows := m.eventsTbl.Rows() + hook := eventCellStyle(cols, m.eventRowKinds(len(rows)), rows) + row := rows[r] + fg := map[eventColumnID]lipgloss.TerminalColor{} + for i, c := range cols { + if i < len(row) && strings.TrimSpace(row[i]) != "" { + fg[c.id] = hook(r, row, i).GetForeground() + } + } + return fg +} + +// drawnLine is the drawn line of view whose plain text contains text. +func drawnLine(t *testing.T, view, text string) string { + t.Helper() + for _, l := range strings.Split(view, "\n") { + if strings.Contains(ansi.Strip(l), text) { + return l + } + } + t.Fatalf("no line with %q in:\n%s", text, ansi.Strip(view)) + return "" +} + +// A tool row steps back (#2019 change 3): every cell is muted, only live state (running, ⋯) +// keeps the warn ink and a failed tool the error ink, and its ┗⚒/┣⚒ mark and a subagent │ +// are dim. The same holds in search results and inside an open subagent block. +func TestEventCellStyle_ToolRowsMuted(t *testing.T) { + withProfile(t, termenv.TrueColor) + okTool := trTool(2, "ok", "Grep", 12, 13, "x") + running := trTool(2, "run", "Bash", 12, -1, "") + failed := trTool(2, "err", "Edit", 12, 13, "") + failed.Error = true + lost := trTool(2, "lost", "Read", 12, 14, "") + lost.Lost = true + m := toolRowsModel(t, trExchange(1, 10, ""), &timeline.Timeline{Tools: []timeline.Tool{okTool, running, failed, lost}}) + want := map[string]map[eventColumnID]lipgloss.AdaptiveColor{ + "ok": {colStatus: colorMuted}, + "run": {colStatus: colorWarn, colDuration: colorWarn}, + "err": {colStatus: colorError}, + "lost": {colStatus: colorError}, + } + for id, special := range want { + r, row := toolRowAt(t, m, id) + for col, fg := range rowFg(m, r) { + c, ok := special[col] + if !ok { + c = colorMuted + } + if strings.TrimSpace(row[colPos(m, col)]) == "—" { + c = colorDim + } + if fg != c { + t.Errorf("%s: column %v = %v, want %v", id, col, fg, c) + } + } + } + view := m.eventsTbl.View() + assertLastInk(t, view, "┣", colorDim, "dim") + assertLastInk(t, view, "┗", colorDim, "dim") + assertLastInk(t, view, "⚒", colorDim, "dim") + assertLastInk(t, drawnLine(t, view, "Grep"), "ok", colorMuted, "muted") + + m.search = map[paneID]string{paneEvents: "Grep"} + m.rebuildEventsTable() + view = m.eventsTbl.View() + assertLastInk(t, drawnLine(t, view, "Grep"), "┣", colorDim, "dim") + assertLastInk(t, drawnLine(t, view, "Grep"), "ok", colorMuted, "muted") + if fg := rowFg(m, slices.IndexFunc(m.visibleRows, func(r eventRow) bool { return r.tool != nil && r.tool.ID == "ok" })); fg[colStatus] != colorMuted { + t.Errorf("search: STATUS ok = %v, want muted", fg[colStatus]) + } +} + +func TestEventCellStyle_ToolRowsMutedInSubagentBlock(t *testing.T) { + withProfile(t, termenv.TrueColor) + events := slices.Concat(trExchange(1, 10, ""), trExchange(2, 20, "a1"), trExchange(3, 30, "")) + tl := &timeline.Timeline{Tools: []timeline.Tool{trTool(4, "sub", "Read", 22, 23, "x")}} + tl.Tools[0].Agent = "a1" + m := toolRowsModel(t, events, tl) + m.subagentOpen = map[string]bool{"a1": true} + m.rebuildEventsTable() + r, _ := toolRowAt(t, m, "sub") + for col, fg := range rowFg(m, r) { + if fg != colorMuted && fg != colorDim { + t.Errorf("column %v = %v, want muted", col, fg) + } + } + line := drawnLine(t, m.eventsTbl.View(), "Read") + assertLastInk(t, line, "│", colorDim, "dim") + assertLastInk(t, line, "Read", colorMuted, "muted") +} + +func TestRowQuiet(t *testing.T) { + skip := pipeline.Invocation{Plugin: "p", Action: pipeline.ActionSkip} + shadowDeny := pipeline.Invocation{Plugin: "p", Action: pipeline.ActionDeny, Shadow: true} + gateDeny := pipeline.Invocation{Plugin: "egress-gate", Action: pipeline.ActionDeny} + tunnel := func(invs ...pipeline.Invocation) cellContext { + ev := &pipeline.SessionEvent{Tunnel: true, Host: "tun.test:443"} + return cellContext{row: eventRow{event: ev}, invs: invs} + } + ctxs := []cellContext{ + {}, // 0: no invocations + {invs: []pipeline.Invocation{skip, skip}}, // 1: all skip + {invs: []pipeline.Invocation{shadowDeny}}, // 2: a shadow deny + {}, // 3: inactive, partner 2 is active + tunnel(), // 4: an unbridged tunnel + tunnel(gateDeny), // 5: a tunnel the gate denied + } + partner := map[int]int{3: 2, 2: 3} + want := []bool{true, true, false, false, true, false} + for j, w := range want { + if got := rowQuiet(ctxs, partner, j); got != w { + t.Errorf("row %d: rowQuiet = %v, want %v", j, got, w) + } + } +} + +// quietEvents are four exchanges to api.test: 1 and 4 quiet and answered 200, 2 active +// (modify) and answered 200, 3 quiet and answered 502. +func quietEvents() []pipeline.SessionEvent { + active := trExchange(2, 20, "") + active[0].Invocations = &pipeline.Invocations{Outbound: []pipeline.Invocation{ + {Plugin: "token-exchange", Action: pipeline.ActionModify}, + }} + failed := trExchange(3, 30, "") + failed[1].StatusCode = 502 + return slices.Concat(trExchange(1, 10, ""), active, failed, trExchange(4, 40, "")) +} + +// exchangeRow is the rendered row index of the exchange whose request has seq. +func exchangeRow(t *testing.T, m *model, seq uint64) int { + t.Helper() + i := slices.IndexFunc(m.visibleRows, func(r eventRow) bool { return r.event != nil && r.event.Seq == seq }) + if i < 0 { + t.Fatalf("no row for seq %d", seq) + } + return i +} + +// wantQuietFg checks row r of m is a quiet row: muted, except the columns in special, and a +// "—" cell, which is dim. +func wantQuietFg(t *testing.T, m *model, r int, special map[eventColumnID]lipgloss.AdaptiveColor) { + t.Helper() + row := m.eventsTbl.Rows()[r] + for col, fg := range rowFg(m, r) { + c, ok := special[col] + if !ok { + c = colorMuted + } + if strings.TrimSpace(row[colPos(m, col)]) == "—" { + c = colorDim + } + if fg != c { + t.Errorf("row %d: column %v = %v, want %v", r, col, fg, c) + } + } +} + +// Background traffic steps back (#2019 change 6): a quiet row is muted, a 5xx keeps its +// error ink, and a run of quiet rows dims what repeats the row above. An active row stops +// the run. +func TestEventCellStyle_QuietRows(t *testing.T) { + withProfile(t, termenv.TrueColor) + m := fitModel(t, paneEvents, 200, 40, quietEvents()) + r1, r2, r3, r4 := exchangeRow(t, m, 1), exchangeRow(t, m, 3), exchangeRow(t, m, 5), exchangeRow(t, m, 7) + if r2 != r1+1 || r3 != r2+1 || r4 != r3+1 { + t.Fatalf("rows %d %d %d %d are not adjacent", r1, r2, r3, r4) + } + wantQuietFg(t, m, r1, nil) + wantQuietFg(t, m, r3, map[eventColumnID]lipgloss.AdaptiveColor{ + colStatus: colorError, colHost: colorMuted, colMethod: colorMuted, colDir: colorMuted, + }) + // The row after r3 repeats it: DIR, METHOD and HOST are dim, TIME stays muted. + wantQuietFg(t, m, r4, map[eventColumnID]lipgloss.AdaptiveColor{ + colHost: colorDim, colMethod: colorDim, colDir: colorDim, + }) + if fg := rowFg(m, r2); fg[colStatus] != colorOK || fg[colDir] != colorOutbound { + t.Errorf("active row: STATUS %v, DIR %v; want ok and outbound ink", fg[colStatus], fg[colDir]) + } + view := m.eventsTbl.View() + assertInk(t, view, "502", colorError, "error") + assertLastInk(t, drawnLine(t, view, "502"), "api.test", colorMuted, "muted") +} + +// The quiet ink and the dim repeats follow the sorted rows, and key by column id with +// ACTION and PLUGIN hidden (#2019 Review Focus 2, 3). +func TestEventCellStyle_QuietFollowsSortAndColumns(t *testing.T) { + withProfile(t, termenv.TrueColor) + m := fitModel(t, paneEvents, 200, 40, quietEvents()) + m.eventColumns[colAction], m.eventColumns[colPlugin] = false, false + m.sortCol, m.sortDesc = colStatus, true + m.rebuildEventsTable() + if !strings.Contains(ansi.Strip(m.eventsTbl.View()), "STATUS▼") { + t.Fatal("no sorted STATUS header") + } + // Sorted: 502 (seq 5), then the 200s in arrival order (1, 3, 7). + order := []int{exchangeRow(t, m, 5), exchangeRow(t, m, 1), exchangeRow(t, m, 3), exchangeRow(t, m, 7)} + for i := 1; i < len(order); i++ { + if order[i] != order[0]+i { + t.Fatalf("sorted rows = %v, want adjacent from %d", order, order[0]) + } + } + fg := rowFg(m, order[0]) + if _, ok := fg[colAction]; ok { + t.Fatal("ACTION is hidden, but the hook styles it") + } + wantQuietFg(t, m, order[0], map[eventColumnID]lipgloss.AdaptiveColor{colStatus: colorError}) + // Seq 1 sits under the quiet 502 row now, so it repeats it. + wantQuietFg(t, m, order[1], map[eventColumnID]lipgloss.AdaptiveColor{ + colHost: colorDim, colMethod: colorDim, colDir: colorDim, + }) + if fg := rowFg(m, order[2]); fg[colStatus] != colorOK { + t.Errorf("active row STATUS = %v, want ok", fg[colStatus]) + } + // Seq 7 sits under the active row, so nothing on it is dim, though in arrival order it + // follows the quiet 502 row. + wantQuietFg(t, m, order[3], nil) +} + +// Search over quiet rows (#2019 Review Focus 1): a match keeps the match style on a muted +// cell and on a dim repeat, a marked row keeps its warn ink, and the selected quiet row +// keeps its tint. +func TestQuietRows_SearchMatchWins(t *testing.T) { + withProfile(t, termenv.TrueColor) + esc := func(s lipgloss.Style) string { return strings.SplitN(s.Render("x"), "x", 2)[0] } + st := tableStyles() + events := slices.Concat(trExchange(1, 10, ""), trExchange(2, 20, ""), trExchange(3, 30, "")) + for i := range events { + events[i].Host = "q.test" + } + // The third exchange's host is cut to HOST's width, so its match is off screen: marked. + events[4].Host, events[5].Host = "aaaaaaaaaaaaaaaaaaaaaaaaaaaa-tail.test", "aaaaaaaaaaaaaaaaaaaaaaaaaaaa-tail.test" + m := fitModel(t, paneEvents, 200, 40, events) + m.search = map[paneID]string{paneEvents: "q.test"} + m.rebuildEventsTable() + m.eventsTbl.SetCursor(exchangeRow(t, m, 1)) + r2 := exchangeRow(t, m, 3) + if fg := rowFg(m, r2); fg[colHost] != colorDim { + t.Fatalf("second row HOST = %v, want the dim repeat", fg[colHost]) + } + lines := []string{} + for _, l := range strings.Split(m.eventsTbl.View(), "\n") { + if strings.Contains(ansi.Strip(l), "q.test") { + lines = append(lines, l) + } + } + if len(lines) != 2 { + t.Fatalf("want 2 lines with q.test, got %d", len(lines)) + } + if !strings.Contains(lines[0], esc(st.Selected)) { + t.Errorf("selected quiet row lost its tint: %q", lines[0]) + } + if !strings.Contains(lines[1], st.Match.Render("q.test")) { + t.Errorf("dim repeat: match style lost: %q", lines[1]) + } + + m.search = map[paneID]string{paneEvents: "tail"} + m.rebuildEventsTable() + if got := rowLook(m.eventsTbl, "aaaaaaaaaaaa"); got != "marked" { + t.Errorf("quiet row with an off-screen match is %s, want marked", got) + } +} diff --git a/cmd/agentop/tui/events_column_sizing_test.go b/cmd/agentop/tui/events_column_sizing_test.go index 0a469e740..40990769f 100644 --- a/cmd/agentop/tui/events_column_sizing_test.go +++ b/cmd/agentop/tui/events_column_sizing_test.go @@ -192,11 +192,9 @@ func TestMeasureColumns_IgnoreTheSearchAndTheInactiveToggle(t *testing.T) { }{ // Every row stays, and the narrow exchange's one row is marked. {"search", func(m *model) { m.search = map[paneID]string{paneEvents: "narrow.example"} }, 2, 1}, - // No plugin acted on these fixture rows, so hiding inactive rows hides all of them. - {"hide inactive", func(m *model) { m.hideInactive = true }, 0, 0}, } { t.Run(tc.name, func(t *testing.T) { - m.search, m.hideInactive = nil, false + m.search = nil tc.apply(m) m.rebuildEventsTable() if got := len(m.eventsTbl.Rows()); got != tc.rows { diff --git a/cmd/agentop/tui/events_columns.go b/cmd/agentop/tui/events_columns.go index 326a64580..833ef1f06 100644 --- a/cmd/agentop/tui/events_columns.go +++ b/cmd/agentop/tui/events_columns.go @@ -53,7 +53,7 @@ type cellContext struct { blockIDs map[*pipeline.SessionEvent]int // invs is this row's invocations, computed once in the row loop. // - // rebuildEventsTable already needs them for the hideInactive check, and + // rebuildEventsTable already needs them for the quiet check, and // rowAction returns ACTION and PLUGIN together — so having each of those two // cells call row.invocations() ran it three times per row and discarded half of // rowAction's result twice. invocations() allocates (allInvocations, plus an @@ -154,8 +154,7 @@ type eventColumn struct { // rowKey is one rendered row's sort position: the column's value, plus which // exchange the row belongs to. // -// exchange is an ARRIVAL index — a position in the session's full row list, before -// hideInactive drops any. Each row is one exchange (#1681), so exchange is the row's own +// exchange is an ARRIVAL index — a position in the session's full row list. Each row is one exchange (#1681), so exchange is the row's own // arrival index. A tool row has the index of its exchange. It is only ever compared, never // used to index a slice, so it stays meaningful next to a filtered `keys`. type rowKey struct { @@ -504,12 +503,15 @@ const ( eventRowExchange eventRowKind = iota eventRowTool eventRowHeader + // eventRowQuiet is an exchange row no plugin acted on: background traffic. + eventRowQuiet ) // eventCellStyle is the events table's cell style hook for the columns cols, in the order -// tableColumns hands them to the table, and the rows of kinds. It reads each cell's column by -// id, never by position or header, so a hidden or sorted column moves no ink to another column. -func eventCellStyle(cols []eventColumn, kinds []eventRowKind) table.CellStyleFunc { +// tableColumns hands them to the table, the rows of kinds, and the table's rows. It reads each +// cell's column by id, never by position or header, so a hidden or sorted column moves no ink +// to another column. +func eventCellStyle(cols []eventColumn, kinds []eventRowKind, rows []table.Row) table.CellStyleFunc { ids := make([]eventColumnID, len(cols)) for i, c := range cols { ids[i] = c.id @@ -531,18 +533,36 @@ func eventCellStyle(cols []eventColumn, kinds []eventRowKind) table.CellStyleFun if col >= len(ids) || v == "" { return styleNone } + // A tool row steps back: all muted, except live state (running, ⋯) and a failed tool. if kind == eventRowTool { switch ids[col] { - case colIndex, colMethod: - return styleTool case colDuration: if strings.HasPrefix(v, "⋯") { - return styleTool + return styleWarn } case colStatus: - return groupStyle(statusGroup(v)) + if g := statusGroup(v); g == groupWarn || g == groupError { + return groupStyle(g) + } } - return styleNone + return styleMuted + } + // A quiet row steps back: all muted, except a failed STATUS. In a run of quiet rows, + // a DIR, ACTION, PLUGIN, METHOD or HOST that repeats the row above is dim, so the run + // reads as one block. + if kind == eventRowQuiet { + switch ids[col] { + case colStatus: + if statusGroup(v) == groupError { + return styleError + } + case colDir, colAction, colPlugin, colMethod, colHost: + if r > 0 && r <= len(rows) && kinds[r-1] == eventRowQuiet && + col < len(rows[r-1]) && strings.TrimSpace(rows[r-1][col]) == v { + return styleDim + } + } + return styleMuted } switch ids[col] { case colIndex, colTime, colHost, colBytes: @@ -577,8 +597,8 @@ func eventCellStyle(cols []eventColumn, kinds []eventRowKind) table.CellStyleFun // cannot widen it — the same reason every declared width leaves room for one (see // sortGlyphAsc). // -// ctxs should be every row of the session, not only those hideInactive keeps. Measured over -// the visible rows, hiding the one row with a saving would narrow TOKENS until the rows were +// ctxs should be every row of the session, not only the rendered ones. Measured over the +// rendered rows, collapsing the one row with a saving would narrow TOKENS until it was // shown again. func measureColumns(cols []eventColumn, ctxs []cellContext) (widths map[eventColumnID]int, cells map[eventColumnID][]string) { diff --git a/cmd/agentop/tui/events_pane.go b/cmd/agentop/tui/events_pane.go index ca9cdb6f4..31a9d3c12 100644 --- a/cmd/agentop/tui/events_pane.go +++ b/cmd/agentop/tui/events_pane.go @@ -19,8 +19,8 @@ import ( // eventKey pins a row to a specific event across rebuilds, so the // cursor follows the same event when the underlying slice shifts: -// FIFO eviction at session.max_events, a re-sort, hideInactive -// toggled. Zero value = unpinned. `at` is UnixNano so struct == is +// FIFO eviction at session.max_events, a re-sort, a block +// collapsed. Zero value = unpinned. `at` is UnixNano so struct == is // safe against time.Time's monotonic clock and Location pointer. type eventKey struct { at int64 @@ -92,7 +92,7 @@ func newEventsTable() table.Model { // beside the widths that actually decide, in eventColumns. // No sort column: the table is chronological until a model says otherwise. table.WithColumns(tableColumns(selectedColumns(defaultColumnSelection()), "", false)), - table.WithCellStyle(eventCellStyle(selectedColumns(defaultColumnSelection()), nil)), + table.WithCellStyle(eventCellStyle(selectedColumns(defaultColumnSelection()), nil, nil)), table.WithFocused(true), ) t.SetStyles(tableStyles()) @@ -117,6 +117,9 @@ type eventRow struct { // of its exchange. tool *toolRow last bool + // quiet is rowQuiet's answer for an exchange row, so the row's ink moves with it when + // sortEventRows reorders the rows. + quiet bool } // invocations returns every plugin invocation the row's ACTION/PLUGIN cell and the inactive @@ -134,15 +137,35 @@ func (er eventRow) invocations() []pipeline.Invocation { return invs } +// eventRowKinds is the kind of each of the first n rendered rows, read from m.visibleRows +// and m.headerRows. +func (m *model) eventRowKinds(n int) []eventRowKind { + kinds := make([]eventRowKind, n) + for i, vr := range m.visibleRows[:min(len(m.visibleRows), n)] { + switch { + case vr.tool != nil: + kinds[i] = eventRowTool + case vr.quiet: + kinds[i] = eventRowQuiet + } + } + for i := range m.headerRows { + if i < n { + kinds[i] = eventRowHeader + } + } + return kinds +} + // partnerActive reports whether row i's paired request or response is one a plugin -// acted on, so hideInactive keeps row i with it. +// acted on, so rowQuiet does not mute row i apart from it. func partnerActive(ctxs []cellContext, partner map[int]int, i int) bool { p, ok := partner[i] return ok && !eventInactive(ctxs[p].invs) } // rebuildEventsTable populates the events table from the cache for the -// currently selected session, applying hideInactive, marking the search's +// currently selected session, marking quiet rows and the search's // matches and preserving the cursor. Also // resizes the table height to account for the IDENTITY banner — when // the session has inbound identity, subtract the banner's rendered @@ -186,19 +209,14 @@ func (m *model) rebuildEventsTable() { // so a merged row keeps the number its request had, and # reads as it always did. eventRows, partner = mergeExchanges(eventRows, partner) - // One cellContext per row of the SESSION, before hideInactive drops any. The - // fitsContent columns are measured over all of them (see measureColumns), and the row - // loop below shows the cells measured there, so a column cannot be sized from one - // reading of a row and filled from another. - // - // That computes invocations, rowAction and the measured cells for rows hideInactive - // then hides, which the loop used to skip. Each is evaluated once per row, which is - // what showing every row pays on every rebuild anyway, so hiding rows never makes a - // rebuild dearer than showing them. + // One cellContext per row of the SESSION, including rows a collapsed block keeps off + // the screen. The fitsContent columns are measured over all of them (see + // measureColumns), and the row loop below shows the cells measured there, so a column + // cannot be sized from one reading of a row and filled from another. ref := m.lostRef(events) ctxs := make([]cellContext, len(eventRows)) for i, er := range eventRows { - // One invocations and one rowAction per row: hideInactive below reads invs, + // One invocations and one rowAction per row: rowQuiet below reads invs, // and the ACTION and PLUGIN cells read this one rowAction result rather than // each recomputing the pair and discarding half of it. Both consider the // folded tunnel's invocations too. @@ -221,7 +239,6 @@ func (m *model) rebuildEventsTable() { // the end of this function — see the note there on why the order matters. rows := make([]table.Row, 0, len(eventRows)) m.visibleRows = m.visibleRows[:0] - m.hiddenInactive = 0 // The older-events row goes first, with no event under it, like a subagent header. // lead is how many rows precede the events: the sort below must not move this one. @@ -236,8 +253,7 @@ func (m *model) rebuildEventsTable() { // Subagent blocks (#1047), only while CHRONOLOGICAL: under a sort the row // order is a ranking, and pulling a subagent's rows under a header would // contradict the very thing the operator sorted to see. Collected over the - // same population the row loop renders — the inactive filter is applied - // identically, via the same predicate — so a header's rollup counts the rows + // same population the row loop renders, so a header's rollup counts the rows // expanding it would show. // // headerRows is rebuilt with them; subagentOpen (the operator's collapses) @@ -248,7 +264,7 @@ func (m *model) rebuildEventsTable() { m.subagentOpen = nil } if m.sortCol == "" { - m.subagentBlocks = m.collectSubagentBlocks(ctxs, partner) + m.subagentBlocks = m.collectSubagentBlocks(ctxs) } else { m.subagentBlocks = nil } @@ -341,6 +357,7 @@ func (m *model) rebuildEventsTable() { row = append(row, c.render(cc)) } rows = append(rows, row) + cc.row.quiet = rowQuiet(ctxs, partner, j) m.visibleRows = append(m.visibleRows, cc.row) if q != "" { full = append(full, eventSearchRow(cols, droppedCols, cc)) @@ -358,19 +375,6 @@ func (m *model) rebuildEventsTable() { return ts } for j, cc := range ctxs { - // hideInactive (the `s` toggle) is off by default — every message is - // shown, including passthrough/skip-only ones, per "I should see all - // network messages". Turning it on focuses the timeline on plugin - // activity (deny/modify/observe/allow). It hides whole exchanges: a row whose - // partner is shown is shown too, or a routed request refused for its model — - // no plugin acts on the 403 — would look as if it never got an answer. - // The predicate is rowInactiveHidden, shared with collectSubagentBlocks - // so the two filter the same rows. - if m.rowInactiveHidden(ctxs, partner, j) { - m.hiddenInactive++ - continue - } - // Subagent blocks: a row naming an agent joins that agent's block, whose // header sits at the block's first surviving row. Collapsed (the default, // and always while no search is live) the row is not rendered at all — the @@ -397,9 +401,9 @@ func (m *model) rebuildEventsTable() { full = append(full, table.SearchRow{Cells: []string{text}}) } if m.blockOpen(b.id, b.subtask, q != "") { - // b.rows holds exactly the member rows that survived the - // inactive filter, in arrival order — the same population the - // loop below renders — so nothing is double-counted or skipped. + // b.rows holds exactly the member rows, in arrival order — the + // same population the loop below renders — so nothing is + // double-counted or skipped. for _, mj := range b.rows { renderEventRow(mj) } @@ -416,9 +420,9 @@ func (m *model) rebuildEventsTable() { // here — render takes its own copy — and no sortKey reads it. // // Each row is one exchange (#1681), so exchange is the row's own arrival - // index. j indexes ctxs, which is every row before hideInactive drops any. - // The sort never reads it as a position in `keys` — only compares two of - // them — so the filter's gaps are harmless. + // index. j indexes ctxs, which is every row of the session. The sort never + // reads it as a position in `keys` — only compares two of them — so a gap + // in the numbering is harmless. // // The exchange's tool rows take its key and its exchange (#1805). All three // tiers of sortEventRows then tie, and the row position keeps the tools @@ -463,18 +467,7 @@ func (m *model) rebuildEventsTable() { // or narrowing as figures arrive, which can push a column off the terminal or // let one back on. The third happens mid-stream with no keystroke behind it, so // none of them may re-anchor the pane under an operator who is reading it. - kinds := make([]eventRowKind, len(rows)) - for i, vr := range m.visibleRows[:min(len(m.visibleRows), len(rows))] { - if vr.tool != nil { - kinds[i] = eventRowTool - } - } - for i := range m.headerRows { - if i < len(kinds) { - kinds[i] = eventRowHeader - } - } - m.eventsTbl.SetCellStyle(eventCellStyle(cols, kinds)) + m.eventsTbl.SetCellStyle(eventCellStyle(cols, m.eventRowKinds(len(rows)), rows)) newCols := tableColumns(cols, m.sortCol, m.sortDesc) switch oldCols := m.eventsTbl.Columns(); { case slices.Equal(oldCols, newCols): @@ -500,7 +493,7 @@ func (m *model) rebuildEventsTable() { // next event, for every session long enough to scroll. setCursorVisible // carries the mechanics. // - the old `else if prevRow < len(rows)` skipped the restore entirely when - // the rows SHRANK under the cursor — a filter typed, hideInactive toggled. + // the rows SHRANK under the cursor — a filter typed, a block collapsed. // SetRows had clamped the index by then, so the cursor was left wherever // that landed, with an offset nobody reconciled. // @@ -630,8 +623,8 @@ func sortEventRows(rows []table.Row, visible []eventRow, full []table.SearchRow, // Tiers 2 and 3 do NOT flip. Descending flips which exchange comes first, never // the order of rows that tie. // - // Both tiers compare arrival indexes without indexing anything by them, so the - // gaps hideInactive leaves in that numbering cost nothing. + // Both tiers compare arrival indexes without indexing anything by them, so a + // gap in that numbering costs nothing. sort.SliceStable(idx, func(a, b int) bool { ia, ib := idx[a], idx[b] ka, kb := keys[ia], keys[ib] @@ -740,7 +733,7 @@ func buildEventRows(events []pipeline.SessionEvent) []eventRow { // then show that call's status and duration as this one's. A guessed pair stays two rows. // // Returns the merged rows and the partner map re-indexed onto them. Only guessed pairs are -// left in it, which is what rowInactiveHidden still needs to keep such a pair together. +// left in it, which is what rowQuiet still needs to judge such a pair together. func mergeExchanges(rows []eventRow, partner map[int]int) ([]eventRow, map[int]int) { out := make([]eventRow, 0, len(rows)) at := make(map[int]int, len(rows)) // index in rows → index in out diff --git a/cmd/agentop/tui/events_pane_test.go b/cmd/agentop/tui/events_pane_test.go index 6b8cf7b25..ade623a32 100644 --- a/cmd/agentop/tui/events_pane_test.go +++ b/cmd/agentop/tui/events_pane_test.go @@ -525,81 +525,6 @@ func TestBuildEventRows_TunnelInvocationsFoldIntoRow(t *testing.T) { } } -// TestRebuildEventsTable_HideInactive is the integration check for #5: the -// hideInactive toggle (predicate → row build → footer count) suppresses -// passthrough/skip-only messages while keeping partially-active ones. -func TestRebuildEventsTable_HideInactive(t *testing.T) { - events := []pipeline.SessionEvent{ - // active — a2a observe - {Direction: pipeline.Inbound, Phase: pipeline.SessionRequest, Host: "agent", - Invocations: &pipeline.Invocations{Inbound: []pipeline.Invocation{ - {Plugin: "jwt-validation", Action: pipeline.ActionSkip}, // partially-active: skip + observe - {Plugin: "a2a-parser", Action: pipeline.ActionObserve}, - }}}, - // inactive — no invocations (passthrough response) - {Direction: pipeline.Outbound, Phase: pipeline.SessionResponse, Host: "x", StatusCode: 200}, - // inactive — skip-only - {Direction: pipeline.Outbound, Phase: pipeline.SessionRequest, Host: "y", - Invocations: &pipeline.Invocations{Outbound: []pipeline.Invocation{ - {Plugin: "token-exchange", Action: pipeline.ActionSkip}, - }}}, - } - m := &model{selectedSess: "s", events: map[string][]pipeline.SessionEvent{"s": events}} - m.eventsTbl = newEventsTable() - - m.hideInactive = false - m.rebuildEventsTable() - if len(m.visibleRows) != 3 || m.hiddenInactive != 0 { - t.Fatalf("show-all: rows=%d hidden=%d, want 3/0", len(m.visibleRows), m.hiddenInactive) - } - - m.hideInactive = true - m.rebuildEventsTable() - if len(m.visibleRows) != 1 || m.hiddenInactive != 2 { - t.Fatalf("hide: rows=%d hidden=%d, want 1/2", len(m.visibleRows), m.hiddenInactive) - } - // The surviving row is the partially-active a2a message. - if action, _ := eventAction(m.visibleRows[0].invocations()); action != "observe" { - t.Errorf("surviving row action = %q, want observe", action) - } -} - -// The `s` toggle hides exchanges, not halves of one: an exchange is one row (#1681), -// and it shows when a plugin acted on either half. The live case is a routed -// request refused for its model: no plugin acts on the 403, and hiding it left the -// request looking as if it never got an answer. -func TestRebuildEventsTable_HideInactiveKeepsAnExchangeWhole(t *testing.T) { - routed := &pipeline.Invocations{Outbound: []pipeline.Invocation{ - {Plugin: "inference-router", Action: pipeline.ActionModify, Reason: "routed"}, - }} - observed := &pipeline.Invocations{Outbound: []pipeline.Invocation{ - {Plugin: "inference-parser", Action: pipeline.ActionObserve}, - }} - events := []pipeline.SessionEvent{ - // A request a plugin acted on, and its response no plugin did: shown. - {Direction: pipeline.Outbound, Phase: pipeline.SessionRequest, Host: "ete", RequestID: "a", Invocations: routed}, - {Direction: pipeline.Outbound, Phase: pipeline.SessionResponse, Host: "ete", RequestID: "a", StatusCode: 403}, - // A request no plugin acted on, and a response one did: shown. - {Direction: pipeline.Outbound, Phase: pipeline.SessionRequest, Host: "ete", RequestID: "b"}, - {Direction: pipeline.Outbound, Phase: pipeline.SessionResponse, Host: "ete", RequestID: "b", StatusCode: 200, Invocations: observed}, - // Neither half acted on: hidden. - {Direction: pipeline.Outbound, Phase: pipeline.SessionRequest, Host: "s3", RequestID: "c"}, - {Direction: pipeline.Outbound, Phase: pipeline.SessionResponse, Host: "s3", RequestID: "c", StatusCode: 200}, - } - m := &model{selectedSess: "s", events: map[string][]pipeline.SessionEvent{"s": events}, hideInactive: true} - m.eventsTbl = newEventsTable() - m.rebuildEventsTable() - - if len(m.visibleRows) != 2 || m.hiddenInactive != 1 { - t.Fatalf("rows=%d hidden=%d, want 2/1", len(m.visibleRows), m.hiddenInactive) - } - for i, want := range [][2]*pipeline.SessionEvent{{&events[0], &events[1]}, {&events[2], &events[3]}} { - if got := m.visibleRows[i]; got.event != want[0] || got.resp != want[1] { - t.Errorf("row %d = %+v, want request %s with its response", i, got, want[0].RequestID) - } - } -} - // TestComputeEventPairIDs pairs each response row with its preceding request // row by direction + host + method, sharing one # across the exchange and // minting fresh integers for unpaired rows. @@ -1570,53 +1495,6 @@ func TestSort_DurationLeavesUnpairedRowsAlone(t *testing.T) { } } -// activeInvocation makes a row survive hideInactive: the `s` toggle hides a row -// whose plugins all skipped, and eventInactive counts no invocations as inactive too. -func activeInvocation() *pipeline.Invocations { - return &pipeline.Invocations{Inbound: []pipeline.Invocation{{Action: pipeline.ActionObserve}}} -} - -// With `s` on, the sort still ranks whole exchanges. -// -// The sort keys carry an arrival index over the session's full row list, before -// hideInactive drops any, while the rendered rows are only what survived that filter. -// ONE hidden row shifts every later index by one, which is the fixture that catches a -// sort that reads the two index spaces as one. The hidden row here is a skip-only -// request with no response, which is the ordinary shape of one: a passthrough request -// no plugin acted on. -func TestSort_HideInactiveKeepsAnExchangeTogether(t *testing.T) { - base := time.Date(2026, 10, 13, 8, 0, 0, 0, time.UTC) - events := []pipeline.SessionEvent{ - // Hidden: no invocations, and no partner to vouch for it. Shifts every - // index below it by exactly one. - {Host: "hidden", RequestID: "h1", Phase: pipeline.SessionRequest, At: base}, - {Host: "slow", RequestID: "r1", Phase: pipeline.SessionRequest, At: base.Add(time.Second), Invocations: activeInvocation()}, - {Host: "slow", RequestID: "r1", Phase: pipeline.SessionResponse, At: base.Add(2 * time.Second), Duration: 11 * time.Minute, Invocations: activeInvocation()}, - {Host: "fast", RequestID: "r2", Phase: pipeline.SessionRequest, At: base.Add(3 * time.Second), Invocations: activeInvocation()}, - {Host: "fast", RequestID: "r2", Phase: pipeline.SessionResponse, At: base.Add(4 * time.Second), Duration: 90 * time.Millisecond, Invocations: activeInvocation()}, - } - - m := sortTestModel(events) - m.hideInactive = true - m.sortCol, m.sortDesc = colDuration, true - m.rebuildEventsTable() - - if m.hiddenInactive != 1 { - t.Fatalf("hid %d rows, want exactly 1 — an even shift cannot catch this", m.hiddenInactive) - } - want := []string{"slow", "fast"} - if got := hostsInOrder(m); !slices.Equal(got, want) { - t.Errorf("descending by duration with hideInactive =\n %v\nwant\n %v", got, want) - } - - m.sortDesc = false - m.rebuildEventsTable() - wantAsc := []string{"fast", "slow"} - if got := hostsInOrder(m); !slices.Equal(got, wantAsc) { - t.Errorf("ascending by duration with hideInactive =\n %v\nwant\n %v", got, wantAsc) - } -} - // Two exchanges that TIE on the sorted column keep arrival order, in both directions. // // Equal keys are the norm rather than the exception here: on STATUS almost every row is diff --git a/cmd/agentop/tui/events_tool_rows_test.go b/cmd/agentop/tui/events_tool_rows_test.go index 81c782a36..d6943257d 100644 --- a/cmd/agentop/tui/events_tool_rows_test.go +++ b/cmd/agentop/tui/events_tool_rows_test.go @@ -172,21 +172,6 @@ func TestToolRows_InExpandedBlock(t *testing.T) { } } -func TestToolRows_HideInactiveHidesTools(t *testing.T) { - events := slices.Concat(trExchange(1, 10, ""), trExchange(2, 20, "")) - events[2].Invocations = &pipeline.Invocations{Outbound: []pipeline.Invocation{{Plugin: "p", Action: pipeline.ActionAllow}}} - m := toolRowsModel(t, events, &timeline.Timeline{Tools: []timeline.Tool{ - trTool(2, "hidden", "Bash", 12, 13, ""), - trTool(4, "shown", "Bash", 22, 23, ""), - }}) - m.hideInactive = true - m.rebuildEventsTable() - toolRowAt(t, m, "shown") - if slices.ContainsFunc(m.visibleRows, func(r eventRow) bool { return r.tool != nil && r.tool.ID == "hidden" }) { - t.Errorf("the tool of a hidden exchange still shows") - } -} - // The issue (#1805): under a DURATION sort a long tool stays under its exchange, and it does // not rank above an exchange that took longer than its own. func TestToolRows_SortByDuration(t *testing.T) { diff --git a/cmd/agentop/tui/footer.go b/cmd/agentop/tui/footer.go index 0f20dd7a1..7b8ea5c72 100644 --- a/cmd/agentop/tui/footer.go +++ b/cmd/agentop/tui/footer.go @@ -37,7 +37,7 @@ func (m *model) footerView() string { // reading right now. if m.flash != "" && m.flashSticky { return styleTitle.Render(fitFlashLine(m.flash, m.width)) + "\n" + - renderHints(fitHintLine(m.helpView(), m.width)) + renderKeyBar(fitHintLine(m.helpView(), m.width), m.width) } // Connection state dot. @@ -133,7 +133,7 @@ func (m *model) footerView() string { hint := fitHintLine(m.helpView(), m.width) - return fitStatusLine(status.String(), m.width) + "\n" + renderHints(hint) + return fitStatusLine(status.String(), m.width) + "\n" + renderKeyBar(hint, m.width) } // fitStatusLine bounds the status row to the terminal. diff --git a/cmd/agentop/tui/footer_fit_test.go b/cmd/agentop/tui/footer_fit_test.go index 89ed52ae5..a56731318 100644 --- a/cmd/agentop/tui/footer_fit_test.go +++ b/cmd/agentop/tui/footer_fit_test.go @@ -57,7 +57,7 @@ func TestFitHintLine_DropsFromTheFront(t *testing.T) { got := fitHintLine(m.helpView(), 60) // The specialised, pane-specific keys go first. - for _, gone := range []string{"[↑↓] nav", "[c] columns", "[u] usage"} { + for _, gone := range []string{"[b/f] page", "[↵] detail", "[c] columns"} { if strings.Contains(got, gone) { t.Errorf("width 60 kept %q, which should have been dropped: %q", gone, got) } @@ -92,7 +92,7 @@ func TestFitHintLine_UnknownWidthIsUnchanged(t *testing.T) { } } -// The optional notices — hidden-message and dropped-column counts — must not +// The optional notices — older-event and dropped-column counts — must not // outlive the keys that let a user act on them. // // They were appended AFTER "[q] quit", and fitHintLine drops from the front, so at @@ -105,11 +105,10 @@ func TestFitHintLine_NoticesNeverOutliveQuit(t *testing.T) { }{ {"dropped columns", func(m *model) { m.eventColsDropped = 1 }}, {"many dropped columns", func(m *model) { m.eventColsDropped = 7 }}, - {"hidden messages", func(m *model) { m.hideInactive = true; m.hiddenInactive = 42 }}, + {"older events", func(m *model) { m.olderNotFetched = map[string]int{"": 42} }}, {"both notices", func(m *model) { m.eventColsDropped = 3 - m.hideInactive = true - m.hiddenInactive = 9 + m.olderNotFetched = map[string]int{"": 9} }}, } { m := &model{pane: paneEvents, eventColumns: defaultColumnSelection()} @@ -135,11 +134,10 @@ func TestFitHintLine_NoticesNeverOutliveQuit(t *testing.T) { func TestFooter_NoticesStillAppearWhenThereIsRoom(t *testing.T) { m := &model{pane: paneEvents, eventColumns: defaultColumnSelection()} m.eventColsDropped = 2 - m.hideInactive = true - m.hiddenInactive = 5 + m.olderNotFetched = map[string]int{"": 5} got := fitHintLine(m.helpView(), 220) - for _, want := range []string{"2 more columns", "5 hidden", "[?] keys", "[q] quit"} { + for _, want := range []string{"2 more columns", "5 older", "[?] keys", "[q] quit"} { if !strings.Contains(got, want) { t.Errorf("wide footer omits %q:\n%q", want, got) } diff --git a/cmd/agentop/tui/help_overlay.go b/cmd/agentop/tui/help_overlay.go index 0f149c023..7b4b89d82 100644 --- a/cmd/agentop/tui/help_overlay.go +++ b/cmd/agentop/tui/help_overlay.go @@ -320,7 +320,6 @@ var paneKeys = map[paneID]keyGroup{ bindings: []keyBinding{ {"↑↓ / jk", "navigate"}, {"↵ / → / l", "event detail"}, - {"s", "toggle passthru/skip rows"}, {"/ then tab", "search each row's details: ↵, n and N find the next match"}, {"c", "column picker (checkboxes + descriptions)"}, {"c then s", "sort by a column: desc → asc → chronological"}, @@ -691,6 +690,12 @@ func renderDrillPath(pane paneID, width int) string { return out } +// helpTwoColumnMinWidth is the narrowest body that is drawn in two columns. Each column +// needs the key indent (2), the key column (12), the gutter (2) and about 40 columns of +// description: 2*56, plus 3 for the separator. A 140-column terminal (134 of body) gets two +// columns, an 80-column one (74) gets one. +const helpTwoColumnMinWidth = 2*56 + 3 + // helpBodyLines builds the scrollable body of the key-help overlay, wrapped to // width: the active pane in full (emphasized), then where it can go, then the // spine, then the keys that work anywhere, then the spend drawer's own, then every @@ -701,6 +706,11 @@ func renderDrillPath(pane paneID, width int) string { // GLOBAL → a glyph wall, which answered the last question badly and the first // three not at all. // +// TWO COLUMNS ON A WIDE BODY (helpTwoColumnMinWidth). The left column holds this pane +// and where it can go, the right one the keys that work anywhere and the drill path, +// so the first screen answers more without a scroll. EVERY PANE stays one column below +// them, at the full width. +// // The other panes are rendered IN FULL, descriptions and all, rather than // compacted to their bare keys. `USAGE m w b s esc` told a reader that the // pane has five keys and nothing about what any of them do, which is the defect @@ -713,17 +723,29 @@ func helpBodyLines(pane paneID, width int) string { if width < helpMinProseWidth { width = helpMinProseWidth } - var sections []string + two := width >= helpTwoColumnMinWidth + colW := width + if two { + colW = (width - 3) / 2 + } + var left, right []string if g, ok := paneKeys[pane]; ok { - sections = append(sections, renderKeyGroup(g, true, width, 0)) + left = append(left, renderKeyGroup(g, true, colW, 0)) } - sections = append(sections, - renderJumpSection(pane, width), - renderDrillPath(pane, width), - ) + left = append(left, renderJumpSection(pane, colW)) for _, g := range helpGlobalGroups(pane) { - sections = append(sections, renderKeyGroup(g, false, width, 0)) + right = append(right, renderKeyGroup(g, false, colW, 0)) + } + drill := renderDrillPath(pane, colW) + + var sections []string + if two { + right = append(right, drill) + sections = append(sections, joinHelpColumns( + strings.Join(left, "\n\n"), strings.Join(right, "\n\n"), colW, width)) + } else { + sections = append(append(append(sections, left...), drill), right...) } // Every other pane, in full. The active pane is already rendered above. @@ -746,6 +768,29 @@ func helpBodyLines(pane paneID, width int) string { return strings.Join(sections, "\n\n") } +// joinHelpColumns draws left and right side by side, each line of left padded to colW, +// with a dim separator between. The shorter column is padded with blank lines. +// +// EACH ROW IS PADDED TO width, so the overlay spans the terminal as the one-column body +// does. A body one column short centred the panel one column in, and the base's key bar +// showed in the gap beside it. +func joinHelpColumns(left, right string, colW, width int) string { + l, r := strings.Split(left, "\n"), strings.Split(right, "\n") + sep := styleDim.Render(" │ ") + rows := make([]string, max(len(l), len(r))) + for i := range rows { + var a, b string + if i < len(l) { + a = l[i] + } + if i < len(r) { + b = r[i] + } + rows[i] = padRight(padRight(a, colW)+sep+b, width) + } + return strings.Join(rows, "\n") +} + // helpBodyWidth is the natural (unwrapped) width of the help body, used // to size the overlay before the terminal cap is applied. func helpBodyWidth(body string) int { diff --git a/cmd/agentop/tui/help_pane_map_test.go b/cmd/agentop/tui/help_pane_map_test.go index ac16ee4ed..fcee2990d 100644 --- a/cmd/agentop/tui/help_pane_map_test.go +++ b/cmd/agentop/tui/help_pane_map_test.go @@ -108,6 +108,13 @@ func TestHelpBody_EveryPaneSectionSpellsOutEveryDescription(t *testing.T) { t.Fatalf("body has no EVERY PANE section:\n%s", body) } for p := paneNamespaces; p <= lastPaneID; p++ { + // Read each pane in EVERY PANE, one column at full width: the active pane is drawn + // above it, in a column of a two-column body, so its prose wraps there. + body := body + if p == paneSessions { + body = helpBodyLines(paneEvents, helpWide) + } + body = sectionFrom(t, body, everyPaneTitle, false) g := paneKeys[p] name := paneName(p) if !strings.Contains(body, name) { @@ -443,15 +450,11 @@ func TestHelpNavKeys_NoteNamesTheOneExceptionCorrectly(t *testing.T) { } } -// `s` was Usage's session toggle. Removed, it must do nothing there, not reach the -// global hide-inactive toggle for an Events table the user cannot see. +// `s` was Usage's session toggle. Removed, it must do nothing there. func TestUsagePane_RemovedSKeyDoesNothing(t *testing.T) { m := &model{pane: paneUsage, selectedSess: "s1"} m.usage.session = "s1" m.handleKey(keyRune('s')) - if m.hideInactive { - t.Error("`s` on Usage toggled hideInactive through the global handler") - } if m.pane != paneUsage || m.usage.session != "s1" { t.Errorf("`s` on Usage changed pane %v or scope %q", m.pane, m.usage.session) } @@ -509,18 +512,20 @@ func TestHelpBody_WrapsProseToTheGivenWidth(t *testing.T) { } } -// `s` hides the Events table's passthrough rows, so it works only where that table is. -func TestSKey_TogglesOnlyOnEvents(t *testing.T) { - for _, p := range []paneID{paneSessions, paneAgents, panePipeline, paneTimeline, paneDetail, paneUsage} { - m := &model{pane: p} - m.handleKey(keyRune('s')) - if m.hideInactive { - t.Errorf("pane %v: `s` toggled hideInactive off the Events pane", p) - } - } - m := &model{pane: paneEvents} +// `s` on Events was the hide-passthru toggle (#2019 removed it: quiet rows show muted +// instead). Pressing it now must change nothing: not the rows, the footer or the cursor. +func TestEventsS_DoesNothing(t *testing.T) { + m := newTestEventsModel(t) + m.eventsTbl.SetCursor(2) + rows, footer, cur := len(m.visibleRows), m.helpView(), m.eventsTbl.Cursor() m.handleKey(keyRune('s')) - if !m.hideInactive { - t.Error("`s` on Events did not toggle hideInactive") + if got := len(m.visibleRows); got != rows { + t.Errorf("`s` on Events changed the rows: %d, want %d", got, rows) + } + if got := m.helpView(); got != footer { + t.Errorf("`s` on Events changed the footer:\n got %q\nwant %q", got, footer) + } + if got := m.eventsTbl.Cursor(); got != cur { + t.Errorf("`s` on Events moved the cursor: %d, want %d", got, cur) } } diff --git a/cmd/agentop/tui/help_two_column_test.go b/cmd/agentop/tui/help_two_column_test.go new file mode 100644 index 000000000..9fbca8453 --- /dev/null +++ b/cmd/agentop/tui/help_two_column_test.go @@ -0,0 +1,231 @@ +package tui + +import ( + "strings" + "testing" + + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" + "github.com/charmbracelet/x/ansi" + "github.com/muesli/termenv" +) + +// helpSep is the plain text of the separator between the two help columns. +const helpSep = " │ " + +// helpColumns splits a two-column body line into its left and right column. ok is false +// when the line has no separator. +func helpColumns(line string) (left, right string, ok bool) { + plain := ansi.Strip(line) + i := strings.Index(plain, helpSep) + if i < 0 { + return "", "", false + } + return plain[:i], plain[i+len(helpSep):], true +} + +// TestHelpBody_TwoColumnsAt140: a 140-column terminal gives a 134-column body, which has +// the pane group on the left beside ANYWHERE on the right, and EVERY PANE below them in +// one column. +func TestHelpBody_TwoColumnsAt140(t *testing.T) { + const width = 134 + colW := (width - 3) / 2 + body := helpBodyLines(paneSessions, width) + lines := strings.Split(body, "\n") + + left, right, ok := helpColumns(lines[0]) + if !ok { + t.Fatalf("first line has no %q separator: %q", helpSep, ansi.Strip(lines[0])) + } + if !strings.HasPrefix(left, paneKeys[paneSessions].title) { + t.Errorf("left column does not start with the pane group: %q", left) + } + if !strings.HasPrefix(right, anywhereTitle) { + t.Errorf("right column does not start with %q: %q", anywhereTitle, right) + } + + var leftText, rightText strings.Builder + every := -1 + for i, ln := range lines { + if w := lipgloss.Width(ln); w > width { + t.Errorf("line %d is %d columns, over %d: %q", i, w, width, ansi.Strip(ln)) + } + if strings.HasPrefix(ansi.Strip(ln), everyPaneTitle) { + every = i + break + } + l, r, ok := helpColumns(ln) + if !ok { + continue + } + if lipgloss.Width(l) != colW { + t.Errorf("line %d: left column is %d wide, want %d: %q", i, lipgloss.Width(l), colW, l) + } + leftText.WriteString(l + "\n") + rightText.WriteString(r + "\n") + } + if every < 0 { + t.Fatalf("no %q section in one column:\n%s", everyPaneTitle, ansi.Strip(body)) + } + for _, ln := range lines[every:] { + if strings.Contains(ansi.Strip(ln), helpSep) { + t.Errorf("EVERY PANE has a column separator: %q", ansi.Strip(ln)) + } + } + + l, r := leftText.String(), rightText.String() + if !(strings.Index(l, paneKeys[paneSessions].title) < strings.Index(l, jumpSectionTitle)) { + t.Errorf("left column is not the pane group then %q:\n%s", jumpSectionTitle, l) + } + order := []string{anywhereTitle, helpNavTitle, spendDrawerTitle, drillSectionTitle} + at := -1 + for _, title := range order { + i := strings.Index(r, title) + if i <= at { + t.Errorf("right column does not hold %v in order (at %q):\n%s", order, title, r) + break + } + at = i + } +} + +// TestHelpBody_OneColumnAt80: an 80-column terminal gives a 74-column body, which stays +// one column, in the order of today. +func TestHelpBody_OneColumnAt80(t *testing.T) { + body := ansi.Strip(helpBodyLines(paneSessions, 74)) + if strings.Contains(body, helpSep) { + t.Fatalf("74-column body has a column separator:\n%s", body) + } + order := []string{paneKeys[paneSessions].title, jumpSectionTitle, drillSectionTitle, + anywhereTitle, helpNavTitle, spendDrawerTitle, everyPaneTitle} + at := -1 + for _, title := range order { + i := strings.Index(body, title) + if i <= at { + t.Fatalf("body does not hold %v in order (at %q):\n%s", order, title, body) + } + at = i + } +} + +// TestHelpBody_WrapsUnderDescription: in a column, a long description wraps to the +// description column, not to the key column, and no line is wider than its column. +func TestHelpBody_WrapsUnderDescription(t *testing.T) { + const width = 134 + colW := (width - 3) / 2 + lines := strings.Split(helpBodyLines(paneSessions, width), "\n") + for i, ln := range lines { + l, r, ok := helpColumns(ln) + if !ok { + continue + } + // The row is padded to the full width (so the overlay spans the terminal); the + // right column's text still ends inside colW. + if lipgloss.Width(ln) != width { + t.Errorf("line %d is %d columns, want the full %d", i, lipgloss.Width(ln), width) + } + if lipgloss.Width(l) > colW || lipgloss.Width(strings.TrimRight(r, " ")) > colW { + t.Errorf("line %d is wider than its %d-column column: %q | %q", i, colW, l, r) + } + } + + // A pane binding whose description needs more than one row at this column width. + checked := 0 + for _, kb := range paneKeys[paneSessions].bindings { + row := -1 + for i, ln := range lines { + if l, _, ok := helpColumns(ln); ok && strings.HasPrefix(strings.TrimSpace(l), kb.keys+" ") { + row = i + break + } + } + if row < 0 || row+1 >= len(lines) { + continue + } + l, _, _ := helpColumns(lines[row]) + first := strings.Fields(kb.desc)[0] + descCol := strings.Index(l, " "+first) + 2 + wrapped := wrapWords(kb.desc, colW-descCol) + if len(wrapped) < 2 { + continue + } + next, _, _ := helpColumns(lines[row+1]) + want := strings.Repeat(" ", descCol) + wrapped[1] + if strings.TrimRight(next, " ") != want { + t.Errorf("%q wraps to %q, want %q (under the description)", kb.keys, next, want) + } + checked++ + } + if checked == 0 { + t.Fatal("setup: no sessions binding wraps at this width") + } +} + +// TestHelpBody_CurrentPaneEmphasis: in two columns, the pane group keeps its title style +// and its key style. +func TestHelpBody_CurrentPaneEmphasis(t *testing.T) { + restore := lipgloss.ColorProfile() + t.Cleanup(func() { lipgloss.SetColorProfile(restore) }) + lipgloss.SetColorProfile(termenv.TrueColor) + + g := paneKeys[paneSessions] + body := helpBodyLines(paneSessions, 134) + if want := styleTitle.Render(g.title); !strings.Contains(body, want) { + t.Errorf("pane group title is not in styleTitle: want %q in\n%q", want, body) + } + if want := styleOK.Render(padRight(g.bindings[0].keys, helpKeyColWidth)); !strings.Contains(body, want) { + t.Errorf("pane group keys are not in styleOK: want %q", want) + } + if want := styleDim.Render(helpSep); !strings.Contains(body, want) { + t.Errorf("separator is not dim: want %q", want) + } + lipgloss.SetColorProfile(termenv.Ascii) + plain := helpBodyLines(paneSessions, 134) + if ansi.Strip(body) != plain { + t.Error("the plain text differs under TrueColor and Ascii") + } +} + +// TestHelpOverlay_TwoColumnsScroll: the two-column body still scrolls, and the foot says +// so. +func TestHelpOverlay_TwoColumnsScroll(t *testing.T) { + m := helpModelAt(t, paneSessions, 140, 20) + if m.helpVp.TotalLineCount() <= m.helpVp.VisibleLineCount() { + t.Fatal("setup: the body fits, so nothing scrolls") + } + if v := stripANSI(m.View()); !strings.Contains(v, "[↑↓] scroll 0%") { + t.Errorf("no scroll hint on the two-column overlay:\n%s", v) + } + m.Update(keyRune('G')) + if !m.helpVp.AtBottom() { + t.Error("G did not reach the bottom of the two-column body") + } +} + +// TestHelpSearch_FindsTheRightColumn: a search on a two-column body highlights a match in +// the right column, and n moves to it. +func TestHelpSearch_FindsTheRightColumn(t *testing.T) { + restore := lipgloss.ColorProfile() + t.Cleanup(func() { lipgloss.SetColorProfile(restore) }) + lipgloss.SetColorProfile(termenv.TrueColor) + + const q = "cycle the axis" + m := helpModelAt(t, paneSessions, 140, 40) + typeKeys(m, "/"+q) + press(m, tea.KeyEnter) + if len(m.helpDoc.matches) != 1 { + t.Fatalf("matches = %v, want one", m.helpDoc.matches) + } + row := m.helpDoc.matches[0] + line := ansi.Strip(m.helpDoc.lines[row]) + if i := strings.Index(line, helpSep); i < 0 || strings.Index(line, q) < i { + t.Fatalf("setup: the match is not in the right column: %q", line) + } + m.Update(keyRune('n')) + if r, ok := m.helpDoc.currentRow(); !ok || r != row { + t.Errorf("n: current = %d,%v, want %d", r, ok, row) + } + if want := styleCurrentMatch.Render(q); !strings.Contains(m.helpVp.View(), want) { + t.Errorf("the right-column match is not highlighted: want %q in\n%q", want, m.helpVp.View()) + } +} diff --git a/cmd/agentop/tui/key_bar_short_test.go b/cmd/agentop/tui/key_bar_short_test.go new file mode 100644 index 000000000..73ae0ce02 --- /dev/null +++ b/cmd/agentop/tui/key_bar_short_test.go @@ -0,0 +1,125 @@ +package tui + +import ( + "context" + "strings" + "testing" + + "github.com/charmbracelet/x/ansi" + "github.com/muesli/termenv" + + "github.com/rossoctl/cortex/core/session/timeline" +) + +// The Sessions bar shows only the keys that act on the pane (#2019 change 9). +func TestHelpView_SessionsShort(t *testing.T) { + const want = "[↵] drill [u] usage [$] spend [/] search [?] keys [q] quit" + m := &model{pane: paneSessions} + if got := m.helpView(); got != want { + t.Fatalf("sessions hints\n got %q\nwant %q", got, want) + } + + withProfile(t, termenv.Ascii) + if got := renderKeyBar(fitHintLine(m.helpView(), 200), 200); got != want { + t.Errorf("Ascii bar %q, want %q", got, want) + } + withProfile(t, termenv.TrueColor) + bar := ansi.Strip(renderKeyBar(fitHintLine(m.helpView(), 200), 200)) + // Chips pad each key with one space, so compare the words. + if got, w := strings.Join(strings.Fields(bar), " "), "↵ drill u usage $ spend / search ? keys q quit"; got != w { + t.Errorf("TrueColor bar words %q, want %q", got, w) + } + if strings.Contains(bar, "[") { + t.Errorf("TrueColor bar keeps brackets: %q", bar) + } +} + +func TestHelpView_ShortBarPerPane(t *testing.T) { + agentsVia := &model{pane: paneSessions, sessionsViaAgents: true} + pods := &model{pane: paneSessions, parentCtx: context.Background()} + ns := &model{pane: paneNamespaces} + for _, tc := range []struct { + name string + m *model + want string + }{ + {"sessions via agents", agentsVia, "[↵] drill [u] usage [$] spend [/] search [esc] agents [?] keys [q] quit"}, + {"sessions via pods", pods, "[↵] drill [u] usage [$] spend [/] search [esc] pods [?] keys [q] quit"}, + {"events", &model{pane: paneEvents, eventColumns: defaultColumnSelection()}, + "[b/f] page [↵] detail [c] columns [u] usage [/] search [esc] back [?] keys [q] quit"}, + {"detail", &model{pane: paneDetail}, + "[↵] fold [tab] response [u] usage [/] search [esc] back [?] keys [q] quit"}, + {"pipeline", &model{pane: panePipeline}, + "[↵] plugin detail [e] edit [esc] back [/] search [?] keys [q] quit"}, + {"plugin detail", &model{pane: panePluginDetail}, "[/] search [esc] back [?] keys [q] quit"}, + {"namespaces", ns, + "[↵] open [L] " + shortHost(ns.localEndpointOr()) + " [r] reload [/] search [?] keys [q] quit"}, + {"pods", &model{pane: panePods}, "[↵] connect [Esc] back [r] reload [/] search [?] keys [q] quit"}, + } { + if got := tc.m.helpView(); got != tc.want { + t.Errorf("%s\n got %q\nwant %q", tc.name, got, tc.want) + } + } + + ag := &model{pane: paneAgents} + if got, want := ag.helpView(), "[↵] scope to this agent [esc] back [w] "+ag.agentsWindowLabel()+ + " [$] spend [/] search [?] keys [q] quit"; got != want { + t.Errorf("agents\n got %q\nwant %q", got, want) + } +} + +// The Timeline bar never offers [↑↓], even when rows are hidden: the help lists it. +func TestHelpView_TimelineShort(t *testing.T) { + m := timelineModel(t, 140, 46) + m.timeline.windowIdx = 3 + many := sampleTimeline() + for i := 0; i < 20; i++ { + id := string(rune('b' + i)) + many.Agents = append(many.Agents, timeline.Agent{ID: id, Parent: timeline.MainAgent, Label: "subagent " + id}) + } + m.timeline.tl, m.timeline.layoutKey = many, tlLayoutKey{} + m.layout() + if lay, ok := m.timelineLayoutNow(); !ok || m.timelineScrollMax(lay) == 0 { + t.Fatal("fixture hides no rows") + } + _, _, _, win := m.timelineRange() + want := "[w] " + timelineWindows[win].label + " [←→] moment [enter] events [/] search [esc] back [?] keys [q] quit" + if got := m.helpView(); got != want { + t.Errorf("timeline\n got %q\nwant %q", got, want) + } +} + +// Each key a bar no longer shows is still in that pane's ? help. +func TestHelpOverlay_ListsRemovedKeys(t *testing.T) { + removed := map[paneID][]string{ + paneNamespaces: {"↑↓ / jk"}, + panePods: {"↑↓ / jk"}, + paneSessions: {"↑↓ / jk", "p ", "P "}, + paneEvents: {"↑↓ / jk", "p "}, + paneDetail: {"↑↓ "}, + panePipeline: {"↑↓ / jk"}, + panePluginDetail: {"↑↓ "}, + paneTimeline: {"↑ ↓ / k j"}, + paneAgents: {"↑↓ / jk"}, + } + for pane, keys := range removed { + body := ansi.Strip(helpBodyLines(pane, 200)) + for _, k := range keys { + if !helpHasKey(body, k) { + t.Errorf("%s help does not list %q", paneName(pane), k) + } + } + } +} + +// helpHasKey reports whether a help line starts its key column with k. +func helpHasKey(body, k string) bool { + for _, line := range strings.Split(body, "\n") { + for _, col := range strings.Split(line, "│") { + if strings.HasPrefix(strings.TrimLeft(col, " "), k) { + return true + } + } + } + return false +} diff --git a/cmd/agentop/tui/key_bar_test.go b/cmd/agentop/tui/key_bar_test.go new file mode 100644 index 000000000..a8cb1ca05 --- /dev/null +++ b/cmd/agentop/tui/key_bar_test.go @@ -0,0 +1,199 @@ +package tui + +import ( + "context" + "strings" + "testing" + + "github.com/charmbracelet/lipgloss" + "github.com/charmbracelet/x/ansi" + "github.com/muesli/termenv" +) + +// runeSGR returns, for each printed rune of s, the SGR parameters in force when it is drawn. +func runeSGR(s string) []string { + var out []string + cur := "" + for i := 0; i < len(s); { + if strings.HasPrefix(s[i:], "\x1b[") { + end := strings.IndexByte(s[i:], 'm') + params := s[i+2 : i+end] + if params == "0" || params == "" { + cur = "" + } else { + cur += ";" + params + ";" + } + i += end + 1 + continue + } + _, size := firstRune(s[i:]) + out = append(out, cur) + i += size + } + return out +} + +func firstRune(s string) (rune, int) { + for _, r := range s { + return r, len(string(r)) + } + return 0, 0 +} + +// sgrOf is the SGR parameters TrueColor emits for c in the current theme. +func sgrOf(c lipgloss.AdaptiveColor, bg bool) string { + hex := c.Light + if lipgloss.HasDarkBackground() { + hex = c.Dark + } + return ";" + termenv.TrueColor.Color(hex).Sequence(bg) + ";" +} + +// checkBar asserts out is the key bar for the plain hint fitted at width w. +func checkBar(t *testing.T, out, fitted string, w int) { + t.Helper() + if got := lipgloss.Width(out); got != w { + t.Fatalf("bar width %d, want %d", got, w) + } + want := chipText(fitted) + if got := strings.TrimRight(ansi.Strip(out), " "); got != strings.TrimRight(want, " ") { + t.Fatalf("bar text %q, want %q", got, want) + } + // Mark the runes of each chip in the plain text. + var chip []bool + for _, p := range splitHintChips(fitted) { + n := len([]rune(p.text)) + if p.chip { + n += 2 + } + for range n { + chip = append(chip, p.chip) + } + } + bar, chipBg, chipFg := sgrOf(colorBarBg, true), sgrOf(colorBarChipBg, true), sgrOf(colorBarChipFg, false) + for i, sgr := range runeSGR(out) { + if i < len(chip) && chip[i] { + if !strings.Contains(sgr, chipBg) || !strings.Contains(sgr, chipFg) { + t.Fatalf("chip rune %d drawn with %q, want %q and %q", i, sgr, chipBg, chipFg) + } + } else if !strings.Contains(sgr, bar) { + t.Fatalf("rune %d drawn with %q, want bar background %q", i, sgr, bar) + } + } +} + +func eachTheme(t *testing.T, f func(t *testing.T)) { + orig := lipgloss.HasDarkBackground() + t.Cleanup(func() { lipgloss.SetHasDarkBackground(orig) }) + for _, dark := range []bool{true, false} { + lipgloss.SetHasDarkBackground(dark) + t.Run(map[bool]string{true: "dark", false: "light"}[dark], f) + } +} + +func TestRenderKeyBar_FullWidthUnderColor(t *testing.T) { + withProfile(t, termenv.TrueColor) + h := "[↵] drill [u] usage [/] search [?] keys [q] quit" + eachTheme(t, func(t *testing.T) { + fitted := fitHintLine(h, 100) + checkBar(t, renderKeyBar(fitted, 100), fitted, 100) + // The trailing form: a head with brackets that are not keys. + line := "error: [::1] " + h + checkBarHead(t, renderTrailingKeyBar(line, h, 100), "error: [::1] ", h, 100) + }) +} + +// checkBarHead is checkBar for a trailing bar whose head keeps its brackets. +func checkBarHead(t *testing.T, out, head, keys string, w int) { + t.Helper() + if got := lipgloss.Width(out); got != w { + t.Fatalf("bar width %d, want %d", got, w) + } + if got, want := strings.TrimRight(ansi.Strip(out), " "), head+chipText(keys); got != want { + t.Fatalf("bar text %q, want %q", got, want) + } + bar := sgrOf(colorBarBg, true) + for i, sgr := range runeSGR(out)[:len([]rune(head))] { + if !strings.Contains(sgr, bar) { + t.Fatalf("head rune %d drawn with %q, want bar background", i, sgr) + } + } +} + +// Review Focus 4: a cut that starts with "… " and ends in half a bracket still fills the +// width with the bar, and the half bracket is not a chip. +func TestRenderKeyBar_CutHintFillsWidth(t *testing.T) { + withProfile(t, termenv.TrueColor) + h := "[↵] drill [u] usage [/] search [?] keys [q] quit" + eachTheme(t, func(t *testing.T) { + for _, w := range []int{30, 20, 6} { + fitted := fitHintLine(h, w) + if w == 30 && !strings.HasPrefix(fitted, "… ") { + t.Fatalf("fit at %d = %q, want a … cut", w, fitted) + } + checkBar(t, renderKeyBar(fitted, w), fitted, w) + } + half := "… [esc] back [es" + checkBar(t, renderKeyBar(half, 40), half, 40) + if s := ansi.Strip(renderKeyBar(half, 40)); !strings.Contains(s, "[es") { + t.Fatalf("half bracket became a chip: %q", s) + } + }) +} + +func TestRenderKeyBar_AsciiUnchanged(t *testing.T) { + withProfile(t, termenv.Ascii) + eachTheme(t, func(t *testing.T) { + for _, in := range []string{"[↵] open [/] search", "… [es"} { + if got, want := renderKeyBar(in, 100), renderHints(in); got != want { + t.Fatalf("renderKeyBar(%q) = %q, want %q", in, got, want) + } + if got, want := renderTrailingKeyBar("x "+in, in, 100), renderTrailingHints("x "+in, in); got != want { + t.Fatalf("renderTrailingKeyBar = %q, want %q", got, want) + } + } + }) +} + +func TestRenderKeyBar_NoPadWithoutWidth(t *testing.T) { + withProfile(t, termenv.TrueColor) + in := "[q] quit" + if got := lipgloss.Width(renderKeyBar(in, 0)); got != lipgloss.Width(in) { + t.Fatalf("width %d with no terminal width, want %d", got, lipgloss.Width(in)) + } +} + +// The last line of every screen that draws the key bar fills the terminal width; the status +// line above it is unchanged. +func TestKeyBar_LastLineOfEachScreen(t *testing.T) { + withProfile(t, termenv.TrueColor) + lastLine := func(s string) string { l := strings.Split(s, "\n"); return l[len(l)-1] } + bar := sgrOf(colorBarBg, true) + isBar := func(line string, w int) bool { + sgr := runeSGR(line) + return lipgloss.Width(line) == w && strings.Contains(sgr[0], ";48;") && strings.Contains(sgr[len(sgr)-1], bar) + } + + m := fitModel(t, paneSessions, 120, 30, nil) + m.layout() + if got := lastLine(m.footerView()); !isBar(got, 120) { + t.Fatalf("session footer bar %q: width %d, want 120 with the bar color", got, lipgloss.Width(got)) + } + m.flash, m.flashSticky = "yanked → /tmp/x", true + if got := lastLine(m.footerView()); !isBar(got, 120) { + t.Fatalf("sticky-flash footer bar: width %d, want 120", lipgloss.Width(got)) + } + + lister := &fakeLister{namespaces: fixtureNamespaces} + pm := newPickerModel(context.Background(), lister, nil) + updated, _ := pm.Update(pm.Init()()) + mm := updated.(*model) + mm.width, mm.height = 120, 30 + if got := lastLine(mm.View()); !isBar(got, 120) { + t.Fatalf("namespaces footer bar: width %d, want 120", lipgloss.Width(got)) + } + mm.pane = panePods + if got := lastLine(mm.View()); !isBar(got, 120) { + t.Fatalf("pods footer bar: width %d, want 120", lipgloss.Width(got)) + } +} diff --git a/cmd/agentop/tui/keys.go b/cmd/agentop/tui/keys.go index 87c220308..16c366b9b 100644 --- a/cmd/agentop/tui/keys.go +++ b/cmd/agentop/tui/keys.go @@ -2,6 +2,7 @@ package tui import ( "fmt" + "strings" "time" tea "github.com/charmbracelet/bubbletea" @@ -336,9 +337,8 @@ func (m *model) handleKey(msg tea.KeyMsg) tea.Cmd { // inheriting the previous column's direction — a fresh column is a fresh // question. // - // `s` does not collide with the global hideInactive toggle: this modal block - // returns before the global switch is reached, the same way its `r` shadows - // nothing. + // `s` is free outside this modal block: the Events hide toggle it once + // shadowed was removed in #2019. id := eventColumns[m.colCursor].id switch { case eventColumns[m.colCursor].sortKey == nil: @@ -484,18 +484,6 @@ func (m *model) handleKey(msg tea.KeyMsg) tea.Cmd { } return nil - case "s": - // Toggle hiding of passthrough / skip-only messages. Default is - // off (show everything); turning it on focuses the timeline on - // plugin activity. Events only: on another pane it would change a - // table the user cannot see. - if m.pane != paneEvents { - return nil - } - m.hideInactive = !m.hideInactive - m.rebuildEventsTable() - return nil - case "esc", "left", "h": // Back-out: plugin-detail → pipeline (or catalog if we came from there); // detail → events; events → sessions; pipeline and usage → the @@ -1156,6 +1144,9 @@ func (m *model) setStickyFlash(s string) { // helpView renders the keybinding hint line for the current pane. Short // enough to fit on a single row at 80 cols. +// +// ONLY THE KEYS THAT ACT ON THIS PANE (#2019). General keys a user guesses or +// looks up once — ↑↓/jk, p pause, P plugins — are in the ? help only, and still work. func (m *model) helpView() string { if m.searching { if m.searchPane == paneEvents { @@ -1165,10 +1156,10 @@ func (m *model) helpView() string { } switch m.pane { case paneNamespaces: - return "[↑↓/jk] nav [↵] open [L] " + shortHost(m.localEndpointOr()) + + return "[↵] open [L] " + shortHost(m.localEndpointOr()) + " [r] reload " + m.searchHints(m.pane) + " [?] keys [q] quit" case panePods: - return "[↑↓/jk] nav [↵] connect [Esc] back [r] reload " + m.searchHints(m.pane) + " [?] keys [q] quit" + return "[↵] connect [Esc] back [r] reload " + m.searchHints(m.pane) + " [?] keys [q] quit" case paneSessions: // THE PER-SESSION SCOPE IS NOT SAID HERE. It was, as a leading notice; then the pane's // title carried it as " · lifetime totals"; now neither does. See paneView's sessions @@ -1185,53 +1176,30 @@ func (m *model) helpView() string { // from the line those two describe — so the drawer existed only for a reader who went // looking for it. Placed after [u] so fitHintLine, which drops from the front, gives up // the navigation keys before either of the two that reach cost. - // [P] plugins sits at the TAIL, not where [tab] pipeline used to sit third - // from the left. The tab strip in the title bar survived every width; a footer - // hint does not, and fitHintLine drops from the front — so the key that - // replaced the strip is placed behind the hints it is willing to outlive. - // - // THE HINT SAYS "plugins" WHILE THE PANE TITLES ITSELF "pipeline", and the - // mismatch is deliberate (#1212). "pipeline" is the config noun — what the - // YAML declares and what [e] edits — but a reader meeting this footer has not - // seen that YAML, and the first thing the pane shows them is a table whose main - // column is PLUGIN. The footer is where a key gets DISCOVERED, so it is named - // for what the pane shows rather than for the concept behind it; the [?] - // overlay, which has room, carries the precise version ("the plugin chain this - // proxy runs"). The pane also lists the plugins the proxy offers but does not run, - // under its "available" divider. - // - // MEASURED, because the intuition here is off by more than it looks: the - // un-drilled line is 98 columns, and [P] survives down to 34 columns at the - // tail versus 79 third from the left. So the two placements are equivalent at - // the classic 80-column floor — 79 still fits — and the tail only starts - // paying below that, in a tmux split or a half-screen terminal. It is bought - // cheaply (the hints it outlives are the two most guessable on the line) so it - // is worth having, but it is not the difference between visible and invisible - // at 80 that the first draft of this comment claimed. - // [A] agents is absent for width: the line is already 98 columns, and with one agent — + // [P] plugins and [p] pause are not here (#2019): the ? help lists both. The hint + // was "plugins" while the pane titles itself "pipeline" (#1212); the help keeps + // the precise wording. + // [A] agents is absent for width: with one agent — // the common case — the breakdown is a single row. The [?] overlay names it. esc names // the picker instead when this list was reached through it. search := m.searchHints(m.pane) if m.sessionsViaAgents { - return "[↑↓] nav [↵] drill [u] usage [$] spend " + search + " [esc] agents [p] pause [P] plugins [?] keys [q] quit" + return "[↵] drill [u] usage [$] spend " + search + " [esc] agents [?] keys [q] quit" } if m.parentCtx != nil { - return "[↑↓] nav [↵] drill [u] usage [$] spend " + search + " [esc] pods [p] pause [P] plugins [?] keys [q] quit" + return "[↵] drill [u] usage [$] spend " + search + " [esc] pods [?] keys [q] quit" } - return "[↑↓] nav [↵] drill [u] usage [$] spend " + search + " [p] pause [P] plugins [?] keys [q] quit" + return "[↵] drill [u] usage [$] spend " + search + " [?] keys [q] quit" case paneEvents: - skipHint := "[s] hide passthru/skip" - if m.hideInactive { - skipHint = "[s] show all" - } // Ordered by what must survive truncation, not by how the keys group. The // footer runs 135 columns and an 80-column terminal cuts the tail, so // anything after the cut is invisible — [?] keys and [q] quit were both // past it, which is the pair a stuck user reaches for. They now sit at the // end, and the escapable/discoverable keys ahead of them, with the // specialised ones first to be lost. - base := "[↑↓] nav [b/f] page [↵] detail [c] columns [u] usage " + - skipHint + " [p] pause " + m.searchHints(m.pane) + " [esc] back" + // [b/f] stays: unlike ↑↓, it is not a key a user guesses. + base := "[b/f] page [↵] detail [c] columns [u] usage " + + m.searchHints(m.pane) + " [esc] back" // Notices go BEFORE the essential hints, not after. // @@ -1239,12 +1207,6 @@ func (m *model) helpView() string { // outlives it — at width 40 the footer read "… · → 1 more column ([c] to // choose)" with no way to quit or reach help. A notice is worth less than // the keys that let a user act on it. - // - // Surface the hidden-message count so a filtered timeline doesn't look like - // data loss. Only when hiding is on AND at least one message was hidden. - if m.hideInactive && m.hiddenInactive > 0 { - base = fmt.Sprintf("%s · %d hidden", base, m.hiddenInactive) - } // The older-events row is the timeline's first row, off the screen at the tail. if n := m.olderNotFetched[m.selectedSess]; n > 0 { base = fmt.Sprintf("%s · %d older (▲ at top)", base, n) @@ -1277,7 +1239,7 @@ func (m *model) helpView() string { if m.detailHalf() == nil { yank = "" // y has nothing to write in a missing half } - return "[↑↓] move [↵] fold [tab] " + other + yank + " [u] usage " + + return "[↵] fold [tab] " + other + yank + " [u] usage " + m.searchHints(m.pane) + " [esc] back [?] keys [q] quit" case panePipeline: // ONE SPELLING NOW, where there used to be two. The picker/bypass split @@ -1285,7 +1247,7 @@ func (m *model) helpView() string { // to pods" with a parent context, nothing without one. esc now returns to // whichever pane opened this one in both modes, so there is nothing left for // the branch to say differently. - base := "[↑↓] nav [↵] plugin detail [e] edit [esc] back" + base := "[↵] plugin detail [e] edit [esc] back" // Surface a count of plugins with unmet dependencies so a single "✗" in the // DEPS column doesn't get lost in a long list. Before the essential hints, // for the reason given in the paneEvents case: fitHintLine drops from the @@ -1296,16 +1258,10 @@ func (m *model) helpView() string { } return base + " " + m.searchHints(m.pane) + " [?] keys [q] quit" case panePluginDetail: - return "[↑↓] scroll " + m.searchHints(m.pane) + " [esc] back [?] keys [q] quit" + return m.searchHints(m.pane) + " [esc] back [?] keys [q] quit" case paneTimeline: - // [↑↓] only when there are rows to scroll to: a key that does nothing on screen reads as - // broken. - scroll := "" - if lay, ok := m.timelineLayoutNow(); ok && m.timelineScrollMax(lay) > 0 { - scroll = "[↑↓] rows " - } _, _, _, win := m.timelineRange() - return "[w] " + timelineWindows[win].label + " [←→] moment " + scroll + "[enter] events " + m.searchHints(m.pane) + " [esc] back [?] keys [q] quit" + return "[w] " + timelineWindows[win].label + " [←→] moment [enter] events " + m.searchHints(m.pane) + " [esc] back [?] keys [q] quit" case paneUsage: // [o] is omitted under latency rather than shown as a no-op: a footer that // advertises an inert key is worse than a shorter footer. @@ -1344,12 +1300,10 @@ func (m *model) helpView() string { enterHint = " [↵] all agents" } } - // The full project label after nav: the cell may show only a tail. - navHint := "[↑↓] nav" - if d, ok := m.selectedAgentRow(); ok { - if d.kind == agentRowProject { - navHint += " " + sanitizeLabel(d.project) - } + // The full project label at the head: the cell may show only a tail. + head := "" + if d, ok := m.selectedAgentRow(); ok && d.kind == agentRowProject { + head = sanitizeLabel(d.project) } escHint := " [esc] back" if m.agentsAboveSessions { @@ -1359,7 +1313,7 @@ func (m *model) helpView() string { } } // [S] only on a row where it opens, so the footer never advertises a key that would only - // say why not. After esc, so fitHintLine — which drops from the front — gives up nav first. + // say why not. After esc, so fitHintLine — which drops from the front — gives up [↵] first. serverHint := "" if m.serverKeyOffered() { serverHint = " [S] server" @@ -1368,7 +1322,7 @@ func (m *model) helpView() string { // key gets discovered. The drawer here breaks down the row under the cursor. spendHint := " [$] spend" // [w] the pane's window, which the title names; see cycleAgentsWindow. - return navHint + enterHint + escHint + serverHint + " [w] " + m.agentsWindowLabel() + spendHint + " " + m.searchHints(m.pane) + " [?] keys [q] quit" + return strings.TrimPrefix(head+enterHint, " ") + escHint + serverHint + " [w] " + m.agentsWindowLabel() + spendHint + " " + m.searchHints(m.pane) + " [?] keys [q] quit" } return "[?] keys [q] quit" } diff --git a/cmd/agentop/tui/pending_bucket.go b/cmd/agentop/tui/pending_bucket.go index abf25ddd4..08c5246cb 100644 --- a/cmd/agentop/tui/pending_bucket.go +++ b/cmd/agentop/tui/pending_bucket.go @@ -3,6 +3,8 @@ package tui import ( "strings" + "github.com/charmbracelet/x/ansi" + "github.com/rossoctl/cortex/core/pipeline" "github.com/rossoctl/cortex/core/session" ) @@ -28,14 +30,27 @@ func pendingTitle(pid string) string { return "calls outside any session · pid " + pid } -// sessionIDCell is the SESSION cell: the id, or a pending bucket's agent. The agent and not -// agent·pid, because SESSION is 14 columns and "claude-code·89949" would lose the pid to the -// cut anyway; the pid is in the title. +// sessionIDWidth is the SESSION cell of a session id: its first 8 characters (#2019). +const sessionIDWidth = 8 + +// sessionIDCell is the SESSION cell: the first sessionIDWidth characters of the id, with no +// "…", or a pending bucket's agent in full. The agent and not agent·pid: SESSION widens to the +// agent name (sessionsIDWidth), and the pid is in the title. w cuts only where a narrow +// terminal fits the column below that. func sessionIDCell(id string, w int) string { if agent, _, ok := pendingBucket(id); ok { return trunc(sanitizeLabel(agent), w) } - return trunc(id, w) + return trunc(ansi.Truncate(id, sessionIDWidth, ""), w) +} + +// sessionIDSearch is what `/` reads for the SESSION cell: the FULL id, or a pending bucket's +// agent, so the short cell loses nothing for finding a session. +func sessionIDSearch(id string) string { + if agent, _, ok := pendingBucket(id); ok { + return sanitizeLabel(agent) + } + return id } // sessionAgent is the agent a row belongs to: the server's Agent, or — for a pending bucket, diff --git a/cmd/agentop/tui/pipeline_key_test.go b/cmd/agentop/tui/pipeline_key_test.go index ab2c96608..85c3782b8 100644 --- a/cmd/agentop/tui/pipeline_key_test.go +++ b/cmd/agentop/tui/pipeline_key_test.go @@ -6,6 +6,7 @@ import ( "testing" tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/x/ansi" "github.com/rossoctl/cortex/cmd/agentop/apiclient" ) @@ -216,32 +217,15 @@ func TestTopLevelTitles_CarryNoTabStrip(t *testing.T) { } } -// A surface reached by a key is only as good as the advertisement for that key. -// fitHintLine drops hints from the FRONT, so `[P] plugins` sits near the tail. -// -// THE ASSERTION IS AT 60 COLUMNS, NOT 80, and the difference matters: measured, -// the key survives to 34 columns at the tail and to 79 third from the left, so an -// 80-column assertion passes for BOTH placements and tests nothing. 60 is inside -// the gap — narrow enough that only the tail placement holds, and a width a tmux -// split or half-screen terminal actually reaches. 80 is asserted too, as the -// floor that must never regress. -func TestSessionsFooter_AdvertisesThePipelineKeyAtAWidthThatSurvives(t *testing.T) { - m := &model{pane: paneSessions} - - got := m.helpView() - if !strings.Contains(got, "[P] plugins") { - t.Errorf("the sessions footer omits [P] plugins:\n %s", got) - } - for _, w := range []int{80, 60} { - if fit := fitHintLine(got, w); !strings.Contains(fit, "[P]") { - t.Errorf("a %d-column fit drops the pipeline key:\n %s", w, fit) +// [P] left the sessions bar in #2019: the ? help lists it as a jump target, and it works. +func TestSessionsFooter_PipelineKeyIsInTheHelpOnly(t *testing.T) { + for _, m := range []*model{{pane: paneSessions}, {pane: paneSessions, parentCtx: context.Background()}} { + if got := m.helpView(); strings.Contains(got, "[P]") { + t.Errorf("the sessions footer still offers [P]:\n %s", got) } } - - // The drilled-in spelling is a separate string with its own [esc] pods. - m.parentCtx = context.Background() - if got := m.helpView(); !strings.Contains(got, "[P] plugins") { - t.Errorf("the drilled-in sessions footer omits [P] plugins:\n %s", got) + if !helpHasKey(ansi.Strip(helpBodyLines(paneSessions, 200)), "P ") { + t.Error("the sessions help does not list P") } } diff --git a/cmd/agentop/tui/search_details_test.go b/cmd/agentop/tui/search_details_test.go index 3ace6daf7..0d0f05ca5 100644 --- a/cmd/agentop/tui/search_details_test.go +++ b/cmd/agentop/tui/search_details_test.go @@ -728,22 +728,17 @@ func TestDetailSearch_OpeningARowShowsADeepMatch(t *testing.T) { }) } -// A row hidden when the search ran is outside its answer. Shown again, n searches again and +// A row missing when the search ran is outside its answer. Shown again, n searches again and // reaches it. func TestDetailSearch_ARowShownAgainSearchesAgain(t *testing.T) { f := &fakeSearch{answer: map[string][]uint64{"s": {3}}} m := searchModel(t, 5, f) - for i := range m.events["s"] { - if i != 2 { - m.events["s"][i].Invocations = &pipeline.Invocations{Outbound: []pipeline.Invocation{ - {Plugin: "p", Action: pipeline.ActionObserve}}} - } - } - m.hideInactive = true + all := m.events["s"] + m.events["s"] = slices.Delete(slices.Clone(all), 2, 3) m.rebuildEventsTable() detailsQuery(m, "needle") runAll(m, enter(m)) - m.hideInactive = false + m.events["s"] = all m.rebuildEventsTable() key(m, 'n') if s, _ := f.counts(); s != 2 { diff --git a/cmd/agentop/tui/sessions_context.go b/cmd/agentop/tui/sessions_context.go index 3acdbe271..1d21e985f 100644 --- a/cmd/agentop/tui/sessions_context.go +++ b/cmd/agentop/tui/sessions_context.go @@ -122,36 +122,27 @@ func (m *model) rebaseSessionContext(id string, events []pipeline.SessionEvent) // contextGauge draws prompt tokens against contextWindowTokens, in exactly width columns. // -// A BRACKETED TRACK, because the brackets are what make the scale visible on every row. The -// three designs considered were this, a dotted remainder ("███▎····") and a single eighth-block -// cell; the brackets earn their two columns twice over. A session at 0.8% draws "▕▏ ▏", -// which reads as nearly-empty-out-of-something, where a bare "▏" floating in whitespace reads as -// a rendering fault — and the em dash for an unknown context stays unmistakably different from -// both, which it cannot be when an almost-empty bar is itself almost nothing. -// -// No ░ for the remainder. usage_glyphs.go rejected shaded blocks after measuring them: "█ -// against ▓ is nearly indistinguishable at a glance in most terminal fonts", and a track a -// reader cannot separate from the fill is worse than no track. +// A SHADED TRACK, which the author chose in #2019: the fill, then ░ for the rest of the window, +// so the scale shows on every row without the bracket pair the gauge drew before. A partial cell +// is followed directly by the track, and the small gap inside that cell is accepted. There is no +// "nearly full" color: the fill length is the whole signal. // // Fill arithmetic is tierBar's, reused rather than restated, which brings its rule with it: a // non-zero value never renders as an empty bar. That rule is the whole reason a 8,200-token -// context still shows a sliver. +// context still shows a sliver, and the em dash for an unknown context stays different from it. // // Exactly width columns, so every row's gauge starts and ends in the same place and the fills can // be compared down the column by eye. That is also what makes the column's alignment moot — see // sessionsRightAligned, which lists it for the em dash's sake. func contextGauge(promptTokens, width int) string { - // Three is brackets plus one cell of track. Below that there is nothing to draw, and a - // bracket pair alone would claim a scale it cannot show. - if width < 3 { + if width < 1 { return "" } if promptTokens <= 0 { return emptyCell } - budget := width - 2 - bar := tierBar(int64(promptTokens), contextWindowTokens, budget) - return "▕" + bar + strings.Repeat(" ", budget-lipgloss.Width(bar)) + "▏" + bar := tierBar(int64(promptTokens), contextWindowTokens, width) + return bar + strings.Repeat("░", width-lipgloss.Width(bar)) } // cachedMarker names a row whose events agentop holds and the server no longer lists (#870). diff --git a/cmd/agentop/tui/sessions_context_test.go b/cmd/agentop/tui/sessions_context_test.go index 7b20defb1..8a03fa0ca 100644 --- a/cmd/agentop/tui/sessions_context_test.go +++ b/cmd/agentop/tui/sessions_context_test.go @@ -7,7 +7,10 @@ import ( "time" "github.com/charmbracelet/lipgloss" + "github.com/charmbracelet/x/ansi" + "github.com/muesli/termenv" + "github.com/rossoctl/cortex/cmd/agentop/tui/table" "github.com/rossoctl/cortex/core/pipeline" "github.com/rossoctl/cortex/core/session" ) @@ -93,39 +96,32 @@ func subagent(id string, at time.Time, msgs, context int) []pipeline.SessionEven return roled(conversation(id, at, msgs, context), pipeline.AgentRoleSubagent) } -func TestContextGauge(t *testing.T) { +// The gauge is a shaded track (#2019): the fill, then ░ for the rest of the window. A partial +// cell leaves a gap before the track, which the author accepted. +func TestContextGauge_ShadedTrack(t *testing.T) { for _, tc := range []struct { name string tokens int width int want string }{ - // The track is always drawn, so a scale is visible on every row. - {"half full", 500_000, 10, "▕████ ▏"}, - {"nearly full", 991_200, 10, "▕███████▉▏"}, - {"full", 1_000_000, 10, "▕████████▏"}, - // A NON-ZERO CONTEXT NEVER RENDERS AS AN EMPTY TRACK. tierBar's rule, inherited: 8,200 - // of a million is 0.8%, which rounds to no block at all, so it gets the sliver instead. - // An empty track beside a live session reads as a rendering fault. - {"a sliver rather than nothing", 8_200, 10, "▕▏ ▏"}, - // Unknown is the em dash COST and SAVED use, and it must not be confusable with the - // sliver above — which is the whole reason the brackets are drawn. - {"unknown", 0, 10, emptyCell}, + {"half full", 500_000, 7, "███▌░░░"}, + // A NON-ZERO CONTEXT NEVER RENDERS AS AN EMPTY TRACK: tierBar's sliver rule. + {"a sliver rather than nothing", 8_200, 7, "▏░░░░░░"}, + {"full", 1_000_000, 7, "███████"}, // Over the window: capped rather than overflowing its column. - {"past the window", 1_400_000, 10, "▕████████▏"}, - // Narrow terminals shrink the track with the column. - {"the narrowest useful gauge", 500_000, 3, "▕▌▏"}, - // Below that there is nothing to draw; a bracket pair alone would claim a scale it - // cannot show. - {"too narrow to say anything", 500_000, 2, ""}, + {"past the window", 2_000_000, 7, "███████"}, + // Unknown is the em dash COST and SAVED use, never an empty track. + {"unknown", 0, 7, emptyCell}, + {"one cell", 500_000, 1, "▌"}, + {"no width", 5, 0, ""}, } { t.Run(tc.name, func(t *testing.T) { got := contextGauge(tc.tokens, tc.width) if got != tc.want { t.Errorf("contextGauge(%d, %d) = %q, want %q", tc.tokens, tc.width, got, tc.want) } - // Exactly the column's width, so every row's gauge starts and ends in the same - // place and the fills can be compared down the column by eye. + // Exactly the column's width, so the fills can be compared down the column by eye. if tc.want != "" && tc.want != emptyCell { if w := lipgloss.Width(got); w != tc.width { t.Errorf("gauge is %d columns, want %d: %q", w, tc.width, got) @@ -135,6 +131,48 @@ func TestContextGauge(t *testing.T) { } } +// Under color the CTX cell draws its fill in the accent ink and its ░ track dim, and the plain +// text is the plain gauge. +func TestSessionsGauge_TrueColorInk(t *testing.T) { + withProfile(t, termenv.TrueColor) + gauge := contextGauge(500_000, 7) + cols := []table.Column{{Title: "SESSION", Width: 8}, {Title: contextColumnTitle, Width: 7}} + rows := []table.Row{{"aaaaaaaa", gauge}, {"bbbbbbbb", gauge}, {"cccccccc", gauge}} + tbl := table.New(table.WithColumns(cols), table.WithRows(rows), table.WithHeight(4), + table.WithCellStyle(sessionsCellStyle(cols, nil))) + tbl.SetStyles(tableStyles()) + tbl.SetCursor(0) + + lines, first := tableLines(t, tbl, "aaaaaaaa") + line := lines[first+2] // not the cursor row + if got := ansi.Strip(line); !strings.Contains(got, "cccccccc") || !strings.Contains(got, gauge) { + t.Fatalf("plain row is %q, want it to hold %q", got, gauge) + } + if p := sgrAt(line, "█"); !strings.Contains(p, fgOf(styleAccent)) { + t.Errorf("the fill has SGR %q, want the accent ink %q", p, fgOf(styleAccent)) + } + if p := sgrAt(line, "▌"); !strings.Contains(p, fgOf(styleAccent)) { + t.Errorf("the partial cell has SGR %q, want the accent ink %q", p, fgOf(styleAccent)) + } + // Every ░, not only the first, sits under the dim ink. + n := 0 + for at := 0; ; { + i := strings.Index(line[at:], "░") + if i < 0 { + break + } + at += i + if p := sgrAt(line[:at]+"\x00", "\x00"); !strings.Contains(p, fgOf(styleDim)) { + t.Errorf("track cell %d has SGR %q, want the dim ink %q", n, p, fgOf(styleDim)) + } + n++ + at += len("░") + } + if n != 3 { + t.Fatalf("the row draws %d ░, want 3", n) + } +} + // THE COLUMN REPLACED ACTIVE, and the row arity follows the header — which is the invariant // rebuildSessionsTable's own comment calls a crash rather than a cosmetic bug. func TestSessionsTable_ContextColumnReplacesActive(t *testing.T) { @@ -169,7 +207,7 @@ func TestSessionsTable_ContextColumnReplacesActive(t *testing.T) { } // 500k of 1M: a gauge half full, drawn to the fitted width. cell := row[len(row)-1] - if !strings.Contains(cell, "▕") || !strings.Contains(cell, "█") { + if !strings.Contains(cell, "░") || !strings.Contains(cell, "█") { t.Errorf("last cell is not a gauge: %q", cell) } if got, want := lipgloss.Width(cell), cols[len(cols)-1].Width; got != want { diff --git a/cmd/agentop/tui/sessions_context_wire_test.go b/cmd/agentop/tui/sessions_context_wire_test.go index 5eee7c249..3f5488652 100644 --- a/cmd/agentop/tui/sessions_context_wire_test.go +++ b/cmd/agentop/tui/sessions_context_wire_test.go @@ -451,7 +451,7 @@ func heldContextCell(t *testing.T, m *model, id string) string { return "" } -// assertGaugeFilled fails unless the cell is a bracketed track with something drawn IN it. +// assertGaugeFilled fails unless the cell is a gauge with a fill drawn in it. // // `!= emptyCell` is too weak, which a review caught: an EMPTY track is not the em dash, so it // would pass, and this package calls it a fault in its own right — "an empty track beside a live @@ -459,22 +459,17 @@ func heldContextCell(t *testing.T, m *model, id string) string { // a non-zero figure never drawing as an empty bar. // // NOT the sibling assertion's strings.Contains(cell, "█") though, which holds only for a large -// figure. Measured at this column's width: 500,000 of 1M draws "▕████▌ ▏", but 62,000 draws -// "▕▌ ▏" and 8,200 draws "▕▏ ▏" — no full block in either. Requiring one would fail -// the small figures the tests below deliberately use. Ink between the brackets is the property -// that holds for every non-zero figure. -// -// Sliced by byte offset rather than strings.Trim, and that is not pedantry: the one-eighth fill ▏ -// is THE SAME RUNE as the closing bracket, so Trim(cell, "▕▏") eats an 8,200-token sliver whole -// and then reports the empty track it was written to catch. +// figure. 62,000 of 1M draws a half-block sliver and 8,200 draws "▏" — no full block in either. +// Requiring one would fail the small figures the tests below deliberately use. A cell made only of +// the ░ track and fill runes, with at least one fill rune, is the property that holds for every +// non-zero figure. func assertGaugeFilled(t *testing.T, cell, when string) { t.Helper() - const openBracket, closeBracket = "▕", "▏" - if !strings.HasPrefix(cell, openBracket) || !strings.HasSuffix(cell, closeBracket) { + if cell == "" || strings.Trim(cell, "░█▉▊▋▌▍▎▏") != "" { t.Errorf("%s the row holds %q, which is not a gauge at all", when, cell) return } - if strings.TrimSpace(cell[len(openBracket):len(cell)-len(closeBracket)]) == "" { + if strings.Trim(cell, "░") == "" { t.Errorf("%s the row holds an EMPTY track %q — the figure reached contextRun and not "+ "the cell", when, cell) } @@ -484,10 +479,10 @@ func assertGaugeFilled(t *testing.T, cell, when string) { // table built the row against — a different question from assertGaugeFilled's, and the one the // tests below actually mean. // -// INK BETWEEN THE BRACKETS WAS NOT ENOUGH, measured rather than argued — and the measurement is the +// A FILL IN THE TRACK WAS NOT ENOUGH, measured rather than argued — and the measurement is the // DOUBLED figure. Drawing contextGauge(m.sessionContextFor(...)*2, contextW) in rebuildSessionsTable // left the whole tui suite green before this helper existed, and fails all five row tests below with -// it: a gauge at twice the figure still has ink between its brackets, so "the row repainted" was +// it: a gauge at twice the figure still has a fill in its track, so "the row repainted" was // pinned as "something was drawn". The figure and the cell have to be pinned TOGETHER. // // AND NOT THE CONSTANT GAUGE, which is the mutation the review that found this named first and which diff --git a/cmd/agentop/tui/sessions_pane.go b/cmd/agentop/tui/sessions_pane.go index f249697a7..6e578eca4 100644 --- a/cmd/agentop/tui/sessions_pane.go +++ b/cmd/agentop/tui/sessions_pane.go @@ -22,7 +22,7 @@ import ( // resize: fitting the LIVE columns would be cumulative, and a terminal that got narrower once // would keep its narrowed columns after being widened again. // -// These widths sum to 84 declared columns, or 100 rendered once bubbles adds its two of padding +// These widths sum to 78 declared columns, or 94 rendered once bubbles adds its two of padding // per cell, which is why they are fitted rather than used as-is — see fitTableColumns. // // THIS PARAGRAPH HAS CARRIED WRONG NUMBERS THREE TIMES: 104/116 before a rebase, 98/114 after one @@ -33,21 +33,20 @@ import ( // TITLE is the widest optional column, and it is dropped rather than shrunk when the terminal // cannot seat it — see sessionsShowTitle, which decides after the money columns so that // widening the window never takes a column away. Where TITLE does render, fitTableColumns -// shrinks the widest column rather than dropping any, so it and SESSION pay for each other: -// measured, SESSION is 12 at 97 columns and 14 from 100 up. A 12-character id prefix still -// distinguishes sessions in practice, and an unnamed session is what this column exists to fix. +// shrinks the widest column rather than dropping any. SESSION is 8 wide (an 8-character id +// prefix, #2019), so it is never the widest and TITLE pays for a narrow terminal on its own. // -// A terminal WIDER than 100 rendered is handled by sessionsColumnsFor rather than here: +// A terminal WIDER than 94 rendered is handled by sessionsColumnsFor rather than here: // fitTableColumns only ever shrinks, so these declared widths are simultaneously the // narrow-terminal budget and the wide-terminal ceiling, and titles are mostly directory paths // with nothing to gain from a ceiling of 24 when there are spare columns on the screen. func sessionsColumns() []table.Column { return []table.Column{ - // SESSION, and 14 wide rather than 40. A session id is a 36-character UUID whose - // first characters identify it to a human as well as all of them do, and the 26 - // columns it was spending are the ones the money columns need. `/` filters on the - // FULL id, so nothing is lost for finding a session — only for reading one. - {Title: "SESSION", Width: 14}, + // SESSION, and 8 wide rather than 36: the first 8 characters of a UUID identify a + // session to a human as well as all of them do (#2019). `/` filters on the FULL id, + // so nothing is lost for finding a session — only for reading one. The rebuild widens + // it for a pending bucket's agent name; see sessionsIDWidth. + {Title: "SESSION", Width: sessionIDWidth}, // After SESSION, never before it. Nothing reads the id off a row any more — // selectedSessionID and the cursor restore read sessionRowIDs, kept beside the rows — // but SESSION first is where a reader looks for it, and withColumnIfItFits seats every @@ -170,13 +169,20 @@ var sessionsCellKinds = map[string]cellKind{ } // sessionsCellStyle styles the cells under cols by their declared title (headerTitle), so the -// style follows a column wherever the width puts it. -func sessionsCellStyle(cols []table.Column) table.CellStyleFunc { +// style follows a column wherever the width puts it. The row whose id in ids is the default +// bucket is background traffic, so all of it is muted (an em dash stays dim). +func sessionsCellStyle(cols []table.Column, ids []string) table.CellStyleFunc { kinds := make([]cellKind, len(cols)) for i, c := range cols { kinds[i] = sessionsCellKinds[headerTitle(c)] } - return kindsCellStyle(kinds) + byKind := kindsCellStyle(kinds) + return dashDim(func(r int, row table.Row, col int) lipgloss.Style { + if r < len(ids) && ids[r] == session.DefaultSessionID { + return styleMuted + } + return byKind(r, row, col) + }) } // sessionsTitleWidth is TITLE's floor: the narrowest cell worth granting the column, and its @@ -186,7 +192,7 @@ func sessionsCellStyle(cols []table.Column) table.CellStyleFunc { // does not displace render 67 wide, and 67 + 11 + 2 is 80" — 67 was right then (63 since the // context heading became CTX(1M)), but the gate does not add up declared widths any more: it asks // the fitter what TITLE is left with, and the fitter narrows the two wider columns before it -// touches TITLE. So the real threshold is lower than that sum — 69, measured. +// touches TITLE. So the real threshold is lower than that sum — 67, measured. // // 11 is the narrowest cell where a left-truncated path still says which session it is: // "…claudesessions" fits, where 8 columns give a leaf fragment identifying nothing. Picked for @@ -197,7 +203,8 @@ func sessionsCellStyle(cols []table.Column) table.CellStyleFunc { // that base by three and pushed TITLE's threshold to 83 — caught by // TestSessionsShowTitle_RendersAtTheCommonWidth, which exists because an earlier revision let a // 20-column error through with nothing asserting the threshold. Shortening that heading to -// CTX(1M) took four columns back out, moving the threshold from 73 to 69. Any future column +// CTX(1M) took four columns back out, moving the threshold from 73 to 69, and SESSION going +// from 14 to 8 (#2019) moved it to 67. Any future column // added to this table moves this number again, and that test is what says so. // // Narrow for a path, deliberately: truncLeft keeps the TAIL, so 14 columns of @@ -216,7 +223,7 @@ func newSessionsTable() table.Model { t := table.New( table.WithColumns(alignSessionsHeaders(sessionsColumns())), table.WithFocused(true), - table.WithCellStyle(sessionsCellStyle(sessionsColumns())), + table.WithCellStyle(sessionsCellStyle(sessionsColumns(), nil)), ) t.SetStyles(tableStyles()) return t @@ -268,8 +275,8 @@ func (m *model) rebuildSessionsTable() { // AGENT and SERVER are asked for by what is listed, then dropped whole when the terminal has // no room. Kept, so the search can still read a dropped one. twoAgents := m.sessionsListTwoAgents(scope, project) - want := alignSessionsHeaders(fitTableColumns( - sessionsColumnsWith(m.width, twoAgents, showServer), m.width)) + want := alignSessionsHeaders(fitTableColumns(withSessionsIDWidth( + sessionsColumnsWith(m.width, twoAgents, showServer), m.sessionsIDWidth(scope, project, showTitle)), m.width)) agentW := sessionsColumnWidth(want, "AGENT") serverW := sessionsColumnWidth(want, "SERVER") costW := sessionsColumnWidth(want, "COST") @@ -316,17 +323,12 @@ func (m *model) rebuildSessionsTable() { // started with "↳ ". Plain text, not dim: the table cuts a cell by its bytes, and a // style's escape bytes would mangle it (see cachedMarker). With no TITLE column, the // SESSION cell has the mark. - mark := "" - if strings.HasPrefix(s.Source, coremodel.ImportedSourcePrefix) { - mark = importedMarker - } else if s.ParentSession != "" { - mark = childMarker - } + mark := sessionMark(s) markW := lipgloss.Width(mark) // columns, not bytes: "↳" is 3 bytes and 1 column if showTitle || mark == "" { - b.cut(sessionIDCell(s.ID, idW), func() string { return sessionIDCell(s.ID, noLimit) }) + b.cut(sessionIDCell(s.ID, idW), func() string { return sessionIDSearch(s.ID) }) } else { - b.cut(mark+sessionIDCell(s.ID, idW-markW), func() string { return sessionIDCell(s.ID, noLimit) }) + b.cut(mark+sessionIDCell(s.ID, idW-markW), func() string { return sessionIDSearch(s.ID) }) } // s.Title straight off the summary, where sessionLabel reaches the same value by id // through m.servedTitle. Two routes, equal only because they read the same slice — @@ -400,7 +402,7 @@ func (m *model) rebuildSessionsTable() { } cached := m.events[id] b := newRowBuilder(q != "") - b.cut(sessionIDCell(id, idW), func() string { return sessionIDCell(id, noLimit) }) + b.cut(sessionIDCell(id, idW), func() string { return sessionIDSearch(id) }) // These rows exist precisely because the server no longer lists the session, so there // is no summary to carry a served title. Harvested metadata outlives the listing, so // the cell can still fill from that. Named constant rather than a bare "" so the @@ -464,7 +466,7 @@ func (m *model) rebuildSessionsTable() { m.sessionsTbl.SetRows(nil) m.sessionsTbl.SetColumns(want) } - m.sessionsTbl.SetCellStyle(sessionsCellStyle(want)) + m.sessionsTbl.SetCellStyle(sessionsCellStyle(want, ids)) m.sessionsTbl.SetRows(rows) m.sessionsTbl.SetSearch(q, full) // Published with the rows they describe, never separately. @@ -508,6 +510,54 @@ func (m *model) cachedOnlySessionIDs() []string { return out } +// sessionMark is the plain-text mark before a session's title: imported, or started by another +// session. With no TITLE column, the SESSION cell has it. +func sessionMark(s session.SessionSummary) string { + if strings.HasPrefix(s.Source, coremodel.ImportedSourcePrefix) { + return importedMarker + } + if s.ParentSession != "" { + return childMarker + } + return "" +} + +// sessionsIDWidth is SESSION's width for the listed rows: the widest SESSION cell, an id counted +// at sessionIDWidth, so a pending bucket's agent name is never cut (claude-code gives 11). It +// reads the same filters as rebuildSessionsTable's two row loops. +func (m *model) sessionsIDWidth(scope, project string, showTitle bool) int { + w := sessionIDWidth + for _, s := range m.sessions { + if !m.sessionListed(s, scope, project) || foldedInto(s) != "" { + continue + } + cell := sessionIDCell(s.ID, noLimit) + if !showTitle { + cell = sessionMark(s) + cell + } + w = max(w, lipgloss.Width(cell)) + } + if (scope == "" || scope == otherAgents) && (project == "" || project == otherProjects) { + for _, id := range m.cachedOnlySessionIDs() { + w = max(w, lipgloss.Width(sessionIDCell(id, noLimit))) + } + } + return w +} + +// withSessionsIDWidth is cols with SESSION set to w. Applied before fitTableColumns, so on a +// terminal with no room left the fitter takes the extra from the widest column (TITLE). +func withSessionsIDWidth(cols []table.Column, w int) []table.Column { + out := make([]table.Column, len(cols)) + copy(out, cols) + for i := range out { + if headerTitle(out[i]) == "SESSION" { + out[i].Width = w + } + } + return out +} + // sessionListed reports whether the sessions table shows s: every session, and under an agent // scope only the sessions of that agent — under Other, every session that names no recognised // agent. Under a project scope only the sessions in that project — under otherProjects, every @@ -853,7 +903,7 @@ const sessionMoneyCellMin = 9 // lines above sessionMoneyCell forbids it in both directions. // // The cost is real and measured: on this floor alone the columns disappear below 71 columns -// (TITLE, which they yield to, keeps them out until 93 — see sessionsShowTitle), where an ordinary +// (TITLE, which they yield to, keeps them out until 91 — see sessionsShowTitle), where an ordinary // "$36.58" would still have fitted. Dropping a whole column is this file's stated answer to // not being able to render a cell honestly, and a reader who cannot see COST at all goes // looking for the width; one who sees "—" against a session that definitely spent money @@ -1023,8 +1073,8 @@ func sessionsShowTitle(termWidth int) bool { // paragraph is live. // // What the function does: TITLE is granted when the FITTED set leaves it its floor, measured - // without the money columns because those are what yield to it. TITLE renders from 69; COST - // and SAVED are absent from 69 to 92 and return at 93, where the whole set holds every + // without the money columns because those are what yield to it. TITLE renders from 67; COST + // and SAVED are absent from 67 to 90 and return at 91, where the whole set holds every // minimum at once. // // Why in that order: TITLE is the column this pane gained and the only one whose absence @@ -1040,8 +1090,8 @@ func sessionsShowTitle(termWidth int) bool { // // Measured WITHOUT the money columns, because they are what yields: this gate is decided // first and sessionsShowMoney reads it, so COST and SAVED take only what is left once a - // legible title has its room. They are absent from 69 to 92 for that reason and return at - // 93, where the full set holds every minimum at once. + // legible title has its room. They are absent from 67 to 90 for that reason and return at + // 91, where the full set holds every minimum at once. keep := make([]table.Column, 0, len(sessionsColumns())) for _, c := range sessionsColumns() { switch headerTitle(c) { @@ -1082,7 +1132,7 @@ func growSessionsTitle(cols []table.Column, termWidth, pending int) []table.Colu // // So growth stops at what survives their return. Below the width where they fit, the room // they will take is reserved rather than lent: TITLE grows steadily instead of ballooning - // and collapsing. Column PRESENCE is monotonic — TITLE from 69, the money columns from 93, + // and collapsing. Column PRESENCE is monotonic — TITLE from 67, the money columns from 91, // AGENT and SERVER only where those render (withColumnIfItFits) — and this, with pending, is // what makes TITLE's width so. if !sessionsShowMoney(termWidth) { diff --git a/cmd/agentop/tui/sessions_short_id_test.go b/cmd/agentop/tui/sessions_short_id_test.go new file mode 100644 index 000000000..07f110eb0 --- /dev/null +++ b/cmd/agentop/tui/sessions_short_id_test.go @@ -0,0 +1,104 @@ +package tui + +import ( + "strings" + "testing" + + "github.com/charmbracelet/x/ansi" + "github.com/muesli/termenv" + + "github.com/rossoctl/cortex/core/session" +) + +// SESSION shows the first 8 characters of an id (#2019, change 8), with no "…". default is +// shorter and stays whole. +func TestSessionIDCell_EightChars(t *testing.T) { + for _, w := range []int{8, 14, noLimit} { + if got := sessionIDCell("f0a50e1f-1234-4abc-8def-0123456789ab", w); got != "f0a50e1f" { + t.Errorf("width %d: sessionIDCell = %q, want %q", w, got, "f0a50e1f") + } + } + if got := sessionIDCell(session.DefaultSessionID, 8); got != "default" { + t.Errorf("sessionIDCell(default) = %q, want %q", got, "default") + } +} + +// A pending bucket's agent name is not cut: SESSION widens to the widest cell, ids counted at 8. +func TestSessionsTable_PendingBucketFullAgentName(t *testing.T) { + m := uuidPicker(t, 160, uuidOpened, "pending:claude-code") + if got := m.sessionsTbl.Rows()[rowOf(t, m, "pending:claude-code")][0]; got != "claude-code" { + t.Errorf("bucket SESSION cell = %q, want %q", got, "claude-code") + } + if got := sessionsColumnWidth(m.sessionsTbl.Columns(), "SESSION"); got != 11 { + t.Errorf("SESSION width = %d, want 11", got) + } + // With only ids listed, the column is 8. + m = uuidPicker(t, 160, uuidOpened, uuidOther) + if got := sessionsColumnWidth(m.sessionsTbl.Columns(), "SESSION"); got != 8 { + t.Errorf("ids-only SESSION width = %d, want 8", got) + } +} + +// The columns SESSION gave back go to TITLE: 24 -> 30 at 140 columns with AGENT (and SERVER) +// showing, the layout the issue measured. +func TestSessionsTable_TitleGetsFreedColumns(t *testing.T) { + m := sessionsServerModel(routerRaw) + m.width = 140 + m.rebuildSessionsTable() + cols := m.sessionsTbl.Columns() + if sessionsColumnWidth(cols, "AGENT") == 0 || sessionsColumnWidth(cols, "SERVER") == 0 { + t.Fatalf("want AGENT and SERVER at 140 columns: %v", titles(cols)) + } + if got := sessionsColumnWidth(cols, "TITLE"); got != 30 { + t.Errorf("TITLE width = %d, want 30", got) + } + if got := tableWidth(cols); got > 140 { + t.Errorf("table is %d wide, over the 140-column terminal", got) + } +} + +// The default bucket is background: every cell of its row draws muted (an em dash stays dim). +func TestSessionsTable_DefaultRowMuted(t *testing.T) { + withProfile(t, termenv.TrueColor) + m := uuidPicker(t, 140, uuidOpened, session.DefaultSessionID) + r := rowOf(t, m, session.DefaultSessionID) + if r == m.sessionsTbl.Cursor() { + t.Fatalf("default row is the cursor row") + } + rows := m.sessionsTbl.Rows() + lines, first := tableLines(t, m.sessionsTbl, strings.TrimSpace(rows[0][0])) + line := lines[first+r] + if !strings.Contains(ansi.Strip(line), "default") { + t.Fatalf("line %d is not the default row: %q", first+r, ansi.Strip(line)) + } + for i, cell := range rows[r] { + c := strings.TrimSpace(cell) + if c == "" { + continue + } + want := fgOf(styleMuted) + if c == "—" { + want = fgOf(styleDim) + } + if p := sgrAt(line, c); !strings.Contains(p, want) || boldIn(p) { + t.Errorf("cell %d %q has SGR %q, want %q and not bold", i, c, p, want) + } + } +} + +// The cell is short, but search and the row's id (what drill and the header use) are the full id. +func TestSessionsTable_SearchAndYankUseTheFullID(t *testing.T) { + m := uuidPicker(t, 140, uuidOpened, uuidOther) + if got := m.sessionsTbl.Rows()[rowOf(t, m, uuidOpened)][0]; got != uuidOpened[:8] { + t.Fatalf("SESSION cell = %q, want %q", got, uuidOpened[:8]) + } + m.search = map[paneID]string{paneSessions: uuidOpened[24:]} + m.rebuildSessionsTable() + if got := m.sessionsTbl.Matches(); len(got) != 1 || got[0] != rowOf(t, m, uuidOpened) { + t.Errorf("search for the id's tail matched rows %v, want only row %d", got, rowOf(t, m, uuidOpened)) + } + m.sessionsTbl.SetCursor(rowOf(t, m, uuidOpened)) + if got := m.selectedSessionID(); got != uuidOpened { + t.Errorf("selectedSessionID = %q, want the full id %q", got, uuidOpened) + } +} diff --git a/cmd/agentop/tui/sessions_title_test.go b/cmd/agentop/tui/sessions_title_test.go index 2b4eae88a..874be7924 100644 --- a/cmd/agentop/tui/sessions_title_test.go +++ b/cmd/agentop/tui/sessions_title_test.go @@ -169,8 +169,8 @@ func newServedTitleModel(t *testing.T, meta map[string]SessionMetadata, served m // sessionsColumns' comment and selectedSessionID both depend on that. func titleRow(t *testing.T, m *model, id string) table.Row { t.Helper() - for _, r := range m.sessionsTbl.Rows() { - if r[0] == id { + for i, r := range m.sessionsTbl.Rows() { + if m.sessionRowIDs[i] == id { return r } } @@ -272,10 +272,10 @@ func TestSessionsColumnsFor_TitleGrowsIntoSlackOnly(t *testing.T) { if got, want := width(at200, "TITLE"), sessionsTitleWidth+(200-declared); got != want { t.Errorf("TITLE at 200 = %d, want %d (declared %d + all the slack)", got, want, declared) } - // SESSION, not ID, and 14 rather than 40: main narrowed the id column to seat COST and - // SAVED. The property is unchanged — growth comes from slack, never from a neighbour. - if got := width(at200, "SESSION"); got != 14 { - t.Errorf("SESSION at 200 = %d, want its declared 14 — growth must come from slack, not a neighbour", got) + // SESSION, not ID, and 8 rather than 40: an 8-character id prefix (#2019). The property is + // unchanged — growth comes from slack, never from a neighbour. + if got := width(at200, "SESSION"); got != sessionIDWidth { + t.Errorf("SESSION at 200 = %d, want its declared %d — growth must come from slack, not a neighbour", got, sessionIDWidth) } if got := tableWidth(at200); got != 200 { t.Errorf("rendered width at 200 = %d, want exactly 200", got) diff --git a/cmd/agentop/tui/spend_band.go b/cmd/agentop/tui/spend_band.go index 94091293e..7c90e05c6 100644 --- a/cmd/agentop/tui/spend_band.go +++ b/cmd/agentop/tui/spend_band.go @@ -358,9 +358,10 @@ func joinBandCells(cells []bandCell, ink *bandInk) string { return line.String() } -// styleBandValue dresses one band figure without changing its text: each amount bold, an amount -// in a unit that is not dollars warn, the "~" and "+" markers, the " + " between units and an em -// dash dim. "(mixed)" keeps the default ink: it is not an amount. +// styleBandValue dresses one band figure without changing its text: each amount bold in every +// unit, the word of a unit that is not dollars muted, the "~" and "+" markers, the " + " between +// units and an em dash dim. "(mixed)" keeps the default ink: it is not an amount. No unit is warn +// (#2019): a unit is not a problem. func styleBandValue(v string) string { switch v { case emptyCell: @@ -376,12 +377,10 @@ func styleBandValue(v string) string { } // styleBandAmount is one unit's amount with its markers: a leading "~" and a trailing "+" dim, -// the rest (with any "!") bold for dollars and warn for another unit. +// the amount (with any "!") bold, and for a unit that is not dollars, the trailing " " word +// (" Bobcoins") muted. func styleBandAmount(p string) string { ink := styleBold - if !strings.Contains(p, "$") { - ink = styleWarn - } var b strings.Builder for len(p) > 0 && (p[0] == '~' || p[0] == '!') { if p[0] == '~' { @@ -395,7 +394,11 @@ func styleBandAmount(p string) string { if body, ok := strings.CutSuffix(p, partialMarker); ok { p, tail = body, styleDim.Render(partialMarker) } - return b.String() + ink.Render(p) + tail + unit := "" + if i := strings.LastIndexByte(p, ' '); i >= 0 && !strings.Contains(p, "$") { + p, unit = p[:i], styleMuted.Render(p[i:]) + } + return b.String() + ink.Render(p) + unit + tail } // bandWidth is what these cells render at on one line, skipping the dropped ones. diff --git a/cmd/agentop/tui/spend_band_test.go b/cmd/agentop/tui/spend_band_test.go index 2ed132e69..bd61c7a61 100644 --- a/cmd/agentop/tui/spend_band_test.go +++ b/cmd/agentop/tui/spend_band_test.go @@ -1177,7 +1177,7 @@ func TestSpendBandNeedsScopeMarker_EveryPaneIsClassified(t *testing.T) { } } -// THE STYLED BAND IS THE PLAIN BAND IN COLOR (#2015): amounts bold, a foreign unit warn, +// THE STYLED BAND IS THE PLAIN BAND IN COLOR (#2015): amounts bold, a foreign unit word muted, // markers, em dashes and separators dim, labels muted, and not one column moved. func TestSpendBand_StyledTextAndWidth(t *testing.T) { withProfile(t, termenv.TrueColor) @@ -1204,7 +1204,8 @@ func TestSpendBand_StyledTextAndWidth(t *testing.T) { styled, _ := renderSpendBandStyled(s, 140, true) for _, want := range []struct{ name, part, plain string }{ {"amount bold", styleBold.Render("$703.18"), "$703.18"}, - {"Bobcoins amount warn", styleWarn.Render("7.80 Bobcoins"), "7.80 Bobcoins"}, + {"Bobcoins amount bold", styleBold.Render("7.80"), "7.80 Bobcoins"}, + {"Bobcoins unit muted", styleMuted.Render(" Bobcoins"), "7.80 Bobcoins"}, {"inexact marker dim", styleDim.Render("~"), "~$4.04"}, {"partial marker dim", styleDim.Render("+"), "$4.04+"}, {"em dash dim", styleDim.Render("—"), "—"}, @@ -1220,3 +1221,77 @@ func TestSpendBand_StyledTextAndWidth(t *testing.T) { } } } + +// warnFg is the escape sequence that sets the colorWarn foreground under the current profile. +func warnFg() string { + r := lipgloss.NewStyle().Foreground(colorWarn).Render("x") + return r[:strings.Index(r, "x")] +} + +// A FOREIGN UNIT IS NOT A WARNING (#2019): its amount is bold like dollars, and the unit word +// steps back. +func TestStyleBandValue_BobcoinsBoldNotWarn(t *testing.T) { + withProfile(t, termenv.TrueColor) + got := styleBandValue("12.40 Bobcoins") + for _, part := range []string{styleBold.Render("12.40"), styleMuted.Render(" Bobcoins")} { + if !strings.Contains(got, part) { + t.Errorf("styleBandValue = %q, want it to contain %q", got, part) + } + } + if strings.Contains(got, warnFg()) { + t.Errorf("styleBandValue = %q carries the warn ink", got) + } + if s := ansi.Strip(got); s != "12.40 Bobcoins" { + t.Errorf("plain text = %q, want 12.40 Bobcoins", s) + } + + got = styleBandValue("~12.40 Bobcoins+") + for _, part := range []string{styleDim.Render("~"), styleBold.Render("12.40"), styleMuted.Render(" Bobcoins"), styleDim.Render("+")} { + if !strings.Contains(got, part) { + t.Errorf("styleBandValue(marked) = %q, want it to contain %q", got, part) + } + } + if s := ansi.Strip(got); s != "~12.40 Bobcoins+" { + t.Errorf("plain text = %q, want ~12.40 Bobcoins+", s) + } +} + +// No money figure anywhere is drawn in the warn ink: the band, the drawer and the Usage cost view. +func TestNoCurrencyUsesWarn(t *testing.T) { + withProfile(t, termenv.TrueColor) + warn := warnFg() + + s := withSpan(bandSummary(), spanToday, func(r *spanReading) { + r.USD, r.Units = 7.8, []string{"Bobcoins"} + }) + band, _ := renderSpendBandStyled(s, 140, true) + + snap := &usage.Snapshot{ + Group: usage.GroupEndpoint, + Currencies: []string{"Bobcoins"}, + SeriesCurrencies: map[string][]string{"api.us-east.bob.ibm.com": {"Bobcoins"}}, + Buckets: []usage.Bucket{{ + Counts: usage.Counts{Requests: 3, PricedRequests: 3, CostMicros: 7_800_000}, + Series: map[string]usage.Counts{"api.us-east.bob.ibm.com": {Requests: 3, PricedRequests: 3, CostMicros: 7_800_000}}, + }}, + } + drawer := styleDrawerLines(renderSpendDrawer(snap, nil, usage.GroupEndpoint, "1h", 140)) + + m := fitModel(t, paneUsage, 120, 40, nil) + m.usage.snap = costChartSnapshot([]string{"Bobcoins"}) + m.usage.metric = metricCost + usageView := m.renderUsage(m.width, m.bodyHeight) + + for name, out := range map[string]string{ + "band": strings.Join(band, "\n"), + "drawer": strings.Join(drawer, "\n"), + "usage": usageView, + } { + if !strings.Contains(ansi.Strip(out), "Bobcoins") { + t.Fatalf("%s holds no Bobcoins figure, so the case asserts nothing:\n%s", name, ansi.Strip(out)) + } + if strings.Contains(out, warn) { + t.Errorf("%s draws something in the warn ink:\n%q", name, out) + } + } +} diff --git a/cmd/agentop/tui/styles.go b/cmd/agentop/tui/styles.go index a2e52baca..f84ae23aa 100644 --- a/cmd/agentop/tui/styles.go +++ b/cmd/agentop/tui/styles.go @@ -43,7 +43,10 @@ var ( colorZebraBg = lipgloss.AdaptiveColor{Light: "#F3F4F6", Dark: "#15151C"} // every second table row colorChipBg = lipgloss.AdaptiveColor{Light: "#E5E7EB", Dark: "#374151"} // key chip ground colorChipFg = lipgloss.AdaptiveColor{Light: "#111827", Dark: "#F3F4F6"} // key chip text - colorTool = lipgloss.AdaptiveColor{Light: "#B45309", Dark: "#F59E0B"} // agent tool rows + + colorBarBg = lipgloss.AdaptiveColor{Light: "#F3F4F6", Dark: "#1F2937"} // the key bar, the last line + colorBarChipBg = lipgloss.AdaptiveColor{Light: "#D1D5DB", Dark: "#4B5563"} // a key chip on the bar + colorBarChipFg = lipgloss.AdaptiveColor{Light: "#111827", Dark: "#F9FAFB"} // its text ) var ( @@ -59,8 +62,10 @@ var ( styleDim = lipgloss.NewStyle().Foreground(colorDim) styleBold = lipgloss.NewStyle().Bold(true) styleChip = lipgloss.NewStyle().Foreground(colorChipFg).Background(colorChipBg) + styleBar = lipgloss.NewStyle().Background(colorBarBg) + styleBarLabel = lipgloss.NewStyle().Foreground(colorMuted).Background(colorBarBg) + styleBarChip = lipgloss.NewStyle().Foreground(colorBarChipFg).Background(colorBarChipBg) styleSeg = lipgloss.NewStyle().Foreground(colorOnSeries).Background(colorAccent).Bold(true) - styleTool = lipgloss.NewStyle().Foreground(colorTool) styleAccent = lipgloss.NewStyle().Foreground(colorAccent) styleAccentBold = lipgloss.NewStyle().Foreground(colorAccent).Bold(true) styleMutedBold = lipgloss.NewStyle().Foreground(colorMuted).Bold(true) @@ -142,12 +147,11 @@ func tableStyles() table.Styles { } // tableGlyphs are the runes drawn in their own ink inside a styled cell: the CTX gauge's -// brackets and the BYTES arrows dim, the agents pane's open marks accent. -// -// shortcut: the gauge's one-eighth block is the same rune as its closing bracket (▏), so a fill -// under one eighth of a cell draws dim; give the gauge its own bracket rune if that matters. +// ░ track and the BYTES arrows dim, a tool row's ┗⚒/┣⚒ mark and the subagent │ dim, the agents +// pane's open marks accent. var tableGlyphs = map[rune]lipgloss.Style{ - '▕': styleDim, '▏': styleDim, '↑': styleDim, '↓': styleDim, + '░': styleDim, '↑': styleDim, '↓': styleDim, + '┗': styleDim, '┣': styleDim, '⚒': styleDim, '│': styleDim, '▸': styleAccent, '▾': styleAccent, } @@ -220,12 +224,16 @@ func renderHints(fitted string) string { if !colorOn() { return styleHint.Render(fitted) } + return chipHints(fitted, styleHint, styleChip) +} + +func chipHints(fitted string, label, chip lipgloss.Style) string { var b strings.Builder for _, p := range splitHintChips(fitted) { if p.chip { - b.WriteString(styleChip.Render(" " + p.text + " ")) + b.WriteString(chip.Render(" " + p.text + " ")) } else { - b.WriteString(styleHint.Render(p.text)) + b.WriteString(label.Render(p.text)) } } return b.String() @@ -237,17 +245,45 @@ func renderTrailingHints(fitted, keys string) string { if !colorOn() { return styleHint.Render(fitted) } + return trailingChipHints(fitted, keys, styleHint, styleChip) +} + +func trailingChipHints(fitted, keys string, label, chip lipgloss.Style) string { if head, ok := strings.CutSuffix(fitted, keys); ok { if head == "" { - return renderHints(keys) + return chipHints(keys, label, chip) } - return styleHint.Render(head) + renderHints(keys) + return label.Render(head) + chipHints(keys, label, chip) } // The fit cut into the keys, so no other text is left. if strings.HasSuffix(keys, strings.TrimPrefix(fitted, "… ")) { + return chipHints(fitted, label, chip) + } + return label.Render(fitted) +} + +// renderKeyBar is renderHints for the last line of the screen: with color, the line is a +// shaded bar padded to width (no pad when width <= 0). Under Ascii it is renderHints. +func renderKeyBar(fitted string, width int) string { + if !colorOn() { return renderHints(fitted) } - return styleHint.Render(fitted) + return padBar(chipHints(fitted, styleBarLabel, styleBarChip), width) +} + +// renderTrailingKeyBar is renderTrailingHints drawn as the key bar (see renderKeyBar). +func renderTrailingKeyBar(fitted, keys string, width int) string { + if !colorOn() { + return renderTrailingHints(fitted, keys) + } + return padBar(trailingChipHints(fitted, keys, styleBarLabel, styleBarChip), width) +} + +func padBar(line string, width int) string { + if pad := width - lipgloss.Width(line); pad > 0 { + line += styleBar.Render(strings.Repeat(" ", pad)) + } + return line } // titleMarkRe finds the parts of a title that are not bold default ink. diff --git a/cmd/agentop/tui/table_cursor_test.go b/cmd/agentop/tui/table_cursor_test.go index 780885870..da7f0a500 100644 --- a/cmd/agentop/tui/table_cursor_test.go +++ b/cmd/agentop/tui/table_cursor_test.go @@ -269,7 +269,7 @@ func TestEventsTable_ResizeKeepsSelectionVisible(t *testing.T) { } // TestEventsTable_ShrinkKeepsSelectionVisible covers the rows-SHRINK case, the one the -// old `else if prevRow < len(rows)` skipped outright: toggling hideInactive can pull the +// old `else if prevRow < len(rows)` skipped outright: FIFO eviction can pull the // list out from under the cursor, and with no restore the cursor was left wherever SetRows // had clamped it, with an offset nobody reconciled. (Typing a filter could too, until `/` // became a search that hides nothing.) @@ -278,16 +278,9 @@ func TestEventsTable_ResizeKeepsSelectionVisible(t *testing.T) { // is the one where the stale offset still addresses a line of the new, shorter content — a // drastic shrink is self-correcting, a moderate one is not. func TestEventsTable_ShrinkKeepsSelectionVisible(t *testing.T) { - // keep gives events [from, to) a plugin invocation, so hiding inactive rows keeps those. + // keep leaves only events [from, to) in the cache, as an eviction would. keep := func(from, to int) func(m *model) { - return func(m *model) { - for i := from; i < to; i++ { - m.events["s"][i].Invocations = &pipeline.Invocations{Outbound: []pipeline.Invocation{ - {Plugin: "tool-prune", Action: pipeline.ActionModify, Reason: "tools_pruned"}, - }} - } - m.hideInactive = true - } + return func(m *model) { m.events["s"] = m.events["s"][from:to] } } for _, tc := range []struct { name string @@ -301,6 +294,7 @@ func TestEventsTable_ShrinkKeepsSelectionVisible(t *testing.T) { } { t.Run(tc.name, func(t *testing.T) { m := cursorModel(t, 40) + all := m.events["s"] setCursorVisible(&m.eventsTbl, 30) assertSelectionVisible(t, m.eventsTbl, "parked at row 30") @@ -320,7 +314,7 @@ func TestEventsTable_ShrinkKeepsSelectionVisible(t *testing.T) { } // Showing every row grows the list back; the cursor must still be on screen. - m.hideInactive = false + m.events["s"] = all m.rebuildEventsTable() if got := len(m.eventsTbl.Rows()); got != 40 { t.Fatalf("showing every row left %d rows, want 40", got) @@ -333,43 +327,6 @@ func TestEventsTable_ShrinkKeepsSelectionVisible(t *testing.T) { } } -// hideInactive is the other shrink lever, and it hides rows from the MIDDLE of the list -// rather than the ends, so the surviving rows keep no relationship to their old indices. -func TestEventsTable_HideInactiveShrinkKeepsSelectionVisible(t *testing.T) { - events := cursorRowsFixture(40) - // Give a handful of events a plugin invocation so they survive the inactive filter. - active := map[int]bool{2: true, 9: true, 17: true, 26: true, 33: true, 38: true} - for i := range events { - if active[i] { - events[i].Invocations = &pipeline.Invocations{Outbound: []pipeline.Invocation{ - {Plugin: "tool-prune", Action: pipeline.ActionModify, Reason: "tools_pruned"}, - }} - } - } - m := &model{ - pane: paneEvents, selectedSess: "s", bodyHeight: 12, width: 200, - events: map[string][]pipeline.SessionEvent{"s": events}, - } - m.eventsTbl = newEventsTable() - m.rebuildEventsTable() - setCursorVisible(&m.eventsTbl, 30) - assertSelectionVisible(t, m.eventsTbl, "parked at row 30") - - m.hideInactive = true - m.rebuildEventsTable() - if got, want := len(m.eventsTbl.Rows()), len(active); got != want { - t.Fatalf("hideInactive left %d rows, want %d", got, want) - } - assertSelectionVisible(t, m.eventsTbl, "after hideInactive shrank the list") - if _, ok := m.selectedEventRow(); !ok { - t.Error("no selected row resolves after hideInactive") - } - - m.hideInactive = false - m.rebuildEventsTable() - assertSelectionVisible(t, m.eventsTbl, "after hideInactive off") -} - // sessionsModel builds a sessions pane with n sessions, taller than the table, and the // cursor parked on one of them. IDs carry the marker so the same visibility assertion works. func sessionsModel(t *testing.T, n int) *model { @@ -379,7 +336,8 @@ func sessionsModel(t *testing.T, n int) *model { m.sessionsTbl.SetHeight(12) for i := 0; i < n; i++ { m.sessions = append(m.sessions, session.SessionSummary{ - ID: hostToken(i), UpdatedAt: time.Now(), EventCount: 3, + // The title carries the marker: SESSION shows only 8 characters of the id. + ID: hostToken(i), Title: hostToken(i), UpdatedAt: time.Now(), EventCount: 3, }) } m.rebuildSessionsTable() diff --git a/cmd/agentop/tui/timeline_pane.go b/cmd/agentop/tui/timeline_pane.go index 53aa08267..beaffcad5 100644 --- a/cmd/agentop/tui/timeline_pane.go +++ b/cmd/agentop/tui/timeline_pane.go @@ -8,6 +8,7 @@ import ( "strconv" "strings" "time" + "unicode/utf8" tea "github.com/charmbracelet/bubbletea" "github.com/charmbracelet/lipgloss" @@ -407,14 +408,13 @@ func (m *model) timelineLayoutNow() (tlLayout, bool) { return t.layout, true } -// The pane's fixed lines: tabs, axis, column heads, the separator, the closing rule, the -// legend's lines and the cursor line. Each agent and host row takes two lines, its own and the +// The pane's fixed lines: the header (window tabs, axis and column heads), the separator, the +// closing rule, the legend's line and the cursor line. Each agent and host row takes two lines, its own and the // blank one that keeps a row's bars off the next row's. const ( - timelineFixedLines = 8 - // timelineLegendLines is how many lines legend draws. The tok/s note has a line of its own, - // so it is not cut at a width where the chart itself still fits. - timelineLegendLines = 2 + timelineFixedLines = 5 + // timelineLegendLines is how many lines legend draws. + timelineLegendLines = 1 ) // tlEmptyLines is what an empty side draws in place of its rows: a note and a blank line. @@ -724,18 +724,8 @@ func (m *model) renderTimeline() string { return b.String() } _, _, now, win := m.timelineRange() - var tabs []string - for _, i := range offeredWindows(t.sessionSpan(now)) { - l := timelineWindows[i].label - if i == win { - l = "[" + l + "]" - } - tabs = append(tabs, l) - } - fmt.Fprintf(&b, "%s %s\n", styleTitle.Render("window "+strings.Join(tabs, " ")), styleMuted.Render(m.timelineStatus(lay))) width := lay.axis.width() - b.WriteString(strings.Repeat(" ", timelineLabelWidth) + styleMuted.Render(axisLabels(lay)) + "\n") - b.WriteString(strings.Repeat(" ", timelineLabelWidth+width) + styleMuted.Render(" model tools tok/s") + "\n") + b.WriteString(m.timelineHeader(lay, offeredWindows(t.sessionSpan(now)), win) + "\n") agentRows := m.timelineAgentRows(lay) agentOff, hostOff := m.timelineOffsets(lay) @@ -774,19 +764,32 @@ func (m *model) renderTimeline() string { return b.String() } +// legend is one line that fits m.width: whole items drop from the right, never a wrap. func (m *model) legend() string { - sw := func(c lipgloss.AdaptiveColor, s string) string { - return lipgloss.NewStyle().Foreground(c).Render("█") + styleMuted.Render(" "+s+" ") + sw := func(sep string, c lipgloss.AdaptiveColor, s string) [2]string { + return [2]string{sep + "█ " + s, styleMuted.Render(sep) + lipgloss.NewStyle().Foreground(c).Render("█") + styleMuted.Render(" "+s)} + } + note := func(s string) [2]string { return [2]string{s, styleMuted.Render(s)} } + items := [][2]string{ + sw("", colorTLTool, "tools"), sw(" ", colorTLModel, "model"), sw(" ", colorTLRetry, "retrying"), + sw(" ", colorTLSubs, "waiting on subagents"), sw(" ", colorTLUser, "waiting on you"), + note(" ┆ time cut from the axis"), note(" ▁…█ requests in flight"), + } + var plain, styled strings.Builder + for _, it := range items { + if lipgloss.Width(plain.String()+it[0]) > m.width { + break + } + plain.WriteString(it[0]) + styled.WriteString(it[1]) } - return sw(colorTLTool, "tools") + sw(colorTLModel, "model") + sw(colorTLRetry, "retrying") + - sw(colorTLSubs, "waiting on subagents") + sw(colorTLUser, "waiting on you") + - styleMuted.Render("┆ time cut from the axis, in its colour ▁…█ requests in flight") + "\n" + - styleMuted.Render(" tok/s output per second of model time, last 60 s") + return styled.String() } -func (m *model) timelineStatus(lay tlLayout) string { +// timelineStatus is the pane's notes, joined, or "" when there are none. +func (m *model) timelineStatus() string { t := &m.timeline - parts := []string{fmt.Sprintf("%s → %s", lay.from.Local().Format("01-02 15:04"), lay.to.Local().Format("01-02 15:04"))} + var parts []string if t.tl.Truncated { parts = append(parts, "oldest events not shown") } @@ -796,50 +799,142 @@ func (m *model) timelineStatus(lay tlLayout) string { return strings.Join(parts, " · ") } -// axisLabels is the time axis: each collapsed gap's length centred on its marker, then a time -// every 16 cells where it does not crowd one. -func axisLabels(lay tlLayout) string { +// timelineHeader is the pane's one header line: the window selector in the label column, the +// time axis, and the gutter's column heads. +func (m *model) timelineHeader(lay tlLayout, offered []int, win int) string { + var b strings.Builder + b.WriteString(styleMuted.Render("window ")) + for _, i := range offered { + l := timelineWindows[i].label + switch { + case i != win: + b.WriteString(styleMuted.Render(" " + l + " ")) + case lipgloss.ColorProfile() == termenv.Ascii: + b.WriteString("[" + l + "]") + default: + b.WriteString(styleSeg.Render(" " + l + " ")) + } + } + return padRight(b.String(), timelineLabelWidth) + renderAxisLine(axisLabels(lay), lay.axis.width()) + + styleMuted.Render(padRight(" model tools tok/s", timelineGutterWidth)) +} + +// tlAxisLabel is one label on the time axis. cell is the first column of text; date is the byte +// length of the "MM-DD " part at the start of text, after any leading tick; bold marks the two +// ends. +type tlAxisLabel struct { + cell int + text string + date int + bold bool +} + +// axisLabels places the time axis's labels: the dated start and finish, each collapsed gap's +// length centred on its marker, then a time every 16 cells, dated on a new day. A label that +// would touch a placed one is dropped, never cut. +func axisLabels(lay tlLayout) []tlAxisLabel { w := lay.axis.width() - line := []rune(strings.Repeat(" ", w+16)) - taken := make([]bool, len(line)) - claim := func(c int, s string) { - rs := []rune(s) - if c < 0 || c+len(rs) > len(line) { - return + taken := make([]bool, w) + var out []tlAxisLabel + claim := func(l tlAxisLabel) bool { + n := utf8.RuneCountInString(l.text) + if l.cell < 0 || l.cell+n > w { + return false } - for i := max(c-1, 0); i <= c+len(rs) && i < len(taken); i++ { + for i := max(l.cell-1, 0); i <= l.cell+n && i < w; i++ { if taken[i] { - return + return false } } - for i, r := range rs { - line[c+i], taken[c+i] = r, true + for i := l.cell; i < l.cell+n; i++ { + taken[i] = true } + out = append(out, l) + return true + } + if w == 0 { + return nil + } + format := "15:04" + if lay.to.Sub(lay.from) <= 10*time.Minute { + format = "15:04:05" + } + start, finish := lay.axis.cells[0].from.Local(), lay.axis.cells[w-1].to.Local() + ends := func(dated bool) (tlAxisLabel, tlAxisLabel) { + f, d := format, 0 + if dated { + f, d = "01-02 "+format, len("01-02 ") + } + s, e := start.Format(f), finish.Format(f) + return tlAxisLabel{0, "╷" + s, d, true}, tlAxisLabel{w - utf8.RuneCountInString(e) - 1, e + "╷", d, true} + } + fits := func(s, e tlAxisLabel) bool { return utf8.RuneCountInString(s.text)+1 <= e.cell } + s, e := ends(true) + if !fits(s, e) { + s, e = ends(false) + } + if !claim(s) { + return nil + } + if fits(s, e) { + claim(e) } for c, cell := range lay.axis.cells { if cell.marker { label := tlDuration(cell.to.Sub(cell.from)) - claim(c-len(label)/2, label) + claim(tlAxisLabel{cell: c - len(label)/2, text: label}) } } // A squeezed live wait is labelled with its length, like a gap, since its cells are not to - // scale with the rest. + // scale with the rest. The finish covers those cells, so the label goes just before it. if n := lay.axis.tail; n > 0 { label := "+" + tlDuration(lay.axis.cells[w-1].to.Sub(lay.axis.cells[w-n].from)) - claim(w-n, label) + claim(tlAxisLabel{cell: min(w-n, e.cell-1-utf8.RuneCountInString(label)), text: label}) } - format := "15:04" - if span := lay.to.Sub(lay.from); span <= 10*time.Minute { - format = "15:04:05" - } else if span > 36*time.Hour { - format = "01-02 15:04" + day := start.Format("01-02") + for c := 16; c < w; c += 16 { + if lay.axis.cells[c].gap { + continue + } + t := lay.axis.cells[c].from.Local() + l := tlAxisLabel{cell: c, text: "╷" + t.Format(format)} + if t.Format("01-02") != day { + l.text, l.date = "╷"+t.Format("01-02 "+format), len("01-02 ") + } + if claim(l) { + day = t.Format("01-02") + } } - for c := 0; c < w-5; c += 16 { - if !lay.axis.cells[c].gap { - claim(c, lay.axis.cells[c].from.Local().Format(format)) + return out +} + +// renderAxisLine draws labels on a line exactly w columns wide: ticks dim, dates muted, the +// ends' times bold and the other times muted. +func renderAxisLine(labels []tlAxisLabel, w int) string { + labels = slices.SortedFunc(slices.Values(labels), func(a, b tlAxisLabel) int { return a.cell - b.cell }) + var b strings.Builder + col := 0 + for _, l := range labels { + b.WriteString(strings.Repeat(" ", l.cell-col)) + col = l.cell + utf8.RuneCountInString(l.text) + s, tick := l.text, styleDim.Render("╷") + if r, ok := strings.CutPrefix(s, "╷"); ok { + b.WriteString(tick) + s = r + } + r, tail := strings.CutSuffix(s, "╷") + b.WriteString(styleMuted.Render(r[:l.date])) + if l.bold { + b.WriteString(styleBold.Render(r[l.date:])) + } else { + b.WriteString(styleMuted.Render(r[l.date:])) + } + if tail { + b.WriteString(tick) } } - return strings.TrimRight(string(line[:min(len(line), w+8)]), " ") + b.WriteString(strings.Repeat(" ", max(w-col, 0))) + return b.String() } // timelineLabelHarvestEvery is the shortest time between two harvests that the timeline pane @@ -959,7 +1054,12 @@ func (m *model) cursorAt(c int, s string) string { func (m *model) cursorStrip(lay tlLayout) string { c := m.timeline.cursor if c < 0 || c >= lay.axis.width() { - return renderHints("▸ [←→] pick a moment: lists the tools running then, with their durations and commands") + // The row stays, so the chart does not move when a moment is picked; until then it + // carries the pane's notes. + if st := m.timelineStatus(); st != "" { + return styleMuted.Render(truncToWidth(st, max(m.width, 1))) + } + return "" } cell := lay.axis.cells[c] head := fmt.Sprintf("▸ %s ", cell.from.Local().Format("15:04:05")) diff --git a/cmd/agentop/tui/timeline_pane_test.go b/cmd/agentop/tui/timeline_pane_test.go index c0b407ae4..e88c7fca0 100644 --- a/cmd/agentop/tui/timeline_pane_test.go +++ b/cmd/agentop/tui/timeline_pane_test.go @@ -8,6 +8,7 @@ import ( tea "github.com/charmbracelet/bubbletea" "github.com/charmbracelet/lipgloss" + "github.com/charmbracelet/x/ansi" "github.com/muesli/termenv" "github.com/rossoctl/cortex/cmd/agentop/tui/table" @@ -285,8 +286,8 @@ func TestTimelineAxisLabels_NameTheGap(t *testing.T) { lateEnd := late.Add(5 * time.Minute) tl.Turns = append(tl.Turns, timeline.Turn{Agent: timeline.MainAgent, Start: late, End: &lateEnd, Finish: "end_turn", Seq: 50}) tl.End = lateEnd - lay := buildTimelineLayout(tl, time.Time{}, time.Time{}, 80, time.Time{}, lateEnd) - if labels := axisLabels(lay); !strings.Contains(labels, "26.0h") { + lay := buildTimelineLayout(tl, time.Time{}, time.Time{}, 200, time.Time{}, lateEnd) + if labels := ansi.Strip(renderAxisLine(axisLabels(lay), lay.axis.width())); !strings.Contains(labels, "26.0h") { t.Errorf("axis does not label the gap: %q", labels) } } @@ -379,7 +380,7 @@ func TestTimelineWindows_OfferedBySessionLength(t *testing.T) { if m.timeline.windowIdx != 2 { t.Errorf("drawing the fallback overwrote the saved choice") } - if got := stripANSI(m.renderTimeline()); !strings.Contains(got, "window 5m [all]") { + if got := stripANSI(m.renderTimeline()); !strings.Contains(got, "window 5m [all]") { t.Errorf("tabs are not the offered windows: %q", strings.SplitN(got, "\n", 2)[0]) } } @@ -957,25 +958,6 @@ func TestTimelineEnter_RevealSkipsALinkedBucketsEventOfTheSameSeq(t *testing.T) } } -// [↑↓] is advertised only when some agent rows do not fit. -func TestTimelineFooter_ScrollHintOnlyWhenRowsAreHidden(t *testing.T) { - m := timelineModel(t, 140, 46) - m.timeline.windowIdx = 3 - m.layout() - if strings.Contains(m.helpView(), "[↑↓]") { - t.Errorf("every agent fits, yet the footer offers [↑↓]: %q", m.helpView()) - } - many := sampleTimeline() - for i := 0; i < 20; i++ { - id := string(rune('b' + i)) - many.Agents = append(many.Agents, timeline.Agent{ID: id, Parent: timeline.MainAgent, Label: "subagent " + id}) - } - m.timeline.tl, m.timeline.layoutKey = many, tlLayoutKey{} - if !strings.Contains(m.helpView(), "[↑↓] rows") { - t.Errorf("rows are hidden, yet the footer does not offer [↑↓]: %q", m.helpView()) - } -} - // laterSession is sampleTimeline plus a turn a day after it, so "all" collapses the stretch // between them into a gap. func laterSession(after timeline.Turn) *timeline.Timeline { @@ -1345,9 +1327,12 @@ func TestTimelineAll_LongLiveWaitIsCapped(t *testing.T) { if !tc.capped && (tailCells > timelineTailCells || lay.axis.tail != 0) { t.Errorf("%v on: a short wait took %d cells (tail %d), want it drawn to scale", tc.after, tailCells, lay.axis.tail) } - if label := axisLabels(lay); tc.capped != strings.Contains(label, "+"+tlDuration(tc.after)) { + if label := ansi.Strip(renderAxisLine(axisLabels(lay), lay.axis.width())); tc.capped != strings.Contains(label, "+"+tlDuration(tc.after)) { t.Errorf("%v on: axis %q, want the squeezed wait labelled only when squeezed", tc.after, label) } + if label := ansi.Strip(renderAxisLine(axisLabels(lay), lay.axis.width())); !strings.HasSuffix(strings.TrimRight(label, " "), live.Local().Format("15:04")+"╷") { + t.Errorf("%v on: axis %q, want it to finish at now, %s", tc.after, label, live.Local().Format("15:04")) + } } } @@ -1628,39 +1613,260 @@ func TestTimelineRender_TokPerSecColumn(t *testing.T) { } } -// The tok/s note is the only text that explains the column, so the user must see it. The body -// cuts every line at the pane's width, so the note needs its own legend line to survive at the -// widths people use. -func TestTimelineRender_TokPerSecNoteReachesTheUser(t *testing.T) { - const note = "tok/s output per second of model time, last 60 s" - for _, w := range []int{140, 120} { +const fullTimelineLegend = "█ tools █ model █ retrying █ waiting on subagents █ waiting on you ┆ time cut from the axis ▁…█ requests in flight" + +// The legend is one line, and it no longer explains tok/s or says "in its colour". +func TestTimelineLegend_OneLine(t *testing.T) { + m := timelineModel(t, 200, 46) + plainWidth := lipgloss.Width(m.legend()) + restore := lipgloss.ColorProfile() + t.Cleanup(func() { lipgloss.SetColorProfile(restore) }) + lipgloss.SetColorProfile(termenv.TrueColor) + l := m.legend() + got := ansi.Strip(l) + if !strings.Contains(l, lipgloss.NewStyle().Foreground(colorTLTool).Render("█")) { + t.Errorf("tools swatch lost its color: %q", l) + } + if lipgloss.Width(l) != plainWidth { + t.Errorf("width %d under TrueColor, %d under Ascii", lipgloss.Width(l), plainWidth) + } + if got != fullTimelineLegend { + t.Errorf("legend = %q, want %q", got, fullTimelineLegend) + } + if strings.Contains(got, "\n") || strings.Contains(got, "tok/s") || strings.Contains(got, "in its colour") { + t.Errorf("legend = %q", got) + } +} + +// A legend too wide for the terminal drops whole items from the right and never wraps. +func TestTimelineLegend_DropsFromTheRight(t *testing.T) { + full := lipgloss.Width(fullTimelineLegend) + m := timelineModel(t, full-1, 46) + got := ansi.Strip(m.legend()) + if want := "█ tools █ model █ retrying █ waiting on subagents █ waiting on you ┆ time cut from the axis"; got != want { + t.Errorf("at %d columns legend = %q, want %q", full-1, got, want) + } + m = timelineModel(t, full-30, 46) + if got, want := ansi.Strip(m.legend()), "█ tools █ model █ retrying █ waiting on subagents █ waiting on you"; got != want { + t.Errorf("at %d columns legend = %q, want %q", full-30, got, want) + } + for w := 1; w <= full+2; w++ { m := timelineModel(t, w, 46) - m.timeline.windowIdx = 3 - body := stripANSI(m.timelineBody()) - if !strings.Contains(body, note) { - t.Errorf("at %d columns the body does not explain tok/s:\n%s", w, body) + l := m.legend() + if strings.Contains(l, "\n") || lipgloss.Width(l) > w { + t.Fatalf("at %d columns legend = %q (%d wide)", w, ansi.Strip(l), lipgloss.Width(l)) + } + if !strings.HasPrefix(fullTimelineLegend, ansi.Strip(l)) { + t.Fatalf("at %d columns legend %q is not a cut of the full text from the right", w, ansi.Strip(l)) } - for _, l := range strings.Split(stripANSI(m.legend()), "\n") { - if strings.Contains(l, note) && lipgloss.Width(l) > w { - t.Errorf("at %d columns the note's legend line is %d wide: %q", w, lipgloss.Width(l), l) + } +} + +// With no moment picked the cursor row stays, blank, so ← does not move the chart. +func TestCursorStrip_IdleRowIsBlank(t *testing.T) { + m := timelineModel(t, 140, 46) + m.timeline.windowIdx = 3 + lay, _ := m.timelineLayoutNow() + if s := m.cursorStrip(lay); s != "" { + t.Errorf("idle cursor strip = %q, want blank", ansi.Strip(s)) + } + firstRow := func() int { + for i, l := range strings.Split(stripANSI(m.renderTimeline()), "\n") { + if strings.Contains(l, "main agent") { + return i } } + t.Fatal("no main agent row") + return -1 + } + before := stripANSI(m.renderTimeline()) + at := firstRow() + lines := strings.Split(before, "\n") + if last := lines[len(lines)-1]; strings.TrimSpace(last) != "" { + t.Errorf("idle body ends with %q, want the blank cursor row", last) + } + // Fixed lines (5, one of them the legend) plus two per shown row, and nothing else. + agents := m.timelineAgentRows(lay) + if want := timelineFixedLines + tlEmptyLines(lay) + 2*agents + 2*m.timelineHostRows(lay, agents); len(lines) != want { + t.Errorf("idle body is %d lines, want %d:\n%s", len(lines), want, before) + } + m.handleKey(tea.KeyMsg{Type: tea.KeyLeft}) + if got := firstRow(); got != at { + t.Errorf("← moved the chart from line %d to %d", at, got) + } + if n, k := len(lines), len(strings.Split(stripANSI(m.renderTimeline()), "\n")); n != k { + t.Errorf("← changed the body from %d to %d lines", n, k) } } -// Color changes no text and no width on the timeline; the cursor strip's [←→] is a key chip. +// Color changes no text and no width on the timeline. func TestTimeline_PlainInvariant(t *testing.T) { for _, w := range []int{80, 100, 140} { m := timelineModel(t, w, 46) - assertPlainInvariant(t, m.renderTimeline, -1) + assertPlainInvariant(t, m.renderTimeline, 0, -1) // line 0: the window tabs draw [5m] as a chip } restore := lipgloss.ColorProfile() t.Cleanup(func() { lipgloss.SetColorProfile(restore) }) lipgloss.SetColorProfile(termenv.TrueColor) out := timelineModel(t, 140, 46).renderTimeline() - for _, want := range []string{styleChip.Render(" ←→ "), styleDim.Render("│")} { + for _, want := range []string{styleDim.Render("│")} { if !strings.Contains(out, want) { t.Errorf("timeline lacks %q", want) } } } + +// axisAt is a linear layout of w cells, step apart, from the local time from. +func axisAt(from time.Time, step time.Duration, w int) tlLayout { + to := from.Add(step * time.Duration(w)) + return tlLayout{axis: tlLinearAxis(from, to, w), from: from, to: to} +} + +func localAt(month time.Month, day, hour, min int) time.Time { + return time.Date(2026, month, day, hour, min, 0, 0, time.Local) +} + +// axisTexts is each label's cell and text, in placement order sorted by cell. +func axisTexts(labels []tlAxisLabel) map[int]string { + out := map[int]string{} + for _, l := range labels { + out[l.cell] = l.text + } + return out +} + +func assertAxis(t *testing.T, name string, lay tlLayout, want map[int]string) { + t.Helper() + got := axisTexts(axisLabels(lay)) + if len(got) != len(want) { + t.Errorf("%s: labels %v, want %v", name, got, want) + return + } + for c, s := range want { + if got[c] != s { + t.Errorf("%s: label at cell %d = %q, want %q (all %v)", name, c, got[c], s, got) + } + } + line := renderAxisLine(axisLabels(lay), lay.axis.width()) + if lipgloss.Width(line) != lay.axis.width() { + t.Errorf("%s: axis line is %d wide, want %d", name, lipgloss.Width(line), lay.axis.width()) + } +} + +func TestAxisLabels_SameDay(t *testing.T) { + lay := axisAt(localAt(11, 19, 23, 30), 30*time.Second, 60) + assertAxis(t, "same day", lay, map[int]string{ + 0: "╷11-19 23:30", 16: "╷23:38", 32: "╷23:46", 48: "11-20 00:00╷", + }) +} + +func TestAxisLabels_AcrossMidnight(t *testing.T) { + lay := axisAt(localAt(11, 19, 23, 45), 30*time.Second, 60) + assertAxis(t, "across midnight", lay, map[int]string{ + 0: "╷11-19 23:45", 16: "╷23:53", 32: "╷11-20 00:01", 48: "11-20 00:15╷", + }) +} + +func TestAxisLabels_ThreeDays(t *testing.T) { + lay := axisAt(localAt(11, 18, 0, 0), 45*time.Minute, 96) + assertAxis(t, "three days", lay, map[int]string{ + 0: "╷11-18 00:00", 16: "╷12:00", 32: "╷11-19 00:00", 48: "╷12:00", 64: "╷11-20 00:00", 84: "11-21 00:00╷", + }) +} + +// A middle label that would touch the finish is dropped whole; no label is ever cut. +func TestAxisLabels_DropsOverlap(t *testing.T) { + lay := axisAt(localAt(11, 19, 23, 30), 30*time.Second, 46) + assertAxis(t, "overlap", lay, map[int]string{0: "╷11-19 23:30", 16: "╷23:38", 34: "11-19 23:53╷"}) +} + +// Under 25 cells the dated ends do not fit with a blank between, so they lose their dates; under +// 13 only the start shows, and under 6 nothing does. +func TestAxisLabels_NarrowUndated(t *testing.T) { + assertAxis(t, "21 cells", axisAt(localAt(11, 19, 23, 30), 3*time.Minute, 21), map[int]string{0: "╷23:30", 15: "00:33╷"}) + assertAxis(t, "25 cells", axisAt(localAt(11, 19, 23, 30), 3*time.Minute, 25), map[int]string{0: "╷11-19 23:30", 13: "11-20 00:45╷"}) + assertAxis(t, "12 cells", axisAt(localAt(11, 19, 23, 30), 3*time.Minute, 12), map[int]string{0: "╷23:30"}) + assertAxis(t, "5 cells", axisAt(localAt(11, 19, 23, 30), 3*time.Minute, 5), map[int]string{}) +} + +// Each tick sits on the cell whose start is the label's time, seconds included in a short window; +// the finish ticks the last cell and names its end. +func TestAxisLabels_TickOnNamedCell(t *testing.T) { + for _, tc := range []struct { + lay tlLayout + format string + }{ + {axisAt(localAt(11, 18, 0, 0), 45*time.Minute, 96), "15:04"}, + {axisAt(localAt(11, 19, 23, 58), 5*time.Second, 60), "15:04:05"}, + } { + for _, l := range axisLabels(tc.lay) { + rs := []rune(l.text) + tick, text := l.cell, string(rs[1:]) + if rs[len(rs)-1] == '╷' { + tick, text = l.cell+len(rs)-1, string(rs[:len(rs)-1]) + } + named := tc.lay.axis.cells[tick].from.Local() + if tick == tc.lay.axis.width()-1 { + named = tc.lay.axis.cells[tick].to.Local() + } + if !strings.HasSuffix(text, named.Format(tc.format)) || (l.date > 0 && !strings.HasPrefix(text, named.Format("01-02 "))) { + t.Errorf("label %q ticks cell %d, which starts at %s", l.text, tick, named.Format("01-02 15:04:05")) + } + } + } +} + +// The header is one line: the window selector, the axis and the gutter heads. +func TestTimelineHeader_OneLine(t *testing.T) { + header := func(p termenv.Profile) (string, tlLayout) { + withProfile(t, p) + m := timelineModel(t, 140, 46) + m.timeline.tl = laterSession(timeline.Turn{}) + end := m.timeline.tl.End.Add(2 * time.Hour) + m.now = func() time.Time { return end } + m.timeline.windowIdx = 1 + lay, _ := m.timelineLayoutNow() + return strings.SplitN(m.renderTimeline(), "\n", 2)[0], lay + } + line, lay := header(termenv.TrueColor) + axis := ansi.Strip(renderAxisLine(axisLabels(lay), lay.axis.width())) + if want := padRight("window 5m 1h 24h all ", timelineLabelWidth) + axis + " model tools tok/s"; ansi.Strip(line) != want { + t.Errorf("header = %q\nwant %q", ansi.Strip(line), want) + } + if !strings.Contains(line, styleSeg.Render(" 1h ")) { + t.Errorf("the current window is not filled: %q", line) + } + if strings.Contains(ansi.Strip(line), "→") { + t.Errorf("the range text is still drawn: %q", ansi.Strip(line)) + } + plain, _ := header(termenv.Ascii) + if !strings.HasPrefix(plain, "window 5m [1h] 24h all ") { + t.Errorf("Ascii header = %q, want the current window in brackets", plain) + } + if lipgloss.Width(plain) != lipgloss.Width(line) { + t.Errorf("header is %d wide under Ascii, %d under TrueColor", lipgloss.Width(plain), lipgloss.Width(line)) + } +} + +// The notes the header used to carry show on the cursor row while no moment is picked. +func TestTimelineStatus_OnIdleCursorRow(t *testing.T) { + m := timelineModel(t, 140, 46) + m.timeline.windowIdx = 3 + m.timeline.tl.Truncated = true + last := func() string { + lines := strings.Split(stripANSI(m.renderTimeline()), "\n") + return lines[len(lines)-1] + } + if got := last(); got != "oldest events not shown" { + t.Errorf("idle cursor row = %q, want the note", got) + } + m.timeline.err = errors.New("down") + if got := last(); got != "oldest events not shown · refresh failed: down" { + t.Errorf("idle cursor row = %q, want both notes", got) + } + lay, _ := m.timelineLayoutNow() + m.timeline.cursor = cellOf(t, lay, 210) + if got := last(); !strings.HasPrefix(got, "▸ ") || strings.Contains(got, "oldest events") { + t.Errorf("cursor row with a moment picked = %q, want that moment", got) + } +} diff --git a/cmd/agentop/tui/tool_enter_test.go b/cmd/agentop/tui/tool_enter_test.go index 79e4f5433..cdcb03f9e 100644 --- a/cmd/agentop/tui/tool_enter_test.go +++ b/cmd/agentop/tui/tool_enter_test.go @@ -11,11 +11,6 @@ import ( "github.com/rossoctl/cortex/core/session/timeline" ) -// actOnFirst gives event seq 1 an acting invocation, so hideInactive keeps exchange 1 only. -func actOnFirst(events []pipeline.SessionEvent) { - events[0].Invocations = &pipeline.Invocations{Outbound: []pipeline.Invocation{{Plugin: "p", Action: pipeline.ActionAllow}}} -} - func TestToolTarget(t *testing.T) { lost := trTool(2, "t1", "Bash", 12, 20, "") lost.Lost = true @@ -24,33 +19,21 @@ func TestToolTarget(t *testing.T) { for _, c := range []struct { name string tools []timeline.Tool - hide bool wantSeq uint64 inRequest bool ok bool }{ - {"ended", []timeline.Tool{trTool(2, "t1", "Bash", 12, 20, "")}, false, 3, true, true}, - {"running", []timeline.Tool{trTool(2, "t1", "Bash", 12, -1, "")}, false, 1, false, true}, - {"lost", []timeline.Tool{lost}, false, 1, false, true}, - {"SubagentHandback", []timeline.Tool{handback}, false, 1, false, true}, - {"clamped end", []timeline.Tool{trTool(2, "t1", "Bash", 12, 13, "")}, false, 1, false, true}, - {"hidden by filter", []timeline.Tool{trTool(2, "t1", "Bash", 12, 20, "")}, true, 3, true, true}, - {"not held", []timeline.Tool{trTool(99, "t1", "Bash", 12, 50, "")}, false, 0, false, false}, - {"parallel", []timeline.Tool{trTool(2, "t1", "Bash", 12, 20, ""), trTool(2, "t2", "Read", 12, 20, "")}, false, 3, true, true}, + {"ended", []timeline.Tool{trTool(2, "t1", "Bash", 12, 20, "")}, 3, true, true}, + {"running", []timeline.Tool{trTool(2, "t1", "Bash", 12, -1, "")}, 1, false, true}, + {"lost", []timeline.Tool{lost}, 1, false, true}, + {"SubagentHandback", []timeline.Tool{handback}, 1, false, true}, + {"clamped end", []timeline.Tool{trTool(2, "t1", "Bash", 12, 13, "")}, 1, false, true}, + {"not held", []timeline.Tool{trTool(99, "t1", "Bash", 12, 50, "")}, 0, false, false}, + {"parallel", []timeline.Tool{trTool(2, "t1", "Bash", 12, 20, ""), trTool(2, "t2", "Read", 12, 20, "")}, 3, true, true}, } { t.Run(c.name, func(t *testing.T) { events := slices.Concat(trExchange(1, 10, ""), trExchange(2, 20, "")) - if c.hide { - actOnFirst(events) - } m := toolRowsModel(t, events, &timeline.Timeline{Tools: c.tools}) - if c.hide { - m.hideInactive = true - m.rebuildEventsTable() - if slices.ContainsFunc(m.visibleRows, func(r eventRow) bool { return r.event != nil && r.event.Seq == 3 }) { - t.Fatal("seq 3 still shows") - } - } for _, tool := range c.tools { row, _, inRequest, ok := m.toolTarget(&toolRow{Tool: tool}) if ok != c.ok { @@ -76,22 +59,14 @@ func enterOnTool(t *testing.T, m *model) int { return i } -func endedModel(t *testing.T, hide bool) *model { +func endedModel(t *testing.T) *model { t.Helper() events := slices.Concat(trExchange(1, 10, ""), trExchange(2, 20, "")) - if hide { - actOnFirst(events) - } - m := toolRowsModel(t, events, &timeline.Timeline{Tools: []timeline.Tool{trTool(2, "t1", "Bash", 12, 20, "")}}) - if hide { - m.hideInactive = true - m.rebuildEventsTable() - } - return m + return toolRowsModel(t, events, &timeline.Timeline{Tools: []timeline.Tool{trTool(2, "t1", "Bash", 12, 20, "")}}) } func TestToolEnter_OpensTarget(t *testing.T) { - m := endedModel(t, false) + m := endedModel(t) j := slices.IndexFunc(m.visibleRows, func(r eventRow) bool { return r.event != nil && r.event.Seq == 3 }) want := toolCell(m, m.eventsTbl.Rows()[j], colIndex) enterOnTool(t, m) @@ -106,16 +81,8 @@ func TestToolEnter_OpensTarget(t *testing.T) { } } -func TestToolEnter_HeaderWhenHidden(t *testing.T) { - m := endedModel(t, true) - enterOnTool(t, m) - if m.pane != paneDetail || m.detailNum != "2" { - t.Errorf("pane %v, detailNum = %q, want 2", m.pane, m.detailNum) - } -} - func TestToolEnter_EscBack(t *testing.T) { - m := endedModel(t, false) + m := endedModel(t) i, _ := toolRowAt(t, m, "t1") setCursorVisible(&m.eventsTbl, i) key := m.selectedPinKey() @@ -128,7 +95,7 @@ func TestToolEnter_EscBack(t *testing.T) { // The held events lost the tool's exchange after the table was built: Enter opens nothing. func TestToolEnter_NoTarget(t *testing.T) { - m := endedModel(t, false) + m := endedModel(t) m.events[m.selectedSess] = trExchange(5, 50, "") enterOnTool(t, m) if m.pane != paneEvents { diff --git a/docs/assets/cortex-demo.svg b/docs/assets/cortex-demo.svg index d5e7c6015..b19470e97 100644 --- a/docs/assets/cortex-demo.svg +++ b/docs/assets/cortex-demo.svg @@ -379,27 +379,27 @@ clipPath rect{width:100000px} - - - tools model retrying waiting on subagents waiting on you ┆ time cut from the axis, in its colour … re - - tok/s output per second of model time, last 60 s - - -▸ ←→ pick a moment: lists the tools running then, with their durations and commands - -● connected12.4 events/sec feedback: https://github.com/rossoctl/cortex/issues/new/choose - - - - - - - - - w all ←→ moment enter events / search esc back ? keys q quit - - + tools model retrying waiting on subagents waiting on you ┆ time cut from the axis + +● connected12.4 events/sec feedback: https://github.com/rossoctl/cortex/issues/new/choose + + + + + + + + + + + + + + + + w all ←→ moment enter events / search esc back ? keys q quit + + @@ -429,7 +429,7 @@ clipPath rect{width:100000px} main agent │ 1m 5.9s 91 - + @@ -460,7 +460,7 @@ clipPath rect{width:100000px} Audit the auth flow │ 40s 9.3s 78 - + @@ -488,7 +488,7 @@ clipPath rect{width:100000px} Review retry logic │ 31s 10s 69 - + @@ -514,9 +514,9 @@ clipPath rect{width:100000px} Check DB migrations │ 29s 5.0s 63 - + - + @@ -536,18 +536,18 @@ clipPath rect{width:100000px} Scan deps for CVEs │ 25s 1.0s 82 - + - + Review docs and CI │ 6.0s 0.2s 61 - + -╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ +╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ - + @@ -561,47 +561,47 @@ clipPath rect{width:100000px} api.anthropic.com LLM │ 62 req - + - + github.com 🔒 │ 2 req - + - + api.github.com 🔒 │ 1 req - + -──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── +──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── - + - - - tools model retrying waiting on subagents waiting on you ┆ time cut from the axis, in its colour … re - - tok/s output per second of model time, last 60 s - - -▸ ←→ pick a moment: lists the tools running then, with their durations and commands - -● connected12.4 events/sec feedback: https://github.com/rossoctl/cortex/issues/new/choose - - - - - - - - - w all ←→ moment enter events / search esc back ? keys q quit - - + tools model retrying waiting on subagents waiting on you ┆ time cut from the axis + +● connected12.4 events/sec feedback: https://github.com/rossoctl/cortex/issues/new/choose + + + + + + + + + + + + + + + + w all ←→ moment enter events / search esc back ? keys q quit + + @@ -628,7 +628,7 @@ clipPath rect{width:100000px} main agent │ 1m 5.9s 91 - + @@ -669,7 +669,7 @@ clipPath rect{width:100000px} Audit the auth flow │ 1m 17s 81 - + @@ -708,7 +708,7 @@ clipPath rect{width:100000px} Review retry logic │ 1m 14s 76 - + @@ -742,7 +742,7 @@ clipPath rect{width:100000px} Check DB migrations │ 43s 31s 64 - + @@ -779,7 +779,7 @@ clipPath rect{width:100000px} Scan deps for CVEs │ 1m 2.3s 81 - + @@ -804,7 +804,7 @@ clipPath rect{width:100000px} Review docs and CI │ 34s 11s 82 - + @@ -826,14 +826,14 @@ clipPath rect{width:100000px} api.anthropic.com LLM │ 116 req - + github.com 🔒 │ 2 req - + api.github.com 🔒 │ 1 req - + @@ -858,7 +858,7 @@ clipPath rect{width:100000px} main agent │ 1m 5.9s 91 - + @@ -910,7 +910,7 @@ clipPath rect{width:100000px} Audit the auth flow │ 1m 25s 63 - + @@ -959,7 +959,7 @@ clipPath rect{width:100000px} Review retry logic │ 1m 23s 67 - + @@ -1000,7 +1000,7 @@ clipPath rect{width:100000px} Check DB migrations │ 1m 42s 61 - + @@ -1045,7 +1045,7 @@ clipPath rect{width:100000px} Scan deps for CVEs │ 1m 3.0s 63 - + @@ -1079,7 +1079,7 @@ clipPath rect{width:100000px} Review docs and CI │ 52s 33s 63 - + @@ -1107,14 +1107,14 @@ clipPath rect{width:100000px} api.anthropic.com LLM │ 154 req - + github.com 🔒 │ 2 req - + api.github.com 🔒 │ 1 req - + @@ -1140,7 +1140,7 @@ clipPath rect{width:100000px} main agent │ 1m 5.9s 91 - + @@ -1194,7 +1194,7 @@ clipPath rect{width:100000px} Audit the auth flow │ 2m 36s 61 - + @@ -1249,7 +1249,7 @@ clipPath rect{width:100000px} Review retry logic │ 2m 24s 74 - + @@ -1293,7 +1293,7 @@ clipPath rect{width:100000px} Check DB migrations │ 1m 48s 56 - + @@ -1332,7 +1332,7 @@ clipPath rect{width:100000px} Scan deps for CVEs │ 2m 3.7s 70 - + @@ -1382,7 +1382,7 @@ clipPath rect{width:100000px} Review docs and CI │ 1m 48s 70 - + @@ -1418,14 +1418,14 @@ clipPath rect{width:100000px} api.anthropic.com LLM │ 204 req - + github.com 🔒 │ 2 req - + api.github.com 🔒 │ 1 req - + @@ -1447,7 +1447,7 @@ clipPath rect{width:100000px} main agent │ 1m 5.9s 91 - + @@ -1509,7 +1509,7 @@ clipPath rect{width:100000px} Audit the auth flow │ 2m 41s 76 - + @@ -1558,7 +1558,7 @@ clipPath rect{width:100000px} Review retry logic │ 2m 25s 85 - + @@ -1604,7 +1604,7 @@ clipPath rect{width:100000px} Check DB migrations │ 2m 56s 60 - + @@ -1648,7 +1648,7 @@ clipPath rect{width:100000px} Scan deps for CVEs │ 3m 4.7s 76 - + @@ -1695,7 +1695,7 @@ clipPath rect{width:100000px} Review docs and CI │ 1m 54s 86 - + @@ -1731,14 +1731,14 @@ clipPath rect{width:100000px} api.anthropic.com LLM │ 253 req - + github.com 🔒 │ 2 req - + api.github.com 🔒 │ 1 req - + @@ -1759,7 +1759,7 @@ clipPath rect{width:100000px} main agent │ 1m 5.9s 91 - + @@ -1823,7 +1823,7 @@ clipPath rect{width:100000px} Audit the auth flow │ 3m 53s 73 - + @@ -1879,7 +1879,7 @@ clipPath rect{width:100000px} Review retry logic │ 3m 28s 87 - + @@ -1925,7 +1925,7 @@ clipPath rect{width:100000px} Check DB migrations │ 2m 1m 74 - + @@ -1970,7 +1970,7 @@ clipPath rect{width:100000px} Scan deps for CVEs │ 3m 5.4s 74 - + @@ -2018,7 +2018,7 @@ clipPath rect{width:100000px} Review docs and CI │ 2m 1m 83 - + @@ -2059,17 +2059,17 @@ clipPath rect{width:100000px} api.anthropic.com LLM │ 291 req - + api.github.com 🔒 │ 15 req - + github.com 🔒 │ 2 req -window 5m [all]09-15 42:24 → 09-15 42:24 +window 5m [all]09-15 42:24 → 09-15 42:24 - + @@ -2092,7 +2092,7 @@ clipPath rect{width:100000px} main agent │ 1m 5.9s 91 - + @@ -2152,7 +2152,7 @@ clipPath rect{width:100000px} Audit the auth flow │ 3m 57s 77 - + @@ -2204,7 +2204,7 @@ clipPath rect{width:100000px} Review retry logic │ 3m 32s 89 - + @@ -2259,7 +2259,7 @@ clipPath rect{width:100000px} Check DB migrations │ 3m 1m 76 - + @@ -2298,7 +2298,7 @@ clipPath rect{width:100000px} Scan deps for CVEs │ 3m 5.4s 83 - + @@ -2349,7 +2349,7 @@ clipPath rect{width:100000px} Review docs and CI │ 2m 1m 81 - + @@ -2393,12 +2393,12 @@ clipPath rect{width:100000px} api.anthropic.com LLM │ 308 req - + api.github.com 🔒 │ 15 req - + @@ -2423,7 +2423,7 @@ clipPath rect{width:100000px} main agent │ 1m 6.1s 94 - + @@ -2476,7 +2476,7 @@ clipPath rect{width:100000px} Audit the auth flow │ 4m 1m 78 - + @@ -2525,7 +2525,7 @@ clipPath rect{width:100000px} Review retry logic │ 4m 33s 94 - + @@ -2580,7 +2580,7 @@ clipPath rect{width:100000px} Check DB migrations │ 3m 1m 81 - + @@ -2610,7 +2610,7 @@ clipPath rect{width:100000px} Scan deps for CVEs │ 3m 5.4s 83 - + @@ -2653,7 +2653,7 @@ clipPath rect{width:100000px} Review docs and CI │ 3m 1m 78 - + @@ -2696,11 +2696,11 @@ clipPath rect{width:100000px} api.anthropic.com LLM │ 345 req - + api.github.com 🔒 │ 15 req - + @@ -2721,7 +2721,7 @@ clipPath rect{width:100000px} main agent │ 1m 6.1s 94 - + @@ -2779,7 +2779,7 @@ clipPath rect{width:100000px} Audit the auth flow │ 4m 1m 75 - + @@ -2832,7 +2832,7 @@ clipPath rect{width:100000px} Review retry logic │ 4m 54s 90 - + @@ -2882,7 +2882,7 @@ clipPath rect{width:100000px} Check DB migrations │ 4m 1m 80 - + @@ -2902,7 +2902,7 @@ clipPath rect{width:100000px} Scan deps for CVEs │ 3m 5.4s 83 - + @@ -2946,7 +2946,7 @@ clipPath rect{width:100000px} Review docs and CI │ 3m 1m 79 - + @@ -2990,15 +2990,15 @@ clipPath rect{width:100000px} api.anthropic.com LLM │ 378 req - + api.github.com 🔒 │ 15 req - + github.com 🔒 │ 2 req - + @@ -3019,7 +3019,7 @@ clipPath rect{width:100000px} main agent │ 1m 6.1s 94 - + @@ -3071,7 +3071,7 @@ clipPath rect{width:100000px} Audit the auth flow │ 5m 1m 73 - + @@ -3117,7 +3117,7 @@ clipPath rect{width:100000px} Review retry logic │ 5m 54s 96 - + @@ -3166,7 +3166,7 @@ clipPath rect{width:100000px} Check DB migrations │ 5m 1m 74 - + @@ -3187,7 +3187,7 @@ clipPath rect{width:100000px} Scan deps for CVEs │ 3m 5.4s 83 - + @@ -3233,7 +3233,7 @@ clipPath rect{width:100000px} Review docs and CI │ 4m 1m 79 - + @@ -3278,11 +3278,11 @@ clipPath rect{width:100000px} api.anthropic.com LLM │ 413 req - + api.github.com 🔒 │ 15 req - + @@ -3301,7 +3301,7 @@ clipPath rect{width:100000px} main agent │ 1m 6.3s 92 - + @@ -3347,7 +3347,7 @@ clipPath rect{width:100000px} Audit the auth flow │ 5m 1m 73 - + @@ -3381,7 +3381,7 @@ clipPath rect{width:100000px} Review retry logic │ 5m 54s 96 - + @@ -3441,7 +3441,7 @@ clipPath rect{width:100000px} Check DB migrations │ 5m 1m 71 - + @@ -3462,7 +3462,7 @@ clipPath rect{width:100000px} Scan deps for CVEs │ 3m 5.4s 83 - + @@ -3501,7 +3501,7 @@ clipPath rect{width:100000px} Review docs and CI │ 5m 1m 73 - + @@ -3551,11 +3551,11 @@ clipPath rect{width:100000px} api.anthropic.com LLM │ 442 req - + api.github.com 🔒 │ 15 req - + @@ -3574,7 +3574,7 @@ clipPath rect{width:100000px} main agent │ 1m 6.3s 92 - + @@ -3627,7 +3627,7 @@ clipPath rect{width:100000px} Audit the auth flow │ 6m 1m 75 - + @@ -3672,7 +3672,7 @@ clipPath rect{width:100000px} Review retry logic │ 5m 54s 96 - + @@ -3724,7 +3724,7 @@ clipPath rect{width:100000px} Check DB migrations │ 6m 1m 69 - + @@ -3742,7 +3742,7 @@ clipPath rect{width:100000px} Scan deps for CVEs │ 3m 5.4s 83 - + @@ -3783,7 +3783,7 @@ clipPath rect{width:100000px} Review docs and CI │ 5m 1m 77 - + @@ -3828,14 +3828,14 @@ clipPath rect{width:100000px} api.anthropic.com LLM │ 463 req - + api.github.com 🔒 │ 15 req - + github.com 🔒 │ 2 req - + @@ -3858,7 +3858,7 @@ clipPath rect{width:100000px} main agent │ 1m 6.6s 88 - + @@ -3906,7 +3906,7 @@ clipPath rect{width:100000px} Audit the auth flow │ 7m 1m 77 - + @@ -3942,7 +3942,7 @@ clipPath rect{width:100000px} Review retry logic │ 5m 54s 96 - + @@ -3981,7 +3981,7 @@ clipPath rect{width:100000px} Check DB migrations │ 6m 1m 75 - + @@ -3992,7 +3992,7 @@ clipPath rect{width:100000px} Scan deps for CVEs │ 3m 5.4s 83 - + @@ -4037,7 +4037,7 @@ clipPath rect{width:100000px} Review docs and CI │ 6m 1m 79 - + @@ -4084,13 +4084,13 @@ clipPath rect{width:100000px} api.anthropic.com LLM │ 483 req - + api.github.com 🔒 │ 15 req -12:24 42:24 42:24 42:24 42:24 +12:24 42:24 42:24 42:24 42:24 - + @@ -4113,7 +4113,7 @@ clipPath rect{width:100000px} main agent │ 1m 6.6s 88 - + @@ -4170,7 +4170,7 @@ clipPath rect{width:100000px} Audit the auth flow │ 7m 1m 79 - + @@ -4203,7 +4203,7 @@ clipPath rect{width:100000px} Review retry logic │ 5m 54s 96 - + @@ -4247,7 +4247,7 @@ clipPath rect{width:100000px} Check DB migrations │ 6m 1m 75 - + @@ -4258,7 +4258,7 @@ clipPath rect{width:100000px} Scan deps for CVEs │ 3m 5.4s 83 - + @@ -4301,7 +4301,7 @@ clipPath rect{width:100000px} Review docs and CI │ 7m 1m 77 - + @@ -4354,11 +4354,11 @@ clipPath rect{width:100000px} api.anthropic.com LLM │ 500 req - + api.github.com 🔒 │ 15 req - + @@ -4381,7 +4381,7 @@ clipPath rect{width:100000px} main agent │ 1m 6.6s 88 - + @@ -4442,7 +4442,7 @@ clipPath rect{width:100000px} Audit the auth flow │ 8m 1m 79 - + @@ -4470,7 +4470,7 @@ clipPath rect{width:100000px} Review retry logic │ 5m 54s 96 - + @@ -4504,7 +4504,7 @@ clipPath rect{width:100000px} Check DB migrations │ 6m 1m 75 - + @@ -4513,7 +4513,7 @@ clipPath rect{width:100000px} Scan deps for CVEs │ 3m 5.4s 83 - + @@ -4551,7 +4551,7 @@ clipPath rect{width:100000px} Review docs and CI │ 7m 1m 76 - + @@ -4603,11 +4603,11 @@ clipPath rect{width:100000px} api.anthropic.com LLM │ 517 req - + api.github.com 🔒 │ 15 req - + @@ -4629,7 +4629,7 @@ clipPath rect{width:100000px} main agent │ 1m 6.6s 88 - + @@ -4684,7 +4684,7 @@ clipPath rect{width:100000px} Audit the auth flow │ 8m 1m 79 - + @@ -4717,7 +4717,7 @@ clipPath rect{width:100000px} Review retry logic │ 5m 54s 96 - + @@ -4749,7 +4749,7 @@ clipPath rect{width:100000px} Check DB migrations │ 6m 1m 75 - + @@ -4760,7 +4760,7 @@ clipPath rect{width:100000px} Scan deps for CVEs │ 3m 5.4s 83 - + @@ -4798,7 +4798,7 @@ clipPath rect{width:100000px} Review docs and CI │ 8m 1m 85 - + @@ -4850,11 +4850,11 @@ clipPath rect{width:100000px} api.anthropic.com LLM │ 529 req - + api.github.com 🔒 │ 15 req - + @@ -4884,7 +4884,7 @@ clipPath rect{width:100000px} main agent │ 2m 7.6s 81 - + @@ -4941,7 +4941,7 @@ clipPath rect{width:100000px} Audit the auth flow │ 8m 1m 79 - + @@ -4966,7 +4966,7 @@ clipPath rect{width:100000px} Review retry logic │ 5m 54s 96 - + @@ -4989,7 +4989,7 @@ clipPath rect{width:100000px} Check DB migrations │ 6m 1m 75 - + @@ -5000,7 +5000,7 @@ clipPath rect{width:100000px} Scan deps for CVEs │ 3m 5.4s 83 - + @@ -5032,7 +5032,7 @@ clipPath rect{width:100000px} Review docs and CI │ 8m 1m 101 - + @@ -5082,228 +5082,254 @@ clipPath rect{width:100000px} api.anthropic.com LLM │ 533 req - + api.github.com 🔒 │ 16 req - + github.com 🔒 │ 2 req -agentop · http://127.0.0.1:9094 +agentop · http://127.0.0.1:9094 -LAST 1H~$15.03 · TODAY~$15.03 · 7 DAYS~$15.03 · THIS MONTH~$15.03 +LAST 1H~$15.03 · TODAY~$15.03 · 7 DAYS~$15.03 · THIS MONTH~$15.03 -SESSION TITLE UPDATED EVENTS TOKENS COST SAVED~CTX(1M) +SESSION TITLE UPDATED EVENTS TOKENS COST SAVED~CTX(1M) -api-7f3c audit the repo before release just now 1109 53.8M $14.46 $0.30▕▍ ▏ +api-7f3c audit the repo before release just now 1109 53.8M $14.46 $0.30▋░░░░░░ - -▌web-2a91add dark mode toggle 12m ago 10 49.3k $0.14 —▕▏▏ + +▌web-2a91add dark mode toggle 12m ago 10 49.3k $0.14 —▏░░░░░░ -infra-55de debug the helm chart 12m ago 2 16.2k $0.02 — ▕▏▏ +infra-55de debug the helm chart 12m ago 2 16.2k $0.02 —▏░░░░░░ - + - + - + - + - + - + - + - + - + - + - + - + - + -● connected12.4 events/sec feedback: https://github.com/rossoctl/cortex/issues/new/choose +● connected12.4 events/sec feedback: https://github.com/rossoctl/cortex/issues/new/choose - - - - - - - - - - ↑↓ nav ↵ drill u usage $ spend / search p pause P plugins ? keys q quit + + + + + + + + + + + + + + + + + + + ↑↓ nav ↵ drill u usage $ spend / search p pause P plugins ? keys q quit -agentop · add dark mode toggle (web-2a91) +agentop · add dark mode toggle (web-2a91) -# TIME DIR ACTION PLUGIN METHOD STATUS DURATIONHOST +# TIME DIR ACTION PLUGIN METHOD STATUS DURATIONHOST -1 42:24:24.24outobserve 2 plugins claude-opus-5 200 2.90s api.anthropic.com +1 42:24:24.24outobserve 2 plugins claude-opus-5 200 2.90s api.anthropic.com - -┗⚒ 42:24:24.24 Read ok 17.10s + +┗⚒42:24:24.24 Read ok 17.10s -2 42:24:24.24outobserve 2 plugins claude-opus-5 200 2.90s api.anthropic.com +2 42:24:24.24outobserve 2 plugins claude-opus-5 200 2.90s api.anthropic.com - -┗⚒ 42:24:24.24 Grep ok 17.10s + +┗⚒42:24:24.24 Grep ok 17.10s -3 42:24:24.24outobserve 2 plugins claude-opus-5 200 2.90s api.anthropic.com +3 42:24:24.24outobserve 2 plugins claude-opus-5 200 2.90s api.anthropic.com - -┗⚒ 42:24:24.24 Edit ok 17.10s + +┗⚒42:24:24.24 Edit ok 17.10s -4 42:24:24.24outobserve 2 plugins claude-opus-5 200 2.90s api.anthropic.com +4 42:24:24.24outobserve 2 plugins claude-opus-5 200 2.90s api.anthropic.com - -▌┗⚒42:24:24.24Bash ok 17.10s + +▌┗⚒42:24:24.24Bash ok 17.10s -5 42:24:24.24outobserve 2 plugins claude-opus-5 200 2.90s api.anthropic.com +5 42:24:24.24outobserve 2 plugins claude-opus-5 200 2.90s api.anthropic.com - - - - - - - -… s hide passthru/skip p pause / search esc back · → 3 more columns ( c to choose) ? keys q quit + + + + + + + + + + + + + + + +… s hide passthru/skip p pause / search esc back · → 3 more columns ( c to choose) ? keys q quit -agentop · add dark mode toggle (web-2a91) · event +agentop · add dark mode toggle (web-2a91) · event - + REQUEST │ #5 · claude-opus-5 · 200 · 2.90s · 11.6k→180 tok · $0.0280 -▾ ━━ REQUEST · 42:24:24.24 · observe inference-parser +▾ ━━ REQUEST · 42:24:24.24 · observe inference-parser -{ +{ -"at": "2026-09-22T42:24:24.242424-42:24", +"at": "2026-09-22T42:24:24.242424-42:24", -▾ "client": { +▾ "client": { -"name": "claude-code", +"name": "claude-code", -"raw": "claude-cli/2.1.323 (external, cli)", +"raw": "claude-cli/2.1.323 (external, cli)", -"version": "2.1.323" +"version": "2.1.323" -}, +}, -"direction": "outbound", +"direction": "outbound", -"host": "api.anthropic.com", +"host": "api.anthropic.com", -"httpMethod": "POST", +"httpMethod": "POST", -"httpPath": "/v1/messages", +"httpPath": "/v1/messages", -▾ "inference": { +▾ "inference": { -"agentRole": "main", +"agentRole": "main", -▾ "messages": [ +▾ "messages": [ -▸ 8 earlier messages · 1.4kB +▸ 8 earlier messages · 1.4kB -▾ { +▾ { -"content": "Running the tests to confirm the change holds.", +"content": "Running the tests to confirm the change holds.", -"role": "assistant", +"role": "assistant", -"toolCallNames": "Bash", +"toolCallNames": "Bash", -▾ "toolCalls": [ +▾ "toolCalls": [ -▌▾ { +▌▾ { -▾ "arguments": { +▾ "arguments": { -"command": "npm test -- Settings" +"command": "npm test -- Settings" -}, +}, -"id": "toolu_web_04", +"id": "toolu_web_04", -"name": "Bash" +"name": "Bash" -} +} - - - - - - - - - - ↑↓ move ↵ fold tab response y yank request u usage / search esc back ? keys q quit + + + + + + + + + + + + + + + + + + + ↑↓ move ↵ fold tab response y yank request u usage / search esc back ? keys q quit -"httpMethod": "POST", +"httpMethod": "POST", -"httpPath": "/v1/messages", +"httpPath": "/v1/messages", -▾ "inference": { +▾ "inference": { -"agentRole": "main", +"agentRole": "main", -▾ "messages": [ +▾ "messages": [ -▸ 8 earlier messages · 1.4kB +▸ 8 earlier messages · 1.4kB -▾ { +▾ { -"content": "Running the tests to confirm the change holds.", +"content": "Running the tests to confirm the change holds.", -"role": "assistant", +"role": "assistant", -"toolCallNames": "Bash", +"toolCallNames": "Bash", -▾ "toolCalls": [ +▾ "toolCalls": [ -▾ { +▾ { -▾ "arguments": { +▾ "arguments": { -"command": "npm test -- Settings" +"command": "npm test -- Settings" -}, +}, -"id": "toolu_web_04", +"id": "toolu_web_04", -"name": "Bash" +"name": "Bash" -} +} -] +] -}, +}, -▾ { +▾ { -"role": "user", +"role": "user", -▾ "toolResults": [ +▾ "toolResults": [ -▾ { +▾ { -"content": │ +"content": │ -PASS src/pages/Settings.test.tsx +PASS src/pages/Settings.test.tsx - ✓ toggles dark mode (31 ms) + ✓ toggles dark mode (31 ms) -▌ ✓ keeps the choice after reload (12 ms) +▌ ✓ keeps the choice after reload (12 ms) @@ -5427,10 +5453,10 @@ clipPath rect{width:100000px} ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── SESSION TITLE UPDATED EVENTS TOKENS COST SAVED~CTX(1M) -▌api-7f3caudit the repo before release just now 32 625.1k $0.47 $0.05▕▎ ▏ +▌api-7f3caudit the repo before release just now 32 625.1k $0.47 $0.05▍░░░░░░ -web-2a91 add dark mode toggle 1m ago 10 49.3k $0.14 — ▕▏▏ -infra-55de debug the helm chart 1m ago 2 16.2k $0.02 — ▕▏▏ +web-2a91 add dark mode toggle 1m ago 10 49.3k $0.14 —▏░░░░░░ +infra-55de debug the helm chart 1m ago 2 16.2k $0.02 —▏░░░░░░ @@ -5457,16 +5483,25 @@ clipPath rect{width:100000px} ● connected12.4 events/sec feedback: https://github.com/rossoctl/cortex/issues/new/choose - - - - - - - - - - ↑↓ nav ↵ drill u usage $ spend / search p pause P plugins ? keys q quit + + + + + + + + + + + + + + + + + + + ↑↓ nav ↵ drill u usage $ spend / search p pause P plugins ? keys q quit @@ -5492,8 +5527,6 @@ clipPath rect{width:100000px} - - @@ -5502,12 +5535,14 @@ clipPath rect{width:100000px} - + - + - + + + @@ -5523,10 +5558,6 @@ clipPath rect{width:100000px} - - - - @@ -5535,31 +5566,29 @@ clipPath rect{width:100000px} - + - + - + - + + + - + - - + + - + - + - + - - - - @@ -5568,31 +5597,29 @@ clipPath rect{width:100000px} - + - + - + - + + + - + - - + + - + - + - + - - - - @@ -5601,31 +5628,29 @@ clipPath rect{width:100000px} - + - + - + - + + + - + - - + + - + - + - + - - - - @@ -5634,31 +5659,29 @@ clipPath rect{width:100000px} - + - + - + - + + + - + - - + + - + - + - + - - - - @@ -5667,504 +5690,482 @@ clipPath rect{width:100000px} - + - + - + - + + + - + - - + + - + - + - + - - - - - + - + - + - + - + + + - + - - + + - + - + - + - - - - - + - + - + - + - + + + - + - - + + - + - + - + - - - - - + - + - + - + - + + + - + - - + + - + - + - + - - - - - + - + - + - + - + + + - + - - + + - + - + - + - - - - - + - + - + - + - + + + - + - - + + - + - + - + - - - - - + - + - + - + - + + + - + - - + + - + - + - + - - - - - + - + - + - + - + + + - + - - + + - + - + - + - - - - - - + + - + - + - + - + + + - + - - + + - + - + - + - - - - - - + + - + - + - + - + + + - + - - + + - + - + - + - - - - - - + + - + - + - + - + + + - + - - + + - + - + - + - - - - - - + + - + - + - + - + + + - + - - + + - + - + - + - - - - - - + + - + - + - + - + + + - + - - + + - + - + - + - - - - + + + + + - + + + + + + + + + - + - + - + - - - - - - - - - + + + + - - - - - - - - - + - + - + - + + + - + + + + - - - - - - + - + + + + + @@ -6190,18 +6191,18 @@ clipPath rect{width:100000px} + - - - - - - + - + + + + + @@ -6226,11 +6227,7 @@ clipPath rect{width:100000px} - - - - - - + + diff --git a/docs/getting-started.md b/docs/getting-started.md index 13c5aabf2..a7669648f 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -80,7 +80,7 @@ LAST 1H TODAY 7 DAYS MONTH default 1h ago 8 — — — — ● connected 2.1 events/sec feedback: https://github.com/rossoctl/cortex/issues/new/choose -[↑↓] nav [↵] drill [u] usage [$] spend [/] search [p] pause [P] plugins [?] keys [q] quit +[↵] drill [u] usage [$] spend [/] search [?] keys [q] quit ``` - The band `LAST 1H`, `TODAY`, `7 DAYS`, `MONTH` shows what your agents spent in each time span. diff --git a/docs/superpowers/plans/2026-11-19-tui-polish-2019.md b/docs/superpowers/plans/2026-11-19-tui-polish-2019.md new file mode 100644 index 000000000..68650e3e0 --- /dev/null +++ b/docs/superpowers/plans/2026-11-19-tui-polish-2019.md @@ -0,0 +1,242 @@ +# agentop: quieter rows, clearer panes and a shorter key bar (#2019) Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Make the important rows and numbers in agentop stand out, and make background traffic and general keys step back, with fewer words and fewer keys. + +**Architecture:** All work is in `cmd/agentop/tui` and the agentop docs. New colors go in `styles.go`. Table cells stay plain text: color comes from the `tui/table` cell-style hook (`CellStyleFunc func(r int, row Row, col int) lipgloss.Style`, already in `table/table.go:79`, so it already gets the row index). Chrome lines are styled after every cut or fit step, as #2015 does. + +**Tech Stack:** Go 1.26.10, Bubble Tea v1, Lip Gloss v1.1.0, `github.com/charmbracelet/x/ansi`, `github.com/muesli/termenv`. Add no dependency. + +**Spec:** issue #2019 (`gh issue view 2019 --repo rossoctl/cortex`). Read it in full before you start a task. Where this plan and the issue differ, the issue wins, except for the items under "Decisions". The mockups named in the issue are in `~/Documents/agentop-mockups/` (local files, read-only). + +## Global Constraints + +- The 8 rules of the issue's "Rules that stay from #2015" section apply to every task. In short: + 1. Never cut or pad a styled string with `runewidth.Truncate`, `runewidth.FillRight` or `len`. Style after those steps. `truncToWidth`, `ansi.Truncate` and `lipgloss.Width` may run after styling. + 2. Table cells keep no ANSI. Color is added inside `tui/table` through the cell-style hook. + 3. Search highlighting keeps working over every new style: match styles win, a marked row keeps its ink, the selected row keeps its tint. + 4. A cell style sets only foreground and bold. Never `Reverse` or `Background`. + 5. Each new color is a `lipgloss.AdaptiveColor` in `styles.go`. + 6. Under the Ascii profile (what `go test` gets), keys keep their brackets, and there is no bar, chip or selection mark. + 7. No regression of more than 10% in `BenchmarkRebuildEventsTable`, `BenchmarkRebuildEventsTableTrueColor` and `BenchmarkEventsTableView` (`tui/events_rebuild_bench_test.go`). + 8. The key grammar (`docs/superpowers/specs/2026-11-19-agentop-key-grammar-design.md`, `tui/key_grammar_test.go`) holds. A `[w]` hint shows the current value (`[w] 1h`). +- Each change has a test of the new look under a forced TrueColor profile, and the test checks the plain text with `ansi.Strip`. Use the profile helpers the #2015 tests use (for example `tui/cell_styles_test.go`, `tui/styles_test.go`). +- The `lipgloss.Width` of each line is the same under Ascii and TrueColor. +- Run Go commands from `cmd/agentop` with `GOWORK=off`. Always give `gofmt` a path (`gofmt -l .`). +- While you work: `scripts/dev/go-test-shards.sh -short cmd/agentop` (about 20 s) from the worktree root. The PR gate runs the full suite. +- Commits: `git commit -s`. End each message with `Assisted-By: Claude (Anthropic AI) `. No `Co-Authored-By`. +- Out of scope: everything in #2020 (part 2). Do not add: the title without the default URL, removal of the Usage pricing note, the server name in Events `HOST`. + +## Decisions (made here, with the reason) + +1. **PR split.** The estimate is about 2,210 counted lines, over 2,000. The issue says to split at change 6. So P1 has changes 1-5 (T1-T5) and P2 has changes 6-11 (T6-T11), stacked on P1. Reason: the issue names this split, and T6 and T11 need T3 and T5. +2. **Gauge (T1).** `contextGauge(promptTokens, width)` returns `tierBar(promptTokens, contextWindowTokens, width) + strings.Repeat("░", width-lipgloss.Width(bar))`. `width < 1` returns `""`. `promptTokens <= 0` returns `emptyCell`. Reason: `tierBar` (`spend_tiers.go:440`) already does the 8-step eighths and the "non-zero is never empty" rule. +3. **Gauge glyphs (T1).** Remove `'▕'` and `'▏'` from `tableGlyphs` and add `'░': styleDim`. The CTX column already has kind `cellAccent` (`sessionsCellKinds`), so the fill draws accent and the track draws dim. Delete the `shortcut:` comment about `▏`. +4. **Tool-row glyphs (T3).** Add `'┗'`, `'┣'`, `'⚒'` to `tableGlyphs` as `styleDim`. Draw the subagent `│` dim the same way: add `'│': styleDim`. The reviewer checked the base: the only table cell that holds `│` is the Events `DIR` column (`events_columns.go:253` and `:946`), so the glyph changes no other table, and an exchange row's `│` draws dim too (accepted). Reason: the glyph map is the #2015 way to draw a second ink in one cell. +5. **Bobcoins (T2).** In `styleBandAmount` (`spend_band.go:380`), an amount with no `$` is bold, and a trailing ` Bobcoins` word is `styleMuted`. `grep` found no other currency in `colorWarn` (`spend_drawer.go`, `spend_strip.go`, `usage_*.go` have none). The test keeps that true. +6. **Key bar (T4).** New palette: `colorBarBg {Light "#F3F4F6", Dark "#1F2937"}`, `colorBarChipBg {Light "#D1D5DB", Dark "#4B5563"}`, `colorBarChipFg {Light "#111827", Dark "#F9FAFB"}`. New helpers in `styles.go`: `renderKeyBar(fitted string, width int) string` and `renderTrailingKeyBar(fitted, keys string, width int) string`. Under Ascii they return exactly `renderHints(fitted)` / `renderTrailingHints(fitted, keys)`. With color, every run has `Background(colorBarBg)` (label text `colorMuted` on it, chips `colorBarChipFg` on `colorBarChipBg`), and the line is padded with bar-colored spaces to `width` (no pad when `width <= 0`). Use them only for the LAST line of the screen: `footer.go:40`, `footer.go:136`, and the Namespaces and Pods footers in `app.go` (about lines 2589 and 2614). Modal hint lines (`clear.go`, `server_picker.go`, `edit_overlay.go`, the help overlay foot) keep `renderHints`. Reason: the issue scopes the bar to the key-hint line. +7. **One-line legend (T5).** `legend()` returns exactly this plain text, swatch colors as today: `█ tools █ model █ retrying █ waiting on subagents █ waiting on you ┆ time cut from the axis ▁…█ requests in flight`. The fit width is `m.width`. When it does not fit, drop whole items from the right: first ` ▁…█ requests in flight`, then ` ┆ time cut from the axis`, then the swatch items one at a time from the right. Never wrap. `timelineFixedLines` 8 → 7 and `timelineLegendLines` 2 → 1. +8. **Idle cursor row (T5, T11).** `cursorStrip` with no moment picked returns `""`. The row stays (the `\n` is still written by `renderTimeline`). T11 then puts the `timelineStatus` notes there (see 11). +9. **Quiet predicate (T6).** `func rowQuiet(ctxs []cellContext, partner map[int]int, j int) bool { return eventInactive(ctxs[j].invs) && !partnerActive(ctxs, partner, j) }` in `events_blocks.go`. `rowInactiveHidden` becomes `m.hideInactive && rowQuiet(...)` in T6, and T7 deletes it. Tunnel rows need no special case: an unbridged CONNECT has no invocations, so `eventInactive` is true, and a gate deny on it makes it not quiet. Reason: the issue asks for ONE predicate. +10. **Quiet flags (T6).** Add `quiet bool` to `eventRow` and set it where the row loop renders an exchange row (`renderEventRow` in `rebuildEventsTable`). It is a field of the value in `m.visibleRows`, so `sortEventRows` moves it with its row. Add `eventRowQuiet` to `eventRowKind`, set from `m.visibleRows[i].quiet` where `kinds` is built (`events_pane.go:466`). Change the hook to `eventCellStyle(cols []eventColumn, kinds []eventRowKind, rows []table.Row) table.CellStyleFunc`. In a quiet row every cell is `styleMuted`, except: a STATUS whose `statusGroup` is `groupError` keeps `styleError`; `—` stays dim (`dashDim`); a cell in `colDir`, `colAction`, `colPlugin`, `colMethod` or `colHost` whose trimmed text equals the same column's trimmed text in row `r-1` is `styleDim`, but only when row `r-1` is also `eventRowQuiet`. Reason: a run reads as one block only when the rows touch, and the column ids come from `cols`, so the column picker cannot move the rule. +11. **Timeline header (T11).** One line: label column (26) + axis (exactly `lay.axis.width()` columns) + gutter (`" model tools tok/s"`, padded to `timelineGutterWidth`). + - Label column: `"window "` muted, then for each `offeredWindows` index one item: current = `styleSeg.Render(" "+label+" ")` with color, `"["+label+"]"` under Ascii; other = muted `" "+label+" "`. Pad to 26. Plain text with color: `window 5m 1h 24h all `. + - Axis: `func axisLabels(lay tlLayout) []axisLabel` places labels; `type axisLabel struct { cell int; text string; date int; bold bool }` where `cell` is the first column of `text`, `date` is the byte length of a leading `MM-DD ` date part (0 for none), and `bold` marks the two ends. `func renderAxisLine(labels []axisLabel, w int) string` styles them: `╷` dim, date muted, end times bold, other times muted, and returns exactly `w` columns. + - Order of placement: (a) start `╷` + `01-02 15:04` at cell 0; (b) finish `01-02 15:04` + `╷`, so the `╷` sits on cell `w-1`; (c) the gap-length and live-tail labels of today (no tick, centered as today); (d) middle times every 16 cells on non-gap cells, as `╷HH:MM`, with the date added (`╷01-02 HH:MM`) when its day differs from the day of the label placed before it. A label that touches or overlaps a placed one (keep today's one-cell gap) is dropped, never cut. + - Time format: `15:04`, or `15:04:05` when the window span is at most 10 minutes. Reason: today's axis uses seconds there, and 16-cell labels in a 5-minute window repeat the same minute otherwise. + - Narrow: if both dated ends do not fit with one blank cell between, use undated ends (`╷15:04`, `15:04╷`). If those do not fit, show only the undated start. If that does not fit, show nothing. + - `timelineStatus` returns only the notes (`oldest events not shown`, `refresh failed: …`, joined by ` · `), with no range. `cursorStrip` with no moment picked returns that text muted, or `""` when there is none. + - `timelineFixedLines` 7 → 5. +12. **Short ids (T8).** `sessionIDCell` returns the first 8 bytes of a session id (UUIDs are ASCII), no `…`. `default` and a pending bucket's agent name are not cut. `SESSION` is declared 8 wide, and the rebuild widens it to the widest cell of the listed sessions, counting ids as 8 (so `claude-code` gives 11). The `default` row is all `styleMuted` (Sessions cell style: a row whose id is `default`). Update the comments at `sessions_pane.go:37` ("SESSION is 12 at 97 columns and 14 from 100 up") and in `pending_bucket.go:31`. +13. **Key bar per pane (T9).** Remove only the general keys. New strings (`search` is `m.searchHints(m.pane)`): + - Sessions: `[↵] drill [u] usage [$] spend ` + search + (` [esc] agents` or ` [esc] pods` as today, else nothing) + ` [?] keys [q] quit`. + - Events: `[b/f] page [↵] detail [c] columns [u] usage ` + search + ` [esc] back` + the notices of today + ` [?] keys [q] quit`. (`[b/f]` stays: it is not a key a user guesses.) + - Detail: today's line without `[↑↓] move `. Pipeline: without `[↑↓] nav `. Plugin detail: without `[↑↓] scroll `. Timeline: without the `[↑↓] rows ` hint. Namespaces and Pods: without `[↑↓/jk] nav `. Agents: without `[↑↓] nav`, but the project label stays at the head of the line. Usage: no change. + - Every removed key keeps working, and the `?` help of that pane lists it. Add a help row where one is missing. +14. **Two-column help (T10).** `helpTwoColumnMinWidth = 115`: each column needs keyIndent 2 + key column 12 + gutter 2 + about 40 columns of description, so `2*56 + 3`. At a 140-column terminal the body is 134 wide (two columns). At 80 it is 74 (one column). Column width `colW = (width-3)/2`. Separator: `styleDim.Render(" │ ")`. Left: the pane's group (emphasized, as today) then GO TO ANOTHER PANE. Right: ANYWHERE, MOVING AROUND THIS HELP, INSIDE THE SPEND DRAWER (when `helpGlobalGroups` returns it), THE DRILL PATH. Pad each left line with `padRight` (it uses `lipgloss.Width`). The shorter column is padded with blank lines. EVERY PANE stays one column below, at full `width`. +15. **Live check and benchmark capture against the user's service** are for a human. See "For a human after review". + +## Review Focus + +1. A search on Events that matches a cell in a quiet row or a dim repeat: the match style wins, a marked row keeps its warn ink, the selected quiet row keeps its tint. Test in T6. +2. Events sorted by a column (`STATUS▼`) with quiet rows: the quiet flags and the dim repeats follow the sorted rows, not the arrival order. Test in T6. +3. The column picker hides `ACTION` and `PLUGIN`: the dim-repeat rule still keys by column id. Test in T6. +4. A `fitHintLine` cut that starts with `… ` on the shaded bar: the bar still covers the full width, the width is `m.width`, and no chip forms from a half bracket. Test in T4. +5. Help search (`/` in the `?` overlay) on a two-column body: a match in the right column is highlighted and `n` reaches it. Test in T10. + +## File map + +| File | Tasks | +|---|---| +| `cmd/agentop/tui/styles.go` | T1, T3, T4 | +| `cmd/agentop/tui/sessions_context.go`, `sessions_context_test.go` | T1 | +| `cmd/agentop/tui/spend_band.go`, `spend_band_test.go` | T2 | +| `cmd/agentop/tui/events_columns.go`, `events_cell_styles_test.go`, `events_tool_rows_test.go` | T3, T6 | +| `cmd/agentop/tui/footer.go`, `app.go` (picker footers), `footer_test.go` | T4 | +| `cmd/agentop/tui/timeline_pane.go`, `timeline_pane_test.go` | T5, T11 | +| `cmd/agentop/tui/events_pane.go`, `events_blocks.go`, `app.go` (model fields) | T6, T7 | +| `cmd/agentop/tui/keys.go` | T7, T9 | +| `cmd/agentop/tui/help_overlay.go`, `help_overlay_test.go` | T7, T9, T10 | +| `cmd/agentop/tui/sessions_pane.go`, `pending_bucket.go` and their tests | T8 | +| `docs/using-agentop.md`, `cmd/agentop/README.md` | T1, T7, T9 | +| `docs/superpowers/specs/2026-11-19-agentop-key-grammar-design.md` | T7 | + +--- + +### Task T1: Shaded-track context gauge (change 1) + +Depends on: none + +**Files:** `tui/sessions_context.go:123-155`, `tui/styles.go` (`tableGlyphs`), `tui/sessions_context_test.go` and any gauge test that pins `▕`/`▏`, `docs/using-agentop.md:44`, `cmd/agentop/README.md` (CTX section, `### How CTX is derived`). + +- [ ] Step 1: Write failing tests `TestContextGauge_ShadedTrack`: `contextGauge(500_000, 7) == "███▌░░░"`, `contextGauge(8_200, 7) == "▏░░░░░░"`, `contextGauge(1_000_000, 7) == "███████"`, `contextGauge(2_000_000, 7) == "███████"`, `contextGauge(0, 7) == emptyCell`, `lipgloss.Width` is 7 for every non-dash value, `contextGauge(5, 0) == ""`. And `TestSessionsGauge_TrueColorInk`: under TrueColor the rendered CTX cell has the fill in `colorAccent` and each `░` in `colorDim`, and `ansi.Strip` equals the plain gauge. +- [ ] Step 2: Run them. Expected: FAIL. +- [ ] Step 3: Implement Decisions 2 and 3. Rewrite the `contextGauge` comment: the author chose shaded blocks in #2019, the gap after a partial cell is accepted, and there is no "nearly full" color. Update the old gauge tests to the new text. +- [ ] Step 4: Change the sample `▕████ ▏` in `docs/using-agentop.md` to the 7-cell shaded form (`████░░░`), and the CTX text in `cmd/agentop/README.md` that names brackets. +- [ ] Step 5: Run `scripts/dev/go-test-shards.sh -short cmd/agentop`. Expected: PASS. Commit. + +### Task T2: Bobcoins are not yellow (change 2) + +Depends on: none + +**Files:** `tui/spend_band.go:360-398`, `tui/spend_band_test.go`. + +- [ ] Step 1: Write failing test `TestStyleBandValue_BobcoinsBoldNotWarn`: under TrueColor, `styleBandValue("12.40 Bobcoins")` contains `styleBold.Render("12.40")` and `styleMuted.Render(" Bobcoins")`, contains no `colorWarn` sequence, and `ansi.Strip` gives `12.40 Bobcoins`. Also `"~12.40 Bobcoins+"` keeps `~` and `+` dim. Add `TestNoCurrencyUsesWarn`: render the spend band, the spend drawer and the Usage cost view with a Bobcoins figure under TrueColor and assert that no output has the `colorWarn` foreground sequence. +- [ ] Step 2: Run. Expected: FAIL. +- [ ] Step 3: Implement Decision 5. Update the doc comments of `styleBandValue` and `styleBandAmount`. +- [ ] Step 4: Run the short shards. Expected: PASS. Commit. + +### Task T3: Tool rows step back (change 3) + +Depends on: none + +**Files:** `tui/events_columns.go:530-545` (`eventCellStyle`), `tui/styles.go` (remove `colorTool`, `styleTool`, add glyphs), `tui/events_tool_rows_test.go`, `tui/events_cell_styles_test.go`. + +- [ ] Step 1: Write failing test `TestEventCellStyle_ToolRowsMuted`: for a tool row, every non-empty cell is `styleMuted`; STATUS `ok` is muted; `running` and a DURATION starting with `⋯` are `styleWarn`; `lost`/`error` are `styleError`. Under TrueColor the drawn `┗⚒`/`┣⚒` and a subagent `│` carry the `colorDim` sequence. Check a tool row in search results and inside an open subagent block too. +- [ ] Step 2: Run. Expected: FAIL. +- [ ] Step 3: Implement Decision 4 and the rules above. Delete `colorTool` and `styleTool`. Their only users are `eventCellStyle` (`events_columns.go:537,540`) and `events_cell_styles_test.go`: change that test to expect `styleMuted`. +- [ ] Step 4: Run the short shards and the 3 benchmarks of Global Constraint 7 on the base commit and on HEAD (`GOWORK=off go test -run '^$' -bench 'RebuildEventsTable|EventsTableView' -count 6 ./tui/`). Expected: PASS, and no benchmark more than 10% slower. Commit. + +### Task T4: Full-width shaded key bar (change 4) + +Depends on: none + +**Files:** `tui/styles.go`, `tui/footer.go:40,136`, `tui/app.go` (Namespaces and Pods footers), `tui/footer_test.go`. + +- [ ] Step 1: Write failing tests `TestRenderKeyBar_FullWidthUnderColor`: under TrueColor, `lipgloss.Width(renderKeyBar(fitHintLine(h, 100), 100)) == 100`, every rune of the line has the `colorBarBg` background, chips have `colorBarChipBg` and `colorBarChipFg`, `strings.TrimRight(ansi.Strip(out), " ")` equals the chip form of the hint. `TestRenderKeyBar_AsciiUnchanged`: under Ascii the output equals `renderHints(fitted)`. A case with a `… ` cut and a half bracket (Review Focus 4). Run under both themes (`lipgloss.SetHasDarkBackground`). +- [ ] Step 2: Run. Expected: FAIL. +- [ ] Step 3: Implement Decision 6. The status line above does not change. +- [ ] Step 4: Run the short shards. Fix any test that compares the whole colored footer only where it checks the new background. Expected: PASS. Commit. + +### Task T5: One-line Timeline legend (change 5) + +Depends on: none + +**Files:** `tui/timeline_pane.go:410-440` (constants), `:770-785` (`legend`), `:959-963` (`cursorStrip`), `tui/timeline_pane_test.go`. + +- [ ] Step 1: Write failing tests: `TestTimelineLegend_OneLine` (`ansi.Strip(m.legend())` equals the Decision 7 text at a width of 200, has no `\n`, has no `tok/s`, no `in its colour`); `TestTimelineLegend_DropsFromTheRight` (at a width just under the full text the `▁…█` note is gone; narrower, the `┆` note is gone too; never wider than `m.width`, never two lines); `TestCursorStrip_IdleRowIsBlank` (with `cursor == -1` the row is present and empty, and the chart starts on the same line before and after `←`). Update the row-count tests for `timelineFixedLines` 7 and one legend line, and for nothing else. +- [ ] Step 2: Run. Expected: FAIL. +- [ ] Step 3: Implement Decisions 7 and 8. `legend()` gets the width it fits (`m.width`). Keep the `[←→]` footer hint and the `?` help text. +- [ ] Step 4: Run the short shards. Expected: PASS. Commit. + +### Task T6: Quiet background traffic (change 6) + +Depends on: T3 + +**Files:** `tui/events_blocks.go:105-111`, `tui/events_pane.go` (row loop, `kinds` at `:466`), `tui/events_columns.go` (`eventRowKind`, `eventCellStyle`), `tui/events_cell_styles_test.go`. + +**Interfaces:** Produces `rowQuiet(ctxs []cellContext, partner map[int]int, j int) bool` and `eventRow.quiet`, which T7 uses. + +- [ ] Step 1: Write failing tests: `TestRowQuiet` (no invocations → quiet; all skip → quiet; a shadow deny → not quiet; an inactive row with an active partner → not quiet; an unbridged tunnel row → quiet; a tunnel with a gate deny → not quiet). `TestEventCellStyle_QuietRows` under TrueColor: a quiet row is muted; a quiet row with STATUS 502 keeps `styleError`; in two adjacent quiet rows with the same HOST and METHOD, the second row's HOST and METHOD cells are `styleDim` and its TIME is muted; a non-quiet row between them stops the dim. `TestEventCellStyle_QuietFollowsSortAndColumns`: with `STATUS` sorted, and with `ACTION` and `PLUGIN` hidden in the column picker, the quiet ink and the dim repeats stay on the right rows and columns (Review Focus 2, 3). `TestQuietRows_SearchMatchWins` (Review Focus 1). +- [ ] Step 2: Run. Expected: FAIL. +- [ ] Step 3: Implement Decisions 9 and 10. +- [ ] Step 4: Run the short shards and the 3 benchmarks on the P1 tip and on HEAD (same command as T3). Expected: PASS, and no benchmark more than 10% slower. Commit. + +### Task T7: Remove the `s` toggle on Events (change 7) + +Depends on: T6 + +**Files:** `tui/app.go:651-660` (`hideInactive`, `hiddenInactive`), `tui/keys.go:495` (`case "s"`), `:1222-1247` (hints, `· N hidden`), `tui/events_blocks.go` (`rowInactiveHidden`, `collectSubagentBlocks`), `tui/events_pane.go` (row loop, comments), `tui/help_overlay.go:323`, tests that use `hideInactive`, `docs/using-agentop.md:161,245`, `cmd/agentop/README.md:566,865`, `docs/superpowers/specs/2026-11-19-agentop-key-grammar-design.md:35,76`. + +- [ ] Step 1: Write failing tests: `TestEventsS_DoesNothing` (press `s` on Events: the rows, the footer and the selected row are the same before and after); keep or add `TestColumnPicker_SSorts` (in the picker `s` still sorts). +- [ ] Step 2: Run. Expected: FAIL on the first. +- [ ] Step 3: Remove the fields, the key case, both hints, the hidden notice, `rowInactiveHidden` (the loops call nothing, every row renders), and the help row `{"s", "toggle passthru/skip rows"}`. Keep `eventInactive` and `rowQuiet`. Delete or rewrite the toggle tests. Fix the comments that name `hideInactive`. +- [ ] Step 4: Docs. `docs/using-agentop.md`: delete the line "`s` hides or shows the exchanges that no plugin acted on." and the Keys table row for `s` on Events. Add one line: rows where no plugin acted, and tunnel rows, show muted. `cmd/agentop/README.md`: delete the `s` row at line 865 and `[s] hide passthru/skip ` from the footer sample at 566. Key-grammar spec: change the `s` row of the Changes table to say that `s` on Events is removed (#2019) and that the column picker keeps `s` = sort. Line 76: drop the claim that `s` works on Events. +- [ ] Step 5: Run the short shards. Expected: PASS. Commit. + +### Task T8: Short session ids and wider titles (change 8) + +Depends on: none + +**Files:** `tui/sessions_pane.go:30-60` and the rebuild (`:270`, `:467`, `sessionsColumnsFor` at `:903`), `tui/pending_bucket.go:31-39`, `tui/sessions_rowid_test.go`, `tui/sessions_title_test.go`, `tui/pending_bucket_test.go`. + +- [ ] Step 1: Write failing tests: `TestSessionIDCell_EightChars` (`sessionIDCell("f0a50e1f-1234-…", w) == "f0a50e1f"`; `"default"` stays `"default"`); `TestSessionsTable_PendingBucketFullAgentName` (a bucket for `claude-code` shows `claude-code` and SESSION is 11 wide); `TestSessionsTable_TitleGetsFreedColumns` (at 140 columns with two agents listed so AGENT shows, TITLE is 30, it was 24); `TestSessionsTable_DefaultRowMuted` (TrueColor: every cell of the `default` row is muted); search and yank on a row still use the full id. Update the column-width tests that pin 14. +- [ ] Step 2: Run. Expected: FAIL. +- [ ] Step 3: Implement Decision 12. AGENT keeps `sessionsListTwoAgents`. Check `alignSessionsHeaders` and `growSessionsTitle` with the new width. +- [ ] Step 4: Run the short shards. Expected: PASS. Commit. + +### Task T9: A shorter key bar (change 9) + +Depends on: T7 + +**Files:** `tui/keys.go:1159-1374` (`helpView`), `tui/help_overlay.go` (`paneKeys` rows for removed hints), `tui/footer_fit_test.go` and tests that pin hint text, `cmd/agentop/README.md` (footer samples), `docs/using-agentop.md` (footer samples, if any). + +- [ ] Step 1: Write failing tests: `TestHelpView_SessionsShort` (`ansi.Strip` of the Sessions bar at 200 columns is `↵ drill u usage $ spend / search ? keys q quit` under TrueColor, and `[↵] drill [u] usage [$] spend [/] search [?] keys [q] quit` under Ascii); one test per changed pane for the Decision 13 string; `TestHelpOverlay_ListsRemovedKeys` (for each pane, each key removed from its bar is in that pane's `?` help). Keep `TestFitHintLine_KeepsQuitAndHelpAtEveryWidth` and `key_grammar_test.go` passing with no edit. +- [ ] Step 2: Run. Expected: FAIL. +- [ ] Step 3: Implement Decision 13. Keep the order "what must survive a narrow cut", and keep `[w]` with its value. Update the comments in `helpView` that explain removed hints (for example the `[P] plugins` placement note). +- [ ] Step 4: Update the footer samples in `cmd/agentop/README.md` and `docs/using-agentop.md` to the new strings. +- [ ] Step 5: Run the short shards. Expected: PASS. Commit. + +### Task T10: Help in two columns (change 10) + +Depends on: none + +**Files:** `tui/help_overlay.go:712-750` (`helpBodyLines`), `tui/help_overlay_test.go`. + +- [ ] Step 1: Write failing tests: `TestHelpBody_TwoColumnsAt140` (`helpBodyLines(paneSessions, 134)`: a line has the pane group's title on the left and `ANYWHERE` on the right with a `│` between; EVERY PANE is one column below); `TestHelpBody_OneColumnAt80` (width 74: no `│` separator, same order as today); `TestHelpBody_WrapsUnderDescription` (a long description in a column wraps to the description column, not the key column, and no line is wider than its column); `TestHelpBody_CurrentPaneEmphasis` (the pane group keeps `styleTitle`/`styleOK` under TrueColor); scroll still shows `[↑↓] scroll N%`; Review Focus 5. +- [ ] Step 2: Run. Expected: FAIL. +- [ ] Step 3: Implement Decision 14. `renderHelpOverlay` does not change. +- [ ] Step 4: Run the short shards. Expected: PASS. Commit. + +### Task T11: One Timeline header line with full start and finish (change 11) + +Depends on: T5 + +**Files:** `tui/timeline_pane.go:727-738` (header lines), `:787-840` (`timelineStatus`, `axisLabels`), `:959` (`cursorStrip`), `:410-420` (constants), `tui/timeline_pane_test.go`. + +**Interfaces:** Produces `axisLabels(lay tlLayout) []axisLabel`, `renderAxisLine(labels []axisLabel, w int) string` (Decision 11). + +- [ ] Step 1: Write failing tests: `TestAxisLabels_SameDay` (start `╷11-19 23:30` at cell 0, finish `11-19 23:59╷` with `╷` at cell `w-1`, middle labels `╷HH:MM`); `TestAxisLabels_AcrossMidnight` (the first label on the new day reads `╷11-20 00:01`); `TestAxisLabels_ThreeDays`; `TestAxisLabels_DropsOverlap` (a middle label that would touch the finish is dropped, no label is cut); `TestAxisLabels_NarrowUndated` (a width under 25 gives `╷23:30` and `00:30╷`); `TestAxisLabels_TickOnNamedCell` (each tick sits on the cell whose `from` is the label's time); `TestTimelineHeader_OneLine` (TrueColor: `ansi.Strip` of the line is `window 5m 1h 24h all ` padded to 26, the axis, then ` model tools tok/s`; the current window has the `styleSeg` background; Ascii shows `[1h]`; same `lipgloss.Width` in both); `TestTimelineStatus_OnIdleCursorRow` (with `Truncated` true and no moment picked, the cursor row reads `oldest events not shown`; with a moment picked, it shows that moment's tools). Update the row-count tests for `timelineFixedLines` 5, and for nothing else. +- [ ] Step 2: Run. Expected: FAIL. +- [ ] Step 3: Implement Decision 11. Delete the `from → to` range text and its line. +- [ ] Step 4: Run the short shards. Expected: PASS. Commit. + +## PRs + +Total about 2,210 counted lines: T1 110, T2 70, T3 110, T4 150, T5 170 (P1: 610); T6 260, T7 260, T8 140, T9 260, T10 260, T11 420 (P2: 1,600). Over 2,000, so two PRs, split where the issue says. + +| PR | Title | Parent | Tasks | estLines | +|---|---|---|---|---| +| P1 | `feat: Quiet agentop tool rows and Bobcoins, shade the key bar and shorten the Timeline legend` | "" | T1, T2, T3, T4, T5 | 610 | +| P2 | `feat: Quiet agentop background rows, drop the s toggle, shorten ids, keys and the Timeline header` | P1 | T6, T7, T8, T9, T10, T11 | 1600 | + +Order: P1 runs T1-T5 at the same time. P2 runs T6, T8, T10, T11 at the same time, then T7 after T6, then T9 after T7. + +## Gate + +From the worktree root: + +```sh +(cd cmd/agentop && GOWORK=off go vet ./... && test -z "$(gofmt -l .)" && GOWORK=off go test -race $(GOWORK=off go list ./... | grep -v 'agentop$')) && scripts/dev/go-test-shards.sh -race cmd/agentop && pre-commit run --from-ref 32085fa1ce566d47bef9ad840acc0f096e8d547a --to-ref HEAD +``` + +Gate check (plan review, on the unchanged base): `GOWORK=off go vet ./...` and `gofmt -l .` from `cmd/agentop` both pass. No change to how the gate is called. + +## For a human after review + +Live check (needs T1-T11, or T1-T5 for P1 alone). It drives agentop against the local Cortex service, so a person runs it: + +1. `cd cmd/agentop && GOWORK=off go build -o /tmp/agentop-2019 .` +2. With `expect`, open Sessions, Events, Timeline and the `?` help at 140×30 and 80×24 against `http://127.0.0.1:47601`. Capture each screen and compare it with the mockups in `~/Documents/agentop-mockups/` (`shade_ctx.html`, `ctx_compare.html`, `tool_rows.html`, `footer_bar.html`, `timeline_legend3.html`, `timeline_oneline.html`, `ideas.html`, `ideas2.html`, `ideas3.html`). Where the issue text and a mockup differ, the issue wins (for example, AGENT shows when two agents are listed). +3. Do not run `make dev-install` or restart the service. diff --git a/docs/superpowers/specs/2026-11-19-agentop-key-grammar-design.md b/docs/superpowers/specs/2026-11-19-agentop-key-grammar-design.md index 7772a786c..ff8468ccf 100644 --- a/docs/superpowers/specs/2026-11-19-agentop-key-grammar-design.md +++ b/docs/superpowers/specs/2026-11-19-agentop-key-grammar-design.md @@ -32,7 +32,7 @@ This is project 1 of 3: | Key | Today | After | |---|---|---| -| `s` | Global: toggles `hideInactive` from every pane | Events only. The column picker keeps `s` = sort | +| `s` | Global: toggles `hideInactive` from every pane | Removed on Events (#2019): rows where no plugin acted show muted. The column picker keeps `s` = sort | | `x` | Column picker: toggle a column (`space` also toggles) | Erase only. The column picker toggles with `space` only | | `w` | Footers show `[w] window` | Footers show the current value, for example `[w] 1h` | @@ -73,8 +73,8 @@ The `w` value sets stay as they are, because each one reads different data: - How the guard tests find the global cases (an AST walk or a table). - The exact exception list in guard test 1. -- Docs: `cmd/agentop/README.md` and `docs/using-agentop.md` must say that `s` works on - Events only, and that the column picker toggles with `space`. +- Docs: `cmd/agentop/README.md` and `docs/using-agentop.md` must say that the column + picker toggles with `space`, and sorts with `s`. ## Size diff --git a/docs/using-agentop.md b/docs/using-agentop.md index ef3b8e47e..e0a733c76 100644 --- a/docs/using-agentop.md +++ b/docs/using-agentop.md @@ -41,13 +41,13 @@ LAST 1H TODAY 7 DAYS MONTH $4.04 $18.80 $216.44 $703.18 ──────────────────────────────────────────────────────────────────────────────────────────────────── SESSION TITLE UPDATED EVENTS TOKENS COST SAVED~ CTX(1M) - ctx-abc-123-4… …pend-spans 3s ago 42 48.2k $0.12 $0.01 ▕████ ▏ - ctx-def-567-4… weather-ag… 18m ago 15 1.2k <$0.01 — ▕▏ ▏ - ctx-ghi-901-4… 42m ago 7 2.9k — — ▕██ ▏ + ctx-abc-123-4… …pend-spans 3s ago 42 48.2k $0.12 $0.01 ████░░░ + ctx-def-567-4… weather-ag… 18m ago 15 1.2k <$0.01 — ▏░░░░░░ + ctx-ghi-901-4… 42m ago 7 2.9k — — ██░░░░░ default 1h ago 8 — — — — ● connected 2.1 events/sec feedback: https://github.com/rossoctl/cortex/issues/new/choose -[↑↓] nav [↵] drill [u] usage [$] spend [/] search [p] pause [P] plugins [?] keys [q] quit +[↵] drill [u] usage [$] spend [/] search [?] keys [q] quit ``` The band at the top shows what your agents spent in each period: @@ -154,11 +154,11 @@ Some details: - The `STATUS` of a tunnel is the status of the connection, not the status of the destination. - A blank `STATUS` means that the response did not arrive yet. `lost` means that no response arrived in 10 minutes. - `—` in `ACTION` and `PLUGIN` means that no plugin acted on the row. +- Rows where no plugin acted, and tunnel rows, show muted. ### Keys on Events and Detail - `c` opens the column picker. In the picker, `space` shows or hides a column, and `s` sorts by the column. For example, sort by `DURATION` to find the slowest calls. -- `s` hides or shows the exchanges that no plugin acted on. Press `Enter` on an event to open the Detail pane. It shows the full request and the full response. @@ -242,7 +242,6 @@ When an agent still uses a session, its next request starts that session again. | `S` | On Agents, select the server for the new sessions of the agent. On Sessions, move the session to a different server | | `P` | Open the Pipeline pane | | `c` | On Events, open the column picker | -| `s` | On Events, hide or show the exchanges that no plugin acted on | | `y` | On Detail, write the event to a file | | `x` | On Sessions, erase the session. On Agents, erase the sessions of the agent, or all sessions on the *All agents* row | | `p` | Pause or resume the live stream |