Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

34.4 KB
Raw Blame
import { describe, it, expect, vi, beforeEach } from 'vitest'
import type { Tool } from 'ai'

const { streamText, convertToModelMessages } = vi.hoisted(() => ({
  streamText: vi.fn(),
  convertToModelMessages: vi.fn(async (m: unknown) => m),
}))
vi.mock('ai', async (orig) => ({
  ...(await orig<typeof import('ai')>()),
  streamText,
  convertToModelMessages,
}))

import {
  formatDispatchedPlan,
  injectInputs,
  intersectAllowedTools,
  parseDispatchPlan,
  parentToolNames,
  resolveSubagent,
  runSubagent,
  runDispatchPlan,
  subagentCompletionNotice,
  planCompletionNotice,
  subagentTools,
  SubagentInbox,
  MAX_PARALLEL_SUBAGENTS,
  SUBAGENT_INLINE_MAX,
  PHASE_INPUT_MAX_BYTES,
  __testing,
  type DispatchPlan,
  type SubagentRequest,
  type SubagentResult,
} from '../coworkSubagent'
import type { StreamEvent } from '@/hooks/useCoworkRun'
import { MAX_SUBAGENT_STEPS } from '../coworkBudget'

const tools = (...names: string[]): Record<string, Tool> =>
  Object.fromEntries(names.map((n) => [n, {} as Tool]))

const definition = (over = {}) => ({
  name: 'researcher',
  description: 'reads things',
  system_prompt: 'You research.',
  allowed_tools: null as string[] | null,
  model: null as string | null,
  ...over,
})

describe('the task result and its completion ping', () => {
  const single: DispatchPlan = {
    phases: [{ number: 0, subagents: [{ name: 'researcher', description: 'go' }] }],
  }
  const multi: DispatchPlan = {
    phases: [
      {
        number: 0,
        subagents: [
          { name: 'alpha', description: 'a' },
          { name: 'beta', description: 'b' },
        ],
      },
      { number: 1, subagents: [{ name: 'collector', description: 'c' }] },
    ],
  }

  it('summarizes a single-phase fan-out and names the blackboard dir', () => {
    const out = formatDispatchedPlan(single, '/tmp/blackboard')
    expect(out).toContain('running concurrently')
    expect(out).toContain('researcher')
    expect(out).toContain('/tmp/blackboard/<name>.md')
    expect(out).toContain('do not do them yourself')
  })

  it('names the phase count and phase-1 subagents for a multi-phase plan', () => {
    const out = formatDispatchedPlan(multi, '/tmp/blackboard')
    expect(out).toContain('2-phase plan of 3 subagents')
    expect(out).toContain('Phase 1 is now running: alpha, beta')
    expect(out).toContain('Later phases start automatically')
  })

  it('falls back to inline delivery when there is no scratch', () => {
    const out = formatDispatchedPlan(single, null)
    expect(out).toContain('rides the note')
    expect(out).not.toContain('blackboard')
  })

  /// The row shows the headline and the model gets the instructions after it:
  /// "read that file when you need it" is addressed to the model alone.
  it('splits the fact from the instructions that follow it', () => {
    const out = subagentCompletionNotice({
      name: 'researcher',
      callId: 'c1',
      savedPath: '/tmp/subagents/r.md',
      output: 'the findings',
    })
    expect(out.headline).toBe("Subagent 'researcher' (c1) finished")
    expect(out.headline).not.toContain('/tmp/')
    expect(out.text.startsWith(out.headline)).toBe(true)
    expect(out.text).toContain('/tmp/subagents/r.md')
    // The answer is on disk; repeating it here would spend the context twice.
    expect(out.text).not.toContain('the findings')
  })

  // Nothing else would carry it: with no file, the ping is the only delivery.
  it('carries the answer inline when nothing was saved, capped', () => {
    const output = 'y'.repeat(SUBAGENT_INLINE_MAX + 10)
    const out = subagentCompletionNotice({
      name: 'researcher',
      callId: 'c1',
      savedPath: null,
      output,
    })
    expect(out.text).toContain('y'.repeat(SUBAGENT_INLINE_MAX))
    expect(out.text.length).toBeLessThan(output.length + 200)
    // Still just the fact: the answer is for the model, not the transcript.
    expect(out.headline).toBe("Subagent 'researcher' (c1) finished")
  })

  /// A failure has no instructions to strip, so both registers are the reason
  /// it failed -- which is the one thing here worth reading on screen.
  it('reports a failure as one, in both registers', () => {
    const out = subagentCompletionNotice({
      name: 'researcher',
      callId: 'c1',
      savedPath: null,
      output: 'the model refused',
      isError: true,
    })
    expect(out.headline).toBe("Subagent 'researcher' (c1) failed: the model refused")
    expect(out.text).toBe(out.headline)
  })
})

