Conversation: a streaming reply is formatted as it streams
The draft was drawn as raw text split on blank lines, inside an [equipo-markdown] body whose white-space: normal collapsed every single newline, so bullets and numbered steps ran together in one paragraph until the committed reply's markdown replaced it. The server now renders drafts with the finished message's renderer: chat-stream.js posts the text so far to POST /conversation/draft (member, same-origin) and gets chatmarkdown.RenderDraft's HTML, one request at a time per draft, painted at most once per frame. paint patches the DOM in place: unchanged blocks stay, new words fade in as [data-new] spans inside lists and bold, text that was on screen stays still when an opener closes or a link completes. RenderDraft is Render over the same goldmark parse, leaving out what the next characters could change: a last line that is only a list marker, hashes or a fence waits; in the paragraph still open at the end an unclosed ** or backtick and a link's brackets are not shown; an open fence is an open code block. Tests: corpus prefixes (no markup shows, text is a prefix of the finished reply, whole draft equals Render), the endpoint's guards, and a browser drive (fakeclaude replymd) comparing the last streamed render with the committed reply and timing a 14 KB reply (95th 1.5 ms).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
14 files changed,
+754
−38
internal/chatmarkdown/draft.go+174 −0internal/chatmarkdown/draft_test.go+115 −0internal/chatmarkdown/markdown.go+19 −5internal/equipo/app.go+1 −0internal/equipo/chat_draft.go+35 −0internal/equipo/render.go+1 −1internal/equipo/static/chat-stream.js+153 −28internal/equipo/templates/conversation_card.html+1 −1internal/fakeclaude/fake.go+6 −2internal/fakeclaude/markdown.go+44 −0internal/headless/browser_stream_markdown_test.go+117 −0internal/headless/browser_test.go+1 −1internal/plan3test/conversation_draft_test.go+52 −0scripts/runner-reference-allowlist.json+35 −0
Intent
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)", ``, "<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_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/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 d7baa8f1..2b89b135 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); }); |
| @@ -638,7 +760,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/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." |
| } |
| ] |