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.2 KB
Raw Blame
import { createElement } from 'react'
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import MobileOnboardingScreen from '../../app/mobile-onboarding'
import { findAllByHostType, findByHostType } from '../test-support/react-test-renderer-host-nodes'

const mocks = vi.hoisted(() => ({
  params: { hostId: 'paired-host', steps: 'session-view,notifications' },
  replace: vi.fn(),
  windowWidth: 390,
  reducedMotionEnabled: false,
  animatedTiming: vi.fn(),
  ensureNotificationPermissions: vi.fn(),
  saveDefaultSessionView: vi.fn(),
  setRemotePushEnabled: vi.fn()
}))

vi.mock('react-native', () => ({
  AccessibilityInfo: {
    addEventListener: vi.fn(() => ({ remove: vi.fn() })),
    isReduceMotionEnabled: vi.fn(() => Promise.resolve(mocks.reducedMotionEnabled))
  },
  Animated: {
    Value: class {
      constructor(public current: number) {}
    },
    View: 'AnimatedView',
    // Keep Animated values lazy so later timing updates reach translateX.
    multiply: (value: { current: number }, factor: number) => ({ value, factor }),
    timing: mocks.animatedTiming
  },
  BackHandler: {
    addEventListener: vi.fn(() => ({ remove: vi.fn() }))
  },
  StyleSheet: { create: (styles: unknown) => styles },
  Text: 'Text',
  View: 'View',
  useWindowDimensions: () => ({ width: mocks.windowWidth, height: 844 })
}))

vi.mock('expo-router', () => ({
  useFocusEffect: vi.fn(),
  useLocalSearchParams: () => mocks.params,
  useRouter: () => ({ replace: mocks.replace })
}))

vi.mock('react-native-safe-area-context', () => ({ SafeAreaView: 'SafeAreaView' }))
vi.mock('../components/OrcaLogo', () => ({ OrcaLogo: 'OrcaLogo' }))
vi.mock('./MobileOnboardingPage', () => ({ MobileOnboardingPage: 'MobileOnboardingPage' }))
vi.mock('../notifications/mobile-notifications', () => ({
  ensureNotificationPermissions: mocks.ensureNotificationPermissions
}))
vi.mock('../storage/session-view-preferences', () => ({
  saveDefaultSessionView: mocks.saveDefaultSessionView
}))
vi.mock('../notifications/push-registration', () => ({
  setRemotePushEnabled: mocks.setRemotePushEnabled
}))

