From a67c89be02c3120cdd779deef7114acb3df08c8a Mon Sep 17 00:00:00 2001 From: omesser Date: Mon, 31 Aug 2026 20:04:15 +0300 Subject: [PATCH 1/2] The thinking indicator yields to a reply, and a one-tick line is never lost MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The dialogue pulse rode exactly one Engine tick while the renderer kept only the newest placement, so a pulse could vanish between animation frames — no speech bubble, and a thinking indicator left to die by timer. The bubble decisions now live in bubble.js as a machine node can test: the event listener latches every pulse, a consumed reply hides the indicator the same frame its bubble shows, and the min-hold delays only silent endings. Co-Authored-By: Claude Fable 5 --- src/bubble.js | 100 +++++++++++++++++++++++++ src/main.js | 169 ++++++++++++++----------------------------- tests/bubble.test.js | 138 ++++++++++++++++++++++++++++++++++- 3 files changed, 292 insertions(+), 115 deletions(-) diff --git a/src/bubble.js b/src/bubble.js index 67f9289ee..94c340246 100644 --- a/src/bubble.js +++ b/src/bubble.js @@ -50,6 +50,106 @@ export function wrapText(text, maxWidth, measureFn) { return lines.slice(0, MAX_LINES); } +export const THINKING_GRACE_MS = 250; +export const THINKING_MIN_HOLD_MS = 600; + +// The bubble decisions, apart from the DOM that displays them, so node can +// drive the machine through tick orderings a display never reproduces on +// demand. Two rules the shape of the transport forces: +// +// - `dialogue` rides exactly one Engine tick, and the renderer keeps only the +// newest placement while it waits for its next animation frame. The Engine +// ticks slightly faster than a display refreshes, so some ticks are only +// ever seen by `event`; a pulse read from the newest placement instead +// would vanish there, silently dropping the line and leaving the thinking +// indicator to die by timer. `event` runs per delivery and latches it. +// - A response ends the thinking indicator the same frame it shows, min-hold +// notwithstanding: the hold exists to keep a briefly-shown indicator from +// flickering when a turn ends *silently*, never to sit beside an answer. +export function createBubbleMachine(io) { + const schedule = io.schedule ?? ((fn, ms) => setTimeout(fn, ms)); + const cancel = io.cancel ?? ((id) => clearTimeout(id)); + + let pendingDialogue = null; + let speechTimer = null; + let graceTimer = null; + let minHoldTimer = null; + let thinkingShown = false; + let thinking = false; + + function hideThinkingNow() { + if (graceTimer !== null) { + cancel(graceTimer); + graceTimer = null; + } + if (minHoldTimer !== null) { + cancel(minHoldTimer); + minHoldTimer = null; + } + if (thinkingShown) { + thinkingShown = false; + io.hideThinking(); + } + } + + return { + // Every delivered placement, straight from the event listener. + event(placement) { + if (placement.dialogue) pendingDialogue = placement.dialogue; + }, + + // The newest placement, once per drawn frame. + frame(placement) { + const dialogue = pendingDialogue; + pendingDialogue = null; + + // A hidden sprite speaks to nobody; the pulse is consumed, not queued, + // or the line would pop up whenever the sprite next fades in. + if (dialogue && placement.visible) { + hideThinkingNow(); + if (speechTimer !== null) cancel(speechTimer); + io.showSpeech(dialogue); + speechTimer = schedule(() => { + speechTimer = null; + io.hideSpeech(); + }, bubbleDuration(dialogue)); + } + + thinking = Boolean(placement.thinking && placement.visible); + if (thinking) { + if (!thinkingShown && graceTimer === null) { + graceTimer = schedule(() => { + graceTimer = null; + if (!thinking) return; + thinkingShown = true; + io.showThinking(); + minHoldTimer = schedule(() => { + minHoldTimer = null; + if (!thinking) hideThinkingNow(); + }, THINKING_MIN_HOLD_MS); + }, THINKING_GRACE_MS); + } + } else if (graceTimer !== null) { + cancel(graceTimer); + graceTimer = null; + } else if (thinkingShown && minHoldTimer === null) { + hideThinkingNow(); + } + }, + + // The hide hotkey's instant answer: nothing may stay or come back. + hideAllNow() { + hideThinkingNow(); + if (speechTimer !== null) { + cancel(speechTimer); + speechTimer = null; + } + pendingDialogue = null; + io.hideSpeech(); + }, + }; +} + export function placeBubble(spriteRect, bubbleSize, displayBounds, ceilingClearance) { const spriteHeadY = spriteRect.y; const spriteBottomY = spriteRect.y + spriteRect.height; diff --git a/src/main.js b/src/main.js index 181004d21..8a34bed95 100644 --- a/src/main.js +++ b/src/main.js @@ -4,7 +4,12 @@ // interpolated across. import { interpolate } from "./interpolate.js"; -import { bubbleDuration, wrapText, placeBubble, CEILING_CLEARANCE } from "./bubble.js"; +import { + createBubbleMachine, + wrapText, + placeBubble, + CEILING_CLEARANCE, +} from "./bubble.js"; const sprite = document.getElementById("sprite"); const bubble = document.getElementById("bubble"); @@ -40,15 +45,48 @@ let latest = null; // ask the loader for art it already has. let drawn = null; -// Bubble state: latched dialogue and timers for grace/min-hold. -let speechTimeout = null; -let thinkingGraceTimeout = null; -let thinkingMinHoldTimeout = null; -let thinkingShown = false; -let lastLatchedDialogue = null; -let lastLatchedThinking = false; -const THINKING_GRACE_MS = 250; -const THINKING_MIN_HOLD_MS = 600; +// The bubble decisions live in bubble.js where node can test them; this file +// only supplies the DOM they act on. Showing positions against the newest +// placement; the per-frame follow below keeps a visible bubble tracking a +// walking sprite afterwards. +function currentSpriteRect() { + return { x: latest.x, y: latest.y, width: latest.width, height: latest.height }; +} + +function currentDisplayBounds() { + return { x: 0, y: 0, width: window.innerWidth, height: window.innerHeight }; +} + +function show(element) { + element.classList.remove("hidden"); + element.classList.add("visible"); + positionBubble(element, currentSpriteRect(), currentDisplayBounds()); +} + +function hide(element) { + element.classList.remove("visible"); + const fadeMs = latest?.fade_ms || 0; + setTimeout(() => element.classList.add("hidden"), fadeMs); +} + +const bubbles = createBubbleMachine({ + showSpeech(text) { + const canvas = document.createElement("canvas"); + const ctx = canvas.getContext("2d"); + ctx.font = "14px system-ui, sans-serif"; + bubbleContent.textContent = wrapText(text, 260, ctx.measureText.bind(ctx)).join("\n"); + show(bubble); + }, + hideSpeech() { + hide(bubble); + }, + showThinking() { + show(thinkingBubble); + }, + hideThinking() { + hide(thinkingBubble); + }, +}); function draw(now) { requestAnimationFrame(draw); @@ -81,9 +119,7 @@ function draw(now) { bubble.style.opacity = "0"; thinkingBubble.style.opacity = "0"; if (latest.fade_ms === 0) { - bubble.classList.add("hidden"); - thinkingBubble.classList.add("hidden"); - clearThinkingBubble(); + bubbles.hideAllNow(); } } else { bubble.style.opacity = ""; @@ -112,7 +148,7 @@ function draw(now) { } } - latchBubbles(); + bubbles.frame(latest); const placement = `${latest.animation}#${latest.frame_index} ${latest.width}x${latest.height}`; if (placement === drawn) { @@ -143,106 +179,6 @@ function positionBubble(element, spriteRect, displayBounds) { element.style.setProperty("--tail-offset", `${pos.tailOffset}px`); } -function latchBubbles() { - if (!latest) return; - - const dialogueChanged = latest.dialogue !== lastLatchedDialogue; - const thinkingChanged = latest.thinking !== lastLatchedThinking; - - if (!dialogueChanged && !thinkingChanged) { - return; - } - - lastLatchedDialogue = latest.dialogue; - lastLatchedThinking = latest.thinking; - - const spriteRect = { - x: latest.x, - y: latest.y, - width: latest.width, - height: latest.height, - }; - - const displayBounds = { - x: 0, - y: 0, - width: window.innerWidth, - height: window.innerHeight, - }; - - if (latest.dialogue && latest.visible) { - if (speechTimeout) clearTimeout(speechTimeout); - - const canvas = document.createElement("canvas"); - const ctx = canvas.getContext("2d"); - ctx.font = "14px system-ui, sans-serif"; - const lines = wrapText(latest.dialogue, 260, ctx.measureText.bind(ctx)); - bubbleContent.textContent = lines.join("\n"); - - bubble.classList.remove("hidden"); - bubble.classList.add("visible"); - - positionBubble(bubble, spriteRect, displayBounds); - - const duration = bubbleDuration(latest.dialogue); - const fadeMs = latest.fade_ms || 0; - speechTimeout = setTimeout(() => { - bubble.classList.remove("visible"); - setTimeout(() => bubble.classList.add("hidden"), fadeMs); - }, duration); - - clearThinkingBubble(); - } - - if (latest.thinking && latest.visible) { - if (!thinkingShown && !thinkingGraceTimeout) { - thinkingGraceTimeout = setTimeout(() => { - thinkingGraceTimeout = null; - if (latest?.thinking && latest?.visible) { - showThinkingBubble(spriteRect, displayBounds); - } - }, THINKING_GRACE_MS); - } - } else if (thinkingShown || thinkingGraceTimeout) { - if (thinkingGraceTimeout) { - clearTimeout(thinkingGraceTimeout); - thinkingGraceTimeout = null; - } else if (thinkingShown && !thinkingMinHoldTimeout) { - clearThinkingBubble(); - } - } -} - -function showThinkingBubble(spriteRect, displayBounds) { - thinkingBubble.classList.remove("hidden"); - thinkingBubble.classList.add("visible"); - thinkingShown = true; - - positionBubble(thinkingBubble, spriteRect, displayBounds); - - thinkingMinHoldTimeout = setTimeout(() => { - thinkingMinHoldTimeout = null; - if (!latest?.thinking) { - clearThinkingBubble(); - } - }, THINKING_MIN_HOLD_MS); -} - -function clearThinkingBubble() { - if (thinkingGraceTimeout) { - clearTimeout(thinkingGraceTimeout); - thinkingGraceTimeout = null; - } - if (thinkingMinHoldTimeout) { - clearTimeout(thinkingMinHoldTimeout); - thinkingMinHoldTimeout = null; - } - thinkingBubble.classList.remove("visible"); - const fadeMs = latest?.fade_ms || 0; - setTimeout(() => thinkingBubble.classList.add("hidden"), fadeMs); - thinkingShown = false; -} - async function start() { const character = await window.__TAURI__.core.invoke("character"); art = character.art; @@ -264,6 +200,11 @@ async function start() { ({ payload }) => { previous = latest; latest = { ...payload, at: performance.now() }; + // Dialogue rides exactly one tick, and `latest` keeps only the newest + // placement: an Engine that ticks faster than the display refreshes + // overwrites some placements before `draw` ever reads them. The machine + // latches the pulse here, where every delivery is seen. + bubbles.event(payload); }, { target: overlay.label }, ); diff --git a/tests/bubble.test.js b/tests/bubble.test.js index dac5d4e75..64b184fe4 100644 --- a/tests/bubble.test.js +++ b/tests/bubble.test.js @@ -3,7 +3,15 @@ import assert from "node:assert/strict"; import { test } from "node:test"; -import { bubbleDuration, wrapText, placeBubble, CEILING_CLEARANCE } from "../src/bubble.js"; +import { + bubbleDuration, + wrapText, + placeBubble, + createBubbleMachine, + CEILING_CLEARANCE, + THINKING_GRACE_MS, + THINKING_MIN_HOLD_MS, +} from "../src/bubble.js"; const testMeasureFn = (text) => ({ width: text.length * 8 }); @@ -94,3 +102,131 @@ test("bubble stays whole across display seam", () => { assert.ok(pos.x + bubbleSize.width <= displayBounds.x + displayBounds.width, "bubble not past right edge"); assert.equal(typeof pos.flipped, "boolean", "flipped flag is present"); }); + +// --- The bubble machine: what shows and hides, driven by fake timers. --- + +function machineHarness() { + let now = 0; + let nextId = 1; + const timers = new Map(); + const calls = []; + const machine = createBubbleMachine({ + showSpeech: (text) => calls.push(`showSpeech:${text}`), + hideSpeech: () => calls.push("hideSpeech"), + showThinking: () => calls.push("showThinking"), + hideThinking: () => calls.push("hideThinking"), + schedule(fn, ms) { + const id = nextId++; + timers.set(id, { fn, at: now + ms }); + return id; + }, + cancel(id) { + timers.delete(id); + }, + }); + // Steps timer by timer so a callback that schedules (the grace arming the + // min-hold) sees the clock at its own fire time, the way real timers do. + const advance = (ms) => { + const target = now + ms; + for (;;) { + const due = [...timers.entries()] + .filter(([, timer]) => timer.at <= target) + .sort((a, b) => a[1].at - b[1].at)[0]; + if (!due) break; + const [id, timer] = due; + timers.delete(id); + now = timer.at; + timer.fn(); + } + now = target; + }; + const placement = (overrides) => ({ + dialogue: null, + thinking: false, + visible: true, + ...overrides, + }); + return { machine, calls, advance, placement }; +} + +test("a reply hides the thinking indicator the same frame its bubble shows", () => { + const { machine, calls, advance, placement } = machineHarness(); + + const thinkingTick = placement({ thinking: true }); + machine.event(thinkingTick); + machine.frame(thinkingTick); + advance(THINKING_GRACE_MS); + assert.deepEqual(calls, ["showThinking"], "grace elapsed, indicator up"); + + // The reply lands while the min-hold is still pending: the hold is for + // silent endings and must not delay the answer. + const reply = placement({ dialogue: "hello" }); + machine.event(reply); + machine.frame(reply); + assert.deepEqual( + calls, + ["showThinking", "hideThinking", "showSpeech:hello"], + "indicator gone before the speech bubble shows, no timers involved", + ); +}); + +test("a dialogue pulse overwritten before the next drawn frame still shows", () => { + const { machine, calls, placement } = machineHarness(); + + // The Engine ticks faster than the display refreshes: the dialogue tick + // and its successor both arrive before draw samples the newest placement. + machine.event(placement({ dialogue: "missed me?" })); + machine.event(placement({})); + machine.frame(placement({})); + + assert.deepEqual(calls, ["showSpeech:missed me?"], "the pulse was latched"); +}); + +test("a silent ending within the min-hold clears at the hold, not before", () => { + const { machine, calls, advance, placement } = machineHarness(); + + const thinkingTick = placement({ thinking: true }); + machine.frame(thinkingTick); + advance(THINKING_GRACE_MS); + assert.deepEqual(calls, ["showThinking"]); + + machine.frame(placement({})); + assert.deepEqual(calls, ["showThinking"], "held: no flicker on a fast silent end"); + + advance(THINKING_MIN_HOLD_MS); + assert.deepEqual(calls, ["showThinking", "hideThinking"], "cleared at the hold"); +}); + +test("a silent ending after the min-hold clears immediately", () => { + const { machine, calls, advance, placement } = machineHarness(); + + machine.frame(placement({ thinking: true })); + advance(THINKING_GRACE_MS + THINKING_MIN_HOLD_MS); + assert.deepEqual(calls, ["showThinking"], "still thinking at hold expiry"); + + machine.frame(placement({})); + assert.deepEqual(calls, ["showThinking", "hideThinking"]); +}); + +test("a reply faster than the grace never shows the indicator", () => { + const { machine, calls, advance, placement } = machineHarness(); + + machine.frame(placement({ thinking: true })); + const reply = placement({ dialogue: "quick" }); + machine.event(reply); + machine.frame(reply); + advance(THINKING_GRACE_MS + THINKING_MIN_HOLD_MS); + + assert.deepEqual(calls, ["showSpeech:quick"], "no flash of the indicator"); +}); + +test("the speech bubble hides itself after its reading time", () => { + const { machine, calls, advance, placement } = machineHarness(); + + const reply = placement({ dialogue: "hi" }); + machine.event(reply); + machine.frame(reply); + advance(bubbleDuration("hi")); + + assert.deepEqual(calls, ["showSpeech:hi", "hideSpeech"]); +}); From 3bce8781a8719913d3bc747381a88ef1937dba96 Mon Sep 17 00:00:00 2001 From: omesser Date: Mon, 31 Aug 2026 20:14:25 +0300 Subject: [PATCH 2/2] Speech and the thinking indicator are mutually exclusive, speech wins A new turn starting while a reply was still displayed drew the indicator over it. The indicator now never shows during a line's reading window; when the line hides, a turn still in flight starts its grace from that moment, so a reply landing right then never flashes it. Co-Authored-By: Claude Fable 5 --- src/bubble.js | 39 ++++++++++++++++------- tests/bubble.test.js | 76 +++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 99 insertions(+), 16 deletions(-) diff --git a/src/bubble.js b/src/bubble.js index 94c340246..170373136 100644 --- a/src/bubble.js +++ b/src/bubble.js @@ -55,7 +55,7 @@ export const THINKING_MIN_HOLD_MS = 600; // The bubble decisions, apart from the DOM that displays them, so node can // drive the machine through tick orderings a display never reproduces on -// demand. Two rules the shape of the transport forces: +// demand. Three rules the transport and the reader force: // // - `dialogue` rides exactly one Engine tick, and the renderer keeps only the // newest placement while it waits for its next animation frame. The Engine @@ -66,12 +66,18 @@ export const THINKING_MIN_HOLD_MS = 600; // - A response ends the thinking indicator the same frame it shows, min-hold // notwithstanding: the hold exists to keep a briefly-shown indicator from // flickering when a turn ends *silently*, never to sit beside an answer. +// - Speech and the indicator are mutually exclusive, and speech wins: while +// a line is displayed — its whole reading window — the indicator never +// shows, whatever a new turn does. When the line hides, a turn still in +// flight starts its grace from that moment, so a reply landing right then +// never flashes the indicator. export function createBubbleMachine(io) { const schedule = io.schedule ?? ((fn, ms) => setTimeout(fn, ms)); const cancel = io.cancel ?? ((id) => clearTimeout(id)); let pendingDialogue = null; let speechTimer = null; + let speechShowing = false; let graceTimer = null; let minHoldTimer = null; let thinkingShown = false; @@ -92,6 +98,19 @@ export function createBubbleMachine(io) { } } + function armGrace() { + graceTimer = schedule(() => { + graceTimer = null; + if (!thinking || speechShowing) return; + thinkingShown = true; + io.showThinking(); + minHoldTimer = schedule(() => { + minHoldTimer = null; + if (!thinking) hideThinkingNow(); + }, THINKING_MIN_HOLD_MS); + }, THINKING_GRACE_MS); + } + return { // Every delivered placement, straight from the event listener. event(placement) { @@ -108,26 +127,21 @@ export function createBubbleMachine(io) { if (dialogue && placement.visible) { hideThinkingNow(); if (speechTimer !== null) cancel(speechTimer); + speechShowing = true; io.showSpeech(dialogue); speechTimer = schedule(() => { speechTimer = null; + speechShowing = false; io.hideSpeech(); + // Only now may a turn still in flight surface its indicator. + if (thinking && graceTimer === null && !thinkingShown) armGrace(); }, bubbleDuration(dialogue)); } thinking = Boolean(placement.thinking && placement.visible); if (thinking) { - if (!thinkingShown && graceTimer === null) { - graceTimer = schedule(() => { - graceTimer = null; - if (!thinking) return; - thinkingShown = true; - io.showThinking(); - minHoldTimer = schedule(() => { - minHoldTimer = null; - if (!thinking) hideThinkingNow(); - }, THINKING_MIN_HOLD_MS); - }, THINKING_GRACE_MS); + if (!thinkingShown && graceTimer === null && !speechShowing) { + armGrace(); } } else if (graceTimer !== null) { cancel(graceTimer); @@ -144,6 +158,7 @@ export function createBubbleMachine(io) { cancel(speechTimer); speechTimer = null; } + speechShowing = false; pendingDialogue = null; io.hideSpeech(); }, diff --git a/tests/bubble.test.js b/tests/bubble.test.js index 64b184fe4..c178ddd17 100644 --- a/tests/bubble.test.js +++ b/tests/bubble.test.js @@ -110,11 +110,34 @@ function machineHarness() { let nextId = 1; const timers = new Map(); const calls = []; + // Speech strictly wins: at no step of any test may both be visible. Pinned + // in the harness itself so every scenario asserts it for free. + let speechVisible = false; + let thinkingVisible = false; + const exclusive = () => + assert.ok( + !(speechVisible && thinkingVisible), + "speech and thinking visible together", + ); const machine = createBubbleMachine({ - showSpeech: (text) => calls.push(`showSpeech:${text}`), - hideSpeech: () => calls.push("hideSpeech"), - showThinking: () => calls.push("showThinking"), - hideThinking: () => calls.push("hideThinking"), + showSpeech(text) { + speechVisible = true; + calls.push(`showSpeech:${text}`); + exclusive(); + }, + hideSpeech() { + speechVisible = false; + calls.push("hideSpeech"); + }, + showThinking() { + thinkingVisible = true; + calls.push("showThinking"); + exclusive(); + }, + hideThinking() { + thinkingVisible = false; + calls.push("hideThinking"); + }, schedule(fn, ms) { const id = nextId++; timers.set(id, { fn, at: now + ms }); @@ -230,3 +253,48 @@ test("the speech bubble hides itself after its reading time", () => { assert.deepEqual(calls, ["showSpeech:hi", "hideSpeech"]); }); + +test("a new turn waits behind a displayed reply, indicator only after it hides", () => { + const { machine, calls, advance, placement } = machineHarness(); + + const reply = placement({ dialogue: "hi" }); + machine.event(reply); + machine.frame(reply); + assert.deepEqual(calls, ["showSpeech:hi"]); + + // A second poke starts a new turn while the reply is still on screen: the + // indicator must not appear over it, however long the turn runs. + machine.frame(placement({ thinking: true })); + advance(THINKING_GRACE_MS + THINKING_MIN_HOLD_MS); + assert.deepEqual(calls, ["showSpeech:hi"], "nothing shows over the reply"); + + // Reading time up: the reply hides, and the still-running turn starts its + // grace from this moment. + advance(bubbleDuration("hi") - THINKING_GRACE_MS - THINKING_MIN_HOLD_MS); + assert.deepEqual(calls, ["showSpeech:hi", "hideSpeech"]); + + advance(THINKING_GRACE_MS); + assert.deepEqual(calls, ["showSpeech:hi", "hideSpeech", "showThinking"]); +}); + +test("a reply landing in the post-speech grace never flashes the indicator", () => { + const { machine, calls, advance, placement } = machineHarness(); + + const first = placement({ dialogue: "hi" }); + machine.event(first); + machine.frame(first); + machine.frame(placement({ thinking: true })); + advance(bubbleDuration("hi")); + assert.deepEqual(calls, ["showSpeech:hi", "hideSpeech"], "grace just restarted"); + + const second = placement({ dialogue: "again" }); + machine.event(second); + machine.frame(second); + advance(THINKING_GRACE_MS + THINKING_MIN_HOLD_MS); + + assert.deepEqual( + calls, + ["showSpeech:hi", "hideSpeech", "showSpeech:again"], + "the indicator never appeared", + ); +});