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.

14.5 KB
Raw Blame
import { resolveMobileNativeChatRowProps } from './native-chat/transcript/use-mobile-native-chat-row-props'
import { MobileNativeChatRow } from './native-chat/transcript/MobileNativeChatRowItemSource'
// Compare live merged hooks/list output after every frame with a newly opened chat, including own echoes and host Stopping. Native row rendering, controller input construction and reconnects are outside this proof.

import { createElement, isValidElement, type ReactElement, type ReactNode } from 'react'
import { act, create, type ReactTestInstance, type ReactTestRenderer } from 'react-test-renderer'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type {
  AgentSessionStatusEvent,
  AgentSessionSubscribeEvent
} from '../../../src/shared/agent-session-wire'
import type { NativeChatMessage } from '../../../src/shared/native-chat-types'
import { STRUCTURED_AGENT_SESSION_CLIENT_COALESCE_MS } from '../../../src/shared/structured-agent-session-coalescer'
import type { RpcClient } from '../transport/rpc-client'
import { MobileNativeChatOverlay } from './MobileNativeChatOverlay'
import { MobileNativeChatView } from './MobileNativeChatView'
import {
  NEVER_OPENED,
  STOP_JOURNAL_SESSION,
  stopJournal
} from './mobile-native-chat-stop-journal.test-fixture'
import { useMobileNativeChatDrafts } from './native-chat/composer/use-mobile-native-chat-drafts'
import type { MobileNativeChatController } from './mobile-native-chat-controller-contract'
import { useMobileStructuredAgentSession } from './use-mobile-structured-agent-session'

vi.mock('@react-native-async-storage/async-storage', () => ({
  default: { getItem: vi.fn(async () => null), setItem: vi.fn(), removeItem: vi.fn() }
}))
vi.mock('react-native', async () => {
  const React = await import('react')
  return {
    ActivityIndicator: 'ActivityIndicator',
    FlatList: React.forwardRef((props, ref) => {
      React.useImperativeHandle(ref, () => ({ scrollToEnd: vi.fn(), scrollToOffset: vi.fn() }), [])
      return React.createElement('FlatList', props)
    }),
    Platform: { OS: 'ios' },
    Pressable: 'Pressable',
    StyleSheet: { create: (styles: unknown) => styles, hairlineWidth: 1, absoluteFillObject: {} },
    Text: 'Text',
    View: 'View'
  }
})
vi.mock('../platform/use-reduced-motion', () => ({ useReducedMotionEnabled: () => null }))
vi.mock('react-native-safe-area-context', () => ({
  useSafeAreaInsets: () => ({ top: 0, bottom: 0, left: 0, right: 0 })
}))
vi.mock('react-native-gesture-handler', () => {
  const chain = { runOnJS: () => chain, onStart: () => chain, onUpdate: () => chain }
  return {
    Gesture: { Simultaneous: () => ({}), Native: () => ({}), Pinch: () => chain },
    GestureDetector: 'GestureDetector',
    GestureHandlerRootView: 'GestureHandlerRootView'
  }
})
vi.mock('lucide-react-native', () => ({
  ArrowDown: 'ArrowDown',
  ChevronsDownUp: 'ChevronsDownUp',
  ChevronsUpDown: 'ChevronsUpDown',
  Square: 'Square'
}))
vi.mock('./native-chat/transcript/MobileNativeChatMessage', () => ({
  MobileNativeChatMessage: 'ChatMessage'
}))
vi.mock('./native-chat/transcript/MobileNativeChatMessageActionsSheet', () => ({
  MobileNativeChatMessageActionsSheet: 'MessageActionsSheet'
}))
vi.mock('./native-chat/transcript/MobileNativeChatLiveLine', () => ({
  MobileNativeChatLiveLine: 'LiveStatus'
}))
vi.mock('./native-chat/composer/MobileNativeChatComposer', () => ({
  MobileNativeChatDraftComposer: 'Composer'
}))
vi.mock('./native-chat/input/MobileNativeChatQueuedMessages', () => ({
  MobileNativeChatQueuedMessages: 'Queued'
}))
vi.mock('./native-chat/visual/MobileNativeChatVisual', () => ({
  useMobileNativeChatVisualRenderer: () => null
}))
vi.mock('../components/ActionSheetModal', () => ({ ActionSheetModal: 'ActionSheetModal' }))
vi.mock('./native-chat/input/MobileNativeChatAsk', () => ({ MobileNativeChatAsk: 'ChatAsk' }))
vi.mock('./native-chat/input/MobileNativeChatPermission', () => ({
  MobileNativeChatPermission: 'ChatPermission'
}))
vi.mock('./native-chat/input/MobileNativeChatQuestion', () => ({
  MobileNativeChatQuestion: 'ChatQuestion'
}))

