diff --git a/PLAN.md b/PLAN.md index e88fc26..79ff426 100644 --- a/PLAN.md +++ b/PLAN.md @@ -5,6 +5,20 @@ --- +## 0.4.12 编辑工具的 diff 显示(分支 `flutter`) + +| 项 | 结果 | +| --- | --- | +| 展开为 diff | `edit` / `write` / `patch` 等文件修改工具展开后不再显示一整段 old/new 纯文本,而是逐行 diff:新增行绿色底、删除行红色底、`@@` hunk 头浅色标记、`---/+++` 等元信息变灰;长行软换行,整块可选中复制(对齐 dsh-Go / 上游 `ToolPartDiffPreview`) | +| 数据来源 | 优先用服务端 `state.metadata.files[].patch`(可能多文件,按文件显示标题),其次 `metadata.patch` / `metadata.diff`;老服务端没有 patch 时用输入的 `oldString`/`newString` 做行级 LCS,`write` 只有 `content` 时显示为全新增行 | +| 行尾统计 | 工具行右侧显示 `+N −M`(与 dsh-Go 一致),失败/运行中不显示 | +| 大 diff | 最多渲染 600 行,超出显示「仅显示前 600 行,共 N 行」,避免聊天列表一次构建过多行 | +| 结果行 | diff 下方保留一行工具自身结果(如「Edited PLAN.md (1 replacement)」),错误仍用错误色 | +| 测试 | 新增 `test/diff_view_test.dart`:metadata patch 解析与增删计数、无 patch 的 old/new 回退、`write` 内容回退、失败/非文件工具不显示、DiffView 渲染增删行;57 项全过 | +| 版本 | **0.4.12(code 412)** | + +--- + ## 0.4.11 侧栏对齐调整(分支 `flutter`) | 项 | 结果 | diff --git a/README.md b/README.md index 0812342..61959e5 100644 --- a/README.md +++ b/README.md @@ -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 Flutter to compare mobile UI maturity. -Status: 0.4.11 — servers (passwordless / password login, HTTP/HTTPS and +Status: 0.4.12 — servers (passwordless / password login, HTTP/HTTPS and SOCKS5/socks5h proxy, self-signed certificates and pinning, or a pairing link 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 @@ -25,7 +25,8 @@ draft that only creates the session on the first send; the session list is grouped by project with date captions, pins, archive and swipe actions; 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 -chat is read-only unless the server allows prompting subagents; the +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 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 OpenChamber (including an uploaded/auto icon image), and the chat group has a diff --git a/lib/screens/chat_screen.dart b/lib/screens/chat_screen.dart index 8c83d54..880eef0 100644 --- a/lib/screens/chat_screen.dart +++ b/lib/screens/chat_screen.dart @@ -12,6 +12,7 @@ import '../state.dart'; import '../widgets/composer_attachment.dart'; import '../widgets/markdown_view.dart'; import '../widgets/composer_box.dart'; +import '../widgets/diff_view.dart'; import '../widgets/pet_sprite.dart'; import '../widgets/model_controls.dart'; import '../widgets/slash_palette.dart'; @@ -854,6 +855,13 @@ class _ChatScreenState extends State { ? const <_ImageRef>[] : toolImages(p, chat.dir); final subagentId = _subagentSessionId(p); + final diffFiles = reasoning ? const [] : toolDiffFiles(p); + var diffAdded = 0; + var diffRemoved = 0; + for (final file in diffFiles) { + diffAdded += file.added; + diffRemoved += file.removed; + } return Container( margin: const EdgeInsets.only(left: 22), decoration: BoxDecoration( @@ -921,6 +929,14 @@ class _ChatScreenState extends State { : theme.hintColor)), ), ], + if (diffFiles.isNotEmpty && + !busy && + status != 'error' && + diffAdded + diffRemoved > 0) + Padding( + padding: const EdgeInsets.only(left: 6, right: 2), + child: DiffStats(added: diffAdded, removed: diffRemoved), + ), if (subagentId != null) Icon(Icons.chevron_right, size: 18, color: theme.hintColor) @@ -958,7 +974,7 @@ class _ChatScreenState extends State { _Reveal( open: open, onGrow: _grow, - child: _stepDetails(p, reasoning), + child: _stepDetails(p, reasoning, diffFiles), ), ], ), @@ -1057,8 +1073,10 @@ class _ChatScreenState extends State { /// What the step actually did: the command or path, the rest of the input, /// and the result — never the request JSON as a blob. - Widget _stepDetails(ContentPart p, bool reasoning) { + Widget _stepDetails( + ContentPart p, bool reasoning, List diffFiles) { final theme = Theme.of(context); + if (diffFiles.isNotEmpty) return _diffDetails(p, diffFiles); if (reasoning) { if (p.text.isEmpty) return const SizedBox.shrink(); // The model writes Markdown here too; render it as such, a touch @@ -1125,6 +1143,37 @@ class _ChatScreenState extends State { ); } + /// An edit/write/patch opened: the before/after as tinted diff lines, with + /// the tool's own result in one quiet line under it. + Widget _diffDetails(ContentPart p, List diffFiles) { + final theme = Theme.of(context); + final output = toolOutput(p).trim(); + return Padding( + padding: const EdgeInsets.fromLTRB(10, 2, 10, 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + DiffView(files: diffFiles), + if (output.isNotEmpty) + Padding( + padding: const EdgeInsets.only(top: 6), + child: Text( + output, + maxLines: 4, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 11.5, + color: p.state?.error != null + ? theme.colorScheme.error + : theme.hintColor, + ), + ), + ), + ], + ), + ); + } + static IconData _stepIcon(ContentPart p) { if (p.type == 'reasoning') return Icons.psychology_outlined; switch (p.name ?? '') { diff --git a/lib/version.dart b/lib/version.dart index 88c3be1..a899b0f 100644 --- a/lib/version.dart +++ b/lib/version.dart @@ -1,2 +1,2 @@ /// The app version sent to the server in pairing and relay handshakes. -const appVersion = '0.4.11'; +const appVersion = '0.4.12'; diff --git a/lib/widgets/diff_view.dart b/lib/widgets/diff_view.dart new file mode 100644 index 0000000..30637bc --- /dev/null +++ b/lib/widgets/diff_view.dart @@ -0,0 +1,342 @@ +// Line-level diffs for edit/write/patch tool calls, as the first-party and +// dsh-Go clients show them: added and removed lines tinted, hunk headers +// marked, and the before/after text never dumped as one blob. +import 'dart:math' as math; + +import 'package:flutter/material.dart'; + +import '../api/models.dart'; + +enum DiffLineKind { context, add, del, hunk, meta } + +class DiffLine { + final DiffLineKind kind; + final String text; + + const DiffLine(this.kind, this.text); +} + +class DiffFile { + /// The path the server put in the tool metadata, when it named one. + final String? path; + final List lines; + + const DiffFile({this.path, required this.lines}); + + int get added => + lines.where((line) => line.kind == DiffLineKind.add).length; + + int get removed => + lines.where((line) => line.kind == DiffLineKind.del).length; +} + +const _diffTools = { + 'edit', + 'write', + 'create', + 'file_write', + 'patch', + 'apply_patch', + 'str_replace', + 'str_replace_based_edit_tool', +}; + +bool isDiffTool(String? name) => _diffTools.contains(name ?? ''); + +String? _text(Object? value) => value is String ? value : null; + +String? _nonEmptyText(Object? value) { + final text = _text(value); + return text == null || text.trim().isEmpty ? null : text; +} + +String? _patchText(Object? value) { + if (value is Map) { + return _nonEmptyText(value['patch']) ?? _nonEmptyText(value['diff']); + } + return _nonEmptyText(value); +} + +String? _filePath(Map file) => + _nonEmptyText(file['file']) ?? + _nonEmptyText(file['filePath']) ?? + _nonEmptyText(file['relativePath']) ?? + _nonEmptyText(file['movePath']); + +/// The diff a tool call carries, from the server's `metadata.files[].patch` +/// (falling back to a top-level patch), or computed from the edit's old/new +/// text when an older server sends no patch. +List toolDiffFiles(ContentPart part) { + if (part.type != 'tool' || !isDiffTool(part.name)) return const []; + final state = part.state; + if (state == null) return const []; + if (_nonEmptyText(state.error) != null) return const []; + + final files = []; + final metadata = state.metadata; + final rawFiles = metadata?['files']; + if (rawFiles is List) { + for (final raw in rawFiles) { + if (raw is! Map) continue; + final patch = + _patchText(raw['patch']) ?? _patchText(raw['diff']); + if (patch == null) continue; + final lines = parseUnifiedDiff(patch); + if (lines.isEmpty) continue; + files.add(DiffFile(path: _filePath(raw), lines: lines)); + } + } + + if (files.isEmpty) { + final patch = + _patchText(metadata?['patch']) ?? _patchText(metadata?['diff']); + if (patch != null) { + final lines = parseUnifiedDiff(patch); + if (lines.isNotEmpty) files.add(DiffFile(lines: lines)); + } + } + + if (files.isEmpty) { + final input = state.input; + final path = _nonEmptyText(input['path']) ?? + _nonEmptyText(input['filePath']) ?? + _nonEmptyText(input['file_path']); + final oldText = _text(input['oldString']) ?? + _text(input['old_string']) ?? + _text(input['old_str']); + final newText = _text(input['newString']) ?? + _text(input['new_string']) ?? + _text(input['new_str']); + if (newText != null) { + final lines = computeLineDiff(oldText ?? '', newText); + if (lines.isNotEmpty) files.add(DiffFile(path: path, lines: lines)); + } else if (part.name == 'write' || + part.name == 'create' || + part.name == 'file_write') { + final content = _text(input['content']) ?? _text(input['file_text']); + if (content != null && content.isNotEmpty) { + files.add(DiffFile( + path: path, + lines: [ + for (final line in content.replaceAll('\r\n', '\n').split('\n')) + DiffLine(DiffLineKind.add, '+$line'), + ], + )); + } + } + } + + return files; +} + +/// A unified diff: `@@` hunks, `+++`/`---`/`diff`/`index` metadata, `+` and +/// `-` changes, everything else context. Trailing blank context is dropped so +/// a file's diff ends on its last real line. +List parseUnifiedDiff(String text) { + final lines = []; + for (final raw in text.replaceAll('\r\n', '\n').split('\n')) { + final kind = raw.startsWith('@@') + ? DiffLineKind.hunk + : raw.startsWith('+++') || + raw.startsWith('---') || + raw.startsWith('diff ') || + raw.startsWith('index ') || + raw.startsWith('Index: ') || + raw.startsWith('===') + ? DiffLineKind.meta + : raw.startsWith('+') + ? DiffLineKind.add + : raw.startsWith('-') + ? DiffLineKind.del + : DiffLineKind.context; + lines.add(DiffLine(kind, raw)); + } + while (lines.isNotEmpty && + lines.last.kind == DiffLineKind.context && + lines.last.text.isEmpty) { + lines.removeLast(); + } + return lines; +} + +/// Line-level LCS diff for an edit that came without server patches. Very +/// large pairs fall back to one removed and one added block. +List computeLineDiff(String oldText, String newText) { + final a = oldText.isEmpty ? [] : oldText.split('\n'); + final b = newText.isEmpty ? [] : newText.split('\n'); + if (a.length * b.length > 400 * 400) { + return [ + for (final line in a) DiffLine(DiffLineKind.del, '-$line'), + for (final line in b) DiffLine(DiffLineKind.add, '+$line'), + ]; + } + final dp = List.generate( + a.length + 1, (_) => List.filled(b.length + 1, 0)); + for (var i = a.length - 1; i >= 0; i--) { + for (var j = b.length - 1; j >= 0; j--) { + dp[i][j] = a[i] == b[j] + ? dp[i + 1][j + 1] + 1 + : math.max(dp[i + 1][j], dp[i][j + 1]); + } + } + final lines = []; + var i = 0; + var j = 0; + while (i < a.length && j < b.length) { + if (a[i] == b[j]) { + lines.add(DiffLine(DiffLineKind.context, ' ${a[i]}')); + i++; + j++; + } else if (dp[i + 1][j] >= dp[i][j + 1]) { + lines.add(DiffLine(DiffLineKind.del, '-${a[i]}')); + i++; + } else { + lines.add(DiffLine(DiffLineKind.add, '+${b[j]}')); + j++; + } + } + while (i < a.length) { + lines.add(DiffLine(DiffLineKind.del, '-${a[i]}')); + i++; + } + while (j < b.length) { + lines.add(DiffLine(DiffLineKind.add, '+${b[j]}')); + j++; + } + return lines; +} + +/// Tinted, horizontally wrapped diff lines. Selection spans the whole block, +/// so the diff can be copied line by line as it reads. +class DiffView extends StatelessWidget { + final List files; + + /// Phone-sized preview: a huge generated diff does not build thousands of + /// rows in the message list; the rest is counted, not drawn. + final int maxLines; + + const DiffView({super.key, required this.files, this.maxLines = 600}); + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final scheme = theme.colorScheme; + final dark = theme.brightness == Brightness.dark; + final addBg = const Color(0xFF22C55E).withValues(alpha: dark ? 0.18 : 0.12); + final addFg = + dark ? const Color(0xFF86E7A6) : const Color(0xFF116329); + final delBg = const Color(0xFFEF4444).withValues(alpha: dark ? 0.18 : 0.12); + final delFg = + dark ? const Color(0xFFFF9B9B) : const Color(0xFFA40E26); + final hunkBg = scheme.primary.withValues(alpha: dark ? 0.10 : 0.07); + const mono = TextStyle(fontSize: 12, height: 1.45, fontFamily: 'monospace'); + + var remaining = maxLines; + var total = 0; + for (final file in files) { + total += file.lines.length; + } + final rows = []; + for (var fileIndex = 0; fileIndex < files.length; fileIndex++) { + final file = files[fileIndex]; + if (files.length > 1) { + rows.add(Container( + color: scheme.surfaceContainer, + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 5), + child: Row( + children: [ + Expanded( + child: Text( + file.path ?? '文件 ${fileIndex + 1}', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 11.5, + fontWeight: FontWeight.w600, + color: scheme.onSurfaceVariant, + ), + ), + ), + DiffStats(added: file.added, removed: file.removed), + ], + ), + )); + } + for (final line in file.lines) { + // The step row already names the file; `Index:`/`---`/`+++` headers + // are noise above the hunks (the first-party viewer hides them too). + if (line.kind == DiffLineKind.meta) continue; + if (remaining <= 0) break; + remaining--; + final (background, foreground) = switch (line.kind) { + DiffLineKind.add => (addBg, addFg), + DiffLineKind.del => (delBg, delFg), + DiffLineKind.hunk => (hunkBg, scheme.primary), + DiffLineKind.meta => (null, theme.hintColor), + DiffLineKind.context => (null, scheme.onSurfaceVariant), + }; + rows.add(Container( + color: background, + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 1), + child: Text( + line.text.isEmpty ? ' ' : line.text, + style: mono.copyWith(color: foreground), + ), + )); + } + } + if (total > maxLines) { + rows.add(Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 5), + child: Text( + '仅显示前 $maxLines 行,共 $total 行', + style: TextStyle(fontSize: 11, color: theme.hintColor), + ), + )); + } + + return Container( + width: double.infinity, + decoration: BoxDecoration( + color: scheme.surfaceContainerHighest, + borderRadius: BorderRadius.circular(8), + ), + clipBehavior: Clip.antiAlias, + child: SelectionArea( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: rows, + ), + ), + ); + } + +} + +/// `+3 −1`, as the row and a multi-file header show it. +class DiffStats extends StatelessWidget { + final int added; + final int removed; + + const DiffStats({super.key, required this.added, required this.removed}); + + @override + Widget build(BuildContext context) { + final dark = Theme.of(context).brightness == Brightness.dark; + final addFg = + dark ? const Color(0xFF86E7A6) : const Color(0xFF116329); + final delFg = + dark ? const Color(0xFFFF9B9B) : const Color(0xFFA40E26); + const style = TextStyle(fontSize: 11, fontFamily: 'monospace'); + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (added > 0) Text('+$added', style: style.copyWith(color: addFg)), + if (added > 0 && removed > 0) const SizedBox(width: 4), + if (removed > 0) + Text('−$removed', style: style.copyWith(color: delFg)), + ], + ); + } +} diff --git a/pubspec.yaml b/pubspec.yaml index 24ac033..7c4cc44 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -2,7 +2,7 @@ name: openchamber description: "A lightweight OpenChamber client for phones." publish_to: 'none' -version: 0.4.11+411 +version: 0.4.12+412 environment: sdk: ^3.14.0 diff --git a/test/diff_view_test.dart b/test/diff_view_test.dart new file mode 100644 index 0000000..df8df3f --- /dev/null +++ b/test/diff_view_test.dart @@ -0,0 +1,129 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:openchamber/api/models.dart'; +import 'package:openchamber/widgets/diff_view.dart'; + +ContentPart editPart({ + String name = 'edit', + Map input = const {}, + Map? metadata, + String status = 'completed', + String? error, +}) { + return ContentPart( + type: 'tool', + name: name, + state: ToolState( + status: status, + input: input, + metadata: metadata, + error: error, + ), + ); +} + +void main() { + test('an edit uses the server patch from metadata.files', () { + final part = editPart( + input: {'path': 'PLAN.md'}, + metadata: { + 'files': [ + { + 'file': 'PLAN.md', + 'patch': '--- PLAN.md\n' + '+++ PLAN.md\n' + '@@ -1,3 +1,4 @@\n' + ' same\n' + '-old line\n' + '+new line\n' + '+added line\n' + ' tail\n', + }, + ], + }, + ); + + final files = toolDiffFiles(part); + expect(files, hasLength(1)); + expect(files.single.path, 'PLAN.md'); + expect(files.single.added, 2); + expect(files.single.removed, 1); + expect(files.single.lines.first.kind, DiffLineKind.meta); + expect( + files.single.lines.where((line) => line.kind == DiffLineKind.hunk), + hasLength(1), + ); + expect( + files.single.lines.map((line) => line.text), + containsAll(['-old line', '+new line', '+added line']), + ); + }); + + test('an edit without a patch is diffed from its old and new text', () { + final part = editPart(input: { + 'path': '/tmp/a.txt', + 'oldString': 'one\ntwo', + 'newString': 'one\ntwo\nthree', + }); + + final files = toolDiffFiles(part); + expect(files, hasLength(1)); + expect(files.single.added, 1); + expect(files.single.removed, 0); + expect(files.single.lines.last.text, '+three'); + }); + + test('a new write without a patch shows its content as added lines', () { + final part = editPart( + name: 'write', + input: {'path': 'hello.txt', 'content': 'hello\nworld'}, + ); + + final files = toolDiffFiles(part); + expect(files, hasLength(1)); + expect(files.single.added, 2); + expect(files.single.removed, 0); + expect(files.single.lines.map((line) => line.text), + ['+hello', '+world']); + }); + + test('a failed tool and a non-diff tool have no diff', () { + expect( + toolDiffFiles(editPart( + metadata: { + 'files': [ + {'file': 'a', 'patch': '@@ -1 +1 @@\n-a\n+b\n'}, + ], + }, + error: 'file not found', + )), + isEmpty, + ); + expect( + toolDiffFiles(editPart(name: 'bash', input: {'command': 'ls'})), + isEmpty, + ); + }); + + testWidgets('the diff view tints added and removed lines', (tester) async { + final files = toolDiffFiles(editPart( + metadata: { + 'files': [ + { + 'file': 'a.txt', + 'patch': '@@ -1,2 +1,2 @@\n old\n-removed\n+added\n', + }, + ], + }, + )); + + await tester.pumpWidget(MaterialApp( + home: Scaffold(body: DiffView(files: files)), + )); + + expect(find.text('@@ -1,2 +1,2 @@'), findsOneWidget); + expect(find.text(' old'), findsOneWidget); + expect(find.text('-removed'), findsOneWidget); + expect(find.text('+added'), findsOneWidget); + }); +}