diff --git a/changelog.d/3371.fixed.md b/changelog.d/3371.fixed.md new file mode 100644 index 000000000..a2e00fa76 --- /dev/null +++ b/changelog.d/3371.fixed.md @@ -0,0 +1 @@ +The Tree panel's reorganization notice no longer asks the host for its report from a window nobody is looking at: the card read `tree/reorg` every 30 s for as long as it was mounted, so a minimised app or a tab behind another kept the host busy on that read, and coming back could show a report up to 30 s old. The read now follows the page — a hidden window arms no timer, returning clears and re-arms it and then reads once at once, and unmounting leaves neither the timer nor the listener behind ([#3371](https://github.com/ThinkFlowLab/FlyBot/issues/3371)). diff --git a/docs/subsystems/tree.md b/docs/subsystems/tree.md index fdda29dba..3772280eb 100644 --- a/docs/subsystems/tree.md +++ b/docs/subsystems/tree.md @@ -121,6 +121,7 @@ Both sidebar entries — the `flybot.sidebar.structure` entry ds-bot draws its B - `client.js` keeps one `rosterFeed(flybot, { interval })`: the first subscriber starts the poll, a later subscriber joins it and is handed the current list without a read of its own, a read already in flight sets `again` instead of stacking up behind the timer, and the last subscriber to leave clears it. `apply()` builds one feed and passes it to `registerStructure` and `makeArchivedSection`; called with no feed, each makes its own (tests and other callers keep working). - A field change that matters to either consumer (`archived`, `parent`, `treeRole`, `retired`, `idle`) and `bot.removed` call `refresh()`, so a removal is still immediate instead of waiting for the next tick. +- The reorganization notice's `tree/reorg` read follows the page: `pollWhileVisible(fn, ms)` arms no interval at all while the document is hidden, clears and re-arms it on `visibilitychange` back to visible and then reads once at once, and its cleanup drops both the timer and the listener — a window nobody is looking at does not ask the host every 30 s, and coming back is not up to one period stale (#3371). - Tests: `plugins/tree/test/tree.test.js`, `#816: one roster read per tick…` (one read per tick for two subscribers, the timer stops with the last one, and mounting the archived section inside `apply()` adds no read) and `#816: the archived list is ordered above the reorganization notice`. ### Discarded promise `.catch` (#213) diff --git a/plugins/tree/client.js b/plugins/tree/client.js index bf2cdbcbe..57bb446ac 100644 --- a/plugins/tree/client.js +++ b/plugins/tree/client.js @@ -289,6 +289,27 @@ window.__ModuleLoader__.load({ } const REFRESH_MS = 10000 + // A poll of the host follows the page: a hidden window keeps no interval at all (not one whose + // tick would be wasted), and coming back clears and re-arms it before reading once at once, so + // the read is neither in the background nor up to one period stale. Cleanup drops both. + function pollWhileVisible(fn, ms) { + const doc = globalThis.document + const hidden = () => doc?.hidden === true || doc?.visibilityState === 'hidden' + let timer + const stop = () => { if (timer !== undefined) { clearInterval(timer); timer = undefined } } + const arm = () => { stop(); if (hidden()) return; timer = setInterval(fn, ms) } + const onVisibility = () => { + if (hidden()) { stop(); return } + arm() + fn() + } + doc?.addEventListener?.('visibilitychange', onVisibility) + arm() + return () => { + stop() + doc?.removeEventListener?.('visibilitychange', onVisibility) + } + } // Same as organize.js ARCHIVE_NAME_RE (#452): mis-renamed archived Bots stay out of the list. const ARCHIVE_NAME_RE = /^(?:归档|Archive)[-—–__\s]+/u // 'flybot.sidebar.section' is a FlyBot registry slot (ds-bot renders it), not a DSH @@ -467,8 +488,8 @@ window.__ModuleLoader__.load({ load() let off try { off = flybot.fields?.on?.('change', c => { if (c && c.key === 'reorg') load() }) } catch { /* no change feed */ } - const timer = setInterval(load, REFRESH_MS * 3) - return () => { clearInterval(timer); try { off?.() } catch { /* already gone */ } } + const stop = pollWhileVisible(load, REFRESH_MS * 3) + return () => { stop(); try { off?.() } catch { /* already gone */ } } }, [load]) const run = noticeRun(overview) if (!run) return null diff --git a/plugins/tree/test/hidden-poll.test.js b/plugins/tree/test/hidden-poll.test.js new file mode 100644 index 000000000..fb815d348 --- /dev/null +++ b/plugins/tree/test/hidden-poll.test.js @@ -0,0 +1,131 @@ +// The reorganization notice reads `tree/reorg` from the host on a timer (every 30 s). A window +// nobody is looking at must not keep asking, and coming back must show the result at once rather +// than up to 30 s later — the same rule the timeline and workflow panels follow. +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import { test } from 'node:test' + +const live = { inst: null, idx: 0 } +const react = { + createElement: (type, props, ...children) => ({ type, props: props ?? {}, children: children.flat(Infinity) }), + useState(init) { + const { inst } = live + 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) => { + const value = typeof next === 'function' ? next(slot.value) : next + if (!Object.is(value, slot.value)) { slot.value = value; inst.root.schedule() } + }] + }, + useEffect(fn, deps) { + const { inst } = live + const i = live.idx++ + const prev = inst.hooks[i] + const changed = !prev || !deps || !prev.deps || deps.length !== prev.deps.length || deps.some((dep, k) => !Object.is(dep, prev.deps[k])) + if (!prev) inst.hooks[i] = { deps } + if (changed) { inst.hooks[i].deps = deps; inst.root.pending.push({ slot: inst.hooks[i], fn }) } + }, + useCallback(fn, deps) { + const { inst } = live + const i = live.idx++ + const prev = inst.hooks[i] + const changed = !prev || !deps || !prev.deps || deps.length !== prev.deps.length || deps.some((dep, k) => !Object.is(dep, prev.deps[k])) + if (changed) inst.hooks[i] = { fn, deps } + return inst.hooks[i].fn + }, +} + +function mount(Component, props = {}) { + const root = { instances: new Map(), pending: [], rendering: false, dirty: false, tree: undefined } + const expand = (node, path) => { + if (node === null || node === undefined || typeof node === 'boolean') return undefined + if (typeof node !== 'object') return String(node) + if (Array.isArray(node)) return node.map((child, i) => expand(child, `${path}.${i}`)) + if (typeof node.type === 'function') { + let inst = root.instances.get(path) + if (!inst) { inst = { hooks: [], root }; root.instances.set(path, inst) } + inst.used = true + live.inst = inst + live.idx = 0 + return expand(node.type({ ...node.props, children: node.children }), `${path}/c`) + } + return { type: node.type, props: node.props, children: node.children.map((child, i) => expand(child, `${path}.${i}`)).flat(Infinity).filter(child => child !== undefined) } + } + const render = () => { + root.rendering = true + for (const inst of root.instances.values()) inst.used = false + root.tree = expand({ type: Component, props, children: [] }, 'r') + const run = root.pending.splice(0) + for (const { slot, fn } of run) { slot.cleanup?.(); const out = fn(); slot.cleanup = typeof out === 'function' ? out : undefined } + root.rendering = false + if (root.dirty || root.pending.length) { root.dirty = false; render() } + } + root.schedule = () => { if (root.rendering) root.dirty = true; else render() } + render() + return { + get tree() { return root.tree }, + unmount() { for (const inst of root.instances.values()) for (const slot of inst.hooks) slot?.cleanup?.(); root.instances.clear() }, + } +} + +const flush = async () => { for (let i = 0; i < 8; i++) await Promise.resolve() } + +const loadClient = () => { + let mod + globalThis.window = { __ModuleLoader__: { load: ({ factory }) => { mod = factory(() => react) } } } + new Function(readFileSync(new URL('../client.js', import.meta.url), 'utf8'))() + return mod +} + +const run = { id: 'run-1', at: Date.now() - 60_000, trigger: 'full', summary: ['Moved 3 Bots under FlyBot Lead'], actions: [] } + +test('a hidden window does not read tree/reorg, and coming back reads it at once', async () => { + const mod = loadClient() + const reads = [] + const flybot = { + call(name) { if (name === 'tree/reorg') { reads.push(name); return Promise.resolve({ runs: [run], dismissed: null }) } return Promise.resolve({ ok: true }) }, + fields: { on: () => () => {} }, + } + const timers = [] + const realSet = globalThis.setInterval + const realClear = globalThis.clearInterval + globalThis.setInterval = (fn, ms) => { const id = timers.length + 1; timers.push({ id, fn, ms }); return id } + globalThis.clearInterval = (id) => { const at = timers.findIndex(timer => timer.id === id); if (at >= 0) timers.splice(at, 1) } + const realDoc = globalThis.document + const listeners = [] + const doc = { + hidden: true, + visibilityState: 'hidden', + getElementById: () => null, + createElement: () => ({ id: '', textContent: '' }), + head: { appendChild() {} }, + addEventListener(name, fn) { if (name === 'visibilitychange') listeners.push(fn) }, + removeEventListener(name, fn) { const at = listeners.indexOf(fn); if (name === 'visibilitychange' && at >= 0) listeners.splice(at, 1) }, + } + globalThis.document = doc + const Notice = mod.makeReorgNotice(flybot) + let view + try { + view = mount(Notice, { roster: { bots: [] }, actions: {}, call: flybot.call }) + await flush() + assert.equal(reads.length, 1, 'the first paint reads tree/reorg once') + for (const timer of timers.slice()) timer.fn() + await flush() + assert.equal(reads.length, 1, 'a hidden window does not read tree/reorg again') + doc.hidden = false + doc.visibilityState = 'visible' + for (const fn of listeners.slice()) fn() + await flush() + assert.equal(reads.length, 2, 'coming back reads tree/reorg at once') + view.unmount() + view = undefined + assert.equal(timers.length, 0, 'unmount clears every interval') + assert.equal(listeners.length, 0, 'unmount removes the visibility listener') + } finally { + if (view) view.unmount() + globalThis.document = realDoc + globalThis.setInterval = realSet + globalThis.clearInterval = realClear + } +})