Repository navigation
feat: add interactive CLI chat client with Bubble Tea v2 (#11) - #16
Conversation
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: ⛔ Files ignored due to path filters (1)
📒 Files selected for processing (7)
Cache: Disabled due to data retention organization setting Knowledge base: Disabled due to data retention organization setting 📝 WalkthroughWalkthroughImplements an interactive CLI chat client using Bubble Tea framework. Adds Charm.land dependency imports, creates a chat package with message primitives, UI model with state management and viewport rendering, style definitions, and integrates the feature as a new Cobra subcommand that fetches agent metadata and launches the terminal UI. Changes
Sequence DiagramsequenceDiagram
participant User as User
participant TeaModel as Bubble Tea Model
participant A2A as A2A Client
participant Agent as Agent
User->>TeaModel: Enter message + Enter key
TeaModel->>TeaModel: Set waiting=true<br/>Show "Thinking…" spinner
TeaModel->>A2A: sendMessage(user text)
A2A->>Agent: HTTP POST to agent URL
Agent-->>A2A: Markdown response
A2A-->>TeaModel: Return responseMsg with agent text
TeaModel->>TeaModel: Render with Glamour<br/>Append to message history<br/>Refresh viewport<br/>Set waiting=false
TeaModel->>User: Display updated chat + re-enable input
Estimated code review effort🎯 4 (Complex) | ⏱️ ~50 minutes 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 5
🧹 Nitpick comments (1)
docs/dev/2026-04-10-skill-to-configmap-plan.md (1)
54-106: Consider consolidating.PHONYdeclarations.The plan adds a
.PHONYdeclaration within the new ConfigMap section (line 57) and also updates the existing top-level.PHONYdeclaration (line 105). While multiple.PHONYdeclarations are valid in Makefiles, having both creates redundancy.♻️ Recommended approach
Choose one pattern:
Option 1 (cleaner): Remove the
.PHONYdeclaration from line 57 and only update the main declaration:# --- ConfigMap generation --- -.PHONY: configmap-gen configmap-apply - configmap-gen:Option 2 (if you prefer local declarations): Remove
configmap-gen configmap-applyfrom the main.PHONYupdate and keep only the local declaration at line 57.The codebase currently uses a centralized
.PHONYdeclaration (line 14), so Option 1 maintains consistency.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@docs/dev/2026-04-10-skill-to-configmap-plan.md` around lines 54 - 106, Remove the duplicate local .PHONY declaration inside the ConfigMap section and instead add the new targets to the existing top-level .PHONY list; specifically ensure the main .PHONY includes configmap-gen and configmap-apply and delete the .PHONY: configmap-gen configmap-apply declaration that appears near the ConfigMap recipe so there’s a single centralized .PHONY containing build test lint fmt clean image image-push configmap-gen configmap-apply.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@docs/dev/2026-04-10-cli-chat-client-plan.md`:
- Around line 43-48: Update the Charm module paths used in the docs and code to
match the project's go.mod and implementation: replace any occurrences of
github.com/charmbracelet/... with charm.land/.../v2 in the installation bash
block in docs/dev/2026-04-10-cli-chat-client-plan.md and in all import
statements used by the internal/chat package and related examples (the imports
referenced in the review). Ensure the examples and files that reference Bubble
Tea, Bubbles, Lipgloss or Glamour use the charm.land module paths with the v2
suffix so they compile against the current go.mod.
In `@docs/dev/2026-04-10-skill-to-configmap-plan.md`:
- Around line 54-92: configmap-gen and configmap-apply currently treat all files
as optional but must fail early if the required system-prompt.txt is missing;
add a validation in both the configmap-gen and configmap-apply targets (before
building CONFIG_FILES and before invoking kubectl) that checks [ -s
"$(CONFIG_DIR)/system-prompt.txt" ] and aborts with a clear Makefile error (use
$(error ...) or an exit with message) when the file is missing or empty so
ConfigMap generation/apply stops and surfaces the missing required file.
In `@internal/chat/model.go`:
- Around line 84-112: The viewport sizing currently assumes header/status/input
are one line; instead compute the actual rendered heights and widths for the
header (agentDescription), status text, and input line using the existing
renderer (m.renderer / glamour.NewTermRenderer) and the input component metrics,
then clamp the viewport width/height (m.viewport.SetWidth / SetHeight and
m.input.SetWidth) to m.width minus padding and m.height minus the measured
verticalMargin before applying; also regenerate or reuse the glamour renderer
with the final clamped width (glamour.WithWordWrap) so wrapping measurements are
consistent and avoid overlapping controls.
- Around line 179-183: Agent-controlled strings (m.agentName, m.agentDescription
and the agent response text rendered later around lines 221-233) are being
passed directly into Lip Gloss/Glamour rendering, allowing ANSI/OSC control
sequences to spoof the terminal. Before composing headerText and before
rendering any agent response, strip/normalize terminal escape and control
sequences (e.g., remove ANSI CSI/OSC/ESC sequences) using a reusable sanitizer
(e.g., stripANSI) and use the sanitized values in headerText,
headerStyle.Width(...).Render(...) and the agent response render calls so no raw
control sequences reach the terminal renderer.
In `@internal/cmd/chat.go`:
- Around line 39-46: The Agent Card's Skills field is discarded after
fetchAgentCard: when card is present you set agentName and agentDescription but
never pass card.Skills into the chat model; update the code that constructs the
model (chat.NewModel) to accept and be passed the card.Skills (or a skills
slice/metadata parameter) so the TUI can render advertised capabilities—locate
the fetchAgentCard call, the card variable, and the chat.NewModel invocation and
add a skills argument (or modify NewModel to accept a metadata struct containing
Name, Description, Skills) and wire card.Skills through.
---
Nitpick comments:
In `@docs/dev/2026-04-10-skill-to-configmap-plan.md`:
- Around line 54-106: Remove the duplicate local .PHONY declaration inside the
ConfigMap section and instead add the new targets to the existing top-level
.PHONY list; specifically ensure the main .PHONY includes configmap-gen and
configmap-apply and delete the .PHONY: configmap-gen configmap-apply declaration
that appears near the ConfigMap recipe so there’s a single centralized .PHONY
containing build test lint fmt clean image image-push configmap-gen
configmap-apply.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 0b67a8c6-777a-45c9-9787-725d65eef1e1
⛔ Files ignored due to path filters (1)
go.sumis excluded by!**/*.sum
📒 Files selected for processing (9)
docs/dev/2026-04-10-cli-chat-client-design.mddocs/dev/2026-04-10-cli-chat-client-plan.mddocs/dev/2026-04-10-skill-to-configmap-design.mddocs/dev/2026-04-10-skill-to-configmap-plan.mdgo.modinternal/chat/messages.gointernal/chat/model.gointernal/chat/styles.gointernal/cmd/chat.go
| case tea.WindowSizeMsg: | ||
| m.width = msg.Width | ||
| m.height = msg.Height | ||
|
|
||
| headerHeight := 1 | ||
| statusHeight := 1 | ||
| inputHeight := 1 | ||
| verticalMargin := headerHeight + statusHeight + inputHeight + 1 | ||
|
|
||
| if !m.ready { | ||
| m.viewport = viewport.New( | ||
| viewport.WithWidth(m.width), | ||
| viewport.WithHeight(m.height-verticalMargin), | ||
| ) | ||
| m.viewport.SoftWrap = true | ||
| m.ready = true | ||
| } else { | ||
| m.viewport.SetWidth(m.width) | ||
| m.viewport.SetHeight(m.height - verticalMargin) | ||
| } | ||
| m.input.SetWidth(m.width - 4) | ||
|
|
||
| // Re-create the glamour renderer with updated width. | ||
| if r, err := glamour.NewTermRenderer( | ||
| glamour.WithStandardStyle("dark"), | ||
| glamour.WithWordWrap(m.width-4), | ||
| ); err == nil { | ||
| m.renderer = r | ||
| } |
There was a problem hiding this comment.
Don't reserve a fixed four-row shell around variable-height content.
Lines 88-104 size the viewport as if header, status, and input are always one line, but Lines 179-192 can wrap the header (agentDescription), the status text, and the input line on narrow terminals. Once that happens, the viewport becomes too tall and the bottom controls start overlapping or disappearing. Measure the rendered heights and clamp m.width-4 / m.height-verticalMargin before applying them.
Also applies to: 179-192
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/chat/model.go` around lines 84 - 112, The viewport sizing currently
assumes header/status/input are one line; instead compute the actual rendered
heights and widths for the header (agentDescription), status text, and input
line using the existing renderer (m.renderer / glamour.NewTermRenderer) and the
input component metrics, then clamp the viewport width/height
(m.viewport.SetWidth / SetHeight and m.input.SetWidth) to m.width minus padding
and m.height minus the measured verticalMargin before applying; also regenerate
or reuse the glamour renderer with the final clamped width
(glamour.WithWordWrap) so wrapping measurements are consistent and avoid
overlapping controls.
| headerText := fmt.Sprintf(" %s Chat", m.agentName) | ||
| if m.agentDescription != "" { | ||
| headerText += " — " + m.agentDescription | ||
| } | ||
| header := headerStyle.Width(m.width).Render(headerText) |
There was a problem hiding this comment.
Sanitize agent-controlled text before rendering it in the terminal.
Lines 179-183 and 221-233 write Agent Card metadata and agent responses straight into Lip Gloss/Glamour output. Because chat connects to arbitrary agent URLs, a malicious agent can return ANSI/OSC control sequences that spoof the UI or manipulate the terminal session. Strip terminal escape/control sequences from those fields before formatting them.
Also applies to: 221-233
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/chat/model.go` around lines 179 - 183, Agent-controlled strings
(m.agentName, m.agentDescription and the agent response text rendered later
around lines 221-233) are being passed directly into Lip Gloss/Glamour
rendering, allowing ANSI/OSC control sequences to spoof the terminal. Before
composing headerText and before rendering any agent response, strip/normalize
terminal escape and control sequences (e.g., remove ANSI CSI/OSC/ESC sequences)
using a reusable sanitizer (e.g., stripANSI) and use the sanitized values in
headerText, headerStyle.Width(...).Render(...) and the agent response render
calls so no raw control sequences reach the terminal renderer.
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@internal/cmd/chat.go`:
- Around line 42-43: Replace the unstructured fmt.Fprintf warning in the chat
command with structured logging using log/slog: import "log/slog" (if not
already) and change the fmt.Fprintf(cmd.ErrOrStderr(), "Warning: could not fetch
agent card: %v\n", err) call in the chat command handler to a structured slog
call such as slog.Warn("could not fetch agent card", "error", err) so the
warning follows the repo's structured logging guideline.
- Around line 40-41: fetchAgentCard is using client.Get(...) with a nolint that
ignores cancellation, causing Ctrl+C to wait for the 10s timeout; update the
call site to pass cmd.Context() into fetchAgentCard and modify fetchAgentCard to
accept a ctx context.Context parameter and create the request with
http.NewRequestWithContext(ctx, ...) (or use client.Do with that request)
instead of client.Get so the HTTP call respects cancellation and returns
immediately on Ctrl+C. Ensure all callers of fetchAgentCard (e.g., where card,
err := fetchAgentCard(agentURL) is invoked) pass cmd.Context() and remove the
nolint on the previous client.Get usage.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: c26b4578-d8aa-4d12-adf1-4db68c470e1e
📒 Files selected for processing (4)
CLAUDE.mddocs/dev/2026-04-10-cli-chat-client-plan.mdinternal/chat/model.gointernal/cmd/chat.go
✅ Files skipped from review due to trivial changes (2)
- CLAUDE.md
- docs/dev/2026-04-10-cli-chat-client-plan.md
🚧 Files skipped from review as they are similar to previous changes (1)
- internal/chat/model.go
| card, err := fetchAgentCard(agentURL) | ||
| if err != nil { |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
cat -n internal/cmd/chat.go | head -100Repository: redhat-et/docsclaw
Length of output: 3116
🏁 Script executed:
# Check if context package is imported
rg "import \(" internal/cmd/chat.go -A 10Repository: redhat-et/docsclaw
Length of output: 220
Propagate command context into fetchAgentCard to ensure Ctrl+C remains responsive.
The function uses client.Get(...) with //nolint:noctx (line 76), which ignores context cancellation. When the user presses Ctrl+C, the request will block for up to 10 seconds instead of terminating immediately. Pass cmd.Context() down to fetchAgentCard and use http.NewRequestWithContext() to respect cancellation.
Proposed fix
import (
+ "context"
"encoding/json"
"fmt"
"net/http"
@@
- card, err := fetchAgentCard(agentURL)
+ card, err := fetchAgentCard(cmd.Context(), agentURL)
@@
-func fetchAgentCard(agentURL string) (*a2a.AgentCard, error) {
+func fetchAgentCard(ctx context.Context, agentURL string) (*a2a.AgentCard, error) {
@@
client := &http.Client{Timeout: 10 * time.Second}
- resp, err := client.Get(cardURL) //nolint:noctx // short-lived CLI request
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, cardURL, nil)
+ if err != nil {
+ return nil, fmt.Errorf("failed to create request: %w", err)
+ }
+ resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("HTTP request failed: %w", err)
}🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/cmd/chat.go` around lines 40 - 41, fetchAgentCard is using
client.Get(...) with a nolint that ignores cancellation, causing Ctrl+C to wait
for the 10s timeout; update the call site to pass cmd.Context() into
fetchAgentCard and modify fetchAgentCard to accept a ctx context.Context
parameter and create the request with http.NewRequestWithContext(ctx, ...) (or
use client.Do with that request) instead of client.Get so the HTTP call respects
cancellation and returns immediately on Ctrl+C. Ensure all callers of
fetchAgentCard (e.g., where card, err := fetchAgentCard(agentURL) is invoked)
pass cmd.Context() and remove the nolint on the previous client.Get usage.
| fmt.Fprintf(cmd.ErrOrStderr(), | ||
| "Warning: could not fetch agent card: %v\n", err) |
There was a problem hiding this comment.
Use slog for warning output instead of fmt.Fprintf.
Line 42 emits an unstructured warning; this breaks the repo logging rule and makes diagnostics harder to query.
Proposed fix
import (
"encoding/json"
"fmt"
+ "log/slog"
"net/http"
"strings"
"time"
@@
card, err := fetchAgentCard(agentURL)
if err != nil {
- fmt.Fprintf(cmd.ErrOrStderr(),
- "Warning: could not fetch agent card: %v\n", err)
+ logger := slog.New(slog.NewTextHandler(cmd.ErrOrStderr(), nil))
+ logger.Warn("could not fetch agent card", "agent_url", agentURL, "error", err)
} else {As per coding guidelines "**/*.go: Structured logging must use the log/slog package from the Go standard library".
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| fmt.Fprintf(cmd.ErrOrStderr(), | |
| "Warning: could not fetch agent card: %v\n", err) | |
| import ( | |
| "encoding/json" | |
| "fmt" | |
| "log/slog" | |
| "net/http" | |
| "strings" | |
| "time" | |
| ) | |
| // ... other code ... | |
| card, err := fetchAgentCard(agentURL) | |
| if err != nil { | |
| logger := slog.New(slog.NewTextHandler(cmd.ErrOrStderr(), nil)) | |
| logger.Warn("could not fetch agent card", "agent_url", agentURL, "error", err) | |
| } else { | |
| // ... rest of code ... | |
| } |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@internal/cmd/chat.go` around lines 42 - 43, Replace the unstructured
fmt.Fprintf warning in the chat command with structured logging using log/slog:
import "log/slog" (if not already) and change the fmt.Fprintf(cmd.ErrOrStderr(),
"Warning: could not fetch agent card: %v\n", err) call in the chat command
handler to a structured slog call such as slog.Warn("could not fetch agent
card", "error", err) so the warning follows the repo's structured logging
guideline.
Add a TUI chat client that connects to A2A agents for interactive conversations. Uses Bubble Tea v2, Bubbles v2, Lip Gloss v2, and Glamour v2 for the terminal UI with markdown rendering support. - internal/chat/styles.go: Lip Gloss style definitions - internal/chat/messages.go: chat message types - internal/chat/model.go: Bubble Tea model with viewport, text input, spinner, and async agent communication via bridge.A2AClient - internal/cmd/chat.go: Cobra subcommand with agent card discovery Usage: docsclaw chat --agent-url http://localhost:8080 Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Pavel Anni <[email protected]>
Add `docsclaw chat --agent-url URL` subcommand with: - Bubble Tea v2 TUI with viewport, text input, spinner - Agent Card fetch on connect (name, description, skills) - Glamour v2 Markdown rendering of agent responses - Async message sending via existing A2AClient bridge - --name flag to override agent display name Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Pavel Anni <[email protected]>
- Fix nil logger panic in A2AClient (pass slog.Default) - Add 120s HTTP timeout for agent requests - Add welcome message in empty chat viewport - Move agent description into TUI header (was invisible on stdout) - Add Error() method on errMsg type - Remove dead pre-connect output code Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Pavel Anni <[email protected]>
Focus() has a pointer receiver in bubbles v2, so calling it from Init() (value receiver) set focus on a discarded copy. Move focus to NewModel where we have a pointer, and use textinput.Blink for Init() to start cursor blinking. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Pavel Anni <[email protected]>
- Return textinput.Blink after responseMsg/errMsg so cursor reappears - Use discarding logger for A2AClient to prevent log output from corrupting the Bubble Tea TUI Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Pavel Anni <[email protected]>
The viewport content is only rebuilt on message events, so the spinner rendered inside it was frozen. Remove the duplicate spinner from the viewport and rely on the status bar spinner which redraws every frame. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Pavel Anni <[email protected]>
Replace the input line with the spinner and "Thinking..." text while waiting for a response. Uses agentLabelStyle (green) for visibility instead of the muted status bar color. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Pavel Anni <[email protected]>
Show Agent Card skills in the chat viewport on connect. Update CLAUDE.md project structure with internal/chat/ package. Fix outdated charmbracelet import paths in plan doc. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Pavel Anni <[email protected]>
cb4a480 to
6aa10b0
Compare
Summary
docsclaw chat --agent-url URL [--name NAME]subcommand--nameflag overrides agent display nameNew files
internal/chat/model.gointernal/chat/styles.gointernal/chat/messages.gointernal/cmd/chat.goKnown issues
Closes #11
Test plan
docsclaw chat --helpshows flags--nameflag overrides agent namemake build,make testpassSummary by CodeRabbit
New Features
chatcommand with automatic agent metadata and skills discoveryDocumentation