lithe-cli 0.1.3__tar.gz → 0.1.4__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 (38) hide show
  1. {lithe_cli-0.1.3 → lithe_cli-0.1.4}/PKG-INFO +1 -1
  2. {lithe_cli-0.1.3 → lithe_cli-0.1.4}/lithe_cli/__init__.py +1 -1
  3. {lithe_cli-0.1.3 → lithe_cli-0.1.4}/lithe_cli/agent.py +16 -6
  4. {lithe_cli-0.1.3 → lithe_cli-0.1.4}/lithe_cli/ttui.py +43 -285
  5. lithe_cli-0.1.4/lithe_cli/ttui_widgets.py +287 -0
  6. {lithe_cli-0.1.3 → lithe_cli-0.1.4}/lithe_cli/workbench.py +2 -1
  7. {lithe_cli-0.1.3 → lithe_cli-0.1.4}/lithe_cli.egg-info/PKG-INFO +1 -1
  8. {lithe_cli-0.1.3 → lithe_cli-0.1.4}/lithe_cli.egg-info/SOURCES.txt +1 -0
  9. {lithe_cli-0.1.3 → lithe_cli-0.1.4}/tests/test_cli.py +58 -0
  10. {lithe_cli-0.1.3 → lithe_cli-0.1.4}/tests/test_ttui.py +56 -0
  11. {lithe_cli-0.1.3 → lithe_cli-0.1.4}/LICENSE +0 -0
  12. {lithe_cli-0.1.3 → lithe_cli-0.1.4}/README.md +0 -0
  13. {lithe_cli-0.1.3 → lithe_cli-0.1.4}/lithe_cli/__main__.py +0 -0
  14. {lithe_cli-0.1.3 → lithe_cli-0.1.4}/lithe_cli/clipboard.py +0 -0
  15. {lithe_cli-0.1.3 → lithe_cli-0.1.4}/lithe_cli/commands.py +0 -0
  16. {lithe_cli-0.1.3 → lithe_cli-0.1.4}/lithe_cli/config.py +0 -0
  17. {lithe_cli-0.1.3 → lithe_cli-0.1.4}/lithe_cli/main.py +0 -0
  18. {lithe_cli-0.1.3 → lithe_cli-0.1.4}/lithe_cli/profiles.py +0 -0
  19. {lithe_cli-0.1.3 → lithe_cli-0.1.4}/lithe_cli/prompts.py +0 -0
  20. {lithe_cli-0.1.3 → lithe_cli-0.1.4}/lithe_cli/py.typed +0 -0
  21. {lithe_cli-0.1.3 → lithe_cli-0.1.4}/lithe_cli/sessions.py +0 -0
  22. {lithe_cli-0.1.3 → lithe_cli-0.1.4}/lithe_cli/setup.py +0 -0
  23. {lithe_cli-0.1.3 → lithe_cli-0.1.4}/lithe_cli/tui.py +0 -0
  24. {lithe_cli-0.1.3 → lithe_cli-0.1.4}/lithe_cli/ui.py +0 -0
  25. {lithe_cli-0.1.3 → lithe_cli-0.1.4}/lithe_cli.egg-info/dependency_links.txt +0 -0
  26. {lithe_cli-0.1.3 → lithe_cli-0.1.4}/lithe_cli.egg-info/entry_points.txt +0 -0
  27. {lithe_cli-0.1.3 → lithe_cli-0.1.4}/lithe_cli.egg-info/requires.txt +0 -0
  28. {lithe_cli-0.1.3 → lithe_cli-0.1.4}/lithe_cli.egg-info/top_level.txt +0 -0
  29. {lithe_cli-0.1.3 → lithe_cli-0.1.4}/pyproject.toml +0 -0
  30. {lithe_cli-0.1.3 → lithe_cli-0.1.4}/setup.cfg +0 -0
  31. {lithe_cli-0.1.3 → lithe_cli-0.1.4}/tests/test_cli_budget_steer.py +0 -0
  32. {lithe_cli-0.1.3 → lithe_cli-0.1.4}/tests/test_cli_clipboard.py +0 -0
  33. {lithe_cli-0.1.3 → lithe_cli-0.1.4}/tests/test_cli_guard.py +0 -0
  34. {lithe_cli-0.1.3 → lithe_cli-0.1.4}/tests/test_cli_sessions.py +0 -0
  35. {lithe_cli-0.1.3 → lithe_cli-0.1.4}/tests/test_cli_subagents.py +0 -0
  36. {lithe_cli-0.1.3 → lithe_cli-0.1.4}/tests/test_profiles.py +0 -0
  37. {lithe_cli-0.1.3 → lithe_cli-0.1.4}/tests/test_tui_v2.py +0 -0
  38. {lithe_cli-0.1.3 → lithe_cli-0.1.4}/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.3
3
+ Version: 0.1.4
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.3"
3
+ __version__ = "0.1.4"
@@ -75,10 +75,14 @@ SYSTEM_PROMPT_BASE = (
75
75
  )
76
76
 
77
77
 
78
- def todo_store_path(cfg: Config) -> Path:
78
+ def todo_store_path(cfg: Config, conversation_id: int | None = None) -> Path:
79
+ """Path for one conversation's task list (None is the non-session scope)."""
79
80
  workspace = str(cfg.workspace_dir.expanduser().resolve())
