Skip to content

armgit / orca

Public Imported from GitHub
0

Orca is the place for working with a fleet of agents (e.g. Grok Bot, Claude Code). Run any coding agent with your own subscription. Available on desktop, mobile and remote runtime.

9.4 KB
Raw Blame
import { createElement } from 'react'
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { AgentJournalRenderItem } from '../../../src/shared/agent-session-journal-types'
import type { StructuredAgentSessionState } from '../../../src/shared/structured-agent-session-reducer'
import type { RpcClient } from '../transport/rpc-client'

const mocks = vi.hoisted(() => ({
  sendRequest: vi.fn(),
  promptResponses: vi.fn(() => ({
    respondPermission: vi.fn(),
    respondQuestion: vi.fn()
  }))
}))
vi.mock('./use-mobile-structured-agent-state', () => ({
  useMobileStructuredAgentState: () => ({
    state,
    stateRef,
    olderPages: 'idle',
    loadEarlier: vi.fn()
  })
}))
vi.mock('./use-mobile-structured-agent-options', () => ({
  useMobileStructuredAgentOptions: () => ({
    conversationCommands: [],
    invokeStructuredOption: vi.fn(),
    optionSnapshot: [],
    optionSurface: { getSnapshot: () => [], subscribe: () => () => {} },
    pendingOptionId: null,
    setStructuredOption: vi.fn()
  })
}))
vi.mock('./use-mobile-structured-prompt-responses', () => ({
  useMobileStructuredPromptResponses: mocks.promptResponses
}))

import { useMobileStructuredAgentSession } from './use-mobile-structured-agent-session'

const pendingApproval = (): AgentJournalRenderItem => ({
  itemId: 'approval-1',
  revision: 4,
  sequence: 2,
  observedAt: 2,
  body: {
    kind: 'approval',
    title: 'Allow Bash?',
    detail: null,
    options: [{ id: 'allow', label: 'Allow' }],
    resolution: {
      state: 'pending',
      selectedOptionId: null,
      resolvedBy: null,
      resolvedAt: null
    }
  }
})

const runningTurn = (): AgentJournalRenderItem => ({
  itemId: 'turn-status',
  revision: 1,
  sequence: 1,
  observedAt: 1,
  body: {
    kind: 'status',
    text: 'Waiting',
    turnLifecycle: { turnId: 'turn-1', state: 'running' }
  }
})

const pendingQuestion = (): AgentJournalRenderItem => ({
  itemId: 'question-1',
  revision: 7,
  sequence: 2,
  observedAt: 2,
  body: {
    kind: 'question',
    question: 'Pick a destination',
    options: [{ id: 'local', label: 'Local' }],
    resolution: {
      state: 'pending',
      selectedOptionId: null,
      resolvedBy: null,
      resolvedAt: null
    }
  }
})

let state: StructuredAgentSessionState
const stateRef = {
  get current(): StructuredAgentSessionState {
    return state
  }
}
const client: RpcClient = {
  sendRequest: mocks.sendRequest,
  subscribe: () => () => {},
  updateTerminalSubscriptionViewport: () => {},
  getState: () => 'connected',
  getReconnectAttempt: () => 0,
  getLastConnectedAt: () => null,
  onStateChange: () => () => {},
  notifyForeground: () => {},
  close: () => {}
}

function Harness({
  promptCancelSupported,
  questionAnswersSupported = false
}: {
  promptCancelSupported: boolean
  questionAnswersSupported?: boolean
}): null {
  hook = useMobileStructuredAgentSession({
    client,
    sessionId: 'session-1',
    sourceIdentity: 'host-a\0workspace-a',
    enabled: true,
    connected: true,
    agent: 'codex',
    hostSupport: {
      promptCancel: promptCancelSupported,
      questionAnswers: questionAnswersSupported,
      queuedMessages: false,
      queuedCommands: false,
      statusFeed: false,
      quietRepeatedStop: false,
      sendOptions: false,
      conversationStop: false,
      permissionModes: false,
      itemDetail: false,
      phoneAttachments: false
    },
    onSendError: vi.fn()
  })
  return null
}

let hook: ReturnType<typeof useMobileStructuredAgentSession>
let renderer: ReactTestRenderer | null = null

