import 'package:flutter/material.dart'; import '../../../core/api_gateway.dart'; import '../../../core/error_reason.dart'; import '../../../ui/adaptive/app_popups.dart'; import '../data/chat_repository.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 repository = ChatRepository(widget.gateway); final picker = _ChatModePicker( load: () => repository.modes(widget.sessionId), current: _mode, currentName: _name, 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; }); } }, ); await showAppChoiceMenu(context, builder: (_) => picker); } @override Widget build(BuildContext context) { if (_mode.isEmpty || _name.isEmpty) return const SizedBox.shrink(); 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: [ const Icon(Icons.shield_outlined), if (!iconOnly) ...[ const SizedBox(width: 4), Flexible(child: Text(label, overflow: TextOverflow.ellipsis)), ], ], ); 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: const Key('chat-mode'), 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.choose, }); final Future<({List modes, String current})> Function() load; final String current; final String currentName; 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) => _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) AppChoiceMenuItem( key: ValueKey('chat-mode-option-${mode.id}'), selected: mode.id == _current, onTap: _busy ? null : () => _choose(mode), child: mode.description.isEmpty ? Text(mode.name) : Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ Text(mode.name), Text( mode.description, style: theme.textTheme.bodySmall, ), ], ), ), ], ), ); } }