diff --git a/.agents/skills/charm-tui/SKILL.md b/.agents/skills/charm-tui/SKILL.md new file mode 100644 index 000000000..71dce4705 --- /dev/null +++ b/.agents/skills/charm-tui/SKILL.md @@ -0,0 +1,164 @@ +--- +name: charm-tui +description: Design, implement, review, and refine Go terminal interfaces using Charm's Bubble Tea, Bubbles, Lip Gloss, and Huh. Use for interactive CLIs, pickers, forms, dashboards, streaming views, keyboard/focus bugs, terminal layout, or Charm API migrations. Emphasizes behavior-preserving changes, terminal-native interaction, correct asynchronous state, and restrained visual design. Also use to decide whether a full-screen TUI is appropriate; do not add Charm to ordinary noninteractive Go commands without a need. +--- + +# Charm TUI craft + +Build a terminal tool that is easy to understand, quick to operate, and reliable under real input, data, and terminal conditions. Learn Charm's interaction and engineering practices, not just its palette. + +## Work from an example + +Open [Do by example](examples/WORKED-EXAMPLES.md) and choose the closest task before inventing a new pattern. Each task pairs a concrete user request with before/after code, the full implementation, a sequence to try, and a regression test. Use the example's mechanism; preserve the target application's contract. + +For a new picker, begin with [task 1](examples/WORKED-EXAMPLES.md#1-build-a-compact-picker). For an existing application, jump directly to [focus and modals](examples/WORKED-EXAMPLES.md#2-fix-search-keys-and-modal-fall-through), [cell-aware layout](examples/WORKED-EXAMPLES.md#3-fit-a-narrow-terminal-without-losing-identity), [async search](examples/WORKED-EXAMPLES.md#4-implement-latest-query-wins-search), [pipeline output](examples/WORKED-EXAMPLES.md#5-return-a-result-without-polluting-stdout), [stream anchors](examples/WORKED-EXAMPLES.md#6-keep-a-streaming-view-from-jumping), [subscription closure](examples/WORKED-EXAMPLES.md#7-stop-subscriptions-without-leaks-or-busy-loops), or [behavior-preserving reduction](examples/WORKED-EXAMPLES.md#8-reduce-code-without-redesigning-the-interface). + +### Example: fix the owner of a key, not the key + +Given “typing q in search quits,” do not remove the browse-mode q shortcut. In the key handler, route to the focused input before considering browse bindings. This is an excerpt from the [complete picker](examples/worked/cmd/picker/model.go); `k` is its mode-specific keymap: + +```go +if m.input.Focused() { + if key.Matches(msg, k.back, k.accept) { + m.input.Blur() + m.clampWindow() + return m, nil + } + return m, m.updateInput(msg) +} +``` + +The modal branch precedes this and consumes its key even when closing. The browse branch follows it. Keep `TestPrintableKeysBelongToSearch` and `TestModalEscapeDoesNotQuitOrReopen`, adapting their setup rather than merely repeating the rule. + +### Example: invalidate before waiting + +Given “old results flash during debounce,” change the generation when the query changes. Then test the precise race, using the state implementation from [the search program](examples/worked/cmd/search/request.go): + +```go +a := s.change("a") +s.begin(a.generation) +b := s.change("b") // B has not started yet. +if s.complete(a.generation, []string{"old"}, nil) { + t.Fatal("accepted an old result during the new debounce") +} +s.begin(b.generation) +``` + +The full example also cancels A's context, tags errors, rejects duplicate starts, and retains child input commands. The regression is in [request_test.go](examples/worked/cmd/search/request_test.go). + +### Example: preserve the allocated box width + +Given a 40-column dialog using Lip Gloss v2, with zero margins: + +```go +box := lipgloss.NewStyle().Border(lipgloss.NormalBorder()).Padding(0, 1) +outerWidth := 40 +innerWidth := outerWidth - box.GetHorizontalFrameSize() +content := ansi.Truncate(label, innerWidth, "…") +rendered := box.Width(outerWidth).Render(content) +``` + +Do not feed `innerWidth` back into `box.Width`: it already includes the internal frame. The [complete helper](examples/worked/internal/display/render.go) handles tiny widths by removing the frame, and the supplied rendering test measures actual output. Use cell-width assertions, not byte-length assertions. + +These example fragments are version-specific excerpts, not independent complete programs. The [three complete programs](examples/worked/README.md) supply imports, models, entry points, and tests. Read [verification](VERIFICATION.md) before repeating any claim that they were compiled or terminal-tested. + +## Start with the existing contract + +Before editing, inspect `go.mod`, the entry point, the root model, keybindings, styles, output handling, and relevant tests. Run the existing UI when possible. Record its main task, normal flow, cancellation behavior, output format, and supported environments. For a new tool, derive these from the user's request. + +Treat an existing interface as a contract. Preserve its keys, focus behavior, inline/full-screen mode, sizing, counters, custom visuals, and result semantics unless the requested change requires otherwise. Replacing a bespoke picker with a stock `bubbles/list` is not a behavior-preserving cleanup. Reuse component mechanics beneath the interface when useful. + +Identify the repository's actual Charm major versions. Do not paste v1 examples into v2 code, upgrade dependencies as incidental cleanup, or assume every Charm package uses the same module path. Read [versions and component selection](references/versions-and-components.md) when selecting libraries, writing version-sensitive code, or migrating. + +## Choose the smallest suitable surface + +| User's task | Starting point | +| --- | --- | +| Run once, return a value, integrate into scripts | Flags plus ordinary output; styling is optional | +| Pick, confirm, or enter a few values | Inline interaction; Huh for forms, Gum for shell composition | +| Browse, inspect, filter, or monitor repeatedly | Bubble Tea application with appropriate Bubbles | +| Read formatted prose | Glamour plus a viewport when scrolling is needed | +| Operate through SSH | A session-scoped TUI; investigate Wish only when remote interaction is actually required | + +These are choices, not mandatory layers. A command need not gain a configuration framework, router, event bus, or full-screen shell to become pleasant. Preserve the project's CLI conventions; use ordinary Go functions and structs before adding infrastructure. + +## Design the interaction before decorating it + +Write the primary flow in one sentence: “Filter candidates, inspect the current item, then accept or cancel.” Identify the first useful action and make it visible without opening help. + +Distinguish **focus** (which control receives input), **cursor** (which item is highlighted), **selection** (which IDs have been chosen), and **operation state** (what work is happening). Do not overload one field or one color with these meanings. + +Define loading, ready, empty, no-match, recoverable-error, and terminal-error states where applicable. Give each a truthful message and a useful next action. Preserve valid data during refresh when it remains useful; label it as refreshing or stale. Do not turn every transient failure into an empty screen. + +Use a compact hierarchy: task/context, primary content, local status, contextual controls. Start with the terminal's background, readable text, one accent role, a clear current-row marker, and quiet metadata. Add borders only where they clarify grouping. Personality can live in a title, status wording, or small animation; it must not displace content or obscure state. + +Do not impose a pink palette, rounded boxes, gradients, a large logo, or dashboard cards merely because the task mentions Charm. Read [design and interaction](references/design-and-interaction.md) for concrete patterns and tradeoffs. + +## Keep state ownership obvious + +The model's update path owns mutable UI state. Commands perform I/O or expensive work and return typed results. Rendering describes the current state; it does not initiate network requests, start timers, or secretly change the user's selection. + +Use either a small tree of independently useful components or one root model with simple imperative helpers. Both are legitimate. Extract a component when it owns a coherent interaction or lifecycle, not for every rectangle. A local state change does not need a command that sends a message back to the same model. + +When forwarding an event to a Bubbles component, retain both its returned model and command. Do not broadcast keystrokes to every child. Route non-input results to their owner even when that owner is not visible, when the lifecycle requires it. + +For asynchronous work: + +- Capture inputs before returning a command. Do not let the command read or mutate a live model, slice, or map concurrently. +- Cancel superseded work and tag results with a generation or operation ID. Invalidate the old generation **when intent changes**, not only when the next request starts. Ignore obsolete successes, failures, and completion flags. +- Use `tea.Batch` for independent work. Start result-dependent work from the matching result handler; command ordering is not a data dependency. +- Give timers, subscriptions, and workers an owner and a stop condition. Re-arm a one-shot subscription only once. Stop on channel closure. Bound backlog and work. + +Read [architecture and effects](references/architecture-and-effects.md) for the precise request lifecycle and streaming policy. The [search walkthrough](examples/WORKED-EXAMPLES.md#4-implement-latest-query-wins-search) wires this into an actual input model; the smaller [contract examples](examples/contracts/README.md) isolate the arithmetic/state rules. + +## Route input deliberately + +Set precedence explicitly: emergency/application-level controls, then the active modal or popup, then the focused control, then the current screen's unconsumed navigation keys. The exact interrupt policy is application-specific; document whether it cancels work, backs out, or exits. + +Printable characters belong to an active editor. Typing `q`, `j`, `k`, `/`, `?`, or space must not trigger unrelated navigation or quit. Preserve component editing, paste, cursor, and focus commands. Handle a modal's consumed key exactly once; closing it must not activate the item underneath. + +Use `key.Binding` and `help.Model` when appropriate so active controls and displayed help share definitions. Disable unavailable actions in both routing and help. Escape should unwind a visible interaction predictably; do not unexpectedly discard a draft. Restore focus after closing overlays. + +Keyboard operation must remain complete without a mouse. Mouse hit testing must use the same geometry as rendering. Keep ordinary terminal selection/copy practical; do not enable aggressive mouse capture without a use case. Do not silently take over the clipboard. + +## Treat layout as cell arithmetic + +Let the parent allocate bounds. Measure rendered headers, prompts, help, and status at the current width; subtract them from available space. Clamp derived dimensions. Keep margins, borders, padding, and child content separate. Never depend on a fixed “subtract 4” unless those four rows are a tested invariant. + +In **Lip Gloss v2**, `Width(n)` describes the block including borders and padding, before margins. Do not subtract a frame twice. Details and a worked example are in [layout and rendering](references/layout-and-rendering.md). + +Measure display cells with the relevant Lip Gloss/ANSI helpers, not `len`, byte slicing, or rune counts. Account for styled content, CJK, combining marks, emoji, tabs, prompts, and selection prefixes. A helper that preserves ANSI is not a security sanitizer. + +On narrow terminals, drop optional columns or switch composition before making the primary task unusable. Keep a compact safe view for extremely small dimensions and handle initial zero-size events. Reflow on width changes; clamp or preserve the scroll anchor intentionally. At ordinary sizes, controls should not jump as counts or status strings change. + +## Make output and lifecycle part of the UI + +For a pipeline-oriented command, reserve stdout for its machine-consumable result. Use stderr or an explicitly chosen terminal for interaction, and print the final result only after the UI has finished. Do not mix logging with a live renderer, even on stderr if that is the renderer's output. + +Define noninteractive behavior before opening a terminal. Do not hang CI waiting for a key. Distinguish accepted, cancelled, failed, and interrupted outcomes; cancellation must not accidentally emit a valid-looking selection. Respect existing exit-code conventions. + +Let the runtime restore terminal modes. Return through cleanup paths; avoid `os.Exit` before deferred cleanup. Use the runtime's supported handoff for an interactive child process instead of letting two programs read the same terminal. For SSH, keep model, theme/capability state, cancellation, and authentication boundaries session-scoped. + +Offer a plain or accessible path when relevant. No-color mode is not equivalent to screen-reader accessibility. Avoid reliance on a special font, animation, mouse, terminal graphics, or color alone. + +## Optimize the work, not the appearance of work + +First measure startup, keystroke-to-update responsiveness, rendering cost, allocations, and idle CPU for representative data. Keep inexpensive local filtering simple. Move expensive search/render work out of the update/render path when measurements justify it. + +For large lists, avoid formatting all rows just to display one viewport. Cache costly Markdown or highlighting with explicit data, width, and theme invalidation. Do not compute full-history height every frame merely to decide whether content overflows. A cache has a correctness contract and a memory cost; do not add one reflexively. + +For streams, coalesce redraws without silently dropping durable data. Follow new output only while the user is following the tail; reading older content must not be interrupted by incoming events. Bound history or make its retention policy explicit. + +## Verify the contract, then finish + +Read [testing and release](references/testing-and-release.md). At minimum test state transitions and command results, focus and modal routing, zero/one/many/no-match data, stale completion, resize, Unicode, and stdout separation. Include direct model tests; use the **matching-major** teatest package for integration where suitable. + +Inspect actual terminal output at a normal size and a small size. For existing UIs, compare before and after on the same input. Exercise paste, cancel, error recovery, repeated refresh, light/dark or explicit-theme behavior, and terminal restoration. Use deterministic snapshots or VHS recordings for appearance; they complement behavioral assertions, not replace them. + +Use [evaluation scenarios](evals/scenarios.json) as adversarial review prompts, selecting relevant cases. These are evaluation specifications, not a claim that the target application has passed. + +When delivering work, state the interaction preserved or changed, the implementation choices that mattered, the checks actually run, and any unverified terminal behavior. Distinguish source-reviewed, compiled, unit-tested, and terminal-tested. Do not claim polish from compilation alone. + +## Evidence and further reading + +The [case studies](references/case-studies.md) separate observed application behavior from recommendations, including a concrete example where implementation and maintainer notes disagree. The [source ledger](references/sources.md) records primary sources, inspected revisions, and scope. This skill is an independent synthesis, not an official Charm standard. diff --git a/.agents/skills/charm-tui/examples/WORKED-EXAMPLES.md b/.agents/skills/charm-tui/examples/WORKED-EXAMPLES.md new file mode 100644 index 000000000..8dc94eb1b --- /dev/null +++ b/.agents/skills/charm-tui/examples/WORKED-EXAMPLES.md @@ -0,0 +1,514 @@ +# Do by example: Charm TUIs + +These are worked tasks, not extra rules to memorize. Each starts with a request, shows the change to make, and gives a check that can disprove it. The code is original teaching code informed by the [case studies](../references/case-studies.md), not copied application code. + +Read the closest task, then open its complete source. Adapt the smallest relevant part to the target application's existing behavior. Do not replace a custom application with the demo. Main-loop and rendering APIs target the versions in [go.mod](worked/go.mod); check the target project's actual versions first. + +**Execution boundary:** 26 tests against the actual dependency-free demo source files were executed, including cancellation and ring-buffer logic. The Charm adapters and their additional tests are supplied but were not compiled or terminal-run here because the required toolchain/dependencies could not be downloaded. See [verification](../VERIFICATION.md). The screen samples below are expected compositions, not captured terminal output. + +| Task | Complete implementation | +| --- | --- | +| [1. Build a compact picker](#1-build-a-compact-picker) | [picker model](worked/cmd/picker/model.go) and [entry point](worked/cmd/picker/main.go) | +| [2. Fix search keys and modal fall-through](#2-fix-search-keys-and-modal-fall-through) | [routing](worked/cmd/picker/model.go) and [model tests](worked/cmd/picker/model_test.go) | +| [3. Fit a narrow terminal without losing identity](#3-fit-a-narrow-terminal-without-losing-identity) | [rendering helpers](worked/internal/display/render.go) and [bounds](worked/internal/display/bounds.go) | +| [4. Implement latest-query-wins search](#4-implement-latest-query-wins-search) | [request lifecycle](worked/cmd/search/request.go) and [Tea adapter](worked/cmd/search/model.go) | +| [5. Return a result without polluting stdout](#5-return-a-result-without-polluting-stdout) | [command boundary](worked/cmd/picker/main.go) and [result handling](worked/cmd/picker/selection.go) | +| [6. Keep a streaming view from jumping](#6-keep-a-streaming-view-from-jumping) | [ring history](worked/cmd/tail/history.go) and [view](worked/cmd/tail/model.go) | +| [7. Stop subscriptions without leaks or busy loops](#7-stop-subscriptions-without-leaks-or-busy-loops) | [producer/receive](worked/cmd/tail/stream.go) and [Tea adapter](worked/cmd/tail/model.go) | +| [8. Reduce code without redesigning the interface](#8-reduce-code-without-redesigning-the-interface) | [row renderer](worked/internal/display/render.go) and [render contracts](worked/internal/display/render_test.go) | + +## Run the examples + +From this skill's directory, in a terminal with a suitable Go toolchain and dependency access: + +```sh +cd examples/worked +go mod tidy +go test -race ./... +go vet ./... +go run ./cmd/picker +go run ./cmd/search +go run ./cmd/tail +``` + +Run each demo separately; exit the current one before starting the next. There are no API keys, servers, deployments, or network calls in the demos themselves. Initial Go dependency resolution does need network access. `go mod tidy` creates the missing `go.sum`; the first download was not possible during authoring. Commit it when adopting these examples. + +The picker and search are inline. The event monitor uses the alternate screen. The [demo README](worked/README.md) explains keys, scope, and the offline test command. + +## 1. Build a compact picker + +**Request:** “Let me pick a server. Keep it compact; return the server ID.” + +**Make this, not a dashboard.** Start with one root model, a text input, a plain collection of items, a current-row index, and a final outcome. The supplied picker has five demo servers and no deployment operation. Selecting a server only returns its ID. + +Expected composition at an ordinary width: + +```text +choose a server +/ filter servers +> development eu · ready + staging eu · ready + production eu · healthy + 東京 production jp · healthy + queue worker eu · busy + +5 matches +up up · down down · / search · enter choose · esc cancel · q quit +``` + +The precise spacing and help truncation depend on terminal width. The input placeholder is not a query. `>` indicates the current item, not a committed selection; there is no valid result until confirmation. + +**Build the identity model first.** Store `{ID, Label, Detail}` once. Filter to indexes into that collection. When filtering, preserve the current ID if it still exists; otherwise select the first match. Never return the filtered-list index or the styled label as an ID. Here is the actual filter implementation: + + +```go +func (s *selection) filter(query string) { + old, hadOld := s.current() + s.visible = nil + query = strings.ToLower(query) + for i, row := range s.items { + if strings.Contains(strings.ToLower(row.Label), query) { + s.visible = append(s.visible, i) + } + } + s.cursor = 0 + if hadOld { + for i, index := range s.visible { + if s.items[index].ID == old.ID { + s.cursor = i + break + } + } + } +} +``` + + +**Then connect the interaction.** In [model.go](worked/cmd/picker/model.go), `/` focuses the input; Escape or Enter returns to browsing without accepting anything; Enter while browsing opens a confirmation panel; Enter again commits the captured item. The root owns this routing. The input's returned command is always preserved. + +**Do it.** Run `go run ./cmd/picker`. Move to `production`, press `/`, type `prod`, then press Escape. The same `prod-eu` item should remain current even though its visible index changed. Enter twice should produce exactly `prod-eu` on stdout. Repeat with a query having no matches: Enter must not invent a selection. + +**Keep the test.** `TestFilterPreservesIdentity`, `TestDuplicateLabelsKeepDistinctIDs`, and `TestEmptyAndNoMatchesAreSafe` in [selection_test.go](worked/cmd/picker/selection_test.go) exercise this exact core code and passed offline. Add data replacement/sorting tests before adapting the example to a live catalog. Demo IDs are assumed unique; validate that at the application boundary for untrusted catalogs. + +**Adaptation limit.** This is a single-select picker. Adding multi-select requires a separate set of selected IDs, explicit output ordering, and help for the toggle action—not overloading the current-row index. + +## 2. Fix search keys and modal fall-through + +**Request:** “Typing `q` in my filter quits. Escape from a dialog also leaves the page.” + +A broken routing order often looks like this: + +```go +// Wrong inside the root key handler: it runs before focus is considered. +if msg.String() == "q" { + return m, tea.Quit +} +// ...only afterward does the editor receive the key. +``` + +**Move the ownership boundary, not the shortcut.** Keep `q` as the browse-mode quit key. First handle the explicit application interrupt. Next give a modal exclusive ownership. Next route editor keys. Only then process browse-mode actions. The actual picker modal branch is: + +```go +if m.confirm != nil { + switch msg.String() { + case "esc": + m.confirm = nil + case "enter": + m.result = outcome{Accepted: true, ID: m.confirm.ID} + return m, tea.Quit + } + return m, nil // The closing Escape is consumed here too. +} +``` + +A dialog that closes itself must still consume that event. Do not continue into the underlying list because `m.confirm` has become nil. + +The editor branch, also from the supplied root handler, is: + +```go +if m.input.Focused() { + if key.Matches(msg, k.back, k.accept) { + m.input.Blur() + m.clampWindow() + return m, nil + } + return m, m.updateInput(msg) +} +``` + +`k` comes from `m.keys()`, which changes both routing and help for the current mode. `m.updateInput` is not a placeholder; this is its complete implementation: + + +```go +func (m *model) updateInput(msg tea.Msg) tea.Cmd { + before := m.input.Value() + var cmd tea.Cmd + m.input, cmd = m.input.Update(msg) + if m.input.Value() != before { + m.list.filter(m.input.Value()) + m.clampWindow() + } + return cmd // Never lose child effects, including cursor or paste commands. +} +``` + + +Forward non-key child messages too: a paste result or cursor message does not necessarily arrive as a new keypress. The example uses a virtual cursor so it does not need real-cursor coordinate translation. With a real cursor, offset its coordinates by the rendered input's actual position. [API source](../references/sources.md#s17) + +**Prove it.** [model_test.go](worked/cmd/picker/model_test.go) supplies `TestPrintableKeysBelongToSearch` (types `qj/k? ` into a focused input) and `TestModalEscapeDoesNotQuitOrReopen` (asserts no command or acceptance after closing the panel). These Charm-dependent tests were authored but could not be executed here. Run them against your dependencies, then try bracketed paste and ordinary typing in your supported terminal. + +**Adaptation limit.** The demo only opens confirmation from browse mode, so focus is restored to the same blurred-input state. A dialog that can open from multiple controls must record and restore its previous focus owner; do not hardcode “focus editor” on close. + +## 3. Fit a narrow terminal without losing identity + +**Request:** “The last characters wrap inside my dialog, and the picker is unreadable when narrow.” + +**Repair the arithmetic first.** This is the full helper used by the demos: + + +```go +func Panel(content string, outerWidth int) string { + if outerWidth <= 0 { + return "" + } + box := lipgloss.NewStyle().Border(lipgloss.NormalBorder()).Padding(0, 1) + frame := box.GetHorizontalFrameSize() + if outerWidth <= frame { + return Line(strings.ReplaceAll(content, "\n", " "), outerWidth) + } + lines := strings.Split(content, "\n") + for i := range lines { + lines[i] = Line(lines[i], outerWidth-frame) + } + return box.Width(outerWidth).Render(strings.Join(lines, "\n")) +} +``` + + +For its zero-margin style, two border cells plus two padding cells consume four columns. At `outerWidth = 40`, text has 36 columns; the box still receives `Width(40)`. Calling `box.Width(36)` would subtract the frame twice. The narrow fallback removes the frame instead of drawing an oversized border around zero-width content. This is specifically the Lip Gloss v2 contract, not a rule to paste into a v1 project. [Width source](../references/sources.md#s03) + +**Then change composition before truncating identity.** The row helper keeps a two-column prefix in both states. At 48 columns and above it allocates a right-hand metadata column; below that it drops metadata. It clips by display cells using ANSI-aware helpers, after treating labels as plain data. [ANSI source](../references/sources.md#s17) + +Expected narrow composition: + +```text +choose a server +/ prod +> production + 東京 production + +2 matches +``` + +Do not produce this instead: + +```text +> product… eu · heal… + 東京 pr… jp · heal… +``` + +when dropping secondary metadata would allow the primary label to fit. Long identities may still require clipping; add an inspect view when users need the entire value before accepting. + +**Allocate visible rows.** `model.bodyHeight()` measures the help it will actually render; the two explicitly single-line header rows and the one status row are tested layout contracts. The parent computes the body budget, and the renderer iterates only over the returned visible range. The shared `Window` helper is deliberately for fixed-height rows, not variable-height Markdown messages. + +**Prove it.** [render_test.go](worked/internal/display/render_test.go) checks every width from 0 through 100 with ASCII, `東京サーバー`, combining accents, emoji, and long unbroken labels. It also asserts a 40-column panel actually measures 40 columns. Those Lip Gloss-dependent checks remain unexecuted here. The nonnegative bounds, visible-range invariants, and plain-text control neutralization tests did execute; do not confuse those with a terminal-width test. + +**Do it.** Resize the picker to 80×24, 24×8, and a deliberately tiny size. It should switch to one clipped “resize” line rather than panic, overflow the frame, or become impossible to cancel. Mouse targets, if later added, must use the very same geometry. + +## 4. Implement latest-query-wins search + +**Request:** “My typeahead sometimes shows the previous query's result while I am still typing.” + +**Reproduce this ordering explicitly:** + +```text +A starts → user types B → A completes → B's debounce expires → B starts +``` + +The important event is “user types B,” not “B starts.” In the demo, the query change is processed synchronously through `searchState.change`: + + +```go +func (s *searchState) change(query string) ticket { + s.generation++ // Invalidate A before B's debounce, not when B's I/O starts. + if s.cancel != nil { + s.cancel() + } + ctx, cancel := context.WithTimeout(s.root, 3*time.Second) + s.cancel = cancel + s.query = query + s.phase = waiting + s.rows = nil + s.err = nil + return ticket{ctx: ctx, generation: s.generation, query: query} +} +``` + + +Its immutable `ticket` contains the context, query, and generation. The timer and backend command receive that ticket; neither reads the live model. Superseding a query cancels its timer or I/O immediately, and the three-second context bounds the intent lifetime. The fake backend honors cancellation. A real backend must do the same or enforce its own concurrency limits. + +The command that calls the injected service is complete: + + +```go +func loadCmd(t ticket, search searchFunc) tea.Cmd { + // The closure captures values and a service, never the live model. + return func() tea.Msg { + rows, err := search(t.ctx, t.query) + return loadedMsg{generation: t.generation, rows: rows, err: err} + } +} +``` + + +`debounceMsg` is admitted only when its generation is current and its phase is waiting. `loadedMsg` is applied only when its generation is current and its phase is loading. Rejected results cannot change rows, errors, or the activity status. `ctrl+r` calls `change` even for identical query text, so a retry has fresh identity. The [full adapter](worked/cmd/search/model.go) handles all these messages and passes other events to the input. + +**Keep this deterministic regression, not a sleep-based hope:** + + +```go +func TestOldResultDuringNewDebounceIsRejected(t *testing.T) { + s := stateForTest(t) + a := s.change("a") + if !s.begin(a.generation) { + t.Fatal("A did not start") + } + b := s.change("b") // B has NOT started I/O yet. + if a.ctx.Err() != context.Canceled { + t.Fatal("A wasn't cancelled immediately") + } + if s.complete(a.generation, []string{"old"}, nil) || s.phase != waiting || len(s.rows) != 0 { + t.Fatal("A leaked through debounce") + } + if !s.begin(b.generation) || !s.complete(b.generation, []string{"fresh"}, nil) { + t.Fatal("B rejected") + } + if s.rows[0] != "fresh" { + t.Fatal("wrong rows") + } +} +``` + + +This test operates on the exact state implementation used by the demo, and passed. [request_test.go](worked/cmd/search/request_test.go) also checks stale errors, duplicate debounce admission, completion ownership, same-query retry, shutdown, and prompt cancellation of the timer/backend. [model_test.go](worked/cmd/search/model_test.go) adds adapter-level checks; these require Charm and remain unexecuted here. + +**Do it.** Run `go run ./cmd/search`. Type `slow`, wait until “searching…” is visible, then edit to `queue`. The old answer must not flash during the new debounce. Enter `error` to exercise the recoverable error state; `ctrl+r` retries but deliberately fails again until the query changes. No network service or API key is involved. + +**Adaptation limit.** This is read-only search, not a write-cancellation protocol. A dismissed dialog does not prove that a server cancelled a submitted deployment or payment. Use durable operation identity and reconciliation for writes. + +## 5. Return a result without polluting stdout + +**Request:** “I need to capture the choice in a script, but the UI's escape sequences end up in the value.” + +The broken approach writes the interface or progress messages to stdout, then returns the currently highlighted item even after cancellation. Repair both boundaries. + +**Choose the streams before starting the UI:** + +```go +// main.go: stdout may be piped, but the demo requires terminal stdin/stderr. +final, err := tea.NewProgram( + newModel(servers), + tea.WithInput(os.Stdin), + tea.WithOutput(os.Stderr), +).Run() +``` + +Do not add logging to that same stderr while the renderer owns it. Print diagnostics after `Run` returns or use a separate log file. The example does not silently open `/dev/tty`; unattended use must choose `--id` or `--list` instead. The terminal check happens before launching the program. [Terminal API source](../references/sources.md#s17) + +**Only the final outcome may produce a result:** + + +```go +func finish(w io.Writer, result outcome) (int, error) { + if result.Interrupted { + return 130, nil + } + if !result.Accepted { + return 1, nil + } + if result.ID == "" { + return 2, fmt.Errorf("accepted result has no ID") + } + if _, err := fmt.Fprintln(w, result.ID); err != nil { + return 2, err + } + return 0, nil +} +``` + + +`finish` is called after the runtime has released the terminal. The ID comes from an accepted outcome, never from `cursor`. The demo uses explicit exit codes; retain your existing application's conventions rather than imposing these codes during cleanup. + +**Do it, without any terminal interaction:** + +```sh +go build -o picker ./cmd/picker +./picker --list +./picker --id prod-eu +``` + +The last command must output exactly: + +```text +prod-eu +``` + +In Nushell, an ordinary capture is: + +```nu +let server = (./picker --id prod-eu | str trim) +``` + +For interactive capture, omit `--id` while leaving terminal stdin and stderr available. Cancel and confirm in separate runs; cancellation must not return a valid-looking server ID. Reject invalid `--id` values before starting the TUI. + +**Prove it.** `TestFinishNeverLeaksCancelledSelection` and `TestFinishReportsWriteAndInvalidResult` in [selection_test.go](worked/cmd/picker/selection_test.go) passed against the actual result function. They assert exact bytes, cancellation, keyboard-interrupt precedence, empty-ID rejection, and write-error propagation. The entry point's actual descriptor behavior still needs terminal testing. + +**Adaptation limit.** `--list` is a plain machine-readable catalog, not a claim of screen-reader accessibility for the interactive picker. A numbered plain prompt or Huh's accessible path is a separate interaction decision. + +## 6. Keep a streaming view from jumping + +**Request:** “When I scroll up to read logs, each new line yanks me back to the bottom.” + +The broken handler calls `GotoBottom` unconditionally after every append. Do not replace it with a timeout that guesses whether the user is reading. Store the intention explicitly. + +The supplied monitor uses a bounded ring and logical sequence numbers. `top` points to a record identity, not a slice offset. Its append operation is: + + +```go +func (h *history) append(line string, height int) { + h.buf[h.next%len(h.buf)] = line + h.next++ + if h.next-h.first > len(h.buf) { + h.first = h.next - len(h.buf) + } + if h.follow { + h.top = h.bottom(height) + h.unseen = 0 + return + } + h.unseen++ + if h.top < h.first { + h.top = h.first + h.expired = true + } +} +``` + + +While following, append moves the top to the tail. While reading, append leaves the anchor alone and increments the new-record count. If retention evicts the anchored record, move to the oldest remaining record and report that the anchor expired; pretending it is still the same content would be incorrect. + +**Make “follow” an explicit action.** The monitor's `end` key calls: + + +```go +func (h *history) latest(height int) { + h.follow = true + h.top = h.bottom(height) + h.unseen = 0 + h.expired = false +} +``` + + +Scrolling down to the bottom also resumes following. A resize does not silently enable follow mode; the previous reading intent survives. The demo retains 32 single-line records, and the status reports eviction. It stores display history, not a durable audit log. + +**Prove it.** `TestIncomingEventPreservesReadingAnchor` records the top and first visible line, appends a new record, and asserts that neither changed. Other [history tests](worked/cmd/tail/history_test.go) check ring ordering after 10,000 appends, eviction disclosure, follow restoration, resize, and zero-height windows. All six tests ran and passed on the same implementation used by the demo. + +**Do it.** Run `go run ./cmd/tail`. Once the viewport overflows, press Up a few times. Incoming records should increase “new” without moving the text. Press End to catch up. Keep reading old output until retention evicts it; the status should say so. The synthetic stream eventually ends and the UI remains available for reading until quit. + +**Adaptation limit.** These are single-line records. For wrapped messages, preserve item ID plus within-item line offset; calculate reflow without confusing record indexes and physical rows. A fixed record count also is not a byte bound for arbitrary-size messages—limit record size or add a byte budget before accepting untrusted streams. + +## 7. Stop subscriptions without leaks or busy loops + +**Request:** “After the stream closes, CPU spikes. Sometimes shutdown leaves a waiting goroutine.” + +This pattern is broken: + +```go +// Wrong: a closed channel immediately yields its zero value forever. +return func() tea.Msg { return lineMsg(<-ch) } +// If Update always schedules another wait, this becomes a busy loop. +``` + +**Turn closure into a terminal event.** The example's command waits for one event and distinguishes closure: + + +```go +func waitForLine(ctx context.Context, ch <-chan string) tea.Cmd { + return func() tea.Msg { + line, ok := receive(ctx, ch) + if !ok { + return closedMsg{} + } + return lineMsg(line) + } +} +``` + + +The underlying `receive` selects on both the data channel and context cancellation. The producer's sends also select on cancellation, and the queue is bounded. These are actual implementations in [stream.go](worked/cmd/tail/stream.go), not omitted TODOs. + +**Re-arm in exactly one place:** + +```go +case lineMsg: + if m.ended { + return m, nil + } + m.history.append(string(msg), m.rows()) + return m, waitForLine(m.ctx, m.events) +case closedMsg: + m.ended = true + return m, nil // No successor command after closure. +``` + +`Init` is called once for this subscription. Resize and navigation do not call it again. Quitting cancels the producer/consumer context and returns `tea.Quit`. The monitor does not bind that same worker context to `tea.WithContext`: otherwise cancelling workers as part of a normal quit can abort the program before its quit message is handled. Its `run` also defers cancellation for error paths. Search uses a different arrangement: the program's root context survives individual request cancellations. + +**Prove it.** [stream_test.go](worked/cmd/tail/stream_test.go) passed tests for delivering the last buffered event before closure, unblocking a waiting receiver with cancellation, and producer shutdown. These tests use a timeout only as a deadlock guard. [model_test.go](worked/cmd/tail/model_test.go) also asserts that closure and later stale events return no command; this adapter test needs the unavailable Charm build. + +**Adaptation limit.** A single listener is a lifecycle invariant, not enforced by the channel type. Do not start extra listeners in refresh paths. For a service with external resources, explicitly join its owned workers and close those resources; context cancellation alone is not proof that arbitrary backend code stopped. + +## 8. Reduce code without redesigning the interface + +**Request:** “Shorten the implementation, but keep my keys, layout, and custom look.” + +**Start with a concrete equivalence boundary.** Suppose these are the two old row branches, after plain-text cleanup and for widths large enough for the prefix: + +```go +if current { + return lipgloss.NewStyle().Bold(true).Render("> " + ansi.Truncate(label, width-2, "…")) +} +return lipgloss.NewStyle().Bold(false).Render(" " + ansi.Truncate(label, width-2, "…")) +``` + +The correct reduction is to parameterize the repeated difference, not replace the picker with `bubbles/list` and inherit different spacing/help/keys. In the shared row helper the corresponding branch becomes: + +```go +prefix := " " +if current { + prefix = "> " +} +// The same content budget, marker width, and selected style survive. +body := prefix + name +return lipgloss.NewStyle().Bold(current).Render(body) +``` + +The full [Row helper](worked/internal/display/render.go) also handles optional metadata and tiny widths. For the equivalence task above, pass empty metadata. Do not introduce that metadata column, new colors, borders, selection marks, or breakpoints as incidental cleanup in an existing UI. + +**Prove the transformation at the right level.** [render_test.go](worked/internal/display/render_test.go) contains both the exact prefix/label contract and a byte-for-byte comparison with the previous two-branch renderer for sanitized labels. ANSI-stripped snapshots alone cannot detect changed styling. These rendering tests were authored but not executed here. + +**Then reduce formatting work without changing the result.** This is the picker view's actual strategy: + +```go +lo, hi := display.Window(len(m.list.visible), m.list.cursor, m.top, height) +for i := lo; i < hi; i++ { + row := m.list.items[m.list.visible[i]] + lines = append(lines, display.Row(row.Label, row.Detail, m.width, i == m.list.cursor)) +} +``` + +The expensive row formatter sees only visible rows. `TestWindowFormatsOnlyVisibleRows` exercises the range used by this loop with 100,000 rows and a 12-row viewport; it passed. That establishes a bounded range, not a whole-application performance benchmark. Filtering still scans the sample collection when the query changes; do not claim virtualization made all work constant-time. + +**Acceptance example:** “The row helper replaced the duplicated selected/unselected branches. Existing keys, marker, bolding, spacing, and return values remain the same. The equivalence test and before/after terminal capture were run.” Only say the last sentence after actually doing those checks in the target repository. For this bundle, terminal capture and Charm rendering remain unverified. + +**Adaptation limit.** Do not chase line count by deleting help, error states, rendering distinctions, cancellation handling, or tests. A useful reduction preserves the observable contract and removes repeated mechanics. diff --git a/.agents/skills/charm-tui/examples/contracts/README.md b/.agents/skills/charm-tui/examples/contracts/README.md new file mode 100644 index 000000000..aa3506712 --- /dev/null +++ b/.agents/skills/charm-tui/examples/contracts/README.md @@ -0,0 +1,18 @@ +# Runnable contract exercises + +These are original, dependency-free Go fixtures for two lessons: invalidating asynchronous search results when intent changes, and allocating body rows without negative sizes. They are not a Bubble Tea implementation or a new component library. + +Run from this directory with Go 1.23 or newer: + +```sh +go test -v ./... +go test -race ./... +``` + +Translate the state fields and guards into the existing UI model rather than adding this module to an application. A real adapter must also manage cancellable backend contexts, debounce/timer commands, focus and key routing, stable row identity, and terminal rendering. + +The search fixture uses a clear-on-query-change policy. Retaining previous results is also valid, but requires an explicit stale/refreshing presentation. This latest-result policy applies to read-only search, not automatically to writes whose effects may already be committed remotely. + +**What these tests do not prove:** actual cancellation, resource cleanup, Unicode display widths, Lip Gloss geometry, Bubbles behavior, terminal restoration, or any application integration. The state is single-owner and deliberately not thread-safe. The race test runs this fixture; it is not evidence about an upstream Charm application's concurrency. + +See [architecture and effects](../../references/architecture-and-effects.md) and [testing and release](../../references/testing-and-release.md) for integration obligations. diff --git a/.agents/skills/charm-tui/examples/contracts/go.mod b/.agents/skills/charm-tui/examples/contracts/go.mod new file mode 100644 index 000000000..ae9f93be8 --- /dev/null +++ b/.agents/skills/charm-tui/examples/contracts/go.mod @@ -0,0 +1,3 @@ +module example.invalid/charm-tui-contracts + +go 1.23 diff --git a/.agents/skills/charm-tui/examples/contracts/patterns.go b/.agents/skills/charm-tui/examples/contracts/patterns.go new file mode 100644 index 000000000..f2e092442 --- /dev/null +++ b/.agents/skills/charm-tui/examples/contracts/patterns.go @@ -0,0 +1,82 @@ +// Package contracts is a dependency-free teaching fixture, not a UI framework. +// Its state is owned by one event loop; it is deliberately not thread-safe. +package contracts + +type phase uint8 + +const ( + idle phase = iota + debouncing + loading + ready + failed + stopped +) + +type searchState struct { + generation uint64 + query string + phase phase + rows []string + err error +} + +// change records new intent now, before the debounce timer fires. This fixture +// clears rows; an application may instead retain them with an explicit stale tag. +// The real application must also cancel its superseded backend context. +func (s *searchState) change(query string) uint64 { + s.generation++ + s.query = query + s.phase = debouncing + s.rows = nil + s.err = nil + return s.generation +} + +// begin admits one request for the current intent, rejecting stale or duplicate +// debounce messages. A same-query retry must first create new intent with change. +func (s *searchState) begin(generation uint64) bool { + if generation != s.generation || s.phase != debouncing { + return false + } + s.phase = loading + return true +} + +// finish transfers an immutable result to this state only while its request is +// active. The producer must not mutate rows concurrently, even during this copy. +func (s *searchState) finish(generation uint64, rows []string, err error) bool { + if generation != s.generation || s.phase != loading { + return false + } + if err != nil { + s.phase = failed + s.rows = nil + s.err = err + return true + } + s.phase = ready + s.rows = append([]string(nil), rows...) + s.err = nil + return true +} + +// stop invalidates pending completions. It does not stop real I/O; the caller +// must cancel and clean up the application's owned resources as well. +func (s *searchState) stop() { + s.generation++ + s.phase = stopped +} + +// bodyRows handles nonnegative row allocation. compact is true when the caller +// must use a different layout because the chrome does not fit. It does not +// measure text or model Lip Gloss's box behavior. +func bodyRows(total, header, footer int) (rows int, compact bool) { + total = max(0, total) + header = max(0, header) + footer = max(0, footer) + if header > total || footer > total-header { + return 0, true + } + return total - header - footer, false +} diff --git a/.agents/skills/charm-tui/examples/contracts/patterns_test.go b/.agents/skills/charm-tui/examples/contracts/patterns_test.go new file mode 100644 index 000000000..410ce23b8 --- /dev/null +++ b/.agents/skills/charm-tui/examples/contracts/patterns_test.go @@ -0,0 +1,149 @@ +package contracts + +import ( + "errors" + "reflect" + "testing" +) + +func TestOldResultRejectedBeforeNewDebounce(t *testing.T) { + var s searchState + a := s.change("a") + if !s.begin(a) { + t.Fatal("first request not admitted") + } + b := s.change("b") + before := s + if s.finish(a, []string{"old"}, nil) { + t.Fatal("old result accepted during new debounce") + } + if !reflect.DeepEqual(before, s) { + t.Fatal("rejected result mutated state") + } + if !s.begin(b) || !s.finish(b, []string{"new"}, nil) { + t.Fatal("new request failed") + } + if s.phase != ready || !reflect.DeepEqual(s.rows, []string{"new"}) { + t.Fatalf("unexpected final state: %+v", s) + } +} + +func TestStaleFailureCannotOverwriteSuccess(t *testing.T) { + var s searchState + a := s.change("a") + s.begin(a) + b := s.change("b") + s.begin(b) + s.finish(b, []string{"new"}, nil) + before := s + if s.finish(a, nil, errors.New("old failure")) || !reflect.DeepEqual(before, s) { + t.Fatal("stale failure changed successful state") + } +} + +func TestStaleCompletionCannotStopNewLoading(t *testing.T) { + var s searchState + a := s.change("a") + s.begin(a) + b := s.change("b") + s.begin(b) + if s.finish(a, nil, nil) || s.phase != loading { + t.Fatal("stale completion stopped the new loading state") + } +} + +func TestOldDebounceRejected(t *testing.T) { + var s searchState + a := s.change("a") + b := s.change("b") + if s.begin(a) || !s.begin(b) { + t.Fatal("incorrect debounce ownership") + } +} + +func TestDuplicateBeginAndCompletionRejected(t *testing.T) { + var s searchState + g := s.change("query") + if !s.begin(g) || s.begin(g) { + t.Fatal("request admission is not single-use") + } + if !s.finish(g, []string{"first"}, nil) || s.finish(g, []string{"duplicate"}, nil) { + t.Fatal("request completion is not single-use") + } +} + +func TestSameQueryRetryGetsNewIdentity(t *testing.T) { + var s searchState + a := s.change("query") + s.begin(a) + s.finish(a, nil, errors.New("transient")) + b := s.change("query") + if b == a || s.err != nil || !s.begin(b) || !s.finish(b, []string{"ok"}, nil) { + t.Fatalf("retry failed: %+v", s) + } +} + +func TestEmptyResultIsReadyNotFailure(t *testing.T) { + var s searchState + g := s.change("no matches") + s.begin(g) + if !s.finish(g, nil, nil) || s.phase != ready || s.err != nil || len(s.rows) != 0 { + t.Fatalf("empty successful result misclassified: %+v", s) + } +} + +func TestStopRejectsCompletions(t *testing.T) { + var s searchState + g := s.change("query") + s.begin(g) + s.stop() + if s.finish(g, []string{"late"}, nil) || s.phase != stopped { + t.Fatal("stopped owner accepted completion") + } +} + +func TestAcceptedRowsDoNotAliasCallerSlice(t *testing.T) { + var s searchState + g := s.change("query") + s.begin(g) + rows := []string{"before"} + s.finish(g, rows, nil) + rows[0] = "after" // Sequential mutation, not a concurrent ownership test. + if s.rows[0] != "before" { + t.Fatal("stored rows alias caller slice") + } +} + +func TestResultBeforeBeginRejected(t *testing.T) { + var s searchState + g := s.change("query") + if s.finish(g, []string{"unexpected"}, nil) || s.phase != debouncing { + t.Fatal("accepted a result before admitting its request") + } +} + +func TestBodyRows(t *testing.T) { + cases := []struct { + name string + total, header, footer int + want int + compact bool + }{ + {"normal", 24, 3, 2, 19, false}, + {"exact", 5, 3, 2, 0, false}, + {"header-too-tall", 2, 3, 1, 0, true}, + {"footer-too-tall", 5, 3, 3, 0, true}, + {"zero-with-chrome", 0, 1, 1, 0, true}, + {"zero-empty", 0, 0, 0, 0, false}, + {"negative-size", -1, 1, 1, 0, true}, + {"negative-chrome", 5, -2, -3, 5, false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got, compact := bodyRows(tc.total, tc.header, tc.footer) + if got != tc.want || compact != tc.compact { + t.Fatalf("got (%d, %v), want (%d, %v)", got, compact, tc.want, tc.compact) + } + }) + } +} diff --git a/.agents/skills/charm-tui/examples/worked/README.md b/.agents/skills/charm-tui/examples/worked/README.md new file mode 100644 index 000000000..c097acdb4 --- /dev/null +++ b/.agents/skills/charm-tui/examples/worked/README.md @@ -0,0 +1,51 @@ +# Complete example programs + +Start with the [worked tasks](../WORKED-EXAMPLES.md), not with copying the entire directory into an application. These programs demonstrate the decisions in the skill through concrete code and regression tests. They have no runtime network calls or credentials; search and log events are simulated locally. + +## Try one + +From this directory, with a Go toolchain compatible with [go.mod](go.mod): + +```sh +go mod tidy +go test -race ./... +go vet ./... +go run ./cmd/picker +``` + +Run `go run ./cmd/search` or `go run ./cmd/tail` separately for the other demos. Resolve dependencies once; `go.sum` is intentionally not fabricated. Transitive dependency checksums were unavailable in the authoring environment. + +**Picker.** An inline selector. Up/Down moves; `/` enters search. Escape/Enter from search returns to the list, keeping the query. Enter opens confirmation; Enter confirms and emits the captured ID on stdout. Escape from confirmation returns to the list. `q` quits only in browse mode. Ctrl+C cancels anywhere. `--list` and `--id prod-eu` never open a terminal. Interactive mode permits stdout redirection but requires terminal stdin/stderr; it does not read candidate data from stdin. + +**Search.** An inline text input with a 150 ms cancellable debounce and injected backend. `slow` takes longer, `error` returns a recoverable failure, and `queue` produces a match. Ctrl+R retries with fresh request identity; Escape/Ctrl+C exits. The whole request lifetime, including debounce, has a three-second timeout. Results clear on edit rather than being displayed as stale. A result list larger than the visible area would need navigation/paging before adopting this demo for such a dataset. + +**Tail.** A full-screen log monitor with a bounded 16-record transport queue and a 32-record display ring. Up/Down or j/k scrolls; End follows latest; q/Ctrl+C quits. A finite synthetic stream allows testing closure. Retention eviction is disclosed. It is not a persistent logger or a multi-line transcript renderer. + +## Where the behavior lives + +| Concern | File | +| --- | --- | +| Focus, contextual help, confirmation | [picker/model.go](cmd/picker/model.go) | +| Identity and final-result semantics | [picker/selection.go](cmd/picker/selection.go) | +| TTY detection and stdout/stderr separation | [picker/main.go](cmd/picker/main.go) | +| Request identity and cancellation | [search/request.go](cmd/search/request.go) | +| Tea commands and typed messages | [search/model.go](cmd/search/model.go) | +| Retention, reading anchor, following | [tail/history.go](cmd/tail/history.go) | +| Cancel-aware producer and receiver | [tail/stream.go](cmd/tail/stream.go) | +| One listener and no re-arm on closure | [tail/model.go](cmd/tail/model.go) | +| Actual cell clipping and v2 panels | [display/render.go](internal/display/render.go) | +| Bounds and plain-text control policy | [display/bounds.go](internal/display/bounds.go) | + +## Tests and what has actually run + +The exact core files used by these demos have 26 executed tests across four groups. This includes genuine context/timer/channel cancellation tests, not a mock of Bubble Tea. The source for all Go files was parsed/formatted by `gofmt`. Full module compilation was not possible here: Go 1.23.2 is installed, the module requests a newer toolchain, and network dependency resolution is blocked. Additional Charm model/render tests are supplied but remain unexecuted. + +From the skill root: + +```sh +python3 scripts/test_offline_examples.py +``` + +That script compiles the named dependency-free files directly with module mode disabled. It deliberately does not compile `model.go`, `render.go`, or the CLI entry points. This is not a replacement for `go test -race ./...` after dependency resolution. See [verification](../../VERIFICATION.md) and the [raw core test output](../../verification/worked-offline-tests.txt). + +No terminal/PTY session, Unicode display inspection, agent evaluation, or target-project before/after comparison was executed during authoring. Do those before claiming an adapted UI is polished or behavior-equivalent. diff --git a/.agents/skills/charm-tui/examples/worked/cmd/picker/main.go b/.agents/skills/charm-tui/examples/worked/cmd/picker/main.go new file mode 100644 index 000000000..9c7a37d2f --- /dev/null +++ b/.agents/skills/charm-tui/examples/worked/cmd/picker/main.go @@ -0,0 +1,74 @@ +// picker is a runnable demonstration, not a deployment tool. +package main + +import ( + tea "charm.land/bubbletea/v2" + "flag" + "fmt" + "github.com/charmbracelet/x/term" + "os" +) + +var servers = []item{ + {"dev-eu", "development", "eu · ready"}, + {"stage-eu", "staging", "eu · ready"}, + {"prod-eu", "production", "eu · healthy"}, + {"prod-jp", "東京 production", "jp · healthy"}, + {"queue-eu", "queue worker", "eu · busy"}, +} + +func run(args []string) (int, error) { + flags := flag.NewFlagSet("picker", flag.ContinueOnError) + id := flags.String("id", "", "select an exact ID without opening a terminal") + list := flags.Bool("list", false, "print IDs and labels without opening a terminal") + if err := flags.Parse(args); err != nil { + if err == flag.ErrHelp { + return 0, nil + } + return 2, err + } + if flags.NArg() != 0 { + return 2, fmt.Errorf("unexpected arguments") + } + if *list && *id != "" { + return 2, fmt.Errorf("choose either --list or --id") + } + if *list { + for _, row := range servers { + if _, err := fmt.Fprintf(os.Stdout, "%s\t%s\n", row.ID, row.Label); err != nil { + return 2, err + } + } + return 0, nil + } + if *id != "" { + for _, row := range servers { + if row.ID == *id { + return finish(os.Stdout, outcome{Accepted: true, ID: row.ID}) + } + } + return 2, fmt.Errorf("unknown ID %q", *id) + } + // stdout may be a pipe. Only stdin and the UI's stderr must be terminals. + // Do not open a hidden /dev/tty in unattended jobs. + if !term.IsTerminal(os.Stdin.Fd()) || !term.IsTerminal(os.Stderr.Fd()) { + return 2, fmt.Errorf("interactive mode needs terminal stdin and stderr; use --list or --id") + } + final, err := tea.NewProgram(newModel(servers), tea.WithInput(os.Stdin), tea.WithOutput(os.Stderr)).Run() + if err != nil { + return 2, fmt.Errorf("picker: %w", err) + } + m, ok := final.(*model) + if !ok { + return 2, fmt.Errorf("unexpected final model %T", final) + } + return finish(os.Stdout, m.result) +} + +func main() { + code, err := run(os.Args[1:]) + if err != nil { + fmt.Fprintln(os.Stderr, err) + } + os.Exit(code) // run's defers and Bubble Tea cleanup have already completed. +} diff --git a/.agents/skills/charm-tui/examples/worked/cmd/picker/model.go b/.agents/skills/charm-tui/examples/worked/cmd/picker/model.go new file mode 100644 index 000000000..f19ca8e93 --- /dev/null +++ b/.agents/skills/charm-tui/examples/worked/cmd/picker/model.go @@ -0,0 +1,179 @@ +package main + +import ( + "charm.land/bubbles/v2/help" + "charm.land/bubbles/v2/key" + "charm.land/bubbles/v2/textinput" + tea "charm.land/bubbletea/v2" + "charm.land/lipgloss/v2" + "example.com/charm-tui-worked/internal/display" + "fmt" + "strings" +) + +type model struct { + list selection + input textinput.Model + help help.Model + width, height, top int + confirm *item // Captured target, not a later lookup through a moving cursor. + result outcome +} + +type keys struct{ up, down, search, accept, back, quit key.Binding } + +func binding(k, label string) key.Binding { + return key.NewBinding(key.WithKeys(k), key.WithHelp(k, label)) +} +func (k keys) ShortHelp() []key.Binding { + return []key.Binding{k.up, k.down, k.search, k.accept, k.back, k.quit} +} +func (k keys) FullHelp() [][]key.Binding { return [][]key.Binding{k.ShortHelp()} } + +func (m *model) keys() keys { + k := keys{binding("up", "up"), binding("down", "down"), binding("/", "search"), binding("enter", "choose"), binding("esc", "cancel"), binding("q", "quit")} + if m.input.Focused() { + k.up.SetEnabled(false) + k.down.SetEnabled(false) + k.search.SetEnabled(false) + k.quit.SetEnabled(false) + k.accept = binding("enter", "browse") + k.back = binding("esc", "browse") + } else if m.confirm != nil { + k.up.SetEnabled(false) + k.down.SetEnabled(false) + k.search.SetEnabled(false) + k.quit.SetEnabled(false) + k.accept = binding("enter", "confirm") + k.back = binding("esc", "back") + } else { + _, ok := m.list.current() + k.accept.SetEnabled(ok) + } + return k +} + +func newModel(items []item) *model { + input := textinput.New() + input.Prompt = "/ " + input.Placeholder = "filter servers" + input.SetVirtualCursor(true) // Avoid real-cursor coordinate translation here. + input.SetWidth(48) + return &model{list: newSelection(items), input: input, help: help.New(), width: 60, height: 12} +} + +func (m *model) Init() tea.Cmd { return tea.RequestBackgroundColor } + +func (m *model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { + switch msg := msg.(type) { + case tea.WindowSizeMsg: + m.width = min(72, max(0, msg.Width)) + m.height = min(12, max(0, msg.Height)) + m.input.SetWidth(max(1, m.width-3)) + m.help.SetWidth(m.width) + m.clampWindow() + return m, nil + case tea.BackgroundColorMsg: + m.input.SetStyles(textinput.DefaultStyles(msg.IsDark())) + m.help.Styles = help.DefaultStyles(msg.IsDark()) + return m, nil + case tea.KeyPressMsg: + if msg.String() == "ctrl+c" { + m.result = outcome{Interrupted: true} + return m, tea.Quit + } + // Modal input is consumed exactly once, even when this key closes it. + if m.confirm != nil { + switch msg.String() { + case "esc": + m.confirm = nil + case "enter": + m.result = outcome{Accepted: true, ID: m.confirm.ID} + return m, tea.Quit + } + return m, nil + } + k := m.keys() + // An editor owns printable keys. 'q', '/', '?', 'j' are text here. + if m.input.Focused() { + if key.Matches(msg, k.back, k.accept) { + m.input.Blur() + m.clampWindow() + return m, nil + } + return m, m.updateInput(msg) + } + switch { + case key.Matches(msg, k.quit, k.back): + return m, tea.Quit + case key.Matches(msg, k.search): + cmd := m.input.Focus() + m.clampWindow() + return m, cmd + case key.Matches(msg, k.up): + m.list.move(-1) + case key.Matches(msg, k.down): + m.list.move(1) + case key.Matches(msg, k.accept): + if row, ok := m.list.current(); ok { + m.confirm = &row + } + } + m.clampWindow() + return m, nil + } + // Paste results and cursor messages also need the child update path. + return m, m.updateInput(msg) +} + +func (m *model) updateInput(msg tea.Msg) tea.Cmd { + before := m.input.Value() + var cmd tea.Cmd + m.input, cmd = m.input.Update(msg) + if m.input.Value() != before { + m.list.filter(m.input.Value()) + m.clampWindow() + } + return cmd // Never lose child effects, including cursor or paste commands. +} + +func (m *model) bodyHeight() int { + // Header has exactly two clipped lines; status has one, help is measured. + return display.BodyRows(m.height, 2, 1+lipgloss.Height(m.help.View(m.keys()))) +} +func (m *model) clampWindow() { + m.top, _ = display.Window(len(m.list.visible), m.list.cursor, m.top, m.bodyHeight()) +} + +func (m *model) View() tea.View { + if m.width <= 0 || m.height <= 0 { + return tea.NewView("") + } + if m.width < 20 || m.height < 7 { + return tea.NewView(display.Line("resize · ctrl+c cancel", m.width)) + } + title := lipgloss.NewStyle().Bold(true).Render("choose a server") + if m.confirm != nil { + // Modal panel replaces the content; it is not an overlay compositor. + text := "use " + display.SingleLine(m.confirm.Label) + "?" + content := title + "\n" + display.Panel(text, m.width) + "\n" + m.help.View(m.keys()) + return tea.NewView(content) + } + height := m.bodyHeight() + lo, hi := display.Window(len(m.list.visible), m.list.cursor, m.top, height) + lines := make([]string, 0, hi-lo) + for i := lo; i < hi; i++ { + row := m.list.items[m.list.visible[i]] + lines = append(lines, display.Row(row.Label, row.Detail, m.width, i == m.list.cursor)) + } + if len(m.list.visible) == 0 { + lines = append(lines, "no matches · edit the filter") + } + content := []string{ + title, display.Line(m.input.View(), m.width), + display.FillRows(lines, m.width, height), + display.Line(fmt.Sprintf("%d matches", len(m.list.visible)), m.width), + m.help.View(m.keys()), + } + return tea.NewView(strings.Join(content, "\n")) // Deliberately inline. +} diff --git a/.agents/skills/charm-tui/examples/worked/cmd/picker/model_test.go b/.agents/skills/charm-tui/examples/worked/cmd/picker/model_test.go new file mode 100644 index 000000000..f920f7a7f --- /dev/null +++ b/.agents/skills/charm-tui/examples/worked/cmd/picker/model_test.go @@ -0,0 +1,72 @@ +package main + +import ( + tea "charm.land/bubbletea/v2" + "charm.land/lipgloss/v2" + "strings" + "testing" +) + +func press(m *model, r rune) tea.Cmd { + text := "" + if r >= 32 && r < 127 { + text = string(r) + } + _, cmd := m.Update(tea.KeyPressMsg{Code: r, Text: text}) + return cmd +} + +func TestPrintableKeysBelongToSearch(t *testing.T) { + m := newModel(testItems()) + press(m, '/') + for _, r := range "qj/k? " { + press(m, r) + } + if m.input.Value() != "qj/k? " || !m.input.Focused() || m.result.Accepted { + t.Fatalf("input=%q", m.input.Value()) + } +} + +func TestModalEscapeDoesNotQuitOrReopen(t *testing.T) { + m := newModel(testItems()) + press(m, tea.KeyEnter) + if m.confirm == nil { + t.Fatal("no confirmation") + } + cmd := press(m, tea.KeyEscape) + if m.confirm != nil || m.result.Accepted || cmd != nil { + t.Fatal("modal key leaked to list") + } + press(m, tea.KeyEnter) + press(m, tea.KeyEnter) + if !m.result.Accepted || m.result.ID != "a" { + t.Fatal("confirmation lost its target") + } +} + +func TestNoMatchEnterDoesNothing(t *testing.T) { + m := newModel(testItems()) + m.list.filter("missing") + if cmd := press(m, tea.KeyEnter); cmd != nil || m.confirm != nil { + t.Fatal("empty selection accepted") + } +} + +func TestPickerResizeAndRepeatedView(t *testing.T) { + m := newModel(servers) + for _, size := range [][2]int{{0, 0}, {1, 1}, {19, 6}, {24, 8}, {80, 24}} { + m.Update(tea.WindowSizeMsg{Width: size[0], Height: size[1]}) + beforeCursor := m.list.cursor + beforeTop := m.top + view := m.View().Content + if view != m.View().Content || beforeCursor != m.list.cursor || beforeTop != m.top { + t.Fatal("View changed state") + } + if lipgloss.Width(view) > size[0] { + t.Fatalf("overflow at %v", size) + } + if view != "" && len(strings.Split(view, "\n")) > size[1] { + t.Fatalf("height overflow at %v", size) + } + } +} diff --git a/.agents/skills/charm-tui/examples/worked/cmd/picker/selection.go b/.agents/skills/charm-tui/examples/worked/cmd/picker/selection.go new file mode 100644 index 000000000..7fa72e7f8 --- /dev/null +++ b/.agents/skills/charm-tui/examples/worked/cmd/picker/selection.go @@ -0,0 +1,75 @@ +package main + +import ( + "fmt" + "io" + "strings" +) + +type item struct{ ID, Label, Detail string } + +type selection struct { + items []item + visible []int // Indexes into items; never the identity returned to a caller. + cursor int +} + +func newSelection(items []item) selection { + s := selection{items: append([]item(nil), items...)} + s.filter("") + return s +} + +func (s *selection) current() (item, bool) { + if s.cursor < 0 || s.cursor >= len(s.visible) { + return item{}, false + } + return s.items[s.visible[s.cursor]], true +} + +func (s *selection) filter(query string) { + old, hadOld := s.current() + s.visible = nil + query = strings.ToLower(query) + for i, row := range s.items { + if strings.Contains(strings.ToLower(row.Label), query) { + s.visible = append(s.visible, i) + } + } + s.cursor = 0 + if hadOld { + for i, index := range s.visible { + if s.items[index].ID == old.ID { + s.cursor = i + break + } + } + } +} + +func (s *selection) move(delta int) { + s.cursor = min(max(0, s.cursor+delta), max(0, len(s.visible)-1)) +} + +type outcome struct { + Accepted, Interrupted bool + ID string +} + +// finish is called only after Bubble Tea has released the terminal. +// Demo policy: 0 accepted, 1 cancelled, 130 keyboard interrupt, 2 failure. +func finish(w io.Writer, result outcome) (int, error) { + if result.Interrupted { + return 130, nil + } + if !result.Accepted { + return 1, nil + } + if result.ID == "" { + return 2, fmt.Errorf("accepted result has no ID") + } + if _, err := fmt.Fprintln(w, result.ID); err != nil { + return 2, err + } + return 0, nil +} diff --git a/.agents/skills/charm-tui/examples/worked/cmd/picker/selection_test.go b/.agents/skills/charm-tui/examples/worked/cmd/picker/selection_test.go new file mode 100644 index 000000000..ff767dff7 --- /dev/null +++ b/.agents/skills/charm-tui/examples/worked/cmd/picker/selection_test.go @@ -0,0 +1,89 @@ +package main + +import ( + "bytes" + "errors" + "testing" +) + +func testItems() []item { + return []item{{"a", "alpha", ""}, {"b", "beta", ""}, {"c", "beta clone", ""}} +} + +func TestFilterPreservesIdentity(t *testing.T) { + s := newSelection(testItems()) + s.move(1) + s.filter("beta") + row, ok := s.current() + if !ok || row.ID != "b" || s.cursor != 0 { + t.Fatalf("%+v", s) + } + s.filter("") + row, _ = s.current() + if row.ID != "b" || s.cursor != 1 { + t.Fatal("lost identity when clearing search") + } +} + +func TestEmptyAndNoMatchesAreSafe(t *testing.T) { + for _, items := range [][]item{nil, testItems()} { + s := newSelection(items) + s.filter("not present") + s.move(99) + s.move(-99) + if _, ok := s.current(); ok { + t.Fatal("empty list produced a selection") + } + } +} + +func TestDuplicateLabelsKeepDistinctIDs(t *testing.T) { + s := newSelection([]item{{"one", "same", ""}, {"two", "same", ""}}) + s.move(1) + s.filter("same") + row, _ := s.current() + if row.ID != "two" { + t.Fatal("used label as identity") + } +} + +func TestConstructorOwnsItsItems(t *testing.T) { + rows := testItems() + s := newSelection(rows) + rows[0].Label = "mutated" + row, _ := s.current() + if row.Label != "alpha" { + t.Fatal("shared mutable input") + } +} + +func TestFinishNeverLeaksCancelledSelection(t *testing.T) { + for _, c := range []struct { + result outcome + code int + out string + }{ + {outcome{Accepted: true, ID: "b"}, 0, "b\n"}, + {outcome{ID: "b"}, 1, ""}, + {outcome{Accepted: true, Interrupted: true, ID: "b"}, 130, ""}, + } { + var out bytes.Buffer + code, err := finish(&out, c.result) + if err != nil || code != c.code || out.String() != c.out { + t.Fatalf("code=%d err=%v output=%q", code, err, out.String()) + } + } +} + +type brokenWriter struct{} + +func (brokenWriter) Write([]byte) (int, error) { return 0, errors.New("broken pipe") } +func TestFinishReportsWriteAndInvalidResult(t *testing.T) { + if code, err := finish(brokenWriter{}, outcome{Accepted: true, ID: "b"}); code != 2 || err == nil { + t.Fatal("lost write error") + } + var out bytes.Buffer + if code, err := finish(&out, outcome{Accepted: true}); code != 2 || err == nil || out.Len() != 0 { + t.Fatal("empty ID emitted") + } +} diff --git a/.agents/skills/charm-tui/examples/worked/cmd/search/main.go b/.agents/skills/charm-tui/examples/worked/cmd/search/main.go new file mode 100644 index 000000000..f0b45af84 --- /dev/null +++ b/.agents/skills/charm-tui/examples/worked/cmd/search/main.go @@ -0,0 +1,27 @@ +package main + +import ( + tea "charm.land/bubbletea/v2" + "context" + "fmt" + "github.com/charmbracelet/x/term" + "os" +) + +func run() error { + if !term.IsTerminal(os.Stdin.Fd()) || !term.IsTerminal(os.Stderr.Fd()) { + return fmt.Errorf("search demo requires terminal stdin and stderr") + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + m := newModel(ctx, demoSearch) + defer m.state.stop() + _, err := tea.NewProgram(m, tea.WithContext(ctx), tea.WithInput(os.Stdin), tea.WithOutput(os.Stderr)).Run() + return err +} +func main() { + if err := run(); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } +} diff --git a/.agents/skills/charm-tui/examples/worked/cmd/search/model.go b/.agents/skills/charm-tui/examples/worked/cmd/search/model.go new file mode 100644 index 000000000..764bcd6fa --- /dev/null +++ b/.agents/skills/charm-tui/examples/worked/cmd/search/model.go @@ -0,0 +1,136 @@ +package main + +import ( + "charm.land/bubbles/v2/textinput" + tea "charm.land/bubbletea/v2" + "context" + "example.com/charm-tui-worked/internal/display" + "fmt" + "strings" + "time" +) + +type debounceMsg struct { + ticket ticket + err error +} +type loadedMsg struct { + generation uint64 + rows []string + err error +} + +func debounceCmd(t ticket) tea.Cmd { + return func() tea.Msg { return debounceMsg{ticket: t, err: await(t.ctx, 150*time.Millisecond)} } +} +func loadCmd(t ticket, search searchFunc) tea.Cmd { + // The closure captures values and a service, never the live model. + return func() tea.Msg { + rows, err := search(t.ctx, t.query) + return loadedMsg{generation: t.generation, rows: rows, err: err} + } +} + +type model struct { + input textinput.Model + state searchState + search searchFunc + initial ticket + width, height int +} + +func newModel(ctx context.Context, search searchFunc) *model { + input := textinput.New() + input.Prompt = "/ " + input.Placeholder = "try slow, error, or queue" + input.SetVirtualCursor(true) + input.SetWidth(55) + m := &model{input: input, state: searchState{root: ctx}, search: search, width: 60, height: 12} + m.initial = m.state.change("") + return m +} + +func (m *model) Init() tea.Cmd { + return tea.Batch(m.input.Focus(), debounceCmd(m.initial), tea.RequestBackgroundColor) +} + +func (m *model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { + switch msg := msg.(type) { + case tea.WindowSizeMsg: + m.width = min(72, max(0, msg.Width)) + m.height = min(12, max(0, msg.Height)) + m.input.SetWidth(max(1, m.width-3)) + return m, nil + case tea.BackgroundColorMsg: + m.input.SetStyles(textinput.DefaultStyles(msg.IsDark())) + return m, nil + case tea.KeyPressMsg: + switch msg.String() { + case "esc", "ctrl+c": + m.state.stop() + return m, tea.Quit + case "ctrl+r": + return m, debounceCmd(m.state.change(m.input.Value())) + } + case debounceMsg: + // begin also rejects a duplicated current-generation debounce delivery. + if !m.state.begin(msg.ticket.generation) { + return m, nil + } + if msg.err != nil { + m.state.complete(msg.ticket.generation, nil, msg.err) + return m, nil + } + return m, loadCmd(msg.ticket, m.search) + case loadedMsg: + m.state.complete(msg.generation, msg.rows, msg.err) + return m, nil + } + before := m.input.Value() + var childCmd tea.Cmd + m.input, childCmd = m.input.Update(msg) + if m.input.Value() != before { + t := m.state.change(m.input.Value()) + return m, tea.Batch(childCmd, debounceCmd(t)) + } + return m, childCmd +} + +func (m *model) View() tea.View { + if m.width <= 0 || m.height <= 0 { + return tea.NewView("") + } + if m.width < 20 || m.height < 6 { + return tea.NewView(display.Line("resize · esc quit", m.width)) + } + status := "waiting for input" + switch m.state.phase { + case waiting: + status = "waiting for typing to settle" + case loading: + status = "searching…" + case ready: + status = fmt.Sprintf("%d matches", len(m.state.rows)) + case failed: + status = "search failed · ctrl+r retry" + } + rows := make([]string, 0, len(m.state.rows)) + for _, row := range m.state.rows { + rows = append(rows, display.SingleLine(row)) + } + if m.state.phase == ready && len(rows) == 0 { + rows = append(rows, "no matches · edit the query") + } + if m.state.err != nil { + rows = append(rows, display.SingleLine(m.state.err.Error())) + } + // All four chrome rows are explicitly clipped to one line. + content := []string{ + display.Line("server search · simulated service", m.width), + display.Line(m.input.View(), m.width), + display.Line(status, m.width), + display.FillRows(rows, m.width, display.BodyRows(m.height, 3, 1)), + display.Line("esc quit · ctrl+r retry", m.width), + } + return tea.NewView(strings.Join(content, "\n")) +} diff --git a/.agents/skills/charm-tui/examples/worked/cmd/search/model_test.go b/.agents/skills/charm-tui/examples/worked/cmd/search/model_test.go new file mode 100644 index 000000000..99988245b --- /dev/null +++ b/.agents/skills/charm-tui/examples/worked/cmd/search/model_test.go @@ -0,0 +1,35 @@ +package main + +import ( + tea "charm.land/bubbletea/v2" + "context" + "testing" +) + +func TestModelRejectsResultDuringDebounce(t *testing.T) { + m := newModel(context.Background(), demoSearch) + defer m.state.stop() + a := m.initial + _, load := m.Update(debounceMsg{ticket: a}) + if load == nil { + t.Fatal("did not schedule backend") + } + m.input.Focus() + m.Update(tea.KeyPressMsg{Code: 'b', Text: "b"}) + m.Update(loadedMsg{generation: a.generation, rows: []string{"obsolete"}}) + if m.state.query != "b" || m.state.phase != waiting || len(m.state.rows) != 0 { + t.Fatal("adapter accepted obsolete result") + } +} + +func TestLoadCmdUsesCapturedQueryNotLiveModel(t *testing.T) { + m := newModel(context.Background(), func(_ context.Context, q string) ([]string, error) { return []string{q}, nil }) + defer m.state.stop() + a := m.state.change("captured") + cmd := loadCmd(a, m.search) + m.state.change("later") + got := cmd().(loadedMsg) + if got.rows[0] != "captured" || got.generation != a.generation { + t.Fatal("command observed live state") + } +} diff --git a/.agents/skills/charm-tui/examples/worked/cmd/search/request.go b/.agents/skills/charm-tui/examples/worked/cmd/search/request.go new file mode 100644 index 000000000..6e8b1d1c7 --- /dev/null +++ b/.agents/skills/charm-tui/examples/worked/cmd/search/request.go @@ -0,0 +1,123 @@ +package main + +import ( + "context" + "errors" + "strings" + "time" +) + +type phase uint8 + +const ( + idle phase = iota + waiting + loading + ready + failed + stopped +) + +type ticket struct { + ctx context.Context + generation uint64 + query string +} +type searchState struct { + root context.Context + cancel context.CancelFunc + generation uint64 + query string + phase phase + rows []string + err error +} + +// change is called synchronously in Update at the moment intent changes. +func (s *searchState) change(query string) ticket { + s.generation++ // Invalidate A before B's debounce, not when B's I/O starts. + if s.cancel != nil { + s.cancel() + } + ctx, cancel := context.WithTimeout(s.root, 3*time.Second) + s.cancel = cancel + s.query = query + s.phase = waiting + s.rows = nil + s.err = nil + return ticket{ctx: ctx, generation: s.generation, query: query} +} + +func (s *searchState) begin(generation uint64) bool { + if generation != s.generation || s.phase != waiting { + return false + } + s.phase = loading + return true +} + +func (s *searchState) complete(generation uint64, rows []string, err error) bool { + if generation != s.generation || s.phase != loading { + return false + } + if s.cancel != nil { + s.cancel() + s.cancel = nil + } + s.err = err + if err != nil { + s.phase = failed + s.rows = nil + } else { + s.phase = ready + s.rows = append([]string(nil), rows...) + } + return true +} + +func (s *searchState) stop() { + s.generation++ + s.phase = stopped + if s.cancel != nil { + s.cancel() + s.cancel = nil + } +} + +// await is used by the actual command adapter. Cancellation stops the timer +// instead of leaving a growing pile of superseded debounce timers alive. +func await(ctx context.Context, d time.Duration) error { + timer := time.NewTimer(d) + defer timer.Stop() + select { + case <-ctx.Done(): + return ctx.Err() + case <-timer.C: + return nil + } +} + +type searchFunc func(context.Context, string) ([]string, error) + +// demoSearch is an injected local service, NOT an external API. A backend must +// honor context; generation guards alone do not bound backend resource use. +func demoSearch(ctx context.Context, query string) ([]string, error) { + delay := 60 * time.Millisecond + if query == "slow" { + delay = 500 * time.Millisecond + } + if err := await(ctx, delay); err != nil { + return nil, err + } + if query == "error" { + return nil, errors.New("demo service unavailable") + } + names := []string{"alpha", "beta", "queue worker", "東京 production", "slow worker"} + rows := make([]string, 0, len(names)) + for _, name := range names { + if strings.Contains(strings.ToLower(name), strings.ToLower(query)) { + rows = append(rows, name) + } + } + return rows, nil +} diff --git a/.agents/skills/charm-tui/examples/worked/cmd/search/request_test.go b/.agents/skills/charm-tui/examples/worked/cmd/search/request_test.go new file mode 100644 index 000000000..d0944d989 --- /dev/null +++ b/.agents/skills/charm-tui/examples/worked/cmd/search/request_test.go @@ -0,0 +1,112 @@ +package main + +import ( + "context" + "errors" + "testing" + "time" +) + +func stateForTest(t *testing.T) *searchState { + t.Helper() + s := &searchState{root: context.Background()} + t.Cleanup(s.stop) + return s +} +func TestOldResultDuringNewDebounceIsRejected(t *testing.T) { + s := stateForTest(t) + a := s.change("a") + if !s.begin(a.generation) { + t.Fatal("A did not start") + } + b := s.change("b") // B has NOT started I/O yet. + if a.ctx.Err() != context.Canceled { + t.Fatal("A wasn't cancelled immediately") + } + if s.complete(a.generation, []string{"old"}, nil) || s.phase != waiting || len(s.rows) != 0 { + t.Fatal("A leaked through debounce") + } + if !s.begin(b.generation) || !s.complete(b.generation, []string{"fresh"}, nil) { + t.Fatal("B rejected") + } + if s.rows[0] != "fresh" { + t.Fatal("wrong rows") + } +} +func TestStaleFailureCannotStopNewLoading(t *testing.T) { + s := stateForTest(t) + a := s.change("a") + s.begin(a.generation) + b := s.change("b") + s.begin(b.generation) + if s.complete(a.generation, nil, errors.New("old error")) || s.phase != loading || s.err != nil { + t.Fatal("stale error changed active state") + } +} +func TestDuplicateAndStaleDebouncesDoNotStartWork(t *testing.T) { + s := stateForTest(t) + a := s.change("a") + b := s.change("b") + if s.begin(a.generation) || !s.begin(b.generation) || s.begin(b.generation) { + t.Fatal("invalid request admission") + } +} +func TestCompletionOwnsRowsAndRejectsDuplicate(t *testing.T) { + s := stateForTest(t) + a := s.change("a") + s.begin(a.generation) + rows := []string{"fresh"} + s.complete(a.generation, rows, nil) + rows[0] = "mutated" + if s.rows[0] != "fresh" || s.complete(a.generation, nil, errors.New("late")) { + t.Fatal("completion not isolated") + } + if a.ctx.Err() != context.Canceled { + t.Fatal("completion leaked cancel resources") + } +} +func TestRetryGetsNewIdentityAndStopRejectsResults(t *testing.T) { + s := stateForTest(t) + a := s.change("same") + s.begin(a.generation) + s.complete(a.generation, nil, errors.New("failed")) + if s.phase != failed { + t.Fatal("missing error phase") + } + b := s.change("same") + if a.generation == b.generation || s.err != nil { + t.Fatal("retry reuses old state") + } + s.begin(b.generation) + s.stop() + if b.ctx.Err() != context.Canceled || s.complete(b.generation, []string{"late"}, nil) || s.begin(b.generation) { + t.Fatal("stopped request resumed") + } +} +func TestCancelledDebounceReturnsWithoutWaiting(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + done := make(chan error, 1) + go func() { done <- await(ctx, time.Hour) }() + select { + case err := <-done: + if !errors.Is(err, context.Canceled) { + t.Fatalf("%v", err) + } + case <-time.After(time.Second): + t.Fatal("cancelled timer still waiting") + } +} +func TestDemoBackendCancellationAndResponses(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if _, err := demoSearch(ctx, "slow"); !errors.Is(err, context.Canceled) { + t.Fatalf("%v", err) + } + if rows, err := demoSearch(context.Background(), "QUEUE"); err != nil || len(rows) != 1 || rows[0] != "queue worker" { + t.Fatalf("%v %v", rows, err) + } + if _, err := demoSearch(context.Background(), "error"); err == nil { + t.Fatal("error scenario missing") + } +} diff --git a/.agents/skills/charm-tui/examples/worked/cmd/tail/history.go b/.agents/skills/charm-tui/examples/worked/cmd/tail/history.go new file mode 100644 index 000000000..7fd8c6154 --- /dev/null +++ b/.agents/skills/charm-tui/examples/worked/cmd/tail/history.go @@ -0,0 +1,62 @@ +package main + +// history is a bounded ring of one-line records. Positions are logical sequence +// numbers, not slice offsets, so eviction does not silently change an anchor. +type history struct { + buf []string + first, next, top int + follow bool + unseen int + expired bool +} + +func newHistory(capacity int) history { + return history{buf: make([]string, max(1, capacity)), follow: true} +} +func (h *history) bottom(height int) int { return max(h.first, h.next-max(1, height)) } +func (h *history) append(line string, height int) { + h.buf[h.next%len(h.buf)] = line + h.next++ + if h.next-h.first > len(h.buf) { + h.first = h.next - len(h.buf) + } + if h.follow { + h.top = h.bottom(height) + h.unseen = 0 + return + } + h.unseen++ + if h.top < h.first { + h.top = h.first + h.expired = true + } +} +func (h *history) scroll(delta, height int) { + h.top = min(max(h.first, h.top+delta), h.bottom(height)) + h.follow = h.top == h.bottom(height) + if h.follow { + h.unseen = 0 + h.expired = false + } +} +func (h *history) latest(height int) { + h.follow = true + h.top = h.bottom(height) + h.unseen = 0 + h.expired = false +} +func (h *history) resize(height int) { + if h.follow { + h.top = h.bottom(height) + } else { + h.top = min(max(h.first, h.top), h.bottom(height)) + } +} +func (h *history) visible(height int) []string { + end := min(h.next, h.top+max(0, height)) + out := make([]string, 0, max(0, end-h.top)) + for i := h.top; i < end; i++ { + out = append(out, h.buf[i%len(h.buf)]) + } + return out +} diff --git a/.agents/skills/charm-tui/examples/worked/cmd/tail/history_test.go b/.agents/skills/charm-tui/examples/worked/cmd/tail/history_test.go new file mode 100644 index 000000000..bcf5e8c87 --- /dev/null +++ b/.agents/skills/charm-tui/examples/worked/cmd/tail/history_test.go @@ -0,0 +1,81 @@ +package main + +import ( + "fmt" + "testing" +) + +func seeded(n, capacity, height int) history { + h := newHistory(capacity) + for i := 0; i < n; i++ { + h.append(fmt.Sprint(i), height) + } + return h +} +func TestIncomingEventPreservesReadingAnchor(t *testing.T) { + h := seeded(8, 20, 3) + h.scroll(-2, 3) + before := h.top + first := h.visible(3)[0] + h.append("new", 3) + if h.top != before || h.visible(3)[0] != first || h.unseen != 1 || h.follow { + t.Fatal("new event moved reader") + } + h.latest(3) + if !h.follow || h.unseen != 0 || h.visible(3)[2] != "new" { + t.Fatal("latest did not restore following") + } +} +func TestEvictionMarksLostAnchor(t *testing.T) { + h := seeded(5, 5, 2) + h.scroll(-99, 2) + h.append("5", 2) + if h.first != 1 || h.top != 1 || !h.expired || h.visible(2)[0] != "1" { + t.Fatalf("%+v", h) + } +} +func TestRingBoundAndOrder(t *testing.T) { + h := seeded(10_000, 32, 8) + if len(h.buf) != 32 || h.next-h.first != 32 || h.visible(8)[7] != "9999" { + t.Fatal("ring grew or changed order") + } +} +func TestResizeKeepsFollowState(t *testing.T) { + h := seeded(8, 20, 3) + h.scroll(-1, 3) + h.resize(5) + if h.follow { + t.Fatal("resize enabled follow") + } + h.append("8", 5) + if h.follow || h.unseen != 1 { + t.Fatal("resize lost reading intent") + } + h.latest(2) + h.resize(4) + if h.top != h.bottom(4) { + t.Fatal("following resize not at tail") + } +} +func TestZeroAndTinyWindows(t *testing.T) { + h := newHistory(0) + if len(h.visible(0)) != 0 { + t.Fatal("unexpected records") + } + h.append("a", 0) + h.append("b", 0) + h.scroll(-99, 0) + h.resize(0) + if len(h.visible(0)) != 0 || len(h.buf) != 1 || h.visible(1)[0] != "b" { + t.Fatal("tiny window invalid") + } +} +func TestScrollingBackToBottomFollows(t *testing.T) { + h := seeded(8, 20, 3) + h.scroll(-2, 3) + h.append("8", 3) + h.scroll(99, 3) + if !h.follow || h.unseen != 0 { + t.Fatal("reaching bottom did not follow") + } +} diff --git a/.agents/skills/charm-tui/examples/worked/cmd/tail/main.go b/.agents/skills/charm-tui/examples/worked/cmd/tail/main.go new file mode 100644 index 000000000..31a181871 --- /dev/null +++ b/.agents/skills/charm-tui/examples/worked/cmd/tail/main.go @@ -0,0 +1,27 @@ +package main + +import ( + tea "charm.land/bubbletea/v2" + "context" + "fmt" + "github.com/charmbracelet/x/term" + "os" + "time" +) + +func run() error { + if !term.IsTerminal(os.Stdin.Fd()) || !term.IsTerminal(os.Stderr.Fd()) { + return fmt.Errorf("tail demo requires terminal stdin and stderr") + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + m := &model{ctx: ctx, cancel: cancel, events: produce(ctx, 80, 250*time.Millisecond), history: newHistory(32), width: 80, height: 24} + _, err := tea.NewProgram(m, tea.WithInput(os.Stdin), tea.WithOutput(os.Stderr)).Run() + return err +} +func main() { + if err := run(); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } +} diff --git a/.agents/skills/charm-tui/examples/worked/cmd/tail/model.go b/.agents/skills/charm-tui/examples/worked/cmd/tail/model.go new file mode 100644 index 000000000..16abce41e --- /dev/null +++ b/.agents/skills/charm-tui/examples/worked/cmd/tail/model.go @@ -0,0 +1,97 @@ +package main + +import ( + tea "charm.land/bubbletea/v2" + "context" + "example.com/charm-tui-worked/internal/display" + "fmt" + "strings" +) + +type lineMsg string +type closedMsg struct{} + +func waitForLine(ctx context.Context, ch <-chan string) tea.Cmd { + return func() tea.Msg { + line, ok := receive(ctx, ch) + if !ok { + return closedMsg{} + } + return lineMsg(line) + } +} + +type model struct { + ctx context.Context + cancel context.CancelFunc + events <-chan string + history history + width, height int + ended bool +} + +func (m *model) rows() int { return display.BodyRows(m.height, 1, 2) } +func (m *model) Init() tea.Cmd { return waitForLine(m.ctx, m.events) } +func (m *model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { + switch msg := msg.(type) { + case tea.WindowSizeMsg: + m.width = max(0, msg.Width) + m.height = max(0, msg.Height) + m.history.resize(m.rows()) + case tea.KeyPressMsg: + switch msg.String() { + case "q", "ctrl+c": + m.cancel() + return m, tea.Quit + case "up", "k": + m.history.scroll(-1, m.rows()) + case "down", "j": + m.history.scroll(1, m.rows()) + case "end": + m.history.latest(m.rows()) + } + case lineMsg: + if m.ended { + return m, nil + } + m.history.append(string(msg), m.rows()) + return m, waitForLine(m.ctx, m.events) // Exactly one successor listener. + case closedMsg: + m.ended = true + return m, nil // Never re-arm a closed stream. + } + return m, nil +} +func (m *model) View() tea.View { + v := tea.NewView("") + v.AltScreen = true + if m.width <= 0 || m.height <= 0 { + return v + } + if m.width < 20 || m.height < 5 { + v.Content = display.Line("resize · q quit", m.width) + return v + } + state := "following" + if !m.history.follow { + state = fmt.Sprintf("reading · %d new · end follows", m.history.unseen) + } + if m.history.expired { + state = "old anchor evicted · end follows" + } + if m.ended { + state += " · stream ended" + } + state += fmt.Sprintf(" · %d evicted", m.history.first) + lines := m.history.visible(m.rows()) + for i := range lines { + lines[i] = display.SingleLine(lines[i]) + } + v.Content = strings.Join([]string{ + display.Line("worker events · retain last 32 records", m.width), + display.FillRows(lines, m.width, m.rows()), + display.Line(state, m.width), + display.Line("↑/↓ scroll · end latest · q quit", m.width), + }, "\n") + return v +} diff --git a/.agents/skills/charm-tui/examples/worked/cmd/tail/model_test.go b/.agents/skills/charm-tui/examples/worked/cmd/tail/model_test.go new file mode 100644 index 000000000..6a294e020 --- /dev/null +++ b/.agents/skills/charm-tui/examples/worked/cmd/tail/model_test.go @@ -0,0 +1,23 @@ +package main + +import ( + "context" + "testing" +) + +func TestClosedStreamIsNotRearmed(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + ch := make(chan string) + close(ch) + m := &model{ctx: ctx, cancel: cancel, events: ch, history: newHistory(32), width: 80, height: 24} + msg := m.Init()() + _, cmd := m.Update(msg) + if !m.ended || cmd != nil { + t.Fatal("closed stream re-armed") + } + _, cmd = m.Update(lineMsg("late")) + if cmd != nil || m.history.next != 0 { + t.Fatal("late event revived closed stream") + } +} diff --git a/.agents/skills/charm-tui/examples/worked/cmd/tail/stream.go b/.agents/skills/charm-tui/examples/worked/cmd/tail/stream.go new file mode 100644 index 000000000..7f5ce81a1 --- /dev/null +++ b/.agents/skills/charm-tui/examples/worked/cmd/tail/stream.go @@ -0,0 +1,40 @@ +package main + +import ( + "context" + "fmt" + "time" +) + +// Every send and wait participates in the same root lifetime. The bounded +// channel provides backpressure; records are not dropped to keep drawing fast. +func produce(ctx context.Context, count int, interval time.Duration) <-chan string { + ch := make(chan string, 16) + go func() { + defer close(ch) + ticker := time.NewTicker(interval) + defer ticker.Stop() + for i := 1; i <= count; i++ { + select { + case <-ctx.Done(): + return + case <-ticker.C: + } + line := fmt.Sprintf("event %03d · worker completed a unit of work", i) + select { + case <-ctx.Done(): + return + case ch <- line: + } + } + }() + return ch +} +func receive(ctx context.Context, ch <-chan string) (string, bool) { + select { + case <-ctx.Done(): + return "", false + case line, ok := <-ch: + return line, ok + } +} diff --git a/.agents/skills/charm-tui/examples/worked/cmd/tail/stream_test.go b/.agents/skills/charm-tui/examples/worked/cmd/tail/stream_test.go new file mode 100644 index 000000000..1d12c7439 --- /dev/null +++ b/.agents/skills/charm-tui/examples/worked/cmd/tail/stream_test.go @@ -0,0 +1,47 @@ +package main + +import ( + "context" + "testing" + "time" +) + +func TestClosedChannelAndBufferedRecord(t *testing.T) { + ch := make(chan string, 1) + ch <- "last" + close(ch) + if s, ok := receive(context.Background(), ch); !ok || s != "last" { + t.Fatal("lost last buffered record") + } + if _, ok := receive(context.Background(), ch); ok { + t.Fatal("closed stream looked live") + } +} +func TestReceiveCancellationUnblocks(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + ch := make(chan string) + done := make(chan bool, 1) + go func() { _, ok := receive(ctx, ch); done <- ok }() + cancel() + select { + case ok := <-done: + if ok { + t.Fatal("cancelled receive returned a record") + } + case <-time.After(time.Second): + t.Fatal("receive leaked") + } +} +func TestProducerCancellationClosesStream(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + ch := produce(ctx, 1_000, time.Hour) + cancel() + select { + case _, ok := <-ch: + if ok { + t.Fatal("unexpected record") + } + case <-time.After(time.Second): + t.Fatal("producer leaked") + } +} diff --git a/.agents/skills/charm-tui/examples/worked/go.mod b/.agents/skills/charm-tui/examples/worked/go.mod new file mode 100644 index 000000000..fbe014df9 --- /dev/null +++ b/.agents/skills/charm-tui/examples/worked/go.mod @@ -0,0 +1,11 @@ +module example.com/charm-tui-worked + +go 1.24.2 + +require ( + charm.land/bubbles/v2 v2.2.1 + charm.land/bubbletea/v2 v2.0.9 + charm.land/lipgloss/v2 v2.0.6 + github.com/charmbracelet/x/ansi v0.11.8 + github.com/charmbracelet/x/term v0.2.2 +) diff --git a/.agents/skills/charm-tui/examples/worked/internal/display/bounds.go b/.agents/skills/charm-tui/examples/worked/internal/display/bounds.go new file mode 100644 index 000000000..e4b07599a --- /dev/null +++ b/.agents/skills/charm-tui/examples/worked/internal/display/bounds.go @@ -0,0 +1,42 @@ +// Package display holds small rendering helpers, not an application framework. +package display + +import ( + "strings" + "unicode" +) + +// BodyRows receives already-measured chrome heights, not guessed constants. +func BodyRows(total, header, footer int) int { + return max(0, max(0, total)-max(0, header)-max(0, footer)) +} + +// Window keeps the current row visible and returns a half-open item range. +// It only applies to fixed-height, one-line rows. +func Window(total, cursor, top, height int) (int, int) { + if total <= 0 || height <= 0 { + return 0, 0 + } + cursor = min(max(0, cursor), total-1) + top = min(max(0, top), max(0, total-height)) + if cursor < top { + top = cursor + } + if cursor >= top+height { + top = cursor - height + 1 + } + return top, min(total, top+height) +} + +// SingleLine accepts plain data, not trusted ANSI. It neutralizes terminal +// controls by replacing every C0/C1 control with a space. Escape parameters +// remain visible text. This is deliberately not an ANSI-preserving sanitizer +// or a Unicode spoofing defense. Application styling is added AFTER this call. +func SingleLine(s string) string { + return strings.Map(func(r rune) rune { + if unicode.IsControl(r) || r == '\u2028' || r == '\u2029' { + return ' ' + } + return r + }, strings.ToValidUTF8(s, "\uFFFD")) +} diff --git a/.agents/skills/charm-tui/examples/worked/internal/display/bounds_test.go b/.agents/skills/charm-tui/examples/worked/internal/display/bounds_test.go new file mode 100644 index 000000000..06067035a --- /dev/null +++ b/.agents/skills/charm-tui/examples/worked/internal/display/bounds_test.go @@ -0,0 +1,64 @@ +package display + +import ( + "strings" + "testing" + "unicode" + "unicode/utf8" +) + +func TestBodyRows(t *testing.T) { + for _, c := range []struct{ total, header, footer, want int }{ + {24, 2, 3, 19}, {2, 2, 3, 0}, {0, 0, 0, 0}, {-1, 2, 1, 0}, {5, -1, -1, 5}, + } { + if got := BodyRows(c.total, c.header, c.footer); got != c.want { + t.Fatalf("%+v: %d", c, got) + } + } +} + +func TestWindowBoundsExhaustive(t *testing.T) { + for n := 0; n < 35; n++ { + for h := 0; h < 15; h++ { + for cursor := -1; cursor < n+2; cursor++ { + for top := -1; top < n+2; top++ { + lo, hi := Window(n, cursor, top, h) + if lo < 0 || hi < lo || hi > n || hi-lo > h { + t.Fatalf("n=%d h=%d: [%d,%d)", n, h, lo, hi) + } + c := min(max(0, cursor), n-1) + if n > 0 && h > 0 && (c < lo || c >= hi) { + t.Fatal("cursor outside window") + } + } + } + } + } +} + +func TestWindowFormatsOnlyVisibleRows(t *testing.T) { + lo, hi := Window(100_000, 72_004, 72_000, 12) + count := 0 + for i := lo; i < hi; i++ { + count++ + } // This is the render loop's only row range. + if count != 12 { + t.Fatalf("formatted %d rows", count) + } +} + +func TestSingleLineControlsAndUnicode(t *testing.T) { + input := "東京 e\u0301 👩‍💻\x1b]52;c;payload\a\n\r\t\u009b31m\u2028\u2029\xff" + got := SingleLine(input) + if !utf8.ValidString(got) { + t.Fatal("invalid UTF-8") + } + for _, r := range got { + if unicode.IsControl(r) || r == '\u2028' || r == '\u2029' { + t.Fatalf("control %U", r) + } + } + if !strings.Contains(got, "東京 e\u0301 👩‍💻") { + t.Fatal("damaged ordinary Unicode") + } +} diff --git a/.agents/skills/charm-tui/examples/worked/internal/display/render.go b/.agents/skills/charm-tui/examples/worked/internal/display/render.go new file mode 100644 index 000000000..1696a1fa6 --- /dev/null +++ b/.agents/skills/charm-tui/examples/worked/internal/display/render.go @@ -0,0 +1,72 @@ +package display + +import ( + "charm.land/lipgloss/v2" + "github.com/charmbracelet/x/ansi" + "strings" +) + +// Line clips trusted, possibly application-styled text to display cells. +func Line(s string, width int) string { + if width <= 0 { + return "" + } + return ansi.Truncate(s, width, "…") +} + +// Row spends width on identity before optional metadata. Its prefix has the +// same width in both states, so moving the cursor never shifts the label. +func Row(label, detail string, width int, current bool) string { + if width <= 0 { + return "" + } + prefix := " " + if current { + prefix = "> " + } + if width <= 2 { + return Line(prefix, width) + } + room := width - 2 + metadata := "" + if width >= 48 && detail != "" { + metadata = Line(SingleLine(detail), 18) + room -= ansi.StringWidth(metadata) + 2 + } + name := Line(SingleLine(label), room) + body := prefix + name + if metadata != "" { + body += strings.Repeat(" ", max(0, room-ansi.StringWidth(name))) + " " + metadata + } + return lipgloss.NewStyle().Bold(current).Render(body) +} + +// Panel's argument is the OUTER width with zero margins. Padding and borders +// are already inside Width in Lip Gloss v2. No double frame subtraction. +func Panel(content string, outerWidth int) string { + if outerWidth <= 0 { + return "" + } + box := lipgloss.NewStyle().Border(lipgloss.NormalBorder()).Padding(0, 1) + frame := box.GetHorizontalFrameSize() + if outerWidth <= frame { + return Line(strings.ReplaceAll(content, "\n", " "), outerWidth) + } + lines := strings.Split(content, "\n") + for i := range lines { + lines[i] = Line(lines[i], outerWidth-frame) + } + return box.Width(outerWidth).Render(strings.Join(lines, "\n")) +} + +// FillRows fixes a one-line row region's height without rendering hidden items. +func FillRows(lines []string, width, height int) string { + if height <= 0 || width <= 0 { + return "" + } + out := make([]string, height) + for i := 0; i < min(len(lines), height); i++ { + out[i] = Line(lines[i], width) + } + return strings.Join(out, "\n") +} diff --git a/.agents/skills/charm-tui/examples/worked/internal/display/render_test.go b/.agents/skills/charm-tui/examples/worked/internal/display/render_test.go new file mode 100644 index 000000000..0ce2ae195 --- /dev/null +++ b/.agents/skills/charm-tui/examples/worked/internal/display/render_test.go @@ -0,0 +1,70 @@ +package display + +import ( + "charm.land/lipgloss/v2" + "github.com/charmbracelet/x/ansi" + "strings" + "testing" + "unicode/utf8" +) + +func TestRowAndPanelStayWithinCellBudget(t *testing.T) { + labels := []string{"prod-api-01", "東京サーバー", "e\u0301", "👩‍💻", strings.Repeat("x", 200)} + for w := 0; w <= 100; w++ { + for _, label := range labels { + for _, selected := range []bool{false, true} { + for _, got := range []string{Row(label, "long metadata here", w, selected), Panel(label, w)} { + if !utf8.ValidString(got) || lipgloss.Width(got) > w { + t.Fatalf("width=%d: %q", w, got) + } + } + } + } + } +} + +func TestResponsiveMetadataAndExactPanelWidth(t *testing.T) { + if strings.Contains(ansi.Strip(Row("alpha", "EU-WEST", 24, false)), "EU-WEST") { + t.Fatal("metadata should disappear") + } + if !strings.Contains(ansi.Strip(Row("alpha", "EU-WEST", 60, false)), "EU-WEST") { + t.Fatal("metadata should fit") + } + if got := lipgloss.Width(Panel("alpha", 40)); got != 40 { + t.Fatalf("outer width %d", got) + } +} + +func TestRowRefactorPreservesLiteralPrefixAndLabel(t *testing.T) { + // A before/after contract for the two previously duplicated branches. + for _, label := range []string{"alpha", "東京", "e\u0301"} { + for _, active := range []bool{false, true} { + before := " " + label + if active { + before = "> " + label + } + if got := ansi.Strip(Row(label, "", 32, active)); got != before { + t.Fatalf("%q != %q", got, before) + } + } + } +} + +func TestRowRefactorMatchesPreviousRenderingByteForByte(t *testing.T) { + for _, width := range []int{3, 10, 32, 60} { + for _, label := range []string{"alpha", "東京", "e\u0301", strings.Repeat("x", 100)} { + for _, current := range []bool{false, true} { + name := ansi.Truncate(label, width-2, "…") + var before string + if current { + before = lipgloss.NewStyle().Bold(true).Render("> " + name) + } else { + before = lipgloss.NewStyle().Bold(false).Render(" " + name) + } + if got := Row(label, "", width, current); got != before { + t.Fatalf("width=%d current=%v: %q != %q", width, current, got, before) + } + } + } + } +} diff --git a/.agents/skills/charm-tui/references/architecture-and-effects.md b/.agents/skills/charm-tui/references/architecture-and-effects.md new file mode 100644 index 000000000..d4d233d09 --- /dev/null +++ b/.agents/skills/charm-tui/references/architecture-and-effects.md @@ -0,0 +1,121 @@ +# Architecture and effects + +[Async search](../examples/WORKED-EXAMPLES.md#4-implement-latest-query-wins-search), [follow-tail behavior](../examples/WORKED-EXAMPLES.md#6-keep-a-streaming-view-from-jumping), and [subscription closure](../examples/WORKED-EXAMPLES.md#7-stop-subscriptions-without-leaks-or-busy-loops) now have complete implementations and regression tests. + +## The useful boundary is ownership, not a model count + +Bubble Tea separates state, message handling, effects, and rendering. Its command model lets work return a message without blocking interaction. [S01](sources.md#s01) [S04](sources.md#s04) + +There are two useful composition patterns: + +**Root plus child models.** A child owns a coherent reusable interaction, has its own update method, and returns a command. The root routes events, changes pages, and allocates space. Glow uses this approach for its listing and document view. [S05](sources.md#s05) + +**Root plus imperative components.** The root owns event routing and calls methods such as `ScrollBy`, `SetItems`, or `SetFocused` on simpler helpers. Crush's UI guidance describes this pattern. The helpers need not each become a complete Elm-style model. [S08](sources.md#s08) + +Choose the smaller approach that makes ownership legible in the existing project. Separate files can make a large update function readable without inventing an interface hierarchy. Extract genuinely independent interactions; do not create a component framework because a screen has several rectangles. + +## Commands return facts; Update decides what they mean + +An original integration sketch for v2: + +```go +// Row is an application-owned immutable result value. +type loadedMsg struct { + generation uint64 + rows []Row + err error +} + +// search must honor ctx; it must not read or write the live UI model. +func loadCmd(ctx context.Context, generation uint64, query string, + search func(context.Context, string) ([]Row, error), +) tea.Cmd { + return func() tea.Msg { + rows, err := search(ctx, query) + return loadedMsg{generation: generation, rows: rows, err: err} + } +} +``` + +Imports are `context` and `tea "charm.land/bubbletea/v2"`. The surrounding application's model and `Row` type are intentionally not prescribed. This sketch is not a complete runnable program. + +Capture query, ID, and configuration before constructing the closure. Copy mutable collections when the producer will continue changing them. A value-receiver method does not deep-copy maps, slices, or pointed-to objects. Returning a message is a transfer of ownership or a promise not to mutate the payload afterward. + +Apply results only in the owning update path. For a child, retain **both** returned values: + +```go +var cmd tea.Cmd +m.input, cmd = m.input.Update(msg) +return m, cmd +``` + +When other commands also need to run, collect them rather than overwriting `cmd`. Inspect methods such as `Focus`, spinner updates, and list updates for returned commands; silently dropping one can break blinking, loading, or deferred work. + +Cheap synchronous transitions belong directly in Update. Setting `showHelp`, changing a focus enum, or moving an in-memory cursor rarely requires an asynchronous message round trip. + +## Search, debounce, cancellation, and stale completions + +Treat intent changes and request starts as different events. Correct ordering for latest-query-wins behavior is: + +```text +query changes: + increment generation immediately + cancel previous in-flight context, if any + record new query; invalidate any obsolete error/loading state + clear rows or explicitly retain them as stale + schedule debounce(generation), if debounce is justified + +debounce(g): + ignore unless g equals current generation + begin one request with its own cancellable context + set phase to loading + +result(g, rows, error): + ignore unless g equals current generation AND request is active + release that request's cancellation resources + apply success or failure; stop its activity indicator +``` + +Why invalidate before debounce? Request A can finish after the user types query B but before B's timer fires. Waiting until B starts leaves a window in which A is incorrectly accepted. + +Guard errors and activity flags as carefully as rows. A stale failure must not replace fresh success; a stale completion must not stop the spinner for a newer request. A generation number is a UI correctness guard, not a resource limit: cancellation and bounded backend concurrency are still necessary. + +Every new retry or refresh needs fresh identity even when the query text is unchanged. A user can leave and revisit the same screen; include the screen/session lifetime in the ownership scheme or ensure the generation survives that transition. On shutdown cancel the root context, reject further results, and wait for owned workers when their lifecycle requires it. + +The [contract exercise](../examples/contracts/README.md) demonstrates intent invalidation and acceptance rules with deterministic tests. It does not test a real network backend or guarantee cancellation of code that ignores its context. + +## Batch is concurrency, not dependency injection + +`tea.Batch` runs independent commands without an ordering guarantee. `tea.Sequence` sequences command execution. Neither should be used to pretend that command B can read a model that command A has just updated: results still have to be processed through the event loop. [S01](sources.md#s01) + +If B depends on A's returned ID, start B from the handler for A's result and capture the ID there. If two effects are independent, batch them. If the same mutable collection is shared, making execution appear sequential is not a substitute for an ownership policy. + +Do not wrap cheap internal coordination in commands merely to make everything look asynchronous. Charm's command guidance explicitly distinguishes effects from internal message routing. [S04](sources.md#s04) + +## Subscriptions and timers need lifetimes + +For an external stream, a command can wait for one event and return a typed message. On receipt, process that event and return the next wait command. Handle channel closure as a terminal condition. Include cancellation in the wait; an unbounded receive can outlive the view or program. + +Start only one consumer per intended subscription. Accidentally re-running `Init` on every refresh can create overlapping readers or tick loops. Cancellation ownership must remain at the screen/session/application level, not disappear when a local helper returns. + +Glow's file discovery loop illustrates a one-event command that is re-armed by the update path and reports a closed channel separately. Its particular implementation is evidence for the pattern, not a production cancellation template to copy verbatim. [S05](sources.md#s05) + +For custom timers, inject or model time in tests. A one-shot timer must be re-armed intentionally. Component timers have their own identity conventions; preserve them rather than inventing a second tick loop. Disable unnecessary activity while idle, hidden, or in a reduced-motion mode. + +## Streaming and scrolling + +Separate the durable event stream from the presentation rate. It is reasonable to coalesce redraw notifications or replace intermediate progress values; it is not reasonable to silently drop completed tool results, log records promised to the user, or state transitions. + +Use explicit follow-tail state. When the user scrolls away, hold their anchor as new content arrives and show a new-output indication. A “jump to latest” action restores following. For variable-height items, preserve an item ID plus within-item offset when feasible rather than a brittle global line number. + +Set a retention policy for long-running processes. Measure rendering cost for a large transcript and widths that cause substantial wrapping. Avoid repeatedly formatting the whole history or measuring its complete height to answer a yes/no overflow question. + +Crush's inspected list has bounded overflow checks, width-dependent caches, and incremental prewarming. Its source differs from an older description in its own UI instructions about whether a list-level cache exists. Prefer code at the inspected revision over an architecture note when they disagree. [S09](sources.md#s09) [S08](sources.md#s08) + +## Errors and side-effecting operations + +A latest-query-wins policy is suitable for display-only search. It is not automatically suitable for writes. Cancelling a UI request may not cancel an operation already accepted by a server. Track durable operation IDs and reconcile status rather than calling a dismissed dialog proof of cancellation. + +Prevent accidental duplicate submissions while a write is active. Make retry semantics explicit: safe repeat, idempotency key, or inspect-before-retry. Preserve enough context to explain which operation failed without exposing secrets in logs or terminal content. + +Keep recoverable operation errors near the affected control. Reserve an application-fatal state for an inability to continue. Debug logs should go to a file or separate sink while the TUI owns its output stream. diff --git a/.agents/skills/charm-tui/references/case-studies.md b/.agents/skills/charm-tui/references/case-studies.md new file mode 100644 index 000000000..25ebdf7bd --- /dev/null +++ b/.agents/skills/charm-tui/references/case-studies.md @@ -0,0 +1,49 @@ +# Case studies: observation → lesson → limit + +The material below comes from selected source files and official documentation, not a claim that the complete applications were executed or audited. Revisions and exact inspection scope are in the [source ledger](sources.md). + +## Glow: navigation as an explicit state machine + +**Observed.** The root distinguishes file-list and document states, composes listing/pager children, propagates size changes, and routes commands returned by children. An active filter can receive `q` rather than having the root interpret it as quit. Some background messages are deliberately routed to the listing even while the document view is visible. [S05](sources.md#s05) + +**Lesson.** Treat “which screen is visible?” and “which component owns this result?” as separate questions. Route keys by interaction context and background results by lifecycle ownership. Keep back navigation and document unloading explicit. + +**Limit.** Do not copy every startup, file-reading, or terminal-rendering decision. The source is a real evolving application, not a minimal correctness specification. Its channel loop illustrates re-arming, but a new implementation still needs its own cancellation contract. + +## Gum: a small interaction can be a complete product + +**Observed.** Filter has distinct cursor and selected-item state, focus-dependent bindings, styled match ranges, and inline/full-screen behavior. Its command wrapper builds components, reads candidate input, renders to stderr, receives the final model, and emits the selected value afterward. [S06](sources.md#s06) [S07](sources.md#s07) + +**Lesson.** Shell composability is UX. A narrow picker can be polished without becoming a persistent application shell. Separate canonical values, decorated labels, live UI, and final output. Reuse input and help behavior while keeping a task-specific presentation. + +**Limit.** Small-app implementation choices do not automatically scale. The inspected filter renders candidates into viewport content and mutates that viewport during View. Those are observations, not recommendations to render every row or mutate UI state from every View. Test empty-result actions and large candidate sets independently. + +## Crush: central coordination without a model for every region + +**Observed.** Its UI development notes describe a single root model with targeted helper methods, explicit focus, stacked dialogs, semantic styles, and a hybrid rectangular/string rendering pipeline. The actual list implementation has item caches, width-sensitive invalidation, complete-height caching, bounded overflow detection, and incremental prewarming. [S08](sources.md#s08) [S09](sources.md#s09) + +**Lesson.** A sophisticated TUI can centralize event ownership while keeping display helpers simple. Optimize expensive transcript work around visible content and explicit invalidation. Ask “does this overflow?” without always computing an exact full-history height. + +**Limit and source conflict.** At the inspected commit, `AGENTS.md` says there is no list-level cache, but `list.go` contains one. The code is the stronger evidence for that implementation detail. Documentation can preserve a useful principle while lagging a refactor. Do not repeat the stale claim or transplant Crush's full subsystem into a twenty-row picker. + +## Soft Serve: help and geometry are part of navigation + +**Observed.** The SSH root has active-page state distinct from loading/error/ready state. Help is derived from the active page and filter status. Layout accounts for the rendered footer, and error presentation keeps recovery controls available. [S10](sources.md#s10) + +**Lesson.** Help belongs to the current interaction and consumes real geometry. A terminal application served remotely also needs an intentional session boundary; do not share mutable screen state or terminal capabilities across users. + +**Limit.** This was a selected root-file read, not a security review of the SSH service. Do not infer authentication or concurrency guarantees from a UI example. Avoid copying a whole page framework when a small local tool has only one screen. + +## Huh: accessibility can change the interaction model + +**Observed.** Huh documents forms, validation, themes, and an accessible mode that uses ordinary prompts instead of its normal TUI presentation. [S11](sources.md#s11) + +**Lesson.** Accessibility is not only a different shade of gray. For a bounded data-entry task, a sequential prompt flow can be a valuable first-class interface. Validation should explain what needs fixing and keep the user in control. + +**Limit.** A form abstraction is not automatically the right choice for a streaming log, repository browser, or custom picker. The studied Huh material was official documentation, not its full implementation. + +## Cross-application synthesis + +The recurring quality is not a mandatory color or border. It is a clear task, predictable input ownership, concise feedback, useful defaults, and respect for the terminal and shell around the application. The engineering counterpart is a small number of state owners, effects with lifetimes, cell-correct layout, and evidence from actual interaction tests. + +Apply these ideas as judgment, not as a rewrite mandate. Preserve a working product's distinctive interaction and visuals while simplifying duplicated plumbing underneath it. diff --git a/.agents/skills/charm-tui/references/design-and-interaction.md b/.agents/skills/charm-tui/references/design-and-interaction.md new file mode 100644 index 000000000..7d3dbf8c1 --- /dev/null +++ b/.agents/skills/charm-tui/references/design-and-interaction.md @@ -0,0 +1,117 @@ +# Design and interaction + +For a concrete build, use [the compact picker](../examples/WORKED-EXAMPLES.md#1-build-a-compact-picker). For a bug fix, use [the focus and modal walkthrough](../examples/WORKED-EXAMPLES.md#2-fix-search-keys-and-modal-fall-through). + +These are design recommendations synthesized from the studied applications, not a mandatory Charm visual style. For observations and exact evidence, see the [case studies](case-studies.md). + +## Design the smallest complete loop + +Start with the user outcome, not the component catalogue. For a server picker the loop might be: identify candidates, narrow the set, inspect health, connect. Every persistent screen element should support one of those steps or explain the current state. + +An inline prompt should leave the surrounding shell comprehensible. A full-screen browser can spend more space on context and inspection because the user intends to stay. Do not use a full-screen dashboard for a yes/no question or hide a complex monitoring workflow inside a one-line prompt. + +Gum's filter supports an inline/fixed-height presentation and a full-screen branch. Its command wrapper also separates interactive rendering from result production. The transferable idea is a scoped interaction that remains useful in a larger shell workflow. [S06](sources.md#s06) [S07](sources.md#s07) + +A useful design note before implementation is: + +```text +Task: choose a server and connect. +Primary flow: type to filter -> move cursor -> inspect health -> accept. +Cancel: exit without emitting a server ID. +Output: one stable server ID, not the displayed label. +Preserve: existing search semantics, indicators, counters, animation, and keys. +Small layout: hide secondary columns; retain identity, health, and accept/cancel. +``` + +This is an example of the note's content, not a requirement to add a new file to every repository. + +## Give the screen a reading order + +A practical hierarchy is context first, work second, feedback third, controls last. Title and controls should be discoverable but not compete with the data. + +An illustrative picker, not a prescribed theme: + +```text + Connect 2 of 18 + Filter: prod_ + + > prod-api-01 ready 23 ms + prod-api-02 connecting -- + + enter connect esc cancel ? help +``` + +The second number describes matching or total candidates only if that relationship is clear. Missing latency is not `0 ms`. A highlighted row is not automatically an accepted selection. While probing, allow the user to move or cancel; show pending work without pretending it has completed. + +At a smaller width, simplify structure rather than scale all labels into fragments: + +```text + Connect 2/18 + > prod-api-01 + ready · 23 ms + + enter connect · esc cancel +``` + +Do not let an automatic switch discard the query, move the cursor to a different ID, or clear multi-selection. + +## Make state readable without a legend + +| State | Useful presentation | Common failure | +| --- | --- | --- | +| Initial load | What is loading and how to cancel | A spinner with no object or action | +| Refresh | Existing data plus refreshing/stale indicator | Blanking useful content every refresh | +| Truly empty dataset | What is absent and how to create/import/retry | “No results” with no context | +| No filter matches | Query context and a clear-filter action | An empty list that still accepts Enter | +| Recoverable failure | Operation, concise reason, retry/back | Full-screen fatal error for a transient issue | +| Destructive action | Exact target and consequence | A generic “Are you sure?” | +| Completed action | Stable confirmation or returned value | Disappearing feedback before it can be read | + +Avoid boolean combinations that can accidentally render “loading,” “failed,” and “success” together. Model lifecycle states clearly, while retaining separate flags only for genuinely independent concerns. + +Progress bars need a meaningful denominator. Otherwise use an activity indicator and useful counts or elapsed time. An animation should stop when its operation stops. Do not animate the entire screen to prove that it is alive. + +## Focus is a spatial and behavioral promise + +The focused control should be visually recognizable. The same visual emphasis should not mean focus in one place and danger in another. Multi-selection needs a separate mark from the cursor; keep marker widths stable so text does not jump between rows. + +Define navigation per mode. An example policy is: + +```text +Normal: arrows or j/k move; / enters search; Enter accepts current item. +Search: printable text edits; arrows may navigate results if documented. + Escape leaves search; a subsequent Escape cancels the picker. +Modal: only modal controls react; closing restores previous focus. +``` + +This is not a universal keymap. A type-to-filter picker may start in search and never need a separate normal mode. Preserve an existing convention rather than force a Vim-like mode onto it. + +Glow explicitly protects an active filter from its ordinary `q` quit action. Gum disables normal-mode navigation bindings while search is focused. Both are evidence that keyboard shortcuts must respect editing context. [S05](sources.md#s05) [S06](sources.md#s06) + +Do not consume the same key both globally and locally. Enter that dismisses an error should not also open the first item. Escape that closes a dialog should not also quit the application. If Ctrl+C first cancels work instead of quitting, make that policy observable and test repeated presses. + +## Teach controls at the point of use + +Show the few likely actions near the active task; put the complete reference behind a help action. Derive both from actual enabled bindings where feasible. Hide or explicitly disable controls that cannot work in the current state. + +Soft Serve's help depends on the active page and whether filtering is occurring; it also measures its rendered footer for layout. Help is an active part of the interaction and geometry, not a fixed decorative string. [S10](sources.md#s10) + +Use action verbs: “open,” “connect,” “retry,” “clear filter,” “cancel.” “Submit” may be appropriate for a form, but it often says less than the actual operation. Show the target or scope for a destructive action. Reserve a persistent status area when frequent updates would otherwise make content move. + +## Develop a theme from semantic roles + +A small theme may define foreground, muted foreground, accent, border, focused row, selected mark, success, warning, and error. Derive component styles from these roles. Let a product's existing identity guide the actual colors. + +Prefer the terminal's own background unless full-surface coloring serves a clear purpose. Check muted text on both light and dark backgrounds; “muted” must still be legible. Test a monochrome rendering: cursor marks, labels, and layout should preserve meaning after color disappears. + +Borders consume cells and add noise. Use one around a coherent interaction, or a separator between independent regions, before boxing every field. Prefer padding inside a frame to margins that accidentally push content past it. Use bold or contrast for a few hierarchy levels, not every heading, badge, and value. + +A mascot or accent animation can make a tool memorable. Keep it small, optional when appropriate, and separate from the user's input cursor. Do not remove an existing distinctive feature under the guise of code simplification; reduce implementation duplication rather than behavior. + +## Accessibility and terminal-native operation + +Keep the whole workflow usable with a keyboard and without special fonts. Use text alternatives for icons, color, and changing animation. Avoid stealing conventional copy/paste combinations without a strong reason. Mouse support should add convenience, not become the only way to reach an action. + +A no-color TUI can still be difficult for assistive software because it repeatedly redraws and repositions text. Huh provides `WithAccessible(true)`, which changes interaction into ordinary prompts; that is a distinct capability from changing a palette. Offer a comparable plain or noninteractive path where the application needs one. [S11](sources.md#s11) + +Treat confirmation, cancellation, and recovery as part of polish. A pretty interface that cannot be safely cancelled, piped, or read at a small size is not finished. diff --git a/.agents/skills/charm-tui/references/layout-and-rendering.md b/.agents/skills/charm-tui/references/layout-and-rendering.md new file mode 100644 index 000000000..769d4bc42 --- /dev/null +++ b/.agents/skills/charm-tui/references/layout-and-rendering.md @@ -0,0 +1,95 @@ +# Layout and rendering + +See [the responsive layout walkthrough](../examples/WORKED-EXAMPLES.md#3-fit-a-narrow-terminal-without-losing-identity) for complete row/panel helpers and tests, and [the refactor walkthrough](../examples/WORKED-EXAMPLES.md#8-reduce-code-without-redesigning-the-interface) for behavior-preserving changes. + +## Allocate actual rectangles + +For each component, define whether an input size means total allocation or content area. Prefer parent-owned total allocations and named helpers for frame arithmetic. Rendering, clipping, scrolling, and mouse hit testing must agree on the same bounds. + +Compute header/footer heights from their rendered content at the current width. Help may wrap; an error may add a line; a prompt has a visible prefix. Subtract actual chrome before allocating the body. Do not subtract a nominal height and then render additional lines outside it. + +Use a defined tiny-terminal strategy when the chrome alone cannot fit. It may be a compact status or “resize to continue” view, but cancellation should remain responsive. Initial zero dimensions must not panic or trigger expensive rendering with invalid widths. + +Read-only layout values can be recalculated cheaply. Expensive reflow belongs behind explicit invalidation rather than happening on every spinner tick. A height-only resize need not invalidate width-dependent text wrapping. + +## Lip Gloss v2 box arithmetic + +The v2 API defines `Width(n)` as block width before margins; padding and borders consume space within that width. The frame helpers include their documented frame constituents, so distinguish internal frame from external margins. [S03](sources.md#s03) + +A worked example with **zero margins**: + +```go +// v2 integration sketch. caller guarantees outerWidth >= the frame width. +box := lipgloss.NewStyle(). + Border(lipgloss.NormalBorder()). + Padding(0, 2) + +outerWidth := 40 +innerWidth := outerWidth - box.GetHorizontalFrameSize() // 40 - 6 = 34 +child := ansi.Truncate(label, innerWidth, "…") +rendered := box.Width(outerWidth).Render(child) +``` + +Imports: `charm.land/lipgloss/v2` and `github.com/charmbracelet/x/ansi`. In this particular zero-margin style the frame is the two border cells plus four padding cells. **Do not call `box.Width(innerWidth)` after subtracting the frame**; that makes the outer box smaller a second time. + +With external margins, use explicit arithmetic: + +```text +allocated width = external margins + border-box width +content width = border-box width - borders - padding +``` + +Alternatively remove margins from the inner component style and let the parent own spacing. If the terminal is narrower than the frame itself, omit the decorative frame or choose the tiny view; clamping content to zero does not make an oversized border disappear. + +Apply the same distinction to height. Confirm rendered dimensions in tests, including long unbroken tokens and styled child strings. A requested width is not permission to skip checking the actual output under the target version and configuration. + +## Use terminal cells, not source-string length + +Bytes, Unicode code points, grapheme clusters, and terminal cells are not interchangeable. ANSI control sequences add bytes without normal visible width. East Asian characters, combining marks, and emoji further separate those measures. + +Use `lipgloss.Width`/`Height` to measure styled blocks and `ansi.StringWidth`, `ansi.Truncate`, or `ansi.Cut` for display-aware operations. For editing, use the component's text handling rather than reimplementing cursor motion with byte offsets. The ANSI helpers are documented to handle escape sequences and display-width operations. [S03](sources.md#s03) [S16](sources.md#s16) + +Do not feed a fuzzy library's byte offsets directly into a display-cell range API. Gum explicitly converts match positions before styling the display. That is evidence for a general rule: track each API's index unit and convert deliberately. [S06](sources.md#s06) + +Useful fixtures include: + +```text +ASCII: prod-api-01 +CJK: 東京サーバー +Combining: é +Emoji: 👩‍💻 +Wide path: /very/long/unbroken/component/name/with/no/spaces +ANSI: the same labels with application-owned styling +``` + +The combining example contains an `e` followed by a combining accent. Include tabs, a trailing newline, multi-line data, and mixed-direction text when those inputs are relevant. Terminal/font width disagreements can remain; test supported environments instead of asserting that every emoji occupies a universal width. + +## Keep style, data, and control sequences distinct + +Store canonical labels and IDs separately from their decorated form. Styling should not change the identity used for selection, sorting, filtering, or output. Do not sort ANSI-decorated strings or return the currently rendered row as a machine ID. + +ANSI-aware clipping preserves control sequences; that is useful for trusted styles, but it is **not a security policy for untrusted text**. Before displaying remote names, logs, or filenames, decide how to handle control characters and escape sequences. Prefer plain-text data with application-owned styling. When accepting third-party ANSI, use an explicit allowlist rather than assuming color-preserving helpers neutralize terminal commands. + +Apply styles to logical segments consistently. When composing already styled text, test resets and background continuity; an embedded reset can change following text. Prefer semantic reusable styles to scattered numeric color literals. + +Color detection and output encoding belong at the terminal boundary. In v2, Lip Gloss styles produce full-fidelity output and downsampling happens at the output layer; Bubble Tea handles it for its own renderer. For standalone styled output, use the documented writer helpers. [S03](sources.md#s03) + +Use a reasonable theme before a background-color response arrives, then update through the event loop. Do not synchronously read terminal input from View to discover a color. Session-specific terminal capabilities must not become mutable global state in an SSH service. + +## Responsive composition beats indiscriminate truncation + +Choose an explicit priority for available width. A repository browser might retain the name and status, drop the author column, shorten dates, then switch from side-by-side detail to a separate view. A picker might shorten metadata before its primary identity. + +When clipping identity is unavoidable, provide an inspect action or detail region with the full value. Prefer a stable primary column and aligned metadata over irregular badges. Keep truncation style consistent; do not make selected text wider merely because its prefix changed. + +Measure a pane once and give the same result to its viewport, renderer, and hit regions. For overlays, clamp the dialog to the current viewport, subtract its internal frame once, and draw it last. Resize should not preserve stale mouse rectangles. + +## Hot-path budgeting + +Expensive syntax highlighting and Markdown conversion do not belong in an unconditional View call. Recompute on relevant data, width, or theme changes, then render cached results. Protect asynchronous rendering with the same generation rules as search. + +A render cache must specify its key, invalidation events, maximum retained size, and whether results can be shared. Text width, theme, content revision, expansion state, focus/highlight, and selection overlays may all affect output. Cache only the stable layer when a cheap dynamic overlay changes each frame. + +Crush's inspected list invalidates its render cache on width change and keeps it on height-only changes. Its complete-height computation is cached but still potentially expensive after invalidation; its overflow path can stop early. The lesson is to ask the smallest question needed, not to copy an entire chat-list subsystem into a small picker. [S09](sources.md#s09) + +Benchmark representative data and a resize/scroll sequence before adding virtualized layout or a screen-buffer renderer. Simple string composition is a good default. Ultraviolet or layered composition can be appropriate for complex overlays and rectangular drawing; adopt it because the application needs those capabilities, not because another Charm app has them. diff --git a/.agents/skills/charm-tui/references/sources.md b/.agents/skills/charm-tui/references/sources.md new file mode 100644 index 000000000..3fe597ba6 --- /dev/null +++ b/.agents/skills/charm-tui/references/sources.md @@ -0,0 +1,167 @@ +# Source ledger + +Research date: **2026-09-23**. Primary sources only. Application revisions below are the commit-pinned URLs returned during inspection. A GitHub file's content SHA is not interchangeable with a repository commit; only repository revisions are used in these permalinks. + +This is an independent synthesis. Observed implementation details, documented APIs, and recommended practices are distinguished in the other references. No upstream application was built, executed, or exhaustively audited during this research. Public documentation may change; inspect the target repository's pinned dependencies before using version-sensitive advice. + +## S01 + +**Bubble Tea: current API, upgrade guide, and release.** + +- [API inspected at v2.0.9](https://pkg.go.dev/charm.land/bubbletea/v2@v2.0.9) +- [v2 upgrade guide](https://github.com/charmbracelet/bubbletea/blob/main/UPGRADE_GUIDE_V2.md) +- [v2.0.9 release](https://github.com/charmbracelet/bubbletea/releases/tag/v2.0.9), published 2026-08-19 +- [README and tutorial](https://github.com/charmbracelet/bubbletea) + +Read for model/command/view APIs, input migration, view configuration, and command ordering. The release API independently confirmed the v2.0.9 tag. The upgrade guide was a default-branch snapshot, not pinned to the application's version. + +## S02 + +**Bubbles: catalogue and v2 migration.** + +- [API inspected at v2.2.1](https://pkg.go.dev/charm.land/bubbles/v2@v2.2.1) +- [v2 upgrade guide](https://github.com/charmbracelet/bubbles/blob/main/UPGRADE_GUIDE_V2.md) +- [Component catalogue](https://github.com/charmbracelet/bubbles) + +Read the catalogue, guide introduction and global patterns through the beginning of progress migration. Verified selected concrete v2 input/viewport usage against Gum's source. The displayed documentation publication date was 2026-08-24. Do not treat the abridged comparison table as an exhaustive migration guide. + +## S03 + +**Lip Gloss: layout and v2 style/color model.** + +- [API inspected at v2.0.6](https://pkg.go.dev/charm.land/lipgloss/v2@v2.0.6) +- [Width contract](https://pkg.go.dev/charm.land/lipgloss/v2@v2.0.6#Style.Width) +- [Frame helper](https://pkg.go.dev/charm.land/lipgloss/v2@v2.0.6#Style.GetHorizontalFrameSize) +- [v2 upgrade guide](https://github.com/charmbracelet/lipgloss/blob/main/UPGRADE_GUIDE_V2.md) + +Read layout/color documentation and upgrade material. The displayed documentation publication date was 2026-08-11. Width includes internal border/padding and excludes margins; color handling moved toward output-layer adaptation. This is the source for the skill's version-specific arithmetic, not a CSS analogy. + +## S04 + +**Charm: Commands in Bubble Tea.** + +- [Official engineering article](https://charm.land/blog/commands-in-bubbletea/) + +Read for the purpose of commands, side effects, and avoiding command-based internal message routing. Treat older snippets as conceptual material and translate only after verifying the target APIs. The skill's cancellation and generation protocol is a derived recommendation, not a quotation of this article. + +## S05 + +**Glow root UI.** Revision `6b365eea95f7541d4af441d971010b09f6082a0e`. + +- [ui/ui.go](https://github.com/charmbracelet/glow/blob/6b365eea95f7541d4af441d971010b09f6082a0e/ui/ui.go) + +Read lines 1–465 (the root file): state transitions, key routing, child delegation, theme and size events, view modes, file-discovery commands. The pager/stash internals and specialized renderer were not exhaustively read. + +## S06 + +**Gum filter interaction and rendering.** Revision `7179388031ae67d7f538d001be87d931f1cf5e28`. + +- [filter/filter.go](https://github.com/charmbracelet/gum/blob/7179388031ae67d7f538d001be87d931f1cf5e28/filter/filter.go) + +Read lines 1–270 and 280–525: keys, state, help, rendering, resize, filtering, cursor/selection behavior, and match-position handling. A small intervening portion and the remainder were not needed for the extracted lessons; this was not a complete file audit. + +## S07 + +**Gum command boundary.** Same revision as S06. + +- [filter/command.go](https://github.com/charmbracelet/gum/blob/7179388031ae67d7f538d001be87d931f1cf5e28/filter/command.go) + +Read the command wrapper: component construction, stdin candidates, stderr UI, context ownership, final-model outcome, and result output. This supports shell-composition lessons, not a guarantee of every Gum subcommand's semantics. + +## S08 + +**Crush maintainer UI instructions.** Revision `72654940d9e46961a7d804d536c45761e7084a08`. + +- [internal/ui/AGENTS.md](https://github.com/charmbracelet/crush/blob/72654940d9e46961a7d804d536c45761e7084a08/internal/ui/AGENTS.md) + +Read the architecture, component, dialog, style, and performance guidance. These are maintainer notes, not runtime evidence. The “no list-level cache” statement conflicts with S09 at the same revision; the skill follows the source for that detail. + +## S09 + +**Crush list implementation.** Same revision as S08. + +- [internal/ui/list/list.go](https://github.com/charmbracelet/crush/blob/72654940d9e46961a7d804d536c45761e7084a08/internal/ui/list/list.go) + +Read lines 1–220: fields and cache entries, construction, width-change invalidation, bounded bottom checks, full-height caching, prewarming, and beginning of the overflow method. The whole render/invalidation subsystem was not audited. The initial source segment suffices to establish the cache's existence and stated width dependency. + +## S10 + +**Soft Serve SSH root UI.** Revision `37685d36f5b7bf0e32217ddd7c8e045c57772619`. + +- [pkg/ssh/ui.go](https://github.com/charmbracelet/soft-serve/blob/37685d36f5b7bf0e32217ddd7c8e045c57772619/pkg/ssh/ui.go) + +Read lines 1–300: page/session state, contextual help, sizing, update routing, and view assembly. The server's authentication and transport implementation were not reviewed. + +## S11 + +**Huh official documentation.** + +- [README](https://github.com/charmbracelet/huh) +- [Accessibility section](https://github.com/charmbracelet/huh#accessibility) + +Read form, validation/theme, and accessible-mode documentation. This is documentation-level study, not a Huh source audit. + +## S12 + +**Legacy teatest dependency boundary.** + +- [exp/teatest/go.mod](https://github.com/charmbracelet/x/blob/main/exp/teatest/go.mod) + +Default-branch file inspected during research. It declared Go 1.24.0 and `github.com/charmbracelet/bubbletea v1.3.5`. This is why the unversioned teatest import is not the intended v2 helper. + +## S13 + +**teatest v2 module.** + +- [exp/teatest/v2/go.mod](https://github.com/charmbracelet/x/blob/main/exp/teatest/v2/go.mod) + +Default-branch file inspected during research. It declared module `github.com/charmbracelet/x/exp/teatest/v2`, Go 1.24.2, and a dependency on `charm.land/bubbletea/v2 v2.0.0-rc.1`. Verify compatibility in the target graph; an existing module is not a promise that an arbitrary revision will fit every application. + +## S14 + +**teatest v2 implementation.** + +- [exp/teatest/v2/teatest.go](https://github.com/charmbracelet/x/blob/main/exp/teatest/v2/teatest.go) + +Read lines 1–300: options, test program construction, waits, final model/output, sending/typing, quit, and golden-output helper. Use bounded waits and explicit lifecycle handling. This file was source-reviewed, not compiled in the research environment. + +## S15 + +**VHS official command reference and testing notes.** + +- [README](https://github.com/charmbracelet/vhs) + +Read command reference entries for waits, input, screenshots, environment/recording setup, and text/ASCII outputs used in regression workflows. No recording was produced for this skill. + +## S16 + +**ANSI display-width helpers.** + +- [github.com/charmbracelet/x/ansi documentation](https://pkg.go.dev/github.com/charmbracelet/x/ansi) + +Read helper catalogue and display-aware string operations. The distinction between ANSI-preserving manipulation and an untrusted-data sanitization policy is an engineering recommendation; this skill does not certify a particular sanitizer. + +## S17 + +**Charm ecosystem overview.** + +- [Charm](https://charm.land/) + +Read to identify the roles of the core libraries and adjacent tools including Glamour and Wish. Mentioned for selection and scope; their full APIs and implementations were not independently studied here. + +## How to refresh this research + +Inspect the target repository first. For a new API claim, read official documentation or code at its pinned version. For an application pattern, record a commit permalink and the relevant methods; do not infer the full architecture from a screenshot. When docs disagree with code, report the discrepancy and prefer the implementation for implementation facts. Validate important behavior with tests or an actual terminal run, and record exactly which occurred. + + +## S17 + +**APIs checked while adding worked examples, 2026-09-23.** + +- [Bubble Tea v2.0.9](https://pkg.go.dev/charm.land/bubbletea/v2@v2.0.9): typed key messages, `tea.View`, command constructors, output/input and context options. +- [Bubbles text input v2.2.1](https://pkg.go.dev/charm.land/bubbles/v2@v2.2.1/textinput): `SetWidth`, `Focus`, `Update`, virtual cursor, styles. +- [Lip Gloss v2.0.6](https://pkg.go.dev/charm.land/lipgloss/v2@v2.0.6): total block width before margins, border/padding sizing, rendering and measurement. +- [ANSI v0.11.8](https://pkg.go.dev/github.com/charmbracelet/x/ansi@v0.11.8): display-cell width and truncation. +- [Terminal v0.2.2](https://pkg.go.dev/github.com/charmbracelet/x/term@v0.2.2): `IsTerminal(fd uintptr)`. + +The docs displayed these versions during inspection. The example module uses explicit direct dependency versions, not an assertion that every package is the newest available. API review is not module compilation; transitive resolution and `go.sum` generation were unavailable. The request, retention, output, and sanitization policies in the examples are original application choices, not promises made by Charm. diff --git a/.agents/skills/charm-tui/references/testing-and-release.md b/.agents/skills/charm-tui/references/testing-and-release.md new file mode 100644 index 000000000..31208d594 --- /dev/null +++ b/.agents/skills/charm-tui/references/testing-and-release.md @@ -0,0 +1,83 @@ +# Testing and release + +The [worked examples](../examples/WORKED-EXAMPLES.md) pair concrete changes with real regression tests. [Demo test instructions](../examples/worked/README.md) distinguish executed core tests from unexecuted Charm and terminal checks. + +## Test the user contract in layers + +Do not let a screenshot test stand in for state correctness, or a reducer test stand in for a terminal test. Choose the smallest layer that proves each property. + +### 1. State and effect tests + +Feed messages directly into the model. Assert state and the presence/absence of the next command. For asynchronous behavior, use controlled completions rather than sleeps. Execute simple commands in a fixture when useful; do not treat a composite batch as if it were one ordinary result. + +Required cases for the relevant features: + +| Contract | Adversarial sequence | +| --- | --- | +| Filter owns printable keys | Focus search; type `qjk/? `; app remains active and query changes correctly | +| Modal consumes once | Open modal; close with Enter/Escape; underlying selection does not activate | +| Latest query wins | Start A; type B; deliver A before B's debounce; ignore A | +| Stale failure is harmless | Complete B successfully, then fail A; keep B's success and rows | +| Cancellation is real | Cancel owner; blocked work observes context or declared shutdown policy | +| No empty acceptance | Filter to zero results; Enter, toggle, and navigation cannot index an item | +| Stable selection | Select an ID; refresh/reorder/filter; selection does not jump by index | +| Follow-tail respects reading | Scroll away; append output; anchor remains; jump-to-latest restores following | +| Retry remains usable | Fail an operation; retry; succeed without restarting the program | +| Output has a contract | Accepted/cancelled/error paths produce distinct intended stdout and statuses | + +The [standalone contract exercises](../examples/contracts/README.md) cover several of these policies without Charm dependencies. They are not integration tests for any application. + +### 2. Render and layout tests + +Create deterministic model snapshots. For v2, inspect the root `View().Content` as appropriate; assert mode/cursor metadata separately. Freeze width, height, dataset, clock, operation state, theme, and animation frame. Normalize only values that are intentionally nondeterministic. + +Test ordinary and hostile sizes. Suggested fixtures are `80x24`, `120x40`, `40x12`, `20x6`, `1x1`, and an initial `0x0` message. These are test inputs, not universal supported minimums. For every supported mode, verify the rendered cell bounds, valid cursor positions, body allocation, and visible essential actions. Below the declared minimum, verify the safe fallback and responsive cancellation. + +Use display-width helpers for assertions. Add long paths, CJK, combining sequences, emoji, trusted ANSI styles, no matches, one item, and a large dataset. Explicitly test the effect of a wrapping footer and a prompt prefix. + +A golden snapshot is a proposed visual contract. Review its changes like code. Do not repeatedly run an update flag until a regression becomes the expected result. Keep assertions for semantic state and dimensions alongside snapshots so a golden cannot silently bless a wrong action or overflow. + +### 3. Program-level integration + +Use the matching-major helper: `github.com/charmbracelet/x/exp/teatest/v2` for Tea v2, not the similarly named legacy module. The inspected v2 helper offers `NewTestModel`, `WithInitialTermSize`, `WithProgramOptions`, `Type`, `Send`, `WaitFor`, `FinalModel`, and `WithFinalTimeout`. [S14](sources.md#s14) + +Wait for a specific state/output condition, send input, and use a bounded final timeout. Arrange cleanup even when an assertion fails. Check the final model's accepted/cancelled result, not merely whether some text appeared. Preserve the distinction between a simulated key event and a real bracketed paste or terminal signal. + +When passing program options, verify which options the helper overrides. Pin color profile and terminal size where supported. Avoid recording a new golden for whatever capabilities happen to be present on a developer machine. + +### 4. Real terminal / PTY checks + +Run a real terminal or pseudoterminal flow to verify behavior that direct model tests do not establish: resize delivery, raw/canonical modes, restored cursor, alternate-screen exit, paste handling, interrupt, and child-process handoff. Test stdin data plus a terminal input source for pipeline commands. Check that diagnostic output does not corrupt either the screen or stdout's result. + +For a targeted platform, use the terminal environments actually supported. A local truecolor terminal is not proof of correctness over SSH, in a multiplexer, or on another OS. Declare untested platforms rather than claiming all-terminal support. + +VHS can script interaction, wait for screen content, capture frames, and generate textual/ASCII artifacts for regression review. Pin recording conditions and use assertions in the surrounding test workflow; producing a GIF alone is not a pass/fail test. [S15](sources.md#s15) + +## Performance checks + +Measure representative workloads and report units, data size, terminal size, and environment. Useful measurements include startup-to-interactive time, update/render duration, allocations per render, idle CPU, resize behavior, and memory growth during a long stream. + +Use relative before/after comparisons on the same fixtures. Do not promise a universal millisecond threshold without a target system. Inject backend latency and failures to verify responsiveness while work is pending. Measure worst-case no-match filtering and heavy wrapping, not only a warm cache with a short query. + +Run benchmarks in the target repository, for example: + +```sh +go test ./... +go test -race ./... +go test -run '^$' -bench . -benchmem ./... +``` + +These commands may have platform, compiler, network, or fixture prerequisites. Report exact scope and failures. A race-test pass is useful evidence, not a mathematical proof that every schedule is safe. + +## Release review + +Before calling the UI finished, establish all applicable facts: + +- The primary task works with the keyboard, and current help describes working controls. +- Acceptance, cancellation, errors, and interrupted work have correct outputs and cleanup. +- Normal and small layouts were inspected; zero-size and no-match states are safe. +- Light/dark or the deliberately supported theme, monochrome, and ordinary fonts remain understandable. +- Existing interaction and appearance were compared on fixed fixtures when behavior preservation was requested. +- No unnecessary dependency migration, configuration system, or component framework was introduced. + +Use a delivery note with four short fields: **changed**, **preserved**, **verified**, **not verified**. Include actual command outcomes or terminal evidence. “Source-reviewed only” is more useful than an unsupported claim of production readiness. diff --git a/.agents/skills/charm-tui/references/versions-and-components.md b/.agents/skills/charm-tui/references/versions-and-components.md new file mode 100644 index 000000000..bf1d095fa --- /dev/null +++ b/.agents/skills/charm-tui/references/versions-and-components.md @@ -0,0 +1,82 @@ +# Versions and component selection + +## Resolve the repository before choosing an API + +Research snapshot: **2026-09-23**. The inspected published documentation showed Bubble Tea **v2.0.9**, Bubbles **v2.2.1**, and Lip Gloss **v2.0.6**. This records what was inspected, not a promise that those are permanently the newest releases or an instruction to upgrade a working project. [S01](sources.md#s01) [S02](sources.md#s02) [S03](sources.md#s03) + +Start with the repository's `go.mod`, `go.sum`, `go.work` if present, and source imports. Follow the installed APIs and existing conventions. Check each dependency's Go/toolchain requirement before proposing changes. Module resolution may need network access; do not silently modify the module graph just to inspect it. + +Useful local checks, when the repository and dependencies are available: + +```sh +go version +go list -m all +go test ./... +``` + +Use a focused import search as well. Multiple versions can legitimately appear in a dependency graph, but v1 and v2 Tea model/message/component APIs cannot be casually interchanged in one implementation. + +For an existing v1 application, fixing a focus bug does not require migration. For an explicit migration, move the interdependent Tea/Bubbles/Lip Gloss layer together, adapt the relevant tests, and verify behavior before optimizing. Bubbles' upgrade guide expressly calls for the companion upgrades. [S02](sources.md#s02) + +## High-impact v1/v2 differences + +| Area | Legacy shape | v2 shape to verify in the target version | +| --- | --- | --- | +| Tea import | `github.com/charmbracelet/bubbletea` | `charm.land/bubbletea/v2` | +| Bubbles import | `github.com/charmbracelet/bubbles/...` | `charm.land/bubbles/v2/...` | +| Lip Gloss import | `github.com/charmbracelet/lipgloss` | `charm.land/lipgloss/v2` | +| Root view | `View() string` | `View() tea.View`, often using `tea.NewView(content)` | +| Alternate screen | Program options / imperative commands | `View.AltScreen` | +| Mouse mode | Program options / imperative commands | `View.MouseMode` | +| Ordinary key switch | `case tea.KeyMsg:` for a concrete key event | Usually `case tea.KeyPressMsg:`; `tea.KeyMsg` is now an interface | +| Key content | Legacy type/rune representation | `Code`, `Text`, modifiers; separate press/release concepts | +| Space matching | Often a literal space | `String()` uses `"space"`; prefer current key-binding conventions | +| Paste | Legacy key-message conventions | Dedicated paste messages; preserve input component handling | +| Many component dimensions | Public fields | `SetWidth`, `SetHeight`, `Width()`, `Height()` as applicable | +| Viewport creation | `viewport.New(width, height)` | `viewport.New(viewport.WithWidth(w), viewport.WithHeight(h))` | +| Several default keymaps | Mutable package variables | Constructors such as `DefaultKeyMap()` | +| Colors | `lipgloss.Color` as a string type | `lipgloss.Color(...)` returns `image/color.Color` | +| Adaptive color | Root `AdaptiveColor` | Explicit `LightDark` or compatibility package | +| Lip Gloss renderer | Renderer-associated styles | Value styles; output-layer color handling | + +This is a triage map, not a replacement for the full upgrade guides. Refer to [S01](sources.md#s01), [S02](sources.md#s02), and [S03](sources.md#s03). Do not mechanically convert unrelated packages that retain a `github.com/charmbracelet/...` module path. + +An original minimal v2 **method sketch**, not a standalone application: + +```go +func (m model) View() tea.View { + v := tea.NewView(m.renderContent()) + v.AltScreen = m.fullScreen + return v +} +``` + +For background-aware styling, the documented v2 pattern requests background color through Tea and reacts to `tea.BackgroundColorMsg`. Keep a fallback style when no reply arrives. Root model methods return a `tea.View`; embedded Bubbles often still render strings. Do not change every component's View signature merely because the root signature changed. + +## Choose components for their interaction semantics + +**Text input / textarea:** use for editing, cursor movement, focus, and paste behavior. Configure their styles and dimensions with the target version's API. Keep app shortcuts from stealing printable input. Do not replace their editing model with ad hoc rune slicing to save a small amount of code. + +**List:** appropriate when its filtering, pagination, selection, and help behavior fit. A custom delegate can preserve a bespoke row design. A simple fixed list may only need a slice and cursor; a huge variable-height transcript may need a specialized view. Do not force all three into one abstraction. + +**Table:** appropriate when column comparison is the main task. Decide what columns survive narrowing and what long values do. A table-shaped display is not necessarily an interactive Bubbles table; static Lip Gloss tables serve a different role. + +**Viewport:** owns scrolling, not necessarily the expensive work of generating all content. Decide whether to wrap, clip, or scroll horizontally. Regenerating content should preserve the user's anchor unless a deliberate navigation action changes it. + +**Help + key:** use a shared vocabulary for routing and hints. Enabled bindings should reflect the active state. A hand-written one-line footer can be sufficient for a truly tiny interaction, but it must not drift from the implementation. + +**Spinner / progress / timer:** choose according to available information. Unknown-duration work needs activity, not a fabricated percentage. Preserve returned scheduling commands and stop inactive animation. + +These component categories are documented in the Bubbles catalogue; the selection criteria above are recommendations. [S02](sources.md#s02) + +**Huh:** useful for forms, field validation, and accessible prompting. It is not a reason to turn an arbitrary browser into a form. Do not start a second blocking interactive loop inside a running Tea update function; follow documented embedding or handoff patterns. [S11](sources.md#s11) + +**Gum:** useful for shell-script composition. Importing an entire application because it contains an appealing picker is usually less appropriate than using the underlying Bubbles or learning its interaction pattern. [S07](sources.md#s07) + +**Glamour:** use when Markdown formatting is the task, then cache or schedule expensive rendering appropriately. **Wish:** investigate when serving a TUI over SSH, with session-local ownership. These are optional capabilities, not default dependencies. [S17](sources.md#s17) + +## Testing dependencies must match too + +The inspected legacy `github.com/charmbracelet/x/exp/teatest` module depends on Bubble Tea v1. The separate module `github.com/charmbracelet/x/exp/teatest/v2` exists and imports `charm.land/bubbletea/v2`. Its inspected `go.mod` declares Go 1.24.2 and a v2 release-candidate minimum dependency. These are facts about the inspected files, not proof of compatibility with every later release. Select and test an appropriate revision in the target application's graph. [S12](sources.md#s12) [S13](sources.md#s13) + +The v2 helper supports initial terminal size, program options, sending messages, typing text, waiting for conditions, and reading final model/output with timeouts. Read its current implementation before relying on test lifecycle behavior. A virtual-input test is not equivalent to a real terminal restoration test. [S14](sources.md#s14)