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.

16.1 KB
Raw Blame
// @vitest-environment happy-dom
// URL taps with slight jitter once hit the long-press slop gate and never reached the native browser bridge.
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { TERMINAL_DOCUMENT_SCRIPT } from './terminal-webview-document-script.generated'
import { TERMINAL_DOCUMENT_MARKUP } from './terminal-webview-html'

function bodyMarkup(): string {
  return TERMINAL_DOCUMENT_MARKUP
}

function makeTerminal(
  lineRef: { current: string },
  mouseTrackingMode = 'none',
  scrollbackRows = 0
) {
  return {
    cols: 80,
    rows: 24,
    options: { fontSize: 13 },
    modes: { mouseTrackingMode },
    element: { scrollWidth: 800, scrollHeight: 360 },
    _core: { _renderService: { dimensions: { css: { cell: { width: 8, height: 15 } } } } },
    buffer: {
      active: {
        viewportY: 0,
        baseY: scrollbackRows,
        length: 1,
        cursorY: 0,
        type: 'normal' as const,
        getLine(row: number) {
          // Rows after the first are xterm soft-wrap continuations.
          const text = lineRef.current.split('\n')[row]
          if (text === undefined) {
            return null
          }
          return {
            length: 80,
            isWrapped: row > 0,
            // Honor xterm’s translateToString slice arguments so wide-cell offset conversion is realistic.
            translateToString: (_trim?: boolean, start?: number, end?: number) =>
              text.slice(start ?? 0, end ?? text.length),
            getCell: () => ({ extended: undefined })
          }
        }
      }
    },
    write(_d: string, cb?: () => void) {
      cb?.()
    },
    open() {},
    resize() {},
    clear() {},
    reset() {},
    refresh() {},
    selectAll() {},
    clearSelection() {},
    select() {},
    scrollLines() {},
    scrollToBottom() {},
    getSelection: () => '',
    onLineFeed: () => ({ dispose() {} }),
    onScroll: () => ({ dispose() {} }),
    onWriteParsed: () => ({ dispose() {} }),
    dispose() {}
  }
}

type Posted = Array<Record<string, unknown>>

type OscLinkRange = { row: number; startCol: number; endCol: number; uri: string }

function boot(
  line: string,
  oscLinks?: OscLinkRange[],
  mouseTrackingMode = 'none',
  scrollbackRows = 0
): { posted: Posted; setLine: (line: string) => void } {
  const posted: Posted = []
  const lineRef = { current: line }
  const w = window as unknown as { Terminal: unknown; ReactNativeWebView: unknown }
  w.Terminal = function () {
    return makeTerminal(lineRef, mouseTrackingMode, scrollbackRows)
  }
  w.ReactNativeWebView = {
    postMessage(s: string) {
      posted.push(JSON.parse(s))
    }
  }
  document.body.innerHTML = bodyMarkup()
  // The bundle the WebView loads, run as the WebView runs it.
  new Function(TERMINAL_DOCUMENT_SCRIPT)()
  window.dispatchEvent(
    new MessageEvent('message', {
      data: JSON.stringify({ type: 'init', cols: 80, rows: 24, initialData: '', oscLinks })
    })
  )
  return {
    posted,
    setLine: (nextLine: string) => {
      lineRef.current = nextLine
    }
  }
}

function fireTouch(type: string, touches: Array<{ x: number; y: number }>): void {
  const surface = document.getElementById('terminal-surface') as HTMLElement
  const ev = new Event(type, { bubbles: true, cancelable: true })
  Object.defineProperty(ev, 'touches', {
    value: touches.map((p, i) => ({ identifier: i, clientX: p.x, clientY: p.y, target: surface }))
  })
  surface.dispatchEvent(ev)
}

const settle = (): Promise<void> => new Promise((r) => setTimeout(r, 50))

