Files
CyberGril/web/src/chat/reading.ts
T
白栖知andmultica-agent cef8ae5581 HEL-824: land verified fixes on 4321aeb (small-screen first-press, real-time reading clock)
- 6 modified + handoff JSON per CHANGES-HEL-824.json, all hashes verified against git 4321aeb and package bytes
- rework_browser_check: skip full-text sheet at micro height (<420px design hides the control); migrate stale 返回日子 selector to 结束交谈 · 回到日子
- fresh run evidence: web build 25/25 unit tests, backend 142/142 (py3.12), all four browser checks PASS incl. new compact first-press and 700ms slow-frame sections (slow_frames_new_turn_to_reply_s=2.32s), layout regression 320/390/1024/1600 both themes

Co-authored-by: multica-agent <github@multica.ai>
2026-10-24 07:39:26 +08:00

110 lines
6.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import type { Message } from '../domain/model';
// Reading logic carried over from the verified HEL-793/795 prototype (PR#8) and HEL-799 (approved 01a16810), moved
// onto the real message flow: replies are shown one or two lines at a time and flow on by themselves.
// A message as the stage sees it: stored messages plus, at most, the reply still being written or cut off.
export interface ShownMessage extends Message { live?: 'generating' | 'cancelled' }
export interface Turn { key: string; items: ShownMessage[] }
export interface Page { key: string; text: string; index: number; last: boolean; mi: number; message: ShownMessage }
export interface Metrics { width: number; font: number; compact: boolean }
export const graphemes = (text: string): string[] => typeof Intl.Segmenter === 'function' ? [...new Intl.Segmenter('zh', { granularity: 'grapheme' }).segment(text)].map(s => s.segment) : Array.from(text);
// A turn starts with your message (or with something she says on her own). Server turn ids keep a reply with the
// message it answers; older local records without ids fall back to their order.
export function groupTurns(messages: ShownMessage[]): Turn[] {
const turns: Turn[] = [];
for (const m of messages) {
const cur = turns[turns.length - 1], head = cur?.items[0];
const fresh = !cur || m.role === 'user' || !!m.proactive || (!!m.turnId && !!head?.turnId && m.turnId !== head.turnId);
if (fresh || !cur) turns.push({ key: m.turnId || m.id, items: [m] }); else cur.items.push(m);
}
return turns;
}
export function chunks(text: string, { width, font, compact }: Metrics): string[] {
const perLine = Math.floor(Math.max(220, Math.min(width, 900) - 24) / font), max = Math.max(14, Math.min(60, Math.floor(perLine * (compact ? 1.6 : 2))));
const out: string[] = []; let line = '', n = 0;
for (const ch of graphemes(text)) {
if (ch === '\n') { if (line.trim()) { out.push(line); line = ''; n = 0; } continue; }
// Keep closing punctuation with its sentence; never produce an empty line.
if (!line && out.length && /[。!?!?,、;:,;:」』))”]/u.test(ch)) { out[out.length - 1] += ch; continue; }
line += ch; n++;
// Short sentences travel together (as in the approved still); a line ends at a sentence once it has some weight.
if (/[。!?!?]/u.test(ch) && n >= Math.min(22, max * .45)) { out.push(line); line = ''; n = 0; }
else if (n >= max) {
// Long text without punctuation still breaks, so nothing ever overflows the stage.
const cut = Math.max(line.lastIndexOf(','), line.lastIndexOf('、'), line.lastIndexOf(';'));
if (cut > max * .55) { out.push(line.slice(0, cut + 1)); line = line.slice(cut + 1); n = graphemes(line).length; } else { out.push(line); line = ''; n = 0; }
}
}
if (line.trim()) out.push(line);
return out;
}
export function pagesOf(turn: Turn | undefined, metrics: Metrics): Page[] {
const list: Page[] = [];
if (!turn) return list;
turn.items.forEach((message, mi) => {
const parts = chunks(message.text, metrics);
// The newest chunk of a reply still being written is held back (it may still grow or merge with the next
// sentence), so a line never changes or re-animates after it has appeared.
const held = message.live === 'generating' && parts.length ? 1 : 0;
// Keys follow the turn and position, not the message id, so a streamed reply keeps its lines when it is stored.
for (let index = 0; index < parts.length - held; index++) list.push({ key: `${turn.key}:${mi}:${index}`, text: parts[index], index, last: index === parts.length - 1, mi, message });
});
return list;
}
// Each line stays on screen in proportion to its length (about 2.4–8 s for her, shorter for yours).
export function dwellFor(page: Page) {
const n = graphemes(page.text).length;
return page.message.role === 'user' ? Math.min(3000, Math.max(1400, 900 + n * 60)) : Math.min(8000, Math.max(2400, 1500 + n * 150));
}
// How long the current line has stayed. It counts real time, not frames: busy frames (a new turn's crossfade,
// ink, the room) never stretch a stay. One frame counts at most STALL, so a stall (sleep, debugger) is not
// reading; a hidden page restarts the count from its return.
export const STALL = 1000;
export class ReadingClock {
key = ''; dwell = 0; total = 0;
private last = 0;
// True once the line on screen has stayed its time while reading runs. Same key = same line: a growing stream
// or a re-render never restarts it.
tick(now: number, page: Page | undefined, running: boolean): boolean {
const dt = this.last ? Math.min(STALL, Math.max(0, now - this.last)) : 0; this.last = now;
if (!page) return false;
if (page.key !== this.key) { this.key = page.key; this.dwell = 0; this.total = dwellFor(page); }
if (running && this.dwell < this.total) this.dwell = Math.min(this.total, this.dwell + dt);
return running && this.dwell >= this.total;
}
get progress() { return this.total ? this.dwell / this.total : 0; }
// You moved or resumed: the line you land on gets its full time.
restart() { this.dwell = 0; }
forget() { this.key = ''; }
// Page hidden: the gap until it is seen again is not reading time.
pause() { this.last = 0; }
}
// Reading position as a character offset inside one message, so a re-chunk (resize, keyboard) keeps your place.
export interface Anchor { mi: number; offset: number }
export function anchorOf(pages: Page[], cursor: number): Anchor | null {
const page = pages[cursor];
if (!page) return null;
let offset = 0;
for (const p of pages) { if (p === page) break; if (p.mi === page.mi) offset += p.text.length; }
return { mi: page.mi, offset };
}
export function cursorAt(pages: Page[], anchor: Anchor | null): number {
if (!anchor) return 0;
let used = 0, best = -1;
for (let i = 0; i < pages.length; i++) {
if (pages[i].mi < anchor.mi) { best = i; continue; }
if (pages[i].mi > anchor.mi) break;
best = i;
if (used + pages[i].text.length > anchor.offset) return i;
used += pages[i].text.length;
}
return Math.max(0, best);
}