import '../../../core/api_gateway.dart'; /// Where an opened transcript is split into its older and newer halves. /// /// Opening a long conversation at its newest message used to lay out every row /// above it: a top-anchored list can only reach its end by measuring the rows /// in between. The transcript is instead a two-sided scroll view whose centre /// sits between an anchor row and the rows after it. The anchor row and every /// older row grow upwards from the centre; the rows after it (and the queued, /// unsent and command lines) grow downwards. Opening lays out only what shows. /// /// The split is fixed for as long as the conversation is open, so growth on /// either side never moves the other: an older page loaded above, or a reply /// streaming below, leaves the operator's reading position where it is. The /// newest message row (and a reply that is still streaming) is never the /// anchor or above it, because a row above the centre that grew would push the /// rows above it up while the operator reads them. /// /// Returns null when the transcript has fewer than two message rows: there is /// nothing older to keep unmeasured, and the view stays top-anchored. String? chatTranscriptAnchor(List rows) { var cut = -1; for (var index = rows.length - 1; index >= 0; index--) { if (_messageIds(rows[index]).isNotEmpty) { cut = index; break; } } for (var index = 0; index < rows.length; index++) { if (rows[index]['streaming'] == true && index < cut) { cut = index; break; } } for (var index = cut - 1; index >= 0; index--) { final ids = _messageIds(rows[index]); if (ids.isNotEmpty) return ids.last; } return null; } /// The index of the row that holds [anchor], or -1 when no row does (a repair /// replaced the transcript) or there is no anchor. int chatTranscriptAnchorIndex(List rows, String? anchor) { if (anchor == null) return -1; for (var index = rows.length - 1; index >= 0; index--) { if (_messageIds(rows[index]).contains(anchor)) return index; } return -1; } /// The stored message ids of one user or assistant row. Cards, activity lines /// and the pending-response shell carry none and can never be an anchor. List _messageIds(JsonMap row) { final kind = row['kind']; if (kind == 'assistant') { final listed = row['messageIds']; if (listed is! List) return const []; return [ for (final id in listed) if ('$id'.trim().isNotEmpty) '$id'.trim(), ]; } if (kind == 'user') { final id = '${row['key'] ?? ''}'.trim(); return id.isEmpty ? const [] : [id]; } return const []; }