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

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