//go:build browser
package slidestest
import (
"encoding/json"
"net/http"
"strconv"
"strings"
"testing"
"time"
"github.com/chromedp/cdproto/cdp"
"github.com/chromedp/cdproto/network"
"github.com/chromedp/cdproto/page"
"github.com/chromedp/chromedp"
)
// Astra's second review of #27: the interleavings the first round's fixes
// did not cover. Each was a probe of Astra's that failed at c1d2f4d.
// A resync never discards a change that was waiting for its font. The
// accent's save is refused (413), which sends the editor into a resync;
// meanwhile text with code in it is pasted, its font three seconds away.
// The paste runs once its font is in, on the document it was made in, and
// survives the rebuild: it is on the slide afterwards, in the code face,
// and on the server, once. And it never leaves the slide on the way: once
// its words are there, no frame and no DOM change is without them, in the
// desktop view or the both view, whose phone stage loads over the network
// in the middle of the rebuild (Claude Fable on #27: the server's HTML
// was installed, and painted, before the paste was put back).
func TestFontAResyncNeverDiscardsAWaitingPaste(t *testing.T) {
for _, view := range []string{"desktop", "both"} {
t.Run(view, func(t *testing.T) {
fr := newFontRig(t)
sqid := fr.deck(t, "resync pending paste", inkDeck)
fr.match.Store("LiberationMono-")
fr.slow.Store(int64(3 * time.Second))
fr.rig.Run(fr.navigate("/d/" + sqid + "/edit"))
fr.editable(t)
if view != "desktop" {
fr.eval(t, clickJS(`[slides-switcher] input[value="`+view+`"]`), nil)
fr.rig.Run(chromedp.Sleep(800 * time.Millisecond))
fr.editable(t)
}
fr.eval(t, `(() => { const f = window.fetch; let first = true;
window.fetch = async function (u, o) {
if (first && String(u).endsWith('/updates') && o && o.method === 'POST') { first = false; await new Promise((r) => setTimeout(r, 150)); return new Response('', { status: 413 }) }
return f.call(this, u, o) };
window.__log = []; const stage = document.querySelector('[slides-stage]');
const rec = () => { const has = stage.textContent.includes('REVIEW_RESYNC_PASTE'); const last = window.__log[window.__log.length - 1];
if (!last || last.has !== has) window.__log.push({ ms: Math.round(performance.now()), has }) };
new MutationObserver(rec).observe(stage, { subtree: true, childList: true, characterData: true });
const frame = () => { rec(); requestAnimationFrame(frame) }; requestAnimationFrame(frame);
return true })()`, nil)
fr.eval(t, changeJS("#rst-deck-accent", "#ff0000"), nil)
fr.eval(t, pasteJS(`
REVIEW_RESYNC_PASTE codeword
`), nil)
fr.rig.Run(chromedp.Sleep(6 * time.Second))
text := fr.stageText(t)
if strings.Count(text, "REVIEW_RESYNC_PASTE") != 1 {
t.Errorf("after the resync the paste is on the slide %d times: %q", strings.Count(text, "REVIEW_RESYNC_PASTE"), text)
}
if got := fr.faceOf(t, `[slides-stage] [data-block="text"] code`); !strings.HasPrefix(got, "liberation mono:web") {
t.Errorf("the pasted code is in %s", got)
}
var log []struct {
Ms int `json:"ms"`
Has bool `json:"has"`
}
fr.eval(t, `window.__log`, &log)
seen := 0
for _, e := range log {
if e.Has {
seen++
}
}
if seen != 1 {
t.Errorf("the pasted words appeared %d times on the stage, want once and to stay: %+v", seen, log)
}
view := apiJSON(t, fr.app, http.MethodGet, "/api/v1/decks/"+sqid, fr.token, "", http.StatusOK)
b, _ := json.Marshal(view)
if n := strings.Count(string(b), "REVIEW_RESYNC_PASTE"); n != 1 {
t.Errorf("the server holds the paste %d times, want once: %s", n, b)
}
})
}
}
// refuseFirstSaveJS answers the editor's first save 413 and marks the
// moment (window.refused); every later save is counted (window.later) and
// its bytes kept as a string (window.laterBodies: the words an update
// inserts are in it as they are).
// holdResync holds the rebuild's fetch of the whole log: for ms, or
// forever when ms is 0.
func refuseFirstSaveJS(holdResyncMs int) string {
hold := `await new Promise(() => {})`
if holdResyncMs > 0 {
hold = `await new Promise((r) => setTimeout(r, ` + strconv.Itoa(holdResyncMs) + `))`
}
return `(() => { const f = window.fetch; window.later = []; window.laterBodies = [];
window.fetch = async function (u, o) {
const post = String(u).endsWith('/updates') && o && o.method === 'POST';
if (post && !window.refused) { await new Promise((r) => setTimeout(r, 150)); window.refused = true; return new Response('', { status: 413 }) }
if (window.refused && String(u).includes('since=0')) { ` + hold + ` }
const r = await f.call(this, u, o);
if (post) { window.later.push(r.status); window.laterBodies.push(Array.from(o.body, (c) => String.fromCharCode(c)).join('')) }
return r };
return true })()`
}
// Changes written on top of text the server refused are kept without it
// (feat/replay-while-diverged). Two pastes after the refused words and a
// Backspace over them, none of which waited for a font: their own Yjs
// updates are anchored to the refused words and cannot be carried, so
// they are replayed from their ProseMirror transactions. The pastes land
// where the refused words were, once, on the page and on the server; the
// Backspace had nothing left to delete; the refused words are on neither.
// (On fix/carry-replay they were held back and lost; before it they were
// posted and sat pending in the server's log, Claude Fable on #27/#88.)
func TestChangesOnRefusedTextAreKeptWithoutIt(t *testing.T) {
fr := newFontRig(t)
sqid := fr.deck(t, "uncarriable", inkDeck)
fr.rig.Run(fr.navigate("/d/" + sqid + "/edit"))
fr.editable(t)
fr.eval(t, refuseFirstSaveJS(2500), nil)
fr.eval(t, pasteJS(`REFUSEDWORDS`), nil)
fr.until(t, `window.refused === true`)
fr.rig.Run(chromedp.Sleep(50 * time.Millisecond))
fr.eval(t, pasteJS(`ONTOPOFIT`), nil)
fr.rig.Run(chromedp.Sleep(50 * time.Millisecond))
fr.eval(t, pasteJS(`ANDAGAIN`), nil)
fr.rig.Run(chromedp.Sleep(50 * time.Millisecond))
// Select the refused words and press Backspace.
fr.eval(t, `(() => { const el = document.querySelector('[slides-stage] [data-block="text"]'); el.focus();
const w = document.createTreeWalker(el, NodeFilter.SHOW_TEXT); let n;
while ((n = w.nextNode())) { const i = n.data.indexOf('REFUSEDWORDS'); if (i >= 0) { const r = document.createRange(); r.setStart(n, i); r.setEnd(n, i + 12);
getSelection().removeAllRanges(); getSelection().addRange(r); return true } }
return false })()`, nil)
fr.rig.Run(chromedp.Sleep(50*time.Millisecond), chromedp.KeyEvent("\b"))
fr.rig.Run(chromedp.Sleep(4 * time.Second))
text := fr.stageText(t)
view := apiJSON(t, fr.app, http.MethodGet, "/api/v1/decks/"+sqid, fr.token, "", http.StatusOK)
b, _ := json.Marshal(view)
for _, c := range []struct {
words string
n int
}{{"REFUSEDWORDS", 0}, {"ONTOPOFIT", 1}, {"ANDAGAIN", 1}} {
if got := strings.Count(text, c.words); got != c.n {
t.Errorf("the page holds %s %d times, want %d: %q", c.words, got, c.n, text)
}
if got := strings.Count(string(b), c.words); got != c.n {
t.Errorf("the server holds %s %d times, want %d", c.words, got, c.n)
}
}
samePageAndServer(t, fr, sqid)
}
// Closing the tab while it is diverged sends what was written meanwhile
// (Claude Fable on #27: the beacon read only the old queue, and the words
// typed after the refusal were in neither).
func TestLeavingWhileDivergedSendsWhatWasWritten(t *testing.T) {
fr := newFontRig(t)
sqid := fr.deck(t, "beacon diverged", inkDeck)
fr.rig.Run(fr.navigate("/d/" + sqid + "/edit"))
fr.editable(t)
fr.eval(t, refuseFirstSaveJS(0), nil)
fr.eval(t, changeJS("#rst-deck-accent", "#ff0000"), nil)
fr.until(t, `window.refused === true`)
fr.rig.Run(chromedp.Sleep(50 * time.Millisecond))
fr.eval(t, pasteJS(`BEACONEDWORDS`), nil)
fr.rig.Run(chromedp.Sleep(100 * time.Millisecond))
fr.rig.Run(chromedp.Navigate("about:blank"))
deadline := time.Now().Add(5 * time.Second)
for {
view := apiJSON(t, fr.app, http.MethodGet, "/api/v1/decks/"+sqid, fr.token, "", http.StatusOK)
b, _ := json.Marshal(view)
if strings.Count(string(b), "BEACONEDWORDS") == 1 {
return
}
if time.Now().After(deadline) {
t.Fatalf("the words written while diverged never reached the server: %s", b)
}
time.Sleep(100 * time.Millisecond)
}
}
// A slide made in an empty deck goes up once its save is acknowledged,
// through a retry: the first save answers 500, its retry 204, and the
// stage shows the new slide.
func TestANewSlideGoesUpAfterARetriedSave(t *testing.T) {
fr := newFontRig(t)
sqid := fr.deck(t, "first save retry", `[{"op":"set_meta","theme":"paper","title":"Empty"}]`)
fr.rig.Run(fr.navigate("/d/" + sqid + "/edit"))
fr.until(t, `document.documentElement.dataset.slidesFonts === 'shown' && !!document.querySelector('[slides-menu]')`)
fr.rig.Run(chromedp.Sleep(300 * time.Millisecond))
fr.eval(t, `(() => { const f = fetch; let first = true; window.posts = [];
window.fetch = async (...args) => {
if (String(args[0]).endsWith('/updates') && args[1] && args[1].method === 'POST') {
if (first) { first = false; window.posts.push(500); return new Response('', { status: 500 }) }
const r = await f(...args); window.posts.push(r.status); return r }
return f(...args) };
return true })()`, nil)
fr.eval(t, clickJS(`[slides-menu] [data-command="new-slide"]`), nil)
fr.until(t, `!!document.querySelector('[slides-stage] [data-block="heading"][contenteditable="true"]')`)
var posts []int
fr.eval(t, `window.posts`, &posts)
if len(posts) < 2 || posts[0] != 500 {
t.Errorf("the saves were answered %v; the check meant a 500 then its retry", posts)
}
}
// The projector never goes back to an older slide because an old answer
// arrived late (Astra's finding 2 on #27). Each case holds an answer back,
// lets the session move on through the stream, then releases it: nothing
// changes — not the slide, not the counter, not the blackout.
//
// This is static/present.js's ordering, which a session begun before
// positions keeps (preDeploy). A session with a position moves its slide
// window from memory instead, and its link orders presses and answers
// (fixtures/talk-link.mjs, TestPresenterFastPressesNeverJumpBack).
func TestTheProjectorIgnoresAStaleAnswer(t *testing.T) {
three := strings.TrimSuffix(paperDeck, "]") + `,{"op":"add_slide","id":"slidethree03","layout":"flow","template":"title-body"},{"op":"add_block","slide":"slidethree03","id":"head00000003","type":"heading","region":"heading","props":{"level":1},"markdown":"Third"}]`
// holdJS holds the body of the next response whose URL matches.
holdJS := func(match string) string {
return `(() => { const f = window.fetch; window.fetch = async function (u, o) { const r = await f.call(this, u, o);
if (` + match + `) { const text = r.text.bind(r); r.text = async () => { const html = await text(); window.held = true; await new Promise((res) => (window.release = res)); return html } }
return r }; return true })()`
}
for _, c := range []struct {
name, page, hold, act string
after func(fr *fontRig, session, token string)
want string // the data-slide that must stay
blackout bool
}{
{name: "the presenter's Next answered after the stream moved on", page: "token",
hold: `String(u).endsWith('/command')`,
act: `document.querySelector('[slides-bar] form input[value="next"]').form.requestSubmit()`,
after: func(fr *fontRig, s, tk string) {
fr.until(t, `window.held && document.querySelector('[slides-surface]').dataset.slide === '2'`)
command(t, fr.app, s, "next", tk, "", nil)
}, want: "3"},
{name: "a watcher's Next answered after the stream moved on", page: "watcher",
hold: `String(u).includes('slide=2') && !String(u).includes('/updates')`,
act: `document.querySelector('[slides-bar] a[rel="next"]').click()`,
after: func(fr *fontRig, s, tk string) {
fr.until(t, `window.held`)
command(t, fr.app, s, "next", tk, "", nil)
command(t, fr.app, s, "next", tk, "", nil)
}, want: "3"},
{name: "a watcher's Back answered after the stream moved on", page: "watcher",
hold: `window.armed && String(u) === location.href`,
act: `document.querySelector('[slides-bar] a[rel="next"]').click()`,
after: func(fr *fontRig, s, tk string) {
fr.until(t, `document.querySelector('[slides-surface]').dataset.slide === '2' && location.search.includes('slide=2')`)
fr.eval(t, `window.armed = true; history.back(); true`, nil)
fr.until(t, `window.held`)
command(t, fr.app, s, "next", tk, "", nil)
command(t, fr.app, s, "next", tk, "", nil)
}, want: "3"},
{name: "an old answer does not lift a blackout", page: "token",
hold: `String(u).endsWith('/command')`,
act: `document.querySelector('[slides-bar] form input[value="next"]').form.requestSubmit()`,
after: func(fr *fontRig, s, tk string) {
fr.until(t, `window.held && document.querySelector('[slides-surface]').dataset.slide === '2'`)
command(t, fr.app, s, "blackout", tk, "", nil)
}, want: "2", blackout: true},
} {
t.Run(c.name, func(t *testing.T) {
fr := newFontRig(t)
sqid := fr.deck(t, "ordering", three)
session, token := startPresenting(t, fr.app, "/d/"+sqid, fr.cookies)
preDeploy(t, fr.app, session)
path := "/p/" + session
if c.page == "token" {
path += "?t=" + token
} else {
// A watcher is nobody signed in: the presenter's own
// cookie drives even a talk begun before positions.
fr.rig.Run(cdpStep(network.ClearBrowserCookies, cdp.Empty{}))
}
fr.rig.Run(fr.navigate(path))
fr.shown(t)
fr.rig.Run(chromedp.Sleep(300 * time.Millisecond))
fr.eval(t, holdJS(c.hold), nil)
fr.eval(t, `(() => { `+c.act+`; return true })()`, nil)
c.after(fr, session, token)
want := `document.querySelector('[slides-surface]').dataset.slide === '` + c.want + `'`
if c.blackout {
want += ` && document.querySelector('[slides-surface]').dataset.blackout === 'true'`
}
fr.until(t, want)
fr.eval(t, `window.release(); true`, nil)
fr.rig.Run(chromedp.Sleep(time.Second))
var state struct {
Slide, Blackout, Counter, Text string
}
fr.eval(t, `(() => { const s = document.querySelector('[slides-surface]'); return { Slide: s.dataset.slide, Blackout: s.dataset.blackout,
Counter: (document.querySelector('[slides-counter]') || {}).textContent || '', Text: document.querySelector('[slides-stage]').textContent } })()`, &state)
if state.Slide != c.want {
t.Errorf("the old answer moved the projector to slide %s, want it to stay on %s (%+v)", state.Slide, c.want, state)
}
if c.blackout && state.Blackout != "true" {
t.Error("the old answer lifted the blackout")
}
if !strings.Contains(state.Counter, c.want+" ") && !strings.Contains(state.Counter, " "+c.want+" ") {
t.Errorf("the counter says %q on slide %s", state.Counter, c.want)
}
})
}
}
// A presenter's command whose in-place answer fails is never sent twice
// (Claude Fable on #27: the fallback was form.submit(), a second POST of
// "next"). The server applies the Next and the answer is lost; the page
// falls back to loading itself, and the session is on slide 2, not 3.
//
// static/present.js's fallback, on a session begun before positions
// (preDeploy). A session with a position keeps moving with no answer at
// all and tells the server where it went when it can
// (TestADroppedNetworkKeepsThePressingWindowMoving).
func TestAFailedCommandAnswerIsNotSentAgain(t *testing.T) {
three := strings.TrimSuffix(paperDeck, "]") + `,{"op":"add_slide","id":"slidethree03","layout":"flow","template":"title-body"},{"op":"add_block","slide":"slidethree03","id":"head00000003","type":"heading","region":"heading","props":{"level":1},"markdown":"Third"}]`
fr := newFontRig(t)
sqid := fr.deck(t, "fallback", three)
session, token := startPresenting(t, fr.app, "/d/"+sqid, fr.cookies)
preDeploy(t, fr.app, session)
// The stream is kept quiet, so the failed answer is still the newest
// thing this page has heard: with it, the stream's own event would
// move the page on and the fallback would never run.
fr.rig.Run(cdpStep(page.AddScriptToEvaluateOnNewDocument, page.AddScriptToEvaluateOnNewDocumentParams{
Source: `try { if (sessionStorage.getItem('quiet-stream')) window.EventSource = class { addEventListener () {} close () {} } } catch (e) {}`,
}))
fr.goTo(t, "/p/"+session+"?t="+token)
fr.eval(t, `sessionStorage.setItem('quiet-stream', '1'); true`, nil)
fr.goTo(t, "/p/"+session+"?t="+token)
fr.rig.Run(chromedp.Sleep(300 * time.Millisecond))
fr.eval(t, `(() => { const f = window.fetch; window.fetch = async function (u, o) { const r = await f.call(this, u, o);
if (String(u).endsWith('/command')) return new Response('', { status: 502 });
return r }; window.__before = true; return true })()`, nil)
fr.eval(t, `(() => { document.querySelector('[slides-bar] form input[value="next"]').form.requestSubmit(); return true })()`, nil)
fr.until(t, `!window.__before && document.documentElement.dataset.slidesFonts === 'shown' && !!document.querySelector('[slides-surface]')`)
fr.rig.Run(chromedp.Sleep(time.Second))
var slide string
fr.eval(t, `document.querySelector('[slides-surface]').dataset.slide`, &slide)
if slide != "2" {
t.Errorf("after one Next whose answer failed the session is on slide %s, want 2: the command was sent again", slide)
}
}
// After an in-place change of slide, focus is where a keyboard user
// expects it and the change is said (Astra's finding 4 on #27). Pressed
// with the keyboard: Next keeps focus on Next; Previous onto the first
// slide and Next onto the last, where that link is gone, put focus on the
// slide; the projector's Next button keeps it, and a watcher's Next onto
// the last slide puts it on the slide. Each change is said through a
// polite live region that was in the page before it: "Slide 2 of 3:
// Second".
func TestInPlaceSlideChangesKeepFocusAndAreAnnounced(t *testing.T) {
three := strings.TrimSuffix(paperDeck, "]") + `,{"op":"add_slide","id":"slidethree03","layout":"flow","template":"title-body"},{"op":"add_block","slide":"slidethree03","id":"head00000003","type":"heading","region":"heading","props":{"level":1},"markdown":"Third"}]`
fr := newFontRig(t)
sqid := fr.deck(t, "a11y", three)
type spot struct {
Active, Said, Live, Polite string
}
look := func() spot {
var s spot
fr.eval(t, `(() => { const a = document.activeElement; const r = document.querySelector('[slides-announce]');
return { Active: a === document.body ? 'BODY' : a.matches('[slides-slide]') ? 'SLIDE' : (a.getAttribute('rel') || a.getAttribute('slides-op') || a.tagName),
Said: r ? r.textContent : '', Live: r ? r.getAttribute('role') : '', Polite: r ? r.getAttribute('aria-live') : '' } })()`, &s)
return s
}
check := func(where, active, said string) {
t.Helper()
got := look()
if got.Active != active {
t.Errorf("%s: focus is on %s, want %s", where, got.Active, active)
}
if got.Said != said {
t.Errorf("%s: the live region says %q, want %q", where, got.Said, said)
}
if got.Live != "status" || got.Polite != "polite" {
t.Errorf("%s: the announcement is not a polite status region (%+v)", where, got)
}
}
for _, mode := range []string{"", "&present=1"} {
fr.goTo(t, "/d/"+sqid+"?slide=2"+mode)
fr.rig.Run(chromedp.Sleep(300 * time.Millisecond))
fr.eval(t, `document.querySelector('[slides-pager] a[rel="prev"]').focus(); true`, nil)
fr.rig.Run(chromedp.KeyEvent("\r"))
fr.until(t, `location.search.includes('slide=1') && document.querySelector('[slides-slide]').textContent.includes('A heading in serif')`)
check("viewer"+mode+", Previous to the first slide", "SLIDE", "Slide 1 of 3: A heading in serif")
fr.eval(t, `document.querySelector('[slides-pager] a[rel="next"]').focus(); true`, nil)
fr.rig.Run(chromedp.KeyEvent("\r"))
fr.until(t, `location.search.includes('slide=2') && document.querySelector('[slides-slide]').textContent.includes('Second')`)
check("viewer"+mode+", Next to slide 2", "next", "Slide 2 of 3: Second")
fr.rig.Run(chromedp.KeyEvent("\r"))
fr.until(t, `location.search.includes('slide=3') && document.querySelector('[slides-slide]').textContent.includes('Third')`)
check("viewer"+mode+", Next to the last slide", "SLIDE", "Slide 3 of 3: Third")
}
session, token := startPresenting(t, fr.app, "/d/"+sqid, fr.cookies)
fr.goTo(t, "/p/"+session+"?t="+token)
fr.rig.Run(chromedp.Sleep(300 * time.Millisecond))
fr.eval(t, `document.querySelector('[slides-op="next"]').focus(); true`, nil)
fr.rig.Run(chromedp.KeyEvent("\r"))
fr.until(t, `document.querySelector('[slides-surface]').dataset.slide === '2' && document.querySelector('[slides-announce]').textContent !== ''`)
fr.rig.Run(chromedp.Sleep(500 * time.Millisecond))
check("projector, the Next button", "next", "Slide 2 of 3: Second")
// A watcher is somebody who is not signed in: on a session with a
// position the signed-in presenter gets the controls here instead.
fr.rig.Run(cdpStep(network.ClearBrowserCookies, cdp.Empty{}))
fr.goTo(t, "/p/"+session+"?slide=2")
fr.rig.Run(chromedp.Sleep(300 * time.Millisecond))
fr.eval(t, `document.querySelector('[slides-bar] a[rel="next"]').focus(); true`, nil)
fr.rig.Run(chromedp.KeyEvent("\r"))
fr.until(t, `document.querySelector('[slides-surface]').dataset.slide === '3' && document.querySelector('[slides-announce]').textContent !== ''`)
check("projector, a watcher's Next to the last slide", "SLIDE", "Slide 3 of 3: Third")
}