Chat: answered questions collapse into their turn like tool calls

This commit is contained in:
2026-11-03 19:31:40 +00:00
parent fa6c0864db
commit fc94210595
14 changed files with 760 additions and 38 deletions
@@ -215,11 +215,7 @@ class _ChatQuestionCardState extends State<ChatQuestionCard> {
String _statusLine() {
if (_pending) return chatQuestionWaiting;
if (widget.form['cancelled'] == true) return chatQuestionExpired;
final answers = widget.form['answers'];
return answers is Map && answers.isNotEmpty
? chatQuestionAnswered
: chatQuestionClosed;
return chatQuestionSettledStatus(widget.form);
}
String get _submitLabel {
@@ -132,6 +132,15 @@ String chatQuestionOptionLabel(JsonMap option) {
bool chatFormPending(JsonMap form) =>
form['resolved'] != true && form['cancelled'] != true;
/// How a settled form ended: expired, answered, or closed without an answer.
String chatQuestionSettledStatus(JsonMap form) {
if (form['cancelled'] == true) return chatQuestionExpired;
final answers = form['answers'];
return answers is Map && answers.isNotEmpty
? chatQuestionAnswered
: chatQuestionClosed;
}
/// True when an external form URL is one this app can safely show. Mirrors the
/// web's `safeFormURL`: an absolute HTTP(S) URL with a real host and no spaces.
bool chatExternalUrlIsSafe(String raw) {
@@ -145,21 +154,34 @@ bool chatExternalUrlIsSafe(String raw) {
/// Fold one `form` frame into the retained forms, keyed by id. A resolved or
/// cancelled update keeps the recorded answers so the card can show them
/// read-only instead of dropping evidence.
///
/// [raisedIn] is recorded as [chatQuestionRaisedIn] only on the form's first
/// frame: a later resolution arrives during another message and must not move
/// the question.
Map<String, JsonMap> chatFoldQuestionFrame(
Map<String, JsonMap> current,
JsonMap? form,
) {
JsonMap? form, {
String? raisedIn,
}) {
if (form == null) return current;
final id = _text(form['id']);
if (id.isEmpty) return current;
final existing = current[id];
final next = <String, JsonMap>{...current};
final anchor = _text(raisedIn);
next[id] = existing == null
? Map<String, dynamic>.from(form)
? {
...Map<String, dynamic>.from(form),
if (anchor.isNotEmpty) chatQuestionRaisedIn: anchor,
}
: {...existing, ...Map<String, dynamic>.from(form)};
return next;
}
/// Client-only form key: the agent message id the question was raised during.
/// The server never sends it, so folding a frame never overwrites it.
const chatQuestionRaisedIn = 'raised_in_message_id';
/// A stable id for one confirmed answer action on a form. Reusing the same id
/// across a retry lets the send gate recognise a double tap.
String chatQuestionReplyId(String formId, {String action = ''}) =>
@@ -0,0 +1,211 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../ui/sessions/chat_adaptive.dart';
import '../ui/transcript/chat_turn_chip.dart';
import 'chat_card_styles.dart';
import 'chat_question_card_model.dart';
import 'chat_question_recorded_answers.dart';
/// The settled form of [row], a question card row; null while it still needs
/// the operator or its last answer was refused.
JsonMap? _settled(JsonMap row) {
if (row['kind'] != 'question') return null;
if ('${row['error'] ?? ''}'.trim().isNotEmpty) return null;
final form = row['form'];
if (form is! Map) return null;
final converted = Map<String, dynamic>.from(form);
return chatFormPending(converted) ? null : converted;
}
/// Folds answered and expired question cards out of the card list, the way a
/// turn's tool calls fold into one chip.
///
/// A settled question joins the agent turn it was raised during (the
/// [chatQuestionRaisedIn] message id) as that row's `questions`. Questions
/// naming no turn in view share one `questions` row where the first stood.
/// Pending questions, and ones whose answer was refused, stay full cards.
List<JsonMap> groupSettledQuestions(List<JsonMap> rows) {
final result = <JsonMap>[];
final attached = <int, List<JsonMap>>{};
final loose = <JsonMap>[];
int? looseAt;
for (final row in rows) {
final form = _settled(row);
if (form == null) {
result.add(row);
continue;
}
final turn = _turnOf(result, '${form[chatQuestionRaisedIn] ?? ''}'.trim());
if (turn != null) {
attached.putIfAbsent(turn, () => []).add(form);
} else {
looseAt ??= result.length;
loose.add(form);
}
}
for (final entry in attached.entries) {
result[entry.key] = {...result[entry.key], 'questions': entry.value};
}
if (looseAt != null) {
result.insert(looseAt, {
'kind': 'questions',
'key': 'chat-questions-${loose.first['id']}',
'questions': loose,
});
}
return result;
}
int? _turnOf(List<JsonMap> rows, String messageId) {
if (messageId.isEmpty) return null;
for (var index = rows.length - 1; index >= 0; index--) {
final row = rows[index];
final ids = row['messageIds'];
if (row['kind'] == 'assistant' && ids is List && ids.contains(messageId)) {
return index;
}
}
return null;
}
/// The settled forms a row carries (a turn's or a loose `questions` row's).
List<JsonMap> chatRowQuestions(JsonMap row) {
final questions = row['questions'];
if (questions is! List) return const [];
return [
for (final form in questions)
if (form is Map) Map<String, dynamic>.from(form),
];
}
/// The collapsed line for one settled question: the question and its outcome,
/// `Which database? · Postgres`, `… · +1 more` when several were answered.
String chatQuestionSummary(JsonMap form) {
final fields = chatFormFields(form);
final answers = form['answers'] is Map
? Map<String, dynamic>.from(form['answers'] as Map)
: <String, dynamic>{};
final title = '${form['title'] ?? ''}'.trim();
String question = title.isEmpty ? 'Question' : title;
if (fields.isNotEmpty) {
question = chatQuestionFieldLabel(
fields.first,
'${fields.first['key'] ?? ''}'.trim(),
);
}
if (form['cancelled'] == true) return '$question · Expired';
final answered = [
for (final field in fields)
if (answers.containsKey('${field['key'] ?? ''}'.trim())) field,
];
if (answered.isEmpty) {
return answers.isEmpty ? '$question · Closed' : '$question · Answered';
}
final first = answered.first;
final key = '${first['key'] ?? ''}'.trim();
final more = answers.length - 1;
return [
chatQuestionFieldLabel(first, key),
chatQuestionAnswerText(first, answers[key]),
if (more > 0) '+$more more',
].join(' · ');
}
/// One settled question as the quiet chip a turn's tools use. It opens a
/// native sheet with the full question and the recorded answers.
class ChatQuestionChip extends StatelessWidget {
const ChatQuestionChip({super.key, required this.form});
final JsonMap form;
@override
Widget build(BuildContext context) {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final color = cupertino
? CupertinoColors.secondaryLabel.resolveFrom(context)
: Theme.of(context).colorScheme.onSurfaceVariant;
final label = chatQuestionSummary(form);
return ChatTurnChip(
chipKey: ValueKey<String>('chat-question-chip-${form['id']}'),
leading: Icon(
cupertino ? CupertinoIcons.question_circle : Icons.help_outline,
size: 14,
color: color,
),
label: label,
color: color,
ellipsizeLabel: true,
semanticsLabel: 'Question: $label, expand for details',
sheet: _QuestionSheet(form: form),
);
}
}
/// The chips for [row]'s settled questions, one per question.
List<Widget> chatQuestionChips(JsonMap row) => [
for (final form in chatRowQuestions(row)) ChatQuestionChip(form: form),
];
/// A loose `questions` row: its chips on the agent's side.
class ChatQuestionsRow extends StatelessWidget {
const ChatQuestionsRow({super.key, required this.row});
final JsonMap row;
@override
Widget build(BuildContext context) => Align(
alignment: AlignmentDirectional.centerStart,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: chatQuestionChips(row),
),
);
}
class _QuestionSheet extends StatelessWidget {
const _QuestionSheet({required this.form});
final JsonMap form;
@override
Widget build(BuildContext context) {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final style = cupertino
? CupertinoTheme.of(context).textTheme.textStyle
: Theme.of(context).textTheme.bodyMedium;
final title = '${form['title'] ?? ''}'.trim();
return DefaultTextStyle.merge(
style: style,
child: ConstrainedBox(
constraints: BoxConstraints(
maxHeight: MediaQuery.sizeOf(context).height * 0.8,
),
child: ListView(
key: const Key('chat-question-sheet'),
shrinkWrap: true,
padding: const EdgeInsets.fromLTRB(16, 8, 16, 16),
children: [
Text(
title.isEmpty ? 'Question' : title,
style: chatCardTitleStyle(context, cupertino),
),
Text(
chatQuestionSettledStatus(form),
style: chatCardSecondaryStyle(context, cupertino),
),
...chatQuestionRecordedAnswers(
context: context,
form: form,
cupertino: cupertino,
),
],
),
),
);
}
}
@@ -24,8 +24,8 @@ List<Widget> chatQuestionRecordedAnswers({
widgets.add(
_recorded(
context,
_fieldLabel(field, key),
_answerText(field, answers[key]),
chatQuestionFieldLabel(field, key),
chatQuestionAnswerText(field, answers[key]),
cupertino,
),
);
@@ -33,7 +33,12 @@ List<Widget> chatQuestionRecordedAnswers({
for (final entry in answers.entries) {
if (shown.contains(entry.key)) continue;
widgets.add(
_recorded(context, entry.key, _answerText(null, entry.value), cupertino),
_recorded(
context,
entry.key,
chatQuestionAnswerText(null, entry.value),
cupertino,
),
);
}
if (widgets.isEmpty) {
@@ -49,7 +54,7 @@ List<Widget> chatQuestionRecordedAnswers({
/// The field's display label, falling back past blank recorded strings the same
/// way the pending field does.
String _fieldLabel(JsonMap field, String key) {
String chatQuestionFieldLabel(JsonMap field, String key) {
for (final candidate in [field['title'], field['description']]) {
final text = '${candidate ?? ''}'.trim();
if (text.isNotEmpty) return text;
@@ -74,7 +79,8 @@ Widget _recorded(
),
);
String _answerText(JsonMap? field, Object? value) {
/// A recorded answer as display text: option labels, Yes/No, list joined.
String chatQuestionAnswerText(JsonMap? field, Object? value) {
final values = value is List ? value : [value];
final boolean = field != null && '${field['type'] ?? ''}' == 'boolean';
return values
@@ -10,7 +10,8 @@ import 'chat_question_card_model.dart';
/// gates, so the controller itself stays about messages and live turn state.
///
/// The web drops an approval or form once it is resolved. This app keeps the
/// latest settled cards as read-only evidence, which is an intentional addition;
/// latest settled cards as read-only evidence, collapsed into their turn like
/// tool calls (see `chat_permission_group.dart`, `chat_question_group.dart`);
/// [settledLimit] bounds that history so a long session cannot grow without
/// limit while pending cards are never dropped.
class ChatThreadCards {
@@ -136,11 +137,12 @@ class ChatThreadCards {
}
/// Fold one `form` event. A folded update keeps a settled form's recorded
/// answers for the read-only card.
void foldForm(JsonMap form) {
/// answers for the collapsed row. [raisedIn] is the agent message the first
/// frame arrived during; it places the answered question in its turn.
void foldForm(JsonMap form, {String? raisedIn}) {
final id = '${form['id'] ?? ''}'.trim();
if (id.isEmpty) return;
final next = chatFoldQuestionFrame(_forms, form);
final next = chatFoldQuestionFrame(_forms, form, raisedIn: raisedIn);
if (identical(next, _forms)) return;
_forms
..clear()
@@ -369,7 +369,10 @@ class ChatThreadController extends ChangeNotifier {
if (body['kind'] == 'form') {
final form = body['form'];
if (form is! Map) return;
_cards.foldForm(Map<String, dynamic>.from(form));
_cards.foldForm(
Map<String, dynamic>.from(form),
raisedIn: _answeringMessageId(),
);
return;
}
final current = _thread;
@@ -415,6 +418,21 @@ class ChatThreadController extends ChangeNotifier {
].any((key) => usage[key] != null);
}
/// The agent message a question frame arrives during: the streamed reply,
/// else the last answer when it is the agent's. A question raised before the
/// reply starts names none rather than an older turn.
String? _answeringMessageId() {
final live = _liveAssistantMessageId;
if (live != null && live.isNotEmpty) return live;
for (final message in _messages.reversed) {
if (chatInjectedKind(message) != null) continue;
if (message['role'] != 'assistant') return null;
final id = '${message['id'] ?? ''}'.trim();
return id.isEmpty ? null : id;
}
return null;
}
/// The pushed envelope body, or null for another message type. The server
/// wraps `chat_event` in the typed envelope; domain code never sees the
/// transport fields.
@@ -52,6 +52,7 @@ import 'chat_transcript_cache.dart';
import 'chat_transcript_scroll_view.dart';
import 'chat_permission_card_model.dart';
import 'chat_permission_group.dart';
import 'chat_question_group.dart';
import 'chat_transcript_card.dart';
/// One read-only conversation: the controller's transcript in the order the
@@ -851,22 +852,25 @@ class _ChatThreadViewState extends State<ChatThreadView> {
permissionErrorFor: _controller.permissionErrorFor,
formErrorFor: _controller.questionErrorFor,
);
// Answered approvals fold into their turn's chips, like tool calls.
final allRows = groupSettledPermissions(
transcriptRows(
messages,
trailing: cards,
running:
_controller.running &&
!_reconnecting &&
!_staleTranscript &&
!cards.any(chatCardAwaitingOperator),
awaitingResponse:
_controller.awaitingResponse &&
!_reconnecting &&
!_staleTranscript &&
!cards.any(chatCardAwaitingOperator),
liveMessageId: _controller.liveAssistantMessageId,
// Answered approvals and questions fold into their turn's chips, like
// tool calls; only cards still waiting on the operator stay full cards.
final allRows = groupSettledQuestions(
groupSettledPermissions(
transcriptRows(
messages,
trailing: cards,
running:
_controller.running &&
!_reconnecting &&
!_staleTranscript &&
!cards.any(chatCardAwaitingOperator),
awaitingResponse:
_controller.awaitingResponse &&
!_reconnecting &&
!_staleTranscript &&
!cards.any(chatCardAwaitingOperator),
liveMessageId: _controller.liveAssistantMessageId,
),
),
);
// A transcript held from before a socket gap may still say a compaction is
@@ -1262,6 +1266,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
}
if (kind == 'system_notice') return ChatSystemNoticeLine(row: row);
if (kind == 'task_notices') return ChatTaskNoticesGroup(row: row);
if (kind == 'questions') return ChatQuestionsRow(row: row);
if (kind == 'permission' || kind == 'question') {
return ChatTranscriptCard(
row: row,
@@ -1273,6 +1278,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
final chips = [
if (permissions is List<ChatPermissionCardData> && permissions.isNotEmpty)
ChatPermissionsChip(permissions: permissions),
...chatQuestionChips(row),
];
if (kind == 'permissions') {
return Align(
@@ -14,6 +14,7 @@ class ChatTurnChip extends StatelessWidget {
required this.color,
required this.semanticsLabel,
required this.sheet,
this.ellipsizeLabel = false,
});
final Key chipKey;
@@ -23,6 +24,10 @@ class ChatTurnChip extends StatelessWidget {
final String semanticsLabel;
final Widget sheet;
/// Shrink a long label to one ellipsized line. Only for a chip whose parent
/// bounds its width (a turn footer's Wrap, an aligned row).
final bool ellipsizeLabel;
@override
Widget build(BuildContext context) {
final cupertino =
@@ -32,7 +37,10 @@ class ChatTurnChip extends StatelessWidget {
children: [
leading,
const SizedBox(width: 6),
Text(label, style: TextStyle(color: color, fontSize: 13)),
if (ellipsizeLabel)
Flexible(child: _label(maxLines: 1, overflow: TextOverflow.ellipsis))
else
_label(),
Icon(
cupertino ? CupertinoIcons.chevron_up : Icons.expand_less,
size: 14,
@@ -73,6 +81,13 @@ class ChatTurnChip extends StatelessWidget {
);
}
Text _label({int? maxLines, TextOverflow? overflow}) => Text(
label,
maxLines: maxLines,
overflow: overflow,
style: TextStyle(color: color, fontSize: 13),
);
Future<void> _open(BuildContext context, bool cupertino) {
if (cupertino) {
return showCupertinoModalPopup<void>(
+46
View File
@@ -0,0 +1,46 @@
# Answered questions collapse into their turn like tool calls
User report: after replying to a harness question (OpenCode question tool,
Claude Code AskUserQuestion, Codex elicitation) the question card stays at the
bottom of the chat. Follow-up: it should collapse like tool calls.
## Root cause
Not a missed server event. The reply's ack already marked the form resolved
locally (`ChatThreadCards.answerQuestion`), and OpenCode/Codex resolution
frames folded correctly. But every retained form, settled or not, was still
rendered as a full card in the transcript's `trailing` rows
(`chatCardRows` -> `transcriptRows(trailing:)`), so an answered question stayed
as an "Answer recorded." card pinned after the last message. Narrow and wide
used the same rows; on a phone the card simply covers more of the screen.
## Behavior now
- Pending questions, and ones whose answer was refused (with the server's
reason), stay full interactive cards.
- Once the reply is acknowledged (Claude Code: the ack is the only prompt
signal; the server's readback resolution comes later) or the server sends a
resolved/cancelled `form` frame (OpenCode `form.replied`/`form.cancelled`,
Codex), the card leaves the card list and becomes a `ChatTurnChip` in the
footer of the agent turn it arrived during, beside `N tools`:
`Which database? · Postgres` (`· Expired`, `· Closed`, `· +N more`). It opens
a native sheet with the title, status and full recorded answers.
`groupSettledQuestions` in `lib/features/chat/conversation/chat_question_group.dart`.
- Forms carry no turn id, so the client stamps the agent message streaming
when the first frame arrives (`raised_in_message_id`, client-only). A question
with no turn in view shares one loose `questions` row where it stood.
- Forms are not part of stored history and the server replays only pending
ones, so after a reload an answered question is gone (its tool call remains
in the turn's tools chip).
## Evidence
- Tests: `test/features/chat/conversation/chat_question_group_test.dart`
(grouping, summary, narrow 390x844 and wide 1280x900 ack collapse, refusal
keeps the card, OpenCode/Codex resolution frame, cancel, ack plus
form.replied, Cupertino, stale pending replay, remount). The full
`test/features/chat` suite passes; `flutter analyze` is clean.
- Browser: fixture option `?question=claude|opencode|fail`
(`tool/perf/chat_question_fixture.dart`). Before/after captures at 560x1000
and 1280x800 under `build/cq/out/`.
- Not deployed, no device verification.
@@ -488,7 +488,9 @@ void main() {
});
held.complete(const {});
await tester.pumpAndSettle();
expect(find.text(chatQuestionAnswered), findsOneWidget);
// The answered question leaves the card list (chat_question_group_test).
expect(find.text(chatQuestionWaiting), findsNothing);
expect(find.text('Colour · Red · +1 more'), findsOneWidget);
});
testWidgets('a refused question keeps the card open with the server reason', (
@@ -0,0 +1,301 @@
import 'dart:async';
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_question_card_model.dart';
import 'package:pipelines_app/features/chat/conversation/chat_question_group.dart';
import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart';
import 'chat_thread_fixtures.dart';
JsonMap _turn(String id) => {
'kind': 'assistant',
'key': id,
'messageIds': [id],
'parts': const [],
};
JsonMap _card(
String id, {
String? raisedIn,
bool resolved = false,
bool cancelled = false,
String? error,
}) => {
'kind': 'question',
'key': 'chat-question-$id',
'form': {
'id': id,
'resolved': resolved,
'cancelled': cancelled,
chatQuestionRaisedIn: ?raisedIn,
},
'error': error,
};
JsonMap _form({String id = 'form-1'}) => {
'id': id,
'session_id': 's',
'kind': 'question',
'title': 'Database',
'fields': [
{
'key': 'q0',
'title': 'Which database?',
'type': 'string',
'required': true,
'options': [
{'value': 'pg', 'label': 'Postgres'},
{'value': 'lite', 'label': 'SQLite'},
],
},
],
};
const _chip = 'Which database? · Postgres';
/// A chat whose agent turn `a1` is the one the question arrives during.
Future<FakeChatGateway> _open(
WidgetTester tester,
Size size, {
bool cupertino = false,
}) async {
await tester.binding.setSurfaceSize(size);
addTearDown(() => tester.binding.setSurfaceSize(null));
final gateway = FakeChatGateway()
..history = (_) async => chatPage([
chatMessage(
'u1',
'user',
parts: [
{'type': 'text', 'text': 'Ship the release.'},
],
),
chatMessage(
'a1',
'assistant',
parts: [
{'type': 'text', 'text': 'Which database first?'},
],
),
]);
addTearDown(gateway.close);
final view = ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {});
await tester.pumpWidget(
cupertino
? CupertinoApp(home: CupertinoPageScaffold(child: view))
: MaterialApp(home: Scaffold(body: view)),
);
await tester.pumpAndSettle();
gateway.emitEvent({'session_id': 's', 'kind': 'form', 'form': _form()});
await tester.pumpAndSettle();
expect(find.text(chatQuestionWaiting), findsOneWidget);
return gateway;
}
Future<void> _answerPostgres(WidgetTester tester) async {
await tester.tap(find.text('Postgres'));
await tester.pump();
await tester.tap(find.text(chatQuestionSubmit));
await tester.pumpAndSettle();
}
void _expectCollapsed() {
expect(find.text(chatQuestionWaiting), findsNothing);
expect(find.text(chatQuestionSubmit), findsNothing);
expect(find.text(chatQuestionAnswered), findsNothing);
expect(find.text(_chip), findsOneWidget);
// The chip sits in its turn's footer, under the turn that asked.
expect(
find.descendant(
of: find.byKey(const Key('chat-message-footer')),
matching: find.text(_chip),
),
findsOneWidget,
);
}
void main() {
test('settled questions join the turn they were raised during', () {
final rows = groupSettledQuestions([
_turn('m1'),
_turn('m2'),
_card('a', raisedIn: 'm1', resolved: true),
_card('b', raisedIn: 'm2', cancelled: true),
]);
expect(rows.map((r) => r['kind']), ['assistant', 'assistant']);
expect(chatRowQuestions(rows[0]).map((f) => f['id']), ['a']);
expect(chatRowQuestions(rows[1]).map((f) => f['id']), ['b']);
});
test('questions naming no turn share one row; open ones stay cards', () {
final rows = groupSettledQuestions([
_turn('m1'),
_card('loose-1', resolved: true),
_card('pending', raisedIn: 'm1'),
_card('refused', raisedIn: 'm1', error: 'no longer awaiting'),
_card('loose-2', raisedIn: 'paged-out', resolved: true),
]);
expect(rows.map((r) => r['kind']), [
'assistant',
'questions',
'question',
'question',
]);
expect(rows[0].containsKey('questions'), isFalse);
expect(chatRowQuestions(rows[1]).map((f) => f['id']), [
'loose-1',
'loose-2',
]);
});
test('the summary names the question and its outcome', () {
final form = _form();
expect(
chatQuestionSummary({
...form,
'resolved': true,
'answers': {'q0': 'pg'},
}),
_chip,
);
expect(
chatQuestionSummary({
...form,
'resolved': true,
'answers': {'q0': 'pg', 'extra': 'x'},
}),
'$_chip · +1 more',
);
expect(
chatQuestionSummary({...form, 'cancelled': true}),
'Which database? · Expired',
);
expect(
chatQuestionSummary({...form, 'resolved': true}),
'Which database? · Closed',
);
});
for (final (name, size) in [
('narrow', const Size(390, 844)),
('wide', const Size(1280, 900)),
]) {
testWidgets('$name: an acknowledged answer collapses into its turn at once '
'(Claude Code: the ack is the only signal)', (tester) async {
final gateway = await _open(tester, size);
final held = Completer<JsonMap>();
gateway.answer = (_) => held.future;
await tester.tap(find.text('Postgres'));
await tester.pump();
await tester.tap(find.text(chatQuestionSubmit));
await tester.pump();
// Still the card while the reply is in flight.
expect(find.text(chatQuestionWaiting), findsOneWidget);
held.complete(const {'type': 'chat_answer'});
await tester.pumpAndSettle();
_expectCollapsed();
// A late replay of the pending frame cannot reopen it.
gateway.emitEvent({'session_id': 's', 'kind': 'form', 'form': _form()});
await tester.pumpAndSettle();
_expectCollapsed();
await tester.tap(find.text(_chip));
await tester.pumpAndSettle();
expect(find.byKey(const Key('chat-question-sheet')), findsOneWidget);
expect(find.text('Which database?'), findsOneWidget);
expect(find.text('Postgres'), findsOneWidget);
expect(find.text(chatQuestionAnswered), findsOneWidget);
expect(tester.takeException(), isNull);
});
testWidgets('$name: a refused answer keeps the full card with the reason', (
tester,
) async {
final gateway = await _open(tester, size);
gateway.answer = (_) async =>
throw StateError('the question is no longer awaiting an answer');
await _answerPostgres(tester);
expect(find.textContaining('no longer awaiting'), findsOneWidget);
expect(find.text(chatQuestionWaiting), findsOneWidget);
expect(find.text(chatQuestionSubmit), findsOneWidget);
expect(find.text(_chip), findsNothing);
});
}
testWidgets('OpenCode/Codex: the server resolution collapses a question '
'answered elsewhere', (tester) async {
final gateway = await _open(tester, const Size(390, 844));
gateway.emitEvent({
'session_id': 's',
'kind': 'form',
'form': {'id': 'form-1', 'session_id': 's', 'resolved': true},
});
await tester.pumpAndSettle();
expect(find.text(chatQuestionWaiting), findsNothing);
expect(find.text('Which database? · Closed'), findsOneWidget);
});
testWidgets('a cancelled question collapses as expired', (tester) async {
final gateway = await _open(tester, const Size(390, 844));
gateway.emitEvent({
'session_id': 's',
'kind': 'form',
'form': {'id': 'form-1', 'session_id': 's', 'cancelled': true},
});
await tester.pumpAndSettle();
expect(find.text(chatQuestionWaiting), findsNothing);
expect(find.text('Which database? · Expired'), findsOneWidget);
});
testWidgets('OpenCode: ack then form.replied leaves one collapsed row', (
tester,
) async {
final gateway = await _open(tester, const Size(390, 844));
gateway.answer = (_) async {
gateway.emitEvent({
'session_id': 's',
'kind': 'form',
'form': {'id': 'form-1', 'session_id': 's', 'resolved': true},
});
return const {'type': 'chat_answer'};
};
await _answerPostgres(tester);
_expectCollapsed();
});
testWidgets('Cupertino: the answered question collapses to the native chip', (
tester,
) async {
final gateway = await _open(tester, const Size(390, 844), cupertino: true);
gateway.answer = (_) async => const {'type': 'chat_answer'};
await _answerPostgres(tester);
_expectCollapsed();
expect(tester.takeException(), isNull);
});
testWidgets('after a reload the answered question stays gone', (
tester,
) async {
final gateway = await _open(tester, const Size(390, 844));
gateway.answer = (_) async => const {'type': 'chat_answer'};
await _answerPostgres(tester);
_expectCollapsed();
// A fresh view over the same server: the subscribe replays only pending
// forms, and this one is no longer pending.
await tester.pumpWidget(const SizedBox());
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}),
),
),
);
await tester.pumpAndSettle();
expect(find.text('Which database first?'), findsOneWidget);
expect(find.text(chatQuestionWaiting), findsNothing);
});
}
+86
View File
@@ -0,0 +1,86 @@
// An agent question for captures over the full-app fixture's `?chats=N`
// sessions (tool/perf/perf_fixture.dart). Off by default.
//
// `?question=opencode` 1.5 s after a chat subscribes, a pending question
// form arrives; chat_answer is acknowledged and then
// the server's `form.replied` resolution frame follows
// (OpenCode);
// `?question=claude` the same, but only the reply ack settles it (Claude
// Code's AskUserQuestion: the resolution comes later
// from the server's readback);
// `?question=fail` chat_answer is refused, so the card must stay.
import 'dart:async';
import 'package:pipelines_app/core/api_gateway.dart';
Map<String, String> _params = const {};
void configureChatQuestionFixture(Map<String, String> params) =>
_params = params;
String get _mode => _params['question'] ?? '';
JsonMap _event(String sessionId, JsonMap body) => {
'type': 'chat_event',
'chat_event': {'session_id': sessionId, ...body},
};
/// Pushes the pending question into [sessionId] through [emit].
void chatQuestionStream(String sessionId, void Function(JsonMap frame) emit) {
if (_mode.isEmpty) return;
Timer(const Duration(milliseconds: 1500), () {
emit(
_event(sessionId, {
'kind': 'form',
'form': {
'id': '$sessionId-question',
'session_id': sessionId,
'kind': 'question',
'title': 'Database',
'fields': [
{
'key': 'q0',
'title': 'Which database should the release use?',
'type': 'string',
'required': true,
'options': [
{'value': 'Postgres', 'label': 'Postgres'},
{'value': 'SQLite', 'label': 'SQLite'},
],
},
],
},
}),
);
});
}
/// The chat_answer reply, or null when `?question=` is off.
JsonMap? chatQuestionReply(JsonMap request) {
if (_mode.isEmpty || request['type'] != 'chat_answer') return null;
final id = request['id'];
if (_mode == 'fail') {
return {
'id': id,
'type': 'error',
'error': 'the question is no longer awaiting an answer',
};
}
return {'id': id, 'type': 'chat_answer'};
}
/// The OpenCode resolution frame that follows an accepted answer.
List<JsonMap> chatQuestionFollowUps(JsonMap request) {
if (_mode != 'opencode' || request['type'] != 'chat_answer') {
return const [];
}
final body = request['chat_answer'];
if (body is! Map) return const [];
final session = '${body['session_id'] ?? ''}';
return [
_event(session, {
'kind': 'form',
'form': {'id': body['form_id'], 'session_id': session, 'resolved': true},
}),
];
}
+7
View File
@@ -12,11 +12,13 @@
// them, and keeps colours picked with chat_color;
// `?msgs=`, `?rich=1`, `?older=1`, `?live=N` vary the chat transcripts for
// scroll captures (tool/perf/chat_scroll_fixture.dart).
// `?question=` pushes an agent question (tool/perf/chat_question_fixture.dart).
// `/new` in a fixture chat moves it to a fresh, empty session
// (tool/perf/chat_new_session_fixture.dart).
import 'package:pipelines_app/core/api_gateway.dart';
import 'chat_new_session_fixture.dart';
import 'chat_question_fixture.dart';
import 'chat_scroll_fixture.dart';
Map<String, String> _params = const {};
@@ -25,6 +27,7 @@ Map<String, String> _params = const {};
void configurePerfFixture(Map<String, String> params) {
_params = params;
configureChatScrollFixture(params);
configureChatQuestionFixture(params);
}
int get _hits => int.tryParse(_params['hits'] ?? '') ?? 0;
@@ -91,6 +94,8 @@ bool get _scrollVariety => ['msgs', 'rich', 'older'].any(_params.containsKey);
/// Unsolicited envelopes that follow a reply: the `?quota=` usage frame.
List<JsonMap> perfChatFollowUps(JsonMap request) {
final answered = chatQuestionFollowUps(request);
if (answered.isNotEmpty) return answered;
final quota = _params['quota'];
if (_chats == 0 || quota == null || request['type'] != 'chat_subscribe') {
return const [];
@@ -189,6 +194,8 @@ String _answer(int i) =>
/// Chat replies for `?chats=N`, or null to fall through to the fixture.
JsonMap? perfChatReply(JsonMap request) {
if (_chats == 0) return null;
final question = chatQuestionReply(request);
if (question != null) return question;
final id = request['id'];
switch ('${request['type']}') {
case 'chat_sessions':
+6 -2
View File
@@ -28,6 +28,7 @@ import 'package:web_socket_channel/web_socket_channel.dart';
import 'fixture_host/fixture_host.dart';
import 'perf/chat_search_fixture.dart';
import 'perf/chat_question_fixture.dart';
import 'perf/chat_scroll_fixture.dart';
import 'perf/perf_fixture.dart';
import 'probe_folder_fixture.dart';
@@ -527,9 +528,12 @@ class _FixtureChannel implements WebSocketChannel {
final followUps = perfChatFollowUps(decoded);
final subscribe = decoded['chat_subscribe'];
if (subscribe is Map) {
chatScrollStream('${subscribe['session_id'] ?? ''}', (frame) {
void emit(JsonMap frame) {
if (!_incoming.isClosed) _incoming.add(jsonEncode(frame));
});
}
chatScrollStream('${subscribe['session_id'] ?? ''}', emit);
chatQuestionStream('${subscribe['session_id'] ?? ''}', emit);
}
if (reply == null && followUps.isEmpty) return;
Future<void>.delayed(const Duration(milliseconds: 120), () {