Files
pipelines/app/lib/features/chat/domain/chat_notice.dart
T

214 lines
8.2 KiB
Dart

import '../../../core/api_gateway.dart';
import '../../../core/error_reason.dart';
import 'chat_transcript.dart';
/// The local notices one conversation can record beside its messages.
///
/// A notice is never a chat message and never reaches the agent. Each kind
/// reports one recorded condition; the thread stops showing it only while that
/// condition is unchanged (see [ChatNoticeDismissals]). A [command] notice is
/// the outcome of one slash command the operator ran in that conversation.
enum ChatNoticeKind { connectionRefused, liveFailure, compaction, command }
/// The two failure labels already used by this conversation, kept verbatim so a
/// refused read/watch is never mistaken for an empty transcript.
const String chatConnectionRefusedLabel = 'Chat history unavailable';
const String chatLiveFailureLabel = 'Live updates unavailable';
/// The running-phase words shared verbatim with the web's `turnPhaseLabel`.
const String chatCompactionLabel = chatCompactionPhaseLabel;
/// The accessible name of each kind's dismiss control. The web names its local
/// notice control `Dismiss command notice`; these keep the same shape while
/// naming the condition the operator is hiding.
String chatNoticeDismissLabel(ChatNoticeKind kind) => switch (kind) {
ChatNoticeKind.connectionRefused => 'Dismiss connection notice',
ChatNoticeKind.liveFailure => 'Dismiss live updates notice',
ChatNoticeKind.compaction => 'Dismiss compaction notice',
ChatNoticeKind.command => 'Dismiss command notice',
};
/// One recorded local notice: what it is, which condition it reports and the
/// exact line the thread shows.
class ChatNotice {
const ChatNotice({
required this.kind,
required this.condition,
required this.label,
this.detail = '',
this.failed = true,
});
final ChatNoticeKind kind;
/// Whether the line reports a failure. Every recorded condition does; only a
/// command's accepted outcome is a plain line.
final bool failed;
/// The recorded condition this notice reports. A different value is a new
/// notice even when the words repeat, and a dismissed value stays hidden only
/// while it is still recorded.
final String condition;
/// The condition's label, in the app/web words for that kind.
final String label;
/// The recorded reason, exactly as the web and the native client print it.
/// Empty for a phase with no reason (a running compaction).
final String detail;
/// The line the transcript shows. The reason is the recorded one, never a
/// runtime diagnostic.
String get text => detail.isEmpty ? label : '$label\n$detail';
}
/// Build the notices for the conditions this thread currently records, in the
/// order the thread shows them: a refused read, a refused live watch, then a
/// running compaction. Nothing is invented: an absent condition adds no line.
List<ChatNotice> chatNotices({
String? historyError,
String? liveError,
List<JsonMap> messages = const [],
}) {
final notices = <ChatNotice>[];
final history = _failureDetail(historyError);
if (history != null) {
notices.add(
ChatNotice(
kind: ChatNoticeKind.connectionRefused,
condition: 'connection-refused\n$history',
label: chatConnectionRefusedLabel,
detail: history,
),
);
}
final live = _failureDetail(liveError);
if (live != null) {
notices.add(
ChatNotice(
kind: ChatNoticeKind.liveFailure,
condition: 'live-failure\n$live',
label: chatLiveFailureLabel,
detail: live,
),
);
}
final compaction = chatRunningCompaction(messages);
if (compaction != null) {
notices.add(
ChatNotice(
kind: ChatNoticeKind.compaction,
condition: chatCompactionCondition(compaction),
label: chatCompactionLabel,
),
);
}
return notices;
}
/// One slash command's outcome in its exact words. [sequence] is the
/// conversation's own counter, so the same words twice are two notices and a
/// dismissal hides only the one the operator dismissed.
ChatNotice chatCommandNotice(
String text, {
required int sequence,
bool failed = false,
}) => ChatNotice(
kind: ChatNoticeKind.command,
condition: 'command\n$sequence',
label: text,
failed: failed,
);
/// The condition key of the compaction recorded as [id].
String chatCompactionCondition(String id) => 'compaction\n$id';
/// The recorded reason without a Dart runtime prefix, or null when there is no
/// recorded failure. [describeErrorReason] is the shared rule; a failure that
/// carries no text still says the connection closed, as the web client does.
String? _failureDetail(String? error) {
if (error == null) return null;
return describeErrorReason(error, fallback: 'Connection closed');
}
/// The identity of the newest recorded compaction in [messages], or null unless
/// that compaction is still running.
///
/// The winning record is the last one in transcript order, not the last running
/// one: a later terminal update supersedes an earlier running update. Otherwise
/// a stale id could keep a notice (and suppress the empty state) after the
/// transcript already reports the compaction ended.
String? chatRunningCompaction(List<JsonMap> messages) {
JsonMap? latest;
for (final message in messages) {
if (message['role'] != 'assistant') continue;
for (final part in (message['parts'] as List? ?? const [])) {
if (part is! Map) continue;
final record = Map<String, dynamic>.from(part);
if (!chatActivityType(record)) continue;
if (chatActivityKind(record).toLowerCase() != 'compaction') continue;
latest = record;
}
}
if (latest == null) return null;
if (chatActivityState(latest).toLowerCase() != 'running') return null;
return '${latest['id'] ?? ''}';
}
/// The recorded condition of the running compaction that [row] presents, or
/// null when the row is not a running compaction's activity line.
///
/// That line is the compaction notice drawn in place, not a second copy of it.
/// The view compares this with the notice's own [ChatNotice.condition], so a
/// dismissal hides the compaction the operator named, not every running
/// compaction in the transcript.
String? chatNoticeActivityCondition(JsonMap row) {
if ('${row['kind'] ?? ''}' != 'activity') return null;
final records = row['records'];
if (records is List && records.isNotEmpty) {
for (final record in records.reversed) {
if (record is! Map) continue;
final latest = Map<String, dynamic>.from(record);
if (chatActivityKind(latest).toLowerCase() != 'compaction') return null;
if (chatActivityState(latest).toLowerCase() != 'running') return null;
return chatCompactionCondition('${latest['id'] ?? ''}');
}
return null;
}
// A caller-built row carries the same fields instead of records.
if (chatActivityKind(row).toLowerCase() != 'compaction') return null;
if (chatActivityState(row).toLowerCase() != 'running') return null;
return chatCompactionCondition('${row['id'] ?? ''}');
}
/// The operator's dismissals for one open conversation.
///
/// A dismissal is keyed by the notice's recorded condition. It hides that
/// notice while the same condition stays recorded, and is forgotten as soon as
/// the condition is absent or changes — so a recurrence shows again. A
/// reconnect calls [clear], because a gap can leave an old dismissal behind.
class ChatNoticeDismissals {
final Set<String> _dismissed = <String>{};
/// The notices still shown, in order. Conditions that are no longer recorded
/// are pruned here, so a later recurrence is a new notice.
List<ChatNotice> visible(List<ChatNotice> notices) {
final recorded = {for (final notice in notices) notice.condition};
_dismissed.retainAll(recorded);
return [
for (final notice in notices)
if (!_dismissed.contains(notice.condition)) notice,
];
}
/// Hide [notice] until its recorded condition changes.
void dismiss(ChatNotice notice) => _dismissed.add(notice.condition);
/// Whether [condition] is currently hidden. Used for a running compaction's
/// own activity line, which is the same notice drawn in place.
bool isDismissed(String condition) => _dismissed.contains(condition);
/// Forget every dismissal (a reconnect or a different conversation).
void clear() => _dismissed.clear();
}