Skip to content

Commit 403faab

Browse files
authored
Merge pull request #173 from kalil0321/kalil0321/session-copy
feat(session): drag over the conversation to select and copy its text
2 parents 8d7cd9c + 37474b8 commit 403faab

8 files changed

Lines changed: 531 additions & 17 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
99

1010
### Added
1111
- **`hermes` backend**: `"sdk": "hermes"` engineers a saved capture through the local [`hermes` CLI](https://hermes-agent.nousresearch.com/docs) (`hermes chat --oneshot --format stream-json`), so a run needs no API key in rae — the model, the provider and the authentication are the user's own Hermes configuration. `hermes chat` reads the prompt on stdin, so nothing the model reads is shell-parsed; `hermes_max_turns` overrides the turn cap from the user's Hermes config; runs start with `--ignore-rules` so an `AGENTS.md`/`CLAUDE.md` cannot steer them, and estimate cost from the CLI's token counts, leaving it at 0 for a model with no known price. The backend covers `engineer` only: with `"sdk": "hermes"` the `agent` command stops before browser setup, so capture with another SDK (claude, opencode, copilot or cursor) and engineer that run with hermes; `agent --dry-run` reports the same error. The CLI is found on `PATH` or through `RAE_HERMES_BIN`, and `agent --dry-run` reports it as a check.
12+
- **Copy text from the session**: the session takes the mouse for the wheel and for clicking files and links, so the terminal could not select its text. Dragging over the conversation now selects it and copies it to the clipboard when you let go, with `pbcopy`, `wl-copy`, `xclip` or `xsel`, or through the terminal (OSC 52) otherwise and over SSH. A click without a drag still opens a link.
1213

1314
## [0.15.0] - 2026-11-08
1415

‎src/reverse_api/repl/app.py‎

Lines changed: 113 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
import time
1919
import warnings
2020
from collections.abc import Callable
21-
from concurrent.futures import Future
21+
from concurrent.futures import Future, ThreadPoolExecutor
2222
from datetime import datetime
2323
from pathlib import Path
2424
from typing import IO, Any, cast
@@ -35,20 +35,33 @@
3535
from prompt_toolkit.key_binding import KeyBindings, KeyPressEvent, merge_key_bindings
3636
from prompt_toolkit.key_binding.defaults import load_key_bindings
3737
from prompt_toolkit.layout import ConditionalContainer, HSplit, Layout, VSplit, Window
38-
from prompt_toolkit.layout.controls import BufferControl, FormattedTextControl
3938
from prompt_toolkit.layout.processors import AfterInput, ConditionalProcessor
4039
from prompt_toolkit.lexers import Lexer
40+
from prompt_toolkit.mouse_events import MouseButton, MouseEvent, MouseEventType
4141
from prompt_toolkit.output import create_output
4242
from prompt_toolkit.styles import Style
4343
from rich.console import Console, RenderableType
4444
from rich.text import Text
4545

4646
from ..messages import MessageStore
4747
from ..utils import recorded_cost, usage_tokens
48-
from . import settings
48+
from . import clipboard, settings
4949
from .bridge import Bridge, LedgerUI, activate, first_line, short_name
5050
from .style import DIM, INK, SKY, THEME, height, width
51-
from .transcript import Raw, Transcript, TranscriptControl, TranscriptWriter
51+
from .transcript import (
52+
LINE_END,
53+
InputBelow,
54+
Line,
55+
Raw,
56+
Selection,
57+
TextBelow,
58+
Transcript,
59+
TranscriptControl,
60+
TranscriptWriter,
61+
highlight,
62+
selected_text,
63+
text_of,
64+
)
5265
from .view import EFFORTS, LedgerView, Picker, SessionState, model_label, run_summary
5366

5467
MODES = {
@@ -88,6 +101,7 @@
88101
("ctrl+o", "everything from this session, unfolded"),
89102
("pageup pagedown", "scroll, as does the mouse wheel · end jumps to the latest"),
90103
("click", "open a file or a URL"),
104+
("drag", "select text, copied when you let go"),
91105
("ctrl+c", "stop the run · clear the bar · quit"),
92106
("ctrl+d", "quit"),
93107
)
@@ -221,6 +235,16 @@ def __init__(self) -> None:
221235
self.worker: threading.Thread | None = None
222236
self.update_checked = False
223237
self.buf.on_text_changed += self._reset_palette
238+
# The selection, by (line, column) in the lines last drawn: the header and the conversation.
239+
self.selection: Selection | None = None
240+
self.view_lines: list[Line] = []
241+
self.view_start = self.view_end = 0 # the first of them on screen, and the one past the last
242+
self.view_width = 0
243+
# Off the app's loop, so a slow clipboard command never holds up the screen, and one copy at a time, so an
244+
# older selection cannot land on the clipboard after a newer one.
245+
self.copier = ThreadPoolExecutor(max_workers=1, thread_name_prefix="rae-copy")
246+
self.copies_asked = 0
247+
self.buf.on_text_changed += self._drop_selection
224248
# Stray prints read as notices: dim and indented like the rest of the ledger.
225249
self.capture = TranscriptWriter(self._captured, plain_style=f"fg:{DIM}", indent=" ")
226250

@@ -236,6 +260,9 @@ def _reset_palette(self, _buf: Buffer) -> None:
236260
if self.st.picker is not None and self.st.picker.search:
237261
self.st.picker.index = 0
238262

263+
def _drop_selection(self, _buf: Buffer) -> None:
264+
self.selection = None
265+
239266
def _captured(self, raw: Raw) -> None:
240267
self.view.out(raw)
241268
self.invalidate()
@@ -421,6 +448,7 @@ def run_command(self, text: str) -> None:
421448
self.end_run()
422449
view.flush_live()
423450
self.transcript.clear()
451+
self.selection = None
424452
st.scroll, st.folded, st.cost, st.tokens, st.step = 0, False, 0.0, 0, 0
425453
st.last_client, st.client_name, st.host, st.run_id = None, "", "", None
426454
self.bridge.cost_base = 0.0
@@ -961,11 +989,84 @@ def transcript_view(self, window: Window) -> FormattedText:
961989
rows = window.render_info.window_height if window.render_info else height() - 5
962990
st.scroll = max(0, min(st.scroll, len(lines) - rows))
963991
end = len(lines) - st.scroll
992+
if self.view_width != width():
993+
self.selection = None # the conversation wraps anew, so its lines no longer match
994+
self.view_lines, self.view_start, self.view_end, self.view_width = lines, max(0, end - rows), end, width()
964995
out: list[Any] = []
965-
for i, line in enumerate(lines[max(0, end - rows) : end]):
966-
out += ([("", "\n")] if i else []) + line
996+
for i, line in enumerate(lines[self.view_start : end]):
997+
picked = self.selection.chars(self.view_start + i) if self.selection else None
998+
# A line with no character gives the pointer no position: the window would report the first line.
999+
shown = (highlight(line, *picked) if picked else line) if text_of(line) else [("", " ")]
1000+
out += ([("", "\n")] if i else []) + shown
9671001
return FormattedText(out)
9681002

1003+
def drag(self, event: MouseEvent) -> bool:
1004+
"""A drag over the conversation selects text, copied on release; a click without one still opens a link."""
1005+
at = (self.view_start + event.position.y, event.position.x)
1006+
kind, sel = event.event_type, self.selection
1007+
if kind == MouseEventType.MOUSE_DOWN:
1008+
self.selection = Selection(at, at) if event.button == MouseButton.LEFT else None
1009+
return False
1010+
if sel is None or not sel.dragging:
1011+
return False
1012+
if kind == MouseEventType.MOUSE_MOVE and event.button == MouseButton.LEFT:
1013+
sel.head = at
1014+
return True
1015+
# A release here, or a move with no button held, after a release the session did not see.
1016+
if kind == MouseEventType.MOUSE_UP:
1017+
sel.head = at
1018+
return self.end_drag()
1019+
1020+
def drag_below(self, event: MouseEvent) -> bool:
1021+
"""Mouse events under the conversation: a drag there reaches the end of its last line on screen."""
1022+
sel = self.selection
1023+
if sel is None or not sel.dragging or event.event_type not in (MouseEventType.MOUSE_MOVE, MouseEventType.MOUSE_UP):
1024+
return False
1025+
sel.head = (self.view_end - 1, LINE_END)
1026+
if event.event_type == MouseEventType.MOUSE_MOVE and event.button == MouseButton.LEFT:
1027+
return True
1028+
self.end_drag()
1029+
return True
1030+
1031+
def end_drag(self) -> bool:
1032+
"""Copies what the drag went over; a press and release on one spot was a click."""
1033+
if self.selection is None:
1034+
return False
1035+
self.selection.dragging = False
1036+
if self.selection.anchor == self.selection.head:
1037+
self.selection = None
1038+
return False
1039+
self.copy_selection()
1040+
return True
1041+
1042+
def copy_selection(self) -> None:
1043+
if self.selection is None:
1044+
return
1045+
text = selected_text(self.view_lines, self.selection)
1046+
if not text.strip():
1047+
return
1048+
rows = text.count("\n") + 1
1049+
done = f"copied {rows} lines" if rows > 1 else f"copied {len(text)} characters"
1050+
self.copies_asked += 1
1051+
ticket = self.copies_asked
1052+
1053+
def copy() -> None:
1054+
if ticket != self.copies_asked:
1055+
return # a newer selection came while this one waited its turn
1056+
clipboard.copy(text, lambda data: self.call_soon(lambda: self.write_raw(data)))
1057+
self.call_soon(lambda: self.flash(done))
1058+
1059+
self.copier.submit(copy)
1060+
1061+
def flash(self, message: str) -> None:
1062+
self.st.flash = (message, time.time() + 2)
1063+
self.invalidate()
1064+
1065+
def write_raw(self, data: str) -> None:
1066+
if self.app is not None:
1067+
self.app.output.write_raw(data)
1068+
self.app.output.flush()
1069+
9691070
def build(self) -> Application:
9701071
st, view, buf = self.st, self.view, self.buf
9711072
palette_open = Condition(self.palette_active)
@@ -989,11 +1090,11 @@ def picker_view() -> FormattedText:
9891090
return view.menu(rows, title=p.title, empty="nothing matches what you typed")
9901091

9911092
transcript_window: Window = Window(wrap_lines=False)
992-
transcript_window.content = TranscriptControl(lambda: self.transcript_view(transcript_window), self.scroll)
1093+
transcript_window.content = TranscriptControl(lambda: self.transcript_view(transcript_window), self.scroll, self.drag)
9931094
kb = self.bindings(palette_open, picker_open)
9941095

9951096
def text_window(fn: Callable[[], Any]) -> Window:
996-
return Window(FormattedTextControl(fn), dont_extend_height=True)
1097+
return Window(TextBelow(fn, self.drag_below), dont_extend_height=True)
9971098

9981099
picker_hinted = Condition(lambda: bool(st.picker and st.picker.hint))
9991100
placeholder = ConditionalProcessor(
@@ -1016,9 +1117,11 @@ def text_window(fn: Callable[[], Any]) -> Window:
10161117
text_window(lambda: FormattedText(view.seam())),
10171118
VSplit(
10181119
[
1019-
Window(FormattedTextControl(lambda: FormattedText(view.marker())), dont_extend_width=True, dont_extend_height=True),
1120+
Window(TextBelow(lambda: FormattedText(view.marker()), self.drag_below), dont_extend_width=True, dont_extend_height=True),
10201121
Window(
1021-
BufferControl(buffer=buf, lexer=InputLexer(st), input_processors=[placeholder, follow_hint, picker_hint]),
1122+
InputBelow(
1123+
self.drag_below, buffer=buf, lexer=InputLexer(st), input_processors=[placeholder, follow_hint, picker_hint]
1124+
),
10221125
dont_extend_height=True,
10231126
wrap_lines=True,
10241127
),

‎src/reverse_api/repl/clipboard.py‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
"""The system clipboard, for text selected in the full-screen session."""
2+
3+
from __future__ import annotations
4+
5+
import base64
6+
import os
7+
import shutil
8+
import subprocess
9+
import sys
10+
from collections.abc import Callable
11+
12+
LINUX_COMMANDS = (["xclip", "-selection", "clipboard"], ["xsel", "--clipboard", "--input"])
13+
14+
15+
def copy_command() -> list[str] | None:
16+
"""The platform's copy command, when this machine has one."""
17+
if sys.platform == "darwin":
18+
candidates: tuple[list[str], ...] = (["pbcopy"],)
19+
elif sys.platform.startswith("linux"):
20+
candidates = ((["wl-copy"],) if os.environ.get("WAYLAND_DISPLAY") else ()) + LINUX_COMMANDS
21+
else:
22+
candidates = ()
23+
return next((cmd for cmd in candidates if shutil.which(cmd[0])), None)
24+
25+
26+
def copy(text: str, write_raw: Callable[[str], None]) -> None:
27+
"""Puts text on the clipboard with the platform's command, else asks the terminal to with OSC 52.
28+
29+
Over SSH the platform's clipboard is the remote machine's, so the terminal, on the user's own, does it.
30+
"""
31+
remote = bool(os.environ.get("SSH_CONNECTION") or os.environ.get("SSH_TTY"))
32+
command = None if remote else copy_command()
33+
if command is not None:
34+
# pbcopy reads its input in the locale's encoding.
35+
env = {**os.environ, "LC_CTYPE": "UTF-8"} if command[0] == "pbcopy" else None
36+
try:
37+
# xclip stays in the background to serve the clipboard, holding open any output pipe it was given.
38+
out = subprocess.DEVNULL
39+
subprocess.run(command, input=text.encode(), env=env, check=True, stdout=out, stderr=out, timeout=2)
40+
return
41+
except (OSError, subprocess.SubprocessError):
42+
pass
43+
write_raw(f"\x1b]52;c;{base64.b64encode(text.encode()).decode()}\x07")

‎src/reverse_api/repl/transcript.py‎

Lines changed: 87 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,70 @@
55
import io
66
import threading
77
from collections.abc import Callable
8+
from dataclasses import dataclass
89
from typing import Any
910

1011
from prompt_toolkit.formatted_text import ANSI, FormattedText, to_formatted_text
11-
from prompt_toolkit.layout.controls import FormattedTextControl
12+
from prompt_toolkit.layout.controls import BufferControl, FormattedTextControl
1213
from prompt_toolkit.mouse_events import MouseEvent, MouseEventType
1314
from rich.console import Console, RenderableType
1415

1516
from .style import THEME, pt_style, width
1617

1718
Line = list[tuple[Any, ...]]
19+
# (line, character) in the conversation's lines. A window hands its control the index of the character
20+
# under the pointer, the whole of a wide one, rather than a screen column.
21+
Point = tuple[int, int]
22+
LINE_END = 1 << 30 # past the last character of any line
23+
24+
25+
@dataclass
26+
class Selection:
27+
"""Text dragged over in the conversation, from where the drag began to where the pointer is."""
28+
29+
anchor: Point
30+
head: Point
31+
dragging: bool = True
32+
33+
@property
34+
def span(self) -> tuple[Point, Point]:
35+
return min(self.anchor, self.head), max(self.anchor, self.head)
36+
37+
def chars(self, line: int) -> tuple[int, int | None] | None:
38+
"""The characters selected on a line, both included (None: to its end), or None when it is outside."""
39+
(l0, c0), (l1, c1) = self.span
40+
if not l0 <= line <= l1:
41+
return None
42+
return (c0 if line == l0 else 0), (c1 if line == l1 else None)
43+
44+
45+
def text_of(line: Line) -> str:
46+
return "".join(text for _style, text, *_ in line)
47+
48+
49+
def selected_text(lines: list[Line], selection: Selection) -> str:
50+
"""The selected text, one row per line, without the padding a terminal would also leave out.
51+
52+
Blank rows at its end are dropped: pasted into a shell, a final newline would run the command.
53+
"""
54+
(l0, _), (l1, _) = selection.span
55+
rows = []
56+
for i in range(l0, min(l1, len(lines) - 1) + 1):
57+
lo, hi = selection.chars(i) or (0, None)
58+
rows.append(text_of(lines[i])[lo : None if hi is None else hi + 1].rstrip())
59+
return "\n".join(rows).rstrip("\n")
60+
61+
62+
def highlight(line: Line, lo: int, hi: int | None) -> Line:
63+
"""The line with its characters ``lo`` to ``hi`` drawn reversed; link handlers are kept."""
64+
out: Line = []
65+
i = 0
66+
for style, text, *handler in line:
67+
for ch in text:
68+
picked = i >= lo and (hi is None or i <= hi)
69+
out.append((f"{style} reverse" if picked else style, ch, *handler))
70+
i += 1
71+
return out
1872

1973

2074
class Raw:
@@ -157,11 +211,17 @@ def flush(self) -> None:
157211

158212

159213
class TranscriptControl(FormattedTextControl):
160-
"""The wheel scrolls the conversation; clicks go to the link under the pointer."""
161-
162-
def __init__(self, get_text: Callable[[], FormattedText], on_scroll: Callable[[int], None]) -> None:
214+
"""The wheel scrolls the conversation, a drag selects text, and a click goes to the link under the pointer."""
215+
216+
def __init__(
217+
self,
218+
get_text: Callable[[], FormattedText],
219+
on_scroll: Callable[[int], None],
220+
on_drag: Callable[[MouseEvent], bool] = lambda _event: False,
221+
) -> None:
163222
super().__init__(get_text, focusable=False, show_cursor=False)
164223
self.on_scroll = on_scroll
224+
self.on_drag = on_drag # True when the event was part of a selection
165225

166226
def mouse_handler(self, mouse_event: MouseEvent) -> object:
167227
if mouse_event.event_type == MouseEventType.SCROLL_UP:
@@ -170,4 +230,27 @@ def mouse_handler(self, mouse_event: MouseEvent) -> object:
170230
if mouse_event.event_type == MouseEventType.SCROLL_DOWN:
171231
self.on_scroll(-3)
172232
return None
233+
if self.on_drag(mouse_event):
234+
return None
173235
return super().mouse_handler(mouse_event)
236+
237+
238+
# The rest of the screen is under the conversation: a drag that reaches it goes on, and ends where it is let go.
239+
240+
241+
class TextBelow(FormattedTextControl):
242+
def __init__(self, get_text: Callable[[], Any], on_drag: Callable[[MouseEvent], bool]) -> None:
243+
super().__init__(get_text)
244+
self.on_drag = on_drag
245+
246+
def mouse_handler(self, mouse_event: MouseEvent) -> object:
247+
return None if self.on_drag(mouse_event) else super().mouse_handler(mouse_event)
248+
249+
250+
class InputBelow(BufferControl):
251+
def __init__(self, on_drag: Callable[[MouseEvent], bool], **kwargs: Any) -> None:
252+
super().__init__(**kwargs)
253+
self.on_drag = on_drag
254+
255+
def mouse_handler(self, mouse_event: MouseEvent) -> object:
256+
return None if self.on_drag(mouse_event) else super().mouse_handler(mouse_event)

‎src/reverse_api/repl/view.py‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -229,6 +229,7 @@ class SessionState:
229229
queue: list[str] = field(default_factory=list)
230230
scroll: int = 0 # lines scrolled up from the latest output
231231
folded: bool = False # some output was cut short, so ctrl+o has more to show
232+
flash: tuple[str, float] | None = None # a short confirmation for the status row, until its time
232233
palette_index: int = 0
233234
picker: Picker | None = None
234235
question: Any = None # a free-text question waiting for the next Enter
@@ -754,7 +755,9 @@ def status(self) -> FormattedText:
754755
left += self.pill(CHIP_LAVENDER, gauge) + [(f"fg:{DIM}", " ⌃e ")]
755756
if st.cost:
756757
left += self.pill(CHIP_YELLOW, [(f"fg:{CHIP_INK} bold", f" {money(st.cost)} ")]) + [("", " ")]
757-
if st.scroll:
758+
if st.flash and time.time() < st.flash[1]:
759+
hint = [(f"fg:{PASTEL_WRITE}", f"{st.flash[0]} ")]
760+
elif st.scroll:
758761
hint = [(f"fg:{AMBER}", "end ↓ back to the latest ")]
759762
elif st.question is not None:
760763
hint = [(f"fg:{AMBER}", "type your answer · esc skips ")]

0 commit comments

Comments
 (0)