lithe-cli 0.1.7__tar.gz → 0.1.10__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.10}/PKG-INFO +2 -2
  2. {lithe_cli-0.1.7 → lithe_cli-0.1.10}/lithe_cli/__init__.py +1 -1
  3. {lithe_cli-0.1.7 → lithe_cli-0.1.10}/lithe_cli/agent.py +59 -5
  4. {lithe_cli-0.1.7 → lithe_cli-0.1.10}/lithe_cli/ttui.py +78 -63
  5. {lithe_cli-0.1.7 → lithe_cli-0.1.10}/lithe_cli/ttui_render.py +2 -1
  6. {lithe_cli-0.1.7 → lithe_cli-0.1.10}/lithe_cli/ttui_widgets.py +87 -16
  7. {lithe_cli-0.1.7 → lithe_cli-0.1.10}/lithe_cli/tui.py +52 -10
  8. {lithe_cli-0.1.7 → lithe_cli-0.1.10}/lithe_cli.egg-info/PKG-INFO +2 -2
  9. {lithe_cli-0.1.7 → lithe_cli-0.1.10}/lithe_cli.egg-info/requires.txt +1 -1
  10. {lithe_cli-0.1.7 → lithe_cli-0.1.10}/pyproject.toml +1 -1
  11. {lithe_cli-0.1.7 → lithe_cli-0.1.10}/tests/test_cli.py +23 -0
  12. {lithe_cli-0.1.7 → lithe_cli-0.1.10}/tests/test_cli_subagents.py +29 -0
  13. {lithe_cli-0.1.7 → lithe_cli-0.1.10}/tests/test_ttui.py +81 -1
  14. {lithe_cli-0.1.7 → lithe_cli-0.1.10}/tests/test_tui_v2.py +13 -0
  15. {lithe_cli-0.1.7 → lithe_cli-0.1.10}/LICENSE +0 -0
  16. {lithe_cli-0.1.7 → lithe_cli-0.1.10}/README.md +0 -0
  17. {lithe_cli-0.1.7 → lithe_cli-0.1.10}/lithe_cli/__main__.py +0 -0
  18. {lithe_cli-0.1.7 → lithe_cli-0.1.10}/lithe_cli/cli_parser.py +0 -0
  19. {lithe_cli-0.1.7 → lithe_cli-0.1.10}/lithe_cli/clipboard.py +0 -0
  20. {lithe_cli-0.1.7 → lithe_cli-0.1.10}/lithe_cli/commands.py +0 -0
  21. {lithe_cli-0.1.7 → lithe_cli-0.1.10}/lithe_cli/config.py +0 -0
  22. {lithe_cli-0.1.7 → lithe_cli-0.1.10}/lithe_cli/main.py +0 -0
  23. {lithe_cli-0.1.7 → lithe_cli-0.1.10}/lithe_cli/profiles.py +0 -0
  24. {lithe_cli-0.1.7 → lithe_cli-0.1.10}/lithe_cli/prompts.py +0 -0
  25. {lithe_cli-0.1.7 → lithe_cli-0.1.10}/lithe_cli/py.typed +0 -0
  26. {lithe_cli-0.1.7 → lithe_cli-0.1.10}/lithe_cli/sessions.py +0 -0
  27. {lithe_cli-0.1.7 → lithe_cli-0.1.10}/lithe_cli/setup.py +0 -0
  28. {lithe_cli-0.1.7 → lithe_cli-0.1.10}/lithe_cli/ui.py +0 -0
  29. {lithe_cli-0.1.7 → lithe_cli-0.1.10}/lithe_cli/workbench.py +0 -0
  30. {lithe_cli-0.1.7 → lithe_cli-0.1.10}/lithe_cli.egg-info/SOURCES.txt +0 -0
  31. {lithe_cli-0.1.7 → lithe_cli-0.1.10}/lithe_cli.egg-info/dependency_links.txt +0 -0
  32. {lithe_cli-0.1.7 → lithe_cli-0.1.10}/lithe_cli.egg-info/entry_points.txt +0 -0
  33. {lithe_cli-0.1.7 → lithe_cli-0.1.10}/lithe_cli.egg-info/top_level.txt +0 -0
  34. {lithe_cli-0.1.7 → lithe_cli-0.1.10}/setup.cfg +0 -0
  35. {lithe_cli-0.1.7 → lithe_cli-0.1.10}/tests/test_cli_budget_steer.py +0 -0
  36. {lithe_cli-0.1.7 → lithe_cli-0.1.10}/tests/test_cli_clipboard.py +0 -0
  37. {lithe_cli-0.1.7 → lithe_cli-0.1.10}/tests/test_cli_guard.py +0 -0
  38. {lithe_cli-0.1.7 → lithe_cli-0.1.10}/tests/test_cli_sessions.py +0 -0
  39. {lithe_cli-0.1.7 → lithe_cli-0.1.10}/tests/test_profiles.py +0 -0
  40. {lithe_cli-0.1.7 → lithe_cli-0.1.10}/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.10
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.5
42
+ Requires-Dist: lithe>=0.1.7
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.7"
3
+ __version__ = "0.1.10"
@@ -96,8 +96,55 @@ def sandbox_backend() -> str:
96
96
  return "bwrap" if shutil.which("bwrap") else "passthrough"
