Skip to content

The agent that grows with you

29.1 KB
Raw Blame
import { useCallback } from 'react'

import { requestComposerFocus, requestComposerInsert, requestComposerInsertRefs } from '@/app/chat/composer/focus'
import { droppedFileInlineRef } from '@/app/chat/composer/inline-refs'
import { LARGE_PASTE_TITLE_PREVIEW_CHARS, pasteSizeLabel } from '@/app/chat/composer/large-paste'
import { formatRefValue } from '@/components/assistant-ui/directive-text'
import { useI18n } from '@/i18n'
import { attachmentPathNeedsUpload } from '@/lib/attachment-upload-policy'
import { attachmentId, contextPath, pathLabel } from '@/lib/chat-runtime'
import { readDesktopFileDataUrlLocalFirst, selectDesktopPaths } from '@/lib/desktop-fs'
import { downscaleDataUrlForPreview } from '@/lib/image-resize'
import { normalize } from '@/lib/text'
import {
  addComposerAttachment,
  type ComposerAttachment,
  type ComposerAttachmentPatch,
  createComposerAttachmentOccurrenceId,
  patchMainComposerAttachmentOccurrence,
  removeComposerAttachment,
  setComposerTerminalSelection,
  updateComposerAttachment
} from '@/store/composer'
import { notify, notifyError, readableError } from '@/store/notifications'

import type { ImageDetachResponse } from '../../types'

import { type DropFailure, dropWarning } from './drop-warning'

const IMAGE_EXTENSION_PATTERN = /\.(png|jpe?g|gif|webp|bmp|tiff?|svg|ico)$/i

const BLOB_MIME_EXTENSION: Record<string, string> = {
  'image/bmp': '.bmp',
  'image/gif': '.gif',
  'image/jpeg': '.jpg',
  'image/png': '.png',
  'image/svg+xml': '.svg',
  'image/tiff': '.tiff',
  'image/webp': '.webp',
  'image/x-icon': '.ico'
}

function blobExtension(blob: Blob): string {
  const mime = normalize(blob.type.split(';')[0])

  return BLOB_MIME_EXTENSION[mime] || '.png'
}

export function isImagePath(filePath: string): boolean {
  return IMAGE_EXTENSION_PATTERN.test(filePath)
}

/** A dropped File the composer sends as an image; never a folder, which has no bytes. */
function isDroppedImage(file: File, filePath: string, isDirectory?: boolean): boolean {
  return !isDirectory && (file.type.startsWith('image/') || isImagePath(file.name) || isImagePath(filePath))
}

/**
 * Read an attachment's thumbnail preview, local disk first. Paperclip picks,
 * clipboard saves, and OS drops always hand us paths on THIS machine — the
 * remote-routed fs facade would 404 them against the gateway and toast a bogus
 * "preview failed" even though the attach itself works (upload reads local
 * bytes too). In-app drags from the remote project tree are the opposite case:
 * the local read fails there, so fall back to the facade (remote fs bridge).
 * In local mode the facade IS the local bridge, so this stays a single read.
 */
export async function attachmentPreviewDataUrl(filePath: string): Promise<string> {
  return readDesktopFileDataUrlLocalFirst(filePath)
}

let attachmentPreviewQueue = Promise.resolve()

async function queuedAttachmentPreview(filePath: string): Promise<{ previewUrl: string; thumbnailUrl?: string }> {
  const task = attachmentPreviewQueue.then(async () => {
    const previewUrl = await attachmentPreviewDataUrl(filePath)
    const thumbnailUrl = previewUrl.startsWith('data:image/') ? await downscaleDataUrlForPreview(previewUrl) : undefined

    return { previewUrl, thumbnailUrl }
  })

  attachmentPreviewQueue = task.then(
    () => undefined,
    () => undefined
  )

  return task
}

/**
 * Prefer a cheap object-URL preview when the drop/paste still has a Blob/File
 * handle. `readFileDataUrl` base64-loads the whole file over IPC (capped at
 * 16 MB) and was freezing Desktop on Windows Explorer image drops (#63682).
 * Object URLs skip that read; path-only attaches (paperclip) still fall back
 * to the IPC data-URL path.
 */
