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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 44 additions & 20 deletions docs/04_automation_and_utility.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
---
log:
2026-11-23: Added standalone version-gated update notices fetched from a movable GitHub tag (`notices_url`, defaulting to `https://raw.githubusercontent.com/googlecolab/google-colab-cli/refs/tags/notices/notices.json`) and cached as `update_notices` in `Settings`. Matching PEP 440 `affects` rules display via `announce_notices` independently of whether PyPI reports a newer version, HTTP 404 silently clears retracted notices without warning, transient errors preserve cached notices, and ANSI/control sequences are stripped.
2026-11-13: `_get_adc_credentials` in `auth.py` now catches `DefaultCredentialsError` from `google.auth.default()` so missing local ADC prints the 4-scope `gcloud auth application-default login` command and exits 1 instead of surfacing `google-auth`'s stock unscoped setup message. Updated scope documentation to clarify that both `colaboratory` and `userinfo.email` are required by `colab.research.google.com`.
2026-11-07: Optimized `_get_adc_credentials` in `auth.py` to stub `google.auth._cloud_sdk.get_project_id` around `google.auth.default()`. When ADC user credentials lack a `quota_project_id`, `google-auth` otherwise spawns `gcloud config get-value project` on every CLI invocation to resolve a `project_id` that `_get_adc_credentials` immediately discards (`_`).
2026-11-04: `colab drivemount` now opens the Drive consent URL in the system browser (`utils.open_url_in_browser`, also used by `colab pay`/`colab url --open`) instead of only printing it. The URL is still printed first, and a missing browser opener (SSH, containers, CI) is treated as normal: the flow keeps waiting for the user exactly as before. The prompt moved into `commands/automation.py::show_drive_auth_url` so it can be unit-tested.
Expand Down Expand Up @@ -194,44 +195,67 @@ How each provider supplies the scopes:
Git commit hash using `git rev-parse --short HEAD`.
- Dynamic versioning is supported in the build system via `hatch-vcs`.

### 8. Auto-Update (`colab update`)
### 8. Auto-Update & Standalone Notices (`colab update`)

