Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

kernel: presence survives a backgrounded tab — no more once-a-minute flicker (#534)

nyblnete0a1da4933c0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a6a43854..6e0c8abb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,13 @@ pre-1.0.
## [Unreleased]
+- **Collaborators stop flickering in and out.** A person whose tab was in the
+ background appeared to leave and rejoin about once a minute: a browser slows a
+ hidden tab's timers to roughly one tick a minute, so their "still here" beat
+ arrived later than the 13-second window that decided who was present. The
+ window is now long enough to cover a throttled tab, a tab sends its beat the
+ moment it comes back to the foreground, and a backgrounded collaborator now
+ shows as away rather than vanishing.
- **Formulas that stayed as raw text now render.** 1.2.0 replaced the maths
engine with a smaller one of our own, and a whole set of everyday LaTeX fell
back to raw text: `\frac12`, `\over` and `\choose`, `\pmod`, `\middle|`,
diff --git a/kernel/src/sync/session.ts b/kernel/src/sync/session.ts
index 6031ff81..687a3ec3 100644
--- a/kernel/src/sync/session.ts
+++ b/kernel/src/sync/session.ts
@@ -171,6 +171,10 @@ export interface PresenceInfo {
pub?: string
/** capability of this copy, derived locally from its collab material */
role?: 'owner' | 'editor' | 'viewer'
+ /** the tab is backgrounded (document.hidden) — the UI can dim the avatar
+ * instead of treating a throttled beat as a departure. Presence only; never
+ * in the document. Absent = present/unknown. */
+ away?: boolean
}
export interface Peer extends PresenceInfo {
@@ -310,7 +314,16 @@ function tabActor(): string {
const DIFF_DEBOUNCE_MS = 90
const HEARTBEAT_MS = 5000
-const PEER_TTL_MS = 13000
+// The TTL must clear the worst LEGITIMATE beat interval, not a multiple of the
+// ideal one. A browser throttles a backgrounded tab's timers hard — Chrome to
+// about once a MINUTE after a few minutes hidden, Safari sooner — so a
+// collaborator whose tab is in the background still beats, just every ~60 s. At
+// 13 s (2.6× the 5 s ideal) the sweep dropped them between throttled beats and
+// the next beat re-added them: everyone saw that person leave and rejoin once a
+// minute. 75 s clears the 60 s throttle with margin. A real departure is still
+// gone within 75 s (and instantly on `bye`); backgrounded peers also send
+// `away` so the UI can dim rather than wait.
+const PEER_TTL_MS = 75000
export class SyncSession {
readonly actor: string
@@ -343,6 +356,13 @@ export class SyncSession {
store.on('doc', () => this.onLocalChange())
for (const ev of host.presenceEvents) store.on(ev, () => this.pushPresence())
window.addEventListener('beforeunload', () => this.broadcast({ t: 'bye', a: this.actor }))
+ // A backgrounded tab's heartbeat is throttled to ~once a minute, so beat the
+ // instant it changes visibility: on return the peer refreshes before the TTL
+ // could sweep it, and on leaving it carries `away` so peers dim promptly.
+ // visibilitychange fires unthrottled in both directions.
+ if (typeof document !== 'undefined') {
+ document.addEventListener('visibilitychange', () => this.pushPresence())
+ }
}
// --- lifecycle -----------------------------------------------------------
@@ -738,6 +758,7 @@ export class SyncSession {
...(this.editingEl ? { editing: this.editingEl } : {}),
...(pub ? { pub } : {}),
...(role ? { role } : {}),
+ ...(typeof document !== 'undefined' && document.hidden ? { away: true } : {}),
}
}
diff --git a/scripts/test-sync-session.ts b/scripts/test-sync-session.ts
index a4eec936..8fc9d01e 100644
--- a/scripts/test-sync-session.ts
+++ b/scripts/test-sync-session.ts
@@ -34,6 +34,18 @@ const listeners: Record<string, Array<() => void>> = {};
clearInterval: (h: number) => clearInterval(h),
addEventListener: (ev: string, fn: () => void) => { (listeners[ev] ??= []).push(fn); },
};
+// A document with a mutable `hidden` and captured visibilitychange handlers, so
+// the rig can background/foreground a tab and fire the event the session listens
+// for. The session uses document only for these two things (presence away + the
+// visibility beat).
+const visHandlers: Array<() => void> = [];
+const fakeDoc = {
+ hidden: false,
+ addEventListener: (ev: string, fn: () => void) => { if (ev === 'visibilitychange') visHandlers.push(fn); },
+};
+(globalThis as unknown as { document: unknown }).document = fakeDoc;
+/** background/foreground every tab and fire visibilitychange, as a browser does */
+const setHidden = (h: boolean) => { fakeDoc.hidden = h; for (const fn of visHandlers) fn(); };
// App source is written for Vite and imports without file extensions; Node
// needs help resolving those. Registered BEFORE the dynamic imports below —
@@ -44,6 +56,7 @@ register('./lib/ts-resolve-hooks.mjs', import.meta.url);
const { Store } = await import('../slides/src/store.ts');
const { SyncSession } = await import('../slides/src/sync/session.ts');
const { newDoc, emptySlide } = await import('../slides/src/model.ts');
+const { SYNC_V } = await import('../kernel/src/sync/crdt.ts');
let failures = 0, checks = 0;
function ok(cond: boolean, msg: string) {
@@ -319,6 +332,56 @@ H('a photo-heavy deck snapshot fits under the relay frame ceiling (assets travel
s.stop?.();
}
+// ---- a backgrounded tab is `away`, not gone, and beats on return -----------
+H('presence: a hidden tab is away, and a return beats at once');
+{
+ const { sa, sb, close } = tabs();
+ await settle(150);
+ const aFromB = () => sb.peers().find(p => p.actor === sa.actor);
+ setHidden(true); // browsers fire visibilitychange → the session beats
+ await settle(150);
+ ok(aFromB()?.away === true, 'a hidden tab is seen as away by its peer, not dropped');
+ setHidden(false);
+ await settle(150);
+ ok(!aFromB()?.away, 'returning to the foreground clears away immediately (beat on visibilitychange)');
+ close();
+ setHidden(false);
+}
+
+// ---- a slow (throttled) beat is not swept before the TTL; a real leave is ---
+// A backgrounded tab's timers throttle to ~once a minute; the sweep must not
+// drop such a peer between beats. The clock is mocked so the peer's AGE is
+// controlled, and the heartbeat is sped up so the sweep runs without a 75 s wait.
+H('presence: a peer last seen 60s ago survives; 80s is swept');
+{
+ const win = (globalThis as unknown as { window: { setInterval: (fn: () => void, ms: number) => unknown } }).window;
+ const realSI = win.setInterval;
+ win.setInterval = (fn: () => void, ms: number) => realSI(fn, ms >= 1000 ? 30 : ms); // 5s heartbeat → 30ms
+ const realNow = Date.now; let clock = 5_000_000; (Date as unknown as { now: () => number }).now = () => clock;
+ try {
+ const doc = newDoc(); doc.docId = `rig-ttl-${Math.random().toString(36).slice(2, 8)}`;
+ const s = new Store(JSON.parse(JSON.stringify(doc)));
+ const sess = new SyncSession(s);
+ await settle(80); // sess attaches; sweep now runs every ~30ms
+ const ch = new BroadcastChannel(`bento-sync-${doc.docId}`);
+ // one peer beats ONCE and never again (throttled to silence), at clock=t0
+ ch.postMessage({ t: 'p', a: 'ghost', pv: SYNC_V, p: { name: 'Ghost', color: '#8FA3BF', slide: 's1', sel: [] } });
+ await settle(80);
+ const hasGhost = () => sess.peers().some(p => p.actor === 'ghost');
+ ok(hasGhost(), 'the peer is present after its single beat');
+ clock += 60_000; // 60s later, no further beat
+ await settle(120);
+ ok(hasGhost(), 'a peer last seen 60s ago is NOT swept — the TTL clears the 60s hidden-tab throttle');
+ clock += 20_000; // 80s total
+ await settle(120);
+ ok(!hasGhost(), 'a peer gone 80s IS swept — a real departure still clears');
+ ch.close(); sess.stop?.();
+ } finally {
+ (Date as unknown as { now: () => number }).now = realNow;
+ win.setInterval = realSI;
+ }
+}
+
console.log(`\n${checks - failures}/${checks} checks passed`);
// BroadcastChannel and the heartbeat keep node's event loop alive
process.exit(failures ? 1 : 0);