export async function resolveImageAttachmentPreview(filePath: string, previewSource?: Blob | null): Promise<string> {
  if (previewSource && previewSource.size > 0) {
    return URL.createObjectURL(previewSource)
  }

  return attachmentPreviewDataUrl(filePath)
}

export interface DroppedFile {
  /** Browser-native File handle. Absent for in-app drags (e.g. project tree). */
  file?: File
  /** Absolute filesystem path. Empty when an OS drop didn't carry one. */
  path: string
  /** True if the entry is a directory. Set by in-app drags, and by OS drops via
   * DataTransferItem.webkitGetAsEntry(). */
  isDirectory?: boolean
  /** First line number for in-app line-ref drags (source view gutter). */
  line?: number
  /** Last line number for line-range drags (`line..lineEnd` inclusive). */
  lineEnd?: number
  /** A link dragged out of a browser (`text/uri-list`). Path-less; becomes an `@url:` chip. */
  url?: string
}

/** Resolve a native drop to a host-visible path, staging browser File bytes
 * when the shell cannot expose a native filesystem path. Shared by both the
 * main composer and message-edit composer so neither silently drops files.
 * Empty when there is nothing to stage; a rejected stage keeps the server's
 * or a proxy's reason (an nginx 413) for the caller to report. */
export async function stageDroppedFilePath(candidate: DroppedFile): Promise<string> {
  if (candidate.path) {
    return candidate.path
  }

  // A folder without a host path has no bytes to stage.
  if (candidate.isDirectory) {
    throw new Error("Folders can't be attached by dropping them. Use Attach → Folder… instead.")
  }

  if (!candidate.file || !window.hermesDesktop?.stageFileForAttach) {
    return ''
  }

  return window.hermesDesktop.stageFileForAttach(candidate.file)
}

/** Stage a drop for the main composer's chips. A rejected stage keeps its
 * reason in the failure the drop warning shows, not a bare "Could not attach". */
async function stageDropForChip(candidate: DroppedFile, name: string): Promise<{ failure: DropFailure; path: string }> {
  try {
    return { failure: { name }, path: await stageDroppedFilePath(candidate) }
  } catch (error) {
    const reason = readableError(error, '').message

    return { failure: reason ? { name, reason } : { name }, path: '' }
  }
}

/** MIME emitted by in-app drag sources (project tree, gutter line numbers).
 * Payload is JSON `{ path; isDirectory?; line?; lineEnd? }[]`. */
export const HERMES_PATHS_MIME = 'application/x-hermes-paths'

/**
 * Eagerly resolve files from a drop event into [File?, path, isDirectory?]
 * triples. Internal Hermes sources (e.g. the project tree) ride on a custom
 * MIME and produce path-only entries; OS drops produce File-bearing entries.
 *
 * Must be called synchronously from inside the drop handler — `DataTransfer`
 * items are detached as soon as the handler returns, and `webUtils.getPathForFile`
 * also requires the original (non-cloned) File reference.
 */
