feat(app): show a recorded chat activity sequence as one line

Lift recorded activity/compaction parts out of an assistant turn into a
single activity row before the answer. Running kinds use the web's phase
words; terminal records keep the label the server recorded.
This commit is contained in:
2026-10-22 02:33:08 +01:00
parent 8cfc4443df
commit 4a86f0db77
3 changed files with 403 additions and 13 deletions
@@ -254,18 +254,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
Padding(
key: ValueKey<String>(keys[index]),
padding: const EdgeInsets.symmetric(horizontal: 16),
child:
rows[index]['kind'] == 'permission' ||
rows[index]['kind'] == 'question'
? ChatTranscriptCard(
row: rows[index],
onPermissionDecision: _controller.replyPermission,
onQuestionAnswer: _controller.answerQuestion,
)
: ChatMessageView(
row: rows[index],
textBuilder: chatMarkdownText,
),
child: _transcriptRow(rows[index]),
),
if (_controller.running && !awaiting)
Padding(
@@ -289,6 +278,19 @@ class _ChatThreadViewState extends State<ChatThreadView> {
},
);
Widget _transcriptRow(JsonMap row) {
final kind = '${row['kind'] ?? ''}';
if (kind == 'activity') return _ChatActivityLine(row: row);
if (kind == 'permission' || kind == 'question') {
return ChatTranscriptCard(
row: row,
onPermissionDecision: _controller.replyPermission,
onQuestionAnswer: _controller.answerQuestion,
);
}
return ChatMessageView(row: row, textBuilder: chatMarkdownText);
}
Widget _backButton(bool cupertino) => cupertino
? CupertinoButton(
padding: const EdgeInsetsDirectional.fromSTEB(8, 0, 8, 0),
@@ -308,3 +310,69 @@ class _ChatThreadViewState extends State<ChatThreadView> {
label: const Text('Back to chats'),
);
}
/// One recorded activity line for a turn.
///
/// The line is a summary, not a control: expansion belongs to the later overlay
/// slice. Its wording and state come from the recorded row, and the icon only
/// repeats that state with theme roles, so an unknown kind or state is still
/// readable without colour.
class _ChatActivityLine extends StatelessWidget {
const _ChatActivityLine({required this.row});
final JsonMap row;
@override
Widget build(BuildContext context) {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final state = '${row['state'] ?? ''}'.trim().toLowerCase();
final failed = state == 'failed' || state == 'error';
final running = state == 'running';
final completed =
state == 'completed' || state == 'ended' || state == 'succeeded';
final secondary = cupertino
? CupertinoColors.secondaryLabel.resolveFrom(context)
: Theme.of(context).colorScheme.onSurfaceVariant;
final color = failed
? (cupertino
? CupertinoColors.systemRed.resolveFrom(context)
: Theme.of(context).colorScheme.error)
: secondary;
final style =
(cupertino
? CupertinoTheme.of(context).textTheme.textStyle
: Theme.of(context).textTheme.bodySmall)
?.copyWith(color: color);
final icon = failed
? (cupertino
? CupertinoIcons.exclamationmark_circle
: Icons.error_outline)
: running
? (cupertino ? CupertinoIcons.arrow_2_circlepath : Icons.sync)
: completed
? (cupertino
? CupertinoIcons.check_mark_circled
: Icons.check_circle_outline)
: (cupertino ? CupertinoIcons.circle : Icons.circle_outlined);
final label = '${row['label'] ?? ''}'.trim();
return Semantics(
container: true,
label: label,
value: state,
child: ExcludeSemantics(
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 6),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(icon, color: color),
const SizedBox(width: 8),
Expanded(child: Text(label, style: style)),
],
),
),
),
);
}
}
@@ -41,6 +41,12 @@ JsonMap mergeChatHistory(JsonMap previous, JsonMap page, {bool older = false}) {
/// currently holds so the view can keep the same row element while the turn
/// grows at either end.
///
/// A recorded activity sequence is not an answer bubble. Parts whose `type` is
/// `activity` or `compaction` are lifted out of the turn and collapse into one
/// `activity` row before it, carrying the recorded records, the web wording for
/// the latest record and that record's lifecycle state. Several updates of one
/// compaction are therefore one line, never one line per update.
///
/// [trailing] rows are conversation cards (permission requests and questions),
/// not messages. They keep the server's order after the transcript, the way the
/// web renders approvals and forms at the end of the conversation.
@@ -52,7 +58,19 @@ List<JsonMap> transcriptRows(
String? key;
final ids = <String>[];
final parts = <JsonMap>[];
final activity = <JsonMap>[];
String? activityKey;
void flush() {
if (activity.isNotEmpty) {
final latest = activity.last;
rows.add({
'kind': 'activity',
'key': activityKey == null ? '' : 'chat-activity-$activityKey',
'records': List<JsonMap>.of(activity),
'label': chatActivityLabel(latest),
'state': chatActivityState(latest).toLowerCase(),
});
}
if (key != null && parts.isNotEmpty) {
rows.add({
'kind': 'assistant',
@@ -64,6 +82,8 @@ List<JsonMap> transcriptRows(
key = null;
ids.clear();
parts.clear();
activity.clear();
activityKey = null;
}
for (final message in messages) {
@@ -72,7 +92,14 @@ List<JsonMap> transcriptRows(
key ??= id;
if (id.isNotEmpty) ids.add(id);
for (final part in (message['parts'] as List? ?? const [])) {
if (part is Map) parts.add(Map<String, dynamic>.from(part));
if (part is! Map) continue;
final record = Map<String, dynamic>.from(part);
if (chatActivityType(record)) {
activityKey ??= id.isEmpty ? null : id;
activity.add(record);
} else {
parts.add(record);
}
}
} else {
flush();
@@ -84,6 +111,61 @@ List<JsonMap> transcriptRows(
return rows;
}
/// Whether [part] is a recorded activity record rather than answer content.
///
/// Both spellings occur: `compaction` is the native lifecycle record and
/// `activity` is a generic sequence entry whose [chatActivityKind] carries the
/// concrete kind.
bool chatActivityType(JsonMap part) {
final type = '${part['type'] ?? ''}'.trim().toLowerCase();
return type == 'activity' || type == 'compaction';
}
/// The record's kind, or the part type when the record does not name one.
String chatActivityKind(JsonMap record) {
final kind = '${record['kind'] ?? ''}'.trim();
if (kind.isNotEmpty) return kind;
return '${record['type'] ?? ''}'.trim();
}
/// The record's lifecycle state, exactly as recorded (may be blank).
String chatActivityState(JsonMap record) {
for (final field in const ['state', 'status', 'lifecycle']) {
final value = '${record[field] ?? ''}'.trim();
if (value.isNotEmpty) return value;
}
return '';
}
/// The running-phase words shared verbatim with the web's `turnPhaseLabel`.
/// The web clears a compaction on completion/failure, so there is no web copy
/// for a terminal record: those keep the label the server recorded.
const _chatActivityRunningWords = <String, String>{
'compaction': 'Compacting context…',
'thinking': 'Thinking…',
'tool': 'Running a tool…',
'waiting': 'Waiting…',
};
/// The one line for a recorded activity record.
///
/// A running kind with a web phase word uses that exact wording. Otherwise the
/// server's recorded [record] label wins, including for an unknown kind; with
/// no label the recorded kind and state are kept verbatim rather than inventing
/// copy. Nothing is inferred from text the model wrote.
String chatActivityLabel(JsonMap record) {
final kind = chatActivityKind(record);
final state = chatActivityState(record);
if (state.toLowerCase() == 'running') {
final known = _chatActivityRunningWords[kind.toLowerCase()];
if (known != null) return known;
}
final recorded = '${record['label'] ?? ''}'.trim();
if (recorded.isNotEmpty) return recorded;
if (kind.isEmpty) return state.isEmpty ? 'Activity' : state;
return state.isEmpty ? kind : '$kind · $state';
}
/// Replace a local optimistic user row when its server echo identifies the
/// same operation/native message; otherwise append once by authoritative id.
List<JsonMap> reconcileChatUser(List<JsonMap> messages, JsonMap remote) {
@@ -0,0 +1,240 @@
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/conversation/chat_thread_view.dart';
import 'package:pipelines_app/features/chat/domain/chat_transcript.dart';
import 'chat_thread_fixtures.dart';
JsonMap _record({
String type = 'activity',
String? id,
String? kind,
String? state,
String? label,
}) => {
'type': type,
'id': ?id,
'kind': ?kind,
'state': ?state,
'label': ?label,
};
JsonMap _turn(String id, List<JsonMap> parts) => {
'id': id,
'role': 'assistant',
'parts': parts,
};
List<JsonMap> _activityRows(List<JsonMap> rows) =>
rows.where((row) => row['kind'] == 'activity').toList();
void main() {
group('recorded activity wording', () {
test('running kinds use the web phase words', () {
expect(
chatActivityLabel(_record(kind: 'compaction', state: 'running')),
'Compacting context…',
);
expect(
chatActivityLabel(_record(kind: 'thinking', state: 'running')),
'Thinking…',
);
expect(
chatActivityLabel(_record(kind: 'tool', state: 'running')),
'Running a tool…',
);
expect(
chatActivityLabel(_record(kind: 'waiting', state: 'running')),
'Waiting…',
);
});
test('the part type is the kind when the record does not name one', () {
expect(
chatActivityLabel(_record(type: 'compaction', state: 'running')),
'Compacting context…',
);
});
test('terminal records keep their recorded label', () {
expect(
chatActivityLabel(
_record(
kind: 'compaction',
state: 'completed',
label: 'Context compacted',
),
),
'Context compacted',
);
expect(
chatActivityLabel(
_record(
kind: 'compaction',
state: 'failed',
label: 'Compaction failed',
),
),
'Compaction failed',
);
});
test('an unknown kind keeps its recorded label and state', () {
expect(
chatActivityLabel(
_record(kind: 'weaving', state: 'running', label: 'Weaving context'),
),
'Weaving context',
);
expect(
chatActivityLabel(
_record(kind: 'weaving', state: 'failed', label: 'Weave failed'),
),
'Weave failed',
);
});
test('no recorded label keeps the recorded kind and state verbatim', () {
expect(
chatActivityLabel(_record(kind: 'weaving', state: 'completed')),
'weaving · completed',
);
expect(chatActivityLabel(_record()), 'activity');
});
});
group('recorded activity rows', () {
test('one line per sequence, worded from its latest recorded update', () {
final rows = transcriptRows([
_turn('a1', [
_record(kind: 'thinking', state: 'running', id: 'e1'),
{'type': 'text', 'text': 'answer'},
_record(type: 'compaction', state: 'running', id: 'e2'),
_record(
type: 'compaction',
state: 'completed',
id: 'e3',
label: 'Context compacted',
),
]),
]);
expect(rows.map((row) => row['kind']), ['activity', 'assistant']);
final activity = rows.first;
expect(activity['records'], hasLength(3));
expect(activity['label'], 'Context compacted');
expect(activity['state'], 'completed');
expect((rows.last['parts'] as List).single['text'], 'answer');
});
test('a sequence can span consecutive assistant messages', () {
final rows = transcriptRows([
_turn('a1', [_record(kind: 'thinking', state: 'running', id: 'e1')]),
_turn('a2', [
_record(
kind: 'thinking',
state: 'completed',
id: 'e2',
label: 'Thought',
),
{'type': 'text', 'text': 'answer'},
]),
]);
expect(_activityRows(rows), hasLength(1));
expect(_activityRows(rows).single['label'], 'Thought');
});
test('separate turns keep separate lines', () {
final rows = transcriptRows([
_turn('a1', [_record(kind: 'compaction', state: 'running', id: 'e1')]),
{'id': 'u1', 'role': 'user', 'parts': <JsonMap>[]},
_turn('a2', [_record(kind: 'compaction', state: 'running', id: 'e2')]),
]);
expect(_activityRows(rows), hasLength(2));
expect(_activityRows(rows).map((row) => row['key']), [
'chat-activity-a1',
'chat-activity-a2',
]);
});
test('an activity-only turn renders no empty assistant row', () {
final rows = transcriptRows([
_turn('a1', [_record(kind: 'compaction', state: 'running')]),
]);
expect(rows.map((row) => row['kind']), ['activity']);
});
});
group('recorded activity rendering', () {
Future<FakeChatGateway> pumpThread(
WidgetTester tester, {
required bool cupertino,
}) async {
final gateway = FakeChatGateway();
addTearDown(gateway.close);
gateway.history = (_) async => chatPage([
chatMessage(
'u1',
'user',
parts: [
{'type': 'text', 'text': 'Prompt'},
],
),
chatMessage(
'a1',
'assistant',
parts: [
{
'type': 'activity',
'id': 'e1',
'kind': 'compaction',
'state': 'running',
},
{'type': 'text', 'id': 't1', 'text': 'Answer'},
],
),
]);
final view = ChatThreadView(
gateway: gateway,
sessionId: 's',
onBack: () {},
);
await tester.pumpWidget(
cupertino
? CupertinoApp(
theme: const CupertinoThemeData(brightness: Brightness.dark),
home: CupertinoPageScaffold(child: view),
)
: MaterialApp(
theme: ThemeData(),
home: Scaffold(body: view),
),
);
await tester.pumpAndSettle();
return gateway;
}
testWidgets('Material shows the recorded line once beside the answer', (
tester,
) async {
await pumpThread(tester, cupertino: false);
expect(find.text('Compacting context…'), findsOneWidget);
expect(find.text('Answer'), findsOneWidget);
expect(find.textContaining('Unrecognised part'), findsNothing);
});
testWidgets('Cupertino shows the same recorded line', (tester) async {
await pumpThread(tester, cupertino: true);
expect(find.text('Compacting context…'), findsOneWidget);
expect(find.text('Answer'), findsOneWidget);
expect(find.textContaining('Unrecognised part'), findsNothing);
});
});
}