Repository navigation
feat: abctl — interactive TUI for session events - #372
Merged
Merged
Conversation
huang195
force-pushed
the
feat/abctl-tui
branch
2 times, most recently
from
May 5, 2026 21:58
0d5fa91 to
c58ebb5
Compare
PR rossoctl#371 added MarshalJSON for SessionEvent and String() for Direction and SessionPhase so the wire format uses readable strings. It did not add the matching Unmarshal side — so an off-process Go consumer trying to decode the same payload back into a SessionEvent failed with "cannot unmarshal string into Go struct field". First surfaced while writing the abctl apiclient. Fixing it here rather than shipping a client-side mirror struct so every future Go consumer of the API gets round-trippable types from authlib. - Direction: add MarshalJSON + UnmarshalJSON (string <-> enum). - SessionPhase: same. - SessionEvent: extract the wire layout into a shared sessionEventWire struct; Marshal writes to it, Unmarshal reads from it. durationMs <-> time.Duration symmetry is explicit. Unknown direction/phase strings decode to the zero-value member without error, keeping downstream consumers tolerant of future enum additions. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Hai Huang <[email protected]>
New internal package for the forthcoming abctl TUI. Sole owner of the :9094 wire protocol; the TUI only sees domain types. apiclient.Client - ListSessions(ctx) -> []session.SessionSummary - GetSession(ctx, id) -> *pipeline.SessionView (ErrNotFound on 404) apiclient.Stream - Stream(ctx, sessionFilter) -> <-chan StreamEvent - SSE parser (stdlib scanner; no dep) handling data:/event:/id: lines, ignoring ":" heartbeat comments, tolerating multi-line data values. - Exponential backoff reconnect: 1, 2, 4, 8, 16, 30, 30... forever until ctx is cancelled. Status transitions published on the same channel so the UI can render a "reconnecting in Ns (attempt N)" banner without a side-channel. - Channel close is the terminal signal; cancel ctx to drain. New module authbridge/cmd/abctl with its own go.mod (replace-directive to the local authlib). Registered in authbridge/go.work alongside the existing three modules. httptest-based coverage: list/get happy paths, 404 via ErrNotFound, multi-frame SSE parse, heartbeat-ignore, session-filter query, server- close triggers reconnect (asserts 2+ connects observed), ctx-cancel closes the channel, backoff schedule exact values up to cap. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Hai Huang <[email protected]>
Bubble Tea TUI for reading AuthBridge's session store over the session events API. Single binary, three panes, live streaming. Architecture: - tui/app.go — top-level model/update/view. Owns connection lifecycle (ctx + cancel), data caches, routing between panes. SSE events are delivered via a single long-lived channel; streamPump blocks on the channel for one message at a time and keeps all state mutation on the Tea event loop. Init fires the sessions fetch, opens the stream, and starts a 1 Hz tick for the events/s rate display. - tui/sessions_pane.go — sessions table with relative-time formatting and session-ID filter. Restores cursor after rebuild so live updates don't scroll the user's selection. - tui/events_pane.go — per-session event table with auto-follow at bottom. Substring filter matches across host, audience, method, identity fields, A2A parts, Inference completion, etc. - tui/detail_pane.go — pretty-printed JSON in a scrollable viewport; y yanks to /tmp/abctl-event-<ts>.json. - tui/keys.go — KeyMap dispatcher. Filter mode takes precedence. pane back-out: detail → events → sessions. - tui/styles.go / tui/footer.go — lipgloss palette and the connection/ rate/drops/flash status line. main.go wires --endpoint flag, installs SIGINT/SIGTERM handlers that cancel the tea context, calls tui.Run. Tests: end-to-end smoke that spins up a real sessionapi.Server + session.Store in-process, points apiclient at httptest, appends an event, asserts the model caches it. Three unit tests cover pane-back-out, pause toggle, and filter narrowing — they drive model.Update directly so no PTY is needed in CI. Bumped go.work's go directive to 1.24.2 (required by bubbletea/v1.3). Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Hai Huang <[email protected]>
…cation
Three abctl fixes found while testing against a live sidecar:
- 2 s ticker re-fetches /v1/sessions and drops cached events for
sessions the server no longer knows about. Without this, rekeys
("default" -> contextId) left stub sessions lingering in the TUI
forever. If the user was drilled into a session that vanished,
they're now sent back to the sessions pane instead of stranded.
- Explicit Selected + Header table styles. Default bubbles styling
was too subtle to see the cursor row at a glance; now it's
reverse-video with accent foreground.
- Inference events were classified as "mcp" because mcp-parser sets
MCPExtension on any JSON body that successfully parses as JSON-RPC,
including LLM request bodies with empty method. Prefer Inference
over MCP when both are populated; treat MCP-with-empty-method as a
false-positive. Upstream fix (skip set when method is empty) is a
parser-side follow-up.
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
Add introspection into the runtime plugin composition so off-process
tools (abctl TUI, operator dashboards, debugging scripts) can answer
"what's configured" without parsing the yaml.
- Pipeline gets a Plugins() accessor returning a defensive copy of the
slice. Tests assert round-trip + that mutating the returned slice
doesn't corrupt the backing store.
- sessionapi.Server gets a WithPipelines(inbound, outbound) option and
a GET /v1/pipeline handler. Response shape:
{inbound: [{name, direction, position, bodyAccess, writes, reads}, ...],
outbound: [...]}
A nil pipeline serializes as an empty array so UIs can always write
`for _, p := range body.Inbound` without a nil guard.
- main.go passes both pipelines through when constructing the server.
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
Makes the plugin pipeline browsable in abctl as a peer of the Sessions view. Tab toggles between Sessions and Pipeline; Enter drills into a single plugin's detail; Esc backs out. Matches the k9s pattern (top-level views that don't steal screen real estate from each other). - apiclient: new PipelineView / PipelinePlugin types + GetPipeline(ctx). - tui/pipeline_pane.go: plugins table with "#, DIRECTION, PLUGIN, WRITES, BODY, EVENTS" columns, divider row between inbound and outbound, live event-count attribution from the session cache. - tui/plugin_detail_pane.go: labelled plugin summary with activity count, and a note flagging per-plugin config as a follow-up (requires a Plugin.Config() addition to the Plugin interface). - tui/app.go: two new pane IDs (panePipeline, panePluginDetail), pipelineLoadedMsg fired from Init, tabs rendered in title strip, layout/goTop/goBottom updated for the new panes. - tui/keys.go: Tab cycles top-level peers, Enter on Pipeline drills to plugin detail, Esc backs out. Arrow-key navigation skips the "(app)" divider row cleanly. - tui/detail_pane.go: now colorizes event JSON via the new tui/json_colorize.go — keys in accent, strings green, numbers amber, booleans red, null muted italic. Round-trips through MarshalJSON so enum strings (direction, phase) stay human-readable. - tui/styles.go + tui/events_pane.go + tui/sessions_pane.go: share a tableStyles() helper that layers on DefaultStyles so cell padding survives (fixed the "PROTOMETHOD" alignment bug). Tests cover the new client GetPipeline. Existing tui tests untouched since the pipeline pane behaves as a peer — no regressions in the sessions/events flow. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Hai Huang <[email protected]>
Events and Pipeline tables now render protocol cells in distinct colors so operators can scan a dense session at a glance: a2a blue (user-facing inbound) mcp magenta (tool invocations) inference amber (LLM reasoning) blocked red (reserved for future guardrail plugins) The same palette applies to the Pipeline pane's plugin-name column (so e.g. mcp-parser renders in the same color its events do in the Events pane) and to the plugin detail header. A new protoStyle(proto) helper + pluginStyle(plugin) helper keep the palette centralized in styles.go. Plugins that don't write a protocol extension (jwt-validation, token-exchange) render in the default color so they visually recede. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Hai Huang <[email protected]>
…mit) Two issues surfaced during live testing: - Selected-row styling fought with per-cell protocol colors. Bubbles v1.0.0's Selected.Render wraps the whole row string; the inner \x1b[0m resets our styled cells emit clobber the outer selection style for everything after the first colored cell. Dropped the wrapping Selected style for the events table and added a dedicated 2-char leading indicator column (▸ for the cursor row, blank otherwise). Rebuild-on-cursor-move in keys.go keeps it in sync. - Worse: bubbles/table's renderRow calls runewidth.Truncate(value, col.Width, "…") which counts every byte of an ANSI escape as visible width. For a METHOD cell containing "message/stream" plus ~18 bytes of styling ANSI, the total runewidth (~32) exceeds the column width (22) — so the trailing \x1b[0m reset gets truncated off. The color stays "open" and bleeds into every subsequent cell and row until another escape happens by chance. Hence the "half one color, half another" effect users reported. No fix within bubbles v1. Reverted the per-cell method coloring with a detailed comment explaining the limitation. Bringing colors back here is tracked against a bubbles v2 upgrade (its table uses ANSI-aware truncation). Pipeline pane coloring stays because its column is wide enough for its known-short plugin names and there is nothing else styled in the row to fight with. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Hai Huang <[email protected]>
Two reverts in response to testing feedback: - Events pane: drop the manual ▶ indicator column and the rebuild-on-cursor-move plumbing. Per-cell METHOD coloring was already removed, so bubbles/table's wrapping Selected style works fine here too — use it, matching the Sessions and Pipeline panes. - Pipeline pane: same runewidth.Truncate issue that bit the events METHOD column also bleeds ANSI across plugin-name cells when names exceed ~10 visible chars. Revert plugin-name coloring + drop the pluginStyle helper. Plugin detail header also reverted to plain text. Both colorings stay blocked on the bubbles v2 upgrade (the v2 table uses ANSI-aware truncation). Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Hai Huang <[email protected]>
Two data-correctness bugs surfaced while reading abctl's event detail
pane against a live sidecar:
1) The request event for an outbound LLM call showed response-only
fields (completionTokens, finishReason, promptTokens, totalTokens).
The record helpers stored pctx.Extensions.Inference (and .MCP, and
.A2A) as a LIVE POINTER on the appended SessionEvent. When
OnResponse later mutated fields on the same struct (Completion,
FinishReason, tokens, Result, Err, SessionID on A2A), the
already-recorded request event's view was retroactively rewritten
to include the future response's data.
Fix: snapshot the extension structs at record time. Three small
helpers (snapshotA2A / snapshotMCP / snapshotInference) shallow-copy
the struct so each SessionEvent carries an independent view. Slice
fields are reused — they are assigned, not mutated in place, after
the parsers complete.
Regression tests assert this directly: record an outbound event,
mutate the live extension, then read back via Store.View and
assert the recorded event still reflects the request-phase state.
2) Every inference event carried an empty "mcp": {} shell. mcp-parser
runs before inference-parser in the outbound pipeline; on an OpenAI
chat/completions body (valid JSON but not JSON-RPC), json.Unmarshal
succeeded into a zero-value jsonRPCRequest and mcp-parser still set
pctx.Extensions.MCP{Method: ""}. Downstream, every inference event
inherited the phantom empty MCP extension.
Fix: skip MCP attachment when the unmarshalled method is empty. A
body that parses as JSON but has no "method" field is not a
JSON-RPC request.
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
The InferenceExtension used to store tools as just a list of names —
no descriptions, no parameter schemas. And response-side tool calls
were discarded entirely, so a finish_reason: tool_calls event had no
record of which tool the model chose or what arguments it sent. Both
matter for debugging prompt/tool mismatches and for any future
guardrail that wants to enforce tool-argument policies.
Replace Tools []string with Tools []InferenceTool{Name,
Description, Parameters}. Parameters is the raw JSON Schema object,
kept as map[string]any so no detail is lost.
Add ToolCalls []InferenceToolCall{ID, Name, Arguments} on the
response side. Arguments is kept as a string (the exact form the
model emitted) so malformed JSON from the model doesn't block capture.
Two additional request fields now surface:
- TopP *float64 (OpenAI top_p)
- ToolChoice any ("auto" | "none" | {type, function: {name}})
Updates to inferenceparser.go track these on OnRequest / OnResponse.
Tests cover parameters capture, tool-choice capture, top_p, and the
full two-tool-call response shape. Existing TestInferenceParser_WithTools
adjusted from string comparison to .Name.
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
Add TaskID, FinalStatus, Artifact, and ErrorMessage to A2AExtension. The a2a-parser OnResponse now parses both SSE streams (message/stream) and plain JSON-RPC responses (message/send) to extract: - Final status (completed/failed/canceled) - Artifact text (the agent's actual answer) - Error message (failure reason) - Task ID (for multi-turn correlation) This enables debugging agent behavior from session events without reading raw SSE streams. Session events now show what the agent said, not just that it responded with 200. Signed-off-by: Hai Huang <[email protected]> Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Hai Huang <[email protected]>
…dling
Brings the `feat/a2a-response-summary` work (TaskID, FinalStatus, Artifact,
ErrorMessage on A2AExtension + a2aparser OnResponse parsing) onto the abctl
PR so server and client agree on the wire format (previously the server
emitted tools as []string while the client expected []InferenceTool,
causing snapshot decode failures).
Also fixes three abctl bugs surfaced while testing:
- Detail pane now filters extension fields by event phase so request
rows show only request-side fields and response rows show only
response-side fields (inference/mcp/a2a); yank still writes the full
wire JSON via the raw detailEvent pointer.
- Long JSON strings wrap to the viewport width via ansi.Wrap instead
of running off-screen; re-wraps on terminal resize.
- Snapshot / pipeline fetch failures no longer flip the whole session
into connFailed — they flash the error instead, and when the app
does reach the failed state the footer now shows the error text.
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Hai Huang <[email protected]>
- apiclient: share one http.Transport between the 10s-timeout REST client and the no-timeout stream client so the idle-conn pool survives across reconnects instead of leaking a fresh Transport each time. - tui: yank uses os.CreateTemp (0600 by default) instead of os.WriteFile at 0o644. Session events carry identity subjects, raw LLM completions, and tool arguments - operator-only mode keeps them off shared hosts. - tui: trunc() now rune-aware so multi-byte titles don't get sliced mid-rune. truncStr stays byte-indexed (ASCII table cells) with a comment pointing at trunc if it ever needs multi-byte input. - pipeline: add SessionEvent JSON round-trip test. Marshal -> Unmarshal -> Marshal must produce byte-identical output; catches future fields added to MarshalJSON but missed in UnmarshalJSON, which would silently drop data on the client. - inferenceparser: tolerate malformed tool parameters (string / number / null where an object is expected). Tool name + description still land on the extension; Parameters decodes lazily via json.RawMessage and returns nil when the value is not a JSON object. Test locks it in. - a2aparser: SSE response parser now recognizes kind="artifact-update" (the shape current A2A SDKs emit on message/stream) alongside the legacy "artifact". Also fixed Part struct tags from "type" to "kind" across all response paths - spec and request-side parser both use "kind". Without this the artifact text was silently dropped. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Hai Huang <[email protected]>
The a2a-parser's OnResponse was unconditionally overwriting A2A.SessionID with the contextId extracted from the response body. Agents whose A2A SDK mints a fresh contextId per response (even when the client supplied one — legal per the A2A spec) caused the inbound response event to land in a different session bucket than its request, leaving orphaned 1-event sessions in abctl. Only capture the server-assigned contextId when the request didn't supply one. The request-side contextId is authoritative for telemetry bucketing. Signed-off-by: Hai Huang <[email protected]>
pdettori
approved these changes
May 6, 2026
pdettori
left a comment
Member
There was a problem hiding this comment.
Solid feature PR adding an interactive TUI for AuthBridge session observability. The authlib fixes (snapshot-at-record-time, MCP empty-method filter, enum JSON round-tripping) are correct and well-tested — the snapshot fix in particular prevents a real data corruption class where response-phase mutations retroactively rewrote request events. Test coverage is strong (~800 lines). SSE reconnect logic is clean with proper backoff (1s→30s cap, indefinite retry, no goroutine leaks on ctx cancel). The pipeline introspection endpoint handles nil gracefully.
Areas reviewed: Go (library + CLI/TUI), Tests, Config/Build, Docs
Commits: 11 commits, all signed-off ✓
CI status: All 17 checks passing ✓
- Extract `30 * time.Second` into a named `maxBackoff` constant so the reconnect cap is easy to find and tune without reading backoffSchedule. - Document that the `replace ../../authlib` in abctl's go.mod is workspace-only (resolved via authbridge/go.work) and would need to be removed if abctl is ever distributed as a standalone binary. Signed-off-by: Hai Huang <[email protected]>
TestHandleStream_SessionFilter_WorksOnOutboundMCP flaked on CI with "no data frame received within deadline". Passes 20x locally. The scanner races the SSE subscribe/append handoff on slow runners — 1s leaves no margin. 5s keeps the test fast on local hardware while giving CI a real budget to finish the handshake. Signed-off-by: Hai Huang <[email protected]>
The SSE handler flushed the initial ": ok" comment to the client before calling store.Subscribe(). A client that reacts quickly on ": ok" (or a test that Appends events immediately after reading it) could publish before the subscriber was registered, and those events were silently dropped. Swap the order: Subscribe first, then write ": ok". Any Append concurrent with the handshake is now either before Subscribe (fans out to no one, correct) or after (captured by sub). Signed-off-by: Hai Huang <[email protected]>
Reviewer pointed out two observability gaps where wire-format drift would cause data to vanish with zero signal: - SessionPhase / Direction UnmarshalJSON mapped every unknown string to the zero value. A server emitting "requset" or a new "internal" direction would silently show as request/inbound. Added slog.Debug on the unknown path so drift is at least observable in verbose test runs. - apiclient/sse.go parseSSE dropped malformed JSON frames silently; combined with the tolerant enum unmarshalers this is two layers of silent failure. Log at debug level with a truncated preview so a live-incident schema drift is diagnosable. No behavior change at default log level — Debug-only breadcrumbs. Signed-off-by: Hai Huang <[email protected]>
5 tasks done
3 of 9 tasks
boazdavid
added a commit
to boazdavid/cortex
that referenced
this pull request
Nov 24, 2026
…known, and fix a real regression in the zero-prompt-total gate Two more findings from clawgenti's re-review: - The currency fix only gated PluginSpendMicros (basis usd). PluginSpendUnknownMicros is "not money", but it is still one number, and a USD figure and a differently- priced currency's figure summed into it is just as mixed. Same gate now applies there. - The zero-prompt-total gate in InferenceParser.accountant asked whenever pctx.ReportedOps() was non-empty, reasoning that the pass before any data arrives has no ops either. That was wrong: a structural op (tool-prune's removal, say) reports during OnRequest, before the response exists, so that pass's ops list is not empty either — and asking there calls Host.Compute with an inference extension that is still all zeros, which Compute latches forever, so the real counts that arrive on a later pass are never priced at all. Reproduced by clawgenti; fixed by gating on pctx.StatusCode (set once, when the response is read) instead of on ReportedOps. Added a regression test pinning the exact two-pass sequence. Also dismissed the same 2 alerts' re-raised instances (rossoctl#365, rossoctl#370) after they shifted line following the rebase onto main — the earlier dismissal (rossoctl#372, rossoctl#373) stopped applying once that commit was superseded. Assisted-By: Claude Sonnet 5 <[email protected]> Signed-off-by: DAVID BOAZ <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
abctlis an interactive terminal UI (k9s-style) for AuthBridge's session store. It consumes the HTTP + SSE endpoints from PR #371 and renders three panes:yto yank to/tmp/abctl-event-<ts>.json.What is in this PR
authbridge/authlib/pipeline(small additions to the parent API)Direction.MarshalJSON+UnmarshalJSON; same forSessionPhase.SessionEvent.UnmarshalJSONpaired to the existingMarshalJSONso the wire form round-trips.Surfaced while writing the apiclient — decoding a
SessionEventback from JSON failed without symmetric Unmarshalers. Fixing in authlib rather than mirroring the types in the CLI.New module
authbridge/cmd/abctl/apiclient/— HTTP + SSE client.ListSessions,GetSession,Stream(ctx, sessionFilter). Auto-reconnect with exponential backoff (1s → 30s, capped). Status transitions published on the same channel as events so the UI renders a banner without a side-channel. Stdlib-only SSE parser (~100 lines).tui/— Bubble Tea model. Single long-lived SSE channel;streamPumpblocks for one message at a time so all state mutation stays on the Tea event loop.main.go—--endpointflag, SIGINT/SIGTERM→ctx-cancel wiring,tui.Run.Workspace:
authbridge/go.workgains./cmd/abctl; thegodirective bumps to 1.24.2 (required by bubbletea v1.3).Dependencies added (only in the new abctl module)
github.com/charmbracelet/bubbleteav1.3github.com/charmbracelet/bubblesv0.21github.com/charmbracelet/lipglossv1.2No clipboard dep —
ywrites to/tmpby design.Keybindings
↑ ↓/k jEnter/→/lEsc/←/h/py/tmp/abctl-event-<ts>.jsong/Gq/Ctrl+CTest plan
apiclientunit tests: list/get happy paths, 404 →ErrNotFound, multi-frame SSE, heartbeat ignored,?session=filter passed through, server-close triggers reconnect, ctx-cancel closes the channel, backoff schedule math.tuiend-to-end smoke: realsessionapi.Server+session.Storein-process; append an event server-side; pump through apiclient → model; assert model caches it.tuiunit tests: Esc back-out detail→events→sessions,ptoggles pause,/+ text + Enter narrows the sessions table.go build ./...produces a ~10 MB static binary.go test ./...across the workspace (authlib, authbridge, abctl) is clean.kubectl port-forward+curl /v1/sessions→ JSON decoded cleanly via the real apiclient.Trust model
Matches the server's: no authentication, payloads include raw user content. Use only against sidecars reachable via in-cluster networking or port-forward. See
authbridge/cmd/abctl/README.mdfor the full usage guide.Out of scope
atotto/clipboard)Identity.Subject == X)kubectl abctl weather-agent)Assisted-By: Claude (Anthropic AI) [email protected]