oficina / equipo Public

Turn batching: a batched turn names each message apart, with its files

The instance already batched: messages sent while a turn runs join one
queued turn, and when that turn ends one next turn takes them all, in
the same transaction (since 64cd2ce, thin v1 spec section 2). What was
missing is that the coordinator could not tell them apart: Text was the
words joined by blank lines, and the turn's files were one list.

- dispatch writes Text with turnText. One message is unchanged. Several
  get a short Equipo line, then "Message i of n" with the names of the
  files each carried, oldest first. PersonText, Attachments and the
  frame shape are unchanged, so every protocol (old runners too) reads
  the same frame. No wire, fixture or migration change.
- sync starts a queued turn left behind with nothing in flight, once
  (dispatchNext does nothing while a turn is in flight).
- fakeclaude reads "Message i of n" blocks and says what it saw.
- Contracts: the crash between turns (a trigger aborts the next turn's
  frame, then a restart), the stranded recovery, failed, cancelled,
  interrupted and retried turns, a cancelled batch, and the note
  clearing for all bubbles together. Design note in
  docs/superpowers/specs/2026-11-11-equipo-turn-batching.md.
- Budgets: internal/headless tests 8475, internal/thintest tests 13325.

Failing first, on main 03f8a91 with the new test and fake:

    batching_test.go:69: spend batched: turn t_tczxomy7soezfzy5a7kfjgdqad, 1 usage rows, 102 input tokens, 0 cached
    batching_test.go:80: turn input lacks "Message 1 of 3:\nalpha first" in order:
        alpha first

        bravo second

        charlie third
--- FAIL: TestHeadlessTurnBatching (9.64s)
FAIL	amadan.net/oficina/equipo/internal/headless	9.813s