export function extractDroppedFiles(transfer: DataTransfer): DroppedFile[] {
  const result: DroppedFile[] = []
  const seenPaths = new Set<string>()
  const seenFiles = new Set<File>()
  const getPath = window.hermesDesktop?.getPathForFile
  const urls = droppedLinkUrls(transfer)

  // In-app drags first — they carry richer metadata (isDirectory) than the
  // File-based fallback can provide, and produce no overlapping native files.
  try {
    const internalRaw = transfer.getData(HERMES_PATHS_MIME)

    if (internalRaw) {
      const parsed = JSON.parse(internalRaw) as {
        path?: unknown
        isDirectory?: unknown
        line?: unknown
        lineEnd?: unknown
      }[]

      const positiveInt = (value: unknown) => (typeof value === 'number' && value > 0 ? Math.floor(value) : undefined)

      for (const entry of parsed) {
        if (!entry || typeof entry.path !== 'string' || !entry.path) {
          continue
        }

        const line = positiveInt(entry.line)
        const rawEnd = positiveInt(entry.lineEnd)
        const lineEnd = line && rawEnd && rawEnd > line ? rawEnd : undefined
        const dedupKey = line ? `${entry.path}:${line}-${lineEnd ?? line}` : entry.path

        if (seenPaths.has(dedupKey)) {
          continue
        }

        seenPaths.add(dedupKey)
        result.push({ isDirectory: entry.isDirectory === true, line, lineEnd, path: entry.path })
      }
    }
  } catch {
    // Malformed payload — fall through to native files.
  }

  // Add a native OS-drop entry. A dropped directory has no byte content to
  // upload, so it's emitted as a path-only entry with `isDirectory: true` —
  // that routes it to a `@folder:` ref / folder attachment (like the folder
  // picker) instead of the file-upload pipeline, which can't stage a directory
  // (the gateway can't read its bytes and there's no data_url to send).
  const pushNativeEntry = (file: File, isDirectory: boolean) => {
    if (seenFiles.has(file)) {
      return
    }

    seenFiles.add(file)
    let path = ''

    if (getPath) {
      try {
        path = getPath(file) || ''
      } catch {
        path = ''
      }
    }

    // A link dragged out of a browser rides along as a virtual shortcut File
    // (`<title>.url` on Windows, `.webloc` on macOS) with no on-disk path. It
    // is the same link `text/uri-list` already carries, so drop the stub and
    // let the URL become a chip instead of toasting "Could not attach X.url".
    // A path-less *image* (dragged off a web page) keeps its bytes and wins
    // over the link to its own src.
    if (!path && urls.length) {
      if (isImagePath(file.name) || file.type.startsWith('image/')) {
        urls.length = 0
      } else {
        return
      }
    }

    if (path && seenPaths.has(path)) {
      return
    }

    if (path) {
      seenPaths.add(path)
    }

    // A folder with no host path (the browser Webapp) keeps its File, so the
    // drop reaches the attach pipeline and is reported there, not dropped.
    if (isDirectory) {
      result.push(path ? { isDirectory: true, path } : { file, isDirectory: true, path })

      return
    }

    result.push({ file, path })
  }

  // Process items first: DataTransferItem.webkitGetAsEntry() is the only
  // synchronous way to tell a dropped folder from a file, and it lives only on
  // items (not transfer.files). Must be read here, inside the drop handler,
  // before the DataTransfer detaches.
  const items = transfer.items

  if (items) {
    for (let i = 0; i < items.length; i += 1) {
      const item = items[i]

      if (!item || item.kind !== 'file') {
        continue
      }

      let isDirectory = false

      try {
        const entry = typeof item.webkitGetAsEntry === 'function' ? item.webkitGetAsEntry() : null
        isDirectory = entry?.isDirectory === true
      } catch {
        isDirectory = false
      }

      const file = item.getAsFile()

      if (!file) {
        continue
      }

      pushNativeEntry(file, isDirectory)
    }
  }

  // Fallback for environments that populate transfer.files but not items.
  // webkitGetAsEntry isn't available on this path, so directory detection
  // relies on the items pass above; anything reaching here is treated as a file.
  const fileList = transfer.files

  if (fileList) {
    for (let i = 0; i < fileList.length; i += 1) {
      const file = fileList.item(i)

      if (!file) {
        continue
      }

      pushNativeEntry(file, false)
    }
  }

  for (const url of urls) {
    result.push({ path: '', url })
  }

  return result
}

/** `http(s)` links from a `text/uri-list` payload (one per line, `#` comments
 * skipped), deduped. Empty when the drag carried none. */
function droppedLinkUrls(transfer: DataTransfer): string[] {
  let raw = ''

  try {
    raw = transfer.getData('text/uri-list') || ''
  } catch {
    return []
  }

  const urls: string[] = []

  for (const line of raw.split(/\r?\n/)) {
    const url = line.trim()

    if (/^https?:\/\/[^/\s]/i.test(url) && !urls.includes(url)) {
      urls.push(url)
    }
  }

  return urls
}

/**
 * Split dropped entries by origin. OS/Finder drops carry a native `File`
 * handle; in-app drags (project tree, gutter line refs) are path-only.
 *
 * The distinction is load-bearing: an in-app path is workspace-relative and
 * resolves on the gateway as-is, so it stays an inline `@file:`/`@line:` ref.
 * An OS drop is an absolute path on *this* machine — the gateway can't read it
 * in remote mode, and an image needs its bytes uploaded to get vision either
 * way. So OS drops must go through the attachment/upload pipeline rather than
 * leaking a local path into the prompt text.
 *
 * `staging` narrows that: when the session's backend resolves this machine's
 * paths as-is (a local connection on a shared filesystem — #52427), a
 * non-image OS drop keeps its original-path inline `@file:` ref instead of
 * being copied into the gateway's staging dir. Without it (legacy callers)
 * every OS drop is staged, as before.
 */
export interface OsDropStagingContext {
  /** The session's backend cwd — cross-filesystem detection (Windows host → POSIX backend). */
  backendCwd?: null | string
  /** Whether the connection owning the session is a remote gateway. */
  remote?: boolean
  /** Terminal backend name from session.info (local | docker | ssh | ...). */
  terminalBackend?: null | string
}

function osDropNeedsStaging(candidate: DroppedFile, staging?: OsDropStagingContext): boolean {
  if (!staging) {
    return true
  }

  // No path -> no inline ref is possible; keep it on the upload pipeline so
  // the failure surfaces ("Could not attach") instead of the drop vanishing.
  if (!candidate.path) {
    return true
  }

  // Images keep the attach pipeline everywhere: vision needs the bytes queued
  // gateway-side even when the path itself resolves.
  const file = candidate.file

  if (file && (file.type.startsWith('image/') || isImagePath(file.name))) {
    return true
  }

  if (isImagePath(candidate.path)) {
    return true
  }

  return (
    Boolean(staging.remote) || attachmentPathNeedsUpload(candidate.path, staging.backendCwd, staging.terminalBackend)
  )
}

export function partitionDroppedFiles(
  candidates: DroppedFile[],
  staging?: OsDropStagingContext
): {
  osDrops: DroppedFile[]
  inAppRefs: DroppedFile[]
} {
  const osDrops: DroppedFile[] = []
  const inAppRefs: DroppedFile[] = []

  for (const candidate of candidates) {
    if (candidate.file && osDropNeedsStaging(candidate, staging)) {
      osDrops.push(candidate)
    } else {
      inAppRefs.push(candidate)
    }
  }

  return { osDrops, inAppRefs }
}

/** The composer these actions feed. Defaults to the main chat's scope;
 *  session tiles pass their own so picks/drops/pastes land in THEIR chips. */
interface ComposerActionsScope {
  add: (attachment: ComposerAttachment) => void
  remove: (id: string) => ComposerAttachment | null
  update: (attachment: ComposerAttachment) => boolean
  updateIfCurrent: (expected: ComposerAttachment, patch: ComposerAttachmentPatch) => boolean
  target: string
}

const MAIN_ACTIONS_SCOPE: ComposerActionsScope = {
  add: addComposerAttachment,
  remove: removeComposerAttachment,
  update: updateComposerAttachment,
  updateIfCurrent: patchMainComposerAttachmentOccurrence,
  target: 'main'
}

interface ComposerActionsOptions {
  activeSessionId: string | null
  currentCwd: string
  requestGateway: <T>(method: string, params?: Record<string, unknown>) => Promise<T>
  scope?: ComposerActionsScope
}