const STOP_ROW = `stopped-before-start:orca:${NEVER_OPENED}`

// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the overlay reads only these members of the image attachments, none of which this test exercises.
const OVERLAY_IMAGES = {
  sendNativeChat: async () => true,
  attachImage: async () => {},
  attachments: [],
  removeAttachment: () => {},
  isAttaching: false
} as unknown as Parameters<typeof MobileNativeChatOverlay>[0]['images']

const HOST_SUPPORT = {
  promptCancel: true,
  questionAnswers: true,
  queuedMessages: true,
  queuedCommands: false,
  statusFeed: true,
  quietRepeatedStop: true,
  sendOptions: false,
  conversationStop: false,
  permissionModes: false,
  itemDetail: false,
  phoneAttachments: false
}

type Phone = {
  renderer: ReactTestRenderer
  transcript: (event: AgentSessionSubscribeEvent) => void
  status: (stopping: boolean) => void
  send: () => void
  read: () => string
  listed: () => string[]
  // Detect duplicate keys and arrays mutated in place after being passed to the list.
  listFaults: string[]
}

type DrawnRowProps = {
  message: NativeChatMessage
  turnStatus: { workedSeconds: number | null } | null
  activeTurnIsWorking: boolean
}

function drawnRow(row: ReactNode): unknown {
  if (!isValidElement<DrawnRowProps & Parameters<typeof MobileNativeChatRow>[0]>(row)) {
    return row ?? null
  }
  const { message, turnStatus, activeTurnIsWorking } =
    row.type === MobileNativeChatRow
      ? resolveMobileNativeChatRowProps(row.props.index, row.props.message, row.props.lookups)
      : row.props
  const bar = turnStatus === null ? '-' : (turnStatus.workedSeconds ?? 'live')
  return [
    message.id,
    message.role,
    message.stoppedBeforeStart === true,
    message.blocks,
    bar,
    activeTurnIsWorking
  ]
}

function drawnFooter(node: ReactNode): unknown {
  if (Array.isArray(node)) {
    return node.map(drawnFooter)
  }
  if (!isValidElement<{ children?: ReactNode; line?: { stopping?: boolean } }>(node)) {
    return node ?? null
  }
  const element: ReactElement<{ children?: ReactNode; line?: { stopping?: boolean } }> = node
  if (element.type === 'LiveStatus') {
    return ['live', element.props.line?.stopping === true]
  }
  return element.type === 'ChatMessage' || element.type === MobileNativeChatRow
    ? drawnRow(element)
    : drawnFooter(element.props.children)
}

const mounted: ReactTestRenderer[] = []
afterEach(() => {
  for (const renderer of mounted.splice(0)) {
    act(() => renderer.unmount())
  }
})

