diff --git a/docs/upstream/flybot-files.json b/docs/upstream/flybot-files.json index dde74886c..10dad77e8 100644 --- a/docs/upstream/flybot-files.json +++ b/docs/upstream/flybot-files.json @@ -65,12 +65,6 @@ "mode": "100644", "bytes": 821 }, - "plugins/social/client.js": { - "sha256": "351206abc51ba011f0425c060292515b931dd8462109fe9d8e4d343d86ff88af", - "git_blob_sha": "df78f71716e0713e9151942f3ec0f97b8f0c1e3a", - "mode": "100644", - "bytes": 270636 - }, "plugins/social/test/rest-timeout.test.js": { "sha256": "0c59a063d2c308c1eb2d1cbce5bee57d09579bf6cbb92de6c73eab4f1278b18f", "git_blob_sha": "49f23d0c8f4a5a4dcf8b78e08d0894b9ef3af68d", diff --git a/docs/upstream/migration-manifest.json b/docs/upstream/migration-manifest.json index a66b9d1d3..3af6d8300 100644 --- a/docs/upstream/migration-manifest.json +++ b/docs/upstream/migration-manifest.json @@ -1707,7 +1707,7 @@ "scripts/logo.mjs", "scripts/self-test-catalog.mjs" ], - "file_count": 46 + "file_count": 45 }, "bot-social": { "destination": "services/bot-social", @@ -2258,6 +2258,48 @@ "license_notice": "MIT (Bot Social snapshot)", "new_sha256": "2a477b7e35cdf1d1245486e6980aeb4769d85fc05c82dac774b32814f6325785", "bytes": 22655 + }, + "runtime/flybot/plugins/social/client.js": { + "destination": "runtime/flybot", + "path": "plugins/social/client.js", + "original_sha256": "351206abc51ba011f0425c060292515b931dd8462109fe9d8e4d343d86ff88af", + "original_git_blob_sha": "df78f71716e0713e9151942f3ec0f97b8f0c1e3a", + "new_sha256": "4cc8163ed62299a8bad62a42a126ec7ad4bdc1c3f5e4610cc80747d88b38ad4d", + "bytes": 272278, + "reason": "Repackages the intent of #3356/#3364/#3370 into the vendored plugin: poll only while visible, and draw a failed read as a failed read.", + "license_notice": "Apache-2.0 (FlyBot) file modified in this tree; see runtime/flybot/ORIGIN.md." + }, + "runtime/flybot/plugins/social/test/poll-visibility.test.js": { + "destination": "runtime/flybot", + "path": "plugins/social/test/poll-visibility.test.js", + "new_sha256": "0256e99a2f45db639db3c8ec073243fdbe70e958276fb69520e034aa792cda16", + "bytes": 8036, + "reason": "Test added with the repackage of #3356: a hidden tab holds no poll timer in the approval dock or the requests panel.", + "license_notice": "Apache-2.0 (FlyBot) file modified in this tree; see runtime/flybot/ORIGIN.md." + }, + "runtime/flybot/plugins/social/test/paused-chat-read-error.test.js": { + "destination": "runtime/flybot", + "path": "plugins/social/test/paused-chat-read-error.test.js", + "new_sha256": "a26d4df8cda2601df6490480050442df6c5a05245333a5f09f33e527400c8851", + "bytes": 3885, + "reason": "Test added with the repackage of #3364: a failed paused-chat read is drawn as a failure, not as no pause.", + "license_notice": "Apache-2.0 (FlyBot) file modified in this tree; see runtime/flybot/ORIGIN.md." + }, + "runtime/flybot/plugins/social/test/friend-auto-read-error.test.js": { + "destination": "runtime/flybot", + "path": "plugins/social/test/friend-auto-read-error.test.js", + "new_sha256": "db1ec269a7b6c3e89813d8cc240dd21b671f64657774a80542e7f53e96e39d44", + "bytes": 3777, + "reason": "Test added with the repackage of #3370: a failed Auto-send read is drawn as a failure and the switch is withheld until the value is known.", + "license_notice": "Apache-2.0 (FlyBot) file modified in this tree; see runtime/flybot/ORIGIN.md." + }, + "runtime/flybot/plugins/social/test/client-harness.mjs": { + "destination": "runtime/flybot", + "path": "plugins/social/test/client-harness.mjs", + "new_sha256": "3dba189f2e9a54be2b3a65cebdcc48ed3ca3a02fca8651cabfc6097f487b967e", + "bytes": 5665, + "reason": "Shared render/document/timer bench for the client tests added with the #3364 and #3370 repackage.", + "license_notice": "Apache-2.0 (FlyBot) file modified in this tree; see runtime/flybot/ORIGIN.md." } }, "core_fork_removed": { diff --git a/runtime/flybot/plugins/social/client.js b/runtime/flybot/plugins/social/client.js index df78f7171..79bbf6023 100644 --- a/runtime/flybot/plugins/social/client.js +++ b/runtime/flybot/plugins/social/client.js @@ -91,6 +91,30 @@ window.__ModuleLoader__.load({ return message } + // 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) } + } + // Styles reuse ds-bot's sidebar tokens (--bt-ink, --bt-ink-2, --bt-ink-3, --bt-hover, --bt-line, // --bt-line-2, --bt-card, --bt-accent, --bt-tag-bg/-ink), like @flybot/tree, so both themes follow the app. const CSS = ` @@ -2556,8 +2580,6 @@ window.__ModuleLoader__.load({ useEffect(() => onDockRecords(() => bumpRecord(value => value + 1)), [sessionId]) const failures = dockFailuresOf(sessionId) const load = () => { - // #3080: a tab that is not on screen has nobody reading these cards; showing it catches up below. - if (typeof document !== 'undefined' && document.hidden) return call('social/status', {}).then(value => { setItems(Array.isArray(value?.approvals) ? value.approvals : []) setStatusLoaded(true) @@ -2567,18 +2589,9 @@ window.__ModuleLoader__.load({ setListLoaded(true) }, () => {}) } - useEffect(() => { - load() - if (typeof setInterval !== 'function') return undefined - const timer = setInterval(load, 5000) - timer?.unref?.() - // #3080: a tab that sat in the background catches up the moment it is shown, not one beat later - // (the same shape `everySecond` uses above). - const onShow = () => { if (typeof document === 'undefined' || !document.hidden) load() } - const doc = typeof document !== 'undefined' && typeof document.addEventListener === 'function' ? document : null - doc?.addEventListener('visibilitychange', onShow) - return () => { clearInterval(timer); doc?.removeEventListener('visibilitychange', onShow) } - }, []) + // #3080: a tab nobody is reading keeps no timer; coming back reads once at once and restarts the + // cadence from that read (`pollWhileVisible`). + useEffect(() => pollWhileVisible(load, 5000), []) const session = { sessionId, roster, room, bot, handle: bot?.remote?.handle } // The person who gets it (#418, #498), not the friend's Bot: a local hold already names the person. const named = list => list.map((item) => { @@ -3254,17 +3267,9 @@ window.__ModuleLoader__.load({ const dismissShareRequest = item => call('social/share-request-dismiss', { id: item.id }).then(applyStatus, e => setError(errorText(e))) const dismissAccept = item => call('social/accept-notice-dismiss', { id: item.id }).then(applyStatus, e => setError(errorText(e))) const askShareBack = item => call('social/ask-share-back', { botId: item.botId, to: item.from, noticeId: item.id }).then(applyStatus, e => setError(errorText(e))) - useEffect(() => { - loadApprovals() - if (typeof setInterval !== 'function') return undefined - const tick = () => { - if (typeof document !== 'undefined' && document.hidden) return - loadApprovals() - } - const timer = setInterval(tick, 15_000) - timer?.unref?.() - return () => clearInterval(timer) - }, []) + // A hidden tab is not looking at these requests either, so the 15 s poll runs only while the page + // is on screen and a tab that comes back reads once at once (`pollWhileVisible`). + useEffect(() => pollWhileVisible(loadApprovals, 15_000), []) useEffect(() => facePanel.bind(mode => { setFaceMode(mode === 'start' ? 'start' : 'join'); setFaceOpen(true) }), []) useEffect(() => addFriendPanel.bind(() => setAdding(true)), []) const unavailable = String(error).startsWith('Social is not running:') @@ -3705,14 +3710,25 @@ window.__ModuleLoader__.load({ const remote = bot?.remote const home = remote?.home const handle = remote?.handle - const [auto, setAuto] = useState(false) + // #3366: `null` is "nobody read it yet". A read that failed used to leave `false` here, which is + // drawn exactly like a setting that is off — and the switch stayed live, so the person could read + // the setting as one they chose. The failure is the card's answer while it lasts, and the value + // stays unknown until a read answers (#3323/#3325/#3359 for the same shape elsewhere). + const [auto, setAuto] = useState(null) const [saving, setSaving] = useState(false) const [busy, setBusy] = useState(false) const [asking, setAsking] = useState(false) const [error, setError] = useState('') + const [readError, setReadError] = useState('') useEffect(() => { if (!home) return undefined - call('social/settings', {}).then(value => setAuto(value?.autoAccept?.[home] === true), () => {}) + let live = true + call('social/settings', {}).then(value => { + if (!live) return + setAuto(value?.autoAccept?.[home] === true) + setReadError('') + }, e => { if (live) setReadError(errorText(e)) }) + return () => { live = false } }, [home]) if (!handle) return null const toggleAuto = async (on) => { @@ -3759,9 +3775,10 @@ window.__ModuleLoader__.load({ // The box holds the setting only; the destructive link sits apart, below it (#274). h('div', { className: 'fs-card fs-friend-auto', 'data-flybot': 'friend-auto-box' }, h('label', { className: 'fs-auto', title: AUTO_SEND_NOTE, 'data-flybot': 'friend-auto-send' }, - h('input', { type: 'checkbox', checked: auto === true, disabled: saving || !home, onChange: e => toggleAuto(e.target.checked) }), + h('input', { type: 'checkbox', checked: auto === true, disabled: saving || !home || auto === null, onChange: e => toggleAuto(e.target.checked) }), `Auto-send my Bots' replies to ${who}`), - h('div', { className: 'fs-hint', 'data-flybot': 'friend-auto-hint' }, `Your Bots' replies to ${who} go out without asking you first. What you type is not affected.`)), + h('div', { className: 'fs-hint', 'data-flybot': 'friend-auto-hint' }, `Your Bots' replies to ${who} go out without asking you first. What you type is not affected.`), + readError ? h('div', { className: 'fs-status', 'data-tone': 'error', role: 'status', 'data-flybot': 'friend-auto-read-error' }, readError) : null), h('div', { className: 'fs-friend-remove', 'data-flybot': 'friend-remove-row' }, asking ? h('span', { className: 'fs-leave-ask', 'data-flybot': 'remove-friend-bot-confirm' }, h('span', { className: 'fs-hint' }, `Remove ${botWithOwner(bot.name, named)} from your list? ${keepLine}`), @@ -3953,21 +3970,29 @@ window.__ModuleLoader__.load({ useStyles() const handle = typeof bot?.remote?.handle === 'string' ? bot.remote.handle : '' const [paused, setPaused] = useState(null) + // #3359: a read that failed is not a chat that is not paused. The failure is the card's answer + // while it lasts (the friends list draws it the same way, #3323), so it gets its own state and is + // drawn before the card; a later success replaces it. + const [error, setError] = useState('') useEffect(() => { setPaused(null) + setError('') if (!handle) return undefined let live = true const load = () => { - if (typeof document !== 'undefined' && document.hidden) return - call('social/paused', { handle }).then(value => { if (live) setPaused(value?.paused ?? null) }, () => {}) + call('social/paused', { handle }).then(value => { + if (!live) return + setPaused(value?.paused ?? null) + setError('') + }, e => { if (live) setError(errorText(e)) }) } - load() - if (typeof setInterval !== 'function') return () => { live = false } - const timer = setInterval(load, 5000) - timer?.unref?.() - return () => { live = false; clearInterval(timer) } + const stop = pollWhileVisible(load, 5000) + return () => { live = false; stop?.() } }, [handle]) - if (!handle || !paused) return null + if (!handle) return null + // The 5 s read is the retry: no button, no Extend, no turn count (owner 2026-10-19). + if (error) return h('div', { className: 'fs-hold', 'data-flybot': 'social-paused-error', role: 'status' }, error) + if (!paused) return null return h('div', { className: 'fs-hold fs-chat-approval', 'data-flybot': 'chat-paused', role: 'status' }, h('div', { className: 'fs-label' }, 'Chat paused'), h('div', { className: 'fs-draft' }, `${paused.reason ? `Bot Social paused the last chat with this Bot (${paused.reason}).` : 'Bot Social paused the last chat with this Bot.'} Send your message again: it starts a new chat.`)) diff --git a/runtime/flybot/plugins/social/test/client-harness.mjs b/runtime/flybot/plugins/social/test/client-harness.mjs new file mode 100644 index 000000000..bed902e5a --- /dev/null +++ b/runtime/flybot/plugins/social/test/client-harness.mjs @@ -0,0 +1,144 @@ +// Shared bench for the client-side tests that draw a component from `client.js` and answer its +// `__flybot__.call` reads themselves: a tiny hook runner instead of React, a document whose `hidden` +// the case can flip and whose `visibilitychange` listeners it fires, and a timer table it advances. +// No jsdom — the client is a classic script, so it is loaded into a fake `window` by `loadApp`. +import { readFileSync } from 'node:fs' + +// The hook slots of the component being rendered. `mount` swaps in a fresh table per component, so a +// child's hooks never land in its parent's slots (the way React keeps them apart). +export const live = { inst: null, idx: 0 } + +export const reactStub = { + createElement: (type, props, ...children) => ({ type, props: props ?? {}, children: children.flat(Infinity) }), + Fragment: 'F', + Component: class {}, + useState(init) { + const inst = live.inst + const i = live.idx++ + if (!(i in inst.hooks)) inst.hooks[i] = { value: 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. +export 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 : {})) +} + +export 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() }, + } +} + +export 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. Each `call` takes the next +// queued answer; an `Error` in the queue is a rejection, and an empty queue answers `{}`. +export function scene({ hidden = false, answers = [] } = {}) { + 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__, + } + let queued = [...answers] + globalThis.document = doc + globalThis.setInterval = timers.setInterval + globalThis.clearInterval = timers.clearInterval + globalThis.__flybot__ = { + call: (endpoint, payload) => { + calls.push([endpoint, payload]) + const answer = queued.length > 0 ? queued.shift() : {} + return answer instanceof Error ? Promise.reject(answer) : Promise.resolve(answer) + }, + canRetry: () => true, + } + return { + doc, timers, calls, app, + restore() { + globalThis.document = saved.document + globalThis.setInterval = saved.setInterval + globalThis.clearInterval = saved.clearInterval + globalThis.__flybot__ = saved.flybot + }, + } +} + +export const settle = () => new Promise(resolve => setTimeout(resolve, 0)) +export const unmount = (cleanups) => { for (const off of cleanups.reverse()) off() } + +// 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 observe. +export function mount(app, name, props) { + live.inst = { hooks: {}, effects: [], dirty: false } + live.idx = 0 + const out = app[name](props) + const cleanups = [] + for (const [, fn] of live.inst.effects) { + const off = fn() + if (typeof off === 'function') cleanups.push(off) + } + return { out, cleanups } +} + +// A state update asks React for a new render; this reuses the hook table and runs no effect again. +export function rerender(app, name, props) { + live.idx = 0 + return app[name](props) +} + +// Every element in a drawn tree, depth first, for counting what a state shows. +export function nodes(node, out = []) { + if (node == null || node === false || node === true) return out + if (typeof node === 'string' || typeof node === 'number') return out + if (Array.isArray(node)) { for (const child of node) nodes(child, out); return out } + if (typeof node !== 'object') return out + out.push(node) + nodes(node.children ?? [], out) + return out +} + +export const byMark = (tree, mark) => nodes(tree).filter(node => node?.props?.['data-flybot'] === mark) +export const textOf = node => (Array.isArray(node?.children) ? node.children : [node?.children]).join('') diff --git a/runtime/flybot/plugins/social/test/friend-auto-read-error.test.js b/runtime/flybot/plugins/social/test/friend-auto-read-error.test.js new file mode 100644 index 000000000..28641f53e --- /dev/null +++ b/runtime/flybot/plugins/social/test/friend-auto-read-error.test.js @@ -0,0 +1,74 @@ +// A friend Bot's settings card reads the pair's Auto-send setting once, on mount, through +// `social/settings`. Its rejection branch was an empty function, so a read that failed left the +// checkbox at its initial `false` — drawn exactly like a setting that is off — while the switch stayed +// live: the person then reads "my Bots' replies go out without asking" as a state they chose. The +// failure is the card's answer while it lasts (the friends list and the paused card draw one the same +// way), one quiet status row, and the switch is not offered until the value is known, because a value +// nobody read is not a value to flip. A remount (reopen the card) retries; no button, no new copy. +import assert from 'node:assert/strict' +import { test } from 'node:test' +import { byMark, mount, nodes, rerender, scene, settle, textOf, unmount } from './client-harness.mjs' + +const friendBot = { id: 'f1', name: 'Eve', remote: { home: '@eve.home', handle: '@eve.bot', homeName: 'Eve' } } +const settingsCard = app => mount(app, 'FriendChatSettings', { bot: friendBot }) +const cardTree = (app, out) => rerender(app, 'FriendChatSettings', { bot: friendBot }, out) +const switchOf = tree => nodes(byMark(tree, 'friend-auto-send')[0] ?? {}).find(node => node?.type === 'input') + +test('a settings read that fails is drawn as a failure, not as a setting', async () => { + const s = scene({ answers: [new Error('offline')] }) + try { + const { cleanups, out } = settingsCard(s.app) + await settle() + const tree = cardTree(s.app, out) + assert.equal(byMark(tree, 'friend-auto-read-error').length, 1, 'the failed read is the card’s answer') + unmount(cleanups) + } finally { s.restore() } +}) + +test('a NETWORK failure names the reason the person can act on', async () => { + const s = scene({ answers: [Object.assign(new Error('offline'), { code: 'NETWORK' })] }) + try { + const { cleanups, out } = settingsCard(s.app) + await settle() + const tree = cardTree(s.app, out) + assert.equal(textOf(byMark(tree, 'friend-auto-read-error')[0]), 'Could not reach FlyBot. Check that it is still running.') + unmount(cleanups) + } finally { s.restore() } +}) + +test('a setting nobody read is not offered as a switch to flip', async () => { + const s = scene({ answers: [new Error('offline')] }) + try { + const { cleanups, out } = settingsCard(s.app) + await settle() + const tree = cardTree(s.app, out) + assert.equal(switchOf(tree).props.disabled, true, 'an unknown setting is not a checkbox') + assert.equal(switchOf(tree).props.checked, false, 'and it claims nothing about the value') + unmount(cleanups) + } finally { s.restore() } +}) + +test('a read that says the setting is on still draws a checked, live switch', async () => { + const s = scene({ answers: [{ autoAccept: { '@eve.home': true } }] }) + try { + const { cleanups, out } = settingsCard(s.app) + await settle() + const tree = cardTree(s.app, out) + assert.equal(switchOf(tree).props.checked, true, 'on is drawn as on') + assert.equal(switchOf(tree).props.disabled, false, 'a value that was read is a switch to flip') + assert.equal(byMark(tree, 'friend-auto-read-error').length, 0, 'a read that answered draws no failure') + unmount(cleanups) + } finally { s.restore() } +}) + +test('a read that says the setting is off still draws an unchecked switch', async () => { + const s = scene({ answers: [{ autoAccept: { '@eve.home': false } }] }) + try { + const { cleanups, out } = settingsCard(s.app) + await settle() + const tree = cardTree(s.app, out) + assert.equal(switchOf(tree).props.checked, false, 'off is drawn as off') + assert.equal(switchOf(tree).props.disabled, false, 'a value that was read is a switch to flip') + unmount(cleanups) + } finally { s.restore() } +}) diff --git a/runtime/flybot/plugins/social/test/paused-chat-read-error.test.js b/runtime/flybot/plugins/social/test/paused-chat-read-error.test.js new file mode 100644 index 000000000..7a2d39f12 --- /dev/null +++ b/runtime/flybot/plugins/social/test/paused-chat-read-error.test.js @@ -0,0 +1,83 @@ +// A friend chat Bot Social paused (#404) draws a quiet card from a 5 s `social/paused` read. Its +// rejection branch was an empty function, so a read that failed printed nothing — drawn exactly like +// "this chat is not paused": a card on screen disappeared when the read failed, and one read before a +// failure stayed there quoting an answer that no longer succeeds. The failure is the card's answer +// while it lasts (the friends list draws a failed read the same way), and the 5 s poll is the retry: +// still quiet, still no buttons (owner 2026-10-19). +import assert from 'node:assert/strict' +import { test } from 'node:test' +import { byMark, mount, rerender, scene, settle, textOf, unmount } from './client-harness.mjs' + +const friendBot = { id: 'f1', name: 'Pal', remote: { handle: '@pal.home' } } +const pausedAnswer = { paused: { reason: 'loop detected' } } +const pausedChat = app => mount(app, 'PausedChat', { bot: friendBot }) +const cardTree = (app, out) => rerender(app, 'PausedChat', { bot: friendBot }, out) + +test('a paused-chat read that fails writes one quiet error row', async () => { + const s = scene({ answers: [new Error('offline')] }) + try { + const { cleanups, out } = pausedChat(s.app) + await settle() + const tree = cardTree(s.app, out) + assert.equal(byMark(tree, 'social-paused-error').length, 1, 'the failed read is the card’s answer') + assert.equal(byMark(tree, 'chat-paused').length, 0, 'a failed read is not a paused chat') + unmount(cleanups) + } finally { s.restore() } +}) + +test('a NETWORK failure names the reason the person can act on', async () => { + const s = scene({ answers: [Object.assign(new Error('offline'), { code: 'NETWORK' })] }) + try { + const { cleanups, out } = pausedChat(s.app) + await settle() + const tree = cardTree(s.app, out) + assert.equal(textOf(byMark(tree, 'social-paused-error')[0]), 'Could not reach FlyBot. Check that it is still running.') + unmount(cleanups) + } finally { s.restore() } +}) + +test('a card read before the failure is dropped when the next read fails', async () => { + const s = scene({ answers: [pausedAnswer, new Error('offline')] }) + try { + const { cleanups, out } = pausedChat(s.app) + await settle() + let tree = cardTree(s.app, out) + assert.equal(byMark(tree, 'chat-paused').length, 1, 'the first answer draws the card') + s.timers.tick() + await settle() + tree = cardTree(s.app, out) + assert.equal(byMark(tree, 'chat-paused').length, 0, 'a stale card is not an answer') + assert.equal(byMark(tree, 'social-paused-error').length, 1, 'the failure replaces it') + unmount(cleanups) + } finally { s.restore() } +}) + +test('the next read that succeeds clears the error and draws the card again', async () => { + const s = scene({ answers: [new Error('offline'), pausedAnswer] }) + try { + const { cleanups, out } = pausedChat(s.app) + await settle() + let tree = cardTree(s.app, out) + assert.equal(byMark(tree, 'social-paused-error').length, 1) + s.timers.tick() + await settle() + tree = cardTree(s.app, out) + assert.equal(byMark(tree, 'chat-paused').length, 1, 'a later success draws the card') + assert.equal(byMark(tree, 'social-paused-error').length, 0, 'and drops the error') + unmount(cleanups) + } finally { s.restore() } +}) + +test('the failed read draws no button, input or form', async () => { + const s = scene({ answers: [new Error('offline')] }) + try { + const { cleanups, out } = pausedChat(s.app) + await settle() + const tree = cardTree(s.app, out) + const interactive = byMark(tree, 'social-paused-error') + .flatMap(node => node.children ?? []) + .filter(child => child?.type === 'button' || child?.type === 'input' || child?.type === 'form') + assert.deepEqual(interactive, [], 'the quiet notice is all this state draws (owner 2026-10-19)') + unmount(cleanups) + } finally { s.restore() } +}) diff --git a/runtime/flybot/plugins/social/test/poll-visibility.test.js b/runtime/flybot/plugins/social/test/poll-visibility.test.js new file mode 100644 index 000000000..704d71f27 --- /dev/null +++ b/runtime/flybot/plugins/social/test/poll-visibility.test.js @@ -0,0 +1,183 @@ +// A poll exists to refresh what the person can see, so a tab nobody is looking at should make no read +// and hold no timer. The chat approval dock and the friends/Bot Social panel (share requests, accept +// notices) each ran a bare `setInterval` — the dock skipped the read inside `load`, the panel skipped +// it inside a tick — so a hidden tab kept a timer alive, and the panel had no `visibilitychange` +// listener at all: coming back waited out the rest of the period before its first read. +// +// `pollWhileVisible` is the one rule both now use: no timer while hidden, one read as the tab returns, +// and the cadence restarting from that read. React is replaced by the tiny slot renderer the other +// client tests use, and `document` / `setInterval` are recorded instead of waited on (no jsdom). +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import { test } from 'node:test' + +const live = { inst: null, idx: 0 } +const reactStub = { + createElement: (type, props, ...children) => ({ type, props: props ?? {}, children: children.flat(Infinity) }), + Fragment: 'F', + Component: class {}, + useState(init) { + const inst = live.inst + const i = live.idx++ + if (!(i in inst.hooks)) inst.hooks[i] = { value: 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 = false } = {}) { + 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({}) }, + canRetry: () => true, + } + return { + doc, timers, calls, app, + reads: endpoint => calls.filter(([name]) => name === endpoint).length, + restore() { + globalThis.document = saved.document + globalThis.setInterval = saved.setInterval + globalThis.clearInterval = saved.clearInterval + globalThis.__flybot__ = saved.flybot + }, + } +} +const unmount = cleanups => { for (const off of cleanups.reverse()) off() } + +function mount(app, name, props) { + live.inst = { hooks: {}, effects: [], dirty: false } + live.idx = 0 + app[name](props) + const cleanups = [] + for (const [, fn] of live.inst.effects) { + const off = fn() + if (typeof off === 'function') cleanups.push(off) + } + return { cleanups } +} + +const roster = { bots: [], byId: {}, remoteBots: [] } +const openRoom = () => ({ id: 'r1', origin: 'face-to-face', participants: [] }) + +test('the chat approval dock stops while hidden and reads once when the tab returns', () => { + const s = scene({ hidden: true }) + try { + const { cleanups } = mount(s.app, 'ChatApprovalDock', { + sessionId: 's1', roster, room: openRoom(), bot: { id: 'b1', name: 'Chief' }, actions: {}, + }) + assert.equal(s.reads('social/status'), 0, `a hidden dock made ${s.reads('social/status')} read(s)`) + assert.deepEqual(s.timers.periods(), [], 'a hidden dock holds no poll timer') + s.doc.hidden = false + s.doc.emit('visibilitychange') + assert.equal(s.reads('social/status'), 1, `coming back made ${s.reads('social/status')} read(s), not one`) + assert.deepEqual(s.timers.periods(), [5000], 'the 5 s cadence restarts from that read') + s.timers.tick() + assert.equal(s.reads('social/status'), 2, 'and one period later reads again, once') + s.doc.hidden = true + s.doc.emit('visibilitychange') + s.timers.tick() + assert.equal(s.reads('social/status'), 2, 'going hidden again stops it') + unmount(cleanups) + } finally { s.restore() } +}) + +// The panel's own one-shot mount read of `social/status` (which Bots are mine, my handle) is not the +// poll; the cases below count only the poll's reads, which is what a hidden tab must not make. +test('the friends and requests panel stops while hidden and reads once when the tab returns', () => { + const s = scene({ hidden: true }) + try { + const { cleanups } = mount(s.app, 'FriendsBots', { remoteChats: [], actions: {}, roster }) + // Whatever this panel reads once for itself is not the poll: the poll is the only thing that could + // keep repeating, so it is counted relative to the mount and must add nothing while hidden. + const mountReads = s.reads('social/status') + assert.deepEqual(s.timers.periods(), [], 'a hidden panel holds no poll timer') + s.doc.emit('visibilitychange') + assert.equal(s.reads('social/status'), mountReads, 'a hidden tab reads nothing when a show event fires') + s.doc.hidden = false + s.doc.emit('visibilitychange') + assert.equal(s.reads('social/status'), mountReads + 1, 'coming back makes one poll read at once') + assert.deepEqual(s.timers.periods(), [15000], 'the 15 s cadence restarts from that read') + s.timers.tick() + assert.equal(s.reads('social/status'), mountReads + 2, 'and one period later reads again, once') + s.doc.hidden = true + s.doc.emit('visibilitychange') + s.timers.tick() + assert.equal(s.reads('social/status'), mountReads + 2, 'going hidden again stops it') + } finally { s.restore() } +}) + +test('unmounting a polled component removes its visibility listener', () => { + const s = scene({ hidden: false }) + try { + const { cleanups } = mount(s.app, 'ChatApprovalDock', { + sessionId: 's1', roster, room: openRoom(), bot: { id: 'b1', name: 'Chief' }, actions: {}, + }) + assert.equal(s.doc.listening('visibilitychange'), 1, 'the mounted dock listens once') + unmount(cleanups) + assert.equal(s.doc.listening('visibilitychange'), 0, 'unmount removes the listener') + assert.deepEqual(s.timers.periods(), [], 'and its timer') + } finally { s.restore() } +})