From fa4db4d8cf869f990cfdfa04ff606ce3a8ff220a Mon Sep 17 00:00:00 2001 From: "nekomimi.pet" Date: Wed, 4 Nov 2026 18:46:41 -0500 Subject: [PATCH] run: await job.text()[-n:] slices the text instead of raising on the coroutine --- priv/python/albedo_plugins/run.py | 39 +++++++++++++++++++++++++++++-- robot-docs/extensions.md | 2 +- test/e2e/python_test.py | 8 ++++++- 3 files changed, 45 insertions(+), 4 deletions(-) diff --git a/priv/python/albedo_plugins/run.py b/priv/python/albedo_plugins/run.py index 7195ad642..47258a5b1 100644 --- a/priv/python/albedo_plugins/run.py +++ b/priv/python/albedo_plugins/run.py @@ -301,6 +301,37 @@ class JobFailed(RuntimeError): super().__init__(f"{head}. Its last lines:\n{last}" if last.strip() else head) +class PendingText: + """`job.text()` before it is awaited. `await` binds to everything after + it, so `await job.text()[-2000:]` slices this object, not the text; each + slice is kept and applied once the text arrives.""" + + __slots__ = ("_read", "_keys") + + def __init__( + self, + read: Callable[[], Coroutine[object, object, Text]], + keys: tuple[int | slice, ...] = (), + ) -> None: + self._read = read + self._keys = keys + + def __getitem__(self, key: int | slice) -> PendingText: + return PendingText(self._read, (*self._keys, key)) + + def __await__(self) -> Generator[object, None, Text]: + return self._text().__await__() + + async def _text(self) -> Text: + text = await self._read() + for key in self._keys: + text = Text(text[key]) + return text + + def __repr__(self) -> str: + return "" + + class Job(JobOutput): """One background program and the process group it owns.""" @@ -526,11 +557,15 @@ class Job(JobOutput): self._read = True return self.exit_code - async def text(self, check: bool = True) -> Text: + def text(self, check: bool = True) -> PendingText: """Wait for the job and return its whole output as plain text: escape codes dropped, a redrawn line at its last draw. A job that exits nonzero or times out raises JobFailed with its last lines, unless - check=False.""" + check=False. A slice taken before the await applies to the text, so + `await job.text()[-2000:]` is its last 2000 characters.""" + return PendingText(lambda: self._text(check)) + + async def _text(self, check: bool) -> Text: await self output = plain(self.read()) if check and (self.exit_code != 0 or self.timed_out): diff --git a/robot-docs/extensions.md b/robot-docs/extensions.md index c54531104..10c17f5e6 100644 --- a/robot-docs/extensions.md +++ b/robot-docs/extensions.md @@ -245,7 +245,7 @@ Output read watchers use weak references to bound job methods. They remain regis there is no shell, so shell syntax has python spellings: `cd dir &&` is `cwd=`, `NAME=value` is `env=`, `| tail -n N` and `| head -n N` are `job.tail(lines=N)` and `job.head(lines=N)`, stderr always joins stdout, and chains, loops, and globs are python over the job's output. `a | b` is `run(a…).pipe(b…)`, the same as `run(b…, stdin=job)` but keeping the writer's timeout unless given its own: the writer's bytes stream into the reader exactly, a full reader pauses the writer, and once every reader has closed its stdin the kernel stops reading the writer, so its next write fails as it would into a closed shell pipe (`run('yes').pipe('head', '-2')` ends). the writer still captures its own output; piping retires its wake, and the reader's notice names the whole pipeline. a job that already wrote feeds what it retained first; one that wrote past the 1 MiB it retains cannot be piped after the fact. `run("bash", "-c", …)` and its spellings are refused, and so is a cell's own `subprocess`, `os.system`, `os.exec*`, `os.posix_spawn`, or `asyncio.create_subprocess_*` — an audit hook in `albedo_shell` checks whether the nearest non-stdlib frame is cell code. each refusal carries the `run()` call the line means when it is simple enough to read (`cd cli && go test ./... | tail -5` → `job = run('go', 'test', './...', cwd='cli')`, `await job`, then `job.tail(lines=5)`), so the error is a copy-paste answer rather than a wall. this is guidance, not a sandbox: plugins and libraries a cell calls still spawn, and `exec` of a compiled string is not cell code. -`await job.text(check=True)` awaits the job and returns its whole output as plain text: escape codes (colour, cursor, terminal titles and links) dropped, and a line redrawn with `\r` at its last draw (`albedo_output.plain`). a job that exits nonzero or times out raises `JobFailed` (a `RuntimeError` naming the pipeline, how it ended, and its last 30 lines; `error.output` is the whole text), unless `check=False`. it reads with `job.read()`, so output past 1 MiB raises the same way, and the read retires the job's wake. `await job.wait_for(pattern, timeout=60)` returns the first line of output containing `pattern` (text, or a compiled `re` pattern), scanning from the start in 64 KiB pages and then every 0.1 s, the line still being written included (a prompt has no newline). it raises `TimeoutError` after `timeout` and `JobFailed` when the job ends first; neither stops the job or retires its wake. the instructions name `run(...).text()` as the default way to run a command for its output. the kernel's working directory is the session's own state: `os.chdir(path)` moves where `run()` starts programs and where `files` resolves relative paths, and `albedo_state` saves and restores it across kernel restarts, so a session working in another checkout sets it once. +`await job.text(check=True)` awaits the job and returns its whole output as plain text: escape codes (colour, cursor, terminal titles and links) dropped, and a line redrawn with `\r` at its last draw (`albedo_output.plain`). a job that exits nonzero or times out raises `JobFailed` (a `RuntimeError` naming the pipeline, how it ended, and its last 30 lines; `error.output` is the whole text), unless `check=False`. it reads with `job.read()`, so output past 1 MiB raises the same way, and the read retires the job's wake. `text()` returns a `PendingText`, not a coroutine, so `await job.text()[-2000:]` (the slice binds before the await) slices the text once it arrives. on a coroutine that spelling raised `TypeError` and left the job unread, so it woke the session later. `await job.wait_for(pattern, timeout=60)` returns the first line of output containing `pattern` (text, or a compiled `re` pattern), scanning from the start in 64 KiB pages and then every 0.1 s, the line still being written included (a prompt has no newline). it raises `TimeoutError` after `timeout` and `JobFailed` when the job ends first; neither stops the job or retires its wake. the instructions name `run(...).text()` as the default way to run a command for its output. the kernel's working directory is the session's own state: `os.chdir(path)` moves where `run()` starts programs and where `files` resolves relative paths, and `albedo_state` saves and restores it across kernel restarts, so a session working in another checkout sets it once. ## view diff --git a/test/e2e/python_test.py b/test/e2e/python_test.py index c05111038..1304dba50 100644 --- a/test/e2e/python_test.py +++ b/test/e2e/python_test.py @@ -189,7 +189,11 @@ class PythonToolsTests(unittest.TestCase): "except RuntimeError as error:\n" " print(type(error).__name__, repr(str(error).splitlines()[0]))\n" " print(repr(error.output))\n" - "print(repr(await run(sys.executable, '-c', program, '3').text(check=False)))" + "print(repr(await run(sys.executable, '-c', program, '3').text(check=False)))\n" + # `await` takes the slice with it; the slice applies to the text. + "print(repr(await run(sys.executable, '-c', program, '0').text()[-5:]))\n" + "job = run(sys.executable, '-c', program, '3')\n" + "print(repr(await parallel(job.text(check=False)[:5])))" ) lines = output.splitlines() self.assertEqual(lines[0], repr("green\n100%\n")) @@ -197,6 +201,8 @@ class PythonToolsTests(unittest.TestCase): self.assertIn("exited 3", lines[1]) self.assertEqual(lines[2], repr("green\n100%\n")) self.assertEqual(lines[3], repr("green\n100%\n")) + self.assertEqual(lines[4], repr("100%\n")) + self.assertEqual(lines[5], repr(["green"])) def test_wait_for_returns_the_line_and_leaves_the_job_running(self): server = ( -- knotmirror 0.0.1