diff --git a/lib/chat/chat_session.dart b/lib/chat/chat_session.dart index f5009032e..0e18de37b 100644 --- a/lib/chat/chat_session.dart +++ b/lib/chat/chat_session.dart @@ -1218,6 +1218,7 @@ class ChatSession extends ChangeNotifier implements ChatFeed { now: now, notes: [ ...notes, + ?_imageFilesNote(message.images), ..._placeNotes(from), if (editor != null) ..._editorNotes(editor()), if (from != null) ..._suggestionNotes(), @@ -1226,6 +1227,29 @@ class ChatSession extends ChangeNotifier implements ChatFeed { _kernel.send(turn); } + /// Where the agent finds [images] as files: they reach it as pictures + /// alone, and a tool that wants a file (an upload, an attachment) had it + /// look for one on the disk (#1129). None for a remote project's, which + /// cannot read this machine's files. + String? _imageFilesNote(List images) { + if (images.isEmpty || RemoteLocation.isRemote(kernelContext.cwd ?? '')) { + return null; + } + final lines = [ + for (final (i, image) in images.indexed) + if (PasteStore.saveImage(image.bytes, image.mediaType) case final path?) + '${switch (image.number) { + final number? => imageReference(number), + null => 'Image ${i + 1}', + }}: $path', + ]; + if (lines.isEmpty) return null; + return 'The images attached to this message are also ' + 'saved as files, for when a file is needed rather than what you see ' + '(to upload or attach it, say):\n${lines.join('\n')}\n' + ''; + } + static final _random = math.Random.secure(); /// A random UUID (v4): kernels may use it as the message's id. diff --git a/lib/chat/composer/paste_store.dart b/lib/chat/composer/paste_store.dart index ae50e244b..50568ab4b 100644 --- a/lib/chat/composer/paste_store.dart +++ b/lib/chat/composer/paste_store.dart @@ -1,3 +1,5 @@ +import 'dart:typed_data'; + import 'composer_files.dart'; import 'paste_store_stub.dart' if (dart.library.io) 'paste_store_io.dart' @@ -27,6 +29,17 @@ abstract final class PasteStore { /// Keeps [text]; where, or null where it could not be. static String? save(String text) => platform.savePaste(text); + /// Keeps a picture sent, [bytes] as the agent was sent them, in + /// `images/` beside the pastes (read as they are): for the agent to use + /// as a file (#1129). Where, or null where it could not be. + static String? saveImage(Uint8List bytes, String mediaType) => + platform.saveImage(bytes, switch (mediaType) { + 'image/jpeg' => 'jpg', + 'image/gif' => 'gif', + 'image/webp' => 'webp', + _ => 'png', + }); + /// What the paste kept at [path] says; null where it is gone. One kept /// before the app's data moved is looked for where they are now. static Future read(String path) => platform.readPaste(path); diff --git a/lib/chat/composer/paste_store_io.dart b/lib/chat/composer/paste_store_io.dart index 956f53ae4..ab47cf559 100644 --- a/lib/chat/composer/paste_store_io.dart +++ b/lib/chat/composer/paste_store_io.dart @@ -1,5 +1,6 @@ import 'dart:convert'; import 'dart:io'; +import 'dart:typed_data'; import 'package:crypto/crypto.dart'; import 'package:path/path.dart' as p; @@ -25,6 +26,27 @@ String? savePaste(String text) { } } +String? saveImage(Uint8List bytes, String extension) { + final hash = sha256.convert(bytes).toString(); + final file = File( + p.join( + DataDirectory.current.pastesDir, + 'images', + '${hash.substring(0, 20)}.$extension', + ), + ); + try { + // Sent again: the one kept. + if (!file.existsSync()) { + file.parent.createSync(recursive: true); + file.writeAsBytesSync(bytes, flush: true); + } + return file.path; + } on FileSystemException { + return null; + } +} + Future readPaste(String path) async { for (final candidate in _candidates(path)) { try { diff --git a/lib/chat/composer/paste_store_stub.dart b/lib/chat/composer/paste_store_stub.dart index 42a254f46..9340475b6 100644 --- a/lib/chat/composer/paste_store_stub.dart +++ b/lib/chat/composer/paste_store_stub.dart @@ -1,7 +1,11 @@ +import 'dart:typed_data'; + String? pastesDirectory() => null; String? savePaste(String text) => null; +String? saveImage(Uint8List bytes, String extension) => null; + Future readPaste(String path) async => null; String? readPasteNow(String path) => null; diff --git a/test/chat/image_files_note_test.dart b/test/chat/image_files_note_test.dart new file mode 100644 index 000000000..f1ae8bf61 --- /dev/null +++ b/test/chat/image_files_note_test.dart @@ -0,0 +1,99 @@ +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:baocode/chat/chat_models.dart'; +import 'package:baocode/chat/chat_session.dart'; +import 'package:baocode/kernel/agent_kernel.dart'; +import 'package:baocode/kernel/claude_code/claude_code_kernel.dart'; +import 'package:baocode/platform/data_dir.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import '../kernel_test.dart' show FakeCli; + +void main() { + setUp(() { + final folder = Directory(DataDirectory.current.pastesDir); + if (folder.existsSync()) folder.deleteSync(recursive: true); + }); + + ChatSession start(FakeCli cli, {String? cwd}) { + late final KernelDescriptor descriptor; + descriptor = KernelDescriptor( + id: 'claude-code', + label: 'Claude Code', + icon: Icons.auto_awesome_rounded, + description: '', + create: (context) => + ClaudeCodeKernel(descriptor, context, start: (_) async => cli), + ); + final session = ChatSession( + kernel: descriptor, + kernels: [descriptor], + historyCount: 0, + kernelContext: KernelContext(cwd: cwd), + ); + addTearDown(session.dispose); + return session; + } + + /// The text blocks written with the user's first message. + List texts(FakeCli cli) => [ + for (final block in (cli.users.first['message'] as Map)['content'] as List) + if ((block as Map)['text'] case final String text) text, + ]; + + final png = Uint8List.fromList([0x89, 0x50, 0x4e, 0x47, 1, 2, 3]); + final jpeg = Uint8List.fromList([0xff, 0xd8, 0xff, 4, 5, 6]); + + test( + 'the agent is told where the images sent are, as files (#1129)', + () async { + final cli = FakeCli(); + final session = start(cli); + session.send( + ComposerMessage( + text: 'Upload [Image #3] and this one', + images: [ + ImageAttachment(bytes: png, mediaType: 'image/png', number: 3), + ImageAttachment(bytes: jpeg, mediaType: 'image/jpeg'), + ], + ), + ); + await pumpEventQueue(); + final note = texts(cli).singleWhere((text) => text.contains('saved as')); + final paths = RegExp( + r': (/\S+)$', + multiLine: true, + ).allMatches(note).map((match) => match[1]!).toList(); + expect(note, contains('[Image #3]: ')); + expect(note, contains('Image 2: ')); + expect(paths, hasLength(2)); + expect(paths.first, endsWith('.png')); + expect(paths.last, endsWith('.jpg')); + expect(File(paths.first).readAsBytesSync(), png); + expect(File(paths.last).readAsBytesSync(), jpeg); + expect( + paths.every((path) => path.startsWith(DataDirectory.current.pastesDir)), + isTrue, + ); + }, + ); + + test('none without images, nor for a remote project\'s agent', () async { + final plain = FakeCli(); + start(plain).send(const ComposerMessage(text: 'hi')); + await pumpEventQueue(); + expect(texts(plain).where((text) => text.contains('saved as')), isEmpty); + + final remote = FakeCli(); + start(remote, cwd: 'ssh://host/p').send( + ComposerMessage( + text: 'look', + images: [ImageAttachment(bytes: png, mediaType: 'image/png')], + ), + ); + await pumpEventQueue(); + expect(texts(remote).where((text) => text.contains('saved as')), isEmpty); + }); +}