describe('SubagentInbox', () => {
  const done = { headline: 'done', text: 'done, in full' }

  it('reports work outstanding from dispatch until the ping is taken', async () => {
    const inbox = new SubagentInbox()
    expect(inbox.pending()).toBe(false)
    inbox.begin()
    expect(inbox.pending()).toBe(true)
    inbox.finish(done)
    // Still pending: the ping has been queued but not delivered, so a run that
    // stopped here would drop it.
    expect(inbox.pending()).toBe(true)
    expect(inbox.take()).toEqual([done])
    expect(inbox.take()).toEqual([])
    expect(inbox.pending()).toBe(false)
  })

  it('wakes a waiter when a child finishes', async () => {
    const inbox = new SubagentInbox()
    inbox.begin()
    let woke = false
    const waiting = inbox.wait().then(() => {
      woke = true
    })
    await Promise.resolve()
    expect(woke).toBe(false)
    inbox.finish(done)
    await waiting
    expect(woke).toBe(true)
  })

  it('never parks when there is nothing to wait for', async () => {
    await expect(new SubagentInbox().wait()).resolves.toBeUndefined()
  })

  /// A cancelled run aborts its children, and nothing would ever file their
  /// pings — so the wait has to end with the run, not with the child.
  it('releases the waiter on cancellation', async () => {
    const inbox = new SubagentInbox()
    inbox.begin()
    const controller = new AbortController()
    const waiting = inbox.wait(controller.signal)
    controller.abort()
    await expect(waiting).resolves.toBeUndefined()
  })
})

describe('parseDispatchPlan', () => {
  it('groups a flat subagents list into ordered phases by their `phase` key', () => {
    // Listed out of order and with a gap (0, 2); grouped and ordered, and the
    // phase number carried is the model's own key.
    const plan = parseDispatchPlan({
      subagents: [
        { name: 'c', task: 'do c', phase: 2, allowed_tools: ['read', 42] },
        { name: 'a', task: 'do a' },
        { name: 'b', task: 'do b', phase: 0 },
      ],
    })
    expect(plan).toEqual({
      phases: [
        {
          number: 0,
          subagents: [
            { name: 'a', description: 'do a' },
            { name: 'b', description: 'do b' },
          ],
        },
        {
          number: 2,
          subagents: [{ name: 'c', description: 'do c', allowed_tools: ['read'] }],
        },
      ],
    })
  })

  it('fans out into a single phase when no `phase` is given', () => {
    const plan = parseDispatchPlan({
      subagents: [
        { name: 'a', task: 'x' },
        { name: 'b', task: 'y' },
      ],
    }) as DispatchPlan
    expect(plan.phases).toHaveLength(1)
    expect(plan.phases[0].number).toBe(0)
    expect(plan.phases[0].subagents).toHaveLength(2)
  })

  it('requires a non-empty subagents array', () => {
    expect(parseDispatchPlan({})).toContain('subagents')
    expect(parseDispatchPlan({ subagents: [] })).toContain('at least one')
  })

  it('requires a non-empty name and task per subagent', () => {
    expect(parseDispatchPlan({ subagents: [{ task: 'x' }] })).toContain('name')
    expect(parseDispatchPlan({ subagents: [{ name: 'a' }] })).toContain('task')
  })

  it('rejects an invalid name charset and an over-long name', () => {
    expect(
      parseDispatchPlan({ subagents: [{ name: 'a b', task: 't' }] })
    ).toContain('invalid subagent name')
    expect(
      parseDispatchPlan({ subagents: [{ name: 'a'.repeat(65), task: 't' }] })
    ).toContain('too long')
  })

  it('rejects a non-negative-integer phase', () => {
    expect(
      parseDispatchPlan({ subagents: [{ name: 'a', task: 't', phase: -1 }] })
    ).toContain("invalid 'phase'")
    expect(
      parseDispatchPlan({ subagents: [{ name: 'a', task: 't', phase: 'later' }] })
    ).toContain("invalid 'phase'")
  })

  it('rejects a duplicate name across the whole plan', () => {
    expect(
      parseDispatchPlan({
        subagents: [
          { name: 'dup', task: 't1' },
          { name: 'dup', task: 't2', phase: 1 },
        ],
      })
    ).toContain('duplicate subagent name')
  })

  it('treats an empty allowlist as omitted', () => {
    const plan = parseDispatchPlan({
      subagents: [{ name: 'a', task: 't', allowed_tools: [] }],
    }) as DispatchPlan
    expect(plan.phases[0].subagents[0]).not.toHaveProperty('allowed_tools')
  })
})

