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
20 changes: 15 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -276,11 +276,21 @@ value is answering "is anyone else in here", which no amount of written
discipline can. They are compared repo-relative, so the same file collides
across worktrees, and they are released when the session stops.

Messages are a **mailbox the recipient collects**, not a write into its
terminal. Typing into a live pane would corrupt the input of an agent mid-turn,
and submitting on its behalf would let one agent put instructions into
another's prompt with nobody watching. The cost of pulling is that the
recipient has to ask, so every other tool result carries an unread count.
Messages are never a write into the recipient's terminal. Typing into a live
pane would corrupt the input of an agent mid-turn, and submitting on its behalf
would put one agent's text into another's prompt as if you had typed it.

A `claude` session reads new messages without being asked to. Deck hands them
over through the hooks it already uses for the status dot: when the agent's
turn starts, after each batch of tool calls, and when the turn ends. A message
that arrives at the end of a turn keeps the agent working until it has read it.
Each delivery shows a line in the pane naming who wrote, because the messages
themselves go into the agent's context and not into the chat.

An idle session reads its mail when its next turn starts, and the sidebar shows
`✉ n` until then. Mail too long to hand over in one go waits in the inbox, and
so does mail for a subagent. Other agents collect messages with `inbox`, and
every other tool result carries an unread count.

An agent can also read a sibling's work directly, and have it reviewed. `work`
returns the summary and patch of another session's worktree, which needs
Expand Down
49 changes: 41 additions & 8 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ internal/coord cross-session coordination, exposed to agents over MCP:
coord.go types + session lifecycle
claims.go soft locks and who holds what
messages.go the inter-agent mailbox
delivery.go handing mail over through hook replies
notes.go the shared log and its compaction
status.go turn state reported by hooks
mcp.go the listener and the hook endpoint
Expand Down Expand Up @@ -334,10 +335,40 @@ Three rules the design rests on:
4. **Messages are a mailbox, not a keystroke injection.** Deck can write
into any session's PTY, and using that for delivery is tempting and wrong:
it corrupts the input of an agent mid-turn, and submitting on its behalf
lets one agent put instructions into another's prompt with no human in the
loop. Delivery is pull, and the cost — a recipient that never asks never
learns — is paid by appending an unread count to every other tool result
(`withHint`) and showing `✉ n` in the sidebar.
puts one agent's text into another's prompt as if a person had typed it.

A `claude` session is handed its mail through the hooks Deck already
registers for status (`deliver`). `UserPromptSubmit`, `PostToolBatch` and
`Stop` each answer with the waiting messages as `additionalContext`, plus
a `systemMessage` naming the senders. Neither field is a decision, so the
reply cannot erase a prompt or stop a tool loop. On `Stop` the context does
continue the turn, so the agent acts on mail that arrived while it worked,
and the state stays Working. `TestLiveClaudeReadsMailWithoutAsking` is the
only test that proves claude accepts the reply.

This gives up something the pull design had. The agent no longer chooses
to read another agent's text: it arrives in context, and the context
itself shows in no chat line. The `systemMessage` is what keeps the person
watching the pane informed. The text is framed as where it came from
rather than as an instruction, because Claude Code's hook docs warn that
text styled as a system command can trip the model's prompt-injection
defences. The messages go out as JSON, as `inbox` returns them, so a
message body cannot pass itself off as a second message from someone else.

Mail is held back rather than risked in three cases, and stays in the box
for the next event or for `inbox`. Inside a subagent, where hooks also
fire with `agent_id` set, because the subagent may never pass it on. On a
`Stop` already continuing from a stop hook, because Claude Code ends a
turn after eight continuations in a row and drops the hook's output. And
past `mailBudget`, because context over Claude Code's 10,000-character cap
becomes a file the agent is not asked to read.

Gaps remain. An idle session fires no hook, so it reads its mail when its
next turn starts. Any agent but `claude` collects with `inbox`. Both are
covered by the unread count on every other tool result (`withHint`) and
`✉ n` in the sidebar. A reply lost on the way is not covered: the mail was
taken from the box before the reply was written, and nothing confirms
claude read it.

