import 'dart:async'; 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_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.onAccepted, }); final ApiGateway gateway; final String sessionId; final String backend; final String currentProvider; final String currentModel; 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; if (_isCurrent(model)) { Navigator.of(context).pop(); 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) => _materialChooser(context); 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 SafeArea( child: SingleChildScrollView( key: const Key('chat-model-chooser'), child: Column( mainAxisSize: MainAxisSize.min, children: [ const Padding( padding: EdgeInsets.fromLTRB(16, 0, 16, 8), child: Text('Change model'), ), Padding( padding: const EdgeInsetsDirectional.fromSTEB(16, 0, 16, 8), child: Text( chatModelSelectionNote(widget.backend), style: theme.textTheme.bodySmall?.copyWith(color: secondary), ), ), if (_loading) Padding( padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 16, 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(16, 0, 16, 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(16, 0, 16, 8), child: Text( 'No models are available for this chat.', style: theme.textTheme.bodyMedium?.copyWith(color: secondary), ), ) else ...[ Padding( padding: const EdgeInsetsDirectional.fromSTEB(16, 0, 16, 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) AppChoiceMenuItem( key: _optionKey(model), selected: _isCurrent(model), onTap: _busy ? null : () => _choose(model), child: _optionRow(context, model), ), if (matches.isEmpty && needle.isNotEmpty) Padding( padding: const EdgeInsetsDirectional.fromSTEB(16, 0, 16, 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 _optionRow(BuildContext context, JsonMap model) { final selected = _isCurrent(model); final secondary = Theme.of(context).colorScheme.onSurfaceVariant; 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)), ], ), ), // The shared menu row supplies the check mark. ], ), ); } }