From 1aa84a53e5d94db19d12e56d8f4bd80cca0df241 Mon Sep 17 00:00:00 2001 From: Wang Zichong Date: Sat, 21 Nov 2026 18:32:57 +0800 Subject: [PATCH] feat: queue a message for the running turn, and fold the composer when the IME closes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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). --- PLAN.md | 10 ++ README.md | 11 +- lib/api/client.dart | 36 +++++- lib/api/models.dart | 62 +++++++++++ lib/screens/chat_screen.dart | 163 +++++++++++++++++++++++++-- lib/screens/home_screen.dart | 4 + lib/screens/new_session_screen.dart | 9 +- lib/state.dart | 165 +++++++++++++++++++++++++++- lib/widgets/composer_box.dart | 57 +++++++++- lib/widgets/model_controls.dart | 78 ++++++++----- pubspec.yaml | 2 +- test/composer_box_test.dart | 60 ++++++++++ test/inbox_item_test.dart | 47 ++++++++ 13 files changed, 655 insertions(+), 49 deletions(-) create mode 100644 test/composer_box_test.dart create mode 100644 test/inbox_item_test.dart diff --git a/PLAN.md b/PLAN.md index e27a49b..0b71b27 100644 --- a/PLAN.md +++ b/PLAN.md @@ -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`) | 项 | 结果 | diff --git a/README.md b/README.md index b328482..af66012 100644 --- a/README.md +++ b/README.md @@ -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 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 events, chat with streaming Markdown and full history paging, tool steps 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 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 -composer folds to one line when unfocused and opens into two rows on focus (as -in dsh-Go): the model and its thinking level form one pill, the Build/Plan mode -a separate chip. The picker groups providers, favourites, recents and context size. A +composer folds to one line when unfocused (or when the keyboard is dismissed) +and opens into two rows on focus, as in dsh-Go: the model and its thinking level +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, desktop) shows it beside the chat. Android 7.0 (API 24)+, plus a Linux desktop target used for local testing. diff --git a/lib/api/client.dart b/lib/api/client.dart index aecc156..15ee6b5 100644 --- a/lib/api/client.dart +++ b/lib/api/client.dart @@ -181,22 +181,54 @@ class Client { body: {'decision': decision, if (message.isNotEmpty) 'message': message}); } - Future 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 prompt(String sessionId, {String text = '', String? messageId, String? directory, + String? delivery, List>? files, List? 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: { if (text.isNotEmpty) 'text': text, if (messageId != null) 'id': messageId, + if (delivery != null) 'delivery': delivery, if (files != null && files.isNotEmpty) 'files': files, if (skillIds != null && skillIds.isNotEmpty) 'skills': [ 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> 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 && e['type'] == 'user') + InboxItem.fromJson(e), + ]; + } + + /// Takes a waiting prompt out of the inbox. + Future 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 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 diff --git a/lib/api/models.dart b/lib/api/models.dart index 4a78fa9..59fef38 100644 --- a/lib/api/models.dart +++ b/lib/api/models.dart @@ -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 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 j) { + final time = j['time'] as Map? ?? {}; + final payload = j['payload'] as Map? ?? {}; + 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)) + .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 j, int created) { + final payload = j['payload'] as Map? ?? {}; + 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)) + .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. class FormOption { final String value; diff --git a/lib/screens/chat_screen.dart b/lib/screens/chat_screen.dart index f6f8cac..3ae3c4a 100644 --- a/lib/screens/chat_screen.dart +++ b/lib/screens/chat_screen.dart @@ -25,10 +25,15 @@ class ChatScreen extends StatefulWidget { /// Opens the session drawer. Null where the list is always on screen (a /// wide layout), so no menu button is shown there. 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({ super.key, required this.app, required this.session, + this.keyboardInset = 0, this.onOpenSessions, }); @@ -143,7 +148,7 @@ class _ChatScreenState extends State { Expanded(child: _messageList()), _permissions(), _forms(), - _composer(), + _composer(widget.keyboardInset), ], ), ); @@ -239,6 +244,11 @@ class _ChatScreenState extends State { 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; } @@ -358,6 +368,8 @@ class _ChatScreenState extends State { return _userRow(r.msgId); case 'useractions': return _userActions(r.msgId); + case 'pending': + return _pendingBubble(r.msgId); case 'thinking': return const Padding( padding: EdgeInsets.symmetric(horizontal: 16, vertical: 6), @@ -397,6 +409,87 @@ class _ChatScreenState extends State { 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) { final m = chat.byId[id]!; final theme = Theme.of(context); @@ -1332,10 +1425,12 @@ class _ChatScreenState extends State { onPick: _pickSlash, ); - Widget _composer() { + Widget _composer(double keyboardInset) { final usage = chat.usageReading(); final scheme = Theme.of(context).colorScheme; 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 slashRows = slash ?? const []; Widget body = Padding( @@ -1356,6 +1451,7 @@ class _ChatScreenState extends State { focusNode: _inputFocus, hint: chat.running ? '生成中,仍可输入…' : '发消息…', maxLines: 5, + keyboardInset: keyboardInset, // While the palette is up, the keyboard's action key picks the // highlighted row instead of writing a newline. textInputAction: @@ -1427,14 +1523,15 @@ class _ChatScreenState extends State { ), ) : 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( - icon: chat.running - ? Icons.stop_rounded - : Icons.arrow_upward_rounded, - label: chat.running ? '停止' : '发送', + icon: showStop ? Icons.stop_rounded : Icons.arrow_upward_rounded, + label: showStop ? '停止' : '发送', filled: true, - enabled: chat.running || canSend, - onTap: chat.running ? chat.stop : _send, + enabled: showStop || canSend, + onTap: showStop ? chat.stop : _send, + onLongPress: showStop ? null : _sendOptions, ), ), ], @@ -1470,6 +1567,7 @@ class _ChatScreenState extends State { required IconData icon, required String label, required VoidCallback onTap, + VoidCallback? onLongPress, bool filled = false, bool enabled = true, bool busy = false, @@ -1492,6 +1590,7 @@ class _ChatScreenState extends State { child: InkWell( customBorder: const CircleBorder(), onTap: on ? onTap : null, + onLongPress: on ? onLongPress : null, child: SizedBox( width: 36, height: 36, @@ -1516,9 +1615,53 @@ class _ChatScreenState extends State { onRemove: (i) => setState(() => _attachments.removeAt(i)), ); - Future _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 _sendOptions() async { + if (!chat.running) return _send(); final text = _draftCtrl.text.trim(); if (text.isEmpty && _attachments.isEmpty) return; + final picked = await showModalBottomSheet( + 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 _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. final files = >[]; final images = []; @@ -1528,7 +1671,7 @@ class _ChatScreenState extends State { 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) { // The prompt failed: keep the text for a retry. _draftCtrl.text = chat.draft; diff --git a/lib/screens/home_screen.dart b/lib/screens/home_screen.dart index d09fdbc..dbe2dfa 100644 --- a/lib/screens/home_screen.dart +++ b/lib/screens/home_screen.dart @@ -52,6 +52,8 @@ class _HomeScreenState extends State { @override 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( listenable: widget.app, builder: (context, _) { @@ -65,6 +67,7 @@ class _HomeScreenState extends State { ? NewSessionScreen( key: const ValueKey('draft'), app: app, + keyboardInset: keyboardInset, onOpenSessions: wide ? null : () => _scaffold.currentState?.openDrawer(), @@ -75,6 +78,7 @@ class _HomeScreenState extends State { key: ValueKey(chat.session.id), app: app, session: chat.session, + keyboardInset: keyboardInset, onOpenSessions: wide ? null : () => _scaffold.currentState?.openDrawer(), diff --git a/lib/screens/new_session_screen.dart b/lib/screens/new_session_screen.dart index 7185117..873af08 100644 --- a/lib/screens/new_session_screen.dart +++ b/lib/screens/new_session_screen.dart @@ -18,10 +18,14 @@ class NewSessionScreen extends StatefulWidget { /// Opens the session drawer; null where the list is always on screen. final VoidCallback? onOpenSessions; + /// The soft keyboard's height, from above the shell's Scaffold. + final double keyboardInset; + const NewSessionScreen({ super.key, required this.app, this.onOpenSessions, + this.keyboardInset = 0, }); @override @@ -255,7 +259,7 @@ class _NewSessionScreenState extends State { items: _attachments, onRemove: _removeAttachment, ), - _composer(theme), + _composer(theme, widget.keyboardInset), ], ), ), @@ -296,7 +300,7 @@ class _NewSessionScreenState extends State { ); } - Widget _composer(ThemeData theme) { + Widget _composer(ThemeData theme, double keyboardInset) { final scheme = theme.colorScheme; final sending = widget.app.sendingDraft; final slash = _slashMatches(); @@ -306,6 +310,7 @@ class _NewSessionScreenState extends State { focusNode: _inputFocus, hint: '规划、构建或提问', maxLines: 5, + keyboardInset: keyboardInset, textInputAction: slash != null ? TextInputAction.send : TextInputAction.newline, onSubmitted: slash == null || slashRows.isEmpty diff --git a/lib/state.dart b/lib/state.dart index 670cb88..0816d0e 100644 --- a/lib/state.dart +++ b/lib/state.dart @@ -26,6 +26,10 @@ const _eventTypes = [ 'session.execution.succeeded', 'session.execution.failed', 'session.execution.interrupted', + 'session.inbox.enqueued', + 'session.inbox.delivered', + 'session.inbox.cancelled', + 'session.inbox.delivery.changed', 'session.step.started', 'session.step.ended', 'session.step.failed', @@ -689,7 +693,10 @@ class AppState extends ChangeNotifier { if (client == null) return; _startStream(); await refreshSessions(); - if (chat != null) await chat!.reloadTail(); + if (chat != null) { + await chat!.reloadTail(); + await chat!.reloadInbox(); + } for (final terminal in terminals.values) { await terminal.reconnectIfNeeded(); } @@ -920,6 +927,10 @@ class ChatState extends ChangeNotifier { /// The agent's pending questions (native forms), oldest first. List forms = []; + /// Prompts waiting in the server's inbox (queued, or steering the running + /// turn), oldest first. They enter the transcript only when delivered. + List inbox = []; + /// `/` palette contents, loaded once per open chat. List slashItems = []; bool slashLoading = false; @@ -951,6 +962,7 @@ class ChatState extends ChangeNotifier { notifyListeners(); await reloadTail(); await reloadForms(); + await reloadInbox(); } catch (e) { loading = false; error = e.toString(); @@ -1039,6 +1051,54 @@ class ChatState extends ChangeNotifier { } catch (_) {} } + /// Fetches the prompts waiting in the inbox, which may have been queued by + /// another client while this one was closed. + Future 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 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 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 replyForm(FormInfo form, Map answer) async { final cl = app.client; if (cl == null) return; @@ -1129,7 +1189,13 @@ class ChatState extends ChangeNotifier { byId = {for (final m in msgs) m.id: m}; } - Future send({String? text, List>? 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 send({String? text, + List>? files, + String? delivery}) async { final t = (text ?? draft).trim(); if (t.isEmpty && (files == null || files.isEmpty)) return null; if (t.startsWith('/')) { @@ -1179,6 +1245,10 @@ class ChatState extends ChangeNotifier { return null; } } + // A skill can be queued like any prompt. + if (delivery != null) { + return _sendToInbox(t, files, delivery, skillIds: [item.id]); + } final id = _newMsgId(); msgs.add(Message( id: id, @@ -1208,6 +1278,9 @@ class ChatState extends ChangeNotifier { } } } + if (delivery != null) { + return _sendToInbox(t, files, delivery); + } final id = _newMsgId(); draft = ''; 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 _sendToInbox(String text, + List>? files, String delivery, + {List? 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() => 'msg_${DateTime.now().microsecondsSinceEpoch.toRadixString(36)}'; @@ -1481,6 +1609,39 @@ class ChatState extends ChangeNotifier { final agent = data['agent']; if (agent is String && agent.isNotEmpty) selectedAgent = agent; break; + case 'session.inbox.enqueued': + final iid = data['inboxID'] as String?; + final raw = data['item']; + if (iid != null && raw is Map && 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(); } diff --git a/lib/widgets/composer_box.dart b/lib/widgets/composer_box.dart index 7cf10de..1c380a1 100644 --- a/lib/widgets/composer_box.dart +++ b/lib/widgets/composer_box.dart @@ -9,6 +9,10 @@ class ComposerBox extends StatefulWidget { final FocusNode focusNode; final String hint; 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? onChanged; final ValueChanged? onSubmitted; final TextInputAction textInputAction; @@ -40,6 +44,7 @@ class ComposerBox extends StatefulWidget { this.mode, this.accessory, this.maxLines = 5, + this.keyboardInset = 0, this.onChanged, this.onSubmitted, this.textInputAction = TextInputAction.newline, @@ -55,6 +60,12 @@ class _ComposerBoxState extends State { final GlobalKey _fieldKey = GlobalKey(); 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 void initState() { super.initState(); @@ -68,8 +79,52 @@ class _ComposerBoxState extends State { 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() { - 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; setState(() => _open = open); } diff --git a/lib/widgets/model_controls.dart b/lib/widgets/model_controls.dart index dce989b..c06927c 100644 --- a/lib/widgets/model_controls.dart +++ b/lib/widgets/model_controls.dart @@ -63,36 +63,60 @@ class ModeChip extends StatelessWidget { @override Widget build(BuildContext context) { final current = agent.isEmpty ? _modes.first : agent; - return PopupMenuButton( - tooltip: '模式', - initialValue: current, - onSelected: onAgent, - itemBuilder: (_) { - final known = [ - for (final a in app.agentList) - if (a.mode == 'primary' && !a.hidden) a, - ]; - final ids = { - ..._modes, - for (final a in known) a.id, - }; - return [ - for (final id in ids) - PopupMenuItem( - value: id, - child: Text(_label(id), - style: TextStyle( - fontWeight: - id == current ? FontWeight.w700 : FontWeight.w400)), + return _Pill( + icon: Icons.tune, + label: _label(current), + onTap: () => _open(context, current), + ); + } + + Future _open(BuildContext context, String current) async { + final known = [ + for (final a in app.agentList) + if (a.mode == 'primary' && !a.hidden) a, + ]; + final ids = {..._modes, for (final a in known) a.id}; + final names = {for (final a in known) a.id: a.name}; + final scheme = Theme.of(context).colorScheme; + final picked = await showModalBottomSheet( + 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)), ), - ]; - }, - child: _Pill( - icon: Icons.tune, - label: _label(current), - onTap: null, + for (final id in ids) + ListTile( + leading: Icon( + 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( + fontWeight: 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), + ], + ), ), ); + if (picked != null && picked != current) onAgent(picked); } static String _label(String id) => diff --git a/pubspec.yaml b/pubspec.yaml index edd8109..3ae38c5 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -2,7 +2,7 @@ name: openchamber description: "A lightweight OpenChamber client for phones." publish_to: 'none' -version: 0.3.15+315 +version: 0.3.16+316 environment: sdk: ^3.14.0 diff --git a/test/composer_box_test.dart b/test/composer_box_test.dart new file mode 100644 index 0000000..c73089c --- /dev/null +++ b/test/composer_box_test.dart @@ -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(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( + 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); + }); +} diff --git a/test/inbox_item_test.dart b/test/inbox_item_test.dart new file mode 100644 index 0000000..9b6716d --- /dev/null +++ b/test/inbox_item_test.dart @@ -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'); + }); +}