lithe-cli 0.1.6__tar.gz → 0.1.9__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. {lithe_cli-0.1.6 → lithe_cli-0.1.9}/PKG-INFO +2 -2
  2. {lithe_cli-0.1.6 → lithe_cli-0.1.9}/lithe_cli/__init__.py +1 -1
  3. {lithe_cli-0.1.6 → lithe_cli-0.1.9}/lithe_cli/sessions.py +10 -3
  4. {lithe_cli-0.1.6 → lithe_cli-0.1.9}/lithe_cli/ttui.py +114 -25
  5. {lithe_cli-0.1.6 → lithe_cli-0.1.9}/lithe_cli/ttui_widgets.py +139 -3
  6. {lithe_cli-0.1.6 → lithe_cli-0.1.9}/lithe_cli/tui.py +155 -31
  7. {lithe_cli-0.1.6 → lithe_cli-0.1.9}/lithe_cli.egg-info/PKG-INFO +2 -2
  8. {lithe_cli-0.1.6 → lithe_cli-0.1.9}/lithe_cli.egg-info/requires.txt +1 -1
  9. {lithe_cli-0.1.6 → lithe_cli-0.1.9}/pyproject.toml +1 -1
  10. {lithe_cli-0.1.6 → lithe_cli-0.1.9}/tests/test_cli_sessions.py +20 -0
  11. {lithe_cli-0.1.6 → lithe_cli-0.1.9}/tests/test_cli_subagents.py +54 -9
  12. {lithe_cli-0.1.6 → lithe_cli-0.1.9}/tests/test_ttui.py +142 -0
  13. {lithe_cli-0.1.6 → lithe_cli-0.1.9}/tests/test_tui_v2.py +13 -0
  14. {lithe_cli-0.1.6 → lithe_cli-0.1.9}/LICENSE +0 -0
  15. {lithe_cli-0.1.6 → lithe_cli-0.1.9}/README.md +0 -0
  16. {lithe_cli-0.1.6 → lithe_cli-0.1.9}/lithe_cli/__main__.py +0 -0
  17. {lithe_cli-0.1.6 → lithe_cli-0.1.9}/lithe_cli/agent.py +0 -0
  18. {lithe_cli-0.1.6 → lithe_cli-0.1.9}/lithe_cli/cli_parser.py +0 -0
  19. {lithe_cli-0.1.6 → lithe_cli-0.1.9}/lithe_cli/clipboard.py +0 -0
  20. {lithe_cli-0.1.6 → lithe_cli-0.1.9}/lithe_cli/commands.py +0 -0
  21. {lithe_cli-0.1.6 → lithe_cli-0.1.9}/lithe_cli/config.py +0 -0
  22. {lithe_cli-0.1.6 → lithe_cli-0.1.9}/lithe_cli/main.py +0 -0
  23. {lithe_cli-0.1.6 → lithe_cli-0.1.9}/lithe_cli/profiles.py +0 -0
  24. {lithe_cli-0.1.6 → lithe_cli-0.1.9}/lithe_cli/prompts.py +0 -0
  25. {lithe_cli-0.1.6 → lithe_cli-0.1.9}/lithe_cli/py.typed +0 -0
  26. {lithe_cli-0.1.6 → lithe_cli-0.1.9}/lithe_cli/setup.py +0 -0
  27. {lithe_cli-0.1.6 → lithe_cli-0.1.9}/lithe_cli/ttui_render.py +0 -0
  28. {lithe_cli-0.1.6 → lithe_cli-0.1.9}/lithe_cli/ui.py +0 -0
  29. {lithe_cli-0.1.6 → lithe_cli-0.1.9}/lithe_cli/workbench.py +0 -0
  30. {lithe_cli-0.1.6 → lithe_cli-0.1.9}/lithe_cli.egg-info/SOURCES.txt +0 -0
  31. {lithe_cli-0.1.6 → lithe_cli-0.1.9}/lithe_cli.egg-info/dependency_links.txt +0 -0
  32. {lithe_cli-0.1.6 → lithe_cli-0.1.9}/lithe_cli.egg-info/entry_points.txt +0 -0
  33. {lithe_cli-0.1.6 → lithe_cli-0.1.9}/lithe_cli.egg-info/top_level.txt +0 -0
  34. {lithe_cli-0.1.6 → lithe_cli-0.1.9}/setup.cfg +0 -0
  35. {lithe_cli-0.1.6 → lithe_cli-0.1.9}/tests/test_cli.py +0 -0
  36. {lithe_cli-0.1.6 → lithe_cli-0.1.9}/tests/test_cli_budget_steer.py +0 -0
  37. {lithe_cli-0.1.6 → lithe_cli-0.1.9}/tests/test_cli_clipboard.py +0 -0
  38. {lithe_cli-0.1.6 → lithe_cli-0.1.9}/tests/test_cli_guard.py +0 -0
  39. {lithe_cli-0.1.6 → lithe_cli-0.1.9}/tests/test_profiles.py +0 -0
  40. {lithe_cli-0.1.6 → lithe_cli-0.1.9}/tests/test_workbench.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: lithe-cli
3
- Version: 0.1.6
3
+ Version: 0.1.9
4
4
  Summary: Command-line interface for the lithe agent kernel: chat, one-shot runs, undo, and run inspection.
5
5
  License: MIT License
6
6
 
@@ -39,7 +39,7 @@ Classifier: Typing :: Typed
39
39
  Requires-Python: >=3.10
40
40
  Description-Content-Type: text/markdown
41
41
  License-File: LICENSE
42
- Requires-Dist: lithe>=0.1.4
42
+ Requires-Dist: lithe>=0.1.5
43
43
  Requires-Dist: prompt-toolkit>=3.0.38
44
44
  Requires-Dist: textual>=1.0
45
45
  Provides-Extra: dev
@@ -1,3 +1,3 @@
1
1
  """lithe-cli: the command-line interface for the lithe agent kernel."""
2
2
 
3
- __version__ = "0.1.6"
3
+ __version__ = "0.1.9"
@@ -101,9 +101,16 @@ class SessionManager:
101
101
  conversation_id, self.user_id
102
102
  )
103
103
 
104
- def transcript(self, conversation_id: int, last: int = 200) -> list[dict]:
105
- """Recent messages for display (TUI rebuild), oldest first."""
106
- rows = self.history(conversation_id)
104
+ def transcript(self, conversation_id: int, last: int = 200, *,
105
+ include_subagents: bool = False) -> list[dict]:
106
+ """Recent messages for display (TUI rebuild), oldest first.
107
+
108
+ The default remains the orchestrator-only view used by /copy and
109
+ existing callers. Rich UIs can request instance-tagged worker rows.
110
+ """
111
+ rows = self.store.messages_for_conversation(
112
+ conversation_id, self.user_id, exclude_subagent=not include_subagents
113
+ )
107
114
  return rows[-last:] if last else rows
108
115
 
109
116
  def usage_snapshot(self, conversation_id: int) -> dict:
