Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions docs/02_execution_and_interactive.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
---
log:
2026-11-23: `colab exec` now exits 1 when executed code produces a kernel `error` output (after recording history and saving `*_output.ipynb` for notebooks, stopping further notebook cells) (#250).

2026-05-07: Fixed `colab console` piped-stdin handling. Previously a piped invocation (e.g. `echo 'cmd' | colab console -s s`) sent the command and then hung indefinitely because the previous EOF handler emitted a bare `\x04` (Ctrl-D), which the remote `tmux`-wrapped bash treats as a literal character rather than a session terminator. The new handler sends `exit\n` (which bash actually exits on) and then closes the websocket from the client side after a short grace period (`PIPED_EOF_GRACE_SECONDS = 0.5s`) so any tail output (bash `logout`, tmux `[exited]`) makes it back to the user. TTY mode is unchanged: real-terminal EOF is left to the remote shell. Verified live: `echo 'echo HELLO' | colab console -s s` now exits in ~1.2s instead of hanging.

2026-05-07: Fixed `print_kitty` (used by `colab exec --output-image` and any image-producing exec) to no-op when `sys.stdout.isatty()` is false. The Kitty Graphics Protocol escape sequence is meaningless when stdout is a file or pipe and was visually corrupting captured output (a multi-KB base64 PNG blob would land in log files, grep targets, or showboat captures). Image bytes are still saved to disk via `handle_image`'s file-write path; only the inline-render attempt is suppressed.
Expand Down Expand Up @@ -33,6 +35,7 @@ Execution involves sending Python code (or shell commands) to the Jupyter kernel
- If file path is remote: Execute `!python <path>`.
- **Multi-Modal Output**: Handle `display_data` messages (e.g., `image/png`, `text/html`). For the CLI, we'll save images to temporary files and print their paths, or if the terminal supports it (e.g., iTerm2), inline them.
- **Timeout Configuration**: Exposes a `--timeout` flag (default 30s): the longest silence allowed before execution fails. Raise it so long-running silent tasks (like model compilation or data downloading) are not prematurely killed; `0` means no limit.
- **Error Exit Status**: Exits with status 1 if any executed code block returns an `output_type == "error"` output from the kernel (stopping remaining cells when executing a `.ipynb` notebook while still writing `*_output.ipynb`).

## Implementation Details
- **Kernel Management**: `ColabRuntime` (from `colab-agent`) already handles message signing and message types.
Expand All @@ -46,6 +49,7 @@ TDD is mandatory for all execution features.
- **Test Case**: Verify `ColabRuntime` correctly sends an `execute_request` message over the websocket.
- **Test Case**: Verify `iopub.stream` messages are correctly handled and printed to `stdout` in real-time.
- **Test Case**: Verify `display_data` (specifically `image/png`) triggers the correct local handling (saving or display).
- **Test Case**: Verify `colab exec` exits with status 1 when the kernel emits an `error` output, and halts multi-cell `.ipynb` execution at the failing cell while still saving `*_output.ipynb`.

### 2. TTY and Piping
- **Test Case**: Mock `sys.stdin.isatty()` to verify `colab repl` correctly switches between interactive mode and one-shot piped execution.
Expand Down
1 change: 1 addition & 0 deletions skills/colab-operator/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ by running `uv tool install google-colab-cli` or `pip install google-colab-cli`.
- **Preferred**: `colab exec -s <name> -f <script.py>` runs a local script on the remote VM (read locally, sent to the kernel — no manual upload needed).
- **Piped code**: `echo "print(1)" | colab exec -s <name>` or `cat script.py | colab exec -s <name>`.
- **Notebooks**: `colab exec -s <name> -f nb.ipynb` runs each code cell and writes results to `<basename>_output.ipynb` next to the input. A `# @title Foo` first line labels the cell in progress output.
- **Exit status**: `colab exec` exits `1` when the kernel emits an error output (uncaught Python exception, syntax error, or `SystemExit`); for `.ipynb` notebooks it stops at the failing cell and still writes `<basename>_output.ipynb`. IPython `!cmd` shell escapes do **not** emit a kernel error on a non-zero shell exit — use `colab ssh -s <name> -- <cmd>` or `subprocess.run(..., check=True)` when shell exit status matters.
- **Plots/images**: PNG/JPEG outputs are intercepted. Use `--output-image <path>` on `exec`/`repl` to save to a known location (otherwise a temp path is printed). Inline terminal-image escapes are auto-suppressed when stdout isn't a TTY, so piped/captured output stays clean.
- **Shell**: run a one-shot shell command with `colab ssh -s <name> -- <cmd>`: it runs in `/content` and exits with the command's status. Output is byte-exact when stdout is piped or redirected; ssh allocates a PTY only when stdin and stdout are both terminals, so a shell tool that runs commands in a terminal should add `</dev/null` and redirect the output to a file (a pipe keeps `colab ssh`'s exit status only under `set -o pipefail`). One argument is a shell command line (quote it for pipes or globs: `colab ssh -s <name> -- 'nvidia-smi | head -5'`); several arguments are an exact argv, so pass untrusted values as separate arguments after `--` where the program accepts it (e.g. `colab ssh -s <name> -- ls -- "$f"`), never inside a shell line or a piped script. Pipe a multi-line script to `colab ssh -s <name> -- bash`. Use `colab exec` for Python code. When ssh can't work (no local `ssh` client, no `~/.ssh/id_ed25519` or `id_ecdsa` key and no `-i KEY`, a tool not on the minimal ssh environment's `PATH` such as `gcloud` or `node`, or the runtime's limited concurrent SSH connections in use, which the server answers with 429, e.g. while a person or an IDE is connected), fall back to `exec` with IPython's `!` prefix: `echo '!df -h /content' | colab exec -s <name>` (single quotes stop your local shell expanding `!`). Each `!` line runs in its own shell with no input (a command that prompts hangs), and IPython evaluates `{expr}` as Python even inside quotes and expands `$name` outside single quotes. Start a multi-line script with a `%%bash` line (not with `--env`, which prepends Python lines), use non-interactive flags such as `apt-get -y`, and never put untrusted text in a `%%bash` script or a `!` line (even via `{var}` or `$var`): pass it with `--env NAME=VALUE` and run `subprocess.run(["cmd", "--", os.environ["NAME"]])` from Python. For an interactive shell on the VM, a human runs `colab ssh -s <name>`.
- **Never run `colab repl`, `colab ssh` without `-- CMD`, `colab auth`, or `colab drivemount` interactively from an agent** — `repl`, `auth` and `drivemount` expect a TTY and will hang or fail, and bare `colab ssh` with no saved session creates a billable runtime; an interactive shell is for a human. `repl` accepts piped stdin and exits on EOF; `auth`/`drivemount` genuinely require a human at the terminal.
Expand Down
2 changes: 2 additions & 0 deletions src/colab_cli/commands/execution.py
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,8 @@ def on_sess_started(sid):
"cell_id": block.get("id"),
},
)
if any(o.get("output_type") == "error" for o in outputs):
raise typer.Exit(1)
finally:
s.running = None
state.store.add(s)
Expand Down
41 changes: 40 additions & 1 deletion tests/test_exec.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ def mock_execute_code(code, output_hook=None, **kwargs):
mock_runtime.execute_code.side_effect = mock_execute_code

