Abilities phase 1: Astra round 2 fixes (3 P1, 1 P2)
P1: a folded answer escapes what CommonMark could still read as a link (reference links and definitions, images, autolinks, raw HTML, entities), so an old app shows it as written. P1: a write never lifts a hold; a read Base couldn't record removes what that app said before, and a member's requests are recorded one at a time. P1: a live native session of the member's that Base has never heard say what it draws (sessions joined to home_identity_links, no ask_clients row) holds the member back, so a restart forgets nothing. P2: source titles lose control characters, so server and script draw them alike.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
7 files changed,
+178
−34
docs/api/base-native-v1.md+5 −2internal/browsertest/ask_lookup_test.go+1 −1internal/equipo/lookups.go+19 −5internal/equipo/lookups_test.go+13 −1internal/store/askclients.go+26 −0internal/web/ask_caps.go+48 −14internal/webtest/ask_caps_test.go+66 −11
diff --git a/docs/api/base-native-v1.md b/docs/api/base-native-v1.md| index 4b9df6a..06e9d03 100644 |
| --- a/docs/api/base-native-v1.md |
| +++ b/docs/api/base-native-v1.md |
| @@ -100,8 +100,11 @@ or as the query parameter `client_caps` (the kit's `NativeHTTP` sets no |
| header of its own, so the app sends the parameter). Base keeps the newest |
| list per app session, from these two reads only, and tells the Assistant |
| a feature is drawn only while every app the member used in the last 30 |
| -days last said so. An app that says nothing keeps what it gets today: |
| -its reads carry each message's lookups folded into its `text`. |
| +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 | |
| |---|---| |
diff --git a/internal/browsertest/ask_lookup_test.go b/internal/browsertest/ask_lookup_test.go| index 08457e6..4bd2bbd 100644 |
| --- a/internal/browsertest/ask_lookup_test.go |
| +++ b/internal/browsertest/ask_lookup_test.go |
| @@ -51,7 +51,7 @@ 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/"}}}}, |
| + 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"}}}}, |
| "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"}}}, |
diff --git a/internal/equipo/lookups.go b/internal/equipo/lookups.go| index 878798c..f864323 100644 |
| --- a/internal/equipo/lookups.go |
| +++ b/internal/equipo/lookups.go |
| @@ -4,6 +4,7 @@ import ( |
| "net/url" |
| "regexp" |
| "strings" |
| + "unicode" |
| "unicode/utf8" |
| ) |
| @@ -66,7 +67,12 @@ func cleanLookups(role string, lookups []Lookup) []Lookup { |
| if u == "" { |
| continue |
| } |
| - title := []rune(strings.ToValidUTF8(s.Title, "")) |
| + 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] |
| } |
| @@ -101,7 +107,8 @@ func sourceURL(raw string) string { |
| 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 |
| +// 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})\)`) |
| @@ -111,11 +118,12 @@ var ( |
| // 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. |
| +// 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") |
| - return foldAddress.ReplaceAllStringFunc(answer, func(m string) string { |
| + answer = foldAddress.ReplaceAllStringFunc(answer, func(m string) string { |
| raw := strings.TrimSuffix(strings.TrimPrefix(m, "<"), ">") |
| trail := "" |
| if !strings.HasSuffix(m, ">") { |
| @@ -131,8 +139,14 @@ func plainAnswer(answer string) string { |
| } |
| 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 |
diff --git a/internal/equipo/lookups_test.go b/internal/equipo/lookups_test.go| index f8582ed..6cfbc1e 100644 |
| --- a/internal/equipo/lookups_test.go |
| +++ b/internal/equipo/lookups_test.go |
| @@ -26,7 +26,7 @@ func TestCleanLookupBounds(t *testing.T) { |
| 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)}}}, |
| + {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() |
| @@ -39,6 +39,9 @@ func TestCleanLookupBounds(t *testing.T) { |
| 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)) |
| @@ -94,6 +97,15 @@ func TestPlainLookupsFolds(t *testing.T) { |
| 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  <b>\n\n[ref]: https://evil.test/ \\", |
| + Sources: []equipo.Source{{URL: "https://met.test/", Title: "Met"}}}}}.PlainLookups() |
| + if want := "\\[Open\\]\\[ref\\] and !i \\<b\\>\n\n\\[ref\\]: https\\://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) |
| } |
diff --git a/internal/store/askclients.go b/internal/store/askclients.go| index b3321eb..55d370d 100644 |
| --- a/internal/store/askclients.go |
| +++ b/internal/store/askclients.go |
| @@ -52,3 +52,29 @@ func TouchAskClient(ctx context.Context, db *sql.DB, member int64, client string |
| 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/web/ask_caps.go b/internal/web/ask_caps.go| index 59139eb..e5bc48d 100644 |
| --- a/internal/web/ask_caps.go |
| +++ b/internal/web/ask_caps.go |
| @@ -58,6 +58,14 @@ func (a *app) askCaps(ctx context.Context, member int64) []string { |
| 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) |
| @@ -83,6 +91,45 @@ func (a *app) askCaps(ctx context.Context, member int64) []string { |
| type clientsUnrecorded struct { |
| mu sync.Mutex |
| held map[int64]map[string]bool |
| + // 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.unrecorded.locks.LoadOrStore(member, &sync.Mutex{}) |
| + m.(*sync.Mutex).Lock() |
| + defer m.(*sync.Mutex).Unlock() |
| + 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) |
| } |
| // clientRecorded notes whether client's request was recorded for the |
| @@ -143,20 +190,7 @@ func (a *app) withAskCaps(next http.Handler) http.Handler { |
| return |
| } |
| if native, said := clientCaps(r); native && strings.HasPrefix(r.URL.Path, "/ask/") { |
| - client := "" |
| - c, err := r.Cookie(a.sess.CookieName()) |
| - if err == nil { |
| - 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 { |
| - a.logger.Error("ask: see client", "err", err) |
| - } |
| - a.clientRecorded(n, client, err == nil) |
| + 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) }))) |
diff --git a/internal/webtest/ask_caps_test.go b/internal/webtest/ask_caps_test.go| index 0992629..03d9143 100644 |
| --- a/internal/webtest/ask_caps_test.go |
| +++ b/internal/webtest/ask_caps_test.go |
| @@ -103,7 +103,10 @@ func TestAskCapsWithheldForOldNative(t *testing.T) { |
| // 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, _, f := newNativeAskApp(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++ { |
| @@ -146,9 +149,9 @@ func TestCapabilityHeaderOnEveryCall(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - // The web is never recorded as a client. |
| - if got, err := store.AskClients(context.Background(), web.DB, n, time.Time{}); err != nil || len(got) != 0 { |
| - t.Errorf("web clients recorded: %+v %v", got, 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) |
| } |
| } |
| @@ -197,17 +200,50 @@ func TestAskCapsNativeWriteFirst(t *testing.T) { |
| 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) |
| + want := func(where string, have bool) { |
| + t.Helper() |
| + web.get("/ask") |
| + caps, ok := capsOfLast(t, f, snapshotPath) |
| + if have && (!ok || caps != equipo.CapLookupAnswers) || !have && ok { |
| + t.Errorf("%s: Base-Capabilities %q (%v), want it %v", where, caps, ok, have) |
| + } |
| } |
| + app.header = http.Header{"Base-Client-Capabilities": {equipo.CapLookupAnswers}} |
| 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) |
| + 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) |
| + } |
| } |
| - if _, err := web.DB.Exec(`DROP TRIGGER no_clients`); 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() |
| web.get("/ask") |
| @@ -215,3 +251,22 @@ func TestAskCapsRecordFailureHoldsBack(t *testing.T) { |
| t.Errorf("once recorded, Base-Capabilities %q (%v)", caps, ok) |
| } |
| } |
| + |
| +// A native session Base has never heard from on /ask (an app opened |
| +// before this Base, or one whose first request couldn't be recorded |
| +// before a restart) holds the member back until it says what it draws |
| +// (Astra round 2). |
| +func TestAskCapsUnseenNativeSession(t *testing.T) { |
| + web, app, f := newNativeAskApp(t) |
| + web.approveEquipo(f) |
| + web.get("/ask") |
| + if caps, ok := capsOfLast(t, f, snapshotPath); ok { |
| + t.Errorf("with an unseen app, the web says %q", caps) |
| + } |
| + 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 the app said so: %q (%v)", caps, ok) |
| + } |
| +} |