With the assertions on input logged instead, main's fake coordinator
answered "You sent 4 messages." for the three: it took the attachment
note for a fourth.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev fd22d42ac9ba436083c476a1383553913ce20a28 parent 03f8a91
9 files changed, +669 −15
  • .rastrillo/budgets.txt +2 −2
  • docs/superpowers/specs/2026-11-11-equipo-turn-batching.md +111 −0
  • internal/equipo/chat/attachments.go +9 −6
  • internal/equipo/chat/runner.go +5 −1
  • internal/equipo/chat/store.go +34 −3
  • internal/fakeclaude/fake.go +34 −1
  • internal/headless/batching_test.go +145 −0
  • internal/thintest/batching_contract_test.go +327 −0
  • internal/thintest/instance_contract_test.go +2 −2
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index dd905800..8cd1a464 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -61,6 +61,6 @@ perf GET /conversation/attachments/{id} skip Composer attachments: the bytes of
perf GET /conversation/attachments/{id}/preview skip Composer attachments: an image thumbnail inside the conversation; a file, not a screen.
perf GET /api/v1/runners skip Mac runners person API: bearer-only JSON for devices; the browser shows runners in the Team section.
time cmd/equipo-runner 60s Mac runners slice B: TestReleaseRunnerHasNoFakeWorker builds the release runner exactly as make release-runner does and the thin package under the testbuild tag (measured 11.9s locally with a warm cache).
-size internal/headless - 8400 Merge authority extends 4c_checks_card to end in Equipo's own merge, measured by the real runner, with its receipt (about 30 lines); measured 8330. Claude's sign-in by a link adds its end-to-end, contained-launch and real runner kill tests (signin_test.go, signin_contained_test.go, about 400 lines); measured 8090.
-size internal/thintest - 13070 Merge authority merged onto Machines in Settings, with the re-run ruling's cases and stale thinking lines: measured 12998. Merge authority thin v1 adds its contracts (mergeauth_contract_test.go, about 650 lines) the protocol-aware rigs and the Mac re-run contract (macrecheck_mergeauth_contract_test.go) and the review fixes' contracts; measured 12535 with main merged. Mac recheck adds its enrolment, skip and outcome contracts (macrecheck_contract_test.go, about 210 lines); measured 11537. Machines in Settings adds its fixture, page and browser tests (machines_fixture_test.go, machines_pages_test.go, machines_browser_test.go, about 160 lines); measured 11759. Mac recheck adds its enrolment, skip and outcome contracts (macrecheck_contract_test.go, about 210 lines); measured 11537. Stale thinking lines merged onto Machines in Settings: measured 11967. Machines in Settings adds its fixture, page and browser tests (machines_fixture_test.go, machines_pages_test.go, machines_browser_test.go, about 160 lines); measured 11759. Stale thinking lines add their browser drive (stale_thinking_browser_test.go, about 200 lines) and the queued test now checks the note; measured 11795. Mac recheck adds its enrolment, skip and outcome contracts (macrecheck_contract_test.go, about 210 lines); measured 11537. Spend 1 merged onto the four UI branches: measured 11325. Spend 1 marks overcounting Claude rows (about 120 lines); it adds the task page's spend contract and the 0059 upgrade (spend_pages_test.go, about 100 lines) and the fix round feedback by protocol (about 40); measured 10224. The team panel merged onto Projects UX and the Settings UX pass: measured 11064 with all three. The team panel adds its page contract and the drawer's browser drive at 1280 and 390 (team_panel_test.go, team_panel_browser_test.go, about 300 lines); measured 10235. Projects UX merged onto the Settings UX pass: measured 10768 with both. Projects UX adds the Projects page contracts (order, quiet fold, filter, stars and Undo, the coordinator's star, repository counts, whole words), the decision cards' Mac and Ask about this contracts and their browser drive (projects_pages_test.go, projects_browser_test.go, about 330 lines); measured 10321. The Settings UX pass adds the Settings pattern's page contracts and the savebar, Housekeeping groups and Teams browser drives (settings_ux_pages_test.go, settings_ux_browser_test.go, about 430 lines); measured 10390. Claude's sign-in by a link adds the code contract (signin_contract_test.go: the card, the code route's refusals, the wrong-code card, the kind it becomes and the canary sweep, about 220 lines); measured 9896. The Connections Add page and the Settings rail add their page contracts and the rail's browser drive (connections_add_pages_test.go, settings_rail_pages_test.go, about 230 lines); measured 9676. Claude setup tokens add the token and Check again contracts; measured 9444 with the composer and Mac lines merged. The instant thinking line adds its browser drive (instant_browser_test.go, about 230 lines); measured 9064 with the composer and Mac lines merged. Mac runners add the role, scoping, migration, placement, withdrawal, transfer and publication contracts (about 900 test lines) beside the thin v1 contracts; one package keeps one instance harness.
+size internal/headless - 8475 Turn batching adds TestHeadlessTurnBatching (three messages behind a slow turn through the real runner and fake CLI: the one next turn, its input, the bubbles and note, the usage rows and the spend lines, about 145 lines); measured 8475. Merge authority extends 4c_checks_card to end in Equipo's own merge, measured by the real runner, with its receipt (about 30 lines); measured 8330. Claude's sign-in by a link adds its end-to-end, contained-launch and real runner kill tests (signin_test.go, signin_contained_test.go, about 400 lines); measured 8090.
+size internal/thintest - 13325 Turn batching adds its contracts (the crash between turns, the stranded recovery, failed, cancelled, interrupted and retried turns, the cancelled batch and the note clearing; about 330 lines); measured 13325. Merge authority merged onto Machines in Settings, with the re-run ruling's cases and stale thinking lines: measured 12998. Merge authority thin v1 adds its contracts (mergeauth_contract_test.go, about 650 lines) the protocol-aware rigs and the Mac re-run contract (macrecheck_mergeauth_contract_test.go) and the review fixes' contracts; measured 12535 with main merged. Mac recheck adds its enrolment, skip and outcome contracts (macrecheck_contract_test.go, about 210 lines); measured 11537. Machines in Settings adds its fixture, page and browser tests (machines_fixture_test.go, machines_pages_test.go, machines_browser_test.go, about 160 lines); measured 11759. Mac recheck adds its enrolment, skip and outcome contracts (macrecheck_contract_test.go, about 210 lines); measured 11537. Stale thinking lines merged onto Machines in Settings: measured 11967. Machines in Settings adds its fixture, page and browser tests (machines_fixture_test.go, machines_pages_test.go, machines_browser_test.go, about 160 lines); measured 11759. Stale thinking lines add their browser drive (stale_thinking_browser_test.go, about 200 lines) and the queued test now checks the note; measured 11795. Mac recheck adds its enrolment, skip and outcome contracts (macrecheck_contract_test.go, about 210 lines); measured 11537. Spend 1 merged onto the four UI branches: measured 11325. Spend 1 marks overcounting Claude rows (about 120 lines); it adds the task page's spend contract and the 0059 upgrade (spend_pages_test.go, about 100 lines) and the fix round feedback by protocol (about 40); measured 10224. The team panel merged onto Projects UX and the Settings UX pass: measured 11064 with all three. The team panel adds its page contract and the drawer's browser drive at 1280 and 390 (team_panel_test.go, team_panel_browser_test.go, about 300 lines); measured 10235. Projects UX merged onto the Settings UX pass: measured 10768 with both. Projects UX adds the Projects page contracts (order, quiet fold, filter, stars and Undo, the coordinator's star, repository counts, whole words), the decision cards' Mac and Ask about this contracts and their browser drive (projects_pages_test.go, projects_browser_test.go, about 330 lines); measured 10321. The Settings UX pass adds the Settings pattern's page contracts and the savebar, Housekeeping groups and Teams browser drives (settings_ux_pages_test.go, settings_ux_browser_test.go, about 430 lines); measured 10390. Claude's sign-in by a link adds the code contract (signin_contract_test.go: the card, the code route's refusals, the wrong-code card, the kind it becomes and the canary sweep, about 220 lines); measured 9896. The Connections Add page and the Settings rail add their page contracts and the rail's browser drive (connections_add_pages_test.go, settings_rail_pages_test.go, about 230 lines); measured 9676. Claude setup tokens add the token and Check again contracts; measured 9444 with the composer and Mac lines merged. The instant thinking line adds its browser drive (instant_browser_test.go, about 230 lines); measured 9064 with the composer and Mac lines merged. Mac runners add the role, scoping, migration, placement, withdrawal, transfer and publication contracts (about 900 test lines) beside the thin v1 contracts; one package keeps one instance harness.
perf GET /api/v1/projects/{id}/merge-policy skip Merge authority person API: bearer-only JSON for devices; the browser reads the policy on /projects/{id}.
diff --git a/docs/superpowers/specs/2026-11-11-equipo-turn-batching.md b/docs/superpowers/specs/2026-11-11-equipo-turn-batching.md
new file mode 100644
index 00000000..88436105
--- /dev/null
+++ b/docs/superpowers/specs/2026-11-11-equipo-turn-batching.md
@@ -0,0 +1,111 @@
+# Equipo turn batching
+
+2026-11-11, branch `turn-batching` from main 03f8a91.
+
+## What happens today
+
+The instance already batches. This has been the case since the first thin
+v1 commit (64cd2ce, the thin v1 spec's §2 "Second message rule", tested by
+`TestQueuedMessagesJoinOneTurn` and headless scenario 6).
+
+1. `chatSend` (the page) and `POST /api/v1/messages` (devices) both call
+ `Store.Send`, then `txn.send` in one write transaction.
+2. `send` looks for the person's queued, undispatched person turn. If it
+ finds one, the message joins it. If not, it creates a new turn
+ (`chat_turns`, state `queued`). The message row (`chat_messages`) points
+ at that turn.
+3. If no dispatched turn is in flight (`queued`, `running` or `waiting`),
+ `dispatch` runs in the same transaction. It writes one `message` command
+ to the person's primary runner's mailbox (`runner_commands`): the
+ attachment frames first, then `wire.MessageCommand` with `Text`,
+ `PersonText` (one entry per message), the tail and the attachment refs.
+ The turn becomes `dispatched`. If a turn is already in flight, the
+ message waits in the queued turn.
+4. The runner's ack moves the turn to `running`. `reply`, `report`
+ (failed or cancelled), `sync` (a turn the runner no longer holds) and
+ `Cancel` of an undispatched turn each end the turn and call
+ `dispatchNext` in the same transaction. `dispatchNext` dispatches the
+ oldest queued turn (the person's own first) once nothing is in flight.
+5. The runner (`thin.coordBase.prompt`) puts `Text` under "Newest message"
+ in a fresh session, or sends it alone in a warm one. Claude and Codex
+ read the same text.
+
+So three messages sent during a slow turn already become one next turn and
+one reply. A message sent while nothing runs starts its own turn at once.
+The 13 staging turns fit messages that mostly arrived between turns. I
+could not check this, because I did not read staging.
+
+## What was missing
+
+- **Distinct messages.** `Text` was the messages joined with a blank line.
+ "two\n\nthree" reads the same as one message with two paragraphs. The
+ fake coordinator, which splits on blank lines, counted the attachment
+ note as a fourth message.
+- **Attachments per message.** The runner lists every file of the turn as
+ "the person attached these files", with nothing tying a file to the
+ message that carried it.
+- **Recovery of a stranded queued turn.** Each end path dispatches the next
+ turn in the same transaction, so the current code cannot strand one. A
+ queued turn left behind with nothing in flight (an older build, a manual
+ repair) waited until the person sent another message.
+
+## The change
+
+All of it is in the instance's turn building. There is no wire, protocol,
+fixture or migration change.
+
+- `dispatch` builds `Text` with `turnText`. One message is sent exactly as
+ before. Several messages are sent as:
+
+ ```
+ [Equipo: the person sent 3 messages while you were busy, oldest first. Each is a separate message; answer them together in one reply.]
+
+ Message 1 of 3:
+ alpha first
+
+ Message 2 of 3 (attached: notes.md):
+ bravo second
+
+ Message 3 of 3:
+ charlie third
+ ```
+
+ `relayFiles` also returns each message's file names. `PersonText` and
+ `Attachments` keep their meaning. Every protocol reads `Text` as the
+ person's words, so old and new runners get the same frame shape.
+- `sync`, after it reconciles, calls `dispatchNext` for the person.
+ `dispatchNext` does nothing while a turn is in flight. A stranded queued
+ turn therefore starts on the runner's next connection, exactly once.
+
+## Crash, retry and end cases
+
+| Case | What happens | Contract |
+|---|---|---|
+| Crash between "turn ended" and "next turn created" | The end and the next dispatch are one transaction. Neither commits. The runner's reply is not acked, so it comes again after the restart. The inbox row rolled back with the transaction, so the reply applies once and starts one next turn. | `TestBatchCrashBetweenTurns` |
+| Same reply again, runner reconnects | The inbox drops the duplicate reply. The reconnect resends the same unacked command (same frame id), not a new turn. | `TestBatchCrashBetweenTurns` |
+| End committed without its successor | The next `sync` dispatches it once. A second sync does nothing. | `TestBatchStrandedRecovers` |
+| Running turn fails, is cancelled, or is lost across a runner reconnect | The batch goes next, once. The ended turn keeps only its own message. | `TestBatchAfterTurnEnds` |
+| Running turn retried (attempt 2) | The batch keeps waiting. A message sent during the retry joins it. A late attempt-1 reply is ignored. The batch goes once, after attempt 2 replies. | `TestBatchWaitsForRetriedTurn` |
+| Batch cancelled while it waits | All of its messages end `cancelled` together, unsent. The next message gets a turn of its own. | `TestBatchCancelledWhileWaiting` |
+| Bubbles and the queued note | Each message keeps its own bubble in the queued turn. One note sits under the latest one, as the thinking-stale fix did. The note clears for all of them when the batch's frame goes out, before the ack. | `TestBatchMarkerClearsTogether`, `TestHeadlessTurnBatching` |
+
+## Usage attribution
+
+Usage is recorded per turn (`chat_usage.turn_id`). A batch is one
+coordinator turn, so it is one user message to the CLI and one result.
+Claude's rows come from that result's `model_usage_since_last_result`.
+Codex's `CodexTally` counts one provider turn per attempt. Both attribute
+the whole batch to the batch turn. Nothing reads usage per message.
+`TestHeadlessTurnBatching` checks for one row for the batch turn and none
+for any single message.
+
+## Open product questions
+
+1. **Bursts between turns.** A message sent while nothing runs starts at
+ once. To batch those, the instance would have to hold a message for a
+ short time first, which delays the first token.
+2. **One note or one per bubble.** The rules say each message shows the
+ queued marker. The thinking-stale fix chose one note under the latest
+ waiting message. This branch keeps the merged single note.
+3. **Failure copy for a batch.** `chat.failed` says "this message" even
+ when the failed turn covered several messages.
diff --git a/internal/equipo/chat/attachments.go b/internal/equipo/chat/attachments.go
index c5f85b06..9560bf95 100644
--- a/internal/equipo/chat/attachments.go
+++ b/internal/equipo/chat/attachments.go
@@ -239,14 +239,15 @@ func (s *Store) AttachmentData(ctx context.Context, person, id string, preview b
// relayFiles writes the attachment frames for the files of a turn's
// messages, before its message frame. The command rows hold no bytes:
-// Pending reads each chunk from chat_attachment_data as it sends.
-func (t *txn) relayFiles(person string, messages []string) ([]wire.AttachmentRef, error) {
+// Pending reads each chunk from chat_attachment_data as it sends. names
+// are each message's file names, in order.
+func (t *txn) relayFiles(person string, messages []string) ([]wire.AttachmentRef, map[string][]string, error) {
if len(messages) == 0 {
- return nil, nil
+ return nil, nil, nil
}
var rows []fileRecord
if err := t.db.Where("message_id IN ? AND person = ?", messages, person).Find(&rows).Error; err != nil {
- return nil, err
+ return nil, nil, err
}
order := map[string]int{}
for i, id := range messages {
@@ -259,17 +260,19 @@ func (t *txn) relayFiles(person string, messages []string) ([]wire.AttachmentRef
return a.Position - b.Position
})
refs := make([]wire.AttachmentRef, 0, len(rows))
+ names := map[string][]string{}
for _, r := range rows {
ref := wire.AttachmentRef{ID: r.ID, Kind: r.Kind, Name: r.Name, MediaType: r.MediaType, Size: r.Size, SHA256: r.SHA256}
count := attach.Chunks(r.Size)
for i := 0; i < count; i++ {
if err := t.command(person, wire.FrameAttachment, wire.AttachmentChunk{Person: person, AttachmentRef: ref, Index: i, Count: count}); err != nil {
- return nil, err
+ return nil, nil, err
}
}
refs = append(refs, ref)
+ names[r.MessageID] = append(names[r.MessageID], r.Name)
}
- return refs, nil
+ return refs, names, nil
}
// hydrate fills an attachment frame's bytes from the stored file.
diff --git a/internal/equipo/chat/runner.go b/internal/equipo/chat/runner.go
index af66e6a6..6f886197 100644
--- a/internal/equipo/chat/runner.go
+++ b/internal/equipo/chat/runner.go
@@ -537,7 +537,11 @@ func (t *txn) sync(l Lease, v *wire.Sync) error {
return err
}
}
- return nil
+ // Every path that ends a turn starts the next in the same
+ // transaction. A queued turn left behind with nothing in flight (an
+ // older instance's crash) starts here, once: dispatchNext does nothing
+ // while a turn is in flight.
+ return t.dispatchNext(l.Runner.Person)
}
// markTainted records, for good, that a check ran outside the sandbox on
diff --git a/internal/equipo/chat/store.go b/internal/equipo/chat/store.go
index b249c051..eadefeb9 100644
--- a/internal/equipo/chat/store.go
+++ b/internal/equipo/chat/store.go
@@ -7,6 +7,7 @@ import (
"encoding/hex"
"encoding/json"
"errors"
+ "strconv"
"strings"
"sync"
"sync/atomic"
@@ -246,7 +247,7 @@ func (t *txn) commandTo(runner, person, kind string, body any) error {
}
// dispatch sends a queued turn to the runner with the person's messages
-// joined into one frame and the conversation tail before them. A move-in
+// in one frame (turnText) and the conversation tail before them. A move-in
// or explore turn carries no text: the runner writes its prompt.
func (t *txn) dispatch(r *turnRecord) error {
if err := t.hkSpend(r.Person); err != nil {
@@ -274,10 +275,11 @@ func (t *txn) dispatch(r *turnRecord) error {
ids = append(ids, m.ID)
}
// Attachment bytes go first, as their own frames.
- files, err := t.relayFiles(r.Person, ids)
+ files, names, err := t.relayFiles(r.Person, ids)
if err != nil {
return err
}
+ attached := make([][]string, 0, len(mine))
for _, m := range mine {
own = append(own, m.Text)
text, err := t.answerPrefix(m)
@@ -285,15 +287,44 @@ func (t *txn) dispatch(r *turnRecord) error {
return err
}
texts = append(texts, text)
+ attached = append(attached, names[m.ID])
}
now := t.now()
r.Dispatched, r.DispatchedAt = true, &now
- if err := t.command(r.Person, wire.FrameMessage, wire.MessageCommand{Person: r.Person, TurnID: r.ID, Attempt: r.Attempt, Kind: r.Kind, Text: strings.Join(texts, "\n\n"), PersonText: own, Tail: tail, Attachments: files}); err != nil {
+ if err := t.command(r.Person, wire.FrameMessage, wire.MessageCommand{Person: r.Person, TurnID: r.ID, Attempt: r.Attempt, Kind: r.Kind, Text: turnText(texts, attached), PersonText: own, Tail: tail, Attachments: files}); err != nil {
return err
}
return nil
}
+// turnText is what the coordinator reads for a turn's messages. One
+// message is its words alone (none, for a move-in or explore turn).
+// Several (sent while another turn ran) are each set apart, oldest
+// first, with the names of the files each one carried, so the
+// coordinator can tell them apart and answer them together. Every runner
+// reads Text as the person's words, so the frame is the same at every
+// protocol.
+func turnText(texts []string, files [][]string) string {
+ if len(texts) < 2 {
+ return strings.Join(texts, "")
+ }
+ var b strings.Builder
+ n := strconv.Itoa(len(texts))
+ b.WriteString("[Equipo: the person sent " + n + " messages while you were busy, oldest first. Each is a separate message; answer them together in one reply.]")
+ for i, text := range texts {
+ b.WriteString("\n\nMessage " + strconv.Itoa(i+1) + " of " + n)
+ if len(files[i]) > 0 {
+ b.WriteString(" (attached: " + strings.Join(files[i], ", ") + ")")
+ }
+ b.WriteString(":\n")
+ if text == "" {
+ text = "(files only, no words)"
+ }
+ b.WriteString(text)
+ }
+ return b.String()
+}
+
// personFirst orders queued turns: the person's own before any move-in or
// explore turn, and those before housekeeping, then oldest first.
const personFirst = "CASE WHEN coalesce(kind, '') = '' THEN 0 WHEN kind = '" + wire.TurnHousekeeping + "' THEN 2 ELSE 1 END, created_at, id"
diff --git a/internal/fakeclaude/fake.go b/internal/fakeclaude/fake.go
index b06c72cd..51edb54c 100644
--- a/internal/fakeclaude/fake.go
+++ b/internal/fakeclaude/fake.go
@@ -69,6 +69,11 @@
// "asksleep:<ms>" pauses before the reply.
// Native tools in system/init are those of --tools.
//
+// Several messages in one turn: when the newest part of the prompt holds
+// "Message <i> of <n>:" headers (the instance's batch), the reply ends
+// "You sent <n> messages: <i>/<n> <first line> [<files>]; ...", in the
+// order the prompt gives them, so a test sees each one arrived apart.
+//
// Setup tokens: with CLAUDE_CODE_OAUTH_TOKEN in its environment the fake
// is signed in by that token, as the pinned CLI is: `auth status` says
// logged in for any token at all, never asking the server (with the
@@ -719,7 +724,9 @@ func (f *fake) serve(stdin io.Reader, stdout, stderr io.Writer) int {
if strings.Contains(prompt, "Conversation so far") {
reply += " I see the earlier conversation."
}
- if strings.Contains(prompt, "\n\n") && !strings.Contains(prompt, "Newest message") {
+ if seen := batchMessages(newest); len(seen) > 0 {
+ reply += fmt.Sprintf(" You sent %d messages: %s.", len(seen), strings.Join(seen, "; "))
+ } else if strings.Contains(prompt, "\n\n") && !strings.Contains(prompt, "Newest message") {
reply += fmt.Sprintf(" You sent %d messages.", strings.Count(prompt, "\n\n")+1)
}
if strings.Contains(prompt, "=== Your notebook") {
@@ -921,6 +928,32 @@ func (f *fake) serve(stdin io.Reader, stdout, stderr io.Writer) int {
var moveInPause = regexp.MustCompile(`movein-pause:([0-9]+)`)
+// batchHeader opens each message of a turn that carries several, as the
+// instance writes them: "Message 2 of 3" and, when it has files,
+// " (attached: a.png, b.md)", then a colon and the message.
+var batchHeader = regexp.MustCompile(`(?m)^Message ([0-9]+) of ([0-9]+)(?: \(attached: ([^)\n]*)\))?:$`)
+
+// batchMessages reads the separate messages of a turn that carries
+// several, in the order the prompt gives them: each message's first line,
+// with its files in brackets. Nothing when the turn has one message.
+func batchMessages(newest string) []string {
+ heads := batchHeader.FindAllStringSubmatchIndex(newest, -1)
+ out := make([]string, 0, len(heads))
+ for i, h := range heads {
+ end := len(newest)
+ if i+1 < len(heads) {
+ end = heads[i+1][0]
+ }
+ body := strings.TrimSpace(newest[h[1]:end])
+ first, _, _ := strings.Cut(body, "\n")
+ if h[6] >= 0 {
+ first += " [" + newest[h[6]:h[7]] + "]"
+ }
+ out = append(out, newest[h[2]:h[3]]+"/"+newest[h[4]:h[5]]+" "+first)
+ }
+ return out
+}
+
// attachmentPath is an attached file's path in the namespace.
var attachmentPath = regexp.MustCompile(`/workspace/attachments/at_[a-z0-9]+/[^\s:]+`)
diff --git a/internal/headless/batching_test.go b/internal/headless/batching_test.go
new file mode 100644
index 00000000..4c2f83d7
--- /dev/null
+++ b/internal/headless/batching_test.go
@@ -0,0 +1,145 @@
+package headless
+
+import (
+ "encoding/json"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/thintest"
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// TestHeadlessTurnBatching: three messages sent while a slow turn runs
+// wait together, each in its own bubble. When the slow turn ends, one
+// turn picks all three up; the coordinator gets them in order, as
+// separate messages with their files, and answers once. The spend lines
+// it logs are the turns and input tokens of the batch beside the same
+// three messages sent one at a time.
+func TestHeadlessTurnBatching(t *testing.T) {
+ env, inst, r := localEnv(t)
+ r.start(t)
+ s := open(t, env)
+ busy := s.send(t, "Take your time with this one. sleep:4000")
+ s.waitTurn(t, busy.Turn.ID, wire.TurnRunning)
+ notes := upload(t, s, "notes.md", "text/markdown", []byte("# Notes\n\nStep three fails.\n"))
+ sent := []wire.Sent{s.send(t, "alpha first"), sendWith(t, s, "bravo second", notes), s.send(t, "charlie third")}
+ batch := sent[0].Turn.ID
+ for i, m := range sent {
+ if m.Turn.ID != batch || m.Turn.ID == busy.Turn.ID || m.Turn.State != wire.TurnQueued {
+ t.Fatalf("message %d went to turn %s (%s), not the queued turn %s", i+1, m.Turn.ID, m.Turn.State, batch)
+ }
+ }
+ if ids := sent[2].Turn.MessageIDs; len(ids) != 3 || ids[0] != sent[0].Message.ID || ids[1] != sent[1].Message.ID || ids[2] != sent[2].Message.ID {
+ t.Fatalf("queued turn holds %v", ids)
+ }
+ // Each message keeps its own bubble, in order, in the queued turn; the
+ // quiet note waits under the latest.
+ page := inst.Get(t, "/conversation")
+ at := -1
+ for i, m := range sent {
+ bubble := `data-message="` + m.Message.ID + `" data-turn-id="` + batch + `"`
+ n := strings.Index(page, bubble)
+ if n < 0 || n < at || strings.Count(page, `data-message="`+m.Message.ID+`"`) != 1 {
+ t.Fatalf("bubble %d missing, repeated or out of order", i+1)
+ }
+ at = n
+ }
+ const note = "<p equipo-card-note data-queued>"
+ if strings.Count(page, note) != 1 || strings.Index(page, note) < at {
+ t.Fatalf("queued note not once under the latest message")
+ }
+ s.waitTurn(t, busy.Turn.ID, wire.TurnReplied)
+ reply := replyOf(t, s, batch)
+ // Exactly one next turn: the batch, and no turn for any one message.
+ var turns int
+ if err := inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_turns").Scan(&turns); err != nil {
+ t.Fatal(err)
+ }
+ if turns != 2 {
+ t.Fatalf("%d turns for one slow message and three queued ones", turns)
+ }
+ s.conv.Locked(func(c *thintest.Conversation) {
+ if got := c.Turns[batch].MessageIDs; len(got) != 3 || len(c.Replies()) != 2 {
+ t.Fatalf("batch picked up %v; %d replies", got, len(c.Replies()))
+ }
+ })
+ if page = inst.Get(t, "/conversation"); strings.Contains(page, note) {
+ t.Fatal("queued note still shows after the turn picked the messages up")
+ }
+ // Spend goes to the turn: one usage row for the batch beside the slow
+ // turn's own, none for any one message.
+ if rows := logSpend(t, inst, "batched", batch); rows != 1 || logSpend(t, inst, "slow", busy.Turn.ID) != 1 {
+ t.Fatalf("batch has %d usage rows", rows)
+ }
+ var usage int
+ if err := inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_usage WHERE role = 'coordinator'").Scan(&usage); err != nil || usage != 2 {
+ t.Fatalf("%d coordinator usage rows for two turns: %v", usage, err)
+ }
+ // The coordinator's input: one frame naming each message apart, in
+ // order, with its file.
+ cmds := messageCommands(t, inst, batch)
+ if len(cmds) != 1 {
+ t.Fatalf("%d message commands for the batch", len(cmds))
+ }
+ text, last := cmds[0].Text, -1
+ for _, want := range []string{"Message 1 of 3:\nalpha first", "Message 2 of 3 (attached: notes.md):\nbravo second", "Message 3 of 3:\ncharlie third"} {
+ n := strings.Index(text, want)
+ if n <= last {
+ t.Fatalf("turn input lacks %q in order:\n%s", want, text)
+ }
+ last = n
+ }
+ if p := cmds[0].PersonText; len(p) != 3 || p[0] != "alpha first" || p[1] != "bravo second" || p[2] != "charlie third" {
+ t.Fatalf("person text %q", p)
+ }
+ if len(cmds[0].Attachments) != 1 || cmds[0].Attachments[0].ID != notes.ID {
+ t.Fatalf("attachments %+v", cmds[0].Attachments)
+ }
+ if want := "You sent 3 messages: 1/3 alpha first; 2/3 bravo second [notes.md]; 3/3 charlie third."; !strings.Contains(reply.Text, want) {
+ t.Fatalf("coordinator did not see three messages apart: %q", reply.Text)
+ }
+ // The same three words one at a time, each after the last reply: what
+ // the person pays when nothing is running to batch behind.
+ for i, text := range []string{"alpha first", "bravo second", "charlie third"} {
+ one := s.send(t, text)
+ replyOf(t, s, one.Turn.ID)
+ logSpend(t, inst, "alone "+string(rune('1'+i)), one.Turn.ID)
+ }
+}
+
+// messageCommands are the message frames the instance wrote for a turn.
+func messageCommands(t *testing.T, inst *thintest.Instance, turn string) []wire.MessageCommand {
+ t.Helper()
+ rows, err := inst.DB.Writer().Query("SELECT body FROM runner_commands WHERE kind = ? ORDER BY seq", wire.FrameMessage)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer rows.Close()
+ var out []wire.MessageCommand
+ for rows.Next() {
+ var body string
+ var m wire.MessageCommand
+ if err := rows.Scan(&body); err != nil || json.Unmarshal([]byte(body), &m) != nil {
+ t.Fatalf("command %v", err)
+ }
+ if m.TurnID == turn {
+ out = append(out, m)
+ }
+ }
+ return out
+}
+
+// logSpend logs a coordinator turn's recorded usage (rows, input and
+// cached input tokens) and returns its row count.
+func logSpend(t *testing.T, inst *thintest.Instance, label, turn string) int64 {
+ t.Helper()
+ var rows, input, cached int64
+ if err := inst.DB.Writer().QueryRow("SELECT count(*), coalesce(sum(input_tokens), 0), coalesce(sum(cached_input_tokens), 0) FROM chat_usage WHERE turn_id = ? AND role = 'coordinator'", turn).Scan(&rows, &input, &cached); err != nil {
+ t.Fatal(err)
+ }
+ if rows == 0 {
+ t.Fatalf("no usage recorded for turn %s", turn)
+ }
+ t.Logf("spend %s: turn %s, %d usage rows, %d input tokens, %d cached", label, turn, rows, input, cached)
+ return rows
+}
diff --git a/internal/thintest/batching_contract_test.go b/internal/thintest/batching_contract_test.go
new file mode 100644
index 00000000..67df9461
--- /dev/null
+++ b/internal/thintest/batching_contract_test.go
@@ -0,0 +1,327 @@
+package thintest
+
+import (
+ "context"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// Turn batching: messages sent while a turn runs wait in one queued turn
+// and go to the coordinator together when it ends, exactly once, however
+// it ends and whatever crashes between. The runner here speaks protocol
+// 1, the oldest the instance serves.
+
+// busyWithThree starts a turn, has the runner take it, and queues three
+// messages behind it.
+func (r *rig) busyWithThree(runner *FakeRunner) (wire.Sent, []wire.Sent) {
+ r.t.Helper()
+ busy, err := r.client.Send(r.ctx, "one", "k0")
+ if err != nil {
+ r.t.Fatal(err)
+ }
+ f, _, err := runner.Expect(r.ctx, wire.FrameMessage)
+ if err != nil {
+ r.t.Fatal(err)
+ }
+ runner.Send(r.ctx, "a0", wire.FrameAck, wire.Ack{ID: f.ID})
+ r.turnIs(busy.Turn.ID, wire.TurnRunning)
+ var queued []wire.Sent
+ for i, text := range []string{"alpha", "bravo", "charlie"} {
+ s, err := r.client.Send(r.ctx, text, "kq"+string(rune('1'+i)))
+ if err != nil || s.Turn.ID == busy.Turn.ID || s.Turn.State != wire.TurnQueued || len(queued) > 0 && s.Turn.ID != queued[0].Turn.ID {
+ r.t.Fatalf("message %d: %+v %v", i+1, s.Turn, err)
+ }
+ queued = append(queued, s)
+ }
+ return busy, queued
+}
+
+// acked waits for the instance's ack of one of the runner's frames.
+func (r *rig) acked(runner *FakeRunner, id string) {
+ r.t.Helper()
+ for {
+ _, body, err := runner.Expect(r.ctx, wire.FrameAck)
+ if err != nil {
+ r.t.Fatalf("no ack for %s: %v", id, err)
+ }
+ if body.(*wire.Ack).ID == id {
+ return
+ }
+ }
+}
+
+// turnIs waits until the API reads a turn in state.
+func (r *rig) turnIs(id, state string) wire.Turn {
+ r.t.Helper()
+ var got wire.Turn
+ for deadline := time.Now().Add(10 * time.Second); time.Now().Before(deadline); time.Sleep(20 * time.Millisecond) {
+ var err error
+ if got, err = r.client.Turn(r.ctx, id); err == nil && got.State == state {
+ return got
+ }
+ }
+ r.t.Fatalf("turn %s is %s (%s), not %s", id, got.State, got.Reason, state)
+ return got
+}
+
+// batchFrame expects the next message frame to be the batch: the three
+// messages apart and in order, and nothing else.
+func (r *rig) batchFrame(runner *FakeRunner, batch string, texts ...string) wire.Frame {
+ r.t.Helper()
+ ctx, cancel := context.WithTimeout(r.ctx, 10*time.Second)
+ defer cancel()
+ f, body, err := runner.Expect(ctx, wire.FrameMessage)
+ if err != nil {
+ r.t.Fatalf("no next turn: %v", err)
+ }
+ cmd := body.(*wire.MessageCommand)
+ if cmd.TurnID != batch || len(cmd.PersonText) != len(texts) {
+ r.t.Fatalf("next turn %s carries %q, not the batch %s", cmd.TurnID, cmd.PersonText, batch)
+ }
+ at := -1
+ for i, text := range texts {
+ n := strings.Index(cmd.Text, "Message "+string(rune('1'+i))+" of "+string(rune('0'+len(texts)))+":\n"+text)
+ if n <= at || cmd.PersonText[i] != text {
+ r.t.Fatalf("batch lacks %q in place:\n%s", text, cmd.Text)
+ }
+ at = n
+ }
+ shape(r.t, "frames/message.json", runner.Received[len(runner.Received)-1])
+ return f
+}
+
+// exactlyOnce checks a batch went to the runner in one message frame,
+// that the conversation has turns turns, and that no turn has two replies.
+func (r *rig) exactlyOnce(batch string, turns int) {
+ r.t.Helper()
+ var frames, all, replies int
+ db := r.inst.DB.Writer()
+ if err := db.QueryRow("SELECT count(*) FROM runner_commands WHERE kind = ? AND body LIKE ?", wire.FrameMessage, `%"turn_id":"`+batch+`"%`).Scan(&frames); err != nil {
+ r.t.Fatal(err)
+ }
+ if err := db.QueryRow("SELECT count(*) FROM chat_turns").Scan(&all); err != nil {
+ r.t.Fatal(err)
+ }
+ if err := db.QueryRow("SELECT coalesce(max(n), 0) FROM (SELECT count(*) AS n FROM chat_messages WHERE role = ? GROUP BY turn_id)", wire.RoleCoordinator).Scan(&replies); err != nil {
+ r.t.Fatal(err)
+ }
+ if frames != 1 || all != turns {
+ r.t.Fatalf("batch %s went out %d times; %d turns, want %d", batch, frames, all, turns)
+ }
+ if replies > 1 {
+ r.t.Fatalf("a turn has %d replies", replies)
+ }
+}
+
+// A crash between the end of a turn and the start of the next leaves
+// neither: the instance commits both in one transaction, so the runner's
+// reply comes again after the restart and starts exactly one next turn.
+func TestBatchCrashBetweenTurns(t *testing.T) {
+ r := newRig(t)
+ runner := r.dial(0)
+ busy, queued := r.busyWithThree(runner)
+ batch := queued[0].Turn.ID
+ db := r.inst.DB.Writer()
+ if _, err := db.Exec(`CREATE TRIGGER batch_crash BEFORE INSERT ON runner_commands WHEN NEW.kind = 'message' BEGIN SELECT RAISE(ABORT, 'crash'); END`); err != nil {
+ t.Fatal(err)
+ }
+ reply := wire.Reply{TurnID: busy.Turn.ID, Attempt: 1, Text: "first"}
+ runner.Send(r.ctx, "rep1", wire.FrameReply, reply)
+ for {
+ _, body, err := runner.Next(r.ctx)
+ if err != nil {
+ break
+ }
+ if a, ok := body.(*wire.Ack); ok && a.ID == "rep1" {
+ t.Fatal("the reply was acked with the next turn refused")
+ }
+ }
+ if st, _ := r.client.Turn(r.ctx, busy.Turn.ID); st.State != wire.TurnRunning {
+ t.Fatalf("turn ended without its successor: %s", st.State)
+ }
+ if st, _ := r.client.Turn(r.ctx, batch); st.State != wire.TurnQueued || len(st.MessageIDs) != 3 {
+ t.Fatalf("batch %+v", st)
+ }
+ if _, err := db.Exec(`DROP TRIGGER batch_crash`); err != nil {
+ t.Fatal(err)
+ }
+ r.inst.Restart(t)
+ again := r.dial(runner.Welcome.Generation)
+ again.Send(r.ctx, "s1", wire.FrameSync, wire.Sync{Sessions: []wire.SessionState{}, Runs: []wire.Run{{TurnID: busy.Turn.ID, Attempt: 1, State: wire.TurnRunning}}})
+ // Frames apply in order: once a no-op report is acked, the sync is in.
+ again.Send(r.ctx, "s1b", wire.FrameTurn, wire.TurnReport{TurnID: busy.Turn.ID, Attempt: 1, State: wire.TurnRunning})
+ r.acked(again, "s1b")
+ // The runner still holds the turn: the batch waits for it.
+ var early int
+ if err := r.inst.DB.Writer().QueryRow("SELECT count(*) FROM runner_commands WHERE kind = ? AND body LIKE ?", wire.FrameMessage, `%"turn_id":"`+batch+`"%`).Scan(&early); err != nil || early != 0 {
+ t.Fatalf("batch went out beside the running turn: %d %v", early, err)
+ }
+ again.Send(r.ctx, "rep1", wire.FrameReply, reply)
+ f := r.batchFrame(again, batch, "alpha", "bravo", "charlie")
+ // The same reply once more, and a reconnect that resends the unacked
+ // frame: still the one batch.
+ again.Send(r.ctx, "rep1", wire.FrameReply, reply)
+ again.Close()
+ back := r.dial(runner.Welcome.Generation)
+ if f2 := r.batchFrame(back, batch, "alpha", "bravo", "charlie"); f2.ID != f.ID {
+ t.Fatalf("reconnect wrote a new frame %s, not %s", f2.ID, f.ID)
+ }
+ back.Send(r.ctx, "ab", wire.FrameAck, wire.Ack{ID: f.ID})
+ r.turnIs(batch, wire.TurnRunning)
+ back.Send(r.ctx, "rep2", wire.FrameReply, wire.Reply{TurnID: batch, Attempt: 1, Text: "all three"})
+ r.turnIs(batch, wire.TurnReplied)
+ r.exactlyOnce(batch, 2)
+}
+
+// A turn whose end committed without its successor (an older instance, or
+// a failure this one does not have) recovers on the runner's next sync:
+// exactly one next turn, the waiting messages in it.
+func TestBatchStrandedRecovers(t *testing.T) {
+ r := newRig(t)
+ runner := r.dial(0)
+ busy, queued := r.busyWithThree(runner)
+ batch := queued[0].Turn.ID
+ if _, err := r.inst.DB.Writer().Exec("UPDATE chat_turns SET state = ? WHERE id = ?", wire.TurnFailed, busy.Turn.ID); err != nil {
+ t.Fatal(err)
+ }
+ runner.Close()
+ r.inst.Restart(t)
+ again := r.dial(runner.Welcome.Generation)
+ again.Send(r.ctx, "s1", wire.FrameSync, wire.Sync{Sessions: []wire.SessionState{}, Runs: []wire.Run{}})
+ f := r.batchFrame(again, batch, "alpha", "bravo", "charlie")
+ again.Send(r.ctx, "s2", wire.FrameSync, wire.Sync{Sessions: []wire.SessionState{}, Runs: []wire.Run{}})
+ again.Send(r.ctx, "ab", wire.FrameAck, wire.Ack{ID: f.ID})
+ r.turnIs(batch, wire.TurnRunning)
+ r.exactlyOnce(batch, 2)
+}
+
+// However the running turn ends (failed, cancelled, or lost across a
+// runner reconnect), the batch goes next, once, and the failed turn's own
+// message is not answered again inside it.
+func TestBatchAfterTurnEnds(t *testing.T) {
+ for _, end := range []string{"failed", "cancelled", "interrupted"} {
+ t.Run(end, func(t *testing.T) {
+ r := newRig(t)
+ runner := r.dial(0)
+ busy, queued := r.busyWithThree(runner)
+ batch := queued[0].Turn.ID
+ switch end {
+ case "failed":
+ runner.Send(r.ctx, "e1", wire.FrameTurn, wire.TurnReport{TurnID: busy.Turn.ID, Attempt: 1, State: wire.TurnFailed, Reason: "provider_failed"})
+ case "cancelled":
+ if _, err := r.client.Cancel(r.ctx, busy.Turn.ID); err != nil {
+ t.Fatal(err)
+ }
+ if _, _, err := runner.Expect(r.ctx, wire.FrameCancel); err != nil {
+ t.Fatal(err)
+ }
+ runner.Send(r.ctx, "e1", wire.FrameTurn, wire.TurnReport{TurnID: busy.Turn.ID, Attempt: 1, State: wire.TurnCancelled, Reason: "cancelled"})
+ case "interrupted":
+ // A new runner process no longer holds the turn.
+ runner.Close()
+ runner = r.dial(0)
+ runner.Send(r.ctx, "e1", wire.FrameSync, wire.Sync{Sessions: []wire.SessionState{}, Runs: []wire.Run{}})
+ }
+ r.batchFrame(runner, batch, "alpha", "bravo", "charlie")
+ if st, _ := r.client.Turn(r.ctx, busy.Turn.ID); !wire.Terminal(st.State) || len(st.MessageIDs) != 1 {
+ t.Fatalf("ended turn %+v", st)
+ }
+ r.exactlyOnce(batch, 2)
+ })
+ }
+}
+
+// A turn the runner retries (a new attempt on another connection) keeps
+// the batch waiting: a message sent meanwhile joins it, and the batch
+// goes once, after the retried attempt's reply. A late reply from the
+// abandoned attempt changes nothing.
+func TestBatchWaitsForRetriedTurn(t *testing.T) {
+ r := newRig(t)
+ runner := r.dial(0)
+ busy, queued := r.busyWithThree(runner)
+ batch := queued[0].Turn.ID
+ runner.Send(r.ctx, "r2", wire.FrameTurn, wire.TurnReport{TurnID: busy.Turn.ID, Attempt: 2, State: wire.TurnRunning})
+ for got := r.turnIs(busy.Turn.ID, wire.TurnRunning); got.Attempt != 2; got = r.turnIs(busy.Turn.ID, wire.TurnRunning) {
+ time.Sleep(20 * time.Millisecond)
+ }
+ fourth, err := r.client.Send(r.ctx, "delta", "kq4")
+ if err != nil || fourth.Turn.ID != batch || len(fourth.Turn.MessageIDs) != 4 {
+ t.Fatalf("message during the retry: %+v %v", fourth.Turn, err)
+ }
+ runner.Send(r.ctx, "late", wire.FrameReply, wire.Reply{TurnID: busy.Turn.ID, Attempt: 1, Text: "stale"})
+ runner.Send(r.ctx, "rep", wire.FrameReply, wire.Reply{TurnID: busy.Turn.ID, Attempt: 2, Text: "first"})
+ r.batchFrame(runner, batch, "alpha", "bravo", "charlie", "delta")
+ if got := r.turnIs(busy.Turn.ID, wire.TurnReplied); got.Attempt != 2 {
+ t.Fatalf("replied on attempt %d", got.Attempt)
+ }
+ r.exactlyOnce(batch, 2)
+}
+
+// Cancelling the waiting batch ends all its messages together, unsent;
+// the next message starts a turn of its own without them.
+func TestBatchCancelledWhileWaiting(t *testing.T) {
+ r := newRig(t)
+ runner := r.dial(0)
+ busy, queued := r.busyWithThree(runner)
+ batch := queued[0].Turn.ID
+ if _, err := r.client.Cancel(r.ctx, batch); err != nil {
+ t.Fatal(err)
+ }
+ if got := r.turnIs(batch, wire.TurnCancelled); len(got.MessageIDs) != 3 {
+ t.Fatalf("cancelled batch %+v", got)
+ }
+ later, err := r.client.Send(r.ctx, "echo", "kq5")
+ if err != nil || later.Turn.ID == batch || len(later.Turn.MessageIDs) != 1 {
+ t.Fatalf("later message %+v %v", later.Turn, err)
+ }
+ runner.Send(r.ctx, "rep", wire.FrameReply, wire.Reply{TurnID: busy.Turn.ID, Attempt: 1, Text: "first"})
+ _, body, err := runner.Expect(r.ctx, wire.FrameMessage)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if cmd := body.(*wire.MessageCommand); cmd.TurnID != later.Turn.ID || cmd.Text != "echo" {
+ t.Fatalf("after a cancelled batch the runner got %s %q", cmd.TurnID, cmd.Text)
+ }
+}
+
+// Each waiting message keeps its own bubble in the queued turn, with the
+// one quiet note under the latest. The note goes for all of them together
+// the moment the turn picks them up (its frame is out), before the runner
+// acks it, and the bubbles stay.
+func TestBatchMarkerClearsTogether(t *testing.T) {
+ r := newRig(t)
+ runner := r.dial(0)
+ busy, queued := r.busyWithThree(runner)
+ batch := queued[0].Turn.ID
+ const note = "<p equipo-card-note data-queued>"
+ bubbles := func(page string) int {
+ at := -1
+ for i, m := range queued {
+ n := strings.Index(page, `data-message="`+m.Message.ID+`" data-turn-id="`+batch+`"`)
+ if n <= at {
+ t.Fatalf("bubble %d missing or out of order", i+1)
+ }
+ at = n
+ }
+ return at
+ }
+ page := r.inst.Get(t, "/conversation")
+ if last := bubbles(page); strings.Count(page, note) != 1 || strings.Index(page, note) < last {
+ t.Fatal("waiting messages lack the one note under the latest")
+ }
+ runner.Send(r.ctx, "rep", wire.FrameReply, wire.Reply{TurnID: busy.Turn.ID, Attempt: 1, Text: "first"})
+ f := r.batchFrame(runner, batch, "alpha", "bravo", "charlie")
+ if page = r.inst.Get(t, "/conversation"); strings.Contains(page, note) {
+ t.Fatal("the note stayed after the turn picked the messages up")
+ }
+ bubbles(page)
+ runner.Send(r.ctx, "ab", wire.FrameAck, wire.Ack{ID: f.ID})
+ r.turnIs(batch, wire.TurnRunning)
+ if page = r.inst.Get(t, "/conversation"); strings.Contains(page, note) {
+ t.Fatal("the note came back while the turn runs")
+ }
+ bubbles(page)
+}
diff --git a/internal/thintest/instance_contract_test.go b/internal/thintest/instance_contract_test.go
index e8c2c16c..de46a1b6 100644
--- a/internal/thintest/instance_contract_test.go
+++ b/internal/thintest/instance_contract_test.go
@@ -219,7 +219,7 @@ func TestSendIdempotency(t *testing.T) {
}
// Messages sent while a turn runs join one queued turn and reach the
-// coordinator as one frame.
+// coordinator as one frame, each set apart.
func TestQueuedMessagesJoinOneTurn(t *testing.T) {
r := newRig(t)
runner := r.dial(0)
@@ -240,7 +240,7 @@ func TestQueuedMessagesJoinOneTurn(t *testing.T) {
t.Fatal(err)
}
cmd := body.(*wire.MessageCommand)
- if cmd.TurnID != second.Turn.ID || cmd.Text != "two\n\nthree" || len(cmd.Tail) != 2 || cmd.Tail[0].Text != "one" || cmd.Tail[1].Role != wire.RoleCoordinator {
+ if cmd.TurnID != second.Turn.ID || cmd.Text != "[Equipo: the person sent 2 messages while you were busy, oldest first. Each is a separate message; answer them together in one reply.]\n\nMessage 1 of 2:\ntwo\n\nMessage 2 of 2:\nthree" || len(cmd.PersonText) != 2 || len(cmd.Tail) != 2 || cmd.Tail[0].Text != "one" || cmd.Tail[1].Role != wire.RoleCoordinator {
t.Fatalf("joined command %+v", cmd)
}
}