oficina / base Public

Merge branch 'abilities-phase1' into main

Merge abilities-phase1: Base draws the Assistant's lookup answers

Phase 1 of the assistant abilities plan: client capabilities per member
(migration 0013_ask_clients), lookup answers drawn on the web and native,
and lookup_answers sent in Base-Capabilities. Harmless alone: no Equipo
sends lookups until its own phase 3 is switched on.

Paul approved merging and a staging-only release on 2026-11-29.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev c20c9706e4c44ebde0513fdd1b5e6a8017546a47 parent 5105b89parent ddbeb1b
39 files changed, +2,090 −60
  • docs/api/base-native-v1.md +37 −4
  • docs/copy-pending.md +7 −0
  • internal/browsertest/ask_lookup_test.go +159 −0
  • internal/equipo/abilities.go +58 −0
  • internal/equipo/chat.go +8 −3
  • internal/equipo/equipo.go +1 −0
  • internal/equipo/equipo_test.go +20 −1
  • internal/equipo/equipotest/chat.go +87 −6
  • internal/equipo/equipotest/fake.go +4 −0
  • internal/equipo/files.go +5 −2
  • internal/equipo/lookups.go +187 −0
  • internal/equipo/lookups_test.go +200 −0
  • internal/look/static/app.css +9 −0
  • internal/look/static/ask.js +82 −10
  • internal/store/askclients.go +80 −0
  • internal/store/askclients_test.go +47 −0
  • internal/store/migrations/0013_ask_clients.sql +6 −0
  • internal/web/app.go +6 −1
  • internal/web/ask.go +3 −0
  • internal/web/ask_caps.go +241 −0
  • internal/web/ask_caps_internal_test.go +44 −0
  • internal/web/ask_cards.go +57 −6
  • internal/web/ask_connect.go +4 −3
  • internal/web/ask_internal_test.go +6 −6
  • internal/web/ask_relay.go +10 −4
  • internal/web/rich_internal_test.go +18 −0
  • internal/web/templates/partials/chat.html +5 −3
  • internal/web/testdata/lookup.json +42 −0
  • internal/webtest/ask_caps_test.go +229 −0
  • internal/webtest/ask_lookup_test.go +132 −0
  • internal/webtest/ask_native_contract_test.go +1 −0
  • internal/webtest/harness_test.go +13 −0
  • native/apple/Sources/BaseKit/API/Models.swift +50 −5
  • native/apple/Sources/BaseKit/Ask/Markdown/PersonMarkdown.swift +33 −3
  • native/apple/Sources/BaseKit/Ask/Pill.swift +5 −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/AbilitiesTests.swift +108 −0

CI passed — run details

CI log
=== build ===
CGO_ENABLED=0 go build ./...
=== vet ===
go vet ./...
=== fmt-check ===
=== staticcheck ===
go run honnef.co/go/tools/cmd/staticcheck@v0.7.0 ./...
=== govulncheck ===
go run golang.org/x/vuln/cmd/govulncheck@v1.8.0 ./...
No vulnerabilities found.
=== gitleaks ===
1:21PM INF Unknown SCM platform. Use --platform to include links in findings. host=amadan.net
1:21PM INF 1 commits scanned.
1:21PM INF scanned ~2935619 bytes (2.94 MB) in 311ms
1:21PM INF no leaks found
=== budget ===
go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget size
budget size: 22 directories within budget
=== script-test ===
scripts/prepare-apps_test.sh
ok   releases lookup failure stops before ship
ok   app owned elsewhere stops the script
ok   apps listing failure stops before create
ok   ambiguous release dir is refused
ok   explicit version resolves the ambiguity
ok   releases match is exact, not substring
ok   shipped version is only promoted, existing app not created
ok   fresh account creates, ships, promotes to edge, enables
ok   failing promote stops the script
ok   ship is retried while uploads are rate limited
all passed
hack/fonts_test.sh
fonts_test: ok
=== test ===
go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -count=1 ./...

