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.

14.9 KB
Raw Blame
import { describe, expect, it } from 'vitest'
import * as store from '../parts/index.js'
import type { Part, SwarmParts } from '../parts/index.js'
import { readerView } from './views.js'
import { changesFor } from './changes.js'
import { NOW, outsider, owner, peer, richSwarm } from './fixture.test-support.js'
import type { Actor } from '../model.js'

const R = 9_000
const LATER = NOW + 5_000
const agentActor = (agentId: string): Actor => ({ kind: 'agent', agentId, machineOwnerId: `${owner.userId}-machine` })

function scene(closed = false) {
  const s = richSwarm()
  s.contribute('mac', 'swarm')
  // peer's Buddy chat, or with no kind their Chat with PM from before Buddies replaced it (projects.ts isClosedPmChat).
  const privateId = s.group('Peer and PM')
  s.edit(state => {
    const generation = state.people.find(p => p.id === peer.userId)!.generation
    Object.assign(state.conversations.find(c => c.id === privateId)!, { ...closed ? {} : { kind: 'buddy' }, audience: { people: [{ id: peer.userId, generation }] } })
  })
  return { s, privateId, parts: store.split(s.state, { tabId: 'tab', version: R, now: NOW }) }
}
type Kind = 'members' | 'agents' | 'groups' | 'machines' | 'starts' | 'progress'
/** A later write of one part: its version moves and `change` applies to the stored part (data, tombstone or dormant flag). */
function write(parts: SwarmParts, kind: Kind, key: string, change: (part: Part) => void): Part {
  const part = (parts[kind] as Part[]).find(p => p.key === key)!
  part.version += 1
  part.changedAt = LATER
  change(part)
  return part
}
/** What the reader receives: its view of the active (live) parts, then the changed parts run through its read check. */
function receive(parts: SwarmParts, changed: Part[], actor: Actor, cursor?: number) {
  const active = { ...parts, ...Object.fromEntries((['members', 'agents', 'groups', 'machines', 'starts', 'progress'] as Kind[])
    .map(kind => [kind, (parts[kind] as Part[]).filter(p => !p.deleted && !p.dormant)])) } as SwarmParts
  return changesFor(readerView(active, actor, LATER, { teamMachines: [] }), changed, actor, undefined, cursor)
}
const keys = (list: Array<{ key: string }>) => list.map(p => p.key)

