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
3 changes: 2 additions & 1 deletion docs/06_ssh_access.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
---
log:
2026-11-20: A default key for `colab ssh` and `colab forward` without `-i`: `COLAB_CLI_SSH_IDENTITY`, else `ssh_identity` in `settings.json`, else `~/.ssh/id_ed25519.pub` / `id_ecdsa.pub` (`_default_identity`). The tray's SSH and forward buttons pass no `-i`, so a key with another name (e.g. `~/.ssh/colab_ed25519`) could not be used from there. The no-key message names the setting. Tested live: `colab ssh -- CMD` without `-i`, and the tray's SSH button on an attached web UI runtime.
2026-11-20: Merged upstream `colab ssh --force` (#254): before connecting, it kills the runtime's existing SSH sessions through the kernel (`pkill -P $(pgrep -o -x sshd)`), for when a dead client keeps the session slot and the server answers 429. It works with the fork's interactive shell, `-N`/`-L` forwards, `-- CMD` and `--proxy-mode`.
2026-11-12: Linux: ssh is started with `preexec_fn=_ssh_preexec`, which sets `PR_SET_PDEATHSIG` (SIGTERM), so a SIGKILL of colab also ends ssh and, through ssh, its ProxyCommand; the standalone binary's CLI process ties itself to its PyInstaller launcher the same way (`_tie_to_launcher_linux`, only when the parent runs the same exe). macOS has no equivalent; a closed terminal (SIGHUP) still ends everything there. Git Bash: the remote `-- CMD` arguments are passed through `utils.undo_msys_args`, so `colab ssh -- ls /content` works without `MSYS_NO_PATHCONV`. Live on the Windows binary: ssh path and launcher kill; on the Linux binary: launcher SIGKILL.
2026-11-12: `colab ssh` (interactive, `-- CMD`, `-N`) and `colab forward` check that a key file exists before they create a runtime or start ssh (`_require_ssh_key`), and exit 2. Before, the ProxyCommand child found the key missing, so the user got ssh's exit 255 after an interactive `colab ssh` had already assigned a runtime. Without a default key, the message names other ed25519/ECDSA keys in `~/.ssh` and how to pass one with `-i`. Added `tests/test_ssh_key_precheck.py`.
Expand Down Expand Up @@ -43,7 +44,7 @@ colab ssh [OPTIONS] [-- CMD [ARGS]...]
|---|---|---|---|
| `-s`, `--session` | str | auto | Session to connect to. If omitted, uses your only active session, auto-creates one when you have none (not with `-- CMD`), or errors when you have several. |
| `--proxy-mode` | bool | False | Act as an OpenSSH `ProxyCommand`-compatible WebSocket↔stdio bridge (reads stdin, writes stdout) for `~/.ssh/config`. Every other flag still applies. |
| `-i`, `--identity` | str | auto | SSH key (`.pub` public key or private key path) for the public key sent to Colab. Default: first of `~/.ssh/id_ed25519.pub`, `id_ecdsa.pub`. |
| `-i`, `--identity` | str | auto | SSH key (`.pub` public key or private key path) for the public key sent to Colab. Default: `COLAB_CLI_SSH_IDENTITY`, else `ssh_identity` in `~/.config/colab-cli/settings.json`, else the first of `~/.ssh/id_ed25519.pub`, `id_ecdsa.pub`. |
| `--gpu` | str | None | GPU accelerator for a runtime this command creates (T4, L4, G4, H100, A100). |
| `--tpu` | str | None | TPU accelerator for a runtime this command creates (v5e1, v6e1). |
| `--high-mem` | bool | False | Request high-RAM when this command auto-creates a runtime (ignored when connecting to an existing session). |
Expand Down
2 changes: 2 additions & 0 deletions docs/09_tray_and_profiles.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
---
log:
2026-11-20: The SSH and forward buttons use `ssh_identity` from `settings.json` (or `COLAB_CLI_SSH_IDENTITY`) when the key is not `~/.ssh/id_ed25519` / `id_ecdsa`; before, they ended with "no SSH public key found".
2026-11-20: A card without a wrapped line (an idle runtime, such as one just attached with Connect) has no height for width, and Qt then returns about 1 px: the card list collapsed and the panel looked empty. Each card now takes the larger of its size hint and its height for the panel width.
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).
Expand Down
25 changes: 24 additions & 1 deletion src/colab_cli/commands/ssh.py
Original file line number Diff line number Diff line change
Expand Up @@ -464,6 +464,25 @@ def _resolve_pubkey(identity: Optional[str]) -> str:
raise typer.Exit(code=2)


def _default_identity(identity: Optional[str]) -> Optional[str]:
"""``-i``, else ``COLAB_CLI_SSH_IDENTITY``, else ``ssh_identity`` in settings.json.

The tray's SSH and forward buttons pass no ``-i``; without a setting only
``~/.ssh/id_ed25519`` and ``id_ecdsa`` could be used from there.
"""
if identity:
return identity
if env := os.getenv("COLAB_CLI_SSH_IDENTITY"):
return env
from colab_cli.common import state

