lithe-cli 0.1.7__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.7 → lithe_cli-0.1.9}/PKG-INFO +1 -1
  2. {lithe_cli-0.1.7 → lithe_cli-0.1.9}/lithe_cli/__init__.py +1 -1
  3. {lithe_cli-0.1.7 → lithe_cli-0.1.9}/lithe_cli/ttui.py +62 -49
  4. {lithe_cli-0.1.7 → lithe_cli-0.1.9}/lithe_cli/ttui_widgets.py +40 -4
  5. {lithe_cli-0.1.7 → lithe_cli-0.1.9}/lithe_cli/tui.py +52 -10
  6. {lithe_cli-0.1.7 → lithe_cli-0.1.9}/lithe_cli.egg-info/PKG-INFO +1 -1
  7. {lithe_cli-0.1.7 → lithe_cli-0.1.9}/tests/test_cli_subagents.py +6 -0
  8. {lithe_cli-0.1.7 → lithe_cli-0.1.9}/tests/test_ttui.py +57 -0
  9. {lithe_cli-0.1.7 → lithe_cli-0.1.9}/tests/test_tui_v2.py +13 -0
  10. {lithe_cli-0.1.7 → lithe_cli-0.1.9}/LICENSE +0 -0
  11. {lithe_cli-0.1.7 → lithe_cli-0.1.9}/README.md +0 -0
  12. {lithe_cli-0.1.7 → lithe_cli-0.1.9}/lithe_cli/__main__.py +0 -0
  13. {lithe_cli-0.1.7 → lithe_cli-0.1.9}/lithe_cli/agent.py +0 -0
  14. {lithe_cli-0.1.7 → lithe_cli-0.1.9}/lithe_cli/cli_parser.py +0 -0
  15. {lithe_cli-0.1.7 → lithe_cli-0.1.9}/lithe_cli/clipboard.py +0 -0
  16. {lithe_cli-0.1.7 → lithe_cli-0.1.9}/lithe_cli/commands.py +0 -0
  17. {lithe_cli-0.1.7 → lithe_cli-0.1.9}/lithe_cli/config.py +0 -0
  18. {lithe_cli-0.1.7 → lithe_cli-0.1.9}/lithe_cli/main.py +0 -0
  19. {lithe_cli-0.1.7 → lithe_cli-0.1.9}/lithe_cli/profiles.py +0 -0
  20. {lithe_cli-0.1.7 → lithe_cli-0.1.9}/lithe_cli/prompts.py +0 -0
  21. {lithe_cli-0.1.7 → lithe_cli-0.1.9}/lithe_cli/py.typed +0 -0
  22. {lithe_cli-0.1.7 → lithe_cli-0.1.9}/lithe_cli/sessions.py +0 -0
  23. {lithe_cli-0.1.7 → lithe_cli-0.1.9}/lithe_cli/setup.py +0 -0
  24. {lithe_cli-0.1.7 → lithe_cli-0.1.9}/lithe_cli/ttui_render.py +0 -0
  25. {lithe_cli-0.1.7 → lithe_cli-0.1.9}/lithe_cli/ui.py +0 -0
  26. {lithe_cli-0.1.7 → lithe_cli-0.1.9}/lithe_cli/workbench.py +0 -0
  27. {lithe_cli-0.1.7 → lithe_cli-0.1.9}/lithe_cli.egg-info/SOURCES.txt +0 -0
  28. {lithe_cli-0.1.7 → lithe_cli-0.1.9}/lithe_cli.egg-info/dependency_links.txt +0 -0
  29. {lithe_cli-0.1.7 → lithe_cli-0.1.9}/lithe_cli.egg-info/entry_points.txt +0 -0
  30. {lithe_cli-0.1.7 → lithe_cli-0.1.9}/lithe_cli.egg-info/requires.txt +0 -0
  31. {lithe_cli-0.1.7 → lithe_cli-0.1.9}/lithe_cli.egg-info/top_level.txt +0 -0
  32. {lithe_cli-0.1.7 → lithe_cli-0.1.9}/pyproject.toml +0 -0
  33. {lithe_cli-0.1.7 → lithe_cli-0.1.9}/setup.cfg +0 -0
  34. {lithe_cli-0.1.7 → lithe_cli-0.1.9}/tests/test_cli.py +0 -0
  35. {lithe_cli-0.1.7 → lithe_cli-0.1.9}/tests/test_cli_budget_steer.py +0 -0
  36. {lithe_cli-0.1.7 → lithe_cli-0.1.9}/tests/test_cli_clipboard.py +0 -0
  37. {lithe_cli-0.1.7 → lithe_cli-0.1.9}/tests/test_cli_guard.py +0 -0
  38. {lithe_cli-0.1.7 → lithe_cli-0.1.9}/tests/test_cli_sessions.py +0 -0
  39. {lithe_cli-0.1.7 → lithe_cli-0.1.9}/tests/test_profiles.py +0 -0
  40. {lithe_cli-0.1.7 → 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.7
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
 
@@ -1,3 +1,3 @@
1
1
  """lithe-cli: the command-line interface for the lithe agent kernel."""
2
2
 
3
- __version__ = "0.1.7"
3
+ __version__ = "0.1.9"
@@ -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,
@@ -60,11 +61,15 @@ class LitheApp(App):
60
61
  #body { height: 1fr; }
61
62
  #main-column { width: 1fr; height: 1fr; }
62
63
  #conv { width: 1fr; height: 1fr; border: round #475569; padding: 0 1; }
63
- #subagents { height: auto; max-height: 14; overflow-y: auto; }
64
- .subagent-card { height: auto; border: round #334155; padding: 0 1; margin: 0 0 1 0; }
65
- .subagent-heading { width: 1fr; height: auto; min-height: 1; color: #fbbf24; text-align: left; }
66
- .subagent-search { height: 3; margin: 0 0 1 0; }
67
- .subagent-output { height: auto; color: #cbd5e1; }
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; }
68
73
  #side-wrap { width: 44; border: round #475569; padding: 0 1; }
69
74
  #prompt { border: round #475569; }
70
75
  #foot { height: 1; background: #111827; color: #cbd5e1; }
@@ -101,7 +106,6 @@ class LitheApp(App):
101
106
  self.mode = mode
102
107
  self.args = args
103
108
  self._shown = 0 # feed lines already mounted
104
- self._subagent_signature = ()
105
109
  self._cancel_asked = False # first Ctrl+C cancels, second exits
106
110
  self._pending_selection = "" # selection captured at right-click time
107
111
 
@@ -114,8 +118,6 @@ class LitheApp(App):
114
118
  with ConversationPane(id="conv"):
115
119
  yield Static("", id="streaming", classes="assistant",
116
120
  markup=False)
117
- with VerticalScroll(id="subagents"):
118
- pass
119
121
  with VerticalScroll(id="side-wrap"):
120
122
  yield Static("", id="side", markup=True)
121
123
  yield Static("", id="suggest")
@@ -153,7 +155,6 @@ class LitheApp(App):
153
155
  cid = self._current_cid()
154
156
  self._load_session_history(self.state, cid)
155
157
  self.states[cid] = self.state
156
- self._initial_history_loaded = True
157
158
  for cls, text in opening:
158
159
  self.state.say(cls, text)
159
160
  self.wb.subscribe(
@@ -198,12 +199,17 @@ class LitheApp(App):
198
199
  return st
199
200
 
200
201
  def _load_session_history(self, state: TuiState, cid: int) -> None:
201
- """Load both the orchestrator feed and subagent cards on first open."""
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
+ """
202
208
  history = self.wb.sessions.transcript(
203
209
  cid, last=0, include_subagents=True
204
210
  )
205
- main_rows = [row for row in history if not row.get("subagent")]
206
- state.feed.extend(transcript_feed_lines(main_rows[-200:]))
211
+ rows = transcript_feed_lines(history)
212
+ state.feed.extend(rows[-200:])
207
213
  state.restore_subagents(history)
208
214
  usage = self.wb.sessions.usage_snapshot(cid)
209
215
  if usage.get("known"):
@@ -222,7 +228,7 @@ class LitheApp(App):
222
228
  self.state.subagents.clear()
223
229
  self._load_session_history(self.state, cid)
224
230
  self._shown = 0
225
- self._subagent_signature = ()
231
+ self._clear_conversation()
226
232
  self._sync_feed()
227
233
 
228
234
  def _refresh_meta(self) -> None:
@@ -249,31 +255,40 @@ class LitheApp(App):
249
255
  st = self._base_state(cid)
250
256
  self._load_session_history(st, cid)
251
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()
252
272
  # Reload from the conversation's persisted store when returning to it:
253
273
  # a background turn or /undo may have changed its todos meanwhile.
254
274
  self.states[cid].todos = JsonTodoStore(
255
275
  todo_store_path(self.cfg, cid)
256
276
  ).list()
257
- self.state = self.states[cid]
258
- self._shown = 0
259
- self._subagent_signature = ()
260
- subagents = self.query_one("#subagents", VerticalScroll)
261
- for card in list(subagents.children):
262
- card.remove()
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."""
263
282
  conv = self.query_one("#conv", ConversationPane)
264
283
  for child in list(conv.children):
265
284
  if child.id != "streaming":
266
285
  child.remove()
267
- self._refresh_meta()
268
- self._sync_feed()
269
- self._refresh_chrome()
270
286
 
271
287
  # -- conversation rendering (pure render-from-state) ----------------------
272
288
 
273
289
  def _sync_feed(self) -> None:
274
290
  conv = self.query_one("#conv", ConversationPane)
275
291
  streaming = self.query_one("#streaming", Static)
276
- subagents = self.query_one("#subagents", VerticalScroll)
277
292
  # Follow the feed only when the reader is already at (or near) the
278
293
  # bottom: scrolling up to re-read earlier output mid-run must stick,
279
294
  # not be yanked back to the bottom on every event.
@@ -282,42 +297,38 @@ class LitheApp(App):
282
297
  while self._shown < len(feed):
283
298
  cls, text = feed[self._shown]
284
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
285
311
  # markup=False: model/tool text is data, not Textual markup —
286
312
  # a "[x]" in an answer must render, not parse (and it is what
287
313
  # /copy sends to the clipboard verbatim).
288
314
  conv.mount(Static(text, classes=cls or "dim", markup=False),
289
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.
290
319
  non_stream = [c for c in conv.children if c.id != "streaming"]
291
- for stale in non_stream[:max(0, len(non_stream) - _MAX_FEED)]:
292
- 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()
293
324
  if self.state.streaming:
294
325
  streaming.update(self.state.streaming)
295
326
  else:
296
327
  streaming.update("")
297
- for child in subagents.children:
328
+ for child in conv.children:
298
329
  if isinstance(child, SubagentCard):
299
330
  child._block["expanded"] = child._expanded
300
331
  child._block["search"] = child._search
301
- signature = tuple(
302
- (key, block.get("status"), block.get("task"),
303
- bool(block.get("expanded")), str(block.get("search") or ""))
304
- for key, block in self.state.subagents.items()
305
- )
306
- if signature != self._subagent_signature:
307
- self._subagent_signature = signature
308
- cards = {child.instance: child for child in subagents.children
309
- if isinstance(child, SubagentCard)}
310
- for instance, card in cards.items():
311
- if instance not in self.state.subagents:
312
- card.remove()
313
- for instance, block in self.state.subagents.items():
314
- card = cards.get(instance)
315
- if card is None:
316
- card = SubagentCard(instance, block)
317
- subagents.mount(card)
318
- card.call_after_refresh(card.set_data, block)
319
- else:
320
- card.set_data(block)
321
332
  self.call_after_refresh(self._refresh_subagent_lines)
322
333
  if at_bottom:
323
334
  conv.scroll_end(animate=False)
@@ -331,7 +342,7 @@ class LitheApp(App):
331
342
  def _refresh_subagent_lines(self) -> None:
332
343
  """Refresh mounted card transcripts after each event, preserving UI."""
333
344
  try:
334
- container = self.query_one("#subagents", VerticalScroll)
345
+ container = self.query_one("#conv", ConversationPane)
335
346
  except Exception:
336
347
  return
337
348
  for card in container.children:
@@ -369,8 +380,10 @@ class LitheApp(App):
369
380
  return
370
381
  if t == "session_idle":
371
382
  if cid == self._current_cid():
372
- if self._initial_history_loaded:
373
- self.action_refresh_session_history()
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.
374
387
  self.state.running = False
375
388
  self.state.stop = None
376
389
  self._cancel_asked = False
@@ -4,13 +4,18 @@ 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
15
  from textual.widgets import Button, Input, Label, ListItem, ListView, Static
13
16
 
17
+ from .ui import display_width, truncate
18
+
14
19
  # -- input: completion + persistent history ------------------------------------
15
20
 
16
21
  def completion_suggestions(
@@ -207,6 +212,14 @@ class SubagentCard(Vertical):
207
212
 
208
213
  def set_data(self, block: dict) -> None:
209
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
210
223
  display = str(block.get("display") or block.get("agent") or "子代理")
211
224
  suffix = str(block.get("instance") or "").rsplit(":", 1)[-1][:4]
212
225
  task = str(block.get("task") or "(任务描述载入中)").replace("\n", " ")
@@ -215,15 +228,25 @@ class SubagentCard(Vertical):
215
228
  "running": "运行中", "done": "完成", "max_steps": "步数上限",
216
229
  "failed": "失败", "cancelled": "已取消", "budget_exceeded": "预算超限",
217
230
  }.get(status, status)
231
+ status_mark = {
232
+ "running": "●", "done": "✓", "failed": "✗", "cancelled": "○",
233
+ }.get(status, "·")
218
234
  details = []
219
235
  if block.get("steps") is not None:
220
236
  details.append(f"{block['steps']} 步")
221
237
  if block.get("changes"):
222
238
  details.append(f"{block['changes']} 处改动")
223
239
  detail = " · " + " · ".join(details) if details else ""
224
- heading = self.query_one(".subagent-heading", Button)
225
- self._heading = f"{display}·{suffix} · {status_label}{detail} · {task}"
226
- heading.label = f"{'▾' if self._expanded else '▸'} {self._heading}"
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()
227
250
  search = self.query_one(".subagent-search", Input)
228
251
  output = self.query_one(".subagent-output", Static)
229
252
  if search.value != self._search:
@@ -233,6 +256,12 @@ class SubagentCard(Vertical):
233
256
  if self._expanded:
234
257
  self._render_lines(search.value, output)
235
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
+
236
265
  def refresh_lines(self) -> None:
237
266
  """Refresh transcript text without resetting UI-local search state."""
238
267
  if not self.is_mounted:
@@ -252,13 +281,20 @@ class SubagentCard(Vertical):
252
281
  def on_mount(self) -> None:
253
282
  self.set_data(self._block)
254
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
+
255
291
  def on_button_pressed(self, event: Button.Pressed) -> None:
256
292
  if "subagent-heading" not in event.button.classes:
257
293
  return
258
294
  self._expanded = not self._expanded
259
295
  self._block["expanded"] = self._expanded
260
296
  heading = self.query_one(".subagent-heading", Button)
261
- heading.label = f"{'▾' if self._expanded else '▸'} {self._heading}"
297
+ heading.label = self.heading_label()
262
298
  search = self.query_one(".subagent-search", Input)
263
299
  output = self.query_one(".subagent-output", Static)
264
300
  search.display = self._expanded
@@ -30,6 +30,12 @@ from .ui import fmt_duration, tool_call_label, truncate
30
30
 
31
31
  _STATUS_DONE = "done"
32
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
+
33
39
 
34
40
  def screen_supported() -> bool:
35
41
  """The full-screen UI needs interactive input and output, never pipes
@@ -110,14 +116,27 @@ class TuiState:
110
116
  self.invalidate()
111
117
 
112
118
  def _subagent(self, instance: str, *, agent: str = "?",
113
- display: str = "", task: str = "") -> dict:
114
- """Return/create one delegation card, keyed by its unique instance."""
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
+ """
115
129
  key = str(instance or agent or "unknown")
116
- return self.subagents.setdefault(key, {
130
+ block = self.subagents.setdefault(key, {
117
131
  "instance": key, "agent": agent, "display": display or agent,
118
132
  "task": task, "status": "running", "steps": None,
119
133
  "changes": 0, "lines": [], "expanded": False, "search": "",
134
+ "in_feed": False,
120
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
121
140
 
122
141
  def add_subagent_line(self, instance: str, cls: str, text: str,
123
142
  **identity) -> None:
@@ -126,7 +145,14 @@ class TuiState:
126
145
  self.invalidate()
127
146
 
128
147
  def restore_subagents(self, rows: list[dict]) -> None:
129
- """Rebuild delegation cards from instance-tagged persisted messages."""
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
+ """
130
156
  self.subagents.clear()
131
157
  for row in rows:
132
158
  instance = str(row.get("subagent") or "")
@@ -146,8 +172,10 @@ class TuiState:
146
172
  task=str(task_info.get("task") or ""),
147
173
  ).update({k: task_info[k] for k in
148
174
  ("status", "steps", "changes") if k in task_info})
175
+ self.subagents[instance]["in_feed"] = True
149
176
  continue
150
177
  block = self._subagent(instance)
178
+ block["in_feed"] = True
151
179
  role = row.get("role")
152
180
  content = str(row.get("content") or "").strip()
153
181
  if role == "assistant":
@@ -314,6 +342,7 @@ class TuiState:
314
342
  instance, agent=str(ev.get("agent") or "?"),
315
343
  display=str(ev.get("display") or ""),
316
344
  task=str(ev.get("task") or ""),
345
+ marker=True,
317
346
  )
318
347
  block.update({"agent": str(ev.get("agent") or block["agent"]),
319
348
  "display": str(ev.get("display") or block["display"]),
@@ -324,6 +353,7 @@ class TuiState:
324
353
  block = self._subagent(
325
354
  instance, agent=str(ev.get("agent") or "?"),
326
355
  display=str(ev.get("display") or ""),
356
+ marker=True,
327
357
  )
328
358
  status = str(ev.get("status") or "")
329
359
  block.update(status=status or block["status"],
@@ -335,6 +365,7 @@ class TuiState:
335
365
  block = self._subagent(
336
366
  instance, agent=str(ev.get("agent") or "?"),
337
367
  display=str(ev.get("display") or ""),
368
+ marker=True,
338
369
  )
339
370
  inner = ev.get("event") or {}
340
371
  t = inner.get("type")
@@ -494,7 +525,8 @@ def feed_text(feed: list[tuple[str, str]], scope: str = "all",
494
525
  ``user`` the lines the user typed, ``tools`` the tool call/result
495
526
  lines, ``all`` the whole feed. ``extra`` is the text still streaming:
496
527
  it is not in the feed yet, which makes it *the* newest answer for
497
- ``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.
498
530
  """
499
531
  extra = str(extra or "").rstrip("\n")
500
532
  if scope == "last" and extra.strip():
@@ -506,7 +538,8 @@ def feed_text(feed: list[tuple[str, str]], scope: str = "all",
506
538
  elif scope == "last":
507
539
  lines = _last_answer(feed)
508
540
  else:
509
- lines = [text for _cls, text in feed]
541
+ lines = [text for cls, text in feed
542
+ if not cls.startswith(SUBAGENT_FEED_PREFIX)]
510
543
  text = "\n".join(lines).strip("\n")
511
544
  if extra and scope == "all":
512
545
  text = f"{text}\n{extra}".strip("\n")
@@ -534,14 +567,23 @@ def describe_copy(text: str) -> str:
534
567
 
535
568
 
536
569
  def transcript_feed_lines(rows):
537
- """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
+ """
538
577
  import json as _json
539
578
 
540
579
  out = []
580
+ seen_instances: set[str] = set()
541
581
  for m in rows:
542
- # Subagent transcripts are rendered in their instance cards, never
543
- # folded into the orchestrator's shared conversation stream.
544
- if m.get("subagent"):
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, ""))
545
587
  continue
546
588
  role = m.get("role")
547
589
  content = (m.get("content") or "").strip()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: lithe-cli
3
- Version: 0.1.7
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
 
@@ -279,6 +279,12 @@ def test_tui_folds_subagent_events():
279
279
  feed = "\n".join(text for _, text in state.feed)
280
280
  assert "委派 1 次" in feed and "子代理花费 $0.0100" in feed
281
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
282
288
 
283
289
 
284
290
  def test_tui_subagent_instances_and_history_restore():
@@ -396,11 +396,37 @@ async def _settle_bottom(pilot, conv):
396
396
  return
397
397
 
398
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
+
399
424
  def test_subagent_cards_mount_and_search_independently(tmp_path):
400
425
  async def scenario():
401
426
  app = _app(tmp_path, [])
402
427
  async with app.run_test() as pilot:
403
428
  state = app.state
429
+ state.say("user", "先调研再实现")
404
430
  state.on_event({"type": "subagent_start", "agent": "researcher",
405
431
  "display": "检索员", "task": "找 alpha",
406
432
  "instance": "researcher:a111"})
@@ -408,6 +434,7 @@ def test_subagent_cards_mount_and_search_independently(tmp_path):
408
434
  "display": "检索员", "instance": "researcher:a111",
409
435
  "event": {"type": "tool_result", "ok": True,
410
436
  "summary": "发现 alpha.txt"}})
437
+ state.say("dim", "调研完成,开始实现")
411
438
  state.on_event({"type": "subagent_start", "agent": "coder",
412
439
  "display": "编码员", "task": "实现 beta",
413
440
  "instance": "coder:b222"})
@@ -417,11 +444,24 @@ def test_subagent_cards_mount_and_search_independently(tmp_path):
417
444
  "summary": "修改 beta.py"}})
418
445
  app._sync_feed()
419
446
  await pilot.pause()
447
+ conv = app.query_one("#conv")
420
448
  cards = list(app.query(SubagentCard))
421
449
  assert len(cards) == 2
422
450
  assert {card.instance for card in cards} == {
423
451
  "researcher:a111", "coder:b222"
424
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
425
465
  card = next(c for c in cards if c.instance == "researcher:a111")
426
466
  card._expanded = True
427
467
  card.set_data(state.subagents[card.instance])
@@ -449,6 +489,10 @@ def test_resumed_session_mounts_persisted_subagent_cards(tmp_path):
449
489
  run_id = "persisted-subagent-run"
450
490
  wb.store.create_run(run_id, cfg.user_id, "检查项目",
451
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
+ ))
452
496
  wb.store.add_message(StoredMessage(
453
497
  role="user", content="检查 README", run_id=run_id,
454
498
  user_id=cfg.user_id, subagent="researcher:abcd",
@@ -460,6 +504,10 @@ def test_resumed_session_mounts_persisted_subagent_cards(tmp_path):
460
504
  role="assistant", content="README 包含使用说明", run_id=run_id,
461
505
  user_id=cfg.user_id, subagent="researcher:abcd",
462
506
  ))
507
+ wb.store.add_message(StoredMessage(
508
+ role="assistant", content="结论:README 已检查", run_id=run_id,
509
+ user_id=cfg.user_id,
510
+ ))
463
511
  app = LitheApp(cfg, None, "chat",
464
512
  args=SimpleNamespace(resume=str(cid), cont=False, title=None))
465
513
 
@@ -475,6 +523,15 @@ def test_resumed_session_mounts_persisted_subagent_cards(tmp_path):
475
523
  assert any("README 包含使用说明" in line
476
524
  for _cls, line in app.state.subagents[card.instance]["lines"])
477
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"
478
535
 
479
536
  asyncio.run(scenario())
480
537
 
@@ -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
File without changes