From a83f3095eb1912d016a4d39839f0c670dcb0ba03 Mon Sep 17 00:00:00 2001 From: Phil Haack Date: Wed, 4 Nov 2026 09:03:25 -0800 Subject: [PATCH] Show a background review waiting at a permission prompt claude lists a session stopped partway through its turn at a permission prompt as status "waiting", which docket read as still working. Read it as Prompted, report it as needing the user on the dashboard and through MCP, and list such rows in a "Waiting for you" group at the top. The poll and the archive still act only on a turn that has ended. Claude-Session: https://claude.ai/code/session_01WXojGBSJfMFp3b3nGTZN2o --- CLAUDE.md | 2 +- README.md | 2 +- internal/core/engine/background.go | 17 +++++-- internal/core/engine/background_test.go | 19 ++++++++ internal/core/engine/claude_background.go | 11 ++++- .../core/engine/claude_background_test.go | 19 ++++++++ internal/core/session/background_test.go | 26 ++++++++++ internal/core/session/blocked_test.go | 26 ++++++++++ internal/mcp/mcp.go | 2 +- internal/mcp/mcp_test.go | 18 +++++++ internal/tui/app.go | 12 ++--- internal/tui/app_test.go | 4 ++ internal/tui/screens/dashboard/dashboard.go | 48 +++++++++++++++---- .../tui/screens/dashboard/progress_test.go | 42 ++++++++++++++++ 14 files changed, 223 insertions(+), 25 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 7613904..6b5891e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -60,7 +60,7 @@ These were verified while planning and shape the design. Don't rediscover them. - **Submission is always explicit.** review-code's `create-draft-review.sh` posts a review with no `event`, which GitHub stores as `PENDING` with `submitted_at: null`. Submitting is `POST /repos/{o}/{r}/pulls/{n}/reviews/{id}/events` with `APPROVE`, `COMMENT`, or `REQUEST_CHANGES`. `~/.dotfiles/bin/pr-review.sh` (`fetch_pending_reviews`, `cmd_submit`) is the logic docket ports, except that docket paginates and that script does not. A submit that leaves `body` out keeps the pending review's body, which is review-code's summary (verified on PostHog/posthog#105871). The submit screen fills its body from the pending review and leaves `body` out when the user did not change it, because the text area rewrites what it holds (a tab becomes spaces, control characters go) and sending it back would rewrite the summary. `SetDraft` turns `\r\n` into `\n` first, because a body saved from the browser has them and the text area turns each `\r` into a line break of its own. Whether an explicit empty `body` clears the summary is unverified, so an emptied body is also left out and the screen says the summary stays. A submit of a pending review that was deleted answers 404. A second submit of a review already submitted answers 422 ("Could not comment pull request review.") and leaves its body and `submitted_at` as they were. A second pending review by the same user on one pull request answers 422 ("User can only have one pending review per pull request"). All three were verified on haacked/docket#24, a throwaway pull request. - **Background sessions are claude's alone** (verified on 2.1.273). `claude --bg` refuses `--session-id` (`warning: --bg manages the session id`) and mints its own, so a background record carries no session id until docket reads one back. The short id is the first line of stdout, `backgrounded · `, while `Starting background service…` goes to stderr; the short id is the first 8 characters of the session UUID. `claude agents --json --all` lists every session as `{kind, id, sessionId, cwd, startedAt, state, status, pid}`, where `id` is present only on background entries. A session runs as `state: working`/`status: busy` and finishes as `state: done`/`status: idle`. **A finished session keeps its `pid` and claude keeps holding it**: `claude --resume ` refuses with "is running as a background session … Run `claude attach `". `claude stop ` drops the `pid`, keeps the conversation, and frees it for `--resume`. So the presence of `pid` is what decides whether docket attaches or resumes. `claude rm` deletes the conversation and docket never runs it. - **`claude --bg` refuses a directory nobody has trusted** (verified on 2.1.281). It exits 1 and prints ``Workspace not trusted. Run `claude` in once and accept the trust prompt, then retry.`` on stderr. No flag trusts a directory. `claude /exit` run in the directory shows the trust prompt, then runs `/exit` as its first message and exits 0 once the user accepts; declining exits 1 and trusts nothing (verified through a scripted terminal). The prompt's cursor starts on "No, exit". The trust check walks up from the working directory and stops at its git root (read from 2.1.281's code, not run), so a trusted parent does not cover a tier-2 clone, which is its own git root. `Claude.Untrusted` matches the stderr text and `Claude.TrustSpec` is the `/exit` command. -- **A background session that ends its turn reports `status: idle` and keeps its `pid`, and its `state` says nothing reliable about it** (2.1.281). `state` is claude's own reading of the transcript, and an ended turn has landed in three places. `state: blocked` with `tempo: blocked` came from review-code runs that posted the draft and asked whether to submit it (PostHog/posthog#105555 and #105556). `state: working` with `tempo: idle` and `output: null` came from runs that posted the draft and closed by saying how to amend it, and it stayed that way for three hours (PostHog/posthog#105890 and PostHog/posthog-android#805). `state: done` came from #105890's second turn, which answered a question and asked nothing back. All of them had a pending draft on GitHub. So `ParseStatus` sets `BGStatus.Idle` from the status and reads `state` only for `Done`. `state` has missed `done` for an ended turn but has not reported `done` for a turn still running, so `done` still reads as over. `settle` reads GitHub for an idle session that is not done: the session's own draft or submission moves the record on, and anything else leaves it running, because a session can also end its turn before it posts, at a permission prompt. "Own" is `ownWork`: a launch snapshots `PriorPendingID` beside `PriorReviewIDs`, because an append or overwrite re-review starts with my old pending draft still on GitHub and review-code replaces it only when it posts its own. The poll's `settleIdle` reads GitHub once for each stretch the session stays idle, keyed on the status file's `updatedAt`, and forgets the key once the session works again or its record moves on. `afterBackgroundExit` settles an idle session too, so opening a drafted row's session and leaving it unanswered keeps the draft rather than putting the row back to reviewing, and a failed read there keeps the row's state and puts the error on it, as `detect` does. `state: blocked` also appears in the middle of a run: job `e64beb59` reported it at 17:33 while it waited on its own reviewer agents, before it had posted anything. Whether `status` reads `idle` at such a point is unverified. If it does, the poll reads GitHub once for each change to the session's status file, and the record moves on only once the session's own draft is posted. `status` also reads `idle` for a few seconds after `claude --bg` returns, before the first turn starts, while the status file already says `tempo: active` and `detail: starting…` (probe session 651b6f55 on 2.1.281). The poll that follows a launch therefore reads GitHub once, and `ownWork` leaves the record at `reviewing`. The dashboard says a session is waiting for the user only when the listing reports it idle and the status file does not report it active (`progressFor`), and it shows claude's `needs`, or "your input" when there is none. That rule assumes a session stopped at a permission prompt reads `status: idle`. Two probes could not check it, because both background sessions ran their tool call without asking. If such a session reads `busy`, its row does not turn red and does not show the need. +- **A background session that ends its turn reports `status: idle` and keeps its `pid`, and its `state` says nothing reliable about it** (2.1.281). `state` is claude's own reading of the transcript, and an ended turn has landed in three places. `state: blocked` with `tempo: blocked` came from review-code runs that posted the draft and asked whether to submit it (PostHog/posthog#105555 and #105556). `state: working` with `tempo: idle` and `output: null` came from runs that posted the draft and closed by saying how to amend it, and it stayed that way for three hours (PostHog/posthog#105890 and PostHog/posthog-android#805). `state: done` came from #105890's second turn, which answered a question and asked nothing back. All of them had a pending draft on GitHub. So `ParseStatus` sets `BGStatus.Idle` from the status and reads `state` only for `Done`. `state` has missed `done` for an ended turn but has not reported `done` for a turn still running, so `done` still reads as over. `settle` reads GitHub for an idle session that is not done: the session's own draft or submission moves the record on, and anything else leaves it running, because a session can also end its turn before it posts, at a permission prompt. "Own" is `ownWork`: a launch snapshots `PriorPendingID` beside `PriorReviewIDs`, because an append or overwrite re-review starts with my old pending draft still on GitHub and review-code replaces it only when it posts its own. The poll's `settleIdle` reads GitHub once for each stretch the session stays idle, keyed on the status file's `updatedAt`, and forgets the key once the session works again or its record moves on. `afterBackgroundExit` settles an idle session too, so opening a drafted row's session and leaving it unanswered keeps the draft rather than putting the row back to reviewing, and a failed read there keeps the row's state and puts the error on it, as `detect` does. `state: blocked` also appears in the middle of a run: job `e64beb59` reported it at 17:33 while it waited on its own reviewer agents, before it had posted anything. Whether `status` reads `idle` at such a point is unverified. If it does, the poll reads GitHub once for each change to the session's status file, and the record moves on only once the session's own draft is posted. `status` also reads `idle` for a few seconds after `claude --bg` returns, before the first turn starts, while the status file already says `tempo: active` and `detail: starting…` (probe session 651b6f55 on 2.1.281). The poll that follows a launch therefore reads GitHub once, and `ownWork` leaves the record at `reviewing`. The dashboard says a session is waiting for the user when `BGStatus.NeedsUser` holds (`progressFor`): the listing reports it idle and the status file does not report it active, or the listing reports `status: waiting`. It shows claude's `needs`, or "your input" when there is none, and lists the row under "Waiting for you", above every other group. `SetBackground` keeps the cursor on its record when a poll moves the row between groups. **A session stopped at a permission prompt partway through its turn reads `state: blocked` and `status: waiting`**, which is neither idle nor busy, and its status file reads `tempo: blocked` with a `needs` such as `approve Bash: ` (verified on 2.1.318 with a background session asked to `sed` a file under the claude config dir, which auto mode does not approve on its own and records as `reasonCode: safetyCheck`). `ParseStatus` reads it as `Prompted`. Its turn has not ended, so `Waiting` stays false: the poll reads nothing from GitHub for it, and `stopFinished` leaves it running. A transcript records a prompt the user answered as a `permissionDecision` whose `source` is `user_temporary` or `user_permanent`. The session for PostHog/posthog-python#1176 waited 3h46m at such a prompt before docket showed it. - **claude's background service keeps a status file per session** at `/jobs//state.json` (2.1.281), where the config dir is the one in the next bullet. docket reads `detail` (a one-line summary claude rewrites as the session goes), `tempo` (`active`, `idle`, or `blocked`, of which docket reads only whether it is `active`), `needs` (what a blocked session is waiting for, often null), `fan` (the session's sub-agents, where a finished one keeps its entry for a while with `doneAt` set, so docket counts only the entries without it), and `updatedAt`. `claude agents --json` carries none of these. The file is undocumented, so `Claude.Progress` returns an empty `Progress` when the file is missing or does not parse, and the poll carries on with the listing alone. - **`CLAUDE_CONFIG_DIR` picks the Claude Code account, and claude keeps everything about a session under it** (read from 2.1.284's code and run against two accounts). The config dir is `$CLAUDE_CONFIG_DIR`, or `~/.claude` when the variable is unset. The login, the conversations, and the jobs directory are under it, and so is the answer to the trust prompt: `~/.claude-automation/.claude.json` trusted one directory while `~/.claude.json` trusted sixty. `claude agents --json --all` lists only the sessions of its own config dir: under `~/.claude-automation` it printed `[]` while the default account listed dozens. **Setting the variable to `~/.claude` is not the same as leaving it unset**: claude names the keychain entry `Claude Code-credentials` and adds `-` plus the first 8 hex digits of the dir's SHA-256 whenever the variable is set, so an explicit `~/.claude` looks up a login that does not exist. So `Record.ClaudeConfigDir` holds the dir a record was created under, which `resolve` takes from `claude_config_dir` in `config.toml` or else from the `CLAUDE_CONFIG_DIR` docket started with. `Load` refuses a relative one, because `agents` and `stop` run in docket's working directory while the others run in the record's. A record written before the field existed reads as the default account, which is right only if docket was not started with `CLAUDE_CONFIG_DIR` exported. Every claude command for the record runs under that dir through `claudeCommand`, which sets the variable for a named dir and unsets it for an empty one. The poll runs one listing per engine and account, and `Rereview` keeps the record's dir, so a change to `claude_config_dir` applies to new records and leaves the open ones on the account their sessions are under. - **claude refuses a session whose account is over a usage limit only once the turn starts** (verified on 2.1.308 against an account over its weekly limit). `claude --bg` exits 0 and prints an id. Within two seconds the session's transcript at `/projects//.jsonl` gets an `assistant` line with `isApiErrorMessage: true`, `error: "rate_limit"`, `apiError: "usage_limit_reached"`, `apiErrorStatus: 429`, and `apiErrorParams.rate_limit_info.resetsAt` in unix seconds. Only bookkeeping lines follow it (`system` with `subtype: turn_duration`, `bridge-session`, `cost-state`, `last-prompt`). The listing reports the session `state: blocked` and `status: idle` with its `pid`, and the status file reports `tempo: blocked` and a `needs` that starts with "rate limited". A refusal partway through a run can also be followed by a `user` line that claude writes itself (2.1.310). The session for PostHog/posthog#123624 was refused while a sub-agent ran, and 30 ms later claude wrote a `` that the sub-agent had finished. claude ran no turn for it, and the status file still read `inFlight.queued: 1` three hours later. claude marks with `promptSource: "system"` the messages it writes into the conversation for a sub-agent, a background task, or another session. It runs a turn for most of them. `queueTranscriptOnly: true` marks a line it runs no turn for. In 300 local transcripts, none of the 234 `system` lines that carried it was followed by a turn, and 1,046 of the 1,066 that did not carry it were. A message a person sends carries another value (`typed`, `queued`, `suggestion_accepted`, `sdk`) or none, as on the `/exit` lines in that same transcript. `Claude.UsageLimit` reads the last 64 KiB of the transcript and answers only from the last `user` or `assistant` line that is not a sub-agent's (`isSidechain`), so a later message that the tail cuts off can never let an earlier refusal through. It also passes over a `user` line that carries `queueTranscriptOnly: true` and either `promptSource: "system"` or `isMeta: true` with no `promptSource` (`queuedWithoutTurn`), and only after the whole line decodes, because a line it cannot read may be the user continuing. The meta case is a companion that claude writes ahead of a notification of its own, under the same `promptId`. After the refusal of the session for PostHog/posthog#124731 (2.1.312), such a `` line carried `isMeta`, `turnCompanion`, and `queueTranscriptOnly` but no `promptSource`. In 9,356 local transcripts, no line that carried `queueTranscriptOnly` was followed directly by an assistant line. A person's message never carries `isMeta`, and a line with a person's `promptSource` is never passed over. `UsageLimit` also passes over a person's `/exit`, which claude writes as three `user` lines under one `promptId`: a caveat, the line that starts `/exit` with no `promptSource`, and its output. A person who opens a session with `enter` and closes it leaves those lines behind, and they would otherwise read as the person continuing. Four refused docket sessions in the local transcripts ended that way, two of them interactive. No local command in those transcripts was followed directly by a turn, but `UsageLimit` passes over `/exit` alone, because `/model` or `/login` suggests the person means to continue. A five-hour limit writes the same `error` as a weekly one, with `rateLimitType: "five_hour"` (2.1.312, the same session). `claude stop` on a session that is already stopped exits 0. diff --git a/README.md b/README.md index 52b1aab..d7920df 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ A review runs in the background by default, so you can start several and keep wo default_run = "terminal" # or "background", the default ``` -docket asks `claude` every fifteen seconds how each session is doing. The line under each running row shows claude's one-line summary of what the session is doing and how many agents it is running. When a session is waiting for you, that line turns red and says what the session needs, and `enter` opens the session so you can answer it. When claude has not updated its summary for ten minutes, the line says how long the session has been quiet, which is your cue to open it and look. When a session finishes, docket reads GitHub for what it left and moves the record on, the same way it does after a session you sat through. review-code ends a background review once it has posted the draft, often by asking whether to submit it, and the session then waits on you rather than finishing. When your draft is on GitHub, docket moves that row to Drafted anyway, so `s` submits it from the dashboard, and `enter` still opens the session if you would rather answer it there. If you open a drafted row's session and leave it working, docket cannot tell whether the session is changing the review, so the row goes back to Reviewing until the session ends its turn. `s` still submits the draft meanwhile, and submitting leaves a session that is still working running. +docket asks `claude` every fifteen seconds how each session is doing. The line under each running row shows claude's one-line summary of what the session is doing and how many agents it is running. When a session is waiting for you, because it asked a question or stopped to ask permission to run a tool, its row moves to a Waiting for you group at the top of the dashboard, the line turns red and says what the session needs, and `enter` opens the session so you can answer it. When claude has not updated its summary for ten minutes, the line says how long the session has been quiet, which is your cue to open it and look. When a session finishes, docket reads GitHub for what it left and moves the record on, the same way it does after a session you sat through. review-code ends a background review once it has posted the draft, often by asking whether to submit it, and the session then waits on you rather than finishing. When your draft is on GitHub, docket moves that row to Drafted anyway, so `s` submits it from the dashboard, and `enter` still opens the session if you would rather answer it there. If you open a drafted row's session and leave it working, docket cannot tell whether the session is changing the review, so the row goes back to Reviewing until the session ends its turn. `s` still submits the draft meanwhile, and submitting leaves a session that is still working running. `claude` runs a background session only in a directory you have trusted, and it can ask that question only in a terminal. When it refuses a review for that reason, docket hands the terminal to `claude` in that directory. Pick "Yes, I trust this folder", and docket starts the review again. Tier-1 reviews share one directory, so this happens once for all of them. Each tier-2 review clones into a directory of its own, so it happens once for each. A review that still does not start waits under "Did not start" with claude's reason, and `enter` starts it again. diff --git a/internal/core/engine/background.go b/internal/core/engine/background.go index e71fce9..721bbb7 100644 --- a/internal/core/engine/background.go +++ b/internal/core/engine/background.go @@ -27,6 +27,10 @@ type BGStatus struct { // session is not working. The listing can say so just as a turn starts. // Waiting, not Idle, is the test for an ended turn. Idle bool + // Prompted reports that the session stopped partway through its turn until + // the user answers a prompt, such as a request to run a tool. The turn has + // not ended, so Waiting stays false and the poll reads nothing from GitHub. + Prompted bool // Progress is what the agent says the session is doing, beyond the listing. // The poll fills it in for a session that is still running. Progress review.Progress @@ -39,11 +43,18 @@ func (s BGStatus) Waiting() bool { return s.Idle && !s.Progress.Active } -// Need is what a waiting session needs from the user, when the agent named one. +// NeedsUser reports that the session makes no progress until the user answers +// it. Either it ended its turn, or it stopped at a prompt partway through one. +func (s BGStatus) NeedsUser() bool { + return s.Waiting() || s.Prompted +} + +// Need is what the session needs from the user, when the agent named one. // claude's own reading of the conversation can name a need while the session's -// reviewer agents still run. A session that is not waiting therefore has none. +// reviewer agents still run. A session that does not need the user therefore +// has none. func (s BGStatus) Need() string { - if !s.Waiting() { + if !s.NeedsUser() { return "" } return s.Progress.Needs diff --git a/internal/core/engine/background_test.go b/internal/core/engine/background_test.go index 6b7a1c3..7108a72 100644 --- a/internal/core/engine/background_test.go +++ b/internal/core/engine/background_test.go @@ -36,6 +36,7 @@ func TestNeedIsNamedOnlyWhileTheSessionWaits(t *testing.T) { {name: "waiting", status: BGStatus{Idle: true, Progress: needs}, want: "permission to run gh"}, {name: "working", status: BGStatus{Progress: needs}, want: ""}, {name: "starting", status: BGStatus{Idle: true, Progress: review.Progress{Active: true, Needs: needs.Needs}}, want: ""}, + {name: "at a prompt", status: BGStatus{Prompted: true, Progress: needs}, want: "permission to run gh"}, } for _, tc := range tests { if got := tc.status.Need(); got != tc.want { @@ -44,6 +45,24 @@ func TestNeedIsNamedOnlyWhileTheSessionWaits(t *testing.T) { } } +// A prompt stops a session partway through its turn. The session makes no +// progress until the user answers, but its turn has not ended. +func TestASessionAtAPromptNeedsTheUserWithoutEndingItsTurn(t *testing.T) { + prompted := BGStatus{Prompted: true, Progress: review.Progress{Active: true}} + if !prompted.NeedsUser() { + t.Error("a session at a prompt does not need the user") + } + if prompted.Waiting() { + t.Error("a session at a prompt read as having ended its turn") + } + if !(BGStatus{Idle: true}).NeedsUser() { + t.Error("a session that ended its turn does not need the user") + } + if (BGStatus{}).NeedsUser() { + t.Error("a working session needs the user") + } +} + func TestBackgroundNamePrefersTheOneAskedForAndFallsBackToOneWithABackgroundMode(t *testing.T) { if got := BackgroundName("claude"); got != "claude" { t.Errorf("BackgroundName(claude) = %q", got) diff --git a/internal/core/engine/claude_background.go b/internal/core/engine/claude_background.go index 17b1fd7..82c22e3 100644 --- a/internal/core/engine/claude_background.go +++ b/internal/core/engine/claude_background.go @@ -87,6 +87,12 @@ const bgStateDone = "done" // also reports it for a few seconds after launch, before the first turn starts. const bgStatusIdle = "idle" +// bgStatusWaiting is the status claude reports for a session stopped partway +// through its turn at a permission prompt (verified on 2.1.318). The listing +// then reads state "blocked", and the status file reads tempo "blocked" with a +// need such as "approve Bash: ". +const bgStatusWaiting = "waiting" + // agentEntry is one element of `claude agents --json`. Interactive sessions // appear too and carry no ID. type agentEntry struct { @@ -120,8 +126,9 @@ func (Claude) ParseStatus(res exec.Result) (map[string]BGStatus, error) { // says. `claude stop` on a session still working leaves it as // "stopped", which is not "done" and would otherwise be polled for // ever, and the user can stop one from outside docket. - Done: entry.State == bgStateDone || entry.PID == 0, - Idle: entry.Status == bgStatusIdle, + Done: entry.State == bgStateDone || entry.PID == 0, + Idle: entry.Status == bgStatusIdle, + Prompted: entry.Status == bgStatusWaiting, // claude keeps the process after the session's turn ends, and drops // it once the session is stopped. That is the difference between a // session that has to be attached and one a plain resume reopens. diff --git a/internal/core/engine/claude_background_test.go b/internal/core/engine/claude_background_test.go index c4b2f51..e97ee69 100644 --- a/internal/core/engine/claude_background_test.go +++ b/internal/core/engine/claude_background_test.go @@ -346,6 +346,25 @@ func TestParseStatusReportsABlockedSession(t *testing.T) { } } +// A session stopped at a permission prompt partway through its turn reports +// waiting, which is neither idle nor busy (verified on 2.1.318). Its turn has not +// ended, so it does not read as idle, which is what makes the poll read GitHub. +func TestParseStatusReportsASessionStoppedAtAPrompt(t *testing.T) { + statuses, err := Claude{}.ParseStatus(exec.Result{ + Stdout: `[{"id": "aaaaaaaa", "kind": "background", "state": "blocked", "status": "waiting", "pid": 5}]`, + }) + if err != nil { + t.Fatalf("ParseStatus: %v", err) + } + got := statuses["aaaaaaaa"] + if !got.Prompted { + t.Error("a session stopped at a prompt did not read as prompted") + } + if got.Idle || got.Done { + t.Errorf("a session stopped at a prompt read as idle %v or done %v", got.Idle, got.Done) + } +} + // A session that ends its turn without asking anything keeps its process and // its working state, and only the status says the turn is over. review-code's // background runs end this way when the last message tells the user what to do diff --git a/internal/core/session/background_test.go b/internal/core/session/background_test.go index 49823d8..3c96a31 100644 --- a/internal/core/session/background_test.go +++ b/internal/core/session/background_test.go @@ -884,6 +884,32 @@ func TestSubmittingWhileTheSessionWorksLeavesTheSessionRunning(t *testing.T) { } } +// A session at a permission prompt is partway through its turn. Archiving after +// the submit stops only a session whose turn has ended, so this one keeps +// running with its clone. +func TestSubmittingWhileTheSessionWaitsAtAPromptLeavesTheSessionRunning(t *testing.T) { + ghc := &fakeGH{login: "haacked", info: prInfo()} + svc, _ := newService(t, ghc, newFakeGit()) + runner := bgRunner("") + rec := reopenedWhileWorking(t, svc, ghc, runner) + runner.Results["agents"] = exec.Result{Stdout: bgEntry("6d681a76", bgSession, "blocked", "waiting", true)} + + done, _, err := svc.Submit(context.Background(), rec, review.EventComment, "") + if err != nil { + t.Fatalf("Submit: %v", err) + } + + if slices.ContainsFunc(runner.Lines(), func(l string) bool { return strings.Contains(l, "claude stop") }) { + t.Errorf("the submit stopped a session waiting at a prompt: %v", runner.Lines()) + } + if _, err := os.Stat(rec.Dir); err != nil { + t.Errorf("the clone at %s was deleted under a session waiting at a prompt: %v", rec.Dir, err) + } + if !strings.Contains(done.Err, "still working") { + t.Errorf("the row does not say the session was left running: %q", done.Err) + } +} + // review-code ends its turn once the draft is posted, and claude goes on holding // the session. Submitting from the dashboard is the usual end of that review. func TestSubmittingADraftWhoseSessionEndedItsTurnStopsTheSession(t *testing.T) { diff --git a/internal/core/session/blocked_test.go b/internal/core/session/blocked_test.go index 269c2e1..bc44547 100644 --- a/internal/core/session/blocked_test.go +++ b/internal/core/session/blocked_test.go @@ -63,6 +63,32 @@ func TestPollKeepsABlockedSessionWithNothingPostedRunning(t *testing.T) { } } +// A permission prompt stops a session partway through its turn, and claude lists +// it as waiting rather than idle. The turn has not ended, so the poll reads +// nothing from GitHub, even when a draft of mine is already there. +func TestPollReadsNothingFromGitHubForASessionAtAPermissionPrompt(t *testing.T) { + ghc := &fakeGH{login: "haacked", info: prInfo()} + svc, _ := newService(t, ghc, newFakeGit()) + writeJobState(t, defaultJobs(t, svc), "6d681a76", `{"tempo": "blocked", "needs": "approve Bash: gh pr diff 7"}`) + rec := startedBackground(t, svc, bgRunner(bgEntry("6d681a76", bgSession, "blocked", "waiting", true))) + ghc.reviews = []review.GHReview{myPending()} + before := ghc.reads + + records, statuses, err := svc.PollBackground(context.Background()) + if err != nil { + t.Fatalf("PollBackground: %v", err) + } + if got := ghc.reads - before; got != 0 { + t.Errorf("read GitHub %d times for a session whose turn has not ended, want 0", got) + } + if records[0].State != review.StateReviewing { + t.Errorf("state = %q, want the review still running", records[0].State) + } + if status := statuses[rec.ID]; !status.Prompted || status.Need() != "approve Bash: gh pr diff 7" { + t.Errorf("status = %+v, want a session at a prompt that names it", status) + } +} + // A session stays blocked until the user answers it. Reading GitHub on every // tick for that long would spend two API calls per session every 15 seconds. func TestPollReadsGitHubOnceForEachStretchASessionIsBlocked(t *testing.T) { diff --git a/internal/mcp/mcp.go b/internal/mcp/mcp.go index 200f4fa..1cbca55 100644 --- a/internal/mcp/mcp.go +++ b/internal/mcp/mcp.go @@ -402,7 +402,7 @@ func view(rec review.Record, statuses map[string]engine.BGStatus) Review { p := status.Progress out.Progress = &Progress{ Detail: p.Detail, - Waiting: status.Waiting(), + Waiting: status.NeedsUser(), Needs: status.Need(), Agents: p.Agents, UpdatedAt: p.UpdatedAt, diff --git a/internal/mcp/mcp_test.go b/internal/mcp/mcp_test.go index d4eaa1f..416ab03 100644 --- a/internal/mcp/mcp_test.go +++ b/internal/mcp/mcp_test.go @@ -580,6 +580,24 @@ func TestListReviewsSaysWhatAWaitingSessionNeeds(t *testing.T) { } } +// A permission prompt stops the session partway through its turn, and claude's +// listing reports it as waiting rather than idle. +func TestListReviewsSaysASessionAtAPermissionPromptIsWaiting(t *testing.T) { + f := newFixture(t) + f.started(t) + f.agents("blocked", "waiting") + f.jobState(t, `{"tempo":"blocked","needs":"approve Bash: gh pr diff 7"}`) + + got := f.listedOne(t) + + if got.State != string(review.StateReviewing) || got.Progress == nil { + t.Fatalf("review = %+v, want reviewing with progress", got) + } + if p := *got.Progress; !p.Waiting || p.Needs != "approve Bash: gh pr diff 7" { + t.Errorf("progress = %+v, want waiting on the permission prompt", p) + } +} + // Nothing else moves a finished background session on while the TUI is closed. // Listing therefore reads the agent and GitHub rather than the index alone. func TestListReviewsMovesAFinishedSessionToDrafted(t *testing.T) { diff --git a/internal/tui/app.go b/internal/tui/app.go index 84106c2..7f67417 100644 --- a/internal/tui/app.go +++ b/internal/tui/app.go @@ -1676,8 +1676,7 @@ func (a App) applyPoll(polled bgPolledMsg) (tea.Model, tea.Cmd) { // change screens. a.err = polled.err if polled.records != nil { - a.dash = a.dash.SetRecords(polled.records) - a.dash.Background = polled.progress + a.dash = a.dash.SetRecords(polled.records).SetBackground(polled.progress) } return a.armPoll() } @@ -1708,16 +1707,15 @@ func (a App) pollBackground() tea.Cmd { } // progressFor hands each session's progress to the dashboard, which holds no -// engine to ask. A session that is Waiting is waiting for the user. The -// dashboard draws a row as waiting when the row names a need, so a waiting -// session always names one. A working session with no detail shows the agent's -// state. +// engine to ask. The dashboard draws a row as waiting when the row names a need, +// so a session that needs the user always names one. A working session with no +// detail shows the agent's state. func progressFor(statuses map[string]engine.BGStatus) map[string]review.Progress { progress := make(map[string]review.Progress, len(statuses)) for id, status := range statuses { p := status.Progress p.Needs = status.Need() - if status.Waiting() { + if status.NeedsUser() { p.Needs = cmp.Or(p.Needs, "your input") } else { p.Detail = cmp.Or(p.Detail, status.State) diff --git a/internal/tui/app_test.go b/internal/tui/app_test.go index 0ca2afe..e47b94e 100644 --- a/internal/tui/app_test.go +++ b/internal/tui/app_test.go @@ -370,6 +370,7 @@ func TestProgressForMarksOnlyASessionThatEndedItsTurnAsWaiting(t *testing.T) { "named": {State: "blocked", Idle: true, Progress: review.Progress{Needs: "permission to run gh"}}, "busy": {State: "blocked", Progress: review.Progress{Needs: "results from 5 reviewers"}}, "starting": {State: "working", Idle: true, Progress: review.Progress{Detail: "starting…", Active: true}}, + "prompted": {State: "blocked", Prompted: true, Progress: review.Progress{Detail: "starting…", Active: true}}, }) if got["bare"].Needs == "" { t.Error("a session that ended its turn with no status file does not read as waiting") @@ -386,6 +387,9 @@ func TestProgressForMarksOnlyASessionThatEndedItsTurnAsWaiting(t *testing.T) { if got["starting"].Needs != "" { t.Errorf("needs = %q, want none while the session starts", got["starting"].Needs) } + if got["prompted"].Needs == "" { + t.Error("a session stopped at a permission prompt does not read as waiting") + } } // claude's status file can be missing or unreadable. The row still says diff --git a/internal/tui/screens/dashboard/dashboard.go b/internal/tui/screens/dashboard/dashboard.go index 43d5705..e6d407f 100644 --- a/internal/tui/screens/dashboard/dashboard.go +++ b/internal/tui/screens/dashboard/dashboard.go @@ -29,13 +29,21 @@ type Styles struct { Err lipgloss.Style } -// groups is the order states appear in. Archived and abandoned records are in -// the last group, which stays hidden until the user asks for it. -var groups = []struct { +type group struct { Title string States []review.State - Closed bool -}{ + // Waiting holds the rows whose session needs the user. Every other group + // leaves them out. + Waiting bool + Closed bool +} + +// groups is the order states appear in. Archived and abandoned records are in +// the last group, which stays hidden until the user asks for it. +var groups = []group{ + // A session that needs the user makes no progress until the user answers + // it, so its row goes above every other. + {Title: "Waiting for you", States: []review.State{review.StateReviewing}, Waiting: true}, {Title: "Reviewing", States: []review.State{review.StateReviewing, review.StatePreparing}}, {Title: "Did not start", States: []review.State{review.StateNotStarted}}, {Title: "Drafted", States: []review.State{review.StateDrafted}}, @@ -83,6 +91,19 @@ func New(styles Styles) Model { func (m Model) SetRecords(records []review.Record) Model { selected, had := m.Selected() m.Records = records + return m.follow(selected, had) +} + +// SetBackground replaces what each session is doing and keeps the cursor on the +// record it was on. A session that starts or stops needing the user moves its +// row between groups. +func (m Model) SetBackground(progress map[string]review.Progress) Model { + selected, had := m.Selected() + m.Background = progress + return m.follow(selected, had) +} + +func (m Model) follow(selected review.Record, had bool) Model { if had { if i := slices.IndexFunc(m.rows(), func(r review.Record) bool { return r.ID == selected.ID }); i >= 0 { m.Cursor = i @@ -179,15 +200,15 @@ func (m Model) rows() []review.Record { if group.Closed && !m.ShowArchived { continue } - rows = append(rows, m.inGroup(group.States)...) + rows = append(rows, m.inGroup(group)...) } return rows } -func (m Model) inGroup(states []review.State) []review.Record { +func (m Model) inGroup(g group) []review.Record { var out []review.Record for _, rec := range m.Records { - if slices.Contains(states, rec.State) { + if slices.Contains(g.States, rec.State) && m.waiting(rec) == g.Waiting { out = append(out, rec) } } @@ -205,7 +226,7 @@ func (m Model) View() string { if group.Closed && !m.ShowArchived { continue } - records := m.inGroup(group.States) + records := m.inGroup(group) if len(records) == 0 { continue } @@ -272,6 +293,13 @@ func (m Model) meta(rec review.Record) string { return m.Styles.Dim.Render("· ") + m.Spinner.Render(note) + " " + meta } +// waiting reports that the row's session needs the user. The root names a need +// for every session that needs the user. +func (m Model) waiting(rec review.Record) bool { + act, ok := m.Background[rec.ID] + return ok && rec.BackgroundRunning() && act.Needs != "" +} + // activity is the line under a running background row that says what its // session is doing, and whether the session is waiting for the user. It is // empty for any other row, and for a session the last poll said nothing about. @@ -280,7 +308,7 @@ func (m Model) activity(rec review.Record) (string, bool) { if !ok || !rec.BackgroundRunning() { return "", false } - if act.Needs != "" { + if m.waiting(rec) { parts := []string{"waiting for you: " + act.Needs, "enter opens it"} if act.Detail != "" { parts = append(parts, act.Detail) diff --git a/internal/tui/screens/dashboard/progress_test.go b/internal/tui/screens/dashboard/progress_test.go index 653b51e..783c999 100644 --- a/internal/tui/screens/dashboard/progress_test.go +++ b/internal/tui/screens/dashboard/progress_test.go @@ -153,6 +153,48 @@ func TestABlockedSessionSaysItIsWaitingForYou(t *testing.T) { } } +// A row waiting on the user goes in a group above every other, so it is the +// first thing on the dashboard rather than a red line among working rows. +func TestASessionWaitingForYouIsGroupedFirst(t *testing.T) { + working := runningRecord() + working.ID, working.BGID = "rec-2", "22222222" + drafted := runningRecord() + drafted.ID, drafted.State, drafted.BGID = "rec-3", review.StateDrafted, "" + m := progressModel(160, drafted, working, runningRecord()) + m.Background = map[string]review.Progress{ + "rec-1": {Needs: "approve Bash: gh pr diff 7"}, + "rec-2": {Detail: "running reviewers"}, + } + + view := m.View() + if !strings.HasPrefix(view, "Waiting for you (1)\n") { + t.Fatalf("the waiting group is missing or not first:\n%s", view) + } + if !strings.Contains(view, "Reviewing (1)") { + t.Errorf("the working row is not left under Reviewing:\n%s", view) + } + if rows := m.rows(); len(rows) != 3 || rows[0].ID != "rec-1" { + t.Errorf("rows = %v, want the waiting row first so the cursor order matches the view", rows) + } +} + +// A poll that finds a session waiting moves its row to another group. The cursor +// stays on the record rather than on the position, so x and s act on the row +// the user chose. +func TestTheCursorFollowsARowThatStartsWaiting(t *testing.T) { + first := runningRecord() + second := runningRecord() + second.ID, second.BGID = "rec-2", "22222222" + m := progressModel(160, first, second) + m.Cursor = 1 + + m = m.SetBackground(map[string]review.Progress{"rec-2": {Needs: "your input"}}) + + if rec, _ := m.Selected(); rec.ID != "rec-2" { + t.Errorf("selected = %s, want rec-2 after it moved to the waiting group", rec.ID) + } +} + // Nothing tells docket that a session has hung. The time since the agent last // updated its account is the sign the user can judge by. func TestAQuietSessionSaysHowLongSinceItsLastUpdate(t *testing.T) {