feat: fold subagent trees and open them from Agent Task rows

Subagent sessions now render as a collapsed tree in the sidebar: parents with
workers get an expand/collapse chevron, expanded child rows sit behind a guide
line, and the parent keeps its worker count. The parent of the open subagent
expands once so its child is visible.

Subagent tool rows in the parent chat (subagent or task) are labeled 子代理,
show the description and open the child session on tap; a child outside the
loaded page is fetched by id first.

Subagent chats are read-only by default with the first-party notice;
allowPromptingSubagentSessions permits ordinary subagents, while a Lead's
operator-child worker stays read-only until takeover.

0.4.10 (410).
This commit is contained in:
blumia committed 2026-11-23 21:15:18 +08:00
1 parent cebf09048e
commit 9cbd97d532
10 files changed
+271 -23

No files matched your search

+13
View File
@@ -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`) ## 0.4.9 浏览子代理会话(分支 `flutter`)
| 项 | 结果 | | 项 | 结果 |
+4 -3
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.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 SOCKS5/socks5h proxy, self-signed certificates and pinning, or a pairing link
over the OpenChamber private relay with end-to-end encryption; the pairing 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 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 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; grouped by project with date captions, pins, archive and swipe actions;
subagent sessions nest under the session that started them and open like any subagent sessions nest under the session that started them (collapsed until
other chat; the 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 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 聊天 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 OpenChamber (including an uploaded/auto icon image), and the chat group has a
+6
View File
@@ -115,6 +115,12 @@ class Client {
next: cursorMap?['next'] as String?, previous: cursorMap?['previous'] as String?); next: cursorMap?['next'] as String?, previous: cursorMap?['previous'] as String?);
} }
Future<Session> 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<String, dynamic>);
}
Future<Set<String>> activeSessions() async { Future<Set<String>> activeSessions() async {
final r = await _json('GET', '/api/session/active'); final r = await _json('GET', '/api/session/active');
final data = r['data'] as Map<String, dynamic>? ?? {}; final data = r['data'] as Map<String, dynamic>? ?? {};
+104 -11
View File
@@ -135,6 +135,44 @@ class _ChatScreenState extends State<ChatScreen> {
super.dispose(); 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. /// The session that started this one, when it is a subagent.
Session? get _parentSession { Session? get _parentSession {
final parentID = widget.session.parentID; final parentID = widget.session.parentID;
@@ -216,7 +254,10 @@ class _ChatScreenState extends State<ChatScreen> {
_permissions(), _permissions(),
_forms(), _forms(),
if (chat.running) _activityStrip(), if (chat.running) _activityStrip(),
_composer(widget.keyboardInset), if (_promptReadOnly)
_readOnlyBanner(theme)
else
_composer(widget.keyboardInset),
], ],
), ),
); );
@@ -812,6 +853,7 @@ class _ChatScreenState extends State<ChatScreen> {
final refs = reasoning || image != null final refs = reasoning || image != null
? const <_ImageRef>[] ? const <_ImageRef>[]
: toolImages(p, chat.dir); : toolImages(p, chat.dir);
final subagentId = _subagentSessionId(p);
return Container( return Container(
margin: const EdgeInsets.only(left: 22), margin: const EdgeInsets.only(left: 22),
decoration: BoxDecoration( decoration: BoxDecoration(
@@ -821,14 +863,19 @@ class _ChatScreenState extends State<ChatScreen> {
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
InkWell( InkWell(
onTap: image != null onTap: subagentId != null
? () => _openPreview(_ImageRef(image, summary.split('/').last)) ? () => _openSubagent(subagentId)
: () { : image != null
setState(() { ? () =>
open ? chat.expanded.remove(key) : chat.expanded.add(key); _openPreview(_ImageRef(image, summary.split('/').last))
}); : () {
if (!open && !reasoning) chat.ensureToolLoaded(id); setState(() {
}, open
? chat.expanded.remove(key)
: chat.expanded.add(key);
});
if (!open && !reasoning) chat.ensureToolLoaded(id);
},
child: Padding( child: Padding(
padding: const EdgeInsets.fromLTRB(10, 3, 10, 3), padding: const EdgeInsets.fromLTRB(10, 3, 10, 3),
child: Row( child: Row(
@@ -874,7 +921,10 @@ class _ChatScreenState extends State<ChatScreen> {
: theme.hintColor)), : 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, Icon(Icons.open_in_full,
size: 14, color: theme.colorScheme.primary) size: 14, color: theme.colorScheme.primary)
else else
@@ -919,6 +969,45 @@ class _ChatScreenState extends State<ChatScreen> {
'png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'avif', '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 = <String>[
for (final part in p.state?.content ?? const <ContentPart>[]) 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<void> _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. /// The file a read/write/edit step points at, when it is an image.
String? _imageArg(ContentPart p) { String? _imageArg(ContentPart p) {
if (p.type != 'tool') return null; if (p.type != 'tool') return null;
@@ -954,6 +1043,7 @@ class _ChatScreenState extends State<ChatScreen> {
case 'web_fetch': case 'web_fetch':
return 'url'; return 'url';
case 'task': case 'task':
case 'subagent':
return 'description'; return 'description';
case 'skill': case 'skill':
return 'id'; return 'id';
@@ -1064,6 +1154,7 @@ class _ChatScreenState extends State<ChatScreen> {
case 'todowrite': case 'todowrite':
return Icons.checklist_rtl; return Icons.checklist_rtl;
case 'task': case 'task':
case 'subagent':
return Icons.smart_toy_outlined; return Icons.smart_toy_outlined;
case 'skill': case 'skill':
return Icons.extension_outlined; return Icons.extension_outlined;
@@ -1100,7 +1191,8 @@ class _ChatScreenState extends State<ChatScreen> {
case 'todowrite': case 'todowrite':
return '任务'; return '任务';
case 'task': case 'task':
return '子任务'; case 'subagent':
return '子代理';
case 'skill': case 'skill':
return '技能'; return '技能';
default: default:
@@ -1131,6 +1223,7 @@ class _ChatScreenState extends State<ChatScreen> {
case 'web_fetch': case 'web_fetch':
return one(input['url']); return one(input['url']);
case 'task': case 'task':
case 'subagent':
return one(input['description'] ?? input['prompt']); return one(input['description'] ?? input['prompt']);
case 'skill': case 'skill':
return one(input['id'] ?? input['name']); return one(input['id'] ?? input['name']);
+60 -6
View File
@@ -32,6 +32,11 @@ class _SessionListPaneState extends State<SessionListPane> {
final Set<String> _collapsed = {}; final Set<String> _collapsed = {};
bool _showArchived = false; 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<String> _expandedChildren = {};
String? _activeChildParent;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
@@ -63,6 +68,7 @@ class _SessionListPaneState extends State<SessionListPane> {
return ListenableBuilder( return ListenableBuilder(
listenable: _app, listenable: _app,
builder: (context, _) { builder: (context, _) {
_syncActiveParent();
final scheme = Theme.of(context).colorScheme; final scheme = Theme.of(context).colorScheme;
return SafeArea( return SafeArea(
child: Column( child: Column(
@@ -499,11 +505,33 @@ class _SessionListPaneState extends State<SessionListPane> {
]..sort((a, b) => a.created.compareTo(b.created)); ]..sort((a, b) => a.created.compareTo(b.created));
} }
List<Widget> _rowsWithChildren(Session session, {bool archived = false}) => [ List<Widget> _rowsWithChildren(Session session, {bool archived = false}) {
_row(session, archived: archived), final rows = <Widget>[_row(session, archived: archived)];
for (final child in _childrenOf(session, archived: archived)) if (!_expandedChildren.contains(session.id)) return rows;
_row(child, archived: archived, child: true), 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, Widget _row(Session session,
{bool archived = false, bool child = false}) { {bool archived = false, bool child = false}) {
@@ -512,6 +540,8 @@ class _SessionListPaneState extends State<SessionListPane> {
final running = _isActive(session); final running = _isActive(session);
final selected = final selected =
!_app.draftOpen && _app.chat?.session.id == session.id; !_app.draftOpen && _app.chat?.session.id == session.id;
final children = child ? const <Session>[] : _childrenOf(session, archived: archived);
final expanded = _expandedChildren.contains(session.id);
return Slidable( return Slidable(
key: ValueKey('${archived ? 'a' : 's'}-${session.id}'), key: ValueKey('${archived ? 'a' : 's'}-${session.id}'),
endActionPane: ActionPane( endActionPane: ActionPane(
@@ -551,7 +581,31 @@ class _SessionListPaneState extends State<SessionListPane> {
leading: child leading: child
? Icon(Icons.smart_toy_outlined, ? Icon(Icons.smart_toy_outlined,
size: 16, color: scheme.onSurfaceVariant) 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( title: Text(
session.title.isEmpty ? '(无标题会话)' : session.title, session.title.isEmpty ? '(无标题会话)' : session.title,
maxLines: 1, maxLines: 1,
+45
View File
@@ -103,6 +103,11 @@ class AppState extends ChangeNotifier {
/// with the web UI; 'queue' is the first-party default. /// with the web UI; 'queue' is the first-party default.
String followUpBehavior = 'queue'; 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 /// Projects the server knows, for the new-session picker and the sidebar's
/// group headers. /// group headers.
List<ProjectInfo> projects = []; List<ProjectInfo> projects = [];
@@ -171,6 +176,8 @@ class AppState extends ChangeNotifier {
final settings = await cl.settings(); final settings = await cl.settings();
if (client != cl) return; if (client != cl) return;
followUpBehavior = normalizeFollowUp(settings['followUpBehavior']); followUpBehavior = normalizeFollowUp(settings['followUpBehavior']);
allowPromptingSubagentSessions =
settings['allowPromptingSubagentSessions'] == true;
notifyListeners(); notifyListeners();
} catch (_) {} } catch (_) {}
} }
@@ -469,6 +476,7 @@ class AppState extends ChangeNotifier {
projects = []; projects = [];
chatsRoot = null; chatsRoot = null;
chatRoots = []; chatRoots = [];
allowPromptingSubagentSessions = false;
_childrenLoaded.clear(); _childrenLoaded.clear();
_childrenLoading.clear(); _childrenLoading.clear();
_projectIcons.clear(); _projectIcons.clear();
@@ -689,6 +697,43 @@ class AppState extends ChangeNotifier {
/// chats root can be relocated away from the home config directory, so it /// 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 /// comes from `/api/fs/home`; before that answer the default layout is still
/// recognised. /// 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<bool> 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) { bool isChatDirectory(String directory) {
if (directory.isEmpty) return false; if (directory.isEmpty) return false;
if (directory == chatTarget) return true; if (directory == chatTarget) return true;
+1 -1
View File
@@ -1,2 +1,2 @@
/// The app version sent to the server in pairing and relay handshakes. /// The app version sent to the server in pairing and relay handshakes.
const appVersion = '0.4.9'; const appVersion = '0.4.10';
+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.4.9+409 version: 0.4.10+410
environment: environment:
sdk: ^3.14.0 sdk: ^3.14.0
+7 -1
View File
@@ -74,9 +74,15 @@ void main() {
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(find.text('子代理输出 hello'), findsOneWidget); 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.text('输出 hello'), findsOneWidget);
expect(find.byIcon(Icons.smart_toy_outlined), findsOneWidget); expect(find.byIcon(Icons.smart_toy_outlined), findsOneWidget);
expect(find.textContaining('1 个子代理'), findsOneWidget);
await tester.tap(find.text('输出 hello')); await tester.tap(find.text('输出 hello'));
await tester.pump(); await tester.pump();
+30
View File
@@ -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);
});
}