diff --git a/src/crates/assembly/core/src/service/filesystem/upload.rs b/src/crates/assembly/core/src/service/filesystem/upload.rs index 3a010c69d1..4f26f7ed58 100644 --- a/src/crates/assembly/core/src/service/filesystem/upload.rs +++ b/src/crates/assembly/core/src/service/filesystem/upload.rs @@ -58,6 +58,9 @@ pub async fn workspace_file_upload( request.remote_connection_id.as_deref(), ) .await?; + if request.action == "begin" && is_runtime_attachment_uri(&request.path) { + ensure_runtime_attachment_parent(&target).await?; + } let scope = TransferScope { account_id, target_id, @@ -118,6 +121,49 @@ pub async fn workspace_file_upload( result.map_err(|error| error.to_string()) } +/// Top-level runtime directory that holds controller-supplied attachments. +const RUNTIME_ATTACHMENTS_DIR: &str = "attachments"; + +/// Whether `path` names a file below `openbitfun://runtime//attachments/`. +/// +/// A controller that does not share this host's filesystem (Peer Device Mode) +/// stages its local files there; agent tools resolve the same URI on this host. +fn is_runtime_attachment_uri(path: &str) -> bool { + use crate::agentic::tools::workspace_paths::{ + is_openbitfun_runtime_uri, parse_openbitfun_runtime_uri, + }; + if !is_openbitfun_runtime_uri(path) { + return false; + } + parse_openbitfun_runtime_uri(path).is_ok_and(|parsed| { + let mut segments = parsed.relative_path.split('/'); + segments.next() == Some(RUNTIME_ATTACHMENTS_DIR) && segments.count() >= 2 + }) +} + +/// Create the runtime-owned parent of an attachment upload. +/// +/// Workspace uploads deliberately require an existing parent. Attachment +/// directories are unique per upload and owned by this runtime, so they are +/// created here, confined to the resolved runtime root. +async fn ensure_runtime_attachment_parent( + target: &openbitfun_services_integrations::remote_connect::file_projection::SessionFileTarget, +) -> Result<(), String> { + if target.remote { + return Err("Runtime attachments must resolve to the executing host".into()); + } + let root = std::path::Path::new(&target.root); + let parent = std::path::Path::new(&target.path) + .parent() + .ok_or("Upload destination has no parent")?; + if !parent.starts_with(root) || parent == root { + return Err("Runtime attachment is outside its runtime root".into()); + } + tokio::fs::create_dir_all(parent) + .await + .map_err(|error| format!("Failed to create runtime attachment directory: {error}")) +} + #[cfg(test)] mod tests { use super::*; @@ -135,6 +181,25 @@ mod tests { assert!(error.contains("workspace identity is required"), "{error}"); } + #[test] + fn runtime_attachment_uri_requires_an_attachments_file() { + assert!(is_runtime_attachment_uri( + "openbitfun://runtime/ws-1/attachments/abc/report.pdf" + )); + assert!(!is_runtime_attachment_uri( + "openbitfun://runtime/ws-1/attachments/report.pdf" + )); + assert!(!is_runtime_attachment_uri( + "openbitfun://runtime/ws-1/plans/abc/plan.md" + )); + assert!(!is_runtime_attachment_uri( + "openbitfun://runtime/ws-1/attachments/../plans/x.md" + )); + assert!(!is_runtime_attachment_uri( + "/tmp/attachments/abc/report.pdf" + )); + } + #[tokio::test] async fn upload_stays_bound_to_explicit_local_workspace() { let directory = tempfile::tempdir().unwrap(); diff --git a/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json b/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json index b18c5968c3..512cc2ec40 100644 --- a/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json +++ b/src/crates/contracts/product-domains/src/generated/remote-surface-registry.json @@ -1,6 +1,6 @@ { "schemaVersion": 1, - "digest": "fnv1a64:f622fe54e98d2ae1", + "digest": "fnv1a64:416c934dda520065", "retiredCommandPrefixes": [ { "prefix": "lsp_", @@ -16,6 +16,7 @@ "dialog_queue_v1", "idempotent_dialog_submit", "inline_image_attachments_v1", + "runtime_attachment_upload_v1", "btw_initial_model_selection_v1", "btw_model_pool_selection_v1", "control_conversation_v1", @@ -64,6 +65,7 @@ "dialog_queue_v1", "idempotent_dialog_submit", "inline_image_attachments_v1", + "runtime_attachment_upload_v1", "btw_initial_model_selection_v1", "btw_model_pool_selection_v1", "control_conversation_v1", @@ -112,6 +114,7 @@ "control_conversation_reset_v1", "idempotent_dialog_submit", "inline_image_attachments_v1", + "runtime_attachment_upload_v1", "btw_initial_model_selection_v1", "btw_model_pool_selection_v1", "targeted_session_rollback", diff --git a/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs b/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs index 050bf50fc8..37b89ad5d5 100644 --- a/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs +++ b/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs @@ -33,6 +33,10 @@ pub enum PeerHostCapability { IdempotentDialogSubmit, /// Inline imageContexts are durably prepared by the receiving Runtime. InlineImageAttachmentsV1, + /// `workspace_file_upload` accepts `openbitfun://runtime//attachments/...` + /// targets and creates their runtime-owned parents, so a controller can + /// attach its own local files to a session executing on this host. + RuntimeAttachmentUploadV1, /// `btw_ask_stream` applies initial model and reasoning selection before the first turn. BtwInitialModelSelectionV1, /// BTW accepts typed initial model/pool choices and retains inherited bindings. @@ -129,6 +133,7 @@ impl PeerHostCapability { Self::DialogQueueV1, Self::IdempotentDialogSubmit, Self::InlineImageAttachmentsV1, + Self::RuntimeAttachmentUploadV1, Self::BtwInitialModelSelectionV1, Self::BtwModelPoolSelectionV1, Self::ControlConversationV1, @@ -180,6 +185,7 @@ impl PeerHostCapability { Self::DialogQueueV1 => "dialog_queue_v1", Self::IdempotentDialogSubmit => "idempotent_dialog_submit", Self::InlineImageAttachmentsV1 => "inline_image_attachments_v1", + Self::RuntimeAttachmentUploadV1 => "runtime_attachment_upload_v1", Self::ControlConversationV1 => "control_conversation_v1", Self::ControlConversationResetV1 => "control_conversation_reset_v1", Self::BtwInitialModelSelectionV1 => "btw_initial_model_selection_v1", @@ -238,6 +244,7 @@ const DESKTOP_CAPABILITIES: &[PeerHostCapability] = &[ PeerHostCapability::DialogQueueV1, PeerHostCapability::IdempotentDialogSubmit, PeerHostCapability::InlineImageAttachmentsV1, + PeerHostCapability::RuntimeAttachmentUploadV1, PeerHostCapability::BtwInitialModelSelectionV1, PeerHostCapability::BtwModelPoolSelectionV1, PeerHostCapability::ControlConversationV1, @@ -289,6 +296,7 @@ const CLI_CAPABILITIES: &[PeerHostCapability] = &[ PeerHostCapability::ControlConversationResetV1, PeerHostCapability::IdempotentDialogSubmit, PeerHostCapability::InlineImageAttachmentsV1, + PeerHostCapability::RuntimeAttachmentUploadV1, PeerHostCapability::BtwInitialModelSelectionV1, PeerHostCapability::BtwModelPoolSelectionV1, PeerHostCapability::TargetedSessionRollback, diff --git a/src/web-ui/src/app/components/panels/FilesPanel.tsx b/src/web-ui/src/app/components/panels/FilesPanel.tsx index 444a94aa83..a850694491 100644 --- a/src/web-ui/src/app/components/panels/FilesPanel.tsx +++ b/src/web-ui/src/app/components/panels/FilesPanel.tsx @@ -55,6 +55,7 @@ import { pasteClipboardFilesToWorkspaceDirectory, resolvePasteTargetDirectory, type TransferProgressState, + type WorkspaceTransferResult, } from '@/tools/file-system/services/workspaceFileTransfer'; import { useWorkspaceFileDrop } from '@/tools/file-system/hooks/useWorkspaceFileDrop'; import { useShortcut } from '@/infrastructure/hooks/useShortcut'; @@ -909,13 +910,28 @@ const FilesPanel: React.FC = ({ setFileDropHighlight(overPanel); }, []); - const handleFileDropComplete = useCallback((targetDirectory: string) => { + const handleFileDropComplete = useCallback(( + targetDirectory: string, + _transferId: string, + result: WorkspaceTransferResult, + ) => { setFileDropHighlight(false); void loadFileTree(workspacePath || '', true); if (workspacePath && !pathsEquivalentFs(targetDirectory, workspacePath)) { expandFolder(targetDirectory, true); } - }, [workspacePath, loadFileTree, expandFolder]); + // Items that were refused or failed must not disappear silently. + if (result.failedFiles.length > 0) { + const failedNames = result.failedFiles.map((entry) => { + const name = entry.path.split(/[/\\]/).pop() || entry.path; + return `${name}: ${entry.error}`; + }).join('\n'); + notification.error( + t('notifications.pasteFailed', { count: result.failedFiles.length }) + `:\n${failedNames}`, + { duration: 5000 }, + ); + } + }, [workspacePath, loadFileTree, expandFolder, notification, t]); const handleFileDropError = useCallback(( error: unknown, diff --git a/src/web-ui/src/app/scenes/miniapps/views/MiniAppGalleryView.tsx b/src/web-ui/src/app/scenes/miniapps/views/MiniAppGalleryView.tsx index 121f7e5acb..7ce1f613d0 100644 --- a/src/web-ui/src/app/scenes/miniapps/views/MiniAppGalleryView.tsx +++ b/src/web-ui/src/app/scenes/miniapps/views/MiniAppGalleryView.tsx @@ -44,6 +44,7 @@ import { useCurrentWorkspace } from '@/infrastructure/contexts/WorkspaceContext' import { useMiniAppStore } from '../miniAppStore'; import { useMiniAppCreation } from '../hooks/useMiniAppCreation'; import { useI18n } from '@/infrastructure/i18n'; +import { isPeerDeviceModeActive } from '@/infrastructure/peer-device/peerModeFlag'; import { useGallerySceneAutoRefresh } from '@/app/hooks/useGallerySceneAutoRefresh'; import { useNotification } from '@/shared/notification-system'; import { getAppearanceOverlayHost } from '@/infrastructure/appearance/runtime/AppearanceOverlayHost'; @@ -274,6 +275,12 @@ const MiniAppGalleryView: React.FC = ({ tabs }) => { const preparePackageImport = useCallback(async (path: string) => { if (!path.toLowerCase().endsWith('.bfminiapp')) return; + // The package path belongs to this controller; a rendered peer would + // resolve it against its own filesystem. + if (isPeerDeviceModeActive()) { + notification.warning(t('market.import.peerUnsupported')); + return; + } try { const inspection = await miniAppMarketAPI.inspectPackage(path); setPendingPackage({ path, inspection }); @@ -284,6 +291,10 @@ const MiniAppGalleryView: React.FC = ({ tabs }) => { }, [notification, t]); const handleAddPackage = async () => { + if (isPeerDeviceModeActive()) { + notification.warning(t('market.import.peerUnsupported')); + return; + } const selected = await open({ directory: false, multiple: false, diff --git a/src/web-ui/src/app/scenes/miniapps/views/MiniAppLibraryView.tsx b/src/web-ui/src/app/scenes/miniapps/views/MiniAppLibraryView.tsx index 1ef2a0c746..02b432cfd0 100644 --- a/src/web-ui/src/app/scenes/miniapps/views/MiniAppLibraryView.tsx +++ b/src/web-ui/src/app/scenes/miniapps/views/MiniAppLibraryView.tsx @@ -53,6 +53,7 @@ import { systemAPI } from '@/infrastructure/api/service-api/SystemAPI'; import { getAppearanceOverlayHost } from '@/infrastructure/appearance/runtime/AppearanceOverlayHost'; import { useCurrentWorkspace } from '@/infrastructure/contexts/WorkspaceContext'; import { useI18n } from '@/infrastructure/i18n'; +import { isPeerDeviceModeActive } from '@/infrastructure/peer-device/peerModeFlag'; import { useAccountIdentity } from '@/infrastructure/account-identity'; import { useNotification } from '@/shared/notification-system'; import { isRemoteWorkspace } from '@/shared/types'; @@ -429,6 +430,12 @@ const MiniAppLibraryContent: React.FC = ({ const preparePackageImport = useCallback(async (path: string) => { if (!path.toLowerCase().endsWith('.bfminiapp')) return; + // The package path belongs to this controller; a rendered peer would + // resolve it against its own filesystem. + if (isPeerDeviceModeActive()) { + notification.warning(t('market.import.peerUnsupported')); + return; + } try { const inspection = await miniAppMarketAPI.inspectPackage(path); setPendingPackage({ path, inspection }); @@ -439,6 +446,10 @@ const MiniAppLibraryContent: React.FC = ({ }, [notification, t]); const handleAddPackage = async () => { + if (isPeerDeviceModeActive()) { + notification.warning(t('market.import.peerUnsupported')); + return; + } const selected = await open({ directory: false, multiple: false, diff --git a/src/web-ui/src/flow_chat/components/ChatInput.tsx b/src/web-ui/src/flow_chat/components/ChatInput.tsx index 20b36758ae..7debe67d2e 100644 --- a/src/web-ui/src/flow_chat/components/ChatInput.tsx +++ b/src/web-ui/src/flow_chat/components/ChatInput.tsx @@ -272,12 +272,23 @@ import { useWindowsFileDropPreview } from '@/infrastructure/files/useWindowsFile import type { FileDropPreview, FileDropPosition } from '@/shared/types/fileDropPreview'; import { resolveBrowserDroppedFilePaths } from '@/infrastructure/files/resolveBrowserDroppedFilePaths'; import { + buildControllerFileContexts, buildExternalFileContexts, partitionExternalDropFiles, resolveExternalFileIntakeAvailability, shouldAttemptNativeClipboardImageRead, + type ExternalFileIntakeFailure, type ExternalFileSource, } from '../utils/externalFileIntake'; +import { + MAX_CONTROLLER_ATTACHMENT_BYTES, + canUploadControllerFiles, + getControllerClipboardFiles, + getControllerClipboardImage, + getControllerFileMetadata, + readControllerImageContext, + uploadControllerFileToRuntime, +} from '../utils/controllerFileTransfer'; import { selectInterruptedTurnRecovery } from '../utils/interruptedTurnRecovery'; import { chatInputPermissionMode, @@ -550,6 +561,8 @@ interface ExternalFileIntakeRequest { sessionId: string | null; surfaceEpoch: number; targetKey: string; + /** Workspace record the session executes in; scopes staged controller files. */ + executionWorkspaceId: string; } export const ChatInput: React.FC = ({ @@ -4990,6 +5003,7 @@ export const ChatInput: React.FC = ({ externalFileAvailability.supported ? 'supported' : externalFileAvailability.reason, effectiveTargetSession?.config.dispatchJobId ?? '', effectiveTargetSession?.config.dispatchTarget ?? null, + executionWorkspaceId ?? '', ]); externalFileIntakeTargetKeyRef.current = externalFileIntakeTargetKey; @@ -4998,9 +5012,11 @@ export const ChatInput: React.FC = ({ sessionId: effectiveTargetSessionId, surfaceEpoch: deviceSurfaceScope.epoch, targetKey: externalFileIntakeTargetKey, + executionWorkspaceId: executionWorkspaceId ?? '', }), [ deviceSurfaceScope.epoch, effectiveTargetSessionId, + executionWorkspaceId, externalFileAvailability, externalFileIntakeTargetKey, ]); @@ -5080,7 +5096,9 @@ export const ChatInput: React.FC = ({ */ const readPastedClipboardImage = useCallback(async (request: ExternalFileIntakeRequest) => { try { - const image = await workspaceAPI.getClipboardImage(); + // The clipboard belongs to this controller even when another device + // executes the session. + const image = await getControllerClipboardImage(); if (!image || !isExternalFileIntakeRequestCurrent(request)) return; const binary = atob(image.base64); const bytes = new Uint8Array(binary.length); @@ -5092,7 +5110,7 @@ export const ChatInput: React.FC = ({ await addClipboardImageFiles(request, [file]); } catch (error) { log.warn('Native clipboard image read failed', { error }); - if (String(error).startsWith('clipboard_image_unsupported:')) { + if (String(error).includes('clipboard_image_unsupported:')) { notificationService.warning(t('input.clipboardImageToolsUnavailable'), { duration: 4000, }); @@ -5100,12 +5118,122 @@ export const ChatInput: React.FC = ({ } }, [addClipboardImageFiles, isExternalFileIntakeRequestCurrent, t]); + const notifyExternalFileFailures = useCallback(( + failures: ExternalFileIntakeFailure[], + addedCount: number, + fileUnsupportedMessage?: string, + ) => { + if (failures.length === 0) return; + const only = (reason: ExternalFileIntakeFailure['reason']) => + failures.every(failure => failure.reason === reason); + const first = failures[0]; + const firstName = first.path.split(/[\\/]/).pop() || first.path; + let message: string; + if (only('image-limit')) { + message = t('input.maxImagesWarning', { count: maxImageCount }); + } else if (only('directory')) { + message = t('input.externalFiles.controllerDirectoryUnsupported'); + } else if (only('file-unsupported') && fileUnsupportedMessage) { + message = fileUnsupportedMessage; + } else if (failures.length === 1 && first.reason === 'too-large') { + message = t('input.externalFiles.controllerFileTooLarge', { + name: firstName, + limit: Math.round(MAX_CONTROLLER_ATTACHMENT_BYTES / (1024 * 1024)), + }); + } else if (failures.length === 1 && (first.reason === 'upload' || first.reason === 'read')) { + message = t('input.externalFiles.controllerUploadFailed', { + name: firstName, + error: first.detail || t('error.unknown'), + }); + } else { + message = t('input.externalFiles.partialFailure', { + failed: failures.length, + added: addedCount, + }); + } + notificationService.warning(message, { duration: 5000 }); + }, [maxImageCount, t]); + + /** + * Attach controller files to a session that executes elsewhere. Images are + * sent as pixels; other files are staged on the execution host when it can + * receive them. A controller path is never sent as a reference. + */ + const addControllerFiles = useCallback(async ( + request: ExternalFileIntakeRequest, + source: ExternalFileSource, + paths: string[], + ) => { + const scope = getActiveSurfaceScope(); + if (scope.epoch !== request.surfaceEpoch) return; + const reason = request.availability.supported ? undefined : request.availability.reason; + const workspaceId = request.executionWorkspaceId; + // Why non-image files cannot be staged, checked in the order a user can act on. + const fileUnsupportedMessage = reason === 'detached-dispatch' + ? t('input.externalFiles.unsupported.detached-dispatch') + : !workspaceId + ? t('input.externalFiles.controllerFilesNeedWorkspace') + : !canUploadControllerFiles(scope) + ? t('input.externalFiles.unsupported.peer-device') + : undefined; + const uploadable = fileUnsupportedMessage === undefined; + const isCurrent = () => isExternalFileIntakeRequestCurrent(request); + let announcedUpload = false; + + const result = await buildControllerFileContexts({ + source, + paths, + existingContexts: contextStore.getState().contexts, + maxImageCount, + maxFileBytes: MAX_CONTROLLER_ATTACHMENT_BYTES, + loadMetadata: getControllerFileMetadata, + readImage: (path, name) => readControllerImageContext(path, name), + uploadFile: uploadable + ? (path, name) => { + if (!announcedUpload) { + announcedUpload = true; + notificationService.info( + t('input.externalFiles.controllerUploading', { count: paths.length }), + { duration: 2500 }, + ); + } + return uploadControllerFileToRuntime({ + path, + name, + workspaceId, + scope, + isCurrent, + }); + } + : undefined, + isCurrent, + }); + if (!isCurrent()) return; + + for (const context of result.contexts) { + addContext(context); + if (context.type === 'image') { + undoImageStackRef.current.push(context.id); + } else { + richTextInputRef.current?.insertTag?.(context); + } + } + notifyExternalFileFailures(result.failures, result.contexts.length, fileUnsupportedMessage); + }, [ + addContext, + contextStore, + isExternalFileIntakeRequestCurrent, + maxImageCount, + notifyExternalFileFailures, + t, + ]); + const addExternalPaths = useCallback(async ( request: ExternalFileIntakeRequest, source: ExternalFileSource, paths: string[], ) => { - if (!request.availability.supported) { + if (!request.availability.supported && request.availability.reason === 'web') { notificationService.warning( t(`input.externalFiles.unsupported.${request.availability.reason}`), { duration: 4000 }, @@ -5121,6 +5249,10 @@ export const ChatInput: React.FC = ({ ); return; } + if (!request.availability.supported) { + await addControllerFiles(request, source, paths); + return; + } const result = await buildExternalFileContexts({ source, @@ -5139,22 +5271,13 @@ export const ChatInput: React.FC = ({ } } - if (result.failures.length > 0) { - const imageLimitCount = result.failures.filter(failure => failure.reason === 'image-limit').length; - notificationService.warning( - imageLimitCount === result.failures.length - ? t('input.maxImagesWarning', { count: maxImageCount }) - : t('input.externalFiles.partialFailure', { - failed: result.failures.length, - added: result.contexts.length, - }), - { duration: 4000 }, - ); - } + notifyExternalFileFailures(result.failures, result.contexts.length); }, [ addContext, + addControllerFiles, contextStore, isExternalFileIntakeRequestCurrent, + notifyExternalFileFailures, sessionBoundWorkspacePath, maxImageCount, t, @@ -5168,7 +5291,7 @@ export const ChatInput: React.FC = ({ */ const readPastedClipboardFiles = useCallback(async (request: ExternalFileIntakeRequest) => { try { - const { files } = await workspaceAPI.getClipboardFiles(); + const { files } = await getControllerClipboardFiles(); if (!isExternalFileIntakeRequestCurrent(request)) return false; if (files.length === 0) return false; await addExternalPaths(request, 'clipboard', files); @@ -5194,6 +5317,19 @@ export const ChatInput: React.FC = ({ const request = captureExternalFileIntakeRequest(); return enqueueExternalFileIntake(request, async () => { if (!request.availability.supported) { + if (request.availability.reason !== 'web') { + // The clipboard of this controller, not of the rendered device. + try { + const { files } = await getControllerClipboardFiles(); + if (!isExternalFileIntakeRequestCurrent(request)) return; + if (files.length > 0) { + await addControllerFiles(request, 'clipboard', files); + return; + } + } catch (error) { + log.warn('Failed to read controller clipboard file paths', error); + } + } await addClipboardImageFiles(request, paste.fallbackImages); if (paste.hasNonImageFiles || paste.fallbackImages.length === 0) { notificationService.warning( @@ -5205,7 +5341,7 @@ export const ChatInput: React.FC = ({ } try { - const { files } = await workspaceAPI.getClipboardFiles(); + const { files } = await getControllerClipboardFiles(); if (!isExternalFileIntakeRequestCurrent(request)) return; if (files.length > 0) { await addExternalPaths(request, 'clipboard', files); @@ -5225,6 +5361,7 @@ export const ChatInput: React.FC = ({ }); }, [ addClipboardImageFiles, + addControllerFiles, addExternalPaths, captureExternalFileIntakeRequest, enqueueExternalFileIntake, @@ -5235,6 +5372,34 @@ export const ChatInput: React.FC = ({ const handleHtmlExternalFilesDrop = useCallback((files: File[]) => { const request = captureExternalFileIntakeRequest(); return enqueueExternalFileIntake(request, async () => { + if (!request.availability.supported && request.availability.reason !== 'web') { + // Files with a controller path go through the controller intake, which + // de-duplicates against the native drop of the same paths. Pathless + // images already carry their pixels. + let dropPayload = partitionExternalDropFiles(files, true); + if (dropPayload.paths.length !== files.length && files.length > 0) { + try { + // Controller-local command: resolves paths on this device. + const resolvedPaths = await resolveBrowserDroppedFilePaths(files); + if (resolvedPaths.length === files.length && resolvedPaths.every(Boolean)) { + dropPayload = { paths: resolvedPaths, fallbackImages: [], hasUnavailableFiles: false }; + } + } catch (error) { + log.warn('Failed to resolve browser-dropped file paths', error); + } + } + await addClipboardImageFiles(request, dropPayload.fallbackImages); + if (dropPayload.paths.length > 0) { + await addControllerFiles(request, 'drop', dropPayload.paths); + } + if (dropPayload.hasUnavailableFiles && isExternalFileIntakeRequestCurrent(request)) { + notificationService.warning( + t('input.externalFiles.dropPathsUnavailable'), + { duration: 4000 }, + ); + } + return; + } const dropPayload = partitionExternalDropFiles( files, request.availability.supported, @@ -5282,6 +5447,7 @@ export const ChatInput: React.FC = ({ }); }, [ addClipboardImageFiles, + addControllerFiles, addExternalPaths, captureExternalFileIntakeRequest, enqueueExternalFileIntake, @@ -5310,7 +5476,7 @@ export const ChatInput: React.FC = ({ // An engine that delivered real File objects already ran the in-page file // branch; reading the host clipboard again would attach twice. if (types.includes('Files')) return; - if (!externalFileAvailability.supported) return; + if (!externalFileAvailability.supported && externalFileAvailability.reason === 'web') return; const emptyTyped = shouldAttemptNativeClipboardImageRead(types); if (!emptyTyped && !isLinuxDesktopRuntime()) return; const request = captureExternalFileIntakeRequest(); diff --git a/src/web-ui/src/flow_chat/components/ChatInputImageIntake.test.ts b/src/web-ui/src/flow_chat/components/ChatInputImageIntake.test.ts index 8c8382b61f..e63c6dc716 100644 --- a/src/web-ui/src/flow_chat/components/ChatInputImageIntake.test.ts +++ b/src/web-ui/src/flow_chat/components/ChatInputImageIntake.test.ts @@ -62,9 +62,12 @@ describe('composer image file intake', () => { expect(component).toMatch( /inputElement\.addEventListener\('paste', handlePasteFallback\);/, ); + // The clipboard belongs to the controller even when a peer renders the + // session, so the read must not go through the rendered transport. expect(component).toMatch( - /const image = await workspaceAPI\.getClipboardImage\(\);/, + /const image = await getControllerClipboardImage\(\);/, ); + expect(component).not.toContain('workspaceAPI.getClipboardImage('); }); it('reads clipboard files first and widens the type gate on Linux', () => { diff --git a/src/web-ui/src/flow_chat/utils/controllerFileTransfer.test.ts b/src/web-ui/src/flow_chat/utils/controllerFileTransfer.test.ts new file mode 100644 index 0000000000..40bc3f982f --- /dev/null +++ b/src/web-ui/src/flow_chat/utils/controllerFileTransfer.test.ts @@ -0,0 +1,150 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import type { SurfaceScope } from '@/infrastructure/peer-device/deviceSurface'; + +const mocks = vi.hoisted(() => ({ + hostInvoke: vi.fn(), + controllerRequest: vi.fn(), + advertised: false, +})); + +vi.mock('@/infrastructure/api/service-api/ApiClient', () => ({ api: { invoke: mocks.hostInvoke } })); +vi.mock('@/infrastructure/api/adapters', () => ({ + createTransportAdapter: () => ({ request: mocks.controllerRequest }), +})); +vi.mock('@/infrastructure/peer-device/deviceSurface', () => ({ + isLocalSurface: (id: string) => id === 'local', +})); +vi.mock('@/infrastructure/peer-device/PeerConnectionManager', () => ({ + peerConnectionManager: { + get: () => ({ getState: () => ({ capabilities: { runtimeAttachmentUploadV1: mocks.advertised } }) }), + }, +})); + +import { + buildRuntimeAttachmentUri, + canUploadControllerFiles, + getControllerFileMetadata, + uploadControllerFileToRuntime, +} from './controllerFileTransfer'; + +const scope = (surfaceId: string, current = () => true): SurfaceScope => ({ + surfaceId, + epoch: 1, + signal: new AbortController().signal, + isCurrent: current, + assertCurrent: () => { + if (!current()) throw new Error('surface changed'); + }, + key: (...parts) => JSON.stringify([surfaceId, ...parts]), +}); + +/** Host stub that follows the `workspace_file_upload` cursor contract. */ +function installUploadHost() { + let next = 0; + let total = 0; + const appended: Uint8Array[] = []; + mocks.hostInvoke.mockImplementation(async (_command: string, args: { request: Record }) => { + const request = args.request; + const status = () => ({ transferId: request.transferId, nextOffset: next, totalBytes: total, completed: next === total && request.action === 'finish' }); + switch (request.action) { + case 'begin': + total = request.totalBytes as number; + return status(); + case 'append': { + const bytes = Uint8Array.from(atob(request.contentBase64 as string), ch => ch.charCodeAt(0)); + appended.push(bytes); + next += bytes.length; + return status(); + } + case 'finish': + return status(); + default: + return status(); + } + }); + return appended; +} + +beforeEach(() => { + mocks.hostInvoke.mockReset(); + mocks.controllerRequest.mockReset(); + mocks.advertised = false; +}); + +describe('controller file transfer', () => { + it('reads controller metadata through the controller host with the local-provider marker', async () => { + mocks.controllerRequest.mockResolvedValue({ path: '/Users/me/a.txt', size: 5, isFile: true, isDir: false }); + const metadata = await getControllerFileMetadata('/Users/me/a.txt'); + expect(mocks.controllerRequest).toHaveBeenCalledWith('get_file_metadata', { + request: { path: '/Users/me/a.txt', remoteConnectionId: '' }, + }); + expect(mocks.hostInvoke).not.toHaveBeenCalled(); + expect(metadata).toMatchObject({ size: 5, isFile: true, isDir: false }); + }); + + it('gates uploads on the local build or the negotiated peer capability', () => { + expect(canUploadControllerFiles(scope('local'))).toBe(true); + expect(canUploadControllerFiles(scope('peer-1'))).toBe(false); + mocks.advertised = true; + expect(canUploadControllerFiles(scope('peer-1'))).toBe(true); + }); + + it('stages bytes read on the controller into the runtime attachments directory', async () => { + mocks.controllerRequest.mockResolvedValue(btoa('hello')); + const appended = installUploadHost(); + + const hostPath = await uploadControllerFileToRuntime({ + path: 'C:\\Users\\me\\notes:v1.md', + name: 'notes:v1.md', + workspaceId: 'ws-1', + scope: scope('peer-1'), + isCurrent: () => true, + }); + + expect(mocks.controllerRequest).toHaveBeenCalledWith('read_file_content', { + request: { filePath: 'C:\\Users\\me\\notes:v1.md', encoding: 'base64', remoteConnectionId: '' }, + }); + expect(hostPath).toMatch(/^openbitfun:\/\/runtime\/ws-1\/attachments\/[0-9a-f]{16}\/notes_v1\.md$/); + const actions = mocks.hostInvoke.mock.calls.map(([command, args]) => [command, args.request.action]); + expect(actions).toEqual([ + ['workspace_file_upload', 'begin'], + ['workspace_file_upload', 'append'], + ['workspace_file_upload', 'finish'], + ]); + const begin = mocks.hostInvoke.mock.calls[0][1].request; + expect(begin).toMatchObject({ + path: hostPath, + workspaceId: 'ws-1', + totalBytes: 5, + expectedHash: '', + sha256: '2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824', + }); + expect(begin.transferId).toMatch(/^[0-9a-f]{64}$/); + expect(new TextDecoder().decode(appended[0])).toBe('hello'); + }); + + it('stops before sending bytes once the rendered surface changed', async () => { + mocks.controllerRequest.mockResolvedValue(btoa('hello')); + installUploadHost(); + let current = true; + mocks.hostInvoke.mockImplementationOnce(async (_command: string, args: { request: Record }) => { + current = false; + return { transferId: args.request.transferId, nextOffset: 0, totalBytes: 5, completed: false }; + }); + + await expect(uploadControllerFileToRuntime({ + path: '/tmp/a.txt', + name: 'a.txt', + workspaceId: 'ws-1', + scope: scope('peer-1', () => current), + isCurrent: () => true, + })).rejects.toThrow('surface changed'); + const actions = mocks.hostInvoke.mock.calls.map(([, args]) => args.request.action); + expect(actions).not.toContain('append'); + }); + + it('builds the runtime URI the agent tools resolve', () => { + expect(buildRuntimeAttachmentUri('ws-9', 'abc', 'a b.txt')) + .toBe('openbitfun://runtime/ws-9/attachments/abc/a b.txt'); + }); +}); diff --git a/src/web-ui/src/flow_chat/utils/controllerFileTransfer.ts b/src/web-ui/src/flow_chat/utils/controllerFileTransfer.ts new file mode 100644 index 0000000000..23dcdb7ba1 --- /dev/null +++ b/src/web-ui/src/flow_chat/utils/controllerFileTransfer.ts @@ -0,0 +1,101 @@ +/** + * Composer attachments from the controller device. + * + * When the session executes on another host (Peer Device Mode), on a remote + * workspace, or as a detached job, a path dropped or pasted into the composer + * belongs to this controller. Images are read here and sent as pixels; other + * files are staged in the execution host's runtime `attachments/` directory, + * which its agent tools resolve, when that host supports it. + */ +import { + readControllerFileBytes, + randomHex, + uploadBytesToHost, +} from '@/infrastructure/files/controllerFiles'; +import { + isLocalSurface, + type SurfaceScope, +} from '@/infrastructure/peer-device/deviceSurface'; +import { peerConnectionManager } from '@/infrastructure/peer-device/PeerConnectionManager'; +import type { ImageContext } from '@/shared/types/context'; +import { controllerAttachmentFileName } from './externalFileIntake'; +import { createImageContextFromFile, getMimeTypeFromFilename } from './imageUtils'; + +export { + getControllerClipboardFiles, + getControllerClipboardImage, + getControllerFileMetadata, +} from '@/infrastructure/files/controllerFiles'; + +/** Bounded so an accidental large drop cannot stall the relay or the host. */ +export const MAX_CONTROLLER_ATTACHMENT_BYTES = 32 * 1024 * 1024; + +/** Read a controller image into an inline (pixel-carrying) image context. */ +export async function readControllerImageContext( + path: string, + name: string, +): Promise { + const bytes = await readControllerFileBytes(path); + const file = new File([bytes as BlobPart], name, { type: getMimeTypeFromFilename(name) }); + const context = await createImageContextFromFile(file); + if (!context.dataUrl) { + throw new Error('Image pixels could not be read'); + } + return { ...context, isLocal: false, imagePath: '' }; +} + +/** + * Whether the execution host of the given surface accepts controller files. + * The local surface is this build; a peer must have negotiated the capability. + */ +export function canUploadControllerFiles(scope: SurfaceScope): boolean { + if (isLocalSurface(scope.surfaceId)) return true; + return peerConnectionManager.get(scope.surfaceId)?.getState() + .capabilities.runtimeAttachmentUploadV1 === true; +} + +export interface UploadControllerFileOptions { + path: string; + name: string; + /** Workspace record the session executes in; scopes the runtime URI. */ + workspaceId: string; + scope: SurfaceScope; + isCurrent: () => boolean; +} + +/** + * Stage a controller file on the execution host and return the runtime URI + * its agent tools resolve. Every host call is checked against the surface + * scope captured by the caller so a device switch never redirects the bytes. + */ +export async function uploadControllerFileToRuntime( + options: UploadControllerFileOptions, +): Promise { + const bytes = await readControllerFileBytes(options.path); + if (bytes.byteLength > MAX_CONTROLLER_ATTACHMENT_BYTES) { + throw new Error('File is too large to send'); + } + const hostPath = buildRuntimeAttachmentUri( + options.workspaceId, + randomHex(8), + controllerAttachmentFileName(options.name), + ); + await uploadBytesToHost({ + bytes, + path: hostPath, + workspaceId: options.workspaceId, + assertCurrent: () => { + options.scope.assertCurrent('upload composer attachment'); + if (!options.isCurrent()) throw new Error('Composer target changed'); + }, + }); + return hostPath; +} + +export function buildRuntimeAttachmentUri( + workspaceId: string, + uploadId: string, + fileName: string, +): string { + return `openbitfun://runtime/${workspaceId}/attachments/${uploadId}/${fileName}`; +} diff --git a/src/web-ui/src/flow_chat/utils/externalFileIntake.test.ts b/src/web-ui/src/flow_chat/utils/externalFileIntake.test.ts index e3b9cf975a..898fcf9129 100644 --- a/src/web-ui/src/flow_chat/utils/externalFileIntake.test.ts +++ b/src/web-ui/src/flow_chat/utils/externalFileIntake.test.ts @@ -1,8 +1,11 @@ import { describe, expect, it, vi } from 'vitest'; import type { FileMetadata } from '@/infrastructure/api/service-api/WorkspaceAPI'; import type { ContextItem } from '@/shared/types/context'; +import type { ImageContext } from '@/shared/types/context'; import { + buildControllerFileContexts, buildExternalFileContexts, + controllerAttachmentFileName, normalizeExternalFilePath, partitionExternalDropFiles, resolveExternalFileIntakeAvailability, @@ -188,3 +191,110 @@ describe('buildExternalFileContexts', () => { expect(shouldAttemptNativeClipboardImageRead(['Files', 'text/plain'])).toBe(false); }); }); + +describe('buildControllerFileContexts', () => { + const inlineImage = (name: string): ImageContext => ({ + id: `img-${name}`, + type: 'image', + imagePath: '', + imageName: name, + fileSize: 3, + mimeType: 'image/png', + source: 'file', + isLocal: false, + dataUrl: 'data:image/png;base64,YQ==', + timestamp: 1, + metadata: {}, + }); + const buildController = ( + paths: string[], + overrides: Partial[0]> = {}, + ) => buildControllerFileContexts({ + source: 'drop', + paths, + existingContexts: [], + maxImageCount: 2, + maxFileBytes: 100, + loadMetadata: async (path: string) => metadata(path.endsWith('folder'), path.endsWith('big.bin') ? 101 : 12), + readImage: async (_path: string, name: string) => inlineImage(name), + uploadFile: async (_path: string, name: string) => `openbitfun://runtime/ws-1/attachments/u1/${name}`, + ...overrides, + }); + + it('sends images as pixels and never references a controller path', async () => { + const result = await buildController(['/Users/me/shot.png']); + expect(result.contexts).toHaveLength(1); + expect(result.contexts[0]).toMatchObject({ + type: 'image', + isLocal: false, + imagePath: '', + dataUrl: 'data:image/png;base64,YQ==', + metadata: { controllerSourcePath: '/Users/me/shot.png', externalFileSource: 'drop' }, + }); + }); + + it('stages other files on the execution host and references the host path', async () => { + const uploadFile = vi.fn(async (_path: string, name: string) => `openbitfun://runtime/ws-1/attachments/u1/${name}`); + const result = await buildController(['C:\\Users\\me\\notes.md'], { uploadFile }); + expect(uploadFile).toHaveBeenCalledWith('C:\\Users\\me\\notes.md', 'notes.md', expect.any(Object)); + expect(result.contexts[0]).toMatchObject({ + type: 'file', + fileName: 'notes.md', + filePath: 'openbitfun://runtime/ws-1/attachments/u1/notes.md', + relativePath: undefined, + metadata: { controllerSourcePath: 'C:\\Users\\me\\notes.md', controllerUpload: true }, + }); + }); + + it('reports explicit reasons for folders, oversize files, and hosts that cannot receive files', async () => { + const withUpload = await buildController(['/tmp/folder', '/tmp/big.bin', '/tmp/a.txt']); + expect(withUpload.contexts.map(context => context.type)).toEqual(['file']); + expect(withUpload.failures.map(failure => failure.reason)).toEqual(['directory', 'too-large']); + + const withoutUpload = await buildController(['/tmp/a.txt', '/tmp/b.png'], { uploadFile: undefined }); + expect(withoutUpload.contexts.map(context => context.type)).toEqual(['image']); + expect(withoutUpload.failures).toEqual([{ path: '/tmp/a.txt', reason: 'file-unsupported' }]); + }); + + it('treats non-inline image formats as files', async () => { + const readImage = vi.fn(async (_path: string, name: string) => inlineImage(name)); + const result = await buildController(['/tmp/scan.bmp'], { readImage }); + expect(readImage).not.toHaveBeenCalled(); + expect(result.contexts[0]).toMatchObject({ type: 'file', fileName: 'scan.bmp' }); + }); + + it('de-duplicates by the controller source path and keeps upload errors', async () => { + const existingContexts = [{ + id: 'f', type: 'file', filePath: 'openbitfun://runtime/ws-1/attachments/u0/a.txt', fileName: 'a.txt', + timestamp: 0, metadata: { controllerSourcePath: '/tmp/a.txt' }, + }] satisfies ContextItem[]; + const result = await buildController(['/tmp/a.txt', '/tmp/b.txt'], { + existingContexts, + uploadFile: async () => { throw new Error('host offline'); }, + }); + expect(result.duplicateCount).toBe(1); + expect(result.failures).toEqual([{ path: '/tmp/b.txt', reason: 'upload', detail: 'host offline' }]); + }); + + it('enforces the image limit and stops once the target changes', async () => { + const limited = await buildController(['/tmp/a.png', '/tmp/b.png', '/tmp/c.png']); + expect(limited.contexts).toHaveLength(2); + expect(limited.failures).toEqual([{ path: '/tmp/c.png', reason: 'image-limit' }]); + + let current = true; + const uploadFile = vi.fn(async (_path: string, name: string) => { + current = false; + return `openbitfun://runtime/ws-1/attachments/u1/${name}`; + }); + const stopped = await buildController(['/tmp/a.txt', '/tmp/b.txt'], { uploadFile, isCurrent: () => current }); + expect(uploadFile).toHaveBeenCalledTimes(1); + expect(stopped.contexts).toHaveLength(1); + }); + + it('builds runtime-safe attachment names', () => { + expect(controllerAttachmentFileName('report v2.pdf')).toBe('report v2.pdf'); + expect(controllerAttachmentFileName('a/b\\c:d*?.txt')).toBe('a_b_c_d__.txt'); + expect(controllerAttachmentFileName('..secret')).toBe('_secret'); + expect(controllerAttachmentFileName(' ')).toBe('attachment'); + }); +}); diff --git a/src/web-ui/src/flow_chat/utils/externalFileIntake.ts b/src/web-ui/src/flow_chat/utils/externalFileIntake.ts index 74c1818868..6c6dfbeb70 100644 --- a/src/web-ui/src/flow_chat/utils/externalFileIntake.ts +++ b/src/web-ui/src/flow_chat/utils/externalFileIntake.ts @@ -24,7 +24,18 @@ export type ExternalFileIntakeAvailability = export interface ExternalFileIntakeFailure { path: string; - reason: 'metadata' | 'invalid-path' | 'image-limit'; + reason: + | 'metadata' + | 'invalid-path' + | 'image-limit' + /** A controller folder cannot be staged on another execution host. */ + | 'directory' + /** The execution host cannot receive controller files. */ + | 'file-unsupported' + | 'too-large' + | 'read' + | 'upload'; + detail?: string; } export interface BuildExternalFileContextsOptions { @@ -77,6 +88,17 @@ export function shouldAttemptNativeClipboardImageRead( return types.length === 0; } +/** + * The controller path a context was attached from. Controller files staged on + * another host carry a runtime path of that host, so duplicate detection keys + * by the path the user dropped instead. + */ +export function getContextExternalSourcePath(context: ContextItem): string | undefined { + const sourcePath = context.metadata?.controllerSourcePath; + if (typeof sourcePath === 'string' && sourcePath) return sourcePath; + return getContextLocalPath(context); +} + export function getContextLocalPath(context: ContextItem): string | undefined { if (context.type === 'file') return context.filePath; if (context.type === 'directory') return context.directoryPath; @@ -207,12 +229,7 @@ function withExternalMetadata( export async function buildExternalFileContexts( options: BuildExternalFileContextsOptions, ): Promise { - const seen = new Set( - options.existingContexts - .map(getContextLocalPath) - .filter((path): path is string => Boolean(path)) - .map(normalizeExternalFilePath), - ); + const seen = externalSourcePathKeys(options.existingContexts); let imageCount = options.existingContexts.filter((context) => context.type === 'image').length; const contexts: ExternalFileIntakeResult['contexts'] = []; const failures: ExternalFileIntakeFailure[] = []; @@ -277,3 +294,153 @@ export async function buildExternalFileContexts( return { contexts, failures, duplicateCount }; } + +function externalSourcePathKeys(contexts: ContextItem[]): Set { + return new Set( + contexts + .map(getContextExternalSourcePath) + .filter((path): path is string => Boolean(path)) + .map(normalizeExternalFilePath), + ); +} + +/** Image extensions the composer can send as inline pixels. */ +const INLINE_IMAGE_EXTENSIONS = new Set(['png', 'jpg', 'jpeg', 'gif', 'webp']); + +function isInlineImageName(name: string): boolean { + const extension = name.toLowerCase().split('.').pop() ?? ''; + return extension !== name.toLowerCase() && INLINE_IMAGE_EXTENSIONS.has(extension); +} + +export interface BuildControllerFileContextsOptions { + source: ExternalFileSource; + paths: string[]; + existingContexts: ContextItem[]; + maxImageCount: number; + /** Largest non-image file sent to the execution host. */ + maxFileBytes: number; + /** Metadata read on the controller, never on the execution host. */ + loadMetadata: (path: string) => Promise; + /** Read controller image pixels into an inline image context. */ + readImage: (path: string, name: string, metadata: FileMetadata) => Promise; + /** + * Stage a controller file on the execution host and return the path its + * agent tools resolve. Absent when that host cannot receive files. + */ + uploadFile?: (path: string, name: string, metadata: FileMetadata) => Promise; + /** Stop before further host work once the composer target changed. */ + isCurrent?: () => boolean; +} + +/** + * Attach controller files to a session whose execution host cannot read the + * controller filesystem (Peer Device, remote workspace, detached dispatch). + * + * Images travel as inline pixels, which every execution host already accepts. + * Other files are staged on the execution host when it supports that. A path + * of this controller is never sent as a reference: the host would resolve it + * against its own filesystem. + */ +export async function buildControllerFileContexts( + options: BuildControllerFileContextsOptions, +): Promise { + const seen = externalSourcePathKeys(options.existingContexts); + let imageCount = options.existingContexts.filter((context) => context.type === 'image').length; + const contexts: ExternalFileIntakeResult['contexts'] = []; + const failures: ExternalFileIntakeFailure[] = []; + let duplicateCount = 0; + const isCurrent = options.isCurrent ?? (() => true); + const errorText = (error: unknown) => (error instanceof Error ? error.message : String(error)); + + for (const path of options.paths) { + if (!isCurrent()) break; + const normalizedPath = normalizeExternalFilePath(path); + if (!normalizedPath || seen.has(normalizedPath)) { + duplicateCount += 1; + continue; + } + seen.add(normalizedPath); + + let metadata: FileMetadata; + try { + metadata = await options.loadMetadata(path); + } catch { + failures.push({ path, reason: 'metadata' }); + continue; + } + if (metadata.isDir) { + failures.push({ path, reason: 'directory' }); + continue; + } + if (!metadata.isFile) { + failures.push({ path, reason: 'invalid-path' }); + continue; + } + + const name = getPathName(path); + if (isInlineImageName(name)) { + if (imageCount >= options.maxImageCount) { + failures.push({ path, reason: 'image-limit' }); + continue; + } + try { + const image = await options.readImage(path, name, metadata); + imageCount += 1; + contexts.push({ + ...image, + metadata: { + ...image.metadata, + controllerSourcePath: path, + externalFileSource: options.source, + }, + }); + } catch (error) { + failures.push({ path, reason: 'read', detail: errorText(error) }); + } + continue; + } + + if (!options.uploadFile) { + failures.push({ path, reason: 'file-unsupported' }); + continue; + } + if (metadata.size > options.maxFileBytes) { + failures.push({ path, reason: 'too-large' }); + continue; + } + let hostPath: string; + try { + hostPath = await options.uploadFile(path, name, metadata); + } catch (error) { + failures.push({ path, reason: 'upload', detail: errorText(error) }); + continue; + } + const context = createPathContext(hostPath, name, false) as FileContext; + contexts.push({ + ...context, + fileSize: metadata.size, + mimeType: getFileMimeType(name), + metadata: { + ...context.metadata, + controllerSourcePath: path, + controllerUpload: true, + externalFileSource: options.source, + }, + }); + } + + return { contexts, failures, duplicateCount }; +} + +/** + * File name safe to use as one runtime path segment on any host OS. The + * original name stays visible on the context pill. + */ +export function controllerAttachmentFileName(name: string): string { + const cleaned = Array.from(name.trim()) + .map((ch) => (ch.charCodeAt(0) < 0x20 || '/\\:*?"<>|'.includes(ch) ? '_' : ch)) + .join('') + .replace(/^\.+/, '_') + .slice(0, 180); + return cleaned || 'attachment'; +} diff --git a/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts b/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts index b2f85c462d..a22bafa49a 100644 --- a/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts +++ b/src/web-ui/src/infrastructure/api/generated/remoteSurface.ts @@ -1,6 +1,6 @@ // Generated by scripts/generate-interactive-capabilities.mjs; do not edit. // Source: openbitfun_product_domains::remote_surface (Product Operation Registry). -export const REMOTE_SURFACE_REGISTRY_DIGEST = "fnv1a64:f622fe54e98d2ae1" as const; +export const REMOTE_SURFACE_REGISTRY_DIGEST = "fnv1a64:416c934dda520065" as const; /** * Registered Tauri commands the Peer Device controller keeps on the controller @@ -177,6 +177,7 @@ export const PEER_HOST_CAPABILITY_IDS = [ "dialog_queue_v1", "idempotent_dialog_submit", "inline_image_attachments_v1", + "runtime_attachment_upload_v1", "btw_initial_model_selection_v1", "btw_model_pool_selection_v1", "control_conversation_v1", @@ -232,6 +233,7 @@ export const PEER_HOST_ADVERTISED_CAPABILITIES: Readonly< "dialog_queue_v1", "idempotent_dialog_submit", "inline_image_attachments_v1", + "runtime_attachment_upload_v1", "btw_initial_model_selection_v1", "btw_model_pool_selection_v1", "control_conversation_v1", @@ -280,6 +282,7 @@ export const PEER_HOST_ADVERTISED_CAPABILITIES: Readonly< "control_conversation_reset_v1", "idempotent_dialog_submit", "inline_image_attachments_v1", + "runtime_attachment_upload_v1", "btw_initial_model_selection_v1", "btw_model_pool_selection_v1", "targeted_session_rollback", diff --git a/src/web-ui/src/infrastructure/files/controllerFiles.ts b/src/web-ui/src/infrastructure/files/controllerFiles.ts new file mode 100644 index 0000000000..aa41c20f96 --- /dev/null +++ b/src/web-ui/src/infrastructure/files/controllerFiles.ts @@ -0,0 +1,191 @@ +/** + * Files that belong to the controller device. + * + * In Peer Device Mode the registered transport follows the rendered device, so + * every `api.invoke` reaches the peer. A path dropped from Finder/Explorer, or + * copied to the OS clipboard, belongs to this controller instead. These helpers + * read such files through the controller's own Tauri host and move their bytes + * to an execution host with the runtime-owned `workspace_file_upload` service, + * so a controller path is never handed to another host as a reference. + */ +import { createTransportAdapter, type ITransportAdapter } from '@/infrastructure/api/adapters'; +import { api } from '@/infrastructure/api/service-api/ApiClient'; +import type { FileMetadata } from '@/infrastructure/api/service-api/WorkspaceAPI'; +import type { ExplorerNodeDto } from '@/infrastructure/api/service-api/tauri-commands'; + +/** Bounded by the host's `MAX_UPLOAD_CHUNK` (3 MiB) with relay headroom. */ +const UPLOAD_CHUNK_BYTES = 1024 * 1024; + +let controllerAdapter: ITransportAdapter | null = null; + +/** + * The controller's own Tauri host. An explicit empty connection id is the + * local-provider marker, so a path that collides with a registered remote + * workspace root still resolves on this machine's filesystem. + */ +function controllerHost(): ITransportAdapter { + controllerAdapter ??= createTransportAdapter('tauri'); + return controllerAdapter; +} + +export async function getControllerFileMetadata(path: string): Promise { + const raw = await controllerHost().request>('get_file_metadata', { + request: { path, remoteConnectionId: '' }, + }); + return { + path: String(raw.path ?? path), + modified: Number(raw.modified ?? 0), + size: Number(raw.size ?? 0), + isFile: raw.isFile === true, + isDir: raw.isDir === true, + isSymlink: typeof raw.isSymlink === 'boolean' ? raw.isSymlink : undefined, + }; +} + +export async function readControllerFileBytes(path: string): Promise { + const base64 = await controllerHost().request('read_file_content', { + request: { filePath: path, encoding: 'base64', remoteConnectionId: '' }, + }); + return decodeBase64(base64); +} + +/** Immediate children of a controller directory. */ +export async function listControllerDirectory(path: string): Promise { + const children = await controllerHost().request('get_directory_children', { + request: { path, remoteConnectionId: '' }, + }); + return Array.isArray(children) ? children : []; +} + +/** File paths on this controller's OS clipboard, not on the rendered device. */ +export async function getControllerClipboardFiles(): Promise<{ files: string[]; isCut: boolean }> { + const result = await controllerHost().request<{ files?: string[]; isCut?: boolean }>( + 'get_clipboard_files', + ); + return { + files: Array.isArray(result?.files) ? result.files : [], + isCut: result?.isCut === true, + }; +} + +/** Image on this controller's OS clipboard, or null when it holds none. */ +export async function getControllerClipboardImage(): Promise<{ base64: string; mimeType: string } | null> { + const response = await controllerHost().request<{ base64?: string; mimeType?: string } | null>( + 'get_clipboard_image', + ); + return response?.base64 && response.mimeType + ? { base64: response.base64, mimeType: response.mimeType } + : null; +} + +export interface UploadBytesToHostOptions { + bytes: Uint8Array; + /** Destination as the execution host resolves it for `workspaceId`. */ + path: string; + workspaceId: string; + /** Throw once the target changed; checked around every host call. */ + assertCurrent: () => void; + onProgress?: (sentBytes: number, totalBytes: number) => void; +} + +interface UploadStatus { + transferId: string; + nextOffset: number; + totalBytes: number; + completed: boolean; +} + +/** + * Publish bytes at a new destination on the rendered execution host. + * + * The host verifies the SHA-256 digest and, because the expected hash is + * empty, refuses to replace an existing file. An unknown append outcome is + * resolved from the host cursor before any byte is resent. + */ +export async function uploadBytesToHost(options: UploadBytesToHostOptions): Promise { + const { bytes } = options; + const transferId = randomHex(32); + const identity = { transferId, path: options.path, workspaceId: options.workspaceId }; + const call = async (args: Record): Promise => { + options.assertCurrent(); + const status = await api.invoke('workspace_file_upload', { + request: { ...identity, ...args }, + }); + options.assertCurrent(); + if ( + status?.transferId !== transferId + || status.totalBytes !== bytes.byteLength + || !Number.isSafeInteger(status.nextOffset) + || status.nextOffset < 0 + || status.nextOffset > bytes.byteLength + ) { + throw new Error('Invalid upload cursor from the execution host'); + } + return status; + }; + + let status = await call({ + action: 'begin', + totalBytes: bytes.byteLength, + sha256: await sha256Hex(bytes), + expectedHash: '', + }); + try { + options.onProgress?.(status.nextOffset, bytes.byteLength); + while (!status.completed && status.nextOffset < bytes.byteLength) { + const offset = status.nextOffset; + const chunk = bytes.subarray(offset, offset + UPLOAD_CHUNK_BYTES); + try { + status = await call({ action: 'append', offset, contentBase64: encodeBase64(chunk) }); + } catch (error) { + const resolved = await call({ action: 'status' }); + if (resolved.nextOffset === offset) throw error; + status = resolved; + } + if (status.nextOffset <= offset) { + throw new Error('Upload made no progress'); + } + options.onProgress?.(status.nextOffset, bytes.byteLength); + } + if (!status.completed) { + status = await call({ action: 'finish' }); + } + } catch (error) { + // Release the staged bytes; the cancel outcome does not change the error. + void api.invoke('workspace_file_upload', { + request: { ...identity, action: 'cancel' }, + }).catch(() => undefined); + throw error; + } + if (!status.completed || status.nextOffset !== bytes.byteLength) { + throw new Error('Upload is incomplete'); + } +} + +export function randomHex(byteCount: number): string { + const bytes = new Uint8Array(byteCount); + globalThis.crypto.getRandomValues(bytes); + return Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join(''); +} + +async function sha256Hex(bytes: Uint8Array): Promise { + const digest = await globalThis.crypto.subtle.digest('SHA-256', bytes as BufferSource); + return Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, '0')).join(''); +} + +function decodeBase64(value: string): Uint8Array { + const binary = atob(value); + const bytes = new Uint8Array(binary.length); + for (let index = 0; index < binary.length; index += 1) { + bytes[index] = binary.charCodeAt(index); + } + return bytes; +} + +function encodeBase64(bytes: Uint8Array): string { + let binary = ''; + for (let index = 0; index < bytes.length; index += 8192) { + binary += String.fromCharCode(...bytes.subarray(index, index + 8192)); + } + return btoa(binary); +} diff --git a/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.ts b/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.ts index 523da7c42a..e5dbdeca3e 100644 --- a/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.ts +++ b/src/web-ui/src/infrastructure/peer-device/PeerConnectionManager.ts @@ -44,6 +44,12 @@ export interface PeerHostCapabilities { readonly idempotentDialogSubmit: boolean; /** Only true after explicit negotiation; older hosts need the upload API. */ readonly inlineImageAttachmentsV1?: boolean; + /** + * `workspace_file_upload` accepts runtime `attachments/` targets, so the + * controller can attach its own local files. Older hosts keep the explicit + * unsupported reply. + */ + readonly runtimeAttachmentUploadV1?: boolean; readonly btwInitialModelSelectionV1?: boolean; readonly btwModelPoolSelectionV1?: boolean; /** Terminal output arrives as replay pages announced on the host stream. */ @@ -195,6 +201,7 @@ const NO_CAPABILITIES: PeerHostCapabilities = { backgroundResultDeliveryV1: false, idempotentDialogSubmit: false, inlineImageAttachmentsV1: false, + runtimeAttachmentUploadV1: false, btwInitialModelSelectionV1: false, btwModelPoolSelectionV1: false, terminalCursorReplayV1: false, @@ -563,6 +570,7 @@ export class PeerConnectionManager { idempotentDialogSubmit: caps?.idempotent_dialog_submit === true, backgroundResultDeliveryV1: caps?.background_result_delivery_v1 === true, inlineImageAttachmentsV1: caps?.inline_image_attachments_v1 === true, + runtimeAttachmentUploadV1: caps?.runtime_attachment_upload_v1 === true, btwInitialModelSelectionV1: caps?.btw_initial_model_selection_v1 === true, btwModelPoolSelectionV1: caps?.btw_model_pool_selection_v1 === true, terminalCursorReplayV1: caps?.terminal_cursor_replay_v1 === true, @@ -832,6 +840,7 @@ function capabilitiesEqual( return a.idempotentDialogSubmit === b.idempotentDialogSubmit && a.backgroundResultDeliveryV1 === b.backgroundResultDeliveryV1 && a.inlineImageAttachmentsV1 === b.inlineImageAttachmentsV1 && + a.runtimeAttachmentUploadV1 === b.runtimeAttachmentUploadV1 && a.btwInitialModelSelectionV1 === b.btwInitialModelSelectionV1 && a.btwModelPoolSelectionV1 === b.btwModelPoolSelectionV1 && a.controlConversationV1 === b.controlConversationV1 && diff --git a/src/web-ui/src/infrastructure/peer-device/README.md b/src/web-ui/src/infrastructure/peer-device/README.md index f5aa2ea11e..5664e6a7a1 100644 --- a/src/web-ui/src/infrastructure/peer-device/README.md +++ b/src/web-ui/src/infrastructure/peer-device/README.md @@ -351,6 +351,29 @@ notification metadata. switching, disconnecting, deleting its data or stopping its work. Activating a hidden device does not override that choice. +22. **Composer attachments from the controller never travel as controller + paths.** A file dropped or pasted into a peer session is read on the + controller through its own Tauri host (`controllerFileTransfer.ts`, local + provider marker), never through the rendered transport, and so is the + clipboard. Supported images become inline image contexts. Other files are + staged with `workspace_file_upload` under + `openbitfun://runtime//attachments//`, which the host's + agent tools resolve, only when the peer negotiated + `runtime_attachment_upload_v1`. Older peers, folders and oversize files get + an explicit reply; there is no path-reference fallback. The same intake + covers remote workspaces (local build uploads) and detached dispatch + (images only). + + The Files panel follows the same rule for drops and OS-clipboard paste: + `uploadLocalPathsToWorkspaceDirectory` publishes controller bytes with + `workspace_file_upload` into the peer workspace (local-paste `name (1)` + naming, never replacing a file) instead of `paste_files` or SSH upload, + which would resolve the controller path on the peer. Folders are refused + because the controller explorer listing filters entries, and a cut + clipboard behaves as a copy. Controller-path imports without a byte + transport, such as `.bfminiapp` packages, are refused while a peer is + rendered. + ### Workspace HTML resources The controller keeps HTML preview HTTP listeners and native browser views local. diff --git a/src/web-ui/src/locales/en-US/flow-chat.json b/src/web-ui/src/locales/en-US/flow-chat.json index f51039abe2..bbd91ba08d 100644 --- a/src/web-ui/src/locales/en-US/flow-chat.json +++ b/src/web-ui/src/locales/en-US/flow-chat.json @@ -773,11 +773,16 @@ "clipboardPathsUnavailable": "The clipboard reported files, but their local paths could not be read.", "dropPathsUnavailable": "This file drop did not expose local paths. Copy the files and paste them into the composer instead.", "partialFailure": "Added {{added}} item(s); {{failed}} item(s) were unavailable or unsupported.", + "controllerDirectoryUnsupported": "Folders from this device cannot be attached to a session that runs on another host. Attach the files inside instead.", + "controllerFilesNeedWorkspace": "Open a workspace for this session to attach files from this device. Images can still be attached.", + "controllerFileTooLarge": "{{name}} is larger than {{limit}} MB and cannot be sent to the executing host.", + "controllerUploading": "Sending {{count}} file(s) to the executing host...", + "controllerUploadFailed": "Could not send {{name}} to the executing host: {{error}}", "unsupported": { "web": "This web session cannot reference local files. Use a Desktop local session.", - "remote-workspace": "This remote workspace cannot reference files from this device.", - "peer-device": "A peer-device session cannot reference files from the controller device.", - "detached-dispatch": "A detached task cannot depend on files from the submitting device." + "remote-workspace": "This remote workspace cannot reference files from this device. Images can still be attached.", + "peer-device": "Update the peer device to attach files from this device. Images can still be attached.", + "detached-dispatch": "A detached task cannot depend on files from the submitting device. Images can still be attached." } }, "removeImage": "Remove image", diff --git a/src/web-ui/src/locales/en-US/panels/files.json b/src/web-ui/src/locales/en-US/panels/files.json index c818d22254..4373226ffd 100644 --- a/src/web-ui/src/locales/en-US/panels/files.json +++ b/src/web-ui/src/locales/en-US/panels/files.json @@ -131,6 +131,10 @@ "cancelled": "Transfer cancelled", "failed": "File transfer failed: {{error}}", "dropHint": "Drop files here to upload", + "peerMissingWorkspace": "The peer workspace could not be identified. Reopen it and try again.", + "peerFolderUnsupported": "Folders from this device cannot be uploaded to a peer device yet. Upload the files inside instead.", + "peerNotAFile": "Only regular files can be uploaded to a peer device.", + "peerFileTooLarge": "Files larger than {{limit}} MB cannot be uploaded to a peer device.", "stop": "Stop" }, "archive": { diff --git a/src/web-ui/src/locales/en-US/scenes/miniapp.json b/src/web-ui/src/locales/en-US/scenes/miniapp.json index 6e1e585b21..94e7e2822d 100644 --- a/src/web-ui/src/locales/en-US/scenes/miniapp.json +++ b/src/web-ui/src/locales/en-US/scenes/miniapp.json @@ -301,6 +301,7 @@ "confirmMessage": "{{description}}\n\nPermissions: {{permissions}}\n\nSHA-256: {{sha256}}", "confirm": "Import", "imported": "Imported “{{name}}”.", + "peerUnsupported": "MiniApp packages on this device cannot be imported into a peer device yet. Switch to this device to import it.", "failed": "Import failed: {{error}}" }, "submissions": { diff --git a/src/web-ui/src/locales/zh-CN/flow-chat.json b/src/web-ui/src/locales/zh-CN/flow-chat.json index d0710dc317..5634798531 100644 --- a/src/web-ui/src/locales/zh-CN/flow-chat.json +++ b/src/web-ui/src/locales/zh-CN/flow-chat.json @@ -773,11 +773,16 @@ "clipboardPathsUnavailable": "剪贴板中包含文件,但无法读取其本机路径。", "dropPathsUnavailable": "此次拖放未提供本机路径,请复制这些文件后粘贴到输入框。", "partialFailure": "已添加 {{added}} 项;另有 {{failed}} 项已失效或不受支持。", + "controllerDirectoryUnsupported": "在其他主机上运行的会话无法引用此设备上的文件夹,请改为添加其中的文件。", + "controllerFilesNeedWorkspace": "请先为此会话打开工作区,才能引用此设备上的文件;图片仍可添加。", + "controllerFileTooLarge": "{{name}} 超过 {{limit}} MB,无法发送到执行主机。", + "controllerUploading": "正在将 {{count}} 个文件发送到执行主机...", + "controllerUploadFailed": "无法将 {{name}} 发送到执行主机:{{error}}", "unsupported": { "web": "Web 会话无法引用本机文件,请使用 Desktop 本地会话。", - "remote-workspace": "远程工作区无法引用此设备上的本机文件。", - "peer-device": "Peer Device 会话无法引用控制端设备上的文件。", - "detached-dispatch": "Detached 任务不能依赖提交设备上的本机文件。" + "remote-workspace": "远程工作区无法引用此设备上的本机文件,图片仍可添加。", + "peer-device": "请先更新被控设备,才能引用此设备上的文件;图片仍可添加。", + "detached-dispatch": "Detached 任务不能依赖提交设备上的本机文件,图片仍可添加。" } }, "removeImage": "移除图片", diff --git a/src/web-ui/src/locales/zh-CN/panels/files.json b/src/web-ui/src/locales/zh-CN/panels/files.json index c7623de970..32486c52ca 100644 --- a/src/web-ui/src/locales/zh-CN/panels/files.json +++ b/src/web-ui/src/locales/zh-CN/panels/files.json @@ -131,6 +131,10 @@ "cancelled": "传输已取消", "failed": "文件传输失败:{{error}}", "dropHint": "将文件拖放到此处以上传", + "peerMissingWorkspace": "无法识别被控设备上的工作区,请重新打开后重试。", + "peerFolderUnsupported": "暂不支持将此设备上的文件夹上传到被控设备,请改为上传其中的文件。", + "peerNotAFile": "只能将普通文件上传到被控设备。", + "peerFileTooLarge": "超过 {{limit}} MB 的文件无法上传到被控设备。", "stop": "停止" }, "archive": { diff --git a/src/web-ui/src/locales/zh-CN/scenes/miniapp.json b/src/web-ui/src/locales/zh-CN/scenes/miniapp.json index 90d5e1cb84..bf54dc1f0a 100644 --- a/src/web-ui/src/locales/zh-CN/scenes/miniapp.json +++ b/src/web-ui/src/locales/zh-CN/scenes/miniapp.json @@ -301,6 +301,7 @@ "confirmMessage": "{{description}}\n\n权限:{{permissions}}\n\nSHA-256:{{sha256}}", "confirm": "确认导入", "imported": "已导入“{{name}}”。", + "peerUnsupported": "暂不支持将此设备上的 MiniApp 包导入被控设备,请切换到本机后再导入。", "failed": "导入失败:{{error}}" }, "submissions": { diff --git a/src/web-ui/src/locales/zh-TW/flow-chat.json b/src/web-ui/src/locales/zh-TW/flow-chat.json index e7e2ca4d0e..fbe36338c7 100644 --- a/src/web-ui/src/locales/zh-TW/flow-chat.json +++ b/src/web-ui/src/locales/zh-TW/flow-chat.json @@ -773,11 +773,16 @@ "clipboardPathsUnavailable": "剪貼簿中包含檔案,但無法讀取其本機路徑。", "dropPathsUnavailable": "此次拖放未提供本機路徑,請複製這些檔案後貼到輸入框。", "partialFailure": "已新增 {{added}} 項;另有 {{failed}} 項已失效或不受支援。", + "controllerDirectoryUnsupported": "在其他主機上執行的工作階段無法引用此裝置上的資料夾,請改為新增其中的檔案。", + "controllerFilesNeedWorkspace": "請先為此工作階段開啟工作區,才能引用此裝置上的檔案;圖片仍可新增。", + "controllerFileTooLarge": "{{name}} 超過 {{limit}} MB,無法傳送到執行主機。", + "controllerUploading": "正在將 {{count}} 個檔案傳送到執行主機...", + "controllerUploadFailed": "無法將 {{name}} 傳送到執行主機:{{error}}", "unsupported": { "web": "Web 工作階段無法引用本機檔案,請使用 Desktop 本機工作階段。", - "remote-workspace": "遠端工作區無法引用此裝置上的本機檔案。", - "peer-device": "Peer Device 工作階段無法引用控制端裝置上的檔案。", - "detached-dispatch": "Detached 任務不能依賴提交裝置上的本機檔案。" + "remote-workspace": "遠端工作區無法引用此裝置上的本機檔案,圖片仍可新增。", + "peer-device": "請先更新被控裝置,才能引用此裝置上的檔案;圖片仍可新增。", + "detached-dispatch": "Detached 任務不能依賴提交裝置上的本機檔案,圖片仍可新增。" } }, "removeImage": "移除圖片", diff --git a/src/web-ui/src/locales/zh-TW/panels/files.json b/src/web-ui/src/locales/zh-TW/panels/files.json index e44ff493f4..71e0d02a44 100644 --- a/src/web-ui/src/locales/zh-TW/panels/files.json +++ b/src/web-ui/src/locales/zh-TW/panels/files.json @@ -131,6 +131,10 @@ "cancelled": "傳輸已取消", "failed": "檔案傳輸失敗:{{error}}", "dropHint": "將檔案拖放到此處以上傳", + "peerMissingWorkspace": "無法識別被控裝置上的工作區,請重新開啟後再試。", + "peerFolderUnsupported": "暫不支援將此裝置上的資料夾上傳到被控裝置,請改為上傳其中的檔案。", + "peerNotAFile": "只能將一般檔案上傳到被控裝置。", + "peerFileTooLarge": "超過 {{limit}} MB 的檔案無法上傳到被控裝置。", "stop": "停止" }, "archive": { diff --git a/src/web-ui/src/locales/zh-TW/scenes/miniapp.json b/src/web-ui/src/locales/zh-TW/scenes/miniapp.json index 8cde33105f..d718f8cf73 100644 --- a/src/web-ui/src/locales/zh-TW/scenes/miniapp.json +++ b/src/web-ui/src/locales/zh-TW/scenes/miniapp.json @@ -301,6 +301,7 @@ "confirmMessage": "{{description}}\n\n權限:{{permissions}}\n\nSHA-256:{{sha256}}", "confirm": "確認匯入", "imported": "已匯入「{{name}}」。", + "peerUnsupported": "暫不支援將此裝置上的 MiniApp 套件匯入被控裝置,請切換到本機後再匯入。", "failed": "匯入失敗:{{error}}" }, "submissions": { diff --git a/src/web-ui/src/tools/file-system/hooks/useWorkspaceFileDrop.ts b/src/web-ui/src/tools/file-system/hooks/useWorkspaceFileDrop.ts index f15989f6b3..2fbd9aa0db 100644 --- a/src/web-ui/src/tools/file-system/hooks/useWorkspaceFileDrop.ts +++ b/src/web-ui/src/tools/file-system/hooks/useWorkspaceFileDrop.ts @@ -6,6 +6,7 @@ import { resolveDropTargetDirectoryFromDragPosition, uploadLocalPathsToWorkspaceDirectory, type TransferProgressState, + type WorkspaceTransferResult, } from '@/tools/file-system/services/workspaceFileTransfer'; const log = createLogger('useWorkspaceFileDrop'); @@ -19,7 +20,8 @@ export interface UseWorkspaceFileDropOptions { enabled?: boolean; onProgress: (state: TransferProgressState | null, transferId: string) => void; onDragOver?: (overPanel: boolean) => void; - onComplete: (targetDirectory: string, transferId: string) => void; + /** `result` lists items that were not transferred so they can be reported. */ + onComplete: (targetDirectory: string, transferId: string, result: WorkspaceTransferResult) => void; onError: (error: unknown, transferId: string) => void; } @@ -156,7 +158,7 @@ export function useWorkspaceFileDrop({ // sending an id no transfer ever registered. const transferId = crypto.randomUUID(); try { - await uploadLocalPathsToWorkspaceDirectory( + const result = await uploadLocalPathsToWorkspaceDirectory( paths, targetDir, currentWorkspace, @@ -164,7 +166,7 @@ export function useWorkspaceFileDrop({ undefined, transferId ); - onComplete(targetDir, transferId); + onComplete(targetDir, transferId, result); } catch (error) { log.error('Failed to upload dropped files', error); onError(error, transferId); diff --git a/src/web-ui/src/tools/file-system/services/workspaceFileTransfer.peer.test.ts b/src/web-ui/src/tools/file-system/services/workspaceFileTransfer.peer.test.ts new file mode 100644 index 0000000000..3cb3fee87b --- /dev/null +++ b/src/web-ui/src/tools/file-system/services/workspaceFileTransfer.peer.test.ts @@ -0,0 +1,163 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { WorkspaceKind, WorkspaceType, type WorkspaceInfo } from "@/shared/types"; + +const mocks = vi.hoisted(() => { + class PeerDeviceTransportAdapter {} + return { + PeerDeviceTransportAdapter, + peerAdapter: new PeerDeviceTransportAdapter(), + surfaceCurrent: true, + getControllerFileMetadata: vi.fn(), + readControllerFileBytes: vi.fn(), + uploadBytesToHost: vi.fn(), + getControllerClipboardFiles: vi.fn(), + getWorkspaceFileMetadata: vi.fn(), + getClipboardFiles: vi.fn(), + pasteFiles: vi.fn(), + uploadFromLocalPath: vi.fn(), + }; +}); + +vi.mock("@/infrastructure/api/adapters/peer-device-adapter", () => ({ + PeerDeviceTransportAdapter: mocks.PeerDeviceTransportAdapter, +})); +vi.mock("@/infrastructure/api/adapters", () => ({ + getTransportAdapter: () => mocks.peerAdapter, + createTransportAdapter: () => ({ request: vi.fn() }), +})); +vi.mock("@/infrastructure/files/controllerFiles", () => ({ + getControllerFileMetadata: mocks.getControllerFileMetadata, + readControllerFileBytes: mocks.readControllerFileBytes, + uploadBytesToHost: mocks.uploadBytesToHost, + getControllerClipboardFiles: mocks.getControllerClipboardFiles, +})); +vi.mock("@/infrastructure/api", () => ({ + workspaceAPI: { + getWorkspaceFileMetadata: mocks.getWorkspaceFileMetadata, + getClipboardFiles: mocks.getClipboardFiles, + pasteFiles: mocks.pasteFiles, + }, +})); +vi.mock("@/features/ssh-remote/sshApi", () => ({ + sshApi: { uploadFromLocalPath: mocks.uploadFromLocalPath }, +})); +vi.mock("@/infrastructure/peer-device/deviceSurface", () => ({ + getActiveSurfaceScope: () => ({ + isCurrent: () => mocks.surfaceCurrent, + assertCurrent: () => { + if (!mocks.surfaceCurrent) throw new Error("surface changed"); + }, + }), +})); + +import { + MAX_PEER_UPLOAD_FILE_BYTES, + pasteClipboardFilesToWorkspaceDirectory, + uploadLocalPathsToWorkspaceDirectory, +} from "./workspaceFileTransfer"; + +const workspace = (kind: WorkspaceKind, rootPath: string): WorkspaceInfo => ({ + id: "peer-ws", + name: "peer", + rootPath, + workspaceType: WorkspaceType.SingleProject, + workspaceKind: kind, + ...(kind === WorkspaceKind.Remote ? { connectionId: "peer-ssh" } : {}), + languages: [], + openedAt: "2024-01-01T00:00:00.000Z", + lastAccessed: "2024-01-01T00:00:00.000Z", + tags: [], +}); + +const fileMetadata = (size = 3) => ({ path: "", modified: 0, size, isFile: true, isDir: false }); + +beforeEach(() => { + vi.clearAllMocks(); + mocks.surfaceCurrent = true; + (globalThis as { window?: unknown }).window = globalThis; + (globalThis as unknown as { __TAURI__: unknown }).__TAURI__ = {}; + mocks.getControllerFileMetadata.mockResolvedValue(fileMetadata()); + mocks.readControllerFileBytes.mockResolvedValue(new Uint8Array([1, 2, 3])); + mocks.uploadBytesToHost.mockResolvedValue(undefined); + mocks.getWorkspaceFileMetadata.mockRejectedValue(new Error("not found")); +}); + +describe("Peer Device workspace uploads from the controller", () => { + it("publishes controller bytes on the peer instead of sending controller paths", async () => { + // `a.txt` already exists on the peer, so local-paste naming applies. + mocks.getWorkspaceFileMetadata.mockImplementation(async (_id: string, path: string) => { + if (path === "/srv/repo/src/a.txt") return fileMetadata(); + throw new Error("not found"); + }); + + const result = await uploadLocalPathsToWorkspaceDirectory( + ["/Users/me/Desktop/a.txt"], + "/srv/repo/src", + workspace(WorkspaceKind.Remote, "/srv/repo"), + vi.fn(), + { isCut: true }, + "drop-1", + ); + + expect(result).toMatchObject({ successCount: 1, failedFiles: [] }); + expect(mocks.readControllerFileBytes).toHaveBeenCalledWith("/Users/me/Desktop/a.txt"); + expect(mocks.uploadBytesToHost).toHaveBeenCalledWith(expect.objectContaining({ + path: "/srv/repo/src/a (1).txt", + workspaceId: "peer-ws", + bytes: new Uint8Array([1, 2, 3]), + })); + expect(mocks.pasteFiles).not.toHaveBeenCalled(); + expect(mocks.uploadFromLocalPath).not.toHaveBeenCalled(); + }); + + it("refuses folders and oversize files explicitly while keeping other files", async () => { + mocks.getControllerFileMetadata.mockImplementation(async (path: string) => { + if (path.endsWith("folder")) return { ...fileMetadata(), isFile: false, isDir: true }; + if (path.endsWith("huge.bin")) return fileMetadata(MAX_PEER_UPLOAD_FILE_BYTES + 1); + return fileMetadata(); + }); + + const result = await uploadLocalPathsToWorkspaceDirectory( + ["/tmp/folder", "/tmp/huge.bin", "/tmp/ok.md"], + "C:\\work\\repo", + workspace(WorkspaceKind.Normal, "C:\\work\\repo"), + vi.fn(), + ); + + expect(result.successCount).toBe(1); + expect(result.failedFiles.map(entry => entry.path)).toEqual(["/tmp/folder", "/tmp/huge.bin"]); + expect(mocks.uploadBytesToHost).toHaveBeenCalledTimes(1); + expect(mocks.uploadBytesToHost.mock.calls[0][0].path).toBe("C:/work/repo/ok.md"); + expect(mocks.readControllerFileBytes).not.toHaveBeenCalledWith("/tmp/huge.bin"); + }); + + it("abandons the drop when the rendered device changes", async () => { + mocks.uploadBytesToHost.mockImplementation(async () => { + mocks.surfaceCurrent = false; + throw new Error("surface changed"); + }); + + await expect(uploadLocalPathsToWorkspaceDirectory( + ["/tmp/a.txt", "/tmp/b.txt"], + "/srv/repo", + workspace(WorkspaceKind.Remote, "/srv/repo"), + vi.fn(), + )).rejects.toThrow("surface changed"); + expect(mocks.uploadBytesToHost).toHaveBeenCalledTimes(1); + }); + + it("pastes from the controller clipboard, not the peer clipboard", async () => { + mocks.getControllerClipboardFiles.mockResolvedValue({ files: ["/Users/me/b.txt"], isCut: false }); + + const result = await pasteClipboardFilesToWorkspaceDirectory( + "/srv/repo", + workspace(WorkspaceKind.Remote, "/srv/repo"), + vi.fn(), + ); + + expect(result.successCount).toBe(1); + expect(mocks.getControllerClipboardFiles).toHaveBeenCalledTimes(1); + expect(mocks.getClipboardFiles).not.toHaveBeenCalled(); + expect(mocks.uploadBytesToHost.mock.calls[0][0].path).toBe("/srv/repo/b.txt"); + }); +}); diff --git a/src/web-ui/src/tools/file-system/services/workspaceFileTransfer.ts b/src/web-ui/src/tools/file-system/services/workspaceFileTransfer.ts index 04298a1645..42fa01390c 100644 --- a/src/web-ui/src/tools/file-system/services/workspaceFileTransfer.ts +++ b/src/web-ui/src/tools/file-system/services/workspaceFileTransfer.ts @@ -10,7 +10,14 @@ import { PeerDeviceTransportAdapter, type PeerDeviceCommandResponse, } from "@/infrastructure/api/adapters/peer-device-adapter"; +import { + getControllerClipboardFiles, + getControllerFileMetadata, + readControllerFileBytes, + uploadBytesToHost, +} from "@/infrastructure/files/controllerFiles"; import { i18nService } from "@/infrastructure/i18n"; +import { getActiveSurfaceScope } from "@/infrastructure/peer-device/deviceSurface"; import { isRemoteWorkspace, type WorkspaceInfo } from "@/shared/types"; import { dirnameAbsolutePath, @@ -730,6 +737,170 @@ export async function downloadWorkspaceFileToDisk( } } +/** Whole-file controller reads stay bounded; larger files need a local session. */ +export const MAX_PEER_UPLOAD_FILE_BYTES = 64 * 1024 * 1024; + +function peerUploadName(name: string, counter: number): string { + if (counter === 0) return name; + const dot = name.lastIndexOf("."); + return dot > 0 + ? `${name.slice(0, dot)} (${counter})${name.slice(dot)}` + : `${name} (${counter})`; +} + +/** + * First free `name`, `name (1)`, ... in a peer directory, matching local paste. + * A failed probe counts as free: the upload itself refuses to replace a file. + */ +async function freePeerDestination( + directory: string, + name: string, + workspaceId: string, + remote: boolean, + assertCurrent: () => void, +): Promise { + for (let counter = 0; counter < 1000; counter += 1) { + const candidate = joinWorkspaceTargetPath(directory, peerUploadName(name, counter), remote); + assertCurrent(); + let exists = false; + try { + const metadata = await workspaceAPI.getWorkspaceFileMetadata(workspaceId, candidate); + exists = metadata.isFile || metadata.isDir; + } catch { + exists = false; + } + assertCurrent(); + if (!exists) return candidate; + } + throw new Error(`No free destination name for '${name}'`); +} + +/** + * Upload controller files into a directory of the peer's workspace. + * + * Every path here belongs to this controller. Bytes are read through the + * controller's own host and published by the peer's runtime-owned + * `workspace_file_upload`; `paste_files` / SSH upload would resolve the + * controller path on the peer instead. Folders are refused explicitly: the + * controller's directory listing applies explorer filters and would copy a + * silently incomplete tree. The controller source is never removed, so a cut + * clipboard behaves as a copy. + */ +async function uploadControllerPathsToPeerWorkspace( + localPaths: string[], + targetDirectory: string, + workspace: WorkspaceInfo | null, + onProgress: (state: TransferProgressState | null) => void, + transferId?: string, +): Promise { + const workspaceId = workspace?.id; + if (!workspaceId) { + throw new Error(i18nService.t("panels/files:transfer.peerMissingWorkspace")); + } + const scope = getActiveSurfaceScope(); + const remote = isRemoteWorkspace(workspace); + const target = normalizeWorkspaceTargetDirectory(targetDirectory, workspace); + const assertCurrent = () => { + scope.assertCurrent("upload to peer workspace"); + throwIfCancelled(transferId); + }; + const failedFiles: WorkspaceTransferResult["failedFiles"] = []; + let successCount = 0; + let cancelled = false; + const total = localPaths.length; + + try { + for (let i = 0; i < total; i += 1) { + if (isWorkspaceTransferCancelled(transferId)) break; + const localPath = localPaths[i]!; + const name = localPath.replace(/[/\\]+$/, "").split(/[/\\]/).pop() ?? ""; + const singleItem = total === 1; + onProgress({ + phase: "upload", + current: i, + total, + label: singleItem ? name : `${name} (${i + 1}/${total})`, + indeterminate: true, + ...(transferId ? { transferId } : {}), + }); + try { + if (!isSafePeerTransferEntryName(name)) { + throw new Error(`Unsafe file name '${name}'`); + } + const metadata = await getControllerFileMetadata(localPath); + if (metadata.isDir) { + throw new Error(i18nService.t("panels/files:transfer.peerFolderUnsupported")); + } + if (!metadata.isFile) { + throw new Error(i18nService.t("panels/files:transfer.peerNotAFile")); + } + if (metadata.size > MAX_PEER_UPLOAD_FILE_BYTES) { + throw new Error(i18nService.t("panels/files:transfer.peerFileTooLarge", { + limit: Math.round(MAX_PEER_UPLOAD_FILE_BYTES / (1024 * 1024)), + })); + } + assertCurrent(); + const bytes = await readControllerFileBytes(localPath); + if (bytes.byteLength > MAX_PEER_UPLOAD_FILE_BYTES) { + throw new Error(i18nService.t("panels/files:transfer.peerFileTooLarge", { + limit: Math.round(MAX_PEER_UPLOAD_FILE_BYTES / (1024 * 1024)), + })); + } + const destination = await freePeerDestination(target, name, workspaceId, remote, assertCurrent); + await uploadBytesToHost({ + bytes, + path: destination, + workspaceId, + assertCurrent, + onProgress: singleItem + ? (sent, totalBytes) => onProgress({ + phase: "upload", + current: sent, + total: totalBytes, + label: name, + indeterminate: false, + bytesTransferred: sent, + bytesTotal: totalBytes, + ...(transferId ? { transferId } : {}), + }) + : undefined, + }); + successCount += 1; + } catch (error) { + // A device switch abandons the whole drop; nothing may land elsewhere. + if (!scope.isCurrent()) throw error; + if (isWorkspaceTransferCancelled(transferId)) break; + failedFiles.push({ + path: localPath, + error: error instanceof Error ? error.message : String(error), + }); + } + } + } finally { + cancelled = isWorkspaceTransferCancelled(transferId); + // The id only means something while this upload runs. + completeWorkspaceTransfer(transferId); + if (!cancelled && scope.isCurrent()) { + onProgress({ + phase: "upload", + current: total, + total, + label: "", + indeterminate: false, + ...(transferId ? { transferId } : {}), + }); + } + window.setTimeout(() => onProgress(null), 450); + } + + if (successCount === 0 && failedFiles.length > 0 && !cancelled) { + throw new Error( + failedFiles.map((entry) => `${entry.path}: ${entry.error}`).join("; "), + ); + } + return { successCount, directoryCount: 0, failedFiles, cancelled }; +} + export async function uploadLocalPathsToWorkspaceDirectory( localPaths: string[], targetDirectory: string, @@ -747,6 +918,17 @@ export async function uploadLocalPathsToWorkspaceDirectory( return { successCount: 0, directoryCount: 0, failedFiles: [] }; } + // Local paths belong to this controller; the rendered peer cannot read them. + if (currentPeerAdapter()) { + return uploadControllerPathsToPeerWorkspace( + normalizedLocalPaths, + targetDirectory, + workspace, + onProgress, + transferId, + ); + } + const remote = isRemoteWorkspace(workspace); const normalizedTargetDirectory = normalizeWorkspaceTargetDirectory( targetDirectory, @@ -951,7 +1133,8 @@ export async function pasteClipboardFilesToWorkspaceDirectory( onProgress: (state: TransferProgressState | null) => void, transferId?: string, ): Promise { - const { files, isCut } = await workspaceAPI.getClipboardFiles(); + // The OS clipboard belongs to this controller, also while a peer is rendered. + const { files, isCut } = await getControllerClipboardFiles(); return uploadLocalPathsToWorkspaceDirectory( files, targetDirectory,