oficina / equipo Public

Merge main into thinking-stale

Brings in mac-recheck and stream-markdown (e0595b5) before CI.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 37f0bed08ff56e9e768262336bbbc6edba9c0d62 parent cf32916parent e0595b5
26 files changed, +1,143 −47
  • .rastrillo/budgets.txt +2 −2
  • docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md +9 −1
  • internal/chatmarkdown/draft.go +174 −0
  • internal/chatmarkdown/draft_test.go +115 −0
  • internal/chatmarkdown/markdown.go +19 −5
  • internal/equipo/app.go +1 −0
  • internal/equipo/chat/macrecheck.go +90 −0
  • internal/equipo/chat/review.go +4 −0
  • internal/equipo/chat/runner.go +8 −2
  • internal/equipo/chat/runners.go +7 −1
  • internal/equipo/chat/tasks.go +3 −0
  • internal/equipo/chat_draft.go +35 −0
  • internal/equipo/copy.go +1 −1
  • internal/equipo/migrations/0060_thin_mac_recheck.sql +1 −0
  • internal/equipo/migrations/schema.sql +1 −1
  • internal/equipo/render.go +1 −1
  • internal/equipo/static/chat-stream.js +153 −28
  • internal/equipo/templates/conversation_card.html +1 −1
  • internal/fakeclaude/fake.go +6 −2
  • internal/fakeclaude/markdown.go +44 −0
  • internal/headless/browser_stream_markdown_test.go +117 −0
  • internal/headless/browser_test.go +1 −1
  • internal/plan3test/conversation_draft_test.go +52 −0
  • internal/thintest/macrecheck_contract_test.go +262 −0
  • internal/thintest/projects_pages_test.go +1 −1
  • scripts/runner-reference-allowlist.json +35 −0
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index e283c55d..01305a54 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -49,7 +49,7 @@ perf GET /api/v1/notebook skip Thin v1 person API: bearer-only JSON for devices;
perf GET /api/v1/thinking skip Thin v1 person API: bearer-only JSON for devices; the browser reads thinking words on /settings/thinking.
perf GET /api/v1/tasks skip Thin v1 person API: bearer-only JSON for devices; the browser reads tasks through /tasks.
perf GET /api/v1/tasks/{id} skip Thin v1 person API: bearer-only JSON for devices; the browser reads a task through /tasks/{id}.
-size internal/equipo/chat 12450 - 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 12550 - 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.
@@ -62,4 +62,4 @@ perf GET /conversation/attachments/{id}/preview skip Composer attachments: an im
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 - 8300 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 - 11400 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/thintest - 11600 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.
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
index 99451fde..11f0396b 100644
--- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
+++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
@@ -5947,7 +5947,7 @@ records remain unchanged.
| `work.chip.waiting_mac` | Waiting for a Mac to run checks | Tasks and Needs you (projects-ux) | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-11) |
| `work.summary.waiting_mac` | Approved. Waiting for a Mac to run checks. You can merge now without checks. | Tasks and Needs you (projects-ux) | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-11) |
| `work.decide.mac_why` | Review approved. Checks need a Mac, and no Mac is set up to run them. | Tasks and Needs you (projects-ux) | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-11) |
-| `work.decide.mac_hint` | Merge now merges it without checks. Wait for a Mac leaves it as it is. Once a Mac is set up, checks run on its next change, and if they pass, Equipo merges it by itself. | Tasks and Needs you (projects-ux) | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-11) |
+| `work.decide.mac_hint` | Merge now merges it without checks. Wait for a Mac keeps it ready. Once a Mac is set up, checks run, and if they pass, Equipo merges it by itself. | Tasks and Needs you (projects-ux) | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-11) |
| `work.decide.mac.merge` | Merge now | Tasks and Needs you (projects-ux) | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-11) |
| `work.decide.mac.wait` | Wait for a Mac | Tasks and Needs you (projects-ux) | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-11) |
| `work.decide.mac_set_up` | Set up a Mac | Tasks and Needs you (projects-ux) | COPY ACCEPTED BY DELEGATION (Astra, 2026-11-11) |
@@ -6711,3 +6711,11 @@ coordinator's ruling (2026-11-11), still accepted by delegation:
Spend 1's eight strings (`work.spend*`, with `work.spend_left_out`) had
their own small Astra pass on 2026-11-11 with the same brief: all eight
kept, no flags; marked accepted by delegation.
+
+Mac recheck (2026-11-11) closes the `work.decide.mac_hint` gap above: a
+Mac that fits, enrolling or back online, runs a waiting task's
+`needs_macos` checks again on its candidate (`chat/macrecheck.go`), and a
+pass merges under slice 4c. The hint is a plain line again: "Merge now
+merges it without checks. Wait for a Mac keeps it ready. Once a Mac is set
+up, checks run, and if they pass, Equipo merges it by itself." Accepted by
+delegation like its neighbours.
diff --git a/internal/chatmarkdown/draft.go b/internal/chatmarkdown/draft.go
new file mode 100644
index 00000000..b438a20b
--- /dev/null
+++ b/internal/chatmarkdown/draft.go
@@ -0,0 +1,174 @@
+package chatmarkdown
+
+import (
+ "bytes"
+ "regexp"
+ "sort"
+ "strings"
+
+ "github.com/yuin/goldmark/ast"
+ "github.com/yuin/goldmark/parser"
+ "github.com/yuin/goldmark/text"
+ "github.com/yuin/goldmark/util"
+)
+
+// A draft is a reply still arriving, rendered by Render's own walk over
+// the same parse. What the next characters could still change is left
+// out until they come:
+//
+// - a last line that is only a list marker, a heading's hashes, a fence
+// or a rule on its way ("-", "2.", "##", "``") waits for more of its
+// line;
+// - in the paragraph still open at the end, an emphasis opener or a
+// backtick with no closer yet is not shown, so its words are plain
+// text until it closes, and a link on its way shows only its words;
+// - an open code fence is an open code block, as goldmark parses it.
+//
+// Everything else is Render's: the same parser, the same escaping, the
+// same links.
+
+// parse is goldmark's default parser with its emphasis and code span
+// parsers watched: what each returns is noted in seen, so a draft
+// can find the openers left without a closer. Watching changes nothing
+// they parse, and Render and RenderDraft share it.
+func parse(source []byte) (ast.Node, *seen) {
+ inline := parser.DefaultInlineParsers()
+ for i, p := range inline {
+ if ip, ok := p.Value.(parser.InlineParser); ok && bytes.ContainsAny(ip.Trigger(), "*_`") {
+ inline[i] = util.Prioritized(watched{ip}, p.Priority)
+ }
+ }
+ p := parser.NewParser(parser.WithBlockParsers(parser.DefaultBlockParsers()...),
+ parser.WithInlineParsers(inline...),
+ parser.WithParagraphTransformers(parser.DefaultParagraphTransformers()...),
+ )
+ s := &seen{}
+ pc := parser.NewContext()
+ pc.Set(seenKey, s)
+ return p.Parse(text.NewReader(source), parser.WithContext(pc)), s
+}
+
+var seenKey = parser.NewContextKey()
+
+type seen struct{ found []ast.Node }
+
+type watched struct{ parser.InlineParser }
+
+func (w watched) Parse(parent ast.Node, block text.Reader, pc parser.Context) ast.Node {
+ n := w.InlineParser.Parse(parent, block, pc)
+ if s, ok := pc.Get(seenKey).(*seen); ok && n != nil {
+ s.found = append(s.found, n)
+ }
+ return n
+}
+
+// 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.
+func steady(body string) string {
+ i := strings.LastIndexByte(body, '\n') + 1
+ if markerOnly.MatchString(body[i:]) {
+ return body[:i]
+ }
+ return body
+}
+
+// openLink is a link on its way at the end of a line: its "[" (or "!["),
+// its words, and its "]" or "](" with as much of the destination as has
+// come. Brackets in a code span are not a link (no backtick inside).
+var openLink = regexp.MustCompile("(!?\\[)[^\\[\\]\n`]*(\\](?:\\([^()\\s]*)?)?$")
+
+// unclosed is what a draft leaves out of the paragraph still open at the
+// end: openers without a closer and the brackets of a link on its way.
+func unclosed(root ast.Node, source []byte, s *seen) spans {
+ from := openFrom(root, source)
+ if from < 0 {
+ return nil
+ }
+ var out spans
+ for _, n := range s.found {
+ switch v := n.(type) {
+ case *parser.Delimiter:
+ // What is left of a run that can open: "**Yes" and " *it",
+ // not "2 * 3" (which cannot open) or "it*" (which closes);
+ // and a run at the very end, which can be either once the
+ // next character comes.
+ opens := v.CanOpen && (!v.CanClose || v.OriginalLength >= 2) || v.Segment.Stop == len(source)
+ if v.Length > 0 && opens && v.Segment.Start >= from {
+ out = append(out, v.Segment)
+ }
+ case *ast.Text:
+ // The code span parser returns its backticks as text when no
+ // closing run follows.
+ if v.Segment.Start >= from {
+ out = append(out, v.Segment)
+ }
+ }
+ }
+ line := bytes.LastIndexByte(source, '\n') + 1
+ if line < from {
+ line = from
+ }
+ if m := openLink.FindSubmatchIndex(source[line:]); m != nil && (line+m[2] == 0 || source[line+m[2]-1] != '\\') {
+ out = append(out, text.NewSegment(line+m[2], line+m[3]))
+ if m[4] >= 0 {
+ out = append(out, text.NewSegment(line+m[4], line+m[5]))
+ }
+ }
+ sort.Slice(out, func(i, j int) bool { return out[i].Start < out[j].Start })
+ return out
+}
+
+// openFrom is where the paragraph (or heading) still open at the end of
+// the source starts, or -1 when the source ends in anything else or the
+// last paragraph has ended: a blank line after it, or a heading's line
+// break. Openers before it were never closed and show as the finished
+// message shows them.
+func openFrom(root ast.Node, source []byte) int {
+ n := root
+ for n.LastChild() != nil && n.LastChild().Type() == ast.TypeBlock {
+ n = n.LastChild()
+ }
+ switch n.(type) {
+ case *ast.Paragraph, *ast.TextBlock, *ast.Heading:
+ default:
+ return -1
+ }
+ lines := n.Lines()
+ if lines.Len() == 0 {
+ return -1
+ }
+ breaks := bytes.Count(source[lines.At(lines.Len()-1).Stop:], []byte("\n"))
+ if _, heading := n.(*ast.Heading); heading && breaks > 0 || breaks > 1 {
+ return -1
+ }
+ return lines.At(0).Start
+}
+
+// spans are source ranges a draft leaves out of its text, in order.
+type spans []text.Segment
+
+// value is a text segment's source without the ranges left out.
+func (h spans) value(source []byte, s text.Segment) []byte {
+ if len(h) == 0 {
+ return s.Value(source)
+ }
+ var out []byte
+ at := s.Start
+ for _, x := range h {
+ if x.Stop <= at || x.Start >= s.Stop {
+ continue
+ }
+ if x.Start > at {
+ out = append(out, source[at:x.Start]...)
+ }
+ at = x.Stop
+ }
+ if at < s.Stop {
+ out = append(out, source[at:s.Stop]...)
+ }
+ return out
+}
diff --git a/internal/chatmarkdown/draft_test.go b/internal/chatmarkdown/draft_test.go
new file mode 100644
index 00000000..82bb6496
--- /dev/null
+++ b/internal/chatmarkdown/draft_test.go
@@ -0,0 +1,115 @@
+package chatmarkdown
+
+import (
+ "html"
+ "regexp"
+ "strings"
+ "testing"
+ "unicode/utf8"
+)
+
+// corpus is coordinator replies as they are written: the recorded ones
+// (a bold opening line, a bold-led bullet list and a numbered list run
+// together while streaming) and the rest of the subset the chat renders.
+var corpus = []string{
+ // fakeclaude's markdownSample, which the browser test streams.
+ "**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.",
+ "**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:\n\n1. **Owner of the fix:** Engineering, on the checkout repository.\n2. **One complete change:** the total, the receipt and a test for both.\n3. **Review:** an independent check before it merges.\n",
+ "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.",
+ "Café con ñandú, señor. ☕ **Ünïcödé** 🎉 works.\nA soft break, then\n\n---\n\nafter a rule.",
+}
+
+// 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 {
+ text := html.UnescapeString(regexp.MustCompile(`<[^>]*>`).ReplaceAllString(h, ""))
+ return strings.TrimSpace(strings.Join(strings.Fields(text), " "))
+}
+
+// code is a code block, whose text is the reply's own characters.
+var code = regexp.MustCompile(`(?s)<pre>.*?</pre>`)
+
+// The draft of a whole reply is the reply: the end of a stream adds
+// 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 {
+ t.Errorf("draft of the whole reply differs\n draft: %q\nreply: %q", got, want)
+ }
+ }
+}
+
+// Every prefix of a reply, as it streams: no markup characters show (the
+// corpus has no literal ones), and what shows is the start of what the
+// finished reply shows.
+func TestDraftShowsNoMarkupAndOnlyTheReplysText(t *testing.T) {
+ for _, reply := range corpus {
+ final := visible(string(Render(reply)))
+ for i := 0; i <= len(reply); i++ {
+ if i < len(reply) && !utf8.RuneStart(reply[i]) {
+ continue
+ }
+ draft := string(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)
+ }
+ if !strings.HasPrefix(final, seen) {
+ t.Fatalf("draft at %d %q shows %q, not the start of %q", i, reply[:i], seen, final)
+ }
+ }
+ }
+}
+
+func TestDraftPartialSyntax(t *testing.T) {
+ for _, c := range []struct{ text, want string }{
+ // An unclosed ** or backtick is plain text until it closes.
+ {"**Yes. This is", "<p>Yes. This is</p>\n"},
+ {"**Yes. This is**", "<p><strong>Yes. This is</strong></p>\n"},
+ {"**closed** and **op", "<p><strong>closed</strong> and op</p>\n"},
+ {"*it", "<p>it</p>\n"},
+ {"Run `go te", "<p>Run go te</p>\n"},
+ {"Run `go test`", "<p>Run <code>go test</code></p>\n"},
+ {"- **Guest:** sees it\n- **Cus", "<ul><li><strong>Guest:</strong> sees it</li>\n<li>Cus</li>\n</ul>\n"},
+ // A paragraph that has ended keeps what it has: it shows as the
+ // finished reply will.
+ {"Para **open\n\nNext", "<p>Para **open</p>\n<p>Next</p>\n"},
+ // Arithmetic is not an opener.
+ {"2 * 3", "<p>2 * 3</p>\n"},
+ // A partial list marker or heading waits for more of its line.
+ {"- **Guest:** a\n-", "<ul><li><strong>Guest:</strong> a</li>\n</ul>\n"},
+ {"- **Guest:** a\n- ", "<ul><li><strong>Guest:</strong> a</li>\n</ul>\n"},
+ {"1. **Owner**\n2", "<ol><li><strong>Owner</strong></li>\n</ol>\n"},
+ {"1. **Owner**\n2.", "<ol><li><strong>Owner</strong></li>\n</ol>\n"},
+ {"Text\n\n##", "<p>Text</p>\n"},
+ {"## Pl", "<p>Pl</p>\n"},
+ {"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"},
+ {"``", ""},
+ // 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"},
+ {"See [Fix](/tasks/tk1", "<p>See Fix</p>\n"},
+ {"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 {
+ t.Errorf("RenderDraft(%q)\n got %q\nwant %q", c.text, got, c.want)
+ }
+ }
+}
+
+// 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)", `![x](https://evil.test/a)`, "<scr"} {
+ got := string(RenderDraft(raw))
+ if strings.Contains(got, "<script") || strings.Contains(got, "<img") || strings.Contains(got, "<scr") || strings.Contains(got, `href="javascript:`) {
+ t.Fatal("unsafe", got)
+ }
+ }
+}
diff --git a/internal/chatmarkdown/markdown.go b/internal/chatmarkdown/markdown.go
index 1cf76bf0..28f26f11 100644
--- a/internal/chatmarkdown/markdown.go
+++ b/internal/chatmarkdown/markdown.go
@@ -8,15 +8,29 @@ import (
"net/url"
"regexp"
- "github.com/yuin/goldmark"
"github.com/yuin/goldmark/ast"
- "github.com/yuin/goldmark/text"
"github.com/yuin/goldmark/util"
)
-func Render(body string) template.HTML {
+// Render renders a finished message.
+func Render(body string) template.HTML { return render(body, false) }
+
+// 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 render(body string, draft bool) template.HTML {
+ var hide spans
+ if draft {
+ body = steady(body)
+ }
source := []byte(body)
- root := goldmark.DefaultParser().Parse(text.NewReader(source))
+ root, seen := parse(source)
+ if draft {
+ hide = unclosed(root, source, seen)
+ }
var out bytes.Buffer
escape := func(b []byte) { out.WriteString(html.EscapeString(string(b))) }
var node func(ast.Node)
@@ -35,7 +49,7 @@ func Render(body string) template.HTML {
case *ast.TextBlock:
children(n)
case *ast.Text:
- escape(util.ResolveEntityNames(util.ResolveNumericReferences(util.UnescapePunctuations(v.Segment.Value(source)))))
+ escape(util.ResolveEntityNames(util.ResolveNumericReferences(util.UnescapePunctuations(hide.value(source, v.Segment)))))
if v.HardLineBreak() {
out.WriteString("<br>\n")
} else if v.SoftLineBreak() {
diff --git a/internal/equipo/app.go b/internal/equipo/app.go
index 5cbdba01..6834ac84 100644
--- a/internal/equipo/app.go
+++ b/internal/equipo/app.go
@@ -244,6 +244,7 @@ func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logg
r.Get("/conversation", a.chatPage)
r.Post("/conversation", a.chatSend)
r.Post("/conversation/attachments", a.chatUpload)
+ r.Post("/conversation/draft", a.chatDraft)
r.Get("/conversation/attachments/{id}", a.chatAttachment(false))
r.Get("/conversation/attachments/{id}/preview", a.chatAttachment(true))
r.Post("/conversation/cards/{id}/answer", a.chatCardAnswer)
diff --git a/internal/equipo/chat/macrecheck.go b/internal/equipo/chat/macrecheck.go
new file mode 100644
index 00000000..0d8e9ad6
--- /dev/null
+++ b/internal/equipo/chat/macrecheck.go
@@ -0,0 +1,90 @@
+package chat
+
+import (
+ "slices"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// recheckMac runs again the checks of the person's tasks that wait for a
+// Mac, when runner (just enrolled, or back online) fits them: Ready to
+// merge, approved, their newest checks not run because no runner could
+// (needs_macos), the branch still at that candidate and no merge of it.
+// The checks are placed afresh on that exact candidate through the usual
+// placement (nextStep), so a pass merges under the slice 4c policy
+// (advance grants it) and a failure takes the fix round. Once per
+// candidate per runner: a reconnect of the same runner runs nothing.
+func (t *txn) recheckMac(person, runner string) error {
+ rs, err := t.runners(person)
+ if err != nil {
+ return err
+ }
+ primary, err := t.s.authority.PrimaryRunner(t.db, person)
+ if err != nil {
+ return err
+ }
+ var mac *runnerInfo
+ relay := false
+ for i := range rs {
+ if rs[i].ID == runner && rs[i].Online && slices.Contains(rs[i].tags(), wire.TagMacOS) {
+ mac = &rs[i]
+ }
+ if rs[i].ID == primary && rs[i].Protocol >= wire.Protocol2 {
+ relay = true
+ }
+ }
+ if mac == nil || !relay && runner != primary {
+ // Not a Mac, or placement would end on the primary again.
+ return nil
+ }
+ var tasks []taskRecord
+ if err := t.db.Where("creator = ? AND stage = ? AND cancel_requested = ?", person, wire.StageReadyToMerge, false).Order("created_at, id").Find(&tasks).Error; err != nil {
+ return err
+ }
+ for i := range tasks {
+ k := &tasks[i]
+ steps, err := t.steps(k.ID)
+ if err != nil {
+ return err
+ }
+ p := progressFor(*k, steps)
+ c := p.checks
+ if p.moved || p.merge != nil || p.eng == nil || p.eng.Person != person || c == nil || c.State != wire.StepDone || c.Checks != wire.ChecksCannotRun || c.Reason != "needs_macos" {
+ continue
+ }
+ if _, _, verdict, _ := p.judged(); verdict != wire.VerdictApprove {
+ continue
+ }
+ needs := decodeList(c.Needs)
+ if len(needs) == 0 {
+ if needs, err = t.checksNeeds(*k, *c); err != nil {
+ return err
+ }
+ }
+ if !slices.Contains(needs, wire.TagMacOS) || !mac.fits(needs, decodeList(c.RefusedBy)) {
+ continue
+ }
+ var ran int64
+ if err := t.db.Model(&stepRecord{}).Where("task_id = ? AND specialist = ? AND candidate_sha = ? AND recheck_by = ?", k.ID, wire.SpecialistChecks, p.candidate, runner).Count(&ran).Error; err != nil {
+ return err
+ }
+ if ran > 0 {
+ continue
+ }
+ // The card asked whether to merge without checks; they run now,
+ // and their outcome asks afresh if it must.
+ if err := t.withdrawMergeCards(*k); err != nil {
+ return err
+ }
+ k.MergeAsked = ""
+ if err := t.db.Model(&taskRecord{}).Where("id = ?", k.ID).Update("merge_asked", "").Error; err != nil {
+ return err
+ }
+ s := stepRecord{Specialist: wire.SpecialistChecks, Person: p.eng.Person, Round: p.eng.Round, BaseSHA: k.BaseSHA, CandidateSHA: p.candidate, RecheckBy: runner}
+ k.Stage = wire.StageInReview
+ if err := t.nextStep(k, steps, s); err != nil {
+ return err
+ }
+ }
+ return nil
+}
diff --git a/internal/equipo/chat/review.go b/internal/equipo/chat/review.go
index 319461b2..c019a211 100644
--- a/internal/equipo/chat/review.go
+++ b/internal/equipo/chat/review.go
@@ -192,6 +192,10 @@ func (t *txn) advance(k *taskRecord) error {
if checks == wire.ChecksPassed {
k.MergeEligible = p.candidate
}
+ } else if checks == wire.ChecksPassed && p.checks.RecheckBy != "" && k.MergeEligible != p.candidate {
+ // Its checks waited for a Mac and passed there (macrecheck.go):
+ // what passing at the first Ready would have granted.
+ k.MergeEligible, ready = p.candidate, true
}
if ready {
if err := t.saveTask(k); err != nil {
diff --git a/internal/equipo/chat/runner.go b/internal/equipo/chat/runner.go
index 3114e7db..3646113e 100644
--- a/internal/equipo/chat/runner.go
+++ b/internal/equipo/chat/runner.go
@@ -95,7 +95,10 @@ func (s *Store) Connect(ctx context.Context, p RunnerPrincipal, process string,
return err
}
// A runner that fits may have come online.
- return t.placeWaiting(p.Person)
+ if err := t.placeWaiting(p.Person); err != nil {
+ return err
+ }
+ return t.recheckMac(p.Person, p.RunnerID)
})
return lease, err
}
@@ -174,7 +177,10 @@ func (s *Store) Heartbeat(ctx context.Context, l Lease, hello wire.Hello) error
if err := t.runnerEvent(l.Runner.Person, r); err != nil {
return err
}
- return t.placeWaiting(l.Runner.Person)
+ if err := t.placeWaiting(l.Runner.Person); err != nil {
+ return err
+ }
+ return t.recheckMac(l.Runner.Person, l.Runner.RunnerID)
}
return nil
})
diff --git a/internal/equipo/chat/runners.go b/internal/equipo/chat/runners.go
index 3922070c..93b31696 100644
--- a/internal/equipo/chat/runners.go
+++ b/internal/equipo/chat/runners.go
@@ -248,6 +248,12 @@ func (r runnerInfo) tags() []string {
return r.Hello.Capabilities.Tags
}
+// fits reports whether checks with needs, refused by those runners, may
+// be placed on r.
+func (r runnerInfo) fits(needs, refused []string) bool {
+ return wire.Covers(r.tags(), needs) && !slices.Contains(refused, r.ID) && r.Protocol >= wire.Protocol2 && !r.Removing
+}
+
// runners are the person's unrevoked runners in enrolment order, with
// what each last said and how many steps it runs.
func (t *txn) runners(person string) ([]runnerInfo, error) {
@@ -464,7 +470,7 @@ func (t *txn) place(k *taskRecord, s *stepRecord) (placed bool, err error) {
if r.ID == primary && r.Protocol >= wire.Protocol2 {
relay = true
}
- if wire.Covers(r.tags(), needs) && !slices.Contains(refused, r.ID) && r.Protocol >= wire.Protocol2 && !r.Removing {
+ if r.fits(needs, refused) {
fit = append(fit, r)
}
}
diff --git a/internal/equipo/chat/tasks.go b/internal/equipo/chat/tasks.go
index d2d92d76..d33ebc7d 100644
--- a/internal/equipo/chat/tasks.go
+++ b/internal/equipo/chat/tasks.go
@@ -166,6 +166,9 @@ type stepRecord struct {
// none when they ran outside the sandbox (Paul's ruling 2). "" is the
// primary's bubblewrap.
ChecksSandbox string
+ // RecheckBy is the runner whose arrival ran these checks again, after
+ // they waited for a Mac (macrecheck.go). Set only at creation.
+ RecheckBy string
}
func (stepRecord) TableName() string { return "chat_steps" }
diff --git a/internal/equipo/chat_draft.go b/internal/equipo/chat_draft.go
new file mode 100644
index 00000000..464cc04a
--- /dev/null
+++ b/internal/equipo/chat_draft.go
@@ -0,0 +1,35 @@
+package equipo
+
+import (
+ "io"
+ "net/http"
+
+ "amadan.net/oficina/equipo/internal/chatmarkdown"
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// chatDraft renders a reply that is still streaming, as far as it has
+// come, with the renderer the finished message uses (chatmarkdown), so
+// the end of a stream changes nothing but the last characters. The page
+// (chat-stream.js) posts the text it has gathered from the deltas; it is
+// rendered and sent back, from this origin only, and nothing is kept.
+func (a *application) chatDraft(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Cache-Control", "no-store")
+ if _, _, ok := sessionContext(r); !ok || r.Header.Get("Sec-Fetch-Site") != "same-origin" {
+ a.failure(w, r, ErrForbidden)
+ return
+ }
+ // A reply is kept to 4*MaxMessageBytes (chat.reply); the form
+ // encoding may triple it.
+ r.Body = http.MaxBytesReader(w, r.Body, 12*wire.MaxMessageBytes+64)
+ if err := r.ParseForm(); err != nil {
+ a.failure(w, r, ErrInvalid)
+ return
+ }
+ text := r.PostForm.Get("text")
+ if len(text) > 4*wire.MaxMessageBytes {
+ text = text[:4*wire.MaxMessageBytes]
+ }
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ _, _ = io.WriteString(w, string(chatmarkdown.RenderDraft(text)))
+}
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go
index 140ca98b..97889891 100644
--- a/internal/equipo/copy.go
+++ b/internal/equipo/copy.go
@@ -1138,7 +1138,7 @@ var pageCopy = map[string]string{
"work.chip.waiting_mac": "Waiting for a Mac to run checks", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-11)
"work.summary.waiting_mac": "Approved. Waiting for a Mac to run checks. You can merge now without checks.", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-11)
"work.decide.mac_why": "Review approved. Checks need a Mac, and no Mac is set up to run them.", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-11)
- "work.decide.mac_hint": "Merge now merges it without checks. Wait for a Mac leaves it as it is. Once a Mac is set up, checks run on its next change, and if they pass, Equipo merges it by itself.", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-11)
+ "work.decide.mac_hint": "Merge now merges it without checks. Wait for a Mac keeps it ready. Once a Mac is set up, checks run, and if they pass, Equipo merges it by itself.", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-11)
"work.decide.mac.merge": "Merge now", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-11)
"work.decide.mac.wait": "Wait for a Mac", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-11)
"work.decide.mac_set_up": "Set up a Mac", // COPY ACCEPTED BY DELEGATION (Astra, 2026-11-11)
diff --git a/internal/equipo/migrations/0060_thin_mac_recheck.sql b/internal/equipo/migrations/0060_thin_mac_recheck.sql
new file mode 100644
index 00000000..1cdbed2a
--- /dev/null
+++ b/internal/equipo/migrations/0060_thin_mac_recheck.sql
@@ -0,0 +1 @@
+ALTER TABLE chat_steps ADD COLUMN recheck_by text;
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql
index 0a02895c..4902d47a 100644
--- a/internal/equipo/migrations/schema.sql
+++ b/internal/equipo/migrations/schema.sql
@@ -598,7 +598,7 @@ CREATE INDEX chat_card_task ON chat_cards(task_id);
CREATE TABLE chat_project_attachments (project_id text, kind text, ref text, name text, created_at datetime, PRIMARY KEY (project_id, kind, ref));
CREATE TABLE chat_tasks (id text PRIMARY KEY, project_id text, title text, brief text, stage text, branch text, base_sha text, creator text, turn_id text, cancel_requested numeric, revision integer, created_at datetime, updated_at datetime, watching text, moved_from text, branch_head text, merge_asked text, merged_sha text, merged_into text, merge_strategy text, merged_without_checks numeric, merged_at datetime, ready_sha text, merge_eligible text, done_at datetime, duplicate_of text, folded_into text, folded_stage text, folded_at datetime, engineering_runner text);
CREATE INDEX chat_task_project ON chat_tasks(project_id);
-CREATE TABLE chat_steps (id text PRIMARY KEY, task_id text, idx integer, specialist text, person text, state text, reason text, attempt integer, base_sha text, candidate_sha text, pushed numeric, terminated numeric, summary text, log_tail text, started_at datetime, finished_at datetime, revision integer, created_at datetime, updated_at datetime, round integer, family text, account text, verdict text, review_label text, findings text, checks text, gate text, exit_code integer, output text, republish numeric, from_attempt integer, askable numeric, rebase numeric, from_base text, from_candidate text, merge_sha text, merge_into text, merge_strategy text, without_checks numeric, activity text, switched text, headline text, runner_id text, needs text, placement text, waiting_since datetime, refused_by text, withdrawn numeric, termination_kind text, publication text, publication_id text, apple numeric, checks_sandbox text);
+CREATE TABLE chat_steps (id text PRIMARY KEY, task_id text, idx integer, specialist text, person text, state text, reason text, attempt integer, base_sha text, candidate_sha text, pushed numeric, terminated numeric, summary text, log_tail text, started_at datetime, finished_at datetime, revision integer, created_at datetime, updated_at datetime, round integer, family text, account text, verdict text, review_label text, findings text, checks text, gate text, exit_code integer, output text, republish numeric, from_attempt integer, askable numeric, rebase numeric, from_base text, from_candidate text, merge_sha text, merge_into text, merge_strategy text, without_checks numeric, activity text, switched text, headline text, runner_id text, needs text, placement text, waiting_since datetime, refused_by text, withdrawn numeric, termination_kind text, publication text, publication_id text, apple numeric, checks_sandbox text, recheck_by text);
CREATE INDEX chat_step_task ON chat_steps(task_id);
CREATE TABLE chat_task_entries (id text PRIMARY KEY, task_id text, idempotency_key text, kind text, author text, text text, repo text, path text, line integer, created_at datetime, headline text, folded_from text);
CREATE INDEX chat_entry_task ON chat_task_entries(task_id);
diff --git a/internal/equipo/render.go b/internal/equipo/render.go
index 4311f51e..b7ff532e 100644
--- a/internal/equipo/render.go
+++ b/internal/equipo/render.go
@@ -37,7 +37,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, "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": 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"} },
"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 dd24d6a4..54e90087 100644
--- a/internal/equipo/static/chat-stream.js
+++ b/internal/equipo/static/chat-stream.js
@@ -267,39 +267,157 @@
var line = li.querySelector("[equipo-activity-line]");
if (line) line.toggleAttribute("data-leaving", gone);
}
- // The streaming draft, drawn as the committed message will be: one
- // paragraph per blank-line break, new text fading in, nothing redrawn.
+ // ── The streaming draft ────────────────────────────────────────────
+ // The draft is drawn by the renderer the committed reply uses: the
+ // server's (POST /conversation/draft, chatmarkdown.RenderDraft), so a
+ // list is a list as it streams and the end of the stream changes
+ // nothing but the last words. One request at a time per draft, always
+ // with the whole text so far; its answer is drawn at the next frame.
function drawDraft(li, text) {
var body = li.querySelector("[data-stream-text]");
if (!body) return;
- var paras = text.split(/\n\s*\n/).filter(function (p) { return /\S/.test(p); });
- var ps = body.querySelectorAll(":scope > p");
- paras.forEach(function (para, i) {
- var p = ps[i];
- if (!p) {
- p = document.createElement("p");
- p.drawn = "";
- body.append(p);
+ var d = body.draft || (body.draft = { want: "", asked: null, html: null, frame: 0, busy: false });
+ d.want = text;
+ ask(body, d);
+ }
+ function ask(body, d) {
+ if (d.busy || d.want === d.asked || body.draft !== d || !body.isConnected) return;
+ d.asked = d.want;
+ d.busy = true;
+ fetch("/conversation/draft", { method: "POST", credentials: "same-origin", headers: { "Accept": "text/html" }, body: new URLSearchParams({ text: d.asked }) })
+ .then(function (r) { if (!r.ok) throw new Error("draft"); return r.text(); })
+ .then(function (html) {
+ d.busy = false;
+ d.html = html;
+ if (!d.frame) d.frame = requestAnimationFrame(function () { d.frame = 0; paint(body, d); });
+ ask(body, d);
+ }, function () {
+ // The next words ask again, or a second from now; the committed
+ // reply replaces the draft either way.
+ d.busy = false;
+ d.asked = null;
+ setTimeout(function () { ask(body, d); }, 1000);
+ });
+ }
+ // paint draws the latest render over what is on screen, keeping it:
+ // a block that is the same stays as it is, text that grew gets its new
+ // part as a [data-new] span (the words fade in, gently under reduced
+ // motion), and only what changed is replaced. Timed as "equipo-draft".
+ function paint(body, d) {
+ if (body.draft !== d || !body.hasAttribute("data-stream-text") || d.html === null) return;
+ var started = performance.now();
+ var next = document.createElement("template");
+ next.innerHTML = d.html;
+ var caret = body.querySelector("[equipo-stream-caret]");
+ if (caret) caret.remove();
+ patch(body, next.content);
+ if (LOOK.handoff !== "gone") {
+ // The caret or dot ends the last line of text.
+ var end = body;
+ while (end.lastElementChild && /^(P|UL|OL|LI|PRE|CODE|BLOCKQUOTE)$/.test(end.lastElementChild.tagName)) end = end.lastElementChild;
+ if (end !== body) {
+ if (!caret) {
+ caret = document.createElement("span");
+ caret.setAttribute("equipo-stream-caret", LOOK.handoff);
+ caret.setAttribute("aria-hidden", "true");
+ }
+ end.append(caret);
}
- if (para.indexOf(p.drawn) !== 0) {
- p.textContent = para;
- } else if (para.length > p.drawn.length) {
- var add = document.createElement("span");
- add.setAttribute("data-new", "");
- add.textContent = para.slice(p.drawn.length);
- p.append(add);
+ }
+ try { performance.measure("equipo-draft", { start: started }); } catch (_) { /* older browsers */ }
+ scroll();
+ }
+ // Text on screen: plain text and the spans that faded in.
+ function textish(n) { return n instanceof Text || n.tagName === "SPAN" && n.hasAttribute("data-new"); }
+ function fresh(s) {
+ if (!/\S/.test(s)) return new Text(s);
+ var span = document.createElement("span");
+ span.setAttribute("data-new", "");
+ span.textContent = s;
+ return span;
+ }
+ function same(a, b) {
+ if (a.tagName !== b.tagName || a.attributes.length !== b.attributes.length) return false;
+ for (var i = 0; i < b.attributes.length; i++) if (a.getAttribute(b.attributes[i].name) !== b.attributes[i].value) return false;
+ return true;
+ }
+ // common is how much two texts share from the start, never splitting a
+ // surrogate pair.
+ function common(a, b) {
+ var k = 0, n = Math.min(a.length, b.length);
+ while (k < n && a.charCodeAt(k) === b.charCodeAt(k)) k++;
+ if (k > 0 && k < b.length && b.charCodeAt(k - 1) >= 0xD800 && b.charCodeAt(k - 1) < 0xDC00) k--;
+ return k;
+ }
+ // copy brings a piece of the render onto the page; the first seen.n
+ // characters of its text were on screen already and stay still.
+ function copy(w, seen) {
+ if (w instanceof Text) {
+ var out = document.createDocumentFragment(), n = Math.min(seen.n, w.data.length);
+ if (n) out.append(new Text(w.data.slice(0, n)));
+ if (n < w.data.length) out.append(fresh(w.data.slice(n)));
+ seen.n -= n;
+ return out;
+ }
+ var el = document.createElement(w.tagName);
+ for (var i = 0; i < w.attributes.length; i++) el.setAttribute(w.attributes[i].name, w.attributes[i].value);
+ for (var c = w.firstChild; c; c = c.nextSibling) el.append(copy(c, seen));
+ return el;
+ }
+ // patch makes el's children the render's (next), keeping what is on
+ // screen: el's children are walked once, in step with the render's.
+ function patch(el, next) {
+ var at = el.firstChild;
+ // run takes the text on screen from at: its pieces and its words.
+ function run() {
+ var r = { parts: [], text: "" };
+ while (at && textish(at)) {
+ r.parts.push(at);
+ r.text += at.textContent;
+ at = at.nextSibling;
}
- p.drawn = para;
- });
- for (var i = paras.length; i < ps.length; i++) ps[i].remove();
- var caret = body.querySelector("[equipo-stream-caret]");
- if (LOOK.handoff !== "gone" && body.lastElementChild) {
- if (!caret) {
- caret = document.createElement("span");
- caret.setAttribute("equipo-stream-caret", LOOK.handoff);
- caret.setAttribute("aria-hidden", "true");
+ return r;
+ }
+ // left puts back, still, what of a run the render did not take, for
+ // the next piece to take (a link that has just completed, say).
+ function left(r, k) {
+ r.parts.forEach(function (p) { p.remove(); });
+ if (k < r.text.length) {
+ var rest = new Text(r.text.slice(k));
+ el.insertBefore(rest, at);
+ at = rest;
+ }
+ }
+ for (var w = next.firstChild; w; w = w.nextSibling) {
+ if (w instanceof Text) {
+ var r = run(), k = common(r.text, w.data);
+ if (k === r.text.length) {
+ if (k < w.data.length) el.insertBefore(fresh(w.data.slice(k)), at);
+ continue;
+ }
+ // What was drawn changed: what they share stays still.
+ left(r, k);
+ if (k) el.insertBefore(new Text(w.data.slice(0, k)), at);
+ if (k < w.data.length) el.insertBefore(fresh(w.data.slice(k)), at);
+ } else if (at && !textish(at) && same(at, w)) {
+ patch(at, w);
+ at = at.nextSibling;
+ } else {
+ // A new element: the start of its words that were on screen as
+ // plain text in its place (an opener that just closed) stays still.
+ var seen = { n: 0 };
+ if (at && textish(at)) {
+ var t = run();
+ seen.n = common(t.text, w.textContent);
+ left(t, seen.n);
+ }
+ el.insertBefore(copy(w, seen), at);
}
- body.lastElementChild.append(caret);
+ }
+ while (at) {
+ var gone = at;
+ at = at.nextSibling;
+ gone.remove();
}
}
// The committed reply takes over its draft in place: the same element,
@@ -315,6 +433,10 @@
time.textContent = done.textContent;
}
var body = live.querySelector("[equipo-message-body]"), final = server.querySelector("[equipo-message-body]");
+ if (body && body.draft) {
+ cancelAnimationFrame(body.draft.frame);
+ delete body.draft;
+ }
if (body && final) {
Array.from(body.attributes).forEach(function (a) { body.removeAttribute(a.name); });
Array.from(final.attributes).forEach(function (a) { body.setAttribute(a.name, a.value); });
@@ -706,7 +828,10 @@
// The refused attempt's words go; the next attempt's follow.
delete drafts[v.id];
var body = shownDraft && shownDraft.querySelector("[data-stream-text]");
- if (body) body.textContent = "";
+ if (body) {
+ delete body.draft;
+ body.textContent = "";
+ }
}
// Going again on a connection: the status and the card go.
if (heldNow || feed.querySelector('[data-message] [data-waiting-connection]')) refreshSoon();
diff --git a/internal/equipo/templates/conversation_card.html b/internal/equipo/templates/conversation_card.html
index 23f67b01..556c8392 100644
--- a/internal/equipo/templates/conversation_card.html
+++ b/internal/equipo/templates/conversation_card.html
@@ -31,7 +31,7 @@
</section>
{{end}}
{{define "conversation-card"}}
-{{if .Thinking}}<div equipo-message="incoming" equipo-thinking data-turn="{{.ID}}" aria-busy="true"><div equipo-message-meta><strong>{{icon "message-circle"}}{{copy "conversation.coordinator"}}</strong></div><div equipo-bubble>{{if .ConnectionLabel}}<span>{{printf (copy "coordinator.waiting_connection_label") .ConnectionLabel}}</span>{{else if .PartialText}}<div equipo-markdown data-stream-text>{{chatMarkdown .PartialText}}</div>{{else}}<span equipo-visually-hidden>{{copy "conversation.thinking"}}</span>{{end}}<span equipo-thinking-dots aria-hidden="true"><i></i><i></i><i></i></span></div></div>{{else}}
+{{if .Thinking}}<div equipo-message="incoming" equipo-thinking data-turn="{{.ID}}" aria-busy="true"><div equipo-message-meta><strong>{{icon "message-circle"}}{{copy "conversation.coordinator"}}</strong></div><div equipo-bubble>{{if .ConnectionLabel}}<span>{{printf (copy "coordinator.waiting_connection_label") .ConnectionLabel}}</span>{{else if .PartialText}}<div equipo-markdown data-stream-text>{{chatDraft .PartialText}}</div>{{else}}<span equipo-visually-hidden>{{copy "conversation.thinking"}}</span>{{end}}<span equipo-thinking-dots aria-hidden="true"><i></i><i></i><i></i></span></div></div>{{else}}
<article {{if eq .Kind "coordinator"}}equipo-system-note{{end}} equipo-card data-card="{{.ID}}"{{if or .NativeQuestion .Question}} equipo-question{{end}}>
{{with .ProjectProposal}}
<h2>{{printf (copy "project_setup.heading") .Name .Repository}}</h2><p>{{.Why}}</p>
diff --git a/internal/fakeclaude/fake.go b/internal/fakeclaude/fake.go
index 1c487990..b06c72cd 100644
--- a/internal/fakeclaude/fake.go
+++ b/internal/fakeclaude/fake.go
@@ -11,7 +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, "slowstream" pauses after every chunk,
+// replies with non-ASCII text, "replymd" (or "replymd:long") 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>...,
@@ -712,6 +713,9 @@ func (f *fake) serve(stdin io.Reader, stdout, stderr io.Writer) int {
if strings.Contains(newest, "accents") {
reply = "Café con ñandú, señor. ☕ Ünïcödé 🎉 works."
}
+ if md, ok := markdownReply(newest); ok {
+ reply = md
+ }
if strings.Contains(prompt, "Conversation so far") {
reply += " I see the earlier conversation."
}
@@ -886,7 +890,7 @@ func (f *fake) serve(stdin io.Reader, stdout, stderr io.Writer) int {
if byToken {
reply += " (signed in by token)"
}
- chunks := split(reply, 3)
+ chunks := split(reply, chunkCount(newest))
for i, chunk := range chunks {
if f.partial {
emit(map[string]any{"type": "stream_event", "session_id": f.session, "parent_tool_use_id": nil, "event": map[string]any{"type": "content_block_delta", "index": 0, "delta": map[string]string{"type": "text_delta", "text": chunk}}, "uuid": fmt.Sprintf("delta-%d-%d", turn, i)})
diff --git a/internal/fakeclaude/markdown.go b/internal/fakeclaude/markdown.go
new file mode 100644
index 00000000..dff66ccc
--- /dev/null
+++ b/internal/fakeclaude/markdown.go
@@ -0,0 +1,44 @@
+package fakeclaude
+
+import (
+ "regexp"
+ "strconv"
+ "strings"
+)
+
+// markdownSample is a coordinator reply in the shape the conversation
+// streams most: a bold opening line, a bold-led bullet list and a
+// 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`)
+
+func markdownReply(newest string) (string, bool) {
+ m := markdownWord.FindStringSubmatch(newest)
+ if m == nil {
+ return "", false
+ }
+ if m[1] == "" {
+ return markdownSample, true
+ }
+ parts := make([]string, 30)
+ for i := range parts {
+ parts[i] = "## Part " + strconv.Itoa(i+1) + "\n\n" + markdownSample
+ }
+ return strings.Join(parts, "\n\n"), true
+}
+
+// chunksWord streams the reply in that many deltas ("chunks:<n>",
+// three without it).
+var chunksWord = regexp.MustCompile(`\bchunks:([0-9]+)`)
+
+func chunkCount(newest string) int {
+ if m := chunksWord.FindStringSubmatch(newest); m != nil {
+ if n, err := strconv.Atoi(m[1]); err == nil && n > 0 {
+ return n
+ }
+ }
+ return 3
+}
diff --git a/internal/headless/browser_stream_markdown_test.go b/internal/headless/browser_stream_markdown_test.go
new file mode 100644
index 00000000..afed7f2c
--- /dev/null
+++ b/internal/headless/browser_stream_markdown_test.go
@@ -0,0 +1,117 @@
+//go:build browser
+
+package headless
+
+import (
+ "context"
+ "sort"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/browsertest"
+ "amadan.net/rastrillo/rastrillo/harness"
+ "github.com/chromedp/cdproto/cdp"
+ "github.com/chromedp/cdproto/emulation"
+ "github.com/chromedp/cdproto/network"
+ "github.com/chromedp/chromedp"
+)
+
+// A formatted reply is formatted as it streams: its bullets are list
+// items on their own lines, no asterisks show, the new words fade in
+// inside the formatting, and the committed reply is the last streamed
+// render plus at most its last characters (normalised HTML; the same
+// height when equal). A long reply is drawn within light.js's frame
+// budget (about 4 ms).
+func TestBrowserDraftStreamsFormatted(t *testing.T) {
+ _, inst, r := localEnv(t)
+ r.start(t)
+ alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(chromedp.DefaultExecAllocatorOptions[:], chromedp.ExecPath(harness.ChromePath(t)), chromedp.Flag("headless", true), chromedp.NoSandbox)...)
+ defer cancelAlloc()
+ ctx, cancel := chromedp.NewContext(alloc)
+ defer cancel()
+ run := func(actions ...chromedp.Action[chromedp.Void]) {
+ t.Helper()
+ if err := chromedp.Do(ctx, actions...); err != nil {
+ t.Fatal(err)
+ }
+ }
+ check := func(expression, reason string) {
+ t.Helper()
+ if !evaluateIn[bool](t, ctx, expression) {
+ t.Fatalf("%s (recorded: %s)", reason, evaluateIn[string](t, ctx, `JSON.stringify(window.__s ? {last: window.__s.last, stray: window.__s.stray, fade: window.__s.fade, lines: window.__s.lines} : null)`))
+ }
+ }
+ cookie := inst.Cookie()
+ open := func(motion string) {
+ t.Helper()
+ run(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error {
+ if _, err := cdp.Call(ctx, target, network.SetCookie, network.SetCookieParams{Name: cookie.Name, Value: cookie.Value, URL: inst.URL}); err != nil {
+ return err
+ }
+ _, err := cdp.Call(ctx, target, emulation.SetEmulatedMedia, emulation.SetEmulatedMediaParams{Features: []*emulation.MediaFeature{{Name: "prefers-reduced-motion", Value: motion}}})
+ return err
+ }), chromedp.EmulateViewport(1280, 800), chromedp.Navigate(inst.URL+"/conversation"), browsertest.Wait(`!!document.querySelector('[data-chat-stream]') && document.querySelector('[equipo-offline]').hidden`))
+ }
+ // record follows the next reply frame by frame until it is committed:
+ // its last render (the fade spans unwrapped) and height, markup shown
+ // outside code, the fade inside a list item, where two list items sit,
+ // and each draw's time.
+ record := `(()=>{const s=window.__s={el:null,last:null,h:0,stray:null,fade:null,lines:null,frames:[],done:false};
+new PerformanceObserver(l=>{for(const e of l.getEntries())if(e.name==='equipo-draft')s.frames.push(e.duration)}).observe({type:'measure'});
+window.__norm=b=>{const c=document.createElement('div');c.innerHTML=b.innerHTML;c.querySelectorAll('[equipo-stream-caret]').forEach(e=>e.remove());c.querySelectorAll('span[data-new]').forEach(e=>e.replaceWith(new Text(e.textContent)));c.normalize();return c.innerHTML};
+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('[data-stream-text]');if(b&&b.firstChild){s.last=window.__norm(b);s.h=b.getBoundingClientRect().height;
+const c=document.createElement('div');c.innerHTML=b.innerHTML;c.querySelectorAll('pre, code').forEach(e=>e.remove());if(/[*\x60]|\]\(/.test(c.textContent))s.stray=c.textContent;
+const n=b.querySelector('li [data-new]');if(n&&!s.fade){const st=getComputedStyle(n);s.fade=st.animationName+' '+st.animationDuration}
+const li=b.querySelectorAll('ul > li');if(li.length>=2&&!s.lines)s.lines=[li[0].getBoundingClientRect().top,li[1].getBoundingClientRect().top,li[0].textContent,li[1].textContent]}}
+if(!x||x.hasAttribute('equipo-thinking'))requestAnimationFrame(f);else s.done=true};f();return true})()`
+ send := func(text string) {
+ t.Helper()
+ check(record, "record")
+ check(`(()=>{document.querySelector('#chat-body').value=`+jsString(text)+`;document.querySelector('#composer').requestSubmit();return true})()`, "send")
+ }
+ committed := func(reason string) {
+ t.Helper()
+ run(browsertest.WaitWithin(`window.__s.done && !!window.__s.el.dataset.message`, 60*time.Second))
+ // Past what the two share, the last render has only the closing
+ // tags of the text it ends in.
+ check(`(()=>{const f=window.__norm(window.__s.el.querySelector('[equipo-message-body]')),l=window.__s.last;let k=0;while(k<l.length&&l[k]===f[k])k++;window.__s.same=l===f;return l===f||/^(<\/[a-z]+>\s*)+$/.test(l.slice(k))&&f.length-k<80})()`, reason+": the committed reply is not the last streamed render plus its last characters")
+ check(`!window.__s.same || Math.abs(window.__s.el.querySelector('[equipo-message-body]').getBoundingClientRect().height-window.__s.h)<1`, reason+": the reply changed height when committed")
+ t.Logf("%s: last streamed render equal to the committed reply: %v", reason, evaluateIn[bool](t, ctx, `window.__s.same`))
+ check(`window.__s.stray===null`, reason+": markup characters showed while streaming")
+ }
+ for _, m := range []struct{ motion, fade string }{{"no-preference", "equipo-fade 0.32s"}, {"reduce", "equipo-fade 0.2s"}} {
+ open(m.motion)
+ send("replymd chunks:80 sleep:40 slowstream")
+ // While streaming the bullets are list items on their own lines.
+ run(browsertest.WaitWithin(`!!window.__s.lines`, 30*time.Second))
+ check(`window.__s.lines[1]-window.__s.lines[0]>8 && window.__s.lines[2].startsWith('Guest:') && (window.__s.lines[3].startsWith('Customer:') || 'Customer:'.startsWith(window.__s.lines[3]))`, "the bullets did not stream as list items on their own lines")
+ committed(m.motion)
+ check(`window.__s.fade===`+jsString(m.fade), "the words in a list item did not fade in as "+m.fade)
+ check(`(()=>{const b=window.__s.el.querySelector('[equipo-message-body]');return b.querySelectorAll('ol > li').length===3 && b.querySelectorAll('strong').length===6 && !!b.querySelector('a[href="/tasks/tks6kwzzdngr"]') && !!b.querySelector('li code')})()`, "the committed reply lost its formatting")
+ }
+ // A long reply: about 14 KB in 400 deltas.
+ open("no-preference")
+ send("replymd:long chunks:400 sleep:12 slowstream")
+ committed("long reply")
+ // The runner sends the deltas it has about ten times a second.
+ frames := evaluateIn[[]float64](t, ctx, `window.__s.frames`)
+ sort.Float64s(frames)
+ if n := len(frames); n < 30 || frames[n*95/100] > 4 {
+ t.Fatalf("long reply: %d draws (want 30 or more), 95th percentile %.2f ms (budget 4 ms)", n, frames[n*95/100])
+ }
+ t.Logf("long reply: %d draws, median %.2f ms, 95th %.2f ms, worst %.2f ms", len(frames), frames[len(frames)/2], frames[len(frames)*95/100], frames[len(frames)-1])
+}
+
+// evaluateIn is the value of a page expression in the browser of ctx.
+func evaluateIn[T any](t *testing.T, ctx context.Context, expression string) T {
+ t.Helper()
+ var out T
+ if err := chromedp.Do(ctx, chromedp.Func(func(ctx context.Context, target *chromedp.Target) (err error) {
+ out, err = chromedp.Evaluate[T](expression)(ctx, target)
+ return
+ })); err != nil {
+ t.Fatal(err)
+ }
+ return out
+}
diff --git a/internal/headless/browser_test.go b/internal/headless/browser_test.go
index 0af12971..84238961 100644
--- a/internal/headless/browser_test.go
+++ b/internal/headless/browser_test.go
@@ -51,7 +51,7 @@ func TestBrowserChat(t *testing.T) {
// Multibyte text: every delta lands in the draft, which reaches the
// full reply before the committed message replaces it.
send("accents slowstream sleep:700")
- run(browsertest.Wait(`[...document.querySelectorAll('[data-stream-text]')].some(e=>e.textContent==="Café con ñandú, señor. ☕ Ünïcödé 🎉 works.")`))
+ run(browsertest.Wait(`[...document.querySelectorAll('[data-stream-text]')].some(e=>e.textContent.trim()==="Café con ñandú, señor. ☕ Ünïcödé 🎉 works.")`))
run(browsertest.Wait(`[...document.querySelectorAll('[equipo-markdown]:not([data-stream-text])')].some(e=>e.textContent.includes("🎉 works")) && !document.querySelector('[equipo-thinking]')`))
r.stop(t)
run(browsertest.Wait(`!document.querySelector('[equipo-offline]').hidden`))
diff --git a/internal/plan3test/conversation_draft_test.go b/internal/plan3test/conversation_draft_test.go
new file mode 100644
index 00000000..2fce5fc1
--- /dev/null
+++ b/internal/plan3test/conversation_draft_test.go
@@ -0,0 +1,52 @@
+package plan3test
+
+import (
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/chatmarkdown"
+)
+
+// A streaming reply is drawn by the server's renderer: the page posts the
+// text so far and gets back RenderDraft's HTML, from this origin, to a
+// member only.
+func TestConversationDraftRendersOnTheServer(t *testing.T) {
+ f := newFixture(t)
+ post := func(cookie bool, site, text string) *httptest.ResponseRecorder {
+ t.Helper()
+ r := httptest.NewRequest("POST", "/conversation/draft", strings.NewReader(url.Values{"text": {text}}.Encode()))
+ r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ r.Header.Set("Origin", origin)
+ if site != "" {
+ r.Header.Set("Sec-Fetch-Site", site)
+ }
+ if cookie {
+ r.AddCookie(f.Cookies[owner.Address])
+ }
+ w := httptest.NewRecorder()
+ f.Handler.ServeHTTP(w, r)
+ return w
+ }
+ 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)) {
+ 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" {
+ t.Fatal("draft headers", w.Header())
+ }
+ if w := post(true, "cross-site", text); w.Code != 403 {
+ t.Fatal("cross-site draft render", w.Code)
+ }
+ if w := post(true, "", text); w.Code != 403 {
+ t.Fatal("draft render without fetch metadata", w.Code)
+ }
+ if w := post(false, "same-origin", text); w.Code == 200 {
+ t.Fatal("draft render without a session")
+ }
+ if w := post(true, "same-origin", strings.Repeat("a", 300<<10)); w.Code == 200 {
+ t.Fatal("oversized draft rendered")
+ }
+}
diff --git a/internal/thintest/macrecheck_contract_test.go b/internal/thintest/macrecheck_contract_test.go
new file mode 100644
index 00000000..4f5d8b4a
--- /dev/null
+++ b/internal/thintest/macrecheck_contract_test.go
@@ -0,0 +1,262 @@
+package thintest
+
+import (
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// waitingForMac runs an iOS change with no Mac enrolled to Ready to merge:
+// its checks end on the primary as not run (needs_macos), review
+// approves, and the merge card asks. It returns the task, its candidate
+// and the card.
+func (r *runnersRig) waitingForMac(title string) (task, sha string, card wire.Card) {
+ r.t.Helper()
+ task, sha = r.candidate(title, true)
+ _, body := r.expect(wire.FrameDispatch)
+ c := body.(*wire.DispatchCommand)
+ if c.Specialist != wire.SpecialistChecks || c.TaskID != task || len(c.Needs) != 0 {
+ r.t.Fatalf("checks on the primary %+v", c)
+ }
+ r.checks(task+"-c", c, wire.ChecksCannotRun, nil, "needs_macos", "")
+ _, body = r.expect(wire.FrameDispatch)
+ r.verdict(task+"-r", body.(*wire.DispatchCommand), wire.VerdictApprove)
+ r.wait("waiting for a Mac", func(c *Conversation) bool {
+ for _, k := range c.Cards {
+ if k.Kind == wire.CardMerge && k.TaskID == task && c.Tasks[task].Stage == wire.StageReadyToMerge {
+ card = k
+ return true
+ }
+ }
+ return false
+ })
+ return task, sha, card
+}
+
+// checksRuns are the task's checks steps.
+func (r *runnersRig) checksRuns(task string) []wire.Step {
+ r.t.Helper()
+ k, err := r.client.Task(r.ctx, task)
+ if err != nil {
+ r.t.Fatal(err)
+ }
+ var out []wire.Step
+ for _, s := range k.Steps {
+ if s.Specialist == wire.SpecialistChecks {
+ out = append(out, s)
+ }
+ }
+ return out
+}
+
+// macRecheck reads the Mac's dispatch of a task's checks again, on sha.
+func macRecheck(t *testing.T, w *peer, task, sha string) *wire.DispatchCommand {
+ t.Helper()
+ _, body := w.expect(wire.FrameDispatch)
+ d := body.(*wire.DispatchCommand)
+ if d.Specialist != wire.SpecialistChecks || d.TaskID != task || d.CandidateSHA != sha || d.Attempt != 1 || strings.Join(d.Needs, ",") != "macos,xcode" {
+ t.Fatalf("checks again on the Mac %+v", d)
+ }
+ return d
+}
+
+// A task waiting for a Mac (Wait for a Mac on its card) gets its checks
+// again, on the exact candidate, the moment a Mac that fits enrols: once,
+// a reconnect places nothing more. They pass on the Mac (sandboxed), so
+// Equipo merges that SHA with no tap.
+func TestContractMacRecheckOnEnrol(t *testing.T) {
+ r := newRunnersRig(t)
+ task, sha, card := r.waitingForMac("Swipe back on iOS")
+ if out, err := r.client.Answer(r.ctx, card.ID, wire.ChoiceWait, card.Revision); err != nil || out.Card.Choice != wire.ChoiceWait {
+ t.Fatalf("wait %+v %v", out, err)
+ }
+ w, _ := r.newWorker("Tito Studio")
+ d := macRecheck(t, w, task, sha)
+ if runs := r.checksRuns(task); len(runs) != 2 || runs[1].ID != d.StepID || runs[1].RunnerLabel != "Tito Studio" {
+ t.Fatalf("checks runs %+v", runs)
+ }
+ w = r.reconnectPeer(w)
+ w.none(wire.FrameDispatch, 200*time.Millisecond)
+ if runs := r.checksRuns(task); len(runs) != 2 {
+ t.Fatalf("a reconnect ran the checks again: %+v", runs)
+ }
+ r.relay(w, []byte("PACK swipe back"))
+ if !w.lease(d.StepID, 1) {
+ t.Fatal("start refused")
+ }
+ pass := passed(task, d.StepID, 1, sha)
+ pass.ChecksSandbox = wire.SandboxSeatbelt
+ w.send(wire.FrameStep, pass)
+ _, body := r.expect(wire.FrameDispatch)
+ if m := body.(*wire.DispatchCommand); m.Specialist != wire.SpecialistMerge || m.TaskID != task || m.CandidateSHA != sha {
+ t.Fatalf("merge dispatch %+v", m)
+ }
+ if k, _ := r.client.Task(r.ctx, task); k.Stage != wire.StageMerging || k.Checks != wire.ChecksPassed {
+ t.Fatalf("after the Mac's pass %+v", k)
+ }
+}
+
+// Only tasks still waiting: a Linux runner enrolling places nothing; a
+// Mac enrolling skips cancelled tasks, merged ones, ones whose person
+// chose Merge (without checks, even back at Ready after the hub refused
+// it) and ones whose branch moved off the
+// candidate, and re-runs only the one still waiting (left with its card
+// open, which the run withdraws).
+func TestContractMacRecheckOnlyWaiting(t *testing.T) {
+ r := newRunnersRig(t)
+ waiting, sha, open := r.waitingForMac("Still waiting")
+ cancelled, _, _ := r.waitingForMac("Cancelled one")
+ if _, err := r.client.CancelTask(r.ctx, cancelled); err != nil {
+ t.Fatal(err)
+ }
+ merged, _, mc := r.waitingForMac("Merged")
+ if _, err := r.client.Answer(r.ctx, mc.ID, wire.ChoiceMerge, mc.Revision); err != nil {
+ t.Fatal(err)
+ }
+ _, body := r.expect(wire.FrameDispatch)
+ r.mergedStep("merged-m", body.(*wire.DispatchCommand), strings.Repeat("f", 40))
+ chosen, _, cc := r.waitingForMac("Merge chosen")
+ if _, err := r.client.Answer(r.ctx, cc.ID, wire.ChoiceMerge, cc.Revision); err != nil {
+ t.Fatal(err)
+ }
+ _, body = r.expect(wire.FrameDispatch)
+ m := body.(*wire.DispatchCommand)
+ if m.Specialist != wire.SpecialistMerge {
+ t.Fatalf("merge chosen %+v", m)
+ }
+ // The hub refused it: back at Ready to merge, with Retry.
+ r.step("chosen-m", wire.StepReport{TaskID: chosen, StepID: m.StepID, Attempt: 1, State: wire.StepFailed, Reason: "amadan_ci_pending", BaseSHA: m.BaseSHA, CandidateSHA: m.CandidateSHA, Termination: true})
+ moved, msha, _ := r.waitingForMac("Moved")
+ if err := r.runner.Send(r.ctx, "moved-b", wire.FrameBranch, wire.BranchReport{TaskID: moved, CandidateSHA: msha, Head: strings.Repeat("9", 40)}); err != nil {
+ t.Fatal(err)
+ }
+ r.wait("ended or moved", func(c *Conversation) bool {
+ return c.Tasks[moved].NeedsYou == wire.NeedsBranchMoved && c.Tasks[merged].Stage == wire.StageDone && c.Tasks[cancelled].Stage == wire.StageCancelled && c.Tasks[chosen].Stage == wire.StageReadyToMerge
+ })
+
+ linux := WorkerHello(0)
+ linux.Label, linux.Platform, linux.Sandbox = "Build box", &wire.Platform{OS: "linux", Arch: "amd64"}, wire.SandboxBubblewrap
+ linux.Capabilities = &wire.Capabilities{Simulators: []wire.Simulator{}, Tags: []string{wire.TagLinux, wire.TagGo}}
+ lr, err := DialRunnerHello(r.ctx, r.inst.URL, r.inst.EnrolRunner(t).Token, linux)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(lr.Close)
+ (&peer{t: t, r: r.toolRig, fr: lr}).none(wire.FrameDispatch, 200*time.Millisecond)
+ for _, id := range []string{waiting, cancelled, merged, chosen, moved} {
+ if runs := r.checksRuns(id); len(runs) != 1 {
+ t.Fatalf("a Linux runner re-ran %s's checks: %+v", id, runs)
+ }
+ }
+
+ w, _ := r.newWorker("Tito Studio")
+ macRecheck(t, w, waiting, sha)
+ w.none(wire.FrameDispatch, 200*time.Millisecond)
+ for _, id := range []string{cancelled, merged, chosen, moved} {
+ if runs := r.checksRuns(id); len(runs) != 1 {
+ t.Fatalf("checks of %s re-ran: %+v", id, runs)
+ }
+ }
+ r.wait("card withdrawn", func(c *Conversation) bool { return c.Cards[open.ID].State == wire.CardResolved })
+}
+
+// The run follows the usual paths: ending not run again on the Mac
+// (needs_macos) asks the card afresh, and that Mac reconnecting runs
+// nothing (once per candidate per enrolment); another Mac enrolling runs
+// them once more, and checks that fail send Engineering its fix round.
+func TestContractMacRecheckOutcomes(t *testing.T) {
+ r := newRunnersRig(t)
+ task, sha, _ := r.waitingForMac("Swipe back on iOS")
+ a, _ := r.newWorker("Mac A")
+ d := macRecheck(t, a, task, sha)
+ r.relay(a, []byte("PACK a"))
+ if !a.lease(d.StepID, 1) {
+ t.Fatal("start refused")
+ }
+ a.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: d.StepID, Attempt: 1, State: wire.StepDone, Reason: "needs_macos", CandidateSHA: sha, Checks: wire.ChecksCannotRun, Termination: true, TerminationKind: wire.TerminationProcessGroup, Findings: []wire.Finding{}})
+ var card wire.Card
+ r.wait("asked again", func(c *Conversation) bool {
+ for _, k := range c.Cards {
+ if k.Kind == wire.CardMerge && k.TaskID == task && k.State == wire.CardOpen {
+ card = k
+ }
+ }
+ return card.ID != "" && c.Tasks[task].Stage == wire.StageReadyToMerge
+ })
+ a = r.reconnectPeer(a)
+ a.none(wire.FrameDispatch, 200*time.Millisecond)
+ if runs := r.checksRuns(task); len(runs) != 2 {
+ t.Fatalf("the same Mac reconnecting re-ran them: %+v", runs)
+ }
+ // Mac A away, so placement takes the newcomer.
+ a.fr.Close()
+ time.Sleep(100 * time.Millisecond)
+ b, _ := r.newWorker("Mac B")
+ _, body := b.expect(wire.FrameDispatch)
+ d2 := body.(*wire.DispatchCommand)
+ if d2.TaskID != task || d2.CandidateSHA != sha || d2.StepID == d.StepID {
+ t.Fatalf("second Mac's checks %+v", d2)
+ }
+ r.relay(b, []byte("PACK b"))
+ if !b.lease(d2.StepID, 1) {
+ t.Fatal("start refused")
+ }
+ one := 1
+ b.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: d2.StepID, Attempt: 1, State: wire.StepDone, CandidateSHA: sha, Checks: wire.ChecksFailed, Gate: "xcodebuild test", ExitCode: &one, Output: "** TEST FAILED **", ChecksSandbox: wire.SandboxSeatbelt, Termination: true, TerminationKind: wire.TerminationProcessGroup, Findings: []wire.Finding{}})
+ _, body = r.expect(wire.FrameDispatch)
+ if e := body.(*wire.DispatchCommand); e.Specialist != wire.SpecialistEngineering || e.TaskID != task || e.Round != 1 {
+ t.Fatalf("fix round %+v", e)
+ }
+}
+
+// A Mac that comes back online (a heartbeat after it was offline) runs
+// the waiting checks too, once: it connected before its capability report
+// was in (no tags, so nothing then), went quiet, and says hello as a Mac.
+// Even with those checks ended not run again, its coming back again, or
+// reconnecting, runs nothing more.
+func TestContractMacRecheckBackOnline(t *testing.T) {
+ r := newRunnersRig(t)
+ task, sha, _ := r.waitingForMac("Swipe back on iOS")
+ token := r.inst.EnrolRunner(t).Token
+ bare := WorkerHello(0)
+ bare.Capabilities = nil
+ fr, err := DialRunnerHello(r.ctx, r.inst.URL, token, bare)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(fr.Close)
+ w := &peer{t: t, r: r.toolRig, fr: fr}
+ w.none(wire.FrameDispatch, 200*time.Millisecond)
+ if runs := r.checksRuns(task); len(runs) != 1 {
+ t.Fatalf("a runner with no tags re-ran the checks: %+v", runs)
+ }
+ clock := time.Now().UTC()
+ r.inst.Store.Chat().SetClock(func() time.Time { return clock })
+ back := func() {
+ clock = clock.Add(2 * time.Minute)
+ w.heartbeat(WorkerHello(0))
+ }
+ back()
+ d := macRecheck(t, w, task, sha)
+ r.relay(w, []byte("PACK swipe back"))
+ if !w.lease(d.StepID, 1) {
+ t.Fatal("start refused")
+ }
+ w.send(wire.FrameStep, wire.StepReport{TaskID: task, StepID: d.StepID, Attempt: 1, State: wire.StepDone, Reason: "needs_macos", CandidateSHA: sha, Checks: wire.ChecksCannotRun, Termination: true, TerminationKind: wire.TerminationProcessGroup, Findings: []wire.Finding{}})
+ r.wait("ready again", func(c *Conversation) bool { return c.Tasks[task].Stage == wire.StageReadyToMerge })
+ back()
+ w.none(wire.FrameDispatch, 200*time.Millisecond)
+ fr.Close()
+ time.Sleep(100 * time.Millisecond)
+ again, err := DialRunnerHello(r.ctx, r.inst.URL, token, WorkerHello(fr.Welcome.Generation))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(again.Close)
+ (&peer{t: t, r: r.toolRig, fr: again}).none(wire.FrameDispatch, 200*time.Millisecond)
+ if runs := r.checksRuns(task); len(runs) != 2 {
+ t.Fatalf("coming back again re-ran the checks: %+v", runs)
+ }
+}
diff --git a/internal/thintest/projects_pages_test.go b/internal/thintest/projects_pages_test.go
index ece6ead4..f6705f04 100644
--- a/internal/thintest/projects_pages_test.go
+++ b/internal/thintest/projects_pages_test.go
@@ -252,7 +252,7 @@ func TestPagesTaskDecisionsSayWhy(t *testing.T) {
card := regexp.MustCompile(`(?s)<div equipo-decision[^>]*data-decision="` + g.unchecked + `">.*?</div>\n</div>`).FindString(needs)
for _, want := range []string{"Review approved. Checks need a Mac, and no Mac is set up to run them.", "Merge without checks?",
`data-merge-choice="merge">Merge now</button>`, `data-merge-choice="wait">Wait for a Mac</button>`,
- "Merge now merges it without checks. Wait for a Mac leaves it as it is. Once a Mac is set up, checks run on its next change, and if they pass, Equipo merges it by itself.",
+ "Merge now merges it without checks. Wait for a Mac keeps it ready. Once a Mac is set up, checks run, and if they pass, Equipo merges it by itself.",
`<a equipo-link href="/runners/enrol" data-set-up-mac>Set up a Mac</a>`, `href="/conversation?about=` + g.unchecked + `" data-ask-about>Ask about this</a>`} {
if !strings.Contains(card, want) {
t.Fatalf("Mac decision lacks %q:\n%s", want, card)
diff --git a/scripts/runner-reference-allowlist.json b/scripts/runner-reference-allowlist.json
index bedbde36..66a8b12e 100644
--- a/scripts/runner-reference-allowlist.json
+++ b/scripts/runner-reference-allowlist.json
@@ -11016,5 +11016,40 @@
"match": "npm",
"count": 1,
"reason": "Team panel activity wording: recognises a specialist's npm or node command to describe it in plain words; not a runner dependency."
+ },
+ {
+ "path": "internal/chatmarkdown/draft.go",
+ "line_sha256": "ee91145c8919642eb26c82db1674ec5f86d7a5127626b5780ad4b75816a5e34c",
+ "match": "Node",
+ "count": 1,
+ "reason": "Markdown syntax tree node traversal in the Go renderer; no external runtime."
+ },
+ {
+ "path": "internal/chatmarkdown/draft.go",
+ "line_sha256": "bfd8eb8376e241eca5adaf2bb9c3072529c3bfa7c8e481d2274df30a885fc039",
+ "match": "Node",
+ "count": 1,
+ "reason": "Markdown syntax tree node traversal in the Go renderer; no external runtime."
+ },
+ {
+ "path": "internal/chatmarkdown/draft.go",
+ "line_sha256": "221929a57b168baeb3648aee8733abd4af0a08a0124a1c022f07eadfd182eb27",
+ "match": "Node",
+ "count": 2,
+ "reason": "Markdown syntax tree node traversal in the Go renderer; no external runtime."
+ },
+ {
+ "path": "internal/chatmarkdown/draft.go",
+ "line_sha256": "0a119e5854b4f0f14cbed0e318beedcf8e02a58d81995a51a4e6a70445560211",
+ "match": "Node",
+ "count": 1,
+ "reason": "Markdown syntax tree node traversal in the Go renderer; no external runtime."
+ },
+ {
+ "path": "internal/chatmarkdown/draft.go",
+ "line_sha256": "d60d917f1adaa14b960bae0ec9de8bc3ef9be5178caf139edd0996094c22526b",
+ "match": "Node",
+ "count": 1,
+ "reason": "Markdown syntax tree node traversal in the Go renderer; no external runtime."
}
]