diff --git a/PLAN.md b/PLAN.md index 60a6c94..360fd03 100644 --- a/PLAN.md +++ b/PLAN.md @@ -5,6 +5,19 @@ --- +## 0.4.10 子代理树折叠、Agent Task 行与只读输入(分支 `flutter`) + +| 项 | 结果 | +| --- | --- | +| 侧栏树 | 子代理行默认折叠:有子代理的父行左侧出现展开/收起箭头(tooltip「展开子代理/收起子代理」),展开后子行缩进并带一条竖线;父行副标题仍显示「N 个子代理」。当前打开的子代理会自动展开它的父行,手动收起后不会被重新展开 | +| Agent Task | 父会话的工具步骤识别 `subagent` / `task`(上游 Agent Task),显示子代理图标和描述;点击整行直接打开对应子会话(`state.metadata.sessionID`,旧结果从 `sessionID: ses_…` 文本解析)。会话不在当前分页时用 `GET /api/session/{id}` 取回 | +| 只读输入 | 普通子代理会话默认只读,底部显示「无法向子智能体会话发送提示。」;服务端 `allowPromptingSubagentSessions` 为 true 时才显示输入框。Lead 的 operator-child(`metadata.openchamber.kind = 'operator-child'`)始终只读,显示「此会话由 Lead 管理,接管后才能继续。」,直到后续实现接管 | +| 返回父会话 | 0.4.9 的父会话返回保留 | +| 测试 | `test/subagent_readonly_test.dart`(默认只读、设置放开、operator-child 即使放开也只读);侧栏测试改为默认折叠→点箭头展开→打开子行;51 项全过 | +| 版本 | **0.4.10(code 410)** | + +--- + ## 0.4.9 浏览子代理会话(分支 `flutter`) | 项 | 结果 | diff --git a/README.md b/README.md index 884aba0..62c0a71 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.4.9 — servers (passwordless / password login, HTTP/HTTPS and +Status: 0.4.10 — servers (passwordless / password login, HTTP/HTTPS and SOCKS5/socks5h proxy, self-signed certificates and pinning, or a pairing link over the OpenChamber private relay with end-to-end encryption; the pairing link is pasted or scanned with the camera), session list with search and live @@ -23,8 +23,9 @@ attaches to the shells the server still holds instead of starting new ones. The 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; -subagent sessions nest under the session that started them and open like any -other chat; the +subagent sessions nest under the session that started them (collapsed until +expanded) and open from the sidebar or the parent's Agent Task row; a subagent +chat is read-only unless the server allows prompting subagents; the server's managed chat folders are one 聊天 group, and a new session can target 聊天 instead of a project. Project rows use the icon and colour chosen in OpenChamber (including an uploaded/auto icon image), and the chat group has a diff --git a/lib/api/client.dart b/lib/api/client.dart index 26ad155..8e89497 100644 --- a/lib/api/client.dart +++ b/lib/api/client.dart @@ -115,6 +115,12 @@ class Client { next: cursorMap?['next'] as String?, previous: cursorMap?['previous'] as String?); } + Future getSession(String id, {String? directory}) async { + final r = await _json('GET', '/api/session/${Uri.encodeComponent(id)}', + directory: directory); + return Session.fromJson(r['data'] as Map); + } + Future> activeSessions() async { final r = await _json('GET', '/api/session/active'); final data = r['data'] as Map? ?? {}; diff --git a/lib/screens/chat_screen.dart b/lib/screens/chat_screen.dart index c97b6c5..8c83d54 100644 --- a/lib/screens/chat_screen.dart +++ b/lib/screens/chat_screen.dart @@ -135,6 +135,44 @@ class _ChatScreenState extends State { super.dispose(); } + /// A subagent is view-only unless the server allows prompting subagents; + /// a lead's operator worker stays view-only until it is taken over. + bool get _promptReadOnly => + widget.app.promptReadOnlyFor(widget.session); + + Widget _readOnlyBanner(ThemeData theme) { + final scheme = theme.colorScheme; + final openchamber = widget.session.metadata['openchamber']; + final operator = + openchamber is Map && openchamber['kind'] == 'operator-child'; + return Container( + width: double.infinity, + padding: EdgeInsets.fromLTRB( + 16, 12, 16, 12 + widget.keyboardInset), + decoration: BoxDecoration( + color: scheme.surfaceContainerHighest, + border: Border( + top: BorderSide(color: theme.dividerColor, width: 0.5), + ), + ), + child: Row( + children: [ + Icon(Icons.lock_outline, size: 16, color: theme.hintColor), + const SizedBox(width: 8), + Expanded( + child: Text( + operator + ? '此会话由 Lead 管理,接管后才能继续。' + : '无法向子智能体会话发送提示。', + style: TextStyle( + fontSize: 12.5, color: scheme.onSurfaceVariant), + ), + ), + ], + ), + ); + } + /// The session that started this one, when it is a subagent. Session? get _parentSession { final parentID = widget.session.parentID; @@ -216,7 +254,10 @@ class _ChatScreenState extends State { _permissions(), _forms(), if (chat.running) _activityStrip(), - _composer(widget.keyboardInset), + if (_promptReadOnly) + _readOnlyBanner(theme) + else + _composer(widget.keyboardInset), ], ), ); @@ -812,6 +853,7 @@ class _ChatScreenState extends State { final refs = reasoning || image != null ? const <_ImageRef>[] : toolImages(p, chat.dir); + final subagentId = _subagentSessionId(p); return Container( margin: const EdgeInsets.only(left: 22), decoration: BoxDecoration( @@ -821,14 +863,19 @@ class _ChatScreenState extends State { crossAxisAlignment: CrossAxisAlignment.start, children: [ InkWell( - onTap: image != null - ? () => _openPreview(_ImageRef(image, summary.split('/').last)) - : () { - setState(() { - open ? chat.expanded.remove(key) : chat.expanded.add(key); - }); - if (!open && !reasoning) chat.ensureToolLoaded(id); - }, + onTap: subagentId != null + ? () => _openSubagent(subagentId) + : image != null + ? () => + _openPreview(_ImageRef(image, summary.split('/').last)) + : () { + setState(() { + open + ? chat.expanded.remove(key) + : chat.expanded.add(key); + }); + if (!open && !reasoning) chat.ensureToolLoaded(id); + }, child: Padding( padding: const EdgeInsets.fromLTRB(10, 3, 10, 3), child: Row( @@ -874,7 +921,10 @@ class _ChatScreenState extends State { : theme.hintColor)), ), ], - if (image != null) + if (subagentId != null) + Icon(Icons.chevron_right, + size: 18, color: theme.hintColor) + else if (image != null) Icon(Icons.open_in_full, size: 14, color: theme.colorScheme.primary) else @@ -919,6 +969,45 @@ class _ChatScreenState extends State { 'png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'avif', }; + /// The child session a subagent tool call started: the server puts it in the + /// tool metadata, and older results carry `sessionID: ses_…` in the text. + static String? _subagentSessionId(ContentPart p) { + if (p.type != 'tool') return null; + if (p.name != 'subagent' && p.name != 'task') return null; + final meta = p.state?.metadata; + if (meta != null) { + for (final key in const [ + 'sessionID', + 'sessionId', + 'childSessionID', + 'childSessionId', + ]) { + final value = meta[key]; + if (value is String && value.isNotEmpty) return value; + } + } + final pattern = + RegExp(r'(?:sessionID|sessionId)["\s:=]+(ses_[A-Za-z0-9]+)'); + final texts = [ + for (final part in p.state?.content ?? const []) part.text, + if (p.state?.error != null) p.state!.error!, + ]; + for (final text in texts) { + final match = pattern.firstMatch(text); + if (match != null) return match.group(1); + } + return null; + } + + Future _openSubagent(String id) async { + final ok = await widget.app.openSubagent(id); + if (ok || !mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(widget.app.lastError ?? '无法打开子代理会话')), + ); + widget.app.clearLastError(); + } + /// The file a read/write/edit step points at, when it is an image. String? _imageArg(ContentPart p) { if (p.type != 'tool') return null; @@ -954,6 +1043,7 @@ class _ChatScreenState extends State { case 'web_fetch': return 'url'; case 'task': + case 'subagent': return 'description'; case 'skill': return 'id'; @@ -1064,6 +1154,7 @@ class _ChatScreenState extends State { case 'todowrite': return Icons.checklist_rtl; case 'task': + case 'subagent': return Icons.smart_toy_outlined; case 'skill': return Icons.extension_outlined; @@ -1100,7 +1191,8 @@ class _ChatScreenState extends State { case 'todowrite': return '任务'; case 'task': - return '子任务'; + case 'subagent': + return '子代理'; case 'skill': return '技能'; default: @@ -1131,6 +1223,7 @@ class _ChatScreenState extends State { case 'web_fetch': return one(input['url']); case 'task': + case 'subagent': return one(input['description'] ?? input['prompt']); case 'skill': return one(input['id'] ?? input['name']); diff --git a/lib/screens/sessions_screen.dart b/lib/screens/sessions_screen.dart index 571a32b..1392b43 100644 --- a/lib/screens/sessions_screen.dart +++ b/lib/screens/sessions_screen.dart @@ -32,6 +32,11 @@ class _SessionListPaneState extends State { final Set _collapsed = {}; bool _showArchived = false; + /// Parents whose subagents are expanded. Collapsed is the default; the + /// parent of the open child expands once so its child is visible. + final Set _expandedChildren = {}; + String? _activeChildParent; + @override void initState() { super.initState(); @@ -63,6 +68,7 @@ class _SessionListPaneState extends State { return ListenableBuilder( listenable: _app, builder: (context, _) { + _syncActiveParent(); final scheme = Theme.of(context).colorScheme; return SafeArea( child: Column( @@ -499,11 +505,33 @@ class _SessionListPaneState extends State { ]..sort((a, b) => a.created.compareTo(b.created)); } - List _rowsWithChildren(Session session, {bool archived = false}) => [ - _row(session, archived: archived), - for (final child in _childrenOf(session, archived: archived)) - _row(child, archived: archived, child: true), - ]; + List _rowsWithChildren(Session session, {bool archived = false}) { + final rows = [_row(session, archived: archived)]; + if (!_expandedChildren.contains(session.id)) return rows; + final theme = Theme.of(context); + for (final child in _childrenOf(session, archived: archived)) { + rows.add(Container( + margin: const EdgeInsets.only(left: 24), + decoration: BoxDecoration( + border: Border( + left: BorderSide(color: theme.dividerColor, width: 1), + ), + ), + child: _row(child, archived: archived, child: true), + )); + } + return rows; + } + + /// Expands the parent of the open subagent once, so the sidebar shows where + /// the child is. Collapsing it by hand stays collapsed until another child + /// is opened. + void _syncActiveParent() { + final parent = _app.chat?.session.parentID; + if (parent == _activeChildParent) return; + _activeChildParent = parent; + if (parent != null) _expandedChildren.add(parent); + } Widget _row(Session session, {bool archived = false, bool child = false}) { @@ -512,6 +540,8 @@ class _SessionListPaneState extends State { final running = _isActive(session); final selected = !_app.draftOpen && _app.chat?.session.id == session.id; + final children = child ? const [] : _childrenOf(session, archived: archived); + final expanded = _expandedChildren.contains(session.id); return Slidable( key: ValueKey('${archived ? 'a' : 's'}-${session.id}'), endActionPane: ActionPane( @@ -551,7 +581,31 @@ class _SessionListPaneState extends State { leading: child ? Icon(Icons.smart_toy_outlined, size: 16, color: scheme.onSurfaceVariant) - : null, + : children.isEmpty + ? null + : SizedBox( + width: 32, + height: 32, + child: IconButton( + icon: Icon( + expanded + ? Icons.expand_more + : Icons.chevron_right, + size: 18), + tooltip: expanded ? '收起子代理' : '展开子代理', + padding: EdgeInsets.zero, + visualDensity: VisualDensity.compact, + constraints: + const BoxConstraints(minWidth: 32, minHeight: 32), + onPressed: () => setState(() { + if (expanded) { + _expandedChildren.remove(session.id); + } else { + _expandedChildren.add(session.id); + } + }), + ), + ), title: Text( session.title.isEmpty ? '(无标题会话)' : session.title, maxLines: 1, diff --git a/lib/state.dart b/lib/state.dart index 5f0dcb8..1836417 100644 --- a/lib/state.dart +++ b/lib/state.dart @@ -103,6 +103,11 @@ class AppState extends ChangeNotifier { /// with the web UI; 'queue' is the first-party default. String followUpBehavior = 'queue'; + /// Server setting: allow typing into a subagent session. Off by default; + /// lead workers stay read-only until taken over regardless (the first-party + /// `allowPromptingSubagentSessions`). + bool allowPromptingSubagentSessions = false; + /// Projects the server knows, for the new-session picker and the sidebar's /// group headers. List projects = []; @@ -171,6 +176,8 @@ class AppState extends ChangeNotifier { final settings = await cl.settings(); if (client != cl) return; followUpBehavior = normalizeFollowUp(settings['followUpBehavior']); + allowPromptingSubagentSessions = + settings['allowPromptingSubagentSessions'] == true; notifyListeners(); } catch (_) {} } @@ -469,6 +476,7 @@ class AppState extends ChangeNotifier { projects = []; chatsRoot = null; chatRoots = []; + allowPromptingSubagentSessions = false; _childrenLoaded.clear(); _childrenLoading.clear(); _projectIcons.clear(); @@ -689,6 +697,43 @@ class AppState extends ChangeNotifier { /// chats root can be relocated away from the home config directory, so it /// comes from `/api/fs/home`; before that answer the default layout is still /// recognised. + /// A subagent session is read-only unless the server allows prompting + /// subagents. A lead's operator worker is read-only until it is taken over. + bool promptReadOnlyFor(Session session) { + final openchamber = session.metadata['openchamber']; + if (openchamber is Map && openchamber['kind'] == 'operator-child') { + return true; + } + if (session.isChild) return !allowPromptingSubagentSessions; + return false; + } + + /// Opens a subagent by id, fetching its record when the loaded list does not + /// have it (the tool row can name a session older than the current page). + Future openSubagent(String sessionId) async { + if (sessionId.isEmpty) return false; + for (final session in sessions) { + if (session.id == sessionId) { + await openChat(session); + return true; + } + } + final cl = client; + if (cl == null) return false; + try { + final session = + await cl.getSession(sessionId, directory: chat?.session.directory); + if (client != cl) return false; + if (!sessions.any((s) => s.id == session.id)) sessions.add(session); + await openChat(session); + return true; + } catch (e) { + _lastError = '无法打开子代理会话:$e'; + notifyListeners(); + return false; + } + } + bool isChatDirectory(String directory) { if (directory.isEmpty) return false; if (directory == chatTarget) return true; diff --git a/lib/version.dart b/lib/version.dart index aee9758..0a72600 100644 --- a/lib/version.dart +++ b/lib/version.dart @@ -1,2 +1,2 @@ /// The app version sent to the server in pairing and relay handshakes. -const appVersion = '0.4.9'; +const appVersion = '0.4.10'; diff --git a/pubspec.yaml b/pubspec.yaml index 4776231..119647b 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.4.9+409 +version: 0.4.10+410 environment: sdk: ^3.14.0 diff --git a/test/sidebar_rows_test.dart b/test/sidebar_rows_test.dart index 55331d2..ed9e2e8 100644 --- a/test/sidebar_rows_test.dart +++ b/test/sidebar_rows_test.dart @@ -74,9 +74,15 @@ void main() { await tester.pumpAndSettle(); expect(find.text('子代理输出 hello'), findsOneWidget); + // Tree rows start collapsed; the parent alone shows the count. + expect(find.text('输出 hello'), findsNothing); + expect(find.byTooltip('展开子代理'), findsOneWidget); + expect(find.textContaining('1 个子代理'), findsOneWidget); + + await tester.tap(find.byTooltip('展开子代理')); + await tester.pump(); expect(find.text('输出 hello'), findsOneWidget); expect(find.byIcon(Icons.smart_toy_outlined), findsOneWidget); - expect(find.textContaining('1 个子代理'), findsOneWidget); await tester.tap(find.text('输出 hello')); await tester.pump(); diff --git a/test/subagent_readonly_test.dart b/test/subagent_readonly_test.dart new file mode 100644 index 0000000..2da594d --- /dev/null +++ b/test/subagent_readonly_test.dart @@ -0,0 +1,30 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:openchamber/api/models.dart'; +import 'package:openchamber/state.dart'; + +void main() { + test('subagent chats are read-only unless the server allows prompting them', + () { + final app = AppState(); + addTearDown(app.dispose); + final child = Session(id: 'child', title: '输出 hello', parentID: 'parent'); + + expect(app.promptReadOnlyFor(child), isTrue); + app.allowPromptingSubagentSessions = true; + expect(app.promptReadOnlyFor(child), isFalse); + + // A lead's operator worker stays read-only until taken over, whatever the + // subagent setting says. + final worker = Session( + id: 'worker', + title: 'worker', + metadata: { + 'openchamber': {'kind': 'operator-child', 'parentID': 'lead'}, + }, + ); + expect(app.promptReadOnlyFor(worker), isTrue); + + final root = Session(id: 'root', title: 'root'); + expect(app.promptReadOnlyFor(root), isFalse); + }); +}