97
97
 
98
98
 
99
+ def environment_facts(cfg: Config) -> str:
100
+ """Env-fact lines for the system prompt (host, shell, workspace layout).
101
+
102
+ The layout line exists because the dominant first-hour failures in a
103
+ real delegation session were assumption mismatches, not tool bugs:
104
+ git run at a workspace root that is not a repo while the real repos
105
+ live in nested sub-directories, CI snippets with project-relative
106
+ paths, a husk ``.venv`` guessed usable. A few dozen tokens of facts
107
+ replace each of those wrong guesses (one failed round-trip apiece).
108
+ The ``run_command`` hint rides along only when the shell capability
109
+ is on, keeping the no-shell prompt free of the tool's name.
110
+ """
111
+ if sys.platform == "win32":
112
+ if shutil.which("pwsh"):
113
+ shell = "PowerShell 7+(pwsh)"
114
+ elif shutil.which("powershell"):
115
+ shell = "Windows PowerShell 5.1(无 &&,用 cmd1; if ($?) { cmd2 })"
116
+ else:
117
+ shell = "cmd"
118
+ facts = f"宿主环境:Windows,shell 为 {shell}。"
119
+ else:
120
+ facts = "宿主环境:Linux/macOS(POSIX shell)。"
121
+ root = cfg.workspace_dir.expanduser().resolve()
122
+ try:
123
+ entries = sorted(
124
+ (p for p in root.iterdir()
125
+ if p.is_dir() and not p.name.startswith(".")),
126
+ key=lambda p: p.name.lower())
127
+ except OSError:
128
+ return facts
129
+ names = [p.name for p in entries[:10]]
130
+ layout = "、".join(names) if names else "(空)"
131
+ if len(entries) > 10:
132
+ layout += f" 等 {len(entries)} 项"
133
+ line = (f"工作区 {root}("
134
+ f"{'是' if (root / '.git').exists() else '不是'} git 仓库)"
135
+ f"顶层目录:{layout}")
136
+ repos = [p.name for p in entries if (p / ".git").exists()]
137
+ if repos:
138
+ line += f";其中的独立 git 仓库:{'、'.join(repos)}"
139
+ if cfg.shell:
140
+ line += ("。对子项目执行命令用 run_command 的 cwd 参数指定目录"
141
+ "(区内自由、区外需用户审批),不要假设工作区根是仓库,"
142
+ "也不要在命令里拼接 cd")
143
+ return facts + "\n" + line
144
+
145
+
99
146
  def build_system_prompt(cfg: Config) -> str:
