Skip to content

Commit 3008d9b

Browse files
authored
Refuse to prompt when nothing can answer the prompt (#652)
`basecamp setup --json < /dev/null` hung forever. #646 removed `timeline --watch` as "the only reachable tea.NewProgram without a gate", but that claim came from `rg 'tea.NewProgram'`, and the instrument could not see the larger family: internal/tui/forms.go wraps huh, and huh calls tea.NewProgram inside its own package. Every tui.Confirm/Select/Input was a bubbletea launcher the grep never showed, and `NewSetupCmd` reached one with no interactivity check at all. Two things make a reached prompt hang rather than fail. Bubble Tea does not error on a non-terminal stdin — it opens /dev/tty and waits on the real terminal (tea.go:590-613). And InteractiveStdio() tested ModeCharDevice, so /dev/null passed: `cmd < /dev/null`, which is exactly how an agent says it has nothing to type, was classified interactive. So fix the instrument rather than adding another call-site check: - InteractiveStdio() now asks term.IsTerminal, from the same charmbracelet/x/term that Bubble Tea itself imports, so this floor and the /dev/tty fallback it prevents cannot disagree about what a terminal is. IsPiped keeps the character-device test; it answers a different question. Adds InteractivePrompt() for stdin+stderr, because huh draws forms to stderr while the picker draws to stdout — asking about the wrong stream would let `cmd 2>somewhere` render an invisible question that still blocks a terminal, and would refuse `cmd | less` where the prompt would have worked fine. - internal/tui grows a floor with one guarded runner per launcher: every huh form goes through runForm, every bubbletea program through runPicker. Both return a typed ErrNotInteractive. This covers prompts nobody has written yet, which a call-site audit cannot — the audit is what missed setup. - `basecamp setup` refuses non-interactive stdio and machine-output modes with a usage error naming what does work without a terminal. The gate is on the parent's RunE only: `setup claude`, `setup codex` and `setup agents` stay non-interactive and keep working. Refusing machine output leaves the wizard's structured envelope unreachable, so that branch, its two helpers and WizardResult's json tags go with it. - `chat delete` refuses before any lookup when it would reach a confirmation stdin cannot answer, naming --force. isNonInteractiveCommand is left alone; it reads stdout, never stdin, and widening it would change missingArg and noChanges across many commands. Tests. A structural check that fails on a bubbletea launcher or a huh import outside a short allowlist, and — inside an allowlisted file — on a launch outside its named runner, so a second unguarded program cannot ride in on the file's exemption. Its import resolver is itself tested, because getting it wrong is silent. Both bubbletea modules sit at a path ending in bubbletea (or bubbletea/v2) and declare `package tea`, so path and package name disagree: deriving the identifier from the path registers "bubbletea" while the file binds "tea", and every unaliased launcher walks straight past. Nothing in the repo would have noticed, since picker.go happens to alias its import. The resolver now records each module's declared package name and honors an explicit alias over it, with all four spellings pinned by test. Also: a table over every exported prompt, AST-checked for completeness, that fails if a new prompt skips the floor. A predicate matrix whose terminal/terminal row is the baseline that keeps the negative rows from holding vacuously. And e2e cases that put a real pty on stdout with /dev/null on stdin, the only shape that reproduces the original hang. Tests that used /dev/null as a terminal stand-in now open /dev/ptmx, and each floor test points the launcher's own output stream at a pty so stdin is the variable actually under test.
1 parent c058edd commit 3008d9b

24 files changed

Lines changed: 2130 additions & 313 deletions

‎e2e/setup.bats‎

Lines changed: 193 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,193 @@
1+
#!/usr/bin/env bats
2+
# setup.bats - `basecamp setup` refuses to prompt when nothing can answer it.
3+
#
4+
# The wizard is prompts end to end, and huh runs them as a bubbletea program.
5+
# Redirecting stdin does not make that program fail: bubbletea sees a
6+
# non-terminal stdin and opens /dev/tty instead, so the prompt waits on the real
7+
# terminal — `basecamp setup --json < /dev/null` hung forever.
8+
#
9+
# Every case runs under a timeout, and the timeout is the assertion: exit 124 is
10+
# the bug reproducing. A unit test with a fake reader cannot catch this, because
11+
# the hang lives in what the real os.Stdin makes bubbletea do — which is also
12+
# why the PTY case at the bottom exists. Under bats alone, stdout is captured,
13+
# so stdout is what fails the interactivity check and stdin is never the
14+
# deciding factor.
15+
16+
load test_helper
17+
18+
# timeout_bin names GNU timeout, which stock macOS does not ship. Tests that
19+
# need it skip rather than silently drop their only real assertion.
20+
timeout_bin() {
21+
if command -v timeout >/dev/null 2>&1; then
22+
echo timeout
23+
elif command -v gtimeout >/dev/null 2>&1; then
24+
echo gtimeout
25+
fi
26+
}
27+
28+
# run_guarded runs a shell snippet under a timeout.
29+
#
30+
# The timeout wraps the whole shell, not the snippet's first word. Prefixing it
31+
# (`timeout 10 printf '' | basecamp setup`) times `printf` and leaves `basecamp`
32+
# to hang the suite forever — the exact failure these tests exist to catch.
33+
# pipefail so a refusal upstream of a pipe is not masked by the last stage.
34+
run_guarded() {
35+
local to
36+
to="$(timeout_bin)"
37+
if [[ -z "$to" ]]; then
38+
skip "no GNU timeout available (install coreutils)"
39+
fi
40+
run "$to" 10 bash -c "set -o pipefail; $1"
41+
}
42+
43+
assert_not_timed_out() {
44+
if [[ "$status" -eq 124 ]]; then
45+
echo "Command hit the timeout (exit 124) — it hung instead of refusing"
46+
echo "Output: $output"
47+
return 1
48+
fi
49+
}
50+
51+
# assert_refused is the whole contract: exit 1, a usage envelope, and a hint
52+
# naming something that works without a terminal. "Non-zero and not 124" is too
53+
# weak — the pre-fix binary also exits non-zero where no controlling terminal
54+
# exists, on huh's own TTY error, several steps in.
55+
assert_refused() {
56+
assert_not_timed_out
57+
assert_exit_code 1
58+
assert_json_value '.code' 'usage'
59+
assert_json_value '.hint | contains("basecamp setup agents")' 'true'
60+
}
61+
62+
63+
@test "setup --json with stdin closed refuses instead of hanging" {
64+
create_credentials
65+
create_global_config '{"account_id": 99999}'
66+
67+
run_guarded "basecamp setup --json < /dev/null"
68+
assert_refused
69+
}
70+
71+
@test "setup without --json and stdin closed refuses instead of hanging" {
72+
create_credentials
73+
create_global_config '{"account_id": 99999}'
74+
75+
run_guarded "basecamp setup < /dev/null"
76+
assert_refused
77+
}
78+
79+
@test "setup with piped stdin refuses instead of hanging" {
80+
create_credentials
81+
create_global_config '{"account_id": 99999}'
82+
83+
run_guarded "printf '' | basecamp setup --json"
84+
assert_refused
85+
}
86+
87+
@test "setup with piped stdout refuses instead of hanging" {
88+
create_credentials
89+
create_global_config '{"account_id": 99999}'
90+
91+
run_guarded "basecamp setup --json < /dev/null | cat"
92+
assert_refused
93+
}
94+
95+
96+
# The reported bug: a real terminal on stdout, nothing on stdin. bats cannot
97+
# produce that on its own — it captures stdout — so borrow a pty from script(1).
98+
# The exit code travels in a sentinel rather than through script, whose status
99+
# propagation differs between the util-linux and BSD versions.
100+
101+
# run_in_pty runs a shell snippet with stdout attached to a pseudo-terminal.
102+
run_in_pty() {
103+
local snippet="$1"
104+
if ! command -v script >/dev/null 2>&1; then
105+
skip "script(1) not available to allocate a pty"
106+
fi
107+
if script --version 2>&1 | grep -qi util-linux; then
108+
run bash -c "script -qec '$snippet' /dev/null | tr -d '\r'"
109+
else
110+
run bash -c "script -q /dev/null /bin/sh -c '$snippet' | tr -d '\r'"
111+
fi
112+
}
113+
114+
@test "setup --json on a terminal with stdin closed refuses instead of hanging" {
115+
create_credentials
116+
create_global_config '{"account_id": 99999}'
117+
118+
local to
119+
to="$(timeout_bin)"
120+
if [[ -z "$to" ]]; then
121+
skip "no GNU timeout available (install coreutils)"
122+
fi
123+
124+
# stdout is a pty here, so /dev/null on stdin is the only disqualifier — the
125+
# case a character-device check called interactive and bubbletea did not.
126+
run_in_pty "$to 10 basecamp setup --json < /dev/null; echo EXIT:\$?"
127+
128+
assert_output_not_contains "EXIT:124"
129+
assert_output_contains "EXIT:1"
130+
assert_output_contains "basecamp setup agents"
131+
}
132+
133+
@test "setup on a terminal with stdin closed refuses instead of hanging" {
134+
create_credentials
135+
create_global_config '{"account_id": 99999}'
136+
137+
local to
138+
to="$(timeout_bin)"
139+
if [[ -z "$to" ]]; then
140+
skip "no GNU timeout available (install coreutils)"
141+
fi
142+
143+
run_in_pty "$to 10 basecamp setup < /dev/null; echo EXIT:\$?"
144+
145+
assert_output_not_contains "EXIT:124"
146+
assert_output_contains "EXIT:1"
147+
assert_output_contains "basecamp setup agents"
148+
}
149+
150+
151+
# The gate is on the parent's RunE only. These three are the supported
152+
# non-interactive paths and have to keep working — a persistent hook would have
153+
# taken all of them out, which is the easiest thing to get wrong here.
154+
155+
# hide_agent_binaries drops the developer's real claude/codex from PATH. Without
156+
# it these tests shell out to whichever agent CLI happens to be installed, and
157+
# those have prompts of their own — a hang in somebody else's tool, unrelated to
158+
# the gate under test. What we are asserting is that the parent's gate does not
159+
# reach the subcommands, and that holds with or without an agent installed.
160+
hide_agent_binaries() {
161+
export PATH="$BASECAMP_ROOT/bin:/usr/bin:/bin"
162+
}
163+
164+
@test "setup agents still runs without a terminal" {
165+
create_credentials
166+
create_global_config '{"account_id": 99999}'
167+
hide_agent_binaries
168+
export BASECAMP_SETUP_AGENT=none
169+
170+
run_guarded "basecamp setup agents --json < /dev/null"
171+
assert_not_timed_out
172+
assert_success
173+
}
174+
175+
@test "setup claude still runs without a terminal" {
176+
create_credentials
177+
create_global_config '{"account_id": 99999}'
178+
hide_agent_binaries
179+
180+
run_guarded "basecamp setup claude --json < /dev/null"
181+
assert_not_timed_out
182+
assert_success
183+
}
184+
185+
@test "setup codex still runs without a terminal" {
186+
create_credentials
187+
create_global_config '{"account_id": 99999}'
188+
hide_agent_binaries
189+
190+
run_guarded "basecamp setup codex --json < /dev/null"
191+
assert_not_timed_out
192+
assert_success
193+
}

‎internal/appctx/context.go‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -375,10 +375,11 @@ func (a *App) IsInteractive() bool {
375375
return false
376376
}
377377

378-
// Both stdout and stdin must be character devices: a TUI draws to stdout
379-
// and reads keystrokes from stdin, so a pipe on either end can never
380-
// drive one — and when the command is consuming piped content (a "-"
381-
// stdin input), a TUI would eat that content as key events.
378+
// Both stdout and stdin must be terminals: a TUI draws to stdout and reads
379+
// keystrokes from stdin, so a pipe on either end can never drive one — and
380+
// when the command is consuming piped content (a "-" stdin input), a TUI
381+
// would eat that content as key events. A character device is not enough;
382+
// /dev/null is one and delivers nothing. See stdinarg.InteractiveStdio.
382383
return stdinarg.InteractiveStdio()
383384
}
384385

