//go:build browser // Gate 7, scriptless (spec §11): the walk through today's note, ⌘K, // create, link, save and conflict, in a real Chromium with JavaScript // off and then on. The harness fails on any console error, failed // request or 4xx/5xx, and on any JS value leaked to the screen. // // make browser // // It needs a Chromium: on PATH, via RASTRILLO_CHROME, or in a Playwright // cache. A skip is not a pass. package mapatest import ( "context" "io" "log/slog" "net/http" "net/http/httptest" "path/filepath" "strconv" "strings" "testing" "time" "amadan.net/rastrillo/rastrillo/blobs" "amadan.net/rastrillo/rastrillo/db" "amadan.net/rastrillo/rastrillo/harness" "github.com/chromedp/cdproto/cdp" "github.com/chromedp/cdproto/emulation" "github.com/chromedp/chromedp" "github.com/chromedp/chromedp/kb" "amadan.net/oficina/mapa/internal/mapa" ) // browserRig is the app signed in as Ana, at the rig's own origin, and // the store, so Bo can write in between as a teammate would. Every // request asks for en-IE, the team's default, whatever the browser's // own Accept-Language says (build note 85). func browserRig(t *testing.T, pages int, options ...harness.Option) (*harness.Rig, *mapa.Store) { return browserRigOf(t, pages, "en-IE", nil, options...) } // browserRigAsking is browserRig with each request's Accept-Language // replaced by language; "" leaves the browser's own. func browserRigAsking(t *testing.T, pages int, language string, options ...harness.Option) (*harness.Rig, *mapa.Store) { return browserRigOf(t, pages, language, nil, options...) } // browserRigWith is browserRig with its images kept in a directory, as // development keeps them, seen through wrap when there is one: the // images' L9 holds uploads in flight with it. func browserRigWith(t *testing.T, pages int, wrap func(blobs.Store) blobs.Store, options ...harness.Option) (*harness.Rig, *mapa.Store) { return browserRigOf(t, pages, "en-IE", wrap, options...) } // browserRigOf is the rig asking for language, its images seen through // wrap when there is one. func browserRigOf(t *testing.T, pages int, language string, wrap func(blobs.Store) blobs.Store, options ...harness.Option) (*harness.Rig, *mapa.Store) { var store *mapa.Store rig := harness.New(t, func(origin string) http.Handler { logger := slog.New(slog.NewTextHandler(io.Discard, nil)) database, err := db.Open(filepath.Join(t.TempDir(), "mapa.db"), logger) if err != nil { t.Fatal(err) } t.Cleanup(func() { database.Close() }) env := testEnv(Ana + "," + Bo) env["MAPA_ORIGIN"] = origin config, err := mapa.LoadConfig(func(key string) string { return env[key] }) if err != nil { t.Fatal(err) } images, err := blobs.Dir(filepath.Join(t.TempDir(), "images")) if err != nil { t.Fatal(err) } if wrap != nil { images = wrap(images) } config.Images.Objects = images built, err := mapa.AppForTest(database, config, logger, Ana) if err != nil { t.Fatal(err) } store = built.Store if err := mapa.SeedSynthetic(context.Background(), store, Bo, pages); err != nil { t.Fatal(err) } return asking(language, built.Mux) }, options...) return rig, store } // asking sets every request's Accept-Language to language, unless it // is "". func asking(language string, next http.Handler) http.Handler { if language == "" { return next } return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { request.Header.Set("Accept-Language", language) next.ServeHTTP(writer, request) }) } // scripts turns JavaScript on or off for the pages that load next. func scripts(on bool) chromedp.Action[chromedp.Void] { return chromedp.Func(func(ctx context.Context, target *chromedp.Target) error { _, err := cdp.Call(ctx, target, emulation.SetScriptExecutionDisabled, emulation.SetScriptExecutionDisabledParams{Value: !on}) return err }) } // written is a page's text as read, never the script's live preview. const written = `article[mapa-body]:not([mapa-preview])` // save is the page's Save: the primary submit of its form. const save = `main form button[type="submit"][rst-btn~="primary"]` // press activates a control the way a keyboard does: focus, then Enter. func press(selector string) chromedp.Action[chromedp.Void] { return chromedp.Steps(chromedp.Focus(selector), chromedp.KeyEvent("\r")) } // drive runs steps with a deadline, so a step that cannot happen fails // the test instead of waiting for ever. func drive(t *testing.T, rig *harness.Rig, steps ...chromedp.Action[chromedp.Void]) { t.Helper() ctx, cancel := context.WithTimeout(rig.Context(), 20*time.Second) defer cancel() if err := chromedp.Do(ctx, steps...); err != nil { t.Fatalf("a step did not happen: %v", err) } } // read runs one action that returns a value, with a deadline. func read[T any](t *testing.T, rig *harness.Rig, action chromedp.Action[T]) T { t.Helper() ctx, cancel := context.WithTimeout(rig.Context(), 20*time.Second) defer cancel() value, err := chromedp.Run(ctx, action) if err != nil { t.Fatalf("could not read the page: %v", err) } return value } func text(t *testing.T, rig *harness.Rig, selector string) string { t.Helper() return read(t, rig, chromedp.Text(selector)) } func TestGate7TheWalkWithScriptsOff(t *testing.T) { rig, store := browserRig(t, 0) rig.Run(scripts(false)) walk(t, rig, store, false) } func TestGate7TheWalkWithScriptsOn(t *testing.T) { rig, store := browserRig(t, 0) rig.Run(scripts(true)) walk(t, rig, store, true) } // walk is gate 7's walk: today's note, search, create, link, save, // conflict. func walk(t *testing.T, rig *harness.Rig, store *mapa.Store, live bool) { t.Helper() drive(t, rig, chromedp.Navigate(rig.Origin+"/")) writeToday(t, rig, live) rig.Screen(`[mapa-actions] a[href$="/edit"]`, "today, written") if !strings.Contains(text(t, rig, written), "about the pilot") { t.Fatal("today's note did not save") } if live { searchByPalette(t, rig) } else { searchByPage(t, rig) } rig.Screen(`main input[name="title"]`, "create, offered") createAcme(t, rig) rig.Screen("header[mapa-page-head]", "the new page") if !strings.Contains(text(t, rig, "#backlinks ~ *, [mapa-linked]"), "November") { t.Fatal("the new page does not show today's note linking to it") } saveAndConflict(t, rig, store, live) if live { historyInPlace(t, rig) } historyAndRestore(t, rig) } // createAcme creates the offered page, then writes its text. New page // is one title field (build note 77), so the text is written on the // page, here through Edit as Markdown, the floor. func createAcme(t *testing.T, rig *harness.Rig) { t.Helper() drive(t, rig, press(save), chromedp.WaitVisible("h1[mapa-title]")) path := strings.TrimPrefix(read(t, rig, chromedp.Location()), rig.Origin) drive(t, rig, chromedp.Navigate(rig.Origin+path+"/edit"), chromedp.SendKeys("textarea[mapa-editor]", "Acme is a customer."), press(save)) } // writeToday writes today's note: in the page editor with scripts, and // with them off through Edit as Markdown, the floor (level-up §6.10). func writeToday(t *testing.T, rig *harness.Rig, live bool) { if !live { rig.Screen(`[mapa-actions] a[href$="/edit"]`, "today, unwritten") drive(t, rig, chromedp.Click(`[mapa-actions] a[href$="/edit"]`), chromedp.WaitVisible("textarea[mapa-editor]"), chromedp.SendKeys("textarea[mapa-editor]", "Met [[Acme]] about the pilot."), press(save)) return } rig.Screen(mounted, "today, unwritten") drive(t, rig, caretAt(0), chromedp.KeyEvent("Met [[Acme]] about the pilot."), chromedp.KeyEvent("s", mod())) read(t, rig, chromedp.Poll[bool](`mapaEditor.saver.version === "0" && mapaEditor.saver.base !== "0"`)) drive(t, rig, chromedp.Reload(), chromedp.WaitVisible(mounted)) } // searchByPage is ⌘K without scripts: GET /search?q= as a full page, // and its Create offer. func searchByPage(t *testing.T, rig *harness.Rig) { drive(t, rig, chromedp.Navigate(rig.Origin+"/search")) rig.Screen(`input[name="q"]`, "search") drive(t, rig, chromedp.SendKeys(`input[name="q"]`, "Acme"), chromedp.Submit(`input[name="q"]`), ) rig.Screen("[mapa-create] a", "search results") create := read(t, rig, chromedp.AttributeValue("[mapa-create] a", "href")).Value drive(t, rig, chromedp.Navigate(rig.Origin+create)) } // searchByPalette is ⌘K with scripts: the box over everything, and its // Create offer, chosen with the keyboard. func searchByPalette(t *testing.T, rig *harness.Rig) { drive(t, rig, chromedp.KeyEvent("k", chromedp.KeyModifiers( chromedp.ModifierCtrl)), chromedp.WaitVisible("dialog[mapa-palette] input"), chromedp.SendKeys("dialog[mapa-palette] input", "Acme"), // The answer to the whole word, not to "Acm": each keystroke // asks, and an earlier answer can be on screen first. chromedp.WaitVisible( `[mapa-palette-results] a[href="/new?title=Acme"]`), ) if !strings.Contains(text(t, rig, "[mapa-palette-results]"), "Create") { t.Fatal("⌘K does not offer to create Acme") } // Create is the last choice: up from the first wraps to it. drive(t, rig, chromedp.KeyEvent(kb.ArrowUp), chromedp.KeyEvent("\r")) } // saveAndConflict edits the page, has Bo save the same block meanwhile, // and settles the conflict by choosing. func saveAndConflict(t *testing.T, rig *harness.Rig, store *mapa.Store, live bool) { path := strings.TrimPrefix(read(t, rig, chromedp.Location()), rig.Origin) drive(t, rig, chromedp.Navigate(rig.Origin+path+"/edit")) rig.Screen("textarea[mapa-editor]", "the editor") drive(t, rig, chromedp.SendKeys("textarea[mapa-editor]", "Ana's words. "), ) if live { assistedEditing(t, rig) } writeAsBo(t, store, path) drive(t, rig, press(save)) rig.Screen("form[mapa-conflict]", "the conflict view") drive(t, rig, chromedp.Focus(`input[value="mine"]`), chromedp.KeyEvent(" "), press(`form[mapa-conflict] button[type="submit"]`), ) rig.Screen("header[mapa-page-head]", "after choosing") got := text(t, rig, written) if !strings.Contains(got, "Ana's words") || strings.Contains(got, "Bo") { t.Fatalf("the choice did not stick: %q", got) } } // writeAsBo saves the page's only block as Bo, through the store. func writeAsBo(t *testing.T, store *mapa.Store, path string) { t.Helper() ctx := context.Background() pageID, _, err := store.RowID(ctx, strings.TrimPrefix(path, "/p/")) if err != nil { t.Fatal(err) } viewer, _ := store.Viewer(ctx, Bo, nil) history, err := store.History(ctx, viewer, pageID, 0) if err != nil || len(history.Versions) == 0 { t.Fatalf("history: %v", err) } if _, err := store.Commit(ctx, Bo, pageID, history.Versions[0].Revision, "Acme, as Bo has it."); err != nil { t.Fatal(err) } } // assistedEditing is what scripts add to the editor: the preview, [[ // completion, and an autosave that writes a draft and not the page. func assistedEditing(t *testing.T, rig *harness.Rig) { drive(t, rig, chromedp.SendKeys("textarea[mapa-editor]", " See [[Acm"), chromedp.WaitVisible("[mapa-suggest] li"), chromedp.KeyEvent("\r"), chromedp.WaitVisible("[mapa-preview] a"), chromedp.Sleep(2*time.Second), ) value := read(t, rig, chromedp.Value("textarea[mapa-editor]")) if !strings.Contains(value, "See [[Acme]]") { t.Fatalf("[[ completion left %q", value) } status := text(t, rig, "[mapa-status]") if !strings.Contains(status, "Draft saved") { t.Fatalf("no autosave: %q", status) } } // TestKeystrokeToResults is §6.1's second warm target, at gate 6's size: // from a keystroke in ⌘K to its results, p95 ≤ 100 ms, same machine. // // **What is asserted is keystroke to results in the page**, timed inside // the page from the keystroke to the result list changing: the app's // whole part, request and render included. Paint follows in the next // frame on a real screen. Headless Chromium has no display to pace its // frames, and its next animation frame arrived 20 to 150 ms late with // the list long since rendered, so that figure is logged, not asserted // (spec §15, build note). Keys are typed from the page, as an input // event, because a DevTools key event is held for the renderer's next // frame for the same reason. func TestKeystrokeToResults(t *testing.T) { ctx := plainBrowser(t, fixturePages) run := func(steps ...chromedp.Action[chromedp.Void]) { t.Helper() if err := chromedp.Do(ctx, steps...); err != nil { t.Fatal(err) } } run(chromedp.WaitVisible(`input[name="q"]`), chromedp.KeyEvent("k", chromedp.KeyModifiers(chromedp.ModifierCtrl)), chromedp.WaitVisible("dialog[mapa-palette] input"), chromedp.Evaluate[chromedp.Void](keystrokeTimer)) words := mapa.SyntheticWords() for _, word := range []string{"w", words[3], words[400], "stra bra", mapa.SyntheticTitle(4321)} { for _, key := range word { run(chromedp.Evaluate[chromedp.Void]( "__type("+strconv.Quote(string(key))+")"), chromedp.Sleep(120*time.Millisecond)) } run(chromedp.Evaluate[chromedp.Void]("__clear()"), chromedp.Sleep(120*time.Millisecond)) } rendered := timings(t, ctx, "__rendered.slice(1)") painted := timings(t, ctx, "__painted.slice(1)") p95 := percentile(rendered, 95) t.Logf("keystroke to results, %d keystrokes at %d pages: p50 %v, "+ "p95 %v; headless next frame p50 %v, p95 %v", len(rendered), fixturePages, percentile(rendered, 50), p95, percentile(painted, 50), percentile(painted, 95)) if p95 > 100*time.Millisecond { t.Errorf("p95 is %v, over §6.1's 100 ms", p95) } } func timings(t *testing.T, ctx context.Context, expression string) []time.Duration { t.Helper() times, err := chromedp.Run(ctx, chromedp.Evaluate[[]float64](expression)) if err != nil || len(times) < 30 { t.Fatalf("%d keystrokes timed: %v", len(times), err) } out := make([]time.Duration, len(times)) for at, millis := range times { out[at] = time.Duration(millis * float64(time.Millisecond)) } return out } // keystrokeTimer types into ⌘K from the page and times each keystroke to // the result list changing, and to the frame after. const keystrokeTimer = `(function () { window.__rendered = []; window.__painted = []; var input = document.querySelector("dialog[mapa-palette] input"); var list = document.querySelector("[mapa-palette-results]"); var started = 0; window.__type = function (key) { started = performance.now(); input.value += key; input.dispatchEvent(new Event("input")); }; window.__clear = function () { started = 0; input.value = ""; }; new MutationObserver(function () { if (!started) return; var from = started; started = 0; __rendered.push(performance.now() - from); requestAnimationFrame(function () { __painted.push(performance.now() - from); }); }).observe(list, { childList: true }); })()` // plainBrowser serves the app with pages synthetic pages and opens its // search page in a headless Chromium with chromedp's defaults. func plainBrowser(t *testing.T, pages int) context.Context { logger := slog.New(slog.NewTextHandler(io.Discard, nil)) database, err := db.Open(filepath.Join(t.TempDir(), "mapa.db"), logger) if err != nil { t.Fatal(err) } t.Cleanup(func() { database.Close() }) listener := httptest.NewUnstartedServer(nil) origin := "http://" + listener.Listener.Addr().String() env := testEnv(Ana + "," + Bo) env["MAPA_ORIGIN"] = origin config, err := mapa.LoadConfig(func(key string) string { return env[key] }) if err != nil { t.Fatal(err) } built, err := mapa.AppForTest(database, config, logger, Ana) if err != nil { t.Fatal(err) } mapa.SeedSynthetic(context.Background(), built.Store, Bo, pages) listener.Config.Handler = built.Mux listener.Start() t.Cleanup(listener.Close) options := append(chromedp.DefaultExecAllocatorOptions[:], chromedp.ExecPath(harness.ChromePath(t))) allocator, cancelAllocator := chromedp.NewExecAllocator( context.Background(), options...) ctx, cancel := chromedp.NewContext(allocator) t.Cleanup(func() { cancel(); cancelAllocator() }) err = chromedp.Do(ctx, chromedp.Navigate(origin+"/search")) if err != nil { t.Fatal(err) } return ctx } // Review H1: an idle commit that merges a teammate's edit, then a Save, // keeps both edits. Before the fix the Save went out from the unmerged // textarea over the merged revision and quietly undid the teammate's. func TestAnIdleMergeThenSaveKeepsBothEdits(t *testing.T) { rig, store := browserRig(t, 0) ctx := context.Background() page, err := store.CreateTeamPage(ctx, Bo, "Plan", "One.\n\nTwo.") if err != nil { t.Fatal(err) } path := rig.Origin + mapa.PagePath(page) drive(t, rig, scripts(true), chromedp.Navigate(path+"/edit")) rig.Screen("textarea[mapa-editor]", "Ana's editor") drive(t, rig, chromedp.Evaluate[chromedp.Void]( `document.documentElement.setAttribute("data-mapa-idle", "300")`)) if _, err := store.Commit(ctx, Bo, page.ID, page.Revision, "One.\n\nTwo, as Bo has it."); err != nil { t.Fatal(err) } drive(t, rig, chromedp.SendKeys("textarea[mapa-editor]", "Ana: "), chromedp.Sleep(3*time.Second)) status := text(t, rig, "[mapa-status]") drive(t, rig, press(save)) rig.Screen("header[mapa-page-head]", "after Save") got := text(t, rig, written) if !strings.Contains(got, "Ana: One.") || !strings.Contains(got, "Two, as Bo has it.") { t.Fatalf("an edit was lost: %q", got) } if !strings.Contains(status, "merged") { t.Fatalf("the idle commit did not report a merge: %q", status) } }