describe('changes since a cursor (design 4.4)', () => {
  it('sends nothing but derived when nothing changed, and the head only when it changed', () => {
    const { parts } = scene()
    expect(receive(parts, [], peer)).toMatchObject({ head: null, members: [], agents: [], groups: [], machines: [], starts: [], progress: [] })
    const head = { ...parts.head, version: R + 1, changedAt: LATER }
    parts.head = head
    expect(receive(parts, [head], peer).head).toMatchObject({ key: 'head', version: R + 1 })
  })

  // Tasks #3593, #4419: each task keeps its own status line, but readers get the card in the head's project; a change poll that
  // sent only the task would leave Desktop and web on the old card until something else moved the head. The head goes only when
  // a changed task's line moved since the reader's cursor: a task changes with every message, and the head is large.
  it('sends the head with a task whose status line moved since the cursor, so a live reader sees the card move', () => {
    const { s, parts } = scene()
    const line = { text: '#1 "Web": working. Waits on: nothing. Owner: Ada.', since: NOW }
    const changed = [write(parts, 'groups', s.web, p => { (p.data as { statusLine?: object }).statusLine = line })]
    const received = receive(parts, changed, owner, NOW - 1_000)
    expect(received.head).not.toBeNull()
    expect(received.head!.data.projects![0]!.status!.text).toContain('#1 "Web": working.')
  })

  it('sends the head with a task whose line left the card since the cursor', () => {
    const { s, parts } = scene()
    const changed = [write(parts, 'groups', s.web, p => { (p.data as { statusLine?: object }).statusLine = { text: '', since: NOW } })]
    expect(receive(parts, changed, owner, NOW - 1_000).head).not.toBeNull()
  })

  it('leaves the head out for a task change that left its line as the reader already has it', () => {
    const { s, parts } = scene()
    // The line moved long before the reader's cursor; the task changed since for another reason (a message, a title).
    const line = { text: '#1 "Web": working. Waits on: nothing. Owner: Ada.', since: NOW - 3_600_000 }
    const changed = [write(parts, 'groups', s.web, p => { (p.data as { statusLine?: object; title: string }).statusLine = line; (p.data as { title: string }).title = 'Web 3' })]
    expect(receive(parts, changed, owner, NOW - 1_000).head).toBeNull()
  })

  it('sends a changed group whole to its readers and nothing to anyone else', () => {
    const { s, parts } = scene()
    const changed = [write(parts, 'groups', s.web, p => { (p.data as { title: string }).title = 'Web 2' }),
      write(parts, 'groups', s.secretGroup, p => { (p.data as { title: string }).title = 'Secret 2' })]
    const peerGroups = receive(parts, changed, peer).groups
    expect(peerGroups).toEqual([expect.objectContaining({ key: s.web, version: R + 1, data: expect.objectContaining({ title: 'Web 2', messageSeq: R }) })])
    expect(keys(receive(parts, changed, owner).groups)).toEqual([s.web, s.secretGroup])
  })

  it('sends a Buddy chat\'s change, removal and dormant stub only to its owner, never the Lead; a closed Chat with PM\'s to nobody', () => {
    const { s, privateId } = scene()
    for (const change of [(p: Part) => { (p.data as { title: string }).title = 'x' }, (p: Part) => { p.deleted = true }, (p: Part) => { p.dormant = true }]) {
      const { parts: fresh } = scene()
      const changed = [write(fresh, 'groups', privateId, change)]
      expect(keys(receive(fresh, changed, peer).groups)).toEqual([privateId])
      for (const reader of [agentActor(s.lead), owner, agentActor(s.worker)]) expect(receive(fresh, changed, reader).groups).toEqual([])
      const { parts: closed } = scene(true)
      const closedChange = [write(closed, 'groups', privateId, change)]
      for (const reader of [peer, agentActor(s.lead), owner]) expect(receive(closed, closedChange, reader).groups).toEqual([])
    }
  })

  it('sends a removed or dormant group as a one-line stub, never its last data', () => {
    const { s, parts } = scene()
    const changed = [write(parts, 'groups', s.done, p => { p.deleted = true }), write(parts, 'groups', s.web, p => { p.dormant = true })]
    expect(receive(parts, changed, peer).groups).toEqual([
      { key: s.done, version: R + 1, changedAt: LATER, deleted: true },
      { key: s.web, version: R + 1, changedAt: LATER, dormant: true }])
  })

  it('sends an agent\'s removal only to readers of its project, and a member\'s removal to everyone', () => {
    const { s, parts } = scene()
    const secretAgent = s.add('secret-harness', s.secretGroup)
    const fresh = store.split(s.state, { tabId: 'tab', version: R, now: NOW })
    const changed = [write(fresh, 'agents', secretAgent, p => { p.deleted = true }), write(fresh, 'agents', s.worker, p => { p.deleted = true }),
      write(fresh, 'members', outsider.userId, p => { p.deleted = true })]
    expect(receive(fresh, changed, peer)).toMatchObject({ agents: [{ key: s.worker, deleted: true }], members: [{ key: outsider.userId, deleted: true }] })
    expect(keys(receive(fresh, changed, owner).agents)).toEqual([secretAgent, s.worker])
    void parts
  })

  it('sends a machine whose contribution ended as a removal', () => {
    const { parts } = scene()
    const changed = [write(parts, 'machines', 'mac', p => { (p.data as { contribution: unknown }).contribution = null })]
    expect(receive(parts, changed, peer).machines).toEqual([{ key: 'mac', version: R + 1, changedAt: LATER, deleted: true }])
  })

  it('sends a start\'s removal only to readers of its group', () => {
    const { s } = scene()
    s.edit(state => {
      state.starts = [s.web, s.secretGroup].map(conversationId => ({ id: `start-${conversationId}`, creationId: 'c', actorKey: 'person:owner',
        contributorId: owner.userId, membershipGeneration: 'tab', machineOwnerId: owner.userId, hostGrant: null, harnessId: null, dispatched: false, error: null,
        request: { conversationId, machineId: 'mac', engine: 'codex', name: 'Builder', cwd: '/repo', worktree: false,
          requirements: { memoryBytes: 0, diskBytes: 0, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false } } }))
    })
    const fresh = store.split(s.state, { tabId: 'tab', version: R, now: NOW })
    const changed = [write(fresh, 'starts', `start-${s.web}`, p => { p.deleted = true }), write(fresh, 'starts', `start-${s.secretGroup}`, p => { p.deleted = true })]
    expect(keys(receive(fresh, changed, peer).starts)).toEqual([`start-${s.web}`])
    expect(keys(receive(fresh, changed, owner).starts)).toEqual([`start-${s.web}`, `start-${s.secretGroup}`])
    // A Buddy reads no starts, not even a removal's id, though it reads their group (security review 2 of #2258).
    s.edit(state => {
      const generation = state.people.find(p => p.id === peer.userId)!.generation, worker = state.agents.find(a => a.id === s.worker)!
      state.agents.push({ ...worker, id: 'buddy', harnessId: 'buddy-harness', contributorId: peer.userId, membershipGeneration: generation,
        name: 'Buddy', buddyOf: { personId: peer.userId, generation } })
    })
    const withBuddy = store.split(s.state, { tabId: 'tab', version: R, now: NOW })
    const removed = [write(withBuddy, 'starts', `start-${s.web}`, p => { p.deleted = true })]
    const buddy: Actor = { kind: 'agent', agentId: 'buddy', machineOwnerId: `${owner.userId}-machine` }
    expect(keys(receive(withBuddy, [write(withBuddy, 'groups', s.web, () => {})], buddy).groups)).toEqual([s.web])
    expect(receive(withBuddy, removed, buddy).starts).toEqual([])
    expect(keys(receive(withBuddy, removed, peer).starts)).toEqual([`start-${s.web}`])
  })

  it('sends changed project progress only to readers of the project', () => {
    const { s } = scene()
    s.edit(state => { for (const p of state.projects!) p.progress = { since: 1, summarizedFloor: 0, summarized: {}, requestedFloor: 0, requested: {} } })
    const fresh = store.split(s.state, { tabId: 'tab', version: R, now: NOW })
    const changed = [write(fresh, 'progress', 'lead', () => {}), write(fresh, 'progress', s.secret, () => {})]
    expect(receive(fresh, changed, peer).progress).toEqual([{ key: 'lead', version: R + 1, changedAt: LATER,
      data: { since: 1, summarizedFloor: 0, summarized: {}, requestedFloor: 0, requested: {}, requestedAt: null } }])
  })

  it('hands a reader only the required machines they see, whole and in changes', () => {
    const { s } = scene()
    // Only an agent of the private project runs on 'secret-mac', so the peer does not see that machine.
    s.add('secret-harness', s.secretGroup, false, owner, 'secret-mac')
    s.run({ type: 'work.define', conversationId: s.done, task: { goal: 'Check the device', changes: 'None', constraints: 'None', owns: ['devices'],
      requires: { machines: ['secret-mac', 'mac'] } }, checks: [{ description: 'It answers.', independent: false }] })
    const fresh = store.split(s.state, { tabId: 'tab', version: R, now: NOW })
    const requires = (groups: Array<{ key: string }>) => (groups.find(g => g.key === s.done) as unknown as { data: { task: { requires: unknown } } }).data.task.requires
    expect(requires(readerView(fresh, owner, LATER, { teamMachines: [] }).parts.groups)).toEqual({ machines: ['secret-mac', 'mac'] })
    expect(requires(readerView(fresh, peer, LATER, { teamMachines: [] }).parts.groups)).toEqual({ machines: ['mac'], unseenMachines: 1 })
    const changed = [write(fresh, 'groups', s.done, () => {})]
    expect(requires(receive(fresh, changed, peer).groups)).toEqual({ machines: ['mac'], unseenMachines: 1 })
    expect(requires(receive(fresh, changed, owner).groups)).toEqual({ machines: ['secret-mac', 'mac'] })
  })
})