result = runner.invoke(app, ["exec", "-s", "s1"], input="do_stuff()")
assert result.exit_code == 0
assert result.exit_code == 1

mock_handle_image.assert_any_call("png_data", "image/png", target_path=None)
mock_handle_image.assert_any_call("jpeg_data", "image/jpeg", target_path=None)
Expand All @@ -262,6 +262,45 @@ def mock_execute_code(code, output_hook=None, **kwargs):
assert "line1\nline2\n" in result.stderr


def test_cli_exec_file_error_exits_nonzero(
mock_store, mock_runtime_class, mock_common_state, tmp_path
):
mock_session = MagicMock()
mock_session.name = "s1"
mock_session.url = "http://url"
mock_session.token = "token"
mock_session.kernel_id = None
mock_session.session_id = None
mock_store.get.return_value = mock_session
mock_common_state.resolve_session.return_value = "s1"

def mock_execute_code(code, output_hook=None, **kwargs):
if output_hook is None:
return []
err = {
"output_type": "error",
"ename": "ValueError",
"evalue": "boom",
"traceback": ["Traceback (most recent call last):\n", "ValueError: boom"],
}
output_hook(err)
return [err]

mock_runtime = mock_runtime_class.return_value
mock_runtime.execute_code.side_effect = mock_execute_code

script = tmp_path / "raise.py"
script.write_text('raise ValueError("boom")\n')

result = runner.invoke(app, ["exec", "-s", "s1", "-f", str(script)])

assert result.exit_code == 1
assert "ValueError: boom" in result.stderr
assert mock_session.running is None
mock_common_state.history.log_event.assert_called_once()
mock_runtime.stop.assert_called_once()


def test_cli_exec_empty_code(mock_runtime_class, mock_store, mock_common_state):
mock_session = MagicMock()
mock_session.name = "s1"
Expand Down
46 changes: 46 additions & 0 deletions tests/test_ipynb_exec.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,52 @@ def test_exec_ipynb_creates_output_file(
self.assertEqual(len(output_nb.cells[2].outputs), 1)
self.assertEqual(output_nb.cells[2].outputs[0].text, "cell 2\n")

@patch("colab_cli.commands.execution.ColabRuntime")
@patch("colab_cli.state.StateStore")
@patch("colab_cli.commands.execution.typer.echo")
def test_exec_ipynb_cell_error_stops_and_exits_nonzero(
self,
mock_echo,
mock_store_class,
mock_runtime_class,
):
with patch.object(
sys, "argv", ["colab", "exec", "-s", "test-s", "-f", self.nb_path]
):
mock_store = mock_store_class.return_value
mock_store.get.return_value = MagicMock(
name="test-s", url="http://url", token="token"
)

mock_runtime = mock_runtime_class.return_value
mock_runtime.execute_code.side_effect = [
[],
[
{
"output_type": "error",
"ename": "RuntimeError",
"evalue": "cell 1 failed",
"traceback": ["RuntimeError: cell 1 failed"],
}
],
[{"output_type": "stream", "name": "stdout", "text": "cell 2\n"}],
]

with patch("builtins.print"), pytest.raises(SystemExit) as error:
main()

assert error.value.code == 1
self.assertEqual(mock_runtime.execute_code.call_count, 2)

output_nb_path = self.nb_path.replace(".ipynb", "_output.ipynb")
self.assertTrue(os.path.exists(output_nb_path))
with open(output_nb_path, "r", encoding="utf-8") as f:
output_nb = nbformat.read(f, as_version=4)

self.assertEqual(len(output_nb.cells[0].outputs), 1)
self.assertEqual(output_nb.cells[0].outputs[0].output_type, "error")
self.assertEqual(len(output_nb.cells[2].outputs), 0)


if __name__ == "__main__":
unittest.main()