Keep chat activity stable in one live disclosure and distinguish unread attention

This commit is contained in:
2026-10-28 16:45:05 +00:00
parent e0317574de
commit 7027da4248
22 changed files with 968 additions and 301 deletions
@@ -88,22 +88,29 @@ List<JsonMap> transcriptRows(
final activity = <JsonMap>[];
String? activityKey;
void flush() {
if (activity.isNotEmpty) {
final latest = activity.last;
final compactions = activity
.where((p) => chatActivityKind(p) == 'compaction')
.toList();
final passive = activity
.where((p) => chatActivityKind(p) != 'compaction')
.toList();
if (compactions.isNotEmpty) {
final latest = compactions.last;
rows.add({
'kind': 'activity',
'key': activityKey == null ? '' : 'chat-activity-$activityKey',
'records': List<JsonMap>.of(activity),
'records': compactions,
'label': chatActivityLabel(latest),
'state': chatActivityState(latest).toLowerCase(),
});
}
if (key != null && parts.isNotEmpty) {
if (key != null && (parts.isNotEmpty || passive.isNotEmpty)) {
rows.add({
'kind': 'assistant',
'key': key,
'messageIds': List<String>.of(ids),
'parts': List<JsonMap>.of(parts),
if (passive.isNotEmpty) 'activityRecords': passive,
// The model that answered, as the server recorded it on the reply.
if (model.isNotEmpty) 'model': model,
});
@@ -0,0 +1,125 @@
import '../../../core/api_gateway.dart';
import 'chat_tool_calls.dart';
import 'chat_transcript.dart';
/// Presentation facts only: never infer a command or successful outcome from
/// answer prose, and never treat a still-running record as a completed command.
class ChatTurnActivityData {
ChatTurnActivityData(this.parts, {required this.streaming});
final List<JsonMap> parts;
final bool streaming;
List<JsonMap> get tools => parts.where(isChatToolPart).toList();
List<String> get reasoning => [
for (final p in parts)
if (p['type'] == 'reasoning' && '${p['text'] ?? ''}'.trim().isNotEmpty)
'${p['text']}',
];
List<JsonMap> get records => parts.where(chatActivityType).toList();
bool get hasDetails =>
tools.isNotEmpty || reasoning.isNotEmpty || records.isNotEmpty;
JsonMap? get active {
for (final tool in tools.reversed) {
if (chatToolRunning(tool)) return tool;
}
if (records.isNotEmpty) {
// Sequence updates can be distinct records; a completed newest record
// must not resurrect an older running phase.
final record = records.last;
if ([
'running',
'streaming',
'pending',
].contains(chatActivityState(record))) {
return record;
}
}
return null;
}
String get identity {
final p = active;
return p == null
? 'thinking'
: '${p['type']}:${p['id'] ?? p['name'] ?? p['kind'] ?? ''}';
}
DateTime? get started {
final p = active;
if (p == null) return null;
final state = p['state'];
final time = p['time'] ?? (state is Map ? state['time'] : null);
if (time is! Map) return null;
final value = time['ran'] ?? time['started'] ?? time['created'];
if (value is num && value > 0) {
return DateTime.fromMillisecondsSinceEpoch(value.toInt());
}
return value is String ? DateTime.tryParse(value) : null;
}
String get label {
if (streaming) {
final p = active;
if (p == null) {
for (final part in parts.reversed) {
if (part['type'] == 'text' &&
'${part['text'] ?? ''}'.trim().isNotEmpty) {
return 'Responding';
}
if (part['type'] == 'reasoning') return 'Thinking';
}
return 'Thinking';
}
if (!isChatToolPart(p)) {
return chatActivityLabel(p).replaceAll('…', '').trim();
}
final state = p['state'];
final title = state is Map ? '${state['title'] ?? ''}'.trim() : '';
return title.isNotEmpty
? title
: chatToolDetail(p) ??
(_command(p)
? 'Running a command'
: 'Running ${chatToolLabel(p)}');
}
final calls = tools;
if (calls.isEmpty) {
return records.isNotEmpty ? 'Activity details' : 'Reasoning';
}
final commands = calls.every(_command);
final failed = calls.where(chatToolFailed).length;
final unfinished = calls.any((p) {
final state = p['state'];
return chatToolRunning(p) ||
(state is Map &&
[
'stopped',
'interrupted',
'canceled',
'cancelled',
'pending',
].contains(state['status']));
});
final noun = commands
? (calls.length == 1 ? 'command' : 'commands')
: (calls.length == 1 ? 'tool' : 'tools');
final summary =
'${unfinished
? 'Stopped after'
: commands
? 'Ran'
: 'Used'} ${calls.length} $noun';
return failed == 0 ? summary : '$summary · $failed failed';
}
bool get failed => tools.any(chatToolFailed);
}
bool _command(JsonMap tool) => const [
'bash',
'shell',
'command',
'exec',
'execute',
'run_command',
].contains(chatToolLabel(tool).toLowerCase());
@@ -39,6 +39,8 @@ class ChatSessionsController extends ChangeNotifier {
bool _disposed = false;
int _generation = 0;
Future<void> _persistTail = Future<void>.value();
int _runningRevision = 0;
final Map<String, ({int revision, bool running})> _runningFrames = {};
StreamSubscription<JsonMap>? _frameSubscription;
String? activeSessionId;
@@ -61,6 +63,7 @@ class ChatSessionsController extends ChangeNotifier {
void _setRunning(String id, bool running) {
if (_disposed) return;
_runningFrames[id] = (revision: ++_runningRevision, running: running);
var changed = false;
_sessions = _sessions.map((session) {
if ('${session['id'] ?? ''}' != id || session['running'] == running) {
@@ -121,6 +124,7 @@ class ChatSessionsController extends ChangeNotifier {
void replaceRepository(ChatRepository next) {
if (identical(next.gateway, repository.gateway)) return;
repository = next;
_runningFrames.clear();
_listenFrames();
refresh();
}
@@ -135,9 +139,17 @@ class ChatSessionsController extends ChangeNotifier {
// must not hide the list or delay the first request.
unawaited(_ensureLocal());
try {
final runningRevision = _runningRevision;
final sessions = await repository.sessions();
if (generation != _generation) return;
_sessions = sessions;
_sessions = [
for (final row in sessions)
if ((_runningFrames['${row['id'] ?? ''}']?.revision ?? 0) >
runningRevision)
{...row, 'running': _runningFrames['${row['id'] ?? ''}']!.running}
else
row,
];
_seedLocal();
_loading = false;
_notify();
@@ -48,27 +48,17 @@ ChatSessionFrameEffect? chatSessionFrameEffect(JsonMap frame) {
} else if (kind == 'step') {
final step = event['step'];
if (step is Map) {
if (step['status'] == 'started' || step['status'] == 'streamed') {
if ([
'started',
'streamed',
'running',
'streaming',
].contains(step['status'])) {
running = true;
} else if (step['status'] == 'ended' && step['intermediate'] != true) {
running = false;
}
}
} else if (kind == 'compaction') {
final compaction = event['compaction'];
if (compaction is Map) {
if (compaction['status'] == 'running') running = true;
if (compaction['status'] == 'completed' ||
compaction['status'] == 'failed') {
running = false;
}
}
} else if (kind == 'shell') {
final shell = event['shell'];
if (shell is Map) {
if (shell['status'] == 'running') running = true;
if (shell['status'] == 'exited') running = false;
}
}
} else if (type == 'chat_permission') {
final permission = frame['chat_permission'];
@@ -82,7 +82,11 @@ class ChatSessionRowContent extends StatelessWidget {
children: [
if (status != null)
_StatusLabel(status: status!, style: statusStyle),
if (status == null && loading) _LoadingStatus(),
if (status == null && loading)
Semantics(
label: 'Chat is working',
child: const _LoadingStatus(),
),
for (final line in meta)
Text(
line,
@@ -123,6 +127,7 @@ class ChatSessionRowContent extends StatelessWidget {
}
class _LoadingStatus extends StatelessWidget {
const _LoadingStatus();
@override
Widget build(BuildContext context) {
if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) {
@@ -6,10 +6,8 @@ import 'package:flutter/material.dart';
import '../../../../core/api_gateway.dart';
import '../sessions/chat_adaptive.dart';
import '../../domain/chat_tool_calls.dart';
import 'chat_tool_calls_view.dart';
import 'chat_reasoning_chip.dart';
import 'chat_turn_activity_view.dart';
import 'native_disclosure.dart';
import 'chat_response_pending.dart';
/// Builds an assistant text part; the default keeps the server's text exactly.
typedef ChatMessageTextBuilder = Widget Function(BuildContext, String);
@@ -27,8 +25,7 @@ class ChatMessageView extends StatelessWidget {
final JsonMap row;
final ChatMessageTextBuilder? textBuilder;
/// More of an agent turn's summary chips, after its reasoning and tools chips
/// (the turn's settled permission requests).
/// The turn's settled permissions, independent of passive activity details.
final List<Widget> footer;
@override
@@ -199,9 +196,8 @@ class ChatMessageView extends StatelessWidget {
return widgets;
}
/// The turn's footer: its reasoning, tools and permissions chips, then its
/// model. Each chip opens a native sheet; an open reasoning sheet follows
/// live deltas.
/// Stable activity precedes the answer; permission summaries and recorded
/// model remain beneath it. Pending interaction cards are rendered separately.
Widget _agentTurn(BuildContext context, List<Widget> content, Widget bubble) {
final parts = _partsOf(row);
final reasoning = [
@@ -216,13 +212,6 @@ class ChatMessageView extends StatelessWidget {
];
final model = '${row['model'] ?? ''}'.trim();
final footer = <Widget>[
if (reasoning.isNotEmpty)
ChatReasoningChip(
key: const Key('chat-turn-reasoning'),
steps: reasoning,
streaming: row['streaming'] == true && _reasoningIsNewest(parts),
),
if (tools.isNotEmpty) ChatToolCallsChip(calls: tools),
...this.footer,
if (model.isNotEmpty)
Text(
@@ -238,6 +227,20 @@ class ChatMessageView extends StatelessWidget {
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (row['streaming'] == true ||
reasoning.isNotEmpty ||
tools.isNotEmpty ||
(row['activityRecords'] as List? ?? const []).isNotEmpty)
ChatTurnActivityView(
key: const Key('chat-stable-turn-activity'),
parts: [
...parts,
...List<JsonMap>.from(
row['activityRecords'] as List? ?? const [],
),
],
streaming: row['streaming'] == true,
),
if (content.isNotEmpty) bubble,
if (footer.isNotEmpty)
Wrap(
@@ -266,9 +269,6 @@ class ChatMessageView extends StatelessWidget {
KeyedSubtree(key: _partKey(part, index, seen), child: widget),
);
}
if (widgets.isEmpty && row['streaming'] == true) {
widgets.add(const ChatResponsePending());
}
return widgets;
}
@@ -294,7 +294,7 @@ class ChatMessageView extends StatelessWidget {
if (!hasText) return type.isEmpty ? _unrecognised(part) : null;
return textBuilder?.call(context, text) ?? SelectableText(text);
}
// Reasoning and tool calls are drawn outside the bubble (_agentTurn).
// Reasoning and tools are retained in the turn's activity disclosure.
if (type == 'reasoning' || type == 'tool') return null;
if (type == 'file') {
if (_isFile(part)) return _attachment(context, part);
@@ -343,21 +343,6 @@ class ChatMessageView extends StatelessWidget {
SelectableText(const JsonEncoder.withIndent(' ').convert(part));
}
/// Whether the turn's newest drawn part is reasoning: while it streams, that
/// is the step still arriving. Once an answer or a tool call starts after it,
/// the reasoning chip stops spinning (a running tool spins its own chip).
bool _reasoningIsNewest(List<JsonMap> parts) {
for (final part in parts.reversed) {
final type = part['type'];
if (type == 'tool') return false;
if ((type == 'text' || type == 'reasoning') &&
'${part['text'] ?? ''}'.trim().isNotEmpty) {
return type == 'reasoning';
}
}
return false;
}
List<JsonMap> _partsOf(Map<dynamic, dynamic> source) {
final parts = source['parts'];
if (parts is! List) return const [];
@@ -85,7 +85,7 @@ class _ToolCallsSheet extends StatelessWidget {
style: const TextStyle(fontWeight: FontWeight.w600),
),
),
for (final call in calls) _ToolCallRow(call: call),
for (final call in calls) ChatToolCallDetail(call: call),
],
),
),
@@ -95,8 +95,8 @@ class _ToolCallsSheet extends StatelessWidget {
/// One call: status glyph, name, its command/description and duration; it
/// opens to the formatted INPUT and OUTPUT (or ERROR).
class _ToolCallRow extends StatelessWidget {
const _ToolCallRow({required this.call});
class ChatToolCallDetail extends StatelessWidget {
const ChatToolCallDetail({super.key, required this.call});
final JsonMap call;
@@ -0,0 +1,47 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../domain/chat_turn_activity.dart';
import '../../domain/chat_activity_detail.dart';
import '../sessions/chat_adaptive.dart';
import 'chat_tool_calls_view.dart';
import 'native_disclosure.dart';
class ChatTurnActivityDetails extends StatelessWidget {
const ChatTurnActivityDetails({super.key, required this.data});
final ChatTurnActivityData data;
@override
Widget build(BuildContext context) {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
return DefaultTextStyle.merge(
style: cupertino
? CupertinoTheme.of(context).textTheme.textStyle
: Theme.of(context).textTheme.bodyMedium,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.min,
children: [
if (!data.hasDetails) const Text('Waiting for activity details.'),
for (final (index, step) in data.reasoning.indexed)
NativeDisclosure(
label: 'Reasoning ${index + 1}',
childBuilder: (_) => SelectableText(step),
),
for (final tool in data.tools) ChatToolCallDetail(call: tool),
for (final record in data.records)
NativeDisclosure(
label: '${record['label'] ?? record['kind'] ?? 'Activity'}',
childBuilder: (_) {
final d = chatActivityDetail(record);
return SelectableText(
'Status: ${d.lifecycle}\nInput: ${d.input}\nOutput: ${d.output}\nError: ${d.error}\nDuration: ${d.duration}\nDiff: ${d.diff}',
);
},
),
],
),
);
}
}
@@ -0,0 +1,193 @@
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../../core/api_gateway.dart';
import '../../domain/chat_turn_activity.dart';
import '../sessions/chat_adaptive.dart';
import 'chat_response_pending.dart';
import 'chat_turn_activity_details.dart';
/// A stable one-line turn status; only this small subtree ticks, never the
/// transcript. The same disclosure and live records survive tool transitions.
class ChatTurnActivityView extends StatefulWidget {
const ChatTurnActivityView({
super.key,
required this.parts,
required this.streaming,
});
final List<JsonMap> parts;
final bool streaming;
@override
State<ChatTurnActivityView> createState() => _ChatTurnActivityViewState();
}
class _ChatTurnActivityViewState extends State<ChatTurnActivityView> {
late final _live = ValueNotifier(_data);
ChatTurnActivityData get _data =>
ChatTurnActivityData(widget.parts, streaming: widget.streaming);
Timer? _timer;
final _clock = Stopwatch()..start();
Duration _observedAt = Duration.zero;
String? _identity;
TransitionRoute<void>? _modal;
@override
void initState() {
super.initState();
_sync();
}
void _sync() {
final data = _data;
if (_identity != data.identity) {
_identity = data.identity;
_observedAt = _clock.elapsed;
}
_timer?.cancel();
if (widget.streaming) {
_timer = Timer.periodic(const Duration(seconds: 1), (_) {
if (mounted) setState(() {});
});
}
}
@override
void didUpdateWidget(ChatTurnActivityView oldWidget) {
super.didUpdateWidget(oldWidget);
_sync();
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) _live.value = _data;
});
}
void _open() {
if (_modal != null) return;
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
Widget dialog(BuildContext dialogContext) {
final content = ValueListenableBuilder<ChatTurnActivityData>(
valueListenable: _live,
builder: (_, data, _) =>
SingleChildScrollView(child: ChatTurnActivityDetails(data: data)),
);
void close() => Navigator.of(dialogContext).pop();
return cupertino
? CupertinoAlertDialog(
title: const Text('Activity details'),
content: content,
actions: [
CupertinoDialogAction(
onPressed: close,
child: const Text('Done'),
),
],
)
: AlertDialog(
title: const Text('Activity details'),
scrollable: true,
content: content,
actions: [
TextButton(onPressed: close, child: const Text('Done')),
],
);
}
final TransitionRoute<void> route = cupertino
? CupertinoDialogRoute<void>(
context: context,
barrierDismissible: true,
builder: dialog,
)
: DialogRoute<void>(context: context, builder: dialog);
_modal = route;
Navigator.of(context, rootNavigator: true).push(route);
route.completed.then((_) {
if (_modal == route) _modal = null;
});
}
@override
void dispose() {
_timer?.cancel();
_clock.stop();
final route = _modal;
if (route != null) {
// Do not pop a different route the operator opened above our dialog.
WidgetsBinding.instance.addPostFrameCallback((_) {
if (route.isActive) route.navigator?.removeRoute(route);
});
route.completed.then((_) => _live.dispose());
} else {
_live.dispose();
}
super.dispose();
}
@override
Widget build(BuildContext context) {
final data = _data;
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final accent = cupertino
? CupertinoTheme.of(context).primaryColor
: Theme.of(context).colorScheme.primary;
final color = data.failed && !widget.streaming
? (cupertino
? CupertinoColors.systemRed.resolveFrom(context)
: Theme.of(context).colorScheme.error)
: (cupertino
? CupertinoColors.secondaryLabel.resolveFrom(context)
: Theme.of(context).colorScheme.onSurfaceVariant);
final started = data.started;
final duration = started == null
? _clock.elapsed - _observedAt
: DateTime.now().difference(started);
final seconds = duration.inSeconds.clamp(0, 2147483647);
final label = '${data.label}${widget.streaming ? ' ${seconds}s' : ''}';
final content = Row(
children: [
if (widget.streaming) ...[
ExcludeSemantics(
child: DefaultTextStyle.merge(
style: TextStyle(color: accent),
child: const ChatResponsePending(),
),
),
const SizedBox(width: 8),
],
Expanded(
child: Text(
label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: color),
),
),
Icon(
cupertino ? CupertinoIcons.chevron_right : Icons.chevron_right,
color: color,
),
],
);
return Semantics(
button: true,
label: '$label, expand for details',
excludeSemantics: true,
onTap: _open,
child: cupertino
? CupertinoButton(
key: const Key('chat-turn-activity'),
padding: EdgeInsets.zero,
onPressed: _open,
child: content,
)
: TextButton(
key: const Key('chat-turn-activity'),
onPressed: _open,
child: content,
),
);
}
}