Merge main into flutter/chat-notices: keep chat info beside dismissible notices

This commit is contained in:
2026-10-22 11:14:01 +01:00
31 changed files with 2178 additions and 34 deletions
@@ -4,6 +4,8 @@ import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../domain/chat_attachment_draft.dart';
import '../domain/chat_attachment_picker.dart';
import '../ui/sessions/chat_adaptive.dart';
import 'chat_composer_controller.dart';
@@ -14,6 +16,9 @@ const String chatComposerPlaceholder = 'Message the agent… or / for commands';
const String chatSendLabel = 'Send';
const String chatStopLabel = 'Stop';
/// The attach control's accessible name, verbatim from the web composer.
const String chatAttachLabel = 'Attach file';
/// Shown while the reply says this prompt waits behind the running turn.
const String chatQueuedNotice =
'Queued — it will send when the current turn finishes.';
@@ -24,13 +29,15 @@ const String chatQueuedNotice =
/// The field owns only its [TextEditingController] and focus; the durable draft
/// text lives in the composer controller, so a live transcript rebuild never
/// replaces the operator's caret. Enter inserts a newline and Ctrl/Cmd+Enter
/// sends the plain message. Attachments and the slash palette are not part of
/// this slice.
/// sends the plain message. Picked files are memory-only chips: their names are
/// shown with the host's own remove action and the bounded draft owns every
/// refusal. Sending does not yet carry attachments, and paste is not wired.
class ChatComposerBar extends StatefulWidget {
const ChatComposerBar({
super.key,
required this.composer,
required this.running,
this.picker,
});
final ChatComposerController composer;
@@ -38,6 +45,9 @@ class ChatComposerBar extends StatefulWidget {
/// The thread controller's running bit; it alone decides Send versus Stop.
final bool running;
/// The host picker seam; production uses [hostChatAttachmentPicker].
final ChatAttachmentPicker? picker;
@override
State<ChatComposerBar> createState() => _ChatComposerBarState();
}
@@ -47,6 +57,10 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
text: widget.composer.draft,
);
final FocusNode _focus = FocusNode(debugLabel: 'chat-composer');
final ChatAttachmentDraft _attachments = ChatAttachmentDraft();
String? _attachmentError;
ChatAttachmentPicker get _picker => widget.picker ?? hostChatAttachmentPicker;
@override
void initState() {
@@ -100,6 +114,37 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
_focus.requestFocus();
}
/// Adds the operator's explicit selection through the host seam. A dismissed
/// picker changes nothing; a bounded draft refusal is shown in its own words
/// while every attachment already in the draft stays.
Future<void> _pickAttachments() async {
if (widget.composer.sending || !_picker.isSupported) return;
List<ChatPickedFile>? files;
try {
files = await _picker.pick();
} catch (error) {
if (!mounted) return;
setState(() => _attachmentError = '$error');
return;
}
if (!mounted || files == null) return;
final picked = files;
setState(() {
_attachmentError = null;
for (final file in picked) {
final refusal = _attachments.add(file.attachment);
if (refusal != null) _attachmentError = refusal.message;
}
});
}
void _removeAttachment(ChatAttachment attachment) {
setState(() {
_attachments.remove(attachment);
_attachmentError = null;
});
}
@override
void dispose() {
widget.composer.removeListener(_syncDraft);
@@ -126,6 +171,15 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (!_attachments.isEmpty) _attachmentStrip(context, cupertino),
if (_attachmentError != null)
_notice(
context,
cupertino,
key: const Key('chat-composer-attachment-error'),
text: _attachmentError!,
failed: true,
),
if (composer.queued)
_notice(
context,
@@ -144,6 +198,8 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
_attach(context, cupertino),
const SizedBox(width: 8),
Expanded(
child: Focus(
canRequestFocus: false,
@@ -164,6 +220,118 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
);
}
/// The attach control: a host button that opens the picker, disabled when the
/// host has no picker or one prompt is already awaiting its reply.
Widget _attach(BuildContext context, bool cupertino) {
final enabled = _picker.isSupported && !widget.composer.sending;
final onPressed = enabled ? () => unawaited(_pickAttachments()) : null;
if (cupertino) {
return Semantics(
label: chatAttachLabel,
button: true,
enabled: enabled,
child: ExcludeSemantics(
child: CupertinoButton(
key: const Key('chat-composer-attach'),
padding: EdgeInsets.zero,
onPressed: onPressed,
child: const Icon(CupertinoIcons.paperclip),
),
),
);
}
return IconButton(
key: const Key('chat-composer-attach'),
tooltip: chatAttachLabel,
onPressed: onPressed,
icon: const Icon(Icons.attach_file),
);
}
/// The files attached to the next message. Each chip carries only the
/// operator's recorded name and a native remove action.
Widget _attachmentStrip(BuildContext context, bool cupertino) {
final attachments = _attachments.attachments;
return Padding(
key: const Key('chat-composer-attachments'),
padding: const EdgeInsetsDirectional.only(bottom: 8),
child: Wrap(
spacing: 8,
runSpacing: 4,
children: [
for (var index = 0; index < attachments.length; index += 1)
if (cupertino)
_cupertinoChip(context, attachments[index], index)
else
_materialChip(attachments[index], index),
],
),
);
}
Widget _materialChip(ChatAttachment attachment, int index) => Chip(
key: ValueKey<String>('chat-composer-attachment-$index'),
label: Text(attachment.name),
onDeleted: () => _removeAttachment(attachment),
deleteButtonTooltipMessage: 'Remove ${attachment.name}',
);
/// Cupertino has no chip control, so the host's capsule fill and its own
/// button carry the same name and remove action.
Widget _cupertinoChip(
BuildContext context,
ChatAttachment attachment,
int index,
) {
return Semantics(
container: true,
explicitChildNodes: true,
child: DefaultTextStyle.merge(
style: CupertinoTheme.of(context).textTheme.textStyle,
child: DecoratedBox(
key: ValueKey<String>('chat-composer-attachment-$index'),
decoration: ShapeDecoration(
shape: const StadiumBorder(),
color: CupertinoColors.secondarySystemFill.resolveFrom(context),
),
child: Padding(
padding: const EdgeInsetsDirectional.fromSTEB(12, 4, 4, 4),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Flexible(
child: Text(attachment.name, overflow: TextOverflow.ellipsis),
),
const SizedBox(width: 4),
Semantics(
container: true,
button: true,
label: 'Remove ${attachment.name}',
onTap: () => _removeAttachment(attachment),
child: ExcludeSemantics(
child: CupertinoButton(
key: ValueKey<String>(
'chat-composer-attachment-remove-$index',
),
padding: EdgeInsets.zero,
onPressed: () => _removeAttachment(attachment),
child: Icon(
CupertinoIcons.xmark_circle_fill,
color: CupertinoColors.secondaryLabel.resolveFrom(
context,
),
),
),
),
),
],
),
),
),
),
);
}
Widget _field(bool cupertino) {
final composer = widget.composer;
void changed(String value) => unawaited(composer.setDraft(value));
@@ -191,6 +359,7 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
onChanged: changed,
decoration: const InputDecoration(
hintText: chatComposerPlaceholder,
hintMaxLines: 1,
border: OutlineInputBorder(),
),
);
@@ -4,6 +4,7 @@ import 'package:flutter/foundation.dart';
import '../../../core/api_gateway.dart';
import '../data/chat_repository.dart';
import '../domain/chat_sessions.dart';
import '../domain/chat_transcript.dart';
import 'chat_thread_cards.dart';
@@ -42,6 +43,7 @@ class ChatThreadController extends ChangeNotifier {
bool _hasMore = false;
String _cursor = '';
String _nativeTurnId = '';
JsonMap? _usage;
String? _error;
bool _subscribed = false;
@@ -59,6 +61,11 @@ class ChatThreadController extends ChangeNotifier {
/// The server's opaque older-page cursor. Never interpreted, only passed back.
String get cursor => _cursor;
/// The latest recorded usage snapshot, or null before the harness reports.
/// Unknown fields stay null, so a viewer can distinguish them from zero.
JsonMap? get usage => _usage;
String? get error => _error;
bool get subscribed => _subscribed;
String? get subscriptionError => _subscriptionError;
@@ -222,6 +229,16 @@ class ChatThreadController extends ChangeNotifier {
unawaited(resync());
return;
}
if (body['kind'] == 'usage') {
// Usage replaces the last snapshot and never adds a message, runs a turn
// or admits a queued prompt. An unusable snapshot keeps the previous
// recorded values instead of replacing them with fabricated zeros.
final usage = chatUsageSnapshot(body['usage']);
if (usage == null || !_reportedUsage(usage)) return;
_usage = usage;
_notify();
return;
}
if (body['kind'] == 'form') {
final form = body['form'];
if (form is! Map) return;
@@ -240,6 +257,23 @@ class ChatThreadController extends ChangeNotifier {
_notify();
}
/// Whether a normalized snapshot names a scope or carries a recorded fact.
/// A window of zero reports no usable limit, and a rate basis alone reports
/// no number at all, so neither counts as a fact on its own.
bool _reportedUsage(JsonMap usage) {
if ('${usage['scope'] ?? ''}'.isNotEmpty) return true;
if (usage['context_window'] is int &&
(usage['context_window'] as int) > 0) {
return true;
}
return const [
'total_tokens',
'context_tokens',
'cost_usd',
'output_tokens_per_second',
].any((key) => usage[key] != null);
}
/// The pushed envelope body, or null for another message type. The server
/// wraps `chat_event` in the typed envelope; domain code never sees the
/// transport fields.
@@ -121,6 +121,34 @@ class _ChatThreadViewState extends State<ChatThreadView> {
});
}
/// Reports the harness's recorded usage. The standard sheet is dismissed the
/// platform's way (drag/barrier/Back, or a popup tap) and closes explicitly.
Future<void> _openInfo() async {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
if (cupertino) {
await showCupertinoModalPopup<void>(
context: context,
builder: (sheetContext) => Align(
alignment: Alignment.bottomCenter,
child: SafeArea(
child: CupertinoPopupSurface(
child: _ChatInfoSheet(controller: _controller),
),
),
),
);
return;
}
await showModalBottomSheet<void>(
context: context,
showDragHandle: true,
isScrollControlled: true,
useSafeArea: true,
builder: (sheetContext) => _ChatInfoSheet(controller: _controller),
);
}
/// Local turns whose authoritative copy is not in the held transcript yet.
/// A live user frame or a history page that carries the same operation,
/// native id or message id hides the local copy instead of drawing it twice.
@@ -272,6 +300,13 @@ class _ChatThreadViewState extends State<ChatThreadView> {
).textTheme.navTitleTextStyle
: Theme.of(context).textTheme.titleLarge,
),
ChatBarAction(
key: const Key('chat-info'),
label: 'Chat information',
onPressed: _openInfo,
materialIcon: Icons.info_outline,
cupertinoIcon: CupertinoIcons.info,
),
],
),
),
@@ -551,6 +586,227 @@ class _ChatNoticeLine extends StatelessWidget {
}
}
/// One reported usage metric: its web label, whether the harness reported it,
/// and the displayed value. Unavailable is a word, never a zero.
typedef _ChatInfoMetric = ({
String key,
String label,
bool available,
String value,
});
const _chatInfoUnavailable = 'Unavailable';
/// The four chat usage facts in the web order and wording.
///
/// Values come only from [ChatThreadController.usage]; a missing count, amount
/// or window is "Unavailable". A reported zero stays a reported zero, and the
/// context row keeps the web's partial forms when only one side was reported.
List<_ChatInfoMetric> _chatInfoMetrics(JsonMap? usage) {
final scope = '${usage?['scope'] ?? ''}';
final basis = '${usage?['rate_basis'] ?? ''}';
final rate = _chatInfoAmount(usage?['output_tokens_per_second']);
final total = _chatInfoCount(usage?['total_tokens']);
final used = _chatInfoCount(usage?['context_tokens']);
final reportedWindow = _chatInfoCount(usage?['context_window']);
// The web treats a zero context window as no reported limit.
final limit = reportedWindow != null && reportedWindow > 0
? reportedWindow
: null;
final cost = _chatInfoAmount(usage?['cost_usd']);
final context = used != null && limit != null
? '${_chatInfoInteger(used)} / ${_chatInfoInteger(limit)}'
: limit != null
? '${_chatInfoInteger(limit)} limit'
: used != null
? '${_chatInfoInteger(used)} used'
: _chatInfoUnavailable;
return [
(
key: 'rate',
label: basis == 'turn' ? 'Avg output rate' : 'Output rate',
available: rate != null,
value: rate == null ? _chatInfoUnavailable : _chatInfoRate(rate),
),
(
key: 'tokens',
label: scope == 'turn' ? 'Turn tokens' : 'Total tokens',
available: total != null,
value: total == null ? _chatInfoUnavailable : _chatInfoInteger(total),
),
(
key: 'context',
label: 'Context',
available: used != null || limit != null,
value: context,
),
(
key: 'cost',
label: 'Reported cost',
available: cost != null,
value: cost == null ? _chatInfoUnavailable : _chatInfoDollars(cost),
),
];
}
int? _chatInfoCount(Object? value) => value is int && value >= 0 ? value : null;
num? _chatInfoAmount(Object? value) =>
value is num && value.isFinite && value >= 0 ? value : null;
String _chatInfoInteger(int value) {
final digits = value.toString();
final grouped = StringBuffer();
for (var index = 0; index < digits.length; index++) {
if (index > 0 && (digits.length - index) % 3 == 0) grouped.write(',');
grouped.write(digits[index]);
}
return grouped.toString();
}
String _chatInfoRate(num value) {
final atMostOneDecimal = value.toStringAsFixed(1);
final number = atMostOneDecimal.endsWith('.0')
? atMostOneDecimal.substring(0, atMostOneDecimal.length - 2)
: atMostOneDecimal;
return value > 0 && value < 0.1 ? '<0.1 tok/s' : '$number tok/s';
}
String _chatInfoDollars(num value) {
if (value > 0 && value < 0.000001) return '<\$0.000001';
final fixed = value.toStringAsFixed(6);
final point = fixed.indexOf('.');
var decimals = fixed.substring(point + 1);
while (decimals.length > 4 && decimals.endsWith('0')) {
decimals = decimals.substring(0, decimals.length - 1);
}
final whole = int.parse(fixed.substring(0, point));
return '\$${_chatInfoInteger(whole)}.$decimals';
}
/// The "Chat information" panel. It rebuilds from the controller, so metrics
/// that arrive while it is open replace the displayed snapshot.
class _ChatInfoSheet extends StatelessWidget {
const _ChatInfoSheet({required this.controller});
final ChatThreadController controller;
@override
Widget build(BuildContext context) {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
return AnimatedBuilder(
animation: controller,
builder: (context, _) {
final titleStyle = cupertino
? CupertinoTheme.of(context).textTheme.navTitleTextStyle
: Theme.of(context).textTheme.titleLarge;
final content = Column(
key: const Key('chat-info-sheet'),
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsetsDirectional.fromSTEB(24, 8, 16, 4),
child: Row(
children: [
Expanded(
child: Semantics(
header: true,
child: Text('Chat information', style: titleStyle),
),
),
if (cupertino)
CupertinoButton(
key: const Key('chat-info-close'),
padding: EdgeInsets.zero,
onPressed: () => Navigator.of(context).pop(),
child: const Text('Close'),
)
else
TextButton(
key: const Key('chat-info-close'),
onPressed: () => Navigator.of(context).pop(),
child: const Text('Close'),
),
],
),
),
for (final metric in _chatInfoMetrics(controller.usage))
_ChatInfoRow(metric: metric, cupertino: cupertino),
Padding(
padding: const EdgeInsetsDirectional.fromSTEB(24, 8, 24, 16),
child: Text(
'Last reported by the harness. '
'Unavailable values are not estimated.',
style:
(cupertino
? CupertinoTheme.of(context).textTheme.textStyle
: Theme.of(context).textTheme.bodySmall)
?.copyWith(
color: cupertino
? CupertinoColors.secondaryLabel.resolveFrom(
context,
)
: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
),
],
);
if (!cupertino) return SingleChildScrollView(child: content);
// A tall text scale must scroll inside the popup rather than push its
// heading off-screen. The height follows the viewport, not a fixed size.
return ConstrainedBox(
constraints: BoxConstraints(
maxHeight: MediaQuery.sizeOf(context).height * 0.8,
),
child: SingleChildScrollView(child: content),
);
},
);
}
}
class _ChatInfoRow extends StatelessWidget {
const _ChatInfoRow({required this.metric, required this.cupertino});
final _ChatInfoMetric metric;
final bool cupertino;
@override
Widget build(BuildContext context) {
final secondary = cupertino
? CupertinoColors.secondaryLabel.resolveFrom(context)
: Theme.of(context).colorScheme.onSurfaceVariant;
final labelStyle =
(cupertino
? CupertinoTheme.of(context).textTheme.textStyle
: Theme.of(context).textTheme.bodySmall)
?.copyWith(color: secondary);
final valueStyle = cupertino
? CupertinoTheme.of(context).textTheme.textStyle
: Theme.of(context).textTheme.bodyLarge;
return Padding(
key: Key('chat-info-metric-${metric.key}'),
padding: const EdgeInsetsDirectional.fromSTEB(24, 6, 24, 6),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(metric.label, style: labelStyle),
Text(
metric.value,
key: Key('chat-info-value-${metric.key}'),
style: metric.available
? valueStyle
: valueStyle?.copyWith(color: secondary),
),
],
),
);
}
}
/// One recorded activity line for a turn.
///
/// The line is a summary of the recorded sequence. Its wording and state come