diff --git a/app/lib/features/chat/domain/chat_attachment_wire.dart b/app/lib/features/chat/domain/chat_attachment_wire.dart new file mode 100644 index 00000000..4a429921 --- /dev/null +++ b/app/lib/features/chat/domain/chat_attachment_wire.dart @@ -0,0 +1,128 @@ +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 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 +/// [ChatAttachmentDraft.maxTotalBytes] 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 > ChatAttachmentDraft.maxTotalBytes) { + throw const ChatAttachmentWireException( + 'Attachments are too large for web chat (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. +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; +} diff --git a/app/test/features/chat/domain/chat_attachment_wire_test.dart b/app/test/features/chat/domain/chat_attachment_wire_test.dart new file mode 100644 index 00000000..ee5cf497 --- /dev/null +++ b/app/test/features/chat/domain/chat_attachment_wire_test.dart @@ -0,0 +1,193 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/data/chat_repository.dart'; +import 'package:pipelines_app/features/chat/domain/chat_attachment_draft.dart'; +import 'package:pipelines_app/features/chat/domain/chat_attachment_wire.dart'; + +class _RecordingGateway implements ApiGateway { + JsonMap? fields; + + @override + Stream get frames => const Stream.empty(); + + @override + Future call(String type, [JsonMap fields = const {}]) async { + this.fields = fields; + return const {}; + } +} + +ChatAttachment attachment( + String name, + int sizeBytes, { + String mime = 'text/plain', +}) => ChatAttachment(name: name, mime: mime, sizeBytes: sizeBytes); + +void main() { + final png = Uint8List.fromList([0, 1, 2, 255]); + final notes = Uint8List.fromList(utf8.encode('hello')); + + test('builds one exact {name, mime, data} part per draft file, in order', () { + final draft = ChatAttachmentDraft() + ..add(attachment(' screen.png ', png.length, mime: ' image/png ')) + ..add(attachment('notes.txt', notes.length, mime: '')); + + final parts = chatAttachmentParts( + draft, + read: (entry) => entry.name.trim() == 'screen.png' ? png : notes, + ); + + expect(parts, hasLength(2)); + expect(parts[0].keys.toList(), ['name', 'mime', 'data']); + expect(parts[0], { + 'name': 'screen.png', + 'mime': 'image/png', + 'data': base64Encode(png), + }); + expect(parts[1], { + 'name': 'notes.txt', + 'mime': 'application/octet-stream', + 'data': base64Encode(notes), + }); + }); + + test('base64 data round-trips to the picked bytes', () { + final draft = ChatAttachmentDraft() + ..add(attachment('screen.png', png.length, mime: 'image/png')); + + final part = chatAttachmentParts(draft, read: (_) => png).single; + final encoded = part['data'] as String; + + expect(encoded, 'AAEC/w=='); + expect(base64Decode(encoded), png); + }); + + test( + 'an empty draft yields no parts, so the prompt has no attachments key', + () async { + final gateway = _RecordingGateway(); + final parts = chatAttachmentParts( + ChatAttachmentDraft(), + read: (_) => throw StateError('an empty draft reads nothing'), + ); + + expect(parts, isEmpty); + + await ChatRepository( + gateway, + ).prompt('ses_1', 'hello', operationId: 'op_1', attachments: parts); + final body = gateway.fields!['chat_prompt'] as JsonMap; + expect(body.containsKey('attachments'), isFalse); + }, + ); + + test('refuses more than eight files before reading any of them', () { + final draft = ChatAttachmentDraft(); + for (var index = 0; index < maxChatAttachmentCount + 1; index += 1) { + draft.add(attachment('file-$index.bin', 0)); + } + var reads = 0; + + expect( + () => chatAttachmentParts( + draft, + read: (_) { + reads += 1; + return Uint8List(0); + }, + ), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'At most 8 attachments are allowed.', + ), + ), + ); + expect(reads, 0); + }); + + test('refuses an actual total over 1 MiB before encoding a part', () { + final draft = ChatAttachmentDraft() + ..add(attachment('first.bin', 1)) + ..add(attachment('second.bin', 1)); + var reads = 0; + + expect( + () => chatAttachmentParts( + draft, + read: (_) { + reads += 1; + return Uint8List(ChatAttachmentDraft.maxTotalBytes + 1); + }, + ), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'Attachments are too large for web chat (1 MiB total).', + ), + ), + ); + // The bound is checked while reading: no part was built and the next file + // was never touched. + expect(reads, 1); + }); + + test('names the file that could not be read', () { + final draft = ChatAttachmentDraft()..add(attachment('missing.txt', 4)); + + expect( + () => chatAttachmentParts(draft, read: (_) => null), + throwsA( + isA().having( + (error) => error.message, + 'message', + '"missing.txt" could not be read.', + ), + ), + ); + }); + + test('parses a recorded history file part without decoding it into UI', () { + final parsed = chatAttachmentFromHistoryPart({ + 'type': 'file', + 'name': 'report.csv', + 'mime': 'text/csv', + 'uri': 'file:///tmp/report.csv', + }); + + expect( + parsed, + const ChatAttachment(name: 'report.csv', mime: 'text/csv', sizeBytes: 0), + ); + }); + + test('falls back to the URI basename and keeps a recorded size', () { + expect( + chatAttachmentFromHistoryPart({ + 'type': 'file', + 'uri': 'file:///tmp/plan.md', + 'size': 42, + }), + const ChatAttachment(name: 'plan.md', mime: '', sizeBytes: 42), + ); + }); + + test('ignores parts that are not a recorded attachment', () { + expect(chatAttachmentFromHistoryPart(null), isNull); + expect(chatAttachmentFromHistoryPart('file'), isNull); + expect( + chatAttachmentFromHistoryPart({'type': 'text', 'text': 'hello'}), + isNull, + ); + expect(chatAttachmentFromHistoryPart({'type': 'file'}), isNull); + expect( + chatAttachmentFromHistoryPart({'type': 'file', 'name': ' '}), + isNull, + ); + }); +}