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.7 KB
Raw Blame
import { describe, expect, it, vi } from 'vitest'
import { LogicalClientCutoverError } from '../transport/stable-logical-rpc-client'
import type { RpcClient } from '../transport/rpc-client'
import type { RpcFailure, RpcResponse, RpcSuccess } from '../transport/types'
import {
  dictationModelRowAction,
  deleteDictationModel,
  downloadDictationModel,
  fetchDictationSetup,
  dictationNeedsSetup,
  isDictationSetupRequiredError,
  dictationFailureMessage,
  isModelInFlight,
  setDictationConfig,
  type MobileSpeechModel,
  type MobileSpeechSetup
} from './mobile-dictation-setup'

function ok(result: unknown): RpcSuccess {
  return { id: 'r', ok: true, result, _meta: { runtimeId: 'rt' } }
}
function fail(message: string): RpcFailure {
  return { id: 'r', ok: false, error: { code: 'x', message }, _meta: { runtimeId: 'rt' } }
}
function malformedFailure(error: { code?: string; message?: string }): RpcResponse {
  // SAFETY: Intentionally omit RPC error fields to exercise older or malformed server replies.
  return { id: 'r', ok: false, error, _meta: { runtimeId: 'rt' } } as unknown as RpcResponse
}

function clientWith(responses: RpcResponse[]): Pick<RpcClient, 'sendRequest'> & {
  calls: Array<{ method: string; params: unknown }>
} {
  const calls: Array<{ method: string; params: unknown }> = []
  return {
    calls,
    sendRequest: vi.fn(async (method: string, params?: unknown) => {
      calls.push({ method, params })
      return responses.shift() ?? fail('unexpected')
    })
  }
}

function model(overrides: Partial<MobileSpeechModel> = {}): MobileSpeechModel {
  return {
    id: 'm1',
    label: 'M1',
    provider: 'local',
    sizeBytes: 100,
    recommended: true,
    status: 'not-downloaded',
    progress: null,
    ...overrides
  }
}

describe('isDictationSetupRequiredError', () => {
  it('matches the setup-required error codes', () => {
    expect(isDictationSetupRequiredError('voice_dictation_disabled')).toBe(true)
    expect(isDictationSetupRequiredError('voice_model_not_selected')).toBe(true)
    expect(isDictationSetupRequiredError('voice_model_not_ready:not-downloaded')).toBe(true)
    expect(isDictationSetupRequiredError('dictation_already_active')).toBe(false)
    expect(isDictationSetupRequiredError('network down')).toBe(false)
  })
})

