HEL-880: preserve inbox pagination gaps until reach-outs are delivered
Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
+24
-11
@@ -10,21 +10,34 @@ export const serverId = (m: Message) => /^[1-9]\d{0,18}$/u.test(m.id) ? Number(m
|
||||
export const newestId = (messages: Message[]) => messages.reduce((top, m) => Math.max(top, serverId(m)), 0);
|
||||
const newestProactive = (messages: Message[]) => messages.reduce((top, m) => m.proactive ? Math.max(top, serverId(m)) : top, 0);
|
||||
|
||||
// Rows newer than `after`, oldest first. Pages back only as far as needed (a long absence on a sleeping tab), bounded.
|
||||
export async function fetchAfter(after: number, signal: AbortSignal, pages = 5): Promise<{ rows: Message[]; newest: number }> {
|
||||
// Where reading stands. Every row up to `through` has been read and handed over. The server only pages backwards from
|
||||
// the newest row, so after a long absence one bounded read may stop short: then `gap` remembers it. Rows from `before`
|
||||
// up to `top` are read, and her reach-outs among them are `held`; rows between `through` and `before` are not read yet.
|
||||
export interface InboxCursor { through: number; gap: { before: number; top: number; held: Message[] } | null }
|
||||
export const startAt = (through: number): InboxCursor => ({ through, gap: null });
|
||||
|
||||
// Her reach-outs newer than the cursor, oldest first, and where the next read starts. At most `pages` pages per call.
|
||||
// A read that stops short hands over nothing yet: the next call goes on down from where it stopped (before looking for
|
||||
// anything newer), and when it meets `through` everything held is handed over at once, in id order, exactly once. So an
|
||||
// older reach-out is never skipped, and newer ones wait only for the reads still owed, never for good. A failed or
|
||||
// aborted read throws and leaves the cursor it was given untouched; the same call simply runs again.
|
||||
export async function fetchAfter(cursor: InboxCursor, signal: AbortSignal, pages = 5): Promise<{ rows: Message[]; cursor: InboxCursor }> {
|
||||
const rows: Message[] = [];
|
||||
let before: number | null = null, newest = after;
|
||||
let through = cursor.through, gap = cursor.gap && { ...cursor.gap, held: [...cursor.gap.held] }, carried = !!gap;
|
||||
for (let i = 0; i < pages; i++) {
|
||||
const page: MessagePage = await api(`messages?limit=50${before ? `&before=${before}` : ''}`, { signal: within(signal, 10000) });
|
||||
const page: MessagePage = await api(`messages?limit=50${gap ? `&before=${gap.before}` : ''}`, { signal: within(signal, 10000) });
|
||||
const list = Array.isArray(page.messages) ? page.messages.filter(m => Number.isSafeInteger(m?.id) && m.id > 0 && typeof m.text === 'string') : [];
|
||||
for (const m of list) newest = Math.max(newest, m.id);
|
||||
const fresh = list.filter(m => m.id > after);
|
||||
rows.unshift(...fresh.map(toMessage));
|
||||
// Reached what the page already holds (or the start of the record): stop.
|
||||
if (fresh.length < list.length || !page.next_before || !after) break;
|
||||
before = page.next_before;
|
||||
const fresh = list.filter(m => m.id > through), opened = !gap;
|
||||
gap ??= { before: 0, top: list.reduce((top, m) => Math.max(top, m.id), through), held: [] };
|
||||
gap.held.unshift(...fresh.filter(m => m.proactive === true).map(toMessage));
|
||||
// Not yet down to what was read before, and more of the record below: keep the gap for the next page or call.
|
||||
if (fresh.length === list.length && page.next_before && Number.isSafeInteger(page.next_before)) { gap.before = page.next_before; continue; }
|
||||
rows.push(...gap.held); through = gap.top; gap = null;
|
||||
// A gap left by an earlier call is closed; look once for anything newer. Otherwise the newest rows were read.
|
||||
if (opened || !carried) break;
|
||||
carried = false;
|
||||
}
|
||||
return { rows, newest };
|
||||
return { rows, cursor: { through, gap } };
|
||||
}
|
||||
|
||||
// What may be added from a poll: her own reach-out rows the page does not hold yet. Your own turns (and her replies to
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { api, lifeStatus, loadReal, memoryNote, type Health } from '../adapters/real';
|
||||
import { arrivals, fetchAfter, initialSeen, newestId, seenThrough, storeSeen, unreadOf } from '../adapters/inbox';
|
||||
import { arrivals, fetchAfter, initialSeen, newestId, seenThrough, startAt, storeSeen, unreadOf } from '../adapters/inbox';
|
||||
import type { DemoState, Message, Theme } from '../domain/model';
|
||||
import { Presenter } from '../stage/Presenter';
|
||||
import { CreationWizard } from '../manage/CreationWizard';
|
||||
@@ -17,14 +17,14 @@ export function RealApp() {
|
||||
const [theme, setTheme] = useState<Theme>(() => { try { return localStorage.getItem('cg.theme') === 'fog' ? 'fog' : 'moon'; } catch { return 'moon'; } });
|
||||
const [herFocus, setHerFocus] = useState(0);
|
||||
const latest = useRef(state); latest.current = state;
|
||||
// ── Her reach-outs while the page is open (inbox.ts). `cursor` is the newest server row this page has read;
|
||||
// ── Her reach-outs while the page is open (inbox.ts). `cursor` is how far this page has read the server record;
|
||||
// `incoming` holds what arrived during a conversation until the stage lets it in; `seen` is the unread mark. ──
|
||||
const cursor = useRef(0), [incoming, setIncoming] = useState<Message[]>([]), held = useRef(incoming); held.current = incoming;
|
||||
const cursor = useRef(startAt(0)), [incoming, setIncoming] = useState<Message[]>([]), held = useRef(incoming); held.current = incoming;
|
||||
const [seen, setSeen] = useState(0), [fresh, setFresh] = useState<Message | null>(null), [visible, setVisible] = useState(!document.hidden);
|
||||
const areaNow = useRef(area); areaNow.current = area;
|
||||
const initialize = useCallback(async () => {
|
||||
setError(''); setReady(false);
|
||||
try { setHealth(await api<Health>('health')); const next = await loadReal(); cursor.current = next ? newestId(next.messages) : 0; setSeen(next ? initialSeen(next.messages) : 0); setState(next); setCreating(!next); setReady(true); }
|
||||
try { setHealth(await api<Health>('health')); const next = await loadReal(); cursor.current = startAt(next ? newestId(next.messages) : 0); setSeen(next ? initialSeen(next.messages) : 0); setState(next); setCreating(!next); setReady(true); }
|
||||
catch (e) { setError((e as Error).message || '暂时连不上真实服务。'); }
|
||||
}, []);
|
||||
useEffect(() => { void initialize(); }, [initialize]);
|
||||
@@ -35,7 +35,8 @@ export function RealApp() {
|
||||
useEffect(() => { document.documentElement.classList.toggle('reduced', !!state?.settings.reduced); }, [state?.settings.reduced]);
|
||||
const changeMessages = useCallback((messages: Message[]) => { if (latest.current) { const next = { ...latest.current, messages }; latest.current = next; setState(next); } }, []);
|
||||
// Read the newest rows every 20 s while the page is shown, at once on return or reconnect. A failed read is quiet
|
||||
// (the next one simply tries again, slower); nothing on screen changes until a new row actually exists.
|
||||
// (the next one simply tries again, slower); nothing on screen changes until a new row actually exists. A read that
|
||||
// stopped short of what was read before goes on after a second, until it has caught up.
|
||||
const live = !!state && !creating && ready;
|
||||
useEffect(() => {
|
||||
if (!live) return;
|
||||
@@ -44,16 +45,16 @@ export function RealApp() {
|
||||
if (running || stopped || document.hidden) return;
|
||||
running = true; clearTimeout(timer); controller = new AbortController();
|
||||
try {
|
||||
const { rows, newest } = await fetchAfter(cursor.current, controller.signal);
|
||||
const { rows, cursor: next } = await fetchAfter(cursor.current, controller.signal);
|
||||
if (stopped) return;
|
||||
cursor.current = Math.max(cursor.current, newest); failures = 0;
|
||||
cursor.current = next; failures = 0;
|
||||
const add = latest.current ? arrivals([...latest.current.messages, ...held.current], rows) : [];
|
||||
if (add.length && latest.current) {
|
||||
if (areaNow.current === 'talk') setIncoming(list => [...list, ...add]);
|
||||
else { changeMessages([...latest.current.messages, ...add]); setFresh(add[add.length - 1]); }
|
||||
}
|
||||
} catch { failures++; }
|
||||
finally { running = false; if (!stopped) timer = setTimeout(() => void poll(), failures ? Math.min(120000, 20000 * 2 ** failures) : 20000); }
|
||||
finally { running = false; if (!stopped) timer = setTimeout(() => void poll(), failures ? Math.min(120000, 20000 * 2 ** failures) : cursor.current.gap ? 1000 : 20000); }
|
||||
};
|
||||
const wake = () => { setVisible(!document.hidden); if (!document.hidden) void poll(); };
|
||||
document.addEventListener('visibilitychange', wake); addEventListener('online', wake);
|
||||
|
||||
Reference in New Issue
Block a user