lithe-cli 0.1.2__tar.gz → 0.1.3__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.
- {lithe_cli-0.1.2 → lithe_cli-0.1.3}/PKG-INFO +1 -1
- {lithe_cli-0.1.2 → lithe_cli-0.1.3}/lithe_cli/__init__.py +1 -1
- lithe_cli-0.1.3/lithe_cli/clipboard.py +123 -0
- {lithe_cli-0.1.2 → lithe_cli-0.1.3}/lithe_cli/commands.py +9 -0
- {lithe_cli-0.1.2 → lithe_cli-0.1.3}/lithe_cli/main.py +49 -0
- {lithe_cli-0.1.2 → lithe_cli-0.1.3}/lithe_cli/ttui.py +163 -11
- {lithe_cli-0.1.2 → lithe_cli-0.1.3}/lithe_cli/tui.py +84 -1
- {lithe_cli-0.1.2 → lithe_cli-0.1.3}/lithe_cli/workbench.py +9 -0
- {lithe_cli-0.1.2 → lithe_cli-0.1.3}/lithe_cli.egg-info/PKG-INFO +1 -1
- {lithe_cli-0.1.2 → lithe_cli-0.1.3}/lithe_cli.egg-info/SOURCES.txt +2 -0
- lithe_cli-0.1.3/tests/test_cli_clipboard.py +179 -0
- {lithe_cli-0.1.2 → lithe_cli-0.1.3}/tests/test_cli_sessions.py +46 -0
- {lithe_cli-0.1.2 → lithe_cli-0.1.3}/tests/test_ttui.py +197 -1
- {lithe_cli-0.1.2 → lithe_cli-0.1.3}/tests/test_tui_v2.py +60 -1
- {lithe_cli-0.1.2 → lithe_cli-0.1.3}/LICENSE +0 -0
- {lithe_cli-0.1.2 → lithe_cli-0.1.3}/README.md +0 -0
- {lithe_cli-0.1.2 → lithe_cli-0.1.3}/lithe_cli/__main__.py +0 -0
- {lithe_cli-0.1.2 → lithe_cli-0.1.3}/lithe_cli/agent.py +0 -0
- {lithe_cli-0.1.2 → lithe_cli-0.1.3}/lithe_cli/config.py +0 -0
- {lithe_cli-0.1.2 → lithe_cli-0.1.3}/lithe_cli/profiles.py +0 -0
- {lithe_cli-0.1.2 → lithe_cli-0.1.3}/lithe_cli/prompts.py +0 -0
- {lithe_cli-0.1.2 → lithe_cli-0.1.3}/lithe_cli/py.typed +0 -0
- {lithe_cli-0.1.2 → lithe_cli-0.1.3}/lithe_cli/sessions.py +0 -0
- {lithe_cli-0.1.2 → lithe_cli-0.1.3}/lithe_cli/setup.py +0 -0
- {lithe_cli-0.1.2 → lithe_cli-0.1.3}/lithe_cli/ui.py +0 -0
- {lithe_cli-0.1.2 → lithe_cli-0.1.3}/lithe_cli.egg-info/dependency_links.txt +0 -0
- {lithe_cli-0.1.2 → lithe_cli-0.1.3}/lithe_cli.egg-info/entry_points.txt +0 -0
- {lithe_cli-0.1.2 → lithe_cli-0.1.3}/lithe_cli.egg-info/requires.txt +0 -0
- {lithe_cli-0.1.2 → lithe_cli-0.1.3}/lithe_cli.egg-info/top_level.txt +0 -0
- {lithe_cli-0.1.2 → lithe_cli-0.1.3}/pyproject.toml +0 -0
- {lithe_cli-0.1.2 → lithe_cli-0.1.3}/setup.cfg +0 -0
- {lithe_cli-0.1.2 → lithe_cli-0.1.3}/tests/test_cli.py +0 -0
- {lithe_cli-0.1.2 → lithe_cli-0.1.3}/tests/test_cli_budget_steer.py +0 -0
- {lithe_cli-0.1.2 → lithe_cli-0.1.3}/tests/test_cli_guard.py +0 -0
- {lithe_cli-0.1.2 → lithe_cli-0.1.3}/tests/test_cli_subagents.py +0 -0
- {lithe_cli-0.1.2 → lithe_cli-0.1.3}/tests/test_profiles.py +0 -0
- {lithe_cli-0.1.2 → lithe_cli-0.1.3}/tests/test_workbench.py +0 -0
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
"""System-clipboard delivery for the CLI's copy commands.
|
|
2
|
+
|
|
3
|
+
Deliberately dependency-free and front-end-free: the Textual screen, the
|
|
4
|
+
plain per-line REPL and the tests all go through
|
|
5
|
+
:func:`deliver_clipboard`, which tries three channels in order —
|
|
6
|
+
|
|
7
|
+
1. the platform's own tool (``pbcopy`` / ``clip`` / ``wl-copy`` /
|
|
8
|
+
``xclip`` / ``xsel``): the only channel that writes the *real* system
|
|
9
|
+
clipboard no matter what the terminal implements;
|
|
10
|
+
2. OSC 52 through the caller's app (Textual's ``copy_to_clipboard``):
|
|
11
|
+
covers terminals without those tools, including remote sessions —
|
|
12
|
+
``app`` is optional because only a full-screen front-end has one;
|
|
13
|
+
3. a plain file under ``$LITHE_HOME`` (``clipboard-<ts>.txt``), so a copy
|
|
14
|
+
is never a silent no-op on a terminal where neither works.
|
|
15
|
+
|
|
16
|
+
Everything is best-effort: failures come back as a reason string instead
|
|
17
|
+
of an exception, because a copy the user cannot find is worth reporting,
|
|
18
|
+
not crashing on.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import inspect
|
|
24
|
+
import os
|
|
25
|
+
import shutil
|
|
26
|
+
import subprocess
|
|
27
|
+
import sys
|
|
28
|
+
import time
|
|
29
|
+
from pathlib import Path
|
|
30
|
+
from typing import Any
|
|
31
|
+
|
|
32
|
+
from .config import lithe_home
|
|
33
|
+
|
|
34
|
+
_TIMEOUT = 5 # seconds: a wedged clipboard helper must not freeze the UI
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def native_clipboard_command() -> list[str] | None:
|
|
38
|
+
"""The installed platform clipboard tool, if any (a pure PATH lookup)."""
|
|
39
|
+
if sys.platform == "darwin":
|
|
40
|
+
candidates = [["pbcopy"]]
|
|
41
|
+
elif os.name == "nt":
|
|
42
|
+
candidates = [["clip"]]
|
|
43
|
+
else:
|
|
44
|
+
candidates = [
|
|
45
|
+
["wl-copy"],
|
|
46
|
+
["xclip", "-selection", "clipboard"],
|
|
47
|
+
["xsel", "-i", "--clipboard"],
|
|
48
|
+
]
|
|
49
|
+
for argv in candidates:
|
|
50
|
+
if shutil.which(argv[0]):
|
|
51
|
+
return argv
|
|
52
|
+
return None
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def pipe_to_clipboard(text: str, argv: list[str]) -> bool:
|
|
56
|
+
"""Feed *text* to a clipboard tool over stdin; ``False`` on any failure.
|
|
57
|
+
|
|
58
|
+
``clip.exe`` reads UTF-16LE from a pipe (cmd's convention), the Unix
|
|
59
|
+
helpers UTF-8.
|
|
60
|
+
"""
|
|
61
|
+
name = Path(argv[0]).name.lower()
|
|
62
|
+
encoding = "utf-16-le" if name.startswith("clip") else "utf-8"
|
|
63
|
+
try:
|
|
64
|
+
proc = subprocess.run(
|
|
65
|
+
argv, input=text.encode(encoding), capture_output=True,
|
|
66
|
+
timeout=_TIMEOUT,
|
|
67
|
+
)
|
|
68
|
+
except (OSError, ValueError, subprocess.SubprocessError):
|
|
69
|
+
return False
|
|
70
|
+
return proc.returncode == 0
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def write_clipboard_file(text: str, home: Path | None = None) -> Path | None:
|
|
74
|
+
"""Last-resort copy: the text as ``$LITHE_HOME/clipboard-<ts>.txt``."""
|
|
75
|
+
base = Path(home) if home is not None else lithe_home()
|
|
76
|
+
try:
|
|
77
|
+
base.mkdir(parents=True, exist_ok=True)
|
|
78
|
+
path = base / f"clipboard-{time.strftime('%Y%m%d-%H%M%S')}.txt"
|
|
79
|
+
path.write_text(text if text.endswith("\n") else text + "\n",
|
|
80
|
+
encoding="utf-8")
|
|
81
|
+
except OSError:
|
|
82
|
+
return None
|
|
83
|
+
return path
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
async def deliver_clipboard(
|
|
87
|
+
text: str, *, app: Any = None, home: Path | None = None
|
|
88
|
+
) -> tuple[bool, str]:
|
|
89
|
+
"""Copy *text* by the best available channel; returns ``(ok, channel)``.
|
|
90
|
+
|
|
91
|
+
``channel`` is what the user should be told: the tool that took it
|
|
92
|
+
(``pbcopy``), ``OSC 52``, or the fallback file's path — and when
|
|
93
|
+
nothing worked, the reason.
|
|
94
|
+
"""
|
|
95
|
+
argv = native_clipboard_command()
|
|
96
|
+
if argv is not None and pipe_to_clipboard(text, argv):
|
|
97
|
+
return True, argv[0]
|
|
98
|
+
if app is not None and await _osc52(app, text):
|
|
99
|
+
return True, "OSC 52"
|
|
100
|
+
path = write_clipboard_file(text, home)
|
|
101
|
+
if path is not None:
|
|
102
|
+
return True, str(path)
|
|
103
|
+
return False, ("系统剪贴板不可用(未找到 pbcopy/clip/wl-copy/xclip,"
|
|
104
|
+
"终端也不接受 OSC 52,且写入 $LITHE_HOME 失败)")
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
async def _osc52(app: Any, text: str) -> bool:
|
|
108
|
+
"""Textual's clipboard write, tolerant of sync or coroutine flavours.
|
|
109
|
+
|
|
110
|
+
The release-switch that renamed pieces of the selection API is exactly
|
|
111
|
+
why this goes through ``getattr``: an app that cannot copy must fall
|
|
112
|
+
through to the next channel, not raise out of a key handler.
|
|
113
|
+
"""
|
|
114
|
+
copy = getattr(app, "copy_to_clipboard", None)
|
|
115
|
+
if not callable(copy):
|
|
116
|
+
return False
|
|
117
|
+
try:
|
|
118
|
+
result = copy(text)
|
|
119
|
+
if inspect.isawaitable(result):
|
|
120
|
+
await result
|
|
121
|
+
except Exception: # noqa: BLE001 — no driver/headless: try the next channel
|
|
122
|
+
return False
|
|
123
|
+
return True
|
|
@@ -13,6 +13,10 @@ from dataclasses import dataclass, field
|
|
|
13
13
|
from typing import Any
|
|
14
14
|
from collections.abc import Callable
|
|
15
15
|
|
|
16
|
+
# The /copy scope vocabulary lives with the feed it extracts from, so the
|
|
17
|
+
# completion hint, the help line and the parser can never drift apart.
|
|
18
|
+
from .tui import COPY_SCOPE_HELP
|
|
19
|
+
|
|
16
20
|
# name → (args hint, one-line description); order is the help order.
|
|
17
21
|
COMMANDS: dict[str, tuple[str, str]] = {
|
|
18
22
|
"help": ("", "显示这条帮助"),
|
|
@@ -26,6 +30,7 @@ COMMANDS: dict[str, tuple[str, str]] = {
|
|
|
26
30
|
"profile": ("[名称]", "查看/切换 provider 档案"),
|
|
27
31
|
"set": ("[名称] [值]", "查看/调整运行设置(F5 同效);面板内空格连切不关闭、Enter 切换并关闭,下一轮生效"),
|
|
28
32
|
"tools": ("", "列出已注册的工具"),
|
|
33
|
+
"copy": (f"[{COPY_SCOPE_HELP}]", "复制对话文本到系统剪贴板(右键同效);默认最后一条回答"),
|
|
29
34
|
"undo": ("[run]", "撤销当前会话最近一轮(或指定 run)的文件改动"),
|
|
30
35
|
"sidebar": ("", "显示/隐藏右侧状态栏(F2 同效)"),
|
|
31
36
|
"exit": ("", "退出(等同 /quit)"),
|
|
@@ -52,6 +57,10 @@ class ActionResult:
|
|
|
52
57
|
overlay: str | None = None # TUI picker: "sessions" | "model" | "set"
|
|
53
58
|
toggle_sidebar: bool = False
|
|
54
59
|
changed: bool = False # model/session changed → refresh banner/sidebar
|
|
60
|
+
# /copy: which slice of the feed the front-end should put on the
|
|
61
|
+
# clipboard. The workbench only parses it — the text itself lives in
|
|
62
|
+
# the front-end (feed in the TUI, store transcript in the plain REPL).
|
|
63
|
+
copy_scope: str | None = None
|
|
55
64
|
# Zero-arg coroutine the frontend must run: plain → asyncio.run,
|
|
56
65
|
# TUI → create_task (so /models fetches never block the screen).
|
|
57
66
|
awaitable: Callable[[], Any] | None = None
|
|
@@ -224,6 +224,11 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
224
224
|
sessions_p.add_argument("--limit", type=int, default=30)
|
|
225
225
|
sessions_p.add_argument("--rename", nargs=2, metavar=("ID", "TITLE"))
|
|
226
226
|
sessions_p.add_argument("--delete", metavar="ID")
|
|
227
|
+
sessions_p.add_argument(
|
|
228
|
+
"--export", metavar="ID|标题",
|
|
229
|
+
help="print a conversation as plain text (pipe it: lithe sessions "
|
|
230
|
+
"--export 12 | pbcopy)",
|
|
231
|
+
)
|
|
227
232
|
|
|
228
233
|
models_p = sub.add_parser(
|
|
229
234
|
"models", help="list the endpoint's models (GET /models)"
|
|
@@ -344,6 +349,23 @@ def _cmd_sessions(cfg: Any, args: Any) -> int:
|
|
|
344
349
|
from .sessions import SessionManager, format_session_rows
|
|
345
350
|
|
|
346
351
|
mgr = SessionManager(JsonlRunStore(cfg.store_dir), cfg.user_id)
|
|
352
|
+
if args.export:
|
|
353
|
+
# Plain text on stdout, so a copy-and-paste workflow works outside
|
|
354
|
+
# the full-screen UI too: `lithe sessions --export 12 | pbcopy`.
|
|
355
|
+
from .tui import feed_text, transcript_feed_lines
|
|
356
|
+
|
|
357
|
+
row, err = mgr.resolve_exact(args.export)
|
|
358
|
+
if row is None:
|
|
359
|
+
print(ui.s(err, RED))
|
|
360
|
+
return 1
|
|
361
|
+
text = feed_text(
|
|
362
|
+
transcript_feed_lines(mgr.history(row["id"])), "all"
|
|
363
|
+
)
|
|
364
|
+
if not text.strip():
|
|
365
|
+
print(ui.s(f"会话 #{row['id']} 没有可导出的文本", YELLOW))
|
|
366
|
+
return 1
|
|
367
|
+
print(text)
|
|
368
|
+
return 0
|
|
347
369
|
if args.rename:
|
|
348
370
|
ident, new_title = args.rename
|
|
349
371
|
row, err = mgr.resolve_exact(ident)
|
|
@@ -608,6 +630,31 @@ def _print_result_messages(messages) -> None:
|
|
|
608
630
|
print(ui.s(text, style) if style else text)
|
|
609
631
|
|
|
610
632
|
|
|
633
|
+
def _copy_plain(wb: Any, scope: str) -> None:
|
|
634
|
+
"""``/copy`` outside the full-screen UI: the store holds the text.
|
|
635
|
+
|
|
636
|
+
The TUI copies from its live feed; the plain REPL rebuilds the same
|
|
637
|
+
rows from the session transcript, so both frontends send identical
|
|
638
|
+
text through the same layered :mod:`lithe_cli.clipboard` channels.
|
|
639
|
+
"""
|
|
640
|
+
from .clipboard import deliver_clipboard
|
|
641
|
+
from .tui import COPY_SCOPE_LABELS, describe_copy, feed_text, \
|
|
642
|
+
transcript_feed_lines
|
|
643
|
+
|
|
644
|
+
label = COPY_SCOPE_LABELS.get(scope, scope)
|
|
645
|
+
cid = wb.current["id"] if wb.current else None
|
|
646
|
+
rows = wb.sessions.transcript(cid) if cid is not None else []
|
|
647
|
+
text = feed_text(transcript_feed_lines(rows), scope)
|
|
648
|
+
if not text.strip():
|
|
649
|
+
print(ui.s(f"没有可复制的{label}(对话还是空的)", YELLOW))
|
|
650
|
+
return
|
|
651
|
+
ok, channel = asyncio.run(deliver_clipboard(text))
|
|
652
|
+
if ok:
|
|
653
|
+
print(ui.s(f"✓ 已复制{label}({describe_copy(text)} → {channel})", GREEN))
|
|
654
|
+
else:
|
|
655
|
+
print(ui.s(f"复制{label}失败:{channel}", RED))
|
|
656
|
+
|
|
657
|
+
|
|
611
658
|
def _chat_loop(
|
|
612
659
|
cfg: Any,
|
|
613
660
|
resume: str | None = None,
|
|
@@ -673,6 +720,8 @@ def _chat_loop(
|
|
|
673
720
|
_print_result_messages(r.messages)
|
|
674
721
|
if r.toggle_sidebar:
|
|
675
722
|
print(ui.s("(纯文本模式没有侧栏;交互终端里按 F2)", YELLOW))
|
|
723
|
+
if r.copy_scope:
|
|
724
|
+
_copy_plain(wb, r.copy_scope)
|
|
676
725
|
if r.action == "exit":
|
|
677
726
|
break
|
|
678
727
|
if r.awaitable is not None:
|
|
@@ -12,9 +12,13 @@ Input niceties: ``/``-commands complete inline (suggestions above the
|
|
|
12
12
|
prompt, Tab accepts the first), and ↑/↓ recall the persistent chat history
|
|
13
13
|
(shared with the plain REPL through prompt_toolkit's FileHistory store).
|
|
14
14
|
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
15
|
+
Copying: mouse reporting means the terminal's own drag-select and menu
|
|
16
|
+
never reach it, so the app brings its own — right-click opens a copy menu,
|
|
17
|
+
``/copy`` takes the whole conversation (or the last answer, the user's
|
|
18
|
+
lines, the tool output), and ``Ctrl+C`` copies a Textual text selection
|
|
19
|
+
when there is one before it falls back to cancel/exit. Delivery is
|
|
20
|
+
layered (platform tool → OSC 52 → file) in :mod:`lithe_cli.clipboard`;
|
|
21
|
+
Shift+drag still works in terminals that keep native selection.
|
|
18
22
|
"""
|
|
19
23
|
|
|
20
24
|
from __future__ import annotations
|
|
@@ -30,7 +34,16 @@ from textual.message import Message
|
|
|
30
34
|
from textual.screen import ModalScreen
|
|
31
35
|
from textual.widgets import Input, Label, ListItem, ListView, Static
|
|
32
36
|
|
|
33
|
-
from .
|
|
37
|
+
from .clipboard import deliver_clipboard, write_clipboard_file
|
|
38
|
+
from .config import lithe_home
|
|
39
|
+
from .tui import (
|
|
40
|
+
COPY_SCOPE_LABELS,
|
|
41
|
+
COPY_SCOPES,
|
|
42
|
+
TuiState,
|
|
43
|
+
describe_copy,
|
|
44
|
+
feed_text,
|
|
45
|
+
transcript_feed_lines,
|
|
46
|
+
)
|
|
34
47
|
from .ui import fmt_duration
|
|
35
48
|
|
|
36
49
|
_MAX_FEED = 400 # mounted conversation lines before trimming the oldest
|
|
@@ -269,6 +282,47 @@ class WbEvent(Message):
|
|
|
269
282
|
self.ev = ev
|
|
270
283
|
|
|
271
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
|
+
|
|
272
326
|
# -- pickers ---------------------------------------------------------------------
|
|
273
327
|
|
|
274
328
|
class PickerModal(ModalScreen):
|
|
@@ -423,19 +477,21 @@ class LitheApp(App):
|
|
|
423
477
|
self.args = args
|
|
424
478
|
self._shown = 0 # feed lines already mounted
|
|
425
479
|
self._cancel_asked = False # first Ctrl+C cancels, second exits
|
|
480
|
+
self._pending_selection = "" # selection captured at right-click time
|
|
426
481
|
|
|
427
482
|
# -- composition ----------------------------------------------------------
|
|
428
483
|
|
|
429
484
|
def compose(self) -> ComposeResult:
|
|
430
|
-
yield Static("", id="top")
|
|
485
|
+
yield Static("", id="top", markup=False)
|
|
431
486
|
with Horizontal(id="body"):
|
|
432
|
-
with
|
|
433
|
-
yield Static("", id="streaming", classes="assistant"
|
|
487
|
+
with ConversationPane(id="conv"):
|
|
488
|
+
yield Static("", id="streaming", classes="assistant",
|
|
489
|
+
markup=False)
|
|
434
490
|
with VerticalScroll(id="side-wrap"):
|
|
435
491
|
yield Static("", id="side", markup=True)
|
|
436
492
|
yield Static("", id="suggest")
|
|
437
493
|
yield HistoryInput(placeholder="输入任务,/help 查看命令", id="prompt")
|
|
438
|
-
yield Static("", id="foot")
|
|
494
|
+
yield Static("", id="foot", markup=False)
|
|
439
495
|
|
|
440
496
|
def on_mount(self) -> None:
|
|
441
497
|
from lithe.bundles import JsonTodoStore
|
|
@@ -540,7 +596,7 @@ class LitheApp(App):
|
|
|
540
596
|
self.states[cid] = st
|
|
541
597
|
self.state = self.states[cid]
|
|
542
598
|
self._shown = 0
|
|
543
|
-
conv = self.query_one("#conv",
|
|
599
|
+
conv = self.query_one("#conv", ConversationPane)
|
|
544
600
|
for child in list(conv.children):
|
|
545
601
|
if child.id != "streaming":
|
|
546
602
|
child.remove()
|
|
@@ -551,7 +607,7 @@ class LitheApp(App):
|
|
|
551
607
|
# -- conversation rendering (pure render-from-state) ----------------------
|
|
552
608
|
|
|
553
609
|
def _sync_feed(self) -> None:
|
|
554
|
-
conv = self.query_one("#conv",
|
|
610
|
+
conv = self.query_one("#conv", ConversationPane)
|
|
555
611
|
streaming = self.query_one("#streaming", Static)
|
|
556
612
|
# Follow the feed only when the reader is already at (or near) the
|
|
557
613
|
# bottom: scrolling up to re-read earlier output mid-run must stick,
|
|
@@ -561,7 +617,10 @@ class LitheApp(App):
|
|
|
561
617
|
while self._shown < len(feed):
|
|
562
618
|
cls, text = feed[self._shown]
|
|
563
619
|
self._shown += 1
|
|
564
|
-
|
|
620
|
+
# markup=False: model/tool text is data, not Textual markup —
|
|
621
|
+
# a "[x]" in an answer must render, not parse (and it is what
|
|
622
|
+
# /copy sends to the clipboard verbatim).
|
|
623
|
+
conv.mount(Static(text, classes=cls or "dim", markup=False),
|
|
565
624
|
before=streaming)
|
|
566
625
|
non_stream = [c for c in conv.children if c.id != "streaming"]
|
|
567
626
|
for stale in non_stream[:max(0, len(non_stream) - _MAX_FEED)]:
|
|
@@ -695,6 +754,11 @@ class LitheApp(App):
|
|
|
695
754
|
from .tui import _CHAT_KEYS
|
|
696
755
|
|
|
697
756
|
self.state.say("dim", _CHAT_KEYS)
|
|
757
|
+
self._sync_feed()
|
|
758
|
+
if r.copy_scope:
|
|
759
|
+
# /copy: the front-end owns the text (the workbench only
|
|
760
|
+
# resolved the scope), so the copy happens here.
|
|
761
|
+
await self._copy_scope(r.copy_scope)
|
|
698
762
|
self._sync_feed()
|
|
699
763
|
if r.toggle_sidebar:
|
|
700
764
|
self.state.show_sidebar = not self.state.show_sidebar
|
|
@@ -945,6 +1009,86 @@ class LitheApp(App):
|
|
|
945
1009
|
def _picker_fetch_models(self, payload) -> None:
|
|
946
1010
|
asyncio.create_task(self.wb._fetch_and_report())
|
|
947
1011
|
|
|
1012
|
+
# -- copy ----------------------------------------------------------------------
|
|
1013
|
+
|
|
1014
|
+
def _scope_text(self, scope: str) -> str:
|
|
1015
|
+
"""The feed slice /copy hands to the clipboard (streaming included)."""
|
|
1016
|
+
return feed_text(self.state.feed, scope, extra=self.state.streaming)
|
|
1017
|
+
|
|
1018
|
+
async def _copy_text(self, text: str, label: str) -> bool:
|
|
1019
|
+
"""One copy through the layered channels (see lithe_cli.clipboard)."""
|
|
1020
|
+
ok, channel = await deliver_clipboard(text, app=self, home=lithe_home())
|
|
1021
|
+
if ok:
|
|
1022
|
+
self.state.say("ok", f"已复制{label}"
|
|
1023
|
+
f"({describe_copy(text)} → {channel})")
|
|
1024
|
+
else:
|
|
1025
|
+
self.state.say("err", f"复制{label}失败:{channel}")
|
|
1026
|
+
self._sync_feed()
|
|
1027
|
+
return ok
|
|
1028
|
+
|
|
1029
|
+
async def _copy_scope(self, scope: str) -> bool:
|
|
1030
|
+
label = COPY_SCOPE_LABELS.get(scope, scope)
|
|
1031
|
+
text = self._scope_text(scope)
|
|
1032
|
+
if not text.strip():
|
|
1033
|
+
self.state.say("warn", f"没有可复制的{label}(对话还是空的)")
|
|
1034
|
+
self._sync_feed()
|
|
1035
|
+
return False
|
|
1036
|
+
return await self._copy_text(text, label)
|
|
1037
|
+
|
|
1038
|
+
async def _copy_file(self) -> bool:
|
|
1039
|
+
"""Export the whole conversation under $LITHE_HOME (no clipboard)."""
|
|
1040
|
+
text = self._scope_text("all")
|
|
1041
|
+
path = write_clipboard_file(text, lithe_home())
|
|
1042
|
+
if path is None:
|
|
1043
|
+
self.state.say("err", "导出失败:无法写入 $LITHE_HOME")
|
|
1044
|
+
else:
|
|
1045
|
+
self.state.say("ok", "已导出整段对话"
|
|
1046
|
+
f"({describe_copy(text)})→ {path}")
|
|
1047
|
+
self._sync_feed()
|
|
1048
|
+
return path is not None
|
|
1049
|
+
|
|
1050
|
+
def open_copy_menu(self) -> None:
|
|
1051
|
+
"""The right-click copy menu (also the app-level right-click hook)."""
|
|
1052
|
+
selection = selected_text(self.screen, self)
|
|
1053
|
+
items: list[tuple[dict, str]] = []
|
|
1054
|
+
if selection:
|
|
1055
|
+
items.append(({"selection": True},
|
|
1056
|
+
f"复制选中文本({describe_copy(selection)})"))
|
|
1057
|
+
for scope in COPY_SCOPES:
|
|
1058
|
+
items.append(({"scope": scope}, f"复制{COPY_SCOPE_LABELS[scope]}"))
|
|
1059
|
+
items.append(({"file": True}, "整段对话存为文件($LITHE_HOME)"))
|
|
1060
|
+
# The modal takes the selection with it, so keep it here for the
|
|
1061
|
+
# callback instead of re-reading it after the dismiss.
|
|
1062
|
+
self._pending_selection = selection
|
|
1063
|
+
self.push_screen(
|
|
1064
|
+
PickerModal("复制", items, "Enter 复制 · Esc 关闭"),
|
|
1065
|
+
self._copy_picked,
|
|
1066
|
+
)
|
|
1067
|
+
|
|
1068
|
+
def _copy_picked(self, result) -> None:
|
|
1069
|
+
if not result or result[0] != "select" or not result[1]:
|
|
1070
|
+
return
|
|
1071
|
+
payload = result[1]
|
|
1072
|
+
if payload.get("selection"):
|
|
1073
|
+
if self._pending_selection:
|
|
1074
|
+
asyncio.create_task(
|
|
1075
|
+
self._copy_text(self._pending_selection, "选中文本"))
|
|
1076
|
+
return
|
|
1077
|
+
if payload.get("file"):
|
|
1078
|
+
asyncio.create_task(self._copy_file())
|
|
1079
|
+
return
|
|
1080
|
+
asyncio.create_task(self._copy_scope(payload.get("scope") or "last"))
|
|
1081
|
+
|
|
1082
|
+
def on_mouse_down(self, event) -> None:
|
|
1083
|
+
"""Right-click outside the conversation pane (header, sidebar,
|
|
1084
|
+
footer) gets the same copy menu — mouse reporting leaves the
|
|
1085
|
+
terminal's own menu unreachable in here."""
|
|
1086
|
+
if getattr(event, "button", 0) != 3:
|
|
1087
|
+
return
|
|
1088
|
+
if isinstance(self.screen, PickerModal):
|
|
1089
|
+
return
|
|
1090
|
+
self.open_copy_menu()
|
|
1091
|
+
|
|
948
1092
|
# -- keys -----------------------------------------------------------------------
|
|
949
1093
|
|
|
950
1094
|
def action_toggle_sidebar(self) -> None:
|
|
@@ -952,6 +1096,14 @@ class LitheApp(App):
|
|
|
952
1096
|
self._refresh_chrome()
|
|
953
1097
|
|
|
954
1098
|
def action_cancel_or_exit(self) -> None:
|
|
1099
|
+
text = selected_text(self.screen, self)
|
|
1100
|
+
if text:
|
|
1101
|
+
# A native-Ctrl+C reflex over a drag selection: copy it instead
|
|
1102
|
+
# of cancelling the turn (press again with nothing selected to
|
|
1103
|
+
# cancel/exit). Absent a selection API this is a no-op and the
|
|
1104
|
+
# documented cancel/exit behaviour stands.
|
|
1105
|
+
asyncio.create_task(self._copy_text(text, "选中文本"))
|
|
1106
|
+
return
|
|
955
1107
|
if self.state.running:
|
|
956
1108
|
if not self.wb.cancel(self._current_cid()):
|
|
957
1109
|
# One-shot run mode drives no workbench turn, so wb.cancel
|
|
@@ -10,6 +10,9 @@ remaining front-ends build on:
|
|
|
10
10
|
- :class:`TuiState` — kernel-event folding (feed, tools, usage
|
|
11
11
|
accounting) the Textual app renders from;
|
|
12
12
|
- :func:`transcript_feed_lines` — stored session messages → feed rows;
|
|
13
|
+
- :func:`parse_copy_scope` / :func:`feed_text` — what ``/copy`` lifts off
|
|
14
|
+
the feed (right-click and Ctrl+C over a selection go through the same
|
|
15
|
+
extraction in the Textual front-end);
|
|
13
16
|
- ``_CHAT_KEYS`` — the ``/keys`` help text.
|
|
14
17
|
|
|
15
18
|
Pure data and formatting only — no terminal ownership of any kind.
|
|
@@ -366,7 +369,87 @@ class TuiState:
|
|
|
366
369
|
|
|
367
370
|
_CHAT_KEYS = """按键:PgUp/PgDn 或鼠标滚轮 滚动对话,Home/End 跳到顶/底。
|
|
368
371
|
F2 侧栏 · F3 会话选择器 · F4 模型选择器 · F5 设置 · F6 推理强度(Esc 关闭)。
|
|
369
|
-
|
|
372
|
+
复制:右键菜单 或 /copy(默认最后一条回答;/copy all|user|tools)→ 系统剪贴板,
|
|
373
|
+
终端工具缺失时自动退到 OSC 52,再不行落到 $LITHE_HOME 的 clipboard-*.txt。
|
|
374
|
+
终端原生选区(Shift+拖拽)仍可用:选中后 Ctrl+C 复制,不再取消本轮;侧栏碍事时按 F2 隐藏。"""
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
# -- /copy: which feed rows land on the clipboard --------------------------------
|
|
378
|
+
|
|
379
|
+
# The scopes /copy accepts; ``last`` is the answer just given.
|
|
380
|
+
COPY_SCOPES = ("last", "all", "user", "tools")
|
|
381
|
+
|
|
382
|
+
COPY_SCOPE_HELP = "|".join(COPY_SCOPES)
|
|
383
|
+
|
|
384
|
+
COPY_SCOPE_LABELS = {
|
|
385
|
+
"last": "最后一条回答",
|
|
386
|
+
"all": "整段对话",
|
|
387
|
+
"user": "我的输入",
|
|
388
|
+
"tools": "工具输出",
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
_COPY_SCOPE_ALIASES = {
|
|
392
|
+
"": "last", "last": "last", "answer": "last", "回答": "last",
|
|
393
|
+
"all": "all", "全部": "all", "对话": "all",
|
|
394
|
+
"user": "user", "me": "user", "输入": "user", "我": "user",
|
|
395
|
+
"tools": "tools", "tool": "tools", "工具": "tools",
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
def parse_copy_scope(arg: str) -> str | None:
|
|
400
|
+
"""Normalise a ``/copy`` argument to one of :data:`COPY_SCOPES`.
|
|
401
|
+
|
|
402
|
+
``None`` means "not a scope" so the caller can report the usage instead
|
|
403
|
+
of silently copying something unexpected.
|
|
404
|
+
"""
|
|
405
|
+
return _COPY_SCOPE_ALIASES.get(str(arg or "").strip().lower())
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def feed_text(feed: list[tuple[str, str]], scope: str = "all",
|
|
409
|
+
extra: str = "") -> str:
|
|
410
|
+
"""Plain text of the conversation, for the clipboard (pure; tested).
|
|
411
|
+
|
|
412
|
+
``last`` is the newest assistant block — the answer just given —
|
|
413
|
+
``user`` the lines the user typed, ``tools`` the tool call/result
|
|
414
|
+
lines, ``all`` the whole feed. ``extra`` is the text still streaming:
|
|
415
|
+
it is not in the feed yet, which makes it *the* newest answer for
|
|
416
|
+
``last`` and a tail to append for ``all``.
|
|
417
|
+
"""
|
|
418
|
+
extra = str(extra or "").rstrip("\n")
|
|
419
|
+
if scope == "last" and extra.strip():
|
|
420
|
+
return extra.strip("\n")
|
|
421
|
+
if scope == "user":
|
|
422
|
+
lines = [text for cls, text in feed if cls == "user"]
|
|
423
|
+
elif scope == "tools":
|
|
424
|
+
lines = [text for cls, text in feed if cls in ("tool", "ok", "err")]
|
|
425
|
+
elif scope == "last":
|
|
426
|
+
lines = _last_answer(feed)
|
|
427
|
+
else:
|
|
428
|
+
lines = [text for _cls, text in feed]
|
|
429
|
+
text = "\n".join(lines).strip("\n")
|
|
430
|
+
if extra and scope == "all":
|
|
431
|
+
text = f"{text}\n{extra}".strip("\n")
|
|
432
|
+
return text
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
def _last_answer(feed: list[tuple[str, str]]) -> list[str]:
|
|
436
|
+
"""The trailing run of assistant rows (one answer, gap-free)."""
|
|
437
|
+
end = next(
|
|
438
|
+
(i for i in range(len(feed) - 1, -1, -1)
|
|
439
|
+
if feed[i][0] == "assistant" and str(feed[i][1]).strip()),
|
|
440
|
+
None,
|
|
441
|
+
)
|
|
442
|
+
if end is None:
|
|
443
|
+
return []
|
|
444
|
+
start = end
|
|
445
|
+
while start > 0 and feed[start - 1][0] == "assistant":
|
|
446
|
+
start -= 1
|
|
447
|
+
return [text for _cls, text in feed[start:end + 1]]
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
def describe_copy(text: str) -> str:
|
|
451
|
+
"""``N 行 · M 字符`` — the confirmation tail after a finished copy."""
|
|
452
|
+
return f"{len(text.splitlines())} 行 · {len(text)} 字符"
|
|
370
453
|
|
|
371
454
|
|
|
372
455
|
def transcript_feed_lines(rows):
|
|
@@ -30,6 +30,7 @@ from .commands import ActionResult, help_text
|
|
|
30
30
|
from .config import Config
|
|
31
31
|
from .profiles import ProfileStore, fetch_models
|
|
32
32
|
from .sessions import SessionManager, auto_title, format_session_rows
|
|
33
|
+
from .tui import COPY_SCOPE_HELP, parse_copy_scope
|
|
33
34
|
|
|
34
35
|
# Session-adjustable settings for /set: (user key, cfg attr, label, kind).
|
|
35
36
|
# Order is the /set display order. Only per-turn assembly inputs belong
|
|
@@ -718,6 +719,14 @@ class Workbench:
|
|
|
718
719
|
save = "--save" in arg
|
|
719
720
|
level = arg.replace("--save", "").strip()
|
|
720
721
|
return self.set_reasoning(level, save=save)
|
|
722
|
+
if cmd == "copy":
|
|
723
|
+
scope = parse_copy_scope(arg)
|
|
724
|
+
if scope is None:
|
|
725
|
+
result.say("err", f"用法:/copy [{COPY_SCOPE_HELP}]"
|
|
726
|
+
"(不写参数即最后一条回答)")
|
|
727
|
+
return result
|
|
728
|
+
result.copy_scope = scope
|
|
729
|
+
return result
|
|
721
730
|
if cmd == "sidebar":
|
|
722
731
|
result.toggle_sidebar = True
|
|
723
732
|
return result
|
|
@@ -4,6 +4,7 @@ pyproject.toml
|
|
|
4
4
|
lithe_cli/__init__.py
|
|
5
5
|
lithe_cli/__main__.py
|
|
6
6
|
lithe_cli/agent.py
|
|
7
|
+
lithe_cli/clipboard.py
|
|
7
8
|
lithe_cli/commands.py
|
|
8
9
|
lithe_cli/config.py
|
|
9
10
|
lithe_cli/main.py
|
|
@@ -24,6 +25,7 @@ lithe_cli.egg-info/requires.txt
|
|
|
24
25
|
lithe_cli.egg-info/top_level.txt
|
|
25
26
|
tests/test_cli.py
|
|
26
27
|
tests/test_cli_budget_steer.py
|
|
28
|
+
tests/test_cli_clipboard.py
|
|
27
29
|
tests/test_cli_guard.py
|
|
28
30
|
tests/test_cli_sessions.py
|
|
29
31
|
tests/test_cli_subagents.py
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
"""Clipboard delivery: channel order, platform tools, file fallback.
|
|
2
|
+
|
|
3
|
+
Offline by construction: the native tools are faked (PATH lookups are
|
|
4
|
+
monkeypatched, the one real subprocess is this interpreter reading stdin)
|
|
5
|
+
and OSC 52 is stubbed, so nothing here touches the host clipboard.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import asyncio
|
|
11
|
+
import sys
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from lithe_cli import clipboard
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _deliver(text: str, home: Path, app=None):
|
|
18
|
+
"""deliver_clipboard with an explicit home (the async seam it needs)."""
|
|
19
|
+
return asyncio.run(clipboard.deliver_clipboard(text, app=app, home=home))
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def test_native_command_matches_platform(monkeypatch):
|
|
23
|
+
monkeypatch.setattr(clipboard.shutil, "which", lambda name: f"/x/{name}")
|
|
24
|
+
|
|
25
|
+
# sys.platform is checked first, so both attributes must be set per case.
|
|
26
|
+
monkeypatch.setattr(clipboard.sys, "platform", "darwin")
|
|
27
|
+
monkeypatch.setattr(clipboard.os, "name", "posix")
|
|
28
|
+
assert clipboard.native_clipboard_command() == ["pbcopy"]
|
|
29
|
+
|
|
30
|
+
monkeypatch.setattr(clipboard.sys, "platform", "win32")
|
|
31
|
+
monkeypatch.setattr(clipboard.os, "name", "nt")
|
|
32
|
+
assert clipboard.native_clipboard_command() == ["clip"]
|
|
33
|
+
|
|
34
|
+
monkeypatch.setattr(clipboard.sys, "platform", "linux")
|
|
35
|
+
monkeypatch.setattr(clipboard.os, "name", "posix")
|
|
36
|
+
# Wayland first, then X11 — the first tool that exists wins.
|
|
37
|
+
assert clipboard.native_clipboard_command() == ["wl-copy"]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def test_native_command_none_when_nothing_installed(monkeypatch):
|
|
41
|
+
monkeypatch.setattr(clipboard.shutil, "which", lambda name: None)
|
|
42
|
+
assert clipboard.native_clipboard_command() is None
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def test_clip_tool_gets_utf16_but_unix_tools_get_utf8(monkeypatch):
|
|
46
|
+
"""clip.exe reads UTF-16LE from a pipe (cmd's convention) while the
|
|
47
|
+
Unix helpers read UTF-8; the encoding must follow the tool."""
|
|
48
|
+
seen: list[bytes] = []
|
|
49
|
+
|
|
50
|
+
class _Proc:
|
|
51
|
+
returncode = 0
|
|
52
|
+
|
|
53
|
+
def fake_run(argv, input=None, **kw): # noqa: A002 — mirrors subprocess API
|
|
54
|
+
seen.append(input)
|
|
55
|
+
return _Proc()
|
|
56
|
+
|
|
57
|
+
monkeypatch.setattr(clipboard.subprocess, "run", fake_run)
|
|
58
|
+
assert clipboard.pipe_to_clipboard("中文", ["clip"])
|
|
59
|
+
assert clipboard.pipe_to_clipboard("中文", ["pbcopy"])
|
|
60
|
+
assert seen[0] == "中文".encode("utf-16-le")
|
|
61
|
+
assert seen[1] == "中文".encode()
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def test_pipe_reports_failure_without_raising(monkeypatch):
|
|
65
|
+
class _Proc:
|
|
66
|
+
returncode = 1
|
|
67
|
+
|
|
68
|
+
monkeypatch.setattr(clipboard.subprocess, "run", lambda *a, **k: _Proc())
|
|
69
|
+
assert clipboard.pipe_to_clipboard("x", ["pbcopy"]) is False
|
|
70
|
+
|
|
71
|
+
def boom(*a, **k):
|
|
72
|
+
raise OSError("no such tool")
|
|
73
|
+
|
|
74
|
+
monkeypatch.setattr(clipboard.subprocess, "run", boom)
|
|
75
|
+
assert clipboard.pipe_to_clipboard("x", ["pbcopy"]) is False
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def test_pipe_runs_for_real_through_this_interpreter():
|
|
79
|
+
"""One end-to-end pipe (no clipboard involved): a process that reads
|
|
80
|
+
stdin and exits 0 counts as a delivered copy."""
|
|
81
|
+
code = "import sys; sys.stdin.buffer.read()"
|
|
82
|
+
assert clipboard.pipe_to_clipboard("hello 中文",
|
|
83
|
+
[sys.executable, "-c", code])
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def test_write_clipboard_file_adds_newline_and_timestamps(tmp_path):
|
|
87
|
+
path = clipboard.write_clipboard_file("第一行\n第二行", tmp_path)
|
|
88
|
+
assert path is not None and path.parent == tmp_path
|
|
89
|
+
assert path.name.startswith("clipboard-") and path.suffix == ".txt"
|
|
90
|
+
assert path.read_text(encoding="utf-8") == "第一行\n第二行\n"
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def test_write_clipboard_file_survives_an_unwritable_home(tmp_path):
|
|
94
|
+
# A path whose parent is a *file* cannot be created: report, don't raise.
|
|
95
|
+
blocker = tmp_path / "home"
|
|
96
|
+
blocker.write_text("not a dir", encoding="utf-8")
|
|
97
|
+
assert clipboard.write_clipboard_file("x", blocker / "sub") is None
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def test_deliver_prefers_the_native_tool(monkeypatch, tmp_path):
|
|
101
|
+
calls: list[str] = []
|
|
102
|
+
monkeypatch.setattr(clipboard, "native_clipboard_command",
|
|
103
|
+
lambda: ["pbcopy"])
|
|
104
|
+
monkeypatch.setattr(clipboard, "pipe_to_clipboard",
|
|
105
|
+
lambda text, argv: calls.append(text) or True)
|
|
106
|
+
ok, channel = _deliver("hello", tmp_path)
|
|
107
|
+
assert (ok, channel) == (True, "pbcopy")
|
|
108
|
+
assert calls == ["hello"]
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def test_deliver_falls_back_to_osc52_when_tools_are_missing(
|
|
112
|
+
monkeypatch, tmp_path):
|
|
113
|
+
monkeypatch.setattr(clipboard, "native_clipboard_command", lambda: None)
|
|
114
|
+
copied: list[str] = []
|
|
115
|
+
|
|
116
|
+
async def fake_osc52(app, text):
|
|
117
|
+
copied.append(text)
|
|
118
|
+
return True
|
|
119
|
+
|
|
120
|
+
monkeypatch.setattr(clipboard, "_osc52", fake_osc52)
|
|
121
|
+
ok, channel = _deliver("hello", tmp_path, app=object())
|
|
122
|
+
assert (ok, channel) == (True, "OSC 52")
|
|
123
|
+
assert copied == ["hello"]
|
|
124
|
+
# No file was needed, so the fallback stayed unused.
|
|
125
|
+
assert list(tmp_path.glob("clipboard-*")) == []
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def test_deliver_falls_back_to_a_file_when_nothing_else_works(
|
|
129
|
+
monkeypatch, tmp_path):
|
|
130
|
+
monkeypatch.setattr(clipboard, "native_clipboard_command", lambda: None)
|
|
131
|
+
|
|
132
|
+
async def no_osc52(app, text):
|
|
133
|
+
return False
|
|
134
|
+
|
|
135
|
+
monkeypatch.setattr(clipboard, "_osc52", no_osc52)
|
|
136
|
+
ok, channel = _deliver("hello", tmp_path, app=object())
|
|
137
|
+
assert ok is True
|
|
138
|
+
assert Path(channel).read_text(encoding="utf-8") == "hello\n"
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def test_deliver_reports_when_every_channel_fails(monkeypatch, tmp_path):
|
|
142
|
+
monkeypatch.setattr(clipboard, "native_clipboard_command", lambda: None)
|
|
143
|
+
monkeypatch.setattr(clipboard, "write_clipboard_file", lambda *a, **k: None)
|
|
144
|
+
ok, channel = _deliver("hello", tmp_path)
|
|
145
|
+
assert ok is False and "不可用" in channel
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def test_osc52_tolerates_apps_without_the_api():
|
|
149
|
+
class _NoApi:
|
|
150
|
+
pass
|
|
151
|
+
|
|
152
|
+
class _Boom:
|
|
153
|
+
def copy_to_clipboard(self, text):
|
|
154
|
+
raise RuntimeError("no driver")
|
|
155
|
+
|
|
156
|
+
class _Sync:
|
|
157
|
+
def __init__(self):
|
|
158
|
+
self.copied = []
|
|
159
|
+
|
|
160
|
+
def copy_to_clipboard(self, text):
|
|
161
|
+
self.copied.append(text)
|
|
162
|
+
|
|
163
|
+
class _Async:
|
|
164
|
+
def __init__(self):
|
|
165
|
+
self.copied = []
|
|
166
|
+
|
|
167
|
+
async def copy_to_clipboard(self, text):
|
|
168
|
+
self.copied.append(text)
|
|
169
|
+
|
|
170
|
+
assert asyncio.run(clipboard._osc52(_NoApi(), "x")) is False
|
|
171
|
+
assert asyncio.run(clipboard._osc52(_Boom(), "x")) is False
|
|
172
|
+
|
|
173
|
+
sync_app = _Sync()
|
|
174
|
+
assert asyncio.run(clipboard._osc52(sync_app, "x")) is True
|
|
175
|
+
assert sync_app.copied == ["x"]
|
|
176
|
+
|
|
177
|
+
async_app = _Async()
|
|
178
|
+
assert asyncio.run(clipboard._osc52(async_app, "x")) is True
|
|
179
|
+
assert async_app.copied == ["x"]
|
|
@@ -40,6 +40,52 @@ def test_resume_accepts_hash_prefixed_id(tmp_path):
|
|
|
40
40
|
assert wb.sessions.resolve(str(ids[2]))["id"] == ids[2]
|
|
41
41
|
|
|
42
42
|
|
|
43
|
+
def test_sessions_export_prints_plain_text_for_piping(tmp_path, capsys):
|
|
44
|
+
"""`lithe sessions --export 12 | pbcopy` is the non-TTY copy path: the
|
|
45
|
+
text must land on stdout with no tables, markup or color codes."""
|
|
46
|
+
from lithe_cli.main import main
|
|
47
|
+
|
|
48
|
+
wb, ids = _make_sessions(tmp_path, n=1)
|
|
49
|
+
store_args = ["--store", str(wb.cfg.store_dir), "--user", wb.cfg.user_id]
|
|
50
|
+
|
|
51
|
+
assert main(["sessions", *store_args, "--export", str(ids[0])]) == 0
|
|
52
|
+
out = capsys.readouterr().out
|
|
53
|
+
assert "任务 0" in out and "已写入 a.txt。" in out
|
|
54
|
+
# Plain text for a pipe: no ANSI, and the conversation's own rows
|
|
55
|
+
# (tool-call markers included) verbatim — not the sidebar's markup.
|
|
56
|
+
assert "\x1b[" not in out
|
|
57
|
+
assert "◆ write_file" in out and "F3" not in out
|
|
58
|
+
|
|
59
|
+
assert main(["sessions", *store_args, "--export", "999"]) == 1
|
|
60
|
+
assert "找不到" in capsys.readouterr().out
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def test_plain_repl_copy_command_reaches_the_clipboard(
|
|
64
|
+
tmp_path, monkeypatch, capsys):
|
|
65
|
+
"""The plain REPL has no feed, so /copy rebuilds the rows from the
|
|
66
|
+
store transcript and sends them through the same channels. There is
|
|
67
|
+
no app to ask for OSC 52 here, so the platform tool (or the file
|
|
68
|
+
fallback) is what delivers it."""
|
|
69
|
+
from lithe_cli import main as main_mod
|
|
70
|
+
from lithe_cli import prompts
|
|
71
|
+
from lithe_cli import clipboard as clipboard_mod
|
|
72
|
+
|
|
73
|
+
wb, ids = _make_sessions(tmp_path, n=1)
|
|
74
|
+
copied: list[str] = []
|
|
75
|
+
monkeypatch.setenv("LITHE_HOME", str(tmp_path / "home"))
|
|
76
|
+
monkeypatch.setattr(clipboard_mod, "native_clipboard_command",
|
|
77
|
+
lambda: ["pbcopy"])
|
|
78
|
+
monkeypatch.setattr(clipboard_mod, "pipe_to_clipboard",
|
|
79
|
+
lambda text, argv: copied.append(text) or True)
|
|
80
|
+
lines = iter(["/copy", "/exit"])
|
|
81
|
+
monkeypatch.setattr(prompts, "chat_line", lambda *a, **k: next(lines))
|
|
82
|
+
|
|
83
|
+
assert main_mod._chat_loop(wb.cfg, resume=str(ids[0])) == 0
|
|
84
|
+
assert copied and copied[0] == "已写入 a.txt。"
|
|
85
|
+
out = capsys.readouterr().out
|
|
86
|
+
assert "已复制最后一条回答" in out and "pbcopy" in out
|
|
87
|
+
|
|
88
|
+
|
|
43
89
|
def test_sessions_subcommand_lists_renames_deletes(tmp_path, capsys):
|
|
44
90
|
from lithe_cli.main import main
|
|
45
91
|
|
|
@@ -12,6 +12,8 @@ textual = pytest.importorskip("textual")
|
|
|
12
12
|
|
|
13
13
|
from textual.containers import VerticalScroll # noqa: E402
|
|
14
14
|
|
|
15
|
+
from lithe_cli import clipboard as clipboard_mod # noqa: E402
|
|
16
|
+
|
|
15
17
|
from lithe_cli.ttui import ( # noqa: E402
|
|
16
18
|
LitheApp,
|
|
17
19
|
PickerModal,
|
|
@@ -27,6 +29,34 @@ WRITE_THEN_ANSWER = [
|
|
|
27
29
|
]
|
|
28
30
|
|
|
29
31
|
|
|
32
|
+
# -- copy: hermetic clipboard ------------------------------------------------
|
|
33
|
+
|
|
34
|
+
@pytest.fixture
|
|
35
|
+
def copied(monkeypatch):
|
|
36
|
+
"""Capture what the app sends to the clipboard, whichever channel."""
|
|
37
|
+
sink: list[str] = []
|
|
38
|
+
|
|
39
|
+
async def fake_osc52(app, text):
|
|
40
|
+
sink.append(text)
|
|
41
|
+
return True
|
|
42
|
+
|
|
43
|
+
monkeypatch.setattr(clipboard_mod, "native_clipboard_command", lambda: None)
|
|
44
|
+
monkeypatch.setattr(clipboard_mod, "_osc52", fake_osc52)
|
|
45
|
+
return sink
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class _RightClick:
|
|
49
|
+
"""Stand-in for Textual's MouseDown with button=3 (no driver needed)."""
|
|
50
|
+
|
|
51
|
+
button = 3
|
|
52
|
+
|
|
53
|
+
def __init__(self):
|
|
54
|
+
self.stopped = False
|
|
55
|
+
|
|
56
|
+
def stop(self):
|
|
57
|
+
self.stopped = True
|
|
58
|
+
|
|
59
|
+
|
|
30
60
|
def _app(tmp_path, responses, mode="chat"):
|
|
31
61
|
cfg = make_config(tmp_path, responses)
|
|
32
62
|
return LitheApp(cfg, "示例任务" if mode == "run" else None, mode)
|
|
@@ -347,7 +377,10 @@ def test_completion_suggestions_commands_and_args():
|
|
|
347
377
|
|
|
348
378
|
got = completion_suggestions("/mo", COMMANDS, [], [], [])
|
|
349
379
|
assert got[:2] == ["/model ", "/models "]
|
|
350
|
-
|
|
380
|
+
# "/" lists commands alphabetically, so /copy now leads the list
|
|
381
|
+
assert completion_suggestions("/", COMMANDS, [], [], [])[:2] == \
|
|
382
|
+
["/copy ", "/exit "]
|
|
383
|
+
assert completion_suggestions("/co", COMMANDS, [], [], []) == ["/copy "]
|
|
351
384
|
assert completion_suggestions("普通输入", COMMANDS, [], [], []) == []
|
|
352
385
|
assert completion_suggestions(
|
|
353
386
|
"/model glm-4.5", COMMANDS, ["glm-4.6", "glm-4.5-air"], [], []
|
|
@@ -513,3 +546,166 @@ def test_command_output_refreshes_model_candidates(tmp_path):
|
|
|
513
546
|
assert "端点返回" in _conv_text(app)
|
|
514
547
|
|
|
515
548
|
asyncio.run(scenario())
|
|
549
|
+
|
|
550
|
+
|
|
551
|
+
# --- copy: right-click, /copy, Ctrl+C over a selection, verbatim text --------
|
|
552
|
+
|
|
553
|
+
|
|
554
|
+
def test_right_click_on_the_conversation_opens_the_copy_menu(
|
|
555
|
+
tmp_path, copied):
|
|
556
|
+
"""Mouse reporting swallows the terminal's own context menu, so the
|
|
557
|
+
pane must answer button=3 itself (and stop the event, or the app
|
|
558
|
+
handler would open a second menu)."""
|
|
559
|
+
|
|
560
|
+
async def scenario():
|
|
561
|
+
app = _app(tmp_path, [])
|
|
562
|
+
async with app.run_test(size=(100, 30)) as pilot:
|
|
563
|
+
await pilot.pause()
|
|
564
|
+
app.state.say("assistant", "答案第一行")
|
|
565
|
+
app._sync_feed()
|
|
566
|
+
await pilot.pause()
|
|
567
|
+
|
|
568
|
+
event = _RightClick()
|
|
569
|
+
app.query_one("#conv").on_mouse_down(event)
|
|
570
|
+
await pilot.pause()
|
|
571
|
+
assert event.stopped, "pane handler must consume the click"
|
|
572
|
+
assert isinstance(app.screen, PickerModal)
|
|
573
|
+
payloads = [payload for payload, _ in app.screen.items]
|
|
574
|
+
assert [p.get("scope") for p in payloads if "scope" in p] == \
|
|
575
|
+
["last", "all", "user", "tools"]
|
|
576
|
+
assert not any("selection" in p for p in payloads)
|
|
577
|
+
|
|
578
|
+
app.screen.query_one("#picker-list").index = 1 # 复制整段对话
|
|
579
|
+
await pilot.press("enter")
|
|
580
|
+
await pilot.pause()
|
|
581
|
+
assert copied and "答案第一行" in copied[-1]
|
|
582
|
+
assert "已复制整段对话" in _conv_text(app)
|
|
583
|
+
|
|
584
|
+
asyncio.run(scenario())
|
|
585
|
+
|
|
586
|
+
|
|
587
|
+
def test_right_click_offers_the_selection_when_there_is_one(
|
|
588
|
+
tmp_path, copied, monkeypatch):
|
|
589
|
+
async def scenario():
|
|
590
|
+
app = _app(tmp_path, [])
|
|
591
|
+
async with app.run_test(size=(100, 30)) as pilot:
|
|
592
|
+
await pilot.pause()
|
|
593
|
+
monkeypatch.setattr("lithe_cli.ttui.selected_text",
|
|
594
|
+
lambda *a: "拖选出来的两行")
|
|
595
|
+
app.state.say("assistant", "答案")
|
|
596
|
+
app._sync_feed()
|
|
597
|
+
app.open_copy_menu()
|
|
598
|
+
await pilot.pause()
|
|
599
|
+
payloads = [payload for payload, _ in app.screen.items]
|
|
600
|
+
assert payloads[0] == {"selection": True}
|
|
601
|
+
await pilot.press("enter")
|
|
602
|
+
await pilot.pause()
|
|
603
|
+
assert copied[-1] == "拖选出来的两行"
|
|
604
|
+
assert "已复制选中文本" in _conv_text(app)
|
|
605
|
+
|
|
606
|
+
asyncio.run(scenario())
|
|
607
|
+
|
|
608
|
+
|
|
609
|
+
def test_copy_command_copies_the_last_answer(tmp_path, copied):
|
|
610
|
+
async def scenario():
|
|
611
|
+
app = _app(tmp_path, [])
|
|
612
|
+
async with app.run_test(size=(100, 30)) as pilot:
|
|
613
|
+
await pilot.pause()
|
|
614
|
+
app.state.say("user", "把 a.txt 改一下")
|
|
615
|
+
app.state.say("assistant", "已经改好了。")
|
|
616
|
+
app.state.say("assistant", "还要提交吗?")
|
|
617
|
+
app._sync_feed()
|
|
618
|
+
await pilot.pause()
|
|
619
|
+
|
|
620
|
+
prompt = app.query_one("#prompt")
|
|
621
|
+
prompt.value = "/copy"
|
|
622
|
+
await pilot.press("enter")
|
|
623
|
+
await pilot.pause()
|
|
624
|
+
assert copied[-1] == "已经改好了。\n还要提交吗?"
|
|
625
|
+
|
|
626
|
+
prompt.value = "/copy user"
|
|
627
|
+
await pilot.press("enter")
|
|
628
|
+
await pilot.pause()
|
|
629
|
+
assert copied[-1] == "把 a.txt 改一下"
|
|
630
|
+
|
|
631
|
+
asyncio.run(scenario())
|
|
632
|
+
|
|
633
|
+
|
|
634
|
+
def test_copy_command_rejects_an_unknown_scope(tmp_path, copied):
|
|
635
|
+
async def scenario():
|
|
636
|
+
app = _app(tmp_path, [])
|
|
637
|
+
async with app.run_test(size=(100, 30)) as pilot:
|
|
638
|
+
await pilot.pause()
|
|
639
|
+
app.query_one("#prompt").value = "/copy 乱七八糟"
|
|
640
|
+
await pilot.press("enter")
|
|
641
|
+
await pilot.pause()
|
|
642
|
+
text = _conv_text(app)
|
|
643
|
+
assert "用法" in text and "/copy" in text
|
|
644
|
+
assert copied == [], "a bad scope must not copy anything"
|
|
645
|
+
|
|
646
|
+
asyncio.run(scenario())
|
|
647
|
+
|
|
648
|
+
|
|
649
|
+
def test_copy_on_an_empty_conversation_says_so(tmp_path, copied):
|
|
650
|
+
async def scenario():
|
|
651
|
+
app = _app(tmp_path, [])
|
|
652
|
+
async with app.run_test(size=(100, 30)) as pilot:
|
|
653
|
+
await pilot.pause()
|
|
654
|
+
app.query_one("#prompt").value = "/copy all"
|
|
655
|
+
await pilot.press("enter")
|
|
656
|
+
await pilot.pause()
|
|
657
|
+
assert "没有可复制" in _conv_text(app)
|
|
658
|
+
assert copied == []
|
|
659
|
+
|
|
660
|
+
asyncio.run(scenario())
|
|
661
|
+
|
|
662
|
+
|
|
663
|
+
def test_ctrl_c_copies_a_selection_instead_of_cancelling(
|
|
664
|
+
tmp_path, copied, monkeypatch):
|
|
665
|
+
"""The native Ctrl+C reflex over a drag selection must not kill the
|
|
666
|
+
turn; with nothing selected Ctrl+C still cancels."""
|
|
667
|
+
monkeypatch.setattr("lithe_cli.ttui.selected_text",
|
|
668
|
+
lambda *a: "选中了这一段")
|
|
669
|
+
|
|
670
|
+
async def scenario():
|
|
671
|
+
app = _app(tmp_path, [])
|
|
672
|
+
async with app.run_test(size=(100, 30)) as pilot:
|
|
673
|
+
await pilot.pause()
|
|
674
|
+
await pilot.press("ctrl+c")
|
|
675
|
+
await pilot.pause()
|
|
676
|
+
assert copied == ["选中了这一段"]
|
|
677
|
+
assert app.is_running, "Ctrl+C over a selection must not exit"
|
|
678
|
+
assert "已复制选中文本" in _conv_text(app)
|
|
679
|
+
|
|
680
|
+
# No selection: the documented exit path is untouched.
|
|
681
|
+
monkeypatch.setattr("lithe_cli.ttui.selected_text", lambda *a: "")
|
|
682
|
+
await pilot.press("ctrl+c")
|
|
683
|
+
await pilot.pause()
|
|
684
|
+
|
|
685
|
+
asyncio.run(scenario())
|
|
686
|
+
|
|
687
|
+
|
|
688
|
+
def test_feed_text_is_renderable_verbatim_not_as_markup(tmp_path, copied):
|
|
689
|
+
"""Model output is data: a "[dim]" in an answer must reach both the
|
|
690
|
+
screen and the clipboard exactly as written (markup parsing would
|
|
691
|
+
swallow it, and every caller reads widget content back for /copy)."""
|
|
692
|
+
answer = "用 [dim] 标灰,用 [/] 收尾"
|
|
693
|
+
|
|
694
|
+
async def scenario():
|
|
695
|
+
app = _app(tmp_path, [])
|
|
696
|
+
async with app.run_test(size=(100, 30)) as pilot:
|
|
697
|
+
await pilot.pause()
|
|
698
|
+
app.state.say("assistant", answer)
|
|
699
|
+
app._sync_feed()
|
|
700
|
+
await pilot.pause()
|
|
701
|
+
rendered = [str(s.content) for s in app.query("#conv Static")]
|
|
702
|
+
assert answer in rendered
|
|
703
|
+
prompt = app.query_one("#prompt")
|
|
704
|
+
prompt.value = "/copy"
|
|
705
|
+
await pilot.press("enter")
|
|
706
|
+
await pilot.pause()
|
|
707
|
+
assert copied[-1] == answer
|
|
708
|
+
|
|
709
|
+
asyncio.run(scenario())
|
|
710
|
+
|
|
711
|
+
asyncio.run(scenario())
|
|
@@ -10,7 +10,66 @@ from lithe_cli.ttui import (
|
|
|
10
10
|
header_text,
|
|
11
11
|
sidebar_markup,
|
|
12
12
|
)
|
|
13
|
-
from lithe_cli.tui import
|
|
13
|
+
from lithe_cli.tui import (
|
|
14
|
+
COPY_SCOPES,
|
|
15
|
+
TuiState,
|
|
16
|
+
describe_copy,
|
|
17
|
+
feed_text,
|
|
18
|
+
parse_copy_scope,
|
|
19
|
+
transcript_feed_lines,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def test_parse_copy_scope_accepts_aliases_and_rejects_junk():
|
|
24
|
+
assert parse_copy_scope("") == "last"
|
|
25
|
+
assert parse_copy_scope(" last ") == "last"
|
|
26
|
+
assert parse_copy_scope("全部") == "all"
|
|
27
|
+
assert parse_copy_scope("工具") == "tools"
|
|
28
|
+
assert parse_copy_scope("输入") == "user"
|
|
29
|
+
assert parse_copy_scope("nonsense") is None
|
|
30
|
+
assert set(COPY_SCOPES) == {"last", "all", "user", "tools"}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def test_feed_text_scopes_pick_the_right_rows():
|
|
34
|
+
feed = [
|
|
35
|
+
("user", "把 a.txt 改一下"),
|
|
36
|
+
("tool", "◆ edit_file"),
|
|
37
|
+
("ok", "✓ 编辑 a.txt(+3 -1 行) 0.0s"),
|
|
38
|
+
("assistant", "已完成。"),
|
|
39
|
+
("assistant", "还要我提交吗?"),
|
|
40
|
+
("dim", " · read_file:a.txt(12 行)"),
|
|
41
|
+
]
|
|
42
|
+
assert feed_text(feed, "all").splitlines()[0] == "把 a.txt 改一下"
|
|
43
|
+
assert feed_text(feed, "user") == "把 a.txt 改一下"
|
|
44
|
+
# The whole trailing assistant run is one answer, not just its last row.
|
|
45
|
+
assert feed_text(feed, "last") == "已完成。\n还要我提交吗?"
|
|
46
|
+
tools = feed_text(feed, "tools")
|
|
47
|
+
assert "◆ edit_file" in tools and "✓ 编辑 a.txt" in tools
|
|
48
|
+
assert "已完成。" not in tools
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def test_feed_text_last_does_not_walk_into_earlier_answers():
|
|
52
|
+
feed = [
|
|
53
|
+
("assistant", "第一轮回答"),
|
|
54
|
+
("user", "追问"),
|
|
55
|
+
("assistant", "第二轮回答"),
|
|
56
|
+
]
|
|
57
|
+
assert feed_text(feed, "last") == "第二轮回答"
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def test_feed_text_streaming_text_is_the_newest_answer():
|
|
61
|
+
feed = [("assistant", "上一轮")]
|
|
62
|
+
# The in-flight answer is not in the feed yet: it *is* the last answer.
|
|
63
|
+
assert feed_text(feed, "last", extra="正在写的回答") == "正在写的回答"
|
|
64
|
+
# ...and it is appended as a tail for the whole-conversation copy.
|
|
65
|
+
assert feed_text(feed, "all", extra="正在写的回答") == \
|
|
66
|
+
"上一轮\n正在写的回答"
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def test_feed_text_empty_feed_yields_empty_text():
|
|
70
|
+
assert feed_text([], "last") == ""
|
|
71
|
+
assert feed_text([], "all") == ""
|
|
72
|
+
assert describe_copy("a\nb") == "2 行 · 3 字符"
|
|
14
73
|
|
|
15
74
|
|
|
16
75
|
def test_sidebar_sections_show_session_and_model():
|
|
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
|
|
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
|
|
File without changes
|