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.

11.5 KB
Raw Blame
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const fakes = vi.hoisted(() => ({
  linkOptions: null as null | {
    onHello(value: unknown): void
    onAuthenticated(): void
    onText(value: string): void
    onBinary(value: Uint8Array): void
  },
  sendText: vi.fn((_frame: string) => true),
  close: vi.fn()
}))

vi.mock('./mobile-relay-e2ee-link', () => ({
  MobileRelayE2eeLink: class {
    constructor(options: NonNullable<typeof fakes.linkOptions>) {
      fakes.linkOptions = options
    }
    sendText = fakes.sendText
    close = fakes.close
  }
}))

import { connectMobileRelayRpcSession } from './mobile-relay-rpc-session'
import { RelayReconnectController } from './mobile-relay-reconnect-controller'
import { createStableLogicalRpcClient } from './stable-logical-rpc-client'
import type { ConnectionLogSink } from './types'

const relay = {
  v: 1 as const,
  directorUrl: 'https://relay.onorca.dev',
  cellUrl: 'https://relay-c1.onorca.dev',
  assignmentEpoch: 7,
  relayHostId: 'AbCdEf0123_-xyZ9',
  e2eeFraming: 2 as const
}

async function authenticateSession(onLog?: ConnectionLogSink) {
  const session = connectMobileRelayRpcSession({
    relay,
    resumeToken: 'resume-secret',
    resumeCredentialVersion: 3,
    resumeConfirmReqId: 'confirm-1',
    deviceToken: 'device-token',
    desktopPublicKeyB64: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=',
    requestTimeoutMs: 30_000,
    onLog
  })
  fakes.linkOptions!.onHello({
    type: 'relay-hello',
    ok: true,
    credentialKind: 'resume',
    leaseExpiresAt: Date.now() + 60_000,
    acceptedCredentialVersion: 3,
    acceptedAs: 'current',
    resumeExpiresAt: Date.now() + 300_000
  })
  fakes.linkOptions!.onAuthenticated()
  await vi.waitFor(() => expect(fakes.sendText).toHaveBeenCalledOnce())
  const confirmation = sentRequests()[0]!
  expect(confirmation).toMatchObject({
    method: 'pairing.getEndpoints',
    params: { resumeConfirmReqId: 'confirm-1' },
    deviceToken: 'device-token'
  })
  fakes.linkOptions!.onText(
    JSON.stringify({
      id: confirmation.id,
      ok: true,
      result: {
        v: 1,
        relay,
        resumeConfirmation: {
          v: 1,
          reqId: 'confirm-1',
          currentVersion: 3,
          acceptedAs: 'current',
          renewed: true,
          resumeExpiresAt: Date.now() + 300_000
        }
      },
      _meta: { runtimeId: 'runtime-1' }
    })
  )
  await vi.waitFor(() => expect(fakes.sendText).toHaveBeenCalledTimes(2))
  const capabilities = sentRequests()[1]!
  expect(capabilities).toMatchObject({
    method: 'runtime.clientCapabilities.update',
    params: { clientCapabilities: expect.arrayContaining(['agent-session.structured.v1']) },
    deviceToken: 'device-token'
  })
  fakes.linkOptions!.onText(
    JSON.stringify({
      id: capabilities.id,
      ok: true,
      result: {},
      _meta: { runtimeId: 'runtime-1' }
    })
  )
  await vi.waitFor(() => expect(session.getState()).toBe('connected'))
  fakes.sendText.mockClear()
  return session
}

function sentRequests() {
  return fakes.sendText.mock.calls.map(([value]) => {
    const request: unknown = JSON.parse(value)
    if (
      !request ||
      typeof request !== 'object' ||
      !('id' in request) ||
      typeof request.id !== 'string' ||
      !('method' in request) ||
      typeof request.method !== 'string'
    ) {
      throw new Error('Expected a serialized RPC request')
    }
    return request
  })
}

