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.

4.7 KB
Raw Blame
import {
  mobileNativeChatDraftDestination,
  updateMobileNativeChatDraftInputs,
  type MobileNativeChatDraftDestination
} from './mobile-native-chat-draft-inputs'
import { useCallback, useLayoutEffect, useRef, useState } from 'react'
import { translate } from '../../../i18n/mobile-i18n'
import { CLIPBOARD_IMAGE_TOO_LARGE_ERROR } from '../../../../../src/shared/clipboard-image'
import type { RpcClient } from '../../../transport/rpc-client'
import type { ConnectionState } from '../../../transport/types'
import { useMediaPicker } from '../../../platform/media-picker'
import {
  ImageLibraryPermissionError,
  type MobileImageSource
} from '../../../platform/media-picker-contract'
import {
  uploadMobileNativeChatImages,
  type PendingNativeChatImage
} from './mobile-native-chat-image-attachment'

type CurrentRef<T> = { readonly current: T }
type UploadedNativeChatImage = Omit<PendingNativeChatImage, 'id'>
type ShowToast = (message: string, durationMs?: number) => void

export function useMobileNativeChatImageUpload(args: {
  client: RpcClient | null
  activeHandleRef: CurrentRef<string | null>
  getActiveWorktreeConnectionId: () => Promise<string | null>
  connState: ConnectionState
  scopeKey: string | null
  structuredNativeChat: boolean
  showToast: ShowToast
  onImagesUploaded: (
    scope: MobileNativeChatDraftDestination,
    images: UploadedNativeChatImage[]
  ) => void
  onAttachSuccess?: () => void
  onError?: () => void
}): {
  attachImage: (source: MobileImageSource) => Promise<void>
  isAttaching: boolean
} {
  const {
    activeHandleRef,
    client,
    connState,
    getActiveWorktreeConnectionId,
    onAttachSuccess,
    onError,
    onImagesUploaded,
    scopeKey,
    showToast,
    structuredNativeChat
  } = args
  const [isAttaching, setIsAttaching] = useState(false)
  const picker = useMediaPicker()
  const attachingCount = useRef(0)
  const connStateRef = useRef(connState)
  useLayoutEffect(() => {
    connStateRef.current = connState
  }, [connState])

  const attachImage = useCallback(
    async (source: MobileImageSource): Promise<void> => {
      const scope = scopeKey
      if (
        !client ||
        !scope ||
        connState !== 'connected' ||
        (!activeHandleRef.current && !structuredNativeChat)
      ) {
        return
      }
      const destination = mobileNativeChatDraftDestination(scope)
      updateMobileNativeChatDraftInputs(destination, (inputs) => ({
        ...inputs,
        pending: (inputs.pending ?? 0) + 1
      }))
      let started = false
      const uploadedImages: UploadedNativeChatImage[] = []
      let uploadError: unknown = null
      try {
        await uploadMobileNativeChatImages(source, {
          canContinue: () => destination.active,
          client,
          getConnectionId: getActiveWorktreeConnectionId,
          pickImages: picker.pickImages,
          onImageUploaded: (image) => uploadedImages.push(image),
          onUploadStart: () => {
            started = true
            attachingCount.current += 1
            setIsAttaching(true)
          }
        })
      } catch (error) {
        uploadError = error
      } finally {
        if (started) {
          attachingCount.current -= 1
          if (attachingCount.current === 0) {
            setIsAttaching(false)
          }
        }
      }
      if (uploadedImages.length > 0) {
        onImagesUploaded(destination, uploadedImages)
        onAttachSuccess?.()
      }
      updateMobileNativeChatDraftInputs(destination, (inputs) => ({
        ...inputs,
        pending: Math.max(0, (inputs.pending ?? 0) - 1)
      }))
      if (uploadError !== null && destination.active) {
        const message = uploadError instanceof Error ? uploadError.message : String(uploadError)
        onError?.()
        if (connStateRef.current !== 'connected') {
          showToast(
            translate('chat.useImageUpload.disconnected', 'Attach failed (disconnected)'),
            1500
          )
          return
        }
        if (uploadError instanceof ImageLibraryPermissionError) {
          showToast(
            translate('chat.useImageUpload.permissionDenied', 'Photo permission denied'),
            1500
          )
          return
        }
        if (message === CLIPBOARD_IMAGE_TOO_LARGE_ERROR) {
          showToast(
            translate('chat.useImageUpload.imageTooLarge', 'Image too large to attach'),
            1500
          )
          return
        }
        showToast(translate('chat.useImageUpload.attachFailed', 'Attach failed'), 1500)
      }
    },
    [
      activeHandleRef,
      client,
      connState,
      getActiveWorktreeConnectionId,
      onAttachSuccess,
      onError,
      onImagesUploaded,
      picker,
      scopeKey,
      showToast,
      structuredNativeChat
    ]
  )

  return { attachImage, isAttaching }
}