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.

9.5 KB
Raw Blame
// @vitest-environment happy-dom
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { terminalDocumentDouble } from './document/document-terminal-double.test-support'
import type { TerminalDocumentTerminal } from './document/document-terminal-shape'
import { createTerminalDocument } from './document/create-terminal-document'
import { TERMINAL_DOCUMENT_SCRIPT } from './terminal-webview-document-script.generated'
import { TERMINAL_DOCUMENT_MARKUP } from './terminal-webview-html'

type BufferState = {
  baseY: number
  type: 'alternate' | 'normal'
  viewportY: number
}

const CELL_HEIGHT = 15
const FRAME_MS = 16
const ESC_ARROW_DOWN = '\u001b[B'

function makeTerminal(
  buffer: BufferState,
  scrollLines: (lines: number) => void
): TerminalDocumentTerminal {
  let openedOn: HTMLElement | undefined
  return {
    ...terminalDocumentDouble().terminal,
    cols: 40,
    rows: 24,
    modes: { mouseTrackingMode: 'none' },
    _core: {
      _renderService: { dimensions: { css: { cell: { width: 8, height: CELL_HEIGHT } } } }
    },
    buffer: {
      active: {
        get baseY() {
          return buffer.baseY
        },
        get type() {
          return buffer.type
        },
        get viewportY() {
          return buffer.viewportY
        },
        cursorY: 0,
        length: 1,
        getLine: () => undefined
      }
    },
    get element() {
      return openedOn
    },
    open(surface: HTMLElement) {
      openedOn = surface
    },
    scrollLines
  }
}

