Remove Cupertino chat conversation branches

Keep the Material-only conversation implementation while preserving public Cupertino parameters for callers. Narrow affected tests to Material hosts so the dead platform paths are no longer exercised.
This commit is contained in:
2026-11-11 13:11:05 +00:00
parent 8f52c7ec55
commit 96de9f5bea
32 changed files with 812 additions and 2005 deletions
@@ -1,4 +1,3 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'chat_bar_tint.dart'; import 'chat_bar_tint.dart';
@@ -25,12 +24,13 @@ ButtonStyle chatBarTextButtonStyle(
/// Horizontal padding inside the bar's text buttons (model, mode). /// Horizontal padding inside the bar's text buttons (model, mode).
const EdgeInsets chatBarButtonPadding = EdgeInsets.symmetric(horizontal: 12); const EdgeInsets chatBarButtonPadding = EdgeInsets.symmetric(horizontal: 12);
/// Cupertino: [content] (a [CupertinoButton]'s child) in the label colour /// Puts [content] (a button's child) in the bar's foreground colour: the
/// instead of the button's tint. /// chat's tint if it has one, else `onSurfaceVariant`. Kept for existing
/// callers; the Material path colours buttons with [chatBarTextButtonStyle].
Widget chatBarCupertinoContent(BuildContext context, Widget content) { Widget chatBarCupertinoContent(BuildContext context, Widget content) {
final color = final color =
ChatBarTintScope.foregroundOf(context) ?? ChatBarTintScope.foregroundOf(context) ??
CupertinoColors.label.resolveFrom(context); Theme.of(context).colorScheme.onSurfaceVariant;
return IconTheme.merge( return IconTheme.merge(
data: IconThemeData(color: color), data: IconThemeData(color: color),
child: DefaultTextStyle.merge( child: DefaultTextStyle.merge(
@@ -1,4 +1,3 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
/// Host-native typography and colour for the approval and question cards. /// Host-native typography and colour for the approval and question cards.
@@ -6,24 +5,21 @@ import 'package:flutter/material.dart';
/// The cards share one hierarchy: the card title uses the host's title style, /// 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 /// 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 /// style. Keeping the styles here stops each card file from inventing its own
/// size and colour; everything still comes from the active Material/Cupertino /// size and colour; everything still comes from the active Material theme, so
/// theme, so light, dark and text scaling follow the host. /// light, dark and text scaling follow the host.
TextStyle? chatCardTitleStyle(BuildContext context, bool cupertino) => cupertino ///
? CupertinoTheme.of(context).textTheme.navTitleTextStyle /// The `cupertino` parameters are kept for existing callers; the app is
: Theme.of(context).textTheme.titleMedium; /// Material-only, so every helper returns its Material value.
TextStyle? chatCardTitleStyle(BuildContext context, bool cupertino) =>
Theme.of(context).textTheme.titleMedium;
TextStyle? chatCardBodyStyle(BuildContext context, bool cupertino) => cupertino TextStyle? chatCardBodyStyle(BuildContext context, bool cupertino) =>
? CupertinoTheme.of(context).textTheme.textStyle Theme.of(context).textTheme.bodyMedium;
: Theme.of(context).textTheme.bodyMedium;
/// A field or recorded-answer label. Under Cupertino the system tab-label style /// A field or recorded-answer label: `titleSmall`, so labels sit visibly
/// (the same subordinate style the rest of the app uses for secondary copy) /// below the card title without reading as extra headings.
/// keeps labels from reading as extra headings; Material keeps `titleSmall`. TextStyle? chatCardLabelStyle(BuildContext context, bool cupertino) =>
TextStyle? chatCardLabelStyle(BuildContext context, bool cupertino) => cupertino Theme.of(context).textTheme.titleSmall;
? 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. /// Body text that supports a control, such as a field description.
TextStyle? chatCardSecondaryStyle(BuildContext context, bool cupertino) => TextStyle? chatCardSecondaryStyle(BuildContext context, bool cupertino) =>
@@ -31,25 +27,19 @@ TextStyle? chatCardSecondaryStyle(BuildContext context, bool cupertino) =>
color: chatCardSecondaryColor(context, cupertino), color: chatCardSecondaryColor(context, cupertino),
); );
Color chatCardSecondaryColor(BuildContext context, bool cupertino) => cupertino Color chatCardSecondaryColor(BuildContext context, bool cupertino) =>
? CupertinoColors.secondaryLabel.resolveFrom(context) Theme.of(context).colorScheme.onSurfaceVariant;
: Theme.of(context).colorScheme.onSurfaceVariant;
Color chatCardErrorColor(BuildContext context, bool cupertino) => cupertino Color chatCardErrorColor(BuildContext context, bool cupertino) =>
? CupertinoColors.systemRed.resolveFrom(context) Theme.of(context).colorScheme.error;
: Theme.of(context).colorScheme.error;
/// The amber risk hue: the host's warning role, never a bespoke palette. /// The amber risk hue: the host's warning role, never a bespoke palette.
Color chatCardWarningColor(BuildContext context, bool cupertino) => cupertino Color chatCardWarningColor(BuildContext context, bool cupertino) =>
? CupertinoColors.systemOrange.resolveFrom(context) Theme.of(context).colorScheme.tertiary;
: Theme.of(context).colorScheme.tertiary;
/// A quiet inset surface for resource blocks and risk panels. /// A quiet inset surface for resource blocks and risk panels.
Color chatCardFillColor(BuildContext context, bool cupertino) => cupertino Color chatCardFillColor(BuildContext context, bool cupertino) =>
? CupertinoColors.secondarySystemFill.resolveFrom(context) Theme.of(context).colorScheme.surfaceContainerHighest;
: Theme.of(context).colorScheme.surfaceContainerHighest;
Color chatCardWarningFillColor(BuildContext context, bool cupertino) => Color chatCardWarningFillColor(BuildContext context, bool cupertino) =>
cupertino Theme.of(context).colorScheme.tertiaryContainer;
? CupertinoColors.secondarySystemFill.resolveFrom(context)
: Theme.of(context).colorScheme.tertiaryContainer;
@@ -1,15 +1,12 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../domain/chat_commands.dart'; import '../domain/chat_commands.dart';
import '../ui/sessions/chat_adaptive.dart';
/// The command palette above the composer: the recorded commands matching the /// The command palette above the composer: the recorded commands matching the
/// slash word, each with its own `/name` and summary. /// slash word, each with its own `/name` and summary.
/// ///
/// Rows are standard host controls (Material's selected `ListTile`, Cupertino's /// Rows are standard Material `ListTile`s, so typography, colours and text
/// own button on a popup surface), so typography, colours and text scaling stay /// scaling stay the theme's. The list is content-sized and never imposes a fixed height;
/// the platform's. The list is content-sized and never imposes a fixed height;
/// a viewport-bound scroll keeps a tall text scale reachable. /// a viewport-bound scroll keeps a tall text scale reachable.
class ChatCommandPalette extends StatelessWidget { class ChatCommandPalette extends StatelessWidget {
const ChatCommandPalette({ const ChatCommandPalette({
@@ -29,9 +26,6 @@ class ChatCommandPalette extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
if (commands.isEmpty) return const SizedBox.shrink(); if (commands.isEmpty) return const SizedBox.shrink();
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final list = cupertino ? _cupertinoRows(context) : _materialRows(context);
return ConstrainedBox( return ConstrainedBox(
constraints: BoxConstraints( constraints: BoxConstraints(
maxHeight: MediaQuery.sizeOf(context).height * 0.4, maxHeight: MediaQuery.sizeOf(context).height * 0.4,
@@ -40,7 +34,7 @@ class ChatCommandPalette extends StatelessWidget {
child: Semantics( child: Semantics(
container: true, container: true,
label: 'Command suggestions', label: 'Command suggestions',
child: list, child: _materialRows(context),
), ),
), ),
); );
@@ -66,62 +60,4 @@ class ChatCommandPalette extends StatelessWidget {
), ),
); );
} }
/// Cupertino has no list tile that keeps a wrapping summary, so each row is
/// the host's own button, with the name and summary at the native text style
/// and the selected row on the host's semantic fill.
Widget _cupertinoRows(BuildContext context) {
final secondary = CupertinoColors.secondaryLabel.resolveFrom(context);
final selectedFill = CupertinoColors.systemFill.resolveFrom(context);
final textStyle = CupertinoTheme.of(context).textTheme.textStyle;
return CupertinoPopupSurface(
key: const Key('chat-command-palette'),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
for (var index = 0; index < commands.length; index += 1)
Semantics(
selected: index == selectedIndex,
child: SizedBox(
width: double.infinity,
child: CupertinoButton(
key: ValueKey<String>('chat-command-${commands[index].name}'),
padding: EdgeInsets.zero,
onPressed: () => onSelected(commands[index]),
child: SizedBox(
width: double.infinity,
child: DecoratedBox(
decoration: BoxDecoration(
color: index == selectedIndex ? selectedFill : null,
),
child: Padding(
padding: const EdgeInsetsDirectional.fromSTEB(
16,
10,
16,
10,
),
child: DefaultTextStyle.merge(
style: textStyle,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('/${commands[index].name}'),
Text(
commands[index].summary,
style: TextStyle(color: secondary),
),
],
),
),
),
),
),
),
),
),
],
),
);
}
} }
@@ -1,7 +1,5 @@
import 'dart:async'; import 'dart:async';
import 'dart:math' as math;
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
@@ -19,7 +17,6 @@ import '../domain/chat_attachment_picker.dart';
import '../domain/chat_attachment_wire.dart'; import '../domain/chat_attachment_wire.dart';
import '../domain/chat_clipboard_paste.dart'; import '../domain/chat_clipboard_paste.dart';
import '../domain/chat_commands.dart'; import '../domain/chat_commands.dart';
import '../ui/sessions/chat_adaptive.dart';
import 'chat_command_actions.dart'; import 'chat_command_actions.dart';
import 'chat_command_palette.dart'; import 'chat_command_palette.dart';
import 'chat_composer_controller.dart'; import 'chat_composer_controller.dart';
@@ -821,8 +818,6 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
return ListenableBuilder( return ListenableBuilder(
listenable: widget.composer, listenable: widget.composer,
builder: (context, _) { builder: (context, _) {
@@ -837,12 +832,11 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
// command palette, a separate menu, floats above it. // command palette, a separate menu, floats above it.
final extras = <Widget>[ final extras = <Widget>[
if (chatDraftIsShell(composer.draft)) if (chatDraftIsShell(composer.draft))
ChatShellModeIndicator(cupertino: cupertino), ChatShellModeIndicator(cupertino: false),
if (!_attachments.isEmpty) _attachmentStrip(context, cupertino), if (!_attachments.isEmpty) _attachmentStrip(context),
if (_uploading) if (_uploading)
_notice( _notice(
context, context,
cupertino,
key: const Key('chat-composer-uploading'), key: const Key('chat-composer-uploading'),
text: _attachments.attachments.length == 1 text: _attachments.attachments.length == 1
? 'Uploading 1 file…' ? 'Uploading 1 file…'
@@ -851,23 +845,20 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
if (_attachmentError != null) if (_attachmentError != null)
_notice( _notice(
context, context,
cupertino,
key: const Key('chat-composer-attachment-error'), key: const Key('chat-composer-attachment-error'),
text: _attachmentError!, text: _attachmentError!,
failed: true, failed: true,
), ),
if (_commandNotice != null) _commandReport(context, cupertino), if (_commandNotice != null) _commandReport(context),
if (composer.queued) if (composer.queued)
_notice( _notice(
context, context,
cupertino,
key: const Key('chat-composer-queued'), key: const Key('chat-composer-queued'),
text: chatQueuedNotice, text: chatQueuedNotice,
), ),
if (error != null) if (error != null)
_notice( _notice(
context, context,
cupertino,
key: const Key('chat-composer-error'), key: const Key('chat-composer-error'),
text: error, text: error,
failed: true, failed: true,
@@ -911,7 +902,6 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
key: const ValueKey('chat-composer-entrance'), key: const ValueKey('chat-composer-entrance'),
child: _pill( child: _pill(
context, context,
cupertino,
Column( Column(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch, crossAxisAlignment: CrossAxisAlignment.stretch,
@@ -935,13 +925,13 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
builder: (context, constraints) => Row( builder: (context, constraints) => Row(
crossAxisAlignment: CrossAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.end,
children: [ children: [
_attach(context, cupertino), _attach(context),
Expanded( Expanded(
child: Focus( child: Focus(
canRequestFocus: false, canRequestFocus: false,
includeSemantics: false, includeSemantics: false,
onKeyEvent: _onKey, onKeyEvent: _onKey,
child: _field(cupertino), child: _field(),
), ),
), ),
// Shown only while tasks run (or their list // Shown only while tasks run (or their list
@@ -955,10 +945,10 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
child: widget.backgroundTasks!, child: widget.backgroundTasks!,
), ),
if (widget.running) ...[ if (widget.running) ...[
_primary(context, cupertino, stop: true), _primary(context, stop: true),
const SizedBox(width: 4), const SizedBox(width: 4),
], ],
_primary(context, cupertino), _primary(context),
], ],
), ),
), ),
@@ -984,45 +974,28 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
/// the transcript, so the composer reads as a single input rather than a /// the transcript, so the composer reads as a single input rather than a
/// row of separate controls, and the conversation shows through it. While /// row of separate controls, and the conversation shows through it. While
/// the field has focus a ring in the chat's colour runs along its edge. /// the field has focus a ring in the chat's colour runs along its edge.
Widget _pill(BuildContext context, bool cupertino, Widget child) => Widget _pill(BuildContext context, Widget child) => ComposerFocusRing(
ComposerFocusRing( focus: _focus,
focus: _focus, accent: chatFocusRingColor(context, widget.chatColor),
accent: chatFocusRingColor(context, widget.chatColor), shape: _pillShape,
shape: _pillShape, child: GlassPill(
child: GlassPill( key: const Key('chat-composer-pill'),
key: const Key('chat-composer-pill'), cupertino: false,
cupertino: cupertino, shape: _pillShape,
shape: _pillShape, // The end controls keep the same gap from the pill's sides as from
// The end controls keep the same gap from the pill's sides as from // its bottom (and its top while the field is one line).
// its bottom (and its top while the field is one line). child: Padding(
child: Padding( padding: const EdgeInsets.all(GlassBarMetrics.fieldEdgeGap),
padding: const EdgeInsets.all(GlassBarMetrics.fieldEdgeGap), child: child,
child: child, ),
), ),
), );
);
/// The attach control: a host button that opens the picker, disabled when the /// 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. /// host has no picker or one prompt is already awaiting its reply.
Widget _attach(BuildContext context, bool cupertino) { Widget _attach(BuildContext context) {
final enabled = _picker.isSupported && !widget.composer.sending; final enabled = _picker.isSupported && !widget.composer.sending;
final onPressed = enabled ? () => unawaited(_pickAttachments()) : null; 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,
minimumSize: GlassBarMetrics.cupertinoMinimumSize(),
onPressed: onPressed,
child: const Icon(CupertinoIcons.add),
),
),
);
}
return IconButton( return IconButton(
key: const Key('chat-composer-attach'), key: const Key('chat-composer-attach'),
tooltip: chatAttachLabel, tooltip: chatAttachLabel,
@@ -1033,7 +1006,7 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
/// The files attached to the next message. Each chip carries only the /// The files attached to the next message. Each chip carries only the
/// operator's recorded name and a native remove action. /// operator's recorded name and a native remove action.
Widget _attachmentStrip(BuildContext context, bool cupertino) { Widget _attachmentStrip(BuildContext context) {
final attachments = _attachments.attachments; final attachments = _attachments.attachments;
return Padding( return Padding(
key: const Key('chat-composer-attachments'), key: const Key('chat-composer-attachments'),
@@ -1045,8 +1018,6 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
for (var index = 0; index < attachments.length; index += 1) for (var index = 0; index < attachments.length; index += 1)
if (_imageBytes(index) case final bytes?) if (_imageBytes(index) case final bytes?)
_imageThumbnail(context, attachments[index], bytes, index) _imageThumbnail(context, attachments[index], bytes, index)
else if (cupertino)
_cupertinoChip(context, attachments[index], index)
else else
_materialChip(attachments[index], index), _materialChip(attachments[index], index),
], ],
@@ -1071,8 +1042,6 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
Uint8List bytes, Uint8List bytes,
int index, int index,
) { ) {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
return Semantics( return Semantics(
key: ValueKey<String>('chat-composer-attachment-$index'), key: ValueKey<String>('chat-composer-attachment-$index'),
container: true, container: true,
@@ -1094,13 +1063,8 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
bytes, bytes,
key: ValueKey<String>('chat-composer-thumbnail-$index'), key: ValueKey<String>('chat-composer-thumbnail-$index'),
fit: BoxFit.cover, fit: BoxFit.cover,
errorBuilder: (_, _, _) => Center( errorBuilder: (_, _, _) =>
child: Icon( const Center(child: Icon(Icons.image_outlined)),
cupertino
? CupertinoIcons.photo
: Icons.image_outlined,
),
),
), ),
), ),
), ),
@@ -1123,10 +1087,10 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
shape: BoxShape.circle, shape: BoxShape.circle,
), ),
padding: const EdgeInsets.all(2), padding: const EdgeInsets.all(2),
child: Icon( child: const Icon(
cupertino ? CupertinoIcons.xmark : Icons.close, Icons.close,
size: 14, size: 14,
color: const Color(0xFFFFFFFF), color: Color(0xFFFFFFFF),
), ),
), ),
), ),
@@ -1159,80 +1123,6 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
deleteButtonTooltipMessage: 'Remove ${attachment.name}', 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: () => _removeAttachmentAt(index),
child: ExcludeSemantics(
child: CupertinoButton(
key: ValueKey<String>(
'chat-composer-attachment-remove-$index',
),
padding: EdgeInsets.zero,
onPressed: () => _removeAttachmentAt(index),
child: Icon(
CupertinoIcons.xmark_circle_fill,
color: CupertinoColors.secondaryLabel.resolveFrom(
context,
),
),
),
),
),
],
),
),
),
),
);
}
/// The lines the composer placeholder needs at [width] (the field's
/// default 7px side padding excluded), capped at 3.
int _placeholderLines(BuildContext context, double width) {
if (!width.isFinite) return 1;
final painter = TextPainter(
text: TextSpan(
text: widget.placeholder,
style: CupertinoTheme.of(context).textTheme.textStyle,
),
textDirection: Directionality.of(context),
textScaler: MediaQuery.textScalerOf(context),
maxLines: 3,
)..layout(maxWidth: math.max(0, width - 14));
final lines = painter.computeLineMetrics().length;
painter.dispose();
return lines.clamp(1, 3);
}
/// The most lines the field grows to before it scrolls: up to /// The most lines the field grows to before it scrolls: up to
/// [_composerMaxLines], but never more than about 40% of the visible /// [_composerMaxLines], but never more than about 40% of the visible
/// height (the keyboard excluded), so the conversation stays in view. /// height (the keyboard excluded), so the conversation stays in view.
@@ -1250,49 +1140,8 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
return fit.clamp(3, _composerMaxLines); return fit.clamp(3, _composerMaxLines);
} }
Widget _field(bool cupertino) { Widget _field() {
final maxLines = _maxLines(context); final maxLines = _maxLines(context);
if (cupertino) {
// CupertinoTextField lays its placeholder out with up to maxLines lines
// but sizes an empty field by minLines, so a wrapped placeholder was
// clipped on a narrow pane. While empty the field is exactly as tall as
// its placeholder (at most 3 lines, then ellipsised); typing restores
// the normal range (see _maxLines).
return LayoutBuilder(
builder: (context, constraints) {
final empty = _text.text.isEmpty;
final lines = empty
? _placeholderLines(context, constraints.maxWidth)
: 1;
return CupertinoTextField(
key: const Key('chat-composer-field'),
controller: _text,
focusNode: _focus,
scrollController: _fieldScroll,
placeholder: widget.placeholder,
// The pill draws the field's surface; the field adds no border.
decoration: null,
// The contextual prompt must stay readable on the glass fill;
// placeholderText falls below normal-text contrast here.
placeholderStyle: TextStyle(
color: CupertinoColors.label.resolveFrom(context),
overflow: TextOverflow.ellipsis,
),
minLines: lines,
// Keep the empty field multiline too: a single-line web editor
// strips Shift+Enter's newline on the next text edit.
maxLines: empty && lines > 1 ? lines : maxLines,
keyboardType: TextInputType.multiline,
textInputAction: _enterSends
? TextInputAction.send
: TextInputAction.newline,
onEditingComplete: () {},
onSubmitted: (_) => _submitDraft(),
onChanged: _onDraftEdited,
);
},
);
}
return TextField( return TextField(
key: const Key('chat-composer-field'), key: const Key('chat-composer-field'),
controller: _text, controller: _text,
@@ -1320,7 +1169,7 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
); );
} }
Widget _primary(BuildContext context, bool cupertino, {bool stop = false}) { Widget _primary(BuildContext context, {bool stop = false}) {
final composer = widget.composer; final composer = widget.composer;
final enabled = stop final enabled = stop
? !composer.stopping ? !composer.stopping
@@ -1356,42 +1205,6 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
// A coloured chat's send button takes the chat's colour (its seeded // A coloured chat's send button takes the chat's colour (its seeded
// primary, like the focus ring); stop stays the host's error red. // primary, like the focus ring); stop stays the host's error red.
final tinted = chatSchemeOf(context, widget.chatColor); final tinted = chatSchemeOf(context, widget.chatColor);
if (cupertino) {
return Semantics(
button: true,
label: label,
excludeSemantics: true,
// A filled circle centred in a full touch target, like Material's
// filled icon button, so it keeps the pill's edge gap on every side.
child: SizedBox.square(
dimension: GlassBarMetrics.controlExtent(true),
child: Center(
child: CupertinoButton.filled(
key: key,
sizeStyle: CupertinoButtonSize.small,
padding: EdgeInsets.zero,
minimumSize: Size.square(GlassBarMetrics.filledExtent(true)),
borderRadius: BorderRadius.circular(
GlassBarMetrics.filledExtent(true) / 2,
),
color: stop
? CupertinoColors.systemRed.resolveFrom(context)
: tinted?.primary,
onPressed: enabled ? press : null,
child: stop
? const ChatStopIcon(
child: Icon(CupertinoIcons.stop_fill, size: 18),
)
: Icon(
CupertinoIcons.arrow_up,
size: 18,
color: enabled ? tinted?.onPrimary : null,
),
),
),
),
);
}
final scheme = Theme.of(context).colorScheme; final scheme = Theme.of(context).colorScheme;
return IconButton.filled( return IconButton.filled(
key: key, key: key,
@@ -1418,7 +1231,7 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
/// shape, plus the offer's two host controls when an unknown command can be /// shape, plus the offer's two host controls when an unknown command can be
/// sent as a message. Neither action is a prompt until the operator chooses /// sent as a message. Neither action is a prompt until the operator chooses
/// "Send as message". /// "Send as message".
Widget _commandReport(BuildContext context, bool cupertino) { Widget _commandReport(BuildContext context) {
final offer = _commandOffer; final offer = _commandOffer;
return Column( return Column(
key: const Key('chat-composer-command-notice'), key: const Key('chat-composer-command-notice'),
@@ -1433,36 +1246,21 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
: chatCommandNoticeLabel, : chatCommandNoticeLabel,
style: TextStyle( style: TextStyle(
color: _commandFailed color: _commandFailed
? (cupertino ? Theme.of(context).colorScheme.error
? CupertinoColors.systemRed.resolveFrom(context)
: Theme.of(context).colorScheme.error)
: null, : null,
), ),
), ),
), ),
if (cupertino) IconButton(
Semantics( key: const Key('chat-command-dismiss'),
button: true, tooltip: chatCommandDismissLabel,
label: chatCommandDismissLabel, onPressed: () => setState(_dismissCommandReport),
child: CupertinoButton( icon: const Icon(Icons.close),
key: const Key('chat-command-dismiss'), ),
padding: EdgeInsets.zero,
onPressed: () => setState(_dismissCommandReport),
child: const Text('Dismiss'),
),
)
else
IconButton(
key: const Key('chat-command-dismiss'),
tooltip: chatCommandDismissLabel,
onPressed: () => setState(_dismissCommandReport),
icon: const Icon(Icons.close),
),
], ],
), ),
_notice( _notice(
context, context,
cupertino,
key: const Key('chat-composer-command-text'), key: const Key('chat-composer-command-text'),
text: _commandNotice!, text: _commandNotice!,
failed: _commandFailed, failed: _commandFailed,
@@ -1476,13 +1274,11 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
runSpacing: 4, runSpacing: 4,
children: [ children: [
_commandAction( _commandAction(
cupertino,
key: const Key('chat-command-send-as-message'), key: const Key('chat-command-send-as-message'),
label: chatCommandSendAsMessageLabel, label: chatCommandSendAsMessageLabel,
onPressed: () => unawaited(_sendOffered()), onPressed: () => unawaited(_sendOffered()),
), ),
_commandAction( _commandAction(
cupertino,
key: const Key('chat-command-cancel'), key: const Key('chat-command-cancel'),
label: chatCommandCancelLabel, label: chatCommandCancelLabel,
onPressed: () => setState(_dismissCommandReport), onPressed: () => setState(_dismissCommandReport),
@@ -1494,45 +1290,27 @@ class _ChatComposerBarState extends State<ChatComposerBar> {
); );
} }
Widget _commandAction( Widget _commandAction({
bool cupertino, {
required Key key, required Key key,
required String label, required String label,
required VoidCallback onPressed, required VoidCallback onPressed,
}) { }) {
if (cupertino) {
return CupertinoButton(
key: key,
padding: EdgeInsets.zero,
onPressed: onPressed,
child: Text(label),
);
}
return TextButton(key: key, onPressed: onPressed, child: Text(label)); return TextButton(key: key, onPressed: onPressed, child: Text(label));
} }
/// A polite, secondary line for queued/refused state. The error uses the /// A polite, secondary line for queued/refused state. The error uses the
/// host's own semantic error tint, never a bespoke palette. /// host's own semantic error tint, never a bespoke palette.
Widget _notice( Widget _notice(
BuildContext context, BuildContext context, {
bool cupertino, {
required Key key, required Key key,
required String text, required String text,
bool failed = false, bool failed = false,
}) { }) {
final theme = Theme.of(context); final theme = Theme.of(context);
final color = failed final color = failed
? (cupertino ? theme.colorScheme.error
? CupertinoColors.systemRed.resolveFrom(context) : theme.colorScheme.onSurfaceVariant;
: theme.colorScheme.error) final style = theme.textTheme.bodyMedium?.copyWith(color: color);
: (cupertino
? CupertinoColors.secondaryLabel.resolveFrom(context)
: theme.colorScheme.onSurfaceVariant);
final style =
(cupertino
? CupertinoTheme.of(context).textTheme.textStyle
: theme.textTheme.bodyMedium)
?.copyWith(color: color);
return Semantics( return Semantics(
liveRegion: true, liveRegion: true,
child: Padding( child: Padding(
@@ -1,4 +1,3 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'chat_deliveries.dart'; import 'chat_deliveries.dart';
@@ -41,12 +40,8 @@ class ChatDeliveryIndicator extends StatelessWidget {
Widget build(BuildContext context) { Widget build(BuildContext context) {
final failed = state == ChatDelivery.failed; final failed = state == ChatDelivery.failed;
final color = failed final color = failed
? (cupertino ? Theme.of(context).colorScheme.error
? CupertinoColors.systemRed.resolveFrom(context) : Theme.of(context).colorScheme.onSurfaceVariant;
: Theme.of(context).colorScheme.error)
: (cupertino
? CupertinoColors.secondaryLabel.resolveFrom(context)
: Theme.of(context).colorScheme.onSurfaceVariant);
final style = DefaultTextStyle.of( final style = DefaultTextStyle.of(
context, context,
).style.merge(TextStyle(fontSize: 12, color: color)); ).style.merge(TextStyle(fontSize: 12, color: color));
@@ -75,13 +70,11 @@ class ChatDeliveryIndicator extends StatelessWidget {
} }
IconData get _icon => switch (state) { IconData get _icon => switch (state) {
ChatDelivery.sending => cupertino ? CupertinoIcons.clock : Icons.schedule, ChatDelivery.sending => Icons.schedule,
ChatDelivery.sent => cupertino ? CupertinoIcons.checkmark : Icons.done, ChatDelivery.sent => Icons.done,
ChatDelivery.queued => ChatDelivery.queued => Icons.hourglass_empty,
cupertino ? CupertinoIcons.hourglass : Icons.hourglass_empty, ChatDelivery.steered => Icons.done,
ChatDelivery.steered => cupertino ? CupertinoIcons.checkmark : Icons.done, ChatDelivery.failed => Icons.error_outline,
ChatDelivery.failed =>
cupertino ? CupertinoIcons.exclamationmark_circle : Icons.error_outline,
}; };
Widget _action( Widget _action(
@@ -90,15 +83,6 @@ class ChatDeliveryIndicator extends StatelessWidget {
VoidCallback onPressed, VoidCallback onPressed,
TextStyle style, TextStyle style,
) { ) {
if (cupertino) {
return CupertinoButton(
key: Key(key),
padding: const EdgeInsets.symmetric(horizontal: 6),
minimumSize: Size.zero,
onPressed: onPressed,
child: Text(text, style: style.copyWith(fontWeight: FontWeight.w600)),
);
}
return TextButton( return TextButton(
key: Key(key), key: Key(key),
style: TextButton.styleFrom( style: TextButton.styleFrom(
@@ -1,22 +1,18 @@
import '../../../ui/adaptive/app_menu_anchor.dart';
import 'dart:async'; import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart'; import '../../../core/api_gateway.dart';
import '../../../core/error_reason.dart'; import '../../../core/error_reason.dart';
import '../ui/sessions/chat_adaptive.dart'; import '../../../ui/adaptive/app_menu_anchor.dart';
import 'chat_bar_control_style.dart'; import 'chat_bar_control_style.dart';
import 'chat_effort_sheet.dart';
import 'chat_efforts.dart'; import 'chat_efforts.dart';
import 'chat_models.dart'; import 'chat_models.dart';
/// The conversation bar's thinking-level control ("Thinking: High"). /// The conversation bar's thinking-level control ("Thinking: High").
/// ///
/// It shows the levels the session row names for the chat's model without a /// It shows the levels the session row names for the chat's model without a
/// request of its own. Material opens a menu and Cupertino an action sheet of /// request of its own. It opens a menu of those levels; choosing one sends `chat_effort` through the chat's own
/// those levels; choosing one sends `chat_effort` through the chat's own
/// gateway. The level applies from the next turn: while a turn runs, the /// gateway. The level applies from the next turn: while a turn runs, the
/// choices say so and the label marks the new level "next turn". A model with /// choices say so and the label marks the new level "next turn". A model with
/// no levels (or a harness without them) shows no control. After the model /// no levels (or a harness without them) shows no control. After the model
@@ -114,20 +110,9 @@ class _ChatEffortControlState extends State<ChatEffortControl> {
} }
} }
Future<void> _openSheet() => showCupertinoModalPopup<void>(
context: context,
builder: (_) => ChatEffortSheet(
state: _state,
running: widget.running,
choose: _choose,
),
);
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
if (!_state.supported) return const SizedBox.shrink(); if (!_state.supported) return const SizedBox.shrink();
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final label = final label =
'${chatEffortLabel(_state)}${_nextTurn ? ' · next turn' : ''}'; '${chatEffortLabel(_state)}${_nextTurn ? ' · next turn' : ''}';
final iconOnly = final iconOnly =
@@ -135,7 +120,7 @@ class _ChatEffortControlState extends State<ChatEffortControl> {
final content = Row( final content = Row(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
Icon(cupertino ? CupertinoIcons.lightbulb : Icons.psychology_outlined), const Icon(Icons.psychology_outlined),
if (!iconOnly) ...[ if (!iconOnly) ...[
const SizedBox(width: 4), const SizedBox(width: 4),
Flexible(child: Text(label, overflow: TextOverflow.ellipsis)), Flexible(child: Text(label, overflow: TextOverflow.ellipsis)),
@@ -143,22 +128,6 @@ class _ChatEffortControlState extends State<ChatEffortControl> {
], ],
); );
const key = Key('chat-effort'); const key = Key('chat-effort');
if (cupertino) {
return Semantics(
container: true,
button: true,
label: 'Change thinking level, currently ${_state.currentName}',
onTap: _openSheet,
child: ExcludeSemantics(
child: CupertinoButton(
key: key,
padding: chatBarButtonPadding,
onPressed: _openSheet,
child: chatBarCupertinoContent(context, content),
),
),
);
}
return AppMenuAnchor( return AppMenuAnchor(
menuChildren: [ menuChildren: [
Padding( Padding(
@@ -1,11 +1,14 @@
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart';
import '../../../core/error_reason.dart'; import '../../../core/error_reason.dart';
import 'chat_efforts.dart'; import 'chat_efforts.dart';
/// The Cupertino action sheet of a chat's thinking levels, the current one /// The thinking-level chooser of a chat: the levels with the current one
/// checked. It stays open with the server's reason when a choice is refused /// checked, in a Material dialog. It stays open with the server's reason when
/// and closes once one is accepted. /// a choice is refused and closes once one is accepted.
///
/// Nothing opens it now: the effort control shows its levels in an anchored
/// menu. The class stays so existing references keep compiling.
class ChatEffortSheet extends StatefulWidget { class ChatEffortSheet extends StatefulWidget {
const ChatEffortSheet({ const ChatEffortSheet({
super.key, super.key,
@@ -53,49 +56,40 @@ class _ChatEffortSheetState extends State<ChatEffortSheet> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final secondary = CupertinoColors.secondaryLabel.resolveFrom(context); final scheme = Theme.of(context).colorScheme;
final error = _error; final error = _error;
return CupertinoActionSheet( return AlertDialog(
key: const Key('chat-effort-sheet'), key: const Key('chat-effort-sheet'),
title: const Text('Thinking'), title: const Text('Thinking'),
message: Text( content: SingleChildScrollView(
error ?? chatEffortNote(running: widget.running), child: ListBody(
key: const Key('chat-effort-note'), children: [
style: error == null Text(
? null error ?? chatEffortNote(running: widget.running),
: TextStyle(color: CupertinoColors.systemRed.resolveFrom(context)), key: const Key('chat-effort-note'),
style: error == null ? null : TextStyle(color: scheme.error),
),
for (final level in widget.state.levels)
ListTile(
key: ValueKey<String>('chat-effort-option-${level.id}'),
title: Text(level.name),
subtitle: level.description.isEmpty
? null
: Text(level.description),
trailing: level.id == widget.state.current
? const Icon(Icons.check)
: null,
onTap: () => _choose(level),
),
],
),
), ),
actions: [ actions: [
for (final level in widget.state.levels) TextButton(
CupertinoActionSheetAction( onPressed: () => Navigator.of(context).pop(),
key: ValueKey<String>('chat-effort-option-${level.id}'), child: const Text('Cancel'),
onPressed: () => _choose(level), ),
child: Column(
children: [
Row(
mainAxisSize: MainAxisSize.min,
children: [
Flexible(child: Text(level.name)),
if (level.id == widget.state.current) ...[
const SizedBox(width: 6),
const Icon(CupertinoIcons.checkmark_alt),
],
],
),
if (level.description.isNotEmpty)
Text(
level.description,
textAlign: TextAlign.center,
style: TextStyle(fontSize: 13, color: secondary),
),
],
),
),
], ],
cancelButton: CupertinoActionSheetAction(
onPressed: () => Navigator.of(context).pop(),
child: const Text('Cancel'),
),
); );
} }
} }
@@ -1,6 +1,5 @@
import 'dart:async'; import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart'; import '../../../core/api_gateway.dart';
@@ -141,11 +140,7 @@ class _ChatModelChooserState extends State<ChatModelChooser> {
} }
@override @override
Widget build(BuildContext context) => Widget build(BuildContext context) => _materialChooser(context);
widget.cupertino ? _cupertinoChooser(context) : _materialChooser(context);
/// Whether the catalog loaded far enough to search it.
bool get _hasCatalog => !_loading && _error == null && _models.isNotEmpty;
Widget _materialChooser(BuildContext context) { Widget _materialChooser(BuildContext context) {
final theme = Theme.of(context); final theme = Theme.of(context);
@@ -210,7 +205,7 @@ class _ChatModelChooserState extends State<ChatModelChooser> {
SimpleDialogOption( SimpleDialogOption(
key: _optionKey(model), key: _optionKey(model),
onPressed: _busy ? null : () => _choose(model), onPressed: _busy ? null : () => _choose(model),
child: _optionRow(context, model, cupertino: false), child: _optionRow(context, model),
), ),
if (matches.isEmpty && needle.isNotEmpty) if (matches.isEmpty && needle.isNotEmpty)
Padding( Padding(
@@ -237,111 +232,10 @@ class _ChatModelChooserState extends State<ChatModelChooser> {
); );
} }
Widget _cupertinoChooser(BuildContext context) { Widget _optionRow(BuildContext context, JsonMap model) {
final secondary = CupertinoColors.secondaryLabel.resolveFrom(context);
final error = CupertinoColors.systemRed.resolveFrom(context);
final matches = filterChatModels(_models, _search.text);
final needle = _search.text.trim();
return CupertinoActionSheet(
key: const Key('chat-model-chooser'),
title: const Text('Change model'),
message: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
chatModelSelectionNote(widget.backend),
textAlign: TextAlign.center,
),
if (_hasCatalog)
Padding(
padding: const EdgeInsetsDirectional.only(top: 12),
// The search field sits in the sheet's message slot: a native
// search field is the only way to type here, and the sheet's own
// scroll keeps a long catalog reachable.
child: CupertinoSearchTextField(
key: const Key('chat-model-search'),
controller: _search,
placeholder: 'Search models',
onChanged: (_) => setState(() {}),
),
),
if (_loading)
const Padding(
padding: EdgeInsetsDirectional.only(top: 12),
child: Row(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
CupertinoActivityIndicator(),
SizedBox(width: 8),
Flexible(child: Text('Loading models…')),
],
),
)
else if (_error != null)
Padding(
padding: const EdgeInsetsDirectional.only(top: 8),
child: Text(
_error!,
key: const Key('chat-model-error'),
textAlign: TextAlign.center,
style: TextStyle(color: error),
),
)
else if (_models.isEmpty)
Padding(
padding: const EdgeInsetsDirectional.only(top: 8),
child: Text(
'No models are available for this chat.',
textAlign: TextAlign.center,
style: TextStyle(color: secondary),
),
)
else if (matches.isEmpty && needle.isNotEmpty)
Padding(
padding: const EdgeInsetsDirectional.only(top: 8),
child: Text(
'No models match "$needle".',
key: const Key('chat-model-no-match'),
textAlign: TextAlign.center,
style: TextStyle(color: secondary),
),
),
],
),
actions: _hasCatalog
? [
for (final model in matches)
CupertinoActionSheetAction(
key: _optionKey(model),
isDefaultAction: _isCurrent(model),
onPressed: () {
if (!_busy) _choose(model);
},
child: _optionRow(context, model, cupertino: true),
),
]
: null,
cancelButton: CupertinoActionSheetAction(
key: const Key('chat-model-cancel'),
onPressed: () => Navigator.of(context).pop(),
child: const Text('Cancel'),
),
);
}
Widget _optionRow(
BuildContext context,
JsonMap model, {
required bool cupertino,
}) {
final selected = _isCurrent(model); final selected = _isCurrent(model);
final secondary = cupertino final secondary = Theme.of(context).colorScheme.onSurfaceVariant;
? CupertinoColors.secondaryLabel.resolveFrom(context) final accent = Theme.of(context).colorScheme.primary;
: Theme.of(context).colorScheme.onSurfaceVariant;
final accent = cupertino
? CupertinoTheme.of(context).primaryColor
: Theme.of(context).colorScheme.primary;
final provider = '${model['provider'] ?? ''}'.trim(); final provider = '${model['provider'] ?? ''}'.trim();
return Semantics( return Semantics(
selected: selected, selected: selected,
@@ -358,11 +252,7 @@ class _ChatModelChooserState extends State<ChatModelChooser> {
], ],
), ),
), ),
if (selected) if (selected) Icon(Icons.check, color: accent),
Icon(
cupertino ? CupertinoIcons.check_mark : Icons.check,
color: accent,
),
], ],
), ),
); );
@@ -1,8 +1,6 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart'; import '../../../core/api_gateway.dart';
import '../ui/sessions/chat_adaptive.dart';
import 'chat_bar_control_style.dart'; import 'chat_bar_control_style.dart';
import 'chat_model_chooser.dart'; import 'chat_model_chooser.dart';
import 'chat_models.dart'; import 'chat_models.dart';
@@ -75,24 +73,15 @@ class _ChatModelControlState extends State<ChatModelControl> {
} }
Future<void> _open() async { Future<void> _open() async {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final chooser = ChatModelChooser( final chooser = ChatModelChooser(
gateway: widget.gateway, gateway: widget.gateway,
sessionId: widget.sessionId, sessionId: widget.sessionId,
backend: '${widget.session['backend'] ?? ''}'.trim(), backend: '${widget.session['backend'] ?? ''}'.trim(),
currentProvider: _provider, currentProvider: _provider,
currentModel: _model, currentModel: _model,
cupertino: cupertino, cupertino: false,
onAccepted: _accept, onAccepted: _accept,
); );
if (cupertino) {
await showCupertinoModalPopup<void>(
context: context,
builder: (_) => chooser,
);
return;
}
await showDialog<void>(context: context, builder: (_) => chooser); await showDialog<void>(context: context, builder: (_) => chooser);
} }
@@ -110,8 +99,6 @@ class _ChatModelControlState extends State<ChatModelControl> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final backend = '${widget.session['backend'] ?? ''}'.trim(); final backend = '${widget.session['backend'] ?? ''}'.trim();
final label = _model.isNotEmpty final label = _model.isNotEmpty
? chatModelLabel(_model, _selection) ? chatModelLabel(_model, _selection)
@@ -126,26 +113,10 @@ class _ChatModelControlState extends State<ChatModelControl> {
children: [ children: [
Flexible(child: Text(label, overflow: TextOverflow.ellipsis)), Flexible(child: Text(label, overflow: TextOverflow.ellipsis)),
const SizedBox(width: 4), const SizedBox(width: 4),
Icon(cupertino ? CupertinoIcons.chevron_down : Icons.expand_more), const Icon(Icons.expand_more),
], ],
); );
const key = Key('chat-model'); const key = Key('chat-model');
if (cupertino) {
return Semantics(
container: true,
button: true,
label: 'Change model, currently $label',
onTap: _open,
child: ExcludeSemantics(
child: CupertinoButton(
key: key,
padding: chatBarButtonPadding,
onPressed: _open,
child: chatBarCupertinoContent(context, content),
),
),
);
}
return Semantics( return Semantics(
container: true, container: true,
button: true, button: true,
@@ -1,8 +1,5 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../ui/sessions/chat_adaptive.dart';
/// The open chat's Next chat button: the platform's icon button, labelled /// The open chat's Next chat button: the platform's icon button, labelled
/// "Next chat", that opens the chat after this one in the list. /// "Next chat", that opens the chat after this one in the list.
/// ///
@@ -18,17 +15,6 @@ class ChatNextChatButton extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) {
return Semantics(
label: label,
button: true,
child: CupertinoButton(
padding: EdgeInsets.zero,
onPressed: onPressed,
child: const Icon(CupertinoIcons.arrow_right_to_line),
),
);
}
return IconButton( return IconButton(
tooltip: label, tooltip: label,
onPressed: onPressed, onPressed: onPressed,
@@ -1,8 +1,5 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../ui/sessions/chat_adaptive.dart';
/// Selects a retained pane when the window cannot show every chat at once. /// Selects a retained pane when the window cannot show every chat at once.
Future<void> showChatPanePicker( Future<void> showChatPanePicker(
BuildContext context, { BuildContext context, {
@@ -11,45 +8,23 @@ Future<void> showChatPanePicker(
required ValueChanged<String> onSelected, required ValueChanged<String> onSelected,
String title = 'Open chats', String title = 'Open chats',
}) async { }) async {
final String? selected; final selected = await showDialog<String>(
if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) { context: context,
selected = await showCupertinoModalPopup<String>( builder: (context) => SimpleDialog(
context: context, title: Text(title),
builder: (context) => CupertinoActionSheet( children: [
title: Text(title), for (final pane in panes)
actions: [ SimpleDialogOption(
for (final pane in panes) onPressed: () => Navigator.pop(context, pane.id),
CupertinoActionSheetAction( child: Row(
isDefaultAction: pane.id == activeId, children: [
onPressed: () => Navigator.pop(context, pane.id), Expanded(child: Text(pane.title)),
child: Text(pane.title), if (pane.id == activeId) const Icon(Icons.check),
],
), ),
], ),
cancelButton: CupertinoActionSheetAction( ],
onPressed: () => Navigator.pop(context), ),
child: const Text('Cancel'), );
),
),
);
} else {
selected = await showDialog<String>(
context: context,
builder: (context) => SimpleDialog(
title: Text(title),
children: [
for (final pane in panes)
SimpleDialogOption(
onPressed: () => Navigator.pop(context, pane.id),
child: Row(
children: [
Expanded(child: Text(pane.title)),
if (pane.id == activeId) const Icon(Icons.check),
],
),
),
],
),
);
}
if (selected != null && context.mounted) onSelected(selected); if (selected != null && context.mounted) onSelected(selected);
} }
@@ -1,8 +1,5 @@
import '../../../ui/theme/app_theme.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../ui/sessions/chat_adaptive.dart';
import '../ui/transcript/native_disclosure.dart'; import '../ui/transcript/native_disclosure.dart';
import 'chat_card_styles.dart'; import 'chat_card_styles.dart';
import 'chat_permission_card_model.dart'; import 'chat_permission_card_model.dart';
@@ -25,105 +22,93 @@ class ChatPermissionCard extends StatelessWidget {
final Future<void> Function(String decision) onDecision; final Future<void> Function(String decision) onDecision;
final String? error; final String? error;
/// The card-style helpers keep their `cupertino` flag for existing callers;
/// the card is always Material, so every call passes `false`.
@override @override
Widget build(BuildContext context) => Widget build(BuildContext context) => Card(
chatControlsStyleOf(context) == ChatControlsStyle.cupertino // Consecutive cards must read as separate surfaces; the row itself adds only
? _cupertino(context) // the horizontal inset.
: _material(context); margin: const EdgeInsets.only(bottom: 12),
child: Padding(padding: const EdgeInsets.all(16), child: _body(context)),
);
Widget _body(BuildContext context, {required bool cupertino}) { Widget _body(BuildContext context) => Column(
final body = Column( mainAxisSize: MainAxisSize.min,
mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch,
crossAxisAlignment: CrossAxisAlignment.stretch, children: [
children: [ Row(
Row( crossAxisAlignment: CrossAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start, children: [
children: [ Padding(
Padding( padding: const EdgeInsetsDirectional.only(end: 12),
padding: const EdgeInsetsDirectional.only(end: 12), child: Icon(
child: Icon( Icons.shield_outlined,
cupertino color: chatCardWarningColor(context, false),
? 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) Expanded(
NativeDisclosure( child: Column(
label: 'Show full request', crossAxisAlignment: CrossAxisAlignment.start,
childBuilder: (context) => children: [
SelectableText(card.resources.join('\n')), Text(card.headline, style: chatCardTitleStyle(context, false)),
Text(
card.statusLine,
style: chatCardSecondaryStyle(context, false),
),
],
), ),
),
], ],
if (card.showRisk && card.risk.trim().isNotEmpty) ...[ ),
const SizedBox(height: 12), if (card.resourceText.isNotEmpty) ...[
_risk(context, cupertino), const SizedBox(height: 12),
], DecoratedBox(
if (error != null && error!.trim().isNotEmpty) ...[ decoration: BoxDecoration(
const SizedBox(height: 12), color: chatCardFillColor(context, false),
Semantics( borderRadius: BorderRadius.circular(8),
liveRegion: true, ),
child: Padding(
padding: const EdgeInsets.all(8),
child: Text( child: Text(
error!, card.resourceText,
style: chatCardBodyStyle( maxLines: chatApprovalMaxResourceLines,
context, overflow: TextOverflow.ellipsis,
cupertino,
)?.copyWith(color: chatCardErrorColor(context, cupertino)),
), ),
), ),
], ),
if (card.actionable) ...[ if (card.resources.join('\n') != card.resourceText)
const SizedBox(height: 12), NativeDisclosure(
_controls(context, cupertino), label: 'Show full request',
], childBuilder: (context) =>
SelectableText(card.resources.join('\n')),
),
], ],
); if (card.showRisk && card.risk.trim().isNotEmpty) ...[
return cupertino const SizedBox(height: 12),
? DefaultTextStyle.merge( _risk(context),
style: CupertinoTheme.of(context).textTheme.textStyle, ],
child: body, if (error != null && error!.trim().isNotEmpty) ...[
) const SizedBox(height: 12),
: body; Semantics(
} liveRegion: true,
child: Text(
error!,
style: chatCardBodyStyle(
context,
false,
)?.copyWith(color: chatCardErrorColor(context, false)),
),
),
],
if (card.actionable) ...[const SizedBox(height: 12), _controls(context)],
],
);
Widget _risk(BuildContext context, bool cupertino) { Widget _risk(BuildContext context) {
final tint = chatCardWarningColor(context, cupertino); final tint = chatCardWarningColor(context, false);
return DecoratedBox( return DecoratedBox(
decoration: BoxDecoration( decoration: BoxDecoration(
color: chatCardWarningFillColor(context, cupertino), color: chatCardWarningFillColor(context, false),
borderRadius: BorderRadius.circular(8), borderRadius: BorderRadius.circular(8),
), ),
child: Padding( child: Padding(
@@ -133,105 +118,45 @@ class ChatPermissionCard extends StatelessWidget {
children: [ children: [
Row( Row(
children: [ children: [
Icon( Icon(Icons.shield_outlined, size: 16, color: tint),
cupertino
? CupertinoIcons.exclamationmark_shield
: Icons.shield_outlined,
size: 16,
color: tint,
),
const SizedBox(width: 6), const SizedBox(width: 6),
Expanded( Expanded(
child: Text( child: Text(
chatRiskReviewLabel, chatRiskReviewLabel,
style: chatCardLabelStyle( style: chatCardLabelStyle(
context, context,
cupertino, false,
)?.copyWith(color: tint), )?.copyWith(color: tint),
), ),
), ),
], ],
), ),
const SizedBox(height: 4), const SizedBox(height: 4),
Text(card.risk, style: chatCardBodyStyle(context, cupertino)), Text(card.risk, style: chatCardBodyStyle(context, false)),
], ],
), ),
), ),
); );
} }
Widget _controls(BuildContext context, bool cupertino) { Widget _controls(BuildContext context) => Wrap(
final always = card.alwaysLabel; spacing: 8,
if (cupertino) { runSpacing: 8,
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(
backgroundColor: AppColors.groupedBackground,
// As the Material card: the transcript row owns the horizontal inset, so
// the card lines up with the message bubbles.
margin: const EdgeInsets.only(bottom: 12),
children: [ children: [
Padding( FilledButton(
padding: const EdgeInsets.all(16), onPressed: () => onDecision(chatDecisionOnce),
child: _body(context, cupertino: true), child: const Text(chatApprovalOnceLabel),
),
TextButton(
onPressed: () => onDecision(chatDecisionAlways),
child: Text(card.alwaysLabel),
),
TextButton(
onPressed: () => onDecision(chatDecisionReject),
style: TextButton.styleFrom(
foregroundColor: Theme.of(context).colorScheme.error,
),
child: const Text(chatApprovalRejectLabel),
), ),
], ],
); );
@@ -1,9 +1,7 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart'; import '../../../core/api_gateway.dart';
import '../../../ui/text/monospace.dart'; import '../../../ui/text/monospace.dart';
import '../ui/sessions/chat_adaptive.dart';
import '../ui/transcript/chat_turn_chip.dart'; import '../ui/transcript/chat_turn_chip.dart';
import '../ui/transcript/native_disclosure.dart'; import '../ui/transcript/native_disclosure.dart';
import 'chat_permission_card_model.dart'; import 'chat_permission_card_model.dart';
@@ -101,24 +99,14 @@ class ChatPermissionsChip extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final rejected = permissions.any((p) => p.decision == chatDecisionReject); final rejected = permissions.any((p) => p.decision == chatDecisionReject);
final color = rejected final color = rejected
? (cupertino ? Theme.of(context).colorScheme.error
? CupertinoColors.systemRed.resolveFrom(context) : Theme.of(context).colorScheme.onSurfaceVariant;
: Theme.of(context).colorScheme.error)
: (cupertino
? CupertinoColors.secondaryLabel.resolveFrom(context)
: Theme.of(context).colorScheme.onSurfaceVariant);
final label = chatPermissionsLabel(permissions.length); final label = chatPermissionsLabel(permissions.length);
return ChatTurnChip( return ChatTurnChip(
chipKey: const Key('chat-permission-chip'), chipKey: const Key('chat-permission-chip'),
leading: Icon( leading: Icon(Icons.shield_outlined, size: 14, color: color),
cupertino ? CupertinoIcons.checkmark_shield : Icons.shield_outlined,
size: 14,
color: color,
),
label: label, label: label,
color: color, color: color,
semanticsLabel: permissions.length == 1 semanticsLabel: permissions.length == 1
@@ -136,11 +124,7 @@ class _PermissionsSheet extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final cupertino = final style = Theme.of(context).textTheme.bodyMedium;
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final style = cupertino
? CupertinoTheme.of(context).textTheme.textStyle
: Theme.of(context).textTheme.bodyMedium;
return DefaultTextStyle.merge( return DefaultTextStyle.merge(
style: style, style: style,
child: ConstrainedBox( child: ConstrainedBox(
@@ -1,9 +1,6 @@
import '../../../ui/theme/app_theme.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart'; import '../../../core/api_gateway.dart';
import '../ui/sessions/chat_adaptive.dart';
import 'chat_card_styles.dart'; import 'chat_card_styles.dart';
import 'chat_question_card_controls.dart'; import 'chat_question_card_controls.dart';
import 'chat_question_card_fields.dart'; import 'chat_question_card_fields.dart';
@@ -125,34 +122,14 @@ class _ChatQuestionCardState extends State<ChatQuestionCard> {
} }
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) => Card(
final cupertino = // Keep consecutive cards visually separate; the transcript row only
chatControlsStyleOf(context) == ChatControlsStyle.cupertino; // supplies the horizontal inset.
final body = _body(context, cupertino); margin: const EdgeInsets.only(bottom: 12),
final wrapped = cupertino child: Padding(padding: const EdgeInsets.all(16), child: _body(context)),
? DefaultTextStyle.merge( );
style: CupertinoTheme.of(context).textTheme.textStyle,
child: body,
)
: body;
if (cupertino) {
return CupertinoListSection.insetGrouped(
backgroundColor: AppColors.groupedBackground,
// As the Material card: the transcript row owns the horizontal inset,
// so the card lines up with the message bubbles.
margin: const EdgeInsets.only(bottom: 12),
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) { Widget _body(BuildContext context) {
final actions = widget.form['actions']; final actions = widget.form['actions'];
final error = widget.error?.trim().isNotEmpty == true final error = widget.error?.trim().isNotEmpty == true
? widget.error!.trim() ? widget.error!.trim()
@@ -165,9 +142,9 @@ class _ChatQuestionCardState extends State<ChatQuestionCard> {
'${widget.form['title'] ?? ''}'.trim().isEmpty '${widget.form['title'] ?? ''}'.trim().isEmpty
? 'Question' ? 'Question'
: '${widget.form['title']}'.trim(), : '${widget.form['title']}'.trim(),
style: chatCardTitleStyle(context, cupertino), style: chatCardTitleStyle(context, false),
), ),
Text(_statusLine(), style: chatCardSecondaryStyle(context, cupertino)), Text(_statusLine(), style: chatCardSecondaryStyle(context, false)),
if (error.isNotEmpty) if (error.isNotEmpty)
Padding( Padding(
padding: const EdgeInsets.only(top: 8), padding: const EdgeInsets.only(top: 8),
@@ -177,8 +154,8 @@ class _ChatQuestionCardState extends State<ChatQuestionCard> {
error, error,
style: chatCardBodyStyle( style: chatCardBodyStyle(
context, context,
cupertino, false,
)?.copyWith(color: chatCardErrorColor(context, cupertino)), )?.copyWith(color: chatCardErrorColor(context, false)),
), ),
), ),
), ),
@@ -187,7 +164,7 @@ class _ChatQuestionCardState extends State<ChatQuestionCard> {
context: context, context: context,
fields: _fields, fields: _fields,
answers: _answers, answers: _answers,
cupertino: cupertino, cupertino: false,
controllers: _controllers, controllers: _controllers,
onChanged: _changed, onChanged: _changed,
) )
@@ -195,13 +172,13 @@ class _ChatQuestionCardState extends State<ChatQuestionCard> {
...chatQuestionRecordedAnswers( ...chatQuestionRecordedAnswers(
context: context, context: context,
form: widget.form, form: widget.form,
cupertino: cupertino, cupertino: false,
), ),
if (_pending) ...[ if (_pending) ...[
const SizedBox(height: 12), const SizedBox(height: 12),
chatQuestionControls( chatQuestionControls(
context: context, context: context,
cupertino: cupertino, cupertino: false,
actions: actions, actions: actions,
submitLabel: _submitLabel, submitLabel: _submitLabel,
sending: _sending, sending: _sending,
@@ -1,11 +1,11 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
/// Submit and optional decline/cancel controls for a pending question. /// Submit and optional decline/cancel controls for a pending question.
/// ///
/// The web shows `Confirm completion` when every field is external, otherwise /// The web shows `Confirm completion` when every field is external, otherwise
/// `Send answer`, and offers only the actions the form records. The labels are /// `Send answer`, and offers only the actions the form records. The labels are
/// passed in so this file stays layout only. /// passed in so this file stays layout only. `cupertino` is kept for existing
/// callers; the controls are always Material.
Widget chatQuestionControls({ Widget chatQuestionControls({
required BuildContext context, required BuildContext context,
required bool cupertino, required bool cupertino,
@@ -17,31 +17,6 @@ Widget chatQuestionControls({
}) { }) {
final canDecline = actions is List && actions.contains('decline'); final canDecline = actions is List && actions.contains('decline');
final canCancel = actions is List && actions.contains('cancel'); 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( return Wrap(
spacing: 8, spacing: 8,
runSpacing: 8, runSpacing: 8,
@@ -1,4 +1,3 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart'; import '../../../core/api_gateway.dart';
@@ -91,7 +90,6 @@ Widget _field({
label: label, label: label,
keyName: keyName, keyName: keyName,
controller: controllers[keyName]!, controller: controllers[keyName]!,
cupertino: cupertino,
hasOptions: chatQuestionOptions(field).isNotEmpty, hasOptions: chatQuestionOptions(field).isNotEmpty,
onChanged: (value) => onChanged( onChanged: (value) => onChanged(
keyName, keyName,
@@ -110,7 +108,6 @@ Widget _input({
required String label, required String label,
required String keyName, required String keyName,
required TextEditingController controller, required TextEditingController controller,
required bool cupertino,
required bool hasOptions, required bool hasOptions,
required ValueChanged<String> onChanged, required ValueChanged<String> onChanged,
}) { }) {
@@ -131,24 +128,14 @@ Widget _input({
: TextInputType.text; : TextInputType.text;
// The visual label sits above the input; the same words must also reach the // 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. // input's own semantics node, as the web's `aria-label` does.
final input = cupertino final input = TextField(
? CupertinoTextField( key: ValueKey<String>('chat-question-input-$keyName'),
key: ValueKey<String>('chat-question-input-$keyName'), controller: controller,
controller: controller, obscureText: secret,
placeholder: placeholder, keyboardType: keyboard,
obscureText: secret, decoration: InputDecoration(hintText: placeholder),
keyboardType: keyboard, onChanged: onChanged,
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); return Semantics(label: label, child: input);
} }
@@ -1,8 +1,6 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart'; import '../../../core/api_gateway.dart';
import '../ui/sessions/chat_adaptive.dart';
import '../ui/transcript/chat_turn_chip.dart'; import '../ui/transcript/chat_turn_chip.dart';
import 'chat_card_styles.dart'; import 'chat_card_styles.dart';
import 'chat_question_card_model.dart'; import 'chat_question_card_model.dart';
@@ -122,19 +120,11 @@ class ChatQuestionChip extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final cupertino = final color = Theme.of(context).colorScheme.onSurfaceVariant;
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final color = cupertino
? CupertinoColors.secondaryLabel.resolveFrom(context)
: Theme.of(context).colorScheme.onSurfaceVariant;
final label = chatQuestionSummary(form); final label = chatQuestionSummary(form);
return ChatTurnChip( return ChatTurnChip(
chipKey: ValueKey<String>('chat-question-chip-${form['id']}'), chipKey: ValueKey<String>('chat-question-chip-${form['id']}'),
leading: Icon( leading: Icon(Icons.help_outline, size: 14, color: color),
cupertino ? CupertinoIcons.question_circle : Icons.help_outline,
size: 14,
color: color,
),
label: label, label: label,
color: color, color: color,
ellipsizeLabel: true, ellipsizeLabel: true,
@@ -173,11 +163,7 @@ class _QuestionSheet extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final cupertino = final style = Theme.of(context).textTheme.bodyMedium;
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final style = cupertino
? CupertinoTheme.of(context).textTheme.textStyle
: Theme.of(context).textTheme.bodyMedium;
final title = '${form['title'] ?? ''}'.trim(); final title = '${form['title'] ?? ''}'.trim();
return DefaultTextStyle.merge( return DefaultTextStyle.merge(
style: style, style: style,
@@ -192,16 +178,16 @@ class _QuestionSheet extends StatelessWidget {
children: [ children: [
Text( Text(
title.isEmpty ? 'Question' : title, title.isEmpty ? 'Question' : title,
style: chatCardTitleStyle(context, cupertino), style: chatCardTitleStyle(context, false),
), ),
Text( Text(
chatQuestionSettledStatus(form), chatQuestionSettledStatus(form),
style: chatCardSecondaryStyle(context, cupertino), style: chatCardSecondaryStyle(context, false),
), ),
...chatQuestionRecordedAnswers( ...chatQuestionRecordedAnswers(
context: context, context: context,
form: form, form: form,
cupertino: cupertino, cupertino: false,
), ),
], ],
), ),
@@ -1,8 +1,6 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart'; import '../../../core/api_gateway.dart';
import 'chat_card_styles.dart';
import 'chat_question_card_model.dart'; import 'chat_question_card_model.dart';
/// Native option controls for one question field. Single-select uses the host's /// Native option controls for one question field. Single-select uses the host's
@@ -23,43 +21,6 @@ Widget chatQuestionOptionsField({
final selected = multi final selected = multi
? (value is List ? value.map((entry) => '$entry').toSet() : <String>{}) ? (value is List ? value.map((entry) => '$entry').toSet() : <String>{})
: <String>{if (value is String) value}; : <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) { if (multi) {
return Column( return Column(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
@@ -102,8 +63,7 @@ Widget chatQuestionOptionsField({
); );
} }
/// Yes/No for a boolean field: native checkmarks under Cupertino, the web's /// Yes/No for a boolean field: the web's explicit "Choose Yes or No" menu.
/// explicit "Choose Yes or No" menu under Material.
Widget chatQuestionBooleanField({ Widget chatQuestionBooleanField({
required BuildContext context, required BuildContext context,
required JsonMap field, required JsonMap field,
@@ -113,24 +73,6 @@ Widget chatQuestionBooleanField({
required void Function(String key, Object? value) onChanged, required void Function(String key, Object? value) onChanged,
}) { }) {
final value = answers[keyName]; 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>( return DropdownButtonFormField<String>(
initialValue: value is bool ? '$value' : null, initialValue: value is bool ? '$value' : null,
hint: const Text('Choose Yes or No'), hint: const Text('Choose Yes or No'),
@@ -1,4 +1,3 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart'; import '../../../core/api_gateway.dart';
@@ -1,6 +1,5 @@
import 'dart:async'; import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
@@ -12,6 +11,8 @@ import 'chat_export_controller.dart';
/// The info sheet's "Session" section: the harness's native session id with a /// The info sheet's "Session" section: the harness's native session id with a
/// copy control, the harness and the working directory, the verified terminal /// copy control, the harness and the working directory, the verified terminal
/// command that resumes the session, and the export actions. /// command that resumes the session, and the export actions.
///
/// `cupertino` is kept for existing callers; the section is always Material.
class ChatSessionSection extends StatefulWidget { class ChatSessionSection extends StatefulWidget {
const ChatSessionSection({ const ChatSessionSection({
super.key, super.key,
@@ -51,24 +52,13 @@ class _ChatSessionSectionState extends State<ChatSessionSection> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final cupertino = widget.cupertino;
final handoff = widget.handoff; final handoff = widget.handoff;
final secondary = cupertino final secondary = Theme.of(context).colorScheme.onSurfaceVariant;
? CupertinoColors.secondaryLabel.resolveFrom(context) final body = Theme.of(context).textTheme.bodyLarge;
: Theme.of(context).colorScheme.onSurfaceVariant; final title = Theme.of(context).textTheme.titleSmall;
final body = cupertino final label = Theme.of(
? CupertinoTheme.of(context).textTheme.textStyle context,
: Theme.of(context).textTheme.bodyLarge; ).textTheme.bodySmall?.copyWith(color: secondary);
final title = cupertino
? CupertinoTheme.of(
context,
).textTheme.textStyle.copyWith(fontWeight: FontWeight.w600)
: Theme.of(context).textTheme.titleSmall;
final label =
(cupertino
? CupertinoTheme.of(context).textTheme.textStyle
: Theme.of(context).textTheme.bodySmall)
?.copyWith(color: secondary);
final mono = body?.copyWith(fontFamily: appMonospaceFamily); final mono = body?.copyWith(fontFamily: appMonospaceFamily);
final muted = body?.copyWith(color: secondary); final muted = body?.copyWith(color: secondary);
@@ -111,16 +101,11 @@ class _ChatSessionSectionState extends State<ChatSessionSection> {
), ),
_ActionButton( _ActionButton(
key: const Key('chat-session-copy-id'), key: const Key('chat-session-copy-id'),
cupertino: cupertino,
label: _copied == 'id' ? 'Copied' : 'Copy', label: _copied == 'id' ? 'Copied' : 'Copy',
semanticsLabel: _copied == 'id' semanticsLabel: _copied == 'id'
? 'Copied' ? 'Copied'
: 'Copy session ID', : 'Copy session ID',
icon: _copied == 'id' icon: _copied == 'id' ? Icons.check : Icons.copy_outlined,
? (cupertino ? CupertinoIcons.checkmark : Icons.check)
: (cupertino
? CupertinoIcons.doc_on_doc
: Icons.copy_outlined),
onPressed: handoff.id.isEmpty onPressed: handoff.id.isEmpty
? null ? null
: () => _copy('id', handoff.id), : () => _copy('id', handoff.id),
@@ -144,37 +129,27 @@ class _ChatSessionSectionState extends State<ChatSessionSection> {
if (handoff.resumeCommand.isNotEmpty) if (handoff.resumeCommand.isNotEmpty)
_ActionButton( _ActionButton(
key: const Key('chat-session-copy-resume'), key: const Key('chat-session-copy-resume'),
cupertino: cupertino,
label: _copied == 'resume' label: _copied == 'resume'
? 'Copied' ? 'Copied'
: 'Copy resume command', : 'Copy resume command',
icon: _copied == 'resume' icon: _copied == 'resume' ? Icons.check : Icons.terminal,
? (cupertino ? CupertinoIcons.checkmark : Icons.check)
: (cupertino
? CupertinoIcons
.chevron_left_slash_chevron_right
: Icons.terminal),
onPressed: () => _copy('resume', handoff.resumeCommand), onPressed: () => _copy('resume', handoff.resumeCommand),
), ),
_exportButton( _exportButton(
ChatExportFormat.markdown, ChatExportFormat.markdown,
'Export conversation', 'Export conversation',
cupertino Icons.ios_share,
? CupertinoIcons.square_arrow_up
: Icons.ios_share,
), ),
_exportButton( _exportButton(
ChatExportFormat.json, ChatExportFormat.json,
'Export JSON', 'Export JSON',
cupertino ? CupertinoIcons.doc_text : Icons.data_object, Icons.data_object,
), ),
if (handoff.nativeExport) if (handoff.nativeExport)
_exportButton( _exportButton(
ChatExportFormat.native, ChatExportFormat.native,
'Export native session', 'Export native session',
cupertino Icons.description_outlined,
? CupertinoIcons.doc
: Icons.description_outlined,
), ),
], ],
), ),
@@ -201,7 +176,6 @@ class _ChatSessionSectionState extends State<ChatSessionSection> {
final exporter = widget.exporter; final exporter = widget.exporter;
return _ActionButton( return _ActionButton(
key: Key('chat-session-export-${format.wire}'), key: Key('chat-session-export-${format.wire}'),
cupertino: widget.cupertino,
label: label, label: label,
icon: icon, icon: icon,
busy: exporter.active == format, busy: exporter.active == format,
@@ -214,7 +188,6 @@ class _ChatSessionSectionState extends State<ChatSessionSection> {
class _ActionButton extends StatelessWidget { class _ActionButton extends StatelessWidget {
const _ActionButton({ const _ActionButton({
super.key, super.key,
required this.cupertino,
required this.label, required this.label,
required this.icon, required this.icon,
required this.onPressed, required this.onPressed,
@@ -222,7 +195,6 @@ class _ActionButton extends StatelessWidget {
this.busy = false, this.busy = false,
}); });
final bool cupertino;
final String label; final String label;
final String? semanticsLabel; final String? semanticsLabel;
final IconData icon; final IconData icon;
@@ -232,12 +204,10 @@ class _ActionButton extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final Widget leading = busy final Widget leading = busy
? (cupertino ? const SizedBox.square(
? const CupertinoActivityIndicator() dimension: 18,
: const SizedBox.square( child: CircularProgressIndicator(strokeWidth: 2),
dimension: 18, )
child: CircularProgressIndicator(strokeWidth: 2),
))
: Icon(icon, size: 18); : Icon(icon, size: 18);
final child = Row( final child = Row(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
@@ -247,13 +217,6 @@ class _ActionButton extends StatelessWidget {
Flexible(child: Text(label, semanticsLabel: semanticsLabel)), Flexible(child: Text(label, semanticsLabel: semanticsLabel)),
], ],
); );
final button = cupertino return TextButton(onPressed: onPressed, child: child);
? CupertinoButton(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
onPressed: onPressed,
child: child,
)
: TextButton(onPressed: onPressed, child: child);
return button;
} }
} }
@@ -1,6 +1,5 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../ui/sessions/chat_adaptive.dart';
import '../../../ui/adaptive/segmented_bar.dart'; import '../../../ui/adaptive/segmented_bar.dart';
enum ChatSidebarMode { expanded, compact, hidden } enum ChatSidebarMode { expanded, compact, hidden }
@@ -31,46 +30,24 @@ class ChatSidebarButton extends StatelessWidget
); );
Future<void> _choose(BuildContext context) async { Future<void> _choose(BuildContext context) async {
final ChatSidebarMode? choice; final choice = await showDialog<ChatSidebarMode>(
if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) { context: context,
choice = await showCupertinoModalPopup<ChatSidebarMode>( builder: (context) => SimpleDialog(
context: context, title: const Text('Chat list'),
builder: (context) => CupertinoActionSheet( children: [
title: const Text('Chat list'), for (final value in ChatSidebarMode.values)
actions: [ SimpleDialogOption(
for (final value in ChatSidebarMode.values) onPressed: () => Navigator.pop(context, value),
CupertinoActionSheetAction( child: Row(
isDefaultAction: mode == value, children: [
onPressed: () => Navigator.pop(context, value), Expanded(child: Text(_label(value))),
child: Text(_label(value)), if (value == mode) const Icon(Icons.check),
],
), ),
], ),
cancelButton: CupertinoActionSheetAction( ],
onPressed: () => Navigator.pop(context), ),
child: const Text('Cancel'), );
),
),
);
} else {
choice = await showDialog<ChatSidebarMode>(
context: context,
builder: (context) => SimpleDialog(
title: const Text('Chat list'),
children: [
for (final value in ChatSidebarMode.values)
SimpleDialogOption(
onPressed: () => Navigator.pop(context, value),
child: Row(
children: [
Expanded(child: Text(_label(value))),
if (value == mode) const Icon(Icons.check),
],
),
),
],
),
);
}
if (choice != null && context.mounted) onChanged(choice); if (choice != null && context.mounted) onChanged(choice);
} }
@@ -80,20 +57,9 @@ class ChatSidebarButton extends StatelessWidget
ChatSidebarMode.hidden => 'Hide chat list', ChatSidebarMode.hidden => 'Hide chat list',
}; };
@override @override
Widget build(BuildContext context) => Widget build(BuildContext context) => IconButton(
chatControlsStyleOf(context) == ChatControlsStyle.cupertino tooltip: 'Chat list layout',
? Semantics( onPressed: () => _choose(context),
label: 'Chat list layout', icon: const Icon(Icons.view_sidebar_outlined),
button: true, );
child: CupertinoButton(
padding: EdgeInsets.zero,
onPressed: () => _choose(context),
child: const Icon(CupertinoIcons.sidebar_left),
),
)
: IconButton(
tooltip: 'Chat list layout',
onPressed: () => _choose(context),
icon: const Icon(Icons.view_sidebar_outlined),
);
} }
@@ -1,4 +1,3 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart'; import '../../../core/api_gateway.dart';
@@ -28,7 +27,7 @@ class ChatTaskMetadataView extends StatelessWidget {
final facts = <Widget>[ final facts = <Widget>[
if (!detail) if (!detail)
ChatTaskFact( ChatTaskFact(
icon: taskCupertino(context) ? CupertinoIcons.clock : Icons.schedule, icon: Icons.schedule,
label: 'Started', label: 'Started',
value: start == null value: start == null
? 'Start time unavailable' ? 'Start time unavailable'
@@ -36,49 +35,37 @@ class ChatTaskMetadataView extends StatelessWidget {
), ),
if (!detail && start != null && start.isAfter(now)) if (!detail && start != null && start.isAfter(now))
ChatTaskFact( ChatTaskFact(
icon: taskCupertino(context) icon: Icons.info_outline,
? CupertinoIcons.exclamationmark_circle
: Icons.info_outline,
label: 'Device clock', label: 'Device clock',
value: 'Start time is ahead of this device’s clock', value: 'Start time is ahead of this device’s clock',
), ),
if (!detail && start == null && duration != null) if (!detail && start == null && duration != null)
ChatTaskFact( ChatTaskFact(
icon: taskCupertino(context) icon: Icons.timer_outlined,
? CupertinoIcons.timer
: Icons.timer_outlined,
label: 'Reported runtime', label: 'Reported runtime',
value: taskDuration(Duration(milliseconds: duration)), value: taskDuration(Duration(milliseconds: duration)),
), ),
if (!detail && tools != null) if (!detail && tools != null)
ChatTaskFact( ChatTaskFact(
icon: taskCupertino(context) icon: Icons.build_outlined,
? CupertinoIcons.wrench
: Icons.build_outlined,
label: 'Tool calls', label: 'Tool calls',
value: formatTaskCount(tools), value: formatTaskCount(tools),
), ),
if (!detail && tokens != null) if (!detail && tokens != null)
ChatTaskFact( ChatTaskFact(
icon: taskCupertino(context) icon: Icons.token_outlined,
? CupertinoIcons.number
: Icons.token_outlined,
label: 'Tokens', label: 'Tokens',
value: formatTaskCount(tokens), value: formatTaskCount(tokens),
), ),
if (detail && lastTool != null) if (detail && lastTool != null)
ChatTaskFact( ChatTaskFact(
icon: taskCupertino(context) icon: Icons.build_outlined,
? CupertinoIcons.wrench
: Icons.build_outlined,
label: 'Last tool', label: 'Last tool',
value: lastTool, value: lastTool,
), ),
if (detail && updated != null) if (detail && updated != null)
ChatTaskFact( ChatTaskFact(
icon: taskCupertino(context) icon: Icons.update,
? CupertinoIcons.arrow_clockwise
: Icons.update,
label: 'Last update', label: 'Last update',
value: formatTaskDate(context, updated), value: formatTaskDate(context, updated),
), ),
@@ -1,22 +1,17 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../domain/chat_task_metadata.dart'; import '../domain/chat_task_metadata.dart';
import '../../../ui/text/monospace.dart'; import '../../../ui/text/monospace.dart';
import '../ui/sessions/chat_adaptive.dart';
bool taskCupertino(BuildContext context) => /// Always false: the app is Material-only. Kept so existing callers compile;
chatControlsStyleOf(context) == ChatControlsStyle.cupertino; /// a later run removes it with its callers.
bool taskCupertino(BuildContext context) => false;
Color taskSecondary(BuildContext context) => taskCupertino(context) Color taskSecondary(BuildContext context) =>
? CupertinoColors.secondaryLabel.resolveFrom(context) Theme.of(context).colorScheme.onSurfaceVariant;
: Theme.of(context).colorScheme.onSurfaceVariant;
TextStyle taskHeading(BuildContext context) => taskCupertino(context) TextStyle taskHeading(BuildContext context) =>
? CupertinoTheme.of( Theme.of(context).textTheme.titleMedium ?? const TextStyle();
context,
).textTheme.textStyle.copyWith(fontWeight: FontWeight.w600)
: Theme.of(context).textTheme.titleMedium ?? const TextStyle();
String taskDisplayTitle(Map<String, dynamic> shell) => String taskDisplayTitle(Map<String, dynamic> shell) =>
taskText(shell, 'description') ?? taskText(shell, 'description') ??
@@ -65,12 +60,11 @@ String formatTaskDate(BuildContext context, DateTime time) {
MaterialLocalizations, MaterialLocalizations,
); );
final monthYear = final monthYear =
material?.formatMonthYear(time) ?? material?.formatMonthYear(time) ?? '${time.month}/${time.year}';
'${CupertinoLocalizations.of(context).datePickerMonth(time.month)} ${time.year}';
return '${time.day} $monthYear · ${time.hour.toString().padLeft(2, '0')}:${time.minute.toString().padLeft(2, '0')}'; return '${time.day} $monthYear · ${time.hour.toString().padLeft(2, '0')}:${time.minute.toString().padLeft(2, '0')}';
} }
/// Native grouped surface; callers supply content that grows with text scaling. /// A Material filled card; callers supply content that grows with text scaling.
class ChatTaskSurface extends StatelessWidget { class ChatTaskSurface extends StatelessWidget {
const ChatTaskSurface({ const ChatTaskSurface({
super.key, super.key,
@@ -81,16 +75,10 @@ class ChatTaskSurface extends StatelessWidget {
final EdgeInsetsGeometry padding; final EdgeInsetsGeometry padding;
@override @override
Widget build(BuildContext context) => taskCupertino(context) Widget build(BuildContext context) => Card.filled(
? CupertinoListSection.insetGrouped( margin: EdgeInsets.zero,
margin: EdgeInsets.zero, child: Padding(padding: padding, child: child),
backgroundColor: CupertinoColors.transparent, );
children: [Padding(padding: padding, child: child)],
)
: Card.filled(
margin: EdgeInsets.zero,
child: Padding(padding: padding, child: child),
);
} }
class ChatTaskFact extends StatelessWidget { class ChatTaskFact extends StatelessWidget {
@@ -1,10 +1,8 @@
import '../../../core/servers/server_context.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../../../core/servers/server_context.dart';
import '../../../ui/adaptive/segmented_bar.dart'; import '../../../ui/adaptive/segmented_bar.dart';
import '../../../ui/adaptive/segmented_bar_overflow.dart'; import '../../../ui/adaptive/segmented_bar_overflow.dart';
import '../ui/sessions/chat_adaptive.dart';
import 'chat_bar_tint.dart'; import 'chat_bar_tint.dart';
import '../workspace/chat_workspace_pane_scope.dart'; import '../workspace/chat_workspace_pane_scope.dart';
@@ -60,8 +58,6 @@ class ChatThreadHeader extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final tint = chatBarTintOf(context, chatColor); final tint = chatBarTintOf(context, chatColor);
return LayoutBuilder( return LayoutBuilder(
builder: (context, constraints) { builder: (context, constraints) {
@@ -73,7 +69,7 @@ class ChatThreadHeader extends StatelessWidget {
if (action is! SegmentedOverflowable) action, if (action is! SegmentedOverflowable) action,
if (moreActions.whereType<SegmentedOverflowable>().isNotEmpty) if (moreActions.whereType<SegmentedOverflowable>().isNotEmpty)
SegmentedMoreButton( SegmentedMoreButton(
cupertino: cupertino, cupertino: false,
entries: [ entries: [
for (final action for (final action
in moreActions.whereType<SegmentedOverflowable>()) in moreActions.whereType<SegmentedOverflowable>())
@@ -82,7 +78,7 @@ class ChatThreadHeader extends StatelessWidget {
), ),
]; ];
final Widget bar = SegmentedBar( final Widget bar = SegmentedBar(
cupertino: cupertino, cupertino: false,
pillColor: tint?.fill, pillColor: tint?.fill,
foregroundColor: tint?.foreground, foregroundColor: tint?.foreground,
automaticallyImplyLeading: false, automaticallyImplyLeading: false,
@@ -91,16 +87,14 @@ class ChatThreadHeader extends StatelessWidget {
leading: showBack leading: showBack
? SegmentedBackButton( ? SegmentedBackButton(
key: const Key('chat-back'), key: const Key('chat-back'),
cupertino: cupertino, cupertino: false,
onPressed: onBack, onPressed: onBack,
) )
: null, : null,
title: title.isEmpty ? 'Chat' : title, title: title.isEmpty ? 'Chat' : title,
titleLeading: identity, titleLeading: identity,
subtitle: ServerContext.metadata(context, folder), subtitle: ServerContext.metadata(context, folder),
subtitleIcon: cupertino subtitleIcon: Icons.folder_outlined,
? CupertinoIcons.folder
: Icons.folder_outlined,
onTitlePressed: onInfo, onTitlePressed: onInfo,
titleSemanticLabel: 'Chat information', titleSemanticLabel: 'Chat information',
titleKey: const Key('chat-info'), titleKey: const Key('chat-info'),
@@ -131,15 +125,13 @@ class ChatThreadHeader extends StatelessWidget {
bottomPadding: compact ? 8 : 16, bottomPadding: compact ? 8 : 16,
); );
return ColoredBox( return ColoredBox(
color: cupertino color: Theme.of(context).colorScheme.surface,
? CupertinoTheme.of(context).scaffoldBackgroundColor
: Theme.of(context).colorScheme.surface,
child: tint == null child: tint == null
? bar ? bar
: ChatBarTintScope( : ChatBarTintScope(
key: const Key('chat-bar-tint'), key: const Key('chat-bar-tint'),
tint: tint, tint: tint,
cupertino: cupertino, cupertino: false,
child: bar, child: bar,
), ),
); );
@@ -21,10 +21,10 @@ import '../../../core/transport/pipelines_client.dart'
import '../domain/chat_shown_items.dart'; import '../domain/chat_shown_items.dart';
import '../domain/chat_transcript.dart'; import '../domain/chat_transcript.dart';
import '../domain/chat_turn_diffs.dart'; import '../domain/chat_turn_diffs.dart';
import '../ui/sessions/chat_adaptive.dart';
import '../ui/sessions/chat_color_picker.dart'; import '../ui/sessions/chat_color_picker.dart';
import '../ui/sessions/session_actions.dart'; import '../ui/sessions/session_actions.dart';
import '../ui/sessions/session_row_content.dart'; import '../ui/sessions/session_row_content.dart';
import '../ui/sessions/chat_adaptive.dart';
import '../ui/transcript/chat_markdown_view.dart'; import '../ui/transcript/chat_markdown_view.dart';
import '../ui/transcript/chat_message_bubble.dart'; import '../ui/transcript/chat_message_bubble.dart';
import '../ui/transcript/chat_message_view.dart'; import '../ui/transcript/chat_message_view.dart';
@@ -300,8 +300,6 @@ class _ChatThreadViewState extends State<ChatThreadView> {
return; return;
} }
_filesSheetOpen = true; _filesSheetOpen = true;
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
// In a floating window the explorer is a page of that window, so a file // In a floating window the explorer is a page of that window, so a file
// it opens stays in the window too. // it opens stays in the window too.
final sheet = WindowScope.maybeOf(context) != null final sheet = WindowScope.maybeOf(context) != null
@@ -313,21 +311,6 @@ class _ChatThreadViewState extends State<ChatThreadView> {
), ),
), ),
) )
: cupertino
? showCupertinoModalPopup<void>(
context: context,
builder: (_) => Align(
alignment: Alignment.bottomCenter,
child: SafeArea(
child: CupertinoPopupSurface(
child: SizedBox(
height: MediaQuery.sizeOf(context).height * .85,
child: FilesPanel(controller: _files),
),
),
),
),
)
: showModalBottomSheet<void>( : showModalBottomSheet<void>(
context: context, context: context,
isScrollControlled: true, isScrollControlled: true,
@@ -999,8 +982,6 @@ class _ChatThreadViewState extends State<ChatThreadView> {
_shellRuns.membership, _shellRuns.membership,
]), ]),
builder: (context, _) { builder: (context, _) {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final messages = _visibleMessages(); final messages = _visibleMessages();
final cards = chatCardRows( final cards = chatCardRows(
permissions: _controller.permissionFrames, permissions: _controller.permissionFrames,
@@ -1209,10 +1190,8 @@ class _ChatThreadViewState extends State<ChatThreadView> {
Padding( Padding(
key: const Key('chat-thread-loading'), key: const Key('chat-thread-loading'),
padding: const EdgeInsets.all(16), padding: const EdgeInsets.all(16),
child: Center( child: const Center(
child: cupertino child: CircularProgressIndicator(),
? const CupertinoActivityIndicator()
: const CircularProgressIndicator(),
), ),
), ),
if (_controller.hasMore) if (_controller.hasMore)
@@ -1223,20 +1202,12 @@ class _ChatThreadViewState extends State<ChatThreadView> {
), ),
child: Align( child: Align(
alignment: AlignmentDirectional.centerStart, alignment: AlignmentDirectional.centerStart,
child: cupertino child: TextButton(
? CupertinoButton( onPressed: _controller.loading
padding: EdgeInsets.zero, ? null
onPressed: _controller.loading : _controller.loadOlder,
? null child: const Text('Load older'),
: _controller.loadOlder, ),
child: const Text('Load older'),
)
: TextButton(
onPressed: _controller.loading
? null
: _controller.loadOlder,
child: const Text('Load older'),
),
), ),
), ),
if (historyNotice != null) if (historyNotice != null)
@@ -1276,7 +1247,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
padding: const EdgeInsets.symmetric( padding: const EdgeInsets.symmetric(
horizontal: 16, horizontal: 16,
), ),
child: _queuedRow(prompt, cupertino), child: _queuedRow(prompt),
), ),
// Messages the server has not accepted follow the // Messages the server has not accepted follow the
// transcript until they are retried or edited. // transcript until they are retried or edited.
@@ -1288,7 +1259,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
padding: const EdgeInsets.symmetric( padding: const EdgeInsets.symmetric(
horizontal: 16, horizontal: 16,
), ),
child: _unsentRow(send, cupertino), child: _unsentRow(send),
), ),
// The conversation's own command lines sit after the // The conversation's own command lines sit after the
// turns, as on the web; they are never bubbles. // turns, as on the web; they are never bubbles.
@@ -1310,7 +1281,6 @@ class _ChatThreadViewState extends State<ChatThreadView> {
child: _ChatJumpToLatest( child: _ChatJumpToLatest(
key: const Key('chat-jump-to-latest'), key: const Key('chat-jump-to-latest'),
label: chatJumpToLatestLabel(newMessages), label: chatJumpToLatestLabel(newMessages),
cupertino: cupertino,
onPressed: _followLatest, onPressed: _followLatest,
), ),
), ),
@@ -1487,7 +1457,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
runChatShellFromMenu( runChatShellFromMenu(
context, context,
_shellRuns, _shellRuns,
cupertino: chatControlsStyleOf(context) == ChatControlsStyle.cupertino, cupertino: false,
showNotice: _showCommandNotice, showNotice: _showCommandNotice,
), ),
); );
@@ -1497,7 +1467,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
context, context,
_shellRuns, _shellRuns,
_shellRuns.finishedIds, _shellRuns.finishedIds,
cupertino: chatControlsStyleOf(context) == ChatControlsStyle.cupertino, cupertino: false,
onRefused: (refusal) => _showCommandNotice( onRefused: (refusal) => _showCommandNotice(
"Couldn't dismiss the commands: $refusal", "Couldn't dismiss the commands: $refusal",
failed: true, failed: true,
@@ -1612,8 +1582,6 @@ class _ChatThreadViewState extends State<ChatThreadView> {
final delivery = message != null final delivery = message != null
? _composer.deliveries.stateFor(message) ? _composer.deliveries.stateFor(message)
: null; : null;
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final onRemove = _removeAction('${message?['operation_id'] ?? ''}'); final onRemove = _removeAction('${message?['operation_id'] ?? ''}');
// An unchanged finished row hands back its previous widget, so a streamed // An unchanged finished row hands back its previous widget, so a streamed
// delta rebuilds only the live turn. Transcript snapshots are copied on // delta rebuilds only the live turn. Transcript snapshots are copied on
@@ -1623,15 +1591,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
return _rowWidgets.widgetFor( return _rowWidgets.widgetFor(
key, key,
row, row,
[ [delivery, onRemove != null, _images, _controller, _composer, _shellRuns],
delivery,
cupertino,
onRemove != null,
_images,
_controller,
_composer,
_shellRuns,
],
() => ChatMessageView( () => ChatMessageView(
row: row, row: row,
textBuilder: chatMarkdownText, textBuilder: chatMarkdownText,
@@ -1640,7 +1600,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
if (delivery != null) if (delivery != null)
ChatDeliveryIndicator( ChatDeliveryIndicator(
state: delivery, state: delivery,
cupertino: cupertino, cupertino: false,
onRemove: onRemove, onRemove: onRemove,
), ),
], ],
@@ -1671,7 +1631,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
/// One prompt the server holds queued that the transcript does not show, /// One prompt the server holds queued that the transcript does not show,
/// as the sender's bubble with "Queued" and its Remove. /// as the sender's bubble with "Queued" and its Remove.
Widget _queuedRow(JsonMap prompt, bool cupertino) { Widget _queuedRow(JsonMap prompt) {
final message = ChatServerQueue.message(prompt); final message = ChatServerQueue.message(prompt);
return ChatMessageView( return ChatMessageView(
row: {'kind': 'user', 'key': message['id'], 'message': message}, row: {'kind': 'user', 'key': message['id'], 'message': message},
@@ -1680,7 +1640,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
footer: [ footer: [
ChatDeliveryIndicator( ChatDeliveryIndicator(
state: ChatDelivery.queued, state: ChatDelivery.queued,
cupertino: cupertino, cupertino: false,
onRemove: _removeAction('${prompt['operation_id'] ?? ''}'), onRemove: _removeAction('${prompt['operation_id'] ?? ''}'),
), ),
], ],
@@ -1689,7 +1649,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
/// One message the server has not accepted, as the operator's bubble with /// One message the server has not accepted, as the operator's bubble with
/// "Not sent" and its Retry and Edit. /// "Not sent" and its Retry and Edit.
Widget _unsentRow(ChatComposerSend send, bool cupertino) { Widget _unsentRow(ChatComposerSend send) {
final composer = _composer; final composer = _composer;
return ChatMessageView( return ChatMessageView(
row: { row: {
@@ -1702,7 +1662,7 @@ class _ChatThreadViewState extends State<ChatThreadView> {
footer: [ footer: [
ChatDeliveryIndicator( ChatDeliveryIndicator(
state: ChatDelivery.failed, state: ChatDelivery.failed,
cupertino: cupertino, cupertino: false,
onRetry: send.canRetry && !composer.sending onRetry: send.canRetry && !composer.sending
? () => unawaited(composer.retry(send.operationId)) ? () => unawaited(composer.retry(send.operationId))
: null, : null,
@@ -1722,38 +1682,17 @@ class _ChatThreadViewState extends State<ChatThreadView> {
} }
/// The native dismiss control shared by a local notice and a running /// The native dismiss control shared by a local notice and a running
/// compaction's activity line. Material uses a tooltip; Cupertino carries the /// compaction's activity line: an icon button whose tooltip is its label.
/// same accessible name on the wrapping node, since its button has none.
Widget _noticeDismissControl({ Widget _noticeDismissControl({
required bool cupertino,
required String label, required String label,
required Key key, required Key key,
required VoidCallback onPressed, required VoidCallback onPressed,
}) { }) => IconButton(
final icon = Icon(cupertino ? CupertinoIcons.xmark_circle_fill : Icons.close); key: key,
if (!cupertino) { tooltip: label,
return IconButton( onPressed: onPressed,
key: key, icon: const Icon(Icons.close),
tooltip: label, );
onPressed: onPressed,
icon: icon,
);
}
return Semantics(
container: true,
button: true,
label: label,
onTap: onPressed,
child: ExcludeSemantics(
child: CupertinoButton(
key: key,
padding: EdgeInsets.zero,
onPressed: onPressed,
child: icon,
),
),
);
}
/// One local notice beside the conversation: a recorded failure or a slash /// One local notice beside the conversation: a recorded failure or a slash
/// command's outcome. /// command's outcome.
@@ -1777,27 +1716,13 @@ class _ChatNoticeLine extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final theme = Theme.of(context); final theme = Theme.of(context);
final failed = notice.failed; final failed = notice.failed;
final color = failed final color = failed
? (cupertino ? theme.colorScheme.error
? CupertinoColors.systemRed.resolveFrom(context) : theme.colorScheme.onSurfaceVariant;
: theme.colorScheme.error) final style = theme.textTheme.bodyMedium?.copyWith(color: color);
: (cupertino final icon = failed ? Icons.error_outline : Icons.info_outline;
? CupertinoColors.secondaryLabel.resolveFrom(context)
: theme.colorScheme.onSurfaceVariant);
final style =
(cupertino
? CupertinoTheme.of(context).textTheme.textStyle
: theme.textTheme.bodyMedium)
?.copyWith(color: color);
final icon = failed
? (cupertino
? CupertinoIcons.exclamationmark_circle
: Icons.error_outline)
: (cupertino ? CupertinoIcons.info_circle : Icons.info_outline);
return Padding( return Padding(
padding: const EdgeInsetsDirectional.fromSTEB(16, 4, 8, 4), padding: const EdgeInsetsDirectional.fromSTEB(16, 4, 8, 4),
child: Column( child: Column(
@@ -1820,33 +1745,24 @@ class _ChatNoticeLine extends StatelessWidget {
), ),
), ),
), ),
_dismissControl(cupertino), _dismissControl(),
], ],
), ),
if (onRetry != null) if (onRetry != null)
Align( Align(
alignment: AlignmentDirectional.centerStart, alignment: AlignmentDirectional.centerStart,
child: cupertino child: TextButton(onPressed: onRetry, child: const Text('Retry')),
? CupertinoButton(
padding: EdgeInsets.zero,
onPressed: onRetry,
child: const Text('Retry'),
)
: TextButton(onPressed: onRetry, child: const Text('Retry')),
), ),
], ],
), ),
); );
} }
Widget _dismissControl(bool cupertino) { Widget _dismissControl() => _noticeDismissControl(
return _noticeDismissControl( label: chatNoticeDismissLabel(notice.kind),
cupertino: cupertino, key: ValueKey<String>('chat-notice-dismiss-${notice.kind.name}'),
label: chatNoticeDismissLabel(notice.kind), onPressed: () => onDismiss(notice),
key: ValueKey<String>('chat-notice-dismiss-${notice.kind.name}'), );
onPressed: () => onDismiss(notice),
);
}
} }
/// One reported usage metric: its web label, whether the harness reported it, /// One reported usage metric: its web label, whether the harness reported it,
@@ -1966,8 +1882,6 @@ class _ChatInfoSheet extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
return AnimatedBuilder( return AnimatedBuilder(
animation: controller, animation: controller,
builder: (context, _) { builder: (context, _) {
@@ -1978,76 +1892,53 @@ class _ChatInfoSheet extends StatelessWidget {
children: [ children: [
AppSheetHeader( AppSheetHeader(
title: 'Chat information', title: 'Chat information',
cupertino: cupertino, cupertino: false,
doneKey: const Key('chat-info-close'), doneKey: const Key('chat-info-close'),
), ),
if (onColorSelected case final onSelected?) if (onColorSelected case final onSelected?)
ChatColorSection(selected: color, onSelected: onSelected), ChatColorSection(selected: color, onSelected: onSelected),
for (final metric in _chatInfoMetrics(controller.usage)) for (final metric in _chatInfoMetrics(controller.usage))
_ChatInfoRow(metric: metric, cupertino: cupertino), _ChatInfoRow(metric: metric),
ChatAccountUsageSection( ChatAccountUsageSection(
usage: controller.accountUsage, usage: controller.accountUsage,
cupertino: cupertino, cupertino: false,
), ),
Padding( Padding(
padding: const EdgeInsetsDirectional.fromSTEB(24, 8, 24, 16), padding: const EdgeInsetsDirectional.fromSTEB(24, 8, 24, 16),
child: Text( child: Text(
'Last reported by the harness. ' 'Last reported by the harness. '
'Unavailable values are not estimated.', 'Unavailable values are not estimated.',
style: style: Theme.of(context).textTheme.bodySmall?.copyWith(
(cupertino color: Theme.of(context).colorScheme.onSurfaceVariant,
? CupertinoTheme.of(context).textTheme.textStyle ),
: Theme.of(context).textTheme.bodySmall)
?.copyWith(
color: cupertino
? CupertinoColors.secondaryLabel.resolveFrom(
context,
)
: Theme.of(context).colorScheme.onSurfaceVariant,
),
), ),
), ),
ChatSessionSection( ChatSessionSection(
handoff: handoff, handoff: handoff,
exporter: exporter, exporter: exporter,
cupertino: cupertino, cupertino: false,
), ),
const SizedBox(height: 12), const SizedBox(height: 12),
], ],
); );
if (!cupertino) return SingleChildScrollView(child: content); 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 { class _ChatInfoRow extends StatelessWidget {
const _ChatInfoRow({required this.metric, required this.cupertino}); const _ChatInfoRow({required this.metric});
final _ChatInfoMetric metric; final _ChatInfoMetric metric;
final bool cupertino;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final secondary = cupertino final secondary = Theme.of(context).colorScheme.onSurfaceVariant;
? CupertinoColors.secondaryLabel.resolveFrom(context) final labelStyle = Theme.of(
: Theme.of(context).colorScheme.onSurfaceVariant; context,
final labelStyle = ).textTheme.bodySmall?.copyWith(color: secondary);
(cupertino final valueStyle = Theme.of(context).textTheme.bodyLarge;
? 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( return Padding(
key: Key('chat-info-metric-${metric.key}'), key: Key('chat-info-metric-${metric.key}'),
padding: const EdgeInsetsDirectional.fromSTEB(24, 6, 24, 6), padding: const EdgeInsetsDirectional.fromSTEB(24, 6, 24, 6),
@@ -2075,37 +1966,19 @@ class _ChatJumpToLatest extends StatelessWidget {
const _ChatJumpToLatest({ const _ChatJumpToLatest({
super.key, super.key,
required this.label, required this.label,
required this.cupertino,
required this.onPressed, required this.onPressed,
}); });
final String label; final String label;
final bool cupertino;
final VoidCallback onPressed; final VoidCallback onPressed;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final button = cupertino final button = FilledButton.tonalIcon(
? CupertinoButton.filled( onPressed: onPressed,
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), icon: const Icon(Icons.arrow_downward),
onPressed: onPressed, label: Text(label, textAlign: TextAlign.center),
child: Row( );
mainAxisSize: MainAxisSize.min,
children: [
Icon(
CupertinoIcons.arrow_down,
color: CupertinoTheme.of(context).primaryContrastingColor,
),
const SizedBox(width: 8),
Flexible(child: Text(label, textAlign: TextAlign.center)),
],
),
)
: FilledButton.tonalIcon(
onPressed: onPressed,
icon: const Icon(Icons.arrow_downward),
label: Text(label, textAlign: TextAlign.center),
);
// A long count at a large text scale wraps inside the pane instead of // A long count at a large text scale wraps inside the pane instead of
// pushing the control past the transcript's edge. // pushing the control past the transcript's edge.
return ConstrainedBox( return ConstrainedBox(
@@ -2157,35 +2030,21 @@ class _ChatActivityLineState extends State<_ChatActivityLine> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final state = '${widget.row['state'] ?? ''}'.trim().toLowerCase(); final state = '${widget.row['state'] ?? ''}'.trim().toLowerCase();
final failed = state == 'failed' || state == 'error'; final failed = state == 'failed' || state == 'error';
final running = state == 'running'; final running = state == 'running';
final completed = final completed =
state == 'completed' || state == 'ended' || state == 'succeeded'; state == 'completed' || state == 'ended' || state == 'succeeded';
final secondary = _secondary(context, cupertino); final secondary = Theme.of(context).colorScheme.onSurfaceVariant;
final color = failed final color = failed ? Theme.of(context).colorScheme.error : secondary;
? (cupertino final style = Theme.of(context).textTheme.bodySmall?.copyWith(color: color);
? CupertinoColors.systemRed.resolveFrom(context)
: Theme.of(context).colorScheme.error)
: secondary;
final style =
(cupertino
? CupertinoTheme.of(context).textTheme.textStyle
: Theme.of(context).textTheme.bodySmall)
?.copyWith(color: color);
final icon = failed final icon = failed
? (cupertino ? Icons.error_outline
? CupertinoIcons.exclamationmark_circle
: Icons.error_outline)
: running : running
? (cupertino ? CupertinoIcons.arrow_2_circlepath : Icons.sync) ? Icons.sync
: completed : completed
? (cupertino ? Icons.check_circle_outline
? CupertinoIcons.check_mark_circled : Icons.circle_outlined;
: Icons.check_circle_outline)
: (cupertino ? CupertinoIcons.circle : Icons.circle_outlined);
final label = '${widget.row['label'] ?? ''}'.trim(); final label = '${widget.row['label'] ?? ''}'.trim();
return Padding( return Padding(
padding: const EdgeInsets.symmetric(vertical: 6), padding: const EdgeInsets.symmetric(vertical: 6),
@@ -2213,65 +2072,39 @@ class _ChatActivityLineState extends State<_ChatActivityLine> {
), ),
), ),
), ),
_toggleControl(cupertino), _toggleControl(),
if (widget.onDismiss != null) if (widget.onDismiss != null)
_noticeDismissControl( _noticeDismissControl(
cupertino: cupertino,
label: chatNoticeDismissLabel(ChatNoticeKind.compaction), label: chatNoticeDismissLabel(ChatNoticeKind.compaction),
key: const ValueKey<String>('chat-notice-dismiss-compaction'), key: const ValueKey<String>('chat-notice-dismiss-compaction'),
onPressed: widget.onDismiss!, onPressed: widget.onDismiss!,
), ),
], ],
), ),
if (_expanded) _detail(context, cupertino, secondary), if (_expanded) _detail(context, secondary),
], ],
), ),
); );
} }
/// The host's own disclosure control, with an action label that states what a /// The disclosure control, with an action label that states what a tap does.
/// tap does. Cupertino's button has no built-in label, so the wrapping node Widget _toggleControl() {
/// carries it and the button keeps the pointer handling.
Widget _toggleControl(bool cupertino) {
const key = ValueKey<String>('chat-activity-toggle'); const key = ValueKey<String>('chat-activity-toggle');
final label = _expanded ? 'Collapse activity' : 'Expand activity'; final label = _expanded ? 'Collapse activity' : 'Expand activity';
final icon = Icon( return IconButton(
_expanded key: key,
? (cupertino ? CupertinoIcons.chevron_up : Icons.expand_less) tooltip: label,
: (cupertino ? CupertinoIcons.chevron_down : Icons.expand_more), onPressed: _toggle,
); icon: Icon(_expanded ? Icons.expand_less : Icons.expand_more),
if (!cupertino) {
return IconButton(
key: key,
tooltip: label,
onPressed: _toggle,
icon: icon,
);
}
return Semantics(
container: true,
button: true,
label: label,
onTap: _toggle,
child: ExcludeSemantics(
child: CupertinoButton(
key: key,
padding: EdgeInsets.zero,
onPressed: _toggle,
child: icon,
),
),
); );
} }
/// The expanded section: every recorded field, with the exact absence sentence /// The expanded section: every recorded field, with the exact absence sentence
/// for one the record did not carry. Only [ChatActivityDetail] reads the /// for one the record did not carry. Only [ChatActivityDetail] reads the
/// record, so the line and its details cannot disagree about a field. /// record, so the line and its details cannot disagree about a field.
Widget _detail(BuildContext context, bool cupertino, Color secondary) { Widget _detail(BuildContext context, Color secondary) {
final detail = chatActivityDetail(_record()); final detail = chatActivityDetail(_record());
final baseStyle = cupertino final baseStyle = Theme.of(context).textTheme.bodyMedium;
? CupertinoTheme.of(context).textTheme.textStyle
: Theme.of(context).textTheme.bodyMedium;
final labelStyle = TextStyle(color: secondary, fontWeight: FontWeight.w600); final labelStyle = TextStyle(color: secondary, fontWeight: FontWeight.w600);
Widget field(String label, String value) { Widget field(String label, String value) {
final absent = final absent =
@@ -2315,8 +2148,4 @@ class _ChatActivityLineState extends State<_ChatActivityLine> {
), ),
); );
} }
Color _secondary(BuildContext context, bool cupertino) => cupertino
? CupertinoColors.secondaryLabel.resolveFrom(context)
: Theme.of(context).colorScheme.onSurfaceVariant;
} }
+100 -109
View File
@@ -226,124 +226,115 @@ Future<void> replyChatHistory(
} }
void main() { void main() {
for (final cupertino in [false, true]) { testWidgets(
testWidgets( 'a wide /chat/s1 deep link shows that thread beside the list and route Back returns to /chat',
'a wide /chat/s1 deep link shows that thread beside the list and route Back returns to /chat ($cupertino)', (tester) async {
(tester) async { tester.view.physicalSize = const Size(900, 900);
tester.view.physicalSize = const Size(900, 900); tester.view.devicePixelRatio = 1;
tester.view.devicePixelRatio = 1; addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetPhysicalSize); addTearDown(tester.view.resetDevicePixelRatio);
addTearDown(tester.view.resetDevicePixelRatio);
if (cupertino) {
tester.platformDispatcher.platformBrightnessTestValue =
Brightness.dark;
addTearDown(
tester.platformDispatcher.clearPlatformBrightnessTestValue,
);
}
final channel = FakeChannel()..readyCompleter.complete(); final channel = FakeChannel()..readyCompleter.complete();
final client = PipelinesClient(channelFactory: (_) => channel); final client = PipelinesClient(channelFactory: (_) => channel);
final provider = PlatformRouteInformationProvider( final provider = PlatformRouteInformationProvider(
initialRouteInformation: RouteInformation(uri: Uri.parse('/chat/s1')), initialRouteInformation: RouteInformation(uri: Uri.parse('/chat/s1')),
); );
addTearDown(provider.dispose); addTearDown(provider.dispose);
await tester.pumpWidget( await tester.pumpWidget(
PipelinesApp( PipelinesApp(
androidSupported: false, androidSupported: false,
server: webServer(), server: webServer(),
client: client, client: client,
cupertino: cupertino, cupertino: false,
routeInformationProvider: provider, routeInformationProvider: provider,
), ),
); );
await tester.pump(); await tester.pump();
await replySessions(tester, channel); await replySessions(tester, channel);
await replySubscribe(tester, channel); await replySubscribe(tester, channel);
await replyHistory(tester, channel); await replyHistory(tester, channel);
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(provider.value.uri.path, '/chat/s1'); expect(provider.value.uri.path, '/chat/s1');
expect(find.byType(ChatThreadView), findsOneWidget); expect(find.byType(ChatThreadView), findsOneWidget);
// The exact route names the session; the request carries the same id. // The exact route names the session; the request carries the same id.
expect(requestOf(channel, 'chat_subscribe')!['chat_subscribe'], { expect(requestOf(channel, 'chat_subscribe')!['chat_subscribe'], {
'session_id': 's1', 'session_id': 's1',
}); });
expect(requestOf(channel, 'chat_messages')!['chat_query'], { expect(requestOf(channel, 'chat_messages')!['chat_query'], {
'session_id': 's1', 'session_id': 's1',
'limit': 200, 'limit': 200,
'cursor': '', 'cursor': '',
}); });
expect(find.text('The stored reply stays readable.'), findsOneWidget); expect(find.text('The stored reply stays readable.'), findsOneWidget);
expect(find.text('Ran 1 command'), findsOneWidget); expect(find.text('Ran 1 command'), findsOneWidget);
expect(find.byKey(const Key('chat-turn-activity')), findsOneWidget); expect(find.byKey(const Key('chat-turn-activity')), findsOneWidget);
expect(find.text('Kept behind a native disclosure.'), findsNothing); expect(find.text('Kept behind a native disclosure.'), findsNothing);
// The shell bar stays over the list and tabs; the open chat draws its // The shell bar stays over the list and tabs; the open chat draws its
// own floating bar in its pane, with no Back: the list beside it is the // own floating bar in its pane, with no Back: the list beside it is the
// way out. // way out.
expect(find.byType(ChatSessionsScreen), findsOneWidget); expect(find.byType(ChatSessionsScreen), findsOneWidget);
expect(find.byType(NavigationRail), findsNothing); expect(find.byType(NavigationRail), findsNothing);
expect(find.byType(FloatingDestinationBar), findsOneWidget); expect(find.byType(FloatingDestinationBar), findsOneWidget);
// The shell's bar and the conversation's own header. // The shell's bar and the conversation's own header.
expect(find.byType(SegmentedBar), findsNWidgets(2)); expect(find.byType(SegmentedBar), findsNWidgets(2));
expect(find.byType(AppBar), findsNothing); expect(find.byType(AppBar), findsNothing);
expect(find.byType(CupertinoNavigationBar), findsNothing); expect(find.byType(CupertinoNavigationBar), findsNothing);
expect(find.byKey(const Key('chat-thread-header')), findsOneWidget); expect(find.byKey(const Key('chat-thread-header')), findsOneWidget);
expect(findNativeBack(), findsNothing); expect(findNativeBack(), findsNothing);
// A live frame updates the held thread. // A live frame updates the held thread.
channel.incoming.add( channel.incoming.add(
jsonEncode({ jsonEncode({
'type': 'chat_event', 'type': 'chat_event',
'chat_event': { 'chat_event': {
'session_id': 's1', 'session_id': 's1',
'message_id': 'a1', 'message_id': 'a1',
'kind': 'text', 'kind': 'text',
'part': {'id': 'p2', 'type': 'text'}, 'part': {'id': 'p2', 'type': 'text'},
'delta': 'A live line arrived.', 'delta': 'A live line arrived.',
}, },
}), }),
); );
await tester.pump(); await tester.pump();
await tester.pump(); await tester.pump();
expect(find.text('A live line arrived.'), findsOneWidget); expect(find.text('A live line arrived.'), findsOneWidget);
// The thread's own bar carries its controls once: no second bar. // The thread's own bar carries its controls once: no second bar.
expect(find.byKey(const Key('chat-thread-header')), findsOneWidget); expect(find.byKey(const Key('chat-thread-header')), findsOneWidget);
// Browser Back to /chat clears the open pane and keeps the list. // Browser Back to /chat clears the open pane and keeps the list.
await provider.didPushRouteInformation( await provider.didPushRouteInformation(
RouteInformation(uri: Uri.parse('/chat')), RouteInformation(uri: Uri.parse('/chat')),
); );
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(provider.value.uri.path, '/chat'); expect(provider.value.uri.path, '/chat');
expect(find.byType(ChatThreadView), findsNothing); expect(find.byType(ChatThreadView), findsNothing);
expect(find.byType(ChatSessionsScreen), findsOneWidget); expect(find.byType(ChatSessionsScreen), findsOneWidget);
expect(find.text('Wire chat'), findsOneWidget); expect(find.text('Wire chat'), findsOneWidget);
expect(find.text('Select a chat to open it here.'), findsOneWidget); expect(find.text('Select a chat to open it here.'), findsOneWidget);
// Browser Forward re-opens the same session through its route. // Browser Forward re-opens the same session through its route.
await provider.didPushRouteInformation( await provider.didPushRouteInformation(
RouteInformation(uri: Uri.parse('/chat/s1')), RouteInformation(uri: Uri.parse('/chat/s1')),
); );
await tester.pump(); await tester.pump();
expect(provider.value.uri.path, '/chat/s1'); expect(provider.value.uri.path, '/chat/s1');
await replySubscribe(tester, channel, index: 1); await replySubscribe(tester, channel, index: 1);
await replyHistory( await replyHistory(
tester, tester,
channel, channel,
index: 1, index: 1,
text: 'Reopened from the route.', text: 'Reopened from the route.',
); );
expect(find.text('Reopened from the route.'), findsOneWidget); expect(find.text('Reopened from the route.'), findsOneWidget);
await tester.pumpWidget(const SizedBox.shrink()); await tester.pumpWidget(const SizedBox.shrink());
await tester.pump(); await tester.pump();
}, },
); );
}
testWidgets( testWidgets(
'mobile Chats retap reopens the retained multi-pane workspace after tabs', 'mobile Chats retap reopens the retained multi-pane workspace after tabs',
@@ -64,7 +64,7 @@ Future<_Gateway> _pumpShell(
MaterialApp( MaterialApp(
theme: ThemeData(platform: platform, brightness: brightness), theme: ThemeData(platform: platform, brightness: brightness),
home: AdaptiveShell( home: AdaptiveShell(
cupertino: platform == TargetPlatform.iOS, cupertino: false,
destination: AppDestination.chat, destination: AppDestination.chat,
destinationBodies: { destinationBodies: {
AppDestination.chat: (_) => ChatScreen(gateway: gateway), AppDestination.chat: (_) => ChatScreen(gateway: gateway),
@@ -234,55 +234,50 @@ void main() {
await tester.pumpWidget(const SizedBox.shrink()); await tester.pumpWidget(const SizedBox.shrink());
}); });
for (final platform in [TargetPlatform.android, TargetPlatform.iOS]) { for (final brightness in Brightness.values) {
for (final brightness in Brightness.values) { final host = 'Material ${brightness.name}';
final host = testWidgets('$host: a coloured chat tints its bar, with no wash; the '
'${platform == TargetPlatform.iOS ? 'Cupertino' : 'Material'} ' 'info sheet changes the colour', (tester) async {
'${brightness.name}'; final gateway = await _pumpShell(
testWidgets('$host: a coloured chat tints its bar, with no wash; the ' tester,
'info sheet changes the colour', (tester) async { const Size(1280, 800),
final gateway = await _pumpShell( brightness: brightness,
tester, );
const Size(1280, 800), await _ctrl(tester, LogicalKeyboardKey.digit1);
platform: platform, expect(_thread('a'), findsOneWidget);
brightness: brightness, // The colour lives in the bar's pieces; the page has no wash.
); expect(find.byKey(const Key('chat-bar-tint')), findsOneWidget);
await _ctrl(tester, LogicalKeyboardKey.digit1); expect(find.byKey(const Key('chat-color-wash')), findsNothing);
expect(_thread('a'), findsOneWidget); expect(find.byKey(const Key('chat-color-wash-below')), findsNothing);
// The colour lives in the bar's pieces; the page has no wash. final tint = tester.widget<ChatBarTintScope>(
expect(find.byKey(const Key('chat-bar-tint')), findsOneWidget); find.byKey(const Key('chat-bar-tint')),
expect(find.byKey(const Key('chat-color-wash')), findsNothing); );
expect(find.byKey(const Key('chat-color-wash-below')), findsNothing); final pill = tester.widget<GlassPill>(
final tint = tester.widget<ChatBarTintScope>( find
find.byKey(const Key('chat-bar-tint')), .ancestor(
); of: find.byKey(const Key('chat-info')),
final pill = tester.widget<GlassPill>( matching: find.byType(GlassPill),
find )
.ancestor( .first,
of: find.byKey(const Key('chat-info')), );
matching: find.byType(GlassPill), expect(pill.fill, tint.tint.fill);
)
.first,
);
expect(pill.fill, tint.tint.fill);
// A plain chat keeps the neutral bar. // A plain chat keeps the neutral bar.
await _ctrl(tester, LogicalKeyboardKey.digit3); await _ctrl(tester, LogicalKeyboardKey.digit3);
expect(find.byKey(const Key('chat-bar-tint')), findsNothing); expect(find.byKey(const Key('chat-bar-tint')), findsNothing);
await tester.tap(find.byKey(const Key('chat-info'))); await tester.tap(find.byKey(const Key('chat-info')));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(find.byKey(const Key('chat-color-section')), findsOneWidget); expect(find.byKey(const Key('chat-color-section')), findsOneWidget);
await tester.tap(find.byKey(const Key('chat-color-blue'))); await tester.tap(find.byKey(const Key('chat-color-blue')));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(gateway.calls.last.fields, { expect(gateway.calls.last.fields, {
'chat_query': {'session_id': 'r', 'color': 'blue'}, 'chat_query': {'session_id': 'r', 'color': 'blue'},
});
await tester.tap(find.byKey(const Key('chat-info-close')));
await tester.pumpAndSettle();
expect(find.byKey(const Key('chat-bar-tint')), findsOneWidget);
await tester.pumpWidget(const SizedBox.shrink());
}); });
} await tester.tap(find.byKey(const Key('chat-info-close')));
await tester.pumpAndSettle();
expect(find.byKey(const Key('chat-bar-tint')), findsOneWidget);
await tester.pumpWidget(const SizedBox.shrink());
});
} }
} }
@@ -1,7 +1,6 @@
import 'dart:async'; import 'dart:async';
import 'dart:typed_data'; import 'dart:typed_data';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart'; import 'package:pipelines_app/core/api_gateway.dart';
@@ -31,9 +30,7 @@ class _FakePicker {
ChatPickedFile _file(String name, {int size = 3, String mime = 'text/plain'}) => ChatPickedFile _file(String name, {int size = 3, String mime = 'text/plain'}) =>
ChatPickedFile(name: name, mime: mime, bytes: Uint8List(size)); ChatPickedFile(name: name, mime: mime, bytes: Uint8List(size));
Widget _host(Widget bar, {required bool cupertino}) => cupertino Widget _host(Widget bar) => materialHost(bar);
? CupertinoApp(home: CupertinoPageScaffold(child: bar))
: materialHost(bar);
void main() { void main() {
late ComposerBarGateway gateway; late ComposerBarGateway gateway;
@@ -68,49 +65,37 @@ void main() {
Future<void> pumpBar( Future<void> pumpBar(
WidgetTester tester, { WidgetTester tester, {
ChatAttachmentPicker? picker, ChatAttachmentPicker? picker,
bool cupertino = false,
}) async { }) async {
newComposer(); newComposer();
await tester.pumpWidget( await tester.pumpWidget(
_host( _host(
ChatComposerBar(composer: composer, running: false, picker: picker), ChatComposerBar(composer: composer, running: false, picker: picker),
cupertino: cupertino,
), ),
); );
await tester.pump(); await tester.pump();
} }
for (final cupertino in [false, true]) { testWidgets('picking a file shows its recorded name and removes it', (
testWidgets('picking a file shows its recorded name and removes it ' tester,
'(${cupertino ? 'cupertino' : 'material'})', (tester) async { ) async {
final fake = _FakePicker([ final fake = _FakePicker([
[_file('notes.txt')], [_file('notes.txt')],
]); ]);
await pumpBar(tester, picker: fake.picker, cupertino: cupertino); await pumpBar(tester, picker: fake.picker);
await tester.tap(find.byKey(const Key('chat-composer-attach'))); await tester.tap(find.byKey(const Key('chat-composer-attach')));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(fake.calls, 1); expect(fake.calls, 1);
expect( expect(find.byKey(const Key('chat-composer-attachments')), findsOneWidget);
find.byKey(const Key('chat-composer-attachments')), expect(find.text('notes.txt'), findsOneWidget);
findsOneWidget,
);
expect(find.text('notes.txt'), findsOneWidget);
if (cupertino) { await tester.tap(find.byTooltip('Remove notes.txt'));
await tester.tap( await tester.pump();
find.byKey(const Key('chat-composer-attachment-remove-0')),
);
} else {
await tester.tap(find.byTooltip('Remove notes.txt'));
}
await tester.pump();
expect(find.text('notes.txt'), findsNothing); expect(find.text('notes.txt'), findsNothing);
expect(find.byKey(const Key('chat-composer-attachments')), findsNothing); expect(find.byKey(const Key('chat-composer-attachments')), findsNothing);
}); });
}
testWidgets('a file over the draft budget shows the draft refusal line', ( testWidgets('a file over the draft budget shows the draft refusal line', (
tester, tester,
@@ -218,32 +203,28 @@ void main() {
expect(attach.onPressed, isNull); expect(attach.onPressed, isNull);
}); });
for (final cupertino in [false, true]) { testWidgets('a long attachment name fits a narrow 2x composer', (
testWidgets('a long attachment name fits a narrow 2x composer ' tester,
'(${cupertino ? 'cupertino' : 'material'})', (tester) async { ) async {
tester.view.physicalSize = const Size(640, 1200); tester.view.physicalSize = const Size(640, 1200);
tester.view.devicePixelRatio = 2; tester.view.devicePixelRatio = 2;
tester.platformDispatcher.textScaleFactorTestValue = 2; tester.platformDispatcher.textScaleFactorTestValue = 2;
addTearDown(tester.view.resetPhysicalSize); addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio); addTearDown(tester.view.resetDevicePixelRatio);
addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue); addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
final name = final name =
'a-very-long-recorded-attachment-name-that-must-not-overflow.pdf'; 'a-very-long-recorded-attachment-name-that-must-not-overflow.pdf';
final fake = _FakePicker([ final fake = _FakePicker([
[_file(name)], [_file(name)],
]); ]);
await pumpBar(tester, picker: fake.picker, cupertino: cupertino); await pumpBar(tester, picker: fake.picker);
await tester.tap(find.byKey(const Key('chat-composer-attach'))); await tester.tap(find.byKey(const Key('chat-composer-attach')));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(tester.takeException(), isNull); expect(tester.takeException(), isNull);
expect(find.text(name), findsOneWidget); expect(find.text(name), findsOneWidget);
expect( expect(find.byKey(const Key('chat-composer-attachments')), findsOneWidget);
find.byKey(const Key('chat-composer-attachments')), });
findsOneWidget,
);
});
}
} }
@@ -1,4 +1,3 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart'; import 'package:pipelines_app/core/api_gateway.dart';
@@ -185,42 +184,4 @@ void main() {
expect(find.text('Thinking: Max'), findsOneWidget); expect(find.text('Thinking: Max'), findsOneWidget);
expect(changes.single.defaultEffort, 'max'); expect(changes.single.defaultEffort, 'max');
}); });
testWidgets('Cupertino uses an action sheet that reports a refusal', (
tester,
) async {
Widget app(ApiGateway gateway) => CupertinoApp(
home: CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
trailing: ChatEffortControl(
gateway: gateway,
sessionId: 's',
session: _row(),
),
),
child: const SizedBox.shrink(),
),
);
final refusing = _EffortGateway(refuse: 'level refused');
await tester.pumpWidget(app(refusing));
await tester.tap(find.byKey(const Key('chat-effort')));
await tester.pumpAndSettle();
expect(find.byType(CupertinoActionSheet), findsOneWidget);
await tester.tap(find.byKey(const ValueKey('chat-effort-option-low')));
await tester.pumpAndSettle();
expect(find.byType(CupertinoActionSheet), findsOneWidget);
expect(find.textContaining('level refused'), findsOneWidget);
final gateway = _EffortGateway();
await tester.pumpWidget(app(gateway));
await tester.pumpAndSettle();
await tester.tapAt(const Offset(10, 10));
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('chat-effort')));
await tester.pumpAndSettle();
await tester.tap(find.byKey(const ValueKey('chat-effort-option-xhigh')));
await tester.pumpAndSettle();
expect(find.byType(CupertinoActionSheet), findsNothing);
expect(gateway.requests.single['type'], 'chat_effort');
});
} }
@@ -1,6 +1,5 @@
import 'dart:async'; import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart'; import 'package:pipelines_app/core/api_gateway.dart';
@@ -19,16 +18,6 @@ Widget materialHost(Widget child) => MaterialApp(
Widget scrollHost(Widget child) => Widget scrollHost(Widget child) =>
materialHost(SingleChildScrollView(child: 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() => [ List<JsonMap> fields() => [
{ {
'key': 'colour', 'key': 'colour',
@@ -235,19 +224,6 @@ void main() {
expect(find.text('Send answer'), findsNothing); 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', ( testWidgets('a free-text input carries its visual label in semantics', (
tester, tester,
) async { ) async {
@@ -424,29 +400,6 @@ void main() {
expect(find.text('kept'), 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', ( testWidgets('a pushed form renders and sends one exact chat_answer', (
tester, tester,
) async { ) async {
@@ -1,4 +1,3 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/chat/conversation/chat_stop_icon.dart'; import 'package:pipelines_app/features/chat/conversation/chat_stop_icon.dart';
@@ -121,61 +120,55 @@ void main() {
await tester.pumpWidget(const SizedBox.shrink()); await tester.pumpWidget(const SizedBox.shrink());
}); });
for (final cupertino in [false, true]) { testWidgets(
testWidgets( 'rotating Stop keeps its target and interrupt action; Send stays available',
'rotating Stop keeps its target and interrupt action; Send stays available ($cupertino)', (tester) async {
(tester) async { final gateway = ComposerBarGateway();
final gateway = ComposerBarGateway(); addTearDown(gateway.close);
addTearDown(gateway.close); final composer = ChatComposerController(
final composer = ChatComposerController( gateway,
gateway, 's',
's', drafts: MemoryChatDraftStore(),
drafts: MemoryChatDraftStore(), );
); addTearDown(composer.dispose);
addTearDown(composer.dispose); final running = ValueNotifier<bool>(true);
final running = ValueNotifier<bool>(true); addTearDown(running.dispose);
addTearDown(running.dispose); final bar = ValueListenableBuilder<bool>(
final bar = ValueListenableBuilder<bool>( valueListenable: running,
valueListenable: running, builder: (_, value, _) =>
builder: (_, value, _) => ChatComposerBar(composer: composer, running: value),
ChatComposerBar(composer: composer, running: value), );
); await tester.pumpWidget(
await tester.pumpWidget( MaterialApp(
cupertino home: Scaffold(body: Center(child: bar)),
? CupertinoApp( ),
home: CupertinoPageScaffold(child: Center(child: bar)), );
) // The composer pops in first; Stop's target is measured once it has.
: MaterialApp( await tester.pump(Motion.tabEntranceDuration);
home: Scaffold(body: Center(child: bar)), final stop = find.byKey(const Key('chat-composer-stop'));
), final target = tester.getRect(stop);
); await tester.pump(const Duration(seconds: 3));
// The composer pops in first; Stop's target is measured once it has. expect(tester.getRect(stop), target);
await tester.pump(Motion.tabEntranceDuration); expect(find.byKey(const Key('chat-composer-primary')), findsOneWidget);
final stop = find.byKey(const Key('chat-composer-stop')); expect(
final target = tester.getRect(stop); tester
await tester.pump(const Duration(seconds: 3)); .widget<RotationTransition>(
expect(tester.getRect(stop), target); find.byKey(const Key('chat-stop-rotation')),
expect(find.byKey(const Key('chat-composer-primary')), findsOneWidget); )
expect( .turns
tester .value,
.widget<RotationTransition>( greaterThan(0),
find.byKey(const Key('chat-stop-rotation')), );
) await tester.tap(stop);
.turns await tester.pump();
.value, await tester.pump();
greaterThan(0), expect(gateway.interruptBodies, [
); {'session_id': 's'},
await tester.tap(stop); ]);
await tester.pump(); running.value = false;
await tester.pump(); await tester.pumpAndSettle();
expect(gateway.interruptBodies, [ expect(find.byType(ChatStopIcon), findsNothing);
{'session_id': 's'}, expect(tester.binding.transientCallbackCount, 0);
]); },
running.value = false; );
await tester.pumpAndSettle();
expect(find.byType(ChatStopIcon), findsNothing);
expect(tester.binding.transientCallbackCount, 0);
},
);
}
} }
@@ -19,15 +19,10 @@ const _session = <String, dynamic>{
'model_provider': 'p1', 'model_provider': 'p1',
}; };
Widget _host(Widget child, {required bool cupertino}) => cupertino Widget _host(Widget child) => MaterialApp(
? CupertinoApp( theme: ThemeData(platform: TargetPlatform.android),
theme: const CupertinoThemeData(brightness: Brightness.dark), home: Scaffold(body: child),
home: CupertinoPageScaffold(child: child), );
)
: MaterialApp(
theme: ThemeData(platform: TargetPlatform.android),
home: Scaffold(body: child),
);
void _useNarrowText(WidgetTester tester) { void _useNarrowText(WidgetTester tester) {
tester.view.physicalSize = const Size(320, 640); tester.view.physicalSize = const Size(320, 640);
@@ -39,58 +34,49 @@ void _useNarrowText(WidgetTester tester) {
} }
void main() { void main() {
for (final cupertino in [false, true]) { testWidgets('wide header uses one explicit control gap', (tester) async {
testWidgets( tester.view.physicalSize = const Size(1440, 900);
'${cupertino ? 'Cupertino' : 'Material'} wide header uses one explicit control gap', tester.view.devicePixelRatio = 1;
(tester) async { addTearDown(tester.view.resetPhysicalSize);
tester.view.physicalSize = const Size(1440, 900); addTearDown(tester.view.resetDevicePixelRatio);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
Widget control(String key) => Widget control(String key) =>
SizedBox(key: Key(key), width: 48, height: 48); SizedBox(key: Key(key), width: 48, height: 48);
await tester.pumpWidget( await tester.pumpWidget(
_host( _host(
ChatThreadHeader( ChatThreadHeader(
title: 'Chat', title: 'Chat',
folder: 'demo', folder: 'demo',
onInfo: () {}, onInfo: () {},
controls: [ controls: [control('header-control-1'), control('header-control-2')],
control('header-control-1'), actions: [control('header-action-1'), control('header-action-2')],
control('header-control-2'), moreActions: [
], ChatBarAction(
actions: [control('header-action-1'), control('header-action-2')], label: 'More action',
moreActions: [ onPressed: () {},
ChatBarAction( materialIcon: Icons.more_horiz,
label: 'More action', cupertinoIcon: CupertinoIcons.ellipsis,
onPressed: () {},
materialIcon: Icons.more_horiz,
cupertinoIcon: CupertinoIcons.ellipsis,
),
],
), ),
cupertino: cupertino, ],
), ),
); ),
await tester.pumpAndSettle();
double gap(String left, String right) =>
tester.getTopLeft(find.byKey(Key(right))).dx -
tester.getTopRight(find.byKey(Key(left))).dx;
expect(gap('header-control-1', 'header-control-2'), 8);
expect(gap('header-control-2', 'header-action-1'), 8);
expect(gap('header-action-1', 'header-action-2'), 8);
expect(
tester.getTopLeft(find.byKey(segmentedMoreKey).first).dx -
tester.getTopRight(find.byKey(const Key('header-action-2'))).dx,
8,
);
},
); );
} await tester.pumpAndSettle();
double gap(String left, String right) =>
tester.getTopLeft(find.byKey(Key(right))).dx -
tester.getTopRight(find.byKey(Key(left))).dx;
expect(gap('header-control-1', 'header-control-2'), 8);
expect(gap('header-control-2', 'header-action-1'), 8);
expect(gap('header-action-1', 'header-action-2'), 8);
expect(
tester.getTopLeft(find.byKey(segmentedMoreKey).first).dx -
tester.getTopRight(find.byKey(const Key('header-action-2'))).dx,
8,
);
});
testWidgets('short large-text header keeps controls in its single row', ( testWidgets('short large-text header keeps controls in its single row', (
tester, tester,
@@ -116,7 +102,6 @@ void main() {
), ),
), ),
), ),
cupertino: false,
), ),
); );
await tester.pumpAndSettle(); await tester.pumpAndSettle();
@@ -148,7 +133,6 @@ void main() {
session: _session, session: _session,
onBack: () => backed++, onBack: () => backed++,
), ),
cupertino: false,
), ),
); );
await tester.pumpAndSettle(); await tester.pumpAndSettle();
@@ -194,157 +178,134 @@ void main() {
); );
// The mode control is Material only. // The mode control is Material only.
for (final cupertino in [false]) { for (final width in [320.0, 390.0, 1280.0]) {
for (final width in [320.0, 390.0, 1280.0]) { testWidgets('grouped actions at $width and text scale 2', (tester) async {
testWidgets( _useNarrowText(tester);
'${cupertino ? 'Cupertino' : 'Material'} grouped actions at $width and text scale 2', tester.view.physicalSize = Size(width, 800);
(tester) async { final gateway = FakeChatGateway();
_useNarrowText(tester); addTearDown(gateway.close);
tester.view.physicalSize = Size(width, 800); gateway.history = (_) async => chatPage(const []);
final gateway = FakeChatGateway(); gateway.subscribe = () async => const {};
addTearDown(gateway.close); var sidebar = 0;
gateway.history = (_) async => chatPage(const []); var pane = 0;
gateway.subscribe = () async => const {}; var next = 0;
var sidebar = 0; await tester.pumpWidget(
var pane = 0; _host(
var next = 0; ChatThreadView(
await tester.pumpWidget( gateway: gateway,
_host( sessionId: 's',
ChatThreadView( title: _title,
gateway: gateway, session: {
sessionId: 's', ..._session,
title: _title, 'mode': 'safe',
session: { 'mode_name': 'Ask before making changes',
..._session, },
'mode': 'safe', onBack: () {},
'mode_name': 'Ask before making changes', onNextChat: () => next++,
}, sidebarControl: ChatBarAction(
onBack: () {}, label: 'Sidebar action',
onNextChat: () => next++, onPressed: () => sidebar++,
sidebarControl: ChatBarAction( materialIcon: Icons.menu,
label: 'Sidebar action', cupertinoIcon: CupertinoIcons.sidebar_left,
onPressed: () => sidebar++,
materialIcon: Icons.menu,
cupertinoIcon: CupertinoIcons.sidebar_left,
),
paneControls: [
ChatBarAction(
label: 'Pane action',
onPressed: () => pane++,
materialIcon: Icons.add_box,
cupertinoIcon: CupertinoIcons.plus_square,
),
],
),
cupertino: cupertino,
), ),
); paneControls: [
await tester.pumpAndSettle(); ChatBarAction(
final selectors = find.byKey( label: 'Pane action',
const Key('chat-model-permission-island'), onPressed: () => pane++,
); materialIcon: Icons.add_box,
final actions = find.byKey(const Key('chat-actions-island')); cupertinoIcon: CupertinoIcons.plus_square,
expect(selectors, findsOneWidget);
expect(actions, findsOneWidget);
expect(
(tester.getCenter(selectors).dy - tester.getCenter(actions).dy)
.abs(),
lessThan(16),
);
expect(find.byKey(const Key('chat-next')), findsNothing);
expect(find.text('Next chat'), findsNothing);
expect(find.byKey(const Key('chat-model')), findsOneWidget);
expect(find.byKey(const Key('chat-mode')), findsOneWidget);
if (width < 600) {
expect(find.text('model-a'), findsNothing);
expect(find.text('Ask before making changes'), findsNothing);
expect(find.byIcon(Icons.memory_outlined), findsOneWidget);
expect(
find.byIcon(
cupertino
? CupertinoIcons.shield_lefthalf_fill
: Icons.shield_outlined,
), ),
findsOneWidget, ],
); ),
if (!cupertino) { ),
expect(
tester.getSemantics(find.byKey(const Key('chat-model'))).label,
contains('Change model, currently'),
);
expect(
tester.getSemantics(find.byKey(const Key('chat-mode'))).label,
contains('Change mode, currently'),
);
}
expect(
(tester.getCenter(selectors).dy - tester.getCenter(actions).dy)
.abs(),
lessThan(16),
);
}
for (final key in ['chat-model', 'chat-mode']) {
expect(
tester.getSize(find.byKey(Key(key))).width,
greaterThanOrEqualTo(cupertino ? 44 : 48),
);
}
expect(find.text('Sidebar action'), findsNothing);
expect(find.text('Pane action'), findsNothing);
expect(tester.takeException(), isNull);
// Both More entries retain their original callbacks in native menus.
await tester.tap(find.byKey(segmentedMoreKey).hitTestable());
await tester.pumpAndSettle();
await tester.tap(find.text('Sidebar action'));
await tester.pumpAndSettle();
expect(sidebar, 1);
await tester.tap(find.byKey(segmentedMoreKey).hitTestable());
await tester.pumpAndSettle();
await tester.tap(find.text('Pane action'));
await tester.pumpAndSettle();
expect(pane, 1);
expect(next, 0);
expect(tester.takeException(), isNull);
},
); );
} await tester.pumpAndSettle();
final selectors = find.byKey(const Key('chat-model-permission-island'));
final actions = find.byKey(const Key('chat-actions-island'));
expect(selectors, findsOneWidget);
expect(actions, findsOneWidget);
expect(
(tester.getCenter(selectors).dy - tester.getCenter(actions).dy).abs(),
lessThan(16),
);
expect(find.byKey(const Key('chat-next')), findsNothing);
expect(find.text('Next chat'), findsNothing);
expect(find.byKey(const Key('chat-model')), findsOneWidget);
expect(find.byKey(const Key('chat-mode')), findsOneWidget);
if (width < 600) {
expect(find.text('model-a'), findsNothing);
expect(find.text('Ask before making changes'), findsNothing);
expect(find.byIcon(Icons.memory_outlined), findsOneWidget);
expect(find.byIcon(Icons.shield_outlined), findsOneWidget);
expect(
tester.getSemantics(find.byKey(const Key('chat-model'))).label,
contains('Change model, currently'),
);
expect(
tester.getSemantics(find.byKey(const Key('chat-mode'))).label,
contains('Change mode, currently'),
);
expect(
(tester.getCenter(selectors).dy - tester.getCenter(actions).dy).abs(),
lessThan(16),
);
}
for (final key in ['chat-model', 'chat-mode']) {
expect(
tester.getSize(find.byKey(Key(key))).width,
greaterThanOrEqualTo(48),
);
}
expect(find.text('Sidebar action'), findsNothing);
expect(find.text('Pane action'), findsNothing);
expect(tester.takeException(), isNull);
// Both More entries retain their original callbacks in native menus.
await tester.tap(find.byKey(segmentedMoreKey).hitTestable());
await tester.pumpAndSettle();
await tester.tap(find.text('Sidebar action'));
await tester.pumpAndSettle();
expect(sidebar, 1);
await tester.tap(find.byKey(segmentedMoreKey).hitTestable());
await tester.pumpAndSettle();
await tester.tap(find.text('Pane action'));
await tester.pumpAndSettle();
expect(pane, 1);
expect(next, 0);
expect(tester.takeException(), isNull);
});
} }
for (final cupertino in [false, true]) { testWidgets('sidebar layout submenu retains callback on Material', (
testWidgets( tester,
'sidebar layout submenu retains callback on ${cupertino ? 'Cupertino' : 'Material'}', ) async {
(tester) async { ChatSidebarMode? picked;
ChatSidebarMode? picked; await tester.pumpWidget(
await tester.pumpWidget( _host(
_host( ChatThreadHeader(
ChatThreadHeader( title: 'Chat',
title: 'Chat', folder: 'demo',
folder: 'demo', onInfo: () {},
onInfo: () {}, actions: const [Icon(Icons.folder_outlined)],
actions: const [Icon(Icons.folder_outlined)], moreActions: [
moreActions: [ ChatSidebarButton(
ChatSidebarButton( mode: ChatSidebarMode.expanded,
mode: ChatSidebarMode.expanded, onChanged: (value) => picked = value,
onChanged: (value) => picked = value,
),
],
), ),
cupertino: cupertino, ],
), ),
); ),
await tester.pumpAndSettle();
expect(find.byType(ChatSidebarButton), findsNothing);
await tester.tap(find.byKey(segmentedMoreKey).hitTestable());
await tester.pumpAndSettle();
await tester.tap(find.text('Chat list layout'));
await tester.pumpAndSettle();
await tester.tap(find.text('Hide chat list'));
await tester.pumpAndSettle();
expect(picked, ChatSidebarMode.hidden);
expect(tester.takeException(), isNull);
},
); );
} await tester.pumpAndSettle();
expect(find.byType(ChatSidebarButton), findsNothing);
await tester.tap(find.byKey(segmentedMoreKey).hitTestable());
await tester.pumpAndSettle();
await tester.tap(find.text('Chat list layout'));
await tester.pumpAndSettle();
await tester.tap(find.text('Hide chat list'));
await tester.pumpAndSettle();
expect(picked, ChatSidebarMode.hidden);
expect(tester.takeException(), isNull);
});
testWidgets('a conversation without a model keeps the same compact row', ( testWidgets('a conversation without a model keeps the same compact row', (
tester, tester,
@@ -364,7 +325,6 @@ void main() {
session: {..._session, 'backend': 'other'}, session: {..._session, 'backend': 'other'},
onBack: () {}, onBack: () {},
), ),
cupertino: false,
), ),
); );
await tester.pumpAndSettle(); await tester.pumpAndSettle();