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

+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)),
],
),
),
],
),
),
);
},
),
);
}
}