diff --git a/CHANGELOG.md b/CHANGELOG.md
index a738020..2954268 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,15 +6,41 @@ All notable changes are recorded here. The format follows
## [Unreleased]
+## [0.2.0] - 2026-11-16
+
### Added
+- A new home screen. Bare `kdev` in a terminal is a live menu that is usable
+ at once: the box and every account's quota fill in while it is on screen, a
+ running box counts down in place, and the active account's quota bar shows
+ what the next box would use. Every action has a key (`1`-`4`, `s` status, `a`
+ accounts, `d` doctor, `q` quits), arrows and `j`/`k` move, and the
+ highlighted item shows the exact command it runs. Read-only picks return to
+ the menu.
+- Every list prompt is numbered; a digit picks its row at once, `j`/`k` move.
+- `kdev up` draws its progress as a rail, with a clock per step and how long
+ that step usually takes on this machine.
+- `status` and the ready card show the time left as a draining bar that turns
+ yellow at 30 minutes and red at 10.
+- `kdev --help` ends with worked examples and uses kdev's palette. Usage
+ mistakes are reported in the same voice as every other error, with the
+ `--help` of the command being typed, and a near-miss setting or `--gpu`
+ value gets a "Did you mean".
+- `kdev account` (and `--json`, as `quota_resets`) and the home screen say
+ when the weekly quota refills. Choosing a session length shows what each
+ choice leaves of this week's quota.
+- Every prompt, spinner and card sits on the same two-column gutter; a
+ spinner shows its elapsed time once a wait passes three seconds. In a
+ short terminal the home screen drops the logo and folds its secondary
+ actions onto one line.
+- `kdev workspace files` summarises each top-level folder; `--all` lists every
+ file. `kdev backup --force` overrides the new restore guard (see Fixed).
- A project website at https://kdev-cli.pages.dev: the docs with search, an
interactive architecture explorer and the changelog. The README, PyPI page and
citation now link to it.
-- Colour terminals show a five-line pixel kdev header with the command and
- version beside the terminal symbol, once per invocation, including setup and menu
- actions. Narrow terminals use the compact terminal badge;
- ASCII terminals and `NO_COLOR` use plain titles. The wordmark adapts to light
- and dark backgrounds. Piped output, JSON, logs and SSH command output stay clean.
+- Colour terminals show a five-line pixel kdev header on the home screen and in
+ setup; every other command gets one line, `›_ kdev › status`, with its
+ context on the right. ASCII terminals and `NO_COLOR` use plain titles.
+ Piped output, JSON, logs and SSH command output stay clean.
- CI reports test coverage from one Linux matrix job and includes the coverage
table in each pull request's job summary.
- `uv run basedpyright` type-checks `src` and `tests` in basic mode; it runs on
@@ -31,8 +57,8 @@ All notable changes are recorded here. The format follows
### Changed
- The terminal UI uses a geometric KDEV wordmark and terminal badge, consistent rounded
- workspace and result cards, clearer account quotas, framed progress with
- elapsed times, and grouped command help. Tables and next actions adapt to
+ workspace and result cards, clearer account quotas, and grouped command
+ help. Tables and next actions adapt to
narrow terminals without dropping values. Light/dark terminal colors,
ASCII and monochrome prompts remain usable; live refresh is limited to 8 Hz.
@@ -48,6 +74,36 @@ All notable changes are recorded here. The format follows
preventing repeated warnings on `kdev up`.
- `kdev logs` hides the kernel's debugger start-up warnings; `--all` still
shows them.
+- `kdev status` took 13s on a large workspace: reading one version's state paged
+ through its whole file listing. It now stops after the first page (5.5s), and
+ Kaggle and ssh are asked at once. `history` reads versions in parallel and
+ remembers ended ones (61s, then 1.2s on a repeat run). `doctor` checks
+ accounts in parallel.
+- Every command minted a new Kaggle access token, often several, and wrote it
+ into `~/.kaggle/credentials.json` -- the official CLI's own login. Tokens are
+ now reused until near expiry and only ever written to kdev's own files.
+- Offline, every networked command died with "unexpected error"; accounts now
+ show "could not reach Kaggle", and `doctor` reports it as a check.
+- A transient Kaggle error while reading the notebook could make `kdev up`
+ replace the notebook's own code; only a missing notebook counts as empty now.
+- `workspace share` added a second binding for a group already on the notebook.
+- Non-interactive ssh and VS Code's server lost the notebook's PATH (`/opt/bin`,
+ CUDA) to pam_env; the box now gives pam_env the same PATH (verified on a box).
+- Changing `ssh-alias` or `tunnel-hostname` left a stale `~/.ssh/config` block,
+ and the block was appended after any `Host *`, whose settings then won.
+- `kdev backup` could replace the local copy with a box that never finished
+ restoring; it now refuses unless `--force`.
+- Piped output was wrapped at 80 columns; tables are now tab-separated and
+ nothing wraps. `kdev logs | head` no longer fails; `status --json` exits 1
+ when the state is unknown; `logs` on a stopped box says which run it shows.
+- ASCII-only terminals crashed on `×` and `·`; they get ASCII stand-ins.
+- Rate limiting (HTTP 429) is waited out, honouring Retry-After.
+- The `up` progress clocks and spinner froze between log lines during a long
+ silent step; an interrupted step was drawn as done.
+- Piped hints and next steps went to stdout between data rows; they now go
+ to stderr, and tables are real tab-separated values.
+- Some ssh calls had no timeout and could hang `up`, `restore` or `down`.
+- The tests no longer download cloudflared or touch the network or `$HOME`.
## [0.1.4] - 2026-09-24
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index e614dda..aaa0991 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -1,17 +1,110 @@
# Contributing to kdev
-Thanks for helping. The full guide lives in the README, under
-[Contributing](README.md#contributing): how to set up, how to try a change
-against real Kaggle without spending GPU quota, how the code is laid out, and
-what a pull request needs.
+Contributions are welcome — bug reports, fixes, docs and features alike. kdev
+is small and opinionated, so for anything bigger than a fix, open an issue
+first and say what you want to change and why. It saves you writing code that
+goes a different way than the project.
-The short version:
-
-- For anything bigger than a fix, open an issue first.
-- `uv sync && uv run pre-commit install`, then `uv run pytest`.
-- A bug fix comes with a test that fails without it.
-- Commit messages follow [Conventional Commits](https://www.conventionalcommits.org/).
-- Note what users will notice under `## [Unreleased]` in `CHANGELOG.md`.
-- Security issues go through [SECURITY.md](SECURITY.md), never a public issue.
+Before you change the box, the tunnel or the restore, read
+[docs/ARCHITECTURE.md](docs/ARCHITECTURE.md): how the pieces fit, what
+`kdev up` does step by step, how files persist, and how the code is laid out.
By taking part you agree to the [Code of Conduct](CODE_OF_CONDUCT.md).
+
+## Ways to help
+
+- **Ask a question** in [Discussions](https://github.com/tushar-mahalya/kdev/discussions):
+ how to do something, or whether what you see is expected.
+- **Report a bug.** Open an issue with what you ran, what you expected and
+ what happened. The output of the same command with `-v` (`kdev -v up …`)
+ helps most. It logs every Kaggle API call; check it for anything you would
+ rather not share before you paste it.
+- **Fix something.** Issues labelled
+ [`good first issue`](https://github.com/tushar-mahalya/kdev/labels/good%20first%20issue)
+ are small and well described; [`help wanted`](https://github.com/tushar-mahalya/kdev/labels/help%20wanted)
+ ones are bigger. Say in the issue that you are on it, so two people don't
+ fix the same thing.
+- **Improve the docs.** If something was unclear when you set up, it will
+ be unclear to the next person too. The user docs live in
+ [`website/src/content/docs/`](website/src/content/docs/).
+- **Report a vulnerability** privately, as [SECURITY.md](SECURITY.md)
+ describes, never in a public issue.
+
+## Set up
+
+You need Python 3.11+ and [uv](https://docs.astral.sh/uv/).
+
+```bash
+git clone https://github.com/tushar-mahalya/kdev && cd kdev
+uv sync
+uv run pre-commit install # hooks on commit, tests on push
+uv run basedpyright # basic-mode type check, also on every commit
+uv run pytest # unit and regression tests, no network needed
+uv run pytest --cov # the same suite with a local coverage report
+uv run kdev -v … # the working tree, with API logging
+```
+
+Every commit runs formatting, lint, type-checking (`basedpyright`), a secrets scan
+(`detect-secrets`, private-key detection), config validation and a lockfile
+check; every push runs the tests. CI runs the same hooks, the tests on Python
+3.11–3.13, a build-and-install check, and `gitleaks` over the full history.
+
+## Trying a change against real Kaggle
+
+The test suite needs no Kaggle account, and most changes need nothing more.
+When yours touches the box, the tunnel or the restore, try it for real:
+
+- Use **your own** workspace (`kdev workspace create --group `), not a
+ shared one someone else works in.
+- Start **CPU boxes**: `uv run kdev up --gpu none --hours 1`. They cost no GPU
+ quota. A GPU run spends the quota of whichever account starts it.
+- `kdev down` when you are done, and `kdev workspace files` to see exactly
+ what was saved.
+
+## How the code is laid out
+
+The full picture, with a diagram, is in
+[docs/ARCHITECTURE.md](docs/ARCHITECTURE.md#how-the-code-is-laid-out). In short:
+
+| layer | rule |
+|---|---|
+| `commands/` | parse arguments, call logic, render with `ui`; no API calls of their own beyond reads |
+| `session`, `persistence`, `quota`, `notebook` | the behaviour; testable without a terminal |
+| `kdev_box.py` | standard library only; it's shipped into the container and runs there |
+| `ui.py` | every visual element, with its tokens and rules written down at the top |
+| `errors.KdevError` | every failure a user can act on: a message and the command that fixes it |
+
+Tests are split by module. `tests/test_cli.py` runs every command through
+the real entry point against a fake Kaggle. `tests/test_kdev_box.py` runs the
+on-box restore against a temporary directory.
+
+## Pull requests
+
+- **One change per pull request**, with a description of the problem it
+ solves and how you checked it.
+- **A bug fix comes with a test** that fails without the fix. New behaviour
+ comes with the smallest test that would catch it breaking. Tests stay
+ offline: use the fake Kaggle in `tests/test_cli.py`.
+- **Match the code around you.** `kdev_box.py` stays standard-library only.
+ Everything the user sees goes through `ui.py`. A failure the user can act on
+ is a `KdevError` with the command that fixes it.
+- **Commit messages** follow [Conventional Commits](https://www.conventionalcommits.org/)
+ (`fix:`, `feat:`, `docs:`, `test:`, `ci:`, `refactor:`), with the *why* in
+ the body.
+- **Record what users will notice** under `## [Unreleased]` in
+ [CHANGELOG.md](CHANGELOG.md). If a command or its behaviour changes, update
+ the [README](README.md), the [website docs](website/src/content/docs/) and,
+ for how things work inside, [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md).
+
+## Releasing
+
+For maintainers: bump `version` in `pyproject.toml`, move the `Unreleased`
+notes in `CHANGELOG.md` under the new version, then
+`git tag vX.Y.Z && git push origin vX.Y.Z`. The release workflow checks that
+the tag matches the version, runs the tests, and publishes a GitHub release
+with the wheel and sdist attached.
+
+## License
+
+kdev is [MIT licensed](LICENSE). By contributing, you agree that your
+contributions are licensed under the same terms.
diff --git a/README.md b/README.md
index 847ddf2..0b1e98d 100644
--- a/README.md
+++ b/README.md
@@ -12,413 +12,111 @@
+
-
+
-
+## Why kdev
-```bash
-kdev setup # once per machine
-kdev up # start the box (or connect to the one that is running)
-ssh kaggle # or VS Code → Remote-SSH → kaggle
-kdev down # optional: stop early and hand the quota back
-```
+Kaggle gives every account free GPU hours, but only inside a notebook. kdev
+turns that notebook into a machine you can `ssh` into or open in VS Code.
-- **One box, pooled quota.** Every account in your group runs the same shared
- notebook on its own 30 GPU-hours a week. When one runs short, `kdev up` asks
- which account takes over.
+- **One box, pooled quota.** Every account in your Kaggle group runs the same
+ shared notebook on its own weekly GPU hours. When one runs short, `kdev up`
+ asks which account takes over.
- **Files that persist.** Whatever is in `/kaggle/working` when a session ends
- comes back at the next start, however it ended: `kdev down`, the Kaggle UI,
- a timeout, a crash, your wifi dropping.
+ comes back at the next start, however it ended: `kdev down`, a timeout, a
+ crash, your wifi dropping.
- **A real server.** A stable hostname over Cloudflare Tunnel, public-key SSH,
- your notebook's full environment (CUDA, Python, Kaggle variables) in every
- session, interactive or not.
-
----
-
-## Contents
-
-- [How it works](#how-it-works)
-- [Install and set up](#install-and-set-up)
-- [Everyday use](#everyday-use)
-- [Your files](#your-files)
-- [Several accounts, several machines](#several-accounts-several-machines)
-- [Commands](#commands)
-- [Settings](#settings)
-- [Troubleshooting](#troubleshooting)
-- [Security and limits](#security-and-limits)
-- [Contributing](#contributing)
-
----
-
-## How it works
-
-Kaggle's API can save a notebook and run it, but it has no "give me a shell"
-call. kdev writes a small cell at the top of your notebook. When Kaggle runs
-that cell, it turns the container into an SSH server and connects it to your
-Cloudflare tunnel. Your laptop then reaches it by name.
-
-```mermaid
-flowchart LR
- subgraph laptop["Your machine"]
- cli["kdev"]
- code["VS Code / ssh"]
- end
- subgraph kaggle["Kaggle"]
- api["Kaggle API"]
- store[("Notebook versions = saved /kaggle/working")]
- subgraph box["The box (a notebook session)"]
- cell["kdev's cell: sshd · cloudflared · restore"]
- work["/kaggle/working"]
- end
- end
- edge(("Cloudflare edge"))
-
- cli -- "save + run notebook, quota, logs" --> api
- api --> box
- cell -- "outbound tunnel" --> edge
- code -- "ssh kaggle" --> edge
- edge --> cell
- work -. "saved when the session ends" .-> store
- store -. "restored at the next start" .-> work
-```
-
-Nothing listens on a public port: the box dials *out* to Cloudflare, and your
-`ssh` reaches it through Cloudflare by hostname.
-
-### What `kdev up` does
-
-```mermaid
-sequenceDiagram
- autonumber
- actor You
- participant K as kdev
- participant API as Kaggle API
- participant B as The box
- participant CF as Cloudflare
-
- You->>K: kdev up
- K->>API: session status (already running?)
- alt a box is running
- K-->>You: connect to it — no second session
- else nothing running
- K->>API: which saved version to build on (walk back from latest)
- K->>API: SaveKernel: your notebook + kdev's cell, "Save & Run All"
- API->>B: start the container
- B->>B: record the plan in .kdev/state.json (before anything slow)
- B->>B: sshd, environment, git clone
- B->>CF: open the tunnel
- B-->>K: KDEV_READY (via the session log)
- K->>API: fresh file list + signed URLs for the saved version
- K->>B: "restore this" (over ssh)
- B->>API: download every file straight from Kaggle
- B->>B: put back symlinks, empty dirs, exec bits
- K->>B: ssh check
- K-->>You: ready — open VS Code or a shell
- end
-```
-
-The board you watch while this happens shows each step's own clock, so a slow
-queue looks like a queue and not a hang:
-
-```
- alice · T4 ×2 · 9h 1m52s
- ✓ Submitting 1s
- ✓ Waiting for a machine 1m21s
- ✓ Installing SSH server 14s
- ✓ Exporting notebook environment 0s
- ✓ Syncing workspace 0s
- ✓ Starting Cloudflare tunnel 4s
- ⠹ Restoring your files 9s
- 812/1505 files
- ○ Ready
-```
-
----
-
-## Install and set up
+ and your notebook's full environment (CUDA, Python, Kaggle variables).
+ No port is opened on the box.
-
-
-
+## Install
Needs Python 3.11+, `ssh`, and a Kaggle account in a Kaggle group.
```bash
uv tool install kdev-cli # or: pipx install kdev-cli
-kdev setup
-```
-
-The package is `kdev-cli` (PyPI does not allow `kdev`); the command it installs
-is `kdev`. Upgrade with `uv tool upgrade kdev-cli`.
-
-To run what is on `main` but not released yet:
-`uv tool install git+https://github.com/tushar-mahalya/kdev`.
-
-`kdev setup` does only what is missing, so it is safe to run again at any
-time. It will:
-
-1. find (or create) your SSH key;
-2. fetch Cloudflare's `cloudflared` if you don't have it — a system install
- (`brew install cloudflared`) always wins;
-3. sign a Kaggle account in, through your browser (OAuth);
-4. join your group's workspace notebook, or create one;
-5. set up the tunnel — **skipped on a second machine**, which takes the tunnel
- from the notebook itself.
-
-### The tunnel
-
-With a domain on Cloudflare (free plan, domain showing *Active*):
-
-```bash
-kdev tunnel setup # opens a browser once to authorise your Cloudflare account
-```
-
-It creates the tunnel and its DNS record, and stores the credentials. There's
-nothing to configure in the Zero Trust dashboard. Re-running it is a no-op; it
-never repoints a hostname that belongs to something else without asking.
-
-| | Named tunnel (your domain) | Quick tunnel (no domain) |
-|---|---|---|
-| Setup | once, ~2 minutes | none |
-| Hostname | the same forever | new every session |
-| After a network drop | same name, `ssh` just reconnects | new name; `kdev up` finds it |
-| Speed | identical | identical |
-
-### The workspace
-
-A Kaggle group can't own anything, so one account owns the notebook and shares
-it with the group as **Can Edit**:
-
-```bash
-kdev workspace create --group # the owner, once
-kdev workspace join # everyone else
-```
-
----
-
-## Everyday use
-
-```bash
-kdev # overview: the box, every account's quota, what to do next
-kdev up # start the box, or connect to the one already running
-kdev status # running? who started it? when does it end? files back?
-kdev down # stop it now
-```
-
-Bare `kdev` in a terminal ends with a menu of the actions that make sense
-right now: connect or stop when the box is up; start it, or switch account,
-when it isn't.
-
-The box you start is a setting — pick once, and `kdev up` stops asking:
-
-```bash
-kdev config set gpu t4
-kdev config set hours 9
```
-**Leaving needs no ceremony.** Close the laptop, lose the wifi, walk away.
-The box runs to the end of its session and saves as it stops. `kdev down` is
-for stopping *early*, to hand the quota back.
+The package is `kdev-cli`; the command it installs is `kdev`. Upgrade with
+`uv tool upgrade kdev-cli`.
----
-
-## Your files
-
-`/kaggle/working` behaves like a disk that is always there.
-
-**Kaggle saves it.** When a "Save & Run All" session ends, Kaggle keeps
-`/kaggle/working` as that version's output — and it does so however the
-session ends. A clean exit, a crash and a cancel were all measured to save
-every file up to the moment the container stopped. Older versions stay
-readable (`v1`, `v2`, …), and they belong to the **notebook**, not to an account.
-
-**kdev puts it back.** Kaggle starts every batch session with an empty
-`/kaggle/working`; its "Persistence" setting only covers the web editor. So
-each `kdev up` works out which saved version you left off at, and the new box
-downloads it before you connect.
-
-```mermaid
-stateDiagram-v2
- direction LR
- [*] --> Running: kdev up
- Running --> Saved: the session ends, however it ends
- Saved --> Running: kdev up, any account or machine
-```
-
-| how the last session ended | what the next `kdev up` gives you |
-|---|---|
-| `kdev down` | everything |
-| `kdev down`, then `kdev up` straight away | everything: `up` waits for the save first (about 2 min per GB) |
-| **Stop session** in the Kaggle UI | everything (a cancel still saves) |
-| the session's time ran out | everything (the box stops itself 2 min early) |
-| the tunnel process died | everything |
-| the box crashed | everything, up to the crash |
-| your laptop or network dropped | the box is still running: `kdev up` connects to it |
-| Kaggle's machine itself failed | not testable; a git remote covers it |
-
-### What kdev adds on top of Kaggle
-
-Kaggle's saved output keeps every regular file — thousands of them, dotfiles,
-`.git`, large binaries. It **drops symlinks and empty directories, and loses
-executable bits**, which would break a Python virtualenv. The box records
-those in `.kdev/meta.json` every 30 seconds, and the restore puts them back.
-
-### Picking the version to restore
-
-```mermaid
-flowchart TD
- start["latest saved version vN"] --> empty{"has files?"}
- empty -- no --> back["try v(N-1)"] --> empty
- empty -- yes --> state{"its .kdev/state.json says"}
- state -- "restored: true (or kdev never touched it)" --> one["restore vN alone"]
- state -- "restored: false, or files missing (cut short, or worked in before the restore)" --> stack["what vN never got from its base layers, then vN on top"]
-```
-
-A version with no files is a source-only save (group setup, a Quick Save), so
-kdev walks past it. A session that was stopped before its restore finished —
-or that you worked in before restoring — is not skipped: it gets stacked on
-the versions it was meant to be built on, so nothing done in it is lost. The
-layers underneath fill in only what that session's restore never delivered
-(the box logs each file as it lands, in `.kdev/fetched`), so a file you deleted
-there stays deleted.
-
-A restore never overwrites a file written in the current session, so it is
-safe to run again at any time:
+## Quick start
```bash
-kdev restore # finish or repeat the restore on the running box
-kdev restore --from v12 # add files v12 has that the box doesn't (not a rollback)
-kdev workspace files # what `kdev up` would restore (--version v12 for another)
-kdev backup # optional: an exact copy of the box on this machine
-```
-
-### Your own cells in the notebook
-
-kdev's cell sits on top, and **nothing below it runs**. When a session ends,
-later cells are blanked for that run, so a training cell can't start after
-`kdev down` and use quota. Your cells stay in the notebook, untouched.
-
-### Files made in the Kaggle web editor
-
-The editor's interactive session is the one place kdev can't reach: its files
-only reach the API when a version is saved. Kaggle describes Quick Save as
-saving the notebook "as displayed", which isn't a clear promise to save the
-working directory, so check with `kdev workspace files`. Everything made
-through kdev is covered.
-
----
-
-## Several accounts, several machines
-
-```mermaid
-flowchart TB
- subgraph group["Kaggle group (Can Edit on one notebook)"]
- a["account A · 30h GPU/week"]
- b["account B · 30h GPU/week"]
- c["account C · 30h GPU/week"]
- end
- nb[("the shared notebook + its saved versions")]
- a & b & c -- "each runs it on its own quota" --> nb
- l1["laptop 1"] & l2["laptop 2"] -- "kdev up / ssh" --> nb
+kdev setup # once per machine: SSH key, cloudflared, Kaggle sign-in, workspace, tunnel
+kdev up # start the box, or connect to the one already running
+ssh kaggle # or VS Code → Remote-SSH → kaggle
+kdev down # optional: stop early and hand the quota back
```
-- **Quota is per account.** A session is charged to the account that starts
- it, not to the notebook's owner (measured).
-- **Switching is a question, not a wall.** If the active account can't finish
- the session you asked for, `kdev up` shows every account's remaining hours
- and lets you pick. `kdev account use ` switches by hand.
-- **The box is still running?** `kdev up` from any account or machine
- connects to it instead of starting a second one.
-- **A new laptop.** `kdev setup` signs you in and joins the workspace. The
- tunnel and git settings come from the notebook, and the new laptop's SSH
- key is saved in the workspace (`.kdev/authorized_keys`). So every machine
- that has used it can reach every later box.
-- **Stopping a box someone else started.** Kaggle only lets the account that
- started a session cancel it. When the box doesn't answer, `kdev down` finds
- out which account that was and cancels as it — or tells you which account
- has to.
+`kdev setup` only does what is missing, so it is safe to run again. Two parts
+of it you may want to run on their own:
-```bash
-kdev account add alice # sign an account in (browser); re-run to refresh it
-kdev account # every account and its GPU/TPU hours left
-kdev account use alice # it runs the next box
-```
+- **The tunnel.** With a domain on Cloudflare, `kdev tunnel setup` creates a
+ named tunnel with a hostname that never changes. Without one, `kdev setup`
+ offers a free quick tunnel, on a new hostname each session.
+- **The workspace.** One account owns the notebook and shares it with the
+ group: `kdev workspace create --group `, once. Everyone else
+ runs `kdev workspace join`.
----
+Leaving needs no ceremony: close the laptop and walk away. The box runs to the
+end of its session and saves as it stops.
-## Commands
+## Everyday commands
| command | what it does |
|---|---|
-| `kdev` | overview of the box, accounts and workspace; in a terminal, the next actions |
-| `kdev setup` | get this machine ready; only does what is missing |
+| `kdev` | the home screen: the box and every account's quota, live; one key per action |
| `kdev up` | start the box, or connect to the running one |
| `kdev down` | stop the box; files are saved however it stops |
-| `kdev ssh [-- ARGS]` | shell on the box; ssh's exit code is kdev's |
-| `kdev forward PORT...` | forward localhost ports to services on the box (`9000:8888` remaps a port) |
-| `kdev status [--json]` | running?, started by, ends at, reachable, restore state |
-| `kdev history [-n N] [--json]` | recent saved sessions, who ran them and how they ended |
-| `kdev logs [-n N] [--all]` | the session log |
-| `kdev restore [--from vN \| --from-backup]` | put saved files back |
-| `kdev backup` | copy the running box to this machine |
-| `kdev account [--json]` | accounts and quota |
-| `kdev account add \| use \| remove` | manage accounts |
-| `kdev workspace` | the notebook: owner, sharing, members, saved versions |
-| `kdev workspace files [--version vN] [--json]` | what a saved version holds |
-| `kdev workspace join \| use \| create \| share` | choose, make, or re-share the notebook |
-| `kdev config` / `set KEY VALUE` / `unset KEY` | settings |
-| `kdev tunnel` / `tunnel setup` | the Cloudflare tunnel |
-| `kdev doctor [--fix]` | check everything; exits 1 if something is broken |
+| `kdev ssh` | open a shell on the box |
+| `kdev status` | running? who started it? when does it end? files back? |
+| `kdev forward PORT` | reach a service on the box through localhost (`9000:8888` remaps) |
+| `kdev logs` | stream the session's log |
+| `kdev history` | past saved sessions, who ran them and how they ended |
+| `kdev restore` | finish or repeat the restore of your saved files |
+| `kdev backup` | copy the running box's files to this machine |
+| `kdev account` | accounts and their GPU/TPU hours left (`add`, `use`, `remove`) |
+| `kdev workspace` | the shared notebook (`files`, `join`, `use`, `create`, `share`) |
+| `kdev doctor` | check everything kdev depends on |
+
+Run bare `kdev` and press a key: `1` starts the box, `s` shows its status, `q`
+quits. The highlighted item always shows the command it runs, so everything
+the menu does you can also type or script.
Useful flags on `kdev up`: `--gpu none|t4|p100|tpu`, `--hours N`,
`--account NAME`, `--open code|shell|none`, `--no-restore`, `--replace`, `-y`.
-
-Global: `-v` logs every Kaggle API call with its status and timing;
-`--version`; `--install-completion` for shell completion.
-
-**Exit codes:** `0` success · `1` failed (the message says why and what to
-run) · `2` usage mistake · `130` cancelled.
-
-**Scripting:** every prompt has a flag, and a prompt never appears without a
-terminal. `status`, `history`, `account` and `workspace files` take `--json` (data on
-stdout, errors on stderr). `NO_COLOR` is honoured.
-
----
+Add `-v` to any command to log each Kaggle API call. `status`, `history`,
+`account` and `workspace files` take `--json` for scripts.
+See the [full command reference](https://kdev-cli.pages.dev/docs/commands/).
## Settings
-`kdev config` lists them; secrets are never shown.
+Pick once with `kdev config set`, and `kdev up` stops asking:
-| setting | meaning |
-|---|---|
-| `gpu` | accelerator for `kdev up`: `none`, `t4`, `p100`, `tpu` (and `l4`, `a100`, `h100` where your account has them) |
-| `hours` | session length for `kdev up` (Kaggle's limit: 12h, 9h on TPU) |
-| `git-remote` | a repo cloned at boot, pushed every 15 minutes and at teardown |
-| `git-deploy-key` | path to that repo's deploy key |
-| `ssh-key` | path to this machine's public key |
-| `ssh-alias` | the name in `~/.ssh/config` (default `kaggle`) |
-| `tunnel-hostname` | the box's hostname |
-| `tunnel-token` | a Cloudflare-dashboard tunnel token, instead of `kdev tunnel setup` |
-
-Stored in `~/.config/kdev/config.json` (mode 0600). Move it with
-`KDEV_CONFIG_DIR`.
+```bash
+kdev config set gpu t4 # none, t4, p100, tpu (and l4, a100, h100 where available)
+kdev config set hours 9 # Kaggle's limit: 12h, 9h on TPU
+kdev config # list every setting; secrets are never shown
+```
----
+Other settings cover a git remote that the box clones at boot and pushes every
+15 minutes, your SSH key and alias, and the tunnel. They are stored in
+`~/.config/kdev/config.json` (mode 0600). All of them:
+[Settings](https://kdev-cli.pages.dev/docs/settings/).
## Troubleshooting
@@ -428,164 +126,37 @@ kdev -v status # the same command, with each Kaggle API call logged
kdev logs # what the box itself is saying
```
-| you see | what to do |
-|---|---|
-| `… is not signed in` | `kdev account add ` refreshes that account |
-| `ssh does not answer` right after starting | give Cloudflare a minute; `kdev ssh` |
-| `The session never reported a tunnel` | `kdev logs`; the message names the command to stop it |
-| `Only X can cancel session …` | sign X in (`kdev account add`) or stop it in the Kaggle UI |
-| `Not all your files are back yet` | `kdev restore` finishes it |
-| `your last box is still saving your files` | nothing: `kdev up` waits, then starts |
-| `… has a session kdev cannot reach` | someone is using the notebook in the Kaggle editor |
-
----
-
-## Security and limits
-
-- **Access** is public-key SSH only; password login is disabled. The box
- accepts every key saved in the workspace's `.kdev/authorized_keys`: remove a
- line there to revoke a machine.
-- **Secrets in the notebook.** Kaggle has no API for notebook Secrets, so the
- tunnel credentials (and a git deploy key, if you set one) sit in the private
- notebook's source. Anyone with Can Edit can read them. Scope a deploy key to
- one repository.
-- **Host keys.** Every session is a new container with a new host key, so the
- `kaggle` block in `~/.ssh/config` doesn't pin one; a pinned key would break
- VS Code on every other machine. Only a box holding the workspace's tunnel
- credentials can answer on that hostname, and anyone holding those can
- already edit the notebook that builds the box.
-- **Simultaneous starts converge on one box.** If several machines run
- `kdev up` together, the lowest live notebook version wins. Each losing
- client stops its own run as the account that started it, waits for the
- cancellation to finish, then connects to the winner. Status, logs and stop
- commands find that winner even when a cancelled version is newer. Startup
- verifies the SSH session before restoring files; cancelled contenders do
- not replace the winner's saved workspace. Their output remains available
- through `kdev restore --from vN`. If Kaggle cannot confirm a cancellation,
- kdev reports the run to stop and does not declare the shared tunnel ready.
-- **Metadata in the last 30 s.** After a hard kill, symlinks, empty folders and
- executable bits created in the final 30 seconds are gone. File contents never
- are.
-- **Nothing sensitive in crash reports.** kdev never prints tracebacks with
- local variables; `-v` shows a traceback when you ask for one.
-- **Kaggle's limits:** 12h per CPU/GPU session and 9h on TPU; weekly GPU/TPU
- quota per account; 20 GB of `/kaggle/working` saved per version.
-- **Kaggle's terms.** Kaggle allows one account per person, and restricts
- tunnelling out of notebooks; accounts have been banned for both. kdev does
- nothing to hide what it does. Know the rules you are working under.
-
----
+Most messages name the command that fixes them. Common ones are listed in
+[Troubleshooting](https://kdev-cli.pages.dev/docs/troubleshooting/).
+
+## Documentation
+
+- [Install and set up](https://kdev-cli.pages.dev/docs/): the tunnel and the workspace in detail
+- [How it works](https://kdev-cli.pages.dev/docs/how-it-works/): the architecture, what `kdev up` does, how files persist, with diagrams
+- [Your files](https://kdev-cli.pages.dev/docs/files/) and [Several accounts, several machines](https://kdev-cli.pages.dev/docs/accounts/)
+- [Security and limits](https://kdev-cli.pages.dev/docs/security/)
+- [Architecture for contributors](https://github.com/tushar-mahalya/kdev/blob/main/docs/ARCHITECTURE.md), including how the code is laid out
## Contributing
-Contributions are welcome — bug reports, fixes, docs and features alike. kdev
-is small and opinionated, so for anything bigger than a fix, open an issue
-first and say what you want to change and why. It saves you writing code that
-goes a different way than the project.
-
-### Ways to help
-
-- **Ask a question** in [Discussions](https://github.com/tushar-mahalya/kdev/discussions):
- how to do something, or whether what you see is expected.
-- **Report a bug.** Open an issue with what you ran, what you expected and
- what happened. The output of the same command with `-v` (`kdev -v up …`)
- helps most. It logs every Kaggle API call; check it for anything you would
- rather not share before you paste it.
-- **Fix something.** Issues labelled
- [`good first issue`](https://github.com/tushar-mahalya/kdev/labels/good%20first%20issue)
- are small and well described; [`help wanted`](https://github.com/tushar-mahalya/kdev/labels/help%20wanted)
- ones are bigger. Say in the issue that you are on it, so two people don't
- fix the same thing.
-- **Improve the docs.** If something here was unclear when you set up, it will
- be unclear to the next person too.
-- **Report a vulnerability** privately, as [SECURITY.md](https://github.com/tushar-mahalya/kdev/blob/main/SECURITY.md)
- describes, never in a public issue.
-
-### Set up
-
-You need Python 3.11+ and [uv](https://docs.astral.sh/uv/).
+Bug reports, fixes, docs and features are welcome. For anything bigger than a
+fix, open an issue first. Questions go to
+[Discussions](https://github.com/tushar-mahalya/kdev/discussions). How to set
+up, test without spending GPU quota, and send a pull request:
+[CONTRIBUTING.md](https://github.com/tushar-mahalya/kdev/blob/main/CONTRIBUTING.md).
-```bash
-git clone https://github.com/tushar-mahalya/kdev && cd kdev
-uv sync
-uv run pre-commit install # hooks on commit, tests on push
-uv run basedpyright # basic-mode type check, also on every commit
-uv run pytest # unit and regression tests, no network needed
-uv run pytest --cov # the same suite with a local coverage report
-uv run kdev -v … # the working tree, with API logging
-```
+## Security
-Every commit runs formatting, lint, type-checking (`basedpyright`), a secrets scan
-(`detect-secrets`, private-key detection), config validation and a lockfile
-check; every push runs the tests. CI runs the same hooks, the tests on Python
-3.11–3.13, a build-and-install check, and `gitleaks` over the full history.
-
-### Trying a change against real Kaggle
-
-The test suite needs no Kaggle account, and most changes need nothing more.
-When yours touches the box, the tunnel or the restore, try it for real:
-
-- Use **your own** workspace (`kdev workspace create --group `), not a
- shared one someone else works in.
-- Start **CPU boxes**: `uv run kdev up --gpu none --hours 1`. They cost no GPU
- quota. A GPU run spends the quota of whichever account starts it.
-- `kdev down` when you are done, and `kdev workspace files` to see exactly
- what was saved.
-
-### How the code is laid out
-
-```mermaid
-flowchart LR
- cli["cli.py entry point, one error boundary"]
- cmds["commands/ box · account · workspace config · tunnel · doctor · home"]
- logic["session · persistence quota · notebook · bootstrap"]
- edges["api · auth · config tunnel · cloudflared · sshcfg"]
- ui["ui.py the design system"]
- kbox["kdev_box.py runs on the box"]
-
- cli --> cmds --> logic --> edges
- cmds --> ui
- logic -. "bootstrap ships it inside kdev's cell" .-> kbox
-```
+Access is public-key SSH only. Kaggle has no API for notebook Secrets, so the
+tunnel credentials sit in the private notebook's source, readable by anyone
+with Can Edit. Kaggle allows one account per person and restricts tunnelling
+out of notebooks; know the rules you are working under. Details are in
+[Security and limits](https://kdev-cli.pages.dev/docs/security/). Report a
+vulnerability privately, as
+[SECURITY.md](https://github.com/tushar-mahalya/kdev/blob/main/SECURITY.md)
+describes.
-| layer | rule |
-|---|---|
-| `commands/` | parse arguments, call logic, render with `ui`; no API calls of their own beyond reads |
-| `session`, `persistence`, `quota`, `notebook` | the behaviour; testable without a terminal |
-| `kdev_box.py` | standard library only; it's shipped into the container and runs there |
-| `ui.py` | every visual element, with its tokens and rules written down at the top |
-| `errors.KdevError` | every failure a user can act on: a message and the command that fixes it |
-
-Tests are split by module. `tests/test_cli.py` runs every command through
-the real entry point against a fake Kaggle. `tests/test_kdev_box.py` runs the
-on-box restore against a temporary directory.
-
-### Pull requests
-
-- **One change per pull request**, with a description of the problem it
- solves and how you checked it.
-- **A bug fix comes with a test** that fails without the fix. New behaviour
- comes with the smallest test that would catch it breaking. Tests stay
- offline: use the fake Kaggle in `tests/test_cli.py`.
-- **Match the code around you.** `kdev_box.py` stays standard-library only.
- Everything the user sees goes through `ui.py`. A failure the user can act on
- is a `KdevError` with the command that fixes it.
-- **Commit messages** follow [Conventional Commits](https://www.conventionalcommits.org/)
- (`fix:`, `feat:`, `docs:`, `test:`, `ci:`, `refactor:`), with the *why* in
- the body.
-- **Record what users will notice** under `## [Unreleased]` in
- [CHANGELOG.md](https://github.com/tushar-mahalya/kdev/blob/main/CHANGELOG.md), and update this README if a command or its
- behaviour changes.
-
-### Releasing
-
-For maintainers: bump `version` in `pyproject.toml`, move the `Unreleased`
-notes in `CHANGELOG.md` under the new version, then
-`git tag vX.Y.Z && git push origin vX.Y.Z`. The release workflow checks that
-the tag matches the version, runs the tests, and publishes a GitHub release
-with the wheel and sdist attached.
-
-### License
-
-kdev is [MIT licensed](https://github.com/tushar-mahalya/kdev/blob/main/LICENSE). By contributing, you agree that your
-contributions are licensed under the same terms.
+## License
+
+[MIT](https://github.com/tushar-mahalya/kdev/blob/main/LICENSE). kdev is an
+independent project, not affiliated with Kaggle, Google or Cloudflare.
diff --git a/SECURITY.md b/SECURITY.md
index b155fc8..7531eb2 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -40,7 +40,7 @@ Sigstore-signed build provenance for its wheel and sdist. To check that a file
was built from this repository by its release workflow:
```bash
-gh attestation verify kdev_cli-0.1.4-py3-none-any.whl --repo tushar-mahalya/kdev
+gh attestation verify kdev_cli-0.2.0-py3-none-any.whl --repo tushar-mahalya/kdev
```
The same signed provenance is attached to each GitHub release as
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
new file mode 100644
index 0000000..4803f86
--- /dev/null
+++ b/docs/ARCHITECTURE.md
@@ -0,0 +1,336 @@
+# How kdev works
+
+This is the technical companion to the [README](../README.md): how kdev turns a
+Kaggle notebook into a remote dev box, how your files survive between
+sessions, how several accounts and machines share one box, the security model,
+and how the code is laid out. The same material, with drawn diagrams, is on the
+website at [kdev-cli.pages.dev/docs/how-it-works](https://kdev-cli.pages.dev/docs/how-it-works/).
+
+- [The big picture](#the-big-picture)
+- [What `kdev up` does](#what-kdev-up-does)
+- [Your files](#your-files)
+- [Picking the version to restore](#picking-the-version-to-restore)
+- [Several accounts, several machines](#several-accounts-several-machines)
+- [Security and limits](#security-and-limits)
+- [How the code is laid out](#how-the-code-is-laid-out)
+
+---
+
+## The big picture
+
+Kaggle's API can save a notebook and run it, but it has no "give me a shell"
+call. kdev writes a small cell at the top of your notebook. When Kaggle runs
+that cell, it turns the container into an SSH server and connects it to your
+Cloudflare tunnel. Your laptop then reaches it by name.
+
+```mermaid
+flowchart LR
+ subgraph laptop["Your machine"]
+ cli["kdev"]
+ code["VS Code / ssh"]
+ end
+ subgraph kaggle["Kaggle"]
+ api["Kaggle API"]
+ store[("Notebook versions = saved /kaggle/working")]
+ subgraph box["The box (a notebook session)"]
+ cell["kdev's cell: sshd · cloudflared · restore"]
+ work["/kaggle/working"]
+ end
+ end
+ edge(("Cloudflare edge"))
+
+ cli -- "save + run notebook, quota, logs" --> api
+ api --> box
+ cell -- "outbound tunnel" --> edge
+ code -- "ssh kaggle" --> edge
+ edge --> cell
+ work -. "saved when the session ends" .-> store
+ store -. "restored at the next start" .-> work
+```
+
+Nothing listens on a public port: the box dials *out* to Cloudflare, and your
+`ssh` reaches it through Cloudflare by hostname.
+
+The box reports back through its own session log: `KDEV_STAGE` lines drive the
+progress board, `KDEV_READY` carries the hostname, `KDEV_ALIVE` is a heartbeat
+with the seconds left, and `KDEV_DONE` marks the end.
+
+### The tunnel
+
+With a domain on Cloudflare (free plan, domain showing *Active*),
+`kdev tunnel setup` opens a browser once to authorise your Cloudflare account,
+then creates the tunnel and its DNS record and stores the credentials. There's
+nothing to configure in the Zero Trust dashboard. Re-running it is a no-op; it
+never repoints a hostname that belongs to something else without asking.
+
+| | Named tunnel (your domain) | Quick tunnel (no domain) |
+|---|---|---|
+| Setup | once, ~2 minutes | none |
+| Hostname | the same forever | new every session |
+| After a network drop | same name, `ssh` just reconnects | new name; `kdev up` finds it |
+| Speed | identical | identical |
+
+### The workspace
+
+A Kaggle group can't own anything, so one account owns the notebook and shares
+it with the group as **Can Edit** (`kdev workspace create --group `, once);
+everyone else runs `kdev workspace join`.
+
+---
+
+## What `kdev up` does
+
+```mermaid
+sequenceDiagram
+ autonumber
+ actor You
+ participant K as kdev
+ participant API as Kaggle API
+ participant B as The box
+ participant CF as Cloudflare
+
+ You->>K: kdev up
+ K->>API: session status (already running?)
+ alt a box is running
+ K-->>You: connect to it — no second session
+ else nothing running
+ K->>API: which saved version to build on (walk back from latest)
+ K->>API: SaveKernel: your notebook + kdev's cell, "Save & Run All"
+ API->>B: start the container
+ B->>B: record the plan in .kdev/state.json (before anything slow)
+ B->>B: sshd, environment, git clone
+ B->>CF: open the tunnel
+ B-->>K: KDEV_READY (via the session log)
+ K->>B: ssh check: is this the session we started?
+ K->>API: fresh file list + signed URLs for the saved version
+ K->>B: "restore this" (over ssh)
+ B->>API: download every file straight from Kaggle
+ B->>B: put back symlinks, empty dirs, exec bits
+ K->>B: ssh check
+ K-->>You: ready — open VS Code or a shell
+ end
+```
+
+kdev verifies over ssh that the tunnel reaches the session it started before
+it restores anything, and checks ssh once more before it calls the box ready.
+The board you watch while this happens shows each step's own clock, so a slow
+queue looks like a queue and not a hang.
+
+### Your own cells in the notebook
+
+kdev's cell sits on top, and **nothing below it runs**. When a session ends,
+later cells are blanked for that run, so a training cell can't start after
+`kdev down` and use quota. Your cells stay in the notebook, untouched.
+
+---
+
+## Your files
+
+`/kaggle/working` behaves like a disk that is always there.
+
+**Kaggle saves it.** When a "Save & Run All" session ends, Kaggle keeps
+`/kaggle/working` as that version's output — and it does so however the
+session ends. A clean exit, a crash and a cancel were all measured to save
+every file up to the moment the container stopped. Older versions stay
+readable (`v1`, `v2`, …), and they belong to the **notebook**, not to an account.
+
+**kdev puts it back.** Kaggle starts every batch session with an empty
+`/kaggle/working`; its "Persistence" setting only covers the web editor. So
+each `kdev up` works out which saved version you left off at, and the new box
+downloads it before you connect.
+
+```mermaid
+stateDiagram-v2
+ direction LR
+ [*] --> Running: kdev up
+ Running --> Saved: the session ends, however it ends
+ Saved --> Running: kdev up, any account or machine
+```
+
+| how the last session ended | what the next `kdev up` gives you |
+|---|---|
+| `kdev down` | everything |
+| `kdev down`, then `kdev up` straight away | everything: `up` waits for the save first (about 2 min per GB) |
+| **Stop session** in the Kaggle UI | everything (a cancel still saves) |
+| the session's time ran out | everything (the box stops itself 2 min early) |
+| the tunnel process died | everything |
+| the box crashed | everything, up to the crash |
+| your laptop or network dropped | the box is still running: `kdev up` connects to it |
+| Kaggle's machine itself failed | not testable; a git remote covers it |
+
+### What kdev adds on top of Kaggle
+
+Kaggle's saved output keeps every regular file — thousands of them, dotfiles,
+`.git`, large binaries. It **drops symlinks and empty directories, and loses
+executable bits**, which would break a Python virtualenv. The box records
+those in `.kdev/meta.json` every 30 seconds, and the restore puts them back.
+
+The files under `/kaggle/working/.kdev/`:
+
+| file | what it holds |
+|---|---|
+| `state.json` | the plan for this session (which versions to restore), written before anything slow, and whether the restore finished |
+| `meta.json` | symlinks, empty directories and executable bits, refreshed every 30 seconds |
+| `fetched` | every file the restore delivered, logged as it lands |
+| `authorized_keys` | the SSH key of every machine that has used the workspace |
+
+### Backups and git
+
+- With `git-remote` set, the box clones the repo at boot, commits and pushes
+ every 15 minutes, and once more at teardown. It is the one copy that survives
+ a failure of Kaggle's machine itself.
+- `kdev backup` copies the running box's `/kaggle/working` to this machine.
+ It is optional, since Kaggle keeps your files anyway; push it back with
+ `kdev restore --from-backup`.
+
+### Files made in the Kaggle web editor
+
+The editor's interactive session is the one place kdev can't reach: its files
+only reach the API when a version is saved. Kaggle describes Quick Save as
+saving the notebook "as displayed", which isn't a clear promise to save the
+working directory, so check with `kdev workspace files`. Everything made
+through kdev is covered.
+
+---
+
+## Picking the version to restore
+
+```mermaid
+flowchart TD
+ start["latest saved version vN"] --> empty{"has files?"}
+ empty -- no --> back["try v(N-1)"] --> empty
+ empty -- yes --> state{"its .kdev/state.json says"}
+ state -- "restored: true (or kdev never touched it)" --> one["restore vN alone"]
+ state -- "restored: false, or files missing (cut short, or worked in before the restore)" --> stack["what vN never got from its base layers, then vN on top"]
+```
+
+A version with no files is a source-only save (group setup, a Quick Save), so
+kdev walks past it. A session that was stopped before its restore finished —
+or that you worked in before restoring — is not skipped: it gets stacked on
+the versions it was meant to be built on, so nothing done in it is lost. The
+layers underneath fill in only what that session's restore never delivered
+(the box logs each file as it lands, in `.kdev/fetched`), so a file you deleted
+there stays deleted.
+
+The box downloads every file itself, straight from Kaggle's signed URLs, so
+your laptop only sends the plan. A restore never overwrites a file written in
+the current session, so it is safe to run again at any time:
+
+```bash
+kdev restore # finish or repeat the restore on the running box
+kdev restore --from v12 # add files v12 has that the box doesn't (not a rollback)
+kdev workspace files # what `kdev up` would restore (--version v12 for another)
+kdev backup # optional: an exact copy of the box on this machine
+```
+
+---
+
+## Several accounts, several machines
+
+```mermaid
+flowchart TB
+ subgraph group["Kaggle group (Can Edit on one notebook)"]
+ a["account A · 30h GPU/week"]
+ b["account B · 30h GPU/week"]
+ c["account C · 30h GPU/week"]
+ end
+ nb[("the shared notebook + its saved versions")]
+ a & b & c -- "each runs it on its own quota" --> nb
+ l1["laptop 1"] & l2["laptop 2"] -- "kdev up / ssh" --> nb
+```
+
+- **Quota is per account.** A session is charged to the account that starts
+ it, not to the notebook's owner (measured).
+- **Switching is a question, not a wall.** If the active account can't finish
+ the session you asked for, `kdev up` shows every account's remaining hours
+ and lets you pick. `kdev account use ` switches by hand.
+- **The box is still running?** `kdev up` from any account or machine
+ connects to it instead of starting a second one.
+- **A new laptop.** `kdev setup` signs you in and joins the workspace. The
+ tunnel and git settings come from the notebook, and the new laptop's SSH
+ key is saved in the workspace (`.kdev/authorized_keys`). So every machine
+ that has used it can reach every later box.
+- **Stopping a box someone else started.** Kaggle only lets the account that
+ started a session cancel it. When the box doesn't answer, `kdev down` finds
+ out which account that was and cancels as it — or tells you which account
+ has to.
+
+```bash
+kdev account add alice # sign an account in (browser); re-run to refresh it
+kdev account # every account and its GPU/TPU hours left
+kdev account use alice # it runs the next box
+```
+
+---
+
+## Security and limits
+
+- **Access** is public-key SSH only; password login is disabled. The box
+ accepts every key saved in the workspace's `.kdev/authorized_keys`: remove a
+ line there to revoke a machine.
+- **Secrets in the notebook.** Kaggle has no API for notebook Secrets, so the
+ tunnel credentials (and a git deploy key, if you set one) sit in the private
+ notebook's source. Anyone with Can Edit can read them. Scope a deploy key to
+ one repository.
+- **Host keys.** Every session is a new container with a new host key, so the
+ `kaggle` block in `~/.ssh/config` doesn't pin one; a pinned key would break
+ VS Code on every other machine. Only a box holding the workspace's tunnel
+ credentials can answer on that hostname, and anyone holding those can
+ already edit the notebook that builds the box.
+- **Simultaneous starts converge on one box.** If several machines run
+ `kdev up` together, the lowest live notebook version wins. Each losing
+ client stops its own run as the account that started it, waits for the
+ cancellation to finish, then connects to the winner. Status, logs and stop
+ commands find that winner even when a cancelled version is newer. Startup
+ verifies the SSH session before restoring files; cancelled contenders do
+ not replace the winner's saved workspace. Their output remains available
+ through `kdev restore --from vN`. If Kaggle cannot confirm a cancellation,
+ kdev reports the run to stop and does not declare the shared tunnel ready.
+- **Metadata in the last 30 s.** After a hard kill, symlinks, empty folders and
+ executable bits created in the final 30 seconds are gone. File contents never
+ are.
+- **Nothing sensitive in crash reports.** kdev never prints tracebacks with
+ local variables; `-v` shows a traceback when you ask for one.
+- **Local settings** live in `~/.config/kdev/config.json` (mode 0600), with
+ one Kaggle OAuth credential per account beside it; `KDEV_CONFIG_DIR` moves
+ them. `kdev config` never shows secrets.
+- **Kaggle's limits:** 12h per CPU/GPU session and 9h on TPU; weekly GPU/TPU
+ quota per account; 20 GB of `/kaggle/working` saved per version.
+- **Kaggle's terms.** Kaggle allows one account per person, and restricts
+ tunnelling out of notebooks; accounts have been banned for both. kdev does
+ nothing to hide what it does. Know the rules you are working under.
+
+To report a vulnerability, follow [SECURITY.md](../SECURITY.md).
+
+---
+
+## How the code is laid out
+
+```mermaid
+flowchart LR
+ cli["cli.py entry point, one error boundary"]
+ cmds["commands/ box · account · workspace config · tunnel · doctor · home"]
+ logic["session · persistence quota · notebook · bootstrap"]
+ edges["api · auth · config tunnel · cloudflared · sshcfg"]
+ ui["ui.py · menu.py the design system, the home screen"]
+ kbox["kdev_box.py runs on the box"]
+
+ cli --> cmds --> logic --> edges
+ cmds --> ui
+ logic -. "bootstrap ships it inside kdev's cell" .-> kbox
+```
+
+| layer | rule |
+|---|---|
+| `commands/` | parse arguments, call logic, render with `ui`; no API calls of their own beyond reads |
+| `session`, `persistence`, `quota`, `notebook` | the behaviour; testable without a terminal |
+| `kdev_box.py` | standard library only; it's shipped into the container and runs there |
+| `ui.py` | every visual element, with its tokens and rules written down at the top |
+| `menu.py` | the home screen: an inline prompt_toolkit app whose facts load on threads while it is already usable; each item knows the command it runs |
+| `errors.KdevError` | every failure a user can act on: a message and the command that fixes it |
+
+Tests are split by module. `tests/test_cli.py` runs every command through
+the real entry point against a fake Kaggle. `tests/test_kdev_box.py` runs the
+on-box restore against a temporary directory.
+
+For how to set up, test and send a change, see [CONTRIBUTING.md](../CONTRIBUTING.md).
diff --git a/pyproject.toml b/pyproject.toml
index a186f08..bde6e8e 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "kdev-cli"
-version = "0.1.4"
+version = "0.2.0"
description = "A Kaggle notebook as your remote dev box: SSH and VS Code in, files that persist across sessions, accounts and machines."
readme = "README.md"
requires-python = ">=3.11"
@@ -28,6 +28,9 @@ dependencies = [
"kaggle>=2.2,<3",
"typer>=0.27,<1",
"questionary>=2.0,<3",
+ # The home menu is a small prompt_toolkit app of its own (questionary is
+ # built on it too).
+ "prompt-toolkit>=3.0.36,<4",
"rich>=13,<16",
]
diff --git a/src/kdev/api.py b/src/kdev/api.py
index b12d546..6b00bed 100644
--- a/src/kdev/api.py
+++ b/src/kdev/api.py
@@ -11,6 +11,8 @@
import json
import logging
+import random
+import threading
import time
from collections.abc import Iterator
from dataclasses import dataclass
@@ -81,6 +83,41 @@ def headers(self) -> dict[str, str]:
RETRY_STATUS = frozenset({429, 500, 502, 503, 504})
+_pool: httpx.Client | None = None
+_pool_lock = threading.Lock()
+
+
+def _post(url: str, **kwargs: Any) -> httpx.Response:
+ """POST over one shared keep-alive pool: a fresh TLS handshake per call
+ cost ~0.3s each, and a status check makes several calls in a row. Tests
+ patch `httpx.post`, so a patched one is honoured."""
+ global _pool
+ if httpx.post is not _REAL_POST:
+ return httpx.post(url, **kwargs)
+ with _pool_lock:
+ if _pool is None:
+ _pool = httpx.Client(timeout=120.0, limits=httpx.Limits(max_keepalive_connections=8))
+ return _pool.post(url, **kwargs)
+
+
+_REAL_POST = httpx.post
+
+#: Extra tries a retryable call gets when Kaggle answers 429.
+RATE_LIMIT_EXTRA = 2
+
+
+def _backoff(r: httpx.Response, attempt: int) -> float:
+ """Kaggle's Retry-After when it sends one (capped), else exponential with
+ jitter -- so threads that were limited together do not return together."""
+ try:
+ after = float((getattr(r, "headers", None) or {}).get("retry-after", ""))
+ except ValueError:
+ after = 0.0
+ if after > 0:
+ return min(after, 30.0)
+ return 2**attempt + random.uniform(0, 1)
+
+
def call(
creds: Creds,
method: str,
@@ -89,16 +126,23 @@ def call(
attempts: int = 3,
) -> dict:
url = f"{BASE}/{service}/{method}"
- for attempt in range(attempts):
- last = attempt == attempts - 1
+ # Two budgets. Failures (no answer, 5xx) get the caller's `attempts`.
+ # Rate limiting is Kaggle asking us to slow down, not failing: a call that
+ # may be retried at all gets RATE_LIMIT_EXTRA more tries for a 429 only,
+ # so being offline still fails fast.
+ tries = 0
+ limited = 0
+ while True:
+ tries += 1
+ last = tries >= attempts
started = time.monotonic()
try:
- r = httpx.post(url, json=payload or {}, headers=creds.headers, timeout=120.0)
+ r = _post(url, json=payload or {}, headers=creds.headers, timeout=120.0)
except httpx.HTTPError as e:
- log.debug("%s as %s: %s (attempt %d)", method, creds.username, e, attempt + 1)
+ log.debug("%s as %s: %s (attempt %d)", method, creds.username, e, tries)
if last:
raise KaggleError(f"{method}: could not reach Kaggle ({e})") from e
- time.sleep(2**attempt)
+ time.sleep(2 ** (tries - 1))
continue
log.debug(
"%s as %s -> %d in %.2fs",
@@ -107,8 +151,13 @@ def call(
r.status_code,
time.monotonic() - started,
)
+ if r.status_code == 429 and attempts > 1 and limited < RATE_LIMIT_EXTRA:
+ limited += 1
+ tries -= 1 # a rate-limited try does not spend the failure budget
+ time.sleep(_backoff(r, limited))
+ continue
if r.status_code in RETRY_STATUS and not last:
- time.sleep(2**attempt)
+ time.sleep(_backoff(r, tries - 1))
continue
break
if r.status_code == 401:
@@ -128,9 +177,11 @@ def call(
def _message(r: httpx.Response) -> str:
"""Kaggle's own error message, not the JSON envelope around it."""
try:
- err = (r.json() or {}).get("error")
+ body = r.json()
except ValueError:
- err = None
+ body = None
+ # A proxy or an outage page can answer with any JSON at all, or none.
+ err = body.get("error") if isinstance(body, dict) else None
if isinstance(err, dict) and err.get("message"):
return f"{err['message']} (HTTP {r.status_code})"
return f"HTTP {r.status_code}: {r.text[:200]}"
@@ -169,12 +220,15 @@ def save_kernel(
#: The most ListKernelSessionOutput accepts per page (it says so on a 400).
OUTPUT_PAGE = 500
+#: The first page of a prefix read: enough for `.kdev/` when it sorts first.
+PREFIX_PAGE = 50
-def session_output(creds: Creds, slug: str, version: str = "") -> list[dict]:
+def session_output(creds: Creds, slug: str, version: str = "", *, prefix: str = "") -> list[dict]:
"""Every file a saved version left in /kaggle/working, with signed URLs.
- `version` is a label like "v7"; empty means the latest. Older versions stay
+ `version` is a label like "v7"; empty means the latest. With `prefix`,
+ paging stops once every name under it has been listed (see `_past`). Older versions stay
readable, which is what lets a restore build on the last good one when the
newest was cut short. A notebook cannot mount its own output (Kaggle
rejects the data source), so this listing is the only way back.
@@ -182,8 +236,13 @@ def session_output(creds: Creds, slug: str, version: str = "") -> list[dict]:
user, _, kslug = slug.partition("/")
out = []
token = None
+ # A prefix read wants the first names only: a small page answers faster.
+ # If that page does not get past the prefix (a `.git/` or `.cache/` at the
+ # root sorts before `.kdev/`), start over at the full size rather than
+ # walk thousands of names fifty at a time.
+ size = PREFIX_PAGE if prefix else OUTPUT_PAGE
while True:
- payload = {"userName": user, "kernelSlug": kslug, "pageSize": OUTPUT_PAGE}
+ payload = {"userName": user, "kernelSlug": kslug, "pageSize": size}
if version:
payload["versionLabel"] = version
if token:
@@ -196,6 +255,21 @@ def session_output(creds: Creds, slug: str, version: str = "") -> list[dict]:
token = resp.get("nextPageToken")
if not token:
return out
+ if size == PREFIX_PAGE and not _past(resp.get("files") or [], prefix):
+ out, token, size = [], None, OUTPUT_PAGE
+ continue
+ if prefix and _past(resp.get("files") or [], prefix):
+ # Only the names under `prefix` must be complete, and Kaggle lists
+ # names in order (measured): a sorted page that ends beyond the
+ # prefix means no later page holds one. The listing returned is
+ # partial -- complete under `prefix`, a sample of the rest.
+ return out
+
+
+def _past(page: list[dict], prefix: str) -> bool:
+ """Whether a page is sorted and ends after every name starting `prefix`."""
+ names = [str(f.get("fileName") or "") for f in page]
+ return bool(names) and names == sorted(names) and names[-1] > prefix + "\U0010ffff"
#: The status of a notebook that has never been run. Kaggle answers that with
@@ -286,7 +360,15 @@ def stream_logs(
if idle is None:
raise
else:
- for entry in json.loads(r.read() or b"[]"):
+ try:
+ entries = json.loads(r.read() or b"[]")
+ except ValueError as e:
+ raise KaggleError(
+ "logs: Kaggle sent something that is not JSON", r.status_code
+ ) from e
+ if not isinstance(entries, list):
+ entries = [entries]
+ for entry in entries:
yield _log_text(entry)
@@ -327,7 +409,10 @@ def share_with_group(
bindings = [dict(b) for b in policy.get("bindings") or []]
def is_our_group(member: dict) -> bool:
- return (member.get("group") or {}).get("slug") == group_slug
+ # GetIamPolicy leaves `group.slug` null and puts it on `group.avatar`
+ # (see policy_groups); a binding we wrote ourselves has it at the top.
+ g = member.get("group") or {}
+ return group_slug in (g.get("slug"), (g.get("avatar") or {}).get("slug"))
for b in bindings:
b["members"] = [m for m in (b.get("members") or []) if not is_our_group(m)]
diff --git a/src/kdev/auth.py b/src/kdev/auth.py
index 48bba0e..e22cccd 100644
--- a/src/kdev/auth.py
+++ b/src/kdev/auth.py
@@ -5,7 +5,8 @@
status) answer 401. Only a Bearer access token works.
Tokens expire after 12 hours, but the credentials file also carries a
-long-lived refresh token, and kagglesdk refreshes transparently. kdev keeps one
+long-lived refresh token, which kdev trades for a new access token when the
+stored one is within an hour of expiring. kdev keeps one
credentials file per profile so several teammates' accounts can coexist -- the
official CLI only ever has one, at ~/.kaggle/credentials.json.
"""
@@ -13,18 +14,31 @@
from __future__ import annotations
import json
+import os
import shutil
import subprocess
import sys
+import threading
+from datetime import UTC, datetime, timedelta
from pathlib import Path
+from . import api
from . import config as _config
KAGGLE_CREDENTIALS = Path.home() / ".kaggle" / "credentials.json"
+#: The RPC service that turns a refresh token into an access token.
+ACCOUNTS = "users.AccountService"
class AuthError(RuntimeError):
- pass
+ """This account cannot authenticate: not signed in, or its sign-in is
+ no longer accepted. Signing in again fixes it."""
+
+
+class AuthUnavailable(AuthError):
+ """The token could not be refreshed right now -- offline, a proxy, Kaggle
+ down. Signing in again would not help, so callers must not treat this as
+ "signed out"."""
def creds_dir() -> Path:
@@ -75,10 +89,8 @@ def login(profile: str) -> str:
if not data.get("refresh_token"):
raise AuthError("Credentials are missing a refresh token.")
- dest = creds_path(profile)
- dest.parent.mkdir(parents=True, exist_ok=True)
- dest.write_text(json.dumps(data, indent=2))
- dest.chmod(0o600)
+ _write_private(creds_path(profile), data)
+ invalidate(profile)
# Put the shared file back so kdev does not disturb the user's own CLI login.
if before is not None:
@@ -87,24 +99,150 @@ def login(profile: str) -> str:
return data.get("username") or ""
-def access_token(profile: str) -> str:
- """A valid access token for this profile, refreshing it if it has expired."""
- path = creds_path(profile)
- if not path.exists():
- raise AuthError(f"{profile} is not signed in. Run: kdev account add {profile}")
+#: Refresh a token this long before it expires. Longer than any one wait
+#: that holds a single `Creds` (a box boot or a save: up to 30 min), so a
+#: token never lapses halfway through and fails as "signed out".
+REFRESH_MARGIN = timedelta(hours=1)
+#: What kagglesdk asks for; Kaggle's answer says what it actually granted.
+TOKEN_LIFETIME = timedelta(hours=12)
+
+#: profile creds path -> (file identity, token, expiry). One process reads an
+#: account's token dozens of times; minting one costs a round trip each.
+_cache: dict[str, tuple[tuple[int, int, int], str, datetime]] = {}
+_locks: dict[str, threading.Lock] = {}
+_locks_guard = threading.Lock()
+
+
+def _lock_for(key: str) -> threading.Lock:
+ # One lock per account, so several accounts still mint in parallel.
+ with _locks_guard:
+ return _locks.setdefault(key, threading.Lock())
+
+
+def _identity(path: Path) -> tuple[int, int, int]:
+ """Changes whenever the file is replaced -- a re-login, another kdev."""
+ st = path.stat()
+ return st.st_ino, st.st_mtime_ns, st.st_size
+
+
+def _expiry(value: object) -> datetime | None:
+ if not value or not isinstance(value, str):
+ return None
try:
- from kagglesdk import KaggleClient
- from kagglesdk.kaggle_creds import KaggleCredentials
- except ImportError as e: # pragma: no cover - dependency is declared
- raise AuthError(f"kagglesdk is not installed: {e}") from e
-
- creds = KaggleCredentials.load(KaggleClient(), file_path=str(path))
- if creds is None:
- raise AuthError(f"Could not read credentials for {profile!r}.")
- token = creds.get_access_token()
+ when = datetime.fromisoformat(value)
+ except ValueError:
+ return None
+ return when if when.tzinfo else when.replace(tzinfo=UTC)
+
+
+def _fresh(expires: datetime) -> bool:
+ return expires - datetime.now(UTC) > REFRESH_MARGIN
+
+
+def invalidate(profile: str) -> None:
+ """Forget the cached token, after the account's file was replaced."""
+ _cache.pop(str(creds_path(profile)), None)
+
+
+def _write_private(path: Path, data: dict) -> None:
+ """Write JSON through a temp file and a rename, 0600 from the start.
+
+ Several threads, or kdev processes, can refresh one account at once; a
+ half-written file would sign the account out.
+ """
+ path.parent.mkdir(parents=True, exist_ok=True)
+ tmp = path.with_name(f".{path.name}.{os.getpid()}.{threading.get_ident()}.tmp")
+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
+ try:
+ with os.fdopen(fd, "w") as f:
+ json.dump(data, f, indent=2)
+ os.chmod(tmp, 0o600)
+ tmp.replace(path)
+ except BaseException:
+ tmp.unlink(missing_ok=True)
+ raise
+
+
+def _mint(profile: str, refresh_token: str) -> tuple[str, datetime]:
+ """A new access token from the refresh token. Nothing is written here.
+
+ The same request kagglesdk's `KaggleCredentials.generate_access_token`
+ builds (users.AccountService/GenerateAccessToken), sent directly: the SDK's
+ refresh path saves the result to ~/.kaggle/credentials.json -- the user's
+ own CLI login -- sends with no timeout, and attaches whatever other
+ credentials it finds in the environment.
+ """
+ payload = {
+ "refreshToken": refresh_token,
+ "apiVersion": "API_VERSION_V1",
+ "expirationDuration": f"{int(TOKEN_LIFETIME.total_seconds())}s",
+ }
+ try:
+ resp = api.call(api.Creds(profile), "GenerateAccessToken", payload, service=ACCOUNTS)
+ except api.KaggleError as e:
+ if e.status in (400, 401, 403, 404):
+ raise AuthError(
+ f"Kaggle no longer accepts {profile}'s sign-in. Run: kdev account add {profile}"
+ ) from e
+ raise AuthUnavailable(
+ f"Could not reach Kaggle to refresh {profile}'s sign-in ({e})."
+ ) from e
+ token = str(resp.get("token") or "")
if not token:
- raise AuthError(f"Could not refresh {profile}'s sign-in. Run: kdev account add {profile}")
- return token
+ raise AuthUnavailable(f"Kaggle sent no access token for {profile}.")
+ try:
+ seconds = int(resp.get("expiresIn") or 0)
+ except (TypeError, ValueError):
+ seconds = 0
+ lifetime = timedelta(seconds=seconds) if seconds > 0 else TOKEN_LIFETIME
+ return token, datetime.now(UTC) + lifetime
+
+
+def access_token(profile: str) -> str:
+ """A valid access token for this profile, refreshing it when near expiry.
+
+ Read once per process and kept, so the dozens of calls one command makes
+ share a token. A refresh lands in the profile's own file, never in the
+ official CLI's.
+ """
+ path = creds_path(profile)
+ key = str(path)
+ with _lock_for(key):
+ try:
+ ident = _identity(path)
+ except FileNotFoundError:
+ _cache.pop(key, None)
+ raise AuthError(
+ f"{profile} is not signed in. Run: kdev account add {profile}"
+ ) from None
+ except OSError as e:
+ raise AuthError(f"Could not read credentials for {profile!r}: {e}") from e
+ hit = _cache.get(key)
+ if hit and hit[0] == ident and _fresh(hit[2]):
+ return hit[1]
+
+ try:
+ data = json.loads(path.read_text())
+ except (OSError, ValueError) as e:
+ raise AuthError(f"Could not read credentials for {profile!r}: {e}") from e
+ if not isinstance(data, dict) or not data.get("refresh_token"):
+ raise AuthError(
+ f"{profile}'s credentials have no refresh token. Run: kdev account add {profile}"
+ )
+ token = str(data.get("access_token") or "")
+ expires = _expiry(data.get("access_token_expiration"))
+ if not token or expires is None or not _fresh(expires):
+ token, expires = _mint(profile, str(data["refresh_token"]))
+ data["access_token"] = token
+ data["access_token_expiration"] = expires.isoformat()
+ try:
+ _write_private(path, data)
+ ident = _identity(path)
+ except OSError:
+ # The token is good either way; the next process mints again.
+ pass
+ _cache[key] = (ident, token, expires)
+ return token
def signed_in(profile: str) -> bool:
@@ -113,3 +251,4 @@ def signed_in(profile: str) -> bool:
def forget(profile: str) -> None:
creds_path(profile).unlink(missing_ok=True)
+ invalidate(profile)
diff --git a/src/kdev/bootstrap.py b/src/kdev/bootstrap.py
index 40ec725..b0cf29e 100644
--- a/src/kdev/bootstrap.py
+++ b/src/kdev/bootstrap.py
@@ -113,6 +113,7 @@ def export_env():
ssh_env.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
ssh_env.write_text("".join(f"{k}={v}\n" for k, v in env.items()))
ssh_env.chmod(0o600)
+ _pam_path(env.get("PATH", ""))
# Also kept as a sourceable file, for scripts that start from a clean env.
pathlib.Path("/root/.kdev_env.sh").write_text(
@@ -124,9 +125,26 @@ def export_env():
f.write(hook)
+def _pam_path(path):
+ """sshd applies ~/.ssh/environment, then PAM's pam_env sets PATH again from
+ /etc/environment -- measured: a non-interactive ssh had no /opt/bin, so no
+ nvidia-smi, and VS Code's server no CUDA. Give pam_env the notebook's PATH."""
+ if not path or '"' in path:
+ return
+ etc = pathlib.Path("/etc/environment")
+ try:
+ lines = etc.read_text().splitlines() if etc.exists() else []
+ kept = [ln for ln in lines if not ln.startswith("PATH=")]
+ etc.write_text("\n".join(kept + [f'PATH="{path}"']) + "\n")
+ except OSError as e:
+ print(f"could not set PATH for ssh sessions: {e}", flush=True)
+
+
def add_env(name, value):
"""Add one variable to every future ssh session."""
os.environ[name] = value
+ if name == "PATH":
+ _pam_path(value)
with pathlib.Path("/root/.ssh/environment").open("a") as f:
f.write(f"{name}={value}\n")
with pathlib.Path("/root/.kdev_env.sh").open("a") as f:
diff --git a/src/kdev/cli.py b/src/kdev/cli.py
index 78c20b6..0b0532f 100644
--- a/src/kdev/cli.py
+++ b/src/kdev/cli.py
@@ -7,6 +7,7 @@
from __future__ import annotations
+import contextlib
import logging
import sys
@@ -19,9 +20,44 @@
from .commands import tunnel as tunnel_cmd
from .errors import Cancelled, KdevError
+
+def _brand_help() -> None:
+ """--help in kdev's own palette: accent for what you type, grey for the rest."""
+ import typer.rich_utils as ru
+
+ ru.STYLE_OPTION = f"bold {ui.ACCENT}"
+ ru.STYLE_SWITCH = ui.ACCENT
+ ru.STYLE_NEGATIVE_OPTION = ui.ACCENT
+ ru.STYLE_NEGATIVE_SWITCH = ui.ACCENT
+ ru.STYLE_TYPES = ui.MUTED
+ ru.STYLE_USAGE = f"bold {ui.ACCENT}"
+ ru.STYLE_USAGE_COMMAND = "bold"
+ ru.STYLE_COMMANDS_TABLE_FIRST_COLUMN = f"bold {ui.ACCENT}"
+ ru.STYLE_OPTIONS_PANEL_BORDER = "grey42"
+ ru.STYLE_COMMANDS_PANEL_BORDER = "grey42"
+ ru.STYLE_HELPTEXT = ui.MUTED
+ ru.STYLE_OPTION_DEFAULT = ui.MUTED
+
+
+_brand_help()
+
+EXAMPLES = """[bold]Examples[/bold]
+
+ [bold #00b8d4]kdev[/] the home screen: the box, quota, one key to act
+ [bold #00b8d4]kdev up[/] start the box, or connect to the one running
+ [bold #00b8d4]kdev up --gpu none --hours 2[/] a CPU box that uses no GPU quota
+ [bold #00b8d4]kdev up --open code -y[/] no questions; open VS Code when ready
+ [bold #00b8d4]kdev ssh -- nvidia-smi[/] run one command on the box
+ [bold #00b8d4]kdev forward 8888[/] reach the box's Jupyter on localhost:8888
+ [bold #00b8d4]kdev status --json[/] for scripts: JSON on stdout, nothing else
+ [bold #00b8d4]kdev down[/] stop it; your files are saved either way
+
+Docs: https://kdev-cli.pages.dev/docs/"""
+
app = typer.Typer(
name="kdev",
help=__doc__,
+ epilog=EXAMPLES,
no_args_is_help=False,
rich_markup_mode="rich",
context_settings={"help_option_names": ["-h", "--help"]},
@@ -99,6 +135,13 @@ def _dispatch(argv: list[str]) -> None:
raise typer.Exit(code)
+def _quote_commands(message: str) -> str:
+ """click quotes names as 'status'; kdev draws commands as commands."""
+ import re
+
+ return re.sub(r"'([^'\s]+)'", r"`\1`", message)
+
+
def _explain(e: api.KaggleError) -> tuple[str, str]:
text = str(e)
if e.status == 401:
@@ -136,18 +179,33 @@ def main() -> None:
sys.exit(1)
except KeyboardInterrupt:
ui.errconsole.print(ui.Text("\n interrupted", style="kdev.muted"))
+ if len(sys.argv) > 1 and sys.argv[1] == "up":
+ ui.errconsole.print(
+ ui.Text(
+ " A box may still be starting and using quota: "
+ "kdev up connects to it, kdev down stops it.",
+ style="kdev.muted",
+ )
+ )
sys.exit(130)
+ except BrokenPipeError:
+ # `kdev logs | head -1`: the reader left, which is not a failure.
+ import os
+
+ with contextlib.suppress(OSError):
+ os.dup2(os.open(os.devnull, os.O_WRONLY), sys.stdout.fileno())
+ sys.exit(0)
except typer.Abort:
ui.errconsole.print(ui.Text("\n interrupted", style="kdev.muted"))
sys.exit(130)
except typer.TyperException as e:
# Usage mistakes -- a bad option, a missing argument -- in the
- # parser's own words, which are good, plus where to look.
- show = getattr(e, "show", None)
- if callable(show):
- show()
- else:
- ui.err(str(e), "kdev --help lists every command and option.")
+ # parser's own words, which are good (including "Did you mean"), in
+ # kdev's voice, with the help for the command that was being typed.
+ ctx = getattr(e, "ctx", None)
+ where = ctx.command_path if ctx is not None else "kdev"
+ message = e.format_message() if hasattr(e, "format_message") else str(e)
+ ui.err(_quote_commands(message), f"See `{where} --help`")
sys.exit(getattr(e, "exit_code", 2))
except typer.Exit as e:
sys.exit(e.exit_code)
diff --git a/src/kdev/cloudflared.py b/src/kdev/cloudflared.py
index 54ab7c6..965e68f 100644
--- a/src/kdev/cloudflared.py
+++ b/src/kdev/cloudflared.py
@@ -11,7 +11,6 @@
from __future__ import annotations
-import hashlib
import os
import platform
import shutil
@@ -128,19 +127,21 @@ def install(progress=None) -> Path:
return dest
-def _download(url: str, dest: Path, progress=None) -> str:
- sha = hashlib.sha256()
+def _download(url: str, dest: Path, progress=None) -> None:
+ # Not checksummed: Cloudflare's only published sums are free text in the
+ # release notes, behind a separate (rate-limited) GitHub API call that can
+ # race `latest`, and for the macOS .tgz they do not match the asset
+ # (checked on 2026.11.0). TLS to GitHub, plus the `--version` run after
+ # install, is the check.
with urllib.request.urlopen(url, timeout=120) as r:
total = int(r.headers.get("Content-Length") or 0)
done = 0
with dest.open("wb") as f:
while chunk := r.read(262144):
f.write(chunk)
- sha.update(chunk)
done += len(chunk)
if progress:
progress(done, total)
- return sha.hexdigest()
def ensure(auto: bool = True, progress=None) -> Path:
@@ -150,7 +151,7 @@ def ensure(auto: bool = True, progress=None) -> Path:
return found
if not auto:
raise KdevError(
- "cloudflared not found. Run `kdev doctor --install` or "
+ "cloudflared not found. Run `kdev doctor --fix` or "
"install it yourself: brew install cloudflared"
)
return install(progress)
diff --git a/src/kdev/commands/_common.py b/src/kdev/commands/_common.py
index 4979c31..3e6c15c 100644
--- a/src/kdev/commands/_common.py
+++ b/src/kdev/commands/_common.py
@@ -37,12 +37,15 @@ def need_notebook(cfg: config.Config, override: str = "") -> str:
def context(cfg: config.Config, account: str = "", notebook: str = "") -> list[tuple[str, str]]:
- """The facts a header shows: who, which notebook, which tunnel."""
- return [
- ("account", account or cfg.active or "—"),
- ("notebook", notebook or cfg.notebook or "—"),
- ("tunnel", cfg.tunnel_hostname or "quick"),
- ]
+ """The facts a header shows: who runs it, and which notebook. The
+ notebook's owner is left out when it is that same account: the line
+ stays short enough for the right-hand side of the header."""
+ who = account or cfg.active or "—"
+ where = notebook or cfg.notebook or "—"
+ owner, _, slug = where.partition("/")
+ if slug and owner == (cfg.profiles[who].username if who in cfg.profiles else who):
+ where = slug
+ return [("account", who), ("notebook", where)]
def box_label(cfg: config.Config) -> str:
diff --git a/src/kdev/commands/account.py b/src/kdev/commands/account.py
index 0d95413..a09288e 100644
--- a/src/kdev/commands/account.py
+++ b/src/kdev/commands/account.py
@@ -2,6 +2,8 @@
from __future__ import annotations
+from datetime import UTC, datetime
+
import typer
from .. import auth, config, quota, ui, wizard
@@ -39,23 +41,30 @@ def main(
"gpu_seconds_left": r.gpu_left,
"gpu_seconds_total": r.gpu_total,
"tpu_seconds_left": r.tpu_left,
+ "tpu_seconds_total": r.tpu_total,
+ "quota_resets": (
+ datetime.fromtimestamp(r.resets, UTC).isoformat().replace("+00:00", "Z")
+ if r.resets
+ else None
+ ),
"error": r.error or None,
}
for r in rows
]
)
return
- ui.section("Accounts", f"{len(rows)} connected")
ui.console.print(ui.accounts_table(rows))
total = sum(r.gpu_left for r in rows if not r.error)
ui.blank()
+ refill = quota.resets(rows)
ui.hint(
f"{ui.fmt_hours(total)} of GPU left across {len(rows)} account(s) "
- f"{ui.g('bullet')} {ui.g('live')} runs the next box"
+ + (f"{ui.g('bullet')} refills {ui.fmt_when(refill)} " if refill else "")
+ + f"{ui.g('bullet')} {ui.g('live')} runs the next box"
)
- broken = [r.name for r in rows if r.error]
+ # Only a sign-in problem is fixed by signing in again; offline is not.
+ broken = [r.name for r in rows if r.error and r.error != quota.OFFLINE]
if broken:
- ui.blank()
ui.next_steps([(f"kdev account add {n}", "sign it in again") for n in broken])
@@ -80,7 +89,6 @@ def add(name: str = typer.Argument("", help="A short name for the account, e.g.
f"added {name} ({cfg.profiles[name].username})"
+ ("; it runs the next box" if cfg.active == name else "")
)
- ui.blank()
ui.next_steps([("kdev account", "see every account's quota")])
@@ -105,6 +113,8 @@ def _refresh(cfg: config.Config, name: str) -> None:
f"Switch Kaggle accounts in the browser, then: kdev account add {name}",
)
auth.creds_path(scratch).replace(auth.creds_path(name))
+ auth.invalidate(name)
+ auth.invalidate(scratch)
ui.ok(f"signed {name} in again")
@@ -120,7 +130,7 @@ def use(name: str = typer.Argument("", help="The account to make active.")) -> N
raise KdevError("Name the account.", "kdev account use ")
with ui.spinner("reading quota…"):
rows = quota.rows(cfg)
- name = ui.pick_profile(rows, 0)
+ name = ui.pick_profile(rows, 0, question="Which account runs the next box?")
cfg.profile(name)
cfg.active = name
config.save(cfg)
diff --git a/src/kdev/commands/box.py b/src/kdev/commands/box.py
index 647fb91..76adbe7 100644
--- a/src/kdev/commands/box.py
+++ b/src/kdev/commands/box.py
@@ -7,6 +7,7 @@
import socket
import subprocess
import time
+from concurrent.futures import ThreadPoolExecutor
from datetime import UTC, datetime
from typing import Annotated, NoReturn
@@ -26,7 +27,7 @@
ui,
)
from .. import notebook as nb
-from ..errors import KdevError
+from ..errors import KdevError, did_you_mean
from ._common import cap_for, context, load_ready, need_notebook
OPEN_CHOICES = ("code", "shell", "none")
@@ -204,6 +205,7 @@ def up(
if not winner:
raise
joined = True
+ board.record = False
board.note(f"Kaggle rejected our submission; joining {winner}")
else:
board.note(f"version {resp.get('versionNumber')}")
@@ -227,6 +229,7 @@ def up(
seen.clear()
host = session.await_ready(prof.creds, target, board, seen=seen, version=winner)
if joined:
+ board.record = False
board.note(f"using the session another machine started: {winner}")
if host:
board.note("waiting for concurrent starts to stop…")
@@ -308,7 +311,17 @@ def up(
ui.blank()
files = f"{restored.get('done', 0)} restored" if restored.get("total") else ""
- ui.ready_card(cfg.ssh_host_alias, host, hours, label, name, note=files)
+ own = persistence.box_state(cfg.ssh_host_alias)
+ ui.ready_card(
+ cfg.ssh_host_alias,
+ host,
+ hours,
+ label,
+ name,
+ note=files,
+ started=ui.epoch(own.get("started")),
+ ends=ui.epoch(own.get("ends")),
+ )
_open(cfg.ssh_host_alias, open_with, interactive)
@@ -328,13 +341,16 @@ def _box_spec(
else:
gpu = "t4"
if gpu not in api.SHAPES:
- raise KdevError(f"--gpu must be one of: {', '.join(api.SHAPES)}.")
+ raise KdevError(
+ f"No accelerator called `{gpu}`.{did_you_mean(gpu, api.SHAPES)}",
+ f"--gpu takes one of: {', '.join(api.SHAPES)}",
+ )
cap = cap_for(gpu)
if hours is None:
if cfg.default_hours:
hours = cfg.default_hours
elif interactive:
- hours, hours_picked = ui.pick_hours(gpu, cap), True
+ hours, hours_picked = ui.pick_hours(gpu, _quota_left(cfg, gpu)), True
else:
hours = 9.0
if not hours or hours <= 0:
@@ -345,6 +361,18 @@ def _box_spec(
return gpu, float(hours), gpu_picked, hours_picked
+def _quota_left(cfg: config.Config, gpu: str) -> float | None:
+ """The active account's hours left of the accelerator, or None if it
+ cannot be read now: the question is asked either way."""
+ if gpu == "none" or not cfg.active:
+ return None
+ with ui.spinner("reading quota…"):
+ row = quota.row(cfg, cfg.active)
+ if row.error:
+ return None
+ return (row.tpu_left if gpu == "tpu" else row.gpu_left) / 3600
+
+
def _cloudflared(interactive: bool):
"""Resolved before the session starts: discovering it is missing after the
container boots would waste quota on a box nobody can reach."""
@@ -372,18 +400,24 @@ def _stop_and_wait(
with ui.spinner("stopping the running box and waiting for it to save…"):
stopped = False
if session.reachable(cfg.ssh_host_alias):
- r = subprocess.run(
- [
- "ssh",
- "-T",
- "-o",
- "BatchMode=yes",
- cfg.ssh_host_alias,
- "touch /kaggle/working/.kdev-stop",
- ],
- capture_output=True,
- )
- stopped = r.returncode == 0
+ try:
+ r = subprocess.run(
+ [
+ "ssh",
+ "-T",
+ "-o",
+ "BatchMode=yes",
+ "-o",
+ "ConnectTimeout=15",
+ cfg.ssh_host_alias,
+ "touch /kaggle/working/.kdev-stop",
+ ],
+ capture_output=True,
+ timeout=60,
+ )
+ stopped = r.returncode == 0
+ except (subprocess.SubprocessError, OSError):
+ stopped = False
if not stopped:
sid, runner = session.live_session_id(creds, target, version=version)
if not sid or not session.cancel_as_owner(cfg, int(sid), runner):
@@ -439,7 +473,15 @@ def _connect(
cfg, prof.creds, target, hours, gpu, account, version=version
)
ui.blank()
- ui.ready_card(cfg.ssh_host_alias, host, hours, label, account)
+ ui.ready_card(
+ cfg.ssh_host_alias,
+ host,
+ hours,
+ label,
+ account,
+ started=ui.epoch(state.get("started")),
+ ends=ui.epoch(state.get("ends")),
+ )
_open(cfg.ssh_host_alias, open_with, interactive)
@@ -703,6 +745,13 @@ def forward(
# --- status -------------------------------------------------------------------
+def _probe_box(alias: str) -> tuple[bool, dict]:
+ """(reachable, the box's own state), in one ssh round trip when it answers."""
+ if not session.reachable(alias):
+ return False, {}
+ return True, persistence.box_state(alias)
+
+
def _run_status_label(status: object) -> str:
value = str(status)
return {
@@ -726,16 +775,24 @@ def status(
target = need_notebook(cfg)
creds = cfg.profile(account).creds
with ui.spinner("checking…"):
- version = ""
- try:
- version, state = session.current_status(creds, target)
- except api.KaggleError as e:
- state = {"status": "UNKNOWN", "failureMessage": str(e)}
- reachable = session.reachable(cfg.ssh_host_alias)
- box = persistence.box_state(cfg.ssh_host_alias) if reachable else {}
+ # Kaggle's view and ssh's are independent: ask both at once. A
+ # successful read of the box's state is itself proof it is reachable.
+ with ThreadPoolExecutor(max_workers=2) as pool:
+ kaggle = pool.submit(session.current_status, creds, target)
+ probe = pool.submit(_probe_box, cfg.ssh_host_alias)
+ version = ""
+ try:
+ version, state = kaggle.result()
+ except (api.KaggleError, KdevError) as e:
+ state = {"status": "UNKNOWN", "failureMessage": str(e)}
+ reachable, box = probe.result()
running = state.get("status") in api.LIVE_STATES
+ # Only a RUNNING box that stopped answering might be stopping; a
+ # queued or booting one is simply not up yet.
saving = state.get("status") == api.SAVING or (
- running and not reachable and session.stopping(creds, target, version=version)
+ state.get("status") == "RUNNING"
+ and not reachable
+ and session.stopping(creds, target, version=version)
)
info = {
"notebook": target,
@@ -753,6 +810,8 @@ def status(
}
if as_json:
ui.emit_json(info)
+ if info["status"] == "UNKNOWN" and info["failure"]:
+ raise typer.Exit(1) # scripts must be able to tell "unknown" from "stopped"
return
# Kaggle's words describe the last *run*; the user asked about the *box*.
@@ -768,26 +827,34 @@ def status(
(" " + target, "kdev.muted"),
)
rows: list[tuple[str, object]] = []
+ up = Text.assemble(("kdev up", "kdev.cmd"), (" brings them back", "kdev.muted"))
if not running:
rows.append(("last run", _run_status_label(info["status"])))
if info["status"] == api.NEVER_RUN:
- rows.append(("files", "nothing saved yet; `kdev up` starts it"))
- else:
- rows.append(("files", "saved in the notebook; `kdev up` puts them back"))
+ rows.append(("files", Text.assemble(("nothing saved yet ", ""), up)))
+ elif not saving:
+ rows.append(("files", Text.assemble(("saved in the notebook ", ""), up)))
if box.get("run_by"):
rows.append(("started by", box["run_by"]))
- if box.get("ends"):
- left = max(0, int(box["ends"]) - int(time.time()))
- ends = time.strftime("%H:%M", time.localtime(int(box["ends"])))
- rows.append(("ends", f"{ends} ({ui.fmt_hours(left)} left)"))
+ ends, started = ui.epoch(box.get("ends")), ui.epoch(box.get("started"))
+ if ends:
+ rows.append(("time", ui.countdown(started or ends - 12 * 3600, ends)))
if saving:
- rows.append(("files", "being saved; `kdev up` waits for them"))
+ rows.append(
+ (
+ "files",
+ Text.assemble(
+ ("being saved ", "kdev.warn"), ("kdev up waits for them", "kdev.muted")
+ ),
+ )
+ )
elif running:
- reach = Text(
- f"{cfg.ssh_host_alias} {ui.g('arrow')} {cfg.tunnel_hostname or 'quick tunnel'} "
+ reach = Text.assemble(
+ (cfg.ssh_host_alias, "kdev.cmd"),
+ (f" {ui.g('arrow')} {cfg.tunnel_hostname or 'quick tunnel'} ", "kdev.muted"),
)
reach.append(
- "reachable" if reachable else "not reachable yet",
+ f"{ui.g('ok')} reachable" if reachable else "not reachable yet",
style="kdev.ok" if reachable else "kdev.warn",
)
rows.append(("ssh", reach))
@@ -795,10 +862,10 @@ def status(
layers = " + ".join(box.get("layers") or []) or "nothing saved yet"
rows.append(
(
- "files",
- Text(f"restored from {layers}", style="kdev.ok")
+ "restored",
+ Text(f"{ui.g('ok')} from {layers}", style="kdev.ok")
if box.get("restored")
- else Text("restore not finished: kdev restore", style="kdev.warn"),
+ else Text.assemble(("not finished ", "kdev.warn"), ("kdev restore", "kdev.cmd")),
)
)
if box.get("notebook") and box["notebook"] != target:
@@ -809,7 +876,9 @@ def status(
rows.append(("error", Text(info["failure"], style="kdev.err")))
ui.card(title, rows, tone="ok" if running else "muted")
if running and not reachable and not saving:
- ui.hint("Running but not reachable yet: give it a minute, or `kdev logs` to see why.")
+ ui.next_steps([("kdev logs", "see what the box is doing; ssh can take a minute")])
+ elif running:
+ ui.next_steps([("kdev ssh", "open a shell"), ("kdev down", "stop it; files are saved")])
# --- history ------------------------------------------------------------------
@@ -893,7 +962,9 @@ def history(
def logs(
account: str = typer.Option("", "--account", "-a", help="Read as this account."),
- lines: int = typer.Option(0, "--lines", "-n", help="Stop after N lines (default: follow)."),
+ lines: int = typer.Option(
+ 0, "--lines", "-n", min=0, help="Stop after N lines (default: follow)."
+ ),
everything: bool = typer.Option(False, "--all", help="Include heartbeat and debugger lines."),
) -> None:
"""Stream the session's log."""
@@ -901,7 +972,16 @@ def logs(
target = need_notebook(cfg)
shown = 0
creds = cfg.profile(account).creds
- version, _ = session.current_status(creds, target)
+ version, state = session.current_status(creds, target)
+ if state.get("status") not in api.LIVE_STATES:
+ # On stderr: the log itself stays clean for `kdev logs > file`.
+ ui.errconsole.print(
+ Text(
+ f" no box is running; this is the log of {version or 'the last run'} "
+ f"({_run_status_label(state.get('status', '?'))})",
+ style="kdev.muted",
+ )
+ )
for line in api.stream_logs(creds, target, version=version):
text = line.rstrip()
if not everything and text.startswith(("KDEV_ALIVE", "0.00s - ")):
@@ -994,7 +1074,11 @@ def restore_cmd(
# --- backup -------------------------------------------------------------------
-def backup() -> None:
+def backup(
+ force: bool = typer.Option(
+ False, "--force", help="Back up even a box that never finished restoring."
+ ),
+) -> None:
"""Copy the running box's /kaggle/working to this machine.
Optional: Kaggle keeps your files anyway. This is a local copy you can
@@ -1003,6 +1087,20 @@ def backup() -> None:
cfg = config.load()
ui.header("backup", terminal_only=True)
session.ssh_ready(cfg)
+ # The copy mirrors the box, deletions included: a box that never got its
+ # files back would mirror as nearly empty and wipe the last good backup.
+ with ui.spinner("reading the box…"):
+ state = persistence.box_state(cfg.ssh_host_alias)
+ if not state:
+ raise KdevError("Could not reach the box over ssh.", "Is it up? kdev status")
+ if not state.get("restored") and persistence.contents():
+ if not force:
+ raise KdevError(
+ "This box never finished restoring your files; a backup now would "
+ "replace this machine's copy with a partial one.",
+ "Finish it first: kdev restore or overwrite anyway: kdev backup --force",
+ )
+ ui.warn("the box never finished restoring; overwriting the local backup anyway")
with ui.spinner("copying the box to this machine…"):
ok, err = persistence.pull(cfg.ssh_host_alias)
if not ok:
diff --git a/src/kdev/commands/doctor.py b/src/kdev/commands/doctor.py
index e1c2125..7f68660 100644
--- a/src/kdev/commands/doctor.py
+++ b/src/kdev/commands/doctor.py
@@ -5,9 +5,12 @@
import re
import shutil
import sys
+from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
+from urllib.parse import quote
import typer
+from rich.text import Text
from .. import api, auth, cloudflared, config, sshcfg, ui
from .. import tunnel as cftunnel
@@ -20,6 +23,31 @@ class Check:
detail: str
fix: str = ""
warn_only: bool = False
+ group: str = "This machine"
+
+
+def _account_check(name: str, prof: config.Profile) -> Check:
+ if not auth.signed_in(name):
+ return Check(name, False, "not signed in", f"kdev account add {name}", group="Accounts")
+ try:
+ api.quota(prof.creds)
+ return Check(name, True, prof.username, group="Accounts")
+ except (api.KaggleError, auth.AuthError) as e:
+ if _offline(e):
+ return Check(
+ name, False, "could not reach Kaggle", "check your connection", group="Accounts"
+ )
+ return Check(name, False, _short(e), f"kdev account add {name}", group="Accounts")
+
+
+def _offline(e: Exception) -> bool:
+ return isinstance(e, auth.AuthUnavailable) or (isinstance(e, api.KaggleError) and not e.status)
+
+
+def _short(e: Exception, width: int = 60) -> str:
+ """An error's first clause, cut at a word rather than mid-word."""
+ text = str(e).split(" (")[0]
+ return text if len(text) <= width else text[:width].rsplit(" ", 1)[0] + "…"
def _checks(cfg: config.Config) -> list[Check]:
@@ -56,42 +84,70 @@ def _checks(cfg: config.Config) -> list[Check]:
)
)
if not cfg.profiles:
- out.append(Check("accounts", False, "none", "kdev account add"))
- for name, prof in cfg.profiles.items():
- if not auth.signed_in(name):
- out.append(Check(f"account {name}", False, "not signed in", f"kdev account add {name}"))
- continue
- try:
- api.quota(prof.creds)
- out.append(Check(f"account {name}", True, prof.username))
- except api.KaggleError as e:
- out.append(Check(f"account {name}", False, str(e)[:60], f"kdev account add {name}"))
+ out.append(Check("accounts", False, "none", "kdev account add", group="Accounts"))
+ # One round trip per account, all at once: a slow account must not make
+ # the whole check wait N times over.
+ with ThreadPoolExecutor(max_workers=max(1, min(8, len(cfg.profiles)))) as pool:
+ out += list(pool.map(lambda item: _account_check(*item), cfg.profiles.items()))
if cfg.notebook and cfg.profiles:
try:
meta = api.get_kernel(cfg.profile().creds, cfg.notebook)
- out.append(Check("workspace", bool(meta), cfg.notebook))
- except api.KaggleError as e:
+ out.append(Check("workspace", bool(meta), cfg.notebook, group="Workspace"))
+ except (api.KaggleError, auth.AuthError) as e:
+ offline = _offline(e)
out.append(
- Check("workspace", False, f"{cfg.notebook}: {str(e)[:50]}", "kdev workspace join")
+ Check(
+ "workspace",
+ False,
+ f"{cfg.notebook}: " + ("could not reach Kaggle" if offline else _short(e, 50)),
+ "check your connection" if offline else "kdev workspace join",
+ group="Workspace",
+ )
)
else:
- out.append(Check("workspace", False, "none", "kdev workspace join"))
+ out.append(Check("workspace", False, "none", "kdev workspace join", group="Workspace"))
if cfg.tunnel_credentials or cfg.tunnel_token:
detail = cfg.tunnel_hostname or "token"
good = True
+ unread = False
if cfg.tunnel_credentials and cftunnel.logged_in():
- rec = cftunnel.dns_record(cfg.tunnel_hostname)
- good = bool(rec and rec.get("content") == cftunnel.tunnel_target(cfg.tunnel_id))
- detail += "" if good else " (DNS does not point at it)"
- out.append(Check("tunnel", good, detail, "kdev tunnel setup --force"))
+ body = cftunnel._api(f"/dns_records?name={quote(cfg.tunnel_hostname)}")
+ if not body.get("success"):
+ # Unreachable is not "wrong": don't send anyone to rebuild a tunnel.
+ unread, good = True, False
+ detail += " (DNS not checked: could not reach Cloudflare)"
+ else:
+ rec = next(iter(body.get("result") or []), None)
+ good = bool(rec and rec.get("content") == cftunnel.tunnel_target(cfg.tunnel_id))
+ detail += "" if good else " (DNS does not point at it)"
+ out.append(
+ Check(
+ "tunnel",
+ good,
+ detail,
+ "" if unread else "kdev tunnel setup --force",
+ warn_only=unread,
+ group="Workspace",
+ )
+ )
else:
- out.append(Check("tunnel", True, "quick (new hostname each session)", warn_only=True))
+ out.append(
+ Check(
+ "tunnel",
+ True,
+ "quick (new hostname each session)",
+ "kdev tunnel setup",
+ warn_only=True,
+ group="Workspace",
+ )
+ )
out.append(
Check(
"ssh config",
True,
f"{cfg.ssh_host_alias} "
+ ("present" if sshcfg.has_block() else "written on the next kdev up"),
+ group="Workspace",
)
)
return out
@@ -112,17 +168,22 @@ def doctor(
with ui.spinner("checking…"):
checks = _checks(cfg)
width = max(len(c.name) for c in checks)
- for c in checks:
- label = f"{c.name:<{width}} {c.detail}"
- if c.ok and not (c.warn_only and "quick" in c.detail):
- ui.ok(label)
- elif c.warn_only:
- ui.warn(label)
- else:
- ui.err(label, c.fix)
+ groups = list(dict.fromkeys(c.group for c in checks))
+ for n, group in enumerate(groups):
+ if n:
+ ui.blank()
+ ui.section(group)
+ for c in (c for c in checks if c.group == group):
+ label = Text.assemble((f"{c.name:<{width}} ", "bold"), (c.detail, ""))
+ if c.ok and not (c.warn_only and "quick" in c.detail):
+ ui.ok(label)
+ elif c.warn_only:
+ ui.warn(label, f"{' ' * (width + 4)}{c.fix}" if c.fix else "")
+ else:
+ ui.err(label, f"{' ' * (width + 4)}fix: {c.fix}" if c.fix else "")
broken = [c for c in checks if not c.ok and not c.warn_only]
ui.blank()
if broken:
- ui.err(f"{len(broken)} problem(s)")
+ ui.err(f"{len(broken)} problem(s) to fix")
raise typer.Exit(1)
- ui.ok("everything kdev needs is in place")
+ ui.ok(Text("everything kdev needs is in place", style="kdev.ok"))
diff --git a/src/kdev/commands/home.py b/src/kdev/commands/home.py
index 6822f66..919ffb6 100644
--- a/src/kdev/commands/home.py
+++ b/src/kdev/commands/home.py
@@ -1,20 +1,296 @@
-"""Bare `kdev`: everything at a glance, then the next thing to do."""
+"""Bare `kdev`: the front door. Everything at a glance, then one key to act.
+
+In a terminal it is a live menu (see `kdev.menu`): the box and every
+account's quota load while it is already on screen, each item has a key,
+and the highlighted one shows the command it runs. Read-only picks come back
+to the menu; picks that hand you the box (up, ssh, VS Code) leave it.
+Without a terminal it prints the same facts as plain lines.
+"""
from __future__ import annotations
+import shutil
+from collections.abc import Callable
+from io import StringIO
+
import typer
+from prompt_toolkit.formatted_text import ANSI, to_formatted_text
+from rich.console import Console, Group, RenderableType
+from rich.padding import Padding
+from rich.table import Table
from rich.text import Text
-from .. import api, config, quota, session, ui, wizard
+from .. import api, auth, config, menu, persistence, quota, session, tunnel, ui, wizard
+from ..errors import Cancelled, KdevError
from ._common import box_label
+#: Terminal height from which the home screen opens with the full logo.
+LOGO_ROWS = 30
+
def setup() -> None:
"""Get this machine ready. Safe to re-run: only does what is missing."""
session.ssh_ready(wizard.run())
-def overview(run_command) -> None:
+# --- facts -------------------------------------------------------------------
+
+
+def _box_facts(cfg: config.Config) -> dict:
+ """The box as Kaggle sees it: one call chain, no ssh."""
+ if not cfg.notebook:
+ return {"status": "", "running": False}
+ _, state = session.current_status(cfg.profile().creds, cfg.notebook)
+ status = state.get("status", "")
+ return {
+ "status": status,
+ "running": status in api.LIVE_STATES,
+ "saving": status == api.SAVING,
+ "queued": status == "QUEUED",
+ "failure": state.get("failureMessage") or "",
+ }
+
+
+def _reach_facts(cfg: config.Config) -> dict:
+ """The box as ssh sees it: reachable, and its own record of when it ends."""
+ if not session.reachable(cfg.ssh_host_alias, timeout=8):
+ return {"reachable": False}
+ state = persistence.box_state(cfg.ssh_host_alias)
+ return {"reachable": True, **state}
+
+
+# --- the dashboard -----------------------------------------------------------
+
+
+def _loading(text: str) -> Text:
+ return Text.assemble((menu.spinner_frame() + " ", "kdev.accent"), (text, "kdev.muted"))
+
+
+def _box_line(cfg: config.Config, live: menu.Live) -> RenderableType:
+ if not cfg.notebook:
+ return Text.assemble((ui.g("warn") + " ", "kdev.warn"), ("no workspace yet", "kdev.warn"))
+ if not live.ready("box"):
+ return _loading("checking the box…")
+ box = live.get("box")
+ if not isinstance(box, dict):
+ return Text.assemble(
+ (ui.g("warn") + " ", "kdev.warn"),
+ ("could not read the box", "kdev.warn"),
+ (f" {live.errors.get('box', '')[:60]}", "kdev.muted"),
+ )
+ if box.get("saving"):
+ return Text.assemble(
+ (ui.g("live") + " ", "kdev.warn"),
+ ("stopping", "bold"),
+ (" saving your files", "kdev.muted"),
+ )
+ if not box.get("running"):
+ return Text.assemble(
+ (ui.g("pending") + " ", "kdev.muted"),
+ ("stopped", "bold"),
+ (f" {ui.g('bullet')} next box {box_label(cfg)}", "kdev.muted"),
+ )
+ word = "starting" if box.get("queued") else "running"
+ head = Text.assemble((ui.g("live") + " ", "kdev.ok"), (word, "kdev.running"))
+ reach = live.get("reach") if live.ready("reach") else None
+ if not live.ready("reach"):
+ head.append(" ")
+ head.append(_loading("reaching it over ssh…"))
+ return head
+ if not isinstance(reach, dict) or not reach.get("reachable"):
+ head.append(f" {ui.g('bullet')} ", "kdev.muted")
+ head.append("not reachable yet", "kdev.warn")
+ return head
+ if reach.get("run_by"):
+ head.append(f" {ui.g('bullet')} started by {reach['run_by']}", "kdev.muted")
+ head.append(f" {ui.g('bullet')} ", "kdev.muted")
+ head.append(f"ssh {cfg.ssh_host_alias}", "kdev.cmd")
+ ends, started = ui.epoch(reach.get("ends")), ui.epoch(reach.get("started"))
+ if ends:
+ return Group(head, ui.countdown(started or ends - 12 * 3600, ends, width=12))
+ return head
+
+
+def _quota_block(cfg: config.Config, live: menu.Live, width: int) -> RenderableType:
+ if not live.ready("quota"):
+ return _loading("reading quota…")
+ rows = live.get("quota")
+ if not isinstance(rows, list) or not rows:
+ return Text("could not read quota", style="kdev.warn")
+ next_hours = cfg.default_hours or 9.0
+ gpu_box = (cfg.default_gpu or "t4") not in ("none", "tpu")
+ total = sum(r.gpu_left for r in rows if not r.error)
+ refill = quota.resets(rows)
+ if len(rows) > 4 or width < 72:
+ best = max((r for r in rows if not r.error), key=lambda r: r.gpu_left, default=None)
+ line = Text.assemble((ui.fmt_hours(total), "bold"), (" of GPU left", "kdev.muted"))
+ line.append(f" {ui.g('bullet')} {len(rows)} accounts", "kdev.muted")
+ if refill:
+ line.append(f" {ui.g('bullet')} refills {ui.fmt_when(refill)}", "kdev.muted")
+ if best and line.cell_len + len(best.name) + 20 < width - 14:
+ line.append(f" {ui.g('bullet')} most: {best.name} {best.hours}", "kdev.muted")
+ return line
+ grid = Table.grid(padding=(0, 2))
+ grid.add_column(no_wrap=True)
+ grid.add_column(no_wrap=True)
+ grid.add_column(no_wrap=True)
+ for r in rows:
+ name = Text.assemble(
+ (ui.g("live") if r.active else " ", "kdev.accent"), " ", (r.name, "bold")
+ )
+ if r.error:
+ grid.add_row(name, Text(r.error[:40], style="kdev.err"), Text(""))
+ continue
+ ghost = 0.0
+ after = ""
+ box = live.get("box") if live.ready("box") else None
+ box_running = isinstance(box, dict) and box.get("running")
+ if r.active and gpu_box and r.gpu_total and width >= 92 and not box_running:
+ ghost = min(next_hours * 3600, r.gpu_left) / r.gpu_total
+ left_after = max(r.gpu_left - next_hours * 3600, 0)
+ after = f"{ui.g('arrow')} {ui.fmt_hours(left_after)} after a {next_hours:g}h box"
+ meter = Text.assemble(
+ ui.bar(r.fraction, width=12, ghost=ghost), (f" {r.hours:>6}", "bold")
+ )
+ grid.add_row(name, meter, Text(after, style="kdev.muted"))
+ if refill:
+ grid.add_row(Text(""), Text(f"refills {ui.fmt_when(refill)}", style="kdev.muted"), Text(""))
+ return grid
+
+
+def _rows() -> int:
+ return shutil.get_terminal_size((80, 24)).lines
+
+
+def _dashboard(cfg: config.Config, live: menu.Live, width: int) -> RenderableType:
+ rows: list[tuple[str, RenderableType]] = [
+ ("box", _box_line(cfg, live)),
+ ("quota", _quota_block(cfg, live, width)),
+ ]
+ # Where it is reached is the least urgent fact: first to go when short.
+ if width >= 60 and _rows() >= 24:
+ rows.append(("workspace", Text(cfg.notebook or "—", style="kdev.muted")))
+ rows.append(
+ (
+ "tunnel",
+ Text(cfg.tunnel_hostname or "quick (new hostname each session)", "kdev.muted"),
+ )
+ )
+ grid = Table.grid(padding=(0, 2))
+ grid.add_column(style="kdev.muted", justify="right", no_wrap=True, min_width=9)
+ grid.add_column(overflow="ellipsis", no_wrap=True)
+ for label, value in rows:
+ grid.add_row(label, value)
+ return Padding(grid, (0, 0, 0, ui.GUTTER))
+
+
+def _ansi(renderable: RenderableType, width: int) -> menu.Fragments:
+ """Draw a rich renderable for prompt_toolkit, at the menu's width."""
+ out = StringIO()
+ target = Console(
+ file=out,
+ width=width,
+ force_terminal=True,
+ color_system="truecolor" if ui.console.color_system == "truecolor" else "256",
+ no_color=ui.console.no_color or ui._no_colour(),
+ theme=ui.THEME,
+ legacy_windows=False,
+ )
+ target.print(renderable)
+ return to_formatted_text(ANSI(out.getvalue().rstrip("\n")))
+
+
+# --- what you can do ----------------------------------------------------------
+
+
+def _items(cfg: config.Config, live: menu.Live) -> list[menu.Item]:
+ box = live.get("box") if live.ready("box") else None
+ known = isinstance(box, dict)
+ running = known and bool(box.get("running")) and not box.get("saving")
+ reach = live.get("reach") if live.ready("reach") else None
+ reachable = isinstance(reach, dict) and bool(reach.get("reachable"))
+ waiting = "" if known else "checking the box…"
+ off = waiting or ("no box is running" if not running else "")
+
+ items: list[menu.Item] = []
+ if not cfg.notebook:
+ items.append(menu.Item("1", "Join your group's workspace", ("workspace", "join")))
+ elif running:
+ editor = session.editor()
+ if editor:
+ items.append(
+ menu.Item("1", "Open in VS Code", ("up", "--open", "code"), note=f"via {editor}")
+ )
+ items.append(
+ menu.Item(
+ str(len(items) + 1),
+ "Open a shell",
+ ("ssh",),
+ note=f"ssh {cfg.ssh_host_alias}",
+ disabled="" if reachable or not live.ready("reach") else "ssh does not answer yet",
+ )
+ )
+ items.append(
+ menu.Item(str(len(items) + 1), "Forward a port", ("forward",), note="localhost → box")
+ )
+ items.append(
+ menu.Item(str(len(items) + 1), "Stop the box", ("down",), note="files are saved")
+ )
+ else:
+ on = f"on {cfg.active}" if cfg.active else ""
+ items.append(
+ menu.Item("1", "Start the box", ("up",), note=f"{box_label(cfg)} {on}".strip())
+ )
+ items.append(
+ menu.Item(
+ "2",
+ "Start a CPU box",
+ ("up", "--gpu", "none", "--hours", "2"),
+ note="2h · no GPU quota",
+ )
+ )
+ items.append(menu.Item("3", "Open a shell", ("ssh",), disabled=off))
+ items.append(menu.Item("4", "Stop the box", ("down",), disabled=off))
+
+ more = [
+ menu.Item("s", "Status", ("status",), group="more"),
+ menu.Item("l", "Logs", ("logs",), group="more"),
+ menu.Item("h", "History", ("history",), group="more"),
+ menu.Item("a", "Accounts", ("account",), group="more"),
+ ]
+ if len(cfg.profiles) > 1:
+ more.append(menu.Item("u", "Switch account", ("account", "use"), group="more"))
+ more += [
+ menu.Item("w", "Workspace", ("workspace",), group="more"),
+ menu.Item("c", "Settings", ("config",), group="more"),
+ menu.Item("d", "Doctor", ("doctor",), group="more"),
+ menu.Item("?", "All commands", ("--help",), group="more"),
+ ]
+ return items + more
+
+
+#: Picks that hand you the box, or end with it gone: the menu's job is done.
+_LEAVES = {
+ ("up",),
+ ("up", "--open", "code"),
+ ("ssh",),
+ ("up", "--gpu", "none", "--hours", "2"),
+ # Kaggle still says "running" while the box saves: coming back to the
+ # menu would show a box you just stopped as up.
+ ("down",),
+}
+
+
+def _ask_args(item: menu.Item) -> list[str]:
+ """The arguments an item needs that only you can give."""
+ argv = list(item.argv)
+ if argv == ["forward"]:
+ port = ui.ask("Port on the box (or LOCAL:REMOTE)", default="8888")
+ argv.append(port)
+ return argv
+
+
+def overview(run_command: Callable[[list[str]], None]) -> None:
"""The home screen. `run_command(argv)` dispatches a picked action."""
cfg = config.load()
if not cfg.profiles:
@@ -24,70 +300,100 @@ def overview(run_command) -> None:
ui.err("kdev is not set up on this machine.", "Run `kdev setup` in a terminal.")
raise typer.Exit(1)
- ui.header()
- with ui.spinner("looking around…"):
- state = {}
- if cfg.notebook:
- try:
- _, state = session.current_status(cfg.profile().creds, cfg.notebook)
- except api.KaggleError:
- state = {}
- running = state.get("status") in api.LIVE_STATES
- reachable = running and session.reachable(cfg.ssh_host_alias)
- rows = quota.rows(cfg)
-
- box = Text.assemble(ui.live_dot(running), " ")
- if not cfg.notebook:
- box.append("no workspace yet", style="kdev.warn")
- elif running:
- box.append("running", style="kdev.running")
- box.append(" reachable" if reachable else " starting or unreachable", style="kdev.muted")
- else:
- box.append("stopped", style="bold")
- box.append(f" files saved in {cfg.notebook}", style="kdev.muted")
- overview = [
- ("box", box),
- ("workspace", cfg.notebook or "—"),
- ("next box", box_label(cfg)),
- ("tunnel", cfg.tunnel_hostname or "quick"),
- ]
- if ui.console.is_terminal:
- ui.card("Workspace", overview)
- else:
- ui.console.print(ui.facts(overview))
- ui.blank()
- ui.section("Accounts", f"{len(rows)} connected")
- ui.console.print(ui.accounts_table(rows))
- ui.blank()
-
if not ui.interactive():
- steps = (
- [("kdev ssh", "open a shell"), ("kdev down", "stop it")]
- if running
- else [("kdev up", "start the box"), ("kdev account", "accounts and quota")]
- )
- ui.next_steps(steps)
+ _plain(cfg)
return
- actions: list[tuple[str, str]] = []
- if not cfg.notebook:
- actions.append(("workspace join", "Join your group's workspace"))
- elif running:
- actions += [
- ("up --open code", "Open it in VS Code"),
- ("ssh", "Open a shell"),
- ("status", "Details"),
- ("down", "Stop it"),
- ]
- else:
- actions += [
- ("up", f"Start the box {box_label(cfg)}"),
- ("up --gpu none --hours 2", "Start a CPU box uses no GPU quota"),
- ]
- if len(cfg.profiles) > 1:
- actions.append(("account use", "Switch account"))
- actions += [("account add", "Add an account"), ("doctor", "Check setup"), ("", "Quit")]
- picked = ui.choose("What now?", [(a, label) for a, label in actions])
- if picked:
+ # The logo is a welcome, not information: it gives way to the menu in a
+ # short terminal (an editor's panel is often 15 rows).
+ ui.header(logo=_rows() >= LOGO_ROWS)
+ while True:
+ cfg = config.load()
+ live = menu.Live()
+
+ def load_box(cfg: config.Config = cfg, live: menu.Live = live) -> dict:
+ box = _box_facts(cfg)
+ if box.get("running") and not box.get("saving"):
+ live.load("reach", lambda: _reach_facts(cfg))
+ return box
+
+ live.load("box", load_box)
+ live.load("quota", lambda cfg=cfg: quota.rows(cfg))
+ picker = menu.Menu(
+ items=lambda cfg=cfg, live=live: _items(cfg, live),
+ dashboard=lambda width, cfg=cfg, live=live: _ansi(_dashboard(cfg, live, width), width),
+ live=live,
+ )
+ picked = picker.run()
+ if picked is None:
+ return
+ try:
+ argv = _ask_args(picked)
+ except Cancelled:
+ continue
+ # The pick, as the command you could have typed: the menu's header for it.
+ ui.header(" ".join(argv))
+ leaves = tuple(picked.argv) in _LEAVES
+ if leaves:
+ _flush_input()
+ with ui.header_given():
+ run_command(argv)
+ return
+ try:
+ with ui.header_given():
+ run_command(argv)
+ except typer.Exit as e:
+ if e.exit_code not in (0, None):
+ ui.hint(f"exited with status {e.exit_code}")
+ except Cancelled:
+ ui.hint("cancelled")
+ except KdevError as e:
+ ui.err(e.message, e.hint)
+ except (api.KaggleError, auth.AuthError, tunnel.TunnelError) as e:
+ ui.err(str(e))
+ except KeyboardInterrupt:
+ ui.blank()
ui.blank()
- run_command(picked.split())
+
+
+def _flush_input() -> None:
+ """Drop keys typed ahead while the menu closed: they belong to kdev, not
+ to the remote shell that is about to open."""
+ try:
+ import sys
+ import termios
+
+ termios.tcflush(sys.stdin, termios.TCIFLUSH)
+ except (ImportError, OSError, ValueError):
+ pass
+
+
+def _plain(cfg: config.Config) -> None:
+ """The overview without a terminal: plain, greppable lines."""
+ ui.header(terminal_only=True)
+ try:
+ box = _box_facts(cfg)
+ except (api.KaggleError, KdevError):
+ box = {"status": "UNKNOWN", "running": False}
+ rows = quota.rows(cfg)
+ running = bool(box.get("running"))
+ word = "running" if running else "stopping" if box.get("saving") else "stopped"
+ ui.console.print(
+ ui.facts(
+ [
+ ("box", word if cfg.notebook else "no workspace yet"),
+ ("workspace", cfg.notebook or "—"),
+ ("next box", box_label(cfg)),
+ ("tunnel", cfg.tunnel_hostname or "quick"),
+ ]
+ )
+ )
+ ui.blank()
+ ui.console.print(ui.accounts_table(rows))
+ ui.blank()
+ steps = (
+ [("kdev ssh", "open a shell"), ("kdev down", "stop it")]
+ if running
+ else [("kdev up", "start the box"), ("kdev account", "accounts and quota")]
+ )
+ ui.next_steps(steps)
diff --git a/src/kdev/commands/settings.py b/src/kdev/commands/settings.py
index af91a51..9c32448 100644
--- a/src/kdev/commands/settings.py
+++ b/src/kdev/commands/settings.py
@@ -10,8 +10,8 @@
import typer
from rich.text import Text
-from .. import api, config, tunnel, ui
-from ..errors import KdevError
+from .. import api, config, session, tunnel, ui
+from ..errors import KdevError, did_you_mean
from ._common import cap_for
app = typer.Typer(
@@ -21,7 +21,10 @@
def _gpu(value: str, cfg: config.Config) -> str:
if value not in api.SHAPES:
- raise KdevError(f"gpu must be one of: {', '.join(api.SHAPES)}.")
+ raise KdevError(
+ f"No accelerator called `{value}`.{did_you_mean(value, api.SHAPES)}",
+ f"Choose one of: {', '.join(api.SHAPES)}",
+ )
cap = cap_for(value)
if cfg.default_hours and cfg.default_hours > cap:
cfg.default_hours = cap
@@ -117,10 +120,28 @@ def _shown(cfg: config.Config, key: str) -> Text:
def _key(name: str) -> Setting:
if name not in SETTINGS:
- raise KdevError(f"No setting called {name!r}.", "Settings: " + ", ".join(SETTINGS))
+ raise KdevError(
+ f"No setting called `{name}`.{did_you_mean(name, SETTINGS)}",
+ "See them all: `kdev config`",
+ )
return SETTINGS[name]
+#: Settings that ~/.ssh/config's kdev block is written from.
+SSH_SETTINGS = ("ssh-alias", "tunnel-hostname")
+
+
+def _sync_ssh(cfg: config.Config, name: str) -> None:
+ """Rewrite the ssh block after a setting it is made of changed: left
+ alone, `kdev ssh` would ask ssh for an alias the file no longer has."""
+ if name not in SSH_SETTINGS:
+ return
+ try:
+ session.ssh_ready(cfg, host_changed=name == "tunnel-hostname")
+ except OSError as e:
+ ui.warn(f"could not update ~/.ssh/config ({e}); the next kdev up will")
+
+
@app.callback()
def main(ctx: typer.Context) -> None:
"""Show every setting."""
@@ -157,6 +178,7 @@ def set_(
setting = _key(name)
setattr(cfg, setting.attr, setting.parse(value, cfg))
config.save(cfg)
+ _sync_ssh(cfg, name)
ui.ok(Text.assemble((name, "bold"), " is now ", _shown(cfg, name)))
@@ -168,4 +190,5 @@ def unset(name: str = typer.Argument(..., help="The setting to reset.")) -> None
setting = _key(name)
setattr(cfg, setting.attr, config.Config.__dataclass_fields__[setting.attr].default)
config.save(cfg)
+ _sync_ssh(cfg, name)
ui.ok(Text.assemble((name, "bold"), " is back to ", _shown(cfg, name)))
diff --git a/src/kdev/commands/tunnel.py b/src/kdev/commands/tunnel.py
index 85de4dd..a9ce1a2 100644
--- a/src/kdev/commands/tunnel.py
+++ b/src/kdev/commands/tunnel.py
@@ -47,24 +47,27 @@ def main(ctx: typer.Context) -> None:
where = f"points at {rec.get('content')}" if rec else "has no record"
rows.append(("dns", Text(f"{ui.g('err')} {where}", style="kdev.err")))
fix = "kdev tunnel setup --force"
- ui.console.print(ui.facts(rows))
+ ui.card(
+ Text.assemble((ui.g("live") + " ", "kdev.ok"), ("named tunnel", "bold")),
+ rows,
+ tone="err" if fix else "muted",
+ )
if fix:
- ui.blank()
ui.next_steps([(fix, "point the hostname back at the tunnel")])
elif cfg.tunnel_token:
- ui.console.print(
- ui.facts(
- [
- ("kind", "managed in the Cloudflare dashboard"),
- ("host", cfg.tunnel_hostname or Text("not set", style="kdev.warn")),
- ]
- )
+ ui.card(
+ Text("dashboard tunnel", style="bold"),
+ [
+ ("kind", "managed in the Cloudflare dashboard"),
+ ("host", cfg.tunnel_hostname or Text("not set", style="kdev.warn")),
+ ],
)
else:
- ui.console.print(
- ui.facts([("kind", Text("quick: a new hostname every session", style="kdev.warn"))])
+ ui.card(
+ Text("quick tunnel", style="bold"),
+ [("kind", Text("a new hostname every session", style="kdev.warn"))],
+ tone="warn",
)
- ui.blank()
ui.next_steps([("kdev tunnel setup", "one hostname that survives drops")])
diff --git a/src/kdev/commands/workspace.py b/src/kdev/commands/workspace.py
index e4d8383..966d29a 100644
--- a/src/kdev/commands/workspace.py
+++ b/src/kdev/commands/workspace.py
@@ -80,6 +80,7 @@ def files(
),
account: str = typer.Option("", "--account", "-a", help="Read as this account."),
as_json: bool = typer.Option(False, "--json", help="Print JSON instead."),
+ every: bool = typer.Option(False, "--all", help="Every file, one per line."),
) -> None:
"""What a saved version holds -- what `kdev up` restores."""
cfg = config.load()
@@ -96,8 +97,10 @@ def files(
else:
# The newest version with files: a running box's own has none.
latest = int(api.get_kernel(creds, target).get("currentVersionNumber") or 0)
- version, found = persistence.newest_saved(creds, target, latest)
- listing = list(found)
+ version, _ = persistence.newest_saved(creds, target, latest)
+ listing = (
+ list(persistence.version_files(creds, target, version) or {}) if version else []
+ )
except api.KaggleError as e:
raise KdevError(
f"Could not read {version or 'the saved files'} of {target}.", str(e)
@@ -114,15 +117,38 @@ def files(
if as_json:
ui.emit_json({"notebook": target, "version": version or None, "files": names})
return
- ui.console.print(
- Text.assemble((target, "bold"), (" " + (version or "no saved version"), "kdev.muted"))
+ if every or not ui.console.is_terminal:
+ for name in names:
+ ui.console.print(name, highlight=False, markup=False, soft_wrap=True)
+ return
+ ui.section(
+ target,
+ f"{version or 'no saved version'} {ui.g('bullet')} {len(names):,} file(s)",
)
- for name in names[:50]:
- ui.hint(name)
- if len(names) > 50:
- ui.hint(f"… and {len(names) - 50} more (--json lists them all)")
if not names:
ui.hint("nothing saved yet")
+ return
+ # A workspace is a few projects, each thousands of files deep: show the
+ # shape -- each top-level entry and how much is under it.
+ tops: dict[str, int] = {}
+ for name in names:
+ head, sep, _ = name.partition("/")
+ key = head + "/" if sep else head
+ tops[key] = tops.get(key, 0) + 1
+ shown = sorted(tops.items(), key=lambda kv: (not kv[0].endswith("/"), kv[0].lower()))
+ grid = ui.Table.grid(padding=(0, 3))
+ grid.add_column(no_wrap=True, overflow="ellipsis")
+ grid.add_column(justify="right", style="kdev.muted", no_wrap=True)
+ for key, count in shown[:40]:
+ folder = key.endswith("/")
+ grid.add_row(
+ Text(key, style="bold kdev.accent" if folder else ""),
+ f"{count:,} file(s)" if folder else "",
+ )
+ ui.console.print(ui.Padding(grid, (0, ui.GUTTER)))
+ if len(shown) > 40:
+ ui.hint(f"… and {len(shown) - 40} more entries")
+ ui.next_steps([("kdev workspace files --all", "every file, one per line")])
@app.command("join")
@@ -139,7 +165,6 @@ def join(account: str = typer.Option("", "--account", "-a", help="Look as this a
if nb.join(cfg, prof.creds, prof.username):
_adopt(cfg, prof.creds)
config.save(cfg)
- ui.blank()
ui.next_steps([("kdev up", "start the box")])
@@ -185,7 +210,6 @@ def create(
ui.ok(f"shared with {group} (Can Edit)")
cfg.notebook, cfg.notebook_id, cfg.group_slug = slug, kid, group
config.save(cfg)
- ui.blank()
ui.next_steps(
[
("kdev up", "start the box"),
diff --git a/src/kdev/config.py b/src/kdev/config.py
index afb7e68..b0a812b 100644
--- a/src/kdev/config.py
+++ b/src/kdev/config.py
@@ -33,12 +33,25 @@ class Profile:
@property
def creds(self) -> Creds:
+ """This account's credentials, with a current token.
+
+ Cheap after the first read in a process: `auth` keeps the token until
+ it is near expiry. Deliberately not cached here as well -- a Profile
+ lives as long as a `kdev up`, which can outlast the token.
+
+ A sign-in that is missing or no longer accepted yields an empty token,
+ so the call it is for fails as "not signed in". One that could not be
+ refreshed for now (offline, Kaggle down) raises `auth.AuthUnavailable`:
+ that is not a reason to sign in again.
+ """
from . import auth
token = ""
if self.name and auth.signed_in(self.name):
try:
token = auth.access_token(self.name)
+ except auth.AuthUnavailable:
+ raise
except auth.AuthError:
token = ""
return Creds(self.username, token)
diff --git a/src/kdev/errors.py b/src/kdev/errors.py
index 194c324..c62042f 100644
--- a/src/kdev/errors.py
+++ b/src/kdev/errors.py
@@ -8,6 +8,8 @@
from __future__ import annotations
+from collections.abc import Iterable
+
class KdevError(Exception):
"""A failure the user can do something about."""
@@ -23,3 +25,13 @@ class Cancelled(KdevError):
def __init__(self) -> None:
super().__init__("cancelled")
+
+
+def did_you_mean(value: str, choices: Iterable[object]) -> str:
+ """` Did you mean `t4`?` for a near miss, else nothing."""
+ import difflib
+
+ close = difflib.get_close_matches(
+ str(value).lower(), [str(c) for c in choices], n=1, cutoff=0.6
+ )
+ return f" Did you mean `{close[0]}`?" if close else ""
diff --git a/src/kdev/menu.py b/src/kdev/menu.py
new file mode 100644
index 0000000..fee703a
--- /dev/null
+++ b/src/kdev/menu.py
@@ -0,0 +1,372 @@
+"""The home screen's live menu: a small inline app, not a full-screen one.
+
+It draws below whatever kdev already printed, so the scrollback stays a
+readable record, and it gives the terminal back the moment you pick
+something. What it adds over a plain list:
+
+ * it is usable at once -- the box and quota fill in while you look, each
+ with its own spinner, instead of a blank wait before anything appears;
+ * every item has a key, and arrows, j/k and enter work too;
+ * the highlighted item shows the exact command it runs, so the menu
+ teaches the scriptable form as you use it;
+ * a running box counts down in place.
+
+Only ever entered from `ui.interactive()`; without a terminal the home
+screen prints plain lines instead.
+"""
+
+from __future__ import annotations
+
+import threading
+import time
+from collections.abc import Callable, Sequence
+from dataclasses import dataclass, field
+
+from prompt_toolkit.application import Application
+from prompt_toolkit.formatted_text import StyleAndTextTuples
+from prompt_toolkit.key_binding import KeyBindings, KeyPressEvent
+from prompt_toolkit.layout import HSplit, Layout, Window
+from prompt_toolkit.layout.controls import FormattedTextControl
+from prompt_toolkit.styles import Style
+
+from . import ui
+
+Fragments = StyleAndTextTuples
+
+
+@dataclass
+class Item:
+ """One thing the menu can do."""
+
+ key: str
+ label: str
+ argv: Sequence[str] = ()
+ #: Shown beside the label: why it is the way it is ("T4 ×2 · 9h").
+ note: str = ""
+ #: Why it cannot be picked right now; empty means it can.
+ disabled: str = ""
+ group: str = ""
+
+ @property
+ def command(self) -> str:
+ return "kdev " + " ".join(self.argv) if self.argv else ""
+
+
+@dataclass
+class Live:
+ """Facts that arrive while the menu is already on screen.
+
+ `slots` maps a name to its value once loaded; a missing name is still
+ loading. Loaders run on threads and only ever assign whole values, so a
+ render never sees half of one.
+ """
+
+ slots: dict[str, object] = field(default_factory=dict)
+ errors: dict[str, str] = field(default_factory=dict)
+ changed: Callable[[], None] = lambda: None
+
+ def load(self, name: str, fn: Callable[[], object]) -> None:
+ def run() -> None:
+ try:
+ self.slots[name] = fn()
+ except Exception as e: # shown in place; never kills the menu
+ self.errors[name] = str(e) or type(e).__name__
+ self.slots[name] = None
+ self.changed()
+
+ threading.Thread(target=run, name=f"kdev-load-{name}", daemon=True).start()
+
+ def ready(self, name: str) -> bool:
+ return name in self.slots
+
+ def get(self, name: str, default: object = None) -> object:
+ return self.slots.get(name, default)
+
+
+STYLE = Style.from_dict(
+ {
+ "accent": f"fg:{ui.ACCENT}",
+ "accent.bold": f"fg:{ui.ACCENT} bold",
+ "muted": "fg:#8a8a8a",
+ "faint": "fg:#5f5f5f",
+ "ok": "fg:ansigreen",
+ "warn": "fg:ansiyellow",
+ "err": "fg:ansired",
+ "bold": "bold",
+ "key": f"fg:{ui.ACCENT} bold",
+ "key.off": "fg:#5f5f5f",
+ "pointer": f"fg:{ui.ACCENT} bold",
+ "label.on": "bold",
+ "label.off": "fg:#6c6c6c",
+ "rail": "fg:#4e4e4e",
+ "cmd": f"fg:{ui.ACCENT}",
+ }
+)
+MONO = Style.from_dict({})
+
+
+def spinner_frame() -> str:
+ frames = ui._spinner_frames()
+ return frames[int(time.monotonic() * 10) % len(frames)]
+
+
+#: Terminal heights (rows) at which the menu folds its secondary parts.
+SHORT = 20
+TINY = 15
+
+
+class Menu:
+ """Pick one item; returns it, or None for quit.
+
+ `dashboard()` is redrawn ten times a second, so it can show spinners and
+ countdowns; it must be cheap and must not block.
+ """
+
+ def __init__(
+ self,
+ items: Callable[[], Sequence[Item]],
+ dashboard: Callable[[int], Fragments],
+ live: Live | None = None,
+ title: str = "What now?",
+ *,
+ input=None, # prompt_toolkit input and output, for tests
+ output=None,
+ ):
+ self._items = items
+ self._dashboard = dashboard
+ self.live = live or Live()
+ self.title = title
+ self.index = 0
+ self.flash = ""
+ self._app: Application | None = None
+ self._io = {"input": input, "output": output}
+
+ # --- state ----------------------------------------------------------------
+
+ def _enabled(self) -> list[int]:
+ return [i for i, item in enumerate(self._items()) if not item.disabled]
+
+ def _move(self, step: int) -> None:
+ items = self._items()
+ if not items:
+ return
+ for _ in range(len(items)):
+ self.index = (self.index + step) % len(items)
+ if not items[self.index].disabled:
+ break
+ self.flash = ""
+
+ def _settle(self) -> None:
+ """Keep the pointer on something pickable as items change under it."""
+ items = self._items()
+ if not items:
+ self.index = 0
+ return
+ self.index = min(self.index, len(items) - 1)
+ if items[self.index].disabled:
+ enabled = self._enabled()
+ if enabled:
+ self.index = min(enabled, key=lambda i: abs(i - self.index))
+
+ # --- drawing --------------------------------------------------------------
+
+ def _height(self) -> int:
+ try:
+ return self._app.output.get_size().rows if self._app else 24
+ except Exception:
+ return 24
+
+ def _width(self) -> int:
+ try:
+ return min(self._app.output.get_size().columns, ui.MAX_WIDTH) if self._app else 80
+ except Exception:
+ return 80
+
+ def _render_menu(self) -> Fragments:
+ """Main items one per line, numbered; the rest as a row of keyed chips."""
+ self._settle()
+ width = self._width()
+ items = self._items()
+ out: Fragments = []
+ pad = " " * ui.GUTTER
+ out += [("", "\n"), ("", pad), ("class:bold", self.title), ("", "\n")]
+ main = [(n, i) for n, i in enumerate(items) if not i.group]
+ more = [(n, i) for n, i in enumerate(items) if i.group]
+ label_w = max((len(i.label) for _, i in main), default=0)
+ show_notes = width >= ui.GUTTER + 6 + label_w + 16
+ for n, item in main:
+ on, off = n == self.index, bool(item.disabled)
+ out.append(("", pad))
+ out.append(("class:pointer", ui.g("prompt") + " ") if on else ("", " "))
+ out.append(("class:key.off" if off else "class:key", item.key))
+ out.append(("", " "))
+ label_style = "class:label.off" if off else "class:label.on" if on else ""
+ out.append((label_style, item.label.ljust(label_w)))
+ note = item.disabled or item.note
+ if note and show_notes:
+ room = width - ui.GUTTER - 6 - label_w - 3
+ if len(note) > room:
+ note = note[: max(room - 1, 0)] + ("…" if room > 1 else "")
+ out.append(("class:faint" if off else "class:muted", " " + note))
+ out.append(("", "\n"))
+ # A short terminal (an editor's panel) keeps every key on one line:
+ # the label of the chip under the pointer, the others as bare keys.
+ compact = self._height() < SHORT
+ if more:
+ out.append(("", "\n"))
+ line_len = ui.GUTTER
+ out.append(("", pad))
+ if compact:
+ out.append(("class:faint", "more "))
+ for n, item in more:
+ on = n == self.index
+ if compact:
+ out.append(("class:pointer", ui.g("prompt")) if on else ("", " "))
+ out.append(("class:key", item.key))
+ if on:
+ out.append(("class:label.on", " " + item.label))
+ continue
+ chip = 2 + len(item.key) + 1 + len(item.label) + 1
+ if line_len + chip > width and line_len > ui.GUTTER:
+ out += [("", "\n"), ("", pad)]
+ line_len = ui.GUTTER
+ out.append(("class:pointer", ui.g("prompt") + " ") if on else ("", " "))
+ out.append(("class:key", item.key))
+ out.append(("class:label.on" if on else "class:muted", " " + item.label + " "))
+ line_len += chip
+ return out
+
+ def _render_footer(self) -> Fragments:
+ items = self._items()
+ current = items[self.index] if items else None
+ pad = " " * ui.GUTTER
+ out: Fragments = [("", "\n")]
+ if self.flash:
+ out += [("", pad), ("class:warn", self.flash), ("", "\n")]
+ elif current and current.command:
+ out += [
+ ("", pad),
+ ("class:faint", "$ "),
+ ("class:cmd", current.command),
+ ("", "\n"),
+ ]
+ else:
+ out += [("", "\n")]
+ if self._height() < TINY:
+ return out[:-1] if out and out[-1] == ("", "\n") else out
+ sep = f" {ui.g('bullet')} "
+ keys = [
+ ("↑↓" if not ui._ascii_only() else "up/down", "move"),
+ ("enter", "run"),
+ ("1-9 a-z", "pick"),
+ ("q", "quit"),
+ ]
+ out.append(("", pad))
+ for i, (key, what) in enumerate(keys):
+ if i:
+ out.append(("class:faint", sep))
+ out += [("class:muted bold", key), ("class:faint", " " + what)]
+ return out
+
+ # --- running --------------------------------------------------------------
+
+ def run(self) -> Item | None:
+ kb = KeyBindings()
+ result: dict[str, Item | None] = {"item": None}
+
+ def pick(event: KeyPressEvent, item: Item) -> None:
+ if item.disabled:
+ self.flash = f"{item.label}: {item.disabled}"
+ return
+ result["item"] = item
+ event.app.exit()
+
+ @kb.add("down")
+ @kb.add("j")
+ @kb.add("tab")
+ def _down(event: KeyPressEvent) -> None:
+ self._move(1)
+
+ @kb.add("up")
+ @kb.add("k")
+ @kb.add("s-tab")
+ def _up(event: KeyPressEvent) -> None:
+ self._move(-1)
+
+ @kb.add("enter")
+ @kb.add("right")
+ def _enter(event: KeyPressEvent) -> None:
+ items = self._items()
+ if items:
+ pick(event, items[self.index])
+
+ @kb.add("q")
+ @kb.add("escape", eager=True)
+ @kb.add("c-c")
+ @kb.add("c-d")
+ def _quit(event: KeyPressEvent) -> None:
+ result["item"] = None
+ event.app.exit()
+
+ @kb.add("")
+ def _key(event: KeyPressEvent) -> None:
+ pressed = event.data.lower()
+ for n, item in enumerate(self._items()):
+ if item.key == pressed:
+ self.index = n
+ pick(event, item)
+ return
+
+ def plain(render: Callable[[], Fragments]) -> Callable[[], Fragments]:
+ if not ui._ascii_only():
+ return render
+
+ def translated() -> Fragments:
+ return [(f[0], f[1].translate(ui._ASCII)) for f in render()]
+
+ return translated
+
+ body = HSplit(
+ [
+ Window(
+ FormattedTextControl(plain(lambda: self._dashboard(self._width()))),
+ dont_extend_height=True,
+ wrap_lines=False,
+ ),
+ Window(
+ FormattedTextControl(plain(self._render_menu)),
+ dont_extend_height=True,
+ wrap_lines=False,
+ ),
+ Window(
+ FormattedTextControl(plain(self._render_footer)),
+ dont_extend_height=True,
+ wrap_lines=False,
+ ),
+ ]
+ )
+ style = MONO if ui._no_colour() or ui.console.no_color else STYLE
+ self._app = Application(
+ layout=Layout(body),
+ key_bindings=kb,
+ style=style,
+ full_screen=False,
+ erase_when_done=True,
+ refresh_interval=0.1,
+ mouse_support=False,
+ include_default_pygments_style=False,
+ **{k: v for k, v in self._io.items() if v is not None},
+ )
+ app = self._app
+
+ def changed() -> None:
+ # Called from loader threads: invalidate is the one safe call.
+ app.invalidate()
+
+ self.live.changed = changed
+ try:
+ app.run()
+ finally:
+ self.live.changed = lambda: None
+ self._app = None
+ return result["item"]
diff --git a/src/kdev/notebook.py b/src/kdev/notebook.py
index 62c446a..32b9616 100644
--- a/src/kdev/notebook.py
+++ b/src/kdev/notebook.py
@@ -11,8 +11,9 @@
from __future__ import annotations
import re
+from concurrent.futures import ThreadPoolExecutor
-from . import api, bootstrap, config, persistence, ui
+from . import api, bootstrap, config, persistence, safety, ui
from .errors import KdevError
PLACEHOLDER = "# kdev workspace notebook -- source is generated per session.\n"
@@ -49,6 +50,10 @@ def discover(creds: api.Creds) -> list[tuple[str, str]]:
]
+#: Notebooks read at once by `scan`. Small: each is two calls on one account.
+SCAN_WORKERS = 4
+
+
def scan(creds: api.Creds) -> tuple[list[dict], list[dict]]:
"""Which groups this account is in, and which notebooks each shares.
@@ -57,11 +62,20 @@ def scan(creds: api.Creds) -> tuple[list[dict], list[dict]]:
and the sharing policy on each. A group with no shared notebook is
therefore invisible, which is why creating the first box asks for a slug.
"""
- notebooks = []
- for ref, title in discover(creds):
+
+ def read(found: tuple[str, str]) -> dict:
+ ref, title = found
kid = api.kernel_id(creds, ref)
groups = api.policy_groups(api.get_policy(creds, kid)) if kid else []
- notebooks.append({"ref": ref, "title": title, "id": kid, "groups": groups})
+ return {"ref": ref, "title": title, "id": kid, "groups": groups}
+
+ shared = discover(creds)
+ # Two calls per notebook, none depending on another: read them at once.
+ # `map` keeps the listing's order.
+ notebooks: list[dict] = []
+ if shared:
+ with ThreadPoolExecutor(max_workers=min(SCAN_WORKERS, len(shared))) as pool:
+ notebooks = list(pool.map(read, shared))
by_slug: dict[str, dict] = {}
for nb in notebooks:
for g in nb["groups"]:
@@ -89,21 +103,38 @@ def describe(cfg: config.Config, creds: api.Creds) -> dict:
cfg.notebook_id = cfg.notebook_id or int(meta.get("id") or 0)
except (api.KaggleError, TypeError, ValueError) as e:
out["errors"].append(f"notebook: {e}")
- if cfg.group_slug and cfg.notebook_id:
- try:
- out["role"] = api.group_role(api.get_policy(creds, cfg.notebook_id), cfg.group_slug)
- except api.KaggleError as e:
- out["errors"].append(f"sharing: {e}")
- try:
- out["members"] = [
- m.get("username", "?") for m in api.group_members(creds, cfg.group_slug)
- ]
- except api.KaggleError as e:
- out["errors"].append(f"members: {e}")
- # The newest version with files, not the newest version: while a box runs
- # its own has none yet, and "0 files" reads as everything being lost.
- out["saved"], files = persistence.newest_saved(creds, cfg.notebook, out["version"])
- out["files"] = len(files) if out["saved"] else None
+ sharing = bool(cfg.group_slug and cfg.notebook_id)
+ group, kid = cfg.group_slug, cfg.notebook_id
+
+ def role() -> str:
+ return api.group_role(api.get_policy(creds, kid), group)
+
+ def members() -> list[str]:
+ return [m.get("username", "?") for m in api.group_members(creds, group)]
+
+ def saved() -> tuple[str, int | None]:
+ # The newest version with files, not the newest version: while a box
+ # runs its own has none yet, and "0 files" reads as everything lost.
+ label, _ = persistence.newest_saved(creds, cfg.notebook, out["version"])
+ return label, (persistence.file_count(creds, cfg.notebook, label) if label else None)
+
+ # Independent reads, each one or more round trips: run them together.
+ with ThreadPoolExecutor(max_workers=3) as pool:
+ role_f = pool.submit(role) if sharing else None
+ members_f = pool.submit(members) if sharing else None
+ saved_f = pool.submit(saved)
+ # Errors are reported in a fixed order, whichever call failed first.
+ if role_f is not None:
+ try:
+ out["role"] = role_f.result()
+ except api.KaggleError as e:
+ out["errors"].append(f"sharing: {e}")
+ if members_f is not None:
+ try:
+ out["members"] = members_f.result()
+ except api.KaggleError as e:
+ out["errors"].append(f"members: {e}")
+ out["saved"], out["files"] = saved_f.result()
return out
@@ -150,7 +181,11 @@ def create(creds: api.Creds, owner: str, title: str) -> tuple[str, int]:
raise KdevError(f"{title!r} makes an empty notebook name.", "Use letters or digits.")
try:
existing = api.get_kernel(creds, slug)
- except api.KaggleError:
+ except api.KaggleError as e:
+ # Only "not there" clears the way. A failed read is not an empty
+ # name: guessing wrong here replaces a real notebook's source.
+ if not safety.missing(e, creds, slug):
+ raise
existing = {}
if existing.get("id"):
raise KdevError(
@@ -201,8 +236,6 @@ def use(cfg: config.Config, creds: api.Creds, ref: str) -> None:
def join(cfg: config.Config, creds: api.Creds, owner: str) -> bool:
"""Interactive: pick the group, then a notebook in it or a new one."""
- from . import safety
-
with ui.spinner("reading your groups and notebooks…"):
groups, _ = scan(creds)
diff --git a/src/kdev/persistence.py b/src/kdev/persistence.py
index c8352bd..c164008 100644
--- a/src/kdev/persistence.py
+++ b/src/kdev/persistence.py
@@ -19,8 +19,11 @@
from __future__ import annotations
import json
+import os
import subprocess
+import threading
import time
+from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import httpx
@@ -85,6 +88,22 @@ def version_files(creds: api.Creds, notebook: str, label: str) -> dict[str, str]
return {f["name"]: f["url"] for f in files}
+def version_meta(creds: api.Creds, notebook: str, label: str) -> dict[str, str] | None:
+ """Like `version_files`, but only `.kdev/` is guaranteed complete.
+
+ Enough to read a version's saved state and tell whether it holds files,
+ for a fraction of the calls: a 2,400-file workspace lists in five pages
+ of about 2s each, and its `.kdev/` names all sit on the first.
+ """
+ try:
+ files = api.session_output(creds, notebook, label, prefix=".kdev/")
+ except api.KaggleError as e:
+ if e.status == 404:
+ return None
+ raise
+ return {f["name"]: f["url"] for f in files}
+
+
def _state(files: dict[str, str]) -> dict | None:
"""The .kdev/state.json a version saved, fetched through its own URL."""
url = files.get(STATE)
@@ -128,7 +147,7 @@ def newest_saved(creds: api.Creds, notebook: str, latest: int) -> tuple[str, dic
"""
number, remaining, unconfirmed = latest, WALK_BACK, 0
while number > 0 and remaining > 0:
- files = version_files(creds, notebook, f"v{number}")
+ files = version_meta(creds, notebook, f"v{number}")
if files:
state = _state(files)
if STATE in files and state is None:
@@ -148,6 +167,44 @@ def newest_saved(creds: api.Creds, notebook: str, latest: int) -> tuple[str, dic
return "", {}
+_ENDED = frozenset({"COMPLETE", "ERROR", "CANCEL_ACKNOWLEDGED"})
+_cache_lock = threading.Lock()
+
+
+def _history_cache_path() -> Path:
+ return _config.CONFIG_DIR / "cache" / "history.json"
+
+
+def _history_cache() -> dict:
+ try:
+ data = json.loads(_history_cache_path().read_text())
+ except (OSError, ValueError):
+ return {}
+ return data if isinstance(data, dict) else {}
+
+
+def _save_history_cache(cache: dict) -> None:
+ path = _history_cache_path()
+ try:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ tmp = path.with_suffix(f".{os.getpid()}.tmp")
+ tmp.write_text(json.dumps(cache, sort_keys=True))
+ tmp.replace(path)
+ except OSError:
+ pass # only a cache
+
+
+def file_count(creds: api.Creds, notebook: str, label: str) -> int:
+ """How many of your files a saved version holds -- kdev's own `.kdev/`
+ bookkeeping excluded, the same count `kdev history` shows. An ended
+ version's count is remembered, so this is usually free."""
+ hit = _history_cache().get(f"{notebook}@{label}")
+ if isinstance(hit, dict) and hit.get("status") in _ENDED and isinstance(hit.get("files"), int):
+ return hit["files"]
+ files = version_files(creds, notebook, label) or {}
+ return sum(not name.startswith(".kdev/") for name in files)
+
+
def session_history(creds: api.Creds, notebook: str, latest: int, limit: int = 10) -> list[dict]:
"""Recent saved sessions, newest first.
@@ -155,31 +212,60 @@ def session_history(creds: api.Creds, notebook: str, latest: int, limit: int = 1
metadata comes from the version itself and run status is requested for the
same version label.
"""
- rows: list[dict] = []
- for number in range(latest, max(0, latest - WALK_BACK), -1):
- if len(rows) >= limit:
- break
- label = f"v{number}"
- files = version_files(creds, notebook, label)
- if not files:
- continue
- state = _state(files) or {}
+
+ cache = _history_cache()
+
+ def read(label: str) -> dict | None:
+ key = f"{notebook}@{label}"
+ hit = cache.get(key)
+ if isinstance(hit, dict) and hit.get("status") in _ENDED:
+ return dict(hit)
+ # Status before the listing: a version still saving when listed may
+ # end a moment later, and its partial file count must not be cached
+ # as final. Only a version that had ended before it was listed is.
try:
status = api.session_status(creds, notebook, label)
except api.KaggleError:
status = {"status": "UNKNOWN"}
- rows.append(
- {
- "version": label,
- "run_by": state.get("run_by") or None,
- "started": state.get("started") or None,
- "ends": state.get("ends") or None,
- "status": status.get("status") or "UNKNOWN",
- "files": sum(not name.startswith(".kdev/") for name in files),
- "restored": state.get("restored") if "restored" in state else None,
- "restore_finished": state.get("finished") or None,
- }
- )
+ files = version_files(creds, notebook, label)
+ if not files:
+ return None
+ state = _state(files) or {}
+ row = {
+ "version": label,
+ "run_by": state.get("run_by") or None,
+ "started": state.get("started") or None,
+ "ends": state.get("ends") or None,
+ "status": status.get("status") or "UNKNOWN",
+ "files": sum(not name.startswith(".kdev/") for name in files),
+ "restored": state.get("restored") if "restored" in state else None,
+ "restore_finished": state.get("finished") or None,
+ }
+ if row["status"] in _ENDED:
+ # A version that has ended never changes again: remember it.
+ with _cache_lock:
+ cache[key] = row
+ return row
+
+ # Empty versions do not count towards `limit`, so the window must be
+ # wider than it -- but bounded, since each version costs a full listing.
+ window = max(WALK_BACK, limit * 2)
+ labels = [f"v{n}" for n in range(latest, max(0, latest - window), -1)]
+ rows: list[dict] = []
+ # Read a batch at once, newest first in the result: each version is
+ # several seconds of paging, and none depends on another. Later batches
+ # are only read while `limit` is not yet met.
+ batch = max(WALK_BACK, limit)
+ # Four at a time: more finishes no sooner (each version is paged in
+ # order) and trips Kaggle's rate limit.
+ with ThreadPoolExecutor(max_workers=max(1, min(4, len(labels)))) as pool:
+ for start in range(0, len(labels), batch):
+ for row in pool.map(read, labels[start : start + batch]):
+ if row and len(rows) < limit:
+ rows.append(row)
+ if len(rows) >= limit:
+ break
+ _save_history_cache(cache)
return rows
@@ -214,7 +300,13 @@ def _still_needed(top: dict[str, str]):
def build_plan(creds: api.Creds, notebook: str, labels: list[str]) -> dict:
"""Fresh signed URLs for each layer, resolved just before they are used."""
- listed = [(label, version_files(creds, notebook, label)) for label in labels]
+ # Listed together: each is a few seconds of paging, and none depends on another.
+ with ThreadPoolExecutor(max_workers=max(1, min(4, len(labels)))) as pool:
+ listed = list(
+ zip(
+ labels, pool.map(lambda lb: version_files(creds, notebook, lb), labels), strict=True
+ )
+ )
listed = [(label, files) for label, files in listed if files]
needed = _still_needed(listed[-1][1]) if len(listed) > 1 else None
layers = []
@@ -341,13 +433,26 @@ def follow(alias: str, progress=None) -> tuple[bool, dict]:
return bool(last.get("restored")), last
+#: The longest one sync may take. A stalled tunnel otherwise hangs forever.
+RSYNC_TIMEOUT = 1800
+
+
def _rsync(src: str, dst: str, *extra: str, excludes: bool = True) -> subprocess.CompletedProcess:
cmd = ["rsync", "-az", "--partial", *extra, "-e", "ssh -o BatchMode=yes -o ConnectTimeout=20"]
if excludes:
for pattern in EXCLUDES:
cmd += ["--exclude", pattern]
cmd += [src, dst]
- return subprocess.run(cmd, capture_output=True, text=True, timeout=1800)
+ try:
+ return subprocess.run(cmd, capture_output=True, text=True, timeout=RSYNC_TIMEOUT)
+ except subprocess.TimeoutExpired:
+ # Reported like any failed sync: push and pull keep their (ok, err)
+ # answer, and --partial lets the next attempt pick up where this left.
+ return subprocess.CompletedProcess(
+ cmd, 124, "", f"rsync timed out after {RSYNC_TIMEOUT // 60} min"
+ )
+ except OSError as e:
+ return subprocess.CompletedProcess(cmd, 127, "", f"could not run rsync: {e}")
def wait_reachable(alias: str, timeout: int = 180) -> bool:
@@ -359,12 +464,18 @@ def wait_reachable(alias: str, timeout: int = 180) -> bool:
"""
deadline = time.time() + timeout
while time.time() < deadline:
- r = subprocess.run(
- ["ssh", "-T", "-o", "BatchMode=yes", "-o", "ConnectTimeout=10", alias, "true"],
- capture_output=True,
- )
- if r.returncode == 0:
- return True
+ try:
+ # ConnectTimeout covers the TCP connect only; a ProxyCommand that
+ # connects and then stalls would hang here without a cap.
+ r = subprocess.run(
+ ["ssh", "-T", "-o", "BatchMode=yes", "-o", "ConnectTimeout=10", alias, "true"],
+ capture_output=True,
+ timeout=30,
+ )
+ if r.returncode == 0:
+ return True
+ except subprocess.TimeoutExpired:
+ pass
time.sleep(5)
return False
diff --git a/src/kdev/quota.py b/src/kdev/quota.py
index 4668b7e..337e193 100644
--- a/src/kdev/quota.py
+++ b/src/kdev/quota.py
@@ -9,7 +9,9 @@
from concurrent.futures import ThreadPoolExecutor
-from . import api, config, ui
+import httpx
+
+from . import api, auth, config, ui
from .errors import KdevError
@@ -33,6 +35,10 @@ def remaining(quota: dict, kind: str = "gpuQuota") -> tuple[int, int]:
return max(total - used, 0), total
+#: A quota row's error when Kaggle could not be reached at all.
+OFFLINE = "offline: could not reach Kaggle"
+
+
def _row(cfg: config.Config, name: str) -> ui.ProfileRow:
prof = cfg.profiles[name]
row = ui.ProfileRow(
@@ -41,13 +47,39 @@ def _row(cfg: config.Config, name: str) -> ui.ProfileRow:
try:
q = api.quota(prof.creds)
except api.KaggleError as e:
- row.error = "signed out: kdev account add " + name if e.status == 401 else str(e)[:48]
+ if e.status == 401:
+ row.error = "signed out: kdev account add " + name
+ elif e.status == 0:
+ row.error = OFFLINE
+ else:
+ row.error = str(e)[:48]
+ return row
+ except auth.AuthUnavailable:
+ row.error = OFFLINE
+ return row
+ except auth.AuthError:
+ row.error = "signed out: kdev account add " + name
+ return row
+ except (httpx.HTTPError, OSError) as e:
+ row.error = str(e)[:48] or type(e).__name__
return row
row.gpu_left, row.gpu_total = remaining(q)
row.tpu_left, row.tpu_total = remaining(q, "tpuQuota")
+ row.resets = ui.epoch(q.get("quotaRefreshTime"))
return row
+def row(cfg: config.Config, name: str) -> ui.ProfileRow:
+ """One account's quota; errors are on the row, never raised."""
+ return _row(cfg, name)
+
+
+def resets(rows: list[ui.ProfileRow]) -> float:
+ """The next quota refill among the accounts (Kaggle refills them all at
+ the same weekly moment), or 0 if no account said."""
+ return min((r.resets for r in rows if r.resets), default=0.0)
+
+
def rows(cfg: config.Config) -> list[ui.ProfileRow]:
"""Every account's quota, read in parallel -- one slow account must not
make the whole screen wait N times over."""
diff --git a/src/kdev/safety.py b/src/kdev/safety.py
index feebaf7..16a6a09 100644
--- a/src/kdev/safety.py
+++ b/src/kdev/safety.py
@@ -54,6 +54,19 @@ def prune(prefix: str, keep: int = KEEP_BACKUPS) -> None:
path.unlink(missing_ok=True)
+def missing(e: api.KaggleError, creds: api.Creds, slug: str) -> bool:
+ """Whether a failed GetKernel means the notebook is not there.
+
+ Kaggle answers 403 "Permission 'kernels.get' was denied", not 404, for a
+ slug that does not exist in your own namespace (measured). In anyone
+ else's, a 403 may just mean "not shared with you", so only 404 counts.
+ """
+ if e.status == 404:
+ return True
+ owner = slug.partition("/")[0]
+ return e.status == 403 and bool(owner) and owner.lower() == creds.username.lower()
+
+
def check(creds: api.Creds, slug: str) -> tuple[str, str, Path | None]:
"""Classify a notebook before kdev writes to it.
@@ -62,7 +75,11 @@ def check(creds: api.Creds, slug: str) -> tuple[str, str, Path | None]:
"""
try:
source = api.kernel_source(creds, slug)
- except api.KaggleError:
+ except api.KaggleError as e:
+ if not missing(e, creds, slug):
+ # Offline, signed out, Kaggle down: the notebook may well exist
+ # and hold work. "Could not look" is never "nothing there".
+ raise
# A notebook that does not exist yet is safe to create.
return "safe", "", None
diff --git a/src/kdev/session.py b/src/kdev/session.py
index 41be560..1db6a3f 100644
--- a/src/kdev/session.py
+++ b/src/kdev/session.py
@@ -69,7 +69,7 @@ def current_status(creds: api.Creds, slug: str) -> tuple[str, dict]:
elif candidate.get("status") == api.SAVING:
saving = label, candidate
elif candidate.get("status") in ENDED_STATES:
- files = persistence.version_files(creds, slug, label) or {}
+ files = persistence.version_meta(creds, slug, label) or {}
saved = persistence._state(files)
if persistence.STATE in files and saved is None:
raise KdevError(f"Could not read the saved startup state of {label}.")
@@ -236,15 +236,33 @@ def cancel_created(creds: api.Creds, slug: str, version: str, timeout: int = REA
raise KdevError(f"Duplicate {version} has not finished stopping.", hint)
-def ssh_ready(cfg: config.Config) -> None:
+def ssh_ready(cfg: config.Config, *, host_changed: bool = False) -> None:
"""Make `ssh ` -- and VS Code's host of that name -- work here.
A named tunnel's hostname never changes, so the block needs no box to look
at: a machine that did not start the running box, or that ran `kdev down`
on the last one, can still reach the next.
+
+ An existing block keeps its hostname unless `host_changed` says the
+ configured one was just changed: a box another machine started on a
+ quick tunnel is reachable only at the hostname the block already has.
"""
- if cfg.tunnel_hostname and cfg.ssh_host_alias and not sshcfg.has_block():
- sshcfg.write(cfg.ssh_host_alias, cfg.tunnel_hostname, cloudflared_path=cloudflared.find())
+ if not cfg.ssh_host_alias:
+ return
+ block = sshcfg.current()
+ if block is None:
+ if cfg.tunnel_hostname:
+ sshcfg.write(
+ cfg.ssh_host_alias, cfg.tunnel_hostname, cloudflared_path=cloudflared.find()
+ )
+ return
+ alias, host = block
+ # The alias was renamed since the block was written (`kdev config set
+ # ssh-alias`): `ssh ` would find no such host. Only the name moves;
+ # the hostname may be a quick tunnel's, which only the box knows.
+ want = (host_changed and cfg.tunnel_hostname) or host
+ if alias != cfg.ssh_host_alias or want != host:
+ sshcfg.write(cfg.ssh_host_alias, want, cloudflared_path=cloudflared.find())
def box_gone(cfg: config.Config) -> None:
diff --git a/src/kdev/sshcfg.py b/src/kdev/sshcfg.py
index fd5d6c9..1421d3a 100644
--- a/src/kdev/sshcfg.py
+++ b/src/kdev/sshcfg.py
@@ -48,20 +48,66 @@ def render_block(
)
+#: A line that opens a stanza. ssh takes the first value it finds for each
+#: option, so a block below a `Host *` loses every option that one sets.
+_STANZA_RE = re.compile(r"^\s*(host|match)(\s|=)", re.IGNORECASE)
+
+
+def _without_block(text: str) -> str:
+ """The file with kdev's block cut out, and the gap it leaves closed."""
+ while m := BLOCK_RE.search(text):
+ before, after = text[: m.start()].rstrip("\n"), text[m.end() :].lstrip("\n")
+ text = before + ("\n\n" if before and after else "\n" if before else "") + after
+ return text
+
+
+def _insert_at(lines: list[str]) -> int:
+ """Where the block goes: above the first stanza, and above the comments
+ directly on top of it, which belong to that stanza. Global options and
+ `Include`s before any stanza stay first; they apply to every host."""
+ for i, line in enumerate(lines):
+ if _STANZA_RE.match(line):
+ while i > 0 and lines[i - 1].lstrip().startswith("#"):
+ i -= 1
+ return i
+ return len(lines)
+
+
def write(
alias: str, hostname: str, user: str = "root", cloudflared_path: Path | None = None
) -> Path:
+ """Put the block in ~/.ssh/config ahead of every other stanza.
+
+ Written in place, not via a rename, so a symlinked config (dotfiles)
+ stays a symlink. An earlier block -- even one below a `Host *` -- is
+ moved, not duplicated; nothing else in the file changes.
+ """
SSH_CONFIG.parent.mkdir(mode=0o700, exist_ok=True)
existing = SSH_CONFIG.read_text() if SSH_CONFIG.exists() else ""
- stripped = BLOCK_RE.sub("\n", existing).strip()
- body = (stripped + "\n\n" if stripped else "") + render_block(
- alias, hostname, user, cloudflared_path
- )
+ lines = _without_block(existing).strip("\n").splitlines(keepends=True)
+ if lines and not lines[-1].endswith("\n"):
+ lines[-1] += "\n"
+ at = _insert_at(lines)
+ head, tail = "".join(lines[:at]).rstrip("\n"), "".join(lines[at:]).lstrip("\n")
+ block = render_block(alias, hostname, user, cloudflared_path)
+ body = (head + "\n\n" if head else "") + block + ("\n" + tail if tail else "")
SSH_CONFIG.write_text(body)
SSH_CONFIG.chmod(0o600)
return SSH_CONFIG
+def current() -> tuple[str, str] | None:
+ """(alias, hostname) of the block in ~/.ssh/config, or None if none."""
+ if not SSH_CONFIG.exists():
+ return None
+ m = BLOCK_RE.search(SSH_CONFIG.read_text())
+ if not m:
+ return None
+ alias = re.search(r"^\s*Host\s+(\S+)", m.group(0), re.MULTILINE)
+ host = re.search(r"^\s*HostName\s+(\S+)", m.group(0), re.MULTILINE)
+ return (alias.group(1) if alias else "", host.group(1) if host else "")
+
+
def has_block() -> bool:
"""Whether ~/.ssh/config currently points the alias at a session."""
return SSH_CONFIG.exists() and BEGIN in SSH_CONFIG.read_text()
@@ -69,4 +115,4 @@ def has_block() -> bool:
def clear() -> None:
if SSH_CONFIG.exists():
- SSH_CONFIG.write_text(BLOCK_RE.sub("\n", SSH_CONFIG.read_text()).strip() + "\n")
+ SSH_CONFIG.write_text(_without_block(SSH_CONFIG.read_text()).strip("\n") + "\n")
diff --git a/src/kdev/ui.py b/src/kdev/ui.py
index 979a5c7..577d617 100644
--- a/src/kdev/ui.py
+++ b/src/kdev/ui.py
@@ -1,13 +1,16 @@
"""kdev's design system. Every command builds its output from these parts only.
Not a full-screen app, on purpose: `kdev up` ends by handing you a shell, and a
-UI you have to quit first would be in the way. The references, and what each
-contributed:
-
- Docker Compose the status board -- a line per step, each with its own clock
- fly / vercel the result card -- the few facts that matter, and the command
+UI you have to quit first would be in the way. The home screen (`kdev.menu`)
+is an inline app that gives the terminal back the moment you pick. The
+references, and what each contributed:
+
+ Mole (tw93) the front door: a keyed menu, and every action also a command
+ clack the rail that long, linear work is drawn on
+ Docker Compose a clock per step, so a slow step is visibly slow
+ fly / vercel the result card -- the few facts that matter, the command
to copy
- gh glyph-and-gutter status lines, and data on stdout
+ gh / Primer glyph-and-gutter status lines; piped output as plain words
Charm a quiet palette where colour carries meaning, not decoration
Tokens
@@ -18,16 +21,23 @@
muted grey labels, secondary facts, hints
bold the values that matter: hosts, names, counts
-Glyphs ✓ done ! attention ✗ failed ● live ○ idle/pending › step
+Glyphs ✓ done ! attention ✗ failed ● live ○ pending › prompt ◇ step done
+ ┌ │ └ the rail █ ▒ ░ a bar: left now, what the next box uses, used
Components
- header(title, facts) pixel logo in colour terminals, then the command context
- ok / warn / err a status line; `hint` sits indented beneath
+ header(title, ctx) the logo on the front door and in setup; one line,
+ `›_ kdev › status`, everywhere else
+ ok / warn / err a status line; `hint` sits indented beneath; text in
+ `backticks` is drawn as a command
facts(rows) aligned label/value pairs
card(title, rows) the command's result, with facts and next actions
- table(...) restrained headers; labeled records on narrow terminals
- Stages the live board for long operations
- next_steps(cmds) what to run next, commands in accent
+ section(title) `Accounts ──────── 3 connected`, one line
+ table(...) restrained headers; labeled records when narrow;
+ tab-separated words when piped
+ Stages the rail for long operations, with remembered timings
+ bar / countdown quota left (with the next box as a ghost), time left
+ next_steps(cmds) `→ kdev up start the box`
+ select / confirm / ask prompts; list rows are numbered and a digit picks
spinner(text) "doing something…", always present tense and lowercase
Voice
@@ -35,8 +45,9 @@
A command, when shown, is the literal thing to type. Durations like 9h or
2m04s, clock times like 14:05. One result card per command.
-It degrades: without a TTY, boards become plain lines and prompts never
-appear; NO_COLOR is honoured; a terminal that cannot draw the glyphs gets ASCII.
+It degrades: without a TTY, boards become plain lines, cards plain facts and
+prompts never appear; NO_COLOR is honoured; a terminal that cannot draw the
+glyphs gets ASCII, and its typographic characters ASCII stand-ins.
"""
from __future__ import annotations
@@ -46,7 +57,7 @@
import sys
import time
from collections.abc import Callable, Iterable, Iterator, Sequence
-from contextlib import contextmanager
+from contextlib import contextmanager, suppress
from contextvars import ContextVar
from dataclasses import dataclass
from itertools import groupby
@@ -97,6 +108,8 @@
"f": "default", # Wordmark follows the foreground of light and dark terminals.
}
_logo_printed: ContextVar[bool | None] = ContextVar("kdev_logo_printed", default=None)
+#: Set while the home menu runs a pick: it printed the header already.
+_header_given: ContextVar[bool] = ContextVar("kdev_header_given", default=False)
THEME = Theme(
{
@@ -119,9 +132,31 @@ def _no_colour() -> bool:
return bool(os.environ.get("NO_COLOR")) or os.environ.get("TERM") == "dumb"
-console = Console(theme=THEME, no_color=_no_colour(), soft_wrap=False)
+def _pipe_width(stream) -> int | None:
+ """Piped output is read by programs, not people: never wrap or crop it."""
+ try:
+ return None if stream.isatty() else 4096
+ except (AttributeError, ValueError):
+ return None
+
+
+class _Console(Console):
+ def on_broken_pipe(self) -> None:
+ """`kdev logs | head`: the reader left early, which is not a failure.
+ rich's own handler exits 1; scripts would read that as kdev failing."""
+ self.quiet = True
+ with suppress(OSError):
+ os.dup2(os.open(os.devnull, os.O_WRONLY), sys.stdout.fileno())
+ raise SystemExit(0)
+
+
+console = _Console(
+ theme=THEME, no_color=_no_colour(), soft_wrap=False, width=_pipe_width(sys.stdout)
+)
#: Failures go to stderr, so `kdev status --json | jq` never sees them.
-errconsole = Console(theme=THEME, no_color=_no_colour(), soft_wrap=False, stderr=True)
+errconsole = _Console(
+ theme=THEME, no_color=_no_colour(), soft_wrap=False, stderr=True, width=_pipe_width(sys.stderr)
+)
_GLYPHS = {
"ok": ("✓", "+"),
@@ -132,7 +167,12 @@ def _no_colour() -> bool:
"bullet": ("·", "."),
"full": ("█", "#"),
"empty": ("░", "."),
+ "ghost": ("▒", "="),
"prompt": ("›", ">"),
+ "done": ("◇", "o"),
+ "rail": ("│", "|"),
+ "top": ("┌", "+"),
+ "bottom": ("└", "+"),
"arrow": ("→", "->"),
}
_SPINNERS = ("⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏", "|/-\\")
@@ -145,6 +185,46 @@ def _ascii_only() -> bool:
)
+_ASCII = str.maketrans(
+ {
+ "·": ".",
+ "—": "-",
+ "–": "-",
+ "…": "...",
+ "×": "x",
+ "→": "->",
+ "›": ">",
+ "‹": "<",
+ "‘": "'",
+ "’": "'",
+ "“": '"',
+ "”": '"',
+ }
+)
+
+
+class _AsciiStream:
+ """stdout for a terminal that cannot draw `×` or `·`: the few typographic
+ characters in kdev's own sentences become their ASCII stand-ins, and
+ anything else unencodable a `?`, never a UnicodeEncodeError."""
+
+ def __init__(self, stream):
+ self._stream = stream
+ with suppress(AttributeError, ValueError):
+ stream.reconfigure(errors="replace")
+
+ def write(self, text: str) -> int:
+ return self._stream.write(text.translate(_ASCII))
+
+ def __getattr__(self, name: str):
+ return getattr(self._stream, name)
+
+
+if _ascii_only() and not isinstance(sys.stdout, _AsciiStream):
+ sys.stdout = _AsciiStream(sys.stdout) # type: ignore[assignment]
+ sys.stderr = _AsciiStream(sys.stderr) # type: ignore[assignment]
+
+
def g(name: str) -> str:
"""The right glyph for this terminal."""
return _GLYPHS[name][1 if _ascii_only() else 0]
@@ -201,8 +281,22 @@ def interactive() -> bool:
GUTTER = 2
+def _styled(msg: str | Text, base: str = "", target: Console | None = None) -> Text:
+ """`backticked` spans in kdev's sentences are commands: draw them as one.
+ Where nothing is drawn (piped), the backticks stay: they are the quotes."""
+ if isinstance(msg, Text):
+ return msg
+ if target is not None and not target.is_terminal:
+ return Text(msg, style=base)
+ text = Text(style=base)
+ for i, part in enumerate(msg.split("`")):
+ if part:
+ text.append(part, style="kdev.cmd" if i % 2 else "")
+ return text
+
+
def _line(target: Console, glyph: str, style: str, msg: str | Text) -> None:
- line = Text.assemble((f"{glyph:<{GUTTER}}", style), msg)
+ line = Text.assemble((f"{glyph:<{GUTTER}}", style), _styled(msg, target=target))
target.print(Padding(line, (0, 0, 0, GUTTER), expand=False) if target.is_terminal else line)
@@ -222,19 +316,33 @@ def err(msg: str | Text, hint_text: str = "") -> None:
_line(errconsole, g("err"), "kdev.err", msg)
if hint_text:
errconsole.print(
- Padding(Text(hint_text, style="kdev.muted"), (0, 0, 0, GUTTER), expand=False)
+ Padding(_styled(hint_text, "kdev.muted", errconsole), (0, 0, 0, GUTTER), expand=False)
)
def hint(msg: str | Text) -> None:
+ """Advice for a person. Piped, it goes to stderr: stdout is the data
+ (`kdev account | cut -f2`), and advice in it would be read as rows."""
+ target = console if console.is_terminal else errconsole
# Padding rather than a literal prefix: a long hint that wraps keeps its
# indent on the continuation lines instead of falling back to column 0.
- text = msg if isinstance(msg, Text) else Text(msg, style="kdev.muted")
- console.print(Padding(text, (0, 0, 0, GUTTER), expand=False))
+ target.print(Padding(_styled(msg, "kdev.muted", target), (0, 0, 0, GUTTER), expand=False))
def blank() -> None:
- console.print()
+ """Breathing room for a person; piped data gets none (no empty rows)."""
+ if console.is_terminal:
+ console.print()
+
+
+@contextmanager
+def header_given() -> Iterator[None]:
+ """Run a command whose header the caller already printed."""
+ token = _header_given.set(True)
+ try:
+ yield
+ finally:
+ _header_given.reset(token)
@contextmanager
@@ -276,72 +384,127 @@ def _logo(*, compact: bool = False, metadata: Text | None = None) -> Text:
return art
+#: Commands whose header is the full logo: the front door and first run.
+#: Everything else gets one line, so the answer is on screen, not the brand.
+_LOGO_TITLES = ("", "overview", "setup")
+
+
+def _can_draw_logo() -> bool:
+ return bool(
+ console.is_terminal
+ and console.color_system
+ and not console.no_color
+ and not _no_colour()
+ and not _ascii_only()
+ and console.width >= _ICON_WIDTH + GUTTER
+ and _logo_printed.get() is not True
+ )
+
+
+def _mark() -> Text:
+ """The one-line brand mark: the logo's own prompt and cursor, then the name."""
+ if not console.is_terminal or _ascii_only() or console.no_color or _no_colour():
+ return Text("kdev", style="kdev.head")
+ return Text.assemble(("›_", "kdev.accent"), " ", ("kdev", "bold"))
+
+
def header(
title: str = "",
context: Sequence[tuple[str, str]] = (),
*,
terminal_only: bool = False,
+ logo: bool | None = None,
) -> None:
- """Responsive branding and context; terminal-only headers preserve piped data."""
+ """Branding and context. The front door gets the logo; every other command
+ one line -- `›_ kdev status` with its context on the right -- so a
+ command's answer is never pushed below the fold by its own banner.
+ Terminal-only headers keep piped data clean."""
from . import __version__
if terminal_only and not console.is_terminal:
return
- metadata = Text.assemble(
- (title or "overview", "bold"),
- (f" {g('bullet')} v{__version__}", "kdev.muted"),
- )
- full_logo = console.width >= max(_LOGO_WIDTH, _WORDMARK_LEFT + metadata.cell_len) + GUTTER
- show_logo = (
- console.is_terminal
- and console.color_system
- and not console.no_color
- and not _no_colour()
- and not _ascii_only()
- and console.width >= _ICON_WIDTH + GUTTER
- and _logo_printed.get() is not True
- )
- if show_logo:
+ if _header_given.get():
+ return
+ width = min(console.width, MAX_WIDTH)
+ want_logo = title in _LOGO_TITLES if logo is None else logo
+ if want_logo and _can_draw_logo():
+ metadata = Text.assemble(
+ (title or "overview", "bold"),
+ (f" {g('bullet')} v{__version__}", "kdev.muted"),
+ )
+ full = console.width >= max(_LOGO_WIDTH, _WORDMARK_LEFT + metadata.cell_len) + GUTTER
console.print(
- Padding(
- _logo(compact=not full_logo, metadata=metadata), (0, 0, 0, GUTTER), expand=False
- )
+ Padding(_logo(compact=not full, metadata=metadata), (0, 0, 0, GUTTER), expand=False)
)
+ if not full:
+ line = Text.assemble(_mark(), " ", metadata)
+ if line.cell_len + GUTTER > console.width:
+ line = Text.assemble(_mark(), " ", (title or "overview", "bold"))
+ console.print()
+ console.print(Padding(line, (0, 0, 0, GUTTER), expand=False))
if _logo_printed.get() is not None:
_logo_printed.set(True)
- if not (show_logo and full_logo):
- if show_logo:
+ if context:
console.print()
- line = Text.assemble(("kdev", "kdev.head"))
- if title:
- line.append(f" {g('bullet')} ", style="kdev.muted")
- line.append(title, style="bold")
+ console.print(_context_line(context, width))
+ console.print()
+ return
+
+ line = _mark()
+ if title:
+ line.append(f" {g('prompt')} ", style="kdev.muted")
+ line.append(title, style="bold")
+ if not context:
line.append(f" v{__version__}", style="kdev.muted")
- if console.is_terminal:
- console.print(Padding(line, (0, 0, 0, GUTTER), expand=False))
- else:
- console.print(line)
- if context:
- if show_logo and full_logo:
- console.print()
- row = Text(" ")
- for i, (label, value) in enumerate(context):
- if i:
- row.append(f" {g('bullet')} ", style="kdev.muted")
- row.append(f"{label} ", style="kdev.muted")
- row.append(value)
- if row.cell_len <= console.width:
- console.print(row)
- else:
- # A hostname broken across two lines is unreadable and un-copyable.
- width = max(len(label) for label, _ in context)
- for label, value in context:
- console.print(
- Text.assemble((" ", ""), (f"{label:>{width}} ", "kdev.muted"), value)
- )
+ if not console.is_terminal:
+ console.print(line)
+ if context:
+ console.print(_context_line(context, width))
+ console.print()
+ return
+ right = _context_text(context)
+ room = width - GUTTER * 2 - line.cell_len - 4
+ if context and right.cell_len <= room:
+ row = Table.grid(expand=True, padding=0)
+ row.add_column(no_wrap=True)
+ row.add_column(justify="right", no_wrap=True)
+ row.add_row(line, right)
+ console.print(Padding(row, (0, GUTTER)), width=width)
+ else:
+ console.print(Padding(line, (0, 0, 0, GUTTER), expand=False))
+ if context:
+ console.print(_context_line(context, width))
+ console.print(
+ Padding(Rule(style="kdev.border", characters="-" if _ascii_only() else "─"), (0, GUTTER)),
+ width=width,
+ )
console.print()
+def _context_text(context: Sequence[tuple[str, str]]) -> Text:
+ row = Text()
+ for i, (label, value) in enumerate(context):
+ if i:
+ row.append(f" {g('bullet')} ", style="kdev.muted")
+ row.append(f"{label} ", style="kdev.muted")
+ row.append(value)
+ return row
+
+
+def _context_line(context: Sequence[tuple[str, str]], width: int) -> RenderableType:
+ row = _context_text(context)
+ if row.cell_len + GUTTER <= width:
+ return Padding(row, (0, 0, 0, GUTTER), expand=False)
+ # A hostname broken across two lines is unreadable and un-copyable.
+ label_w = max(len(label) for label, _ in context)
+ return Group(
+ *(
+ Text.assemble((" " * GUTTER, ""), (f"{label:>{label_w}} ", "kdev.muted"), value)
+ for label, value in context
+ )
+ )
+
+
def _facts_body(rows: Sequence[tuple[str, object]], width: int) -> RenderableType:
"""Keep long paths, hostnames and commands visible, even in a small window."""
if width < 44:
@@ -361,59 +524,117 @@ def _facts_body(rows: Sequence[tuple[str, object]], width: int) -> RenderableTyp
return grid
-def facts(rows: Sequence[tuple[str, object]], indent: int = GUTTER) -> Padding:
- """Aligned facts, stacked when labels would crowd out their values."""
+def facts(rows: Sequence[tuple[str, object]], indent: int = GUTTER) -> RenderableType:
+ """Aligned facts, stacked when labels would crowd out their values.
+ Piped: `label value` lines, with no padding after the value."""
+ if not console.is_terminal:
+ label_w = max((len(label) for label, _ in rows), default=0)
+ return Group(
+ *(
+ Text.assemble(
+ " " * indent + f"{label:>{label_w}} ",
+ value if isinstance(value, Text) else str(value),
+ no_wrap=True,
+ )
+ for label, value in rows
+ if label or value
+ )
+ )
width = min(console.width, MAX_WIDTH) - indent
return Padding(_facts_body(rows, width), (0, 0, 0, indent), expand=False)
def section(title: str, detail: str = "") -> None:
- """A quiet heading for a group of related information in a terminal."""
+ """A quiet one-line heading: `Accounts ──────── 3 connected`."""
if not console.is_terminal:
return
- text = Text(title, style="bold")
+ width = min(console.width, MAX_WIDTH) - GUTTER * 2
+ rule = "-" if _ascii_only() else "─"
+ head = Text(title, style="bold")
+ tail = Text(detail, style="kdev.muted") if detail else Text()
+ fill = width - head.cell_len - tail.cell_len - (4 if detail else 2)
+ line = Text.assemble(head, " ", (rule * max(fill, 2), "kdev.border"))
if detail:
- text.append(f" {g('bullet')} {detail}", style="kdev.muted")
- console.print(Padding(text, (0, 0, 0, GUTTER), expand=False))
- console.print(
- Padding(
- Rule(style="kdev.border", characters="-" if _ascii_only() else "─"),
- (0, GUTTER),
- ),
- width=min(console.width, MAX_WIDTH),
- )
+ line.append(" ")
+ line.append(tail)
+ console.print(Padding(line, (0, 0, 0, GUTTER), expand=False), no_wrap=True, overflow="crop")
def card(title: str | Text, rows: Sequence[tuple[str, object]], tone: str = "muted") -> None:
- """A bounded result card, with space for facts and copyable commands."""
+ """A bounded result card, with space for facts and copyable commands.
+ Piped, it is a title line and plain facts: boxes are for people."""
terminal = console.is_terminal
- width = min(console.width, MAX_WIDTH)
+ if not terminal:
+ console.print(Text(title) if isinstance(title, str) else title)
+ console.print(facts(rows))
+ return
+ # On the gutter, the width of the header's rule: one left edge for all.
+ width = min(console.width, MAX_WIDTH) - GUTTER * 2
padding = (1, 2 if width >= 48 else 1)
body = _facts_body(rows, width - padding[1] * 2 - 2)
border = {"ok": "kdev.ok", "warn": "kdev.warn", "err": "kdev.err"}.get(
tone, "kdev.border" if terminal else MUTED
)
- console.print(
- Panel(
- body,
- title=Text(title, style="bold default") if isinstance(title, str) else title,
- title_align="left",
- border_style=border,
- box=box.ASCII if _ascii_only() else box.ROUNDED,
- padding=padding,
- width=width if terminal else None,
- expand=terminal,
- )
+ panel = Panel(
+ body,
+ title=Text(title, style="bold default") if isinstance(title, str) else title,
+ title_align="left",
+ border_style=border,
+ box=box.ASCII if _ascii_only() else box.ROUNDED,
+ padding=padding,
+ width=width,
+ expand=True,
)
+ console.print(Padding(panel, (0, 0, 0, GUTTER), expand=False))
class _ResponsiveTable(Table):
- """Retain Table's public API while giving narrow terminals labeled records."""
+ """Retain Table's public API while giving narrow terminals labeled records.
+
+ In a terminal the table sits on the same two-space gutter as every other
+ line, header rule included."""
+
+ _in_gutter = False
def __rich_console__(self, target: Console, options: ConsoleOptions) -> RenderResult:
width = min(options.max_width, MAX_WIDTH)
- threshold = 80 if len(self.columns) >= 5 else 64
- if target.is_terminal and width < threshold:
+ if not target.is_terminal:
+ # Piped: tab-separated words, one record a line, so `cut -f2`
+ # and `awk -F'\t'` work and nothing wraps at 80 columns.
+ # An unlabeled first column is the active-account marker: as data
+ # it is a yes/no column called `active`.
+ marker = bool(self.columns) and not str(self.columns[0].header).strip()
+ header = [str(c.header).lower() or "-" for c in self.columns]
+ if marker:
+ header[0] = "active"
+ cells = [list(c.cells) for c in self.columns]
+ lines = ["\t".join(header)]
+ for index in range(self.row_count):
+ row = []
+ for n, column in enumerate(cells):
+ cell = column[index]
+ plain = (cell.plain if isinstance(cell, Text) else str(cell)).strip()
+ if marker and n == 0:
+ plain = "yes" if plain else "no"
+ row.append("-" if plain in ("", "—") else plain)
+ lines.append("\t".join(row))
+ # Raw segments: rich expands tabs inside Text, which would turn
+ # the columns back into spaces.
+ from rich.segment import Segment
+
+ for line in lines:
+ yield Segment(line)
+ yield Segment.line()
+ return
+ if target.is_terminal and not self._in_gutter and width >= self._narrow_at():
+ self._in_gutter = True
+ try:
+ padded = Padding(self, (0, GUTTER)) # pyright: ignore[reportArgumentType]
+ yield from target.render(padded, options.update(width=width))
+ finally:
+ self._in_gutter = False
+ return
+ if target.is_terminal and width < self._narrow_at():
if self.title:
yield Padding(Text(str(self.title), style="bold"), (0, 0, 1, GUTTER))
cells = [list(column.cells) for column in self.columns]
@@ -439,6 +660,9 @@ def __rich_console__(self, target: Console, options: ConsoleOptions) -> RenderRe
return
yield from super().__rich_console__(target, options)
+ def _narrow_at(self) -> int:
+ return 80 if len(self.columns) >= 5 else 64
+
def table(
columns: Sequence[tuple[str, str]], rows: Iterable[Sequence[object]], title: str = ""
@@ -451,14 +675,14 @@ def table(
box=(box.ASCII if _ascii_only() else box.SIMPLE_HEAD) if terminal else None,
border_style="kdev.border",
expand=False,
- padding=(0, 1) if terminal else (0, 2),
+ padding=(0, 2, 0, 0) if terminal else (0, 2),
header_style="kdev.table_head" if terminal else "kdev.muted",
title=title or None,
title_style="bold",
title_justify="left",
- pad_edge=True,
+ pad_edge=not terminal,
show_edge=not terminal,
- width=min(console.width, MAX_WIDTH) if terminal else None,
+ width=None,
)
for name, justify in columns:
t.add_column(name.upper(), justify=justify, overflow="fold") # type: ignore[arg-type]
@@ -468,25 +692,33 @@ def table(
def next_steps(steps: Sequence[tuple[str, str]]) -> None:
- """What to run next. Commands in accent, aligned, one per line."""
+ """What to run next: `→ kdev up start the box`, commands in accent."""
if not steps:
return
if console.is_terminal:
- section("Next")
- rows = [
- (Text(command, style="kdev.cmd"), Text(what, style="kdev.muted"))
- for command, what in steps
- ]
+ console.print()
+ arrow = g("arrow")
if console.width < 64:
- for command, what in rows:
- console.print(Padding(Group(command, what), (0, GUTTER, 1, GUTTER)))
- else:
- grid = Table.grid(padding=(0, 3))
- grid.add_column(overflow="fold")
- grid.add_column(overflow="fold")
- for command, what in rows:
- grid.add_row(command, what)
- console.print(Padding(grid, (0, GUTTER)), width=min(console.width, MAX_WIDTH))
+ for command, what in steps:
+ console.print(
+ Padding(
+ Group(
+ Text.assemble((arrow + " ", "kdev.muted"), (command, "kdev.cmd")),
+ Text(" " + " " * len(arrow) + what, style="kdev.muted"),
+ ),
+ (0, GUTTER),
+ )
+ )
+ return
+ grid = Table.grid(padding=(0, 3))
+ grid.add_column(no_wrap=True)
+ grid.add_column(overflow="fold")
+ for command, what in steps:
+ grid.add_row(
+ Text.assemble((arrow + " ", "kdev.muted"), (command, "kdev.cmd")),
+ Text(what, style="kdev.muted"),
+ )
+ console.print(Padding(grid, (0, GUTTER)), width=min(console.width, MAX_WIDTH))
return
width = max(len(cmd) for cmd, _ in steps)
for cmd, what in steps:
@@ -510,19 +742,39 @@ class _Status(Protocol):
def update(self, *args: Any, **kwargs: Any) -> None: ...
+class _SpinnerLine:
+ """`⠋ checking… 4s`, on the gutter: the clock appears once a wait is
+ long enough to wonder about, so slow never looks like stuck."""
+
+ def __init__(self, text: str | Text):
+ from rich.spinner import Spinner
+
+ self.text: str | Text = text
+ self.started = time.monotonic()
+ self._spinner = Spinner("line" if _ascii_only() else "dots", style="kdev.accent")
+
+ def update(self, text: str | Text | None = None, **_: Any) -> None:
+ if text is not None:
+ self.text = text
+
+ def __rich__(self) -> RenderableType:
+ label = self.text if isinstance(self.text, Text) else Text(self.text, style="kdev.muted")
+ waited = time.monotonic() - self.started
+ if waited >= 3:
+ label = Text.assemble(label, (f" {_fmt_elapsed(waited)}", "kdev.muted"))
+ self._spinner.text = label
+ return Padding(self._spinner, (0, 0, 0, GUTTER))
+
+
@contextmanager
def spinner(text: str) -> Iterator[_Status]:
"""A transient spinner. Present tense, lowercase, ends in an ellipsis."""
if not interactive():
yield _NullStatus()
return
- with console.status(
- Text(text, style="kdev.muted"),
- spinner="line" if _ascii_only() else "dots",
- spinner_style="kdev.accent",
- refresh_per_second=8,
- ) as status:
- yield status
+ line = _SpinnerLine(text)
+ with Live(line, console=console, refresh_per_second=10, transient=True):
+ yield line
class _NullStatus:
@@ -535,16 +787,93 @@ def emit_json(data: object) -> None:
sys.stdout.write(json.dumps(data, indent=2, sort_keys=True, default=str) + "\n")
-def bar(fraction: float, width: int = 14) -> Text:
- """A quota bar. Colour is the signal; the number beside it is the detail."""
+def _headroom_colour(fraction: float) -> str:
+ return "green" if fraction > 0.5 else "yellow" if fraction > 0.15 else "red"
+
+
+def bar(fraction: float, width: int = 14, ghost: float = 0.0) -> Text:
+ """A quota bar. Colour is the signal; the number beside it is the detail.
+
+ `ghost` is the share the next box would use, drawn as a lighter run at
+ the end of the filled part: what is left now, and what will be after."""
fraction = max(0.0, min(1.0, fraction))
+ ghost = max(0.0, min(fraction, ghost))
filled = round(fraction * width)
- colour = "green" if fraction > 0.5 else "yellow" if fraction > 0.15 else "red"
- t = Text(g("full") * filled, style=colour)
+ after = round((fraction - ghost) * width) if ghost else filled
+ after = min(after, filled - 1) if ghost and filled else after
+ colour = _headroom_colour(fraction)
+ t = Text(g("full") * max(after, 0), style=colour)
+ if filled > after:
+ t.append(g("ghost") * (filled - after), style=f"{colour} dim")
+ t.append(g("empty") * (width - filled), style=MUTED)
+ t.style = colour
+ return t
+
+
+def countdown(started: float, ends: float, width: int = 16, now: float | None = None) -> Text:
+ """Time left on a box: a draining bar, then `5h12m left · ends 21:40`.
+ Yellow under 30 minutes, red under 10 -- the moment to save work."""
+ now = time.time() if now is None else now
+ total = max(ends - started, 1.0)
+ left = max(ends - now, 0.0)
+ if not console.is_terminal:
+ return Text(f"{fmt_left(left)} left, ends {time.strftime('%H:%M', time.localtime(ends))}")
+ colour = "red" if left < 600 else "yellow" if left < 1800 else "green"
+ filled = round(left / total * width)
+ t = Text()
+ t.append(g("full") * filled, style=colour)
t.append(g("empty") * (width - filled), style=MUTED)
+ t.append(f" {fmt_left(left)} left", style="bold")
+ t.append(f" {g('bullet')} ends {time.strftime('%H:%M', time.localtime(ends))}", "kdev.muted")
return t
+def fmt_when(at: float, now: float | None = None) -> str:
+ """A moment in the coming week, as a person says it: `today 05:30`,
+ `tomorrow 05:30`, `Sat 05:30 (in 4d)`."""
+ now = time.time() if now is None else now
+ local, today = time.localtime(at), time.localtime(now)
+ clock = time.strftime("%H:%M", local)
+ days = (
+ time.mktime((*local[:3], 0, 0, 0, 0, 0, -1)) - time.mktime((*today[:3], 0, 0, 0, 0, 0, -1))
+ ) / 86400
+ days = round(days)
+ if days <= 0:
+ return f"today {clock}"
+ if days == 1:
+ return f"tomorrow {clock}"
+ return f"{time.strftime('%a', local)} {clock} (in {days}d)"
+
+
+def epoch(value: object) -> float:
+ """Seconds since the epoch from a number or an ISO-8601 string; 0 if neither."""
+ if isinstance(value, bool):
+ return 0.0
+ if isinstance(value, (int, float)):
+ return float(value)
+ if isinstance(value, str) and value:
+ from datetime import UTC, datetime
+
+ try:
+ instant = datetime.fromisoformat(value.replace("Z", "+00:00"))
+ except ValueError:
+ return 0.0
+ if instant.tzinfo is None:
+ instant = instant.replace(tzinfo=UTC)
+ return instant.timestamp()
+ return 0.0
+
+
+def fmt_left(seconds: float) -> str:
+ """5h12m, 42m, 30s: what a person reads at a glance."""
+ seconds = int(max(seconds, 0))
+ if seconds >= 3600:
+ return f"{seconds // 3600}h{seconds % 3600 // 60:02d}m"
+ if seconds >= 60:
+ return f"{seconds // 60}m"
+ return f"{seconds}s"
+
+
def _fmt_elapsed(seconds: float) -> str:
seconds = int(seconds)
if seconds < 60:
@@ -569,6 +898,8 @@ class ProfileRow:
tpu_total: int = 0
active: bool = False
error: str = ""
+ #: When Kaggle refills this account's weekly quota (epoch seconds), if known.
+ resets: float = 0.0
@property
def fraction(self) -> float:
@@ -605,9 +936,12 @@ def accounts_table(rows: Sequence[ProfileRow]) -> Table:
Text("-" if _ascii_only() else "—"),
)
else:
- meter = bar(r.fraction, width=10 if console.is_terminal else 14)
if console.is_terminal:
- meter.append(f" {r.fraction:.0%}", style="kdev.muted")
+ meter = Text.assemble(
+ bar(r.fraction, width=10), (f" {r.fraction:.0%}", "kdev.muted")
+ )
+ else:
+ meter = Text(f"{r.fraction:.0%}")
t.add_row(
marker,
name,
@@ -619,7 +953,9 @@ def accounts_table(rows: Sequence[ProfileRow]) -> Table:
return t
-def pick_profile(rows: Sequence[ProfileRow], need_hours: float) -> str:
+def pick_profile(
+ rows: Sequence[ProfileRow], need_hours: float, question: str = "Which account should run it?"
+) -> str:
"""Account picker with quota inline, most quota first."""
usable = [r for r in rows if not r.error]
if not usable:
@@ -634,10 +970,12 @@ def pick_profile(rows: Sequence[ProfileRow], need_hours: float) -> str:
for r in usable:
meter = "".join(g("full") if j < round(r.fraction * 10) else g("empty") for j in range(10))
note = "" if r.gpu_left >= need_hours * 3600 else " short for this session"
+ if r.active:
+ note += " (active now)"
choices.append(
Choice(title=f"{r.name:<{width}} {meter} {r.hours:>6} left{note}", value=r.name)
)
- return select("Which account should run it?", choices)
+ return select(question, choices)
# --- prompts ------------------------------------------------------------------
@@ -647,17 +985,102 @@ def _prompt_style() -> questionary.Style:
return _MONO_STYLE if _no_colour() or console.no_color else STYLE
+def _QMARK() -> str:
+ """The prompt mark, on the gutter like every other line."""
+ return " " * GUTTER + g("prompt")
+
+
+def _answered(question: str, answer: str) -> None:
+ """One answered line, the same for every kind of prompt and however it
+ was answered: ` › Question Answer`."""
+ console.print(
+ Padding(
+ Text.assemble(
+ (g("prompt") + " ", "kdev.accent"),
+ (question, "bold"),
+ " ",
+ (answer, "kdev.accent"),
+ ),
+ (0, 0, 0, GUTTER),
+ expand=False,
+ ),
+ highlight=False,
+ )
+
+
+def _answer(question: Any) -> Any:
+ """Ask, and turn Ctrl-C into None quietly: questionary's own `ask` prints
+ "Cancelled by user", and kdev already says "cancelled" once."""
+ unsafe = getattr(question, "unsafe_ask", None)
+ if unsafe is None:
+ return question.ask()
+ try:
+ return unsafe()
+ except KeyboardInterrupt:
+ return None
+
+
def select(question: str, choices: list[Choice]) -> str:
- answer = questionary.select(
+ """A list to pick from: arrows or j/k to move, enter to pick, or a digit
+ to pick that row at once -- the numbers are shown beside each choice."""
+ numbered: list[Choice] = []
+ picks: dict[str, object] = {}
+ labels: dict[int, str] = {}
+ for choice in choices:
+ if isinstance(choice, Choice) and not choice.disabled and len(picks) < 9:
+ key = str(len(picks) + 1)
+ picks[key] = choice.value
+ title = choice.title if isinstance(choice.title, str) else str(choice.title)
+ labels[id(choice.value)] = title.split(" ")[0].strip()
+ numbered.append(
+ Choice(
+ title=f"{key} {title}",
+ value=choice.value,
+ disabled=choice.disabled,
+ checked=choice.checked,
+ description=getattr(choice, "description", None),
+ )
+ )
+ else:
+ numbered.append(choice)
+ question_ = questionary.select(
question,
- choices=choices,
+ choices=numbered,
style=_prompt_style(),
- qmark=g("prompt"),
- pointer=g("prompt"),
- instruction="(up/down to move, enter to select)",
- ).ask()
+ qmark=_QMARK(),
+ pointer=" " + g("prompt"),
+ instruction=" ",
+ use_jk_keys=True,
+ use_indicator=False,
+ erase_when_done=True,
+ )
+ app = getattr(question_, "application", None)
+ if app is not None and picks:
+ from prompt_toolkit.key_binding import KeyBindings, merge_key_bindings
+
+ extra = KeyBindings()
+ for key, value in picks.items():
+
+ @extra.add(key, eager=True)
+ def _pick(event, value=value) -> None:
+ event.app.exit(result=value)
+
+ app.key_bindings = merge_key_bindings([app.key_bindings, extra]) # type: ignore[list-item]
+ answer = _answer(question_)
if answer is None:
raise Cancelled()
+ # One answered line, the same however it was picked: `› Question Answer`.
+ label = labels.get(id(answer)) or next(
+ (
+ lb
+ for v, lb in (
+ (c.value, labels.get(id(c.value))) for c in choices if isinstance(c, Choice)
+ )
+ if v == answer and lb
+ ),
+ str(answer),
+ )
+ _answered(question, label)
return answer
@@ -674,26 +1097,34 @@ def confirm(question: str, default: bool = True) -> bool:
wherever saying yes would lose something."""
if not interactive():
return default
- answer = questionary.confirm(
- question, default=default, style=_prompt_style(), qmark=g("prompt")
- ).ask()
+ answer = _answer(
+ questionary.confirm(
+ question,
+ default=default,
+ style=_prompt_style(),
+ qmark=_QMARK(),
+ erase_when_done=True,
+ )
+ )
if answer is None:
raise Cancelled()
+ _answered(question, "yes" if answer else "no")
return answer
def ask(question: str, default: str = "", secret: bool = False) -> str:
# Called separately: `password` takes no default, and the two signatures
# are honest on their own terms rather than joined through **kwargs.
+ common = {"style": _prompt_style(), "qmark": _QMARK(), "erase_when_done": True}
if secret:
- answer = questionary.password(question, style=_prompt_style(), qmark=g("prompt")).ask()
+ answer = _answer(questionary.password(question, **common))
else:
- answer = questionary.text(
- question, default=default, style=_prompt_style(), qmark=g("prompt")
- ).ask()
+ answer = _answer(questionary.text(question, default=default, **common))
if answer is None:
raise Cancelled()
- return answer.strip()
+ answer = answer.strip()
+ _answered(question, "•" * min(len(answer), 8) if secret else answer or "—")
+ return answer
GPU_CHOICES = [
@@ -705,7 +1136,8 @@ def ask(question: str, default: str = "", secret: bool = False) -> str:
def gpu_label(key: str) -> str:
- return {k: label for k, label, _ in GPU_CHOICES}.get(key, key)
+ label = {k: label for k, label, _ in GPU_CHOICES}.get(key, key)
+ return label.replace("×", "x") if _ascii_only() else label
def pick_gpu() -> str:
@@ -715,19 +1147,28 @@ def pick_gpu() -> str:
)
-def pick_hours(gpu: str, quota_hours: float) -> float:
+def pick_hours(gpu: str, quota_hours: float | None = None) -> float:
+ """Session length, each choice with what it leaves of this week's quota
+ (`quota_hours`, when known; a CPU box uses none)."""
cap = 9.0 if gpu == "tpu" else 12.0
options = [h for h in (2.0, 4.0, 9.0, 12.0) if h <= cap]
choices = []
for h in options:
- note = f" more than the {quota_hours:.1f}h left" if h > quota_hours else ""
- choices.append(Choice(title=f"{h:g} hours{note}", value=h))
+ note = ""
+ if quota_hours is not None and gpu != "none":
+ if h > quota_hours:
+ note = f" more than the {quota_hours:.1f}h left; Kaggle stops it early"
+ else:
+ note = f" leaves {quota_hours - h:.1f}h this week"
+ choices.append(Choice(title=f"{h:g} hours".ljust(8) + note, value=h))
choices.append(Choice(title="Custom…", value=0.0))
answer = float(select(f"Session length? (Kaggle stops it at {cap:g}h)", choices))
if answer == 0.0:
- raw = questionary.text(
- "Hours:", default="6", style=_prompt_style(), qmark=g("prompt")
- ).ask()
+ raw = _answer(
+ questionary.text(
+ "Hours", default="6", style=_prompt_style(), qmark=_QMARK(), erase_when_done=True
+ )
+ )
if raw is None:
raise Cancelled()
from .errors import KdevError
@@ -759,6 +1200,46 @@ def elapsed(self) -> float:
return (self.ended or time.monotonic()) - self.started
+def _timings_path() -> Path:
+ from .config import CONFIG_DIR
+
+ return CONFIG_DIR / "timings.json"
+
+
+def _load_timings() -> dict[str, float]:
+ try:
+ data = json.loads(_timings_path().read_text())
+ except (OSError, ValueError):
+ return {}
+ return {k: float(v) for k, v in data.items() if isinstance(v, (int, float))}
+
+
+def _save_timings(measured: dict[str, float], previous: dict[str, float]) -> None:
+ """Remember each step's time, smoothed, so a slow step reads as slow."""
+ if not measured:
+ return
+ merged = dict(previous)
+ for key, seconds in measured.items():
+ old = previous.get(key)
+ merged[key] = round(seconds if old is None else old * 0.6 + seconds * 0.4, 1)
+ try:
+ path = _timings_path()
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps(merged, indent=1, sort_keys=True))
+ except OSError:
+ pass
+
+
+class _LiveBoard:
+ """What Live draws: the board as it is at this refresh, not as it was."""
+
+ def __init__(self, board: Stages):
+ self.board = board
+
+ def __rich__(self) -> RenderableType:
+ return self.board._render(final=self.board._final)
+
+
class Stages:
"""Live board, modelled on Docker Compose's: each step keeps its own line
and clock, so a slow step is visibly slow rather than indistinguishable
@@ -773,6 +1254,12 @@ def __init__(self, stages: Sequence[tuple[str, str]], head: str = ""):
self.tick = 0
self.started = time.monotonic()
self._live: Live | None = None
+ #: How long each step took last time on this machine, by key.
+ self.usual: dict[str, float] = _load_timings()
+ self._final = False
+ #: Whether this run's clocks are worth remembering. A joined session's
+ #: log replays in milliseconds and would make "usually" meaningless.
+ self.record = True
@property
def done(self) -> list[str]:
@@ -780,8 +1267,10 @@ def done(self) -> list[str]:
def __enter__(self) -> Stages:
if interactive():
+ # The board renders itself on every refresh, so its clocks and
+ # spinner keep moving through a long, silent step.
self._live = Live(
- self._render(), console=console, refresh_per_second=8, transient=False
+ _LiveBoard(self), console=console, refresh_per_second=8, transient=False
)
self._live.__enter__()
elif self.head:
@@ -789,16 +1278,29 @@ def __enter__(self) -> Stages:
return self
def __exit__(self, *exc) -> None:
+ if exc[0] is not None:
+ # Interrupted or failed mid-step: that step did not finish, and
+ # the last frame must not draw it as done.
+ stage = self._by_key.get(self.current or "")
+ if stage and not stage.ended:
+ stage.failed = True
+ stage.ended = time.monotonic()
if self._live:
- self._live.update(self._render(final=True))
+ self._final = True
+ self._live.update(_LiveBoard(self))
self._live.__exit__(*exc)
+ complete = len(self.done) == len(self._stages)
+ if self._live and exc[0] is None and self.record and complete:
+ _save_timings(
+ {s.key: s.elapsed for s in self._stages if s.ended and not s.failed}, self.usual
+ )
def _marks(self, stage: _Stage, final: bool) -> tuple[Text, Text]:
running = stage.key == self.current and not stage.ended and not final
if stage.failed:
glyph, style, label_style = g("err"), "kdev.err", "kdev.err"
elif stage.ended or (stage.key == self.current and final):
- glyph, style, label_style = g("ok"), "kdev.ok", ""
+ glyph, style, label_style = g("done"), "kdev.ok", ""
elif running:
frames = _spinner_frames()
glyph, style, label_style = frames[self.tick % len(frames)], "kdev.accent", "bold"
@@ -806,55 +1308,72 @@ def _marks(self, stage: _Stage, final: bool) -> tuple[Text, Text]:
glyph, style, label_style = g("pending"), "kdev.muted", "kdev.muted"
return Text(glyph, style=style), Text(stage.label, style=label_style)
- def _render(self, final: bool = False) -> Group | Panel:
+ def _render(self, final: bool = False) -> Group:
+ """A rail, after clack: one row per step, each with its own clock, the
+ running one with how long it usually takes on this machine."""
self.tick += 1
- lines = []
- if self.head and not console.is_terminal:
- head = Text(" " + self.head, style="kdev.muted")
- head.append(f" {_fmt_elapsed(time.monotonic() - self.started)}", style="kdev.muted")
- lines.append(head)
- board = Table.grid(padding=(0, 1), expand=console.is_terminal)
- board.add_column(width=2)
- board.add_column(width=1)
- board.add_column(ratio=1, overflow="fold")
- board.add_column(justify="right")
+ rail = Text(g("rail"), style="kdev.border")
+ board = Table.grid(padding=(0, 2), expand=False)
+ board.add_column(width=1, no_wrap=True)
+ board.add_column(overflow="fold", min_width=min(36, max(console.width - 24, 10)))
+ board.add_column(justify="right", no_wrap=True, min_width=5)
+ board.add_column(no_wrap=True, style="kdev.muted")
+ failed = next((s for s in self._stages if s.failed), None)
+ lines: list[RenderableType] = []
+ if self.head:
+ lines.append(
+ Padding(
+ Text.assemble((g("top") + " ", "kdev.border"), (self.head, "bold")),
+ (0, 0, 0, GUTTER),
+ )
+ )
+ board.add_row(rail, "", "", "")
for stage in self._stages:
glyph, label = self._marks(stage, final)
- clock = _fmt_elapsed(stage.elapsed) if stage.started else ""
- board.add_row("", glyph, label, Text(clock, style="kdev.muted"))
+ clock = Text(_fmt_elapsed(stage.elapsed) if stage.started else "", "kdev.muted")
+ running = stage.key == self.current and not stage.ended and not final
+ usual = self.usual.get(stage.key)
+ # Only once it is worth knowing, and never for a step that is
+ # usually instant: "usually 0s" would only alarm.
+ note = (
+ f"usually {_fmt_elapsed(usual)}"
+ if running and usual and usual >= 3 and stage.elapsed >= 2
+ else ""
+ )
+ board.add_row(glyph, label, clock, note)
# A failed stage keeps its detail on the final frame: the reason it
# failed is the whole point of the line.
if self.detail and stage.key == self.current and (not final or stage.failed):
- board.add_row("", "", Text(self.detail, style="kdev.muted"), "")
- lines.append(board)
- if console.is_terminal:
- elapsed = _fmt_elapsed(time.monotonic() - self.started)
- completed = len(self.done)
- summary = Text(
- f"{completed}/{len(self._stages)} complete {g('bullet')} {elapsed}",
- style="kdev.muted",
+ board.add_row(rail, Text(self.detail, style="kdev.muted"), "", "")
+ board.add_row(rail, "", "", "")
+ elapsed = _fmt_elapsed(time.monotonic() - self.started)
+ if failed:
+ end = Text.assemble(
+ (g("bottom") + " ", "kdev.err"),
+ (f"stopped at {failed.label.lower()}", "kdev.err"),
+ (f" {g('bullet')} {elapsed}", "kdev.muted"),
)
- content: list[RenderableType] = []
- if self.head:
- content.append(Text(self.head, style="bold"))
- content.append(Text(""))
- content.append(board)
- return Panel(
- Group(*content),
- title=Text("Progress", style="bold default"),
- subtitle=summary,
- title_align="left",
- subtitle_align="right",
- border_style="kdev.border",
- box=box.ASCII if _ascii_only() else box.ROUNDED,
- padding=(1, 1),
- width=min(console.width, MAX_WIDTH),
+ elif final and len(self.done) == len(self._stages):
+ end = Text.assemble(
+ (g("bottom") + " ", "kdev.ok"),
+ ("done", "kdev.ok"),
+ (f" in {elapsed}", "kdev.muted"),
)
+ else:
+ end = Text.assemble(
+ (g("bottom") + " ", "kdev.border"),
+ (
+ f"{len(self.done)}/{len(self._stages)} complete {g('bullet')} {elapsed}",
+ "kdev.muted",
+ ),
+ )
+ lines.append(Padding(board, (0, 0, 0, GUTTER)))
+ lines.append(Padding(end, (0, 0, 0, GUTTER)))
return Group(*lines)
def _refresh(self) -> None:
if self._live:
- self._live.update(self._render())
+ self._live.refresh()
def advance(self, key: str) -> None:
now = time.monotonic()
@@ -897,20 +1416,40 @@ def finish(self) -> None:
if stage and not stage.ended:
stage.ended = time.monotonic()
if self._live:
- self._live.update(self._render(final=True))
+ self._final = True
+ self._live.refresh()
def refresh(self) -> None:
self._refresh()
-def ready_card(alias: str, host: str, hours: float, gpu: str, account: str, note: str = "") -> None:
- """How `up` ends: the facts about the box, and how to get in."""
- ends = time.localtime(time.time() + hours * 3600)
+def ready_card(
+ alias: str,
+ host: str,
+ hours: float,
+ gpu: str,
+ account: str,
+ note: str = "",
+ *,
+ started: float = 0.0,
+ ends: float = 0.0,
+) -> None:
+ """How `up` ends: the facts about the box, and how to get in. `started`
+ and `ends` are the box's own record when known: it stops a little before
+ Kaggle would, so the clock must come from it, not from `hours`."""
+ now = time.time()
+ if ends:
+ hours = max(ends - now, 0) / 3600
rows: list[tuple[str, object]] = [
("host", Text(host, style="bold")),
("account", account),
("accelerator", gpu),
- ("ends", f"{time.strftime('%H:%M', ends)} ({hours:g}h from now)"),
+ (
+ "time",
+ countdown(now, now + hours * 3600, width=12)
+ if console.is_terminal
+ else f"{hours:g}h, ends {time.strftime('%H:%M', time.localtime(now + hours * 3600))}",
+ ),
]
if note:
rows.append(("files", note))
diff --git a/src/kdev/wizard.py b/src/kdev/wizard.py
index 920a57b..fb28e9c 100644
--- a/src/kdev/wizard.py
+++ b/src/kdev/wizard.py
@@ -7,6 +7,7 @@
from __future__ import annotations
+import re
import subprocess
from pathlib import Path
@@ -164,10 +165,16 @@ def ensure_ssh_key(cfg: config.Config) -> None:
ui.ok("ssh key generated ~/.ssh/id_ed25519")
+def _short(version: str) -> str:
+ """`cloudflared version 2026.9.1 (built …)` -> `2026.9.1`."""
+ found = re.search(r"\d{4}\.\d+\.\d+", version)
+ return found.group(0) if found else version
+
+
def ensure_cloudflared() -> None:
found = cloudflared.find()
if found:
- ui.ok(f"cloudflared {cloudflared.version(found)}")
+ ui.ok(f"cloudflared {_short(cloudflared.version(found))}")
return
ui.warn("cloudflared is missing; ssh uses it to reach the box")
if not ui.confirm(
@@ -175,7 +182,7 @@ def ensure_cloudflared() -> None:
):
raise KdevError("kdev needs cloudflared.", "Install it: brew install cloudflared")
path = ui.download("cloudflared", cloudflared.install)
- ui.ok(f"cloudflared {cloudflared.version(path)}")
+ ui.ok(f"cloudflared {_short(cloudflared.version(path))}")
def sign_in(cfg: config.Config, name: str = "") -> str:
@@ -243,8 +250,7 @@ def run() -> config.Config:
config.save(cfg)
ui.blank()
- ui.ok("ready", f"settings saved to {config.CONFIG_PATH}")
- ui.blank()
+ ui.ok(ui.Text("ready", style="kdev.ok"), f"settings saved to {config.CONFIG_PATH}")
ui.next_steps(
[("kdev up", "start the box"), ("kdev account add", "add another account to share quota")]
)
diff --git a/tests/conftest.py b/tests/conftest.py
new file mode 100644
index 0000000..6444440
--- /dev/null
+++ b/tests/conftest.py
@@ -0,0 +1,86 @@
+"""Every test runs against a throwaway home, with no network.
+
+The paths kdev writes to are computed at import, so pointing $HOME elsewhere
+is not enough on its own: the module attributes are moved too. Without this a
+test that forgets one fixture writes to the developer's real ~/.ssh/config or
+~/.config/kdev, or downloads the real cloudflared.
+"""
+
+from __future__ import annotations
+
+import urllib.parse
+import urllib.request
+from pathlib import Path
+
+import httpx
+import pytest
+from rich.style import Style
+
+#: What `cloudflared.find` answers in tests. Never executed.
+FAKE_CLOUDFLARED = Path("/opt/kdev-test/bin/cloudflared")
+
+
+#: Loopback stays open: some tests serve a canned response from a local socket.
+LOCAL = frozenset({"127.0.0.1", "localhost", "::1"})
+
+
+def _no_network(url: str):
+ # pytest.fail raises a BaseException: kdev's own `except Exception` and
+ # retry loops cannot swallow it and report an "offline" result instead.
+ pytest.fail(f"a test reached the real network ({url}); monkeypatch the call instead")
+
+
+def _guard(real, url_of):
+ def guarded(*args, **kwargs):
+ url = url_of(*args, **kwargs)
+ if urllib.parse.urlsplit(url).hostname not in LOCAL:
+ _no_network(url)
+ return real(*args, **kwargs)
+
+ return guarded
+
+
+def _request_url(_self, request, *args, **kwargs) -> str:
+ return str(request.url)
+
+
+def _urlopen_url(url, *args, **kwargs) -> str:
+ return url.full_url if isinstance(url, urllib.request.Request) else str(url)
+
+
+@pytest.fixture(autouse=True)
+def _isolated(tmp_path_factory, monkeypatch):
+ from kdev import auth, cloudflared, config, sshcfg
+
+ home = tmp_path_factory.mktemp("home")
+ config_dir = home / ".config" / "kdev"
+ monkeypatch.setenv("HOME", str(home))
+ monkeypatch.setenv("KDEV_CONFIG_DIR", str(config_dir))
+ monkeypatch.setenv("KDEV_DATA_DIR", str(home / ".local" / "share" / "kdev"))
+ monkeypatch.delenv("XDG_DATA_HOME", raising=False)
+ for var in ("HTTPS_PROXY", "HTTP_PROXY", "ALL_PROXY", "https_proxy", "http_proxy"):
+ monkeypatch.delenv(var, raising=False)
+
+ monkeypatch.setattr(config, "CONFIG_DIR", config_dir)
+ monkeypatch.setattr(config, "CONFIG_PATH", config_dir / "config.json")
+ monkeypatch.setattr(auth, "KAGGLE_CREDENTIALS", home / ".kaggle" / "credentials.json")
+ monkeypatch.setattr(sshcfg, "SSH_CONFIG", home / ".ssh" / "config")
+ monkeypatch.setattr(cloudflared, "find", lambda: FAKE_CLOUDFLARED)
+ monkeypatch.setattr(auth, "_cache", {})
+ # Rich memoises parsed styles, and each Style keeps the ANSI codes of the
+ # first colour system it rendered for. A test that renders through a
+ # 16-colour console (Typer forces one under GITHUB_ACTIONS) would otherwise
+ # leave truecolor tests seeing `36` where `#00b8d4` should be.
+ Style.parse.cache_clear()
+ Style._add.cache_clear()
+
+ monkeypatch.setattr(httpx.Client, "send", _guard(httpx.Client.send, _request_url))
+ monkeypatch.setattr(httpx.AsyncClient, "send", _guard(httpx.AsyncClient.send, _request_url))
+ monkeypatch.setattr(urllib.request, "urlopen", _guard(urllib.request.urlopen, _urlopen_url))
+ try:
+ import requests
+ except ImportError: # pragma: no cover - kagglesdk brings it
+ pass
+ else:
+ monkeypatch.setattr(requests.Session, "send", _guard(requests.Session.send, _request_url))
+ return home
diff --git a/tests/test_account.py b/tests/test_account.py
new file mode 100644
index 0000000..f0be81e
--- /dev/null
+++ b/tests/test_account.py
@@ -0,0 +1,56 @@
+import json
+
+import pytest
+
+from kdev import cloudflared, config, quota, ui
+from kdev.errors import KdevError
+
+
+def _accounts(monkeypatch, rows):
+ cfg = config.Config()
+ for r in rows:
+ cfg.add(r.name, config.Profile(r.username))
+ config.save(cfg)
+ monkeypatch.setattr(quota, "rows", lambda cfg: rows)
+
+
+def _kdev(monkeypatch, *argv) -> int:
+ from kdev import cli
+
+ monkeypatch.setattr("sys.argv", ["kdev", *argv])
+ try:
+ cli.main()
+ except SystemExit as e:
+ return e.code if isinstance(e.code, int) else int(e.code is not None)
+ return 0
+
+
+def test_account_json_has_every_total(monkeypatch, capsys):
+ _accounts(
+ monkeypatch,
+ [ui.ProfileRow("alice", "alice", 3600, 108000, tpu_left=600, tpu_total=72000)],
+ )
+ assert _kdev(monkeypatch, "account", "--json") == 0
+ [row] = json.loads(capsys.readouterr().out)
+ assert row["tpu_seconds_total"] == 72000 and row["tpu_seconds_left"] == 600
+ assert row["gpu_seconds_total"] == 108000
+
+
+def test_offline_accounts_are_not_told_to_sign_in_again(monkeypatch, capsys):
+ _accounts(
+ monkeypatch,
+ [
+ ui.ProfileRow("alice", "alice", 0, 0, error=quota.OFFLINE),
+ ui.ProfileRow("bob", "bob", 0, 0, error="signed out: kdev account add bob"),
+ ],
+ )
+ assert _kdev(monkeypatch, "account") == 0
+ out = capsys.readouterr().out
+ assert "kdev account add bob" in out and "kdev account add alice" not in out
+ assert "unexpected" not in out
+
+
+def test_missing_cloudflared_points_at_a_command_that_exists(monkeypatch):
+ monkeypatch.setattr(cloudflared, "find", lambda: None)
+ with pytest.raises(KdevError, match="kdev doctor --fix"):
+ cloudflared.ensure(auto=False)
diff --git a/tests/test_api.py b/tests/test_api.py
index 72e9eb1..74fbdd0 100644
--- a/tests/test_api.py
+++ b/tests/test_api.py
@@ -183,3 +183,93 @@ def denied(creds, method, payload=None, service=api.KERNELS, attempts=3):
monkeypatch.setattr(api, "call", denied)
with pytest.raises(api.KaggleError):
api.session_status(api.Creds("u"), "a/b") # other failures still surface
+
+
+def test_a_prefix_listing_stops_paging_once_past_the_prefix(monkeypatch):
+ pages = {
+ None: {
+ "files": [{"fileName": n, "url": "u"} for n in (".kdev/a", ".kdev/state.json", "b")],
+ "nextPageToken": "p2",
+ },
+ "p2": {"files": [{"fileName": "c", "url": "u"}]},
+ }
+ seen = []
+
+ def call(creds, method, payload, **kw):
+ seen.append(payload.get("pageToken"))
+ return pages[payload.get("pageToken")]
+
+ monkeypatch.setattr(api, "call", call)
+ names = [f["name"] for f in api.session_output(api.Creds("u"), "a/b", "v1", prefix=".kdev/")]
+ assert seen == [None] and ".kdev/state.json" in names
+
+
+def test_a_prefix_listing_keeps_paging_when_the_prefix_may_continue(monkeypatch):
+ pages = {
+ None: {"files": [{"fileName": ".kdev/a", "url": "u"}], "nextPageToken": "p2"},
+ "p2": {
+ "files": [{"fileName": ".kdev/state.json", "url": "u"}, {"fileName": "b", "url": "u"}]
+ },
+ }
+ monkeypatch.setattr(api, "call", lambda c, m, p, **kw: pages[p.get("pageToken")])
+ names = [f["name"] for f in api.session_output(api.Creds("u"), "a/b", "v1", prefix=".kdev/")]
+ assert ".kdev/state.json" in names
+
+
+def test_an_unsorted_page_is_never_trusted_to_end_the_prefix(monkeypatch):
+ pages = {
+ None: {
+ "files": [{"fileName": n, "url": "u"} for n in ("z", ".kdev/a")],
+ "nextPageToken": "p2",
+ },
+ "p2": {"files": [{"fileName": ".kdev/state.json", "url": "u"}]},
+ }
+ monkeypatch.setattr(api, "call", lambda c, m, p, **kw: pages[p.get("pageToken")])
+ names = [f["name"] for f in api.session_output(api.Creds("u"), "a/b", "v1", prefix=".kdev/")]
+ assert ".kdev/state.json" in names
+
+
+def test_rate_limiting_is_waited_out_with_retry_after(monkeypatch):
+ import httpx
+
+ answers = iter(
+ [httpx.Response(429, headers={"retry-after": "2"})] * 3
+ + [httpx.Response(200, json={"ok": 1})]
+ )
+ slept = []
+ monkeypatch.setattr(api.httpx, "post", lambda *a, **kw: next(answers))
+ monkeypatch.setattr(api.time, "sleep", slept.append)
+ assert api.call(api.Creds("u"), "GetKernel", {}) == {"ok": 1}
+ assert slept == [2.0, 2.0, 2.0]
+
+
+def test_a_call_that_must_not_repeat_is_never_retried_even_when_limited(monkeypatch):
+ import httpx
+
+ calls = []
+ monkeypatch.setattr(api.httpx, "post", lambda *a, **kw: calls.append(1) or httpx.Response(429))
+ with pytest.raises(api.KaggleError):
+ api.call(api.Creds("u"), "SaveKernel", {}, attempts=1)
+ assert len(calls) == 1
+
+
+def test_a_prefix_read_falls_back_to_full_pages_when_the_prefix_sorts_late(monkeypatch):
+ """A `.git/` at the root sorts before `.kdev/`: fifty names at a time
+ would take dozens of calls, so the read restarts at the full page size."""
+ names = [f".git/objects/{i:04d}" for i in range(900)] + [".kdev/state.json", "z.py"]
+ calls = []
+
+ def call(creds, method, payload, **kw):
+ size, start = payload["pageSize"], int(payload.get("pageToken") or 0)
+ calls.append(size)
+ page = names[start : start + size]
+ nxt = start + size
+ return {
+ "files": [{"fileName": n, "url": "u"} for n in page],
+ "nextPageToken": str(nxt) if nxt < len(names) else "",
+ }
+
+ monkeypatch.setattr(api, "call", call)
+ got = [f["name"] for f in api.session_output(api.Creds("u"), "a/b", "v1", prefix=".kdev/")]
+ assert ".kdev/state.json" in got
+ assert calls == [api.PREFIX_PAGE, api.OUTPUT_PAGE, api.OUTPUT_PAGE]
diff --git a/tests/test_api_errors.py b/tests/test_api_errors.py
new file mode 100644
index 0000000..a72571f
--- /dev/null
+++ b/tests/test_api_errors.py
@@ -0,0 +1,55 @@
+"""Kaggle answering with something other than what the API promises."""
+
+from contextlib import contextmanager
+
+import httpx
+import pytest
+
+from kdev import api
+
+
+@pytest.mark.parametrize(
+ "body",
+ [b'["a", "list"]', b'"a string"', b"42", b"null", b"bad gateway", b""],
+)
+def test_an_error_body_of_any_shape_becomes_a_kaggle_error(monkeypatch, body):
+ """A JSON list used to raise AttributeError: "unexpected error", not a message."""
+ monkeypatch.setattr(
+ api.httpx,
+ "post",
+ lambda url, **kw: httpx.Response(
+ 403, content=body, headers={"content-type": "application/json"}
+ ),
+ )
+ with pytest.raises(api.KaggleError) as e:
+ api.call(api.Creds("u", "t"), "GetKernel", {})
+ assert e.value.status == 403 and "HTTP 403" in str(e.value)
+
+
+def test_kaggles_own_error_message_is_kept(monkeypatch):
+ monkeypatch.setattr(
+ api.httpx,
+ "post",
+ lambda url, **kw: httpx.Response(403, json={"error": {"message": "Permission denied"}}),
+ )
+ with pytest.raises(api.KaggleError, match="Permission denied"):
+ api.call(api.Creds("u", "t"), "GetKernel", {})
+
+
+def _logs(monkeypatch, content_type: str, body: bytes) -> list[str]:
+ @contextmanager
+ def stream(method, url, **kw):
+ yield httpx.Response(200, headers={"content-type": content_type}, content=body)
+
+ monkeypatch.setattr(api.httpx, "stream", stream)
+ return list(api.stream_logs(api.Creds("u"), "alice/box"))
+
+
+def test_a_persisted_log_that_is_not_json_is_a_kaggle_error(monkeypatch):
+ """json.loads used to raise JSONDecodeError straight out of `kdev logs`."""
+ with pytest.raises(api.KaggleError, match="not JSON"):
+ _logs(monkeypatch, "application/json", b"gateway timeout")
+
+
+def test_a_persisted_log_that_is_one_object_is_still_shown(monkeypatch):
+ assert _logs(monkeypatch, "application/json", b'{"data": "only line"}') == ["only line"]
diff --git a/tests/test_auth.py b/tests/test_auth.py
index 86a3fb6..49c3e90 100644
--- a/tests/test_auth.py
+++ b/tests/test_auth.py
@@ -1,8 +1,12 @@
import json
+import os
+import threading
+from datetime import UTC, datetime, timedelta
+import httpx
import pytest
-from kdev import config
+from kdev import api, auth, config
def test_an_account_authenticates_with_a_bearer_token_only():
@@ -62,3 +66,242 @@ def test_profile_without_login_yields_no_token(tmp_path, monkeypatch):
monkeypatch.setattr(auth, "creds_dir", lambda: tmp_path / "creds")
cfg = config.Config(profiles={"me": config.Profile("u")}, active="me")
assert cfg.profile().creds.token == ""
+
+
+# --- access tokens --------------------------------------------------------------
+
+
+def _stored(name: str, *, expires_in: timedelta | None, token: str = "old-token") -> dict:
+ data = {
+ "refresh_token": f"rt-{name}",
+ "access_token": token,
+ "access_token_expiration": (
+ (datetime.now(UTC) + expires_in).isoformat() if expires_in else ""
+ ),
+ "username": name,
+ "scopes": ["resources.admin:*"],
+ }
+ path = auth.creds_path(name)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps(data))
+ path.chmod(0o600)
+ return data
+
+
+def _mint_counter(monkeypatch, expires_in: int = 43200) -> list[dict]:
+ """Answer GenerateAccessToken; record each request made."""
+ minted: list[dict] = []
+
+ def call(creds, method, payload=None, service=api.KERNELS, attempts=3):
+ assert (service, method) == (auth.ACCOUNTS, "GenerateAccessToken")
+ assert not creds.token, "minting must not send another account's token"
+ minted.append(payload or {})
+ return {"token": f"new-token-{len(minted)}", "expiresIn": expires_in}
+
+ monkeypatch.setattr(api, "call", call)
+ return minted
+
+
+def test_a_token_is_minted_once_per_process_and_kept(monkeypatch):
+ """`kdev up` reads an account's creds ~20 times; each read used to mint."""
+ _stored("alice", expires_in=timedelta(hours=-1))
+ minted = _mint_counter(monkeypatch)
+
+ tokens = {auth.access_token("alice") for _ in range(20)}
+ assert tokens == {"new-token-1"} and len(minted) == 1
+ assert minted[0]["refreshToken"] == "rt-alice"
+ assert minted[0]["expirationDuration"] == "43200s"
+
+
+def test_a_refreshed_token_is_saved_to_the_profile_for_the_next_process(monkeypatch):
+ _stored("alice", expires_in=None)
+ _mint_counter(monkeypatch)
+ auth.access_token("alice")
+
+ path = auth.creds_path("alice")
+ saved = json.loads(path.read_text())
+ assert saved["access_token"] == "new-token-1"
+ assert saved["refresh_token"] == "rt-alice" and saved["scopes"] == ["resources.admin:*"]
+ left = datetime.fromisoformat(saved["access_token_expiration"]) - datetime.now(UTC)
+ assert timedelta(hours=11) < left <= timedelta(hours=12)
+ assert oct(path.stat().st_mode)[-3:] == "600"
+
+ # A new process (an empty cache) uses the saved token without a round trip.
+ monkeypatch.setattr(auth, "_cache", {})
+ monkeypatch.setattr(api, "call", lambda *a, **k: pytest.fail("must not mint again"))
+ assert auth.access_token("alice") == "new-token-1"
+
+
+def test_a_stored_token_with_time_left_is_used_as_is(monkeypatch):
+ _stored("alice", expires_in=timedelta(hours=5), token="still-good")
+ monkeypatch.setattr(api, "call", lambda *a, **k: pytest.fail("must not mint"))
+ assert auth.access_token("alice") == "still-good"
+
+
+@pytest.mark.parametrize(
+ "left",
+ [timedelta(minutes=59), timedelta(minutes=29), timedelta(minutes=1), timedelta(hours=-3)],
+)
+def test_a_token_near_or_past_expiry_is_refreshed(monkeypatch, left):
+ """kagglesdk's own check was backwards: it only refreshed 30 minutes
+ *after* expiry, so a token could lapse in the middle of a session start.
+ kdev refreshes while an hour or less is left."""
+ _stored("alice", expires_in=left)
+ minted = _mint_counter(monkeypatch)
+ assert auth.access_token("alice") == "new-token-1" and len(minted) == 1
+
+
+def test_a_cached_token_is_refreshed_once_it_nears_expiry(monkeypatch):
+ _stored("alice", expires_in=None)
+ # Granted for less than the refresh margin: stale as soon as it is cached.
+ minted = _mint_counter(monkeypatch, expires_in=int(auth.REFRESH_MARGIN.total_seconds()) - 60)
+ assert auth.access_token("alice") == "new-token-1"
+ assert auth.access_token("alice") == "new-token-2"
+ assert len(minted) == 2
+
+
+def test_minting_never_touches_the_official_cli_login(monkeypatch):
+ """kagglesdk's refresh saved every new token to ~/.kaggle/credentials.json,
+ which is the user's own `kaggle` CLI login and possibly another account."""
+ from pathlib import Path
+
+ shared = auth.KAGGLE_CREDENTIALS
+ shared.parent.mkdir(parents=True, exist_ok=True)
+ shared.write_text(json.dumps({"refresh_token": "mine", "username": "me"}))
+ before = (shared.read_text(), shared.stat().st_mtime_ns)
+
+ _stored("alice", expires_in=None)
+ _stored("bob", expires_in=None)
+ _mint_counter(monkeypatch)
+ auth.access_token("alice")
+ auth.access_token("bob")
+
+ assert (shared.read_text(), shared.stat().st_mtime_ns) == before
+ assert sorted(p.name for p in (Path.home() / ".kaggle").iterdir()) == ["credentials.json"]
+
+
+def test_concurrent_reads_mint_once_and_leave_valid_json(monkeypatch):
+ """quota.rows reads every account at once, and threads share accounts."""
+ _stored("alice", expires_in=None)
+ gate = threading.Event()
+ minted = []
+
+ def slow_call(creds, method, payload=None, service=api.KERNELS, attempts=3):
+ minted.append(1)
+ gate.wait(2)
+ return {"token": "new", "expiresIn": 43200}
+
+ monkeypatch.setattr(api, "call", slow_call)
+ results = []
+ threads = [
+ threading.Thread(target=lambda: results.append(auth.access_token("alice")))
+ for _ in range(8)
+ ]
+ for t in threads:
+ t.start()
+ gate.set()
+ for t in threads:
+ t.join(5)
+ assert results == ["new"] * 8 and len(minted) == 1
+ assert json.loads(auth.creds_path("alice").read_text())["access_token"] == "new"
+ assert [p.name for p in auth.creds_dir().iterdir()] == ["alice.json"], "no temp files left"
+
+
+def test_a_failed_write_leaves_the_old_file_whole(monkeypatch):
+ """Written through a temp file: a crash mid-write must not sign anyone out."""
+ original = _stored("alice", expires_in=None)
+ _mint_counter(monkeypatch)
+
+ def crash(src, dst):
+ raise OSError("disk full")
+
+ monkeypatch.setattr(os, "replace", crash)
+ monkeypatch.setattr(
+ type(auth.creds_path("alice")), "replace", lambda self, dst: crash(self, dst)
+ )
+ # The token still works for this process; the file is untouched.
+ assert auth.access_token("alice") == "new-token-1"
+ assert json.loads(auth.creds_path("alice").read_text()) == original
+ assert [p.name for p in auth.creds_dir().iterdir()] == ["alice.json"]
+
+
+def test_a_relogin_is_picked_up_without_restarting(monkeypatch):
+ """`kdev account add ` replaces the file; the cached token is someone's old one."""
+ _stored("alice", expires_in=timedelta(hours=5), token="before")
+ assert auth.access_token("alice") == "before"
+ _stored("alice", expires_in=timedelta(hours=5), token="after-relogin")
+ assert auth.access_token("alice") == "after-relogin"
+
+
+def test_being_offline_is_not_being_signed_out(monkeypatch):
+ """Offline used to crash with "unexpected error" (requests' ConnectionError
+ escaped), or read as signed out. It must be its own, clear AuthError."""
+ _stored("alice", expires_in=None)
+
+ def offline(url, **kw):
+ raise httpx.ConnectError("[Errno 61] Connection refused")
+
+ monkeypatch.setattr(api.httpx, "post", offline)
+ monkeypatch.setattr(api.time, "sleep", lambda s: None)
+ with pytest.raises(auth.AuthUnavailable, match="Could not reach Kaggle"):
+ auth.access_token("alice")
+
+ cfg = config.Config()
+ cfg.add("alice", config.Profile("alice"))
+ with pytest.raises(auth.AuthError):
+ _ = cfg.profile("alice").creds
+
+
+@pytest.mark.parametrize("status", [500, 503])
+def test_kaggle_failing_to_mint_is_unavailable_not_signed_out(monkeypatch, status):
+ _stored("alice", expires_in=None)
+ monkeypatch.setattr(api.httpx, "post", lambda url, **kw: httpx.Response(status, text="down"))
+ monkeypatch.setattr(api.time, "sleep", lambda s: None)
+ with pytest.raises(auth.AuthUnavailable):
+ auth.access_token("alice")
+
+
+def test_a_rejected_refresh_token_reads_as_signed_out(monkeypatch):
+ _stored("alice", expires_in=None)
+ monkeypatch.setattr(api.httpx, "post", lambda url, **kw: httpx.Response(401, text="no"))
+ with pytest.raises(auth.AuthError, match="kdev account add alice") as e:
+ auth.access_token("alice")
+ assert not isinstance(e.value, auth.AuthUnavailable)
+
+ cfg = config.Config()
+ cfg.add("alice", config.Profile("alice"))
+ assert cfg.profile("alice").creds.token == "", "the call it is for then says: not signed in"
+
+
+def test_the_quota_table_shows_an_offline_account_as_a_row_not_a_crash(monkeypatch):
+ from kdev import quota
+
+ cfg = config.Config()
+ for name in ("alice", "bob", "carol"):
+ cfg.add(name, config.Profile(name))
+ _stored(name, expires_in=None)
+
+ def offline(url, **kw):
+ raise httpx.ConnectError("Connection refused")
+
+ monkeypatch.setattr(api.httpx, "post", offline)
+ monkeypatch.setattr(api.time, "sleep", lambda s: None)
+ rows = quota.rows(cfg)
+ assert [r.name for r in rows] == ["alice", "bob", "carol"]
+ assert {r.error for r in rows} == {quota.OFFLINE}
+
+
+def test_the_quota_table_survives_any_transport_error(monkeypatch):
+ from kdev import quota
+
+ cfg = config.Config()
+ cfg.add("alice", config.Profile("alice"))
+ monkeypatch.setattr(auth, "signed_in", lambda name: True)
+ monkeypatch.setattr(auth, "access_token", lambda name: "t")
+
+ def boom(creds):
+ raise httpx.RemoteProtocolError("peer closed connection")
+
+ monkeypatch.setattr(api, "quota", boom)
+ [row] = quota.rows(cfg)
+ assert "peer closed" in row.error
diff --git a/tests/test_bootstrap.py b/tests/test_bootstrap.py
index ddd55d7..af45f1f 100644
--- a/tests/test_bootstrap.py
+++ b/tests/test_bootstrap.py
@@ -401,3 +401,23 @@ def test_quick_tunnel_render_has_no_hostname_and_scrapes_the_log():
ast.parse(src)
assert "wait_for_quick_tunnel_host" in src
assert "trycloudflare.com" in src
+
+
+def test_ssh_sessions_get_the_notebooks_path_despite_pam_env(monkeypatch, tmp_path):
+ """pam_env resets PATH from /etc/environment after ~/.ssh/environment, so
+ the notebook's PATH (CUDA, /opt/bin) must be written there too."""
+ src = bootstrap.render(ssh_public_key="k", tunnel_hostname="", hold_seconds=60)
+ body = src[src.index("def _pam_path(path):") : src.index("def add_env(")]
+ etc = tmp_path / "environment"
+ etc.write_text('PATH="/usr/bin:/bin"\nLANG=C.UTF-8\n')
+ real_path = pathlib.Path
+
+ def fake_path(p, *rest):
+ return etc if str(p) == "/etc/environment" else real_path(p, *rest)
+
+ scope = {"pathlib": type("P", (), {"Path": staticmethod(fake_path)})}
+ exec(body, scope)
+ scope["_pam_path"]("/opt/bin:/usr/local/cuda/bin:/usr/bin")
+ assert etc.read_text() == 'LANG=C.UTF-8\nPATH="/opt/bin:/usr/local/cuda/bin:/usr/bin"\n'
+ scope["_pam_path"]('bad"quote') # never writes a value it cannot quote
+ assert "bad" not in etc.read_text()
diff --git a/tests/test_cli.py b/tests/test_cli.py
index 291b00c..d118a5e 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -14,7 +14,7 @@
import pytest
from rich.text import Text
-from kdev import api, auth, cli, config, persistence, session, sshcfg, ui
+from kdev import api, auth, cli, config, menu, persistence, session, sshcfg, ui
class FakeKaggle:
@@ -70,7 +70,7 @@ def install(self, monkeypatch):
)
mp(api, "kernel_id", lambda c, s: 42)
mp(api, "kernel_source", lambda c, s: self.source)
- mp(api, "session_output", lambda c, s, v="": list(self.outputs.get(v, [])))
+ mp(api, "session_output", lambda c, s, v="", **kw: list(self.outputs.get(v, [])))
mp(
api,
"quota",
@@ -265,11 +265,17 @@ def colour_terminal(monkeypatch):
("workspace", "files"),
],
)
-def test_commands_show_the_logo_once(home, kaggle, capsys, colour_terminal, argv):
+def test_commands_show_one_header(home, kaggle, capsys, colour_terminal, argv):
+ """The front door shows the logo once; every other command one brand line."""
configured()
code, out, err = kdev(capsys, *argv)
assert code == 0, err
- assert Text.from_ansi(out).plain.count(ui._logo().plain.splitlines()[0].strip()) == 1
+ text = Text.from_ansi(out).plain
+ logos = text.count(ui._logo().plain.splitlines()[0].strip())
+ if argv:
+ assert logos == 0 and text.count("›_ kdev") == 1
+ else:
+ assert logos == 1
@pytest.mark.parametrize(
@@ -303,12 +309,17 @@ def test_menu_dispatch_does_not_repeat_the_logo(home, kaggle, capsys, colour_ter
configured()
kaggle.status = "RUNNING"
monkeypatch.setattr(ui, "interactive", lambda: True)
- monkeypatch.setattr(ui, "choose", lambda *args, **kwargs: "status")
+ from kdev.commands import home as home_cmd
+
+ monkeypatch.setattr(home_cmd, "_rows", lambda: 40) # tall enough for the logo
+ picks = iter([menu.Item("s", "Status", ("status",)), None])
+ monkeypatch.setattr(menu.Menu, "run", lambda self: next(picks))
code, out, err = kdev(capsys)
assert code == 0, err
text = Text.from_ansi(out).plain
assert text.count(ui._logo().plain.splitlines()[0].strip()) == 1
- assert "kdev · status" in text
+ assert text.count("kdev › status") == 1, "the pick is the header, printed once"
+ assert "stopped" in text or "running" in text
@pytest.mark.parametrize("remote_args", [(), ("-T", "printf hello")])
@@ -334,7 +345,7 @@ def run(argv, **kwargs):
if remote_args:
assert out == "remote output\n"
else:
- assert Text.from_ansi(out).plain.count(ui._logo().plain.splitlines()[0].strip()) == 1
+ assert Text.from_ansi(out).plain.count("›_ kdev › ssh") == 1
@pytest.mark.parametrize("argv", [("config",), ("status",), ("account",), ("workspace", "files")])
@@ -357,10 +368,11 @@ def test_nothing_configured_says_how_to_start(home, capsys):
def test_the_overview_shows_the_box_and_every_account(home, kaggle, capsys):
configured()
- code, out, _ = kdev(capsys)
+ code, out, err = kdev(capsys)
assert code == 0
assert "stopped" in out and "alice" in out and "bob" in out
- assert "kdev up" in out # the next step, when not in a terminal
+ assert "kdev up" in err # the next step: advice, so on stderr when piped
+ assert "kdev up" not in out
@pytest.mark.skipif(not hasattr(time, "tzset"), reason="changing the process timezone needs tzset")
@@ -487,8 +499,10 @@ def test_history_json_is_machine_readable(home, kaggle, capsys):
def test_account_lists_quota(home, kaggle, capsys):
configured()
- code, out, _ = kdev(capsys, "account")
- assert code == 0 and "29.0h" in out and "58.0h of GPU left across 2" in out
+ code, out, err = kdev(capsys, "account")
+ assert code == 0 and "29.0h" in out and "58.0h of GPU left across 2" in err
+ rows = [line.split("\t") for line in out.strip().splitlines()]
+ assert rows[0][:2] == ["active", "account"] and [r[1] for r in rows[1:]] == ["alice", "bob"]
def test_account_json_is_machine_readable(home, kaggle, capsys):
@@ -910,7 +924,7 @@ def test_home_finds_winner_hidden_by_cancelled_latest(home, kaggle, capsys):
kaggle.statuses["v4"] = "RUNNING"
code, out, err = kdev(capsys)
assert code == 0, err
- assert "running" in out and "kdev down" in out
+ assert "running" in out and "kdev down" in err
def test_status_reports_hidden_winner_save_as_stopping(home, kaggle, capsys):
@@ -1236,7 +1250,7 @@ def test_a_command_picked_from_the_menu_keeps_its_exit_status(home, kaggle, caps
kaggle.status = "RUNNING"
monkeypatch.setattr(session, "reachable", lambda alias, timeout=10: True)
monkeypatch.setattr(ui, "interactive", lambda: True)
- monkeypatch.setattr(ui, "choose", lambda q, options: "ssh")
+ monkeypatch.setattr(menu.Menu, "run", lambda self: menu.Item("2", "Open a shell", ("ssh",)))
monkeypatch.setattr("subprocess.run", lambda *a, **k: type("R", (), {"returncode": 5})())
sshcfg.write("kaggle", "box.example.com")
assert kdev(capsys)[0] == 5
diff --git a/tests/test_concurrent_start.py b/tests/test_concurrent_start.py
index e65c816..6631a15 100644
--- a/tests/test_concurrent_start.py
+++ b/tests/test_concurrent_start.py
@@ -38,7 +38,7 @@ def status(creds, slug, version=""):
monkeypatch.setattr(api, "session_status", status)
monkeypatch.setattr(api, "get_kernel", lambda *a: {"currentVersionNumber": 20})
- monkeypatch.setattr(persistence, "version_files", lambda *a: {})
+ monkeypatch.setattr(persistence, "version_meta", lambda *a: {})
return states, reads
@@ -201,7 +201,7 @@ def test_inconsistent_metadata_cannot_make_a_shared_tunnel_ready(runs, monkeypat
def test_unreadable_startup_state_cannot_hide_an_older_winner(runs, monkeypatch):
- monkeypatch.setattr(persistence, "version_files", lambda *a: {persistence.STATE: "bad-url"})
+ monkeypatch.setattr(persistence, "version_meta", lambda *a: {persistence.STATE: "bad-url"})
monkeypatch.setattr(persistence, "_state", lambda f: None)
with pytest.raises(KdevError, match="saved startup state"):
session.current_status(CREDS, SLUG)
@@ -289,7 +289,7 @@ def test_pending_save_is_not_preferred_over_a_live_winner(runs):
def test_unconfirmed_discovery_limit_requires_inspection(runs, monkeypatch):
monkeypatch.setattr(api, "get_kernel", lambda *a: {"currentVersionNumber": 1000})
- monkeypatch.setattr(persistence, "version_files", lambda *a: {"state": "url"})
+ monkeypatch.setattr(persistence, "version_meta", lambda *a: {"state": "url"})
monkeypatch.setattr(persistence, "_state", lambda f: {"startup_confirmed": False})
with pytest.raises(KdevError, match="Too many unconfirmed"):
session.current_status(CREDS, SLUG)
@@ -336,7 +336,7 @@ def test_discovery_pins_latest_status_despite_metadata_logical_race(runs):
def test_confirmed_history_bounds_discovery_without_hiding_winner(runs, monkeypatch):
states, reads = runs
states["v17"] = "RUNNING"
- monkeypatch.setattr(persistence, "version_files", lambda c, s, v: {"state": v})
+ monkeypatch.setattr(persistence, "version_meta", lambda c, s, v: {"state": v})
monkeypatch.setattr(
persistence, "_state", lambda files: {"startup_confirmed": files["state"] == "v16"}
)
@@ -347,7 +347,7 @@ def test_confirmed_history_bounds_discovery_without_hiding_winner(runs, monkeypa
def test_many_unconfirmed_losers_do_not_hide_winner(runs, monkeypatch):
states, _ = runs
states["v1"] = "RUNNING"
- monkeypatch.setattr(persistence, "version_files", lambda *a: {"state": "url"})
+ monkeypatch.setattr(persistence, "version_meta", lambda *a: {"state": "url"})
monkeypatch.setattr(persistence, "_state", lambda f: {"startup_confirmed": False})
assert session.current_status(CREDS, SLUG)[0] == "v1"
diff --git a/tests/test_hermetic.py b/tests/test_hermetic.py
new file mode 100644
index 0000000..311d0d7
--- /dev/null
+++ b/tests/test_hermetic.py
@@ -0,0 +1,28 @@
+"""The test environment itself: nothing may reach the developer's machine."""
+
+from pathlib import Path
+
+import httpx
+import pytest
+
+from kdev import api, auth, cloudflared, config, sshcfg
+
+
+def test_paths_point_into_a_throwaway_home():
+ home = Path.home()
+ assert "pytest" in str(home) or "tmp" in str(home).lower()
+ for path in (config.CONFIG_DIR, sshcfg.SSH_CONFIG, auth.KAGGLE_CREDENTIALS):
+ assert path.is_relative_to(home), path
+
+
+def test_cloudflared_is_never_the_real_one():
+ """`kdev up` tests would otherwise download a 39 MB binary."""
+ found = cloudflared.find()
+ assert found is not None and not found.exists()
+
+
+def test_the_real_network_is_off_limits():
+ with pytest.raises(pytest.fail.Exception, match="real network"):
+ api.call(api.Creds("u", "t"), "GetKernel", {}, attempts=1)
+ with pytest.raises(pytest.fail.Exception, match="real network"):
+ httpx.get("https://example.com")
diff --git a/tests/test_menu.py b/tests/test_menu.py
new file mode 100644
index 0000000..82d9a7b
--- /dev/null
+++ b/tests/test_menu.py
@@ -0,0 +1,93 @@
+"""The home menu: keys pick, disabled items refuse, quitting is not an error."""
+
+import pytest
+from prompt_toolkit.input import create_pipe_input
+from prompt_toolkit.output import DummyOutput
+
+from kdev import menu
+
+
+def _items():
+ return [
+ menu.Item("1", "Start the box", ("up",)),
+ menu.Item("2", "Open a shell", ("ssh",), disabled="no box is running"),
+ menu.Item("3", "Stop the box", ("down",)),
+ menu.Item("s", "Status", ("status",), group="more"),
+ ]
+
+
+def _run(keys: str):
+ with create_pipe_input() as pipe:
+ pipe.send_text(keys)
+ picker = menu.Menu(
+ _items, lambda width: [("", "dashboard")], input=pipe, output=DummyOutput()
+ )
+ return picker.run(), picker
+
+
+@pytest.mark.parametrize(
+ "keys,expected",
+ [
+ ("\r", "up"),
+ ("3", "down"),
+ ("s", "status"),
+ ("S", "status"),
+ ("j\r", "down"),
+ ("jj\r", "status"),
+ ],
+)
+def test_keys_pick_items(keys, expected):
+ item, _ = _run(keys)
+ assert item is not None and item.argv[0] == expected
+
+
+def test_arrows_skip_disabled_items_and_wrap():
+ item, _ = _run("\x1b[B\x1b[B\x1b[B\r") # down x3 from 1: 3, s, back to 1
+ assert item is not None and item.argv == ("up",)
+
+
+def test_a_disabled_item_explains_itself_instead_of_running():
+ item, picker = _run("2q")
+ assert item is None
+ assert "no box is running" in picker.flash
+
+
+@pytest.mark.parametrize("keys", ["q", "\x03", "\x04"])
+def test_quitting_returns_nothing(keys):
+ item, _ = _run(keys)
+ assert item is None
+
+
+def test_each_item_shows_the_command_it_runs():
+ assert menu.Item("1", "x", ("up", "--gpu", "none")).command == "kdev up --gpu none"
+ assert menu.Item("q", "Quit").command == ""
+
+
+def test_live_slots_fill_from_threads_and_record_failures():
+ import threading
+
+ live = menu.Live()
+ done = threading.Event()
+ calls = []
+
+ def changed() -> None:
+ calls.append(1)
+ if len(calls) == 2:
+ done.set()
+
+ live.changed = changed # pyright: ignore[reportAttributeAccessIssue]
+ live.load("ok", lambda: 42)
+ live.load("bad", lambda: 1 / 0)
+ assert done.wait(5)
+ assert live.get("ok") == 42 and live.ready("bad") and live.get("bad") is None
+ assert "division" in live.errors["bad"]
+
+
+@pytest.mark.parametrize("rows,folded", [(14, True), (40, False)])
+def test_a_short_terminal_keeps_every_key_on_one_line(monkeypatch, rows, folded):
+ picker = menu.Menu(_items, lambda width: [])
+ monkeypatch.setattr(picker, "_height", lambda: rows)
+ text = "".join(f[1] for f in picker._render_menu())
+ assert ("more" in text) is folded
+ assert "s" in text
+ assert ("Status" in text) is not folded
diff --git a/tests/test_notebook.py b/tests/test_notebook.py
index e6b8563..3f1cbde 100644
--- a/tests/test_notebook.py
+++ b/tests/test_notebook.py
@@ -1,10 +1,29 @@
+import pytest
+
from kdev import api, bootstrap
-def test_sharing_preserves_existing_collaborators():
- """SetIamPolicy replaces the whole policy; a blind write would drop people."""
- from kdev import api
+def _capture_set_policy(monkeypatch, existing: dict) -> dict:
+ """Serve `existing` as the notebook's policy; return what SetIamPolicy got."""
+ sent: dict = {}
+ monkeypatch.setattr(api, "get_policy", lambda c, k: existing)
+ monkeypatch.setattr(api, "call", lambda c, m, p=None, service=None: sent.update(p or {}) or {})
+ return sent
+
+
+#: A group member as GetIamPolicy really returns it: `group.slug` is absent
+#: and the identity sits on the nested avatar.
+def _real_group_member(slug: str) -> dict:
+ return {
+ "group": {
+ "id": 1983003,
+ "avatar": {"id": 1983003, "slug": slug, "name": "My Team", "memberCount": 3},
+ }
+ }
+
+def test_sharing_preserves_existing_collaborators(monkeypatch):
+ """SetIamPolicy replaces the whole policy; a blind write would drop people."""
existing = {
"owner": {"user": {"userName": "alice"}},
"bindings": [
@@ -12,9 +31,7 @@ def test_sharing_preserves_existing_collaborators():
{"role": api.ROLE_VIEWER, "members": [{"user": {"userName": "carol"}}]},
],
}
- sent = {}
- api.get_policy = lambda c, k: existing
- api.call = lambda c, m, p=None, service=None: sent.update(p or {}) or {}
+ sent = _capture_set_policy(monkeypatch, existing)
api.share_with_group(api.Creds("a", "b"), 1, "my-team")
policy = sent["policy"]
@@ -25,48 +42,48 @@ def test_sharing_preserves_existing_collaborators():
assert {"group": {"slug": "my-team"}} in editors["members"]
-def test_resharing_does_not_duplicate_or_strand_the_group(monkeypatch):
- """Re-running share, or changing role, must leave exactly one binding."""
- import importlib
-
- from kdev import api as fresh
-
- importlib.reload(fresh)
+@pytest.mark.parametrize(
+ "member",
+ [_real_group_member("my-team"), {"group": {"slug": "my-team"}}],
+ ids=["as-kaggle-returns-it", "as-kdev-writes-it"],
+)
+def test_resharing_does_not_duplicate_or_strand_the_group(monkeypatch, member):
+ """Re-running share, or changing role, must leave exactly one binding --
+ whichever shape the existing group member comes back in."""
+ state = {"bindings": [{"role": api.ROLE_VIEWER, "members": [member]}]}
+ sent = _capture_set_policy(monkeypatch, state)
+ api.share_with_group(api.Creds("a", "b"), 1, "my-team")
- state = {"bindings": [{"role": fresh.ROLE_VIEWER, "members": [{"group": {"slug": "my-team"}}]}]}
- sent = {}
- monkeypatch.setattr(fresh, "get_policy", lambda c, k: state)
- monkeypatch.setattr(
- fresh, "call", lambda c, m, p=None, service=None: sent.update(p or {}) or {}
- )
- fresh.share_with_group(fresh.Creds("a", "b"), 1, "my-team")
-
- bindings = sent["policy"]["bindings"]
- hits = [
- (b["role"], m)
- for b in bindings
- for m in b["members"]
- if m.get("group", {}).get("slug") == "my-team"
- ]
+ groups = api.policy_groups(sent["policy"])
+ hits = [g for g in groups if g["slug"] == "my-team"]
assert len(hits) == 1, f"group appears {len(hits)} times"
- assert hits[0][0] == fresh.ROLE_EDITOR, "role must be upgraded, not duplicated"
+ assert hits[0]["role"] == api.ROLE_EDITOR, "role must be upgraded, not duplicated"
-def test_group_role_reads_back_the_binding():
- import importlib
-
- from kdev import api as fresh
+def test_resharing_keeps_other_groups(monkeypatch):
+ state = {
+ "bindings": [
+ {
+ "role": api.ROLE_EDITOR,
+ "members": [_real_group_member("my-team"), _real_group_member("other")],
+ }
+ ]
+ }
+ sent = _capture_set_policy(monkeypatch, state)
+ api.share_with_group(api.Creds("a", "b"), 1, "my-team")
+ slugs = sorted(g["slug"] for g in api.policy_groups(sent["policy"]))
+ assert slugs == ["my-team", "other"]
- importlib.reload(fresh)
+def test_group_role_reads_back_the_binding():
policy = {
"bindings": [
- {"role": fresh.ROLE_VIEWER, "members": [{"user": {"userName": "bob"}}]},
- {"role": fresh.ROLE_EDITOR, "members": [{"group": {"slug": "my-team"}}]},
+ {"role": api.ROLE_VIEWER, "members": [{"user": {"userName": "bob"}}]},
+ {"role": api.ROLE_EDITOR, "members": [_real_group_member("my-team")]},
]
}
- assert fresh.group_role(policy, "my-team") == fresh.ROLE_EDITOR
- assert fresh.group_role(policy, "other-team") == ""
+ assert api.group_role(policy, "my-team") == api.ROLE_EDITOR
+ assert api.group_role(policy, "other-team") == ""
def test_group_identity_is_read_from_the_nested_avatar():
@@ -165,16 +182,63 @@ def test_kdev_owned_and_empty_notebooks_are_safe(monkeypatch, tmp_path):
assert verdict == "safe", f"should be safe: {source!r}"
-def test_missing_notebook_is_safe_to_create(monkeypatch, tmp_path):
+@pytest.mark.parametrize(
+ ("status", "slug"), [(404, "me/new"), (404, "someone/new"), (403, "me/new"), (403, "Me/new")]
+)
+def test_missing_notebook_is_safe_to_create(monkeypatch, tmp_path, status, slug):
+ """Kaggle answers 403 "Permission 'kernels.get' was denied" for a slug that
+ does not exist in your own namespace (measured)."""
+ from kdev import api, safety
+
+ monkeypatch.setattr(safety, "backups_dir", lambda: tmp_path)
+
+ def missing(c, s):
+ raise api.KaggleError("GetKernel: not there", status)
+
+ monkeypatch.setattr(api, "kernel_source", missing)
+ assert safety.check(api.Creds("me"), slug)[0] == "safe"
+
+
+def test_a_403_on_someone_elses_notebook_is_not_missing(monkeypatch, tmp_path):
+ """There it can mean "exists, not shared with you": not proof of absence."""
+ from kdev import api, safety
+
+ monkeypatch.setattr(safety, "backups_dir", lambda: tmp_path)
+
+ def denied(c, s):
+ raise api.KaggleError("GetKernel: Permission 'kernels.get' was denied", 403)
+
+ monkeypatch.setattr(api, "kernel_source", denied)
+ with pytest.raises(api.KaggleError):
+ safety.check(api.Creds("me"), "alice/box")
+
+
+@pytest.mark.parametrize("status", [0, 401, 429, 500, 503])
+def test_a_notebook_that_could_not_be_read_is_never_safe(monkeypatch, tmp_path, status):
+ """Offline, signed out or Kaggle down says nothing about what the notebook
+ holds. Calling it safe let kdev overwrite real work."""
from kdev import api, safety
monkeypatch.setattr(safety, "backups_dir", lambda: tmp_path)
- def boom(c, s):
- raise api.KaggleError("404")
+ def broken(c, s):
+ raise api.KaggleError("GetKernel: HTTP trouble", status)
+
+ monkeypatch.setattr(api, "kernel_source", broken)
+ with pytest.raises(api.KaggleError):
+ safety.check(api.Creds("me"), "me/box")
+
+
+def test_create_never_saves_over_a_notebook_it_could_not_check(monkeypatch):
+ from kdev import notebook
+
+ def broken(c, slug, version=""):
+ raise api.KaggleError("GetKernel: HTTP 500", 500)
- monkeypatch.setattr(api, "kernel_source", boom)
- assert safety.check(api.Creds("u"), "me/new")[0] == "safe"
+ monkeypatch.setattr(api, "get_kernel", broken)
+ monkeypatch.setattr(api, "save_kernel", lambda *a, **k: pytest.fail("must not save"))
+ with pytest.raises(api.KaggleError):
+ notebook.create(api.Creds("u", "t"), "me", "box")
def test_backups_are_capped_per_notebook(tmp_path, monkeypatch):
@@ -216,3 +280,103 @@ def test_a_new_machine_adopts_settings_but_never_overrides_its_own(monkeypatch):
assert configured.tunnel_hostname == "mine.example.com"
assert not any(k.startswith("tunnel_") for k in taken)
assert configured.git_remote == "git@e:ws.git" # empty here, so taken
+
+
+def test_scan_reads_notebooks_in_parallel_and_keeps_their_order(monkeypatch):
+ """Two calls per shared notebook, one after another, made `join` crawl."""
+ import threading
+ import time
+
+ from kdev import notebook as g
+
+ refs = [(f"o/nb{i}", f"NB {i}") for i in range(6)]
+ monkeypatch.setattr(g, "discover", lambda c: refs)
+ together = threading.Barrier(g.SCAN_WORKERS, timeout=5)
+
+ def kernel_id(c, ref):
+ n = int(ref.rsplit("nb", 1)[1])
+ if n < g.SCAN_WORKERS:
+ together.wait() # breaks, failing the test, unless they run at once
+ time.sleep(0.01 * (6 - n)) # finish out of order
+ return n + 1
+
+ monkeypatch.setattr(api, "kernel_id", kernel_id)
+ monkeypatch.setattr(
+ api,
+ "get_policy",
+ lambda c, kid: {
+ "bindings": [{"role": api.ROLE_EDITOR, "members": [_real_group_member(f"g{kid % 2}")]}]
+ },
+ )
+ groups, notebooks = g.scan(api.Creds("u"))
+ assert [nb["ref"] for nb in notebooks] == [r for r, _ in refs]
+ assert [nb["id"] for nb in notebooks] == [1, 2, 3, 4, 5, 6]
+ assert [gr["slug"] for gr in groups] == ["g1", "g0"]
+
+
+def test_scan_with_nothing_shared(monkeypatch):
+ from kdev import notebook as g
+
+ monkeypatch.setattr(g, "discover", lambda c: [])
+ assert g.scan(api.Creds("u")) == ([], [])
+
+
+def _describe_setup(monkeypatch, barrier=None):
+ from kdev import config, persistence
+
+ def meet():
+ if barrier:
+ barrier.wait()
+
+ monkeypatch.setattr(
+ api, "get_kernel", lambda c, s, version="": {"currentVersionNumber": 7, "id": 42}
+ )
+
+ def policy(c, kid):
+ meet()
+ return {"bindings": [{"role": api.ROLE_EDITOR, "members": [_real_group_member("crew")]}]}
+
+ def members(c, slug):
+ meet()
+ return [{"username": "alice"}, {"username": "bob"}]
+
+ def newest(c, nb, latest):
+ meet()
+ assert latest == 7
+ return "v6", {}
+
+ monkeypatch.setattr(api, "get_policy", policy)
+ monkeypatch.setattr(api, "group_members", members)
+ monkeypatch.setattr(persistence, "newest_saved", newest)
+ monkeypatch.setattr(persistence, "version_files", lambda c, nb, label: {"a": "u", "b": "u"})
+ return config.Config(notebook="alice/box", group_slug="crew")
+
+
+def test_describe_reads_sharing_members_and_saves_at_once(monkeypatch):
+ import threading
+
+ from kdev import notebook as g
+
+ cfg = _describe_setup(monkeypatch, threading.Barrier(3, timeout=5))
+ out = g.describe(cfg, api.Creds("u"))
+ assert out["role"] == api.ROLE_EDITOR and out["members"] == ["alice", "bob"]
+ assert (out["version"], out["saved"], out["files"]) == (7, "v6", 2)
+ assert out["errors"] == [] and cfg.notebook_id == 42
+
+
+def test_describe_reports_errors_in_a_fixed_order(monkeypatch):
+ from kdev import notebook as g
+
+ cfg = _describe_setup(monkeypatch)
+
+ def fail(name):
+ def boom(*a, **k):
+ raise api.KaggleError(f"{name} failed", 500)
+
+ return boom
+
+ monkeypatch.setattr(api, "get_policy", fail("policy"))
+ monkeypatch.setattr(api, "group_members", fail("members"))
+ out = g.describe(cfg, api.Creds("u"))
+ assert out["errors"] == ["sharing: policy failed", "members: members failed"]
+ assert out["saved"] == "v6"
diff --git a/tests/test_persistence.py b/tests/test_persistence.py
index 5099b1f..dddf726 100644
--- a/tests/test_persistence.py
+++ b/tests/test_persistence.py
@@ -87,9 +87,11 @@ def _versions(monkeypatch, table):
"""table: label -> (files dict or None, state dict or None)."""
from kdev import persistence as w
- monkeypatch.setattr(
- w, "version_files", lambda c, nb, label: (table.get(label) or (None, None))[0]
- )
+ def listed(c, nb, label):
+ return (table.get(label) or (None, None))[0]
+
+ monkeypatch.setattr(w, "version_files", listed)
+ monkeypatch.setattr(w, "version_meta", listed)
monkeypatch.setattr(
w, "_state", lambda files: next((st for f, st in table.values() if f is files), None)
)
@@ -101,9 +103,10 @@ def test_session_history_caps_scanned_versions_independently_of_limit(monkeypatc
scanned = []
monkeypatch.setattr(w, "version_files", lambda c, nb, label: scanned.append(label) or None)
+ monkeypatch.setattr(api, "session_status", lambda c, nb, label: {"status": "COMPLETE"})
assert w.session_history(api.Creds("u"), "a/b", latest=100, limit=2) == []
- assert scanned == [f"v{number}" for number in range(100, 100 - w.WALK_BACK, -1)]
+ assert sorted(scanned) == sorted(f"v{number}" for number in range(100, 100 - w.WALK_BACK, -1))
def test_a_complete_saved_version_is_used_on_its_own(monkeypatch):
@@ -215,7 +218,7 @@ def test_unreadable_saved_state_fails_before_workspace_history_is_guessed(monkey
def test_failed_output_lookup_is_not_treated_as_empty_history(monkeypatch, status):
from kdev import persistence as w
- def failed(*a):
+ def failed(*a, **kw):
raise api.KaggleError("output lookup failed", status)
monkeypatch.setattr(api, "session_output", failed)
@@ -226,7 +229,7 @@ def failed(*a):
def test_absent_output_version_can_still_be_skipped(monkeypatch):
from kdev import persistence as w
- def absent(*a):
+ def absent(*a, **kw):
raise api.KaggleError("no output", 404)
monkeypatch.setattr(api, "session_output", absent)
@@ -426,3 +429,134 @@ def test_stacked_layers_only_fill_in_what_the_newest_never_got(monkeypatch):
monkeypatch.setattr(w, "_fetched", lambda files: {"kept.py", "deleted.py"})
plan = w.build_plan(api.Creds("u"), "a/b", ["v1", "v2"])
assert sorted(plan["layers"][0]["files"]) == [".kdev/meta.json", "failed.bin", "never.py"]
+
+
+def test_history_can_show_more_than_the_restore_walk_back(monkeypatch):
+ """`kdev history --limit 50` was silently capped at 10 scanned versions."""
+ from kdev import persistence as w
+
+ monkeypatch.setattr(w, "version_files", lambda c, nb, label: {"a.py": "u"})
+ monkeypatch.setattr(w, "_state", lambda files: {})
+ monkeypatch.setattr(api, "session_status", lambda c, nb, label: {"status": "COMPLETE"})
+ rows = w.session_history(api.Creds("u"), "a/b", latest=200, limit=50)
+ assert [r["version"] for r in rows] == [f"v{n}" for n in range(200, 150, -1)]
+
+
+def test_history_looks_past_empty_versions_but_not_forever(monkeypatch):
+ from kdev import persistence as w
+
+ scanned = []
+
+ def listed(c, nb, label):
+ scanned.append(label)
+ return {"a.py": "u"} if int(label[1:]) % 2 else None # every other one empty
+
+ monkeypatch.setattr(w, "version_files", listed)
+ monkeypatch.setattr(w, "_state", lambda files: {})
+ monkeypatch.setattr(api, "session_status", lambda c, nb, label: {"status": "COMPLETE"})
+ rows = w.session_history(api.Creds("u"), "a/b", latest=101, limit=20)
+ assert len(rows) == 20 and rows[0]["version"] == "v101"
+ assert len(scanned) <= 40, "the window is bounded by twice the limit"
+
+
+def test_history_stops_reading_once_it_has_enough(monkeypatch):
+ """Each version is a full listing: one batch that fills the limit is enough."""
+ from kdev import persistence as w
+
+ scanned = []
+ monkeypatch.setattr(
+ w, "version_files", lambda c, nb, label: scanned.append(label) or {"a": "u"}
+ )
+ monkeypatch.setattr(w, "_state", lambda files: {})
+ monkeypatch.setattr(api, "session_status", lambda c, nb, label: {"status": "COMPLETE"})
+ assert len(w.session_history(api.Creds("u"), "a/b", latest=100, limit=10)) == 10
+ assert len(scanned) == w.WALK_BACK
+
+
+def test_a_hung_rsync_is_a_failed_sync_not_a_crash(monkeypatch):
+ import subprocess
+
+ from kdev import persistence as w
+
+ seen = {}
+
+ def hang(cmd, **kw):
+ seen.update(kw)
+ raise subprocess.TimeoutExpired(cmd, kw.get("timeout") or 0)
+
+ monkeypatch.setattr(w.subprocess, "run", hang)
+ r = w._rsync("a/", "b/")
+ assert seen["timeout"] == w.RSYNC_TIMEOUT
+ assert r.returncode != 0 and "timed out" in r.stderr
+
+
+def test_pull_reports_a_hung_rsync(monkeypatch, tmp_path):
+ import subprocess
+
+ from kdev import persistence as w
+
+ monkeypatch.setattr(w, "mirror_dir", lambda: tmp_path)
+
+ def hang(cmd, **kw):
+ raise subprocess.TimeoutExpired(cmd, kw.get("timeout") or 0)
+
+ monkeypatch.setattr(w.subprocess, "run", hang)
+ ok, err = w.pull("kaggle")
+ assert not ok and "timed out" in err
+
+
+def test_wait_reachable_never_blocks_on_one_stalled_ssh(monkeypatch):
+ """ConnectTimeout covers TCP only; a ProxyCommand that stalls hung forever."""
+ import subprocess
+
+ from kdev import persistence as w
+
+ clock = [0.0]
+ monkeypatch.setattr(w.time, "time", lambda: clock[0])
+ monkeypatch.setattr(w.time, "sleep", lambda s: clock.__setitem__(0, clock[0] + s))
+ calls = []
+
+ def ssh(cmd, **kw):
+ calls.append(kw.get("timeout"))
+ clock[0] += kw["timeout"]
+ if len(calls) < 3:
+ raise subprocess.TimeoutExpired(cmd, kw["timeout"])
+ return subprocess.CompletedProcess(cmd, 0)
+
+ monkeypatch.setattr(w.subprocess, "run", ssh)
+ assert w.wait_reachable("kaggle", timeout=180)
+ assert calls and all(t for t in calls)
+
+
+def test_history_remembers_ended_versions_and_rereads_live_ones(monkeypatch):
+ from kdev import persistence as w
+
+ listed = []
+ statuses = {"v2": "COMPLETE", "v1": "COMPLETE", "v3": "RUNNING"}
+ monkeypatch.setattr(
+ w, "version_files", lambda c, nb, label: listed.append(label) or {"a.py": "u"}
+ )
+ monkeypatch.setattr(w, "_state", lambda files: {"run_by": "alice"})
+ monkeypatch.setattr(api, "session_status", lambda c, nb, label: {"status": statuses[label]})
+
+ first = w.session_history(api.Creds("u"), "a/b", latest=3, limit=3)
+ listed.clear()
+ again = w.session_history(api.Creds("u"), "a/b", latest=3, limit=3)
+ assert again == first
+ assert listed == ["v3"], "only the version still running is read again"
+
+
+def test_a_version_that_ends_while_being_listed_is_not_cached_as_final(monkeypatch):
+ from kdev import persistence as w
+
+ seen = {"status": "CANCEL_REQUESTED"}
+
+ def listing(c, nb, label):
+ seen["status"] = "COMPLETE" # it finishes saving mid-listing
+ return {"a.py": "u"}
+
+ monkeypatch.setattr(w, "version_files", listing)
+ monkeypatch.setattr(w, "_state", lambda files: {})
+ monkeypatch.setattr(api, "session_status", lambda c, nb, label: dict(seen))
+ w.session_history(api.Creds("u"), "a/b", latest=1, limit=1)
+ assert "a/b@v1" not in w._history_cache()
diff --git a/tests/test_sshcfg.py b/tests/test_sshcfg.py
index 6b7b92b..a9f4fb9 100644
--- a/tests/test_sshcfg.py
+++ b/tests/test_sshcfg.py
@@ -1,3 +1,5 @@
+import pytest
+
from kdev import sshcfg
@@ -42,3 +44,171 @@ def test_ssh_block_presence_is_detectable(tmp_path, monkeypatch):
assert sshcfg.has_block()
sshcfg.clear()
assert not sshcfg.has_block()
+
+
+# --- placement --------------------------------------------------------------------
+
+USER_CONFIG = """\
+# my global settings
+AddKeysToAgent yes
+Include ~/.ssh/config.d/*
+
+# work machines
+Host github.com
+ User git
+
+Host *
+ User nobody
+ ServerAliveInterval 5
+"""
+
+
+def _lines(text: str) -> list[str]:
+ return [line for line in text.splitlines() if line.strip()]
+
+
+def test_the_block_goes_above_every_stanza_so_host_star_cannot_override_it(tmp_path, monkeypatch):
+ """ssh uses the first value it finds: below `Host *`, our `User root` lost."""
+ cfgfile = tmp_path / "config"
+ cfgfile.write_text(USER_CONFIG)
+ monkeypatch.setattr(sshcfg, "SSH_CONFIG", cfgfile)
+ sshcfg.write("kaggle", "box.example.com")
+ text = cfgfile.read_text()
+
+ assert text.index(sshcfg.BEGIN) < text.index("Host *")
+ assert text.index(sshcfg.BEGIN) < text.index("Host github.com")
+ # Global options apply to every host and stay on top; the comment above
+ # a stanza stays with it.
+ assert text.index("Include ~/.ssh/config.d/*") < text.index(sshcfg.BEGIN)
+ assert text.index(sshcfg.END) < text.index("# work machines")
+ # Nothing of the user's is lost or reordered.
+ block = _lines(sshcfg.render_block("kaggle", "box.example.com"))
+ assert [x for x in _lines(text) if x not in block] == _lines(USER_CONFIG)
+
+
+def test_rewriting_is_idempotent(tmp_path, monkeypatch):
+ cfgfile = tmp_path / "config"
+ cfgfile.write_text(USER_CONFIG)
+ monkeypatch.setattr(sshcfg, "SSH_CONFIG", cfgfile)
+ sshcfg.write("kaggle", "box.example.com")
+ once = cfgfile.read_text()
+ sshcfg.write("kaggle", "box.example.com")
+ assert cfgfile.read_text() == once
+ sshcfg.clear()
+ assert _lines(cfgfile.read_text()) == _lines(USER_CONFIG)
+
+
+def test_a_block_left_below_host_star_by_an_older_kdev_moves_up(tmp_path, monkeypatch):
+ cfgfile = tmp_path / "config"
+ old = sshcfg.render_block("kaggle", "old.example.com")
+ cfgfile.write_text("Host *\n User nobody\n\n" + old)
+ monkeypatch.setattr(sshcfg, "SSH_CONFIG", cfgfile)
+ sshcfg.write("kaggle", "new.example.com")
+ text = cfgfile.read_text()
+ assert text.count(sshcfg.BEGIN) == 1 and "old.example.com" not in text
+ assert text.startswith(sshcfg.BEGIN)
+ assert text.index(sshcfg.END) < text.index("Host *") and "User nobody" in text
+
+
+@pytest.mark.parametrize(
+ "existing",
+ ["", "\n\n", "AddKeysToAgent yes", "Match host foo\n User bar", "host=lower\n User x\n"],
+)
+def test_odd_configs_keep_their_content(tmp_path, monkeypatch, existing):
+ cfgfile = tmp_path / "config"
+ cfgfile.write_text(existing)
+ monkeypatch.setattr(sshcfg, "SSH_CONFIG", cfgfile)
+ sshcfg.write("kaggle", "box.example.com")
+ text = cfgfile.read_text()
+ assert text.count(sshcfg.BEGIN) == 1
+ for line in _lines(existing):
+ assert line in text
+ if _lines(existing) and existing.lstrip().lower().startswith(("match", "host")):
+ assert text.startswith(sshcfg.BEGIN)
+ assert sshcfg.current() == ("kaggle", "box.example.com")
+
+
+def test_a_symlinked_config_stays_a_symlink(tmp_path, monkeypatch):
+ """Dotfile managers link ~/.ssh/config; replacing the link loses the repo copy."""
+ real = tmp_path / "dotfiles" / "ssh_config"
+ real.parent.mkdir()
+ real.write_text("Host other\n User me\n")
+ link = tmp_path / "config"
+ link.symlink_to(real)
+ monkeypatch.setattr(sshcfg, "SSH_CONFIG", link)
+ sshcfg.write("kaggle", "box.example.com")
+ assert link.is_symlink() and sshcfg.BEGIN in real.read_text()
+
+
+# --- keeping it in step with the settings -----------------------------------------
+
+
+def _cfg(**kw):
+ from kdev import config
+
+ return config.Config(**kw)
+
+
+def test_renaming_the_alias_rewrites_the_block(monkeypatch):
+ """`kdev config set ssh-alias box` left `Host kaggle` behind; `kdev ssh` then
+ asked ssh for a host the file did not have."""
+ from kdev import session
+
+ sshcfg.write("kaggle", "box.example.com")
+ session.ssh_ready(_cfg(tunnel_hostname="box.example.com", ssh_host_alias="gpu"))
+ assert sshcfg.current() == ("gpu", "box.example.com")
+ assert sshcfg.SSH_CONFIG.read_text().count(sshcfg.BEGIN) == 1
+
+
+def test_a_quick_tunnel_host_survives_an_alias_rename(monkeypatch):
+ """Only the box knows a quick tunnel's hostname: it must not be replaced
+ by the configured one, or by nothing."""
+ from kdev import session
+
+ sshcfg.write("kaggle", "random-words.trycloudflare.com")
+ session.ssh_ready(_cfg(tunnel_hostname="", ssh_host_alias="gpu"))
+ assert sshcfg.current() == ("gpu", "random-words.trycloudflare.com")
+ # A named tunnel configured here does not override a box that is up
+ # on a quick one -- unless the hostname setting itself just changed.
+ session.ssh_ready(_cfg(tunnel_hostname="box.example.com", ssh_host_alias="gpu"))
+ assert sshcfg.current() == ("gpu", "random-words.trycloudflare.com")
+ session.ssh_ready(
+ _cfg(tunnel_hostname="box.example.com", ssh_host_alias="gpu"), host_changed=True
+ )
+ assert sshcfg.current() == ("gpu", "box.example.com")
+
+
+def test_ssh_ready_leaves_a_matching_block_alone(monkeypatch):
+ from kdev import session
+
+ sshcfg.write("kaggle", "box.example.com")
+ before = sshcfg.SSH_CONFIG.stat().st_mtime_ns
+ monkeypatch.setattr(sshcfg, "write", lambda *a, **k: pytest.fail("must not rewrite"))
+ session.ssh_ready(_cfg(tunnel_hostname="box.example.com", ssh_host_alias="kaggle"))
+ assert sshcfg.SSH_CONFIG.stat().st_mtime_ns == before
+
+
+@pytest.mark.parametrize(
+ ("argv", "expected"),
+ [
+ (["set", "ssh-alias", "gpu"], ("gpu", "box.example.com")),
+ (["unset", "ssh-alias"], ("kaggle", "box.example.com")),
+ (["set", "tunnel-hostname", "new.example.com"], ("kaggle", "new.example.com")),
+ ],
+)
+def test_config_set_keeps_ssh_config_in_step(monkeypatch, argv, expected):
+ from typer.testing import CliRunner
+
+ from kdev import config
+ from kdev.commands import settings
+
+ cfg = config.Config(tunnel_hostname="box.example.com", ssh_host_alias="gpu")
+ cfg.add("alice", config.Profile("alice"))
+ if argv[0] == "set" and argv[1] == "tunnel-hostname":
+ cfg.ssh_host_alias = "kaggle"
+ config.save(cfg)
+ sshcfg.write(cfg.ssh_host_alias, cfg.tunnel_hostname)
+
+ result = CliRunner().invoke(settings.app, argv)
+ assert result.exit_code == 0, result.output
+ assert sshcfg.current() == expected
diff --git a/tests/test_ui.py b/tests/test_ui.py
index 6f5ccda..dfd8185 100644
--- a/tests/test_ui.py
+++ b/tests/test_ui.py
@@ -162,14 +162,14 @@ def test_header_shows_compact_multicolour_logo_in_a_colour_terminal(monkeypatch)
theme=ui.THEME,
)
monkeypatch.setattr(ui, "console", terminal)
- ui.header("up", [("tunnel", "box.example.com")])
+ ui.header("setup", [("tunnel", "box.example.com")])
text = terminal.export_text()
lines = text.splitlines()
assert len(lines[: lines.index("")]) == 5
assert all(len(line) <= terminal.width for line in lines)
assert any(char in text for char in "█▀▄")
- assert "up · v" in text and "box.example.com" in text
+ assert "setup · v" in text and "tunnel box.example.com" in text
for rgb in ("0;184;212", "67;213;237", "33;142;255"):
assert rgb in output.getvalue()
@@ -197,10 +197,11 @@ def test_header_uses_plain_title_when_pixel_art_cannot_render(monkeypatch, limit
theme=ui.THEME,
)
monkeypatch.setattr(ui, "console", terminal)
- ui.header("status")
+ ui.header("setup")
text = terminal.export_text()
- assert text.lstrip().startswith("kdev") and "status" in text
+ first = text.lstrip().splitlines()[0]
+ assert first.startswith(("kdev", "›_ kdev")) and "setup" in first
assert not any(char in text for char in "█▀▄")
@@ -223,14 +224,14 @@ def test_header_uses_compact_mascot_without_wrapping(monkeypatch, width):
theme=ui.THEME,
)
monkeypatch.setattr(ui, "console", terminal)
- ui.header("status")
+ ui.header("setup")
lines = terminal.export_text().splitlines()
compact = ui._logo(compact=True).plain.splitlines()
assert len(lines[: lines.index("")]) == len(compact) == 4
assert [line[ui.GUTTER :] for line in lines[:4]] == compact
assert all(len(line) <= width for line in lines)
- assert "kdev · status" in "\n".join(lines)
+ assert "kdev setup" in "\n".join(lines)
def test_logo_uses_terminal_foreground_for_light_and_dark_themes():
@@ -270,14 +271,31 @@ def test_header_scope_suppresses_duplicate_logos_and_resets_after_errors(monkeyp
monkeypatch.setattr(ui, "console", terminal)
with pytest.raises(RuntimeError), ui.command_header_scope():
ui.header("setup")
- ui.header("up")
+ ui.header("")
raise RuntimeError("cancelled setup")
with ui.command_header_scope():
- ui.header("status")
+ ui.header("overview")
text = terminal.export_text()
assert text.count(ui._logo().plain.splitlines()[0].strip()) == 2
- assert "setup" in text and "up" in text and "status" in text
+ assert "setup" in text and "overview" in text
+
+
+def test_subcommands_get_a_one_line_header_with_their_context(monkeypatch):
+ from io import StringIO
+
+ from rich.console import Console
+
+ from kdev import ui
+
+ monkeypatch.delenv("NO_COLOR", raising=False)
+ monkeypatch.setenv("TERM", "xterm")
+ terminal = Console(file=StringIO(), width=100, force_terminal=True, record=True, theme=ui.THEME)
+ monkeypatch.setattr(ui, "console", terminal)
+ ui.header("up", [("account", "alice"), ("tunnel", "box.example.com")])
+ lines = terminal.export_text().splitlines()
+ assert "kdev › up" in lines[0] and "tunnel box.example.com" in lines[0]
+ assert not any(char in "".join(lines) for char in "█▀▄")
def test_terminal_only_header_leaves_piped_output_untouched(monkeypatch):
@@ -383,7 +401,7 @@ def test_terminal_stage_board_keeps_failure_pending_stages_and_timings(monkeypat
compact = "".join(line.strip(" │|") for line in text.splitlines())
assert "Couldnotrestoresavedfiles" in "".join(compact.split())
assert ui.g("err") in text and ui.g("pending") in text
- assert "1/3 complete" in text and "Connect SSH" in text
+ assert "stopped at restore" in text and "Connect SSH" in text
assert stage.done == ["a"]
@@ -453,7 +471,8 @@ def make(message, **kwargs):
monkeypatch.setattr(ui, "interactive", lambda: True)
choices = [ui.Choice("Keep files", value="keep"), ui.Choice("Replace files", value="replace")]
assert ui.select("Files?", choices) == "keep"
- assert calls[0][2]["choices"] is choices
+ assert [c.value for c in calls[0][2]["choices"]] == ["keep", "replace"]
+ assert calls[0][2]["choices"][0].title == "1 Keep files"
assert [choice.value for choice in choices] == ["keep", "replace"]
assert ui.confirm("Replace?", default=False) is False
assert calls[1][2]["default"] is False
@@ -466,3 +485,43 @@ def make(message, **kwargs):
monkeypatch.setattr(ui, "interactive", lambda: False)
assert ui.confirm("Replace?", default=False) is False
assert len(calls) == 5
+
+
+def test_a_digit_picks_its_row_at_once():
+ from prompt_toolkit.input import create_pipe_input
+ from prompt_toolkit.output import DummyOutput
+
+ from kdev import ui
+
+ with create_pipe_input() as pipe:
+ real = ui.questionary.select
+
+ def select(*a, **kw):
+ return real(*a, input=pipe, output=DummyOutput(), **kw)
+
+ with patch.object(ui.questionary, "select", select):
+ pipe.send_text("2")
+ assert (
+ ui.select("Which?", [ui.Choice("A", value="a"), ui.Choice("B", value="b")]) == "b"
+ )
+
+
+def test_step_timings_are_remembered_only_for_complete_own_runs(monkeypatch, tmp_path):
+ from kdev import config, ui
+
+ monkeypatch.setattr(config, "CONFIG_DIR", tmp_path)
+ monkeypatch.setattr(ui, "interactive", lambda: True)
+
+ def run(record=True, finish=True):
+ with ui.Stages([("a", "A"), ("b", "B")]) as board:
+ board.record = record
+ board.advance("a")
+ board.advance("b")
+ if finish:
+ board.finish()
+
+ run(record=False)
+ run(finish=False)
+ assert not (tmp_path / "timings.json").exists()
+ run()
+ assert set(ui._load_timings()) == {"a", "b"}
diff --git a/uv.lock b/uv.lock
index c39308c..ff13a88 100644
--- a/uv.lock
+++ b/uv.lock
@@ -495,11 +495,12 @@ wheels = [
[[package]]
name = "kdev-cli"
-version = "0.1.4"
+version = "0.2.0"
source = { editable = "." }
dependencies = [
{ name = "httpx" },
{ name = "kaggle" },
+ { name = "prompt-toolkit" },
{ name = "questionary" },
{ name = "rich" },
{ name = "typer" },
@@ -518,6 +519,7 @@ dev = [
requires-dist = [
{ name = "httpx", specifier = ">=0.27,<1" },
{ name = "kaggle", specifier = ">=2.2,<3" },
+ { name = "prompt-toolkit", specifier = ">=3.0.36,<4" },
{ name = "questionary", specifier = ">=2.0,<3" },
{ name = "rich", specifier = ">=13,<16" },
{ name = "typer", specifier = ">=0.27,<1" },
diff --git a/website/README.md b/website/README.md
index fd3a861..49ba647 100644
--- a/website/README.md
+++ b/website/README.md
@@ -13,6 +13,10 @@ npm run preview # wrangler pages dev on the built dist/ (real 404s and head
```
- Docs live in `src/content/docs/*.md` (adapted from the root README).
+ Diagrams are inline HTML/SVG `` blocks inside the
+ Markdown (no blank lines inside a block), styled by the `.fig` and `.seq`
+ rules in `src/styles/global.css`. The plain-text outputs (`/docs/*.md`,
+ `/llms-full.txt`) replace each figure with its caption.
- `/changelog` renders the repository's own `CHANGELOG.md`; nothing to copy.
- No third-party requests: fonts are self-hosted via Fontsource, search is
Pagefind running in the browser. `scripts/postbuild.mjs` hashes the inline
diff --git a/website/src/components/Footer.astro b/website/src/components/Footer.astro
index bbd8545..caf3274 100644
--- a/website/src/components/Footer.astro
+++ b/website/src/components/Footer.astro
@@ -7,6 +7,7 @@ const cols = [
title: 'Use',
items: [
{ href: '/docs/', label: 'Get started' },
+ { href: '/docs/how-it-works/', label: 'How it works' },
{ href: '/docs/commands/', label: 'Commands' },
{ href: '/docs/troubleshooting/', label: 'Troubleshooting' },
{ href: '/changelog/', label: 'Changelog' },
diff --git a/website/src/components/HowItWorks.astro b/website/src/components/HowItWorks.astro
index 3b9abb6..40aa0a5 100644
--- a/website/src/components/HowItWorks.astro
+++ b/website/src/components/HowItWorks.astro
@@ -15,7 +15,7 @@ const steps = [
How it works
One cell on top of your notebook. Six steps to a shell.
-
The simple picture is on the right. When you want every module, file and API call, open the full architecture.
+
The simple picture is on the right. When you want every module, file and API call, open the full architecture, or read how it works, in depth: the start sequence, your files, accounts and the security model, with diagrams.
diff --git a/website/src/components/Nav.astro b/website/src/components/Nav.astro
index 8c756df..a508e49 100644
--- a/website/src/components/Nav.astro
+++ b/website/src/components/Nav.astro
@@ -5,11 +5,15 @@ import { site } from '../data/site';
const path = Astro.url.pathname;
const items = [
{ href: '/#features', label: 'Features' },
- { href: '/#how', label: 'How it works' },
+ { href: '/docs/how-it-works/', label: 'How it works' },
{ href: '/docs/', label: 'Docs' },
{ href: '/changelog/', label: 'Changelog' },
];
-const isActive = (href: string) => !href.includes('#') && path.startsWith(href);
+// The most specific match wins, so /docs/how-it-works/ lights "How it works", not "Docs".
+const active = items
+ .filter((i) => !i.href.includes('#') && path.startsWith(i.href))
+ .sort((a, b) => b.href.length - a.href.length)[0]?.href;
+const isActive = (href: string) => href === active;
---
diff --git a/website/src/components/Terminal.astro b/website/src/components/Terminal.astro
index fb458b0..f48af25 100644
--- a/website/src/components/Terminal.astro
+++ b/website/src/components/Terminal.astro
@@ -1,6 +1,6 @@
---
-// A replay of `kdev up`: the steps, glyphs and per-step clocks the CLI's
-// status board draws (ui.py: Stages), its ready card (ui.ready_card), then ssh.
+// A replay of `kdev up`: the rail, glyphs and per-step clocks the CLI's
+// progress board draws (ui.py: Stages), its ready card (ui.ready_card), then ssh.
// Server-rendered in its final state so it reads correctly without JS; the
// script rewinds it and plays it.
const steps = [
@@ -26,22 +26,29 @@ const steps = [
$kdev up
-
alice· T4 ×2 · 9h2m03s
+
┌ alice· T4 ×2 · 9h
+
│
{steps.map((s, i) => (
- ✓
+ ◇{s.t}{s.d}
))}
-
1505/1505 files
-
●Ready
+
│1505/1505 files
+
◇Ready
+
│
+
└ done in 2m03s
-
✓ ready
-
host box.example.com
-
ends 23:14 (9h from now) files 1505 restored
-
connect ssh kaggle stop kdev down
+
✓ ready
+
host box.example.com
+
account alice
+
time 9h00m left · ends 23:14
+
files 1505 restored
+
+
connect ssh kaggle
+
stop kdev down
$ssh kaggle
root@kaggle:/kaggle/working# nvidia-smi -L
@@ -93,9 +100,9 @@ const steps = [
.r { color: #3ddc97; }
.ok { color: #3ddc97; }
b { color: #fff; font-weight: 600; }
- .board { margin: 10px 0 12px; padding: 10px 14px; border: 1px solid rgb(255 255 255 / 0.08); border-radius: 10px; background: rgb(255 255 255 / 0.015); }
- .head { display: flex; justify-content: space-between; margin-bottom: 4px; }
- .step { display: grid; grid-template-columns: 22px 1fr auto; }
+ .board { margin: 10px 0 12px; }
+ .rl { color: #4d5763; }
+ .step { display: grid; grid-template-columns: 30px 1fr auto; max-width: 460px; }
.step .g { color: #3ddc97; }
.step.is-wait .g, .step.is-wait .st { color: #4d5763; }
.step.is-run .g { color: #00b8d4; }
@@ -103,10 +110,12 @@ const steps = [
.step.ready .g { color: #3ddc97; }
.step .clk { color: var(--term-dim); font-variant-numeric: tabular-nums; }
.step.is-wait .clk { visibility: hidden; }
- .sub { display: flex; gap: 12px; align-items: center; padding-left: 22px; }
+ .sub { display: grid; grid-template-columns: 30px auto 1fr; gap: 0 12px; align-items: center; }
.bar { width: 120px; height: 4px; border-radius: 4px; background: rgb(255 255 255 / 0.08); overflow: hidden; }
.bar i { display: block; height: 100%; width: calc(var(--p) * 100%); background: linear-gradient(90deg, #00b8d4, #43d5ed); border-radius: inherit; }
- .card { padding: 2px 0 12px; }
+ .card { position: relative; max-width: 470px; margin: 18px 0 14px; padding: 16px 14px 10px; border: 1px solid rgb(61 220 151 / 0.7); border-radius: 10px; }
+ .card__t { position: absolute; top: -12px; left: 12px; padding: 0 6px; background: var(--t-bg); }
+ .left { display: inline-block; width: 96px; height: 10px; border-radius: 2px; background: #3ddc97; vertical-align: -1px; }
.cur { display: inline-block; width: 8px; height: 15px; background: #00b8d4; vertical-align: -3px; animation: cur 1s steps(2) infinite; }
@keyframes cur { 50% { opacity: 0; } }
[data-hide] { display: none; }
@@ -114,8 +123,7 @@ const steps = [
@media (max-width: 560px) {
.term { font-size: 11px; }
.term__body { height: 470px; padding: 14px 14px 18px; }
- .board { padding: 8px 10px; }
- .bar { width: 70px; }
+ .bar { width: 70px; }
}
@@ -170,6 +178,7 @@ const steps = [
later.forEach((el) => el.setAttribute('data-hide', ''));
typed.forEach((el) => (el.textContent = ''));
steps.forEach((el) => { el.className = el.className.replace(/is-\w+/g, '').trim() + ' is-wait'; const g = el.querySelector('[data-g]')!; g.textContent = '○'; });
+ q('[data-foot]').setAttribute('data-hide', '');
files.setAttribute('data-hide', '');
bar.style.setProperty('--p', '0');
count.textContent = '0';
@@ -209,12 +218,13 @@ const steps = [
await wait(80, s);
}
elapsed += realMs;
- g.textContent = '✓';
+ g.textContent = '◇';
el.classList.replace('is-run', 'is-done');
}
const ready = steps[steps.length - 1];
ready.classList.replace('is-wait', 'is-done');
- ready.querySelector('[data-g]')!.textContent = '●';
+ ready.querySelector('[data-g]')!.textContent = '◇';
+ q('[data-foot]').removeAttribute('data-hide');
await wait(500, s);
later[1].removeAttribute('data-hide');
await wait(1100, s);
diff --git a/website/src/content/docs/commands.md b/website/src/content/docs/commands.md
index 298817c..76a6aae 100644
--- a/website/src/content/docs/commands.md
+++ b/website/src/content/docs/commands.md
@@ -11,7 +11,7 @@ order: 6
| command | what it does |
|---|---|
-| `kdev` | overview of the box, accounts and workspace; in a terminal, the next actions |
+| `kdev` | the home screen: the box and every account's quota, live, with one key per action |
| `kdev setup` | get this machine ready; only does what is missing |
| `kdev up` | start the box, or connect to the running one |
| `kdev down` | stop the box; files are saved however it stops |
@@ -21,11 +21,11 @@ order: 6
| `kdev history [-n N] [--json]` | recent saved sessions, who ran them and how they ended |
| `kdev logs [-n N] [--all]` | the session log |
| `kdev restore [--from vN \| --from-backup]` | put saved files back |
-| `kdev backup` | copy the running box to this machine |
+| `kdev backup [--force]` | copy the running box to this machine (refuses a box that never finished restoring, unless `--force`) |
| `kdev account [--json]` | accounts and quota |
| `kdev account add \| use \| remove` | manage accounts |
| `kdev workspace` | the notebook: owner, sharing, members, saved versions |
-| `kdev workspace files [--version vN] [--json]` | what a saved version holds |
+| `kdev workspace files [--version vN] [--all] [--json]` | what a saved version holds: each top-level folder and its file count; `--all` lists every file |
| `kdev workspace join \| use \| create \| share` | choose, make, or re-share the notebook |
| `kdev config` / `set KEY VALUE` / `unset KEY` | settings |
| `kdev tunnel` / `tunnel setup` | the Cloudflare tunnel |
diff --git a/website/src/content/docs/contributing.md b/website/src/content/docs/contributing.md
index 43a3665..9d39af6 100644
--- a/website/src/content/docs/contributing.md
+++ b/website/src/content/docs/contributing.md
@@ -61,6 +61,9 @@ When yours touches the box, the tunnel or the restore, try it for real:
## How the code is laid out
+The full picture, with diagrams, is in
+[docs/ARCHITECTURE.md](https://github.com/tushar-mahalya/kdev/blob/main/docs/ARCHITECTURE.md).
+
| layer | rule |
|---|---|
| `commands/` | parse arguments, call logic, render with `ui`; no API calls of their own beyond reads |
diff --git a/website/src/content/docs/everyday-use.md b/website/src/content/docs/everyday-use.md
index ea5ebfb..a06e541 100644
--- a/website/src/content/docs/everyday-use.md
+++ b/website/src/content/docs/everyday-use.md
@@ -6,15 +6,27 @@ order: 2
---
```bash
-kdev # overview: the box, every account's quota, what to do next
+kdev # the home screen: the box and quota, live; one key per action
kdev up # start the box, or connect to the one already running
kdev status # running? who started it? when does it end? files back?
kdev down # stop it now
```
-Bare `kdev` in a terminal ends with a menu of the actions that make sense
-right now: connect or stop when the box is up; start it, or switch account,
-when it isn't.
+Bare `kdev` in a terminal is the home screen. It is usable at once: the box
+and every account's quota fill in while you look, a running box counts down
+in place, and the active account's bar shows what the next box will use.
+Every action has a key — `1` starts or opens the box, `s` status, `a`
+accounts, `d` doctor, `q` quits — and arrows, `j`/`k` and Enter work too. The
+highlighted item shows the exact command it runs (`$ kdev up`), so anything
+you do from the menu you can also type or script. Read-only picks come back
+to the menu; `up`, `ssh` and VS Code hand you the box, and `down` ends it.
+
+In a short terminal, such as an editor's panel, the logo gives way and the
+secondary actions fold onto one line of keys.
+
+Without a terminal (`kdev | cat`, CI), the same facts print as plain lines,
+tables become tab-separated so `cut -f2` works, and advice (hints, next
+steps) goes to stderr, so stdout carries only data.
The box you start is a setting — pick once, and `kdev up` stops asking:
diff --git a/website/src/content/docs/how-it-works.md b/website/src/content/docs/how-it-works.md
index 229ca43..b7c3b63 100644
--- a/website/src/content/docs/how-it-works.md
+++ b/website/src/content/docs/how-it-works.md
@@ -1,6 +1,6 @@
---
title: "How it works"
-description: "What kdev writes into your notebook, and what happens between kdev up and a shell."
+description: "The architecture, what kdev up does, how your files persist and come back, how accounts and machines share one box, and the security model."
group: Concepts
order: 3
---
@@ -10,47 +10,473 @@ call. kdev writes a small cell at the top of your notebook. When Kaggle runs
that cell, it turns the container into an SSH server and connects it to your
Cloudflare tunnel. Your laptop then reaches it by name.
-> **Your machine** runs `kdev`, which talks to the **Kaggle API** to save
-> and run the notebook, read quota and stream logs. **The box** (a notebook
-> session) runs kdev's cell: `sshd`, `cloudflared` and the restore. Your
-> `ssh` goes to **Cloudflare's edge**, which forwards to the box's outbound
-> tunnel. When the session ends, `/kaggle/working` is saved as a **notebook
-> version**, and the next start restores it.
+## The big picture
-Nothing listens on a public port: the box dials *out* to Cloudflare, and your
-`ssh` reaches it through Cloudflare by hostname.
+
+
+
+
+The architecture. kdev starts the box through the Kaggle API. The box and your ssh both dial out to Cloudflare's edge, which joins them by hostname, so nothing listens on a public port. When a session ends, Kaggle keeps /kaggle/working as a saved version, and the next start restores it.
+
+
+- **Your machine** runs `kdev`. It talks to the Kaggle API over HTTPS to save
+ and run the notebook, read quota and stream the session log. It also writes
+ a `kaggle` host into `~/.ssh/config`, so `ssh kaggle` and VS Code
+ Remote-SSH work.
+- **The box** is one notebook session. kdev's cell runs `sshd` and
+ `cloudflared`, exports the notebook's environment (CUDA, Python, Kaggle
+ variables) to every ssh session, and restores your files.
+- **Cloudflare's edge** is where the two meet. Both sides dial out to it, so
+ no port is open on the box.
+- **Saved versions** are Kaggle's own: when a session ends, `/kaggle/working`
+ is kept as that version's output.
+
+The box reports back through its own session log: `KDEV_STAGE` lines drive
+the progress board, `KDEV_READY` carries the hostname, `KDEV_ALIVE` is a
+heartbeat, and `KDEV_DONE` marks the end.
## What `kdev up` does
+
+
+
+
You
+
kdev
+
Kaggle API
+
The box
+
Cloudflare
+
+
1kdev up
+
2session status: running already?
+
if a box is already running
+
3connect to it, no second box
+
else nothing is running
+
4pick the saved version to build on
+
5SaveKernel: notebook + kdev's cell
+
6Save & Run All: start the container
+
7 record the plan in .kdev/state.json
+
8 sshd · environment · git clone
+
9open the tunnel, dialling out
+
10KDEV_READY in the session log
+
11ssh: is this the session we started?
+
12fresh file list + signed URLs
+
13"restore this", over ssh
+
14download every file straight from Kaggle
+
15 put back symlinks, empty dirs, exec bits
+
16ssh check
+
17ready: VS Code or a shell
+
+
+One kdev up, start to finish. Solid arrows are requests, dashed ones are answers. kdev checks that the tunnel reaches the session it started before it restores anything, and checks ssh once more before it calls the box ready.
+
+
1. **Is a box already running?** kdev asks the Kaggle API for the session
- status. If one is up, it connects to it: no second session.
-2. **Which saved version to build on.** It walks back from the latest version
- to the one that holds your files.
+ status. If one is up, from any account or machine, it connects to it: no
+ second session.
+2. **Which saved version to build on.** It walks back from the latest
+ version to the one that holds your files
+ ([how it picks](#picking-the-version-to-restore)).
3. **Save & Run All.** Your notebook goes up with kdev's cell on top
- (`SaveKernel`), and Kaggle starts the container.
-4. **The box sets itself up.** It records the plan in `.kdev/state.json` before
- anything slow, then starts `sshd`, exports the notebook environment and
- clones your repo.
-5. **The tunnel opens.** `cloudflared` dials out to Cloudflare and the box
- reports `KDEV_READY` through the session log.
-6. **Restore.** kdev fetches a fresh file list with signed URLs for the saved
- version and tells the box to restore it over ssh. The box downloads every
- file straight from Kaggle, then puts back symlinks, empty directories and
- exec bits.
+ (`SaveKernel`), and Kaggle starts the container on the quota of the account
+ that asked. Nothing below kdev's cell runs.
+4. **The box sets itself up.** It records the plan in `.kdev/state.json`
+ before anything slow, then starts `sshd`, exports the notebook environment
+ and clones your repo, if you set one.
+5. **The tunnel opens.** `cloudflared` dials out to Cloudflare, and the box
+ reports `KDEV_READY` with its hostname through the session log.
+6. **Check, then restore.** kdev verifies over ssh that the tunnel reaches the
+ session it started. Then it fetches a fresh file list with signed URLs and
+ tells the box to restore it. The box downloads every file straight from
+ Kaggle, then puts back symlinks, empty directories and exec bits.
7. **Hand over.** A final ssh check, and kdev opens VS Code or a shell.
-The board you watch while this happens shows each step's own clock, so a slow
-queue looks like a queue and not a hang:
+The rail you watch while this happens shows each step's own clock, and how
+long that step usually takes on your machine, so a slow queue looks like a
+queue and not a hang. This is a real run, a CPU box restoring 2,428 files:
```
- alice · T4 ×2 · 9h 1m52s
- ✓ Submitting 1s
- ✓ Waiting for a machine 1m21s
- ✓ Installing SSH server 14s
- ✓ Exporting notebook environment 0s
- ✓ Syncing workspace 0s
- ✓ Starting Cloudflare tunnel 4s
- ⠹ Restoring your files 9s
- 812/1505 files
- ○ Ready
+ ┌ alice · CPU only · 1h
+ │
+ ◇ Submitting 4s
+ ◇ Waiting for a machine 6s
+ ◇ Installing SSH server 21s
+ ◇ Exporting notebook environment 0s
+ ◇ Syncing workspace 0s
+ ◇ Starting Cloudflare tunnel 15s
+ ⠹ Restoring your files 1m12s usually 1m46s
+ │ 1704/2428 files
+ ○ Ready
+ │
+ └ 6/8 complete · 2m01s
```
+
+If several machines run `kdev up` at the same moment, they
+[converge on one box](#security-model).
+
+## Files and persistence
+
+
+
+
+
+Files across sessions. However a session ends, Kaggle keeps /kaggle/working as that version's output. The next kdev up, from any account or machine, restores it into the new box. A git remote and kdev backup are optional extra copies.
+
+
+`/kaggle/working` behaves like a disk that is always there.
+
+- **Kaggle saves it.** When a "Save & Run All" session ends, Kaggle keeps
+ `/kaggle/working` as that version's output, however the session ends. A
+ clean exit, a crash and a cancel were all measured to save every file up to
+ the moment the container stopped.
+- **kdev puts it back.** Kaggle starts every batch session with an empty
+ `/kaggle/working`; its "Persistence" setting only covers the web editor. So
+ each `kdev up` works out which saved version you left off at, and the new
+ box downloads it before you connect.
+- **kdev fills Kaggle's gaps.** Kaggle's saved output keeps every regular
+ file, but drops symlinks and empty directories and loses executable bits,
+ which would break a Python virtualenv. The box records those in
+ `.kdev/meta.json` every 30 seconds, and the restore puts them back.
+- **Extra copies, if you want them.** With `git-remote` set, the box clones
+ the repo at boot and pushes every 15 minutes and at teardown: the one copy
+ that survives a failure of Kaggle's own machine. `kdev backup` copies the
+ running box to this machine; `kdev restore --from-backup` pushes it back.
+
+Every way a session can end, and what the next start gives you, is listed in
+[Your files](/docs/files/).
+
+## Picking the version to restore
+
+
+
+
+
+How kdev up picks what to restore. It walks back past versions with no files. A version whose restore finished is restored alone; one that was cut short is stacked on the versions it was meant to be built on, so nothing done in it is lost.
+
+
+A version with no files is a source-only save (group setup, a Quick Save), so
+kdev walks past it. A session that was stopped before its restore finished,
+or that you worked in before restoring, is not skipped: it gets stacked on the
+versions it was meant to be built on. The layers underneath fill in only what
+that session's restore never delivered (the box logs each file as it lands, in
+`.kdev/fetched`), so a file you deleted there stays deleted.
+
+A restore never overwrites a file written in the current session, so it is
+safe to run again at any time:
+
+```bash
+kdev restore # finish or repeat the restore on the running box
+kdev restore --from v12 # add files v12 has that the box doesn't (not a rollback)
+kdev workspace files # what `kdev up` would restore (--version v12 for another)
+```
+
+## Several accounts, several machines
+
+
+
+
+
+One box, many accounts and machines. Every account in the group can start the shared notebook, on its own weekly quota. Every machine that has used the workspace has its key saved there, so it can reach every later box.
+
+
+- **Quota is per account.** A session is charged to the account that starts
+ it, not to the notebook's owner (measured).
+- **Switching is a question, not a wall.** If the active account can't finish
+ the session you asked for, `kdev up` shows every account's remaining hours
+ and lets you pick. `kdev account use ` switches by hand.
+- **The box is still running?** `kdev up` from any account or machine
+ connects to it instead of starting a second one.
+- **A new laptop.** `kdev setup` signs you in and joins the workspace. The
+ tunnel and git settings come from the notebook, and the new laptop's SSH key
+ is saved in the workspace (`.kdev/authorized_keys`).
+- **Stopping a box someone else started.** Kaggle only lets the account that
+ started a session cancel it. When the box doesn't answer, `kdev down` finds
+ out which account that was and cancels as it, or tells you which account
+ has to.
+
+More in [Several accounts, several machines](/docs/accounts/).
+
+## Security model
+
+
+
+
+
+Who can reach the box. Your SSH private key stays on your machine, and the box accepts public keys only. Only a box holding the workspace's tunnel credentials can answer on your hostname, and those credentials sit in the private notebook, where anyone with Can Edit can read them.
+
+
+- **Access** is public-key SSH only; password login is disabled. The box
+ accepts every key saved in the workspace's `.kdev/authorized_keys`: remove a
+ line there to revoke a machine.
+- **Secrets in the notebook.** Kaggle has no API for notebook Secrets, so the
+ tunnel credentials (and a git deploy key, if you set one) sit in the private
+ notebook's source. Anyone with Can Edit can read them. Scope a deploy key to
+ one repository.
+- **Host keys.** Every session is a new container with a new host key, so the
+ `kaggle` block in `~/.ssh/config` doesn't pin one; a pinned key would break
+ VS Code on every other machine. Only a box holding the workspace's tunnel
+ credentials can answer on that hostname, and anyone holding those can
+ already edit the notebook that builds the box.
+- **Simultaneous starts converge on one box.** If several machines run
+ `kdev up` together, the lowest live notebook version wins. Each losing
+ client stops its own run as the account that started it, waits for the
+ cancellation to finish, then connects to the winner. Startup verifies the
+ SSH session before restoring files, so cancelled contenders never replace
+ the winner's saved workspace; their output stays available through
+ `kdev restore --from vN`.
+- **On your machine,** settings live in `~/.config/kdev/config.json`
+ (mode 0600), and `kdev config` never shows secrets.
+
+Limits, Kaggle's terms and the rest are in
+[Security and limits](/docs/security/).
diff --git a/website/src/content/docs/index.md b/website/src/content/docs/index.md
index 576df6f..1a5f69d 100644
--- a/website/src/content/docs/index.md
+++ b/website/src/content/docs/index.md
@@ -5,7 +5,8 @@ group: Start
order: 1
---
-Needs Python 3.11+, `ssh`, and a Kaggle account in a Kaggle group.
+Needs Python 3.11+, `ssh`, and a Kaggle account in a Kaggle group. To see
+what kdev sets up before you run it, read [How it works](/docs/how-it-works/).
```bash
uv tool install kdev-cli # or: pipx install kdev-cli
diff --git a/website/src/data/site.ts b/website/src/data/site.ts
index 7a3cbb7..29ebc28 100644
--- a/website/src/data/site.ts
+++ b/website/src/data/site.ts
@@ -5,7 +5,7 @@ export const site = {
'kdev is a free, open-source CLI that turns a Kaggle notebook into a remote dev box: SSH or VS Code Remote-SSH into free T4, P100 or TPU machines, and get your files back on the next session, from any account or machine.',
repo: 'https://github.com/tushar-mahalya/kdev',
pypi: 'https://pypi.org/project/kdev-cli/',
- version: '0.1.4',
+ version: '0.2.0',
install: 'uv tool install kdev-cli',
};
diff --git a/website/src/lib/plain-markdown.ts b/website/src/lib/plain-markdown.ts
new file mode 100644
index 0000000..c758450
--- /dev/null
+++ b/website/src/lib/plain-markdown.ts
@@ -0,0 +1,22 @@
+// Docs pages may hold diagrams as inline HTML (). The
+// plain-text outputs (/docs/*.md and /llms-full.txt) carry each figure's
+// caption instead of its markup.
+const entities: Record = { '&': '&', '<': '<', '>': '>', '"': '"', ''': "'" };
+
+export function plainMarkdown(body: string): string {
+ return body.replace(/]*>[\s\S]*?<\/figure>/g, (figure) => {
+ const caption = /]*>([\s\S]*?)<\/figcaption>/.exec(figure)?.[1] ?? '';
+ let text = caption
+ .replace(/&(amp|lt|gt|quot|#39);/g, (e) => entities[e])
+ .replace(/([\s\S]*?)<\/code>/g, '`$1`')
+ .replace(/<\/?(b|strong)>/g, '**');
+ // Strip tags until none are left (a nested `ipt>` needs two
+ // passes), then drop any stray bracket, so no markup survives.
+ for (let previous = ''; previous !== text; ) {
+ previous = text;
+ text = text.replace(/<[^<>]*>/g, '');
+ }
+ text = text.replace(/[<>]/g, '').replace(/\s+/g, ' ').trim();
+ return text ? `> Diagram: ${text}` : '';
+ });
+}
diff --git a/website/src/pages/docs/[id].md.ts b/website/src/pages/docs/[id].md.ts
index c1c318e..c9efb24 100644
--- a/website/src/pages/docs/[id].md.ts
+++ b/website/src/pages/docs/[id].md.ts
@@ -1,5 +1,6 @@
import type { APIRoute, GetStaticPaths } from 'astro';
import { getCollection } from 'astro:content';
+import { plainMarkdown } from '../../lib/plain-markdown';
// Every docs page as plain Markdown, for people and language models that
// would rather read the source than the rendered page.
@@ -8,6 +9,6 @@ export const getStaticPaths: GetStaticPaths = async () =>
export const GET: APIRoute = ({ props }) => {
const { entry } = props as { entry: Awaited>>[number] };
- const body = `# ${entry.data.title}\n\n> ${entry.data.description}\n\n${entry.body ?? ''}`;
+ const body = `# ${entry.data.title}\n\n> ${entry.data.description}\n\n${plainMarkdown(entry.body ?? '')}`;
return new Response(body, { headers: { 'Content-Type': 'text/markdown; charset=utf-8' } });
};
diff --git a/website/src/pages/llms-full.txt.ts b/website/src/pages/llms-full.txt.ts
index e766de9..3076a81 100644
--- a/website/src/pages/llms-full.txt.ts
+++ b/website/src/pages/llms-full.txt.ts
@@ -1,9 +1,10 @@
import type { APIRoute } from 'astro';
import { getCollection } from 'astro:content';
import { site } from '../data/site';
+import { plainMarkdown } from '../lib/plain-markdown';
export const GET: APIRoute = async () => {
const docs = (await getCollection('docs')).sort((a, b) => a.data.order - b.data.order);
- const text = [`# kdev: full documentation\n\n> ${site.description}\n\nSource: ${site.repo}\n`, ...docs.map((d) => `\n---\n\n# ${d.data.title}\n\n> ${d.data.description}\n\n${d.body ?? ''}`)].join('\n');
+ const text = [`# kdev: full documentation\n\n> ${site.description}\n\nSource: ${site.repo}\n`, ...docs.map((d) => `\n---\n\n# ${d.data.title}\n\n> ${d.data.description}\n\n${plainMarkdown(d.body ?? '')}`)].join('\n');
return new Response(text, { headers: { 'Content-Type': 'text/plain; charset=utf-8' } });
};
diff --git a/website/src/styles/global.css b/website/src/styles/global.css
index c0e3f15..376ff99 100644
--- a/website/src/styles/global.css
+++ b/website/src/styles/global.css
@@ -287,3 +287,113 @@ code, kbd, pre { font-family: var(--font-mono); font-size: 0.92em; }
/* Brand wordmarks drawn in black (NVIDIA) turn white on a dark ground. */
:root[data-theme='dark'] .logo-ink { filter: brightness(0) invert(1); }
@media (prefers-color-scheme: dark) { :root:not([data-theme='light']) .logo-ink { filter: brightness(0) invert(1); } }
+
+/* ---------------------------------------------------------------- diagrams (docs)
+ Inline SVG and HTML figures inside docs Markdown. Every colour is a token,
+ so both themes follow; wide figures scroll sideways on small screens. */
+.prose > .fig { margin: 2em 0; }
+.fig { margin: 0; }
+.fig {
+ padding: clamp(14px, 2.4vw, 22px); border: 1px solid var(--line); border-radius: var(--radius);
+ background: var(--panel); box-shadow: var(--shadow);
+}
+.fig__art, .seq-wrap { overflow-x: auto; overscroll-behavior-x: contain; }
+.fig__art > svg { width: 100%; min-width: 600px; height: auto; }
+.fig figcaption {
+ margin-top: 16px; padding-top: 14px; border-top: 1px solid var(--line);
+ font-size: 14px; line-height: 1.6; color: var(--ink-3);
+}
+.fig figcaption b { color: var(--ink); font-weight: 600; }
+
+.fig .z { fill: color-mix(in srgb, var(--ink) 2.5%, transparent); stroke: var(--line-2); stroke-dasharray: 4 5; }
+.fig .zl { font-family: var(--font-pixel); font-size: 10px; letter-spacing: 0.08em; text-transform: uppercase; fill: var(--ink-3); }
+.fig .b { fill: var(--panel-2); stroke: var(--line-2); stroke-width: 1; }
+.fig .b--a { fill: color-mix(in srgb, var(--accent) 7%, var(--panel-2)); stroke: var(--accent); }
+.fig .b--ok { fill: color-mix(in srgb, var(--ok) 7%, var(--panel-2)); stroke: color-mix(in srgb, var(--ok) 70%, transparent); }
+.fig .b--warn { fill: color-mix(in srgb, var(--amber) 7%, var(--panel-2)); stroke: color-mix(in srgb, var(--amber) 70%, transparent); }
+.fig .b--ghost { fill: none; stroke-dasharray: 4 4; }
+.fig .b--back { opacity: 0.5; }
+.fig .cp { fill: color-mix(in srgb, var(--ink) 5%, transparent); stroke: var(--line); }
+.fig .cp--a { fill: var(--accent-soft); stroke: color-mix(in srgb, var(--accent) 45%, transparent); }
+.fig .lyr { fill: color-mix(in srgb, var(--ink) 6%, transparent); stroke: var(--line); }
+.fig .lyr--top { fill: color-mix(in srgb, var(--amber) 16%, transparent); stroke: color-mix(in srgb, var(--amber) 60%, transparent); }
+.fig .bar { fill: color-mix(in srgb, var(--ink) 9%, transparent); }
+.fig .bar__f { fill: var(--ok); }
+.fig .bar__f--warn { fill: var(--amber); }
+
+.fig .h { font-family: var(--font-sans); font-weight: 600; font-size: 15px; letter-spacing: -0.01em; fill: var(--ink); }
+.fig .h--s { font-size: 13.5px; }
+.fig .s { font-family: var(--font-mono); font-size: 11px; fill: var(--ink-3); }
+.fig .s--ink { fill: var(--ink-2); }
+.fig .c { font-family: var(--font-mono); font-size: 11px; fill: var(--ink-2); }
+.fig .r { font-family: var(--font-sans); font-size: 11px; fill: var(--ink-3); }
+.fig .l {
+ font-family: var(--font-mono); font-size: 11px; fill: var(--ink-2);
+ paint-order: stroke; stroke: var(--panel); stroke-width: 5px; stroke-linejoin: round;
+}
+.fig .l--a { fill: var(--accent-ink); }
+.fig .l--ok { fill: var(--ok); }
+.fig .l--warn { fill: var(--amber); }
+
+.fig .w { fill: none; stroke: var(--ink-3); stroke-width: 1.4; }
+.fig .w--a { stroke: var(--accent); }
+.fig .w--ok { stroke: var(--ok); }
+.fig .w--warn { stroke: var(--amber); }
+.fig .w--d { stroke-dasharray: 4 5; }
+.fig .ah { fill: var(--ink-3); }
+.fig .ah--a { fill: var(--accent); }
+.fig .ah--ok { fill: var(--ok); }
+.fig .ah--warn { fill: var(--amber); }
+
+/* sequence diagram: five lifelines on a grid, one message per row */
+.seq {
+ --c: var(--ink-3);
+ position: relative; display: grid; grid-template-columns: repeat(5, minmax(0, 1fr));
+ min-width: 620px; padding: 0 4px 4px; font-size: 13px; line-height: 1.35; color: var(--ink-2);
+}
+.seq::before {
+ content: ''; position: absolute; inset: 18px 0 0;
+ background-image:
+ repeating-linear-gradient(to bottom, var(--line-2) 0 4px, transparent 4px 9px),
+ repeating-linear-gradient(to bottom, var(--line-2) 0 4px, transparent 4px 9px),
+ repeating-linear-gradient(to bottom, var(--line-2) 0 4px, transparent 4px 9px),
+ repeating-linear-gradient(to bottom, var(--line-2) 0 4px, transparent 4px 9px),
+ repeating-linear-gradient(to bottom, var(--line-2) 0 4px, transparent 4px 9px);
+ background-size: 1px 100%; background-repeat: no-repeat;
+ background-position: 10% 0, 30% 0, 50% 0, 70% 0, 90% 0;
+}
+.seq > * { position: relative; z-index: 1; }
+.seq code { font-size: 0.92em; padding: 0.1em 0.35em; }
+.seq__p {
+ justify-self: center; margin-bottom: 12px; padding: 6px 12px; border-radius: 999px; white-space: nowrap;
+ border: 1px solid var(--line-2); background: var(--panel-2); color: var(--ink); font-weight: 600; font-size: 13.5px;
+}
+.seq__p--a { border-color: var(--accent); background: color-mix(in srgb, var(--accent) 8%, var(--panel-2)); }
+.seq__k {
+ display: inline-grid; place-items: center; min-width: 18px; height: 18px; padding: 0 4px; border-radius: 999px; flex: none;
+ background: var(--accent-soft); color: var(--accent-ink); font-family: var(--font-mono); font-size: 10.5px; font-weight: 600;
+}
+.seq__m {
+ display: flex; justify-content: center; align-items: center; gap: 6px;
+ margin-inline: calc(100% / (2 * var(--n, 2))); padding: 7px 0 13px;
+}
+.seq__m > span { white-space: nowrap; }
+.seq__m::before { content: ''; position: absolute; left: 0; right: 0; bottom: 5px; border-top: 1.5px solid var(--c); }
+.seq__m::after {
+ content: ''; position: absolute; right: -1px; bottom: 1px;
+ border-left: 9px solid var(--c); border-block: 4.5px solid transparent;
+}
+.seq__m--l::after { right: auto; left: -1px; border-left: 0; border-right: 9px solid var(--c); }
+.seq__m--d::before { border-top-style: dashed; }
+.seq__m--a { --c: var(--accent); }
+.seq__m--ok { --c: var(--ok); }
+.seq__n {
+ margin: 4px -46%; padding: 6px 10px; border-radius: 8px; text-align: center;
+ border: 1px solid var(--line-2); background: var(--panel-2); font-family: var(--font-mono); font-size: 11.5px; color: var(--ink-2);
+}
+.seq__n .seq__k { margin-right: 4px; vertical-align: 1px; }
+.seq__f { grid-column: 1 / -1; z-index: 0; margin: 2px -4px 0; border: 1px dashed var(--line-2); border-radius: 10px; pointer-events: none; }
+.seq__g { grid-column: 1 / -1; padding: 8px 10px 0; font-size: 12.5px; color: var(--ink-3); }
+.seq__g b { margin-right: 6px; font-family: var(--font-pixel); font-weight: 400; font-size: 10px; letter-spacing: 0.08em; text-transform: uppercase; color: var(--accent-ink); }
+.seq__g--else { margin: 6px 0 0; border-top: 1px dashed var(--line-2); }
+@media (max-width: 600px) { .fig { padding: 12px; } .fig figcaption { font-size: 13.5px; } }