feat: show edit and write tools as line diffs

Expanding an edit, write or patch call now renders the change as tinted
diff lines instead of an old/new text blob: added lines green, removed
lines red, @@ hunk headers marked, and file header noise hidden. The
patch comes from the server's metadata.files[].patch; older servers fall
back to a line diff of the edit's old/new strings, and a write with only
content shows as added lines.

The tool row also shows +N −M for these calls, as dsh-Go does, and a
phone-sized preview stops at 600 lines.

0.4.12 (412).
This commit is contained in:
blumia committed 2026-11-23 22:36:05 +08:00
1 parent 0f850b6191
commit d533bc95ef
7 files changed
+541 -6

No files matched your search

+51 -2
View File
@@ -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<ChatScreen> {
? const <_ImageRef>[]
: toolImages(p, chat.dir);
final subagentId = _subagentSessionId(p);
final diffFiles = reasoning ? const <DiffFile>[] : 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<ChatScreen> {
: 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<ChatScreen> {
_Reveal(
open: open,
onGrow: _grow,
child: _stepDetails(p, reasoning),
child: _stepDetails(p, reasoning, diffFiles),
),
],
),
@@ -1057,8 +1073,10 @@ class _ChatScreenState extends State<ChatScreen> {
/// 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<DiffFile> 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<ChatScreen> {
);
}
/// 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<DiffFile> 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 ?? '') {
+1 -1
View File
@@ -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';
+342
View File
@@ -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<DiffLine> 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<dynamic, dynamic> 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<DiffFile> 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 = <DiffFile>[];
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<DiffLine> parseUnifiedDiff(String text) {
final lines = <DiffLine>[];
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<DiffLine> computeLineDiff(String oldText, String newText) {
final a = oldText.isEmpty ? <String>[] : oldText.split('\n');
final b = newText.isEmpty ? <String>[] : 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<int>.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 = <DiffLine>[];
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<DiffFile> 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 = <Widget>[];
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)),
],
);
}
}