oficina / base Public

Ask: draw lookups live as they arrive

ask.js draws a message event's lookups after the reply's words, as the
server does: lookupMarkdown (rich with strict emphasis and links off,
after turning Markdown links into their words), and the Sources line
with each https source's title as a link in a new tab and its host.
Browser tests pin the DOM to the server's for two lookups, a link in an
answer and a multibyte title, the new-tab rules, and no links in answers.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev c40029ca80b0cf86c35e622b52687bb32ad69a40 parent 9a4b829
4 files changed, +189 −5
  • internal/browsertest/ask_lookup_test.go +112 −0
  • internal/equipo/equipotest/chat.go +11 −0
  • internal/look/static/app.css +1 −0
  • internal/look/static/ask.js +65 −5
diff --git a/internal/browsertest/ask_lookup_test.go b/internal/browsertest/ask_lookup_test.go
new file mode 100644
index 0000000..dd3395d
--- /dev/null
+++ b/internal/browsertest/ask_lookup_test.go
@@ -0,0 +1,112 @@
+//go:build browser
+
+package browsertest
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "strconv"
+ "testing"
+ "time"
+
+ "github.com/chromedp/chromedp"
+
+ "amadan.net/rastrillo/rastrillo/harness"
+
+ "amadan.net/oficina/base/internal/equipo"
+)
+
+// sameAsServer is every reply in the panel whose HTML differs from the
+// same reply on /ask, drawn by the server; "" when they all match.
+const sameAsServer = `(async () => {
+ const page = new DOMParser().parseFromString(await (await fetch("/ask")).text(), "text/html");
+ const out = [];
+ for (const m of document.querySelectorAll("#ask-panel .msg.coordinator")) {
+ const s = page.querySelector('.msg.coordinator[data-id="' + CSS.escape(m.dataset.id) + '"]');
+ if (!s) out.push(m.dataset.id + ": not on /ask");
+ else if (s.innerHTML !== m.innerHTML) out.push(JSON.stringify(m.textContent) + "\n script " + m.innerHTML + "\n server " + s.innerHTML);
+ }
+ return out.join("\n");
+})()`
+
+// sayLookups has the Assistant say each reply, with its lookups, while the
+// panel is open, and waits for them all to be drawn.
+func sayLookups(t *testing.T, replies map[string][]equipo.Lookup, order []string) *harness.Rig {
+ t.Helper()
+ rig, f := askBase(t)
+ openPanel(t, rig)
+ for _, text := range order {
+ f.SayWithLookups(text, replies[text]...)
+ }
+ drive(t, rig, chromedp.Poll[chromedp.Void](`document.querySelectorAll("#ask-panel .msg.coordinator").length === `+strconv.Itoa(len(order)),
+ chromedp.WithPollingTimeout(10*time.Second)))
+ return rig
+}
+
+// The panel draws a message event's lookups exactly as the server draws
+// them on /ask: two lookups, a link in an answer, a multibyte title.
+func TestAskLookupMatchesServer(t *testing.T) {
+ order := []string{"Here it is.", "Both of them.", ""}
+ rig := sayLookups(t, map[string][]equipo.Lookup{
+ "Here it is.": {{Answer: "**Rain** later, see [Met](https://met.test/x) & <b>more</b>.",
+ Sources: []equipo.Source{{URL: "https://www.met.test/dublin?d=1&e=2", Title: "Met Éireann · 日本 😀"}, {URL: "https://b.test/"}}}},
+ "Both of them.": {
+ {Answer: "First:\n- one\n- *two*", Sources: []equipo.Source{{URL: "https://one.test/a", Title: "One"}}},
+ {Answer: "Second, https://two.test/x.", Sources: []equipo.Source{{URL: "https://two.test/", Title: "Two"}}},
+ },
+ "": {{Answer: "Only an answer.", Sources: []equipo.Source{{URL: "https://three.test/", Title: "Three"}}}},
+ }, order)
+ if got := harness.Evaluate[string](rig, sameAsServer, chromedp.EvalAwaitPromise); got != "" {
+ t.Errorf("the script and the server draw lookups differently:\n%s", got)
+ }
+ if n := harness.Evaluate[int](rig, `document.querySelectorAll("#ask-panel .lookup").length`); n != 4 {
+ t.Errorf("%d lookups drawn, want 4", n)
+ }
+ rig.Screen("#ask-panel", "a reply with lookups and their sources")
+ if dir := os.Getenv("BASE_BROWSER_ARTIFACTS"); dir != "" {
+ var png []byte
+ drive(t, rig, chromedp.Func(func(ctx context.Context, target *chromedp.Target) error {
+ var err error
+ png, err = chromedp.FullScreenshot(100)(ctx, target)
+ return err
+ }))
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(dir, "ask-lookups.png"), png, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ }
+}
+
+// Every source opens in a new tab, and tells the page nothing of Base.
+func TestAskLookupSourcesNewTab(t *testing.T) {
+ rig := sayLookups(t, map[string][]equipo.Lookup{"Here.": {{Answer: "Sunny.",
+ Sources: []equipo.Source{{URL: "https://met.test/", Title: "Met"}, {URL: "https://b.test/", Title: "B"}}}}}, []string{"Here."})
+ got := harness.Evaluate[string](rig, `[...document.querySelectorAll("#ask-panel .lookup-sources a")]
+ .map(a => a.target + " " + a.rel + " " + a.href).join("\n")`)
+ if want := "_blank noopener noreferrer nofollow https://met.test/\n_blank noopener noreferrer nofollow https://b.test/"; got != want {
+ t.Errorf("sources:\n%s\nwant\n%s", got, want)
+ }
+}
+
+// An answer's links, bare URLs, autolinks and markup are text; the
+// sources are still links.
+func TestAskLookupMarkdownNoLinks(t *testing.T) {
+ rig := sayLookups(t, map[string][]equipo.Lookup{"Look.": {{
+ Answer: "- [Click](https://evil.test/a)\n- https://evil.test/b\n- <https://evil.test/c>\n- <script>alert(1)</script><img src=x onerror=alert(1)>",
+ Sources: []equipo.Source{{URL: "https://good.test/", Title: "Good"}}}}}, []string{"Look."})
+ if n := harness.Evaluate[int](rig, `document.querySelectorAll("#ask-panel .lookup-answer a, #ask-panel .lookup-answer img, #ask-panel .lookup-answer script").length`); n != 0 {
+ t.Errorf("%d links or markup drawn in an answer", n)
+ }
+ if got := harness.Evaluate[string](rig, `[...document.querySelectorAll("#ask-panel .lookup-answer li")].map(l => l.textContent).join("|")`); got != "Click|https://evil.test/b|<https://evil.test/c>|<script>alert(1)</script><img src=x onerror=alert(1)>" {
+ t.Errorf("answer text %q", got)
+ }
+ if n := harness.Evaluate[int](rig, `document.querySelectorAll('#ask-panel .lookup-sources a[href="https://good.test/"]').length`); n != 1 {
+ t.Errorf("the source is not a link")
+ }
+ if got := harness.Evaluate[string](rig, sameAsServer, chromedp.EvalAwaitPromise); got != "" {
+ t.Errorf("the script and the server draw differently:\n%s", got)
+ }
+}
diff --git a/internal/equipo/equipotest/chat.go b/internal/equipo/equipotest/chat.go
index 51ad915..700733a 100644
--- a/internal/equipo/equipotest/chat.go
+++ b/internal/equipo/equipotest/chat.go
@@ -395,6 +395,17 @@ func (f *Fake) Say(text string) {
f.emit("message", "message", m.ID, 1, "", m)
}
+// SayWithLookups adds an Assistant line with lookups on it, as a reply
+// that looked things up has (ReplyWithLookups, without a turn).
+func (f *Fake) SayWithLookups(text string, lookups ...equipo.Lookup) {
+ f.cmu.Lock()
+ defer f.cmu.Unlock()
+ m := message{ID: f.next("m"), Revision: 1, Role: "assistant", Text: text, CreatedAt: time.Now().UTC(),
+ Lookups: append([]equipo.Lookup(nil), lookups...)}
+ f.messages = append(f.messages, m)
+ f.emit("message", "message", m.ID, 1, "", m)
+}
+
// LastTurn is the id of the newest turn ("" when there is none).
func (f *Fake) LastTurn() string {
f.cmu.Lock()
diff --git a/internal/look/static/app.css b/internal/look/static/app.css
index 39e6c0f..4c126a8 100644
--- a/internal/look/static/app.css
+++ b/internal/look/static/app.css
@@ -572,6 +572,7 @@ aside.ask-panel { position: absolute; top: 16px; right: 16px; bottom: 16px; widt
/* A lookup under the Assistant's words (ask-lookup): the answer, then a
quiet Sources line, each source's title a link with its host after it. */
.msg .lookup { margin-top: 10px; }
+.msg .lookup:first-child { margin-top: 0; }
.msg .lookup-answer { margin: 0; }
.msg .lookup-sources { margin: 6px 0 0; display: flex; flex-wrap: wrap; gap: 2px 12px; white-space: normal; color: var(--haze); font-size: 13.5px; line-height: 1.4; }
.msg .lookup-label { font-weight: 500; }
diff --git a/internal/look/static/ask.js b/internal/look/static/ask.js
index 7863189..720b6a0 100644
--- a/internal/look/static/ask.js
+++ b/internal/look/static/ask.js
@@ -128,6 +128,8 @@ function start(root) {
// Assistant's (rich), with emphasis only at word boundaries
// (strictEmphasis).
rich(li, m.text, m.role === "person");
+ // What the Assistant looked up for its reply, after its words.
+ if (m.role !== "person") for (const l of m.lookups || []) li.append(lookupBox(l));
// A person's files sit above their words, drawn as chat.html draws them.
if (m.role === "person" && m.attachments && m.attachments.length) {
attachMod.then((mod) => { if (mod) li.prepend(mod.filesRow(m.attachments, mod.wordsOf(composer))); });
@@ -300,7 +302,7 @@ function start(root) {
}
// Line breaks are read as a page reads them (\r\n and \r are \n, and a
// NUL goes), so the server's HTML and this draw the same.
- function rich(el, text, strict = false) {
+ function rich(el, text, strict = false, links = true) {
el.replaceChildren();
const lines = text.replace(/\r\n?/g, "\n").replaceAll("\0", "").split("\n");
for (let i = 0; i < lines.length; ) {
@@ -308,7 +310,7 @@ function start(root) {
if (!first) {
let j = i + 1;
while (j < lines.length && !listLine(lines[j])) j++;
- inline(el, lines.slice(i, j).join("\n"), strict);
+ inline(el, lines.slice(i, j).join("\n"), strict, links);
i = j;
continue;
}
@@ -316,15 +318,15 @@ function start(root) {
if (first.kind === "ol" && first.n !== 1) list.start = first.n;
for (let l; i < lines.length && (l = listLine(lines[i])) && l.kind === first.kind; i++) {
const li = document.createElement("li");
- inline(li, l.item, strict);
+ inline(li, l.item, strict, links);
list.append(li);
}
el.append(list);
}
}
// inline appends text with its safe links, and bold and italics between
- // them.
- function inline(el, text, strict) {
+ // them. Without links, each address is text, untouched by emphasis.
+ function inline(el, text, strict, links = true) {
const emphasis = strict ? strictEmphasis : looseEmphasis;
let last = 0;
for (const m of text.matchAll(linkRE)) {
@@ -337,6 +339,11 @@ function start(root) {
const href = webURL(target);
if (!href) continue;
emphasis(el, text.slice(last, m.index));
+ if (!links) {
+ el.append(text.slice(m.index, end));
+ last = end;
+ continue;
+ }
el.append(link(href, label));
last = end;
}
@@ -406,6 +413,59 @@ function start(root) {
}
if (text.length > last) el.append(text.slice(last));
}
+ // A lookup's answer: the person's Markdown (lists, and bold and italics
+ // at word boundaries) with no links at all; a Markdown link shows as its
+ // words, a bare URL or an autolink as text (lookupMarkdown in
+ // ask_cards.go, and the app's LookupMarkdown).
+ const mdLinkRE = /\[([^\[\]\n]{1,300})\]\(([^()\s]{1,1000})\)/g;
+ function lookupMarkdown(el, text) {
+ rich(el, text.replace(/\r\n?/g, "\n").replaceAll("\0", "").replace(mdLinkRE, "$1"), true, false);
+ }
+ // sourceHost is a source's host as its line shows it, without "www."
+ // (sourceHost in ask_cards.go).
+ function sourceHost(u) {
+ try {
+ return new URL(u).hostname.toLowerCase().replace(/^www\./, "");
+ } catch {
+ return "";
+ }
+ }
+ // A lookup under the Assistant's reply, as the ask-lookup template draws
+ // it: the answer, then the quiet Sources line (ask.sources, copy review
+ // 14), each source's title a link opening in a new tab and its host
+ // after it.
+ function lookupBox(l) {
+ const box = document.createElement("div");
+ box.className = "lookup";
+ const answer = document.createElement("div");
+ answer.className = "lookup-answer";
+ lookupMarkdown(answer, String(l.answer || ""));
+ const line = document.createElement("p");
+ line.className = "lookup-sources";
+ const label = document.createElement("span");
+ label.className = "lookup-label";
+ label.textContent = "Sources";
+ line.append(label);
+ for (const s of l.sources || []) {
+ const href = webURL(s.url);
+ if (!href || !href.startsWith("https:")) continue;
+ const host = sourceHost(s.url);
+ const one = document.createElement("span");
+ one.className = "source";
+ const a = document.createElement("a");
+ a.href = s.url;
+ a.target = "_blank";
+ a.rel = "noopener noreferrer nofollow";
+ a.textContent = s.title || host;
+ const h = document.createElement("span");
+ h.className = "source-host";
+ h.textContent = host;
+ one.append(a, h);
+ line.append(one);
+ }
+ box.append(answer, line);
+ return box;
+ }
const space = (c) => c === " " || c === "\t";
const emphasized = (x) => x !== "" && !x.includes("\n") && !space(x[0]) && !space(x[x.length - 1]);
// A word's code unit: an ASCII letter, digit or _, or anything beyond