From f6a7df008e7342395fbcfb51453eb1612a5bee4f Mon Sep 17 00:00:00 2001 From: Day Dreamer <87640074+HugoXK@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:27:41 +0800 Subject: [PATCH 1/3] test(social): pin the face-room polls to the visible tab The waiting room (2 s) and the room overview (3 s) refreshed `social/face-rooms` at their full rate in a hidden tab, and a tab that came back waited out the rest of the period. The cases mount both effects with a recorded `setInterval` / `visibilitychange`, so they fail on the behaviour a plain `setInterval` has and pass once the poll is scoped to a visible tab: no call while hidden, one at once on return (the 2 s and 3 s cadence restarting from it), and the listener gone on unmount. Fixes #3315 Owner: Dev-3 Written-by: Dev-3 Bot: Dev-3 --- plugins/social/test/poll-visibility.test.js | 205 ++++++++++++++++++++ 1 file changed, 205 insertions(+) create mode 100644 plugins/social/test/poll-visibility.test.js diff --git a/plugins/social/test/poll-visibility.test.js b/plugins/social/test/poll-visibility.test.js new file mode 100644 index 000000000..433f27d0c --- /dev/null +++ b/plugins/social/test/poll-visibility.test.js @@ -0,0 +1,205 @@ +// #3315: the waiting room (2 s) and the room overview (3 s) refreshed `social/face-rooms` at their +// full rate while the tab was hidden, and a tab that came back waited out the rest of the period +// instead of reading once at once. Both effects now go through `pollWhileVisible`: no timer while +// `document.hidden`, one read as the tab comes back, and the cadence restarts from that read. +// +// The client is a classic script; react is the tiny hook runner the other client tests use, and +// `setInterval` / `visibilitychange` are recorded instead of waited on (no jsdom). The assertions +// count calls per mount and per window, never a golden log. +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import { test } from 'node:test' + +const live = { inst: null, idx: 0, stateIdx: 0, queue: null } +const reactStub = { + createElement: (type, props, ...children) => ({ type, props: props ?? {}, children: children.flat(Infinity) }), + Fragment: 'F', + useState(init) { + const inst = live.inst + const i = live.idx++ + if (!(i in inst.hooks)) inst.hooks[i] = { value: live.queue ? live.queue[live.stateIdx++] : (typeof init === 'function' ? init() : init) } + const slot = inst.hooks[i] + return [slot.value, next => { slot.value = typeof next === 'function' ? next(slot.value) : next; inst.dirty = true }] + }, + useEffect(fn, deps) { + live.inst.effects.push([live.idx++, fn, deps]) + }, + useRef(value) { + const inst = live.inst + const i = live.idx++ + if (!(i in inst.hooks)) inst.hooks[i] = { current: value } + return inst.hooks[i] + }, + useMemo(fn) { live.idx++; return fn() }, + useCallback(fn) { live.idx++; return fn }, +} + +// The browser bundle registers its factory under its package name; load it the way the other client +// tests do and hand the factory the hook stub above. +function loadApp() { + const modules = new Map() + const window = { __ModuleLoader__: { load: entry => modules.set(entry.id, entry.factory) } } + new Function('window', readFileSync(new URL('../client.js', import.meta.url), 'utf8'))(window) + return modules.get('@flybot/social')(name => (name === 'react' ? reactStub : {})) +} + +// A document whose `hidden` can change and whose `visibilitychange` listeners the test fires, and a +// timer table the test advances — both installed as globals for the duration of a case. +function makeDocument({ hidden = false } = {}) { + const listeners = new Map() + return { + hidden, + getElementById: () => null, + createElement: () => ({}), + head: { appendChild() {} }, + addEventListener(type, fn) { + const set = listeners.get(type) ?? new Set() + set.add(fn) + listeners.set(type, set) + }, + removeEventListener(type, fn) { listeners.get(type)?.delete(fn) }, + listening: type => (listeners.get(type) ?? new Set()).size, + emit(type) { for (const fn of [...(listeners.get(type) ?? [])]) fn() }, + } +} +function makeTimers() { + let next = 0 + const timers = new Map() + return { + setInterval(fn, ms) { const id = `t${++next}`; timers.set(id, { fn, ms }); return id }, + clearInterval(id) { timers.delete(id) }, + periods: () => [...timers.values()].map(timer => timer.ms), + tick() { for (const timer of [...timers.values()]) timer.fn() }, + } +} +// One case: a fresh document, timer table, call log and module instance. +function scene({ hidden = true } = {}) { + const doc = makeDocument({ hidden }) + const timers = makeTimers() + const calls = [] + const app = loadApp() + const saved = { + document: globalThis.document, + setInterval: globalThis.setInterval, + clearInterval: globalThis.clearInterval, + flybot: globalThis.__flybot__, + } + globalThis.document = doc + globalThis.setInterval = timers.setInterval + globalThis.clearInterval = timers.clearInterval + globalThis.__flybot__ = { + call: (endpoint, payload) => { calls.push([endpoint, payload]); return Promise.resolve({ rooms: [], bots: [] }) }, + canRetry: () => true, + } + return { + doc, timers, calls, app, + faceCalls: () => calls.filter(([endpoint]) => endpoint === 'social/face-rooms').length, + restore() { + globalThis.document = saved.document + globalThis.setInterval = saved.setInterval + globalThis.clearInterval = saved.clearInterval + globalThis.__flybot__ = saved.flybot + }, + } +} +// React would run the first-mount effects after drawing; here that is the call site's own immediate +// read plus its timer, which is exactly what the cases below observe. +function mount(app, name, props, queue = null) { + live.inst = { hooks: {}, effects: [], dirty: false } + live.idx = 0 + live.stateIdx = 0 + live.queue = queue + const out = app[name](props) + live.queue = null + const cleanups = [] + for (const [, fn] of live.inst.effects) { + const off = fn() + if (typeof off === 'function') cleanups.push(off) + } + return { out, cleanups } +} +const unmount = cleanups => { for (const off of cleanups.reverse()) off() } + +const roster = { readOnly: '', byId: {} } +const openRoom = () => ({ id: 'r1', origin: 'face-to-face', face: { status: 'open', roomId: 'fr1' }, participants: [] }) +const overview = app => mount(app, 'FaceRoomOverview', { room: openRoom(), roster, actions: {} }) + +test('#3315: a hidden tab does not poll the room overview', () => { + const s = scene({ hidden: true }) + try { + const { cleanups } = overview(s.app) + s.timers.tick() + s.timers.tick() + assert.equal(s.faceCalls(), 0, `a hidden tab made ${s.faceCalls()} face-room call(s) in one mount`) + assert.deepEqual(s.timers.periods(), [], 'a hidden tab holds no poll timer') + unmount(cleanups) + } finally { s.restore() } +}) + +test('#3315: coming back reads once at once and restarts the 3 s cadence', () => { + const s = scene({ hidden: true }) + try { + const { cleanups } = overview(s.app) + // The hidden mount must add nothing: whatever the log holds was the mounted call, not this return. + s.calls.length = 0 + s.doc.hidden = false + s.doc.emit('visibilitychange') + assert.equal(s.faceCalls(), 1, `coming back made ${s.faceCalls()} face-room call(s), not one`) + assert.deepEqual(s.timers.periods(), [3000], 'the timer restarts from that read') + s.timers.tick() + assert.equal(s.faceCalls(), 2, 'and one period later reads again, once') + unmount(cleanups) + } finally { s.restore() } +}) + +test('#3315: going hidden stops the cadence, and unmount removes the listener', () => { + const s = scene({ hidden: false }) + try { + const { cleanups } = overview(s.app) + assert.equal(s.faceCalls(), 1, 'a visible mount reads at once') + assert.deepEqual(s.timers.periods(), [3000]) + s.doc.hidden = true + s.doc.emit('visibilitychange') + s.timers.tick() + assert.equal(s.faceCalls(), 1, 'a tab that went hidden makes no further call') + assert.deepEqual(s.timers.periods(), [], 'its timer is cleared, not just guarded') + assert.equal(s.doc.listening('visibilitychange'), 1, 'the listener is still there to know it came back') + s.doc.hidden = false + s.doc.emit('visibilitychange') + assert.equal(s.faceCalls(), 2, 'the tab that comes back reads once at once') + assert.deepEqual(s.timers.periods(), [3000], 'from a rebuilt timer, not a hidden phase’s remainder') + unmount(cleanups) + assert.equal(s.doc.listening('visibilitychange'), 0, 'unmount removes the listener') + assert.deepEqual(s.timers.periods(), [], 'and its timer') + } finally { s.restore() } +}) + +// The waiting room's own effect: the same helper at 2 s. Its eleven state slots are answered in the +// order the component asks for them, as the waiting-room i18n test does. +const WAIT_ROOM = { + roomId: 'local1', faceRoomId: 'fr1', joinCode: '482913', status: 'open', mineHandles: ['@chief.home'], + members: [{ id: 'b1', remote: false, handle: '@chief.home', name: 'Chief', ownerName: 'Ann' }], +} +const BOT = { id: 'b1', name: 'Chief', handle: '@chief.home', isMain: true } +const waiting = app => mount(app, 'FaceToFaceGroup', { mode: 'join', roster, remoteChats: [] }, + ['waiting', [BOT], ['b1'], '482913', false, null, [], WAIT_ROOM, 0, null, { link: '', status: null }]) + +test('#3315: the waiting room stops while hidden and reads once when the tab returns', () => { + const s = scene({ hidden: true }) + try { + const { cleanups } = waiting(s.app) + s.timers.tick() + s.timers.tick() + assert.equal(s.faceCalls(), 0, `a hidden waiting room made ${s.faceCalls()} face-room call(s)`) + assert.deepEqual(s.timers.periods(), [], 'a hidden waiting room holds no poll timer') + s.doc.hidden = false + s.doc.emit('visibilitychange') + assert.equal(s.faceCalls(), 1, `coming back made ${s.faceCalls()} face-room call(s), not one`) + assert.deepEqual(s.timers.periods(), [2000], 'the waiting room keeps its 2 s cadence') + s.doc.hidden = true + s.doc.emit('visibilitychange') + s.timers.tick() + assert.equal(s.faceCalls(), 1, 'and going hidden again stops it') + unmount(cleanups) + } finally { s.restore() } +}) From 67e03461a55951dbf925af97b6815e4a9f3945bd Mon Sep 17 00:00:00 2001 From: Day Dreamer <87640074+HugoXK@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:27:44 +0800 Subject: [PATCH 2/3] fix(social): refresh face rooms only while the tab is visible Both face-room refreshes now go through one `pollWhileVisible` helper: it registers the `visibilitychange` listener, reads once and starts the interval only while the tab is visible, clears the timer when the tab hides, and on return reads once at once and rebuilds the interval from that read, so the next call is a full period later rather than the remainder of the hidden phase. The cadences (2000 ms / 3000 ms) and the immediate read on a visible mount are unchanged. Fixes #3315 Owner: Dev-3 Written-by: Dev-3 Bot: Dev-3 --- plugins/social/client.js | 36 ++++++++++++++++++++++++++---------- 1 file changed, 26 insertions(+), 10 deletions(-) diff --git a/plugins/social/client.js b/plugins/social/client.js index 67a0b1813..098d1b47a 100644 --- a/plugins/social/client.js +++ b/plugins/social/client.js @@ -1511,11 +1511,7 @@ window.__ModuleLoader__.load({ const next = list.find(item => (faceId && item.faceRoomId === faceId) || (localId && item.roomId === localId)) if (next) setRoom(current => current ? { ...current, ...next } : next) }, () => {}) - load() - if (typeof setInterval !== 'function') return undefined - const timer = setInterval(load, 2000) - timer?.unref?.() - return () => clearInterval(timer) + return pollWhileVisible(load, 2000) }, [step, room?.faceRoomId, room?.roomId]) useEffect(() => { if (step !== 'waiting' || room?.status !== 'candidate' || !room?.expiresAt) return undefined @@ -3039,6 +3035,30 @@ window.__ModuleLoader__.load({ return () => { clearInterval(timer); doc?.removeEventListener('visibilitychange', onShow) } } + // A poll exists to refresh what the person can see: it does not run while the tab is hidden, it + // reads once as the tab comes back, and the cadence restarts from that read rather than from the + // hidden phase (#3315). + function pollWhileVisible(fn, ms) { + if (typeof setInterval !== 'function') return undefined + const doc = typeof document !== 'undefined' && typeof document.addEventListener === 'function' ? document : null + const visible = () => !doc || !doc.hidden + let timer = null + const stop = () => { if (timer !== null) { clearInterval(timer); timer = null } } + // The first read and the interval start together, so a mount that is already visible refreshes + // at once and a hidden one refreshes when it is shown — one read, then a full period later. + const start = () => { + stop() + if (!visible()) return + fn() + timer = setInterval(fn, ms) + timer?.unref?.() + } + const onShow = () => start() + doc?.addEventListener('visibilitychange', onShow) + start() + return () => { stop(); doc?.removeEventListener('visibilitychange', onShow) } + } + const isPastFace = (room) => { if (!room) return false if (room.status === 'closed' || room.status === 'left') return true @@ -3121,11 +3141,7 @@ window.__ModuleLoader__.load({ const next = list.find(item => (face?.roomId && item.faceRoomId === face.roomId) || item.roomId === room.id) if (next) setSnapshot(next) }, () => {}) - load() - if (typeof setInterval !== 'function') return undefined - const timer = setInterval(load, 3000) - timer?.unref?.() - return () => clearInterval(timer) + return pollWhileVisible(load, 3000) }, [live, face?.roomId, room?.id]) useEffect(() => { const expiresAt = snapshot?.expiresAt || face?.expiresAt From fb4e8812c1196c96f3d3e307d9510ecece291890 Mon Sep 17 00:00:00 2001 From: Day Dreamer <87640074+HugoXK@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:27:49 +0800 Subject: [PATCH 3/3] docs(social): record the visibility-scoped face-room polls Fixes #3315 Owner: Dev-3 Written-by: Dev-3 Bot: Dev-3 --- changelog.d/3315.fixed.md | 1 + docs/subsystems/social.md | 1 + 2 files changed, 2 insertions(+) create mode 100644 changelog.d/3315.fixed.md diff --git a/changelog.d/3315.fixed.md b/changelog.d/3315.fixed.md new file mode 100644 index 000000000..2f1ef3156 --- /dev/null +++ b/changelog.d/3315.fixed.md @@ -0,0 +1 @@ +The social client's waiting-room (2 s) and face-room overview (3 s) polls no longer call `social/face-rooms` while the tab is hidden; coming back reads once at once and restarts the cadence from that read instead of waiting out the hidden period's remainder ([#3315](https://github.com/ThinkFlowLab/FlyBot/issues/3315)). diff --git a/docs/subsystems/social.md b/docs/subsystems/social.md index 552db1ab7..7bd86987c 100644 --- a/docs/subsystems/social.md +++ b/docs/subsystems/social.md @@ -120,6 +120,7 @@ Creating a group opens its Session with zero turns, and the host draws no sessio ### Face-room human turns and UI polish (#166, #167) +- Refresh only what the person can see (#3315): the waiting room's 2 s and the room overview's 3 s `social/face-rooms` polls go through `pollWhileVisible`, so a hidden tab makes no call, coming back reads once at once, and the cadence restarts from that read (clear and rebuild) rather than from the hidden phase's remainder; unmount removes the `visibilitychange` listener. - A plain human line in an open face-to-face room is logged and fanned out once, and starts a single pass of every local Bot (admin first, capped at 6, no @ needed; #287, #295; core `openingSpeakers`, see [core-host](core-host.md)). Since #299 the Bots pick the responder from a plain line (they may `[PASS]`; the first Bot that answers ends the round unless the line is to everyone; the first Bot answers if all pass on the owner's own line), and a line to everyone or `@all` is unchanged. A friend's attested plain line (or `@all`) starts the same pass on this home, routed and single like the owner's own line (#462) (the plugin passes `attested: true` to `postHuman` only for a stamped line); an attested line that names Bots starts only the Bot(s) it names by the label the picker shows (`Friend's Chief`) or by handle; `plugins/social/test` has the two-home case. **Explicit mention list (#293):** the sender's host resolves the picker's labels against the room (`faceMentions().handles`; core `onFaceLine(fn)` passes `{ mentions }` for the owner's typed line) and `faceApi.send` puts the handles in `mentions` next to `typed_by_owner` only when `GET /v1/platform` `features` lists `mentions` (the one feature probe, `serverMentions()`); never on the legacy envelope, Bot lines or an older server. The receiver reads `mentions` (`cleanMentions`, at most 8 handles) only from a line the server attests `typed_by_owner` (`renderFaceEvent`), and `postHuman` resolves the handles against the room first (`mentionedByHandle`): only my own Bots in the list answer; a list naming nobody the room knows, or no list, falls back to the label/name reading above. The composer's `@` picker inserts the label text, so the handles are derived from it at send, not tracked in the composer. - The encoded human line is bounded at 18 000 **code points**, not UTF-16 units (#2641): `encodeFaceHuman` cuts with the file's own `cutCodePoints`, the same 18 000-code-point budget `coSeatEnvelope` applies to an outgoing room-share line, so a person's line whose bound falls inside an emoji ends on a code-point boundary instead of storing a lone surrogate that the next UTF-8 write turns into `U+FFFD`. - A peer string that arrives from the far side of Bot Social is capped on **code points** too (#2693): `cleanText` (60, so a friend's Bot or owner display name), `safeName` (120, an attached file's name), `draftText` (800), the person label `grantPersonView` builds in `mcp-client.js` (60), and the error and invite lines the host caps. All of them cut with one `cutCodePoints` in `src/code-points.js`, which `social.js` still re-exports (#2581), so a value whose bound falls inside an emoji keeps the emoji whole instead of ending on a lone high surrogate that a stored setting, a remote session name or a cross-home payload would show as `U+FFFD`; a value already stored that way is left unchanged rather than migrated.