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.

8.4 KB
Raw Blame
import type { ReactElement } from 'react'
import { act, create } from 'react-test-renderer'
import type { ReactTestRenderer } from 'react-test-renderer'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { BRIDGE_PROTOCOL_VERSION } from '../mobile-web-shell/bridge/bridge-envelope'
import { BRIDGE_PAGE_CLIENT_ID } from '../mobile-web-shell/bridge/bridge-page-client-identity'
import { createShellPageClient } from '../mobile-web-shell/bridge/page-bootstrap'
import type { BridgeRpcClient } from '../mobile-web-shell/bridge/bridge-rpc-client'
import type { RpcClientContextValue } from './rpc-client-context-contract'

// Mock unused re-exported hooks because their real imports require Expo runtime.
vi.mock('./host-client-hooks', () => ({
  useDisconnectHostClient: () => () => {},
  useForceReconnect: () => null,
  useForgetHostClient: () => () => {},
  useHostClient: () => ({ client: null, clientId: null, state: 'disconnected' }),
  usePrimeHosts: () => () => {},
  useRefreshHostClient: () => () => {}
}))

import { RpcClientProvider, useRpcClientContext } from './client-context.web'

const INIT = {
  v: BRIDGE_PROTOCOL_VERSION,
  type: 'init',
  sessionId: 'session-a',
  buildId: 'build-a',
  connection: {
    state: 'connected',
    reconnectAttempt: 2,
    lastConnectedAt: 1700,
    lastInboundAt: 1800,
    generation: 5
  },
  grants: { rpc: { maxPendingRequests: 64, maxSubscriptions: 32 }, native: [] }
}

const screen: { mounts: number; context: RpcClientContextValue | null } = {
  mounts: 0,
  context: null
}

function Screen(): null {
  screen.context = useRpcClientContext()
  screen.mounts += 1
  return null
}

const trees: ReactTestRenderer[] = []
const clients: BridgeRpcClient[] = []

function mount(client: BridgeRpcClient): ReactTestRenderer {
  const tree = create(render(client))
  trees.push(tree)
  return tree
}

function render(client: BridgeRpcClient): ReactElement {
  return (
    <RpcClientProvider client={client}>
      <Screen />
    </RpcClientProvider>
  )
}

function installChannel(): { deliver: (frame: unknown) => void } {
  const channel: {
    postMessage: (json: string) => void
    onmessage: ((e: { data: string }) => void) | null
  } = {
    postMessage: () => {},
    onmessage: null
  }
  Object.defineProperty(globalThis, 'orcaBridge', { value: channel, configurable: true })
  return {
    deliver: (frame) => {
      channel.onmessage?.({ data: JSON.stringify(frame) })
    }
  }
}

function createReadyClient(
  deliver: (frame: unknown) => void,
  init: unknown = INIT
): BridgeRpcClient {
  const client = createShellPageClient()
  if (client === null) {
    throw new Error('no channel installed')
  }
  clients.push(client)
  deliver(init)
  return client
}

function readContext(): RpcClientContextValue {
  const context = screen.context
  if (context === null) {
    throw new Error('no screen mounted')
  }
  return context
}

beforeEach(() => {
  vi.useFakeTimers()
  screen.mounts = 0
  screen.context = null
})

afterEach(() => {
  act(() => {
    for (const tree of trees.splice(0)) {
      tree.unmount()
    }
  })
  for (const client of clients.splice(0)) {
    client.close()
  }
  vi.restoreAllMocks()
  vi.useRealTimers()
  Reflect.deleteProperty(globalThis, 'orcaBridge')
})

