import 'dart:async'; 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 'chat_models.dart'; /// The native model chooser. /// /// It loads the recorded catalog once, offers the web's search over name, id /// and provider, shows the server's rows in server order, and keeps the /// previous model when a switch is refused. Acceptance is reported to the /// conversation even when the operator dismisses the chooser while the switch /// is still in flight, because the server has already applied it. class ChatModelChooser extends StatefulWidget { const ChatModelChooser({ super.key, required this.gateway, required this.sessionId, required this.backend, required this.currentProvider, required this.currentModel, required this.cupertino, required this.onAccepted, }); final ApiGateway gateway; final String sessionId; final String backend; final String currentProvider; final String currentModel; final bool cupertino; final ValueChanged onAccepted; @override State createState() => _ChatModelChooserState(); } class _ChatModelChooserState extends State { final TextEditingController _search = TextEditingController(); List _models = const []; bool _loading = true; bool _busy = false; String? _error; @override void initState() { super.initState(); unawaited(_load()); } @override void dispose() { _search.dispose(); super.dispose(); } Future _load() async { try { final catalog = await ChatRepository( widget.gateway, ).models(widget.sessionId); if (!mounted) return; setState(() { _models = catalog; _loading = false; }); } catch (error) { if (!mounted) return; setState(() { _loading = false; _error = describeErrorReason( error, fallback: 'The model list could not be loaded.', ); }); } } bool _isCurrent(JsonMap model) { final id = '${model['id'] ?? ''}'.trim(); if (id != widget.currentModel) return false; final provider = '${model['provider'] ?? ''}'.trim(); return widget.currentProvider.isEmpty || provider == widget.currentProvider; } Key _optionKey(JsonMap model) => ValueKey( 'chat-model-option-${model['provider'] ?? ''}/${model['id'] ?? ''}', ); Future _choose(JsonMap model) async { if (_busy) return; setState(() { _busy = true; _error = null; }); final provider = '${model['provider'] ?? ''}'.trim(); final id = '${model['id'] ?? ''}'.trim(); try { final reply = await ChatRepository( widget.gateway, ).selectModel(widget.sessionId, provider, id); final applied = _appliedSelection(reply, provider: provider, model: id); // The accepted switch belongs to the conversation, not to this dialog. widget.onAccepted(applied); if (!mounted) return; Navigator.of(context).pop(); } catch (error) { if (!mounted) return; setState(() { _busy = false; _error = describeErrorReason( error, fallback: 'The model was not changed.', ); }); } } /// The server's echo wins; a reply that omits a field keeps the value the /// request carried, matching the web repository's fallback. ChatModelSelection _appliedSelection( JsonMap reply, { required String provider, required String model, }) { final echoed = reply['chat_model']; final body = echoed is Map ? Map.from(echoed) : const {}; final replyProvider = '${body['provider'] ?? ''}'.trim(); final replyModel = '${body['model'] ?? ''}'.trim(); return ( provider: replyProvider.isEmpty ? provider : replyProvider, model: replyModel.isEmpty ? model : replyModel, selection: '${body['selection'] ?? ''}'.trim(), ); } @override Widget build(BuildContext 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) { final theme = Theme.of(context); final secondary = theme.colorScheme.onSurfaceVariant; final matches = filterChatModels(_models, _search.text); final needle = _search.text.trim(); return SimpleDialog( key: const Key('chat-model-chooser'), title: const Text('Change model'), children: [ Padding( padding: const EdgeInsetsDirectional.fromSTEB(24, 0, 24, 8), child: Text( chatModelSelectionNote(widget.backend), style: theme.textTheme.bodySmall?.copyWith(color: secondary), ), ), if (_loading) Padding( padding: const EdgeInsetsDirectional.fromSTEB(24, 8, 24, 8), child: Row( children: [ const CircularProgressIndicator(), const SizedBox(width: 12), const Expanded(child: Text('Loading models…')), ], ), ) else if (_error != null) Padding( padding: const EdgeInsetsDirectional.fromSTEB(24, 0, 24, 8), child: Text( _error!, key: const Key('chat-model-error'), style: theme.textTheme.bodyMedium?.copyWith( color: theme.colorScheme.error, ), ), ) else if (_models.isEmpty) Padding( padding: const EdgeInsetsDirectional.fromSTEB(24, 0, 24, 8), child: Text( 'No models are available for this chat.', style: theme.textTheme.bodyMedium?.copyWith(color: secondary), ), ) else ...[ Padding( padding: const EdgeInsetsDirectional.fromSTEB(24, 0, 24, 8), child: TextField( key: const Key('chat-model-search'), controller: _search, onChanged: (_) => setState(() {}), decoration: const InputDecoration( prefixIcon: Icon(Icons.search), hintText: 'Search models', ), ), ), for (final model in matches) SimpleDialogOption( key: _optionKey(model), onPressed: _busy ? null : () => _choose(model), child: _optionRow(context, model, cupertino: false), ), if (matches.isEmpty && needle.isNotEmpty) Padding( padding: const EdgeInsetsDirectional.fromSTEB(24, 0, 24, 8), child: Text( 'No models match "$needle".', key: const Key('chat-model-no-match'), style: theme.textTheme.bodyMedium?.copyWith(color: secondary), ), ), ], Padding( padding: const EdgeInsetsDirectional.fromSTEB(16, 4, 16, 8), child: Align( alignment: AlignmentDirectional.centerEnd, child: TextButton( key: const Key('chat-model-cancel'), onPressed: () => Navigator.of(context).pop(), child: const Text('Cancel'), ), ), ), ], ); } Widget _cupertinoChooser(BuildContext context) { 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 secondary = cupertino ? CupertinoColors.secondaryLabel.resolveFrom(context) : Theme.of(context).colorScheme.onSurfaceVariant; final accent = cupertino ? CupertinoTheme.of(context).primaryColor : Theme.of(context).colorScheme.primary; final provider = '${model['provider'] ?? ''}'.trim(); return Semantics( selected: selected, child: Row( children: [ Expanded( child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text(chatModelName(model)), if (provider.isNotEmpty) Text(provider, style: TextStyle(color: secondary)), ], ), ), if (selected) Icon( cupertino ? CupertinoIcons.check_mark : Icons.check, color: accent, ), ], ), ); } }