oficina / base Public

Abilities phase 1: Astra round 1 fixes (4 P1, 2 P2)

P1: the plain fallback folds an answer without its own links (a
Markdown link is its words, an address its host). P1: a native app's
every /ask/* request is recorded, a first write as drawing nothing and
any write as a sign of life; only the two reads say what it draws. P1:
a client Base couldn't record holds the member's capabilities back
until it is recorded. P1: capabilities are worked out as each Equipo
call is sent (WithCapabilitiesFunc), not when the request began.
P2: lookup answers spell their whitespace out and count characters
alike in Go, ask.js (u flag) and the app, pinned by shared samples. P2:
sources need a DNS name with no port, so every client reads one host.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 3a761a1a17ebf37a37ad37b91761da5433a58686 parent 887b6f7
13 files changed, +291 −42
  • internal/browsertest/ask_lookup_test.go +25 −0
  • internal/equipo/abilities.go +21 −8
  • internal/equipo/lookups.go +47 −11
  • internal/equipo/lookups_test.go +33 −1
  • internal/look/static/ask.js +6 −2
  • internal/store/askclients.go +10 −0
  • internal/web/app.go +2 −0
  • internal/web/ask_caps.go +59 −13
  • internal/web/ask_cards.go +16 −3
  • internal/web/ask_connect.go +2 −2
  • internal/web/testdata/lookup.json +12 −0
  • internal/webtest/ask_caps_test.go +51 −0
  • native/apple/Sources/BaseKit/Ask/Markdown/PersonMarkdown.swift +7 −2
diff --git a/internal/browsertest/ask_lookup_test.go b/internal/browsertest/ask_lookup_test.go
index 2da207c..08457e6 100644
--- a/internal/browsertest/ask_lookup_test.go
+++ b/internal/browsertest/ask_lookup_test.go
@@ -4,6 +4,7 @@ package browsertest
import (
"context"
+ "encoding/json"
"os"
"path/filepath"
"strconv"
@@ -132,3 +133,27 @@ func TestStoppedCarryOnDrawn(t *testing.T) {
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
index c8114bf..2c7bab2 100644
--- a/internal/equipo/abilities.go
+++ b/internal/equipo/abilities.go
@@ -25,21 +25,34 @@ 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 {
- return context.WithValue(ctx, capsKey{}, append([]string(nil), caps...))
+ 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)
}
-// CapabilitiesOf are the capabilities ctx carries.
-func CapabilitiesOf(ctx context.Context) []string {
- caps, _ := ctx.Value(capsKey{}).([]string)
- return caps
+// 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 on req.
+// setCapabilities puts ctx's capabilities, as they are now, on req.
func setCapabilities(ctx context.Context, req *http.Request) {
- if caps := CapabilitiesOf(ctx); len(caps) > 0 {
- req.Header.Set(CapabilitiesHeader, strings.Join(caps, ","))
+ 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/lookups.go b/internal/equipo/lookups.go
index ad98b99..878798c 100644
--- a/internal/equipo/lookups.go
+++ b/internal/equipo/lookups.go
@@ -2,6 +2,7 @@ package equipo
import (
"net/url"
+ "regexp"
"strings"
"unicode/utf8"
)
@@ -78,29 +79,64 @@ func cleanLookups(role string, lookups []Lookup) []Lookup {
return out
}
-// sourceURL is raw if it is an absolute https address with a host of
-// ASCII alone (so every client shows the host alike) and no user info,
-// of at most maxSourceURL bytes, else "".
+// 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" {
+ if u == "" || err != nil || p.Scheme != "https" || p.Port() != "" || !sourceHostRE.MatchString(strings.ToLower(p.Host)) {
return ""
}
- for i := 0; i < len(p.Host); i++ {
- if p.Host[i] >= utf8.RuneSelf {
- return ""
- }
- }
return u
}
+// 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. 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. Trailing
+// punctuation stays as text.
+func plainAnswer(answer string) string {
+ answer = foldMarkdownLink.ReplaceAllString(answer, "$1")
+ return 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
+ })
+}
+
// 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. Lookups is nil.
+// "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 != "" {
@@ -111,7 +147,7 @@ func (m Message) PlainLookups() Message {
for _, s := range l.Sources {
urls = append(urls, s.URL)
}
- parts = append(parts, l.Answer, fallbackSources+"\n"+strings.Join(urls, "\n"))
+ 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
index 3f9a2e4..f8582ed 100644
--- a/internal/equipo/lookups_test.go
+++ b/internal/equipo/lookups_test.go
@@ -59,7 +59,9 @@ func TestCleanLookupBounds(t *testing.T) {
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://ok.test/a?b=1", Title: "e"}}},
+ {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/a?b=1", Title: "e"}}},
{Answer: "No sources", Sources: []equipo.Source{{URL: "http://plain.test/"}}},
{Answer: " ", Sources: []equipo.Source{src(1)}},
}}.Clean()
@@ -83,6 +85,15 @@ func TestPlainLookupsFolds(t *testing.T) {
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)
+ }
if got := (equipo.Message{Text: "Plain"}).PlainLookups(); got.Text != "Plain" {
t.Errorf("no lookups: %q", got.Text)
}
@@ -153,3 +164,24 @@ func TestFakeLookupFallbackWithoutCapability(t *testing.T) {
}
}
}
+
+// 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/ask.js b/internal/look/static/ask.js
index 1c699ab..d6b59f3 100644
--- a/internal/look/static/ask.js
+++ b/internal/look/static/ask.js
@@ -329,7 +329,7 @@ function start(root) {
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(/[.,;:!?]+$/, "");
@@ -417,7 +417,11 @@ function start(root) {
// at word boundaries) with no links at all; a Markdown link shows as its
// words, a bare URL or an autolink as text (lookupMarkdown in
// ask_cards.go, and the app's LookupMarkdown).
- const mdLinkRE = /\[([^\[\]\n]{1,300})\]\(([^()\s]{1,1000})\)/g;
+ // 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);
}
diff --git a/internal/store/askclients.go b/internal/store/askclients.go
index 2c61d92..b3321eb 100644
--- a/internal/store/askclients.go
+++ b/internal/store/askclients.go
@@ -42,3 +42,13 @@ func AskClients(ctx context.Context, db *sql.DB, member int64, since time.Time)
}
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
+}
diff --git a/internal/web/app.go b/internal/web/app.go
index 28ace58..ce5b2e1 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
diff --git a/internal/web/ask_caps.go b/internal/web/ask_caps.go
index c13bada..59139eb 100644
--- a/internal/web/ask_caps.go
+++ b/internal/web/ask_caps.go
@@ -5,6 +5,7 @@ import (
"net/http"
"slices"
"strings"
+ "sync"
"time"
"amadan.net/oficina/home/connect"
@@ -51,8 +52,12 @@ func clientCaps(r *http.Request) (native bool, caps []string) {
// 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.
+// 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 {
+ if a.clientsDown(member) {
+ return nil
+ }
clients, err := store.AskClients(ctx, a.db, member, time.Now().Add(-clientWindow))
if err != nil {
a.logger.Error("ask: clients", "err", err)
@@ -71,6 +76,45 @@ func (a *app) askCaps(ctx context.Context, member int64) []string {
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]bool
+}
+
+// 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]bool{}
+ }
+ if u.held[member] == nil {
+ u.held[member] = map[string]bool{}
+ }
+ u.held[member][client] = true
+}
+
+// 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()
+ return len(a.unrecorded.held[member]) > 0
+}
+
// 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.
@@ -79,7 +123,9 @@ func recordsClient(r *http.Request) bool {
}
// withAskCaps records what a native app's /ask/state or /ask/events read
-// says it can draw (web sessions are not recorded), then puts the member's capabilities
+// 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 {
@@ -96,24 +142,24 @@ func (a *app) withAskCaps(next http.Handler) http.Handler {
next.ServeHTTP(w, r)
return
}
- recorded := true
- if native, said := clientCaps(r); native && recordsClient(r) {
+ if native, said := clientCaps(r); native && strings.HasPrefix(r.URL.Path, "/ask/") {
+ client := ""
c, err := r.Cookie(a.sess.CookieName())
if err == nil {
- err = store.SeeAskClient(ctx, a.db, n, sessions.HashToken(c.Value), strings.Join(said, ","))
+ client = sessions.HashToken(c.Value)
+ if recordsClient(r) {
+ err = store.SeeAskClient(ctx, a.db, n, client, strings.Join(said, ","))
+ } else {
+ err = store.TouchAskClient(ctx, a.db, n, client)
+ }
}
if err != nil {
- // Unrecorded, this app could be one that can't draw
- // them: withhold every capability for this request.
a.logger.Error("ask: see client", "err", err)
- recorded = false
}
+ a.clientRecorded(n, client, err == nil)
}
- var caps []string
- if recorded {
- caps = a.askCaps(ctx, n)
- }
- next.ServeHTTP(w, r.WithContext(equipo.WithCapabilities(ctx, caps)))
+ // 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) })))
})
}
diff --git a/internal/web/ask_cards.go b/internal/web/ask_cards.go
index 437224e..528ae05 100644
--- a/internal/web/ask_cards.go
+++ b/internal/web/ask_cards.go
@@ -35,8 +35,17 @@ func personText(text string) template.HTML { return richMarkdown(text, true) }
func richMarkdown(text string, strict bool) template.HTML { return markdown(text, strict, true) }
-// mdLinkRE is a Markdown link, [label](target).
-var mdLinkRE = regexp.MustCompile(`\[([^\[\]\n]{1,300})\]\(([^()\s]{1,1000})\)`)
+// 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,
@@ -112,8 +121,12 @@ func inline(b *strings.Builder, text string, strict, links bool) {
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]]
diff --git a/internal/web/ask_connect.go b/internal/web/ask_connect.go
index 4c31602..d2f5e87 100644
--- a/internal/web/ask_connect.go
+++ b/internal/web/ask_connect.go
@@ -397,9 +397,9 @@ func (a *app) zoneFor(parent context.Context, me store.Member, token string, fre
}
z.busy = true
a.ask.zoneMu.Unlock()
- caps := equipo.CapabilitiesOf(parent)
+ caps := equipo.CapabilitiesFuncOf(parent)
go func() {
- ctx, cancel := context.WithTimeout(equipo.WithCapabilities(context.Background(), caps), 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/testdata/lookup.json b/internal/web/testdata/lookup.json
index ad1a384..50ad0cd 100644
--- a/internal/web/testdata/lookup.json
+++ b/internal/web/testdata/lookup.json
@@ -22,5 +22,17 @@
{
"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)"
}
]
diff --git a/internal/webtest/ask_caps_test.go b/internal/webtest/ask_caps_test.go
index d7d17cf..0992629 100644
--- a/internal/webtest/ask_caps_test.go
+++ b/internal/webtest/ask_caps_test.go
@@ -164,3 +164,54 @@ func jobsOf(t *testing.T, a *testApp) []json.RawMessage {
}
return s.Jobs
}
+
+// A native app whose first request is a write, before it ever reads, is
+// recorded as drawing nothing (Astra round 1, P1-2), 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)
+ 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")
+ if caps, ok := capsOfLast(t, f, snapshotPath); ok {
+ t.Errorf("an app seen only writing counts as drawing lookups: %q", caps)
+ }
+ 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)
+ }
+}
+
+// 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)
+ if _, err := web.DB.Exec(`CREATE TRIGGER no_clients BEFORE INSERT ON ask_clients BEGIN SELECT RAISE(ABORT, 'refused'); END`); err != nil {
+ t.Fatal(err)
+ }
+ app.askState()
+ web.get("/ask")
+ if caps, ok := capsOfLast(t, f, snapshotPath); ok {
+ t.Errorf("after a failed record the web still says %q", caps)
+ }
+ if _, err := web.DB.Exec(`DROP TRIGGER no_clients`); err != nil {
+ t.Fatal(err)
+ }
+ app.header = http.Header{"Base-Client-Capabilities": {equipo.CapLookupAnswers}}
+ app.askState()
+ web.get("/ask")
+ if caps, ok := capsOfLast(t, f, snapshotPath); !ok || caps != equipo.CapLookupAnswers {
+ t.Errorf("once recorded, Base-Capabilities %q (%v)", caps, ok)
+ }
+}
diff --git a/native/apple/Sources/BaseKit/Ask/Markdown/PersonMarkdown.swift b/native/apple/Sources/BaseKit/Ask/Markdown/PersonMarkdown.swift
index 0b9bc33..0a0ba7a 100644
--- a/native/apple/Sources/BaseKit/Ask/Markdown/PersonMarkdown.swift
+++ b/native/apple/Sources/BaseKit/Ask/Markdown/PersonMarkdown.swift
@@ -63,6 +63,11 @@ 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
@@ -77,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))
@@ -139,7 +144,7 @@ enum PersonMarkdown {
/// ask.js). A Markdown link shows as its words; a bare URL or an autolink
/// stays as text. The only links under a reply are its sources.
enum LookupMarkdown {
- private static let markdownLink = try! NSRegularExpression(pattern: #"\[([^\[\]\n]{1,300})\]\(([^()\s]{1,1000})\)"#)
+ 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")