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:
2026-10-22 12:28:13 +01:00
parent 81b2805cdd
commit 2a66be7b27
11 changed files with 1415 additions and 30 deletions
@@ -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');
});
}