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..10c3b649 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). @@ -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 | @@ -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 | @@ -139,12 +139,27 @@ 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. 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. + +```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 * **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..aad12e59 100644 --- a/docs/02_execution_and_interactive.md +++ b/docs/02_execution_and_interactive.md @@ -1,5 +1,11 @@ --- 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. 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. + +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. 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,8 +39,8 @@ 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. -- **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. +- **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 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. @@ -54,4 +60,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..3afc9cd3 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 @@ -149,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 d2600091..a959c908 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 = ( @@ -180,7 +167,7 @@ def drivefs_hook(deserialize_msg, wsclient): sys.stderr.write(f"{ename}: {evalue}\n") finally: s.running = None - state.store.add(s) + state.store.update_if_present(s) runtime.stop() @@ -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/execution.py b/src/colab_cli/commands/execution.py index 336a5ffb..e5505ee7 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,75 @@ 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. " + "Entries that look like numbers or ranges are always read as " + "such." + ), + ), + ] = 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) @@ -207,6 +319,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, @@ -226,27 +339,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", @@ -268,20 +376,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.add(s) + 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[ @@ -308,6 +435,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 +476,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 +494,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 +522,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/files.py b/src/colab_cli/commands/files.py index fa1c9050..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") @@ -152,20 +185,26 @@ 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) - click.edit(filename=local_path) + _launch_editor(local_path) hash_after = get_file_hash(local_path) 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/commands/ssh.py b/src/colab_cli/commands/ssh.py index 5bceea7a..c8db6c8a 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,11 @@ 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. 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]: @@ -421,7 +433,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 +496,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 +558,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..79f4c38b 100644 --- a/src/colab_cli/console.py +++ b/src/colab_cli/console.py @@ -12,13 +12,13 @@ # See the License for the specific language governing permissions and # limitations under the License. +import contextlib import json import logging import os import signal import sys import threading -import time try: import termios @@ -28,25 +28,40 @@ # 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, + windows_raw_console, +) logger = logging.getLogger(__name__) # 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, -# 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): @@ -56,7 +71,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}") @@ -73,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): @@ -96,30 +115,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 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 + if not _closed.wait(PIPED_EOF_CLOSE_TIMEOUT_SECONDS): + try: + ws.close() + except Exception: + pass + break + chunks = [char] + for chunk in chunks: + ws.send(json.dumps({"data": chunk})) except Exception: break @@ -131,8 +164,13 @@ 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 + _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. + enable_windows_virtual_terminal() # Construct the WebSocket URL from the base URL parsed = urlparse(session.url) @@ -140,9 +178,13 @@ 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 + # 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 +208,49 @@ def handle_sigwinch(signum, frame): send_terminal_size(ws) sigwinch = getattr(signal, "SIGWINCH", None) + resize_stop = threading.Event() + + 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) + + raw_cm = windows_raw_console() if use_windows_raw else contextlib.nullcontext() try: - if can_raw: - tty.setraw(fd, termios.TCSANOW) - if sigwinch is not None: - signal.signal(sigwinch, handle_sigwinch) + 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() - # 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) - 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}") + 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/notebook.py b/src/colab_cli/notebook.py new file mode 100644 index 00000000..b073b176 --- /dev/null +++ b/src/colab_cli/notebook.py @@ -0,0 +1,179 @@ +# 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. 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) + 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/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/src/colab_cli/terminal.py b/src/colab_cli/terminal.py new file mode 100644 index 00000000..30335921 --- /dev/null +++ b/src/colab_cli/terminal.py @@ -0,0 +1,315 @@ +# 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 re +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``). + 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. + """ + if windows is None: + windows = is_windows() + if windows: + return subprocess.list2cmdline(argv) + 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_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_cli.py b/tests/test_cli.py index b7d08ef2..da29c045 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 @@ -47,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 @@ -397,9 +406,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 @@ -568,6 +581,134 @@ 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 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() @@ -657,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_console.py b/tests/test_console.py index 13f20961..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") @@ -225,7 +283,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,11 +295,96 @@ 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() + + +@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_no_termios_degrades_gracefully( - mock_isatty, mock_ws_app, mock_session +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): """Windows has no termios/tty/SIGWINCH. connect_console must not crash. Regression test for `ModuleNotFoundError: No module named 'termios'` @@ -259,3 +406,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 " 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", [ @@ -248,6 +314,9 @@ def test_bridge_proxy_mode_pumps_ws_to_stdout(mocker): "$(touch /tmp/pwned)", "a;rm -rf /", "ünïcode", + "a&b|c", + "100%", + "a%h", ], ids=[ "word", @@ -257,6 +326,9 @@ def test_bridge_proxy_mode_pumps_ws_to_stdout(mocker): "cmd-substitution", "semicolon", "non-ascii", + "cmd-metachars", + "percent", + "percent-token", ], ) @pytest.mark.parametrize( @@ -265,12 +337,13 @@ def test_bridge_proxy_mode_pumps_ws_to_stdout(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, @@ -343,18 +416,14 @@ def test_ssh_proxy_mode_calls_websocket(mock_common_state, mocker): connect = mocker.patch.object( ssh_module, "_connect_websocket", return_value=fake_ws ) - bridge = mocker.patch.object( - ssh_module, "_bridge_proxy_mode", return_value=0 - ) + bridge = mocker.patch.object(ssh_module, "_bridge_proxy_mode", return_value=0) ssh_subprocess = mocker.patch.object(ssh_module, "_run_interactive_ssh") result = runner.invoke(app, ["ssh", "--proxy-mode", "-s", "s1"]) assert result.exit_code == 0 connect.assert_called_once() args, _ = connect.call_args - assert args[0].startswith( - "wss://abc-foo.colab.googleusercontent.com/colab/ssh" - ) + assert args[0].startswith("wss://abc-foo.colab.googleusercontent.com/colab/ssh") assert args[1] == fake_pub bridge.assert_called_once_with(fake_ws) ssh_subprocess.assert_not_called() @@ -401,9 +470,7 @@ def fake_connect(url, pubkey): captured["url"] = url return MagicMock() - mocker.patch.object( - ssh_module, "_connect_websocket", side_effect=fake_connect - ) + mocker.patch.object(ssh_module, "_connect_websocket", side_effect=fake_connect) mocker.patch.object(ssh_module, "_bridge_proxy_mode", return_value=0) runner.invoke(app, ["ssh", "--proxy-mode", "-s", "s1"]) @@ -430,9 +497,7 @@ def test_ssh_handshake_400_emits_actionable_message( ssh_module, "_resolve_pubkey", return_value="ssh-rsa AAAAfake u@h" ) - err = websocket.WebSocketBadStatusException( - "Handshake status 400 Bad Request", 400 - ) + err = websocket.WebSocketBadStatusException("Handshake status 400 Bad Request", 400) err.status_code = 400 err.resp_body = resp_body mocker.patch.object(websocket.WebSocket, "connect", side_effect=err) 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( 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 diff --git a/tests/test_terminal.py b/tests/test_terminal.py new file mode 100644 index 00000000..72534b2e --- /dev/null +++ b/tests/test_terminal.py @@ -0,0 +1,219 @@ +# 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 used by console, ssh, and drivemount. + +These tests mock the platform so they run on Linux CI and still pin the +Windows PowerShell / cmd.exe behavior. +""" + +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"), + [ + ("a", None, "a"), + ("\r", None, "\r"), # Enter, same byte a POSIX raw tty produces + ("\x03", None, "\x03"), # Ctrl-C must reach the remote shell + ("\x00", "H", "\x1b[A"), # up + ("\xe0", "P", "\x1b[B"), # down + ("\x00", "M", "\x1b[C"), # right + ("\xe0", "K", "\x1b[D"), # left + ("\x00", "G", "\x1b[H"), # home + ("\xe0", "O", "\x1b[F"), # end + ("\x00", "S", "\x1b[3~"), # delete + ("\xe0", "Z", ""), # unknown scan code is dropped, not forwarded raw + ], +) +def test_translate_windows_key(first, second, expected): + assert translate_windows_key(first, second) == expected + + +def test_join_argv_posix_round_trips_through_shlex(): + import shlex + + argv = ["/usr/bin/python3", "-m", "colab_cli.cli", "ssh", "-s", "a b"] + cmd = join_argv(argv, windows=False) + assert shlex.split(cmd) == argv + + +def test_join_argv_windows_uses_cmd_quoting(): + """Windows OpenSSH runs ProxyCommand via cmd.exe, which does not treat + single quotes as quoting. Spaces must be double-quoted.""" + argv = [ + r"C:\Program Files\Python\python.exe", + "-m", + "colab_cli.cli", + "ssh", + "--proxy-mode", + "-s", + "my session", + ] + cmd = join_argv(argv, windows=True) + assert cmd == subprocess.list2cmdline(argv) + assert '"C:\\Program Files\\Python\\python.exe"' in cmd + assert '"my session"' in cmd + assert "'" not in cmd + + +def test_read_controlling_line_windows_uses_conin(mocker): + mocker.patch("colab_cli.terminal.is_windows", return_value=True) + fake = mocker.mock_open(read_data="\n") + mocker.patch("builtins.open", fake) + assert read_controlling_line("Press Enter... ") == "\n" + fake.assert_called_once_with("CONIN$", "r", encoding="utf-8", errors="replace") + + +def test_read_controlling_line_posix_uses_dev_tty(mocker): + mocker.patch("colab_cli.terminal.is_windows", return_value=False) + fake = mocker.mock_open(read_data="yes\n") + mocker.patch("builtins.open", fake) + assert read_controlling_line() == "yes\n" + fake.assert_called_once_with("/dev/tty", encoding="utf-8", errors="replace") + + +def test_read_controlling_line_falls_back_to_stdin(mocker): + mocker.patch("colab_cli.terminal.is_windows", return_value=False) + mocker.patch("builtins.open", side_effect=OSError("no tty")) + mocker.patch("sys.stdin.readline", return_value="ok\n") + assert read_controlling_line() == "ok\n" + + +def test_open_url_windows_uses_startfile(mocker): + mocker.patch("colab_cli.terminal.is_windows", return_value=True) + startfile = mocker.Mock() + mocker.patch("colab_cli.terminal.os.startfile", startfile, create=True) + assert open_url_in_browser("https://accounts.google.com/o/oauth2/v2/auth") is True + startfile.assert_called_once_with("https://accounts.google.com/o/oauth2/v2/auth") + + +def test_open_url_linux_skips_when_xdg_open_missing(mocker): + mocker.patch("colab_cli.terminal.is_windows", return_value=False) + mocker.patch("colab_cli.terminal.sys.platform", "linux") + mocker.patch("colab_cli.terminal.shutil.which", return_value=None) + assert open_url_in_browser("https://example.com") is False + + +def test_open_url_linux_uses_xdg_open(mocker): + mocker.patch("colab_cli.terminal.is_windows", return_value=False) + mocker.patch("colab_cli.terminal.sys.platform", "linux") + mocker.patch("colab_cli.terminal.shutil.which", return_value="/usr/bin/xdg-open") + popen = mocker.patch("colab_cli.terminal.subprocess.Popen") + assert open_url_in_browser("https://example.com") is True + assert popen.call_args.args[0] == ["/usr/bin/xdg-open", "https://example.com"] + + +def test_open_url_macos_uses_open(mocker): + mocker.patch("colab_cli.terminal.is_windows", return_value=False) + mocker.patch("colab_cli.terminal.sys.platform", "darwin") + mocker.patch("colab_cli.terminal.shutil.which", return_value="/usr/bin/open") + popen = mocker.patch("colab_cli.terminal.subprocess.Popen") + assert open_url_in_browser("https://example.com") is True + assert popen.call_args.args[0][0] == "/usr/bin/open" + + +def test_enable_virtual_terminal_noop_off_windows(mocker): + mocker.patch("colab_cli.terminal.is_windows", return_value=False) + assert enable_windows_virtual_terminal() is False + + +def test_windows_raw_console_noop_off_windows(mocker): + mocker.patch("colab_cli.terminal.is_windows", return_value=False) + with windows_raw_console(): + pass