‎internal/appctx/context_test.go‎

Lines changed: 19 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"net/http"
88
"net/http/httptest"
99
"os"
10+
"runtime"
1011
"sync/atomic"
1112
"testing"
1213
"time"
@@ -205,30 +206,34 @@ func TestIsInteractiveWithCountMode(t *testing.T) {
205206
}
206207

207208
func TestIsInteractiveWithNonInteractiveEnv(t *testing.T) {
208-
// Swap os.Stdout to the null device — a char device that passes the
209-
// ModeCharDevice guard — so IsInteractive() would otherwise return true.
210-
// Without this, go test's piped stdout makes IsInteractive() false regardless
211-
// of the env var, and the assertion would pass even if the short-circuit were
212-
// removed.
213-
devNull, err := os.Open(os.DevNull)
209+
// Point both ends at a pseudo-terminal so IsInteractive() would otherwise
210+
// return true. Without this, go test's piped stdout and /dev/null stdin make
211+
// it false regardless of the env var, and the assertion would pass even if
212+
// the short-circuit were removed. /dev/null will not stand in for a terminal
213+
// here: it is a character device but not a terminal, which is precisely the
214+
// distinction IsInteractive() now draws.
215+
if runtime.GOOS == "windows" {
216+
t.Skip("no /dev/ptmx on Windows")
217+
}
218+
pty, err := os.OpenFile("/dev/ptmx", os.O_RDWR, 0)
214219
if err != nil {
215-
t.Skip(os.DevNull + " not available")
220+
t.Skipf("open /dev/ptmx: %v", err)
216221
}
217-
origStdout := os.Stdout
218-
os.Stdout = devNull
222+
origStdout, origStdin := os.Stdout, os.Stdin
223+
os.Stdout, os.Stdin = pty, pty
219224
t.Cleanup(func() {
220-
os.Stdout = origStdout
221-
devNull.Close()
225+
os.Stdout, os.Stdin = origStdout, origStdin
226+
pty.Close()
222227
})
223228

224229
cfg := &config.Config{}
225230
app := NewApp(cfg)
226231

227-
// Baseline: char-device stdout, no env/flags → interactive.
232+
// Baseline: terminal stdio, no env/flags → interactive.
228233
t.Setenv("BASECAMP_NONINTERACTIVE", "")
229-
require.True(t, app.IsInteractive(), "char-device stdout should be interactive without the escape hatch")
234+
require.True(t, app.IsInteractive(), "terminal stdio should be interactive without the escape hatch")
230235

231-
// The env escape hatch forces non-interactive even with an interactive stdout.
236+
// The env escape hatch forces non-interactive even with interactive stdio.
232237
t.Setenv("BASECAMP_NONINTERACTIVE", "1")
233238
assert.False(t, app.IsInteractive(), "BASECAMP_NONINTERACTIVE should force non-interactive")
234239
// Output format is untouched — the escape hatch only disables prompts.

‎internal/cli/root.go‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -578,13 +578,15 @@ func profileNames(cfg *config.Config) string {
578578
}
579579

580580
// isInteractiveTTY reports whether the profile picker may run: no
581-
// noninteractive mode set, and both ends of stdio are character devices.
581+
// noninteractive mode set, and both ends of stdio are terminals.
582582
//
583583
// Stdin counts because the picker is a TUI reading key events, and this runs
584584
// from PersistentPreRunE — before any command touches its own input. Gating on
585585
// stdout alone let "printf body | basecamp todos create -" open the picker on
586-
// a terminal stdout and consume the piped body as keystrokes. Same predicate
587-
// as App.IsInteractive and resolve.Resolver.IsInteractive.
586+
// a terminal stdout and consume the piped body as keystrokes. A character
587+
// device is not enough either: /dev/null is one, delivers no keystrokes, and
588+
// Bubble Tea answers it by waiting on /dev/tty. Same predicate as
589+
// App.IsInteractive and resolve.Resolver.IsInteractive.
588590
func isInteractiveTTY(flags appctx.GlobalFlags) bool {
589591
if config.NonInteractiveEnv() {
590592
return false

‎internal/cli/root_test.go‎

Lines changed: 18 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package cli
33
import (
44
"bytes"
55
"os"
6+
"runtime"
67
"testing"
78

89
"github.com/spf13/cobra"
@@ -166,7 +167,7 @@ func isolateRootTest(t *testing.T) {
166167
}
167168

168169
func TestIsInteractiveTTYWithNonInteractiveEnv(t *testing.T) {
169-
stubCharDeviceStdio(t)
170+
stubTerminalStdio(t)
170171

171172
t.Setenv("BASECAMP_NONINTERACTIVE", "")
172173
require.True(t, isInteractiveTTY(appctx.GlobalFlags{}))
@@ -283,10 +284,10 @@ func TestVersionWithJQReturnsUsageError(t *testing.T) {
283284
// feeding a "-" content input the picker would eat that body as keystrokes —
284285
// so a terminal stdout is not on its own enough to open one.
285286
func TestIsInteractiveTTYRequiresUnpipedStdin(t *testing.T) {
286-
stubCharDeviceStdio(t)
287+
stubTerminalStdio(t)
287288
t.Setenv("BASECAMP_NONINTERACTIVE", "")
288289

289-
require.True(t, isInteractiveTTY(appctx.GlobalFlags{}), "char-device stdio is interactive")
290+
require.True(t, isInteractiveTTY(appctx.GlobalFlags{}), "terminal stdio is interactive")
290291

291292
reader, writer, err := os.Pipe()
292293
require.NoError(t, err)
@@ -306,13 +307,12 @@ func TestIsInteractiveTTYRequiresUnpipedStdin(t *testing.T) {
306307
// must stay nil for cobra's unknown-command handling), so quick-start's own
307308
// interactive paths sit behind it. The e2e suite always has a piped stdout,
308309
// which takes the machine-output branch and never reaches them — this covers
309-
// the other side: a character-device stdout, the terminal stand-in, with a
310-
// piped stdin. The root carries a subcommand so InstallDashGuard takes the
310+
// the other side: a terminal stdout with a piped stdin. The root carries a subcommand so InstallDashGuard takes the
311311
// pre-run branch production uses, not the Args branch for a childless root.
312312
func TestRootDashGuardWithTerminalStdout(t *testing.T) {
313313
isolateRootTest(t)
314314

315-
stubCharDeviceStdio(t)
315+
stubTerminalStdio(t)
316316
t.Setenv("BASECAMP_NONINTERACTIVE", "")
317317

318318
reader, writer, err := os.Pipe()
@@ -350,16 +350,23 @@ func TestRootDashGuardWithTerminalStdout(t *testing.T) {
350350
// device, so interactivity assertions do not depend on how `go test` itself was
351351
// invoked — a piped stdin on the test runner would otherwise fail the
352352
// interactive baseline now that both streams are checked.
353-
func stubCharDeviceStdio(t *testing.T) {
353+
// stubTerminalStdio points stdio at a pseudo-terminal, the only stand-in
354+
// isInteractiveTTY accepts. /dev/null used to serve here — it is a character
355+
// device — but a character device is not a terminal, and treating it as one is
356+
// how `cmd < /dev/null` ended up launching prompts that wait on /dev/tty.
357+
func stubTerminalStdio(t *testing.T) {
354358
t.Helper()
355-
devNull, err := os.Open(os.DevNull)
359+
if runtime.GOOS == "windows" {
360+
t.Skip("no /dev/ptmx on Windows")
361+
}
362+
pty, err := os.OpenFile("/dev/ptmx", os.O_RDWR, 0)
356363
if err != nil {
357-
t.Skip(os.DevNull + " not available")
364+
t.Skipf("open /dev/ptmx: %v", err)
358365
}
359366
origStdout, origStdin := os.Stdout, os.Stdin
360-
os.Stdout, os.Stdin = devNull, devNull
367+
os.Stdout, os.Stdin = pty, pty
361368
t.Cleanup(func() {
362369
os.Stdout, os.Stdin = origStdout, origStdin
363-
devNull.Close()
370+
pty.Close()
364371
})
365372
}

0 commit comments

Comments
 (0)