Show a thinking-level control beside the chat model and mode
Material menu or Cupertino action sheet of the levels the chat's model accepts, sent with chat_effort through the chat's own gateway. Hidden when the model has none; says when a running turn keeps its level; re-reads the levels after a model switch.
This commit is contained in:
@@ -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<ChatEffortState>? onChanged;
|
||||
final bool showLabel;
|
||||
|
||||
@override
|
||||
State<ChatEffortControl> createState() => _ChatEffortControlState();
|
||||
}
|
||||
|
||||
class _ChatEffortControlState extends State<ChatEffortControl> {
|
||||
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<void> _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<void> _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<void> _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<void> _openSheet() => showCupertinoModalPopup<void>(
|
||||
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<String>('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,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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<void> Function(ChatEffortLevel level) choose;
|
||||
|
||||
@override
|
||||
State<ChatEffortSheet> createState() => _ChatEffortSheetState();
|
||||
}
|
||||
|
||||
class _ChatEffortSheetState extends State<ChatEffortSheet> {
|
||||
bool _busy = false;
|
||||
String? _error;
|
||||
|
||||
Future<void> _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<String>('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'),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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 = <ChatEffortLevel>[];
|
||||
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<ChatEffortLevel> 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<ChatEffortState> 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<ChatEffortState> 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']);
|
||||
}
|
||||
@@ -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<ChatEffortState>? onEffortChanged;
|
||||
|
||||
/// Advances when the shared socket is replaced, keeping this selection.
|
||||
final int syncToken;
|
||||
|
||||
@@ -1336,6 +1342,8 @@ class _ChatThreadViewState extends State<ChatThreadView> {
|
||||
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<ChatThreadView> {
|
||||
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<String>('chat-effort-${widget.sessionId}'),
|
||||
gateway: widget.gateway,
|
||||
sessionId: widget.sessionId,
|
||||
session: session,
|
||||
running: _controller.running,
|
||||
onChanged: widget.onEffortChanged,
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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<ChatScreen>
|
||||
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<ChatScreen>
|
||||
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),
|
||||
|
||||
Reference in New Issue
Block a user