100
- """Base prompt plus one line per enabled capability."""
147
+ """Base prompt plus one line per enabled capability, then env facts."""
101
148
  extras = []
102
149
  if cfg.code:
103
150
  extras.append("可以用 run_code 执行 Python 来验证想法、计算或测试。")
@@ -114,8 +161,7 @@ def build_system_prompt(cfg: Config) -> str:
114
161
  extras.append("可以用 delegate 把独立子任务委派给子代理(可用名单见工具说明:检索/编码/操作),"
115
162
  "互不依赖的子任务用 delegate_parallel 并行委派;"
116
163
  "子代理与本对话共享预算,汇报时合并它们的结果。")
117
- if not extras:
118
- return SYSTEM_PROMPT_BASE
164
+ extras.append(environment_facts(cfg))
119
165
  return SYSTEM_PROMPT_BASE + "\n" + "\n".join(extras)
120
166
 
121
167
 
@@ -196,7 +242,8 @@ def build_registry(
196
242
  from lithe.bundles.command import CommandRunner
197
243
 
198
244
  register_command_tools(
199
- reg, lambda ctx: cfg.workspace_dir.resolve(), CommandRunner()
245
+ reg, lambda ctx: cfg.workspace_dir.resolve(), CommandRunner(),
246
+ approver=approver,
200
247
  )
201
248
  # Dangerous-command guard: catastrophic commands never run; the
202
249
  # destructive-but-scoped tier (rm -r <path>, git push --force,
@@ -328,7 +375,14 @@ def register_subagents(cfg: Config, host: AgentHost, reg: ToolRegistry,
328
375
  else:
329
376
  render_event(enriched)
330
377
 
331
- engine = SubagentEngine(host, roster, on_subagent_event=forward_progress)
378
+ engine = SubagentEngine(
379
+ host, roster, on_subagent_event=forward_progress,
380
+ # Subagents do not inherit the orchestrator's system prompt — the
381
+ # roster's spec prompts are all they see. Prepending the same env
382
+ # facts (platform, shell, nested-repo layout) keeps the operator
383
+ # from re-learning the workspace layout by failed guesses.
384
+ prompt_builder=lambda spec, ctx: f"{environment_facts(cfg)}\n\n{spec.prompt}",
385
+ )
332
386
  register_delegate_tools(reg, engine, parallel=True)
333
387
  return engine
334
388
 
@@ -30,13 +30,14 @@ from typing import Any
30
30
  from textual.app import App, ComposeResult
31
31
  from textual.binding import Binding
32
32
  from textual.containers import Horizontal, Vertical, VerticalScroll
33
- from textual.widgets import Input, Static
33
+ from textual.widgets import Static, TextArea
34
34
 
35
35
  from .clipboard import deliver_clipboard, write_clipboard_file
36
36
  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,
@@ -46,7 +47,7 @@ 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
49
  ConfirmModal, ConversationPane, HistoryInput, PickerModal, SubagentCard,
49
- WbEvent, completion_suggestions, selected_text,
50
+ HistoryInputSubmitted, WbEvent, completion_suggestions, selected_text,
50
51
  )
51
52
  from .ttui_render import footer_text, header_text, sidebar_markup
52
53
 
@@ -60,13 +61,17 @@ 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
- #prompt { border: round #475569; }
74
+ #prompt { height: auto; max-height: 8; border: round #475569; }
70
75
  #foot { height: 1; background: #111827; color: #cbd5e1; }
71
76
  #picker { width: 60%; height: auto; max-height: 80%;
72
77
  border: round #38bdf8; background: $surface; padding: 1 2; }
@@ -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(
@@ -161,13 +162,13 @@ class LitheApp(App):
161
162
  )
162
163
  self._sync_feed()
163
164
  self._refresh_chrome()
164
- self.query_one("#prompt", Input).focus()
165
+ self.query_one("#prompt", HistoryInput).focus()
165
166
  # Live turn timer: kernel events alone leave the screen static
166
167
  # during long model calls, so the chrome repaints on a heartbeat
167
168
  # while a turn runs (elapsed comes from TuiState.elapsed()).
168
169
  self.set_interval(0.5, self._tick_elapsed)
169
170
  if self.mode == "run" and self.initial_task:
170
- self.query_one("#prompt", Input).disabled = True
171
+ self.query_one("#prompt", HistoryInput).disabled = True
171
172
  asyncio.create_task(self._run_one_shot(self.initial_task))
172
173
 
173
174
  # -- state management --------------------------------------------------------
@@ -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
@@ -404,29 +417,31 @@ class LitheApp(App):
404
417
 
405
418
  # -- input -------------------------------------------------------------------
406
419
 
407
- def on_input_changed(self, event: Input.Changed) -> None:
408
- if event.input.id != "prompt":
420
+ def on_text_area_changed(self, event: TextArea.Changed) -> None:
421
+ if event.text_area.id != "prompt":
409
422
  return
410
423
  from .commands import COMMANDS
411
424
 
412
425
  prompt = self.query_one("#prompt", HistoryInput)
413
- prompt.suggestion = completion_suggestions(
414
- event.value,
426
+ prompt.completions = completion_suggestions(
427
+ event.text_area.text,
415
428
  COMMANDS,
416
429
  self.state.model_candidates,
417
430
  self.state.profile_names,
418
431
  [f"#{row['id']}" for row in self.state.sessions],
419
432
  )
420
433
  strip = self.query_one("#suggest", Static)
421
- if prompt.suggestion:
434
+ if prompt.completions:
422
435
  strip.update("[dim]Tab 采纳 →[/] " +
423
- " ".join(prompt.suggestion[:4]))
436
+ " ".join(prompt.completions[:4]))
424
437
  strip.display = True
425
438
  else:
426
439
  strip.update("")
427
440
  strip.display = False
428
441
 
429
- async def on_input_submitted(self, event: Input.Submitted) -> None:
442
+ async def on_history_input_submitted(
443
+ self, event: HistoryInputSubmitted,
444
+ ) -> None:
430
445
  if event.input.id != "prompt":
431
446
  return
432
447
  line = event.value.strip()
@@ -701,7 +716,7 @@ class LitheApp(App):
701
716
  self._activate(self.wb.current["id"])
702
717
 
703
718
  def _picker_rename(self, payload) -> None:
704
- prompt = self.query_one("#prompt", Input)
719
+ prompt = self.query_one("#prompt", HistoryInput)
705
720
  prompt.value = "/rename "
706
721
  prompt.focus()
707
722
 
@@ -878,7 +893,7 @@ class LitheApp(App):
878
893
  self._cancel_asked = False
879
894
  self._sync_feed()
880
895
  self._refresh_chrome()
881
- self.query_one("#prompt", Input).disabled = False
896
+ self.query_one("#prompt", HistoryInput).disabled = False
882
897
 
883
898
 
884
899
  async def _driver(app: LitheApp) -> int:
@@ -118,5 +118,6 @@ def footer_text(state: TuiState) -> str:
118
118
  timer = f" · {fmt_duration(live)}" if live is not None else ""
119
119
  return (f" ● {state.status}{timer} · Ctrl+C 取消 · F3 会话"
120
120
  f" · F4 模型 · F6 推理 ")
121
- return (f" ● {state.status} · Enter 发送 · F2 侧栏 · F3 会话 · F4 模型"
121
+ return (f" ● {state.status} · Enter 发送 · Ctrl+Enter 换行 · F2 侧栏"
122
+ f" · F3 会话 · F4 模型"
122
123
  f" · F5 设置 · F6 推理 · /help ")
@@ -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 Button, Input, Label, ListItem, ListView, Static
15
+ from textual.widgets import Button, Input, Label, ListItem, ListView, Static, TextArea
16
+
17
+ from .ui import display_width, truncate
13
18
 
14
19
  # -- input: completion + persistent history ------------------------------------
15
20
 
@@ -26,7 +31,7 @@ def completion_suggestions(
26
31
  complete their first argument (cached models, saved profiles, session
27
32
  ids). Empty result hides the suggestion strip.
28
33
  """
29
- if not value.startswith("/"):
34
+ if "\n" in value or not value.startswith("/"):
30
35
  return []
31
36
  if " " not in value:
32
37
  prefix = value.rstrip()
@@ -47,14 +52,17 @@ def completion_suggestions(
47
52
  return [w for w in words if w.startswith(arg) and w != arg][:6]
48
53
 
49
54
 
50
- class HistoryInput(Input):
51
- """Input with ↑/↓ recall over a persistent FileHistory store."""
55
+ class HistoryInput(TextArea):
56
+ """Multiline prompt with history recall and persistent FileHistory."""
52
57
 
53
58
  BINDINGS = [
54
59
  Binding("up", "history_prev", "上一条", show=False, priority=True),
55
60
  Binding("down", "history_next", "下一条", show=False, priority=True),
56
61
  Binding("tab", "accept_suggestion", "采纳", show=False,
57
62
  priority=True),
63
+ Binding("enter", "submit", "发送", show=False, priority=True),
64
+ Binding("ctrl+enter", "insert_newline", "换行", show=False,
65
+ priority=True),
58
66
  ]
59
67
 
60
68
  def __init__(self, *args, file_history=None, **kwargs):
@@ -63,9 +71,24 @@ class HistoryInput(Input):
63
71
  self._lines: list[str] = []
64
72
  self._pos: int | None = None
65
73
  self._draft = ""
66
- self.suggestion: list[str] = []
74
+ self.completions: list[str] = []
67
75
  self.reload_history()
68
76
 
77
+ @property
78
+ def value(self) -> str:
79
+ """Input-compatible alias used by the workbench and UI code."""
80
+ return self.text
81
+
82
+ @value.setter
83
+ def value(self, text: str) -> None:
84
+ self.text = text
85
+
86
+ def action_submit(self) -> None:
87
+ self.post_message(HistoryInputSubmitted(self, self.text))
88
+
89
+ def action_insert_newline(self) -> None:
90
+ self.insert("\n")
91
+
69
92
  def reload_history(self) -> None:
70
93
  self._lines = []
71
94
  if self.file_history is not None:
@@ -77,8 +100,7 @@ class HistoryInput(Input):
77
100
  self._draft = ""
78
101
 
79
102
  def record(self, line: str) -> None:
80
- line = line.strip()
81
- if not line:
103
+ if not line.strip():
82
104
  return
83
105
  if not self._lines or self._lines[-1] != line:
84
106
  self._lines.append(line)
@@ -93,9 +115,15 @@ class HistoryInput(Input):
93
115
  def _apply(self, text: str, pos: int | None) -> None:
94
116
  self._pos = pos
95
117
  self.value = text
96
- self.cursor_position = len(text)
118
+ lines = text.split("\n")
119
+ self.move_cursor((len(lines) - 1, len(lines[-1])))
97
120
 
98
121
  def action_history_prev(self) -> None:
122
+ # Keep normal vertical editing inside a multiline draft; history is
123
+ # recalled only when the cursor is already on its first line.
124
+ if self.cursor_location[0] > 0:
125
+ self.action_cursor_up()
126
+ return
99
127
  if not self._lines:
100
128
  return
101
129
  if self._pos is None:
@@ -105,6 +133,9 @@ class HistoryInput(Input):
105
133
  self._apply(self._lines[self._pos - 1], self._pos - 1)
106
134
 
107
135
  def action_history_next(self) -> None:
136
+ if self.cursor_location[0] < len(self.text.split("\n")) - 1:
137
+ self.action_cursor_down()
138
+ return
108
139
  if self._pos is None:
109
140
  return
110
141
  if self._pos < len(self._lines) - 1:
@@ -113,11 +144,20 @@ class HistoryInput(Input):
113
144
  self._apply(self._draft, None)
114
145
 
115
146
  def action_accept_suggestion(self) -> None:
116
- if self.suggestion:
117
- accepted = self.suggestion[0]
147
+ if self.completions:
148
+ accepted = self.completions[0]
118
149
  self.value = accepted
119
- self.cursor_position = len(accepted)
120
- self.suggestion = []
150
+ self.move_cursor((0, len(accepted)))
151
+ self.completions = []
152
+
153
+
154
+ class HistoryInputSubmitted(Message):
155
+ """A multiline prompt submission, kept separate from TextArea.Changed."""
156
+
157
+ def __init__(self, input: HistoryInput, value: str) -> None:
158
+ super().__init__()
159
+ self.input = input
160
+ self.value = value
121
161
 
122
162
 
123
163
  # -- workbench → app message ----------------------------------------------------
@@ -207,6 +247,14 @@ class SubagentCard(Vertical):
207
247
 
208
248
  def set_data(self, block: dict) -> None:
209
249
  self.update_data(block)
250
+ try:
251
+ heading = self.query_one(".subagent-heading", Button)
252
+ except NoMatches:
253
+ # The card sits in its parent's children but its compose()
254
+ # children are not mounted yet — a sibling subagent's event
255
+ # syncing this card inside that window hit here. The data is
256
+ # already stored; on_mount re-renders once the card is live.
257
+ return
210
258
  display = str(block.get("display") or block.get("agent") or "子代理")
211
259
  suffix = str(block.get("instance") or "").rsplit(":", 1)[-1][:4]
212
260
  task = str(block.get("task") or "(任务描述载入中)").replace("\n", " ")
@@ -215,15 +263,25 @@ class SubagentCard(Vertical):
215
263
  "running": "运行中", "done": "完成", "max_steps": "步数上限",
216
264
  "failed": "失败", "cancelled": "已取消", "budget_exceeded": "预算超限",
217
265
  }.get(status, status)
266
+ status_mark = {
267
+ "running": "●", "done": "✓", "failed": "✗", "cancelled": "○",
268
+ }.get(status, "·")
218
269
  details = []
219
270
  if block.get("steps") is not None:
220
271
  details.append(f"{block['steps']} 步")
221
272
  if block.get("changes"):
222
273
  details.append(f"{block['changes']} 处改动")
223
274
  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}"
275
+ # One collapsed line: identity + status, then the task squeezed into
276
+ # whatever width remains. The budget is measured on the heading
277
+ # button itself (the card's rail and padding shrink it) and covers
278
+ # the arrow prefix, the button's pad and the " · " join, so the
279
+ # ellipsis — not the pane — ends the line.
280
+ head = f"{status_mark} {display}·{suffix} · {status_label}{detail}"
281
+ width = heading.content_size.width or self.content_size.width or 64
282
+ self._heading = \
283
+ f"{head} · {truncate(task, max(4, width - display_width(head) - 8))}"
284
+ heading.label = self.heading_label()
227
285
  search = self.query_one(".subagent-search", Input)
228
286
  output = self.query_one(".subagent-output", Static)
229
287
  if search.value != self._search:
@@ -233,6 +291,12 @@ class SubagentCard(Vertical):
233
291
  if self._expanded:
234
292
  self._render_lines(search.value, output)
235
293
 
294
+ def heading_label(self) -> Content:
295
+ """The heading as verbatim content — task text is model data, and
296
+ Button labels parse square-bracket markup (``[/]`` would raise)."""
297
+ arrow = "▾" if self._expanded else "▸"
298
+ return Content.from_rich_text(Text(f"{arrow} {self._heading}"))
299
+
236
300
  def refresh_lines(self) -> None:
237
301
  """Refresh transcript text without resetting UI-local search state."""
238
302
  if not self.is_mounted:
@@ -252,13 +316,20 @@ class SubagentCard(Vertical):
252
316
  def on_mount(self) -> None:
253
317
  self.set_data(self._block)
254
318
 
319
+ def on_resize(self) -> None:
320
+ """The one-line heading truncates to the laid-out width, which is
321
+ still 0 at mount time — re-render once the card has its real size
322
+ (and again if the terminal is resized)."""
323
+ if self._block:
324
+ self.set_data(self._block)
325
+
255
326
  def on_button_pressed(self, event: Button.Pressed) -> None:
256
327
  if "subagent-heading" not in event.button.classes:
257
328
  return
258
329
  self._expanded = not self._expanded
259
330
  self._block["expanded"] = self._expanded
260
331
  heading = self.query_one(".subagent-heading", Button)
261
- heading.label = f"{'▾' if self._expanded else '▸'} {self._heading}"
332
+ heading.label = self.heading_label()
262
333
  search = self.query_one(".subagent-search", Input)
263
334
  output = self.query_one(".subagent-output", Static)
264
335
  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.10
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.5
42
+ Requires-Dist: lithe>=0.1.7
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.5
1
+ lithe>=0.1.7
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.5", "prompt-toolkit>=3.0.38", "textual>=1.0"]
12
+ dependencies = ["lithe>=0.1.7", "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",
@@ -552,6 +552,29 @@ def test_system_prompt_puts_each_capability_on_its_own_line():
552
552
  assert "\n可以用 run_command" in prompt
553
553
 
554
554
 
555
+ def test_system_prompt_carries_environment_facts(tmp_path):
556
+ from lithe_cli.agent import build_system_prompt
557
+ from lithe_cli.config import Config
558
+
559
+ (tmp_path / "lithe").mkdir()
560
+ (tmp_path / "lithe" / ".git").mkdir()
561
+ (tmp_path / "notes").mkdir()
562
+ cfg = Config(workspace_dir=tmp_path)
563
+ prompt = build_system_prompt(cfg)
564
+ assert "宿主环境" in prompt
565
+ assert "不是 git 仓库" in prompt
566
+ assert "lithe" in prompt and "notes" in prompt
567
+ assert "独立 git 仓库:lithe" in prompt
568
+ # the run_command cwd hint rides along only with the shell capability
569
+ assert "run_command" not in prompt
570
+ shell_on = build_system_prompt(Config(workspace_dir=tmp_path, shell=True))
571
+ assert "cwd 参数" in shell_on
572
+
573
+ # a root-level repo flips the layout verdict
574
+ (tmp_path / ".git").mkdir()
575
+ assert "是 git 仓库" in build_system_prompt(Config(workspace_dir=tmp_path))
576
+
577
+
555
578
  def test_todo_storage_is_scoped_to_user_and_workspace(tmp_path):
556
579
  from lithe_cli.agent import todo_store_path
557
580
  from lithe_cli.config import Config
@@ -133,6 +133,29 @@ def test_roster_adapts_to_capability_flags(tmp_path):
133
133
  assert "run_command" in op_names
134
134
 
135
135
 
136
+ def test_subagent_prompt_prepends_environment_facts(tmp_path):
137
+ """Subagents never see the orchestrator's system prompt — without the
138
+ facts prepended they re-learn the workspace layout (nested repos,
139
+ platform) by failed guesses, which is what this fixes."""
140
+ from lithe import AgentContext
141
+
142
+ cfg = make_config(tmp_path, [])
143
+ cfg.subagents = True
144
+ cfg.shell = True
145
+ cfg.workspace_dir.mkdir(parents=True, exist_ok=True)
146
+ (cfg.workspace_dir / "svc").mkdir()
147
+ (cfg.workspace_dir / "svc" / ".git").mkdir()
148
+ reg = build_registry(cfg)
149
+ host = build_host(cfg, reg)
150
+ engine = register_subagents(cfg, host, reg)
151
+ prompt = engine.system_prompt(
152
+ engine.roster.get("researcher"), AgentContext(run_id="r", user_id="u"))
153
+ assert "宿主环境" in prompt
154
+ assert "独立 git 仓库:svc" in prompt
155
+ # the spec's own persona is intact after the prepended facts
156
+ assert "只读检索子代理" in prompt
157
+
158
+
136
159
  def test_set_subagents_toggles_and_warns(tmp_path):
137
160
  cfg = make_config(tmp_path, [])
138
161
  assert cfg.subagents is True # default-on since the roster adds no powers
@@ -279,6 +302,12 @@ def test_tui_folds_subagent_events():
279
302
  feed = "\n".join(text for _, text in state.feed)
280
303
  assert "委派 1 次" in feed and "子代理花费 $0.0100" in feed
281
304
  assert not any("检索员" in text for _, text in state.feed)
305
+ # the live start dropped one position marker into the feed — the pane
306
+ # mounts the card there, in the conversation's scroll flow
307
+ from lithe_cli.tui import SUBAGENT_FEED_PREFIX
308
+
309
+ assert (SUBAGENT_FEED_PREFIX + "researcher:a111", "") in state.feed
310
+ assert block["in_feed"] is True
282
311
 
283
312
 
284
313
  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,11 +504,18 @@ 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
 
466
514
  async def scenario():
467
- async with app.run_test() as pilot:
515
+ # wide terminal: the one-line heading truncates the task to the
516
+ # pane width, so give it room to show "检查 README" in full on
517
+ # every runner (the assertion would be width-dependent otherwise)
518
+ async with app.run_test(size=(120, 30)) as pilot:
468
519
  await pilot.pause()
469
520
  cards = list(app.query(SubagentCard))
470
521
  assert len(cards) == 1
@@ -475,6 +526,15 @@ def test_resumed_session_mounts_persisted_subagent_cards(tmp_path):
475
526
  assert any("README 包含使用说明" in line
476
527
  for _cls, line in app.state.subagents[card.instance]["lines"])
477
528
  assert not any("检查 README" in line for _cls, line in app.state.feed)
529
+ # The card mounts where the delegation sat in the stored
530
+ # transcript — between the orchestrator's own rows, not
531
+ # appended after them.
532
+ conv = app.query_one("#conv")
533
+ order = [type(c).__name__ for c in conv.children
534
+ if c.id != "streaming"]
535
+ pos = order.index("SubagentCard")
536
+ assert 0 < pos < len(order) - 1
537
+ assert order[pos - 1] == order[pos + 1] == "Static"
478
538
 
479
539
  asyncio.run(scenario())
480
540
 
@@ -573,6 +633,26 @@ def test_app_completion_strip_and_history_recall(tmp_path, monkeypatch):
573
633
  asyncio.run(scenario())
574
634
 
575
635
 
636
+ def test_prompt_submits_multiline_text_and_ctrl_enter_inserts_newline(tmp_path):
637
+ async def scenario():
638
+ app = _app(tmp_path, [{"content": "收到完整内容"}])
639
+ async with app.run_test(size=(100, 30)) as pilot:
640
+ await pilot.pause()
641
+ prompt = app.query_one("#prompt")
642
+ prompt.focus()
643
+
644
+ await pilot.press("a", "ctrl+enter", "b")
645
+ await pilot.pause()
646
+ assert prompt.text == "a\nb"
647
+
648
+ await pilot.press("enter")
649
+ assert await _run_until_done(pilot, app), "multiline turn did not finish"
650
+ assert "a\nb" in _conv_text(app)
651
+ assert "收到完整内容" in _conv_text(app)
652
+
653
+ asyncio.run(scenario())
654
+
655
+
576
656
  def test_history_persists_across_processes(tmp_path, monkeypatch):
577
657
  monkeypatch.setenv("LITHE_HOME", str(tmp_path / "home"))
578
658
 
@@ -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