// 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'; import '../l10n.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: AppText( file.path ?? trArgs('文件 {0}', [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: AppText( 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: AppText( trArgs('仅显示前 {0} 行,共 {1} 行', [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) AppText('+$added', style: style.copyWith(color: addFg)), if (added > 0 && removed > 0) const SizedBox(width: 4), if (removed > 0) AppText('−$removed', style: style.copyWith(color: delFg)), ], ); } }