Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions lib/chat/chat_session.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand All @@ -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<ImageAttachment> 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 '<system-reminder>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'
'</system-reminder>';
}

static final _random = math.Random.secure();

/// A random UUID (v4): kernels may use it as the message's id.
Expand Down
13 changes: 13 additions & 0 deletions lib/chat/composer/paste_store.dart
Original file line number Diff line number Diff line change
@@ -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'
Expand Down Expand Up @@ -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<String?> read(String path) => platform.readPaste(path);
Expand Down
22 changes: 22 additions & 0 deletions lib/chat/composer/paste_store_io.dart
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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<String?> readPaste(String path) async {
for (final candidate in _candidates(path)) {
try {
Expand Down
4 changes: 4 additions & 0 deletions lib/chat/composer/paste_store_stub.dart
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import 'dart:typed_data';

String? pastesDirectory() => null;

String? savePaste(String text) => null;

String? saveImage(Uint8List bytes, String extension) => null;

Future<String?> readPaste(String path) async => null;

String? readPasteNow(String path) => null;
99 changes: 99 additions & 0 deletions test/chat/image_files_note_test.dart
Original file line number Diff line number Diff line change
@@ -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<String> 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);
});
}