feat(app): dismiss recorded local chat notices in the thread

Show dismissible notices for refused history reads, refused live watches and a running compaction. A dismissal lasts only while the recorded condition is unchanged; a syncToken gap hides pre-gap notices until fresh state arrives.
This commit is contained in:
2026-10-22 11:10:42 +01:00
parent fc573e8743
commit c1b87dea54
4 changed files with 865 additions and 15 deletions
@@ -5,6 +5,7 @@ import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../domain/chat_activity_detail.dart';
import '../domain/chat_notice.dart';
import '../domain/chat_transcript.dart';
import '../ui/sessions/chat_adaptive.dart';
import '../ui/transcript/chat_markdown_view.dart';
@@ -63,6 +64,25 @@ class _ChatThreadViewState extends State<ChatThreadView> {
late ChatComposerController _composer = _attachComposer();
late ChatRowKeys _rowKeys = ChatRowKeys();
/// Local notices the operator hid; cleared when the conversation or socket
/// changes so a reconnect never keeps a stale dismissal.
ChatNoticeDismissals _dismissals = ChatNoticeDismissals();
/// True while a reconnect repair is in flight: notices recorded before the
/// gap are stale, so none is drawn until the repair reports fresh state.
bool _reconnecting = false;
int _syncGeneration = 0;
/// The transcript held when the socket was replaced. A running state recorded
/// before the gap cannot be trusted again until a fresh read or frame
/// replaces that transcript.
List<JsonMap>? _preGapMessages;
/// The chain that repairs the newest socket gap. A second gap waits for an
/// in-flight repair instead of treating the controller's immediate return as
/// completion, which would expose stale notices mid-repair.
Future<void>? _repair;
/// A sent turn shown before history or a live frame echoes it.
final List<JsonMap> _optimistic = [];
@@ -132,9 +152,38 @@ class _ChatThreadViewState extends State<ChatThreadView> {
_controller = _attach();
_composer = _attachComposer();
_rowKeys = ChatRowKeys();
_dismissals = ChatNoticeDismissals();
_reconnecting = false;
_preGapMessages = null;
_syncGeneration++;
_optimistic.clear();
} else if (oldWidget.syncToken != widget.syncToken) {
unawaited(_controller.resync());
// The socket was replaced: conditions recorded before the gap are stale,
// so no earlier dismissal survives and nothing recorded before the gap is
// painted while the repair runs.
_dismissals.clear();
_preGapMessages = _controller.messages;
_reconnecting = true;
final generation = ++_syncGeneration;
final previous = _repair;
final repair = (previous ?? Future<void>.value())
.then((_) async {
// A newer gap owns the repair; its own step in this chain runs next.
if (!mounted || generation != _syncGeneration) return;
await _controller.resync();
})
.whenComplete(() {
if (!mounted || generation != _syncGeneration) return;
setState(() {
_reconnecting = false;
// A successful repair replaced the transcript with fresh state.
if (!identical(_controller.messages, _preGapMessages)) {
_preGapMessages = null;
}
});
});
_repair = repair;
unawaited(repair);
}
}
@@ -151,6 +200,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
builder: (context, _) {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final messages = _visibleMessages();
final cards = chatCardRows(
permissions: _controller.permissionFrames,
forms: _controller.questionForms,
@@ -162,7 +212,29 @@ class _ChatThreadViewState extends State<ChatThreadView> {
// not generating, so the transcript indicator and its live region stand
// down; the composer's Stop control still follows `running`.
final awaiting = cards.any(chatCardAwaitingOperator);
final rows = transcriptRows(_visibleMessages(), trailing: cards);
final allRows = transcriptRows(messages, trailing: cards);
// A transcript held from before a socket gap may still say a compaction is
// running even when the repair's read is refused. That running state is
// stale, so no compaction notice is derived from it until a fresh read or
// frame replaces the transcript. Fresh failure notices still report.
//
// Notices report recorded conditions only: a refused read/watch and a
// running compaction. A dismissal keeps one hidden until its condition
// changes. A running compaction's own activity line is that notice, so it
// is not drawn twice; hiding it when dismissed is the whole dismissal.
final allNotices = _reconnecting
? const <ChatNotice>[]
: chatNotices(
historyError: _controller.error,
liveError: _controller.subscriptionError,
messages: _staleTranscript ? const [] : _controller.messages,
);
final notices = _dismissals.visible(allNotices);
final compactionNotice = _noticeOf(notices, ChatNoticeKind.compaction);
final rows = [
for (final row in allRows)
if (!_hiddenRunningCompaction(row)) row,
];
// Older pages prepend messages and a live frame can append one, so a
// folded assistant turn's first message id is not a stable identity.
// ChatRowKeys carries a turn's key forward while it still holds any of
@@ -170,6 +242,11 @@ class _ChatThreadViewState extends State<ChatThreadView> {
// across paging and streaming.
final keys = _rowKeys.forRows(rows);
final initialLoad = !_controller.loaded && _controller.loading;
final historyNotice = _noticeOf(
notices,
ChatNoticeKind.connectionRefused,
);
final liveNotice = _noticeOf(notices, ChatNoticeKind.liveFailure);
return Column(
children: [
Expanded(
@@ -230,21 +307,23 @@ class _ChatThreadViewState extends State<ChatThreadView> {
),
),
),
if (_controller.error != null)
ChatErrorNotice(
if (historyNotice != null)
_ChatNoticeLine(
key: const Key('chat-history-error'),
message: 'Chat history unavailable\n${_controller.error}',
notice: historyNotice,
onDismiss: _dismiss,
onRetry: _controller.load,
),
if (_controller.subscriptionError != null)
ChatErrorNotice(
if (liveNotice != null)
_ChatNoticeLine(
key: const Key('chat-live-error'),
message:
'Live updates unavailable\n${_controller.subscriptionError}',
notice: liveNotice,
onDismiss: _dismiss,
onRetry: _controller.resync,
),
if (_controller.loaded &&
rows.isEmpty &&
allRows.isEmpty &&
allNotices.isEmpty &&
_controller.error == null)
const Padding(
key: Key('chat-thread-empty'),
@@ -255,7 +334,15 @@ class _ChatThreadViewState extends State<ChatThreadView> {
Padding(
key: ValueKey<String>(keys[index]),
padding: const EdgeInsets.symmetric(horizontal: 16),
child: _transcriptRow(rows[index]),
child: _transcriptRow(
rows[index],
onDismissCompaction:
compactionNotice != null &&
chatNoticeActivityCondition(rows[index]) ==
compactionNotice.condition
? () => _dismiss(compactionNotice)
: null,
),
),
if (_controller.running && !awaiting)
Padding(
@@ -279,9 +366,41 @@ class _ChatThreadViewState extends State<ChatThreadView> {
},
);
Widget _transcriptRow(JsonMap row) {
ChatNotice? _noticeOf(List<ChatNotice> notices, ChatNoticeKind kind) {
for (final notice in notices) {
if (notice.kind == kind) return notice;
}
return null;
}
/// Whether a running compaction's activity line must stay off screen.
///
/// That line is the compaction notice, so it follows the same conditions: it
/// is hidden while the repair runs, while the held transcript is still the
/// pre-gap one, and when the operator dismissed this exact compaction. A
/// different running compaction in the transcript keeps its own line.
bool _hiddenRunningCompaction(JsonMap row) {
final condition = chatNoticeActivityCondition(row);
if (condition == null) return false;
return _reconnecting ||
_staleTranscript ||
_dismissals.isDismissed(condition);
}
/// Whether the held transcript is still the one recorded before the gap.
bool get _staleTranscript =>
_preGapMessages != null &&
identical(_controller.messages, _preGapMessages);
void _dismiss(ChatNotice notice) {
setState(() => _dismissals.dismiss(notice));
}
Widget _transcriptRow(JsonMap row, {VoidCallback? onDismissCompaction}) {
final kind = '${row['kind'] ?? ''}';
if (kind == 'activity') return _ChatActivityLine(row: row);
if (kind == 'activity') {
return _ChatActivityLine(row: row, onDismiss: onDismissCompaction);
}
if (kind == 'permission' || kind == 'question') {
return ChatTranscriptCard(
row: row,
@@ -312,6 +431,126 @@ class _ChatThreadViewState extends State<ChatThreadView> {
);
}
/// The native dismiss control shared by a local notice and a running
/// compaction's activity line. Material uses a tooltip; Cupertino carries the
/// same accessible name on the wrapping node, since its button has none.
Widget _noticeDismissControl({
required bool cupertino,
required String label,
required Key key,
required VoidCallback onPressed,
}) {
final icon = Icon(cupertino ? CupertinoIcons.xmark_circle_fill : Icons.close);
if (!cupertino) {
return IconButton(
key: key,
tooltip: label,
onPressed: onPressed,
icon: icon,
);
}
return Semantics(
container: true,
button: true,
label: label,
onTap: onPressed,
child: ExcludeSemantics(
child: CupertinoButton(
key: key,
padding: EdgeInsets.zero,
onPressed: onPressed,
child: icon,
),
),
);
}
/// One local failure notice beside the conversation.
///
/// It is never a message bubble and never sent to the agent. The line carries
/// the kind's own words plus the recorded reason, keeps its native Retry and
/// adds a native dismiss control. Colour only repeats the failure state, so the
/// words remain readable without it. A running compaction is a recorded activity
/// line and is dismissed there instead.
class _ChatNoticeLine extends StatelessWidget {
const _ChatNoticeLine({
super.key,
required this.notice,
required this.onDismiss,
this.onRetry,
});
final ChatNotice notice;
final ValueChanged<ChatNotice> onDismiss;
final VoidCallback? onRetry;
@override
Widget build(BuildContext context) {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final theme = Theme.of(context);
final color = cupertino
? CupertinoColors.systemRed.resolveFrom(context)
: theme.colorScheme.error;
final style =
(cupertino
? CupertinoTheme.of(context).textTheme.textStyle
: theme.textTheme.bodyMedium)
?.copyWith(color: color);
final icon = cupertino
? CupertinoIcons.exclamationmark_circle
: Icons.error_outline;
return Padding(
padding: const EdgeInsetsDirectional.fromSTEB(16, 4, 8, 4),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsetsDirectional.only(top: 8),
child: Icon(icon, color: color),
),
const SizedBox(width: 8),
Expanded(
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 8),
child: Semantics(
liveRegion: true,
child: Text(notice.text, style: style),
),
),
),
_dismissControl(cupertino),
],
),
if (onRetry != null)
Align(
alignment: AlignmentDirectional.centerStart,
child: cupertino
? CupertinoButton(
padding: EdgeInsets.zero,
onPressed: onRetry,
child: const Text('Retry'),
)
: TextButton(onPressed: onRetry, child: const Text('Retry')),
),
],
),
);
}
Widget _dismissControl(bool cupertino) {
return _noticeDismissControl(
cupertino: cupertino,
label: chatNoticeDismissLabel(notice.kind),
key: ValueKey<String>('chat-notice-dismiss-${notice.kind.name}'),
onPressed: () => onDismiss(notice),
);
}
}
/// One recorded activity line for a turn.
///
/// The line is a summary of the recorded sequence. Its wording and state come
@@ -321,10 +560,14 @@ class _ChatThreadViewState extends State<ChatThreadView> {
/// input, output, error, duration and edit diff; collapsing restores the single
/// line without touching the turn.
class _ChatActivityLine extends StatefulWidget {
const _ChatActivityLine({required this.row});
const _ChatActivityLine({required this.row, this.onDismiss});
final JsonMap row;
/// Set only for a running compaction, whose line is the local notice the
/// operator can hide until that compaction's condition changes.
final VoidCallback? onDismiss;
@override
State<_ChatActivityLine> createState() => _ChatActivityLineState();
}
@@ -405,6 +648,13 @@ class _ChatActivityLineState extends State<_ChatActivityLine> {
),
),
_toggleControl(cupertino),
if (widget.onDismiss != null)
_noticeDismissControl(
cupertino: cupertino,
label: chatNoticeDismissLabel(ChatNoticeKind.compaction),
key: const ValueKey<String>('chat-notice-dismiss-compaction'),
onPressed: widget.onDismiss!,
),
],
),
if (_expanded) _detail(context, cupertino, secondary),
@@ -0,0 +1,192 @@
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]).
enum ChatNoticeKind { connectionRefused, liveFailure, compaction }
/// 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',
};
/// 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 = '',
});
final ChatNoticeKind kind;
/// 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;
}
/// 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();
}
@@ -137,11 +137,15 @@ String chatActivityState(JsonMap record) {
return '';
}
/// The web's `Compacting context…` phase words. Both this activity line and the
/// local compaction notice use this one constant, so their wording cannot drift.
const String chatCompactionPhaseLabel = 'Compacting context…';
/// The running-phase words shared verbatim with the web's `turnPhaseLabel`.
/// The web clears a compaction on completion/failure, so there is no web copy
/// for a terminal record: those keep the label the server recorded.
const _chatActivityRunningWords = <String, String>{
'compaction': 'Compacting context…',
'compaction': chatCompactionPhaseLabel,
'thinking': 'Thinking…',
'tool': 'Running a tool…',
'waiting': 'Waiting…',
@@ -0,0 +1,404 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart';
import 'package:pipelines_app/features/chat/domain/chat_notice.dart';
import 'package:pipelines_app/features/chat/domain/chat_transcript.dart';
import 'chat_thread_fixtures.dart';
Widget host(Widget child) => MaterialApp(
theme: ThemeData(platform: TargetPlatform.android),
home: Scaffold(body: child),
);
Widget cupertinoHost(Widget child) => CupertinoApp(
theme: const CupertinoThemeData(brightness: Brightness.dark),
home: CupertinoPageScaffold(child: child),
);
JsonMap compactionTurn(
String messageId,
String id, [
String state = 'running',
]) => chatMessage(
messageId,
'assistant',
parts: [
{'type': 'compaction', 'kind': 'compaction', 'id': id, 'status': state},
],
);
JsonMap runningCompaction(String id) => compactionTurn('a1', id);
const compactionDismissKey = ValueKey<String>('chat-notice-dismiss-compaction');
void main() {
test('each recorded condition keeps its own exact wording', () {
final notices = chatNotices(
historyError: 'Bad state: Connection closed',
liveError: 'Exception: live watch refused',
messages: [runningCompaction('c1')],
);
expect(notices, hasLength(3));
expect(notices[0].kind, ChatNoticeKind.connectionRefused);
expect(notices[0].text, 'Chat history unavailable\nConnection closed');
expect(notices[1].kind, ChatNoticeKind.liveFailure);
expect(notices[1].text, 'Live updates unavailable\nlive watch refused');
// The phase words are the web's own (`turnPhaseLabel`).
expect(notices[2].kind, ChatNoticeKind.compaction);
expect(notices[2].text, 'Compacting context…');
expect(notices[2].detail, isEmpty);
expect(
[for (final kind in ChatNoticeKind.values) chatNoticeDismissLabel(kind)],
[
'Dismiss connection notice',
'Dismiss live updates notice',
'Dismiss compaction notice',
],
);
// A later compaction has its own recorded condition.
final next = chatNotices(messages: [runningCompaction('c2')]).single;
expect(next.condition, isNot(notices[2].condition));
});
test('a dismissal hides one condition until that condition changes', () {
final dismissals = ChatNoticeDismissals();
final first = chatNotices(liveError: 'first refusal').single;
expect(dismissals.visible([first]), [first]);
dismissals.dismiss(first);
expect(dismissals.visible([first]), isEmpty);
// The same recorded condition stays hidden.
expect(
dismissals.visible(chatNotices(liveError: 'first refusal')),
isEmpty,
);
// A different recorded reason is a new notice.
final second = dismissals
.visible(chatNotices(liveError: 'second refusal'))
.single;
expect(second.text, 'Live updates unavailable\nsecond refusal');
// A condition that disappears and comes back is recorded afresh.
expect(dismissals.visible(const []), isEmpty);
expect(
dismissals.visible(chatNotices(liveError: 'first refusal')).single.text,
'Live updates unavailable\nfirst refusal',
);
});
test('a reconnect forgets every earlier dismissal', () {
final dismissals = ChatNoticeDismissals();
final notice = chatNotices(historyError: 'Connection closed').single;
dismissals.dismiss(notice);
expect(dismissals.visible([notice]), isEmpty);
dismissals.clear();
expect(dismissals.visible([notice]), [notice]);
});
test('an unchanged transcript invents no notice', () {
expect(chatNotices(), isEmpty);
expect(chatNotices(messages: const []), isEmpty);
expect(
chatNotices(
messages: [
chatMessage(
'a1',
'assistant',
parts: [
{'type': 'text', 'text': 'Just an answer.'},
{'type': 'reasoning', 'text': 'Thinking.'},
{
'type': 'tool',
'state': {'status': 'completed'},
},
],
),
],
),
isEmpty,
);
// A compaction that already ended is recorded history, not a live notice.
expect(
chatNotices(
messages: [
chatMessage(
'a1',
'assistant',
parts: [
{
'type': 'compaction',
'kind': 'compaction',
'id': 'c1',
'status': 'completed',
},
],
),
],
),
isEmpty,
);
});
test('a later terminal record supersedes an earlier running compaction', () {
final messages = [
compactionTurn('a1', 'c1'),
compactionTurn('a2', 'c2', 'completed'),
];
expect(chatRunningCompaction(messages), isNull);
expect(chatNotices(messages: messages), isEmpty);
// The line itself is still the recorded activity: the compaction ended.
expect(transcriptRows(messages).single['state'], 'completed');
expect(
chatNoticeActivityCondition(transcriptRows(messages).single),
isNull,
);
});
test('each running compaction row carries its own notice condition', () {
final rows = transcriptRows([
compactionTurn('a1', 'c1'),
chatMessage('u1', 'user', parts: const []),
compactionTurn('a2', 'c2'),
]);
final conditions = [
for (final row in rows)
if (row['kind'] == 'activity') chatNoticeActivityCondition(row),
];
expect(conditions, ['compaction\nc1', 'compaction\nc2']);
// The transcript's newest running compaction is the one it reports.
expect(
chatNotices(
messages: [
compactionTurn('a1', 'c1'),
chatMessage('u1', 'user', parts: const []),
compactionTurn('a2', 'c2'),
],
).single.condition,
'compaction\nc2',
);
});
testWidgets('the live failure notice has a native dismiss that hides it', (
tester,
) async {
final gateway = FakeChatGateway();
addTearDown(gateway.close);
gateway.subscribe = () async => throw StateError('live watch refused');
gateway.history = (_) async => chatPage(const []);
await tester.pumpWidget(
host(ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {})),
);
await tester.pumpAndSettle();
expect(find.byKey(const Key('chat-live-error')), findsOneWidget);
expect(find.textContaining('live watch refused'), findsOneWidget);
await tester.tap(
find.byKey(const ValueKey<String>('chat-notice-dismiss-liveFailure')),
);
await tester.pump();
expect(find.byKey(const Key('chat-live-error')), findsNothing);
expect(find.textContaining('live watch refused'), findsNothing);
// A later transcript frame changes no condition, so it stays hidden.
gateway.emitEvent(chatTextFrame('An answer.'));
await tester.pumpAndSettle();
expect(find.byKey(const Key('chat-live-error')), findsNothing);
});
testWidgets('a reconnect clears the stale notice and its dismissal', (
tester,
) async {
final gateway = FakeChatGateway();
addTearDown(gateway.close);
gateway.subscribe = () async => throw StateError('live watch refused');
gateway.history = (_) async => chatPage(const []);
await tester.pumpWidget(
host(ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {})),
);
await tester.pumpAndSettle();
await tester.tap(
find.byKey(const ValueKey<String>('chat-notice-dismiss-liveFailure')),
);
await tester.pump();
expect(find.byKey(const Key('chat-live-error')), findsNothing);
// The socket comes back and the watch is accepted: the recorded condition
// is gone, so the old notice cannot linger.
gateway.subscribe = () async => const {};
await tester.pumpWidget(
host(
ChatThreadView(
gateway: gateway,
sessionId: 's',
onBack: () {},
syncToken: 1,
),
),
);
// The pre-gap notice is stale as soon as the socket is replaced.
await tester.pump();
expect(find.byKey(const Key('chat-live-error')), findsNothing);
await tester.pumpAndSettle();
expect(find.byKey(const Key('chat-live-error')), findsNothing);
// A failure recorded after the reconnect is shown again: the old dismissal
// did not survive the gap, even though the words repeat.
gateway.subscribe = () async => throw StateError('live watch refused');
await tester.pumpWidget(
host(
ChatThreadView(
gateway: gateway,
sessionId: 's',
onBack: () {},
syncToken: 2,
),
),
);
await tester.pumpAndSettle();
expect(find.byKey(const Key('chat-live-error')), findsOneWidget);
expect(find.textContaining('live watch refused'), findsOneWidget);
});
testWidgets('a reconnect hides a stale running compaction until fresh state', (
tester,
) async {
final gateway = FakeChatGateway();
addTearDown(gateway.close);
gateway.history = (_) async => chatPage([runningCompaction('c1')]);
await tester.pumpWidget(
host(ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {})),
);
await tester.pumpAndSettle();
expect(find.text('Compacting context…'), findsOneWidget);
await tester.tap(find.byKey(compactionDismissKey));
await tester.pump();
expect(find.text('Compacting context…'), findsNothing);
// The socket is replaced and the repair's history read has not answered:
// the pre-gap running state is stale, and the earlier dismissal does not
// make it visible again.
gateway.history = null;
await tester.pumpWidget(
host(
ChatThreadView(
gateway: gateway,
sessionId: 's',
onBack: () {},
syncToken: 1,
),
),
);
await tester.pump();
expect(find.text('Compacting context…'), findsNothing);
expect(find.byKey(compactionDismissKey), findsNothing);
// The repair reports the same compaction still running: the fresh record
// shows again with its dismiss control; the gap cleared the old dismissal.
gateway.historyRequests.last.complete(chatPage([runningCompaction('c1')]));
await tester.pumpAndSettle();
expect(find.text('Compacting context…'), findsOneWidget);
expect(find.byKey(compactionDismissKey), findsOneWidget);
});
testWidgets('a refused repair keeps the pre-gap compaction hidden', (
tester,
) async {
final gateway = FakeChatGateway();
addTearDown(gateway.close);
gateway.history = (_) async => chatPage([runningCompaction('c1')]);
await tester.pumpWidget(
host(ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {})),
);
await tester.pumpAndSettle();
await tester.tap(find.byKey(compactionDismissKey));
await tester.pump();
expect(find.text('Compacting context…'), findsNothing);
gateway.history = (_) async => throw StateError('history refused');
await tester.pumpWidget(
host(
ChatThreadView(
gateway: gateway,
sessionId: 's',
onBack: () {},
syncToken: 1,
),
),
);
await tester.pumpAndSettle();
// The refused repair is a fresh failure notice; the held transcript's
// running compaction is not painted again as if it were current.
expect(find.byKey(const Key('chat-history-error')), findsOneWidget);
expect(find.textContaining('history refused'), findsOneWidget);
expect(find.text('Compacting context…'), findsNothing);
expect(find.byKey(compactionDismissKey), findsNothing);
});
testWidgets('dismissing one running compaction leaves the other line alone', (
tester,
) async {
final gateway = FakeChatGateway();
addTearDown(gateway.close);
gateway.history = (_) async => chatPage([
compactionTurn('a1', 'c1'),
chatMessage('u1', 'user', parts: const []),
compactionTurn('a2', 'c2'),
]);
await tester.pumpWidget(
host(ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {})),
);
await tester.pumpAndSettle();
expect(find.text('Compacting context…'), findsNWidgets(2));
// Only the transcript's newest running compaction is the reported notice.
expect(find.byKey(compactionDismissKey), findsOneWidget);
await tester.tap(find.byKey(compactionDismissKey));
await tester.pump();
// c2's line is hidden; the separately recorded c1 line keeps its words.
expect(find.text('Compacting context…'), findsOneWidget);
expect(find.byKey(compactionDismissKey), findsNothing);
});
testWidgets('a running compaction notice is native, dismissed and exact', (
tester,
) async {
final gateway = FakeChatGateway();
addTearDown(gateway.close);
gateway.history = (_) async => chatPage([runningCompaction('c1')]);
await tester.pumpWidget(
cupertinoHost(
ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}),
),
);
await tester.pumpAndSettle();
expect(find.byKey(const Key('chat-compaction-notice')), findsNothing);
expect(find.text('Compacting context…'), findsOneWidget);
expect(find.byType(Material), findsNothing);
expect(find.bySemanticsLabel('Dismiss compaction notice'), findsOneWidget);
await tester.tap(
find.byKey(const ValueKey<String>('chat-notice-dismiss-compaction')),
);
await tester.pump();
expect(find.text('Compacting context…'), findsNothing);
});
}