81
+ scope_data = {"user_id": str(cfg.user_id), "workspace": workspace}
82
+ if conversation_id is not None:
83
+ scope_data["conversation_id"] = conversation_id
80
84
  scope = json.dumps(
81
- {"user_id": str(cfg.user_id), "workspace": workspace},
85
+ scope_data,
82
86
  ensure_ascii=False,
83
87
  sort_keys=True,
84
88
  separators=(",", ":"),
@@ -159,7 +163,11 @@ def build_llm(cfg: Config) -> LLMConfig:
159
163
  return LLMConfig(**overrides)
160
164
 
161
165
 
162
- def build_registry(cfg: Config, approver: Callable[[str], Awaitable[bool]] | None = None) -> ToolRegistry:
166
+ def build_registry(
167
+ cfg: Config,
168
+ approver: Callable[[str], Awaitable[bool]] | None = None,
169
+ conversation_id: int | None = None,
170
+ ) -> ToolRegistry:
163
171
  """Register the CLI's tool set against the configured workspace.
164
172
 
165
173
  ``approver`` is the human-confirmation channel for destructive
@@ -173,7 +181,7 @@ def build_registry(cfg: Config, approver: Callable[[str], Awaitable[bool]] | Non
173
181
 
174
182
  register_file_tools(reg, workspace_for)
175
183
  register_apply_patch_tool(reg, workspace_for)
176
- todo_store = JsonTodoStore(todo_store_path(cfg))
184
+ todo_store = JsonTodoStore(todo_store_path(cfg, conversation_id))
177
185
  register_todo_tools(reg, lambda ctx: todo_store)
178
186
  if cfg.download:
179
187
  register_download_tools(reg, workspace_for)
@@ -517,7 +525,7 @@ async def execute(
517
525
  the steering channel: a queue of user texts the kernel drains at step
518
526
  boundaries and injects as user messages (see AgentRuntime.run).
519
527
  """
520
- reg = build_registry(cfg, approver)
528
+ reg = build_registry(cfg, approver, conversation_id=conversation_id)
521
529
  host = build_host(cfg, reg)
522
530
  if cfg.subagents:
523
531
  register_subagents(cfg, host, reg, on_event=on_event)
@@ -560,7 +568,9 @@ async def execute(
560
568
 
561
569
  async def undo(cfg: Config, run_id: str, quiet: bool = False) -> int:
562
570
  """Revert a run's mutations; returns how many actions were reverted."""
563
- reg = build_registry(cfg)
571
+ run = JsonlRunStore(cfg.store_dir).get_run(run_id, cfg.user_id)
572
+ conversation_id = run.conversation_id if run is not None else None
573
+ reg = build_registry(cfg, conversation_id=conversation_id)
564
574
  host = build_host(cfg, reg)
565
575
  report = await undo_run(host, run_id, cfg.user_id)
566
576
  if not quiet:
@@ -24,15 +24,13 @@ Shift+drag still works in terminals that keep native selection.
24
24
  from __future__ import annotations
25
25
 
26
26
  import asyncio
27
- from collections.abc import Callable
27
+
28
28
  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, Vertical, VerticalScroll
33
- from textual.message import Message
34
- from textual.screen import ModalScreen
35
- from textual.widgets import Input, Label, ListItem, ListView, Static
32
+ from textual.containers import Horizontal, VerticalScroll
33
+ from textual.widgets import Input, Static
36
34
 
37
35
  from .clipboard import deliver_clipboard, write_clipboard_file
38
36
  from .config import lithe_home
@@ -45,6 +43,11 @@ from .tui import (
45
43
  transcript_feed_lines,
46
44
  )
47
45
  from .ui import fmt_duration
46
+ from . import ttui_widgets as _widgets
47
+ from .ttui_widgets import (
48
+ ConfirmModal, ConversationPane, HistoryInput, PickerModal, WbEvent,
49
+ completion_suggestions, selected_text,
50
+ )
48
51
 
49
52
  _MAX_FEED = 400 # mounted conversation lines before trimming the oldest
50
53
 
@@ -162,278 +165,6 @@ def footer_text(state: TuiState) -> str:
162
165
  f" · F5 设置 · F6 推理 · /help ")
163
166
 
164
167
 
165
- # -- input: completion + persistent history ------------------------------------
166
-
167
- def completion_suggestions(
168
- value: str,
169
- commands: dict,
170
- models: list[str],
171
- profiles: list[str],
172
- session_ids: list[str],
173
- ) -> list[str]:
174
- """Suggest completions for a half-typed input line (pure; tested).
175
-
176
- ``/prefix`` completes command names; ``/model | /profile | /resume``
177
- complete their first argument (cached models, saved profiles, session
178
- ids). Empty result hides the suggestion strip.
179
- """
180
- if not value.startswith("/"):
181
- return []
182
- if " " not in value:
183
- prefix = value.rstrip()
184
- return [
185
- f"/{name} "
186
- for name in sorted(commands)
187
- if prefix == "/" or f"/{name}".startswith(prefix)
188
- ][:6]
189
- head, _, arg = value.partition(" ")
190
- command = head[1:].lower()
191
- words: list[str] = []
192
- if command == "model":
193
- words = models
194
- elif command == "profile":
195
- words = profiles
196
- elif command == "resume":
197
- words = session_ids
198
- return [w for w in words if w.startswith(arg) and w != arg][:6]
199
-
200
-
201
- class HistoryInput(Input):
202
- """Input with ↑/↓ recall over a persistent FileHistory store."""
203
-
204
- BINDINGS = [
205
- Binding("up", "history_prev", "上一条", show=False, priority=True),
206
- Binding("down", "history_next", "下一条", show=False, priority=True),
207
- Binding("tab", "accept_suggestion", "采纳", show=False,
208
- priority=True),
209
- ]
210
-
211
- def __init__(self, *args, file_history=None, **kwargs):
212
- super().__init__(*args, **kwargs)
213
- self.file_history = file_history
214
- self._lines: list[str] = []
215
- self._pos: int | None = None
216
- self._draft = ""
217
- self.suggestion: list[str] = []
218
- self.reload_history()
219
-
220
- def reload_history(self) -> None:
221
- self._lines = []
222
- if self.file_history is not None:
223
- try:
224
- self._lines = list(self.file_history.load_history_strings())
225
- except OSError:
226
- self._lines = []
227
- self._pos = None
228
- self._draft = ""
229
-
230
- def record(self, line: str) -> None:
231
- line = line.strip()
232
- if not line:
233
- return
234
- if not self._lines or self._lines[-1] != line:
235
- self._lines.append(line)
236
- if self.file_history is not None:
237
- try:
238
- self.file_history.store_string(line)
239
- except OSError:
240
- pass
241
- self._pos = None
242
- self._draft = ""
243
-
244
- def _apply(self, text: str, pos: int | None) -> None:
245
- self._pos = pos
246
- self.value = text
247
- self.cursor_position = len(text)
248
-
249
- def action_history_prev(self) -> None:
250
- if not self._lines:
251
- return
252
- if self._pos is None:
253
- self._draft = self.value
254
- self._apply(self._lines[-1], len(self._lines) - 1)
255
- elif self._pos > 0:
256
- self._apply(self._lines[self._pos - 1], self._pos - 1)
257
-
258
- def action_history_next(self) -> None:
259
- if self._pos is None:
260
- return
261
- if self._pos < len(self._lines) - 1:
262
- self._apply(self._lines[self._pos + 1], self._pos + 1)
263
- else:
264
- self._apply(self._draft, None)
265
-
266
- def action_accept_suggestion(self) -> None:
267
- if self.suggestion:
268
- accepted = self.suggestion[0]
269
- self.value = accepted
270
- self.cursor_position = len(accepted)
271
- self.suggestion = []
272
-
273
-
274
- # -- workbench → app message ----------------------------------------------------
275
-
276
- class WbEvent(Message):
277
- """One Workbench event, marshalled into the UI message pump."""
278
-
279
- def __init__(self, cid: int, ev: dict) -> None:
280
- super().__init__()
281
- self.cid = cid
282
- self.ev = ev
283
-
284
-
285
- # -- clipboard hooks -------------------------------------------------------------
286
-
287
- def selected_text(screen: Any, app: Any = None) -> str:
288
- """The current Textual text selection, if this release has one.
289
-
290
- The selection API moved names between Textual releases (and is absent
291
- in the headless test driver), so every candidate is probed and a miss
292
- simply means "no selection" — callers keep their old behaviour.
293
- """
294
- for holder in (screen, app):
295
- if holder is None:
296
- continue
297
- getter = getattr(holder, "get_selected_text", None)
298
- if not callable(getter):
299
- continue
300
- try:
301
- text = getter()
302
- except Exception: # noqa: BLE001 — no selection model: not fatal
303
- continue
304
- if isinstance(text, str) and text.strip():
305
- return text
306
- return ""
307
-
308
-
309
- class ConversationPane(VerticalScroll):
310
- """The conversation pane.
311
-
312
- Right-click is handled here rather than on the app: mouse reporting is
313
- on, so the terminal's own context menu never opens inside the screen,
314
- and the pane is where a reader aims when they want text out of it.
315
- """
316
-
317
- def on_mouse_down(self, event) -> None:
318
- if getattr(event, "button", 0) != 3:
319
- return
320
- stop = getattr(event, "stop", None)
321
- if callable(stop): # keep the app's own handler from firing twice
322
- stop()
323
- self.app.open_copy_menu()
324
-
325
-
326
- # -- pickers ---------------------------------------------------------------------
327
-
328
- class PickerModal(ModalScreen):
329
- """Generic list picker: Enter selects, letters run extra actions,
330
- Esc/q closes. ``items`` are (payload, markup label) tuples."""
331
-
332
- BINDINGS = [
333
- Binding("escape", "dismiss_none", "关闭"),
334
- Binding("q", "dismiss_none", "关闭", show=False),
335
- Binding("n", "letter('n')", show=False),
336
- Binding("d", "letter('d')", show=False),
337
- Binding("r", "letter('r')", show=False),
338
- Binding("s", "letter('s')", show=False),
339
- # In-place toggle for the settings picker: flips the focused row
340
- # without dismissing, so several knobs change in one visit.
341
- Binding("space", "toggle", "切换(不关闭)", priority=True),
342
- ]
343
-
344
- def __init__(self, title: str, items: list[tuple[dict, str]],
345
- hint: str = "", letter_actions: dict[str, str] | None = None,
346
- live_toggle: Callable[[dict], str | None] | None = None):
347
- super().__init__()
348
- self.title = title
349
- self.items = items
350
- self.hint = hint
351
- self.letter_actions = letter_actions or {}
352
- self.live_toggle = live_toggle
353
-
354
- def compose(self) -> ComposeResult:
355
- with Vertical(id="picker"):
356
- yield Static(self.title, id="picker-title")
357
- yield ListView(
358
- *[ListItem(Label(label)) for _payload, label in self.items],
359
- id="picker-list",
360
- )
361
- if self.hint:
362
- yield Static(self.hint, id="picker-hint")
363
-
364
- def on_mount(self) -> None:
365
- self.query_one("#picker-list", ListView).focus()
366
-
367
- def _current_payload(self) -> dict | None:
368
- view = self.query_one("#picker-list", ListView)
369
- index = view.index if view.index is not None else 0
370
- if 0 <= index < len(self.items):
371
- return self.items[index][0]
372
- return None
373
-
374
- def on_list_view_selected(self, event: ListView.Selected) -> None:
375
- view = self.query_one("#picker-list", ListView)
376
- index = view.children.index(event.item) if event.item in view.children \
377
- else None
378
- payload = self.items[index][0] if index is not None else None
379
- self.dismiss(("select", payload))
380
-
381
- def action_dismiss_none(self) -> None:
382
- self.dismiss(None)
383
-
384
- def action_letter(self, key: str) -> None:
385
- name = self.letter_actions.get(key)
386
- payload = self._current_payload()
387
- self.dismiss(("letter", name, payload) if name else None)
388
-
389
- def action_toggle(self) -> None:
390
- """Flip the focused row in place: the ``live_toggle`` callback
391
- applies the change and returns a rebuilt label (``None`` when the
392
- row is not toggleable); the modal stays open."""
393
- if self.live_toggle is None:
394
- return
395
- view = self.query_one("#picker-list", ListView)
396
- index = view.index if view.index is not None else 0
397
- if not 0 <= index < len(self.items):
398
- return
399
- payload = self.items[index][0]
400
- label = self.live_toggle(payload)
401
- if label is None:
402
- return
403
- self.items[index] = (payload, label)
404
- row = view.children[index]
405
- if row.children:
406
- row.children[0].update(label)
407
-
408
-
409
- # -- command approval --------------------------------------------------------
410
-
411
- class ConfirmModal(ModalScreen):
412
- """y/n on a destructive run_command: y allows, n/Esc refuses."""
413
-
414
- BINDINGS = [
415
- Binding("y", "allow", "允许"),
416
- Binding("n", "refuse", "拒绝"),
417
- Binding("escape", "refuse", "拒绝", show=False),
418
- ]
419
-
420
- def __init__(self, command: str):
421
- super().__init__()
422
- self.command = command
423
-
424
- def compose(self) -> ComposeResult:
425
- with Vertical(id="picker"):
426
- yield Static("⚠ 破坏性命令需确认", id="picker-title")
427
- yield Static(self.command, id="picker-hint")
428
- yield Static("y 允许执行 · n/Esc 拒绝", id="picker-hint")
429
-
430
- def action_allow(self) -> None:
431
- self.dismiss(True)
432
-
433
- def action_refuse(self) -> None:
434
- self.dismiss(False)
435
-
436
-
437
168
  # -- the app ----------------------------------------------------------------------
438
169
 
439
170
  class LitheApp(App):
@@ -449,6 +180,7 @@ class LitheApp(App):
449
180
  #picker-title { color: #38bdf8; text-style: bold; }
450
181
  #picker-list { height: auto; max-height: 16; }
451
182
  #picker-hint { color: #94a3b8; }
183
+ #picker-command { color: #f87171; }
452
184
  .user { color: #60a5fa; }
453
185
  .assistant { color: #4ade80; }
454
186
  .tool { color: #22d3ee; }
@@ -494,10 +226,7 @@ class LitheApp(App):
494
226
  yield Static("", id="foot", markup=False)
495
227
 
496
228
  def on_mount(self) -> None:
497
- from lithe.bundles import JsonTodoStore
498
-
499
229
  from . import __version__
500
- from .agent import todo_store_path
501
230
  from .prompts import open_history
502
231
  from .workbench import Workbench
503
232
 
@@ -505,7 +234,6 @@ class LitheApp(App):
505
234
  # Destructive run_command approval rides a modal; the turn task and
506
235
  # the app share one loop, so the middleware can await the human.
507
236
  self.wb.approver = self.confirm_command
508
- self.todo_store = JsonTodoStore(todo_store_path(self.cfg))
509
237
  self.version = __version__
510
238
  prompt = self.query_one("#prompt", HistoryInput)
511
239
  if self.mode == "chat":
@@ -549,6 +277,10 @@ class LitheApp(App):
549
277
  and self.wb.current else None
550
278
 
551
279
  def _base_state(self, cid: int | None) -> TuiState:
280
+ from lithe.bundles import JsonTodoStore
281
+
282
+ from .agent import todo_store_path
283
+
552
284
  title = ""
553
285
  if cid is not None:
554
286
  title = (self.wb.sessions.get(cid) or {}).get("title", "")
@@ -556,7 +288,7 @@ class LitheApp(App):
556
288
  self.cfg.model or "(scripted)",
557
289
  str(self.cfg.workspace_dir.resolve()),
558
290
  self.cfg.max_steps,
559
- self.todo_store.list(),
291
+ JsonTodoStore(todo_store_path(self.cfg, cid)).list(),
560
292
  profile=self.cfg.profile or "",
561
293
  session_id=cid,
562
294
  session_title=title,
@@ -581,6 +313,10 @@ class LitheApp(App):
581
313
  st.set_sessions(self.wb.session_list(), self.wb.busy_ids())
582
314
 
583
315
  def _activate(self, cid: int) -> None:
316
+ from lithe.bundles import JsonTodoStore
317
+
318
+ from .agent import todo_store_path
319
+
584
320
  if cid not in self.states:
585
321
  st = self._base_state(cid)
586
322
  st.feed.extend(
@@ -594,6 +330,11 @@ class LitheApp(App):
594
330
  st.tokens = usage["total_tokens"]
595
331
  st.cost = usage["cost"]
596
332
  self.states[cid] = st
333
+ # Reload from the conversation's persisted store when returning to it:
334
+ # a background turn or /undo may have changed its todos meanwhile.
335
+ self.states[cid].todos = JsonTodoStore(
336
+ todo_store_path(self.cfg, cid)
337
+ ).list()
597
338
  self.state = self.states[cid]
598
339
  self._shown = 0
599
340
  conv = self.query_one("#conv", ConversationPane)
@@ -680,9 +421,18 @@ class LitheApp(App):
680
421
  self._refresh_chrome()
681
422
  return
682
423
  if t == "undo_done":
683
- self.state.say("ok", f"已撤销 {ev.get('reverted', 0)} 个操作"
684
- f"(run {ev.get('run_id')})")
685
- self._sync_feed()
424
+ from lithe.bundles import JsonTodoStore
425
+
426
+ from .agent import todo_store_path
427
+
428
+ if cid in self.states:
429
+ self.states[cid].todos = JsonTodoStore(
430
+ todo_store_path(self.cfg, cid)
431
+ ).list()
432
+ if cid == self._current_cid():
433
+ self.state.say("ok", f"已撤销 {ev.get('reverted', 0)} 个操作"
434
+ f"(run {ev.get('run_id')})")
435
+ self._sync_feed()
686
436
  return
687
437
  if cid in (-1, self._current_cid()):
688
438
  self.state.on_event(ev)
@@ -1179,3 +929,11 @@ def run_textual_screen(cfg, task: str | None, mode: str,
1179
929
  """The full-screen driver for `lithe chat` (mode='chat') and `lithe run`."""
1180
930
  app = LitheApp(cfg, task, mode, args)
1181
931
  return asyncio.run(_driver(app))
932
+
933
+
934
+ def __getattr__(name: str):
935
+ """Forward extracted widget names for existing ``lithe_cli.ttui`` users."""
936
+ try:
937
+ return getattr(_widgets, name)
938
+ except AttributeError:
939
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}") from None
@@ -0,0 +1,287 @@
1
+ """Reusable Textual widgets and modal dialogs used by the full-screen UI."""
2
+ from __future__ import annotations
3
+
4
+ from collections.abc import Callable
5
+ from typing import Any
6
+
7
+ from textual.app import ComposeResult
8
+ from textual.binding import Binding
9
+ from textual.containers import Vertical, VerticalScroll
10
+ from textual.message import Message
11
+ from textual.screen import ModalScreen
12
+ from textual.widgets import Input, Label, ListItem, ListView, Static
13
+
14
+ # -- input: completion + persistent history ------------------------------------
15
+
16
+ def completion_suggestions(
17
+ value: str,
18
+ commands: dict,
19
+ models: list[str],
20
+ profiles: list[str],
21
+ session_ids: list[str],
22
+ ) -> list[str]:
23
+ """Suggest completions for a half-typed input line (pure; tested).
24
+
25
+ ``/prefix`` completes command names; ``/model | /profile | /resume``
26
+ complete their first argument (cached models, saved profiles, session
27
+ ids). Empty result hides the suggestion strip.
28
+ """
29
+ if not value.startswith("/"):
30
+ return []
31
+ if " " not in value:
32
+ prefix = value.rstrip()
33
+ return [
34
+ f"/{name} "
35
+ for name in sorted(commands)
36
+ if prefix == "/" or f"/{name}".startswith(prefix)
37
+ ][:6]
38
+ head, _, arg = value.partition(" ")
39
+ command = head[1:].lower()
40
+ words: list[str] = []
41
+ if command == "model":
42
+ words = models
43
+ elif command == "profile":
44
+ words = profiles
45
+ elif command == "resume":
46
+ words = session_ids
47
+ return [w for w in words if w.startswith(arg) and w != arg][:6]
48
+
49
+
50
+ class HistoryInput(Input):
51
+ """Input with ↑/↓ recall over a persistent FileHistory store."""
52
+
53
+ BINDINGS = [
54
+ Binding("up", "history_prev", "上一条", show=False, priority=True),
55
+ Binding("down", "history_next", "下一条", show=False, priority=True),
56
+ Binding("tab", "accept_suggestion", "采纳", show=False,
57
+ priority=True),
58
+ ]
59
+
60
+ def __init__(self, *args, file_history=None, **kwargs):
61
+ super().__init__(*args, **kwargs)
62
+ self.file_history = file_history
63
+ self._lines: list[str] = []
64
+ self._pos: int | None = None
65
+ self._draft = ""
66
+ self.suggestion: list[str] = []
67
+ self.reload_history()
68
+
69
+ def reload_history(self) -> None:
70
+ self._lines = []
71
+ if self.file_history is not None:
72
+ try:
73
+ self._lines = list(self.file_history.load_history_strings())
74
+ except OSError:
75
+ self._lines = []
76
+ self._pos = None
77
+ self._draft = ""
78
+
79
+ def record(self, line: str) -> None:
80
+ line = line.strip()
81
+ if not line:
82
+ return
83
+ if not self._lines or self._lines[-1] != line:
84
+ self._lines.append(line)
85
+ if self.file_history is not None:
86
+ try:
87
+ self.file_history.store_string(line)
88
+ except OSError:
89
+ pass
90
+ self._pos = None
91
+ self._draft = ""
92
+
93
+ def _apply(self, text: str, pos: int | None) -> None:
94
+ self._pos = pos
95
+ self.value = text
96
+ self.cursor_position = len(text)
97
+
98
+ def action_history_prev(self) -> None:
99
+ if not self._lines:
100
+ return
101
+ if self._pos is None:
102
+ self._draft = self.value
103
+ self._apply(self._lines[-1], len(self._lines) - 1)
104
+ elif self._pos > 0:
105
+ self._apply(self._lines[self._pos - 1], self._pos - 1)
106
+
107
+ def action_history_next(self) -> None:
108
+ if self._pos is None:
109
+ return
110
+ if self._pos < len(self._lines) - 1:
111
+ self._apply(self._lines[self._pos + 1], self._pos + 1)
112
+ else:
113
+ self._apply(self._draft, None)
114
+
115
+ def action_accept_suggestion(self) -> None:
116
+ if self.suggestion:
117
+ accepted = self.suggestion[0]
118
+ self.value = accepted
119
+ self.cursor_position = len(accepted)
120
+ self.suggestion = []
121
+
122
+
123
+ # -- workbench → app message ----------------------------------------------------
124
+
125
+ class WbEvent(Message):
126
+ """One Workbench event, marshalled into the UI message pump."""
127
+
128
+ def __init__(self, cid: int, ev: dict) -> None:
129
+ super().__init__()
130
+ self.cid = cid
131
+ self.ev = ev
132
+
133
+
134
+ # -- clipboard hooks -------------------------------------------------------------
135
+
136
+ def selected_text(screen: Any, app: Any = None) -> str:
137
+ """The current Textual text selection, if this release has one.
138
+
139
+ The selection API moved names between Textual releases (and is absent
140
+ in the headless test driver), so every candidate is probed and a miss
141
+ simply means "no selection" — callers keep their old behaviour.
142
+ """
143
+ for holder in (screen, app):
144
+ if holder is None:
145
+ continue
146
+ getter = getattr(holder, "get_selected_text", None)
147
+ if not callable(getter):
148
+ continue
149
+ try:
150
+ text = getter()
151
+ except Exception: # noqa: BLE001 — no selection model: not fatal
152
+ continue
153
+ if isinstance(text, str) and text.strip():
154
+ return text
155
+ return ""
156
+
157
+
158
+ class ConversationPane(VerticalScroll):
159
+ """The conversation pane.
160
+
161
+ Right-click is handled here rather than on the app: mouse reporting is
162
+ on, so the terminal's own context menu never opens inside the screen,
163
+ and the pane is where a reader aims when they want text out of it.
164
+ """
165
+
166
+ def on_mouse_down(self, event) -> None:
167
+ if getattr(event, "button", 0) != 3:
168
+ return
169
+ stop = getattr(event, "stop", None)
170
+ if callable(stop): # keep the app's own handler from firing twice
171
+ stop()
172
+ self.app.open_copy_menu()
173
+
174
+
175
+ # -- pickers ---------------------------------------------------------------------
176
+
177
+ class PickerModal(ModalScreen):
178
+ """Generic list picker: Enter selects, letters run extra actions,
179
+ Esc/q closes. ``items`` are (payload, markup label) tuples."""
180
+
181
+ BINDINGS = [
182
+ Binding("escape", "dismiss_none", "关闭"),
183
+ Binding("q", "dismiss_none", "关闭", show=False),
184
+ Binding("n", "letter('n')", show=False),
185
+ Binding("d", "letter('d')", show=False),
186
+ Binding("r", "letter('r')", show=False),
187
+ Binding("s", "letter('s')", show=False),
188
+ # In-place toggle for the settings picker: flips the focused row
189
+ # without dismissing, so several knobs change in one visit.
190
+ Binding("space", "toggle", "切换(不关闭)", priority=True),
191
+ ]
192
+
193
+ def __init__(self, title: str, items: list[tuple[dict, str]],
194
+ hint: str = "", letter_actions: dict[str, str] | None = None,
195
+ live_toggle: Callable[[dict], str | None] | None = None):
196
+ super().__init__()
197
+ self.title = title
198
+ self.items = items
199
+ self.hint = hint
200
+ self.letter_actions = letter_actions or {}
201
+ self.live_toggle = live_toggle
202
+
203
+ def compose(self) -> ComposeResult:
204
+ with Vertical(id="picker"):
205
+ yield Static(self.title, id="picker-title")
206
+ yield ListView(
207
+ *[ListItem(Label(label)) for _payload, label in self.items],
208
+ id="picker-list",
209
+ )
210
+ if self.hint:
211
+ yield Static(self.hint, id="picker-hint")
212
+
213
+ def on_mount(self) -> None:
214
+ self.query_one("#picker-list", ListView).focus()
215
+
216
+ def _current_payload(self) -> dict | None:
217
+ view = self.query_one("#picker-list", ListView)
218
+ index = view.index if view.index is not None else 0
219
+ if 0 <= index < len(self.items):
220
+ return self.items[index][0]
221
+ return None
222
+
223
+ def on_list_view_selected(self, event: ListView.Selected) -> None:
224
+ view = self.query_one("#picker-list", ListView)
225
+ index = view.children.index(event.item) if event.item in view.children \
226
+ else None
227
+ payload = self.items[index][0] if index is not None else None
228
+ self.dismiss(("select", payload))
229
+
230
+ def action_dismiss_none(self) -> None:
231
+ self.dismiss(None)
232
+
233
+ def action_letter(self, key: str) -> None:
234
+ name = self.letter_actions.get(key)
235
+ payload = self._current_payload()
236
+ self.dismiss(("letter", name, payload) if name else None)
237
+
238
+ def action_toggle(self) -> None:
239
+ """Flip the focused row in place: the ``live_toggle`` callback
240
+ applies the change and returns a rebuilt label (``None`` when the
241
+ row is not toggleable); the modal stays open."""
242
+ if self.live_toggle is None:
243
+ return
244
+ view = self.query_one("#picker-list", ListView)
245
+ index = view.index if view.index is not None else 0
246
+ if not 0 <= index < len(self.items):
247
+ return
248
+ payload = self.items[index][0]
249
+ label = self.live_toggle(payload)
250
+ if label is None:
251
+ return
252
+ self.items[index] = (payload, label)
253
+ row = view.children[index]
254
+ if row.children:
255
+ row.children[0].update(label)
256
+
257
+
258
+ # -- command approval --------------------------------------------------------
259
+
260
+ class ConfirmModal(ModalScreen):
261
+ """y/n on a destructive run_command: y allows, n/Esc refuses."""
262
+
263
+ BINDINGS = [
264
+ Binding("y", "allow", "允许"),
265
+ Binding("n", "refuse", "拒绝"),
266
+ Binding("escape", "refuse", "拒绝", show=False),
267
+ ]
268
+
269
+ def __init__(self, command: str):
270
+ super().__init__()
271
+ self.command = command
272
+
273
+ def compose(self) -> ComposeResult:
274
+ with Vertical(id="picker"):
275
+ yield Static("⚠ 破坏性命令需确认", id="picker-title")
276
+ # 命令行与按键说明各用各的 id:Textual 要求同一父级下 id 唯一,
277
+ # 早前两处都叫 picker-hint,push_screen 时直接 MountError。
278
+ yield Static(self.command, id="picker-command")
279
+ yield Static("y 允许执行 · n/Esc 拒绝", id="picker-hint")
280
+
281
+ def action_allow(self) -> None:
282
+ self.dismiss(True)
283
+
284
+ def action_refuse(self) -> None:
285
+ self.dismiss(False)
286
+
287
+
@@ -506,7 +506,8 @@ class Workbench:
506
506
  return
507
507
  rid = runs[-1].run_id
508
508
  reverted = await undo(self.cfg, rid, quiet=True)
509
- cid = self._cid() or -1
509
+ run = self.store.get_run(rid, self.cfg.user_id)
510
+ cid = (run.conversation_id if run is not None else None) or -1
510
511
  self._emit(cid, {"type": "undo_done", "run_id": rid,
511
512
  "reverted": reverted})
512
513
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: lithe-cli
3
- Version: 0.1.3
3
+ Version: 0.1.4
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
 
@@ -14,6 +14,7 @@ lithe_cli/py.typed
14
14
  lithe_cli/sessions.py
15
15
  lithe_cli/setup.py
16
16
  lithe_cli/ttui.py
17
+ lithe_cli/ttui_widgets.py
17
18
  lithe_cli/tui.py
18
19
  lithe_cli/ui.py
19
20
  lithe_cli/workbench.py
@@ -567,6 +567,64 @@ def test_todo_storage_is_scoped_to_user_and_workspace(tmp_path):
567
567
  assert first_path.suffix == ".json"
568
568
  assert first_path != todo_store_path(second)
569
569
  assert first_path != todo_store_path(third)
570
+ assert first_path != todo_store_path(first, conversation_id=1)
571
+ assert todo_store_path(first, conversation_id=1) != todo_store_path(
572
+ first, conversation_id=2
573
+ )
574
+
575
+
576
+ def test_todo_tools_are_scoped_to_conversation(tmp_path):
577
+ from lithe import AgentContext
578
+ from lithe.bundles import JsonTodoStore
579
+ from lithe_cli.agent import build_registry, todo_store_path
580
+
581
+ cfg = make_config(tmp_path, [])
582
+
583
+ async def update(conversation_id, content):
584
+ registry = build_registry(cfg, conversation_id=conversation_id)
585
+ return await registry.dispatch(
586
+ "update_todos",
587
+ {"todos": [{"content": content, "status": "pending"}]},
588
+ AgentContext(
589
+ run_id=f"run-{conversation_id}",
590
+ user_id=cfg.user_id,
591
+ extra={"conversation_id": conversation_id},
592
+ ),
593
+ )
594
+
595
+ result_a = asyncio.run(update(101, "对话 A 的任务"))
596
+ result_b = asyncio.run(update(202, "对话 B 的任务"))
597
+ assert result_a.ok and result_b.ok
598
+ assert JsonTodoStore(todo_store_path(cfg, 101)).list()[0]["content"] == "对话 A 的任务"
599
+ assert JsonTodoStore(todo_store_path(cfg, 202)).list()[0]["content"] == "对话 B 的任务"
600
+
601
+
602
+ def test_undo_todo_change_uses_owning_conversation_store(tmp_path):
603
+ from lithe.bundles import JsonTodoStore
604
+ from lithe_cli.agent import todo_store_path
605
+
606
+ responses = [
607
+ {"tool_calls": [_tc("update_todos", {
608
+ "todos": [{"content": "会话 A 任务", "status": "pending"}],
609
+ }, "a1")]},
610
+ {"content": "A 已记录"},
611
+ {"tool_calls": [_tc("update_todos", {
612
+ "todos": [{"content": "会话 B 任务", "status": "pending"}],
613
+ }, "b1")]},
614
+ {"content": "B 已记录"},
615
+ ]
616
+ cfg = make_config(tmp_path, responses)
617
+ rid_a, done_a, _ = asyncio.run(
618
+ execute(cfg, "记录 A 任务", conversation_id=11)
619
+ )
620
+ rid_b, done_b, _ = asyncio.run(
621
+ execute(cfg, "记录 B 任务", conversation_id=22)
622
+ )
623
+ assert done_a["status"] == done_b["status"] == "done"
624
+
625
+ assert asyncio.run(undo(cfg, rid_a)) == 1
626
+ assert JsonTodoStore(todo_store_path(cfg, 11)).list() == []
627
+ assert JsonTodoStore(todo_store_path(cfg, 22)).list()[0]["content"] == "会话 B 任务"
570
628
 
571
629
 
572
630
  def test_persisted_todos_are_not_injected_into_unrelated_prompts(tmp_path):
@@ -15,6 +15,7 @@ from textual.containers import VerticalScroll # noqa: E402
15
15
  from lithe_cli import clipboard as clipboard_mod # noqa: E402
16
16
 
17
17
  from lithe_cli.ttui import ( # noqa: E402
18
+ ConfirmModal,
18
19
  LitheApp,
19
20
  PickerModal,
20
21
  footer_text,
@@ -183,6 +184,61 @@ def test_session_picker_switches_sessions(tmp_path):
183
184
  asyncio.run(scenario())
184
185
 
185
186
 
187
+ def test_todos_are_loaded_per_conversation_on_new_and_switch(tmp_path):
188
+ async def scenario():
189
+ app = _app(tmp_path, [])
190
+ async with app.run_test(size=(100, 30)) as pilot:
191
+ await pilot.pause()
192
+ from lithe.bundles import JsonTodoStore
193
+ from lithe_cli.agent import todo_store_path
194
+
195
+ first = app.wb.current["id"]
196
+ JsonTodoStore(todo_store_path(app.cfg, first)).replace([
197
+ {"content": "第一会话任务", "status": "pending"},
198
+ ])
199
+
200
+ second_conv = app.wb.new_session()
201
+ app._activate(second_conv["id"])
202
+ assert app.state.todos == []
203
+
204
+ JsonTodoStore(todo_store_path(app.cfg, second_conv["id"])).replace([
205
+ {"content": "第二会话任务", "status": "pending"},
206
+ ])
207
+ app.wb.current = app.wb.sessions.get(first)
208
+ app._activate(first)
209
+ assert [todo["content"] for todo in app.state.todos] == ["第一会话任务"]
210
+
211
+ asyncio.run(scenario())
212
+
213
+
214
+ def test_confirm_modal_mounts_and_answers(tmp_path):
215
+ """回归:ConfirmModal 的 compose 必须可挂载(同父级 id 唯一)并能
216
+ y/n 应答——早前两行同用 id="picker-hint",破坏性命令审批一弹出
217
+ 就 MountError 崩溃。"""
218
+
219
+ async def scenario():
220
+ app = _app(tmp_path, [])
221
+ async with app.run_test(size=(100, 30)) as pilot:
222
+ await pilot.pause()
223
+ got: list[bool] = []
224
+ app.push_screen(ConfirmModal("rm -rf build"), got.append)
225
+ await pilot.pause()
226
+ assert isinstance(app.screen, ConfirmModal)
227
+ assert app.screen.query_one("#picker-command")
228
+ await pilot.press("y")
229
+ await pilot.pause()
230
+ assert got == [True]
231
+
232
+ got.clear()
233
+ app.push_screen(ConfirmModal("del /s build"), got.append)
234
+ await pilot.pause()
235
+ await pilot.press("escape")
236
+ await pilot.pause()
237
+ assert got == [False]
238
+
239
+ asyncio.run(scenario())
240
+
241
+
186
242
  def test_model_picker_and_command_switch_model(tmp_path, monkeypatch):
187
243
  monkeypatch.setenv("LITHE_HOME", str(tmp_path / "home"))
188
244
  from lithe_cli.profiles import ProfileStore
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