export function useComposerActions({
  activeSessionId,
  currentCwd,
  requestGateway,
  scope = MAIN_ACTIONS_SCOPE
}: ComposerActionsOptions) {
  const { t } = useI18n()
  const copy = t.desktop

  /** Add to this scope's composer and focus it. All sidebar/picker/drop
   *  attach paths funnel through here. */
  const attachToMain = useCallback(
    (attachment: ComposerAttachment) => {
      const stagedUpload =
        attachment.kind === 'file' && attachment.path
          ? window.hermesDesktop?.getStagedFileForAttach?.(attachment.path)
          : undefined

      const displayName =
        attachment.kind === 'file' && attachment.path && attachment.label === pathLabel(attachment.path)
          ? window.hermesDesktop?.getStagedFileDisplayName?.(attachment.path)
          : undefined

      scope.add({
        ...attachment,
        ...(stagedUpload ? { stagedUpload } : {}),
        ...(displayName ? { label: displayName } : {})
      })
      requestComposerFocus(scope.target)
    },
    [scope]
  )

  const addTextToDraft = useCallback((text: string) => {
    requestComposerInsert(text, { mode: 'block' })
  }, [])

  const addTerminalSelectionAttachment = useCallback((text: string, label = 'selection') => {
    const trimmed = text.trim()
    const normalizedLabel = label.trim() || 'selection'
    const refText = `@terminal:${formatRefValue(normalizedLabel)}`

    if (!trimmed) {
      return
    }

    setComposerTerminalSelection(normalizedLabel, trimmed)
    requestComposerInsert(refText, { mode: 'inline' })
  }, [])

  const addContextRefAttachment = useCallback(
    (refText: string, label?: string, detail?: string) => {
      const kind: ComposerAttachment['kind'] = refText.startsWith('@folder:')
        ? 'folder'
        : refText.startsWith('@url:')
          ? 'url'
          : 'file'

      attachToMain({
        id: attachmentId(kind, refText),
        kind,
        label: label || refText.replace(/^@(file|folder|url):/, ''),
        detail,
        refText
      })
    },
    [attachToMain]
  )

  const pickContextPaths = useCallback(
    async (kind: 'file' | 'folder') => {
      let paths: string[]

      try {
        paths = await selectDesktopPaths({
          title: kind === 'file' ? 'Add files as context' : 'Add folders as context',
          defaultPath: currentCwd || undefined,
          directories: kind === 'folder'
        })
      } catch (err) {
        // As in pickImages: the browser stages a pick before returning its path, and a refused
        // stage (a file over the upload limit) is reported here, not left as an unhandled rejection.
        notifyError(err, copy.attachFailed)

        return
      }

      if (!paths?.length) {
        return
      }

      for (const path of paths) {
        const rel = contextPath(path, currentCwd)

        attachToMain({
          id: attachmentId(kind, rel),
          kind,
          label: pathLabel(path),
          detail: rel,
          refText: `@${kind}:${formatRefValue(rel)}`,
          path
        })
      }
    },
    [attachToMain, copy.attachFailed, currentCwd]
  )

  const insertContextPathInlineRef = useCallback(
    (path: string, isDirectory = false) => {
      if (!path) {
        return false
      }

      const ref = droppedFileInlineRef({ isDirectory, path }, currentCwd)

      if (!ref) {
        return false
      }

      requestComposerInsertRefs([ref], { target: scope.target })
      requestComposerFocus(scope.target)

      return true
    },
    [currentCwd, scope.target]
  )

  const attachContextFilePath = useCallback(
    (filePath: string) => {
      if (!filePath) {
        return false
      }

      const rel = contextPath(filePath, currentCwd)

      attachToMain({
        id: attachmentId('file', rel),
        kind: 'file',
        label: pathLabel(filePath),
        detail: rel,
        refText: `@file:${formatRefValue(rel)}`,
        path: filePath
      })

      return true
    },
    [attachToMain, currentCwd]
  )

  const attachImagePath = useCallback(
    async (filePath: string, previewSource?: Blob | null) => {
      if (!filePath) {
        return false
      }

      const baseAttachment: ComposerAttachment = {
        id: attachmentId('image', filePath),
        occurrenceId: createComposerAttachmentOccurrenceId(),
        kind: 'image',
        label: pathLabel(filePath),
        detail: filePath,
        path: filePath
      }

      attachToMain(baseAttachment)

      try {
        // OS drops / clipboard blobs pass their File/Blob so preview never
        // base64-loads the full image over IPC (Windows freeze on Explorer
        // drag-drop — #63682). Path-only picks keep the queued IPC thumbnail
        // path; blob previews skip the read entirely.
        if (previewSource && previewSource.size > 0) {
          const previewUrl = URL.createObjectURL(previewSource)

          scope.updateIfCurrent(baseAttachment, { previewUrl })

          return true
        }

        const { previewUrl, thumbnailUrl } = await queuedAttachmentPreview(filePath)

        if (previewUrl) {
          // Keep only the bounded thumbnail in composer state. The full source
          // is read on demand for lightbox/download and separately at submit
          // for the model, so retaining 72 multi-MB data URLs serves no purpose.
          // Bind the late preview to this attachment occurrence's stable token.
          // Object identity is insufficient because a session draft round-trip
          // clones attachments; id alone is insufficient because remove +
          // reattach of the same path reuses it.
          scope.updateIfCurrent(baseAttachment, thumbnailUrl ? { thumbnailUrl } : { previewUrl })
        }

        return true
      } catch (err) {
        notifyError(err, copy.imagePreviewFailed)

        return true
      }
    },
    [attachToMain, copy.imagePreviewFailed, scope]
  )

  const attachImageBlob = useCallback(
    async (blob: Blob, isCurrent: () => boolean = () => true) => {
      if (blob.size === 0 || !isCurrent()) {
        return false
      }

      if (blob.type && !blob.type.startsWith('image/')) {
        return false
      }

      try {
        const buffer = await blob.arrayBuffer()

        if (!isCurrent()) {
          return false
        }

        const data = new Uint8Array(buffer)
        const name = blob instanceof File ? blob.name : undefined
        const savedPath = await window.hermesDesktop?.saveImageBuffer(data, blobExtension(blob), name)

        if (!savedPath) {
          notify({ kind: 'error', title: copy.imageAttach, message: copy.imageWriteFailed })

          return false
        }

        // Reuse the in-hand blob for the chip preview — do not re-read the
        // just-written temp file as a data URL. A late component unmount must
        // not leak the attach: attach only while still current.
        return isCurrent() ? attachImagePath(savedPath, blob) : false
      } catch (err) {
        notifyError(err, copy.imageAttachFailed)

        return false
      }
    },
    [attachImagePath, copy.imageAttach, copy.imageAttachFailed, copy.imageWriteFailed]
  )

  const pickImages = useCallback(async () => {
    let paths: string[]

    try {
      paths = await selectDesktopPaths({
        title: copy.attachImages,
        defaultPath: currentCwd || undefined,
        filters: [
          {
            name: t.composer.images,
            extensions: ['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'tiff']
          }
        ]
      })
    } catch (err) {
      // The browser stages a pick before returning its path; a refused stage (an image over the
      // upload limit) is reported here, not left as an unhandled rejection.
      notifyError(err, copy.imageAttachFailed)

      return
    }

    if (!paths?.length) {
      return
    }

    for (const path of paths) {
      await attachImagePath(path)
    }
  }, [attachImagePath, copy.attachImages, copy.imageAttachFailed, currentCwd, t.composer.images])

  const pasteClipboardImage = useCallback(
    async ({ silent = false }: { silent?: boolean } = {}) => {
      try {
        const path = await window.hermesDesktop?.saveClipboardImage()

        if (!path) {
          if (!silent) {
            notify({
              kind: 'warning',
              title: copy.clipboard,
              message: copy.noClipboardImage
            })
          }

          return false
        }

        await attachImagePath(path)

        return true
      } catch (err) {
        if (!silent) {
          notifyError(err, copy.clipboardPasteFailed)
        }

        return false
      }
    },
    [attachImagePath, copy.clipboard, copy.clipboardPasteFailed, copy.noClipboardImage]
  )

  /**
   * Convert a very large plain-text paste into a `.txt` attachment chip.
   * The trimmed, sanitized paste text is written to a
   * Hermes-managed composer-pastes file via the main process, then attached
   * through the same `@file:` pipeline as a manually attached text file.
   * Returns false (paste stays inline) when the desktop bridge is missing
   * or the write fails.
   */
  const attachPastedText = useCallback(
    async (text: string) => {
      const save = window.hermesDesktop?.savePastedText

      if (!text || !save) {
        return false
      }

      try {
        const savedPath = await save(text)

        if (!savedPath) {
          return false
        }

        attachToMain({
          id: attachmentId('file', savedPath),
          kind: 'file',
          label: `${copy.pastedContent} (${pasteSizeLabel(text)})`,
          detail: contextPath(savedPath, currentCwd),
          refText: `@file:${formatRefValue(savedPath)}`,
          path: savedPath,
          titlePreview: text.slice(0, LARGE_PASTE_TITLE_PREVIEW_CHARS)
        })

        return true
      } catch (err) {
        notifyError(err, copy.pasteAttachFailed)

        return false
      }
    },
    [attachToMain, copy.pasteAttachFailed, copy.pastedContent, currentCwd]
  )

  const attachContextFolderPath = useCallback(
    (folderPath: string) => {
      if (!folderPath) {
        return false
      }

      const rel = contextPath(folderPath, currentCwd)

      attachToMain({
        id: attachmentId('folder', rel),
        kind: 'folder',
        label: pathLabel(folderPath),
        detail: rel,
        refText: `@folder:${formatRefValue(rel)}`,
        path: folderPath
      })

      return true
    },
    [attachToMain, currentCwd]
  )

  const attachDroppedItems = useCallback(
    async (candidates: DroppedFile[]) => {
      if (candidates.length === 0) {
        return false
      }

      let attached = false
      // Every item that failed, so a drop that attached some files still names the rest.
      const failures: DropFailure[] = []

      for (const candidate of candidates) {
        const { file, isDirectory, path: knownPath } = candidate

        // Path-only entry (in-app drag from the file browser tree, etc.).
        if (!file) {
          if (isDirectory) {
            if (knownPath && attachContextFolderPath(knownPath)) {
              attached = true

              continue
            }

            failures.push({ name: `folder ${knownPath || ''}` })

            continue
          }

          if (knownPath && isImagePath(knownPath)) {
            if (await attachImagePath(knownPath)) {
              attached = true

              continue
            }

            failures.push({ name: knownPath })

            continue
          }

          if (knownPath && attachContextFilePath(knownPath)) {
            attached = true

            continue
          }

          failures.push({ name: knownPath || 'file' })

          continue
        }

        const fallbackPath =
          !knownPath && window.hermesDesktop?.getPathForFile ? window.hermesDesktop.getPathForFile(file) : ''

        const filePath = knownPath || fallbackPath || ''
        const isImage = isDroppedImage(file, filePath, isDirectory)

        if (isImage) {
          // Persist the File bytes into Desktop's durable composer-image cache
          // FIRST: Finder may expose a dropped screenshot through a short-lived
          // TemporaryItems/NSIRD_screencaptureui path even when the visible file
          // has already landed on Desktop — reading that path for the preview
          // can succeed, then image.attach fails after macOS removes it before
          // submit. attachImageBlob also hands the in-hand blob through for a
          // non-blocking object-URL chip preview (#63682); the native path stays
          // the fallback for shells that cannot save the buffer.
          if ((await attachImageBlob(file)) || (filePath && (await attachImagePath(filePath, file)))) {
            attached = true

            continue
          }

          failures.push({ name: file.name || 'image' })

          continue
        }

        // The resolved native path wins; with none, the File bytes are staged.
        const staged = await stageDropForChip({ ...candidate, path: filePath }, file.name || 'file')

        if (staged.path && attachContextFilePath(staged.path)) {
          attached = true

          continue
        }

        failures.push(staged.failure)
      }

      if (failures.length) {
        notify({ kind: 'warning', title: copy.dropFiles, ...dropWarning(failures, copy.dropFilesMore) })
      }

      return attached
    },
    [attachContextFilePath, attachContextFolderPath, attachImageBlob, attachImagePath, copy.dropFiles, copy.dropFilesMore]
  )

  const removeAttachment = useCallback(
    async (id: string) => {
      const removed = scope.remove(id)

      if (
        removed?.kind === 'image' &&
        removed.path &&
        activeSessionId &&
        removed.attachedSessionId &&
        removed.attachedSessionId === activeSessionId
      ) {
        await requestGateway<ImageDetachResponse>('image.detach', {
          session_id: activeSessionId,
          path: removed.path
        }).catch(() => undefined)
      }
    },
    [activeSessionId, requestGateway, scope]
  )

  return {
    addContextRefAttachment,
    addTerminalSelectionAttachment,
    addTextToDraft,
    attachContextFilePath,
    attachContextFolderPath,
    attachDroppedItems,
    attachImageBlob,
    attachImagePath,
    attachPastedText,
    insertContextPathInlineRef,
    pasteClipboardImage,
    pickContextPaths,
    pickImages,
    removeAttachment
  }
}