Repository navigation
Feat: Add a command line interface / terminal user interface to Kagenti - #835
Conversation
|
Converting to a draft. This is a HUGE pr. I want to ensure I step through it with people in a considerate way. |
Add oauth2.device.authorization.grant.enabled attribute to the kagenti Keycloak client configuration. This enables the device code flow used by CLI/TUI clients that cannot handle browser redirects directly. Assisted-By: Claude Opus 4.6 Signed-off-by: usize <[email protected]>
Adds a terminal UI built with Bubble Tea that connects to the existing Kagenti backend API. Features include: - REPL-style / command system with autocomplete - Status dashboard (connection, auth, agent/tool counts, dashboard links) - Agent and tool listing with navigable tables - Agent and tool detail views - Deploy agent/tool via interactive huh forms - SSE streaming chat with agents - Keycloak device-code login with PKCE and auto browser-open - Automatic token refresh on 401 with refresh_token persistence - Namespace switching - Configurable via file, env vars, or CLI flags The TUI is a standalone Go module at kagenti/tui/ with no Python dependencies. Build with `make build-tui` from the repo root. Closes rossoctl#775 Assisted-By: Claude Opus 4.6 Signed-off-by: usize <[email protected]>
Signed-off-by: usize <[email protected]>
Signed-off-by: usize <[email protected]>
Wire MCP tool selection and env var support into agent/tool deploy forms. Fix chat input not accepting spaces by handling tea.KeySpace separately from tea.KeyRunes, since bubbletea treats space as a distinct key type. Assisted-By: Claude Opus 4.6 Signed-off-by: usize <[email protected]>
Deploy agent form now offers OpenAI/Ollama presets that emit the correct env vars (with secretKeyRef for API keys) matching the environments ConfigMap. Deploy tool form gains a Log Level field. Agent and tool detail views show configured environment variables with sensitive values masked. Chat view adds debug trace panel (Ctrl+D) and streaming fixes. Assisted-By: Claude Opus 4.6 Signed-off-by: usize <[email protected]>
Assisted-By: Claude Opus 4.6 Signed-off-by: usize <[email protected]>
Move llmPresetEnvVars, parseExtraEnvVars, and openBrowser out of TUI views into a shared helpers package so both the interactive TUI and the upcoming non-interactive CLI can use them without duplicating logic. Assisted-By: Claude Opus 4.6 <[email protected]> Signed-off-by: usize <[email protected]>
Rewrite main.go to use cobra as the CLI framework. Running without a subcommand launches the interactive TUI (preserving existing behavior). Subcommands provide scripting-friendly access to all TUI capabilities: agents, tools, chat, deploy, delete, login/logout, status, and version. Assisted-By: Claude Opus 4.6 <[email protected]> Signed-off-by: usize <[email protected]>
Tests use httptest to mock the Kagenti API server and verify all CLI subcommands: agents list/detail, tools list/detail, chat streaming, deploy agent/tool, delete agent/tool, status (table and JSON), version, root help, and output formatting helpers. Also adds tests for the LLMPresetEnvVars and ParseEnvVars helper functions. Assisted-By: Claude Opus 4.6 <[email protected]> Signed-off-by: usize <[email protected]>
The session ID returned by the agent is now printed to stderr so users can pass it back via --session-id on subsequent calls. Output goes to stderr to keep stdout clean for piping response content. Note: session resumption depends on the agent implementing stateful context management — the CLI simply forwards the session ID in the request. Assisted-By: Claude Opus 4.6 <[email protected]> Signed-off-by: usize <[email protected]>
Phase 1 — API client tests (internal/api/client_test.go): - 401 token refresh: verifies retry with refreshed token, OnTokenRefresh callback, and POST body replay on retry - Refresh failures: table-driven tests for Keycloak 400, 500, and empty access token responses - No-refresh without config: verifies 401 is surfaced when Keycloak config is absent - SSE stream failures: dropped connection, malformed JSON recovery, and HTTP error status codes (500, 403, 404) - Timeout: verifies client surfaces timeout error on slow responses Phase 2 — Bubble Tea component tests: - CommandInput (internal/ui/components/commandinput_test.go): activate/ deactivate, typing and filtering, backspace, Esc, arrow navigation with wrapping, Tab completion (selected and single-match), Enter submit (typed and selected), space clears matches, args, inactive no-op, and View rendering - ChatView (internal/ui/views/views_test.go): stream accumulation, Done flushes buffer, chatStreamDoneMsg flushes, error stops streaming, debug events skipped, input ignored while streaming, input handling, history navigation, Ctrl+D toggles debug, and View state rendering - DeployAgentView: empty name validation, default form values, fallback namespaces, success navigation, error state, and View state rendering Assisted-By: Claude Opus 4.6 <[email protected]> Signed-off-by: usize <[email protected]>
Tests cover the App model's command dispatching, global navigation, and state management without making real network calls: - Command dispatch: table-driven tests for all 10 routable commands verifying correct ViewID transitions - Missing args: chat, agent, tool, deploy all set err when args absent - Unknown command: sets err with descriptive message - Esc navigation: returns to ViewHome from all 9 sub-views, no-op on Home - Slash activation: activates CommandInput on Home, ignored in Chat and deploy forms - Auth state: userFetchedMsg updates user, authOn, and bar.User; error leaves defaults unchanged - NavigateMsg: home, agent-detail, tool-detail all route correctly - WindowSizeMsg: updates width, height, and bar.Width - Logout: clears token, sets user to "guest", returns to Home - Namespace switch: updates client, bar, and returns to Home - Quit: both /quit command and Ctrl+C return tea.Quit Assisted-By: Claude Opus 4.6 <[email protected]> Signed-off-by: usize <[email protected]>
Tests the full LoginView state machine without making network calls or
opening a browser:
- Happy path: loading → authConfigLoaded → loading (waiting for device
code) → deviceCodeMsg → prompt → Enter → polling → loginCompleteMsg
→ done, with field assertions at each transition
- Disabled auth: authConfigLoaded with Enabled=false → disabled
- Error paths: auth config error, device code error, login complete
error all transition to "error" state with err set
- Terminal state navigation: Esc and Enter from done/error/disabled all
produce NavigateMsg{Target: "home"}
- Prompt ignores non-Enter keys
- Token persistence: loginCompleteMsg updates client token and refresh
token
- View rendering: all 6 states produce expected content strings
Also makes helpers.OpenBrowser a replaceable function variable so tests
can stub it out and avoid launching a real browser in CI.
Assisted-By: Claude Opus 4.6 <[email protected]>
Signed-off-by: usize <[email protected]>
Adds a parallel 'tui' job to the CI workflow that runs go vet, go test, and go build for the kagenti/tui module on every PR. Uses Go 1.23 with module cache via go.sum for fast dependency resolution. Assisted-By: Claude Opus 4.6 <[email protected]> Signed-off-by: usize <[email protected]>
The backend can return the protocol label as either a string ("a2a") or
an array (["a2a", "mcp"]). Add a FlexibleString type that accepts both
JSON forms, joining array elements with ", ". This fixes the
"cannot unmarshal array into Go struct field" error when listing tools.
Assisted-By: Claude Opus 4.6 <[email protected]>
Signed-off-by: usize <[email protected]>
…> label Signed-off-by: usize <[email protected]>
Delete agent/tool now asks for confirmation before proceeding. Pass -y/--yes to skip the prompt for scripting and CI use. Assisted-By: Claude Opus 4.6 <[email protected]> Signed-off-by: usize <[email protected]>
pdettori
left a comment
There was a problem hiding this comment.
Review Summary
This PR adds a comprehensive Go-based TUI and CLI for Kagenti (~6,700 lines across 52 files). The implementation is well-structured with Bubble Tea for the interactive TUI, Cobra for the CLI, Keycloak device-code auth with PKCE, and good test coverage. CI is all green. All 18 commits are signed-off.
Areas reviewed: Go, Python, CI, Docs, Security
Commits: 18 commits, all signed-off ✅
CI status: All automated checks passing ✅ (E2E HyperShift pending manual trigger)
Two must-fix items flagged below (data race on Token fields and StreamChat bypassing auth refresh). The remaining items are suggestions/nits.
🤖 Reviewed with Claude Code
| } | ||
|
|
||
| // SetToken updates the auth token. | ||
| func (c *Client) SetToken(token string) { |
There was a problem hiding this comment.
must-fix: Data race on Token/RefreshToken
SetToken() and SetRefreshToken() write to c.Token and c.RefreshToken without synchronization, while refreshAccessToken() protects writes with refreshMu. Meanwhile newRequest() reads c.Token without the mutex. If do() is ever called from multiple goroutines, this is a data race.
Options:
- Protect all reads/writes to Token/RefreshToken with the mutex (make them unexported, add
token()/setToken()methods that lock) - Document that Client is not goroutine-safe and ensure single-goroutine usage throughout
A common pattern for option 1: inside refreshAccessToken, after acquiring the lock, compare the current token to the one that triggered the 401 — if they differ, another goroutine already refreshed it.
|
|
||
| // StreamChat opens an SSE connection and sends events to the returned channel. | ||
| // The channel is closed when the stream ends or on error. | ||
| func (c *Client) StreamChat(namespace, name string, chatReq *ChatRequest) (<-chan ChatStreamEvent, error) { |
There was a problem hiding this comment.
must-fix: StreamChat bypasses auth refresh
This method creates a separate http.Client and builds the request via http.NewRequest directly instead of c.newRequest(). This skips the do() retry-on-401 logic entirely. If the access token expires before starting a stream, the user gets a raw 401 with no refresh attempt.
Suggestion: use c.newRequest() for header injection, and add at least a single refresh-retry before opening the stream (check for 401, call refreshAccessToken(), retry once).
| Long: "Kagenti is a cloud-native middleware platform for deploying and orchestrating AI agents.\nRun without a subcommand to launch the interactive TUI.", | ||
| // SilenceUsage prevents cobra from printing usage on every error. | ||
| SilenceUsage: true, | ||
| PersistentPreRunE: func(cmd *cobra.Command, args []string) error { |
There was a problem hiding this comment.
suggestion: Duplicated client initialization
PersistentPreRunE and RunE both independently create a client with identical config load → client creation → refresh token → OnTokenRefresh callback logic. If one is updated but not the other, they will drift. Consider extracting a newClientFromConfig(cfg *config.Config) *api.Client helper.
| if ns == "" { | ||
| ns = c.Namespace | ||
| } | ||
| url := c.apiURL(fmt.Sprintf("/agents?namespace=%s", ns)) |
There was a problem hiding this comment.
suggestion: Unescaped query parameter
fmt.Sprintf("/agents?namespace=%s", ns) does not URL-encode the namespace. Same pattern in tools.go. Use url.Values or url.QueryEscape() for safety:
q := url.Values{"namespace": {ns}}
url := c.apiURL("/agents?" + q.Encode())|
|
||
| // PollDeviceToken polls Keycloak's token endpoint for device code completion. | ||
| // It blocks until the user authorizes, the code expires, or an error occurs. | ||
| func (c *Client) PollDeviceToken(keycloakURL, realm, clientID, deviceCode, codeVerifier string, interval int) (*TokenResponse, error) { |
There was a problem hiding this comment.
suggestion: No cancellation in polling loop
PollDeviceToken loops with time.Sleep and has no context.Context parameter. An interrupted CLI (Ctrl+C) will not cancel the polling goroutine cleanly. Consider accepting a context.Context and using http.NewRequestWithContext.
|
|
||
| // Layer 1: config file | ||
| if data, err := os.ReadFile(configPath()); err == nil { | ||
| _ = yaml.Unmarshal(data, cfg) |
There was a problem hiding this comment.
suggestion: Silent unmarshal failure
When yaml.Unmarshal fails on a corrupted config file, the error is silently discarded and defaults are used. A warning log (or at minimum a comment explaining the intentional fallback) would help users debug config issues.
|
|
||
| // confirmDelete prompts the user to confirm a destructive action. | ||
| // Returns true if the user confirms or if yes is already set. | ||
| var confirmDelete = func(kind, name string) bool { |
There was a problem hiding this comment.
suggestion: Confirmation does not show namespace
The delete confirmation prompt shows only the resource name. For a destructive operation, consider including the target namespace so users know exactly what they are deleting:
Delete agent "my-agent" in namespace "team1"? [y/N]
| - name: Set up Go | ||
| uses: actions/setup-go@d35c59abb061a4a6fb18e82ac0862c26744d6ab5 # v5 | ||
| with: | ||
| go-version: '1.23' |
There was a problem hiding this comment.
nit: Consider go-version-file: kagenti/tui/go.mod instead of hardcoding '1.23' to keep the CI and module in sync. Also, Go 1.23 is EOL — worth bumping to 1.24.
Use url.Values to properly encode the namespace parameter in ListAgents and ListTools instead of raw string interpolation. Assisted-By: Claude Opus 4.6 <[email protected]> Signed-off-by: usize <[email protected]>
Accept a context.Context parameter so Ctrl+C in the CLI cleanly cancels the polling loop. Uses http.NewRequestWithContext for the HTTP calls and select on ctx.Done() for the sleep intervals. The TUI caller passes context.TODO() for now since Bubble Tea manages its own lifecycle. Assisted-By: Claude Opus 4.6 <[email protected]> Signed-off-by: usize <[email protected]>
Print a warning to stderr when yaml.Unmarshal fails on the config file so users can diagnose config issues instead of wondering why their settings are being ignored. Assisted-By: Claude Opus 4.6 <[email protected]> Signed-off-by: usize <[email protected]>
Go 1.23 is EOL. Bump go.mod to 1.24 and switch the CI workflow from a hardcoded go-version to go-version-file so the CI and module stay in sync automatically. Assisted-By: Claude Opus 4.6 <[email protected]> Signed-off-by: usize <[email protected]>
Replace Run+os.Exit(0) with RunE returning nil so the version command does not bypass deferred cleanup or break testability. Update the test to verify actual output. Assisted-By: Claude Opus 4.6 <[email protected]> Signed-off-by: usize <[email protected]>
Call Keycloak's revocation endpoint to invalidate the refresh token before clearing local config. If the server is unreachable, log a warning but still clear local tokens so logout always succeeds. Assisted-By: Claude Opus 4.6 <[email protected]> Signed-off-by: usize <[email protected]>
Add a Security Notes section covering token storage risks, file permissions, and recommended mitigations. Assisted-By: Claude Opus 4.6 <[email protected]> Signed-off-by: usize <[email protected]>
Apply url.PathEscape() to namespace and name values interpolated into URL paths. Prevents path traversal or query injection from names containing /, .., ?, or # characters. Assisted-By: Claude Opus 4.6 <[email protected]> Signed-off-by: usize <[email protected]>
Cap all io.ReadAll calls on server response bodies to 1 MB to prevent OOM from a malicious or misbehaving server. The request body read in do() is left unbounded since it reads our own payload. Assisted-By: Claude Opus 4.6 <[email protected]> Signed-off-by: usize <[email protected]>
Parse the URL and verify the scheme is http or https before passing it to the OS open command. Silently rejects file://, javascript:, and other schemes that could be injected via a compromised server response. Assisted-By: Claude Opus 4.6 <[email protected]> Signed-off-by: usize <[email protected]>
|
/run-e2e |
E2E HyperShift Tests PassedCommit: The If you push new commits, the label will be removed and you'll need to comment |
pdettori
left a comment
There was a problem hiding this comment.
Review Summary (Re-review)
This PR adds a well-structured Go TUI/CLI (~8,200 lines across 52 files) for Kagenti with Bubble Tea interactive mode and Cobra CLI subcommands. The author has thoroughly addressed the previous review's must-fix issues and added substantial security hardening.
Previous Must-Fix Issues — Resolved ✅
| Issue | Fix |
|---|---|
| Data race on Token/RefreshToken | tokenMu sync.RWMutex + accessor methods. refreshAccessToken uses stale-token comparison under lock to avoid redundant refreshes. |
| StreamChat bypasses auth refresh | Now uses c.newRequest() + single 401 retry with stale-token check before opening SSE stream. |
Additional Hardening (post-review commits)
url.PathEscape()on all URL path segments,url.Valuesfor query paramsio.LimitReader(resp.Body, 1 MB)on all response body reads- URL scheme validation before
OpenBrowser(rejectsfile://,javascript:, etc.) - Server-side token revocation via Keycloak
/revokeendpoint on logout context.ContextinPollDeviceTokenfor Ctrl+C cancellation- Config file parse warning instead of silent defaults fallback
- Token file written with
0600permissions os.Exit(0)removed from version command- Go bumped from 1.23 (EOL) to 1.24 with
go-version-filein CI - Delete commands require confirmation (
-y/--yesto skip)
Nits (non-blocking)
- Makefile: Missing newline at end of file.
kagenti/backend/app/routers/agents.py:PROTOCOL_LABEL_PREFIXimported inside function body — consider top-level import if no circular dependency concern.
Areas reviewed: Go (API client, CLI, TUI views, tests), Python, CI, Security, Docs
Commits: 31 commits, all signed-off ✅
CI status: All checks passing ✅ (E2E HyperShift pending manual trigger)
🤖 Reviewed with Claude Code
Add missing newline at end of Makefile. Remove redundant function-level import of PROTOCOL_LABEL_PREFIX that is already imported at module level. Assisted-By: Claude Opus 4.6 <[email protected]> Signed-off-by: usize <[email protected]>
New Commits DetectedThe New HEAD: For maintainers: Please review the new changes and comment Security checklistBefore running E2E tests, verify the PR does NOT contain:
This is an automated security measure to prevent TOCTOU attacks |
Re-scan: Code Review & Security Review (Post-Fix)Reviewer: Claude Code | Scope: Full updated diff (7899 additions, 51 files) Following up on the initial review. Re-scanned the updated diff to verify fixes. Fix Verification Summary
Remaining Items (Non-blocking, follow-up)
Updated Security Risk Rating: LowAll critical and important security findings have been addressed:
The remaining items are low-risk improvements suitable for follow-up work. 🤖 Generated with Claude Code |
Summary
Kagenti's UI now operates on an API backend. This creates the possibility for a variety of user interface experiences. It also opens the possibility of automating things like agent deployment and connection without the need for applying a k8s manifest.
To achieve that, here we introduce a single
kagenti-tuiwhich may operate in interactive or non-interactive modes. It allows for authentication via Oauth + KeyCloak. Because this authentication may persist between flows, it creates the possibility for simple automation.We may follow up with additional enhancements e.g., API keys to further enhance its utility for automation purposes.
Related issue(s)
Fixes #775
(Optional) Testing Instructions
cd kagenti/tui && make test