describe('mobile structured prompt cancellation', () => {
  beforeEach(() => {
    vi.clearAllMocks()
    state = {
      epoch: 'epoch-1',
      cursor: { epoch: 'epoch-1', sequence: 2 },
      fence: 3,
      items: [runningTurn(), pendingApproval()],
      submissions: [],
      retainedOwnItemLimit: 1024,
      retainedItemCap: 8192,
      hasOlder: false,
      status: 'ready'
    }
    mocks.sendRequest.mockResolvedValue({
      ok: true,
      result: {
        ok: true,
        replayed: false,
        fence: 3,
        cursor: { epoch: 'epoch-1', sequence: 3 },
        value: { turnId: 'turn-1', cancelled: true }
      }
    })
    renderer = null
  })
  afterEach(() => {
    act(() => renderer?.unmount())
    renderer = null
  })

  it('hands question answering the host answers capability', () => {
    act(() => {
      renderer = create(
        createElement(Harness, { promptCancelSupported: false, questionAnswersSupported: true })
      )
    })
    expect(mocks.promptResponses).toHaveBeenLastCalledWith(
      expect.objectContaining({ questionAnswersSupported: true })
    )
  })

  it('sends the clicked prompt identity on capable hosts', async () => {
    act(() => {
      renderer = create(createElement(Harness, { promptCancelSupported: true }))
    })
    await act(async () => {
      expect(await hook.cancelPrompt()).toBe(true)
    })
    expect(mocks.sendRequest).toHaveBeenCalledWith(
      'agentSession.cancel',
      expect.objectContaining({
        turnId: 'turn-1',
        prompt: { itemId: 'approval-1', expectedRevision: 4 }
      }),
      expect.any(Object)
    )
  })

  it('downgrades to turn-only cancellation on an old host', async () => {
    act(() => {
      renderer = create(createElement(Harness, { promptCancelSupported: false }))
    })
    await act(async () => {
      expect(await hook.cancelPrompt()).toBe(true)
    })
    const call = mocks.sendRequest.mock.calls.find(([method]) => method === 'agentSession.cancel')
    expect(call?.[1]).toMatchObject({ turnId: 'turn-1' })
    expect(call?.[1]).not.toHaveProperty('prompt')
  })

  it('cancels a question card with its item identity', async () => {
    state = { ...state, items: [runningTurn(), pendingQuestion()] }
    act(() => {
      renderer = create(createElement(Harness, { promptCancelSupported: true }))
    })
    await act(async () => {
      expect(await hook.cancelPrompt({ itemId: 'question-1', expectedRevision: 7 })).toBe(true)
    })
    expect(mocks.sendRequest).toHaveBeenCalledWith(
      'agentSession.cancel',
      expect.objectContaining({
        turnId: 'turn-1',
        prompt: { itemId: 'question-1', expectedRevision: 7 }
      }),
      expect.any(Object)
    )
  })

  it("stops the host's running turn when its record is not loaded", async () => {
    state = {
      ...state,
      hasOlder: true,
      items: [pendingApproval()],
      latestTurn: {
        itemId: 'turn-status',
        observedAt: 1,
        turn: { turnId: 'turn-1', state: 'running', startedAt: 1 }
      }
    }
    act(() => {
      renderer = create(createElement(Harness, { promptCancelSupported: true }))
    })
    expect(hook.isWorking).toBe(true)
    await act(async () => {
      expect(await hook.cancelPrompt()).toBe(true)
    })
    expect(mocks.sendRequest).toHaveBeenCalledWith(
      'agentSession.cancel',
      expect.objectContaining({
        turnId: 'turn-1',
        prompt: { itemId: 'approval-1', expectedRevision: 4 }
      }),
      expect.any(Object)
    )
  })

  it('reads a turn the host ended as ended, though its running row is still loaded', () => {
    state = {
      ...state,
      latestTurn: {
        itemId: 'turn-status',
        observedAt: 1,
        turn: { turnId: 'turn-1', state: 'completed', startedAt: 1, completedAt: 2 }
      }
    }
    act(() => {
      renderer = create(createElement(Harness, { promptCancelSupported: true }))
    })
    expect(hook.turnId).toBeNull()
  })

  it("reads Working from the host's answer, and from its rows only when an older host gives none", () => {
    state = { ...state, items: [runningTurn()], working: false }
    act(() => {
      renderer = create(createElement(Harness, { promptCancelSupported: true }))
    })
    expect(hook.isWorking).toBe(false)
    act(() => renderer?.unmount())
    const { working: _answered, ...olderHost } = state
    state = olderHost
    act(() => {
      renderer = create(createElement(Harness, { promptCancelSupported: true }))
    })
    expect(hook.isWorking).toBe(true)
  })

  it('uses the rendered prompt identity when the journal changes before tap', async () => {
    act(() => {
      renderer = create(createElement(Harness, { promptCancelSupported: true }))
    })
    const renderedIdentity = { itemId: 'approval-1', expectedRevision: 4 }
    state = {
      ...state,
      items: [runningTurn(), { ...pendingApproval(), itemId: 'approval-new', revision: 9 }]
    }
    await act(async () => {
      expect(await hook.cancelPrompt(renderedIdentity)).toBe(true)
    })
    expect(mocks.sendRequest).toHaveBeenCalledWith(
      'agentSession.cancel',
      expect.objectContaining({ prompt: renderedIdentity }),
      expect.any(Object)
    )
  })

  it("names the host's running turn for a plain Stop when its record is not loaded", async () => {
    state = {
      ...state,
      hasOlder: true,
      items: [],
      latestTurn: {
        itemId: 'turn-status',
        observedAt: 1,
        turn: { turnId: 'turn-1', state: 'running' }
      }
    }
    act(() => {
      renderer = create(createElement(Harness, { promptCancelSupported: true }))
    })
    expect(hook.turnId).toBe('turn-1')
    await act(async () => {
      hook.cancel()
    })
    const call = mocks.sendRequest.mock.calls.find(([method]) => method === 'agentSession.cancel')
    expect(call).toBeDefined()
    expect(call?.[1]).toMatchObject({ turnId: 'turn-1' })
    expect(call?.[1]).not.toHaveProperty('prompt')
  })
})