with contextlib.suppress(Exception):
configured = state.settings_store.load().ssh_identity
if isinstance(configured, str) and configured:
return configured
return None


def _ssh_dir() -> Path:
return Path(os.path.expanduser("~/.ssh"))

Expand All @@ -472,7 +491,9 @@ def _no_key_message(ssh_dir: Path) -> str:
"""Says no default key exists, naming other usable keys in ``ssh_dir``."""
message = (
"[colab] no SSH public key found in ~/.ssh/. Run "
"`ssh-keygen -t ed25519` to generate one, or pass --identity."
"`ssh-keygen -t ed25519` to generate one, or pass --identity "
'(to keep using a key, set "ssh_identity" in '
"~/.config/colab-cli/settings.json or COLAB_CLI_SSH_IDENTITY)."
)
others = []
with contextlib.suppress(OSError):
Expand Down Expand Up @@ -1344,6 +1365,7 @@ def ssh(
if proxy_mode and cmd:
typer.echo("[colab] --proxy-mode takes no command.", err=True)
raise typer.Exit(code=2)
identity = _default_identity(identity)
forwards = [_parse_forward(f) for f in forward or []]
keep_alive = bool(forwards) and not no_keep_alive
if no_shell and not forwards:
Expand Down Expand Up @@ -1422,6 +1444,7 @@ def forward(
Only your machine can reach it. The runtime is kept alive meanwhile.
"""
forwards = [_parse_forward(p) for p in ports]
identity = _default_identity(identity)
_require_ssh_key(identity)
s = _resolve_session(session)
raise typer.Exit(
Expand Down
3 changes: 3 additions & 0 deletions src/colab_cli/state.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,9 @@ class Settings(BaseModel):
)
last_check: Optional[datetime] = None
enable_update_check: bool = True
# SSH key for `colab ssh` / `colab forward` without -i (and so for the
# tray's SSH and forward buttons); COLAB_CLI_SSH_IDENTITY overrides it.
ssh_identity: Optional[str] = None
# Highest fork version seen on the update source; cached for the banner.
latest_version: Optional[str] = None
# Wheel of that fork release, installed by `colab update --install`.
Expand Down
4 changes: 2 additions & 2 deletions src/colab_cli/tray/i18n.py
Original file line number Diff line number Diff line change
Expand Up @@ -378,7 +378,7 @@ def hardware_label(hw: str) -> str:
"help.env": "Environment variables, one KEY=VALUE per line. Not for tokens: use Secrets.",
"help.vars": "Python globals set before the script runs, as a JSON object, e.g. {\"CONFIG\": {\"access\": \"forward\"}}. Useful for notebooks that read settings from variables (#@param).",
"help.forward": "Runtime ports to forward to this computer after the script ran, separated by commas: 8188, or LOCAL:REMOTE (8080:80). Needs a passphrase-less SSH key. The forward keeps the runtime alive while it runs.",
"help.ssh_key": "The private key for the forward. Empty: ~/.ssh/id_ed25519 or id_ecdsa. It must have no passphrase.",
"help.ssh_key": "The private key for the forward. Empty: ssh_identity from settings.json, else ~/.ssh/id_ed25519 or id_ecdsa. It must have no passphrase.",
"help.open": "Opened in the browser once the service answers, e.g. http://127.0.0.1:8188. The tray's Open button uses it too.",
"help.ready": "The address that tells the service is up (any answer below HTTP 500). Empty: the Open URL.",
"help.stop_when_done": "Job: the tray stops the runtime once the job has ended (only while the tray runs). Kernel: the runtime stops when the run ends (the forward is closed). Off: the runtime keeps running and using compute units until you stop it.",
Expand Down Expand Up @@ -441,7 +441,7 @@ def hardware_label(hw: str) -> str:
"help.env": "Környezeti változók, soronként egy KULCS=ÉRTÉK. Tokenhez ne ezt használd, hanem a Titkokat.",
"help.vars": "A script előtt beállított Python-globálisok JSON-objektumként, pl. {\"CONFIG\": {\"access\": \"forward\"}}. Olyan notebookokhoz jó, amelyek változókból olvassák a beállításaikat (#@param).",
"help.forward": "A script után a gépedre továbbítandó portok, vesszővel elválasztva: 8188, vagy HELYI:TÁVOLI (8080:80). Jelszó nélküli SSH-kulcs kell hozzá. Amíg a továbbítás fut, ébren tartja a gépet.",
"help.ssh_key": "A továbbításhoz használt privát kulcs. Üresen: ~/.ssh/id_ed25519 vagy id_ecdsa. Nem lehet jelszava.",
"help.ssh_key": "A továbbításhoz használt privát kulcs. Üresen: a settings.json ssh_identity értéke, különben ~/.ssh/id_ed25519 vagy id_ecdsa. Nem lehet jelszava.",
"help.open": "Ezt nyitja meg a böngészőben, ha a szolgáltatás válaszol, pl. http://127.0.0.1:8188. A tray Megnyitás gombja is ezt használja.",
"help.ready": "Erről a címről derül ki, hogy a szolgáltatás elindult (bármilyen válasz HTTP 500 alatt). Üresen: a megnyitandó cím.",
"help.stop_when_done": "Háttérfeladat: a feladat végén a tray leállítja a gépet (csak ha a tray fut). Kernel: a futtatás végén (a továbbítás bezárásakor) áll le a gép. Kikapcsolva a gép tovább fut és fogyaszt, amíg le nem állítod.",
Expand Down
7 changes: 6 additions & 1 deletion src/colab_cli/tray/panel.py
Original file line number Diff line number Diff line change
Expand Up @@ -329,7 +329,12 @@ def _render_cards(self, view):
c.ensurePolished()
for child in c.findChildren(QWidget):
child.ensurePolished()
height = sum(c.layout().totalHeightForWidth(CARDS_WIDTH) for c in visible)
# A card without a wrapped label has no height for width (Qt
# returns next to nothing): take its size hint then.
height = sum(
max(c.sizeHint().height(), c.layout().totalHeightForWidth(CARDS_WIDTH))
for c in visible
)
height += 8 * max(len(visible) - 1, 0)
self.scroll.setFixedHeight(height if visible else 40)

Expand Down
77 changes: 77 additions & 0 deletions tests/test_ssh_identity_setting.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
# 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.

"""A default SSH key from settings.json or COLAB_CLI_SSH_IDENTITY.

The tray's SSH and forward buttons run `colab ssh` / `colab forward` without
-i, so a key with another name than id_ed25519 / id_ecdsa could not be used.
"""

from unittest.mock import MagicMock

import pytest
from typer.testing import CliRunner

from colab_cli.cli import app
from colab_cli.commands import ssh as ssh_module
from colab_cli.state import Settings

runner = CliRunner()


@pytest.fixture
def key(tmp_path):
priv = tmp_path / "colab_ed25519"
priv.write_text("private")
(tmp_path / "colab_ed25519.pub").write_text("ssh-ed25519 AAAA test")
return str(priv)


@pytest.fixture
def forward(mock_common_state, mocker, monkeypatch):
monkeypatch.delenv("COLAB_CLI_SSH_IDENTITY", raising=False)
mock_common_state.settings_store.load.return_value = Settings()
mocker.patch.object(ssh_module, "_resolve_session", return_value=MagicMock())
return mocker.patch.object(ssh_module, "_run_forward_only", return_value=0)


def _identity(run):
return run.call_args.args[1]


def test_settings_ssh_identity_is_the_default_key(mock_common_state, forward, key):
mock_common_state.settings_store.load.return_value = Settings(ssh_identity=key)
result = runner.invoke(app, ["forward", "-s", "s1", "8080"])
assert result.exit_code == 0, result.output
assert _identity(forward) == key


def test_env_var_wins_over_settings(mock_common_state, forward, key, monkeypatch):
mock_common_state.settings_store.load.return_value = Settings(ssh_identity="~/.ssh/other")
monkeypatch.setenv("COLAB_CLI_SSH_IDENTITY", key)
result = runner.invoke(app, ["forward", "-s", "s1", "8080"])
assert result.exit_code == 0, result.output
assert _identity(forward) == key


def test_dash_i_wins(mock_common_state, forward, key, monkeypatch):
monkeypatch.setenv("COLAB_CLI_SSH_IDENTITY", "~/.ssh/other")
result = runner.invoke(app, ["forward", "-s", "s1", "-i", key, "8080"])
assert result.exit_code == 0, result.output
assert _identity(forward) == key


def test_no_key_message_names_the_setting(tmp_path, monkeypatch):
message = ssh_module._no_key_message(tmp_path)
assert "ssh_identity" in message and "COLAB_CLI_SSH_IDENTITY" in message
11 changes: 10 additions & 1 deletion tests/test_tray_panel.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ def test_many_runtimes_scroll(tray):

assert len(tray.panel.cards) == 5
first = tray.panel.cards[:MAX_VISIBLE_CARDS]
heights = [c.layout().totalHeightForWidth(CARDS_WIDTH) for c in first]
heights = [max(c.sizeHint().height(), c.layout().totalHeightForWidth(CARDS_WIDTH)) for c in first]
assert tray.panel.scroll.height() == sum(heights) + 8 * (len(first) - 1)
assert tray.panel.cards_host.sizeHint().height() > tray.panel.scroll.height()

Expand Down Expand Up @@ -597,3 +597,12 @@ def test_dialogs_stay_on_the_screen(tray, mocker):
assert screen.contains(dialog.frameGeometry().topLeft())
assert dialog.width() <= screen.width()
dialog.deleteLater()


def test_a_card_without_wrapped_text_is_shown(tray):
"""Without a wrapped label (an idle runtime, e.g. one just attached) the
layout has no height for width: the list was 1 px high and looked empty."""
_render(tray, [_entry("web-2gw7hz", None)])
card = tray.panel.cards[0]
assert card.sizeHint().height() > 50
assert tray.panel.scroll.height() >= card.sizeHint().height()