import '../../../core/api_gateway.dart'; import '../shell/chat_shell_history.dart'; import 'chat_task_notices.dart'; import 'chat_tool_calls.dart'; import 'chat_turn_activity.dart'; /// The row kind of a run of activity-only rows folded into one summary line. const String chatActivityGroupKind = 'activity_group'; /// Whether [row] carries activity only: an agent turn with nothing but tool /// calls, reasoning or recorded activity (no answer text, file or unknown part, /// and no footer chip), or a background-task notice. Such rows say that work /// happened, not what the agent said, so a run of them reads as one line. /// /// A streaming turn is never activity-only: its live status stays its own row. bool chatActivityOnlyRow(JsonMap row) { switch (row['kind']) { case 'task_notices': return true; case 'system_notice': return _noticeMessage(row) != null; case 'assistant': break; default: return false; } if (row['streaming'] == true || row['turnDiff'] != null) return false; for (final field in ['permissions', 'questions', chatShellHistoryField]) { final value = row[field]; if (value is List && value.isNotEmpty) return false; } for (final part in row['parts'] as List? ?? const []) { if (part is! Map) return false; final type = '${part['type'] ?? ''}'; if (type == 'tool' || type == 'reasoning') continue; if (type == 'text' && '${part['text'] ?? ''}'.trim().isEmpty) continue; return false; } return true; } /// Folds every run of consecutive activity-only rows (see /// [chatActivityOnlyRow]) between two content rows into one /// [chatActivityGroupKind] row, so the agent's own messages are not buried /// under one line per tool turn and one per background-task notice. /// /// The group lists its member rows in `rows`, as they render on their own. /// A run's task notices fold into one member at the newest notice's place (a /// `task_notices` row, or the lone notice), so the background-task chip shows /// once per run; a notice whose message id recurs later in the transcript is /// counted only at its latest position. A run of a single agent turn stays that /// row. The group's `messageIds` lists every member's ids, so [ChatRowKeys] /// keeps one widget identity as the run grows, and an unchanged run yields the /// identical group object. List groupChatActivity(List rows) { final stale = _staleNotices(rows); final result = []; final run = []; void close() { if (run.isEmpty) return; final members = _members(run, stale); if (members.length == 1 && members.single['kind'] == 'assistant') { result.add(members.single); } else if (members.isNotEmpty) { result.add(_group(members)); } run.clear(); } for (final row in rows) { if (chatActivityOnlyRow(row)) { run.add(row); } else { close(); result.add(row); } } close(); return result; } /// The notice messages a notice row carries, in transcript order. List _rowNotices(JsonMap row) { if (row['kind'] == 'system_notice') { final message = _noticeMessage(row); return message == null ? const [] : [message]; } if (row['kind'] != 'task_notices') return const []; return [ for (final message in row['messages'] as List? ?? const []) if (message is Map && chatTaskNotice(message) != null) message, ]; } JsonMap? _noticeMessage(JsonMap row) { final message = row['message']; if (message is! Map) return null; return chatTaskNotice(message) == null ? null : message; } /// Notice messages whose id appears again later: only the latest counts. Set _staleNotices(List rows) { final seen = {}; final stale = Set.identity(); for (final row in rows.reversed) { for (final message in _rowNotices(row).reversed) { final id = '${message['id'] ?? ''}'.trim(); if (id.isNotEmpty && !seen.add(id)) stale.add(message); } } return stale; } /// [run]'s members: its agent turns in order, with its current notices as one /// member where the newest of them was. List _members(List run, Set stale) { final members = []; final notices = []; final sources = {}; var at = -1; for (final row in run) { final rowNotices = _rowNotices(row); if (rowNotices.isEmpty && row['kind'] == 'assistant') { members.add(row); continue; } for (final message in rowNotices) { if (stale.contains(message)) continue; notices.add(message); sources.add(row); at = members.length; } } if (notices.isEmpty) return members; return members..insert(at, _noticeMember(notices, sources)); } /// One member for [notices]: the row that already holds exactly them, a lone /// notice line, or a `task_notices` row (the same object while they hold). JsonMap _noticeMember(List notices, Set sources) { if (sources.length == 1) { final source = sources.single; if (_identical(_rowNotices(source), notices)) return source; } if (notices.length == 1) { final message = notices.single; return {'kind': 'system_notice', 'key': message['id'], 'message': message}; } final held = _noticeRows[notices.first]; if (held != null && _identical(held.notices, notices)) return held.row; final row = { 'kind': 'task_notices', 'key': notices.first['id'], 'messageIds': [for (final message in notices) '${message['id'] ?? ''}'], 'messages': notices, }; _noticeRows[notices.first] = (notices: List.of(notices), row: row); return row; } final Expando<({List notices, JsonMap row})> _noticeRows = Expando( 'chat activity notices', ); final Expando<({List members, JsonMap group})> _groups = Expando( 'chat activity group', ); bool _identical(List a, List b) { if (a.length != b.length) return false; for (var index = 0; index < a.length; index++) { if (!identical(a[index], b[index])) return false; } return true; } JsonMap _group(List members) { final held = _groups[members.first]; if (held != null && _identical(held.members, members)) return held.group; var commands = 0, tools = 0, failed = 0, tasks = 0; var tasksEnded = false, thinking = false; for (final member in members) { for (final message in _rowNotices(member)) { final notice = chatTaskNotice(message)!; tasks++; if (notice.outcome == ChatTaskOutcome.failed) failed++; if (notice.outcome != ChatTaskOutcome.finished) tasksEnded = true; } if (member['kind'] != 'assistant') continue; final parts = [ for (final part in member['parts'] as List? ?? const []) if (part is Map) Map.from(part), ]; final calls = parts.where(isChatToolPart).toList(); // Summed the way each turn's own line words it: a turn of commands only // says "Ran N commands", any other turn "Used N tools". if (calls.isNotEmpty && calls.every(chatToolIsCommand)) { commands += calls.length; } else { tools += calls.length; } failed += calls.where(chatToolFailed).length; if (parts.any((part) => part['type'] == 'reasoning')) thinking = true; } final first = members.first; final group = { 'kind': chatActivityGroupKind, 'key': 'chat-activity-group-${first['key'] ?? ''}', 'messageIds': [for (final member in members) ..._memberIds(member)], 'rows': members, 'commands': commands, 'tools': tools, 'tasks': tasks, 'tasksEnded': tasksEnded, 'failed': failed, 'thinking': thinking, }; _groups[first] = (members: List.of(members), group: group); return group; } List _memberIds(JsonMap row) { final listed = row['messageIds']; if (listed is List) return [for (final id in listed) '$id']; final key = '${row['key'] ?? ''}'.trim(); return key.isEmpty ? const [] : [key]; } /// The member rows a group row folds, in transcript order. List chatActivityGroupRows(JsonMap row) => [ for (final member in row['rows'] as List? ?? const []) if (member is Map) member, ]; /// The agent-turn message ids a group holds (what a scroll anchor may name). List chatActivityGroupTurnIds(JsonMap row) => [ for (final member in chatActivityGroupRows(row)) if (member['kind'] == 'assistant') ..._memberIds(member), ]; /// One piece of a group's summary; [failed] pieces draw in the error colour. typedef ChatActivitySegment = ({String text, bool failed}); /// A group's summary, e.g. `Ran 7 commands`, `used 9 tools`, /// `3 background tasks finished`, `1 failed`. List chatActivityGroupSegments(JsonMap row) { int count(String field) => (row[field] as num?)?.toInt() ?? 0; String plural(int n, String one) => n == 1 ? '1 $one' : '$n ${one}s'; final commands = count('commands'), tools = count('tools'); final tasks = count('tasks'), failed = count('failed'); final texts = [ if (commands > 0) 'ran ${plural(commands, 'command')}', if (tools > 0) 'used ${plural(tools, 'tool')}', if (tasks > 0) '${plural(tasks, 'background task')} ' '${row['tasksEnded'] == true ? 'ended' : 'finished'}', ]; if (texts.isEmpty) { texts.add(row['thinking'] == true ? 'reasoning' : 'activity'); } texts[0] = texts[0][0].toUpperCase() + texts[0].substring(1); return [ for (final text in texts) (text: text, failed: false), if (failed > 0) (text: '$failed failed', failed: true), ]; } /// The summary as one line: its segments joined by ` · `. String chatActivityGroupLabel(JsonMap row) => chatActivityGroupSegments(row).map((segment) => segment.text).join(' · ');