Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 0 additions & 6 deletions docs/upstream/flybot-files.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
44 changes: 43 additions & 1 deletion docs/upstream/migration-manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -1707,7 +1707,7 @@
"scripts/logo.mjs",
"scripts/self-test-catalog.mjs"
],
"file_count": 46
"file_count": 45
},
"bot-social": {
"destination": "services/bot-social",
Expand Down Expand Up @@ -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": {
Expand Down
99 changes: 62 additions & 37 deletions runtime/flybot/plugins/social/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = `
Expand Down Expand Up @@ -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)
Expand All @@ -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) => {
Expand Down Expand Up @@ -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:')
Expand Down Expand Up @@ -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) => {
Expand Down Expand Up @@ -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}`),
Expand Down Expand Up @@ -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.`))
Expand Down
144 changes: 144 additions & 0 deletions runtime/flybot/plugins/social/test/client-harness.mjs
Original file line number Diff line number Diff line change
@@ -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('')
Loading
Loading