diff --git a/app/lib/features/chat/conversation/chat_effort_control.dart b/app/lib/features/chat/conversation/chat_effort_control.dart new file mode 100644 index 00000000..08cecfc8 --- /dev/null +++ b/app/lib/features/chat/conversation/chat_effort_control.dart @@ -0,0 +1,215 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../../../core/error_reason.dart'; +import '../ui/sessions/chat_adaptive.dart'; +import 'chat_bar_control_style.dart'; +import 'chat_effort_sheet.dart'; +import 'chat_efforts.dart'; +import 'chat_models.dart'; + +/// The conversation bar's thinking-level control ("Thinking: High"). +/// +/// It shows the levels the session row names for the chat's model without a +/// request of its own. Material opens a menu and Cupertino an action sheet of +/// those levels; choosing one sends `chat_effort` through the chat's own +/// gateway. The level applies from the next turn: while a turn runs, the +/// choices say so and the label marks the new level "next turn". A model with +/// no levels (or a harness without them) shows no control. After the model +/// changes, the levels are re-read from that model's `chat_models` reply. +class ChatEffortControl extends StatefulWidget { + const ChatEffortControl({ + super.key, + required this.gateway, + required this.sessionId, + required this.session, + this.running = false, + this.onChanged, + this.showLabel = false, + }); + + final ApiGateway gateway; + final String sessionId; + + /// The opened row: `effort`, `efforts`, `default_effort` and its model. + final JsonMap session; + + /// Whether the chat's turn is running now. + final bool running; + + /// The server's echo after an accepted level. + final ValueChanged? onChanged; + final bool showLabel; + + @override + State createState() => _ChatEffortControlState(); +} + +class _ChatEffortControlState extends State { + late ChatEffortState _state = ChatEffortState.fromJson(widget.session); + bool _nextTurn = false; + int _reads = 0; + + @override + void didUpdateWidget(covariant ChatEffortControl oldWidget) { + super.didUpdateWidget(oldWidget); + if (!widget.running) _nextTurn = false; + final row = ChatEffortState.fromJson(widget.session); + if (row.signature != + ChatEffortState.fromJson(oldWidget.session).signature) { + _state = row; + } else if (chatModelRecordedFacts(oldWidget.session) != + chatModelRecordedFacts(widget.session)) { + unawaited(_reread()); + } + } + + /// A model switch keeps the row's old levels; ask the server for the new + /// model's. A refusal keeps the shown levels rather than inventing any. + Future _reread() async { + final read = ++_reads; + try { + final state = await readChatEffort(widget.gateway, widget.sessionId); + if (!mounted || read != _reads) return; + setState(() => _state = state); + widget.onChanged?.call(state); + } catch (_) {} + } + + Future _choose(ChatEffortLevel level) async { + final running = widget.running; + final applied = await selectChatEffort( + widget.gateway, + widget.sessionId, + level.id, + ); + widget.onChanged?.call(applied); + if (!mounted) return; + setState(() { + _state = applied; + _nextTurn = running; + }); + } + + Future _chooseFromMenu(ChatEffortLevel level) async { + if (level.id == _state.effort) return; + try { + await _choose(level); + } catch (error) { + if (!mounted) return; + ScaffoldMessenger.maybeOf(context)?.showSnackBar( + SnackBar( + content: Text( + describeErrorReason( + error, + fallback: 'The thinking level was not changed.', + ), + ), + ), + ); + } + } + + Future _openSheet() => showCupertinoModalPopup( + context: context, + builder: (_) => ChatEffortSheet( + state: _state, + running: widget.running, + choose: _choose, + ), + ); + + @override + Widget build(BuildContext context) { + if (!_state.supported) return const SizedBox.shrink(); + final cupertino = + chatControlsStyleOf(context) == ChatControlsStyle.cupertino; + final label = + '${chatEffortLabel(_state)}${_nextTurn ? ' · next turn' : ''}'; + final iconOnly = + !widget.showLabel && MediaQuery.sizeOf(context).width < 600; + final content = Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(cupertino ? CupertinoIcons.lightbulb : Icons.psychology_outlined), + if (!iconOnly) ...[ + const SizedBox(width: 4), + Flexible(child: Text(label, overflow: TextOverflow.ellipsis)), + ], + ], + ); + const key = Key('chat-effort'); + if (cupertino) { + return Semantics( + container: true, + button: true, + label: 'Change thinking level, currently ${_state.currentName}', + onTap: _openSheet, + child: ExcludeSemantics( + child: CupertinoButton( + key: key, + padding: const EdgeInsets.symmetric(horizontal: 8), + onPressed: _openSheet, + child: chatBarCupertinoContent(context, content), + ), + ), + ); + } + return MenuAnchor( + menuChildren: [ + Padding( + padding: const EdgeInsets.fromLTRB(12, 8, 12, 4), + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 280), + child: Text( + chatEffortNote(running: widget.running), + key: const Key('chat-effort-note'), + style: Theme.of(context).textTheme.bodySmall, + ), + ), + ), + for (final level in _state.levels) + MenuItemButton( + key: ValueKey('chat-effort-option-${level.id}'), + trailingIcon: level.id == _state.current + ? const Icon(Icons.check) + : null, + onPressed: () => unawaited(_chooseFromMenu(level)), + child: level.description.isEmpty + ? Text(level.name) + : Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text(level.name), + Text( + level.description, + style: Theme.of(context).textTheme.bodySmall, + ), + ], + ), + ), + ], + builder: (context, menu, _) => Semantics( + container: true, + button: true, + label: 'Change thinking level, currently ${_state.currentName}', + onTap: () => menu.isOpen ? menu.close() : menu.open(), + child: ExcludeSemantics( + child: Tooltip( + message: 'Change thinking level (currently ${_state.currentName})', + child: TextButton( + key: key, + style: chatBarTextButtonStyle(context), + onPressed: () => menu.isOpen ? menu.close() : menu.open(), + child: content, + ), + ), + ), + ), + ); + } +} diff --git a/app/lib/features/chat/conversation/chat_effort_sheet.dart b/app/lib/features/chat/conversation/chat_effort_sheet.dart new file mode 100644 index 00000000..47075397 --- /dev/null +++ b/app/lib/features/chat/conversation/chat_effort_sheet.dart @@ -0,0 +1,101 @@ +import 'package:flutter/cupertino.dart'; + +import '../../../core/error_reason.dart'; +import 'chat_efforts.dart'; + +/// The Cupertino action sheet of a chat's thinking levels, the current one +/// checked. It stays open with the server's reason when a choice is refused +/// and closes once one is accepted. +class ChatEffortSheet extends StatefulWidget { + const ChatEffortSheet({ + super.key, + required this.state, + required this.running, + required this.choose, + }); + + final ChatEffortState state; + final bool running; + final Future Function(ChatEffortLevel level) choose; + + @override + State createState() => _ChatEffortSheetState(); +} + +class _ChatEffortSheetState extends State { + bool _busy = false; + String? _error; + + Future _choose(ChatEffortLevel level) async { + if (_busy) return; + if (level.id == widget.state.effort) { + Navigator.of(context).pop(); + return; + } + setState(() { + _busy = true; + _error = null; + }); + try { + await widget.choose(level); + if (mounted) Navigator.of(context).pop(); + } catch (error) { + if (!mounted) return; + setState(() { + _busy = false; + _error = describeErrorReason( + error, + fallback: 'The thinking level was not changed.', + ); + }); + } + } + + @override + Widget build(BuildContext context) { + final secondary = CupertinoColors.secondaryLabel.resolveFrom(context); + final error = _error; + return CupertinoActionSheet( + key: const Key('chat-effort-sheet'), + title: const Text('Thinking'), + message: Text( + error ?? chatEffortNote(running: widget.running), + key: const Key('chat-effort-note'), + style: error == null + ? null + : TextStyle(color: CupertinoColors.systemRed.resolveFrom(context)), + ), + actions: [ + for (final level in widget.state.levels) + CupertinoActionSheetAction( + key: ValueKey('chat-effort-option-${level.id}'), + onPressed: () => _choose(level), + child: Column( + children: [ + Row( + mainAxisSize: MainAxisSize.min, + children: [ + Flexible(child: Text(level.name)), + if (level.id == widget.state.current) ...[ + const SizedBox(width: 6), + const Icon(CupertinoIcons.checkmark_alt), + ], + ], + ), + if (level.description.isNotEmpty) + Text( + level.description, + textAlign: TextAlign.center, + style: TextStyle(fontSize: 13, color: secondary), + ), + ], + ), + ), + ], + cancelButton: CupertinoActionSheetAction( + onPressed: () => Navigator.of(context).pop(), + child: const Text('Cancel'), + ), + ); + } +} diff --git a/app/lib/features/chat/conversation/chat_efforts.dart b/app/lib/features/chat/conversation/chat_efforts.dart new file mode 100644 index 00000000..fb1ef97e --- /dev/null +++ b/app/lib/features/chat/conversation/chat_efforts.dart @@ -0,0 +1,116 @@ +import '../../../core/api_gateway.dart'; + +/// One thinking level the chat's model accepts, as its harness names it. +typedef ChatEffortLevel = ({String id, String name, String description}); + +/// A chat's thinking levels: the levels its current (or saved next-turn) +/// model accepts, the stored level (empty for the harness default) and the +/// level the harness uses when none was chosen, when it reports one. +/// +/// The server sends these on the session row (`effort`, `efforts`, +/// `default_effort`) and in a `chat_effort` reply or a `chat_models` reply's +/// `chat_effort` field. No levels means the model has none the harness can +/// set, so no control is shown. +class ChatEffortState { + const ChatEffortState({ + this.levels = const [], + this.effort = '', + this.defaultEffort = '', + }); + + /// Reads a session row or a `chat_effort` body. + factory ChatEffortState.fromJson(Object? value) { + if (value is! Map) return const ChatEffortState(); + final raw = value['efforts']; + final levels = []; + if (raw is List) { + for (final item in raw) { + if (item is! Map) continue; + final id = '${item['id'] ?? ''}'.trim(); + if (id.isEmpty || levels.any((level) => level.id == id)) continue; + final name = '${item['name'] ?? ''}'.trim(); + levels.add(( + id: id, + name: name.isEmpty ? id : name, + description: '${item['description'] ?? ''}'.trim(), + )); + } + } + return ChatEffortState( + levels: levels, + effort: '${value['effort'] ?? ''}'.trim(), + defaultEffort: '${value['default_effort'] ?? ''}'.trim(), + ); + } + + final List levels; + final String effort; + final String defaultEffort; + + bool get supported => levels.isNotEmpty; + + /// The level in effect: the stored one, else the harness default. + String get current => effort.isNotEmpty ? effort : defaultEffort; + + /// The current level's name, or "Default" when the harness did not say. + String get currentName { + for (final level in levels) { + if (level.id == current) return level.name; + } + return 'Default'; + } + + /// The facts the control displays, so an identical row never resets it. + String get signature => + '$effort\u0000$defaultEffort\u0000${levels.map((l) => l.id).join(',')}'; + + /// The row with this state folded in. + JsonMap applyTo(JsonMap row) => { + ...row, + 'effort': effort, + 'default_effort': defaultEffort, + 'efforts': [ + for (final level in levels) + { + 'id': level.id, + 'name': level.name, + if (level.description.isNotEmpty) 'description': level.description, + }, + ], + }; +} + +/// The header's label for [state]. +String chatEffortLabel(ChatEffortState state) => + 'Thinking: ${state.currentName}'; + +/// The note shown with the levels: the choice never changes a running turn. +String chatEffortNote({required bool running}) => running + ? 'A turn is running. The new level applies from the next turn you send.' + : 'Applies from the next turn you send.'; + +/// Sets the chat's level with `chat_effort` and returns the server's echo. +Future selectChatEffort( + ApiGateway gateway, + String sessionId, + String effort, +) async { + final session = sessionId.trim(); + if (session.isEmpty) throw ArgumentError('Select a chat session first.'); + final reply = await gateway.call('chat_effort', { + 'chat_effort': {'session_id': session, 'effort': effort.trim()}, + }); + return ChatEffortState.fromJson(reply['chat_effort']); +} + +/// Re-reads the chat's levels after its model changed, from the +/// `chat_models` reply's `chat_effort` field. +Future readChatEffort( + ApiGateway gateway, + String sessionId, +) async { + final reply = await gateway.call('chat_models', { + 'chat_query': {'session_id': sessionId.trim()}, + }); + return ChatEffortState.fromJson(reply['chat_effort']); +} diff --git a/app/lib/features/chat/conversation/chat_thread_view.dart b/app/lib/features/chat/conversation/chat_thread_view.dart index 7d1c7c07..d24ff72f 100644 --- a/app/lib/features/chat/conversation/chat_thread_view.dart +++ b/app/lib/features/chat/conversation/chat_thread_view.dart @@ -42,6 +42,8 @@ import 'chat_composer_bar.dart'; import 'chat_composer_controller.dart'; import 'chat_delivery_indicator.dart'; import 'chat_draft_store.dart'; +import 'chat_effort_control.dart'; +import 'chat_efforts.dart'; import 'chat_mode_control.dart'; import 'chat_model_control.dart'; import 'chat_models.dart'; @@ -94,6 +96,7 @@ class ChatThreadView extends StatefulWidget { this.session, this.onModelChanged, this.onModeChanged, + this.onEffortChanged, this.syncToken = 0, this.drafts, this.newOperationId, @@ -163,6 +166,9 @@ class ChatThreadView extends StatefulWidget { /// The accepted permission mode's id and name. final void Function(String mode, String name)? onModeChanged; + /// The accepted thinking level with its model's levels. + final ValueChanged? onEffortChanged; + /// Advances when the shared socket is replaced, keeping this selection. final int syncToken; @@ -1336,6 +1342,8 @@ class _ChatThreadViewState extends State { widget, inShellBar, canGoBack, + // The thinking control says when a turn is running. + _controller.running, ], () => _buildHeader(session, inShellBar, canGoBack, answeredBy)); } @@ -1411,6 +1419,16 @@ class _ChatThreadViewState extends State { answeredBy: answeredBy, ), if (hasMode) _modeControl(), + // Only a model with levels gets the control (and its pill). + if (session != null && ChatEffortState.fromJson(session).supported) + ChatEffortControl( + key: ValueKey('chat-effort-${widget.sessionId}'), + gateway: widget.gateway, + sessionId: widget.sessionId, + session: session, + running: _controller.running, + onChanged: widget.onEffortChanged, + ), ], ); } diff --git a/app/lib/features/chat/screen.dart b/app/lib/features/chat/screen.dart index 6326d970..3fcf98e9 100644 --- a/app/lib/features/chat/screen.dart +++ b/app/lib/features/chat/screen.dart @@ -22,6 +22,7 @@ import '../../core/servers/server_scope.dart'; import 'workspace/chat_workspace_binding.dart'; import 'workspace/chat_workspace_snapshot.dart'; import 'workspace/chat_workspace_store.dart'; +import 'conversation/chat_efforts.dart'; import 'conversation/chat_models.dart'; import 'conversation/chat_pane_picker.dart'; import 'conversation/chat_add_pane_picker.dart'; @@ -372,6 +373,14 @@ class _ChatScreenState extends State unawaited(_sessions.refresh()); } + /// An accepted thinking level updates the opened row like a mode switch. + void _effortChanged(String id, ChatEffortState state) { + final row = _openedSessions[id]; + if (!mounted || row == null) return; + setState(() => _openedSessions[id] = state.applyTo(row)); + unawaited(_sessions.refresh()); + } + /// The row to open for [id], with an accepted model folded in. @override JsonMap? _rowFor(String id) { @@ -468,6 +477,7 @@ class _ChatScreenState extends State onBack: onBack, onModelChanged: (applied) => _modelChanged(selected, applied), onModeChanged: (mode, name) => _modeChanged(selected, mode, name), + onEffortChanged: (state) => _effortChanged(selected, state), onNewSession: _startedNewSession, onSessionRenamed: (title) => _renamed(selected, title), onSessionClosed: () => _closed(selected), diff --git a/app/test/features/chat/conversation/chat_effort_control_test.dart b/app/test/features/chat/conversation/chat_effort_control_test.dart new file mode 100644 index 00000000..669b62b3 --- /dev/null +++ b/app/test/features/chat/conversation/chat_effort_control_test.dart @@ -0,0 +1,226 @@ +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/pipelines_client.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_effort_control.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_efforts.dart'; + +const _levels = [ + {'id': 'low', 'name': 'Low', 'description': 'Quick answers'}, + {'id': 'high', 'name': 'High'}, + {'id': 'xhigh', 'name': 'Extra high'}, +]; + +JsonMap _row({ + String effort = '', + String defaultEffort = 'high', + List levels = _levels, + String model = 'thinker', +}) => { + 'id': 's', + 'backend': 'codex', + 'model': model, + 'model_provider': 'openai', + 'effort': effort, + 'default_effort': defaultEffort, + 'efforts': levels, +}; + +class _EffortGateway implements ApiGateway { + _EffortGateway({this.refuse}); + + final String? refuse; + final requests = []; + JsonMap reread = const {}; + + @override + Stream get frames => const Stream.empty(); + + @override + Future call(String type, [JsonMap fields = const {}]) async { + requests.add({'type': type, ...fields}); + if (type == 'chat_effort') { + final refused = refuse; + if (refused != null) throw ProtocolError(refused); + final effort = '${(fields['chat_effort'] as Map)['effort']}'; + return { + 'chat_effort': { + 'session_id': 's', + 'effort': effort, + 'efforts': _levels, + 'default_effort': 'high', + }, + }; + } + if (type == 'chat_models') { + return {'chat_models': const [], 'chat_effort': reread}; + } + return {}; + } +} + +Widget _material( + ApiGateway gateway, + JsonMap row, { + bool running = false, + ValueChanged? onChanged, +}) => MaterialApp( + home: Scaffold( + appBar: AppBar( + actions: [ + ChatEffortControl( + gateway: gateway, + sessionId: 's', + session: row, + running: running, + onChanged: onChanged, + ), + ], + ), + ), +); + +void main() { + test('state reads a row and folds an echo back into it', () { + final state = ChatEffortState.fromJson(_row(effort: 'xhigh')); + expect(state.levels.map((level) => level.id), ['low', 'high', 'xhigh']); + expect(state.currentName, 'Extra high'); + expect(chatEffortLabel(ChatEffortState.fromJson(_row())), 'Thinking: High'); + expect( + chatEffortLabel(ChatEffortState.fromJson(_row(defaultEffort: ''))), + 'Thinking: Default', + ); + expect(ChatEffortState.fromJson({'efforts': 'bad'}).supported, isFalse); + final folded = state.applyTo({'id': 's', 'title': 'Chat'}); + expect(folded['title'], 'Chat'); + expect(ChatEffortState.fromJson(folded).signature, state.signature); + }); + + testWidgets("shows the row's level without a request and switches it", ( + tester, + ) async { + final gateway = _EffortGateway(); + final changes = []; + await tester.pumpWidget( + _material(gateway, _row(), onChanged: (s) => changes.add(s.effort)), + ); + await tester.pumpAndSettle(); + expect(find.text('Thinking: High'), findsOneWidget); + expect(gateway.requests, isEmpty); + + await tester.tap(find.byKey(const Key('chat-effort'))); + await tester.pumpAndSettle(); + expect(find.text('Applies from the next turn you send.'), findsOneWidget); + expect(find.text('Quick answers'), findsOneWidget); + await tester.tap(find.byKey(const ValueKey('chat-effort-option-low'))); + await tester.pumpAndSettle(); + expect(gateway.requests.single, { + 'type': 'chat_effort', + 'chat_effort': {'session_id': 's', 'effort': 'low'}, + }); + expect(find.text('Thinking: Low'), findsOneWidget); + expect(changes, ['low']); + }); + + testWidgets('a model or harness without levels shows no control', ( + tester, + ) async { + await tester.pumpWidget(_material(_EffortGateway(), _row(levels: []))); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('chat-effort')), findsNothing); + await tester.pumpWidget(_material(_EffortGateway(), {'id': 's'})); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('chat-effort')), findsNothing); + }); + + testWidgets('a running turn keeps its level and the label says so', ( + tester, + ) async { + final gateway = _EffortGateway(); + final row = _row(); + await tester.pumpWidget(_material(gateway, row, running: true)); + await tester.tap(find.byKey(const Key('chat-effort'))); + await tester.pumpAndSettle(); + expect(find.textContaining('A turn is running.'), findsOneWidget); + await tester.tap(find.byKey(const ValueKey('chat-effort-option-xhigh'))); + await tester.pumpAndSettle(); + expect(find.text('Thinking: Extra high · next turn'), findsOneWidget); + await tester.pumpWidget(_material(gateway, row)); + await tester.pumpAndSettle(); + expect(find.text('Thinking: Extra high'), findsOneWidget); + }); + + testWidgets('a refusal keeps the level and reports the reason', ( + tester, + ) async { + final gateway = _EffortGateway(refuse: 'level refused'); + await tester.pumpWidget(_material(gateway, _row())); + await tester.tap(find.byKey(const Key('chat-effort'))); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const ValueKey('chat-effort-option-low'))); + await tester.pumpAndSettle(); + expect(find.textContaining('level refused'), findsOneWidget); + expect(find.text('Thinking: High'), findsOneWidget); + }); + + testWidgets("a model switch re-reads the new model's levels", (tester) async { + final gateway = _EffortGateway(); + gateway.reread = { + 'session_id': 's', + 'effort': '', + 'efforts': [ + {'id': 'max', 'name': 'Max'}, + ], + 'default_effort': 'max', + }; + final changes = []; + await tester.pumpWidget(_material(gateway, _row(), onChanged: changes.add)); + await tester.pumpAndSettle(); + await tester.pumpWidget( + _material(gateway, _row(model: 'other'), onChanged: changes.add), + ); + await tester.pumpAndSettle(); + expect(gateway.requests.single['type'], 'chat_models'); + expect(find.text('Thinking: Max'), findsOneWidget); + expect(changes.single.defaultEffort, 'max'); + }); + + testWidgets('Cupertino uses an action sheet that reports a refusal', ( + tester, + ) async { + Widget app(ApiGateway gateway) => CupertinoApp( + home: CupertinoPageScaffold( + navigationBar: CupertinoNavigationBar( + trailing: ChatEffortControl( + gateway: gateway, + sessionId: 's', + session: _row(), + ), + ), + child: const SizedBox.shrink(), + ), + ); + final refusing = _EffortGateway(refuse: 'level refused'); + await tester.pumpWidget(app(refusing)); + await tester.tap(find.byKey(const Key('chat-effort'))); + await tester.pumpAndSettle(); + expect(find.byType(CupertinoActionSheet), findsOneWidget); + await tester.tap(find.byKey(const ValueKey('chat-effort-option-low'))); + await tester.pumpAndSettle(); + expect(find.byType(CupertinoActionSheet), findsOneWidget); + expect(find.textContaining('level refused'), findsOneWidget); + + final gateway = _EffortGateway(); + await tester.pumpWidget(app(gateway)); + await tester.pumpAndSettle(); + await tester.tapAt(const Offset(10, 10)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('chat-effort'))); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const ValueKey('chat-effort-option-xhigh'))); + await tester.pumpAndSettle(); + expect(find.byType(CupertinoActionSheet), findsNothing); + expect(gateway.requests.single['type'], 'chat_effort'); + }); +} diff --git a/app/test/features/chat/conversation/chat_effort_header_test.dart b/app/test/features/chat/conversation/chat_effort_header_test.dart new file mode 100644 index 00000000..419bfa37 --- /dev/null +++ b/app/test/features/chat/conversation/chat_effort_header_test.dart @@ -0,0 +1,90 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart'; + +import 'chat_thread_fixtures.dart'; + +/// The conversation header places the thinking control beside model and +/// mode only when the chat's model has levels. + +Map _session({bool levels = true}) => { + 'id': 's', + 'backend': 'codex', + 'model': 'gpt-test', + 'model_provider': 'openai', + 'mode': 'ask', + 'mode_name': 'Ask for approval', + 'directory': '/srv', + if (levels) ...{ + 'effort': 'high', + 'efforts': [ + {'id': 'low', 'name': 'Low'}, + {'id': 'high', 'name': 'High'}, + ], + }, +}; + +Future _pump( + WidgetTester tester, { + required bool cupertino, + required Map session, +}) async { + tester.view.physicalSize = const Size(1200, 800); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final gateway = FakeChatGateway(); + addTearDown(gateway.close); + gateway.history = (_) async => chatPage(const []); + gateway.subscribe = () async => const {}; + final view = ChatThreadView( + gateway: gateway, + sessionId: 's', + title: 'Thinking', + session: session, + onBack: () {}, + ); + await tester.pumpWidget( + cupertino + ? CupertinoApp(home: CupertinoPageScaffold(child: view)) + : MaterialApp(home: Scaffold(body: view)), + ); + await tester.pumpAndSettle(); +} + +void main() { + for (final cupertino in [false, true]) { + final host = cupertino ? 'Cupertino' : 'Material'; + + testWidgets('$host header shows the level beside model and mode', ( + tester, + ) async { + await _pump(tester, cupertino: cupertino, session: _session()); + final header = find.byKey(const Key('chat-thread-header')); + for (final key in ['chat-model', 'chat-mode', 'chat-effort']) { + expect( + find.descendant(of: header, matching: find.byKey(Key(key))), + findsOneWidget, + ); + } + expect(find.text('Thinking: High'), findsOneWidget); + final mode = tester.getRect(find.byKey(const Key('chat-mode'))); + final effort = tester.getRect(find.byKey(const Key('chat-effort'))); + expect(effort.left, greaterThanOrEqualTo(mode.right)); + expect((effort.center.dy - mode.center.dy).abs(), lessThan(2)); + }); + + testWidgets('$host header has no thinking control without levels', ( + tester, + ) async { + await _pump( + tester, + cupertino: cupertino, + session: _session(levels: false), + ); + expect(find.byKey(const Key('chat-model')), findsOneWidget); + expect(find.byKey(const Key('chat-effort')), findsNothing); + }); + } +}