oficina / base Public

Native: draw lookup answers and say so to Base

Base folds a message's lookups into its text on /ask/state and
/ask/events for a native app that didn't say it draws them, whatever
Equipo sent. Base records what an app draws on those two reads only,
from Base-Client-Capabilities or the client_caps query parameter: the
native kit (rastrillo/native NativeHTTP) sets no header of its own.

The app decodes message.lookups (https sources only), draws each answer
with LookupMarkdown (no links) and a Sources line, and its production
transport adds client_caps=lookup_answers to the two reads. Shared
samples in internal/web/testdata/lookup.json pin server and app alike.
The Swift half is untested here: it needs a Mac with Xcode.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 29999ed6c1435de2157322bd2e69982528016aaf parent c40029c
16 files changed, +429 −25
  • docs/api/base-native-v1.md +21 −6
  • internal/equipo/equipotest/chat.go +7 −4
  • internal/equipo/equipotest/fake.go +4 −0
  • internal/web/ask.go +3 −0
  • internal/web/ask_caps.go +36 −7
  • internal/web/ask_relay.go +8 −3
  • internal/web/rich_internal_test.go +18 −0
  • internal/web/testdata/lookup.json +26 −0
  • internal/webtest/ask_caps_test.go +18 −0
  • internal/webtest/ask_lookup_test.go +38 −0
  • native/apple/Sources/BaseKit/API/Models.swift +46 −2
  • native/apple/Sources/BaseKit/Ask/Markdown/PersonMarkdown.swift +25 −2
  • native/apple/Sources/BaseKit/Ask/Thread.swift +43 −0
  • native/apple/Sources/BaseKit/Resources/Localizable.xcstrings +12 −0
  • native/apple/Sources/BaseKit/Session/BaseSession.swift +31 −1
  • native/apple/Tests/BaseKitTests/LookupTests.swift +93 −0