@@ -29,7 +29,7 @@ from typing import Any
29
29
 
30
30
  from textual.app import App, ComposeResult
31
31
  from textual.binding import Binding
32
- from textual.containers import Horizontal, VerticalScroll
32
+ from textual.containers import Horizontal, Vertical, VerticalScroll
33
33
  from textual.widgets import Input, Static
34
34
 
35
35
  from .clipboard import deliver_clipboard, write_clipboard_file
@@ -37,6 +37,7 @@ from .config import lithe_home
37
37
  from .tui import (
38
38
  COPY_SCOPE_LABELS,
39
39
  COPY_SCOPES,
40
+ SUBAGENT_FEED_PREFIX,
40
41
  TuiState,
41
42
  describe_copy,
42
43
  feed_text,
@@ -45,8 +46,8 @@ from .tui import (
45
46
  from .ui import fmt_duration as fmt_duration # noqa: F401 — legacy re-export
46
47
  from . import ttui_widgets as _widgets
47
48
  from .ttui_widgets import (
48
- ConfirmModal, ConversationPane, HistoryInput, PickerModal, WbEvent,
49
- completion_suggestions, selected_text,
49
+ ConfirmModal, ConversationPane, HistoryInput, PickerModal, SubagentCard,
50
+ WbEvent, completion_suggestions, selected_text,
50
51
  )
51
52
  from .ttui_render import footer_text, header_text, sidebar_markup
52
53
 
@@ -58,7 +59,17 @@ class LitheApp(App):
58
59
  CSS = """
59
60
  #top { height: 1; background: #172033; color: #e2e8f0; }
60
61
  #body { height: 1fr; }
61
- #conv { width: 1fr; border: round #475569; padding: 0 1; }
62
+ #main-column { width: 1fr; height: 1fr; }
63
+ #conv { width: 1fr; height: 1fr; border: round #475569; padding: 0 1; }
64
+ /* Subagent cards live inline in the conversation: a one-line heading
65
+ when collapsed (plus the left rail), search + transcript expanded. */
66
+ .subagent-card { height: auto; margin: 0 0 1 0; padding: 0 1 0 0;
67
+ border-left: round #475569; }
68
+ .subagent-heading { height: 1; width: 1fr; border: none; min-width: 0;
69
+ background: #1b2438; color: #fbbf24;
70
+ text-align: left; content-align: left middle; }
71
+ .subagent-search { height: 3; margin: 0 1 0 1; border: round #334155; }
72
+ .subagent-output { height: auto; margin: 0 1 0 1; color: #cbd5e1; }
62
73
  #side-wrap { width: 44; border: round #475569; padding: 0 1; }
63
74
  #prompt { border: round #475569; }
64
75
  #foot { height: 1; background: #111827; color: #cbd5e1; }
@@ -103,9 +114,10 @@ class LitheApp(App):
103
114
  def compose(self) -> ComposeResult:
104
115
  yield Static("", id="top", markup=False)
105
116
  with Horizontal(id="body"):
106
- with ConversationPane(id="conv"):
107
- yield Static("", id="streaming", classes="assistant",
108
- markup=False)
117
+ with Vertical(id="main-column"):
118
+ with ConversationPane(id="conv"):
119
+ yield Static("", id="streaming", classes="assistant",
120
+ markup=False)
109
121
  with VerticalScroll(id="side-wrap"):
110
122
  yield Static("", id="side", markup=True)
111
123
  yield Static("", id="suggest")
@@ -140,7 +152,9 @@ class LitheApp(App):
140
152
  self.state = self._base_state(self._current_cid())
141
153
  self.states: dict[int, TuiState] = {}
142
154
  if self._current_cid() is not None:
143
- self.states[self._current_cid()] = self.state
155
+ cid = self._current_cid()
156
+ self._load_session_history(self.state, cid)
157
+ self.states[cid] = self.state
144
158
  for cls, text in opening:
145
159
  self.state.say(cls, text)
146
160
  self.wb.subscribe(
@@ -184,6 +198,39 @@ class LitheApp(App):
184
198
  st.max_total_tokens = self.cfg.max_total_tokens
185
199
  return st
186
200
 
201
+ def _load_session_history(self, state: TuiState, cid: int) -> None:
202
+ """Load both the orchestrator feed and subagent cards on first open.
203
+
204
+ The feed is built from the interleaved history in one pass, so each
205
+ subagent's marker row (and with it its card) sits where the
206
+ delegation actually happened, not pinned below the conversation.
207
+ """
208
+ history = self.wb.sessions.transcript(
209
+ cid, last=0, include_subagents=True
210
+ )
211
+ rows = transcript_feed_lines(history)
212
+ state.feed.extend(rows[-200:])
213
+ state.restore_subagents(history)
214
+ usage = self.wb.sessions.usage_snapshot(cid)
215
+ if usage.get("known"):
216
+ state.input_tokens = usage["prompt_tokens"]
217
+ state.output_tokens = usage["completion_tokens"]
218
+ state.cached_tokens = usage["cached_tokens"]
219
+ state.tokens = usage["total_tokens"]
220
+ state.cost = usage["cost"]
221
+
222
+ def action_refresh_session_history(self) -> None:
223
+ """Reload durable transcript for the active session."""
224
+ cid = self._current_cid()
225
+ if cid is None:
226
+ return
227
+ self.state.feed.clear()
228
+ self.state.subagents.clear()
229
+ self._load_session_history(self.state, cid)
230
+ self._shown = 0
231
+ self._clear_conversation()
232
+ self._sync_feed()
233
+
187
234
  def _refresh_meta(self) -> None:
188
235
  st = self.state
189
236
  st.model = self.cfg.model or "(scripted)"
@@ -206,31 +253,36 @@ class LitheApp(App):
206
253
 
207
254
  if cid not in self.states:
208
255
  st = self._base_state(cid)
209
- st.feed.extend(
210
- transcript_feed_lines(self.wb.sessions.transcript(cid))
211
- )
212
- usage = self.wb.sessions.usage_snapshot(cid)
213
- if usage.get("known"):
214
- st.input_tokens = usage["prompt_tokens"]
215
- st.output_tokens = usage["completion_tokens"]
216
- st.cached_tokens = usage["cached_tokens"]
217
- st.tokens = usage["total_tokens"]
218
- st.cost = usage["cost"]
256
+ self._load_session_history(st, cid)
219
257
  self.states[cid] = st
258
+ self.state = st
259
+ self._shown = 0
260
+ self._clear_conversation()
261
+ self._sync_feed()
262
+ else:
263
+ self.state = self.states[cid]
264
+ if cid not in self.wb.busy_ids():
265
+ # Returning to an idle session: rebuild from the persisted
266
+ # store, because a turn that finished while another session
267
+ # was active never fed events into this state (and the live
268
+ # feed keeps transient notices a store rebuild would drop).
269
+ # A busy session keeps its live cache so the running turn
270
+ # keeps rendering.
271
+ self.action_refresh_session_history()
220
272
  # Reload from the conversation's persisted store when returning to it:
221
273
  # a background turn or /undo may have changed its todos meanwhile.
222
274
  self.states[cid].todos = JsonTodoStore(
223
275
  todo_store_path(self.cfg, cid)
224
276
  ).list()
225
- self.state = self.states[cid]
226
- self._shown = 0
277
+ self._refresh_meta()
278
+ self._refresh_chrome()
279
+
280
+ def _clear_conversation(self) -> None:
281
+ """Unmount feed lines and subagent cards, keep the streaming slot."""
227
282
  conv = self.query_one("#conv", ConversationPane)
228
283
  for child in list(conv.children):
229
284
  if child.id != "streaming":
230
285
  child.remove()
231
- self._refresh_meta()
232
- self._sync_feed()
233
- self._refresh_chrome()
234
286
 
235
287
  # -- conversation rendering (pure render-from-state) ----------------------
236
288
 
@@ -245,18 +297,39 @@ class LitheApp(App):
245
297
  while self._shown < len(feed):
246
298
  cls, text = feed[self._shown]
247
299
  self._shown += 1
300
+ if cls.startswith(SUBAGENT_FEED_PREFIX):
301
+ # A subagent card mounts where the delegation began, so it
302
+ # scrolls with the conversation instead of squatting in a
303
+ # fixed region below it. Data refresh rides the pass below.
304
+ instance = cls[len(SUBAGENT_FEED_PREFIX):]
305
+ block = self.state.subagents.get(instance)
306
+ if block is not None:
307
+ card = SubagentCard(instance, block)
308
+ conv.mount(card, before=streaming)
309
+ card.call_after_refresh(card.set_data, block)
310
+ continue
248
311
  # markup=False: model/tool text is data, not Textual markup —
249
312
  # a "[x]" in an answer must render, not parse (and it is what
250
313
  # /copy sends to the clipboard verbatim).
251
314
  conv.mount(Static(text, classes=cls or "dim", markup=False),
252
315
  before=streaming)
316
+ # Trim the oldest mounted rows, but never a card: a long-running
317
+ # subagent's block must not vanish mid-flight just because the
318
+ # orchestrator talked a lot after delegating.
253
319
  non_stream = [c for c in conv.children if c.id != "streaming"]
254
- for stale in non_stream[:max(0, len(non_stream) - _MAX_FEED)]:
255
- stale.remove()
320
+ stale = [c for c in non_stream[:max(0, len(non_stream) - _MAX_FEED)]
321
+ if not isinstance(c, SubagentCard)]
322
+ for old in stale:
323
+ old.remove()
256
324
  if self.state.streaming:
257
325
  streaming.update(self.state.streaming)
258
326
  else:
259
327
  streaming.update("")
328
+ for child in conv.children:
329
+ if isinstance(child, SubagentCard):
330
+ child._block["expanded"] = child._expanded
331
+ child._block["search"] = child._search
332
+ self.call_after_refresh(self._refresh_subagent_lines)
260
333
  if at_bottom:
261
334
  conv.scroll_end(animate=False)
262
335
  # The pane's extent only grows once the newly mounted lines lay
@@ -266,6 +339,18 @@ class LitheApp(App):
266
339
  # "still reading up there" and stops following for good.
267
340
  conv.call_after_refresh(conv.scroll_end, animate=False)
268
341
 
342
+ def _refresh_subagent_lines(self) -> None:
343
+ """Refresh mounted card transcripts after each event, preserving UI."""
344
+ try:
345
+ container = self.query_one("#conv", ConversationPane)
346
+ except Exception:
347
+ return
348
+ for card in container.children:
349
+ if isinstance(card, SubagentCard):
350
+ block = self.state.subagents.get(card.instance)
351
+ if block is not None:
352
+ card.set_data(block)
353
+
269
354
  def _refresh_chrome(self) -> None:
270
355
  self.query_one("#top", Static).update(
271
356
  header_text(self.state, getattr(self, "version", ""))
@@ -295,6 +380,10 @@ class LitheApp(App):
295
380
  return
296
381
  if t == "session_idle":
297
382
  if cid == self._current_cid():
383
+ # No feed rebuild here: the live feed (transient steering
384
+ # notices, elapsed times, subagent cards) is richer than a
385
+ # store reload; _activate rebuilds from the store when the
386
+ # reader returns to the session.
298
387
  self.state.running = False
299
388
  self.state.stop = None
300
389
  self._cancel_asked = False
@@ -4,12 +4,17 @@ from __future__ import annotations
4
4
  from collections.abc import Callable
5
5
  from typing import Any
6
6
 
7
+ from rich.text import Text
7
8
  from textual.app import ComposeResult
8
9
  from textual.binding import Binding
9
10
  from textual.containers import Vertical, VerticalScroll
11
+ from textual.content import Content
12
+ from textual.css.query import NoMatches
10
13
  from textual.message import Message
11
14
  from textual.screen import ModalScreen
12
- from textual.widgets import Input, Label, ListItem, ListView, Static
15
+ from textual.widgets import Button, Input, Label, ListItem, ListView, Static
16
+
17
+ from .ui import display_width, truncate
13
18
 
14
19
  # -- input: completion + persistent history ------------------------------------
15
20
 
@@ -172,6 +177,139 @@ class ConversationPane(VerticalScroll):
172
177
  self.app.open_copy_menu()
173
178
 
174
179
 
180
+ class SubagentCard(Vertical):
181
+ """A collapsible, independently searchable subagent transcript."""
182
+
183
+ def __init__(self, instance: str, block: dict | None = None, **kwargs) -> None:
184
+ safe_id = "subagent-" + "".join(
185
+ c if c.isalnum() or c in "-_" else "-" for c in instance
186
+ )
187
+ super().__init__(id=safe_id, classes="subagent-card", **kwargs)
188
+ self.instance = instance
189
+ self._expanded = bool((block or {}).get("expanded"))
190
+ self._search = str((block or {}).get("search") or "")
191
+ self._lines: list[tuple[str, str]] = []
192
+ self._block: dict = {}
193
+ self._heading = ""
194
+ if block:
195
+ self.update_data(block)
196
+
197
+ def compose(self) -> ComposeResult:
198
+ yield Button("", classes="subagent-heading", variant="default")
199
+ yield Input(placeholder="搜索此子任务…", classes="subagent-search")
200
+ yield Static("", classes="subagent-output", markup=False)
201
+
202
+ def update_data(self, block: dict) -> None:
203
+ same_block = self._block is block
204
+ if self.is_mounted and same_block:
205
+ block["expanded"] = self._expanded
206
+ block["search"] = self._search
207
+ self._block = block
208
+ self._lines = list(block.get("lines") or [])
209
+ if not (self.is_mounted and same_block):
210
+ self._expanded = bool(block.get("expanded"))
211
+ self._search = str(block.get("search") or "")
212
+
213
+ def set_data(self, block: dict) -> None:
214
+ self.update_data(block)
215
+ try:
216
+ heading = self.query_one(".subagent-heading", Button)
217
+ except NoMatches:
218
+ # The card sits in its parent's children but its compose()
219
+ # children are not mounted yet — a sibling subagent's event
220
+ # syncing this card inside that window hit here. The data is
221
+ # already stored; on_mount re-renders once the card is live.
222
+ return
223
+ display = str(block.get("display") or block.get("agent") or "子代理")
224
+ suffix = str(block.get("instance") or "").rsplit(":", 1)[-1][:4]
225
+ task = str(block.get("task") or "(任务描述载入中)").replace("\n", " ")
226
+ status = str(block.get("status") or "running")
227
+ status_label = {
228
+ "running": "运行中", "done": "完成", "max_steps": "步数上限",
229
+ "failed": "失败", "cancelled": "已取消", "budget_exceeded": "预算超限",
230
+ }.get(status, status)
231
+ status_mark = {
232
+ "running": "●", "done": "✓", "failed": "✗", "cancelled": "○",
233
+ }.get(status, "·")
234
+ details = []
235
+ if block.get("steps") is not None:
236
+ details.append(f"{block['steps']} 步")
237
+ if block.get("changes"):
238
+ details.append(f"{block['changes']} 处改动")
239
+ detail = " · " + " · ".join(details) if details else ""
240
+ # One collapsed line: identity + status, then the task squeezed into
241
+ # whatever width remains. The budget is measured on the heading
242
+ # button itself (the card's rail and padding shrink it) and covers
243
+ # the arrow prefix, the button's pad and the " · " join, so the
244
+ # ellipsis — not the pane — ends the line.
245
+ head = f"{status_mark} {display}·{suffix} · {status_label}{detail}"
246
+ width = heading.content_size.width or self.content_size.width or 64
247
+ self._heading = \
248
+ f"{head} · {truncate(task, max(4, width - display_width(head) - 8))}"
249
+ heading.label = self.heading_label()
250
+ search = self.query_one(".subagent-search", Input)
251
+ output = self.query_one(".subagent-output", Static)
252
+ if search.value != self._search:
253
+ search.value = self._search
254
+ search.display = self._expanded
255
+ output.display = self._expanded
256
+ if self._expanded:
257
+ self._render_lines(search.value, output)
258
+
259
+ def heading_label(self) -> Content:
260
+ """The heading as verbatim content — task text is model data, and
261
+ Button labels parse square-bracket markup (``[/]`` would raise)."""
262
+ arrow = "▾" if self._expanded else "▸"
263
+ return Content.from_rich_text(Text(f"{arrow} {self._heading}"))
264
+
265
+ def refresh_lines(self) -> None:
266
+ """Refresh transcript text without resetting UI-local search state."""
267
+ if not self.is_mounted:
268
+ return
269
+ self._lines = list(self._block.get("lines") or [])
270
+ search = self.query_one(".subagent-search", Input)
271
+ output = self.query_one(".subagent-output", Static)
272
+ if self._expanded:
273
+ self._render_lines(search.value, output)
274
+
275
+ def _render_lines(self, query: str, output: Static) -> None:
276
+ needle = query.casefold().strip()
277
+ lines = [text for _cls, text in self._lines
278
+ if not needle or needle in text.casefold()]
279
+ output.update("\n".join(lines) if lines else ("(没有匹配内容)" if needle else "(暂无子任务输出)"))
280
+
281
+ def on_mount(self) -> None:
282
+ self.set_data(self._block)
283
+
284
+ def on_resize(self) -> None:
285
+ """The one-line heading truncates to the laid-out width, which is
286
+ still 0 at mount time — re-render once the card has its real size
287
+ (and again if the terminal is resized)."""
288
+ if self._block:
289
+ self.set_data(self._block)
290
+
291
+ def on_button_pressed(self, event: Button.Pressed) -> None:
292
+ if "subagent-heading" not in event.button.classes:
293
+ return
294
+ self._expanded = not self._expanded
295
+ self._block["expanded"] = self._expanded
296
+ heading = self.query_one(".subagent-heading", Button)
297
+ heading.label = self.heading_label()
298
+ search = self.query_one(".subagent-search", Input)
299
+ output = self.query_one(".subagent-output", Static)
300
+ search.display = self._expanded
301
+ output.display = self._expanded
302
+ if self._expanded:
303
+ self._render_lines(search.value, output)
304
+
305
+ def on_input_changed(self, event: Input.Changed) -> None:
306
+ if "subagent-search" in event.input.classes:
307
+ self._search = event.value
308
+ self._block["search"] = event.value
309
+ self._render_lines(event.value,
310
+ self.query_one(".subagent-output", Static))
311
+
312
+
175
313
  # -- pickers ---------------------------------------------------------------------
176
314
 
177
315
  class PickerModal(ModalScreen):
@@ -283,5 +421,3 @@ class ConfirmModal(ModalScreen):
283
421
 
284
422
  def action_refuse(self) -> None:
285
423
  self.dismiss(False)
286
-
287
-
@@ -26,11 +26,16 @@ import os
26
26
  import sys
27
27
  import time
28
28
 
29
- from .agent import _agent_label
30
- from .ui import SUBAGENT_STATUS, fmt_duration, tool_call_label, truncate
29
+ from .ui import fmt_duration, tool_call_label, truncate
31
30
 
32
31
  _STATUS_DONE = "done"
33
32
 
33
+ # Feed rows whose class starts with this prefix are not text lines but
34
+ # position markers: the conversation pane mounts a subagent card at the
35
+ # marker's place, so the card scrolls with the conversation instead of
36
+ # living in a separate region below it.
37
+ SUBAGENT_FEED_PREFIX = "subagent:"
38
+
34
39
 
35
40
  def screen_supported() -> bool:
36
41
  """The full-screen UI needs interactive input and output, never pipes
@@ -94,6 +99,9 @@ class TuiState:
94
99
  self.max_total_tokens: int | None = None
95
100
  self.tools: list[dict] = []
96
101
  self.feed: list[tuple[str, str]] = []
102
+ # One independently searchable transcript per delegation instance.
103
+ # The kernel already gives each parallel invocation a unique tag.
104
+ self.subagents: dict[str, dict] = {}
97
105
  self.streaming = ""
98
106
  self.show_sidebar = True
99
107
  self.started: float | None = None
@@ -107,6 +115,89 @@ class TuiState:
107
115
  self.feed.extend((cls, line) for line in lines)
108
116
  self.invalidate()
109
117
 
118
+ def _subagent(self, instance: str, *, agent: str = "?",
119
+ display: str = "", task: str = "",
120
+ marker: bool = False) -> dict:
121
+ """Return/create one delegation card, keyed by its unique instance.
122
+
123
+ ``marker=True`` (live events) also drops a ``subagent:<instance>``
124
+ marker row into the feed — once per instance — so the card mounts
125
+ at the moment the delegation started. History restore leaves the
126
+ markers to :func:`transcript_feed_lines`, which walks the stored
127
+ rows in order.
128
+ """
129
+ key = str(instance or agent or "unknown")
130
+ block = self.subagents.setdefault(key, {
131
+ "instance": key, "agent": agent, "display": display or agent,
132
+ "task": task, "status": "running", "steps": None,
133
+ "changes": 0, "lines": [], "expanded": False, "search": "",
134
+ "in_feed": False,
135
+ })
136
+ if marker and not block["in_feed"]:
137
+ block["in_feed"] = True
138
+ self.feed.append((SUBAGENT_FEED_PREFIX + key, ""))
139
+ return block
140
+
141
+ def add_subagent_line(self, instance: str, cls: str, text: str,
142
+ **identity) -> None:
143
+ block = self._subagent(instance, **identity)
144
+ block["lines"].append((cls, str(text)))
145
+ self.invalidate()
146
+
147
+ def restore_subagents(self, rows: list[dict]) -> None:
148
+ """Rebuild delegation cards from instance-tagged persisted messages.
149
+
150
+ Feed markers are NOT appended here: the caller builds the feed from
151
+ the same rows through :func:`transcript_feed_lines`, which emits one
152
+ marker per instance at its first row (preserving chronology). The
153
+ blocks are flagged ``in_feed`` so a later live event for the same
154
+ instance cannot append a second marker.
155
+ """
156
+ self.subagents.clear()
157
+ for row in rows:
158
+ instance = str(row.get("subagent") or "")
159
+ if not instance:
160
+ continue
161
+ meta = row.get("meta")
162
+ if isinstance(meta, str):
163
+ try:
164
+ meta = json.loads(meta)
165
+ except (ValueError, TypeError):
166
+ meta = None
167
+ task_info = meta.get("subagent_task") if isinstance(meta, dict) else None
168
+ if isinstance(task_info, dict):
169
+ self._subagent(
170
+ instance, agent=str(task_info.get("agent") or "?"),
171
+ display=str(task_info.get("display") or ""),
172
+ task=str(task_info.get("task") or ""),
173
+ ).update({k: task_info[k] for k in
174
+ ("status", "steps", "changes") if k in task_info})
175
+ self.subagents[instance]["in_feed"] = True
176
+ continue
177
+ block = self._subagent(instance)
178
+ block["in_feed"] = True
179
+ role = row.get("role")
180
+ content = str(row.get("content") or "").strip()
181
+ if role == "assistant":
182
+ calls = row.get("tool_calls")
183
+ if isinstance(calls, str):
184
+ try:
185
+ calls = json.loads(calls)
186
+ except (ValueError, TypeError):
187
+ calls = None
188
+ if isinstance(calls, list):
189
+ for call in calls:
190
+ fn = call.get("function") if isinstance(call, dict) else None
191
+ if isinstance(fn, dict):
192
+ name = str(fn.get("name") or "tool")
193
+ block["lines"].append(("tool", f"◆ {name}"))
194
+ if content:
195
+ block["lines"].append(("assistant", content))
196
+ elif role == "tool" and content:
197
+ name = str(row.get("tool_name") or "工具")
198
+ block["lines"].append(("dim", f"{name}:{content}"))
199
+ self.invalidate()
200
+
110
201
  def invalidate(self) -> None:
111
202
  """Presentation refresh hook. The Textual front-end repaints on its
112
203
  own event loop, so this is deliberately a no-op here."""
@@ -246,29 +337,36 @@ class TuiState:
246
337
  # shows why the model's course changed.
247
338
  self.say("user", str(ev.get("text") or ""))
248
339
  elif kind == "subagent_start":
249
- # Per-delegation record (ToolResult.ui): which worker got what
250
- # task — the group's feed line, labeled with the display name
251
- # (plus the instance suffix that keeps same-agent parallel
252
- # delegations distinguishable).
253
- who = _agent_label(ev)
254
- task = str(ev.get("task") or "").replace("\n", " ").strip()
255
- self.say("tool", f"▸ {who}:{task[:120]}" if task else f"▸ {who}")
340
+ instance = str(ev.get("instance") or ev.get("agent") or "unknown")
341
+ block = self._subagent(
342
+ instance, agent=str(ev.get("agent") or "?"),
343
+ display=str(ev.get("display") or ""),
344
+ task=str(ev.get("task") or ""),
345
+ marker=True,
346
+ )
347
+ block.update({"agent": str(ev.get("agent") or block["agent"]),
348
+ "display": str(ev.get("display") or block["display"]),
349
+ "task": str(ev.get("task") or block["task"])})
350
+ self.invalidate()
256
351
  elif kind == "subagent_end":
257
- who = _agent_label(ev)
352
+ instance = str(ev.get("instance") or ev.get("agent") or "unknown")
353
+ block = self._subagent(
354
+ instance, agent=str(ev.get("agent") or "?"),
355
+ display=str(ev.get("display") or ""),
356
+ marker=True,
357
+ )
258
358
  status = str(ev.get("status") or "")
259
- bits = [SUBAGENT_STATUS.get(status, status or "?")]
260
- if ev.get("steps") is not None:
261
- bits.append(f"{ev['steps']} 步")
262
- if ev.get("changes"):
263
- bits.append(f"{ev['changes']} 处改动")
264
- cls = ("ok" if ev.get("ok")
265
- else "warn" if status == "cancelled" else "err")
266
- self.say(cls, f"▪ {who} · " + " · ".join(bits))
359
+ block.update(status=status or block["status"],
360
+ steps=ev.get("steps"), changes=ev.get("changes", 0))
361
+ self.invalidate()
267
362
  elif kind == "subagent_progress":
268
- # Live heartbeat (kernel on_subagent_event, wired in
269
- # register_subagents): each worker's tool calls and outputs,
270
- # prefixed so parallel workers stay distinguishable.
271
- who = _agent_label(ev)
363
+ # Live worker output belongs to its independent instance block.
364
+ instance = str(ev.get("instance") or ev.get("agent") or "unknown")
365
+ block = self._subagent(
366
+ instance, agent=str(ev.get("agent") or "?"),
367
+ display=str(ev.get("display") or ""),
368
+ marker=True,
369
+ )
272
370
  inner = ev.get("event") or {}
273
371
  t = inner.get("type")
274
372
  if t == "tool_call":
@@ -280,7 +378,10 @@ class TuiState:
280
378
  except (ValueError, TypeError):
281
379
  args = {}
282
380
  args = args if isinstance(args, dict) else {}
283
- self.say("tool", f"[{who}] ◆ {tool_call_label(name, args)}")
381
+ label = f"◆ {tool_call_label(name, args)}"
382
+ self.add_subagent_line(instance, "tool", label,
383
+ agent=block["agent"],
384
+ display=block["display"])
284
385
  elif t == "tool_result":
285
386
  ok = bool(inner.get("ok"))
286
387
  label = str(inner.get("summary") or "").replace("\n", " ")
@@ -290,17 +391,25 @@ class TuiState:
290
391
  label = detail if len(detail) > len(label) else label
291
392
  elif detail:
292
393
  label = f"{label} · {detail}" if label else detail
293
- self.say("ok" if ok else "err",
294
- f"[{who}] {'✓' if ok else '✗'} {label}")
394
+ self.add_subagent_line(instance, "ok" if ok else "err",
395
+ f"{'✓' if ok else '✗'} {label}",
396
+ agent=block["agent"],
397
+ display=block["display"])
295
398
  elif t == "assistant":
296
399
  text = str(inner.get("text") or "").replace("\n", " ").strip()
297
400
  if text:
298
- self.say("dim", f"[{who}] {text[:200]}")
401
+ self.add_subagent_line(instance, "dim", text[:200],
402
+ agent=block["agent"],
403
+ display=block["display"])
299
404
  elif t == "error":
300
405
  msg = str(inner.get("message") or "出错").replace("\n", " ")
301
- self.say("err", f"[{who}] {msg[:200]}")
406
+ self.add_subagent_line(instance, "err", msg[:200],
407
+ agent=block["agent"],
408
+ display=block["display"])
302
409
  elif t == "cancelled":
303
- self.say("warn", f"[{who}] 已取消")
410
+ self.add_subagent_line(instance, "warn", "已取消",
411
+ agent=block["agent"],
412
+ display=block["display"])
304
413
  elif kind == "done":
305
414
  status = str(ev.get("status") or _STATUS_DONE)
306
415
  self.last_status = status
@@ -416,7 +525,8 @@ def feed_text(feed: list[tuple[str, str]], scope: str = "all",
416
525
  ``user`` the lines the user typed, ``tools`` the tool call/result
417
526
  lines, ``all`` the whole feed. ``extra`` is the text still streaming:
418
527
  it is not in the feed yet, which makes it *the* newest answer for
419
- ``last`` and a tail to append for ``all``.
528
+ ``last`` and a tail to append for ``all``. Subagent position markers
529
+ carry no text and never reach the clipboard.
420
530
  """
421
531
  extra = str(extra or "").rstrip("\n")
422
532
  if scope == "last" and extra.strip():
@@ -428,7 +538,8 @@ def feed_text(feed: list[tuple[str, str]], scope: str = "all",
428
538
  elif scope == "last":
429
539
  lines = _last_answer(feed)
430
540
  else:
431
- lines = [text for _cls, text in feed]
541
+ lines = [text for cls, text in feed
542
+ if not cls.startswith(SUBAGENT_FEED_PREFIX)]
432
543
  text = "\n".join(lines).strip("\n")
433
544
  if extra and scope == "all":
434
545
  text = f"{text}\n{extra}".strip("\n")
@@ -456,11 +567,24 @@ def describe_copy(text: str) -> str:
456
567
 
457
568
 
458
569
  def transcript_feed_lines(rows):
459
- """Stored session messages -> conversation feed rows (feed rebuild)."""
570
+ """Stored session messages -> conversation feed rows (feed rebuild).
571
+
572
+ A subagent's own rows are rendered in its instance card, never folded
573
+ into the orchestrator's shared stream; each instance contributes one
574
+ ``subagent:<instance>`` marker at its first stored row, where the
575
+ conversation pane mounts that card (chronology preserved).
576
+ """
460
577
  import json as _json
461
578
 
462
579
  out = []
580
+ seen_instances: set[str] = set()
463
581
  for m in rows:
582
+ instance = str(m.get("subagent") or "")
583
+ if instance:
584
+ if instance not in seen_instances:
585
+ seen_instances.add(instance)
586
+ out.append((SUBAGENT_FEED_PREFIX + instance, ""))
587
+ continue
464
588
  role = m.get("role")
465
589
  content = (m.get("content") or "").strip()
466
590
  if role == "user" and content:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: lithe-cli
3
- Version: 0.1.6
3
+ Version: 0.1.9
4
4
  Summary: Command-line interface for the lithe agent kernel: chat, one-shot runs, undo, and run inspection.
5
5
  License: MIT License
6
6
 
@@ -39,7 +39,7 @@ Classifier: Typing :: Typed
39
39
  Requires-Python: >=3.10
40
40
  Description-Content-Type: text/markdown
41
41
  License-File: LICENSE
42
- Requires-Dist: lithe>=0.1.4
42
+ Requires-Dist: lithe>=0.1.5
43
43
  Requires-Dist: prompt-toolkit>=3.0.38
44
44
  Requires-Dist: textual>=1.0
45
45
  Provides-Extra: dev
@@ -1,4 +1,4 @@
1
- lithe>=0.1.4
1
+ lithe>=0.1.5
2
2
  prompt-toolkit>=3.0.38
3
3
  textual>=1.0
4
4
 
@@ -9,7 +9,7 @@ description = "Command-line interface for the lithe agent kernel: chat, one-shot
9
9
  readme = "README.md"
10
10
  license = { file = "LICENSE" }
11
11
  requires-python = ">=3.10"
12
- dependencies = ["lithe>=0.1.4", "prompt-toolkit>=3.0.38", "textual>=1.0"]
12
+ dependencies = ["lithe>=0.1.5", "prompt-toolkit>=3.0.38", "textual>=1.0"]
13
13
  keywords = ["agent", "llm", "react", "cli", "tool-calling"]
14
14
  classifiers = [
15
15
  "Development Status :: 4 - Beta",
@@ -86,6 +86,26 @@ def test_plain_repl_copy_command_reaches_the_clipboard(
86
86
  assert "已复制最后一条回答" in out and "pbcopy" in out
87
87
 
88
88
 
89
+ def test_transcript_can_include_subagent_instance_rows(tmp_path):
90
+ wb = Workbench(make_config(tmp_path, []))
91
+ wb.open(title="有子任务的会话")
92
+ cid = wb.current["id"]
93
+ rid = "subagent-history-test"
94
+ wb.store.create_run(rid, wb.cfg.user_id, "任务", conversation_id=cid)
95
+ from lithe.bundles.store.protocol import StoredMessage
96
+
97
+ wb.store.add_message(StoredMessage(
98
+ role="user", content="主任务", run_id=rid, user_id=wb.cfg.user_id
99
+ ))
100
+ wb.store.add_message(StoredMessage(
101
+ role="user", content="子任务", run_id=rid, user_id=wb.cfg.user_id,
102
+ subagent="researcher:abcd",
103
+ ))
104
+ assert [r["content"] for r in wb.sessions.transcript(cid)] == ["主任务"]
105
+ all_rows = wb.sessions.transcript(cid, last=0, include_subagents=True)
106
+ assert [r.get("subagent") for r in all_rows] == [None, "researcher:abcd"]
107
+
108
+
89
109
  def test_sessions_subcommand_lists_renames_deletes(tmp_path, capsys):
90
110
  from lithe_cli.main import main
91
111
 
@@ -179,7 +179,7 @@ def test_delegation_renders_live_progress_and_records(tmp_path, capsys):
179
179
  # same-agent parallel delegations distinguishable
180
180
  assert re.search(r"\[检索员·[0-9a-f]{4}\]", out)
181
181
  assert "a.md 的内容是待办清单" in out
182
- # per-agent start/end records follow the delegation's tool_result
182
+ # the plain REPL still renders task lifecycle records after the live output
183
183
  assert re.search(r"▸ 检索员·[0-9a-f]{4}:找一下 a\.md 里写了什么", out)
184
184
  assert re.search(r"▪ 检索员·[0-9a-f]{4} · 完成", out)
185
185
  # the footer carries the delegation footprint
@@ -251,23 +251,68 @@ def test_tui_folds_subagent_events():
251
251
 
252
252
  state = TuiState("m", "/ws", 5)
253
253
  state.on_event({"type": "subagent_start", "agent": "researcher",
254
- "display": "检索员", "task": "查 a.md"})
254
+ "display": "检索员", "task": "查 a.md",
255
+ "instance": "researcher:a111"})
255
256
  state.on_event({"type": "subagent_progress", "agent": "researcher",
256
- "display": "检索员", "event": {
257
+ "display": "检索员", "instance": "researcher:a111",
258
+ "event": {
257
259
  "type": "tool_call", "name": "read_file",
258
260
  "args": '{"path": "a.md"}'}})
259
261
  state.on_event({"type": "subagent_progress", "agent": "researcher",
260
- "display": "检索员", "event": {
262
+ "display": "检索员", "instance": "researcher:a111",
263
+ "event": {
261
264
  "type": "tool_result", "ok": True,
262
265
  "summary": "读取 a.md"}})
263
266
  state.on_event({"type": "subagent_end", "agent": "researcher",
264
- "display": "检索员", "status": "done", "steps": 2,
267
+ "display": "检索员", "instance": "researcher:a111",
268
+ "status": "done", "steps": 2,
265
269
  "changes": 0, "ok": True})
266
270
  state.on_event({"type": "done", "status": "done", "steps": 2,
267
271
  "subagent_delegations": 1, "subagent_cost": 0.01})
272
+ assert len(state.subagents) == 1
273
+ block = state.subagents["researcher:a111"]
274
+ assert block["task"] == "查 a.md"
275
+ assert block["status"] == "done" and block["steps"] == 2
276
+ lines = "\n".join(text for _, text in block["lines"])
277
+ assert "read_file" in lines and "a.md" in lines
278
+ assert "✓ 读取 a.md" in lines
268
279
  feed = "\n".join(text for _, text in state.feed)
269
- assert "▸ 检索员:查 a.md" in feed
270
- assert "[检索员] ◆ read_file · 读取 a.md" in feed
271
- assert "[检索员] ✓ 读取 a.md" in feed
272
- assert "▪ 检索员 · 完成 · 2 步" in feed
273
280
  assert "委派 1 次" in feed and "子代理花费 $0.0100" in feed
281
+ assert not any("检索员" in text for _, text in state.feed)
282
+ # the live start dropped one position marker into the feed — the pane
283
+ # mounts the card there, in the conversation's scroll flow
284
+ from lithe_cli.tui import SUBAGENT_FEED_PREFIX
285
+
286
+ assert (SUBAGENT_FEED_PREFIX + "researcher:a111", "") in state.feed
287
+ assert block["in_feed"] is True
288
+
289
+
290
+ def test_tui_subagent_instances_and_history_restore():
291
+ from lithe_cli.tui import TuiState, transcript_feed_lines
292
+
293
+ state = TuiState("m", "/ws", 5)
294
+ rows = [
295
+ {"role": "user", "content": "检查 alpha", "subagent": "researcher:a111",
296
+ "meta": {"subagent_task": {"agent": "researcher", "display": "检索员",
297
+ "task": "检查 alpha", "status": "running"}}},
298
+ {"role": "assistant", "content": "发现 alpha", "subagent": "researcher:a111"},
299
+ {"role": "tool", "tool_name": "read_file", "content": "读取 alpha.txt",
300
+ "subagent": "researcher:a111"},
301
+ {"role": "assistant", "content": None, "subagent": "researcher:a111",
302
+ "meta": {"subagent_task": {"agent": "researcher", "display": "检索员",
303
+ "task": "检查 alpha", "status": "done",
304
+ "steps": 2}}},
305
+ {"role": "user", "content": "检查 beta", "subagent": "researcher:b222",
306
+ "meta": {"subagent_task": {"agent": "researcher", "display": "检索员",
307
+ "task": "检查 beta", "status": "failed"}}},
308
+ ]
309
+ state.feed.extend(transcript_feed_lines(rows))
310
+ state.restore_subagents(rows)
311
+ assert len(state.subagents) == 2
312
+ assert state.subagents["researcher:a111"]["status"] == "done"
313
+ assert state.subagents["researcher:a111"]["steps"] == 2
314
+ assert "发现 alpha" in " ".join(
315
+ text for _, text in state.subagents["researcher:a111"]["lines"]
316
+ )
317
+ assert state.subagents["researcher:b222"]["status"] == "failed"
318
+ assert not any("alpha" in text or "beta" in text for _, text in state.feed)
@@ -3,6 +3,7 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import asyncio
6
+ from types import SimpleNamespace
6
7
 
7
8
  import pytest
8
9
 
@@ -18,6 +19,7 @@ from lithe_cli.ttui import ( # noqa: E402
18
19
  ConfirmModal,
19
20
  LitheApp,
20
21
  PickerModal,
22
+ SubagentCard,
21
23
  footer_text,
22
24
  header_text,
23
25
  sidebar_markup,
@@ -394,6 +396,146 @@ async def _settle_bottom(pilot, conv):
394
396
  return
395
397
 
396
398
 
399
+ def test_completed_turn_does_not_duplicate_the_feed(tmp_path):
400
+ """Regression: session_idle used to reload the store transcript on top
401
+ of the live-mounted rows, so every finished turn appeared twice."""
402
+
403
+ async def scenario():
404
+ app = _app(tmp_path, WRITE_THEN_ANSWER)
405
+ async with app.run_test(size=(100, 30)) as pilot:
406
+ await pilot.pause()
407
+ app.query_one("#prompt").value = "把 a.txt 写为 hi"
408
+ await pilot.press("enter")
409
+ assert await _run_until_done(pilot, app), "turn did not finish"
410
+ await pilot.pause(0.3) # let the idle event land
411
+ conv = app.query_one("#conv")
412
+ mounted = [str(c.content) for c in conv.children
413
+ if c.id != "streaming"]
414
+ assert len(mounted) == len(set(mounted)), "rows must not double"
415
+ from lithe_cli.tui import SUBAGENT_FEED_PREFIX
416
+
417
+ expected = [text for cls, text in app.state.feed
418
+ if not cls.startswith(SUBAGENT_FEED_PREFIX)]
419
+ assert mounted == expected
420
+
421
+ asyncio.run(scenario())
422
+
423
+
424
+ def test_subagent_cards_mount_and_search_independently(tmp_path):
425
+ async def scenario():
426
+ app = _app(tmp_path, [])
427
+ async with app.run_test() as pilot:
428
+ state = app.state
429
+ state.say("user", "先调研再实现")
430
+ state.on_event({"type": "subagent_start", "agent": "researcher",
431
+ "display": "检索员", "task": "找 alpha",
432
+ "instance": "researcher:a111"})
433
+ state.on_event({"type": "subagent_progress", "agent": "researcher",
434
+ "display": "检索员", "instance": "researcher:a111",
435
+ "event": {"type": "tool_result", "ok": True,
436
+ "summary": "发现 alpha.txt"}})
437
+ state.say("dim", "调研完成,开始实现")
438
+ state.on_event({"type": "subagent_start", "agent": "coder",
439
+ "display": "编码员", "task": "实现 beta",
440
+ "instance": "coder:b222"})
441
+ state.on_event({"type": "subagent_progress", "agent": "coder",
442
+ "display": "编码员", "instance": "coder:b222",
443
+ "event": {"type": "tool_result", "ok": True,
444
+ "summary": "修改 beta.py"}})
445
+ app._sync_feed()
446
+ await pilot.pause()
447
+ conv = app.query_one("#conv")
448
+ cards = list(app.query(SubagentCard))
449
+ assert len(cards) == 2
450
+ assert {card.instance for card in cards} == {
451
+ "researcher:a111", "coder:b222"
452
+ }
453
+ # Cards live inside the conversation pane, in chronology with
454
+ # the feed lines around them — they scroll with the transcript,
455
+ # not in a region of their own below it.
456
+ assert all(card.parent is conv for card in cards)
457
+ kinds = ["user" if c.classes == {"user"} else
458
+ "card" if isinstance(c, SubagentCard) else "line"
459
+ for c in conv.children if c.id != "streaming"]
460
+ assert kinds == ["user", "card", "line", "card"]
461
+ # Collapsed = exactly one row (heading only, no borders/margins)
462
+ collapsed = next(c for c in cards
463
+ if c.instance == "coder:b222")
464
+ assert collapsed.region.height == 1
465
+ card = next(c for c in cards if c.instance == "researcher:a111")
466
+ card._expanded = True
467
+ card.set_data(state.subagents[card.instance])
468
+ await pilot.pause()
469
+ search = card.query_one(".subagent-search")
470
+ search.value = "alpha"
471
+ await pilot.pause()
472
+ output = str(card.query_one(".subagent-output").content)
473
+ assert "alpha" in output
474
+ assert "beta" not in output
475
+ other = next(c for c in cards if c.instance == "coder:b222")
476
+ assert other._search == ""
477
+
478
+ asyncio.run(scenario())
479
+
480
+
481
+ def test_resumed_session_mounts_persisted_subagent_cards(tmp_path):
482
+ from lithe.bundles.store.protocol import StoredMessage
483
+ from lithe_cli.workbench import Workbench
484
+
485
+ cfg = make_config(tmp_path, [])
486
+ wb = Workbench(cfg)
487
+ session = wb.new_session(title="恢复子任务")
488
+ cid = session["id"]
489
+ run_id = "persisted-subagent-run"
490
+ wb.store.create_run(run_id, cfg.user_id, "检查项目",
491
+ conversation_id=cid)
492
+ wb.store.add_message(StoredMessage(
493
+ role="user", content="开始检查项目", run_id=run_id,
494
+ user_id=cfg.user_id,
495
+ ))
496
+ wb.store.add_message(StoredMessage(
497
+ role="user", content="检查 README", run_id=run_id,
498
+ user_id=cfg.user_id, subagent="researcher:abcd",
499
+ meta={"subagent_task": {"agent": "researcher", "display": "检索员",
500
+ "task": "检查 README", "instance": "researcher:abcd",
501
+ "status": "done", "steps": 3}},
502
+ ))
503
+ wb.store.add_message(StoredMessage(
504
+ role="assistant", content="README 包含使用说明", run_id=run_id,
505
+ user_id=cfg.user_id, subagent="researcher:abcd",
506
+ ))
507
+ wb.store.add_message(StoredMessage(
508
+ role="assistant", content="结论:README 已检查", run_id=run_id,
509
+ user_id=cfg.user_id,
510
+ ))
511
+ app = LitheApp(cfg, None, "chat",
512
+ args=SimpleNamespace(resume=str(cid), cont=False, title=None))
513
+
514
+ async def scenario():
515
+ async with app.run_test() as pilot:
516
+ await pilot.pause()
517
+ cards = list(app.query(SubagentCard))
518
+ assert len(cards) == 1
519
+ card = cards[0]
520
+ assert card.instance == "researcher:abcd"
521
+ assert "检查 README" in str(card.query_one(".subagent-heading").label)
522
+ assert app.state.subagents[card.instance]["status"] == "done"
523
+ assert any("README 包含使用说明" in line
524
+ for _cls, line in app.state.subagents[card.instance]["lines"])
525
+ assert not any("检查 README" in line for _cls, line in app.state.feed)
526
+ # The card mounts where the delegation sat in the stored
527
+ # transcript — between the orchestrator's own rows, not
528
+ # appended after them.
529
+ conv = app.query_one("#conv")
530
+ order = [type(c).__name__ for c in conv.children
531
+ if c.id != "streaming"]
532
+ pos = order.index("SubagentCard")
533
+ assert 0 < pos < len(order) - 1
534
+ assert order[pos - 1] == order[pos + 1] == "Static"
535
+
536
+ asyncio.run(scenario())
537
+
538
+
397
539
  def test_sync_feed_follows_only_when_at_bottom(tmp_path):
398
540
  """Scrolling up to re-read earlier output sticks; new events must not
399
541
  yank the reader back to the bottom."""
@@ -48,6 +48,19 @@ def test_feed_text_scopes_pick_the_right_rows():
48
48
  assert "已完成。" not in tools
49
49
 
50
50
 
51
+ def test_feed_text_skips_subagent_position_markers():
52
+ """Markers are mounting instructions for the pane, not transcript text:
53
+ /copy all must lift the conversation without blank marker lines."""
54
+ from lithe_cli.tui import SUBAGENT_FEED_PREFIX
55
+
56
+ feed = [
57
+ ("user", "分工"),
58
+ (SUBAGENT_FEED_PREFIX + "researcher:a111", ""),
59
+ ("assistant", "已完成。"),
60
+ ]
61
+ assert feed_text(feed, "all") == "分工\n已完成。"
62
+
63
+
51
64
  def test_feed_text_last_does_not_walk_into_earlier_answers():
52
65
  feed = [
53
66
  ("assistant", "第一轮回答"),
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes