import '../../../core/api_gateway.dart'; import 'chat_shell_run.dart'; /// The row field that carries an answer's dismissed command ids, oldest /// first: what its footer's "N commands" chip lists. const String chatShellHistoryField = 'shellHistory'; /// The transcript row kind of the history chip a chat with no answer shows. const String chatShellHistoryRowKind = 'shell_history'; /// Attaches each dismissed run to an answer's footer as [chatShellHistoryField]: /// the first assistant reply created at or after the run started, or the last /// reply for a run newer than every reply. A reply without a recorded time is /// only chosen as that last reply. With no assistant reply at all, one /// [chatShellHistoryRowKind] row at the end holds every run. List attachChatShellHistory( List rows, List dismissed, ) { if (dismissed.isEmpty) return rows; final replies = [ for (var i = 0; i < rows.length; i++) if (rows[i]['kind'] == 'assistant') i, ]; final ordered = [...dismissed] ..sort((a, b) => a.startedAt.compareTo(b.startedAt)); if (replies.isEmpty) { return [ ...rows, { 'kind': chatShellHistoryRowKind, 'key': 'chat-shell-history', chatShellHistoryField: [for (final run in ordered) run.id], }, ]; } final assigned = >{}; for (final run in ordered) { final index = replies.firstWhere((i) { final created = rows[i]['created_at']; return created is num && created >= run.startedAt; }, orElse: () => replies.last); (assigned[index] ??= []).add(run.id); } return [ for (var i = 0; i < rows.length; i++) if (assigned[i] case final ids?) {...rows[i], chatShellHistoryField: ids} else rows[i], ]; } /// The dismissed command ids [row] carries, oldest first. List chatShellHistoryIds(JsonMap row) => [ for (final id in row[chatShellHistoryField] as List? ?? const []) '$id', ]; /// The chip's label, e.g. `2 commands`. String chatShellHistoryLabel(int count) => count == 1 ? '1 command' : '$count commands'; /// The chip's accessible name. String chatShellHistorySemantics(int count) => '${chatShellHistoryLabel(count)} dismissed, open command history';