feat: show short paths and generated images in the chat

A file tool's row keeps only the part of the path under the session's
directory (lib/screens/chat_screen.dart instead of the whole absolute
path), as the first-party client does, so a phone still shows the file
name; the diff card's file headings drop the same prefix.

A finished openchamber_image call is lifted out of the folded run and
drawn as the picture it saved, in place, as ShownToolCard does through
GeneratedImages: tap opens the full-screen preview, and the card and
preview share an in-memory cache of the bytes.

0.4.13 (413).
This commit is contained in:
blumia committed 2026-11-24 01:05:00 +08:00
1 parent 5c0ea6f6f4
commit 809e0a747a
7 files changed
+353 -25

No files matched your search

+53
View File
@@ -1,6 +1,8 @@
// OpenChamber API models, ported from the Go client's protocol knowledge.
library;
import 'dart:convert';
class ModelRef {
final String id;
final String providerId;
@@ -255,6 +257,19 @@ String pathLeaf(String path) {
String slashPath(String path) =>
path.replaceAll('\\', '/').replaceAll(RegExp(r'/+$'), '');
/// A file inside [directory] shown without it: the tool row says
/// `lib/screens/chat_screen.dart`, as the first-party client does, so a phone
/// still sees the part of the path that matters. Paths elsewhere stay whole.
String relativePath(String path, String directory) {
final file = path.trim();
final dir = slashPath(directory.trim());
if (file.isEmpty || dir.isEmpty) return file;
final normalized = slashPath(file);
if (normalized == dir) return '.';
if (normalized.startsWith('$dir/')) return normalized.substring(dir.length + 1);
return file;
}
/// Whether [directory] is [root] or inside it. Separators are unified and a
/// Windows drive path compares case-insensitively, as [samePath] does.
bool isUnderDirectory(String directory, String root) {
@@ -1034,3 +1049,41 @@ String _jsonString(Object? o) {
if (o is String) return o;
return o.toString();
}
/// The images an `openchamber_image` call saved. The first-party client lifts
/// such a call out of the folded run and shows the pictures in the chat; this
/// reads the call's result envelope (`{ok, action: image.generate, data:
/// {images: [{path}]}}`) to know which files those are.
List<String> generatedImagePaths(ContentPart part) {
const empty = <String>[];
if (part.type != 'tool' || part.name != 'openchamber_image') return empty;
final state = part.state;
if (state == null || state.status != 'completed') return empty;
final text = state.content
.where((c) => c.type == 'text')
.map((c) => c.text)
.join()
.trim();
if (text.isEmpty) return empty;
Object? decoded;
try {
decoded = jsonDecode(text);
} catch (_) {
return empty;
}
if (decoded is! Map) return empty;
if (decoded['ok'] != true || decoded['action'] != 'image.generate') {
return empty;
}
final data = decoded['data'];
if (data is! Map) return empty;
final images = data['images'];
if (images is! List) return empty;
final out = <String>[];
for (final image in images) {
if (image is! Map) continue;
final path = image['path'];
if (path is String && path.trim().isNotEmpty) out.add(path.trim());
}
return out;
}
+190 -21
View File
@@ -386,7 +386,12 @@ class _ChatScreenState extends State<ChatScreen> {
}
for (var p = 0; p < m.content.length; p++) {
final part = m.content[p];
if (part.type == 'reasoning' || part.type == 'tool') {
if (part.type == 'tool' && generatedImagePaths(part).isNotEmpty) {
// A generated picture is shown where the call ran, as the
// first-party client draws it, not folded into the run above.
flush();
out.add(_Row('images', m.id, p));
} else if (part.type == 'reasoning' || part.type == 'tool') {
pending.add(_Step(m.id, p, part));
} else if (part.type == 'text') {
flush();
@@ -460,6 +465,8 @@ class _ChatScreenState extends State<ChatScreen> {
}
final part = m.content[p];
if (part.type != 'reasoning' && part.type != 'tool') break;
// A generated picture is its own card; the run stops before it.
if (generatedImagePaths(part).isNotEmpty) break;
out.add(_Step(m.id, p, part));
p++;
}
@@ -491,6 +498,8 @@ class _ChatScreenState extends State<ChatScreen> {
return _textRow(r.msgId, r.part);
case 'steps':
return _stepsBlock(r.msgId, r.part);
case 'images':
return _imagesRow(r.msgId, r.part);
case 'step':
return _stepRow(r.msgId, r.part);
case 'footer':
@@ -780,10 +789,38 @@ class _ChatScreenState extends State<ChatScreen> {
);
}
/// A picture a tool generated, drawn in the conversation where the call
/// ran. The first-party client hoists `image.generate` results this way
/// (ShownToolCard → GeneratedImages) instead of folding them with Activity.
Widget _imagesRow(String id, int part) {
final m = chat.byId[id]!;
if (part < 0 || part >= m.content.length) return const SizedBox.shrink();
final paths = generatedImagePaths(m.content[part]);
if (paths.isEmpty) return const SizedBox.shrink();
return Padding(
padding: const EdgeInsets.fromLTRB(16, 6, 16, 6),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
for (var i = 0; i < paths.length; i++)
Padding(
padding: EdgeInsets.only(bottom: i == paths.length - 1 ? 0 : 8),
child: _GeneratedImage(
source: paths[i],
directory: chat.dir,
client: widget.app.client!,
onTap: () =>
_showImageDialog(pathLeaf(paths[i]), source: paths[i]),
),
),
],
),
);
}
/// Keeps the list under a growing run: the reversed list would otherwise
/// push the header up by exactly the height that was just revealed.
void _grow(double delta) {
if (!mounted || !_scroll.hasClients || delta.abs() < 0.01) return;
void _grow(double delta) { if (!mounted || !_scroll.hasClients || delta.abs() < 0.01) return;
final p = _scroll.position;
final target = (p.pixels + delta).clamp(p.minScrollExtent, p.maxScrollExtent);
if ((target - p.pixels).abs() > 0.01) _scroll.jumpTo(target);
@@ -1153,7 +1190,17 @@ class _ChatScreenState extends State<ChatScreen> {
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
DiffView(files: diffFiles),
DiffView(files: [
// The row already names the file; a path inside the session's
// directory drops the prefix so it fits a phone.
for (final file in diffFiles)
DiffFile(
path: file.path == null
? null
: relativePath(file.path!, chat.dir),
lines: file.lines,
),
]),
if (output.isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 6),
@@ -1187,6 +1234,8 @@ class _ChatScreenState extends State<ChatScreen> {
return Icons.note_add_outlined;
case 'edit':
return Icons.edit_outlined;
case 'openchamber_image':
return Icons.image_outlined;
case 'patch':
case 'apply_patch':
return Icons.difference_outlined;
@@ -1244,13 +1293,15 @@ class _ChatScreenState extends State<ChatScreen> {
return '子代理';
case 'skill':
return '技能';
case 'openchamber_image':
return '生成图片';
default:
return p.name == null || p.name!.isEmpty ? '工具' : p.name!;
}
}
/// One line that says what the step is about, so a folded run stays useful.
static String _stepSummary(ContentPart p) {
String _stepSummary(ContentPart p) {
if (p.type == 'reasoning') return _firstLine(p.text);
final input = p.state?.input ?? const <String, dynamic>{};
String one(Object? v) =>
@@ -1263,7 +1314,8 @@ class _ChatScreenState extends State<ChatScreen> {
case 'read':
case 'write':
case 'edit':
return one(input['filePath'] ?? input['path'] ?? input['file']);
return relativePath(
one(input['filePath'] ?? input['path'] ?? input['file']), chat.dir);
case 'grep':
case 'glob':
case 'find':
@@ -1281,8 +1333,10 @@ class _ChatScreenState extends State<ChatScreen> {
'description', 'filePath', 'path', 'command', 'query', 'url',
'pattern', 'name', 'id',
]) {
final v = one(input[k]);
if (v.isNotEmpty) return v;
var v = one(input[k]);
if (v.isEmpty) continue;
if (k == 'filePath' || k == 'path') v = relativePath(v, chat.dir);
return v;
}
if (input.isEmpty) return '';
return one(const JsonEncoder().convert(input));
@@ -2389,6 +2443,132 @@ String toolOutput(ContentPart p) {
}
/// Already-fetched pictures, kept for the card and the full-screen view so a
/// rebuild does not ask the server again. Generated images are large, so only
/// a handful stay.
final Map<String, Uint8List> _imageBytes = {};
Future<Uint8List> _imageBytesFor(
Client client, String source, String directory) async {
if (source.startsWith('data:')) {
final comma = source.indexOf(',');
if (comma < 0) throw Exception('无效的 data URL');
final meta = source.substring(5, comma);
if (!meta.contains('base64')) throw Exception('不支持的 data URL');
return base64Decode(source.substring(comma + 1));
}
final cached = _imageBytes[source];
if (cached != null) return cached;
final bytes =
Uint8List.fromList(await client.rawFile(source, directory: directory));
if (_imageBytes.length >= 8) _imageBytes.remove(_imageBytes.keys.first);
_imageBytes[source] = bytes;
return bytes;
}
/// One generated picture, in the conversation where the call ran. Loading is
/// its own state, as the image dialog does it: the row is created before the
/// bytes arrive.
class _GeneratedImage extends StatefulWidget {
final String source;
final String directory;
final Client client;
final VoidCallback onTap;
const _GeneratedImage({
required this.source,
required this.directory,
required this.client,
required this.onTap,
});
@override
State<_GeneratedImage> createState() => _GeneratedImageState();
}
class _GeneratedImageState extends State<_GeneratedImage> {
Uint8List? _bytes;
Object? _error;
@override
void initState() {
super.initState();
_load();
}
Future<void> _load() async {
try {
final bytes =
await _imageBytesFor(widget.client, widget.source, widget.directory);
if (mounted) setState(() => _bytes = bytes);
} catch (e) {
if (mounted) setState(() => _error = e);
}
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
if (_error != null) {
return Container(
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(10),
),
child: Row(
children: [
Icon(Icons.broken_image_outlined,
size: 16, color: theme.hintColor),
const SizedBox(width: 8),
Expanded(
child: Text(
'图片加载失败:${pathLeaf(widget.source)}',
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 12, color: theme.hintColor),
),
),
],
),
);
}
if (_bytes == null) {
return Container(
height: 150,
alignment: Alignment.center,
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(10),
),
child: const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(strokeWidth: 2),
),
);
}
return Align(
alignment: Alignment.centerLeft,
child: InkWell(
onTap: widget.onTap,
borderRadius: BorderRadius.circular(10),
child: ClipRRect(
borderRadius: BorderRadius.circular(10),
child: ConstrainedBox(
constraints: const BoxConstraints(maxHeight: 380),
child: Image.memory(
_bytes!,
fit: BoxFit.contain,
alignment: Alignment.centerLeft,
gaplessPlayback: true,
),
),
),
),
);
}
}
/// A full-screen-ish image preview that loads itself: the dialog is created
/// first, so the image and its spinner must live in a StatefulWidget.
class _ImagePreviewDialog extends StatefulWidget {
@@ -2438,19 +2618,8 @@ class _ImagePreviewDialogState extends State<_ImagePreviewDialog> {
}
}
Future<Uint8List> _fetch() async {
final source = widget.source;
if (source.startsWith('data:')) {
final comma = source.indexOf(',');
if (comma < 0) throw Exception('无效的 data URL');
final meta = source.substring(5, comma);
if (!meta.contains('base64')) throw Exception('不支持的 data URL');
return base64Decode(source.substring(comma + 1));
}
final bytes =
await widget.client.rawFile(source, directory: widget.directory);
return Uint8List.fromList(bytes);
}
Future<Uint8List> _fetch() =>
_imageBytesFor(widget.client, widget.source, widget.directory);
@override
Widget build(BuildContext context) {
+1 -1
View File
@@ -1,2 +1,2 @@
/// The app version sent to the server in pairing and relay handshakes.
const appVersion = '0.4.12';
const appVersion = '0.4.13';