describe('injectInputs', () => {
  it('returns the task unchanged when there are no inputs', () => {
    expect(injectInputs('do it', [])).toBe('do it')
  })

  it('prefixes the previous phase results and keeps the task last', () => {
    const out = injectInputs('synthesize', [{ name: 'alpha', output: 'found X' }])
    expect(out).toContain('Results from the previous phase')
    expect(out).toContain('### alpha')
    expect(out).toContain('found X')
    expect(out.trimEnd().endsWith('synthesize')).toBe(true)
  })

  it('truncates a verbose input at the byte cap with a pointer to the blackboard', () => {
    const big = 'x'.repeat(PHASE_INPUT_MAX_BYTES + 500)
    const out = injectInputs('t', [{ name: 'beta', output: big }])
    expect(out).toContain('truncated; read blackboard/beta.md')
  })
})

describe('resolveSubagent bash refusal', () => {
  // An ad-hoc dispatch has no definition, so the refusal must name the
  // call's own list -- the one the model wrote and can fix.
  it("names the call's own list for an ad-hoc subagent", () => {
    const out = resolveSubagent(
      { name: 'adhoc', description: 't', allowed_tools: ['bash'] },
      [],
      ['read', 'shell']
    )
    expect(out).toHaveProperty('error')
    const error = (out as { error: string }).error
    expect(error.startsWith('allowed_tools names `bash`')).toBe(true)
    expect(error).not.toContain('definition')
  })
})

describe('intersectAllowedTools', () => {
  // A list still naming `bash` is refused with the rename, rather than
  // giving a child that silently has no shell.
  it('refuses a bash entry with the rename', () => {
    const parent = ['read', 'shell', 'skill_list', 'skill_read']
    const fromDefinition = intersectAllowedTools(['read', 'bash'], null, parent)
    expect(fromDefinition).toEqual({
      error:
        "the subagent definition's allowed_tools names `bash`, which matches " +
        'nothing: the shell tool is now `shell`. Rename it to `shell` for it to apply.',
    })
    expect(intersectAllowedTools(null, ['Bash'], parent)).toHaveProperty('error')
    expect(intersectAllowedTools(['read', 'shell'], ['shell'], parent)).toEqual({
      tools: ['shell', 'skill_list', 'skill_read'],
    })
  })

  const parent = ['read', 'grep', 'write', 'skill_list', 'skill_read']

  it('inherits the parent set when neither side narrows', () => {
    expect(intersectAllowedTools(null, null, parent)).toEqual({ tools: null })
  })

  it('narrows to the definition, dropping what the parent lacks', () => {
    // The definition's author cannot know the parent's mode, so a tool the
    // parent lacks is dropped rather than raised as an error.
    const out = intersectAllowedTools(['read', 'shell'], null, parent)
    expect(out).toEqual({ tools: ['read', 'skill_list', 'skill_read'] })
  })

  it('refuses a request outside the definition', () => {
    expect(
      intersectAllowedTools(['read'], ['write'], parent)
    ).toEqual({
      error: expect.stringContaining("outside the subagent definition's"),
    })
  })

  it('refuses a request the parent cannot call', () => {
    // This is what makes plan mode and a withheld `shell` propagate: the parent's
    // advertised set is the ceiling.
    expect(intersectAllowedTools(null, ['shell'], parent)).toEqual({
      error: expect.stringContaining('not available to this run'),
    })
  })

  it('never widens past the parent', () => {
    const out = intersectAllowedTools(null, ['read'], parent)
    expect(out).toEqual({ tools: ['read', 'skill_list', 'skill_read'] })
  })

  it('always grants the read-side skill tools', () => {
    // Ported from `SUBAGENT_SKILL_TOOLS`: a Claude-style `tools:` list never
    // names them, so a narrowed set must not strip them.
    const out = intersectAllowedTools(['read'], null, parent)
    expect(out).toEqual({ tools: ['read', ...__testing.SUBAGENT_SKILL_TOOLS] })
  })

  it('does not grant skill tools the parent itself lacks', () => {
    expect(intersectAllowedTools(['read'], null, ['read'])).toEqual({
      tools: ['read'],
    })
  })
})

