diff --git a/AGENTS.md b/AGENTS.md index c8caa38..202671a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -185,7 +185,7 @@ Install the release locally: `brew update && brew upgrade ccs`. - `View()` / `viewScreen()` / `overlayCentre()` - `viewScreen` draws the current screen (list or usage); `View` then overlays popups (the update offer) centred on top, ANSI-aware so the screen stays visible around them. Screens never draw popups themselves, so any new screen gets them for free - `uiState` / `restore()` / `restoreEnv` - before the post-update restart, `uiState()` (screen name, search text and cursor position, selected SessionID, preview scroll) goes into `CCS_RESTORE_STATE` for the new process only; `main` reads it once, unsets it, and `restore()` puts the user back (a missing conversation is skipped). A new screen needs a case in `screenName()` and `restore()` - Commands from the message box (`run.go`: `commandLine`, `startRun`, `typeSlash`, `proc.RunShell`) - only Enter in the TUI's focused box reaches `commandLine`, so `ccs serve`, MCP and peer messages can never run or type anything. `!cmd` runs `$SHELL -lc cmd` (cmd one argument; /bin/zsh without $SHELL) in the session's cwd: Setsid, no stdin, `GIT_TERMINAL_PROMPT=0`, `runTimeout` (2m), stdout+stderr capped at `runOutputCap` (64KB, then `… cut`), and a timeout or Esc/^C kills the process group (`cmd.Cancel`), as does the shell exiting (what it put in the background goes with it). Output is cleaned by `cleanOutput`, which is `transcript.CleanText` (the one cleaner); the cap never splits a character. A run is registered in `activeRun`: ccs's exit (quit, error or an update's restart) calls `stopActiveRun`, and automatic updates wait while `runActive` (the header says `update waiting: a ! command running`). One at a time (`m.run`, `runGen` drops stale results); its box (`runLines`, the held box's frame, at most `runLimit` rows) sits above the message box with `$ cmd`, the output through `CleanText`, then `exit N · 0.3s` (red when non-zero), `timed out after 2m` or `stopped`; `running… Ns` ticks once a second only while it runs (`runTick`). PgUp/PgDn scroll it (`scrollRun`), Esc stops it, then closes it, and the activity log gets the command, folder and outcome, never the output. Once it has ended, ^S on an empty message box (`runSendable`) opens a choice in the box (`shellRun.asking`, which owns the keys: o, e, esc; any other key is ignored) to send the result to the session it ran for (`runsend.go`: `runMessage`, the first line "I ran `cmd` in : exit N" always, with o the cleaned output in a fence longer than any backtick run in it, cut to `runSendCap` (16KB) at a line, saying from what size). The run records the session's pid and process start time when it starts (`sessions.LiveStart`), and `sendRunResult` refuses unless the same process is still that session, never the current selection; `deliverRunResult` sends over its message socket (Codex: its queue) and never types, and a failure puts nothing in the box (`sendDoneMsg.keepDraft`). The activity log gets the command and outcome, never the output. `/cmd` is typed into the session's tab with Enter (`typeSlash`: `slashRefusal` on the key, `typeSlashNow` in the worker, both shared with ^X V's Remote Control), only when it's idle and has no prompt ccs holds: checked on the key, then again in the worker after `FindTerminal` and immediately before `SendKeys` (`sessions.StillTheSession`: same session, same process start; `heldFor`). Only an atomic operation on Claude Code's side could close the last gap. Also refused: isn't Codex or app-hosted, and has no control characters; a refusal is a grey note and the text stays in the box. `!!x` and `//x` send `!x` and `/x` as messages (`sendLine(draft, payload)`): the box's draft is never rewritten, so a refusal or failure gives back the escaped line. `deliverMessage` never types a message starting `/` or `!` (with no socket it's refused), since typed it would run. Stubs: `runShell`, `runTimeout` -- Message box (`chat*`, `deliverMessage()`) - when the selected conversation is live, its preview gets a status line and a one-line message box. Moving the selection (keys, wheel, click) onto a live session focuses its box, and onto anything else (no box, or one hidden behind its question) returns typing to the search (`selectionMoved`; never called for a search narrowing the list, so search typing never lands in a box); Enter or a click focuses the box, and Enter on the empty box opens the session (`focusCmd`), so with typing in the search Enter takes two steps to reach its tab; one waiting on a menu or prompt has no box, so Enter goes straight to its tab (`resumeCmd` focuses a live one); the search gets typing back only when asked: Esc in the box (the session stays selected; a further Esc walks up its parents, `parentRow`) or a click on the search row. Enter sends via `sendViaSocket` (the session file's `messagingSocketPath`: newline-delimited JSON, an `auth` line with the `sessions.PeerToken` from `..key`, then a `user` message wrapped in ``, starting with `transcript.CcsNote`, which tells the recipient it was typed by the user, not another Claude session, so it answers in its own conversation instead of messaging back; `transcript.PeerParts` strips the note for the preview); only if the socket can't be reached at all (`sessions.ErrNotConnected`) does it type into the terminal instead (`typeIntoSession`: tmux `send-keys -l`, or iTerm `write text`; control characters refused). Never both. The socket gives no acknowledgement; the recipient logs a `queue-operation` enqueue the moment it arrives (`conv.peerQueued`), then hands it to Claude at once when idle (a user line prefixed "Another Claude session sent a message:") or at its next step when busy (an `attachment` of type `queued_command`, which `transcript.ParseLine` also reads, so mid-turn messages the user types show too). `checkDelivered` calls it delivered once it's in the conversation; a socket send not enqueued within `heldTimeout` (5s) shows a hedged warning that a bypass-permissions session may be holding it. Delivery receipts (`sessions.receiptInbox()` / `sessions.serveReceipts()` / `sessions.ParseReceipt()` / `applyReceipt()`): each socket message carries `msgV:1` and `from:"uds:/ccs--inbox.sock"` (Claude Code only sends receipts to a `.sock` in the recipient's own socket folder, and checks the listener is the sending process); the session connects back with `{"type":"control","action":"peer_message_status","status":…,"orig_msg_id":…}` only when a message doesn't go straight in: held (shown as `⏸ held: approve it in `, replacing the 5s guess), then delivered, denied or expired; refused (`expired` + `status_detail:"refused"`); or dropped (`drop_reason`, `dropped_msg_ids`). `sessions.SentMsgs` maps msg_id to session; `waitReceipt` blocks, so idle frames stay still. The inbox is removed when ccs exits (`sessions.CloseInboxes`), and inboxes of exited ccs processes are reaped (`sessions.reapInboxes`). Replies and idle notices sent to the inbox are ignored. Messages from ccs or other sessions (`transcript.PeerMessage`, kept even though marked meta) show in the preview under a `From ` header. While a live session is selected, `chatTickCmd` checks its transcript and busy/idle status every `chatFastRefresh` (250ms); an idle frame stays static, and only a busy session's working line changes: `workingLine`, at the left of the status row above the box, an animated glyph (`spinnerFrames`) and `Working…` in the agent's colour, then dim `(1m 4s · ↓ 2.5k tokens)`: the time since the turn began (`TurnStart`: `statusUpdatedAt`, which stays put through a turn's steps, or Codex's task_started; but Claude Code doesn't always move it between turns, so a turn end the transcript records after it (`turn_duration`, `stop_hook_summary`) wins, and the turn began with the first user line after that end; `ccs sessions` gives a busy session the same since), and the output tokens of replies since then (`outputSince`, `conv.outputs`, finished replies only, so it runs behind Claude Code's live count). Claude Code's verb and tip aren't written anywhere ccs can read, so the word is fixed and there's no tip +- Message box (`chat*`, `deliverMessage()`) - when the selected conversation is live, its preview gets a status line and a one-line message box. Moving the selection (keys, wheel, click) onto a live session focuses its box, and onto anything else (no box, or one hidden behind its question) returns typing to the search (`selectionMoved`; never called for a search narrowing the list, so search typing never lands in a box); Enter or a click focuses the box, and Enter on the empty box opens the session (`focusCmd`), so with typing in the search Enter takes two steps to reach its tab; one waiting on a menu or prompt has no box, so Enter goes straight to its tab (`resumeCmd` focuses a live one); the search gets typing back only when asked: Esc in the box (the session stays selected; a further Esc walks up its parents, `parentRow`) or a click on the search row. Enter types it into the session's terminal first (`typeIntoSession`, `sessions.SendKeys`: tmux `send-keys -l`, or iTerm `write text … newline false`, then after `sessions.SubmitDelay` (300ms) Enter on its own, since Claude Code reads a burst of 64 bytes or more as a paste whose Enter is a newline, and the message sat in the prompt unsent; a failed Enter is `ErrEnterNotSent`, never `ErrNoTerminal`, so it isn't sent again another way) when its pid is verified, it isn't on a menu, and the text has no control character (a newline included) and doesn't start `/` or `!`; otherwise it sends via `sendViaSocket` (the session file's `messagingSocketPath`: newline-delimited JSON, an `auth` line with the `sessions.PeerToken` from `..key`, then a `user` message wrapped in ``, starting with `transcript.CcsNote`, which tells the recipient it was typed by the user, not another Claude session, so it answers in its own conversation instead of messaging back; `transcript.PeerParts` strips the note for the preview)). Never both. Neither gives an acknowledgement; a busy recipient logs a `queue-operation` enqueue the moment it arrives (`conv.Queued`, typed ones as plain text), then hands it to Claude at once when idle (a user line prefixed "Another Claude session sent a message:") or at its next step when busy (an `attachment` of type `queued_command`, which `transcript.ParseLine` also reads, so mid-turn messages the user types show too). `checkDelivered` calls it delivered once it's in the conversation; a socket send not enqueued within `heldTimeout` (5s) shows a hedged warning that a bypass-permissions session may be holding it, and a typed one (`m.typed`, `typedNote`) a red `✗ not arrived` saying it may sit unsent in the prompt. Delivery receipts (`sessions.receiptInbox()` / `sessions.serveReceipts()` / `sessions.ParseReceipt()` / `applyReceipt()`): each socket message carries `msgV:1` and `from:"uds:/ccs--inbox.sock"` (Claude Code only sends receipts to a `.sock` in the recipient's own socket folder, and checks the listener is the sending process); the session connects back with `{"type":"control","action":"peer_message_status","status":…,"orig_msg_id":…}` only when a message doesn't go straight in: held (shown as `⏸ held: approve it in `, replacing the 5s guess), then delivered, denied or expired; refused (`expired` + `status_detail:"refused"`); or dropped (`drop_reason`, `dropped_msg_ids`). `sessions.SentMsgs` maps msg_id to session; `waitReceipt` blocks, so idle frames stay still. The inbox is removed when ccs exits (`sessions.CloseInboxes`), and inboxes of exited ccs processes are reaped (`sessions.reapInboxes`). Replies and idle notices sent to the inbox are ignored. Messages from ccs or other sessions (`transcript.PeerMessage`, kept even though marked meta) show in the preview under a `From ` header. While a live session is selected, `chatTickCmd` checks its transcript and busy/idle status every `chatFastRefresh` (250ms); an idle frame stays static, and only a busy session's working line changes: `workingLine`, at the left of the status row above the box, an animated glyph (`spinnerFrames`) and `Working…` in the agent's colour, then dim `(1m 4s · ↓ 2.5k tokens)`: the time since the turn began (`TurnStart`: `statusUpdatedAt`, which stays put through a turn's steps, or Codex's task_started; but Claude Code doesn't always move it between turns, so a turn end the transcript records after it (`turn_duration`, `stop_hook_summary`) wins, and the turn began with the first user line after that end; `ccs sessions` gives a busy session the same since), and the output tokens of replies since then (`outputSince`, `conv.outputs`, finished replies only, so it runs behind Claude Code's live count). Claude Code's verb and tip aren't written anywhere ccs can read, so the word is fixed and there's no tip - `transcript.noteSent()` / `transcript.noteReceived()` / `peerEnds()` / `peerLabels()` / `sessionLinks()` - messages between sessions, both ends: a `SendMessage` call becomes a `sent` Message (`To`, `Note` its summary; after the reply's text) drawn as `To `; a cross-session message received keeps its sender's `from=` socket and `from-name`. Each is a `transcript.PeerRef` (`conv.peers`, its text's start as `transcript.peerKey`), so the other end is the session whose transcript holds the same text (`peerEnds` across all items), else the live session on its socket (`sessionAt`, the pid in `.sock`), else (received) the session titled as its from-name. A sent message found at the other end shows `✓ arrived`. The labels go into the preview through the drawn copy's `peerNotes` (part of `cachedPreview`'s key, so an arrival redraws it), worked out through `cachedPeerLabels`, again only when `peerLabelKey` (every session's id, title, peer and message counts, status name, and the live pids) changes, never per frame or scroll step. ^O lists those sessions first (`→ to` / `← from`, `sessionLink`): Enter selects it in the list (`selectSession`: clears a search hiding it, expands its folder). `lastSaid` skips sent messages, so one sent after a question doesn't hide it - `waitSignal()` / `applyStats()` / `waitingCount()` - statuses come from the live tick (`scanSessions`, one read per session file) and the fast tick, and reach `chatStatus` only through `setStat`. Claude Code can leave a session's file on `busy` after its turn ends, so `setStat` reads busy as idle (since that end) when the transcript records a turn end after the status time with no user or assistant line or queued prompt written after it (`Conversation.TurnOver`, `turnStirred`); waiting and Codex are never overridden, and the fast tick applies its transcript before its status so the end it just read counts. `ccs sessions` reads it the same way (`sessionRow`). `waiting` is Claude Code's status for a permission prompt or a question menu (`waitPrompt`, a magenta `●`); an `idle` session whose last message ends in `?` is `waitAsked` (light magenta, a guess). A session whose file is missing or unreadable keeps its last state while its pid is still the same process (`lastScan`). Nothing pops up and nothing moves: Tab goes to waiting sessions (`nextWaiting`), the header counts menus and prompts (`N waiting`, no key), the selected one's question shows in the bottom pane in place of its message box (`chatAsk`, `askLines`, `boxHidden`), a held one is answered there (held.go, menu.go) and ccs selects it when you're idle (`autoSelect`); one ccs doesn't hold is answered in its tab (Enter opens it). While something holds prompts, the pane never draws a question from the transcript (`askLines`, and the status line's "answer it in its tab") within `heldGrace` (1s) of its wait beginning (`waitSeen`, from `setStat`, which also asks for the held list at once, then every `heldQuick` while one is due, `heldDue`, `heldRetry`, whatever is selected) or of its held prompt leaving the list (`heldGone`, from `applyHeld`, also when an ask fails or the holder goes, `dropHeld`; the status still says waiting until Claude Code moves on), and, for a prompt ccs answered itself, for as long as the status still reports that same wait (`heldAnswered`, its statusUpdatedAt, from `applyHeldDone`; `setStat` drops it when the wait ends or changes; at most `heldAnsweredMax`, 30s): `heldPending`, judged by `paneNow` (the time Update last finished, so `chatRows` and `chatView` agree), with a dim "waiting on you…" status line meanwhile (`heldPendingLine`), so a held question only ever shows in the held menu, and one nothing holds shows from the transcript once the grace has passed; with no holder it shows at once. There is no ^X W overlay any more: it was removed once every answer moved into the main view (docs/design/input-prompt-overlay.md) - `autoFocusCmd()` / `applyAutoFocus()` / `userIdle` - auto-focus (^X A, off by default, saved in `settings`; the header says `auto-focus`; it also selects the waiting session in ccs's own list, `autoSelect` in held.go): from each live tick, a session that starts waiting on a menu or prompt gets its tab or pane selected (`focusSession(pid, false)`: never `activate`, so iTerm isn't pulled in front of another app). Once per wait (`focusHandled`, by statusUpdatedAt, kept across restarts in `focusRecordPath`, so a restart doesn't switch to a question again but one that came up meanwhile is switched to); questions already waiting at startup or when ^X A turns it on are switched to as well; only after `autoFocusIdle` (2s) since the last key press (`userIdle`: CoreGraphics' seconds since a key-down, read through `osascript -l JavaScript`; the mouse doesn't count, it can't answer anything and is rarely still; unknown means never), so keystrokes meant elsewhere can't answer the menu; never while ccs has the terminal's focus and its selection needs you (`selectionNeedsYou`, logged once per wait as not switching), since you may be reading its question there; and not again until the question it switched to is answered (`focusHeld`). Each step goes once per wait to the activity log (`state.LogActivity`, `~/Library/Logs/ccs/activity.log` beside the update log; `noteFocus`): waiting, you're typing, switched, couldn't find its tab, holding on another, answered. Both logs share `state.AppendLog`, which rotates at 1MB to `.1`. Tests stub `userIdle` and `autoFocusTab` diff --git a/internal/sessions/typekeys.go b/internal/sessions/typekeys.go index 9204991..7d19cd7 100644 --- a/internal/sessions/typekeys.go +++ b/internal/sessions/typekeys.go @@ -46,18 +46,26 @@ var FindTerminal = func(pid int) Terminal { return Terminal{} } -// SendKeys types text into t, pressing Enter after it when enter is set. A -// timeout may still have typed it, so it's never retried. -var SendKeys = func(t Terminal, text string, enter bool) error { - switch t.Kind { - case "tmux pane": - if _, err := proc.RunBounded(5*time.Second, nil, "tmux", "send-keys", "-t", t.Target, "-l", "--", text); err != nil || !enter { - return err - } - _, err := proc.RunBounded(5*time.Second, nil, "tmux", "send-keys", "-t", t.Target, "Enter") - return err - case "iTerm tab": - script := fmt.Sprintf(`tell application "iTerm2" +// SubmitDelay is how long SendKeys waits between the text and its Enter. +// Claude Code reads a burst of 64 bytes or more as a paste, and a paste's +// Enter is a newline: typed with the text in one write, a message of 63 +// characters or more sat in the prompt unsent (iTerm's write text sends the +// text and its \r in one write). Codex's paste-burst detection does the same. +// Sent apart, the Enter arrives as a key of its own and submits. A var for +// tests. +var SubmitDelay = 300 * time.Millisecond + +// runKeys runs one terminal command for SendKeys; a var so tests see the +// sequence without a terminal. +var runKeys = func(name string, args ...string) ([]byte, error) { + return proc.RunBounded(5*time.Second, nil, name, args...) +} + +// itermWrite is the AppleScript that writes text to the iTerm session on tty, +// with a newline after it when newline is set; it returns "typed" if it found +// the session. +func itermWrite(tty, text string, newline bool) string { + return fmt.Sprintf(`tell application "iTerm2" repeat with w in windows repeat with t in tabs of w repeat with s in sessions of t @@ -68,17 +76,56 @@ var SendKeys = func(t Terminal, text string, enter bool) error { end repeat end repeat end repeat -end tell`, t.Target, text, enter) - out, err := proc.RunBounded(5*time.Second, nil, "osascript", "-e", script) - if err != nil { +end tell`, tty, text, newline) +} + +// ErrEnterNotSent: the text was typed but its Enter wasn't, so it may sit in +// the prompt. Not ErrNoTerminal: the text went in, so nothing may send it +// another way. +var ErrEnterNotSent = errors.New("typed, but Enter couldn't be pressed: it may be waiting in the prompt") + +// SendKeys types text into t, then, when enter is set, waits SubmitDelay and +// presses Enter on its own (see SubmitDelay). A timeout may still have typed +// it, so it's never retried. +var SendKeys = func(t Terminal, text string, enter bool) error { + var typeText, pressEnter func() error + switch t.Kind { + case "tmux pane": + typeText = func() error { + _, err := runKeys("tmux", "send-keys", "-t", t.Target, "-l", "--", text) + return err + } + pressEnter = func() error { + _, err := runKeys("tmux", "send-keys", "-t", t.Target, "Enter") return err } - if strings.TrimSpace(string(out)) != "typed" { - return ErrNoTerminal + case "iTerm tab": + write := func(s string, newline bool) error { + out, err := runKeys("osascript", "-e", itermWrite(t.Target, s, newline)) + if err != nil { + return err + } + if strings.TrimSpace(string(out)) != "typed" { + return ErrNoTerminal + } + return nil + } + typeText = func() error { return write(text, false) } + pressEnter = func() error { return write("", true) } // write text "" sends \r alone + default: + return ErrNoTerminal + } + if err := typeText(); err != nil || !enter { + return err + } + time.Sleep(SubmitDelay) + if err := pressEnter(); err != nil { + if errors.Is(err, proc.ErrTimedOut) { + return err } - return nil + return fmt.Errorf("%w (%v)", ErrEnterNotSent, err) } - return ErrNoTerminal + return nil } // TypeKeys types text into the terminal running pid (FindTerminal, then diff --git a/internal/sessions/typekeys_test.go b/internal/sessions/typekeys_test.go new file mode 100644 index 0000000..6f73c32 --- /dev/null +++ b/internal/sessions/typekeys_test.go @@ -0,0 +1,101 @@ +package sessions + +import ( + "errors" + "strings" + "testing" + "time" +) + +type keyCall struct { + at time.Time + args []string +} + +// stubKeys records every terminal command SendKeys runs; fail, when set, +// answers the n-th call (from 1) with an error. +func stubKeys(t *testing.T, out string, fail int) *[]keyCall { + t.Helper() + var calls []keyCall + old, oldDelay := runKeys, SubmitDelay + runKeys = func(name string, args ...string) ([]byte, error) { + calls = append(calls, keyCall{time.Now(), append([]string{name}, args...)}) + if len(calls) == fail { + return nil, errors.New("boom") + } + return []byte(out), nil + } + SubmitDelay = 20 * time.Millisecond + t.Cleanup(func() { runKeys, SubmitDelay = old, oldDelay }) + return &calls +} + +// The text and its Enter go separately, SubmitDelay apart: in one burst of +// 64 bytes or more Claude Code reads the Enter as part of a paste, a newline, +// and the message sits in the prompt unsent. +func TestSendKeysPressesEnterApart(t *testing.T) { + text := strings.Repeat("long message ", 8) + t.Run("tmux", func(t *testing.T) { + calls := stubKeys(t, "", 0) + if err := SendKeys(Terminal{"tmux pane", "%3"}, text, true); err != nil { + t.Fatal(err) + } + c := *calls + if len(c) != 2 { + t.Fatalf("want text then Enter, got %v", c) + } + if got := strings.Join(c[0].args, " "); got != "tmux send-keys -t %3 -l -- "+text { + t.Errorf("text call = %q", got) + } + if got := strings.Join(c[1].args, " "); got != "tmux send-keys -t %3 Enter" { + t.Errorf("Enter call = %q", got) + } + if gap := c[1].at.Sub(c[0].at); gap < SubmitDelay { + t.Errorf("Enter came %v after the text, want at least %v", gap, SubmitDelay) + } + }) + t.Run("iTerm", func(t *testing.T) { + calls := stubKeys(t, "typed\n", 0) + if err := SendKeys(Terminal{"iTerm tab", "/dev/ttys009"}, text, true); err != nil { + t.Fatal(err) + } + c := *calls + if len(c) != 2 { + t.Fatalf("want text then Enter, got %d calls", len(c)) + } + first, second := c[0].args[2], c[1].args[2] + if !strings.Contains(first, "write text \""+text+"\" newline false") { + t.Errorf("the text should go without a newline:\n%s", first) + } + if !strings.Contains(second, `write text "" newline true`) { + t.Errorf("Enter should go on its own:\n%s", second) + } + if c[1].at.Sub(c[0].at) < SubmitDelay { + t.Error("Enter came too soon after the text") + } + }) + t.Run("no Enter", func(t *testing.T) { + calls := stubKeys(t, "", 0) + if err := SendKeys(Terminal{"tmux pane", "%3"}, "2", false); err != nil || len(*calls) != 1 { + t.Errorf("a menu digit is one call with no Enter: err=%v calls=%d", err, len(*calls)) + } + }) +} + +// Once the text is in, a failed Enter must not read as "no terminal", which +// would let the caller send it again over the socket: a second copy. +func TestSendKeysEnterFailureIsNotNoTerminal(t *testing.T) { + stubKeys(t, "", 2) + err := SendKeys(Terminal{"tmux pane", "%3"}, "hello", true) + if !errors.Is(err, ErrEnterNotSent) || errors.Is(err, ErrNoTerminal) { + t.Errorf("err = %v, want ErrEnterNotSent and not ErrNoTerminal", err) + } + stubKeys(t, "", 1) + if err := SendKeys(Terminal{"tmux pane", "%3"}, "hello", true); err == nil || errors.Is(err, ErrEnterNotSent) { + t.Errorf("a failed text call is a plain failure, got %v", err) + } + calls := stubKeys(t, "not found", 0) + if err := SendKeys(Terminal{"iTerm tab", "/dev/ttys009"}, "hello", true); !errors.Is(err, ErrNoTerminal) || len(*calls) != 1 { + t.Errorf("no iTerm session: ErrNoTerminal before any Enter, got %v after %d calls", err, len(*calls)) + } +} diff --git a/internal/transcript/transcript.go b/internal/transcript/transcript.go index ed89f6a..cc2bb97 100644 --- a/internal/transcript/transcript.go +++ b/internal/transcript/transcript.go @@ -85,7 +85,7 @@ type Conversation struct { 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 - PeerQueued []string // recent messages from other sessions/ccs the session has queued, for delivery status + 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 @@ -636,11 +636,11 @@ func parseLine(conv *Conversation, line []byte) bool { noteReceived(conv, text) } case "queue-operation": - if text := extractText(raw.Content); raw.Operation == "enqueue" && PeerMessage.MatchString(text) { - if len(conv.PeerQueued) >= 20 { - conv.PeerQueued = conv.PeerQueued[1:] + if text := extractText(raw.Content); raw.Operation == "enqueue" && strings.TrimSpace(text) != "" { + if len(conv.Queued) >= 20 { + conv.Queued = conv.Queued[1:] } - conv.PeerQueued = append(conv.PeerQueued, text) + conv.Queued = append(conv.Queued, text) } case "assistant": conv.turnStirred = true diff --git a/internal/transcript/transcript_test.go b/internal/transcript/transcript_test.go index 3162707..ef07b54 100644 --- a/internal/transcript/transcript_test.go +++ b/internal/transcript/transcript_test.go @@ -786,7 +786,8 @@ func TestMidTurnAndPrefixedPeerMessagesParsed(t *testing.T) { // busy: queued, then attached mid-turn `{"type":"queue-operation","operation":"enqueue","content":` + j(strings.Replace(wrap, "check CI", "and the logs", 1)) + `,"timestamp":"2026-09-30T10:02:00Z"}`, `{"type":"attachment","attachment":{"type":"queued_command","prompt":` + j(strings.Replace(wrap, "check CI", "and the logs", 1)) + `,"commandMode":"prompt","isMeta":true},"timestamp":"2026-09-30T10:02:05Z"}`, - // the user typing mid-turn + // the user typing mid-turn: queued at once as plain text, attached later + `{"type":"queue-operation","operation":"enqueue","content":"also bump node","timestamp":"2026-09-30T10:02:03Z"}`, `{"type":"attachment","attachment":{"type":"queued_command","prompt":"also bump node","commandMode":"prompt"},"timestamp":"2026-09-30T10:02:06Z"}`, // other attachments are ignored `{"type":"attachment","attachment":{"type":"queued_command","prompt":"x","commandMode":"task-notification"},"timestamp":"2026-09-30T10:02:07Z"}`, @@ -805,8 +806,8 @@ func TestMidTurnAndPrefixedPeerMessagesParsed(t *testing.T) { if !reflect.DeepEqual(got, want) { t.Errorf("messages = %q, want %q", got, want) } - if len(c.PeerQueued) != 1 { - t.Errorf("the enqueue should be recorded, got %d", len(c.PeerQueued)) + if len(c.Queued) != 2 || c.Queued[1] != "also bump node" { + t.Errorf("both enqueues (a peer's and one typed) should be recorded, got %q", c.Queued) } } diff --git a/internal/tui/chat.go b/internal/tui/chat.go index 3b18c59..8e8136f 100644 --- a/internal/tui/chat.go +++ b/internal/tui/chat.go @@ -438,6 +438,9 @@ func (m model) chatBox(conv transcript.Conversation, in textinput.Model, focus b left = "\033[90m sending: " + chatSnippet(m.pending[id], width-40) + "\033[0m" case m.pending[id] != "" && m.held[id]: left = "\033[33m ⏸ held: approve it in " + name + " · " + chatSnippet(m.pending[id], width-50-len(name)) + "\033[0m" + case m.pending[id] != "" && m.typed[id] && !m.sentAt[id].IsZero() && time.Since(m.sentAt[id]) > heldTimeout: + why := " · typed, but not in its conversation: it may be sitting unsent in its prompt, press Enter in its tab" + left = "\033[31m ✗ not arrived: " + chatSnippet(m.pending[id], width-20-len(why)) + why + "\033[0m" case m.pending[id] != "" && !m.sentAt[id].IsZero() && time.Since(m.sentAt[id]) > heldTimeout: why := " · if it runs with bypass permissions, approve it in that session" if m.chatStatus[id].Status == "waiting" { @@ -651,12 +654,18 @@ func sendViaSocket(path, token, text string) (string, error) { func waitReceipt() tea.Msg { return <-sessions.ReceiptsCh } // typeIntoSession types text into the terminal running pid and presses -// Enter: its tmux pane, else its iTerm tab. where names what it used ("" if -// neither found it). A timeout may still have typed it, so it's not retried. +// Enter on its own a moment later (sessions.SubmitDelay): its tmux pane, else +// its iTerm tab. where names what it used ("" if neither found it). A timeout +// may still have typed it, so it's not retried. Typing gives no receipt, so +// checkDelivered watches the transcript and the status line says when a typed +// message hasn't arrived. func typeIntoSession(pid int, text string) (where string, err error) { return typeKeys(pid, text, true) } +// typedNote: a send's note says the message was typed into its terminal. +func typedNote(note string) bool { return strings.HasPrefix(note, "✓ Typed into ") } + // typeKeys is typeIntoSession with Enter optional: a digit alone picks a // question menu's option. func typeKeys(pid int, text string, enter bool) (where string, err error) { @@ -684,16 +693,25 @@ func (m *model) checkDelivered(id string) { delete(m.pending, id) delete(m.sentAt, id) delete(m.held, id) - if strings.Contains(m.sendNote[id], "socket") { + switch { + case m.typed[id]: + m.sendNote[id] = "✓ Delivered to " + m.sessionName(item.conv) + " (typed, as you)" + case strings.Contains(m.sendNote[id], "socket"): m.sendNote[id] = "✓ Delivered to " + m.sessionName(item.conv) + " (as a message from ccs)" } + delete(m.typed, id) return } } - // Claude Code logs a socket message as queued the moment it arrives, - // then hands it to Claude at the next step (or at once when idle). - for _, q := range item.conv.PeerQueued { - if _, b, ok := transcript.PeerParts(q); ok && strings.TrimSpace(b) == text { + // Claude Code logs a message as queued the moment it arrives while + // it's busy (over the socket, or typed and submitted), then hands it + // to Claude at the next step. + for _, q := range item.conv.Queued { + body := q + if _, b, ok := transcript.PeerParts(q); ok { + body = b + } + if strings.TrimSpace(transcript.StripImageNote(body)) == text { delete(m.sentAt, id) } } diff --git a/internal/tui/chat_test.go b/internal/tui/chat_test.go index 611256f..e0b3293 100644 --- a/internal/tui/chat_test.go +++ b/internal/tui/chat_test.go @@ -544,7 +544,7 @@ func TestChatPendingLine(t *testing.T) { } for i := range m.items { if m.items[i].conv.SessionID == id { - m.items[i].conv.PeerQueued = []string{"\n" + transcript.CcsNote + "please check the logs.\nthen fix it.\n"} + m.items[i].conv.Queued = []string{"\n" + transcript.CcsNote + "please check the logs.\nthen fix it.\n"} } } m.pending[id] = "please check the logs.\nthen fix it." @@ -554,6 +554,49 @@ func TestChatPendingLine(t *testing.T) { } } +// A typed message gives no receipt: ccs watches the transcript, says plainly +// when it hasn't arrived (sitting unsent in the prompt), and counts a plain +// enqueue (typed while busy) or a user line as arrival. +func TestTypedMessageDelivery(t *testing.T) { + m := chatModel(t) + m, _ = key(m, tea.KeyMsg{Type: tea.KeyDown}) + id := m.filtered[m.cursor].conv.SessionID + text := "a message long enough that one burst with its Enter reads as a paste" + m.pending = map[string]string{id: text} + mm, _ := m.Update(sendDoneMsg{id: id, note: "✓ Typed into x's iTerm tab (as you)"}) + m = mm.(model) + if !m.typed[id] || m.sentAt[id].IsZero() { + t.Fatalf("a typed send should be tracked until it shows up: typed=%v sentAt=%v", m.typed[id], m.sentAt[id]) + } + m.sentAt[id] = time.Now().Add(-2 * heldTimeout) + if v := strip2(m.View()); !strings.Contains(v, "not arrived") || strings.Contains(v, "not picked up yet") { + t.Errorf("a typed message missing from the transcript should say it may sit in the prompt:\n%s", v) + } + idx := -1 + for i := range m.items { + if m.items[i].conv.SessionID == id { + idx = i + } + } + m.items[idx].conv.Queued = []string{text} + m.checkDelivered(id) + if v := strip2(m.View()); strings.Contains(v, "not arrived") { + t.Errorf("queued while busy is arrived:\n%s", v) + } + m.items[idx].conv.Messages = append(m.items[idx].conv.Messages, transcript.Message{Role: "user", Text: text}) + m.checkDelivered(id) + if m.pending[id] != "" || m.typed[id] || !strings.Contains(m.sendNote[id], "Delivered") { + t.Errorf("a user line should settle it as delivered: pending=%q note=%q", m.pending[id], m.sendNote[id]) + } + // A socket send keeps its own wording. + m.pending[id] = "other" + mm, _ = m.Update(sendDoneMsg{id: id, note: "✓ Sent to x via its message socket (as a message from ccs)"}) + m = mm.(model) + if m.typed[id] { + t.Error("a socket send isn't typed") + } +} + func TestDeliveryReceipts(t *testing.T) { defer sessions.CloseInboxes() m := chatModel(t) diff --git a/internal/tui/ui.go b/internal/tui/ui.go index 78de0b0..317e09d 100644 --- a/internal/tui/ui.go +++ b/internal/tui/ui.go @@ -187,7 +187,8 @@ type model struct { chatStatus map[string]sessions.SessionStat // every live session's last known status (set only by setStat; applyStats drops sessions that are gone) pending map[string]string // text sent but not yet seen in the transcript, by SessionID sendNote map[string]string // outcome of the last send, by SessionID - sentAt map[string]time.Time // when a socket send finished, by SessionID, until the session queues it + sentAt map[string]time.Time // when a socket or typed send finished, by SessionID, until the session queues it + typed map[string]bool // the pending message was typed into its terminal, not sent over the socket held map[string]bool // a receipt said the session is holding the message for approval sending bool run *shellRun // the last ! command run from the message box (run.go) @@ -1878,11 +1879,15 @@ func (m model) update(msg tea.Msg) (tea.Model, tea.Cmd) { if errors.Is(msg.err, sessions.ErrUnsent) && !msg.keepDraft { m.sendNote[msg.id] += " · " + m.giveBack(msg.id, msg.text) } - } else if strings.Contains(msg.note, "socket") { + } else if typed := typedNote(msg.note); typed || strings.Contains(msg.note, "socket") { if m.sentAt == nil { m.sentAt = make(map[string]time.Time) } + if m.typed == nil { + m.typed = make(map[string]bool) + } m.sentAt[msg.id] = time.Now() + m.typed[msg.id] = typed } m.checkDelivered(msg.id) return m, nil