describe('terminal WebView touch scrolling', () => {
  let animationFrames: Map<number, (frameTime: number) => void>
  let nextFrameId: number
  let buffer: BufferState
  let now: number
  let postMessage: ReturnType<typeof vi.fn<(data: string) => void>>
  let scrollLines: ReturnType<typeof vi.fn<(lines: number) => void>>
  let stopDocument: (() => void) | undefined

  function boot(importedDocument = false): void {
    document.body.innerHTML = TERMINAL_DOCUMENT_MARKUP
    if (importedDocument) {
      const terminalDocument = createTerminalDocument()
      stopDocument = () => terminalDocument.stop()
    } else {
      new Function(TERMINAL_DOCUMENT_SCRIPT)()
    }
    window.dispatchEvent(
      new MessageEvent('message', {
        data: JSON.stringify({ type: 'init', cols: 40, rows: 24, initialData: '' })
      })
    )
    // Wait for init’s next-frame surface commit.
    runFrames(8)
  }

  function runFrames(count: number): void {
    for (let i = 0; i < count && animationFrames.size > 0; i++) {
      now += FRAME_MS
      const currentFrames = [...animationFrames]
      for (const [id, callback] of currentFrames) {
        if (animationFrames.delete(id)) {
          callback(now)
        }
      }
    }
  }

  function fireTouch(type: string, point: { x: number; y: number } | null): void {
    fireTouches(type, point ? [point] : [])
  }

  function fireTouches(type: string, points: Array<{ x: number; y: number }>): void {
    const surface = document.getElementById('terminal-surface')
    if (!surface) {
      throw new Error('terminal surface missing')
    }
    const event = new Event(type, { bubbles: true, cancelable: true })
    const touches = points.map((point, identifier) => ({
      identifier,
      clientX: point.x,
      clientY: point.y,
      target: surface
    }))
    Object.defineProperty(event, 'touches', { value: touches })
    surface.dispatchEvent(event)
  }

  function dragUp(fromY: number, stepPx: number, steps: number): number {
    let y = fromY
    for (let i = 0; i < steps; i++) {
      y -= stepPx
      now += FRAME_MS
      fireTouch('touchmove', { x: 40, y })
      runFrames(1)
    }
    return y
  }

  function scrolledRows(): number {
    return scrollLines.mock.calls.reduce((total, [lines]) => total + lines, 0)
  }

  function terminalInputBytes(): string {
    return postMessage.mock.calls
      .map(([raw]): { bytes?: string; type?: string } => JSON.parse(raw))
      .filter((msg) => msg.type === 'terminal-input')
      .map((msg) => msg.bytes ?? '')
      .join('')
  }

  beforeEach(() => {
    vi.spyOn(window, 'addEventListener')
    vi.spyOn(document, 'addEventListener')
    animationFrames = new Map()
    nextFrameId = 1
    buffer = { baseY: 500, type: 'normal', viewportY: 100 }
    now = 1_000
    scrollLines = vi.fn<(lines: number) => void>()
    postMessage = vi.fn<(data: string) => void>()
    vi.spyOn(Date, 'now').mockImplementation(() => now)
    vi.spyOn(performance, 'now').mockImplementation(() => now)
    vi.stubGlobal('requestAnimationFrame', (callback: (frameTime: number) => void) => {
      const id = nextFrameId++
      animationFrames.set(id, callback)
      return id
    })
    vi.stubGlobal('cancelAnimationFrame', (id: number) => {
      animationFrames.delete(id)
    })
    Object.defineProperty(window, 'innerWidth', { value: 381, configurable: true })
    Object.defineProperty(window, 'innerHeight', { value: 612, configurable: true })
    Object.assign(window, {
      Terminal: function () {
        return makeTerminal(buffer, scrollLines)
      },
      ReactNativeWebView: { postMessage }
    })
  })

  afterEach(() => {
    stopDocument?.()
    stopDocument = undefined
    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()
    vi.unstubAllGlobals()
    vi.useRealTimers()
  })

  it('scrolls scrollback for a drag slower than one pixel per frame', () => {
    boot()

    fireTouch('touchstart', { x: 40, y: 400 })
    dragUp(400, 0.5, 200)

    expect(scrolledRows()).toBe(6)
  })

  it('carries the sub-row remainder of a fast drag into the next move', () => {
    boot()

    fireTouch('touchstart', { x: 40, y: 400 })
    const y = dragUp(400, 100, 1)
    expect(scrolledRows()).toBe(6)

    dragUp(y, 5, 1)
    expect(scrolledRows()).toBe(7)
  })

  it('coasts when the finger lifts mid-drag', () => {
    boot()

    fireTouch('touchstart', { x: 40, y: 400 })
    dragUp(400, 20, 5)
    const rowsWhileTouching = scrolledRows()
    fireTouch('touchend', null)
    runFrames(30)

    expect(scrolledRows()).toBeGreaterThan(rowsWhileTouching)
  })

  it('does not coast when the finger rested before lifting', () => {
    boot()

    fireTouch('touchstart', { x: 40, y: 400 })
    dragUp(400, 20, 5)
    const rowsWhileTouching = scrolledRows()
    now += 500
    fireTouch('touchend', null)
    runFrames(30)

    expect(scrolledRows()).toBe(rowsWhileTouching)
  })

  it('does not send a resting finger’s momentum to an alternate-screen app', () => {
    buffer = { baseY: 0, type: 'alternate', viewportY: 0 }
    boot()

    fireTouch('touchstart', { x: 40, y: 400 })
    dragUp(400, 20, 5)
    const bytesWhileTouching = terminalInputBytes()
    expect(bytesWhileTouching).toContain(ESC_ARROW_DOWN)
    now += 500
    fireTouch('touchend', null)
    runFrames(30)

    expect(terminalInputBytes()).toBe(bytesWhileTouching)
  })

  it('drops an uncommitted scroll when a second finger starts a pinch', () => {
    boot()
    fireTouch('touchstart', { x: 40, y: 400 })
    now += FRAME_MS
    fireTouch('touchmove', { x: 40, y: 380 })
    fireTouches('touchstart', [
      { x: 40, y: 380 },
      { x: 140, y: 380 }
    ])
    runFrames(1)
    fireTouch('touchend', null)
    runFrames(30)

    expect(scrolledRows()).toBe(0)
    expect(terminalInputBytes()).toBe('')
  })

  it('drops queued scroll and velocity when the platform cancels a touch', () => {
    boot()
    fireTouch('touchstart', { x: 40, y: 400 })
    now += FRAME_MS
    fireTouch('touchmove', { x: 40, y: 320 })
    fireTouch('touchcancel', null)
    fireTouch('touchend', null)
    runFrames(30)

    expect(scrolledRows()).toBe(0)
    expect(terminalInputBytes()).toBe('')
    fireTouch('touchstart', { x: 40, y: 320 })
    fireTouch('touchend', null)
    expect(
      postMessage.mock.calls.filter(([raw]) => JSON.parse(raw).type === 'terminal-tap')
    ).toHaveLength(1)
  })

  it('does not send cancelled momentum to an alternate-screen app', () => {
    buffer = { baseY: 0, type: 'alternate', viewportY: 0 }
    boot()
    fireTouch('touchstart', { x: 40, y: 400 })
    dragUp(400, 20, 5)
    const bytesBeforeCancel = terminalInputBytes()
    expect(bytesBeforeCancel).toContain(ESC_ARROW_DOWN)
    fireTouch('touchcancel', null)
    fireTouch('touchend', null)
    runFrames(30)

    expect(terminalInputBytes()).toBe(bytesBeforeCancel)
  })

  it('retires queued scroll and momentum when the document is disposed', () => {
    boot(true)
    fireTouch('touchstart', { x: 40, y: 400 })
    now += FRAME_MS
    fireTouch('touchmove', { x: 40, y: 320 })
    fireTouch('touchend', null)
    stopDocument?.()
    runFrames(30)

    expect(scrolledRows()).toBe(0)
    expect(terminalInputBytes()).toBe('')
  })

  it('retires subthreshold scroll velocity when a long press enters selection', () => {
    boot()
    vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
    fireTouch('touchstart', { x: 40, y: 400 })
    now += 480
    fireTouch('touchmove', { x: 40, y: 399.5 })
    now += 19
    fireTouch('touchmove', { x: 40, y: 391.5 })
    now += 1
    vi.advanceTimersByTime(500)
    expect(
      postMessage.mock.calls.some(([raw]) => {
        const message = JSON.parse(raw)
        return message.type === 'set-select-mode' && message.enabled
      })
    ).toBe(true)

    fireTouch('touchend', null)
    runFrames(30)

    expect(scrolledRows()).toBe(0)
    expect(terminalInputBytes()).toBe('')
  })
})