describe('MobileOnboardingScreen', () => {
  let renderer: ReactTestRenderer | null = null

  beforeEach(() => {
    mocks.params = { hostId: 'paired-host', steps: 'session-view,notifications' }
    mocks.replace.mockReset()
    mocks.windowWidth = 390
    mocks.reducedMotionEnabled = false
    mocks.animatedTiming
      .mockReset()
      .mockImplementation((value: { current: number }, config: { toValue: number }) => ({
        start: (callback: (result: { finished: boolean }) => void) => {
          value.current = config.toValue
          callback({ finished: true })
        }
      }))
    mocks.ensureNotificationPermissions.mockReset().mockResolvedValue(true)
    mocks.saveDefaultSessionView.mockReset().mockResolvedValue(undefined)
    mocks.setRemotePushEnabled.mockReset().mockResolvedValue(undefined)
  })

  afterEach(() => {
    act(() => renderer?.unmount())
    renderer = null
    vi.restoreAllMocks()
  })

  async function renderScreen(viewportWidth = 390) {
    const consoleError = vi.spyOn(console, 'error').mockImplementation((...args) => {
      if (typeof args[0] !== 'string' || !args[0].includes('react-test-renderer is deprecated')) {
        throw new Error(String(args[0]))
      }
    })
    await act(async () => {
      renderer = create(createElement(MobileOnboardingScreen))
    })
    await layoutViewport(viewportWidth)
    consoleError.mockRestore()
  }

  async function layoutViewport(width: number) {
    const viewport = renderer!.root.findAll((node) => node.props.onLayout !== undefined)[0]
    await act(async () => viewport?.props.onLayout({ nativeEvent: { layout: { width } } }))
  }

  function trackStyle() {
    return findByHostType(renderer!.root, 'AnimatedView').props.style[1]
  }

  function trackWidth(): number {
    return trackStyle().width
  }

  function translateX(): number {
    const { value, factor } = trackStyle().transform[0].translateX
    return value.current * factor + 0
  }

  function pages() {
    return findAllByHostType(renderer!.root, 'MobileOnboardingPage')
  }

  it('advances from session view to notifications before opening the paired host', async () => {
    await renderScreen()
    expect(pages().map((page) => page.props.active)).toEqual([true, false])

    await act(async () => pages()[0].props.onSessionChoice('chat'))
    expect(mocks.saveDefaultSessionView).toHaveBeenCalledWith('chat')
    expect(pages().map((page) => page.props.active)).toEqual([false, true])
    expect(mocks.replace).not.toHaveBeenCalled()

    await act(async () => pages()[1].props.onNotificationChoice('skip'))
    expect(mocks.ensureNotificationPermissions).not.toHaveBeenCalled()
    expect(mocks.setRemotePushEnabled).toHaveBeenCalledWith(false)
    expect(mocks.replace).toHaveBeenCalledWith('/h/paired-host')
  })

  it.each([true, false])(
    'saves permission result %s through the consent owner once',
    async (granted) => {
      mocks.params = { hostId: 'paired-host', steps: 'notifications' }
      mocks.ensureNotificationPermissions.mockResolvedValue(granted)
      await renderScreen()
      await act(async () => pages()[0].props.onNotificationChoice('enable'))
      expect(mocks.setRemotePushEnabled).toHaveBeenCalledExactlyOnceWith(granted)
      expect(mocks.replace).toHaveBeenCalledWith('/h/paired-host')
    }
  )

  it('keeps notification consent retryable when its local write fails', async () => {
    mocks.params = { hostId: 'paired-host', steps: 'notifications' }
    mocks.setRemotePushEnabled.mockRejectedValueOnce(new Error('disk full'))
    await renderScreen()
    await act(async () => pages()[0].props.onNotificationChoice('enable'))
    expect(pages()[0].props.error).toBe('Notification settings could not be updated. Try again.')
    expect(mocks.replace).not.toHaveBeenCalled()
    await act(async () => pages()[0].props.onNotificationChoice('enable'))
    expect(mocks.setRemotePushEnabled).toHaveBeenCalledTimes(2)
    expect(mocks.setRemotePushEnabled).toHaveBeenLastCalledWith(true)
    expect(mocks.replace).toHaveBeenCalledWith('/h/paired-host')
  })

  it('finishes immediately when the plan contains only one outstanding step', async () => {
    mocks.params = { hostId: 'paired-host', steps: 'session-view' }
    await renderScreen()

    await act(async () => pages()[0].props.onSessionChoice('terminal'))
    expect(mocks.replace).toHaveBeenCalledWith('/h/paired-host')
  })

  it('keeps the current step retryable when persistence fails', async () => {
    mocks.params = { hostId: 'paired-host', steps: 'session-view' }
    mocks.saveDefaultSessionView
      .mockRejectedValueOnce(new Error('storage unavailable'))
      .mockResolvedValueOnce(undefined)
    await renderScreen()

    await act(async () => pages()[0].props.onSessionChoice('chat'))
    expect(pages()[0].props.error).toBe('Your choice could not be saved. Try again.')

    await act(async () => pages()[0].props.onSessionChoice('chat'))
    expect(mocks.saveDefaultSessionView).toHaveBeenCalledTimes(2)
    expect(mocks.replace).toHaveBeenCalledWith('/h/paired-host')
  })

  it('resets carousel state when the route supplies a new onboarding plan', async () => {
    await renderScreen()
    await act(async () => pages()[0].props.onSessionChoice('chat'))
    expect(pages().map((page) => page.props.active)).toEqual([false, true])

    mocks.params = { hostId: 'paired-host', steps: 'notifications' }
    await act(async () => renderer!.update(createElement(MobileOnboardingScreen)))
    await layoutViewport(390)

    expect(pages()).toHaveLength(1)
    expect(pages()[0].props).toMatchObject({ step: 'notifications', active: true })
  })

  it('skips the slide animation when the device requests reduced motion', async () => {
    mocks.reducedMotionEnabled = true
    await renderScreen()

    await act(async () => pages()[0].props.onSessionChoice('chat'))

    expect(mocks.animatedTiming).toHaveBeenCalledWith(
      expect.anything(),
      expect.objectContaining({ duration: 0, useNativeDriver: true })
    )
  })

  it('keeps the next decision available if the cosmetic transition is interrupted', async () => {
    mocks.animatedTiming.mockReturnValue({
      start: (callback: (result: { finished: boolean }) => void) => callback({ finished: false })
    })
    await renderScreen()

    await act(async () => pages()[0].props.onSessionChoice('chat'))

    expect(pages()[1].props).toMatchObject({ active: true, busyChoice: null })
  })

  it('sizes slides from the modal viewport rather than the wider window', async () => {
    mocks.windowWidth = 1024
    await renderScreen(540)

    expect(pages().map((page) => page.props.width)).toEqual([540, 540])
    expect(trackWidth()).toBe(1080)
    expect(translateX()).toBe(0)

    await act(async () => pages()[0].props.onSessionChoice('chat'))
    expect(translateX()).toBe(-540)

    await layoutViewport(700)
    expect(pages().map((page) => page.props.width)).toEqual([700, 700])
    expect(trackWidth()).toBe(1400)
    expect(translateX()).toBe(-700)
  })

  it('keeps the pager unrendered until the viewport reports a real width', async () => {
    await renderScreen(0)
    expect(pages()).toHaveLength(0)

    await layoutViewport(540)
    expect(pages().map((page) => page.props.width)).toEqual([540, 540])
  })
})