describe('rpc wrappers', () => {
  it('fetches setup', async () => {
    const setup: MobileSpeechSetup = {
      enabled: false,
      selectedModelId: '',
      dictationMode: 'toggle',
      models: []
    }
    const client = clientWith([ok(setup)])
    await expect(fetchDictationSetup(client)).resolves.toEqual(setup)
    expect(client.calls[0]).toEqual({ method: 'speech.models.list', params: null })
  })

  it('retries the idempotent setup read once after logical-client cutover', async () => {
    const setup: MobileSpeechSetup = {
      enabled: false,
      selectedModelId: '',
      dictationMode: 'toggle',
      models: []
    }
    const sendRequest = vi
      .fn()
      .mockRejectedValueOnce(new LogicalClientCutoverError())
      .mockResolvedValueOnce(ok(setup))

    await expect(fetchDictationSetup({ sendRequest })).resolves.toEqual(setup)
    expect(sendRequest).toHaveBeenCalledTimes(2)
    expect(sendRequest).toHaveBeenNthCalledWith(1, 'speech.models.list', null)
    expect(sendRequest).toHaveBeenNthCalledWith(2, 'speech.models.list', null)
  })

  it('does not retry unrelated setup-read failures', async () => {
    const sendRequest = vi.fn().mockRejectedValue(new Error('offline'))

    await expect(fetchDictationSetup({ sendRequest })).rejects.toThrow('offline')
    expect(sendRequest).toHaveBeenCalledOnce()
  })

  it('starts a download', async () => {
    const client = clientWith([ok({ started: true })])
    await downloadDictationModel(client, 'm1')
    expect(client.calls[0]).toEqual({ method: 'speech.models.download', params: { modelId: 'm1' } })
  })

  it('deletes a model and returns refreshed setup', async () => {
    const setup: MobileSpeechSetup = {
      enabled: true,
      selectedModelId: '',
      dictationMode: 'toggle',
      models: []
    }
    const client = clientWith([ok(setup)])
    await expect(deleteDictationModel(client, 'm1')).resolves.toEqual(setup)
    expect(client.calls[0]).toEqual({ method: 'speech.models.delete', params: { modelId: 'm1' } })
  })

  it('sets config', async () => {
    const setup: MobileSpeechSetup = {
      enabled: true,
      selectedModelId: 'm1',
      dictationMode: 'hold',
      models: []
    }
    const client = clientWith([ok(setup)])
    await expect(setDictationConfig(client, { enabled: true, modelId: 'm1' })).resolves.toEqual(
      setup
    )
    expect(client.calls[0]).toEqual({
      method: 'speech.dictation.setup',
      params: { enabled: true, modelId: 'm1' }
    })
  })

  it('surfaces RPC failures as errors', async () => {
    const client = clientWith([fail('disconnected')])
    await expect(fetchDictationSetup(client)).rejects.toThrow('disconnected')
  })

  it('maps legacy desktop denials to update guidance', async () => {
    const client = clientWith([
      {
        id: 'r',
        ok: false,
        error: {
          code: 'forbidden',
          message: "Method 'speech.models.list' is not available to mobile clients"
        },
        _meta: { runtimeId: 'rt' }
      }
    ])

    await expect(fetchDictationSetup(client)).rejects.toThrow(
      'Update the paired desktop Orca app to use mobile voice settings.'
    )
  })

  it('maps legacy desktop method-not-found failures to update guidance', async () => {
    const client = clientWith([
      malformedFailure({
        code: 'method_not_found',
        message: 'Unknown method: speech.models.list'
      })
    ])

    await expect(fetchDictationSetup(client)).rejects.toThrow(
      'Update the paired desktop Orca app to use mobile voice settings.'
    )
  })

  it('maps a headless server with no speech to update guidance (#31174)', async () => {
    const client = clientWith([
      malformedFailure({
        code: 'runtime_error',
        message: 'speech_unavailable: this host has no speech services'
      })
    ])

    await expect(fetchDictationSetup(client)).rejects.toThrow(
      'Update Orca on this server to use voice dictation.'
    )
  })

  it('recognizes an old server refusing a dictation start', () => {
    expect(dictationFailureMessage('speech_unavailable: this host has no speech services')).toBe(
      'Update Orca on this server to use voice dictation.'
    )
    expect(dictationFailureMessage('voice_dictation_disabled')).toBe('voice_dictation_disabled')
  })

  it('keeps unrelated speech model failures specific', async () => {
    const client = clientWith([
      malformedFailure({
        code: 'internal_error',
        message: 'speech.models.list failed unexpectedly'
      })
    ])

    await expect(fetchDictationSetup(client)).rejects.toThrow(
      'speech.models.list failed unexpectedly'
    )
  })

  it('falls back when runtime failures omit a message', async () => {
    const client = clientWith([malformedFailure({ code: 'internal_error' })])

    await expect(fetchDictationSetup(client)).rejects.toThrow('Failed to load dictation models')
  })
})

describe('dictationModelRowAction', () => {
  it('keeps on-device rows downloadable until they are ready', () => {
    expect(dictationModelRowAction(model({ status: 'not-downloaded' }), '')).toBe('download')
    expect(dictationModelRowAction(model({ status: 'error' }), '')).toBe('download')
    expect(dictationModelRowAction(model({ status: 'downloading' }), '')).toBe('downloading')
    expect(dictationModelRowAction(model({ status: 'ready' }), 'm1')).toBe('in-use')
  })
})

describe('state helpers', () => {
  it('isModelInFlight covers downloading + extracting', () => {
    expect(isModelInFlight(model({ status: 'downloading' }))).toBe(true)
    expect(isModelInFlight(model({ status: 'extracting' }))).toBe(true)
    expect(isModelInFlight(model({ status: 'ready' }))).toBe(false)
  })

  it('dictationNeedsSetup mirrors the host start refusals', () => {
    const setup = (enabled: boolean, selectedModelId: string, models: MobileSpeechModel[]) => ({
      enabled,
      selectedModelId,
      dictationMode: 'toggle' as const,
      models
    })
    expect(dictationNeedsSetup(setup(true, 'm1', [model({ status: 'ready' })]))).toBe(false)
    expect(dictationNeedsSetup(setup(false, 'm1', [model({ status: 'ready' })]))).toBe(true)
    expect(dictationNeedsSetup(setup(true, 'm1', [model({ status: 'not-downloaded' })]))).toBe(true)
    expect(dictationNeedsSetup(setup(true, '', []))).toBe(true)
    // A user model is absent from the host catalog; only the host can judge it.
    expect(dictationNeedsSetup(setup(true, 'custom', [model({ status: 'ready' })]))).toBe(false)
    // Older hosts may omit enabled and the selection.
    expect(dictationNeedsSetup({ dictationMode: 'toggle', models: [] })).toBe(false)
  })
})