Show a chat turn's changed files as a chip that opens its diff

The answer footer shows '3 files changed +9 -2'; tapping opens the turn's
files in the sheet (wide) or a full-screen page (narrow), and a file opens
the run Changes diff viewer. Patches load through the chat's own gateway.
This commit is contained in:
2026-11-09 16:08:35 +00:00
parent 0696ab849a
commit 3374bea2ef
15 changed files with 1155 additions and 36 deletions
+3 -1
View File
@@ -11,7 +11,9 @@ export 'domain/change_wording.dart';
export 'domain/file_change.dart';
export 'domain/run_changes.dart';
export 'domain/unified_patch.dart';
export 'widgets/change_style.dart' show DiffForm, hostTextTheme, usesCupertino;
export 'widgets/capture_section.dart' show ChangeFileRow;
export 'widgets/change_style.dart'
show ChangeStatText, DiffForm, hostTextTheme, usesCupertino;
export 'widgets/changes_viewer.dart';
export 'widgets/file_diff_viewer.dart';
export 'widgets/patch_view.dart';
@@ -7,6 +7,7 @@ import '../data/chat_repository.dart';
import '../domain/chat_account_usage.dart';
import '../domain/chat_sessions.dart';
import '../domain/chat_transcript.dart';
import '../domain/chat_turn_diffs.dart';
import 'chat_server_queue.dart';
import 'chat_thread_cards.dart';
import 'chat_transcript_cache.dart';
@@ -60,6 +61,13 @@ class ChatThreadController extends ChangeNotifier {
final _transcriptChanges = ChangeNotifier();
final ChatServerQueue _queue = ChatServerQueue();
/// The per-turn change summaries the transcript's change chips show.
final ChatTurnDiffs turnDiffs = ChatTurnDiffs();
/// Fetches one turn's recorded changes through this chat's own gateway.
Future<JsonMap> turnDiff(String turnId) =>
_repository.turnDiff(sessionId, turnId);
/// Told about every queue body the server sends (the subscribe reply's and
/// each `chat_queue` frame), so delivery states follow the server.
void Function(JsonMap queue)? onQueue;
@@ -208,6 +216,7 @@ class ChatThreadController extends ChangeNotifier {
limit: 200,
);
if (!_owned(token)) return;
turnDiffs.apply(page['turnDiffs'], sessionId);
final merged = mergeChatHistory(
{'messages': _messages},
page,
@@ -260,6 +269,7 @@ class ChatThreadController extends ChangeNotifier {
try {
final page = await _repository.history(sessionId, limit: 200);
if (!_owned(token)) return;
turnDiffs.apply(page['turnDiffs'], sessionId);
if (replaceHeldTurn) {
_messages = (page['messages'] as List? ?? const [])
.whereType<Map>()
@@ -336,6 +346,10 @@ class ChatThreadController extends ChangeNotifier {
_applyQueue(envelope['chat_queue']);
return;
}
if (envelope['type'] == 'chat_turn_diffs') {
if (turnDiffs.apply(envelope['chat_turn_diffs'], sessionId)) _notify();
return;
}
if (envelope['type'] == 'chat_permission') {
final permission = envelope['chat_permission'];
if (permission is! Map) return;
@@ -15,6 +15,7 @@ import '../domain/chat_notice.dart';
import '../domain/chat_attachment_picker.dart';
import '../domain/chat_colors.dart';
import '../domain/chat_transcript.dart';
import '../domain/chat_turn_diffs.dart';
import '../ui/sessions/chat_adaptive.dart';
import '../ui/sessions/chat_color_picker.dart';
import '../ui/sessions/session_actions.dart';
@@ -24,6 +25,7 @@ import '../ui/transcript/chat_message_view.dart';
import '../ui/transcript/chat_transcript_selection.dart';
import '../ui/transcript/chat_injected_rows.dart';
import '../ui/transcript/chat_task_notices_group.dart';
import '../ui/transcript/chat_turn_diff_chip.dart';
import '../../artifacts/actions/artifact_file_bridge.dart';
import '../domain/chat_session_handoff.dart';
import 'chat_account_usage_section.dart';
@@ -977,24 +979,28 @@ class _ChatThreadViewState extends State<ChatThreadView> {
);
// Answered approvals and questions fold into their turn's chips, like
// tool calls; only cards still waiting on the operator stay full cards.
final allRows = groupSettledQuestions(
groupSettledPermissions(
transcriptRows(
messages,
trailing: cards,
running:
_controller.running &&
!_reconnecting &&
!_staleTranscript &&
!cards.any(chatCardAwaitingOperator),
awaitingResponse:
_controller.awaitingResponse &&
!_reconnecting &&
!_staleTranscript &&
!cards.any(chatCardAwaitingOperator),
liveMessageId: _controller.liveAssistantMessageId,
// A turn that changed files carries its summary for the change chip.
final allRows = attachChatTurnDiffs(
groupSettledQuestions(
groupSettledPermissions(
transcriptRows(
messages,
trailing: cards,
running:
_controller.running &&
!_reconnecting &&
!_staleTranscript &&
!cards.any(chatCardAwaitingOperator),
awaitingResponse:
_controller.awaitingResponse &&
!_reconnecting &&
!_staleTranscript &&
!cards.any(chatCardAwaitingOperator),
liveMessageId: _controller.liveAssistantMessageId,
),
),
),
_controller.turnDiffs,
);
// A transcript held from before a socket gap may still say a compaction is
// running even when the repair's read is refused. That running state is
@@ -1454,6 +1460,11 @@ class _ChatThreadViewState extends State<ChatThreadView> {
if (permissions is List<ChatPermissionCardData> && permissions.isNotEmpty)
ChatPermissionsChip(permissions: permissions),
...chatQuestionChips(row),
if (row['turnDiff'] case final Map diff)
ChatTurnDiffChip(
summary: Map<String, dynamic>.from(diff),
load: () => _controller.turnDiff('${diff['turn_id']}'),
),
];
if (kind == 'permissions') {
return Align(
@@ -89,9 +89,10 @@ class ChatRepository {
}))['chat_shells'],
);
Future<JsonMap> automations(String sessionId) => gateway.call('chat_automations', {
'chat_query': {'session_id': sessionId},
});
Future<JsonMap> automations(String sessionId) =>
gateway.call('chat_automations', {
'chat_query': {'session_id': sessionId},
});
Future<List<String>> directories() async {
final value = (await gateway.call('chat_directories'))['chat_directories'];
if (value is! List) {
@@ -139,20 +140,37 @@ class ChatRepository {
'chat_query': {'session_id': sessionId, 'limit': limit, 'cursor': cursor},
});
final page = reply['chat_history'];
// The session's recorded per-turn changes ride with its history.
final turnDiffs = reply['chat_turn_diffs'];
if (page is Map) {
return {
'messages': _maps(page['messages']),
'nextCursor': '${page['next_cursor'] ?? ''}',
'hasMore': page['has_more'] == true,
'turnDiffs': ?turnDiffs,
};
}
return {
'messages': _maps(reply['chat_messages']),
'nextCursor': '',
'hasMore': false,
'turnDiffs': ?turnDiffs,
};
}
/// One turn's recorded file changes: the `chat_turn_diff` body with its
/// `summary` and `changes` (a `file_changes`-shaped capture).
Future<JsonMap> turnDiff(String sessionId, String turnId) async {
final reply = await gateway.call('chat_turn_diff', {
'chat_turn_diff': {'session_id': sessionId, 'turn_id': turnId},
});
final body = reply['chat_turn_diff'];
if (body is! Map || body['changes'] is! Map) {
throw StateError('The server returned no changes for this turn.');
}
return Map<String, dynamic>.from(body);
}
Future<JsonMap> subscribe(String sessionId) =>
gateway.call('chat_subscribe', {
'chat_subscribe': {'session_id': sessionId},
@@ -0,0 +1,126 @@
import '../../../core/api_gateway.dart';
import '../../changes/domain/unified_patch.dart';
/// The server's per-turn workspace change summaries for one chat: what the
/// transcript's "N files changed" chip shows. The server sends them with the
/// history (`chat_turn_diffs` on a `chat_messages` reply) and pushes one per
/// finished turn that changed files; the full patches are fetched on demand.
class ChatTurnDiffs {
final Map<String, JsonMap> _byTurn = {};
/// Summaries in the server's order (oldest first).
List<JsonMap> get summaries => List.unmodifiable(_byTurn.values);
bool get isEmpty => _byTurn.isEmpty;
/// Folds a `chat_turn_diffs` body for [sessionId]; true when it changed
/// anything. A body for another session, or without turns, is ignored.
bool apply(Object? body, String sessionId) {
if (body is! Map || '${body['session_id'] ?? ''}' != sessionId) {
return false;
}
final turns = body['turn_diffs'];
if (turns is! List) return false;
var changed = false;
for (final value in turns) {
if (value is! Map) continue;
final summary = Map<String, dynamic>.from(value);
final id = '${summary['turn_id'] ?? ''}'.trim();
if (id.isEmpty || chatTurnDiffFiles(summary) <= 0) continue;
_byTurn[id] = summary;
changed = true;
}
return changed;
}
}
/// Attaches each summary to the assistant row it belongs to as `turnDiff`.
/// A row holding one of the turn's streamed message ids wins; otherwise the
/// first assistant row created inside the turn's recorded time span. A
/// summary that matches no held row draws nothing (it may belong to a page
/// not loaded yet), and each summary attaches to at most one row.
List<JsonMap> attachChatTurnDiffs(List<JsonMap> rows, ChatTurnDiffs diffs) {
if (diffs.isEmpty) return rows;
final assigned = <int, JsonMap>{};
for (final summary in diffs.summaries) {
final index = _rowFor(rows, summary, assigned);
if (index != null) assigned[index] = summary;
}
if (assigned.isEmpty) return rows;
return [
for (var i = 0; i < rows.length; i++)
if (assigned[i] case final summary?)
{...rows[i], 'turnDiff': summary}
else
rows[i],
];
}
int? _rowFor(List<JsonMap> rows, JsonMap summary, Map<int, JsonMap> taken) {
final ids = {
for (final id in summary['message_ids'] as List? ?? const []) '$id',
};
if (ids.isNotEmpty) {
for (var i = 0; i < rows.length; i++) {
if (rows[i]['kind'] != 'assistant' || taken.containsKey(i)) continue;
final held = rows[i]['messageIds'] as List? ?? const [];
if (held.any((id) => ids.contains('$id'))) return i;
}
}
final started = summary['started_at'], ended = summary['ended_at'];
if (started is! num || ended is! num || started <= 0) return null;
for (var i = 0; i < rows.length; i++) {
if (rows[i]['kind'] != 'assistant' || taken.containsKey(i)) continue;
final created = rows[i]['created_at'];
if (created is num && created >= started && created <= ended) return i;
}
return null;
}
int chatTurnDiffFiles(JsonMap summary) => _count(summary['files']);
int chatTurnDiffAdditions(JsonMap summary) => _count(summary['additions']);
int chatTurnDiffDeletions(JsonMap summary) => _count(summary['deletions']);
bool chatTurnDiffTruncated(JsonMap summary) => summary['truncated'] == true;
/// The chip's label, e.g. `3 files changed +42 −7`.
String chatTurnDiffLabel(JsonMap summary) {
final files = chatTurnDiffFiles(summary);
return '${files == 1 ? '1 file' : '$files files'} changed '
'+${chatTurnDiffAdditions(summary)} '
'−${chatTurnDiffDeletions(summary)}';
}
/// The viewer's heading in the run Changes stat form, e.g.
/// `3 files changed +42 -7`; a zero count is left out, as there.
String chatTurnDiffHeading(JsonMap summary) {
final files = chatTurnDiffFiles(summary);
final stat = changeStat(
chatTurnDiffAdditions(summary),
chatTurnDiffDeletions(summary),
);
return '${files == 1 ? '1 file' : '$files files'} changed'
'${stat.isEmpty ? '' : ' $stat'}';
}
/// The chip's accessible name: the counts in words, and that it opens.
String chatTurnDiffSemantics(JsonMap summary) {
final files = chatTurnDiffFiles(summary);
final added = chatTurnDiffAdditions(summary);
final removed = chatTurnDiffDeletions(summary);
return '${files == 1 ? '1 file' : '$files files'} changed, '
'$added ${added == 1 ? 'line' : 'lines'} added, '
'$removed ${removed == 1 ? 'line' : 'lines'} removed'
'${chatTurnDiffTruncated(summary) ? ', partly shown' : ''}'
', open changes';
}
/// The note shown above a truncated turn's files.
String chatTurnDiffTruncationNote(String diagnostic) {
final detail = diagnostic.trim();
return detail.isEmpty
? 'Some changes exceeded the capture limits, so this is not the '
'complete diff.'
: detail;
}
int _count(Object? value) => value is num ? value.toInt() : 0;
@@ -13,16 +13,22 @@ class ChatTurnChip extends StatelessWidget {
required this.label,
required this.color,
required this.semanticsLabel,
required this.sheet,
this.sheet,
this.open,
this.ellipsizeLabel = false,
});
}) : assert(sheet != null || open != null);
final Key chipKey;
final Widget leading;
final String label;
final Color color;
final String semanticsLabel;
final Widget sheet;
/// The native sheet the chip opens, unless [open] presents it instead.
final Widget? sheet;
/// A custom presentation (a full-screen route on a narrow window).
final Future<void> Function(BuildContext context, bool cupertino)? open;
/// Shrink a long label to one ellipsized line. Only for a chip whose parent
/// bounds its width (a turn footer's Wrap, an aligned row).
@@ -89,18 +95,29 @@ class ChatTurnChip extends StatelessWidget {
);
Future<void> _open(BuildContext context, bool cupertino) {
if (cupertino) {
return showCupertinoModalPopup<void>(
context: context,
builder: (_) => CupertinoPopupSurface(child: SafeArea(child: sheet)),
);
}
return showModalBottomSheet<void>(
context: context,
isScrollControlled: true,
showDragHandle: true,
useSafeArea: true,
builder: (_) => sheet,
);
if (open case final open?) return open(context, cupertino);
return showChatTurnSheet(context, cupertino, sheet!);
}
}
/// The native sheet a turn chip opens: a Cupertino popup surface or a
/// Material modal bottom sheet.
Future<void> showChatTurnSheet(
BuildContext context,
bool cupertino,
Widget sheet,
) {
if (cupertino) {
return showCupertinoModalPopup<void>(
context: context,
builder: (_) => CupertinoPopupSurface(child: SafeArea(child: sheet)),
);
}
return showModalBottomSheet<void>(
context: context,
isScrollControlled: true,
showDragHandle: true,
useSafeArea: true,
builder: (_) => sheet,
);
}
@@ -0,0 +1,76 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../../core/api_gateway.dart';
import '../../../../shell/list_detail_policy.dart';
import '../../domain/chat_turn_diffs.dart';
import '../sessions/chat_adaptive.dart';
import 'chat_turn_chip.dart';
import 'chat_turn_diff_view.dart';
/// A turn's workspace changes below its answer, in the tool chip's family:
/// `3 files changed +42 −7`. A wide window opens the files in the turn sheet;
/// a narrow one opens them as a full-screen page. No diff text is inline.
class ChatTurnDiffChip extends StatelessWidget {
const ChatTurnDiffChip({
super.key,
required this.summary,
required this.load,
});
final JsonMap summary;
/// Fetches the turn's `chat_turn_diff` body through the chat's gateway.
final Future<JsonMap> Function() load;
@override
Widget build(BuildContext context) {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final color = cupertino
? CupertinoColors.secondaryLabel.resolveFrom(context)
: Theme.of(context).colorScheme.onSurfaceVariant;
return ChatTurnChip(
chipKey: const Key('chat-turn-diff-chip'),
leading: Icon(
cupertino ? CupertinoIcons.doc_text : Icons.difference_outlined,
size: 14,
color: color,
),
label: chatTurnDiffLabel(summary),
color: color,
semanticsLabel: chatTurnDiffSemantics(summary),
ellipsizeLabel: true,
open: _open,
);
}
Future<void> _open(BuildContext context, bool cupertino) {
if (MediaQuery.sizeOf(context).width >= kListDetailMinWidth) {
return showChatTurnSheet(
context,
cupertino,
ChatTurnDiffView(summary: summary, load: load),
);
}
final view = ChatTurnDiffView(summary: summary, load: load, inSheet: false);
const title = Text('Turn changes');
return Navigator.of(context).push<void>(
cupertino
? CupertinoPageRoute<void>(
fullscreenDialog: true,
builder: (_) => CupertinoPageScaffold(
navigationBar: const CupertinoNavigationBar(middle: title),
child: SafeArea(child: view),
),
)
: MaterialPageRoute<void>(
fullscreenDialog: true,
builder: (_) => Scaffold(
appBar: AppBar(title: title),
body: SafeArea(child: view),
),
),
);
}
}
@@ -0,0 +1,154 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../../core/api_gateway.dart';
import '../../../changes/changes.dart';
import '../../domain/chat_turn_diffs.dart';
import '../sessions/chat_adaptive.dart';
/// One chat turn's recorded file changes: the counts, an honest note when the
/// capture was partial or truncated, and one row per file that opens the
/// app's file diff viewer. It reads the changes through [load] (the chat's own
/// gateway) when it opens; the transcript never holds the patches.
class ChatTurnDiffView extends StatefulWidget {
const ChatTurnDiffView({
super.key,
required this.summary,
required this.load,
this.inSheet = true,
});
final JsonMap summary;
final Future<JsonMap> Function() load;
/// In a sheet the list shrinks to its content under a height bound; on a
/// full-screen page it fills the body.
final bool inSheet;
@override
State<ChatTurnDiffView> createState() => _ChatTurnDiffViewState();
}
class _ChatTurnDiffViewState extends State<ChatTurnDiffView> {
late Future<JsonMap> _reply = widget.load();
void _retry() {
final next = widget.load();
setState(() {
_reply = next;
});
}
@override
Widget build(BuildContext context) {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final style = cupertino
? CupertinoTheme.of(context).textTheme.textStyle
: Theme.of(context).textTheme.bodyMedium;
final list = FutureBuilder<JsonMap>(
future: _reply,
builder: (context, snapshot) {
final children = <Widget>[
Padding(
padding: const EdgeInsets.only(bottom: 4),
// The run Changes stat form (+N -M), so it is coloured alike.
child: ChangeStatText(
chatTurnDiffHeading(widget.summary),
style: const TextStyle(fontWeight: FontWeight.w600),
),
),
..._body(context, snapshot, cupertino),
];
return ListView(
key: const Key('chat-turn-diff-list'),
shrinkWrap: widget.inSheet,
padding: const EdgeInsets.fromLTRB(16, 8, 16, 16),
children: children,
);
},
);
// File rows may be Material list tiles inside a Cupertino surface.
final content = Material(
type: MaterialType.transparency,
child: DefaultTextStyle.merge(style: style, child: list),
);
if (!widget.inSheet) return content;
return ConstrainedBox(
constraints: BoxConstraints(
maxHeight: MediaQuery.sizeOf(context).height * 0.8,
),
child: content,
);
}
List<Widget> _body(
BuildContext context,
AsyncSnapshot<JsonMap> snapshot,
bool cupertino,
) {
if (snapshot.connectionState != ConnectionState.done) {
return [
Padding(
padding: const EdgeInsets.all(16),
child: Center(
child: cupertino
? const CupertinoActivityIndicator()
: const CircularProgressIndicator(),
),
),
];
}
if (snapshot.hasError) {
return [
Text('Could not load the changes: ${snapshot.error}'),
Align(
alignment: AlignmentDirectional.centerStart,
child: cupertino
? CupertinoButton(onPressed: _retry, child: const Text('Retry'))
: TextButton(onPressed: _retry, child: const Text('Retry')),
),
];
}
final changes = snapshot.data!['changes'];
final capture = ChangeCapture.fromJson(
Map<String, dynamic>.from(changes as Map),
);
final truncated =
chatTurnDiffTruncated(widget.summary) ||
!capture.complete ||
capture.omitted > 0;
return [
if (truncated)
Padding(
key: const Key('chat-turn-diff-truncated'),
padding: const EdgeInsets.only(bottom: 8),
child: Text(
chatTurnDiffTruncationNote(capture.diagnostic),
style: TextStyle(
fontSize: 13,
color: cupertino
? CupertinoColors.secondaryLabel.resolveFrom(context)
: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
),
for (final file in capture.files)
ChangeFileRow(
key: ValueKey<String>('chat-turn-diff-file-${file.path}'),
file: file,
onOpen: (file) =>
showFileDiffViewer(context, file, files: capture.files),
),
if (capture.omitted > 0)
Padding(
padding: const EdgeInsets.only(top: 8),
child: Text(
'${capture.omitted} more '
'${capture.omitted == 1 ? 'file was' : 'files were'} '
'omitted by the size limit.',
),
),
];
}
}
+101
View File
@@ -0,0 +1,101 @@
# Chat per-turn diffs
User request: show per-turn diffs as a compact chip like the tool count, which
opens the actual diff, never raw diff text in the transcript.
## Behaviour
- Server (`internal/server/chat_turn_diff.go`): for every harness, the chat hub
snapshots the chat's recorded directory (`operator_sessions.directory`) at
turn start and compares it at turn end with `internal/filediff`
(`Capture`/`Compare`, the stage-visit capture). A turn the room prompts is
captured synchronously before the prompt is posted; a turn the stream
announces (non-intermediate `step started`, e.g. CLI-originated) is captured
from that frame. The end is the authoritative `step ended` frame. The next
turn's baseline waits for the previous turn's end snapshot.
- Git working trees use filediff's Git path (clean files kept as blob ids and
recovered from Git); other directories use filediff's workspace walk. An
unreadable directory or unavailable capture records nothing (no chip).
- A turn with no changed file records nothing. A changed turn is stored in
`chat_turn_diffs` (SQLite, newest 100 per session, pruned on insert) and
pushed to the chat's watchers as `chat_turn_diffs`.
- Protocol (`internal/protocol/chat_turn_diff.go`):
- `chat_turn_diffs` body `{session_id, turn_diffs: [summary]}`: pushed per
finished turn and attached to every `chat_messages` reply (survives reload
and server restart).
- summary: `turn_id, message_ids (≤16 assistant ids streamed in the turn),
started_at, ended_at (ms), files, additions, deletions, truncated, status,
diagnostic`.
- `chat_turn_diff {session_id, turn_id}` → reply `chat_turn_diff` with
`summary` and `changes` (the `file_changes` shape: per-file patches).
- App: `ChatThreadController.turnDiffs` folds history and pushes for its own
session; `attachChatTurnDiffs` puts a summary on the assistant row holding
one of its message ids (fallback: the first assistant row created inside
the turn's time span). The row footer shows `ChatTurnDiffChip`
("3 files changed +9 −2", accessible label "3 files changed, 9 lines added,
2 lines removed, partly shown, open changes"). Tap: wide window (≥600) opens
the turn sheet (Material bottom sheet / Cupertino popup, like the tool
chip); narrow opens a full-screen "Turn changes" route. The viewer lists
files with `ChangeFileRow`; a file opens the run Changes `FileDiffPage`
(rendered/raw patch, copy, previous/next file). Patches are fetched on open
through the chat's own gateway, so multi-machine chats go to their machine
(`ChatServerGateway` re-keys `session_id` both ways).
## Limits
- Bounds are filediff's: 1 MiB per text file, 32 MiB retained text per
snapshot, 5,000 lines per comparison, 64 KiB per patch, 128 KiB per turn,
10,000 files, 20 s per snapshot. Over-limit files are listed without a patch
with a reason; the summary is `truncated` and the viewer shows the capture's
diagnostic above the files.
- Protected paths (`.git`, `.env*`, keys, `node_modules`, databases …) and
symlinks are never read.
- The diff is observed change in the chat's directory during the turn, not
authorship: another process (a run, another chat) editing the same
directory at the same time shows up too.
- Turns the hub does not observe (no room: nobody watching and nothing
unattended) are not captured. A room released mid-turn drops its baseline.
- Codex `turn/diff/updated` is not used; the generic snapshot covers it.
## Verification (2026-11-09)
```
go test ./internal/server ./internal/pipeline ./internal/protocol ./internal/filediff -count=1
ok git.a-wan.net/alan/pipelines/internal/server 66.283s
ok git.a-wan.net/alan/pipelines/internal/pipeline 7.208s
ok git.a-wan.net/alan/pipelines/internal/protocol 0.203s
ok git.a-wan.net/alan/pipelines/internal/filediff 5.752s
go test ./internal/server -run TestChatTurnDiff -v
--- PASS: TestChatTurnDiffRecordsGitWorkspaceChanges
--- PASS: TestChatTurnDiffNonGitDirectoryUsesWorkspaceSnapshot
--- PASS: TestChatTurnDiffRecordsNothingWithoutChanges
--- PASS: TestChatTurnDiffMarksBoundedPatchesTruncated
--- PASS: TestChatTurnDiffCapturesStreamAnnouncedTurn
--- PASS: TestChatTurnDiffPatchLineCounts
--- PASS: TestChatTurnDiffProtocolRoundTrip
tool/memwatch/full.sh test/features/chat
memwatch: PASS: 1075 passed, 0 failed, 0 skipped; peak 2233 MB; 148s; exit 0 (test/features/chat)
tool/memwatch/full.sh test/core/servers
memwatch: PASS: 50 passed, 0 failed, 0 skipped; peak 1509 MB; 11s; exit 0 (test/core/servers)
tool/memwatch/full.sh test/features/changes
memwatch: PASS: 73 passed, 0 failed, 0 skipped; peak 1710 MB; 12s; exit 0 (test/features/changes)
tool/analyze.sh lib test tool
analyze: clean; 11s; exit 0
tool/analyze.sh
analyze: 0 errors, 8 warnings, 0 infos; 7s; exit 1
```
The 8 whole-app warnings are all `invalid_null_aware_operator` in
`integration_test/discovery_probe_test.dart`, a file this change does not touch.
Browser captures (fixture `tool/search_selection_probe_entry.dart` with
`--params 'chats=1&turndiffs=1'`, `open=/chat/perf-chat-0`, click chip, click
`lib/search/search_box.dart`), Material and Cupertino at 1100x900 and 560x1000:
`/tmp/turn-diff-shots/<platform>-<size>/{01-chip,02-viewer,03-file-diff}.png`.
Inspected: the chip sits in the answer footer beside Copy; the wide viewer is
the turn sheet with the truncation note and three file rows; the narrow viewer
is a full-screen "Turn changes" page; a file opens the rendered patch with
"1 of 3" paging. Not verified: a live harness turn against a real server, and
any device.
@@ -0,0 +1,73 @@
import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/core/servers/chat/chat_identity.dart';
import 'package:pipelines_app/core/servers/chat/chat_server_gateway.dart';
import 'package:pipelines_app/core/servers/chat/federated_chat_gateway.dart';
import 'package:pipelines_app/core/servers/server_catalog.dart';
class _Machine implements ApiGateway {
final events = StreamController<JsonMap>.broadcast();
final calls = <(String, JsonMap)>[];
@override
Stream<JsonMap> get frames => events.stream;
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
calls.add((type, fields));
return {
'type': type,
'chat_turn_diff': {
'session_id': 'native',
'turn_id': 'turn_1',
'changes': {'status': 'complete', 'files': <JsonMap>[]},
},
'chat_turn_diffs': {'session_id': 'native', 'turn_diffs': <JsonMap>[]},
};
}
}
SavedServer _server(String id) => SavedServer.validated(
id: id,
name: 'Machine $id',
endpoints: ['ws://$id.test/connect'],
);
void main() {
test(
'turn diffs go to the chat\'s own machine and come back namespaced',
() async {
final a = _Machine(), b = _Machine();
final sources = {
'a': ChatServerGateway(_server('a'), a),
'b': ChatServerGateway(_server('b'), b),
};
final all = FederatedChatGateway(
() => sources,
() => 'a',
const Stream.empty(),
);
final remote = federatedChatId('b', 'native');
final reply = await all.call('chat_turn_diff', {
'chat_turn_diff': {'session_id': remote, 'turn_id': 'turn_1'},
});
expect(a.calls, isEmpty);
expect(b.calls.single.$2['chat_turn_diff'], {
'session_id': 'native',
'turn_id': 'turn_1',
});
expect((reply['chat_turn_diff'] as Map)['session_id'], remote);
expect((reply['chat_turn_diffs'] as Map)['session_id'], remote);
// A pushed summary list is re-keyed to the machine's namespaced id.
final pushed = sources['b']!.frames.first;
b.events.add({
'type': 'chat_turn_diffs',
'chat_turn_diffs': {'session_id': 'native', 'turn_diffs': <JsonMap>[]},
});
expect(((await pushed)['chat_turn_diffs'] as Map)['session_id'], remote);
await a.events.close();
await b.events.close();
},
);
}
@@ -0,0 +1,127 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart';
import 'chat_thread_fixtures.dart';
/// Answers chat_turn_diff with one recorded file for the asked turn.
class _DiffGateway extends FakeChatGateway {
final asked = <JsonMap>[];
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
if (type != 'chat_turn_diff') return super.call(type, fields);
final body = Map<String, dynamic>.from(fields['chat_turn_diff'] as Map);
asked.add(body);
return {
'type': 'chat_turn_diff',
'chat_turn_diff': {
...body,
'changes': {
'status': 'complete',
'files': [
{
'path': 'lib/${body['turn_id']}.dart',
'kind': 'added',
'patch': '@@ -0,0 +1 @@\n+x\n',
},
],
},
},
};
}
}
JsonMap _summary(String turn, String message) => {
'turn_id': turn,
'message_ids': [message],
'files': 1,
'additions': 1,
'deletions': 0,
'status': 'complete',
};
void main() {
testWidgets('history and live summaries draw a change chip per turn; the '
'chip fetches that turn through the chat gateway', (tester) async {
final gateway = _DiffGateway();
addTearDown(gateway.close);
gateway.history = (_) async => {
...chatPage([
chatMessage(
'u1',
'user',
parts: [
{'type': 'text', 'text': 'Edit it'},
],
),
chatMessage(
'a1',
'assistant',
parts: [
{'type': 'text', 'text': 'Edited.'},
],
),
chatMessage(
'u2',
'user',
parts: [
{'type': 'text', 'text': 'Again'},
],
),
chatMessage(
'a2',
'assistant',
parts: [
{'type': 'text', 'text': 'Edited again.'},
],
),
]),
'chat_turn_diffs': {
'session_id': 's',
'turn_diffs': [_summary('turn_a', 'a1')],
},
};
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(platform: TargetPlatform.android),
home: Scaffold(
body: ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}),
),
),
);
await tester.pumpAndSettle();
final chips = find.byKey(const Key('chat-turn-diff-chip'));
expect(chips, findsOneWidget);
expect(find.text('1 file changed +1 −0'), findsOneWidget);
// Another session's push is ignored; this session's push adds a chip.
gateway.emitRaw({
'type': 'chat_turn_diffs',
'chat_turn_diffs': {
'session_id': 'other',
'turn_diffs': [_summary('turn_x', 'a2')],
},
});
await tester.pumpAndSettle();
expect(chips, findsOneWidget);
gateway.emitRaw({
'type': 'chat_turn_diffs',
'chat_turn_diffs': {
'session_id': 's',
'turn_diffs': [_summary('turn_b', 'a2')],
},
});
await tester.pumpAndSettle();
expect(chips, findsNWidgets(2));
await tester.tap(chips.last);
await tester.pumpAndSettle();
expect(gateway.asked, [
{'session_id': 's', 'turn_id': 'turn_b'},
]);
expect(find.text('lib/turn_b.dart'), findsOneWidget);
expect(tester.takeException(), isNull);
});
}
@@ -0,0 +1,91 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/chat/domain/chat_turn_diffs.dart';
void main() {
test('summaries apply only for their session and attach by message id', () {
final diffs = ChatTurnDiffs();
expect(
diffs.apply({
'session_id': 'other',
'turn_diffs': [
{'turn_id': 't0', 'files': 1},
],
}, 'ses_1'),
isFalse,
);
expect(
diffs.apply({
'session_id': 'ses_1',
'turn_diffs': [
{
'turn_id': 't1',
'message_ids': ['m2'],
'files': 1,
'additions': 3,
'deletions': 1,
},
{'turn_id': 'empty', 'files': 0},
],
}, 'ses_1'),
isTrue,
);
final rows = [
{
'kind': 'assistant',
'messageIds': ['m1'],
},
{'kind': 'user'},
{
'kind': 'assistant',
'messageIds': ['m2', 'm3'],
},
];
final attached = attachChatTurnDiffs(rows, diffs);
expect(attached[0].containsKey('turnDiff'), isFalse);
expect((attached[2]['turnDiff'] as Map)['turn_id'], 't1');
expect(diffs.summaries, hasLength(1));
expect(chatTurnDiffLabel(diffs.summaries.single), '1 file changed +3 −1');
});
test('a summary without a held message id falls back to its time span', () {
final diffs = ChatTurnDiffs()
..apply({
'session_id': 's',
'turn_diffs': [
{
'turn_id': 't',
'message_ids': ['gone'],
'started_at': 1000,
'ended_at': 2000,
'files': 2,
},
],
}, 's');
final rows = [
{
'kind': 'assistant',
'messageIds': ['a'],
'created_at': 500,
},
{
'kind': 'assistant',
'messageIds': ['b'],
'created_at': 1500,
},
];
final attached = attachChatTurnDiffs(rows, diffs);
expect(attached[0].containsKey('turnDiff'), isFalse);
expect(attached[1].containsKey('turnDiff'), isTrue);
// A summary for a turn not held at all draws nothing.
expect(
attachChatTurnDiffs([
{
'kind': 'assistant',
'messageIds': ['x'],
'created_at': 9000,
},
], diffs).single.containsKey('turnDiff'),
isFalse,
);
});
}
@@ -0,0 +1,213 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/chat/ui/transcript/chat_message_view.dart';
import 'package:pipelines_app/features/chat/ui/transcript/chat_turn_diff_chip.dart';
const _patch =
'--- "a/lib/a.dart"\n+++ "b/lib/a.dart"\n@@ -1,2 +1,2 @@\n-old\n+new\n same\n';
JsonMap _summary({bool truncated = false}) => {
'turn_id': 'turn_1',
'message_ids': ['a1'],
'files': 2,
'additions': 42,
'deletions': 7,
'status': truncated ? 'partial' : 'complete',
if (truncated) 'truncated': true,
};
JsonMap _reply({bool truncated = false}) => {
'session_id': 'ses_1',
'turn_id': 'turn_1',
'summary': _summary(truncated: truncated),
'changes': {
'status': truncated ? 'partial' : 'complete',
if (truncated)
'diagnostic': 'Some patches were omitted/truncated by capture limits.',
'files': [
{'path': 'lib/a.dart', 'kind': 'modified', 'patch': _patch},
{
'path': 'big.txt',
'kind': 'added',
if (truncated) 'truncated': true,
if (truncated) 'no_patch': true,
if (truncated) 'no_patch_reason': 'lines',
},
],
'skipped': 0,
},
};
Widget _app(Widget body, bool cupertino, {Size size = const Size(1000, 800)}) {
final media = MediaQueryData(size: size);
final home = MediaQuery(data: media, child: body);
return cupertino
? CupertinoApp(home: CupertinoPageScaffold(child: home))
: MaterialApp(
theme: ThemeData(platform: TargetPlatform.android),
home: Scaffold(body: home),
);
}
final _chip = find.byKey(const Key('chat-turn-diff-chip'));
void main() {
for (final cupertino in [false, true]) {
final host = cupertino ? 'Cupertino' : 'Material';
testWidgets('the chip reads files and line counts, no inline diff '
'($host)', (tester) async {
final row = {
'kind': 'assistant',
'key': 'a1',
'messageIds': ['a1'],
'parts': [
{'type': 'text', 'text': 'Edited the files.'},
],
};
await tester.pumpWidget(
_app(
ListView(
children: [
ChatMessageView(
row: row,
footer: [
ChatTurnDiffChip(
summary: _summary(),
load: () async => _reply(),
),
],
),
],
),
cupertino,
),
);
await tester.pumpAndSettle();
expect(_chip, findsOneWidget);
expect(find.text('2 files changed +42 −7'), findsOneWidget);
expect(
find.bySemanticsLabel(
'2 files changed, 42 lines added, 7 lines removed, open changes',
),
findsOneWidget,
);
expect(find.textContaining('+new'), findsNothing);
});
testWidgets('tapping opens the file list and a file opens its patch '
'($host)', (tester) async {
var loads = 0;
await tester.pumpWidget(
_app(
Center(
child: ChatTurnDiffChip(
summary: _summary(),
load: () async {
loads++;
return _reply();
},
),
),
cupertino,
),
);
await tester.tap(_chip);
await tester.pumpAndSettle();
expect(loads, 1);
expect(find.byKey(const Key('chat-turn-diff-list')), findsOneWidget);
expect(find.text('lib/a.dart'), findsOneWidget);
expect(find.text('big.txt'), findsOneWidget);
expect(find.byKey(const Key('chat-turn-diff-truncated')), findsNothing);
await tester.tap(find.text('lib/a.dart'));
await tester.pumpAndSettle();
expect(
find.byKey(const ValueKey('file-diff-lib/a.dart')),
findsOneWidget,
);
expect(tester.takeException(), isNull);
});
testWidgets('a truncated turn says so and names the file without a patch '
'($host)', (tester) async {
await tester.pumpWidget(
_app(
Center(
child: ChatTurnDiffChip(
summary: _summary(truncated: true),
load: () async => _reply(truncated: true),
),
),
cupertino,
),
);
expect(
find.bySemanticsLabel(
'2 files changed, 42 lines added, 7 lines removed, partly shown, '
'open changes',
),
findsOneWidget,
);
await tester.tap(_chip);
await tester.pumpAndSettle();
expect(find.byKey(const Key('chat-turn-diff-truncated')), findsOneWidget);
expect(
find.text('Some patches were omitted/truncated by capture limits.'),
findsOneWidget,
);
expect(find.textContaining('truncated'), findsWidgets);
});
testWidgets('a narrow window opens the changes full screen ($host)', (
tester,
) async {
tester.view.physicalSize = const Size(400, 800);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
await tester.pumpWidget(
_app(
Center(
child: ChatTurnDiffChip(
summary: _summary(),
load: () async => _reply(),
),
),
cupertino,
size: const Size(400, 800),
),
);
await tester.tap(_chip);
await tester.pumpAndSettle();
expect(find.text('Turn changes'), findsOneWidget);
expect(find.text('lib/a.dart'), findsOneWidget);
});
testWidgets('a failed load reports and retries ($host)', (tester) async {
var fail = true;
await tester.pumpWidget(
_app(
Center(
child: ChatTurnDiffChip(
summary: _summary(),
load: () async {
if (fail) throw StateError('no recorded changes for this turn');
return _reply();
},
),
),
cupertino,
),
);
await tester.tap(_chip);
await tester.pumpAndSettle();
expect(find.textContaining('no recorded changes'), findsOneWidget);
fail = false;
await tester.tap(find.text('Retry'));
await tester.pumpAndSettle();
expect(find.text('lib/a.dart'), findsOneWidget);
});
}
}
+91
View File
@@ -0,0 +1,91 @@
import 'package:pipelines_app/core/api_gateway.dart';
/// `?turndiffs=1`: the bench transcript's last answer (`perf-m19`) changed
/// two files, one of them truncated, so captures can review the transcript's
/// change chip and the turn changes viewer. Fixture data only; it never
/// contacts a server.
const chatTurnDiffFixtureTurn = 'turn_fixture';
JsonMap chatTurnDiffFixtureList(String session) => {
'session_id': session,
'turn_diffs': [
{
'turn_id': chatTurnDiffFixtureTurn,
'message_ids': ['perf-m19'],
'files': 3,
'additions': 9,
'deletions': 2,
'truncated': true,
'status': 'partial',
'diagnostic':
'Some changed files exceeded capture limits and are listed without '
'patches; this is not a complete workspace diff.',
},
],
};
JsonMap chatTurnDiffFixtureReply(Object? id, JsonMap request) {
final body = request['chat_turn_diff'];
final session = body is Map ? '${body['session_id'] ?? ''}' : '';
return {
'id': id,
'type': 'chat_turn_diff',
'chat_turn_diff': {
'session_id': session,
'turn_id': chatTurnDiffFixtureTurn,
'summary': (chatTurnDiffFixtureList(session)['turn_diffs'] as List).first,
'changes': {
'status': 'partial',
'scope': 'Git tracked and nonignored files in the run directory',
'diagnostic':
'Some changed files exceeded capture limits and are listed '
'without patches; this is not a complete workspace diff.',
'skipped': 0,
'files': [
{
'path': 'lib/search/search_box.dart',
'kind': 'modified',
'before_mode': '0644',
'after_mode': '0644',
'patch':
'--- "a/lib/search/search_box.dart"\n'
'+++ "b/lib/search/search_box.dart"\n'
'@@ -10,7 +10,12 @@\n'
' class SearchBox extends StatelessWidget {\n'
'- const SearchBox({super.key});\n'
'+ const SearchBox({super.key, this.onSubmit});\n'
'+\n'
'+ /// Runs the query when the operator presses Enter.\n'
'+ final ValueChanged<String>? onSubmit;\n'
' \n'
' @override\n'
'- Widget build(BuildContext context) => const TextField();\n'
'+ Widget build(BuildContext context) =>\n'
'+ TextField(onSubmitted: onSubmit);\n'
' }\n',
},
{
'path': 'docs/search.md',
'kind': 'added',
'after_mode': '0644',
'patch':
'--- "/dev/null"\n'
'+++ "b/docs/search.md"\n'
'@@ -0,0 +1,3 @@\n'
'+# Search\n'
'+\n'
'+Press Enter to run the query.\n',
},
{
'path': 'assets/fixtures/large.json',
'kind': 'added',
'after_mode': '0644',
'truncated': true,
'no_patch': true,
'no_patch_reason': 'lines',
},
],
},
},
};
}
+5
View File
@@ -21,6 +21,7 @@
import 'package:pipelines_app/core/api_gateway.dart';
import 'chat_new_session_fixture.dart';
import 'chat_turn_diff_fixture.dart';
import 'chat_question_fixture.dart';
import 'chat_scroll_fixture.dart';
@@ -374,7 +375,11 @@ JsonMap? perfChatReply(JsonMap request) {
'next_cursor': '',
'has_more': false,
},
if (_params['turndiffs'] == '1')
'chat_turn_diffs': chatTurnDiffFixtureList(session),
};
case 'chat_turn_diff':
return chatTurnDiffFixtureReply(id, request);
}
return null;
}