Files
pipelines/app/lib/features/chat/conversation/chat_row_keys.dart
T

74 lines
2.5 KiB
Dart

import '../../../core/api_gateway.dart';
/// Stable widget-key strings for transcript rows while history grows at both
/// ends.
///
/// A folded assistant turn has no stable message boundary: `Load older` can
/// prepend messages into the turn (changing its first id) and a live frame can
/// append a message (changing its last id). Deriving the row key from either
/// boundary remounts the row and resets every native disclosure in it, which
/// moved an open reasoning block to another answer or closed it.
///
/// So the first sighting of a turn assigns a synthetic key, and later calls
/// carry that key forward while the turn still contains any message it held
/// before. Rows without a message id fall back to their position: they have no
/// identity that survives a prepend.
class ChatRowKeys {
final Map<String, String> _byMessageId = {};
int _serial = 0;
/// One key per row, in row order. Call once per build.
List<String> forRows(List<JsonMap> rows) {
final nextByMessageId = <String, String>{};
final used = <String>{};
final keys = <String>[];
for (var index = 0; index < rows.length; index++) {
final row = rows[index];
final kind = '${row['kind'] ?? ''}';
final ids = _messageIds(row);
String? key;
for (final id in ids) {
final held = _byMessageId[id];
if (held != null) {
key = held;
break;
}
}
if (key == null) {
// A row with no id has no identity that survives a prepend, so it
// follows its position, as a plain indexed list would. Every other new
// row gets a key no older row can generate.
key = ids.isEmpty
? 'chat-row-$kind-index-$index'
: 'chat-row-$kind-${_serial++}';
used.add(key);
} else if (!used.add(key)) {
// Defensive: a held key is only reused once even if input unexpectedly
// splits one turn into two rows; duplicate widget keys would throw.
key = 'chat-row-$kind-${_serial++}';
used.add(key);
}
keys.add(key);
for (final id in ids) {
nextByMessageId[id] = key;
}
}
_byMessageId
..clear()
..addAll(nextByMessageId);
return keys;
}
static List<String> _messageIds(JsonMap row) {
final listed = row['messageIds'];
if (listed is List) {
return listed
.map((id) => '$id'.trim())
.where((id) => id.isNotEmpty)
.toList();
}
final key = '${row['key'] ?? ''}'.trim();
return key.isEmpty ? const [] : [key];
}
}