Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md

Large diffs are not rendered by default.

85 changes: 66 additions & 19 deletions internal/sessions/typekeys.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
101 changes: 101 additions & 0 deletions internal/sessions/typekeys_test.go
Original file line number Diff line number Diff line change
@@ -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))
}
}
10 changes: 5 additions & 5 deletions internal/transcript/transcript.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
7 changes: 4 additions & 3 deletions internal/transcript/transcript_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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":"<task-notification>x</task-notification>","commandMode":"task-notification"},"timestamp":"2026-09-30T10:02:07Z"}`,
Expand All @@ -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)
}
}

Expand Down
32 changes: 25 additions & 7 deletions internal/tui/chat.go
Original file line number Diff line number Diff line change
Expand Up @@ -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" {
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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)
}
}
Expand Down
45 changes: 44 additions & 1 deletion internal/tui/chat_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{"<cross-session-message from-name=\"x\">\n" + transcript.CcsNote + "please check the logs.\nthen fix it.\n</cross-session-message>"}
m.items[i].conv.Queued = []string{"<cross-session-message from-name=\"x\">\n" + transcript.CcsNote + "please check the logs.\nthen fix it.\n</cross-session-message>"}
}
}
m.pending[id] = "please check the logs.\nthen fix it."
Expand All @@ -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)
Expand Down
9 changes: 7 additions & 2 deletions internal/tui/ui.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down
Loading