// A client that asks for it gets a line for a machine's own reading (Ken's machine-cap plan, 2026-11-04).
describe('a machine\'s reading, for a client that asks for lines', () => {
  const SINCE = NOW + 1_000
  const lightly = (parts: SwarmParts, changed: Part[], actor: Actor) => {
    const view = readerView(parts, actor, LATER, { teamMachines: [] })
    return changesFor(view, changed, actor, { since: SINCE })
  }
  const reading = (parts: SwarmParts, change: (p: Part) => void = () => {}) => {
    const part = parts.machines.find(p => p.key === 'mac')! as Part
    part.version += 1
    part.readAt = LATER
    const data = part.data as { contribution: { observation?: unknown } }
    data.contribution.observation = { receivedAt: LATER, resources: {}, quotas: [], tools: {}, runningHarnessIds: [], stoppedHarnessIds: [] }
    change(part)
    return part
  }

  it('is a line when only the reading moved', () => {
    const { parts } = scene()
    const out = lightly(parts, [reading(parts)], peer)
    expect(out.machines).toEqual([])
    expect(out.machineReadings).toEqual([{ key: 'mac', version: R + 1, receivedAt: LATER }])
  })

  it('is the whole part when its content changed since the cursor', () => {
    const { parts } = scene()
    const out = lightly(parts, [reading(parts, p => { p.contentAt = LATER })], peer)
    expect(keys(out.machines)).toEqual(['mac'])
    expect(out.machineReadings).toEqual([])
  })

  it('is the whole part when anything else changed since the cursor, and a line when its content changed before it', () => {
    const { parts } = scene()
    expect(keys(lightly(parts, [reading(parts, p => { p.changedAt = LATER })], peer).machines)).toEqual(['mac'])
    const { parts: older } = scene()
    expect(lightly(older, [reading(older, p => { p.contentAt = SINCE - 1 })], peer).machines).toEqual([])
  })

  it('is a removal, never a line, when the machine left', () => {
    const { parts } = scene()
    const gone = write(parts, 'machines', 'mac', p => { p.deleted = true; p.readAt = LATER })
    const out = changesFor(readerView({ ...parts, machines: [] }, peer, LATER, { teamMachines: [] }), [gone], peer, { since: SINCE })
    expect(out.machines).toEqual([{ key: 'mac', version: R + 1, changedAt: LATER, deleted: true }])
    expect(out.machineReadings).toEqual([])
  })

  it('tells a Buddy nothing, and anyone nothing of a Buddy-only machine', () => {
    const { parts, s } = scene()
    s.edit(state => { state.agents.push({ ...state.agents[0]!, id: 'buddy', buddyOf: { personId: peer.userId, generation: 'g' } } as never) })
    const withBuddy = store.split(s.state, { tabId: 'tab', version: R, now: NOW })
    const buddy: Actor = { kind: 'agent', agentId: 'buddy', machineOwnerId: `${owner.userId}-machine` }
    expect(lightly(withBuddy, [reading(withBuddy)], buddy).machineReadings).toEqual([])
    const hidden = reading(parts, p => { (p.data as { contribution: { buddyOnly?: true } }).contribution.buddyOnly = true })
    expect(lightly(parts, [hidden], peer).machineReadings).toEqual([])
  })

  it('leaves the reply as it was for a client that did not ask', () => {
    const { parts } = scene()
    const out = receive(parts, [reading(parts)], peer)
    expect(keys(out.machines)).toEqual(['mac'])
    expect(out).not.toHaveProperty('machineReadings')
  })
})