describe('resolveSubagent', () => {
  const parent = ['read', 'grep', 'skill_list', 'skill_read']

  it('uses a saved definition', () => {
    const out = resolveSubagent(
      { name: 'researcher', description: 'go' },
      [definition({ allowed_tools: ['read'], model: 'm-1' })],
      parent
    )
    expect(out).toEqual({
      name: 'researcher',
      systemPrompt: 'You research.',
      allowedTools: ['read', 'skill_list', 'skill_read'],
      model: 'm-1',
    })
  })

  it('resolves an unknown name to an ephemeral generalist (no error)', () => {
    const out = resolveSubagent(
      { name: 'designer', description: 'go', allowed_tools: ['read'] },
      [],
      parent
    )
    expect(out).toMatchObject({
      name: 'designer',
      allowedTools: ['read', 'skill_list', 'skill_read'],
      model: null,
    })
    // The ephemeral system prompt names the subagent and its hand-off role.
    expect((out as { systemPrompt: string }).systemPrompt).toBe(
      __testing.ephemeralSubagentPrompt('designer')
    )
    expect((out as { systemPrompt: string }).systemPrompt).toContain('designer')
  })

  it('surfaces a call-site tool outside the saved definition as an error', () => {
    const out = resolveSubagent(
      { name: 'researcher', description: 'go', allowed_tools: ['write'] },
      [definition({ allowed_tools: ['read'] })],
      parent
    )
    expect(out).toEqual({
      error: expect.stringContaining("outside the subagent definition's"),
    })
  })

  it('lets a call site narrow a saved definition', () => {
    const out = resolveSubagent(
      { name: 'researcher', description: 'go', allowed_tools: ['read'] },
      [definition({ allowed_tools: ['read', 'grep'] })],
      parent
    )
    expect(out).toMatchObject({
      allowedTools: ['read', 'skill_list', 'skill_read'],
    })
  })
})

describe('subagentTools', () => {
  it('withholds the parent-only tools whatever the allowlist says', () => {
    // `task` is the depth cap; `ask` and `todo` belong to the parent's
    // conversation, which no child is attached to.
    const out = subagentTools(
      tools('read', 'task', 'ask', 'todo'),
      ['read', 'task', 'ask', 'todo']
    )
    expect(Object.keys(out)).toEqual(['read'])
  })

  it('never gives a child memory, even when its allowlist names it', () => {
    const out = subagentTools(tools('read', 'memory'), ['read', 'memory'])
    expect(Object.keys(out)).toEqual(['read'])
    expect(Object.keys(subagentTools(tools('read', 'memory'), null))).toEqual([
      'read',
    ])
  })

  it('narrows to the allowlist', () => {
    const out = subagentTools(tools('read', 'grep', 'write'), ['read'])
    expect(Object.keys(out)).toEqual(['read'])
  })

  it('inherits everything offerable when the allowlist is null', () => {
    const out = subagentTools(tools('read', 'grep', 'task'), null)
    expect(Object.keys(out)).toEqual(['read', 'grep'])
  })
})

describe('parentToolNames', () => {
  it('excludes what a child can never be granted', () => {
    expect(parentToolNames(tools('read', 'task', 'ask', 'todo'))).toEqual([
      'read',
    ])
  })
})

describe('Semaphore', () => {
  it('runs up to the cap at once and queues the rest in order', async () => {
    const s = new __testing.Semaphore(2)
    const a = await s.acquire()
    await s.acquire()
    expect(s.waiting).toBe(0)
    expect(s.available).toBe(0)

    const order: number[] = []
    const third = s.acquire().then((r) => {
      order.push(3)
      return r
    })
    const fourth = s.acquire().then((r) => {
      order.push(4)
      return r
    })
    expect(s.waiting).toBe(2)

    a()
    ;(await third)()
    ;(await fourth)()
    // FIFO, so the queue position reported to the UI is the one it gets.
    expect(order).toEqual([3, 4])
  })
})

// A `finish` chunk carrying usage, matching what `toUIMessageStream` emits.
const chunkStream = (chunks: unknown[]) =>
  new ReadableStream({
    start(c) {
      for (const chunk of chunks) c.enqueue(chunk)
      c.close()
    },
  })

const textStep = (text: string, usage = 12) => [
  { type: 'text-delta', delta: text },
  { type: 'finish', messageMetadata: { usage: { totalTokens: usage } } },
]

const toolStep = (id: string, name: string, input: unknown) => [
  { type: 'tool-input-start', toolCallId: id, toolName: name },
  { type: 'tool-input-available', toolCallId: id, toolName: name, input },
  { type: 'finish', messageMetadata: { usage: { totalTokens: 5 } } },
]

