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

+12
View File
@@ -5,6 +5,18 @@
--- ---
## 0.4.13 相对路径与生成图片的行内展示(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 路径显示 | 折叠状态下 `read` / `write` / `edit` 等文件工具只显示相对于会话目录的路径(如 `lib/screens/chat_screen.dart`),不再被 `/home/...` 前缀挤掉文件名;会话目录之外的路径(如 `/tmp/...`)仍显示完整路径。diff 展开后的多文件标题同样去前缀 |
| 生成图片 | 对照上游确认:`openchamber_image`(`action=image.generate`,结果 JSON 里 `data.images[].path`)在 `isShownInPlace` 为真时会从 Activity 折叠里**提升**出来,由 `ShownToolCard → GeneratedImages` 在对话中直接显示图片(懒加载、点开画廊、上方有下载)。现在我们也把它从工具运行段里提出来:运行段在它之前结束,图片以卡片形式出现在原位置,最大高度 380,点击打开既有的全屏预览;运行中仍是「正在生成图片」的普通步骤,失败则留在运行段显示错误 |
| 图片缓存 | 卡片与全屏预览共用一份内存缓存(最多 8 张),列表重建不重复请求 `/api/fs/raw` |
| 测试 | 新增 `test/generated_images_test.dart`:结果 JSON 解析多图、未完成/失败/其它工具/非 JSON 不显示,`relativePath` 去前缀、目录外保留、尾斜杠与相似前缀;65 项全过 |
| 版本 | **0.4.13(code 413)** |
---
## 0.4.12 编辑工具的 diff 显示(分支 `flutter`) ## 0.4.12 编辑工具的 diff 显示(分支 `flutter`)
| 项 | 结果 | | 项 | 结果 |
+4 -2
View File
@@ -5,7 +5,7 @@ Android first. This branch (`flutter`) is a framework evaluation: the same
feature set as the earlier Asuka/Go and MyGo attempts, reimplemented in feature set as the earlier Asuka/Go and MyGo attempts, reimplemented in
Flutter to compare mobile UI maturity. Flutter to compare mobile UI maturity.
Status: 0.4.12 — servers (passwordless / password login, HTTP/HTTPS and Status: 0.4.13 — servers (passwordless / password login, HTTP/HTTPS and
SOCKS5/socks5h proxy, self-signed certificates and pinning, or a pairing link SOCKS5/socks5h proxy, self-signed certificates and pinning, or a pairing link
over the OpenChamber private relay with end-to-end encryption; the pairing over the OpenChamber private relay with end-to-end encryption; the pairing
link is pasted or scanned with the camera), session list with search and live link is pasted or scanned with the camera), session list with search and live
@@ -26,7 +26,9 @@ grouped by project with date captions, pins, archive and swipe actions;
subagent sessions nest under the session that started them (collapsed until subagent sessions nest under the session that started them (collapsed until
expanded) and open from the sidebar or the parent's Agent Task row; a subagent expanded) and open from the sidebar or the parent's Agent Task row; a subagent
chat is read-only unless the server allows prompting subagents; edit, write chat is read-only unless the server allows prompting subagents; edit, write
and patch calls open as tinted line diffs with +N −M counts; the and patch calls open as tinted line diffs with +N −M counts and show their
file path relative to the session directory; a finished image-generation call
shows the picture in the conversation instead of folding it away; the
server's managed chat folders are one 聊天 group, and a new session can target server's managed chat folders are one 聊天 group, and a new session can target
聊天 instead of a project. Project rows use the icon and colour chosen in 聊天 instead of a project. Project rows use the icon and colour chosen in
OpenChamber (including an uploaded/auto icon image), and the chat group has a OpenChamber (including an uploaded/auto icon image), and the chat group has a
+53
View File
@@ -1,6 +1,8 @@
// OpenChamber API models, ported from the Go client's protocol knowledge. // OpenChamber API models, ported from the Go client's protocol knowledge.
library; library;
import 'dart:convert';
class ModelRef { class ModelRef {
final String id; final String id;
final String providerId; final String providerId;
@@ -255,6 +257,19 @@ String pathLeaf(String path) {
String slashPath(String path) => String slashPath(String path) =>
path.replaceAll('\\', '/').replaceAll(RegExp(r'/+$'), ''); 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 /// Whether [directory] is [root] or inside it. Separators are unified and a
/// Windows drive path compares case-insensitively, as [samePath] does. /// Windows drive path compares case-insensitively, as [samePath] does.
bool isUnderDirectory(String directory, String root) { bool isUnderDirectory(String directory, String root) {
@@ -1034,3 +1049,41 @@ String _jsonString(Object? o) {
if (o is String) return o; if (o is String) return o;
return o.toString(); 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++) { for (var p = 0; p < m.content.length; p++) {
final part = m.content[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)); pending.add(_Step(m.id, p, part));
} else if (part.type == 'text') { } else if (part.type == 'text') {
flush(); flush();
@@ -460,6 +465,8 @@ class _ChatScreenState extends State<ChatScreen> {
} }
final part = m.content[p]; final part = m.content[p];
if (part.type != 'reasoning' && part.type != 'tool') break; 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)); out.add(_Step(m.id, p, part));
p++; p++;
} }
@@ -491,6 +498,8 @@ class _ChatScreenState extends State<ChatScreen> {
return _textRow(r.msgId, r.part); return _textRow(r.msgId, r.part);
case 'steps': case 'steps':
return _stepsBlock(r.msgId, r.part); return _stepsBlock(r.msgId, r.part);
case 'images':
return _imagesRow(r.msgId, r.part);
case 'step': case 'step':
return _stepRow(r.msgId, r.part); return _stepRow(r.msgId, r.part);
case 'footer': 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 /// Keeps the list under a growing run: the reversed list would otherwise
/// push the header up by exactly the height that was just revealed. /// push the header up by exactly the height that was just revealed.
void _grow(double delta) { void _grow(double delta) { if (!mounted || !_scroll.hasClients || delta.abs() < 0.01) return;
if (!mounted || !_scroll.hasClients || delta.abs() < 0.01) return;
final p = _scroll.position; final p = _scroll.position;
final target = (p.pixels + delta).clamp(p.minScrollExtent, p.maxScrollExtent); final target = (p.pixels + delta).clamp(p.minScrollExtent, p.maxScrollExtent);
if ((target - p.pixels).abs() > 0.01) _scroll.jumpTo(target); if ((target - p.pixels).abs() > 0.01) _scroll.jumpTo(target);
@@ -1153,7 +1190,17 @@ class _ChatScreenState extends State<ChatScreen> {
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch, crossAxisAlignment: CrossAxisAlignment.stretch,
children: [ 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) if (output.isNotEmpty)
Padding( Padding(
padding: const EdgeInsets.only(top: 6), padding: const EdgeInsets.only(top: 6),
@@ -1187,6 +1234,8 @@ class _ChatScreenState extends State<ChatScreen> {
return Icons.note_add_outlined; return Icons.note_add_outlined;
case 'edit': case 'edit':
return Icons.edit_outlined; return Icons.edit_outlined;
case 'openchamber_image':
return Icons.image_outlined;
case 'patch': case 'patch':
case 'apply_patch': case 'apply_patch':
return Icons.difference_outlined; return Icons.difference_outlined;
@@ -1244,13 +1293,15 @@ class _ChatScreenState extends State<ChatScreen> {
return '子代理'; return '子代理';
case 'skill': case 'skill':
return '技能'; return '技能';
case 'openchamber_image':
return '生成图片';
default: default:
return p.name == null || p.name!.isEmpty ? '工具' : p.name!; return p.name == null || p.name!.isEmpty ? '工具' : p.name!;
} }
} }
/// One line that says what the step is about, so a folded run stays useful. /// 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); if (p.type == 'reasoning') return _firstLine(p.text);
final input = p.state?.input ?? const <String, dynamic>{}; final input = p.state?.input ?? const <String, dynamic>{};
String one(Object? v) => String one(Object? v) =>
@@ -1263,7 +1314,8 @@ class _ChatScreenState extends State<ChatScreen> {
case 'read': case 'read':
case 'write': case 'write':
case 'edit': case 'edit':
return one(input['filePath'] ?? input['path'] ?? input['file']); return relativePath(
one(input['filePath'] ?? input['path'] ?? input['file']), chat.dir);
case 'grep': case 'grep':
case 'glob': case 'glob':
case 'find': case 'find':
@@ -1281,8 +1333,10 @@ class _ChatScreenState extends State<ChatScreen> {
'description', 'filePath', 'path', 'command', 'query', 'url', 'description', 'filePath', 'path', 'command', 'query', 'url',
'pattern', 'name', 'id', 'pattern', 'name', 'id',
]) { ]) {
final v = one(input[k]); var v = one(input[k]);
if (v.isNotEmpty) return v; if (v.isEmpty) continue;
if (k == 'filePath' || k == 'path') v = relativePath(v, chat.dir);
return v;
} }
if (input.isEmpty) return ''; if (input.isEmpty) return '';
return one(const JsonEncoder().convert(input)); 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 /// 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. /// first, so the image and its spinner must live in a StatefulWidget.
class _ImagePreviewDialog extends StatefulWidget { class _ImagePreviewDialog extends StatefulWidget {
@@ -2438,19 +2618,8 @@ class _ImagePreviewDialogState extends State<_ImagePreviewDialog> {
} }
} }
Future<Uint8List> _fetch() async { Future<Uint8List> _fetch() =>
final source = widget.source; _imageBytesFor(widget.client, widget.source, widget.directory);
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);
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
+1 -1
View File
@@ -1,2 +1,2 @@
/// The app version sent to the server in pairing and relay handshakes. /// The app version sent to the server in pairing and relay handshakes.
const appVersion = '0.4.12'; const appVersion = '0.4.13';
+1 -1
View File
@@ -2,7 +2,7 @@ name: openchamber
description: "A lightweight OpenChamber client for phones." description: "A lightweight OpenChamber client for phones."
publish_to: 'none' publish_to: 'none'
version: 0.4.12+412 version: 0.4.13+413
environment: environment:
sdk: ^3.14.0 sdk: ^3.14.0
+92
View File
@@ -0,0 +1,92 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:openchamber/api/models.dart';
ContentPart imageTool({
String name = 'openchamber_image',
String status = 'completed',
String text = '',
String? error,
}) {
return ContentPart(
type: 'tool',
name: name,
state: ToolState(
status: status,
content: [ContentPart(type: 'text', text: text)],
error: error,
),
);
}
const envelope =
'{"schemaVersion":1,"ok":true,"action":"image.generate","data":'
'{"model":"axonhub-image/sensenova-u1.5-lite","images":['
'{"path":"/tmp/opencode/generated-images/a.png","mime":"image/png"},'
'{"path":"/tmp/opencode/generated-images/b.png","mime":"image/png"}]}}';
void main() {
group('generatedImagePaths', () {
test('reads every path from a finished image call', () {
final part = imageTool(text: envelope);
expect(generatedImagePaths(part), [
'/tmp/opencode/generated-images/a.png',
'/tmp/opencode/generated-images/b.png',
]);
});
test('shows nothing while the call still runs', () {
expect(generatedImagePaths(imageTool(status: 'running', text: envelope)),
isEmpty);
});
test('shows nothing for a failed call', () {
expect(
generatedImagePaths(
imageTool(status: 'error', text: envelope, error: 'no model')),
isEmpty,
);
});
test('only the openchamber_image tool is lifted out', () {
expect(generatedImagePaths(imageTool(name: 'bash', text: envelope)),
isEmpty);
expect(
generatedImagePaths(ContentPart(type: 'text', text: envelope)),
isEmpty,
);
});
test('a plain text result is not a picture', () {
expect(generatedImagePaths(imageTool(text: '图片已生成')), isEmpty);
expect(
generatedImagePaths(imageTool(text: '{"ok":false,"action":"x"}')),
isEmpty,
);
});
});
group('relativePath', () {
test('drops the session directory', () {
expect(
relativePath('/home/blumia/src/app/lib/main.dart',
'/home/blumia/src/app'),
'lib/main.dart',
);
});
test('keeps paths outside it whole', () {
expect(
relativePath('/tmp/opencode/generated-images/a.png',
'/home/blumia/src/app'),
'/tmp/opencode/generated-images/a.png',
);
});
test('tolerates a trailing slash and a file elsewhere', () {
expect(relativePath('/a/b/c.txt', '/a/b/'), 'c.txt');
expect(relativePath('/a/bc/c.txt', '/a/b'), '/a/bc/c.txt');
expect(relativePath('x.txt', ''), 'x.txt');
expect(relativePath('/a/b', '/a/b'), '.');
});
});
}