import 'dart:convert'; import 'dart:typed_data'; import '../../../core/api_gateway.dart'; import 'chat_attachment_draft.dart'; /// The most files one prompt may carry. The web composer refuses more, and the /// server applies the same bound. const int maxChatAttachmentCount = 8; /// The inline route's budget: base64 bytes inside the 2 MiB websocket frame. /// Uploaded files ([chatAttachmentUploadParts]) are not bound by it. const int maxInlineAttachmentBytes = 1 << 20; /// The web's fallback name when an attachment's recorded name is blank. const String chatAttachmentFallbackName = 'attachment'; /// The web's fallback MIME when an attachment's recorded type is blank. const String chatAttachmentFallbackMime = 'application/octet-stream'; /// Why a prompt's attachment payload could not be built, in the web composer's /// own words so the operator reads the same sentence on every client. class ChatAttachmentWireException implements Exception { const ChatAttachmentWireException(this.message); /// The operator-facing reason. final String message; @override String toString() => message; } /// Supplies the drafted file's bytes when the prompt is built, or null when /// they are no longer readable. /// /// [ChatAttachmentDraft] records metadata only, so the caller keeps the picked /// bytes and hands them over here at send time. A removed or refused file is /// never asked for, because only the draft's own attachments are read. typedef ChatAttachmentBytes = Uint8List? Function(ChatAttachment attachment); /// The `attachments` array of one `chat_prompt`, in draft order. /// /// Each part is exactly the web's wire shape: `{name, mime, data}`, with the /// recorded name trimmed (else [chatAttachmentFallbackName]), the recorded MIME /// trimmed (else [chatAttachmentFallbackMime]), and the file's bytes as standard /// base64. There is one part per draft attachment and the order is preserved. /// /// An empty draft yields an empty list, so the caller adds no `attachments` key /// at all; the web omits it for a text-only prompt. The count and the actual /// byte lengths are checked before any part is encoded: more than /// [maxChatAttachmentCount] files, an unreadable file, or a total over /// [maxInlineAttachmentBytes] throws [ChatAttachmentWireException]. /// Actual bytes are used, not the recorded size, matching the web reader. List chatAttachmentParts( ChatAttachmentDraft draft, { required ChatAttachmentBytes read, }) { final attachments = draft.attachments; if (attachments.isEmpty) return const []; if (attachments.length > maxChatAttachmentCount) { throw const ChatAttachmentWireException( 'At most 8 attachments are allowed.', ); } // Read and bound every file before encoding the first one, so a refused // prompt builds no payload at all. final contents = []; var total = 0; for (final attachment in attachments) { final bytes = read(attachment); if (bytes == null) { throw ChatAttachmentWireException( '"${chatAttachmentDisplayName(attachment.name, '')}" could not be read.', ); } total += bytes.length; if (total > maxInlineAttachmentBytes) { throw const ChatAttachmentWireException( 'Attachments are too large to send without a server (1 MiB total).', ); } contents.add(bytes); } return [ for (var index = 0; index < attachments.length; index += 1) { 'name': _wireText(attachments[index].name, chatAttachmentFallbackName), 'mime': _wireText(attachments[index].mime, chatAttachmentFallbackMime), 'data': base64Encode(contents[index]), }, ]; } /// The attachment a recorded history `file` part names, or null when the part /// is not a recorded attachment. /// /// The name follows the web's display rule (its own name, else the URI /// basename, else `file`), and the MIME is the recorded type. History records /// only `name`, `mime` and `uri`: the server never copies the base64 bytes into /// history, so this reports no decoded bytes and its /// [ChatAttachment.sizeBytes] is 0 (or the record's own numeric `size` when a /// caller supplied one). Nothing here builds UI or keeps file contents. /// Stores one file on the server and returns its upload name. typedef ChatAttachmentUpload = Future Function(ChatAttachment attachment, Uint8List bytes); /// The prompt parts for files sent ahead through [upload]: each part names the /// stored file instead of carrying its bytes, so size is bound by the server's /// upload limit, not the websocket frame. Throws [ChatAttachmentWireException] /// for an unreadable file; [upload]'s own exceptions pass through. Future> chatAttachmentUploadParts( ChatAttachmentDraft draft, { required ChatAttachmentBytes read, required ChatAttachmentUpload upload, }) async { final attachments = draft.attachments; if (attachments.isEmpty) return const []; if (attachments.length > maxChatAttachmentCount) { throw const ChatAttachmentWireException( 'At most 8 attachments are allowed.', ); } final parts = []; for (final attachment in attachments) { final bytes = read(attachment); if (bytes == null) { throw ChatAttachmentWireException( '"${chatAttachmentDisplayName(attachment.name, '')}" could not be read.', ); } parts.add({ 'name': _wireText(attachment.name, chatAttachmentFallbackName), 'mime': _wireText(attachment.mime, chatAttachmentFallbackMime), 'upload': await upload(attachment, bytes), }); } return parts; } ChatAttachment? chatAttachmentFromHistoryPart(Object? part) { if (part is! Map) return null; if ('${part['type'] ?? ''}'.trim() != 'file') return null; final name = '${part['name'] ?? ''}'.trim(); final uri = '${part['uri'] ?? ''}'.trim(); if (name.isEmpty && uri.isEmpty) return null; final size = part['size']; return ChatAttachment( name: chatAttachmentDisplayName(name, uri), mime: '${part['mime'] ?? ''}'.trim(), sizeBytes: size is num && size >= 0 ? size.toInt() : 0, ); } /// The name shown for a recorded attachment, never blank: its own trimmed /// name, else the URI's basename, else `file` (the web's /// `attachmentDisplayName`). String chatAttachmentDisplayName(String name, String uri) { final shown = name.trim(); if (shown.isNotEmpty) return shown; final basename = uri.split('/').last.trim(); return basename.isEmpty ? 'file' : basename; } String _wireText(String value, String fallback) { final trimmed = value.trim(); return trimmed.isEmpty ? fallback : trimmed; }