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.5 KB
Raw Blame
import { describe, expect, it, vi } from 'vitest'
import type { RpcClient } from '../transport/rpc-client'
import type { RpcResponse, RpcSuccess } from '../transport/types'
import { attachMobileImageToTerminal } from './mobile-image-attachment'

function ok(id: string, result: unknown): RpcSuccess {
  return { id, ok: true, result, _meta: { runtimeId: 'runtime-1' } }
}

function clientWithResponses(responses: RpcResponse[]): Pick<RpcClient, 'sendRequest'> & {
  calls: { method: string; params: unknown }[]
} {
  const calls: { method: string; params: unknown }[] = []
  return {
    calls,
    sendRequest: vi.fn(async (method: string, params?: unknown) => {
      calls.push({ method, params })
      const response = responses.shift()
      if (!response) {
        throw new Error(`unexpected request: ${method}`)
      }
      return response
    })
  }
}

describe('attachMobileImageToTerminal', () => {
  it.each([null, 'unknown', 'codex'])(
    'uploads an image as an attachment path when terminal agent is %s',
    async (agent) => {
      const client = clientWithResponses([
        ok('start', { uploadId: 'upload-1' }),
        ok('append', { receivedBase64Length: 4 }),
        ok('commit', '/tmp/codex-shot.png'),
        ok('send', { send: { accepted: true } })
      ])

      expect(
        await attachMobileImageToTerminal('library', {
          client,
          agent,
          terminal: 'codex-term',
          deviceToken: null,
          getConnectionId: async () => 'connection-ssh',
          pickImage: async () => ({ base64: 'AAAA' })
        })
      ).toBe(true)
      expect(
        client.calls.find((call) => call.method === 'clipboard.startImageUpload')?.params
      ).toMatchObject({ connectionId: 'connection-ssh' })
      expect(client.calls.at(-1)).toEqual({
        method: 'terminal.send',
        params: {
          terminal: 'codex-term',
          text: '\x1b[200~/tmp/codex-shot.png\x1b[201~ ',
          enter: false
        }
      })
    }
  )

  it('keeps the captured OMP format while the picker is pending', async () => {
    const client = clientWithResponses([
      {
        id: 'start',
        ok: false,
        error: { code: 'method_not_found', message: 'no' },
        _meta: { runtimeId: 'r' }
      },
      ok('save', '/tmp/my image.png'),
      ok('send', { send: { accepted: true } })
    ])
    let resolvePick!: (value: { base64: string }) => void
    const deps = {
      client,
      terminal: 'omp-term',
      agent: 'omp',
      deviceToken: null,
      getConnectionId: async () => null,
      pickImage: () =>
        new Promise<{ base64: string }>((resolve) => {
          resolvePick = resolve
        })
    }
    const pending = attachMobileImageToTerminal('library', deps)
    deps.agent = 'claude'
    deps.terminal = 'other-term'
    resolvePick({ base64: 'AAAA' })
    expect(await pending).toBe(true)
    expect(client.calls.find((call) => call.method === 'terminal.send')?.params).toMatchObject({
      terminal: 'omp-term',
      text: '\x1b[200~@"/tmp/my image.png"\x1b[201~ ',
      enter: false
    })
  })

  it('uploads the picked image and pastes its bracketed path into the terminal', async () => {
    const client = clientWithResponses([
      {
        id: 'start',
        ok: false,
        error: { code: 'method_not_found', message: 'no' },
        _meta: { runtimeId: 'r' }
      },
      ok('save', '/tmp/orca-attach.png'),
      ok('send', { send: { accepted: true } })
    ])

    const sent = await attachMobileImageToTerminal('library', {
      client,
      agent: 'claude',
      terminal: 'term-1',
      deviceToken: 'device-9',
      getConnectionId: async () => 'conn-7',
      pickImage: vi.fn().mockResolvedValue({ base64: 'AAAA' })
    })

    expect(sent).toBe(true)
    const sendCall = client.calls.find((c) => c.method === 'terminal.send')
    expect(sendCall?.params).toEqual({
      terminal: 'term-1',
      // A separator prevents the next keystroke gluing to the pasted image path.
      text: '\x1b[200~/tmp/orca-attach.png\x1b[201~ ',
      enter: false,
      client: { id: 'device-9', type: 'mobile' }
    })
  })

  it('uploads the selected image bytes with the active worktree connectionId', async () => {
    const client = clientWithResponses([
      {
        id: 'start',
        ok: false,
        error: { code: 'method_not_found', message: 'no' },
        _meta: { runtimeId: 'r' }
      },
      ok('save', '/tmp/x.png'),
      ok('send', { send: { accepted: true } })
    ])

    await attachMobileImageToTerminal('files', {
      client,
      agent: 'claude',
      terminal: 'term-1',
      deviceToken: null,
      getConnectionId: async () => 'conn-ssh',
      pickImage: vi.fn().mockResolvedValue({ base64: 'BBBB' })
    })

    const saveCall = client.calls.find((c) => c.method === 'clipboard.saveImageAsTempFile')
    expect(saveCall?.params).toEqual({ contentBase64: 'BBBB', connectionId: 'conn-ssh' })
  })

  it('forwards the picked fileName when attaching from files', async () => {
    const client = clientWithResponses([
      ok('start', { uploadId: 'upload-file-1' }),
      ok('append', { received: 4 }),
      ok('commit', '/tmp/orca-paste-1/柴静-看见.txt'),
      ok('send', { send: { accepted: true } })
    ])

    const sent = await attachMobileImageToTerminal('files', {
      client,
      agent: 'claude',
      terminal: 'term-1',
      deviceToken: null,
      getConnectionId: async () => null,
      pickImage: vi.fn().mockResolvedValue({ base64: 'BBBB', fileName: '柴静-看见.txt' })
    })

    expect(sent).toBe(true)
    const startCall = client.calls.find((c) => c.method === 'clipboard.startImageUpload')
    expect(startCall?.params).toMatchObject({ fileName: '柴静-看见.txt' })
  })

  it('does nothing and returns false when the picker is cancelled', async () => {
    const client = clientWithResponses([])

    const sent = await attachMobileImageToTerminal('library', {
      client,
      agent: 'claude',
      terminal: 'term-1',
      deviceToken: null,
      getConnectionId: async () => null,
      pickImage: vi.fn().mockResolvedValue(null)
    })

    expect(sent).toBe(false)
    expect(client.calls).toEqual([])
  })

  it('omits the client field when there is no device token', async () => {
    const client = clientWithResponses([
      {
        id: 'start',
        ok: false,
        error: { code: 'method_not_found', message: 'no' },
        _meta: { runtimeId: 'r' }
      },
      ok('save', '/tmp/y.png'),
      ok('send', { send: { accepted: true } })
    ])

    await attachMobileImageToTerminal('library', {
      client,
      agent: 'claude',
      terminal: 'term-2',
      deviceToken: null,
      getConnectionId: async () => null,
      pickImage: vi.fn().mockResolvedValue({ base64: 'CCCC' })
    })

    const sendCall = client.calls.find((c) => c.method === 'terminal.send')
    expect(sendCall?.params).not.toHaveProperty('client')
  })

  it('drops the image payload when the final pre-send check observes an input lease gap', async () => {
    const client = clientWithResponses([
      {
        id: 'start',
        ok: false,
        error: { code: 'method_not_found', message: 'no' },
        _meta: { runtimeId: 'r' }
      },
      ok('save', '/tmp/pending.png')
    ])
    // Why: upload can outlive the stream subscription whose acknowledgement
    // originally enabled the composer.
    const beforeTerminalSend = vi.fn(async () => false)

    const sent = await attachMobileImageToTerminal('library', {
      client,
      agent: 'claude',
      terminal: 'term-pending',
      deviceToken: null,
      getConnectionId: async () => null,
      pickImage: vi.fn().mockResolvedValue({ base64: 'DDDD' }),
      beforeTerminalSend
    })

    expect(sent).toBe(false)
    expect(beforeTerminalSend).toHaveBeenCalledWith('term-pending')
    expect(client.calls.some((call) => call.method === 'terminal.send')).toBe(false)
  })

  it('reports failure when the terminal rejects the uploaded image path', async () => {
    const client = clientWithResponses([
      {
        id: 'start',
        ok: false,
        error: { code: 'method_not_found', message: 'no' },
        _meta: { runtimeId: 'r' }
      },
      ok('save', '/tmp/rejected.png'),
      ok('send', { send: { accepted: false } })
    ])

    const sent = await attachMobileImageToTerminal('library', {
      client,
      agent: 'claude',
      terminal: 'term-rejected',
      deviceToken: null,
      getConnectionId: async () => null,
      pickImage: vi.fn().mockResolvedValue({ base64: 'EEEE' })
    })

    expect(sent).toBe(false)
  })
})