feat(app): native permission and question cards in the chat transcript

This commit is contained in:
2026-10-22 02:01:41 +01:00
parent 38488b7ec7
commit 221a2582dc
24 changed files with 3756 additions and 8 deletions
@@ -0,0 +1,415 @@
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_permission_card.dart';
import 'package:pipelines_app/features/chat/conversation/chat_permission_card_model.dart';
import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart';
import 'chat_thread_fixtures.dart';
Widget materialHost(Widget child) => MaterialApp(
theme: ThemeData(platform: TargetPlatform.android),
home: Scaffold(body: child),
);
Widget scrollHost(Widget child) =>
materialHost(SingleChildScrollView(child: child));
Widget cupertinoHost(Widget child) => CupertinoApp(
theme: const CupertinoThemeData(brightness: Brightness.dark),
home: CupertinoPageScaffold(
child: SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: child,
),
),
);
JsonMap permission({
String id = 'req-1',
String action = 'bash',
List<String> resources = const [
'command: rm -rf build',
'cwd: /workspace/demo',
],
String message = 'This deletes the build output.',
bool resolved = false,
String decision = '',
}) => {
'session_id': 's',
'request_id': id,
'action': action,
'resources': resources,
'message': message,
'source': {'type': 'tool'},
'resolved': resolved,
if (decision.isNotEmpty) 'decision': decision,
};
void main() {
test('recorded action, risk and options survive the card model', () {
final card = chatPermissionCard(permission(), '')!;
expect(card.headline, 'Approve bash');
expect(card.statusLine, chatApprovalStatusPending);
expect(card.risk, 'This deletes the build output.');
expect(card.resources, ['command: rm -rf build', 'cwd: /workspace/demo']);
expect(card.alwaysLabel, 'Always allow');
expect(card.actionable, isTrue);
expect(card.showRisk, isTrue);
});
test('resources keep their recorded indentation and order', () {
final card = chatPermissionCard(
permission(
resources: const [
' cd /workspace/demo',
'command: |\n echo hello',
' ',
],
),
'',
)!;
expect(card.resources, [
' cd /workspace/demo',
'command: |\n echo hello',
]);
expect(
card.resourceText,
' cd /workspace/demo\ncommand: |\n echo hello',
);
});
test('risk falls back to the action and resources cap at six lines', () {
final card = chatPermissionCard(
permission(
message: '',
resources: const [
'one',
'two\nthree',
'four',
'five',
'six',
'seven',
'eight',
],
),
'',
)!;
expect(
card.risk,
'The agent is asking to run bash; review the request before allowing.',
);
expect(card.resourceText.split('\n'), hasLength(6));
expect(card.resourceText.endsWith('…'), isTrue);
expect(card.resources, hasLength(7));
});
test('a server resolution outranks a local answer and a blank decision is '
'stale', () {
final resolved = chatPermissionCard(
permission(
resolved: true,
decision: 'always',
message: 'Another client already allowed this.',
),
'once',
)!;
expect(resolved.state, ChatPermissionState.resolved);
expect(resolved.headline, 'Always allowed');
expect(resolved.statusLine, 'Another client already allowed this.');
expect(resolved.actionable, isFalse);
expect(resolved.showRisk, isFalse);
final stale = chatPermissionCard(
permission(resolved: true, message: ''),
'',
)!;
expect(stale.state, ChatPermissionState.stale);
expect(stale.headline, 'Already resolved');
expect(stale.statusLine, chatApprovalStatusResolved);
expect(stale.actionable, isFalse);
});
test('a rejection keeps the risk panel while answered', () {
final rejected = chatPermissionCard(permission(), 'reject')!;
expect(rejected.state, ChatPermissionState.answered);
expect(rejected.headline, 'Rejected');
expect(rejected.statusLine, chatApprovalStatusAnswered);
expect(rejected.showRisk, isTrue);
expect(rejected.actionable, isFalse);
});
test('one stable reply id per confirmed action', () {
expect(
chatPermissionReplyId('req-1', 'once'),
chatPermissionReplyId('req-1', 'once'),
);
expect(
chatPermissionReplyId('req-1', 'once'),
isNot(chatPermissionReplyId('req-1', 'always')),
);
final gate = ChatActionGate();
final id = chatPermissionReplyId('req-1', 'once');
expect(gate.start(id), isTrue);
expect(gate.start(id), isFalse);
gate.release(id);
expect(gate.start(id), isTrue);
});
testWidgets('a pending approval renders native Material controls', (
tester,
) async {
final decisions = <String>[];
final card = chatPermissionCard(permission(), '')!;
await tester.pumpWidget(
scrollHost(
ChatPermissionCard(
card: card,
onDecision: (value) async {
decisions.add(value);
},
),
),
);
expect(find.text('Approve bash'), findsOneWidget);
expect(find.text('Waiting for your response'), findsOneWidget);
expect(find.text('RISK REVIEW'), findsOneWidget);
expect(find.text('This deletes the build output.'), findsOneWidget);
expect(find.text('Allow once'), findsOneWidget);
expect(find.text('Always allow'), findsOneWidget);
expect(find.text('Reject'), findsOneWidget);
expect(find.text('Permission request · tool'), findsNothing);
await tester.tap(find.text('Allow once'));
await tester.pump();
expect(decisions, ['once']);
});
testWidgets('Show full request expands to every recorded resource line', (
tester,
) async {
final card = chatPermissionCard(
permission(
resources: const [
' one',
'two',
'three',
'four',
'five',
'six',
'seven',
],
),
'',
)!;
await tester.pumpWidget(
scrollHost(ChatPermissionCard(card: card, onDecision: (_) async {})),
);
expect(find.text(' one'), findsNothing);
await tester.tap(find.text('Show full request'));
await tester.pumpAndSettle();
expect(find.text(card.resources.join('\n')), findsOneWidget);
});
testWidgets('320px at 2x in dark Cupertino keeps the card native and '
'readable', (tester) async {
tester.view.physicalSize = const Size(640, 1400);
tester.view.devicePixelRatio = 2;
tester.platformDispatcher.textScaleFactorTestValue = 2;
tester.platformDispatcher.platformBrightnessTestValue = Brightness.dark;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
addTearDown(tester.platformDispatcher.clearPlatformBrightnessTestValue);
final card = chatPermissionCard(
permission(
action: 'a very long tool name that has to wrap at twice the text size',
resources: const [
'a long resource line that wraps instead of clipping any words at all',
],
),
'',
)!;
await tester.pumpWidget(
cupertinoHost(ChatPermissionCard(card: card, onDecision: (_) async {})),
);
expect(tester.takeException(), isNull);
expect(find.text('Allow once'), findsOneWidget);
expect(find.byType(Material), findsNothing);
});
testWidgets('a pushed chat_permission renders, sends the recorded reply, '
'and a second tap sends once', (tester) async {
final gateway = FakeChatGateway();
addTearDown(gateway.close);
gateway.history = (_) async => chatPage(const []);
final held = Completer<JsonMap>();
gateway.reply = (_) => held.future;
await tester.pumpWidget(
materialHost(
ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}),
),
);
await tester.pumpAndSettle();
gateway.emitRaw({
'type': 'chat_permission',
'chat_permission': permission(),
});
await tester.pumpAndSettle();
expect(find.text('Approve bash'), findsOneWidget);
await tester.tap(find.text('Allow once'));
await tester.tap(find.text('Allow once'));
await tester.pump();
final replies = gateway.calls.where((call) => call.type == 'chat_reply');
expect(replies, hasLength(1));
expect(replies.single.fields, {
'chat_reply': {
'session_id': 's',
'request_id': 'req-1',
'decision': 'once',
'client': 'Web',
},
});
expect(find.text('Allowed once'), findsOneWidget);
expect(find.text('Waiting for the agent to continue…'), findsOneWidget);
held.complete(const {});
await tester.pumpAndSettle();
});
testWidgets('a refused reply keeps the card pending and shows the server '
'reason', (tester) async {
final gateway = FakeChatGateway();
addTearDown(gateway.close);
gateway.history = (_) async => chatPage(const []);
gateway.reply = (_) async => throw StateError('request expired');
await tester.pumpWidget(
materialHost(
ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}),
),
);
await tester.pumpAndSettle();
gateway.emitRaw({
'type': 'chat_permission',
'chat_permission': permission(),
});
await tester.pumpAndSettle();
await tester.tap(find.text('Reject'));
await tester.pumpAndSettle();
expect(find.textContaining('request expired'), findsOneWidget);
expect(find.text('Approve bash'), findsOneWidget);
expect(find.text('Allow once'), findsOneWidget);
expect(find.text('Reject'), findsOneWidget);
});
testWidgets('a server resolution clears the controls and shows the recorded '
'decision', (tester) async {
final gateway = FakeChatGateway();
addTearDown(gateway.close);
gateway.history = (_) async => chatPage(const []);
await tester.pumpWidget(
materialHost(
ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}),
),
);
await tester.pumpAndSettle();
gateway.emitRaw({
'type': 'chat_permission',
'chat_permission': permission(),
});
await tester.pumpAndSettle();
expect(find.text('Allow once'), findsOneWidget);
gateway.emitRaw({
'type': 'chat_permission',
'chat_permission': permission(
resolved: true,
decision: 'once',
message: 'Another device allowed once.',
),
});
await tester.pumpAndSettle();
expect(find.text('Allowed once'), findsOneWidget);
expect(find.text('Another device allowed once.'), findsOneWidget);
expect(find.text('Allow once'), findsNothing);
});
testWidgets('a turn waiting on a pending card hides the running indicator '
'but keeps Stop', (tester) async {
final gateway = FakeChatGateway();
addTearDown(gateway.close);
gateway.history = (_) async => chatPage(const []);
await tester.pumpWidget(
materialHost(
ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}),
),
);
await tester.pumpAndSettle();
gateway.emitRaw({
'type': 'chat_permission',
'chat_permission': permission(),
});
gateway.emitEvent(chatStepFrame('running'));
await tester.pumpAndSettle();
expect(find.text('Approve bash'), findsOneWidget);
expect(find.text('Assistant is responding…'), findsNothing);
expect(find.text('Stop'), findsOneWidget);
gateway.emitRaw({
'type': 'chat_permission',
'chat_permission': permission(resolved: true, decision: 'once'),
});
await tester.pumpAndSettle();
expect(find.text('Assistant is responding…'), findsOneWidget);
expect(find.text('Stop'), findsOneWidget);
});
testWidgets('consecutive Material cards stay separate surfaces', (
tester,
) async {
final gateway = FakeChatGateway();
addTearDown(gateway.close);
gateway.history = (_) async => chatPage(const []);
await tester.pumpWidget(
materialHost(
ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}),
),
);
await tester.pumpAndSettle();
gateway.emitRaw({
'type': 'chat_permission',
'chat_permission': permission(id: 'req-1'),
});
gateway.emitRaw({
'type': 'chat_permission',
'chat_permission': permission(id: 'req-2', action: 'python'),
});
await tester.pumpAndSettle();
final first = tester.getRect(
find
.descendant(of: find.byType(Card).at(0), matching: find.byType(Material))
.first,
);
final second = tester.getRect(
find
.descendant(of: find.byType(Card).at(1), matching: find.byType(Material))
.first,
);
expect(second.top - first.bottom, greaterThanOrEqualTo(12));
});
}
@@ -0,0 +1,159 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/chat/conversation/chat_question_card_model.dart';
import 'package:pipelines_app/features/chat/conversation/chat_question_validation.dart';
void main() {
test('field visibility keeps false and zero as answers', () {
final fields = [
{'key': 'enabled', 'type': 'boolean'},
{
'key': 'count',
'type': 'integer',
'when': [
{'key': 'enabled', 'op': 'eq', 'value': true},
],
},
];
final hidden = {'enabled': false, 'count': 0};
expect(chatFormFieldVisible(fields[1], hidden), isFalse);
expect(chatFormAnswerError(fields, hidden), '');
expect(chatVisibleFormAnswers(fields, hidden), {'enabled': false});
});
test('required free text and numeric bounds use the web wording', () {
final fields = [
{'key': 'note', 'title': 'Notes', 'type': 'string', 'required': true},
{'key': 'count', 'type': 'integer', 'minimum': 1, 'maximum': 5},
];
expect(
chatFormAnswerError(fields, {'count': 2}),
'Answer Notes before sending.',
);
expect(
chatFormAnswerError(fields, {'note': 'ok', 'count': 1.5}),
'count needs a valid integer.',
);
expect(
chatFormAnswerError(fields, {'note': 'ok', 'count': 6}),
'count must be at most 5.',
);
expect(
chatFormAnswerError(fields, {'note': 'ok', 'count': 0}),
'count must be at least 1.',
);
expect(chatFormAnswerError(fields, {'note': 'ok', 'count': 5}), '');
});
test('integer input becomes an int, including decimal and exponent forms', () {
final field = <String, dynamic>{'key': 'count', 'type': 'integer'};
expect(chatFormFieldValue(field, '1.0'), isA<int>());
expect(chatFormFieldValue(field, '1.0'), 1);
expect(chatFormFieldValue(field, '1e3'), 1000);
expect(chatFormFieldValue(field, '1.5'), 1.5);
expect((chatFormFieldValue(field, 'nope')! as num).isNaN, isTrue);
expect(chatFormFieldValue({'type': 'number'}, '1e3'), 1000.0);
final fields = [field];
expect(
chatVisibleFormAnswers(
fields,
{'count': chatFormFieldValue(field, '1.0')},
),
{'count': 1},
);
expect(
chatFormAnswerError(fields, {'count': chatFormFieldValue(field, '1.0')}),
'',
);
});
test('a malformed pattern is reported with the documented wording', () {
final fields = [
{
'key': 'code',
'title': 'Code',
'type': 'string',
'pattern': r'^[a-z]+$',
},
];
expect(chatFormAnswerError(fields, {'code': 'abc'}), '');
expect(
chatFormAnswerError(fields, {'code': 'ABC'}),
'Code does not match the required format.',
);
// An unparseable server pattern constrains nothing, like a browser ignoring
// an invalid `pattern` attribute.
expect(
chatFormAnswerError([
{'key': 'code', 'type': 'string', 'pattern': '('},
], {'code': 'anything'}),
'',
);
});
test('email, URL and date formats are checked like native inputs', () {
final fields = [
{'key': 'mail', 'title': 'Email', 'type': 'string', 'format': 'email'},
{'key': 'site', 'title': 'Site', 'type': 'string', 'format': 'uri'},
{'key': 'day', 'title': 'Day', 'type': 'string', 'format': 'date'},
];
expect(chatFormAnswerError(fields, {'mail': 'a@b.co'}), '');
expect(
chatFormAnswerError(fields, {
'mail': 'not-a-mail',
'site': 'https://example.com',
'day': '2026-10-22',
}),
'Email is not a valid email address.',
);
expect(
chatFormAnswerError(fields, {
'mail': 'a@b.co',
'site': 'exa mple',
'day': '2026-10-22',
}),
'Site is not a valid URL.',
);
expect(
chatFormAnswerError(fields, {
'mail': 'a@b.co',
'site': 'https://example.com',
'day': '2026-02-31',
}),
'Day is not a valid date.',
);
expect(
chatFormAnswerError(fields, {
'mail': 'a@b.co',
'site': 'https://example.com',
'day': '2026-10-22',
}),
'',
);
});
test('options with an empty recorded value are skipped', () {
final field = <String, dynamic>{
'key': 'choice',
'options': [
{'value': '', 'label': 'Blank'},
{'value': 'red', 'label': 'Red'},
{'label': 'Blue'},
],
};
expect(chatQuestionOptions(field).map(chatQuestionOptionValue), [
'red',
'Blue',
]);
expect(chatQuestionFieldOptionValues(field), ['red', 'Blue']);
});
test('external URLs require an absolute HTTP(S) URL with a host', () {
expect(chatExternalUrlIsSafe('https://example.com/form'), isTrue);
expect(chatExternalUrlIsSafe('http://example.com'), isTrue);
expect(chatExternalUrlIsSafe('http://'), isFalse);
expect(chatExternalUrlIsSafe('http://exa mple.com'), isFalse);
expect(chatExternalUrlIsSafe('ftp://example.com'), isFalse);
expect(chatExternalUrlIsSafe('not a url'), isFalse);
});
}
@@ -0,0 +1,545 @@
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.dart';
import 'package:pipelines_app/features/chat/conversation/chat_question_card_model.dart';
import 'package:pipelines_app/features/chat/conversation/chat_question_validation.dart';
import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart';
import 'chat_thread_fixtures.dart';
Widget materialHost(Widget child) => MaterialApp(
theme: ThemeData(platform: TargetPlatform.android),
home: Scaffold(body: child),
);
Widget scrollHost(Widget child) =>
materialHost(SingleChildScrollView(child: child));
Widget cupertinoHost(Widget child) => CupertinoApp(
theme: const CupertinoThemeData(brightness: Brightness.dark),
home: CupertinoPageScaffold(
child: SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: child,
),
),
);
List<JsonMap> fields() => [
{
'key': 'colour',
'title': 'Colour',
'type': 'string',
'required': true,
'options': [
{'value': 'red', 'label': 'Red'},
{'value': 'blue', 'label': 'Blue'},
],
},
{
'key': 'extras',
'title': 'Extras',
'type': 'multiselect',
'options': [
{'value': 'extra-a', 'label': 'Extra A'},
{'value': 'extra-b', 'label': 'Extra B'},
],
},
{
'key': 'note',
'title': 'Notes',
'type': 'string',
'required': true,
'min_length': 3,
},
];
JsonMap question({
bool resolved = false,
bool cancelled = false,
Map<String, dynamic>? answers,
}) => {
'id': 'form-1',
'session_id': 's',
'kind': 'question',
'title': 'A demo question',
'fields': fields(),
'actions': ['accept', 'decline', 'cancel'],
if (resolved) 'resolved': true,
if (cancelled) 'cancelled': true,
'answers': ?answers,
};
void main() {
test('field visibility keeps false and zero as answers', () {
final fields = [
{'key': 'enabled', 'type': 'boolean'},
{
'key': 'count',
'type': 'integer',
'when': [
{'key': 'enabled', 'op': 'eq', 'value': true},
],
},
];
final hidden = {'enabled': false, 'count': 0};
expect(chatFormFieldVisible(fields[1], hidden), isFalse);
expect(chatFormAnswerError(fields, hidden), '');
expect(chatVisibleFormAnswers(fields, hidden), {'enabled': false});
});
test('required free text and numeric bounds use the web wording', () {
final fields = [
{'key': 'note', 'title': 'Notes', 'type': 'string', 'required': true},
{'key': 'count', 'type': 'integer', 'minimum': 1, 'maximum': 5},
];
expect(
chatFormAnswerError(fields, {'count': 2}),
'Answer Notes before sending.',
);
expect(
chatFormAnswerError(fields, {'note': 'ok', 'count': 1.5}),
'count needs a valid integer.',
);
expect(
chatFormAnswerError(fields, {'note': 'ok', 'count': 6}),
'count must be at most 5.',
);
expect(
chatFormAnswerError(fields, {'note': 'ok', 'count': 0}),
'count must be at least 1.',
);
expect(chatFormAnswerError(fields, {'note': 'ok', 'count': 5}), '');
});
testWidgets('a pending question answers single, multi and required free text '
'exactly as recorded', (tester) async {
tester.view.physicalSize = const Size(800, 1200);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
Map<String, dynamic>? sent;
await tester.pumpWidget(
scrollHost(
ChatQuestionCard(
form: question(),
onSubmit: (answers, action) async {
sent = answers;
},
),
),
);
expect(find.text('A demo question'), findsOneWidget);
expect(find.text(chatQuestionWaiting), findsOneWidget);
await tester.tap(find.text('Red'));
await tester.pump();
await tester.tap(find.text('Extra A'));
await tester.pump();
await tester.tap(find.text('Send answer'));
await tester.pump();
expect(find.text('Answer Notes before sending.'), findsOneWidget);
expect(sent, isNull);
await tester.enterText(
find.byKey(const ValueKey<String>('chat-question-input-note')),
' ready ',
);
await tester.pump();
await tester.tap(find.text('Send answer'));
await tester.pumpAndSettle();
expect(sent, {
'colour': 'red',
'extras': ['extra-a'],
'note': ' ready ',
});
});
testWidgets('a single-select option replaces the previous choice and a '
'multi-select toggles', (tester) async {
Map<String, dynamic>? sent;
await tester.pumpWidget(
scrollHost(
ChatQuestionCard(
form: question(),
onSubmit: (answers, action) async {
sent = answers;
},
),
),
);
await tester.tap(find.text('Red'));
await tester.pump();
await tester.tap(find.text('Blue'));
await tester.pump();
await tester.tap(find.text('Extra A'));
await tester.pump();
await tester.tap(find.text('Extra B'));
await tester.pump();
await tester.tap(find.text('Extra A'));
await tester.pump();
await tester.enterText(
find.byKey(const ValueKey<String>('chat-question-input-note')),
'done',
);
await tester.tap(find.text('Send answer'));
await tester.pumpAndSettle();
expect(sent, {
'colour': 'blue',
'extras': ['extra-b'],
'note': 'done',
});
});
testWidgets('answered questions show the recorded answer read-only', (
tester,
) async {
await tester.pumpWidget(
scrollHost(
ChatQuestionCard(
form: question(
resolved: true,
answers: {
'colour': 'red',
'extras': ['extra-b'],
'note': 'Recorded note',
},
),
onSubmit: (_, _) async {},
),
),
);
expect(find.text(chatQuestionAnswered), findsOneWidget);
expect(find.text('Red'), findsOneWidget);
expect(find.text('Extra B'), findsOneWidget);
expect(find.text('Recorded note'), findsOneWidget);
expect(find.text('Send answer'), findsNothing);
});
testWidgets('an expired question keeps recorded answers and offers no '
'controls', (tester) async {
await tester.pumpWidget(
scrollHost(
ChatQuestionCard(
form: question(cancelled: true, answers: {'colour': 'red'}),
onSubmit: (_, _) async {},
),
),
);
expect(find.text(chatQuestionExpired), findsOneWidget);
expect(find.text('Red'), findsOneWidget);
expect(find.text('Send answer'), findsNothing);
});
testWidgets('Cupertino field labels stay subordinate to the card title', (
tester,
) async {
await tester.pumpWidget(
cupertinoHost(
ChatQuestionCard(form: question(), onSubmit: (_, _) async {}),
),
);
final title = tester.widget<Text>(find.text('A demo question'));
final label = tester.widget<Text>(find.text('Colour'));
expect(label.style!.fontSize, lessThan(title.style!.fontSize!));
});
testWidgets('a free-text input carries its visual label in semantics', (
tester,
) async {
final semantics = tester.ensureSemantics();
await tester.pumpWidget(
scrollHost(
ChatQuestionCard(form: question(), onSubmit: (_, _) async {}),
),
);
final node = tester.getSemantics(
find.byKey(const ValueKey<String>('chat-question-input-note')),
);
expect(node.label, contains('Notes'));
semantics.dispose();
});
testWidgets('integer input sends an int, never a decimal double', (
tester,
) async {
Map<String, dynamic>? sent;
await tester.pumpWidget(
scrollHost(
ChatQuestionCard(
form: {
'id': 'form-int',
'title': 'How many?',
'actions': ['accept'],
'fields': [
{'key': 'count', 'title': 'Count', 'type': 'integer'},
],
},
onSubmit: (answers, action) async {
sent = answers;
},
),
),
);
await tester.enterText(
find.byKey(const ValueKey<String>('chat-question-input-count')),
'1.0',
);
await tester.pump();
await tester.tap(find.text('Send answer'));
await tester.pumpAndSettle();
expect(sent, {'count': 1});
expect(sent!['count'], isA<int>());
});
testWidgets('decline and cancel send their recorded actions with no answers', (
tester,
) async {
final actions = <String>[];
final answers = <Map<String, dynamic>>[];
await tester.pumpWidget(
scrollHost(
ChatQuestionCard(
form: question(),
onSubmit: (sent, action) async {
actions.add(action);
answers.add(sent);
},
),
),
);
await tester.tap(find.text('Decline'));
await tester.pumpAndSettle();
await tester.tap(find.text('Cancel question'));
await tester.pumpAndSettle();
expect(actions, ['decline', 'cancel']);
expect(answers, [<String, dynamic>{}, <String, dynamic>{}]);
});
testWidgets('an all-external form confirms completion without field answers', (
tester,
) async {
Map<String, dynamic>? sent;
String? action;
await tester.pumpWidget(
scrollHost(
ChatQuestionCard(
form: {
'id': 'form-external',
'title': 'Open the form',
'actions': ['accept'],
'fields': [
{
'key': 'form',
'title': 'External form',
'type': 'external',
'url': 'https://example.com/complete',
},
],
},
onSubmit: (answers, next) async {
sent = answers;
action = next;
},
),
),
);
expect(find.text('Confirm completion'), findsOneWidget);
expect(find.text('https://example.com/complete'), findsOneWidget);
await tester.tap(find.text('Confirm completion'));
await tester.pumpAndSettle();
expect(sent, isEmpty);
expect(action, 'accept');
});
testWidgets('an unsupported external URL shows the web alert wording', (
tester,
) async {
await tester.pumpWidget(
scrollHost(
ChatQuestionCard(
form: {
'id': 'form-external',
'title': 'Open the form',
'actions': ['accept'],
'fields': [
{'key': 'form', 'type': 'external', 'url': 'http://'},
],
},
onSubmit: (_, _) async {},
),
),
);
expect(
find.text('This form has an unsupported external URL.'),
findsOneWidget,
);
});
testWidgets('a resolved question without answers says none was recorded', (
tester,
) async {
await tester.pumpWidget(
scrollHost(
ChatQuestionCard(
form: question(resolved: true, answers: const {}),
onSubmit: (_, _) async {},
),
),
);
expect(find.text('No answer was recorded.'), findsOneWidget);
});
testWidgets('recorded booleans use Yes/No and blank titles fall back to the '
'key', (tester) async {
await tester.pumpWidget(
scrollHost(
ChatQuestionCard(
form: {
'id': 'form-recorded',
'title': 'Recorded',
'resolved': true,
'answers': {'enabled': true, 'extra': 'kept'},
'fields': [
{'key': 'enabled', 'title': '', 'description': '', 'type': 'boolean'},
],
},
onSubmit: (_, _) async {},
),
),
);
expect(find.text('enabled'), findsOneWidget);
expect(find.text('Yes'), findsOneWidget);
expect(find.text('true'), findsNothing);
expect(find.text('extra'), findsOneWidget);
expect(find.text('kept'), findsOneWidget);
});
testWidgets('320px at 2x in dark Cupertino keeps native controls', (
tester,
) async {
tester.view.physicalSize = const Size(640, 1600);
tester.view.devicePixelRatio = 2;
tester.platformDispatcher.textScaleFactorTestValue = 2;
tester.platformDispatcher.platformBrightnessTestValue = Brightness.dark;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
addTearDown(tester.platformDispatcher.clearPlatformBrightnessTestValue);
await tester.pumpWidget(
cupertinoHost(
ChatQuestionCard(form: question(), onSubmit: (_, _) async {}),
),
);
expect(tester.takeException(), isNull);
expect(find.text('A demo question'), findsOneWidget);
expect(find.text('Send answer'), findsOneWidget);
expect(find.byType(Material), findsNothing);
});
testWidgets('a pushed form renders and sends one exact chat_answer', (
tester,
) async {
final gateway = FakeChatGateway();
addTearDown(gateway.close);
gateway.history = (_) async => chatPage(const []);
final held = Completer<JsonMap>();
gateway.answer = (_) => held.future;
await tester.pumpWidget(
materialHost(
ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}),
),
);
await tester.pumpAndSettle();
gateway.emitEvent({'session_id': 's', 'kind': 'form', 'form': question()});
await tester.pumpAndSettle();
expect(find.text('A demo question'), findsOneWidget);
await tester.tap(find.text('Red'));
await tester.pump();
await tester.enterText(
find.byKey(const ValueKey<String>('chat-question-input-note')),
'sent once',
);
await tester.tap(find.text('Send answer'));
await tester.tap(find.text('Send answer'));
await tester.pump();
final answers = gateway.calls.where((call) => call.type == 'chat_answer');
expect(answers, hasLength(1));
expect(answers.single.fields, {
'chat_answer': {
'session_id': 's',
'form_id': 'form-1',
'answers': {'colour': 'red', 'note': 'sent once'},
'action': 'accept',
},
});
held.complete(const {});
await tester.pumpAndSettle();
expect(find.text(chatQuestionAnswered), findsOneWidget);
});
testWidgets('a refused question keeps the card open with the server reason', (
tester,
) async {
final gateway = FakeChatGateway();
addTearDown(gateway.close);
gateway.history = (_) async => chatPage(const []);
gateway.answer = (_) async => throw StateError('form already closed');
await tester.pumpWidget(
materialHost(
ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}),
),
);
await tester.pumpAndSettle();
gateway.emitEvent({'session_id': 's', 'kind': 'form', 'form': question()});
await tester.pumpAndSettle();
await tester.tap(find.text('Red'));
await tester.pump();
await tester.enterText(
find.byKey(const ValueKey<String>('chat-question-input-note')),
'retry me',
);
await tester.tap(find.text('Send answer'));
await tester.pumpAndSettle();
expect(find.textContaining('form already closed'), findsOneWidget);
expect(find.text('Send answer'), findsOneWidget);
expect(find.text(chatQuestionWaiting), findsOneWidget);
});
testWidgets('unknown transcript parts remain available beside cards', (
tester,
) async {
final gateway = FakeChatGateway();
addTearDown(gateway.close);
gateway.history = (_) async => chatPage([
chatMessage(
'a1',
'assistant',
parts: [
{'type': 'text', 'text': 'Recorded answer with a fallback part.'},
{'type': 'future-content', 'future_value': 'still preserved'},
],
),
]);
await tester.pumpWidget(
materialHost(
ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}),
),
);
await tester.pumpAndSettle();
expect(find.text('Recorded answer with a fallback part.'), findsOneWidget);
await tester.tap(find.text('Unrecognised part: future-content'));
await tester.pumpAndSettle();
expect(find.textContaining('still preserved'), findsOneWidget);
});
}
@@ -0,0 +1,82 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/chat/conversation/chat_thread_controller.dart';
import 'package:pipelines_app/features/chat/conversation/chat_thread_cards.dart';
import 'chat_thread_fixtures.dart';
JsonMap permission(String id, {bool resolved = false}) => {
'session_id': 's',
'request_id': id,
'action': 'bash',
'resources': const ['command: ls'],
'message': '',
'resolved': resolved,
if (resolved) 'decision': 'once',
};
JsonMap form(String id, {bool resolved = false}) => {
'id': id,
'session_id': 's',
'title': 'Question',
'fields': const [],
'actions': const ['accept'],
'resolved': resolved,
if (resolved) 'answers': const {'note': 'recorded'},
};
void main() {
test('settled approvals are bounded while the pending one is kept', () async {
final gateway = FakeChatGateway();
addTearDown(gateway.close);
final controller = ChatThreadController(gateway, 's');
addTearDown(controller.dispose);
for (var index = 0; index < ChatThreadCards.settledLimit + 5; index++) {
gateway.emitRaw({
'type': 'chat_permission',
'chat_permission': permission('req-$index', resolved: true),
});
}
gateway.emitRaw({
'type': 'chat_permission',
'chat_permission': permission('req-pending'),
});
await pumpEventQueue();
expect(controller.permissionFrames, hasLength(ChatThreadCards.settledLimit + 1));
expect(
controller.permissionFrames.first['request_id'],
'req-5',
);
expect(
controller.permissionFrames.last['request_id'],
'req-pending',
);
});
test('settled forms are bounded while the pending one is kept', () async {
final gateway = FakeChatGateway();
addTearDown(gateway.close);
final controller = ChatThreadController(gateway, 's');
addTearDown(controller.dispose);
for (var index = 0; index < ChatThreadCards.settledLimit + 5; index++) {
gateway.emitEvent({
'session_id': 's',
'kind': 'form',
'form': form('form-$index', resolved: true),
});
}
gateway.emitEvent({
'session_id': 's',
'kind': 'form',
'form': form('form-pending'),
});
await pumpEventQueue();
expect(controller.questionForms, hasLength(ChatThreadCards.settledLimit + 1));
expect(controller.questionForms.first['id'], 'form-5');
expect(controller.questionForms.last['id'], 'form-pending');
});
}
@@ -9,6 +9,8 @@ class FakeChatGateway implements ApiGateway {
final _frames = StreamController<JsonMap>.broadcast();
Future<JsonMap> Function(JsonMap fields)? history;
Future<JsonMap> Function()? subscribe;
Future<JsonMap> Function(JsonMap fields)? reply;
Future<JsonMap> Function(JsonMap fields)? answer;
void Function()? onSubscribe;
@override
@@ -23,6 +25,12 @@ class FakeChatGateway implements ApiGateway {
historyRequests.add(completer);
if (history != null) return history!(fields);
return completer.future;
case 'chat_reply':
if (reply != null) return reply!(fields);
return <String, dynamic>{};
case 'chat_answer':
if (answer != null) return answer!(fields);
return <String, dynamic>{};
}
return <String, dynamic>{};
}