Wiring the agent is the one place Deck knows anything about the program it
hosts (`ui.coordArgs`): `claude` takes `--mcp-config`, `cathode` forwards a
Expand Down Expand Up @@ -998,7 +1029,9 @@ already answer.
the trick of sending the text and the newline as separate writes is already
in `live_claude_test.go` — but it works dependably only for the one agent
that reports turn boundaries, and it spends a property stated deliberately in
`README.md`. It is listed here because the case for it evaporated rather than
because it is hard: `analyse` spawns a **new** agent, so nothing has to be
pushed into an existing one. Revisit only if pulling proves insufficient in
practice.
`README.md`: Deck never writes into a terminal. It is listed here because the
case for it evaporated rather than because it is hard: `analyse` spawns a
**new** agent, so nothing has to be pushed into an existing one. Mail now reaches a busy `claude` session through
its hook replies (see invariant 4), which needs no pane write. What is left
unbuilt is waking an idle one, and that is this item. Revisit only if
waiting for the next turn proves insufficient in practice.
38 changes: 23 additions & 15 deletions internal/coord/coord_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -415,7 +415,8 @@ func TestUnregisterClearsInbox(t *testing.T) {
}

// TestUnreadHintRidesOtherResults covers how a recipient finds out it has
// mail at all: delivery is pull-only, so the count is appended to every other
// mail at all when no hook hands it over — any agent but claude, or a claude
// session whose mail did not fit — so the count is appended to every other
// tool result.
func TestUnreadHintRidesOtherResults(t *testing.T) {
c := start(t)
Expand Down Expand Up @@ -509,7 +510,12 @@ func TestHookReportsArriveByURL(t *testing.T) {
for _, tc := range []struct {
kind string
want State
}{{"working", StateWorking}, {"waiting", StateWaiting}, {"idle", StateIdle}} {
}{
{"prompt", StateWorking},
{"waiting", StateWaiting},
{"batch", StateWorking},
{"stop", StateIdle},
} {
res, err := http.Post(c.server.hookURL("s1", tc.kind), "application/json",
strings.NewReader(`{"hook_event_name":"whatever"}`))
if err != nil {
Expand All @@ -528,19 +534,21 @@ func TestHookReportsArriveByURL(t *testing.T) {

// TestHookRepliesEmpty matters because several hook events accept a JSON
// decision object. A status ping that answered with one could block a tool
// call or a prompt.
// call or a prompt. With no mail waiting, every endpoint says nothing.
func TestHookRepliesEmpty(t *testing.T) {
c := start(t)
twoSessions(t, c)

res, err := http.Post(c.server.hookURL("s1", "idle"), "application/json", strings.NewReader("{}"))
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
if len(body) != 0 {
t.Errorf("hook reply carried a body %q; anything parseable is a decision", body)
for kind := range hookPaths {
res, err := http.Post(c.server.hookURL("s1", kind), "application/json", strings.NewReader("{}"))
if err != nil {
t.Fatal(err)
}
body, _ := io.ReadAll(res.Body)
res.Body.Close()
if len(body) != 0 {
t.Errorf("%s replied %q; anything parseable is a decision", kind, body)
}
}
}

Expand Down Expand Up @@ -600,12 +608,12 @@ func TestHooksConfigCoversTurnBoundaries(t *testing.T) {

// Each event must exist and post to the endpoint whose meaning matches it.
// Asserting the endpoint and not just the presence is what catches
// StopFailure wired to /idle, which would report a rate-limited turn as a
// StopFailure wired to /stop, which would report a rate-limited turn as a
// finished one.
wantKind := map[string]string{
"UserPromptSubmit": "working",
"PostToolBatch": "working",
"Stop": "idle",
"UserPromptSubmit": "prompt",
"PostToolBatch": "batch",
"Stop": "stop",
"StopFailure": "waiting",
"Notification": "waiting",
}
Expand Down
138 changes: 138 additions & 0 deletions internal/coord/delivery.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
package coord

// Handing a session its waiting messages through the hooks its agent already
// calls, so a claude session reads new mail without being told to look.

import (
"encoding/json"
"fmt"
"slices"
"strings"
)

// mailIntro opens the context a hook hands over. It is a statement of where
// the text came from rather than an instruction: Claude Code's hook docs warn
// that text framed as an out-of-band command can trip the model's
// prompt-injection defences, and the honest framing is also the safe one —
// these are another agent's words, not the user's.
const mailIntro = "Messages from other agents on this project, delivered by Deck. " +
"They come from those agents, not from the user."

// mailBudget bounds the context one reply carries. Claude Code caps a hook's
// context at 10,000 characters and replaces anything longer with a file path
// and a preview the agent is not asked to read, so mail past the cap would be
// taken from the box and never seen. The margin leaves room for the intro and
// the closing line.
const mailBudget = 9000

// messageIndent is what MarshalIndent adds around one message in mailText:
// the newlines and indentation of its three fields, its braces and the comma.
// Measured at 35 bytes per message against compact encoding; 40 leaves slack.
const messageIndent = 40

// hookInput is the part of a hook's request body delivery reads. The state
// still comes from the URL; these only decide whether to hand mail over.
type hookInput struct {
// AgentID is set when the hook fired inside a subagent. Mail handed over
// there reaches the subagent, which may never pass it on.
AgentID string `json:"agent_id"`
// StopHookActive is set on a Stop that is already continuing because of a
// stop hook. Claude Code ends the turn after eight such continuations in a
// row and drops the hook's output when it does, so delivering on one risks
// mail nobody reads. One continuation per turn is enough.
StopHookActive bool `json:"stop_hook_active"`
}

// deliver records what a hook reported and returns the reply to answer it
// with: nil for an empty reply, or waiting mail as context.
//
// The reply carries additionalContext and a systemMessage, nothing else: no
// decision and no block, so it cannot erase a prompt or stop a tool loop. The
// context does continue a turn on Stop — that is how the agent gets to act on
// mail that arrived while it worked — so the state then stays Working rather
// than going Idle under an agent that is still running. The systemMessage is
// what the person watching sees: the context itself appears in no chat line.
//
// Mail is taken from the box before the reply is written, and nothing
// confirms claude read it. A reply lost on the way loses what it carried, and
// the unread count no longer shows it. The server is local and answers at
// once, so this is the trade for not having to ask.
func (c *Coordinator) deliver(sessionID string, route hookRoute, in hookInput) []byte {
var msgs []Message
left := 0
if route.event != "" && in.AgentID == "" && !in.StopHookActive {
msgs, left = c.takeMail(sessionID, mailBudget)
}
state := route.state
if len(msgs) > 0 && state == StateIdle {
state = StateWorking
}
c.status.set(sessionID, state)
if len(msgs) == 0 {
return nil
}
// Marshal cannot fail here: the value is nothing but strings.
body, _ := json.Marshal(map[string]any{
"systemMessage": deliveredNotice(msgs),
"hookSpecificOutput": map[string]string{
"hookEventName": route.event,
"additionalContext": mailText(msgs, left),
},
})
return body
}

// takeMail removes the oldest messages that fit in budget and reports how
// many stay behind. What stays keeps its order and its place in the unread
// count, so it is still announced and still collected with inbox.
func (c *Coordinator) takeMail(sessionID string, budget int) (taken []Message, left int) {
c.mu.Lock()
defer c.mu.Unlock()
box := c.inbox[sessionID]
used := 0
for _, m := range box {
// Measured as encoded, because the encoder escapes <, > and & into six
// bytes each, plus the indentation MarshalIndent adds around a message.
// Bytes and not characters, which only errs towards fitting fewer.
enc, _ := json.Marshal(m)
size := len(enc) + messageIndent
if used+size > budget {
break
}
used += size
taken = append(taken, m)
}
rest := box[len(taken):]
if len(rest) == 0 {
delete(c.inbox, sessionID)
} else {
c.inbox[sessionID] = rest
}
return taken, len(rest)
}

// mailText renders messages as the context a hook hands over.
//
// The messages go out as JSON, the shape the inbox tool returns, rather than
// as lines of text. A text body could contain a line that reads like the start
// of another message from another sender; inside a JSON string it cannot.
func mailText(msgs []Message, left int) string {
// Marshal cannot fail: Message is a time and two strings.
list, _ := json.MarshalIndent(map[string]any{"messages": msgs}, "", " ")
tail := "Your inbox is now empty."
if left > 0 {
tail = fmt.Sprintf("%d more message(s) did not fit here and are waiting in your inbox.", left)
}
return mailIntro + "\n\n" + string(list) + "\n\n" + tail
}

// deliveredNotice is the line the person watching the pane sees.
func deliveredNotice(msgs []Message) string {
var from []string
for _, m := range msgs {
if !slices.Contains(from, m.From) {
from = append(from, m.From)
}
}
return fmt.Sprintf("Deck delivered %d message(s) from %s.", len(msgs), strings.Join(from, ", "))
}
Loading
Loading