fix: switching a session's model, and put the model row in the composer

- POST /api/session/:id/model takes the reference under `model`; sending it
  at the top level was rejected with "Missing key at [model]".
- The chat now shows the model/agent row above the input (revealed while
  typing or running, as dsh-Go does) instead of in the app bar; the draft
  keeps the same row, with its project chip first.
- Thinking levels: /api/model's variants become a 思考 chip and sheet; the
  choice travels as ModelRef.variant on the switch or the create, and the
  last level per model is remembered on the device.
- The model picker groups providers, adds 收藏 and 最近 (device-local), shows
  each model's context size and reasoning mark, and collapses sections.
- The `/` palette is shared by the chat and the draft (new slash_palette
  widget); the draft lists commands and skills but not the client-local
  /compact, which needs an existing session.
- 0.3.14 (314).
This commit is contained in:
blumia committed 2026-11-21 17:03:22 +08:00
1 parent fff6562cbc
commit 7f2f454539
12 files changed
+962 -344

No files matched your search

+3 -1
View File
@@ -305,8 +305,10 @@ class Client {
}
Future<void> switchModel(String sessionId, ModelRef model, {String? directory}) async {
// The route takes the reference under `model`; sending it at the top level
// is rejected with "Missing key at [model]".
await _json('POST', '/api/session/${Uri.encodeComponent(sessionId)}/model',
directory: directory, body: model.toJson());
directory: directory, body: {'model': model.toJson()});
}
Future<void> switchAgent(String sessionId, String agent, {String? directory}) async {
+20 -1
View File
@@ -803,17 +803,36 @@ class ModelInfo {
final String name;
final int context;
final int output;
ModelInfo(this.id, this.providerId, this.name, this.context, this.output);
/// Thinking levels this model offers (`minimal`, `low`, `medium`, …), as
/// v2's model variants. Empty means the model has no effort choice.
final List<String> variants;
/// The provider says the model reasons; worth a mark in the picker.
final bool reasoning;
ModelInfo(this.id, this.providerId, this.name, this.context, this.output,
{this.variants = const [], this.reasoning = false});
factory ModelInfo.fromJson(Map<String, dynamic> j) {
final lim = j['limit'] as Map<String, dynamic>? ?? {};
final capabilities = j['capabilities'];
return ModelInfo(
j['id'] as String,
j['providerID'] as String? ?? '',
j['name'] as String? ?? (j['id'] as String? ?? ''),
(lim['context'] as num?)?.toInt() ?? 0,
(lim['output'] as num?)?.toInt() ?? 0,
variants: [
for (final v in (j['variants'] as List? ?? []))
if (v is Map && v['id'] is String) v['id'] as String,
],
reasoning:
capabilities is Map && capabilities['reasoning'] == true,
);
}
bool get hasEffort => variants.isNotEmpty;
}
class AgentInfo {
+106
View File
@@ -0,0 +1,106 @@
// Model picker preferences: favorites, recently used models, and the effort
// last chosen for each. Device-local; the server has no say in them.
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
class ModelPrefs {
ModelPrefs._();
static final ModelPrefs instance = ModelPrefs._();
static const _favoritesKey = 'model.favorites.v1';
static const _recentsKey = 'model.recents.v1';
static const _effortsKey = 'model.efforts.v1';
static const _maxRecents = 6;
final Set<String> favorites = {};
final List<String> recents = [];
final Map<String, String> efforts = {};
bool _loaded = false;
static String keyFor(String providerId, String id) => '$providerId/$id';
Future<void> ensureLoaded() async {
if (_loaded) return;
_loaded = true;
try {
final prefs = await SharedPreferences.getInstance();
favorites
..clear()
..addAll(prefs.getStringList(_favoritesKey) ?? const []);
recents
..clear()
..addAll(prefs.getStringList(_recentsKey) ?? const []);
final raw = prefs.getString(_effortsKey);
if (raw != null && raw.isNotEmpty) {
final decoded = jsonDecode(raw);
if (decoded is Map) {
efforts
..clear()
..addAll({
for (final entry in decoded.entries)
if (entry.value is String)
'${entry.key}': entry.value as String,
});
}
}
} catch (_) {}
}
bool isFavorite(String key) => favorites.contains(key);
Future<void> toggleFavorite(String key) async {
if (!favorites.remove(key)) favorites.add(key);
final prefs = await SharedPreferences.getInstance();
await prefs.setStringList(_favoritesKey, favorites.toList());
}
Future<void> rememberModel(String key) async {
recents.remove(key);
recents.insert(0, key);
if (recents.length > _maxRecents) recents.removeRange(_maxRecents, recents.length);
final prefs = await SharedPreferences.getInstance();
await prefs.setStringList(_recentsKey, recents);
}
String? effortFor(String key) => efforts[key];
Future<void> rememberEffort(String key, String? variant) async {
if (variant == null || variant.isEmpty) {
efforts.remove(key);
} else {
efforts[key] = variant;
}
final prefs = await SharedPreferences.getInstance();
await prefs.setString(_effortsKey, jsonEncode(efforts));
}
}
/// `200000` reads as `200K`, `1000000` as `1M`.
String formatTokenCount(int tokens) {
if (tokens <= 0) return '';
String trim(String value) =>
value.endsWith('.0') ? value.substring(0, value.length - 2) : value;
if (tokens >= 1000000) {
return '${trim((tokens / 1000000).toStringAsFixed(1))}M';
}
if (tokens >= 1000) {
return '${(tokens / 1000).round()}K';
}
return '$tokens';
}
/// The Chinese label for an effort variant; unknown ids keep their own name.
String effortLabel(String? variant) {
if (variant == null || variant.isEmpty) return '默认';
return switch (variant.toLowerCase()) {
'default' => '默认',
'none' => '无',
'minimal' => '极低',
'low' => '低',
'medium' || 'mid' => '中',
'high' => '高',
'xhigh' || 'max' => '极高',
_ => variant,
};
}
+37 -216
View File
@@ -11,7 +11,8 @@ import '../api/models.dart';
import '../state.dart';
import '../widgets/composer_attachment.dart';
import '../widgets/markdown_view.dart';
import '../widgets/model_picker.dart';
import '../widgets/model_controls.dart';
import '../widgets/slash_palette.dart';
import '../widgets/usage_ring.dart';
import 'files_panel.dart';
@@ -61,6 +62,7 @@ class _ChatScreenState extends State<ChatScreen> {
void initState() {
super.initState();
chat.addListener(_onChat);
_inputFocus.addListener(_onFocusChanged);
// The list is reversed: offset 0 is the newest message (the bottom), and
// older pages grow above without moving what is on screen.
_scroll.addListener(() {
@@ -86,9 +88,14 @@ class _ChatScreenState extends State<ChatScreen> {
}
}
void _onFocusChanged() {
if (mounted) setState(() {});
}
@override
void dispose() {
chat.removeListener(_onChat);
_inputFocus.removeListener(_onFocusChanged);
_draftCtrl.dispose();
_inputFocus.dispose();
_scroll.dispose();
@@ -109,27 +116,6 @@ class _ChatScreenState extends State<ChatScreen> {
),
title: Text(_title(), maxLines: 1, overflow: TextOverflow.ellipsis),
actions: [
Padding(
padding: const EdgeInsets.only(right: 4),
child: ActionChip(
visualDensity: VisualDensity.compact,
avatar: const Icon(Icons.smart_toy_outlined, size: 16),
label: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 120),
child: Text(_modelLabel(),
maxLines: 1, overflow: TextOverflow.ellipsis),
),
onPressed: () => showModelPickerSheet(
context,
app: widget.app,
kind: 'model',
model: chat.selectedModel ?? widget.session.model,
agent: chat.selectedAgent,
onModel: (m) => chat.switchModel(m),
onAgent: (a) => chat.switchAgent(a),
),
),
),
IconButton(
icon: const Icon(Icons.view_sidebar_outlined),
tooltip: '文件',
@@ -1283,49 +1269,14 @@ class _ChatScreenState extends State<ChatScreen> {
// composer.dart, referenced rather than copied).
/// Chinese faces for the first-party commands, as dsh-Go shows them; the
/// registry's name is what is sent.
static const _slashLabels = {
'compact': '压缩',
'init': '初始化',
'review': '审查',
'goal': '目标',
'new-extension': '新建扩展',
'permission': '权限',
'plan': '计划',
'feedback': '反馈',
};
static String? _slashLabel(SlashItem item) =>
item.skill ? null : _slashLabels[item.name];
/// Rows for the current draft, or null when the palette is closed. It
/// stays up while the command name is being typed and closes once an
/// argument has started.
List<SlashItem>? _slashMatches() {
final text = _draftCtrl.text;
if (_slashDismissed == text) return null;
final t = text.trimLeft();
if (!t.startsWith('/')) return null;
if (t.length > 1 && RegExp(r'\s').hasMatch(t.substring(1))) return null;
final q = t.substring(1).toLowerCase().trim();
final all = chat.slashItems;
if (q.isEmpty) return all;
bool hit(SlashItem e) {
final label = _slashLabel(e) ?? '';
return e.name.toLowerCase().contains(q) ||
label.toLowerCase().contains(q) ||
e.description.toLowerCase().contains(q);
}
final matches = all.where(hit).toList()
..sort((a, b) {
final ap = a.name.toLowerCase().startsWith(q) ? 0 : 1;
final bp = b.name.toLowerCase().startsWith(q) ? 0 : 1;
if (ap != bp) return ap - bp;
if (a.skill != b.skill) return a.skill ? 1 : -1;
return a.name.compareTo(b.name);
});
return matches;
}
List<SlashItem>? _slashMatches() => matchSlashItems(
items: chat.slashItems,
text: _draftCtrl.text,
dismissed: _slashDismissed,
);
void _moveSlash(List<SlashItem> items, int delta) {
if (items.isEmpty) return;
@@ -1373,153 +1324,19 @@ class _ChatScreenState extends State<ChatScreen> {
}
/// The palette above the composer: dsh-Go's `/` menu, on the app's theme.
Widget _slashPalette(List<SlashItem> items) {
final scheme = Theme.of(context).colorScheme;
final typed = _draftCtrl.text.trimLeft().length > 1;
final index = items.isEmpty ? 0 : _slashIndex.clamp(0, items.length - 1);
Widget row(IconData icon, String title, String subtitle) => Padding(
padding: const EdgeInsets.fromLTRB(14, 14, 14, 14),
child: Row(
children: [
SizedBox(
width: 32,
child: Icon(icon, size: 20, color: scheme.onSurfaceVariant),
),
const SizedBox(width: 8),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(title,
style: TextStyle(
fontSize: 14, color: scheme.onSurface)),
if (subtitle.isNotEmpty)
Text(subtitle,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 12, color: scheme.onSurfaceVariant)),
],
),
),
],
),
);
return Container(
constraints: const BoxConstraints(maxHeight: 56 * 5.5),
clipBehavior: Clip.antiAlias,
decoration: BoxDecoration(
color: scheme.surfaceContainerHigh,
borderRadius: BorderRadius.circular(20),
border: Border.all(color: scheme.outlineVariant.withValues(alpha: 0.6)),
),
child: items.isEmpty
? (chat.slashLoading
? const Padding(
padding: EdgeInsets.all(18),
child: Center(
child: SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(strokeWidth: 2)),
),
)
: row(Icons.search_off, '没有可用的指令', '这个目录还没有注册指令或技能'))
: ListView.builder(
shrinkWrap: true,
padding: const EdgeInsets.symmetric(vertical: 6, horizontal: 6),
itemCount: items.length,
itemBuilder: (context, i) {
final item = items[i];
final label = _slashLabel(item);
final selected = i == index;
final scheme = Theme.of(context).colorScheme;
return InkWell(
borderRadius: BorderRadius.circular(14),
onTap: () => _pickSlash(item),
child: Container(
height: 56,
padding: const EdgeInsets.symmetric(horizontal: 8),
decoration: BoxDecoration(
color:
selected ? scheme.primary.withValues(alpha: 0.10) : null,
borderRadius: BorderRadius.circular(14),
),
child: Row(
children: [
SizedBox(
width: 32,
child: Icon(
item.skill
? Icons.extension_outlined
: Icons.terminal,
size: 20,
color: scheme.onSurfaceVariant,
),
),
const SizedBox(width: 8),
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
if (label != null) ...[
Text(label,
style: const TextStyle(
fontSize: 14,
fontWeight: FontWeight.w500)),
const SizedBox(width: 8),
],
Flexible(
child: Text('/${item.name}',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 12.5,
color: scheme.onSurfaceVariant)),
),
if (item.skill) ...[
const SizedBox(width: 6),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 6, vertical: 1),
decoration: BoxDecoration(
color: scheme.secondaryContainer,
borderRadius:
BorderRadius.circular(6),
),
child: Text('技能',
style: TextStyle(
fontSize: 10.5,
color:
scheme.onSecondaryContainer)),
),
],
],
),
if (item.description.isNotEmpty)
Text(item.description,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 12,
color: scheme.onSurfaceVariant)),
],
),
),
if (selected && typed)
Icon(Icons.keyboard_return,
size: 16, color: scheme.onSurfaceVariant),
],
),
),
);
},
),
);
}
Widget _slashPalette(List<SlashItem> items) => SlashPalette(
items: items,
index: _slashIndex,
loading: chat.slashLoading,
onPick: _pickSlash,
);
/// dsh-Go shows the model row while the input is in use; an empty, idle
/// composer leaves the space to the messages.
bool _showModelControls() =>
_inputFocus.hasFocus ||
_draftCtrl.text.trim().isNotEmpty ||
chat.running;
Widget _composer() {
final usage = chat.usageReading();
@@ -1532,6 +1349,16 @@ class _ChatScreenState extends State<ChatScreen> {
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
if (_showModelControls()) ...[
ModelControlsBar(
app: widget.app,
model: chat.selectedModel ?? widget.session.model,
agent: chat.selectedAgent,
onModel: (m) => chat.switchModel(m),
onAgent: (a) => chat.switchAgent(a),
),
const SizedBox(height: 6),
],
if (_attachments.isNotEmpty) _attachmentTray(),
if (slash != null) ...[
KeyedSubtree(
@@ -1716,13 +1543,6 @@ class _ChatScreenState extends State<ChatScreen> {
onRemove: (i) => setState(() => _attachments.removeAt(i)),
);
String _modelLabel() {
final m = chat.selectedModel ?? widget.session.model;
final model = m == null ? '模型' : widget.app.modelName(m);
final agent = chat.selectedAgent;
return agent.isEmpty ? model : '$model · $agent';
}
Future<void> _send() async {
final text = _draftCtrl.text.trim();
if (text.isEmpty && _attachments.isEmpty) return;
@@ -1771,6 +1591,7 @@ class _ChatScreenState extends State<ChatScreen> {
}
}
// ---------------------------------------------------------- permissions
/// The agent's blocking questions sit just above the composer, like the
+151 -51
View File
@@ -7,7 +7,8 @@ import 'package:flutter/services.dart';
import '../api/models.dart';
import '../state.dart';
import '../widgets/composer_attachment.dart';
import '../widgets/model_picker.dart';
import '../widgets/model_controls.dart';
import '../widgets/slash_palette.dart';
import 'files_panel.dart';
class NewSessionScreen extends StatefulWidget {
@@ -33,6 +34,14 @@ class _NewSessionScreenState extends State<NewSessionScreen> {
List<ComposerAttachment> _attachments = [];
bool _attaching = false;
/// The `/` palette for the draft's directory. It carries commands and
/// skills, not the client-local `compact` that needs an existing session.
List<SlashItem> _slashItems = [];
bool _slashLoading = false;
bool _slashLoaded = false;
int _slashIndex = 0;
String? _slashDismissed;
@override
void initState() {
super.initState();
@@ -58,6 +67,70 @@ class _NewSessionScreenState extends State<NewSessionScreen> {
bool get _canSend =>
_text.text.trim().isNotEmpty || _attachments.isNotEmpty;
List<SlashItem>? _slashMatches() => matchSlashItems(
items: _slashItems,
text: _text.text,
dismissed: _slashDismissed,
);
Future<void> _ensureSlash() async {
if (_slashLoaded || _slashLoading) return;
_slashLoading = true;
if (mounted) setState(() {});
try {
_slashItems = await widget.app.slashItemsFor(_draft.directory,
includeLocal: false);
_slashLoaded = true;
} catch (_) {
// An empty palette; a send falls back to a plain prompt.
}
_slashLoading = false;
if (mounted) setState(() {});
}
void _moveSlash(List<SlashItem> items, int delta) {
if (items.isEmpty) return;
setState(() {
_slashIndex = (_slashIndex + delta).clamp(0, items.length - 1);
});
}
void _dismissSlash() => setState(() => _slashDismissed = _text.text);
/// A row was picked: no-argument commands run at once (creating the session
/// on the spot), the rest complete the name and wait for arguments.
void _pickSlash(SlashItem item) {
HapticFeedback.selectionClick();
final text = _text.text;
final lead = text.length - text.trimLeft().length;
final rest = text.trimLeft();
final match = RegExp(r'\s').firstMatch(rest);
final suffix = match == null ? '' : rest.substring(match.start);
final completes = item.skill || item.takesArgs;
if (!completes) {
final command = '/${item.name}';
_text.value = TextEditingValue(
text: command,
selection: TextSelection.collapsed(offset: command.length),
);
widget.app.updateDraftText(command);
setState(() {});
_send();
return;
}
final prefix = '${text.substring(0, lead)}/${item.name}';
final separator =
suffix.isEmpty || !RegExp(r'^\s').hasMatch(suffix) ? ' ' : '';
final next = '$prefix$separator$suffix';
_text.value = TextEditingValue(
text: next,
selection: TextSelection.collapsed(offset: prefix.length + 1),
);
widget.app.updateDraftText(next);
_inputFocus.requestFocus();
setState(() {});
}
Future<void> _send() async {
if (!_canSend || widget.app.sendingDraft) return;
final text = _text.text.trim();
@@ -171,12 +244,14 @@ class _NewSessionScreenState extends State<NewSessionScreen> {
fontSize: 12.5, color: scheme.error),
),
),
Row(
children: [
_projectChip(draft),
const Spacer(),
_modelChip(draft),
],
ModelControlsBar(
app: widget.app,
model: draft.model,
agent: draft.agent,
leading: _projectChip(draft),
onModel: (m) => widget.app.updateDraftModel(m),
onAgent: (a) =>
widget.app.updateDraftModel(null, agent: a),
),
const SizedBox(height: 6),
if (_attachments.isNotEmpty)
@@ -225,52 +300,12 @@ class _NewSessionScreenState extends State<NewSessionScreen> {
);
}
Widget _modelChip(SessionDraft draft) {
final app = widget.app;
final model = draft.model == null
? '模型'
: app.modelName(draft.model!);
final label =
draft.agent.isEmpty ? model : '$model · ${draft.agent}';
return InkWell(
borderRadius: BorderRadius.circular(18),
onTap: () => showModelPickerSheet(
context,
app: app,
kind: 'model',
model: draft.model,
agent: draft.agent,
onModel: (m) => app.updateDraftModel(m),
onAgent: (a) => app.updateDraftModel(null, agent: a),
),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.smart_toy_outlined,
size: 15, color: Theme.of(context).hintColor),
const SizedBox(width: 5),
ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 170),
child: Text(
label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 12.5, color: Theme.of(context).hintColor),
),
),
],
),
),
);
}
Widget _composer(ThemeData theme) {
final scheme = theme.colorScheme;
final sending = widget.app.sendingDraft;
return Container(
final slash = _slashMatches();
final slashRows = slash ?? const <SlashItem>[];
Widget body = Container(
padding: const EdgeInsets.all(6),
decoration: BoxDecoration(
color: scheme.surfaceContainerHighest,
@@ -293,7 +328,34 @@ class _NewSessionScreenState extends State<NewSessionScreen> {
minLines: 1,
maxLines: 5,
keyboardType: TextInputType.multiline,
onChanged: (_) => setState(() {}),
textInputAction: slash != null
? TextInputAction.send
: TextInputAction.newline,
onSubmitted: slash == null || slashRows.isEmpty
? null
: (_) => _pickSlash(
slashRows[_slashIndex.clamp(0, slashRows.length - 1)]),
onChanged: (v) {
widget.app.updateDraftText(v);
_slashIndex = 0;
if (_slashDismissed != null && v != _slashDismissed) {
_slashDismissed = null;
}
if (v.trimLeft().startsWith('/')) _ensureSlash();
setState(() {});
if (slash != null && v.endsWith('\n')) {
final trimmed = v.trimRight();
_text.value = TextEditingValue(
text: trimmed,
selection: TextSelection.collapsed(offset: trimmed.length),
);
widget.app.updateDraftText(trimmed);
final rows = _slashMatches() ?? const <SlashItem>[];
if (rows.isNotEmpty) {
_pickSlash(rows[_slashIndex.clamp(0, rows.length - 1)]);
}
}
},
decoration: const InputDecoration(
isCollapsed: true,
border: InputBorder.none,
@@ -307,6 +369,42 @@ class _NewSessionScreenState extends State<NewSessionScreen> {
],
),
);
return Column(
mainAxisSize: MainAxisSize.min,
children: [
if (slash != null) ...[
KeyedSubtree(
key: const ValueKey('draft-slash-palette'),
child: SlashPalette(
items: slashRows,
index: _slashIndex,
loading: _slashLoading,
onPick: _pickSlash,
),
),
const SizedBox(height: 6),
],
CallbackShortcuts(
bindings: slash == null
? const {}
: {
const SingleActivator(LogicalKeyboardKey.arrowDown): () =>
_moveSlash(slashRows, 1),
const SingleActivator(LogicalKeyboardKey.arrowUp): () =>
_moveSlash(slashRows, -1),
const SingleActivator(LogicalKeyboardKey.enter): () =>
_pickSlash(slashRows[
_slashIndex.clamp(0, slashRows.length - 1)]),
const SingleActivator(LogicalKeyboardKey.numpadEnter): () =>
_pickSlash(slashRows[
_slashIndex.clamp(0, slashRows.length - 1)]),
const SingleActivator(LogicalKeyboardKey.escape):
_dismissSlash,
},
child: body,
),
],
);
}
Widget _roundKey(
@@ -412,6 +510,8 @@ class _NewSessionScreenState extends State<NewSessionScreen> {
: null,
onTap: () {
app.updateDraftTarget(project.canonical);
_slashLoaded = false;
_slashItems = [];
Navigator.pop(context);
},
),
+54 -29
View File
@@ -351,6 +351,59 @@ class AppState extends ChangeNotifier {
bool get hasMoreSessions => _sessionsNext != null;
/// Commands and skills of one directory, cached. The chat and the draft
/// both read this; the client-local `compact` is left out for a session
/// that does not exist yet.
final Map<String, List<SlashItem>> _slashCache = {};
Future<List<SlashItem>> slashItemsFor(String directory,
{bool includeLocal = true}) async {
final key = '${includeLocal ? 1 : 0}:$directory';
final cached = _slashCache[key];
if (cached != null) return cached;
final cl = client;
if (cl == null) return const [];
final results = await Future.wait([
cl.commands(directory: directory),
cl.skills(directory: directory),
]);
const local = [
SlashItem(
name: 'compact',
description: '使用 AI 压缩会话历史以减少上下文大小',
action: 'compact',
),
];
final localNames = {for (final c in local) c.name};
final items = [
if (includeLocal) ...local,
for (final c in results[0])
if ((c['name'] ?? '').isNotEmpty && !localNames.contains(c['name']))
SlashItem(name: c['name']!, description: c['description'] ?? ''),
for (final k in results[1])
if ((k['name'] ?? '').isNotEmpty)
SlashItem(
name: k['name']!,
description: k['description'] ?? '',
skill: true,
id: k['id'] ?? '',
),
];
_slashCache[key] = items;
return items;
}
/// The catalog entry for a model reference, when the list has it.
ModelInfo? modelInfo(ModelRef? ref) {
if (ref == null) return null;
for (final model in modelList) {
if (model.id == ref.id && model.providerId == ref.providerId) {
return model;
}
}
return null;
}
String projectLabelFor(String directory) {
if (directory.isEmpty) return '';
for (final project in projects) {
@@ -915,35 +968,7 @@ class ChatState extends ChangeNotifier {
slashLoading = true;
notifyListeners();
try {
final results = await Future.wait([
cl.commands(directory: dir),
cl.skills(directory: dir),
]);
const local = [
SlashItem(
name: 'compact',
description: '使用 AI 压缩会话历史以减少上下文大小',
action: 'compact',
),
];
final localNames = {for (final c in local) c.name};
slashItems = [
...local,
for (final c in results[0])
if ((c['name'] ?? '').isNotEmpty && !localNames.contains(c['name']))
SlashItem(
name: c['name']!,
description: c['description'] ?? '',
),
for (final k in results[1])
if ((k['name'] ?? '').isNotEmpty)
SlashItem(
name: k['name']!,
description: k['description'] ?? '',
skill: true,
id: k['id'] ?? '',
),
];
slashItems = await app.slashItemsFor(dir);
_slashLoaded = true;
} catch (_) {
// Keep the palette empty; a send falls back to a plain prompt.
+126
View File
@@ -0,0 +1,126 @@
// The composer's model row, shared by the chat and the new-session draft:
// the model/agent chip, the thinking level when the model has one, and any
// leading chip the screen adds (the draft's project).
import 'package:flutter/material.dart';
import '../api/models.dart';
import '../model_prefs.dart';
import '../state.dart';
import 'model_picker.dart';
class ModelControlsBar extends StatelessWidget {
final AppState app;
final ModelRef? model;
final String agent;
final ValueChanged<ModelRef> onModel;
final ValueChanged<String> onAgent;
/// Shown first, e.g. the project chip on the draft.
final Widget? leading;
const ModelControlsBar({
super.key,
required this.app,
required this.model,
required this.agent,
required this.onModel,
required this.onAgent,
this.leading,
});
ModelInfo? get _info => app.modelInfo(model);
@override
Widget build(BuildContext context) {
final info = _info;
final modelLabel = model == null
? '模型'
: (agent.isEmpty ? app.modelName(model!) : '${app.modelName(model!)} · $agent');
final hasEffort = info != null && info.hasEffort;
// The server may name the default level "default"; the picker only knows
// the variants the catalog lists, so anything else counts as no effort.
final effort = model?.variant != null &&
info != null &&
info.variants.contains(model!.variant)
? model!.variant
: null;
return Wrap(
spacing: 6,
runSpacing: 4,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
if (leading != null) leading!,
_chip(
context,
icon: Icons.smart_toy_outlined,
label: modelLabel,
onTap: () => showModelPickerSheet(
context,
app: app,
kind: 'model',
model: model,
agent: agent,
onModel: onModel,
onAgent: onAgent,
),
),
if (hasEffort)
_chip(
context,
icon: Icons.psychology_outlined,
label: '思考·${effortLabel(effort)}',
active: effort != null,
onTap: () => showEffortSheet(
context,
variants: info.variants,
value: effort,
modelName: info.name,
onPick: (variant) => onModel(
ModelRef(model!.id, model!.providerId, variant)),
),
),
],
);
}
Widget _chip(BuildContext context,
{required IconData icon,
required String label,
required VoidCallback onTap,
bool active = false}) {
final theme = Theme.of(context);
final scheme = theme.colorScheme;
return InkWell(
borderRadius: BorderRadius.circular(16),
onTap: onTap,
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 5),
decoration: BoxDecoration(
color: active
? scheme.primary.withValues(alpha: 0.14)
: scheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(16),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon, size: 14, color: active ? scheme.primary : theme.hintColor),
const SizedBox(width: 4),
ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 210),
child: Text(
label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 12,
color: active ? scheme.primary : theme.hintColor,
),
),
),
],
),
),
);
}
}
+252 -43
View File
@@ -1,8 +1,10 @@
// The model / agent picker, shared by the chat's app-bar chip and the
// new-session draft (where it chooses what the session will start on).
// The model / agent picker, shared by the chat composer and the new-session
// draft: favourites, recents, models grouped by provider with their context
// size, and the thinking level of the chosen model.
import 'package:flutter/material.dart';
import '../api/models.dart';
import '../model_prefs.dart';
import '../state.dart';
Future<void> showModelPickerSheet(
@@ -13,15 +15,17 @@ Future<void> showModelPickerSheet(
required String agent,
required ValueChanged<ModelRef> onModel,
required ValueChanged<String> onAgent,
}) {
}) async {
app.refreshModels();
await ModelPrefs.instance.ensureLoaded();
if (!context.mounted) return;
return showModalBottomSheet<void>(
context: context,
isScrollControlled: true,
builder: (context) => DraggableScrollableSheet(
expand: false,
initialChildSize: 0.8,
maxChildSize: 0.92,
initialChildSize: 0.85,
maxChildSize: 0.95,
builder: (context, controller) => _PickerSheet(
app: app,
kind: kind,
@@ -35,6 +39,55 @@ Future<void> showModelPickerSheet(
);
}
/// The thinking levels of one model, as a small sheet.
Future<void> showEffortSheet(
BuildContext context, {
required List<String> variants,
required String? value,
required String modelName,
required ValueChanged<String?> onPick,
}) {
return showModalBottomSheet<void>(
context: context,
builder: (context) => SafeArea(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(16, 14, 16, 2),
child: Text('思考强度',
style:
const TextStyle(fontSize: 17, fontWeight: FontWeight.w600)),
),
Padding(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 8),
child: Text(modelName,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 12, color: Theme.of(context).hintColor)),
),
for (final option in <String?>[null, ...variants])
ListTile(
dense: true,
title: Text(effortLabel(option)),
trailing: (value ?? '') == (option ?? '')
? Icon(Icons.check,
size: 18, color: Theme.of(context).colorScheme.primary)
: null,
onTap: () {
Navigator.pop(context);
onPick(option);
},
),
const SizedBox(height: 8),
],
),
),
);
}
class _PickerSheet extends StatefulWidget {
final AppState app;
final String kind;
@@ -61,6 +114,9 @@ class _PickerSheet extends StatefulWidget {
class _PickerSheetState extends State<_PickerSheet> {
late String _kind = widget.kind;
String _filter = '';
final Set<String> _collapsed = {};
ModelPrefs get _prefs => ModelPrefs.instance;
@override
Widget build(BuildContext context) {
@@ -99,59 +155,212 @@ class _PickerSheetState extends State<_PickerSheet> {
isDense: true),
),
),
Expanded(child: _items()),
Expanded(child: _kind == 'agent' ? _agents() : _models()),
],
),
);
}
Widget _items() {
// -------------------------------------------------------------- agents
Widget _agents() {
final filter = _filter.toLowerCase();
// (key, title, modelOrAgent, selected)
final items = <(String, String, Object?, bool)>[];
if (_kind == 'model') {
for (final m in widget.app.modelList) {
final selected = widget.model != null &&
widget.model!.providerId == m.providerId &&
widget.model!.id == m.id;
items.add((
'${m.providerId}/${m.id}',
m.name,
ModelRef(m.id, m.providerId),
selected
));
}
} else {
for (final a in widget.app.agentList) {
// Compaction, Title and Summary are primary but hidden.
if (a.mode != 'primary' || a.hidden) continue;
items.add(('agent/${a.id}', a.name, a.id, widget.agent == a.id));
}
}
final visible = items
.where((e) => filter.isEmpty || e.$2.toLowerCase().contains(filter))
.toList();
if (visible.isEmpty) {
return const Center(child: Text('没有结果'));
}
final agents = [
for (final a in widget.app.agentList)
if (a.mode == 'primary' && !a.hidden)
if (filter.isEmpty || a.name.toLowerCase().contains(filter)) a,
];
if (agents.isEmpty) return const Center(child: Text('没有结果'));
return ListView.builder(
controller: widget.scrollController,
itemCount: visible.length,
itemCount: agents.length,
itemBuilder: (context, i) {
final it = visible[i];
final agent = agents[i];
return ListTile(
title: Text(it.$2),
trailing: it.$4 ? const Icon(Icons.check) : null,
dense: true,
title: Text(agent.name),
trailing: widget.agent == agent.id
? Icon(Icons.check,
size: 18, color: Theme.of(context).colorScheme.primary)
: null,
onTap: () {
Navigator.pop(context);
if (it.$3 is ModelRef) {
widget.onModel(it.$3 as ModelRef);
} else {
widget.onAgent(it.$3 as String);
}
widget.onAgent(agent.id);
},
);
},
);
}
// -------------------------------------------------------------- models
Widget _models() {
final app = widget.app;
final all = app.modelList;
if (all.isEmpty) {
return const Center(child: Text('正在载入模型…'));
}
final filter = _filter.trim().toLowerCase();
final matching = filter.isEmpty
? all
: [
for (final m in all)
if (m.name.toLowerCase().contains(filter) ||
m.id.toLowerCase().contains(filter))
m,
];
if (matching.isEmpty) return const Center(child: Text('没有结果'));
final byKey = {
for (final m in all) ModelPrefs.keyFor(m.providerId, m.id): m,
};
final favorites = [
for (final key in _prefs.favorites)
if (byKey[key] != null) byKey[key]!,
]..sort((a, b) => a.name.compareTo(b.name));
final recentKeys = [
for (final key in _prefs.recents)
if (byKey[key] != null && !_prefs.favorites.contains(key)) key,
];
final recents = [for (final key in recentKeys) byKey[key]!];
final providers = <String, List<ModelInfo>>{};
for (final model in matching) {
providers.putIfAbsent(model.providerId, () => []).add(model);
}
final children = <Widget>[];
if (filter.isEmpty) {
if (favorites.isNotEmpty) {
children.add(_sectionHeader('收藏', 'favorites', count: favorites.length));
if (!_collapsed.contains('favorites')) {
for (final model in favorites) {
children.add(_modelRow(model));
}
}
}
if (recents.isNotEmpty) {
children.add(_sectionHeader('最近', 'recents', count: recents.length));
if (!_collapsed.contains('recents')) {
for (final model in recents) {
children.add(_modelRow(model));
}
}
}
}
for (final entry in providers.entries) {
final label = entry.key.isEmpty ? '其它' : entry.key;
children.add(_sectionHeader(label, 'provider:${entry.key}',
count: entry.value.length));
if (!_collapsed.contains('provider:${entry.key}')) {
for (final model in entry.value) {
children.add(_modelRow(model));
}
}
}
return ListView(
controller: widget.scrollController,
children: children,
);
}
Widget _sectionHeader(String label, String key, {int? count}) {
final collapsed = _collapsed.contains(key);
return InkWell(
onTap: () => setState(() {
if (collapsed) {
_collapsed.remove(key);
} else {
_collapsed.add(key);
}
}),
child: Padding(
padding: const EdgeInsets.fromLTRB(16, 10, 16, 4),
child: Row(
children: [
Icon(collapsed ? Icons.chevron_right : Icons.expand_more,
size: 16, color: Theme.of(context).hintColor),
const SizedBox(width: 4),
Expanded(
child: Text(
count == null ? label : '$label($count)',
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w700,
color: Theme.of(context).hintColor),
),
),
],
),
),
);
}
Widget _modelRow(ModelInfo model) {
final theme = Theme.of(context);
final key = ModelPrefs.keyFor(model.providerId, model.id);
final selected = widget.model != null &&
widget.model!.id == model.id &&
widget.model!.providerId == model.providerId;
final favorite = _prefs.isFavorite(key);
return ListTile(
dense: true,
contentPadding: const EdgeInsets.only(left: 20, right: 4),
title: Row(
children: [
Flexible(
child: Text(model.name,
maxLines: 1, overflow: TextOverflow.ellipsis),
),
if (model.reasoning)
Padding(
padding: const EdgeInsets.only(left: 4),
child: Icon(Icons.psychology_outlined,
size: 14, color: theme.hintColor),
),
],
),
subtitle: model.context > 0
? Text('${formatTokenCount(model.context)} 上下文',
style: TextStyle(fontSize: 11, color: theme.hintColor))
: null,
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
if (selected)
Padding(
padding: const EdgeInsets.only(right: 4),
child: Icon(Icons.check,
size: 18, color: theme.colorScheme.primary),
),
IconButton(
visualDensity: VisualDensity.compact,
icon: Icon(
favorite ? Icons.star : Icons.star_border,
size: 18,
color: favorite ? theme.colorScheme.primary : theme.hintColor,
),
tooltip: favorite ? '取消收藏' : '收藏',
onPressed: () async {
await _prefs.toggleFavorite(key);
if (mounted) setState(() {});
},
),
],
),
onTap: () => _select(model),
);
}
Future<void> _select(ModelInfo model) async {
final key = ModelPrefs.keyFor(model.providerId, model.id);
final remembered = _prefs.effortFor(key);
final variant = remembered != null && model.variants.contains(remembered)
? remembered
: null;
await _prefs.rememberModel(key);
if (!mounted) return;
Navigator.pop(context);
widget.onModel(ModelRef(model.id, model.providerId, variant));
}
}
+195
View File
@@ -0,0 +1,195 @@
// The `/` palette above a composer, shared by the chat and the new-session
// draft: commands and skills of one directory, filtered as the name is typed.
import 'package:flutter/material.dart';
import '../state.dart';
const _slashLabels = {
'compact': '压缩',
'init': '初始化',
'review': '审查',
'goal': '目标',
'new-extension': '新建扩展',
'permission': '权限',
'plan': '计划',
'feedback': '反馈',
};
String? slashLabel(SlashItem item) =>
item.skill ? null : _slashLabels[item.name];
/// Rows for a draft, or null when the palette should stay closed. It stays
/// up while only the command name is typed and closes once an argument
/// starts, unless the same text was dismissed with Esc.
List<SlashItem>? matchSlashItems({
required List<SlashItem> items,
required String text,
String? dismissed,
}) {
if (dismissed == text) return null;
final trimmed = text.trimLeft();
if (!trimmed.startsWith('/')) return null;
if (trimmed.length > 1 && RegExp(r'\s').hasMatch(trimmed.substring(1))) {
return null;
}
final query = trimmed.substring(1).toLowerCase().trim();
if (query.isEmpty) return items;
bool hit(SlashItem item) {
final label = slashLabel(item) ?? '';
return item.name.toLowerCase().contains(query) ||
label.toLowerCase().contains(query) ||
item.description.toLowerCase().contains(query);
}
return items.where(hit).toList()
..sort((a, b) {
final aPrefix = a.name.toLowerCase().startsWith(query) ? 0 : 1;
final bPrefix = b.name.toLowerCase().startsWith(query) ? 0 : 1;
if (aPrefix != bPrefix) return aPrefix - bPrefix;
if (a.skill != b.skill) return a.skill ? 1 : -1;
return a.name.compareTo(b.name);
});
}
/// The panel itself: rows with an icon, the command and its description.
class SlashPalette extends StatelessWidget {
final List<SlashItem> items;
final int index;
final bool loading;
final ValueChanged<SlashItem> onPick;
const SlashPalette({
super.key,
required this.items,
required this.index,
required this.loading,
required this.onPick,
});
@override
Widget build(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
final selected = items.isEmpty ? 0 : index.clamp(0, items.length - 1);
Widget row(IconData icon, String title, String subtitle) => Padding(
padding: const EdgeInsets.fromLTRB(14, 14, 14, 14),
child: Row(
children: [
SizedBox(
width: 32,
child: Icon(icon, size: 20, color: scheme.onSurfaceVariant),
),
const SizedBox(width: 8),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(title,
style:
TextStyle(fontSize: 14, color: scheme.onSurface)),
if (subtitle.isNotEmpty)
Text(subtitle,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 12,
color: scheme.onSurfaceVariant)),
],
),
),
],
),
);
return Container(
constraints: const BoxConstraints(maxHeight: 56 * 5.5),
clipBehavior: Clip.antiAlias,
decoration: BoxDecoration(
color: scheme.surfaceContainerHigh,
borderRadius: BorderRadius.circular(20),
border: Border.all(color: scheme.outlineVariant.withValues(alpha: 0.6)),
),
child: items.isEmpty
? (loading
? const Padding(
padding: EdgeInsets.all(18),
child: Center(
child: SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(strokeWidth: 2)),
),
)
: row(Icons.search_off, '没有可用的指令', '这个目录还没有注册指令或技能'))
: ListView.builder(
shrinkWrap: true,
padding: const EdgeInsets.symmetric(vertical: 6, horizontal: 6),
itemCount: items.length,
itemBuilder: (context, i) {
final item = items[i];
final label = slashLabel(item);
final isSelected = i == selected;
return InkWell(
borderRadius: BorderRadius.circular(14),
onTap: () => onPick(item),
child: Container(
height: 56,
padding: const EdgeInsets.symmetric(horizontal: 8),
decoration: BoxDecoration(
color: isSelected
? scheme.primary.withValues(alpha: 0.10)
: null,
borderRadius: BorderRadius.circular(14),
),
child: Row(
children: [
SizedBox(
width: 32,
child: Icon(
item.skill
? Icons.extension_outlined
: Icons.terminal,
size: 20,
color: scheme.onSurfaceVariant,
),
),
const SizedBox(width: 8),
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Text('/${item.name}',
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w600,
color: scheme.onSurface)),
if (label != null)
Padding(
padding: const EdgeInsets.only(left: 6),
child: Text(label,
style: TextStyle(
fontSize: 12,
color: scheme.onSurfaceVariant)),
),
],
),
if (item.description.isNotEmpty)
Text(item.description,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 12,
color: scheme.onSurfaceVariant)),
],
),
),
],
),
),
);
},
),
);
}
}