diff --git a/README.md b/README.md index f0c20c1..69f46be 100644 --- a/README.md +++ b/README.md @@ -55,9 +55,9 @@ billing the API. Deck finds `claude` on the PATH it was started with, which is not always the one your shell has. A tmux server started without nvm loaded, for example, finds a system-wide install your shell never reaches. So starting a session names the -file it ran, and for `claude` and `cathode` the `claude` version that answers, -in the footer: `started /usr/local/bin/claude (2.0.9) in …`. A version you do -not recognise is a second install. +file it ran, and for `claude` and `cathode` the `claude` it finds and its +version, in the footer: `started /usr/local/bin/claude (2.0.9) in …`. A path or +version you did not expect means that install is not the one you updated. ## Use diff --git a/docs/architecture.md b/docs/architecture.md index 5bd99de..3eb5a06 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -359,7 +359,7 @@ Three rules the design rests on: for the next event or for `inbox`. Inside a subagent, where hooks also fire with `agent_id` set, because the subagent may never pass it on. On a `Stop` already continuing from a stop hook, because Claude Code ends a - turn after eight continuations in a row and drops the hook's output. And + turn after eight continuations in a row whatever the hook replies. And past `mailBudget`, because context over Claude Code's 10,000-character cap becomes a file the agent is not asked to read. @@ -375,14 +375,28 @@ Wiring the agent is where Deck knows most about the program it hosts second config with `-mcp`. Any other agent gets no config file at all. Starting one also names what ran (`ui/agentinfo.go`). The footer gives the file -the agent's name resolved to on PATH, and for `claude` and `cathode` — which -starts `claude` by name from the PATH it inherits — the `claude` that answers -and its `--version`. That check runs as a command off the UI's goroutine, and -its answer replaces the notice only if nothing newer has. It exists because a -second install is easy to have and invisible otherwise: a tmux server started -without nvm loaded found a stale system-wide `claude` that the user's own shell -never reached, and every session failed with a model the API no longer serves -while the same command typed by hand worked. +the agent ran, `Runner.Path`, which is `exec.Cmd`'s own answer rather than a +second lookup: the PATH hit for a bare name, or a path as given — absolute, or +relative to the directory it ran in. Working the path out again was tried and +named the wrong file: a lexical join takes `..` differently from the kernel +inside a symlinked directory. `checkCommandFile` refuses a path that is missing +or a directory with that reason, and hands the path to the kernel as written +for the same reason. For `claude`, and for `cathode`, whose default backend +starts `claude` by name from the PATH it inherits, the footer adds the `claude` +that PATH finds and its `--version`, run in the session's directory so a +relative path finds the same file. + +That check runs as a command off the UI's goroutine, bounded by +`versionTimeout`, plus `WaitDelay` for a wrapper's child that still holds the +output pipe. The timeout kills the process it started, not that process's own +children. A failure is shown with the first line `claude` wrote to stderr, and a +timeout says so rather than reading as a crash. The answer replaces the notice +only if that notice is still the one from the same start, counted by +`Model.starts`, because two starts in one directory set identical notices. It +exists because a second install is easy to have and invisible otherwise: a tmux +server started without nvm loaded found a stale system-wide `claude` that the +user's own shell never reached, and every session failed with a model the API +no longer serves while the same command typed by hand worked. `TestLiveClaudeSeesSiblings` drives a real `claude` against the server and is the only test that proves config shape, transport, and tool naming actually @@ -853,9 +867,12 @@ directory: that would put an agent to work in a tree the user believed was untouched. A corrupt `state.json` fails the launch rather than starting empty, because starting empty invites duplicate worktrees over sessions we cannot see. Closing a session leaves its worktree on disk and says where. `model.fault` -holds errors the user must see and is never auto-cleared. Every write into an -agent pane goes through `toAgent`, so no keystroke, literal `^g` or wheel -notch can drop a failed write. +holds errors the user must see. Time never clears it; the next key Deck +handles itself does, because the footer was in view when it was pressed. A key +sent to an attached agent does not, and a fault that stayed for the whole run +hid every notice after it. Every write into an agent pane goes through +`toAgent`, so no keystroke, literal `^g` or wheel notch can drop a failed +write. Reporting is not the same as abandoning. `ui.formProblem` puts a failure *into* the open form instead of dismissing it, so the user keeps what they typed and @@ -990,7 +1007,8 @@ already reads `Status`. Without it the model stayed attached, so every key was written to a dead PTY. The first one was refused and surfaced `send to agent: process has exited`, which reads as a fault in Deck rather than as the agent having quit — and -the fault line is never auto-cleared, so it stayed on screen. +every later key went to the agent, which never clears the fault line, so it +stayed on screen. The pane says what to do next, because the banner only said what had happened. `↵` runs `attach`, which already restarts an exited runner rather than diff --git a/internal/agent/agent.go b/internal/agent/agent.go index 998b855..db0a061 100644 --- a/internal/agent/agent.go +++ b/internal/agent/agent.go @@ -45,7 +45,12 @@ type Config struct { // Runner owns one PTY, one child process, and one emulated screen. type Runner struct { - cfg Config + cfg Config + // path is the file exec runs: what PATH gave for a bare name, or the + // command as given — absolute, or relative to Dir, or to Deck's own + // directory when Dir is empty. Read off exec.Cmd rather than worked out + // again, because a second resolution can disagree with it. + path string cmd *exec.Cmd ptmx *os.File term *vt.SafeEmulator @@ -89,8 +94,9 @@ func Start(cfg Config) (*Runner, error) { if cfg.Height < 5 { cfg.Height = 5 } - if _, err := exec.LookPath(cfg.Command); err != nil { - return nil, fmt.Errorf("agent %q not found on PATH: %w", cfg.Command, err) + cmd := exec.Command(cfg.Command, cfg.Args...) + if cmd.Err != nil { + return nil, fmt.Errorf("agent %q %s: %w", cfg.Command, LookupReason(cmd.Err), cmd.Err) } // Checked here because the PTY start cannot say it. pty.StartWithSize sets // SysProcAttr, and with that set os.StartProcess skips its own check of the @@ -101,8 +107,10 @@ func Start(cfg Config) (*Runner, error) { return nil, fmt.Errorf("start %s: session directory: %w", cfg.Command, err) } } + if err := checkCommandFile(cmd.Path, cfg.Dir); err != nil { + return nil, err + } - cmd := exec.Command(cfg.Command, cfg.Args...) cmd.Dir = cfg.Dir // TERM tells the agent what it may emit; it must match what the emulator // below can parse. COLORTERM unlocks 24-bit colour in most TUIs. @@ -120,6 +128,7 @@ func Start(cfg Config) (*Runner, error) { term.SetScrollbackSize(scrollbackLines) r := &Runner{ + path: cmd.Path, cfg: cfg, cmd: cmd, ptmx: ptmx, diff --git a/internal/agent/agent_test.go b/internal/agent/agent_test.go index bcc1671..d4c1ed4 100644 --- a/internal/agent/agent_test.go +++ b/internal/agent/agent_test.go @@ -214,3 +214,82 @@ func TestScrubbedEnvDropsWhatAnAgentMustNotInherit(t *testing.T) { t.Error("ScrubbedEnv did not drop anything") } } + +// TestStartRunsARelativeCommandFromTheSessionDir: the child runs in Dir, so a +// relative command is a file there. It need not exist where Deck runs, and a +// check made from there refused a command that would have run. +func TestStartRunsARelativeCommandFromTheSessionDir(t *testing.T) { + dir := t.TempDir() + t.Chdir(t.TempDir()) + if err := os.WriteFile(filepath.Join(dir, "agent"), []byte("#!/bin/sh\necho from-session-dir\nexec /bin/sleep 30\n"), 0o755); err != nil { + t.Fatal(err) + } + + r, err := Start(Config{Command: "./agent", Dir: dir, Width: 80, Height: 24}) + if err != nil { + t.Fatalf("Start refused a command that exists in the session dir: %v", err) + } + t.Cleanup(r.Stop) + if !screenContains(t, r, "from-session-dir", 5*time.Second) { + t.Error("the session dir's command did not run") + } + if r.Path() != "./agent" { + t.Errorf("Path() = %q, want the command as exec ran it", r.Path()) + } +} + +// TestStartRefusesADirectoryWithThatReason: exec would refuse it at fork as +// "permission denied", which sends someone after the wrong problem. +func TestStartRefusesADirectoryWithThatReason(t *testing.T) { + dir := t.TempDir() + if err := os.Mkdir(filepath.Join(dir, "adir"), 0o755); err != nil { + t.Fatal(err) + } + _, err := Start(Config{Command: "./adir", Dir: dir, Width: 80, Height: 24}) + if err == nil || !strings.Contains(err.Error(), "is a directory") { + t.Errorf("err = %v, want it to say the command is a directory", err) + } +} + +// TestStartChecksDotDotWhereTheKernelResolvesIt: inside a symlinked session +// dir, ".." is the link target's parent. A check that joined the path as text +// would look in the link's parent and refuse a command that runs. +func TestStartChecksDotDotWhereTheKernelResolvesIt(t *testing.T) { + root := t.TempDir() + target := filepath.Join(root, "real", "sub") + if err := os.MkdirAll(target, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(root, "real", "agent"), []byte("#!/bin/sh\nexec /bin/sleep 30\n"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(filepath.Join(root, "links"), 0o755); err != nil { + t.Fatal(err) + } + link := filepath.Join(root, "links", "sess") + if err := os.Symlink(target, link); err != nil { + t.Fatal(err) + } + + r, err := Start(Config{Command: "../agent", Dir: link, Width: 80, Height: 24}) + if err != nil { + t.Fatalf("Start refused ../agent that the kernel finds from the link's target: %v", err) + } + r.Stop() +} + +// TestARelativePathEntrySaysSo: a command found only through "." on PATH is +// refused by exec, and was found — "not found on PATH" misdirects. +func TestARelativePathEntrySaysSo(t *testing.T) { + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "dotagent"), []byte("#!/bin/sh\n"), 0o755); err != nil { + t.Fatal(err) + } + t.Chdir(dir) + t.Setenv("PATH", ".") + + _, err := Start(Config{Command: "dotagent", Width: 80, Height: 24}) + if err == nil || !strings.Contains(err.Error(), "relative PATH entry") { + t.Errorf("err = %v, want it to name the relative PATH entry", err) + } +} diff --git a/internal/agent/executable.go b/internal/agent/executable.go new file mode 100644 index 0000000..0898c20 --- /dev/null +++ b/internal/agent/executable.go @@ -0,0 +1,52 @@ +package agent + +// Which file an agent runs: the path exec resolved, kept on the Runner, and +// the check that refuses a missing file or a directory with that reason +// rather than with the error the PTY start would give. + +import ( + "errors" + "fmt" + "os" + "os/exec" + "path/filepath" + "strings" +) + +// Path is the file the agent runs. See Runner.path. +func (r *Runner) Path() string { return r.path } + +// checkCommandFile refuses a command named by path that is missing or a +// directory, with that reason. exec would refuse it too, but at fork as +// "permission denied" for a directory. The path is handed to the kernel as +// written, joined by a plain separator rather than filepath.Join, which would +// take ".." textually where the kernel takes it after a symlink — the stat then +// checks the file exec will run. A bare name was already found on PATH. +func checkCommandFile(path, dir string) error { + if !strings.ContainsRune(path, filepath.Separator) { + return nil + } + at := path + if dir != "" && !filepath.IsAbs(path) { + at = dir + string(filepath.Separator) + path + } + info, err := os.Stat(at) + if err != nil { + return fmt.Errorf("agent %q: %w", path, err) + } + if info.IsDir() { + return fmt.Errorf("agent %q is a directory", path) + } + return nil +} + +// LookupReason says why a bare command name did not resolve on PATH, for an +// error from exec.LookPath or exec.Cmd.Err. exec refuses a file found only +// through a relative PATH entry such as ".", and that file was found: +// reporting it as "not found" sent the reader after the wrong problem. +func LookupReason(err error) string { + if errors.Is(err, exec.ErrDot) { + return "found only through a relative PATH entry, which is refused — put an absolute directory on PATH" + } + return "not found on PATH" +} diff --git a/internal/coord/delivery.go b/internal/coord/delivery.go index 296ed10..eb15536 100644 --- a/internal/coord/delivery.go +++ b/internal/coord/delivery.go @@ -37,9 +37,9 @@ type hookInput struct { // there reaches the subagent, which may never pass it on. AgentID string `json:"agent_id"` // StopHookActive is set on a Stop that is already continuing because of a - // stop hook. Claude Code ends the turn after eight such continuations in a - // row and drops the hook's output when it does, so delivering on one risks - // mail nobody reads. One continuation per turn is enough. + // stop hook. Claude Code's hook docs say that after eight continuations in + // a row it "overrides the next block and ends the turn", so mail handed over + // on one risks never being acted on. One continuation per turn is enough. StopHookActive bool `json:"stop_hook_active"` } diff --git a/internal/coord/delivery_test.go b/internal/coord/delivery_test.go index beef7bb..f02edea 100644 --- a/internal/coord/delivery_test.go +++ b/internal/coord/delivery_test.go @@ -216,7 +216,7 @@ func TestNoDeliveryInsideASubagent(t *testing.T) { } // TestNoDeliveryOnAContinuedStop: Claude Code ends a turn after eight stop -// continuations in a row and drops the hook's output, so a Stop that is +// continuations in a row, overriding the hook's reply, so a Stop that is // already continuing hands nothing over and lets the turn end. func TestNoDeliveryOnAContinuedStop(t *testing.T) { c := start(t) diff --git a/internal/store/query.go b/internal/store/query.go index 2240449..24055a3 100644 --- a/internal/store/query.go +++ b/internal/store/query.go @@ -105,9 +105,9 @@ func (s *State) SessionsFor(projectID string) []Session { // // The values the project's sessions hold are reassigned in their new order // rather than recomputed, so a session opened later by the clock still takes -// a value below all of them. Equal values — a hand-edited file with no creation times — are -// raised to be distinct first, upwards only for the same reason; reassigning -// equal values would move nothing and still report a move. +// a value below all of them. Equal values — a hand-edited file with no +// creation times — are raised to be distinct first, upwards only for the same +// reason; reassigning equal values would move nothing and still report a move. func (s *State) MoveSession(id string, to int) bool { sess := s.Session(id) if sess == nil { diff --git a/internal/ui/agentinfo.go b/internal/ui/agentinfo.go index 778c3a8..a71d49a 100644 --- a/internal/ui/agentinfo.go +++ b/internal/ui/agentinfo.go @@ -1,8 +1,8 @@ package ui -// What the footer says about the program a session started: the file its -// name resolved to on PATH, and for an agent that runs claude, which claude -// answers and its version. +// What the footer says about the program a session started: the file it ran, +// and for an agent that runs claude, which claude that PATH finds and its +// version. // // Deck starts an agent by name, and two installs of one program on PATH are // easy to end up with. The shell you type in may find a different one from @@ -13,6 +13,7 @@ package ui import ( "context" + "errors" "os/exec" "path/filepath" "strings" @@ -24,15 +25,25 @@ import ( ) // versionTimeout bounds `claude --version`. It runs off the UI's goroutine, -// so a slow one costs nothing but a late notice; this only stops a wedged one -// from leaving a process behind. -const versionTimeout = 5 * time.Second +// so a slow one costs nothing but a late notice; this bounds a wedged one, +// plus versionWaitDelay when a child of it holds the output pipe. The timeout +// kills the process it started, not that process's own children. A var so a +// test can shorten it rather than wait five seconds. +var versionTimeout = 5 * time.Second + +// versionWaitDelay is how long the check waits for the output pipe to close +// once the process it started has gone. A wrapper or shim whose own child +// inherits stdout keeps the pipe open after the wrapper exits, or after the +// timeout kills it, and without this the read waits for that child instead. +const versionWaitDelay = time.Second // agentVersionMsg carries what a version check found back to the footer. -// started is the notice it was asked for, so a notice that has since been -// replaced is left alone. +// started is the notice it was asked for and seq the start it belongs to, so +// a notice that has since been replaced is left alone — even by an identical +// one, which two starts in the same directory produce. type agentVersionMsg struct { started, agentPath, dir, info string + seq int } // startedNotice is the footer line for an agent that just started. info is @@ -45,8 +56,10 @@ func startedNotice(agentPath, dir, info string) string { } // runsClaude reports whether an agent answers through the claude CLI: claude -// itself, or cathode, which starts claude by name from the PATH it inherits -// from Deck. coordArgs and willResume switch on the same base name. +// itself, or cathode, whose default backend starts claude by name from the +// PATH it inherits from Deck. cathode run with another backend, through +// -agent-args, starts no claude, and the notice then names one that is not +// answering. coordArgs and willResume switch on the same base name. func runsClaude(command string) bool { switch filepath.Base(command) { case "claude", "cathode": @@ -58,46 +71,60 @@ func runsClaude(command string) bool { // announceStart sets the notice for an agent that just started and returns // the check that completes it, or nil when there is nothing to ask. // -// Start has already resolved the command, so LookPath answers here; a failure -// would mean PATH changed between the two, and the name is shown instead. -func (m *Model) announceStart(command, dir string) tea.Cmd { - agentPath, err := exec.LookPath(command) - if err != nil { - agentPath = command - } +// agentPath is the file the runner started (agent.Runner.Path), not a second +// lookup of the command, which could find a different one. A relative path is +// shown as given, beside the directory it ran in, and the check runs in that +// directory so it finds the same file. +func (m *Model) announceStart(agentPath, command, dir string) tea.Cmd { m.notice = startedNotice(agentPath, dir, "") + m.starts++ if !runsClaude(command) { return nil } - started := m.notice + started, seq := m.notice, m.starts return func() tea.Msg { - return agentVersionMsg{started: started, agentPath: agentPath, dir: dir, - info: claudeInfo(filepath.Base(command) == "claude", agentPath)} + return agentVersionMsg{started: started, agentPath: agentPath, dir: dir, seq: seq, + info: claudeInfo(filepath.Base(command) == "claude", agentPath, dir)} } } // claudeInfo is the claude part of the notice. For claude itself the path is -// already shown, so only the version is; for cathode it is the claude cathode -// will start, which is the one that answers. +// already shown, so only the version is; for cathode it is the claude its +// default backend will start. // // A failure is reported in place of the version rather than dropped: "could // not read" is the notice that should send someone to look. -func claudeInfo(isClaude bool, agentPath string) string { +func claudeInfo(isClaude bool, agentPath, dir string) string { path := agentPath if !isClaude { p, err := exec.LookPath("claude") if err != nil { - return "claude not found on PATH" + return "claude " + agent.LookupReason(err) } path = p } ctx, cancel := context.WithTimeout(context.Background(), versionTimeout) defer cancel() cmd := exec.CommandContext(ctx, path, "--version") + cmd.Dir = dir cmd.Env = agent.ScrubbedEnv() + cmd.WaitDelay = versionWaitDelay out, err := cmd.Output() - if err != nil { - return "could not read the version of " + path + ": " + err.Error() + // A pipe a child still held is not a failure when the version arrived. + if err != nil && !(errors.Is(err, exec.ErrWaitDelay) && len(out) > 0) { + reason := err.Error() + var exit *exec.ExitError + switch { + case ctx.Err() != nil: + // Killed by the timeout above, which "signal: killed" would + // report as claude crashing. + reason = "no answer within " + versionTimeout.String() + case errors.As(err, &exit): + if line, _, _ := strings.Cut(strings.TrimSpace(string(exit.Stderr)), "\n"); line != "" { + reason += ": " + printable(line) + } + } + return "could not read the version of " + path + ": " + reason } // "2.1.322 (Claude Code)": the first word is the version, and the rest // only repeats the program's name, which the notice already gives. @@ -114,7 +141,19 @@ func claudeInfo(isClaude bool, agentPath string) string { // applyVersion completes the start notice, unless something has replaced it // since — a later notice is newer news than this one. func (m *Model) applyVersion(msg agentVersionMsg) { - if m.notice == msg.started { + if m.notice == msg.started && m.starts == msg.seq { m.notice = startedNotice(msg.agentPath, msg.dir, msg.info) } } + +// printable drops control characters from text bound for the footer. stderr is +// a pipe here, so colour codes are unlikely, but an escape sequence that did +// arrive would be interpreted by the terminal rather than shown. +func printable(s string) string { + return strings.Map(func(r rune) rune { + if r < 0x20 || r == 0x7f { + return -1 + } + return r + }, s) +} diff --git a/internal/ui/agentinfo_test.go b/internal/ui/agentinfo_test.go index 9e7934c..1a672db 100644 --- a/internal/ui/agentinfo_test.go +++ b/internal/ui/agentinfo_test.go @@ -9,6 +9,7 @@ import ( "path/filepath" "strings" "testing" + "time" "github.com/tripledownab/deck/internal/store" ) @@ -121,3 +122,168 @@ func TestALaterNoticeIsNotOverwritten(t *testing.T) { t.Errorf("the late version replaced a newer notice: %q", got) } } + +// claudeWith is a fake claude whose --version runs body, and which otherwise +// stays up as the real one does in a pane. +func claudeWith(body string) string { + return "#!/bin/sh\nif [ \"$1\" = --version ]; then " + body + "; fi\nexec /bin/sleep 30\n" +} + +// TestTheCheckDoesNotHoldTheUI: starting returns before the check answers. +// The check runs as a command; run inline it would freeze every key and frame +// for as long as claude takes to print its version. +func TestTheCheckDoesNotHoldTheUI(t *testing.T) { + fakeBin(t, map[string]string{"claude": claudeWith("/bin/sleep 2; echo 1.0; exit 0")}) + st := &store.State{} + p := st.AddProject(store.Project{Name: "demo", Path: t.TempDir()}) + st.AddSession(store.Session{ProjectID: p.ID, Name: "s", Agent: "claude", Dir: t.TempDir()}) + m := sized(New(st, "claude", nil), 120, 30) + m.screen = screenSession + t.Cleanup(func() { m.Close() }) + + began := time.Now() + next, cmd := m.attach() + t.Cleanup(func() { next.(Model).Close() }) + if took := time.Since(began); took > time.Second { + t.Errorf("starting took %v; the version check ran on the UI's goroutine", took) + } + if cmd == nil { + t.Error("no check was returned to run") + } +} + +// TestAWedgedCheckIsBounded, and one whose child holds the output pipe: a +// shell wrapper's own child keeps stdout open after the wrapper is gone, and +// the read must not wait for it. +func TestAWedgedCheckIsBounded(t *testing.T) { + // Long enough for a fresh shell script to start and print on a loaded + // machine — 300ms missed that a few times in fifteen runs — and short + // enough to keep the test under its bound. + saved := versionTimeout + versionTimeout = 1500 * time.Millisecond + t.Cleanup(func() { versionTimeout = saved }) + + for name, body := range map[string]string{ + "wedged": "exec /bin/sleep 30", + "child waits": "/bin/sleep 30", + "child stays": "/bin/sleep 30 & echo 2.0.9; exit 0", + "silent child": "/bin/sleep 30 & exit 0", + } { + fakeBin(t, map[string]string{"cathode": "#!/bin/sh\nexec /bin/sleep 30\n", "claude": claudeWith(body)}) + began := time.Now() + _, notice := startedWith(t, "cathode") + if took := time.Since(began); took > 5*time.Second { + t.Errorf("%s: the check took %v", name, took) + } + want := "could not read the version" + switch name { + case "child stays": + want = "claude 2.0.9 at" + case "wedged": + want = "no answer within" + } + if !strings.Contains(notice, want) { + t.Errorf("%s: notice = %q, want %q", name, notice, want) + } + } +} + +// TestTheReasonForAFailureIsShown: "exit status 1" alone does not say why, and +// the line claude wrote to stderr usually does. +func TestTheReasonForAFailureIsShown(t *testing.T) { + fakeBin(t, map[string]string{"cathode": "#!/bin/sh\nexec /bin/sleep 30\n", + "claude": claudeWith("echo 'boom: node too old' >&2; exit 1")}) + if _, notice := startedWith(t, "cathode"); !strings.Contains(notice, "boom: node too old") { + t.Errorf("notice = %q, want the reason claude gave", notice) + } + + // An escape sequence in it reaches the footer as text, not as a command + // to the terminal. + fakeBin(t, map[string]string{"cathode": "#!/bin/sh\nexec /bin/sleep 30\n", + "claude": claudeWith("printf '\\033[31mboom\\033[0m\\n' >&2; exit 1")}) + if _, notice := startedWith(t, "cathode"); strings.ContainsRune(notice, 0x1b) || !strings.Contains(notice, "boom") { + t.Errorf("notice = %q, want the reason without control bytes", notice) + } +} + +// TestAClaudeThatPrintsNothingSaysSo rather than showing an empty version. +func TestAClaudeThatPrintsNothingSaysSo(t *testing.T) { + fakeBin(t, map[string]string{"claude": claudeWith("exit 0")}) + if _, notice := startedWith(t, "claude"); !strings.Contains(notice, "(no version printed)") { + t.Errorf("notice = %q", notice) + } +} + +// TestTheCheckRunsInTheAgentsEnvironment: the same scrub as the agent, so a +// key Deck keeps from the agent is kept from the check too. +func TestTheCheckRunsInTheAgentsEnvironment(t *testing.T) { + t.Setenv("ANTHROPIC_API_KEY", "leaked") + fakeBin(t, map[string]string{"claude": claudeWith("echo ${ANTHROPIC_API_KEY:-clean}; exit 0")}) + if _, notice := startedWith(t, "claude"); !strings.Contains(notice, "(clean)") { + t.Errorf("notice = %q, want the check run without the key", notice) + } +} + +// TestARelativeAgentIsNamedFromTheSessionDir: the child runs in the session's +// directory, so a relative command names a file there. Deck's own directory +// holds a different one, whose version the notice must not give. +func TestARelativeAgentIsNamedFromTheSessionDir(t *testing.T) { + fakeBin(t, nil) + deckDir, sessDir := t.TempDir(), t.TempDir() + for dir, version := range map[string]string{deckDir: "1.0.0", sessDir: "9.9.9"} { + if err := os.MkdirAll(filepath.Join(dir, "b"), 0o755); err != nil { + t.Fatal(err) + } + body := claudeWith("echo " + version + "; exit 0") + if err := os.WriteFile(filepath.Join(dir, "b", "claude"), []byte(body), 0o755); err != nil { + t.Fatal(err) + } + } + t.Chdir(deckDir) + + st := &store.State{} + p := st.AddProject(store.Project{Name: "demo", Path: t.TempDir()}) + st.AddSession(store.Session{ProjectID: p.ID, Name: "s", Agent: "b/claude", Dir: sessDir}) + m := sized(New(st, "b/claude", nil), 120, 30) + m.screen = screenSession + t.Cleanup(func() { m.Close() }) + next, cmd := m.attach() + m = next.(Model) + if m.fault != nil { + t.Fatalf("start: %v", m.fault) + } + after, _ := m.Update(cmd()) + notice := after.(Model).notice + if want := "started b/claude (9.9.9) in " + sessDir; notice != want { + t.Errorf("notice = %q, want %q: the version of the file the agent ran", notice, want) + } +} + +// TestAnOlderAnswerDoesNotCompleteANewerStart: two starts in one directory +// set identical notices, and the first start's answer belongs to the first. +func TestAnOlderAnswerDoesNotCompleteANewerStart(t *testing.T) { + m := Model{} + m.announceStart("/bin/claude", "claude", "/d") + older := agentVersionMsg{started: m.notice, agentPath: "/bin/claude", dir: "/d", info: "1.0", seq: m.starts} + m.announceStart("/bin/claude", "claude", "/d") + m.applyVersion(older) + if strings.Contains(m.notice, "1.0") { + t.Errorf("the first start's answer completed the second's notice: %q", m.notice) + } +} + +// TestAClaudeFoundOnlyRelativelySaysSo: the check names why it cannot use the +// claude it found, as Start does for an agent. +func TestAClaudeFoundOnlyRelativelySaysSo(t *testing.T) { + bin := fakeBin(t, map[string]string{"cathode": "#!/bin/sh\nexec /bin/sleep 30\n"}) + cwd := t.TempDir() + if err := os.WriteFile(filepath.Join(cwd, "claude"), []byte(fakeClaude), 0o755); err != nil { + t.Fatal(err) + } + t.Chdir(cwd) + t.Setenv("PATH", bin+":.") + + if _, notice := startedWith(t, "cathode"); !strings.Contains(notice, "relative PATH entry") { + t.Errorf("notice = %q, want it to name the relative PATH entry", notice) + } +} diff --git a/internal/ui/fault_test.go b/internal/ui/fault_test.go new file mode 100644 index 0000000..31ad34a --- /dev/null +++ b/internal/ui/fault_test.go @@ -0,0 +1,42 @@ +package ui + +// The footer's fault line: shown until a key Deck handles acknowledges it, +// and never acknowledged by a key the agent receives. + +import ( + "errors" + "strings" + "testing" +) + +// TestAKeyDeckHandlesAcknowledgesTheFault: a fault that stayed for the whole +// run hid every notice after it. The key's own notice is the one shown next. +func TestAKeyDeckHandlesAcknowledgesTheFault(t *testing.T) { + t.Setenv("XDG_STATE_HOME", t.TempDir()) + m := sized(New(mouseState(1, 3), "bash", nil), 120, 30) + m.focusContent() + m.fault = errors.New("an earlier failure") + + m = sendKey(m, typed("K")) // at the top already: sets a notice + if m.fault != nil { + t.Errorf("fault = %v after a key Deck handled", m.fault) + } + if !strings.Contains(m.dashboardFooter(), "already at the top") { + t.Errorf("footer = %q, want the key's own notice", m.dashboardFooter()) + } +} + +// TestAKeyForTheAgentLeavesTheFault: typing into an attached agent is not +// reading Deck's footer, so the fault stays until a key reaches Deck. +func TestAKeyForTheAgentLeavesTheFault(t *testing.T) { + m := sessionView(t, 1, 120, 30) + sess := m.currentSession() + m.runners[sess.ID] = startAgent(t, sess.Dir, "") + m.attached = true + m.fault = errors.New("an earlier failure") + + m = sendKey(m, typed("a")) + if m.fault == nil { + t.Error("a key sent to the agent cleared the fault") + } +} diff --git a/internal/ui/input.go b/internal/ui/input.go index aec29eb..8567af4 100644 --- a/internal/ui/input.go +++ b/internal/ui/input.go @@ -18,6 +18,14 @@ func (m Model) handleKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { // change screens, and the rows the drag was moving between may be gone. m.lastPress, m.dragging = target{}, "" + // A key Deck handles itself acknowledges the fault on screen: the footer + // was in view when it was pressed. It is cleared before the key acts, so a + // failure the key itself causes is the one shown next. A key the agent + // receives acknowledges nothing — whoever typed it was typing to the agent + // — so that branch puts the fault back. + shown := m.fault + m.fault = nil + // A modal owns every key while it is up. if m.picker != nil { return m.pickerKey(msg) @@ -56,6 +64,7 @@ func (m Model) handleKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) { // Attached: every remaining key belongs to the agent. if m.screen == screenSession && m.attached { + m.fault = shown if b := keyToBytes(msg); len(b) > 0 { m.sendToAgent(b) } diff --git a/internal/ui/model.go b/internal/ui/model.go index a0021f6..88ec076 100644 --- a/internal/ui/model.go +++ b/internal/ui/model.go @@ -45,6 +45,9 @@ type Model struct { // lastPress is what the previous mouse press landed on, cleared by any key. // A click opens a row only when the press before it landed on that row. lastPress target + // starts counts agent starts, so a late version check can tell whether the + // notice it would complete still belongs to its start. See agentVersionMsg. + starts int // dragging is the id of the session a held left button is moving, or "" // when no drag is in progress. See dragMouse. dragging string @@ -86,11 +89,14 @@ type Model struct { // notice is a one-line message in the footer; fault is a failure the user // must see, and it outranks the notice. // - // Neither is auto-cleared. For fault that is deliberate — a failure the - // user has not acknowledged must not scroll away. A notice lingering until - // the next one replaces it is a weaker choice than it looks: the footer - // keeps saying "stopped wily-crane-bbbb" long after that stopped being - // news, and the keys hint it displaces is more useful by then. Clearing it + // Neither is cleared by time. A fault stays until a key Deck handles itself + // acknowledges it (handleKey): a failure the user has not seen must not + // scroll away, and one that stayed for the whole run hid every notice + // after it. A key sent to an attached agent does not count. + // + // A notice lingering until the next one replaces it is a weaker choice than + // it looks: the footer keeps saying "stopped wily-crane-bbbb" long after + // that stopped being news, and the keys hint it displaces is more useful by then. Clearing it // on the next keystroke would fix that, and would touch every screen, so // it is not a thing to change while passing through. notice string diff --git a/internal/ui/runner.go b/internal/ui/runner.go index ed19628..909506d 100644 --- a/internal/ui/runner.go +++ b/internal/ui/runner.go @@ -38,7 +38,7 @@ func (m Model) attach() (tea.Model, tea.Cmd) { m.runners[sess.ID] = r m.attached = true m.screen = screenSession - announce := m.announceStart(sess.Agent, sess.Dir) + announce := m.announceStart(r.Path(), sess.Agent, sess.Dir) // Announce the session so its siblings can see it. Registering after the // process starts keeps the registry to sessions that actually exist.