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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ Run `colab <command> --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 |

Expand Down
7 changes: 7 additions & 0 deletions docs/01_session_management.md
Original file line number Diff line number Diff line change
@@ -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-<first 6 of the id's last part>`; 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 <id>` 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`.
Expand Down Expand Up @@ -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**:
Expand Down
1 change: 1 addition & 0 deletions docs/09_tray_and_profiles.md
Original file line number Diff line number Diff line change
@@ -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 <id>`; 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 <id>` 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.
Expand Down
66 changes: 66 additions & 0 deletions src/colab_cli/commands/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -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-<id>).",
),
] = 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)
Expand Down
5 changes: 5 additions & 0 deletions src/colab_cli/tray/actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"]]
Expand Down
5 changes: 5 additions & 0 deletions src/colab_cli/tray/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down
2 changes: 2 additions & 0 deletions src/colab_cli/tray/i18n.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@
"ssh": "SSH",
"open": "Open",
"stop": "Stop",
"attach": "Connect",
"compute_units": "Compute Units",
"balance": "Balance:",
"usage": "Usage:",
Expand Down Expand Up @@ -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",
Expand Down
11 changes: 9 additions & 2 deletions src/colab_cli/tray/panel.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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
Expand Down
98 changes: 98 additions & 0 deletions tests/test_attach.py
Original file line number Diff line number Diff line change
@@ -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()
5 changes: 5 additions & 0 deletions tests/test_tray_actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
7 changes: 5 additions & 2 deletions tests/test_tray_panel.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading