From 5aa58268c16f79badc99f2952a508d6b4b7edc27 Mon Sep 17 00:00:00 2001 From: "arlinamid\\arlinamid" Date: Fri, 20 Nov 2026 02:39:43 +0100 Subject: [PATCH] feat: colab attach uses a web UI runtime as a local session A runtime opened in the Colab web UI (or by colab on another computer) is listed by `colab sessions` as `[?]`, but no command could work on it: there was no way to upload a file to a notebook's runtime from the CLI. `colab attach --endpoint ID [-s NAME]` saves it as a local session from the assignment's proxy URL and token, so `colab upload`, `exec`, `ssh` and scp through `colab ssh --proxy-mode` work on it. The CLI runs code in its own kernel; files under /content are shared with the notebook. In the tray, the card of such a runtime gets a Connect button. Tested live: a runtime started in the web UI was attached, files were uploaded with `colab upload`, over `colab ssh -- sh -c 'cat > ...'` and with Windows OpenSSH scp, and all three showed in the notebook's Files panel; the runtime was then stopped. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- README.md | 1 + docs/01_session_management.md | 7 +++ docs/09_tray_and_profiles.md | 1 + src/colab_cli/commands/session.py | 66 +++++++++++++++++++++ src/colab_cli/tray/actions.py | 5 ++ src/colab_cli/tray/app.py | 5 ++ src/colab_cli/tray/i18n.py | 2 + src/colab_cli/tray/panel.py | 11 +++- tests/test_attach.py | 98 +++++++++++++++++++++++++++++++ tests/test_tray_actions.py | 5 ++ tests/test_tray_panel.py | 7 ++- 12 files changed, 205 insertions(+), 5 deletions(-) create mode 100644 tests/test_attach.py diff --git a/AGENTS.md b/AGENTS.md index 63ef12f..af109f3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -36,7 +36,7 @@ 3. **Finalize**: Ensure everything is complete and correct. **Whenever features are added or behaviors change, you MUST re-review the corresponding design document in `docs/` and update it to reflect the new state. You should also add a brief log entry to the frontmatter of the updated design document with the current date summarizing the change.** Finally, commit the finished changes to the git branch for review. ## Subcommand Workflows -- **Session Management**: `new`, `sessions`, `status`, `stop`. +- **Session Management**: `new`, `attach`, `sessions`, `status`, `stop`. - **Execution**: `repl`, `exec`, `ssh`. - **Files**: `ls`, `rm`, `upload`, `download`, `edit`. - **Automation**: `auth`, `drivemount`, `install`, `log`, `pay`, `version`, `update`. diff --git a/README.md b/README.md index 5288b70..48423a5 100644 --- a/README.md +++ b/README.md @@ -112,6 +112,7 @@ Run `colab --help` to view specific options, defaults, and detailed he | `colab stop [-s NAME]` | Terminate a session VM and release its resources | | `colab stop --all` | Stop every local session the server still has | | `colab stop --orphans [--yes]` | List server-side runtimes with no local session (`[?]` in `colab sessions`) and stop them after confirmation | +| `colab attach --endpoint ID [-s NAME]` | Use a runtime opened elsewhere (e.g. in the Colab web UI) as a local session: `colab upload`, `colab exec`, `colab ssh` and scp then work on it | | `colab stop --endpoint ID` | Stop one runtime by the endpoint `colab sessions` lists, also one opened in the Colab web UI | | `colab url [-s NAME] [--open]` | Print or open a browser URL connecting to the active session | diff --git a/docs/01_session_management.md b/docs/01_session_management.md index b4bba51..f6ff266 100644 --- a/docs/01_session_management.md +++ b/docs/01_session_management.md @@ -1,5 +1,6 @@ --- log: +2026-11-20: `colab attach --endpoint ID [-s NAME]` saves a runtime that has no local session (opened in the Colab web UI, or by colab on another computer) as a local session, from the assignment's proxy URL and token (`/tun/m/assignments`), so every session command works on it. Default name `web-`; an endpoint that is already a session says so; an unknown endpoint exits 1; an existing name exits 2. The CLI starts its own kernel; `/content` is shared with the notebook. Tested live: a web UI runtime attached, then files uploaded with `colab upload`, over `colab ssh -- sh -c 'cat > ...'` and with Windows OpenSSH scp through `colab ssh --proxy-mode`; all three showed in the notebook's Files panel. 2026-11-20: Listed the fork code that keys runtimes by `endpoint` and has to follow upstream #260 (Public API assign/unassign) once it lands; see TODO. 2026-11-20: `colab stop --endpoint ` stops one runtime by the endpoint `colab sessions` lists, also one with no local session (`[?]`, e.g. opened in the Colab web UI); an endpoint of a local session stops that session as `-s` does, an unknown one exits 1, and it cannot be combined with `-s`, `--orphans` or `--all` (exit 2). The tray's Stop button uses it for such runtimes. 2026-11-20: After the last allocation POST fails with `ReadTimeout` or 502/503/504, `Client.assign` waits one more backoff step and queries the notebook hash again, so a runtime the backend created after the timeout is returned and `colab new` / `colab run` save it instead of leaving a `[?]` orphan (upstream issue #263). If it is still not there, a timeout raises `AssignmentTimeoutError` (a `TimeoutError`, printed as one `[colab]` line) that points to `colab sessions`, `colab stop --orphans` and `COLAB_CLI_REQUEST_TIMEOUT`. Verified live with `COLAB_CLI_REQUEST_TIMEOUT=1 COLAB_CLI_ASSIGN_RETRIES=0`. @@ -111,6 +112,12 @@ tokens, retry limits, exponential backoff and permanent-error handling. A live allocation/recovery test is also required before declaring the behavior verified end to end; mocked timeouts alone do not establish backend compatibility. +### 0. Attach a Runtime (`colab attach`) +- **Purpose**: use a runtime that was not created by this CLI (opened in the Colab web UI, or by colab on another computer; `[?]` in `colab sessions`) as a local session, e.g. to upload files to a notebook's runtime over `colab upload`, `colab ssh` or scp. +- **How**: `sync_sessions()` lists the assignments; the one with the given endpoint becomes a `SessionState` with its `runtimeProxyInfo` token, URL and expiry, accelerator, variant and machine shape. Token refresh then works like for any session. No kernel is recorded, so the first `exec` starts the CLI's own kernel (the notebook's kernel and variables are not shared; files under `/content` are). +- **Errors**: unknown endpoint, exit 1; already a local session, prints its name, exit 0; `-s NAME` taken by another session, exit 2. +- **Stopping**: `colab stop -s NAME` stops the runtime in the web UI too. + ### 1. New Session (`colab new`) - **API**: `GET https://colab.sandbox.google.com/tun/m/assign` (based on HAR). - **Parameters**: diff --git a/docs/09_tray_and_profiles.md b/docs/09_tray_and_profiles.md index ba32e08..2bddd4a 100644 --- a/docs/09_tray_and_profiles.md +++ b/docs/09_tray_and_profiles.md @@ -1,5 +1,6 @@ --- log: +2026-11-20: The card of a runtime with no local session also has a Connect button, which runs `colab attach --endpoint `; the runtime then becomes a normal card with Log and SSH. 2026-11-20: A runtime with no local session (one opened in the Colab web UI or on another computer) can be stopped from the panel. Its card shows the endpoint instead of `?`, says where it may be open, and has only a Stop button (no session for Log or SSH); Stop runs `colab stop --endpoint ` after a dialog that says it stops there too. Before, the card had no buttons, only the `colab stop --orphans` hint. Dialogs have a fixed width with wrapped texts (the radio buttons do not wrap, so each choice is a wrapping label beside one) and are kept inside the screen. Card heights are measured after styling and with word wrap (`totalHeightForWidth(CARDS_WIDTH)`), which had cut off a card's last line and buttons. Tested live with two web UI runtimes stopped from the panel. 2026-11-19: The panel image (`docs/images/tray_panel_training.png`) rendered again with the fork's own logo; the 2026-11-13 image still showed the earlier orange logo. Same example data as before (the demo profile at epoch 2 of 5, no account balance or own profiles). 2026-11-18: About window (`TrayApp.open_about`): the logo, "Hybrid edition", the installed version (`auto_update.get_app_version`, selectable), what the fork adds, links to this fork, its releases and Google's original, and the Apache 2.0 license; English and Hungarian. Opened from the tray menu (Refresh now, Settings, About, Quit) and by clicking the logo in the panel header (`Panel.about_clicked`, tooltip "About"). Checked on screenshots of the dialog and the panel rendered with Windows fonts. diff --git a/src/colab_cli/commands/session.py b/src/colab_cli/commands/session.py index b86138f..ba0a451 100644 --- a/src/colab_cli/commands/session.py +++ b/src/colab_cli/commands/session.py @@ -515,8 +515,74 @@ def stop( typer.echo("[colab] Session terminated.") +def attach( + endpoint: Annotated[ + str, + typer.Option( + "--endpoint", + help="The runtime to attach, by the endpoint `colab sessions` lists.", + ), + ], + session: Annotated[ + Optional[str], + typer.Option( + "-s", + "--session", + help="Name for the local session (default: web-).", + ), + ] = None, +): + """Attach a runtime opened elsewhere (Colab web UI) as a local session""" + from colab_cli.common import state + + sessions, assignments = state.sync_sessions() + assignment = next((a for a in assignments if a.endpoint == endpoint), None) + if assignment is None: + typer.echo(f"[colab] No runtime with endpoint '{endpoint}' on the server.", err=True) + raise typer.Exit(code=1) + owner = next((n for n, s in sessions.items() if s.endpoint == endpoint), None) + if owner: + typer.echo(f"[colab] Runtime {endpoint} is already the session '{owner}'.") + return + name = session or f"web-{endpoint.rsplit('-', 1)[-1][:6]}" + if state.store.get(name): + typer.echo( + f"[colab] A session named '{name}' already exists; choose another with -s.", + err=True, + ) + raise typer.Exit(code=2) + + proxy = assignment.runtime_proxy_info + s = SessionState( + name=name, + token=proxy.token, + url=proxy.url, + endpoint=endpoint, + token_expires_at=proxy.expires_at(), + variant=assignment.variant.name, + accelerator=assignment.accelerator.value, + machine_shape=assignment.machine_shape.name, + ) + state.store.add(s) + state.history.log_event( + name, + "session_attached", + {"endpoint": endpoint, "accelerator": s.accelerator, "variant": s.variant}, + ) + typer.echo(f"[colab] Attached runtime {endpoint} as session '{name}'.") + typer.echo( + f"[colab] Use it like any session: colab exec -s {name}, colab ssh -s {name}, " + f"colab upload -s {name} ..." + ) + typer.echo( + "[colab] The CLI runs code in its own kernel, not in the notebook's; files " + f"under /content are shared. `colab stop -s {name}` stops it there too." + ) + + def register(app: typer.Typer): app.command()(new) + app.command()(attach) app.command(name="sessions")(sessions_command) app.command(name="restart-kernel")(restart_kernel) app.command()(status) diff --git a/src/colab_cli/tray/actions.py b/src/colab_cli/tray/actions.py index 9242e1f..67aa360 100644 --- a/src/colab_cli/tray/actions.py +++ b/src/colab_cli/tray/actions.py @@ -92,6 +92,11 @@ def stop_options(card: Dict[str, Any], has_service: bool, lang: str) -> List[Tup return options +def attach_argv(card: Dict[str, Any]) -> List[str]: + """Make a runtime with no local session (e.g. from the web UI) a local one.""" + return ["attach", "--endpoint", card["endpoint"]] + + def stop_argv(card: Dict[str, Any], choice: str) -> List[str]: if choice == "job": return ["job", "stop", "-s", card["name"], card["job_id"]] diff --git a/src/colab_cli/tray/app.py b/src/colab_cli/tray/app.py index dc325fc..8824aee 100644 --- a/src/colab_cli/tray/app.py +++ b/src/colab_cli/tray/app.py @@ -141,6 +141,7 @@ def __init__(self, state, interval: float): self.panel.ssh_clicked.connect(lambda c: self.in_terminal(actions.ssh_argv(c))) self.panel.open_clicked.connect(self.open_service) self.panel.stop_clicked.connect(self.ask_stop) + self.panel.attach_clicked.connect(self.attach) self.panel.profile_clicked.connect(self.start_profile) self.panel.refresh_clicked.connect(self.refresh) self.panel.settings_clicked.connect(self.open_settings) @@ -448,6 +449,10 @@ def ask_stop(self, card): self.run_cli(actions.stop_argv(card, choice)) QTimer.singleShot(3000, self.refresh) + def attach(self, card): + self.run_cli(actions.attach_argv(card)) + QTimer.singleShot(3000, self.refresh) + def confirm(self, title: str, body: str) -> bool: box = QMessageBox(QMessageBox.Question, title, body) start = box.addButton(t(self.lang, "start"), QMessageBox.AcceptRole) diff --git a/src/colab_cli/tray/i18n.py b/src/colab_cli/tray/i18n.py index 91c4bcb..38181bf 100644 --- a/src/colab_cli/tray/i18n.py +++ b/src/colab_cli/tray/i18n.py @@ -72,6 +72,7 @@ "ssh": "SSH", "open": "Open", "stop": "Stop", + "attach": "Connect", "compute_units": "Compute Units", "balance": "Balance:", "usage": "Usage:", @@ -167,6 +168,7 @@ "notify.already_starting": "{name} már indul vagy fut; várd meg, vagy előbb állítsd le.", "orphan": "nincs a helyi munkamenetek között", "orphan_hint": "lehet, hogy a Colab webes felületén vagy egy másik gépen van megnyitva", + "attach": "Csatlakozás", "forwarding": "továbbítás: {ports}", "not_answering": "{port} (nem válaszol)", "epoch": "{cur} / {total} epoch", diff --git a/src/colab_cli/tray/panel.py b/src/colab_cli/tray/panel.py index 691536c..6d5e4dc 100644 --- a/src/colab_cli/tray/panel.py +++ b/src/colab_cli/tray/panel.py @@ -138,6 +138,7 @@ class Panel(QWidget): ssh_clicked = Signal(dict) open_clicked = Signal(dict) stop_clicked = Signal(dict) + attach_clicked = Signal(dict) profile_clicked = Signal(str) refresh_clicked = Signal() settings_clicked = Signal() @@ -374,8 +375,14 @@ def _card(self, item, lang) -> QFrame: # Still being created: no runtime to open a log, SSH or stop yet. return frame buttons = QHBoxLayout() - # A runtime unknown to this CLI has no session for a log or SSH; it - # can only be stopped, by its endpoint. + # A runtime unknown to this CLI (opened in the web UI, or on another + # computer) has no session for a log or SSH: it can be attached as + # one, or stopped by its endpoint. + if not card["local"]: + b = QPushButton(t(lang, "attach"), objectName="action") + b.setIcon(glyph_icon("open", TEXT)) + b.clicked.connect(lambda _=False, c=card: self.attach_clicked.emit(c)) + buttons.addWidget(b) for key, glyph, signal in (("log", "log", self.log_clicked), ("ssh", "terminal", self.ssh_clicked)): if not card["local"]: break diff --git a/tests/test_attach.py b/tests/test_attach.py new file mode 100644 index 0000000..bcf2405 --- /dev/null +++ b/tests/test_attach.py @@ -0,0 +1,98 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +"""`colab attach`: a runtime opened elsewhere (Colab web UI) as a local session.""" + +from datetime import datetime, timezone +from unittest.mock import MagicMock + +import pytest +from typer.testing import CliRunner + +from colab_cli.cli import app +from colab_cli.state import SessionState + +runner = CliRunner() +EXPIRES = datetime(2030, 1, 1, tzinfo=timezone.utc) + + +def _assignment(endpoint, accelerator="NONE", variant="DEFAULT"): + a = MagicMock(endpoint=endpoint) + a.accelerator.value = accelerator + a.variant.name = variant + a.machine_shape.name = "STANDARD" + a.runtime_proxy_info.token = f"tok-{endpoint}" + a.runtime_proxy_info.url = f"https://8080-{endpoint}.prod.colab.dev" + a.runtime_proxy_info.expires_at.return_value = EXPIRES + return a + + +@pytest.fixture +def server(mock_common_state): + """One local session (`mine`) and one runtime opened in the web UI.""" + mine = SessionState(name="mine", token="t", url="u", endpoint="ep-mine") + mock_common_state.sync_sessions.return_value = ( + {"mine": mine}, + [_assignment("ep-mine"), _assignment("m-s-use1c1-239y7roywmzti", "T4", "GPU")], + ) + mock_common_state.store.get.side_effect = lambda n: mine if n == "mine" else None + return mock_common_state + + +def _saved(server): + server.store.add.assert_called_once() + return server.store.add.call_args.args[0] + + +def test_attach_saves_the_runtime_as_a_session(server): + result = runner.invoke(app, ["attach", "--endpoint", "m-s-use1c1-239y7roywmzti", "-s", "web"]) + + assert result.exit_code == 0, result.output + s = _saved(server) + assert (s.name, s.endpoint) == ("web", "m-s-use1c1-239y7roywmzti") + assert s.token == "tok-m-s-use1c1-239y7roywmzti" + assert s.url == "https://8080-m-s-use1c1-239y7roywmzti.prod.colab.dev" + assert (s.accelerator, s.variant, s.machine_shape) == ("T4", "GPU", "STANDARD") + assert s.token_expires_at == EXPIRES and s.kernel_id is None + server.history.log_event.assert_called_once() + assert server.history.log_event.call_args.args[:2] == ("web", "session_attached") + assert "colab exec -s web" in result.output + assert "own kernel" in result.output and "stops it there too" in result.output + + +def test_attach_names_the_session_after_the_endpoint(server): + result = runner.invoke(app, ["attach", "--endpoint", "m-s-use1c1-239y7roywmzti"]) + assert result.exit_code == 0, result.output + assert _saved(server).name == "web-239y7r" + + +def test_attach_unknown_endpoint(server): + result = runner.invoke(app, ["attach", "--endpoint", "ep-gone"]) + assert result.exit_code == 1 + assert "ep-gone" in result.output + server.store.add.assert_not_called() + + +def test_attach_a_runtime_that_already_has_a_session(server): + result = runner.invoke(app, ["attach", "--endpoint", "ep-mine"]) + assert result.exit_code == 0 + assert "already the session 'mine'" in result.output + server.store.add.assert_not_called() + + +def test_attach_does_not_overwrite_another_session(server): + result = runner.invoke(app, ["attach", "--endpoint", "m-s-use1c1-239y7roywmzti", "-s", "mine"]) + assert result.exit_code == 2 + server.store.add.assert_not_called() diff --git a/tests/test_tray_actions.py b/tests/test_tray_actions.py index 0078382..42d961f 100644 --- a/tests/test_tray_actions.py +++ b/tests/test_tray_actions.py @@ -199,3 +199,8 @@ def test_orphan_card_stops_by_endpoint(): assert "m-s-web-123" in opts["runtime"] and "Colab web UI" in opts["runtime"] assert "Colab webes" in dict(a.stop_options(orphan, has_service=False, lang="hu"))["runtime"] assert a.stop_argv(orphan, "runtime") == ["stop", "--endpoint", "m-s-web-123"] + + +def test_attach_argv_for_an_orphan(): + orphan = _card(name="?", local=False, endpoint="m-s-web-123", job_id=None, can_stop_job=False) + assert a.attach_argv(orphan) == ["attach", "--endpoint", "m-s-web-123"] diff --git a/tests/test_tray_panel.py b/tests/test_tray_panel.py index d255838..ff82dde 100644 --- a/tests/test_tray_panel.py +++ b/tests/test_tray_panel.py @@ -133,11 +133,14 @@ def test_many_runtimes_scroll(tray): assert tray.panel.cards_host.sizeHint().height() > tray.panel.scroll.height() -def test_an_orphan_card_can_only_be_stopped(tray, mocker): +def test_an_orphan_card_can_be_attached_or_stopped(tray, mocker): _render(tray, [_entry("?", None, local=False, endpoint="m-s-web-123")]) card = tray.panel.cards[0] buttons = card.findChildren(QPushButton) - assert [b.text() for b in buttons] == ["Leállítás"] + assert [b.text() for b in buttons] == ["Csatlakozás", "Leállítás"] + buttons[0].click() + assert tray.popen.call_args.args[0] == ["colab", "attach", "--endpoint", "m-s-web-123"] + buttons = buttons[1:] texts = [w.text() for w in card.findChildren(QLabel)] assert "m-s-web-123" in texts assert any("Colab webes felületén" in x for x in texts)