Merge main into draft-stream-timing
Brings in turn-batching, runner-startup-logs and paste-box (d309188). budgets.txt: headless test lines to 8679 and thintest to 13685, measured with both.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
44 files changed,
+2,482
−96
.rastrillo/budgets.txt+4 −4cmd/equipo-runner/main.go+21 −0cmd/equipo-runner/main_test.go+37 −0docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md+63 −0docs/superpowers/plans/TURNBATCH-PROGRESS.md+98 −0docs/superpowers/specs/2026-11-11-equipo-turn-batching.md+133 −0internal/chatmarkdown/draft.go+38 −3internal/chatmarkdown/draft_test.go+55 −7internal/chatmarkdown/markdown.go+53 −4internal/chatmarkdown/markdown_test.go+68 −5internal/equipo/chat/attachments.go+9 −6internal/equipo/chat/runner.go+5 −1internal/equipo/chat/store.go+107 −7internal/equipo/chat/stream.go+8 −1internal/equipo/chat_draft.go+1 −2internal/equipo/chat_page.go+5 −1internal/equipo/copy.go+10 −0internal/equipo/render.go+1 −2internal/equipo/static/chat-stream.js+2 −1internal/equipo/static/equipo.css+27 −0internal/equipo/static/paste.js+56 −0internal/equipo/templates/chat.html+1 −1internal/equipo/templates/chrome.html+1 −1internal/fakeclaude/fake.go+36 −3internal/fakeclaude/markdown.go+12 −3internal/headless/batching_test.go+188 −0internal/headless/browser_paste_test.go+129 −0internal/plan3test/conversation_draft_test.go+1 −1internal/runner/thin/capabilities.go+20 −3internal/runner/thin/claude.go+2 −1internal/runner/thin/contract_test.go+2 −2internal/runner/thin/link.go+37 −6internal/runner/thin/mac.go+246 −13internal/runner/thin/probe_storm_test.go+77 −0internal/runner/thin/procgroup_other.go+12 −0internal/runner/thin/procgroup_unix.go+29 −0internal/runner/thin/procgroup_unix_test.go+112 −0internal/runner/thin/run.go+69 −15internal/runner/thin/startup_logs_test.go+204 −0internal/runner/thin/voice_test.go+17 −0internal/thintest/batching_contract_test.go+429 −0internal/thintest/instance_contract_test.go+2 −2internal/thintest/instant_browser_test.go+5 −0scripts/runner-reference-allowlist.json+50 −1
CI passed — run details
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index fb9b02cb..269a9bf4 100644 |
| --- a/.rastrillo/budgets.txt |
| +++ b/.rastrillo/budgets.txt |
| @@ -34,7 +34,7 @@ time internal/runner/provider 15s Plan 3 CI repair measured 10.346s for the full |
| perf GET /releases/* skip Verified runner release file downloads, not browser GET screens. |
| perf GET /install.sh skip Mac runners: the one-line bootstrap a terminal pipes to sh, not a browser screen. |
| time internal/runner/containment 15s Plan 3 loaded CI measured 10.817s; niced serial reruns measured 5.773s and 5.750s. The added coordinator mount check has no repeated launches to remove; 15s leaves 38 percent headroom for namespace, process-exit and recovery assertions. |
| -size internal/runner/thin 16250 - Merge authority thin v1 adds the review's measured change facts (facts.go: raw and numstat listings, modes, signing lines, the revert tree check, about 230 lines), the merge_request confirmation and the merge's provenance; measured 16196 with spend-1 merged. Spend 1 resumes a fix round in Engineering's kept session on its healthy connection (fixSession, fixPlan, fixPrompt, keptCommit, about 90 lines); measured 15873. Claude's sign-in by a link's review round 1 contains its setup-token in a recorded namespace (the contained terminal, its proven stop and the start's recovery before a home goes, about 130 lines); measured 15787. Claude's sign-in by a link adds the runner's own setup-token attempt, the code's sealed delivery with its crash boundaries and the shared token commit (signin.go, about 300 lines, less the removed terminal watcher); measured 15655. Claude setup tokens add sealed delivery, the token check, Check again and recovery (token.go, tokencheck.go, about 700 lines) beside the composer and Mac lines; measured 15239. Astra round 2 moves the attachment quota to admission: arriving files counted by declared size, admissions protecting a file until its message names it, room made from the oldest unprotected files, refusal as runner_storage_full, and a sweep that stops when protection cannot be read (about 150 lines); measured 12191. Mac runners slices A and B add protocol negotiation (link.go), the capability report, the start authorization, the pack relay (relay.go), the primary's publication, the worker executor (worker.go) and the test-build fake worker, about 2700 lines on the same step engine. Composer attachments add the chunked receipt with exactly-once writes, the read-only desk delivery and its checks (files.go, about 230 lines), image blocks and localImage inputs, the attachment read through read_file; measured 11736. Connections slice 1 Astra round 1 adds the Codex step path (codexstep.go: Engineering and Review on the pinned app-server in the implement and inspect containment, about 300 lines); measured 11345. Connections slice 1 (after Astra round 1) also keeps a durable ledger of each turn's write tools so a later attempt never repeats one (effects.go), the waiting state between attempts and usage rows per attempt, about 500 lines more; measured 10590 before gate 1d. Connections slice 1 adds the Codex coordinator beside the Claude one (codex.go: the pinned app-server over JSON-RPC in the converse containment, sharing the coordinator base, desk, tool socket and session table), the connection registry over the bindings with health and provider limits (conns.go), in-app sign-in attempts (connector.go) and turn failover and holding (failover.go), about 1500 lines; the pure parts (the choice function, limit parsing, the app-server client, the sign-in flows) live in internal/runner/connect. Measured 10097. Thin v1 UX1 adds step activity lines from the specialist's stream, the repository head and checks gate in the index and project-tagged notes (about 120 lines); measured 8615 with slice 4c's review fixes. Thin v1 slice 4c adds the merge step (mergestep.go, about 190 lines) and the rebase round beside the slice 4b ask fixes. Thin v1 slice 3 adds Engineering steps beside the coordinator: the durable step state and engine (step.go) and the executor that checks out the task tree, runs the CLI in the implement containment, commits and pushes (engineer.go), about 800 lines sharing the coordinator's launch, tool socket and account selection. Measured 5686 source lines. Splitting would export the launch internals; revisit at the slice 7 sweep. Slice 4 adds checks and review on a candidate (judge.go) and the merge watch (merge.go), about 800 lines, sharing the Engineer launch path; measured 6808, 7035 after review round 1 (branch head watch, deadlines, streamed outputs). Slice 4b keeps Engineering and Review sessions and answers the creator's questions from them (ask.go: kept-session and ask state, read-only git tools, the answer stream), about 700 lines on the same launch path. |
| +size internal/runner/thin 16573 - The paste box house rule merged onto the runner logs: measured 16573. The leftover helper's debug line adds 3 lines: measured 16572. The Mac host's hang fix and probe pacing add the process group and its kill (procgroup_unix.go, procgroup_other.go), the bounded wait for a command's output, and the untrusted report's rerun decision with its tool fingerprint (about 165 lines); measured 16569. Runner startup logs add the info lines a silent start is pinned to a phase by (startup phases, the Mac host's xcode-select and capability commands, slow-command warnings, the probes, and the link's connecting, hello and welcome lines: startPhase, openRunner, watchSlow and logged, about 155 lines); measured 16405. Merge authority thin v1 adds the review's measured change facts (facts.go: raw and numstat listings, modes, signing lines, the revert tree check, about 230 lines), the merge_request confirmation and the merge's provenance; measured 16196 with spend-1 merged. Spend 1 resumes a fix round in Engineering's kept session on its healthy connection (fixSession, fixPlan, fixPrompt, keptCommit, about 90 lines); measured 15873. Claude's sign-in by a link's review round 1 contains its setup-token in a recorded namespace (the contained terminal, its proven stop and the start's recovery before a home goes, about 130 lines); measured 15787. Claude's sign-in by a link adds the runner's own setup-token attempt, the code's sealed delivery with its crash boundaries and the shared token commit (signin.go, about 300 lines, less the removed terminal watcher); measured 15655. Claude setup tokens add sealed delivery, the token check, Check again and recovery (token.go, tokencheck.go, about 700 lines) beside the composer and Mac lines; measured 15239. Astra round 2 moves the attachment quota to admission: arriving files counted by declared size, admissions protecting a file until its message names it, room made from the oldest unprotected files, refusal as runner_storage_full, and a sweep that stops when protection cannot be read (about 150 lines); measured 12191. Mac runners slices A and B add protocol negotiation (link.go), the capability report, the start authorization, the pack relay (relay.go), the primary's publication, the worker executor (worker.go) and the test-build fake worker, about 2700 lines on the same step engine. Composer attachments add the chunked receipt with exactly-once writes, the read-only desk delivery and its checks (files.go, about 230 lines), image blocks and localImage inputs, the attachment read through read_file; measured 11736. Connections slice 1 Astra round 1 adds the Codex step path (codexstep.go: Engineering and Review on the pinned app-server in the implement and inspect containment, about 300 lines); measured 11345. Connections slice 1 (after Astra round 1) also keeps a durable ledger of each turn's write tools so a later attempt never repeats one (effects.go), the waiting state between attempts and usage rows per attempt, about 500 lines more; measured 10590 before gate 1d. Connections slice 1 adds the Codex coordinator beside the Claude one (codex.go: the pinned app-server over JSON-RPC in the converse containment, sharing the coordinator base, desk, tool socket and session table), the connection registry over the bindings with health and provider limits (conns.go), in-app sign-in attempts (connector.go) and turn failover and holding (failover.go), about 1500 lines; the pure parts (the choice function, limit parsing, the app-server client, the sign-in flows) live in internal/runner/connect. Measured 10097. Thin v1 UX1 adds step activity lines from the specialist's stream, the repository head and checks gate in the index and project-tagged notes (about 120 lines); measured 8615 with slice 4c's review fixes. Thin v1 slice 4c adds the merge step (mergestep.go, about 190 lines) and the rebase round beside the slice 4b ask fixes. Thin v1 slice 3 adds Engineering steps beside the coordinator: the durable step state and engine (step.go) and the executor that checks out the task tree, runs the CLI in the implement containment, commits and pushes (engineer.go), about 800 lines sharing the coordinator's launch, tool socket and account selection. Measured 5686 source lines. Splitting would export the launch internals; revisit at the slice 7 sweep. Slice 4 adds checks and review on a candidate (judge.go) and the merge watch (merge.go), about 800 lines, sharing the Engineer launch path; measured 6808, 7035 after review round 1 (branch head watch, deadlines, streamed outputs). Slice 4b keeps Engineering and Review sessions and answers the creator's questions from them (ask.go: kept-session and ask state, read-only git tools, the answer stream), about 700 lines on the same launch path. |
| time internal/thintest 180s Mac runners slices A and B add role, scoping, migration, placement, withdrawal, transfer and publication contracts, and Astra round 1 eight transition contracts (about 15s; the package measured 126s locally under load). Housekeeping slice 1 adds six contract tests (combine, Undo round trips and the race, Pause, auto-disable, quiet hours, restart while claimed; about 6s); the package measured 67.7s beside other packages locally, so 75s. Thin v1 slice 4c adds the merge, adoption, cancel and retention contract tests (CI measured 35.7s). Thin v1 contract tests: a real instance and a scripted runner per test, fixtures replayed against every request, frame and event. Slice 3 adds the task, step-sync and grant contracts; CI measured 14.805s. 30s keeps room for the slice 4 review contracts. UX1 adds step activity, task source and duplicates, coordinator merging and project facts (four contracts, about 6s); the package measured 34s locally under load, so 40s. UX1's inner screens gallery (two owners, seven tasks, every page) adds about 3s; measured 40.9s locally under load, so 60s. |
| time internal/runner/mac 30s Mac runners (Darwin worker): real process groups killed after a grace and proven gone (SIGTERM, SIGKILL, the marker sweep), and the probes run end to end with fake srt and xcodebuild, P6 killing a waiting test two seconds after it starts. About 6s alone; loaded CI measured 12.5s. |
| time internal/runner/thin 45s Thin v1 slice 4 review: real git repositories for the merge and squash checks, a stalled fetch, and a 16 MiB candidate streamed through the review diff and the checks pack (about 5s). Measured 17.8s locally under load. Slice 4b review adds a 16 MiB git output bound, an injected index-pack failure and stall (3s deadline) and held-answer tests; measured 30.3s locally under load. 45s keeps 33 percent headroom. |
| @@ -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 - 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 - 13251 The inner screens drive waits for the row menu's opacity transition to end before it reads the menu at rest (about 7 lines); measured 13251. The thinking cycles drive takes a still clock, a timer that is seen to look and the page's record of each phrase, so a slow machine cannot fail it (about 50 lines); measured 13244. 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 - 8679 The draft stream drive records each draw and the commit (about 27 lines) merged onto the paste box: measured 8679. 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 - 13685 The InnerScreens transition wait merged onto main: measured 13685. The inner screens drive waits for the row menu's opacity transition to end before it reads the menu at rest (about 7 lines); measured 13251. 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/cmd/equipo-runner/main.go b/cmd/equipo-runner/main.go| index ea79a86f..fc06f911 100644 |
| --- a/cmd/equipo-runner/main.go |
| +++ b/cmd/equipo-runner/main.go |
| @@ -7,6 +7,7 @@ import ( |
| "fmt" |
| "io" |
| "log/slog" |
| + "net/url" |
| "os" |
| "os/signal" |
| "syscall" |
| @@ -17,6 +18,7 @@ import ( |
| "amadan.net/oficina/equipo/internal/runner/mac" |
| runnersetup "amadan.net/oficina/equipo/internal/runner/setup" |
| "amadan.net/oficina/equipo/internal/runner/thin" |
| + "amadan.net/oficina/equipo/internal/wire" |
| "amadan.net/rastrillo/rastrillo" |
| ) |
| @@ -109,6 +111,7 @@ func run(ctx context.Context, args []string, input io.Reader, output, errorOutpu |
| case "run": |
| opts := thin.OptionsFromEnv(getenv) |
| opts.Version, opts.Logger = rastrillo.BuildVersion, slog.New(slog.NewTextHandler(errorOutput, nil)) |
| + logStart(opts.Logger, cfg, opts.Version, envFile) |
| err = thin.Run(ctx, cfg, opts) |
| if errors.Is(err, thin.ErrSuperseded) { |
| _, _ = fmt.Fprintf(errorOutput, equipo.CopyRunnerDiagnostic, "runner.superseded", "-") |
| @@ -158,6 +161,24 @@ func main() { |
| os.Exit(code) |
| } |
| +// logStart is the runner's first line: what starts, where it connects |
| +// (the origin's host only) and from which env file. No credential. |
| +func logStart(log *slog.Logger, cfg runner.Config, version, envFile string) { |
| + role := wire.RolePrimary |
| + if cfg.WorkerOnly || runner.ReadRole(cfg.StateDir) == wire.RoleWorker { |
| + role = wire.RoleWorker |
| + } |
| + host := "" |
| + if u, err := url.Parse(cfg.Origin); err == nil { |
| + host = u.Host |
| + } |
| + attrs := []any{"version", version, "os", goos(), "arch", goarch(), "role", role, "origin", host, "label", cfg.MachineLabel} |
| + if envFile != "" { |
| + attrs = append(attrs, "env_file", envFile) |
| + } |
| + log.Info("runner starting", attrs...) |
| +} |
| + |
| // supersededExit: systemd must not restart a runner that lost its lease |
| // (RestartPreventExitStatus=3); launchd restarts any non-zero exit |
| // (KeepAlive SuccessfulExit false), so on a Mac it is 0. |
diff --git a/cmd/equipo-runner/main_test.go b/cmd/equipo-runner/main_test.go| index 2fbcd25d..7b914f3c 100644 |
| --- a/cmd/equipo-runner/main_test.go |
| +++ b/cmd/equipo-runner/main_test.go |
| @@ -3,6 +3,8 @@ package main |
| import ( |
| "bytes" |
| "context" |
| + "os" |
| + "path/filepath" |
| "strings" |
| "testing" |
| ) |
| @@ -36,3 +38,38 @@ func TestRunnerDiagnosticIsCredentialFree(t *testing.T) { |
| t.Fatal("missing or unsafe diagnostic", log.String()) |
| } |
| } |
| + |
| +// run's first line says what starts and where it connects: the version, |
| +// the platform, the role, the origin's host alone, the machine's label |
| +// and the env file it read. It comes before anything that could hang. |
| +func TestRunLogsItsStart(t *testing.T) { |
| + root, err := filepath.EvalSymlinks(t.TempDir()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + vars := map[string]string{"EQUIPO_ORIGIN": "https://equipo.example.com", "EQUIPO_INSTANCE_ID": "i1", "EQUIPO_FAKE_PLATFORM": "darwin/arm64", "EQUIPO_MACHINE_LABEL": `"Test Mac"`, "EQUIPO_AMADAN_PATH": "/bin/sh"} |
| + for _, v := range []string{"BWRAP_PATH", "CLAUDE_PATH", "CODEX_CODE_MODE_HOST_PATH", "RUNNER_STATE_DIR", "AMADAN_CREDENTIAL_PATH", "ACCOUNT_BINDINGS_PATH", "CODEX_PATH", "GO_ROOT", "GO_BINARY", "WORKSPACE_ROOT", "SCRATCH_ROOT", "GIT_PATH"} { |
| + vars["EQUIPO_"+v] = filepath.Join(root, strings.ToLower(v)) |
| + } |
| + var lines []string |
| + for k, v := range vars { |
| + lines = append(lines, k+"="+v) |
| + } |
| + envFile := filepath.Join(root, "runner.env") |
| + if err := os.WriteFile(envFile, []byte(strings.Join(lines, "\n")+"\n"), 0600); err != nil { |
| + t.Fatal(err) |
| + } |
| + var out, log bytes.Buffer |
| + // No credential in the state directory: the run ends at once, after |
| + // its first line. |
| + run(context.Background(), []string{"run", "--env-file", envFile}, strings.NewReader(""), &out, &log, func(string) string { return "" }) |
| + first, _, _ := strings.Cut(log.String(), "\n") |
| + for _, want := range []string{`level=INFO msg="runner starting" version=`, " os=" + goos() + " arch=" + goarch() + " role=worker origin=equipo.example.com", `label="Test Mac"`, "env_file=" + envFile} { |
| + if !strings.Contains(first, want) { |
| + t.Fatalf("start line lacks %q:\n%s", want, log.String()) |
| + } |
| + } |
| + if strings.Contains(first, "https://") { |
| + t.Fatalf("start line names more than the origin's host: %s", first) |
| + } |
| +} |
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md| index 2c7fd9e6..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) | |
| @@ -6114,6 +6115,9 @@ records remain unchanged. |
| | `machines.step_approve` | Check that the label and key fingerprint match the machine, then approve it. You can check its connection below. | Add a machine: step 3 | Runtime; COPY ACCEPTED BY DELEGATION (Astra, 2026-11-11) | |
| | `machines.new` | New machines | Add a machine: group heading | Runtime; COPY ACCEPTED BY DELEGATION (Astra, 2026-11-11) | |
| | `machines.new_none` | Recently approved machines appear here, along with any that have never connected. | Add a machine: group with no new machines | Runtime; COPY ACCEPTED BY DELEGATION (Astra, 2026-11-11) | |
| +| `chat.paste.copy` | Copy | Paste box: the Copy button on every fenced block in a message | Runtime; COPY ACCEPTED BY DELEGATION (Astra, 2026-11-11) | |
| +| `chat.paste.copied` | Copied | Paste box: the button for a moment after a copy, and announced | Runtime; COPY ACCEPTED BY DELEGATION (Astra, 2026-11-11) | |
| +| `chat.paste.selected` | Selected. Copy it with your keyboard. | Paste box: announced, not shown, when the clipboard is refused and the text is left selected | Runtime; COPY ACCEPTED BY DELEGATION (Astra, 2026-11-11) | |
| ## Task 21 |
| @@ -6920,3 +6924,62 @@ Verification (targeted, niced): |
| - `go test ./internal/thintest -run '^(TestPagesInnerScreens|TestContractShipsQuestion|TestPagesTasksAndProjects|TestContractMergePolicyTool)$'`: ok. |
| - `go test -tags browser ./internal/thintest -run '^TestBrowserShipsButtons$'`: ok. Mutation: the script returning at once fails it at "Saved and Undo". `'^TestBrowserInnerScreens$'`: ok. |
| - `go test ./internal/equipo -run 'TestTemplateCopyKeys|TestRunnerCopyInventory'` and `EQUIPO_RELEASE_COPY_CHECK=1 go test ./internal/equipotest -run '^TestReleaseCopyReviewed$'`: ok. `make budget`: ok after raising internal/thintest to 13196 test lines (measured). |
| + |
| +## Paste box (2026-11-11) |
| + |
| +Paul: "Equipo should be able to present things that need to be pasted in |
| +a "Paste" box with a "copy" button e.g. for sharing prompts or commands |
| +or whatever." |
| + |
| +Every fenced block in a rendered message is a paste box, made once in |
| +the shared renderer (`chatmarkdown`), so the final reply, the streamed |
| +draft (`POST /conversation/draft`) and every page that shows markdown |
| +draw the same box. The box is the block's surface with a quiet bar (the |
| +fence's language when it is a short safe word, escaped, and Copy) over |
| +the text in a selectable `<pre><code>`. A `prompt` or `text` block wraps |
| +and reads as prose; anything else keeps its lines and scrolls. Indented |
| +code blocks stay plain. `paste.js` (on every chrome page) copies the |
| +code's text content with `navigator.clipboard.writeText`, less the |
| +newline that ends its last line, so the copy is the fence's text byte for |
| +byte with entities decoded; if the clipboard is refused it copies from a |
| +hidden field, or leaves the text selected and says so. "Copied" shows on |
| +the button for 1.8 s and is announced through one polite status line. |
| +Copy is a real button (Enter and Space, a 2px accent focus ring). Until |
| +`paste.js` runs it is hidden with its space kept; with scripts off it is |
| +gone and the text is still there to select. |
| + |
| +While streaming, a fence's opening line waits for its end (`steady`), so |
| +the box shows with its label and wrapping settled. The fenced code |
| +parser is watched like the inline ones: a fence that meets its closing |
| +line is noted, and a draft's open fence has Copy `aria-disabled` (dimmed |
| +to 0.45, a click does nothing). When the fence closes only the button's |
| +attribute changes; the box stays the same element in the same place. |
| + |
| +The coordinator's opening gains one static line, in the stable cached |
| +prefix ahead of the conversation: "Anything the person may need to paste |
| +(commands, prompts, config, codes) goes in a fenced code block, one block |
| +per thing to paste, with its kind after the opening fence (bash for a |
| +command, prompt for a prompt, text for plain text): the chat shows each |
| +block with a Copy button." `houseRule` moves to `2026-11-11.1` so |
| +sessions started under the old rule start fresh. No test pins the prefix |
| +bytes or a hash; `TestCoordinatorPromptStablePrefix` still holds |
| +unchanged, and `TestOpeningPutsPastesInFences` checks the line, that the |
| +opening is static, and that the version moved. |
| + |
| +Copy: three strings (`chat.paste.copy`, `chat.paste.copied`, |
| +`chat.paste.selected`), in the inventory above. One delegated Astra pass |
| +(gpt-6-astra, effort high) kept all three. Its flags were behaviour, not |
| +words, and the code settles both: the status line is cleared and then |
| +set once per copy, and the fallback selects the code element's |
| +contents. COPY ACCEPTED BY DELEGATION (Astra, 2026-11-11). |
| + |
| +The reference scan gains one exact entry: goldmark's syntax tree type |
| +in the watched fence parser's `Continue` signature. |
| + |
| +Verification (targeted, niced): |
| + |
| +- `go test ./internal/chatmarkdown`: ok. New: TestFenceIsAPasteBox, TestPasteBoxLabelIsEscaped, TestPasteBoxKeepsTheText, TestDraftOpenFenceWaitsToCopy, the fence rows of TestDraftPartialSyntax, a two-box reply in the stream corpus. Mutations, each red then restored: never open (TestDraftPartialSyntax, TestDraftOpenFenceWaitsToCopy), always open in a draft (TestDraftOfTheWholeReplyIsTheReply, TestDraftOpenFenceWaitsToCopy), no opener hold (TestDraftShowsNoMarkupAndOnlyTheReplysText, TestDraftPartialSyntax), no label charset (TestPasteBoxLabelIsEscaped), unescaped code (TestSafeSubset, TestPasteBoxKeepsTheText), text not prose (TestFenceIsAPasteBox). |
| +- `go test ./internal/runner/thin -run 'TestOpening|TestCoordinatorPromptStablePrefix'`: TestOpeningPutsPastesInFences red before the line, then ok. |
| +- `go test ./internal/equipo -run 'TestTemplateCopyKeys|TestRunnerCopyInventory'`, `go test ./internal/plan3test -run 'TestConversationDraftRendersOnTheServer'`: ok. |
| +- `go test -tags browser ./internal/headless -run '^TestBrowserPasteBox$'` (new; streams `replymd:paste` from fakeclaude): two local runs found test faults only (JS string quoting, then a batch that brought the trailing spaces and the closing fence together, which the test read as a move). The assertions are now precise. Hosted CI at 9b70f33 ran it in browser-headless-rest: ok. That run failed only on this report's own wording in the reference scan, fixed here. |
| +- `python3 scripts/runner-dead-references.py`: 0 failures. `EQUIPO_RELEASE_COPY_CHECK=1 CGO_ENABLED=0 go test ./internal/equipotest -run '^TestReleaseCopyReviewed$'`: ok. |
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/chatmarkdown/draft.go b/internal/chatmarkdown/draft.go| index b438a20b..936f4cd3 100644 |
| --- a/internal/chatmarkdown/draft.go |
| +++ b/internal/chatmarkdown/draft.go |
| @@ -38,7 +38,13 @@ func parse(source []byte) (ast.Node, *seen) { |
| inline[i] = util.Prioritized(watched{ip}, p.Priority) |
| } |
| } |
| - p := parser.NewParser(parser.WithBlockParsers(parser.DefaultBlockParsers()...), |
| + blocks := parser.DefaultBlockParsers() |
| + for i, b := range blocks { |
| + if bp, ok := b.Value.(parser.BlockParser); ok && bytes.ContainsAny(bp.Trigger(), "`") { |
| + blocks[i] = util.Prioritized(fence{bp}, b.Priority) |
| + } |
| + } |
| + p := parser.NewParser(parser.WithBlockParsers(blocks...), |
| parser.WithInlineParsers(inline...), |
| parser.WithParagraphTransformers(parser.DefaultParagraphTransformers()...), |
| ) |
| @@ -62,15 +68,44 @@ func (w watched) Parse(parent ast.Node, block text.Reader, pc parser.Context) as |
| return n |
| } |
| +// fence is goldmark's fenced code parser, watched: a fence that meets its |
| +// closing line is noted in seen, so a draft knows which fence is still |
| +// open. Watching changes nothing it parses. |
| +type fence struct{ parser.BlockParser } |
| + |
| +func (f fence) Continue(b ast.Node, reader text.Reader, pc parser.Context) parser.State { |
| + st := f.BlockParser.Continue(b, reader, pc) |
| + if s, ok := pc.Get(seenKey).(*seen); ok && st&parser.Close != 0 { |
| + s.found = append(s.found, b) |
| + } |
| + return st |
| +} |
| + |
| +// closed is whether a fence met its closing line. |
| +func (s *seen) closed(v *ast.FencedCodeBlock) bool { |
| + for _, f := range s.found { |
| + if f == v { |
| + return true |
| + } |
| + } |
| + return false |
| +} |
| + |
| // markerOnly is a last line with nothing yet but the start of a block: |
| // a bullet or a number, hashes, a quote, a fence, a rule or an underline, |
| // perhaps with the opener of its first words ("- **"). |
| var markerOnly = regexp.MustCompile("^[ \t]*(?:[-+*>]|[0-9]{1,9}[.)]?|#{1,6}|[`~]+|[-=_* \t]+)?[ \t]*[*_`]*$") |
| -// steady holds back a last line that is only a block's marker. |
| +// fenceLine is a last line that opens a fence, perhaps in a quote or a |
| +// list item: its label is still arriving, and the box it opens waits for |
| +// the whole line so its label and its wrapping are settled when it shows. |
| +var fenceLine = regexp.MustCompile("^[ \t>]*(?:(?:[-+*]|[0-9]{1,9}[.)])[ \t]+)?(?:```|~~~)[^\n]*$") |
| + |
| +// steady holds back a last line that is only a block's marker, or a |
| +// fence's opening line. |
| func steady(body string) string { |
| i := strings.LastIndexByte(body, '\n') + 1 |
| - if markerOnly.MatchString(body[i:]) { |
| + if markerOnly.MatchString(body[i:]) || fenceLine.MatchString(body[i:]) { |
| return body[:i] |
| } |
| return body |
diff --git a/internal/chatmarkdown/draft_test.go b/internal/chatmarkdown/draft_test.go| index 82bb6496..7ab66a88 100644 |
| --- a/internal/chatmarkdown/draft_test.go |
| +++ b/internal/chatmarkdown/draft_test.go |
| @@ -18,9 +18,19 @@ var corpus = []string{ |
| "I've logged [Fix the invoice total](/tasks/tks6kwzzdngr) in [Comercio](/projects/p_abc123). Engineering starts with a reproduction.", |
| "Run `go test ./internal/checkout/...` first, then this:\n\n```go\nfunc total(lines []Line) int {\n\tsum := 0\n\tfor _, l := range lines {\n\t\tsum += l.Price\n\t}\n\treturn sum\n}\n```\n\nThat is *all* it needs.", |
| "## Plan\n\nThree steps, each **small**:\n\n- read the code\n- reproduce it\n- fix it, with *one* test\n\nNested:\n\n1. First\n - a detail\n - another\n2. Second\n\n> Quoted note.\n\nLast line with a hard break \nand its continuation.", |
| + // Two paste boxes: a command and a prompt. |
| + "Run this in a terminal:\n\n```bash\ngo test ./internal/checkout/... -run 'TestTotal' > out.txt && echo ok\n```\n\nThen paste this into the review:\n\n```prompt\nCheck that the total counts delivery once, & say which test shows it.\n```\n\nThat is all.", |
| "Café con ñandú, señor. ☕ **Ünïcödé** 🎉 works.\nA soft break, then\n\n---\n\nafter a rule.", |
| } |
| +// labels are the paste box's words in these tests. |
| +var labels = Labels{Copy: "Copy", Copied: "Copied", Selected: "Selected"} |
| + |
| +// open is the draft of a fence still open: its box, Copy disabled. |
| +func open(lang, kind, text string) string { |
| + return `<div equipo-paste="` + kind + `"><div equipo-paste-bar><span equipo-paste-lang>` + lang + `</span><button type="button" equipo-paste-copy data-copied="Copied" data-selected="Selected" aria-disabled="true">Copy</button></div><pre><code>` + text + "</code></pre></div>\n" |
| +} |
| + |
| // visible is what a reader sees of rendered HTML: the text without tags, |
| // entities resolved, runs of whitespace as one space. |
| func visible(h string) string { |
| @@ -35,7 +45,7 @@ var code = regexp.MustCompile(`(?s)<pre>.*?</pre>`) |
| // nothing to the layout but what the last characters bring. |
| func TestDraftOfTheWholeReplyIsTheReply(t *testing.T) { |
| for _, reply := range corpus { |
| - if got, want := RenderDraft(reply), Render(reply); got != want { |
| + if got, want := labels.RenderDraft(reply), labels.Render(reply); got != want { |
| t.Errorf("draft of the whole reply differs\n draft: %q\nreply: %q", got, want) |
| } |
| } |
| @@ -46,12 +56,12 @@ func TestDraftOfTheWholeReplyIsTheReply(t *testing.T) { |
| // finished reply shows. |
| func TestDraftShowsNoMarkupAndOnlyTheReplysText(t *testing.T) { |
| for _, reply := range corpus { |
| - final := visible(string(Render(reply))) |
| + final := visible(string(labels.Render(reply))) |
| for i := 0; i <= len(reply); i++ { |
| if i < len(reply) && !utf8.RuneStart(reply[i]) { |
| continue |
| } |
| - draft := string(RenderDraft(reply[:i])) |
| + draft := string(labels.RenderDraft(reply[:i])) |
| seen := visible(draft) |
| if prose := visible(code.ReplaceAllString(draft, "")); strings.ContainsAny(prose, "*`[]#") || strings.Contains(prose, "](") { |
| t.Fatalf("markup shows at %d %q: %q", i, reply[:i], seen) |
| @@ -88,9 +98,15 @@ func TestDraftPartialSyntax(t *testing.T) { |
| {"Text\n--", "<p>Text</p>\n"}, |
| // An open code fence is an open code block; a closing fence on |
| // its way shows nothing. |
| - {"```go\nfmt.Println(", "<pre><code>fmt.Println(\n</code></pre>\n"}, |
| - {"```go\nx := 1\n``", "<pre><code>x := 1\n</code></pre>\n"}, |
| + {"```go\nfmt.Println(", open("go", "code", "fmt.Println(\n")}, |
| + {"```go\nx := 1\n``", open("go", "code", "x := 1\n")}, |
| {"``", ""}, |
| + // A fence's opening line waits for its end, so the box shows |
| + // with its label and its wrapping settled. |
| + {"Run:\n\n```ba", "<p>Run:</p>\n"}, |
| + {"Run:\n\n```prompt", "<p>Run:</p>\n"}, |
| + {"```prompt\n", open("prompt", "prose", "")}, |
| + {"- step\n ```sh", "<ul><li>step</li>\n</ul>\n"}, |
| // A link on its way shows its words. |
| {"See [Fix the inv", "<p>See Fix the inv</p>\n"}, |
| {"See [Fix the invoice]", "<p>See Fix the invoice</p>\n"}, |
| @@ -98,7 +114,7 @@ func TestDraftPartialSyntax(t *testing.T) { |
| {"See [Fix](/tasks/tk1)", "<p>See <a href=\"/tasks/tk1\" rel=\"noopener\">Fix</a></p>\n"}, |
| {"Code `a[b`", "<p>Code <code>a[b</code></p>\n"}, |
| } { |
| - if got := string(RenderDraft(c.text)); got != c.want { |
| + if got := string(labels.RenderDraft(c.text)); got != c.want { |
| t.Errorf("RenderDraft(%q)\n got %q\nwant %q", c.text, got, c.want) |
| } |
| } |
| @@ -107,9 +123,41 @@ func TestDraftPartialSyntax(t *testing.T) { |
| // The draft keeps the safe subset: the same rules as a finished reply. |
| func TestDraftKeepsTheSafeSubset(t *testing.T) { |
| for _, raw := range []string{`<script>alert(1)</script>`, `<img src=x onerror=alert(1)>`, `[x](javascript:alert%281%29)`, "[x](javascript:alert(1)", ``, "<scr"} { |
| - got := string(RenderDraft(raw)) |
| + got := string(labels.RenderDraft(raw)) |
| if strings.Contains(got, "<script") || strings.Contains(got, "<img") || strings.Contains(got, "<scr") || strings.Contains(got, `href="javascript:`) { |
| t.Fatal("unsafe", got) |
| } |
| } |
| } |
| + |
| +// A fence still arriving is open in the draft, and Copy waits: it turns |
| +// on when the closing line comes, and only the button changes. A |
| +// finished message is never open, even if its fence never closed. |
| +func TestDraftOpenFenceWaitsToCopy(t *testing.T) { |
| + text := "Run:\n\n```bash\ngo test ./...\n" |
| + draft := string(labels.RenderDraft(text)) |
| + if !strings.Contains(draft, `aria-disabled="true"`) { |
| + t.Fatalf("an open fence's Copy is not disabled: %s", draft) |
| + } |
| + // The closing line on its way is held back: still open. |
| + if got := string(labels.RenderDraft(text + "```")); got != draft { |
| + t.Fatalf("a closing line on its way changed the box: %s", got) |
| + } |
| + for _, closed := range []string{text + "```\n", text + "```\n\nDone."} { |
| + got := string(labels.RenderDraft(closed)) |
| + if strings.Contains(got, "aria-disabled") { |
| + t.Fatalf("a closed fence's Copy is disabled (%q): %s", closed, got) |
| + } |
| + if strings.Replace(draft, ` aria-disabled="true"`, "", 1) != got[:len(draft)-len(` aria-disabled="true"`)] { |
| + t.Fatalf("the box changed when its fence closed\n open: %s\nclosed: %s", draft, got) |
| + } |
| + } |
| + if got := string(labels.Render(text)); strings.Contains(got, "aria-disabled") { |
| + t.Fatalf("a finished message's unclosed fence is disabled: %s", got) |
| + } |
| + // Two fences: the first closed, the second still open. |
| + two := string(labels.RenderDraft("```sh\nls\n```\n\n```sh\npw")) |
| + if strings.Count(two, "<button") != 2 || strings.Count(two, "aria-disabled") != 1 || strings.Index(two, "aria-disabled") < strings.LastIndex(two, "<button") { |
| + t.Fatalf("only the last, open fence waits: %s", two) |
| + } |
| +} |
diff --git a/internal/chatmarkdown/markdown.go b/internal/chatmarkdown/markdown.go| index 28f26f11..edbce5a1 100644 |
| --- a/internal/chatmarkdown/markdown.go |
| +++ b/internal/chatmarkdown/markdown.go |
| @@ -7,21 +7,27 @@ import ( |
| "html/template" |
| "net/url" |
| "regexp" |
| + "strings" |
| "github.com/yuin/goldmark/ast" |
| "github.com/yuin/goldmark/util" |
| ) |
| +// Labels are the words of a paste box, from the app's copy: its Copy |
| +// button, the button once it has copied, and what is announced when the |
| +// clipboard is refused and the text is selected instead. |
| +type Labels struct{ Copy, Copied, Selected string } |
| + |
| // Render renders a finished message. |
| -func Render(body string) template.HTML { return render(body, false) } |
| +func (l Labels) Render(body string) template.HTML { return render(body, false, l) } |
| // RenderDraft renders a reply that is still arriving with the same rules, |
| // leaving out only what the next characters could still change (see |
| // draft.go). The draft of a whole reply is the reply's Render, unless the |
| // reply itself ends on an unclosed opener or a bare list marker. |
| -func RenderDraft(body string) template.HTML { return render(body, true) } |
| +func (l Labels) RenderDraft(body string) template.HTML { return render(body, true, l) } |
| -func render(body string, draft bool) template.HTML { |
| +func render(body string, draft bool, l Labels) template.HTML { |
| var hide spans |
| if draft { |
| body = steady(body) |
| @@ -69,7 +75,10 @@ func render(body string, draft bool) template.HTML { |
| escape(c.(*ast.Text).Segment.Value(source)) |
| } |
| out.WriteString("</code>") |
| - case *ast.FencedCodeBlock, *ast.CodeBlock: |
| + case *ast.FencedCodeBlock: |
| + // Copy waits while a draft's fence is still open. |
| + l.box(&out, v, source, draft && !seen.closed(v)) |
| + case *ast.CodeBlock: |
| out.WriteString("<pre><code>") |
| for i := 0; i < n.Lines().Len(); i++ { |
| line := n.Lines().At(i) |
| @@ -117,3 +126,43 @@ func render(body string, draft bool) template.HTML { |
| // sitePage is a same-origin link the chat may render: a task or a project. |
| var sitePage = regexp.MustCompile(`^/(tasks/tk[a-z0-9]{1,32}|projects/p_[a-z0-9]{1,40})$`) |
| + |
| +// box is a fenced block as a paste box: its language, quietly, when the |
| +// fence names a safe one, a Copy button, and the text in a selectable |
| +// <pre><code>, which is what the button copies (paste.js reads the code's |
| +// text, so entities are the characters they stand for). A prompt or text |
| +// block is prose and wraps; anything else is code and scrolls. While a |
| +// draft's fence is open the button is there but aria-disabled, so a |
| +// half-streamed command is never copied, and the box does not move when |
| +// it closes: only the button's attribute changes. |
| +func (l Labels) box(out *bytes.Buffer, v *ast.FencedCodeBlock, source []byte, open bool) { |
| + lang := string(v.Language(source)) |
| + if !language.MatchString(lang) { |
| + lang = "" |
| + } |
| + kind := "code" |
| + if prose[strings.ToLower(lang)] { |
| + kind = "prose" |
| + } |
| + out.WriteString(`<div equipo-paste="` + kind + `"><div equipo-paste-bar>`) |
| + if lang != "" { |
| + out.WriteString(`<span equipo-paste-lang>` + html.EscapeString(lang) + `</span>`) |
| + } |
| + out.WriteString(`<button type="button" equipo-paste-copy data-copied="` + html.EscapeString(l.Copied) + `" data-selected="` + html.EscapeString(l.Selected) + `"`) |
| + if open { |
| + out.WriteString(` aria-disabled="true"`) |
| + } |
| + out.WriteString(`>` + html.EscapeString(l.Copy) + `</button></div><pre><code>`) |
| + for i := 0; i < v.Lines().Len(); i++ { |
| + line := v.Lines().At(i) |
| + out.WriteString(html.EscapeString(string(line.Value(source)))) |
| + } |
| + out.WriteString("</code></pre></div>\n") |
| +} |
| + |
| +// language is a fence's label that may show: a short word of letters, |
| +// digits and the marks language names use (c++, c#, objective-c, .env). |
| +var language = regexp.MustCompile(`^\.?[A-Za-z0-9][A-Za-z0-9_+#.-]{0,23}$`) |
| + |
| +// prose are the labels of text a person reads and pastes whole: it wraps. |
| +var prose = map[string]bool{"prompt": true, "text": true} |
diff --git a/internal/chatmarkdown/markdown_test.go b/internal/chatmarkdown/markdown_test.go| index d2bcff53..3d4e0c44 100644 |
| --- a/internal/chatmarkdown/markdown_test.go |
| +++ b/internal/chatmarkdown/markdown_test.go |
| @@ -1,24 +1,26 @@ |
| package chatmarkdown |
| import ( |
| + "html" |
| + "regexp" |
| "strings" |
| "testing" |
| ) |
| func TestSafeSubset(t *testing.T) { |
| - got := string(Render("**bold** *italic* `inline`\n\n- one\n- two\n\n```go\n<script>\n```\n\n[link](https://example.test)")) |
| + got := string(labels.Render("**bold** *italic* `inline`\n\n- one\n- two\n\n```go\n<script>\n```\n\n[link](https://example.test)")) |
| for _, want := range []string{"<strong>bold</strong>", "<em>italic</em>", "<code>inline</code>", "<ul>", "<li>", "<pre><code>", "<script>", `rel="noopener"`} { |
| if !strings.Contains(got, want) { |
| t.Errorf("missing %s: %s", want, got) |
| } |
| } |
| for _, raw := range []string{`<script>alert(1)</script>`, `<img src=x onerror=alert(1)>`, `[x](javascript:alert%281%29)`, `[x](data:text/html,evil)`, `[x](//evil.test)`, `[x](javascript:evil)`, ``} { |
| - got := string(Render(raw)) |
| + got := string(labels.Render(raw)) |
| if strings.Contains(got, "<script") || strings.Contains(got, "<img") || strings.Contains(got, `href="javascript:`) || strings.Contains(got, `href="data:`) || strings.Contains(got, `href="//`) { |
| t.Fatal("unsafe", got) |
| } |
| } |
| - if !strings.Contains(string(Render(`<b>raw</b>`)), "<b>") { |
| + if !strings.Contains(string(labels.Render(`<b>raw</b>`)), "<b>") { |
| t.Fatal("raw HTML not escaped") |
| } |
| } |
| @@ -26,15 +28,76 @@ func TestSafeSubset(t *testing.T) { |
| // The coordinator links a task by its title; on this site only task and |
| // project pages become links. |
| func TestSiteLinksOnlyTasksAndProjects(t *testing.T) { |
| - got := string(Render("I've logged [Swipe back doesn't work](/tasks/tks6kwzzdngr) in [Woodstar](/projects/p_abc123).")) |
| + got := string(labels.Render("I've logged [Swipe back doesn't work](/tasks/tks6kwzzdngr) in [Woodstar](/projects/p_abc123).")) |
| for _, want := range []string{`<a href="/tasks/tks6kwzzdngr" rel="noopener">Swipe back doesn't work</a>`, `<a href="/projects/p_abc123" rel="noopener">Woodstar</a>`} { |
| if !strings.Contains(got, want) { |
| t.Fatalf("missing %s: %s", want, got) |
| } |
| } |
| for _, raw := range []string{`[x](/conversation/tasks/tk1/retry)`, `[x](/tasks/tk1/../../logout)`, `[x](/settings)`, `[x](tasks/tk1)`, `[x](/tasks/TK1)`, `[x](/tasks/tk1?a=b)`, `[x](/\\evil.test)`} { |
| - if got := string(Render(raw)); strings.Contains(got, "<a ") { |
| + if got := string(labels.Render(raw)); strings.Contains(got, "<a ") { |
| t.Fatalf("linked %s: %s", raw, got) |
| } |
| } |
| } |
| + |
| +// Every fenced block is a paste box: its label, a Copy button and the |
| +// text in a selectable <pre><code>. |
| +func TestFenceIsAPasteBox(t *testing.T) { |
| + got := string(labels.Render("Run this:\n\n```bash\ngo test ./...\n```\n")) |
| + want := `<p>Run this:</p> |
| +<div equipo-paste="code"><div equipo-paste-bar><span equipo-paste-lang>bash</span><button type="button" equipo-paste-copy data-copied="Copied" data-selected="Selected">Copy</button></div><pre><code>go test ./... |
| +</code></pre></div> |
| +` |
| + if got != want { |
| + t.Fatalf("paste box\n got %q\nwant %q", got, want) |
| + } |
| + // No label: still a box, a code one. A prompt or text label is prose. |
| + for _, c := range []struct{ fence, kind, lang string }{{"```", "code", ""}, {"~~~", "code", ""}, {"```prompt", "prose", "prompt"}, {"```Text", "prose", "Text"}, {"```go linenos", "code", "go"}, {"```c++", "code", "c++"}, {"```.env", "code", ".env"}} { |
| + got := string(labels.Render(c.fence + "\nx\n" + c.fence[:3])) |
| + if !strings.HasPrefix(got, `<div equipo-paste="`+c.kind+`">`) { |
| + t.Fatalf("%s: not a %s box: %s", c.fence, c.kind, got) |
| + } |
| + if has := strings.Contains(got, "<span equipo-paste-lang>"+c.lang+"</span>"); has != (c.lang != "") || c.lang == "" && strings.Contains(got, "equipo-paste-lang") { |
| + t.Fatalf("%s: label: %s", c.fence, got) |
| + } |
| + } |
| + // An indented code block stays a plain one. |
| + if got := string(labels.Render(" indented\n")); got != "<pre><code>indented\n</code></pre>\n" { |
| + t.Fatalf("indented code: %s", got) |
| + } |
| +} |
| + |
| +// A label shows only in a safe charset, escaped; anything else shows no |
| +// label and keeps the box. The button's words are escaped too. |
| +func TestPasteBoxLabelIsEscaped(t *testing.T) { |
| + for _, info := range []string{"<script>", `a"onmouseover=x`, "x'y", "a&b", "<b>", "a<b", "\"x", strings.Repeat("a", 25), "-x", "{.go}", "é"} { |
| + got := string(labels.Render("```" + info + "\nbody\n```")) |
| + if strings.Contains(got, "equipo-paste-lang") || strings.Contains(got, "<script") || strings.Contains(got, "onmouseover") || !strings.Contains(got, "<pre><code>body\n</code></pre>") { |
| + t.Fatalf("label %q: %s", info, got) |
| + } |
| + } |
| + odd := Labels{Copy: `<b>"Copy"</b>`, Copied: `"><x>`, Selected: "a&b"} |
| + got := string(odd.Render("```sh\nls\n```")) |
| + if strings.Contains(got, "<b>") || strings.Contains(got, "<x>") || !strings.Contains(got, `data-copied=""><x>"`) || !strings.Contains(got, `data-selected="a&b"`) || !strings.Contains(got, `<b>"Copy"</b></button>`) { |
| + t.Fatalf("labels not escaped: %s", got) |
| + } |
| +} |
| + |
| +// The box's code is the fence's text exactly: what the page reads as the |
| +// code's text content (entities resolved) is the raw content, with its |
| +// <, &, tabs and trailing spaces; Copy drops only the one newline that |
| +// ends the last line. |
| +func TestPasteBoxKeepsTheText(t *testing.T) { |
| + raw := "if a < b && c > d {\n\tfmt.Println(\"x & y\") \n}\t\n two trailing \n<script>alert(1)</script>" |
| + for _, render := range []func(string) string{func(s string) string { return string(labels.Render(s)) }, func(s string) string { return string(labels.RenderDraft(s)) }} { |
| + got := render("```go\n" + raw + "\n```\n") |
| + m := regexp.MustCompile(`(?s)<pre><code>(.*)</code></pre>`).FindStringSubmatch(got) |
| + if m == nil || strings.Contains(m[1], "<script") { |
| + t.Fatalf("code: %s", got) |
| + } |
| + if text := strings.TrimSuffix(html.UnescapeString(m[1]), "\n"); text != raw { |
| + t.Fatalf("the box's text is not the fence's\n got %q\nwant %q", text, raw) |
| + } |
| + } |
| +} |
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_draft.go b/internal/equipo/chat_draft.go| index 464cc04a..f9218850 100644 |
| --- a/internal/equipo/chat_draft.go |
| +++ b/internal/equipo/chat_draft.go |
| @@ -4,7 +4,6 @@ import ( |
| "io" |
| "net/http" |
| - "amadan.net/oficina/equipo/internal/chatmarkdown" |
| "amadan.net/oficina/equipo/internal/wire" |
| ) |
| @@ -31,5 +30,5 @@ func (a *application) chatDraft(w http.ResponseWriter, r *http.Request) { |
| text = text[:4*wire.MaxMessageBytes] |
| } |
| w.Header().Set("Content-Type", "text/html; charset=utf-8") |
| - _, _ = io.WriteString(w, string(chatmarkdown.RenderDraft(text))) |
| + _, _ = io.WriteString(w, string(pasteLabels.RenderDraft(text))) |
| } |
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 a883ea55..e901af82 100644 |
| --- a/internal/equipo/copy.go |
| +++ b/internal/equipo/copy.go |
| @@ -3,6 +3,7 @@ package equipo |
| import ( |
| "sort" |
| + "amadan.net/oficina/equipo/internal/chatmarkdown" |
| "amadan.net/oficina/equipo/internal/runner" |
| "amadan.net/oficina/equipo/internal/runnerproto" |
| ) |
| @@ -566,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) |
| @@ -1676,8 +1678,16 @@ var pageCopy = map[string]string{ |
| "team.ask_failed": "That question did not go through. Try again.", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-11): team panel drawer |
| "team.recent": "Recent work", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-11): team panel drawer |
| "team.recent_empty": "Nothing yet.", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-11): team panel drawer |
| + |
| + // The paste box: every fenced block in a rendered message. |
| + "chat.paste.copy": "Copy", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-11): paste box button |
| + "chat.paste.copied": "Copied", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-11): paste box button after a copy, and announced |
| + "chat.paste.selected": "Selected. Copy it with your keyboard.", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-11): announced when the clipboard is refused and the text is selected |
| } |
| +// pasteLabels are the paste box's words, for the shared renderer. |
| +var pasteLabels = chatmarkdown.Labels{Copy: copyText("chat.paste.copy"), Copied: copyText("chat.paste.copied"), Selected: copyText("chat.paste.selected")} |
| + |
| func copyText(key string) string { |
| if text, ok := runnerDraftCopy[key]; ok { |
| return text |
diff --git a/internal/equipo/render.go b/internal/equipo/render.go| index 365945f5..fef26f7a 100644 |
| --- a/internal/equipo/render.go |
| +++ b/internal/equipo/render.go |
| @@ -1,7 +1,6 @@ |
| package equipo |
| import ( |
| - "amadan.net/oficina/equipo/internal/chatmarkdown" |
| "bytes" |
| "embed" |
| "encoding/json" |
| @@ -37,7 +36,7 @@ func init() { |
| for _, name := range []string{"person_devices", "person_device", "teams", "onboarding", "invite", "playbooks", "playbook_form", "playbook_diff", "specialist_form", "template_library", "template_diff", "conversation", "chat", "thread", "plan", "coordinator", "preferences", "index", "empty", "projects", "project", "project_form", "people", "settings", "specialist", "errors", "signin_page", "form_error", "runners", "tasks", "task", "task_form", "question", "merge", "connections", "recovery", "recovery_form", "rendered_approval", "notebook", "housekeeping", "work_tasks", "work_task", "work_projects", "work_project", "models", "work_needs", "settings_hub", "team"} { |
| page := template.Must(template.New("layout"). |
| Funcs(ui.Funcs(ui.WithIcons(icons.Icon, icons.Assets))). |
| - Funcs(template.FuncMap{"chatMarkdown": chatmarkdown.Render, "chatDraft": chatmarkdown.RenderDraft, "fileSize": fileSize, "loadingLine": loadingLine, "split": strings.Split, "since": sinceMillis, "elapsed": elapsedText, "short": short, "agoData": agoData, "agoText": agoText, "hostOf": hostOf, "deref": deref, "agoFormats": agoFormats, "projectAllows": library.ProjectAllowed, "asset": assets.Path, "copy": copyText, "taskGroups": func() []string { return []string{"needs-person", "running", "queued", "finished"} }, |
| + Funcs(template.FuncMap{"chatMarkdown": pasteLabels.Render, "chatDraft": pasteLabels.RenderDraft, "fileSize": fileSize, "loadingLine": loadingLine, "split": strings.Split, "since": sinceMillis, "elapsed": elapsedText, "short": short, "agoData": agoData, "agoText": agoText, "hostOf": hostOf, "deref": deref, "agoFormats": agoFormats, "projectAllows": library.ProjectAllowed, "asset": assets.Path, "copy": copyText, "taskGroups": func() []string { return []string{"needs-person", "running", "queued", "finished"} }, |
| "kindKey": func(k ProjectKind) string { return "kind." + string(k) }, |
| "ownerKey": func(k string) string { return "owner." + k }, |
| "roleKey": func(k Role) string { return "role." + string(k) }, |
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/static/equipo.css b/internal/equipo/static/equipo.css| index 380fc171..016e7664 100644 |
| --- a/internal/equipo/static/equipo.css |
| +++ b/internal/equipo/static/equipo.css |
| @@ -278,6 +278,33 @@ html:has([equipo-conversation]) { overflow: hidden; scrollbar-gutter: auto; } |
| [equipo-markdown] > :first-child { margin-block-start: 0; } |
| [equipo-markdown] > :last-child { margin-block-end: 0; } |
| [equipo-markdown] pre { max-inline-size: 100%; overflow-x: auto; white-space: pre; padding: var(--rst-sp-3); background: var(--rst-surface); border: 1px solid var(--rst-line); border-radius: var(--rst-radius); } |
| +/* The paste box: every fenced block in a message (chatmarkdown, paste.js). |
| + The block's surface holds a quiet bar (the fence's language, Copy) over |
| + the text. Code and commands keep their lines and scroll; a prompt or |
| + text block wraps and reads as prose. Copy waits, dimmed, while the |
| + block is still streaming, and is hidden until paste.js runs (gone when |
| + scripts are off): the text is still there to select. */ |
| +[equipo-markdown] [equipo-paste] { margin-block: var(--rst-sp-3); max-inline-size: 100%; background: var(--rst-surface); border: 1px solid var(--rst-line); border-radius: var(--rst-radius); } |
| +[equipo-markdown] > [equipo-paste]:first-child { margin-block-start: 0; } |
| +[equipo-markdown] > [equipo-paste]:last-child { margin-block-end: 0; } |
| +[equipo-paste-bar] { display: flex; align-items: center; justify-content: space-between; gap: var(--rst-sp-2); min-block-size: 1.75rem; padding: var(--rst-sp-1) var(--rst-sp-1) 0 var(--rst-sp-3); } |
| +[equipo-paste-lang] { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: var(--rst-fs-xs); color: var(--rst-text-muted); } |
| +[equipo-paste-copy] { margin-inline-start: auto; padding: .25rem .6rem; border: 0; border-radius: var(--rst-radius-sm, 4px); background: none; font: inherit; font-size: var(--rst-fs-xs); color: var(--rst-text-muted); cursor: pointer; } |
| +[equipo-paste-copy]:hover { color: var(--rst-text); background: var(--rst-tint-hover, var(--rst-surface-2)); } |
| +[equipo-paste-copy]:focus-visible { color: var(--rst-text); outline: 2px solid var(--rst-accent); outline-offset: 1px; } |
| +/* Copy keeps its place but shows only once paste.js is running. */ |
| +:root:not([data-paste]) [equipo-paste-copy] { visibility: hidden; } |
| +[equipo-paste-copy][aria-disabled="true"] { opacity: .45; cursor: default; background: none; color: var(--rst-text-muted); } |
| +[equipo-markdown] [equipo-paste] pre { margin: 0; padding: var(--rst-sp-1) var(--rst-sp-3) var(--rst-sp-3); background: none; border: 0; border-radius: 0; font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: var(--rst-fs-sm); line-height: 1.5; tab-size: 4; } |
| +[equipo-markdown] [equipo-paste] pre code { font: inherit; } |
| +[equipo-markdown] [equipo-paste="prose"] pre { white-space: pre-wrap; overflow-wrap: anywhere; overflow-x: visible; font-family: inherit; line-height: 1.55; } |
| +[equipo-paste] pre ::selection { background: var(--rst-accent-soft); color: var(--rst-text); } |
| +@media (scripting: none) { |
| + [equipo-paste-copy] { display: none; } |
| + [equipo-paste-bar]:not(:has([equipo-paste-lang])) { display: none; } |
| + [equipo-markdown] [equipo-paste] pre { padding-block-start: var(--rst-sp-3); } |
| + [equipo-markdown] [equipo-paste-bar]:has([equipo-paste-lang]) + pre { padding-block-start: var(--rst-sp-1); } |
| +} |
| [equipo-markdown] ul, [equipo-markdown] ol { padding-inline-start: var(--rst-sp-5); } |
| /* Receipts say what the coordinator did: a quiet line, no button chrome. |
| Their actions show on hover or keyboard focus on pointer devices, and |
diff --git a/internal/equipo/static/paste.js b/internal/equipo/static/paste.js| new file mode 100644 |
| index 00000000..74d26e79 |
| --- /dev/null |
| +++ b/internal/equipo/static/paste.js |
| @@ -0,0 +1,56 @@ |
| +// paste.js is the paste box's Copy button. Every fenced block in a |
| +// rendered message is a paste box (chatmarkdown), on every page that shows |
| +// one, streamed or final. Copy puts the block's text on the clipboard |
| +// exactly as the code element holds it, less the newline that ends its |
| +// last line. It waits while the block is still streaming (aria-disabled). |
| +// If the clipboard is refused the text is copied from a field nobody sees, |
| +// or else selected for the person to copy, and that is announced. Without |
| +// script the button is hidden (equipo.css) and the text can be selected. |
| +(function () { |
| + "use strict"; |
| + // Copy shows from here on (equipo.css hides it until then). |
| + document.documentElement.setAttribute("data-paste", ""); |
| + var status = null; |
| + // say announces through one polite status line for the whole page. |
| + function say(text) { |
| + if (!status) { |
| + status = document.createElement("div"); |
| + status.setAttribute("role", "status"); |
| + status.setAttribute("equipo-visually-hidden", ""); |
| + document.body.append(status); |
| + } |
| + status.textContent = ""; |
| + // A fresh change, so a second copy is announced again. |
| + setTimeout(function () { status.textContent = text; }, 60); |
| + } |
| + document.addEventListener("click", function (event) { |
| + var button = event.target instanceof Element && event.target.closest("[equipo-paste-copy]"); |
| + if (!button || button.getAttribute("aria-disabled") === "true") return; |
| + var box = button.closest("[equipo-paste]"), code = box && box.querySelector("pre > code"); |
| + if (!code) return; |
| + var text = code.textContent.replace(/\r?\n$/, ""); |
| + if (!button.pasteLabel) button.pasteLabel = button.textContent; |
| + function done() { |
| + button.textContent = button.dataset.copied; |
| + say(button.dataset.copied); |
| + clearTimeout(button.pasteTimer); |
| + button.pasteTimer = setTimeout(function () { button.textContent = button.pasteLabel; }, 1800); |
| + } |
| + function fallback() { |
| + var field = document.createElement("textarea"), copied = false; |
| + field.value = text; |
| + field.setAttribute("readonly", ""); |
| + field.setAttribute("equipo-visually-hidden", ""); |
| + document.body.append(field); |
| + field.select(); |
| + try { copied = document.execCommand("copy"); } catch (e) { /* select it below */ } |
| + field.remove(); |
| + button.focus(); |
| + if (copied) return done(); |
| + getSelection().selectAllChildren(code); |
| + say(button.dataset.selected); |
| + } |
| + if (navigator.clipboard && window.isSecureContext) navigator.clipboard.writeText(text).then(done, fallback); |
| + else fallback(); |
| + }); |
| +})(); |
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/equipo/templates/chrome.html b/internal/equipo/templates/chrome.html| index 15ba1153..7f997f36 100644 |
| --- a/internal/equipo/templates/chrome.html |
| +++ b/internal/equipo/templates/chrome.html |
| @@ -1,6 +1,6 @@ |
| {{define "rail-brand"}}<span hidden></span>{{end}} |
| {{define "title"}}{{copy .Title}} · {{copy "brand"}}{{end}} |
| -{{define "head"}}{{.Live.Head (T "rastrillo.ui.live.paused") (T "rastrillo.ui.live.unconfirmed")}}<link rel="stylesheet" href="{{asset "static/equipo.css"}}"><script defer src="{{asset "static/nav-stream.js"}}"></script><script defer src="{{asset "static/work-stream.js"}}"></script><script defer src="{{asset "static/stardust.js"}}"></script><script defer src="{{asset "static/team-panel.js"}}"></script>{{with .Thin.MergePolicy}}{{if .Editable}}<script defer src="{{asset "static/merge-ships.js"}}"></script>{{end}}{{end}}{{if .HousekeepingStream}}<script defer src="{{asset "static/housekeeping.js"}}"></script>{{end}}{{if or (eq .Key "thinking") (eq .Key "settings-hub")}}<script defer src="{{asset "static/thinking-preview.js"}}"></script><script defer src="{{asset "static/settings.js"}}"></script>{{end}}{{if .ConnectionsStream}}<script defer src="{{asset "static/vendor/tweetnacl/nacl-fast.js"}}"></script><script defer src="{{asset "static/seal.js"}}"></script><script defer src="{{asset "static/connections.js"}}"></script>{{end}}{{if .MachinesStream}}<script defer src="{{asset "static/machines.js"}}"></script>{{end}}{{if .ChatStream}}<script defer src="{{asset "static/chat-stream.js"}}"></script><script defer src="{{asset "static/chat-compose.js"}}"></script><script defer src="{{asset "static/ask-target.js"}}"></script>{{if eq .Key "conversation"}}<script defer src="{{asset "static/chat-anchor.js"}}"></script><script defer src="{{asset "static/chat-attach.js"}}"></script>{{end}}{{else if eq .Key "conversation"}}<script defer blocking="render" src="{{asset "static/chat-navigation.js"}}"></script><script defer src="{{asset "static/chat.js"}}"></script><script defer src="{{asset "static/chat-send.js"}}"></script>{{end}}{{end}} |
| +{{define "head"}}{{.Live.Head (T "rastrillo.ui.live.paused") (T "rastrillo.ui.live.unconfirmed")}}<link rel="stylesheet" href="{{asset "static/equipo.css"}}"><script defer src="{{asset "static/nav-stream.js"}}"></script><script defer src="{{asset "static/work-stream.js"}}"></script><script defer src="{{asset "static/stardust.js"}}"></script><script defer src="{{asset "static/team-panel.js"}}"></script><script defer src="{{asset "static/paste.js"}}"></script>{{with .Thin.MergePolicy}}{{if .Editable}}<script defer src="{{asset "static/merge-ships.js"}}"></script>{{end}}{{end}}{{if .HousekeepingStream}}<script defer src="{{asset "static/housekeeping.js"}}"></script>{{end}}{{if or (eq .Key "thinking") (eq .Key "settings-hub")}}<script defer src="{{asset "static/thinking-preview.js"}}"></script><script defer src="{{asset "static/settings.js"}}"></script>{{end}}{{if .ConnectionsStream}}<script defer src="{{asset "static/vendor/tweetnacl/nacl-fast.js"}}"></script><script defer src="{{asset "static/seal.js"}}"></script><script defer src="{{asset "static/connections.js"}}"></script>{{end}}{{if .MachinesStream}}<script defer src="{{asset "static/machines.js"}}"></script>{{end}}{{if .ChatStream}}<script defer src="{{asset "static/chat-stream.js"}}"></script><script defer src="{{asset "static/chat-compose.js"}}"></script><script defer src="{{asset "static/ask-target.js"}}"></script>{{if eq .Key "conversation"}}<script defer src="{{asset "static/chat-anchor.js"}}"></script><script defer src="{{asset "static/chat-attach.js"}}"></script>{{end}}{{else if eq .Key "conversation"}}<script defer blocking="render" src="{{asset "static/chat-navigation.js"}}"></script><script defer src="{{asset "static/chat.js"}}"></script><script defer src="{{asset "static/chat-send.js"}}"></script>{{end}}{{end}} |
| {{define "up"}}/work{{if .Key}}#nav-{{.Key}}{{end}}{{end}} |
| {{define "up-label"}}{{.TeamName}}{{end}} |
| {{define "brand"}}<a rst-shell-brand href="/work">{{icon "users"}}{{.TeamName}}</a>{{end}} |
diff --git a/internal/fakeclaude/fake.go b/internal/fakeclaude/fake.go| index b06c72cd..b621acc0 100644 |
| --- a/internal/fakeclaude/fake.go |
| +++ b/internal/fakeclaude/fake.go |
| @@ -11,8 +11,8 @@ |
| // steer it: "sleep:<ms>" pauses mid-reply, "crash" exits mid-turn, "fail" |
| // ends the turn with an error result, "badinit" reports a native tool in |
| // system/init, "othersession" answers under another session id, "accents" |
| -// replies with non-ASCII text, "replymd" (or "replymd:long") with a |
| -// formatted one, "chunks:<n>" streams in n deltas, "slowstream" pauses after every chunk, |
| +// replies with non-ASCII text, "replymd" (or "replymd:long", or |
| +// "replymd:paste" with two paste boxes) with a formatted one, "chunks:<n>" streams in n deltas, "slowstream" pauses after every chunk, |
| // "think" opens with a thinking block, "pause:<ms>" waits before any text, and "tool:<name>[:<arg>]" calls an |
| // Equipo MCP tool before replying (add_project:<repo>, |
| // create_project:<namespace>/<name>, ask_person:<question>|<option>..., |
| @@ -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/fakeclaude/markdown.go b/internal/fakeclaude/markdown.go| index dff66ccc..5cbb0db1 100644 |
| --- a/internal/fakeclaude/markdown.go |
| +++ b/internal/fakeclaude/markdown.go |
| @@ -11,9 +11,15 @@ import ( |
| // numbered list, with a task link and inline code. |
| const markdownSample = "**Yes. This is the right shape for it.** The invoice total is counted twice when delivery is added.\n\nTwo people see it:\n\n- **Guest:** sees the total on the basket page.\n- **Customer:** sees it again on the receipt.\n\nWhat I'd do, in [Fix the invoice total](/tasks/tks6kwzzdngr):\n\n1. **Owner of the fix:** Engineering, on the checkout repository.\n2. **One complete change:** the total, the receipt and `go test ./checkout/...` for both.\n3. **Review:** an independent check before it merges." |
| -// markdownWord asks for markdownSample as the reply ("replymd"), or for |
| -// a long reply of it repeated ("replymd:long"). |
| -var markdownWord = regexp.MustCompile(`\breplymd(:long)?\b`) |
| +// pasteSample is a reply with two things to paste: a command, with the |
| +// characters a copy must keep (<, &, quotes, a tab, trailing spaces), and |
| +// a prompt, which wraps. |
| +const pasteSample = "Run this in a terminal:\n\n```bash\ngo test ./internal/checkout/... -run 'TestTotal' > out.txt && echo \"a < b\"\t \n```\n\nThen paste this prompt into the review:\n\n```prompt\nCheck that the invoice total counts delivery once, & say which test shows it. Keep the receipt as it is.\n```" |
| + |
| +// markdownWord asks for markdownSample as the reply ("replymd"), for a |
| +// long reply of it repeated ("replymd:long"), or for pasteSample |
| +// ("replymd:paste"). |
| +var markdownWord = regexp.MustCompile(`\breplymd(:long|:paste)?\b`) |
| func markdownReply(newest string) (string, bool) { |
| m := markdownWord.FindStringSubmatch(newest) |
| @@ -23,6 +29,9 @@ func markdownReply(newest string) (string, bool) { |
| if m[1] == "" { |
| return markdownSample, true |
| } |
| + if m[1] == ":paste" { |
| + return pasteSample, true |
| + } |
| parts := make([]string, 30) |
| for i := range parts { |
| parts[i] = "## Part " + strconv.Itoa(i+1) + "\n\n" + markdownSample |
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/headless/browser_paste_test.go b/internal/headless/browser_paste_test.go| new file mode 100644 |
| index 00000000..f6d195f8 |
| --- /dev/null |
| +++ b/internal/headless/browser_paste_test.go |
| @@ -0,0 +1,129 @@ |
| +//go:build browser |
| + |
| +package headless |
| + |
| +import ( |
| + "context" |
| + "os" |
| + "path/filepath" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/browsertest" |
| + "github.com/chromedp/cdproto/cdp" |
| + "github.com/chromedp/cdproto/emulation" |
| + "github.com/chromedp/chromedp" |
| +) |
| + |
| +// pasted are the two blocks of fakeclaude's pasteSample, as written |
| +// between their fences: a command with <, &, quotes, a tab and trailing |
| +// spaces, and a prompt. |
| +const ( |
| + pastedCommand = "go test ./internal/checkout/... -run 'TestTotal' > out.txt && echo \"a < b\"\t " |
| + pastedPrompt = "Check that the invoice total counts delivery once, & say which test shows it. Keep the receipt as it is." |
| +) |
| + |
| +// Every fenced block in a reply is a paste box. While its fence is still |
| +// streaming the box shows and Copy is there but disabled (a click copies |
| +// nothing); when the fence closes Copy turns on in the same box, which |
| +// does not move. In the committed reply a click copies the block's exact |
| +// text, "Copied" shows and is announced, then Copy comes back; from the |
| +// keyboard, Tab reaches the next Copy with a visible focus ring, and |
| +// Enter and Space copy. Set EQUIPO_SCREENSHOTS to a directory to save |
| +// paste-*.png. |
| +func TestBrowserPasteBox(t *testing.T) { |
| + _, inst, r := localEnv(t) |
| + r.start(t) |
| + c := inst.Cookie() |
| + p := openPage(t, inst.URL, c.Name, c.Value, 1280, 900, true) |
| + defer p.stop() |
| + // The clipboard records what it is given. |
| + p.check(`(()=>{window.__copied=[];navigator.clipboard.writeText=t=>{window.__copied.push(t);return Promise.resolve()};return true})()`, "clipboard stub") |
| + // record follows the streaming reply frame by frame: the first box |
| + // while its Copy is disabled (its text, its place in the message, a |
| + // click on it) and the first frame Copy is on. Its place is its top in |
| + // the message, its bar's height and Copy's distance from its right edge: |
| + // the bubble may still widen as the last line grows. |
| + record := `(()=>{const s=window.__p={el:null,box:null,open:0,openText:null,openAt:null,dim:null,clicked:false,on:null,onAt:null,same:null,done:false}; |
| +const at=(b,x)=>[b.getBoundingClientRect().top-x.getBoundingClientRect().top,b.querySelector('[equipo-paste-bar]').getBoundingClientRect().height,b.getBoundingClientRect().right-b.querySelector('[equipo-paste-copy]').getBoundingClientRect().right]; |
| +const f=()=>{if(!s.el)s.el=document.querySelector('[equipo-thinking][data-streaming]');const x=s.el; |
| +if(x&&x.hasAttribute('equipo-thinking')){const b=x.querySelector('[equipo-paste]');if(b){const btn=b.querySelector('[equipo-paste-copy]'),code=b.querySelector('pre > code').textContent; |
| +if(btn.getAttribute('aria-disabled')==='true'){if(!s.box)s.box=b;s.open++;s.openText=code;s.openAt=at(b,x);s.dim=getComputedStyle(btn).opacity;if(!s.clicked){s.clicked=true;btn.click()}} |
| +else if(s.on===null){s.on=code;s.onAt=at(b,x);s.same=s.box===b}}} |
| +if(!x||x.hasAttribute('equipo-thinking'))requestAnimationFrame(f);else s.done=true};f();return true})()` |
| + p.check(record, "record") |
| + p.send("replymd:paste chunks:120 sleep:40 slowstream") |
| + p.run(browsertest.WaitWithin(`window.__p.done && !!window.__p.el.dataset.message`, 60*time.Second)) |
| + state := func() string { return evaluateIn[string](t, p.ctx, `JSON.stringify(window.__p)`) } |
| + p.check(`window.__p.open>0 && window.__p.box!==null`, "the box did not show while its fence was open: "+state()) |
| + p.check(`parseFloat(window.__p.dim)<0.7`, "the disabled Copy is not visibly dimmed: "+state()) |
| + p.check(`window.__copied.length===0`, "a click on an open fence's Copy copied: "+state()) |
| + // An open block's last line is still arriving; the renderer ends it |
| + // with a newline, as it ends every line. |
| + p.check(`(`+jsonString(pastedCommand)+`).startsWith(window.__p.openText.replace(/\n$/,''))`, "the open box showed other text: "+state()) |
| + p.check(`window.__p.on!==null && window.__p.same`, "Copy did not turn on in the same box while streaming: "+state()) |
| + p.check(`window.__p.on===`+jsonString(pastedCommand+"\n"), "Copy turned on before the fence closed: "+state()) |
| + p.check(`window.__p.openAt.every((v,i)=>Math.abs(v-window.__p.onAt[i])<0.5)`, "the box moved when its fence closed: "+state()) |
| + |
| + // The committed reply: two boxes, a command and a prompt. |
| + p.check(`(()=>{const m=window.__p.el,b=m.querySelectorAll('[equipo-paste]');if(b.length!==2||b[0].getAttribute('equipo-paste')!=='code'||b[1].getAttribute('equipo-paste')!=='prose')return false; |
| +if(b[0].querySelector('[equipo-paste-lang]').textContent!=='bash'||b[1].querySelector('[equipo-paste-lang]').textContent!=='prompt'||m.querySelector('[aria-disabled]'))return false; |
| +const cs=getComputedStyle(b[0].querySelector('pre')),ps=getComputedStyle(b[1].querySelector('pre'));if(cs.whiteSpace!=='pre'||ps.whiteSpace!=='pre-wrap'||!/mono/i.test(cs.fontFamily))return false; |
| +b[0].querySelector('[equipo-paste-copy]').id='paste-a';b[1].querySelector('[equipo-paste-copy]').id='paste-b';b[0].scrollIntoView({block:'center'});return true})()`, "the committed reply's boxes") |
| + shot := func(name string) { |
| + dir := os.Getenv("EQUIPO_SCREENSHOTS") |
| + if dir == "" { |
| + return |
| + } |
| + var raw []byte |
| + p.run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { |
| + var err error |
| + raw, err = chromedp.CaptureScreenshot()(ctx, target) |
| + return err |
| + })) |
| + if err := os.WriteFile(filepath.Join(dir, "paste-"+name+".png"), raw, 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + shot("light") |
| + |
| + // A click copies the command exactly; "Copied" shows, is announced, |
| + // then Copy comes back. |
| + p.run(chromedp.Click(chromedp.CSS(`#paste-a`))) |
| + p.run(browsertest.Wait(`window.__copied.length===1`)) |
| + p.check(`window.__copied[0]===`+jsonString(pastedCommand), "the copied text is not the block's: "+evaluateIn[string](t, p.ctx, `JSON.stringify(window.__copied)`)) |
| + p.check(`document.querySelector('#paste-a').textContent==='Copied'`, "the button did not say Copied") |
| + p.run(browsertest.Wait(`[...document.querySelectorAll('[role="status"]')].some(e=>e.textContent==='Copied')`)) |
| + shot("copied") |
| + p.run(browsertest.WaitWithin(`document.querySelector('#paste-a').textContent==='Copy'`, 5*time.Second)) |
| + |
| + // The keyboard: Tab from the first Copy reaches the second, with a |
| + // visible focus ring; Enter copies the prompt, Space the command. |
| + p.check(`(()=>{document.querySelector('#paste-a').focus();return true})()`, "focus") |
| + p.run(chromedp.KeyEvent("\t")) |
| + p.check(`(()=>{const a=document.activeElement;return a.id==='paste-b'&&a.matches(':focus-visible')&&getComputedStyle(a).outlineStyle==='solid'&&parseFloat(getComputedStyle(a).outlineWidth)>=2})()`, "Tab did not reach the second Copy with a focus ring") |
| + shot("focus") |
| + p.run(chromedp.KeyEvent("\r")) |
| + p.run(browsertest.Wait(`window.__copied.length===2 && document.querySelector('#paste-b').textContent==='Copied'`)) |
| + p.check(`window.__copied[1]===`+jsonString(pastedPrompt), "Enter copied other text") |
| + p.check(`(()=>{document.querySelector('#paste-a').focus();return true})()`, "focus") |
| + p.run(chromedp.KeyEvent(" ")) |
| + p.run(browsertest.Wait(`window.__copied.length===3`)) |
| + p.check(`window.__copied[2]===`+jsonString(pastedCommand), "Space copied other text") |
| + |
| + // Dark theme, for the screenshots. |
| + p.check(`(()=>{document.documentElement.dataset.theme='dark';return true})()`, "theme") |
| + shot("dark") |
| + |
| + // Without script the box is still there and its text can be |
| + // selected; Copy is hidden, never a button that does nothing. |
| + p.run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { |
| + _, err := cdp.Call(ctx, target, emulation.SetScriptExecutionDisabled, emulation.SetScriptExecutionDisabledParams{Value: true}) |
| + return err |
| + }), chromedp.Navigate(inst.URL+"/conversation")) |
| + p.run(browsertest.Wait(`document.querySelectorAll('[equipo-paste]').length>=2`)) |
| + t.Logf("scripting: none matches: %v", evaluateIn[bool](t, p.ctx, `matchMedia('(scripting: none)').matches`)) |
| + p.check(`!document.documentElement.hasAttribute('data-paste')`, "paste.js ran with scripts off") |
| + p.check(`(()=>{const b=[...document.querySelectorAll('[equipo-paste]')].slice(-2);return b.every(x=>{const st=getComputedStyle(x.querySelector('[equipo-paste-copy]'));return (st.display==='none'||st.visibility==='hidden')&&getComputedStyle(x.querySelector('pre > code')).userSelect!=='none'})&&b[0].querySelector('pre > code').textContent===`+jsonString(pastedCommand+"\n")+`})()`, "without script Copy shows, or the text is not there to select") |
| + shot("noscript") |
| +} |
diff --git a/internal/plan3test/conversation_draft_test.go b/internal/plan3test/conversation_draft_test.go| index 2fce5fc1..fc205359 100644 |
| --- a/internal/plan3test/conversation_draft_test.go |
| +++ b/internal/plan3test/conversation_draft_test.go |
| @@ -31,7 +31,7 @@ func TestConversationDraftRendersOnTheServer(t *testing.T) { |
| } |
| text := "**Yes.** Two people see it:\n\n- **Guest:** the basket\n- **Cus" |
| w := post(true, "same-origin", text) |
| - if w.Code != 200 || w.Body.String() != string(chatmarkdown.RenderDraft(text)) { |
| + if w.Code != 200 || w.Body.String() != string(chatmarkdown.Labels{}.RenderDraft(text)) /* no fence, so no paste box words */ { |
| t.Fatalf("draft render: %d %q", w.Code, w.Body.String()) |
| } |
| if !strings.HasPrefix(w.Header().Get("Content-Type"), "text/html") || w.Header().Get("Cache-Control") != "no-store" { |
diff --git a/internal/runner/thin/capabilities.go b/internal/runner/thin/capabilities.go| index ebd6e6b4..be2b130b 100644 |
| --- a/internal/runner/thin/capabilities.go |
| +++ b/internal/runner/thin/capabilities.go |
| @@ -2,9 +2,11 @@ package thin |
| import ( |
| "context" |
| + "log/slog" |
| "os/exec" |
| "regexp" |
| "runtime" |
| + "strings" |
| "sync" |
| "time" |
| @@ -21,10 +23,14 @@ const capabilityEvery = time.Hour |
| // runner had to refuse), sent with every heartbeat. |
| type Capabilities struct { |
| Probe func(context.Context) wire.Capabilities |
| + // Logger hears each gathering: the first (the one the first hello |
| + // waits on) at info, later ones at debug. |
| + Logger *slog.Logger |
| - mu sync.Mutex |
| - last wire.Capabilities |
| - at time.Time |
| + mu sync.Mutex |
| + last wire.Capabilities |
| + at time.Time |
| + logged bool |
| } |
| // Get is the newest report, probing when it is older than an hour. |
| @@ -32,7 +38,18 @@ func (c *Capabilities) Get(ctx context.Context) wire.Capabilities { |
| c.mu.Lock() |
| defer c.mu.Unlock() |
| if c.at.IsZero() || time.Since(c.at) > capabilityEvery { |
| + level := slog.LevelDebug |
| + if !c.logged { |
| + level, c.logged = slog.LevelInfo, true |
| + } |
| + start := time.Now() |
| + if c.Logger != nil { |
| + c.Logger.Log(ctx, level, "capabilities gathering") |
| + } |
| next := c.Probe(ctx) |
| + if c.Logger != nil { |
| + c.Logger.Log(ctx, level, "capabilities gathered", "took", took(start), "tags", strings.Join(next.Tags, ",")) |
| + } |
| if wire.ValidCapabilities(next) != nil { |
| // Out of bounds: say only the tags, which are always valid. |
| next = wire.Capabilities{Tags: next.Tags} |
diff --git a/internal/runner/thin/claude.go b/internal/runner/thin/claude.go| index e3a6e742..481b8451 100644 |
| --- a/internal/runner/thin/claude.go |
| +++ b/internal/runner/thin/claude.go |
| @@ -529,7 +529,7 @@ func (c *claudeCoordinator) idleExit() { |
| // houseRule versions the opening's rule. Changing the rule's text changes |
| // it, so sessions started under an older rule are not resumed. |
| -const houseRule = "2026-11-07.9" |
| +const houseRule = "2026-11-11.1" |
| // sessionAccount records the account and house rule a session runs on. |
| func (c *coordBase) sessionAccount() string { return c.account.ID + "#rule-" + houseRule } |
| @@ -619,6 +619,7 @@ func opening(person string, catalog []wire.RepoInfo) string { |
| b.WriteString("When the person reports a bug or asks for a change, call record_task at once, before investigating, with the repository it belongs to, a short title and their words as the brief. Then investigate with search_code and read_file, attach what you found with add_finding (a one-sentence headline for the person, plain words and no file paths, and the full finding with its file and line), and call start_task with a brief for Engineering. Engineering changes the code on the task's own branch and pushes it to Amadan; the change is then checked and reviewed, and Equipo's merge rules decide whether it merges on its own or asks the person with a card that gives Equipo's call. You cannot make it merge: when you have a concrete reason a change needs the person's look, call hold_merge with that reason. When the person says how a project should merge (\"always ask me about Suite\", \"main is not a release for Woodstar\"), call set_merge_policy with their words; a stricter rule applies at once and a looser one waits for their tap. Never offer to merge or open a pull request, and never ask the person to merge. Use ask_person only for a question only the person can answer.\n") |
| b.WriteString("Never file the same problem twice. If record_task returns similar open tasks and one of them is what the person is reporting, call add_report on it with their words and tell them in one line it is already logged and where it stands, naming it as a markdown link; record a separate task only when it is clearly a different problem.\n") |
| b.WriteString("Speak at the outcome level: what you understood, what is happening, what you need from the person. For example: \"Got it, I've logged [Swipe back doesn't work](/tasks/tk...) and Engineering is on it.\" No file paths, line numbers or code mechanics in your replies; the diagnosis goes on the task with add_finding. Always name a task as a markdown link with its title and the link from record_task, start_task or read_task, never as \"the task card\".\n") |
| + b.WriteString("Anything the person may need to paste (commands, prompts, config, codes) goes in a fenced code block, one block per thing to paste, with its kind after the opening fence (bash for a command, prompt for a prompt, text for plain text): the chat shows each block with a Copy button.\n") |
| b.WriteString("When the person wants specifics about how something was changed, do not explain them yourself: point them to the task, where they can ask the specialist who did the work, for example \"You can ask Engineering on [Swipe back doesn't work](/tasks/tk...).\" (or Review, about the review). Never relay technical detail from read_task.\n") |
| b.WriteString("When the person names an app, product or feature, use find, then search_code and read_file to answer from the actual code. Never ask which repository or framework. If find reaches nothing, say so in one short line and stop there: the person sees a card showing how to give Equipo access, so do not repeat it.\n") |
| b.WriteString("When the person says a project is a priority, or no longer is, call star_project and say so in one line.\n") |
diff --git a/internal/runner/thin/contract_test.go b/internal/runner/thin/contract_test.go| index c7fa7378..ea029b6d 100644 |
| --- a/internal/runner/thin/contract_test.go |
| +++ b/internal/runner/thin/contract_test.go |
| @@ -516,7 +516,7 @@ func TestStartupRefusesSharedRootsBeforeRecovery(t *testing.T) { |
| first := runner.Config{ScratchRoot: filepath.Join(root, "scratch"), WorkspaceRoot: filepath.Join(root, "work"), StateDir: filepath.Join(root, "state-a")} |
| second := first |
| second.StateDir = filepath.Join(root, "state-b") |
| - release, err := startup(context.Background(), first, func(context.Context) error { return nil }) |
| + release, err := startup(context.Background(), first, nil, func(context.Context) error { return nil }) |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -528,7 +528,7 @@ func TestStartupRefusesSharedRootsBeforeRecovery(t *testing.T) { |
| record := filepath.Join(first.ScratchRoot, "0123456789abcdef0123456789abcdef.json") |
| os.WriteFile(record, []byte("{}"), 0600) |
| recovered := false |
| - if _, err = startup(context.Background(), second, func(context.Context) error { recovered = true; return nil }); err != ErrRootShared { |
| + if _, err = startup(context.Background(), second, nil, func(context.Context) error { recovered = true; return nil }); err != ErrRootShared { |
| t.Fatalf("second runner on shared roots: %v", err) |
| } |
| if recovered { |
diff --git a/internal/runner/thin/link.go b/internal/runner/thin/link.go| index b99ed0b2..9f282014 100644 |
| --- a/internal/runner/thin/link.go |
| +++ b/internal/runner/thin/link.go |
| @@ -7,6 +7,7 @@ import ( |
| "log/slog" |
| "math/rand/v2" |
| "net/http" |
| + "net/url" |
| "strings" |
| "sync" |
| "time" |
| @@ -369,13 +370,9 @@ func (l *Link) Run(ctx context.Context) error { |
| } |
| return err |
| } |
| - if errors.Is(err, ErrInstanceTooOld) || errors.Is(err, ErrRoleMismatch) { |
| + older := errors.Is(err, ErrInstanceTooOld) || errors.Is(err, ErrRoleMismatch) |
| + if older { |
| retry = olderRetry |
| - if l.Logger != nil { |
| - l.Logger.Error("runner refused: this runner is a worker and the instance is an older release", "origin", l.Origin, "err", err) |
| - } |
| - } else if err != nil && l.Logger != nil { |
| - l.Logger.Warn("runner stream", "err", err) |
| } |
| wait := backoff |
| if retry > 0 { |
| @@ -384,6 +381,18 @@ func (l *Link) Run(ctx context.Context) error { |
| backoff *= 2 |
| } |
| wait += time.Duration(rand.Int64N(int64(wait / 4))) |
| + // Every ending is logged with the wait before the next try, the |
| + // first included: a runner that never connects says why. |
| + if l.Logger != nil { |
| + switch { |
| + case older: |
| + l.Logger.Error("runner refused: this runner is a worker and the instance is an older release", "origin", l.Origin, "err", err, "retry_in", wait.Round(time.Millisecond)) |
| + case err != nil: |
| + l.Logger.Warn("runner stream", "err", err, "retry_in", wait.Round(time.Millisecond)) |
| + default: |
| + l.Logger.Info("runner stream ended", "retry_in", wait.Round(time.Millisecond)) |
| + } |
| + } |
| select { |
| case <-ctx.Done(): |
| return ctx.Err() |
| @@ -448,6 +457,9 @@ func (l *Link) session(ctx context.Context) (time.Duration, error) { |
| // handshake dials, says hello at offer and reads the welcome. |
| func (l *Link) handshake(ctx context.Context, offer int) (*websocket.Conn, *wire.Welcome, error) { |
| url := "ws" + strings.TrimPrefix(l.Origin, "http") + wire.StreamPath |
| + host := originHost(l.Origin) |
| + l.info("connecting", "host", host, "protocol", offer) |
| + start := time.Now() |
| dctx, cancel := context.WithTimeout(ctx, 20*time.Second) |
| c, res, err := websocket.Dial(dctx, url, &websocket.DialOptions{HTTPHeader: http.Header{"Authorization": {"Bearer " + l.Token}}, CompressionMode: websocket.CompressionDisabled}) |
| cancel() |
| @@ -457,6 +469,7 @@ func (l *Link) handshake(ctx context.Context, offer int) (*websocket.Conn, *wire |
| } |
| return nil, nil, err |
| } |
| + l.info("connected", "host", host, "took", took(start)) |
| c.SetReadLimit(wire.MaxFrameBytes) |
| hello := l.Hello() |
| l.mu.Lock() |
| @@ -467,6 +480,7 @@ func (l *Link) handshake(ctx context.Context, offer int) (*websocket.Conn, *wire |
| c.CloseNow() |
| return nil, nil, err |
| } |
| + l.info("hello sent", "protocol", offer) |
| rctx, rcancel := context.WithTimeout(ctx, 15*time.Second) |
| _, raw, err := c.Read(rctx) |
| rcancel() |
| @@ -507,9 +521,26 @@ func (l *Link) handshake(ctx context.Context, offer int) (*websocket.Conn, *wire |
| l.mu.Lock() |
| l.proto, l.role = min(spoken, offer), role |
| l.mu.Unlock() |
| + l.info("welcome", "protocol", min(spoken, offer), "role", role, "generation", welcome.Generation) |
| return c, welcome, nil |
| } |
| +// info logs one line of a connection's start (a few per reconnect). |
| +func (l *Link) info(msg string, args ...any) { |
| + if l.Logger != nil { |
| + l.Logger.Info(msg, args...) |
| + } |
| +} |
| + |
| +// originHost is the origin's host and port alone, for a log line. |
| +func originHost(origin string) string { |
| + u, err := url.Parse(origin) |
| + if err != nil { |
| + return "" |
| + } |
| + return u.Host |
| +} |
| + |
| // serve runs one connection after its welcome. |
| func (l *Link) serve(ctx context.Context, c *websocket.Conn, welcome *wire.Welcome) (time.Duration, error) { |
| defer c.CloseNow() |
diff --git a/internal/runner/thin/mac.go b/internal/runner/thin/mac.go| index 091f74f8..4e6cf78a 100644 |
| --- a/internal/runner/thin/mac.go |
| +++ b/internal/runner/thin/mac.go |
| @@ -7,11 +7,13 @@ import ( |
| "encoding/json" |
| "errors" |
| "io" |
| + "log/slog" |
| "net" |
| "net/http" |
| "os" |
| "os/exec" |
| "path/filepath" |
| + "strconv" |
| "strings" |
| "sync" |
| "sync/atomic" |
| @@ -123,24 +125,53 @@ const probeTrust = 24 * time.Hour |
| // for this checks profile, made with the srt, Node and ripgrep that are |
| // on disk now matching the pins compiled into this binary (verified), |
| // and less than a day old; otherwise checks |
| -// run as not verified and the probes run again. `equipo-runner probe` |
| -// only asks for that (request): a forged request costs a probe run and |
| -// never upgrades trust. |
| +// run as not verified. The probes run again only when that can change |
| +// the answer (see untrusted), not on every look. `equipo-runner probe` |
| +// asks for a run at once (request): a forged request costs a probe run |
| +// and never upgrades trust. |
| type macProbes struct { |
| version string |
| run func(context.Context) mac.Report |
| verified func() bool |
| - request string |
| - now func() time.Time |
| + // fingerprint names the tools on disk a report depends on (cheaply: |
| + // paths, link targets, sizes and times); nil is "". |
| + fingerprint func() string |
| + request string |
| + now func() time.Time |
| + // log hears each run start and finish, with the verdicts, and why a |
| + // report is not trusted. |
| + log *slog.Logger |
| mu sync.Mutex |
| last mac.Report |
| ready chan struct{} |
| again chan struct{} |
| + // What the last run was made with and when it started; whether a |
| + // run asked for by untrusted has yet to report; the wait before the |
| + // next run of an unchanged untrusted report; the last reason warned. |
| + ranWith string |
| + ranAt time.Time |
| + pending bool |
| + backoff time.Duration |
| + warned string |
| } |
| +// probeRetry is the first wait before an untrusted report whose inputs |
| +// have not changed is probed again; it doubles up to probeTrust. |
| +const probeRetry = time.Hour |
| + |
| func newMacProbes(version, request string, run func(context.Context) mac.Report, verified func() bool) *macProbes { |
| - return &macProbes{version: version, request: request, run: run, verified: verified, now: time.Now, ready: make(chan struct{}), again: make(chan struct{}, 1)} |
| + return &macProbes{version: version, request: request, run: run, verified: verified, now: time.Now, ready: make(chan struct{}), again: make(chan struct{}, 1), backoff: probeRetry} |
| +} |
| + |
| +// inputs is what a report depends on: this binary's version, the tools' |
| +// fingerprint and whether they match their pins. |
| +func (p *macProbes) inputs(verified bool) string { |
| + fp := "" |
| + if p.fingerprint != nil { |
| + fp = p.fingerprint() |
| + } |
| + return p.version + "|" + strconv.FormatBool(verified) + "|" + fp |
| } |
| // report is the newest report, for the instance to show. |
| @@ -153,13 +184,68 @@ func (p *macProbes) report() mac.Report { |
| // trusted is the newest report and whether it may decide a gate now. |
| func (p *macProbes) trusted() (mac.Report, bool) { |
| r := p.report() |
| - ok := r.Version == p.version && r.Profile == mac.ProfileDigest() && r.SRT == srtPinned && p.verified() && !r.At.IsZero() && p.now().Sub(r.At) < probeTrust && p.now().Sub(r.At) >= -time.Minute |
| + verified, now := p.verified(), p.now() |
| + ok := r.Version == p.version && r.Profile == mac.ProfileDigest() && r.SRT == srtPinned && verified && !r.At.IsZero() && now.Sub(r.At) < probeTrust && now.Sub(r.At) >= -time.Minute |
| if !ok && !r.At.IsZero() { |
| - p.probeSoon() |
| + p.untrusted(r, verified, now) |
| } |
| return r, ok |
| } |
| +// untrusted decides whether an untrusted report is probed again. Every |
| +// hello and every check looks, so asking each time would run the whole |
| +// suite on every heartbeat. A run is asked for when the report expired, |
| +// or what it was made with changed (the version, the tools' fingerprint, |
| +// whether they match their pins), or else once probeRetry has passed |
| +// since the last run, the wait doubling each time up to a day. One run |
| +// at a time: none is asked for while one asked for has yet to report. |
| +// Each reason, and each run it asks for, is warned once. |
| +func (p *macProbes) untrusted(r mac.Report, verified bool, now time.Time) { |
| + reason := "" |
| + switch { |
| + case r.Version != p.version || r.Profile != mac.ProfileDigest(): |
| + reason = "the report is another runner version's or checks profile's" |
| + case !verified: |
| + reason = "srt or its tools on disk do not match their pins" |
| + case r.SRT != srtPinned: |
| + reason = "the report was made with tools that did not match their pins" |
| + case now.Sub(r.At) < -time.Minute: |
| + reason = "the report is dated in the future" |
| + default: |
| + reason = "the report is more than a day old" |
| + } |
| + expired := now.Sub(r.At) >= probeTrust || now.Sub(r.At) < -time.Minute |
| + inputs := p.inputs(verified) |
| + p.mu.Lock() |
| + again, why := false, "" |
| + switch { |
| + case p.pending: |
| + case expired: |
| + again, why = true, "expired" |
| + case inputs != p.ranWith: |
| + again, why, p.backoff = true, "its inputs changed", probeRetry |
| + case now.Sub(p.ranAt) >= p.backoff: |
| + again, why = true, "retry after "+p.backoff.String() |
| + p.backoff = min(2*p.backoff, probeTrust) |
| + } |
| + if again { |
| + p.pending = true |
| + } |
| + warn := again || reason != p.warned |
| + p.warned = reason |
| + p.mu.Unlock() |
| + if warn && p.log != nil { |
| + attrs := []any{"reason", reason, "probe_again", again} |
| + if again { |
| + attrs = append(attrs, "because", why) |
| + } |
| + p.log.Warn("probe report not trusted", attrs...) |
| + } |
| + if again { |
| + p.probeSoon() |
| + } |
| +} |
| + |
| func (p *macProbes) probeSoon() { |
| select { |
| case p.again <- struct{}{}: |
| @@ -173,20 +259,42 @@ func (p *macProbes) probeSoon() { |
| func (p *macProbes) start(ctx context.Context, refresh func()) { |
| go func() { |
| first := true |
| + said := "" |
| for { |
| // The tools must match their pins before the probes and still |
| // after them: a report made with anything else is never |
| // trusted. |
| before := p.verified() |
| + inputs := p.inputs(before) |
| + p.mu.Lock() |
| + p.ranWith, p.ranAt = inputs, p.now() |
| + p.mu.Unlock() |
| + // The first run at info; later ones (a day on, asked for, or |
| + // an untrusted report's retry) at debug unless their verdicts |
| + // changed. |
| + start, level := time.Now(), slog.LevelDebug |
| + if first { |
| + level = slog.LevelInfo |
| + } |
| + if p.log != nil { |
| + p.log.Log(ctx, level, "probes started") |
| + } |
| r := p.run(ctx) |
| if ctx.Err() != nil { |
| return |
| } |
| + if v := verdicts(r.Probes); p.log != nil { |
| + if v != said { |
| + level = slog.LevelInfo |
| + } |
| + p.log.Log(ctx, level, "probes finished", "took", took(start), "verdicts", v) |
| + said = v |
| + } |
| if before && p.verified() { |
| r.SRT = srtPinned |
| } |
| p.mu.Lock() |
| - p.last = r |
| + p.last, p.pending = r, false |
| p.mu.Unlock() |
| if first { |
| close(p.ready) |
| @@ -223,6 +331,16 @@ func (p *macProbes) watch(ctx context.Context) { |
| } |
| } |
| +// verdicts is each probe's name and verdict ("P1=passed P2=denied"), |
| +// never its detail. |
| +func verdicts(probes []wire.Probe) string { |
| + out := make([]string, 0, len(probes)) |
| + for _, p := range probes { |
| + out = append(out, p.ID+"="+p.Verdict) |
| + } |
| + return strings.Join(out, " ") |
| +} |
| + |
| func (p *macProbes) wait(ctx context.Context) error { |
| select { |
| case <-p.ready: |
| @@ -232,6 +350,24 @@ func (p *macProbes) wait(ctx context.Context) error { |
| } |
| } |
| +// toolFingerprint names the tools a probe report depends on without |
| +// reading them (verified hashes them): each one's path, link target, |
| +// size, mode and modification time, and the srt package tree's. |
| +func toolFingerprint(installDir string, t mac.Tools) string { |
| + var b strings.Builder |
| + for _, path := range []string{t.SRT, t.Node, t.RG, filepath.Join(installDir, "srt", "node_modules")} { |
| + b.WriteString(path) |
| + if target, err := os.Readlink(path); err == nil { |
| + b.WriteString(" -> " + target) |
| + } |
| + if info, err := os.Stat(path); err == nil { |
| + b.WriteString(" " + strconv.FormatInt(info.Size(), 10) + " " + info.Mode().String() + " " + strconv.FormatInt(info.ModTime().UnixNano(), 10)) |
| + } |
| + b.WriteByte('\n') |
| + } |
| + return b.String() |
| +} |
| + |
| // srtPinned marks a report made with srt, Node and ripgrep matching the |
| // pins compiled into this binary. |
| const srtPinned = "pinned" |
| @@ -251,8 +387,21 @@ type macHost struct { |
| checks *macChecks |
| taint *macTaint |
| caps func(context.Context) wire.Capabilities |
| + // log hears slow commands, and each command of the first capability |
| + // gathering (capsLogged) and of xcode-select at start. |
| + log *slog.Logger |
| + capsLogged atomic.Bool |
| } |
| +// slowCommand is how long a command the Mac worker runs may take before |
| +// it is logged as slow: while it still runs, so a hung child shows. |
| +var slowCommand = 10 * time.Second |
| + |
| +// commandWaitDelay bounds how long run waits for a command's output once |
| +// it has exited or been killed: a grandchild still holding the pipe |
| +// cannot hold the runner. |
| +var commandWaitDelay = 5 * time.Second |
| + |
| // Mac tool discovery (spec §3.3): EQUIPO_SRT_PATH and the installer's |
| // private srt first, then the usual places. |
| func macTools(installDir, home string, getenv func(string) string) mac.Tools { |
| @@ -289,10 +438,79 @@ func executable(p string) bool { |
| func (h *macHost) run(ctx context.Context, name string, args ...string) (string, error) { |
| cmd := exec.CommandContext(ctx, name, args...) |
| cmd.Env = withPath(os.Environ(), gatePath(h.tools)) |
| + // Its own process group, killed whole at the timeout, and a bounded |
| + // wait for its output: a grandchild holding the pipe (xcrun, swift |
| + // or claude starting a helper) cannot block run past its timeout. |
| + ownGroup(cmd) |
| + cmd.WaitDelay = commandWaitDelay |
| + done := h.watchSlow(name, args) |
| out, err := cmd.Output() |
| + if errors.Is(err, exec.ErrWaitDelay) { |
| + // The command itself exited successfully; only something it left |
| + // behind in its group still held the pipe. That goes, and what |
| + // the command printed is its answer. |
| + _ = killGroup(cmd) |
| + err = nil |
| + if h.log != nil { |
| + h.log.Debug("command left a helper holding its output; helper killed", "cmd", name, "args", logArgs(args)) |
| + } |
| + } |
| + done(err) |
| return string(out), err |
| } |
| +// watchSlow warns when a command is still running after slowCommand, |
| +// and again with its time and error when such a command ends. |
| +func (h *macHost) watchSlow(name string, args []string) func(error) { |
| + if h.log == nil { |
| + return func(error) {} |
| + } |
| + start, limit := time.Now(), slowCommand |
| + t := time.AfterFunc(limit, func() { |
| + h.log.Warn("command still running", "cmd", name, "args", logArgs(args), "after", limit) |
| + }) |
| + return func(err error) { |
| + if t.Stop() { |
| + return |
| + } |
| + attrs := []any{"cmd", name, "args", logArgs(args), "took", took(start)} |
| + if err != nil { |
| + attrs = append(attrs, "err", err.Error()) |
| + } |
| + h.log.Warn("slow command finished", attrs...) |
| + } |
| +} |
| + |
| +// logged runs a command through run and logs it at level with its time |
| +// and, when it failed, its exit status. |
| +func (h *macHost) logged(level slog.Level) mac.Exec { |
| + return func(ctx context.Context, name string, args ...string) (string, error) { |
| + start := time.Now() |
| + out, err := h.run(ctx, name, args...) |
| + if h.log != nil { |
| + attrs := []any{"cmd", name, "args", logArgs(args), "took", took(start)} |
| + if err != nil { |
| + attrs = append(attrs, "err", err.Error()) |
| + } |
| + h.log.Log(ctx, level, "command", attrs...) |
| + } |
| + return out, err |
| + } |
| +} |
| + |
| +// logArgs is a command's arguments for a log line, a password argument's |
| +// value (security -w) withheld. |
| +func logArgs(args []string) string { |
| + out := make([]string, len(args)) |
| + for i, a := range args { |
| + if i > 0 && args[i-1] == "-w" { |
| + a = "[withheld]" |
| + } |
| + out[i] = a |
| + } |
| + return strings.Join(out, " ") |
| +} |
| + |
| func withPath(env []string, path string) []string { |
| out := []string{"PATH=" + path} |
| for _, kv := range env { |
| @@ -326,7 +544,9 @@ func contains(list []string, s string) bool { |
| return false |
| } |
| -func newMacHost(c runner.Config, o Options) (*macHost, error) { |
| +func newMacHost(c runner.Config, o Options) (h *macHost, err error) { |
| + done := startPhase(o.Logger, "mac_host") |
| + defer func() { done(err) }() |
| getenv := o.Getenv |
| if getenv == nil { |
| getenv = os.Getenv |
| @@ -339,13 +559,13 @@ func newMacHost(c runner.Config, o Options) (*macHost, error) { |
| if accounts == "" { |
| accounts = DefaultAccountsRoot() |
| } |
| - h := &macHost{scratch: c.ScratchRoot} |
| + h = &macHost{scratch: c.ScratchRoot, log: o.Logger} |
| others, err := mac.OtherHomes(macUsers, home) |
| h.paths = mac.Paths{Home: home, StateDir: c.StateDir, AccountsRoot: accounts, SessionRoot: SessionRoot(c), InstallDir: filepath.Dir(c.Executable), OtherHomes: others, HomesUnknown: err != nil} |
| h.tools = macTools(h.paths.InstallDir, home, getenv) |
| h.env = []string{"HOME=" + home, "PATH=" + gatePath(h.tools), "CI=1", "LANG=en_US.UTF-8"} |
| ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) |
| - if out, err := h.run(ctx, "/usr/bin/xcode-select", "-p"); err == nil && filepath.IsAbs(strings.TrimSpace(out)) { |
| + if out, err := h.logged(slog.LevelInfo)(ctx, "/usr/bin/xcode-select", "-p"); err == nil && filepath.IsAbs(strings.TrimSpace(out)) { |
| h.env = append(h.env, "DEVELOPER_DIR="+strings.TrimSpace(out)) |
| } |
| cancel() |
| @@ -379,10 +599,18 @@ func newMacHost(c runner.Config, o Options) (*macHost, error) { |
| h.probes = newMacProbes(o.Version, ProbeRequest(c), func(ctx context.Context) mac.Report { |
| return mac.RunProbes(ctx, h.probeHost(o.Version, gate)) |
| }, func() bool { return mac.VerifyTools(h.paths.InstallDir, h.tools) == nil }) |
| + h.probes.log = o.Logger |
| + h.probes.fingerprint = func() string { return toolFingerprint(h.paths.InstallDir, h.tools) } |
| h.taint = loadTaint(filepath.Join(c.StateDir, "tainted")) |
| h.checks = &macChecks{probes: h.probes, taint: h.taint, srt: h.tools.SRT, sandboxed: gate(h.tools.SRT, wire.SandboxSeatbelt), unproven: gate(h.tools.SRT, wire.SandboxNone), bare: gate("", wire.SandboxNone)} |
| h.caps = func(ctx context.Context) wire.Capabilities { |
| - caps := mac.Capabilities(ctx, h.run, h.tools) |
| + // The first gathering is the one the first hello waits on: each |
| + // command at info. Later ones (hourly, each check's gate) at debug. |
| + level := slog.LevelDebug |
| + if h.capsLogged.CompareAndSwap(false, true) { |
| + level = slog.LevelInfo |
| + } |
| + caps := mac.Capabilities(ctx, h.logged(level), h.tools) |
| if probes := h.probes.report().Probes; len(probes) > 0 { |
| caps.Probes = probes |
| } |
| @@ -433,6 +661,11 @@ func runMac(ctx context.Context, c runner.Config, o Options) error { |
| if err != nil { |
| return err |
| } |
| + return serveMac(ctx, c, o, h) |
| +} |
| + |
| +// serveMac serves the instance as the Mac worker h sets up. |
| +func serveMac(ctx context.Context, c runner.Config, o Options, h *macHost) error { |
| if o.Logger != nil && h.tools.SRT == "" { |
| o.Logger.Warn("srt is not installed: checks run outside the sandbox and say so") |
| } |
diff --git a/internal/runner/thin/probe_storm_test.go b/internal/runner/thin/probe_storm_test.go| new file mode 100644 |
| index 00000000..30e49236 |
| --- /dev/null |
| +++ b/internal/runner/thin/probe_storm_test.go |
| @@ -0,0 +1,77 @@ |
| +package thin |
| + |
| +import ( |
| + "log/slog" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// An untrusted report is not probed again on every look (every hello |
| +// and check looks): only when what it was made with changes, or an hour |
| +// on with the wait doubling, and each decision is warned once. A request |
| +// (equipo-runner probe) still runs the probes at once. |
| +func TestMacProbesUntrustedDoNotStorm(t *testing.T) { |
| + x := newProbeRig(t) |
| + x.pinned = false |
| + var fp atomic.Value |
| + fp.Store("tools-a") |
| + x.p.fingerprint = func() string { return fp.Load().(string) } |
| + logs := &syncBuffer{} |
| + x.p.log = slog.New(slog.NewTextHandler(logs, nil)) |
| + x.started(t) |
| + look := func() { |
| + t.Helper() |
| + for range 50 { |
| + if _, ok := x.p.trusted(); ok { |
| + t.Fatal("a report made with tools off their pins trusted") |
| + } |
| + } |
| + } |
| + runs := func(want int32) { |
| + t.Helper() |
| + look() |
| + deadline := time.Now().Add(5 * time.Second) |
| + for { |
| + x.p.mu.Lock() |
| + pending := x.p.pending |
| + x.p.mu.Unlock() |
| + if x.runs.Load() >= want && !pending { |
| + break |
| + } |
| + if time.Now().After(deadline) { |
| + t.Fatalf("%d probe runs, want %d (pending %v):\n%s", x.runs.Load(), want, pending, logs) |
| + } |
| + time.Sleep(10 * time.Millisecond) |
| + } |
| + look() |
| + time.Sleep(100 * time.Millisecond) |
| + if n := x.runs.Load(); n != want { |
| + t.Fatalf("%d probe runs, want %d:\n%s", n, want, logs) |
| + } |
| + } |
| + warned := func() int { return strings.Count(logs.String(), `level=WARN msg="probe report not trusted"`) } |
| + |
| + runs(1) |
| + if n := warned(); n != 1 || !strings.Contains(logs.String(), "probe_again=false") { |
| + t.Fatalf("an unchanged untrusted report warned %d times:\n%s", n, logs) |
| + } |
| + fp.Store("tools-b") |
| + runs(2) |
| + if !strings.Contains(logs.String(), `because="its inputs changed"`) { |
| + t.Fatalf("no warning for the rerun:\n%s", logs) |
| + } |
| + x.now = x.now.Add(probeRetry) |
| + runs(3) |
| + // The next retry waits two hours: one more hour is not enough. |
| + x.now = x.now.Add(probeRetry) |
| + runs(3) |
| + x.now = x.now.Add(probeRetry) |
| + runs(4) |
| + if n := warned(); n != 4 { |
| + t.Fatalf("%d warnings for 3 reruns and the first look:\n%s", n, logs) |
| + } |
| + x.p.probeSoon() |
| + runs(5) |
| +} |
diff --git a/internal/runner/thin/procgroup_other.go b/internal/runner/thin/procgroup_other.go| new file mode 100644 |
| index 00000000..78eca926 |
| --- /dev/null |
| +++ b/internal/runner/thin/procgroup_other.go |
| @@ -0,0 +1,12 @@ |
| +//go:build !unix |
| + |
| +package thin |
| + |
| +import "os/exec" |
| + |
| +// ownGroup leaves cmd as it is where there are no Unix process groups: |
| +// its context kills cmd alone, and WaitDelay still bounds the wait. |
| +func ownGroup(*exec.Cmd) {} |
| + |
| +// killGroup has no group to kill here. |
| +func killGroup(*exec.Cmd) error { return nil } |
diff --git a/internal/runner/thin/procgroup_unix.go b/internal/runner/thin/procgroup_unix.go| new file mode 100644 |
| index 00000000..96b560c7 |
| --- /dev/null |
| +++ b/internal/runner/thin/procgroup_unix.go |
| @@ -0,0 +1,29 @@ |
| +//go:build unix |
| + |
| +package thin |
| + |
| +import ( |
| + "errors" |
| + "os/exec" |
| + "syscall" |
| +) |
| + |
| +// ownGroup starts cmd in a process group of its own and makes the end of |
| +// its context kill that whole group, not only cmd: a grandchild that |
| +// ignores SIGTERM and holds cmd's output dies with it. |
| +func ownGroup(cmd *exec.Cmd) { |
| + cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} |
| + cmd.Cancel = func() error { return killGroup(cmd) } |
| +} |
| + |
| +// killGroup sends SIGKILL to cmd's process group (-pgid); a group that |
| +// is already gone is not an error. |
| +func killGroup(cmd *exec.Cmd) error { |
| + if cmd.Process == nil { |
| + return nil |
| + } |
| + if err := syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL); err != nil && !errors.Is(err, syscall.ESRCH) { |
| + return err |
| + } |
| + return nil |
| +} |
diff --git a/internal/runner/thin/procgroup_unix_test.go b/internal/runner/thin/procgroup_unix_test.go| new file mode 100644 |
| index 00000000..da225753 |
| --- /dev/null |
| +++ b/internal/runner/thin/procgroup_unix_test.go |
| @@ -0,0 +1,112 @@ |
| +//go:build unix |
| + |
| +package thin |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "log/slog" |
| + "os" |
| + "path/filepath" |
| + "strconv" |
| + "strings" |
| + "syscall" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// A command whose grandchild ignores SIGTERM and holds its output open |
| +// cannot hold run past its timeout: the whole process group is killed |
| +// when the context ends, and WaitDelay bounds the wait for the pipes. |
| +// The grandchild is gone afterwards. |
| +func TestMacRunEndsAHungGrandchild(t *testing.T) { |
| + pidFile := filepath.Join(t.TempDir(), "grandchild") |
| + pid := 0 |
| + t.Cleanup(func() { |
| + // Only the grandchild this test started, by pid, if it is still |
| + // that sleep. |
| + if pid > 0 && grandchildAlive(pid) { |
| + _ = syscall.Kill(pid, syscall.SIGKILL) |
| + } |
| + }) |
| + const timeout = 300 * time.Millisecond |
| + script := `sh -c 'trap "" TERM; echo $$ > "$1"; exec sleep 15' grandchild "$1" & wait` |
| + ctx, cancel := context.WithTimeout(context.Background(), timeout) |
| + defer cancel() |
| + start := time.Now() |
| + _, err := (&macHost{}).run(ctx, "/bin/sh", "-c", script, "child", pidFile) |
| + took := time.Since(start) |
| + if raw, rerr := os.ReadFile(pidFile); rerr == nil { |
| + pid, _ = strconv.Atoi(strings.TrimSpace(string(raw))) |
| + } |
| + if limit := timeout + commandWaitDelay + 2*time.Second; took > limit { |
| + t.Fatalf("run took %s, past its timeout and WaitDelay (%s): err %v", took.Round(time.Millisecond), limit, err) |
| + } |
| + if err == nil { |
| + t.Fatal("a command killed at its timeout succeeded") |
| + } |
| + if pid <= 0 { |
| + t.Fatal("the grandchild never started") |
| + } |
| + for deadline := time.Now().Add(2 * time.Second); grandchildAlive(pid); time.Sleep(20 * time.Millisecond) { |
| + if time.Now().After(deadline) { |
| + t.Fatalf("the grandchild %d outlived run", pid) |
| + } |
| + } |
| +} |
| + |
| +// A command that exits at once but leaves a helper holding its output |
| +// answers within WaitDelay with what it printed, and the helper, left in |
| +// the command's own group, is gone. |
| +func TestMacRunAnswersPastALingeringHelper(t *testing.T) { |
| + was := commandWaitDelay |
| + commandWaitDelay = 200 * time.Millisecond |
| + defer func() { commandWaitDelay = was }() |
| + pidFile := filepath.Join(t.TempDir(), "helper") |
| + pid := 0 |
| + t.Cleanup(func() { |
| + if pid > 0 && grandchildAlive(pid) { |
| + _ = syscall.Kill(pid, syscall.SIGKILL) |
| + } |
| + }) |
| + script := `echo 1.2.3; sh -c 'echo $$ > "$1"; exec sleep 15' helper "$1" & while [ ! -s "$1" ]; do sleep 0.01; done` |
| + start := time.Now() |
| + var logs bytes.Buffer |
| + host := &macHost{log: slog.New(slog.NewTextHandler(&logs, &slog.HandlerOptions{Level: slog.LevelDebug}))} |
| + out, err := host.run(context.Background(), "/bin/sh", "-c", script, "child", pidFile) |
| + took := time.Since(start) |
| + if raw, rerr := os.ReadFile(pidFile); rerr == nil { |
| + pid, _ = strconv.Atoi(strings.TrimSpace(string(raw))) |
| + } |
| + if pid <= 0 { |
| + t.Fatal("the helper never started") |
| + } |
| + if err != nil || out != "1.2.3\n" || took > 3*time.Second { |
| + t.Fatalf("run answered %q %v after %s", out, err, took.Round(time.Millisecond)) |
| + } |
| + // The leftover is said once, at debug only: it is not a failure. |
| + if l := logs.String(); !strings.Contains(l, "level=DEBUG msg=\"command left a helper holding its output; helper killed\"") || strings.Contains(l, "level=WARN") || strings.Contains(l, "level=ERROR") { |
| + t.Fatalf("the leftover helper was not logged at debug only: %q", l) |
| + } |
| + for deadline := time.Now().Add(2 * time.Second); pid > 0 && grandchildAlive(pid); time.Sleep(20 * time.Millisecond) { |
| + if time.Now().After(deadline) { |
| + t.Fatalf("the helper %d outlived run", pid) |
| + } |
| + } |
| +} |
| + |
| +// grandchildAlive: pid is a live process (not a zombie) running sleep. |
| +func grandchildAlive(pid int) bool { |
| + if syscall.Kill(pid, 0) != nil { |
| + return false |
| + } |
| + if stat, err := os.ReadFile("/proc/" + strconv.Itoa(pid) + "/stat"); err == nil { |
| + if i := strings.LastIndexByte(string(stat), ')'); i > 0 && i+2 < len(stat) && stat[i+2] == 'Z' { |
| + return false |
| + } |
| + } |
| + if cmdline, err := os.ReadFile("/proc/" + strconv.Itoa(pid) + "/cmdline"); err == nil { |
| + return strings.Contains(string(cmdline), "sleep") |
| + } |
| + return true |
| +} |
diff --git a/internal/runner/thin/run.go b/internal/runner/thin/run.go| index abcb88eb..7413aa8c 100644 |
| --- a/internal/runner/thin/run.go |
| +++ b/internal/runner/thin/run.go |
| @@ -5,6 +5,8 @@ import ( |
| "crypto/sha256" |
| "encoding/hex" |
| "errors" |
| + "fmt" |
| + "io/fs" |
| "log/slog" |
| "os" |
| "path/filepath" |
| @@ -21,6 +23,7 @@ import ( |
| "amadan.net/oficina/equipo/internal/runner/containment" |
| "amadan.net/oficina/equipo/internal/runner/mac" |
| "amadan.net/oficina/equipo/internal/runner/provider" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| "amadan.net/oficina/equipo/internal/sealbox" |
| "amadan.net/oficina/equipo/internal/wire" |
| ) |
| @@ -114,7 +117,7 @@ func Run(ctx context.Context, c runner.Config, o Options) error { |
| // Ownership first: the state lock, then the scratch and workspace |
| // roots. Only then may recovery touch namespaces or scratch. |
| var manager *containment.Manager |
| - release, err := startup(ctx, c, func(ctx context.Context) error { |
| + release, err := startup(ctx, c, o.Logger, func(ctx context.Context) error { |
| var err error |
| manager, err = containment.New(containment.Config{Binary: c.Bwrap(), RunnerBinary: c.Executable, ScratchRoot: c.ScratchRoot, ProviderNetworks: []provider.NetworkContract{{Provider: "claude"}, {Provider: "codex"}}}) |
| if err != nil { |
| @@ -133,11 +136,7 @@ func Run(ctx context.Context, c runner.Config, o Options) error { |
| return err |
| } |
| defer release() |
| - creds, err := runner.ReadCredentials(filepath.Join(c.StateDir, "credentials.json")) |
| - if err != nil { |
| - return err |
| - } |
| - state, err := OpenState(ctx, c.StateDir) |
| + creds, state, err := openRunner(ctx, c, o.Logger) |
| if err != nil { |
| return err |
| } |
| @@ -154,7 +153,7 @@ func Run(ctx context.Context, c runner.Config, o Options) error { |
| ctx, cancel := context.WithCancel(ctx) |
| defer cancel() |
| platform := hostPlatform() |
| - caps := &Capabilities{Probe: linuxCapabilities(c)} |
| + caps := &Capabilities{Probe: linuxCapabilities(c), Logger: o.Logger} |
| link := &Link{Origin: c.Origin, Token: creds.Bearer.Token, State: state, Logger: o.Logger, Connected: o.Connected, Protocol: o.Protocol, WorkerOnly: platform.OS == "darwin", Role: enrolledRole(c, creds.Bearer.Role)} |
| link.Files = &Files{State: state, SessionRoot: o.Claude.SessionRoot, Logger: o.Logger} |
| // Attachments stay bounded whether or not anything arrives. |
| @@ -368,20 +367,26 @@ const ownerFile = ".equipo-root-owner" |
| // ownership of its scratch and workspace roots, then recovery of what its |
| // own dead processes left (namespaces, then credential copies and other |
| // scratch). A runner refused its roots recovers and deletes nothing. |
| -func startup(ctx context.Context, c runner.Config, recover func(context.Context) error) (func(), error) { |
| +func startup(ctx context.Context, c runner.Config, log *slog.Logger, recover func(context.Context) error) (func(), error) { |
| + done := startPhase(log, "state_lock") |
| lock, err := runner.LockState(c.StateDir) |
| + done(err) |
| if err != nil { |
| return nil, err |
| } |
| + done = startPhase(log, "claim_roots") |
| roots, err := claimRoots(c) |
| + done(err) |
| if err != nil { |
| lock.Close() |
| return nil, err |
| } |
| release := func() { roots(); lock.Close() } |
| + done = startPhase(log, "sweep") |
| if err = recover(ctx); err == nil { |
| err = sweepOrphans(c) |
| } |
| + done(err) |
| if err != nil { |
| release() |
| return nil, err |
| @@ -389,6 +394,59 @@ func startup(ctx context.Context, c runner.Config, recover func(context.Context) |
| return release, nil |
| } |
| +// openRunner reads the runner's credential and opens its state, each a |
| +// logged startup phase. Nothing of the credential is logged. |
| +func openRunner(ctx context.Context, c runner.Config, log *slog.Logger) (runnerproto.CredentialRotation, *State, error) { |
| + done := startPhase(log, "credentials") |
| + creds, err := runner.ReadCredentials(filepath.Join(c.StateDir, "credentials.json")) |
| + done(credentialLogError(err)) |
| + if err != nil { |
| + return creds, nil, err |
| + } |
| + done = startPhase(log, "open_state") |
| + state, err := OpenState(ctx, c.StateDir) |
| + done(err) |
| + return creds, state, err |
| +} |
| + |
| +// credentialLogError is a credential read failure as it may be logged: a |
| +// path, policy or identity error as it is; anything the decoder said |
| +// about the file's content only by its type. |
| +func credentialLogError(err error) error { |
| + var path *fs.PathError |
| + if err == nil || errors.As(err, &path) || errors.Is(err, provider.ErrPolicy) || errors.Is(err, provider.ErrIdentity) { |
| + return err |
| + } |
| + return fmt.Errorf("unreadable credential file (%T)", err) |
| +} |
| + |
| +// startPhase logs a startup phase's start; the function it returns logs |
| +// its end, how long it took and its error. A silent hang at start is |
| +// pinned to the phase that started and never ended. |
| +func startPhase(log *slog.Logger, phase string) func(error) { |
| + if log == nil { |
| + return func(error) {} |
| + } |
| + start := time.Now() |
| + log.Info("startup phase", "phase", phase) |
| + return func(err error) { |
| + if err != nil { |
| + log.Warn("startup phase failed", "phase", phase, "took", took(start), "err", err.Error()) |
| + return |
| + } |
| + log.Info("startup phase done", "phase", phase, "took", took(start)) |
| + } |
| +} |
| + |
| +// took is the time since start, rounded for a log line. |
| +func took(start time.Time) time.Duration { |
| + d := time.Since(start) |
| + if d >= time.Second { |
| + return d.Round(time.Millisecond) |
| + } |
| + return d.Round(time.Microsecond) |
| +} |
| + |
| // prepareRoots claims the roots and sweeps orphans. |
| func prepareRoots(c runner.Config) (func(), error) { |
| release, err := claimRoots(c) |
| @@ -545,23 +603,19 @@ var ErrUpdated = errors.New("runner updated to the instance's release") |
| // runWorker serves the instance as a worker: it runs the steps placed on |
| // it and nothing else (no coordinator, no clone, no forge credential). |
| func runWorker(ctx context.Context, c runner.Config, o Options, platform wire.Platform, w workerSetup) error { |
| - release, err := startup(ctx, c, func(context.Context) error { return nil }) |
| + release, err := startup(ctx, c, o.Logger, func(context.Context) error { return nil }) |
| if err != nil { |
| return err |
| } |
| defer release() |
| - creds, err := runner.ReadCredentials(filepath.Join(c.StateDir, "credentials.json")) |
| - if err != nil { |
| - return err |
| - } |
| - state, err := OpenState(ctx, c.StateDir) |
| + creds, state, err := openRunner(ctx, c, o.Logger) |
| if err != nil { |
| return err |
| } |
| defer state.Close() |
| ctx, cancel := context.WithCancelCause(ctx) |
| defer cancel(nil) |
| - caps := &Capabilities{Probe: w.probe} |
| + caps := &Capabilities{Probe: w.probe, Logger: o.Logger} |
| link := &Link{Origin: c.Origin, Token: creds.Bearer.Token, State: state, Logger: o.Logger, Connected: o.Connected, Protocol: o.Protocol, WorkerOnly: true, Role: enrolledRole(c, creds.Bearer.Role)} |
| link.Hello = func() wire.Hello { |
| report := caps.Get(ctx) |
diff --git a/internal/runner/thin/startup_logs_test.go b/internal/runner/thin/startup_logs_test.go| new file mode 100644 |
| index 00000000..f1bfae02 |
| --- /dev/null |
| +++ b/internal/runner/thin/startup_logs_test.go |
| @@ -0,0 +1,204 @@ |
| +package thin |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "log/slog" |
| + "net" |
| + "net/http" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/runner" |
| + "amadan.net/oficina/equipo/internal/runner/mac" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "amadan.net/oficina/equipo/internal/wire" |
| + "github.com/coder/websocket" |
| +) |
| + |
| +// A Mac worker's start logs each phase at info, in order, through its |
| +// hello and the welcome: a hang shows as a phase that started and never |
| +// ended. The instance's first refusal is logged with its error and the |
| +// wait before the next try, and no line holds the bearer. |
| +func TestWorkerStartupLogs(t *testing.T) { |
| + root := t.TempDir() |
| + c := runner.Config{StateDir: filepath.Join(root, "state"), ScratchRoot: filepath.Join(root, "scratch"), WorkspaceRoot: filepath.Join(root, "work"), Executable: filepath.Join(root, "lib", "equipo-runner")} |
| + if err := os.Mkdir(c.StateDir, 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + const bearer = "bearer-5f2c9a71d04e-never-logged" |
| + credential, _ := json.Marshal(runnerproto.CredentialRotation{Bearer: runnerproto.RunnerCredential{Token: bearer, Role: wire.RoleWorker}}) |
| + if err := os.WriteFile(filepath.Join(c.StateDir, "credentials.json"), credential, 0600); err != nil { |
| + t.Fatal(err) |
| + } |
| + // The Mac's tools, as scripts that print a version; xcodebuild and |
| + // swift (fixed /usr/bin paths) are missing here, so they fail. |
| + bin := filepath.Join(root, "bin") |
| + if err := os.Mkdir(bin, 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + env := map[string]string{} |
| + for name, version := range map[string]string{"node": "v22.12.0", "srt": "0.0.81", "rg": "14.1.1", "claude": "2.1.312", "codex": "0.1.0"} { |
| + p := filepath.Join(bin, name) |
| + if err := os.WriteFile(p, []byte("#!/bin/sh\necho "+version+"\n"), 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + env["EQUIPO_"+strings.ToUpper(name)+"_PATH"] = p |
| + } |
| + was := macUsers |
| + macUsers = filepath.Join(root, "Users") |
| + defer func() { macUsers = was }() |
| + |
| + var dials atomic.Int32 |
| + conns := make(chan *websocket.Conn, 2) |
| + l, err := net.Listen("tcp", "127.0.0.1:0") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if dials.Add(1) == 1 { |
| + http.Error(w, "starting", http.StatusServiceUnavailable) |
| + return |
| + } |
| + if r.URL.Path != wire.StreamPath || r.Header.Get("Authorization") != "Bearer "+bearer { |
| + http.Error(w, "forbidden", http.StatusForbidden) |
| + return |
| + } |
| + ws, err := websocket.Accept(w, r, nil) |
| + if err != nil { |
| + return |
| + } |
| + conns <- ws |
| + <-r.Context().Done() |
| + })} |
| + go srv.Serve(l) |
| + defer srv.Close() |
| + c.Origin = "http://" + l.Addr().String() |
| + |
| + logs := &syncBuffer{} |
| + o := OptionsFromEnv(func(k string) string { return env[k] }) |
| + o.Version, o.Logger = "v-test", slog.New(slog.NewTextHandler(logs, nil)) |
| + h, err := newMacHost(c, o) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + // The probes' verdicts, without running the Mac's probes here. |
| + h.probes.run = func(context.Context) mac.Report { |
| + return mac.Report{Version: "v-test", Profile: mac.ProfileDigest(), At: time.Now(), Probes: probesAll(wire.ProbeDenied)} |
| + } |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + defer cancel() |
| + done := make(chan error, 1) |
| + go func() { done <- serveMac(ctx, c, o, h) }() |
| + |
| + var ws *websocket.Conn |
| + select { |
| + case ws = <-conns: |
| + case <-time.After(15 * time.Second): |
| + t.Fatalf("never connected:\n%s", logs) |
| + } |
| + rctx, rcancel := context.WithTimeout(context.Background(), 10*time.Second) |
| + _, raw, err := ws.Read(rctx) |
| + rcancel() |
| + if f, _, perr := wire.ParseFrame(raw); err != nil || perr != nil || f.Type != wire.FrameHello { |
| + t.Fatalf("no hello: %v %s", err, raw) |
| + } |
| + welcome, _ := wire.NewFrame("i-welcome-1", wire.FrameWelcome, wire.Welcome{Generation: 1, RunnerID: "R1", Protocol: wire.Protocol2, Role: wire.RoleWorker}) |
| + raw, _ = json.Marshal(welcome) |
| + write(t, ws, raw) |
| + // Answer the runner's goodbye at once. |
| + ws.CloseRead(context.Background()) |
| + for deadline := time.Now().Add(10 * time.Second); !strings.Contains(logs.String(), "msg=welcome") || !strings.Contains(logs.String(), `msg="probes finished"`); { |
| + if time.Now().After(deadline) { |
| + t.Fatalf("no welcome or probes line:\n%s", logs) |
| + } |
| + time.Sleep(20 * time.Millisecond) |
| + } |
| + cancel() |
| + if err := <-done; err != nil { |
| + t.Fatalf("worker ended: %v", err) |
| + } |
| + out := logs.String() |
| + t.Logf("a Mac worker's start:\n%s", out) |
| + |
| + host := l.Addr().String() |
| + order := []string{ |
| + `level=INFO msg="startup phase" phase=mac_host`, |
| + `level=INFO msg=command cmd=/usr/bin/xcode-select args=-p took=`, |
| + `level=INFO msg="startup phase done" phase=mac_host took=`, |
| + `level=INFO msg="startup phase" phase=state_lock`, |
| + `level=INFO msg="startup phase done" phase=state_lock took=`, |
| + `level=INFO msg="startup phase" phase=claim_roots`, |
| + `level=INFO msg="startup phase done" phase=claim_roots took=`, |
| + `level=INFO msg="startup phase" phase=sweep`, |
| + `level=INFO msg="startup phase done" phase=sweep took=`, |
| + `level=INFO msg="startup phase" phase=credentials`, |
| + `level=INFO msg="startup phase done" phase=credentials took=`, |
| + `level=INFO msg="startup phase" phase=open_state`, |
| + `level=INFO msg="startup phase done" phase=open_state took=`, |
| + `level=INFO msg=connecting host=` + host + ` protocol=` + itoa(int64(wire.ProtocolCurrent)), |
| + `level=WARN msg="runner stream" err=`, |
| + `level=INFO msg=connecting host=` + host, |
| + `level=INFO msg=connected host=` + host + ` took=`, |
| + `level=INFO msg="capabilities gathering"`, |
| + `level=INFO msg=command cmd=/usr/bin/xcodebuild args=-version took=`, |
| + `level=INFO msg=command cmd=` + env["EQUIPO_NODE_PATH"] + ` args=--version took=`, |
| + `level=INFO msg=command cmd=` + env["EQUIPO_CLAUDE_PATH"] + ` args=--version took=`, |
| + `level=INFO msg="capabilities gathered" took=`, |
| + `level=INFO msg="hello sent" protocol=`, |
| + `level=INFO msg=welcome protocol=2 role=worker generation=1`, |
| + } |
| + if n := strings.Count(out, `level=INFO msg="probes started"`); n != 1 { |
| + t.Fatalf("probes started at info %d times: a run asked for again, verdicts the same, is debug:\n%s", n, out) |
| + } |
| + lines, at := strings.Split(out, "\n"), 0 |
| + for _, want := range order { |
| + for at < len(lines) && !strings.Contains(lines[at], want) { |
| + at++ |
| + } |
| + if at == len(lines) { |
| + t.Fatalf("missing or out of order: %s\n%s", want, out) |
| + } |
| + at++ |
| + } |
| + // The dial failure: the error and the wait before the next try. |
| + if !strings.Contains(out, "503") || !strings.Contains(out, "retry_in=") { |
| + t.Fatalf("the dial failure says neither why nor when:\n%s", out) |
| + } |
| + // A failed command says how; the probes say names and verdicts only. |
| + if !strings.Contains(out, `cmd=/usr/bin/xcodebuild args=-version`) || !strings.Contains(out, `msg="probes started"`) || !strings.Contains(out, `verdicts="P1=passed P2=denied`) { |
| + t.Fatalf("command or probes lines:\n%s", out) |
| + } |
| + if strings.Contains(out, bearer) { |
| + t.Fatalf("a line holds the bearer:\n%s", out) |
| + } |
| +} |
| + |
| +// A command still running after slowCommand is logged while it runs, |
| +// with its arguments (a password's value withheld), and again when it |
| +// ends with how long it took. |
| +func TestMacSlowCommandLogged(t *testing.T) { |
| + was := slowCommand |
| + slowCommand = 50 * time.Millisecond |
| + defer func() { slowCommand = was }() |
| + logs := &syncBuffer{} |
| + h := &macHost{log: slog.New(slog.NewTextHandler(logs, nil))} |
| + if _, err := h.run(context.Background(), "/bin/sh", "-c", "sleep 0.3", "sh", "-w", "hunter2"); err != nil { |
| + t.Fatal(err) |
| + } |
| + out := logs.String() |
| + still, finished := strings.Index(out, `level=WARN msg="command still running" cmd=/bin/sh`), strings.Index(out, `level=WARN msg="slow command finished" cmd=/bin/sh`) |
| + if still < 0 || finished < still || !strings.Contains(out, `args="-c sleep 0.3 sh -w [withheld]"`) || strings.Contains(out, "hunter2") { |
| + t.Fatalf("slow command lines:\n%s", out) |
| + } |
| + // A quick command says nothing. |
| + quiet := &syncBuffer{} |
| + h.log = slog.New(slog.NewTextHandler(quiet, nil)) |
| + if _, err := h.run(context.Background(), "/bin/sh", "-c", "true"); err != nil || quiet.String() != "" { |
| + t.Fatalf("a quick command logged: %v %q", err, quiet.String()) |
| + } |
| +} |
diff --git a/internal/runner/thin/voice_test.go b/internal/runner/thin/voice_test.go| index cae23c40..207c4c78 100644 |
| --- a/internal/runner/thin/voice_test.go |
| +++ b/internal/runner/thin/voice_test.go |
| @@ -80,3 +80,20 @@ func TestOpeningReusesOpenTasks(t *testing.T) { |
| t.Fatalf("add_report is not offered: %v", tools) |
| } |
| } |
| + |
| +// What the person may need to paste comes in its own fenced block, which |
| +// the chat shows as a paste box with Copy (Paul, 2026-11-11). The line is |
| +// static, in the opening, so the cached prefix stays the same between |
| +// turns. |
| +func TestOpeningPutsPastesInFences(t *testing.T) { |
| + o := opening("p@example.com", nil) |
| + if !strings.Contains(o, "Anything the person may need to paste (commands, prompts, config, codes) goes in a fenced code block, one block per thing to paste") { |
| + t.Fatal("the opening lacks the paste rule") |
| + } |
| + if o != opening("p@example.com", nil) { |
| + t.Fatal("the opening is not static") |
| + } |
| + if houseRule == "2026-11-07.9" { |
| + t.Fatal("the rule changed: its version must move so sessions read it") |
| + } |
| +} |
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/scripts/runner-reference-allowlist.json b/scripts/runner-reference-allowlist.json| index 08a1c17e..0e5c9420 100644 |
| --- a/scripts/runner-reference-allowlist.json |
| +++ b/scripts/runner-reference-allowlist.json |
| @@ -10354,7 +10354,7 @@ |
| }, |
| { |
| "path": "internal/runner/thin/mac.go", |
| - "line_sha256": "cf8018bd71b2fac45dcea98e9f738fc5b20ae35a34133b27198635cd160a72c4", |
| + "line_sha256": "b26743611f2f5ce41538d4cd3dd9cc0215ce18b9410a5307b973ba30ab7b8bf4", |
| "match": "equipo-runner", |
| "count": 1, |
| "reason": "Mac runner (darwin worker): the runner executable, its launchd agent, install paths, the pinned srt package and Node it needs, and their tests and docs." |
| @@ -11037,5 +11037,54 @@ |
| "match": "Node", |
| "count": 1, |
| "reason": "Markdown syntax tree node traversal in the Go renderer; no external runtime." |
| + }, |
| + { |
| + "path": "internal/runner/thin/startup_logs_test.go", |
| + "line_sha256": "704a7f04f7c0889ea6ddcc56fbf48a12285d55adfbd56278f506e3d8c5373685", |
| + "match": "equipo-runner", |
| + "count": 1, |
| + "reason": "Mac runner (darwin worker): the runner executable, its launchd agent, install paths, the pinned srt package and Node it needs, and their tests and docs." |
| + }, |
| + { |
| + "path": "internal/runner/thin/startup_logs_test.go", |
| + "line_sha256": "eefda536b0faad0515e585db2b6dfd12f883f294e75ac964bf608e0de760bc23", |
| + "match": "node", |
| + "count": 1, |
| + "reason": "Mac runner (darwin worker): the runner executable, its launchd agent, install paths, the pinned srt package and Node it needs, and their tests and docs." |
| + }, |
| + { |
| + "path": "internal/runner/thin/startup_logs_test.go", |
| + "line_sha256": "f2c292ad45f220fb68204b44ed49c974f19dca0ccc9f770eab347ac717833eb1", |
| + "match": "NODE", |
| + "count": 1, |
| + "reason": "Mac runner (darwin worker): the runner executable, its launchd agent, install paths, the pinned srt package and Node it needs, and their tests and docs." |
| + }, |
| + { |
| + "path": "internal/runner/thin/mac.go", |
| + "line_sha256": "aeb7fbbdabfa876ff3091fb2e4961286eb2c2913fdc59d680bcf81d52e8a17d5", |
| + "match": "Node", |
| + "count": 1, |
| + "reason": "Mac runner (darwin worker): the runner executable, its launchd agent, install paths, the pinned srt package and Node it needs, and their tests and docs." |
| + }, |
| + { |
| + "path": "internal/runner/thin/mac.go", |
| + "line_sha256": "aeb7fbbdabfa876ff3091fb2e4961286eb2c2913fdc59d680bcf81d52e8a17d5", |
| + "match": "node", |
| + "count": 1, |
| + "reason": "Mac runner (darwin worker): the runner executable, its launchd agent, install paths, the pinned srt package and Node it needs, and their tests and docs." |
| + }, |
| + { |
| + "path": "internal/runner/thin/probe_storm_test.go", |
| + "line_sha256": "e9d2fc83d5d2c09493fac24dd1085f051109661785e322c7bd78d24fbedb8a8f", |
| + "match": "equipo-runner", |
| + "count": 1, |
| + "reason": "Mac runner (darwin worker): the runner executable, its launchd agent, install paths, the pinned srt package and Node it needs, and their tests and docs." |
| + }, |
| + { |
| + "path": "internal/chatmarkdown/draft.go", |
| + "line_sha256": "22a4908753eba625925bc6d73b9f556d68708af8710c79108490564280f1233b", |
| + "match": "Node", |
| + "count": 1, |
| + "reason": "goldmark's ast.Node in the watched fence parser's Continue signature; Markdown syntax tree, no external runtime." |
| } |
| ] |