Files
orca/src/shared/native-file-drop.ts
T
Jinjing 449b8ca17d fix(drop): route local terminal and composer drops through the resolver (#24009)
* fix(drop): copy macOS drag-temp files so the PTY daemon can read them

macOS screenshot thumbnails live in $TMPDIR/TemporaryItems/NSIRD_*, which
only processes attributed to Orca main may open. The detached PTY daemon is
not, so agents in local terminals get EPERM and Claude Code silently drops
the paste.

fs:resolveDroppedPathsForAgent now copies those files, and only those, into a
private per-user orca-drops-<uid>/orca-drop-XXXXXX/ directory, keeping the
original name. It streams from an O_NOFOLLOW handle capped at the inspected
size, so no xattrs (com.apple.macl) come along. The copy is 0600 in a 0700
directory, bounded by the remote-import per-file and per-drop limits, and
rechecked for changes. Other paths pass through. The local branch returns
per-item results, authorizes what it returns, and accepts no worktreePath.
Expired copies are swept 7 days later.

No renderer calls the local branch outside WSL yet, so this ships dark
until the renderer routes local drops through it.

* fix(drop): route local terminal and composer drops through the resolver

Local terminal drops pasted the dropped path directly, and composer drops
attached it after a per-path authorize call. So a macOS screenshot thumbnail
reached Claude Code as a path in a folder the PTY daemon can't open, and the
paste was silently dropped.

Every local terminal drop now calls fs:resolveDroppedPathsForAgent, pastes
what it returns, and reports skips and failures with local wording ("Could
not prepare N dropped files"). The WSL-only branch and the direct-paste
branch are gone; the local-WSL path mapping stays as a step after
resolution. The composer resolves the whole drop in one call, without a
project path so its attachments never get the WSL rewrite, stats only the
resolved paths, and folds resolver skips and failures into its existing
toast. The pane, transport, mounted and owner checks still run after the
await.

* test: verify resolver and write errors surface independently on drop

Add a test case ensuring that when path resolution and PTY write both fail during a file drop, the UI reports both failures separately rather than letting the write error mask the resolution issues. Refactor error handling in pasteLocalDropPaths to catch IPC resolution errors immediately, then handle paste errors separately, so skipped/failed files are always reported via the finally block regardless of outcome.

* test: extract transport variable in drop resolution test

Improves readability by extracting the terminal transport creation from the Map initialization.

* refactor(drop): extract native file drop relay and temp staging utilitie

- Move the native file drop relay queue from attach-main-window-services into
  a dedicated native-file-drop-relay module so it owns the async copy and
  forward pipeline for drag-temp files, separate from main window setup.
- Extract shared temp-directory management (ownership checks, sweeps,
  permissions) into owned-temp-staging-root, used by both drag-temp copies
  and remote clipboard staging.
- Simplify dropped-path-resolution to handle only the WSL path rewrite on
  local worktrees; the relay handles macOS drag-temp copying before it
  reaches terminal/composer drop handlers.

* fix(drop): pass drag-temp files through uncopied with timeout and budget

Large files exceeding the copy budget are now passed through uncopied instead
of rejecting the drop, so copy failures don't lose the entire interaction.
Copy timeout prevents hung copies from blocking subsequent drops, and budget
tracking accounts for retained copies to prevent disk fill.
Extract darwin-user-temp-dir to resolve the correct macOS per-user temp dir
rather than relying on $TMPDIR.

* fix(drop): discard queued drops on renderer reload

Capture the renderer's lifetime when a drop is enqueued. When the
renderer reloads before a copy completes, the operation cancels and
queued drops are discarded, preventing stale content from reaching
the reloaded document.

* fix(drop): serialize drag-temp copies and localize failure reasons

Main no longer sends user-facing failure messages; instead it sends reason tokens
that the renderer localizes. Drag-temp copies run serially under one byte budget
with a pending-copy limit, so non-temp drops can overtake. When a copy stage
aborts, remove any partial copies made so far. Distinguish 'uncopied' (original
handed over) from 'failed' (couldn't get it at all), and add specific reasons for
storage, permission, timeout, and budget exhaustion.

* fix(drop): serialize drops and extend TTL to 7 days

Ensure drops reach the renderer in arrival order by queuing all path drops,
not just copies. Extend TTL from 24h to 7d to support lazy readers like
drafts and startup prompts. Withhold uncopied files from agents that can't
open originals (terminal, composer), keeping editor-only access working.
2026-10-01 10:00:31 -07:00

323 lines
9.8 KiB
TypeScript

import { measureClipboardTextByteLength } from './clipboard-text'
export const ORCA_INTERNAL_FILE_DRAG_TYPE = 'text/x-orca-file-path'
export const NATIVE_FILE_DROP_MAX_PATHS = 256
export const NATIVE_FILE_DROP_MAX_PATH_BYTES = 256 * 1024
export const NATIVE_FILE_DROP_TARGET = {
editor: 'editor',
terminal: 'terminal',
composer: 'composer',
fileExplorer: 'file-explorer',
projectSidebar: 'project-sidebar'
} as const
export type NativeDropResolution =
| { target: typeof NATIVE_FILE_DROP_TARGET.editor }
| { target: typeof NATIVE_FILE_DROP_TARGET.terminal; tabId?: string; paneLeafId?: string }
| { target: typeof NATIVE_FILE_DROP_TARGET.composer; scopeKey?: string }
| { target: typeof NATIVE_FILE_DROP_TARGET.fileExplorer; destinationDir: string }
| { target: typeof NATIVE_FILE_DROP_TARGET.projectSidebar }
| { target: 'rejected' }
export type NativeFileDropPayload =
| { paths: string[]; target: typeof NATIVE_FILE_DROP_TARGET.editor }
| {
paths: string[]
target: typeof NATIVE_FILE_DROP_TARGET.terminal
tabId?: string
paneLeafId?: string
}
| { paths: string[]; target: typeof NATIVE_FILE_DROP_TARGET.composer; scopeKey?: string }
| {
paths: string[]
target: typeof NATIVE_FILE_DROP_TARGET.fileExplorer
destinationDir: string
}
| { paths: string[]; target: typeof NATIVE_FILE_DROP_TARGET.projectSidebar }
| NativeFileDropRejectedPayload
export type NativeFileDropRejectedPayload = {
byteLength: number
pathCount: number
reason: NativeFileDropRejectionReason
target: 'rejected'
/** Why every file in a `temp-copy-failed` drop went uncopied, when they share one reason. */
commonReason?: NativeFileDropCopyFailureReason
}
// Why tokens: the renderer owns the localized copy; main never sends display text.
export const NATIVE_FILE_DROP_COPY_FAILURE_REASONS = [
'missing',
'permission-denied',
'changed',
'out-of-space',
'storage-unavailable',
'storage-not-private',
'copy-failed',
'timed-out',
'busy',
// Too big to copy, so agents in terminals and composers can't be given it.
'too-large',
'storage-full'
] as const
export type NativeFileDropCopyFailureReason = (typeof NATIVE_FILE_DROP_COPY_FAILURE_REASONS)[number]
/** What path validation alone can reject a drop for. */
export type NativeFileDropSizeRejectionReason = 'paths-too-large' | 'too-many-paths'
/** `unresolved-paths`: the OS handed us file items no path could be read from
* (promised/virtual files), which used to be swallowed with no feedback.
* `temp-copy-failed`: main could not copy a macOS drag-temp file; only main sends it. */
export type NativeFileDropRejectionReason =
| NativeFileDropSizeRejectionReason
| 'unresolved-paths'
| 'temp-copy-failed'
export type NativeFileDropPathEntry = {
nativeFileDropTarget?: string
nativeFileDropDir?: string
composerScopeKey?: string
terminalTabId?: string
terminalPaneLeafId?: string
}
export type NativeFileDropPathValidation =
| { byteLength: number; pathCount: number; status: 'accepted' }
| {
byteLength: number
pathCount: number
reason: NativeFileDropSizeRejectionReason
status: 'rejected'
}
function isNativeFileDropRejectedReason(
reason: unknown
): reason is NativeFileDropRejectedPayload['reason'] {
return (
reason === 'paths-too-large' ||
reason === 'too-many-paths' ||
reason === 'unresolved-paths' ||
reason === 'temp-copy-failed'
)
}
function isNativeFileDropCopyFailureReason(
reason: unknown
): reason is NativeFileDropCopyFailureReason {
return NATIVE_FILE_DROP_COPY_FAILURE_REASONS.some((known) => known === reason)
}
function isNativeFileDropTarget(target: unknown): target is NativeFileDropPayload['target'] {
return Object.values(NATIVE_FILE_DROP_TARGET).includes(target as never) || target === 'rejected'
}
function isOptionalNativeFileDropString(value: unknown): value is string | undefined {
return value === undefined || typeof value === 'string'
}
function isNativeFileDropPathList(value: unknown): value is string[] {
return Array.isArray(value) && value.every((path) => typeof path === 'string')
}
function isNonNegativeFiniteNumber(value: unknown): value is number {
return typeof value === 'number' && Number.isFinite(value) && value >= 0
}
function getDataTransferTypes(
types: Iterable<string> | ArrayLike<string> | null | undefined
): string[] {
return types ? Array.from(types) : []
}
export function hasNativeFileDragTypes(
types: Iterable<string> | ArrayLike<string> | null | undefined
): boolean {
const values = getDataTransferTypes(types)
return values.includes('Files') && !values.includes(ORCA_INTERNAL_FILE_DRAG_TYPE)
}
export function resolveNativeFileDropPath(
path: readonly NativeFileDropPathEntry[]
): NativeDropResolution | null {
let foundExplorer = false
let destinationDir: string | undefined
let terminalPaneLeafId: string | undefined
let composerScopeKey: string | undefined
for (const entry of path) {
terminalPaneLeafId ??= entry.terminalPaneLeafId
composerScopeKey ??= entry.composerScopeKey
const target = entry.nativeFileDropTarget
if (target === NATIVE_FILE_DROP_TARGET.terminal) {
return { target, tabId: entry.terminalTabId, paneLeafId: terminalPaneLeafId }
}
if (target === NATIVE_FILE_DROP_TARGET.composer) {
// Composer drops fan out window-wide, so carry the receiving composer's
// scope key the way a terminal drop carries its pane leaf id.
return { target, ...(composerScopeKey ? { scopeKey: composerScopeKey } : {}) }
}
if (target === NATIVE_FILE_DROP_TARGET.editor) {
return { target }
}
if (target === NATIVE_FILE_DROP_TARGET.projectSidebar) {
return { target }
}
if (target === NATIVE_FILE_DROP_TARGET.fileExplorer) {
foundExplorer = true
}
// Pick the nearest (innermost) destination directory marker.
if (destinationDir === undefined && entry.nativeFileDropDir) {
destinationDir = entry.nativeFileDropDir
}
}
if (foundExplorer) {
if (!destinationDir) {
return { target: 'rejected' }
}
return { target: NATIVE_FILE_DROP_TARGET.fileExplorer, destinationDir }
}
return null
}
export function validateNativeFileDropPaths(
paths: readonly string[],
options: {
maxPathBytes?: number
maxPaths?: number
} = {}
): NativeFileDropPathValidation {
const pathCount = paths.length
const maxPaths = options.maxPaths ?? NATIVE_FILE_DROP_MAX_PATHS
if (pathCount > maxPaths) {
return {
byteLength: 0,
pathCount,
reason: 'too-many-paths',
status: 'rejected'
}
}
const maxPathBytes = options.maxPathBytes ?? NATIVE_FILE_DROP_MAX_PATH_BYTES
let byteLength = 0
for (const path of paths) {
const measurement = measureClipboardTextByteLength(path, {
stopAfterBytes: maxPathBytes - byteLength
})
byteLength += measurement.byteLength
if (byteLength > maxPathBytes) {
return {
byteLength,
pathCount,
reason: 'paths-too-large',
status: 'rejected'
}
}
}
return { byteLength, pathCount, status: 'accepted' }
}
export function createRejectedNativeFileDropPayload(
validation: Extract<NativeFileDropPathValidation, { status: 'rejected' }>
): NativeFileDropRejectedPayload {
return {
byteLength: validation.byteLength,
pathCount: validation.pathCount,
reason: validation.reason,
target: 'rejected'
}
}
export function createNativeFileDropPayload(
resolution: NativeDropResolution | null,
paths: readonly string[]
): NativeFileDropPayload | null {
const validation = validateNativeFileDropPaths(paths)
if (validation.status === 'rejected') {
return createRejectedNativeFileDropPayload(validation)
}
if (resolution?.target === 'rejected') {
return null
}
if (resolution?.target === NATIVE_FILE_DROP_TARGET.fileExplorer) {
return {
paths: [...paths],
target: NATIVE_FILE_DROP_TARGET.fileExplorer,
destinationDir: resolution.destinationDir
}
}
if (resolution?.target === NATIVE_FILE_DROP_TARGET.composer) {
return {
paths: [...paths],
target: resolution.target,
...(resolution.scopeKey ? { scopeKey: resolution.scopeKey } : {})
}
}
const target = resolution?.target ?? NATIVE_FILE_DROP_TARGET.editor
if (resolution?.target === NATIVE_FILE_DROP_TARGET.terminal) {
return {
paths: [...paths],
target: resolution.target,
...(resolution.tabId ? { tabId: resolution.tabId } : {}),
...(resolution.paneLeafId ? { paneLeafId: resolution.paneLeafId } : {})
}
}
return { paths: [...paths], target }
}
export function isNativeFileDropPayload(value: unknown): value is NativeFileDropPayload {
if (!value || typeof value !== 'object') {
return false
}
const payload = value as Record<string, unknown>
const { target } = payload
if (!isNativeFileDropTarget(target)) {
return false
}
if (target === 'rejected') {
return (
isNonNegativeFiniteNumber(payload.byteLength) &&
isNonNegativeFiniteNumber(payload.pathCount) &&
isNativeFileDropRejectedReason(payload.reason) &&
(payload.commonReason === undefined ||
isNativeFileDropCopyFailureReason(payload.commonReason))
)
}
if (!isNativeFileDropPathList(payload.paths)) {
return false
}
if (validateNativeFileDropPaths(payload.paths).status !== 'accepted') {
return false
}
if (target === NATIVE_FILE_DROP_TARGET.terminal) {
return (
isOptionalNativeFileDropString(payload.tabId) &&
isOptionalNativeFileDropString(payload.paneLeafId)
)
}
if (target === NATIVE_FILE_DROP_TARGET.fileExplorer) {
return typeof payload.destinationDir === 'string'
}
if (target === NATIVE_FILE_DROP_TARGET.composer) {
return isOptionalNativeFileDropString(payload.scopeKey)
}
return (
target === NATIVE_FILE_DROP_TARGET.editor || target === NATIVE_FILE_DROP_TARGET.projectSidebar
)
}