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.

5.7 KB
Raw Blame
import { describe, expect, it } from 'vitest'
import {
  buildShellCommandFromArgv,
  clearEnvCommand,
  commandSeparator,
  isPosixStartupShell,
  quoteStartupArg,
  tokenizeStartupCommand
} from './tui-agent-startup-shell'
import { buildAgentDraftLaunchPlan } from './tui-agent-startup'

function expectSpansCoverTokens(source: string, shell: 'powershell' | 'cmd'): string[] {
  const result = tokenizeStartupCommand(source, shell)
  expect(result.ok).toBe(true)
  if (!result.ok) {
    return []
  }
  expect(result.spans).toHaveLength(result.tokens.length)
  let previousEnd = 0
  for (const [index, { start, end }] of result.spans.entries()) {
    expect(start).toBeGreaterThanOrEqual(previousEnd)
    expect(end).toBeGreaterThan(start)
    // Every raw span must re-tokenize to exactly its own token.
    const slice = tokenizeStartupCommand(source.slice(start, end), shell)
    expect(slice.ok && slice.tokens).toEqual([result.tokens[index]])
    previousEnd = end
  }
  return result.spans.map(({ start, end }) => source.slice(start, end))
}

describe('tokenizeStartupCommand spans (windows shells)', () => {
  it('covers plain and quoted tokens on powershell', () => {
    const source = "claude --msg 'hello world'"
    const result = tokenizeStartupCommand(source, 'powershell')
    expect(result).toEqual({
      ok: true,
      tokens: ['claude', '--msg', 'hello world'],
      spans: [
        { start: 0, end: 6, divergesFromShell: false },
        { start: 7, end: 12, divergesFromShell: false },
        { start: 13, end: 26, divergesFromShell: false }
      ]
    })
  })

  it('starts a span at a token-leading escape character', () => {
    expect(expectSpansCoverTokens('claude ^&literal next', 'cmd')).toEqual([
      'claude',
      '^&literal',
      'next'
    ])
    expect(expectSpansCoverTokens('claude `x tail', 'powershell')).toEqual(['claude', '`x', 'tail'])
  })

  it('spans a powershell doubled-quote token as one raw range', () => {
    expect(expectSpansCoverTokens("claude 'a''b' end", 'powershell')).toEqual([
      'claude',
      "'a''b'",
      'end'
    ])
  })

  it('spans a token opened by a quote at end of input', () => {
    expect(expectSpansCoverTokens('claude ""', 'cmd')).toEqual(['claude', '""'])
  })
})

describe('one Unix startup dialect', () => {
  it('clears variables with a self-contained branch, not a per-shell builtin', () => {
    // Commands can land in unwrapped sh/dash/ksh or pasted shells; no wrapper helper or single fish/sh builtin works everywhere.
    expect(clearEnvCommand('CODEX_HOME', 'posix')).toBe(
      `command test -n "$fish_pid" && set --erase -g CODEX_HOME; command test -z "$fish_pid" && unset CODEX_HOME; true`
    )
    expect(clearEnvCommand(['A', 'B'], 'posix')).toBe(
      `command test -n "$fish_pid" && set --erase -g A B; command test -z "$fish_pid" && unset A B; true`
    )
    expect(clearEnvCommand('CODEX_HOME', 'cmd')).toBe('set "CODEX_HOME="')
    expect(clearEnvCommand('CODEX_HOME', 'powershell')).toBe(
      'Remove-Item Env:CODEX_HOME -ErrorAction SilentlyContinue'
    )
  })

  it.each([
    'FOO; rm -rf /tmp/x',
    'FOO BAR',
    '',
    '1LEADING_DIGIT',
    'has-dash',
    '$FOO',
    'PATH\nHOME'
  ])('refuses %j as an environment variable name', (bad) => {
    // Interpolated names must be identifiers; shell syntax would inject commands and fish erase could delete session variables.
    expect(() => clearEnvCommand(bad, 'posix')).toThrow(/not an environment variable name/)
    expect(() => clearEnvCommand(['OK', bad], 'posix')).toThrow(/not an environment variable name/)
  })

  it('quotes so fish reads back the same bytes sh does', () => {
    // Fish single quotes interpret backslash/apostrophe escapes; plain sh quoting would alter backslashes or fail at a trailing one.
    expect(quoteStartupArg("it's", 'posix')).toBe(`'it'"'"'s'`)
    expect(quoteStartupArg(String.raw`\\server\share`, 'posix')).toBe(
      `"\\\\""\\\\"'server'"\\\\"'share'`
    )
    expect(quoteStartupArg('ends\\', 'posix')).toBe(`'ends'"\\\\"`)
    expect(quoteStartupArg('', 'posix')).toBe(`''`)
  })

  it('keeps the sh-family grammar claims that do hold for fish', () => {
    expect(commandSeparator('posix')).toBe('; ')
    expect(isPosixStartupShell('posix')).toBe(true)
    expect(isPosixStartupShell('powershell')).toBe(false)
    expect(buildShellCommandFromArgv(['codex', 'resume', 'a b'], 'posix')).toBe(
      `'codex' 'resume' 'a b'`
    )
  })

  it('round-trips an adversarial argument through quote then tokenize', () => {
    for (const value of [
      String.raw`use \d+ and \\server\share`,
      "it's mine",
      'ends\\',
      'a "b" c',
      '$PATH *.ts'
    ]) {
      const tokenized = tokenizeStartupCommand(quoteStartupArg(value, 'posix'), 'posix')
      expect(tokenized.ok && tokenized.tokens).toEqual([value])
    }
  })

  it('clears an agent draft prefill variable with the portable teardown', () => {
    const plan = buildAgentDraftLaunchPlan({
      agent: 'pi',
      draft: 'hello',
      cmdOverrides: {},
      platform: 'darwin'
    })

    expect(plan?.launchCommand).toBe(
      `pi; command test -n "$fish_pid" && set --erase -g ORCA_PI_PREFILL; command test -z "$fish_pid" && unset ORCA_PI_PREFILL; true`
    )
    expect(plan?.env?.ORCA_PI_PREFILL).toBe('hello')
  })

  it('leaves a multi-line argv draft to the paste fallback in cmd.exe', () => {
    const draft = 'Linked Linear issue: ENG-1\nhttps://linear.app/acme/issue/ENG-1'
    const args = { agent: 'claude' as const, draft, cmdOverrides: {}, platform: 'win32' as const }

    expect(buildAgentDraftLaunchPlan({ ...args, shell: 'cmd' })).toBeNull()
    expect(buildAgentDraftLaunchPlan({ ...args, shell: 'powershell' })?.launchCommand).toContain(
      '`n'
    )
  })
})