describe('the page provider', () => {
  it('answers every screen with the one client the page has', () => {
    const channel = installChannel()
    const client = createReadyClient(channel.deliver)
    act(() => {
      mount(client)
    })

    expect(screen.mounts).toBe(1)
    const context = readContext()
    expect(context.acquire('host-a', {})).toBe(client)
    expect(context.acquire('host-b', {})).toBe(client)
    expect(context.getAllClients()).toEqual([
      { hostId: 'host-a', client },
      { hostId: 'host-b', client }
    ])
  })

  it('reads the connection the shell primed rather than a state of its own', () => {
    const channel = installChannel()
    const client = createReadyClient(channel.deliver)
    act(() => {
      mount(client)
    })

    const context = readContext()
    expect(context.getState('host-a')).toBe('connected')
    expect(context.getKnownState('host-a')).toBe('connected')
    expect(context.getReconnectAttempt('host-a')).toBe(2)
    expect(context.getLastConnectedAt('host-a')).toBe(1700)
  })

  it('claims the placeholder the shell swaps, never the session id', () => {
    const channel = installChannel()
    const client = createReadyClient(channel.deliver)
    act(() => {
      mount(client)
    })

    // Terminal subscription and send gates require a stable device identity before init/input can open.
    expect(readContext().getClientId('host-a')).toBe(BRIDGE_PAGE_CLIENT_ID)
    expect(readContext().getClientId('host-a')).not.toBe(INIT.sessionId)
  })

  it('keeps the same identity across a remount, so a resent message keeps its caller', () => {
    const channel = installChannel()
    const client = createReadyClient(channel.deliver)
    act(() => {
      mount(client)
    })
    const first = readContext().getClientId('host-a')

    // Keep caller identity across shell remounts; changing it permanently refuses retained composer journal sends.
    act(() => {
      for (const tree of trees.splice(0)) {
        tree.unmount()
      }
    })
    client.close()
    const nextChannel = installChannel()
    act(() => {
      mount(createReadyClient(nextChannel.deliver, { ...INIT, sessionId: 'session-b' }))
    })

    expect(readContext().getClientId('host-a')).toBe(first)
    expect(first).toBe(BRIDGE_PAGE_CLIENT_ID)
  })

  it('carries a state change from the shell to the screens watching it', () => {
    const channel = installChannel()
    const client = createReadyClient(channel.deliver)
    act(() => {
      mount(client)
    })
    const listener = vi.fn()
    readContext().subscribeHostState('host-a', listener)

    act(() => {
      channel.deliver({
        v: BRIDGE_PROTOCOL_VERSION,
        type: 'state',
        connection: { ...INIT.connection, state: 'reconnecting' }
      })
    })

    expect(listener).toHaveBeenCalledWith('reconnecting')
    expect(readContext().getState('host-a')).toBe('reconnecting')
  })

  it('wakes a screen watching every host on the same change', () => {
    const channel = installChannel()
    const client = createReadyClient(channel.deliver)
    act(() => {
      mount(client)
    })
    const listener = vi.fn()
    const unsubscribe = readContext().subscribeAllHosts(listener)

    act(() => {
      channel.deliver({
        v: BRIDGE_PROTOCOL_VERSION,
        type: 'state',
        connection: { ...INIT.connection, state: 'reconnecting' }
      })
    })

    expect(listener).toHaveBeenCalledTimes(1)
    unsubscribe()
    act(() => {
      channel.deliver({
        v: BRIDGE_PROTOCOL_VERSION,
        type: 'state',
        connection: { ...INIT.connection, state: 'disconnected' }
      })
    })
    expect(listener).toHaveBeenCalledTimes(1)
  })

  it('stops listening when the screen that asked goes away', () => {
    const channel = installChannel()
    const client = createReadyClient(channel.deliver)
    act(() => {
      mount(client)
    })
    const listener = vi.fn()
    const unsubscribe = readContext().subscribeHostState('host-a', listener)
    unsubscribe()

    act(() => {
      channel.deliver({
        v: BRIDGE_PROTOCOL_VERSION,
        type: 'state',
        connection: { ...INIT.connection, state: 'reconnecting' }
      })
    })

    expect(listener).not.toHaveBeenCalled()
  })

  it('never closes, drops or re-dials the connection the shell owns', async () => {
    const channel = installChannel()
    const client = createReadyClient(channel.deliver)
    const close = vi.spyOn(client, 'close')
    act(() => {
      mount(client)
    })

    const context = readContext()
    expect(context.acquire('host-a', {})).toBe(client)
    context.release('host-a', {})
    context.releaseAndCloseIfUnused('host-a', {})
    context.closeIfUnused('host-a')
    context.disconnectHostClient('host-a')
    context.forgetHostClient('host-a')
    context.refreshHostClient('host-a')

    expect(close).not.toHaveBeenCalled()
    expect(context.acquire('host-a', {})).toBe(client)
  })

  it('offers no re-dial at all, so no screen can wire a Retry to one', () => {
    // Null hides Retry/Reconnect; a no-op callback would expose controls the page cannot fulfill.
    const channel = installChannel()
    act(() => {
      mount(createReadyClient(channel.deliver))
    })
    expect(readContext().forceReconnect).toBeNull()
  })
})