From c4d0ee6d3317d16ee680a28a17c89250a0534b06 Mon Sep 17 00:00:00 2001 From: "arlinamid\\arlinamid" Date: Fri, 20 Nov 2026 03:27:36 +0100 Subject: [PATCH 1/3] feat(files): ls --json, mkdir, rm -r, and upload/download --via ssh The pieces the tray's file manager runs as CLI subcommands: - `colab ls --json`: one object with the path and its items (name, type, size, last_modified), folders first; an error is JSON too. - `colab mkdir PATH` creates a remote folder. - `colab rm -r PATH` removes a folder and everything in it (the contents API refuses a folder that is not empty), children first. - `colab upload/download --via ssh [-i KEY]` copies with OpenSSH scp through `colab ssh --proxy-mode` instead of the contents API; it uses the default key from `ssh_identity` / COLAB_CLI_SSH_IDENTITY. Tested live on an attached Colab web UI runtime: mkdir, a tree uploaded and downloaded back identical over scp, ls --json, rm -r. Co-Authored-By: Claude Opus 5.5 --- src/colab_cli/commands/files.py | 124 ++++++++++++++++++++++++++++- src/colab_cli/commands/ssh.py | 26 ++++++ src/colab_cli/contents.py | 15 ++++ tests/test_files_extras.py | 136 ++++++++++++++++++++++++++++++++ 4 files changed, 298 insertions(+), 3 deletions(-) create mode 100644 tests/test_files_extras.py diff --git a/src/colab_cli/commands/files.py b/src/colab_cli/commands/files.py index beb3503..5e5796c 100644 --- a/src/colab_cli/commands/files.py +++ b/src/colab_cli/commands/files.py @@ -14,6 +14,7 @@ import click import hashlib +import json import os import shutil import subprocess @@ -33,6 +34,13 @@ def ls( Optional[str], typer.Option("-s", "--session", help="Session name") ] = None, path: Annotated[str, typer.Argument(help="Remote path to list")] = "content", + as_json: Annotated[ + bool, + typer.Option( + "--json", + help="One JSON object: path and items (name, type, size, last_modified).", + ), + ] = False, ): """List files in a session""" from colab_cli.common import state @@ -44,6 +52,9 @@ def ls( try: data = contents.list_dir(path) state.history.log_event(name, "file_operation", {"op": "ls", "path": path}) + if as_json: + typer.echo(json.dumps(_listing(path, data))) + return if data.get("type") == "directory": items = data.get("content", []) for item in sorted( @@ -53,6 +64,50 @@ def ls( typer.echo(f"{item.get('name')}{suffix}") else: typer.echo(data.get("name")) + except Exception as e: + if as_json: + typer.echo(json.dumps({"path": path, "error": redact_secrets(str(e))})) + else: + typer.echo(f"[colab] Error: {redact_secrets(str(e))}") + raise typer.Exit(1) + finally: + contents.close() + + +def _listing(path: str, data: dict) -> dict: + """`ls --json`: folders first, then by name, as for the plain listing.""" + if data.get("type") != "directory": + data = {"content": [data]} + items = [ + { + "name": item.get("name"), + "type": item.get("type"), + "size": item.get("size"), + "last_modified": item.get("last_modified"), + } + for item in data.get("content") or [] + ] + items.sort(key=lambda i: (i["type"] != "directory", i["name"] or "")) + return {"path": path, "items": items} + + +def mkdir( + session: Annotated[ + Optional[str], typer.Option("-s", "--session", help="Session name") + ] = None, + path: Annotated[str, typer.Argument(help="Remote folder to create")] = ..., +): + """Create a remote folder""" + from colab_cli.common import state + + name = state.resolve_session(session) + path = undo_msys_path(path) + s = state.get_session(name) + contents = ContentsClient(s) + try: + contents.mkdir(path) + state.history.log_event(name, "file_operation", {"op": "mkdir", "path": path}) + typer.echo(f"[colab] Created {path}") except Exception as e: typer.echo(f"[colab] Error: {redact_secrets(str(e))}") raise typer.Exit(1) @@ -65,8 +120,12 @@ def rm( Optional[str], typer.Option("-s", "--session", help="Session name") ] = None, path: Annotated[str, typer.Argument(help="Remote path to remove")] = ..., + recursive: Annotated[ + bool, + typer.Option("-r", "--recursive", help="Remove a folder and everything in it"), + ] = False, ): - """Remove a remote file""" + """Remove a remote file, or a folder with -r""" from colab_cli.common import state name = state.resolve_session(session) @@ -74,8 +133,13 @@ def rm( s = state.get_session(name) contents = ContentsClient(s) try: - contents.rm(path) - state.history.log_event(name, "file_operation", {"op": "rm", "path": path}) + if recursive: + contents.rm_tree(path) + else: + contents.rm(path) + state.history.log_event( + name, "file_operation", {"op": "rm", "path": path, "recursive": recursive} + ) typer.echo(f"[colab] Deleted {path}") except Exception as e: typer.echo(f"[colab] Error: {redact_secrets(str(e))}") @@ -96,6 +160,17 @@ def upload( bool, typer.Option("-r", "--recursive", help="Recursively upload a directory"), ] = False, + via: Annotated[ + str, + typer.Option( + "--via", + help="contents (Jupyter contents API, the default) or ssh (scp; needs an SSH key).", + ), + ] = "contents", + identity: Annotated[ + Optional[str], + typer.Option("--identity", "-i", help="With --via ssh: the SSH key, as for `colab ssh`."), + ] = None, ): """Upload a file or directory to a session""" from colab_cli.common import state @@ -113,6 +188,9 @@ def upload( label = "path" if recursive else "file" typer.echo(f"[colab] Local {label} '{local_path}' not found.") raise typer.Exit(1) + if _check_via(via) == "ssh": + _transfer_via_ssh(state, name, s, identity, local_path, remote_path, upload=True, recursive=is_dir) + return contents = ContentsClient(s) try: if is_dir: @@ -160,13 +238,28 @@ def download( bool, typer.Option("-r", "--recursive", help="Recursively download a directory"), ] = False, + via: Annotated[ + str, + typer.Option( + "--via", + help="contents (Jupyter contents API, the default) or ssh (scp; needs an SSH key).", + ), + ] = "contents", + identity: Annotated[ + Optional[str], + typer.Option("--identity", "-i", help="With --via ssh: the SSH key, as for `colab ssh`."), + ] = None, ): """Download a file or directory from a session""" from colab_cli.common import state + _check_via(via) name = state.resolve_session(session) remote_path = undo_msys_path(remote_path) s = state.get_session(name) + if via == "ssh": + _transfer_via_ssh(state, name, s, identity, remote_path, local_path, upload=False, recursive=recursive) + return contents = ContentsClient(s) try: if recursive: @@ -200,6 +293,30 @@ def download( contents.close() +def _check_via(via: str) -> str: + if via not in ("contents", "ssh"): + typer.echo(f"[colab] --via must be contents or ssh, not {via!r}.", err=True) + raise typer.Exit(2) + return via + + +def _transfer_via_ssh(state, name, s, identity, source, target, *, upload, recursive) -> None: + """scp through the session's SSH bridge; exits with scp's code on failure.""" + from colab_cli.commands.ssh import scp_transfer + + code = scp_transfer(s, identity, source, target, upload=upload, recursive=recursive) + op = "upload" if upload else "download" + state.history.log_event( + name, + "file_operation", + {"op": op, "source": source, "target": target, "via": "ssh", "recursive": recursive, "exit_code": code}, + ) + if code: + typer.echo(f"[colab] {op.capitalize()} over ssh failed (scp exit code {code}).", err=True) + raise typer.Exit(code) + typer.echo(f"[colab] {'Uploaded' if upload else 'Downloaded'} '{source}' to '{target}' over ssh") + + def _launch_editor(path: str) -> None: """Open ``path`` in the user's editor and wait for it to exit. @@ -300,6 +417,7 @@ def get_file_hash(path): def register(app: typer.Typer): app.command()(ls) app.command()(rm) + app.command()(mkdir) app.command()(upload) app.command()(download) app.command()(edit) diff --git a/src/colab_cli/commands/ssh.py b/src/colab_cli/commands/ssh.py index edd5509..00895a2 100644 --- a/src/colab_cli/commands/ssh.py +++ b/src/colab_cli/commands/ssh.py @@ -957,6 +957,32 @@ def _ssh_base_args( return args +def scp_transfer( + session: SessionState, + identity: Optional[str], + source: str, + target: str, + *, + upload: bool, + recursive: bool, +) -> int: + """Copies with OpenSSH scp through this session's WebSocket bridge. + + The remote side is a path on the runtime (``content/x`` or ``/content/x``); + returns scp's exit code. + """ + identity = _default_identity(identity) + _require_ssh_key(identity) + args = _ssh_base_args(_proxy_command(session, identity, _DEFAULT_SSH_MODE), identity) + args[0] = _openssh_tool("scp") + args.insert(1, "-q") + if recursive: + args.insert(1, "-r") + remote = f"{_SSH_HOST}:/{target.lstrip('/') if upload else source.lstrip('/')}" + args += [source, remote] if upload else [remote, target] + return subprocess.call(args) + + def _call_ssh(args: list[str], session: SessionState, keep_alive: bool) -> int: """Runs ssh and returns its exit code, pinging keep-alive while it runs. diff --git a/src/colab_cli/contents.py b/src/colab_cli/contents.py index b5739bb..d61ba6a 100644 --- a/src/colab_cli/contents.py +++ b/src/colab_cli/contents.py @@ -291,3 +291,18 @@ def write_text(self, remote_path: str, text: str): def rm(self, remote_path: str): self._request("DELETE", remote_path) + + def rm_tree(self, remote_path: str) -> None: + """Delete a folder and everything in it, children first. + + The contents API does not delete a folder that is not empty. + """ + data = self.list_dir(remote_path) + if data.get("type") == "directory": + for item in data.get("content") or []: + child = posixpath.join(remote_path, _validate_entry_name(item.get("name"))) + if item.get("type") == "directory": + self.rm_tree(child) + else: + self.rm(child) + self.rm(remote_path) diff --git a/tests/test_files_extras.py b/tests/test_files_extras.py new file mode 100644 index 0000000..9420419 --- /dev/null +++ b/tests/test_files_extras.py @@ -0,0 +1,136 @@ +# 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. + + +"""CLI pieces the tray's file manager runs (docs/09): ls --json, mkdir, +rm -r, and upload/download --via ssh (scp through `colab ssh --proxy-mode`).""" + +import json +from unittest.mock import MagicMock, call + +import pytest +from typer.testing import CliRunner + +from colab_cli.cli import app +from colab_cli.commands import files as files_module +from colab_cli.contents import ContentsClient + +runner = CliRunner() + + +@pytest.fixture +def session(mock_common_state): + s = MagicMock(url="https://u", token="t", endpoint="ep") + s.name = "s1" + mock_common_state.resolve_session.return_value = "s1" + mock_common_state.get_session.return_value = s + return s + + +@pytest.fixture +def contents(mocker, session): + return mocker.patch.object(files_module, "ContentsClient").return_value + + +def test_ls_json_lists_folders_first_with_sizes(contents): + contents.list_dir.return_value = { + "type": "directory", + "path": "content", + "content": [ + {"name": "b.txt", "type": "file", "size": 3, "last_modified": "2026-11-20T01:00:00Z"}, + {"name": "data", "type": "directory", "size": None, "last_modified": "2026-11-19T01:00:00Z"}, + {"name": "a.ipynb", "type": "notebook", "size": 10, "last_modified": "2026-11-20T02:00:00Z"}, + ], + } + result = runner.invoke(app, ["ls", "-s", "s1", "--json", "content"]) + assert result.exit_code == 0, result.output + data = json.loads(result.stdout) + assert data["path"] == "content" + assert [i["name"] for i in data["items"]] == ["data", "a.ipynb", "b.txt"] + assert data["items"][0] == { + "name": "data", "type": "directory", "size": None, "last_modified": "2026-11-19T01:00:00Z", + } + + +def test_ls_json_error_is_json_too(contents): + contents.list_dir.side_effect = FileNotFoundError("File or directory not found: nope") + result = runner.invoke(app, ["ls", "-s", "s1", "--json", "nope"]) + assert result.exit_code == 1 + assert "not found" in json.loads(result.stdout)["error"] + + +def test_mkdir(contents): + result = runner.invoke(app, ["mkdir", "-s", "s1", "content/new"]) + assert result.exit_code == 0, result.output + contents.mkdir.assert_called_once_with("content/new") + + +def test_rm_r_removes_a_tree(contents): + result = runner.invoke(app, ["rm", "-s", "s1", "-r", "content/data"]) + assert result.exit_code == 0, result.output + contents.rm_tree.assert_called_once_with("content/data") + contents.rm.assert_not_called() + + +def test_rm_tree_deletes_children_before_their_folder(): + client = ContentsClient.__new__(ContentsClient) + listings = { + "d": {"type": "directory", "content": [ + {"name": "f.txt", "type": "file"}, {"name": "sub", "type": "directory"}, + ]}, + "d/sub": {"type": "directory", "content": [{"name": "g.txt", "type": "file"}]}, + } + client.list_dir = MagicMock(side_effect=lambda p: listings[p]) + client.rm = MagicMock() + client.rm_tree("d") + assert client.rm.call_args_list == [call("d/f.txt"), call("d/sub/g.txt"), call("d/sub"), call("d")] + + +@pytest.fixture +def scp(mocker, session, tmp_path, monkeypatch): + key = tmp_path / "k" + key.write_text("private") + (tmp_path / "k.pub").write_text("ssh-ed25519 AAAA") + monkeypatch.setenv("COLAB_CLI_SSH_IDENTITY", str(key)) + mocker.patch("colab_cli.commands.ssh._proxy_command", return_value="PROXY") + return mocker.patch("colab_cli.commands.ssh.subprocess.call", return_value=0) + + +def test_upload_via_ssh_runs_scp(scp, tmp_path): + folder = tmp_path / "dir" + folder.mkdir() + result = runner.invoke(app, ["upload", "-s", "s1", "-r", "--via", "ssh", str(folder), "content/dir"]) + assert result.exit_code == 0, result.output + argv = scp.call_args.args[0] + assert "scp" in argv[0] and "-r" in argv and "ProxyCommand=PROXY" in argv + assert argv[-2:] == [str(folder), "root@colab-runtime:/content/dir"] + + +def test_download_via_ssh_runs_scp(scp, tmp_path): + result = runner.invoke(app, ["download", "-s", "s1", "--via", "ssh", "content/a.txt", str(tmp_path / "a.txt")]) + assert result.exit_code == 0, result.output + argv = scp.call_args.args[0] + assert "-r" not in argv + assert argv[-2:] == ["root@colab-runtime:/content/a.txt", str(tmp_path / "a.txt")] + + +def test_scp_failure_exits_with_its_code(scp, tmp_path): + scp.return_value = 1 + result = runner.invoke(app, ["download", "-s", "s1", "--via", "ssh", "content/a.txt", str(tmp_path / "a")]) + assert result.exit_code == 1 + + +def test_unknown_via(session, tmp_path): + result = runner.invoke(app, ["download", "-s", "s1", "--via", "ftp", "content/a", str(tmp_path / "a")]) + assert result.exit_code == 2 From e0e591ba9092984595e563de896139ebb445f93d Mon Sep 17 00:00:00 2001 From: "arlinamid\\arlinamid" Date: Fri, 20 Nov 2026 03:42:40 +0100 Subject: [PATCH 2/3] feat(tray): a two-pane file manager for a runtime The Files button of a local card opens a Total Commander style window: this computer on the left (drive list, Up), the runtime on the right from /content. Drag and drop, the Upload/Download buttons or F5 copy between them; F7 makes a folder, F8 deletes (local files go to the recycle bin, remote ones after a confirmation), Enter or double-click opens, Backspace goes up. The line at the bottom runs a command in the runtime's folder: `colab ssh -- sh -c` over ssh, otherwise `colab exec` with Python on stdin, so it works without an SSH key. Transfers go over the contents API or ssh/scp, chosen at the top and saved as `tray_transfer` in settings.json. Every action is one of the CLI's own subcommands (ls --json, upload/download -r --via, mkdir, rm -r, ssh, exec), run one at a time with QProcess. Tested live: the window's runner uploaded, downloaded, ran a command and deleted on an attached Colab web UI runtime, and the window was tried from the tray (a locked system file reported its permission error). Co-Authored-By: Claude Opus 5.5 --- README.md | 9 +- docs/03_file_management.md | 1 + docs/09_tray_and_profiles.md | 9 + src/colab_cli/state.py | 2 + src/colab_cli/tray/app.py | 15 + src/colab_cli/tray/file_ops.py | 102 +++++++ src/colab_cli/tray/files.py | 501 +++++++++++++++++++++++++++++++++ src/colab_cli/tray/glyphs.py | 1 + src/colab_cli/tray/i18n.py | 72 +++++ src/colab_cli/tray/panel.py | 4 +- tests/test_tray_file_ops.py | 81 ++++++ tests/test_tray_files.py | 205 ++++++++++++++ tests/test_tray_panel.py | 10 +- 13 files changed, 1002 insertions(+), 10 deletions(-) create mode 100644 src/colab_cli/tray/file_ops.py create mode 100644 src/colab_cli/tray/files.py create mode 100644 tests/test_tray_file_ops.py create mode 100644 tests/test_tray_files.py diff --git a/README.md b/README.md index 0bd3d27..c4d0565 100644 --- a/README.md +++ b/README.md @@ -135,10 +135,11 @@ Run `colab --help` to view specific options, defaults, and detailed he ### File Operations | Command | Description | | --- | --- | -| `colab ls [-s NAME] [PATH]` | List remote files on the VM | -| `colab upload [-s NAME] [-r] LOCAL REMOTE` | Upload a local file or directory (`-r`) to the VM filesystem | -| `colab download [-s NAME] [-r] REMOTE LOCAL` | Download a remote file or directory (`-r`) from the VM filesystem | -| `colab rm [-s NAME] PATH` | Delete a remote file on the VM filesystem | +| `colab ls [-s NAME] [--json] [PATH]` | List remote files on the VM (`--json`: name, type, size, modified) | +| `colab upload [-s NAME] [-r] [--via contents\|ssh] LOCAL REMOTE` | Upload a local file or directory (`-r`) to the VM filesystem; `--via ssh` copies with scp | +| `colab download [-s NAME] [-r] [--via contents\|ssh] REMOTE LOCAL` | Download a remote file or directory (`-r`) from the VM filesystem; `--via ssh` copies with scp | +| `colab mkdir [-s NAME] PATH` | Create a remote folder | +| `colab rm [-s NAME] [-r] PATH` | Delete a remote file, or a folder with everything in it (`-r`) | | `colab edit [-s NAME] PATH` | Edit a remote file in-place using your local `$EDITOR` | ### Automation & Utilities diff --git a/docs/03_file_management.md b/docs/03_file_management.md index 2ed7939..f7cb26a 100644 --- a/docs/03_file_management.md +++ b/docs/03_file_management.md @@ -1,5 +1,6 @@ --- log: +2026-11-20: For the tray's file manager: `colab ls --json` (one object: path, items with name/type/size/last_modified, folders first; an error is JSON too), `colab mkdir`, `colab rm -r` (`ContentsClient.rm_tree`, children first, since the contents API refuses a folder that is not empty), and `--via ssh [-i KEY]` on `upload`/`download`, which copies with OpenSSH scp through `colab ssh --proxy-mode` (`ssh.scp_transfer`) using the default key setting. Tested live on an attached web UI runtime. 2026-11-20: Took upstream PR #267 (`colab upload -r` / `colab download -r`, by Koji Shukawa) before Google merged it, with its review comments applied: no `ntpath` import (a drive-prefixed entry name is still refused on Windows, through `os.path.splitdrive`), simpler `posixpath.join` calls, `_is_local_symlink` so a destination given as `link/` is still seen as a symlink on POSIX, and HTTP errors without the URL (the fork's message, which hides the runtime proxy token). Tested live on a Colab web UI runtime: a tree with subfolders and an empty folder uploaded and downloaded back identical. 2026-11-19: Added `-r`/`--recursive` support to `colab upload` and `colab download` via `ContentsClient.mkdir`, `_ensure_dir`, `upload_dir`, and `download_dir` (preserving empty directories, skipping symlinks on upload, handling single-file `download -r` targets, normalizing remote paths, and enforcing entry-name, canonical local-symlink/containment, and recursion-depth checks). Reused a persistent `requests.Session` in `ContentsClient` with `close()`/context-manager cleanup (reopening a fresh client after `$EDITOR` in `colab edit`) for HTTP keep-alive, and redacted `colab-runtime-proxy-token` query params from `HTTPError` messages. 2026-11-12: Errors no longer show the runtime proxy token: `ContentsClient` reports an HTTP error as status and path (requests put the full URL, token included, in its message) and the file commands print errors through `common.redact_secrets`. Under Git Bash on Windows, remote paths that MSYS rewrote (`/content` -> `C:/Program Files/Git/content`) are turned back by `utils.undo_msys_path`. A failing editor in `colab edit` prints `[colab] ...: Editing failed` and exits 1 instead of a traceback (Typer vendors its own Click and does not handle `click.ClickException`). diff --git a/docs/09_tray_and_profiles.md b/docs/09_tray_and_profiles.md index aeb8407..20ca72a 100644 --- a/docs/09_tray_and_profiles.md +++ b/docs/09_tray_and_profiles.md @@ -1,5 +1,6 @@ --- log: +2026-11-20: A two-pane file manager (`tray/files.py`, argv in `tray/file_ops.py`), opened with the Files button of a local card, in the style of Total Commander: this computer on the left (drive list, Up), the runtime on the right from `content`. Copy by drag and drop, the Upload/Download buttons or F5; F7 new folder, F8 delete (a local file goes to the recycle bin, a remote one after a confirmation, `rm -r` for a folder), Enter or double-click opens, Backspace goes up. The line at the bottom runs a command in the runtime's folder (`colab ssh -- sh -c` over ssh, otherwise `colab exec` with Python on stdin, so no key is needed). Transfers go over the contents API or scp (`--via`), chosen at the top and saved as `tray_transfer`. Every action is a CLI subcommand run with QProcess, one at a time. Tested live: the window's runner uploaded, downloaded, ran a command and deleted on an attached web UI runtime; the user tried it from the tray. 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 `; the runtime then becomes a normal card with Log and SSH. @@ -255,6 +256,14 @@ run it on each binary. running job only the runtime can be stopped. A runtime with no local session is stopped by its endpoint (`colab stop --endpoint`), and the dialog says it may be open in the Colab web UI or on another computer. +- **Files** opens a two-pane file manager for the runtime (`tray/files.py`): + this computer on the left (drive list, Up), the runtime on the right. Drag + and drop, the Upload/Download buttons or F5 copy; F7 makes a folder, F8 + deletes (local files go to the recycle bin), Enter opens, Backspace goes up, + and the bottom line runs a command in the runtime's folder. The transfer + goes over the contents API (no key) or ssh/scp, saved as `tray_transfer`. + Every action is a CLI subcommand (`ls --json`, `upload`/`download -r --via`, + `mkdir`, `rm -r`, `ssh -- CMD` or `exec`), run one at a time. - **Log** opens a window that runs `colab job tail -n 200` (Follow adds `--follow` while the job runs) or, without a job, `colab log -n 200`, and shows the output as it comes; a help line says what it shows and where the diff --git a/src/colab_cli/state.py b/src/colab_cli/state.py index 632b80f..9a75822 100644 --- a/src/colab_cli/state.py +++ b/src/colab_cli/state.py @@ -66,6 +66,8 @@ class Settings(BaseModel): tray_interval: Optional[float] = None tray_notifications: bool = True tray_language: str = "auto" + # The tray's file manager: "contents" (contents API) or "ssh" (scp). + tray_transfer: str = "contents" tray_last_profile: Optional[str] = None # Warn when the balance lasts less than this many hours at the current # rate, or a runtime has been idle this many minutes (Colab reclaims diff --git a/src/colab_cli/tray/app.py b/src/colab_cli/tray/app.py index 8824aee..88028cb 100644 --- a/src/colab_cli/tray/app.py +++ b/src/colab_cli/tray/app.py @@ -142,6 +142,7 @@ def __init__(self, state, interval: float): 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.files_clicked.connect(self.open_files) self.panel.profile_clicked.connect(self.start_profile) self.panel.refresh_clicked.connect(self.refresh) self.panel.settings_clicked.connect(self.open_settings) @@ -449,6 +450,20 @@ def ask_stop(self, card): self.run_cli(actions.stop_argv(card, choice)) QTimer.singleShot(3000, self.refresh) + def open_files(self, card): + """The two-pane file manager for this runtime (tray/files.py).""" + from colab_cli.tray.files import FileManager + + for w in self.windows: + if isinstance(w, FileManager) and w.session == card["name"] and w.isVisible(): + w.raise_() + w.activateWindow() + return w + return self._show_window(FileManager( + card["name"], self.lang, colab_argv(self.state), + settings_store=getattr(self.state, "settings_store", None), + )) + def attach(self, card): self.run_cli(actions.attach_argv(card)) QTimer.singleShot(3000, self.refresh) diff --git a/src/colab_cli/tray/file_ops.py b/src/colab_cli/tray/file_ops.py new file mode 100644 index 0000000..05e8eea --- /dev/null +++ b/src/colab_cli/tray/file_ops.py @@ -0,0 +1,102 @@ +# 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. + +"""What the tray's file manager runs, as CLI argv (docs/09). No Qt. + +Every action is one of the CLI's own subcommands (`colab ls --json`, +`upload`, `download`, `mkdir`, `rm`, `ssh -- CMD`, `exec`), so the window +never talks to the runtime itself. Remote paths are contents-API paths +(`content/data`), as `colab ls` takes them. +""" + +import json +import os +import posixpath +import shlex +from typing import List, Optional, Tuple + +VIAS = ("contents", "ssh") + + +def remote_join(folder: str, name: str) -> str: + return posixpath.join(folder, name) if folder else name + + +def remote_parent(path: str) -> str: + return posixpath.dirname(path.rstrip("/")) + + +def ls_argv(session: str, path: str) -> List[str]: + return ["ls", "-s", session, "--json", path] + + +def copy_argv(session: str, source: str, target_dir: str, *, upload: bool, is_dir: bool, via: str) -> List[str]: + """Copy ``source`` into ``target_dir`` on the other side, keeping its name.""" + if upload: + target = remote_join(target_dir, os.path.basename(source.rstrip("/\\"))) + else: + target = os.path.join(target_dir, posixpath.basename(source.rstrip("/"))) + argv = ["upload" if upload else "download", "-s", session] + if is_dir: + argv.append("-r") + return argv + ["--via", via, source, target] + + +def mkdir_argv(session: str, path: str) -> List[str]: + return ["mkdir", "-s", session, path] + + +def rm_argv(session: str, path: str, *, is_dir: bool) -> List[str]: + return ["rm", "-s", session, *(["-r"] if is_dir else []), path] + + +def command_argv(session: str, cwd: str, command: str, *, via: str) -> Tuple[List[str], Optional[str]]: + """The command line: run ``command`` in the remote folder ``cwd``. + + Over ssh it is `colab ssh -- sh -c`; otherwise `colab exec` gets Python + code on stdin, so it works without an SSH key. Returns (argv, stdin). + """ + folder = "/" + cwd.strip("/") + if via == "ssh": + return ["ssh", "-s", session, "--", "sh", "-c", f"cd {shlex.quote(folder)} && {command}"], None + code = ( + "import subprocess, sys\n" + f"r = subprocess.run({command!r}, shell=True, cwd={folder!r}, capture_output=True, text=True)\n" + "sys.stdout.write(r.stdout + r.stderr)\n" + "print(f'[exit {r.returncode}]')\n" + ) + return ["exec", "-s", session], code + + +def parse_listing(text: str) -> List[dict]: + """The items of `colab ls --json` output; raises ValueError with its error.""" + for line in reversed(text.splitlines()): + line = line.strip() + if line.startswith("{"): + data = json.loads(line) + if "error" in data: + raise ValueError(data["error"]) + return data.get("items") or [] + raise ValueError(text.strip().splitlines()[-1] if text.strip() else "no output") + + +def human_size(size: Optional[int]) -> str: + if size is None: + return "" + value = float(size) + for unit in ("B", "KB", "MB", "GB"): + if value < 1024 or unit == "GB": + return f"{int(value)} B" if unit == "B" else f"{value:.1f} {unit}" + value /= 1024 + return "" diff --git a/src/colab_cli/tray/files.py b/src/colab_cli/tray/files.py new file mode 100644 index 0000000..809027a --- /dev/null +++ b/src/colab_cli/tray/files.py @@ -0,0 +1,501 @@ +# 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 two-pane file manager for one runtime (docs/09), in the style of +Total Commander: this computer on the left, the runtime on the right. + +Drag and drop or F5 copies between the panes, F7 makes a folder, F8 deletes +(a local file goes to the recycle bin), Enter opens, Backspace goes up, and +the line at the bottom runs a command in the runtime's folder. Every action +runs one of the CLI's own subcommands (file_ops), one after the other; the +transfer goes over the contents API or over ssh (scp), as chosen at the top. +""" + +import codecs +import json +import os +from typing import Callable, List, Optional + +from PySide6.QtCore import QDir, QMimeData, QProcess, QProcessEnvironment, Qt, QUrl +from PySide6.QtGui import QDesktopServices, QFont, QFontDatabase, QKeySequence, QShortcut +from PySide6.QtWidgets import ( + QComboBox, + QFileSystemModel, + QHBoxLayout, + QInputDialog, + QLabel, + QLineEdit, + QMessageBox, + QPlainTextEdit, + QPushButton, + QSplitter, + QTreeView, + QTreeWidget, + QTreeWidgetItem, + QVBoxLayout, + QWidget, +) + +from colab_cli.tray import file_ops +from colab_cli.tray.glyphs import icon as glyph_icon +from colab_cli.tray.i18n import t +from colab_cli.tray.windows import WINDOW_QSS + +REMOTE_MIME = "application/x-colab-remote-paths" +REMOTE_ROOT = "content" + +Run = Callable[[List[str], Optional[str], str, Callable[[int, str], None]], None] + + +class _RemoteTree(QTreeWidget): + """The runtime's folder: drags out its paths, takes local files dropped in.""" + + def __init__(self, owner: "FileManager"): + super().__init__() + self.owner = owner + self.setDragEnabled(True) + self.setAcceptDrops(True) + self.setDropIndicatorShown(True) + self.setSelectionMode(QTreeWidget.ExtendedSelection) + self.setRootIsDecorated(False) + + def mimeTypes(self): + return [REMOTE_MIME] + + def mimeData(self, items): + data = QMimeData() + data.setData(REMOTE_MIME, json.dumps(self.owner.remote_entries(items)).encode("utf-8")) + return data + + def _local_paths(self, event) -> List[str]: + if not event.mimeData().hasUrls(): + return [] + return [u.toLocalFile() for u in event.mimeData().urls() if u.isLocalFile()] + + def dragEnterEvent(self, event): + if self._local_paths(event): + event.acceptProposedAction() + else: + event.ignore() + + def dragMoveEvent(self, event): + if self._local_paths(event): + event.acceptProposedAction() + else: + event.ignore() + + def dropEvent(self, event): + paths = self._local_paths(event) + if not paths: + event.ignore() + return + item = self.itemAt(event.position().toPoint()) + target = self.owner.remote_dir + if item is not None and item.data(0, Qt.UserRole + 1) and item.text(0) != "..": + target = item.data(0, Qt.UserRole) + event.acceptProposedAction() + self.owner.upload(paths, target) + + +class _LocalView(QTreeView): + """This computer's folder: drags out file URLs, takes the runtime's paths.""" + + def __init__(self, owner: "FileManager"): + super().__init__() + self.owner = owner + self.setDragEnabled(True) + self.setAcceptDrops(True) + self.setDropIndicatorShown(True) + self.setDragDropMode(QTreeView.DragDrop) + self.setSelectionMode(QTreeView.ExtendedSelection) + self.setRootIsDecorated(False) + self.setItemsExpandable(False) + + def dragEnterEvent(self, event): + if event.mimeData().hasFormat(REMOTE_MIME): + event.acceptProposedAction() + else: + event.ignore() + + def dragMoveEvent(self, event): + if event.mimeData().hasFormat(REMOTE_MIME): + event.acceptProposedAction() + else: + event.ignore() + + def dropEvent(self, event): + if not event.mimeData().hasFormat(REMOTE_MIME): + event.ignore() + return + entries = json.loads(bytes(event.mimeData().data(REMOTE_MIME)).decode("utf-8")) + index = self.indexAt(event.position().toPoint()) + target = self.owner.local_dir + if index.isValid() and self.owner.local_model.isDir(index): + target = self.owner.local_model.filePath(index) + event.acceptProposedAction() + self.owner.download(entries, target) + + +class FileManager(QWidget): + def __init__(self, session: str, lang: str, base_argv: List[str], settings_store=None, + run: Optional[Run] = None, start_dir: Optional[str] = None): + super().__init__(None, Qt.Window) + self.session, self.lang, self.base_argv = session, lang, base_argv + self.settings_store = settings_store + self.run = run or self._run_process + self.queue: List[tuple] = [] + self.proc: Optional[QProcess] = None + self.remote_dir = REMOTE_ROOT + self.local_dir = start_dir or os.path.expanduser("~") + self.active = "remote" + self.setObjectName("window") + self.setStyleSheet(WINDOW_QSS) + self.setWindowTitle(t(lang, "files.title", session=session)) + self.resize(1100, 680) + box = QVBoxLayout(self) + + top = QHBoxLayout() + top.addWidget(QLabel(t(lang, "files.via"))) + self.via = QComboBox() + self.via.addItem(t(lang, "files.via_contents"), "contents") + self.via.addItem(t(lang, "files.via_ssh"), "ssh") + self.via.setCurrentIndex(max(0, self.via.findData(self._saved_via()))) + self.via.currentIndexChanged.connect(self._save_via) + top.addWidget(self.via) + top.addStretch() + refresh = QPushButton(t(lang, "log.refresh")) + refresh.setIcon(glyph_icon("refresh", "#e8eaed")) + refresh.clicked.connect(self.refresh_remote) + top.addWidget(refresh) + box.addLayout(top) + + split = QSplitter(Qt.Horizontal) + self.local_path = QLineEdit(self.local_dir) + self.local_path.returnPressed.connect(lambda: self.open_local(self.local_path.text())) + self.local_model = QFileSystemModel(self) + self.local_model.setRootPath("") + self.local_model.setReadOnly(True) + self.local_model.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot | QDir.AllDirs) + self.local_view = _LocalView(self) + self.local_view.setModel(self.local_model) + self.local_view.setColumnWidth(0, 260) + self.local_view.activated.connect(self._local_activated) + self.drives = QComboBox() + self.drives.addItems([QDir.toNativeSeparators(d.absolutePath()) for d in QDir.drives()]) + self.drives.setToolTip(t(lang, "files.drive")) + self.drives.textActivated.connect(self.open_local) + split.addWidget(self._pane(t(lang, "files.local"), self.local_path, self.local_view, + self._local_up, lead=self.drives)) + + self.remote_path = QLineEdit(self.remote_dir) + self.remote_path.returnPressed.connect(lambda: self.open_remote(self.remote_path.text().strip("/"))) + self.remote = _RemoteTree(self) + self.remote.setHeaderLabels([t(lang, "files.name"), t(lang, "files.size"), t(lang, "files.modified")]) + self.remote.setColumnWidth(0, 280) + self.remote.itemActivated.connect(lambda item, _c: self._remote_activated(item)) + split.addWidget(self._pane(t(lang, "files.remote", session=session), self.remote_path, self.remote, + self._remote_up)) + box.addWidget(split, 3) + + bar = QHBoxLayout() + self.buttons = {} + for key, slot in (("files.upload", self.upload_selected), ("files.download", self.download_selected), + ("files.mkdir", self.make_folder), ("files.delete", self.delete_selected)): + button = QPushButton(t(lang, key)) + button.clicked.connect(slot) + bar.addWidget(button, 1) + self.buttons[key] = button + box.addLayout(bar) + box.addWidget(QLabel(t(lang, "files.keys"), objectName="muted")) + cmd_row = QHBoxLayout() + self.prompt = QLabel() + cmd_row.addWidget(self.prompt) + self.command = QLineEdit(placeholderText=t(lang, "files.command_hint")) + self.command.returnPressed.connect(self.run_command) + cmd_row.addWidget(self.command, 1) + box.addLayout(cmd_row) + self.output = QPlainTextEdit(objectName="log", readOnly=True) + self.output.setMaximumBlockCount(5000) + fixed = QFontDatabase.systemFont(QFontDatabase.FixedFont) + self.output.setFont(QFont(fixed.family(), 10)) + box.addWidget(self.output, 1) + self.status = QLabel(objectName="muted") + box.addWidget(self.status) + + for key, slot in ((Qt.Key_F5, self.copy_selected), (Qt.Key_F7, self.make_folder), + (Qt.Key_F8, self.delete_selected)): + QShortcut(QKeySequence(key), self, slot) + # Enter and double-click arrive as `activated`; Backspace goes up. + for view, up in ((self.local_view, self._local_up), (self.remote, self._remote_up)): + QShortcut(QKeySequence(Qt.Key_Backspace), view, up, context=Qt.WidgetShortcut) + self.local_view.installEventFilter(self) + self.remote.installEventFilter(self) + + self.open_local(self.local_dir) + self.open_remote(REMOTE_ROOT) + + def _pane(self, title: str, path: QLineEdit, view: QWidget, up: Callable[[], None], + lead: Optional[QWidget] = None) -> QWidget: + pane = QWidget() + lay = QVBoxLayout(pane) + lay.setContentsMargins(0, 0, 0, 0) + lay.addWidget(QLabel(title, objectName="helptitle")) + row = QHBoxLayout() + if lead is not None: + row.addWidget(lead) + row.addWidget(path, 1) + button = QPushButton("⬆ ..") + button.setToolTip(t(self.lang, "files.up")) + button.clicked.connect(up) + row.addWidget(button) + lay.addLayout(row) + lay.addWidget(view, 1) + return pane + + def eventFilter(self, obj, event): + if event.type() == event.Type.FocusIn: + self.active = "local" if obj is self.local_view else "remote" + return False + + # --- settings --- + + def _saved_via(self) -> str: + try: + return self.settings_store.load().tray_transfer + except Exception: + return "contents" + + def _save_via(self) -> None: + if self.settings_store is None: + return + try: + settings = self.settings_store.load() + settings.tray_transfer = self.via.currentData() + self.settings_store.save(settings) + except Exception: + pass + + # --- running CLI commands, one at a time --- + + def submit(self, argv: List[str], label: str, done: Optional[Callable[[int, str], None]] = None, + stdin: Optional[str] = None) -> None: + self.run(argv, stdin, label, done or (lambda code, out: None)) + + def _run_process(self, argv, stdin, label, done) -> None: + self.queue.append((argv, stdin, label, done)) + if self.proc is None: + self._next() + + def _next(self) -> None: + if not self.queue: + self.proc = None + self.status.setText(t(self.lang, "files.idle")) + return + argv, stdin, label, done = self.queue.pop(0) + self.status.setText(t(self.lang, "files.running", what=label, left=len(self.queue))) + proc = QProcess(self) + env = QProcessEnvironment.systemEnvironment() + for k, v in (("NO_COLOR", "1"), ("PYTHONIOENCODING", "utf-8"), ("TERM", "dumb")): + env.insert(k, v) + proc.setProcessEnvironment(env) + proc.setProcessChannelMode(QProcess.MergedChannels) + decoder = codecs.getincrementaldecoder("utf-8")("replace") + chunks: List[str] = [] + proc.readyReadStandardOutput.connect(lambda: chunks.append(decoder.decode(bytes(proc.readAllStandardOutput())))) + + def finished(code, _status=None): + chunks.append(decoder.decode(b"", final=True)) + try: + done(code, "".join(chunks)) + finally: + proc.deleteLater() + self._next() + + proc.finished.connect(finished) + self.proc = proc + full = [*self.base_argv, *argv] + proc.start(full[0], full[1:]) + if stdin is not None: + proc.write(stdin.encode("utf-8")) + proc.closeWriteChannel() + + def log(self, text: str) -> None: + self.output.appendPlainText(text.rstrip("\n")) + + # --- the remote pane --- + + def open_remote(self, path: str) -> None: + self.remote_dir = path + self.remote_path.setText(path) + self.prompt.setText(f"/{path}$") + self.submit(file_ops.ls_argv(self.session, path), t(self.lang, "files.listing", path=path), + lambda code, out, p=path: self._fill_remote(p, code, out)) + + def refresh_remote(self) -> None: + self.open_remote(self.remote_dir) + + def _fill_remote(self, path: str, code: int, out: str) -> None: + if path != self.remote_dir: + return + try: + items = file_ops.parse_listing(out) + except ValueError as e: + self.log(f"[{path}] {e}") + return + self.remote.clear() + if path: + self._add_remote_item("..", file_ops.remote_parent(path), True, None, None) + for item in items: + is_dir = item.get("type") == "directory" + self._add_remote_item(item["name"], file_ops.remote_join(path, item["name"]), is_dir, + item.get("size"), item.get("last_modified")) + + def _add_remote_item(self, name, full, is_dir, size, modified) -> None: + row = QTreeWidgetItem([name + ("/" if is_dir and name != ".." else ""), + "" if is_dir else file_ops.human_size(size), + (modified or "")[:19].replace("T", " ")]) + row.setData(0, Qt.UserRole, full) + row.setData(0, Qt.UserRole + 1, is_dir) + self.remote.addTopLevelItem(row) + + def remote_entries(self, items) -> List[dict]: + return [{"path": i.data(0, Qt.UserRole), "dir": bool(i.data(0, Qt.UserRole + 1))} + for i in items if i.text(0) != ".."] + + def _remote_activated(self, item) -> None: + if item.data(0, Qt.UserRole + 1): + self.open_remote(item.data(0, Qt.UserRole)) + + def _remote_up(self) -> None: + if self.remote_dir: + self.open_remote(file_ops.remote_parent(self.remote_dir)) + + # --- the local pane --- + + def open_local(self, path: str) -> None: + if not os.path.isdir(path): + self.log(t(self.lang, "files.no_folder", path=path)) + return + self.local_dir = os.path.abspath(path) + self.local_path.setText(self.local_dir) + self.local_view.setRootIndex(self.local_model.index(self.local_dir)) + drive = os.path.splitdrive(self.local_dir)[0] + for i in range(self.drives.count()): + if drive and self.drives.itemText(i).upper().startswith(drive.upper()): + self.drives.setCurrentIndex(i) + + def _local_activated(self, index) -> None: + path = self.local_model.filePath(index) + if self.local_model.isDir(index): + self.open_local(path) + else: + QDesktopServices.openUrl(QUrl.fromLocalFile(path)) + + def _local_up(self) -> None: + parent = os.path.dirname(self.local_dir.rstrip("/\\")) + if parent and parent != self.local_dir: + self.open_local(parent) + + def local_selection(self) -> List[str]: + rows = self.local_view.selectionModel().selectedRows() if self.local_view.selectionModel() else [] + return [self.local_model.filePath(i) for i in rows] + + # --- actions --- + + def upload(self, paths: List[str], target: str) -> None: + via = self.via.currentData() + for path in paths: + argv = file_ops.copy_argv(self.session, path, target, upload=True, is_dir=os.path.isdir(path), via=via) + self.submit(argv, t(self.lang, "files.uploading", name=os.path.basename(path.rstrip("/\\"))), + self._after_transfer) + + def download(self, entries: List[dict], target: str) -> None: + via = self.via.currentData() + for entry in entries: + argv = file_ops.copy_argv(self.session, entry["path"], target, upload=False, is_dir=entry["dir"], via=via) + self.submit(argv, t(self.lang, "files.downloading", name=entry["path"].rsplit("/", 1)[-1]), + self._after_transfer) + + def _after_transfer(self, code: int, out: str) -> None: + self.log(out) + self.refresh_remote() + + def upload_selected(self) -> None: + paths = self.local_selection() + if not paths: + self.status.setText(t(self.lang, "files.select_local")) + return + self.upload(paths, self.remote_dir) + + def download_selected(self) -> None: + entries = self.remote_entries(self.remote.selectedItems()) + if not entries: + self.status.setText(t(self.lang, "files.select_remote")) + return + self.download(entries, self.local_dir) + + def copy_selected(self) -> None: + if self.active == "local": + self.upload(self.local_selection(), self.remote_dir) + else: + self.download(self.remote_entries(self.remote.selectedItems()), self.local_dir) + + def make_folder(self) -> None: + name, ok = QInputDialog.getText(self, t(self.lang, "files.mkdir_title"), t(self.lang, "files.mkdir_prompt")) + name = name.strip().strip("/\\") + if not ok or not name: + return + if self.active == "local": + os.makedirs(os.path.join(self.local_dir, name), exist_ok=True) + else: + self.submit(file_ops.mkdir_argv(self.session, file_ops.remote_join(self.remote_dir, name)), + t(self.lang, "files.mkdir_title"), self._after_transfer) + + def confirm(self, text: str) -> bool: + box = QMessageBox(QMessageBox.Question, t(self.lang, "files.delete_title"), text, + QMessageBox.Yes | QMessageBox.Cancel, self) + return box.exec() == QMessageBox.Yes + + def delete_selected(self) -> None: + if self.active == "local": + paths = self.local_selection() + if paths and self.confirm(t(self.lang, "files.delete_local", names=", ".join(map(os.path.basename, paths)))): + from PySide6.QtCore import QFile + + for path in paths: + if not QFile.moveToTrash(path): + self.log(t(self.lang, "files.trash_failed", path=path)) + return + entries = self.remote_entries(self.remote.selectedItems()) + names = ", ".join(e["path"].rsplit("/", 1)[-1] for e in entries) + if entries and self.confirm(t(self.lang, "files.delete_remote", names=names)): + for entry in entries: + self.submit(file_ops.rm_argv(self.session, entry["path"], is_dir=entry["dir"]), + t(self.lang, "files.deleting", name=entry["path"]), self._after_transfer) + + def run_command(self) -> None: + text = self.command.text().strip() + if not text: + return + self.command.clear() + self.log(f"/{self.remote_dir}$ {text}") + argv, stdin = file_ops.command_argv(self.session, self.remote_dir, text, via=self.via.currentData()) + self.submit(argv, text, self._after_transfer, stdin=stdin) + + def closeEvent(self, event): + self.queue.clear() + if self.proc is not None and self.proc.state() != QProcess.NotRunning: + self.proc.kill() + self.proc.waitForFinished(3000) + super().closeEvent(event) diff --git a/src/colab_cli/tray/glyphs.py b/src/colab_cli/tray/glyphs.py index e17c895..450e35b 100644 --- a/src/colab_cli/tray/glyphs.py +++ b/src/colab_cli/tray/glyphs.py @@ -49,6 +49,7 @@ def _cog() -> str: "chevron_right": '', "chevron_down": '', "plus": '', + "folder": '', "check": '', "quit": '', } diff --git a/src/colab_cli/tray/i18n.py b/src/colab_cli/tray/i18n.py index bf2e8f9..e1603da 100644 --- a/src/colab_cli/tray/i18n.py +++ b/src/colab_cli/tray/i18n.py @@ -453,3 +453,75 @@ def hardware_label(hw: str) -> str: "log.help_session": "Amit ez a CLI a(z) {name} gépen futtatott: parancsok, kód és kimenetek a helyi előzményekből (a legújabb alul). Egy szerver saját naplója a gépen van, pl. colab ssh -s {name} -- tail -f /content/server.log", "log.ended": "[vége, kilépési kód: {code}]", }) +STRINGS["en"].update({ + "files": "Files", + "files.title": "Files – {session}", + "files.local": "This computer", + "files.remote": "Colab runtime: {session}", + "files.via": "Transfer:", + "files.via_contents": "Contents API (no key needed)", + "files.via_ssh": "SSH / scp (faster for big files, needs an SSH key)", + "files.name": "Name", + "files.size": "Size", + "files.modified": "Modified", + "files.keys": "Drag between the panes or F5 Copy · F7 New folder · F8 Delete · Enter Open · Backspace Up · the line below runs a command in the runtime's folder", + "files.command_hint": "Command to run in this folder on the runtime, e.g. ls -la", + "files.idle": "Ready.", + "files.running": "Running: {what} ({left} waiting)", + "files.listing": "listing {path}", + "files.uploading": "uploading {name}", + "files.downloading": "downloading {name}", + "files.deleting": "deleting {name}", + "files.mkdir_title": "New folder", + "files.mkdir_prompt": "Name of the new folder:", + "files.delete_title": "Delete", + "files.delete_local": "Move to the recycle bin: {names}?", + "files.delete_remote": "Delete from the runtime, for good: {names}?", + "files.trash_failed": "Could not move to the recycle bin: {path}", + "files.no_folder": "Not a folder: {path}", +}) +STRINGS["hu"].update({ + "files": "Fájlok", + "files.title": "Fájlok – {session}", + "files.local": "Ez a gép", + "files.remote": "Colab-gép: {session}", + "files.via": "Átvitel:", + "files.via_contents": "Contents API (nem kell kulcs)", + "files.via_ssh": "SSH / scp (nagy fájlokra gyorsabb, SSH-kulcs kell)", + "files.name": "Név", + "files.size": "Méret", + "files.modified": "Módosítva", + "files.keys": "Húzd át a fájlokat a panelek között, vagy F5 Másolás · F7 Új mappa · F8 Törlés · Enter Megnyitás · Backspace Fel · a lenti sor parancsot futtat a gép mappájában", + "files.command_hint": "Parancs a gépen, ebben a mappában, pl. ls -la", + "files.idle": "Kész.", + "files.running": "Fut: {what} (még {left} vár)", + "files.listing": "{path} listázása", + "files.uploading": "{name} feltöltése", + "files.downloading": "{name} letöltése", + "files.deleting": "{name} törlése", + "files.mkdir_title": "Új mappa", + "files.mkdir_prompt": "Az új mappa neve:", + "files.delete_title": "Törlés", + "files.delete_local": "Lomtárba helyezed: {names}?", + "files.delete_remote": "Végleg törlöd a gépről: {names}?", + "files.trash_failed": "Nem sikerült a lomtárba tenni: {path}", + "files.no_folder": "Nem mappa: {path}", +}) +STRINGS["en"].update({"files.drive": "Drive", "files.up": "Up one folder (Backspace)"}) +STRINGS["hu"].update({"files.drive": "Meghajtó", "files.up": "Egy mappával feljebb (Backspace)"}) +STRINGS["en"].update({ + "files.upload": "Upload ➜", + "files.download": "⬅ Download", + "files.mkdir": "F7 New folder", + "files.delete": "F8 Delete", + "files.select_local": "Select files or folders on the left to upload.", + "files.select_remote": "Select files or folders on the right to download.", +}) +STRINGS["hu"].update({ + "files.upload": "Feltöltés ➜", + "files.download": "⬅ Letöltés", + "files.mkdir": "F7 Új mappa", + "files.delete": "F8 Törlés", + "files.select_local": "Jelölj ki fájlt vagy mappát a bal oldalon a feltöltéshez.", + "files.select_remote": "Jelölj ki fájlt vagy mappát a jobb oldalon a letöltéshez.", +}) diff --git a/src/colab_cli/tray/panel.py b/src/colab_cli/tray/panel.py index 2e326bd..15e1701 100644 --- a/src/colab_cli/tray/panel.py +++ b/src/colab_cli/tray/panel.py @@ -139,6 +139,7 @@ class Panel(QWidget): open_clicked = Signal(dict) stop_clicked = Signal(dict) attach_clicked = Signal(dict) + files_clicked = Signal(dict) profile_clicked = Signal(str) refresh_clicked = Signal() settings_clicked = Signal() @@ -388,7 +389,8 @@ def _card(self, item, lang) -> QFrame: 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)): + for key, glyph, signal in (("log", "log", self.log_clicked), ("ssh", "terminal", self.ssh_clicked), + ("files", "folder", self.files_clicked)): if not card["local"]: break b = QPushButton(t(lang, key), objectName="action") diff --git a/tests/test_tray_file_ops.py b/tests/test_tray_file_ops.py new file mode 100644 index 0000000..54755ee --- /dev/null +++ b/tests/test_tray_file_ops.py @@ -0,0 +1,81 @@ +# 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. + + +"""The file manager's actions as CLI argv (no Qt).""" + +import json +import os + +import pytest + +from colab_cli.tray import file_ops as f + + +def test_ls_argv(): + assert f.ls_argv("s1", "content/data") == ["ls", "-s", "s1", "--json", "content/data"] + + +def test_copy_argv_upload_a_folder_into_the_remote_folder(): + argv = f.copy_argv("s1", os.path.join("C:", "work", "data"), "content", upload=True, is_dir=True, via="contents") + assert argv == ["upload", "-s", "s1", "-r", "--via", "contents", os.path.join("C:", "work", "data"), "content/data"] + + +def test_copy_argv_download_a_file_over_ssh(tmp_path): + argv = f.copy_argv("s1", "content/out/model.pt", str(tmp_path), upload=False, is_dir=False, via="ssh") + assert argv == ["download", "-s", "s1", "--via", "ssh", "content/out/model.pt", os.path.join(str(tmp_path), "model.pt")] + + +def test_mkdir_and_rm_argv(): + assert f.mkdir_argv("s1", "content/new") == ["mkdir", "-s", "s1", "content/new"] + assert f.rm_argv("s1", "content/x.txt", is_dir=False) == ["rm", "-s", "s1", "content/x.txt"] + assert f.rm_argv("s1", "content/d", is_dir=True) == ["rm", "-s", "s1", "-r", "content/d"] + + +def test_remote_paths(): + assert f.remote_join("", "content") == "content" + assert f.remote_join("content", "a b") == "content/a b" + assert f.remote_parent("content/data/") == "content" + assert f.remote_parent("content") == "" + + +def test_command_over_ssh_runs_in_the_folder(): + argv, stdin = f.command_argv("s1", "content/my dir", "ls -la", via="ssh") + assert argv == ["ssh", "-s", "s1", "--", "sh", "-c", "cd '/content/my dir' && ls -la"] + assert stdin is None + + +def test_command_over_contents_runs_through_exec(): + argv, stdin = f.command_argv("s1", "content", "echo 'hi' $HOME", via="contents") + assert argv == ["exec", "-s", "s1"] + assert "'/content'" in stdin and repr("echo 'hi' $HOME") in stdin + compile(stdin, "", "exec") + + +def test_parse_listing_takes_the_json_line(): + payload = {"path": "content", "items": [{"name": "a", "type": "file", "size": 1, "last_modified": None}]} + text = "\n[colab] some notice\n" + json.dumps(payload) + "\n" + assert f.parse_listing(text) == payload["items"] + + +def test_parse_listing_errors(): + with pytest.raises(ValueError, match="not found"): + f.parse_listing(json.dumps({"path": "x", "error": "File or directory not found: x"})) + with pytest.raises(ValueError): + f.parse_listing("Traceback ...") + + +@pytest.mark.parametrize("size,text", [(None, ""), (0, "0 B"), (999, "999 B"), (2048, "2.0 KB"), (5 * 1024**3, "5.0 GB")]) +def test_human_size(size, text): + assert f.human_size(size) == text diff --git a/tests/test_tray_files.py b/tests/test_tray_files.py new file mode 100644 index 0000000..39fb6b1 --- /dev/null +++ b/tests/test_tray_files.py @@ -0,0 +1,205 @@ +# 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. + + +"""The tray's file manager window, on Qt's offscreen platform (docs/09).""" + +import json +import os + +os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") + +from unittest.mock import MagicMock # noqa: E402 + +import pytest # noqa: E402 + +try: + from PySide6.QtCore import QMimeData, QPointF, Qt, QUrl # noqa: E402 + from PySide6.QtGui import QDropEvent # noqa: E402 + from PySide6.QtWidgets import QApplication # noqa: E402 + + from colab_cli.tray import files as files_mod # noqa: E402 +except ImportError as e: + pytest.skip(f"Qt is not usable here: {e}", allow_module_level=True) + +from colab_cli.state import Settings # noqa: E402 + +LISTING = {"path": "content", "items": [ + {"name": "data", "type": "directory", "size": None, "last_modified": "2026-11-20T01:02:03Z"}, + {"name": "model.pt", "type": "file", "size": 2048, "last_modified": "2026-11-20T04:05:06Z"}, +]} + + +@pytest.fixture(scope="module") +def qapp(): + return QApplication.instance() or QApplication([]) + + +@pytest.fixture +def fm(qapp, tmp_path): + calls = [] + + def run(argv, stdin, label, done): + calls.append({"argv": argv, "stdin": stdin, "done": done}) + + store = MagicMock() + store.load.return_value = Settings() + (tmp_path / "local.txt").write_text("hi") + window = files_mod.FileManager("s1", "hu", ["colab"], settings_store=store, run=run, start_dir=str(tmp_path)) + window.calls = calls + window.store = store + yield window + window.close() + window.deleteLater() + + +def _answer_listing(fm, listing=LISTING): + fm.calls[-1]["done"](0, "[colab] notice\n" + json.dumps(listing) + "\n") + + +def _rows(fm): + return [fm.remote.topLevelItem(i).text(0) for i in range(fm.remote.topLevelItemCount())] + + +def test_opens_on_content_and_lists_it(fm): + assert fm.calls[0]["argv"] == ["ls", "-s", "s1", "--json", "content"] + _answer_listing(fm) + assert _rows(fm) == ["..", "data/", "model.pt"] + assert fm.remote.topLevelItem(2).text(1) == "2.0 KB" + + +def test_entering_a_remote_folder_lists_it(fm): + _answer_listing(fm) + fm._remote_activated(fm.remote.topLevelItem(1)) + assert fm.calls[-1]["argv"] == ["ls", "-s", "s1", "--json", "content/data"] + assert fm.prompt.text() == "/content/data$" + + +def test_f5_from_the_remote_pane_downloads_into_the_local_folder(fm, tmp_path): + _answer_listing(fm) + fm.active = "remote" + fm.remote.topLevelItem(2).setSelected(True) + fm.copy_selected() + assert fm.calls[-1]["argv"] == [ + "download", "-s", "s1", "--via", "contents", "content/model.pt", os.path.join(str(tmp_path), "model.pt"), + ] + + +def test_ssh_transfer_is_remembered_and_used(fm, tmp_path): + _answer_listing(fm) + fm.via.setCurrentIndex(fm.via.findData("ssh")) + assert fm.store.save.call_args.args[0].tray_transfer == "ssh" + fm.upload([str(tmp_path / "local.txt")], "content") + assert fm.calls[-1]["argv"][:4] == ["upload", "-s", "s1", "--via"] + assert fm.calls[-1]["argv"][4] == "ssh" + + +def test_dropping_local_files_on_the_remote_pane_uploads_them(fm, tmp_path): + _answer_listing(fm) + mime = QMimeData() + mime.setUrls([QUrl.fromLocalFile(str(tmp_path / "local.txt"))]) + event = QDropEvent(QPointF(1, 1), Qt.CopyAction, mime, Qt.LeftButton, Qt.NoModifier) + fm.remote.dropEvent(event) + argv = fm.calls[-1]["argv"] + assert argv[:5] == ["upload", "-s", "s1", "--via", "contents"] + assert os.path.normpath(argv[5]) == os.path.normpath(str(tmp_path / "local.txt")) + assert argv[6] == "content/local.txt" + + +def test_dragging_remote_items_carries_their_paths_to_the_local_pane(fm, tmp_path): + _answer_listing(fm) + mime = fm.remote.mimeData([fm.remote.topLevelItem(1), fm.remote.topLevelItem(2)]) + entries = json.loads(bytes(mime.data(files_mod.REMOTE_MIME)).decode()) + assert entries == [{"path": "content/data", "dir": True}, {"path": "content/model.pt", "dir": False}] + event = QDropEvent(QPointF(-5, -5), Qt.CopyAction, mime, Qt.LeftButton, Qt.NoModifier) + fm.local_view.dropEvent(event) + assert fm.calls[-2]["argv"][:4] == ["download", "-s", "s1", "-r"] + assert fm.calls[-1]["argv"][-1] == os.path.join(str(tmp_path), "model.pt") + + +def test_f8_deletes_a_remote_folder_after_asking(fm, mocker): + _answer_listing(fm) + fm.active = "remote" + fm.remote.topLevelItem(1).setSelected(True) + mocker.patch.object(fm, "confirm", return_value=True) + fm.delete_selected() + assert fm.calls[-1]["argv"] == ["rm", "-s", "s1", "-r", "content/data"] + + +def test_f8_cancelled_deletes_nothing(fm, mocker): + _answer_listing(fm) + fm.active = "remote" + fm.remote.topLevelItem(2).setSelected(True) + before = len(fm.calls) + mocker.patch.object(fm, "confirm", return_value=False) + fm.delete_selected() + assert len(fm.calls) == before + + +def test_command_line_runs_in_the_remote_folder(fm): + _answer_listing(fm) + fm.command.setText("ls -la") + fm.run_command() + assert fm.calls[-1]["argv"] == ["exec", "-s", "s1"] + assert "'/content'" in fm.calls[-1]["stdin"] + fm.via.setCurrentIndex(fm.via.findData("ssh")) + fm.command.setText("du -sh .") + fm.run_command() + assert fm.calls[-1]["argv"] == ["ssh", "-s", "s1", "--", "sh", "-c", "cd /content && du -sh ."] + + +def test_a_listing_error_is_shown_not_raised(fm): + fm.calls[-1]["done"](1, json.dumps({"path": "content", "error": "File or directory not found: content"})) + assert "not found" in fm.output.toPlainText() + + +def test_local_folders_open_with_enter_or_double_click_and_go_up(fm, tmp_path): + (tmp_path / "inner").mkdir() + index = fm.local_model.index(str(tmp_path / "inner")) + fm.local_view.activated.emit(index) + assert fm.local_dir == str(tmp_path / "inner") + fm._local_up() + assert fm.local_dir == str(tmp_path) + + +def test_the_drive_list_opens_a_drive(fm): + assert fm.drives.count() >= 1 + first = fm.drives.itemText(0) + fm.drives.textActivated.emit(first) + assert os.path.normcase(fm.local_dir) == os.path.normcase(os.path.abspath(first)) + + +def test_remote_folders_open_on_activation(fm): + _answer_listing(fm) + fm.remote.itemActivated.emit(fm.remote.topLevelItem(1), 0) + assert fm.calls[-1]["argv"] == ["ls", "-s", "s1", "--json", "content/data"] + + +def test_upload_and_download_buttons(fm, tmp_path): + _answer_listing(fm) + before = len(fm.calls) + fm.buttons["files.upload"].click() + assert len(fm.calls) == before and "bal oldalon" in fm.status.text() + + fm.local_view.selectionModel().select( + fm.local_model.index(str(tmp_path / "local.txt")), + fm.local_view.selectionModel().SelectionFlag.Select | fm.local_view.selectionModel().SelectionFlag.Rows, + ) + fm.buttons["files.upload"].click() + assert fm.calls[-1]["argv"][0] == "upload" and fm.calls[-1]["argv"][-1] == "content/local.txt" + + fm.remote.topLevelItem(2).setSelected(True) + fm.buttons["files.download"].click() + assert fm.calls[-1]["argv"][0] == "download" + assert fm.calls[-1]["argv"][-1] == os.path.join(str(tmp_path), "model.pt") diff --git a/tests/test_tray_panel.py b/tests/test_tray_panel.py index be12fc6..65e2c46 100644 --- a/tests/test_tray_panel.py +++ b/tests/test_tray_panel.py @@ -115,7 +115,7 @@ def test_one_card_as_in_the_design(tray): assert "2 / 5 epoch · kb. 12 perc hátra" in texts assert tray.panel.cards[0].findChildren(QProgressBar)[0].value() == 450 buttons = [b.text() for b in tray.panel.cards[0].findChildren(QPushButton)] - assert buttons == ["Napló", "SSH", "Leállítás"] + assert buttons == ["Napló", "SSH", "Fájlok", "Leállítás"] assert tray.panel.count_badge.text() == "1 aktív" assert tray.panel.status_text.text() == "Kapcsolódva" assert "Becsült hátralévő idő" in tray.panel.cu_estimate.text() @@ -228,7 +228,7 @@ def test_start_profile_after_confirmation(tray, tmp_path, mocker): # The running kernel profile is a service with an Open button. _render(tray, [_entry("ui", None, profile="ui")]) assert [b.text() for b in tray.panel.cards[0].findChildren(QPushButton)] == [ - "Napló", "SSH", "Megnyitás", "Leállítás"] + "Napló", "SSH", "Fájlok", "Megnyitás", "Leállítás"] def test_declined_profile_does_not_start(tray, tmp_path, mocker): @@ -310,7 +310,7 @@ def test_a_forwarded_runtime_gets_an_open_button(tray, mocker): view = _render(tray, [entry]) card = tray.panel.cards[0] - assert [b.text() for b in card.findChildren(QPushButton)] == ["Napló", "SSH", "Megnyitás", "Leállítás"] + assert [b.text() for b in card.findChildren(QPushButton)] == ["Napló", "SSH", "Fájlok", "Megnyitás", "Leállítás"] assert "továbbítás: 8188" in [w.text() for w in card.findChildren(QLabel)] tray.open_service(view["cards"][0]["card"]) opened.assert_called_once_with("http://127.0.0.1:8188") @@ -391,7 +391,7 @@ def test_a_started_profile_shows_at_once_and_cannot_start_twice(tray, tmp_path, _log(tray, "train", "[colab] Session READY.\n[colab] Started job j-1 (pid 7) on 'train-1113-180000'.\n") _render(tray, [_entry("train-1113-180000", _job())]) [card] = tray.panel.cards - assert [b.text() for b in card.findChildren(QPushButton)] == ["Napló", "SSH", "Leállítás"] + assert [b.text() for b in card.findChildren(QPushButton)] == ["Napló", "SSH", "Fájlok", "Leállítás"] # The run ended: the profile can be started again. tray.popen.return_value.poll.return_value = 0 @@ -416,7 +416,7 @@ def test_a_kernel_profile_shows_its_setup_and_refreshes_sooner(tray, tmp_path, m texts = [w.text() for w in card.findChildren(QLabel)] assert "NVIDIA T4 · Indul" in texts assert any(x.endswith("› Telepítés kész.") for x in texts) - assert [b.text() for b in card.findChildren(QPushButton)] == ["Napló", "SSH", "Leállítás"] + assert [b.text() for b in card.findChildren(QPushButton)] == ["Napló", "SSH", "Fájlok", "Leállítás"] # Started (the script finished): a service again, and no faster refresh. _log(tray, "ui", "[colab] Script finished on 'ui'.\n") From 9257834b434eddb2a4fb0d5f6092571ac2793070 Mon Sep 17 00:00:00 2001 From: "arlinamid\\arlinamid" Date: Fri, 20 Nov 2026 04:05:45 +0100 Subject: [PATCH 3/3] feat(tray): file manager progress, cancel, and a banner when the runtime is gone - Progress: a bar with files done / total, the file being copied and the time. `colab upload/download --progress` prints one line per file (ContentsClient.upload_dir/download_dir take an on_file hook); scp shows a moving bar and the time. - Cancel: stops the running command and drops the waiting ones. The whole process tree is stopped (taskkill /T on Windows, where scp would outlive the CLI; SIGTERM elsewhere, on which `--via ssh` kills scp). The output says what is left for each transfer mode. - When the runtime is gone (the tray's refresh no longer has it, or a command prints "Session not found"), a red banner says so, waiting commands are dropped and the remote side is disabled; the local pane keeps working, and the window comes back if the runtime does. - A failed or cancelled scp warns that the target may be cut short. - docs/09 section 5 documents the window in full; the README has user sections for the file manager and for runtimes from the Colab web UI. Tested live: per-file progress on a 30-file upload; cancel over the contents API (stopped at 7 of 60 files) and over scp (no scp.exe left); the banner after `colab stop` with the window open. Co-Authored-By: Claude Opus 5.5 --- README.md | 27 +++++ docs/03_file_management.md | 1 + docs/09_tray_and_profiles.md | 106 ++++++++++++++++++-- src/colab_cli/commands/files.py | 33 +++++- src/colab_cli/commands/ssh.py | 18 +++- src/colab_cli/contents.py | 25 ++++- src/colab_cli/tray/app.py | 5 + src/colab_cli/tray/file_ops.py | 18 +++- src/colab_cli/tray/files.py | 171 +++++++++++++++++++++++++++++--- src/colab_cli/tray/i18n.py | 34 +++++++ tests/test_files_extras.py | 49 ++++++++- tests/test_tray_file_ops.py | 10 +- tests/test_tray_files.py | 103 ++++++++++++++++++- tests/test_tray_panel.py | 12 +++ 14 files changed, 579 insertions(+), 33 deletions(-) diff --git a/README.md b/README.md index c4d0565..2776119 100644 --- a/README.md +++ b/README.md @@ -273,6 +273,33 @@ Make the script executable (`chmod +x script.py`) and run it: `./script.py`. The --- +### Tray File Manager + +`colab tray` shows a **Files** button on each runtime's card. It opens a two-pane window, like Total Commander: this computer on the left, the runtime's `/content` on the right. + +- **Copy:** drag and drop between the panes (or from Explorer), the **Upload / Download** buttons, or **F5**. **F7** new folder, **F8** delete (local files go to the recycle bin), **Enter** opens, **Backspace** goes up, the drive list switches drives. +- **Transfer:** *Contents API* (no key needed) or *SSH / scp* (faster for big files; needs an SSH key without a passphrase: set `"ssh_identity": "~/.ssh/your_key"` in `~/.config/colab-cli/settings.json` if it is not `~/.ssh/id_ed25519`). +- **Progress and Cancel:** a bar with files done / total and the time; Cancel stops the copy (files already copied stay; with scp the file being copied may be cut short). +- **Command line:** the field at the bottom runs a command in the runtime's current folder. +- If the runtime stops or the connection ends, a red banner says so and only the local pane stays usable. + +Details: [docs/09_tray_and_profiles.md](docs/09_tray_and_profiles.md), section 5. + +### Runtimes Opened in the Colab Web UI + +A runtime you started in the browser shows as `[?]` in `colab sessions`. Attach it to use it from the CLI: + +```bash +colab sessions # [?] m-s-usc1c3-29lht8cq7mkz8 | Hardware: CPU ... +colab attach --endpoint m-s-usc1c3-29lht8cq7mkz8 -s web +colab upload -s web data.csv /content/data.csv +colab upload -s web -r --via ssh ./project /content/project +colab ssh -s web -- ls -la /content +colab stop -s web # stops it in the browser too +``` + +The CLI runs code in its own kernel, not the notebook's, but `/content` is shared, so uploaded files show in the notebook's Files panel at once. In the tray, the card of such a runtime has a **Connect** button that runs `colab attach` for you. To stop one without attaching: `colab stop --endpoint ID`. + ## Deep Dive Documentation For comprehensive architectural overviews and deep-dives into specific CLI sub-systems, refer to the detailed documentation: diff --git a/docs/03_file_management.md b/docs/03_file_management.md index f7cb26a..5300db5 100644 --- a/docs/03_file_management.md +++ b/docs/03_file_management.md @@ -1,5 +1,6 @@ --- log: +2026-11-20: `upload`/`download --progress` prints `[colab] progress DONE/TOTAL PATH` after each file (TOTAL is `?` for a recursive download, which does not count first); the tray's file manager reads it for its progress bar. `upload/download --via ssh` kill their scp when they get SIGTERM, so a cancel does not leave scp copying. 2026-11-20: For the tray's file manager: `colab ls --json` (one object: path, items with name/type/size/last_modified, folders first; an error is JSON too), `colab mkdir`, `colab rm -r` (`ContentsClient.rm_tree`, children first, since the contents API refuses a folder that is not empty), and `--via ssh [-i KEY]` on `upload`/`download`, which copies with OpenSSH scp through `colab ssh --proxy-mode` (`ssh.scp_transfer`) using the default key setting. Tested live on an attached web UI runtime. 2026-11-20: Took upstream PR #267 (`colab upload -r` / `colab download -r`, by Koji Shukawa) before Google merged it, with its review comments applied: no `ntpath` import (a drive-prefixed entry name is still refused on Windows, through `os.path.splitdrive`), simpler `posixpath.join` calls, `_is_local_symlink` so a destination given as `link/` is still seen as a symlink on POSIX, and HTTP errors without the URL (the fork's message, which hides the runtime proxy token). Tested live on a Colab web UI runtime: a tree with subfolders and an empty folder uploaded and downloaded back identical. 2026-11-19: Added `-r`/`--recursive` support to `colab upload` and `colab download` via `ContentsClient.mkdir`, `_ensure_dir`, `upload_dir`, and `download_dir` (preserving empty directories, skipping symlinks on upload, handling single-file `download -r` targets, normalizing remote paths, and enforcing entry-name, canonical local-symlink/containment, and recursion-depth checks). Reused a persistent `requests.Session` in `ContentsClient` with `close()`/context-manager cleanup (reopening a fresh client after `$EDITOR` in `colab edit`) for HTTP keep-alive, and redacted `colab-runtime-proxy-token` query params from `HTTPError` messages. diff --git a/docs/09_tray_and_profiles.md b/docs/09_tray_and_profiles.md index 20ca72a..378a03d 100644 --- a/docs/09_tray_and_profiles.md +++ b/docs/09_tray_and_profiles.md @@ -1,5 +1,6 @@ --- log: +2026-11-20: File manager: a progress bar with files done / total, the file and the time (`--progress` lines from `upload`/`download`), a Cancel button that stops the whole process tree (taskkill /T on Windows; SIGTERM elsewhere, on which scp is killed), a red banner and a read-only remote side when the runtime is gone (from the tray's refresh or a "Session not found"), and a note that a failed or cancelled scp may leave a cut-short file. Section 5 documents the window in full. Tested live: per-file progress on a 30-file upload, cancel over the contents API (7 of 60 files copied) and over scp (no scp left running), and the banner after `colab stop` with the window open. 2026-11-20: A two-pane file manager (`tray/files.py`, argv in `tray/file_ops.py`), opened with the Files button of a local card, in the style of Total Commander: this computer on the left (drive list, Up), the runtime on the right from `content`. Copy by drag and drop, the Upload/Download buttons or F5; F7 new folder, F8 delete (a local file goes to the recycle bin, a remote one after a confirmation, `rm -r` for a folder), Enter or double-click opens, Backspace goes up. The line at the bottom runs a command in the runtime's folder (`colab ssh -- sh -c` over ssh, otherwise `colab exec` with Python on stdin, so no key is needed). Transfers go over the contents API or scp (`--via`), chosen at the top and saved as `tray_transfer`. Every action is a CLI subcommand run with QProcess, one at a time. Tested live: the window's runner uploaded, downloaded, ran a command and deleted on an attached web UI runtime; the user tried it from the tray. 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. @@ -256,14 +257,7 @@ run it on each binary. running job only the runtime can be stopped. A runtime with no local session is stopped by its endpoint (`colab stop --endpoint`), and the dialog says it may be open in the Colab web UI or on another computer. -- **Files** opens a two-pane file manager for the runtime (`tray/files.py`): - this computer on the left (drive list, Up), the runtime on the right. Drag - and drop, the Upload/Download buttons or F5 copy; F7 makes a folder, F8 - deletes (local files go to the recycle bin), Enter opens, Backspace goes up, - and the bottom line runs a command in the runtime's folder. The transfer - goes over the contents API (no key) or ssh/scp, saved as `tray_transfer`. - Every action is a CLI subcommand (`ls --json`, `upload`/`download -r --via`, - `mkdir`, `rm -r`, `ssh -- CMD` or `exec`), run one at a time. +- **Files** opens a two-pane file manager for the runtime; see section 5. - **Log** opens a window that runs `colab job tail -n 200` (Follow adds `--follow` while the job runs) or, without a job, `colab log -n 200`, and shows the output as it comes; a help line says what it shows and where the @@ -313,6 +307,102 @@ run it on each binary. from the Colab logo of homarr-labs/dashboard-icons (Apache-2.0): Colab's C and a teal ring. The Colab logo is a trademark of Google. +## 5. The file manager (`tray/files.py`) + +The Files button of a local card opens a two-pane window for that runtime, +in the style of Total Commander. `tray/file_ops.py` (no Qt) turns every +action into argv for one of the CLI's own subcommands; the window runs them +with QProcess, one at a time, and never talks to the runtime itself. + +### Layout + +| Part | What it is | +|------|------------| +| Banner (red, hidden normally) | Shown when the runtime is gone; see *When the runtime goes away*. | +| Transfer | Contents API or SSH / scp; remembered as `tray_transfer` in `settings.json`. Refresh re-lists the remote folder. | +| Left pane: *This computer* | Drive list (`QDir.drives()`), path field (type a path and press Enter), up button (parent). A `QFileSystemModel` view of the folder. | +| Right pane: *Colab runtime* | Path field (contents-API path such as `content/data`), up button, and the listing from `colab ls --json`: name (folders end in `/`), size, modified. Starts at `content` (`/content`); `..` goes up, up to the runtime's root. | +| Button bar | Upload, Download, F7 New folder, F8 Delete. | +| Command line | `/content/...$` prompt and a field: runs a command in the remote folder. | +| Output | What every command printed (transfers, errors, command output). | +| Progress | A bar and a Cancel button while something runs; the status line under it. | + +### Keys and mouse + +| Action | How | +|--------|-----| +| Copy | Drag files or folders from one pane to the other (also from Explorer / Finder onto the right pane), the Upload / Download buttons, or F5 (copies the selection of the focused pane to the other pane's folder). Dropping on a folder copies into that folder. | +| Open | Enter or double-click: a folder opens; a local file opens in its default program; a remote file does nothing. | +| Up | Backspace, or the up button. | +| New folder | F7 (in the focused pane). | +| Delete | F8 (in the focused pane), after a confirmation. Local files go to the recycle bin (`QFile.moveToTrash`); remote ones are deleted for good (`colab rm`, `rm -r` for a folder). | +| Command | Type in the line at the bottom and press Enter. | + +### Transfers + +| | Contents API (default) | SSH / scp | +|---|---|---| +| Runs | `colab upload/download [-r] --via contents --progress` | `colab upload/download [-r] --via ssh` (OpenSSH scp through `colab ssh --proxy-mode`) | +| Needs | nothing | an SSH key: `ssh_identity` in `settings.json`, `COLAB_CLI_SSH_IDENTITY`, or `~/.ssh/id_ed25519` / `id_ecdsa`; no passphrase | +| Speed | base64 inside JSON: fine for code and small data | faster for big files | +| Progress | per file: "3 / 10 files, path, 0:12" and a filling bar (a download counts files without a total) | a moving bar and the time; no per-file data | +| A failure or cancel | each file is written whole or not at all; files copied before stay | the file being copied may be cut short (the window says so) | +| Limits | | a free CPU runtime takes one SSH connection at a time, so an open `colab ssh` makes scp fail with 429 | + +A folder is copied with its subfolders, empty ones included. Copying onto an +existing remote folder of the same name merges into it over the contents +API; scp then puts the folder inside it. + +### Command line + +The command runs in the remote folder shown in the prompt. Over SSH it is +`colab ssh -s NAME -- sh -c "cd FOLDER && COMMAND"`; otherwise `colab exec` +gets Python on stdin that runs the command with `subprocess.run(shell=True, +cwd=FOLDER)` and prints its output and `[exit N]`, so it works without a key +(in the CLI's kernel, not a notebook's). The listing is refreshed after it. +If the connection ends, an ssh command ends with it; one run through +`colab exec` may go on running on the runtime. + +### Cancel + +Cancel stops the running command and drops the waiting ones. The window stops +the whole process tree: `taskkill /T /F` on Windows (a child such as scp +outlives its parent there), SIGTERM elsewhere, on which `colab upload/download +--via ssh` kills its scp. The output says what is left: over the contents API +the files copied before the cancel stay and the file being copied was not +written; over scp that file may be cut short. + +### When the runtime goes away + +On each refresh the tray tells every open file manager whether its runtime +is still a local session (`set_available`); a command that prints +`Session 'NAME' not found` does the same. Without the runtime the banner +says so, waiting commands are dropped, and the remote side (listing, path, +command line, transfer choice, Refresh, Upload, Download) is disabled; the +left pane still works. If the runtime comes back (for example it was only +missing from one refresh), the window lists it again. + +### What it leaves behind + +- On this computer: only what you download, in the folder you chose. Local + deletes go to the recycle bin. `tray_transfer` is saved in `settings.json`, + and every command adds its usual lines to + `~/.config/colab-cli/history/NAME.jsonl` and `colab.log`. The window writes + no temporary files. +- On the runtime: only what you upload or create. A delete through the + contents API makes the Jupyter server create an empty `.ipynb_checkpoints` + folder in the parent folder (seen live); it is harmless and stays visible, + as hidden files are not hidden here. +- Everything on the runtime is lost when it stops. + +### A runtime opened in the Colab web UI + +Such a runtime has no local session, so its card has Connect and Stop only. +Connect runs `colab attach --endpoint ID`; the card then becomes a local one +with Log, SSH, Files and Stop, and the file manager works on the notebook's +`/content` (the CLI's commands run in their own kernel, not the notebook's). +Stop on that card stops it in the web UI too. + ## Testing - `tests/test_job_vm.py`: cell markers, the notebook driver with IPython and diff --git a/src/colab_cli/commands/files.py b/src/colab_cli/commands/files.py index 5e5796c..0740fba 100644 --- a/src/colab_cli/commands/files.py +++ b/src/colab_cli/commands/files.py @@ -18,6 +18,7 @@ import os import shutil import subprocess +import sys import tempfile import typer from typing import Optional @@ -171,6 +172,10 @@ def upload( Optional[str], typer.Option("--identity", "-i", help="With --via ssh: the SSH key, as for `colab ssh`."), ] = None, + progress: Annotated[ + bool, + typer.Option("--progress", help="Print a line per copied file: [colab] progress DONE/TOTAL PATH."), + ] = False, ): """Upload a file or directory to a session""" from colab_cli.common import state @@ -194,7 +199,7 @@ def upload( contents = ContentsClient(s) try: if is_dir: - count = contents.upload_dir(local_path, remote_path) + count = contents.upload_dir(local_path, remote_path, **_progress_kwargs(progress)) state.history.log_event( name, "file_operation", @@ -211,6 +216,8 @@ def upload( ) else: contents.upload(local_path, remote_path) + if progress: + _progress_printer(True)(1, 1, remote_path) state.history.log_event( name, "file_operation", @@ -249,6 +256,10 @@ def download( Optional[str], typer.Option("--identity", "-i", help="With --via ssh: the SSH key, as for `colab ssh`."), ] = None, + progress: Annotated[ + bool, + typer.Option("--progress", help="Print a line per copied file: [colab] progress DONE/TOTAL PATH."), + ] = False, ): """Download a file or directory from a session""" from colab_cli.common import state @@ -263,7 +274,7 @@ def download( contents = ContentsClient(s) try: if recursive: - count = contents.download_dir(remote_path, local_path) + count = contents.download_dir(remote_path, local_path, **_progress_kwargs(progress)) state.history.log_event( name, "file_operation", @@ -280,6 +291,8 @@ def download( ) else: contents.download(remote_path, local_path) + if progress: + _progress_printer(True)(1, 1, remote_path) state.history.log_event( name, "file_operation", @@ -293,6 +306,22 @@ def download( contents.close() +def _progress_printer(enabled: bool): + """With --progress, one line per file for the tray's file manager to read.""" + if not enabled: + return None + + def printer(done: int, total, path: str) -> None: + typer.echo(f"[colab] progress {done}/{total if total is not None else '?'} {path}") + sys.stdout.flush() + + return printer + + +def _progress_kwargs(enabled: bool) -> dict: + return {"on_file": _progress_printer(True)} if enabled else {} + + def _check_via(via: str) -> str: if via not in ("contents", "ssh"): typer.echo(f"[colab] --via must be contents or ssh, not {via!r}.", err=True) diff --git a/src/colab_cli/commands/ssh.py b/src/colab_cli/commands/ssh.py index 00895a2..fe8ed65 100644 --- a/src/colab_cli/commands/ssh.py +++ b/src/colab_cli/commands/ssh.py @@ -980,7 +980,23 @@ def scp_transfer( args.insert(1, "-r") remote = f"{_SSH_HOST}:/{target.lstrip('/') if upload else source.lstrip('/')}" args += [source, remote] if upload else [remote, target] - return subprocess.call(args) + proc = subprocess.Popen(args) + + def stop(_signum, _frame): + raise KeyboardInterrupt + + previous = signal.signal(signal.SIGTERM, stop) + try: + return proc.wait() + except KeyboardInterrupt: + # Cancelled (the tray's file manager sends SIGTERM): scp must not + # go on copying in the background. + return 130 + finally: + signal.signal(signal.SIGTERM, previous) + if proc.poll() is None: + proc.kill() + proc.wait() def _call_ssh(args: list[str], session: SessionState, keep_alive: bool) -> int: diff --git a/src/colab_cli/contents.py b/src/colab_cli/contents.py index d61ba6a..b7b2bbb 100644 --- a/src/colab_cli/contents.py +++ b/src/colab_cli/contents.py @@ -169,7 +169,8 @@ def _ensure_dir(self, remote_path: str) -> None: self._ensure_dir(parent) self.mkdir(remote_path) - def upload_dir(self, local_dir: str, remote_dir: str) -> int: + def upload_dir(self, local_dir: str, remote_dir: str, on_file=None) -> int: + """Upload a tree; ``on_file(done, total, remote_path)`` after each file.""" if not os.path.isdir(local_dir): raise NotADirectoryError(f"Not a directory: {local_dir}") base_remote = _normalize_remote_path(remote_dir) @@ -179,6 +180,14 @@ def upload_dir(self, local_dir: str, remote_dir: str) -> int: def _raise_walk_error(err: OSError) -> None: raise err + total = None + if on_file is not None: + total = sum( + 1 + for root, dirs, files in os.walk(local_dir, followlinks=False) + for f in files + if not os.path.islink(os.path.join(root, f)) and os.path.isfile(os.path.join(root, f)) + ) count = 0 for root, dirs, files in os.walk( local_dir, followlinks=False, onerror=_raise_walk_error @@ -195,8 +204,11 @@ def _raise_walk_error(err: OSError) -> None: for f in files: local_file = os.path.join(root, f) if not os.path.islink(local_file) and os.path.isfile(local_file): - self.upload(local_file, posixpath.join(current_remote, f)) + remote_file = posixpath.join(current_remote, f) + self.upload(local_file, remote_file) count += 1 + if on_file is not None: + on_file(count, total, remote_file) return count def download(self, remote_path: str, local_path: str): @@ -215,9 +227,13 @@ def download_dir( remote_path: str, local_path: str, *, + on_file=None, _depth: int = 0, _max_depth: int = 64, + _done=None, ) -> int: + """Download a tree; ``on_file(done, None, remote_path)`` after each file.""" + _done = _done if _done is not None else [0] if _depth > _max_depth: raise RecursionError( f"Maximum directory depth ({_max_depth}) exceeded while downloading {remote_path!r}" @@ -258,12 +274,17 @@ def download_dir( count += self.download_dir( child_remote, child_local, + on_file=on_file, _depth=_depth + 1, _max_depth=_max_depth, + _done=_done, ) else: self.download(child_remote, child_local) count += 1 + _done[0] += 1 + if on_file is not None: + on_file(_done[0], None, child_remote) return count def read_text(self, remote_path: str) -> str: diff --git a/src/colab_cli/tray/app.py b/src/colab_cli/tray/app.py index 88028cb..6a976dc 100644 --- a/src/colab_cli/tray/app.py +++ b/src/colab_cli/tray/app.py @@ -175,6 +175,11 @@ def on_snapshot(self, snap: Dict[str, Any]): self.busy = False prev, self.snapshot = self.snapshot, snap self._reap_children() + if snap.get("ok"): + local = {e["name"] for e in snap.get("sessions", []) if e.get("local")} + for window in self.windows: + if hasattr(window, "set_available") and getattr(window, "session", None): + window.set_available(window.session in local) if self.settings.tray_notifications: for event in events(prev, snap, low_balance_hours=self.settings.tray_low_balance_hours): self.notify(actions.notification(event, self.lang), diff --git a/src/colab_cli/tray/file_ops.py b/src/colab_cli/tray/file_ops.py index 05e8eea..c655021 100644 --- a/src/colab_cli/tray/file_ops.py +++ b/src/colab_cli/tray/file_ops.py @@ -23,6 +23,7 @@ import json import os import posixpath +import re import shlex from typing import List, Optional, Tuple @@ -50,7 +51,22 @@ def copy_argv(session: str, source: str, target_dir: str, *, upload: bool, is_di argv = ["upload" if upload else "download", "-s", session] if is_dir: argv.append("-r") - return argv + ["--via", via, source, target] + argv += ["--via", via] + if via == "contents": + argv.append("--progress") + return argv + [source, target] + + +PROGRESS = re.compile(r"^\[colab\] progress (\d+)/(\d+|\?) (.*)$") + + +def parse_progress(line: str) -> Optional[Tuple[int, Optional[int], str]]: + """A `--progress` line as (done, total or None, path); None for other lines.""" + match = PROGRESS.match(line.strip()) + if not match: + return None + total = match.group(2) + return int(match.group(1)), None if total == "?" else int(total), match.group(3) def mkdir_argv(session: str, path: str) -> List[str]: diff --git a/src/colab_cli/tray/files.py b/src/colab_cli/tray/files.py index 809027a..4a52d80 100644 --- a/src/colab_cli/tray/files.py +++ b/src/colab_cli/tray/files.py @@ -25,9 +25,12 @@ import codecs import json import os +import subprocess +import sys +import time from typing import Callable, List, Optional -from PySide6.QtCore import QDir, QMimeData, QProcess, QProcessEnvironment, Qt, QUrl +from PySide6.QtCore import QDir, QMimeData, QProcess, QProcessEnvironment, Qt, QTimer, QUrl from PySide6.QtGui import QDesktopServices, QFont, QFontDatabase, QKeySequence, QShortcut from PySide6.QtWidgets import ( QComboBox, @@ -38,6 +41,7 @@ QLineEdit, QMessageBox, QPlainTextEdit, + QProgressBar, QPushButton, QSplitter, QTreeView, @@ -159,12 +163,20 @@ def __init__(self, session: str, lang: str, base_argv: List[str], settings_store self.remote_dir = REMOTE_ROOT self.local_dir = start_dir or os.path.expanduser("~") self.active = "remote" + self.available = True self.setObjectName("window") self.setStyleSheet(WINDOW_QSS) self.setWindowTitle(t(lang, "files.title", session=session)) self.resize(1100, 680) box = QVBoxLayout(self) + self.banner = QLabel(t(lang, "files.gone", session=session), wordWrap=True) + self.banner.setStyleSheet( + "background: #5c1d1d; color: #f6aea9; border: 1px solid #ea4335; border-radius: 6px; padding: 8px;" + ) + self.banner.hide() + box.addWidget(self.banner) + top = QHBoxLayout() top.addWidget(QLabel(t(lang, "files.via"))) self.via = QComboBox() @@ -174,10 +186,10 @@ def __init__(self, session: str, lang: str, base_argv: List[str], settings_store self.via.currentIndexChanged.connect(self._save_via) top.addWidget(self.via) top.addStretch() - refresh = QPushButton(t(lang, "log.refresh")) - refresh.setIcon(glyph_icon("refresh", "#e8eaed")) - refresh.clicked.connect(self.refresh_remote) - top.addWidget(refresh) + self.refresh_button = QPushButton(t(lang, "log.refresh")) + self.refresh_button.setIcon(glyph_icon("refresh", "#e8eaed")) + self.refresh_button.clicked.connect(self.refresh_remote) + top.addWidget(self.refresh_button) box.addLayout(top) split = QSplitter(Qt.Horizontal) @@ -230,8 +242,22 @@ def __init__(self, session: str, lang: str, base_argv: List[str], settings_store fixed = QFontDatabase.systemFont(QFontDatabase.FixedFont) self.output.setFont(QFont(fixed.family(), 10)) box.addWidget(self.output, 1) + progress_row = QHBoxLayout() + self.progress = QProgressBar() + self.progress.setTextVisible(True) + self.progress.hide() + progress_row.addWidget(self.progress, 1) + self.cancel_button = QPushButton(t(lang, "files.cancel"), objectName="danger") + self.cancel_button.clicked.connect(self.cancel) + self.cancel_button.hide() + progress_row.addWidget(self.cancel_button) + box.addLayout(progress_row) + self.job_via = None self.status = QLabel(objectName="muted") box.addWidget(self.status) + self.job_label, self.job_start, self.job_progress, self._line_buf = "", 0.0, None, "" + self.ticker = QTimer(self) + self.ticker.timeout.connect(self._tick) for key, slot in ((Qt.Key_F5, self.copy_selected), (Qt.Key_F7, self.make_folder), (Qt.Key_F8, self.delete_selected)): @@ -290,7 +316,37 @@ def _save_via(self) -> None: def submit(self, argv: List[str], label: str, done: Optional[Callable[[int, str], None]] = None, stdin: Optional[str] = None) -> None: - self.run(argv, stdin, label, done or (lambda code, out: None)) + if not self.available: + self.status.setText(t(self.lang, "files.gone_short")) + return + done = done or (lambda code, out: None) + missing = f"Session '{self.session}' not found" + + def checked(code: int, out: str) -> None: + done(code, out) + if code and missing in out: + self.set_available(False) + + self.run(argv, stdin, label, checked) + + def set_available(self, available: bool) -> None: + """Called by the tray on each refresh, and when a command finds no session. + + Without the runtime the remote side is read-only history: the banner + says so, waiting commands are dropped, and only the local pane works. + """ + if available == self.available: + return + self.available = available + self.banner.setVisible(not available) + for widget in (self.remote, self.remote_path, self.command, self.via, self.refresh_button, + self.buttons["files.upload"], self.buttons["files.download"]): + widget.setEnabled(available) + if not available: + self.queue.clear() + self.status.setText(t(self.lang, "files.gone_short")) + else: + self.refresh_remote() def _run_process(self, argv, stdin, label, done) -> None: self.queue.append((argv, stdin, label, done)) @@ -300,10 +356,11 @@ def _run_process(self, argv, stdin, label, done) -> None: def _next(self) -> None: if not self.queue: self.proc = None - self.status.setText(t(self.lang, "files.idle")) + self._all_done() return argv, stdin, label, done = self.queue.pop(0) - self.status.setText(t(self.lang, "files.running", what=label, left=len(self.queue))) + self.job_via = argv[argv.index("--via") + 1] if "--via" in argv else None + self._job_started(label) proc = QProcess(self) env = QProcessEnvironment.systemEnvironment() for k, v in (("NO_COLOR", "1"), ("PYTHONIOENCODING", "utf-8"), ("TERM", "dumb")): @@ -312,7 +369,13 @@ def _next(self) -> None: proc.setProcessChannelMode(QProcess.MergedChannels) decoder = codecs.getincrementaldecoder("utf-8")("replace") chunks: List[str] = [] - proc.readyReadStandardOutput.connect(lambda: chunks.append(decoder.decode(bytes(proc.readAllStandardOutput())))) + + def read(): + text = decoder.decode(bytes(proc.readAllStandardOutput())) + chunks.append(text) + self._feed_progress(text) + + proc.readyReadStandardOutput.connect(read) def finished(code, _status=None): chunks.append(decoder.decode(b"", final=True)) @@ -330,6 +393,77 @@ def finished(code, _status=None): proc.write(stdin.encode("utf-8")) proc.closeWriteChannel() + # --- progress: a bar, the file being copied, the time so far --- + + def _job_started(self, label: str) -> None: + self.job_label, self.job_start, self.job_progress, self._line_buf = label, time.monotonic(), None, "" + self.progress.setRange(0, 0) + self.progress.show() + self.cancel_button.show() + self._tick() + self.ticker.start(1000) + + def _feed_progress(self, text: str) -> None: + self._line_buf += text + *lines, self._line_buf = self._line_buf.split("\n") + for line in lines: + parsed = file_ops.parse_progress(line) + if parsed: + self._set_progress(*parsed) + + def _set_progress(self, done: int, total: Optional[int], path: str) -> None: + self.job_progress = (done, total, path) + if total: + self.progress.setRange(0, total) + self.progress.setValue(done) + self._tick() + + def _tick(self) -> None: + seconds = int(time.monotonic() - self.job_start) + parts = [t(self.lang, "files.now", what=self.job_label)] + if self.job_progress: + done, total, path = self.job_progress + parts.append(t(self.lang, "files.of_total", done=done, total=total) if total + else t(self.lang, "files.count", done=done)) + parts.append(path) + parts.append(f"{seconds // 60}:{seconds % 60:02d}") + if self.queue: + parts.append(t(self.lang, "files.waiting", left=len(self.queue))) + self.status.setText(" · ".join(parts)) + + def cancel(self) -> None: + """Stop the running command and drop the waiting ones.""" + dropped = len(self.queue) + self.queue.clear() + running = self.proc is not None and self.proc.state() != QProcess.NotRunning + if running: + self.log(t(self.lang, "files.cancelled", what=self.job_label, dropped=dropped)) + if self.job_via == "ssh": + self.log(t(self.lang, "files.cancelled_ssh")) + elif self.job_via == "contents": + self.log(t(self.lang, "files.cancelled_contents")) + self._stop_process_tree(self.proc) + elif dropped: + self.log(t(self.lang, "files.cancelled", what="", dropped=dropped)) + + @staticmethod + def _stop_process_tree(proc: QProcess) -> None: + """Stop the CLI and what it started (scp): killing only the CLI leaves + scp copying on Windows, where children outlive their parent.""" + pid = proc.processId() + if sys.platform == "win32" and pid: + subprocess.run(["taskkill", "/PID", str(pid), "/T", "/F"], capture_output=True, + creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0)) + return + proc.terminate() + QTimer.singleShot(5000, lambda: proc.state() != QProcess.NotRunning and proc.kill()) + + def _all_done(self) -> None: + self.ticker.stop() + self.progress.hide() + self.cancel_button.hide() + self.status.setText(t(self.lang, "files.idle" if self.available else "files.gone_short")) + def log(self, text: str) -> None: self.output.appendPlainText(text.rstrip("\n")) @@ -418,18 +552,31 @@ def upload(self, paths: List[str], target: str) -> None: for path in paths: argv = file_ops.copy_argv(self.session, path, target, upload=True, is_dir=os.path.isdir(path), via=via) self.submit(argv, t(self.lang, "files.uploading", name=os.path.basename(path.rstrip("/\\"))), - self._after_transfer) + self._transfer_done(argv[-1], via)) def download(self, entries: List[dict], target: str) -> None: via = self.via.currentData() for entry in entries: argv = file_ops.copy_argv(self.session, entry["path"], target, upload=False, is_dir=entry["dir"], via=via) self.submit(argv, t(self.lang, "files.downloading", name=entry["path"].rsplit("/", 1)[-1]), - self._after_transfer) + self._transfer_done(argv[-1], via)) + + def _transfer_done(self, target: str, via: str) -> Callable[[int, str], None]: + """scp writes as it goes: after a failure the target may be cut short. + + The contents API writes a file whole or not at all, so only files + already copied stay; nothing needs saying then. + """ + def done(code: int, out: str) -> None: + self._after_transfer(code, out) + if code and via == "ssh": + self.log(t(self.lang, "files.partial", path=target)) + return done def _after_transfer(self, code: int, out: str) -> None: self.log(out) - self.refresh_remote() + if self.available: + self.refresh_remote() def upload_selected(self) -> None: paths = self.local_selection() diff --git a/src/colab_cli/tray/i18n.py b/src/colab_cli/tray/i18n.py index e1603da..ed07830 100644 --- a/src/colab_cli/tray/i18n.py +++ b/src/colab_cli/tray/i18n.py @@ -525,3 +525,37 @@ def hardware_label(hw: str) -> str: "files.select_local": "Jelölj ki fájlt vagy mappát a bal oldalon a feltöltéshez.", "files.select_remote": "Jelölj ki fájlt vagy mappát a jobb oldalon a letöltéshez.", }) +STRINGS["en"].update({ + "files.gone": "The runtime {session} is gone (stopped, idled out, or the connection to it ended). Waiting commands were dropped; the left pane still works. This window comes back to life if the runtime does.", + "files.gone_short": "The runtime is gone: nothing can be copied to or from it.", + "files.partial": "scp stopped with an error: {path} may be cut short; check it or copy it again.", +}) +STRINGS["hu"].update({ + "files.gone": "A(z) {session} gép eltűnt (leállt, tétlenség miatt leállították, vagy megszakadt a kapcsolat). A várakozó műveletek törlődtek; a bal oldali panel továbbra is használható. Ha a gép visszajön, az ablak újra működik.", + "files.gone_short": "A gép eltűnt: nem lehet rá vagy róla másolni.", + "files.partial": "Az scp hibával állt le: a(z) {path} csonka lehet; ellenőrizd vagy másold újra.", +}) +STRINGS["en"].update({ + "files.now": "Running: {what}", + "files.of_total": "{done} / {total} files", + "files.count": "{done} files done", + "files.waiting": "{left} waiting", +}) +STRINGS["hu"].update({ + "files.now": "Fut: {what}", + "files.of_total": "{done} / {total} fájl", + "files.count": "{done} fájl kész", + "files.waiting": "még {left} vár", +}) +STRINGS["en"].update({ + "files.cancel": "Cancel", + "files.cancelled": "Cancelled: {what} ({dropped} waiting dropped).", + "files.cancelled_contents": "Files copied before the cancel stay; the file being copied was not written.", + "files.cancelled_ssh": "The file scp was copying may be cut short; check it or copy it again.", +}) +STRINGS["hu"].update({ + "files.cancel": "Megszakítás", + "files.cancelled": "Megszakítva: {what} ({dropped} várakozó törölve).", + "files.cancelled_contents": "A megszakítás előtt átment fájlok megmaradnak; az éppen másolt fájl nem íródott ki.", + "files.cancelled_ssh": "Az scp által éppen másolt fájl csonka lehet; ellenőrizd vagy másold újra.", +}) diff --git a/tests/test_files_extras.py b/tests/test_files_extras.py index 9420419..9320960 100644 --- a/tests/test_files_extras.py +++ b/tests/test_files_extras.py @@ -104,7 +104,10 @@ def scp(mocker, session, tmp_path, monkeypatch): (tmp_path / "k.pub").write_text("ssh-ed25519 AAAA") monkeypatch.setenv("COLAB_CLI_SSH_IDENTITY", str(key)) mocker.patch("colab_cli.commands.ssh._proxy_command", return_value="PROXY") - return mocker.patch("colab_cli.commands.ssh.subprocess.call", return_value=0) + popen = mocker.patch("colab_cli.commands.ssh.subprocess.Popen") + popen.return_value.wait.return_value = 0 + popen.return_value.poll.return_value = 0 + return popen def test_upload_via_ssh_runs_scp(scp, tmp_path): @@ -126,7 +129,7 @@ def test_download_via_ssh_runs_scp(scp, tmp_path): def test_scp_failure_exits_with_its_code(scp, tmp_path): - scp.return_value = 1 + scp.return_value.wait.return_value = 1 result = runner.invoke(app, ["download", "-s", "s1", "--via", "ssh", "content/a.txt", str(tmp_path / "a")]) assert result.exit_code == 1 @@ -134,3 +137,45 @@ def test_scp_failure_exits_with_its_code(scp, tmp_path): def test_unknown_via(session, tmp_path): result = runner.invoke(app, ["download", "-s", "s1", "--via", "ftp", "content/a", str(tmp_path / "a")]) assert result.exit_code == 2 + + +def test_upload_dir_reports_each_file_with_the_total(tmp_path): + (tmp_path / "d" / "sub").mkdir(parents=True) + (tmp_path / "d" / "a.txt").write_text("a") + (tmp_path / "d" / "sub" / "b.txt").write_text("b") + client = ContentsClient.__new__(ContentsClient) + client._ensure_dir = MagicMock() + client.mkdir = MagicMock() + client.upload = MagicMock() + seen = [] + client.upload_dir(str(tmp_path / "d"), "content/d", on_file=lambda *a: seen.append(a)) + assert seen == [(1, 2, "content/d/a.txt"), (2, 2, "content/d/sub/b.txt")] + + +def test_download_dir_counts_across_subfolders(tmp_path): + client = ContentsClient.__new__(ContentsClient) + listings = { + "d": {"type": "directory", "content": [{"name": "a", "type": "file"}, {"name": "s", "type": "directory"}]}, + "d/s": {"type": "directory", "content": [{"name": "b", "type": "file"}]}, + } + client._request = MagicMock(side_effect=lambda m, p, params=None, json_data=None: listings[p]) + client.download = MagicMock() + seen = [] + client.download_dir("d", str(tmp_path / "out"), on_file=lambda *a: seen.append(a)) + assert seen == [(1, None, "d/a"), (2, None, "d/s/b")] + + +def test_progress_lines(contents, tmp_path): + folder = tmp_path / "dir" + folder.mkdir() + + def fake_upload_dir(local, remote, on_file=None): + on_file(1, 2, "content/dir/a") + on_file(2, 2, "content/dir/b") + return 2 + + contents.upload_dir.side_effect = fake_upload_dir + result = runner.invoke(app, ["upload", "-s", "s1", "-r", "--progress", str(folder), "content/dir"]) + assert result.exit_code == 0, result.output + assert "[colab] progress 1/2 content/dir/a" in result.stdout + assert "[colab] progress 2/2 content/dir/b" in result.stdout diff --git a/tests/test_tray_file_ops.py b/tests/test_tray_file_ops.py index 54755ee..1c9e97a 100644 --- a/tests/test_tray_file_ops.py +++ b/tests/test_tray_file_ops.py @@ -29,7 +29,9 @@ def test_ls_argv(): def test_copy_argv_upload_a_folder_into_the_remote_folder(): argv = f.copy_argv("s1", os.path.join("C:", "work", "data"), "content", upload=True, is_dir=True, via="contents") - assert argv == ["upload", "-s", "s1", "-r", "--via", "contents", os.path.join("C:", "work", "data"), "content/data"] + assert argv == [ + "upload", "-s", "s1", "-r", "--via", "contents", "--progress", os.path.join("C:", "work", "data"), "content/data", + ] def test_copy_argv_download_a_file_over_ssh(tmp_path): @@ -79,3 +81,9 @@ def test_parse_listing_errors(): @pytest.mark.parametrize("size,text", [(None, ""), (0, "0 B"), (999, "999 B"), (2048, "2.0 KB"), (5 * 1024**3, "5.0 GB")]) def test_human_size(size, text): assert f.human_size(size) == text + + +def test_parse_progress(): + assert f.parse_progress("[colab] progress 3/10 content/d/sub/b.txt\n") == (3, 10, "content/d/sub/b.txt") + assert f.parse_progress("[colab] progress 7/? content/x") == (7, None, "content/x") + assert f.parse_progress("[colab] Uploaded 'x' to 'y'") is None diff --git a/tests/test_tray_files.py b/tests/test_tray_files.py index 39fb6b1..22c0440 100644 --- a/tests/test_tray_files.py +++ b/tests/test_tray_files.py @@ -92,7 +92,8 @@ def test_f5_from_the_remote_pane_downloads_into_the_local_folder(fm, tmp_path): fm.remote.topLevelItem(2).setSelected(True) fm.copy_selected() assert fm.calls[-1]["argv"] == [ - "download", "-s", "s1", "--via", "contents", "content/model.pt", os.path.join(str(tmp_path), "model.pt"), + "download", "-s", "s1", "--via", "contents", "--progress", "content/model.pt", + os.path.join(str(tmp_path), "model.pt"), ] @@ -112,9 +113,9 @@ def test_dropping_local_files_on_the_remote_pane_uploads_them(fm, tmp_path): event = QDropEvent(QPointF(1, 1), Qt.CopyAction, mime, Qt.LeftButton, Qt.NoModifier) fm.remote.dropEvent(event) argv = fm.calls[-1]["argv"] - assert argv[:5] == ["upload", "-s", "s1", "--via", "contents"] - assert os.path.normpath(argv[5]) == os.path.normpath(str(tmp_path / "local.txt")) - assert argv[6] == "content/local.txt" + assert argv[:6] == ["upload", "-s", "s1", "--via", "contents", "--progress"] + assert os.path.normpath(argv[6]) == os.path.normpath(str(tmp_path / "local.txt")) + assert argv[7] == "content/local.txt" def test_dragging_remote_items_carries_their_paths_to_the_local_pane(fm, tmp_path): @@ -203,3 +204,97 @@ def test_upload_and_download_buttons(fm, tmp_path): fm.buttons["files.download"].click() assert fm.calls[-1]["argv"][0] == "download" assert fm.calls[-1]["argv"][-1] == os.path.join(str(tmp_path), "model.pt") + + +def test_a_gone_runtime_shows_a_banner_and_stops_remote_actions(fm, tmp_path): + _answer_listing(fm) + fm.queue.append((["upload"], None, "x", lambda c, o: None)) + fm.set_available(False) + assert fm.banner.isVisibleTo(fm) and fm.queue == [] + assert not fm.buttons["files.upload"].isEnabled() and not fm.buttons["files.download"].isEnabled() + assert not fm.remote.isEnabled() and not fm.command.isEnabled() + before = len(fm.calls) + fm.upload([str(tmp_path / "local.txt")], "content") + fm.refresh_remote() + assert len(fm.calls) == before + assert fm.local_view.isEnabled() + + fm.set_available(True) + assert not fm.banner.isVisibleTo(fm) and fm.remote.isEnabled() + assert fm.calls[-1]["argv"] == ["ls", "-s", "s1", "--json", "content"] + + +def test_a_missing_session_in_the_output_marks_the_runtime_gone(fm): + fm.calls[-1]["done"](1, "[colab] Session 's1' not found.\n") + assert fm.banner.isVisibleTo(fm) + + +def test_a_failed_scp_warns_that_the_target_may_be_partial(fm, tmp_path): + _answer_listing(fm) + fm.via.setCurrentIndex(fm.via.findData("ssh")) + fm.download([{"path": "content/model.pt", "dir": False}], str(tmp_path)) + fm.calls[-1]["done"](1, "[colab] Download over ssh failed (scp exit code 1).") + text = fm.output.toPlainText() + assert "csonka" in text and os.path.join(str(tmp_path), "model.pt") in text + + +def test_a_failed_contents_transfer_does_not_claim_a_partial_file(fm, tmp_path): + _answer_listing(fm) + fm.download([{"path": "content/model.pt", "dir": False}], str(tmp_path)) + fm.calls[-1]["done"](1, "[colab] Download failed: boom") + assert "csonka" not in fm.output.toPlainText() + + +def test_progress_bar_shows_files_done_and_hides_when_all_done(fm): + fm._job_started("updir feltöltése") + assert fm.progress.isVisibleTo(fm) and fm.progress.maximum() == 0 + fm._feed_progress("[colab] progress 3/1") + fm._feed_progress("0 content/updir/sub/b.txt\n[colab] Uploaded") + assert (fm.progress.maximum(), fm.progress.value()) == (10, 3) + assert "3 / 10 fájl" in fm.status.text() and "content/updir/sub/b.txt" in fm.status.text() + assert "updir feltöltése" in fm.status.text() and "0:0" in fm.status.text() + fm._all_done() + assert not fm.progress.isVisibleTo(fm) and fm.status.text() == "Kész." + + +def test_progress_without_a_total_counts_files(fm): + fm._job_started("letöltés") + fm._feed_progress("[colab] progress 4/? content/x\n") + assert fm.progress.maximum() == 0 and "4 fájl kész" in fm.status.text() + + +def test_cancel_kills_the_running_copy_and_drops_the_rest(fm, mocker): + from PySide6.QtCore import QProcess + + fm._job_started("tree feltöltése") + assert fm.cancel_button.isVisibleTo(fm) + fm.queue[:] = [(["upload"], None, "a", None), (["upload"], None, "b", None)] + fm.proc = MagicMock() + fm.proc.state.return_value = QProcess.Running + fm.proc.processId.return_value = 4321 + fm.job_via = "ssh" + run = mocker.patch.object(files_mod.subprocess, "run") + fm.cancel() + if files_mod.sys.platform == "win32": + assert run.call_args.args[0] == ["taskkill", "/PID", "4321", "/T", "/F"] + else: + fm.proc.terminate.assert_called_once() + assert fm.queue == [] + text = fm.output.toPlainText() + assert "Megszakítva: tree feltöltése (2 várakozó törölve)" in text and "csonka" in text + fm.proc = None + fm._all_done() + assert not fm.cancel_button.isVisibleTo(fm) + + +def test_cancel_over_contents_says_copied_files_stay(fm, mocker): + mocker.patch.object(files_mod.subprocess, "run") + from PySide6.QtCore import QProcess + + fm._job_started("letöltés") + fm.proc = MagicMock() + fm.proc.state.return_value = QProcess.Running + fm.job_via = "contents" + fm.cancel() + assert "átment fájlok megmaradnak" in fm.output.toPlainText() + fm.proc = None diff --git a/tests/test_tray_panel.py b/tests/test_tray_panel.py index 65e2c46..c25d191 100644 --- a/tests/test_tray_panel.py +++ b/tests/test_tray_panel.py @@ -606,3 +606,15 @@ def test_a_card_without_wrapped_text_is_shown(tray): card = tray.panel.cards[0] assert card.sizeHint().height() > 50 assert tray.panel.scroll.height() >= card.sizeHint().height() + + +def test_snapshot_tells_open_file_managers_whether_their_runtime_is_there(tray): + window = MagicMock(session="train-t4") + gone = MagicMock(session="old") + tray.windows = [window, gone] + tray.on_snapshot(_snap([_entry("train-t4", None)])) + window.set_available.assert_called_with(True) + gone.set_available.assert_called_with(False) + window.set_available.reset_mock() + tray.on_snapshot(_snap([], ok=False)) + window.set_available.assert_not_called()