function mockSteps(steps: unknown[][]) {
  let i = 0
  streamText.mockImplementation(() => ({
    toUIMessageStream: () => chunkStream(steps[i++] ?? []),
  }))
}

const baseOpts = (over = {}) => ({
  resolved: {
    name: 'researcher',
    systemPrompt: 'You research.',
    allowedTools: null,
    model: null,
  },
  description: 'find the config',
  model: 'model-instance' as never,
  parentTools: tools('read', 'task', 'ask'),
  system: {
    workspacePath: '/ws/s1',
    readOnlyFolder: null,
    bashAvailable: false,
  },
  dispatch: vi.fn(async () => ({ output: 'ok' })),
  signal: new AbortController().signal,
  events: {
    onQueued: vi.fn(),
    onStart: vi.fn(),
    onInner: vi.fn(),
    onEnd: vi.fn(),
  },
  ...over,
})

describe('runSubagent', () => {
  beforeEach(() => {
    streamText.mockReset()
    convertToModelMessages.mockClear()
  })

  it('returns the final text as the task output', async () => {
    mockSteps([textStep('the config is at /etc/x')])
    const opts = baseOpts()
    const out = await runSubagent(opts)
    expect(out.output).toBe('the config is at /etc/x')
    expect(out.isError).toBeFalsy()
    expect(opts.events.onStart).toHaveBeenCalled()
    expect(opts.events.onEnd).toHaveBeenCalledWith(
      expect.objectContaining({ total_tokens: 12 })
    )
  })

  it('reuses the parent model instance rather than creating one', async () => {
    mockSteps([textStep('done')])
    await runSubagent(baseOpts())
    expect(streamText).toHaveBeenCalledWith(
      expect.objectContaining({ model: 'model-instance' })
    )
  })

  it('never advertises the parent-only tools to the child', async () => {
    mockSteps([textStep('done')])
    await runSubagent(baseOpts())
    const passed = streamText.mock.calls[0][0].tools as Record<string, Tool>
    expect(Object.keys(passed)).toEqual(['read'])
  })

  it('starts from a fresh history: only the description', async () => {
    mockSteps([textStep('done')])
    await runSubagent(baseOpts())
    const sent = streamText.mock.calls[0][0].messages as Array<{
      role: string
      parts: Array<{ text: string }>
    }>
    expect(sent).toHaveLength(1)
    expect(sent[0].role).toBe('user')
    expect(sent[0].parts[0].text).toBe('find the config')
  })

  it('puts the sandbox path in the child system prompt', async () => {
    mockSteps([textStep('done')])
    await runSubagent(baseOpts())
    const system = streamText.mock.calls[0][0].system as string
    // A child cannot guess the sandbox path, and the Rust override would have
    // replaced the workspace block wholesale.
    expect(system).toContain('You research.')
    expect(system).toContain('/ws/s1')
    expect(system).toContain('cannot dispatch')
  })

  it('reports the child transcript as inner stream events', async () => {
    mockSteps([toolStep('c1', 'read', { path: 'a' }), textStep('found it')])
    const opts = baseOpts()
    await runSubagent(opts)
    const kinds = (opts.events.onInner.mock.calls as [StreamEvent][]).map(
      ([e]) => e.type
    )
    // `applyInnerToTurns` consumes exactly these, unchanged from the Rust shape.
    expect(kinds).toContain('tool_call_started')
    expect(kinds).toContain('tool_call')
    expect(kinds).toContain('tool_result')
    expect(kinds).toContain('token')
  })

  // The lane renders `MessageItem` from these turns, so the child's finish
  // metadata has to reach it or the subagent rows show no speed at all.
  it('forwards a finished child step metadata block, before its tool results', async () => {
    mockSteps([
      [
        { type: 'text-delta', delta: 'answer' },
        { type: 'tool-input-start', toolCallId: 'c1', toolName: 'read' },
        {
          type: 'tool-input-available',
          toolCallId: 'c1',
          toolName: 'read',
          input: { path: 'a' },
        },
        {
          type: 'finish',
          messageMetadata: {
            usage: { totalTokens: 12 },
            tokenSpeed: { tokenSpeed: 42.5, tokenCount: 300, durationMs: 7000 },
          },
        },
      ],
    ])
    const opts = baseOpts()
    await runSubagent(opts)
    const events = (opts.events.onInner.mock.calls as [StreamEvent][]).map(
      ([e]) => e
    )
    const step = events.find((e) => e.type === 'step_metadata')
    expect(step).toMatchObject({
      metadata: { tokenSpeed: { tokenSpeed: 42.5, tokenCount: 300 } },
    })
    // Before the results: the lane hangs it on the answer row, and a tool row
    // arriving first would leave it nowhere to land.
    const kinds = events.map((e) => e.type)
    expect(kinds.indexOf('step_metadata')).toBeGreaterThan(
      kinds.indexOf('tool_call')
    )
    expect(kinds.indexOf('step_metadata')).toBeLessThan(
      kinds.indexOf('tool_result')
    )
  })

  it('dispatches the child tool calls', async () => {
    mockSteps([toolStep('c1', 'read', { path: 'a' }), textStep('done')])
    const opts = baseOpts()
    await runSubagent(opts)
    expect(opts.dispatch).toHaveBeenCalledWith(
      expect.objectContaining({ toolName: 'read' }),
      expect.anything()
    )
  })

  it('reports a step cap as an error, keeping the partial output', async () => {
    mockSteps(
      Array.from({ length: 4 }, (_, i) =>
        toolStep(`c${i}`, 'read', { path: 'a' })
      )
    )
    const out = await runSubagent(baseOpts({ maxSteps: 2 }))
    // The parent can finish the errand itself, but not if it believes the child
    // answered in full.
    expect(out.isError).toBe(true)
    expect(out.output).toContain('2-step budget')
  })

  it('defaults to the subagent step cap, not the parent one', async () => {
    mockSteps(
      Array.from({ length: MAX_SUBAGENT_STEPS + 1 }, (_, i) =>
        toolStep(`c${i}`, 'read', { path: 'a' })
      )
    )
    const out = await runSubagent(baseOpts())
    expect(out.output).toContain(`${MAX_SUBAGENT_STEPS}-step budget`)
  })

  it('returns cleanly when already aborted', async () => {
    mockSteps([textStep('never')])
    const controller = new AbortController()
    controller.abort()
    const opts = baseOpts({ signal: controller.signal })
    const out = await runSubagent(opts)
    expect(out.isError).toBe(true)
    expect(streamText).not.toHaveBeenCalled()
    // Still closed out, so a caller that opened a lane on `onQueued` does not
    // leave a spinner running.
    expect(opts.events.onEnd).toHaveBeenCalled()
  })

  it('surfaces a stream error as the task result', async () => {
    streamText.mockImplementation(() => ({
      toUIMessageStream: () =>
        chunkStream([{ type: 'error', errorText: 'context overflow' }]),
    }))
    const out = await runSubagent(baseOpts())
    expect(out).toMatchObject({ output: 'context overflow', isError: true })
  })

  it('says so when the child produced no answer', async () => {
    mockSteps([[{ type: 'finish', messageMetadata: {} }]])
    const out = await runSubagent(baseOpts())
    expect(out.output).toContain('no answer')
  })

  it('caps concurrency at three', () => {
    expect(MAX_PARALLEL_SUBAGENTS).toBe(3)
  })

  it('queues the fourth child and reports its position', async () => {
    let releaseAll = () => {}
    const held = new Promise<void>((r) => {
      releaseAll = r
    })
    streamText.mockImplementation(() => ({
      toUIMessageStream: () =>
        new ReadableStream({
          async start(c) {
            await held
            c.enqueue({ type: 'text-delta', delta: 'done' })
            c.close()
          },
        }),
    }))

    const runs = Array.from({ length: 4 }, () => baseOpts())
    const all = Promise.all(runs.map((o) => runSubagent(o)))
    // Let the three admitted children reach streamText.
    for (let i = 0; i < 20; i += 1) await Promise.resolve()

    expect(streamText).toHaveBeenCalledTimes(MAX_PARALLEL_SUBAGENTS)
    const queued = runs.filter((o) => o.events.onQueued.mock.calls.length > 0)
    expect(queued).toHaveLength(1)
    expect(queued[0].events.onQueued).toHaveBeenCalledWith(1)
    expect(queued[0].events.onStart).not.toHaveBeenCalled()

    releaseAll()
    await all
    // The queued child runs once a permit frees, rather than being dropped.
    expect(streamText).toHaveBeenCalledTimes(4)
    expect(queued[0].events.onStart).toHaveBeenCalled()
  })
})