- **Action**: Check if a new version of the Colab CLI is available.
- **Auto-check**: The CLI automatically checks for updates once every 24 hours
during the execution of any command. Independently, the cached
`latest_version` (see below) is consulted on **every** invocation so the
upgrade banner remains visible between fetches without requiring a network
- **Action**: Check if a new version of the Colab CLI or any standalone
version-gated advisory notice is available.
- **Auto-check**: The CLI automatically fetches PyPI and the standalone
notices feed once every 24 hours during the execution of any non-suppressed
command. Independently, the cached `latest_version` and `update_notices`
are consulted on **every** invocation so upgrade and standalone notice
banners remain visible between fetches without requiring a network
round-trip.
- **Suppressed subcommands**: To keep machine-parseable output clean, the
daily fetch and the cached banner are suppressed for `update` (which
runs its own check), `version`, `log`, `pay`, `url`, `help`, and
`whoami`. The list lives as `_AUTO_UPDATE_SUPPRESSED` in the global
Typer callback in `cli.py`.
- **Manual-check**: `colab update` forces a check and prints the status.
daily fetch and the cached banners are suppressed for subcommands listed in
`_AUTO_UPDATE_SUPPRESSED` (and non-TTY `ssh`) in the global Typer callback
in `cli.py`.
- **Manual-check**: `colab update` forces a check and prints the status plus
any matching standalone notices.
- **Implementation**:
- Fetches a PyPI-style JSON document from a configurable `update_url`
- Fetches a PyPI-style JSON document from `update_url`
(default: `https://pypi.org/pypi/google-colab-cli/json`) and reads
`info.version`.
- Compares the fetched version with the current CLI version using
PEP 440 / semantic versioning, falling back to string equality when a
version is unparseable.
- Independently fetches standalone notices from `notices_url` (default:
`https://raw.githubusercontent.com/googlecolab/google-colab-cli/refs/tags/notices/notices.json`;
managed via `tools/notices.py`, see [07_update_notices.md](07_update_notices.md)).
- Notice payload schema: a JSON array `[{"affects": "<1.0.0", "message": "..."}]`
(or `{"notices": [...]}`). Each entry's `affects` is evaluated against
the installed version with `packaging.specifiers.SpecifierSet(..., prereleases=True)`.
ANSI escape codes and control characters are stripped, messages are
truncated to 500 characters, and at most 3 deduplicated notices are
printed.
- Persists the following fields in `~/.config/colab-cli/settings.json`:
- `update_url`: source configuration.
- `update_url`: PyPI JSON source configuration.
- `notices_url`: standalone notices JSON source configuration.
- `last_check`: timestamp of the last fetch (drives the daily
throttle).
- `enable_update_check`: master switch for both the daily fetch and
the cached banner.
cached upgrade/notice banners.
- `latest_version`: highest version observed during the most
recent successful check. Updated whenever a strictly-newer
version is observed (never downgraded), and preserved verbatim
across failed checks so transient network issues do not erase
the cache.
- **Notification**: If a new version is found, a non-intrusive message is
printed to the console with a `Run 'pip install --upgrade google-colab-cli' to
update.` hint. On Linux and macOS platforms where `--install` self-update is supported,
an additional hint `You can run 'colab update --install' to upgrade in place.`
is displayed above the pip/uv install command. The cached banner shown between
fetches uses the generic `Run 'colab update' to update.` hint.
- `update_notices`: list of `{affects, message}` entries from the
most recent successful notices fetch. Overwritten on HTTP 200 or
cleared to `[]` on HTTP 404 (absent/deleted `notices` tag, with no
warning printed), and preserved across transient network failures.
`affects` is re-evaluated on every invocation so cached notices
stop appearing immediately once the user upgrades past the range.
- **Notification**:
- If a new version is found, a non-intrusive banner is printed with a
`Run 'pip install --upgrade google-colab-cli' to update.` (or `uv tool
install -U`) hint, plus `You can run 'colab update --install' to upgrade
in place.` on Linux and macOS. Cached banners between fetches use the
generic `Run 'colab update' to update.` hint.
- Any matching standalone notices are printed via `announce_notices` as
`[colab] Notice: <message>`, **even when the CLI is already on the
latest PyPI version**. When both an upgrade banner and notices are
shown unsolicited, the `"enable_update_check": false` silence hint is
printed only once at the bottom.
- **Self-install (`--install`)**: An opt-in `--install` flag (default
`False`) makes `colab update` upgrade the CLI in place (**Linux and macOS**).
It detects how the CLI was installed:
Expand Down
169 changes: 169 additions & 0 deletions docs/07_update_notices.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
---
log:
2026-11-23: Initial design and maintainer workflow documentation for standalone version-gated update notices (`refs/tags/notices` on GitHub CDN) and the `tools/notices.py` management script.
---

# Design & Operations: Standalone Update Notices (`refs/tags/notices`)

## Motivation

`colab update` and the daily background update check notify users when a newer
version is published on PyPI, but PyPI release metadata is immutable once
published. Maintainers need a lightweight way to surface targeted messages to
existing installations **in the future without cutting a new PyPI release** —
for example:

