From df65ddd321fd7e4f572a0e3e8b35bb69cfade66b Mon Sep 17 00:00:00 2001 From: Patrick Dewey Date: Tue, 6 Oct 2026 09:14:33 -0400 Subject: [PATCH] cli: pass terminal files through to the editor handoff --- cli/internal/cli/root.go | 19 ++----- robot-docs/commands.md | 15 +++++ test/e2e/editor_test.py | 115 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 136 insertions(+), 13 deletions(-) create mode 100644 test/e2e/editor_test.py diff --git a/cli/internal/cli/root.go b/cli/internal/cli/root.go index b306bc34e..307cd4e3c 100644 --- a/cli/internal/cli/root.go +++ b/cli/internal/cli/root.go @@ -45,8 +45,8 @@ func Execute(ctx context.Context, args []string, deps Dependencies, streams Stre } root := NewRoot(deps) root.SetIn(streams.In) - root.SetOut(preserveFile(output)) - root.SetErr(preserveFile(errorOutput)) + root.SetOut(output) + root.SetErr(errorOutput) root.SetArgs(args) err := root.ExecuteContext(ctx) if outputErr := output.Err(); outputErr != nil && !errors.Is(err, outputErr) { @@ -85,19 +85,12 @@ func (w *checkedWriter) Err() error { return w.err } -// Bubble Tea uses the output file descriptor to detect size and terminal modes. -// Keep those methods when tracking writes to an actual file. -type checkedFile struct { - *os.File - writer *checkedWriter -} - -func (f *checkedFile) Write(data []byte) (int, error) { return f.writer.Write(data) } -func (f *checkedFile) WriteString(value string) (int, error) { return f.writer.Write([]byte(value)) } - +// Interactive children need the actual *os.File: os/exec connects any wrapper +// through a pipe, even one exposing Fd. Keep error tracking on Cobra output and +// injected writers, but pass terminal files directly to Bubble Tea. func preserveFile(writer *checkedWriter) io.Writer { if file, ok := writer.Writer.(*os.File); ok { - return &checkedFile{File: file, writer: writer} + return file } return writer } diff --git a/robot-docs/commands.md b/robot-docs/commands.md index 2cc2e2071..34127b906 100644 --- a/robot-docs/commands.md +++ b/robot-docs/commands.md @@ -79,3 +79,18 @@ This needs permission to read the terminal's clipboard; OSC 52 alone supports te Bubble Tea's existing terminal reader delivers the replies; no subprocess opens a competing TTY reader. One read may be pending per chat. Request IDs reject delayed replies, session generations reject delayed completions, and replies continue reaching the chat while a modal is open. Reads accept at most 5 MiB total, with individual decoded chunks capped at 4096 bytes, and expire after 30 seconds (including time spent granting permission). Denied permission, unsupported terminals, malformed responses, and timeout report an error without changing the draft. Closing the chat drops its pending buffer. Each reply chunk is larger than one terminal read. `cli/go.mod` replaces ultraviolet with [okami.mom/ultraviolet](https://tangled.org/okami.mom/ultraviolet), whose reader waits for a reply cut between the ESC and backslash of its terminator, and holds a partial `ESC ]5522;` reply for up to 5 seconds after its last byte instead of flushing it at the 50 ms escape timeout. Upstream dropped the first kind and typed a `\` into the draft, and typed the rest of the payload for the second; both lost image bytes. proxy.golang.org cannot fetch from tangled knots, so Go falls back to fetching the fork with git; `go.sum` pins it. + +## CLI terminal handoff + +`cli/internal/cli/root.go` keeps output-error tracking on Cobra's command/help +writers, but passes actual `*os.File` streams to the terminal service. Exposing +`Fd` on a writer wrapper is not enough: Go's `os/exec` gives interactive children +a pipe unless their stream is a concrete `*os.File`, breaking editor TTY +recognition, sizing, rendering, and keyboard input. + +`cli/internal/tui/editor.go` owns Ctrl-G's temporary prompt file and uses +`tea.Exec` to stop Bubble Tea's input reader and renderer while the editor owns +the terminal. It restores the cursor column and negotiated grapheme mode before +Bubble Tea resumes, retains successful edits even if restoration fails, reports +editor failures without replacing the draft, and removes the temporary file. +SSH sign-in also uses Bubble Tea's interactive process handoff. diff --git a/test/e2e/editor_test.py b/test/e2e/editor_test.py new file mode 100644 index 000000000..2ad6692a6 --- /dev/null +++ b/test/e2e/editor_test.py @@ -0,0 +1,115 @@ +"""Ctrl-G must lend the editor a real terminal, then restore the composer.""" + +import os +import pty +import select +import sys +import termios +import time +import unittest + +from harness import Albedo, exclusive + + +EDITOR = r""" +import json +import os +from pathlib import Path +import sys +import termios +import tty + +if not all(os.isatty(fd) for fd in (0, 1, 2)): + print("EDITOR_NOT_A_TERMINAL", flush=True) + sys.exit(2) +path = Path(sys.argv[1]) +state = termios.tcgetattr(0) +try: + tty.setraw(0) + rows, columns = os.get_terminal_size(1) + # Exercise a full-screen render, not just a short line in a pipe. + os.write(1, b"\x1b[?1049h\x1b[H" + (b"x" * columns) * rows) + os.write(1, b"EDITOR_READY:" + json.dumps(path.read_text()).encode()) + data = b"" + while not data.endswith(b"\r"): + data += os.read(0, 1) + if data == b"fail\r": + sys.exit(7) + path.write_text(data[:-1].decode().replace("\x1b", "")) +finally: + os.write(1, b"\x1b[?1049lEDITOR_DONE") + termios.tcsetattr(0, termios.TCSANOW, state) +""" + + +@exclusive # The CLI's EDITOR and TERM are daemon-fixture environment settings. +class EditorTest(unittest.TestCase): + def test_editor_owns_terminal_and_composer_recovers_after_success_and_failure(self): + def prepare(app): + editor = app.root / "editor.py" + editor.write_text(EDITOR) + app.env.update(EDITOR=f"{sys.executable} {editor}", TERM="xterm-256color") + + with Albedo(prepare=prepare) as app: + session = app.session() + master, slave = pty.openpty() + termios.tcsetwinsize(slave, (24, 100)) + process = app.daemon.start_cli( + "resume", session, stdin=slave, stdout=slave, stderr=slave + ) + os.close(slave) + output = b"" + + def until(marker): + nonlocal output + deadline = time.monotonic() + 15 + while marker not in output: + remaining = deadline - time.monotonic() + self.assertGreater(remaining, 0, repr(output[-4000:])) + readable, _, _ = select.select([master], [], [], remaining) + if not readable: + continue + chunk = os.read(master, 65536) + self.assertTrue(chunk, repr(output[-4000:])) + output += chunk + self.assertNotIn(b"EDITOR_NOT_A_TERMINAL", output) + # Answer the startup queries as an ordinary terminal would. + if b"\x1b[6n" in chunk: + os.write(master, b"\x1b[1;1R") + if b"\x1b[c" in chunk: + os.write(master, b"\x1b[?1;2c") + if b"Restart Albedo? [y/N]" in chunk: + os.write(master, b"n\r") + if b"Press Enter to continue." in chunk: + os.write(master, b"\r") + + try: + until(b"your messages") + os.write(master, b"draft\x07") + until(b'EDITOR_READY:"draft"') + output = b"" + # Escape and navigation bytes must reach the editor unchanged. + os.write(master, b"edited \x1b[Dprompt\r") + until(b"EDITOR_DONE") + until(b"your messages") + output = b"" + os.write(master, b"\x07") + until(b'EDITOR_READY:"edited [Dprompt"') + output = b"" + os.write(master, b"fail\r") + until(b"Could not finish editing the prompt") + until(b"your messages") + output = b"" + # A failed editor must retain the previous draft. + os.write(master, b"\x07") + until(b'EDITOR_READY:"edited [Dprompt"') + os.write(master, b"recovered\r") + until(b"EDITOR_DONE") + until(b"your messages") + os.write(master, b"\x03") + self.assertEqual(process.wait(timeout=10), 0) + finally: + if process.poll() is None: + process.kill() + process.wait(timeout=10) + os.close(master) -- knotmirror 0.0.1