async function mountPhone(): Promise<Phone> {
  const listeners = new Map<string, (value: unknown) => void>()
  const client: RpcClient = {
    sendRequest: async () => ({
      id: 'request',
      ok: true,
      result: {},
      _meta: { runtimeId: 'runtime' }
    }),
    subscribe: (method, _params, onData) => {
      listeners.set(method, onData)
      return () => {}
    },
    updateTerminalSubscriptionViewport: () => {},
    getState: () => 'connected',
    getReconnectAttempt: () => 0,
    getLastConnectedAt: () => null,
    onStateChange: () => () => {},
    notifyForeground: () => {},
    close: () => {}
  }
  let latest: ReturnType<typeof useMobileNativeChatDrafts> | null = null
  function Harness(): ReturnType<typeof createElement> {
    const session = useMobileStructuredAgentSession({
      client,
      sessionId: STOP_JOURNAL_SESSION,
      sourceIdentity: 'host\0workspace',
      enabled: true,
      connected: true,
      agent: 'codex',
      hostSupport: HOST_SUPPORT,
      onSendError: () => {}
    })
    const drafts = useMobileNativeChatDrafts({
      hostId: 'host',
      worktreeId: 'workspace',
      tabId: 'tab',
      sessionId: STOP_JOURNAL_SESSION,
      messages: session.session.messages,
      transcriptSettled: session.session.status === 'ready'
    })
    latest = drafts
    // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: every member the list's rows, bars and footer read comes from the two hooks above, as the controller passes them; showNativeChat, nativeChatAgent, nativeChatCanStop, nativeChatStructured are constants; the overlay's other members stay undefined: the composer's and Stop's handlers, files and options never reach the list, the streaming text is undefined on a structured tab too, and the prompts, which would hide the live status, are absent in this flow.
    const controller = {
      showNativeChat: true,
      nativeChatSession: session.session,
      nativeChatAgent: 'codex',
      nativeChatCanStop: false,
      nativeChatStructured: true,
      nativeChatTurnIndicator: session.turnIndicator,
      nativeChatWorkingStartedAt: session.workingStartedAt,
      nativeChatSettledTurns: session.settledTurns,
      nativeChatTurnJournal: session.turnJournal,
      nativeChatTurnActive: session.isWorking,
      chatPending: drafts.pending,
      chatImagePreviewsByMessageId: drafts.imagePreviewsByMessageId,
      chatDraftKey: drafts.draftKey,
      setChatComposerText: drafts.setComposerText,
      getChatComposerEditGeneration: drafts.getComposerEditGeneration,
      nativeChatQueued: session.queued
    } as unknown as MobileNativeChatController
    return createElement(MobileNativeChatOverlay, {
      controller,
      onOpenFile: () => {},
      images: OVERLAY_IMAGES,
      onMicPress: () => {},
      micActive: false,
      micStarting: false,
      micProcessing: false,
      dictationMode: 'toggle',
      onMicPressIn: () => {},
      onMicPressOut: () => {},
      inputLockReason: null,
      sendErrorMessage: null,
      onClearSendError: () => {},
      sendSurfaceId: 'host\0workspace\0tab',
      sessionId: null,
      getSendCompletionGeneration: () => 0,
      keyboardInset: 0,
      hostName: null
    })
  }
  let renderer: ReactTestRenderer | null = null
  await act(async () => {
    renderer = create(createElement(Harness))
  })
  const listFaults: string[] = []
  let handed: { data: unknown; ids: string } | null = null
  const flatList = (): { data: NativeChatMessage[]; props: ReactTestInstance['props'] } => {
    const props = renderer!.root.find((node) => String(node.type) === 'FlatList').props
    const data: NativeChatMessage[] = props.data
    const ids = data.map((row) => row.id).join(',')
    const keys = data.map((row, index) => props.keyExtractor(row, index))
    if (new Set(keys).size !== keys.length) {
      listFaults.push(`colliding keys: ${keys.join(',')}`)
    }
    if (handed && handed.data === data && handed.ids !== ids) {
      listFaults.push(`changed rows in the same array: ${ids}`)
    }
    handed = { data, ids }
    return { data, props }
  }
  mounted.push(renderer!)
  await vi.waitFor(() => expect(listeners.get('agentSession.subscribe')).toBeDefined())
  await vi.waitFor(() => expect(listeners.get('agentSession.subscribeStatus')).toBeDefined())
  return {
    renderer: renderer!,
    transcript: (event) =>
      act(() => {
        listeners.get('agentSession.subscribe')!(structuredClone(event))
        vi.advanceTimersByTime(STRUCTURED_AGENT_SESSION_CLIENT_COALESCE_MS)
      }),
    status: (stopping) => {
      const event: AgentSessionStatusEvent = {
        type: 'status',
        session: {
          sessionId: STOP_JOURNAL_SESSION,
          workspaceId: 'workspace',
          agent: 'codex',
          status: stopping ? 'working' : 'idle',
          latestPrompt: '',
          updatedAt: 0,
          ...(stopping ? { stopping: true } : {})
        }
      }
      act(() => listeners.get('agentSession.subscribeStatus')!(event))
    },
    send: () => {
      const origin = latest!.captureSendOrigin(NEVER_OPENED)!
      act(() => latest!.acceptSend(origin, NEVER_OPENED))
    },
    read: () => {
      const view = renderer!.root.findByType(MobileNativeChatView).props
      const { data, props } = flatList()
      const renderRow: (row: { item: NativeChatMessage; index: number }) => ReactNode =
        props.renderItem
      return JSON.stringify({
        working: view.agentWorking,
        stopping: view.turnIndicator.stopping,
        rows: data.map((item, index) => drawnRow(renderRow({ item, index }))),
        footer: drawnFooter(props.ListFooterComponent)
      })
    },
    listed: () => flatList().data.map((row) => row.id),
    listFaults
  }
}