- Breaking CLI migrations (e.g., "`colab console` was removed; use `colab ssh`
instead").
- Retroactive security advisories affecting older versions (e.g., `<0.8.0`).
- Upcoming Colab backend or authentication changes that affect **all** current
releases (`<=X.Y.Z`), even when no newer PyPI version exists yet.

## Architecture

1. **Movable Git Tag (`refs/tags/notices`)**:
- Active notices live in a single root file `notices.json` under the tag `refs/tags/notices`.
- Avoids triggering a release build from `cloudbuild.yaml` which triggers on `refs/tags/v*`
2. **CDN Delivery (`raw.githubusercontent.com`)**:
- Clients fetch `settings.notices_url`, which defaults to:
`https://raw.githubusercontent.com/googlecolab/google-colab-cli/refs/tags/notices/notices.json`
- Served by GitHub's Fastly CDN (`Cache-Control: max-age=300`, ~5-minute propagation window)
with no authentication required
3. **Standalone Evaluation**:
- Notices are evaluated and displayed via `announce_notices` **independently**
of whether PyPI reports a newer version (`latest > current`). A user
already on the latest PyPI version still sees any notice whose `affects`
specifier matches their installed version.

## Payload Schema

`notices.json` at the root of `refs/tags/notices` is a UTF-8 JSON array (or an
object `{"notices": [...]}`) of rule objects:

```json
[
{
"affects": "<0.8.0",
"message": "Versions <0.8.0 logged credentials to ~/.config/colab-cli/colab.log; upgrade and delete old logs."
},
{
"affects": "<0.9.0",
"message": "colab console was removed; use colab ssh instead."
}
]
```

| Field | Type | Rules |
|---|---|---|
| `affects` | `str` | Non-empty PEP 440 version specifier parsed with `packaging.specifiers.SpecifierSet(..., prereleases=True)`. Examples: `<0.9.0`, `<=0.8.0`, `>=0.7.0,<0.8.0`, `==0.8.2`, `>=0.0.0`. |
| `message` | `str` | Plain-text notice (`<= 500` characters). Clients strip ANSI escape sequences and control characters, deduplicate identical messages, and display at most `3` matching notices. |

Unknown JSON fields are ignored so future schema additions remain backward
compatible with older CLI installations.

## Maintainer Workflow (`tools/notices.py`)

`tools/notices.py` manages `refs/tags/notices` using low-level Git plumbing
(`git hash-object`, `git mktree`, `git commit-tree`, `git tag -fa`). It **never**
checks out branches or modifies your `HEAD`, staging area, or working directory,
and it chains each update onto the previous `refs/tags/notices` commit so
`git log notices` preserves a linear audit history.

By default, commands update only your local `refs/tags/notices` tag so you can
inspect and preview first; pass `--push` to publish immediately to `origin`.

### 1. List Active Notices & Preview Client Output

```bash
# Fetch refs/tags/notices from origin and display active JSON rules:
./tools/notices.py list

# Preview the exact banner a user on version 0.8.0 will see:
./tools/notices.py list --version 0.8.0
```

### 2. Add a Notice

```bash
# Stage locally first, then preview:
./tools/notices.py add \
--affects "<0.9.0" \
--message "colab console was removed; use colab ssh instead."
./tools/notices.py list --no-fetch --version 0.8.5

# Or validate, commit to refs/tags/notices, and push in one step:
./tools/notices.py add \
--affects "<0.9.0" \
--message "colab console was removed; use colab ssh instead." \
--push
```

`tools/notices.py` rejects empty/invalid PEP 440 specifiers, messages containing
ANSI/control characters, and messages over 500 characters before creating the
tag.

### 3. Replace the Full Notice List from a File

When editing or reordering multiple notices at once:

```bash
./tools/notices.py set path/to/notices.json --push
```

(Pass `-` instead of a file path to read JSON from `stdin`.)

### 4. Clear / Retract Notices

There are two equivalent ways to retract all notices:

```bash
# Option 1 (recommended): publish an empty [] list, keeping git log history on refs/tags/notices
./tools/notices.py clear --push

# Option 2: delete refs/tags/notices from origin (HTTP 404 also clears client caches)
./tools/notices.py clear --delete-tag --push
```

## Client Behavior & Caching

- **Schedule**: Fetched once every 24 hours alongside PyPI during non-suppressed
commands (`run_background_check`) and unconditionally on `colab update`.
- **Persistence**: Cached as `update_notices` in `~/.config/colab-cli/settings.json`.
- **HTTP 200**: Replaces `update_notices` with the newly fetched list.
- **HTTP 404**: Silently sets `update_notices = []` with **no** warning even on
explicit `colab update` (both before the `notices` tag is ever created and
after tag deletion).
- **Network / 5xx Error**: Preserves the previously cached `update_notices`.
- **Post-Upgrade Suppression**: `maybe_show_cached_banner` re-evaluates
`affects` against `get_app_version()` on every run, so once a user upgrades
past the affected range, cached notices stop displaying immediately without
waiting for the next 24-hour fetch.
- **Banner Formatting**:
```text
[colab] Notice: colab console was removed; use colab ssh instead.
[colab] To silence this check, set "enable_update_check": false in ~/.config/colab-cli/settings.json
```
- Explicit `colab update` omits the `"To silence this check..."` line.
- When both an upgrade banner and standalone notices match on an unsolicited
check, the silence hint appears only once at the bottom.
- Setting `"enable_update_check": false` in `~/.config/colab-cli/settings.json`
disables both the PyPI check and standalone notices.
- Pipeable and machine-parsed subcommands in `_AUTO_UPDATE_SUPPRESSED` (and
non-TTY `ssh`) in `cli.py` never print notices.

## Testing Strategy

- **Runtime Unit Tests (`tests/test_update.py`, `tests/test_state.py`)**:
Standalone notice display when up to date (explicit, background, and cached),
combined upgrade + notice rendering without duplicate silence hints, PEP 440
range filtering across skipped versions, immediate cache suppression after
upgrade, silent HTTP 404 clearing, transient error cache preservation, ANSI
and length sanitization, and `enable_update_check=False` suppression.
- **Tool Unit Tests (`tests/test_notices_tool.py`)**:
Verifies `list`, `list --version`, `add`, `set`, `clear`, and
`clear --delete-tag` against temporary bare `origin` + multi-clone Git
repositories, ensuring `HEAD` and dirty working-tree files remain untouched
and force-moved tag history chains cleanly across clones.
- **End-to-End Integration Test (`integration/repro_update_notices/test.sh`)**:
Verifies live PyPI + live GitHub CDN 404 handling, local HTTP notice serving,
offline throttled cache playback, suppressed subcommands, and 404 retraction.
1 change: 1 addition & 0 deletions integration/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ End-to-end tests that run against a **live Colab backend** (unlike the mocked un
| `repro_variable_persistence/` | Variables persist across `colab exec` calls in the same session. |
| `repro_bundled_oauth/` | Fast smoke test (~5s): verifies that the fallback OAuth configuration is loaded and starts the OAuth flow with the default client ID when local config is missing. |
| `repro_legacy_token_migration/` | Fast smoke test (~5s, no VM): a pre-keyring `~/.config/colab-cli/token.json` is migrated into the keyring and deleted, deleted when the keyring already has a token, and kept (with a stderr warning) when the keyring is inaccessible. Uses a throwaway HOME and file-backed test keyring. |
| `repro_update_notices/` | Fast smoke test (~5s, no VM): verifies live PyPI + default GitHub `notices` tag 404 handling, standalone notice display when already up to date, throttled cache playback, suppression on pipeable commands, and 404 notice retraction in an isolated HOME. |
| `repro_ssh/` | Fast smoke test (~5s): `--help` advertises the flags and an unknown session exits. Slow soak test (~95s): Live e2e allocates a CPU VM, runs a real remote command over `colab ssh --proxy-mode` |
| `repro_windows_ssh/` | Native Windows live CPU test: Windows OpenSSH launches the generated ProxyCommand, executes a remote marker command, and releases the recorded runtime. Requires OAuth2 credentials cached in the OS keyring; exits 77 if prerequisites are missing. |

Expand Down
Loading