diff --git a/frontend/app/src/main.ts b/frontend/app/src/main.ts index f21bccd..5c91649 100644 --- a/frontend/app/src/main.ts +++ b/frontend/app/src/main.ts @@ -16,6 +16,7 @@ import { Poem, RATING_ANCHORS, suggestedDuration, + type LineState, type PoemLine, type RatingValue, } from "./poem"; @@ -29,6 +30,7 @@ import type { RegisterView } from "./notation"; import type { CanonicalMotion } from "./types"; import { openAutosave } from "./autosave"; import { askFor, continuityLabel, readPanel } from "./triptych"; +import { wholePoemAction, wholePoemLabel, wholePoemTitle } from "./whole-poem"; import { SessionError, fromSession, restore, sessionFilename, sessionUrl, toSession } from "./session"; // Where the FastAPI service listens. Keep in sync with service/ CORS + --port. @@ -1044,10 +1046,13 @@ function setBarLabels(): void { generateEl.title = comparing ? "Ask all three models (D)" : "Generate the selected line alone (D)"; - bakeEl.textContent = comparing ? "Whole poem" : "Bake"; + // Only one model can answer a whole poem as one motion, so the bench button names the + // action it is actually about to take rather than the one the key is called after. + const action = wholePoemAction(capabilities.get(modelEl.value)); + bakeEl.textContent = comparing ? "Whole poem" : wholePoemLabel(action); bakeEl.title = comparing ? "Ask all three models the whole poem (B)" - : "Generate the whole poem continuously (B)"; + : wholePoemTitle(action); } function triptychPill(): string { @@ -1533,6 +1538,23 @@ function generationFailed(err: unknown, keeping: string): void { generationStatusEl.className = "generation-status error"; } +/** + * Hand the buttons back, and say how it went. + * + * `setGenerating` owns the status line and clears it, so the outcome has to be written + * *after* the buttons come back rather than before — otherwise re-enabling them wipes what + * just happened, and the elapsed time is never seen. That ordering is easy to get wrong + * twice, so it lives in one function instead of in three that have to agree. + */ +function generationSettled(failure: unknown, started: number, keeping: string): void { + setGenerating(false); + if (failure) { + generationFailed(failure, keeping); + return; + } + generationStatusEl.textContent = `${((performance.now() - started) / 1000).toFixed(1)} s`; +} + async function post(body: unknown): Promise { // Every route to the service comes through here — drafting, baking, the triptych. A // published build refuses before the fetch rather than after it: reaching localhost from a @@ -1566,9 +1588,13 @@ async function draftLine(id: number | null = poem.selectedId): Promise { const line = id === null ? undefined : poem.get(id); if (!line || !line.text.trim()) return; const started = performance.now(); + // What to put the row back to if the request never arrives. `markGenerating` overwrites + // it, and nothing else can work it out afterwards. + const was: LineState = line.state; poem.markGenerating(line.id); renderPoem(); setGenerating(true, "drafting…"); + let failure: unknown = null; try { const motion = await post({ model: modelEl.value, @@ -1580,25 +1606,88 @@ async function draftLine(id: number | null = poem.selectedId): Promise { }); poem.recordDraft(line.id, motion); showCurrent(); - generationStatusEl.textContent = `${((performance.now() - started) / 1000).toFixed(1)} s`; } catch (err) { - poem.setText(line.id, line.text); // knocks it out of "generating" - generationFailed(err, "The line is unchanged."); + failure = err; + poem.cancelGenerating(line.id, was); + } finally { + renderPoem(); + generationSettled(failure, started, "The line is unchanged."); + } +} + +/** + * Generate every line on a model that cannot stitch a poem. + * + * Each line is generated alone — the same request `D` sends — and lands as that line's own + * draft. **No bake is recorded**, deliberately: `poem.baked` stays null, `bakeIsCurrent` + * keeps reporting false, and the banner keeps saying there is no continuous reading. These + * lines were never carried into one another, and writing them into the bake would put that + * claim into every session file the poem is exported to, where it would be read by people + * who were not here to watch the body jump between them. + * + * Sequential, for two reasons: the service gates a local worker to one generation at a time + * anyway, so firing them together buys nothing; and a failure part way through then leaves + * every line drafted before it untouched rather than abandoning a half-made batch. + */ +async function draftAllLines(): Promise { + const lines = poem.written; + if (!lines.length) return; + const started = performance.now(); + let done = 0; + let failure: unknown = null; + try { + for (const line of lines) { + setGenerating(true, `drafting line ${done + 1} of ${lines.length}…`); + const motion = await post({ + model: modelEl.value, + prompt: line.text.trim(), + // The ghost-cloud is a per-line instrument, and four readings of every line of a + // poem is minutes of generation. Drafting the whole poem never asks for one. + variants: 1, + duration_seconds: poem.durationOf(line), + denoising_steps: chosenSteps(), + }); + poem.recordDraft(line.id, motion); + done += 1; + // The rows are cheap to redraw and show each line turning into a draft as it lands. + // The stage is not: `showCurrent` lays every drafted motion end to end, so doing it + // per line would be quadratic in the length of the poem — and a rating corpus can be + // hundreds of lines. It is laid out once, after the last line arrives. + renderPoem(); + } + } catch (err) { + failure = err; } finally { + showCurrent(); renderPoem(); - setGenerating(false); + generationSettled( + failure, + started, + done + ? `${done} of ${lines.length} lines were drafted, and are kept.` + : "The poem is unchanged.", + ); } } /** * Bake the whole poem: every line in one pass, each conditioned on the body the line * before it left behind. This is the real reading. + * + * Only a model that says it can carry one line into the next is asked for this. For the + * others `B` still means "the whole poem", but the whole poem is a batch of drafts — see + * `draftAllLines`, and `whole-poem.ts` for why the two must not share a name. */ async function bake(): Promise { + if (wholePoemAction(capabilities.get(modelEl.value)) === "draft-all") { + await draftAllLines(); + return; + } const lines = poem.toLines(); if (!lines.length) return; const started = performance.now(); setGenerating(true, `baking ${lines.length} lines…`); + let failure: unknown = null; try { const motion = await post({ model: modelEl.value, @@ -1609,12 +1698,11 @@ async function bake(): Promise { loopingLineId = null; renderer.setLoop("whole"); showCurrent(); - generationStatusEl.textContent = `${((performance.now() - started) / 1000).toFixed(1)} s`; } catch (err) { - generationFailed(err, "The previous reading is still on the stage."); + failure = err; } finally { renderPoem(); - setGenerating(false); + generationSettled(failure, started, "The previous reading is still on the stage."); } } @@ -1698,6 +1786,9 @@ function bakeHere(): void { generateEl.addEventListener("click", draftHere); bakeEl.addEventListener("click", bakeHere); +// Which whole-poem action is available is a fact about the selected model, so the button +// has to be renamed when the selection changes and not only when a view opens. +modelEl.addEventListener("change", setBarLabels); triptychEl.addEventListener("click", () => setComparing(!comparing)); registersBtnEl.addEventListener("click", () => setReading(!reading)); @@ -1914,6 +2005,8 @@ async function start(): Promise { } const serviceUp = serviceExpected() ? await refreshCapabilities() : false; + // Now that the capabilities are known, the whole-poem button can name what it will do. + setBarLabels(); if (restored) { showCurrent(); } else if (serviceUp && anyModelReady()) { diff --git a/frontend/app/src/poem.test.ts b/frontend/app/src/poem.test.ts index c05a0bb..5927a29 100644 --- a/frontend/app/src/poem.test.ts +++ b/frontend/app/src/poem.test.ts @@ -355,3 +355,58 @@ test("drafted clips lay end to end, each starting at its own frame zero", () => assert.equal(entryAt(timeline, 74)?.index, 1); assert.equal(entryAt(timeline, 75)?.index, 2); }); + +test("a generation that fails never leaves the line spinning", () => { + // `generating` describes a request in flight. A row that goes on spinning after the + // request died is a lie told by a dot, and it is also unrecoverable on screen: nothing + // else in the state machine clears that state. + const poem = new Poem(["first"]); + const id = poem.all[0].id; + const was = poem.all[0].state; + poem.markGenerating(id); + assert.equal(poem.all[0].state, "generating"); + + poem.cancelGenerating(id, was); + assert.equal(poem.all[0].state, "empty"); +}); + +test("a line that already had a draft keeps it when the next one fails", () => { + // Nothing about the line changed, so it goes back to exactly what it was. Marking it + // `stale` would claim the take it already has had been invalidated, which it has not. + const poem = new Poem(["first"]); + const id = poem.all[0].id; + poem.recordDraft(id, motion(30)); + assert.equal(poem.all[0].state, "draft"); + + const was = poem.all[0].state; + poem.markGenerating(id); + poem.cancelGenerating(id, was); + + assert.equal(poem.all[0].state, "draft"); + assert.equal(poem.all[0].motion?.frames.length, 30); + assert.equal(poem.all[0].history.length, 0); // the take that never arrived made no history +}); + +test("cancelling touches nothing that is not generating", () => { + const poem = new Poem(["first"]); + const id = poem.all[0].id; + poem.recordDraft(id, motion(30)); + + poem.cancelGenerating(id, "empty"); // not in flight — must be a no-op + assert.equal(poem.all[0].state, "draft"); +}); + +test("cancelling never restores 'generating', whatever it is handed", () => { + // The caller passes back what it replaced. If that were itself `generating` — a second + // request on a row already spinning — honouring it would re-arm the lie. + const poem = new Poem(["first"]); + const id = poem.all[0].id; + poem.markGenerating(id); + poem.cancelGenerating(id, "generating"); + assert.equal(poem.all[0].state, "empty"); + + poem.recordDraft(id, motion(30)); + poem.markGenerating(id); + poem.cancelGenerating(id, "generating"); + assert.equal(poem.all[0].state, "stale"); // it has a motion, so it is stale, never 'draft' +}); diff --git a/frontend/app/src/poem.ts b/frontend/app/src/poem.ts index 38d8ea3..f4111d8 100644 --- a/frontend/app/src/poem.ts +++ b/frontend/app/src/poem.ts @@ -372,6 +372,25 @@ export class Poem { if (line) line.state = "generating"; } + /** + * Abandon a generation that never arrived. + * + * `generating` describes a request **in flight**. When one fails nothing is in flight any + * more, and a row that goes on spinning is a lie told by a dot — the same reason a restore + * refuses to bring that state back (see `docs/session-schema.md`). + * + * Nothing about the line itself changed, so it returns to exactly what it was: a line that + * already had a valid draft still has one, and a baked line is still baked. `generating` is + * refused as a destination, falling back to what the line's own motion can support — and + * never to `draft`, because the take that would justify that word is the one that did not + * arrive. + */ + cancelGenerating(id: number, was: LineState): void { + const line = this.get(id); + if (!line || line.state !== "generating") return; + line.state = was !== "generating" ? was : line.motion ? "stale" : "empty"; + } + /** * Record a line's own motion. Only ever makes that one line valid. * diff --git a/frontend/app/src/whole-poem.test.ts b/frontend/app/src/whole-poem.test.ts new file mode 100644 index 0000000..92c73e6 --- /dev/null +++ b/frontend/app/src/whole-poem.test.ts @@ -0,0 +1,49 @@ +/** + * What the whole-poem button is allowed to claim. + * + * The stake here is not a cosmetic label. The button names the action, and the action + * decides whether the result is written into `poem.baked` — which travels into every + * session file the poem is exported to and is read later by people who were not there. A + * button that called a batch of independent drafts a "bake" would be the one case in this + * codebase where the instrument asserts a continuity that never happened. + * + * Run with `npm test` (Node runs TypeScript directly; no test runner is installed). + */ + +import assert from "node:assert/strict"; +import { test } from "node:test"; + +import { wholePoemAction, wholePoemLabel, wholePoemTitle } from "./whole-poem.ts"; + +test("a model that can stitch a poem bakes it", () => { + assert.equal(wholePoemAction({ can_stitch_poems: true }), "bake"); + assert.equal(wholePoemLabel("bake"), "Bake whole poem"); +}); + +test("a model that cannot stitch drafts every line instead", () => { + assert.equal(wholePoemAction({ can_stitch_poems: false }), "draft-all"); + assert.equal(wholePoemLabel("draft-all"), "Draft all lines"); +}); + +test("a model that never said is not assumed able to stitch", () => { + // `null` is not `false` — but it is not `true` either, and the whole-poem action is the + // wrong place to find out. Drafting line by line is something every model can answer. + assert.equal(wholePoemAction({ can_stitch_poems: null }), "draft-all"); + assert.equal(wholePoemAction({}), "draft-all"); + assert.equal(wholePoemAction(undefined), "draft-all"); +}); + +test("the two actions never share a label", () => { + // The label is the whole notification. If these ever collapsed into one string, a + // non-stitching model would silently claim a continuous reading on screen. + assert.notEqual(wholePoemLabel("bake"), wholePoemLabel("draft-all")); + assert.notEqual(wholePoemTitle("bake"), wholePoemTitle("draft-all")); +}); + +test("only the bake label says the lines are carried", () => { + assert.match(wholePoemTitle("bake"), /carried into the next/); + assert.match(wholePoemTitle("draft-all"), /cannot carry one line into the next/); + // And the word "bake" never appears on the action that is not one. + assert.doesNotMatch(wholePoemLabel("draft-all"), /bake/i); + assert.doesNotMatch(wholePoemTitle("draft-all"), /\bbake\b/i); +}); diff --git a/frontend/app/src/whole-poem.ts b/frontend/app/src/whole-poem.ts new file mode 100644 index 0000000..ed99095 --- /dev/null +++ b/frontend/app/src/whole-poem.ts @@ -0,0 +1,50 @@ +/** + * What the whole-poem button does, for the model that is selected. + * + * `B` has always meant "the whole poem", but only one model can answer that as *one* motion. + * Kimodo conditions each line on the decoded tail of the line before it. SnapMoGen and + * Language of Motion cannot, and SnapMoGen's worker refuses a poem outright rather than + * laying independent lines end to end and calling the result continuous. + * + * So for those models the whole-poem action is a **batch of drafts**, not a bake, and the + * naming is load-bearing. A draft is one line generated alone and the body jumps between + * them; a bake is the whole poem in one pass. A button reading "Bake" while drafting every + * line apart would rename the one distinction `poem.ts` exists to protect — and a label is + * on screen every time, where a dialog is dismissed once by the person who already knew. + * + * The decision lives here rather than in the DOM for the same reason `askFor` does: it is + * the kind of thing that can be wrong without *looking* wrong, so it is tested instead of + * clicked through. We ask using a **capability** and name the action we are about to take. + */ + +import { askFor, type PanelCapability } from "./triptych.ts"; + +export type WholePoemAction = + /** One continuous motion, each line conditioned on the body the last one left. */ + | "bake" + /** Every line generated alone. The body jumps between them, and no bake is recorded. */ + | "draft-all"; + +/** + * Which whole-poem action this model can actually perform. + * + * Delegates the capability read to `askFor`, so there is exactly one place in the codebase + * that decides what `can_stitch_poems` means — including that **`null` is not `true`**: a + * model that never said gets its lines asked for one at a time, which every model can + * answer, rather than being sent a poem on a guess and refused. + */ +export function wholePoemAction(capability: PanelCapability | undefined): WholePoemAction { + return askFor(capability) === "whole" ? "bake" : "draft-all"; +} + +/** The words on the button. Kept beside the decision so the two cannot drift apart. */ +export function wholePoemLabel(action: WholePoemAction): string { + return action === "bake" ? "Bake whole poem" : "Draft all lines"; +} + +/** The hover text, which is where the *reason* goes — the button has room for neither. */ +export function wholePoemTitle(action: WholePoemAction): string { + return action === "bake" + ? "Generate the whole poem continuously, each line carried into the next (B)" + : "This model cannot carry one line into the next — generate every line alone (B)"; +}