oficina / memoria Public

Clone
git clone https://amadan.net/oficina/memoria

Plain git — no account needed to clone.

Download

Download this file

1//go:build browser
2
3// Fiesta's rhythm audit over Memoria's screens, in a real Chromium. Run
4// with `make browser`.
5//
6// Paul, 2026-11-22: "Can we somehow put something in place to avoid
7// weird spacing issues like this in future?", then "Release and start
8// the rollout". `make ci` runs the stylesheet half (go tool fiesta
9// spacing); this is the half only a laid-out page can answer: every gap
10// between two blocks is a step of the scale, no text rests on a control,
11// and every heading sits closer to its own content than to what comes
12// before it.
13//
14// The audit does not walk into an element carrying an rst- name other
15// than rst-page, rst-stack and rst-section, because those are Fiesta's
16// components, spaced by Fiesta. Memoria's own regions are rst- names too
17// (rst-home, rst-paper, rst-fact-box, rst-ai-answer, …), so to the audit
18// each would be one opaque block. Each page is therefore read from main
19// AND from each of those regions it shows, as roots of their own: a
20// root is always walked. Fiesta's own components inside them (a callout,
21// a table, a list row) are still Fiesta's.
22//
23// One skip: the Colophon's list ([estilo-credits]), estilo's template
24// and stylesheet, whose h1 and list keep the browser's margins (18.8px);
25// that is estilo's to put on a stack. The door's card and the connect
26// pages are estilo's too, and opaque here by their estilo- and rst-
27// names without a skip; estilo audits its own card (6238a47).
28//
29// Screens are drawn in the states that change their blocks: the front
30// page with recent searches, a fact box, ?explain=facts, an AI answer,
31// no results, a document, its delete question, Add content (and with
32// its outcome flash), Sources and Notion unconnected and then connected
33// with an import behind them and suite apps in each breaker state, a
34// correction, Reports with a row, the 👎 page, the Colophon, a 404, and
35// team mode's partial lists. Not the upload tray: it is fixed in the
36// corner, out of the page's flow.
37//
38// Written against origin/main (5d9034d) first, its static/ and
39// templates/ under this branch's go.mod: 72 findings on 26 of the 34
40// screen-widths, 67 of them signed in (68 off-scale, such as the h1's
41// browser margin of 18.8px, 28px above the home lists and 17.4px under
42// the results count; and 4 headings no closer to their content than to
43// the block before them, the Add content h1 among them) and 5 on the
44// door (estilo before 6238a47: 22px under the brand). It passes on the
45// stack. MUTATION-TESTED 2026-11-22, each reverted: rst-stack taken off
46// <main> → 16 findings on a document, Add content, Sources and Notion at
47// both widths (an h1 back on its browser margin, 18.8px); [rst-ai-by]'s
48// margin put back to 0.4rem → "6.4px between blocks" in [rst-ai-answer]
49// at both widths, which only the region roots can see. (A hand margin on
50// a stack's child, [rst-home-lists] given back 1.75rem, changes nothing:
51// the stack's rule outweighs it, which is the point of the stack.)
52package memoriatest
53
54import (
55 "context"
56 "fmt"
57 "io"
58 "log/slog"
59 "net/http"
60 "net/url"
61 "path/filepath"
62 "regexp"
63 "testing"
64 "time"
65
66 "amadan.net/rastrillo/fiesta/check/rhythm"
67 "amadan.net/rastrillo/rastrillo/db"
68 "amadan.net/rastrillo/rastrillo/harness"
69 "github.com/chromedp/cdproto/runtime"
70 "github.com/chromedp/chromedp"
71
72 memoria "amadan.net/oficina/memoria/internal/memoria"
73 "amadan.net/oficina/memoria/internal/memoria/notion"
74 "amadan.net/oficina/memoria/internal/memoria/provider"
75 "amadan.net/oficina/memoria/internal/memoria/sibling"
76)
77
78// quickAI answers at once, with a paragraph and a list, so the answer
79// card is drawn with both of its shapes.
80type quickAI struct{}
81
82func (quickAI) ExtractAddresses(context.Context, []string) ([]provider.Pointer, error) {
83 return []provider.Pointer{}, nil
84}
85
86func (quickAI) Answer(context.Context, string, []string) ([]provider.Sentence, error) {
87 return []provider.Sentence{
88 {Text: "The kitchen rota is pinned by the kettle.", Cite: []int{0}},
89 {Text: "- Mondays: Paul", Cite: []int{0}},
90 {Text: "- Tuesdays: Doc", Cite: []int{0}},
91 }, nil
92}
93
94// rhythmRegions are Memoria's own regions that hold blocks, each audited
95// as a root of its own where the page shows one (see above).
96var rhythmRegions = []string{
97 "[rst-home]",
98 "[rst-home-lists] > section",
99 "[rst-refresh=\"results\"]",
100 "[rst-answer]",
101 "[rst-ai-answer]",
102 "[rst-fact-box]",
103 "[rst-paper]",
104 "[rst-correct]",
105 "[rst-correct-form]",
106 "[rst-dropzone]",
107 "[rst-sources] > li",
108 "[rst-report]",
109 "[rst-page-footer]",
110}
111
112// rhythmSkip are the regions whose spacing is not the page's.
113var rhythmSkip = []string{
114 // The Colophon is estilo's template and estilo's stylesheet
115 // (estilo/credits); its h1 and list keep the browser's margins, which
116 // is estilo's to put on its stack.
117 "[estilo-credits]",
118}
119
120// auditRhythm reads the page the browser is on from main and from each
121// of Memoria's regions it shows, and returns every finding.
122func auditRhythm(ctx context.Context) ([]rhythm.Finding, error) {
123 var all []rhythm.Finding
124 for _, root := range append([]string{"main"}, rhythmRegions...) {
125 var present bool
126 if err := chromedp.Do(ctx, evalInto(&present, fmt.Sprintf(`!!document.querySelector(%q)`, root))); err != nil {
127 return nil, err
128 }
129 if !present {
130 continue
131 }
132 var found []rhythm.Finding
133 if err := chromedp.Do(ctx, evalInto(&found, rhythm.Expression(root, rhythm.Options{Skip: rhythmSkip}))); err != nil {
134 return nil, fmt.Errorf("audit %s: %w", root, err)
135 }
136 for i := range found {
137 found[i].Message = root + ": " + found[i].Message
138 }
139 all = append(all, found...)
140 }
141 return all, nil
142}
143
144// settle waits for the page's fonts, so the audit measures the type the
145// reader sees and not the fallback's.
146var settle = evalOnly(`document.fonts.ready.then(() => true)`, func(p *runtime.EvaluateParams) { p.AwaitPromise = new(true) })
147
148// TestEveryScreenKeepsTheRhythm is the audit over every signed-in
149// screen, at a desktop width and a phone's.
150func TestEveryScreenKeepsTheRhythm(t *testing.T) {
151 var app interface {
152 Store() *memoria.Store
153 UseFakeSource(memoria.SourceClient, func(context.Context, string) (string, error))
154 UseSiblings(memoria.Custody)
155 PreviewUnknownStanding()
156 }
157 rig := harness.New(t, func(origin string) http.Handler {
158 logger := slog.New(slog.NewTextHandler(io.Discard, nil))
159 d, err := db.Open(filepath.Join(t.TempDir(), "app.db"), logger)
160 if err != nil {
161 t.Fatalf("db.Open: %v", err)
162 }
163 t.Cleanup(func() { d.Close() })
164 mux, a, err := memoria.AppForTest(d, origin, testDEK(t), logger)
165 if err != nil {
166 t.Fatalf("AppForTest: %v", err)
167 }
168 app = a
169 a.UseFakeModel(quickAI{})
170 for _, doc := range [][2]string{
171 {"Office", "## Office Address\n\nThe office phone number is: +353 (0)1 547 7854\n\n" +
172 "We also have the following unused phone numbers: +353 (0)1 598 1234\n\nOffice VAT: IE3384527RH\n\n" +
173 "### Directions\n\n- Take the Luas to Abbey Street\n- Walk north\n - Past the Spire\n\n> Ring the bell twice.\n\n" +
174 "| Floor | Team |\n|---|---|\n| 1 | Sales |\n| 2 | Ops |\n"},
175 {"Kitchen", "## Rota\n\nThe kitchen rota is pinned by the kettle."},
176 {"Accounts", "## Contact\n\nAccounts email: accounts@tito-example.ie"},
177 } {
178 if _, err := a.Store().Ingest(context.Background(), memoria.IngestSpec{Source: "upload", Key: doc[0], Title: doc[0], Body: doc[1]}); err != nil {
179 t.Fatal(err)
180 }
181 }
182 return mux
183 })
184
185 run := func(what string, actions ...chromedp.Action[chromedp.Void]) {
186 t.Helper()
187 ctx, cancel := context.WithTimeout(rig.Context(), 30*time.Second)
188 defer cancel()
189 if err := chromedp.Do(ctx, actions...); err != nil {
190 t.Fatalf("%s: %v", what, err)
191 }
192 }
193
194 // A document's page, its delete question, a correction (so Reports
195 // has a row) and a 👎 (so the feedback page exists).
196 var at string
197 run("find a document",
198 chromedp.Navigate(rig.Origin+"/documents"),
199 chromedp.WaitVisible(chromedp.CSS(`a[href^="/documents/"]`)),
200 attributeInto(chromedp.CSS(`a[href^="/documents/"]`), "href", &at, nil),
201 )
202 doc := regexp.MustCompile(`^/documents/\d+$`).FindString(at)
203 if doc == "" {
204 t.Fatalf("the documents list links no document (got %q)", at)
205 }
206 phone := "/facts/correct?q=" + url.QueryEscape("office phone number")
207 run("report a correction",
208 chromedp.Navigate(rig.Origin+phone),
209 chromedp.WaitVisible(chromedp.CSS(`input[name="choice"]`)),
210 chromedp.Click(chromedp.CSS(`input[name="choice"]`)),
211 chromedp.Submit(chromedp.CSS(`input[name="choice"]`)),
212 chromedp.WaitVisible(chromedp.CSS(`input[type="search"]`)),
213 )
214 var feedback string
215 run("rate an answer down",
216 chromedp.Navigate(rig.Origin+"/?q="+url.QueryEscape("kitchen rota")),
217 chromedp.WaitVisible(chromedp.CSS(`[rst-ai-feedback] button[value="down"]`)),
218 chromedp.Click(chromedp.CSS(`[rst-ai-feedback] button[value="down"]`)),
219 chromedp.WaitVisible(chromedp.CSS(`textarea[name="note"]`)),
220 locationInto(&feedback),
221 )
222 if u, err := url.Parse(feedback); err == nil {
223 feedback = u.Path
224 }
225
226 audit := func(path string, width int64, actions ...chromedp.Action[chromedp.Void]) {
227 t.Helper()
228 ctx, cancel := context.WithTimeout(rig.Context(), 30*time.Second)
229 defer cancel()
230 err := chromedp.Do(ctx, append([]chromedp.Action[chromedp.Void]{chromedp.EmulateViewport(width, 900)}, append(actions, settle)...)...)
231 var found []rhythm.Finding
232 if err == nil {
233 found, err = auditRhythm(ctx)
234 }
235 if err != nil {
236 t.Fatalf("%s at %dpx: %v", path, width, err)
237 }
238 if len(found) > 0 {
239 t.Errorf("%s at %dpx: %s", path, width, rhythm.Report(found))
240 }
241 }
242 visit := func(path, ready string, width int64) {
243 t.Helper()
244 audit(path, width, chromedp.Navigate(rig.Origin+path), chromedp.WaitVisible(chromedp.CSS(ready)))
245 }
246
247 screens := []struct{ path, ready string }{
248 {"/", `[rst-home]`},
249 {"/?q=" + url.QueryEscape("office phone number"), `[rst-fact-box]`},
250 {"/?q=" + url.QueryEscape("office phone number") + "&explain=facts", `[rst-fact-explain]`},
251 {"/?q=" + url.QueryEscape("kitchen rota"), `[rst-ai-answer]`},
252 {"/?q=" + url.QueryEscape("zebra crossings"), `[rst-search-empty]`},
253 {"/documents", `[rst-docs]`},
254 {doc, `[rst-paper]`},
255 {doc + "/delete", `form[action$="/delete"]`},
256 {"/add", `textarea[name="body"]`},
257 {"/connectors", `main h1`},
258 {"/connectors/notion", `input[name="token"]`},
259 {phone, `input[name="choice"]`},
260 {"/reports", `[rst-report]`},
261 {feedback, `textarea[name="note"]`},
262 {"/help/open-source", `main h1`},
263 {"/no-such-page", `main`},
264 }
265 for _, width := range []int64{1280, 390} {
266 for _, s := range screens {
267 visit(s.path, s.ready, width)
268 }
269 // Add content with its outcome: the flash under the form.
270 audit("/add, stored", width,
271 chromedp.Navigate(rig.Origin+"/add"),
272 chromedp.WaitVisible(chromedp.CSS(`textarea[name="body"]`)),
273 chromedp.SendKeys(chromedp.CSS(`textarea[name="body"]`), "The fire drill is on Thursdays."),
274 chromedp.Click(chromedp.CSS(`[rst-actions] button`)),
275 chromedp.WaitVisible(chromedp.CSS(`main [rst-callout]`)),
276 )
277 }
278
279 // Sources and Notion connected, with an import behind them, and the
280 // suite apps in the breaker's three states (tools/drive's seed).
281 seedRhythmConnector(t, app)
282 seedRhythmSiblings(t, app)
283 for _, width := range []int64{1280, 390} {
284 visit("/connectors/notion", `[rst-facts]`, width)
285 visit("/connectors", `[rst-source-name]`, width)
286 }
287
288 // Team mode with the reader's standing unknown: the list pages are
289 // partial, with the notice.
290 app.PreviewUnknownStanding()
291 for _, width := range []int64{1280, 390} {
292 for _, path := range []string{"/", "/documents", "/reports", "/?q=" + url.QueryEscape("office phone number")} {
293 visit(path, `main [rst-callout]`, width)
294 }
295 }
296}
297
298// rhythmSource is a two-page stand-in for Notion.
299type rhythmSource struct{}
300
301func (rhythmSource) Roots(context.Context) (roots, orphans []notion.Ref, err error) {
302 return []notion.Ref{{ID: "handbook", Title: "Handbook", EditedTime: "t1", Kind: notion.KindPage}}, nil, nil
303}
304
305func (rhythmSource) Fetch(_ context.Context, ref notion.Ref) (*notion.Content, error) {
306 c := &notion.Content{Markdown: "## " + ref.Title + "\n\nImported for the rhythm audit.", UnreadBlocks: 2}
307 if ref.ID == "handbook" {
308 c.Children = []notion.Ref{{ID: "onboarding", Title: "Onboarding", Path: []string{"Handbook"}, EditedTime: "t1", Kind: notion.KindPage}}
309 }
310 return c, nil
311}
312
313// seedRhythmConnector connects Notion and runs one import to the end.
314func seedRhythmConnector(t *testing.T, app interface {
315 Store() *memoria.Store
316 UseFakeSource(memoria.SourceClient, func(context.Context, string) (string, error))
317}) {
318 t.Helper()
319 ctx := context.Background()
320 app.UseFakeSource(rhythmSource{}, func(context.Context, string) (string, error) { return "rhythm-workspace", nil })
321 if err := app.Store().SaveConnector(ctx, "notion", "ntn_rhythm_token", "rhythm-workspace"); err != nil {
322 t.Fatal(err)
323 }
324 c, err := app.Store().Connector(ctx, "notion")
325 if err != nil {
326 t.Fatal(err)
327 }
328 run, err := app.Store().StartRun(ctx, c.ID)
329 if err != nil {
330 t.Fatal(err)
331 }
332 memoria.NewSyncer(app.Store(), slog.New(slog.NewTextHandler(io.Discard, nil))).RunWith(ctx, rhythmSource{}, c.ID, run.ID)
333}
334
335// seedRhythmSiblings puts three suite apps on Sources, quiet, firing and
336// cannot-determine, as tools/drive does.
337func seedRhythmSiblings(t *testing.T, app interface {
338 Store() *memoria.Store
339 UseSiblings(memoria.Custody)
340}) {
341 t.Helper()
342 ctx := context.Background()
343 custody, err := memoria.NewSiblings("rhythm", nil, []sibling.Sibling{
344 {Name: "Docs", BaseURL: "https://rhythm.docs.oficina.works", Token: "rhythm"},
345 {Name: "Sheets", BaseURL: "https://rhythm.sheets.oficina.works", Token: "rhythm"},
346 {Name: "Calendar", BaseURL: "https://rhythm.calendar.oficina.works", Token: "rhythm"},
347 })
348 if err != nil {
349 t.Fatal(err)
350 }
351 app.UseSiblings(custody)
352 store, now := app.Store(), time.Now().UTC()
353 for app, since := range map[string]time.Time{"Docs": now.AddDate(0, 0, -30), "Sheets": now.AddDate(0, 0, -30), "Calendar": now.AddDate(0, 0, -2)} {
354 if err := store.StartCounting(ctx, app, since); err != nil {
355 t.Fatal(err)
356 }
357 }
358 for _, who := range []string{"ana@example.com", "ben@example.com", "cleo@example.com"} {
359 store.SeedTallyForDrive(ctx, "Sheets", who, now.AddDate(0, 0, -3), 5, 0)
360 store.SeedTallyForDrive(ctx, "Sheets", who, now, 0, 4)
361 }
362}
363
364// TestTheDoorKeepsTheRhythm: the signed-out pages, drawn through the
365// production App with sign-in wired: the door and /signed-out.
366func TestTheDoorKeepsTheRhythm(t *testing.T) {
367 rig := harness.New(t, func(origin string) http.Handler {
368 logger := slog.New(slog.NewTextHandler(io.Discard, nil))
369 d, err := db.Open(filepath.Join(t.TempDir(), "app.db"), logger)
370 if err != nil {
371 t.Fatalf("db.Open: %v", err)
372 }
373 t.Cleanup(func() { d.Close() })
374 mux, a, err := memoria.App(d, origin, testDEK(t), logger)
375 if err != nil {
376 t.Fatalf("App: %v", err)
377 }
378 au, err := memoria.NewAuth(d.Writer(), memoria.AuthEnv{
379 Origin: origin, InstanceKey: "rhythm-test-instance-key",
380 Owners: []string{dialTestOwner}, Mailer: &stubMailer{},
381 }, logger, a)
382 if err != nil {
383 t.Fatalf("NewAuth: %v", err)
384 }
385 a.UseAuth(au)
386 a.SetOwners([]string{dialTestOwner})
387 a.MountAuth(mux, origin)
388 return mux
389 })
390 for _, width := range []int64{1280, 390} {
391 for _, path := range []string{"/signin", "/signed-out"} {
392 ctx, cancel := context.WithTimeout(rig.Context(), 30*time.Second)
393 err := chromedp.Do(ctx,
394 chromedp.EmulateViewport(width, 900),
395 chromedp.Navigate(rig.Origin+path),
396 chromedp.WaitVisible(chromedp.CSS(`main`)),
397 settle,
398 )
399 var found []rhythm.Finding
400 if err == nil {
401 found, err = auditRhythm(ctx)
402 }
403 cancel()
404 if err != nil {
405 t.Fatalf("%s at %dpx: %v", path, width, err)
406 }
407 if len(found) > 0 {
408 t.Errorf("%s at %dpx: %s", path, width, rhythm.Report(found))
409 }
410 }
411 }
412}
413