From 1f7bd6e4901bb7097ee7791c6ce1f30b3514b022 Mon Sep 17 00:00:00 2001 From: Cody Confer Date: Fri, 6 Nov 2026 17:12:43 -0700 Subject: [PATCH 1/2] Add status-shaded command output boxes --- README.md | 23 ++++++++++++++++ outputbox/box.go | 63 +++++++++++++++++++++++++++++++++++++++++++ outputbox/box_test.go | 34 +++++++++++++++++++++++ 3 files changed, 120 insertions(+) create mode 100644 outputbox/box.go create mode 100644 outputbox/box_test.go diff --git a/README.md b/README.md index 9c3e333..862e3f9 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,7 @@ core + deck. | `theme` | `Theme` + `Use` / `Cur` palettes and status helpers | | `glyph` | Nerd/Uni/ASCII variants, status strip, severity vocabulary | | `console` | Output capability detection: TTY, ANSI, Unicode, Powerline/Nerd Fonts | +| `outputbox` | Borderless, status-shaded command output blocks for scrollback | | `keys` | Keybinding tables | | `forms` | Field builders | | `list` / `browser` | List/browser helpers | @@ -119,6 +120,28 @@ Interactive apps use `deck.Model` as the session tea root. Pass the scope with themes/keys/views before `deck.Run`. Full contract: [`deck/INTERFACE.md`](deck/INTERFACE.md). +### Command output boxes + +`outputbox.Render` renders borderless command output blocks with full-width +status backgrounds: neutral running, green success, yellow review, red failure. +Explicit status labels remain readable with color disabled. Rendering is pure: +append each returned box to keep earlier actions in scrollback; no cursor moves, +terminal detection, or global renderer changes are performed. + +```go +import "github.com/codyconfer/viewkit/outputbox" + +box := outputbox.Render("go test ./...", []string{"ok example/package"}, + 80, true, outputbox.Success) +fmt.Fprintln(os.Stdout, box) +``` + +Width includes padding and clamps to at least eight cells. Long text wraps without +truncation, including wide Unicode. Pass the color capability resolved by your +application (for example from `console.Detect`); use `false` for plain transcripts. +Content may include trusted ANSI styles; sanitize untrusted terminal controls +before rendering. The package has no Bubble Tea dependency. + ### Inline CLI workflows `deck.Inline` provides sequential setup/onboarding panels without entering a diff --git a/outputbox/box.go b/outputbox/box.go new file mode 100644 index 0000000..a7f5ad4 --- /dev/null +++ b/outputbox/box.go @@ -0,0 +1,63 @@ +// Package outputbox renders append-only, status-colored command output blocks. +package outputbox + +import ( + "io" + "strings" + + "github.com/charmbracelet/lipgloss" + "github.com/charmbracelet/x/ansi" + "github.com/muesli/termenv" +) + +// Status identifies the outcome shown in a box header and background. +type Status string + +const ( + // Pending marks an action still in progress. + Pending Status = "RUNNING" + // Success marks a completed action. + Success Status = "DONE" + // Warning marks output that needs review. + Warning Status = "REVIEW" + // Failure marks a failed action. + Failure Status = "ERROR" +) + +// Render returns a borderless box. Width includes horizontal padding. Without +// color the status label remains visible, including in redirected transcripts. +// Widths below eight cells are clamped to eight. Content may contain trusted ANSI +// styling; callers must sanitize terminal control sequences from untrusted input. +// Render does not write output, move the cursor, or change global color settings. +func Render(title string, lines []string, width int, color bool, status Status) string { + width = max(8, width) + inner := width - 4 + r := lipgloss.NewRenderer(io.Discard) + profile := termenv.Ascii + if color { + profile = termenv.ANSI256 + } + r.SetColorProfile(profile) + bg, fg := lipgloss.Color("236"), lipgloss.Color("252") + switch status { + case Success: + bg = "22" + case Warning: + bg = "58" + case Failure: + bg = "52" + } + row := r.NewStyle().Background(bg).Foreground(fg).Width(width).Padding(0, 2) + header := r.NewStyle().Bold(true) + // Wrap before styling so every physical line receives full-width shading. + content := []string{header.Render("[" + string(status) + "] " + title), ""} + content = append(content, lines...) + result := []string{row.Render("")} + for _, block := range content { + for _, line := range strings.Split(ansi.Wrap(block, inner, ""), "\n") { + result = append(result, row.Render(line)) + } + } + result = append(result, row.Render("")) + return strings.Join(result, "\n") +} diff --git a/outputbox/box_test.go b/outputbox/box_test.go new file mode 100644 index 0000000..c20d08f --- /dev/null +++ b/outputbox/box_test.go @@ -0,0 +1,34 @@ +package outputbox + +import ( + "strings" + "testing" + + "github.com/charmbracelet/x/ansi" +) + +func TestBoxStatusColorAndWidth(t *testing.T) { + backgrounds := map[Status]string{Pending: "236", Success: "22", Warning: "58", Failure: "52"} + for _, status := range []Status{Pending, Success, Warning, Failure} { + for _, color := range []bool{false, true} { + text := Render("gcx login ops", []string{strings.Repeat("界", 40), "complete"}, 40, color, status) + if !strings.Contains(ansi.Strip(text), "["+string(status)+"]") || strings.Count(ansi.Strip(text), "界") != 40 { + t.Fatal("missing status or truncated output", text) + } + if strings.ContainsAny(ansi.Strip(text), "╭╰│") || strings.Contains(text, "\x1b[J") { + t.Fatal("unexpected chrome/cursor movement") + } + if strings.Contains(text, "\x1b[") != color { + t.Fatal("wrong color mode") + } + for _, line := range strings.Split(text, "\n") { + if ansi.StringWidth(line) != 40 { + t.Fatalf("expected full-width shading: %q", line) + } + } + if color && !strings.Contains(text, "48;5;"+backgrounds[status]+"m") { + t.Fatalf("missing %s status background: %q", status, text) + } + } + } +} From c4ea1904a3a454a4aa50e2efc80a6549cdf9f7ce Mon Sep 17 00:00:00 2001 From: Cody Confer Date: Fri, 6 Nov 2026 17:18:09 -0700 Subject: [PATCH 2/2] Support custom append-only inline presentation --- README.md | 16 +++++++ deck/INTERFACE.md | 10 +++++ deck/inline.go | 68 ++++++++++++++++++++++++---- deck/inline_test.go | 77 ++++++++++++++++++++++++++++++++ skills/viewkit/references/api.md | 11 +++++ 5 files changed, 174 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 862e3f9..d5a2b8f 100644 --- a/README.md +++ b/README.md @@ -188,6 +188,22 @@ than risking erasure of unrelated reflowed scrollback. Interactive prompts honor context cancellation; generic line readers can only check it before/after reads. See the executable `ExampleInline` and terminal tests in `deck/inline*_test.go`. +To keep completed actions in scrollback while editing the active prompt, set +`InlineSpec.AppendOnly: true`. For application-specific presentation, supply a +pure `Render func(deck.InlinePanel) string`: it receives sanitized text, the +bounded total panel width, and `InlineContent`, `InlineEditing`, +`InlineSubmitted`, `InlineCancelled`, or `InlineError`. For example, a renderer +can map these states to `outputbox` status colors. Normal `Panel` calls have no +implied success/failure status; applications own those semantics. Renderers must +fit within the supplied width, must not write terminal commands, and must omit +the trailing newline. Plain mode (and extremely narrow terminals) bypass custom +renderers. Scoped keys and prompt behavior are unchanged. + +ANSI styles are normally stripped from redirected or dumb output. Applications +with an explicit forced-color option may opt into `AllowANSI: true`; this does +**not** enable cursor movement or interactive input on redirected streams. +`Plain: true` still strips ANSI regardless of `AllowANSI`. + ## Status API may still shift before a published `v1`. diff --git a/deck/INTERFACE.md b/deck/INTERFACE.md index 6393a52..1250aba 100644 --- a/deck/INTERFACE.md +++ b/deck/INTERFACE.md @@ -64,6 +64,16 @@ secret redaction, and exit policy; `Report`/`ErrorReported` preserve error identity while avoiding duplicate error messages. The API is sequential, not concurrency-safe. Terminal-width changes preserve earlier reflowed output. +`InlineSpec.AppendOnly` retains completed panels even on interactive terminals; +it does not disable active-prompt editing. `Render` is an optional pure +presentation hook, receiving sanitized, wrapped `InlinePanel` text, bounded total +width, and a neutral `InlineState`. The host still owns input, hints, lifecycle, +newline accounting, and error reporting. Renderers own safe chrome/style only, +must fit the supplied width, and must not emit terminal control commands. +`Plain` and extremely narrow terminals bypass this hook. `AllowANSI` permits +styles on redirected output without changing interaction/clearing capability; +`Plain` takes precedence. Default behavior remains unchanged. + ## Chrome contract Apps inject branding via `WithChrome(Chrome{Brand, BrandGlyph, Subtitle, ClockGlyph})`. diff --git a/deck/inline.go b/deck/inline.go index e3d7aa6..9c1e058 100644 --- a/deck/inline.go +++ b/deck/inline.go @@ -26,6 +26,32 @@ import ( // it through InlineSpec.Keys. const InlineClear keys.Action = "inline.clear" +// InlineState identifies the lifecycle of a rendered workflow panel. +type InlineState uint8 + +const ( + // InlineContent is a caller-supplied panel, with no implied status. + InlineContent InlineState = iota + // InlineEditing is a text prompt awaiting a response. + InlineEditing + // InlineSubmitted is the final view of a submitted prompt. + InlineSubmitted + // InlineCancelled is the final view of a cancelled prompt. + InlineCancelled + // InlineError is an error displayed by Report. + InlineError +) + +// InlinePanel is the neutral input to a custom workflow renderer. Title and +// Lines contain sanitized text; Lines are wrapped to the preferred body width. +// Width includes the four columns reserved for default panel chrome. +type InlinePanel struct { + Title string + Lines []string + Width int + State InlineState +} + // InlineSpec configures a sequential, inline CLI workflow. Domain checks, // validation, persistence, and external commands belong to the caller. type InlineSpec struct { @@ -39,6 +65,19 @@ type InlineSpec struct { Width int // Plain disables panels, cursor movement, and interactive editing. Plain bool + // AppendOnly keeps completed panels in scrollback even on terminals. + // The active text prompt still edits and redraws interactively. + AppendOnly bool + // Render replaces the default panel presentation. It must be a pure + // renderer, fit within InlinePanel.Width, and return no trailing newline. + // It is not called in Plain mode or on terminals narrower than 5 cells. + // ANSI styles are allowed; terminal control commands are not. The host + // strips ANSI unless output supports it or AllowANSI is true. + Render func(InlinePanel) string + // AllowANSI preserves renderer styles even for redirected/dumb output + // (for example, an application's forced-color option). It never enables + // interaction or cursor movement, and Plain still strips all ANSI. + AllowANSI bool // Keys overrides the text editor map, including submit and cancel. Nil // uses text-safe scoped confirm/cancel/quit/erase and ctrl+u to clear. Keys *keys.Map @@ -60,6 +99,8 @@ type Inline struct { keyMap *keys.Map width int plain bool + appendOnly bool + renderPanel func(InlinePanel) string interactive bool ansi bool title string @@ -86,7 +127,8 @@ func NewInline(spec InlineSpec) *Inline { u := &Inline{ in: in, out: out, lines: bufio.NewReader(in), scope: scope, keyMap: spec.Keys, width: layout.NewFrame(spec.Width).Width, - plain: spec.Plain, ansi: caps.ANSI && !spec.Plain, + plain: spec.Plain, ansi: (caps.ANSI || spec.AllowANSI) && !spec.Plain, + appendOnly: spec.AppendOnly, renderPanel: spec.Render, interactive: inlineTerminal(in) && caps.ANSI && !spec.Plain, } u.size = func() (int, int) { @@ -127,7 +169,7 @@ func (u *Inline) frame(width int) layout.Frame { return layout.Frame{Width: bodyWidth + 4, UI: u.scope} } -func (u *Inline) render(title string, body []string, width int) string { +func (u *Inline) render(title string, body []string, width int, state InlineState) string { f := u.frame(width) bodyWidth := max(1, f.Width-4) if width > 0 && width < 5 { @@ -144,6 +186,8 @@ func (u *Inline) render(title string, body []string, width int) string { titleWidth = min(titleWidth, width) } text = inlineWrap(inlineText(title), titleWidth) + "\n" + strings.Join(lines, "\n") + } else if u.renderPanel != nil { + text = u.renderPanel(InlinePanel{Title: inlineText(title), Lines: lines, Width: f.Width, State: state}) } else { text = f.CellBox(inlineText(title), lines...) } @@ -165,7 +209,7 @@ func inlineWrap(text string, width int) string { } func (u *Inline) clear(width, height int) error { - if u.interactive && u.rows > 0 && width == u.lastWidth { + if u.interactive && !u.appendOnly && u.rows > 0 && width == u.lastWidth { rows := u.rows if height > 0 { rows = min(rows, height-1) @@ -186,8 +230,12 @@ func (u *Inline) clear(width, height int) error { // are untrusted text: terminal control sequences are stripped. A matching Ask // retains these instructions inside the same panel. func (u *Inline) Panel(title string, lines ...string) error { + return u.panel(InlineContent, title, lines...) +} + +func (u *Inline) panel(state InlineState, title string, lines ...string) error { width, height := u.size() - text := u.render(title, lines, width) + text := u.render(title, lines, width, state) if err := u.clear(width, height); err != nil { return err } @@ -241,7 +289,7 @@ func (u *Inline) Ask(ctx context.Context, title, label, value string) (string, e } // No Tea program or cursor escapes for transcripts. Reuse one buffered // reader across prompts so read-ahead remains available to the next step. - if err := u.Panel(title, append(body, inlineText(label)+" ["+value+"]:")...); err != nil { + if err := u.panel(InlineEditing, title, append(body, inlineText(label)+" ["+value+"]:")...); err != nil { return "", err } // A prompt is not an instruction for the following Ask/Report. @@ -304,7 +352,7 @@ func (u *Inline) Report(err error) error { title = "Error" } body := append(append([]string(nil), u.body...), err.Error()) - if renderErr := u.Panel(title, body...); renderErr != nil { + if renderErr := u.panel(InlineError, title, body...); renderErr != nil { return errors.Join(err, renderErr) } return inlineReportedError{err: err} @@ -381,7 +429,7 @@ func (m *inlineModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { func (m *inlineModel) View() string { if m.cancelled { - return m.owner.render(m.title, []string{"Cancelled."}, m.width) + "\n" + return m.owner.render(m.title, []string{"Cancelled."}, m.width, InlineCancelled) + "\n" } lines := append([]string(nil), m.body...) lines = append(lines, "", inlineText(m.label)+": "+m.form.Focused().Text, "") @@ -401,5 +449,9 @@ func (m *inlineModel) View() string { } lines = append(lines, strings.Join(hints, " · ")) } - return m.owner.render(m.title, lines, m.width) + "\n" + state := InlineEditing + if m.submitted { + state = InlineSubmitted + } + return m.owner.render(m.title, lines, m.width, state) + "\n" } diff --git a/deck/inline_test.go b/deck/inline_test.go index 55b54ca..5776082 100644 --- a/deck/inline_test.go +++ b/deck/inline_test.go @@ -270,6 +270,83 @@ func TestInlineScopedKeysAndHints(t *testing.T) { } } +func TestInlineCustomPresentation(t *testing.T) { + var out bytes.Buffer + var seen []InlinePanel + u := NewInline(InlineSpec{ + Input: strings.NewReader("answer\n"), Output: &out, AppendOnly: true, + Render: func(p InlinePanel) string { + seen = append(seen, p) + return "custom " + p.Title + "\n" + strings.Join(p.Lines, "\n") + }, + }) + u.size = func() (int, int) { return 50, 20 } + u.interactive = true // exercise terminal replacement independently of a PTY + if err := u.Panel("First\x1b[2J", "body\x1b[2J"); err != nil { + t.Fatal(err) + } + if err := u.Panel("Second", "instructions"); err != nil { + t.Fatal(err) + } + if seen[0].Title != "First" || seen[0].Lines[0] != "body" || seen[0].Width != 50 || seen[0].State != InlineContent { + t.Fatalf("renderer input not sanitized/sized: %#v", seen[0]) + } + if strings.Contains(out.String(), "\x1b") || !u.interactive { + t.Fatal("append-only must not clear panels or disable interactive editing", out.String()) + } + m := &inlineModel{owner: u, title: "Prompt", label: "Name", width: 50, + form: forms.NewForm(forms.Text("value", "Name"))} + m.View() + if seen[len(seen)-1].State != InlineEditing { + t.Fatal(seen) + } + m.Update(tea.KeyMsg{Type: tea.KeyEnter}) + m.View() + if seen[len(seen)-1].State != InlineSubmitted { + t.Fatal(seen) + } + m.cancelled = true + m.View() + if seen[len(seen)-1].State != InlineCancelled { + t.Fatal(seen) + } + if err := u.Report(errors.New("failed")); !ErrorReported(err) || seen[len(seen)-1].State != InlineError { + t.Fatal(err, seen) + } + u.interactive = false + if _, err := u.Ask(context.Background(), "Transcript", "Name", ""); err != nil || seen[len(seen)-1].State != InlineEditing { + t.Fatal(err, seen) + } +} + +func TestInlineCustomRendererColorAndPlain(t *testing.T) { + for _, tc := range []struct { + name string + plain, allowANSI bool + }{ + {name: "redirected"}, {name: "forced color", allowANSI: true}, + {name: "plain wins", plain: true, allowANSI: true}, + } { + t.Run(tc.name, func(t *testing.T) { + var out bytes.Buffer + called := false + u := NewInline(InlineSpec{Input: strings.NewReader(""), Output: &out, + Plain: tc.plain, AllowANSI: tc.allowANSI, + Render: func(p InlinePanel) string { + called = true + return "\x1b[31m" + p.Title + "\x1b[0m" + }, + }) + if err := u.Panel("Title"); err != nil { + t.Fatal(err) + } + if called == tc.plain || strings.Contains(out.String(), "\x1b") != (tc.allowANSI && !tc.plain) || u.interactive { + t.Fatalf("called=%v interactive=%v output=%q", called, u.interactive, out.String()) + } + }) + } +} + func ExampleInline() { var transcript bytes.Buffer flow := NewInline(InlineSpec{ diff --git a/skills/viewkit/references/api.md b/skills/viewkit/references/api.md index 2cd1494..24d6e74 100644 --- a/skills/viewkit/references/api.md +++ b/skills/viewkit/references/api.md @@ -306,8 +306,19 @@ type InlineSpec struct { UI *ui.Scope // nil = ui.Default() Width int // preferred body width, zero = document width Plain bool // no panels, editing, or cursor movement + AppendOnly bool // retain completed panels; still edit active prompt + Render func(InlinePanel) string // pure bounded renderer; bypassed in plain mode + AllowANSI bool // permit forced-color styles, not cursor movement Keys *keys.Map // nil = text-safe scoped editor map } +type InlineState uint8 +const (InlineContent InlineState = iota; InlineEditing; InlineSubmitted; InlineCancelled; InlineError) +type InlinePanel struct { + Title string // sanitized + Lines []string // sanitized and wrapped + Width int // total width including chrome + State InlineState +} const InlineClear keys.Action = "inline.clear" // default ctrl+u func NewInline(spec InlineSpec) *Inline func (u *Inline) Panel(title string, lines ...string) error