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

This commit is contained in:
2026-10-22 02:01:41 +01:00
parent 38488b7ec7
commit 221a2582dc
24 changed files with 3756 additions and 8 deletions
@@ -0,0 +1,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;
}