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

+13
View File
@@ -27,6 +27,19 @@
--- ---
## 0.3.6 斜杠指令与错误显示(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| `/` 指令面板 | 输入框以 `/` 开头且还没打空格时,在输入条上方弹出(dsh-Go 的样子:图标 + 中文名 + `/name` + 一行说明,最多 5.5 行,首条高亮,右侧 ↵)。来源是这个会话目录的 `GET /api/command` 与 `GET /api/skill`,第一次打开时加载并缓存;支持按名称/说明过滤,↑/↓ 选择、回车选中、Esc 关闭 |
| 选中行为 | 说明里带 `[…]` 参数形式的指令补全成 `/name ` 并等待参数;没有参数的(如 `/init`)立即执行;技能补全为文本随下一条消息发出。未知的 `/xxx` 仍是普通消息 |
| 发送路由 | 指令走 `POST /api/session/:id/command`(`{name, text}`,服务端展开模板并写用户消息);技能走普通 `/prompt` 并附 `skills: [{id}]`;失败时保留草稿 |
| 错误显示 | 解析消息上的 `error`(`provider.*`、`provider.auth`、`MessageAbortedError` 等):只显示结束这一轮的那一步的错误(被后续步骤接上的失败不算),另外显示失败的压缩消息和未被助手消息覆盖的 idle 错误。样式为浅红圆角块 + 图标 + 中文说明(认证失败、重试中、已停止、发送失败),provider 的原始响应放在「显示详情」里(美化过的 JSON) |
| 刷新 | `session.execution.started` 时拉一次尾部:指令这条由服务端写入的用户消息(以及别的客户端发的消息)能立刻出现,不用重进会话 |
| 版本 | **0.3.6(code 306)** |
---
## 0.3.5 折叠动画与流式修复(分支 `flutter`) ## 0.3.5 折叠动画与流式修复(分支 `flutter`)
| 项 | 结果 | | 项 | 结果 |
+1 -1
View File
@@ -5,7 +5,7 @@ Android first. This branch (`flutter`) is a framework evaluation: the same
feature set as the earlier Asuka/Go and MyGo attempts, reimplemented in feature set as the earlier Asuka/Go and MyGo attempts, reimplemented in
Flutter to compare mobile UI maturity. Flutter to compare mobile UI maturity.
Status: 0.3.5 — servers (passwordless / password login, HTTP/HTTPS and Status: 0.3.6 — servers (passwordless / password login, HTTP/HTTPS and
SOCKS5/socks5h proxy, self-signed certificates and pinning), session list with search and live SOCKS5/socks5h proxy, self-signed certificates and pinning), session list with search and live
events, chat with streaming Markdown and full history paging, tool steps events, chat with streaming Markdown and full history paging, tool steps
grouped per turn (icon, one-line summary, foldable run) with image previews, a grouped per turn (icon, one-line summary, foldable run) with image previews, a
+50 -1
View File
@@ -250,15 +250,64 @@ class Client {
} }
Future<void> prompt(String sessionId, Future<void> prompt(String sessionId,
{String text = '', String? messageId, String? directory, List<Map<String, String>>? files}) async { {String text = '',
String? messageId,
String? directory,
List<Map<String, String>>? files,
List<String>? skillIds}) async {
await _json('POST', '/api/session/${Uri.encodeComponent(sessionId)}/prompt', directory: directory, await _json('POST', '/api/session/${Uri.encodeComponent(sessionId)}/prompt', directory: directory,
body: { body: {
if (text.isNotEmpty) 'text': text, if (text.isNotEmpty) 'text': text,
if (messageId != null) 'id': messageId, if (messageId != null) 'id': messageId,
if (files != null && files.isNotEmpty) 'files': files, if (files != null && files.isNotEmpty) 'files': files,
if (skillIds != null && skillIds.isNotEmpty)
'skills': [
for (final id in skillIds) {'id': id},
],
}); });
} }
/// Runs a registered slash command (`/initialize`, `/review`, …). The
/// server expands the command template and starts the turn.
Future<void> command(String sessionId,
{required String name, String text = '', String? directory,
List<Map<String, String>>? files}) async {
await _json('POST', '/api/session/${Uri.encodeComponent(sessionId)}/command',
directory: directory,
body: {
'name': name,
'text': text,
if (files != null && files.isNotEmpty) 'files': files,
});
}
/// The commands this directory registers (`/api/command`).
Future<List<Map<String, String>>> commands({String? directory}) async {
final r = await _json('GET', '/api/command', directory: directory);
return [
for (final e in (r['data'] as List? ?? []))
if (e is Map)
{
'name': e['name'] as String? ?? '',
'description': e['description'] as String? ?? '',
},
];
}
/// The skills opencode knows in this directory (`/api/skill`).
Future<List<Map<String, String>>> skills({String? directory}) async {
final r = await _json('GET', '/api/skill', directory: directory);
return [
for (final e in (r['data'] as List? ?? []))
if (e is Map)
{
'id': e['id'] as String? ?? '',
'name': e['name'] as String? ?? '',
'description': e['description'] as String? ?? '',
},
];
}
Future<bool> interrupt(String sessionId, {String? directory}) async { Future<bool> interrupt(String sessionId, {String? directory}) async {
final r = await _json('POST', '/api/session/${Uri.encodeComponent(sessionId)}/interrupt', final r = await _json('POST', '/api/session/${Uri.encodeComponent(sessionId)}/interrupt',
directory: directory, body: const {}); directory: directory, body: const {});
+37
View File
@@ -158,6 +158,29 @@ class ToolState {
}; };
} }
/// The error OpenCode recorded on a message (a failed step, a failed
/// compaction). `body` is the provider's raw response, when there was one.
class MessageError {
final String type;
final String message;
final int? status;
final String? body;
const MessageError({this.type = '', this.message = '', this.status, this.body});
factory MessageError.fromJson(Map<String, dynamic> j) {
final data = j['data'];
final response = j['response'];
return MessageError(
type: (j['type'] ?? j['name'] ?? '') as String? ?? '',
message: (j['message'] as String?) ??
(data is Map ? data['message'] as String? : null) ??
'',
status: (j['status'] as num?)?.toInt(),
body: response is Map ? response['body'] as String? : null,
);
}
bool get isEmpty => type.isEmpty && message.isEmpty;
}
class Message { class Message {
final String id; final String id;
final String type; final String type;
@@ -171,6 +194,12 @@ class Message {
final String finish; final String finish;
final double cost; final double cost;
final TokenUsage? tokens; final TokenUsage? tokens;
/// Set when the step (or compaction) failed.
final MessageError? error;
/// Compaction messages: 'failed' etc.
final String status;
/// Compaction messages: why it ran ('manual').
final String reason;
Message({ Message({
required this.id, required this.id,
required this.type, required this.type,
@@ -184,6 +213,9 @@ class Message {
this.finish = '', this.finish = '',
this.cost = 0, this.cost = 0,
this.tokens, this.tokens,
this.error,
this.status = '',
this.reason = '',
}); });
factory Message.fromJson(Map<String, dynamic> j) { factory Message.fromJson(Map<String, dynamic> j) {
final t = j['time'] as Map<String, dynamic>? ?? {}; final t = j['time'] as Map<String, dynamic>? ?? {};
@@ -206,6 +238,11 @@ class Message {
finish: j['finish'] as String? ?? '', finish: j['finish'] as String? ?? '',
cost: (j['cost'] as num?)?.toDouble() ?? 0, cost: (j['cost'] as num?)?.toDouble() ?? 0,
tokens: j['tokens'] == null ? null : TokenUsage.fromJson(j['tokens'] as Map<String, dynamic>), tokens: j['tokens'] == null ? null : TokenUsage.fromJson(j['tokens'] as Map<String, dynamic>),
error: j['error'] == null
? null
: MessageError.fromJson(j['error'] as Map<String, dynamic>),
status: j['status'] as String? ?? '',
reason: j['reason'] as String? ?? '',
); );
} }
String get partText { String get partText {
+472 -7
View File
@@ -30,6 +30,7 @@ class ChatScreen extends StatefulWidget {
class _ChatScreenState extends State<ChatScreen> { class _ChatScreenState extends State<ChatScreen> {
ChatState get chat => widget.app.chat!; ChatState get chat => widget.app.chat!;
final TextEditingController _draftCtrl = TextEditingController(); final TextEditingController _draftCtrl = TextEditingController();
final FocusNode _inputFocus = FocusNode();
final ScrollController _scroll = ScrollController(); final ScrollController _scroll = ScrollController();
bool _stick = true; bool _stick = true;
bool _pickerOpen = false; bool _pickerOpen = false;
@@ -38,6 +39,10 @@ class _ChatScreenState extends State<ChatScreen> {
List<_Attach> _attachments = []; List<_Attach> _attachments = [];
bool _attaching = false; 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 /// 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). /// header of each run folds it away (key: message id and start part).
/// These are the runs the person folded or unfolded, overriding the /// These are the runs the person folded or unfolded, overriding the
@@ -78,6 +83,7 @@ class _ChatScreenState extends State<ChatScreen> {
void dispose() { void dispose() {
chat.removeListener(_onChat); chat.removeListener(_onChat);
_draftCtrl.dispose(); _draftCtrl.dispose();
_inputFocus.dispose();
_scroll.dispose(); _scroll.dispose();
super.dispose(); super.dispose();
} }
@@ -194,6 +200,26 @@ class _ChatScreenState extends State<ChatScreen> {
_turnRows(out, mi, end); _turnRows(out, mi, end);
mi = end; mi = end;
break; 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': case 'shell':
out.add(_Row('shell', m.id, -1)); out.add(_Row('shell', m.id, -1));
break; break;
@@ -238,8 +264,14 @@ class _ChatScreenState extends State<ChatScreen> {
} }
} }
flush(); flush();
if (chat.msgs[to].completed > 0 && _turnEndsAt(to)) { final last = chat.msgs[to];
out.add(_Row('footer', chat.msgs[to].id, -1)); // 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); return _stepRow(r.msgId, r.part);
case 'footer': case 'footer':
return _footerRow(r.msgId); return _footerRow(r.msgId);
case 'error':
return _errorRow(r.msgId);
case 'shell': case 'shell':
return Padding( return Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4), 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) { String _turnDuration(Message m) {
var start = 0; var start = 0;
final idx = chat.msgs.indexWhere((x) => x.id == m.id); 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 // 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/ // trailing send/stop key, all 36px round keys (MIT, app/lib/ui/chat/
// composer.dart, referenced rather than copied). // 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() { Widget _composer() {
final usage = chat.usageReading(); final usage = chat.usageReading();
final scheme = Theme.of(context).colorScheme; final scheme = Theme.of(context).colorScheme;
final canSend = _draftCtrl.text.trim().isNotEmpty || _attachments.isNotEmpty; final canSend = _draftCtrl.text.trim().isNotEmpty || _attachments.isNotEmpty;
return SafeArea( final slash = _slashMatches();
top: false, final slashRows = slash ?? const <SlashItem>[];
child: Padding( Widget body = Padding(
padding: const EdgeInsets.fromLTRB(8, 6, 8, 6), padding: const EdgeInsets.fromLTRB(8, 6, 8, 6),
child: Column( child: Column(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
if (_attachments.isNotEmpty) _attachmentTray(), if (_attachments.isNotEmpty) _attachmentTray(),
if (slash != null) ...[
KeyedSubtree(
key: const ValueKey('slash-palette'),
child: _slashPalette(slashRows),
),
const SizedBox(height: 6),
],
Container( Container(
key: const ValueKey('composer-bar'),
padding: const EdgeInsets.all(6), padding: const EdgeInsets.all(6),
decoration: BoxDecoration( decoration: BoxDecoration(
color: scheme.surfaceContainerHighest, color: scheme.surfaceContainerHighest,
@@ -1035,13 +1447,44 @@ class _ChatScreenState extends State<ChatScreen> {
Expanded( Expanded(
child: TextField( child: TextField(
controller: _draftCtrl, controller: _draftCtrl,
focusNode: _inputFocus,
minLines: 1, minLines: 1,
maxLines: 5, maxLines: 5,
keyboardType: TextInputType.multiline, 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) { onChanged: (v) {
chat.draft = v; chat.draft = v;
_slashIndex = 0;
if (_slashDismissed != null && v != _slashDismissed) {
_slashDismissed = null;
}
if (v.trimLeft().startsWith('/')) chat.ensureSlash();
setState(() {}); 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), style: const TextStyle(fontSize: 15, height: 1.45),
decoration: InputDecoration( 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(); _draftCtrl.clear();
setState(() => _attachments = []); setState(() => _attachments = []);
if (images.isNotEmpty) { if (images.isNotEmpty && id.isNotEmpty) {
chat.imagePaths[id] = images; chat.imagePaths[id] = images;
chat.touch(); chat.touch();
} }
+151 -4
View File
@@ -479,6 +479,25 @@ class AppState extends ChangeNotifier {
// The open chat. // The open chat.
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
/// One entry of the composer's `/` palette: a command registered for the
/// directory, or a skill opencode can attach to a prompt.
class SlashItem {
final String name;
final String description;
final bool skill;
final String id;
const SlashItem({
required this.name,
this.description = '',
this.skill = false,
this.id = '',
});
/// Commands whose description shows an argument form (`[commit|branch|pr]`)
/// expect one; the palette completes those and runs the rest outright.
bool get takesArgs => description.contains('[');
}
class ChatState extends ChangeNotifier { class ChatState extends ChangeNotifier {
final AppState app; final AppState app;
final Session session; final Session session;
@@ -498,6 +517,11 @@ class ChatState extends ChangeNotifier {
ModelRef? selectedModel; ModelRef? selectedModel;
String selectedAgent; String selectedAgent;
/// `/` palette contents, loaded once per open chat.
List<SlashItem> slashItems = [];
bool slashLoading = false;
bool _slashLoaded = false;
ChatState(this.app, this.session) ChatState(this.app, this.session)
: selectedModel = session.model, : selectedModel = session.model,
selectedAgent = session.agent; selectedAgent = session.agent;
@@ -520,6 +544,7 @@ class ChatState extends ChangeNotifier {
olderCursor = page.next; olderCursor = page.next;
hasMore = page.next != null && page.data.length >= _pageSize; hasMore = page.next != null && page.data.length >= _pageSize;
loading = false; loading = false;
error = null;
notifyListeners(); notifyListeners();
await reloadTail(); await reloadTail();
} catch (e) { } catch (e) {
@@ -529,6 +554,54 @@ class ChatState extends ChangeNotifier {
} }
} }
/// Loads the directory's commands and skills for the `/` palette. Called
/// when the palette first opens and before a `/name` send, so a typed
/// command never falls through to the model as plain text.
Future<void> ensureSlash() async {
if (_slashLoaded || slashLoading) return;
final cl = app.client;
if (cl == null) return;
slashLoading = true;
notifyListeners();
try {
final results = await Future.wait([
cl.commands(directory: dir),
cl.skills(directory: dir),
]);
slashItems = [
for (final c in results[0])
if ((c['name'] ?? '').isNotEmpty)
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'] ?? '',
),
];
_slashLoaded = true;
} catch (_) {
// Keep the palette empty; a send falls back to a plain prompt.
}
slashLoading = false;
notifyListeners();
}
SlashItem? slashFor(String text) {
final m = RegExp(r'^/([^\s/]+)').firstMatch(text.trimLeft());
if (m == null) return null;
final name = m.group(1)!;
for (final item in slashItems) {
if (item.name == name) return item;
}
return null;
}
/// Refreshes the newest page without dropping the older pages that were /// Refreshes the newest page without dropping the older pages that were
/// already loaded; the server's copy wins for messages it returns. /// already loaded; the server's copy wins for messages it returns.
Future<void> reloadTail() async { Future<void> reloadTail() async {
@@ -591,8 +664,61 @@ class ChatState extends ChangeNotifier {
Future<String?> send({String? text, List<Map<String, String>>? files}) async { Future<String?> send({String? text, List<Map<String, String>>? files}) async {
final t = (text ?? draft).trim(); final t = (text ?? draft).trim();
if (t.isEmpty && (files == null || files.isEmpty)) return null; if (t.isEmpty && (files == null || files.isEmpty)) return null;
if (t.startsWith('/')) {
await ensureSlash();
final item = slashFor(t);
if (item != null) {
final args =
(RegExp(r'^/\S+\s*([\s\S]*)$').firstMatch(t)?.group(1) ?? '').trim();
draft = '';
if (!item.skill) {
// A command is expanded by the server, which also writes the user
// message; there is no id to show optimistically.
try {
await app.client!.command(this.id,
name: item.name, text: args, directory: dir, files: files);
error = null;
await reloadTail();
return '';
} catch (e) {
draft = t;
error = e.toString();
notifyListeners();
return null;
}
}
final id = _newMsgId();
msgs.add(Message(
id: id,
type: 'user',
text: t,
created: DateTime.now().millisecondsSinceEpoch,
files: files?.map((f) => FileAttachment(f['name'] ?? '附件', '')).toList() ?? const [],
));
_sortMsgs();
notifyListeners();
try {
// The skill is attached by id; the text still names it, as the
// official composer sends it.
await app.client!.prompt(this.id,
text: t, messageId: id, directory: dir, files: files,
skillIds: [item.id]);
error = null;
notifyListeners();
return id;
} catch (e) {
msgs.removeWhere((m) => m.id == id);
_reindex();
draft = t;
error = e.toString();
notifyListeners();
return null;
}
}
}
final id = _newMsgId(); final id = _newMsgId();
draft = ''; draft = '';
error = null;
msgs.add(Message( msgs.add(Message(
id: id, id: id,
type: 'user', type: 'user',
@@ -604,6 +730,10 @@ class ChatState extends ChangeNotifier {
notifyListeners(); notifyListeners();
try { try {
await app.client!.prompt(this.id, text: t, messageId: id, directory: dir, files: files); await app.client!.prompt(this.id, text: t, messageId: id, directory: dir, files: files);
if (error != null) {
error = null;
notifyListeners();
}
return id; return id;
} catch (e) { } catch (e) {
// The prompt did not reach the server: take the optimistic message back // The prompt did not reach the server: take the optimistic message back
@@ -719,6 +849,9 @@ class ChatState extends ChangeNotifier {
switch (type) { switch (type) {
case 'session.execution.started': case 'session.execution.started':
running = true; running = true;
// A command's user message is written by the server, and another
// client may have sent it: take the tail from the server.
reloadTail();
break; break;
case 'session.execution.succeeded': case 'session.execution.succeeded':
case 'session.execution.failed': case 'session.execution.failed':
@@ -745,7 +878,12 @@ class ChatState extends ChangeNotifier {
cost: (data['cost'] as num?)?.toDouble() ?? m.cost, cost: (data['cost'] as num?)?.toDouble() ?? m.cost,
tokens: data['tokens'] == null tokens: data['tokens'] == null
? m.tokens ? m.tokens
: TokenUsage.fromJson(data['tokens'] as Map<String, dynamic>))); : TokenUsage.fromJson(data['tokens'] as Map<String, dynamic>),
error: data['error'] == null
? m.error
: MessageError.fromJson(data['error'] as Map<String, dynamic>),
status: m.status,
reason: m.reason));
// Live events name a tool only by id, so a streamed step would keep // Live events name a tool only by id, so a streamed step would keep
// a generic label ("工具") until the session was reopened. The // a generic label ("工具") until the session was reopened. The
// finished message has the names, inputs and attachments. // finished message has the names, inputs and attachments.
@@ -841,7 +979,10 @@ class ChatState extends ChangeNotifier {
files: m.files, files: m.files,
finish: m.finish, finish: m.finish,
cost: m.cost, cost: m.cost,
tokens: m.tokens); tokens: m.tokens,
error: m.error,
status: m.status,
reason: m.reason);
}); });
} }
@@ -901,7 +1042,10 @@ class ChatState extends ChangeNotifier {
files: m.files, files: m.files,
finish: m.finish, finish: m.finish,
cost: m.cost, cost: m.cost,
tokens: m.tokens); tokens: m.tokens,
error: m.error,
status: m.status,
reason: m.reason);
} }
} }
content.add(part); content.add(part);
@@ -917,7 +1061,10 @@ class ChatState extends ChangeNotifier {
files: m.files, files: m.files,
finish: m.finish, finish: m.finish,
cost: m.cost, cost: m.cost,
tokens: m.tokens); tokens: m.tokens,
error: m.error,
status: m.status,
reason: m.reason);
}); });
} }
+1 -1
View File
@@ -2,7 +2,7 @@ name: openchamber
description: "A lightweight OpenChamber client for phones." description: "A lightweight OpenChamber client for phones."
publish_to: 'none' publish_to: 'none'
version: 0.3.5+305 version: 0.3.6+306
environment: environment:
sdk: ^3.14.0 sdk: ^3.14.0