diff --git a/docs/api/base-native-v1.md b/docs/api/base-native-v1.md
index 279c03a..dbdf38d 100644
--- a/docs/api/base-native-v1.md
+++ b/docs/api/base-native-v1.md
@@ -94,11 +94,14 @@ for a form). Every answer is `no-store`.
### What the app can draw
-Every `/ask/*` request may send `Base-Client-Capabilities`, a
-comma-separated list of what this build of the app draws. Base keeps the
-newest list per app session, and tells the Assistant a feature is drawn
-only while every app the member used in the last 30 days last said so.
-An app that doesn't send a value keeps what it gets today.
+`GET /ask/state` and `GET /ask/events` may say what this build of the app
+draws: a comma-separated list, as the header `Base-Client-Capabilities`
+or as the query parameter `client_caps` (the kit's `NativeHTTP` sets no
+header of its own, so the app sends the parameter). Base keeps the newest
+list per app session, from these two reads only, and tells the Assistant
+a feature is drawn only while every app the member used in the last 30
+days last said so. An app that says nothing keeps what it gets today:
+its reads carry each message's lookups folded into its `text`.
| value | what the app draws |
|---|---|
@@ -151,13 +154,25 @@ An app that doesn't send a value keeps what it gets today.
runner can take files. Offer attaching only then; an older Equipo never
says so.
-**Message** `{"id", "role": "person"|"assistant", "text", "turn_id", "created_at", "attachments"?}`.
+**Message** `{"id", "role": "person"|"assistant", "text", "turn_id", "created_at", "attachments"?, "lookups"?}`.
An assistant's `text` may carry the little Markdown `ask.js` draws (lists,
links to http(s) only, bold and italics). `attachments` is there only on a
person's message with files, in the order they were attached; its `text`
may then be `""`. Until the app draws files, show their names as a line
under the text, so a bubble is never empty.
+`lookups` is there only on an assistant's message that looked
+something up, and only for an app that says it draws them (above), at
+most 2, in the order they were made.
+
+**Lookup** `{"answer", "sources": [{"url", "title"}]}`. Draw each after
+the message's own words: the answer in the little Markdown above but with
+**no links at all** (a Markdown link shows as its words, a bare URL as
+text), then a quiet "Sources" line with each source's `title` as a link
+(an `https` address, opening in the browser) and its host after it, without
+`www.`. An empty `title` shows the host. The answer is at most 1,200
+characters, a title at most 120, and there are at most 5 sources.
+
**Attachment** `{"id", "kind": "image"|"file", "name", "media_type", "size", "width", "height"}`.
`size` is in bytes; `width` and `height` are an image's upright size, `0`
for a file. Treat any other `kind` as `file`. Read it from Base, never from
diff --git a/internal/equipo/equipotest/chat.go b/internal/equipo/equipotest/chat.go
index 700733a..6f031a4 100644
--- a/internal/equipo/equipotest/chat.go
+++ b/internal/equipo/equipotest/chat.go
@@ -39,7 +39,10 @@ type message struct {
// drawsLookups reports whether r says Base draws lookup answers
// (Base-Capabilities), as Equipo reads it.
-func drawsLookups(r *http.Request) bool {
+func (f *Fake) drawsLookups(r *http.Request) bool {
+ if f.LookupsRegardless {
+ return true
+ }
for _, v := range r.Header.Values(equipo.CapabilitiesHeader) {
for _, c := range strings.Split(v, ",") {
if strings.TrimSpace(c) == equipo.CapLookupAnswers {
@@ -454,7 +457,7 @@ func (f *Fake) serveChat(w http.ResponseWriter, r *http.Request) {
f.snapshot(w, r)
case r.Method == http.MethodGet && p == "/messages":
f.cmu.Lock()
- writeJSON(w, 200, map[string]any{"items": read(f.tail(), drawsLookups(r)), "before": ""})
+ writeJSON(w, 200, map[string]any{"items": read(f.tail(), f.drawsLookups(r)), "before": ""})
f.cmu.Unlock()
case r.Method == http.MethodPost && p == "/messages":
f.send(w, r, d.id)
@@ -509,7 +512,7 @@ func (f *Fake) snapshot(w http.ResponseWriter, r *http.Request) {
writeJSON(w, 200, map[string]any{
"me": map[string]any{"id": f.address, "address": f.address, "role": "owner",
"person": map[string]any{"name": "Paul"}, "team_id": f.Instance, "team_name": "Tito"},
- "messages": read(f.tail(), drawsLookups(r)), "turns": turns, "cards": cards, "cursor": f.cursor,
+ "messages": read(f.tail(), f.drawsLookups(r)), "turns": turns, "cards": cards, "cursor": f.cursor,
"available": f.runner == "", "can_attach": f.canAttach(),
})
}
@@ -1009,7 +1012,7 @@ func (f *Fake) stream(w http.ResponseWriter, r *http.Request) {
}
after = n
}
- paused, draws := pausedOK(r), drawsLookups(r)
+ paused, draws := pausedOK(r), f.drawsLookups(r)
rc := http.NewResponseController(w)
w.Header().Set("Content-Type", "text/event-stream")
w.WriteHeader(200)
diff --git a/internal/equipo/equipotest/fake.go b/internal/equipo/equipotest/fake.go
index de46c00..95467eb 100644
--- a/internal/equipo/equipotest/fake.go
+++ b/internal/equipo/equipotest/fake.go
@@ -52,6 +52,10 @@ type Fake struct {
// new turn running until Answer, so a test can cancel one.
Reply func(text string) string
Hold bool
+ // LookupsRegardless sends lookups to every read, whatever
+ // Base-Capabilities says, so a test can see what Base itself does
+ // with them.
+ LookupsRegardless bool
srv *httptest.Server
closing chan struct{}
diff --git a/internal/web/ask.go b/internal/web/ask.go
index d8070c8..8629575 100644
--- a/internal/web/ask.go
+++ b/internal/web/ask.go
@@ -608,6 +608,9 @@ func (a *app) askStateJSON(w http.ResponseWriter, r *http.Request) {
}
// RenewAfter is when the native app should set Ask up again with a
// fresh Oficina ID assertion: "" for a key from the code flow.
+ for i, m := range v.Messages {
+ v.Messages[i] = asDrawn(r, m)
+ }
renew := ""
if at := renewAfter(l, sec); !at.IsZero() && state != askConnect {
renew = at.Format(time.RFC3339)
diff --git a/internal/web/ask_caps.go b/internal/web/ask_caps.go
index ecc3480..c13bada 100644
--- a/internal/web/ask_caps.go
+++ b/internal/web/ask_caps.go
@@ -14,9 +14,14 @@ import (
"amadan.net/oficina/base/internal/store"
)
-// clientCapsHeader is what Base's native app says it can draw, on each of
-// its /ask/* requests (docs/api/base-native-v1.md).
-const clientCapsHeader = "Base-Client-Capabilities"
+// clientCapsHeader is what Base's native app says it can draw, on its
+// /ask/* reads (docs/api/base-native-v1.md); clientCapsParam is the same
+// list as a query parameter, for an app whose HTTP kit sets no header of
+// its own (rastrillo/native's NativeHTTP).
+const (
+ clientCapsHeader = "Base-Client-Capabilities"
+ clientCapsParam = "client_caps"
+)
// clientWindow is how long a native client's last word counts: one not
// seen for longer no longer holds a capability back.
@@ -31,7 +36,7 @@ func clientCaps(r *http.Request) (native bool, caps []string) {
return false, nil
}
said := map[string]bool{}
- for _, v := range r.Header.Values(clientCapsHeader) {
+ for _, v := range append(r.Header.Values(clientCapsHeader), r.URL.Query()[clientCapsParam]...) {
for _, c := range strings.Split(v, ",") {
said[strings.TrimSpace(c)] = true
}
@@ -66,8 +71,15 @@ func (a *app) askCaps(ctx context.Context, member int64) []string {
return out
}
-// withAskCaps records what a native /ask/* request says its app can draw
-// (web sessions are not recorded), then puts the member's capabilities
+// recordsClient reports whether r is one of the two reads on which an
+// app says what it can draw: every app reads /ask/state and opens
+// /ask/events, and only these answers carry lookups.
+func recordsClient(r *http.Request) bool {
+ return r.Method == http.MethodGet && (r.URL.Path == "/ask/state" || r.URL.Path == "/ask/events")
+}
+
+// withAskCaps records what a native app's /ask/state or /ask/events read
+// says it can draw (web sessions are not recorded), then puts the member's capabilities
// (askCaps) on the request's context, so every Equipo call made for it
// carries Base-Capabilities. It runs behind the member gate.
func (a *app) withAskCaps(next http.Handler) http.Handler {
@@ -85,7 +97,7 @@ func (a *app) withAskCaps(next http.Handler) http.Handler {
return
}
recorded := true
- if native, said := clientCaps(r); native && strings.HasPrefix(r.URL.Path, "/ask/") {
+ if native, said := clientCaps(r); native && recordsClient(r) {
c, err := r.Cookie(a.sess.CookieName())
if err == nil {
err = store.SeeAskClient(ctx, a.db, n, sessions.HashToken(c.Value), strings.Join(said, ","))
@@ -104,3 +116,20 @@ func (a *app) withAskCaps(next http.Handler) http.Handler {
next.ServeHTTP(w, r.WithContext(equipo.WithCapabilities(ctx, caps)))
})
}
+
+// plainLookups reports whether r is the native app's and didn't say it
+// draws lookups: its /ask/* answers then carry each message's lookups
+// folded into its text (equipo.Message.PlainLookups), whatever Equipo
+// sent.
+func plainLookups(r *http.Request) bool {
+ native, caps := clientCaps(r)
+ return native && !slices.Contains(caps, equipo.CapLookupAnswers)
+}
+
+// asDrawn is m as client r draws it (plainLookups).
+func asDrawn(r *http.Request, m equipo.Message) equipo.Message {
+ if plainLookups(r) {
+ return m.PlainLookups()
+ }
+ return m
+}
diff --git a/internal/web/ask_relay.go b/internal/web/ask_relay.go
index 70aa709..855bb1d 100644
--- a/internal/web/ask_relay.go
+++ b/internal/web/ask_relay.go
@@ -271,7 +271,7 @@ func (a *app) askEvents(w http.ResponseWriter, r *http.Request) {
if down.send("retry: 3000\n\n") != nil {
return
}
- seen.base = a.cfg.Origin
+ seen.base, seen.plain = a.cfg.Origin, plainLookups(r)
relay(down, res.Body, streamIdle, cancel, seen)
}
@@ -432,6 +432,9 @@ func (e sseEvent) frame(seen *turnsSeen) string {
} else {
data, ok = project(e.typ, env.Data, seen.base)
}
+ if m, msg := data.(equipo.Message); msg && seen.plain {
+ data = m.PlainLookups()
+ }
if c, card := data.(equipo.Card); card {
// A connect card waits for the reply of the turn that raised it.
data = c.WithTurn(env.TurnID)
@@ -515,8 +518,10 @@ const maxGlance = 60
// no glance for a turn it does not know.
type turnsSeen struct {
live, past map[string]bool
- // base is Base's origin, for Card.CleanAt.
- base string
+ // base is Base's origin, for Card.CleanAt; plain says the client
+ // can't draw lookups, so a message's are folded into its text.
+ base string
+ plain bool
}
// seedTurns is what the snapshot s says of its turns.
diff --git a/internal/web/rich_internal_test.go b/internal/web/rich_internal_test.go
index e7b1cbb..3f0424a 100644
--- a/internal/web/rich_internal_test.go
+++ b/internal/web/rich_internal_test.go
@@ -91,3 +91,21 @@ func TestPersonText(t *testing.T) {
t.Errorf("richText changed: %s", got)
}
}
+
+// A lookup's answer: the person's Markdown with no links at all. The
+// samples are the app's too (testLookupMarkdownNoLinks).
+func TestLookupMarkdown(t *testing.T) {
+ raw, err := os.ReadFile("testdata/lookup.json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var cases []struct{ Text, HTML string }
+ if err := json.Unmarshal(raw, &cases); err != nil {
+ t.Fatal(err)
+ }
+ for _, c := range cases {
+ if got := string(lookupMarkdown(c.Text)); got != c.HTML {
+ t.Errorf("lookupMarkdown(%q)\n got %s\nwant %s", c.Text, got, c.HTML)
+ }
+ }
+}
diff --git a/internal/web/testdata/lookup.json b/internal/web/testdata/lookup.json
new file mode 100644
index 0000000..ad1a384
--- /dev/null
+++ b/internal/web/testdata/lookup.json
@@ -0,0 +1,26 @@
+[
+ {
+ "text": "**Rain** later, see [Met](https://met.test/x) & <b>more</b>.",
+ "html": "<strong>Rain</strong> later, see Met &amp; &lt;b&gt;more&lt;/b&gt;."
+ },
+ {
+ "text": "- [Click](https://evil.test/a)\n- https://evil.test/b\n- <https://evil.test/c>\n- <script>alert(1)</script>",
+ "html": "<ul><li>Click</li><li>https://evil.test/b</li><li>&lt;https://evil.test/c&gt;</li><li>&lt;script&gt;alert(1)&lt;/script&gt;</li></ul>"
+ },
+ {
+ "text": "See https://a.test/_x_ and *it*.",
+ "html": "See https://a.test/_x_ and <em>it</em>."
+ },
+ {
+ "text": "[x](javascript:alert(1)) and 2*3*4",
+ "html": "[x](javascript:alert(1)) and 2*3*4"
+ },
+ {
+ "text": "Opens at 10:00, *Saturday*\r\n1. One\n2. Two",
+ "html": "Opens at 10:00, <em>Saturday</em><ol><li>One</li><li>Two</li></ol>"
+ },
+ {
+ "text": "[*it*](https://b.test/?q=1&r=2) \"quoted\" it's",
+ "html": "<em>it</em> &#34;quoted&#34; it&#39;s"
+ }
+]
diff --git a/internal/webtest/ask_caps_test.go b/internal/webtest/ask_caps_test.go
index 427193b..d7d17cf 100644
--- a/internal/webtest/ask_caps_test.go
+++ b/internal/webtest/ask_caps_test.go
@@ -71,9 +71,27 @@ func TestAskCapsWithheldForOldNative(t *testing.T) {
web.get("/ask")
want("the web, once the app is upgraded", true)
+ // A write says nothing of what the app draws: it changes nothing.
+ bare := *app
+ bare.header = nil
+ if r := bare.nativeForm("/ask/messages", url.Values{"text": {"Hi"}, "key": {"caps-w"}}); r.Code != 200 {
+ t.Fatalf("send: %d %s", r.Code, r.Body)
+ }
+ web.get("/ask")
+ want("the web, after the upgraded app wrote", true)
+
app.header = nil
app.askState()
want("the app, downgraded", false)
+
+ // The app's kit sets no header of its own: the same list as a query
+ // parameter counts alike.
+ if r := app.nativeGet("/ask/state?client_caps=" + equipo.CapLookupAnswers); r.Code != 200 {
+ t.Fatalf("/ask/state: %d", r.Code)
+ }
+ want("the app, saying so in the query", true)
+ app.askState()
+ want("the app, downgraded again", false)
if _, err := web.DB.Exec(`UPDATE ask_clients SET seen_at = ?`, time.Now().Add(-31*24*time.Hour).UTC()); err != nil {
t.Fatal(err)
}
diff --git a/internal/webtest/ask_lookup_test.go b/internal/webtest/ask_lookup_test.go
index 1e1af6e..26b9498 100644
--- a/internal/webtest/ask_lookup_test.go
+++ b/internal/webtest/ask_lookup_test.go
@@ -134,3 +134,41 @@ func TestLookupInState(t *testing.T) {
t.Errorf("lookups %+v", l)
}
}
+
+// A native app that doesn't say it draws lookups gets them folded into
+// the reply's text, from /ask/state and /ask/events, even should Equipo
+// send them; an app that says it does gets them as they are.
+func TestNativeWithoutClientHeaderGetsPlainLookups(t *testing.T) {
+ web, app, f := newNativeAskApp(t)
+ web.approveEquipo(f)
+ f.LookupsRegardless = true
+ lookup := equipo.Lookup{Answer: "Rain later.", Sources: []equipo.Source{{URL: "https://met.test/dublin", Title: "Met"}}}
+ s, _ := app.askState()
+ f.SayWithLookups("Here it is.", lookup)
+ plain := equipo.Message{Role: "assistant", Text: "Here it is.", Lookups: []equipo.Lookup{lookup}}.PlainLookups().Text
+ check := func(where, raw string, drawn bool) {
+ t.Helper()
+ var m equipo.Message
+ if err := json.Unmarshal([]byte(raw), &m); err != nil {
+ t.Fatalf("%s: %s", where, raw)
+ }
+ if drawn && (m.Text != "Here it is." || len(m.Lookups) != 1) || !drawn && (m.Text != plain || m.Lookups != nil || strings.Contains(raw, "lookups")) {
+ t.Errorf("%s (drawn %v): %s", where, drawn, raw)
+ }
+ }
+ for _, drawn := range []bool{false, true} {
+ if drawn {
+ app.header = http.Header{"Base-Client-Capabilities": {equipo.CapLookupAnswers}}
+ }
+ after, _ := app.askState()
+ check("state", string(after.Messages[len(after.Messages)-1]), drawn)
+ frames := app.events(t, strconv64(s.Cursor), func(got []sseFrame) bool {
+ return len(got) > 0 && got[len(got)-1].Event == "message"
+ })
+ var ev struct {
+ Data json.RawMessage `json:"data"`
+ }
+ _ = json.Unmarshal([]byte(frames[len(frames)-1].Data), &ev)
+ check("event", string(ev.Data), drawn)
+ }
+}
diff --git a/native/apple/Sources/BaseKit/API/Models.swift b/native/apple/Sources/BaseKit/API/Models.swift
index 66c549a..9e601bb 100644
--- a/native/apple/Sources/BaseKit/API/Models.swift
+++ b/native/apple/Sources/BaseKit/API/Models.swift
@@ -166,19 +166,63 @@ public struct AskMessage: Decodable, Sendable, Equatable, Identifiable {
public var createdAt: Date?
/// The files the person sent with it, in order (none for most).
public var attachments: [AskAttachment]
+ /// What the Assistant looked up on the web for its reply, in the order
+ /// it did, drawn under its words (none on a person's message).
+ public var lookups: [AskLookup]
public var isPerson: Bool { role == "person" }
- public init(id: String, role: String, text: String, turnID: String = "", createdAt: Date? = nil, attachments: [AskAttachment] = []) {
+ public init(id: String, role: String, text: String, turnID: String = "", createdAt: Date? = nil, attachments: [AskAttachment] = [],
+ lookups: [AskLookup] = []) {
self.id = id; self.role = role; self.text = text; self.turnID = turnID; self.createdAt = createdAt; self.attachments = attachments
+ self.lookups = lookups
}
- enum CodingKeys: String, CodingKey { case id, role, text, turnID = "turn_id", createdAt = "created_at", attachments }
+ enum CodingKeys: String, CodingKey { case id, role, text, turnID = "turn_id", createdAt = "created_at", attachments, lookups }
public init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
id = c.value(.id, ""); role = c.value(.role, ""); text = c.value(.text, "")
turnID = c.value(.turnID, ""); createdAt = c.date(.createdAt)
attachments = c.value(.attachments, [AskAttachment]()).filter { !$0.id.isEmpty }
+ lookups = role == "person" ? [] : c.value(.lookups, [AskLookup]()).filter { !$0.answer.isEmpty && !$0.sources.isEmpty }
}
}
+/// One thing the Assistant looked up for a reply (docs/api/base-native-v1.md,
+/// Lookup): a short answer, drawn with LookupMarkdown (never a link), and
+/// the pages it came from, each drawn as its title (a link) and its host.
+public struct AskLookup: Decodable, Sendable, Equatable {
+ public var answer: String
+ public var sources: [AskSource]
+ public init(answer: String, sources: [AskSource]) { self.answer = answer; self.sources = sources }
+ enum CodingKeys: String, CodingKey { case answer, sources }
+ public init(from decoder: Decoder) throws {
+ let c = try decoder.container(keyedBy: CodingKeys.self)
+ answer = c.value(.answer, "")
+ sources = c.value(.sources, [AskSource]()).filter { $0.url != nil }
+ }
+}
+
+/// A page a lookup's answer came from: https only (anything else has no
+/// url, and is dropped).
+public struct AskSource: Decodable, Sendable, Equatable {
+ public var url: URL?
+ public var title: String
+ public init(url: URL?, title: String) { self.url = url; self.title = title }
+ enum CodingKeys: String, CodingKey { case url, title }
+ public init(from decoder: Decoder) throws {
+ let c = try decoder.container(keyedBy: CodingKeys.self)
+ let u = c.webURL(.url)
+ url = u?.scheme == "https" ? u : nil
+ title = c.value(.title, "")
+ }
+ /// The host as the Sources line shows it, without "www." (sourceHost
+ /// in ask_cards.go).
+ public var host: String {
+ let h = (url?.host ?? "").lowercased()
+ return h.hasPrefix("www.") ? String(h.dropFirst(4)) : h
+ }
+ /// What the link says: the title, or the host without one.
+ public var label: String { title.isEmpty ? host : title }
+}
+
/// One of a message's files (docs/api/base-native-v1.md, Attachment).
/// Until the app draws files (slice 2), only its name shows. A kind the
/// app doesn't know is a file.
diff --git a/native/apple/Sources/BaseKit/Ask/Markdown/PersonMarkdown.swift b/native/apple/Sources/BaseKit/Ask/Markdown/PersonMarkdown.swift
index e9db975..0b9bc33 100644
--- a/native/apple/Sources/BaseKit/Ask/Markdown/PersonMarkdown.swift
+++ b/native/apple/Sources/BaseKit/Ask/Markdown/PersonMarkdown.swift
@@ -12,8 +12,9 @@ import Foundation
/// entities and indented code are text as typed. The samples in
/// internal/web/testdata/person.json check the three agree.
enum PersonMarkdown {
- static func parse(_ text: String) -> [ChatMarkdownNode] {
- var builder = Builder()
+ /// `links: false` draws every address as text (LookupMarkdown).
+ static func parse(_ text: String, links: Bool = true) -> [ChatMarkdownNode] {
+ var builder = Builder(links: links)
let lines = text.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n")
.replacingOccurrences(of: "\0", with: "").components(separatedBy: "\n")
var out: [ChatMarkdownNode] = []
@@ -64,6 +65,7 @@ enum PersonMarkdown {
private static let link = try! NSRegularExpression(pattern: #"\[([^\[\]\n]{1,300})\]\(([^()\s]{1,1000})\)|https?://[^\s<>()\[\]"']+"#)
private struct Builder {
+ let links: Bool
var offset = 0
/// Every node its own offset: the rows are told apart by it.
mutating func node(_ kind: String, text: String? = nil, target: String? = nil, children: [ChatMarkdownNode] = []) -> ChatMarkdownNode {
@@ -86,6 +88,12 @@ enum PersonMarkdown {
}
guard ChatMarkdown.allowsLink(target) else { continue }
out += emphasis(ns.substring(with: NSRange(location: last, length: m.range.location - last)))
+ guard links else {
+ // An address as text, untouched by emphasis.
+ out.append(node("text", text: ns.substring(with: NSRange(location: m.range.location, length: end - m.range.location))))
+ last = end
+ continue
+ }
out.append(node("link", target: target, children: [node("text", text: label)]))
last = end
}
@@ -125,3 +133,18 @@ enum PersonMarkdown {
}
}
}
+
+/// Base: a lookup's answer as the chat's Markdown tree: PersonMarkdown's
+/// subset with no links at all (lookupMarkdown in ask_cards.go and
+/// ask.js). A Markdown link shows as its words; a bare URL or an autolink
+/// stays as text. The only links under a reply are its sources.
+enum LookupMarkdown {
+ private static let markdownLink = try! NSRegularExpression(pattern: #"\[([^\[\]\n]{1,300})\]\(([^()\s]{1,1000})\)"#)
+
+ static func parse(_ text: String) -> [ChatMarkdownNode] {
+ let t = text.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n")
+ .replacingOccurrences(of: "\0", with: "")
+ let words = markdownLink.stringByReplacingMatches(in: t, range: NSRange(t.startIndex..., in: t), withTemplate: "$1")
+ return PersonMarkdown.parse(words, links: false)
+ }
+}
diff --git a/native/apple/Sources/BaseKit/Ask/Thread.swift b/native/apple/Sources/BaseKit/Ask/Thread.swift
index 3e6f62d..cd84f51 100644
--- a/native/apple/Sources/BaseKit/Ask/Thread.swift
+++ b/native/apple/Sources/BaseKit/Ask/Thread.swift
@@ -100,6 +100,10 @@ struct AskThread: View {
} else {
BaseMarkdownView(m.text, draft: false, id: m.id, transcript: transcript)
}
+ // What the Assistant looked up, after its words.
+ ForEach(Array(m.lookups.enumerated()), id: \.offset) { i, lookup in
+ LookupView(lookup: lookup, id: m.id + ":lookup:\(i)", transcript: transcript)
+ }
if let names = parts.names {
FilesLine(names: names)
}
@@ -160,6 +164,45 @@ struct FilesLine: View {
}
}
+/// A lookup under the Assistant's reply (chat.html `ask-lookup`): its
+/// answer (LookupMarkdown, never a link), then a quiet Sources line with
+/// each source's title as a link and its host after it.
+struct LookupView: View {
+ let lookup: AskLookup
+ let id: String
+ let transcript: MarkdownTranscript
+ @Environment(\.colorScheme) private var scheme
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 6) {
+ BaseMarkdownView(person: LookupMarkdown.parse(lookup.answer), id: id, transcript: transcript)
+ Text(Self.sources(lookup.sources, label: BaseText.text("ask.sources"), palette: Palette(scheme)))
+ .font(BaseFont.body(13.5, relativeTo: .footnote))
+ .foregroundStyle(Palette(scheme)[.haze])
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ .padding(.top, 6)
+ }
+
+ /// The Sources line: the label, then each source's title (a link,
+ /// opening in the browser) and its host.
+ static func sources(_ sources: [AskSource], label: String, palette p: Palette) -> AttributedString {
+ var line = AttributedString(label)
+ line.font = BaseFont.body(13.5, .medium, relativeTo: .footnote)
+ for s in sources {
+ guard let url = s.url else { continue }
+ var title = AttributedString(s.label)
+ title.link = url
+ title.foregroundColor = p[.focus]
+ title.underlineStyle = .single
+ var host = AttributedString(" " + s.host)
+ host.font = BaseFont.body(12.5, relativeTo: .footnote)
+ line += AttributedString(" ") + title + host
+ }
+ return line
+ }
+}
+
/// A line of the conversation: the person's on the right in teal, the
/// Assistant's on the left, each with one tucked corner (app.css `.msg`).
struct Bubble<Content: View>: View {
diff --git a/native/apple/Sources/BaseKit/Resources/Localizable.xcstrings b/native/apple/Sources/BaseKit/Resources/Localizable.xcstrings
index 3af3278..0dce4ff 100644
--- a/native/apple/Sources/BaseKit/Resources/Localizable.xcstrings
+++ b/native/apple/Sources/BaseKit/Resources/Localizable.xcstrings
@@ -265,6 +265,18 @@
}
}
},
+ "ask.sources": {
+ "comment": "Copy review 14 (approved, Paul, 2026-11-28, mi3kgi7nubnsf7kxn235tqwrbu). The quiet line under a lookup's answer, before each source's title (a link) and host (chat.html, ask-lookup).",
+ "extractionState": "manual",
+ "localizations": {
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Sources"
+ }
+ }
+ }
+ },
"ask.stop": {
"comment": "Base on the web's approved copy. The composer's Stop button, a square, while a turn runs (chat.html).",
"extractionState": "manual",
diff --git a/native/apple/Sources/BaseKit/Session/BaseSession.swift b/native/apple/Sources/BaseKit/Session/BaseSession.swift
index 785bf8b..39a3778 100644
--- a/native/apple/Sources/BaseKit/Session/BaseSession.swift
+++ b/native/apple/Sources/BaseKit/Session/BaseSession.swift
@@ -64,7 +64,7 @@ import RastrilloApple
return
}
if let previous = account, previous.identity != state.identity.id { forgetDisconnectIfGone(previous.identity) }
- begin(identity: state.identity.id, origin: state.origin, transport: state.client(), state: state)
+ begin(identity: state.identity.id, origin: state.origin, transport: CapabilityTransport(state.client()), state: state)
}
/// Who the session is for: an identity at a Base. Anything that
@@ -303,3 +303,33 @@ final class SwappableTransport: NativeTransport, @unchecked Sendable {
try await current.download(path, to: destination)
}
}
+
+/// Says what this app draws on its Ask reads, `/ask/state` and
+/// `/ask/events` (docs/api/base-native-v1.md, "What the app can draw"):
+/// `client_caps=lookup_answers`, a query parameter, since the kit's
+/// NativeHTTP sets no header of its own. Base counts it as
+/// `Base-Client-Capabilities`. Every other request goes as it is.
+final class CapabilityTransport: NativeTransport, @unchecked Sendable {
+ /// What this build draws, comma-separated.
+ static let capabilities = "lookup_answers"
+ private let inner: NativeTransport
+ init(_ inner: NativeTransport) { self.inner = inner }
+
+ /// path with the capabilities added, if it is one of Ask's reads.
+ static func path(_ path: String) -> String {
+ let bare = path.split(separator: "?", maxSplits: 1).first.map(String.init) ?? path
+ guard bare == "/ask/state" || bare == "/ask/events" else { return path }
+ return path + (path.contains("?") ? "&" : "?") + "client_caps=" + capabilities
+ }
+
+ var origin: URL { inner.origin }
+ func responseDetails(_ path: String, method: String, body: Data?, contentType: String, maxBytes: Int) async throws -> NativeResponse {
+ try await inner.responseDetails(method == "GET" ? Self.path(path) : path, method: method, body: body, contentType: contentType, maxBytes: maxBytes)
+ }
+ func stream(_ path: String, onOpen: @Sendable () async throws -> Void, onLine: @Sendable (String) async throws -> Void) async throws {
+ try await inner.stream(Self.path(path), onOpen: onOpen, onLine: onLine)
+ }
+ func download(_ path: String, to destination: URL) async throws {
+ try await inner.download(path, to: destination)
+ }
+}
diff --git a/native/apple/Tests/BaseKitTests/LookupTests.swift b/native/apple/Tests/BaseKitTests/LookupTests.swift
new file mode 100644
index 0000000..f5a8090
--- /dev/null
+++ b/native/apple/Tests/BaseKitTests/LookupTests.swift
@@ -0,0 +1,93 @@
+@testable import BaseKit
+import Foundation
+import RastrilloApple
+import RastrilloTestSupport
+import SwiftUI
+import XCTest
+
+/// What the Assistant looked up for a reply (docs/api/base-native-v1.md,
+/// Lookup), drawn as the web draws it (chat.html `ask-lookup`).
+final class LookupTests: XCTestCase {
+ /// A reply's lookups decode with https sources only; one left without
+ /// a source, or without an answer, is dropped; a person's message has
+ /// none. The Sources line is the label, then each title (a link) and
+ /// its host.
+ func testLookupAnswerAndSources() throws {
+ let raw = #"""
+ {"id":"m1","role":"assistant","text":"Here it is.","turn_id":"t1","lookups":[
+ {"answer":"Rain later.","sources":[{"url":"https://www.met.test/dublin","title":"Met"},{"url":"http://plain.test/","title":"Plain"},
+ {"url":"javascript:alert(1)","title":"Bad"},{"url":"https://b.test/","title":""}]},
+ {"answer":"No sources.","sources":[{"url":"http://plain.test/","title":"Plain"}]},
+ {"answer":"","sources":[{"url":"https://c.test/","title":"C"}]}]}
+ """#
+ let m = try JSONDecoder().decode(AskMessage.self, from: Data(raw.utf8))
+ XCTAssertEqual(m.lookups.count, 1)
+ let l = try XCTUnwrap(m.lookups.first)
+ XCTAssertEqual(l.answer, "Rain later.")
+ XCTAssertEqual(l.sources.map { $0.url?.absoluteString }, ["https://www.met.test/dublin", "https://b.test/"])
+ XCTAssertEqual(l.sources.map(\.host), ["met.test", "b.test"])
+ XCTAssertEqual(l.sources.map(\.label), ["Met", "b.test"])
+
+ let person = try JSONDecoder().decode(AskMessage.self, from: Data(#"{"id":"m2","role":"person","text":"Hi","lookups":[{"answer":"x","sources":[{"url":"https://a.test/","title":"A"}]}]}"#.utf8))
+ XCTAssertEqual(person.lookups, [])
+ let none = try JSONDecoder().decode(AskMessage.self, from: Data(#"{"id":"m3","role":"assistant","text":"Hi"}"#.utf8))
+ XCTAssertEqual(none.lookups, [])
+
+ let line = LookupView.sources(l.sources, label: BaseText.text("ask.sources"), palette: Palette(.light))
+ XCTAssertEqual(String(line.characters), "Sources Met met.test b.test b.test")
+ let links = line.runs.compactMap(\.link)
+ XCTAssertEqual(links.map(\.absoluteString), ["https://www.met.test/dublin", "https://b.test/"])
+ XCTAssertEqual(BaseText.text("ask.sources"), "Sources")
+ }
+
+ /// The web's server draws each of these (TestLookupMarkdown): no link
+ /// at all, whatever the answer says.
+ func testLookupMarkdownNoLinks() throws {
+ struct Case: Decodable { let text: String; let html: String }
+ let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
+ .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
+ let cases = try JSONDecoder().decode([Case].self, from: Data(contentsOf: root.appendingPathComponent("internal/web/testdata/lookup.json")))
+ XCTAssertGreaterThan(cases.count, 4)
+ func escape(_ s: String) -> String {
+ s.replacingOccurrences(of: "&", with: "&amp;").replacingOccurrences(of: "<", with: "&lt;").replacingOccurrences(of: ">", with: "&gt;")
+ .replacingOccurrences(of: "'", with: "&#39;").replacingOccurrences(of: "\"", with: "&#34;")
+ }
+ func html(_ nodes: [ChatMarkdownNode]) -> String {
+ nodes.map { n in
+ switch n.kind {
+ case "text": escape(n.text ?? "")
+ case "strong": "<strong>\(html(n.children))</strong>"
+ case "emphasis": "<em>\(html(n.children))</em>"
+ case "link": "<a>\(html(n.children))</a>"
+ case "unordered": "<ul>\(html(n.children))</ul>"
+ case "ordered": (n.start.map { "<ol start=\"\($0)\">" } ?? "<ol>") + html(n.children) + "</ol>"
+ case "item": "<li>\(html(n.children))</li>"
+ default: html(n.children)
+ }
+ }.joined()
+ }
+ for c in cases {
+ XCTAssertEqual(html(LookupMarkdown.parse(c.text)), c.html, c.text)
+ }
+ // The person's own words keep their links.
+ XCTAssertTrue(html(PersonMarkdown.parse("[Met](https://met.test/)")).hasPrefix("<a>"))
+ }
+
+ /// The app says it draws lookups on Ask's two reads, as a query
+ /// parameter (the kit sets no header), and on nothing else.
+ func testClientCapabilityLookup() async throws {
+ XCTAssertEqual(CapabilityTransport.path("/ask/state"), "/ask/state?client_caps=lookup_answers")
+ XCTAssertEqual(CapabilityTransport.path("/ask/events?after=42"), "/ask/events?after=42&client_caps=lookup_answers")
+ XCTAssertEqual(CapabilityTransport.path("/ask/messages"), "/ask/messages")
+ XCTAssertEqual(CapabilityTransport.path("/api/v1/me"), "/api/v1/me")
+
+ let inner = ScriptedTransport([json(200, #"{"state":"connect","messages":[],"jobs":[],"cards":[],"turn":null,"status":"","cursor":0}"#),
+ json(200, #"{"message":{"id":"m1","role":"person","text":"Hi","turn_id":"t1"},"turn":{"id":"t1","kind":"chat","state":"queued"}}"#),
+ .respond(status: 200, body: Data())])
+ let client = BaseClient(transport: CapabilityTransport(inner)) {}
+ _ = try await client.askState()
+ _ = try await client.send("Hi", key: "k1")
+ try? await client.events(after: 7) { _, _ in }
+ XCTAssertEqual(inner.calls.map(\.path), ["/ask/state?client_caps=lookup_answers", "/ask/messages", "/ask/events?after=7&client_caps=lookup_answers"])
+ }
+}