import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import '../../../core/api_gateway.dart'; import '../../../core/error_reason.dart'; import '../data/chat_repository.dart'; import '../ui/sessions/chat_adaptive.dart'; import 'chat_bar_control_style.dart'; /// The conversation bar's permission-mode control. /// /// It shows the mode the session row names (`mode_name`, the harness default /// when none was chosen) without a request of its own, since requests are /// serialized and must not delay the transcript. Tapping reads the harness's /// modes (`chat_modes`) into a native picker; choosing one sends `chat_mode`. A /// refusal keeps the picker open with the server's reason. A row without a /// mode (an older server or a harness without modes) shows no control. class ChatModeControl extends StatefulWidget { const ChatModeControl({ super.key, required this.gateway, required this.sessionId, required this.mode, required this.modeName, this.onChanged, this.showLabel = false, }); final bool showLabel; final ApiGateway gateway; final String sessionId; /// The row's `mode` id and its display name. final String mode; final String modeName; /// The accepted mode's id and name, so the opened row keeps up. final void Function(String mode, String name)? onChanged; @override State createState() => _ChatModeControlState(); } class _ChatModeControlState extends State { late String _mode = widget.mode; late String _name = widget.modeName; @override void didUpdateWidget(covariant ChatModeControl oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.mode != widget.mode || oldWidget.modeName != widget.modeName) { _mode = widget.mode; _name = widget.modeName; } } Future _open() async { final cupertino = chatControlsStyleOf(context) == ChatControlsStyle.cupertino; final repository = ChatRepository(widget.gateway); final picker = _ChatModePicker( load: () => repository.modes(widget.sessionId), current: _mode, currentName: _name, cupertino: cupertino, choose: (mode) async { final applied = await repository.selectMode(widget.sessionId, mode.id); final name = applied == mode.id ? mode.name : applied; widget.onChanged?.call(applied, name); if (mounted) { setState(() { _mode = applied; _name = name; }); } }, ); if (cupertino) { await showCupertinoModalPopup( context: context, builder: (_) => picker, ); return; } await showModalBottomSheet( context: context, showDragHandle: true, isScrollControlled: true, useSafeArea: true, builder: (_) => picker, ); } @override Widget build(BuildContext context) { if (_mode.isEmpty || _name.isEmpty) return const SizedBox.shrink(); final cupertino = chatControlsStyleOf(context) == ChatControlsStyle.cupertino; final label = _name; // At phone widths the title and a named mode cannot both remain useful. // Keep the mode's shield, whose semantic label and picker still name it. final iconOnly = !widget.showLabel && MediaQuery.sizeOf(context).width < 600; final content = Row( mainAxisSize: MainAxisSize.min, children: [ Icon( cupertino ? CupertinoIcons.shield_lefthalf_fill : Icons.shield_outlined, ), if (!iconOnly) ...[ const SizedBox(width: 4), Flexible(child: Text(label, overflow: TextOverflow.ellipsis)), ], ], ); const key = Key('chat-mode'); if (cupertino) { return Semantics( container: true, button: true, label: 'Change mode, currently $label', onTap: _open, child: ExcludeSemantics( child: CupertinoButton( key: key, padding: chatBarButtonPadding, onPressed: _open, child: chatBarCupertinoContent(context, content), ), ), ); } return Semantics( container: true, button: true, label: 'Change mode, currently $label', onTap: _open, child: ExcludeSemantics( child: Tooltip( message: 'Change mode (currently $label)', child: TextButton( key: key, style: chatBarTextButtonStyle(context, compact: iconOnly), onPressed: _open, child: content, ), ), ), ); } } /// One mode the harness offers. typedef _Mode = ({String id, String name, String description}); /// The native mode list: each mode's name and description, the current one /// checked. It reads the list when opened and closes once the server accepts /// a choice. class _ChatModePicker extends StatefulWidget { const _ChatModePicker({ required this.load, required this.current, required this.currentName, required this.cupertino, required this.choose, }); final Future<({List modes, String current})> Function() load; final String current; final String currentName; final bool cupertino; final Future Function(_Mode mode) choose; @override State<_ChatModePicker> createState() => _ChatModePickerState(); } class _ChatModePickerState extends State<_ChatModePicker> { List<_Mode>? _modes; late String _current = widget.current; bool _busy = false; String? _error; /// The session row has already named the selected mode. Some harnesses do /// not return a catalog, so retain that known value in the picker rather /// than opening an action sheet with no visible mode. List<_Mode> get _visibleModes { final modes = _modes; if (modes == null || _current.isEmpty || widget.currentName.isEmpty || modes.any((mode) => mode.id == _current)) { return modes ?? const []; } return [ ...modes, (id: _current, name: widget.currentName, description: ''), ]; } @override void initState() { super.initState(); _read(); } Future _read() async { try { final reply = await widget.load(); if (!mounted) return; setState(() { _modes = [ for (final mode in reply.modes) if ('${mode['id'] ?? ''}'.trim().isNotEmpty) ( id: '${mode['id']}'.trim(), name: '${mode['name'] ?? mode['id']}'.trim(), description: '${mode['description'] ?? ''}'.trim(), ), ]; if (reply.current.isNotEmpty) _current = reply.current; }); } catch (error) { if (!mounted) return; setState(() { _modes = const []; _error = describeErrorReason( error, fallback: 'The modes could not be loaded.', ); }); } } Future _choose(_Mode mode) async { if (_busy) return; if (mode.id == _current) { Navigator.of(context).pop(); return; } setState(() { _busy = true; _error = null; }); try { await widget.choose(mode); if (mounted) Navigator.of(context).pop(); } catch (error) { if (!mounted) return; setState(() { _busy = false; _error = describeErrorReason( error, fallback: 'The mode was not changed.', ); }); } } @override Widget build(BuildContext context) => widget.cupertino ? _cupertinoSheet(context) : _materialSheet(context); Widget _materialSheet(BuildContext context) { final theme = Theme.of(context); final modes = _visibleModes; final loaded = _modes != null; return SafeArea( child: ListView( key: const Key('chat-mode-sheet'), shrinkWrap: true, children: [ Padding( padding: const EdgeInsets.fromLTRB(16, 0, 16, 8), child: Text('Mode', style: theme.textTheme.titleMedium), ), if (_error != null) Padding( padding: const EdgeInsets.fromLTRB(16, 0, 16, 8), child: Text( _error!, style: TextStyle(color: theme.colorScheme.error), ), ), if (!loaded) const Padding( padding: EdgeInsets.all(16), child: Center(child: CircularProgressIndicator()), ) else for (final mode in modes) ListTile( key: ValueKey('chat-mode-option-${mode.id}'), enabled: !_busy, title: Text(mode.name), subtitle: mode.description.isEmpty ? null : Text(mode.description), trailing: mode.id == _current ? Icon(Icons.check, color: theme.colorScheme.primary) : null, onTap: () => _choose(mode), ), ], ), ); } Widget _cupertinoSheet(BuildContext context) { final secondary = CupertinoColors.secondaryLabel.resolveFrom(context); final modes = _visibleModes; final loaded = _modes != null; return CupertinoActionSheet( key: const Key('chat-mode-sheet'), title: const Text('Mode'), message: _error != null ? Text( _error!, style: TextStyle( color: CupertinoColors.systemRed.resolveFrom(context), ), ) : !loaded ? const CupertinoActivityIndicator() : null, actions: [ for (final mode in modes) CupertinoActionSheetAction( key: ValueKey('chat-mode-option-${mode.id}'), onPressed: () => _choose(mode), child: Column( children: [ Row( mainAxisSize: MainAxisSize.min, children: [ Flexible(child: Text(mode.name)), if (mode.id == _current) ...[ const SizedBox(width: 6), const Icon(CupertinoIcons.checkmark_alt), ], ], ), if (mode.description.isNotEmpty) Text( mode.description, textAlign: TextAlign.center, style: TextStyle(fontSize: 13, color: secondary), ), ], ), ), ], cancelButton: CupertinoActionSheetAction( onPressed: () => Navigator.of(context).pop(), child: const Text('Cancel'), ), ); } }