receipt: test step 12.706s against a 60s target (the gate's other steps are not in this figure)
receipt: 16 packages ran, 0 cached, 6 without tests, 0 failed
receipt: slow package 11.771s amadan.net/oficina/base/internal/webtest
receipt: slow package 1.465s amadan.net/oficina/base/internal/issuer
receipt: slow package 700ms amadan.net/oficina/base/internal/equipo
receipt: slow package 600ms amadan.net/oficina/base/internal/operations
receipt: slow package 293ms amadan.net/oficina/base/internal/web
receipt: slow test 1.52s amadan.net/oficina/base/internal/webtest TestHomeDoesNotWaitOnAStalledSnapshot
receipt: slow test 1.09s amadan.net/oficina/base/internal/webtest TestAskZoneIsToldOnce
receipt: slow test 1.04s amadan.net/oficina/base/internal/issuer TestAuthorizeSignsForInstalledApp
receipt: slow test 630ms amadan.net/oficina/base/internal/webtest TestAskUploadStalledBodyFreesItsSlot
receipt: slow test 520ms amadan.net/oficina/base/internal/operations TestOperationsRefusals
=== native ===
strings: copy review's strings.json is not here (git-ignored); its comparison skipped
strings: 121 in the catalog, 118 used
worktree-lib_test: ok
diff --git a/docs/api/base-native-v1.md b/docs/api/base-native-v1.md
index e94af98..3dc572f 100644
--- a/docs/api/base-native-v1.md
+++ b/docs/api/base-native-v1.md
@@ -164,6 +164,24 @@ The web's own routes. Writes are **form-encoded**
`Accept: application/json` to get JSON back (without it they redirect, as
for a form). Every answer is `no-store`.
+### What the app can draw
+
+`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 session Base has not yet heard say it (a live
+session that hasn't read `/ask/state` since, or whose read Base couldn't
+record) counts as drawing nothing. An app that says nothing keeps what it
+gets today: its reads carry each message's lookups folded into its
+`text`, with the answer's own links and markup escaped.
+
+| value | what the app draws |
+|---|---|
+| `lookup_answers` | A message's `lookups` (below) |
+
### The states
`state` is one of:
@@ -211,13 +229,25 @@ for a form). Every answer is `no-store`.
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
@@ -236,8 +266,11 @@ Equipo: `GET /ask/attachments/{id}`, and an image's thumbnail (at most
more and `started_at` when it began. A `paused` job carries on by itself
(draw it with the clock mark); its `result` and `detail` are Equipo's,
already in the team's time zone ("Paused until 21:00"): show them as
- given. `carry_on: true` (on a `paused` job card only, else absent) offers
- "Carry on now" (`POST /ask/cards/{id}/carry_on`).
+ given. `carry_on: true` (on a `paused` or `stopped` job card only, else
+ absent) offers "Carry on now" (`POST /ask/cards/{id}/carry_on`). On a
+ `paused` job it has the line "Uses your other plan, at no extra cost."
+ under it; on a `stopped` one (a job held while building was turned off
+ for the person, now on again) it has no line.
- `job` names the job card a card belongs to; `turn_id`, on a connect card
from the stream, the turn that raised it.
@@ -307,7 +340,7 @@ Form: `choice` (an option's `value`), `revision` (the card's, as seen) and
### `POST /ask/cards/{id}/carry_on`
-A paused job's "Carry on now". Form: `revision` (the job card's, as seen)
+A paused or held job's "Carry on now". Form: `revision` (the job card's, as seen)
and `key`, a fresh idempotency key kept until an answer settles the
outcome (a resend after a network error or a `502` reuses it).
diff --git a/docs/copy-pending.md b/docs/copy-pending.md
index b917e6d..2379a5b 100644
--- a/docs/copy-pending.md
+++ b/docs/copy-pending.md
@@ -448,3 +448,10 @@ Review 13 (reviewed by Luna, 2026-11-26; Luna's verdicts are the review, as Paul
| ask.turn.no_room | ask.go, ask.js | REVIEWED (Luna, 2026-11-26): status line: the runner had no room for the files (runner_storage_full) | There’s no room left for these files. Try fewer or smaller ones. |
| ask.turn.runner_too_old | ask.go, ask.js | REVIEWED (Luna, 2026-11-26): status line: the turn with files was failed when an older runner connected (runner_too_old) | Files can’t be read right now. Send it again without them. |
| ask.files_line_a11y | native Thread.swift (Localizable.xcstrings) | REVIEWED (Luna, 2026-11-26): VoiceOver: the plain line of a person's files' names under their words in the Mac and iPhone apps, until slice 2 draws files; {names} comma-separated | Attached: {names} |
+
+Review 14 (approved, Paul, 2026-11-28, copy review mi3kgi7nubnsf7kxn235tqwrbu, every string unchanged): the Assistant's abilities (spec 2026-11-26-assistant-abilities, plan 2026-11-27). When the Assistant looks something up on the web, the answer shows under its reply with the pages it came from. The answer's own words come from the instance; Base draws them with its little Markdown, never as links. Phase 1 uses the two rows below; the person page and Settings strings of the same review land with phase 4.
+
+| Id | File | Context | Text |
+|---|---|---|---|
+| ask.sources | partials/chat.html, ask.js, native Thread.swift (Localizable.xcstrings) | APPROVED (Paul, 2026-11-28): the quiet line under a lookup's answer, before each source's title (a link) and host | Sources |
+| ask.fallback_sources | internal/equipo/lookups.go | APPROVED (Paul, 2026-11-28): in the plain text an app that can't draw lookups gets instead: the reply's words, the answer, then this line and the sources' addresses | Sources: |
diff --git a/internal/browsertest/ask_lookup_test.go b/internal/browsertest/ask_lookup_test.go
new file mode 100644
index 0000000..165e455
--- /dev/null
+++ b/internal/browsertest/ask_lookup_test.go
@@ -0,0 +1,159 @@
+//go:build browser
+
+package browsertest
+
+import (
+ "context"
+ "encoding/json"
+ "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/"}, {URL: "https://c.test/", Title: "Met\rNow\x00"}, {URL: "https://d.test/wiki/Foo_(bar)'s", Title: "Wiki"}}}},
+ "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)
+ }
+}
+
+// With scripts, a held job that offers it shows Carry on now in its view,
+// with no "other plan" line, and carries on in place (plan AD4).
+func TestStoppedCarryOnDrawn(t *testing.T) {
+ rig, f := askBase(t)
+ openPanel(t, rig)
+ id := f.AskJob("Bakery website")
+ f.StopJob(id, "Stopped", "Building is on again. You can carry on with this, or drop it.", true)
+ job := `#ask-panel li.job[data-job="` + id + `"]`
+ drive(t, rig, chromedp.Poll[chromedp.Void](`document.querySelector(`+strconv.Quote(job)+`)?.dataset.state === "stopped" && document.querySelector(`+strconv.Quote(job+` .jv-act`)+`) !== null`,
+ chromedp.WithPollingTimeout(10*time.Second)))
+ if got := harness.Evaluate[string](rig, `(() => { const f = document.querySelector(`+strconv.Quote(job+` .jv-act`)+`);
+ return [f.querySelector("button").textContent, f.querySelectorAll("small").length].join("|"); })()`); got != "Carry on now|0" {
+ t.Errorf("the held job's Carry on now: %s", got)
+ }
+ drive(t, rig, chromedp.Click(chromedp.CSS(job+` summary`)), chromedp.Sleep(250*time.Millisecond),
+ chromedp.Click(chromedp.CSS(job+` .jv-act button`)))
+ drive(t, rig, chromedp.Poll[chromedp.Void](`document.querySelector(`+strconv.Quote(job)+`)?.dataset.state === "working"`, chromedp.WithPollingTimeout(10*time.Second)))
+ if n := len(f.Calls("/api/v1/assistant/cards/" + id + "/carry_on")); n != 1 {
+ t.Errorf("carry on went %d times", n)
+ }
+}
+
+// Every shared sample (internal/web/testdata/lookup.json, which the
+// server's and the app's tests check too) is drawn by the script exactly
+// as the server draws it: characters counted alike, whitespace read alike.
+func TestAskLookupMarkdownFixtures(t *testing.T) {
+ raw, err := os.ReadFile("../web/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)
+ }
+ replies, order := map[string][]equipo.Lookup{}, []string{}
+ for i, c := range cases {
+ text := "Sample " + strconv.Itoa(i)
+ replies[text] = []equipo.Lookup{{Answer: c.Text, Sources: []equipo.Source{{URL: "https://src.test/", Title: "Src"}}}}
+ order = append(order, text)
+ }
+ rig := sayLookups(t, replies, order)
+ if got := harness.Evaluate[string](rig, sameAsServer, chromedp.EvalAwaitPromise); got != "" {
+ t.Errorf("the script and the server draw the samples differently:\n%s", got)
+ }
+}
diff --git a/internal/equipo/abilities.go b/internal/equipo/abilities.go
new file mode 100644
index 0000000..2c7bab2
--- /dev/null
+++ b/internal/equipo/abilities.go
@@ -0,0 +1,58 @@
+package equipo
+
+import (
+ "context"
+ "net/http"
+ "strings"
+)
+
+// The values of Base-Capabilities: what Base, and every client the
+// member uses, can draw. CapLookupAnswers: a reply's lookup answers and
+// their sources (Message.Lookups).
+const CapLookupAnswers = "lookup_answers"
+
+// KnownCapabilities are the values Base may send, in order. A value is
+// sent for a member only while each of their clients can draw it.
+var KnownCapabilities = []string{CapLookupAnswers}
+
+// AbilityKeys are what the Base owner can turn off for a member, in the
+// order the person page lists them. Equipo's internal/wire/abilities.go
+// has the same list; Base can't import it.
+var AbilityKeys = []string{"web", "apps_read", "apps_write", "build", "go_live", "services", "services_add"}
+
+// CapabilitiesHeader is the header that carries them on every call.
+const CapabilitiesHeader = "Base-Capabilities"
+
+type capsKey struct{}
+
+// CapabilitiesFunc works out the capabilities to send, as a call is sent.
+type CapabilitiesFunc func(ctx context.Context) []string
+
+// WithCapabilities is ctx with caps to send as Base-Capabilities on every
+// call made with it (none: the header is left out).
+func WithCapabilities(ctx context.Context, caps []string) context.Context {
+ caps = append([]string(nil), caps...)
+ return WithCapabilitiesFunc(ctx, func(context.Context) []string { return caps })
+}
+
+// WithCapabilitiesFunc is ctx with f, asked for the capabilities as each
+// call made with it is sent: a call sent late (an upload, a goroutine)
+// says what holds then, not when its request began.
+func WithCapabilitiesFunc(ctx context.Context, f CapabilitiesFunc) context.Context {
+ return context.WithValue(ctx, capsKey{}, f)
+}
+
+// CapabilitiesFuncOf is ctx's CapabilitiesFunc, or nil.
+func CapabilitiesFuncOf(ctx context.Context) CapabilitiesFunc {
+ f, _ := ctx.Value(capsKey{}).(CapabilitiesFunc)
+ return f
+}
+
+// setCapabilities puts ctx's capabilities, as they are now, on req.
+func setCapabilities(ctx context.Context, req *http.Request) {
+ if f := CapabilitiesFuncOf(ctx); f != nil {
+ if caps := f(ctx); len(caps) > 0 {
+ req.Header.Set(CapabilitiesHeader, strings.Join(caps, ","))
+ }
+ }
+}
diff --git a/internal/equipo/chat.go b/internal/equipo/chat.go
index d18d676..6a5a652 100644
--- a/internal/equipo/chat.go
+++ b/internal/equipo/chat.go
@@ -30,7 +30,9 @@ func InFlight(state string) bool {
// Message is one line of the conversation; Role is person or assistant.
// Attachments are the files the person sent with it, in their order
-// (Clean keeps those Base passes on).
+// (Clean keeps those Base passes on); Lookups, on the Assistant's reply,
+// what it looked up on the web for it, in the order it did (Clean keeps
+// them within bounds).
type Message struct {
ID string `json:"id"`
Role string `json:"role"`
@@ -38,6 +40,7 @@ type Message struct {
TurnID string `json:"turn_id"`
CreatedAt time.Time `json:"created_at"`
Attachments []Attachment `json:"attachments,omitempty"`
+ Lookups []Lookup `json:"lookups,omitempty"`
}
// Turn is the Assistant's answer to the person's messages.
@@ -56,7 +59,8 @@ type Turn struct {
// sentence more and StartedAt when it began; Job is the job card a
// go-ahead or Publish card belongs to. A paused job's Result and Detail
// are already in the person's time zone ("Paused until 21:00"), and
-// CarryOn says the person may start it again now (CarryOnNow).
+// CarryOn says the person may start it again now (CarryOnNow): a paused
+// job, or a stopped one held while building was off, once it is on again.
type Card struct {
ID string `json:"id"`
Revision int64 `json:"revision"`
@@ -150,7 +154,7 @@ func (c Card) CleanAt(base string) (Card, bool) {
Options: []Option{}, Links: []Link{}, Result: c.Result}
if c.Kind == CardJob {
out.Detail, out.StartedAt = c.Detail, c.StartedAt
- out.CarryOn = c.CarryOn && c.State == JobPaused
+ out.CarryOn = c.CarryOn && (c.State == JobPaused || c.State == JobStopped)
} else {
for _, o := range c.Options {
out.Options = append(out.Options, Option{Value: o.Value, Label: o.Label})
@@ -368,6 +372,7 @@ func (c *Client) Events(ctx context.Context, token, after string) (*http.Respons
}
req.Header.Set("Accept", "text/event-stream")
req.Header.Set("Authorization", "Bearer "+token)
+ setCapabilities(ctx, req)
late := time.AfterFunc(c.StreamHeaderTimeout, cancel)
res, err := c.http.Do(req)
if !late.Stop() && err == nil {
diff --git a/internal/equipo/equipo.go b/internal/equipo/equipo.go
index b800739..2f4de14 100644
--- a/internal/equipo/equipo.go
+++ b/internal/equipo/equipo.go
@@ -135,6 +135,7 @@ func (c *Client) call(ctx context.Context, method, path, token, key string, head
req.Header.Set("Content-Type", "application/json")
}
req.Header.Set("Accept", "application/json")
+ setCapabilities(ctx, req)
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
diff --git a/internal/equipo/equipo_test.go b/internal/equipo/equipo_test.go
index fdb1e82..a8463ac 100644
--- a/internal/equipo/equipo_test.go
+++ b/internal/equipo/equipo_test.go
@@ -490,7 +490,6 @@ func TestCardCleanPausedJob(t *testing.T) {
}
for _, c := range []equipo.Card{
{ID: "c_2", Kind: equipo.CardJob, State: equipo.JobWorking, CarryOn: true},
- {ID: "c_3", Kind: equipo.CardJob, State: equipo.JobStopped, CarryOn: true},
{ID: "c_4", Kind: equipo.CardOutcome, State: "open", CarryOn: true},
} {
got, _ := c.Clean()
@@ -500,6 +499,26 @@ func TestCardCleanPausedJob(t *testing.T) {
}
}
+// A stopped job keeps carry_on: a job held because building was turned
+// off, once it is on again, carries on when the person says so (plan
+// AD4). Any card that isn't a job never has it.
+func TestCardCleanStoppedCarryOn(t *testing.T) {
+ got, ok := equipo.Card{ID: "c_1", Revision: 2, Kind: equipo.CardJob, State: equipo.JobStopped, Question: "Bakery website",
+ Result: "Stopped", Detail: "Building is on again. You can carry on with this, or drop it.", CarryOn: true}.Clean()
+ if !ok || !got.CarryOn {
+ t.Errorf("stopped job: %v %+v", ok, got)
+ }
+ for _, c := range []equipo.Card{
+ {ID: "c_2", Kind: equipo.CardOutcome, State: "open", CarryOn: true},
+ {ID: "c_3", Kind: equipo.CardQuestion, State: equipo.JobStopped, CarryOn: true},
+ {ID: "c_4", Kind: equipo.CardJob, State: equipo.JobReady, CarryOn: true},
+ } {
+ if got, _ := c.Clean(); got.CarryOn {
+ t.Errorf("%s %s kept carry_on", c.Kind, c.State)
+ }
+ }
+}
+
// CarryOnNow posts {revision, idempotency_key} with the key as the
// Idempotency-Key and reads the card back from {"card"}; the same key
// replays the answer; Equipo's 409s come back as errors with their codes.
diff --git a/internal/equipo/equipotest/chat.go b/internal/equipo/equipotest/chat.go
index 9169a5c..b916b5c 100644
--- a/internal/equipo/equipotest/chat.go
+++ b/internal/equipo/equipotest/chat.go
@@ -32,6 +32,46 @@ type message struct {
// Attachments are the files sent with a person's message, in order;
// omitted when there are none (wire.Message).
Attachments []file `json:"attachments,omitempty"`
+ // Lookups are what the Assistant looked up for a reply, sent only to
+ // a Base that draws them (asRead).
+ Lookups []equipo.Lookup `json:"lookups,omitempty"`
+}
+
+// drawsLookups reports whether r says Base draws lookup answers
+// (Base-Capabilities), as Equipo reads it.
+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 {
+ return true
+ }
+ }
+ }
+ return false
+}
+
+// asRead is m as a read with draws gets it: its lookups as they are, or,
+// for a Base that can't draw them, folded into its text, as Equipo's
+// plain-text fallback does (computed at read time, never stored).
+func asRead(m message, draws bool) message {
+ if draws || len(m.Lookups) == 0 {
+ return m
+ }
+ m.Text = equipo.Message{Text: m.Text, Lookups: m.Lookups}.PlainLookups().Text
+ m.Lookups = nil
+ return m
+}
+
+// read is msgs as a read with draws gets them (asRead).
+func read(msgs []message, draws bool) []message {
+ out := make([]message, len(msgs))
+ for i, m := range msgs {
+ out[i] = asRead(m, draws)
+ }
+ return out
}
type turn struct {
@@ -254,6 +294,22 @@ func (f *Fake) PauseJob(id, result, detail string, carryOn bool) {
}
}
+// StopJob moves job card id to stopped, with result and detail, and
+// carryOn saying whether the person may carry it on now (a job held
+// because building was turned off, once it is on again): a new revision,
+// announced.
+func (f *Fake) StopJob(id, result, detail string, carryOn bool) {
+ f.SetJob(id, equipo.JobStopped, result, detail)
+ f.cmu.Lock()
+ defer f.cmu.Unlock()
+ for _, c := range f.cards {
+ if c.ID == id && c.CarryOn != carryOn {
+ c.CarryOn, c.Revision = carryOn, c.Revision+1
+ f.emit("card", "card", c.ID, c.Revision, "", *c)
+ }
+ }
+}
+
// SetJobStarted moves when job card id started to at: a new revision,
// announced.
func (f *Fake) SetJobStarted(id string, at time.Time) {
@@ -358,6 +414,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)
+}
+
// Turn is the state of the turn with id ("" when there is none).
func (f *Fake) Turn(id string) string {
f.cmu.Lock()
@@ -390,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": f.tail(), "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)
@@ -445,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": f.tail(), "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(),
})
}
@@ -600,7 +667,17 @@ func (f *Fake) answerTurn(id, text string) {
// Answer answers the running turn with id (one Hold kept running): with
// deltas, the reply streamed in word by word first (Stream); then the
// reply message, and the turn replied.
-func (f *Fake) Answer(id, reply string, deltas bool) {
+func (f *Fake) Answer(id, reply string, deltas bool) { f.answerWith(id, reply, deltas, nil) }
+
+// ReplyWithLookups answers the running turn with id as Answer does (its
+// words streamed first), with lookups on the reply, as Equipo attaches
+// what the Assistant looked up for it. A read that doesn't say Base draws
+// them gets them folded into the text.
+func (f *Fake) ReplyWithLookups(id, reply string, lookups ...equipo.Lookup) {
+ f.answerWith(id, reply, true, lookups)
+}
+
+func (f *Fake) answerWith(id, reply string, deltas bool, lookups []equipo.Lookup) {
if deltas {
f.Stream(id, reply)
}
@@ -609,7 +686,8 @@ func (f *Fake) Answer(id, reply string, deltas bool) {
if f.turns[id].State != "running" {
return
}
- m := message{ID: f.next("m"), Revision: 1, Role: "assistant", Text: reply, TurnID: id, CreatedAt: time.Now().UTC()}
+ m := message{ID: f.next("m"), Revision: 1, Role: "assistant", Text: reply, TurnID: id, CreatedAt: time.Now().UTC(),
+ Lookups: append([]equipo.Lookup(nil), lookups...)}
f.messages = append(f.messages, m)
f.emit("message", "message", m.ID, 1, id, m)
t := f.turns[id]
@@ -799,7 +877,7 @@ func (f *Fake) carryOn(w http.ResponseWriter, r *http.Request, id string) {
writeJSON(w, 200, map[string]any{"card": *c})
case c.Revision != in.Revision:
conflict("card_stale")
- case c.State != equipo.JobPaused:
+ case c.State != equipo.JobPaused && c.State != equipo.JobStopped:
conflict("not_paused")
case !c.CarryOn:
conflict("carry_on_unavailable")
@@ -934,7 +1012,7 @@ func (f *Fake) stream(w http.ResponseWriter, r *http.Request) {
}
after = n
}
- paused := pausedOK(r)
+ paused, draws := pausedOK(r), f.drawsLookups(r)
rc := http.NewResponseController(w)
w.Header().Set("Content-Type", "text/event-stream")
w.WriteHeader(200)
@@ -956,6 +1034,9 @@ func (f *Fake) stream(w http.ResponseWriter, r *http.Request) {
if c, ok := e.Data.(card); ok {
e.Data = asSeen(c, paused)
}
+ if m, ok := e.Data.(message); ok {
+ e.Data = asRead(m, draws)
+ }
raw, _ := json.Marshal(e)
id := ""
if e.Cursor != 0 {
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/equipo/files.go b/internal/equipo/files.go
index 634cb7f..0f54582 100644
--- a/internal/equipo/files.go
+++ b/internal/equipo/files.go
@@ -37,8 +37,9 @@ func ValidAttachmentID(id string) bool { return attachmentID.MatchString(id) }
var attachmentID = regexp.MustCompile(`^at_[a-z0-9]{8,60}$`)
-// Clean is the message as Base passes it on: only the attachments whose id
-// it would call Equipo with, each with a kind Base draws (an unknown kind
+// Clean is the message as Base passes it on: its lookups within bounds
+// (cleanLookups), and only the attachments whose id it would call Equipo
+// with, each with a kind Base draws (an unknown kind
// is a file), a name of valid UTF-8 (at most 255 bytes; "file" when
// empty), and no negative size or side. Nil when none are left, so a
// message without files is what it always was.
@@ -63,6 +64,7 @@ func (m Message) Clean() Message {
out = append(out, a)
}
m.Attachments = out
+ m.Lookups = cleanLookups(m.Role, m.Lookups)
return m
}
@@ -121,6 +123,7 @@ func (c *Client) do(ctx context.Context, method, path, token string, header http
req.Header[k] = v
}
req.Header.Set("Authorization", "Bearer "+token)
+ setCapabilities(ctx, req)
late := time.AfterFunc(c.fileTimeout(), cancel)
res, err := c.http.Do(req)
if !late.Stop() && err == nil {
diff --git a/internal/equipo/lookups.go b/internal/equipo/lookups.go
new file mode 100644
index 0000000..4ebd507
--- /dev/null
+++ b/internal/equipo/lookups.go
@@ -0,0 +1,187 @@
+package equipo
+
+import (
+ "fmt"
+ "net/url"
+ "regexp"
+ "strings"
+ "unicode"
+ "unicode/utf8"
+)
+
+// Lookup is one thing the Assistant looked up on the web for a reply: a
+// short answer, and the pages it came from. Equipo sends a message's
+// lookups only to a Base that said it draws them (CapLookupAnswers).
+type Lookup struct {
+ Answer string `json:"answer"`
+ Sources []Source `json:"sources"`
+}
+
+// Source is a page a lookup's answer came from.
+type Source struct {
+ URL string `json:"url"`
+ Title string `json:"title"`
+}
+
+// The bounds Clean keeps a message's lookups to: an answer of at most
+// MaxLookupAnswer characters (a longer one is dropped with its lookup), at
+// most MaxLookupSources sources each, titles cut to MaxLookupTitle
+// characters, and at most MaxLookups lookups.
+const (
+ MaxLookupAnswer = 1200
+ MaxLookupSources = 5
+ MaxLookupTitle = 120
+ MaxLookups = 2
+ // maxSourceURL bounds a source's address, in bytes.
+ maxSourceURL = 2 << 10
+)
+
+// fallbackSources heads a lookup's addresses in the plain text a client
+// that can't draw lookups gets (copy ask.fallback_sources, approved by
+// Paul, 2026-11-28, copy review mi3kgi7nubnsf7kxn235tqwrbu).
+const fallbackSources = "Sources:"
+
+// cleanLookups is lookups as Base passes them on (Message.Clean): only an
+// assistant's message has any; each answer is valid UTF-8, not blank and
+// at most MaxLookupAnswer characters; each source an absolute https
+// address (sourceURL) with its title cut to MaxLookupTitle characters; a
+// lookup left without a source is dropped. Nil when none are left.
+func cleanLookups(role string, lookups []Lookup) []Lookup {
+ if role != "assistant" {
+ return nil
+ }
+ var out []Lookup
+ for _, l := range lookups {
+ if len(out) == MaxLookups {
+ break
+ }
+ answer := strings.ToValidUTF8(l.Answer, "")
+ if strings.TrimSpace(answer) == "" || utf8.RuneCountInString(answer) > MaxLookupAnswer {
+ continue
+ }
+ var sources []Source
+ for _, s := range l.Sources {
+ if len(sources) == MaxLookupSources {
+ break
+ }
+ u := sourceURL(s.URL)
+ if u == "" {
+ continue
+ }
+ title := []rune(strings.Map(func(r rune) rune {
+ if unicode.IsControl(r) {
+ return ' '
+ }
+ return r
+ }, strings.ToValidUTF8(s.Title, "")))
+ if len(title) > MaxLookupTitle {
+ title = title[:MaxLookupTitle]
+ }
+ sources = append(sources, Source{URL: u, Title: string(title)})
+ }
+ if len(sources) > 0 {
+ out = append(out, Lookup{Answer: answer, Sources: sources})
+ }
+ }
+ return out
+}
+
+// sourceURL is raw if it is an absolute https address with a DNS name
+// for its host (sourceHostRE), no port and no user info, of at most
+// maxSourceURL bytes, else "".
+func sourceURL(raw string) string {
+ if len(raw) > maxSourceURL {
+ return ""
+ }
+ u := WebURL(raw)
+ p, err := url.Parse(u)
+ if u == "" || err != nil || p.Scheme != "https" || p.Port() != "" || !sourceHostRE.MatchString(strings.ToLower(p.Host)) {
+ return ""
+ }
+ return normalizeURL(u)
+}
+
+// normalizeURL percent-encodes every byte of u that Go's html/template
+// would encode in an href (all but letters, digits, -._~, the reserved
+// !#$&*+,/:;=?@[] and %), so the address the server draws and the one
+// ask.js and the app are handed are the same.
+func normalizeURL(u string) string {
+ var b strings.Builder
+ for i := 0; i < len(u); i++ {
+ c := u[i]
+ switch {
+ case 'a' <= c && c <= 'z', 'A' <= c && c <= 'Z', '0' <= c && c <= '9', strings.IndexByte("-._~!#$&*+,/:;=?@[]%", c) >= 0:
+ b.WriteByte(c)
+ default:
+ fmt.Fprintf(&b, "%%%02X", c)
+ }
+ }
+ return b.String()
+}
+
+// sourceHostRE is a source's host: a DNS name of two labels or more in
+// ASCII letters, digits and inner hyphens, the last with a letter, and
+// no port. So it is no IP literal in any form, and every client (Go's
+// url, a browser's URL, Foundation's URL) reads the same host from it.
+var sourceHostRE = regexp.MustCompile(`^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9-]*[a-z][a-z0-9-]*$`)
+
+// The addresses plainAnswer takes out of an answer's text: a Markdown
+// link, an autolink, a bare http(s) address, and a www. name; then
+// markdownEscaper. Whitespace
+// is spelled out, so every engine reads it alike.
+var (
+ foldMarkdownLink = regexp.MustCompile(`\[([^\[\]\n]{1,300})\]\(([^()\t\n\f\r ]{1,1000})\)`)
+ foldAddress = regexp.MustCompile(`<?(?:https?://|www\.)[^\t\n\f\r <>()\[\]"']+>?`)
+)
+
+// plainAnswer is a lookup's answer as a client that draws ordinary
+// Markdown may show it with no link of its own (spec §4.6): a Markdown
+// link is its words, and an address (bare, an autolink, or a www. name)
+// is its host alone, without "www.", which no Markdown links; and what
+// Markdown could still read as a link is escaped. Trailing punctuation
+// stays as text.
+func plainAnswer(answer string) string {
+ answer = foldMarkdownLink.ReplaceAllString(answer, "$1")
+ answer = foldAddress.ReplaceAllStringFunc(answer, func(m string) string {
+ raw := strings.TrimSuffix(strings.TrimPrefix(m, "<"), ">")
+ trail := ""
+ if !strings.HasSuffix(m, ">") {
+ cut := strings.TrimRight(raw, ".,;:!?")
+ trail, raw = raw[len(cut):], cut
+ }
+ if strings.HasPrefix(raw, "www.") {
+ raw = "https://" + raw
+ }
+ u, err := url.Parse(raw)
+ if err != nil {
+ return trail
+ }
+ return strings.TrimPrefix(strings.ToLower(u.Hostname()), "www.") + trail
+ })
+ return markdownEscaper.Replace(answer)
+}
+
+// markdownEscaper escapes what CommonMark could still read as a link: a
+// reference link or its definition, an image, an autolink, raw HTML or
+// an entity in a destination. Escaped, each shows as written.
+var markdownEscaper = strings.NewReplacer(`\`, `\\`, `[`, `\[`, `]`, `\]`, `<`, `\<`, `>`, `\>`, `&`, `\&`)
+
+// PlainLookups is m for a client that can't draw lookups: each answer
+// folded into the text after the message's own words, followed by
+// "Sources:" and its sources' addresses, one per line; the answer's own
+// addresses are taken out (plainAnswer). Lookups is nil.
+func (m Message) PlainLookups() Message {
+ parts := []string{}
+ if m.Text != "" {
+ parts = append(parts, m.Text)
+ }
+ for _, l := range m.Lookups {
+ urls := make([]string, 0, len(l.Sources))
+ for _, s := range l.Sources {
+ urls = append(urls, s.URL)
+ }
+ parts = append(parts, plainAnswer(l.Answer), fallbackSources+"\n"+strings.Join(urls, "\n"))
+ }
+ m.Text, m.Lookups = strings.Join(parts, "\n\n"), nil
+ return m
+}
diff --git a/internal/equipo/lookups_test.go b/internal/equipo/lookups_test.go
new file mode 100644
index 0000000..d8fda38
--- /dev/null
+++ b/internal/equipo/lookups_test.go
@@ -0,0 +1,200 @@
+package equipo_test
+
+import (
+ "bufio"
+ "context"
+ "encoding/json"
+ "reflect"
+ "strings"
+ "testing"
+ "time"
+ "unicode/utf8"
+
+ "amadan.net/oficina/base/internal/equipo"
+ "amadan.net/oficina/base/internal/equipo/equipotest"
+)
+
+func src(n int) equipo.Source {
+ return equipo.Source{URL: "https://site.test/" + strings.Repeat("p", n), Title: "Page"}
+}
+
+// Clean keeps an answer of at most 1,200 characters and drops a longer
+// one, keeps at most 5 sources and 2 lookups, and cuts a title to 120
+// characters at a character boundary.
+func TestCleanLookupBounds(t *testing.T) {
+ long := strings.Repeat("é", equipo.MaxLookupAnswer)
+ m := equipo.Message{ID: "m1", Role: "assistant", Lookups: []equipo.Lookup{
+ {Answer: long, Sources: []equipo.Source{src(1), src(2), src(3), src(4), src(5), src(6)}},
+ {Answer: long + "x", Sources: []equipo.Source{src(1)}},
+ {Answer: "Second", Sources: []equipo.Source{{URL: "https://b.test/", Title: strings.Repeat("ü", equipo.MaxLookupTitle+1)}, {URL: "https://c.test/", Title: "Met\rNow\x00\tthen"}}},
+ {Answer: "Third", Sources: []equipo.Source{src(1)}},
+ {Answer: "Fourth", Sources: []equipo.Source{src(1)}},
+ }}.Clean()
+ if len(m.Lookups) != equipo.MaxLookups {
+ t.Fatalf("%d lookups kept, want %d: %+v", len(m.Lookups), equipo.MaxLookups, m.Lookups)
+ }
+ if m.Lookups[0].Answer != long || len(m.Lookups[0].Sources) != equipo.MaxLookupSources {
+ t.Errorf("first lookup: %d characters, %d sources", utf8.RuneCountInString(m.Lookups[0].Answer), len(m.Lookups[0].Sources))
+ }
+ if m.Lookups[1].Answer != "Second" {
+ t.Errorf("the answer of 1,201 characters was kept: %q", m.Lookups[1].Answer[:20])
+ }
+ if got := m.Lookups[1].Sources[1].Title; got != "Met Now then" {
+ t.Errorf("a title's control characters: %q", got)
+ }
+ title := m.Lookups[1].Sources[0].Title
+ if !utf8.ValidString(title) || utf8.RuneCountInString(title) != equipo.MaxLookupTitle {
+ t.Errorf("title cut to %d characters (valid %v)", utf8.RuneCountInString(title), utf8.ValidString(title))
+ }
+ // A person's message carries none, and a message without any is what
+ // it always was.
+ if p := (equipo.Message{Role: "person", Lookups: []equipo.Lookup{{Answer: "x", Sources: []equipo.Source{src(1)}}}}).Clean(); p.Lookups != nil {
+ t.Errorf("a person's message kept lookups: %+v", p.Lookups)
+ }
+ raw, _ := json.Marshal(equipo.Message{ID: "m2", Role: "assistant"}.Clean())
+ if strings.Contains(string(raw), "lookups") {
+ t.Errorf("a message without lookups: %s", raw)
+ }
+}
+
+// Only https sources are kept; a lookup left without any is dropped, as
+// is one with an empty answer.
+func TestCleanLookupHTTPSOnly(t *testing.T) {
+ m := equipo.Message{Role: "assistant", Lookups: []equipo.Lookup{
+ {Answer: "Kept", Sources: []equipo.Source{{URL: "http://plain.test/", Title: "a"}, {URL: "javascript:alert(1)", Title: "b"},
+ {URL: "/relative", Title: "c"}, {URL: "https://user:pw@x.test/", Title: "d"}, {URL: "https://café.test/", Title: "idn"},
+ {URL: "https://[::1]/", Title: "v6"}, {URL: "https://127.1/", Title: "v4"}, {URL: "https://ok.test:8443/", Title: "port"},
+ {URL: "https://localhost/", Title: "bare name"}, {URL: "https://-x.test/", Title: "hyphen"},
+ {URL: "https://ok.test/wiki/Foo_(bar)'s", Title: "f"}, {URL: "https://ok.test/a?b=1", Title: "e"}}},
+ {Answer: "No sources", Sources: []equipo.Source{{URL: "http://plain.test/"}}},
+ {Answer: " ", Sources: []equipo.Source{src(1)}},
+ }}.Clean()
+ want := []equipo.Lookup{{Answer: "Kept", Sources: []equipo.Source{{URL: "https://ok.test/wiki/Foo_%28bar%29%27s", Title: "f"}, {URL: "https://ok.test/a?b=1", Title: "e"}}}}
+ if !reflect.DeepEqual(m.Lookups, want) {
+ t.Errorf("lookups %+v, want %+v", m.Lookups, want)
+ }
+}
+
+// PlainLookups folds each answer and its sources' addresses into the
+// text, for a client that can't draw them.
+func TestPlainLookupsFolds(t *testing.T) {
+ m := equipo.Message{Role: "assistant", Text: "Here you go.", Lookups: []equipo.Lookup{
+ {Answer: "Rain later.", Sources: []equipo.Source{{URL: "https://met.test/dublin", Title: "Met"}, {URL: "https://b.test/", Title: "B"}}},
+ {Answer: "Open at 10.", Sources: []equipo.Source{{URL: "https://museum.test/", Title: "Museum"}}},
+ }}.PlainLookups()
+ want := "Here you go.\n\nRain later.\n\nSources:\nhttps://met.test/dublin\nhttps://b.test/\n\nOpen at 10.\n\nSources:\nhttps://museum.test/"
+ if m.Text != want || m.Lookups != nil {
+ t.Errorf("folded %q, lookups %v\nwant %q", m.Text, m.Lookups, want)
+ }
+ if got := (equipo.Message{Role: "assistant", Lookups: []equipo.Lookup{{Answer: "A.", Sources: []equipo.Source{src(1)}}}}).PlainLookups(); got.Text != "A.\n\nSources:\nhttps://site.test/p" {
+ t.Errorf("no words of its own: %q", got.Text)
+ }
+ // An answer's own addresses never come back as links in the folded
+ // text: a Markdown link is its words, and a bare address, an autolink
+ // or a www. name is its host alone, which no Markdown links.
+ linked := equipo.Message{Role: "assistant", Lookups: []equipo.Lookup{{
+ Answer: "See [Met](https://evil.test/a), https://www.evil.test/b?c=1, <https://evil.test/c> and www.evil.test/d.",
+ Sources: []equipo.Source{{URL: "https://met.test/", Title: "Met"}}}}}.PlainLookups()
+ if want := "See Met, evil.test, evil.test and evil.test.\n\nSources:\nhttps://met.test/"; linked.Text != want {
+ t.Errorf("folded links %q\nwant %q", linked.Text, want)
+ }
+ // Nor through a reference link, an entity in a destination or raw
+ // HTML: what Markdown reads as a link, an autolink or markup is
+ // escaped, so it shows as written (Astra round 2).
+ ref := equipo.Message{Role: "assistant", Lookups: []equipo.Lookup{{
+ Answer: "[Open][ref] and ![i](x) <b>\n\n[ref]: https&#58;//evil.test/ \\",
+ Sources: []equipo.Source{{URL: "https://met.test/", Title: "Met"}}}}}.PlainLookups()
+ if want := "\\[Open\\]\\[ref\\] and !i \\<b\\>\n\n\\[ref\\]: https\\&#58;//evil.test/ \\\\\n\nSources:\nhttps://met.test/"; ref.Text != want {
+ t.Errorf("folded reference %q\nwant %q", ref.Text, want)
+ }
+ if got := (equipo.Message{Text: "Plain"}).PlainLookups(); got.Text != "Plain" {
+ t.Errorf("no lookups: %q", got.Text)
+ }
+}
+
+// The ability keys, in the spec's order (§3).
+func TestAbilityKeysMatchSpec(t *testing.T) {
+ want := []string{"web", "apps_read", "apps_write", "build", "go_live", "services", "services_add"}
+ if !reflect.DeepEqual(equipo.AbilityKeys, want) {
+ t.Errorf("AbilityKeys %v, want %v", equipo.AbilityKeys, want)
+ }
+}
+
+// The fake serves a reply's lookups only to a call that says Base draws
+// them, and otherwise the plain text Equipo falls back to, in the
+// snapshot, the messages page and the event stream alike.
+func TestFakeLookupFallbackWithoutCapability(t *testing.T) {
+ f := equipotest.New(t)
+ f.Hold = true
+ c := equipo.New(f.URL)
+ cred := signIn(t, f, c)
+ sent, err := c.Send(context.Background(), cred.Token, "Weather in Dublin?", "k-1", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for f.Turn(sent.Turn.ID) != "running" {
+ time.Sleep(5 * time.Millisecond)
+ }
+ lookup := equipo.Lookup{Answer: "Rain later.", Sources: []equipo.Source{{URL: "https://met.test/dublin", Title: "Met"}}}
+ f.ReplyWithLookups(sent.Turn.ID, "Here it is.", lookup)
+
+ drawn := equipo.WithCapabilities(context.Background(), []string{equipo.CapLookupAnswers})
+ s, err := c.Snapshot(drawn, cred.Token)
+ if err != nil {
+ t.Fatal(err)
+ }
+ reply := s.Messages[len(s.Messages)-1]
+ if reply.Text != "Here it is." || !reflect.DeepEqual(reply.Lookups, []equipo.Lookup{lookup}) {
+ t.Errorf("with the capability: %+v", reply)
+ }
+ plain := equipo.Message{Role: "assistant", Text: "Here it is.", Lookups: []equipo.Lookup{lookup}}.PlainLookups().Text
+ for _, ctx := range []context.Context{context.Background(), equipo.WithCapabilities(context.Background(), []string{"job_actions"})} {
+ s, err := c.Snapshot(ctx, cred.Token)
+ if err != nil {
+ t.Fatal(err)
+ }
+ reply := s.Messages[len(s.Messages)-1]
+ if reply.Text != plain || reply.Lookups != nil {
+ t.Errorf("without the capability: %+v", reply)
+ }
+ }
+ for name, ctx := range map[string]context.Context{"drawn": drawn, "plain": context.Background()} {
+ res, err := c.Events(ctx, cred.Token, "0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ sc := bufio.NewScanner(res.Body)
+ var got string
+ for sc.Scan() {
+ if line := sc.Text(); strings.HasPrefix(line, "data: ") && strings.Contains(line, `"role":"assistant"`) {
+ got = line
+ break
+ }
+ }
+ res.Body.Close()
+ if has := strings.Contains(got, `"lookups"`); has != (name == "drawn") || name == "plain" && !strings.Contains(got, "Sources:") {
+ t.Errorf("%s event: %s", name, got)
+ }
+ }
+}
+
+// Capabilities given as a function are worked out as each call is sent,
+// not when the request began (Astra round 1, P1-4).
+func TestCapabilitiesAtSend(t *testing.T) {
+ f := equipotest.New(t)
+ c := equipo.New(f.URL)
+ cred := signIn(t, f, c)
+ caps := []string{equipo.CapLookupAnswers}
+ ctx := equipo.WithCapabilitiesFunc(context.Background(), func(context.Context) []string { return caps })
+ if _, err := c.Snapshot(ctx, cred.Token); err != nil {
+ t.Fatal(err)
+ }
+ caps = nil
+ if _, err := c.Snapshot(ctx, cred.Token); err != nil {
+ t.Fatal(err)
+ }
+ calls := f.Calls("/api/v1/assistant/snapshot")
+ if len(calls) != 2 || calls[0].Header.Get("Base-Capabilities") != equipo.CapLookupAnswers || calls[1].Header.Get("Base-Capabilities") != "" {
+ t.Errorf("headers %q then %q", calls[0].Header.Get("Base-Capabilities"), calls[1].Header.Get("Base-Capabilities"))
+ }
+}
diff --git a/internal/look/static/app.css b/internal/look/static/app.css
index 3510975..4c126a8 100644
--- a/internal/look/static/app.css
+++ b/internal/look/static/app.css
@@ -569,6 +569,15 @@ aside.ask-panel { position: absolute; top: 16px; right: 16px; bottom: 16px; widt
.choices { display: flex; flex-wrap: wrap; gap: 8px; }
.msg.card p + p { margin-top: -4px; }
.card-link, .msg.coordinator a { color: var(--focus); text-decoration: underline; text-underline-offset: 3px; overflow-wrap: anywhere; }
+/* 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; }
+.msg .lookup-sources .source { display: inline-flex; flex-wrap: wrap; align-items: baseline; gap: 0 6px; min-width: 0; }
+.msg .lookup-sources .source-host { color: var(--haze); font-size: 12.5px; }
/* The person's links keep their bubble's ink, underlined. */
.msg.person a { color: inherit; text-decoration: underline; text-underline-offset: 3px; overflow-wrap: anywhere; }
/* A person's files above their words (ask-files): thumbnails, then a pill
diff --git a/internal/look/static/ask.js b/internal/look/static/ask.js
index 7863189..211aad3 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,24 +318,32 @@ 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)) {
+ for (const m of text.matchAll(links ? linkRE : plainLinkRE)) {
let end = m.index + m[0].length, label = m[1], target = m[2];
if (label === undefined) {
target = m[0].replace(/[.,;:!?]+$/, "");
end = m.index + target.length;
label = target;
}
+ if (!links) {
+ // An address is text, whatever it is: no URL check decides how
+ // it is drawn.
+ emphasis(el, text.slice(last, m.index));
+ el.append(text.slice(m.index, end));
+ last = end;
+ continue;
+ }
const href = webURL(target);
if (!href) continue;
emphasis(el, text.slice(last, m.index));
@@ -406,6 +416,63 @@ 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).
+ // Whitespace is spelled out (lookupSpace in ask_cards.go), and the u
+ // flag counts characters, not UTF-16 units, as Go and the app do.
+ const lookupSpace = "\\t\\n\\f\\r \\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000";
+ const mdLinkRE = new RegExp(`\\[([^\\[\\]\\n]{1,300})\\]\\(([^()${lookupSpace}]{1,1000})\\)`, "gu");
+ const plainLinkRE = new RegExp(`\\[([^\\[\\]\\n]{1,300})\\]\\(([^()${lookupSpace}]{1,1000})\\)|https?:\\/\\/[^${lookupSpace}<>()\\[\\]"']+`, "gu");
+ 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
@@ -788,7 +855,7 @@ function start(root) {
header.append(stateMark(c.state), h3, close);
view.append(header, para("jv-stage", c.result || ""));
if (c.detail) view.append(para("jv-detail", c.detail));
- if (c.state === "paused" && c.carry_on === true) view.append(carryOn(c));
+ if ((c.state === "paused" || c.state === "stopped") && c.carry_on === true) view.append(carryOn(c));
const ended = document.createElement("ol");
ended.className = "jv-cards";
view.append(ended);
@@ -825,11 +892,16 @@ function start(root) {
b.className = "btn ghost";
b.type = "submit";
b.textContent = "Carry on now";
- const note = document.createElement("small");
- note.textContent = "Uses your other plan, at no extra cost.";
const error = para("jv-error", "");
error.setAttribute("role", "status");
- form.append(rev, b, note, error);
+ form.append(rev, b);
+ // A held job (stopped) carries on on the same plan: no note.
+ if (c.state === "paused") {
+ const note = document.createElement("small");
+ note.textContent = "Uses your other plan, at no extra cost.";
+ form.append(note);
+ }
+ form.append(error);
return form;
}
diff --git a/internal/store/askclients.go b/internal/store/askclients.go
new file mode 100644
index 0000000..55d370d
--- /dev/null
+++ b/internal/store/askclients.go
@@ -0,0 +1,80 @@
+package store
+
+import (
+ "context"
+ "database/sql"
+ "time"
+)
+
+// AskClient is one native app of a member's: what it last said it can
+// draw (a comma-separated list, Base-Client-Capabilities) and when.
+type AskClient struct {
+ Client string
+ Caps string
+ SeenAt time.Time
+}
+
+// SeeAskClient records that the member numbered member's native client
+// called with caps, replacing what it said before.
+func SeeAskClient(ctx context.Context, db *sql.DB, member int64, client, caps string) error {
+ _, err := db.ExecContext(ctx, `INSERT INTO ask_clients (member_id, client, caps, seen_at) VALUES (?, ?, ?, ?)
+ ON CONFLICT (member_id, client) DO UPDATE SET caps = excluded.caps, seen_at = excluded.seen_at`,
+ member, client, caps, time.Now().UTC())
+ return err
+}
+
+// AskClients are the member numbered member's native clients seen since
+// since.
+func AskClients(ctx context.Context, db *sql.DB, member int64, since time.Time) ([]AskClient, error) {
+ rows, err := db.QueryContext(ctx, `SELECT client, caps, seen_at FROM ask_clients WHERE member_id = ? AND seen_at >= ?
+ ORDER BY client`, member, since.UTC())
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ var out []AskClient
+ for rows.Next() {
+ var c AskClient
+ if err := rows.Scan(&c.Client, &c.Caps, &c.SeenAt); err != nil {
+ return nil, err
+ }
+ out = append(out, c)
+ }
+ return out, rows.Err()
+}
+
+// TouchAskClient records that the member numbered member's native client
+// called without saying what it draws (a write): a client seen for the
+// first time draws nothing, and one seen before keeps what it last said,
+// seen now.
+func TouchAskClient(ctx context.Context, db *sql.DB, member int64, client string) error {
+ _, err := db.ExecContext(ctx, `INSERT INTO ask_clients (member_id, client, caps, seen_at) VALUES (?, ?, '', ?)
+ ON CONFLICT (member_id, client) DO UPDATE SET seen_at = excluded.seen_at`, member, client, time.Now().UTC())
+ return err
+}
+
+// ForgetAskClient removes what the member numbered member's client last
+// said, so it counts as a client Base knows nothing of (UnseenNativeClients).
+func ForgetAskClient(ctx context.Context, db *sql.DB, member int64, client string) error {
+ _, err := db.ExecContext(ctx, `DELETE FROM ask_clients WHERE member_id = ? AND client = ?`, member, client)
+ return err
+}
+
+// UnseenNativeClients counts the live native sessions (method, created
+// after since, not expired at now) of the Oficina accounts linked to the
+// member numbered member that have no ask_clients row: apps Base has
+// never heard say what they draw. Without Oficina ID sign-in there are
+// none.
+func UnseenNativeClients(ctx context.Context, db *sql.DB, member int64, method string, since, now time.Time) (int, error) {
+ var tables int
+ if err := db.QueryRowContext(ctx, `SELECT count(*) FROM sqlite_master WHERE type = 'table' AND name IN ('home_identity_links', 'sessions')`).Scan(&tables); err != nil || tables < 2 {
+ return 0, err
+ }
+ var n int
+ err := db.QueryRowContext(ctx, `SELECT count(*) FROM sessions s
+ WHERE s.method = ? AND s.created_at > ? AND s.expires_at > ?
+ AND s.subject IN (SELECT subject FROM home_identity_links WHERE person_id = ?)
+ AND NOT EXISTS (SELECT 1 FROM ask_clients c WHERE c.member_id = ? AND c.client = s.token_hash)`,
+ method, since.UTC().Format(time.RFC3339), now.UTC().Format(time.RFC3339), member, member).Scan(&n)
+ return n, err
+}
diff --git a/internal/store/askclients_test.go b/internal/store/askclients_test.go
new file mode 100644
index 0000000..f2ffde1
--- /dev/null
+++ b/internal/store/askclients_test.go
@@ -0,0 +1,47 @@
+package store
+
+import (
+ "context"
+ "testing"
+ "time"
+)
+
+// Each native client keeps only the newest capabilities it called with,
+// and AskClients lists only those seen since the time asked for.
+func TestSeeAskClientNewest(t *testing.T) {
+ ctx, db := context.Background(), open(t)
+ if err := SeeAskClient(ctx, db, 7, "phone", ""); err != nil {
+ t.Fatal(err)
+ }
+ if err := SeeAskClient(ctx, db, 7, "phone", "lookup_answers"); err != nil {
+ t.Fatal(err)
+ }
+ if err := SeeAskClient(ctx, db, 7, "mac", ""); err != nil {
+ t.Fatal(err)
+ }
+ if err := SeeAskClient(ctx, db, 8, "phone", "other"); err != nil {
+ t.Fatal(err)
+ }
+ got, err := AskClients(ctx, db, 7, time.Now().Add(-time.Hour))
+ if err != nil {
+ t.Fatal(err)
+ }
+ caps := map[string]string{}
+ for _, c := range got {
+ caps[c.Client] = c.Caps
+ }
+ if len(got) != 2 || caps["phone"] != "lookup_answers" || caps["mac"] != "" {
+ t.Fatalf("member 7's clients = %+v", got)
+ }
+ // Nothing was seen after now.
+ if got, err := AskClients(ctx, db, 7, time.Now().Add(time.Minute)); err != nil || len(got) != 0 {
+ t.Fatalf("clients seen in the future = %+v, %v", got, err)
+ }
+ // A row seen long ago is left out.
+ if _, err := db.Exec(`UPDATE ask_clients SET seen_at = ? WHERE member_id = 7 AND client = 'mac'`, time.Now().Add(-31*24*time.Hour)); err != nil {
+ t.Fatal(err)
+ }
+ if got, err := AskClients(ctx, db, 7, time.Now().Add(-30*24*time.Hour)); err != nil || len(got) != 1 || got[0].Client != "phone" {
+ t.Fatalf("clients seen in the last 30 days = %+v, %v", got, err)
+ }
+}
diff --git a/internal/store/migrations/0013_ask_clients.sql b/internal/store/migrations/0013_ask_clients.sql
new file mode 100644
index 0000000..0ea1966
--- /dev/null
+++ b/internal/store/migrations/0013_ask_clients.sql
@@ -0,0 +1,6 @@
+-- ask_clients: what each of a member's native apps last said it can draw
+-- (Base-Client-Capabilities), so Base tells Equipo only what every client
+-- the member uses can show. member_id is the member's number; client is
+-- the app's native session (its token's hash, never the token). Web
+-- sessions are not recorded: the web is Base's own and always can.
+CREATE TABLE ask_clients (member_id integer NOT NULL, client text NOT NULL, caps text NOT NULL DEFAULT '', seen_at datetime NOT NULL, PRIMARY KEY (member_id, client));
diff --git a/internal/web/app.go b/internal/web/app.go
index d3d7e2e..6f429c9 100644
--- a/internal/web/app.go
+++ b/internal/web/app.go
@@ -62,6 +62,8 @@ type app struct {
oficina *oficina
// ask is "Ask Base anything", nil when cfg.EquipoOrigin is empty.
ask *asker
+ // unrecorded are native clients Base couldn't record (ask_caps.go).
+ unrecorded clientsUnrecorded
}
// App builds Base's router. d is rastrillo's database handle (auth and
@@ -85,7 +87,7 @@ func App(d *db.DB, cfg config.Config, mailer mail.Sender, inst Installer, logger
}
// newKey gives each chat form its own request key when the page is
// drawn; startedText says when a job started, as of then.
- pages, err := look.NewRenderer(sub, template.FuncMap{"newKey": equipo.NewKey, "fileSize": fileSize,
+ pages, err := look.NewRenderer(sub, template.FuncMap{"newKey": equipo.NewKey, "fileSize": fileSize, "lookupAnswer": lookupMarkdown, "sourceHost": sourceHost,
"startedText": func(at *time.Time) string { return startedText(*at, time.Now(), cfg.Timezone) }})
if err != nil {
return nil, err
@@ -197,6 +199,9 @@ func App(d *db.DB, cfg config.Config, mailer mail.Sender, inst Installer, logger
r.Post(passkeyDoor.FinishPath, a.pk.DiscoverFinish)
r.Group(func(r chi.Router) {
r.Use(a.requireMember)
+ if a.ask != nil {
+ r.Use(a.withAskCaps)
+ }
r.Get("/", a.home)
r.Get("/people", a.people)
r.Post("/people", a.invite)
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
new file mode 100644
index 0000000..c7b8b2a
--- /dev/null
+++ b/internal/web/ask_caps.go
@@ -0,0 +1,241 @@
+package web
+
+import (
+ "context"
+ "net/http"
+ "slices"
+ "strings"
+ "sync"
+ "time"
+
+ "amadan.net/oficina/home/connect"
+ "amadan.net/rastrillo/rastrillo/sessions"
+
+ "amadan.net/oficina/base/internal/equipo"
+ "amadan.net/oficina/base/internal/store"
+)
+
+// 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.
+const clientWindow = 30 * 24 * time.Hour
+
+// clientCaps reads a request's Base-Client-Capabilities: native is true
+// for the native app's session, caps are the known values it named, in
+// KnownCapabilities' order. A web session is never native.
+func clientCaps(r *http.Request) (native bool, caps []string) {
+ s, ok := sessions.Current(r)
+ if !ok || s.Method != connect.NativeMethod {
+ return false, nil
+ }
+ said := map[string]bool{}
+ for _, v := range append(r.Header.Values(clientCapsHeader), r.URL.Query()[clientCapsParam]...) {
+ for _, c := range strings.Split(v, ",") {
+ said[strings.TrimSpace(c)] = true
+ }
+ }
+ for _, c := range equipo.KnownCapabilities {
+ if said[c] {
+ caps = append(caps, c)
+ }
+ }
+ return true, caps
+}
+
+// askCaps are the capabilities Base tells Equipo for the member numbered
+// member: every known one, but those a native client of theirs seen in
+// the last 30 days last called without. A read error withholds them all,
+// and so does a client of theirs Base couldn't record (clientsDown).
+func (a *app) askCaps(ctx context.Context, member int64) []string {
+ // Worked out under the member's lock, so no record of theirs is
+ // half made meanwhile.
+ m := a.memberLock(member)
+ m.Lock()
+ defer m.Unlock()
+ if a.clientsDown(member) {
+ return nil
+ }
+ // An app Base has never heard from draws nothing.
+ now := time.Now()
+ if unseen, err := store.UnseenNativeClients(ctx, a.db, member, connect.NativeMethod, now.Add(-connect.NativeLifetime), now); err != nil || unseen > 0 {
+ if err != nil {
+ a.logger.Error("ask: native sessions", "err", err)
+ }
+ return nil
+ }
+ clients, err := store.AskClients(ctx, a.db, member, time.Now().Add(-clientWindow))
+ if err != nil {
+ a.logger.Error("ask: clients", "err", err)
+ return nil
+ }
+ var out []string
+ for _, c := range equipo.KnownCapabilities {
+ ok := true
+ for _, cl := range clients {
+ ok = ok && slices.Contains(strings.Split(cl.Caps, ","), c)
+ }
+ if ok {
+ out = append(out, c)
+ }
+ }
+ return out
+}
+
+// clientsUnrecorded holds, per member number, the native clients whose
+// last request Base couldn't record: while any is held, the member is
+// told to draw nothing. It lives in memory: a restart forgets it, and
+// the client's next request records it.
+type clientsUnrecorded struct {
+ mu sync.Mutex
+ held map[int64]map[string]time.Time
+ // locks holds a *sync.Mutex per member number (recordClient).
+ locks sync.Map
+}
+
+// recordClient records a native request of the member numbered member's
+// (its session's token hash is the client): on one of the two reads,
+// what it says it draws, else only that it was seen (a first write draws
+// nothing). Base's knowledge only ever narrows on a failure: a read Base
+// couldn't record removes what the client said before, so it counts as
+// unseen (UnseenNativeClients), and holds the member back in memory as
+// well, until a read of that client's is recorded. A write never lifts
+// that. One member's requests are recorded one at a time.
+func (a *app) recordClient(ctx context.Context, r *http.Request, member int64, said []string) {
+ c, err := r.Cookie(a.sess.CookieName())
+ if err != nil {
+ a.logger.Error("ask: see client", "err", err)
+ a.clientRecorded(member, "", false)
+ return
+ }
+ client := sessions.HashToken(c.Value)
+ m := a.memberLock(member)
+ m.Lock()
+ defer m.Unlock()
+ // A client going away mid-request doesn't stop its record (nor its
+ // undoing on a failure), which stays bounded.
+ ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), recordWait)
+ defer cancel()
+ if !recordsClient(r) {
+ if err := store.TouchAskClient(ctx, a.db, member, client); err != nil {
+ a.logger.Error("ask: see client", "err", err)
+ a.clientRecorded(member, client, false)
+ }
+ return
+ }
+ if err := store.SeeAskClient(ctx, a.db, member, client, strings.Join(said, ",")); err != nil {
+ a.logger.Error("ask: see client", "err", err)
+ if err := store.ForgetAskClient(ctx, a.db, member, client); err != nil {
+ a.logger.Error("ask: forget client", "err", err)
+ }
+ a.clientRecorded(member, client, false)
+ return
+ }
+ a.clientRecorded(member, client, true)
+}
+
+// recordWait bounds recording one client's request.
+const recordWait = 5 * time.Second
+
+// memberLock is the member numbered member's lock: their clients are
+// recorded, and their capabilities worked out, one at a time.
+func (a *app) memberLock(member int64) *sync.Mutex {
+ m, _ := a.unrecorded.locks.LoadOrStore(member, &sync.Mutex{})
+ return m.(*sync.Mutex)
+}
+
+// clientRecorded notes whether client's request was recorded for the
+// member numbered member.
+func (a *app) clientRecorded(member int64, client string, ok bool) {
+ u := &a.unrecorded
+ u.mu.Lock()
+ defer u.mu.Unlock()
+ if ok {
+ delete(u.held[member], client)
+ if len(u.held[member]) == 0 {
+ delete(u.held, member)
+ }
+ return
+ }
+ if u.held == nil {
+ u.held = map[int64]map[string]time.Time{}
+ }
+ if u.held[member] == nil {
+ u.held[member] = map[string]time.Time{}
+ }
+ u.held[member][client] = time.Now()
+}
+
+// clientsDown reports whether a native client of the member numbered
+// member went unrecorded.
+func (a *app) clientsDown(member int64) bool {
+ a.unrecorded.mu.Lock()
+ defer a.unrecorded.mu.Unlock()
+ for client, at := range a.unrecorded.held[member] {
+ // A hold lasts as long as a client's word does.
+ if time.Since(at) < clientWindow {
+ return true
+ }
+ delete(a.unrecorded.held[member], client)
+ }
+ return false
+}
+
+// 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, and every other native /ask/* request as a sign of
+// life (a client first seen writing draws nothing; 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 {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ me, ok := CurrentMember(r)
+ if !ok {
+ next.ServeHTTP(w, r)
+ return
+ }
+ ctx := r.Context()
+ n, err := store.MemberNumber(ctx, a.db, me.ID)
+ if err != nil {
+ a.logger.Error("ask: member number", "err", err)
+ next.ServeHTTP(w, r)
+ return
+ }
+ if native, said := clientCaps(r); native && strings.HasPrefix(r.URL.Path, "/ask/") {
+ a.recordClient(ctx, r, n, said)
+ }
+ // Worked out as each call to Equipo is sent, not now.
+ next.ServeHTTP(w, r.WithContext(equipo.WithCapabilitiesFunc(ctx, func(ctx context.Context) []string { return a.askCaps(ctx, n) })))
+ })
+}
+
+// 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_caps_internal_test.go b/internal/web/ask_caps_internal_test.go
new file mode 100644
index 0000000..c0ff8f4
--- /dev/null
+++ b/internal/web/ask_caps_internal_test.go
@@ -0,0 +1,44 @@
+package web
+
+import (
+ "context"
+ "log/slog"
+ "testing"
+ "time"
+)
+
+// Capabilities are worked out under the member's lock: never while one of
+// their clients is half recorded (Astra round 3).
+func TestAskCapsWaitsForRecord(t *testing.T) {
+ a := &app{logger: slog.New(slog.DiscardHandler)}
+ a.clientRecorded(7, "client", false)
+ m := a.memberLock(7)
+ m.Lock()
+ done := make(chan []string, 1)
+ go func() { done <- a.askCaps(context.Background(), 7) }()
+ select {
+ case <-done:
+ t.Fatal("askCaps didn't wait for the member's record")
+ case <-time.After(50 * time.Millisecond):
+ }
+ m.Unlock()
+ if got := <-done; got != nil {
+ t.Errorf("a held member's capabilities: %v", got)
+ }
+}
+
+// A hold on a client Base couldn't record lasts as long as a client's
+// word does, 30 days, and no longer (Astra round 3).
+func TestAskCapsHoldExpires(t *testing.T) {
+ a := &app{logger: slog.New(slog.DiscardHandler)}
+ a.clientRecorded(7, "client", false)
+ if !a.clientsDown(7) || a.clientsDown(8) {
+ t.Fatal("hold not kept for its member alone")
+ }
+ a.unrecorded.mu.Lock()
+ a.unrecorded.held[7]["client"] = time.Now().Add(-clientWindow - time.Minute)
+ a.unrecorded.mu.Unlock()
+ if a.clientsDown(7) {
+ t.Error("a hold outlived the client window")
+ }
+}
diff --git a/internal/web/ask_cards.go b/internal/web/ask_cards.go
index e20f534..9bd0cf6 100644
--- a/internal/web/ask_cards.go
+++ b/internal/web/ask_cards.go
@@ -3,6 +3,7 @@ package web
import (
"html"
"html/template"
+ "net/url"
"regexp"
"strconv"
"strings"
@@ -32,7 +33,33 @@ func richText(text string) template.HTML { return richMarkdown(text, false) }
// same.
func personText(text string) template.HTML { return richMarkdown(text, true) }
-func richMarkdown(text string, strict bool) template.HTML {
+func richMarkdown(text string, strict bool) template.HTML { return markdown(text, strict, true) }
+
+// lookupSpace is the whitespace a lookup's answer ends an address at,
+// spelled out so Go, ask.js (with its u flag) and the app's ICU read it
+// alike: ASCII's, and Unicode's spaces and line breaks.
+const lookupSpace = `\t\n\f\r \x{00a0}\x{1680}\x{2000}-\x{200a}\x{2028}\x{2029}\x{202f}\x{205f}\x{3000}`
+
+// mdLinkRE is a Markdown link, [label](target), in a lookup's answer;
+// plainLinkRE is linkRE for one, with lookupSpace for its whitespace.
+var (
+ mdLinkRE = regexp.MustCompile(`\[([^\[\]\n]{1,300})\]\(([^()` + lookupSpace + `]{1,1000})\)`)
+ plainLinkRE = regexp.MustCompile(`\[([^\[\]\n]{1,300})\]\(([^()` + lookupSpace + `]{1,1000})\)|https?://[^` + lookupSpace + `<>()\[\]"']+`)
+)
+
+// lookupMarkdown is a lookup's answer as HTML: personText's Markdown
+// (lists, and bold and italics at word boundaries) with no links at all,
+// since the only links under a reply are the sources Equipo recorded
+// (spec 2026-11-26-assistant-abilities §4.6). A Markdown link shows as
+// its words; a bare URL or an autolink stays as text. ask.js
+// (lookupMarkdown) and the app (LookupMarkdown) do the same.
+func lookupMarkdown(text string) template.HTML {
+ return markdown(mdLinkRE.ReplaceAllString(asPageReads.Replace(text), "$1"), true, false)
+}
+
+// markdown is richMarkdown, with links drawn only when links is set
+// (otherwise every address is text).
+func markdown(text string, strict, links bool) template.HTML {
var b strings.Builder
lines := strings.Split(asPageReads.Replace(text), "\n")
for i := 0; i < len(lines); {
@@ -42,7 +69,7 @@ func richMarkdown(text string, strict bool) template.HTML {
for j < len(lines) && !isListLine(lines[j]) {
j++
}
- inline(&b, strings.Join(lines[i:j], "\n"), strict)
+ inline(&b, strings.Join(lines[i:j], "\n"), strict, links)
i = j
continue
}
@@ -57,7 +84,7 @@ func richMarkdown(text string, strict bool) template.HTML {
break
}
b.WriteString("<li>")
- inline(&b, item, strict)
+ inline(&b, item, strict, links)
b.WriteString("</li>")
}
b.WriteString("</" + kind + ">")
@@ -87,14 +114,19 @@ func listLine(line string) (kind string, n int, item string) {
func isListLine(line string) bool { k, _, _ := listLine(line); return k != "" }
// inline writes text with its safe links, and bold and italics between
-// them.
-func inline(b *strings.Builder, text string, strict bool) {
+// them. Without links, each address is written as text, untouched by
+// emphasis.
+func inline(b *strings.Builder, text string, strict, links bool) {
emphasis := emphasis
if strict {
emphasis = strictEmphasis
}
+ re := linkRE
+ if !links {
+ re = plainLinkRE
+ }
last := 0
- for _, m := range linkRE.FindAllStringSubmatchIndex(text, -1) {
+ for _, m := range re.FindAllStringSubmatchIndex(text, -1) {
end, label, target := m[1], "", ""
if m[2] >= 0 {
label, target = text[m[2]:m[3]], text[m[4]:m[5]]
@@ -102,6 +134,14 @@ func inline(b *strings.Builder, text string, strict bool) {
target = strings.TrimRight(text[m[0]:m[1]], ".,;:!?")
end, label = m[0]+len(target), target
}
+ if !links {
+ // An address is text, whatever it is: no URL check decides
+ // how it is drawn.
+ emphasis(b, text[last:m[0]])
+ b.WriteString(html.EscapeString(text[m[0]:end]))
+ last = end
+ continue
+ }
href := equipo.WebURL(target)
if href == "" {
continue
@@ -206,5 +246,16 @@ func wordByte(c byte) bool {
// Rich is an Assistant's line with its links (richText), for templates.
func (v askView) Rich(text string) template.HTML { return richText(text) }
+// sourceHost is u's host name as a source line shows it after the
+// source's title, without a leading "www.". ask.js has the same
+// (sourceHost).
+func sourceHost(u string) string {
+ p, err := url.Parse(u)
+ if err != nil {
+ return ""
+ }
+ return strings.TrimPrefix(strings.ToLower(p.Hostname()), "www.")
+}
+
// RichPerson is the person's own message (personText), for templates.
func (v askView) RichPerson(text string) template.HTML { return personText(text) }
diff --git a/internal/web/ask_connect.go b/internal/web/ask_connect.go
index daa6512..d2f5e87 100644
--- a/internal/web/ask_connect.go
+++ b/internal/web/ask_connect.go
@@ -333,7 +333,7 @@ func (a *app) registerHost(ctx context.Context, me store.Member, dev, token stri
func (a *app) hostFor(ctx context.Context, me store.Member, dev, token string, fresh bool) {
ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), storeTimeout)
defer cancel()
- a.zoneFor(me, token, fresh)
+ a.zoneFor(ctx, me, token, fresh)
defer a.lockMember(me.ID)()
if !fresh {
done, err := store.HostRegistered(ctx, a.db, me.ID)
@@ -375,7 +375,7 @@ type zoneTold struct {
// connection (fresh). It never holds up the page or the member's lock:
// the call runs on its own, bounded by zoneWait. After a failure (5xx,
// 429, 404, no answer in time) it is tried again no sooner than zoneRetry.
-func (a *app) zoneFor(me store.Member, token string, fresh bool) {
+func (a *app) zoneFor(parent context.Context, me store.Member, token string, fresh bool) {
if a.ask.zone == "" {
return
}
@@ -397,8 +397,9 @@ func (a *app) zoneFor(me store.Member, token string, fresh bool) {
}
z.busy = true
a.ask.zoneMu.Unlock()
+ caps := equipo.CapabilitiesFuncOf(parent)
go func() {
- ctx, cancel := context.WithTimeout(context.Background(), zoneWait)
+ ctx, cancel := context.WithTimeout(equipo.WithCapabilitiesFunc(context.Background(), caps), zoneWait)
defer cancel()
err := a.ask.client.SetTimeZone(ctx, token, a.ask.zone)
var e *equipo.Error
diff --git a/internal/web/ask_internal_test.go b/internal/web/ask_internal_test.go
index 97d3bf0..2ce7f02 100644
--- a/internal/web/ask_internal_test.go
+++ b/internal/web/ask_internal_test.go
@@ -110,12 +110,12 @@ func TestZoneBacksOffOn404(t *testing.T) {
}
me := store.Member{ID: "m1"}
start := time.Now()
- a.zoneFor(me, token, false)
+ a.zoneFor(context.Background(), me, token, false)
z := told(t, a, me.ID)
if z.settled != tc.settled || !tc.settled && z.retryAt.Before(start.Add(zoneRetry)) || tc.settled && !z.retryAt.IsZero() {
t.Errorf("%d: settled %v, retry at %v (want settled %v)", tc.status, z.settled, z.retryAt, tc.settled)
}
- a.zoneFor(me, token, false)
+ a.zoneFor(context.Background(), me, token, false)
if n := len(f.Calls("/api/v1/assistant/time-zone")); n != 1 {
t.Errorf("%d: %d calls before the wait is up", tc.status, n)
}
@@ -129,11 +129,11 @@ func TestZoneAgainForAConnectionMidCall(t *testing.T) {
a, f, token := newZoneApp(t)
release := f.HoldTimeZone()
me := store.Member{ID: "m1"}
- a.zoneFor(me, token, true)
+ a.zoneFor(context.Background(), me, token, true)
for len(f.Calls("/api/v1/assistant/time-zone")) == 0 {
time.Sleep(5 * time.Millisecond)
}
- a.zoneFor(me, token, true) // the new connection, mid-call: no second call yet
+ a.zoneFor(context.Background(), me, token, true) // the new connection, mid-call: no second call yet
if n := len(f.Calls("/api/v1/assistant/time-zone")); n != 1 {
t.Fatalf("%d calls while one is in flight", n)
}
@@ -141,9 +141,9 @@ func TestZoneAgainForAConnectionMidCall(t *testing.T) {
if z := told(t, a, me.ID); z.settled {
t.Fatal("the call before the new connection settled it")
}
- a.zoneFor(me, token, false)
+ a.zoneFor(context.Background(), me, token, false)
told(t, a, me.ID)
- a.zoneFor(me, token, false)
+ a.zoneFor(context.Background(), me, token, false)
told(t, a, me.ID)
if n := len(f.Calls("/api/v1/assistant/time-zone")); n != 2 {
t.Errorf("%d calls, want the held one and one for the new connection", n)
diff --git a/internal/web/ask_relay.go b/internal/web/ask_relay.go
index f2c680c..855bb1d 100644
--- a/internal/web/ask_relay.go
+++ b/internal/web/ask_relay.go
@@ -179,7 +179,8 @@ func (a *app) askAnswer(w http.ResponseWriter, r *http.Request) {
}
out.Card, _ = in.Card.CleanAt(a.cfg.Origin)
if in.Message.ID != "" {
- out.Message = &in.Message
+ m := in.Message.Clean()
+ out.Message = &m
}
if in.Turn.ID != "" {
out.Turn = &in.Turn
@@ -270,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)
}
@@ -431,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)
@@ -514,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/templates/partials/chat.html b/internal/web/templates/partials/chat.html
index 265ca91..85f79cc 100644
--- a/internal/web/templates/partials/chat.html
+++ b/internal/web/templates/partials/chat.html
@@ -17,12 +17,12 @@
<ol class="job-cards">{{range .OpenCards}}{{template "ask-card" .}}{{end}}</ol></li>{{end}}
{{/* A job state's mark: working has none (the mark turns, in CSS); the rest are still icons: paused a clock (it carries on by itself), stopped a square (it waits for the person). ask.js has the same paths (marks), and so does the native app (BaseIcon). */}}
{{define "ask-mark"}}{{if eq . "asking"}}<svg viewBox="0 0 24 24"><path d="M9.2 9.2a2.9 2.9 0 0 1 5.6 1c0 2-2.8 2.4-2.8 4.3M12 18.2h.01"/></svg>{{else if eq . "ready"}}<svg viewBox="0 0 24 24"><path d="M8 16L16 8M9.5 8H16v6.5"/></svg>{{else if eq . "done"}}<svg viewBox="0 0 24 24"><path d="M6 12.5l4 4 8-9"/></svg>{{else if eq . "paused"}}<svg viewBox="0 0 24 24"><path d="M19.2 12a7.2 7.2 0 1 1-14.4 0a7.2 7.2 0 1 1 14.4 0zM12 8.6V12l2.4 1.6"/></svg>{{else if eq . "stopped"}}<svg viewBox="0 0 24 24"><path d="M9 7.5h6a1.5 1.5 0 0 1 1.5 1.5v6a1.5 1.5 0 0 1-1.5 1.5H9a1.5 1.5 0 0 1-1.5-1.5V9A1.5 1.5 0 0 1 9 7.5z"/></svg>{{end}}{{end}}
-{{/* The job view, opened from the pill: its title, the status, one sentence more, for a paused job that offers it "Carry on now" (assistant.job.carry_on, with assistant.job.carry_on_note under it: copy review 2026-11-24) posting the card's revision, the job's cards that have ended (each its question and how it ended: ask-jobcard), when it started, and once there is something to see the link to it. The title links to the job's own page in Equipo (Card.Equipo, "Open in Equipo" as its tooltip, an arrow on hover and focus): the only place the chat links there, never a step the person must take. Without scripts it opens in place under the pill; the panel's script makes it a popover beside the pill, or a sheet on a phone, and shows Close (ask.js, jobView). */}}
+{{/* The job view, opened from the pill: its title, the status, one sentence more, for a paused job that offers it "Carry on now" (assistant.job.carry_on, with assistant.job.carry_on_note under it: copy review 2026-11-24), and for a stopped one held while building was off, once it is on again, the same button with no note (abilities plan AD4) posting the card's revision, the job's cards that have ended (each its question and how it ended: ask-jobcard), when it started, and once there is something to see the link to it. The title links to the job's own page in Equipo (Card.Equipo, "Open in Equipo" as its tooltip, an arrow on hover and focus): the only place the chat links there, never a step the person must take. Without scripts it opens in place under the pill; the panel's script makes it a popover beside the pill, or a sheet on a phone, and shows Close (ask.js, jobView). */}}
{{define "ask-jobview"}}<section class="jobview" aria-label="{{.Question}}"><header><span class="state-mark" aria-hidden="true">{{template "ask-mark" .State}}</span>
<h3>{{with .Equipo}}<a class="jv-title" href="{{.URL}}" title="{{.Label}}" target="_blank" rel="noopener">{{$.Question}}<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M9 6h9v9M18 6L7 17"/></svg></a>{{else}}{{.Question}}{{end}}</h3>
<button class="round" type="button" data-job-close aria-label="Close" hidden><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M6 6l12 12M18 6L6 18"/></svg></button></header>
<p class="jv-stage">{{.Result}}</p>{{with .Detail}}<p class="jv-detail">{{.}}</p>{{end}}
-{{- if and (eq .State "paused") .CarryOn}}<form class="jv-act" method="post" action="/ask/cards/{{.ID}}/carry_on"><input type="hidden" name="revision" value="{{.Revision}}"><input type="hidden" name="key" value="{{newKey}}"><button class="btn ghost" type="submit">Carry on now</button><small>Uses your other plan, at no extra cost.</small><p class="jv-error" role="status"></p></form>{{end}}<ol class="jv-cards">{{range .EndedCards}}{{template "ask-jobcard" .}}{{end}}</ol>{{with .StartedAt}}<p class="jv-started">{{startedText .}}</p>{{end}}
+{{- if and (or (eq .State "paused") (eq .State "stopped")) .CarryOn}}<form class="jv-act" method="post" action="/ask/cards/{{.ID}}/carry_on"><input type="hidden" name="revision" value="{{.Revision}}"><input type="hidden" name="key" value="{{newKey}}"><button class="btn ghost" type="submit">Carry on now</button>{{if eq .State "paused"}}<small>Uses your other plan, at no extra cost.</small>{{end}}<p class="jv-error" role="status"></p></form>{{end}}<ol class="jv-cards">{{range .EndedCards}}{{template "ask-jobcard" .}}{{end}}</ol>{{with .StartedAt}}<p class="jv-started">{{startedText .}}</p>{{end}}
{{- if or (eq .State "ready") (eq .State "done")}}{{with .Go}}<a class="jv-go" href="{{.URL}}" target="_blank" rel="noopener">{{.Label}}</a>{{end}}{{end}}</section>{{end}}
{{/* A job's card that has ended, in its view: the question and how it ended, nothing to press. The panel's script draws the same (ask.js, addCard). */}}
{{define "ask-jobcard"}}<li class="jv-card" data-card="{{.ID}}" data-revision="{{.Revision}}" data-for="{{.Job}}"><p class="jv-q">{{.Question}}</p><p class="jv-result">{{.Result}}</p></li>{{end}}
@@ -30,6 +30,8 @@
{{define "ask-files"}}<div class="files" role="group" aria-label="Attached files">{{range .}}{{if eq .Kind "image"}}<a class="thumb" href="/ask/attachments/{{.ID}}" data-attachment="{{.ID}}"><img loading="lazy" src="/ask/attachments/{{.ID}}/preview" alt="{{.Name}}"{{if and .Width .Height}} width="{{.Width}}" height="{{.Height}}"{{end}}></a>{{end}}{{end}}{{range .}}{{if ne .Kind "image"}}<a class="file" href="/ask/attachments/{{.ID}}" download aria-label="{{.Name}}, {{fileSize .Size}}. Download">{{template "ask-file-mark"}}<span class="file-name">{{.Name}}</span><span class="file-size">{{fileSize .Size}}</span></a>{{end}}{{end}}</div>{{end}}
{{/* A file's mark: a page with its corner folded. ask-attach.js has the same path (fileMark). */}}
{{define "ask-file-mark"}}<svg class="file-mark" viewBox="0 0 24 24" aria-hidden="true"><path d="M14 3.5H7.5a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2h9a2 2 0 0 0 2-2V8zM14 3.5V8h4.5"/></svg>{{end}}
+{{/* A lookup under the Assistant's reply: its answer (lookupMarkdown: lists, bold and italics, never a link), then a quiet Sources line (copy ask.sources) with each source's title as a link opening in a new tab, and its host after it. The panel's script draws the same (ask.js, addLookup), and so does the app. */}}
+{{define "ask-lookup"}}<div class="lookup"><div class="lookup-answer">{{lookupAnswer .Answer}}</div><p class="lookup-sources"><span class="lookup-label">Sources</span>{{range .Sources}}<span class="source"><a href="{{.URL}}" target="_blank" rel="noopener noreferrer nofollow">{{or .Title (sourceHost .URL)}}</a><span class="source-host">{{sourceHost .URL}}</span></span>{{end}}</p></div>{{end}}
{{define "ask-body"}}<div class="ask-note" data-when="connect"{{if not (.Shows "connect")}} hidden{{end}}>
<p>Set up Ask Base to start asking.</p>
<form method="post" action="/ask/connect"><input type="hidden" name="next" value="{{.Next}}"><button class="btn" type="submit">Set up Ask Base</button></form>
@@ -47,7 +49,7 @@
</div>
<div class="ask-chat" data-when="ready norunner oldrunner"{{if not (.Shows "ready norunner oldrunner")}} hidden{{end}}>
<div class="log"><ol class="thread" role="log" aria-label="Conversation"{{with .Zone}} data-zone="{{.}}"{{end}} data-mark="{{asset "static/oficina/equipo.svg"}}">
-{{range .Messages}}{{if eq .Role "person"}}<li class="msg person" data-id="{{.ID}}">{{with .Attachments}}{{template "ask-files" .}}{{end}}{{with .Text}}{{$.RichPerson .}}{{end}}</li>{{else}}<li class="msg coordinator" data-id="{{.ID}}">{{$.Rich .Text}}{{range $.OffersAt .ID}}<div class="connect-offer" data-card="{{.ID}}" data-revision="{{.Revision}}">{{template "ask-offer" .}}</div>{{end}}</li>{{end}}
+{{range .Messages}}{{if eq .Role "person"}}<li class="msg person" data-id="{{.ID}}">{{with .Attachments}}{{template "ask-files" .}}{{end}}{{with .Text}}{{$.RichPerson .}}{{end}}</li>{{else}}<li class="msg coordinator" data-id="{{.ID}}">{{$.Rich .Text}}{{range .Lookups}}{{template "ask-lookup" .}}{{end}}{{range $.OffersAt .ID}}<div class="connect-offer" data-card="{{.ID}}" data-revision="{{.Revision}}">{{template "ask-offer" .}}</div>{{end}}</li>{{end}}
{{end}}{{with .Notice}}<li class="ask-notice" data-after="{{$.NoticeAfter}}">{{.}}</li>
{{end}}{{range .Jobs}}{{template "ask-job" .}}
{{end}}{{range .LooseCards}}{{template "ask-card" .}}
diff --git a/internal/web/testdata/lookup.json b/internal/web/testdata/lookup.json
new file mode 100644
index 0000000..af8e8a8
--- /dev/null
+++ b/internal/web/testdata/lookup.json
@@ -0,0 +1,42 @@
+[
+ {
+ "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"
+ },
+ {
+ "text": "[😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀](https://evil.test/) done",
+ "html": "😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀 done"
+ },
+ {
+ "text": "See https://a.test/ *x* and [y](https://b.test/ z)",
+ "html": "See https://a.test/ *x* and [y](https://b.test/ z)"
+ },
+ {
+ "text": "Go https://a.test/x *now* or [z](https://c.test/ q)",
+ "html": "Go https://a.test/x *now* or [z](https://c.test/ q)"
+ },
+ {
+ "text": "See https://a.test/%zz/*x* ok and _y_",
+ "html": "See https://a.test/%zz/*x* ok and <em>y</em>"
+ }
+]
diff --git a/internal/webtest/ask_caps_test.go b/internal/webtest/ask_caps_test.go
new file mode 100644
index 0000000..715123f
--- /dev/null
+++ b/internal/webtest/ask_caps_test.go
@@ -0,0 +1,229 @@
+package webtest
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/url"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/base/internal/equipo"
+ "amadan.net/oficina/base/internal/equipo/equipotest"
+ "amadan.net/oficina/base/internal/store"
+)
+
+// capsOfLast is the Base-Capabilities header of the newest call to path,
+// and whether the header was there at all.
+func capsOfLast(t *testing.T, f *equipotest.Fake, path string) (string, bool) {
+ t.Helper()
+ calls := f.Calls(path)
+ if len(calls) == 0 {
+ t.Fatalf("no call to %s", path)
+ }
+ v, ok := calls[len(calls)-1].Header["Base-Capabilities"]
+ if !ok {
+ return "", false
+ }
+ return strings.Join(v, ","), true
+}
+
+const snapshotPath = "/api/v1/assistant/snapshot"
+
+// wantCaps fails unless the newest call to path carried
+// Base-Capabilities: lookup_answers (have) or none at all (!have).
+func wantCaps(t *testing.T, f *equipotest.Fake, path, where string, have bool) {
+ t.Helper()
+ caps, ok := capsOfLast(t, f, path)
+ if have && (!ok || caps != equipo.CapLookupAnswers) || !have && ok {
+ t.Errorf("%s: Base-Capabilities %q (%v), want it %v", where, caps, ok, have)
+ }
+}
+
+// A member who uses only the web is told, on Equipo's every call, that
+// Base draws lookup answers.
+func TestAskCapsWebOnly(t *testing.T) {
+ a, f := newAskApp(t)
+ a.approveEquipo(f)
+ if r := a.get("/ask"); r.Code != 200 {
+ t.Fatalf("/ask: %d", r.Code)
+ }
+ wantCaps(t, f, snapshotPath, "the web", true)
+}
+
+// One native app that called without saying it draws lookups withholds
+// the capability for the member, on the web too, until it calls with it,
+// or until it was last seen more than 30 days ago.
+func TestAskCapsWithheldForOldNative(t *testing.T) {
+ web, app, f := newNativeAskApp(t)
+ web.approveEquipo(f)
+ want := func(where string, have bool) { t.Helper(); wantCaps(t, f, snapshotPath, where, have) }
+ app.askState()
+ want("an old app's own read", false)
+ if r := web.get("/ask"); r.Code != 200 {
+ t.Fatalf("/ask: %d", r.Code)
+ }
+ want("the web, while the old app is in use", false)
+
+ app.header = http.Header{"Base-Client-Capabilities": {"job_actions, " + equipo.CapLookupAnswers}}
+ app.askState()
+ want("the app, upgraded", true)
+ 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)
+ }
+ web.get("/ask")
+ want("the web, the old app unseen for 31 days", true)
+}
+
+// Every relayed call carries the header: the snapshot, the event stream,
+// a message, a card's answer, Carry on now and the time zone. The host's
+// registration carries it too, with its body as it always was.
+func TestCapabilityHeaderOnEveryCall(t *testing.T) {
+ web, app, f := newNativeAskApp(t)
+ // The member's app says what it draws before they connect.
+ app.header = http.Header{"Base-Client-Capabilities": {equipo.CapLookupAnswers}}
+ app.askState()
+ web.approveEquipo(f)
+ web.get("/ask")
+ for i := 0; i < 200 && len(f.Calls("/api/v1/assistant/time-zone")) == 0; i++ {
+ time.Sleep(10 * time.Millisecond)
+ }
+ card := f.AskQuestion("Which colour?", "Blue", "Green")
+ job := f.AskJob("A form")
+ f.PauseJob(job, "Paused until 21:00", "It has reached the limit on its plan for now.", true)
+ if r := web.post("/ask/messages", url.Values{"text": {"Hello"}, "key": {"caps-1"}}); r.Code != 303 {
+ t.Fatalf("send: %d %s", r.Code, r.Body)
+ }
+ if r := web.post("/ask/cards/"+card+"/answer", url.Values{"choice": {"Blue"}, "revision": {"1"}, "key": {"caps-2"}}); r.Code != 303 {
+ t.Fatalf("answer: %d %s", r.Code, r.Body)
+ }
+ rev := int64(3) // asked, paused, carry_on offered: the fake's revisions
+ if r := web.post("/ask/cards/"+job+"/carry_on", url.Values{"revision": {strconv.FormatInt(rev, 10)}, "key": {"caps-3"}}); r.Code != 303 {
+ t.Fatalf("carry on: %d %s", r.Code, r.Body)
+ }
+ web.events(t, "0", func(got []sseFrame) bool { return len(got) >= 2 })
+ for _, p := range []string{snapshotPath, "/api/v1/assistant/events", "/api/v1/assistant/messages",
+ "/api/v1/assistant/cards/" + card + "/answer", "/api/v1/assistant/cards/" + job + "/carry_on",
+ "/api/v1/assistant/time-zone", "/api/v1/assistant/host"} {
+ wantCaps(t, f, p, p, true)
+ }
+ hosts := f.Hosts()
+ var body map[string]string
+ if err := json.Unmarshal([]byte(hosts[len(hosts)-1].Body), &body); err != nil || len(body) != 2 || body["origin"] == "" || body["token"] == "" {
+ t.Errorf("host body %q: %v", hosts[len(hosts)-1].Body, err)
+ }
+ n, err := store.MemberNumber(context.Background(), web.DB, web.ownerID())
+ if err != nil {
+ t.Fatal(err)
+ }
+ // The web is never recorded as a client: only the app is.
+ if got, err := store.AskClients(context.Background(), web.DB, n, time.Time{}); err != nil || len(got) != 1 {
+ t.Errorf("clients recorded: %+v %v", got, err)
+ }
+}
+
+// A native session Base has never heard from on /ask (an app opened
+// before this Base, or one whose record failed before a restart) holds
+// the member back (Astra round 2); one whose first request is a write is
+// recorded as drawing nothing (round 1), and a write keeps an old app's
+// 30-day window open.
+func TestAskCapsNativeWriteFirst(t *testing.T) {
+ web, app, f := newNativeAskApp(t)
+ web.approveEquipo(f)
+ web.get("/ask")
+ wantCaps(t, f, snapshotPath, "an app never heard from", false)
+ if r := app.nativeForm("/ask/messages", url.Values{"text": {"Hi"}, "key": {"first-w"}}); r.Code != 200 {
+ t.Fatalf("send: %d %s", r.Code, r.Body)
+ }
+ web.get("/ask")
+ wantCaps(t, f, snapshotPath, "an app seen only writing", false)
+ old := time.Now().Add(-29 * 24 * time.Hour).UTC()
+ if _, err := web.DB.Exec(`UPDATE ask_clients SET seen_at = ?`, old); err != nil {
+ t.Fatal(err)
+ }
+ if r := app.nativeForm("/ask/messages", url.Values{"text": {"Again"}, "key": {"first-w2"}}); r.Code != 200 {
+ t.Fatalf("send: %d %s", r.Code, r.Body)
+ }
+ var seen time.Time
+ if err := web.DB.QueryRow(`SELECT seen_at FROM ask_clients`).Scan(&seen); err != nil || !seen.After(old.Add(time.Hour)) {
+ t.Errorf("a write didn't keep the app's window open: %v %v", seen, err)
+ }
+ app.header = http.Header{"Base-Client-Capabilities": {equipo.CapLookupAnswers}}
+ app.askState()
+ web.get("/ask")
+ wantCaps(t, f, snapshotPath, "once the app said so", true)
+}
+
+// When Base can't record what an app said, the member is told to draw
+// nothing until it can, on every request, not just that one (Astra
+// round 1, P1-3).
+func TestAskCapsRecordFailureHoldsBack(t *testing.T) {
+ web, app, f := newNativeAskApp(t)
+ web.approveEquipo(f)
+ want := func(where string, have bool) { t.Helper(); web.get("/ask"); wantCaps(t, f, snapshotPath, where, have) }
+ app.header = http.Header{"Base-Client-Capabilities": {equipo.CapLookupAnswers}}
+ app.askState()
+ want("the app says it draws them", true)
+ for _, q := range []string{
+ `CREATE TRIGGER no_insert BEFORE INSERT ON ask_clients BEGIN SELECT RAISE(ABORT, 'refused'); END`,
+ `CREATE TRIGGER no_update BEFORE UPDATE ON ask_clients BEGIN SELECT RAISE(ABORT, 'refused'); END`,
+ } {
+ if _, err := web.DB.Exec(q); err != nil {
+ t.Fatal(err)
+ }
+ }
+ // Downgraded, its read can't be recorded: held back from then on,
+ // and not only in this process (the app's row is gone, and its
+ // session is one Base knows nothing of).
+ app.header = nil
+ app.askState()
+ want("the app's downgrade went unrecorded", false)
+ var rows int
+ if err := web.DB.QueryRow(`SELECT count(*) FROM ask_clients`).Scan(&rows); err != nil || rows != 0 {
+ t.Errorf("%d rows left for a client Base couldn't record: %v", rows, err)
+ }
+ // A write that can't be recorded either holds it back too, and one
+ // that can doesn't undo that.
+ if r := app.nativeForm("/ask/messages", url.Values{"text": {"Hi"}, "key": {"held-w"}}); r.Code != 200 {
+ t.Fatalf("send: %d", r.Code)
+ }
+ want("after a write", false)
+ for _, q := range []string{`DROP TRIGGER no_insert`, `DROP TRIGGER no_update`} {
+ if _, err := web.DB.Exec(q); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if r := app.nativeForm("/ask/messages", url.Values{"text": {"Again"}, "key": {"held-w2"}}); r.Code != 200 {
+ t.Fatalf("send: %d", r.Code)
+ }
+ want("after a recorded write", false)
+ app.header = http.Header{"Base-Client-Capabilities": {equipo.CapLookupAnswers}}
+ app.askState()
+ want("once recorded", true)
+}
diff --git a/internal/webtest/ask_lookup_test.go b/internal/webtest/ask_lookup_test.go
new file mode 100644
index 0000000..dc7244f
--- /dev/null
+++ b/internal/webtest/ask_lookup_test.go
@@ -0,0 +1,132 @@
+package webtest
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/url"
+ "regexp"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/base/internal/equipo"
+)
+
+// replyOf is the Assistant's last line in a page: its <li> and what is in it.
+var replyRE = regexp.MustCompile(`(?s)<li class="msg coordinator" data-id="[^"]+">(.*?)</li>\n`)
+
+func lastReply(t *testing.T, body string) string {
+ t.Helper()
+ all := replyRE.FindAllStringSubmatch(body, -1)
+ if len(all) == 0 {
+ t.Fatalf("no reply in:\n%s", body)
+ }
+ return all[len(all)-1][1]
+}
+
+// The answer is drawn after the reply's words, escaped, with a Markdown
+// link in it shown as its words; then the quiet Sources line, each source
+// a link opening in a new tab, with its host after it.
+func TestLookupDrawn(t *testing.T) {
+ a, f := newAskApp(t)
+ a.approveEquipo(f)
+ f.SayWithLookups("Here it is.", equipo.Lookup{
+ Answer: "**Rain** later, see [Met](https://met.test/x) & <b>more</b>.",
+ Sources: []equipo.Source{{URL: "https://www.met.test/dublin?d=1", Title: "Met Éireann"}, {URL: "https://b.test/", Title: ""}},
+ }, equipo.Lookup{Answer: "Second answer.", Sources: []equipo.Source{{URL: "https://two.test/", Title: "Two"}}})
+ reply := lastReply(t, a.get("/ask").Body)
+ // Two lookups, in the order they were made, each with its sources.
+ if i, j := strings.Index(reply, "b.test</span>"), strings.Index(reply, "Second answer."); strings.Count(reply, `class="lookup"`) != 2 || i < 0 || j < i {
+ t.Errorf("two lookups out of order:\n%s", reply)
+ }
+ if !strings.HasPrefix(reply, "Here it is.") {
+ t.Errorf("the reply's own words come first: %q", reply)
+ }
+ answer := `<div class="lookup"><div class="lookup-answer"><strong>Rain</strong> later, see Met &amp; &lt;b&gt;more&lt;/b&gt;.</div>`
+ if !strings.Contains(reply, answer) {
+ t.Errorf("answer not drawn as %s in:\n%s", answer, reply)
+ }
+ sources := `<p class="lookup-sources"><span class="lookup-label">Sources</span>` +
+ `<span class="source"><a href="https://www.met.test/dublin?d=1" target="_blank" rel="noopener noreferrer nofollow">Met Éireann</a><span class="source-host">met.test</span></span>` +
+ `<span class="source"><a href="https://b.test/" target="_blank" rel="noopener noreferrer nofollow">b.test</a><span class="source-host">b.test</span></span></p></div>`
+ if !strings.Contains(reply, sources) {
+ t.Errorf("sources not drawn as\n%s\nin:\n%s", sources, reply)
+ }
+ if strings.Index(reply, "Here it is.") > strings.Index(reply, `class="lookup"`) {
+ t.Errorf("the answer came before the reply's words")
+ }
+}
+
+// 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)
+ }
+}
+
+// A job held because building was turned off, once it is on again, offers
+// Carry on now, without scripts too: the form posts to the card's
+// carry_on, and no "other plan" line is drawn (plan AD4).
+func TestStoppedCarryOnDrawn(t *testing.T) {
+ a, f := newAskApp(t)
+ a.approveEquipo(f)
+ id := f.AskJob("Bakery website")
+ f.StopJob(id, "Stopped", "Building is on again. You can carry on with this, or drop it.", true)
+ body := a.get("/ask").Body
+ form := `<form class="jv-act" method="post" action="/ask/cards/` + id + `/carry_on">`
+ if !strings.Contains(body, form) || !strings.Contains(body, ">Carry on now</button>") {
+ t.Fatalf("no Carry on now for the stopped job:\n%s", body)
+ }
+ if strings.Contains(body, "Uses your other plan") {
+ t.Errorf("the other plan's line is drawn for a held job")
+ }
+ rev := regexp.MustCompile(`action="/ask/cards/` + id + `/carry_on"><input type="hidden" name="revision" value="(\d+)">`).FindStringSubmatch(body)
+ if rev == nil {
+ t.Fatal("no revision in the form")
+ }
+ if r := a.post("/ask/cards/"+id+"/carry_on", url.Values{"revision": {rev[1]}, "key": {"held-1"}}); r.Code != 303 || r.Location() != "/ask" {
+ t.Fatalf("carry on: %d %q", r.Code, r.Location())
+ }
+ if n := len(f.Calls("/api/v1/assistant/cards/" + id + "/carry_on")); n != 1 {
+ t.Errorf("carry on went %d times", n)
+ }
+ if body := a.get("/ask").Body; strings.Contains(body, form) {
+ t.Errorf("Carry on now still offered once the job carried on")
+ }
+ // A stopped job that doesn't offer it has none.
+ other := f.AskJob("Invoices")
+ f.StopJob(other, "Stopped", "Building is turned off for you. Paul can turn it back on, or you can drop this.", false)
+ if body := a.get("/ask").Body; strings.Contains(body, `action="/ask/cards/`+other+`/carry_on"`) {
+ t.Errorf("Carry on now offered while building is off")
+ }
+}
diff --git a/internal/webtest/ask_native_contract_test.go b/internal/webtest/ask_native_contract_test.go
index 2ad304f..df9d2de 100644
--- a/internal/webtest/ask_native_contract_test.go
+++ b/internal/webtest/ask_native_contract_test.go
@@ -410,6 +410,7 @@ func (a *testApp) events(t *testing.T, after string, done func([]sseFrame) bool)
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, a.base+"/ask/events?after="+after, nil)
req.Header.Set("Origin", homeOrigin)
req.Header.Set("Accept", "text/event-stream")
+ a.addHeader(req)
for _, c := range a.client.Jar.Cookies(req.URL) {
req.AddCookie(c)
}
diff --git a/internal/webtest/harness_test.go b/internal/webtest/harness_test.go
index eeb6b74..bea93ee 100644
--- a/internal/webtest/harness_test.go
+++ b/internal/webtest/harness_test.go
@@ -97,6 +97,9 @@ type testApp struct {
seenMu *sync.Mutex
// logs is everything the app logged.
logs *logBuffer
+ // header is sent with every request this browser makes (the native
+ // app's Base-Client-Capabilities), unless the request sets it itself.
+ header http.Header
}
// logBuffer is the app's log, written by its handlers and read by a test.
@@ -166,6 +169,7 @@ func newAppConfigured(t *testing.T, build func(*sql.DB, config.Config) web.Insta
func (a *testApp) do(req *http.Request) Resp {
a.t.Helper()
+ a.addHeader(req)
res, err := a.client.Do(req)
if err != nil {
a.t.Fatal(err)
@@ -179,6 +183,15 @@ func (a *testApp) do(req *http.Request) Resp {
return out
}
+// addHeader sets a.header's fields on req where req has none of its own.
+func (a *testApp) addHeader(req *http.Request) {
+ for k, v := range a.header {
+ if _, ok := req.Header[k]; !ok {
+ req.Header[k] = v
+ }
+ }
+}
+
func (a *testApp) get(target string) Resp {
a.t.Helper()
req, _ := http.NewRequest(http.MethodGet, a.base+target, nil)
diff --git a/native/apple/Sources/BaseKit/API/Models.swift b/native/apple/Sources/BaseKit/API/Models.swift
index 66c549a..8c7b4e5 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.
@@ -265,7 +309,7 @@ public struct AskCard: Decodable, Sendable, Equatable, Identifiable {
public var startedAt: Date?
public var turnID: String
/// A paused job offers "Carry on now" (`carry_on`; Base sends it on a
- /// paused job card only).
+ /// paused or stopped job card only).
public var carryOn: Bool
public init(id: String, revision: Int64 = 1, kind: String, state: String, question: String = "", options: [Option] = [],
@@ -291,8 +335,9 @@ public struct AskCard: Decodable, Sendable, Equatable, Identifiable {
public var isOpen: Bool { state == "open" }
public var isJob: Bool { kind == "job" }
public var jobState: JobState? { isJob ? JobState(rawValue: state) : nil }
- /// A paused job that offers "Carry on now".
- public var offersCarryOn: Bool { jobState == .paused && carryOn }
+ /// A paused job that offers "Carry on now", or a stopped one held
+ /// while building was off, once it is on again.
+ public var offersCarryOn: Bool { (jobState == .paused || jobState == .stopped) && carryOn }
/// The kinds drawn as cards (ask.js `kinds`).
public static let drawnKinds: Set<String> = ["question", "confirm", "outcome", "connect"]
/// Where to see a job's work once there is something to see (ready,
diff --git a/native/apple/Sources/BaseKit/Ask/Markdown/PersonMarkdown.swift b/native/apple/Sources/BaseKit/Ask/Markdown/PersonMarkdown.swift
index e9db975..ee128e3 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] = []
@@ -62,8 +63,14 @@ enum PersonMarkdown {
}
private static let link = try! NSRegularExpression(pattern: #"\[([^\[\]\n]{1,300})\]\(([^()\s]{1,1000})\)|https?://[^\s<>()\[\]"']+"#)
+ /// A lookup's answer's whitespace, spelled out as Go and ask.js spell
+ /// it (lookupSpace in ask_cards.go).
+ static let lookupSpace = #"\t\n\f\r \x{00a0}\x{1680}\x{2000}-\x{200a}\x{2028}\x{2029}\x{202f}\x{205f}\x{3000}"#
+ /// link with lookupSpace for its whitespace (plainLinkRE in ask_cards.go).
+ private static let plainLink = try! NSRegularExpression(pattern: #"\[([^\[\]\n]{1,300})\]\(([^()"# + lookupSpace + #"]{1,1000})\)|https?://[^"# + lookupSpace + #"<>()\[\]"']+"#)
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 {
@@ -75,7 +82,7 @@ enum PersonMarkdown {
var out: [ChatMarkdownNode] = []
let ns = text as NSString
var last = 0
- for m in PersonMarkdown.link.matches(in: text, range: NSRange(location: 0, length: ns.length)) {
+ for m in (links ? PersonMarkdown.link : PersonMarkdown.plainLink).matches(in: text, range: NSRange(location: 0, length: ns.length)) {
var end = NSMaxRange(m.range), label: String, target: String
if m.range(at: 1).location != NSNotFound {
label = ns.substring(with: m.range(at: 1)); target = ns.substring(with: m.range(at: 2))
@@ -84,6 +91,14 @@ enum PersonMarkdown {
while let c = bare.last, ".,;:!?".contains(c) { bare.removeLast() }
target = bare; label = bare; end = m.range.location + (bare as NSString).length
}
+ guard links else {
+ // An address is text, whatever it is, untouched by
+ // emphasis: no URL check decides how it is drawn.
+ out += emphasis(ns.substring(with: NSRange(location: last, length: m.range.location - last)))
+ out.append(node("text", text: ns.substring(with: NSRange(location: m.range.location, length: end - m.range.location))))
+ last = end
+ continue
+ }
guard ChatMarkdown.allowsLink(target) else { continue }
out += emphasis(ns.substring(with: NSRange(location: last, length: m.range.location - last)))
out.append(node("link", target: target, children: [node("text", text: label)]))
@@ -125,3 +140,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})\]\(([^()"# + PersonMarkdown.lookupSpace + #"]{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/Pill.swift b/native/apple/Sources/BaseKit/Ask/Pill.swift
index 230afa1..eb9a6a7 100644
--- a/native/apple/Sources/BaseKit/Ask/Pill.swift
+++ b/native/apple/Sources/BaseKit/Ask/Pill.swift
@@ -253,8 +253,11 @@ public struct JobView: View {
Button(action: carryOn) { Text(BaseText.text("assistant.job.carry_on")) }
.buttonStyle(BaseButtonStyle(.ghost))
.disabled(carrying)
- Text(BaseText.text("assistant.job.carry_on_note"))
- .font(BaseFont.body(13, relativeTo: .footnote)).foregroundStyle(p[.haze])
+ // A held job (stopped) carries on on the same plan: no note.
+ if job.card.jobState == .paused {
+ Text(BaseText.text("assistant.job.carry_on_note"))
+ .font(BaseFont.body(13, relativeTo: .footnote)).foregroundStyle(p[.haze])
+ }
if let carryOnError {
Text(verbatim: carryOnError)
.font(BaseFont.body(13, relativeTo: .footnote))
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/AbilitiesTests.swift b/native/apple/Tests/BaseKitTests/AbilitiesTests.swift
new file mode 100644
index 0000000..3efa44e
--- /dev/null
+++ b/native/apple/Tests/BaseKitTests/AbilitiesTests.swift
@@ -0,0 +1,108 @@
+@testable import BaseKit
+import Foundation
+import RastrilloApple
+import RastrilloTestSupport
+import SwiftUI
+import XCTest
+
+/// The Assistant's abilities in the app: what it looked up for a reply
+/// (docs/api/base-native-v1.md, Lookup), drawn as the web draws it
+/// (chat.html `ask-lookup`), and a held job's Carry on now.
+final class AbilitiesTests: 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"])
+ }
+
+ /// A job held while building was off, once it is on again, offers
+ /// Carry on now as a paused one does (plan AD4); without carry_on, or
+ /// in any other state, it doesn't.
+ func testStoppedCarryOn() throws {
+ func card(_ state: String, _ carryOn: Bool) throws -> AskCard {
+ try JSONDecoder().decode(AskCard.self, from: Data(#"{"id":"c1","revision":3,"kind":"job","state":"\#(state)","question":"Bakery website","result":"Stopped","carry_on":\#(carryOn)}"#.utf8))
+ }
+ XCTAssertTrue(try card("stopped", true).offersCarryOn)
+ XCTAssertTrue(try card("paused", true).offersCarryOn)
+ XCTAssertFalse(try card("stopped", false).offersCarryOn)
+ XCTAssertFalse(try card("ready", true).offersCarryOn)
+ XCTAssertFalse(try card("working", true).offersCarryOn)
+ }
+}