oficina / equipo Public

Merge main into paste-box

Brings in browser-timing and turn-batching (b6c6268). budgets.txt:
headless test lines to 8652, measured with both.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 0b84f7d727873aeefebce72e3c93fa739ebe9028 parent 4a3b5b9parent b6c6268
18 files changed, +1,106 −52
  • .rastrillo/budgets.txt +3 −3
  • docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md +1 −0
  • docs/superpowers/plans/TURNBATCH-PROGRESS.md +98 −0
  • docs/superpowers/specs/2026-11-11-equipo-turn-batching.md +133 −0
  • internal/equipo/chat/attachments.go +9 −6
  • internal/equipo/chat/runner.go +5 −1
  • internal/equipo/chat/store.go +107 −7
  • internal/equipo/chat/stream.go +8 −1
  • internal/equipo/chat_page.go +5 −1
  • internal/equipo/copy.go +1 −0
  • internal/equipo/static/chat-stream.js +2 −1
  • internal/equipo/templates/chat.html +1 −1
  • internal/fakeclaude/fake.go +34 −1
  • internal/headless/batching_test.go +188 −0
  • internal/thintest/batching_contract_test.go +429 −0
  • internal/thintest/instance_contract_test.go +2 −2
  • internal/thintest/instant_browser_test.go +5 −0
  • internal/thintest/thinking_browser_test.go +75 −28

CI passed — run details

diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index 4288d9f9..eb0e78d0 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -49,7 +49,7 @@ perf GET /api/v1/notebook skip Thin v1 person API: bearer-only JSON for devices;
perf GET /api/v1/thinking skip Thin v1 person API: bearer-only JSON for devices; the browser reads thinking words on /settings/thinking.
perf GET /api/v1/tasks skip Thin v1 person API: bearer-only JSON for devices; the browser reads tasks through /tasks.
perf GET /api/v1/tasks/{id} skip Thin v1 person API: bearer-only JSON for devices; the browser reads a task through /tasks/{id}.
-size internal/equipo/chat 14050 - The re-run ruling (recheckMayMerge, refreshAfterRecheck, about 70 lines); measured 13981. Merge authority thin v1 adds the gate's store side (mergeauth.go: authorizeMerge before dispatch and at each hub request, the fence for runners below the merge-facts protocol, the ask card in Equipo's words, the ships question, receipts with Undo, the policy tool and API, about 1000 lines); the gate is pure, in internal/equipo/mergegate, but its inputs and audit must be read and written inside the store's transactions. Measured 13204. Mac recheck runs a waiting task's needs_macos checks again when a Mac that fits arrives (macrecheck.go, about 90 lines); measured 12485. Spend 1 merged onto Projects UX: measured 12376 with both. Spend 1 adds a task's spend from its usage rows (TaskSpend, about 60 lines) and the usage rows' round; measured 12047. Projects UX adds per-person project stars with the auto-star reconciliation, the person's and the coordinator's star_project (stars.go, about 210 lines) and the project's own repository in its view; measured 12206. Claude's sign-in by a link adds the code route beside the token's in SendSecret, the sign-in prompt and the kind it becomes (about 40 lines); measured 11933. Mac runners slices A and B add per-runner mailboxes, placement, withdrawal, the offline rule, the runners view, transfers and publication (runners.go, transfers.go, about 1100 lines). Composer attachments add uploads, the message link, the mailbox relay with chunk frames hydrated from the stored file, and serving (attachments.go, attachments_http.go, about 330 lines); the link and relay run inside the send and dispatch transactions, so they live beside them; sniffing and stripping are pure, in internal/attach. Measured 10292. Merged with UX1 thinking words (f2602d3), measured 9801. Housekeeping slice 1 adds the loop's ledger and state machine, the housekeeping principal's checks inside the shared store functions, reservations, Pause, quiet hours, the digest, claim recovery and the API (housekeeping.go, housekeeping_control.go, housekeeping_http.go, about 1,350 lines); the checks must run inside the store's transactions, so they live beside them; the detectors themselves are pure, in internal/equipo/housekeeping. Measured 9637. Thin v1 UX1 thinking words adds the per-person set and its API (thinking.go, about 100 lines); measured 8305. Connections slice 1 review round 2: the mutation ledger matches record_task by subject only and refuses an ambiguous call with the earlier operations, the preference and forget (about 120 lines); measured 8236. Thin v1 UX1 round 3 adds Equipo combining duplicate tasks reversibly (duplicates.go: detection, the in-transaction fold checks, fold, Undo, about 400 lines) and headlines on findings and steps (headline.go); measured 7898. Connections slice 1 adds connection records from hello and attempts, the connect mailbox, the API, usage rows and the turn's mutation ledger (connections.go and tools.go, about 600 lines); measured 7400 after merging UX1. Thin v1 UX1 adds step activity lines, duplicates and their fold, the coordinator at work on a task, project facts from the runner catalog and open merge cards for the pages (inner.go, about 330 lines); measured 6610 with slice 4c's review fixes. Thin v1 slice 4c adds the merge policy, the merge card, the rebase round and duplicate reports (merge.go, about 380 lines). Thin v1 instance core: conversation, projects, tasks, review and, from slice 4b, questions to the specialists (questions.go, about 470 lines) share one store, transaction and event log; splitting would export the transaction internals. Measured 5514 source lines; revisit at the slice 7 sweep.
+size internal/equipo/chat 14100 - Turn batching adds turnText, the frame fit (fitTail, batchFull) and the stranded-turn recovery in sync (about 115 lines); measured 14095. The re-run ruling (recheckMayMerge, refreshAfterRecheck, about 70 lines); measured 13981. Merge authority thin v1 adds the gate's store side (mergeauth.go: authorizeMerge before dispatch and at each hub request, the fence for runners below the merge-facts protocol, the ask card in Equipo's words, the ships question, receipts with Undo, the policy tool and API, about 1000 lines); the gate is pure, in internal/equipo/mergegate, but its inputs and audit must be read and written inside the store's transactions. Measured 13204. Mac recheck runs a waiting task's needs_macos checks again when a Mac that fits arrives (macrecheck.go, about 90 lines); measured 12485. Spend 1 merged onto Projects UX: measured 12376 with both. Spend 1 adds a task's spend from its usage rows (TaskSpend, about 60 lines) and the usage rows' round; measured 12047. Projects UX adds per-person project stars with the auto-star reconciliation, the person's and the coordinator's star_project (stars.go, about 210 lines) and the project's own repository in its view; measured 12206. Claude's sign-in by a link adds the code route beside the token's in SendSecret, the sign-in prompt and the kind it becomes (about 40 lines); measured 11933. Mac runners slices A and B add per-runner mailboxes, placement, withdrawal, the offline rule, the runners view, transfers and publication (runners.go, transfers.go, about 1100 lines). Composer attachments add uploads, the message link, the mailbox relay with chunk frames hydrated from the stored file, and serving (attachments.go, attachments_http.go, about 330 lines); the link and relay run inside the send and dispatch transactions, so they live beside them; sniffing and stripping are pure, in internal/attach. Measured 10292. Merged with UX1 thinking words (f2602d3), measured 9801. Housekeeping slice 1 adds the loop's ledger and state machine, the housekeeping principal's checks inside the shared store functions, reservations, Pause, quiet hours, the digest, claim recovery and the API (housekeeping.go, housekeeping_control.go, housekeeping_http.go, about 1,350 lines); the checks must run inside the store's transactions, so they live beside them; the detectors themselves are pure, in internal/equipo/housekeeping. Measured 9637. Thin v1 UX1 thinking words adds the per-person set and its API (thinking.go, about 100 lines); measured 8305. Connections slice 1 review round 2: the mutation ledger matches record_task by subject only and refuses an ambiguous call with the earlier operations, the preference and forget (about 120 lines); measured 8236. Thin v1 UX1 round 3 adds Equipo combining duplicate tasks reversibly (duplicates.go: detection, the in-transaction fold checks, fold, Undo, about 400 lines) and headlines on findings and steps (headline.go); measured 7898. Connections slice 1 adds connection records from hello and attempts, the connect mailbox, the API, usage rows and the turn's mutation ledger (connections.go and tools.go, about 600 lines); measured 7400 after merging UX1. Thin v1 UX1 adds step activity lines, duplicates and their fold, the coordinator at work on a task, project facts from the runner catalog and open merge cards for the pages (inner.go, about 330 lines); measured 6610 with slice 4c's review fixes. Thin v1 slice 4c adds the merge policy, the merge card, the rebase round and duplicate reports (merge.go, about 380 lines). Thin v1 instance core: conversation, projects, tasks, review and, from slice 4b, questions to the specialists (questions.go, about 470 lines) share one store, transaction and event log; splitting would export the transaction internals. Measured 5514 source lines; revisit at the slice 7 sweep.
perf GET /api/v1/questions/{id} skip Thin v1 person API: bearer-only JSON for devices; the browser reads questions on /tasks/{id}.
perf GET /api/v1/steps/{id}/log skip Thin v1 person API: bearer-only JSON for devices; the browser shows the log tail on /tasks/{id}.
perf GET /api/v1/connections/preference skip Connections slice 1 person API: bearer-only JSON for devices; the browser shows the preference on /conversation/connections.
@@ -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 - 8464 The paste box adds its browser drive (browser_paste_test.go, about 130 lines: streaming, copy text, keyboard, scripts off); measured 8464. 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 - 13197 The browser lane merged onto the ship buttons: measured 13197. The ship buttons add their contract and browser tests (ships_buttons_test.go, ships_buttons_browser_test.go, about 190 lines); measured 13196. 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 - 8652 The paste box merged onto turn batching: measured 8652. The paste box adds its browser drive (browser_paste_test.go, about 130 lines: streaming, copy text, keyboard, scripts off); measured 8464. 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. Turn batching merged onto the browser lane: measured 8523. 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) and TestHeadlessBatchAfterRefusedReply (the real runner reconnects after a refused reply), about 190 lines; measured 8518. 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 - 13678 Turn batching merged onto the ThinkingCycles clock fix (the drive takes a still clock and the page's record of each phrase, about 50 lines): measured 13678. Turn batching merged onto the browser lane: measured 13631. Turn batching adds its contracts (the crash between turns, the stranded recovery, failed, cancelled, interrupted and retried turns, the cancelled batch, the note clearing, batches split to fit one frame and the failed batch's note; about 430 lines); measured 13630 with the ship buttons merged. The ship buttons add their contract and browser tests (ships_buttons_test.go, ships_buttons_browser_test.go, about 190 lines); measured 13196. 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/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
index ca4dcff2..a87690c6 100644
--- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
+++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
@@ -5995,6 +5995,7 @@ records remain unchanged.
| `teams.undo` | Undo | Settings UX pass (Paul, 2026-11-11): Teams, after Forget | Runtime; COPY ACCEPTED BY DELEGATION (Astra, 2026-11-11) |
| `chat.activity.star_project` | Starring a project… | Coordinator activity (projects-ux) | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-11) |
| `chat.queued` | Waiting its turn | Conversation: the note under a message sent while a turn runs (thinking-stale hot fix) | Runtime; COPY ACCEPTED BY DELEGATION (Astra, 2026-11-11) |
+| `chat.failed_many` | The coordinator could not answer these messages. | Conversation: the note when a turn that covered several messages fails (turn batching) | Runtime; COPY ACCEPTED BY DELEGATION (Astra, 2026-11-11) |
| `work.reason.provider_failed` | the model connection failed | Tasks: why a step stopped (projects-ux) | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-11) |
| `work.reason.provider_rejected` | the model service declined the request | Tasks: why a step stopped (projects-ux) | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-11) |
| `work.reason.policy_rejected` | Equipo's rules blocked it | Tasks: why a step stopped (projects-ux) | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-11) |
diff --git a/docs/superpowers/plans/TURNBATCH-PROGRESS.md b/docs/superpowers/plans/TURNBATCH-PROGRESS.md
new file mode 100644
index 00000000..b5e2a8f1
--- /dev/null
+++ b/docs/superpowers/plans/TURNBATCH-PROGRESS.md
@@ -0,0 +1,98 @@
+# Turn batching: progress
+
+Branch `turn-batching` from main 03f8a91. Design note:
+`docs/superpowers/specs/2026-11-11-equipo-turn-batching.md`.
+
+## Done
+
+1. **Finding.** The instance already batched messages sent during a turn
+ into one next turn (64cd2ce). The gap was that the messages were not
+ distinct: `Text` was the words joined by blank lines, and the files
+ were one list for the whole turn.
+2. **Change** (instance only, no wire, fixture or migration change):
+ `turnText` sets each message of a batch apart, with its files. `sync`
+ starts a stranded queued turn.
+3. **Failing first.** `TestHeadlessTurnBatching` (real runner, fake CLI,
+ thintest instance) failed on main for the input check. The output is
+ in commit fd22d42.
+4. **Contracts** (`internal/thintest/batching_contract_test.go`, protocol
+ 1 runner): `TestBatchCrashBetweenTurns`, `TestBatchStrandedRecovers`,
+ `TestBatchAfterTurnEnds` (failed, cancelled, interrupted),
+ `TestBatchWaitsForRetriedTurn`, `TestBatchCancelledWhileWaiting`,
+ `TestBatchMarkerClearsTogether`, `TestBatchSplitsToFitTheFrame`, and
+ headless `TestHeadlessBatchAfterRefusedReply` (real runner).
+5. **Astra round 1** (gpt-6-astra, high): REQUEST CHANGES, three
+ Important findings.
+ - Oversized batches could exceed the 256 KiB frame, and the runner
+ would refuse them on every resend. Fixed: batches split to fit, the
+ tail is trimmed to fit, and a waiting batch is kept out of an
+ earlier batch's tail.
+ - A store error on a runner frame closed with `CloseRevoked`, which
+ stops a real runner. Fixed: the close is now 1011 (retryable);
+ `ErrForbidden` still closes `CloseRevoked`.
+ - Queued marker on each bubble: this is a product question, left for
+ the controller. The branch keeps the single note from the
+ thinking-stale fix.
+6. **Rulings.** No hold between turns, and the single note stays.
+ `chat.failed_many` ("The coordinator could not answer these
+ messages.") is added for a failed batch, on the page and from the
+ event stream. Delegated Astra copy pass: KEEP, marked COPY ACCEPTED BY
+ DELEGATION (Astra, 2026-11-11) in copy.go and the Plan 3 inventory.
+ Mutations: drop the page's batch case and `TestBatchFailedSaysThemAll`
+ dies ("a failed batch lacks the note for its messages"); drop the
+ script's and `TestBrowserInstantThinkingQueued` dies ("waiting for the
+ failed batch's note").
+7. **Merged origin/main** 42a31cb (ship buttons). The budgets conflict
+ was resolved by keeping both reasons (internal/thintest at 13600, then 13630 with the plural note).
+
+## Mutations
+
+Each guard was broken once, with the targeted runs below, then restored.
+Command: `CGO_ENABLED=0 nice -n 10 go test ./internal/thintest -run
+'^(TestBatch|TestQueuedMessagesJoinOneTurn$)'` and, where shown, `go test
+./internal/headless -run '^TestHeadlessTurnBatching$'`.
+
+| Guard | Mutation | Died |
+|---|---|---|
+| Ordering | dispatch reads the batch `seq DESC` | thintest: CrashBetweenTurns "batch lacks alpha in place", StrandedRecovers and others; headless: "turn input lacks Message 1 of 3" |
+| Distinct messages | `turnText` joins the words as before | the same tests in both packages |
+| One next turn | every message opens a turn of its own (`fresh := true`) | thintest: "message 2: ... MessageIDs:[one id]" in every TestBatch |
+| One at a time (send) | a message dispatches beside the running turn | thintest: "message 2" in every TestBatch |
+| One at a time (end and recovery) | `dispatchNext` ignores a turn in flight | thintest: CrashBetweenTurns, the batch frame arrived during the held turn |
+| Atomic end and next | `reply` commits when the next dispatch fails | thintest: CrashBetweenTurns "the reply was acked with the next turn refused" |
+| Recovery | `sync` no longer calls `dispatchNext` | thintest: StrandedRecovers "no next turn" |
+| Marker clearing | the line's holder may be a turn that ended | thintest: MarkerClearsTogether "the note stayed after the turn picked the messages up" (headless survives: its runner acks at once) |
+| One note | every waiting bubble gets the note | thintest: MarkerClearsTogether; headless: "queued note not once under the latest message" |
+| Frame fit (split) | a batch never fills up | thintest: SplitsToFitTheFrame "12 large messages made batches of [one]" |
+| Frame fit (tail) | the tail is never trimmed | thintest: SplitsToFitTheFrame "message too big: read limited at 262145 bytes" |
+| Tail excludes waiting batches | the tail takes every other turn's messages | thintest: SplitsToFitTheFrame "batch 1's tail holds a message still waiting" |
+| Retryable close | a failed frame closes `CloseRevoked` again | headless: BatchAfterRefusedReply "runner stopped: runner credential refused" |
+
+## Spend (fake CLI, input tokens are prompt length / 4)
+
+| Case | Turns after the slow one | Input tokens |
+|---|---|---|
+| main, three messages during a slow turn | 1 | 102 |
+| this branch, the same | 1 | 154 (+52 for the batch line and headers) |
+| the same three words, each after the last reply | 3 | 2, 3, 3 |
+
+The fake does not model the fixed context every real turn pays (about
+17k input tokens on staging, 77% cached), so the third row understates
+real spend: three turns pay that context three times, and a batch pays
+it once. Usage stays per turn: one row for the batch turn and none for
+any single message (`TestHeadlessTurnBatching`).
+
+## Verification
+
+- Targeted: the contracts above, `TestQueuedMessagesJoinOneTurn`,
+ `TestCancel`, `TestMailboxResendAndGenerations`, `TestDrainAndRestart`,
+ `TestSecondaryRunnerSyncIgnored`, `TestContractAttachments`,
+ `TestContractStorageFullInWords`, the move-in contracts,
+ `TestContractConversation`, `TestSendIdempotency`, `TestChatPage`,
+ `TestReplacedConnectionFenced`, headless `6_quick_messages`.
+- Browser, one at a time: `TestBrowserInstantThinking*`,
+ `TestBrowserThinkingLinesClear`, `TestBrowserDraftStreamsFormatted`.
+ All pass.
+- `make budget`, vet, staticcheck on the changed packages, and
+ `TestReleaseCopyReviewed` with `EQUIPO_RELEASE_COPY_CHECK=1` (no UI
+ strings changed).
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..3781e591
--- /dev/null
+++ b/docs/superpowers/specs/2026-11-11-equipo-turn-batching.md
@@ -0,0 +1,133 @@
+# 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 on the instance, mostly in its 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.
+- **One frame each** (Astra round 1). A runner reads at most
+ `wire.MaxFrameBytes` (256 KiB) and refuses a larger frame every time it
+ is resent. Each message is up to 16 KiB and goes in twice (`Text` and
+ `PersonText`), JSON-escaped. A message joins the newest waiting batch
+ only while the batch's own part fits `batchRoom` (the frame less 64
+ KiB). Otherwise it starts the next batch, which goes after the first,
+ one turn at a time and in order. `dispatch` drops the oldest tail
+ messages until the command fits (`fitTail`). The tail never holds the
+ messages of a batch still waiting behind the one being sent.
+- **A failed runner frame is retryable** (Astra round 1). A store error
+ while applying a runner frame used to close the socket with
+ `CloseRevoked`, so a real runner stopped as if its credential had been
+ revoked. Now it closes with 1011 (internal error): the runner
+ reconnects with backoff and resends the unacked frame. `ErrForbidden`
+ keeps `CloseRevoked`. A credential revoked meanwhile is refused at the
+ handshake (403), and every runner version maps that to revoked. Old
+ runners treat any other close code as a reason to reconnect.
+
+## 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` |
+| The instance refuses the next turn (a store error) with a real runner | The reply rolls back and the socket closes 1011. The runner reconnects and resends the reply, and the batch goes once. | `TestHeadlessBatchAfterRefusedReply` |
+| Batch too big for one frame | It is split into several batches, sent one after another, in order. Each frame fits. | `TestBatchSplitsToFitTheFrame` |
+| 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.
+
+## Rulings (controller, 2026-11-11)
+
+1. **No hold.** A message sent while nothing runs starts its turn at
+ once. A fast first reply beats batching messages that arrive between
+ turns.
+2. **One note.** The single "Waiting its turn" note under the latest
+ waiting message stays, as the thinking-stale fix built it.
+3. **Plural failure.** A failed turn that covered more than one message
+ says `chat.failed_many`, "The coordinator could not answer these
+ messages." (Astra copy pass: KEEP). The page and the event stream
+ (`chat-stream.js`, from the turn's `message_ids`) both choose it.
+ `TestBatchFailedSaysThemAll` and `TestBrowserInstantThinkingQueued`
+ cover it.
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..15ff0ba4 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 {
@@ -259,8 +260,11 @@ func (t *txn) dispatch(r *turnRecord) error {
if len(mine) == 0 && r.Kind == wire.TurnPerson {
return ErrInvalid
}
+ // The tail is what went before: never this turn's messages, nor those
+ // of a batch still waiting behind it (a batch too big for one frame
+ // goes as several turns, one after another).
var prior []messageRecord
- if err := t.db.Where("person = ? AND turn_id <> ?", r.Person, r.ID).Order("seq DESC").Limit(wire.MaxTailMessages).Find(&prior).Error; err != nil {
+ if err := t.db.Where("person = ? AND turn_id <> ? AND turn_id NOT IN (SELECT id FROM chat_turns WHERE person = ? AND dispatched = ? AND state = ?)", r.Person, r.ID, r.Person, false, wire.TurnQueued).Order("seq DESC").Limit(wire.MaxTailMessages).Find(&prior).Error; err != nil {
return err
}
tail := make([]wire.TailMessage, 0, len(prior))
@@ -274,10 +278,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,13 +290,100 @@ 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 {
+ cmd := wire.MessageCommand{Person: r.Person, TurnID: r.ID, Attempt: r.Attempt, Kind: r.Kind, Text: turnText(texts, attached), PersonText: own, Tail: tail, Attachments: files}
+ if cmd.Tail, err = fitTail(cmd); err != nil {
return err
}
- return nil
+ return t.command(r.Person, wire.FrameMessage, cmd)
+}
+
+// frameRoom is what a message command's body may take: the frame limit
+// less its envelope (id and type).
+const frameRoom = wire.MaxFrameBytes - 1<<10
+
+// fitTail drops the oldest tail messages until the command fits one
+// frame: a runner refuses a larger frame, every time it is resent.
+func fitTail(cmd wire.MessageCommand) ([]wire.TailMessage, error) {
+ raw, err := json.Marshal(cmd)
+ if err != nil {
+ return nil, err
+ }
+ size, tail := len(raw), cmd.Tail
+ for len(tail) > 0 && size > frameRoom {
+ one, err := json.Marshal(tail[0])
+ if err != nil {
+ return nil, err
+ }
+ size, tail = size-len(one)-1, tail[1:]
+ }
+ return tail, nil
+}
+
+// batchRoom bounds the person's own part of a batch (its words twice, as
+// Text and PersonText, and its files), leaving room for answer prefixes
+// and some tail.
+const batchRoom = wire.MaxFrameBytes - 64<<10
+
+// batchFull reports whether a queued turn has no room left for one more
+// message: its text and its number of files. A full batch stays as it is;
+// the message starts the next batch, which goes after it.
+func (t *txn) batchFull(turn, text string, files int) (bool, error) {
+ var rows []messageRecord
+ if err := t.db.Select("id", "text").Where("turn_id = ? AND role = ?", turn, wire.RolePerson).Find(&rows).Error; err != nil {
+ return false, err
+ }
+ ids := make([]string, 0, len(rows))
+ texts := []string{text}
+ for _, m := range rows {
+ ids, texts = append(ids, m.ID), append(texts, m.Text)
+ }
+ var held int64
+ if len(ids) > 0 {
+ if err := t.db.Model(&fileRecord{}).Where("message_id IN ?", ids).Count(&held).Error; err != nil {
+ return false, err
+ }
+ }
+ size := 256 + 512*(int(held)+files)
+ for _, text := range texts {
+ raw, err := json.Marshal(text)
+ if err != nil {
+ return false, err
+ }
+ size += 2*len(raw) + 64
+ }
+ return size > batchRoom, 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
@@ -328,7 +420,8 @@ func bodyHash(text string) string {
}
// Send records a person message. While a turn is in flight, new messages
-// join one queued turn, which goes to the coordinator as a single frame.
+// join one queued turn, which goes to the coordinator as a single frame
+// (several, one turn after another, when they would not fit one).
func (s *Store) Send(ctx context.Context, person string, in wire.SendMessage) (out wire.Sent, created bool, err error) {
// A message is words, attachments or both.
if in.Text = strings.TrimSpace(in.Text); in.Text == "" && len(in.Attachments) == 0 || len(in.Text) > wire.MaxMessageBytes || !utf8.ValidString(in.Text) || strings.ContainsRune(in.Text, 0) {
@@ -378,11 +471,18 @@ func (t *txn) send(person, key, text string, files []string, before func(message
}
now := t.now()
var turn turnRecord
- err = t.db.Where("person = ? AND dispatched = ? AND state = ? AND coalesce(kind, '') = ''", person, false, wire.TurnQueued).Order("created_at, id").First(&turn).Error
+ // The message joins the newest waiting batch, unless that batch would
+ // no longer fit one frame.
+ err = t.db.Where("person = ? AND dispatched = ? AND state = ? AND coalesce(kind, '') = ''", person, false, wire.TurnQueued).Order("created_at DESC, id DESC").First(&turn).Error
fresh := errors.Is(err, gorm.ErrRecordNotFound)
if err != nil && !fresh {
return out, false, err
}
+ if !fresh {
+ if fresh, err = t.batchFull(turn.ID, text, len(files)); err != nil {
+ return out, false, err
+ }
+ }
if fresh {
turn = turnRecord{ID: newID("t_"), Person: person, State: wire.TurnQueued, Attempt: 1, CreatedAt: now, UpdatedAt: now}
if err = t.db.Create(&turn).Error; err != nil {
diff --git a/internal/equipo/chat/stream.go b/internal/equipo/chat/stream.go
index 821ef57a..691b253a 100644
--- a/internal/equipo/chat/stream.go
+++ b/internal/equipo/chat/stream.go
@@ -208,9 +208,16 @@ func (rc *runnerConn) read(ctx context.Context) websocket.StatusCode {
return wire.CloseSuperseded
case errors.Is(err, ErrInvalid):
return websocket.StatusPolicyViolation
- case err != nil && !errors.Is(err, ErrNotFound):
+ case errors.Is(err, ErrForbidden):
rc.log("runner frame", err)
return wire.CloseRevoked
+ case err != nil && !errors.Is(err, ErrNotFound):
+ // The frame's transaction rolled back and it stays unacked. The
+ // runner reconnects and sends it again; a credential revoked
+ // meanwhile is refused at the handshake (403), which is how
+ // every runner learns it is revoked.
+ rc.log("runner frame", err)
+ return websocket.StatusInternalError
}
if f.Durable() {
ack, _ := wire.NewFrame("a"+f.ID, wire.FrameAck, wire.Ack{ID: f.ID})
diff --git a/internal/equipo/chat_page.go b/internal/equipo/chat_page.go
index f01b82fd..e7a28367 100644
--- a/internal/equipo/chat_page.go
+++ b/internal/equipo/chat_page.go
@@ -306,9 +306,13 @@ func (a *application) chatPage(w http.ResponseWriter, r *http.Request) {
}
if latest != nil && (latest.State == wire.TurnFailed || latest.State == wire.TurnCancelled) {
key := "chat." + latest.State
- if latest.Reason == wire.ReasonStorageFull {
+ switch {
+ case latest.Reason == wire.ReasonStorageFull:
// The runner had no room for an attachment: said in words.
key = "chat.failed_storage"
+ case latest.State == wire.TurnFailed && len(latest.MessageIDs) > 1:
+ // The turn carried a batch: messages sent while another ran.
+ key = "chat.failed_many"
}
view.Ended = &chatEnded{ID: latest.ID, Key: key}
}
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go
index 3169e44c..e901af82 100644
--- a/internal/equipo/copy.go
+++ b/internal/equipo/copy.go
@@ -567,6 +567,7 @@ var pageCopy = map[string]string{
"conversation.thinking": "Thinking",
"chat.offline": "Your runner is offline. Messages wait here until it is back.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
"chat.failed": "The coordinator could not answer this message.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.failed_many": "The coordinator could not answer these messages.", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-11)
"chat.cancelled": "Stopped.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
"chat.activity.thinking": "Thinking", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
"chat.activity.status": "Checking your projects…", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
diff --git a/internal/equipo/static/chat-stream.js b/internal/equipo/static/chat-stream.js
index 25886291..7ce58740 100644
--- a/internal/equipo/static/chat-stream.js
+++ b/internal/equipo/static/chat-stream.js
@@ -892,7 +892,8 @@
if (v.kind) return;
var note = template("equipo-ended-template");
note.dataset.ended = v.id;
- note.querySelector("p").textContent = v.state !== "failed" ? form.dataset.cancelled : v.reason === "runner_storage_full" && form.dataset.failedStorage ? form.dataset.failedStorage : form.dataset.failed;
+ // A batch (messages sent while another turn ran) says them all.
+ note.querySelector("p").textContent = v.state !== "failed" ? form.dataset.cancelled : v.reason === "runner_storage_full" && form.dataset.failedStorage ? form.dataset.failedStorage : (v.message_ids || []).length > 1 && form.dataset.failedMany ? form.dataset.failedMany : form.dataset.failed;
feed.append(note);
scroll();
}
diff --git a/internal/equipo/templates/chat.html b/internal/equipo/templates/chat.html
index f1919dda..9b8d8a4c 100644
--- a/internal/equipo/templates/chat.html
+++ b/internal/equipo/templates/chat.html
@@ -45,7 +45,7 @@
</div>
<div equipo-announcements role="status" aria-live="polite" aria-atomic="false"></div>
<div id="chat-composer">
-<form id="composer" equipo-form equipo-composer method="post" action="/conversation" data-failed="{{copy "chat.failed"}}" data-failed-storage="{{copy "chat.failed_storage"}}" data-retry="{{copy "conversation.retry"}}" data-cancelled="{{copy "chat.cancelled"}}" data-upload="/conversation/attachments" data-max-files="5" data-max-bytes="10485760" data-too-large="{{copy "api.attachment_too_large"}}" data-heic="{{copy "api.attachment_heic"}}" data-too-many="{{copy "chat.attach.too_many"}}" data-upload-failed="{{copy "chat.attach.failed"}}" data-uploading="{{copy "chat.attach.uploading"}}" data-remove="{{copy "chat.attach.remove"}}">
+<form id="composer" equipo-form equipo-composer method="post" action="/conversation" data-failed="{{copy "chat.failed"}}" data-failed-many="{{copy "chat.failed_many"}}" data-failed-storage="{{copy "chat.failed_storage"}}" data-retry="{{copy "conversation.retry"}}" data-cancelled="{{copy "chat.cancelled"}}" data-upload="/conversation/attachments" data-max-files="5" data-max-bytes="10485760" data-too-large="{{copy "api.attachment_too_large"}}" data-heic="{{copy "api.attachment_heic"}}" data-too-many="{{copy "chat.attach.too_many"}}" data-upload-failed="{{copy "chat.attach.failed"}}" data-uploading="{{copy "chat.attach.uploading"}}" data-remove="{{copy "chat.attach.remove"}}">
<input type="hidden" name="request_id" value="{{.RequestID}}">
<div equipo-adder hidden><button type="button" equipo-plus aria-label="{{copy "chat.attach.add"}}" title="{{copy "chat.attach.add"}}" aria-haspopup="menu" aria-expanded="false" aria-controls="attach-menu">{{icon "plus"}}</button><div equipo-add-menu id="attach-menu" role="menu" aria-label="{{copy "chat.attach.add"}}" hidden><button type="button" role="menuitem" data-pick="image">{{icon "image"}}<span>{{copy "chat.attach.image"}}</span></button><button type="button" role="menuitem" data-pick="file">{{icon "file-text"}}<span>{{copy "chat.attach.file"}}</span></button></div><input type="file" data-picker="image" accept="image/*" multiple tabindex="-1" aria-hidden="true" equipo-visually-hidden><input type="file" data-picker="file" accept=".txt,.md,.markdown,.csv,.json,.log,.pdf,text/plain,text/markdown,text/csv,application/json,application/pdf" multiple tabindex="-1" aria-hidden="true" equipo-visually-hidden></div>
<div equipo-pill>
diff --git a/internal/fakeclaude/fake.go b/internal/fakeclaude/fake.go
index 41eafb31..b621acc0 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..20e24470
--- /dev/null
+++ b/internal/headless/batching_test.go
@@ -0,0 +1,188 @@
+package headless
+
+import (
+ "encoding/json"
+ "strings"
+ "testing"
+ "time"
+
+ "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
+}
+
+// TestHeadlessBatchAfterRefusedReply: when the instance cannot start the
+// next turn, the reply that ended the slow one rolls back with it. The
+// real runner is not told it was revoked: it reconnects, sends the reply
+// again once the instance can take it, and the batch goes once.
+func TestHeadlessBatchAfterRefusedReply(t *testing.T) {
+ env, inst, r := localEnv(t)
+ r.start(t)
+ s := open(t, env)
+ s.keep()
+ busy := s.send(t, "Take your time with this one. sleep:3000")
+ s.waitTurn(t, busy.Turn.ID, wire.TurnRunning)
+ a, b := s.send(t, "alpha first"), s.send(t, "bravo second")
+ db := inst.DB.Writer()
+ if _, err := db.Exec(`CREATE TRIGGER refuse_next BEFORE INSERT ON runner_commands WHEN NEW.kind = 'message' BEGIN SELECT RAISE(ABORT, 'refused'); END`); err != nil {
+ t.Fatal(err)
+ }
+ for deadline := time.Now().Add(time.Minute); strings.Count(inst.Logs(), "refused") < 2; time.Sleep(100 * time.Millisecond) {
+ if time.Now().After(deadline) {
+ t.Fatal("the reply was never refused twice")
+ }
+ }
+ select {
+ case err := <-r.done:
+ t.Fatalf("the runner stopped: %v", err)
+ default:
+ }
+ if st, err := env.Client.Turn(s.ctx, busy.Turn.ID); err != nil || st.State != wire.TurnRunning {
+ t.Fatalf("slow turn %+v %v while its successor is refused", st, err)
+ }
+ if _, err := db.Exec(`DROP TRIGGER refuse_next`); err != nil {
+ t.Fatal(err)
+ }
+ replyOf(t, s, busy.Turn.ID)
+ reply := replyOf(t, s, a.Turn.ID)
+ if b.Turn.ID != a.Turn.ID || !strings.Contains(reply.Text, "You sent 2 messages: 1/2 alpha first; 2/2 bravo second.") {
+ t.Fatalf("batch %s/%s answered %q", a.Turn.ID, b.Turn.ID, reply.Text)
+ }
+ if cmds := messageCommands(t, inst, a.Turn.ID); len(cmds) != 1 {
+ t.Fatalf("%d frames for the batch", len(cmds))
+ }
+}
diff --git a/internal/thintest/batching_contract_test.go b/internal/thintest/batching_contract_test.go
new file mode 100644
index 00000000..ef5e7a36
--- /dev/null
+++ b/internal/thintest/batching_contract_test.go
@@ -0,0 +1,429 @@
+package thintest
+
+import (
+ "context"
+ "fmt"
+ "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)
+}
+
+// Messages that would not fit one frame together go as several batches,
+// one turn after another, in order. Each frame fits (the runner reads at
+// most wire.MaxFrameBytes): the oldest tail goes first, and a later
+// batch's messages are never in an earlier one's tail.
+func TestBatchSplitsToFitTheFrame(t *testing.T) {
+ r := newRig(t)
+ runner := r.dial(0)
+ busy, err := r.client.Send(r.ctx, "one", "k0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ f, _, _ := runner.Expect(r.ctx, wire.FrameMessage)
+ runner.Send(r.ctx, "a0", wire.FrameAck, wire.Ack{ID: f.ID})
+ r.turnIs(busy.Turn.ID, wire.TurnRunning)
+ var texts []string
+ turns := map[string][]string{}
+ var order []string
+ for i := range 12 {
+ // Near the largest message, with characters JSON escapes (the
+ // person API reads at most twice the limit).
+ text := fmt.Sprintf("m%02d %s%s", i+1, strings.Repeat("x", wire.MaxMessageBytes-2008), strings.Repeat("<", 2000))
+ s, err := r.client.Send(r.ctx, text, fmt.Sprintf("kb%d", i))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, ok := turns[s.Turn.ID]; !ok {
+ order = append(order, s.Turn.ID)
+ }
+ turns[s.Turn.ID] = append(turns[s.Turn.ID], text)
+ texts = append(texts, text)
+ }
+ if len(order) < 2 || len(turns[order[0]]) < 2 {
+ t.Fatalf("12 large messages made batches of %v", order)
+ }
+ end := wire.Reply{TurnID: busy.Turn.ID, Attempt: 1, Text: "first"}
+ var got []string
+ for i, batch := range order {
+ runner.Send(r.ctx, fmt.Sprintf("rep%d", i), wire.FrameReply, end)
+ mf, body, err := runner.Expect(r.ctx, wire.FrameMessage)
+ if err != nil {
+ t.Fatalf("batch %d: %v", i+1, err)
+ }
+ cmd := body.(*wire.MessageCommand)
+ if cmd.TurnID != batch || len(cmd.PersonText) != len(turns[batch]) {
+ t.Fatalf("batch %d is %s with %d messages", i+1, cmd.TurnID, len(cmd.PersonText))
+ }
+ for _, m := range cmd.Tail {
+ for _, later := range order[i+1:] {
+ for _, text := range turns[later] {
+ if m.Text == text {
+ t.Fatalf("batch %d's tail holds a message still waiting", i+1)
+ }
+ }
+ }
+ }
+ if len(cmd.Tail) == 0 || cmd.Tail[len(cmd.Tail)-1].Text != end.Text {
+ t.Fatalf("batch %d's tail lost the newest reply", i+1)
+ }
+ got = append(got, cmd.PersonText...)
+ runner.Send(r.ctx, fmt.Sprintf("ab%d", i), wire.FrameAck, wire.Ack{ID: mf.ID})
+ r.turnIs(batch, wire.TurnRunning)
+ end = wire.Reply{TurnID: batch, Attempt: 1, Text: fmt.Sprintf("reply %d", i+1)}
+ }
+ if len(got) != len(texts) {
+ t.Fatalf("%d of %d messages reached the coordinator", len(got), len(texts))
+ }
+ for i := range texts {
+ if got[i] != texts[i] {
+ t.Fatalf("message %d out of place", i+1)
+ }
+ }
+}
+
+// A failed batch says the coordinator could not answer these messages; a
+// failed turn of one message still says this message.
+func TestBatchFailedSaysThemAll(t *testing.T) {
+ r := newRig(t)
+ runner := r.dial(0)
+ busy, queued := r.busyWithThree(runner)
+ batch := queued[0].Turn.ID
+ 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")
+ runner.Send(r.ctx, "ab", wire.FrameAck, wire.Ack{ID: f.ID})
+ runner.Send(r.ctx, "fb", wire.FrameTurn, wire.TurnReport{TurnID: batch, Attempt: 1, State: wire.TurnFailed, Reason: "provider_failed"})
+ r.turnIs(batch, wire.TurnFailed)
+ if page := r.inst.Get(t, "/conversation"); !strings.Contains(page, `data-ended="`+batch+`"><p>The coordinator could not answer these messages.</p>`) {
+ t.Fatal("a failed batch lacks the note for its messages")
+ }
+ one, err := r.client.Send(r.ctx, "delta", "kq6")
+ if err != nil {
+ t.Fatal(err)
+ }
+ of, _, _ := runner.Expect(r.ctx, wire.FrameMessage)
+ runner.Send(r.ctx, "a1", wire.FrameAck, wire.Ack{ID: of.ID})
+ runner.Send(r.ctx, "f1", wire.FrameTurn, wire.TurnReport{TurnID: one.Turn.ID, Attempt: 1, State: wire.TurnFailed, Reason: "provider_failed"})
+ r.turnIs(one.Turn.ID, wire.TurnFailed)
+ if page := r.inst.Get(t, "/conversation"); !strings.Contains(page, `data-ended="`+one.Turn.ID+`"><p>The coordinator could not answer this message.</p>`) {
+ t.Fatal("a failed single message lacks its note")
+ }
+}
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)
}
}
diff --git a/internal/thintest/instant_browser_test.go b/internal/thintest/instant_browser_test.go
index 05cbf4c2..88ad81f8 100644
--- a/internal/thintest/instant_browser_test.go
+++ b/internal/thintest/instant_browser_test.go
@@ -241,5 +241,10 @@ func TestBrowserInstantThinkingQueued(t *testing.T) {
// The first replies: the queued turn's line comes, the note goes.
runner.Send(r.ctx, "r-q1", wire.FrameReply, wire.Reply{TurnID: first, Attempt: 1, Text: "First done."})
p.wait(`document.querySelectorAll('[equipo-thinking]').length===1 && document.querySelector('[equipo-thinking]').dataset.turn===`+jsString(second)+` && !document.querySelector('[data-queued]')`, "the second turn's line, no note")
+ // The batch of two fails: its note says these messages, from the event.
+ bf := messageFrame(t, r, runner)
+ runner.Send(r.ctx, "a-q2", wire.FrameAck, wire.Ack{ID: bf.ID})
+ runner.Send(r.ctx, "f-q2", wire.FrameTurn, wire.TurnReport{TurnID: second, Attempt: 1, State: wire.TurnFailed, Reason: "provider_failed"})
+ p.wait(`(document.querySelector('[data-ended=`+jsString(second)+`] p')||{}).textContent===`+jsString("The coordinator could not answer these messages."), "the failed batch's note")
p.stayed("queued sends")
}
diff --git a/internal/thintest/thinking_browser_test.go b/internal/thintest/thinking_browser_test.go
index 800935b3..10b389b5 100644
--- a/internal/thintest/thinking_browser_test.go
+++ b/internal/thintest/thinking_browser_test.go
@@ -7,7 +7,6 @@ import (
"encoding/json"
"fmt"
"testing"
- "time"
"amadan.net/oficina/equipo/internal/wire"
"github.com/chromedp/cdproto/cdp"
@@ -100,13 +99,18 @@ func TestBrowserThinkingWords(t *testing.T) {
// TestBrowserThinkingCycles: Paul, 2026-11-09: "They could swap a touch
// less frequently, they're a bit frantic. There needs to be many more per
-// category so it takes a while before I see the same ones again." With a
-// fake clock: a situation's first phrase holds about 5 s, then a new one
-// every 6 to 8 s; the phrases come from a shuffled deck, none again until
-// all have shown, across two turns (a reload keeps only localStorage);
-// after the deck runs out the next is none of the last three; a new
-// activity switches to its own phrases at once; under reduced motion the
-// words still change.
+// category so it takes a while before I see the same ones again." A
+// situation's first phrase holds 5 s, then a new one every 6 to 8 s; the
+// phrases come from a shuffled deck, none again until all have shown,
+// across two turns (a reload keeps only localStorage); after the deck runs
+// out the next is none of the last three; a new activity switches to its
+// own phrases at once; under reduced motion the words still change.
+//
+// The page's clock stands still but for the test (clock below): each
+// phrase is held to just under its minimum while the phrase timer looks,
+// then to its maximum. The page records each phrase it draws with its
+// clock, and the dwell rule is judged from that record, never from how
+// long the test waited, so a slow machine cannot make a phrase go early.
func TestBrowserThinkingCycles(t *testing.T) {
r := newToolRig(t)
words, _ := r.client.Thinking(r.ctx)
@@ -117,50 +121,92 @@ func TestBrowserThinkingCycles(t *testing.T) {
}
}
js := func(v any) string { raw, _ := json.Marshal(v); return string(raw) }
+ // The runner keeps reading, so it answers the instance's pings (a
+ // websocket answers only while it reads) and its stream outlives the
+ // ping deadline however slow the machine is; nothing it is sent
+ // matters here.
+ go func() {
+ for {
+ if _, _, err := r.runner.Conn.Read(r.ctx); err != nil {
+ return
+ }
+ }
+ }()
+ // clock: Date.now is base + skew, both kept in sessionStorage so a
+ // reload goes on from the same time; it moves only when the test
+ // moves it. The phrase timer (chat-stream.js turns phrases from a
+ // 250 ms interval) looks every 50 ms here, which changes no dwell (the
+ // dwell is read from the clock), and __ticks counts its runs, so the
+ // test knows the timer has looked at the clock it set. __drawn is each
+ // phrase drawn: its turn, its text and the clock when it came in.
+ const clock = `(()=>{const real=Date.now.bind(Date);window.__base=Number(sessionStorage.getItem('base'))||real();sessionStorage.setItem('base',window.__base);window.__skew=Number(sessionStorage.getItem('skew')||0);Date.now=()=>window.__base+window.__skew;` +
+ `window.__ticks=0;const every=window.setInterval;window.setInterval=function(fn,ms,...rest){if(ms===250&&typeof fn==='function'){const f=fn;fn=function(){try{return f.apply(this,arguments)}finally{window.__ticks++}};ms=50}return every.call(window,fn,ms,...rest)};` +
+ `window.__drawn=[];const once=new WeakSet();new MutationObserver(ms=>{for(const m of ms)for(const e of m.target.querySelectorAll('[equipo-phrase] > [data-in]'))if(!once.has(e)&&once.add(e))window.__drawn.push({turn:e.closest('[equipo-thinking]')?.dataset.turn,text:e.textContent,at:Date.now()})}).observe(document,{childList:true,subtree:true});})()`
for _, motion := range []string{"no-preference", "reduce"} {
p := openInner(t, r.inst.URL, r.inst.Cookie(), 390, 844, true, "dark", motion)
p.do(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error {
- _, err := cdp.Call(ctx, target, page.AddScriptToEvaluateOnNewDocument, page.AddScriptToEvaluateOnNewDocumentParams{Source: `(()=>{const real=Date.now.bind(Date);window.__skew=Number(sessionStorage.getItem('skew')||0);Date.now=()=>real()+window.__skew;})()`})
+ _, err := cdp.Call(ctx, target, page.AddScriptToEvaluateOnNewDocument, page.AddScriptToEvaluateOnNewDocumentParams{Source: clock})
return err
}))
p.open("/conversation")
line := `document.querySelector('[equipo-thinking][data-turn="` + r.turn + `"]')`
phrase := line + `?.querySelector('[equipo-phrase] [data-in]')?.textContent`
- advance := func(ms int) {
+ drawn := `window.__drawn.filter(d=>d.turn===` + js(r.turn) + `)`
+ // age: the page's clock to ms after the shown phrase came in, by
+ // the page's record.
+ age := func(ms int) {
t.Helper()
- p.check(fmt.Sprintf(`(()=>{window.__skew+=%d;sessionStorage.setItem('skew',window.__skew);return true})()`, ms), "advance the clock")
+ p.check(fmt.Sprintf(`(()=>{const d=%s;window.__skew=d[d.length-1].at-window.__base+%d;sessionStorage.setItem('skew',window.__skew);window.__looked=window.__ticks;return true})()`, drawn, ms), "set the clock")
+ }
+ var seen []string
+ first := func(what string) {
+ t.Helper()
+ p.wait(js(think)+`.includes(`+phrase+`) && `+drawn+`.length>0`, what)
+ seen = append(seen, eval[string](p, phrase))
}
- p.wait(js(think)+`.includes(`+phrase+`)`, "the first thinking phrase")
- seen := []string{eval[string](p, phrase)}
- // The pace: the first holds past 4.5 s and goes by 5.5 s; then each
- // holds past 5.8 s and goes by 8.2 s.
+ // holds: at ms, once the phrase timer has looked, the same phrase.
holds := func(ms int, what string) {
t.Helper()
- advance(ms)
- time.Sleep(600 * time.Millisecond)
+ age(ms)
+ p.wait(`window.__ticks>window.__looked`, "the phrase timer looked")
p.check(phrase+`===`+js(seen[len(seen)-1]), what)
}
next := func(ms int) {
t.Helper()
- advance(ms)
+ age(ms)
p.wait(phrase+`!==`+js(seen[len(seen)-1])+` && `+js(think)+`.includes(`+phrase+`)`, fmt.Sprintf("phrase %d", len(seen)+1))
seen = append(seen, eval[string](p, phrase))
}
- holds(4500, motion+": the first phrase went before 5 s")
- next(1000)
- for i := 0; i < 3; i++ {
- holds(5800, motion+": a phrase went before 6 s")
- next(2400)
+ // cycle: the next phrase, held past just under 6 s, gone by 8 s.
+ cycle := func() {
+ t.Helper()
+ holds(5999, motion+": a phrase went before 6 s")
+ next(8000)
+ }
+ // dwelt: the page's record of this page's phrases is seen[from:],
+ // in order; the first came in 5 s after the one before it, each
+ // later one 6 to 8 s after.
+ dwelt := func(from int) {
+ t.Helper()
+ if bad := eval[string](p, `(()=>{const d=`+drawn+`,want=`+js(seen[from:])+`;if(JSON.stringify(d.map(x=>x.text))!==JSON.stringify(want))return 'drawn '+JSON.stringify(d.map(x=>x.text));for(let i=1;i<d.length;i++){const g=d[i].at-d[i-1].at,min=i===1?5000:6000,max=i===1?5000:8000;if(g<min||g>max)return 'phrase '+(i+1)+' came '+g+' ms after the one before'}return ''})()`); bad != "" {
+ t.Fatalf("%s: %s", motion, bad)
+ }
}
+ first("the first thinking phrase")
+ holds(4999, motion+": the first phrase went before 5 s")
+ next(5000)
for len(seen) < 20 {
- next(8100)
+ cycle()
}
+ dwelt(0)
// A new turn: the page again, nothing kept but localStorage.
p.do(chromedp.Reload())
- p.wait(js(think)+`.includes(`+phrase+`)`, "the thinking phrase after the reload")
- seen = append(seen, eval[string](p, phrase))
+ from := len(seen)
+ first("the thinking phrase after the reload")
+ holds(4999, motion+": the first phrase after the reload went before 5 s")
+ next(5000)
for len(seen) < len(think) {
- next(8100)
+ cycle()
}
distinct := map[string]bool{}
for _, s := range seen {
@@ -171,12 +217,13 @@ func TestBrowserThinkingCycles(t *testing.T) {
}
// The deck ran out: the next is none of the last three.
last := seen[len(seen)-3:]
- next(8100)
+ cycle()
for _, l := range last {
if seen[len(seen)-1] == l {
t.Fatalf("%s: %q again straight after the deck ran out", motion, l)
}
}
+ dwelt(from)
// A new activity: its own phrases at once.
if err := r.runner.Send(r.ctx, "cyc-read-"+motion, wire.FrameActivity, wire.ActivityReport{TurnID: r.turn, Attempt: 1, Kind: wire.ActivityTool, Tool: wire.ToolReadFile}); err != nil {
t.Fatal(err)