Live search feels instant: partial words while typing, sooner, no model per keystroke
Paul, 2026-10-26: "the whole UI appears to be slow as the results live-update. Other similar systems just update the UI instantly." - While typing, the last word (two characters or more) matches as a prefix (index.SearchTyping). The list no longer empties on the way to every word. Submitted, Entered, settled and native searches still use whole words. - search.js asks after 40 ms, not 120 ms. - Keystroke requests (typing=1) skip §8.9's model call, which could take up to 800 ms, and mark the fragment. search.js makes one full request once typing pauses for 450 ms, including after a space or an undone letter. The footer now says passages go to TensorX "once you stop typing". - Non-ASCII punctuation ends a term. Reviewed by GPT-6 Astra (REQUEST CHANGES). Fixed: - the settled request could be lost; - finished words still matched as prefixes through trimming; - "a—" glued into one term. New guards: a typing search is still ruled and boxed; a browser test of settling; an index test that only typing is a prefix. All surviving mutants are built and red. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Squashed from feat/instant-search into main.
17 files changed,
+432
−38
Makefile+1 −1README.md+4 −3docs/superpowers/specs/2026-09-03-memoria-design.md+26 −6internal/memoria/handlers.go+12 −1internal/memoria/index/index.go+46 −5internal/memoria/index/index_test.go+36 −0internal/memoria/modelfacts_test.go+54 −2internal/memoria/narrow_test.go+38 −1internal/memoria/static/memoria.css+2 −0internal/memoria/static/search.js+39 −7internal/memoria/store.go+45 −9internal/memoria/templates/layout.html+1 −1internal/memoria/templates/results.html+3 −0internal/memoriatest/chrome_test.go+3 −1internal/memoriatest/factbox_test.go+1 −1internal/memoriatest/footer_model_test.go+30 −0internal/memoriatest/settle_browser_test.go+91 −0
CI passed — run details
diff --git a/Makefile b/Makefile| index 691cf78..f5e8085 100644 |
| --- a/Makefile |
| +++ b/Makefile |
| @@ -120,7 +120,7 @@ ci: vet fmt-check test migration-check |
| # Mac from the Playwright cache. |
| RASTRILLO_CHROME ?= $(firstword $(wildcard $(HOME)/Library/Caches/ms-playwright/chromium-*/chrome-mac*/Chromium.app/Contents/MacOS/Chromium)) |
| browser: |
| - RASTRILLO_CHROME="$(RASTRILLO_CHROME)" CGO_ENABLED=0 go test -tags browser -count=1 -run 'OnTap|ProductionCSP|NoSidewaysScroll' ./internal/memoriatest/ |
| + RASTRILLO_CHROME="$(RASTRILLO_CHROME)" CGO_ENABLED=0 go test -tags browser -count=1 -run 'OnTap|ProductionCSP|NoSidewaysScroll|SettlesADeferredBox' ./internal/memoriatest/ |
| .PHONY: credits |
| credits: |
diff --git a/README.md b/README.md| index f03327c..505f745 100644 |
| --- a/README.md |
| +++ b/README.md |
| @@ -20,9 +20,10 @@ memoria first looks for one with its own checks. Addresses have no |
| checksum, so those checks cannot find one. It then sends **up to eight |
| passages per search request** — the top eight that search returned, |
| passages you were already allowed to read — to **TensorX**, the one named |
| -provider, which points at any addresses in them. **That includes the live |
| -searches that run while you type**, not only the one you submit: each |
| -pause in typing a query that asks for an address is its own request. |
| +provider, which points at any addresses in them. **Not while you type:** |
| +live search skips this step on each keystroke and makes one request with |
| +it once you pause typing. Submitting with Enter, or reloading, is another |
| +full request, so one query can send passages more than once. |
| memoria shows only text it finds byte-for-byte in those passages, marks |
| each such row 🤖 with TensorX and the model's name, and never shows the |
| model's own words. Nothing else is sent: not |
diff --git a/docs/superpowers/specs/2026-09-03-memoria-design.md b/docs/superpowers/specs/2026-09-03-memoria-design.md| index 626f13e..cd4d546 100644 |
| --- a/docs/superpowers/specs/2026-09-03-memoria-design.md |
| +++ b/docs/superpowers/specs/2026-09-03-memoria-design.md |
| @@ -3729,12 +3729,32 @@ recall limit this section accepts in exchange for a bounded payload and a |
| response inside the deadline. Each passage is sent with an index, and |
| nothing else about it — no title, no path, no id. |
| -**Per request, and that includes live search.** `GET /search` renders the |
| -results region on each pause in typing and runs this path like the full |
| -page does, so a query that asks for an address sends passages on every |
| -debounced keystroke that reaches the server. The request context bounds |
| -it — `search.js` aborts a superseded fetch and the call is cancelled with |
| -it — but it is still a request per pause, and the README says so. |
| +**Not on keystrokes (2026-10-26).** This path used to run on every |
| +debounced keystroke of a query that named a model kind. Paul found live |
| +results slow, and a keystroke could wait up to the deadline below. Now |
| +`search.js` marks a keystroke's request `typing=1`, and |
| +`Store.SearchWhileTyping` builds the results and §8.8's box under the same |
| +§4.1 ruling, but never calls the model. The fragment carries |
| +`[rst-facts-deferred]` when it skipped the step. Once typing has paused |
| +for 450 ms with the same query in the box, `search.js` makes one request |
| +without the flag, and that request runs this path. That holds even if the |
| +last keystroke changed nothing after trimming, such as a space or a |
| +letter typed and taken back; a review found the request was lost in that |
| +case. **Passages are not sent once per query, only less often:** the |
| +settled request sends them, and pressing Enter or reloading is another |
| +full request that sends them again. The footer says "once you stop |
| +typing", and the README says the rest. |
| + |
| +**While typing, the last word matches as a prefix (2026-10-26).** |
| +Whole-token matching made live search find nothing on the way to a word: |
| +"offi" matched no passage, so the list emptied until "office" was |
| +complete. `index.SearchTyping` (`MatchQueryTyping`) makes the last term |
| +an FTS5 prefix term when it is at least two characters. Only keystroke |
| +requests use it. A submitted page, Enter, a settled request and the |
| +native API all use whole words, because the text arrives trimmed and |
| +"finished" cannot be read from a trailing space. Non-ASCII terms now keep |
| +only letters, digits and combining marks, so a dash ends a term as |
| +unicode61 says it does. The debounce is 40 ms, down from 120 ms. |
| **Egress is the existing category with a new trigger**, and §3.2 now says |
| both halves: the same recipient and the same kind of transmission as the |
diff --git a/internal/memoria/handlers.go b/internal/memoria/handlers.go| index cd41050..33a38a5 100644 |
| --- a/internal/memoria/handlers.go |
| +++ b/internal/memoria/handlers.go |
| @@ -193,6 +193,9 @@ type page struct { |
| // it; it exists so the owner can see why a box did or did not appear |
| // on data nobody else can read. |
| Explained []FactExplanation |
| + // FactsDeferred: a typing request skipped §8.9's model step; the |
| + // fragment carries a marker so search.js completes it on a pause. |
| + FactsDeferred bool |
| // SearchFailed is not "no results". A search that errored renders |
| // its own callout in the results region, because "nothing matched" |
| @@ -669,7 +672,14 @@ func (a *app) runSearch(r *http.Request, p *page) { |
| p.Searched, p.SearchFailed = false, true |
| return |
| } |
| - found, err := a.store.Search(r.Context(), |
| + search := a.store.Search |
| + // search.js marks a keystroke's request typing=1. It gets the |
| + // deterministic box and the results, never the model step; the |
| + // request it makes once typing pauses is the full one (§8.9). |
| + if r.URL.Query().Get("typing") == "1" { |
| + search = a.store.SearchWhileTyping |
| + } |
| + found, err := search(r.Context(), |
| suite.Subject{Kind: suite.SubjectAddress, Value: addr}, p.Query, 25) |
| if err != nil { |
| // No query text in the log line: AGENTS.md, and `carlos logs` is |
| @@ -684,6 +694,7 @@ func (a *app) runSearch(r *http.Request, p *page) { |
| // Primed is decided here: the page and the fragment must not be able |
| // to disagree about whether there is a box. |
| p.Facts = found.Facts |
| + p.FactsDeferred = found.FactsDeferred |
| if r.URL.Query().Get("explain") == "facts" { |
| p.Explained = found.Explained |
| } |
diff --git a/internal/memoria/index/index.go b/internal/memoria/index/index.go| index 179eb9d..a5ce49b 100644 |
| --- a/internal/memoria/index/index.go |
| +++ b/internal/memoria/index/index.go |
| @@ -19,6 +19,8 @@ import ( |
| "fmt" |
| "strings" |
| "sync" |
| + "unicode" |
| + "unicode/utf8" |
| _ "modernc.org/sqlite" |
| ) |
| @@ -210,7 +212,18 @@ const ( |
| // Search runs a BM25 query, weighted by the constants above. |
| func (i *Index) Search(query string, limit int) ([]Hit, error) { |
| - q := MatchQuery(query) |
| + return i.search(MatchQuery(query), limit) |
| +} |
| + |
| +// SearchTyping is Search for live search's keystrokes: the last term |
| +// matches as a prefix (MatchQueryTyping). Every other caller — a |
| +// submitted page, Enter, a settled request, the native API — uses |
| +// Search, where a word means the whole word. |
| +func (i *Index) SearchTyping(query string, limit int) ([]Hit, error) { |
| + return i.search(MatchQueryTyping(query), limit) |
| +} |
| + |
| +func (i *Index) search(q string, limit int) ([]Hit, error) { |
| if q == "" { |
| return nil, nil |
| } |
| @@ -273,6 +286,26 @@ func (i *Index) Search(query string, limit int) ([]Hit, error) { |
| // worth almost nothing. Precision comes from ranking, not from |
| // exclusion. |
| func MatchQuery(raw string) string { |
| + return matchQuery(raw, false) |
| +} |
| + |
| +// MatchQueryTyping is MatchQuery for a query somebody is still typing: |
| +// its last term, if it is at least two characters, is an FTS5 prefix |
| +// term. Whole-token matching made live search find nothing on the way |
| +// to a word — "offi" matched no passage, so the list emptied on every |
| +// keystroke until "office" was complete (Paul, 2026-10-26: "the whole UI |
| +// appears to be slow as the results live-update"). One letter is never |
| +// a prefix: it matches nearly every passage and says nothing. |
| +// |
| +// Only keystroke requests use it, so a finished query — submitted, |
| +// Entered, settled, or from the native client — means exactly the words |
| +// typed. The typed text arrives trimmed, so there is no trailing space |
| +// to read "finished" from; this is decided by who is asking instead. |
| +func MatchQueryTyping(raw string) string { |
| + return matchQuery(raw, true) |
| +} |
| + |
| +func matchQuery(raw string, typing bool) string { |
| var terms []string |
| var cur strings.Builder |
| flush := func() { |
| @@ -286,10 +319,14 @@ func MatchQuery(raw string) string { |
| switch { |
| case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9': |
| cur.WriteRune(r) |
| - case r > 127: |
| + case r > 127 && (unicode.IsLetter(r) || unicode.IsDigit(r) || unicode.Is(unicode.Mn, r)): |
| // Keep non-ASCII letters: "café", "Müller", CJK. unicode61 |
| // tokenises them; dropping them would silently narrow a |
| - // search in any language but English. |
| + // search in any language but English. Letters, digits and |
| + // combining marks only: a dash or a curly quote is |
| + // punctuation to unicode61, and kept here it glued "a—" into |
| + // one term that FTS5 then split back to "a" (review, |
| + // 2026-10-26). |
| cur.WriteRune(r) |
| default: |
| flush() |
| @@ -315,8 +352,12 @@ func MatchQuery(raw string) string { |
| terms = terms[:maxTerms] |
| } |
| quoted := make([]string, 0, len(terms)+1) |
| - for _, t := range terms { |
| - quoted = append(quoted, `"`+t+`"`) |
| + for n, t := range terms { |
| + q := `"` + t + `"` |
| + if typing && n == len(terms)-1 && utf8.RuneCountInString(t) >= 2 { |
| + q += "*" |
| + } |
| + quoted = append(quoted, q) |
| } |
| // The query's words required to appear TOGETHER, added as a further |
| // OR operand rather than replacing anything. |
diff --git a/internal/memoria/index/index_test.go b/internal/memoria/index/index_test.go| index 4c4bc06..0112b73 100644 |
| --- a/internal/memoria/index/index_test.go |
| +++ b/internal/memoria/index/index_test.go |
| @@ -237,3 +237,39 @@ func TestIndexIsBackedByNoFile(t *testing.T) { |
| t.Fatalf("the index is backed by %q; FTS5 postings are plaintext and §3.1 forbids them reaching a file", file) |
| } |
| } |
| + |
| +// Keystroke requests match the word being typed as a prefix; every other |
| +// search means whole words (Paul, 2026-10-26: live results emptied on the |
| +// way to every word). |
| +// |
| +// MUTATION-TESTED 2026-10-26, each reverted: SearchTyping using |
| +// MatchQuery → "SearchTyping(\"offi\") = 0 hits"; Search using |
| +// MatchQueryTyping → "Search(\"offi\") = 1 hits"; the two-rune minimum |
| +// removed → `MatchQueryTyping("office p")`; non-ASCII punctuation kept in |
| +// terms → `MatchQueryTyping("a—")`. |
| +func TestOnlyTypingMatchesAPrefix(t *testing.T) { |
| + for q, want := range map[string]string{ |
| + "offi": `"offi"*`, |
| + "o": `"o"`, |
| + "office p": `"office" OR "p" OR NEAR("office" "p", 2)`, |
| + "office ph": `"office" OR "ph"* OR NEAR("office" "ph"*, 2)`, |
| + "a—": `"a"`, |
| + "café": `"café"*`, |
| + "office phone": `"office" OR "phone"* OR NEAR("office" "phone"*, 2)`, |
| + } { |
| + if got := MatchQueryTyping(q); got != want { |
| + t.Errorf("MatchQueryTyping(%q) = %q, want %q", q, got, want) |
| + } |
| + } |
| + if got := MatchQuery("offi"); got != `"offi"` { |
| + t.Errorf("MatchQuery(%q) = %q: a finished query is whole words", "offi", got) |
| + } |
| + |
| + ix := build(t, Entry{ChunkID: 1, DocumentID: 1, Heading: "Contact", Text: "The office phone number is on the wall."}) |
| + if hits, err := ix.SearchTyping("offi", 10); err != nil || len(hits) != 1 { |
| + t.Errorf("SearchTyping(%q) = %d hits, %v; want the passage", "offi", len(hits), err) |
| + } |
| + if hits, err := ix.Search("offi", 10); err != nil || len(hits) != 0 { |
| + t.Errorf("Search(%q) = %d hits, %v; want none: a finished query is whole words", "offi", len(hits), err) |
| + } |
| +} |
diff --git a/internal/memoria/modelfacts_test.go b/internal/memoria/modelfacts_test.go| index 8424de0..2c09244 100644 |
| --- a/internal/memoria/modelfacts_test.go |
| +++ b/internal/memoria/modelfacts_test.go |
| @@ -775,7 +775,7 @@ func TestGate39WhatTheFirstDraftCouldNotSee(t *testing.T) { |
| rec := &recorder{} |
| s.extractor = rec |
| page := Page{Results: ruled.Results} |
| - s.addFacts(context.Background(), &page, "office address") |
| + s.addFacts(context.Background(), &page, "office address", true) |
| if len(rec.calls) != 1 { |
| t.Fatalf("calls = %d", len(rec.calls)) |
| } |
| @@ -796,7 +796,7 @@ func TestGate39WhatTheFirstDraftCouldNotSee(t *testing.T) { |
| rec2 := &recorder{reply: point(0, addrOf[second.DocumentID])} |
| s.extractor = rec2 |
| page2 := Page{Results: ruled.Results} |
| - s.addFacts(context.Background(), &page2, "office address") |
| + s.addFacts(context.Background(), &page2, "office address", true) |
| rows := modelRows(page2) |
| if len(rows) != 1 || rows[0].DocumentID != second.DocumentID || rows[0].Title != second.Title || rows[0].Ordinal != second.Ordinal { |
| t.Errorf("rows = %+v; want one, cited to result two (doc %d)", rows, second.DocumentID) |
| @@ -1161,3 +1161,55 @@ type movingDeadline struct { |
| } |
| func (c movingDeadline) Deadline() (time.Time, bool) { return *c.dl, true } |
| + |
| +// A keystroke's search never calls the model, and says it deferred |
| +// (Paul, 2026-10-26: live results felt slow). The model step can take |
| +// provider.Deadline and sends passages out; running it on every keystroke |
| +// of "office address" made each one wait for it. The settled request |
| +// search.js makes after a pause is the full one. |
| +// |
| +// MUTATION-TESTED 2026-10-26, each reverted: SearchWhileTyping mapped to |
| +// modeFull → "a typing search sent 1 requests to the model"; the |
| +// FactsDeferred line removed → "FactsDeferred = false"; the deferral |
| +// applied to Search as well → "the full search sent 0 requests". |
| +func TestTypingDefersTheModelStep(t *testing.T) { |
| + const addr = "12 Main Street, Dublin 2, D02 X285" |
| + s := storeForTest(t) |
| + upload(t, s, "Tito office", "## Contact\n\nOffice address: "+addr) |
| + rec := &recorder{reply: point(0, addr)} |
| + s.extractor = rec |
| + asker := suite.Subject{Kind: suite.SubjectAddress, Value: "paul@tito.io"} |
| + |
| + p, err := s.SearchWhileTyping(context.Background(), asker, "office address", 25) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(p.Results) == 0 { |
| + t.Fatal("no results, so the absence of a model call proves nothing") |
| + } |
| + if len(rec.calls) != 0 { |
| + t.Errorf("a typing search sent %d requests to the model", len(rec.calls)) |
| + } |
| + if !p.FactsDeferred { |
| + t.Error("FactsDeferred = false; search.js would never complete the box") |
| + } |
| + if len(modelRows(p)) != 0 { |
| + t.Errorf("model rows = %+v from a search that called no model", modelRows(p)) |
| + } |
| + |
| + full, err := s.Search(context.Background(), asker, "office address", 25) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(rec.calls) != 1 { |
| + t.Errorf("the full search sent %d requests, want 1", len(rec.calls)) |
| + } |
| + if full.FactsDeferred || len(modelRows(full)) != 1 { |
| + t.Errorf("full search: deferred = %v, model rows = %d; want false and 1", full.FactsDeferred, len(modelRows(full))) |
| + } |
| + |
| + // A query naming no model kind defers nothing. |
| + if q, _ := s.SearchWhileTyping(context.Background(), asker, "office", 25); q.FactsDeferred { |
| + t.Error("a query naming no model kind was marked deferred") |
| + } |
| +} |
diff --git a/internal/memoria/narrow_test.go b/internal/memoria/narrow_test.go| index 2e7274e..096c76f 100644 |
| --- a/internal/memoria/narrow_test.go |
| +++ b/internal/memoria/narrow_test.go |
| @@ -281,7 +281,7 @@ func TestGate40NarrowingPicksExactlyOneOverTheCap(t *testing.T) { |
| if target.DocumentID == 0 || target.Ordinal == 0 || len(p.Results) < 2 || target.DocumentID == p.Results[0].DocumentID { |
| t.Fatalf("fixture lacks distinct coordinates: target %+v, first %+v", target, p.Results[0]) |
| } |
| - s.addFacts(context.Background(), &p, "office phone") |
| + s.addFacts(context.Background(), &p, "office phone", true) |
| want := []Fact{{ |
| Kind: "phone", Title: "Target document", Trail: "Labelled office", |
| Label: "Office phone", Span: "01 547 0001", |
| @@ -382,3 +382,40 @@ func TestFactNoteText(t *testing.T) { |
| } |
| } |
| } |
| + |
| +// A keystroke's search is still a ruled search with a deterministic box. |
| +// SearchWhileTyping changes how the last word matches and defers §8.9; |
| +// nothing else. GPT-6 Astra's review (2026-10-26) found that bypassing |
| +// the ruling only for typing, or dropping the deterministic box only for |
| +// typing, both passed every test then. |
| +// |
| +// MUTATION-TESTED 2026-10-26, each reverted: rule() skipped in typing |
| +// mode → "a withheld document is in a typing search's results"; |
| +// addFacts skipped in typing mode → "a typing search built no box". |
| +func TestTypingSearchIsStillRuledAndBoxed(t *testing.T) { |
| + roster := docsRoster() |
| + s := factCorpus(t, &perItemCustody{ |
| + apps: roster, |
| + give: map[string]suite.Authorization{"b": suite.NOT_VISIBLE}, |
| + }, [][3]string{ |
| + {"a", "Dublin", "## Dublin office\n\nOffice phone: +353 (0)1 547 0001"}, |
| + {"b", "Cork", "## Cork office\n\nOffice phone: +353 (0)21 547 0002"}, |
| + }) |
| + asker := suite.Subject{Kind: suite.SubjectAddress, Value: "paul@tito.io"} |
| + |
| + p, err := s.SearchWhileTyping(context.Background(), asker, "office phone", 25) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(p.Results) == 0 { |
| + t.Fatal("no results, so nothing below proves anything") |
| + } |
| + for _, r := range p.Results { |
| + if r.Title == "Cork" { |
| + t.Errorf("a withheld document is in a typing search's results: %+v", r) |
| + } |
| + } |
| + if got := spans(p); !reflect.DeepEqual(got, []string{"+353 (0)1 547 0001"}) { |
| + t.Errorf("a typing search built no box, or the wrong one: spans = %q", got) |
| + } |
| +} |
diff --git a/internal/memoria/static/memoria.css b/internal/memoria/static/memoria.css| index 2e122a9..185bd6d 100644 |
| --- a/internal/memoria/static/memoria.css |
| +++ b/internal/memoria/static/memoria.css |
| @@ -412,6 +412,8 @@ html { scrollbar-gutter: stable; } |
| * server's and a pause only has to lift the attribute. */ |
| [rst-search-pending] [rst-search-empty] { visibility: hidden; } |
| [rst-search-empty] { margin: 0 0 1rem; } |
| +/* A typing request's note that §8.9 was deferred; never shown. */ |
| +[rst-facts-deferred] { display: none; } |
| /* The Sources page's lists: rows with a rule between them. They were |
| * rastrillo's rounded rst-list card holding bare <li>s, so browser bullets |
diff --git a/internal/memoria/static/search.js b/internal/memoria/static/search.js| index 9b21d0d..95710b2 100644 |
| --- a/internal/memoria/static/search.js |
| +++ b/internal/memoria/static/search.js |
| @@ -48,12 +48,20 @@ |
| (function () { |
| "use strict"; |
| - var DEBOUNCE_MS = 120; |
| + // 40ms, down from 120: the results felt like they trailed the typing |
| + // (Paul, 2026-10-26). In-flight requests for an older query are |
| + // aborted, so a shorter wait costs requests, not correctness. |
| + var DEBOUNCE_MS = 40; |
| // How long a live zero-result line waits for the person to stop typing. |
| - // Matching is whole-token, so "rev" finds nothing on the way to |
| - // "revenue"; "No matches" on every partial keystroke was noise (polish |
| + // The word being typed matches as a prefix now, but a misspelling still |
| + // finds nothing, and "No matches" on every keystroke is noise (polish |
| // audit §B1). A submitted search is a page render and shows it at once. |
| var PAUSE_MS = 900; |
| + // How long after the last keystroke a deferred box is completed. A |
| + // keystroke's request skips §8.9's model step (it can take 800ms and |
| + // sends passages out); once typing settles, one full request fills it. |
| + var SETTLE_MS = 450; |
| + var settleTimer = null; |
| var form = document.querySelector("form[rst-search]"); |
| var input = form && form.querySelector('input[type="search"]'); |
| @@ -118,12 +126,12 @@ |
| // away. Read once, from the URL the page was loaded with. |
| var explain = /(?:^|[?&])explain=facts(?:&|$)/.test(location.search) ? "&explain=facts" : ""; |
| - function search(q) { |
| + function search(q, typing) { |
| if (inflight) inflight.abort(); |
| var ctl = new AbortController(); |
| inflight = ctl; |
| inflightFor = q; |
| - return fetch("/search?q=" + encodeURIComponent(q) + explain, { |
| + return fetch("/search?q=" + encodeURIComponent(q) + explain + (typing ? "&typing=1" : ""), { |
| signal: ctl.signal, |
| credentials: "same-origin", |
| headers: { Accept: "text/html" }, |
| @@ -149,6 +157,7 @@ |
| if (ctl !== inflight) throw stale(); |
| inflight = inflightFor = null; |
| put(html, q); |
| + if (typing) settle(q); |
| }) |
| .catch(function (err) { |
| if (err && err.stale) throw err; |
| @@ -260,8 +269,25 @@ |
| status.textContent = said ? said.textContent.trim() : ""; |
| } |
| + /* settle completes a box a keystroke's request deferred: if the |
| + fragment says the model step was skipped, and the box still holds |
| + this query after a pause, ask once more without typing=1. */ |
| + function settle(q) { |
| + var el = region(); |
| + if (!el || !el.querySelector("[rst-facts-deferred]")) return; |
| + settleTimer = setTimeout(function () { |
| + settleTimer = null; |
| + if (input.value.trim() !== q) return; |
| + search(q, false).catch(function () {}); |
| + }, SETTLE_MS); |
| + } |
| + |
| function schedule() { |
| if (timer) clearTimeout(timer); |
| + if (settleTimer) { |
| + clearTimeout(settleTimer); |
| + settleTimer = null; |
| + } |
| var q = input.value.trim(); |
| // An in-flight fetch for some OTHER query is now answering a |
| // question nobody is asking. Dropping it here rather than leaving it |
| @@ -271,10 +297,16 @@ |
| inflight.abort(); |
| inflight = inflightFor = null; |
| } |
| - if (rendered() === q) return; |
| + // Same query as on screen — a space added, or a letter typed and |
| + // taken back. No new search, but a deferred box still needs its |
| + // settled request, and the timer for it was just cleared above. |
| + if (rendered() === q) { |
| + settle(q); |
| + return; |
| + } |
| timer = setTimeout(function () { |
| timer = null; |
| - search(input.value.trim()).catch(function () {}); |
| + search(input.value.trim(), true).catch(function () {}); |
| }, DEBOUNCE_MS); |
| } |
diff --git a/internal/memoria/store.go b/internal/memoria/store.go| index dd78574..d1c68e2 100644 |
| --- a/internal/memoria/store.go |
| +++ b/internal/memoria/store.go |
| @@ -122,6 +122,9 @@ type Page struct { |
| // Built from the same ruled candidates as Facts and nothing else; the |
| // page shows it only when asked (?explain=facts). |
| Explained []FactExplanation |
| + // FactsDeferred: this was a while-typing search, and §8.9's model |
| + // step was skipped for a kind the query named. Nothing was sent. |
| + FactsDeferred bool |
| } |
| // FactExplanation is one kind's account of the box: its candidates and |
| @@ -635,7 +638,20 @@ func (s *Store) Rebuild(ctx context.Context) (int, error) { |
| // — §4.1's typed subject travels on the wire precisely so a receiver that |
| // cannot make sense of it says UNKNOWN rather than guessing. |
| func (s *Store) Search(ctx context.Context, asker suite.Subject, query string, limit int) (Page, error) { |
| - return s.search(ctx, asker, query, limit, true) |
| + return s.search(ctx, asker, query, limit, modeFull) |
| +} |
| + |
| +// SearchWhileTyping is Search for live search's keystrokes: identical |
| +// ruling and the deterministic box, the last word matched as a prefix |
| +// (index.SearchTyping), and no §8.9 model call. A model call |
| +// may take up to provider.Deadline (800ms) and it ran on every keystroke |
| +// of any query naming a model kind, so live results waited on it and |
| +// each keystroke sent passages out (Paul, 2026-10-26: "the whole UI |
| +// appears to be slow"). When the model would have run, the page says so |
| +// (Page.FactsDeferred) and search.js asks again with Search once typing |
| +// pauses. |
| +func (s *Store) SearchWhileTyping(ctx context.Context, asker suite.Subject, query string, limit int) (Page, error) { |
| + return s.search(ctx, asker, query, limit, modeTyping) |
| } |
| // SearchWithoutFacts is Search for a surface that cannot show the fact |
| @@ -648,14 +664,27 @@ func (s *Store) Search(ctx context.Context, asker suite.Subject, query string, l |
| // without ever receiving the address it was for. Found by review. When the |
| // native client can show attributed facts, it moves back to Search. |
| func (s *Store) SearchWithoutFacts(ctx context.Context, asker suite.Subject, query string, limit int) (Page, error) { |
| - return s.search(ctx, asker, query, limit, false) |
| + return s.search(ctx, asker, query, limit, modeNoFacts) |
| } |
| -func (s *Store) search(ctx context.Context, asker suite.Subject, query string, limit int, facts bool) (Page, error) { |
| +// searchMode is which kind of search this is. |
| +type searchMode int |
| + |
| +const ( |
| + modeNoFacts searchMode = iota // whole words, no box (native search) |
| + modeTyping // last word a prefix; §8.8 only, §8.9 deferred |
| + modeFull // whole words; §8.8 and §8.9 |
| +) |
| + |
| +func (s *Store) search(ctx context.Context, asker suite.Subject, query string, limit int, mode searchMode) (Page, error) { |
| if asker.Value == "" { |
| return Page{}, errors.New("search: no asker; nothing can be authorized") |
| } |
| - hits, err := s.ix.Search(query, limit) |
| + find := s.ix.Search |
| + if mode == modeTyping { |
| + find = s.ix.SearchTyping |
| + } |
| + hits, err := find(query, limit) |
| if err != nil { |
| return Page{}, err |
| } |
| @@ -786,8 +815,8 @@ func (s *Store) search(ctx context.Context, asker suite.Subject, query string, l |
| // **After the ruling, never before it.** §8.8's box is built from the |
| // passages rule() kept, so a withheld one cannot contribute a |
| // candidate and cannot be counted towards the cap. |
| - if facts { |
| - s.addFacts(ctx, &page, query) |
| + if mode != modeNoFacts { |
| + s.addFacts(ctx, &page, query, mode == modeFull) |
| } |
| return page, nil |
| } |
| @@ -1109,7 +1138,7 @@ type Fact struct { |
| // question: a box that vanishes for passing the cap because of documents |
| // the reader may not see reports the existence of those documents, and so |
| // does an ambiguity of two where the reader may read one. |
| -func (s *Store) addFacts(ctx context.Context, p *Page, query string) { |
| +func (s *Store) addFacts(ctx context.Context, p *Page, query string, withModel bool) { |
| want := fact.Wanted(query) |
| if len(want) == 0 || len(p.Results) == 0 { |
| // **No database work for a query that names no kind**, which is |
| @@ -1227,9 +1256,16 @@ func (s *Store) addFacts(ctx context.Context, p *Page, query string) { |
| return |
| } |
| for _, k := range want { |
| - if fact.ModelKind(k) { |
| - p.Facts = append(p.Facts, s.modelFacts(ctx, p.Results, texts, k)...) |
| + if !fact.ModelKind(k) { |
| + continue |
| + } |
| + if !withModel { |
| + // Typing: nothing is sent, and the page says the box is not |
| + // finished so the next, settled request completes it. |
| + p.FactsDeferred = true |
| + continue |
| } |
| + p.Facts = append(p.Facts, s.modelFacts(ctx, p.Results, texts, k)...) |
| } |
| } |
diff --git a/internal/memoria/templates/layout.html b/internal/memoria/templates/layout.html| index 2a6a475..68309d8 100644 |
| --- a/internal/memoria/templates/layout.html |
| +++ b/internal/memoria/templates/layout.html |
| @@ -98,7 +98,7 @@ |
| this footer back in the same response. */}} |
| {{if .ModelOn}}Search is lexical. <strong>AI is on:</strong> a search |
| that asks for a postal address sends up to eight of its passages to |
| - TensorX, including while you type. No other document leaves this |
| + TensorX once you stop typing. No other document leaves this |
| instance. |
| {{else}}Search is lexical only — no assistant, and <strong>no document ever |
| leaves this instance</strong>.{{end}} |
diff --git a/internal/memoria/templates/results.html b/internal/memoria/templates/results.html| index 7196746..00ecca4 100644 |
| --- a/internal/memoria/templates/results.html |
| +++ b/internal/memoria/templates/results.html |
| @@ -17,6 +17,9 @@ |
| <div rst-callout-body><p>{{template "searchFailed"}}</p></div> |
| </div> |
| {{else if .Searched}} |
| + {{/* A typing request skipped §8.9's model step (nothing was sent); |
| + search.js sees this and asks again, in full, once typing pauses. */}} |
| + {{if .FactsDeferred}}<span rst-facts-deferred hidden></span>{{end}} |
| {{/* The count heading only when there is something to count. A zero |
| is said once, below, as one quiet line (spec §4): "0 results for |
| “rev”" over a callout was what live search showed on every partial |
diff --git a/internal/memoriatest/chrome_test.go b/internal/memoriatest/chrome_test.go| index 99724ec..00648f3 100644 |
| --- a/internal/memoriatest/chrome_test.go |
| +++ b/internal/memoriatest/chrome_test.go |
| @@ -438,7 +438,9 @@ func TestDeleteAsksFirst(t *testing.T) { |
| func TestNoZeroResultsWhileTyping(t *testing.T) { |
| h := newApp(t) |
| store(t, h, "Revenue", "revenue grows next year") |
| - frag := get(t, h, "/search?q=reve").Body.String() |
| + // A misspelling: the word being typed matches as a prefix now, so a |
| + // partial word ("reve") finds "revenue" and is no longer the zero case. |
| + frag := get(t, h, "/search?q=revx").Body.String() |
| if strings.Contains(frag, "0 results") || !strings.Contains(frag, "rst-search-empty") || strings.Contains(frag, "rst-callout") { |
| t.Errorf("the live zero state is not one marked quiet line:\n%s", frag) |
| } |
diff --git a/internal/memoriatest/factbox_test.go b/internal/memoriatest/factbox_test.go| index 3a6cfd7..1c9ebff 100644 |
| --- a/internal/memoriatest/factbox_test.go |
| +++ b/internal/memoriatest/factbox_test.go |
| @@ -495,7 +495,7 @@ func TestLiveSearchKeepsTheExplanation(t *testing.T) { |
| js := get(t, newApp(t), "/static/search.js").Body.String() |
| for _, want := range []string{ |
| `var explain = /(?:^|[?&])explain=facts(?:&|$)/.test(location.search) ? "&explain=facts" : "";`, |
| - `fetch("/search?q=" + encodeURIComponent(q) + explain,`, |
| + `fetch("/search?q=" + encodeURIComponent(q) + explain + (typing ? "&typing=1" : ""),`, |
| `"?q=" + encodeURIComponent(q) + explain;`, |
| } { |
| if !strings.Contains(js, want) { |
diff --git a/internal/memoriatest/footer_model_test.go b/internal/memoriatest/footer_model_test.go| index 652a3b7..fd80e76 100644 |
| --- a/internal/memoriatest/footer_model_test.go |
| +++ b/internal/memoriatest/footer_model_test.go |
| @@ -5,6 +5,7 @@ import ( |
| "io" |
| "log/slog" |
| "net/http" |
| + "net/url" |
| "path/filepath" |
| "strconv" |
| "strings" |
| @@ -209,3 +210,32 @@ func keys(m map[string]string) []string { |
| } |
| return out |
| } |
| + |
| +// Live search's keystrokes skip the model step and mark the fragment, so |
| +// search.js completes the box once typing pauses; the settled request |
| +// (no typing flag) runs it. Through the real route and template. |
| +// |
| +// MUTATION-TESTED 2026-10-26, reverted: the handler ignoring typing=1 → |
| +// "the typing fragment called the model"; the marker removed from the |
| +// template → "the typing fragment carries no deferral marker". |
| +func TestTypingFragmentsDeferTheModel(t *testing.T) { |
| + m := &countingModel{} |
| + h, _ := appWithModel(t, m) |
| + q := url.QueryEscape("office address") |
| + |
| + typing := get(t, h, "/search?q="+q+"&typing=1").Body.String() |
| + if m.calls != 0 { |
| + t.Errorf("the typing fragment called the model %d times", m.calls) |
| + } |
| + if !strings.Contains(typing, "<span rst-facts-deferred hidden></span>") { |
| + t.Errorf("the typing fragment carries no deferral marker:\n%s", typing) |
| + } |
| + |
| + settled := get(t, h, "/search?q="+q).Body.String() |
| + if m.calls != 1 { |
| + t.Errorf("the settled fragment called the model %d times, want 1", m.calls) |
| + } |
| + if strings.Contains(settled, "rst-facts-deferred") { |
| + t.Error("the settled fragment is marked deferred") |
| + } |
| +} |
diff --git a/internal/memoriatest/settle_browser_test.go b/internal/memoriatest/settle_browser_test.go| new file mode 100644 |
| index 0000000..bb27da1 |
| --- /dev/null |
| +++ b/internal/memoriatest/settle_browser_test.go |
| @@ -0,0 +1,91 @@ |
| +//go:build browser |
| + |
| +// Live search completes a deferred box once typing pauses, in a real |
| +// Chromium. Run with `make browser`. |
| +// |
| +// A keystroke's request skips §8.9's model step and marks the fragment; |
| +// search.js then makes one settled request. GPT-6 Astra's review |
| +// (2026-10-26) found the settled request lost for good when a space was |
| +// typed after the results arrived: the keystroke cleared the timer and |
| +// returned early because the trimmed query had not changed. And removing |
| +// settling altogether passed every test, browser ones included. |
| +// |
| +// MUTATION-TESTED 2026-10-26, each reverted: settle() emptied → "the |
| +// model was called 0 times"; the re-arm on an unchanged query removed → |
| +// the space case: "the model was called 0 times". |
| +package memoriatest |
| + |
| +import ( |
| + "context" |
| + "io" |
| + "log/slog" |
| + "net/http" |
| + "path/filepath" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/rastrillo/rastrillo/db" |
| + "amadan.net/rastrillo/rastrillo/harness" |
| + "github.com/chromedp/chromedp" |
| + |
| + memoria "amadan.net/oficina/memoria/internal/memoria" |
| +) |
| + |
| +func TestLiveSearchSettlesADeferredBox(t *testing.T) { |
| + for _, c := range []struct { |
| + name string |
| + after string // typed once the first results are on screen |
| + }{ |
| + {"typing stops", ""}, |
| + {"a space after the results arrive", " "}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + m := &countingModel{} |
| + rig := 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(m) |
| + if _, err := a.Store().Ingest(context.Background(), memoria.IngestSpec{ |
| + Source: "upload", Key: "office", Title: "Tito office", |
| + Body: "## Contact\n\nOffice address: 12 Main Street, Dublin 2", |
| + }); err != nil { |
| + t.Fatal(err) |
| + } |
| + return mux |
| + }) |
| + var deferred bool |
| + ctx, cancel := context.WithTimeout(rig.Context(), 20*time.Second) |
| + defer cancel() |
| + actions := []chromedp.Action{ |
| + chromedp.Navigate(rig.Origin + "/"), |
| + chromedp.WaitVisible(`input[type="search"]`, chromedp.ByQuery), |
| + chromedp.SendKeys(`input[type="search"]`, "office address", chromedp.ByQuery), |
| + chromedp.WaitVisible(`[rst-result-title]`, chromedp.ByQuery), |
| + } |
| + if c.after != "" { |
| + actions = append(actions, chromedp.SendKeys(`input[type="search"]`, c.after, chromedp.ByQuery)) |
| + } |
| + actions = append(actions, |
| + chromedp.Sleep(1500*time.Millisecond), |
| + chromedp.Evaluate(`!!document.querySelector("[rst-facts-deferred]")`, &deferred), |
| + ) |
| + if err := chromedp.Run(ctx, actions...); err != nil { |
| + t.Fatalf("live search: %v", err) |
| + } |
| + if m.calls != 1 { |
| + t.Errorf("the model was called %d times, want 1: the settled request never ran, or ran per keystroke", m.calls) |
| + } |
| + if deferred { |
| + t.Error("the box on screen is still marked deferred after the pause") |
| + } |
| + }) |
| + } |
| +} |