feat(app): choose a chat model from the conversation header
Native model control and chooser in the chat thread header, matching the web chat_models/chat_model exchange. Fixes the chat_models list parsing, keeps the accepted server echo across Back/reopen, and resolves the session row for /chat/:id deep links.
This commit is contained in:
@@ -0,0 +1,370 @@
|
||||
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<ChatModelSelection> onAccepted;
|
||||
|
||||
@override
|
||||
State<ChatModelChooser> createState() => _ChatModelChooserState();
|
||||
}
|
||||
|
||||
class _ChatModelChooserState extends State<ChatModelChooser> {
|
||||
final TextEditingController _search = TextEditingController();
|
||||
List<JsonMap> _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<void> _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<String>(
|
||||
'chat-model-option-${model['provider'] ?? ''}/${model['id'] ?? ''}',
|
||||
);
|
||||
|
||||
Future<void> _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<String, dynamic>.from(echoed)
|
||||
: const <String, dynamic>{};
|
||||
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,
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../ui/sessions/chat_adaptive.dart';
|
||||
import 'chat_model_chooser.dart';
|
||||
import 'chat_models.dart';
|
||||
|
||||
/// The conversation header's model control.
|
||||
///
|
||||
/// It shows the opened row's recorded model (with the web's next-turn suffix)
|
||||
/// and opens the harness's own catalog in a native chooser. Choosing an entry
|
||||
/// sends the web's `chat_model` request. A refusal leaves this control's model
|
||||
/// untouched and reports the reason in the chooser; an acceptance adopts the
|
||||
/// server's echoed model instead of the row that was tapped and reports it, so
|
||||
/// the destination's opened row keeps up with the server.
|
||||
class ChatModelControl extends StatefulWidget {
|
||||
const ChatModelControl({
|
||||
super.key,
|
||||
required this.gateway,
|
||||
required this.sessionId,
|
||||
required this.session,
|
||||
this.onChanged,
|
||||
});
|
||||
|
||||
final ApiGateway gateway;
|
||||
final String sessionId;
|
||||
|
||||
/// The opened row's recorded facts: `backend`, `model`, `model_provider` and
|
||||
/// `model_selection`.
|
||||
final JsonMap session;
|
||||
|
||||
/// The server's echo after an accepted switch.
|
||||
final ValueChanged<ChatModelSelection>? onChanged;
|
||||
|
||||
@override
|
||||
State<ChatModelControl> createState() => _ChatModelControlState();
|
||||
}
|
||||
|
||||
class _ChatModelControlState extends State<ChatModelControl> {
|
||||
late String _provider;
|
||||
late String _model;
|
||||
late String _selection;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_adopt(widget.session);
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(covariant ChatModelControl oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
// The destination replaces the opened row after an accepted switch (and may
|
||||
// re-read the list), so a changed row is adopted instead of only read once.
|
||||
if (chatModelRecordedFacts(oldWidget.session) !=
|
||||
chatModelRecordedFacts(widget.session)) {
|
||||
_adopt(widget.session);
|
||||
}
|
||||
}
|
||||
|
||||
void _adopt(JsonMap session) {
|
||||
final facts = chatModelRecordedFacts(session);
|
||||
_provider = facts.provider;
|
||||
_model = facts.model;
|
||||
_selection = facts.selection;
|
||||
}
|
||||
|
||||
Future<void> _open() async {
|
||||
final cupertino =
|
||||
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
|
||||
final chooser = ChatModelChooser(
|
||||
gateway: widget.gateway,
|
||||
sessionId: widget.sessionId,
|
||||
backend: '${widget.session['backend'] ?? ''}'.trim(),
|
||||
currentProvider: _provider,
|
||||
currentModel: _model,
|
||||
cupertino: cupertino,
|
||||
onAccepted: _accept,
|
||||
);
|
||||
if (cupertino) {
|
||||
await showCupertinoModalPopup<void>(
|
||||
context: context,
|
||||
builder: (_) => chooser,
|
||||
);
|
||||
return;
|
||||
}
|
||||
await showDialog<void>(context: context, builder: (_) => chooser);
|
||||
}
|
||||
|
||||
void _accept(ChatModelSelection applied) {
|
||||
// The server has applied the switch, so the destination is told even if
|
||||
// this conversation was left while the request was in flight.
|
||||
widget.onChanged?.call(applied);
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_provider = applied.provider;
|
||||
_model = applied.model;
|
||||
_selection = applied.selection;
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final cupertino =
|
||||
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
|
||||
final label = chatModelLabel(_model, _selection);
|
||||
final content = Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Flexible(child: Text(label, overflow: TextOverflow.ellipsis)),
|
||||
const SizedBox(width: 4),
|
||||
Icon(cupertino ? CupertinoIcons.chevron_down : Icons.expand_more),
|
||||
],
|
||||
);
|
||||
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: const EdgeInsets.symmetric(horizontal: 8),
|
||||
onPressed: _open,
|
||||
child: content,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
return Tooltip(
|
||||
message: 'Change model (currently $label)',
|
||||
child: TextButton(key: key, onPressed: _open, child: content),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
|
||||
/// A model switch the server accepted, as its own reply reported it.
|
||||
typedef ChatModelSelection = ({
|
||||
String provider,
|
||||
String model,
|
||||
String selection,
|
||||
});
|
||||
|
||||
/// Harnesses with a verified catalog and model-selection path, matching the
|
||||
/// web's `supportsChatModels`.
|
||||
bool supportsChatModels(String backend) =>
|
||||
const ['', 'opencode', 'codex'].contains(backend.trim());
|
||||
|
||||
/// The recorded current model, or the web's "Model" when none was recorded.
|
||||
String chatModelLabel(String model, String selection) {
|
||||
final recorded = model.trim();
|
||||
final label = recorded.isEmpty ? 'Model' : recorded;
|
||||
return selection == 'next_turn' ? '$label · next turn' : label;
|
||||
}
|
||||
|
||||
/// The helper shown above the catalog, verbatim from the web.
|
||||
String chatModelSelectionNote(String backend) => backend.trim() == 'codex'
|
||||
? 'Saved by Pipelines for the next turn you send. Does not resume this '
|
||||
'thread or edit global Codex configuration.'
|
||||
: 'Applies to the next turn in this chat.';
|
||||
|
||||
/// A model's display name, or its id when the server gave no name.
|
||||
String chatModelName(JsonMap model) {
|
||||
final name = '${model['name'] ?? ''}'.trim();
|
||||
return name.isNotEmpty ? name : '${model['id'] ?? ''}'.trim();
|
||||
}
|
||||
|
||||
/// The rows a query matches: a case-insensitive substring over the display
|
||||
/// name, id and provider, in the server's order. A blank query keeps the whole
|
||||
/// catalog, and a row with neither name nor id is never offered.
|
||||
List<JsonMap> filterChatModels(List<JsonMap> models, String query) {
|
||||
final needle = query.trim().toLowerCase();
|
||||
final result = <JsonMap>[];
|
||||
for (final model in models) {
|
||||
if (chatModelName(model).isEmpty) continue;
|
||||
if (needle.isNotEmpty) {
|
||||
final name = '${model['name'] ?? ''}';
|
||||
final id = '${model['id'] ?? ''}';
|
||||
final provider = '${model['provider'] ?? ''}';
|
||||
final haystack = '$name\u0000$id\u0000$provider'.toLowerCase();
|
||||
if (!haystack.contains(needle)) continue;
|
||||
}
|
||||
result.add(model);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// The recorded facts a model control displays, so a row replaced with the
|
||||
/// same values never resets a newer local choice.
|
||||
({String provider, String model, String selection}) chatModelRecordedFacts(
|
||||
JsonMap session,
|
||||
) => (
|
||||
provider: '${session['model_provider'] ?? ''}'.trim(),
|
||||
model: '${session['model'] ?? ''}'.trim(),
|
||||
selection: '${session['model_selection'] ?? ''}'.trim(),
|
||||
);
|
||||
@@ -13,6 +13,8 @@ import '../ui/transcript/chat_message_view.dart';
|
||||
import 'chat_composer_bar.dart';
|
||||
import 'chat_composer_controller.dart';
|
||||
import 'chat_draft_store.dart';
|
||||
import 'chat_model_control.dart';
|
||||
import 'chat_models.dart';
|
||||
import 'chat_row_keys.dart';
|
||||
import 'chat_thread_controller.dart';
|
||||
import 'chat_transcript_card.dart';
|
||||
@@ -34,6 +36,8 @@ class ChatThreadView extends StatefulWidget {
|
||||
required this.sessionId,
|
||||
required this.onBack,
|
||||
this.title = '',
|
||||
this.session,
|
||||
this.onModelChanged,
|
||||
this.syncToken = 0,
|
||||
this.drafts,
|
||||
this.newOperationId,
|
||||
@@ -46,6 +50,15 @@ class ChatThreadView extends StatefulWidget {
|
||||
/// The list row's title when this visit knows it; a deep link may not.
|
||||
final String title;
|
||||
|
||||
/// The opened row's recorded facts when this visit knows them. The model
|
||||
/// control reads its current model from this row; the destination supplies
|
||||
/// it from the tapped row or from the list's loaded rows for a routed id.
|
||||
final JsonMap? session;
|
||||
|
||||
/// The server's echo after an accepted model switch, so the destination can
|
||||
/// keep the row it opened current for the next visit.
|
||||
final ValueChanged<ChatModelSelection>? onModelChanged;
|
||||
|
||||
/// Advances when the shared socket is replaced, keeping this selection.
|
||||
final int syncToken;
|
||||
|
||||
@@ -300,6 +313,19 @@ class _ChatThreadViewState extends State<ChatThreadView> {
|
||||
).textTheme.navTitleTextStyle
|
||||
: Theme.of(context).textTheme.titleLarge,
|
||||
),
|
||||
if (widget.session != null &&
|
||||
supportsChatModels(
|
||||
'${widget.session!['backend'] ?? ''}',
|
||||
))
|
||||
ChatModelControl(
|
||||
key: ValueKey<String>(
|
||||
'chat-model-${widget.sessionId}',
|
||||
),
|
||||
gateway: widget.gateway,
|
||||
sessionId: widget.sessionId,
|
||||
session: widget.session!,
|
||||
onChanged: widget.onModelChanged,
|
||||
),
|
||||
ChatBarAction(
|
||||
key: const Key('chat-info'),
|
||||
label: 'Chat information',
|
||||
|
||||
@@ -15,25 +15,40 @@ class ChatRepository {
|
||||
|
||||
Future<List<JsonMap>> sessions() async =>
|
||||
_maps((await gateway.call('chat_sessions'))['chat_sessions']);
|
||||
Future<JsonMap> models(String sessionId) async {
|
||||
|
||||
/// The models the session's harness offers, in the server's order.
|
||||
///
|
||||
/// `chat_models` is a JSON list, the same shape the web client reads. A
|
||||
/// missing or wrong-typed field is an empty catalog, never invented rows.
|
||||
Future<List<JsonMap>> models(String sessionId) async {
|
||||
final session = sessionId.trim();
|
||||
if (session.isEmpty) {
|
||||
throw ArgumentError('Select a chat session first.');
|
||||
}
|
||||
final reply = await gateway.call('chat_models', {
|
||||
'chat_query': {'session_id': sessionId},
|
||||
'chat_query': {'session_id': session},
|
||||
});
|
||||
final value = reply['chat_models'];
|
||||
return value is List ? _maps(value) : const [];
|
||||
}
|
||||
|
||||
Future<JsonMap> selectModel(String sessionId, String provider, String model) {
|
||||
final session = sessionId.trim();
|
||||
if (session.isEmpty) {
|
||||
throw ArgumentError('Select a chat session first.');
|
||||
}
|
||||
if (provider.trim().isEmpty || model.trim().isEmpty) {
|
||||
throw ArgumentError('Choose a model first.');
|
||||
}
|
||||
return gateway.call('chat_model', {
|
||||
'chat_model': {
|
||||
'session_id': session,
|
||||
'provider': provider.trim(),
|
||||
'model': model.trim(),
|
||||
},
|
||||
});
|
||||
final catalog = reply['chat_models'];
|
||||
return catalog is Map ? Map<String, dynamic>.from(catalog) : {};
|
||||
}
|
||||
|
||||
Future<JsonMap> selectModel(
|
||||
String sessionId,
|
||||
String provider,
|
||||
String model,
|
||||
) => gateway.call('chat_model', {
|
||||
'chat_model': {
|
||||
'session_id': sessionId,
|
||||
'provider': provider,
|
||||
'model': model,
|
||||
},
|
||||
});
|
||||
Future<List<JsonMap>> shells(String sessionId) async => _maps(
|
||||
(await gateway.call('chat_shells', {
|
||||
'chat_query': {'session_id': sessionId},
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../core/api_gateway.dart';
|
||||
import 'conversation/chat_models.dart';
|
||||
import 'conversation/chat_thread_view.dart';
|
||||
import 'ui/sessions/chat_sessions_screen.dart';
|
||||
|
||||
@@ -37,9 +38,16 @@ class ChatScreen extends StatefulWidget {
|
||||
}
|
||||
|
||||
class _ChatScreenState extends State<ChatScreen> {
|
||||
/// Rows opened in this visit, used only for the native title. A deep link has
|
||||
/// no title until the list loads, and this screen waits for no list request.
|
||||
final Map<String, String> _titles = {};
|
||||
/// Rows this visit has opened, used for the native title and the recorded
|
||||
/// model facts. The mounted list also reports its loaded rows, so a routed id
|
||||
/// (a deep link) resolves the same row without a second list request.
|
||||
final Map<String, JsonMap> _openedSessions = {};
|
||||
|
||||
/// Model switches the server accepted after a row was opened. The row that
|
||||
/// opened the conversation may still carry the pre-switch model, so these win
|
||||
/// for the rest of this visit, including when the same chat is reopened.
|
||||
final Map<String, ChatModelSelection> _acceptedModels = {};
|
||||
|
||||
String? _standaloneSelection;
|
||||
|
||||
String? get _selected {
|
||||
@@ -51,8 +59,7 @@ class _ChatScreenState extends State<ChatScreen> {
|
||||
void _open(JsonMap session) {
|
||||
final id = '${session['id'] ?? ''}';
|
||||
if (id.isEmpty) return;
|
||||
final title = '${session['title'] ?? ''}'.trim();
|
||||
if (title.isNotEmpty) _titles[id] = title;
|
||||
_openedSessions[id] = session;
|
||||
final select = widget.onSessionSelected;
|
||||
if (select != null) {
|
||||
select(id);
|
||||
@@ -61,6 +68,38 @@ class _ChatScreenState extends State<ChatScreen> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Adopts the list's loaded rows for the routed session: a deep link opens
|
||||
/// the conversation before any row has been tapped, and the header's title
|
||||
/// and model control come from that row. Called after a frame, never during
|
||||
/// the list's own build.
|
||||
void _adoptRows(List<JsonMap> rows) {
|
||||
final id = _selected;
|
||||
if (id == null || _openedSessions.containsKey(id)) return;
|
||||
for (final row in rows) {
|
||||
if ('${row['id'] ?? ''}' != id) continue;
|
||||
setState(() => _openedSessions[id] = row);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
void _modelChanged(String id, ChatModelSelection applied) {
|
||||
if (!mounted) return;
|
||||
setState(() => _acceptedModels[id] = applied);
|
||||
}
|
||||
|
||||
/// The row to open for [id], with an accepted model folded in.
|
||||
JsonMap? _rowFor(String id) {
|
||||
final row = _openedSessions[id];
|
||||
final accepted = _acceptedModels[id];
|
||||
if (row == null || accepted == null) return row;
|
||||
return {
|
||||
...row,
|
||||
'model': accepted.model,
|
||||
'model_provider': accepted.provider,
|
||||
'model_selection': accepted.selection,
|
||||
};
|
||||
}
|
||||
|
||||
void _back() {
|
||||
final back = widget.onBack;
|
||||
if (back != null) {
|
||||
@@ -73,6 +112,7 @@ class _ChatScreenState extends State<ChatScreen> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final selected = _selected;
|
||||
final row = selected == null ? null : _rowFor(selected);
|
||||
return Stack(
|
||||
children: [
|
||||
Offstage(
|
||||
@@ -82,6 +122,7 @@ class _ChatScreenState extends State<ChatScreen> {
|
||||
embedded: true,
|
||||
syncToken: widget.syncToken,
|
||||
onOpen: _open,
|
||||
onSessions: _adoptRows,
|
||||
),
|
||||
),
|
||||
if (selected != null)
|
||||
@@ -89,9 +130,11 @@ class _ChatScreenState extends State<ChatScreen> {
|
||||
key: ValueKey<String>('chat-session-$selected'),
|
||||
gateway: widget.gateway,
|
||||
sessionId: selected,
|
||||
title: _titles[selected] ?? '',
|
||||
title: '${row?['title'] ?? ''}'.trim(),
|
||||
session: row,
|
||||
syncToken: widget.syncToken,
|
||||
onBack: _back,
|
||||
onModelChanged: (applied) => _modelChanged(selected, applied),
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
@@ -21,6 +21,7 @@ class ChatSessionsScreen extends StatefulWidget {
|
||||
required this.onOpen,
|
||||
this.embedded = false,
|
||||
this.syncToken = 0,
|
||||
this.onSessions,
|
||||
this.localStore,
|
||||
});
|
||||
final ApiGateway gateway;
|
||||
@@ -33,6 +34,11 @@ class ChatSessionsScreen extends StatefulWidget {
|
||||
/// closed elsewhere during the gap must not stay invisible until Refresh.
|
||||
final int syncToken;
|
||||
|
||||
/// Reports the loaded rows after a frame. The destination resolves a routed
|
||||
/// session id (a deep link) from them, so that conversation gets the same
|
||||
/// title and model facts as a tapped row without a second list request.
|
||||
final ValueChanged<List<JsonMap>>? onSessions;
|
||||
|
||||
/// Overrides the device-local hidden/read store in tests.
|
||||
final ChatSessionLocalStore? localStore;
|
||||
|
||||
@@ -48,6 +54,22 @@ class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
|
||||
final _search = TextEditingController();
|
||||
Timer? _undoTimer;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_controller.addListener(_reportSessions);
|
||||
}
|
||||
|
||||
/// Reports the loaded rows at the end of the frame: the destination learns a
|
||||
/// routed row without this screen calling back inside its own build.
|
||||
void _reportSessions() {
|
||||
if (widget.onSessions == null) return;
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (!mounted) return;
|
||||
widget.onSessions?.call(_controller.sessions);
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(covariant ChatSessionsScreen oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
@@ -61,6 +83,7 @@ class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
|
||||
@override
|
||||
void dispose() {
|
||||
_undoTimer?.cancel();
|
||||
_controller.removeListener(_reportSessions);
|
||||
_controller.dispose();
|
||||
_search.dispose();
|
||||
super.dispose();
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
# Chat model picker (native model control)
|
||||
|
||||
The conversation header shows a model control for backends with a verified
|
||||
catalog and switch path (`""`, `opencode`, `codex`), matching
|
||||
`web/src/chatModels.js`. Files:
|
||||
|
||||
- `lib/features/chat/conversation/chat_models.dart` — the web's model helpers:
|
||||
`supportsChatModels`, `chatModelLabel` (recorded model or `Model`, plus
|
||||
` · next turn` while `model_selection == next_turn`),
|
||||
`chatModelSelectionNote` (both backend sentences verbatim), display name with
|
||||
the id fallback, and `filterChatModels` (case-insensitive over name, id and
|
||||
provider, server order kept, blank query keeps the catalog).
|
||||
- `lib/features/chat/conversation/chat_model_control.dart` — the header control.
|
||||
It reads its current facts from the opened row and adopts a replaced row in
|
||||
`didUpdateWidget`; the server echo after an accepted switch is reported to the
|
||||
destination through `onModelChanged`.
|
||||
- `lib/features/chat/conversation/chat_model_chooser.dart` — `SimpleDialog`
|
||||
(Material) or `CupertinoActionSheet` (Cupertino) with the web's `Search models`
|
||||
field, loading/error/empty/no-match states, the check mark and `selected`
|
||||
semantics on the current row, and Cancel. A refusal keeps the chooser open and
|
||||
shows the server's reason. Acceptance applies the server's `chat_model` echo
|
||||
(provider/model/selection) and is reported even when the chooser was dismissed
|
||||
while the request was in flight — the server has already applied it.
|
||||
|
||||
The wire exchange is the web's: `{"chat_query":{"session_id":"…"}}` then
|
||||
`{"chat_model":{"session_id":"…","provider":"…","model":"…"}}` (trimmed). The
|
||||
repository parser treats `chat_models` as the server's list (`[]ChatModel`),
|
||||
returns an empty catalog for a missing/malformed field, and refuses a blank
|
||||
session id.
|
||||
|
||||
`ChatScreen` keeps the row it opened (`_openedSessions`) and the accepted model
|
||||
per session (`_acceptedModels`), so Back then reopening the same row shows the
|
||||
model the server accepted even when the list row still carries the old value.
|
||||
`ChatSessionsScreen.onSessions` reports its loaded rows after a frame, which is
|
||||
how a `/chat/:id` deep link gets the same title and model facts as a tapped row
|
||||
without a second `chat_sessions` request.
|
||||
|
||||
## Checks run for this slice
|
||||
|
||||
`flutter test test/features/chat` (274 passed), `flutter test` (1406 passed),
|
||||
`flutter analyze` (no issues), `flutter build web` (built), `dart format
|
||||
--set-exit-if-changed` on the touched files (0 changed), `git diff --check`
|
||||
(clean).
|
||||
|
||||
`test/features/chat/conversation/chat_model_picker_test.dart` — 16 tests: exact
|
||||
request bodies, refusal, server echo, initial next-turn suffix, provider match
|
||||
on duplicate ids, search and no-match on both hosts, absent control for an
|
||||
unsupported backend, catalog failure, cancel during an in-flight switch, row
|
||||
replacement, and 320px/2x layout.
|
||||
|
||||
`test/features/chat/chat_screen_model_test.dart` — 3 tests: accepted switch
|
||||
survives Back and reopening from the unchanged list row, `/chat/:id` resolves
|
||||
the loaded row (one `chat_sessions` request), and an unsupported backend shows
|
||||
no control. Both regression tests were confirmed to fail with the fix removed
|
||||
before restoring it.
|
||||
|
||||
No browser capture is claimed here, and mobile remains unverified: this lane
|
||||
develops and tests the web target only.
|
||||
@@ -254,6 +254,15 @@ void main() {
|
||||
});
|
||||
await repo.selectModel('s', 'provider', 'model');
|
||||
expect(gateway.calls.last.type, 'chat_model');
|
||||
gateway.calls.clear();
|
||||
await repo.selectModel(' s ', ' provider ', ' model ');
|
||||
expect(gateway.calls.single.fields, {
|
||||
'chat_model': {
|
||||
'session_id': 's',
|
||||
'provider': 'provider',
|
||||
'model': 'model',
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
test('rejects invalid permissions and prompts before sending', () async {
|
||||
@@ -272,21 +281,26 @@ void main() {
|
||||
expect(gateway.calls, isEmpty);
|
||||
});
|
||||
test(
|
||||
'uses the server model catalog object and default history limit',
|
||||
'uses the server model catalog list and default history limit',
|
||||
() async {
|
||||
gateway.reply = {
|
||||
'chat_models': {
|
||||
'providers': {
|
||||
'p': ['m'],
|
||||
},
|
||||
},
|
||||
'chat_models': [
|
||||
{'id': 'm', 'provider': 'p', 'name': 'Model'},
|
||||
],
|
||||
};
|
||||
expect((await repo.models('s'))['providers'], {
|
||||
'p': ['m'],
|
||||
});
|
||||
final models = await repo.models('s');
|
||||
expect(models.single['id'], 'm');
|
||||
expect(models.single['provider'], 'p');
|
||||
expect(gateway.calls.single.fields, {
|
||||
'chat_query': {'session_id': 's'},
|
||||
});
|
||||
// A malformed catalog is empty, never invented rows, and a blank
|
||||
// session id is refused before any request is sent.
|
||||
gateway.reply = {'chat_models': 'not-a-list'};
|
||||
expect(await repo.models('s'), isEmpty);
|
||||
gateway.calls.clear();
|
||||
await expectLater(repo.models(' '), throwsArgumentError);
|
||||
expect(gateway.calls, isEmpty);
|
||||
gateway.calls.clear();
|
||||
await repo.history('s');
|
||||
expect(gateway.calls.single.fields['chat_query']['limit'], 200);
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/core/api_gateway.dart';
|
||||
import 'package:pipelines_app/features/chat/screen.dart';
|
||||
|
||||
/// A chat destination gateway: one listed session whose harness offers models.
|
||||
class _ScreenGateway implements ApiGateway {
|
||||
final calls = <({String type, JsonMap fields})>[];
|
||||
|
||||
List<JsonMap> sessions = [
|
||||
{
|
||||
'id': 's',
|
||||
'title': 'Wire chat',
|
||||
'backend': 'opencode',
|
||||
'model': 'model-a',
|
||||
'model_provider': 'p1',
|
||||
},
|
||||
];
|
||||
|
||||
JsonMap switchReply = const {
|
||||
'chat_model': {'session_id': 's', 'provider': 'p2', 'model': 'model-b'},
|
||||
};
|
||||
|
||||
@override
|
||||
Stream<JsonMap> get frames => const Stream.empty();
|
||||
|
||||
@override
|
||||
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
|
||||
calls.add((type: type, fields: fields));
|
||||
switch (type) {
|
||||
case 'chat_sessions':
|
||||
return {'chat_sessions': sessions};
|
||||
case 'chat_subscribe':
|
||||
return <String, dynamic>{};
|
||||
case 'chat_messages':
|
||||
return {
|
||||
'chat_history': {
|
||||
'messages': const [],
|
||||
'next_cursor': '',
|
||||
'has_more': false,
|
||||
},
|
||||
};
|
||||
case 'chat_models':
|
||||
return const {
|
||||
'chat_models': [
|
||||
{'id': 'model-a', 'provider': 'p1', 'name': 'Model Alpha'},
|
||||
{'id': 'model-b', 'provider': 'p2', 'name': 'Model Beta'},
|
||||
],
|
||||
};
|
||||
case 'chat_model':
|
||||
return switchReply;
|
||||
}
|
||||
return <String, dynamic>{};
|
||||
}
|
||||
|
||||
int count(String type) => calls.where((call) => call.type == type).length;
|
||||
}
|
||||
|
||||
Future<void> _pumpScreen(
|
||||
WidgetTester tester,
|
||||
_ScreenGateway gateway, {
|
||||
String? initialSessionId,
|
||||
}) async {
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
theme: ThemeData(platform: TargetPlatform.android),
|
||||
home: Scaffold(
|
||||
body: ChatScreen(gateway: gateway, initialSessionId: initialSessionId),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
|
||||
void main() {
|
||||
testWidgets('an accepted switch survives leaving and reopening the chat', (
|
||||
tester,
|
||||
) async {
|
||||
final gateway = _ScreenGateway();
|
||||
await _pumpScreen(tester, gateway);
|
||||
|
||||
await tester.tap(find.byKey(const Key('chat-row-s')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('model-a'), findsOneWidget);
|
||||
|
||||
await tester.tap(find.byKey(const Key('chat-model')));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text('Model Beta'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('model-b'), findsOneWidget);
|
||||
|
||||
await tester.tap(find.text('Back to chats'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('model-b'), findsNothing);
|
||||
|
||||
// The list still carries the row it read before the switch; reopening must
|
||||
// still show the model the server accepted.
|
||||
await tester.tap(find.byKey(const Key('chat-row-s')));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('model-b'), findsOneWidget);
|
||||
expect(find.text('model-a'), findsNothing);
|
||||
|
||||
await tester.tap(find.byKey(const Key('chat-model')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(
|
||||
find.descendant(
|
||||
of: find.byKey(const Key('chat-model-option-p2/model-b')),
|
||||
matching: find.byIcon(Icons.check),
|
||||
),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(
|
||||
find.descendant(
|
||||
of: find.byKey(const Key('chat-model-option-p1/model-a')),
|
||||
matching: find.byIcon(Icons.check),
|
||||
),
|
||||
findsNothing,
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets('a routed chat resolves its row from the loaded list', (
|
||||
tester,
|
||||
) async {
|
||||
final gateway = _ScreenGateway();
|
||||
await _pumpScreen(tester, gateway, initialSessionId: 's');
|
||||
|
||||
// The deep link opened before any row was tapped: the list's own read
|
||||
// supplies the title and the recorded model, with no second list request.
|
||||
expect(find.text('Wire chat'), findsOneWidget);
|
||||
expect(find.text('model-a'), findsOneWidget);
|
||||
expect(find.byKey(const Key('chat-model')), findsOneWidget);
|
||||
expect(gateway.count('chat_sessions'), 1);
|
||||
|
||||
await tester.tap(find.byKey(const Key('chat-model')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(gateway.calls.last.type, 'chat_models');
|
||||
expect(gateway.calls.last.fields, {
|
||||
'chat_query': {'session_id': 's'},
|
||||
});
|
||||
|
||||
await tester.tap(find.text('Model Beta'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(gateway.calls.last.fields, {
|
||||
'chat_model': {'session_id': 's', 'provider': 'p2', 'model': 'model-b'},
|
||||
});
|
||||
expect(find.text('model-b'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'a routed chat on a harness without model switching stays plain',
|
||||
(tester) async {
|
||||
final gateway = _ScreenGateway()
|
||||
..sessions = [
|
||||
{'id': 's', 'title': 'Wire chat', 'backend': 'claude'},
|
||||
];
|
||||
await _pumpScreen(tester, gateway, initialSessionId: 's');
|
||||
|
||||
expect(find.text('Wire chat'), findsOneWidget);
|
||||
expect(find.byKey(const Key('chat-model')), findsNothing);
|
||||
expect(gateway.count('chat_models'), 0);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,472 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/core/api_gateway.dart';
|
||||
import 'package:pipelines_app/core/transport/connection_state.dart';
|
||||
import 'package:pipelines_app/features/chat/conversation/chat_models.dart';
|
||||
import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart';
|
||||
|
||||
/// A chat thread gateway with scripted model catalog and switch replies.
|
||||
class _ModelGateway implements ApiGateway {
|
||||
final calls = <({String type, JsonMap fields})>[];
|
||||
|
||||
JsonMap modelsReply = const {'chat_models': []};
|
||||
JsonMap switchReply = const {};
|
||||
String? switchRefusal;
|
||||
String? modelsRefusal;
|
||||
|
||||
/// Holds a `chat_model` reply until the test completes it.
|
||||
Completer<void>? switchGate;
|
||||
|
||||
@override
|
||||
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
|
||||
calls.add((type: type, fields: fields));
|
||||
switch (type) {
|
||||
case 'chat_subscribe':
|
||||
return <String, dynamic>{};
|
||||
case 'chat_messages':
|
||||
return {
|
||||
'chat_history': {
|
||||
'messages': const [],
|
||||
'next_cursor': '',
|
||||
'has_more': false,
|
||||
},
|
||||
};
|
||||
case 'chat_models':
|
||||
final refusal = modelsRefusal;
|
||||
if (refusal != null) throw ProtocolError(refusal);
|
||||
return modelsReply;
|
||||
case 'chat_model':
|
||||
final refusal = switchRefusal;
|
||||
if (refusal != null) throw ProtocolError(refusal);
|
||||
final gate = switchGate;
|
||||
if (gate != null) await gate.future;
|
||||
return switchReply;
|
||||
}
|
||||
return <String, dynamic>{};
|
||||
}
|
||||
|
||||
@override
|
||||
Stream<JsonMap> get frames => const Stream.empty();
|
||||
|
||||
JsonMap? lastFields(String type) {
|
||||
for (final call in calls.reversed) {
|
||||
if (call.type == type) return call.fields;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Widget _host(Widget child) => MaterialApp(
|
||||
theme: ThemeData(platform: TargetPlatform.android),
|
||||
home: Scaffold(body: child),
|
||||
);
|
||||
|
||||
Widget _cupertinoHost(Widget child) => CupertinoApp(
|
||||
theme: const CupertinoThemeData(brightness: Brightness.dark),
|
||||
home: CupertinoPageScaffold(child: child),
|
||||
);
|
||||
|
||||
const _session = <String, dynamic>{
|
||||
'id': 's',
|
||||
'backend': 'opencode',
|
||||
'model': 'model-a',
|
||||
'model_provider': 'p1',
|
||||
};
|
||||
|
||||
/// The same opened row with some recorded facts replaced.
|
||||
JsonMap _withSession(Map<String, dynamic> changes) => {..._session, ...changes};
|
||||
|
||||
Future<void> _openThread(
|
||||
WidgetTester tester,
|
||||
_ModelGateway gateway, {
|
||||
bool cupertino = false,
|
||||
JsonMap session = _session,
|
||||
ValueChanged<ChatModelSelection>? onChanged,
|
||||
}) async {
|
||||
final thread = ChatThreadView(
|
||||
gateway: gateway,
|
||||
sessionId: 's',
|
||||
session: session,
|
||||
onBack: () {},
|
||||
onModelChanged: onChanged,
|
||||
);
|
||||
await tester.pumpWidget(cupertino ? _cupertinoHost(thread) : _host(thread));
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
|
||||
Future<void> _openChooser(WidgetTester tester) async {
|
||||
await tester.tap(find.byKey(const Key('chat-model')));
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
|
||||
const _catalog = <String, dynamic>{
|
||||
'chat_models': [
|
||||
{'id': 'model-a', 'provider': 'p1', 'name': 'Model Alpha'},
|
||||
{'id': 'model-b', 'provider': 'p2', 'name': 'Model Beta'},
|
||||
],
|
||||
};
|
||||
|
||||
void main() {
|
||||
testWidgets('shows the recorded model and sends the web model requests', (
|
||||
tester,
|
||||
) async {
|
||||
final gateway = _ModelGateway()
|
||||
..modelsReply = _catalog
|
||||
..switchReply = const {
|
||||
'chat_model': {'session_id': 's', 'provider': 'p2', 'model': 'model-b'},
|
||||
};
|
||||
await _openThread(tester, gateway);
|
||||
|
||||
expect(find.text('model-a'), findsOneWidget);
|
||||
|
||||
await _openChooser(tester);
|
||||
|
||||
expect(find.text('Change model'), findsOneWidget);
|
||||
expect(find.text('Applies to the next turn in this chat.'), findsOneWidget);
|
||||
expect(find.text('Model Alpha'), findsOneWidget);
|
||||
expect(find.text('Model Beta'), findsOneWidget);
|
||||
expect(gateway.lastFields('chat_models'), {
|
||||
'chat_query': {'session_id': 's'},
|
||||
});
|
||||
|
||||
await tester.tap(find.text('Model Beta'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(gateway.lastFields('chat_model'), {
|
||||
'chat_model': {'session_id': 's', 'provider': 'p2', 'model': 'model-b'},
|
||||
});
|
||||
expect(find.byKey(const Key('chat-model-chooser')), findsNothing);
|
||||
expect(find.text('model-b'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('a refusal keeps the previous model and shows the reason', (
|
||||
tester,
|
||||
) async {
|
||||
final gateway = _ModelGateway()
|
||||
..modelsReply = _catalog
|
||||
..switchRefusal = 'This harness does not support changing models.';
|
||||
await _openThread(tester, gateway);
|
||||
|
||||
await _openChooser(tester);
|
||||
await tester.tap(find.text('Model Beta'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(
|
||||
find.text('This harness does not support changing models.'),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(find.byKey(const Key('chat-model-chooser')), findsOneWidget);
|
||||
expect(find.text('model-a'), findsOneWidget);
|
||||
|
||||
await tester.tap(find.byKey(const Key('chat-model-cancel')));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.byKey(const Key('chat-model-chooser')), findsNothing);
|
||||
expect(find.text('model-a'), findsOneWidget);
|
||||
expect(find.text('model-b'), findsNothing);
|
||||
});
|
||||
|
||||
for (final cupertino in [false, true]) {
|
||||
testWidgets('an accepted switch shows the server-reported model '
|
||||
'(${cupertino ? 'cupertino' : 'material'})', (tester) async {
|
||||
final gateway = _ModelGateway()
|
||||
..modelsReply = _catalog
|
||||
..switchReply = const {
|
||||
'chat_model': {
|
||||
'session_id': 's',
|
||||
'provider': 'p2',
|
||||
'model': 'server-reported-model',
|
||||
'selection': 'next_turn',
|
||||
},
|
||||
};
|
||||
await _openThread(tester, gateway, cupertino: cupertino);
|
||||
|
||||
await _openChooser(tester);
|
||||
await tester.tap(find.text('Model Beta'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('server-reported-model · next turn'), findsOneWidget);
|
||||
expect(tester.takeException(), isNull);
|
||||
if (cupertino) {
|
||||
expect(find.byType(Material), findsNothing);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
testWidgets('lists only the server catalog and reports an empty one', (
|
||||
tester,
|
||||
) async {
|
||||
final gateway = _ModelGateway()
|
||||
..modelsReply = const {
|
||||
'chat_models': [
|
||||
{'id': 'only-recorded', 'provider': 'p1'},
|
||||
],
|
||||
};
|
||||
await _openThread(tester, gateway);
|
||||
|
||||
await _openChooser(tester);
|
||||
|
||||
expect(find.text('only-recorded'), findsOneWidget);
|
||||
expect(find.text('Model Alpha'), findsNothing);
|
||||
expect(find.text('Model Beta'), findsNothing);
|
||||
|
||||
await tester.tap(find.byKey(const Key('chat-model-cancel')));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
gateway.modelsReply = const {'chat_models': []};
|
||||
await _openChooser(tester);
|
||||
|
||||
expect(find.text('No models are available for this chat.'), findsOneWidget);
|
||||
expect(find.text('only-recorded'), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('reports the accepted server echo to the conversation', (
|
||||
tester,
|
||||
) async {
|
||||
final reported = <ChatModelSelection>[];
|
||||
final gateway = _ModelGateway()
|
||||
..modelsReply = _catalog
|
||||
..switchReply = const {
|
||||
'chat_model': {
|
||||
'session_id': 's',
|
||||
'provider': 'p2',
|
||||
'model': 'server-reported-model',
|
||||
'selection': 'next_turn',
|
||||
},
|
||||
};
|
||||
await _openThread(tester, gateway, onChanged: reported.add);
|
||||
|
||||
await _openChooser(tester);
|
||||
await tester.tap(find.text('Model Beta'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// The server's echo, not the tapped row (`model-b`).
|
||||
expect(reported, [
|
||||
(provider: 'p2', model: 'server-reported-model', selection: 'next_turn'),
|
||||
]);
|
||||
});
|
||||
|
||||
testWidgets('shows the recorded next-turn selection before any switch', (
|
||||
tester,
|
||||
) async {
|
||||
final gateway = _ModelGateway()..modelsReply = _catalog;
|
||||
await _openThread(
|
||||
tester,
|
||||
gateway,
|
||||
session: _withSession({'model_selection': 'next_turn'}),
|
||||
);
|
||||
|
||||
expect(find.text('model-a · next turn'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('adopts a row the destination replaced after an accepted switch', (
|
||||
tester,
|
||||
) async {
|
||||
final gateway = _ModelGateway()..modelsReply = _catalog;
|
||||
final thread = ChatThreadView(
|
||||
gateway: gateway,
|
||||
sessionId: 's',
|
||||
session: _session,
|
||||
onBack: () {},
|
||||
);
|
||||
await tester.pumpWidget(_host(thread));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('model-a'), findsOneWidget);
|
||||
|
||||
await tester.pumpWidget(
|
||||
_host(
|
||||
ChatThreadView(
|
||||
gateway: gateway,
|
||||
sessionId: 's',
|
||||
session: _withSession({
|
||||
'model': 'model-b',
|
||||
'model_provider': 'p2',
|
||||
'model_selection': 'next_turn',
|
||||
}),
|
||||
onBack: () {},
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('model-b · next turn'), findsOneWidget);
|
||||
expect(find.text('model-a'), findsNothing);
|
||||
|
||||
// The chooser marks the replaced row, not the one this control first read.
|
||||
await _openChooser(tester);
|
||||
expect(
|
||||
find.descendant(
|
||||
of: find.byKey(const Key('chat-model-option-p2/model-b')),
|
||||
matching: find.byIcon(Icons.check),
|
||||
),
|
||||
findsOneWidget,
|
||||
);
|
||||
});
|
||||
|
||||
for (final cupertino in [false, true]) {
|
||||
testWidgets('searches the catalog by name, id and provider '
|
||||
'(${cupertino ? 'cupertino' : 'material'})', (tester) async {
|
||||
final gateway = _ModelGateway()..modelsReply = _catalog;
|
||||
await _openThread(tester, gateway, cupertino: cupertino);
|
||||
await _openChooser(tester);
|
||||
|
||||
final search = find.byKey(const Key('chat-model-search'));
|
||||
expect(search, findsOneWidget);
|
||||
|
||||
await tester.enterText(search, 'beta');
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('Model Beta'), findsOneWidget);
|
||||
expect(find.text('Model Alpha'), findsNothing);
|
||||
|
||||
await tester.enterText(search, 'P1');
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('Model Alpha'), findsOneWidget);
|
||||
expect(find.text('Model Beta'), findsNothing);
|
||||
|
||||
await tester.enterText(search, 'zzz');
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('No models match "zzz".'), findsOneWidget);
|
||||
expect(find.text('Model Alpha'), findsNothing);
|
||||
expect(find.text('Model Beta'), findsNothing);
|
||||
|
||||
await tester.enterText(search, '');
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('Model Alpha'), findsOneWidget);
|
||||
expect(find.text('Model Beta'), findsOneWidget);
|
||||
expect(find.text('No models match "zzz".'), findsNothing);
|
||||
});
|
||||
}
|
||||
|
||||
testWidgets('marks the current row by id and provider when ids repeat', (
|
||||
tester,
|
||||
) async {
|
||||
final gateway = _ModelGateway()
|
||||
..modelsReply = const {
|
||||
'chat_models': [
|
||||
{'id': 'shared', 'provider': 'p1', 'name': 'One'},
|
||||
{'id': 'shared', 'provider': 'p2', 'name': 'Two'},
|
||||
],
|
||||
};
|
||||
await _openThread(
|
||||
tester,
|
||||
gateway,
|
||||
session: _withSession({'model': 'shared', 'model_provider': 'p2'}),
|
||||
);
|
||||
await _openChooser(tester);
|
||||
|
||||
expect(
|
||||
find.descendant(
|
||||
of: find.byKey(const Key('chat-model-option-p2/shared')),
|
||||
matching: find.byIcon(Icons.check),
|
||||
),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(
|
||||
find.descendant(
|
||||
of: find.byKey(const Key('chat-model-option-p1/shared')),
|
||||
matching: find.byIcon(Icons.check),
|
||||
),
|
||||
findsNothing,
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets('shows no control for a harness without model switching', (
|
||||
tester,
|
||||
) async {
|
||||
final gateway = _ModelGateway()..modelsReply = _catalog;
|
||||
await _openThread(
|
||||
tester,
|
||||
gateway,
|
||||
session: _withSession({'backend': 'claude'}),
|
||||
);
|
||||
|
||||
expect(find.byKey(const Key('chat-model')), findsNothing);
|
||||
expect(gateway.lastFields('chat_models'), isNull);
|
||||
});
|
||||
|
||||
testWidgets('reports a catalog failure and keeps the recorded model', (
|
||||
tester,
|
||||
) async {
|
||||
final gateway = _ModelGateway()
|
||||
..modelsRefusal = 'The harness is not running.';
|
||||
await _openThread(tester, gateway);
|
||||
|
||||
await _openChooser(tester);
|
||||
|
||||
expect(find.text('The harness is not running.'), findsOneWidget);
|
||||
expect(find.byKey(const Key('chat-model-error')), findsOneWidget);
|
||||
expect(find.text('No models are available for this chat.'), findsNothing);
|
||||
|
||||
await tester.tap(find.byKey(const Key('chat-model-cancel')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('model-a'), findsOneWidget);
|
||||
});
|
||||
|
||||
for (final cupertino in [false, true]) {
|
||||
testWidgets('the chooser fits the smallest surface at 2x text '
|
||||
'(${cupertino ? 'cupertino' : 'material'})', (tester) async {
|
||||
tester.view.physicalSize = const Size(320, 640);
|
||||
tester.view.devicePixelRatio = 1;
|
||||
tester.platformDispatcher.textScaleFactorTestValue = 2;
|
||||
addTearDown(tester.view.resetPhysicalSize);
|
||||
addTearDown(tester.view.resetDevicePixelRatio);
|
||||
addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
|
||||
|
||||
final gateway = _ModelGateway()
|
||||
..modelsReply = {
|
||||
'chat_models': [
|
||||
for (var index = 1; index <= 6; index++)
|
||||
{
|
||||
'id': 'model-$index',
|
||||
'provider': 'provider-$index',
|
||||
'name': 'Model number $index with a longer name',
|
||||
},
|
||||
],
|
||||
};
|
||||
await _openThread(tester, gateway, cupertino: cupertino);
|
||||
await _openChooser(tester);
|
||||
|
||||
expect(find.byKey(const Key('chat-model-chooser')), findsOneWidget);
|
||||
expect(find.byKey(const Key('chat-model-search')), findsOneWidget);
|
||||
expect(tester.takeException(), isNull);
|
||||
if (!cupertino) {
|
||||
// Every row is built inside the dialog's own scroll view.
|
||||
expect(find.textContaining('Model number 6'), findsOneWidget);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
testWidgets('an accepted switch applies after the chooser was dismissed', (
|
||||
tester,
|
||||
) async {
|
||||
final reported = <ChatModelSelection>[];
|
||||
final gateway = _ModelGateway()
|
||||
..modelsReply = _catalog
|
||||
..switchReply = const {
|
||||
'chat_model': {'session_id': 's', 'provider': 'p2', 'model': 'model-b'},
|
||||
}
|
||||
..switchGate = Completer<void>();
|
||||
await _openThread(tester, gateway, onChanged: reported.add);
|
||||
|
||||
await _openChooser(tester);
|
||||
await tester.tap(find.text('Model Beta'));
|
||||
await tester.pump();
|
||||
|
||||
// The switch is in flight, so the operator can still dismiss the chooser.
|
||||
await tester.tap(find.byKey(const Key('chat-model-cancel')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byKey(const Key('chat-model-chooser')), findsNothing);
|
||||
expect(find.text('model-a'), findsOneWidget);
|
||||
|
||||
gateway.switchGate!.complete();
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// The server applied the switch; the conversation reports it rather than
|
||||
// silently dropping it with the dismissed dialog.
|
||||
expect(find.text('model-b'), findsOneWidget);
|
||||
expect(reported.single.model, 'model-b');
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user