describe('runDispatchPlan', () => {
  const okResult = (output: string): SubagentResult => ({
    output,
    usage: null,
    sessionTokens: 0,
  })
  const req = (name: string): SubagentRequest => ({
    name,
    description: `do ${name}`,
  })
  const deferred = () => {
    let resolve!: () => void
    const promise = new Promise<void>((r) => {
      resolve = r
    })
    return { promise, resolve }
  }
  const flush = async () => {
    for (let i = 0; i < 15; i += 1) await Promise.resolve()
  }

  // Mirrors the Rust `a_later_phase_starts_after_the_earlier_one_with_its_results`.
  it('starts a later phase only after the earlier one finished, with its results injected', async () => {
    const plan: DispatchPlan = {
      phases: [
        { number: 0, subagents: [req('alpha'), req('beta')] },
        { number: 1, subagents: [req('collector')] },
      ],
    }
    const order: string[] = []
    const briefs: Record<string, string> = {}
    const gateA = deferred()
    const gateB = deferred()

    const done = runDispatchPlan(plan, 'c1', {
      runOne: async (r, description) => {
        order.push(`start:${r.name}`)
        briefs[r.name] = description
        if (r.name === 'alpha') await gateA.promise
        if (r.name === 'beta') await gateB.promise
        order.push(`end:${r.name}`)
        return okResult(`${r.name} findings`)
      },
      writeBlackboard: async (name) => `/tmp/blackboard/${name}.md`,
      onDispatch: () => {},
      onComplete: () => {},
    })

    await flush()
    // Phase 1 is dispatched; phase 2 must not have started yet.
    expect(order).toContain('start:alpha')
    expect(order).toContain('start:beta')
    expect(order).not.toContain('start:collector')

    gateA.resolve()
    gateB.resolve()
    await done

    const collector = order.indexOf('start:collector')
    expect(collector).toBeGreaterThan(-1)
    expect(order.indexOf('end:alpha')).toBeLessThan(collector)
    expect(order.indexOf('end:beta')).toBeLessThan(collector)

    // The collector's brief carries phase 1's blackboard results.
    expect(briefs.collector).toContain('Results from the previous phase')
    expect(briefs.collector).toContain('alpha findings')
    expect(briefs.collector).toContain('beta findings')
  })

  // Mirrors the Rust `a_cancelled_run_starts_no_further_phase`: a run cancelled
  // while a phase is running starts no phase after it. Before the fix the
  // collector was dispatched anyway -- promoted in the UI, cancelled on arrival,
  // and announced by a terminal notice for a plan nobody was waiting for.
  it('starts no further phase once the run is aborted', async () => {
    const controller = new AbortController()
    const started: string[] = []
    const plan: DispatchPlan = {
      phases: [
        { number: 0, subagents: [req('alpha')] },
        { number: 1, subagents: [req('collector')] },
      ],
    }

    const finalPhase = await runDispatchPlan(plan, 'c1', {
      signal: controller.signal,
      runOne: async (r) => {
        started.push(r.name)
        // Cancelled while phase 0 is still running.
        if (r.name === 'alpha') controller.abort()
        return okResult(`${r.name} out`)
      },
      writeBlackboard: async (name) => `/tmp/blackboard/${name}.md`,
      onDispatch: () => {},
      onComplete: () => {},
    })

    expect(started).toEqual(['alpha'])
    // No final phase: the caller must not ring a doorbell for a plan that never
    // finished, so the half-done phase 1 is not offered as one.
    expect(finalPhase).toEqual([])
  })

  it('dispatches nothing when the run is already aborted', async () => {
    const controller = new AbortController()
    controller.abort()
    const started: string[] = []

    const finalPhase = await runDispatchPlan(
      { phases: [{ number: 0, subagents: [req('alpha')] }] },
      'c1',
      {
        signal: controller.signal,
        runOne: async (r) => {
          started.push(r.name)
          return okResult('out')
        },
        writeBlackboard: async (name) => `/tmp/blackboard/${name}.md`,
        onDispatch: () => {},
        onComplete: () => {},
      }
    )

    expect(started).toEqual([])
    expect(finalPhase).toEqual([])
  })

  it('keys each subagent `${callId}-${name}` and writes real answers to the blackboard', async () => {
    const dispatched: string[] = []
    const writes: string[] = []
    await runDispatchPlan(
      { phases: [{ number: 0, subagents: [req('alpha')] }] },
      'call-9',
      {
        runOne: async () => okResult('the answer'),
        writeBlackboard: async (name, content) => {
          writes.push(`${name}:${content}`)
          return `/tmp/blackboard/${name}.md`
        },
        onDispatch: (id) => dispatched.push(id),
        onComplete: () => {},
      }
    )
    expect(dispatched).toEqual(['call-9-alpha'])
    expect(writes).toEqual(['alpha:the answer'])
  })

  it('proceeds past a failed child and does not write its blackboard', async () => {
    const writes: string[] = []
    const completed: { name: string; savedPath: string | null }[] = []
    await runDispatchPlan(
      {
        phases: [
          { number: 0, subagents: [req('flaky')] },
          { number: 1, subagents: [req('next')] },
        ],
      },
      'c1',
      {
        runOne: async (r) =>
          r.name === 'flaky'
            ? { output: 'boom', usage: null, isError: true, sessionTokens: 0 }
            : okResult('ok'),
        writeBlackboard: async (name) => {
          writes.push(name)
          return `/tmp/blackboard/${name}.md`
        },
        onDispatch: () => {},
        onComplete: (_id, name, _res, savedPath) =>
          completed.push({ name, savedPath }),
      }
    )
    expect(completed).toEqual([
      { name: 'flaky', savedPath: null },
      { name: 'next', savedPath: '/tmp/blackboard/next.md' },
    ])
    expect(writes).toEqual(['next'])
  })

  // The plan hold keeps inbox.pending() true across the phase boundary, even if
  // the run loop drains every ping the instant a child finishes.
  it('keeps the run alive across the whole plan via the plan hold', async () => {
    const inbox = new SubagentInbox()
    const plan: DispatchPlan = {
      phases: [
        { number: 0, subagents: [req('alpha'), req('beta')] },
        { number: 1, subagents: [req('collector')] },
      ],
    }
    let planDone = false
    const observations: boolean[] = []
    inbox.begin() // the plan hold, taken at dispatch

    const drainer = (async () => {
      for (;;) {
        await inbox.wait()
        inbox.take()
        observations.push(inbox.pending())
        if (planDone) break
      }
    })()

    await runDispatchPlan(plan, 'c1', {
      runOne: async (r) => okResult(`${r.name} out`),
      writeBlackboard: async (name) => `/tmp/blackboard/${name}.md`,
      onDispatch: () => inbox.begin(),
      onComplete: (_id, name) => inbox.finish({ headline: name, text: name }),
    })
    planDone = true
    inbox.abandon() // release the plan hold, as the finally in onTask does
    await drainer

    // Every drain while the plan ran saw work outstanding; only the final drain
    // (after the hold released) reads idle.
    expect(observations.length).toBeGreaterThan(0)
    expect(observations.slice(0, -1).every((p) => p === true)).toBe(true)
    expect(observations.at(-1)).toBe(false)
  })

  // The doorbell contract, ported from the Rust
  // `a_multi_phase_plan_rings_the_doorbell_once_at_the_end`: a multi-phase plan
  // queues exactly one ping (the consolidated terminal notice), not one per child.
  it('rings the inbox once for a multi-phase plan, at the end', async () => {
    const inbox = new SubagentInbox()
    const plan: DispatchPlan = {
      phases: [
        { number: 0, subagents: [req('alpha'), req('beta')] },
        { number: 1, subagents: [req('gamma'), req('collector')] },
      ],
    }
    const multi = plan.phases.length > 1
    inbox.begin() // the plan hold

    const finalPhase = await runDispatchPlan(plan, 'c1', {
      runOne: async (r) => okResult(`${r.name} out`),
      writeBlackboard: async (name) => `/tmp/blackboard/${name}.md`,
      onDispatch: () => inbox.begin(),
      // Mirrors the cowork wiring: silent per child for a multi-phase plan.
      onComplete: () => (multi ? inbox.abandon() : undefined),
    })
    inbox.note(
      planCompletionNotice({
        phaseCount: plan.phases.length,
        totalSubagents: 4,
        finalPhase,
      })
    )
    inbox.abandon() // release the plan hold

    const notices = inbox.take()
    expect(notices).toHaveLength(1)
    expect(notices[0].text).toContain('plan finished')
    expect(notices[0].text).toContain('collector')
    expect(inbox.pending()).toBe(false)
  })
})

describe('planCompletionNotice', () => {
  const res = (
    output: string,
    isError = false
  ): SubagentResult => ({ output, usage: null, isError, sessionTokens: 0 })

  it('points at saved files and inlines the rest', () => {
    const out = planCompletionNotice({
      phaseCount: 2,
      totalSubagents: 3,
      finalPhase: [
        { name: 'saved', result: res('long answer'), savedPath: '/tmp/blackboard/saved.md' },
        { name: 'inline', result: res('inline answer'), savedPath: null },
        { name: 'broke', result: res('boom', true), savedPath: null },
      ],
    })
    expect(out.text).toContain('3 subagent(s) across 2 phases')
    expect(out.text).toContain('see /tmp/blackboard/saved.md')
    expect(out.text).toContain('inline answer')
    expect(out.text).toContain('failed: boom')
  })
})