describe('terminal WebView tap routing', () => {
  const URL_LINE = 'visit https://example.com/foo now'
  const tapX = 12 * 8 * 0.3125
  const tapY = 2
  const screenXForCol = (col: number): number => col * 8 * 0.3125

  beforeEach(() => {
    vi.spyOn(window, 'addEventListener')
    vi.spyOn(document, 'addEventListener')
    Object.defineProperty(window, 'innerWidth', { value: 200, configurable: true })
    Object.defineProperty(window, 'innerHeight', { value: 400, configurable: true })
  })

  afterEach(() => {
    for (const [type, listener, options] of vi.mocked(window.addEventListener).mock.calls) {
      window.removeEventListener(type, listener, options)
    }
    for (const [type, listener, options] of vi.mocked(document.addEventListener).mock.calls) {
      document.removeEventListener(type, listener, options)
    }
    vi.restoreAllMocks()
  })

  it('posts open-url when a clean tap lands on a URL', async () => {
    const { posted } = boot(URL_LINE)
    await settle()
    fireTouch('touchstart', [{ x: tapX, y: tapY }])
    fireTouch('touchend', [])
    expect(posted.find((m) => m.type === 'open-url')?.url).toBe('https://example.com/foo')
  })

  it('still posts open-url when the tap jitters a few pixels', async () => {
    // Small finger jitter must stay a tap and open the touched URL.
    const { posted } = boot(URL_LINE)
    await settle()
    fireTouch('touchstart', [{ x: tapX, y: tapY }])
    fireTouch('touchmove', [{ x: tapX + 11, y: tapY + 4 }])
    fireTouch('touchend', [])
    expect(posted.find((m) => m.type === 'open-url')?.url).toBe('https://example.com/foo')
  })

  it('focuses native input after reporting a touch tap to a mouse-tracking TUI', async () => {
    const { posted } = boot('interactive prompt', undefined, 'drag')
    await settle()
    window.dispatchEvent(
      new MessageEvent('message', {
        data: JSON.stringify({ type: 'write', data: '\u001b[?1006l' })
      })
    )

    fireTouch('touchstart', [{ x: 20, y: tapY }])
    fireTouch('touchend', [])

    expect(
      posted
        .filter((message) => message.type === 'terminal-input' || message.type === 'terminal-tap')
        .map((message) => message.type)
    ).toEqual(['terminal-input', 'terminal-tap'])
  })

  it('marks the mouse report a touch tap sends as a click', async () => {
    // A click can move the TUI cursor; order it behind live-field text rather than the wheel queue.
    const { posted } = boot('interactive prompt', undefined, 'drag')
    await settle()
    window.dispatchEvent(
      new MessageEvent('message', {
        data: JSON.stringify({ type: 'write', data: '\u001b[?1006l' })
      })
    )

    fireTouch('touchstart', [{ x: 20, y: tapY }])
    fireTouch('touchend', [])

    const inputs = posted.filter((message) => message.type === 'terminal-input')
    expect(inputs).toHaveLength(1)
    expect(inputs[0]?.click).toBe(true)
  })

  it('focuses native input without mouse bytes while the tracking encoding is unproven', async () => {
    const { posted } = boot('interactive prompt', undefined, 'drag')
    await settle()

    fireTouch('touchstart', [{ x: 20, y: tapY }])
    fireTouch('touchend', [])

    expect(posted.find((message) => message.type === 'terminal-input')).toBeUndefined()
    expect(posted.filter((message) => message.type === 'terminal-tap')).toHaveLength(1)
  })

  it('reports a non-mouse touch tap without terminal mouse bytes', async () => {
    const { posted } = boot('plain prompt')
    await settle()

    fireTouch('touchstart', [{ x: 20, y: tapY }])
    fireTouch('touchend', [])

    expect(posted.find((message) => message.type === 'terminal-input')).toBeUndefined()
    expect(posted.filter((message) => message.type === 'terminal-tap')).toHaveLength(1)
  })

  it('opens the URL even right after a width-change reflow', async () => {
    // Reflow must preserve URL tap routing after scrollback rewrap.
    const { posted } = boot(URL_LINE)
    await settle()
    window.dispatchEvent(
      new MessageEvent('message', { data: JSON.stringify({ type: 'reflow', cols: 100, rows: 24 }) })
    )
    fireTouch('touchstart', [{ x: tapX, y: tapY }])
    fireTouch('touchend', [])
    expect(posted.find((m) => m.type === 'open-url')?.url).toBe('https://example.com/foo')
  })

  it('opens first-load OSC links from snapshot metadata on the exact cell range', async () => {
    const oscLinks = [{ row: 0, startCol: 6, endCol: 11, uri: 'https://example.com/issue/1234' }]
    const { posted } = boot('issue #1234 done', oscLinks)
    await settle()

    fireTouch('touchstart', [{ x: screenXForCol(7), y: tapY }])
    fireTouch('touchend', [])

    expect(posted.find((m) => m.type === 'open-url')?.url).toBe('https://example.com/issue/1234')
  })

  it('opens first-load file OSC links through terminal file taps', async () => {
    const oscLinks = [{ row: 0, startCol: 5, endCol: 15, uri: 'file:///tmp/result.json#L12C3' }]
    const { posted } = boot('open artifact here', oscLinks)
    await settle()

    fireTouch('touchstart', [{ x: screenXForCol(7), y: tapY }])
    fireTouch('touchend', [])

    expect(posted.find((m) => m.type === 'open-url')).toBeUndefined()
    expect(posted.find((m) => m.type === 'terminal-file-tap')).toEqual({
      type: 'terminal-file-tap',
      candidates: [{ pathText: '/tmp/result.json', line: 12, column: 3 }]
    })
  })

  it('keeps the UNC host of an OSC file link for a Windows share workspace', async () => {
    const oscLinks = [
      { row: 0, startCol: 5, endCol: 15, uri: 'file://server/share/repo/app.ts#L12' }
    ]
    const { posted } = boot('open artifact here', oscLinks)
    await settle()

    fireTouch('touchstart', [{ x: screenXForCol(7), y: tapY }])
    fireTouch('touchend', [])

    expect(posted.find((m) => m.type === 'terminal-file-tap')).toEqual({
      type: 'terminal-file-tap',
      candidates: [{ pathText: '//server/share/repo/app.ts', line: 12, column: null }]
    })
  })

  it('keeps a tap on prose beside a path an ordinary tap', async () => {
    const line = 'me@host:~/proj$ git status'
    const { posted } = boot(line)
    await settle()

    fireTouch('touchstart', [{ x: screenXForCol(line.indexOf('git') + 1), y: tapY }])
    fireTouch('touchend', [])

    expect(posted.find((m) => m.type === 'terminal-file-tap')).toBeUndefined()
    expect(posted.find((m) => m.type === 'terminal-tap')).toBeDefined()
  })

  it('opens a markdown link whose destination has spaces', async () => {
    const line = 'see [PDF](</tmp/folder with spaces/report.pdf>)'
    const { posted } = boot(line)
    await settle()

    fireTouch('touchstart', [{ x: screenXForCol(line.indexOf('with') + 1), y: tapY }])
    fireTouch('touchend', [])

    expect(posted.find((m) => m.type === 'terminal-file-tap')).toEqual({
      type: 'terminal-file-tap',
      candidates: [{ pathText: '/tmp/folder with spaces/report.pdf', line: null, column: null }]
    })
  })

  it('opens plain file URLs through terminal file taps', async () => {
    const line = 'open file:///tmp/result.json#L12C3 now'
    const { posted } = boot(line)
    await settle()

    fireTouch('touchstart', [{ x: screenXForCol(line.indexOf('result')), y: tapY }])
    fireTouch('touchend', [])

    expect(posted.find((m) => m.type === 'terminal-file-tap')).toEqual({
      type: 'terminal-file-tap',
      candidates: [{ pathText: '/tmp/result.json', line: 12, column: 3 }]
    })
  })

  it('opens the whole URL when the tap lands on its soft-wrapped second row', async () => {
    const url = `https://example.com/${'a'.repeat(70)}/end`
    const text = `see ${url} now`
    const { posted } = boot(`${text.slice(0, 80)}\n${text.slice(80)}`)
    await settle()

    fireTouch('touchstart', [{ x: screenXForCol(2), y: tapY + 15 * 0.3125 }])
    fireTouch('touchend', [])

    expect(posted.find((m) => m.type === 'open-url')?.url).toBe(url)
  })

  it('does not open snapshot OSC links from adjacent terminal cells', async () => {
    const oscLinks = [{ row: 0, startCol: 6, endCol: 11, uri: 'https://example.com/issue/1234' }]
    const { posted } = boot('issue #1234 done', oscLinks)
    await settle()

    fireTouch('touchstart', [{ x: screenXForCol(12), y: tapY }])
    fireTouch('touchend', [])

    expect(posted.find((m) => m.type === 'open-url')).toBeUndefined()
  })

  it('does not parse off-cell snapshot file OSC links while routing a tap', async () => {
    const oscLinks = Array.from({ length: 50 }, (_, index) => ({
      row: index + 1,
      startCol: 0,
      endCol: 10,
      uri: `file:///tmp/result-${index}.json#L1`
    }))
    const { posted } = boot('plain text', oscLinks)
    await settle()

    const OriginalURL = window.URL
    let parseCount = 0
    const CountingURL = class extends OriginalURL {
      constructor(url: string | URL, base?: string | URL) {
        parseCount += 1
        super(url, base)
      }
    }
    Object.defineProperty(window, 'URL', { value: CountingURL, configurable: true })
    try {
      fireTouch('touchstart', [{ x: screenXForCol(5), y: tapY }])
      fireTouch('touchend', [])
    } finally {
      Object.defineProperty(window, 'URL', { value: OriginalURL, configurable: true })
    }

    expect(parseCount).toBe(0)
    expect(posted.find((m) => m.type === 'terminal-file-tap')).toBeUndefined()
  })

  it('does not open stale snapshot OSC links after the row text changes', async () => {
    const oscLinks = [{ row: 0, startCol: 6, endCol: 11, uri: 'https://example.com/issue/1234' }]
    const { posted, setLine } = boot('issue #1234 done', oscLinks)
    await settle()
    setLine('issue plain done')

    fireTouch('touchstart', [{ x: screenXForCol(7), y: tapY }])
    fireTouch('touchend', [])

    expect(posted.find((m) => m.type === 'open-url')).toBeUndefined()
  })

  it('does not post open-url for a scroll gesture past the tap slop', async () => {
    const { posted } = boot(URL_LINE)
    await settle()
    fireTouch('touchstart', [{ x: tapX, y: tapY }])
    fireTouch('touchmove', [{ x: tapX, y: tapY + 120 }])
    fireTouch('touchend', [])
    expect(posted.find((m) => m.type === 'open-url')).toBeUndefined()
  })

  // Scaled rows are smaller than tap slop; a short drag can still count as a real row scroll.
  it('does not tap after a short drag that scrolled scrollback', async () => {
    const { posted } = boot('plain output', undefined, 'none', 50)
    await settle()
    fireTouch('touchstart', [{ x: 20, y: 100 }])
    fireTouch('touchmove', [{ x: 20, y: 88 }])
    fireTouch('touchend', [])
    expect(posted.find((m) => m.type === 'terminal-tap')).toBeUndefined()
  })

  it('does not tap or click after a short drag that scrolled a mouse-tracking TUI', async () => {
    const { posted } = boot('interactive prompt', undefined, 'drag')
    await settle()
    window.dispatchEvent(
      new MessageEvent('message', {
        data: JSON.stringify({ type: 'write', data: '\u001b[?1006l' })
      })
    )

    fireTouch('touchstart', [{ x: 20, y: 100 }])
    fireTouch('touchmove', [{ x: 20, y: 88 }])
    fireTouch('touchend', [])

    expect(posted.find((m) => m.type === 'terminal-tap')).toBeUndefined()
    const input = posted
      .filter((m) => m.type === 'terminal-input')
      .map((m) => String(m.bytes))
      .join('')
    const reports = input.split('\u001b[M').slice(1)
    expect(reports.length).toBeGreaterThan(0)
    expect(reports.every((report) => report[0] === '`' || report[0] === 'a')).toBe(true)
  })

  it('still taps when the touch moves less than a row', async () => {
    const { posted } = boot('plain output', undefined, 'none', 50)
    await settle()
    fireTouch('touchstart', [{ x: 20, y: 100 }])
    fireTouch('touchmove', [{ x: 20, y: 97 }])
    fireTouch('touchend', [])
    expect(posted.filter((m) => m.type === 'terminal-tap')).toHaveLength(1)
  })

  it('still taps when the touch moves a row and back before anything scrolls', async () => {
    const { posted } = boot('plain output', undefined, 'none', 50)
    await settle()
    fireTouch('touchstart', [{ x: 20, y: 100 }])
    fireTouch('touchmove', [{ x: 20, y: 94 }])
    fireTouch('touchmove', [{ x: 20, y: 100 }])
    fireTouch('touchend', [])
    expect(posted.filter((m) => m.type === 'terminal-tap')).toHaveLength(1)
  })

  it('does not tap when the touch stops a coast', async () => {
    let now = 1_000
    vi.spyOn(Date, 'now').mockImplementation(() => now)
    const { posted } = boot('plain output', undefined, 'none', 50)
    await settle()
    fireTouch('touchstart', [{ x: 20, y: 300 }])
    now += 16
    fireTouch('touchmove', [{ x: 20, y: 240 }])
    now += 16
    fireTouch('touchmove', [{ x: 20, y: 180 }])
    fireTouch('touchend', [])
    const beforeStoppingTouch = posted.length

    fireTouch('touchstart', [{ x: 20, y: 180 }])
    fireTouch('touchend', [])

    expect(posted.slice(beforeStoppingTouch).find((m) => m.type === 'terminal-tap')).toBeUndefined()
  })
})