From c19ce5075683c680e77bf12052e886af18e3d8d9 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 7 Oct 2026 17:44:58 +0000 Subject: [PATCH 1/8] fix: Windows consoles and Drive mount consent MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Interactive colab console on cmd.exe and PowerShell no longer depends on termios. It enables ANSI processing, switches the console to raw input, and translates Windows scan codes to the sequences a POSIX tty would send. colab ssh --proxy-mode reads stdin with a blocking os.read and quotes its ProxyCommand for cmd.exe. colab drivemount passes timeout_ms=600000 so the kernel does not abandon the browser consent step at 120s, runs the handshake off the websocket thread, opens the consent URL, and explains the multi-account HTTP 400 instead of dumping Google's HTML error page. Co-authored-by: János Rózsavölgyi --- AGENTS.md | 2 +- README.md | 7 +- docs/02_execution_and_interactive.md | 6 +- docs/04_automation_and_utility.md | 35 +++- docs/06_ssh_access.md | 2 + skills/colab-operator/SKILL.md | 2 +- src/colab_cli/cli.py | 17 +- src/colab_cli/commands/automation.py | 201 +++++++++--------- src/colab_cli/commands/ssh.py | 75 ++++--- src/colab_cli/console.py | 119 +++++++---- src/colab_cli/drive_auth.py | 303 +++++++++++++++++++++++++++ src/colab_cli/terminal.py | 242 +++++++++++++++++++++ tests/test_automation.py | 55 ++++- tests/test_console.py | 79 ++++++- tests/test_drive_auth.py | 271 ++++++++++++++++++++++++ tests/test_ssh.py | 56 +++-- tests/test_terminal.py | 146 +++++++++++++ 17 files changed, 1422 insertions(+), 196 deletions(-) create mode 100644 src/colab_cli/drive_auth.py create mode 100644 src/colab_cli/terminal.py create mode 100644 tests/test_drive_auth.py create mode 100644 tests/test_terminal.py diff --git a/AGENTS.md b/AGENTS.md index 6e84b75b..04777814 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -87,7 +87,7 @@ As an AI agent operating via non-interactive shell tools (`run_shell_command`), - Specially crafted mock scripts that simulate timeouts or API calls. - **I CANNOT Run (Requires User Assistance):** - **`colab auth`**: This command relies on the traditional Gcloud fallback `input_request` (via `USE_AUTH_EPHEM='0'`), which prompts the user via Python's `input()` to click a URL, sign in, and paste back an authorization code. My shell tool will hang indefinitely on this `input()`. - - **`colab drivemount`**: This command prompts the user via `sys.stdin.readline()` (specifically querying `/dev/tty` to ensure input is captured) to press `Enter` after granting OAuth consent in the browser. My shell tool will timeout/hang waiting for `Enter`. + - **`colab drivemount`**: This command prompts the user to press `Enter` after granting OAuth consent in the browser. The prompt reads the controlling terminal (`/dev/tty` on POSIX, `CONIN$` on Windows), falling back to stdin. My shell tool will timeout/hang waiting for `Enter`. The consent URL is also opened in a GUI browser when one is available. - **Interactive (TTY) `colab repl` / `colab console`**: When stdin is a real terminal these commands drop into interactive raw-TTY modes that require real-time keystroke streaming. My shell tools cannot support this. (Piped stdin is fine — see above.) Whenever working on interactive commands, I must build the core logic, write mock tests, and explicitly ask the user to run the live test in their terminal to verify success. diff --git a/README.md b/README.md index 1cbfedd6..c9ffe973 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ Designed to support seamless developer productivity, headless automation, and AI [Demo](https://github.com/user-attachments/assets/656226a9-af13-4fdb-8eda-d7de747336a2) > [!NOTE] -> **Platform support:** the Colab CLI currently supports **Linux and macOS** only. Windows is not supported at this time. +> **Platform support:** Linux, macOS, and Windows (PowerShell and cmd.exe). Interactive `colab console` uses the Windows console API on Windows (raw keystrokes and ANSI color). `colab ssh --proxy-mode` reads stdin with a blocking read so it works as an OpenSSH ProxyCommand under Windows OpenSSH. > [!TIP] > Looking for in-notebook, interactive agent-assisted coding instead of a terminal workflow? See the [Colab MCP Server](https://github.com/googlecolab/colab-mcp). @@ -97,7 +97,7 @@ Run `colab --help` to view specific options, defaults, and detailed he | Command | Description | | --- | --- | | `colab auth [-s NAME]` | Authenticate the VM for GCP services (BigQuery, GCS, etc.) | -| `colab drivemount [-s NAME] [PATH]` | Mount Google Drive on the VM (default: `/content/drive`) | +| `colab drivemount [-s NAME] [--authuser N] [PATH]` | Mount Google Drive on the VM (default: `/content/drive`) | | `colab install [-s NAME] [-r FILE \| PKG...]` | Install packages on the VM using `uv` (falls back to `pip`) | | `colab log [-s NAME] [-n N] [-o FILE]` | View or export session history (`.ipynb`, `.md`, `.txt`, `.jsonl`) | | `colab usage` | Show account compute-unit usage rate and balance | @@ -144,7 +144,8 @@ colab stop -s analysis ## Usage Notes * **Machine shape:** Use `--high-mem` with `colab new`, `colab run`, or `colab ssh` (when auto-creating a runtime) to request a high-RAM machine shape. Requires Colab Pro or Pro+ entitlement for supported accelerators (CPU, T4, A100, etc.). L4 and TPU runtimes ignore this flag because they only offer one shape. Machine shape is shown in `colab sessions` and `colab status`. -* **TTY Requirements:** The interactive commands `repl` and `console` require a local TTY. When running inside automated scripts or pipelines, make sure to pipe stdin (e.g., `echo "print(1)" | colab repl`) to trigger non-interactive execution modes. +* **TTY Requirements:** The interactive commands `repl` and `console` require a local TTY. When running inside automated scripts or pipelines, make sure to pipe stdin (e.g., `echo "print(1)" | colab repl`) to trigger non-interactive execution modes. On Windows, `colab console` switches the console out of line-editing mode so arrow keys and Ctrl-C reach the remote shell; colors need virtual-terminal processing, which the CLI turns on for cmd.exe and Windows PowerShell. +* **Drive mount and multiple Google accounts:** `colab drivemount` prints a consent URL (and opens it in the browser when it can) and waits up to 10 minutes. On the account chooser, select the same account the CLI authenticated as (`colab whoami` / the `login_hint` in the URL). A browser that is signed into several accounts otherwise attributes the Drive session to the active account, and Colab rejects the mount with HTTP 400. `--authuser N` appends that index to the consent URL when the chooser keeps opening the wrong account. * **Transparent Code Execution:** When calling `colab exec -f file.py`, the CLI reads the file locally and transmits its content to the remote kernel. You do not need to manually upload files before execution. * **Storage & State Paths:** Session tokens and metadata are stored at `~/.config/colab-cli/sessions.json`. Global CLI settings are located at `~/.config/colab-cli/settings.json`. These can be customized or isolated via the global `--config` flag. diff --git a/docs/02_execution_and_interactive.md b/docs/02_execution_and_interactive.md index ed1d782a..29c1f963 100644 --- a/docs/02_execution_and_interactive.md +++ b/docs/02_execution_and_interactive.md @@ -1,5 +1,7 @@ --- log: +2026-10-07: Windows console support for `colab console`. cmd.exe and PowerShell have no `termios`, `/dev/tty`, or `SIGWINCH`, so interactive console used to stay line-buffered (arrow keys never left the local line editor, Ctrl-C killed the CLI, ANSI from the remote PTY rendered as garbage in conhost). `console.py` now enables virtual-terminal processing and UTF-8, switches the input handle to raw mode via `SetConsoleMode`, reads keys with `msvcrt.getwch`, translates scan codes to ANSI, and polls the window size. POSIX raw mode and piped stdin are unchanged. `colab ssh --proxy-mode` reads stdin with a blocking `os.read` (Windows `select()` cannot wait on a pipe) and quotes the ProxyCommand for `cmd.exe`. + 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. @@ -33,7 +35,7 @@ Execution involves sending Python code (or shell commands) to the Jupyter kernel ### 3. Console (`colab console`) - **Implementation**: Connects directly to the backend terminal endpoint (`/colab/tty`) via WebSockets using `websocket-client`. - **Interactive**: Bypasses the Jupyter kernel entirely to provide a raw, PTY-backed bash session on the Colab VM. -- **Terminal Management**: Configures `sys.stdin` to raw mode using `termios` and `tty`, passing single characters to the socket and writing raw ANSI escape sequences directly to `sys.stdout.buffer`. Hooks into `SIGWINCH` to communicate local terminal dimensions (`cols`/`rows`) to the remote bash environment so output rendering works perfectly during resizing. +- **Terminal Management**: On Linux and macOS, configures `sys.stdin` to raw mode using `termios` and `tty`, passing single characters to the socket and writing raw ANSI escape sequences directly to `sys.stdout.buffer`. Hooks into `SIGWINCH` to communicate local terminal dimensions (`cols`/`rows`) to the remote bash environment so output rendering works perfectly during resizing. On Windows (cmd.exe and PowerShell), `termios` does not exist: the CLI enables `ENABLE_VIRTUAL_TERMINAL_PROCESSING` and UTF-8 on the console, sets raw input mode with `SetConsoleMode` (so the local line editor and Ctrl-C handler get out of the way), reads keys with `msvcrt.getwch`, maps scan codes to ANSI sequences, and polls `os.get_terminal_size` because there is no `SIGWINCH`. - **Piped stdin**: Detected via `sys.stdin.isatty()`. When piped, the input characters are forwarded one at a time to the remote pty, and on EOF the client sends `exit\n` and then closes the websocket itself after `PIPED_EOF_GRACE_SECONDS` (0.5s) so the user's shell goodbye text drains back. The remote `/colab/tty` endpoint wraps bash in tmux, which intercepts a bare `\x04` as a literal character — that is why we send `exit\n` rather than Ctrl-D. ## Implementation Details @@ -54,4 +56,6 @@ TDD is mandatory for all execution features. - **Test Case**: Verify large piped inputs are handled without buffer overflow or truncation. - **Test Case**: `colab console` with piped stdin sends `exit\n` and calls `ws.close()` on EOF (regression: previously sent `\x04` only and hung). - **Test Case**: `colab console` in TTY mode does not synthesize an exit on EOF (the user owns the session lifecycle). +- **Test Case**: With `termios` unavailable and `os.name == "nt"`, `connect_console` enters the Windows raw-console context manager and does not call `tty.setraw`. +- **Test Case**: Windows key translation maps scan codes to ANSI and the stdin thread forwards those characters one at a time. - **Test Case**: `print_kitty` is a no-op when `sys.stdout.isatty()` is false (regression: previously emitted ANSI/base64 into pipes and files). diff --git a/docs/04_automation_and_utility.md b/docs/04_automation_and_utility.md index 1a0e2287..009204df 100644 --- a/docs/04_automation_and_utility.md +++ b/docs/04_automation_and_utility.md @@ -1,5 +1,7 @@ --- log: +2026-10-07: Drive mount fixes for upstream issues #113, #103, and #108. `drive.mount` is now called with `timeout_ms=600000` so the kernel's `blocking_request` does not give up at the 120s default while the user is still in the browser (that produced `ValueError: mount failed` with an empty reason). The propagation handshake runs on a daemon thread so it does not block the websocket recv loop. The consent URL is opened in the system browser when one is available (`os.startfile` on Windows, `open` on macOS, `xdg-open` elsewhere) and the prompt names the `login_hint` account. HTTP 400 is explained as a multi-account browser mismatch instead of dumping Google's HTML error page, and an error `colab_reply` unblocks the kernel immediately. Optional `--authuser N` rewrites the consent URL only when the user asks; the propagation request's `authuser` parameter was shown in #103 not to fix the 400 by itself, and the URL is not forced to `authuser=0`. The Enter prompt reads `/dev/tty` on POSIX and `CONIN$` on Windows. + 2026-09-25: Cleaned up references to keep-alive background daemon and pre-flight pings. VM liveness is automatically maintained by the Colab backend based on active kernel activity. 2026-08-10: Added `colab usage` for account-level compute-unit rate/balance via `GET /tun/m/ccu-info` on the session backend (same bearer token as `colab new`). 2026-06-11: Replaced the `oauth2` provider's `run_local_server()` (localhost redirect) with a remote copy-paste flow (`_run_remote_flow` in `auth.py`). The CLI now prints an authorization URL built with `redirect_uri=https://sdk.cloud.google.com/applicationdefaultauthcode.html` and `token_usage=remote`, then reads the pasted authorization code via `input()` and exchanges it with `flow.fetch_token(code=...)`. This is the same flow `gcloud auth application-default login` uses and works identically in local and remote/headless/container environments, removing the heuristic of whether to auto-open a browser. Confirmed server-side acceptance with a live GET-only check against the bundled cloud-SDK client (`764086051850-...`); the OOB redirect and a non-bundled client id were both verified to be rejected (`OOB flow has been blocked` / `redirect_uri_mismatch`). Unit tests in `tests/test_auth.py` assert no localhost server is started, the redirect URI + `token_usage=remote` are set, and the pasted code is exchanged. @@ -116,7 +118,7 @@ How each provider supplies the scope: - **Action**: Execute `drive.mount()` and transparently proxy Colab's proprietary credential propagation flow. - **Code**: `python from google.colab import drive - drive.mount('/content/drive')` + drive.mount('/content/drive', timeout_ms=600000)` - **Handling**: Because `drivefs` enforces the ephemeral side-channel propagation (`colab_request` over websocket), the CLI intercepts these messages using `ColabRuntime.colab_request_hook`. When intercepted, the CLI @@ -128,7 +130,27 @@ How each provider supplies the scope: user is OAuthing in their browser. To avoid the upstream 10s `jupyter_kernel_client` default raising `TimeoutError` mid-flow, this subcommand passes `timeout=INTERACTIVE_AUTOMATION_TIMEOUT_SEC` (600s) to - `ColabRuntime.execute_code`. Same applies to `colab auth`. + `ColabRuntime.execute_code`. Same applies to `colab auth`. Separately, + `google.colab.drive.mount` defaults `timeout_ms` to 120000 and that budget + is the `blocking_request` wait, which includes the browser step. The + injected call passes `timeout_ms=600000` so the kernel does not abandon + the mount at two minutes and then fail with `ValueError: mount failed`. +- **Where the prompt runs**: The `colab_request` hook returns immediately + and finishes propagation on a daemon thread. The websocket recv loop stays + free to deliver the kernel's later output. +- **Consent UX**: The CLI prints the `unauthorized_redirect_uri`, highlights + the `login_hint` account, and tries to open that URL in the GUI browser. + The user presses Enter on the controlling terminal (`/dev/tty` or, on + Windows, `CONIN$`). +- **Multi-account 400**: Propagation HTTP 400 means the browser's active + Google account was not the CLI account. The CLI says so and replies to + the kernel with an error `colab_reply` instead of dumping the HTML body + and leaving `drive.mount` to time out. `--authuser N` is an opt-in that + appends `authuser` to the consent URL; it is not applied by default. +- **What still depends on Google**: The CLI cannot make the browser + attribute the gsession to `login_hint` when a different account is active. + The user has to pick the matching account on the chooser. There is no + fully non-interactive Drive mount; the ephemeral consent page is required. ### 4. Logging and Notebook Capture (`colab log`) @@ -291,8 +313,13 @@ TDD is mandatory for all automation features. - **Test Case**: Verify `colab install` correctly injects `pip install` or `uv install` commands to the remote VM kernel. - **Test Case**: Verify `colab drivemount` correctly injects `drive.mount()` - commands and registers the `colab_request_hook` to intercept credential - propagation events. + commands with `timeout_ms` of at least 10 minutes and registers the + `colab_request_hook` to intercept credential propagation events. +- **Test Case**: A propagation HTTP 400 produces an account-mismatch message + (no raw HTML dump) and a `colab_reply` that carries `error`, so the kernel + does not sit until `timeout_ms`. +- **Test Case**: `--authuser` rewrites the consent URL; the default path + leaves the server-built URL unchanged. ### 2. History Capture diff --git a/docs/06_ssh_access.md b/docs/06_ssh_access.md index 312ada8a..0d085eb8 100644 --- a/docs/06_ssh_access.md +++ b/docs/06_ssh_access.md @@ -1,5 +1,7 @@ --- log: +2026-10-07: Windows ProxyCommand. `select()` on the stdin fd raises on Windows (only sockets are selectable), which killed the `--proxy-mode` input pump. The pump now blocks in `os.read`. The ProxyCommand string is quoted with `subprocess.list2cmdline` on Windows because OpenSSH there re-parses it with cmd.exe, and `UserKnownHostsFile` uses `os.devnull` (`nul`) instead of `/dev/null`. `--rm` signal installation skips `SIGHUP` when the interpreter does not define it. + 2026-09-25: Cleaned up keep-alive daemon references in session creation and teardown documentation. 2026-08-09: Added `--high-mem` passthrough when `colab ssh` auto-creates a runtime (forwards to `colab new --high-mem`). 2026-07-17: Initial design and implementation of `colab ssh` — client side of SSH-over-WebSocket runtime access. Adds three modes (interactive shell, `-s SESSION`, and `--proxy-mode` OpenSSH ProxyCommand bridge), `--identity/-i` key selection, and per-HTTP-status handshake error messages. Server side is out of scope for this repo; the subcommand is a no-op against runtimes that do not expose the `/colab/ssh` endpoint (surfaces an actionable HTTP 404 message). diff --git a/skills/colab-operator/SKILL.md b/skills/colab-operator/SKILL.md index b5f2a687..9ac30ed6 100644 --- a/skills/colab-operator/SKILL.md +++ b/skills/colab-operator/SKILL.md @@ -65,7 +65,7 @@ by running `uv tool install google-colab-cli` or `pip install google-colab-cli`. ### Automate - `colab auth -s ` — VM-side GCP creds, needed before in-VM GCS/BigQuery calls (interactive; not agent-runnable). -- `colab drivemount -s [PATH]` — mounts Drive at `/content/drive` by default (interactive; not agent-runnable). +- `colab drivemount -s [--authuser N] [PATH]` — mounts Drive at `/content/drive` by default (interactive; not agent-runnable). The user must approve the printed consent URL in a browser as the same account `colab whoami` shows; a multi-account browser rejects the mount with HTTP 400 unless that account is the one selected on the chooser. The kernel waits 10 minutes, not 2. - `colab install -s pkg1 pkg2` — installs via `uv pip install --system`, falling back to `pip`. Also `colab install -s -r requirements.txt`. ### Inspect & report diff --git a/src/colab_cli/cli.py b/src/colab_cli/cli.py index 5f837eaf..77b4c8f7 100644 --- a/src/colab_cli/cli.py +++ b/src/colab_cli/cli.py @@ -23,7 +23,16 @@ from colab_cli import auto_update from colab_cli.auth import AuthProvider from colab_cli.common import state, setup_logging -from colab_cli.commands import session, execution, files, automation, run, ssh, utility, usage +from colab_cli.commands import ( + session, + execution, + files, + automation, + run, + ssh, + utility, + usage, +) class AlphabeticalGroup(TyperGroup): @@ -80,6 +89,12 @@ def callback( """ Colab CLI global configuration. """ + # ANSI colors and cursor control in cmd.exe / Windows PowerShell 5.1. + # No-op on Linux, macOS, and consoles that already have virtual-terminal + # processing enabled. + from colab_cli.terminal import enable_windows_virtual_terminal + + enable_windows_virtual_terminal() state.client_oauth_config = client_oauth_config state.config_path = config state.logtostderr = logtostderr diff --git a/src/colab_cli/commands/automation.py b/src/colab_cli/commands/automation.py index d2600091..ff0797b6 100644 --- a/src/colab_cli/commands/automation.py +++ b/src/colab_cli/commands/automation.py @@ -15,16 +15,21 @@ import datetime import os import sys -import json -from typing import Optional, List +import threading +from typing import Callable, Optional, List import typer from rich.console import Console from typing_extensions import Annotated from colab_cli.runtime import ColabRuntime from colab_cli.contents import ContentsClient -from colab_cli.auth import get_credentials -from colab_cli.utils import get_status_code, render_display_data +from colab_cli.drive_auth import ( + DRIVE_AUTH_TIMEOUT_SEC, + mount_code, + perform_drive_authorization, + send_colab_reply, +) +from colab_cli.utils import render_display_data _console = Console() @@ -33,11 +38,76 @@ # drivemount). The kernel goes silent while the user completes a browser # OAuth flow, which can routinely take 30s+; the upstream 10s default # raises ``TimeoutError`` mid-flow even though the mount actually succeeds. -# 10 minutes is long enough for any realistic interactive auth ceremony -# without leaving CI hangs unbounded. -INTERACTIVE_AUTOMATION_TIMEOUT_SEC = 600 +# 10 minutes matches ``drive.mount(timeout_ms=...)`` so the kernel-side +# ``blocking_request`` does not give up at 120s while the user is still in +# the browser (upstream issue #113). +INTERACTIVE_AUTOMATION_TIMEOUT_SEC = DRIVE_AUTH_TIMEOUT_SEC +def make_drivefs_hook( + state, + session_state, + *, + authuser: str = "0", + rewrite_auth_url: bool = False, + runner: Optional[Callable[[Callable[[], None]], None]] = None, +): + """Build the ``colab_request`` hook that answers ``dfs_ephemeral`` mounts. + + The handshake (HTTP propagation, browser prompt, stdin reply) runs off the + websocket thread. Doing it inside ``on_message`` blocks the recv loop for + the whole consent wait, so the kernel's execute reply cannot be delivered + and a late Enter looks like a hang. ``runner`` exists so tests can run the + worker inline; production starts a daemon thread. + """ + + def drivefs_hook(deserialize_msg, wsclient): + content = deserialize_msg.get("content") or {} + request = content.get("request") or {} + if request.get("authType") != "dfs_ephemeral": + return False + msg_id = (deserialize_msg.get("metadata") or {}).get("colab_msg_id") + state.history.log_event( + session_state.name, + "colab_request", + {"type": "dfs_ephemeral", "colab_msg_id": msg_id}, + ) + + def work(): + try: + from colab_cli.auth import get_credentials + + http = get_credentials( + state.client_oauth_config, provider=state.auth_provider + ) + perform_drive_authorization( + colab_domain=state.client.colab_domain, + endpoint=session_state.endpoint, + http=http, + wsclient=wsclient, + deserialize_msg=deserialize_msg, + msg_id=msg_id, + authuser=authuser, + rewrite_auth_url=rewrite_auth_url, + on_event=lambda ev, payload: state.history.log_event( + session_state.name, ev, payload + ), + ) + except Exception as exc: + typer.echo(f"[colab] Drive authorization failed: {exc}", err=True) + try: + send_colab_reply(wsclient, deserialize_msg, msg_id, error=str(exc)) + except Exception: + pass + + if runner is not None: + runner(work) + else: + threading.Thread(target=work, daemon=True, name="colab-drive-auth").start() + return True + + return drivefs_hook + def run_automation( name: str, @@ -46,102 +116,19 @@ def run_automation( allow_stdin: bool = False, path: str = None, timeout: Optional[float] = None, + authuser: str = "0", + rewrite_auth_url: bool = False, ): from colab_cli.common import state s = state.get_session(name) runtime = ColabRuntime(s.url, s.token, session_name=s.name, history=state.history) - - def drivefs_hook(deserialize_msg, wsclient): - content = deserialize_msg.get("content", {}) - if content.get("request", {}).get("authType") == "dfs_ephemeral": - msg_id = deserialize_msg.get("metadata", {}).get("colab_msg_id") - state.history.log_event( - s.name, - "colab_request", - {"type": "dfs_ephemeral", "colab_msg_id": msg_id}, - ) - url = f"{state.client.colab_domain}/tun/m/credentials-propagation/{s.endpoint}" - params = { - "authuser": "0", - "authtype": "dfs_ephemeral", - "version": "2", - "dryrun": "true", - "propagate": "true", - "record": "false", - } - typer.echo( - f"\n[colab] Intercepted Drive Auth Request. Connecting to {state.client.colab_domain}..." - ) - - creds = get_credentials( - state.client_oauth_config, provider=state.auth_provider - ) - resp = creds.request("GET", url, params=params) - token = ( - json.loads(resp.text.split("\n", 1)[-1]).get("token") - if get_status_code(resp) == 200 - else None - ) - - headers = {"x-goog-colab-token": token} - resp = creds.request( - "POST", - url, - params=params, - headers=headers, - files={"file_id": (None, "empty.ipynb")}, - ) - data = json.loads(resp.text.split("\n", 1)[-1]) - - if not data.get("success"): - uri = data.get("unauthorized_redirect_uri") - typer.echo( - f"\n[colab] REQUIRED: Google Drive Authorization needed.\nPlease visit:\n\n{uri}\n" - ) - state.history.log_event(s.name, "drive_auth_needed", {"uri": uri}) - sys.stdout.write("Press Enter after you have granted access... ") - sys.stdout.flush() - try: - with open("/dev/tty") as tty: - tty.readline() - except (FileNotFoundError, OSError, IOError): - # Windows has no /dev/tty; fall back to stdin. - try: - sys.stdin.readline() - except Exception: - try: - input() - except Exception: - pass - - typer.echo("[colab] Authorizing VM...") - params["dryrun"] = "false" - resp = creds.request( - "POST", - url, - params=params, - headers=headers, - files={"file_id": (None, "empty.ipynb")}, - ) - if get_status_code(resp) == 200: - typer.echo("[colab] Credentials propagated. Resuming mount...") - state.history.log_event(s.name, "drive_auth_success", {}) - reply = wsclient.session.msg( - "input_reply", - {"value": {"type": "colab_reply", "colab_msg_id": msg_id}}, - ) - if "header" in deserialize_msg: - reply["parent_header"] = deserialize_msg["header"] - wsclient.stdin_channel.send(reply) - else: - typer.echo( - f"[colab] Error propagating: {get_status_code(resp)} {resp.text}" - ) - return True - return False - - runtime.colab_request_hook = drivefs_hook + runtime.colab_request_hook = make_drivefs_hook( + state, + s, + authuser=authuser, + rewrite_auth_url=rewrite_auth_url, + ) try: s.running = f"automation({op})" s.last_execution = ( @@ -208,13 +195,27 @@ def drivemount( session: Annotated[ Optional[str], typer.Option("-s", "--session", help="Session name") ] = None, + authuser: Annotated[ + Optional[str], + typer.Option( + "--authuser", + help=( + "Account index to select on the Drive consent screen. " + "Appended to the authorization URL. Set this only when the " + "chooser opens the wrong Google account. The propagation " + "request's authuser parameter does not by itself fix a " + "multi-account HTTP 400." + ), + ), + ] = None, path: Annotated[str, typer.Argument(help="Mount path")] = "/content/drive", ): """Mount Google Drive at path""" from colab_cli.common import state name = state.resolve_session(session) - code = f"from google.colab import drive\ndrive.mount('{path}')" + explicit_authuser = authuser is not None + code = mount_code(path, timeout_ms=INTERACTIVE_AUTOMATION_TIMEOUT_SEC * 1000) typer.echo(f"[colab] Mounting Google Drive to '{path}' on {name}...") run_automation( name, @@ -223,6 +224,8 @@ def drivemount( allow_stdin=True, path=path, timeout=INTERACTIVE_AUTOMATION_TIMEOUT_SEC, + authuser=authuser if explicit_authuser else "0", + rewrite_auth_url=explicit_authuser, ) diff --git a/src/colab_cli/commands/ssh.py b/src/colab_cli/commands/ssh.py index 5bceea7a..2d37caae 100644 --- a/src/colab_cli/commands/ssh.py +++ b/src/colab_cli/commands/ssh.py @@ -37,8 +37,6 @@ import contextlib import os from pathlib import Path -import select -import shlex import signal import subprocess import sys @@ -48,6 +46,7 @@ import uuid from colab_cli.state import SessionState +from colab_cli.terminal import join_argv import typer from typing_extensions import Annotated import websocket @@ -93,9 +92,7 @@ def _pubkey_from_identity(identity: str) -> str: raise typer.Exit(code=2) pubkey = res.stdout.strip() if not pubkey: - typer.echo( - f"[colab] ssh-keygen produced no key for {identity}.", err=True - ) + typer.echo(f"[colab] ssh-keygen produced no key for {identity}.", err=True) raise typer.Exit(code=2) return pubkey @@ -346,6 +343,33 @@ def _close_quietly(ws: websocket.WebSocket) -> None: _DATA_OPCODES = (websocket.ABNF.OPCODE_BINARY, websocket.ABNF.OPCODE_TEXT) +def _pump_stdin_to_ws(ws: websocket.WebSocket, read=os.read, fileno=None) -> None: + """Copy stdin bytes onto the WebSocket until EOF. + + A blocking ``os.read`` is equivalent to ``select`` on a single fd with no + timeout, and it works on Windows. ``select.select`` only accepts sockets + there, so calling it on the stdin handle raises ``OSError`` and the pump + thread dies immediately — ``colab ssh --proxy-mode`` then accepts output + but never forwards keystrokes (upstream issues #85 / #100, PR #158). + + Args: + ws: The connected WebSocket to write binary frames to. + read: Byte reader, injectable in tests. Defaults to ``os.read``. + fileno: Stdin fd. Defaults to ``sys.stdin.buffer.fileno()``. + """ + stdin_fd = sys.stdin.buffer.fileno() if fileno is None else fileno + try: + while True: + data = read(stdin_fd, 8192) + if not data: + break + ws.send_binary(data) + except (OSError, websocket.WebSocketException): + pass + finally: + _close_quietly(ws) + + def _bridge_proxy_mode(ws: websocket.WebSocket) -> int: """Bridges the WebSocket <-> stdin/stdout as an OpenSSH ProxyCommand. @@ -355,24 +379,8 @@ def _bridge_proxy_mode(ws: websocket.WebSocket) -> int: Returns: 0 when either side closes. """ - stdin_fd = sys.stdin.buffer.fileno() - def stdin_to_ws(): - try: - while True: - ready, _, _ = select.select([stdin_fd], [], [], None) - if not ready: - continue - data = os.read(stdin_fd, 8192) - if not data: - break - ws.send_binary(data) - except (OSError, websocket.WebSocketException): - pass - finally: - _close_quietly(ws) - - threading.Thread(target=stdin_to_ws, daemon=True).start() + threading.Thread(target=_pump_stdin_to_ws, args=(ws,), daemon=True).start() try: while True: @@ -409,7 +417,9 @@ def _proxy_command(session: SessionState, identity: Optional[str]) -> str: ] if identity: self_cmd.extend(["--identity", identity]) - return shlex.join(self_cmd) + # POSIX OpenSSH re-parses this with /bin/sh. Windows OpenSSH uses cmd.exe, + # which does not honor single quotes. + return join_argv(self_cmd) def _ssh_base_args(proxy_command: str, identity: Optional[str]) -> list[str]: @@ -421,7 +431,9 @@ def _ssh_base_args(proxy_command: str, identity: Optional[str]) -> list[str]: "-o", "StrictHostKeyChecking=no", "-o", - "UserKnownHostsFile=/dev/null", + # ``/dev/null`` on POSIX, ``nul`` on Windows. Windows OpenSSH rejects + # a POSIX null path for the known-hosts file. + f"UserKnownHostsFile={os.devnull}", "-o", "LogLevel=ERROR", ] @@ -482,9 +494,7 @@ def _select_proxy_session( """ if session and not _session_exists(session): with contextlib.redirect_stdout(sys.stderr): - return _auto_create_session( - gpu, tpu, name=session, high_mem=high_mem - ), True + return _auto_create_session(gpu, tpu, name=session, high_mem=high_mem), True return _resolve_session(session), False @@ -546,16 +556,19 @@ def _on_signal(signum, frame): do_rm() os._exit(0) - for sig in (signal.SIGHUP, signal.SIGTERM, signal.SIGINT): + # Windows has SIGINT and SIGTERM but not SIGHUP. Looking the name up + # with getattr avoids AttributeError while evaluating the signal list. + for name in ("SIGHUP", "SIGTERM", "SIGINT"): + sig = getattr(signal, name, None) + if sig is None: + continue try: signal.signal(sig, _on_signal) except (ValueError, OSError): pass # e.g. not running in the main thread -def _run_proxy_bridge( - s: SessionState, identity: Optional[str], rm: bool -) -> int: +def _run_proxy_bridge(s: SessionState, identity: Optional[str], rm: bool) -> int: """Runs the ``--proxy-mode`` WebSocket-stdio bridge, honoring ``--rm``. Args: diff --git a/src/colab_cli/console.py b/src/colab_cli/console.py index ae2786bb..a73c165b 100644 --- a/src/colab_cli/console.py +++ b/src/colab_cli/console.py @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +import contextlib import json import logging import os @@ -33,6 +34,12 @@ import websocket from colab_cli.state import SessionState +from colab_cli.terminal import ( + enable_windows_virtual_terminal, + is_windows, + read_windows_key, + windows_raw_console, +) logger = logging.getLogger(__name__) @@ -96,30 +103,44 @@ def on_open(ws): # Setup the background thread to read from stdin def read_stdin(): is_tty = sys.stdin.isatty() + # Windows consoles are line-buffered unless we switched to raw mode + # in connect_console(). Read keystrokes through the console API and + # translate scan codes to ANSI so cmd.exe and PowerShell behave like + # a POSIX raw tty. Piped stdin stays on sys.stdin.read so EOF still + # works. + windows_tty = is_windows() and is_tty while _is_running: try: - # Read a single character (or escape sequence byte) - char = sys.stdin.read(1) - if not char: - if not is_tty: - # Piped input has reached EOF. The remote /colab/tty - # endpoint wraps bash in tmux which intercepts \x04 - # (Ctrl-D) as a literal character, so it never exits. - # Instead send "exit\n" so bash voluntarily terminates, - # wait a short grace period for the shell's goodbye - # output to drain back to us, then close the websocket - # ourselves to guarantee the client unblocks. - try: - ws.send(json.dumps({"data": "exit\n"})) - except Exception: - pass - time.sleep(PIPED_EOF_GRACE_SECONDS) - try: - ws.close() - except Exception: - pass - break - ws.send(json.dumps({"data": char})) + if windows_tty: + text = read_windows_key() + if not text: + continue + chunks = list(text) + else: + # Read a single character (or escape sequence byte) + char = sys.stdin.read(1) + if not char: + if not is_tty: + # Piped input has reached EOF. The remote /colab/tty + # endpoint wraps bash in tmux which intercepts \x04 + # (Ctrl-D) as a literal character, so it never exits. + # Instead send "exit\n" so bash voluntarily terminates, + # wait a short grace period for the shell's goodbye + # output to drain back to us, then close the websocket + # ourselves to guarantee the client unblocks. + try: + ws.send(json.dumps({"data": "exit\n"})) + except Exception: + pass + time.sleep(PIPED_EOF_GRACE_SECONDS) + try: + ws.close() + except Exception: + pass + break + chunks = [char] + for chunk in chunks: + ws.send(json.dumps({"data": chunk})) except Exception: break @@ -133,6 +154,10 @@ def connect_console(session: SessionState): """ global _is_running, _last_error _last_error = None + # cmd.exe and Windows PowerShell 5.1 do not enable ANSI processing by + # default. The remote PTY speaks ANSI, and we write those bytes straight + # to stdout.buffer, so the console mode has to be switched first. + enable_windows_virtual_terminal() # Construct the WebSocket URL from the base URL parsed = urlparse(session.url) @@ -143,6 +168,9 @@ def connect_console(session: SessionState): fd = None old_settings = None can_raw = termios is not None and tty is not None and is_tty + # Windows has no termios. Raw mode is the console API instead, so + # interactive `colab console` is not stuck in cooked line editing. + use_windows_raw = is_windows() and is_tty and not can_raw if can_raw: try: fd = sys.stdin.fileno() @@ -166,22 +194,43 @@ def handle_sigwinch(signum, frame): send_terminal_size(ws) sigwinch = getattr(signal, "SIGWINCH", None) - try: - if can_raw: - tty.setraw(fd, termios.TCSANOW) - if sigwinch is not None: - signal.signal(sigwinch, handle_sigwinch) + resize_stop = threading.Event() - # This is a blocking call until the connection is closed - ws.run_forever() + def _watch_resize(): + """Poll the console size. Windows has no SIGWINCH.""" + last = None + while not resize_stop.is_set(): + try: + size = os.get_terminal_size() + current = (size.columns, size.lines) + if current != last: + last = current + send_terminal_size(ws) + except Exception: + pass + resize_stop.wait(0.4) - if _last_error: - # Re-raise or wrap terminal errors - err_msg = str(_last_error) - if "404" in err_msg or "401" in err_msg: - # We raise a standard exception that the caller can recognize - raise RuntimeError(f"Connection failed: {err_msg}") + raw_cm = windows_raw_console() if use_windows_raw else contextlib.nullcontext() + try: + with raw_cm: + if use_windows_raw: + threading.Thread(target=_watch_resize, daemon=True).start() + if can_raw: + tty.setraw(fd, termios.TCSANOW) + if sigwinch is not None: + signal.signal(sigwinch, handle_sigwinch) + + # This is a blocking call until the connection is closed + ws.run_forever() + + if _last_error: + # Re-raise or wrap terminal errors + err_msg = str(_last_error) + if "404" in err_msg or "401" in err_msg: + # We raise a standard exception that the caller can recognize + raise RuntimeError(f"Connection failed: {err_msg}") finally: + resize_stop.set() if can_raw: # Always ensure the terminal is restored to its original state try: diff --git a/src/colab_cli/drive_auth.py b/src/colab_cli/drive_auth.py new file mode 100644 index 00000000..a9ae5dde --- /dev/null +++ b/src/colab_cli/drive_auth.py @@ -0,0 +1,303 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Google Drive credential propagation for ``colab drivemount``. + +The kernel's ``drive.mount()`` blocks in ``google.colab._message.blocking_request`` +until the frontend answers the ``dfs_ephemeral`` ``colab_request`` with an +``input_reply`` whose value is ``{"type": "colab_reply", "colab_msg_id": ...}``. +The default ``timeout_ms`` is 120000, and that budget includes the time the +user spends in the browser. This module keeps that wait aligned with the CLI's +interactive timeout and turns the multi-account HTTP 400 into an actionable +message instead of a raw HTML error page. +""" + +import json +import re +from typing import Any, Callable, Optional +from urllib.parse import parse_qs, parse_qsl, urlencode, urlparse, urlunparse + +from colab_cli.terminal import open_url_in_browser, read_controlling_line + +# google.colab.drive.mount defaults to 120s. That is shorter than a normal +# consent click-through, so the kernel gives up, starts DriveFS with no +# credentials, and raises ``ValueError: mount failed`` (upstream issue #113). +# 10 minutes matches the CLI execute() ceiling for this command. +DRIVE_AUTH_TIMEOUT_SEC = 600 +DRIVE_MOUNT_TIMEOUT_MS = DRIVE_AUTH_TIMEOUT_SEC * 1000 + +_XSSI_PREFIX = ")]}'" +_ISSUE_103 = "https://github.com/googlecolab/google-colab-cli/issues/103" +_ISSUE_113 = "https://github.com/googlecolab/google-colab-cli/issues/113" + +Echo = Callable[[str], None] +BrowserOpener = Callable[[str], bool] +LineReader = Callable[..., str] +EventLogger = Callable[[str, dict], None] + + +def mount_code(path: str, timeout_ms: int = DRIVE_MOUNT_TIMEOUT_MS) -> str: + """Python source that mounts Drive and waits long enough for browser consent. + + ``path`` is embedded with ``repr`` so quotes and backslashes round-trip. + """ + return ( + "from google.colab import drive\n" + f"drive.mount({path!r}, timeout_ms={int(timeout_ms)})" + ) + + +def login_hint(uri: str) -> Optional[str]: + """Return the ``login_hint`` query value, or None when it is absent.""" + if not uri: + return None + values = parse_qs(urlparse(uri).query).get("login_hint") or [] + if not values or not values[0]: + return None + return values[0] + + +def with_authuser(uri: str, authuser: Optional[str]) -> str: + """Return ``uri`` with its ``authuser`` query parameter set. + + ``authuser is None`` leaves the URL alone. The server-built consent URL + already carries ``login_hint``; appending ``authuser=0`` by default can + pin a multi-account browser to the wrong account. + """ + if not uri or authuser is None: + return uri + parts = urlparse(uri) + pairs = [ + (key, value) + for key, value in parse_qsl(parts.query, keep_blank_values=True) + if key != "authuser" + ] + pairs.append(("authuser", str(authuser))) + return urlunparse(parts._replace(query=urlencode(pairs))) + + +def propagation_params(authuser: str, *, dryrun: bool) -> dict: + """Query parameters for ``/tun/m/credentials-propagation``.""" + return { + "authuser": str(authuser), + "authtype": "dfs_ephemeral", + "version": "2", + "dryrun": "true" if dryrun else "false", + "propagate": "true", + "record": "false", + } + + +def parse_colab_json(text: str) -> dict: + """Parse a Colab JSON body, stripping the XSSI guard prefix when present.""" + if not text: + return {} + raw = text + if raw.startswith(_XSSI_PREFIX): + raw = raw[len(_XSSI_PREFIX) :] + if raw.startswith("\n"): + raw = raw[1:] + raw = raw.strip() + if not raw: + return {} + try: + data = json.loads(raw) + except json.JSONDecodeError: + return {} + return data if isinstance(data, dict) else {} + + +def _plain_snippet(body: str, limit: int = 300) -> str: + text = re.sub(r"<[^>]+>", " ", body or "") + text = re.sub(r"\s+", " ", text).strip() + if len(text) > limit: + text = text[:limit] + "..." + return text + + +def explain_propagation_failure(status: Optional[int], body: str) -> str: + """Human-readable propagation failure. + + A 400 from this endpoint is the multi-account mismatch described in + upstream issue #103: the consent screen follows ``login_hint``, but the + gsession created at the redirect is attributed to the browser's *active* + account. The response body is a full HTML error page; dumping it does not + tell the user what to do. + """ + snippet = _plain_snippet(body) + guidance = ( + "The browser account that approved access did not match the CLI " + "account. On the account chooser, select the account named in the " + "login_hint (printed above, and shown by `colab whoami`). " + f"{_ISSUE_103}" + ) + if status == 400 or (body and "Bad Request" in body): + message = ( + f"[colab] Drive credential propagation was rejected (HTTP {status}). " + f"{guidance}" + ) + if snippet: + message = f"{message}\n{snippet}" + return message + suffix = f" {snippet}" if snippet else "" + return f"[colab] Error propagating: {status}{suffix}" + + +def send_colab_reply( + wsclient: Any, + deserialize_msg: dict, + msg_id: Any, + *, + error: Optional[str] = None, +) -> None: + """Unblock ``drive.mount`` with a ``colab_reply`` on the stdin channel. + + The kernel matches ``content.value.colab_msg_id`` to the integer it stored + in the request metadata. An ``error`` field makes ``read_reply_from_input`` + raise ``MessageError`` immediately instead of waiting out the mount timeout + and then failing with an empty ``ValueError: mount failed``. + """ + value: dict = {"type": "colab_reply", "colab_msg_id": msg_id} + if error: + value["error"] = error + reply = wsclient.session.msg("input_reply", {"value": value}) + header = deserialize_msg.get("header") + if header: + reply["parent_header"] = header + wsclient.stdin_channel.send(reply) + + +def _json_ok(resp: Any) -> dict: + if getattr(resp, "status_code", None) != 200: + return {} + return parse_colab_json(getattr(resp, "text", "") or "") + + +def perform_drive_authorization( + *, + colab_domain: str, + endpoint: str, + http: Any, + wsclient: Any, + deserialize_msg: dict, + msg_id: Any, + authuser: str = "0", + rewrite_auth_url: bool = False, + open_browser: BrowserOpener = open_url_in_browser, + read_line: LineReader = read_controlling_line, + echo: Optional[Echo] = None, + on_event: Optional[EventLogger] = None, +) -> None: + """Run the Drive credential-propagation handshake and reply to the kernel. + + ``http`` is an authorized ``requests`` session (``get_credentials``). + ``rewrite_auth_url`` appends ``authuser`` to the consent URL. It is off + unless the user passed ``--authuser``: issue #103 showed that changing the + propagation *request* parameter does not fix a multi-account 400, and + forcing ``authuser=0`` onto the browser URL can select the wrong account. + """ + if echo is None: + import typer + + echo = typer.echo + + def emit(message: str) -> None: + echo(message) + + def event(name: str, payload: dict) -> None: + if on_event: + on_event(name, payload) + + url = f"{colab_domain}/tun/m/credentials-propagation/{endpoint}" + emit(f"\n[colab] Intercepted Drive Auth Request. Connecting to {colab_domain}...") + params = propagation_params(authuser, dryrun=True) + token_resp = http.request("GET", url, params=params) + token = _json_ok(token_resp).get("token") + headers = {"x-goog-colab-token": token} if token else {} + files = {"file_id": (None, "empty.ipynb")} + probe = http.request("POST", url, params=params, headers=headers, files=files) + if getattr(probe, "status_code", None) != 200: + message = explain_propagation_failure( + getattr(probe, "status_code", None), getattr(probe, "text", "") or "" + ) + emit(message) + send_colab_reply( + wsclient, + deserialize_msg, + msg_id, + error="Drive credential propagation failed before consent.", + ) + return + + data = _json_ok(probe) + if not data.get("success"): + uri = data.get("unauthorized_redirect_uri") or "" + if rewrite_auth_url: + uri = with_authuser(uri, authuser) + if not uri: + emit("[colab] Drive auth did not return a consent URL.") + emit( + explain_propagation_failure( + getattr(probe, "status_code", None), + getattr(probe, "text", "") or "", + ) + ) + send_colab_reply( + wsclient, + deserialize_msg, + msg_id, + error="Drive auth did not return a consent URL.", + ) + return + account = ( + login_hint(uri) or "the account this CLI authenticated as (colab whoami)" + ) + emit("[colab] Google Drive authorization needed.") + emit(f"Sign in as {account}.") + emit( + "If the browser is signed into more than one Google account, pick " + "this account on the chooser. login_hint alone is not enough: Colab " + "attributes the Drive session to the browser's active account and " + f"rejects a mismatch with HTTP 400 ({_ISSUE_103})." + ) + emit("") + emit(uri) + emit("") + event("drive_auth_needed", {"uri": uri}) + if open_browser(uri): + emit("[colab] Opened that link in your browser.") + else: + emit("[colab] Could not launch a browser here. Open the link above.") + emit(f"[colab] The kernel waits up to 10 minutes for this step ({_ISSUE_113}).") + read_line("Press Enter after you have granted access... ") + + emit("[colab] Authorizing VM...") + params = propagation_params(authuser, dryrun=False) + final = http.request("POST", url, params=params, headers=headers, files=files) + if getattr(final, "status_code", None) == 200: + emit("[colab] Credentials propagated. Resuming mount...") + event("drive_auth_success", {}) + send_colab_reply(wsclient, deserialize_msg, msg_id) + return + + message = explain_propagation_failure( + getattr(final, "status_code", None), getattr(final, "text", "") or "" + ) + emit(message) + send_colab_reply( + wsclient, + deserialize_msg, + msg_id, + error=message, + ) diff --git a/src/colab_cli/terminal.py b/src/colab_cli/terminal.py new file mode 100644 index 00000000..9a440932 --- /dev/null +++ b/src/colab_cli/terminal.py @@ -0,0 +1,242 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Cross-platform terminal helpers. + +POSIX keeps using ``termios`` raw mode in ``console.py``. Windows consoles +(cmd.exe and PowerShell, both conhost and Windows Terminal) have no +``termios``, no ``/dev/tty``, and no ``SIGWINCH``. This module owns the +Windows console-mode and key-translation pieces, plus the controlling-terminal +line read used by interactive prompts. +""" + +import os +import shutil +import subprocess +import sys +from contextlib import contextmanager +from typing import Iterator, Optional + +# Win32 console mode flags. See +# https://learn.microsoft.com/en-us/windows/console/setconsolemode +_ENABLE_PROCESSED_OUTPUT = 0x0001 +_ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004 +_ENABLE_VIRTUAL_TERMINAL_INPUT = 0x0200 +_ENABLE_EXTENDED_FLAGS = 0x0080 + +_STD_INPUT_HANDLE = -10 +_STD_OUTPUT_HANDLE = -11 +_STD_ERROR_HANDLE = -12 + +# Second byte of a Windows console special key (after \x00 or \xe0) mapped to +# the ANSI sequence a POSIX raw tty would emit for the same key. +_SCAN_TO_ANSI = { + "H": "\x1b[A", # up + "P": "\x1b[B", # down + "M": "\x1b[C", # right + "K": "\x1b[D", # left + "G": "\x1b[H", # home + "O": "\x1b[F", # end + "I": "\x1b[5~", # page up + "Q": "\x1b[6~", # page down + "S": "\x1b[3~", # delete + "R": "\x1b[2~", # insert +} + + +def is_windows() -> bool: + """True on Windows, including cmd.exe and PowerShell.""" + return os.name == "nt" + + +def translate_windows_key(first: str, second: Optional[str] = None) -> str: + """Map one Windows console key event to bytes a POSIX raw tty would send. + + ``msvcrt.getwch`` returns a Unicode character. Special keys arrive as + ``\\x00`` or ``\\xe0`` followed by a scan-code character. Arrow keys must + become ANSI sequences so the remote shell's line editor understands them. + Enter arrives as ``\\r``, which is also what a POSIX raw terminal sends + (local ICRNL is off; the remote pty's ICRNL turns ``\\r`` into ``\\n``). + Unrecognized scan codes return an empty string so they are not forwarded + as garbage. + """ + if first in ("\x00", "\xe0"): + if not second: + return "" + return _SCAN_TO_ANSI.get(second, "") + return first + + +def enable_windows_virtual_terminal() -> bool: + """Enable ANSI processing and UTF-8 on the Windows console. + + cmd.exe and Windows PowerShell 5.1 leave + ``ENABLE_VIRTUAL_TERMINAL_PROCESSING`` off, so cursor movement and colors + written as raw bytes show up as garbage. Windows Terminal and PowerShell 7 + often already have the bit set; setting it again is harmless. No-op off + Windows. Returns True when an output mode was updated. + """ + if not is_windows(): + return False + try: + import ctypes + + kernel32 = ctypes.windll.kernel32 + kernel32.SetConsoleOutputCP(65001) + kernel32.SetConsoleCP(65001) + updated = False + for handle_id in (_STD_OUTPUT_HANDLE, _STD_ERROR_HANDLE): + handle = kernel32.GetStdHandle(handle_id) + mode = ctypes.c_uint() + if not kernel32.GetConsoleMode(handle, ctypes.byref(mode)): + continue + new_mode = ( + mode.value + | _ENABLE_PROCESSED_OUTPUT + | _ENABLE_VIRTUAL_TERMINAL_PROCESSING + ) + if kernel32.SetConsoleMode(handle, new_mode): + updated = True + return updated + except Exception: + return False + + +@contextmanager +def windows_raw_console() -> Iterator[None]: + """Put the Windows console input handle into raw (non-line) mode. + + Clears line-input, echo, and processed-input so keystrokes — including + Ctrl-C as ``\\x03`` — reach this process instead of being edited by + conhost or killing the local CLI. Enables virtual-terminal input so newer + consoles can emit ANSI sequences themselves. Restores the previous mode + on exit. No-op when this is not a Windows console (pipes, POSIX). + """ + if not is_windows(): + yield + return + import ctypes + + kernel32 = ctypes.windll.kernel32 + handle = kernel32.GetStdHandle(_STD_INPUT_HANDLE) + old = ctypes.c_uint() + if not kernel32.GetConsoleMode(handle, ctypes.byref(old)): + yield + return + # Leaving LINE/ECHO/PROCESSED unset is the raw mode. EXTENDED_FLAGS has + # to be set for the mode change to stick on modern conhost. + raw = _ENABLE_VIRTUAL_TERMINAL_INPUT | _ENABLE_EXTENDED_FLAGS + kernel32.SetConsoleMode(handle, raw) + try: + yield + finally: + kernel32.SetConsoleMode(handle, old.value) + + +def read_windows_key() -> str: + """Block for one Windows console key and return an ANSI-compatible string. + + Returns ``""`` for an unrecognized scan code. The caller should not + forward that. + """ + import msvcrt + + first = msvcrt.getwch() + if first in ("\x00", "\xe0"): + second = msvcrt.getwch() + return translate_windows_key(first, second) + return translate_windows_key(first) + + +def read_controlling_line(prompt: str = "") -> str: + """Read one line from the controlling terminal, not from a redirected pipe. + + POSIX opens ``/dev/tty``. Windows opens ``CONIN$``, which is the console + even when stdin is redirected (the same reason the POSIX path avoids + stdin). Falls back to ``sys.stdin`` and then ``input()`` when neither + device exists, which is the case under CI and some IDE consoles. + """ + if prompt: + sys.stdout.write(prompt) + sys.stdout.flush() + if is_windows(): + try: + with open("CONIN$", "r", encoding="utf-8", errors="replace") as con: + return con.readline() + except OSError: + pass + else: + try: + with open("/dev/tty", encoding="utf-8", errors="replace") as tty: + return tty.readline() + except OSError: + pass + try: + return sys.stdin.readline() + except Exception: + try: + return input() + "\n" + except Exception: + return "" + + +def open_url_in_browser(url: str) -> bool: + """Open ``url`` in the system GUI browser. + + Windows uses ``os.startfile``, the same association cmd and PowerShell use + for ``start``. macOS uses ``open``. Other platforms use ``xdg-open`` when + it is on ``PATH``. A missing opener returns False so the caller can keep + the printed URL. This never launches a TUI browser (lynx, w3m), which + would steal the terminal the CLI is prompting on. + """ + if is_windows(): + startfile = getattr(os, "startfile", None) + if startfile is None: + return False + try: + startfile(url) + return True + except OSError: + return False + opener_name = "open" if sys.platform == "darwin" else "xdg-open" + opener = shutil.which(opener_name) + if not opener: + return False + try: + subprocess.Popen( + [opener, url], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + return True + except OSError: + return False + + +def join_argv(argv: list[str], *, windows: Optional[bool] = None) -> str: + """Quote an argv for the shell that will re-parse it. + + POSIX OpenSSH runs ``ProxyCommand`` via ``/bin/sh`` (``shlex.join``). + Windows OpenSSH runs it via ``cmd.exe`` (``subprocess.list2cmdline``). + cmd.exe does not treat single quotes as quoting, so a POSIX-quoted path + such as ``'C:\\Program Files\\Python\\python.exe'`` is passed through + literally and the bridge never starts. + """ + if windows is None: + windows = is_windows() + if windows: + return subprocess.list2cmdline(argv) + import shlex + + return shlex.join(argv) diff --git a/tests/test_automation.py b/tests/test_automation.py index 7407edc9..b3da1f45 100644 --- a/tests/test_automation.py +++ b/tests/test_automation.py @@ -12,7 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -from unittest.mock import patch +from unittest.mock import MagicMock, patch import pytest from typer.testing import CliRunner from colab_cli.cli import app @@ -96,7 +96,11 @@ def test_cli_drivemount(mock_state, mock_runtime_class, mock_session): mock_runtime.execute_code.assert_called_once() called_code = mock_runtime.execute_code.call_args[0][0] - assert "drive.mount('/foo/bar')" in called_code + assert "drive.mount('/foo/bar'" in called_code + assert "timeout_ms=" in called_code + # The kernel-side default is 120s and that budget includes the browser + # consent wait. Anything under 5 minutes will still abort a normal mount. + assert "timeout_ms=120000" not in called_code assert mock_runtime.colab_request_hook is not None # Drivemount waits for the user to OAuth in their browser; the kernel # goes silent during that wait and the default 10s execute() timeout @@ -106,6 +110,53 @@ def test_cli_drivemount(mock_state, mock_runtime_class, mock_session): assert kwargs.get("timeout") is not None and kwargs["timeout"] >= 300 +@patch("colab_cli.commands.automation.perform_drive_authorization") +@patch("colab_cli.auth.get_credentials") +@patch("colab_cli.commands.automation.ColabRuntime") +@patch("colab_cli.common.state") +def test_drivemount_hook_runs_off_the_websocket_thread( + mock_state, mock_runtime_class, _mock_creds, mock_perform, mock_session +): + """The dfs_ephemeral handler must return without doing the browser prompt + on the caller (the websocket recv thread).""" + mock_state.get_session.return_value = mock_session + mock_state.resolve_session.return_value = "test-session" + mock_state.client.colab_domain = "https://colab.research.google.com" + mock_runtime = mock_runtime_class.return_value + mock_runtime.execute_code.return_value = [{"text": "Mounted"}] + + result = runner.invoke(app, ["drivemount", "-s", "test-session", "--authuser", "6"]) + assert result.exit_code == 0 + + hook = mock_runtime.colab_request_hook + msg = { + "content": {"request": {"authType": "dfs_ephemeral"}}, + "metadata": {"colab_msg_id": 3}, + "header": {"msg_id": "parent"}, + } + + class SyncThread: + def __init__(self, target=None, daemon=None, name=None): + self.target = target + + def start(self): + self.target() + + with patch("colab_cli.commands.automation.threading.Thread", SyncThread): + assert hook(msg, MagicMock()) is True + assert mock_perform.call_args.kwargs["authuser"] == "6" + assert mock_perform.call_args.kwargs["rewrite_auth_url"] is True + + other = {"content": {"request": {"authType": "something_else"}}} + assert hook(other, MagicMock()) is False + + +def test_drivemount_help_documents_authuser(): + result = runner.invoke(app, ["drivemount", "--help"]) + assert result.exit_code == 0 + assert "--authuser" in result.output + + @patch("colab_cli.commands.automation.ColabRuntime") @patch("colab_cli.common.state") def test_cli_auth_uses_long_timeout(mock_state, mock_runtime_class, mock_session): diff --git a/tests/test_console.py b/tests/test_console.py index 13f20961..55577eb9 100644 --- a/tests/test_console.py +++ b/tests/test_console.py @@ -235,9 +235,7 @@ def start(self): @patch("colab_cli.console.websocket.WebSocketApp") @patch("colab_cli.console.sys.stdin.isatty") -def test_console_no_termios_degrades_gracefully( - mock_isatty, mock_ws_app, mock_session -): +def test_console_no_termios_degrades_gracefully(mock_isatty, mock_ws_app, mock_session): """Windows has no termios/tty/SIGWINCH. connect_console must not crash. Regression test for `ModuleNotFoundError: No module named 'termios'` @@ -259,3 +257,78 @@ def test_console_no_termios_degrades_gracefully( connect_console(mock_session) mock_ws_instance.run_forever.assert_called_once() + + +@patch("colab_cli.console.websocket.WebSocketApp") +@patch("colab_cli.console.sys.stdin.isatty") +def test_console_windows_uses_raw_console_not_termios( + mock_isatty, mock_ws_app, mock_session +): + """cmd.exe and PowerShell have no termios. Interactive console must switch + the Windows console into raw mode instead of staying line-buffered. + """ + import colab_cli.console as console_mod + + mock_isatty.return_value = True + mock_ws_instance = MagicMock() + mock_ws_app.return_value = mock_ws_instance + mock_ws_instance.run_forever.return_value = None + raw_cm = MagicMock() + + with ( + patch.object(console_mod, "termios", None), + patch.object(console_mod, "tty", None), + patch.object(console_mod, "is_windows", return_value=True), + patch.object( + console_mod, "windows_raw_console", return_value=raw_cm + ) as mock_raw, + patch("colab_cli.console.threading.Thread"), + ): + connect_console(mock_session) + + mock_raw.assert_called_once() + raw_cm.__enter__.assert_called_once() + raw_cm.__exit__.assert_called_once() + mock_ws_instance.run_forever.assert_called_once() + + +@patch("colab_cli.console.os.get_terminal_size") +@patch("colab_cli.console.sys.stdin.isatty") +def test_read_stdin_windows_tty_forwards_translated_keys( + mock_isatty, mock_get_term_size +): + """Arrow keys arrive as Windows scan codes. The remote shell needs the + ANSI sequence, one character per websocket frame, matching POSIX raw mode. + """ + import colab_cli.console as console_mod + + mock_isatty.return_value = True + mock_get_term_size.return_value = os.terminal_size((80, 24)) + keys = ["\x1b[A", "\r"] + + def fake_key(): + if not keys: + console_mod._is_running = False + return "" + return keys.pop(0) + + mock_ws = MagicMock() + + class SyncThread: + def __init__(self, target, daemon=None): + self.target = target + + def start(self): + self.target() + + console_mod._is_running = True + with ( + patch.object(console_mod, "is_windows", return_value=True), + patch.object(console_mod, "read_windows_key", side_effect=fake_key), + patch("colab_cli.console.threading.Thread", SyncThread), + ): + on_open(mock_ws) + + sent = [json.loads(call.args[0]) for call in mock_ws.send.call_args_list] + assert sent[0] == {"cols": 80, "rows": 24} + assert [item["data"] for item in sent[1:]] == ["\x1b", "[", "A", "\r"] diff --git a/tests/test_drive_auth.py b/tests/test_drive_auth.py new file mode 100644 index 00000000..419e96bc --- /dev/null +++ b/tests/test_drive_auth.py @@ -0,0 +1,271 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Drive credential propagation. + +Pins the fixes for upstream issues: +- #113 mount failed after exactly 120s (kernel-side drive.mount timeout) +- #103 HTTP 400 when the browser's active account is not the CLI account +- #108 open the consent URL instead of copy-paste only +""" + +import json +from unittest.mock import MagicMock + +from colab_cli.drive_auth import ( + DRIVE_MOUNT_TIMEOUT_MS, + explain_propagation_failure, + login_hint, + mount_code, + perform_drive_authorization, + with_authuser, +) + + +def test_mount_code_extends_kernel_timeout_past_120s(): + """google.colab.drive.mount defaults timeout_ms to 120000. That budget + covers the browser consent wait, so a normal OAuth click-through makes + the kernel give up and raise ``ValueError: mount failed`` (#113). + """ + code = mount_code("/content/drive") + assert "drive.mount('/content/drive'" in code + assert f"timeout_ms={DRIVE_MOUNT_TIMEOUT_MS}" in code + assert DRIVE_MOUNT_TIMEOUT_MS >= 600_000 + + +def test_mount_code_quotes_path_with_repr(): + code = mount_code("/tmp/drive's") + assert ( + "drive.mount('/tmp/drive\\'s'" in code or 'drive.mount("/tmp/drive\'s"' in code + ) + + +def test_login_hint_is_decoded(): + uri = ( + "https://accounts.google.com/o/oauth2/v2/auth" + "?login_hint=user%40example.com&response_type=none+gsession" + ) + assert login_hint(uri) == "user@example.com" + assert login_hint("") is None + assert login_hint("https://accounts.google.com/o/oauth2/v2/auth") is None + + +def test_with_authuser_appends_and_replaces(): + uri = "https://accounts.google.com/o/oauth2/v2/auth?login_hint=a@b.c&authuser=0" + rewritten = with_authuser(uri, "6") + assert "authuser=6" in rewritten + assert "authuser=0" not in rewritten + assert "login_hint=a%40b.c" in rewritten or "login_hint=a@b.c" in rewritten + assert with_authuser(uri, None) == uri + + +def test_explain_400_is_actionable_and_not_a_raw_html_dump(): + html = ( + "Error 400 (Bad Request)!!1" + "" + ("x" * 8000) + "" + ) + text = explain_propagation_failure(400, html) + assert "400" in text + assert "account" in text.lower() + assert "login_hint" in text or "chooser" in text.lower() + assert "https://github.com/googlecolab/google-colab-cli/issues/103" in text + assert " Date: Wed, 7 Oct 2026 20:46:37 +0200 Subject: [PATCH 2/8] fix: colab edit on Windows (PermissionError on the temp file) `colab edit` kept the local copy in an open NamedTemporaryFile. On Windows an open NamedTemporaryFile cannot be opened again, so the download, the hash and the editor all failed with PermissionError. The download error was swallowed, so without the hash crash the editor would have been given an empty file and saving would have overwritten the remote file. Use a path inside a TemporaryDirectory instead, named after the remote file so editors pick the right syntax, and create it empty when the remote file does not exist. Tested: new regression tests fail without the fix and pass with it on Windows; full suite passes on Linux (384); live on Windows against a CPU runtime, editing an existing and a new remote file round-trips correctly and no temp directories are left behind. Co-Authored-By: Claude Opus 5.5 --- src/colab_cli/commands/files.py | 14 +++++-- tests/test_cli.py | 72 +++++++++++++++++++++++++++++++++ 2 files changed, 82 insertions(+), 4 deletions(-) diff --git a/src/colab_cli/commands/files.py b/src/colab_cli/commands/files.py index fa1c9050..ac843767 100644 --- a/src/colab_cli/commands/files.py +++ b/src/colab_cli/commands/files.py @@ -152,16 +152,22 @@ def get_file_hash(path): with open(path, "rb") as f: return hashlib.file_digest(f, "sha256").hexdigest() - _, ext = os.path.splitext(remote_path) - - with tempfile.NamedTemporaryFile(suffix=ext) as tf: - local_path = tf.name + # A path inside a temporary directory, not NamedTemporaryFile: on Windows + # an open NamedTemporaryFile cannot be opened a second time, so the + # download, the hash and the editor would all fail with PermissionError. + # Keeping the remote basename also gives the editor the right extension. + with tempfile.TemporaryDirectory(prefix="colab-edit-") as tmpdir: + local_path = os.path.join( + tmpdir, os.path.basename(remote_path.rstrip("/")) or "file" + ) try: contents.download(remote_path, local_path) except Exception: # If download fails, assume file doesn't exist and start empty pass + if not os.path.exists(local_path): + open(local_path, "wb").close() hash_before = get_file_hash(local_path) diff --git a/tests/test_cli.py b/tests/test_cli.py index b7d08ef2..b2fb367e 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -12,6 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +import os import time from datetime import datetime, timedelta, timezone from unittest.mock import MagicMock, patch @@ -568,6 +569,77 @@ def mock_edit_side_effect(filename, **kwargs): assert "Edited and uploaded 'remote.txt'" in result.output +@patch("colab_cli.commands.files.ContentsClient") +@patch("click.edit") +def test_cli_edit_round_trips_downloaded_content( + mock_edit, mock_contents_class, mock_store, mock_common_state +): + """The download, the editor and the upload must all be able to open the + local file. With an open NamedTemporaryFile this fails on Windows, and the + swallowed download error left the editor with an empty file.""" + mock_common_state.resolve_session.return_value = "s1" + contents = mock_contents_class.return_value + + def fake_download(remote, local): + with open(local, "w") as f: + f.write("remote content\n") + + contents.download.side_effect = fake_download + + seen = {} + + def fake_editor(filename, **kwargs): + seen["path"] = filename + with open(filename) as f: + seen["content"] = f.read() + with open(filename, "a") as f: + f.write("edited\n") + + mock_edit.side_effect = fake_editor + + uploaded = {} + + def fake_upload(local, remote): + with open(local) as f: + uploaded[remote] = f.read() + + contents.upload.side_effect = fake_upload + + result = runner.invoke(app, ["edit", "-s", "s1", "/content/dir/remote.py"]) + + assert result.exit_code == 0, result.output + assert seen["content"] == "remote content\n" + assert os.path.basename(seen["path"]) == "remote.py" + assert uploaded == {"/content/dir/remote.py": "remote content\nedited\n"} + assert not os.path.exists(seen["path"]) + + +@patch("colab_cli.commands.files.ContentsClient") +@patch("click.edit") +def test_cli_edit_missing_remote_file_starts_empty( + mock_edit, mock_contents_class, mock_store, mock_common_state +): + mock_common_state.resolve_session.return_value = "s1" + contents = mock_contents_class.return_value + contents.download.side_effect = Exception("404") + + seen = {} + + def fake_editor(filename, **kwargs): + seen["exists"] = os.path.exists(filename) + with open(filename, "a") as f: + f.write("brand new\n") + + mock_edit.side_effect = fake_editor + + result = runner.invoke(app, ["edit", "-s", "s1", "new.txt"]) + + assert result.exit_code == 0, result.output + assert seen["exists"] is True + contents.upload.assert_called_once() + assert "Edited and uploaded 'new.txt'" in result.output + + def _make_400_error(message="Bad Request"): """Build a ColabRequestError shaped like a 400 from the assign endpoint.""" response = MagicMock() From f3ef7c8e315d53f500228402412b974a8acb7ba4 Mon Sep 17 00:00:00 2001 From: "arlinamid\\arlinamid" Date: Wed, 7 Oct 2026 20:59:14 +0200 Subject: [PATCH 3/8] fix: escape % in the ssh ProxyCommand; make the test suite pass on Windows ProxyCommand (bug fix) OpenSSH expands %-tokens (%h, %p, ...) in ProxyCommand before running it, on POSIX and on Windows. A session name or identity path containing '%' either failed ("unknown key %x") or was silently rewritten ('a%h' became 'a'). _proxy_command now writes '%' as '%%'. Checked against OpenSSH 10.5p1 (WSL) and OpenSSH_for_Windows_9.5p2. The same check showed that OpenSSH for Windows does not run ProxyCommand through cmd.exe: 'a&echo INJECTED' arrives as one literal argument. It goes to CreateProcess and is split with the MSVCRT rules, which is what subprocess.list2cmdline targets, so the code was right and only the comments were wrong. Comments updated. Tests (Windows: 30 failed + 1 hang -> 389 passed, 2 POSIX-only skips) - ProxyCommand round-trip: undo %-escaping, then split with shlex on POSIX and CommandLineToArgvW on Windows. New cases: cmd metacharacters, '%', '%h'. The '%' cases fail without the fix above. - REPL: run each test inside a prompt_toolkit app session with pipe input and DummyOutput; a PromptSession needs a console on Windows. - SIGHUP: patch with create=True, expect only the signals the platform has, and drive the teardown with SIGTERM where SIGHUP does not exist. - --help ordering: skip wrapped description lines (blank command column); Rich renders one column narrower on Windows. - Console: pin the POSIX branch in the TTY-EOF test (on Windows it blocked in msvcrt.getwch) and add a test for the Windows key path. Linux: 391 passed. Co-Authored-By: Claude Opus 5.5 --- src/colab_cli/commands/ssh.py | 8 +++--- src/colab_cli/terminal.py | 6 +++-- tests/test_cli.py | 8 ++++-- tests/test_console.py | 46 ++++++++++++++++++++++++++++++- tests/test_repl.py | 14 ++++++++++ tests/test_ssh.py | 51 ++++++++++++++++++++++++++++++----- tests/test_ssh_autocreate.py | 8 +++++- tests/test_ssh_lifecycle.py | 6 ++++- 8 files changed, 131 insertions(+), 16 deletions(-) diff --git a/src/colab_cli/commands/ssh.py b/src/colab_cli/commands/ssh.py index 2d37caae..c8db6c8a 100644 --- a/src/colab_cli/commands/ssh.py +++ b/src/colab_cli/commands/ssh.py @@ -417,9 +417,11 @@ def _proxy_command(session: SessionState, identity: Optional[str]) -> str: ] if identity: self_cmd.extend(["--identity", identity]) - # POSIX OpenSSH re-parses this with /bin/sh. Windows OpenSSH uses cmd.exe, - # which does not honor single quotes. - return join_argv(self_cmd) + # POSIX OpenSSH re-parses this with /bin/sh. OpenSSH for Windows hands it + # to CreateProcess, so the child splits it with the MSVCRT rules (no + # cmd.exe, no single-quote quoting). Both expand %-tokens (%h, %p, ...) + # before that, so a literal '%' in a name or path must be written '%%'. + return join_argv(self_cmd).replace("%", "%%") def _ssh_base_args(proxy_command: str, identity: Optional[str]) -> list[str]: diff --git a/src/colab_cli/terminal.py b/src/colab_cli/terminal.py index 9a440932..30b817cc 100644 --- a/src/colab_cli/terminal.py +++ b/src/colab_cli/terminal.py @@ -228,8 +228,10 @@ def join_argv(argv: list[str], *, windows: Optional[bool] = None) -> str: """Quote an argv for the shell that will re-parse it. POSIX OpenSSH runs ``ProxyCommand`` via ``/bin/sh`` (``shlex.join``). - Windows OpenSSH runs it via ``cmd.exe`` (``subprocess.list2cmdline``). - cmd.exe does not treat single quotes as quoting, so a POSIX-quoted path + OpenSSH for Windows passes it to ``CreateProcess`` and the child splits + it with the MSVCRT rules (``subprocess.list2cmdline``; checked against + OpenSSH_for_Windows_9.5p2, where ``a&b`` arrives as one literal argument). + Those rules do not treat single quotes as quoting, so a POSIX-quoted path such as ``'C:\\Program Files\\Python\\python.exe'`` is passed through literally and the bridge never starts. """ diff --git a/tests/test_cli.py b/tests/test_cli.py index b2fb367e..b5f6c25e 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -398,9 +398,13 @@ def _extract_command_names(help_output: str) -> list[str]: break # Lines look like: "│ help Show help for a command. │" # Strip the rich box characters. - inner = stripped.strip("│").strip() - if not inner: + inner = stripped.strip("│") + # A wrapped description continues on a line whose command column + # is blank. Rich renders one column narrower on Windows, so this + # happens there at the default width. + if not inner.strip() or not inner[:2].strip(): continue + inner = inner.strip() tok = inner.split()[0] names.append(tok) return names diff --git a/tests/test_console.py b/tests/test_console.py index 55577eb9..d1a52a0e 100644 --- a/tests/test_console.py +++ b/tests/test_console.py @@ -225,7 +225,11 @@ def start(self): self.target() console_mod._is_running = True - with patch("colab_cli.console.threading.Thread", SyncThread): + # This is the POSIX raw-tty path. On Windows a TTY is read through + # msvcrt.getwch(), which would block this test waiting for a keypress. + with patch("colab_cli.console.threading.Thread", SyncThread), patch( + "colab_cli.console.is_windows", return_value=False + ): on_open(mock_ws) sent_payloads = [json.loads(c.args[0]) for c in mock_ws.send.call_args_list] @@ -233,6 +237,46 @@ def start(self): mock_ws.close.assert_not_called() +@patch("colab_cli.console.os.get_terminal_size") +@patch("colab_cli.console.sys.stdin.isatty") +def test_read_stdin_windows_tty_sends_translated_keys( + mock_isatty, mock_get_term_size +): + """On a Windows console, keys come from read_windows_key() (already + translated to ANSI) and are forwarded one character per message.""" + import colab_cli.console as console_mod + + mock_isatty.return_value = True + mock_get_term_size.return_value = os.terminal_size((80, 24)) + mock_ws = MagicMock() + keys = iter(["a", "\x1b[A"]) + + def fake_read_key(): + try: + return next(keys) + except StopIteration: + console_mod._is_running = False + return "" + + class SyncThread: + def __init__(self, target, daemon=None): + self.target = target + + def start(self): + self.target() + + console_mod._is_running = True + with patch("colab_cli.console.threading.Thread", SyncThread), patch( + "colab_cli.console.is_windows", return_value=True + ), patch("colab_cli.console.read_windows_key", side_effect=fake_read_key): + on_open(mock_ws) + + sent = [json.loads(c.args[0]) for c in mock_ws.send.call_args_list] + data = [p["data"] for p in sent if "data" in p] + assert data == ["a", "\x1b", "[", "A"] + mock_ws.close.assert_not_called() + + @patch("colab_cli.console.websocket.WebSocketApp") @patch("colab_cli.console.sys.stdin.isatty") def test_console_no_termios_degrades_gracefully(mock_isatty, mock_ws_app, mock_session): diff --git a/tests/test_repl.py b/tests/test_repl.py index 36dbcdb3..ce1a7745 100644 --- a/tests/test_repl.py +++ b/tests/test_repl.py @@ -23,6 +23,20 @@ runner = CliRunner() +@pytest.fixture(autouse=True) +def _prompt_toolkit_app_session(): + """ColabREPL builds a PromptSession, which needs a terminal. On Windows + without a console prompt_toolkit raises NoConsoleScreenBufferError, so + give every test prompt_toolkit's own pipe input and dummy output.""" + from prompt_toolkit.application import create_app_session + from prompt_toolkit.input import create_pipe_input + from prompt_toolkit.output import DummyOutput + + with create_pipe_input() as pipe_input: + with create_app_session(input=pipe_input, output=DummyOutput()): + yield + + @pytest.fixture def mock_store(mock_common_state): return mock_common_state.store diff --git a/tests/test_ssh.py b/tests/test_ssh.py index 23caddbd..0f2237c1 100644 --- a/tests/test_ssh.py +++ b/tests/test_ssh.py @@ -249,7 +249,8 @@ def test_pump_stdin_uses_blocking_read_not_select(): def test_proxy_command_windows_cmd_quoting(mocker): - """Windows OpenSSH parses ProxyCommand with cmd.exe.""" + """OpenSSH for Windows splits ProxyCommand with the MSVCRT rules, which + only honor double quotes.""" mocker.patch("colab_cli.terminal.is_windows", return_value=True) cmd = ssh_module._proxy_command(_make_session(name="my session"), None) assert '"my session"' in cmd @@ -260,7 +261,8 @@ def test_install_rm_handlers_ignores_missing_sighup(mocker): """Windows has no SIGHUP. Installing --rm handlers must not raise.""" import signal - mocker.patch("colab_cli.commands.ssh.signal.SIGHUP", None) + # create=True: on Windows the attribute does not exist to be patched. + mocker.patch("colab_cli.commands.ssh.signal.SIGHUP", None, create=True) sigmock = mocker.patch("colab_cli.commands.ssh.signal.signal") ssh_module._install_rm_signal_handlers(lambda: None) registered = {call.args[0] for call in sigmock.call_args_list} @@ -272,6 +274,36 @@ def test_install_rm_handlers_ignores_missing_sighup(mocker): # --- ProxyCommand shell quoting --------------------------------------------- +def _windows_command_line_to_argv(cmd: str) -> list[str]: + """Split a command line the way a Windows child process does (MSVCRT).""" + import ctypes + from ctypes import wintypes + + shell32 = ctypes.windll.shell32 + shell32.CommandLineToArgvW.argtypes = [ + wintypes.LPCWSTR, + ctypes.POINTER(ctypes.c_int), + ] + shell32.CommandLineToArgvW.restype = ctypes.POINTER(wintypes.LPWSTR) + argc = ctypes.c_int() + argv = shell32.CommandLineToArgvW(cmd, ctypes.byref(argc)) + try: + return [argv[i] for i in range(argc.value)] + finally: + ctypes.windll.kernel32.LocalFree(argv) + + +def _split_like_openssh(cmd: str) -> list[str]: + """Undo what OpenSSH does to a ProxyCommand before the child sees argv.""" + # %-token expansion comes first; only '%%' may appear, meaning '%'. + assert "%" not in cmd.replace("%%", ""), f"unescaped % in {cmd!r}" + cmd = cmd.replace("%%", "%") + if sys.platform == "win32": + return _windows_command_line_to_argv(cmd) + return shlex.split(cmd) + + + @pytest.mark.parametrize( "name", [ @@ -282,6 +314,9 @@ def test_install_rm_handlers_ignores_missing_sighup(mocker): "$(touch /tmp/pwned)", "a;rm -rf /", "ünïcode", + "a&b|c", + "100%", + "a%h", ], ids=[ "word", @@ -291,6 +326,9 @@ def test_install_rm_handlers_ignores_missing_sighup(mocker): "cmd-substitution", "semicolon", "non-ascii", + "cmd-metachars", + "percent", + "percent-token", ], ) @pytest.mark.parametrize( @@ -299,12 +337,13 @@ def test_install_rm_handlers_ignores_missing_sighup(mocker): def test_proxy_command_round_trips_through_the_shell(name, identity): """The ProxyCommand string must re-parse into the exact argv. - `ssh` hands the ProxyCommand to /bin/sh, so every argument has to survive - word-splitting verbatim -- a hostile session name must arrive as one - literal argument, never as a new word or a substitution. + `ssh` first expands %-tokens in the ProxyCommand, then hands it to + /bin/sh (POSIX) or CreateProcess (Windows), so every argument has to + survive both steps verbatim -- a hostile session name must arrive as one + literal argument, never as a new word, a substitution or a %-token. """ cmd = ssh_module._proxy_command(_make_session(name=name), identity) - argv = shlex.split(cmd) + argv = _split_like_openssh(cmd) assert argv[:7] == [ sys.executable, diff --git a/tests/test_ssh_autocreate.py b/tests/test_ssh_autocreate.py index a7a12ed1..1946b87a 100644 --- a/tests/test_ssh_autocreate.py +++ b/tests/test_ssh_autocreate.py @@ -316,7 +316,13 @@ def test_proxy_mode_signal_handler_installation( assert result.exit_code == 0 if expect_installed: registered = {c.args[0] for c in sigmock.call_args_list} - assert {_signal.SIGHUP, _signal.SIGTERM, _signal.SIGINT} <= registered + # Windows has no SIGHUP; every signal the platform has must be wired. + expected = { + getattr(_signal, n) + for n in ("SIGHUP", "SIGTERM", "SIGINT") + if hasattr(_signal, n) + } + assert expected <= registered else: sigmock.assert_not_called() diff --git a/tests/test_ssh_lifecycle.py b/tests/test_ssh_lifecycle.py index 3143a3b2..cb88c596 100644 --- a/tests/test_ssh_lifecycle.py +++ b/tests/test_ssh_lifecycle.py @@ -251,8 +251,12 @@ def test_proxy_mode_rm_teardown_idempotent(mock_common_state, mocker): ssh_module, "_connect_websocket", return_value=MagicMock() ) + # OpenSSH HUPs the ProxyCommand on POSIX; Windows has no SIGHUP, so the + # same teardown path is driven by SIGTERM there. + sig = getattr(_signal, "SIGHUP", _signal.SIGTERM) + def bridge_then_hup(ws): - handlers[_signal.SIGHUP](_signal.SIGHUP, None) # OpenSSH HUPs us + handlers[sig](sig, None) return 0 mocker.patch.object( From a0ea62e5705444a97bbb01d16db67fcde2f0c06e Mon Sep 17 00:00:00 2001 From: "arlinamid\\arlinamid" Date: Wed, 7 Oct 2026 21:19:55 +0200 Subject: [PATCH 4/8] fix: piped console leaks terminal replies; honor Windows EDITOR paths Piped `colab console` tmux on the runtime sends terminal queries when it attaches (DA1 ESC[c, DA2 ESC[>c, XTVERSION ESC[>q, OSC 10/11 color queries). The local terminal answers them by typing the reply into its own input. With piped stdin the CLI is not reading that input, so the replies could never reach the remote side and were left behind for the next reader: on Windows they showed up in the next command's prompt (ESC[?61;...c ESC[>0;10;1c). This is not Windows-specific; it follows from piped stdin. When stdin is not a TTY, the console now drops terminal queries from the remote output (TerminalQueryFilter), holding back a sequence cut across websocket messages. Interactive sessions are unchanged, because there the replies do flow back to tmux. Measured in a ConPTY terminal: 41 console input events (the DA1 and DA2 replies) left after a piped console before, none after. `colab edit` with a Windows $EDITOR click.edit splits $VISUAL/$EDITOR with POSIX shlex on every platform (pallets/click#3840), so `python D:\x\editor.py` became `D:xeditor.py`. On Windows, when one of those variables is set, `colab edit` now splits it with CommandLineToArgvW, resolves the program with shutil.which (so .cmd launchers like VS Code's `code` work), and runs it itself. POSIX and click's own default editor still go through click.edit. Tests: query filter (each tmux query, kept sequences, chunk splits, flush), console filters only when piped, Windows command-line splitting (Windows-only), editor launch on Windows and fallback to click. Windows: 416 passed, 2 skipped. Linux: 414 passed, 4 skipped. Live on Windows: an unquoted backslash EDITOR path edits an existing and a new remote file. Co-Authored-By: Claude Opus 5.5 --- src/colab_cli/commands/files.py | 35 +++++++++++++++- src/colab_cli/console.py | 19 ++++++++- src/colab_cli/terminal.py | 71 ++++++++++++++++++++++++++++++++ tests/test_cli.py | 65 +++++++++++++++++++++++++++++ tests/test_console.py | 47 +++++++++++++++++++++ tests/test_terminal.py | 73 +++++++++++++++++++++++++++++++++ 6 files changed, 307 insertions(+), 3 deletions(-) diff --git a/src/colab_cli/commands/files.py b/src/colab_cli/commands/files.py index ac843767..d39dbb5d 100644 --- a/src/colab_cli/commands/files.py +++ b/src/colab_cli/commands/files.py @@ -15,12 +15,15 @@ import click import hashlib import os +import shutil +import subprocess import tempfile import typer from typing import Optional from typing_extensions import Annotated from colab_cli.contents import ContentsClient +from colab_cli.terminal import is_windows, split_windows_command_line def ls( @@ -132,6 +135,36 @@ def download( raise typer.Exit(1) +def _launch_editor(path: str) -> None: + """Open ``path`` in the user's editor and wait for it to exit. + + click.edit splits ``$VISUAL``/``$EDITOR`` with POSIX ``shlex`` on every + platform, which drops the backslashes of an unquoted Windows path such as + ``C:\\tools\\edit.exe`` (pallets/click#3840). On Windows, when one of + those variables is set, split it with the Windows rules and start the + editor here. Everything else, including click's own default editor, + still goes through click.edit. + """ + editor = os.environ.get("VISUAL") or os.environ.get("EDITOR") + if not (is_windows() and editor): + click.edit(filename=path) + return + + argv = split_windows_command_line(editor) + if not argv: + click.edit(filename=path) + return + # CreateProcess only appends .exe; which() also finds .cmd/.bat + # launchers such as VS Code's `code`. + argv[0] = shutil.which(argv[0]) or argv[0] + try: + returncode = subprocess.call(argv + [path]) + except OSError as e: + raise click.ClickException(f"{editor}: Editing failed: {e}") from e + if returncode != 0: + raise click.ClickException(f"{editor}: Editing failed") + + def edit( session: Annotated[ Optional[str], typer.Option("-s", "--session", help="Session name") @@ -171,7 +204,7 @@ def get_file_hash(path): hash_before = get_file_hash(local_path) - click.edit(filename=local_path) + _launch_editor(local_path) hash_after = get_file_hash(local_path) diff --git a/src/colab_cli/console.py b/src/colab_cli/console.py index a73c165b..682b8f91 100644 --- a/src/colab_cli/console.py +++ b/src/colab_cli/console.py @@ -29,12 +29,14 @@ # gracefully to line-buffered input when these are unavailable. termios = None # type: ignore tty = None # type: ignore +from typing import Optional from urllib.parse import urlparse import websocket from colab_cli.state import SessionState from colab_cli.terminal import ( + TerminalQueryFilter, enable_windows_virtual_terminal, is_windows, read_windows_key, @@ -46,6 +48,9 @@ # Global flag to stop the read thread when the websocket closes _is_running = False _last_error = None +# Set when stdin is piped: drops terminal queries from the remote output, +# because the local terminal's answers could never reach the remote side. +_output_filter: Optional[TerminalQueryFilter] = None # When stdin is piped and reaches EOF, we send "exit\n" to the remote shell and # then wait this many seconds for any remaining output (the shell's goodbye, @@ -63,7 +68,10 @@ def on_message(ws, message): if "data" in data: # The backend sends raw ANSI escape sequences and string content. # We write it directly to stdout buffer to avoid python print() formatting. - sys.stdout.buffer.write(data["data"].encode("utf-8")) + text = data["data"] + if _output_filter is not None: + text = _output_filter.feed(text) + sys.stdout.buffer.write(text.encode("utf-8")) sys.stdout.buffer.flush() except Exception as e: logger.debug(f"Error parsing message: {e}") @@ -152,7 +160,7 @@ def connect_console(session: SessionState): """ Connects to the Colab TTY endpoint and sets up a raw terminal session. """ - global _is_running, _last_error + global _is_running, _last_error, _output_filter _last_error = None # cmd.exe and Windows PowerShell 5.1 do not enable ANSI processing by # default. The remote PTY speaks ANSI, and we write those bytes straight @@ -165,6 +173,7 @@ def connect_console(session: SessionState): ws_url = f"{ws_scheme}://{parsed.netloc}/colab/tty?colab-runtime-proxy-token={session.token}" is_tty = sys.stdin.isatty() + _output_filter = None if is_tty else TerminalQueryFilter() fd = None old_settings = None can_raw = termios is not None and tty is not None and is_tty @@ -223,6 +232,12 @@ def _watch_resize(): # This is a blocking call until the connection is closed ws.run_forever() + if _output_filter is not None: + tail = _output_filter.flush() + if tail: + sys.stdout.buffer.write(tail.encode("utf-8")) + sys.stdout.buffer.flush() + if _last_error: # Re-raise or wrap terminal errors err_msg = str(_last_error) diff --git a/src/colab_cli/terminal.py b/src/colab_cli/terminal.py index 30b817cc..30335921 100644 --- a/src/colab_cli/terminal.py +++ b/src/colab_cli/terminal.py @@ -22,6 +22,7 @@ """ import os +import re import shutil import subprocess import sys @@ -242,3 +243,73 @@ def join_argv(argv: list[str], *, windows: Optional[bool] = None) -> str: import shlex return shlex.join(argv) + + +def split_windows_command_line(cmd: str) -> list[str]: + """Split ``cmd`` the way a Windows program splits its own command line. + + ``shlex.split`` treats backslashes as escapes, so an unquoted + ``C:\\tools\\edit.exe`` would lose its path separators. This uses + ``CommandLineToArgvW``, the inverse of ``subprocess.list2cmdline``. + """ + import ctypes + from ctypes import wintypes + + shell32 = ctypes.windll.shell32 + shell32.CommandLineToArgvW.argtypes = [ + wintypes.LPCWSTR, + ctypes.POINTER(ctypes.c_int), + ] + shell32.CommandLineToArgvW.restype = ctypes.POINTER(wintypes.LPWSTR) + argc = ctypes.c_int() + argv = shell32.CommandLineToArgvW(cmd, ctypes.byref(argc)) + if not argv: + raise OSError(ctypes.get_last_error(), f"Cannot parse command line: {cmd!r}") + try: + return [argv[i] for i in range(argc.value)] + finally: + ctypes.windll.kernel32.LocalFree(argv) + + +# Sequences a terminal answers by typing the reply into its own input: +# DA1/DA2/DA3 (CSI c, CSI > c, CSI = c), XTVERSION (CSI > q), DSR/CPR +# (CSI n) and OSC color queries (OSC Ps [; Pn] ; ? ST). tmux on the runtime sends +# several of these when the console attaches. +_TERMINAL_QUERY = re.compile( + r"\x1b\[[>=]?[0-9;]*c" + r"|\x1b\[>[0-9;]*q" + r"|\x1b\[[0-9;]*n" + r"|\x1b\][0-9]+(?:;[0-9]+)*;\?(?:\x07|\x1b\\)" +) +# A query cut off at the end of a websocket message. +_PARTIAL_QUERY = re.compile(r"\x1b(?:\[[>=]?[0-9;]*|\][0-9;]*\??\x1b?)?\Z") +_MAX_PENDING = 32 + + +class TerminalQueryFilter: + """Remove terminal queries from a stream of output chunks. + + Used when ``colab console`` reads piped stdin. The local terminal still + answers the queries, but the answers go to the terminal's input, which + the CLI is not reading, so they cannot reach the remote side. They are + left behind and show up in whatever reads the terminal next (the shell + prompt, the next command's Enter prompt). Dropping the queries avoids + that. A sequence split across chunks is held back until it completes. + """ + + def __init__(self) -> None: + self._pending = "" + + def feed(self, text: str) -> str: + text = self._pending + text + self._pending = "" + partial = _PARTIAL_QUERY.search(text) + if partial and len(text) - partial.start() <= _MAX_PENDING: + self._pending = text[partial.start() :] + text = text[: partial.start()] + return _TERMINAL_QUERY.sub("", text) + + def flush(self) -> str: + """Return held-back text that never completed into a query.""" + pending, self._pending = self._pending, "" + return pending diff --git a/tests/test_cli.py b/tests/test_cli.py index b5f6c25e..a9254d32 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -48,6 +48,14 @@ def mock_history(mock_common_state): return mock_common_state.history +@pytest.fixture(autouse=True) +def _no_user_editor(monkeypatch): + """`colab edit` honors $VISUAL/$EDITOR directly on Windows. Keep the + developer's own editor setting from launching a real editor in tests.""" + monkeypatch.delenv("VISUAL", raising=False) + monkeypatch.delenv("EDITOR", raising=False) + + def test_cli_new_tpu(mock_client, mock_store): mock_res = MagicMock() mock_res.__class__ = PostAssignmentResponse @@ -644,6 +652,63 @@ def fake_editor(filename, **kwargs): assert "Edited and uploaded 'new.txt'" in result.output +def test_launch_editor_windows_keeps_backslashes(mocker, monkeypatch): + """On Windows $EDITOR is split with the Windows rules and started + directly, so a backslash path survives (pallets/click#3840).""" + from colab_cli.commands import files + + monkeypatch.setenv("EDITOR", r"C:\tools\edit.exe --wait") + mocker.patch.object(files, "is_windows", return_value=True) + mocker.patch.object( + files, + "split_windows_command_line", + return_value=[r"C:\tools\edit.exe", "--wait"], + ) + mocker.patch.object(files.shutil, "which", return_value=None) + call = mocker.patch.object(files.subprocess, "call", return_value=0) + click_edit = mocker.patch("click.edit") + + files._launch_editor(r"C:\tmp\colab-edit-x\a.py") + + call.assert_called_once_with( + [r"C:\tools\edit.exe", "--wait", r"C:\tmp\colab-edit-x\a.py"] + ) + click_edit.assert_not_called() + + +def test_launch_editor_windows_nonzero_exit_fails(mocker, monkeypatch): + import click + from colab_cli.commands import files + + monkeypatch.setenv("VISUAL", "ed") + mocker.patch.object(files, "is_windows", return_value=True) + mocker.patch.object(files, "split_windows_command_line", return_value=["ed"]) + mocker.patch.object(files.shutil, "which", return_value=r"C:\bin\ed.cmd") + call = mocker.patch.object(files.subprocess, "call", return_value=3) + + with pytest.raises(click.ClickException): + files._launch_editor("f.txt") + call.assert_called_once_with([r"C:\bin\ed.cmd", "f.txt"]) + + +@pytest.mark.parametrize("windows, editor", [(False, "vim"), (True, None)]) +def test_launch_editor_otherwise_uses_click(mocker, monkeypatch, windows, editor): + """POSIX, and Windows without $VISUAL/$EDITOR (click's own default), + keep going through click.edit.""" + from colab_cli.commands import files + + if editor: + monkeypatch.setenv("EDITOR", editor) + mocker.patch.object(files, "is_windows", return_value=windows) + call = mocker.patch.object(files.subprocess, "call") + click_edit = mocker.patch("click.edit") + + files._launch_editor("f.txt") + + click_edit.assert_called_once_with(filename="f.txt") + call.assert_not_called() + + def _make_400_error(message="Bad Request"): """Build a ColabRequestError shaped like a 400 from the assign endpoint.""" response = MagicMock() diff --git a/tests/test_console.py b/tests/test_console.py index d1a52a0e..da9c375a 100644 --- a/tests/test_console.py +++ b/tests/test_console.py @@ -277,6 +277,53 @@ def start(self): mock_ws.close.assert_not_called() +@pytest.mark.parametrize( + "stdin_is_tty, expected", + [ + # Piped: the terminal's answers can never reach the remote side, so + # the queries are dropped (and a cut-off tail is flushed at the end). + (False, ["x", "y", "\x1b["]), + # Interactive: answers flow back through stdin, so pass queries on. + (True, ["x\x1b[>c", "y\x1b["]), + ], + ids=["piped", "tty"], +) +@patch("colab_cli.console.websocket.WebSocketApp") +@patch("colab_cli.console.sys.stdin.isatty") +def test_console_drops_terminal_queries_only_when_piped( + mock_isatty, mock_ws_app, mock_session, stdin_is_tty, expected +): + import colab_cli.console as console_mod + + mock_isatty.return_value = stdin_is_tty + ws = MagicMock() + mock_ws_app.return_value = ws + + def remote_output(): + console_mod.on_message(ws, json.dumps({"data": "x\x1b[>c"})) + console_mod.on_message(ws, json.dumps({"data": "y\x1b["})) + + ws.run_forever.side_effect = remote_output + written = [] + + with ( + patch.object(console_mod, "termios", None), + patch.object(console_mod, "tty", None), + patch.object(console_mod, "is_windows", return_value=False), + patch("colab_cli.console.threading.Thread"), + patch( + "colab_cli.console.sys.stdout.buffer.write", + side_effect=lambda b: written.append(b.decode("utf-8")), + ), + patch("colab_cli.console.sys.stdout.buffer.flush"), + ): + connect_console(mock_session) + + # connect_console prints its own "Connection closed." afterwards. + remote = [w for w in written if w][: len(expected)] + assert remote == expected + + @patch("colab_cli.console.websocket.WebSocketApp") @patch("colab_cli.console.sys.stdin.isatty") def test_console_no_termios_degrades_gracefully(mock_isatty, mock_ws_app, mock_session): diff --git a/tests/test_terminal.py b/tests/test_terminal.py index f5aafe8b..72534b2e 100644 --- a/tests/test_terminal.py +++ b/tests/test_terminal.py @@ -19,19 +19,92 @@ """ import subprocess +import sys import pytest from colab_cli.terminal import ( + TerminalQueryFilter, enable_windows_virtual_terminal, join_argv, open_url_in_browser, read_controlling_line, + split_windows_command_line, translate_windows_key, windows_raw_console, ) +# --- terminal query filter (piped `colab console`) --------------------------- + +# The queries tmux on the runtime sent when a piped console attached. +TMUX_QUERIES = ["\x1b[c", "\x1b[>c", "\x1b[>q", "\x1b]10;?\x1b\\", "\x1b]11;?\x1b\\"] + + +@pytest.mark.parametrize( + "query", TMUX_QUERIES + ["\x1b[0c", "\x1b[=c", "\x1b[6n", "\x1b]4;1;?\x07"] +) +def test_query_filter_drops_terminal_queries(query): + f = TerminalQueryFilter() + assert f.feed(f"before{query}after") == "beforeafter" + assert f.flush() == "" + + +@pytest.mark.parametrize( + "keep", + [ + "\x1b[0m", + "\x1b[1;31m", + "\x1b[?1049h", + "\x1b[2J\x1b[H", + "\x1b]0;window title\x07", + "\x1b[?61;6;7c", # a DA1 *reply* is not a query + ], +) +def test_query_filter_keeps_other_sequences(keep): + f = TerminalQueryFilter() + assert f.feed(f"a{keep}b") + f.flush() == f"a{keep}b" + + +def test_query_filter_handles_queries_split_across_chunks(): + f = TerminalQueryFilter() + stream = "hello" + "".join(TMUX_QUERIES) + "\x1b[0mworld" + out = "".join(f.feed(stream[i : i + 3]) for i in range(0, len(stream), 3)) + out += f.flush() + assert out == "hello\x1b[0mworld" + + +def test_query_filter_flushes_incomplete_tail(): + f = TerminalQueryFilter() + assert f.feed("done\x1b[") == "done" + assert f.flush() == "\x1b[" + + +# --- Windows command-line splitting (EDITOR) --------------------------------- + + +@pytest.mark.skipif(sys.platform != "win32", reason="uses CommandLineToArgvW") +@pytest.mark.parametrize( + "cmd, argv", + [ + ("python D:\\x\\editor.py", ["python", "D:\\x\\editor.py"]), + ( + '"C:\\Program Files\\My Editor\\edit.exe" --wait', + ["C:\\Program Files\\My Editor\\edit.exe", "--wait"], + ), + ("notepad", ["notepad"]), + ], +) +def test_split_windows_command_line_keeps_backslashes(cmd, argv): + assert split_windows_command_line(cmd) == argv + + +@pytest.mark.skipif(sys.platform != "win32", reason="uses CommandLineToArgvW") +def test_split_windows_command_line_inverts_list2cmdline(): + argv = ["C:\\a b\\x.exe", "say \"hi\"", "a&b", "trailing\\"] + assert split_windows_command_line(subprocess.list2cmdline(argv)) == argv + + @pytest.mark.parametrize( ("first", "second", "expected"), [ From 98ad068b9dac0c2f6058a420a0e9add5fed77a93 Mon Sep 17 00:00:00 2001 From: "arlinamid\\arlinamid" Date: Wed, 7 Oct 2026 21:46:14 +0200 Subject: [PATCH 5/8] fix: piped console cut off its own output on a fresh runtime After piped stdin hit EOF, the console sent "exit\n" and closed the websocket itself a fixed 0.5s later (PIPED_EOF_GRACE_SECONDS). On a freshly started runtime the first attach often needs 0.5-1s before the shell answers, so the client closed first and nothing came back. Traced with timestamps on fresh CPU runtimes (one attach each): - 0.5s grace: 1 of 3 got its output; twice the client closed before any output arrived. - 5s wait: 3 of 3; output arrived 0.1-0.8s after "exit", and the backend closed the websocket itself every time (tmux "[exited]", then on_close). The backend closes the socket once bash and tmux exit, after the last output, so the handler now waits for that close (_closed, set by on_close). It only closes from the client side after PIPED_EOF_CLOSE_TIMEOUT_SECONDS (30s), as a fallback for a backend that never closes; as with `echo cmd | ssh host`, a piped command running longer than that is cut off. With the fix, 3 of 3 fresh-runtime runs got their output (one arrived 1.08s after "exit"), and the backend closed the socket each time. Also corrects the docs entry that said OpenSSH for Windows runs the ProxyCommand through cmd.exe (it uses CreateProcess), and documents the piped-mode terminal query filter from a0ea62e. Tests: new test that the client waits for the server-side close; the existing EOF test now covers the fallback close. Windows: 417 passed, 2 skipped. Linux: 415 passed, 4 skipped. Co-Authored-By: Claude Opus 5.5 --- docs/02_execution_and_interactive.md | 6 ++- src/colab_cli/console.py | 37 +++++++++------- tests/test_console.py | 66 ++++++++++++++++++++++++++-- 3 files changed, 87 insertions(+), 22 deletions(-) diff --git a/docs/02_execution_and_interactive.md b/docs/02_execution_and_interactive.md index 29c1f963..d414d086 100644 --- a/docs/02_execution_and_interactive.md +++ b/docs/02_execution_and_interactive.md @@ -1,6 +1,8 @@ --- log: -2026-10-07: Windows console support for `colab console`. cmd.exe and PowerShell have no `termios`, `/dev/tty`, or `SIGWINCH`, so interactive console used to stay line-buffered (arrow keys never left the local line editor, Ctrl-C killed the CLI, ANSI from the remote PTY rendered as garbage in conhost). `console.py` now enables virtual-terminal processing and UTF-8, switches the input handle to raw mode via `SetConsoleMode`, reads keys with `msvcrt.getwch`, translates scan codes to ANSI, and polls the window size. POSIX raw mode and piped stdin are unchanged. `colab ssh --proxy-mode` reads stdin with a blocking `os.read` (Windows `select()` cannot wait on a pipe) and quotes the ProxyCommand for `cmd.exe`. +2026-10-07: Piped `colab console` no longer cuts off its own output on a fresh runtime, and no longer leaks terminal replies. The EOF handler used to close the websocket a fixed 0.5s (`PIPED_EOF_GRACE_SECONDS`) after sending `exit\n`. On a freshly started runtime the first attach often needs 0.5-1s before the shell answers, so the client closed first and nothing came back (2 of 3 fresh-VM runs, traced with timestamps). The backend closes the websocket itself once bash and tmux exit, after the last output, so the handler now waits for that close (`_closed`, set by `on_close`). It only closes from the client side after `PIPED_EOF_CLOSE_TIMEOUT_SECONDS` (30s), as a fallback for a backend that never closes. With a 5s wait, 3 of 3 fresh-VM runs got their output and the backend closed every time, 0.1-1s after `exit`. Separately, tmux sends terminal queries when it attaches (DA1, DA2, XTVERSION, OSC 10/11). With piped stdin the local terminal's replies can never reach the remote side and were left in the terminal's input for the next command. When stdin is not a TTY, `TerminalQueryFilter` now drops those queries from the output. + +2026-10-07: Windows console support for `colab console`. cmd.exe and PowerShell have no `termios`, `/dev/tty`, or `SIGWINCH`, so interactive console used to stay line-buffered (arrow keys never left the local line editor, Ctrl-C killed the CLI, ANSI from the remote PTY rendered as garbage in conhost). `console.py` now enables virtual-terminal processing and UTF-8, switches the input handle to raw mode via `SetConsoleMode`, reads keys with `msvcrt.getwch`, translates scan codes to ANSI, and polls the window size. POSIX raw mode and piped stdin are unchanged. `colab ssh --proxy-mode` reads stdin with a blocking `os.read` (Windows `select()` cannot wait on a pipe) and quotes the ProxyCommand with the MSVCRT rules, because OpenSSH for Windows passes it to `CreateProcess` (not `cmd.exe`, as this entry first said). 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. @@ -36,7 +38,7 @@ Execution involves sending Python code (or shell commands) to the Jupyter kernel - **Implementation**: Connects directly to the backend terminal endpoint (`/colab/tty`) via WebSockets using `websocket-client`. - **Interactive**: Bypasses the Jupyter kernel entirely to provide a raw, PTY-backed bash session on the Colab VM. - **Terminal Management**: On Linux and macOS, configures `sys.stdin` to raw mode using `termios` and `tty`, passing single characters to the socket and writing raw ANSI escape sequences directly to `sys.stdout.buffer`. Hooks into `SIGWINCH` to communicate local terminal dimensions (`cols`/`rows`) to the remote bash environment so output rendering works perfectly during resizing. On Windows (cmd.exe and PowerShell), `termios` does not exist: the CLI enables `ENABLE_VIRTUAL_TERMINAL_PROCESSING` and UTF-8 on the console, sets raw input mode with `SetConsoleMode` (so the local line editor and Ctrl-C handler get out of the way), reads keys with `msvcrt.getwch`, maps scan codes to ANSI sequences, and polls `os.get_terminal_size` because there is no `SIGWINCH`. -- **Piped stdin**: Detected via `sys.stdin.isatty()`. When piped, the input characters are forwarded one at a time to the remote pty, and on EOF the client sends `exit\n` and then closes the websocket itself after `PIPED_EOF_GRACE_SECONDS` (0.5s) so the user's shell goodbye text drains back. The remote `/colab/tty` endpoint wraps bash in tmux, which intercepts a bare `\x04` as a literal character — that is why we send `exit\n` rather than Ctrl-D. +- **Piped stdin**: Detected via `sys.stdin.isatty()`. When piped, the input characters are forwarded one at a time to the remote pty, and on EOF the client sends `exit\n` and waits for the backend to close the websocket. The backend does that once bash and tmux exit, after the last output, so the user's shell goodbye text drains back. The client only closes the websocket itself if that has not happened after `PIPED_EOF_CLOSE_TIMEOUT_SECONDS` (30s), so a piped command running longer than that is cut off. Terminal queries from tmux (DA1/DA2, XTVERSION, OSC colour queries) are dropped from the output in this mode, because the terminal's replies could not reach the remote side. The remote `/colab/tty` endpoint wraps bash in tmux, which intercepts a bare `\x04` as a literal character — that is why we send `exit\n` rather than Ctrl-D. ## Implementation Details - **Kernel Management**: `ColabRuntime` (from `colab-agent`) already handles message signing and message types. diff --git a/src/colab_cli/console.py b/src/colab_cli/console.py index 682b8f91..79f4c38b 100644 --- a/src/colab_cli/console.py +++ b/src/colab_cli/console.py @@ -19,7 +19,6 @@ import signal import sys import threading -import time try: import termios @@ -52,13 +51,17 @@ # because the local terminal's answers could never reach the remote side. _output_filter: Optional[TerminalQueryFilter] = None -# When stdin is piped and reaches EOF, we send "exit\n" to the remote shell and -# then wait this many seconds for any remaining output (the shell's goodbye, -# tmux teardown messages, etc.) to flush before closing the websocket from the -# client side. Empirically 0.5s is enough for the typical /colab/tty backend -# wrapped in tmux + bash; bumping it just delays exit, lowering it risks -# truncating tail output. -PIPED_EOF_GRACE_SECONDS = 0.5 +# When stdin is piped and reaches EOF, we send "exit\n" to the remote shell. +# Once bash exits, tmux exits and the backend closes the websocket itself, so +# we wait for that close rather than for a fixed time. A fixed 0.5s grace cut +# off the output on a freshly started runtime: the first attach often needs +# 0.5-1s before the shell answers, and the client closed the socket before +# anything came back (2 of 3 fresh-VM runs). This is only the fallback for a +# backend that never closes; as with `echo cmd | ssh host`, a piped command +# that runs longer than this is cut off. +PIPED_EOF_CLOSE_TIMEOUT_SECONDS = 30.0 +# Set by on_close, so the stdin thread can wait for the server-side close. +_closed = threading.Event() def on_message(ws, message): @@ -88,6 +91,7 @@ def on_close(ws, close_status_code, close_msg): """Callback for when the websocket is closed.""" global _is_running _is_running = False + _closed.set() def send_terminal_size(ws): @@ -133,18 +137,18 @@ def read_stdin(): # endpoint wraps bash in tmux which intercepts \x04 # (Ctrl-D) as a literal character, so it never exits. # Instead send "exit\n" so bash voluntarily terminates, - # wait a short grace period for the shell's goodbye - # output to drain back to us, then close the websocket - # ourselves to guarantee the client unblocks. + # wait for the backend to close the websocket once the + # shell is gone (all output has arrived by then), and + # only close it ourselves if that never happens. try: ws.send(json.dumps({"data": "exit\n"})) except Exception: pass - time.sleep(PIPED_EOF_GRACE_SECONDS) - try: - ws.close() - except Exception: - pass + if not _closed.wait(PIPED_EOF_CLOSE_TIMEOUT_SECONDS): + try: + ws.close() + except Exception: + pass break chunks = [char] for chunk in chunks: @@ -162,6 +166,7 @@ def connect_console(session: SessionState): """ global _is_running, _last_error, _output_filter _last_error = None + _closed.clear() # cmd.exe and Windows PowerShell 5.1 do not enable ANSI processing by # default. The remote PTY speaks ANSI, and we write those bytes straight # to stdout.buffer, so the console mode has to be switched first. diff --git a/tests/test_console.py b/tests/test_console.py index da9c375a..021c1463 100644 --- a/tests/test_console.py +++ b/tests/test_console.py @@ -15,6 +15,8 @@ import json import os import sys +import threading +import time from unittest.mock import MagicMock, patch try: @@ -151,14 +153,17 @@ def test_read_stdin_eof_piped_sends_exit_and_closes_ws( mock_stdin, mock_isatty, mock_get_term_size ): """When stdin is piped and reaches EOF, the read thread should send 'exit\\n' - to the remote shell and then close the websocket from the client side. + to the remote shell and, if the backend never closes the websocket, close + it from the client side after the timeout. The remote shell at /colab/tty is wrapped in tmux which swallows the bare \\x04 (Ctrl-D) we used to send, so EOF used to leave the websocket open - indefinitely. Sending 'exit\\n' + ws.close() guarantees clean termination. + indefinitely. Sending 'exit\\n' + the fallback ws.close() guarantees clean + termination. """ import colab_cli.console as console_mod + console_mod._closed.clear() mock_isatty.return_value = False # Simulate piped stdin: returns one line then EOF mock_stdin.read.side_effect = ["e", "c", "h", "o", " ", "h", "i", "\n", ""] @@ -180,8 +185,8 @@ def start(self): console_mod._is_running = True with patch("colab_cli.console.threading.Thread", SyncThread): - # Use a tiny grace period for the test - with patch("colab_cli.console.PIPED_EOF_GRACE_SECONDS", 0.01): + # The mock backend never closes, so use a tiny fallback timeout. + with patch("colab_cli.console.PIPED_EOF_CLOSE_TIMEOUT_SECONDS", 0.01): on_open(mock_ws) # Collect what was sent to the websocket @@ -197,6 +202,59 @@ def start(self): mock_ws.close.assert_called_once() +@patch("colab_cli.console.os.get_terminal_size") +@patch("colab_cli.console.sys.stdin.isatty") +@patch("colab_cli.console.sys.stdin") +def test_read_stdin_eof_piped_waits_for_server_close( + mock_stdin, mock_isatty, mock_get_term_size +): + """After 'exit\\n' the client waits for the backend to close the socket + (which it does once tmux exits, after the last output) instead of closing + it after a fixed delay. On a freshly started runtime the shell can take + more than the old 0.5s to answer, and the early close dropped its output. + """ + import colab_cli.console as console_mod + + console_mod._closed.clear() + mock_isatty.return_value = False + mock_stdin.read.side_effect = ["l", "s", "\n", ""] + mock_get_term_size.return_value = os.terminal_size((80, 24)) + mock_ws = MagicMock() + # Created before threading.Thread is patched below: Timer.__init__ looks + # Thread up by name and would get the synchronous stand-in. + server_close = threading.Timer( + 0.05, console_mod.on_close, args=(mock_ws, 1000, "") + ) + + def backend(payload): + # The backend answers 'exit' by closing the socket a moment later. + if json.loads(payload).get("data") == "exit\n": + server_close.start() + + mock_ws.send.side_effect = backend + + class SyncThread: + def __init__(self, target, daemon=None): + self.target = target + + def start(self): + self.target() + + console_mod._is_running = True + # A fixed 0.01s grace would have closed before the backend did; the wait + # must outlast that and end on the server-side close, well before 5s. + with patch("colab_cli.console.threading.Thread", SyncThread), patch( + "colab_cli.console.PIPED_EOF_CLOSE_TIMEOUT_SECONDS", 5.0 + ): + started = time.monotonic() + on_open(mock_ws) + elapsed = time.monotonic() - started + + assert console_mod._closed.is_set() + mock_ws.close.assert_not_called() + assert elapsed < 4.0 + + @patch("colab_cli.console.os.get_terminal_size") @patch("colab_cli.console.sys.stdin.isatty") @patch("colab_cli.console.sys.stdin") From 5beff34c76fe6d14140bcd72fd74277eab6f1656 Mon Sep 17 00:00:00 2001 From: "arlinamid\\arlinamid" Date: Wed, 7 Oct 2026 23:41:22 +0200 Subject: [PATCH 6/8] fix: explain a dropped kernel connection; don't resurrect stopped sessions `colab stop` from another terminal, while `colab exec` (or repl, run, drivemount) was running against the same session, ended the running command with a jupyter_kernel_client traceback: RuntimeError: Connection was lost. ColabRuntime now turns that error into SessionConnectionLost, and the `colab` entry point prints one line with exit code 1: "Session 'X' was stopped, so the running command ended." when the session is gone locally, otherwise "Lost the connection to session 'X' ... check it with `colab status -s X`". The same commands also saved the session back to sessions.json in their `finally` blocks, after `colab stop` had removed it, leaving a stopped session behind locally. They now use StateStore.update_if_present, which writes under the same lock only if the session is still recorded. Six ColabRuntime constructions did not pass session_name, so the first live run printed "Session 'None'"; they now pass it (it is otherwise only used for history logging, which those call sites do not enable). Live (WSL, CPU runtime): a 2-minute `colab exec`, stopped after 15s from another process, printed "[colab] Session 'losttest' was stopped, so the running command ended." with exit code 1, and sessions.json stayed empty. Tests: Windows 423 passed, 2 skipped; Linux 421 passed, 4 skipped. Co-Authored-By: Claude Opus 5.5 --- src/colab_cli/cli.py | 24 ++++++++++++++++- src/colab_cli/commands/automation.py | 2 +- src/colab_cli/commands/execution.py | 10 ++++--- src/colab_cli/commands/run.py | 7 +++-- src/colab_cli/commands/session.py | 5 +++- src/colab_cli/runtime.py | 31 ++++++++++++++++++--- src/colab_cli/state.py | 16 +++++++++++ tests/test_cli.py | 31 +++++++++++++++++++++ tests/test_runtime.py | 40 ++++++++++++++++++++++++++++ tests/test_state.py | 29 ++++++++++++++++++++ 10 files changed, 183 insertions(+), 12 deletions(-) diff --git a/src/colab_cli/cli.py b/src/colab_cli/cli.py index 77b4c8f7..3afc9cd3 100644 --- a/src/colab_cli/cli.py +++ b/src/colab_cli/cli.py @@ -164,8 +164,30 @@ def help_command( usage.register(app) +def _connection_lost_message(name: Optional[str]) -> str: + """Explain a dropped kernel connection in one line, not a traceback.""" + from colab_cli.common import state + + try: + still_recorded = name is not None and state.store.get(name) is not None + except Exception: + still_recorded = True + if not still_recorded: + return f"[colab] Session '{name}' was stopped, so the running command ended." + return ( + f"[colab] Lost the connection to session '{name}'. The runtime may have " + f"been stopped or disconnected; check it with `colab status -s {name}`." + ) + + def main(): - app() + from colab_cli.runtime import SessionConnectionLost + + try: + app() + except SessionConnectionLost as e: + typer.echo(_connection_lost_message(e.session_name), err=True) + raise SystemExit(1) if __name__ == "__main__": diff --git a/src/colab_cli/commands/automation.py b/src/colab_cli/commands/automation.py index ff0797b6..a959c908 100644 --- a/src/colab_cli/commands/automation.py +++ b/src/colab_cli/commands/automation.py @@ -167,7 +167,7 @@ def run_automation( sys.stderr.write(f"{ename}: {evalue}\n") finally: s.running = None - state.store.add(s) + state.store.update_if_present(s) runtime.stop() diff --git a/src/colab_cli/commands/execution.py b/src/colab_cli/commands/execution.py index 336a5ffb..ab9589f2 100644 --- a/src/colab_cli/commands/execution.py +++ b/src/colab_cli/commands/execution.py @@ -207,6 +207,7 @@ def on_sess_started(sid): runtime = ColabRuntime( s.url, s.token, + session_name=s.name, kernel_id=s.kernel_id, session_id=s.session_id, on_kernel_started=on_started, @@ -274,7 +275,7 @@ def on_sess_started(sid): ) finally: s.running = None - state.store.add(s) + state.store.update_if_present(s) runtime.stop() if file and file.endswith(".ipynb"): output_file = os.path.splitext(file)[0] + "_output.ipynb" @@ -308,6 +309,7 @@ def on_sess_started(sid): runtime = ColabRuntime( s.url, s.token, + session_name=s.name, kernel_id=s.kernel_id, session_id=s.session_id, on_kernel_started=on_started, @@ -348,7 +350,7 @@ def on_sess_started(sid): ) finally: s.running = None - state.store.add(s) + state.store.update_if_present(s) runtime.stop() else: from colab_cli.repl import ColabREPL @@ -366,7 +368,7 @@ def on_sess_started(sid): repl_inst.run() finally: s.running = None - state.store.add(s) + state.store.update_if_present(s) def console( @@ -394,7 +396,7 @@ def console( raise e finally: s.running = None - state.store.add(s) + state.store.update_if_present(s) def register(app: typer.Typer): diff --git a/src/colab_cli/commands/run.py b/src/colab_cli/commands/run.py index 0b222170..5fe8aa46 100644 --- a/src/colab_cli/commands/run.py +++ b/src/colab_cli/commands/run.py @@ -391,6 +391,7 @@ def on_sess_started(sid): runtime = ColabRuntime( s.url, s.token, + session_name=s.name, kernel_id=s.kernel_id, session_id=s.session_id, on_kernel_started=on_started, @@ -444,7 +445,7 @@ def on_sess_started(sid): ) finally: s.running = None - state.store.add(s) + state.store.update_if_present(s) # Best-effort runtime close (keeps remote kernel alive for --keep). try: runtime.stop() @@ -473,7 +474,9 @@ def _teardown(name: str, s: SessionState, *, reason: str) -> None: # The script may have outlived the proxy token. fresh = state.get_session(name, ignore_missing_session=True) if fresh: - rt = ColabRuntime(fresh.url, fresh.token, kernel_id=fresh.kernel_id) + rt = ColabRuntime( + fresh.url, fresh.token, kernel_id=fresh.kernel_id, session_name=fresh.name + ) rt.stop(shutdown_kernel=True) except Exception: pass diff --git a/src/colab_cli/commands/session.py b/src/colab_cli/commands/session.py index 6c822042..b8f47df0 100644 --- a/src/colab_cli/commands/session.py +++ b/src/colab_cli/commands/session.py @@ -239,6 +239,7 @@ def on_sess_started(sid): runtime = ColabRuntime( s.url, s.token, + session_name=s.name, kernel_id=s.kernel_id, session_id=s.session_id, on_kernel_started=on_started, @@ -337,7 +338,9 @@ def stop( typer.echo(f"[colab] Stopping session '{name}'...") try: - runtime = ColabRuntime(s.url, s.token, kernel_id=s.kernel_id) + runtime = ColabRuntime( + s.url, s.token, kernel_id=s.kernel_id, session_name=s.name + ) runtime.stop(shutdown_kernel=True) except Exception: pass diff --git a/src/colab_cli/runtime.py b/src/colab_cli/runtime.py index 57e09fde..f6ce70b2 100644 --- a/src/colab_cli/runtime.py +++ b/src/colab_cli/runtime.py @@ -19,6 +19,19 @@ import jupyter_kernel_client import requests +# jupyter_kernel_client raises a bare RuntimeError with this text when the +# kernel websocket drops mid-execution (for example `colab stop` from another +# terminal, or the VM being reclaimed). +_CONNECTION_LOST = "Connection was lost" + + +class SessionConnectionLost(RuntimeError): + """The connection to the session's kernel dropped during an execution.""" + + def __init__(self, session_name: Optional[str]): + self.session_name = session_name + super().__init__(f"Lost the connection to session '{session_name}'.") + class ColabRuntime: def __init__( @@ -177,6 +190,15 @@ def restart( ): self.kernel_client.restart(timeout=timeout) + def _run(self, call, *args, **kwargs): + """Run a kernel-client call, naming a dropped connection explicitly.""" + try: + return call(*args, **kwargs) + except RuntimeError as e: + if _CONNECTION_LOST in str(e): + raise SessionConnectionLost(self.session_name) from e + raise + def execute_code( self, code: str, @@ -234,13 +256,16 @@ def wrapped_output_hook(msg): if idx < len(outputs): output_hook(outputs[idx]) - reply = self.kernel_client.execute_interactive( - code, output_hook=wrapped_output_hook, **kwargs + reply = self._run( + self.kernel_client.execute_interactive, + code, + output_hook=wrapped_output_hook, + **kwargs, ) # execute_interactive returns the raw reply message reply_content = reply["content"] if reply else {"status": "error"} else: - reply = self.kernel_client.execute(code, **kwargs) + reply = self._run(self.kernel_client.execute, code, **kwargs) if not reply: return [] outputs = reply.get("outputs", []) diff --git a/src/colab_cli/state.py b/src/colab_cli/state.py index 7cb6ffb0..f2d60e65 100644 --- a/src/colab_cli/state.py +++ b/src/colab_cli/state.py @@ -138,6 +138,22 @@ def add(self, state: SessionState): sessions[state.name] = state self._save_raw(f, sessions) + def update_if_present(self, state: SessionState) -> bool: + """Write ``state`` back only if its session is still recorded. + + Long-running commands save the session again when they finish (to + clear ``running``). If ``colab stop`` removed the session meanwhile, a + plain ``add`` would resurrect a stopped session in sessions.json. + Returns True when the session was updated. + """ + with self._lock_exclusive() as f: + sessions = self._load_raw(f) + if state.name not in sessions: + return False + sessions[state.name] = state + self._save_raw(f, sessions) + return True + def get(self, name: str) -> Optional[SessionState]: with self._lock_shared() as f: if f is None: diff --git a/tests/test_cli.py b/tests/test_cli.py index a9254d32..da29c045 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -798,3 +798,34 @@ def test_cli_new_412_without_accelerator_shows_friendly_error(mock_client, mock_ assert result.exit_code != 0 assert "precondition" in result.output.lower() mock_store.add.assert_not_called() + + +@pytest.mark.parametrize( + "still_recorded, expected", + [ + (False, "Session 'qwen21' was stopped, so the running command ended."), + (True, "check it with `colab status -s qwen21`"), + ], + ids=["stopped", "disconnected"], +) +def test_main_explains_a_lost_connection( + mocker, capsys, mock_common_state, still_recorded, expected +): + """`colab stop` from another terminal used to end a running `colab exec` + with a jupyter_kernel_client traceback. main() turns it into one line + and exit code 1.""" + from colab_cli import cli + from colab_cli.runtime import SessionConnectionLost + + mocker.patch.object(cli, "app", side_effect=SessionConnectionLost("qwen21")) + mock_common_state.store.get.return_value = ( + MagicMock() if still_recorded else None + ) + + with pytest.raises(SystemExit) as exc: + cli.main() + + assert exc.value.code == 1 + err = capsys.readouterr().err + assert expected in err + assert "Traceback" not in err diff --git a/tests/test_runtime.py b/tests/test_runtime.py index 8d439d0a..a7f34cfe 100644 --- a/tests/test_runtime.py +++ b/tests/test_runtime.py @@ -215,3 +215,43 @@ def test_colab_runtime_stdin_logging(): mock_history.log_event.assert_any_call( "test-s", "input_reply", {"value": "user input"} ) + + +def _runtime_with_kernel(kernel): + runtime = ColabRuntime("http://url", "token123", session_name="s1") + runtime._kernel_client = kernel + return runtime + + +def test_execute_code_names_a_dropped_connection(): + """jupyter_kernel_client raises a bare RuntimeError when the kernel + websocket drops (e.g. `colab stop` mid-run); surface it as + SessionConnectionLost so the CLI can explain it instead of a traceback.""" + import pytest + + from colab_cli.runtime import SessionConnectionLost + + kernel = MagicMock() + kernel.execute_interactive.side_effect = RuntimeError("Connection was lost.") + kernel.execute.side_effect = RuntimeError("Connection was lost.") + runtime = _runtime_with_kernel(kernel) + + with pytest.raises(SessionConnectionLost) as exc: + runtime.execute_code("1", output_hook=lambda o: None) + assert exc.value.session_name == "s1" + with pytest.raises(SessionConnectionLost): + runtime.execute_code("1") + + +def test_execute_code_keeps_other_runtime_errors(): + import pytest + + from colab_cli.runtime import SessionConnectionLost + + kernel = MagicMock() + kernel.execute.side_effect = RuntimeError("something else") + runtime = _runtime_with_kernel(kernel) + + with pytest.raises(RuntimeError, match="something else") as exc: + runtime.execute_code("1") + assert not isinstance(exc.value, SessionConnectionLost) diff --git a/tests/test_state.py b/tests/test_state.py index 6408426a..d7c0ec22 100644 --- a/tests/test_state.py +++ b/tests/test_state.py @@ -344,3 +344,32 @@ def test_state_store_multiprocess_concurrency(temp_config): assert p1.exitcode == 0 assert p2.exitcode == 0 assert len(StateStore(temp_config).list()) == 80 + + +def _session(name="s1", running=None): + return SessionState( + name=name, + token="t", + url="http://localhost", + endpoint="e", + running=running, + ) + + +def test_update_if_present_does_not_resurrect_a_stopped_session(temp_config): + """A command that finishes after `colab stop` removed its session must not + write the session back into sessions.json.""" + store = StateStore(temp_config) + store.add(_session(running="exec(x.py)")) + store.remove("s1") # `colab stop` from another terminal + + assert store.update_if_present(_session()) is False + assert store.get("s1") is None + + +def test_update_if_present_updates_a_live_session(temp_config): + store = StateStore(temp_config) + store.add(_session(running="exec(x.py)")) + + assert store.update_if_present(_session(running=None)) is True + assert store.get("s1").running is None From 29f8bfb6783c8dc2d01a13ff6edb4ab1d2335545 Mon Sep 17 00:00:00 2001 From: "arlinamid\\arlinamid" Date: Thu, 8 Oct 2026 00:02:20 +0200 Subject: [PATCH 7/8] feat(exec): --cells, --stop-on-error, --check/--check-only; non-zero exit on errors `colab exec -f nb.ipynb` always ran every code cell top to bottom, kept going after a cell raised, and exited 0 either way, so a script could not tell that a notebook had failed. A missing file or an unreadable notebook ended in a traceback. - --cells SPEC runs only the selected code cells, in the given order. SPEC is a comma-separated list of code-cell numbers (from 1, markdown cells not counted), ranges (2-5), #@title values or cell ids; an unknown or ambiguous entry is an error (exit 2) before anything runs. - --stop-on-error stops at the first cell with an error output. The partial outputs are still saved to _output.ipynb. - exec exits 1 when the code, or any notebook cell, produced an error output, and lists the failed cells. - --check runs a local pre-flight before anything is sent: notebook validation, --cells resolution and a syntax check of each selected cell (IPython !cmd, %magic, `x = !cmd` and top-level await accepted, %% cell magics skipped, line numbers kept). If it fails, nothing runs (exit 2). --check-only does the same and prints the plan without a session. Works for .py files too. - A missing file or unreadable notebook prints one line. Cell selection and the pre-flight live in colab_cli/notebook.py. Behavior change: exec now exits 1 when the executed code raises; the existing test that expected 0 was updated. Live (WSL, CPU runtime): --check on a notebook with a syntax error reported "cell 2 (Broken), line 2: expected ':'" and ran nothing (exit 2); a 3-cell notebook whose cell 2 raises ran all cells and exited 1; with --stop-on-error it stopped after cell 2; --cells "Three,1" ran cell 3, then cell 1; a missing file printed "File not found" (exit 1). Tests: 33 new. Windows: 463 passed, 2 skipped. Linux: 461 passed, 4 skipped (two cross-process timing tests in test_state.py failed in one run and passed on rerun; this change does not touch state.py). Co-Authored-By: Claude Opus 5.5 --- README.md | 16 ++- docs/02_execution_and_interactive.md | 2 + src/colab_cli/commands/execution.py | 208 +++++++++++++++++++++------ src/colab_cli/notebook.py | 176 +++++++++++++++++++++++ tests/test_exec.py | 3 +- tests/test_exec_notebook_options.py | 193 +++++++++++++++++++++++++ tests/test_notebook.py | 137 ++++++++++++++++++ 7 files changed, 691 insertions(+), 44 deletions(-) create mode 100644 src/colab_cli/notebook.py create mode 100644 tests/test_exec_notebook_options.py create mode 100644 tests/test_notebook.py diff --git a/README.md b/README.md index c9ffe973..2c3da6b2 100644 --- a/README.md +++ b/README.md @@ -79,7 +79,7 @@ Run `colab --help` to view specific options, defaults, and detailed he | Command | Description | | --- | --- | | `colab run [--gpu GPU] [--tpu TPU] [--high-mem] [--keep] SCRIPT [ARGS...]` | Run a local script on a fresh VM, forwarding arguments, then release it | -| `colab exec [-s NAME] [-f FILE] [--output-image PATH]` | Execute Python code from stdin, a local `.py` file, or a `.ipynb` notebook | +| `colab exec [-s NAME] [-f FILE] [--output-image PATH] [--cells SPEC] [--stop-on-error] [--check \| --check-only]` | Execute Python code from stdin, a local `.py` file, or a `.ipynb` notebook (exits 1 if the code or any cell raised an error) | | `colab repl [-s NAME] [--output-image PATH]` | Start an interactive Python REPL on the VM (exits cleanly on piped EOF) | | `colab console [-s NAME]` | Connect to a raw interactive TTY shell (tmux) on the remote VM | | `colab ssh [-s NAME] [--proxy-mode] [-i KEY] [--gpu GPU] [--tpu TPU] [--high-mem]` | Open an SSH shell to the runtime over WebSocket, or act as an OpenSSH `ProxyCommand` bridge for IDE remote-dev | @@ -139,6 +139,20 @@ colab log -s analysis -o execution_log.md colab stop -s analysis ``` +### Choosing Notebook Cells, and Checking Before Running + +`colab exec` runs every code cell top to bottom by default. A cell that raises an error does not stop the run, but the command exits with code 1 and lists the failed cells. You can change this with the following options: + +* `--cells SPEC`: run only some cells, in the order given. `SPEC` is a comma-separated list of code-cell numbers (counted from 1, without markdown cells), ranges such as `2-5`, `#@title` values or cell ids. +* `--stop-on-error`: stop at the first failing cell. +* `--check`: check the selected cells locally before anything runs: the notebook structure, `--cells`, and Python syntax (IPython `!cmd`, `%magic`, `x = !cmd` and top-level `await` are accepted; `%%` cell magics are skipped). If a check fails, nothing runs. +* `--check-only`: run the same checks and print which cells would run, without a session. + +```bash +colab exec -f report.ipynb --check-only --cells "Setup,4-6" +colab exec -s analysis -f report.ipynb --check --cells "Setup,4-6" --stop-on-error +``` + --- ## Usage Notes diff --git a/docs/02_execution_and_interactive.md b/docs/02_execution_and_interactive.md index d414d086..d762e12e 100644 --- a/docs/02_execution_and_interactive.md +++ b/docs/02_execution_and_interactive.md @@ -1,5 +1,7 @@ --- log: +2026-10-07: `colab exec` notebook control and exit codes. `--cells SPEC` runs only the selected code cells, in the given order. SPEC accepts code-cell numbers (counted from 1, markdown cells not counted), ranges, `#@title` values and cell ids. `--stop-on-error` stops at the first cell with an error output. Without it every cell still runs, as before. `exec` now exits with code 1 when the code, or any notebook cell, produced an error output; it used to exit 0, so scripts could not tell. `--check` runs a local pre-flight (`colab_cli/notebook.py`) before anything is sent: notebook validation, `--cells` resolution, and a syntax check of each selected cell, compiled with `PyCF_ALLOW_TOP_LEVEL_AWAIT`. IPython `!cmd`, `%magic` and `x = !cmd` lines become `pass`/`None` with their indentation kept, so line numbers match, and `%%` cell magics are skipped. If any check fails, nothing runs and exec exits 2. `--check-only` does the same checks and prints the plan without resolving a session. A missing file or an unreadable notebook now prints one line instead of a traceback. + 2026-10-07: Piped `colab console` no longer cuts off its own output on a fresh runtime, and no longer leaks terminal replies. The EOF handler used to close the websocket a fixed 0.5s (`PIPED_EOF_GRACE_SECONDS`) after sending `exit\n`. On a freshly started runtime the first attach often needs 0.5-1s before the shell answers, so the client closed first and nothing came back (2 of 3 fresh-VM runs, traced with timestamps). The backend closes the websocket itself once bash and tmux exit, after the last output, so the handler now waits for that close (`_closed`, set by `on_close`). It only closes from the client side after `PIPED_EOF_CLOSE_TIMEOUT_SECONDS` (30s), as a fallback for a backend that never closes. With a 5s wait, 3 of 3 fresh-VM runs got their output and the backend closed every time, 0.1-1s after `exit`. Separately, tmux sends terminal queries when it attaches (DA1, DA2, XTVERSION, OSC 10/11). With piped stdin the local terminal's replies can never reach the remote side and were left in the terminal's input for the next command. When stdin is not a TTY, `TerminalQueryFilter` now drops those queries from the output. 2026-10-07: Windows console support for `colab console`. cmd.exe and PowerShell have no `termios`, `/dev/tty`, or `SIGWINCH`, so interactive console used to stay line-buffered (arrow keys never left the local line editor, Ctrl-C killed the CLI, ANSI from the remote PTY rendered as garbage in conhost). `console.py` now enables virtual-terminal processing and UTF-8, switches the input handle to raw mode via `SetConsoleMode`, reads keys with `msvcrt.getwch`, translates scan codes to ANSI, and polls the window size. POSIX raw mode and piped stdin are unchanged. `colab ssh --proxy-mode` reads stdin with a blocking `os.read` (Windows `select()` cannot wait on a pipe) and quotes the ProxyCommand with the MSVCRT rules, because OpenSSH for Windows passes it to `CreateProcess` (not `cmd.exe`, as this entry first said). diff --git a/src/colab_cli/commands/execution.py b/src/colab_cli/commands/execution.py index ab9589f2..b3c39007 100644 --- a/src/colab_cli/commands/execution.py +++ b/src/colab_cli/commands/execution.py @@ -18,7 +18,6 @@ import re import sys import typer -import uuid from nbformat.v4 import new_output from rich.console import Console from typing import List, Optional @@ -27,10 +26,17 @@ from colab_cli.runtime import ColabRuntime from colab_cli.utils import handle_image, is_terminal_error, render_display_data from colab_cli.console import connect_console +from colab_cli.notebook import ( + TITLE_REGEX, # noqa: F401 (re-exported; it used to live here) + CellSelectionError, + CodeCell, + code_cells, + preflight, + select_cells, +) _console = Console() -TITLE_REGEX = re.compile(r"^\s*#\s*@title\s+(.*)", re.MULTILINE) ENV_KEY_REGEX = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$") @@ -137,6 +143,74 @@ def display_output(out, output_image=None): pass +def _load_code_blocks(file: Optional[str], cells_spec: Optional[str]): + """Read what `colab exec` should run. Returns (notebook or None, blocks). + + Each block is a dict with the code and a human-readable ``label``; + notebook blocks also carry the cell, its number, title and id. + """ + if file: + if not os.path.isfile(file): + typer.echo(f"[colab] File not found: '{file}'", err=True) + raise typer.Exit(1) + if not file.endswith(".ipynb"): + with open(file, "r") as f: + return None, [{"code": f.read(), "id": None, "label": file, "title": ""}] + typer.echo(f"[colab] Parsing notebook '{file}'...") + try: + with open(file, "r", encoding="utf-8") as f: + nb = nbformat.read(f, as_version=4) + nbformat.validate(nb) + except Exception as e: + typer.echo(f"[colab] Cannot read notebook '{file}': {e}", err=True) + raise typer.Exit(2) + try: + selected = select_cells(code_cells(nb), cells_spec) + except CellSelectionError as e: + typer.echo(f"[colab] {e}", err=True) + raise typer.Exit(2) + return nb, [ + { + "code": c.source, + "id": c.id, + "cell": c.cell, + "number": c.number, + "title": c.title, + "label": c.label, + } + for c in selected + ] + if is_stdin_tty(): + typer.echo("[colab] Error: No input provided. Pipe code or provide a file.") + raise typer.Exit(1) + return None, [{"code": sys.stdin.read(), "id": None, "label": "stdin", "title": ""}] + + +def _check_blocks(blocks) -> None: + """The --check pre-flight: report every problem, run nothing if any.""" + problems = preflight( + [ + CodeCell( + number=b.get("number", 1), + id=b.get("id"), + title=b.get("title", ""), + source=b["code"], + name=None if "number" in b else b["label"], + ) + for b in blocks + ] + ) + if problems: + typer.echo( + f"[colab] Check failed ({len(problems)} problem(s)); nothing was run:", + err=True, + ) + for problem in problems: + typer.echo(f" {problem}", err=True) + raise typer.Exit(2) + typer.echo(f"[colab] Check passed ({len(blocks)} cell(s)).") + + def exec_command( session: Annotated[ Optional[str], typer.Option("-s", "--session", help="Session name") @@ -161,37 +235,73 @@ def exec_command( ), ), ] = None, + cells: Annotated[ + Optional[str], + typer.Option( + "--cells", + help=( + "Notebooks only: run just these code cells, in this order. " + "Comma-separated code-cell numbers (from 1, markdown cells not " + "counted), ranges such as 2-5, #@title values or cell ids." + ), + ), + ] = None, + stop_on_error: Annotated[ + bool, + typer.Option( + "--stop-on-error", + help="Notebooks only: stop at the first cell that raises an error.", + ), + ] = False, + check: Annotated[ + bool, + typer.Option( + "--check", + help=( + "Before running anything, check the selected cells locally " + "(notebook structure, --cells, Python syntax with IPython " + "magics allowed). Nothing runs if a check fails." + ), + ), + ] = False, + check_only: Annotated[ + bool, + typer.Option( + "--check-only", + help=( + "Run the --check checks and print which cells would run, " + "without a session and without executing anything." + ), + ), + ] = False, ): - """Execute code in a session""" + """Execute code in a session. + + Exits with code 1 if the code (or any notebook cell) raised an error. + """ from colab_cli.common import state env_vars = _parse_env_vars(env) - name = state.resolve_session(session) - s = state.get_session(name) + is_nb = bool(file and file.endswith(".ipynb")) + if (cells is not None or stop_on_error) and not is_nb: + typer.echo( + "[colab] --cells and --stop-on-error only apply to .ipynb notebooks.", + err=True, + ) + raise typer.Exit(2) - code_blocks = [] - if file: - if file.endswith(".ipynb"): - typer.echo(f"[colab] Parsing notebook '{file}'...") - with open(file, "r", encoding="utf-8") as f: - nb = nbformat.read(f, as_version=4) - for cell in nb.cells: - # nbformat v4.5+ requires 'id' at the top level - if not hasattr(cell, "id") or not cell.id: - cell.id = str(uuid.uuid4()) - - if cell.cell_type == "code": - code_blocks.append( - {"code": cell.source, "id": cell.id, "cell": cell} - ) - else: - with open(file, "r") as f: - code_blocks.append({"code": f.read(), "id": None}) - else: - if is_stdin_tty(): - typer.echo("[colab] Error: No input provided. Pipe code or provide a file.") - raise typer.Exit(1) - code_blocks.append({"code": sys.stdin.read(), "id": None}) + if not check_only: + name = state.resolve_session(session) + s = state.get_session(name) + + nb, code_blocks = _load_code_blocks(file, cells) + + if check or check_only: + _check_blocks(code_blocks) + if check_only: + plan = ", ".join(b["label"] for b in code_blocks) or "nothing" + typer.echo(f"[colab] Would run: {plan}") + raise typer.Exit(0) if not any(b["code"].strip() for b in code_blocks): raise typer.Exit(0) @@ -227,27 +337,22 @@ def on_sess_started(sid): raise typer.Exit(1) raise e + failed = [] try: - is_nb = file and file.endswith(".ipynb") s.running = f"exec({file or 'stdin'})" state.store.add(s) + total = len(code_blocks) for i, block in enumerate(code_blocks): code = _build_env_prelude(env_vars) + block["code"] identifier = None if is_nb: - title_match = TITLE_REGEX.search(code) - if title_match: - identifier = title_match.group(1).strip() - elif block.get("id"): - identifier = block["id"] - else: - identifier = "" - + identifier = block["title"] or block.get("id") or "" identifier_str = f" - {identifier}" if identifier else "" - typer.echo( - f"[colab] Executing cell {i + 1}/{len(code_blocks)}{identifier_str}..." - ) + position = f"{i + 1}/{total}" + if cells is not None: + position = f"{block['number']} ({position})" + typer.echo(f"[colab] Executing cell {position}{identifier_str}...") s.last_execution = ( file or "stdin", @@ -269,20 +374,39 @@ def on_sess_started(sid): { "code": code, "outputs": outputs, - "cell_index": i if len(code_blocks) > 1 else None, + "cell_index": ( + block["number"] - 1 if is_nb else None + ), "cell_id": block.get("id"), }, ) + if any(o.get("output_type") == "error" for o in outputs or []): + failed.append(block["label"]) + if stop_on_error and i + 1 < total: + typer.echo( + f"[colab] Stopping at {block['label']} (--stop-on-error); " + f"{total - i - 1} cell(s) not run.", + err=True, + ) + break finally: s.running = None state.store.update_if_present(s) runtime.stop() - if file and file.endswith(".ipynb"): + if is_nb: output_file = os.path.splitext(file)[0] + "_output.ipynb" typer.echo(f"[colab] Saving notebook with outputs to '{output_file}'...") with open(output_file, "w", encoding="utf-8") as f: nbformat.write(nb, f) + if failed: + if is_nb: + typer.echo( + f"[colab] {len(failed)} cell(s) raised an error: {', '.join(failed)}", + err=True, + ) + raise typer.Exit(1) + def repl( session: Annotated[ diff --git a/src/colab_cli/notebook.py b/src/colab_cli/notebook.py new file mode 100644 index 00000000..fda32c4c --- /dev/null +++ b/src/colab_cli/notebook.py @@ -0,0 +1,176 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Notebook helpers for ``colab exec``: cell selection and a local pre-flight check. + +Both run on the local machine before anything is sent to the runtime, so a +typo in ``--cells`` or a syntax error in cell 7 is reported before cells 1-6 +have already run on a paid accelerator. +""" + +import ast +import re +import uuid +from dataclasses import dataclass +from typing import Any, List, Optional + +TITLE_REGEX = re.compile(r"^\s*#\s*@title\s+(.*)", re.MULTILINE) + +# IPython syntax that is not Python: `!cmd`, `%magic` and `x = !cmd`. +_SHELL_OR_MAGIC_LINE = re.compile(r"^(\s*)[!%]") +_SHELL_OR_MAGIC_ASSIGN = re.compile(r"^(\s*[^=!%#\s][^=!%#]*?=\s*)[!%]") +_RANGE = re.compile(r"(\d+)\s*-\s*(\d+)") + + +@dataclass +class CodeCell: + """A code cell, numbered from 1 among the notebook's code cells.""" + + number: int + id: Optional[str] + title: str + source: str + cell: Any = None + # Overrides the label, e.g. the file name when checking a .py file. + name: Optional[str] = None + + @property + def label(self) -> str: + if self.name: + return self.name + return f"cell {self.number}" + (f" ({self.title})" if self.title else "") + + +class CellSelectionError(ValueError): + """A ``--cells`` value that does not match the notebook.""" + + +def code_cells(nb) -> List[CodeCell]: + """The notebook's code cells in order, giving each an id if it has none.""" + cells = [] + for cell in nb.cells: + # nbformat v4.5+ requires 'id' at the top level + if not getattr(cell, "id", None): + cell.id = str(uuid.uuid4()) + if cell.cell_type != "code": + continue + match = TITLE_REGEX.search(cell.source) + cells.append( + CodeCell( + number=len(cells) + 1, + id=cell.id, + title=match.group(1).strip() if match else "", + source=cell.source, + cell=cell, + ) + ) + return cells + + +def select_cells(cells: List[CodeCell], spec: Optional[str]) -> List[CodeCell]: + """Pick cells for ``--cells``, in the order given. + + ``spec`` is a comma-separated list of code-cell numbers (``3``), ranges + (``2-5``), ``#@title`` values or cell ids. Numbers count code cells only, + from 1, so markdown cells do not shift them. ``None`` selects every cell. + """ + if spec is None: + return list(cells) + by_number = {c.number: c for c in cells} + tokens = [t.strip() for t in spec.split(",")] + if not any(tokens) or any(not t for t in tokens): + raise CellSelectionError(f"Empty entry in --cells {spec!r}.") + + def by_num(n: int) -> CodeCell: + if n not in by_number: + raise CellSelectionError( + f"--cells: there is no code cell {n}; the notebook has " + f"{len(cells)} code cell(s)." + ) + return by_number[n] + + selected: List[CodeCell] = [] + for tok in tokens: + rng = _RANGE.fullmatch(tok) + if rng: + start, end = int(rng.group(1)), int(rng.group(2)) + if start > end: + raise CellSelectionError(f"--cells: range {tok!r} runs backwards.") + selected.extend(by_num(n) for n in range(start, end + 1)) + elif tok.isdigit(): + selected.append(by_num(int(tok))) + else: + matches = [ + c for c in cells if c.title.casefold() == tok.casefold() or c.id == tok + ] + if not matches: + raise CellSelectionError( + f"--cells: no code cell has the title or id {tok!r}." + ) + if len(matches) > 1: + numbers = ", ".join(str(c.number) for c in matches) + raise CellSelectionError( + f"--cells: {len(matches)} code cells are titled {tok!r} " + f"({numbers}); select them by number instead." + ) + selected.append(matches[0]) + return selected + + +def as_python(source: str) -> Optional[str]: + """IPython cell source as plain Python, for a syntax check. + + Shell and magic lines become ``pass`` (or ``None`` on the right of an + assignment) with their indentation kept, so line numbers still match. + Returns None for a cell magic (``%%bash`` ...), whose body is not Python. + """ + lines = source.splitlines() + first = next((line for line in lines if line.strip()), "") + if first.lstrip().startswith("%%"): + return None + out = [] + for line in lines: + assign = _SHELL_OR_MAGIC_ASSIGN.match(line) + if assign: + out.append(assign.group(1) + "None") + continue + magic = _SHELL_OR_MAGIC_LINE.match(line) + if magic: + out.append(magic.group(1) + "pass") + continue + out.append(line) + return "\n".join(out) + + +def preflight(cells: List[CodeCell]) -> List[str]: + """Syntax-check ``cells`` locally. Returns one message per problem.""" + problems = [] + for c in cells: + code = as_python(c.source) + if code is None: + continue + try: + compile( + code, + f"<{c.label}>", + "exec", + flags=ast.PyCF_ALLOW_TOP_LEVEL_AWAIT, + dont_inherit=True, + ) + except SyntaxError as e: + message = f"{c.label}, line {e.lineno}: {e.msg}" + if e.text and e.text.strip(): + message += f"\n {e.text.rstrip()}" + problems.append(message) + return problems diff --git a/tests/test_exec.py b/tests/test_exec.py index 203405c2..00b2c165 100644 --- a/tests/test_exec.py +++ b/tests/test_exec.py @@ -235,7 +235,8 @@ 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 + # The code raised an error, so exec reports failure (it used to exit 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) diff --git a/tests/test_exec_notebook_options.py b/tests/test_exec_notebook_options.py new file mode 100644 index 00000000..3007055f --- /dev/null +++ b/tests/test_exec_notebook_options.py @@ -0,0 +1,193 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""`colab exec` notebook options: --cells, --stop-on-error, --check, --check-only, +exit codes, and the missing-file error.""" + +from unittest.mock import MagicMock + +import nbformat +import pytest +from typer.testing import CliRunner + +from colab_cli.cli import app + +runner = CliRunner() + + +@pytest.fixture +def mock_runtime_class(mocker): + return mocker.patch("colab_cli.commands.execution.ColabRuntime") + + +@pytest.fixture +def session(mock_common_state): + s = MagicMock() + s.name = "s1" + s.kernel_id = None + s.session_id = None + mock_common_state.store.get.return_value = s + mock_common_state.resolve_session.return_value = "s1" + return s + + +def _write_nb(tmp_path, *sources): + nb = nbformat.v4.new_notebook() + nb.cells = [nbformat.v4.new_markdown_cell("# intro")] + [ + nbformat.v4.new_code_cell(src) for src in sources + ] + path = tmp_path / "nb.ipynb" + nbformat.write(nb, str(path)) + return str(path) + + +def _runtime_running(mock_runtime_class, fail_on=()): + """The mock runtime records the cell code it ran; code containing any of + ``fail_on`` returns an error output.""" + ran = [] + + def execute_code(code, output_hook=None, **kwargs): + if code.startswith("import os; os.makedirs('/content'"): + return [] + ran.append(code) + if any(marker in code for marker in fail_on): + out = [{"output_type": "error", "ename": "ValueError", "evalue": "boom"}] + else: + out = [{"output_type": "stream", "name": "stdout", "text": "ok\n"}] + if output_hook: + for o in out: + output_hook(o) + return out + + mock_runtime_class.return_value.execute_code.side_effect = execute_code + return ran + + +NB = ("#@title One\nx = 1", "#@title Two\nraise ValueError('two')", "#@title Three\nprint(x)") + + +def test_runs_all_cells_and_exits_1_when_one_fails(tmp_path, mock_runtime_class, session): + """Old behavior kept: later cells still run. New: the exit code says a + cell failed, so scripts can notice.""" + ran = _runtime_running(mock_runtime_class, fail_on=("raise",)) + result = runner.invoke(app, ["exec", "-s", "s1", "-f", _write_nb(tmp_path, *NB)]) + + assert result.exit_code == 1 + assert len(ran) == 3 + assert "1 cell(s) raised an error: cell 2 (Two)" in result.stderr + + +def test_stop_on_error_skips_the_rest(tmp_path, mock_runtime_class, session): + ran = _runtime_running(mock_runtime_class, fail_on=("raise",)) + path = _write_nb(tmp_path, *NB) + result = runner.invoke(app, ["exec", "-s", "s1", "-f", path, "--stop-on-error"]) + + assert result.exit_code == 1 + assert len(ran) == 2 + assert "Stopping at cell 2 (Two) (--stop-on-error); 1 cell(s) not run." in result.stderr + # The partial outputs are still saved. + out = nbformat.read(str(tmp_path / "nb_output.ipynb"), as_version=4) + code = [c for c in out.cells if c.cell_type == "code"] + assert code[0].outputs and code[1].outputs and not code[2].outputs + + +def test_cells_runs_only_the_selection_in_order(tmp_path, mock_runtime_class, session): + ran = _runtime_running(mock_runtime_class) + path = _write_nb(tmp_path, *NB) + result = runner.invoke(app, ["exec", "-s", "s1", "-f", path, "--cells", "Three,1"]) + + assert result.exit_code == 0, result.output + assert [c.splitlines()[0] for c in ran] == ["#@title Three", "#@title One"] + assert "Executing cell 3 (1/2) - Three..." in result.output + assert "Executing cell 1 (2/2) - One..." in result.output + + +def test_bad_cells_spec_fails_before_running(tmp_path, mock_runtime_class, session): + ran = _runtime_running(mock_runtime_class) + path = _write_nb(tmp_path, *NB) + result = runner.invoke(app, ["exec", "-s", "s1", "-f", path, "--cells", "7"]) + + assert result.exit_code == 2 + assert "there is no code cell 7" in result.stderr + assert ran == [] + + +def test_check_stops_a_broken_notebook_before_it_runs( + tmp_path, mock_runtime_class, session +): + ran = _runtime_running(mock_runtime_class) + path = _write_nb(tmp_path, "!pip install x\nx = 1", "#@title Bad\ny = (1,\n") + result = runner.invoke(app, ["exec", "-s", "s1", "-f", path, "--check"]) + + assert result.exit_code == 2 + assert "Check failed (1 problem(s)); nothing was run:" in result.stderr + assert "cell 2 (Bad), line" in result.stderr + assert ran == [] + mock_runtime_class.assert_not_called() + + +def test_check_passes_then_runs(tmp_path, mock_runtime_class, session): + ran = _runtime_running(mock_runtime_class) + path = _write_nb(tmp_path, "!pip install x\nx = 1", "%cd /content\nprint(x)") + result = runner.invoke(app, ["exec", "-s", "s1", "-f", path, "--check"]) + + assert result.exit_code == 0, result.output + assert "Check passed (2 cell(s))." in result.output + assert len(ran) == 2 + + +def test_check_only_needs_no_session(tmp_path, mock_runtime_class, mock_common_state): + path = _write_nb(tmp_path, *NB) + result = runner.invoke(app, ["exec", "-f", path, "--check-only", "--cells", "3,1"]) + + assert result.exit_code == 0, result.output + assert "Would run: cell 3 (Three), cell 1 (One)" in result.output + mock_common_state.resolve_session.assert_not_called() + mock_runtime_class.assert_not_called() + + +def test_check_applies_to_plain_python_files(tmp_path, mock_runtime_class, session): + script = tmp_path / "job.py" + script.write_text("def broken(:\n pass\n") + result = runner.invoke(app, ["exec", "-s", "s1", "-f", str(script), "--check"]) + + assert result.exit_code == 2 + assert f"{script}, line 1:" in result.stderr + + +def test_missing_file_is_one_line(tmp_path, mock_runtime_class, session): + result = runner.invoke(app, ["exec", "-s", "s1", "-f", str(tmp_path / "nope.ipynb")]) + + assert result.exit_code == 1 + assert "[colab] File not found:" in result.stderr + assert "Traceback" not in result.output + + +def test_unreadable_notebook_is_one_line(tmp_path, mock_runtime_class, session): + path = tmp_path / "broken.ipynb" + path.write_text("{not json") + result = runner.invoke(app, ["exec", "-s", "s1", "-f", str(path)]) + + assert result.exit_code == 2 + assert "[colab] Cannot read notebook" in result.stderr + + +@pytest.mark.parametrize("flag", [["--cells", "1"], ["--stop-on-error"]]) +def test_notebook_flags_need_a_notebook(tmp_path, mock_runtime_class, session, flag): + script = tmp_path / "job.py" + script.write_text("x = 1\n") + result = runner.invoke(app, ["exec", "-s", "s1", "-f", str(script), *flag]) + + assert result.exit_code == 2 + assert "only apply to .ipynb notebooks" in result.stderr diff --git a/tests/test_notebook.py b/tests/test_notebook.py new file mode 100644 index 00000000..9c712528 --- /dev/null +++ b/tests/test_notebook.py @@ -0,0 +1,137 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Cell selection and the local pre-flight check behind `colab exec`.""" + +import nbformat +import pytest + +from colab_cli.notebook import ( + CellSelectionError, + as_python, + code_cells, + preflight, + select_cells, +) + + +def _nb(*sources, markdown_first=True): + nb = nbformat.v4.new_notebook() + cells = [nbformat.v4.new_markdown_cell("# intro")] if markdown_first else [] + cells += [nbformat.v4.new_code_cell(src) for src in sources] + nb.cells = cells + return nb + + +@pytest.fixture +def cells(): + return code_cells( + _nb( + "#@title Setup\nx = 1", + "#@title Train\ny = x + 1", + "print(y)", + "#@title Plot\nprint('plot')", + ) + ) + + +def test_code_cells_numbers_code_cells_only(cells): + assert [c.number for c in cells] == [1, 2, 3, 4] + assert [c.title for c in cells] == ["Setup", "Train", "", "Plot"] + assert cells[0].label == "cell 1 (Setup)" + assert cells[2].label == "cell 3" + assert all(c.id for c in cells) + + +def test_select_all_when_no_spec(cells): + assert select_cells(cells, None) == cells + + +@pytest.mark.parametrize( + "spec, numbers", + [ + ("3", [3]), + ("4,1", [4, 1]), # the given order, not notebook order + ("2-4", [2, 3, 4]), + ("1, 3-4", [1, 3, 4]), + ("plot,setup", [4, 1]), # titles, case-insensitive + ("1,1", [1, 1]), + ], +) +def test_select_cells(cells, spec, numbers): + assert [c.number for c in select_cells(cells, spec)] == numbers + + +def test_select_by_cell_id(cells): + assert select_cells(cells, cells[2].id) == [cells[2]] + + +@pytest.mark.parametrize( + "spec, message", + [ + ("5", "there is no code cell 5; the notebook has 4"), + ("3-6", "there is no code cell 5"), + ("4-2", "runs backwards"), + ("Nope", "no code cell has the title or id 'Nope'"), + ("1,,2", "Empty entry"), + ("", "Empty entry"), + ], +) +def test_select_cells_errors(cells, spec, message): + with pytest.raises(CellSelectionError, match=message): + select_cells(cells, spec) + + +def test_select_ambiguous_title(): + cells = code_cells(_nb("#@title Same\na = 1", "#@title Same\nb = 2")) + with pytest.raises(CellSelectionError, match=r"2 code cells are titled 'Same' \(1, 2\)"): + select_cells(cells, "Same") + + +@pytest.mark.parametrize( + "source", + [ + "!pip install -q x", + "%cd /content\nprint(1)", + "files = !ls\nprint(files)", + "env = %env\n", + "if True:\n !echo hi\n %time x = 1", + "await something()", + "#@title T\nx = 1 #@param {type:'integer'}", + "if a != b:\n pass", + "y = 5 % 3", + ], +) +def test_preflight_accepts_ipython_cells(source): + assert preflight(code_cells(_nb(source))) == [] + + +def test_preflight_skips_cell_magics(): + assert as_python("%%bash\necho $((1 +\n") is None + assert preflight(code_cells(_nb("%%bash\nif then fi"))) == [] + + +def test_preflight_keeps_line_numbers(): + assert as_python("!ls\nx = (1,\n").splitlines()[0] == "pass" + + +def test_preflight_reports_each_broken_cell_with_line(): + cells = code_cells( + _nb("#@title Ok\nx = 1", "#@title Broken\nx = 1\ny = (2,\n", "def f(:\n pass") + ) + problems = preflight(cells) + assert len(problems) == 2 + assert problems[0].startswith("cell 2 (Broken), line ") + assert problems[1].startswith("cell 3, line 1:") + assert "def f(:" in problems[1] From 0f3ad515e209dac26829b78d3fd16fb52c65ad78 Mon Sep 17 00:00:00 2001 From: "arlinamid\\arlinamid" Date: Thu, 8 Oct 2026 00:08:27 +0200 Subject: [PATCH 8/8] fix(exec): make --cells number precedence explicit; deflake id test nbformat gives new cells random 8-hex-digit ids, and about 2% of them are all digits. --cells reads an entry that looks like a number or a range as one, so such a cell cannot be selected by its id; that is the intended precedence (numbers are the common case), but it was not documented, and test_select_by_cell_id used a random id and failed when the id happened to be all digits (seen once on Linux). - The test now uses a fixed id, plus a new test pinning that numbers and ranges win over look-alike ids. - --cells help, the select_cells docstring, README and docs say so. Correction to 29f8bfb's message: its Linux line ("461 passed") was not a clean run. The run it was based on had 459 passed and 2 cross-process timing failures in test_state.py, and a rerun at 29f8bfb hit this flaky test. With this commit: Windows 464 passed, 2 skipped; Linux 462 passed, 4 skipped; the notebook tests passed 20 of 20 repeated runs on Linux. The live results in 29f8bfb's message were re-run with English-titled notebooks and match it. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- docs/02_execution_and_interactive.md | 2 +- src/colab_cli/commands/execution.py | 4 +++- src/colab_cli/notebook.py | 5 ++++- tests/test_notebook.py | 14 +++++++++++++- 5 files changed, 22 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 2c3da6b2..10c3b649 100644 --- a/README.md +++ b/README.md @@ -143,7 +143,7 @@ colab stop -s analysis `colab exec` runs every code cell top to bottom by default. A cell that raises an error does not stop the run, but the command exits with code 1 and lists the failed cells. You can change this with the following options: -* `--cells SPEC`: run only some cells, in the order given. `SPEC` is a comma-separated list of code-cell numbers (counted from 1, without markdown cells), ranges such as `2-5`, `#@title` values or cell ids. +* `--cells SPEC`: run only some cells, in the order given. `SPEC` is a comma-separated list of code-cell numbers (counted from 1, without markdown cells), ranges such as `2-5`, `#@title` values or cell ids. An entry that looks like a number or range is always read as one, so select a cell whose title or id is numeric by its number. * `--stop-on-error`: stop at the first failing cell. * `--check`: check the selected cells locally before anything runs: the notebook structure, `--cells`, and Python syntax (IPython `!cmd`, `%magic`, `x = !cmd` and top-level `await` are accepted; `%%` cell magics are skipped). If a check fails, nothing runs. * `--check-only`: run the same checks and print which cells would run, without a session. diff --git a/docs/02_execution_and_interactive.md b/docs/02_execution_and_interactive.md index d762e12e..aad12e59 100644 --- a/docs/02_execution_and_interactive.md +++ b/docs/02_execution_and_interactive.md @@ -1,6 +1,6 @@ --- log: -2026-10-07: `colab exec` notebook control and exit codes. `--cells SPEC` runs only the selected code cells, in the given order. SPEC accepts code-cell numbers (counted from 1, markdown cells not counted), ranges, `#@title` values and cell ids. `--stop-on-error` stops at the first cell with an error output. Without it every cell still runs, as before. `exec` now exits with code 1 when the code, or any notebook cell, produced an error output; it used to exit 0, so scripts could not tell. `--check` runs a local pre-flight (`colab_cli/notebook.py`) before anything is sent: notebook validation, `--cells` resolution, and a syntax check of each selected cell, compiled with `PyCF_ALLOW_TOP_LEVEL_AWAIT`. IPython `!cmd`, `%magic` and `x = !cmd` lines become `pass`/`None` with their indentation kept, so line numbers match, and `%%` cell magics are skipped. If any check fails, nothing runs and exec exits 2. `--check-only` does the same checks and prints the plan without resolving a session. A missing file or an unreadable notebook now prints one line instead of a traceback. +2026-10-07: `colab exec` notebook control and exit codes. `--cells SPEC` runs only the selected code cells, in the given order. SPEC accepts code-cell numbers (counted from 1, markdown cells not counted), ranges, `#@title` values and cell ids. Entries that look like numbers or ranges are always read as such: nbformat's random cell ids are sometimes all digits, so those cells are selected by number. `--stop-on-error` stops at the first cell with an error output. Without it every cell still runs, as before. `exec` now exits with code 1 when the code, or any notebook cell, produced an error output; it used to exit 0, so scripts could not tell. `--check` runs a local pre-flight (`colab_cli/notebook.py`) before anything is sent: notebook validation, `--cells` resolution, and a syntax check of each selected cell, compiled with `PyCF_ALLOW_TOP_LEVEL_AWAIT`. IPython `!cmd`, `%magic` and `x = !cmd` lines become `pass`/`None` with their indentation kept, so line numbers match, and `%%` cell magics are skipped. If any check fails, nothing runs and exec exits 2. `--check-only` does the same checks and prints the plan without resolving a session. A missing file or an unreadable notebook now prints one line instead of a traceback. 2026-10-07: Piped `colab console` no longer cuts off its own output on a fresh runtime, and no longer leaks terminal replies. The EOF handler used to close the websocket a fixed 0.5s (`PIPED_EOF_GRACE_SECONDS`) after sending `exit\n`. On a freshly started runtime the first attach often needs 0.5-1s before the shell answers, so the client closed first and nothing came back (2 of 3 fresh-VM runs, traced with timestamps). The backend closes the websocket itself once bash and tmux exit, after the last output, so the handler now waits for that close (`_closed`, set by `on_close`). It only closes from the client side after `PIPED_EOF_CLOSE_TIMEOUT_SECONDS` (30s), as a fallback for a backend that never closes. With a 5s wait, 3 of 3 fresh-VM runs got their output and the backend closed every time, 0.1-1s after `exit`. Separately, tmux sends terminal queries when it attaches (DA1, DA2, XTVERSION, OSC 10/11). With piped stdin the local terminal's replies can never reach the remote side and were left in the terminal's input for the next command. When stdin is not a TTY, `TerminalQueryFilter` now drops those queries from the output. diff --git a/src/colab_cli/commands/execution.py b/src/colab_cli/commands/execution.py index b3c39007..e5505ee7 100644 --- a/src/colab_cli/commands/execution.py +++ b/src/colab_cli/commands/execution.py @@ -242,7 +242,9 @@ def exec_command( help=( "Notebooks only: run just these code cells, in this order. " "Comma-separated code-cell numbers (from 1, markdown cells not " - "counted), ranges such as 2-5, #@title values or cell ids." + "counted), ranges such as 2-5, #@title values or cell ids. " + "Entries that look like numbers or ranges are always read as " + "such." ), ), ] = None, diff --git a/src/colab_cli/notebook.py b/src/colab_cli/notebook.py index fda32c4c..b073b176 100644 --- a/src/colab_cli/notebook.py +++ b/src/colab_cli/notebook.py @@ -83,7 +83,10 @@ def select_cells(cells: List[CodeCell], spec: Optional[str]) -> List[CodeCell]: ``spec`` is a comma-separated list of code-cell numbers (``3``), ranges (``2-5``), ``#@title`` values or cell ids. Numbers count code cells only, - from 1, so markdown cells do not shift them. ``None`` selects every cell. + from 1, so markdown cells do not shift them. An entry that looks like a + number or a range is always read as one, even if a title or cell id reads + the same (nbformat's random ids are sometimes all digits); select such a + cell by its number. ``None`` selects every cell. """ if spec is None: return list(cells) diff --git a/tests/test_notebook.py b/tests/test_notebook.py index 9c712528..aed29fdf 100644 --- a/tests/test_notebook.py +++ b/tests/test_notebook.py @@ -74,7 +74,19 @@ def test_select_cells(cells, spec, numbers): def test_select_by_cell_id(cells): - assert select_cells(cells, cells[2].id) == [cells[2]] + # A fixed id: nbformat's random 8-hex-digit ids are occasionally all + # digits, and those select by number (see the next test). + cells[2].id = "data-load" + assert select_cells(cells, "data-load") == [cells[2]] + + +def test_numbers_and_ranges_win_over_look_alike_ids(cells): + """An entry that looks like a number or a range is one, even if a cell id + happens to read the same; such cells are selected by number instead.""" + cells[0].id = "3" + cells[1].id = "1-2" + assert [c.number for c in select_cells(cells, "3")] == [3] + assert [c.number for c in select_cells(cells, "1-2")] == [1, 2] @pytest.mark.parametrize(