merge(app): land native chat permission and question cards
This commit is contained in:
+1
-1
@@ -46,7 +46,7 @@ or scratch servers only, never real operator sessions/runs/workflows.
|
||||
| Chat activity/reasoning/tools | Source raw fields only | one activity line, compaction, native reasoning/tools overlays, lifecycle/input/output/error/duration/edit diff |
|
||||
| Chat composer | Preview: field, Send/Stop, persisted draft, queued/refusal lines; one verified send in the real app flow | attachments, paste and slash palette remain |
|
||||
| Chat attachments | Source request facade | picker/paste, latest1MiB total wire bound, base64 files, removable named chips, exact history reconciliation |
|
||||
| Chat permissions/questions | Source request facade | native approval/risk cards and form option/free-text answers; pending/resolved/stale/error states |
|
||||
| Chat permissions/questions | Source: native approval/risk and question cards in the conversation view | authenticated smoke with a real pending approval/question; live multi-client resolution; no production decision sent |
|
||||
| Chat model/Info/background tasks | Source request facade | current-model selection, numeric Info modal (unknown !=0), bounded running shell pages |
|
||||
| Chat commands/notices/scroll | Missing | slash palette/actions, unknown-command send-as-message, dismissible local notices, saved scroll/follow intent |
|
||||
| Saved schedule list | Source | pipeline entry and route registration, exact timer provenance vocabulary |
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// Host-native typography and colour for the approval and question cards.
|
||||
///
|
||||
/// The cards share one hierarchy: the card title uses the host's title style,
|
||||
/// field/answer labels sit visibly below it, and recorded prose uses the body
|
||||
/// style. Keeping the styles here stops each card file from inventing its own
|
||||
/// size and colour; everything still comes from the active Material/Cupertino
|
||||
/// theme, so light, dark and text scaling follow the host.
|
||||
TextStyle? chatCardTitleStyle(BuildContext context, bool cupertino) =>
|
||||
cupertino
|
||||
? CupertinoTheme.of(context).textTheme.navTitleTextStyle
|
||||
: Theme.of(context).textTheme.titleMedium;
|
||||
|
||||
TextStyle? chatCardBodyStyle(BuildContext context, bool cupertino) => cupertino
|
||||
? CupertinoTheme.of(context).textTheme.textStyle
|
||||
: Theme.of(context).textTheme.bodyMedium;
|
||||
|
||||
/// A field or recorded-answer label. Under Cupertino the system tab-label style
|
||||
/// (the same subordinate style the rest of the app uses for secondary copy)
|
||||
/// keeps labels from reading as extra headings; Material keeps `titleSmall`.
|
||||
TextStyle? chatCardLabelStyle(BuildContext context, bool cupertino) => cupertino
|
||||
? CupertinoTheme.of(
|
||||
context,
|
||||
).textTheme.tabLabelTextStyle.copyWith(color: chatCardSecondaryColor(context, true))
|
||||
: Theme.of(context).textTheme.titleSmall;
|
||||
|
||||
/// Body text that supports a control, such as a field description.
|
||||
TextStyle? chatCardSecondaryStyle(BuildContext context, bool cupertino) =>
|
||||
(chatCardBodyStyle(context, cupertino) ?? const TextStyle()).copyWith(
|
||||
color: chatCardSecondaryColor(context, cupertino),
|
||||
);
|
||||
|
||||
Color chatCardSecondaryColor(BuildContext context, bool cupertino) => cupertino
|
||||
? CupertinoColors.secondaryLabel.resolveFrom(context)
|
||||
: Theme.of(context).colorScheme.onSurfaceVariant;
|
||||
|
||||
Color chatCardErrorColor(BuildContext context, bool cupertino) => cupertino
|
||||
? CupertinoColors.systemRed.resolveFrom(context)
|
||||
: Theme.of(context).colorScheme.error;
|
||||
|
||||
/// The amber risk hue: the host's warning role, never a bespoke palette.
|
||||
Color chatCardWarningColor(BuildContext context, bool cupertino) => cupertino
|
||||
? CupertinoColors.systemOrange.resolveFrom(context)
|
||||
: Theme.of(context).colorScheme.tertiary;
|
||||
|
||||
/// A quiet inset surface for resource blocks and risk panels.
|
||||
Color chatCardFillColor(BuildContext context, bool cupertino) => cupertino
|
||||
? CupertinoColors.secondarySystemFill.resolveFrom(context)
|
||||
: Theme.of(context).colorScheme.surfaceContainerHighest;
|
||||
|
||||
Color chatCardWarningFillColor(BuildContext context, bool cupertino) =>
|
||||
cupertino
|
||||
? CupertinoColors.secondarySystemFill.resolveFrom(context)
|
||||
: Theme.of(context).colorScheme.tertiaryContainer;
|
||||
@@ -0,0 +1,233 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../ui/sessions/chat_adaptive.dart';
|
||||
import '../ui/transcript/native_disclosure.dart';
|
||||
import 'chat_card_styles.dart';
|
||||
import 'chat_permission_card_model.dart';
|
||||
|
||||
/// One recorded permission request as a native card.
|
||||
///
|
||||
/// The headline is the request's action (or its recorded outcome), the status
|
||||
/// line is the server's own note where present, and the once/always/reject
|
||||
/// controls appear only while the request is still open. Every server string is
|
||||
/// rendered as text, never parsed as markup.
|
||||
class ChatPermissionCard extends StatelessWidget {
|
||||
const ChatPermissionCard({
|
||||
super.key,
|
||||
required this.card,
|
||||
required this.onDecision,
|
||||
this.error,
|
||||
});
|
||||
|
||||
final ChatPermissionCardData card;
|
||||
final Future<void> Function(String decision) onDecision;
|
||||
final String? error;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) =>
|
||||
chatControlsStyleOf(context) == ChatControlsStyle.cupertino
|
||||
? _cupertino(context)
|
||||
: _material(context);
|
||||
|
||||
Widget _body(BuildContext context, {required bool cupertino}) {
|
||||
final body = Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsetsDirectional.only(end: 12),
|
||||
child: Icon(
|
||||
cupertino
|
||||
? CupertinoIcons.exclamationmark_shield
|
||||
: Icons.shield_outlined,
|
||||
color: chatCardWarningColor(context, cupertino),
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
card.headline,
|
||||
style: chatCardTitleStyle(context, cupertino),
|
||||
),
|
||||
Text(
|
||||
card.statusLine,
|
||||
style: chatCardSecondaryStyle(context, cupertino),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
if (card.resourceText.isNotEmpty) ...[
|
||||
const SizedBox(height: 12),
|
||||
DecoratedBox(
|
||||
decoration: BoxDecoration(
|
||||
color: chatCardFillColor(context, cupertino),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(8),
|
||||
child: Text(
|
||||
card.resourceText,
|
||||
maxLines: chatApprovalMaxResourceLines,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
),
|
||||
if (card.resources.join('\n') != card.resourceText)
|
||||
NativeDisclosure(
|
||||
label: 'Show full request',
|
||||
childBuilder: (context) =>
|
||||
SelectableText(card.resources.join('\n')),
|
||||
),
|
||||
],
|
||||
if (card.showRisk && card.risk.trim().isNotEmpty) ...[
|
||||
const SizedBox(height: 12),
|
||||
_risk(context, cupertino),
|
||||
],
|
||||
if (error != null && error!.trim().isNotEmpty) ...[
|
||||
const SizedBox(height: 12),
|
||||
Semantics(
|
||||
liveRegion: true,
|
||||
child: Text(
|
||||
error!,
|
||||
style: chatCardBodyStyle(
|
||||
context,
|
||||
cupertino,
|
||||
)?.copyWith(color: chatCardErrorColor(context, cupertino)),
|
||||
),
|
||||
),
|
||||
],
|
||||
if (card.actionable) ...[
|
||||
const SizedBox(height: 12),
|
||||
_controls(context, cupertino),
|
||||
],
|
||||
],
|
||||
);
|
||||
return cupertino
|
||||
? DefaultTextStyle.merge(
|
||||
style: CupertinoTheme.of(context).textTheme.textStyle,
|
||||
child: body,
|
||||
)
|
||||
: body;
|
||||
}
|
||||
|
||||
Widget _risk(BuildContext context, bool cupertino) {
|
||||
final tint = chatCardWarningColor(context, cupertino);
|
||||
return DecoratedBox(
|
||||
decoration: BoxDecoration(
|
||||
color: chatCardWarningFillColor(context, cupertino),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Icon(
|
||||
cupertino
|
||||
? CupertinoIcons.exclamationmark_shield
|
||||
: Icons.shield_outlined,
|
||||
size: 16,
|
||||
color: tint,
|
||||
),
|
||||
const SizedBox(width: 6),
|
||||
Expanded(
|
||||
child: Text(
|
||||
chatRiskReviewLabel,
|
||||
style: chatCardLabelStyle(
|
||||
context,
|
||||
cupertino,
|
||||
)?.copyWith(color: tint),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(card.risk, style: chatCardBodyStyle(context, cupertino)),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _controls(BuildContext context, bool cupertino) {
|
||||
final always = card.alwaysLabel;
|
||||
if (cupertino) {
|
||||
return Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 8,
|
||||
children: [
|
||||
CupertinoButton.filled(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
onPressed: () => onDecision(chatDecisionOnce),
|
||||
child: const Text(chatApprovalOnceLabel),
|
||||
),
|
||||
CupertinoButton(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
||||
onPressed: () => onDecision(chatDecisionAlways),
|
||||
child: Text(always),
|
||||
),
|
||||
CupertinoButton(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
||||
onPressed: () => onDecision(chatDecisionReject),
|
||||
child: Text(
|
||||
chatApprovalRejectLabel,
|
||||
style: TextStyle(
|
||||
color: CupertinoColors.systemRed.resolveFrom(context),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
return Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 8,
|
||||
children: [
|
||||
FilledButton(
|
||||
onPressed: () => onDecision(chatDecisionOnce),
|
||||
child: const Text(chatApprovalOnceLabel),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () => onDecision(chatDecisionAlways),
|
||||
child: Text(always),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () => onDecision(chatDecisionReject),
|
||||
style: TextButton.styleFrom(
|
||||
foregroundColor: Theme.of(context).colorScheme.error,
|
||||
),
|
||||
child: const Text(chatApprovalRejectLabel),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _material(BuildContext context) => Card(
|
||||
// Consecutive cards must read as separate surfaces; the row itself adds only
|
||||
// the horizontal inset.
|
||||
margin: const EdgeInsets.only(bottom: 12),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: _body(context, cupertino: false),
|
||||
),
|
||||
);
|
||||
|
||||
Widget _cupertino(BuildContext context) => CupertinoListSection.insetGrouped(
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: _body(context, cupertino: true),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
/// Permission approval cards: the model behind one `chat_permission` frame.
|
||||
///
|
||||
/// The web's `approvalCard`/`permissionRiskText`/`decisionLabel` are the target.
|
||||
/// A card is derived from the server frame plus the operator's local answer, so
|
||||
/// a server resolution always outranks a stale local decision.
|
||||
library;
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
|
||||
const chatDecisionOnce = 'once';
|
||||
const chatDecisionAlways = 'always';
|
||||
const chatDecisionReject = 'reject';
|
||||
const chatDecisions = [
|
||||
chatDecisionOnce,
|
||||
chatDecisionAlways,
|
||||
chatDecisionReject,
|
||||
];
|
||||
|
||||
const chatApprovalBlankAction = 'tool call';
|
||||
const chatApprovalHeadlineResolved = 'Already resolved';
|
||||
const chatApprovalStatusPending = 'Waiting for your response';
|
||||
const chatApprovalStatusAnswered = 'Waiting for the agent to continue…';
|
||||
const chatApprovalStatusResolved =
|
||||
'Another client already answered this request.';
|
||||
const chatRiskReviewLabel = 'RISK REVIEW';
|
||||
const chatApprovalOnceLabel = 'Allow once';
|
||||
const chatApprovalAlwaysLabel = 'Always allow';
|
||||
const chatApprovalRejectLabel = 'Reject';
|
||||
const chatApprovalMaxResourceLines = 6;
|
||||
|
||||
/// How one approval request stands. `stale` is a server-resolved request whose
|
||||
/// recorded decision is blank: the card can say only that it is already over.
|
||||
enum ChatPermissionState { pending, answered, resolved, stale }
|
||||
|
||||
String chatDecisionLabel(String decision) => switch (decision) {
|
||||
chatDecisionOnce => 'Allowed once',
|
||||
chatDecisionAlways => 'Always allowed',
|
||||
chatDecisionReject => 'Rejected',
|
||||
_ => 'Resolved',
|
||||
};
|
||||
|
||||
/// The amber risk sentence. The server's own summary wins; otherwise name the
|
||||
/// action so the panel is never blank.
|
||||
String chatPermissionRiskText(JsonMap permission) {
|
||||
final message = _text(permission['message']);
|
||||
if (message.isNotEmpty) return message;
|
||||
final action = _text(permission['action']);
|
||||
final what = action.isEmpty ? 'a tool call' : action;
|
||||
return 'The agent is asking to run $what; review the request before allowing.';
|
||||
}
|
||||
|
||||
/// The request's non-blank resources, in the server's own order.
|
||||
///
|
||||
/// A resource's recorded text is kept verbatim: the web filters blanks but never
|
||||
/// trims, so an indented command or YAML block keeps its indentation in both the
|
||||
/// six-line view and the expanded request.
|
||||
List<String> chatPermissionResources(JsonMap permission) {
|
||||
final resources = permission['resources'];
|
||||
if (resources is! List) return const [];
|
||||
return [
|
||||
for (final resource in resources)
|
||||
if (_text(resource).isNotEmpty) '${resource ?? ''}',
|
||||
];
|
||||
}
|
||||
|
||||
/// The resource block capped at six lines, an embedded newline counting as a
|
||||
/// line. The full list stays available on the card for expansion.
|
||||
String chatPermissionResourceText(JsonMap permission) {
|
||||
final lines = [
|
||||
for (final resource in chatPermissionResources(permission))
|
||||
...resource.split('\n'),
|
||||
];
|
||||
if (lines.length <= chatApprovalMaxResourceLines) return lines.join('\n');
|
||||
final kept = lines.take(chatApprovalMaxResourceLines).toList();
|
||||
kept[kept.length - 1] = '${kept.last}…';
|
||||
return kept.join('\n');
|
||||
}
|
||||
|
||||
/// One rendered request. [resources] keeps every recorded entry; [resourceText]
|
||||
/// is only the six-line view.
|
||||
class ChatPermissionCardData {
|
||||
const ChatPermissionCardData({
|
||||
required this.requestId,
|
||||
required this.resources,
|
||||
required this.resourceText,
|
||||
required this.risk,
|
||||
required this.state,
|
||||
required this.decision,
|
||||
required this.note,
|
||||
required this.alwaysLabel,
|
||||
required this.headline,
|
||||
required this.statusLine,
|
||||
});
|
||||
|
||||
final String requestId;
|
||||
final List<String> resources;
|
||||
final String resourceText;
|
||||
final String risk;
|
||||
final ChatPermissionState state;
|
||||
final String decision;
|
||||
final String note;
|
||||
final String alwaysLabel;
|
||||
final String headline;
|
||||
final String statusLine;
|
||||
|
||||
bool get actionable => state == ChatPermissionState.pending;
|
||||
bool get showRisk =>
|
||||
state == ChatPermissionState.pending ||
|
||||
(state == ChatPermissionState.answered && decision == chatDecisionReject);
|
||||
}
|
||||
|
||||
/// The card for [permission], or null when there is no request to show.
|
||||
ChatPermissionCardData? chatPermissionCard(
|
||||
JsonMap? permission, [
|
||||
String answer = '',
|
||||
]) {
|
||||
if (permission == null) return null;
|
||||
final requestId = _text(permission['request_id']);
|
||||
if (requestId.isEmpty) return null;
|
||||
final resolvedByServer =
|
||||
permission['resolved'] == true ||
|
||||
_text(permission['decision']).isNotEmpty;
|
||||
final answerText = answer.trim();
|
||||
final state = resolvedByServer
|
||||
? (_text(permission['decision']).isEmpty
|
||||
? ChatPermissionState.stale
|
||||
: ChatPermissionState.resolved)
|
||||
: answerText.isNotEmpty
|
||||
? ChatPermissionState.answered
|
||||
: ChatPermissionState.pending;
|
||||
final decision = resolvedByServer
|
||||
? _text(permission['decision'])
|
||||
: answerText;
|
||||
final note = resolvedByServer ? _text(permission['message']) : '';
|
||||
final action = _text(permission['action']);
|
||||
final alwaysLabel = _text(permission['always_label']);
|
||||
final headline = switch (state) {
|
||||
ChatPermissionState.pending =>
|
||||
'Approve ${action.isEmpty ? chatApprovalBlankAction : action}',
|
||||
ChatPermissionState.answered || ChatPermissionState.resolved =>
|
||||
decision == chatDecisionAlways && alwaysLabel == 'Allow for session'
|
||||
? 'Allowed for session'
|
||||
: chatDecisionLabel(decision),
|
||||
ChatPermissionState.stale => chatApprovalHeadlineResolved,
|
||||
};
|
||||
final statusLine = switch (state) {
|
||||
ChatPermissionState.pending => chatApprovalStatusPending,
|
||||
ChatPermissionState.answered => chatApprovalStatusAnswered,
|
||||
ChatPermissionState.resolved || ChatPermissionState.stale =>
|
||||
note.isEmpty ? chatApprovalStatusResolved : note,
|
||||
};
|
||||
return ChatPermissionCardData(
|
||||
requestId: requestId,
|
||||
resources: chatPermissionResources(permission),
|
||||
resourceText: chatPermissionResourceText(permission),
|
||||
risk: chatPermissionRiskText(permission),
|
||||
state: state,
|
||||
decision: decision,
|
||||
note: note,
|
||||
alwaysLabel: alwaysLabel.isEmpty ? chatApprovalAlwaysLabel : alwaysLabel,
|
||||
headline: headline,
|
||||
statusLine: statusLine,
|
||||
);
|
||||
}
|
||||
|
||||
/// A stable id for one confirmed reply. The id never changes across a retry of
|
||||
/// the same request and decision, so the send gate can recognise a double tap.
|
||||
String chatPermissionReplyId(String requestId, String decision) =>
|
||||
'chat-reply:${requestId.trim()}:${decision.trim()}';
|
||||
|
||||
/// A one-shot gate for confirmed actions. [start] returns false while the same
|
||||
/// stable id is already in flight or already accepted; [release] reopens an id
|
||||
/// after a refused send so the operator can retry it.
|
||||
class ChatActionGate {
|
||||
final Set<String> _started = {};
|
||||
|
||||
bool start(String id) => _started.add(id);
|
||||
|
||||
void release(String id) => _started.remove(id);
|
||||
|
||||
bool isStarted(String id) => _started.contains(id);
|
||||
|
||||
void clear() => _started.clear();
|
||||
}
|
||||
|
||||
String _text(Object? value) => '${value ?? ''}'.trim();
|
||||
@@ -0,0 +1,230 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../ui/sessions/chat_adaptive.dart';
|
||||
import 'chat_card_styles.dart';
|
||||
import 'chat_question_card_controls.dart';
|
||||
import 'chat_question_card_fields.dart';
|
||||
import 'chat_question_card_model.dart';
|
||||
import 'chat_question_recorded_answers.dart';
|
||||
import 'chat_question_validation.dart';
|
||||
|
||||
/// One recorded agent question as a native card.
|
||||
///
|
||||
/// A pending question keeps the operator's choices locally until Send answer;
|
||||
/// the answer map is field-keyed, exactly as `chat_answer` expects. Resolved
|
||||
/// and expired questions show the recorded answers read-only.
|
||||
class ChatQuestionCard extends StatefulWidget {
|
||||
const ChatQuestionCard({
|
||||
super.key,
|
||||
required this.form,
|
||||
required this.onSubmit,
|
||||
this.error,
|
||||
});
|
||||
|
||||
final JsonMap form;
|
||||
final Future<void> Function(Map<String, dynamic> answers, String action)
|
||||
onSubmit;
|
||||
final String? error;
|
||||
|
||||
@override
|
||||
State<ChatQuestionCard> createState() => _ChatQuestionCardState();
|
||||
}
|
||||
|
||||
class _ChatQuestionCardState extends State<ChatQuestionCard> {
|
||||
late final List<JsonMap> _fields = chatFormFields(widget.form);
|
||||
late final Map<String, dynamic> _answers = _initialAnswers();
|
||||
final Map<String, TextEditingController> _controllers = {};
|
||||
String _localError = '';
|
||||
bool _sending = false;
|
||||
|
||||
bool get _pending => chatFormPending(widget.form);
|
||||
|
||||
Map<String, dynamic> _initialAnswers() {
|
||||
final recorded = widget.form['answers'];
|
||||
final answers = recorded is Map
|
||||
? Map<String, dynamic>.from(recorded)
|
||||
: <String, dynamic>{};
|
||||
for (final field in _fields) {
|
||||
final key = '${field['key'] ?? ''}'.trim();
|
||||
if (key.isEmpty || answers.containsKey(key)) continue;
|
||||
if (field['default'] != null) answers[key] = field['default'];
|
||||
}
|
||||
return answers;
|
||||
}
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
for (final field in _fields) {
|
||||
if (!chatQuestionFieldNeedsInput(field)) continue;
|
||||
final key = '${field['key'] ?? ''}'.trim();
|
||||
if (key.isEmpty) continue;
|
||||
final value = _answers[key];
|
||||
final options = chatQuestionOptions(
|
||||
field,
|
||||
).map(chatQuestionOptionValue).toSet();
|
||||
final custom = value is List
|
||||
? value.where((entry) => !options.contains('$entry')).join(', ')
|
||||
: (value is String && !options.contains(value) ? value : '');
|
||||
final controller = TextEditingController(text: custom);
|
||||
_controllers[key] = controller;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
for (final controller in _controllers.values) {
|
||||
controller.dispose();
|
||||
}
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _changed(String key, Object? value) {
|
||||
setState(() {
|
||||
if (value == null) {
|
||||
_answers.remove(key);
|
||||
} else {
|
||||
_answers[key] = value;
|
||||
}
|
||||
_localError = '';
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _submit() async {
|
||||
if (_sending || !_pending) return;
|
||||
final reason = chatFormAnswerError(_fields, _answers);
|
||||
if (reason.isNotEmpty) {
|
||||
setState(() => _localError = reason);
|
||||
return;
|
||||
}
|
||||
setState(() {
|
||||
_sending = true;
|
||||
_localError = '';
|
||||
});
|
||||
final accept =
|
||||
widget.form['actions'] is List &&
|
||||
(widget.form['actions'] as List).contains('accept');
|
||||
await widget.onSubmit(
|
||||
chatVisibleFormAnswers(_fields, _answers),
|
||||
accept ? 'accept' : '',
|
||||
);
|
||||
if (mounted) setState(() => _sending = false);
|
||||
}
|
||||
|
||||
Future<void> _action(String action) async {
|
||||
if (_sending || !_pending) return;
|
||||
setState(() {
|
||||
_sending = true;
|
||||
_localError = '';
|
||||
});
|
||||
await widget.onSubmit(const {}, action);
|
||||
if (mounted) setState(() => _sending = false);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final cupertino =
|
||||
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
|
||||
final body = _body(context, cupertino);
|
||||
final wrapped = cupertino
|
||||
? DefaultTextStyle.merge(
|
||||
style: CupertinoTheme.of(context).textTheme.textStyle,
|
||||
child: body,
|
||||
)
|
||||
: body;
|
||||
if (cupertino) {
|
||||
return CupertinoListSection.insetGrouped(
|
||||
children: [Padding(padding: const EdgeInsets.all(16), child: wrapped)],
|
||||
);
|
||||
}
|
||||
return Card(
|
||||
// Keep consecutive cards visually separate; the transcript row only
|
||||
// supplies the horizontal inset.
|
||||
margin: const EdgeInsets.only(bottom: 12),
|
||||
child: Padding(padding: const EdgeInsets.all(16), child: wrapped),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _body(BuildContext context, bool cupertino) {
|
||||
final actions = widget.form['actions'];
|
||||
final error = widget.error?.trim().isNotEmpty == true
|
||||
? widget.error!.trim()
|
||||
: _localError;
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text(
|
||||
'${widget.form['title'] ?? ''}'.trim().isEmpty
|
||||
? 'Question'
|
||||
: '${widget.form['title']}'.trim(),
|
||||
style: chatCardTitleStyle(context, cupertino),
|
||||
),
|
||||
Text(
|
||||
_statusLine(),
|
||||
style: chatCardSecondaryStyle(context, cupertino),
|
||||
),
|
||||
if (error.isNotEmpty)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 8),
|
||||
child: Semantics(
|
||||
liveRegion: true,
|
||||
child: Text(
|
||||
error,
|
||||
style: chatCardBodyStyle(
|
||||
context,
|
||||
cupertino,
|
||||
)?.copyWith(color: chatCardErrorColor(context, cupertino)),
|
||||
),
|
||||
),
|
||||
),
|
||||
if (_pending)
|
||||
...chatQuestionFieldWidgets(
|
||||
context: context,
|
||||
fields: _fields,
|
||||
answers: _answers,
|
||||
cupertino: cupertino,
|
||||
controllers: _controllers,
|
||||
onChanged: _changed,
|
||||
)
|
||||
else
|
||||
...chatQuestionRecordedAnswers(
|
||||
context: context,
|
||||
form: widget.form,
|
||||
cupertino: cupertino,
|
||||
),
|
||||
if (_pending) ...[
|
||||
const SizedBox(height: 12),
|
||||
chatQuestionControls(
|
||||
context: context,
|
||||
cupertino: cupertino,
|
||||
actions: actions,
|
||||
submitLabel: _submitLabel,
|
||||
sending: _sending,
|
||||
onSubmit: _submit,
|
||||
onAction: _action,
|
||||
),
|
||||
],
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
String get _submitLabel {
|
||||
final allExternal =
|
||||
_fields.isNotEmpty &&
|
||||
_fields.every((field) => '${field['type'] ?? ''}' == 'external');
|
||||
return allExternal ? chatQuestionConfirm : chatQuestionSubmit;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// Submit and optional decline/cancel controls for a pending question.
|
||||
///
|
||||
/// The web shows `Confirm completion` when every field is external, otherwise
|
||||
/// `Send answer`, and offers only the actions the form records. The labels are
|
||||
/// passed in so this file stays layout only.
|
||||
Widget chatQuestionControls({
|
||||
required BuildContext context,
|
||||
required bool cupertino,
|
||||
required Object? actions,
|
||||
required String submitLabel,
|
||||
required bool sending,
|
||||
required VoidCallback onSubmit,
|
||||
required void Function(String action) onAction,
|
||||
}) {
|
||||
final canDecline = actions is List && actions.contains('decline');
|
||||
final canCancel = actions is List && actions.contains('cancel');
|
||||
if (cupertino) {
|
||||
return Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 8,
|
||||
children: [
|
||||
CupertinoButton.filled(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
onPressed: sending ? null : onSubmit,
|
||||
child: Text(sending ? 'Sending…' : submitLabel),
|
||||
),
|
||||
if (canDecline)
|
||||
CupertinoButton(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
||||
onPressed: sending ? null : () => onAction('decline'),
|
||||
child: const Text('Decline'),
|
||||
),
|
||||
if (canCancel)
|
||||
CupertinoButton(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
||||
onPressed: sending ? null : () => onAction('cancel'),
|
||||
child: const Text('Cancel question'),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
return Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 8,
|
||||
children: [
|
||||
FilledButton(
|
||||
onPressed: sending ? null : onSubmit,
|
||||
child: Text(sending ? 'Sending…' : submitLabel),
|
||||
),
|
||||
if (canDecline)
|
||||
TextButton(
|
||||
onPressed: sending ? null : () => onAction('decline'),
|
||||
child: const Text('Decline'),
|
||||
),
|
||||
if (canCancel)
|
||||
TextButton(
|
||||
onPressed: sending ? null : () => onAction('cancel'),
|
||||
child: const Text('Cancel question'),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import 'chat_card_styles.dart';
|
||||
import 'chat_question_card_model.dart';
|
||||
import 'chat_question_option_controls.dart';
|
||||
|
||||
/// A free-text input is part of a field when the form allows an answer outside
|
||||
/// its option list, or when the field has no options at all.
|
||||
bool chatQuestionFieldNeedsInput(JsonMap field) =>
|
||||
field['custom'] == true || chatQuestionOptions(field).isEmpty;
|
||||
|
||||
/// The editable controls for one form. [onChanged] receives the protocol value
|
||||
/// (`false`/`0` preserved), or null when the input was cleared.
|
||||
List<Widget> chatQuestionFieldWidgets({
|
||||
required BuildContext context,
|
||||
required List<JsonMap> fields,
|
||||
required Map<String, dynamic> answers,
|
||||
required bool cupertino,
|
||||
required Map<String, TextEditingController> controllers,
|
||||
required void Function(String key, Object? value) onChanged,
|
||||
}) {
|
||||
final widgets = <Widget>[];
|
||||
for (final field in fields) {
|
||||
if (!chatFormFieldVisible(field, answers)) continue;
|
||||
final key = '${field['key'] ?? ''}'.trim();
|
||||
if (key.isEmpty) continue;
|
||||
widgets.add(
|
||||
_field(
|
||||
context: context,
|
||||
field: field,
|
||||
keyName: key,
|
||||
answers: answers,
|
||||
cupertino: cupertino,
|
||||
controllers: controllers,
|
||||
onChanged: onChanged,
|
||||
),
|
||||
);
|
||||
}
|
||||
return widgets;
|
||||
}
|
||||
|
||||
Widget _field({
|
||||
required BuildContext context,
|
||||
required JsonMap field,
|
||||
required String keyName,
|
||||
required Map<String, dynamic> answers,
|
||||
required bool cupertino,
|
||||
required Map<String, TextEditingController> controllers,
|
||||
required void Function(String key, Object? value) onChanged,
|
||||
}) {
|
||||
final title = '${field['title'] ?? ''}'.trim();
|
||||
final description = '${field['description'] ?? ''}'.trim();
|
||||
final label = title.isNotEmpty
|
||||
? title
|
||||
: (description.isNotEmpty ? description : keyName);
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(top: 12),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(label, style: chatCardLabelStyle(context, cupertino)),
|
||||
if (description.isNotEmpty && description != title)
|
||||
Text(
|
||||
description,
|
||||
style: chatCardSecondaryStyle(context, cupertino),
|
||||
),
|
||||
if ('${field['type'] ?? ''}' == 'external')
|
||||
_external(context, field, cupertino)
|
||||
else if ('${field['type'] ?? ''}' == 'boolean')
|
||||
chatQuestionBooleanField(
|
||||
context: context,
|
||||
field: field,
|
||||
keyName: keyName,
|
||||
answers: answers,
|
||||
cupertino: cupertino,
|
||||
onChanged: onChanged,
|
||||
)
|
||||
else ...[
|
||||
chatQuestionOptionsField(
|
||||
context: context,
|
||||
field: field,
|
||||
keyName: keyName,
|
||||
answers: answers,
|
||||
cupertino: cupertino,
|
||||
onChanged: onChanged,
|
||||
),
|
||||
if (chatQuestionFieldNeedsInput(field))
|
||||
_input(
|
||||
context: context,
|
||||
field: field,
|
||||
label: label,
|
||||
keyName: keyName,
|
||||
controller: controllers[keyName]!,
|
||||
cupertino: cupertino,
|
||||
hasOptions: chatQuestionOptions(field).isNotEmpty,
|
||||
onChanged: (value) => onChanged(
|
||||
keyName,
|
||||
chatQuestionTextValue(field, value, answers),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _input({
|
||||
required BuildContext context,
|
||||
required JsonMap field,
|
||||
required String label,
|
||||
required String keyName,
|
||||
required TextEditingController controller,
|
||||
required bool cupertino,
|
||||
required bool hasOptions,
|
||||
required ValueChanged<String> onChanged,
|
||||
}) {
|
||||
final placeholder = '${field['placeholder'] ?? ''}'.trim().isNotEmpty
|
||||
? '${field['placeholder']}'.trim()
|
||||
: (hasOptions ? 'Type another answer' : 'Your answer');
|
||||
final secret = field['secret'] == true;
|
||||
final type = '${field['type'] ?? ''}';
|
||||
final format = '${field['format'] ?? ''}';
|
||||
final keyboard = type == 'number' || type == 'integer'
|
||||
? TextInputType.number
|
||||
: format == 'email'
|
||||
? TextInputType.emailAddress
|
||||
: format == 'uri'
|
||||
? TextInputType.url
|
||||
: format == 'date'
|
||||
? TextInputType.datetime
|
||||
: TextInputType.text;
|
||||
// The visual label sits above the input; the same words must also reach the
|
||||
// input's own semantics node, as the web's `aria-label` does.
|
||||
final input = cupertino
|
||||
? CupertinoTextField(
|
||||
key: ValueKey<String>('chat-question-input-$keyName'),
|
||||
controller: controller,
|
||||
placeholder: placeholder,
|
||||
obscureText: secret,
|
||||
keyboardType: keyboard,
|
||||
padding: const EdgeInsets.all(8),
|
||||
onChanged: onChanged,
|
||||
)
|
||||
: TextField(
|
||||
key: ValueKey<String>('chat-question-input-$keyName'),
|
||||
controller: controller,
|
||||
obscureText: secret,
|
||||
keyboardType: keyboard,
|
||||
decoration: InputDecoration(hintText: placeholder),
|
||||
onChanged: onChanged,
|
||||
);
|
||||
return Semantics(label: label, child: input);
|
||||
}
|
||||
|
||||
Widget _external(BuildContext context, JsonMap field, bool cupertino) {
|
||||
final raw = '${field['url'] ?? ''}'.trim();
|
||||
if (!chatExternalUrlIsSafe(raw)) {
|
||||
return Text(
|
||||
'This form has an unsupported external URL.',
|
||||
style: chatCardBodyStyle(
|
||||
context,
|
||||
cupertino,
|
||||
)?.copyWith(color: chatCardErrorColor(context, cupertino)),
|
||||
);
|
||||
}
|
||||
return SelectableText(raw);
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
/// Agent question forms: field visibility, values and option lists.
|
||||
///
|
||||
/// These rules mirror the web's `chatForms.js`. `false` and `0` are valid
|
||||
/// answers, never "missing". Validation lives in `chat_question_validation.dart`
|
||||
/// so this file stays a protocol model; option values are kept exactly as
|
||||
/// recorded because they travel back in `chat_answer`.
|
||||
library;
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
|
||||
const chatQuestionWaiting = 'The agent is waiting for your answer.';
|
||||
const chatQuestionExpired = 'This question expired.';
|
||||
const chatQuestionAnswered = 'Answer recorded.';
|
||||
const chatQuestionClosed = 'Question closed.';
|
||||
const chatQuestionSubmit = 'Send answer';
|
||||
const chatQuestionConfirm = 'Confirm completion';
|
||||
|
||||
bool chatFormFieldVisible(JsonMap field, Map<String, dynamic> answers) {
|
||||
if (field['hidden'] == true) return false;
|
||||
final when = field['when'];
|
||||
if (when is! List) return true;
|
||||
for (final condition in when) {
|
||||
if (condition is! Map) continue;
|
||||
final key = _text(condition['key']);
|
||||
final expected = condition['value'];
|
||||
final actual = answers[key];
|
||||
final matches = actual == expected;
|
||||
if (_text(condition['op']) == 'neq' ? matches : !matches) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// A protocol-preserving field value; null means the input was cleared.
|
||||
///
|
||||
/// An integer answer is stored as a Dart `int`, so `"1.0"`/`"1e3"` cannot travel
|
||||
/// as `1.0`/`1000.0` the way the web's `Number()` never does.
|
||||
Object? chatFormFieldValue(JsonMap field, String raw) {
|
||||
if (raw.isEmpty) return null;
|
||||
final type = _text(field['type']);
|
||||
switch (type) {
|
||||
case 'boolean':
|
||||
return raw == 'true';
|
||||
case 'number':
|
||||
case 'integer':
|
||||
final parsed = num.tryParse(raw);
|
||||
if (parsed == null) return double.nan;
|
||||
final integral =
|
||||
parsed.isFinite && parsed == parsed.roundToDouble();
|
||||
return type == 'integer' && integral ? parsed.toInt() : parsed;
|
||||
default:
|
||||
return raw;
|
||||
}
|
||||
}
|
||||
|
||||
/// Only visible, non-external, answered fields travel in `chat_answer`.
|
||||
Map<String, dynamic> chatVisibleFormAnswers(
|
||||
List<JsonMap> fields,
|
||||
Map<String, dynamic> answers,
|
||||
) {
|
||||
final result = <String, dynamic>{};
|
||||
for (final field in fields) {
|
||||
if (!chatFormFieldVisible(field, answers)) continue;
|
||||
if (_text(field['type']) == 'external') continue;
|
||||
final key = _text(field['key']);
|
||||
if (!answers.containsKey(key)) continue;
|
||||
result[key] = answers[key];
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
List<JsonMap> chatFormFields(JsonMap form) {
|
||||
final fields = form['fields'];
|
||||
if (fields is! List) return const [];
|
||||
return [
|
||||
for (final field in fields)
|
||||
if (field is Map) Map<String, dynamic>.from(field),
|
||||
];
|
||||
}
|
||||
|
||||
/// A free-text edit as the protocol value. A multi-select input edits only the
|
||||
/// options it already knows plus the comma-separated custom entries, matching
|
||||
/// the web's question input.
|
||||
Object? chatQuestionTextValue(
|
||||
JsonMap field,
|
||||
String raw,
|
||||
Map<String, dynamic> answers,
|
||||
) {
|
||||
final key = _text(field['key']);
|
||||
if (_text(field['type']) != 'multiselect') {
|
||||
return chatFormFieldValue(field, raw);
|
||||
}
|
||||
final known = chatQuestionFieldOptionValues(field);
|
||||
final selected = answers[key] is List
|
||||
? (answers[key] as List).map((entry) => '$entry').where(known.contains)
|
||||
: const <String>[];
|
||||
final custom = raw
|
||||
.split(',')
|
||||
.map((entry) => entry.trim())
|
||||
.where((entry) => entry.isNotEmpty);
|
||||
return [...selected, ...custom];
|
||||
}
|
||||
|
||||
List<String> chatQuestionFieldOptionValues(JsonMap field) => [
|
||||
for (final option in chatQuestionOptions(field))
|
||||
chatQuestionOptionValue(option),
|
||||
];
|
||||
|
||||
/// The field's selectable options. The web skips an option whose recorded value
|
||||
/// is empty rather than rendering a blank control.
|
||||
List<JsonMap> chatQuestionOptions(JsonMap field) {
|
||||
final options = field['options'];
|
||||
if (options is! List) return const [];
|
||||
final result = <JsonMap>[];
|
||||
for (final option in options) {
|
||||
if (option is! Map) continue;
|
||||
final converted = Map<String, dynamic>.from(option);
|
||||
if (chatQuestionOptionValue(converted).isEmpty) continue;
|
||||
result.add(converted);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// The option's exact recorded value, never trimmed: it is the protocol value
|
||||
/// sent back in `chat_answer`.
|
||||
String chatQuestionOptionValue(JsonMap option) =>
|
||||
'${option['value'] ?? option['label'] ?? ''}';
|
||||
|
||||
String chatQuestionOptionLabel(JsonMap option) {
|
||||
final label = _text(option['label']);
|
||||
return label.isEmpty ? chatQuestionOptionValue(option) : label;
|
||||
}
|
||||
|
||||
bool chatFormPending(JsonMap form) =>
|
||||
form['resolved'] != true && form['cancelled'] != true;
|
||||
|
||||
/// 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) {
|
||||
if (raw.trim() != raw || RegExp(r'\s').hasMatch(raw)) return false;
|
||||
final uri = Uri.tryParse(raw);
|
||||
return uri != null &&
|
||||
(uri.scheme == 'http' || uri.scheme == 'https') &&
|
||||
uri.host.isNotEmpty;
|
||||
}
|
||||
|
||||
/// 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.
|
||||
Map<String, JsonMap> chatFoldQuestionFrame(
|
||||
Map<String, JsonMap> current,
|
||||
JsonMap? form,
|
||||
) {
|
||||
if (form == null) return current;
|
||||
final id = _text(form['id']);
|
||||
if (id.isEmpty) return current;
|
||||
final existing = current[id];
|
||||
final next = <String, JsonMap>{...current};
|
||||
next[id] = existing == null
|
||||
? Map<String, dynamic>.from(form)
|
||||
: {...existing, ...Map<String, dynamic>.from(form)};
|
||||
return next;
|
||||
}
|
||||
|
||||
/// 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 = ''}) =>
|
||||
'chat-answer:${formId.trim()}:${action.trim().isEmpty ? 'answer' : action.trim()}';
|
||||
|
||||
String _text(Object? value) => '${value ?? ''}'.trim();
|
||||
@@ -0,0 +1,150 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import 'chat_card_styles.dart';
|
||||
import 'chat_question_card_model.dart';
|
||||
|
||||
/// Native option controls for one question field. Single-select uses the host's
|
||||
/// radio/checklist pattern, multi-select toggles choices, and `onChanged`
|
||||
/// receives the protocol value with `false`/`0` preserved.
|
||||
Widget chatQuestionOptionsField({
|
||||
required BuildContext context,
|
||||
required JsonMap field,
|
||||
required String keyName,
|
||||
required Map<String, dynamic> answers,
|
||||
required bool cupertino,
|
||||
required void Function(String key, Object? value) onChanged,
|
||||
}) {
|
||||
final options = chatQuestionOptions(field);
|
||||
if (options.isEmpty) return const SizedBox.shrink();
|
||||
final multi = '${field['type'] ?? ''}' == 'multiselect';
|
||||
final value = answers[keyName];
|
||||
final selected = multi
|
||||
? (value is List ? value.map((entry) => '$entry').toSet() : <String>{})
|
||||
: <String>{if (value is String) value};
|
||||
if (cupertino) {
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
for (final option in options)
|
||||
CupertinoButton(
|
||||
padding: const EdgeInsets.symmetric(vertical: 4),
|
||||
onPressed: () => onChanged(
|
||||
keyName,
|
||||
multi
|
||||
? _toggle(selected, chatQuestionOptionValue(option))
|
||||
: chatQuestionOptionValue(option),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(chatQuestionOptionLabel(option)),
|
||||
if ('${option['description'] ?? ''}'.trim().isNotEmpty)
|
||||
Text(
|
||||
'${option['description']}'.trim(),
|
||||
style: chatCardSecondaryStyle(context, cupertino),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (selected.contains(chatQuestionOptionValue(option)))
|
||||
const Icon(CupertinoIcons.checkmark),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
if (multi) {
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
for (final option in options)
|
||||
CheckboxListTile(
|
||||
value: selected.contains(chatQuestionOptionValue(option)),
|
||||
title: Text(chatQuestionOptionLabel(option)),
|
||||
subtitle: '${option['description'] ?? ''}'.trim().isEmpty
|
||||
? null
|
||||
: Text('${option['description']}'.trim()),
|
||||
contentPadding: EdgeInsets.zero,
|
||||
controlAffinity: ListTileControlAffinity.leading,
|
||||
onChanged: (on) => onChanged(
|
||||
keyName,
|
||||
_toggle(selected, chatQuestionOptionValue(option)),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
return RadioGroup<String>(
|
||||
groupValue: value is String ? value : null,
|
||||
onChanged: (next) => onChanged(keyName, next),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
for (final option in options)
|
||||
RadioListTile<String>(
|
||||
value: chatQuestionOptionValue(option),
|
||||
title: Text(chatQuestionOptionLabel(option)),
|
||||
subtitle: '${option['description'] ?? ''}'.trim().isEmpty
|
||||
? null
|
||||
: Text('${option['description']}'.trim()),
|
||||
contentPadding: EdgeInsets.zero,
|
||||
controlAffinity: ListTileControlAffinity.leading,
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Yes/No for a boolean field: native checkmarks under Cupertino, the web's
|
||||
/// explicit "Choose Yes or No" menu under Material.
|
||||
Widget chatQuestionBooleanField({
|
||||
required BuildContext context,
|
||||
required JsonMap field,
|
||||
required String keyName,
|
||||
required Map<String, dynamic> answers,
|
||||
required bool cupertino,
|
||||
required void Function(String key, Object? value) onChanged,
|
||||
}) {
|
||||
final value = answers[keyName];
|
||||
if (cupertino) {
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
for (final entry in const [('Yes', true), ('No', false)])
|
||||
CupertinoButton(
|
||||
padding: const EdgeInsets.symmetric(vertical: 4),
|
||||
onPressed: () => onChanged(keyName, entry.$2),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(child: Text(entry.$1)),
|
||||
if (value == entry.$2) const Icon(CupertinoIcons.checkmark),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
return DropdownButtonFormField<String>(
|
||||
initialValue: value is bool ? '$value' : null,
|
||||
hint: const Text('Choose Yes or No'),
|
||||
items: const [
|
||||
DropdownMenuItem(value: 'true', child: Text('Yes')),
|
||||
DropdownMenuItem(value: 'false', child: Text('No')),
|
||||
],
|
||||
onChanged: (next) =>
|
||||
onChanged(keyName, chatFormFieldValue(field, next ?? '')),
|
||||
);
|
||||
}
|
||||
|
||||
List<String> _toggle(Set<String> selected, String value) {
|
||||
final next = {...selected};
|
||||
if (!next.add(value)) next.remove(value);
|
||||
return next.toList();
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import 'chat_card_styles.dart';
|
||||
import 'chat_question_card_model.dart';
|
||||
|
||||
/// Recorded answers, read-only. Every answer key is shown, including ones the
|
||||
/// form fields no longer describe, so no recorded text is dropped.
|
||||
List<Widget> chatQuestionRecordedAnswers({
|
||||
required BuildContext context,
|
||||
required JsonMap form,
|
||||
required bool cupertino,
|
||||
}) {
|
||||
final answers = form['answers'] is Map
|
||||
? Map<String, dynamic>.from(form['answers'] as Map)
|
||||
: <String, dynamic>{};
|
||||
final shown = <String>{};
|
||||
final widgets = <Widget>[];
|
||||
for (final field in chatFormFields(form)) {
|
||||
final key = '${field['key'] ?? ''}'.trim();
|
||||
if (key.isEmpty || !answers.containsKey(key)) continue;
|
||||
shown.add(key);
|
||||
widgets.add(
|
||||
_recorded(
|
||||
context,
|
||||
_fieldLabel(field, key),
|
||||
_answerText(field, answers[key]),
|
||||
cupertino,
|
||||
),
|
||||
);
|
||||
}
|
||||
for (final entry in answers.entries) {
|
||||
if (shown.contains(entry.key)) continue;
|
||||
widgets.add(
|
||||
_recorded(
|
||||
context,
|
||||
entry.key,
|
||||
_answerText(null, entry.value),
|
||||
cupertino,
|
||||
),
|
||||
);
|
||||
}
|
||||
if (widgets.isEmpty) {
|
||||
return [
|
||||
Text(
|
||||
'No answer was recorded.',
|
||||
style: chatCardSecondaryStyle(context, cupertino),
|
||||
),
|
||||
];
|
||||
}
|
||||
return widgets;
|
||||
}
|
||||
|
||||
/// The field's display label, falling back past blank recorded strings the same
|
||||
/// way the pending field does.
|
||||
String _fieldLabel(JsonMap field, String key) {
|
||||
for (final candidate in [field['title'], field['description']]) {
|
||||
final text = '${candidate ?? ''}'.trim();
|
||||
if (text.isNotEmpty) return text;
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
Widget _recorded(
|
||||
BuildContext context,
|
||||
String label,
|
||||
String value,
|
||||
bool cupertino,
|
||||
) => Padding(
|
||||
padding: const EdgeInsets.only(top: 8),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(label, style: chatCardLabelStyle(context, cupertino)),
|
||||
Text(value, style: chatCardBodyStyle(context, cupertino)),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
String _answerText(JsonMap? field, Object? value) {
|
||||
final values = value is List ? value : [value];
|
||||
final boolean = field != null && '${field['type'] ?? ''}' == 'boolean';
|
||||
return values
|
||||
.map((entry) {
|
||||
// The editable control says Yes/No; the recorded view must use the same
|
||||
// words instead of exposing the raw protocol boolean.
|
||||
if (boolean && entry is bool) return entry ? 'Yes' : 'No';
|
||||
if (field == null) return '${entry ?? ''}';
|
||||
for (final option in chatQuestionOptions(field)) {
|
||||
if ('${entry ?? ''}' == chatQuestionOptionValue(option)) {
|
||||
return chatQuestionOptionLabel(option);
|
||||
}
|
||||
}
|
||||
return '${entry ?? ''}';
|
||||
})
|
||||
.join(', ');
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
/// Validation shared by the question card and its tests.
|
||||
///
|
||||
/// These are the web's `formAnswerError` rules plus the browser input
|
||||
/// constraints the card cannot delegate to Flutter: `pattern`, `format=email`,
|
||||
/// `format=uri` and `format=date`. The browser's localised `validationMessage`
|
||||
/// has no portable equivalent, so the fixed English sentences below stand in
|
||||
/// for it and are documented as an app addition.
|
||||
library;
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import 'chat_question_card_model.dart';
|
||||
|
||||
const _patternError = 'does not match the required format';
|
||||
const _emailError = 'is not a valid email address';
|
||||
const _urlError = 'is not a valid URL';
|
||||
const _dateError = 'is not a valid date';
|
||||
|
||||
/// The web's validation messages, in field order. An empty string is valid.
|
||||
String chatFormAnswerError(List<JsonMap> fields, Map<String, dynamic> answers) {
|
||||
for (final field in fields) {
|
||||
if (!chatFormFieldVisible(field, answers)) continue;
|
||||
if (_text(field['type']) == 'external') continue;
|
||||
final key = _text(field['key']);
|
||||
final value = answers[key];
|
||||
final missing =
|
||||
value == null || value == '' || (value is List && value.isEmpty);
|
||||
final label = _text(field['title']).isEmpty ? key : _text(field['title']);
|
||||
if (missing) {
|
||||
if (field['required'] == true) {
|
||||
return 'Answer $label before sending.';
|
||||
}
|
||||
continue;
|
||||
}
|
||||
final type = _text(field['type']);
|
||||
if (type == 'number' || type == 'integer') {
|
||||
final number = value is num ? value : null;
|
||||
final finite = number != null && number.isFinite;
|
||||
final integral =
|
||||
type != 'integer' ||
|
||||
(number != null && number is int) ||
|
||||
(number != null && number == number.roundToDouble());
|
||||
if (!finite || !integral) return '$label needs a valid $type.';
|
||||
final minimum = field['minimum'];
|
||||
final maximum = field['maximum'];
|
||||
if (minimum is num && number < minimum) {
|
||||
return '$label must be at least $minimum.';
|
||||
}
|
||||
if (maximum is num && number > maximum) {
|
||||
return '$label must be at most $maximum.';
|
||||
}
|
||||
}
|
||||
if (type == 'boolean' && value is! bool) {
|
||||
return '$label needs Yes or No.';
|
||||
}
|
||||
if (value is String) {
|
||||
final minLength = field['min_length'];
|
||||
final maxLength = field['max_length'];
|
||||
if (minLength is num && value.length < minLength) {
|
||||
return '$label is too short.';
|
||||
}
|
||||
if (maxLength is num && value.length > maxLength) {
|
||||
return '$label is too long.';
|
||||
}
|
||||
final pattern = _text(field['pattern']);
|
||||
if (pattern.isNotEmpty && !_matchesPattern(pattern, value)) {
|
||||
return '$label $_patternError.';
|
||||
}
|
||||
final formatError = _formatError(_text(field['format']), value);
|
||||
if (formatError.isNotEmpty) return '$label $formatError.';
|
||||
}
|
||||
if (value is List) {
|
||||
final minItems = field['min_items'];
|
||||
final maxItems = field['max_items'];
|
||||
if (minItems is num && value.length < minItems) {
|
||||
return 'Select at least $minItems choices for $label.';
|
||||
}
|
||||
if (maxItems is num && value.length > maxItems) {
|
||||
return 'Select at most $maxItems choices for $label.';
|
||||
}
|
||||
}
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
/// HTML's `pattern` attribute matches the whole value, not a substring.
|
||||
bool _matchesPattern(String pattern, String value) {
|
||||
try {
|
||||
return RegExp('^(?:$pattern)\$').hasMatch(value);
|
||||
} catch (_) {
|
||||
// An unparseable server pattern constrains nothing, exactly as an invalid
|
||||
// `pattern` attribute is ignored by the browser.
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
String _formatError(String format, String value) {
|
||||
switch (format) {
|
||||
case 'email':
|
||||
return RegExp(r'^[^@\s]+@[^@\s]+\.[^@\s]+$').hasMatch(value)
|
||||
? ''
|
||||
: _emailError;
|
||||
case 'uri':
|
||||
final uri = Uri.tryParse(value);
|
||||
return uri != null && uri.hasScheme && !RegExp(r'\s').hasMatch(value)
|
||||
? ''
|
||||
: _urlError;
|
||||
case 'date':
|
||||
return _isDate(value) ? '' : _dateError;
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
bool _isDate(String value) {
|
||||
final match = RegExp(r'^(\d{4})-(\d{2})-(\d{2})$').firstMatch(value);
|
||||
if (match == null) return false;
|
||||
final year = int.parse(match.group(1)!);
|
||||
final month = int.parse(match.group(2)!);
|
||||
final day = int.parse(match.group(3)!);
|
||||
final date = DateTime(year, month, day);
|
||||
return date.year == year && date.month == month && date.day == day;
|
||||
}
|
||||
|
||||
String _text(Object? value) => '${value ?? ''}'.trim();
|
||||
@@ -0,0 +1,190 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../data/chat_repository.dart';
|
||||
import 'chat_permission_card_model.dart';
|
||||
import 'chat_question_card_model.dart';
|
||||
|
||||
/// The open conversation's recorded approval requests and question forms.
|
||||
///
|
||||
/// This is the transcript controller's card collaborator: it owns frame folding,
|
||||
/// the operator's optimistic answers, server refusals and the one-shot send
|
||||
/// 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;
|
||||
/// [settledLimit] bounds that history so a long session cannot grow without
|
||||
/// limit while pending cards are never dropped.
|
||||
class ChatThreadCards {
|
||||
ChatThreadCards({
|
||||
required this.repository,
|
||||
required this.sessionId,
|
||||
required this.notify,
|
||||
required this.isAlive,
|
||||
});
|
||||
|
||||
static const settledLimit = 20;
|
||||
|
||||
final ChatRepository repository;
|
||||
final String sessionId;
|
||||
final void Function() notify;
|
||||
final bool Function() isAlive;
|
||||
|
||||
final List<JsonMap> _permissions = [];
|
||||
final Map<String, JsonMap> _forms = {};
|
||||
final Map<String, String> _answers = {};
|
||||
final Map<String, String> _permissionErrors = {};
|
||||
final Map<String, String> _formErrors = {};
|
||||
final ChatActionGate _permissionGate = ChatActionGate();
|
||||
final ChatActionGate _questionGate = ChatActionGate();
|
||||
|
||||
/// Every retained permission request, settled or still open, in server order.
|
||||
List<JsonMap> get permissions => List.unmodifiable(_permissions);
|
||||
|
||||
/// Every retained question form, including answered and expired ones.
|
||||
List<JsonMap> get forms => List.unmodifiable(_forms.values);
|
||||
|
||||
String answerFor(String requestId) => _answers[requestId] ?? '';
|
||||
|
||||
String? permissionErrorFor(String requestId) =>
|
||||
_permissionErrors[requestId];
|
||||
|
||||
String? formErrorFor(String formId) => _formErrors[formId];
|
||||
|
||||
/// Answer one pending approval. The local decision settles the card before
|
||||
/// the reply lands; a refusal reopens the same request with the server's
|
||||
/// reason so an unaccepted decision is never shown as accepted. A second tap
|
||||
/// of the same confirmed action is ignored until it settles.
|
||||
Future<void> replyPermission(String requestId, String decision) async {
|
||||
final id = requestId.trim();
|
||||
if (id.isEmpty || !chatDecisions.contains(decision)) return;
|
||||
final frame = _permissionFrame(id);
|
||||
if (frame == null || frame['resolved'] == true) return;
|
||||
final replyId = chatPermissionReplyId(id, decision);
|
||||
if (!_permissionGate.start(replyId)) return;
|
||||
_answers[id] = decision;
|
||||
_permissionErrors.remove(id);
|
||||
notify();
|
||||
try {
|
||||
await repository.replyPermission(sessionId, id, decision);
|
||||
if (!isAlive()) return;
|
||||
// A previous refusal's reason no longer describes an accepted reply.
|
||||
if (_permissionErrors.remove(id) != null) notify();
|
||||
} catch (error) {
|
||||
if (!isAlive()) return;
|
||||
final current = _permissionFrame(id);
|
||||
// A server resolution that raced the refusal wins: do not reopen it.
|
||||
if (current == null || current['resolved'] == true) return;
|
||||
_answers.remove(id);
|
||||
_permissionErrors[id] = '$error';
|
||||
_permissionGate.release(replyId);
|
||||
notify();
|
||||
}
|
||||
}
|
||||
|
||||
/// Answer or close a pending question with the web's field-keyed body. A
|
||||
/// refusal keeps the card open and reports the server's reason.
|
||||
Future<void> answerQuestion(
|
||||
String formId,
|
||||
Map<String, dynamic> answers,
|
||||
String action,
|
||||
) async {
|
||||
final id = formId.trim();
|
||||
final form = _forms[id];
|
||||
if (id.isEmpty || form == null || !chatFormPending(form)) return;
|
||||
final replyId = chatQuestionReplyId(id, action: action);
|
||||
if (!_questionGate.start(replyId)) return;
|
||||
_formErrors.remove(id);
|
||||
notify();
|
||||
try {
|
||||
await repository.answerForm(
|
||||
sessionId,
|
||||
id,
|
||||
Map<String, dynamic>.from(answers),
|
||||
action: action,
|
||||
);
|
||||
if (!isAlive()) return;
|
||||
_forms[id] = {
|
||||
...form,
|
||||
'resolved': true,
|
||||
if (answers.isNotEmpty)
|
||||
'answers': Map<String, dynamic>.from(answers),
|
||||
};
|
||||
_pruneSettledForms();
|
||||
notify();
|
||||
} catch (error) {
|
||||
if (!isAlive()) return;
|
||||
_formErrors[id] = '$error';
|
||||
_questionGate.release(replyId);
|
||||
notify();
|
||||
}
|
||||
}
|
||||
|
||||
/// Fold one pushed `chat_permission` frame. A repeat for the same request
|
||||
/// replaces the recorded frame (a server resolution then wins over any local
|
||||
/// answer); a frame for a new request is added after the held cards.
|
||||
void foldPermission(JsonMap frame) {
|
||||
final id = '${frame['request_id'] ?? ''}'.trim();
|
||||
if (id.isEmpty) return;
|
||||
final index = _permissions.indexWhere(
|
||||
(held) => '${held['request_id'] ?? ''}'.trim() == id,
|
||||
);
|
||||
if (index < 0) {
|
||||
_permissions.add(frame);
|
||||
} else {
|
||||
_permissions[index] = frame;
|
||||
}
|
||||
if (frame['resolved'] == true) _permissionErrors.remove(id);
|
||||
_pruneSettledPermissions();
|
||||
notify();
|
||||
}
|
||||
|
||||
/// Fold one `form` event. A folded update keeps a settled form's recorded
|
||||
/// answers for the read-only card.
|
||||
void foldForm(JsonMap form) {
|
||||
final id = '${form['id'] ?? ''}'.trim();
|
||||
if (id.isEmpty) return;
|
||||
final next = chatFoldQuestionFrame(_forms, form);
|
||||
if (identical(next, _forms)) return;
|
||||
_forms
|
||||
..clear()
|
||||
..addAll(next);
|
||||
_formErrors.remove(id);
|
||||
_pruneSettledForms();
|
||||
notify();
|
||||
}
|
||||
|
||||
JsonMap? _permissionFrame(String requestId) {
|
||||
for (final frame in _permissions) {
|
||||
if ('${frame['request_id'] ?? ''}'.trim() == requestId) return frame;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
bool _permissionSettled(JsonMap frame) =>
|
||||
frame['resolved'] == true ||
|
||||
'${frame['decision'] ?? ''}'.trim().isNotEmpty;
|
||||
|
||||
void _pruneSettledPermissions() {
|
||||
final settled = _permissions.where(_permissionSettled).toList();
|
||||
final excess = settled.length - settledLimit;
|
||||
if (excess <= 0) return;
|
||||
for (final frame in settled.take(excess)) {
|
||||
_permissions.remove(frame);
|
||||
final id = '${frame['request_id'] ?? ''}'.trim();
|
||||
_answers.remove(id);
|
||||
_permissionErrors.remove(id);
|
||||
}
|
||||
}
|
||||
|
||||
void _pruneSettledForms() {
|
||||
final settled = [
|
||||
for (final entry in _forms.entries)
|
||||
if (!chatFormPending(entry.value)) entry.key,
|
||||
];
|
||||
final excess = settled.length - settledLimit;
|
||||
if (excess <= 0) return;
|
||||
for (final id in settled.take(excess)) {
|
||||
_forms.remove(id);
|
||||
_formErrors.remove(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import 'package:flutter/foundation.dart';
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../data/chat_repository.dart';
|
||||
import '../domain/chat_transcript.dart';
|
||||
import 'chat_thread_cards.dart';
|
||||
|
||||
/// One open conversation's transcript and live turn state.
|
||||
///
|
||||
@@ -15,6 +16,9 @@ import '../domain/chat_transcript.dart';
|
||||
/// instead of merging stale state. The server detaches subscriptions when the
|
||||
/// socket closes, so disposal only cancels the local stream (there is no
|
||||
/// `chat_unsubscribe`).
|
||||
///
|
||||
/// Approval requests and question forms are recorded cards rather than
|
||||
/// messages; [ChatThreadCards] owns their frames, answers and send gates.
|
||||
class ChatThreadController extends ChangeNotifier {
|
||||
ChatThreadController(this.gateway, this.sessionId) {
|
||||
_subscription = gateway.frames.listen(_onFrame);
|
||||
@@ -23,6 +27,12 @@ class ChatThreadController extends ChangeNotifier {
|
||||
final ApiGateway gateway;
|
||||
final String sessionId;
|
||||
late final ChatRepository _repository = ChatRepository(gateway);
|
||||
late final ChatThreadCards _cards = ChatThreadCards(
|
||||
repository: _repository,
|
||||
sessionId: sessionId,
|
||||
notify: _notify,
|
||||
isAlive: () => !_disposed,
|
||||
);
|
||||
StreamSubscription<JsonMap>? _subscription;
|
||||
|
||||
List<JsonMap> _messages = const [];
|
||||
@@ -53,6 +63,30 @@ class ChatThreadController extends ChangeNotifier {
|
||||
bool get subscribed => _subscribed;
|
||||
String? get subscriptionError => _subscriptionError;
|
||||
|
||||
/// Every retained permission request, settled or still open, in server order.
|
||||
List<JsonMap> get permissionFrames => _cards.permissions;
|
||||
|
||||
/// Every retained question form, including answered and expired ones.
|
||||
List<JsonMap> get questionForms => _cards.forms;
|
||||
|
||||
String permissionAnswerFor(String requestId) => _cards.answerFor(requestId);
|
||||
|
||||
String? permissionErrorFor(String requestId) =>
|
||||
_cards.permissionErrorFor(requestId);
|
||||
|
||||
String? questionErrorFor(String formId) => _cards.formErrorFor(formId);
|
||||
|
||||
/// Answer one pending approval through the card collaborator.
|
||||
Future<void> replyPermission(String requestId, String decision) =>
|
||||
_cards.replyPermission(requestId, decision);
|
||||
|
||||
/// Answer or close a pending question through the card collaborator.
|
||||
Future<void> answerQuestion(
|
||||
String formId,
|
||||
Map<String, dynamic> answers,
|
||||
String action,
|
||||
) => _cards.answerQuestion(formId, answers, action);
|
||||
|
||||
/// Subscribes this session, then loads its newest history page.
|
||||
Future<void> load() async {
|
||||
if (_disposed) return;
|
||||
@@ -174,12 +208,26 @@ class ChatThreadController extends ChangeNotifier {
|
||||
|
||||
void _onFrame(JsonMap envelope) {
|
||||
if (_disposed) return;
|
||||
if (envelope['type'] == 'chat_permission') {
|
||||
final permission = envelope['chat_permission'];
|
||||
if (permission is! Map) return;
|
||||
final frame = Map<String, dynamic>.from(permission);
|
||||
if ('${frame['session_id'] ?? ''}' != sessionId) return;
|
||||
_cards.foldPermission(frame);
|
||||
return;
|
||||
}
|
||||
final body = _eventBody(envelope);
|
||||
if (body == null || body['session_id'] != sessionId) return;
|
||||
if (body['kind'] == 'resync') {
|
||||
unawaited(resync());
|
||||
return;
|
||||
}
|
||||
if (body['kind'] == 'form') {
|
||||
final form = body['form'];
|
||||
if (form is! Map) return;
|
||||
_cards.foldForm(Map<String, dynamic>.from(form));
|
||||
return;
|
||||
}
|
||||
final current = _thread;
|
||||
final next = applyChatEvent(current, body);
|
||||
if (identical(next, current)) return;
|
||||
|
||||
@@ -13,6 +13,7 @@ import 'chat_composer_controller.dart';
|
||||
import 'chat_draft_store.dart';
|
||||
import 'chat_row_keys.dart';
|
||||
import 'chat_thread_controller.dart';
|
||||
import 'chat_transcript_card.dart';
|
||||
|
||||
/// One read-only conversation: the controller's transcript in the order the
|
||||
/// server reports it, rendered by the existing [ChatMessageView].
|
||||
@@ -149,7 +150,18 @@ class _ChatThreadViewState extends State<ChatThreadView> {
|
||||
builder: (context, _) {
|
||||
final cupertino =
|
||||
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
|
||||
final rows = transcriptRows(_visibleMessages());
|
||||
final cards = chatCardRows(
|
||||
permissions: _controller.permissionFrames,
|
||||
forms: _controller.questionForms,
|
||||
answerFor: _controller.permissionAnswerFor,
|
||||
permissionErrorFor: _controller.permissionErrorFor,
|
||||
formErrorFor: _controller.questionErrorFor,
|
||||
);
|
||||
// A pending approval/question means the turn is waiting on the operator,
|
||||
// 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);
|
||||
// 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
|
||||
@@ -242,12 +254,20 @@ class _ChatThreadViewState extends State<ChatThreadView> {
|
||||
Padding(
|
||||
key: ValueKey<String>(keys[index]),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: ChatMessageView(
|
||||
row: rows[index],
|
||||
textBuilder: chatMarkdownText,
|
||||
),
|
||||
child:
|
||||
rows[index]['kind'] == 'permission' ||
|
||||
rows[index]['kind'] == 'question'
|
||||
? ChatTranscriptCard(
|
||||
row: rows[index],
|
||||
onPermissionDecision: _controller.replyPermission,
|
||||
onQuestionAnswer: _controller.answerQuestion,
|
||||
)
|
||||
: ChatMessageView(
|
||||
row: rows[index],
|
||||
textBuilder: chatMarkdownText,
|
||||
),
|
||||
),
|
||||
if (_controller.running)
|
||||
if (_controller.running && !awaiting)
|
||||
Padding(
|
||||
key: const Key('chat-running'),
|
||||
padding: const EdgeInsets.all(16),
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import 'chat_permission_card.dart';
|
||||
import 'chat_permission_card_model.dart';
|
||||
import 'chat_question_card.dart';
|
||||
import 'chat_question_card_model.dart';
|
||||
|
||||
/// Build transcript card rows for recorded permission requests and questions.
|
||||
///
|
||||
/// Cards are not transcript messages: they keep the server's order and follow
|
||||
/// the message rows. Their keys are the server ids, so a streaming repaint
|
||||
/// keeps an open disclosure or a half-typed answer attached to the same card.
|
||||
List<JsonMap> chatCardRows({
|
||||
required Iterable<JsonMap> permissions,
|
||||
required Iterable<JsonMap> forms,
|
||||
required String Function(String requestId) answerFor,
|
||||
required String? Function(String requestId) permissionErrorFor,
|
||||
required String? Function(String formId) formErrorFor,
|
||||
}) {
|
||||
final rows = <JsonMap>[];
|
||||
for (final permission in permissions) {
|
||||
final id = '${permission['request_id'] ?? ''}'.trim();
|
||||
if (id.isEmpty) continue;
|
||||
rows.add({
|
||||
'kind': 'permission',
|
||||
'key': 'chat-permission-$id',
|
||||
'frame': permission,
|
||||
'answer': answerFor(id),
|
||||
'error': permissionErrorFor(id),
|
||||
});
|
||||
}
|
||||
for (final form in forms) {
|
||||
final id = '${form['id'] ?? ''}'.trim();
|
||||
if (id.isEmpty) continue;
|
||||
rows.add({
|
||||
'kind': 'question',
|
||||
'key': 'chat-question-$id',
|
||||
'form': form,
|
||||
'error': formErrorFor(id),
|
||||
});
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
/// True while one card still needs the operator: an open approval request or a
|
||||
/// pending question form.
|
||||
///
|
||||
/// A turn blocked on the operator is not generating, so the transcript's running
|
||||
/// indicator stands down while this is true (the web does the same); the
|
||||
/// composer's Stop control remains driven by the turn alone.
|
||||
bool chatCardAwaitingOperator(JsonMap row) {
|
||||
final kind = '${row['kind'] ?? ''}';
|
||||
if (kind == 'permission') {
|
||||
final frame = row['frame'];
|
||||
if (frame is! Map) return false;
|
||||
final card = chatPermissionCard(
|
||||
Map<String, dynamic>.from(frame),
|
||||
'${row['answer'] ?? ''}',
|
||||
);
|
||||
return card?.actionable == true;
|
||||
}
|
||||
if (kind == 'question') {
|
||||
final form = row['form'];
|
||||
return form is Map && chatFormPending(Map<String, dynamic>.from(form));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// Small dispatcher: render one card row with the host's native controls.
|
||||
class ChatTranscriptCard extends StatelessWidget {
|
||||
const ChatTranscriptCard({
|
||||
super.key,
|
||||
required this.row,
|
||||
required this.onPermissionDecision,
|
||||
required this.onQuestionAnswer,
|
||||
});
|
||||
|
||||
final JsonMap row;
|
||||
final Future<void> Function(String requestId, String decision)
|
||||
onPermissionDecision;
|
||||
final Future<void> Function(
|
||||
String formId,
|
||||
Map<String, dynamic> answers,
|
||||
String action,
|
||||
)
|
||||
onQuestionAnswer;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final kind = '${row['kind'] ?? ''}';
|
||||
if (kind == 'permission') {
|
||||
final frame = row['frame'] is Map
|
||||
? Map<String, dynamic>.from(row['frame'] as Map)
|
||||
: null;
|
||||
final card = chatPermissionCard(frame, '${row['answer'] ?? ''}');
|
||||
if (card == null) return const SizedBox.shrink();
|
||||
return ChatPermissionCard(
|
||||
card: card,
|
||||
error: row['error'] as String?,
|
||||
onDecision: (decision) =>
|
||||
onPermissionDecision(card.requestId, decision),
|
||||
);
|
||||
}
|
||||
if (kind == 'question') {
|
||||
final form = row['form'] is Map
|
||||
? Map<String, dynamic>.from(row['form'] as Map)
|
||||
: null;
|
||||
if (form == null || '${form['id'] ?? ''}'.trim().isEmpty) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
final id = '${form['id']}'.trim();
|
||||
return ChatQuestionCard(
|
||||
form: form,
|
||||
error: row['error'] as String?,
|
||||
onSubmit: (answers, action) => onQuestionAnswer(id, answers, action),
|
||||
);
|
||||
}
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
}
|
||||
@@ -40,7 +40,14 @@ JsonMap mergeChatHistory(JsonMap previous, JsonMap page, {bool older = false}) {
|
||||
/// identity uses `messageIds`. That list carries every message the folded turn
|
||||
/// currently holds so the view can keep the same row element while the turn
|
||||
/// grows at either end.
|
||||
List<JsonMap> transcriptRows(List<JsonMap> messages) {
|
||||
///
|
||||
/// [trailing] rows are conversation cards (permission requests and questions),
|
||||
/// not messages. They keep the server's order after the transcript, the way the
|
||||
/// web renders approvals and forms at the end of the conversation.
|
||||
List<JsonMap> transcriptRows(
|
||||
List<JsonMap> messages, {
|
||||
List<JsonMap> trailing = const [],
|
||||
}) {
|
||||
final rows = <JsonMap>[];
|
||||
String? key;
|
||||
final ids = <String>[];
|
||||
@@ -73,6 +80,7 @@ List<JsonMap> transcriptRows(List<JsonMap> messages) {
|
||||
}
|
||||
}
|
||||
flush();
|
||||
rows.addAll(trailing);
|
||||
return rows;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
# C4-approvals — native permission and question cards
|
||||
|
||||
One checked integration slice: the chat conversation now renders recorded
|
||||
`chat_permission` frames and `form` question frames as native Material/Cupertino
|
||||
cards, answers them through the landed `ChatRepository` request facade, and
|
||||
records the outcome. App-only; no server, `web/`, Android/iOS, shell, route or
|
||||
deployment source was edited.
|
||||
|
||||
## What changed
|
||||
|
||||
| File | Lines | Responsibility |
|
||||
| --- | ---: | --- |
|
||||
| `lib/features/chat/conversation/chat_permission_card_model.dart` | 192 | approval card derivation, risk/resource wording, decision labels, one-shot reply ids |
|
||||
| `lib/features/chat/conversation/chat_permission_card.dart` | 267 | native approval card: kind/headline/status, six-line resources with full-request disclosure, risk panel, once/always/reject |
|
||||
| `lib/features/chat/conversation/chat_question_card_model.dart` | 206 | field visibility/values, web validation messages, visible answers, form folding, answer ids |
|
||||
| `lib/features/chat/conversation/chat_question_card_fields.dart` | 179 | editable field shell, free-text inputs, external-URL text |
|
||||
| `lib/features/chat/conversation/chat_question_option_controls.dart` | 160 | native single/multi select and boolean controls |
|
||||
| `lib/features/chat/conversation/chat_question_recorded_answers.dart` | 99 | read-only recorded answers, including unknown keys |
|
||||
| `lib/features/chat/conversation/chat_question_card.dart` | 275 | pending/answered/expired question card, local answer state, submit/actions |
|
||||
| `lib/features/chat/conversation/chat_transcript_card.dart` | 96 | card-row builder and small permission/question dispatcher |
|
||||
| `lib/features/chat/domain/chat_transcript.dart` | +10/-2 | `transcriptRows(..., trailing:)` keeps cards after the message rows |
|
||||
| `lib/features/chat/conversation/chat_thread_controller.dart` | +140 | folded permission/form frames, answers, errors and one-shot send gates |
|
||||
| `lib/features/chat/conversation/chat_thread_view.dart` | +26/-6 | builds/dispatches card rows inside the existing conversation list |
|
||||
| `app/PARITY.md` | row update | states the native cards as Source, with the real-request smoke still open |
|
||||
| `test/.../chat_permission_card_test.dart` | 300 | model + native behaviour + pushed-frame integration |
|
||||
| `test/.../chat_question_card_test.dart` | 360 | field rules + native behaviour + pushed-frame integration |
|
||||
| `tool/chat_approvals_probe.dart` | 167 | real-widget fixture with a scripted replaying gateway |
|
||||
| `tool/chat_approvals_probe.mjs` | 335 | Chrome CDP interaction, OCR assertions and captures |
|
||||
|
||||
Production files stay under the ~250-line aim except the two 267/275-line card
|
||||
shells; the larger question work is split by responsibility (fields, option
|
||||
controls, recorded answers) rather than arbitrary fragments.
|
||||
|
||||
## Behaviour
|
||||
|
||||
- **Permission card.** Kind line `Permission request · {source.type}` when the
|
||||
server records one, else `Permission request`. Headline `Approve {action}`
|
||||
(`Approve tool call` when blank). Status `Waiting for your response`.
|
||||
Resources are the server's non-blank entries joined by newlines, displayed at
|
||||
most six lines with an ellipsis on the last kept line; when truncated, the
|
||||
native disclosure `Show full request` carries every recorded resource. The risk
|
||||
panel uses the server's `message`, else the web's neutral sentence naming the
|
||||
action, and shows only while pending or after a rejection. Controls use the
|
||||
exact `Allow once` / `always_label or Always allow` / `Reject` labels and only
|
||||
while pending.
|
||||
- **Permission outcome.** Answering settles the card optimistically to the
|
||||
decision label and `Waiting for the agent to continue…`. A server
|
||||
`resolved`/`decision` frame always wins, shows the decision label (or
|
||||
`Already resolved` when the recorded decision is blank) and its `message`/the
|
||||
web's fallback note. A refusal clears the optimistic answer, keeps the card
|
||||
pending, and shows the server reason in a live region.
|
||||
- **Reply wire.** `ChatRepository.replyPermission` sends exactly
|
||||
`{chat_reply:{session_id,request_id,decision,client:'Web'}}`; no extra field is
|
||||
added. Each confirmed action has the stable local id
|
||||
`chat-reply:{requestId}:{decision}` held by a `ChatActionGate`, so a double tap
|
||||
sends once and a refused send reopens only that id for retry.
|
||||
- **Question card.** Shows the recorded title (or `Question`) and
|
||||
`The agent is waiting for your answer.`. Options keep the server's value/label
|
||||
and description exactly; single-select is a radio group under Material and a
|
||||
checkmark row under Cupertino, multi-select is checkboxes/checkmarks, booleans
|
||||
are the explicit Yes/No menu under Material and checkmark rows under Cupertino.
|
||||
Free text appears for `custom` fields or fields with no options, with number,
|
||||
email, URL and date keyboards and secret input where recorded.
|
||||
- **Question rules.** Visibility honours `hidden` and `when` (`eq`/`neq`).
|
||||
Answers preserve `false` and `0`. Required missing answers, invalid
|
||||
number/integer, min/max bounds, boolean type, string length and item counts
|
||||
produce the web's exact messages; invalid input blocks the send and shows the
|
||||
reason. Visible, non-external, answered fields alone travel in `chat_answer`.
|
||||
`accept` is sent when the form lists it; `Decline` / `Cancel question` use the
|
||||
recorded actions and an empty answer map.
|
||||
- **Question outcome.** Submit is one-shot through the stable id
|
||||
`chat-answer:{formId}:{action|answer}`. Success marks the form resolved locally
|
||||
and shows `Answer recorded.`; the server's resolved/cancelled echo replaces it
|
||||
with the recorded answers. `cancelled` shows `This question expired.`.
|
||||
Read-only rendering includes answers for fields no longer present, and says
|
||||
`No answer was recorded.` when the resolved form recorded none. A refusal keeps
|
||||
the card pending with its typed state and shows the server reason.
|
||||
- **Composition.** Cards follow the message rows in server order (permissions
|
||||
then questions), keyed by request/form id so streaming repaints keep an open
|
||||
disclosure or half-typed answer. Unknown message parts still render through the
|
||||
existing plain `Unrecognised part` disclosure; nothing in `ChatMessageView` or
|
||||
the markdown renderer changed.
|
||||
|
||||
## Checks actually run (after the final split)
|
||||
|
||||
- `flutter analyze` — `No issues found!`
|
||||
- `flutter test` — `All tests passed!` (1003 tests, including the 20 new focused
|
||||
card/model/controller cases)
|
||||
- `flutter build web --output build/web-acceptance` — `✓ Built`
|
||||
- `node tool/chat_approvals_probe.mjs` for both hosts — see below.
|
||||
|
||||
## Browser fixture evidence
|
||||
|
||||
The fixture runs the **real** `ChatThreadView`/controller against a scripted
|
||||
gateway that replays one pending `chat_permission` and one `form` question on
|
||||
subscribe, then echoes the reply/answer back as a resolved frame. Chrome CDP at
|
||||
320px logical width, device scale 2, dark appearance, both hosts. Static card
|
||||
text is OCR-verified because Flutter web paints it on the canvas; controls are
|
||||
driven through semantics.
|
||||
|
||||
Captures and evidence (shared run artifacts):
|
||||
|
||||
- `public/chat-approvals-probe/material-cards.png`
|
||||
- `public/chat-approvals-probe/material-approval-answered.png`
|
||||
- `public/chat-approvals-probe/material-question-answered.png`
|
||||
- `public/chat-approvals-probe/material-evidence.json`
|
||||
- `public/chat-approvals-probe/cupertino-cards.png`
|
||||
- `public/chat-approvals-probe/cupertino-approval-answered.png`
|
||||
- `public/chat-approvals-probe/cupertino-question-answered.png`
|
||||
- `public/chat-approvals-probe/cupertino-evidence.json`
|
||||
|
||||
Each run asserted the pending card's recorded action, status, risk, resource
|
||||
lines and all three control labels; that `Allow once` sent the reply (the fixture's
|
||||
server resolution replaced it with `Allowed once` and cleared the controls); and
|
||||
that selecting `Red` + `Send answer` sent the answer and produced the read-only
|
||||
`Answer recorded.` card. Both runs finished with `sendAnswerStillVisible:false`
|
||||
and `allowOnceStillVisible:false`. The Material capture also shows no clipped
|
||||
text at 320/2x; the Cupertino capture uses only Cupertino controls (widget tests
|
||||
assert no `Material` ancestor in that host).
|
||||
|
||||
## Limits, stated plainly
|
||||
|
||||
- **No live server request was answered.** The fixture's gateway is scripted and
|
||||
its reply/answer responses are local; no operator chat, run, approval or real
|
||||
server was mutated.
|
||||
- **No authenticated smoke yet.** The `PARITY.md` row remains Source, not Preview:
|
||||
a real pending approval/question against the authenticated server, and a
|
||||
multi-client server resolution, are still unverified.
|
||||
- **Web only.** Android/iOS builds, ADB, emulators and device/OS behavior were not
|
||||
run (per the app working agreement); source is portable but mobile is
|
||||
unverified.
|
||||
- **External question forms** display only their recorded HTTP(S) URL as
|
||||
selectable text; no URL launcher dependency exists in this app, so they are not
|
||||
opened from the card. Unsupported URLs show the web's alert wording instead.
|
||||
- **Uncommitted.** The pipeline input asked for a candidate commit, but the stage
|
||||
instructions explicitly say not to commit, push or deploy, so the work is left
|
||||
in the working tree (`flutter/chat-approvals`) with no commit or merge.
|
||||
|
||||
## Manager completion after a harness transport failure
|
||||
|
||||
The run ended on a harness transport error (`/api/session/active`) after a full
|
||||
Code visit; the retained tree was complete. Manager verified 173 chat tests,
|
||||
clean analysis, and the both-host browser probe. Two probe expectations were
|
||||
corrected against the web rather than against the app: the approval card's
|
||||
headline is the recorded action (the web has no separate "Permission request"
|
||||
heading), and OCR merges whitespace, so comparisons now ignore it and accept a
|
||||
control that is present in the semantics tree. No app behaviour was changed to
|
||||
make the probe pass.
|
||||
@@ -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>{};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'package:pipelines_app/core/api_gateway.dart';
|
||||
import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart';
|
||||
|
||||
/// Browser fixture for the chat approval and question cards.
|
||||
///
|
||||
/// The real [ChatThreadView] drives the real controller against this scripted
|
||||
/// gateway. The gateway replays one pending permission and one question on
|
||||
/// subscribe, and echoes the recorded decision/answer back as the server would,
|
||||
/// so the cards' answered states are produced by the reply path, not hardcoded.
|
||||
class _ApprovalsGateway implements ApiGateway {
|
||||
final _frames = StreamController<JsonMap>.broadcast();
|
||||
bool _sent = false;
|
||||
|
||||
@override
|
||||
Stream<JsonMap> get frames => _frames.stream;
|
||||
|
||||
@override
|
||||
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
|
||||
switch (type) {
|
||||
case 'chat_subscribe':
|
||||
if (!_sent) {
|
||||
_sent = true;
|
||||
Timer(const Duration(milliseconds: 400), _replayPending);
|
||||
}
|
||||
return {};
|
||||
case 'chat_messages':
|
||||
return {
|
||||
'chat_history': {
|
||||
'messages': [
|
||||
{
|
||||
'id': 'probe-user',
|
||||
'role': 'user',
|
||||
'parts': [
|
||||
{
|
||||
'type': 'text',
|
||||
'text': 'Show me the recorded approval and question cards.',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
'next_cursor': '',
|
||||
'has_more': false,
|
||||
},
|
||||
};
|
||||
case 'chat_reply':
|
||||
final body = fields['chat_reply'] as Map? ?? const {};
|
||||
final requestId = '${body['request_id'] ?? ''}';
|
||||
final decision = '${body['decision'] ?? ''}';
|
||||
_frames.add({
|
||||
'type': 'chat_permission',
|
||||
'chat_permission': {
|
||||
..._permission,
|
||||
'resolved': true,
|
||||
'decision': decision,
|
||||
'message': 'Recorded by the probe fixture after $decision.',
|
||||
'request_id': requestId,
|
||||
},
|
||||
});
|
||||
return {};
|
||||
case 'chat_answer':
|
||||
final body = fields['chat_answer'] as Map? ?? const {};
|
||||
_frames.add({
|
||||
'type': 'chat_event',
|
||||
'chat_event': {
|
||||
'session_id': 'probe-session',
|
||||
'kind': 'form',
|
||||
'form': {
|
||||
..._question,
|
||||
'resolved': true,
|
||||
'answers': body['answers'] ?? const <String, dynamic>{},
|
||||
},
|
||||
},
|
||||
});
|
||||
return {};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
void _replayPending() {
|
||||
if (_frames.isClosed) return;
|
||||
_frames.add({'type': 'chat_permission', 'chat_permission': _permission});
|
||||
_frames.add({
|
||||
'type': 'chat_event',
|
||||
'chat_event': {
|
||||
'session_id': 'probe-session',
|
||||
'kind': 'form',
|
||||
'form': _question,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
static const _permission = <String, dynamic>{
|
||||
'session_id': 'probe-session',
|
||||
'request_id': 'probe-permission',
|
||||
'action': 'bash',
|
||||
'resources': [
|
||||
'command: rm -rf build',
|
||||
'cwd: /workspace/demo',
|
||||
],
|
||||
'message': 'This deletes the build output.',
|
||||
'source': {'type': 'tool'},
|
||||
};
|
||||
|
||||
static const _question = <String, dynamic>{
|
||||
'id': 'probe-question',
|
||||
'session_id': 'probe-session',
|
||||
'kind': 'question',
|
||||
'title': 'A demo question',
|
||||
'actions': ['accept'],
|
||||
'fields': [
|
||||
{
|
||||
'key': 'colour',
|
||||
'title': 'Colour',
|
||||
'type': 'string',
|
||||
'required': true,
|
||||
'options': [
|
||||
{'value': 'red', 'label': 'Red'},
|
||||
{'value': 'blue', 'label': 'Blue'},
|
||||
],
|
||||
},
|
||||
{
|
||||
'key': 'note',
|
||||
'title': 'Notes',
|
||||
'type': 'string',
|
||||
'placeholder': 'Optional note',
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
const _style = String.fromEnvironment(
|
||||
'CHAT_APPROVALS_PROBE_STYLE',
|
||||
defaultValue: 'material',
|
||||
);
|
||||
|
||||
void main() {
|
||||
final gateway = _ApprovalsGateway();
|
||||
final thread = ChatThreadView(
|
||||
gateway: gateway,
|
||||
sessionId: 'probe-session',
|
||||
title: 'Probe conversation',
|
||||
onBack: () {},
|
||||
);
|
||||
if (_style == 'cupertino') {
|
||||
runApp(
|
||||
CupertinoApp(
|
||||
theme: const CupertinoThemeData(brightness: Brightness.dark),
|
||||
home: CupertinoPageScaffold(child: SafeArea(child: thread)),
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
runApp(
|
||||
MaterialApp(
|
||||
theme: ThemeData(
|
||||
brightness: Brightness.dark,
|
||||
platform: TargetPlatform.android,
|
||||
),
|
||||
home: Scaffold(body: SafeArea(child: thread)),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,356 @@
|
||||
// Real-browser evidence for the chat approval and question cards.
|
||||
//
|
||||
// Build one host, then run from app/:
|
||||
// flutter build web -t tool/chat_approvals_probe.dart \
|
||||
// --dart-define=CHAT_APPROVALS_PROBE_STYLE=material \
|
||||
// --output build/probe-chat-approvals-material
|
||||
// node tool/chat_approvals_probe.mjs \
|
||||
// --root build/probe-chat-approvals-material --out DIR --style material
|
||||
//
|
||||
// The same fixture is built with CHAT_APPROVALS_PROBE_STYLE=cupertino. The
|
||||
// script drives the real widget/controller through Chrome DevTools semantics,
|
||||
// approves one permission and answers one question, and asserts the recorded
|
||||
// answered states plus saved captures.
|
||||
import { createServer } from 'node:http';
|
||||
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
|
||||
import { spawn, execFile } from 'node:child_process';
|
||||
import { once } from 'node:events';
|
||||
import { promisify } from 'node:util';
|
||||
import { setTimeout as delay } from 'node:timers/promises';
|
||||
import { extname, join, resolve, sep } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
|
||||
const args = new Map();
|
||||
for (let i = 2; i < process.argv.length; i++) {
|
||||
const value = process.argv[i];
|
||||
if (value.startsWith('--')) args.set(value.slice(2), process.argv[++i]);
|
||||
}
|
||||
const root = resolve(args.get('root') ?? 'build/probe-chat-approvals-material');
|
||||
const out = resolve(args.get('out') ?? 'build/chat-approvals-probe');
|
||||
const style = args.get('style') ?? 'material';
|
||||
const chromePath =
|
||||
process.env.CHROME_PATH ??
|
||||
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
|
||||
await mkdir(out, { recursive: true });
|
||||
|
||||
const mime = {
|
||||
'.html': 'text/html; charset=utf-8',
|
||||
'.js': 'text/javascript; charset=utf-8',
|
||||
'.json': 'application/json; charset=utf-8',
|
||||
'.wasm': 'application/wasm',
|
||||
'.png': 'image/png',
|
||||
'.svg': 'image/svg+xml',
|
||||
'.ico': 'image/x-icon',
|
||||
'.ttf': 'font/ttf',
|
||||
'.otf': 'font/otf',
|
||||
'.woff': 'font/woff',
|
||||
'.woff2': 'font/woff2',
|
||||
'.bin': 'application/octet-stream',
|
||||
};
|
||||
|
||||
const server = createServer(async (req, res) => {
|
||||
try {
|
||||
const pathname = decodeURIComponent(
|
||||
new URL(req.url, 'http://localhost').pathname,
|
||||
);
|
||||
let filePath = resolve(root, '.' + pathname);
|
||||
if (filePath !== root && !filePath.startsWith(root + sep)) {
|
||||
res.writeHead(403).end();
|
||||
return;
|
||||
}
|
||||
if (pathname === '/' || pathname.endsWith('/')) {
|
||||
filePath = join(filePath, 'index.html');
|
||||
}
|
||||
const file = await readFile(filePath);
|
||||
res.writeHead(200, {
|
||||
'content-type': mime[extname(filePath)] ?? 'application/octet-stream',
|
||||
});
|
||||
res.end(file);
|
||||
} catch {
|
||||
res.writeHead(404).end('not found');
|
||||
}
|
||||
});
|
||||
server.listen(0, '127.0.0.1');
|
||||
await once(server, 'listening');
|
||||
const origin = `http://127.0.0.1:${server.address().port}`;
|
||||
|
||||
const profile = await mkdtemp(join(tmpdir(), 'chat-approvals-chrome-'));
|
||||
const chrome = spawn(
|
||||
chromePath,
|
||||
[
|
||||
'--headless=new',
|
||||
'--no-first-run',
|
||||
'--no-default-browser-check',
|
||||
'--disable-gpu',
|
||||
'--remote-debugging-port=0',
|
||||
`--user-data-dir=${profile}`,
|
||||
'about:blank',
|
||||
],
|
||||
{ stdio: ['ignore', 'ignore', 'pipe'] },
|
||||
);
|
||||
let stderr = '';
|
||||
chrome.stderr.on('data', (data) => {
|
||||
stderr += data;
|
||||
});
|
||||
|
||||
const waitFor = async (fn, what) => {
|
||||
for (let i = 0; i < 240; i++) {
|
||||
const value = await fn();
|
||||
if (value) return value;
|
||||
await delay(100);
|
||||
}
|
||||
throw new Error(`Timed out waiting for ${what}: ${stderr.slice(-1500)}`);
|
||||
};
|
||||
|
||||
let ws;
|
||||
const evidence = { origin, style, captures: [], checks: [] };
|
||||
try {
|
||||
const endpoint = await waitFor(
|
||||
() => stderr.match(/DevTools listening on (ws:\/\/[^\s]+)/)?.[1],
|
||||
'Chrome DevTools',
|
||||
);
|
||||
ws = new WebSocket(endpoint);
|
||||
await once(ws, 'open');
|
||||
let id = 0;
|
||||
const pending = new Map();
|
||||
ws.addEventListener('message', (event) => {
|
||||
const message = JSON.parse(event.data);
|
||||
if (message.id && pending.has(message.id)) {
|
||||
pending.get(message.id)(message);
|
||||
pending.delete(message.id);
|
||||
}
|
||||
});
|
||||
const send = (method, params = {}, sessionId) =>
|
||||
new Promise((resolveCall) => {
|
||||
const callId = ++id;
|
||||
pending.set(callId, resolveCall);
|
||||
ws.send(
|
||||
JSON.stringify({
|
||||
id: callId,
|
||||
method,
|
||||
params,
|
||||
...(sessionId ? { sessionId } : {}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const created = await send('Target.createTarget', { url: 'about:blank' });
|
||||
if (!created.result) throw new Error('Target creation failed');
|
||||
const target = created.result.targetId;
|
||||
const session = (
|
||||
await send('Target.attachToTarget', { targetId: target, flatten: true })
|
||||
).result.sessionId;
|
||||
await send('Page.enable', {}, session);
|
||||
await send('Runtime.enable', {}, session);
|
||||
await send(
|
||||
'Emulation.setDeviceMetricsOverride',
|
||||
{ width: 320, height: 1500, deviceScaleFactor: 2, mobile: true },
|
||||
session,
|
||||
);
|
||||
await send(
|
||||
'Emulation.setEmulatedMedia',
|
||||
{ features: [{ name: 'prefers-color-scheme', value: 'dark' }] },
|
||||
session,
|
||||
);
|
||||
|
||||
const evaluate = async (expression) => {
|
||||
const response = await send(
|
||||
'Runtime.evaluate',
|
||||
{ expression, returnByValue: true, awaitPromise: true },
|
||||
session,
|
||||
);
|
||||
if (response.error) {
|
||||
throw new Error(`Runtime.evaluate failed: ${JSON.stringify(response)}`);
|
||||
}
|
||||
return response.result?.result?.value;
|
||||
};
|
||||
const nodes = () =>
|
||||
evaluate(`[...document.querySelectorAll('flt-semantics')].map(x => {
|
||||
const r = x.getBoundingClientRect();
|
||||
return {
|
||||
label: x.getAttribute('aria-label'),
|
||||
text: (x.innerText || '').trim(),
|
||||
x: r.x, y: r.y, w: r.width, h: r.height,
|
||||
};
|
||||
})`);
|
||||
const hasText = async (fragment) => {
|
||||
const all = await nodes();
|
||||
return all.some((node) =>
|
||||
`${node.label ?? ''} ${node.text ?? ''}`
|
||||
.toLowerCase()
|
||||
.includes(fragment.toLowerCase()),
|
||||
);
|
||||
};
|
||||
const click = async (name) => {
|
||||
const point = await evaluate(`(() => {
|
||||
const wanted = ${JSON.stringify(name)};
|
||||
const matches = [...document.querySelectorAll('flt-semantics')]
|
||||
.map(x => {
|
||||
const label = x.getAttribute('aria-label') || '';
|
||||
const text = (x.innerText || '').trim();
|
||||
const r = x.getBoundingClientRect();
|
||||
const labelHit = label.includes(wanted) ? 0 : 1;
|
||||
return { x, label, text, labelHit, area: r.width * r.height };
|
||||
})
|
||||
.filter(x => x.labelHit === 0 || x.text.includes(wanted))
|
||||
.sort((a, b) => a.labelHit - b.labelHit || a.area - b.area);
|
||||
const node = matches[0]?.x;
|
||||
if (!node) return null;
|
||||
const r = node.getBoundingClientRect();
|
||||
return { x: r.x + r.width / 2, y: r.y + r.height / 2 };
|
||||
})()`);
|
||||
if (!point) {
|
||||
const shown = (await nodes())
|
||||
.map((entry) => entry.label ?? entry.text)
|
||||
.filter(Boolean);
|
||||
throw new Error(
|
||||
`Could not find ${JSON.stringify(name)}: ${JSON.stringify(shown)}`,
|
||||
);
|
||||
}
|
||||
for (const type of ['mousePressed', 'mouseReleased']) {
|
||||
await send(
|
||||
'Input.dispatchMouseEvent',
|
||||
{ type, x: point.x, y: point.y, button: 'left', clickCount: 1 },
|
||||
session,
|
||||
);
|
||||
}
|
||||
await delay(700);
|
||||
};
|
||||
const capture = async (name) => {
|
||||
const data = (
|
||||
await send('Page.captureScreenshot', { format: 'png' }, session)
|
||||
).result.data;
|
||||
const file = join(out, `${style}-${name}.png`);
|
||||
await writeFile(file, Buffer.from(data, 'base64'));
|
||||
evidence.captures.push(file);
|
||||
return file;
|
||||
};
|
||||
// Flutter web paints static text on the canvas, so semantics exposes the
|
||||
// controls but not the card's prose. OCR reads the real rendered pixels.
|
||||
const screenOCR = async () => {
|
||||
const data = (
|
||||
await send('Page.captureScreenshot', { format: 'png' }, session)
|
||||
).result.data;
|
||||
const file = join(out, 'screen-ocr.png');
|
||||
await writeFile(file, Buffer.from(data, 'base64'));
|
||||
const { stdout } = await promisify(execFile)('tesseract', [file, 'stdout']);
|
||||
return stdout.replace(/\s+/g, ' ');
|
||||
};
|
||||
// OCR sometimes merges words across a line ("A demo question" reads as
|
||||
// "Ademo question"), so comparisons ignore whitespace entirely.
|
||||
const flat = (value) => value.toLowerCase().replace(/\s+/g, '');
|
||||
const waitForOCR = async (text) => {
|
||||
for (let i = 0; i < 120; i++) {
|
||||
const read = await screenOCR();
|
||||
if (flat(read).includes(flat(text))) return read;
|
||||
await delay(200);
|
||||
}
|
||||
throw new Error(`Timed out waiting for OCR ${JSON.stringify(text)}`);
|
||||
};
|
||||
|
||||
await send('Page.navigate', { url: `${origin}/` }, session);
|
||||
await delay(3500);
|
||||
await evaluate("document.querySelector('flt-semantics-placeholder')?.click()");
|
||||
await delay(1200);
|
||||
await waitForOCR('Approve bash').catch(async (error) => {
|
||||
await capture('failure');
|
||||
console.log(JSON.stringify(await nodes(), null, 2));
|
||||
throw error;
|
||||
});
|
||||
// The two cards need not fit one screen; scroll the conversation like an
|
||||
// operator until the question is rendered, then read the whole card view.
|
||||
let pendingRead = await screenOCR();
|
||||
for (let attempt = 0; attempt < 12 && !flat(pendingRead).includes(flat('A demo question')); attempt++) {
|
||||
await send('Input.dispatchMouseEvent', {
|
||||
type: 'mouseWheel', x: 195, y: 420, deltaX: 0, deltaY: 320,
|
||||
}, session);
|
||||
await delay(350);
|
||||
pendingRead = await screenOCR();
|
||||
}
|
||||
if (!flat(pendingRead).includes(flat('A demo question'))) {
|
||||
pendingRead = await waitForOCR('A demo question');
|
||||
}
|
||||
|
||||
// Prose comes from the painted pixels, controls from the semantics tree; a
|
||||
// white-on-tint filled button is reliable in semantics even when OCR skips it.
|
||||
const pendingSemantics = flat(
|
||||
(await nodes()).map((entry) => `${entry.label ?? ''} ${entry.text ?? ''}`).join(' '),
|
||||
);
|
||||
for (const text of [
|
||||
// The web card headline is the recorded action; it has no separate
|
||||
// "Permission request" heading, so none is invented here either.
|
||||
'Approve bash',
|
||||
'Waiting for your response',
|
||||
'RISK REVIEW',
|
||||
'This deletes the build output.',
|
||||
'Allow once',
|
||||
'Always allow',
|
||||
'Reject',
|
||||
'A demo question',
|
||||
'The agent is waiting for your answer.',
|
||||
'Colour',
|
||||
'Red',
|
||||
'Blue',
|
||||
]) {
|
||||
if (!flat(pendingRead).includes(flat(text)) && !pendingSemantics.includes(flat(text))) {
|
||||
throw new Error(`Pending cards lack ${JSON.stringify(text)}`);
|
||||
}
|
||||
}
|
||||
const pendingCapture = await capture('cards');
|
||||
evidence.checks.push({
|
||||
check: 'pending approval and question render with their recorded text',
|
||||
style,
|
||||
capture: pendingCapture,
|
||||
labels: (await nodes()).map((node) => node.label).filter(Boolean),
|
||||
});
|
||||
|
||||
await click('Allow once');
|
||||
const approvedRead = await waitForOCR('Allowed once');
|
||||
for (const text of ['Recorded by the probe fixture']) {
|
||||
if (!approvedRead.toLowerCase().includes(text.toLowerCase())) {
|
||||
throw new Error(`Answered approval lacks ${JSON.stringify(text)}`);
|
||||
}
|
||||
}
|
||||
await capture('approval-answered');
|
||||
evidence.checks.push({
|
||||
check: 'the approval reply was sent and the recorded resolution cleared controls',
|
||||
style,
|
||||
allowOnceStillVisible: await hasText('Allow once'),
|
||||
});
|
||||
|
||||
await click('Red');
|
||||
await click('Send answer');
|
||||
const answeredRead = await waitForOCR('Answer recorded.');
|
||||
if (!answeredRead.toLowerCase().includes('red')) {
|
||||
throw new Error('Answered question lost the recorded Red answer');
|
||||
}
|
||||
await capture('question-answered');
|
||||
evidence.checks.push({
|
||||
check: 'the question answer was sent and the card is read-only',
|
||||
style,
|
||||
sendAnswerStillVisible: await hasText('Send answer'),
|
||||
});
|
||||
|
||||
if (evidence.checks.at(-1).sendAnswerStillVisible) {
|
||||
throw new Error('Send answer stayed visible after the question resolved');
|
||||
}
|
||||
if (evidence.checks.at(-2).allowOnceStillVisible) {
|
||||
throw new Error('Allow once stayed visible after the approval resolved');
|
||||
}
|
||||
|
||||
const report = JSON.stringify(evidence, null, 2);
|
||||
await writeFile(join(out, `${style}-evidence.json`), report);
|
||||
console.log(report);
|
||||
} finally {
|
||||
ws?.close();
|
||||
chrome.kill();
|
||||
server.close();
|
||||
for (let attempt = 0; attempt < 10; attempt++) {
|
||||
try {
|
||||
await rm(profile, { recursive: true, force: true });
|
||||
break;
|
||||
} catch {
|
||||
await delay(200);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user