From 764f22b834e442bbb26467f679fcf45c16fdc21c Mon Sep 17 00:00:00 2001 From: Cody Confer Date: Fri, 6 Nov 2026 17:04:10 -0700 Subject: [PATCH] Add reusable inline CLI workflows --- README.md | 46 ++++ deck/INTERFACE.md | 23 ++ deck/inline.go | 405 +++++++++++++++++++++++++++++++ deck/inline_linux_test.go | 139 +++++++++++ deck/inline_test.go | 289 ++++++++++++++++++++++ skills/viewkit/references/api.md | 30 +++ 6 files changed, 932 insertions(+) create mode 100644 deck/inline.go create mode 100644 deck/inline_linux_test.go create mode 100644 deck/inline_test.go diff --git a/README.md b/README.md index c93782e..9c3e333 100644 --- a/README.md +++ b/README.md @@ -119,6 +119,52 @@ 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). +### Inline CLI workflows + +`deck.Inline` provides sequential setup/onboarding panels without entering a +full-screen deck session. Each panel replaces the previous panel on an ANSI +terminal; redirected streams, `TERM=dumb`, and `Plain: true` keep an append-only +transcript. No step numbers or application-specific checks are imposed. + +```go +func setup(ctx context.Context) error { + flow := deck.NewInline(deck.InlineSpec{ + Input: os.Stdin, Output: os.Stdout, UI: ui.Default(), + }) + if err := flow.Panel("Workspace", "Choose a local directory."); err != nil { + return err + } + path, err := flow.Ask(ctx, "Workspace", "Directory", ".") + if err != nil { + return flow.Report(err) // stays inside the current panel + } + if path == "" { + return flow.Report(errors.New("a directory is required")) + } + return flow.Panel("Ready", "Directory: "+path) +} +``` + +A matching `Ask` retains the preceding panel's instructions alongside its text +field and key hints. Defaults can be edited with typing, backspace, and clear; +scoped key bindings drive both dispatch and hints. Cancel returns +`deck.ErrCancelled`. Text responses are visible, not password prompts. Caller +strings are treated as text, with terminal controls stripped; redact secrets +before reporting errors. + +`Report` preserves error identity (`errors.Is`/`errors.As`) and marks successfully +rendered errors. At the CLI boundary, use `deck.ErrorReported(err)` to suppress +duplicate stderr output **without** suppressing a failing exit status. A render +failure returns both errors and does not mark them reported. + +Call `flow.Release()` before any external command or other output. Pass +`flow.Reader()` to a child command's stdin: it preserves scripted bytes already +buffered by an earlier `Ask`. Never write concurrently or nest an `Inline` inside +a running deck. A width change preserves the previous view as transcript rather +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`. + ## Status API may still shift before a published `v1`. diff --git a/deck/INTERFACE.md b/deck/INTERFACE.md index 9c41ceb..6393a52 100644 --- a/deck/INTERFACE.md +++ b/deck/INTERFACE.md @@ -14,6 +14,7 @@ | `Content` / `Text` | Domain-agnostic job body (apps adapt before crossing) | | `Job` + `Work.Collect` / `Work.RunInteractive` | A set of concurrent jobs: errgroup headless + tea progressive UI | | `Confirm` | Yes/no tea prompt | +| `Inline` / `InlineSpec` | Sequential CLI panels, inline text prompts, reported errors, transcript fallback | | `Menu` / `Message` / `Scroll` | Generic views (optional; apps may roll their own) | | `ItemList` | Lazy Fetch+Bind selectable list (domain → `list.Item` in Bind) | | `HomeShell` | Dual-pane menu + optional side list (Fetch+Bind; no app domain types) | @@ -41,6 +42,28 @@ There is no process-global active theme or scheme. Overlays and plugins must not invent a second tea root — register Views/themes and let the host `Model` own the program. +## Standalone CLI workflows + +`Prompt`, `Confirm`, and `Inline.Ask` are standalone prompt hosts, not deck +Views. They may own a short-lived tea program **outside** a deck session, never +nested within `Model`. `Inline` stays in normal scrollback and replaces only its +owned region; it never uses the alternate screen. `Panel` and `Report` are +synchronous writes, and each `Ask` relinquishes raw mode before returning. + +Apps supply domain checks and sequencing through normal Go control flow; no +setup commands, paths, service names, or step counts belong in the library. +`InlineSpec.UI` carries the rendering scope. The default text-safe key map is +derived from that scope, with `InlineClear` bound to ctrl+u; an explicit +`InlineSpec.Keys` replaces it. Input dispatch and hints share the same map. + +Only ANSI-capable input/output terminal pairs replace views. Plain, dumb, or +redirected streams retain transcripts without ANSI, with a shared buffered input +reader for successive prompts. `Release` must precede external writes; +`Reader` hands buffered input to child processes. Callers own validation, +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. + ## Chrome contract Apps inject branding via `WithChrome(Chrome{Brand, BrandGlyph, Subtitle, ClockGlyph})`. diff --git a/deck/inline.go b/deck/inline.go new file mode 100644 index 0000000..e3d7aa6 --- /dev/null +++ b/deck/inline.go @@ -0,0 +1,405 @@ +package deck + +import ( + "bufio" + "context" + "errors" + "fmt" + "io" + "os" + "strings" + "unicode" + + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/x/ansi" + "github.com/charmbracelet/x/term" + + "github.com/codyconfer/viewkit/console" + "github.com/codyconfer/viewkit/forms" + "github.com/codyconfer/viewkit/keys" + "github.com/codyconfer/viewkit/layout" + "github.com/codyconfer/viewkit/ui" +) + +// InlineClear is the action that clears an Inline text response. The default +// binding is ctrl+u when not already used by the scoped editor map; override +// it through InlineSpec.Keys. +const InlineClear keys.Action = "inline.clear" + +// InlineSpec configures a sequential, inline CLI workflow. Domain checks, +// validation, persistence, and external commands belong to the caller. +type InlineSpec struct { + // Input and Output default to os.Stdin and os.Stdout. + Input io.Reader + Output io.Writer + // UI defaults to a snapshot of the built-in rendering scope. + UI *ui.Scope + // Width is the preferred body width, excluding the four columns of panel + // chrome. Zero uses layout.DocumentFrame's width. Terminal width caps it. + Width int + // Plain disables panels, cursor movement, and interactive editing. + Plain 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 +} + +// Inline renders one workflow panel at a time, in normal terminal scrollback +// (never the alternate screen). Panel, Ask, and Report replace the preceding +// view only when both streams are terminals and output supports ANSI. Plain, +// dumb-terminal, and redirected streams are append-only transcripts. +// +// An Inline owns its terminal region. Use it sequentially from one goroutine, +// do not nest it inside a deck session, and call Release before any other code +// writes to its output. It does not install global theme or key state. +type Inline struct { + in io.Reader + out io.Writer + lines *bufio.Reader + scope *ui.Scope + keyMap *keys.Map + width int + plain bool + interactive bool + ansi bool + title string + body []string + rows int + lastWidth int + size func() (int, int) +} + +// NewInline constructs a workflow without reading input or writing output. +func NewInline(spec InlineSpec) *Inline { + in, out := spec.Input, spec.Output + if in == nil { + in = os.Stdin + } + if out == nil { + out = os.Stdout + } + scope := spec.UI + if scope == nil { + scope = ui.Default() + } + caps := console.Detect(out) + 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, + interactive: inlineTerminal(in) && caps.ANSI && !spec.Plain, + } + u.size = func() (int, int) { + if f, ok := out.(interface{ Fd() uintptr }); ok { + w, h, err := term.GetSize(f.Fd()) + if err == nil { + return w, h + } + } + return 0, 0 + } + return u +} + +func inlineTerminal(v any) bool { + f, ok := v.(interface{ Fd() uintptr }) + return ok && term.IsTerminal(f.Fd()) +} + +// inlineText treats caller strings as text, not terminal commands. Newlines +// are retained so multiline instructions and errors still wrap naturally. +func inlineText(s string) string { + return strings.Map(func(r rune) rune { + if unicode.IsControl(r) && r != '\n' { + return ' ' + } + return r + }, ansi.Strip(s)) +} + +func (u *Inline) frame(width int) layout.Frame { + bodyWidth := u.width + if width > 0 { + bodyWidth = min(bodyWidth, max(1, width-4)) + } + // Do not use WithWidth here: its minimum-width clamp can exceed a narrow + // terminal. CellBox is the layout helper with clamp-down semantics. + return layout.Frame{Width: bodyWidth + 4, UI: u.scope} +} + +func (u *Inline) render(title string, body []string, width int) string { + f := u.frame(width) + bodyWidth := max(1, f.Width-4) + if width > 0 && width < 5 { + bodyWidth = width + } + lines := make([]string, len(body)) + for i, line := range body { + lines[i] = inlineWrap(inlineText(line), bodyWidth) + } + var text string + if u.plain || (width > 0 && width < 5) { + titleWidth := u.width + if width > 0 { + titleWidth = min(titleWidth, width) + } + text = inlineWrap(inlineText(title), titleWidth) + "\n" + strings.Join(lines, "\n") + } else { + text = f.CellBox(inlineText(title), lines...) + } + if !u.ansi { + text = ansi.Strip(text) + } + return text +} + +func inlineWrap(text string, width int) string { + wrapped := ansi.Hardwrap(ansi.Wrap(text, width, ""), width, false) + lines := strings.Split(wrapped, "\n") + for i, line := range lines { + // A single wide grapheme cannot fit a one-cell body. Never allow it + // to force a terminal wrap and invalidate our owned-region height. + lines[i] = ansi.Truncate(line, width, "") + } + return strings.Join(lines, "\n") +} + +func (u *Inline) clear(width, height int) error { + if u.interactive && u.rows > 0 && width == u.lastWidth { + rows := u.rows + if height > 0 { + rows = min(rows, height-1) + } + if rows > 0 { + if _, err := fmt.Fprintf(u.out, "\r\x1b[%dA\x1b[J", rows); err != nil { + return err + } + } + } + // A terminal width change can reflow previous output. Keep that view as + // transcript rather than guessing and erasing unrelated scrollback. + u.rows = 0 + return nil +} + +// Panel replaces the current view, or appends it to a transcript. All strings +// 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 { + width, height := u.size() + text := u.render(title, lines, width) + if err := u.clear(width, height); err != nil { + return err + } + if _, err := fmt.Fprintln(u.out, text); err != nil { + return err + } + u.title, u.body = title, append([]string(nil), lines...) + u.rows, u.lastWidth = strings.Count(text, "\n")+1, width + return nil +} + +// Ask collects one text response in the current panel, retaining instructions +// when title matches the preceding Panel. The value is an editable default, +// not a secret: it is displayed in clear text. Cancellation returns +// ErrCancelled. Scripted input accepts an empty line as the default and a final +// nonempty line without a newline. EOF without an answer returns io.EOF. +// +// Context cancellation interrupts the interactive program. Arbitrary fallback +// readers cannot be interrupted: ctx is checked before and after a line read. +func (u *Inline) Ask(ctx context.Context, title, label, value string) (string, error) { + if err := ctx.Err(); err != nil { + return "", err + } + width, height := u.size() + var body []string + if u.title == title { + body = append([]string(nil), u.body...) + } + value = strings.ReplaceAll(inlineText(value), "\n", " ") + m := &inlineModel{ + owner: u, form: forms.NewForm(forms.Text("value", label).WithText(value)), + title: title, label: label, body: body, width: width, + } + if u.interactive { + if err := u.clear(width, height); err != nil { + return "", err + } + _, err := tea.NewProgram(m, tea.WithContext(ctx), tea.WithInput(u.in), tea.WithOutput(u.out)).Run() + u.title, u.body = title, body + u.rows, u.lastWidth = strings.Count(m.View(), "\n"), m.width + if ctx.Err() != nil { + return "", ctx.Err() + } + if err != nil { + return "", err + } + if !m.submitted { + return "", ErrCancelled + } + return m.form.Focused().Text, nil + } + // 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 { + return "", err + } + // A prompt is not an instruction for the following Ask/Report. + u.body = body + answer, err := u.lines.ReadString('\n') + if ctx.Err() != nil { + return "", ctx.Err() + } + if err != nil && (!errors.Is(err, io.EOF) || len(answer) == 0) { + return "", err + } + answer = strings.TrimSpace(answer) + if answer == "" { + answer = value + } + return answer, nil +} + +// Release relinquishes the current terminal region without erasing it. Call +// before external command output or other writers; the next Panel must not +// erase that output. Instructions are forgotten as well. +func (u *Inline) Release() { + u.rows = 0 + u.title, u.body = "", nil +} + +// Reader returns the input stream for an external command after Release. For +// transcripts it includes any bytes buffered by Ask. Do not bypass this reader +// when handing scripted input to a child process. +func (u *Inline) Reader() io.Reader { + if u.interactive { + return u.in + } + return u.lines +} + +type inlineReportedError struct{ err error } + +func (e inlineReportedError) Error() string { return e.err.Error() } +func (e inlineReportedError) Unwrap() error { return e.err } + +// ErrorReported reports whether err (possibly wrapped) has already been +// displayed by Inline.Report. CLIs can suppress a duplicate stderr message +// while retaining their nonzero exit status and errors.Is/errors.As identity. +func ErrorReported(err error) bool { + var reported inlineReportedError + return errors.As(err, &reported) +} + +// Report displays err inside the current panel and returns a marked error +// preserving its identity. Nil and already-reported errors are unchanged. If +// rendering fails, both errors are returned, without marking either reported. +// Error strings are shown verbatim as text; callers must redact secrets first. +func (u *Inline) Report(err error) error { + if err == nil || ErrorReported(err) { + return err + } + title := u.title + if title == "" { + title = "Error" + } + body := append(append([]string(nil), u.body...), err.Error()) + if renderErr := u.Panel(title, body...); renderErr != nil { + return errors.Join(err, renderErr) + } + return inlineReportedError{err: err} +} + +func (u *Inline) editorMap() *keys.Map { + if u.keyMap != nil { + return u.keyMap + } + bindings := u.scope.Keys.EditorBindings(keys.Confirm, keys.Cancel, keys.Quit, keys.Erase) + textBindings := make([]keys.Binding, 0, len(bindings)+1) + for _, binding := range bindings { + // "spacebar" is a printable-space alias in some schemes. Spaces + // must remain text, and hints must name only keys we dispatch. + var control []string + for _, key := range binding.Keys { + if key != "spacebar" { + control = append(control, key) + } + } + if len(control) > 0 { + binding.Keys = control + binding.Glyph = strings.Join(control, "/") + textBindings = append(textBindings, binding) + } + } + km := keys.NewMap(textBindings...) + if _, bound := km.Action("ctrl+u"); bound { + // A scoped control binding wins over the optional clear shortcut. + return km + } + textBindings = append(textBindings, keys.Binding{Action: InlineClear, Keys: []string{"ctrl+u"}, Glyph: "ctrl+u"}) + return keys.NewMap(textBindings...) +} + +type inlineModel struct { + owner *Inline + form *forms.Form + title, label string + body []string + width int + cancelled, submitted bool +} + +func (m *inlineModel) Init() tea.Cmd { return nil } + +func (m *inlineModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { + switch key := msg.(type) { + case tea.WindowSizeMsg: + m.width = key.Width + case tea.KeyMsg: + act, bound := m.owner.editorMap().Action(key.String()) + if bound { + switch act { + case keys.Cancel, keys.Quit: + m.cancelled = true + return m, tea.Quit + case keys.Confirm: + m.submitted = true + return m, tea.Quit + case InlineClear: + m.form.Focused().Text = "" + case keys.Erase: + m.form.Handle(keys.Erase) + } + } else if key.Type == tea.KeyRunes { + m.form.Insert(strings.ReplaceAll(inlineText(string(key.Runes)), "\n", " ")) + } else if key.Type == tea.KeySpace { + m.form.Insert(" ") + } + } + return m, nil +} + +func (m *inlineModel) View() string { + if m.cancelled { + return m.owner.render(m.title, []string{"Cancelled."}, m.width) + "\n" + } + lines := append([]string(nil), m.body...) + lines = append(lines, "", inlineText(m.label)+": "+m.form.Focused().Text, "") + if m.submitted { + lines = append(lines, "Saved response.") + } else { + km := m.owner.editorMap() + var hints []string + for _, item := range []struct { + action keys.Action + label string + }{{keys.Confirm, "submit"}, {InlineClear, "clear"}, {keys.Cancel, "cancel"}, {keys.Quit, "cancel"}} { + if km.Has(item.action) { + h := km.HintLabeled(item.action, item.label) + hints = append(hints, h.Key+" "+h.Label) + } + } + lines = append(lines, strings.Join(hints, " · ")) + } + return m.owner.render(m.title, lines, m.width) + "\n" +} diff --git a/deck/inline_linux_test.go b/deck/inline_linux_test.go new file mode 100644 index 0000000..4b41f5d --- /dev/null +++ b/deck/inline_linux_test.go @@ -0,0 +1,139 @@ +package deck + +import ( + "context" + "fmt" + "os" + "strings" + "testing" + "time" + + "golang.org/x/sys/unix" +) + +// Exercise the real Tea terminal lifecycle, not only Update/View. A real PTY +// catches capability detection, raw mode, final row accounting, and teardown. +func TestInlineTerminalPrompt(t *testing.T) { + for _, cancel := range []bool{false, true} { + t.Run(fmt.Sprint(cancel), func(t *testing.T) { + t.Setenv("TERM", "xterm-256color") + master, slave := inlinePTY(t) + defer master.Close() + defer slave.Close() + chunks := make(chan string, 100) + readDone := make(chan struct{}) + go func() { + defer close(readDone) + buf := make([]byte, 4096) + for { + n, err := master.Read(buf) + if n > 0 { + chunks <- string(buf[:n]) + } + if err != nil { + return + } + } + }() + defer func() { + master.Close() + select { + case <-readDone: + case <-time.After(time.Second): + t.Error("PTY reader did not stop") + } + }() + u := NewInline(InlineSpec{Input: slave, Output: slave, Width: 40}) + if !u.interactive { + t.Fatal("PTY not detected as interactive") + } + if err := u.Panel("Setup", "instructions"); err != nil { + t.Fatal(err) + } + ctx, stop := context.WithTimeout(context.Background(), 5*time.Second) + defer stop() + type response struct { + value string + err error + } + result := make(chan response, 1) + go func() { + value, err := u.Ask(ctx, "Setup", "Value", "") + result <- response{value, err} + }() + var output strings.Builder + for !strings.Contains(output.String(), "Value:") { + select { + case chunk := <-chunks: + output.WriteString(chunk) + case <-ctx.Done(): + t.Fatal("prompt did not render", output.String()) + } + } + input := "answer\r" + if cancel { + input = "\x03" + } + if _, err := master.WriteString(input); err != nil { + t.Fatal(err) + } + var got response + select { + case got = <-result: + case <-ctx.Done(): + t.Fatal("prompt did not finish", output.String()) + } + if cancel { + if got.err != ErrCancelled { + t.Fatalf("cancel error=%v", got.err) + } + } else if got.err != nil || got.value != "answer" { + t.Fatalf("response=%q err=%v", got.value, got.err) + } + if err := u.Panel("Next", "next body"); err != nil { + t.Fatal(err) + } + for !strings.Contains(output.String(), "next body") { + select { + case chunk := <-chunks: + output.WriteString(chunk) + case <-ctx.Done(): + t.Fatal("next panel did not render", output.String()) + } + } + text := output.String() + if strings.Count(text, "\x1b[J") < 2 || strings.Contains(text, "\x1b[?1049h") { + t.Fatalf("expected two inline replacements without alternate screen: %q", text) + } + }) + } +} + +func inlinePTY(t *testing.T) (*os.File, *os.File) { + t.Helper() + fd, err := unix.Open("/dev/ptmx", unix.O_RDWR|unix.O_NOCTTY|unix.O_CLOEXEC|unix.O_NONBLOCK, 0) + if err != nil { + t.Skip("PTY unavailable:", err) + } + master := os.NewFile(uintptr(fd), "ptmx") + if err := unix.IoctlSetPointerInt(fd, unix.TIOCSPTLCK, 0); err != nil { + master.Close() + t.Fatal(err) + } + number, err := unix.IoctlGetInt(fd, unix.TIOCGPTN) + if err != nil { + master.Close() + t.Fatal(err) + } + slave, err := os.OpenFile(fmt.Sprintf("/dev/pts/%d", number), os.O_RDWR, 0) + if err != nil { + master.Close() + t.Fatal(err) + } + if err := unix.IoctlSetWinsize(int(slave.Fd()), unix.TIOCSWINSZ, &unix.Winsize{Row: 30, Col: 60}); err != nil { + master.Close() + slave.Close() + t.Fatal(err) + } + return master, slave +} diff --git a/deck/inline_test.go b/deck/inline_test.go new file mode 100644 index 0000000..55b54ca --- /dev/null +++ b/deck/inline_test.go @@ -0,0 +1,289 @@ +package deck + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "strings" + "testing" + + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/x/ansi" + + "github.com/codyconfer/viewkit/forms" + "github.com/codyconfer/viewkit/keys" + "github.com/codyconfer/viewkit/ui" +) + +func TestInlinePanelReplacement(t *testing.T) { + for _, mode := range []string{"interactive", "plain", "redirected"} { + t.Run(mode, func(t *testing.T) { + var out bytes.Buffer + u := NewInline(InlineSpec{Input: strings.NewReader(""), Output: &out, Plain: mode == "plain"}) + u.interactive = mode == "interactive" + u.ansi = u.interactive + u.size = func() (int, int) { return 60, 30 } + if err := u.Panel("First", "first body"); err != nil { + t.Fatal(err) + } + rows := u.rows + out.Reset() + if err := u.Panel("Next", "next body"); err != nil { + t.Fatal(err) + } + wantPrefix := fmt.Sprintf("\r\x1b[%dA\x1b[J", rows) + if strings.HasPrefix(out.String(), wantPrefix) != u.interactive { + t.Fatalf("unexpected replacement: %q", out.String()) + } + if !u.interactive && strings.Contains(out.String(), "\x1b") { + t.Fatalf("escape in transcript: %q", out.String()) + } + if !strings.Contains(out.String(), "Next") || !strings.Contains(out.String(), "next body") { + t.Fatal(out.String()) + } + if strings.Contains(out.String(), "First") { + t.Fatal("previous panel repeated") + } + if strings.Contains(out.String(), "╭") == u.plain { + t.Fatal("incorrect plain mode") + } + }) + } +} + +func TestInlineRegionBoundsAndHandoff(t *testing.T) { + var out bytes.Buffer + u := NewInline(InlineSpec{Input: strings.NewReader(""), Output: &out}) + u.interactive, u.ansi = true, true + width, height := 60, 4 + u.size = func() (int, int) { return width, height } + u.Panel("Tall", strings.Repeat("line\n", 15)) + out.Reset() + u.Panel("Next", "body") + if !strings.HasPrefix(out.String(), "\r\x1b[3A\x1b[J") { + t.Fatalf("clearing must stay within the screen: %q", out.String()) + } + width = 40 + out.Reset() + u.Panel("Resized", "body") + if strings.Contains(out.String(), "\x1b[J") { + t.Fatal("must preserve reflowed output instead of guessing its height") + } + u.Release() + fmt.Fprintln(&out, "child output") + out.Reset() + u.Panel("After child", "body") + if strings.Contains(out.String(), "\x1b[J") { + t.Fatal("must not erase child output after Release") + } +} + +func TestInlineTranscriptInputAndChildHandoff(t *testing.T) { + for _, plain := range []bool{false, true} { + t.Run(fmt.Sprint(plain), func(t *testing.T) { + var out bytes.Buffer + u := NewInline(InlineSpec{Input: strings.NewReader("alpha\r\n\nchild\n"), Output: &out, Plain: plain}) + u.Panel("Setup", "retained instructions") + for _, want := range []string{"alpha", "default"} { + got, err := u.Ask(context.Background(), "Setup", "Name", "default") + if err != nil || got != want { + t.Fatalf("got=%q want=%q err=%v", got, want, err) + } + } + u.Release() + remaining, err := io.ReadAll(u.Reader()) + if err != nil || string(remaining) != "child\n" { + t.Fatalf("buffered child input lost: %q %v", remaining, err) + } + if strings.Contains(out.String(), "\x1b") { + t.Fatal("transcript has escapes") + } + }) + } +} + +func TestInlineInputEndAndContext(t *testing.T) { + for _, tc := range []struct { + input, want string + err error + }{ + {"last", "last", nil}, {"", "", io.EOF}, {"\n", "seed", nil}, + } { + u := NewInline(InlineSpec{Input: strings.NewReader(tc.input), Output: io.Discard}) + got, err := u.Ask(context.Background(), "Setup", "Value", "seed") + if got != tc.want || !errors.Is(err, tc.err) { + t.Fatalf("input=%q got=%q err=%v", tc.input, got, err) + } + } + ctx, cancel := context.WithCancel(context.Background()) + cancel() + var out bytes.Buffer + u := NewInline(InlineSpec{Input: strings.NewReader("answer\n"), Output: &out}) + if _, err := u.Ask(ctx, "Setup", "Value", ""); !errors.Is(err, context.Canceled) || out.Len() != 0 { + t.Fatalf("cancelled ask wrote output: %q err=%v", out.String(), err) + } + // A general reader may block; cancellation after reading must still win. + ctx, cancel = context.WithCancel(context.Background()) + u = NewInline(InlineSpec{Input: inlineReaderFunc(func(p []byte) (int, error) { + cancel() + return copy(p, "answer\n"), nil + }), Output: io.Discard}) + if _, err := u.Ask(ctx, "Setup", "Value", ""); !errors.Is(err, context.Canceled) { + t.Fatal(err) + } +} + +type inlineReaderFunc func([]byte) (int, error) + +func (f inlineReaderFunc) Read(p []byte) (int, error) { return f(p) } + +type inlineBrokenWriter struct{ err error } + +func (w inlineBrokenWriter) Write([]byte) (int, error) { return 0, w.err } + +func TestInlineReport(t *testing.T) { + var out bytes.Buffer + u := NewInline(InlineSpec{Input: strings.NewReader(""), Output: &out}) + u.interactive, u.ansi = true, true + u.size = func() (int, int) { return 80, 30 } + u.Panel("Setup", "instructions") + out.Reset() + cause := errors.New("cannot continue") + err := u.Report(cause) + if !ErrorReported(fmt.Errorf("wrapped: %w", err)) || !errors.Is(err, cause) { + t.Fatal("reported error lost identity", err) + } + text := ansi.Strip(out.String()) + if strings.Count(text, "Setup") != 1 || !strings.Contains(text, "instructions") || !strings.Contains(text, cause.Error()) { + t.Fatal(text) + } + before := out.Len() + if u.Report(nil) != nil || u.Report(err) != err || out.Len() != before { + t.Fatal("nil/already-reported errors must not print twice") + } + writeErr := errors.New("broken output") + u.out = inlineBrokenWriter{writeErr} + err = u.Report(cause) + if ErrorReported(err) || !errors.Is(err, writeErr) || !errors.Is(err, cause) { + t.Fatal("failed rendering must retain both errors and not claim reported", err) + } + u = NewInline(InlineSpec{Input: strings.NewReader(""), Output: io.Discard}) + if err := u.Panel("Setup"); err != nil { + t.Fatal(err) + } + u.out = inlineBrokenWriter{writeErr} + if _, err := u.Ask(context.Background(), "Setup", "Value", ""); !errors.Is(err, writeErr) { + t.Fatal(err) + } +} + +func TestInlineNarrowWrappingAndSanitization(t *testing.T) { + for _, width := range []int{3, 12, 28, 80} { + var out bytes.Buffer + u := NewInline(InlineSpec{Input: strings.NewReader(""), Output: &out}) + u.size = func() (int, int) { return width, 30 } + u.Panel("Long title\x1b[2J", strings.Repeat("界text ", 20), "multiline\nbody\r\a\x1b]0;bad title\a") + if strings.ContainsAny(out.String(), "\x1b\r\a") { + t.Fatalf("control characters survived: %q", out.String()) + } + for _, line := range strings.Split(out.String(), "\n") { + if ansi.StringWidth(line) > width { + t.Fatalf("width %d exceeded by %q", width, line) + } + } + if !strings.Contains(out.String(), "body") && width >= 12 { + t.Fatal("multiline instructions lost") + } + } +} + +func TestInlineModelEditingSubmissionAndCancel(t *testing.T) { + makeModel := func() *inlineModel { + u := NewInline(InlineSpec{Input: strings.NewReader(""), Output: io.Discard}) + return &inlineModel{owner: u, title: "Setup", label: "Name", body: []string{"instructions"}, width: 50, + form: forms.NewForm(forms.Text("value", "Name").WithText("seed"))} + } + m := makeModel() + m.Update(tea.KeyMsg{Type: tea.KeyCtrlU}) + m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("界a")}) + m.Update(tea.KeyMsg{Type: tea.KeyBackspace}) + m.Update(tea.KeyMsg{Type: tea.KeySpace}) + m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("b")}) + if got := m.form.Focused().Text; got != "界 b" { + t.Fatalf("editing=%q", got) + } + view := ansi.Strip(m.View()) + for _, want := range []string{"Setup", "instructions", "Name: 界 b", "enter submit", "ctrl+u clear", "esc cancel"} { + if !strings.Contains(view, want) { + t.Fatalf("missing %q in %s", want, view) + } + } + m.Update(tea.WindowSizeMsg{Width: 35, Height: 20}) + for _, line := range strings.Split(m.View(), "\n") { + if ansi.StringWidth(line) > 35 { + t.Fatal("model ignored resize") + } + } + _, cmd := m.Update(tea.KeyMsg{Type: tea.KeyEnter}) + if !m.submitted || cmd == nil || !strings.Contains(m.View(), "Saved response.") { + t.Fatal("not submitted") + } + for _, key := range []tea.KeyType{tea.KeyEsc, tea.KeyCtrlC} { + m = makeModel() + _, cmd = m.Update(tea.KeyMsg{Type: key}) + if !m.cancelled || m.submitted || cmd == nil || !strings.Contains(m.View(), "Cancelled.") { + t.Fatal("not cancelled") + } + } +} + +func TestInlineScopedKeysAndHints(t *testing.T) { + scope := ui.Default() + scope.Keys = scope.Keys.With(keys.Binding{Action: keys.Confirm, Keys: []string{"ctrl+s", "s"}, Glyph: "wrong glyph"}) + u := NewInline(InlineSpec{Input: strings.NewReader(""), Output: io.Discard, UI: scope}) + m := &inlineModel{owner: u, title: "Setup", label: "Name", width: 70, + form: forms.NewForm(forms.Text("value", "Name"))} + if view := m.View(); !strings.Contains(view, "ctrl+s submit") || strings.Contains(view, "wrong glyph") || strings.Contains(view, "enter submit") { + t.Fatal(view) + } + m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("s")}) + if m.form.Focused().Text != "s" || m.submitted { + t.Fatal("printable scoped binding swallowed text") + } + m.Update(tea.KeyMsg{Type: tea.KeyCtrlS}) + if !m.submitted { + t.Fatal("scoped submit ignored") + } + scope.Keys = scope.Keys.With(keys.Binding{Action: keys.Confirm, Keys: []string{"ctrl+u"}}) + if action, _ := m.owner.editorMap().Action("ctrl+u"); action != keys.Confirm || m.owner.editorMap().Has(InlineClear) { + t.Fatal("default clear must not shadow a scoped editor binding") + } + custom := keys.NewMap(keys.Binding{Action: keys.Confirm, Keys: []string{"ctrl+d"}, Glyph: "custom"}) + u = NewInline(InlineSpec{Input: strings.NewReader(""), Output: io.Discard, Keys: custom}) + if u.editorMap() != custom { + t.Fatal("custom map ignored") + } + if m.owner.frame(40).UI != scope { + t.Fatal("frame dropped its scope") + } +} + +func ExampleInline() { + var transcript bytes.Buffer + flow := NewInline(InlineSpec{ + Input: strings.NewReader("workspace\n"), Output: &transcript, Plain: true, + }) + if err := flow.Panel("Workspace", "Choose a local directory."); err != nil { + return + } + path, err := flow.Ask(context.Background(), "Workspace", "Directory", ".") + if err != nil { + _ = flow.Report(err) + return + } + flow.Release() // hand output back to the caller without erasing it later + fmt.Println(path) + // Output: workspace +} diff --git a/skills/viewkit/references/api.md b/skills/viewkit/references/api.md index c74ceea..2cd1494 100644 --- a/skills/viewkit/references/api.md +++ b/skills/viewkit/references/api.md @@ -297,6 +297,36 @@ func (c Confirm) Render(f layout.Frame) string func (c Confirm) Overlay(bg string, f layout.Frame, pos ...layout.OverlayPos) string ``` +## deck — inline CLI workflows + +```go +type InlineSpec struct { + Input io.Reader // nil = os.Stdin + Output io.Writer // nil = os.Stdout + UI *ui.Scope // nil = ui.Default() + Width int // preferred body width, zero = document width + Plain bool // no panels, editing, or cursor movement + Keys *keys.Map // nil = text-safe scoped editor map +} +const InlineClear keys.Action = "inline.clear" // default ctrl+u +func NewInline(spec InlineSpec) *Inline +func (u *Inline) Panel(title string, lines ...string) error +func (u *Inline) Ask(ctx context.Context, title, label, value string) (string, error) +func (u *Inline) Report(err error) error // render inside current panel, preserve identity +func ErrorReported(err error) bool // suppress duplicate stderr, not exit failure +func (u *Inline) Release() // before other output, forget owned region +func (u *Inline) Reader() io.Reader // buffered input handoff after Release +var ErrCancelled error // cancelled standalone prompt +``` + +Use sequentially outside a running deck session. Panels replace only on ANSI +terminal pairs; plain/dumb/redirected output is an append-only transcript. +`Ask` keeps instructions from a preceding `Panel` with the same title. Input is +visible text, not a secret field. Callers own checks, validation, redaction, +external commands, and exit policy. Generic reader cancellation is only checked +before/after reads; interactive prompts are interruptible. No global scope or +alternate screen is installed. See README and `deck/INTERFACE.md` for lifecycle. + ## notify — `github.com/codyconfer/viewkit/notify` ```go type Tone int