Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

2.3 KB
Raw Blame
import { subscribeDeskChanged, subscribeDeviceKeysChanged, subscribeZooChanged } from './bus.js'
import { relaySwarmChanges } from './swarmClientPushes.js'

/**
 * The account documents a WEB socket hears about — the desk and the zoo — forwarded to the clients
 * that have no daemon to relay them: the phone and the browser. The same invalidations every adapter
 * socket hears (lib/adapterAccountPushes.ts), as plain frames: one carrying the revision, the document
 * itself re-read over REST, so a burst of edits collapses into one GET.
 *
 *  - `desk_changed` — the account's tabs.
 *  - `zoo_changed`  — the account's daemons and eggs (routes/zoo.ts), its own frame: a desk change
 *    never re-fetches the zoo and the other way round.
 *  - `device_keys_changed` — the account's device key log grew (lib/deviceKeyLog.ts): the app re-reads
 *    from its own head and trusts the machines the log adds.
 *  - `swarm_changed` — a Swarm the account is in changed (lib/swarmClientPushes.ts): the app
 *    reads it again instead of every 15 s. A phone hears it once per
 *    machine socket; the app reads once per burst.
 *
 * ⚠️ A phone holds one of these sockets PER MACHINE, so it hears each change once per machine. The
 * revision is what makes that harmless: an app already at that revision fetches nothing.
 *
 * `zoo` is the server's daemons switch (lib/daemonsSwitch.ts): off, only the desk is listened on.
 *
 * Resolves to the unsubscribe for all of them.
 */
export async function relayWebDocumentPushes(userId: string, send: (frame: unknown) => unknown, opts: { zoo: boolean }): Promise<() => void> {
  const unsubs: Array<() => void> = []
  const stop = (): void => { for (const unsub of unsubs.splice(0)) unsub() }
  try {
    unsubs.push(await subscribeDeskChanged(userId, (msg) => { send({ type: 'desk_changed', payload: { revision: msg.revision } }) }))
    if (opts.zoo) unsubs.push(await subscribeZooChanged(userId, (msg) => { send({ type: 'zoo_changed', payload: { revision: msg.revision } }) }))
    unsubs.push(await subscribeDeviceKeysChanged(userId, (msg) => { send({ type: 'device_keys_changed', payload: { seq: msg.seq, hash: msg.hash } }) }))
    unsubs.push(await relaySwarmChanges(userId, send))
  } catch (err) {
    stop()
    throw err
  }
  return stop
}