feat: slash commands and skills in the composer, readable turn errors

- Typing `/` opens a palette above the composer, dsh-Go's shape: icon, the
  first-party Chinese label, /name, a one-line description, the first match
  highlighted and a return hint. It lists the directory's commands
  (/api/command) and skills (/api/skill), filters by name, label or
  description, and keeps the field focused while it opens.
- Picking completes `/name ` when the command takes arguments (its
  description shows a `[...]` form) and runs argument-free commands at once;
  skills complete and ride the next prompt as a `skills` attachment. Enter
  picks the highlighted row, arrows move, Esc closes.
- Sends route by name: commands go through POST /api/session/:id/command so
  the server expands the template (and writes the user message), skills go
  through the normal prompt with their id attached, anything else stays a
  plain message. A failed command keeps the draft for a retry.
- A failed turn now says so in the transcript: the last step's error is
  rendered under it as a quiet red block with the 中文 reading (auth, retry,
  stopped, send failure) and the provider's raw response behind 显示详情.
  Failed compactions and idle errors not already carried by the step are
  shown too; an error that a later step recovered from is not the turn's
  outcome and stays hidden.
- The tail is refetched when a turn starts, so a command's server-written
  user message (or another client's) appears without reopening the session;
  a successful send clears the stale error banner.
Version 0.3.6 (code 306).
This commit is contained in:
blumia committed 2026-11-20 02:20:35 +08:00
1 parent d7cec9d155
commit 6c00e5e026
7 files changed
+725 -14

No files matched your search

+472 -7
View File
@@ -30,6 +30,7 @@ class ChatScreen extends StatefulWidget {
class _ChatScreenState extends State<ChatScreen> {
ChatState get chat => widget.app.chat!;
final TextEditingController _draftCtrl = TextEditingController();
final FocusNode _inputFocus = FocusNode();
final ScrollController _scroll = ScrollController();
bool _stick = true;
bool _pickerOpen = false;
@@ -38,6 +39,10 @@ class _ChatScreenState extends State<ChatScreen> {
List<_Attach> _attachments = [];
bool _attaching = false;
/// `/` palette: the highlighted row, and the draft Esc closed it at.
int _slashIndex = 0;
String? _slashDismissed;
/// Assistant turns show their reasoning/tool parts as a run of steps; the
/// header of each run folds it away (key: message id and start part).
/// These are the runs the person folded or unfolded, overriding the
@@ -78,6 +83,7 @@ class _ChatScreenState extends State<ChatScreen> {
void dispose() {
chat.removeListener(_onChat);
_draftCtrl.dispose();
_inputFocus.dispose();
_scroll.dispose();
super.dispose();
}
@@ -194,6 +200,26 @@ class _ChatScreenState extends State<ChatScreen> {
_turnRows(out, mi, end);
mi = end;
break;
case 'idle':
// A failed turn also records its error on the idle message. The
// step that failed already prints it, so do not repeat it.
final err = m.error;
if (err != null && !err.isEmpty) {
final prev = mi > 0 ? chat.msgs[mi - 1] : null;
final same = prev?.error;
if (same == null ||
same.message != err.message ||
same.type != err.type) {
out.add(_Row('error', m.id, -1));
}
}
break;
case 'compaction':
if (m.status == 'failed' ||
(m.error != null && !m.error!.isEmpty)) {
out.add(_Row('error', m.id, -1));
}
break;
case 'shell':
out.add(_Row('shell', m.id, -1));
break;
@@ -238,8 +264,14 @@ class _ChatScreenState extends State<ChatScreen> {
}
}
flush();
if (chat.msgs[to].completed > 0 && _turnEndsAt(to)) {
out.add(_Row('footer', chat.msgs[to].id, -1));
final last = chat.msgs[to];
// Only the step that ended the turn speaks for it: a step that failed and
// was followed by another one is not the turn's outcome.
if (last.error != null && !last.error!.isEmpty) {
out.add(_Row('error', last.id, -1));
}
if (last.completed > 0 && _turnEndsAt(to)) {
out.add(_Row('footer', last.id, -1));
}
}
@@ -328,6 +360,8 @@ class _ChatScreenState extends State<ChatScreen> {
return _stepRow(r.msgId, r.part);
case 'footer':
return _footerRow(r.msgId);
case 'error':
return _errorRow(r.msgId);
case 'shell':
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
@@ -923,6 +957,136 @@ class _ChatScreenState extends State<ChatScreen> {
);
}
/// Whether an error detail looks like an authentication failure (the same
/// reading the official client does, so the sentence matches).
static bool _isAuthError(String detail) {
final d = detail.toLowerCase().trim();
if (d.isEmpty) return false;
if (d.contains('token refresh failed') ||
d.contains('unauthorized') ||
d.contains('invalid token') ||
d.contains('expired token')) {
return true;
}
if (d.contains('oauth') &&
(d.contains('failed') || d.contains('invalid') || d.contains('expired'))) {
return true;
}
final has401 = RegExp(r'\b401\b').hasMatch(d);
return has401 &&
(d.contains('auth') || d.contains('token') || d.contains('unauthorized'));
}
/// What a failed step says in the transcript, close to the official
/// client's wording; the provider's raw response is kept for details.
static ({String text, String? body}) _errorNotice(Message m) {
final e = m.error;
final detail = (e != null && e.message.isNotEmpty)
? e.message
: (e != null && e.type.isNotEmpty ? e.type : '未知错误');
final type = (e?.type ?? '').toLowerCase();
final plain = detail.trim().toLowerCase().replaceFirst(RegExp(r'\.$'), '');
if (m.type == 'compaction') {
return (text: '压缩失败:$detail', body: e?.body);
}
if (type == 'sessionretry') {
return (text: 'OpenCode 发送消息失败,正在重试:$detail', body: e?.body);
}
if (_isAuthError(detail)) {
return (
text: '模型的认证失败,请在服务端重新登录或检查 API Key。',
body: e?.body
);
}
if (type == 'messageabortederror' ||
plain == 'aborted' ||
plain == 'step interrupted') {
return (text: '本轮已停止。', body: null);
}
return (text: 'OpenCode 发送消息失败:$detail', body: e?.body);
}
static String _prettyBody(String raw) {
try {
return const JsonEncoder.withIndent(' ').convert(jsonDecode(raw));
} catch (_) {
return raw;
}
}
/// A failed turn's error, as a quiet block under its last step: what went
/// wrong, and the provider's response behind a "详情" toggle.
Widget _errorRow(String id) {
final m = chat.byId[id];
if (m == null) return const SizedBox.shrink();
final notice = _errorNotice(m);
final theme = Theme.of(context);
final scheme = theme.colorScheme;
final key = 'error/$id';
final open = chat.expanded.contains(key);
final raw = notice.body?.trim() ?? '';
final body = raw.isEmpty ? null : _prettyBody(raw);
return Padding(
padding: const EdgeInsets.fromLTRB(16, 6, 16, 4),
child: Container(
padding: const EdgeInsets.fromLTRB(12, 10, 12, 10),
decoration: BoxDecoration(
color: scheme.error.withValues(alpha: 0.08),
border: Border.all(color: scheme.error.withValues(alpha: 0.28)),
borderRadius: BorderRadius.circular(14),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(Icons.error_outline, size: 18, color: scheme.error),
const SizedBox(width: 8),
Expanded(
child: SelectableText(notice.text,
style: const TextStyle(fontSize: 13.5, height: 1.45)),
),
],
),
if (body != null) ...[
Padding(
padding: const EdgeInsets.only(left: 26),
child: TextButton(
style: TextButton.styleFrom(
padding: EdgeInsets.zero,
minimumSize: const Size(0, 30),
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
alignment: Alignment.centerLeft,
foregroundColor: scheme.onSurfaceVariant,
),
onPressed: () => setState(() {
open ? chat.expanded.remove(key) : chat.expanded.add(key);
}),
child: Text(open ? '收起详情' : '显示详情',
style: const TextStyle(fontSize: 12.5)),
),
),
if (open)
Container(
width: double.infinity,
margin: const EdgeInsets.only(left: 26, top: 4),
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: scheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(8),
),
child: SelectableText(body,
style: const TextStyle(
fontSize: 11.5, height: 1.45, fontFamily: 'monospace')),
),
],
],
),
),
);
}
String _turnDuration(Message m) {
var start = 0;
final idx = chat.msgs.indexWhere((x) => x.id == m.id);
@@ -1004,19 +1168,267 @@ class _ChatScreenState extends State<ChatScreen> {
// leading key, an auto-growing borderless field, the usage ring and a
// trailing send/stop key, all 36px round keys (MIT, app/lib/ui/chat/
// 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;
}
void _moveSlash(List<SlashItem> items, int delta) {
if (items.isEmpty) return;
setState(() {
_slashIndex = (_slashIndex + delta).clamp(0, items.length - 1);
});
}
void _dismissSlash() {
setState(() => _slashDismissed = _draftCtrl.text);
}
/// A row was picked. Commands that take no argument run right away (as in
/// dsh-Go); the rest complete the name and wait for the arguments.
void _pickSlash(SlashItem item) {
HapticFeedback.selectionClick();
final text = _draftCtrl.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}';
_draftCtrl.value = TextEditingValue(
text: command,
selection: TextSelection.collapsed(offset: command.length),
);
chat.draft = 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';
_draftCtrl.value = TextEditingValue(
text: next,
selection: TextSelection.collapsed(offset: prefix.length + 1),
);
chat.draft = next;
_inputFocus.requestFocus();
setState(() {});
}
/// 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 _composer() {
final usage = chat.usageReading();
final scheme = Theme.of(context).colorScheme;
final canSend = _draftCtrl.text.trim().isNotEmpty || _attachments.isNotEmpty;
return SafeArea(
top: false,
child: Padding(
final slash = _slashMatches();
final slashRows = slash ?? const <SlashItem>[];
Widget body = Padding(
padding: const EdgeInsets.fromLTRB(8, 6, 8, 6),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
if (_attachments.isNotEmpty) _attachmentTray(),
if (slash != null) ...[
KeyedSubtree(
key: const ValueKey('slash-palette'),
child: _slashPalette(slashRows),
),
const SizedBox(height: 6),
],
Container(
key: const ValueKey('composer-bar'),
padding: const EdgeInsets.all(6),
decoration: BoxDecoration(
color: scheme.surfaceContainerHighest,
@@ -1035,13 +1447,44 @@ class _ChatScreenState extends State<ChatScreen> {
Expanded(
child: TextField(
controller: _draftCtrl,
focusNode: _inputFocus,
minLines: 1,
maxLines: 5,
keyboardType: TextInputType.multiline,
textInputAction: TextInputAction.newline,
// While the palette is up, the keyboard's action key
// picks the highlighted row instead of writing a
// newline.
textInputAction: slash != null
? TextInputAction.send
: TextInputAction.newline,
onSubmitted: slash == null || slashRows.isEmpty
? null
: (_) => _pickSlash(
slashRows[_slashIndex.clamp(0, slashRows.length - 1)]),
onChanged: (v) {
chat.draft = v;
_slashIndex = 0;
if (_slashDismissed != null && v != _slashDismissed) {
_slashDismissed = null;
}
if (v.trimLeft().startsWith('/')) chat.ensureSlash();
setState(() {});
// A soft keyboard whose action key still writes a
// newline commits the highlighted row instead of
// leaving a stray blank line in the draft.
if (slash != null && v.endsWith('\n')) {
final trimmed = v.trimRight();
_draftCtrl.value = TextEditingValue(
text: trimmed,
selection:
TextSelection.collapsed(offset: trimmed.length),
);
chat.draft = trimmed;
final rows = _slashMatches() ?? const <SlashItem>[];
if (rows.isNotEmpty) {
_pickSlash(rows[_slashIndex.clamp(0, rows.length - 1)]);
}
}
},
style: const TextStyle(fontSize: 15, height: 1.45),
decoration: InputDecoration(
@@ -1083,6 +1526,28 @@ class _ChatScreenState extends State<ChatScreen> {
),
],
),
);
// Always wrapped: re-parenting the field when the palette opens would
// drop its focus, and with it the characters typed after `/`.
return SafeArea(
top: false,
child: 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,
),
);
}
@@ -1188,7 +1653,7 @@ class _ChatScreenState extends State<ChatScreen> {
}
_draftCtrl.clear();
setState(() => _attachments = []);
if (images.isNotEmpty) {
if (images.isNotEmpty && id.isNotEmpty) {
chat.imagePaths[id] = images;
chat.touch();
}