feat: queue a message for the running turn, and fold the composer when the IME closes

- A send while a turn runs joins it (delivery "steer") on a short press; a
  long press offers steer or queue. Queue/steer prompts wait in the server's
  inbox and show as a pending bubble at the end of the transcript, with
  改为排队/转为转向 and 撤回 (which puts the text back into the composer).
  The inbox is read on open and resume and kept current by the
  session.inbox.* events; delivery reloads the tail.
- The send key is stop only while running with an empty draft; with text it
  sends (as dsh-Go does), leaving the long press for the delivery choice.
- The composer also folds to one line when the phone's back gesture closes
  the keyboard while the field keeps focus: the page passes the keyboard
  height (a Scaffold strips the bottom inset from its body) and the composer
  treats a fall below half the peak as a dismissal.
- The Build/Plan chip now opens a bottom sheet with icons, hints and a check,
  instead of a popup menu.
- Tests: composer_box_test (focus opens, IME dismissal folds, typing reopens)
  and inbox_item_test (list items, enqueued events, delivery changes).
- 0.3.16 (316).
This commit is contained in:
blumia committed 2026-11-21 18:32:57 +08:00
1 parent ea3b1f0f5e
commit 1aa84a53e5
13 files changed
+649 -43

No files matched your search

+10
View File
@@ -5,6 +5,16 @@
--- ---
## 0.3.16 输入法收起、模式面板与排队消息(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 输入框收起 | 手机返回手势关闭输入法(焦点仍在)时,输入框也收回单行:dsh-Go 用键盘高度判断;`Scaffold` 会从 body 去掉底部 viewInsets,所以由 `HomeScreen`(Scaffold 之上)读取键盘高度,经 `ChatScreen` / `NewSessionScreen` 传给 `ComposerBox`。键盘升到过的峰值一半以下即视为收起,再次唤起时展开。新增 `test/composer_box_test.dart` 覆盖 |
| 模式面板 | 「模式」(Build / Plan)chip 由下拉框改为底部面板:标题、图标、说明、当前项打勾;仍与模型/思考强度分开 |
| 排队消息 | 运行中短按发送默认「转向」(`delivery: steer`),长按发送键弹出「转向当前回合 / 排队」,只用服务端支持的 steer/queue。排队或转向的消息不乐观写入对话,而是显示为末尾的待发气泡(半透明 + 状态:正在转入 / 已排队 / 未发送),可「改为排队 / 转为转向」与「撤回」(`DELETE /api/session/:id/inbox/:id`,文本放回输入框)。打开会话与前台恢复时 `GET /api/session/:id/inbox`;订阅 `session.inbox.enqueued / delivered / cancelled / delivery.changed`,送达时刷新尾部。运行且输入框有文字时发送键显示为发送(dsh-Go 行为),空输入时才显示停止 |
| 版本 | **0.3.16(code 316)** |
---
## 0.3.15 输入框两行折叠、模型与思考成组、模式独立(分支 `flutter`) ## 0.3.15 输入框两行折叠、模型与思考成组、模式独立(分支 `flutter`)
| 项 | 结果 | | 项 | 结果 |
+7 -4
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.15 — servers (passwordless / password login, HTTP/HTTPS and Status: 0.3.16 — 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
@@ -18,9 +18,12 @@ show their progress and can be cancelled. The panel is a tab row with its own
close button, and each tab has its own header row. Starting a session opens a close button, and each tab has its own header row. Starting a session opens a
draft that only creates the session on the first send; the session list is draft that only creates the session on the first send; the session list is
grouped by project with date captions, pins, archive and swipe actions. The grouped by project with date captions, pins, archive and swipe actions. The
composer folds to one line when unfocused and opens into two rows on focus (as composer folds to one line when unfocused (or when the keyboard is dismissed)
in dsh-Go): the model and its thinking level form one pill, the Build/Plan mode and opens into two rows on focus, as in dsh-Go: the model and its thinking level
a separate chip. The picker groups providers, favourites, recents and context size. A form one pill, the Build/Plan mode a separate chip (picked from a sheet). A
message sent while a turn runs can steer it or queue for its end, and waits as a
pending bubble that can be withdrawn. The picker groups providers, favourites,
recents and context size. A
phone opens the session list as the left drawer and a wide window (tablet, phone opens the session list as the left drawer and a wide window (tablet,
desktop) shows it beside the chat. Android 7.0 (API 24)+, plus a Linux desktop desktop) shows it beside the chat. Android 7.0 (API 24)+, plus a Linux desktop
target used for local testing. target used for local testing.
+34 -2
View File
@@ -181,22 +181,54 @@ class Client {
body: {'decision': decision, if (message.isNotEmpty) 'message': message}); body: {'decision': decision, if (message.isNotEmpty) 'message': message});
} }
Future<void> prompt(String sessionId, /// Sends a prompt. [delivery] is 'steer' or 'queue' on a running turn; with
/// none the server starts a turn when idle. Returns the inbox item id.
Future<String?> prompt(String sessionId,
{String text = '', {String text = '',
String? messageId, String? messageId,
String? directory, String? directory,
String? delivery,
List<Map<String, String>>? files, List<Map<String, String>>? files,
List<String>? skillIds}) async { List<String>? skillIds}) async {
await _json('POST', '/api/session/${Uri.encodeComponent(sessionId)}/prompt', directory: directory, final r = 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 (delivery != null) 'delivery': delivery,
if (files != null && files.isNotEmpty) 'files': files, if (files != null && files.isNotEmpty) 'files': files,
if (skillIds != null && skillIds.isNotEmpty) if (skillIds != null && skillIds.isNotEmpty)
'skills': [ 'skills': [
for (final id in skillIds) {'id': id}, for (final id in skillIds) {'id': id},
], ],
}); });
final data = r['data'];
return data is Map ? data['id'] as String? : null;
}
/// Prompts waiting in the session's inbox (queued or about to steer).
Future<List<InboxItem>> inbox(String sessionId, {String? directory}) async {
final r = await _json('GET', '/api/session/${Uri.encodeComponent(sessionId)}/inbox',
directory: directory);
return [
for (final e in (r['data'] as List? ?? []))
if (e is Map<String, dynamic> && e['type'] == 'user')
InboxItem.fromJson(e),
];
}
/// Takes a waiting prompt out of the inbox.
Future<void> cancelInbox(String sessionId, String inboxId, {String? directory}) async {
await _json('DELETE',
'/api/session/${Uri.encodeComponent(sessionId)}/inbox/${Uri.encodeComponent(inboxId)}',
directory: directory);
}
/// Moves a waiting prompt between `steer` and `queue`.
Future<void> updateInbox(String sessionId, String inboxId, String delivery,
{String? directory}) async {
await _json('PATCH',
'/api/session/${Uri.encodeComponent(sessionId)}/inbox/${Uri.encodeComponent(inboxId)}',
directory: directory, body: {'delivery': delivery});
} }
/// Runs a registered slash command (`/initialize`, `/review`, …). The /// Runs a registered slash command (`/initialize`, `/review`, …). The
+62
View File
@@ -403,6 +403,68 @@ class FileAttachment {
); );
} }
/// A prompt the server holds in the session's inbox until it is delivered:
/// `queue` waits for the running turn to end, `steer` joins it at its next
/// step. The message only enters the transcript when it is delivered.
class InboxItem {
final String id;
final String text;
/// 'steer' | 'queue'.
final String delivery;
final int created;
final List<FileAttachment> files;
const InboxItem({
required this.id,
required this.text,
required this.delivery,
this.created = 0,
this.files = const [],
});
/// Non-user inbox entries (compaction, moves, synthetic context) are the
/// server's own; only what the person typed is shown.
factory InboxItem.fromJson(Map<String, dynamic> j) {
final time = j['time'] as Map<String, dynamic>? ?? {};
final payload = j['payload'] as Map<String, dynamic>? ?? {};
return InboxItem(
id: j['id'] as String,
text: payload['text'] as String? ?? '',
delivery: j['delivery'] as String? ?? 'queue',
created: (time['created'] as num?)?.toInt() ?? 0,
files: (payload['files'] as List?)
?.map((e) => FileAttachment.fromJson(e as Map<String, dynamic>))
.toList() ??
const [],
);
}
/// An `enqueued` event carries the payload under `item` and the id beside
/// it, rather than in the item.
factory InboxItem.fromEvent(String id, Map<String, dynamic> j, int created) {
final payload = j['payload'] as Map<String, dynamic>? ?? {};
return InboxItem(
id: id,
text: payload['text'] as String? ?? '',
delivery: j['delivery'] as String? ?? 'queue',
created: created,
files: (payload['files'] as List?)
?.map((e) => FileAttachment.fromJson(e as Map<String, dynamic>))
.toList() ??
const [],
);
}
InboxItem withDelivery(String value) => InboxItem(
id: id,
text: text,
delivery: value,
created: created,
files: files,
);
}
/// One row of a native form's choice control. /// One row of a native form's choice control.
class FormOption { class FormOption {
final String value; final String value;
+153 -10
View File
@@ -25,10 +25,15 @@ class ChatScreen extends StatefulWidget {
/// Opens the session drawer. Null where the list is always on screen (a /// Opens the session drawer. Null where the list is always on screen (a
/// wide layout), so no menu button is shown there. /// wide layout), so no menu button is shown there.
final VoidCallback? onOpenSessions; final VoidCallback? onOpenSessions;
/// The soft keyboard's height, from above the shell's Scaffold (which
/// removes the bottom inset from its body).
final double keyboardInset;
const ChatScreen({ const ChatScreen({
super.key, super.key,
required this.app, required this.app,
required this.session, required this.session,
this.keyboardInset = 0,
this.onOpenSessions, this.onOpenSessions,
}); });
@@ -143,7 +148,7 @@ class _ChatScreenState extends State<ChatScreen> {
Expanded(child: _messageList()), Expanded(child: _messageList()),
_permissions(), _permissions(),
_forms(), _forms(),
_composer(), _composer(widget.keyboardInset),
], ],
), ),
); );
@@ -239,6 +244,11 @@ class _ChatScreenState extends State<ChatScreen> {
break; break;
} }
} }
// Prompts waiting in the inbox stand after the transcript, as dsh-Go's
// pending bubbles do.
for (final item in chat.inbox) {
out.add(_Row('pending', item.id, -1));
}
return out; return out;
} }
@@ -358,6 +368,8 @@ class _ChatScreenState extends State<ChatScreen> {
return _userRow(r.msgId); return _userRow(r.msgId);
case 'useractions': case 'useractions':
return _userActions(r.msgId); return _userActions(r.msgId);
case 'pending':
return _pendingBubble(r.msgId);
case 'thinking': case 'thinking':
return const Padding( return const Padding(
padding: EdgeInsets.symmetric(horizontal: 16, vertical: 6), padding: EdgeInsets.symmetric(horizontal: 16, vertical: 6),
@@ -397,6 +409,87 @@ class _ChatScreenState extends State<ChatScreen> {
return widget.session.title.isEmpty ? '会话' : widget.session.title; return widget.session.title.isEmpty ? '会话' : widget.session.title;
} }
/// A prompt in the server's inbox: dimmer than a sent message, with the
/// label dsh-Go uses and its actions (switch between steering and queueing,
/// or take it back into the composer).
Widget _pendingBubble(String id) {
final item = chat.inbox.where((i) => i.id == id).firstOrNull;
if (item == null) return const SizedBox.shrink();
final theme = Theme.of(context);
final scheme = theme.colorScheme;
final steering = item.delivery == 'steer';
return Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Align(
alignment: Alignment.centerRight,
child: Container(
constraints: const BoxConstraints(maxWidth: 320),
margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: scheme.primary.withValues(alpha: 0.55),
borderRadius: BorderRadius.circular(16),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
if (item.text.isNotEmpty)
Text(item.text,
style: TextStyle(color: scheme.onPrimary)),
if (item.files.isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 4),
child: Text('📎 ${item.files.length} 个附件',
style: TextStyle(
color: scheme.onPrimary, fontSize: 12.5)),
),
],
),
),
),
Padding(
padding: const EdgeInsets.only(right: 6),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(steering ? Icons.alt_route : Icons.schedule,
size: 13, color: theme.hintColor),
const SizedBox(width: 3),
Text(
!chat.running
? '未发送'
: steering
? '正在转入当前回合…'
: '已排队,本轮结束后发送',
style: TextStyle(fontSize: 12, color: theme.hintColor),
),
const SizedBox(width: 4),
TextButton(
onPressed: () => chat.changeInboxDelivery(
item.id, steering ? 'queue' : 'steer'),
child: Text(steering ? '改为排队' : '转为转向',
style: const TextStyle(fontSize: 12.5)),
),
TextButton(
onPressed: () async {
final ok = await chat.withdrawInbox(item.id);
if (!ok || !mounted) return;
_draftCtrl.text = chat.draft;
_draftCtrl.selection = TextSelection.collapsed(
offset: _draftCtrl.text.length);
_inputFocus.requestFocus();
},
child: const Text('撤回',
style: TextStyle(fontSize: 12.5)),
),
],
),
),
],
);
}
Widget _userRow(String id) { Widget _userRow(String id) {
final m = chat.byId[id]!; final m = chat.byId[id]!;
final theme = Theme.of(context); final theme = Theme.of(context);
@@ -1332,10 +1425,12 @@ class _ChatScreenState extends State<ChatScreen> {
onPick: _pickSlash, onPick: _pickSlash,
); );
Widget _composer() { Widget _composer(double keyboardInset) {
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;
// The key is stop only while running with nothing to send.
final showStop = chat.running && !canSend;
final slash = _slashMatches(); final slash = _slashMatches();
final slashRows = slash ?? const <SlashItem>[]; final slashRows = slash ?? const <SlashItem>[];
Widget body = Padding( Widget body = Padding(
@@ -1356,6 +1451,7 @@ class _ChatScreenState extends State<ChatScreen> {
focusNode: _inputFocus, focusNode: _inputFocus,
hint: chat.running ? '生成中,仍可输入…' : '发消息…', hint: chat.running ? '生成中,仍可输入…' : '发消息…',
maxLines: 5, maxLines: 5,
keyboardInset: keyboardInset,
// While the palette is up, the keyboard's action key picks the // While the palette is up, the keyboard's action key picks the
// highlighted row instead of writing a newline. // highlighted row instead of writing a newline.
textInputAction: textInputAction:
@@ -1427,14 +1523,15 @@ class _ChatScreenState extends State<ChatScreen> {
), ),
) )
: null, : null,
// Stop only while the turn runs with an empty draft; once there is
// something to send the key sends again, as dsh-Go's does.
trailing: _roundKey( trailing: _roundKey(
icon: chat.running icon: showStop ? Icons.stop_rounded : Icons.arrow_upward_rounded,
? Icons.stop_rounded label: showStop ? '停止' : '发送',
: Icons.arrow_upward_rounded,
label: chat.running ? '停止' : '发送',
filled: true, filled: true,
enabled: chat.running || canSend, enabled: showStop || canSend,
onTap: chat.running ? chat.stop : _send, onTap: showStop ? chat.stop : _send,
onLongPress: showStop ? null : _sendOptions,
), ),
), ),
], ],
@@ -1470,6 +1567,7 @@ class _ChatScreenState extends State<ChatScreen> {
required IconData icon, required IconData icon,
required String label, required String label,
required VoidCallback onTap, required VoidCallback onTap,
VoidCallback? onLongPress,
bool filled = false, bool filled = false,
bool enabled = true, bool enabled = true,
bool busy = false, bool busy = false,
@@ -1492,6 +1590,7 @@ class _ChatScreenState extends State<ChatScreen> {
child: InkWell( child: InkWell(
customBorder: const CircleBorder(), customBorder: const CircleBorder(),
onTap: on ? onTap : null, onTap: on ? onTap : null,
onLongPress: on ? onLongPress : null,
child: SizedBox( child: SizedBox(
width: 36, width: 36,
height: 36, height: 36,
@@ -1516,9 +1615,53 @@ class _ChatScreenState extends State<ChatScreen> {
onRemove: (i) => setState(() => _attachments.removeAt(i)), onRemove: (i) => setState(() => _attachments.removeAt(i)),
); );
Future<void> _send() async { /// Long-press on send while a turn runs: join it (steer) or wait for it to
/// end (queue). Only the deliveries the server offers are listed.
Future<void> _sendOptions() async {
if (!chat.running) return _send();
final text = _draftCtrl.text.trim(); final text = _draftCtrl.text.trim();
if (text.isEmpty && _attachments.isEmpty) return; if (text.isEmpty && _attachments.isEmpty) return;
final picked = await showModalBottomSheet<String>(
context: context,
showDragHandle: true,
builder: (sheet) => SafeArea(
top: false,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Padding(
padding: EdgeInsets.fromLTRB(20, 4, 20, 8),
child: Text('发送方式',
style: TextStyle(fontSize: 16, fontWeight: FontWeight.w700)),
),
ListTile(
leading: const Icon(Icons.alt_route),
title: const Text('转向当前回合'),
subtitle: const Text('在下一步加入,工作继续'),
onTap: () => Navigator.pop(sheet, 'steer'),
),
ListTile(
leading: const Icon(Icons.schedule),
title: const Text('排队'),
subtitle: const Text('等本轮结束后发送'),
onTap: () => Navigator.pop(sheet, 'queue'),
),
const SizedBox(height: 8),
],
),
),
);
if (picked == null || !mounted) return;
await _send(delivery: picked);
}
Future<void> _send({String? delivery}) async {
final text = _draftCtrl.text.trim();
if (text.isEmpty && _attachments.isEmpty) return;
// An ordinary send while a turn runs joins it, as dsh-Go does; the
// long-press sheet can choose to wait instead.
final effective = chat.running ? (delivery ?? 'steer') : null;
// Files ride with the prompt as data URLs. // Files ride with the prompt as data URLs.
final files = <Map<String, String>>[]; final files = <Map<String, String>>[];
final images = <String>[]; final images = <String>[];
@@ -1528,7 +1671,7 @@ class _ChatScreenState extends State<ChatScreen> {
images.add(a.path!); images.add(a.path!);
} }
} }
final id = await chat.send(text: text, files: files); final id = await chat.send(text: text, files: files, delivery: effective);
if (id == null) { if (id == null) {
// The prompt failed: keep the text for a retry. // The prompt failed: keep the text for a retry.
_draftCtrl.text = chat.draft; _draftCtrl.text = chat.draft;
+4
View File
@@ -52,6 +52,8 @@ class _HomeScreenState extends State<HomeScreen> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
// Read above the shell's Scaffold: its body has the bottom inset removed.
final keyboardInset = MediaQuery.viewInsetsOf(context).bottom;
return ListenableBuilder( return ListenableBuilder(
listenable: widget.app, listenable: widget.app,
builder: (context, _) { builder: (context, _) {
@@ -65,6 +67,7 @@ class _HomeScreenState extends State<HomeScreen> {
? NewSessionScreen( ? NewSessionScreen(
key: const ValueKey('draft'), key: const ValueKey('draft'),
app: app, app: app,
keyboardInset: keyboardInset,
onOpenSessions: wide onOpenSessions: wide
? null ? null
: () => _scaffold.currentState?.openDrawer(), : () => _scaffold.currentState?.openDrawer(),
@@ -75,6 +78,7 @@ class _HomeScreenState extends State<HomeScreen> {
key: ValueKey(chat.session.id), key: ValueKey(chat.session.id),
app: app, app: app,
session: chat.session, session: chat.session,
keyboardInset: keyboardInset,
onOpenSessions: wide onOpenSessions: wide
? null ? null
: () => _scaffold.currentState?.openDrawer(), : () => _scaffold.currentState?.openDrawer(),
+7 -2
View File
@@ -18,10 +18,14 @@ class NewSessionScreen extends StatefulWidget {
/// Opens the session drawer; null where the list is always on screen. /// Opens the session drawer; null where the list is always on screen.
final VoidCallback? onOpenSessions; final VoidCallback? onOpenSessions;
/// The soft keyboard's height, from above the shell's Scaffold.
final double keyboardInset;
const NewSessionScreen({ const NewSessionScreen({
super.key, super.key,
required this.app, required this.app,
this.onOpenSessions, this.onOpenSessions,
this.keyboardInset = 0,
}); });
@override @override
@@ -255,7 +259,7 @@ class _NewSessionScreenState extends State<NewSessionScreen> {
items: _attachments, items: _attachments,
onRemove: _removeAttachment, onRemove: _removeAttachment,
), ),
_composer(theme), _composer(theme, widget.keyboardInset),
], ],
), ),
), ),
@@ -296,7 +300,7 @@ class _NewSessionScreenState extends State<NewSessionScreen> {
); );
} }
Widget _composer(ThemeData theme) { Widget _composer(ThemeData theme, double keyboardInset) {
final scheme = theme.colorScheme; final scheme = theme.colorScheme;
final sending = widget.app.sendingDraft; final sending = widget.app.sendingDraft;
final slash = _slashMatches(); final slash = _slashMatches();
@@ -306,6 +310,7 @@ class _NewSessionScreenState extends State<NewSessionScreen> {
focusNode: _inputFocus, focusNode: _inputFocus,
hint: '规划、构建或提问', hint: '规划、构建或提问',
maxLines: 5, maxLines: 5,
keyboardInset: keyboardInset,
textInputAction: textInputAction:
slash != null ? TextInputAction.send : TextInputAction.newline, slash != null ? TextInputAction.send : TextInputAction.newline,
onSubmitted: slash == null || slashRows.isEmpty onSubmitted: slash == null || slashRows.isEmpty
+163 -2
View File
@@ -26,6 +26,10 @@ const _eventTypes = [
'session.execution.succeeded', 'session.execution.succeeded',
'session.execution.failed', 'session.execution.failed',
'session.execution.interrupted', 'session.execution.interrupted',
'session.inbox.enqueued',
'session.inbox.delivered',
'session.inbox.cancelled',
'session.inbox.delivery.changed',
'session.step.started', 'session.step.started',
'session.step.ended', 'session.step.ended',
'session.step.failed', 'session.step.failed',
@@ -689,7 +693,10 @@ class AppState extends ChangeNotifier {
if (client == null) return; if (client == null) return;
_startStream(); _startStream();
await refreshSessions(); await refreshSessions();
if (chat != null) await chat!.reloadTail(); if (chat != null) {
await chat!.reloadTail();
await chat!.reloadInbox();
}
for (final terminal in terminals.values) { for (final terminal in terminals.values) {
await terminal.reconnectIfNeeded(); await terminal.reconnectIfNeeded();
} }
@@ -920,6 +927,10 @@ class ChatState extends ChangeNotifier {
/// The agent's pending questions (native forms), oldest first. /// The agent's pending questions (native forms), oldest first.
List<FormInfo> forms = []; List<FormInfo> forms = [];
/// Prompts waiting in the server's inbox (queued, or steering the running
/// turn), oldest first. They enter the transcript only when delivered.
List<InboxItem> inbox = [];
/// `/` palette contents, loaded once per open chat. /// `/` palette contents, loaded once per open chat.
List<SlashItem> slashItems = []; List<SlashItem> slashItems = [];
bool slashLoading = false; bool slashLoading = false;
@@ -951,6 +962,7 @@ class ChatState extends ChangeNotifier {
notifyListeners(); notifyListeners();
await reloadTail(); await reloadTail();
await reloadForms(); await reloadForms();
await reloadInbox();
} catch (e) { } catch (e) {
loading = false; loading = false;
error = e.toString(); error = e.toString();
@@ -1039,6 +1051,54 @@ class ChatState extends ChangeNotifier {
} catch (_) {} } catch (_) {}
} }
/// Fetches the prompts waiting in the inbox, which may have been queued by
/// another client while this one was closed.
Future<void> reloadInbox() async {
final cl = app.client;
if (cl == null) return;
try {
inbox = await cl.inbox(id, directory: dir);
notifyListeners();
} catch (_) {}
}
/// Takes a waiting prompt out of the inbox and puts its text back into the
/// composer, as dsh-Go's 撤回 does.
Future<bool> withdrawInbox(String inboxId) async {
final cl = app.client;
if (cl == null) return false;
final item = inbox.where((i) => i.id == inboxId).firstOrNull;
try {
await cl.cancelInbox(id, inboxId, directory: dir);
inbox.removeWhere((i) => i.id == inboxId);
if (item != null) draft = item.text;
notifyListeners();
return true;
} catch (e) {
error = e.toString();
notifyListeners();
return false;
}
}
/// Switches a waiting prompt between steering the running turn and waiting
/// for it to end.
Future<void> changeInboxDelivery(String inboxId, String delivery) async {
final cl = app.client;
if (cl == null) return;
try {
await cl.updateInbox(id, inboxId, delivery, directory: dir);
inbox = [
for (final i in inbox)
i.id == inboxId ? i.withDelivery(delivery) : i,
];
notifyListeners();
} catch (e) {
error = e.toString();
notifyListeners();
}
}
Future<void> replyForm(FormInfo form, Map<String, Object?> answer) async { Future<void> replyForm(FormInfo form, Map<String, Object?> answer) async {
final cl = app.client; final cl = app.client;
if (cl == null) return; if (cl == null) return;
@@ -1129,7 +1189,13 @@ class ChatState extends ChangeNotifier {
byId = {for (final m in msgs) m.id: m}; byId = {for (final m in msgs) m.id: m};
} }
Future<String?> send({String? text, List<Map<String, String>>? files}) async { /// Sends [text]. [delivery] is 'steer' (join the running turn at its next
/// step) or 'queue' (wait for it to end); with none, an idle session starts
/// a turn. Queue and steer prompts show as pending bubbles until the server
/// delivers them, so no user message is written here.
Future<String?> send({String? text,
List<Map<String, String>>? files,
String? delivery}) 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('/')) { if (t.startsWith('/')) {
@@ -1179,6 +1245,10 @@ class ChatState extends ChangeNotifier {
return null; return null;
} }
} }
// A skill can be queued like any prompt.
if (delivery != null) {
return _sendToInbox(t, files, delivery, skillIds: [item.id]);
}
final id = _newMsgId(); final id = _newMsgId();
msgs.add(Message( msgs.add(Message(
id: id, id: id,
@@ -1208,6 +1278,9 @@ class ChatState extends ChangeNotifier {
} }
} }
} }
if (delivery != null) {
return _sendToInbox(t, files, delivery);
}
final id = _newMsgId(); final id = _newMsgId();
draft = ''; draft = '';
error = null; error = null;
@@ -1239,6 +1312,61 @@ class ChatState extends ChangeNotifier {
} }
} }
/// A prompt for the server's inbox: it shows as a pending bubble at the end
/// of the chat until the server delivers it into the transcript.
Future<String?> _sendToInbox(String text,
List<Map<String, String>>? files, String delivery,
{List<String>? skillIds}) async {
final id = _newMsgId();
final item = InboxItem(
id: id,
text: text,
delivery: delivery,
created: DateTime.now().millisecondsSinceEpoch,
files: files
?.map((f) => FileAttachment(f['name'] ?? '附件', ''))
.toList() ??
const [],
);
draft = '';
error = null;
inbox = [...inbox, item]..sort((a, b) => a.created.compareTo(b.created));
notifyListeners();
try {
final serverId = await app.client!.prompt(this.id,
text: text,
messageId: id,
directory: dir,
files: files,
delivery: delivery,
skillIds: skillIds);
// The server names the inbox item; keep the bubble keyed to it so the
// cancel and delivery events find it.
if (serverId != null && serverId != id) {
inbox = [
for (final i in inbox)
i.id == id
? InboxItem(
id: serverId,
text: i.text,
delivery: i.delivery,
created: i.created,
files: i.files)
: i,
];
}
error = null;
notifyListeners();
return serverId ?? id;
} catch (e) {
inbox.removeWhere((i) => i.id == id);
draft = text;
error = e.toString();
notifyListeners();
return null;
}
}
static String _newMsgId() => static String _newMsgId() =>
'msg_${DateTime.now().microsecondsSinceEpoch.toRadixString(36)}'; 'msg_${DateTime.now().microsecondsSinceEpoch.toRadixString(36)}';
@@ -1481,6 +1609,39 @@ class ChatState extends ChangeNotifier {
final agent = data['agent']; final agent = data['agent'];
if (agent is String && agent.isNotEmpty) selectedAgent = agent; if (agent is String && agent.isNotEmpty) selectedAgent = agent;
break; break;
case 'session.inbox.enqueued':
final iid = data['inboxID'] as String?;
final raw = data['item'];
if (iid != null && raw is Map<String, dynamic> && raw['type'] == 'user') {
final parsed = InboxItem.fromEvent(iid, raw, created);
inbox = [
for (final i in inbox)
if (i.id != iid) i,
parsed,
]..sort((a, b) => a.created.compareTo(b.created));
} else {
reloadInbox();
}
break;
case 'session.inbox.delivered':
final iid = data['inboxID'] as String?;
if (iid != null) inbox.removeWhere((i) => i.id == iid);
// The message enters the transcript now: take the server's copy.
reloadTail();
break;
case 'session.inbox.cancelled':
final iid = data['inboxID'] as String?;
if (iid != null) inbox.removeWhere((i) => i.id == iid);
break;
case 'session.inbox.delivery.changed':
final iid = data['inboxID'] as String?;
final d = data['delivery'] as String?;
if (iid != null && d != null) {
inbox = [
for (final i in inbox) i.id == iid ? i.withDelivery(d) : i,
];
}
break;
} }
notifyListeners(); notifyListeners();
} }
+56 -1
View File
@@ -9,6 +9,10 @@ class ComposerBox extends StatefulWidget {
final FocusNode focusNode; final FocusNode focusNode;
final String hint; final String hint;
final int maxLines; final int maxLines;
/// The soft keyboard's height, from the page (a Scaffold removes the bottom
/// view inset from its body, so the composer cannot read it itself).
final double keyboardInset;
final ValueChanged<String>? onChanged; final ValueChanged<String>? onChanged;
final ValueChanged<String>? onSubmitted; final ValueChanged<String>? onSubmitted;
final TextInputAction textInputAction; final TextInputAction textInputAction;
@@ -40,6 +44,7 @@ class ComposerBox extends StatefulWidget {
this.mode, this.mode,
this.accessory, this.accessory,
this.maxLines = 5, this.maxLines = 5,
this.keyboardInset = 0,
this.onChanged, this.onChanged,
this.onSubmitted, this.onSubmitted,
this.textInputAction = TextInputAction.newline, this.textInputAction = TextInputAction.newline,
@@ -55,6 +60,12 @@ class _ComposerBoxState extends State<ComposerBox> {
final GlobalKey _fieldKey = GlobalKey(); final GlobalKey _fieldKey = GlobalKey();
bool _open = false; bool _open = false;
// The keyboard went down with the field still focused (the phone's back
// gesture closes the IME without unfocusing). dsh-Go folds the composer in
// that case too, so the same rule is kept here.
bool _keyboardDown = false;
double _keyboardPeak = 0;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
@@ -68,8 +79,52 @@ class _ComposerBoxState extends State<ComposerBox> {
super.dispose(); super.dispose();
} }
@override
void didUpdateWidget(ComposerBox oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.focusNode != widget.focusNode) {
oldWidget.focusNode.removeListener(_onFocus);
widget.focusNode.addListener(_onFocus);
}
if (oldWidget.keyboardInset != widget.keyboardInset) {
_keyboardMoved(oldWidget.keyboardInset, widget.keyboardInset);
// The build that follows reads this; no second one is needed.
_open = widget.focusNode.hasFocus && !_keyboardDown;
}
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
// A sheet over the page takes the keyboard for a moment; when the page is
// current again, settle on where the composer should be.
WidgetsBinding.instance.addPostFrameCallback((_) => _syncOpen());
}
/// A keyboard rising clears "down"; falling to well under its peak means it
/// was dismissed (a height change alone stays open).
void _keyboardMoved(double before, double inset) {
if (!(ModalRoute.of(context)?.isCurrent ?? true)) return;
if (inset > before) {
_keyboardDown = false;
if (inset > _keyboardPeak) _keyboardPeak = inset;
} else if (inset < _keyboardPeak * 0.5) {
_keyboardDown = true;
_keyboardPeak = 0;
}
}
void _onFocus() { void _onFocus() {
final open = widget.focusNode.hasFocus; if (widget.focusNode.hasFocus) _keyboardDown = false;
_syncOpen();
}
void _syncOpen() {
if (!mounted) return;
// The model sheet (or any page over this one) takes focus for a moment:
// leave the composer as it is until it is current again.
if (!(ModalRoute.of(context)?.isCurrent ?? true)) return;
final open = widget.focusNode.hasFocus && !_keyboardDown;
if (open == _open) return; if (open == _open) return;
setState(() => _open = open); setState(() => _open = open);
} }
+45 -21
View File
@@ -63,36 +63,60 @@ class ModeChip extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final current = agent.isEmpty ? _modes.first : agent; final current = agent.isEmpty ? _modes.first : agent;
return PopupMenuButton<String>( return _Pill(
tooltip: '模式', icon: Icons.tune,
initialValue: current, label: _label(current),
onSelected: onAgent, onTap: () => _open(context, current),
itemBuilder: (_) { );
}
Future<void> _open(BuildContext context, String current) async {
final known = [ final known = [
for (final a in app.agentList) for (final a in app.agentList)
if (a.mode == 'primary' && !a.hidden) a, if (a.mode == 'primary' && !a.hidden) a,
]; ];
final ids = { final ids = <String>{..._modes, for (final a in known) a.id};
..._modes, final names = {for (final a in known) a.id: a.name};
for (final a in known) a.id, final scheme = Theme.of(context).colorScheme;
}; final picked = await showModalBottomSheet<String>(
return [ context: context,
showDragHandle: true,
builder: (sheet) => SafeArea(
top: false,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Padding(
padding: EdgeInsets.fromLTRB(20, 4, 20, 8),
child: Text('模式',
style: TextStyle(fontSize: 16, fontWeight: FontWeight.w700)),
),
for (final id in ids) for (final id in ids)
PopupMenuItem( ListTile(
value: id, leading: Icon(
child: Text(_label(id), id == 'plan' ? Icons.map_outlined : Icons.construction_outlined,
color: id == current ? scheme.primary : null,
),
title: Text(
names[id]?.isNotEmpty == true ? names[id]! : _label(id),
style: TextStyle( style: TextStyle(
fontWeight: fontWeight: id == current ? FontWeight.w700 : FontWeight.w400,
id == current ? FontWeight.w700 : FontWeight.w400)), ),
),
subtitle: Text(id == 'plan' ? '先规划,不改动文件' : '直接构建',
style: const TextStyle(fontSize: 12)),
trailing: id == current
? Icon(Icons.check, size: 20, color: scheme.primary)
: null,
onTap: () => Navigator.pop(sheet, id),
),
const SizedBox(height: 8),
],
), ),
];
},
child: _Pill(
icon: Icons.tune,
label: _label(current),
onTap: null,
), ),
); );
if (picked != null && picked != current) onAgent(picked);
} }
static String _label(String id) => static String _label(String id) =>
+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.15+315 version: 0.3.16+316
environment: environment:
sdk: ^3.14.0 sdk: ^3.14.0
+60
View File
@@ -0,0 +1,60 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:openchamber/widgets/composer_box.dart';
void main() {
testWidgets('the composer opens on focus and folds when the IME closes',
(tester) async {
final controller = TextEditingController();
final focus = FocusNode();
final keyboard = ValueNotifier<double>(0);
addTearDown(controller.dispose);
addTearDown(focus.dispose);
addTearDown(keyboard.dispose);
// A stand-in for the second row's contents: it only exists while open.
const model = Text('MODEL');
// The page owns the keyboard inset (a Scaffold removes it from the body),
// so the test feeds it in as the screens do.
await tester.pumpWidget(MaterialApp(
home: ValueListenableBuilder<double>(
valueListenable: keyboard,
builder: (context, inset, _) => Scaffold(
body: ComposerBox(
controller: controller,
focusNode: focus,
hint: 'hi',
keyboardInset: inset,
leading: const Icon(Icons.attach_file),
model: model,
trailing: const Icon(Icons.send),
),
),
),
));
// Unfocused: one line, no model pill.
expect(find.text('MODEL'), findsNothing);
// Focus: the composer opens into two rows.
focus.requestFocus();
await tester.pumpAndSettle();
expect(find.text('MODEL'), findsOneWidget);
// The soft keyboard rises, then the back gesture closes it while the
// field keeps focus: the composer folds back to one line.
keyboard.value = 300;
await tester.pumpAndSettle();
expect(find.text('MODEL'), findsOneWidget);
keyboard.value = 0;
await tester.pumpAndSettle();
expect(find.text('MODEL'), findsNothing);
expect(focus.hasFocus, isTrue);
// Typing again brings the keyboard back: the composer opens.
keyboard.value = 300;
await tester.pumpAndSettle();
expect(find.text('MODEL'), findsOneWidget);
});
}
+47
View File
@@ -0,0 +1,47 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:openchamber/api/models.dart';
void main() {
test('an inbox list item parses its text, delivery and files', () {
final item = InboxItem.fromJson({
'id': 'msg_1',
'sessionID': 'ses_1',
'time': {'created': 123},
'type': 'user',
'delivery': 'queue',
'payload': {
'text': 'hello',
'files': [
{'name': 'a.png', 'mime': 'image/png', 'data': 'AAAA'},
],
},
});
expect(item.id, 'msg_1');
expect(item.text, 'hello');
expect(item.delivery, 'queue');
expect(item.created, 123);
expect(item.files.single.name, 'a.png');
});
test('an enqueued event carries the id beside the item', () {
final item = InboxItem.fromEvent(
'msg_2',
{
'type': 'user',
'delivery': 'steer',
'payload': {'text': 'steer me'},
},
456,
);
expect(item.id, 'msg_2');
expect(item.text, 'steer me');
expect(item.delivery, 'steer');
expect(item.created, 456);
});
test('withDelivery keeps the rest', () {
final item = const InboxItem(id: 'm', text: 't', delivery: 'queue');
expect(item.withDelivery('steer').delivery, 'steer');
expect(item.withDelivery('steer').text, 't');
});
}