describe("the phone's hooks, from merged frames and from a fresh snapshot", () => {
  beforeEach(() => {
    vi.useFakeTimers()
  })
  afterEach(() => {
    vi.useRealTimers()
  })

  const journal = stopJournal(8)
  const last = journal.rows.length
  const stoppingAt = (upTo: number): boolean =>
    journal.stopping.some((window) => upTo >= window.from && upTo <= window.until)

  const lastRemoval = journal.rows.findLast(
    (row) => row.kind === 'tombstone' && row.stopEvent === undefined
  )!.seq

  // Subscribe around the last dropped status, Stop-held turn, and never-opened send.
  it.each([lastRemoval - 3, journal.neverOpenedSent - 30, journal.neverOpenedSent - 1])(
    'show the same list after every frame, subscribed at row %i',
    async (start) => {
      const live = await mountPhone()
      live.transcript(journal.snapshotAt(start))
      live.status(stoppingAt(start))
      let cursor = { epoch: 'epoch-1', sequence: start }
      let fence = journal.fenceAt(start)
      const differing: string[] = []
      for (let upTo = start + 1; upTo <= last; upTo += 1) {
        if (upTo === journal.neverOpenedSent) {
          live.send()
          expect(live.read()).toContain('"pending-')
        }
        for (const event of journal.framesTo({ cursor, fence }, upTo)) {
          live.transcript(event)
          fence = event.type === 'end' ? fence : (event.fence ?? fence)
        }
        cursor = { epoch: 'epoch-1', sequence: upTo }
        live.status(stoppingAt(upTo))
        if (upTo === journal.takenBack - 1) {
          expect(live.read()).toContain('"stopping":true')
        }
        const fresh = await mountPhone()
        fresh.transcript(journal.snapshotAt(upTo))
        fresh.status(stoppingAt(upTo))
        if (live.read() !== fresh.read()) {
          differing.push(`frame through ${upTo}`)
        }
        differing.push(...live.listFaults.splice(0), ...fresh.listFaults.splice(0))
        if (upTo >= journal.takenBack && !live.listed().includes(STOP_ROW)) {
          differing.push(`no stop row in the merged list through ${upTo}`)
        }
        if (upTo >= journal.takenBack && !fresh.listed().includes(STOP_ROW)) {
          differing.push(`no stop row in the fresh list at ${upTo}`)
        }
        act(() => fresh.renderer.unmount())
        mounted.splice(mounted.indexOf(fresh.renderer), 1)
      }
      expect(differing).toEqual([])
    },
    60_000
  )
})