describe('mobile relay RPC session liveness', () => {
  beforeEach(() => {
    vi.useFakeTimers()
    vi.clearAllMocks()
    fakes.linkOptions = null
    fakes.sendText.mockReturnValue(true)
  })
  afterEach(() => vi.useRealTimers())

  it('sends no periodic traffic while an authenticated relay is idle', async () => {
    const session = await authenticateSession()

    await vi.advanceTimersByTimeAsync(60_000)

    expect(fakes.sendText).not.toHaveBeenCalled()
    expect(session.getState()).toBe('connected')
    session.close()
  })

  it('disconnects after two fair foreground misses', async () => {
    const onLog = vi.fn<ConnectionLogSink>()
    const session = await authenticateSession(onLog)

    session.notifyForeground('focus')
    expect(sentRequests().map(({ method }) => method)).toEqual(['status.get'])
    await vi.advanceTimersByTimeAsync(4_000)
    expect(session.getState()).toBe('connected')
    expect(fakes.sendText).toHaveBeenCalledTimes(2)
    await vi.advanceTimersByTimeAsync(4_000)

    expect(session.getState()).toBe('disconnected')
    expect(fakes.close).toHaveBeenCalledOnce()
    expect(onLog).toHaveBeenCalledWith(
      expect.objectContaining({
        code: 'liveness-timeout',
        path: 'relay',
        message: 'Relay health check failed',
        detail: expect.stringMatching(
          /^probe-timeout; 2\/2 probes missed; last authenticated activity \d+ms ago$/
        )
      })
    )
  })

  it('uses distinct liveness evidence IDs for sessions created in the same millisecond', async () => {
    vi.setSystemTime(1_000)
    const firstLog = vi.fn<ConnectionLogSink>()
    const first = await authenticateSession(firstLog)
    first.notifyForeground('focus')
    await vi.advanceTimersByTimeAsync(8_000)
    const firstId = firstLog.mock.calls[0]?.[0].id

    vi.clearAllMocks()
    fakes.sendText.mockReturnValue(true)
    vi.setSystemTime(1_000)
    const secondLog = vi.fn<ConnectionLogSink>()
    const second = await authenticateSession(secondLog)
    second.notifyForeground('focus')
    await vi.advanceTimersByTimeAsync(8_000)
    const secondId = secondLog.mock.calls[0]?.[0].id

    expect(firstId).toBeTruthy()
    expect(secondId).toBeTruthy()
    expect(secondId).not.toBe(firstId)
  })

  it('rate-limits foreground sequences without suppressing a retry', async () => {
    const session = await authenticateSession()
    session.notifyForeground('focus')
    const firstProbe = sentRequests()[0]!
    fakes.linkOptions!.onText(
      JSON.stringify({ id: firstProbe.id, ok: true, result: {}, _meta: { runtimeId: 'r1' } })
    )

    session.notifyForeground('focus')
    await vi.advanceTimersByTimeAsync(9_999)
    session.notifyForeground('focus')
    expect(fakes.sendText).toHaveBeenCalledOnce()
    await vi.advanceTimersByTimeAsync(1)
    session.notifyForeground('focus')

    expect(fakes.sendText).toHaveBeenCalledTimes(2)
    session.close()
  })

  it('checks a relay on network hints and ends a silent session after one 4s miss', async () => {
    const session = await authenticateSession()

    session.notifyForeground('network-change')

    expect(sentRequests().map(({ method }) => method)).toEqual(['status.get'])
    await vi.advanceTimersByTimeAsync(3_000)
    session.notifyForeground('network-change')
    await vi.advanceTimersByTimeAsync(1_000)
    expect(session.getState()).toBe('disconnected')
    session.close()
  })

  it('does not probe when work follows prolonged inbound silence', async () => {
    const session = await authenticateSession()
    await vi.advanceTimersByTimeAsync(60_000)

    const pending = session.sendRequest('terminal.send', { terminal: 'term', text: 'hi' })
    const outcome = pending.catch(() => undefined)
    session.subscribe('terminal.subscribe', { terminal: 'term' }, vi.fn())
    await vi.advanceTimersByTimeAsync(0)

    expect(sentRequests().map(({ method }) => method)).toEqual([
      'terminal.send',
      'terminal.subscribe'
    ])
    session.close()
    await outcome
  })

  it('fails immediately when a liveness probe cannot be written', async () => {
    const session = await authenticateSession()
    fakes.sendText.mockReturnValue(false)

    session.notifyForeground('focus')

    expect(session.getState()).toBe('disconnected')
    expect(fakes.close).toHaveBeenCalledOnce()
  })

  it('probes for a caller that stopped hearing back, even inside the foreground cooldown', async () => {
    const session = await authenticateSession()
    session.notifyForeground('focus')
    const firstProbe = sentRequests()[0]!
    fakes.linkOptions!.onText(
      JSON.stringify({ id: firstProbe.id, ok: true, result: {}, _meta: { runtimeId: 'r1' } })
    )

    // Just heard from, so not suspect yet.
    session.probeLivenessNow?.()
    expect(fakes.sendText).toHaveBeenCalledOnce()
    await vi.advanceTimersByTimeAsync(4_000)
    session.probeLivenessNow?.()
    expect(fakes.sendText).toHaveBeenCalledTimes(2)
    await vi.advanceTimersByTimeAsync(4_000)

    expect(session.getState()).toBe('disconnected')
  })

  it('redials after one 4s miss when a retained relay returns from the background', async () => {
    const onLog = vi.fn<ConnectionLogSink>()
    const session = await authenticateSession(onLog)

    session.notifyForeground('app-resume')
    expect(sentRequests().map(({ method }) => method)).toEqual(['status.get'])
    await vi.advanceTimersByTimeAsync(3_999)
    expect(session.getState()).toBe('connected')
    await vi.advanceTimersByTimeAsync(1)

    expect(session.getState()).toBe('disconnected')
    expect(fakes.sendText).toHaveBeenCalledOnce()
    expect(onLog).toHaveBeenCalledWith(
      expect.objectContaining({
        code: 'liveness-timeout',
        detail: expect.stringMatching(/^probe-timeout; 1\/1 probes missed;/)
      })
    )
  })

  it('checks a distinct background return after a recently answered network probe', async () => {
    const session = await authenticateSession()
    session.notifyForeground('network-change')
    const probe = sentRequests()[0]
    if (!probe || !fakes.linkOptions) {
      throw new Error('Expected an active relay probe')
    }
    fakes.linkOptions.onText(
      JSON.stringify({ id: probe.id, ok: true, result: {}, _meta: { runtimeId: 'r1' } })
    )
    await vi.advanceTimersByTimeAsync(1_000)

    session.notifyForeground('app-resume')
    await vi.advanceTimersByTimeAsync(3_999)
    expect(session.getState()).toBe('connected')
    await vi.advanceTimersByTimeAsync(1)
    expect(session.getState()).toBe('disconnected')
  })

  it('keeps availability returns tolerant while a proven resume bypasses recent probes', async () => {
    const session = await authenticateSession()
    const logical = createStableLogicalRpcClient(session, 'relay')
    const controller = new RelayReconnectController(
      {
        now: Date.now,
        randomBytes: (length) => new Uint8Array(length),
        setTimer: (callback, delay) => setTimeout(callback, delay),
        clearTimer: clearTimeout
      },
      vi.fn()
    )
    controller.setActiveSession(session)
    session.notifyForeground('focus')
    const probe = sentRequests()[0]
    if (!probe || !fakes.linkOptions) {
      throw new Error('Expected the focus probe')
    }
    fakes.linkOptions.onText(JSON.stringify({ id: probe.id, ok: true, result: {} }))
    await vi.advanceTimersByTimeAsync(1_000)

    // The lifecycle boolean also becomes false during an inactive-only iOS interruption.
    controller.handleForeground(logical, false)
    await vi.advanceTimersByTimeAsync(4_000)
    expect(session.getState()).toBe('connected')
    expect(fakes.sendText).toHaveBeenCalledOnce()

    logical.notifyForeground('app-resume')
    await vi.advanceTimersByTimeAsync(4_000)
    expect(session.getState()).toBe('disconnected')
    controller.clear()
    logical.close()
  })

  it('keeps a relay that answers the background-return probe', async () => {
    const session = await authenticateSession()

    session.notifyForeground('app-resume')
    const probe = sentRequests()[0]!
    fakes.linkOptions!.onText(
      JSON.stringify({ id: probe.id, ok: true, result: {}, _meta: { runtimeId: 'r1' } })
    )
    await vi.advanceTimersByTimeAsync(60_000)

    expect(session.getState()).toBe('connected')
    session.close()
  })
})