//go:build browser // ยง8.11's browser race, in a real Chromium. Run with `make browser`. // // An answer for a query the screen has moved on from must never be // painted. The fake model is slow (1.5 s) and answers with its own // question, so a stale answer is visible by its words. // // Until 2026-10-29 the box searched as it was typed into, and a stale // answer could land on newer live results; two defences and a slow-typing // test kept it off (MUTATION-TESTED 2026-10-27). The typeahead replaced // live search: the answer is now asked for once, by the results page, for // the query that page was rendered for, and a new search is a new page. // What is left to pin is that the box does not disturb the answer and a // new page does not inherit the old one's. package memoriatest import ( "context" "io" "log/slog" "net/http" "path/filepath" "strings" "sync/atomic" "testing" "time" "amadan.net/rastrillo/rastrillo/db" "amadan.net/rastrillo/rastrillo/harness" "github.com/chromedp/chromedp" memoria "amadan.net/oficina/memoria/internal/memoria" "amadan.net/oficina/memoria/internal/memoria/provider" ) // slowAI answers after 1.5 s with its own question, and counts the // answers abandoned by the caller before then. type slowAI struct{ abandoned atomic.Int32 } func (*slowAI) ExtractAddresses(context.Context, []string) ([]provider.Pointer, error) { return []provider.Pointer{}, nil } func (f *slowAI) Answer(ctx context.Context, q string, _ []string) ([]provider.Sentence, error) { select { case <-time.After(1500 * time.Millisecond): case <-ctx.Done(): f.abandoned.Add(1) return nil, ctx.Err() } return []provider.Sentence{{Text: "ANSWER FOR " + strings.ToUpper(q), Cite: []int{0}}}, nil } // aiRig serves memoria with ai as its model and two documents stored. // wrap, if set, sits in front of the app with the stored ids to hand. func aiRig(t *testing.T, ai *slowAI, wrap func(next http.Handler, ids []int64, store *memoria.Store) http.Handler) *harness.Rig { return harness.New(t, func(origin string) http.Handler { logger := slog.New(slog.NewTextHandler(io.Discard, nil)) d, err := db.Open(filepath.Join(t.TempDir(), "app.db"), logger) if err != nil { t.Fatalf("db.Open: %v", err) } t.Cleanup(func() { d.Close() }) mux, a, err := memoria.AppForTest(d, origin, testDEK(t), logger) if err != nil { t.Fatalf("AppForTest: %v", err) } a.UseFakeModel(ai) var ids []int64 for _, doc := range [][2]string{ {"Paul Campbell", "## Roles\n\nPaul Campbell is Chief Executive Officer."}, {"Kitchen", "## Rota\n\nThe kitchen rota is pinned by the kettle."}, } { id, err := a.Store().Ingest(context.Background(), memoria.IngestSpec{Source: "upload", Key: doc[0], Title: doc[0], Body: doc[1]}) if err != nil { t.Fatal(err) } ids = append(ids, id) } if wrap != nil { return wrap(mux, ids, a.Store()) } return mux }) } func TestAStaleAIAnswerIsNeverPainted(t *testing.T) { rig := aiRig(t, &slowAI{}, nil) var page string var final string ctx, cancel := context.WithTimeout(rig.Context(), 30*time.Second) defer cancel() err := chromedp.Do(ctx, chromedp.Navigate(rig.Origin+"/?q=paul+campbell"), chromedp.WaitVisible(chromedp.CSS(`input[type="search"]`)), // The first answer is in flight; a new search is typed and sent. chromedp.Sleep(300*time.Millisecond), evalOnly(`document.querySelector('input[type="search"]').value = ""; true`), chromedp.SendKeys(chromedp.CSS(`input[type="search"]`), "kitchen rota\r"), chromedp.WaitVisible(chromedp.CSS(`[rst-search-results-for="kitchen rota"]`)), chromedp.Sleep(3000*time.Millisecond), evalInto(&page, `document.body.textContent`), evalInto(&final, `(document.querySelector("[rst-answer]") || {}).textContent || ""`), ) if err != nil { t.Fatalf("search: %v", err) } if strings.Contains(page, "ANSWER FOR PAUL CAMPBELL") { t.Fatal("an answer for the old query was painted on the new page") } if !strings.Contains(final, "ANSWER FOR KITCHEN ROTA") { t.Errorf("the current query's answer is not on the page: %q", final) } } // The ways a slot could be left wrong (Astra, 2026-10-27; reworked for // the typeahead 2026-11-02, when "a new search abandons the answer" moved // to TestAStaleAIAnswerIsNeverPainted, where a new search is a new page). // // MUTATION-TESTED 2026-10-27, reverted: the 204 branch leaving the slot โ†’ // "slot left". 2026-11-02, reverted: the box's input handler emptying the // results region (where the slot is) โ†’ "stuck". Clearing only an // [rst-answer] there survived: at 300 ms the answer has not arrived, so // there is nothing of that name to clear. func TestTheAnswerSlotSettles(t *testing.T) { t.Run("a space typed while asking", func(t *testing.T) { rig := aiRig(t, &slowAI{}, nil) var final string ctx, cancel := context.WithTimeout(rig.Context(), 30*time.Second) defer cancel() err := chromedp.Do(ctx, chromedp.Navigate(rig.Origin+"/?q=kitchen+rota"), chromedp.WaitVisible(chromedp.CSS(`input[type="search"]`)), // The answer is in flight; typing in the box is not a search. chromedp.Sleep(300*time.Millisecond), chromedp.SendKeys(chromedp.CSS(`input[type="search"]`), " "), chromedp.Sleep(3500*time.Millisecond), evalInto(&final, `(document.querySelector("[rst-answer]") || {}).textContent || ""`), ) if err != nil { t.Fatalf("search: %v", err) } if !strings.Contains(final, "ANSWER FOR KITCHEN ROTA") { t.Errorf("stuck: the slot says %q", strings.TrimSpace(final)) } }) t.Run("no answer wanted any more", func(t *testing.T) { // The document goes between the page and /answer, so /answer's // own search finds nothing and says 204. rig := aiRig(t, &slowAI{}, func(next http.Handler, ids []int64, st *memoria.Store) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/answer" { for _, id := range ids { _ = st.Delete(r.Context(), id) } } next.ServeHTTP(w, r) }) }) var slots int ctx, cancel := context.WithTimeout(rig.Context(), 30*time.Second) defer cancel() err := chromedp.Do(ctx, chromedp.Navigate(rig.Origin+"/?q=kitchen+rota"), chromedp.WaitVisible(chromedp.CSS(`input[type="search"]`)), chromedp.Sleep(1500*time.Millisecond), evalInto(&slots, `document.querySelectorAll("[rst-answer]").length`), ) if err != nil { t.Fatalf("load: %v", err) } if slots != 0 { t.Errorf("slot left after a 204: %d [rst-answer] on the page", slots) } }) } // ๐Ÿ‘ saves in place: the page does not move, the row says "Thanks.", and // the rating is on Reports. MUTATION-TESTED 2026-10-27, reverted: the // submit listener removed โ†’ "navigated" (the form's own submit reloads // the search). func TestThumbsUpSavesInPlace(t *testing.T) { rig := aiRig(t, &slowAI{}, nil) var said, path, reports string ctx, cancel := context.WithTimeout(rig.Context(), 30*time.Second) defer cancel() err := chromedp.Do(ctx, chromedp.Navigate(rig.Origin+"/?q=kitchen+rota"), chromedp.WaitVisible(chromedp.CSS(`[rst-ai-feedback] button[value="up"]`)), evalOnly(`window.__stayed = true; true`), chromedp.Click(chromedp.CSS(`[rst-ai-feedback] button[value="up"]`)), chromedp.Sleep(1000*time.Millisecond), evalInto(&said, `window.__stayed ? (document.querySelector("[rst-ai-feedback]") || {}).textContent || "" : "navigated"`), evalInto(&path, `location.pathname + location.search`), chromedp.Navigate(rig.Origin+"/reports"), evalInto(&reports, `document.body.textContent`), ) if err != nil { t.Fatalf("thumbs up: %v", err) } if strings.TrimSpace(said) != "Thanks." { t.Errorf("navigated, or no thanks: %q (at %s)", said, path) } if !strings.Contains(reports, "๐Ÿ‘") || !strings.Contains(reports, "kitchen rota") { t.Errorf("the rating is not on Reports") } }