From 1cccc1296b2a3d1cdb43e266c5cbbea0dfd87fac Mon Sep 17 00:00:00 2001 From: Bharat Kunwar Date: Mon, 23 Nov 2026 12:31:41 +0545 Subject: [PATCH] feat: show a busy session's queued messages in the preview MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A message that reaches a session mid-turn (typed in its tab, sent from ccs, or from another session) waits in Claude Code's queue, which its tab shows as "⎿ Queued" until Claude takes it in. The preview now shows the same at its end, while the session is busy or waiting: each message, then a dim "⎿ Queued". Once taken in it is an ordinary message above. The queue comes from Claude Code's queue-operation lines: enqueue adds a message; remove, popAll and popOne drop one by content; a dequeue names none, so the user line or queued_command that follows is the message taken in. Only messages enqueued since the last turn end count, since a turn that ends with messages queued takes them in at once. Queued messages aren't messages: counts, unread, done, WHEN and the search ignore them. ccs sessions lists them as queued: lines (queued in --json). Codex rollouts record no queue. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 1 + README.md | 1 + internal/mcp/sessions.go | 9 ++ internal/mcp/sessions_test.go | 21 +++ internal/transcript/ingest.go | 6 +- internal/transcript/queue.go | 148 ++++++++++++++++++++ internal/transcript/queue_test.go | 225 ++++++++++++++++++++++++++++++ internal/transcript/transcript.go | 83 ++++++----- internal/tui/ingest_clean_test.go | 30 +++- internal/tui/preview.go | 37 ++++- internal/tui/preview_test.go | 48 +++++++ 11 files changed, 570 insertions(+), 39 deletions(-) create mode 100644 internal/transcript/queue.go create mode 100644 internal/transcript/queue_test.go diff --git a/AGENTS.md b/AGENTS.md index 202671a..1f9fcab 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -64,6 +64,7 @@ Install the release locally: `brew update && brew upgrade ccs`. - `internal/mcp/hold.go` - the hold: `Holder` (`NewHolder`, `HoldConfig`: Who, Wait, KeyRelease, MayHold, Yields, OnYield) owns serve-hook.sock and serve-control.sock while it holds the flock on `serve-hook.lock` (`tryLock`; a crashed owner's lock goes with its process, and its sockets are removed on the next bind). `Listen(takeOver)`: ccs serve passes true and asks a TUI owner to `yield` over the control socket (a serve owner refuses: "another ccs serve"); a TUI passes false and is otherwise a client. `holdPrompt` (the nonce acknowledgement, MayHold false lets it go at once, `ReleaseAll`'s channel, the wait, the key release), `serveControl` (list, answer, yield), `control` and `List`/`Answer` for an owner's own use. `ccs serve` holds through one (`s.hold`, `s.prompts` its book; `listenHooks`/`listenControl` are `ownHold`) - `internal/mcp/serve.go`, `access.go`, `serve_pages.go`, `serve_view.go` (the phone layout: `buckets`, `messageViews` and `segments` turn `Conversation.Messages` into bubbles, `pageOf` pages them, `refreshes` decides the meta refresh (the sessions page, a waiting session's page, whose composer is then hidden), the manifest and icons, `/manifest.webmanifest`, `/icon.svg`, `/icon/{180,192,512}`, behind the same checks; a preview's redirects keep its path, `statusWriter.base`) - `ccs serve` (`RunServe`): the sessions as a web page for a phone, behind a Cloudflare Tunnel with Cloudflare Access. It listens on loopback only (`loopbackOnly`) and, on every request, checks the Host (`--host`), then Access's signed `Cf-Access-Jwt-Assertion` itself (`accessVerifier`: RS256 against the team's certs, used for `accessKeysFresh` then fetched again (at most every `accessRefetch`, outside the cache lock; a failed fetch keeps keys under `accessKeysStale`, then refuses), aud, iss, exp/nbf within `accessSkew`, an allowed email), then a POST's `Origin`/`Sec-Fetch-Site`, then the rate limit (`rateLimits`: only a confirmed write spends the write allowance). Pages: `/` the triage (`TriageRows`), `/session` `read_session` with the pending question and, with `--allow-write`, the forms; `/prs` `list_prs`; JSON under `/api/`. Writes are POSTs to `/act` with the CSRF token (`csrf`, HMAC of the email, a key per process), shown as a confirm page (`describe`) until `confirm=yes`. Send goes over the session's socket as `the user, via ccs` with `CcsNote` (Codex: its queue), never typed; nothing is ever typed into a terminal; prompts are answered through `ccs hook permission` (`hook.go`: a PermissionRequest hook that sends its input with a nonce (`hookHello`) to `hookSockPath` once `trustedSocket` passes (a real 0600 socket of this user's in a folder of theirs no one else can write; other users are what it keeps out, same-user processes are out of scope), needs serve's acknowledgement echoing the nonce within `hookAckWait`, and prints `hookDecision`, built from its own input (serve sends only allow or deny and a question's labels, `hookReply`, checked against the question's options), or nothing when no serve listens or it's let go, so the terminal asks as usual. Its hello carries `WaitAt`, its own wait (`ownWait`: the statusUpdatedAt its session file, `hookSessionFile` for its parent pid, shows waiting within `ownWaitWindow` of its start), and a holder with that known holds it on exactly that wait, letting it go at once, unlisted, when its scan shows the wait over. A holder going away (`Holder.Handoff`: the TUI's `releaseHold` on quit or update restart, a yield to ccs serve, ccs serve stopping) replies `Retry` instead of a final no-decision (logged "handed back for a restart"), and the hook (`hookOnce` in a loop) dials again every `hookRedial` with every check repeated (trustedSocket, `hookPeerUID`, a new nonce, the acknowledgement), as it does when the connection closes with no reply (a crash). It stops, printing nothing, when `ownWait.over` (its file shows another session, not waiting, or another wait; an unreadable file says nothing) or `hookMaxWait` after its start (`hookNow`, `hookSleep` stubbed in tests). A reply for another nonce, or a final no-decision, ends it. `Close` stays final; tests' `TestMain` stubs the session file as another session's, so a hook a test leaves behind stops at its first redial; `ccs hook install|uninstall [--print]`, `editHookSettings`, keeps the old settings as `.before-ccs-hook`, timeout `hookTimeout` above `maxHookWait`). With `--allow-write`, `listenHooks` (one ccs serve at a time) holds each prompt (`serve_prompts.go`, `holdPrompt`, `promptBook`) until the page answers it (`actPrompt`, `promptDecision`: allow, an AskUserQuestion's answers in `updatedInput`, each one of its options, deny, or `mac` to let it go), the hook goes away, `--hook-wait` passes, or (not in `--preview`) `keyIdle` (`sessions.KeyIdle`, shared with ^X A) shows a key pressed since it arrived; letting go never decides; a session's own question with no held prompt is shown only (`askView`); `serve_control.go`: `serve-control.sock` (`ControlSockPath`, opened by `listenControl` with the hook socket) lets the TUI list held prompts and answer one (`{"op":"list"}`, `{"op":"answer",prompt,choice,answers}`: a choice and labels only, unknown fields dropped, through `promptDecision` and `prompts.take`, first wins, logged as `tui (this Mac)`), both ends checked with `trustedSocket` and `peerUID`; clients `HeldPrompts`, `AnswerHeld`; launch, close and restart go through `Call`, close and restart passing `session_id` (both tools take it). Every stop goes through `sessions.CloseSession(name, pid, id)`, which checks `IdentityOf(pid)` (the session file's id, read up to three times, else a fresh, uncached `LiveCodexSessions` look for a Codex thread) against id immediately before the SIGTERM and refuses on a mismatch, an unreadable file or no id; `ccs close` by name takes the id at discovery after `sameSession` checks the name is still exactly that session's. Requests share one scan while it runs (`load(ctx)`, `inflight`; the scan runs in its own goroutine and each waiter leaves when its request's context ends) and at most `serveSlots` are served at once. A graceful close whose session id changes in the same pid (`replaced`) leaves that pid running; `SameSession` checks a Codex session (no session file) against `LiveCodexSessions`. Every request goes to the activity log. `--preview` (`serveConfig.preview`) has no verifier: everything lives under `/p/` (`base`, `pageData.Base`, `$.Base` in every template link and form; `previewPath` checks it in constant time and strips it before routing, anything else is a 404 that never logs the path, since loopback is shared by every user and a 127.0.0.1 cookie would reach every port), a loopback Host only, the Access flags refused, logged as `previewUser`; `ccs serve install` refuses it, and `privateServeLog` keeps the agent's log 0600; read-only unless `--allow-write`, and then a POST needs `Origin` `http://`, a same-origin `Sec-Fetch-Site` and the CSRF token, as remotely. Tests stub `sendEnvelope`, `readSessionFile`, `peerToken`, `serveCall`, `sessions.TypeKeys` and the verifier's `fetch` - Remote Control names (`internal/state/remote.go`): Claude Code ignores a session's `--name`/`/rename` title for Remote Control while it suppresses the conversation's history (a conversation started under another organisation, as after a cswap switch: `history-suppression` records in its transcript), showing `-` and later a title made from a message; only an explicit `--remote-control ` always names it. `state.RemoteControlArgs` adds that when ^X V (`remote_control` in settings.json, `state.RemoteControl`, kept by `foreignSettings`) is on or the caller asks: `launchScript` (Claude only, `LaunchOpts.RemoteControl`), `OpenResumeTab` and the exec-in-place resume through `ResumeRemoteControlArgs` (a user-set name only, never a fork), and `RestartSession` asks whenever the old session file had a `bridgeSessionId` (`SessionFile.BridgeSessionID`, `restartTarget.remote`). ^X V opens a popup (`internal/tui/remote.go`: `rcPopup`, `rcKey`, `m.rcOpen`): v toggles that setting (`toggleRemoteControl`); t (the selection) and a (`rcCandidates`: every live Claude Code row) type `/remote-control ` into running sessions (`rcStart`, `rcType`), the name from `rcName` (the session file's name, else a user-set title, matching `state.SessionName`). `rcCheck` refuses on the key: not live, `SessionStat.Remote` (a `bridgeSessionId`; with it on the command opens a menu that waits for a key), no name, anything `slashRefusal` (shared with `typeSlash`: Codex, agy, subagent, background, app-hosted, a held prompt, busy, waiting, unverified) says, or not idle; `typeSlashNow` (also `typeSlash`'s) checks again just before the keys, with a recheck of the fresh session file's `bridgeSessionId`. Then `rcType` polls each typed session's file for `bridgeSessionId` (`rcConfirmWait`, `rcConfirmEvery`) and says when it didn't appear; `applyRC` gives each session a note in its box (grey when skipped), logs each to the activity log and sums it up +- Queued messages (`internal/transcript/queue.go`): Claude Code's queue-operation lines (enqueue with content; remove with content and a reason, `absorbed_mid_turn` then that message's `queued_command`; popAll / popOne per message pulled back to edit; dequeue with no content, then the user line holding it) kept as `Conversation.Queue` (`QueuedMessage`, text cleaned in `noteEnqueued`, `key` the raw `queueKey`: a cross-session message's body, whitespace collapsed, matched exactly, never drawn). A remove or pop drops by content (`noteRemoved`; an absorbed one's key waits in `queueTaken` for its `queued_command`, so the same text queued twice keeps the second), a user line or `queued_command` drops the one it is (`noteUnqueued`); harness text and channel events are never queued. `QueuedNow` is those enqueued after the last turn end, since a turn that ends with messages queued takes them in at once: an older one is one never seen taken in (a slash command). The preview draws them last (`queuedLines`: `❯` text or `From `, then a dim `⎿ Queued`; not in a search), only while the session is busy or waiting (`queuedShown`), and `ccs sessions` rows carry `queued` (`QueuedMessage.Plain`); not `read_session`. Not messages: counts, unread, done, WHEN and the search ignore them. Codex rollouts record no queue - Launch briefs: `briefText` puts a newline before a brief that starts with `-`, so the brief, a positional argument after claude's or codex's options, is never read as an option - `internal/tui` (all `package tui`, same directory) - the terminal UI and the command line (`Main`): everything else, split by area into the files below diff --git a/README.md b/README.md index 1e8e4cf..1bfc556 100644 --- a/README.md +++ b/README.md @@ -245,6 +245,7 @@ export CCS_CLAUDE_ARGS="--permission-mode auto" - The rule for which is which: single keys act now and leave nothing behind (move, open, message, fork, refresh); `Ctrl+X` then a letter changes something that stays (a mark, a setting, a file, whether a session runs), and the ones that can't be undone (`Ctrl+X D` delete, `Ctrl+X K` stop, `Ctrl+X X` shrink) ask first - `↑/↓` or `Ctrl+P/N` - Move through the list - Background sessions (`claude --bg`) show `bg ` on the grey row: Enter opens one with `claude attach` in a new tmux window or iTerm tab, and `Ctrl+X K` stops it once you say `y` (on a session in a terminal tab, it stops it and closes the tab). One started from another session's `claude --bg` sits under it +- Queued messages: while a session is mid-turn, the messages it has queued and not taken in yet (typed in its tab, sent from ccs or from another session) show at the end of its preview as Claude Code draws them, each followed by a dim `⎿ Queued`, until Claude takes it in and it becomes an ordinary message. `ccs sessions` lists them too, as `queued:` lines (`queued` in `--json`). Codex records no queue, so its sessions show none - Messages between sessions show at both ends: the sender's preview shows each `SendMessage` as `To ` (`✓ arrived` once it's in that session's transcript), the recipient's `From ` - A live session run by an app without a terminal shows `in `. One in T3 Code opens in T3 Code with Enter, at its thread; any other app gets a hollow `○`, since ccs can't switch to it, and Enter on its empty message box says to open it there. Messaging it from that box and forking it (`Ctrl+F`) work either way - Each session's name is coloured by its state: magenta waiting on you, light magenta asked you something, amber busy, cyan done since you last looked; plain when it's running and idle, and dim when it isn't running. A session in an app ccs can't open has a `○` before it diff --git a/internal/mcp/sessions.go b/internal/mcp/sessions.go index 1ccfe45..8d6d9c0 100644 --- a/internal/mcp/sessions.go +++ b/internal/mcp/sessions.go @@ -90,6 +90,7 @@ type SessionRow struct { WaitingFor string `json:"waiting_for,omitempty"` // with waiting: "permission prompt", "input needed" Question string `json:"question,omitempty"` // with waiting: the menu or the tool call it asks about Asked bool `json:"asked,omitempty"` // idle, and its last message ends in a question + Queued []string `json:"queued,omitempty"` // busy or waiting: messages it has queued and not taken in yet LastError string `json:"last_error,omitempty"` // the latest API error, until a later reply succeeds LastErrorAt string `json:"last_error_at,omitempty"` PRs []string `json:"prs,omitempty"` // every PR it or its subagents opened, merged or touched @@ -144,6 +145,11 @@ func sessionRow(conv transcript.Conversation, l sessions.LiveSession, ok bool, n case "idle": r.Asked = conv.AskedLast() } + if st.Status == "busy" || st.Status == "waiting" { // an idle session takes a message in as it arrives + for _, q := range conv.QueuedNow() { + r.Queued = append(r.Queued, q.Plain()) + } + } since, _ := time.Parse(time.ANSIC, strings.Join(strings.Fields(l.Start), " ")) r.Tasks = len(transcript.RunningTasks(conv, since, now)) for _, s := range transcript.SubagentsOf(conv) { @@ -235,6 +241,9 @@ func (r SessionRow) details(now time.Time) []string { if r.Asked { out = append(out, "its last message asks something") } + for _, q := range r.Queued { + out = append(out, "queued: "+strings.ReplaceAll(q, "\n", "\n ")) + } if r.LastError != "" { at := "" if r.LastErrorAt != "" { diff --git a/internal/mcp/sessions_test.go b/internal/mcp/sessions_test.go index 0523662..bd67bfc 100644 --- a/internal/mcp/sessions_test.go +++ b/internal/mcp/sessions_test.go @@ -240,3 +240,24 @@ func TestSessionRowStaleBusyIsIdle(t *testing.T) { t.Errorf("got %s since %s, want idle since the turn's end", r.Status, r.Since) } } + +// A busy session lists the messages it has queued and not taken in; an idle +// one has none, whatever an old enqueue says. +func TestSessionRowQueued(t *testing.T) { + now := time.Date(2026, 11, 20, 12, 40, 0, 0, time.UTC) + conv := transcript.Conversation{SessionID: "a"} + transcript.ParseLine(&conv, []byte(`{"type":"user","timestamp":"`+now.Add(-2*time.Minute).Format(time.RFC3339Nano)+`","message":{"role":"user","content":"go"}}`)) + transcript.ParseLine(&conv, []byte(`{"type":"queue-operation","operation":"enqueue","timestamp":"`+now.Add(-time.Minute).Format(time.RFC3339Nano)+`","content":"and the tests"}`)) + busy := sessions.LiveSession{PID: 1, Stat: sessions.SessionStat{Status: "busy", Since: now.Add(-2 * time.Minute)}} + r := sessionRow(conv, busy, true, now) + if len(r.Queued) != 1 || r.Queued[0] != "and the tests" { + t.Fatalf("queued: %q", r.Queued) + } + if d := strings.Join(r.details(now), "\n"); !strings.Contains(d, "queued: and the tests") { + t.Errorf("details: %q", d) + } + idle := sessions.LiveSession{PID: 1, Stat: sessions.SessionStat{Status: "idle", Since: now}} + if r := sessionRow(conv, idle, true, now); r.Queued != nil { + t.Errorf("idle: %q", r.Queued) + } +} diff --git a/internal/transcript/ingest.go b/internal/transcript/ingest.go index 6924239..bc2f7f1 100644 --- a/internal/transcript/ingest.go +++ b/internal/transcript/ingest.go @@ -10,8 +10,10 @@ package transcript // Left raw on purpose, because code matches them rather than draws them: // SessionID, FilePath, PeerRef.Key and .Addr (the other end's copy and // socket path are compared byte for byte), Pending's raw tool input (decoded -// where it is drawn, and cleaned after decoding: DecodeClean), and PRs -// (validated as github.com addresses before use). +// where it is drawn, and cleaned after decoding: DecodeClean), PRs +// (validated as github.com addresses before use), and a queued message's key +// and queueTaken (matched against the copy taken in; its Text is cleaned by +// noteEnqueued, not cleanSince, since the capped queue can keep its length). // ingestMark is how far each record list had got before a line was applied: // everything at or past it is new and still raw. diff --git a/internal/transcript/queue.go b/internal/transcript/queue.go new file mode 100644 index 0000000..a8a7389 --- /dev/null +++ b/internal/transcript/queue.go @@ -0,0 +1,148 @@ +package transcript + +import ( + "slices" + "strings" + "time" +) + +// Claude Code's message queue, as its transcript records it. A message that +// arrives while a turn runs (typed in its tab, sent from ccs, or from another +// session) is held in a queue and shown under the prompt as "⎿ Queued" until +// Claude takes it in. Each change is a queue-operation line: +// +// - enqueue, with the message as content: it joined the queue (a message +// given to an idle session is enqueued and dequeued in the same moment) +// - remove, with content and a reason: it left the queue, taken in mid-turn +// (absorbed_mid_turn, then a queued_command attachment with its text), +// handed to an agent (delivered_to_agent), or dropped +// - popAll / popOne, with content, once per message: pulled back into the +// prompt to edit (Up or Esc), so it is no longer queued +// - dequeue, with no content: taken in at the start of a turn, followed by +// a user line holding its text +// +// A dequeue names no message, so a message counts as taken in when its text +// shows up in a user line or queued_command attachment, the way it appears +// in the conversation; a remove, popAll or popOne names it by content. +// Messages are matched by queueKey, which looks past the wrapping a +// cross-session message is given when it is taken in (an "Another Claude +// session sent a message:" line, attributes such as hop-chain dropped). +// +// Codex keeps no such record: its rollouts have task_started, task_complete +// and turn_aborted, nothing for a queued message. + +// QueuedMessage is a message waiting in the session's queue. +type QueuedMessage struct { + Text string // cleaned where it enters (noteEnqueued) + Ts string + key string // queueKey of the raw text, for matching the copy that is taken in; raw, never drawn +} + +// Plain is the message as the session will be given it, for a list: a +// message from another session says who sent it, one typed in ccs is the +// user's own words. +func (q QueuedMessage) Plain() string { + from, body, ok := PeerParts(q.Text) + switch { + case !ok: + return StripImageNote(q.Text) + case from == CcsSender: + return body + } + return "from " + from + ": " + body +} + +// CcsSender is the from-name of a message typed in ccs and sent over a +// session's socket. +const CcsSender = "the user, via ccs" + +// maxQueue caps the queue ccs keeps: messages it never sees taken in (a +// session that exited with some queued) would otherwise build up. +const maxQueue = 50 + +// queueKey is the part of a queued message that survives being taken in: +// a cross-session message's body, whitespace collapsed. +func queueKey(text string) string { + if m := PeerMessage.FindStringSubmatch(strings.TrimSpace(text)); m != nil { + text = m[2] + } + return strings.Join(strings.Fields(text), " ") +} + +// noteEnqueued adds a message that joined the queue. Harness text (task +// notifications, channel events, reminders) is queued too, but Claude Code +// doesn't show it as a queued message, so neither does ccs. +func noteEnqueued(conv *Conversation, text, ts string) { + if strings.TrimSpace(text) == "" || isChannelEvent(text) { + return + } + if _, _, ok := HarnessNote(text); ok && !PeerMessage.MatchString(text) { + return + } + key := queueKey(text) + if key == "" { + return + } + q := conv.Queue + if len(q) >= maxQueue { + q = slices.Clone(q[1:]) + } + // Cleaned here rather than by cleanSince: at the cap the queue keeps its + // length, so a mark by length wouldn't see the new message. + conv.Queue = append(q, QueuedMessage{Text: CleanText(text), Ts: CleanText(ts), key: key}) +} + +// noteRemoved drops the queued message a remove, popAll or popOne names by +// its content. One taken in mid-turn (absorbed) is followed by its +// queued_command, so its key waits in queueTaken for that copy, which then +// drops nothing: with the same text queued twice, the second stays queued. +func noteRemoved(conv *Conversation, text string, absorbed bool) { + key := queueKey(text) + if i := slices.IndexFunc(conv.Queue, func(q QueuedMessage) bool { return q.key == key }); key != "" && i >= 0 { + conv.Queue = slices.Delete(slices.Clone(conv.Queue), i, i+1) + if absorbed { + taken := conv.queueTaken + if len(taken) >= maxQueue { + taken = slices.Clone(taken[1:]) + } + conv.queueTaken = append(taken, key) + } + } +} + +// noteUnqueued drops the first queued message text is: a user line or +// queued_command, a message as it was taken into the conversation (after a +// dequeue, which names none), unless it's the copy of one a remove already +// dropped. Always a new slice, never the old one's array, since copies of +// the conversation handed out earlier share it. +func noteUnqueued(conv *Conversation, text string) { + if len(conv.Queue) == 0 && len(conv.queueTaken) == 0 || strings.TrimSpace(text) == "" { + return + } + key := queueKey(text) + if i := slices.IndexFunc(conv.queueTaken, func(k string) bool { return k == key }); i >= 0 { + conv.queueTaken = slices.Delete(slices.Clone(conv.queueTaken), i, i+1) + return + } + if i := slices.IndexFunc(conv.Queue, func(q QueuedMessage) bool { return q.key == key }); i >= 0 { + conv.Queue = slices.Delete(slices.Clone(conv.Queue), i, i+1) + } +} + +// QueuedNow is what the session's queue holds now: messages enqueued since +// its last turn end. A turn that ends with messages queued starts the next +// at once by taking them in, so any older one still listed is a message ccs +// never saw taken in (a slash command, which shows as its output, or one +// queued when the session exited). Only meaningful while the session is +// running and mid-turn; an idle session's queue is empty. +func (c Conversation) QueuedNow() []QueuedMessage { + var out []QueuedMessage + for _, q := range c.Queue { + t, err := time.Parse(time.RFC3339Nano, q.Ts) + if err != nil || !t.After(c.turnEnd) { + continue + } + out = append(out, q) + } + return out +} diff --git a/internal/transcript/queue_test.go b/internal/transcript/queue_test.go new file mode 100644 index 0000000..1d2e6bc --- /dev/null +++ b/internal/transcript/queue_test.go @@ -0,0 +1,225 @@ +package transcript + +import ( + "encoding/json" + "testing" +) + +// queueLines applies records, each a map marshalled to one line, to a fresh +// conversation. +func queueLines(t *testing.T, conv *Conversation, records ...map[string]any) { + t.Helper() + for _, r := range records { + b, err := json.Marshal(r) + if err != nil { + t.Fatal(err) + } + if !ParseLine(conv, b) { + t.Fatalf("not applied: %s", b) + } + } +} + +func qop(op, content, ts string, extra ...string) map[string]any { + r := map[string]any{"type": "queue-operation", "operation": op, "timestamp": ts} + if content != "" { + r["content"] = content + } + for i := 0; i+1 < len(extra); i += 2 { + r[extra[i]] = extra[i+1] + } + return r +} + +func queueUserLine(text, ts string) map[string]any { + return map[string]any{"type": "user", "timestamp": ts, "message": map[string]any{"role": "user", "content": text}} +} + +func queuedAttachment(text, ts string) map[string]any { + return map[string]any{"type": "attachment", "timestamp": ts, "attachment": map[string]any{"type": "queued_command", "prompt": text, "commandMode": "prompt"}} +} + +func queuedTexts(c Conversation) []string { + var out []string + for _, q := range c.QueuedNow() { + out = append(out, q.Text) + } + return out +} + +func sameTexts(a, b []string) bool { + if len(a) != len(b) { + return false + } + for i := range a { + if a[i] != b[i] { + return false + } + } + return true +} + +// A message typed mid-turn is queued until Claude takes it in: a remove +// (absorbed_mid_turn) and then its queued_command, which is the message as +// the conversation shows it. +func TestQueueTypedMidTurn(t *testing.T) { + var c Conversation + queueLines(t, &c, + queueUserLine("tidy the docs", "2026-11-23T10:00:00Z"), + qop("enqueue", "and the readme", "2026-11-23T10:00:05Z"), + qop("enqueue", "and the changelog", "2026-11-23T10:00:06Z"), + ) + if got := queuedTexts(c); !sameTexts(got, []string{"and the readme", "and the changelog"}) { + t.Fatalf("queued: %q", got) + } + if len(c.Messages) != 1 { + t.Errorf("a queued message isn't a message yet: %d", len(c.Messages)) + } + queueLines(t, &c, + qop("remove", "and the readme", "2026-11-23T10:00:09Z", "reason", "absorbed_mid_turn"), + queuedAttachment("and the readme", "2026-11-23T10:00:05Z"), + ) + if got := queuedTexts(c); !sameTexts(got, []string{"and the changelog"}) { + t.Errorf("after one is taken in: %q", got) + } + if n := len(c.Messages); n != 2 || c.Messages[1].Text != "and the readme" { + t.Errorf("the one taken in is a message now: %+v", c.Messages) + } +} + +// The same text queued twice: the queued_command that follows a remove is +// that message's copy, so the second stays queued. +func TestQueueSameTextTwice(t *testing.T) { + var c Conversation + queueLines(t, &c, + qop("enqueue", "yes", "2026-11-23T10:00:05Z"), + qop("enqueue", "yes", "2026-11-23T10:00:06Z"), + qop("remove", "yes", "2026-11-23T10:00:09Z", "reason", "absorbed_mid_turn"), + queuedAttachment("yes", "2026-11-23T10:00:05Z"), + ) + if got := queuedTexts(c); len(got) != 1 { + t.Errorf("the second yes should still be queued: %q", got) + } +} + +// A dequeue names no message: the user line that follows is the one taken in. +// A message from another session is taken in wrapped differently from how it +// was queued (an introduction line, attributes such as hop-chain dropped). +func TestQueueDequeuedAtTurnStart(t *testing.T) { + queued := "\nrun the migration\n" + given := "Another Claude session sent a message:\n\nrun the migration\n" + var c Conversation + queueLines(t, &c, + qop("enqueue", "check the build", "2026-11-23T10:00:05Z"), + qop("enqueue", queued, "2026-11-23T10:00:06Z"), + ) + if got := c.QueuedNow(); len(got) != 2 || got[1].Plain() != "from planner: run the migration" { + t.Fatalf("queued: %+v", got) + } + queueLines(t, &c, + map[string]any{"type": "system", "subtype": "turn_duration", "durationMs": 9000, "timestamp": "2026-11-23T10:00:10Z"}, + qop("dequeue", "", "2026-11-23T10:00:10Z"), + map[string]any{"type": "user", "isMeta": true, "timestamp": "2026-11-23T10:00:10Z", "message": map[string]any{"role": "user", "content": given}}, + ) + if got := queuedTexts(c); !sameTexts(got, nil) { + t.Errorf("hidden once its turn ended, and the peer's taken in: %q", got) + } + for _, q := range c.Queue { + if q.Text == queued { + t.Errorf("the peer's message should have left the queue: %+v", c.Queue) + } + } + queueLines(t, &c, + qop("dequeue", "", "2026-11-23T10:00:11Z"), + queueUserLine("check the build", "2026-11-23T10:00:11Z"), + ) + if len(c.Queue) != 0 { + t.Errorf("both taken in: %+v", c.Queue) + } +} + +// Pulled back into the prompt to edit (popAll, popOne) or dropped (remove of +// any reason): no longer queued. +func TestQueuePoppedAndRemoved(t *testing.T) { + var c Conversation + queueLines(t, &c, + qop("enqueue", "one", "2026-11-23T10:00:01Z"), + qop("enqueue", "two", "2026-11-23T10:00:02Z"), + qop("enqueue", "three", "2026-11-23T10:00:03Z"), + qop("popAll", "one", "2026-11-23T10:00:04Z"), + qop("popOne", "two", "2026-11-23T10:00:04Z"), + qop("remove", "three", "2026-11-23T10:00:05Z", "reason", "cleared_on_cancel"), + ) + if len(c.Queue) != 0 || len(c.queueTaken) != 0 { + t.Errorf("queue %+v taken %q", c.Queue, c.queueTaken) + } + // Edited and sent again: queued again, and taken in by its user line. + queueLines(t, &c, + qop("enqueue", "one", "2026-11-23T10:00:06Z"), + qop("dequeue", "", "2026-11-23T10:00:07Z"), + queueUserLine("one", "2026-11-23T10:00:07Z"), + ) + if len(c.Queue) != 0 { + t.Errorf("resent and taken in: %+v", c.Queue) + } +} + +// Task notifications, channel events and other harness text are queued too, +// but Claude Code doesn't show them as queued messages. +func TestQueueSkipsHarnessText(t *testing.T) { + var c Conversation + queueLines(t, &c, + qop("enqueue", "\nb1\ncompleted\n", "2026-11-23T10:00:01Z"), + qop("enqueue", `merged`, "2026-11-23T10:00:02Z"), + qop("enqueue", "", "2026-11-23T10:00:03Z"), + ) + if len(c.Queue) != 0 { + t.Errorf("harness text isn't a queued message: %+v", c.Queue) + } + if c.FirstTimestamp != "" || c.LastTimestamp != "" { + t.Errorf("the queue doesn't move WHEN: %q %q", c.FirstTimestamp, c.LastTimestamp) + } +} + +// A message ccs never saw taken in (a slash command, which shows as its +// output) is hidden once a turn ends after it. +func TestQueueNowAfterTurnEnd(t *testing.T) { + var c Conversation + queueLines(t, &c, + qop("enqueue", "/rename tidy", "2026-11-23T10:00:01Z"), + map[string]any{"type": "system", "subtype": "turn_duration", "durationMs": 1000, "timestamp": "2026-11-23T10:00:02Z"}, + ) + if len(c.Queue) != 1 || len(c.QueuedNow()) != 0 { + t.Errorf("kept but not shown: %+v %+v", c.Queue, c.QueuedNow()) + } + queueLines(t, &c, qop("enqueue", "next", "2026-11-23T10:00:03Z")) + if got := queuedTexts(c); !sameTexts(got, []string{"next"}) { + t.Errorf("queued in the turn running now: %q", got) + } +} + +// Plain is the text as a list shows it: a ccs message is the user's words. +func TestQueuedMessagePlain(t *testing.T) { + q := QueuedMessage{Text: "\n" + CcsNote + "ship it\n"} + if got := q.Plain(); got != "ship it" { + t.Errorf("ccs message: %q", got) + } + if got := (QueuedMessage{Text: "plain words"}).Plain(); got != "plain words" { + t.Errorf("typed: %q", got) + } +} + +// Taking a message out never writes over the array a copy handed out +// earlier still reads. +func TestQueueRemovalCopies(t *testing.T) { + var c Conversation + queueLines(t, &c, + qop("enqueue", "a", "2026-11-23T10:00:01Z"), + qop("enqueue", "b", "2026-11-23T10:00:02Z"), + ) + before := c + queueLines(t, &c, qop("remove", "a", "2026-11-23T10:00:03Z")) + if len(before.Queue) != 2 || before.Queue[0].Text != "a" || before.Queue[1].Text != "b" { + t.Errorf("the earlier copy changed: %+v", before.Queue) + } +} diff --git a/internal/transcript/transcript.go b/internal/transcript/transcript.go index cc2bb97..fe37167 100644 --- a/internal/transcript/transcript.go +++ b/internal/transcript/transcript.go @@ -79,34 +79,36 @@ type Conversation struct { // and whether a user line was seen (it decides Spawned). ParsedBytes int64 sawUser bool - firstCwd string // the folder its first user line was in - lastCwd string // the folder its latest user line was in; Cwd falls back to it when firstCwd is gone (resolveCwd) - sdkCLI bool // its first user line's entrypoint is sdk-cli (claude -p) - firstPrompt string // the first promptId seen - morePrompts bool // a second promptId: something talked to it after its first prompt - CodexExec bool // a Codex session started by codex exec - Queued []string // recent messages the session has queued (peers, ccs's socket, or typed while it's busy), for delivery status - lastUsageID string // one reply spans several lines with the same id and usage; count it once - TailApplied bool // an unterminated last line parsed as a record, so resuming at ParsedBytes would repeat it - Pending *toolCall // the last tool call still without a result: what a waiting session asks about - PRs []string // its PRs, first touched first: Claude Code's pr-link records, and those gh pr create/merge printed (ghPRCall) - GHCalls []string // gh pr create/merge calls awaiting their output - Artifacts []Artifact // claude.ai pages it published, opened or read with the Artifact tool, first touched first (artifacts.go) - artifactCalls []artifactCall // Artifact calls awaiting their result - Spawns []SpawnCmd // claude -p commands it ran, to find the sessions they started - Launches []string // names it started with launch_session or ccs launch, oldest first: evidence for ccs reorg - Peers []PeerRef // its messages to and from other sessions, to link the two ends - outputs []replyOutput // each reply's output tokens, for the working line's count this turn - turnEnd time.Time // the last turn end the transcript records (turn_duration, stop_hook_summary, Codex's task_complete) - turnBegan time.Time // the first user line after turnEnd: when the next turn began; zero until one - turnStirred bool // a user or assistant line (or a queued prompt) came after turnEnd, in file order - Tools []ToolUse // its tool calls and turn ends, for the preview; not messages, so counts, times and search ignore them - Asks []Ask // its AskUserQuestion menus and their answers (asks.go), for read_session; not messages either - PeerNotes map[int]string // set on the copy the preview draws: each peer message's other end (peerLabels) - calls []BgTask // Bash/Agent/Monitor calls awaiting the result that says whether they went to the background - Tasks []BgTask // its background tasks (tasks.go) - Schedules []Schedule // its ScheduleWakeup and CronCreate wake-ups (schedules.go) - schedCalls []schedCall // ScheduleWakeup/CronCreate/CronDelete calls awaiting their result + firstCwd string // the folder its first user line was in + lastCwd string // the folder its latest user line was in; Cwd falls back to it when firstCwd is gone (resolveCwd) + sdkCLI bool // its first user line's entrypoint is sdk-cli (claude -p) + firstPrompt string // the first promptId seen + morePrompts bool // a second promptId: something talked to it after its first prompt + CodexExec bool // a Codex session started by codex exec + Queued []string // recent messages the session has queued (peers, ccs's socket, or typed while it's busy), for delivery status + Queue []QueuedMessage // messages still in its queue, not taken in yet (queue.go); QueuedNow is what to show + queueTaken []string // keys of queued messages a remove took out, until the copy taken in is seen (queue.go) + lastUsageID string // one reply spans several lines with the same id and usage; count it once + TailApplied bool // an unterminated last line parsed as a record, so resuming at ParsedBytes would repeat it + Pending *toolCall // the last tool call still without a result: what a waiting session asks about + PRs []string // its PRs, first touched first: Claude Code's pr-link records, and those gh pr create/merge printed (ghPRCall) + GHCalls []string // gh pr create/merge calls awaiting their output + Artifacts []Artifact // claude.ai pages it published, opened or read with the Artifact tool, first touched first (artifacts.go) + artifactCalls []artifactCall // Artifact calls awaiting their result + Spawns []SpawnCmd // claude -p commands it ran, to find the sessions they started + Launches []string // names it started with launch_session or ccs launch, oldest first: evidence for ccs reorg + Peers []PeerRef // its messages to and from other sessions, to link the two ends + outputs []replyOutput // each reply's output tokens, for the working line's count this turn + turnEnd time.Time // the last turn end the transcript records (turn_duration, stop_hook_summary, Codex's task_complete) + turnBegan time.Time // the first user line after turnEnd: when the next turn began; zero until one + turnStirred bool // a user or assistant line (or a queued prompt) came after turnEnd, in file order + Tools []ToolUse // its tool calls and turn ends, for the preview; not messages, so counts, times and search ignore them + Asks []Ask // its AskUserQuestion menus and their answers (asks.go), for read_session; not messages either + PeerNotes map[int]string // set on the copy the preview draws: each peer message's other end (peerLabels) + calls []BgTask // Bash/Agent/Monitor calls awaiting the result that says whether they went to the background + Tasks []BgTask // its background tasks (tasks.go) + Schedules []Schedule // its ScheduleWakeup and CronCreate wake-ups (schedules.go) + schedCalls []schedCall // ScheduleWakeup/CronCreate/CronDelete calls awaiting their result // ReadAt is when this copy was read from disk (the stat before the read). // Between a full scan and the live tick, the later read wins; file size @@ -155,6 +157,7 @@ type RawMessage struct { Attachment json.RawMessage `json:"attachment"` Operation string `json:"operation"` // queue-operation: enqueue, dequeue, remove Content json.RawMessage `json:"content"` // queue-operation: what was queued + Reason string `json:"reason"` // queue-operation remove: why it left (absorbed_mid_turn: taken in mid-turn) } // queuedCommand is an attachment record for a message that arrived mid-turn. @@ -601,6 +604,7 @@ func parseLine(conv *Conversation, line []byte) bool { conv.turnStirred = true // isMeta lines are harness-injected (e.g. the local-command caveat). text := extractText(raw.Message.Content) + noteUnqueued(conv, text) // a queued message taken in at a turn's start (queue.go) // "/model" logs its result as command output; a switch after the last // reply is the model the session will use next. if m := modelSwitch.FindStringSubmatch(AnsiCodes.ReplaceAllString(text, "")); m != nil { @@ -622,11 +626,15 @@ func parseLine(conv *Conversation, line []byte) bool { } case "attachment": var a queuedCommand - if json.Unmarshal(raw.Attachment, &a) != nil || a.Type != "queued_command" || a.CommandMode != "prompt" { + if json.Unmarshal(raw.Attachment, &a) != nil || a.Type != "queued_command" { break } - conv.turnStirred = true text := extractText(a.Prompt) + noteUnqueued(conv, text) // taken in mid-turn (queue.go) + if a.CommandMode != "prompt" { + break + } + conv.turnStirred = true if isChannelEvent(text) { conv.Messages = append(conv.Messages, Message{Role: "channel", Text: text, Ts: raw.Timestamp}) break @@ -636,11 +644,18 @@ func parseLine(conv *Conversation, line []byte) bool { noteReceived(conv, text) } case "queue-operation": - if text := extractText(raw.Content); raw.Operation == "enqueue" && strings.TrimSpace(text) != "" { - if len(conv.Queued) >= 20 { - conv.Queued = conv.Queued[1:] + text := extractText(raw.Content) + switch raw.Operation { + case "enqueue": + if strings.TrimSpace(text) != "" { + if len(conv.Queued) >= 20 { + conv.Queued = conv.Queued[1:] + } + conv.Queued = append(conv.Queued, CleanText(text)) // compared with what ccs sent, which is clean } - conv.Queued = append(conv.Queued, text) + noteEnqueued(conv, text, raw.Timestamp) + case "remove", "popAll", "popOne": + noteRemoved(conv, text, raw.Operation == "remove" && raw.Reason == "absorbed_mid_turn") } case "assistant": conv.turnStirred = true diff --git a/internal/tui/ingest_clean_test.go b/internal/tui/ingest_clean_test.go index 186a1a2..0e0c554 100644 --- a/internal/tui/ingest_clean_test.go +++ b/internal/tui/ingest_clean_test.go @@ -90,7 +90,8 @@ var rawOnPurpose = map[string]bool{".SessionID": true, ".FilePath": true} func assertCleanConv(t *testing.T, conv transcript.Conversation) { t.Helper() walkStrings(reflect.ValueOf(conv), "", func(path, s string) { - if rawOnPurpose[path] || strings.HasPrefix(path, ".Peers[") && (strings.HasSuffix(path, ".Key") || strings.HasSuffix(path, ".Addr")) { + if rawOnPurpose[path] || strings.HasPrefix(path, ".Peers[") && (strings.HasSuffix(path, ".Key") || strings.HasSuffix(path, ".Addr")) || + strings.HasPrefix(path, ".Queue[") && strings.HasSuffix(path, ".key") || strings.HasPrefix(path, ".queueTaken[") { // queue keys: matched, never drawn return } if path == ".SearchText" || path == ".SearchLower" { @@ -127,7 +128,11 @@ func claudeTranscript(t *testing.T) transcript.Conversation { map[string]any{"type": "tool_result", "tool_use_id": "q1", "content": "answered" + poison}}}, "toolUseResult": map[string]any{"answers": map[string]any{"pick" + poison: "a" + poison}, "annotations": map[string]any{"pick" + poison: map[string]any{"notes": "n" + poison}}}}) + jsonLine(t, map[string]any{"type": "user", "timestamp": ts, "message": map[string]any{"role": "user", "content": teammate}}) + - jsonLine(t, map[string]any{"type": "user", "timestamp": "bad" + poison, "message": map[string]any{"role": "user", "content": "late"}}) + jsonLine(t, map[string]any{"type": "user", "timestamp": "bad" + poison, "message": map[string]any{"role": "user", "content": "late"}}) + + // Messages still in its queue: one typed in its tab, one from another session. + jsonLine(t, map[string]any{"type": "queue-operation", "operation": "enqueue", "timestamp": ts, "content": "queued" + poison}) + + jsonLine(t, map[string]any{"type": "queue-operation", "operation": "enqueue", "timestamp": ts, + "content": `` + "\nwait" + poison + "\n"}) if err := os.WriteFile(path, []byte(lines), 0o600); err != nil { t.Fatal(err) } @@ -237,6 +242,27 @@ func TestUntrustedTextIsCleanedWhereItEnters(t *testing.T) { } }) + t.Run("queued messages", func(t *testing.T) { + if len(conv.QueuedNow()) != 2 { + t.Fatalf("the fixture's queue: %+v", conv.Queue) + } + m := initialModel(buildItems([]transcript.Conversation{conv}), "", nil) + m.width, m.height = 140, 60 + m.chatStatus = map[string]sessions.SessionStat{conv.SessionID: (sessions.SessionFile{Status: "busy"}).Stat()} + preview := strings.Join(m.previewLines(), "\n") + if !strings.Contains(preview, "⎿ Queued") || !strings.Contains(preview, "From peer") || !strings.Contains(preview, "wait") { + t.Fatalf("the queue isn't drawn: %q", preview) + } + if poisoned(preview) { + t.Errorf("a queued message draws the poison: %q", preview) + } + for _, q := range conv.QueuedNow() { + if poisoned(q.Plain()) { + t.Errorf("ccs sessions' queued text keeps the poison: %q", q.Plain()) + } + } + }) + t.Run("Codex rollout", func(t *testing.T) { home := t.TempDir() old := transcript.CodexHome diff --git a/internal/tui/preview.go b/internal/tui/preview.go index 73fcca1..fa290a0 100644 --- a/internal/tui/preview.go +++ b/internal/tui/preview.go @@ -149,9 +149,20 @@ func (m model) previewLines() []string { } conv := m.filtered[m.cursor].conv conv.PeerNotes = m.cachedPeerLabels(conv) // the other ends, which other sessions' transcripts show + conv.Queue = m.queuedShown(conv) // what its queue holds now, drawn at the end return cachedPreview(m.preview, conv, m.searchQuery(), m.paneWidth()-1) // the last column is the scrollbar } +// queuedShown is what conv's queue holds now: only while it runs mid-turn +// (busy, or waiting on a prompt in a turn), since an idle session takes a +// message in as it arrives and an exited one has no queue. +func (m model) queuedShown(conv transcript.Conversation) []transcript.QueuedMessage { + if st := m.chatStatus[conv.SessionID].Status; st != "busy" && st != "waiting" { + return nil + } + return conv.QueuedNow() +} + // previewDebounce is how long the selection must rest before its // conversation is built: scrolling through the list draws only each // preview's header, so a big conversation passed on the way costs nothing. @@ -188,7 +199,7 @@ func cachedPreview(c *previewCache, conv transcript.Conversation, query string, } // Preview lines depend only on the messages and tool calls, and on the // width they're wrapped to. - key := fmt.Sprintf("%s\x00%d\x00%d\x00%d\x00%s\x00%v", conv.SessionID, len(conv.Messages), len(conv.Tools), width, query, conv.PeerNotes) // %v sorts map keys + key := fmt.Sprintf("%s\x00%d\x00%d\x00%d\x00%s\x00%v\x00%v", conv.SessionID, len(conv.Messages), len(conv.Tools), width, query, conv.PeerNotes, conv.Queue) // %v sorts map keys if c.key != key { c.key = key c.lines, c.stamps = buildPreview(conv, query, width) @@ -439,10 +450,34 @@ func buildPreview(conv transcript.Conversation, query string, width int) ([]stri remaining := len(conv.Messages) - lastShown - 1 msgLines = append(msgLines, fmt.Sprintf("\033[90m ... %d more messages\033[0m", remaining)) } + if query == "" { // a search is the matches and their context, as for tools + msgLines = append(msgLines, queuedLines(conv.Queue, width)...) + } return msgLines, stamps } +// queuedLines draws the messages a busy session has queued and not taken in +// yet, as Claude Code's terminal does under its prompt: each message, then a +// dim "⎿ Queued". Claude Code adds "ctrl+enter to send now", a key only its +// own tab has. Once taken in, a message is an ordinary one above. +func queuedLines(queue []transcript.QueuedMessage, width int) []string { + var out []string + for _, q := range queue { + if from, body, ok := transcript.PeerParts(q.Text); ok && from != ccsSender { + out = append(out, "\033[36m From "+from+"\033[0m") + out = append(out, renderBody(body, "", width)...) + } else { + if ok { + q.Text = body // typed in ccs: the user's own words + } + out = append(out, userRows(markFirst(renderBody(transcript.StripImageNote(q.Text), "", width), "❯"), width)...) + } + out = append(out, "\033[90m ⎿ Queued\033[0m", "") + } + return out +} + // carryStyles makes each wrapped line self-contained: styles and a link still // open at a line's end are closed there and reopened on the next line, so an // underline or link never runs on into the rest of the screen. diff --git a/internal/tui/preview_test.go b/internal/tui/preview_test.go index da3174a..04b43df 100644 --- a/internal/tui/preview_test.go +++ b/internal/tui/preview_test.go @@ -17,6 +17,7 @@ import ( "github.com/charmbracelet/x/ansi" "github.com/agentic-utils/ccs/internal/github" + "github.com/agentic-utils/ccs/internal/sessions" "github.com/agentic-utils/ccs/internal/transcript" tea "github.com/charmbracelet/bubbletea" @@ -1241,3 +1242,50 @@ func TestArtifactsInHeaderAndLinksPopup(t *testing.T) { t.Errorf("^O lists them by title, with their address:\n%s", v) } } + +// A busy session's queued messages show at the end of its preview as Claude +// Code draws them, the text then a dim "⎿ Queued", and become an ordinary +// message once taken in. An idle session shows none. +func TestPreviewShowsQueuedMessages(t *testing.T) { + conv := transcript.Conversation{SessionID: "q1"} + for _, l := range []string{ + `{"type":"user","timestamp":"2026-11-23T10:00:00Z","message":{"role":"user","content":"tidy the docs"}}`, + `{"type":"queue-operation","operation":"enqueue","timestamp":"2026-11-23T10:00:05Z","content":"and the readme"}`, + `{"type":"queue-operation","operation":"enqueue","timestamp":"2026-11-23T10:00:06Z","content":"\nhold the release\n"}`, + } { + transcript.ParseLine(&conv, []byte(l)) + } + m := initialModel(buildItems([]transcript.Conversation{conv}), "", nil) + m.width, m.height = 120, 40 + draw := func() string { return strip2(strings.Join(m.previewLines(), "\n")) } + + m.chatStatus = map[string]sessions.SessionStat{"q1": {Status: "busy"}} + got := draw() + if !strings.Contains(got, "❯ and the readme") || !strings.Contains(got, "From planner") || strings.Count(got, "⎿ Queued") != 2 { + t.Fatalf("busy: %q", got) + } + if strings.Index(got, "tidy the docs") > strings.Index(got, "and the readme") { + t.Errorf("queued messages come after the conversation: %q", got) + } + if m.items[0].conv.Queue == nil || len(m.items[0].conv.Messages) != 1 { + t.Errorf("the queue isn't a message: %+v", m.items[0].conv.Messages) + } + + m.chatStatus["q1"] = sessions.SessionStat{Status: "idle"} + if got := draw(); strings.Contains(got, "Queued") { + t.Errorf("idle: %q", got) + } + + m.chatStatus["q1"] = sessions.SessionStat{Status: "busy"} + for _, l := range []string{ + `{"type":"queue-operation","operation":"remove","timestamp":"2026-11-23T10:00:09Z","content":"and the readme","reason":"absorbed_mid_turn"}`, + `{"type":"attachment","timestamp":"2026-11-23T10:00:05Z","attachment":{"type":"queued_command","prompt":"and the readme","commandMode":"prompt"}}`, + } { + transcript.ParseLine(&m.items[0].conv, []byte(l)) + } + m.filtered[0].conv = m.items[0].conv + got = draw() + if strings.Count(got, "⎿ Queued") != 1 || !strings.Contains(got, "❯ and the readme") || strings.Index(got, "and the readme") > strings.Index(got, "From planner") { + t.Errorf("taken in, the readme is a message above the queue: %q", got) + } +}