Skip to content

selftest: add TUI commands for live-terminal testing - #7688

Open
pietern wants to merge 8 commits into
mainfrom
pietern/selftest-tui-coverage
Open

pietern wants to merge 8 commits into
mainfrom
pietern/selftest-tui-coverage

Conversation

@pietern

@pietern pietern commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Changes

Adds hidden databricks selftest tui commands that unblock live-terminal testing while the CLI migrates its Charm TUI libraries (bubbletea, bubbles, lipgloss, huh) from v1 to the charm.land/*/v2 modules. They drive the production cmdio, tableview and huh/appkit code paths and print what they decide or receive. That way the same observable checks can run on the current v1 build and on a v2 build side by side, across terminals (Ghostty, Terminal.app, Linux terminals, tmux, Windows Terminal, conhost, Git Bash).

New commands and flags:

  • keys: prints every key message bubbletea decodes (key string, type, runes, alt, paste). --raw skips bubbletea and prints the raw stdin bytes. Lines start at column 0 in a terminal, where bubbletea's raw mode needs \r\n. Exits on two Ctrl+C or after --timeout.
  • profile: prints the interactive mode and prompt support that cmdio decides, the color decision, color profile and dark-background flag that cmdio.NewRenderer resolves for stdout and stderr, plus the environment variables that affect them (TERM, COLORTERM, CLICOLOR, CLICOLOR_FORCE, NO_COLOR, CI, TERM_PROGRAM, WT_SESSION, COLORFGBG).
  • colors: --stream stdout|stderr picks the output stream. --lipgloss adds truecolor and 256-color swatches, which make differences in color depth visible.
  • pager: runs cmdio.RenderIterator over a fake iterator with the same template/headerTemplate annotations that list commands get, so the production pager gate applies. Flags: --items, --header, --delay-first, --delay, and --fail-after to inject an iterator error.
  • table: runs tableview.Run over generated rows (--rows, --cols).
  • huh: one huh field (--field input|select|confirm|multiselect) using the appkit theme from libs/apps/prompt. Prints the answer, the dark-background decision and the resolved blurred-button colour (the Light or Dark side of the appkit theme's AdaptiveColor).
  • spinner --duration: sets the spinner's total run time.

Only cmd/selftest/tui changes: no libs/cmdio changes and no production behaviour change. profile uses the existing cmdio helpers (GetInteractiveMode, IsPromptSupported, SupportsColor).

Not included, because each would need a production change:

  • --quit-after on prompt/select, to reproduce fast-quit behaviour: runTUI doesn't run the program with a context.
  • A link command: the only hyperlink helper is unexported in cmd/air.

Why

The v2 migration changes key decoding, color-profile detection, background detection, and the bytes written when a TUI starts and exits. Our tests run against pipes and a terminal emulator, so they can't show what a user sees in a real terminal. These commands make those behaviours directly observable for each terminal and platform, before and after the swap.

Tests

  • Unit tests for the raw key reader (keys_test.go) and for the fake iterator (pager_test.go).
  • go build, go vet, golangci-lint (./cmd/selftest/..., ./libs/cmdio/...) and gofmt all pass. The branch merges cleanly into current main (which includes cmdio: gate prompts on MSYS2 pty pipes (no ConPTY), not on Git Bash #7699 and cmdio: make NO_COLOR only affect color #7700); build, vet, lint and tests pass with main merged in.
  • No acceptance tests: in line with the existing selftest tui commands, these are tools for manual testing in a live terminal.
  • Each command was exercised by hand under a Linux PTY.

How to use

databricks selftest tui keys                 # press Esc, Alt+f, Shift+Enter, paste, ...
databricks selftest tui profile              # compare with NO_COLOR=1, TERM unset, CI=1
databricks selftest tui colors --lipgloss --stream stdout
databricks selftest tui pager --items 30 --delay-first 2s --delay 100ms
databricks selftest tui huh --field confirm

This pull request and its description were written by Isaac.

pietern and others added 3 commits November 16, 2026 15:13
Add hidden `databricks selftest tui` commands that drive the production
cmdio, tableview and huh/appkit code paths so their observable behaviour
can be checked in a live terminal. They unblock testing while the CLI
migrates its Charm TUI libraries to the charm.land v2 modules: the same
checks can run on the current v1 build and on the v2 build side by side.

- keys: print each key bubbletea decodes; --raw prints raw stdin bytes
- profile: print the color, background and env decisions for stdout/stderr
- colors: --stream stdout|stderr, --lipgloss adds color depth swatches
- pager: cmdio.RenderIterator over a fake iterator with --fail-after
- table: tableview.Run over generated rows
- huh: one form field with the appkit theme
- spinner: --duration sets the total run time

Only selftest code changes. No production behaviour changes.

Co-authored-by: Isaac <no-reply@databricks.com>
- keys --raw prints CRLF while raw mode is on, so lines start at column 0
- keys and spinner reject negative --timeout and --duration in PreRunE
- colors: replace the inline closure with a named helper
- huh: document that the field is built here and only the theme is shared
- Expected failures in acceptance tests use musterr instead of errcode
- Add a --header case to the pager acceptance test
- Gate the tui acceptance tests off Windows

Co-authored-by: Isaac <no-reply@databricks.com>
- Pin COLORFGBG in the tui acceptance env
- pager rejects negative --delay and --delay-first in PreRunE
- Tighten the writeLine comment and the --stream help text

Co-authored-by: Isaac <no-reply@databricks.com>
@pietern
pietern requested review from a team as code owners November 16, 2026 15:39
The existing selftest tui commands have no acceptance tests, and
acceptance/selftest holds the harness's own self-tests. Keep the unit
tests for the raw key reader and the fake iterator.

Co-authored-by: Isaac <no-reply@databricks.com>
@eng-dev-ecosystem-bot

eng-dev-ecosystem-bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Collaborator

✅ Integration test report

Commit: 034903f

Run: 44164797041

Env 💚​RECOVERED ✅​pass 🙈​skip Time
💚​ aws linux-2core-8gb 1 270 15 6:57
💚​ aws-windows-latest-4core-16gb 1 272 13 7:51
💚​ azure linux-2core-8gb 1 269 15 7:21
💚​ azure-windows-latest-4core-16gb 1 271 13 7:51
💚​ gcp linux-2core-8gb 1 270 15 8:20
💚​ gcp-windows-latest-4core-16gb 1 272 13 8:53
Test Name aws linux-2core-8gb aws-windows-latest-4core-16gb azure linux-2core-8gb azure-windows-latest-4core-16gb gcp linux-2core-8gb gcp-windows-latest-4core-16gb
💚​ TestAccept 💚​R 💚​R 💚​R 💚​R 💚​R 💚​R
Top 5 slowest tests (at least 2 minutes):
duration env testname
4:00 gcp-windows-latest-4core-16gb TestFilerWorkspaceFilesExtensionsDelete
3:41 aws-windows-latest-4core-16gb TestAccept
3:23 azure-windows-latest-4core-16gb TestAccept
3:06 gcp-windows-latest-4core-16gb TestAccept
2:29 gcp linux-2core-8gb TestFilerWorkspaceFilesExtensionsReadDir

Comment thread cmd/selftest/tui/keys.go Outdated
}
line := fmt.Sprintf("key=%q type=%d runes=%q alt=%t paste=%t",
key.String(), key.Type, string(key.Runes), key.Alt, key.Paste)
fmt.Fprintln(m.out, line)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bubbletea puts the TTY in raw mode (which clears OPOST), so this bare "\n" from Fprintln doesn't return the carriage and the key log staircases across the screen in a real terminal, which is the one place this command is meant to run. The --raw path already handles this with "\r\n"; do the same here.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 7888c24. The bubbletea path now prints \r\n when stdin is a terminal, the same condition under which bubbletea enters raw mode, so each key line starts at column 0. The --raw path shares the check through a small rawInputFile helper. None of the other new commands write while a tea program holds the TTY: the spinner's program has no input, and table, pager and huh print after their program exits.

Comment thread cmd/selftest/tui/huh.go Outdated

r, _ := cmdio.NewRenderer(ctx, cmd.ErrOrStderr())
cmdio.LogString(ctx, fmt.Sprintf("dark_background=%t", r.HasDarkBackground()))
cmdio.LogString(ctx, fmt.Sprintf("blurred_button=%+v", theme.Focused.BlurredButton.GetForeground()))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

GetForeground() returns the static lipgloss.AdaptiveColor from AppkitTheme, so this always prints {Light:#A1A1AA Dark:#52525B} whatever the terminal is, and it can't show which colour huh actually picked. If the goal is to see the resolved colour, print the Light or Dark value chosen by the renderer's HasDarkBackground, or drop the line.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in d5e908a. It now prints the side lipgloss resolves, e.g. blurred_button=#52525B (resolved, default renderer dark_background=true). That uses the default renderer's HasDarkBackground, which is what the theme's styles render with (huh's ThemeBase builds them with lipgloss.NewStyle()), so it matches what the production prompts pick.

pietern and others added 4 commits November 17, 2026 19:06
bubbletea puts the terminal in raw mode, which clears OPOST, so the bare
"\n" from the keys log staircased across the screen. Use "\r\n" there too,
the same way the --raw path already does. The other new commands print
outside any tea program: spinner's program has no input, and the table,
pager and huh output comes after or outside tea's raw-mode window.

Co-authored-by: Isaac <no-reply@databricks.com>
GetForeground returned the static AdaptiveColor, which printed the same
Light/Dark pair whatever the terminal was. Print the side lipgloss picks
with the default renderer, which is the renderer the theme's styles use.

Co-authored-by: Isaac <no-reply@databricks.com>
After #7700 NO_COLOR only turns color off, and TERM=dumb also turns off
prompts and spinners. Print cmdio's interactive mode and prompt decision
next to the raw env values, so a run under NO_COLOR shows prompts still on.
This uses the existing cmdio helpers; libs/cmdio is unchanged.

Co-authored-by: Isaac <no-reply@databricks.com>
Co-authored-by: Isaac <no-reply@databricks.com>
@pietern

pietern commented Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

/review

@review-oss-bot review-oss-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good to me — no issues found.

@pietern

pietern commented Nov 20, 2026

Copy link
Copy Markdown
Contributor Author

/review

@review-oss-bot review-oss-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated review at 034903f. Each finding was verified against the code.

Not ready yet: part of the automated review did not complete.

This PR adds several hidden databricks selftest tui subcommands (keys, profile, colors, pager, table, huh, spinner --duration) for live-terminal testing during the Charm v1→v2 migration. The commands are well-structured with consistent flag validation and cobra wiring. The two new test files cover the non-interactive helpers (runRawKeys, pagerFakeIterator). The remaining findings are convention-level: test package naming and missing test files for three new source files.

@@ -0,0 +1,26 @@
package tui

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nit] keys_test.go and pager_test.go both declare package tui; .agents/rules/testing.md asks for package tui_test. These tests call unexported symbols (runRawKeys, pagerFakeIterator, buildPagerRows), so switching requires either exporting them or adding an export_test.go bridge. Same issue in pager_test.go:1.

Comment thread cmd/selftest/tui/huh.go
@@ -0,0 +1,99 @@
package tui

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nice to have] huh.go, profile.go, and table.go are new files with no corresponding _test.go, which .agents/rules/testing.md asks for. The rest of this directory was test-free before this PR, and the files are mostly cobra wiring for interactive commands, so the value is limited — but if any testable logic can be extracted (the way runRawKeys was pulled out of keys.go), a test file would be consistent with the pattern you already set here.

@pietern

pietern commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

/review

@review-oss-bot review-oss-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated review at 034903f. Each finding was verified against the code.

No blocking issues found. 4 non-blocking comment(s) below.

This PR adds hidden selftest tui commands (keys, profile, pager, table, huh, plus new flags on colors and spinner) for checking TUI behaviour in a real terminal during the Charm v1→v2 migration. The commands mostly wrap existing cmdio code and look fine. One real bug: keys --raw errors out on Git Bash without ConPTY, which is one of the terminals the description lists. The rest are smaller: a --fail-after value that is silently ignored, plus two pieces of dead code.

Comment thread cmd/selftest/tui/keys.go
// --raw path put that file in raw mode, which is why output needs "\r\n".
func rawInputFile(ctx context.Context, in io.Reader) (*os.File, bool) {
f, ok := in.(*os.File)
return f, ok && cmdio.IsInputTTY(ctx)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nice to have] cmdio.IsInputTTY is also true for MSYS2/Cygwin pty pipes, because isTTY ORs in isatty.IsCygwinTerminal (see libs/cmdio/conpty.go). In Git Bash/mintty with MSYS=disable_pcon, keys --raw therefore calls term.MakeRaw on a named pipe. That fails, so the command exits with an error before printing a single byte. The bubbletea path picks \r\n for the same wrong reason. Can this check term.IsTerminal(int(f.Fd())) instead, so --raw falls back to reading the pipe as-is? The doc comment's "when it is a terminal" would then match what the code checks.

Comment thread cmd/selftest/tui/pager.go
if delayFirst < 0 || delay < 0 {
return fmt.Errorf("--delay and --delay-first must not be negative, got %s and %s", delay, delayFirst)
}
if failAfter < -1 {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nice to have] pager --items 2 --fail-after 5 prints both rows and exits 0. The iterator never reaches row 5, so the error you asked for is never injected and nothing says so. AGENTS.md says not to silently ignore a flag the current mode can't honor. Can PreRunE also reject failAfter > items with an error that names both flags? The "failure past the end is never reached" test case would then become a PreRunE test.

Comment thread cmd/selftest/tui/pager.go
return cmdio.RenderIterator(cmd.Context(), it)
},
Annotations: map[string]string{
"headerTemplate": pagerDefaultHeader,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nit] Args always overwrites headerTemplate, and --header defaults to "Name", so pagerDefaultHeader and this annotation entry never take effect. Drop them and keep only the template annotation?

Comment thread cmd/selftest/tui/huh.go
resolved = adaptive.Dark
}
cmdio.LogString(ctx, fmt.Sprintf("blurred_button=%s (resolved, default renderer dark_background=%t)", resolved, dark))
} else {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nit] AppkitTheme always sets BlurredButton to colorDimmed, which is a lipgloss.AdaptiveColor (libs/apps/prompt/prompt.go:35). The type assertion always succeeds and this else branch is a just-in-case fallback, which AGENTS.md asks to avoid. Assert the type directly and drop the branch?

camielstee-db pushed a commit to camielstee-db/cli that referenced this pull request Nov 24, 2026
…atabricks#7884)

## Changes
Halve the agent rules: 66 KB → 33 KB of AGENTS.md + `.agents/rules/`.
The rules that are always loaded or loaded on every Go edit shrink the
most:

| Context loaded | Before | After |
|---|---|---|
| Always (AGENTS.md) | 12.2 KB | 6.1 KB |
| Editing a `.go` file (+ style-guide-go, comments) | 23.5 KB | 9.7 KB |
| Editing a `_test.go` file (+ testing) | 45.8 KB | 17.5 KB |
| Editing acceptance outputs (+ testing, auto-generated-files) | 38.5 KB
| 16.4 KB |

Skills are unchanged: they load only when invoked.

What was removed, and why:

- **Already enforced by `./task lint`** (the agent gets the same message
from the linter):
  - integer `range`, builtin `min`/`max` (modernize)
  - loop-variable capture (copyloopvar)
  - `os.Getenv`, `sync.Once` (forbidigo)
  - `context.Background()` (gorules)
  - `t.Context()` in tests (usetesting)
  - stdlib `log` (depguard)
  - `%w` wrapping (errorlint)
  - error-string punctuation (staticcheck ST1005)
  - copying `config.Config` (govet copylocks)
- **Wrong or stale:**
- `errors.As` was recommended, but forbidigo bans it (the tree has 0
`errors.As` calls vs 231 `errors.AsType`).
  - `isResourceGone` doesn't exist.
  - `libs/structpath` has moved to `libs/structs/structpath`.
  - "consult the Makefile": there is no Makefile.
- The `out.test.toml` old-format migration rule is dead: 0 files are
left in that format.
- "Use Python 3.11" also applied to `python/`, which supports `>=3.10`.
- The `databricks_template_schema.json` "reference" was an outdated copy
of dbt-sql's schema. It described a description convention the real file
no longer uses, and it had a typo. It is replaced by pointers to the
real templates and to `libs/jsonschema/extension.go`.
- template-versions.md hardcoded how many pins each template has. The
counts were wrong; the grep in the same rule is what the agent should
rely on.
- **Rules that produced wrong review feedback:**
- "Each source file should have a corresponding test file": 38% of
source files have none, and the rule contradicts acceptance-tests-first.
The reviewer bot used it to request tests for cobra wiring, and those
requests were ignored:
databricks#7688 (comment),
databricks#7742 (comment)
- "Place tests in the same package but with a `_test` suffix": 1050 test
files use the internal package and 231 use `_test`. The rule led to an
invented `_internal_test.go` convention that the author rejected:
databricks#7847 (comment)
- "Add `.databricks` to `Ignore`": `acceptance/script.cleanup` already
removes it. This produced a wrong `[blocking]` comment:
databricks#7846 (comment)
- "Define magic strings as named constants, even if short": reviewers
push back on single-use constants
(databricks#5844 (comment),
databricks#6204 (comment),
databricks#6149 (comment)).
- **Generic guidance current models already follow:**
  - return early
  - `switch` vs `if/else`
  - empty-struct context keys
  - table-driven tests
  - shared test constants
  - Go doc comment format
  - constructor parameter structs
  - "don't explain each test case in your responses"
  - debug prints (pr-checklist already covers them)
  - the GOOD/BAD preamble
- **Repetition:**
- `Cloud = true` runs locally too: this was explained 5 times and is now
explained once in AGENTS.md and once in testing.md.
  - `integration/` is deprecated: stated 4 times.
- "Don't edit generated outputs": stated 4 times across testing.md and
auto-generated-files.md.
- The `print_requests.py`/`jq` guidance was 3 overlapping rules and is
now 1.
- The long GOOD/BAD examples were dropped where the rule sentence
already says it.

Clarified:
- `os.Exit`: the rule now says how `TestMain` should exit. The bot had
suggested `os.Exit(m.Run())`, against this same rule:
databricks#7595 (comment)
- Comments: existing comments may be updated when your change makes them
wrong.

## Why
The rules were mostly mined from review history in
databricks#5078. That PR's follow-up
promised a slim-down that never came
(databricks#4882), and token cost had
already come up in review (databricks#6584).
Every byte of AGENTS.md and the Go/test rules is paid on most turns, and
rules that are wrong or that the linter already enforces either crowd
out the useful ones or become review noise. I checked the 98 comments
from review-oss-bot and the human pushback since 2026: the rules that
went wrong are the ones removed above. The acceptance-test rules that
came from real agent failures (`Cloud`, `EnvMatrix`, TOML dotted keys,
`musterr`/`errcode`, `print_requests.py`, testserver over `[[Server]]`,
GET-response projection) are kept, just shorter.

## Tests
`./task check-agents-setup` and `./task checks` pass. Every path,
helper, task and identifier still mentioned was checked against the
tree.

This pull request and its description were written by Isaac.

---------

Co-authored-by: Isaac <no-reply@databricks.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants