Page: the scrollback is the server's turn log, loaded on open and paged on scroll-up; Retry names the entry it retries; the in-visit-only note is gone

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-12-02 21:59:44 +01:00
commit 9684001600
4 changed files with 195 additions and 57 deletions

View file

@ -65,3 +65,5 @@ textarea { resize: vertical; line-height: 1.5; }
@media (min-width: 700px) { :root { --fs: 1.2rem; } main { padding-top: 1.25rem; } }
.blk { display: block; } .bad { color: var(--bad); } .gap { margin-top: .6rem; margin-bottom: .2rem; }
label.choice { text-transform: none; letter-spacing: 0; font: inherit; color: var(--text); margin: .4rem 0; }
.older { text-align: center; }
.older .btn { margin: .4rem 0; }

View file

@ -1,8 +1,8 @@
// Presentation only. The daemon owns every command and every fact; this page
// shows what the API returns and sends what the player types. The only state it
// keeps on the device is the unsent draft, the text size and the theme. The
// turns on screen are a display cache of what the stream delivered in this
// visit; a reload shows the open turn again from the server.
// scrollback is the server's turn log, loaded on open and paged on scroll-up,
// so a reload or another device shows the same story.
"use strict";
const $view = document.getElementById("view");
@ -57,7 +57,7 @@ document.getElementById("theme").onclick = () => {
};
// ---- state ---------------------------------------------------------------
const S = { me: null, timeline: null, log: [], nextYou: null, lastText: "", keyed: null, stream: null, poll: null, signIn: null };
const S = { me: null, timeline: null, history: [], older: null, live: null, echo: null, keyed: null, tailTried: null, stream: null, poll: null, signIn: null };
function stopLive() {
if (S.stream) { S.stream.close(); S.stream = null; }
@ -138,7 +138,7 @@ document.getElementById("signout").onclick = async () => {
stopLive();
const { status, body } = await post("auth/logout", {});
if (status !== 200) return show(errorLine(body.error || "Sign-out was not confirmed."), retryButton(boot));
S.log = []; S.timeline = null;
S.history = []; S.timeline = null;
boot();
};
document.getElementById("home").onclick = () => { if (S.me && S.me.signedIn) listView(); };
@ -206,9 +206,12 @@ async function beginView() {
}
// ---- play ----------------------------------------------------------------
// The scrollback is the server's turn log: S.history holds the entries fetched
// so far (oldest first), S.live the open turn's view from the stream. Nothing
// here is kept on the device but the unsent draft.
async function openTimeline(id) {
stopLive();
S.timeline = id; S.log = []; S.nextYou = null; S.lastText = ""; S.keyed = null;
S.timeline = id; S.history = []; S.older = null; S.live = null; S.echo = null; S.keyed = null; S.tailTried = null;
const { status, body } = await api("timelines");
if (status !== 200) return show(errorLine(body.error || "Could not open that world."), retryButton(() => openTimeline(id)));
const row = (body.timelines || []).find((r) => r.timeline === id);
@ -227,22 +230,56 @@ async function openTimeline(id) {
playView(row);
}
let $log, $status, $text, $send, $retryRow, $fresh;
function playView(row) {
let $log, $status, $text, $send, $retryRow, $older;
async function playView(row) {
const id = S.timeline;
$older = el("div", { class: "older small" });
$log = el("div", { id: "log" });
$status = el("p", { class: "status", role: "status" });
$retryRow = el("div", { class: "row" });
show(el("h1", {}, row.title), el("p", { class: "small" }, "Earlier turns stay on screen while this page is open; after a reload the open turn is shown again."), $log, $status, $retryRow);
show(el("h1", {}, row.title), $older, $log, $status, $retryRow);
$text = el("textarea", { id: "say", rows: "2", "aria-label": "What do you do?", placeholder: "What do you do? (Empty Send carries on an unfinished turn.)" });
$text.value = LS.get("draft:" + S.timeline) || "";
$text.addEventListener("input", () => LS.set("draft:" + S.timeline, $text.value));
$text.value = LS.get("draft:" + id) || "";
$text.addEventListener("input", () => LS.set("draft:" + id, $text.value));
$send = el("button", { class: "btn", type: "button", onclick: () => send($text.value) }, "Send");
document.body.append(el("div", { class: "compose" }, el("div", { class: "in" }, $text, el("div", { class: "row" }, $send,
el("button", { class: "btn alt", type: "button", title: "Carry on an unfinished turn", onclick: () => send("") }, "Continue"))
)));
const ok = await loadHistory(null);
if (S.timeline !== id) return;
if (ok) window.scrollTo(0, document.documentElement.scrollHeight);
connect();
}
// Reads one page of the log. `before` null reads the newest page and merges it
// into what is held; a number reads the page older than that entry.
async function loadHistory(before) {
const id = S.timeline;
const { status, body } = await api("history/" + encodeURIComponent(id) + (before ? "?before=" + before : ""));
if (S.timeline !== id) return false;
if (status !== 200) {
$older.replaceChildren(errorLine(body.error || "The earlier turns could not be loaded."), retryButton(() => loadHistory(before)));
return false;
}
const first = !S.history.length;
const have = new Map(S.history.map((e) => [e.seq, e]));
for (const entry of body.entries || []) have.set(entry.seq, entry);
S.history = [...have.values()].sort((a, b) => a.seq - b.seq);
// Only a read at the old edge moves the edge; a refresh of the newest page leaves it.
if (before || first) S.older = body.older;
render();
return true;
}
let loadingOlder = false;
window.addEventListener("scroll", async () => {
if (!S.timeline || !$log || !S.older || loadingOlder || window.scrollY > 160) return;
loadingOlder = true;
const height = document.documentElement.scrollHeight;
if (await loadHistory(S.older)) window.scrollTo(0, window.scrollY + document.documentElement.scrollHeight - height);
loadingOlder = false;
}, { passive: true });
function connect() {
const id = S.timeline;
if (S.stream) S.stream.close();
@ -258,75 +295,90 @@ document.addEventListener("visibilitychange", async () => {
if (S.stream && S.stream.readyState === 2) connect();
});
function onTurn(view) {
// Whether the log already holds what the open turn shows.
function logged(turn) {
return S.history.some((e) => e.turn_id === turn.id &&
(turn.state === "awaiting_player" ? e.status === "asked" && turn.question && e.question === turn.question.text : e.status !== "asked"));
}
async function onTurn(view) {
const turn = view.turn;
if (!turn) {
$log.replaceChildren(el("p", { class: "note" }, "The world is ready. Say what you do."));
$status.className = "status"; $status.textContent = ""; $retryRow.replaceChildren();
return;
S.live = turn;
if (S.echo && (!turn || turn.revision !== S.echo.revision)) S.echo = null;
render();
if (turn && turn.state !== "running" && !logged(turn)) {
const mark = turn.id + ":" + turn.revision;
if (S.tailTried !== mark) { S.tailTried = mark; await loadHistory(null); }
}
const nearBottom = !S.log.length || window.innerHeight + window.scrollY >= document.documentElement.scrollHeight - 240;
let entry = S.log.find((e) => e.id === turn.id);
if (!entry) { entry = { id: turn.id, you: S.nextYou }; S.nextYou = null; S.log.push(entry); }
Object.assign(entry, { state: turn.state, narration: turn.narration, question: turn.question, refusal: turn.refusal, fault: turn.fault });
renderLog();
const last = S.log[S.log.length - 1];
}
function render() {
const nearBottom = window.innerHeight + window.scrollY >= document.documentElement.scrollHeight - 240;
const turn = S.live;
$older.replaceChildren(S.older ? el("button", { class: "btn alt", type: "button", onclick: () => loadHistory(S.older) }, "Load earlier turns") : "");
const nodes = S.history.map(entryNode);
const running = turn && turn.state === "running";
if (running || S.echo) {
const text = running ? turn.text : S.echo.text;
nodes.push(el("section", { class: "turn" }, text ? el("p", { class: "you" }, text) : ""));
}
if (!nodes.length) nodes.push(el("p", { class: "note" }, "The world is ready. Say what you do."));
$log.replaceChildren(...nodes);
$retryRow.replaceChildren();
$status.className = "status";
if (turn.state === "running") {
$status.textContent = "";
if (running) {
if (turn.resolving) { $status.className = "status pulse"; $status.textContent = "The storyteller is resolving your turn"; }
else $status.textContent = turn.continue_hint || "This turn is unfinished.";
} else if (turn.state === "awaiting_player") {
} else if (S.echo) {
$status.className = "status pulse"; $status.textContent = "Sent";
} else if (turn && turn.state === "awaiting_player") {
$status.textContent = "The storyteller is waiting for your answer.";
} else { $status.textContent = ""; }
if (turn.fault) {
$retryRow.append(
el("button", { class: "btn", type: "button", onclick: () => send(S.lastText, null, true), disabled: !S.lastText }, "Retry"),
el("button", { class: "btn alt", type: "button", onclick: editAgain, disabled: !S.lastText }, "Edit and resend"));
if (!S.lastText) $retryRow.append(el("p", { class: "small" }, "This page does not hold what you sent before the reload. Write your turn again."));
} else if (turn.refusal) {
$retryRow.append(el("button", { class: "btn alt", type: "button", onclick: editAgain, disabled: !S.lastText }, "Edit and resend"));
}
const last = S.history[S.history.length - 1];
if (last && !running && !S.echo && turn && logged(turn)) {
if (last.status === "faulted" && !last.superseded_by) {
$retryRow.append(
el("button", { class: "btn", type: "button", onclick: () => send(last.text, last.seq) }, "Retry"),
el("button", { class: "btn alt", type: "button", onclick: () => editAgain(last.text) }, "Edit and resend"));
} else if (last.status === "refused") {
$retryRow.append(el("button", { class: "btn alt", type: "button", onclick: () => editAgain(last.text) }, "Edit and resend"));
}
}
if (nearBottom) window.scrollTo(0, document.documentElement.scrollHeight);
}
function renderLog() {
$log.replaceChildren(...S.log.map((entry) => {
const parts = [];
if (entry.you) parts.push(el("p", { class: "you" }, entry.you));
if (entry.narration) parts.push(el("p", { class: "story" }, entry.narration));
if (entry.refusal) parts.push(el("p", { class: "line", role: "alert" }, entry.refusal));
if (entry.fault) parts.push(el("p", { class: "line", role: "alert" }, entry.fault));
if (entry.question) parts.push(el("div", { class: "ask" }, el("strong", {}, "The storyteller asks"), el("p", { class: "story" }, entry.question.text)));
if (entry.answer) parts.push(el("p", { class: "you" }, entry.answer));
const node = el("section", { class: "turn" }, parts);
entry.node = node;
return node;
}));
function entryNode(entry) {
const parts = [];
if (entry.text) parts.push(el("p", { class: "you" }, entry.text));
if (entry.narration) parts.push(el("p", { class: "story" }, entry.narration));
if (entry.refusal) parts.push(el("p", { class: "line", role: "alert" }, entry.refusal));
if (entry.fault) parts.push(el("p", { class: "line", role: "alert" }, entry.fault));
if (entry.superseded_by) parts.push(el("p", { class: "small" }, "Sent again below."));
if (entry.question) parts.push(el("div", { class: "ask" }, el("strong", {}, "The storyteller asks"), el("p", { class: "story" }, entry.question)));
return el("section", { class: "turn" }, parts);
}
function editAgain() { $text.value = S.lastText; LS.set("draft:" + S.timeline, $text.value); $text.focus(); }
function editAgain(text) { $text.value = text; LS.set("draft:" + S.timeline, text); $text.focus(); }
async function send(text, _unused, isRetry) {
async function send(text, retryOf) {
if (!S.timeline) return;
const last = S.log[S.log.length - 1];
const answers = last && last.state === "awaiting_player" && last.question ? last.question.token : null;
const turn = S.live;
const answers = turn && turn.state === "awaiting_player" && turn.question ? turn.question.token : null;
// The same text resent after a lost reply reuses its key, so it cannot play twice.
if (!S.keyed || S.keyed.text !== text || isRetry) S.keyed = { text, key: uuid() };
if (!S.keyed || S.keyed.text !== text || retryOf) S.keyed = { text, key: uuid() };
$send.disabled = true;
// The echo is placed before the request: the stream can deliver the new turn before the reply returns.
if (answers && text) { last.answer = text; renderLog(); } else if (text) S.nextYou = text;
const { status, body } = await post("play", { timeline: S.timeline, key: S.keyed.key, text, answers });
if (text) { S.echo = { text, revision: turn ? turn.revision : null }; render(); }
const { status, body } = await post("play", { timeline: S.timeline, key: S.keyed.key, text, answers, retry_of: retryOf || null });
$send.disabled = false;
if (status === 202 || status === 200) {
S.lastText = text || S.lastText; S.keyed = null;
S.keyed = null;
$text.value = ""; LS.set("draft:" + S.timeline, "");
$status.className = "status pulse"; $status.textContent = "Sent";
if (!text) { $status.className = "status pulse"; $status.textContent = "Sent"; }
return;
}
S.nextYou = null; if (last && answers) last.answer = null;
if (answers) renderLog();
$status.className = "status";
S.echo = null; render();
$retryRow.replaceChildren(errorLine(status === 0 ? "The server could not be reached. Your text is kept; Send resends it safely." : (body.error || "The turn was refused (" + status + ").")));
}

84
probes/page/history.mjs Normal file
View file

@ -0,0 +1,84 @@
// Drives the history probe: api::tests::serve_the_page_for_a_browser_probe with
// GHOSTLIGHT_PROBE_MODE=long (forty scripted closed turns). Plays turns in one
// browser profile, reloads, scrolls up, then signs the same account in from a
// second, separate profile and compares what both show. 360 px phone width.
// usage: node history.mjs <base-url> <out-dir> [chrome-path]
import { spawn } from "node:child_process";
import { writeFileSync, mkdirSync, mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
const [base, out, chrome = "C:/Program Files/Google/Chrome/Application/chrome.exe"] = process.argv.slice(2);
mkdirSync(out, { recursive: true });
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
async function launch(port) {
const proc = spawn(chrome, ["--headless=new", `--remote-debugging-port=${port}`, `--user-data-dir=${mkdtempSync(join(tmpdir(), "hist-"))}`, "--no-first-run", "about:blank"], { stdio: "ignore" });
let targets;
for (let i = 0; i < 50; i++) { try { targets = await (await fetch(`http://127.0.0.1:${port}/json`)).json(); break; } catch { await sleep(200); } }
const ws = new WebSocket(targets.find((t) => t.type === "page").webSocketDebuggerUrl);
await new Promise((r) => (ws.onopen = r));
let id = 0; const pending = new Map();
ws.onmessage = (m) => { const d = JSON.parse(m.data); if (d.id && pending.has(d.id)) { pending.get(d.id)(d); pending.delete(d.id); } };
const cdp = (method, params = {}) => new Promise((r) => { const n = ++id; pending.set(n, r); ws.send(JSON.stringify({ id: n, method, params })); });
const js = async (expression) => (await cdp("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true })).result.result?.value;
await cdp("Page.enable");
await cdp("Emulation.setDeviceMetricsOverride", { width: 360, height: 740, deviceScaleFactor: 2, mobile: true });
const b = {
js,
go: async (url) => { await cdp("Page.navigate", { url }); await sleep(900); },
reload: async () => { await cdp("Page.reload"); await sleep(900); },
waitFor: async (expr, ms = 20000) => { for (let t = 0; t < ms; t += 200) { if (await js(expr)) return true; await sleep(200); } throw new Error("timed out: " + expr); },
fill: (sel, v) => js(`(()=>{const e=document.querySelector(${JSON.stringify(sel)});e.value=${JSON.stringify(v)};e.dispatchEvent(new Event('input',{bubbles:true}))})()`),
clickText: (text) => js(`[...document.querySelectorAll('button')].find(x=>x.textContent.trim()===${JSON.stringify(text)}).click()`),
shot: async (name) => {
await sleep(300);
const overflow = await js("document.documentElement.scrollWidth > document.documentElement.clientWidth");
const { result } = await cdp("Page.captureScreenshot", { format: "png" });
writeFileSync(join(out, `${name}.png`), Buffer.from(result.data, "base64"));
console.log(name, "horizontal-overflow:", overflow);
},
turns: () => js("document.querySelectorAll('#log .turn').length"),
logText: () => js("document.getElementById('log').innerText"),
toBottom: () => js("window.scrollTo(0, document.documentElement.scrollHeight)"),
close: () => { ws.close(); proc.kill(); },
};
return b;
}
const A = await launch(9334);
await A.go(base + "/probe/login"); await A.waitFor("document.body.innerText.includes('Your worlds')");
await A.clickText("Begin a new world"); await A.waitFor("!!document.querySelector('#title')");
await A.fill("#title", "Ashfall"); await A.fill("#name", "Deru"); await A.clickText("Begin");
await A.waitFor("!!document.querySelector('#say')");
const N = 34;
for (let n = 0; n < N; n++) {
await A.fill("#say", `I walk on, step ${n}.`); await A.clickText("Send");
await A.waitFor(`document.getElementById('log').innerText.includes('Narration ${n}:')`);
await sleep(150);
}
await A.toBottom(); await A.shot("13-history-live-360");
await A.reload(); await A.waitFor("document.querySelectorAll('#log .turn').length > 0"); await sleep(400);
await A.toBottom();
const afterReload = await A.turns();
const newestA = await A.logText();
console.log("after reload: turns on screen", afterReload, "(first page)");
await A.shot("14-history-after-reload-360");
await A.js("window.scrollTo(0, 0)"); await A.waitFor(`document.querySelectorAll('#log .turn').length === ${N}`);
await sleep(300);
console.log("after scroll-up: turns on screen", await A.turns());
await A.shot("15-history-older-loaded-360");
const fullA = await A.logText();
const B = await launch(9335);
await B.go(base + "/probe/login"); await B.waitFor("document.querySelectorAll('#log .turn').length > 0"); await sleep(400);
await B.toBottom();
const newestB = await B.logText();
console.log("second context newest page identical to first context's after reload:", newestA === newestB);
await B.shot("16-second-context-360");
await B.js("window.scrollTo(0, 0)"); await B.waitFor(`document.querySelectorAll('#log .turn').length === ${N}`);
await sleep(300);
await B.shot("17-second-context-older-loaded-360");
const fullB = await B.logText();
console.log("full scrollback identical across contexts:", fullA === fullB, "turns:", N);
A.close(); B.close();

View file

@ -55,7 +55,7 @@ await waitFor("document.body.innerText.includes('lost the thread')"); await slee
await clickText("Retry"); await waitFor("document.body.innerText.includes('lost the thread')"); await sleep(800); await shot("09-fault-after-retry");
// A refusal needs a dispatch the world refuses; the scripted model cannot make one cheaply, so the
// turn view the daemon would send is handed to the page's own renderer.
await js(`onTurn({timeline:S.timeline,turn:{id:'probe-refusal',state:'closed',narration:null,question:null,refusal:'The world refuses that: the toll woman is not within your reach.',fault:null,resolving:false}})`);
await js(`S.history.push({seq:999,turn_id:'probe-refusal',submission:1,text:'I reach for the toll woman.',narration:null,question:null,refusal:'The world refuses that: the toll woman is not within your reach.',fault:null,status:'refused',superseded_by:null}); render()`);
await sleep(300); await shot("10-refusal-line");
// Seeding and failed rows come from the daemon's timeline status; stub the list to see them rendered.
await js(`window.fetch=(u,o)=>String(u).endsWith('api/timelines')?Promise.resolve(new Response(JSON.stringify({timelines:[{timeline:'t1',status:'seeding',title:'Zyphos, a long first evening',current:true,createdAt:new Date().toISOString()},{timeline:'t2',status:'failed',reason:'the storyteller was unavailable',title:'Delvehold',createdAt:new Date().toISOString()},{timeline:'t3',status:'ready',parent:'t0',title:'Ashfall',createdAt:new Date().toISOString()}]}),{status:200})):Promise.reject(new Error('stub'));`);