From 93c5140fcd6491d7b356715796847b1ca73d61a6 Mon Sep 17 00:00:00 2001 From: Tyler Potts <49161327+tylerpotts@users.noreply.github.com> Date: Wed, 19 Aug 2026 15:37:41 -0500 Subject: [PATCH 01/24] docs: design spec for interaction-based VS Code idle culling Design for https://github.com/nebari-dev/data-science-pack/issues/208: stop counting VS Code proxy keepalives as jupyter activity, report real user interaction via a server-side code-server extension, and wire CODE_SERVER_IDLE_TIMEOUT_SECONDS to the idle culler timeout. --- .../2026-08-19-vscode-idle-culling-design.md | 227 ++++++++++++++++++ 1 file changed, 227 insertions(+) create mode 100644 docs/superpowers/specs/2026-08-19-vscode-idle-culling-design.md diff --git a/docs/superpowers/specs/2026-08-19-vscode-idle-culling-design.md b/docs/superpowers/specs/2026-08-19-vscode-idle-culling-design.md new file mode 100644 index 00000000..b7488eef --- /dev/null +++ b/docs/superpowers/specs/2026-08-19-vscode-idle-culling-design.md @@ -0,0 +1,227 @@ +# Interaction-based idle culling for VS Code (code-server) + +**Issue:** https://github.com/nebari-dev/data-science-pack/issues/208 + +## Problem + +A user pod running VS Code (code-server, proxied by jupyter-server-proxy) is +never idle-culled while a browser tab stays connected, no matter how long the +user has been away. This keeps expensive pods alive indefinitely. + +### Root cause (verified against source) + +The issue's framing — "the heartbeat function artificially creates network +activity on JHub" — is slightly off. The code-server heartbeat is a local file +touch, not network traffic. The actual mechanism: + +1. An open VS Code tab holds a persistent websocket to code-server. The VS + Code client sends protocol keepalives over it regardless of user + interaction. +2. That traffic flows through jupyter-server-proxy, whose handlers set + `settings["api_last_activity"] = utcnow()` on every proxied request and + websocket message (`jupyter_server_proxy/handlers.py`, gated by the + `update_last_activity` option, default `True`). +3. jupyter-server's `last_activity` therefore never goes stale, so neither the + in-pod `shutdown_no_activity_timeout` (900s) nor the hub-level + jupyterhub-idle-culler (`cull.timeout: 1800`) ever fires. + +The fix proposed in the issue (`CODE_SERVER_IDLE_TIMEOUT_SECONDS`) does not +cover the main case: code-server's idle timer only starts when the heartbeat +expires, and the heartbeat's `isActive()` check is literally +`server.getConnections() > 0` (`src/node/routes/index.ts`). An open tab — +foreground or background — keeps a connection, so the timeout never fires +while a tab is connected. It only helps once every connection is gone (tab +closed, browser quit, laptop asleep, tab discarded by the browser's memory +saver). Additionally, the feature does not exist in the code-server version +this repo pins (4.104.3): it landed in 4.106.0 via +https://github.com/coder/code-server/pull/7539, and code-server refuses to +start when the value is ≤ 60. + +## Desired behavior + +VS Code users get the same idle semantics as notebook users: + +- Real interaction (typing, scrolling, terminal use, focus changes) keeps the + pod alive. +- Running work keeps the pod alive: a terminal command still executing counts + as active, mirroring the kernel culler's `cullBusy: false`. (Decision made + during design review.) +- An open-but-idle tab does **not** keep the pod alive; the existing cullers + fire on their normal schedule. + +## Design + +Two complementary mechanisms (decision made during design review: ship both). +The extension handles connected-but-idle tabs; the idle-timeout env var makes +lingering code-server processes exit after all connections drop, closing issue +208 as written. + +### 1. Stop counting raw VS Code proxy traffic as activity + +Remove the `jupyter-vscode-proxy` git dependency from +`images/jupyterlab/pixi.toml` and register the `vscode` server directly in +`jupyter_server_config.py` (the chart-owned singleuser ConfigMap, +`templates/singleuser-config.yaml`) via `c.ServerProxy.servers`. The entry +reproduces what `jupyter_vscode_proxy` generates — `code-server --auth none +--disable-telemetry`, port templating, `CODE_WORKINGDIR` / +`CODE_EXTENSIONSDIR` env handling, launcher entry — plus the one thing the +packaged entry point cannot express: `update_last_activity: False`. + +Why removal rather than override: jupyter-server-proxy concatenates +`c.ServerProxy.servers` with entry-point-registered servers +(`jupyter_server_proxy/__init__.py::_load_jupyter_server_extension`), so a +same-named config entry would double-register route handlers. Removing the +package is the unambiguous path. The launcher icon SVG currently ships inside +that package, so it gets baked into the image instead. + +With `update_last_activity: False`, an idle tab's keepalives no longer touch +`api_last_activity`, and the existing cullers govern VS Code pods exactly as +they do notebook pods: + +- in-pod: kernels/terminals cull at 900s idle; the server exits 900s after the + last kernel/terminal if no API activity (`singleuserCuller` values). +- hub: `jupyterhub.cull.timeout: 1800` culls on hub-side staleness. + +### 2. Activity-reporter extension + +New artifact: `nebari-activity-reporter`, a plain-JavaScript VS Code extension +in `images/vscode-activity-reporter/`. It runs in code-server's server-side +extension host inside the pod (so it sees the pod environment) and reports +*genuine* user activity to jupyter-server, which then propagates to the hub +through the normal singleuser activity-notification path. + +**Events subscribed:** + +- `workspace.onDidChangeTextDocument` (edits) +- `window.onDidChangeTextEditorSelection` and + `onDidChangeTextEditorVisibleRanges` (cursor movement, scrolling) +- `window.onDidChangeWindowState` (focus changes) +- `window.onDidOpenTerminal` / `onDidCloseTerminal` +- `window.onDidStartTerminalShellExecution` / + `onDidEndTerminalShellExecution` (stable API since VS Code 1.93) + +**Busy tracking:** while any shell execution is in flight (start event seen, +no matching end), the extension counts the pod as active and keeps reporting +each interval even with no interaction. Documented limitation: this relies on +VS Code shell integration, which code-server auto-injects for bash/zsh; +long-running jobs in shells without integration are not detected. + +**Reporting:** throttled to at most one request per 60s. On activity, the +extension makes one authenticated request to the local jupyter server: + +- URL base from `JUPYTERHUB_SERVICE_URL` (present in every singleuser pod). +- `Authorization: token $JUPYTERHUB_API_TOKEN`. +- Endpoint must count toward activity tracking. Verified upstream: handlers + with `_track_activity = False` (`/api/status`, `/api/`) are excluded; + every other authenticated `APIHandler` request updates `api_last_activity` + in `finish()` (`jupyter_server/base/handlers.py`). Use + `GET {base}/api/contents/?content=0` (cheap, tracked). + +**Robustness:** activation on `onStartupFinished`; all failures logged and +retried with backoff; the extension must never throw out of its handlers. It +logs one line on activation so a live deploy can confirm it is running. + +### 3. Extension delivery + +- Image build packages the extension to a `.vsix` with `@vscode/vsce` and + bakes the file into the image (e.g. `/opt/code-server/extensions/`). +- Installation happens in a **postStart lifecycle hook** merged into the + existing hook composition in `config/jupyterhub/01-spawner.py` (the + nss-wrapper hook already merges into `spawner.lifecycle_hooks`; this change + refactors that merge so multiple postStart contributors compose instead of + overwrite). +- Why postStart instead of build-time install: the default code-server + extensions dir lives under the user's home PVC, which mounts over anything + installed there at build time. postStart `code-server --install-extension + ` is idempotent, re-runs on image upgrades (vsix version bumps), and + preserves the user's ability to install their own extensions. + +### 4. Issue 208 mechanism: code-server idle timeout + +- Bump `CODE_SERVER_VERSION` to 4.133.0 in + `images/scripts/install-code-server.sh` (update the pinned `install.sh` + sha256 and the version comment). +- In `config/jupyterhub/01-spawner.py`, set + `CODE_SERVER_IDLE_TIMEOUT_SECONDS = str(cull.timeout)` in the KubeSpawner + environment, sourced from z2jh's `get_config("cull.timeout")`. Skip when + culling is disabled or the timeout is ≤ 60 (code-server rejects ≤ 60 at + startup). No new values knob: the value derives from the idle-culler + setting, per the issue. + +### 5. Escape hatch + +One new values flag: + +```yaml +vscodeActivity: + enabled: true +``` + +`false` renders the vscode server entry with `update_last_activity: True` — +the pre-change behavior — as field insurance if the extension misbehaves. The +extension itself always ships and runs; its pings are harmless either way. + +### 6. Failure modes + +- **Extension silently broken** (packaging bug, API change): active VS Code + users are culled after `cull.timeout` (30 min default). This is the worst + failure mode — worse than today's overspending — and is mitigated by the + escape hatch, activation logging, and the e2e test below, which fails CI if + typing stops advancing `last_activity`. +- **No shell integration** for a long-running terminal job: not detected as + busy (documented limitation; bash/zsh get integration automatically). +- Token lifetime: `JUPYTERHUB_API_TOKEN` is stable for the pod's life; no + rotation handling needed. + +### 7. Testing + +- **Unit (pytest, existing patterns in `tests/unit/`):** + - `CODE_SERVER_IDLE_TIMEOUT_SECONDS` wiring: set from `cull.timeout`; + absent when culling disabled or timeout ≤ 60. + - singleuser ConfigMap rendering: vscode server entry present with + `update_last_activity` False/True per `vscodeActivity.enabled`. + - postStart hook composition: nss-wrapper and extension-install both + present after the merge refactor. +- **E2E (playwright, existing `tests/e2e/`):** open `/vscode` through the + hub; assert jupyter `last_activity` advances while synthesizing typing; + assert it does **not** advance over a few minutes with the tab open and + idle. +- **Manual soak** on a live deploy with shortened timeouts before merge. + +### 8. Documentation + +`docs/src/content/docs/configuration.md` (and README where relevant) gain an +idle-culling section: how VS Code idleness now behaves, the +`vscodeActivity.enabled` escape hatch, the shell-integration caveat, the +code-server idle timeout's derivation from `cull.timeout`, and +`jupyterhub.cull.maxAge` as an optional hard cost cap for always-connected +tabs. + +## Decisions log + +- **Ship both mechanisms** (extension + `CODE_SERVER_IDLE_TIMEOUT_SECONDS`): + user decision, 2026-08-19. +- **Busy terminal counts as active** (mirrors `cullBusy: false`): user + decision, 2026-08-19. +- **Rejected: `update_last_activity: False` alone** — would cull actively + working VS Code users; dealbreaker. +- **Rejected as primary fix: `cull.maxAge`** — blunt hard cap that kills + active users; documented as an optional backstop only. + +## Verified upstream facts + +- code-server idle timeout: added in + https://github.com/coder/code-server/pull/7539 (first release 4.106.0); + env var `CODE_SERVER_IDLE_TIMEOUT_SECONDS`; startup error when ≤ 60; timer + runs only while heartbeat state is `expired`; heartbeat `isActive()` is + `getConnections() > 0` (`src/node/{main,heart}.ts`, + `src/node/routes/index.ts`). +- jupyter-server-proxy: per-server `update_last_activity` trait (default + `True`) controls whether proxied traffic sets `api_last_activity` + (`jupyter_server_proxy/{config,handlers}.py`); entry-point servers are + appended to config servers, so same-name overrides double-register. +- jupyter_server: `APIHandler.finish()` updates `api_last_activity` for + authenticated requests unless the handler sets `_track_activity = False` + (`/api/status` and `/api/` do; contents API does not) + (`jupyter_server/base/handlers.py`, + `jupyter_server/services/api/handlers.py`). From ac3ff5a069e45d8a0c2fd06fb261e193f052f5b5 Mon Sep 17 00:00:00 2001 From: Tyler Potts <49161327+tylerpotts@users.noreply.github.com> Date: Wed, 19 Aug 2026 15:52:37 -0500 Subject: [PATCH 02/24] docs: implementation plan for VS Code idle culling Also records pre-implementation corrections in the spec: registration moves to the image-owned jupyter_server_config.py, vsix packaging uses a stdlib script instead of vsce, and e2e adapts to the kind/HTTP harness. --- .../plans/2026-08-19-vscode-idle-culling.md | 1201 +++++++++++++++++ .../2026-08-19-vscode-idle-culling-design.md | 26 + 2 files changed, 1227 insertions(+) create mode 100644 docs/superpowers/plans/2026-08-19-vscode-idle-culling.md diff --git a/docs/superpowers/plans/2026-08-19-vscode-idle-culling.md b/docs/superpowers/plans/2026-08-19-vscode-idle-culling.md new file mode 100644 index 00000000..4c0330b8 --- /dev/null +++ b/docs/superpowers/plans/2026-08-19-vscode-idle-culling.md @@ -0,0 +1,1201 @@ +# VS Code Interaction-Based Idle Culling Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Make VS Code (code-server) user pods idle-cull with the same semantics as notebook pods: real interaction or running work keeps the pod alive; an open-but-idle browser tab does not. Closes https://github.com/nebari-dev/data-science-pack/issues/208. + +**Architecture:** Two composing mechanisms. (1) The `vscode` jupyter-server-proxy entry is re-registered by this repo (replacing the `jupyter-vscode-proxy` package) with `update_last_activity: False`, so VS Code keepalive traffic stops feeding jupyter's `api_last_activity`; a bundled server-side VS Code extension (`nebari-activity-reporter`) reports *real* user interaction to the local jupyter API instead. (2) `CODE_SERVER_IDLE_TIMEOUT_SECONDS` (new in code-server 4.106.0; we bump to 4.133.0) is derived from the hub culler's `cull.timeout` so lingering code-server processes exit after all browser connections drop. + +**Tech Stack:** Helm chart + z2jh JupyterHub config (Python, exec'd config files), jupyter-server-proxy 4.5.0, code-server 4.133.0, plain-JavaScript VS Code extension (stable API only, no build step), stdlib-Python `.vsix` packager, pytest unit tests, kind-based e2e harness. + +**Spec:** `docs/superpowers/specs/2026-08-19-vscode-idle-culling-design.md` — read it first, especially the "Pre-implementation corrections" block. + +## Global Constraints + +- code-server rejects `--idle-timeout-seconds` ≤ 60 at startup: never set `CODE_SERVER_IDLE_TIMEOUT_SECONDS` unless the value is **> 60** and culling is enabled. +- `jupyter_server` handlers with `_track_activity = False` (`/api/status`, `/api/`) do NOT count as activity. The extension must ping `GET {service}/api/contents/?content=0` (tracked). +- The image config file `images/nebi/jupyter_server_config.py` owns `c.ServerProxy.servers` as a dict **assignment** and loads after the chart ConfigMap — the vscode entry must live there, not in the ConfigMap. +- postStart hook commands are joined with `" && "` in `_setup_nss_wrapper`; the extension install must be wrapped `{ ... || true; }` so its failure can't CrashLoop the pod and can't mask earlier commands' failures. +- Extension uses **stable** VS Code APIs only (`engines.vscode: ^1.93.0`; no `onDidWriteTerminalData`, which is proposed-API). +- Extension names: package `name: nebari-activity-reporter`, `publisher: nebari`, version `0.1.0`. Installed extension dir will be `nebari.nebari-activity-reporter-0.1.0`. Baked vsix path (version-independent): `/opt/code-server-extensions/nebari-activity-reporter.vsix`. +- Env var names (exact): `CODE_SERVER_IDLE_TIMEOUT_SECONDS`, `VSCODE_PROXY_UPDATE_LAST_ACTIVITY`. Chart-derived key (exact): `vscode-activity-enabled`. Values key (exact): `vscodeActivity.enabled`. +- Unit test environment (matches CI `.github/workflows/test.yaml`): + + ```bash + uv venv .venv-unit --python 3.10 + uv pip install --python .venv-unit/bin/python \ + jupyterhub==5.5.0 oauthenticator==17.4.0 jupyterhub-kubespawner==7.0.0 pytest + .venv-unit/bin/python -m pytest tests/unit -v + ``` + + `helm` must be on PATH for `tests/unit/test_chart_derived.py`-style tests (they skip otherwise — a skip is NOT a pass for the tasks below that add helm-rendering tests; install helm). +- Commit style: repo uses conventional commits (`feat:`, `test:`, `docs:`, `refactor:`). Do not add co-authors or "Generated by" lines. + +--- + +### Task 1: Bump code-server to 4.133.0 + +The idle-timeout flag landed in code-server 4.106.0 (coder/code-server PR 7539); the repo pins 4.104.3. `install.sh` is byte-identical between v4.104.3 and v4.133.0 (sha256 `e86784e9fec81106c74941e55dbbcb85dc963a06ad6c3f1a870d4a22cf432e1d`, verified 2026-08-19), so only the version string and URL tag change. + +**Files:** +- Modify: `images/scripts/install-code-server.sh` + +**Interfaces:** +- Produces: a singleuser image whose `code-server` honors `CODE_SERVER_IDLE_TIMEOUT_SECONDS` (consumed by Task 2's env var and Task 10's e2e). + +- [ ] **Step 1: Edit the version pin and URL** + +In `images/scripts/install-code-server.sh` change line 8 and line 14 (the sha256 on line 15 stays): + +```bash +CODE_SERVER_VERSION=4.133.0 +``` + +```bash +# Fetch the snapshot of https://code-server.dev/install.sh as of the time of writing +wget --quiet https://raw.githubusercontent.com/coder/code-server/v4.133.0/install.sh +``` + +- [ ] **Step 2: Verify the hash claim locally** + +Run: +```bash +curl -sL https://raw.githubusercontent.com/coder/code-server/v4.133.0/install.sh | shasum -a 256 +``` +Expected output: `e86784e9fec81106c74941e55dbbcb85dc963a06ad6c3f1a870d4a22cf432e1d -` (matches the `expected_sum` already in the script). + +- [ ] **Step 3: Commit** + +```bash +git add images/scripts/install-code-server.sh +git commit -m "feat: bump code-server to 4.133.0 for idle-timeout support" +``` + +--- + +### Task 2: Spawner sets CODE_SERVER_IDLE_TIMEOUT_SECONDS from cull.timeout + +**Files:** +- Modify: `config/jupyterhub/01-spawner.py` (env section, after the `NEBI_SERVER_ALLOWED_ORIGINS` block ~line 318, before `c.KubeSpawner.environment = env`) +- Test: `tests/unit/test_spawner_code_server_idle.py` (create) + +**Interfaces:** +- Consumes: `get_config` (z2jh) — `cull.enabled` / `cull.timeout` from the jupyterhub subchart values (`values.yaml` sets `enabled: true`, `timeout: 1800`). +- Produces: pod env `CODE_SERVER_IDLE_TIMEOUT_SECONDS` (string), read by code-server ≥ 4.106 (Task 1); asserted by Task 10 e2e. + +- [ ] **Step 1: Write the failing tests** + +Create `tests/unit/test_spawner_code_server_idle.py`: + +```python +"""CODE_SERVER_IDLE_TIMEOUT_SECONDS wiring in `01-spawner.py`. + +code-server >= 4.106 exits N seconds after its last browser connection +closes when this env var is set. It must mirror the hub idle culler's +`cull.timeout` (issue #208) — and must be ABSENT when culling is disabled +or the timeout is <= 60, because code-server refuses to start for values +<= 60 and that would take down every user pod's VS Code. +""" + +from __future__ import annotations + +import importlib.util +import sys +import types + +# 01-spawner.py imports `z2jh.get_config`; stub it so the module exec's standalone. +_z2jh = types.ModuleType("z2jh") +_z2jh.get_config = lambda key, default=None: default +sys.modules.setdefault("z2jh", _z2jh) + +from conftest import CONFIG_DIR, FakeConfig # noqa: E402 + + +def _load_spawner(c: FakeConfig, z2jh_values: dict | None = None, + chart_values: dict | None = None): + """Exec raw 01-spawner.py with per-test z2jh + chart config stubs.""" + z2jh_values = z2jh_values or {} + chart_values = chart_values or {} + z2jh = sys.modules["z2jh"] + orig = z2jh.get_config + z2jh.get_config = lambda key, default=None: z2jh_values.get(key, default) + try: + path = CONFIG_DIR / "01-spawner.py" + spec = importlib.util.spec_from_file_location("_spawner_idle", path) + module = importlib.util.module_from_spec(spec) + module.__dict__["c"] = c + module.__dict__["get_chart_config"] = ( + lambda key, default="": chart_values.get(key, default) + ) + spec.loader.exec_module(module) + finally: + z2jh.get_config = orig + + +def test_idle_timeout_matches_cull_timeout(): + c = FakeConfig() + _load_spawner(c, z2jh_values={"cull.enabled": True, "cull.timeout": 1800}) + assert c.KubeSpawner.environment["CODE_SERVER_IDLE_TIMEOUT_SECONDS"] == "1800" + + +def test_idle_timeout_absent_when_culling_disabled(): + c = FakeConfig() + _load_spawner(c, z2jh_values={"cull.enabled": False, "cull.timeout": 1800}) + assert "CODE_SERVER_IDLE_TIMEOUT_SECONDS" not in c.KubeSpawner.environment + + +def test_idle_timeout_absent_when_60_or_less(): + """code-server errors out at startup for values <= 60 — never set them.""" + c = FakeConfig() + _load_spawner(c, z2jh_values={"cull.enabled": True, "cull.timeout": 60}) + assert "CODE_SERVER_IDLE_TIMEOUT_SECONDS" not in c.KubeSpawner.environment +``` + +- [ ] **Step 2: Run tests to verify they fail** + +Run: `.venv-unit/bin/python -m pytest tests/unit/test_spawner_code_server_idle.py -v` +Expected: `test_idle_timeout_matches_cull_timeout` FAILS with `KeyError: 'CODE_SERVER_IDLE_TIMEOUT_SECONDS'`; the two absence tests PASS (that's fine — the positive test is the driver). + +- [ ] **Step 3: Implement in 01-spawner.py** + +Insert after the `NEBI_SERVER_ALLOWED_ORIGINS` block (after the `env["NEBI_SERVER_ALLOWED_ORIGINS"] = ...` conditional, before `c.KubeSpawner.environment = env`): + +```python +# code-server >= 4.106 exits this many seconds after its last browser +# connection closes. Mirrors the hub idle culler so a lingering code-server +# child (tab closed, laptop asleep) dies on the same schedule the hub would +# cull the pod (issue #208). Values <= 60 are rejected by code-server at +# startup — skip them rather than break every pod's VS Code. +_cull_timeout = int(get_config("cull.timeout", 0) or 0) +if get_config("cull.enabled", False) and _cull_timeout > 60: + env["CODE_SERVER_IDLE_TIMEOUT_SECONDS"] = str(_cull_timeout) +``` + +- [ ] **Step 4: Run tests to verify they pass** + +Run: `.venv-unit/bin/python -m pytest tests/unit/test_spawner_code_server_idle.py tests/unit -v` +Expected: all PASS (whole unit suite, to catch env-section regressions). + +- [ ] **Step 5: Commit** + +```bash +git add config/jupyterhub/01-spawner.py tests/unit/test_spawner_code_server_idle.py +git commit -m "feat: derive CODE_SERVER_IDLE_TIMEOUT_SECONDS from cull.timeout" +``` + +--- + +### Task 3: Chart value vscodeActivity.enabled + chart-derived key + +**Files:** +- Modify: `values.yaml` (insert after the `singleuserCuller` block that ends at `shutdownNoActivityTimeout: 900`, ~line 181) +- Modify: `templates/hub-config.yaml` (`_CHART_DERIVED` dict, after the `"shared-storage-enabled"` entry ~line 56) +- Test: `tests/unit/test_chart_derived.py` (extend) + +**Interfaces:** +- Produces: `get_chart_config("vscode-activity-enabled", True)` returns the Python bool rendered from `.Values.vscodeActivity.enabled` (default `True`). Consumed by Task 4. + +- [ ] **Step 1: Write the failing test** + +Append to `tests/unit/test_chart_derived.py` (it already has the `rendered_chart_derived` fixture and `_exec_chart_derived` helper): + +```python +def test_vscode_activity_enabled_defaults_true(rendered_chart_derived): + """`vscodeActivity.enabled` must reach the spawner via _CHART_DERIVED so + the update_last_activity escape hatch (issue #208) is wireable without + a jupyterhub.custom.* override.""" + ns = _exec_chart_derived(rendered_chart_derived, z2jh_values={}) + assert ns["get_chart_config"]("vscode-activity-enabled") is True +``` + +- [ ] **Step 2: Run test to verify it fails** + +Run: `.venv-unit/bin/python -m pytest tests/unit/test_chart_derived.py::test_vscode_activity_enabled_defaults_true -v` +Expected: FAIL — `get_chart_config("vscode-activity-enabled")` returns `""` (the helper's default) because the key is not in `_CHART_DERIVED`. If the test SKIPS, install helm; a skip does not satisfy this step. + +- [ ] **Step 3: Add the value and the chart-derived entry** + +In `values.yaml`, immediately after the `singleuserCuller:` block: + +```yaml +# VS Code (code-server) idle-culling behavior. When enabled (default), VS +# Code browser traffic does NOT count as jupyter activity — the bundled +# nebari-activity-reporter extension reports real user interaction (typing, +# scrolling, terminal use) instead, so idle VS Code tabs cull on the normal +# schedule (https://github.com/nebari-dev/data-science-pack/issues/208). +# Set enabled: false to revert to counting raw proxied traffic (the +# pre-#208 behavior, which keeps pods alive while any tab is open). +vscodeActivity: + enabled: true +``` + +In `templates/hub-config.yaml`, inside `_CHART_DERIVED` after the `"shared-storage-enabled"` line: + +``` + # Mirrors .Values.vscodeActivity.enabled — drives the vscode proxy + # route's update_last_activity escape hatch in 01-spawner.py. + "vscode-activity-enabled": {{ ternary "True" "False" .Values.vscodeActivity.enabled }}, +``` + +- [ ] **Step 4: Run test to verify it passes** + +Run: `.venv-unit/bin/python -m pytest tests/unit/test_chart_derived.py -v` +Expected: all PASS. + +- [ ] **Step 5: Commit** + +```bash +git add values.yaml templates/hub-config.yaml tests/unit/test_chart_derived.py +git commit -m "feat: add vscodeActivity.enabled value with chart-derived plumbing" +``` + +--- + +### Task 4: Spawner sets VSCODE_PROXY_UPDATE_LAST_ACTIVITY escape hatch + +**Files:** +- Modify: `config/jupyterhub/01-spawner.py` (env section, directly after Task 2's block) +- Test: `tests/unit/test_spawner_code_server_idle.py` (extend — reuses `_load_spawner`) + +**Interfaces:** +- Consumes: `get_chart_config("vscode-activity-enabled", True)` (Task 3). +- Produces: pod env `VSCODE_PROXY_UPDATE_LAST_ACTIVITY="true"` **only when the deployer disables** `vscodeActivity`; read by the image config (Task 5). + +- [ ] **Step 1: Write the failing tests** + +Append to `tests/unit/test_spawner_code_server_idle.py`: + +```python +def test_proxy_activity_env_absent_by_default(): + """Default (vscodeActivity.enabled=true): the image config's default of + update_last_activity=False must apply, so no env var is set.""" + c = FakeConfig() + _load_spawner(c, chart_values={"vscode-activity-enabled": True}) + assert "VSCODE_PROXY_UPDATE_LAST_ACTIVITY" not in c.KubeSpawner.environment + + +def test_proxy_activity_env_set_when_vscode_activity_disabled(): + """vscodeActivity.enabled=false is the field escape hatch: proxied VS + Code traffic counts as activity again (pre-#208 behavior).""" + c = FakeConfig() + _load_spawner(c, chart_values={"vscode-activity-enabled": False}) + assert ( + c.KubeSpawner.environment["VSCODE_PROXY_UPDATE_LAST_ACTIVITY"] == "true" + ) +``` + +- [ ] **Step 2: Run tests to verify the new one fails** + +Run: `.venv-unit/bin/python -m pytest tests/unit/test_spawner_code_server_idle.py -v` +Expected: `test_proxy_activity_env_set_when_vscode_activity_disabled` FAILS with `KeyError`; the absent-by-default test passes. + +- [ ] **Step 3: Implement in 01-spawner.py** + +Directly after Task 2's block: + +```python +# Escape hatch for the interaction-based VS Code idle culling (issue #208): +# vscodeActivity.enabled=false reverts the vscode proxy route to counting +# raw proxied traffic as jupyter activity. The image's +# jupyter_server_config.py reads this env var when building +# c.ServerProxy.servers["vscode"]. +if not get_chart_config("vscode-activity-enabled", True): + env["VSCODE_PROXY_UPDATE_LAST_ACTIVITY"] = "true" +``` + +- [ ] **Step 4: Run tests to verify they pass** + +Run: `.venv-unit/bin/python -m pytest tests/unit/test_spawner_code_server_idle.py -v` +Expected: all PASS. + +- [ ] **Step 5: Commit** + +```bash +git add config/jupyterhub/01-spawner.py tests/unit/test_spawner_code_server_idle.py +git commit -m "feat: escape hatch env var for vscode proxy activity counting" +``` + +--- + +### Task 5: Register vscode server in image config; drop jupyter-vscode-proxy + +**Files:** +- Modify: `images/nebi/jupyter_server_config.py` (append after the existing `c.ServerProxy.servers = {...}` assignment) +- Modify: `images/jupyterlab/pixi.toml` (remove line 75: `jupyter-vscode-proxy = { git = "https://github.com/betatim/vscode-binder.git" }`) +- Modify: `images/jupyterlab/pixi.lock` (regenerated) +- Create: `images/nebi/icons/code-server.svg` (downloaded) +- Test: `tests/unit/test_vscode_server_registration.py` (create) + +**Interfaces:** +- Consumes: env `VSCODE_PROXY_UPDATE_LAST_ACTIVITY` (Task 4), optional `CODE_WORKINGDIR` / `CODE_EXTENSIONSDIR` (pre-existing jupyter-vscode-proxy contract). +- Produces: `c.ServerProxy.servers["vscode"]` dict with keys `command` (list, `--port={port}` placeholder), `timeout`, `new_browser_tab`, `update_last_activity` (bool), `launcher_entry`. Route stays `/vscode/` (same name as before — user bookmarks keep working). + +- [ ] **Step 1: Write the failing tests** + +Create `tests/unit/test_vscode_server_registration.py`: + +```python +"""The image-owned jupyter_server_config.py must register the `vscode` +jupyter-server-proxy entry itself (the jupyter-vscode-proxy package was +dropped) with update_last_activity=False, so VS Code keepalive traffic +stops defeating the idle cullers (issue #208). + +This file exec's like JupyterHub does: with `c` in scope. +""" + +from __future__ import annotations + +import importlib.util +from pathlib import Path + +from conftest import FakeConfig + +REPO_ROOT = Path(__file__).resolve().parents[2] +IMAGE_CONFIG = REPO_ROOT / "images" / "nebi" / "jupyter_server_config.py" + + +def _load_image_config(c: FakeConfig): + spec = importlib.util.spec_from_file_location("_img_jsc", IMAGE_CONFIG) + module = importlib.util.module_from_spec(spec) + module.__dict__["c"] = c + spec.loader.exec_module(module) + return module + + +def test_vscode_entry_registered_alongside_nebi(monkeypatch): + monkeypatch.delenv("VSCODE_PROXY_UPDATE_LAST_ACTIVITY", raising=False) + monkeypatch.delenv("CODE_EXTENSIONSDIR", raising=False) + c = FakeConfig() + _load_image_config(c) + servers = c.ServerProxy.servers + assert "nebi" in servers, "vscode registration must not clobber nebi" + assert "vscode" in servers + + +def test_vscode_does_not_count_proxy_traffic_by_default(monkeypatch): + monkeypatch.delenv("VSCODE_PROXY_UPDATE_LAST_ACTIVITY", raising=False) + c = FakeConfig() + _load_image_config(c) + assert c.ServerProxy.servers["vscode"]["update_last_activity"] is False + + +def test_vscode_escape_hatch_env_restores_activity_counting(monkeypatch): + monkeypatch.setenv("VSCODE_PROXY_UPDATE_LAST_ACTIVITY", "true") + c = FakeConfig() + _load_image_config(c) + assert c.ServerProxy.servers["vscode"]["update_last_activity"] is True + + +def test_vscode_command_matches_previous_package_contract(monkeypatch): + """Drop-in replacement for jupyter-vscode-proxy's generated command.""" + monkeypatch.delenv("CODE_EXTENSIONSDIR", raising=False) + monkeypatch.delenv("CODE_WORKINGDIR", raising=False) + c = FakeConfig() + _load_image_config(c) + cmd = c.ServerProxy.servers["vscode"]["command"] + assert cmd[0] == "code-server" + assert "--auth" in cmd and "none" in cmd + assert "--disable-telemetry" in cmd + assert "--port={port}" in cmd + assert cmd[-1] == "." # CODE_WORKINGDIR default + + +def test_vscode_command_honors_code_extensionsdir(monkeypatch): + monkeypatch.setenv("CODE_EXTENSIONSDIR", "/custom/ext") + c = FakeConfig() + _load_image_config(c) + cmd = c.ServerProxy.servers["vscode"]["command"] + assert "--extensions-dir" in cmd + assert "/custom/ext" in cmd + + +def test_vscode_launcher_entry_and_icon_exist(monkeypatch): + monkeypatch.delenv("VSCODE_PROXY_UPDATE_LAST_ACTIVITY", raising=False) + c = FakeConfig() + _load_image_config(c) + entry = c.ServerProxy.servers["vscode"]["launcher_entry"] + assert entry["title"] == "VS Code" + assert Path(entry["icon_path"]).name == "code-server.svg" + assert (REPO_ROOT / "images" / "nebi" / "icons" / "code-server.svg").exists() +``` + +- [ ] **Step 2: Run tests to verify they fail** + +Run: `.venv-unit/bin/python -m pytest tests/unit/test_vscode_server_registration.py -v` +Expected: all 6 FAIL with `KeyError: 'vscode'` (or icon-missing assert). + +- [ ] **Step 3: Download the launcher icon** + +```bash +curl -fsSL https://raw.githubusercontent.com/betatim/vscode-binder/master/jupyter_vscode_proxy/icons/code-server.svg \ + -o images/nebi/icons/code-server.svg +``` +Verify it's an SVG: `head -c 200 images/nebi/icons/code-server.svg` should show ` { + res.resume(); // drain — only the request itself matters + if (res.statusCode < 200 || res.statusCode >= 300) { + output.appendLine(`activity ping (${reason}): HTTP ${res.statusCode}`); + } + }, + ); + req.on("error", (e) => { + // Never throw out of an event handler; next interaction retries. + output.appendLine(`activity ping (${reason}) failed: ${e.message}`); + }); +} + +function recordActivity(reason) { + const now = Date.now(); + if (now - lastPingMs < PING_INTERVAL_MS) { + return; + } + lastPingMs = now; + ping(reason); +} + +function activate(context) { + output = vscode.window.createOutputChannel("Nebari Activity Reporter"); + output.appendLine("activated"); + + const on = (event, reason) => { + context.subscriptions.push(event(() => recordActivity(reason))); + }; + on(vscode.workspace.onDidChangeTextDocument, "edit"); + on(vscode.window.onDidChangeTextEditorSelection, "selection"); + on(vscode.window.onDidChangeTextEditorVisibleRanges, "scroll"); + on(vscode.window.onDidChangeWindowState, "focus"); + on(vscode.window.onDidOpenTerminal, "terminal-open"); + on(vscode.window.onDidCloseTerminal, "terminal-close"); + + // Busy = active: a running terminal command keeps the pod alive, like + // cullBusy=false does for kernels. Requires shell integration (auto- + // injected for bash/zsh). Guarded: API is stable since 1.93 but cheap + // to feature-detect. + if (vscode.window.onDidStartTerminalShellExecution) { + context.subscriptions.push( + vscode.window.onDidStartTerminalShellExecution(() => { + busyExecutions += 1; + recordActivity("exec-start"); + }), + ); + context.subscriptions.push( + vscode.window.onDidEndTerminalShellExecution(() => { + busyExecutions = Math.max(0, busyExecutions - 1); + recordActivity("exec-end"); + }), + ); + } + + const busyTimer = setInterval(() => { + if (busyExecutions > 0) { + recordActivity("busy"); + } + }, PING_INTERVAL_MS); + context.subscriptions.push({ dispose: () => clearInterval(busyTimer) }); + + // A user just opened/reconnected VS Code — that is activity. + recordActivity("startup"); +} + +function deactivate() {} + +module.exports = { activate, deactivate }; +``` + +- [ ] **Step 3: Syntax-check** + +Run: `node --check images/jupyterlab/vscode-activity-reporter/extension.js && python3 -c "import json; json.load(open('images/jupyterlab/vscode-activity-reporter/package.json'))"` +Expected: no output, exit 0. If `node` is not installed locally, the python json check must still pass and Task 7's packaging test exercises the file read; note the skipped node check in the commit body. + +- [ ] **Step 4: Commit** + +```bash +git add images/jupyterlab/vscode-activity-reporter/ +git commit -m "feat: nebari-activity-reporter VS Code extension" +``` + +--- + +### Task 7: build-vsix.py packager + +A `.vsix` is a zip with `extension.vsixmanifest`, `[Content_Types].xml`, and the extension files under `extension/`. Stdlib-only — the image build has no node/npm. + +**Files:** +- Create: `images/scripts/build-vsix.py` +- Test: `tests/unit/test_build_vsix.py` (create) + +**Interfaces:** +- Consumes: an extension source dir containing `package.json` with `name`, `version`, `publisher` (Task 6's contract). +- Produces: CLI `python build-vsix.py `; the vsix installs via `code-server --install-extension` (Task 8 builds it, Task 9 installs it). + +- [ ] **Step 1: Write the failing test** + +Create `tests/unit/test_build_vsix.py`: + +```python +"""build-vsix.py packages an extension dir into a code-server-installable +.vsix (zip with manifest) without needing node/vsce in the image build.""" + +from __future__ import annotations + +import importlib.util +import json +import zipfile +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parents[2] +SCRIPT = REPO_ROOT / "images" / "scripts" / "build-vsix.py" + + +def _build(tmp_path: Path) -> Path: + src = tmp_path / "ext" + src.mkdir() + (src / "package.json").write_text(json.dumps({ + "name": "nebari-activity-reporter", + "publisher": "nebari", + "version": "0.1.0", + "displayName": "Nebari Activity Reporter", + "description": "test fixture", + })) + (src / "extension.js").write_text("module.exports = {};\n") + dest = tmp_path / "out" / "ext.vsix" + + spec = importlib.util.spec_from_file_location("_build_vsix", SCRIPT) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + module.main(str(src), str(dest)) + return dest + + +def test_vsix_layout(tmp_path): + dest = _build(tmp_path) + with zipfile.ZipFile(dest) as z: + names = set(z.namelist()) + assert "extension.vsixmanifest" in names + assert "[Content_Types].xml" in names + assert "extension/package.json" in names + assert "extension/extension.js" in names + + +def test_vsix_manifest_identity(tmp_path): + dest = _build(tmp_path) + with zipfile.ZipFile(dest) as z: + manifest = z.read("extension.vsixmanifest").decode() + assert 'Id="nebari-activity-reporter"' in manifest + assert 'Publisher="nebari"' in manifest + assert 'Version="0.1.0"' in manifest +``` + +- [ ] **Step 2: Run test to verify it fails** + +Run: `.venv-unit/bin/python -m pytest tests/unit/test_build_vsix.py -v` +Expected: FAIL — `FileNotFoundError` loading `images/scripts/build-vsix.py`. + +- [ ] **Step 3: Write build-vsix.py** + +```python +#!/usr/bin/env python3 +# Copyright (c) Nebari Development Team. +# Distributed under the terms of the Modified BSD License. +"""Package a VS Code extension directory as a .vsix, without vsce. + +A .vsix is a zip containing extension.vsixmanifest, [Content_Types].xml +and the extension files under extension/. `code-server +--install-extension` reads the manifest Identity plus +extension/package.json. Used at image build time because the build +environment has no node/npm toolchain. + +Usage: build-vsix.py +""" + +import json +import sys +import zipfile +from pathlib import Path + +MANIFEST = """ + + + + {display} + {description} + Other + + + + + + + + + +""" + +CONTENT_TYPES = """ + + + + + +""" + + +def main(src, dest): + src, dest = Path(src), Path(dest) + pkg = json.loads((src / "package.json").read_text()) + manifest = MANIFEST.format( + name=pkg["name"], + version=pkg["version"], + publisher=pkg["publisher"], + display=pkg.get("displayName", pkg["name"]), + description=pkg.get("description", ""), + ) + dest.parent.mkdir(parents=True, exist_ok=True) + with zipfile.ZipFile(dest, "w", zipfile.ZIP_DEFLATED) as z: + z.writestr("extension.vsixmanifest", manifest) + z.writestr("[Content_Types].xml", CONTENT_TYPES) + for f in sorted(src.rglob("*")): + if f.is_file(): + z.write(f, "extension/" + str(f.relative_to(src))) + + +if __name__ == "__main__": + if len(sys.argv) != 3: + sys.exit(__doc__) + main(sys.argv[1], sys.argv[2]) +``` + +- [ ] **Step 4: Run tests to verify they pass** + +Run: `.venv-unit/bin/python -m pytest tests/unit/test_build_vsix.py -v` +Expected: both PASS. + +- [ ] **Step 5: Commit** + +```bash +git add images/scripts/build-vsix.py tests/unit/test_build_vsix.py +git commit -m "feat: stdlib vsix packager for image builds" +``` + +--- + +### Task 8: Bake the vsix into the image + +**Files:** +- Modify: `images/jupyterlab/postBuild` (after the `install-code-server.sh` line, before `fix-permissions`) + +**Interfaces:** +- Consumes: Task 6's extension source at `/opt/jupyterlab/vscode-activity-reporter` (`COPY jupyterlab /opt/jupyterlab` already ships it — no Dockerfile change needed) and Task 7's script at `/opt/scripts/build-vsix.py` (`COPY scripts /opt/scripts` already ships it). +- Produces: `/opt/code-server-extensions/nebari-activity-reporter.vsix` in the image (consumed by Task 9's postStart). + +- [ ] **Step 1: Add the packaging step to postBuild** + +`images/jupyterlab/postBuild` becomes: + +```bash +#!/usr/bin/env bash +set -euo pipefail +set -x + +# install code-server extension +sh /opt/scripts/install-code-server.sh "/opt/jupyterlab/.pixi/envs/${DEFAULT_ENV}/share" + +# Package the activity-reporter extension as a vsix. Installed per-user by a +# postStart hook (01-spawner.py) because the extensions dir lives on the +# home PVC, which would shadow a build-time install. The pixi env's python +# is not on PATH at this point in the build — use it explicitly. +"/opt/jupyterlab/.pixi/envs/${DEFAULT_ENV}/bin/python" /opt/scripts/build-vsix.py \ + /opt/jupyterlab/vscode-activity-reporter \ + /opt/code-server-extensions/nebari-activity-reporter.vsix + +fix-permissions "/opt/jupyterlab/.pixi/envs/${DEFAULT_ENV}" +``` + +- [ ] **Step 2: Sanity-check the script parses** + +Run: `bash -n images/jupyterlab/postBuild` +Expected: no output, exit 0. (Full validation is the image build in CI — `build-images.yaml` builds on PR; do not attempt the multi-GB build locally unless something fails there.) + +- [ ] **Step 3: Commit** + +```bash +git add images/jupyterlab/postBuild +git commit -m "feat: bake nebari-activity-reporter vsix into singleuser image" +``` + +--- + +### Task 9: postStart installs the extension into the user pod + +**Files:** +- Modify: `config/jupyterhub/01-spawner.py` (inside `_setup_nss_wrapper`, append to `nss_cmds` immediately after the initial two printf commands, before the `REMOVE_SYMLINK_ONLY` logic) +- Test: `tests/unit/test_nss_wrapper_shared_dir.py` (extend — reuses its `FakeSpawner`, `_load_spawner_module`, `_poststart_cmd` helpers) + +**Interfaces:** +- Consumes: `/opt/code-server-extensions/nebari-activity-reporter.vsix` (Task 8); `code-server` CLI on PATH in the pod (Dockerfile already prepends its bin dir). +- Produces: extension installed under `~/.local/share/code-server/extensions/nebari.nebari-activity-reporter-` on every spawn (asserted by Task 10 e2e). + +- [ ] **Step 1: Write the failing test** + +Append to `tests/unit/test_nss_wrapper_shared_dir.py`: + +```python +def test_poststart_installs_activity_reporter_extension_nonfatally(): + """Every spawn installs the bundled activity-reporter vsix into the + PVC-backed extensions dir (idempotent; --force handles upgrades). The + braces + `|| true` isolate the install: with a bare `a && b || true`, + a failure of the nss-wrapper printf commands would ALSO be masked, + and a failed install would CrashLoop the pod without the guard.""" + mod = _load_spawner_module(shared_storage_enabled=False) + spawner = FakeSpawner() + asyncio.run(mod._setup_nss_wrapper(spawner, "alice", [])) + cmd = _poststart_cmd(spawner) + assert ( + "{ code-server --install-extension " + "/opt/code-server-extensions/nebari-activity-reporter.vsix " + "--force || true; }" in cmd + ) +``` + +- [ ] **Step 2: Run test to verify it fails** + +Run: `.venv-unit/bin/python -m pytest tests/unit/test_nss_wrapper_shared_dir.py -v` +Expected: the new test FAILS (substring not found); all pre-existing tests PASS. + +- [ ] **Step 3: Implement in _setup_nss_wrapper** + +In `config/jupyterhub/01-spawner.py`, right after the `nss_cmds = [...]` list is built (the two printf commands), insert: + +```python + # Install the bundled VS Code activity-reporter extension (issue #208) + # into the user's PVC-backed extensions dir. Runs every spawn: + # idempotent, and --force re-installs on image upgrades (new vsix + # version). Wrapped in { ... || true; } so an install failure neither + # CrashLoops the pod nor (via `&&`/`||` left-associativity) masks a + # failure of the preceding nss-wrapper commands. Silent breakage is + # covered by the e2e extension-installed test. + nss_cmds.append( + "{ code-server --install-extension " + "/opt/code-server-extensions/nebari-activity-reporter.vsix " + "--force || true; }" + ) +``` + +- [ ] **Step 4: Run tests to verify they pass** + +Run: `.venv-unit/bin/python -m pytest tests/unit/test_nss_wrapper_shared_dir.py tests/unit -v` +Expected: all PASS. + +- [ ] **Step 5: Commit** + +```bash +git add config/jupyterhub/01-spawner.py tests/unit/test_nss_wrapper_shared_dir.py +git commit -m "feat: install activity-reporter extension via postStart hook" +``` + +--- + +### Task 10: E2E tests + +The harness (`tests/e2e/`, kind + HTTP, no browser) can verify everything except extension *activation under a live VS Code client* (manual soak covers that). All assertions run inside the pod via `spawn_user(...).exec()`; `curl` is in the image. + +**Files:** +- Create: `tests/e2e/test_vscode_idle_culling.py` + +**Interfaces:** +- Consumes: `spawn_user` fixture (`tests/e2e/conftest.py` — returns `SpawnedUser` with `.exec(*cmd)` → `(rc, out)`), chart defaults (`cull.timeout: 1800`, `vscodeActivity.enabled: true`). + +- [ ] **Step 1: Write the e2e tests** + +Create `tests/e2e/test_vscode_idle_culling.py`: + +```python +"""VS Code idle-culling behavior (issue #208), verified inside a live pod. + +What e2e can and cannot cover: these tests exercise the proxy-activity +plumbing, the extension delivery, and the reporting endpoint — via HTTP +from inside the pod. Extension *activation* needs a real VS Code browser +client, which this harness doesn't have; that path is validated by manual +soak (see the design spec). +""" + +import json +import time + +# JUPYTERHUB_SERVICE_PREFIX ends with "/" — concatenate with ${VAR} (no +# added slash): the proxy route regex does not tolerate "//vscode/". +CURL_STATUS = ( + 'curl -sf -H "Authorization: token $JUPYTERHUB_API_TOKEN" ' + '"http://127.0.0.1:8888${JUPYTERHUB_SERVICE_PREFIX}api/status"' +) + + +def _last_activity(user): + rc, out = user.exec("bash", "-c", CURL_STATUS) + assert rc == 0, f"/api/status failed (rc={rc}): {out}" + return json.loads(out)["last_activity"] + + +def test_code_server_idle_timeout_env_matches_cull_timeout(spawn_user): + """Chart default cull.timeout=1800 must reach the pod env verbatim.""" + u = spawn_user("alice-data") + rc, out = u.exec("printenv", "CODE_SERVER_IDLE_TIMEOUT_SECONDS") + assert rc == 0, "CODE_SERVER_IDLE_TIMEOUT_SECONDS not set on the pod" + assert out.strip() == "1800" + + +def test_activity_reporter_extension_installed(spawn_user): + """postStart must install the bundled vsix. This is the tripwire for + the worst failure mode: silently-broken delivery would get active VS + Code users culled mid-session.""" + u = spawn_user("alice-data") + rc, out = u.exec( + "bash", "-c", "ls /home/jovyan/.local/share/code-server/extensions/" + ) + assert rc == 0, out + assert "nebari.nebari-activity-reporter" in out + + +def test_vscode_proxy_traffic_does_not_count_as_activity(spawn_user): + """The core #208 behavior: requests through /vscode/ (which is exactly + what an open tab's keepalives are) must NOT advance last_activity.""" + u = spawn_user("alice-data") + # First hit starts code-server via jupyter-server-proxy (timeout 300 in + # the server entry; jsp blocks the request until the backend is up). + rc, out = u.exec( + "bash", "-c", + 'curl -sf -o /dev/null -H "Authorization: token $JUPYTERHUB_API_TOKEN" ' + '"http://127.0.0.1:8888${JUPYTERHUB_SERVICE_PREFIX}vscode/"', + ) + assert rc == 0, f"vscode proxy route failed to start code-server: {out}" + + before = _last_activity(u) + for _ in range(3): + time.sleep(2) + u.exec( + "bash", "-c", + 'curl -s -o /dev/null -H "Authorization: token $JUPYTERHUB_API_TOKEN" ' + '"http://127.0.0.1:8888${JUPYTERHUB_SERVICE_PREFIX}vscode/"', + ) + after = _last_activity(u) + assert after == before, ( + f"proxied vscode traffic advanced last_activity {before} -> {after}; " + "update_last_activity=False is not applied on the vscode entry" + ) + + +def test_contents_api_ping_counts_as_activity(spawn_user): + """The extension's reporting mechanism: an authenticated contents-API + request must advance last_activity (ISO8601 compares lexicographically).""" + u = spawn_user("alice-data") + before = _last_activity(u) + time.sleep(1.1) # ensure a strictly later timestamp is observable + rc, out = u.exec( + "bash", "-c", + 'curl -sf -o /dev/null -H "Authorization: token $JUPYTERHUB_API_TOKEN" ' + '"http://127.0.0.1:8888${JUPYTERHUB_SERVICE_PREFIX}api/contents/?content=0"', + ) + assert rc == 0, out + after = _last_activity(u) + assert after > before, ( + "contents-API ping did not advance last_activity — the extension's " + "reporting endpoint would be ineffective" + ) +``` + +Note: `JUPYTERHUB_SERVICE_PREFIX` ends with `/`; every URL above concatenates `${JUPYTERHUB_SERVICE_PREFIX}` directly (no extra slash) and quotes the URL so `${...}` expands inside the `bash -c` string. + +- [ ] **Step 2: Sanity-check collection** + +Run: `.venv-unit/bin/python -m pytest tests/e2e/test_vscode_idle_culling.py --collect-only -q` +Expected: 4 tests collected, no import errors. + +- [ ] **Step 3: Run the e2e suite if a cluster is feasible locally, else rely on CI** + +Run (requires `kind`, `helm`, `kubectl`; heavy): +```bash +uvx pytest tests/e2e/test_vscode_idle_culling.py -v +``` +Expected: 4 PASS. **Important:** these tests exercise the freshly-built image (extension, code-server 4.133.0). CI's e2e job builds the image; locally you must have built it (`make jupyterlab` builds `jupyterlab:test`) and pointed the chart at it, or defer to CI. If deferring, state that explicitly in the task report — do not claim e2e passed. + +- [ ] **Step 4: Commit** + +```bash +git add tests/e2e/test_vscode_idle_culling.py +git commit -m "test: e2e coverage for VS Code idle-culling plumbing" +``` + +--- + +### Task 11: Documentation + +**Files:** +- Modify: `docs/src/content/docs/configuration.md` (values table row + new section) + +**Interfaces:** +- Consumes: names/behavior fixed by Tasks 2–9 (do not paraphrase env var or values keys — copy exactly). + +- [ ] **Step 1: Add the values-table row** + +In the configuration values table (the one whose row reads `| `singleuserCuller` | In-pod idle culling for kernels, terminals, and the server itself (separate from the hub-level `jupyterhub.cull`) |`), add directly below that row: + +```markdown +| `vscodeActivity` | Interaction-based idle culling for VS Code; `enabled: false` reverts to counting raw proxied traffic as activity | +``` + +- [ ] **Step 2: Add the explanatory section** + +Append this section to `docs/src/content/docs/configuration.md` (top-level heading level matching the document's existing section style): + +```markdown +## VS Code idle culling + +An open VS Code tab holds a websocket whose keepalives used to count as +Jupyter activity, so pods with an idle VS Code tab were never culled +([#208](https://github.com/nebari-dev/data-science-pack/issues/208)). The +pack now handles VS Code idleness like notebook idleness: + +- **Real interaction counts.** A bundled extension + (`nebari-activity-reporter`, installed automatically on every spawn) + reports typing, scrolling, terminal use, and window focus to the Jupyter + server. A running terminal command also counts as active — same policy + as `cullBusy: false` for kernels — provided the shell has VS Code shell + integration (automatic for bash/zsh; exotic shells running long jobs are + not detected). +- **Raw traffic does not.** The `/vscode/` proxy route runs with + `update_last_activity` disabled, so keepalives from an idle tab no longer + defeat `singleuserCuller` or the hub-level `jupyterhub.cull` culler. +- **Disconnected sessions exit promptly.** `CODE_SERVER_IDLE_TIMEOUT_SECONDS` + is set to `jupyterhub.cull.timeout` (skipped when culling is disabled or + the timeout is ≤ 60 seconds, which code-server rejects), so a code-server + process whose last browser connection has closed exits on the culler's + schedule instead of lingering. + +To revert to the previous behavior (any open tab keeps the pod alive), set: + +```yaml +vscodeActivity: + enabled: false +``` + +For a hard cost cap regardless of activity — e.g. a tab left open on an +always-awake machine — the hub culler's max-age is available separately: + +```yaml +jupyterhub: + cull: + maxAge: 86400 # kill servers after 24h no matter what +``` +``` + +- [ ] **Step 3: Commit** + +```bash +git add docs/src/content/docs/configuration.md +git commit -m "docs: VS Code idle culling behavior and escape hatches" +``` + +--- + +### Task 12: Final verification + +**Files:** +- No new files; runs and fixes only. + +- [ ] **Step 1: Full unit suite** + +Run: `.venv-unit/bin/python -m pytest tests/unit -v` +Expected: all PASS, zero skips among the tests added by this plan (helm-dependent tests must actually run). + +- [ ] **Step 2: Chart renders clean** + +Run: +```bash +helm dependency update . >/dev/null 2>&1 || true +helm template data-science-pack . --namespace jupyterhub \ + --set keycloak.hostname=keycloak.example.com >/dev/null && echo RENDER_OK +helm template data-science-pack . --namespace jupyterhub \ + --set keycloak.hostname=keycloak.example.com \ + --set vscodeActivity.enabled=false | grep -c '"vscode-activity-enabled": False' +``` +Expected: `RENDER_OK`, then `1` (the ternary renders `False` when disabled). + +- [ ] **Step 3: Lint (mirrors `.github/workflows/lint.yaml`)** + +```bash +helm lint . --set nebariapp.enabled=false +uvx ruff@0.16.0 check config/ +``` +Expected: helm lint reports 0 failures; ruff reports no findings. Fix anything reported. + +- [ ] **Step 4: Verification summary + push** + +Confirm every commit from Tasks 1–11 exists (`git log --oneline origin/main..HEAD`), then report: what was verified by tests, what was deferred to CI (image build, e2e), and what remains manual (soak test of extension activation under a real browser, per the spec's Testing section). diff --git a/docs/superpowers/specs/2026-08-19-vscode-idle-culling-design.md b/docs/superpowers/specs/2026-08-19-vscode-idle-culling-design.md index b7488eef..d1a362ce 100644 --- a/docs/superpowers/specs/2026-08-19-vscode-idle-culling-design.md +++ b/docs/superpowers/specs/2026-08-19-vscode-idle-culling-design.md @@ -2,6 +2,32 @@ **Issue:** https://github.com/nebari-dev/data-science-pack/issues/208 +> **Pre-implementation corrections** (found while writing the plan; the +> behavior below is unchanged, three mechanisms moved): +> +> 1. **Registration lives in the image, not the chart ConfigMap.** The image +> already owns `c.ServerProxy.servers` as a dict *assignment* in +> `images/nebi/jupyter_server_config.py` (the nebi tile), and Jupyter +> loads `/etc/jupyter` (chart CM) *before* `/usr/local/etc/jupyter` +> (image), so a CM-side entry would be clobbered. The vscode entry is +> added next to nebi's in the image file; the `vscodeActivity.enabled` +> escape hatch reaches it via a spawner-set pod env var +> (`VSCODE_PROXY_UPDATE_LAST_ACTIVITY`), the same pattern nebi uses for +> `NEBI_REMOTE_URL`. +> 2. **No `@vscode/vsce`.** The build environment has no node/npm toolchain; +> a `.vsix` is a zip with a static manifest, so a ~50-line stdlib Python +> script (`images/scripts/build-vsix.py`) packages it at image build. +> postStart still installs via `code-server --install-extension` +> (non-fatal, `{ ... || true; }`). +> 3. **E2E is kind + HTTP, not playwright.** The existing harness has no +> browser. Adapted e2e: proxied `/vscode/` traffic does NOT advance +> `last_activity`; a contents-API ping DOES; the extension is installed +> in the pod; `CODE_SERVER_IDLE_TIMEOUT_SECONDS` is set. Extension +> *activation* under a real VS Code client is covered by the manual soak +> only. +> 4. The code-server 4.104.3 → 4.133.0 bump needs no hash change: +> `install.sh` is byte-identical between the two tags (verified). + ## Problem A user pod running VS Code (code-server, proxied by jupyter-server-proxy) is From c6a9ced6a801803a248e1fc14f4b0f79f3bb8b32 Mon Sep 17 00:00:00 2001 From: Tyler Potts <49161327+tylerpotts@users.noreply.github.com> Date: Wed, 19 Aug 2026 15:56:45 -0500 Subject: [PATCH 03/24] feat: bump code-server to 4.133.0 for idle-timeout support --- images/scripts/install-code-server.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/images/scripts/install-code-server.sh b/images/scripts/install-code-server.sh index bbe9733e..a354cd30 100755 --- a/images/scripts/install-code-server.sh +++ b/images/scripts/install-code-server.sh @@ -5,13 +5,13 @@ set -xe DEFAULT_PREFIX="${1}" shift # path to environment yaml or lock file -CODE_SERVER_VERSION=4.104.3 +CODE_SERVER_VERSION=4.133.0 mkdir -p ${DEFAULT_PREFIX}/code-server cd ${DEFAULT_PREFIX}/code-server # Fetch the snapshot of https://code-server.dev/install.sh as of the time of writing -wget --quiet https://raw.githubusercontent.com/coder/code-server/v4.104.3/install.sh +wget --quiet https://raw.githubusercontent.com/coder/code-server/v4.133.0/install.sh expected_sum=e86784e9fec81106c74941e55dbbcb85dc963a06ad6c3f1a870d4a22cf432e1d if [[ ! $(sha256sum install.sh) == "${expected_sum} install.sh" ]]; then From 699b024b657497b91bc4165f45d92bbcf8d60db3 Mon Sep 17 00:00:00 2001 From: Tyler Potts <49161327+tylerpotts@users.noreply.github.com> Date: Wed, 19 Aug 2026 15:59:00 -0500 Subject: [PATCH 04/24] feat: derive CODE_SERVER_IDLE_TIMEOUT_SECONDS from cull.timeout --- config/jupyterhub/01-spawner.py | 9 +++ tests/unit/test_spawner_code_server_idle.py | 61 +++++++++++++++++++++ 2 files changed, 70 insertions(+) create mode 100644 tests/unit/test_spawner_code_server_idle.py diff --git a/config/jupyterhub/01-spawner.py b/config/jupyterhub/01-spawner.py index 917ee4bd..4389c6c0 100644 --- a/config/jupyterhub/01-spawner.py +++ b/config/jupyterhub/01-spawner.py @@ -317,6 +317,15 @@ def _setup_trust_bundle(spawner): if _hub_external_host: env["NEBI_SERVER_ALLOWED_ORIGINS"] = f"https://{_hub_external_host}" +# code-server >= 4.106 exits this many seconds after its last browser +# connection closes. Mirrors the hub idle culler so a lingering code-server +# child (tab closed, laptop asleep) dies on the same schedule the hub would +# cull the pod (issue #208). Values <= 60 are rejected by code-server at +# startup — skip them rather than break every pod's VS Code. +_cull_timeout = int(get_config("cull.timeout", 0) or 0) +if get_config("cull.enabled", False) and _cull_timeout > 60: + env["CODE_SERVER_IDLE_TIMEOUT_SECONDS"] = str(_cull_timeout) + c.KubeSpawner.environment = env diff --git a/tests/unit/test_spawner_code_server_idle.py b/tests/unit/test_spawner_code_server_idle.py new file mode 100644 index 00000000..ec9dbb48 --- /dev/null +++ b/tests/unit/test_spawner_code_server_idle.py @@ -0,0 +1,61 @@ +"""CODE_SERVER_IDLE_TIMEOUT_SECONDS wiring in `01-spawner.py`. + +code-server >= 4.106 exits N seconds after its last browser connection +closes when this env var is set. It must mirror the hub idle culler's +`cull.timeout` (issue #208) — and must be ABSENT when culling is disabled +or the timeout is <= 60, because code-server refuses to start for values +<= 60 and that would take down every user pod's VS Code. +""" + +from __future__ import annotations + +import importlib.util +import sys +import types + +# 01-spawner.py imports `z2jh.get_config`; stub it so the module exec's standalone. +_z2jh = types.ModuleType("z2jh") +_z2jh.get_config = lambda key, default=None: default +sys.modules.setdefault("z2jh", _z2jh) + +from conftest import CONFIG_DIR, FakeConfig # noqa: E402 + + +def _load_spawner(c: FakeConfig, z2jh_values: dict | None = None, + chart_values: dict | None = None): + """Exec raw 01-spawner.py with per-test z2jh + chart config stubs.""" + z2jh_values = z2jh_values or {} + chart_values = chart_values or {} + z2jh = sys.modules["z2jh"] + orig = z2jh.get_config + z2jh.get_config = lambda key, default=None: z2jh_values.get(key, default) + try: + path = CONFIG_DIR / "01-spawner.py" + spec = importlib.util.spec_from_file_location("_spawner_idle", path) + module = importlib.util.module_from_spec(spec) + module.__dict__["c"] = c + module.__dict__["get_chart_config"] = ( + lambda key, default="": chart_values.get(key, default) + ) + spec.loader.exec_module(module) + finally: + z2jh.get_config = orig + + +def test_idle_timeout_matches_cull_timeout(): + c = FakeConfig() + _load_spawner(c, z2jh_values={"cull.enabled": True, "cull.timeout": 1800}) + assert c.KubeSpawner.environment["CODE_SERVER_IDLE_TIMEOUT_SECONDS"] == "1800" + + +def test_idle_timeout_absent_when_culling_disabled(): + c = FakeConfig() + _load_spawner(c, z2jh_values={"cull.enabled": False, "cull.timeout": 1800}) + assert "CODE_SERVER_IDLE_TIMEOUT_SECONDS" not in c.KubeSpawner.environment + + +def test_idle_timeout_absent_when_60_or_less(): + """code-server errors out at startup for values <= 60 — never set them.""" + c = FakeConfig() + _load_spawner(c, z2jh_values={"cull.enabled": True, "cull.timeout": 60}) + assert "CODE_SERVER_IDLE_TIMEOUT_SECONDS" not in c.KubeSpawner.environment From 64573eb139783297599f19038661ccb1b45cd783 Mon Sep 17 00:00:00 2001 From: Tyler Potts <49161327+tylerpotts@users.noreply.github.com> Date: Wed, 19 Aug 2026 16:02:32 -0500 Subject: [PATCH 05/24] feat: add vscodeActivity.enabled value with chart-derived plumbing --- templates/hub-config.yaml | 3 +++ tests/unit/test_chart_derived.py | 8 ++++++++ values.yaml | 10 ++++++++++ 3 files changed, 21 insertions(+) diff --git a/templates/hub-config.yaml b/templates/hub-config.yaml index 7a3ebc27..62742cad 100644 --- a/templates/hub-config.yaml +++ b/templates/hub-config.yaml @@ -54,6 +54,9 @@ data: # both. Deployer override via jupyterhub.custom.shared-storage-enabled # still wins via z2jh. "shared-storage-enabled": {{ ternary "True" "False" .Values.sharedStorage.enabled }}, + # Mirrors .Values.vscodeActivity.enabled — drives the vscode proxy + # route's update_last_activity escape hatch in 01-spawner.py. + "vscode-activity-enabled": {{ ternary "True" "False" .Values.vscodeActivity.enabled }}, } diff --git a/tests/unit/test_chart_derived.py b/tests/unit/test_chart_derived.py index fe941839..fc1fcdd8 100644 --- a/tests/unit/test_chart_derived.py +++ b/tests/unit/test_chart_derived.py @@ -148,3 +148,11 @@ def test_get_chart_config_explicit_override_wins(rendered_chart_derived): ) got = ns["get_chart_config"]("external-url") assert got == "explicit.example.com" + + +def test_vscode_activity_enabled_defaults_true(rendered_chart_derived): + """`vscodeActivity.enabled` must reach the spawner via _CHART_DERIVED so + the update_last_activity escape hatch (issue #208) is wireable without + a jupyterhub.custom.* override.""" + ns = _exec_chart_derived(rendered_chart_derived, z2jh_values={}) + assert ns["get_chart_config"]("vscode-activity-enabled") is True diff --git a/values.yaml b/values.yaml index c8b73a56..72a753d4 100644 --- a/values.yaml +++ b/values.yaml @@ -179,6 +179,16 @@ singleuserCuller: server: shutdownNoActivityTimeout: 900 # 15 min — seconds after last kernel/terminal gone before server self-terminates +# VS Code (code-server) idle-culling behavior. When enabled (default), VS +# Code browser traffic does NOT count as jupyter activity — the bundled +# nebari-activity-reporter extension reports real user interaction (typing, +# scrolling, terminal use) instead, so idle VS Code tabs cull on the normal +# schedule (https://github.com/nebari-dev/data-science-pack/issues/208). +# Set enabled: false to revert to counting raw proxied traffic (the +# pre-#208 behavior, which keeps pods alive while any tab is open). +vscodeActivity: + enabled: true + # Shared storage — per-group directories mounted at /shared/ in user pods. # Requires an RWX StorageClass on the cluster. # From bcc3a7594acea18e30214c6d72d1c2a8326dee4c Mon Sep 17 00:00:00 2001 From: Tyler Potts <49161327+tylerpotts@users.noreply.github.com> Date: Wed, 19 Aug 2026 16:05:07 -0500 Subject: [PATCH 06/24] feat: escape hatch env var for vscode proxy activity counting --- config/jupyterhub/01-spawner.py | 8 ++++++++ tests/unit/test_spawner_code_server_idle.py | 18 ++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/config/jupyterhub/01-spawner.py b/config/jupyterhub/01-spawner.py index 4389c6c0..aef7219f 100644 --- a/config/jupyterhub/01-spawner.py +++ b/config/jupyterhub/01-spawner.py @@ -326,6 +326,14 @@ def _setup_trust_bundle(spawner): if get_config("cull.enabled", False) and _cull_timeout > 60: env["CODE_SERVER_IDLE_TIMEOUT_SECONDS"] = str(_cull_timeout) +# Escape hatch for the interaction-based VS Code idle culling (issue #208): +# vscodeActivity.enabled=false reverts the vscode proxy route to counting +# raw proxied traffic as jupyter activity. The image's +# jupyter_server_config.py reads this env var when building +# c.ServerProxy.servers["vscode"]. +if not get_chart_config("vscode-activity-enabled", True): + env["VSCODE_PROXY_UPDATE_LAST_ACTIVITY"] = "true" + c.KubeSpawner.environment = env diff --git a/tests/unit/test_spawner_code_server_idle.py b/tests/unit/test_spawner_code_server_idle.py index ec9dbb48..baf44fc7 100644 --- a/tests/unit/test_spawner_code_server_idle.py +++ b/tests/unit/test_spawner_code_server_idle.py @@ -59,3 +59,21 @@ def test_idle_timeout_absent_when_60_or_less(): c = FakeConfig() _load_spawner(c, z2jh_values={"cull.enabled": True, "cull.timeout": 60}) assert "CODE_SERVER_IDLE_TIMEOUT_SECONDS" not in c.KubeSpawner.environment + + +def test_proxy_activity_env_absent_by_default(): + """Default (vscodeActivity.enabled=true): the image config's default of + update_last_activity=False must apply, so no env var is set.""" + c = FakeConfig() + _load_spawner(c, chart_values={"vscode-activity-enabled": True}) + assert "VSCODE_PROXY_UPDATE_LAST_ACTIVITY" not in c.KubeSpawner.environment + + +def test_proxy_activity_env_set_when_vscode_activity_disabled(): + """vscodeActivity.enabled=false is the field escape hatch: proxied VS + Code traffic counts as activity again (pre-#208 behavior).""" + c = FakeConfig() + _load_spawner(c, chart_values={"vscode-activity-enabled": False}) + assert ( + c.KubeSpawner.environment["VSCODE_PROXY_UPDATE_LAST_ACTIVITY"] == "true" + ) From cb1ce5b9c01af42bc93e533602f597413740534d Mon Sep 17 00:00:00 2001 From: Tyler Potts <49161327+tylerpotts@users.noreply.github.com> Date: Wed, 19 Aug 2026 16:10:41 -0500 Subject: [PATCH 07/24] feat: own the vscode proxy entry with update_last_activity=False --- images/jupyterlab/pixi.lock | 6 -- images/jupyterlab/pixi.toml | 1 - images/nebi/icons/code-server.svg | 9 ++ images/nebi/jupyter_server_config.py | 48 +++++++++++ tests/unit/test_vscode_server_registration.py | 82 +++++++++++++++++++ 5 files changed, 139 insertions(+), 7 deletions(-) create mode 100644 images/nebi/icons/code-server.svg create mode 100644 tests/unit/test_vscode_server_registration.py diff --git a/images/jupyterlab/pixi.lock b/images/jupyterlab/pixi.lock index 362926aa..4f4e4810 100644 --- a/images/jupyterlab/pixi.lock +++ b/images/jupyterlab/pixi.lock @@ -430,7 +430,6 @@ environments: - conda: https://conda.anaconda.org/conda-forge/noarch/xyzservices-2025.1.0-pyhd8ed1ab_0.conda - conda: https://conda.anaconda.org/conda-forge/noarch/zict-3.0.0-pyhd8ed1ab_1.conda - conda: https://conda.anaconda.org/conda-forge/noarch/zipp-3.21.0-pyhd8ed1ab_1.conda - - pypi: git+https://github.com/betatim/vscode-binder.git#3e69a137988539f24381e07dd373a1a372098ff4 - pypi: https://files.pythonhosted.org/packages/02/11/9cae49425dbb3e89a7bb3a4d2e974711ad86baa6cc1f47c9bb4e009adced/jupyterlab_jhub_apps-0.3.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/04/1e/b832de447dee8b582cac175871d2f6c3d5077cc56d5575cadba1fd1cccfa/linkify_it_py-2.0.3-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/06/ad/5ba858ffc307ed2b51693d87642f9e9dd6013579840981ac364c6e24c38c/backports_zstd-1.1.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl @@ -909,7 +908,6 @@ environments: - conda: https://conda.anaconda.org/conda-forge/noarch/xyzservices-2025.1.0-pyhd8ed1ab_0.conda - conda: https://conda.anaconda.org/conda-forge/noarch/zict-3.0.0-pyhd8ed1ab_1.conda - conda: https://conda.anaconda.org/conda-forge/noarch/zipp-3.21.0-pyhd8ed1ab_1.conda - - pypi: git+https://github.com/betatim/vscode-binder.git#3e69a137988539f24381e07dd373a1a372098ff4 - pypi: https://files.pythonhosted.org/packages/02/11/9cae49425dbb3e89a7bb3a4d2e974711ad86baa6cc1f47c9bb4e009adced/jupyterlab_jhub_apps-0.3.1-py3-none-any.whl - pypi: https://files.pythonhosted.org/packages/02/57/7163ed06a2d9bf1f34d89dcc7c5881119beeed287022c997b0a706edcfbe/dulwich-0.22.8-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl - pypi: https://files.pythonhosted.org/packages/04/1e/b832de447dee8b582cac175871d2f6c3d5077cc56d5575cadba1fd1cccfa/linkify_it_py-2.0.3-py3-none-any.whl @@ -9107,10 +9105,6 @@ packages: - pkg:pypi/zipp?source=hash-mapping size: 21809 timestamp: 1732827613585 -- pypi: git+https://github.com/betatim/vscode-binder.git#3e69a137988539f24381e07dd373a1a372098ff4 - name: jupyter-vscode-proxy - version: 0.7.post4+g3e69a1379 - requires_python: '>=3.8' - pypi: https://files.pythonhosted.org/packages/02/11/9cae49425dbb3e89a7bb3a4d2e974711ad86baa6cc1f47c9bb4e009adced/jupyterlab_jhub_apps-0.3.1-py3-none-any.whl name: jupyterlab-jhub-apps version: 0.3.1 diff --git a/images/jupyterlab/pixi.toml b/images/jupyterlab/pixi.toml index 65f97190..f1fce609 100644 --- a/images/jupyterlab/pixi.toml +++ b/images/jupyterlab/pixi.toml @@ -72,7 +72,6 @@ gnupg = "*" pyjwt = ">=2.13.0,<3" [pypi-dependencies] -jupyter-vscode-proxy = { git = "https://github.com/betatim/vscode-binder.git" } nb_nebi_kernels = "==0.3" jupyterlab_nvdashboard = "==0.12.0" # argo-jupyter-scheduler = "==2024.6.1" # disabled until service is configured diff --git a/images/nebi/icons/code-server.svg b/images/nebi/icons/code-server.svg new file mode 100644 index 00000000..85b701dc --- /dev/null +++ b/images/nebi/icons/code-server.svg @@ -0,0 +1,9 @@ + + \ No newline at end of file diff --git a/images/nebi/jupyter_server_config.py b/images/nebi/jupyter_server_config.py index e37dcd25..14d057bf 100644 --- a/images/nebi/jupyter_server_config.py +++ b/images/nebi/jupyter_server_config.py @@ -80,3 +80,51 @@ }, } } + +# jupyter-server-proxy configuration for VS Code (code-server). +# Registered here instead of via the jupyter-vscode-proxy package so the +# entry can set update_last_activity=False: with it True (the packaged +# default), the VS Code browser client's websocket keepalives count as +# jupyter API activity and neither the in-pod shutdown_no_activity_timeout +# nor the hub idle culler ever fires while a tab is open +# (https://github.com/nebari-dev/data-science-pack/issues/208). Real user +# interaction is reported instead by the bundled nebari-activity-reporter +# extension (see images/jupyterlab/vscode-activity-reporter/). +VSCODE_ICON_PATH = os.path.join( + os.path.dirname(os.path.abspath(__file__)), + "icons", + "code-server.svg", +) + + +def _vscode_command(): + # Mirrors the command jupyter-vscode-proxy generated (minus unix-socket + # support, which nothing here used). {port} is templated by + # jupyter-server-proxy at launch. + cmd = ["code-server", "--auth", "none", "--disable-telemetry", "--port={port}"] + extensions_dir = os.environ.get("CODE_EXTENSIONSDIR") + if extensions_dir: + cmd += ["--extensions-dir", extensions_dir] + cmd.append(os.environ.get("CODE_WORKINGDIR", ".")) + return cmd + + +# Escape hatch: the spawner sets this env var when the deployer disables +# vscodeActivity in values.yaml, restoring the pre-#208 behavior of counting +# raw proxied traffic as activity. +_vscode_count_proxy_traffic = ( + os.environ.get("VSCODE_PROXY_UPDATE_LAST_ACTIVITY", "").lower() + in ("1", "true", "yes") +) + +c.ServerProxy.servers["vscode"] = { + "command": _vscode_command(), + "timeout": 300, + "new_browser_tab": True, + "update_last_activity": _vscode_count_proxy_traffic, + "launcher_entry": { + "title": "VS Code", + "enabled": True, + "icon_path": VSCODE_ICON_PATH, + }, +} diff --git a/tests/unit/test_vscode_server_registration.py b/tests/unit/test_vscode_server_registration.py new file mode 100644 index 00000000..1756d4f5 --- /dev/null +++ b/tests/unit/test_vscode_server_registration.py @@ -0,0 +1,82 @@ +"""The image-owned jupyter_server_config.py must register the `vscode` +jupyter-server-proxy entry itself (the jupyter-vscode-proxy package was +dropped) with update_last_activity=False, so VS Code keepalive traffic +stops defeating the idle cullers (issue #208). + +This file exec's like JupyterHub does: with `c` in scope. +""" + +from __future__ import annotations + +import importlib.util +from pathlib import Path + +from conftest import FakeConfig + +REPO_ROOT = Path(__file__).resolve().parents[2] +IMAGE_CONFIG = REPO_ROOT / "images" / "nebi" / "jupyter_server_config.py" + + +def _load_image_config(c: FakeConfig): + spec = importlib.util.spec_from_file_location("_img_jsc", IMAGE_CONFIG) + module = importlib.util.module_from_spec(spec) + module.__dict__["c"] = c + spec.loader.exec_module(module) + return module + + +def test_vscode_entry_registered_alongside_nebi(monkeypatch): + monkeypatch.delenv("VSCODE_PROXY_UPDATE_LAST_ACTIVITY", raising=False) + monkeypatch.delenv("CODE_EXTENSIONSDIR", raising=False) + c = FakeConfig() + _load_image_config(c) + servers = c.ServerProxy.servers + assert "nebi" in servers, "vscode registration must not clobber nebi" + assert "vscode" in servers + + +def test_vscode_does_not_count_proxy_traffic_by_default(monkeypatch): + monkeypatch.delenv("VSCODE_PROXY_UPDATE_LAST_ACTIVITY", raising=False) + c = FakeConfig() + _load_image_config(c) + assert c.ServerProxy.servers["vscode"]["update_last_activity"] is False + + +def test_vscode_escape_hatch_env_restores_activity_counting(monkeypatch): + monkeypatch.setenv("VSCODE_PROXY_UPDATE_LAST_ACTIVITY", "true") + c = FakeConfig() + _load_image_config(c) + assert c.ServerProxy.servers["vscode"]["update_last_activity"] is True + + +def test_vscode_command_matches_previous_package_contract(monkeypatch): + """Drop-in replacement for jupyter-vscode-proxy's generated command.""" + monkeypatch.delenv("CODE_EXTENSIONSDIR", raising=False) + monkeypatch.delenv("CODE_WORKINGDIR", raising=False) + c = FakeConfig() + _load_image_config(c) + cmd = c.ServerProxy.servers["vscode"]["command"] + assert cmd[0] == "code-server" + assert "--auth" in cmd and "none" in cmd + assert "--disable-telemetry" in cmd + assert "--port={port}" in cmd + assert cmd[-1] == "." # CODE_WORKINGDIR default + + +def test_vscode_command_honors_code_extensionsdir(monkeypatch): + monkeypatch.setenv("CODE_EXTENSIONSDIR", "/custom/ext") + c = FakeConfig() + _load_image_config(c) + cmd = c.ServerProxy.servers["vscode"]["command"] + assert "--extensions-dir" in cmd + assert "/custom/ext" in cmd + + +def test_vscode_launcher_entry_and_icon_exist(monkeypatch): + monkeypatch.delenv("VSCODE_PROXY_UPDATE_LAST_ACTIVITY", raising=False) + c = FakeConfig() + _load_image_config(c) + entry = c.ServerProxy.servers["vscode"]["launcher_entry"] + assert entry["title"] == "VS Code" + assert Path(entry["icon_path"]).name == "code-server.svg" + assert (REPO_ROOT / "images" / "nebi" / "icons" / "code-server.svg").exists() From 14aeb27290e4e93207b12af85597fb82dc800673 Mon Sep 17 00:00:00 2001 From: Tyler Potts <49161327+tylerpotts@users.noreply.github.com> Date: Wed, 19 Aug 2026 16:15:00 -0500 Subject: [PATCH 08/24] feat: nebari-activity-reporter VS Code extension --- .../vscode-activity-reporter/extension.js | 117 ++++++++++++++++++ .../vscode-activity-reporter/package.json | 13 ++ 2 files changed, 130 insertions(+) create mode 100644 images/jupyterlab/vscode-activity-reporter/extension.js create mode 100644 images/jupyterlab/vscode-activity-reporter/package.json diff --git a/images/jupyterlab/vscode-activity-reporter/extension.js b/images/jupyterlab/vscode-activity-reporter/extension.js new file mode 100644 index 00000000..ef19fda9 --- /dev/null +++ b/images/jupyterlab/vscode-activity-reporter/extension.js @@ -0,0 +1,117 @@ +"use strict"; +// Reports real user interaction to the local Jupyter server. +// +// The vscode proxy route runs with update_last_activity=False (see +// images/nebi/jupyter_server_config.py), so VS Code traffic no longer +// counts as jupyter activity. Without this extension, actively working +// VS Code users would be idle-culled — this is the load-bearing half of +// nebari-dev/data-science-pack#208. +// +// Endpoint choice: /api/status and /api/ set _track_activity=False +// upstream (so pollers don't defeat culling); /api/contents/ is tracked. +const vscode = require("vscode"); +const http = require("http"); + +const PING_INTERVAL_MS = 60 * 1000; + +let lastPingMs = 0; +let busyExecutions = 0; // in-flight terminal shell executions +let output; + +function pingUrl() { + const base = process.env.JUPYTERHUB_SERVICE_URL; + if (!base) { + return null; // not running under JupyterHub — nothing to report to + } + try { + const url = new URL(base); + if (url.hostname === "0.0.0.0" || url.hostname === "::") { + url.hostname = "127.0.0.1"; + } + url.pathname = url.pathname.replace(/\/?$/, "/") + "api/contents/"; + url.search = "?content=0"; + return url; + } catch (e) { + output.appendLine(`bad JUPYTERHUB_SERVICE_URL: ${e.message}`); + return null; + } +} + +function ping(reason) { + const url = pingUrl(); + const token = process.env.JUPYTERHUB_API_TOKEN; + if (!url || !token) { + return; + } + const req = http.get( + url, + { headers: { Authorization: `token ${token}` } }, + (res) => { + res.resume(); // drain — only the request itself matters + if (res.statusCode < 200 || res.statusCode >= 300) { + output.appendLine(`activity ping (${reason}): HTTP ${res.statusCode}`); + } + }, + ); + req.on("error", (e) => { + // Never throw out of an event handler; next interaction retries. + output.appendLine(`activity ping (${reason}) failed: ${e.message}`); + }); +} + +function recordActivity(reason) { + const now = Date.now(); + if (now - lastPingMs < PING_INTERVAL_MS) { + return; + } + lastPingMs = now; + ping(reason); +} + +function activate(context) { + output = vscode.window.createOutputChannel("Nebari Activity Reporter"); + output.appendLine("activated"); + + const on = (event, reason) => { + context.subscriptions.push(event(() => recordActivity(reason))); + }; + on(vscode.workspace.onDidChangeTextDocument, "edit"); + on(vscode.window.onDidChangeTextEditorSelection, "selection"); + on(vscode.window.onDidChangeTextEditorVisibleRanges, "scroll"); + on(vscode.window.onDidChangeWindowState, "focus"); + on(vscode.window.onDidOpenTerminal, "terminal-open"); + on(vscode.window.onDidCloseTerminal, "terminal-close"); + + // Busy = active: a running terminal command keeps the pod alive, like + // cullBusy=false does for kernels. Requires shell integration (auto- + // injected for bash/zsh). Guarded: API is stable since 1.93 but cheap + // to feature-detect. + if (vscode.window.onDidStartTerminalShellExecution) { + context.subscriptions.push( + vscode.window.onDidStartTerminalShellExecution(() => { + busyExecutions += 1; + recordActivity("exec-start"); + }), + ); + context.subscriptions.push( + vscode.window.onDidEndTerminalShellExecution(() => { + busyExecutions = Math.max(0, busyExecutions - 1); + recordActivity("exec-end"); + }), + ); + } + + const busyTimer = setInterval(() => { + if (busyExecutions > 0) { + recordActivity("busy"); + } + }, PING_INTERVAL_MS); + context.subscriptions.push({ dispose: () => clearInterval(busyTimer) }); + + // A user just opened/reconnected VS Code — that is activity. + recordActivity("startup"); +} + +function deactivate() {} + +module.exports = { activate, deactivate }; diff --git a/images/jupyterlab/vscode-activity-reporter/package.json b/images/jupyterlab/vscode-activity-reporter/package.json new file mode 100644 index 00000000..94ef9a9b --- /dev/null +++ b/images/jupyterlab/vscode-activity-reporter/package.json @@ -0,0 +1,13 @@ +{ + "name": "nebari-activity-reporter", + "displayName": "Nebari Activity Reporter", + "description": "Reports real user interaction to the Jupyter server so idle culling works correctly with VS Code (nebari-dev/data-science-pack#208).", + "publisher": "nebari", + "version": "0.1.0", + "license": "BSD-3-Clause", + "engines": { "vscode": "^1.93.0" }, + "categories": ["Other"], + "activationEvents": ["onStartupFinished"], + "main": "./extension.js", + "contributes": {} +} From da331d24265c38dd4eab8fb53470e2efd2628d27 Mon Sep 17 00:00:00 2001 From: Tyler Potts <49161327+tylerpotts@users.noreply.github.com> Date: Wed, 19 Aug 2026 16:20:01 -0500 Subject: [PATCH 09/24] fix: harden activity-reporter URL normalization and ping error handling --- .../vscode-activity-reporter/extension.js | 36 +++++++++++-------- 1 file changed, 21 insertions(+), 15 deletions(-) diff --git a/images/jupyterlab/vscode-activity-reporter/extension.js b/images/jupyterlab/vscode-activity-reporter/extension.js index ef19fda9..544485a7 100644 --- a/images/jupyterlab/vscode-activity-reporter/extension.js +++ b/images/jupyterlab/vscode-activity-reporter/extension.js @@ -19,13 +19,15 @@ let busyExecutions = 0; // in-flight terminal shell executions let output; function pingUrl() { - const base = process.env.JUPYTERHUB_SERVICE_URL; + let base = process.env.JUPYTERHUB_SERVICE_URL; if (!base) { return null; // not running under JupyterHub — nothing to report to } try { + // Normalize IPv6 any-host (::) to bracketed form before URL parsing + base = base.replace("://:", "://[::]"); const url = new URL(base); - if (url.hostname === "0.0.0.0" || url.hostname === "::") { + if (url.hostname === "0.0.0.0" || url.hostname === "[::]") { url.hostname = "127.0.0.1"; } url.pathname = url.pathname.replace(/\/?$/, "/") + "api/contents/"; @@ -43,20 +45,24 @@ function ping(reason) { if (!url || !token) { return; } - const req = http.get( - url, - { headers: { Authorization: `token ${token}` } }, - (res) => { - res.resume(); // drain — only the request itself matters - if (res.statusCode < 200 || res.statusCode >= 300) { - output.appendLine(`activity ping (${reason}): HTTP ${res.statusCode}`); - } - }, - ); - req.on("error", (e) => { - // Never throw out of an event handler; next interaction retries. + try { + const req = http.get( + url, + { headers: { Authorization: `token ${token}` } }, + (res) => { + res.resume(); // drain — only the request itself matters + if (res.statusCode < 200 || res.statusCode >= 300) { + output.appendLine(`activity ping (${reason}): HTTP ${res.statusCode}`); + } + }, + ); + req.on("error", (e) => { + // Never throw out of an event handler; next interaction retries. + output.appendLine(`activity ping (${reason}) failed: ${e.message}`); + }); + } catch (e) { output.appendLine(`activity ping (${reason}) failed: ${e.message}`); - }); + } } function recordActivity(reason) { From 2182330a60a76505911dd38f0721d3fe11540b16 Mon Sep 17 00:00:00 2001 From: Tyler Potts <49161327+tylerpotts@users.noreply.github.com> Date: Wed, 19 Aug 2026 16:22:45 -0500 Subject: [PATCH 10/24] feat: stdlib vsix packager for image builds --- images/scripts/build-vsix.py | 69 +++++++++++++++++++++++++++++++++++ tests/unit/test_build_vsix.py | 51 ++++++++++++++++++++++++++ 2 files changed, 120 insertions(+) create mode 100644 images/scripts/build-vsix.py create mode 100644 tests/unit/test_build_vsix.py diff --git a/images/scripts/build-vsix.py b/images/scripts/build-vsix.py new file mode 100644 index 00000000..9bc47e6d --- /dev/null +++ b/images/scripts/build-vsix.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python3 +# Copyright (c) Nebari Development Team. +# Distributed under the terms of the Modified BSD License. +"""Package a VS Code extension directory as a .vsix, without vsce. + +A .vsix is a zip containing extension.vsixmanifest, [Content_Types].xml +and the extension files under extension/. `code-server +--install-extension` reads the manifest Identity plus +extension/package.json. Used at image build time because the build +environment has no node/npm toolchain. + +Usage: build-vsix.py +""" + +import json +import sys +import zipfile +from pathlib import Path + +MANIFEST = """ + + + + {display} + {description} + Other + + + + + + + + + +""" + +CONTENT_TYPES = """ + + + + + +""" + + +def main(src, dest): + src, dest = Path(src), Path(dest) + pkg = json.loads((src / "package.json").read_text()) + manifest = MANIFEST.format( + name=pkg["name"], + version=pkg["version"], + publisher=pkg["publisher"], + display=pkg.get("displayName", pkg["name"]), + description=pkg.get("description", ""), + ) + dest.parent.mkdir(parents=True, exist_ok=True) + with zipfile.ZipFile(dest, "w", zipfile.ZIP_DEFLATED) as z: + z.writestr("extension.vsixmanifest", manifest) + z.writestr("[Content_Types].xml", CONTENT_TYPES) + for f in sorted(src.rglob("*")): + if f.is_file(): + z.write(f, "extension/" + str(f.relative_to(src))) + + +if __name__ == "__main__": + if len(sys.argv) != 3: + sys.exit(__doc__) + main(sys.argv[1], sys.argv[2]) diff --git a/tests/unit/test_build_vsix.py b/tests/unit/test_build_vsix.py new file mode 100644 index 00000000..c6249c81 --- /dev/null +++ b/tests/unit/test_build_vsix.py @@ -0,0 +1,51 @@ +"""build-vsix.py packages an extension dir into a code-server-installable +.vsix (zip with manifest) without needing node/vsce in the image build.""" + +from __future__ import annotations + +import importlib.util +import json +import zipfile +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parents[2] +SCRIPT = REPO_ROOT / "images" / "scripts" / "build-vsix.py" + + +def _build(tmp_path: Path) -> Path: + src = tmp_path / "ext" + src.mkdir() + (src / "package.json").write_text(json.dumps({ + "name": "nebari-activity-reporter", + "publisher": "nebari", + "version": "0.1.0", + "displayName": "Nebari Activity Reporter", + "description": "test fixture", + })) + (src / "extension.js").write_text("module.exports = {};\n") + dest = tmp_path / "out" / "ext.vsix" + + spec = importlib.util.spec_from_file_location("_build_vsix", SCRIPT) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + module.main(str(src), str(dest)) + return dest + + +def test_vsix_layout(tmp_path): + dest = _build(tmp_path) + with zipfile.ZipFile(dest) as z: + names = set(z.namelist()) + assert "extension.vsixmanifest" in names + assert "[Content_Types].xml" in names + assert "extension/package.json" in names + assert "extension/extension.js" in names + + +def test_vsix_manifest_identity(tmp_path): + dest = _build(tmp_path) + with zipfile.ZipFile(dest) as z: + manifest = z.read("extension.vsixmanifest").decode() + assert 'Id="nebari-activity-reporter"' in manifest + assert 'Publisher="nebari"' in manifest + assert 'Version="0.1.0"' in manifest From ceed6bb32009358e3425e69154c9bae238e32771 Mon Sep 17 00:00:00 2001 From: Tyler Potts <49161327+tylerpotts@users.noreply.github.com> Date: Wed, 19 Aug 2026 16:25:41 -0500 Subject: [PATCH 11/24] fix: xml-escape vsix manifest fields --- images/scripts/build-vsix.py | 13 ++++++++----- tests/unit/test_build_vsix.py | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 5 deletions(-) diff --git a/images/scripts/build-vsix.py b/images/scripts/build-vsix.py index 9bc47e6d..aa539887 100644 --- a/images/scripts/build-vsix.py +++ b/images/scripts/build-vsix.py @@ -16,6 +16,7 @@ import sys import zipfile from pathlib import Path +from xml.sax.saxutils import escape MANIFEST = """ @@ -47,12 +48,14 @@ def main(src, dest): src, dest = Path(src), Path(dest) pkg = json.loads((src / "package.json").read_text()) + # Escape XML special characters for both attributes and element text + # For attributes, also escape quotes manifest = MANIFEST.format( - name=pkg["name"], - version=pkg["version"], - publisher=pkg["publisher"], - display=pkg.get("displayName", pkg["name"]), - description=pkg.get("description", ""), + name=escape(pkg["name"], {'"': """}), + version=escape(pkg["version"], {'"': """}), + publisher=escape(pkg["publisher"], {'"': """}), + display=escape(pkg.get("displayName", pkg["name"])), + description=escape(pkg.get("description", "")), ) dest.parent.mkdir(parents=True, exist_ok=True) with zipfile.ZipFile(dest, "w", zipfile.ZIP_DEFLATED) as z: diff --git a/tests/unit/test_build_vsix.py b/tests/unit/test_build_vsix.py index c6249c81..f9378f36 100644 --- a/tests/unit/test_build_vsix.py +++ b/tests/unit/test_build_vsix.py @@ -5,6 +5,7 @@ import importlib.util import json +import xml.etree.ElementTree import zipfile from pathlib import Path @@ -49,3 +50,36 @@ def test_vsix_manifest_identity(tmp_path): assert 'Id="nebari-activity-reporter"' in manifest assert 'Publisher="nebari"' in manifest assert 'Version="0.1.0"' in manifest + + +def test_vsix_manifest_xml_escaping(tmp_path): + """Manifest field values with &, <, > and " must be XML-escaped.""" + src = tmp_path / "ext" + src.mkdir() + (src / "package.json").write_text(json.dumps({ + "name": "test-extension", + "publisher": "Foo & \"baz\"", + "version": "0.1.0", + "displayName": "Test & \"Extension\"", + "description": "Foo & \"baz\"", + })) + (src / "extension.js").write_text("module.exports = {};\n") + dest = tmp_path / "out" / "ext.vsix" + + spec = importlib.util.spec_from_file_location("_build_vsix", SCRIPT) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + module.main(str(src), str(dest)) + + with zipfile.ZipFile(dest) as z: + manifest = z.read("extension.vsixmanifest").decode() + + # Verify escaped forms are present + # Attributes must escape &, <, >, and " + assert 'Publisher="Foo & <Bar> "baz""' in manifest + # Element text must escape &, <, > but not " + assert 'Test & <Unsafe> "Extension"' in manifest + assert 'Foo & <Bar> "baz"' in manifest + + # Verify manifest is valid XML + xml.etree.ElementTree.fromstring(manifest) From 488e5830bedc9693cf4b02202baa6415e9022fbd Mon Sep 17 00:00:00 2001 From: Tyler Potts <49161327+tylerpotts@users.noreply.github.com> Date: Wed, 19 Aug 2026 16:27:45 -0500 Subject: [PATCH 12/24] feat: bake nebari-activity-reporter vsix into singleuser image --- images/jupyterlab/postBuild | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/images/jupyterlab/postBuild b/images/jupyterlab/postBuild index 76c087e8..11730b14 100755 --- a/images/jupyterlab/postBuild +++ b/images/jupyterlab/postBuild @@ -5,4 +5,12 @@ set -x # install code-server extension sh /opt/scripts/install-code-server.sh "/opt/jupyterlab/.pixi/envs/${DEFAULT_ENV}/share" +# Package the activity-reporter extension as a vsix. Installed per-user by a +# postStart hook (01-spawner.py) because the extensions dir lives on the +# home PVC, which would shadow a build-time install. The pixi env's python +# is not on PATH at this point in the build — use it explicitly. +"/opt/jupyterlab/.pixi/envs/${DEFAULT_ENV}/bin/python" /opt/scripts/build-vsix.py \ + /opt/jupyterlab/vscode-activity-reporter \ + /opt/code-server-extensions/nebari-activity-reporter.vsix + fix-permissions "/opt/jupyterlab/.pixi/envs/${DEFAULT_ENV}" From 2561031a3223b6f7428d30be43718740cebfd1db Mon Sep 17 00:00:00 2001 From: Tyler Potts <49161327+tylerpotts@users.noreply.github.com> Date: Wed, 19 Aug 2026 16:30:27 -0500 Subject: [PATCH 13/24] feat: install activity-reporter extension via postStart hook --- config/jupyterhub/01-spawner.py | 13 +++++++++++++ tests/unit/test_nss_wrapper_shared_dir.py | 17 +++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/config/jupyterhub/01-spawner.py b/config/jupyterhub/01-spawner.py index aef7219f..4e215e11 100644 --- a/config/jupyterhub/01-spawner.py +++ b/config/jupyterhub/01-spawner.py @@ -1020,6 +1020,19 @@ async def _setup_nss_wrapper(spawner, username, groups): + " > /tmp/group", ] + # Install the bundled VS Code activity-reporter extension (issue #208) + # into the user's PVC-backed extensions dir. Runs every spawn: + # idempotent, and --force re-installs on image upgrades (new vsix + # version). Wrapped in { ... || true; } so an install failure neither + # CrashLoops the pod nor (via `&&`/`||` left-associativity) masks a + # failure of the preceding nss-wrapper commands. Silent breakage is + # covered by the e2e extension-installed test. + nss_cmds.append( + "{ code-server --install-extension " + "/opt/code-server-extensions/nebari-activity-reporter.vsix " + "--force || true; }" + ) + # Group membership changes between spawns (gain, lose, swap) are a # normal operational scenario. The home PVC persists, so the shape # `~/shared` took on the LAST spawn is still there at the start of diff --git a/tests/unit/test_nss_wrapper_shared_dir.py b/tests/unit/test_nss_wrapper_shared_dir.py index 26a28e01..63484927 100644 --- a/tests/unit/test_nss_wrapper_shared_dir.py +++ b/tests/unit/test_nss_wrapper_shared_dir.py @@ -154,3 +154,20 @@ def test_groups_without_shared_storage_preserves_user_data_in_per_group_dirs(): assert "mkdir -p /home/jovyan/shared" in cmd assert "mkdir -p /home/jovyan/shared/data" in cmd assert "mkdir -p /home/jovyan/shared/ml" in cmd + + +def test_poststart_installs_activity_reporter_extension_nonfatally(): + """Every spawn installs the bundled activity-reporter vsix into the + PVC-backed extensions dir (idempotent; --force handles upgrades). The + braces + `|| true` isolate the install: with a bare `a && b || true`, + a failure of the nss-wrapper printf commands would ALSO be masked, + and a failed install would CrashLoop the pod without the guard.""" + mod = _load_spawner_module(shared_storage_enabled=False) + spawner = FakeSpawner() + asyncio.run(mod._setup_nss_wrapper(spawner, "alice", [])) + cmd = _poststart_cmd(spawner) + assert ( + "{ code-server --install-extension " + "/opt/code-server-extensions/nebari-activity-reporter.vsix " + "--force || true; }" in cmd + ) From 12d7f68094a9844796cd93d4680a9a63487d4445 Mon Sep 17 00:00:00 2001 From: Tyler Potts <49161327+tylerpotts@users.noreply.github.com> Date: Wed, 19 Aug 2026 16:35:23 -0500 Subject: [PATCH 14/24] test: e2e coverage for VS Code idle-culling plumbing --- tests/e2e/test_vscode_idle_culling.py | 91 +++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 tests/e2e/test_vscode_idle_culling.py diff --git a/tests/e2e/test_vscode_idle_culling.py b/tests/e2e/test_vscode_idle_culling.py new file mode 100644 index 00000000..f2d18f24 --- /dev/null +++ b/tests/e2e/test_vscode_idle_culling.py @@ -0,0 +1,91 @@ +"""VS Code idle-culling behavior (issue #208), verified inside a live pod. + +What e2e can and cannot cover: these tests exercise the proxy-activity +plumbing, the extension delivery, and the reporting endpoint — via HTTP +from inside the pod. Extension *activation* needs a real VS Code browser +client, which this harness doesn't have; that path is validated by manual +soak (see the design spec). +""" + +import json +import time + +# JUPYTERHUB_SERVICE_PREFIX ends with "/" — concatenate with ${VAR} (no +# added slash): the proxy route regex does not tolerate "//vscode/". +CURL_STATUS = ( + 'curl -sf -H "Authorization: token $JUPYTERHUB_API_TOKEN" ' + '"http://127.0.0.1:8888${JUPYTERHUB_SERVICE_PREFIX}api/status"' +) + + +def _last_activity(user): + rc, out = user.exec("bash", "-c", CURL_STATUS) + assert rc == 0, f"/api/status failed (rc={rc}): {out}" + return json.loads(out)["last_activity"] + + +def test_code_server_idle_timeout_env_matches_cull_timeout(spawn_user): + """Chart default cull.timeout=1800 must reach the pod env verbatim.""" + u = spawn_user("alice-data") + rc, out = u.exec("printenv", "CODE_SERVER_IDLE_TIMEOUT_SECONDS") + assert rc == 0, "CODE_SERVER_IDLE_TIMEOUT_SECONDS not set on the pod" + assert out.strip() == "1800" + + +def test_activity_reporter_extension_installed(spawn_user): + """postStart must install the bundled vsix. This is the tripwire for + the worst failure mode: silently-broken delivery would get active VS + Code users culled mid-session.""" + u = spawn_user("alice-data") + rc, out = u.exec( + "bash", "-c", "ls /home/jovyan/.local/share/code-server/extensions/" + ) + assert rc == 0, out + assert "nebari.nebari-activity-reporter" in out + + +def test_vscode_proxy_traffic_does_not_count_as_activity(spawn_user): + """The core #208 behavior: requests through /vscode/ (which is exactly + what an open tab's keepalives are) must NOT advance last_activity.""" + u = spawn_user("alice-data") + # First hit starts code-server via jupyter-server-proxy (timeout 300 in + # the server entry; jsp blocks the request until the backend is up). + rc, out = u.exec( + "bash", "-c", + 'curl -sf -o /dev/null -H "Authorization: token $JUPYTERHUB_API_TOKEN" ' + '"http://127.0.0.1:8888${JUPYTERHUB_SERVICE_PREFIX}vscode/"', + ) + assert rc == 0, f"vscode proxy route failed to start code-server: {out}" + + before = _last_activity(u) + for _ in range(3): + time.sleep(2) + u.exec( + "bash", "-c", + 'curl -s -o /dev/null -H "Authorization: token $JUPYTERHUB_API_TOKEN" ' + '"http://127.0.0.1:8888${JUPYTERHUB_SERVICE_PREFIX}vscode/"', + ) + after = _last_activity(u) + assert after == before, ( + f"proxied vscode traffic advanced last_activity {before} -> {after}; " + "update_last_activity=False is not applied on the vscode entry" + ) + + +def test_contents_api_ping_counts_as_activity(spawn_user): + """The extension's reporting mechanism: an authenticated contents-API + request must advance last_activity (ISO8601 compares lexicographically).""" + u = spawn_user("alice-data") + before = _last_activity(u) + time.sleep(1.1) # ensure a strictly later timestamp is observable + rc, out = u.exec( + "bash", "-c", + 'curl -sf -o /dev/null -H "Authorization: token $JUPYTERHUB_API_TOKEN" ' + '"http://127.0.0.1:8888${JUPYTERHUB_SERVICE_PREFIX}api/contents/?content=0"', + ) + assert rc == 0, out + after = _last_activity(u) + assert after > before, ( + "contents-API ping did not advance last_activity — the extension's " + "reporting endpoint would be ineffective" + ) From 7540639cbcee628a1ce28300d023f11c52ccac1a Mon Sep 17 00:00:00 2001 From: Tyler Potts <49161327+tylerpotts@users.noreply.github.com> Date: Wed, 19 Aug 2026 16:38:57 -0500 Subject: [PATCH 15/24] docs: VS Code idle culling behavior and escape hatches --- docs/src/content/docs/configuration.md | 40 ++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/docs/src/content/docs/configuration.md b/docs/src/content/docs/configuration.md index 1af1dcbb..788671cb 100644 --- a/docs/src/content/docs/configuration.md +++ b/docs/src/content/docs/configuration.md @@ -16,6 +16,7 @@ Every derived value can still be overridden explicitly. Values under | `nebariapp` | Whether/how the `NebariApp` CRD is rendered — routing, auth, landing-page card. See [NebariApp Integration](/nebariapp-integration/) | | `singleuser` | Egress NetworkPolicy allowing user pods to reach the Nebari gateway | | `singleuserCuller` | In-pod idle culling for kernels, terminals, and the server itself (separate from the hub-level `jupyterhub.cull`) | +| `vscodeActivity` | Interaction-based idle culling for VS Code; `enabled: false` reverts to counting raw proxied traffic as activity | | `sharedStorage` | Per-group RWX directories and the transitional in-cluster NFS mode. See [Shared Storage](/shared-storage/) | | `nebi` | The companion Nebi service — image, external/internal URLs, namespace, release name | | `rbac.bootstrap` | One-shot Keycloak Job that adds the groups-claim mapper and the shared-mount client role | @@ -31,3 +32,42 @@ The dummy authenticator is used by default so any username/password works without a Keycloak dependency. To test against real OAuth, configure `jupyterhub.hub.config` per the [Zero to JupyterHub authentication docs](https://z2jh.jupyter.org/en/stable/administrator/authentication.html). + +## VS Code idle culling + +An open VS Code tab holds a websocket whose keepalives used to count as +Jupyter activity, so pods with an idle VS Code tab were never culled +([#208](https://github.com/nebari-dev/data-science-pack/issues/208)). The +pack now handles VS Code idleness like notebook idleness: + +- **Real interaction counts.** A bundled extension + (`nebari-activity-reporter`, installed automatically on every spawn) + reports typing, scrolling, terminal use, and window focus to the Jupyter + server. A running terminal command also counts as active — same policy + as `cullBusy: false` for kernels — provided the shell has VS Code shell + integration (automatic for bash/zsh; exotic shells running long jobs are + not detected). +- **Raw traffic does not.** The `/vscode/` proxy route runs with + `update_last_activity` disabled, so keepalives from an idle tab no longer + defeat `singleuserCuller` or the hub-level `jupyterhub.cull` culler. +- **Disconnected sessions exit promptly.** `CODE_SERVER_IDLE_TIMEOUT_SECONDS` + is set to `jupyterhub.cull.timeout` (skipped when culling is disabled or + the timeout is ≤ 60 seconds, which code-server rejects), so a code-server + process whose last browser connection has closed exits on the culler's + schedule instead of lingering. + +To revert to the previous behavior (any open tab keeps the pod alive), set: + +```yaml +vscodeActivity: + enabled: false +``` + +For a hard cost cap regardless of activity — e.g. a tab left open on an +always-awake machine — the hub culler's max-age is available separately: + +```yaml +jupyterhub: + cull: + maxAge: 86400 # kill servers after 24h no matter what +``` From f67324b113d3a60ddbaccbc5ca22ad35a6ae5a27 Mon Sep 17 00:00:00 2001 From: Tyler Potts <49161327+tylerpotts@users.noreply.github.com> Date: Wed, 19 Aug 2026 17:07:53 -0500 Subject: [PATCH 16/24] fix(vscode-idle-culling): flip escape-hatch polarity and harden cull wiring Final-review fixes for the VS Code idle-culling feature (issue #208): - Flip VSCODE_PROXY_UPDATE_LAST_ACTIVITY polarity: absent/empty now means the image's OLD behavior (count proxied traffic as activity); the chart actively sets "false" to opt pods into the new interaction-based behavior. Chart/image skew now fails safe (over-spend) instead of culling active users who lack the activity-reporter extension. - Correct the culling mental model in the design spec and configuration docs: configurable-http-proxy still sees websocket activity on the /vscode/ route regardless of update_last_activity, so the hub-level jupyterhub.cull culler is not fixed by this change. The load-bearing mechanism is the in-pod singleuserCuller.server.shutdownNoActivityTimeout. Extended the e2e module docstring to note the in-pod curls bypass CHP and cannot observe that hub-side signal. - postStart install now runs under `timeout 60` so a hung install cannot stall pod startup, and mirrors CODE_EXTENSIONSDIR via ${CODE_EXTENSIONSDIR:+--extensions-dir "$CODE_EXTENSIONSDIR"} so the extension installs into the same directory VS Code reads from. - Guard the cull.timeout int() conversion so a non-numeric deployer value disables the feature instead of raising and crashing the spawner config. Tests updated/added first (TDD) for each behavior change: inverted the proxy-activity env-var tests, renamed the image-config tests to match the new semantics, updated the postStart command assertion, and added boundary (61) and non-numeric cull.timeout regression tests. --- config/jupyterhub/01-spawner.py | 52 +++++++++++++------ docs/src/content/docs/configuration.md | 14 +++-- .../2026-08-19-vscode-idle-culling-design.md | 26 +++++++--- images/nebi/jupyter_server_config.py | 18 ++++--- tests/e2e/test_vscode_idle_culling.py | 15 ++++++ tests/unit/test_nss_wrapper_shared_dir.py | 20 +++++-- tests/unit/test_spawner_code_server_idle.py | 39 ++++++++++---- tests/unit/test_vscode_server_registration.py | 17 +++++- 8 files changed, 154 insertions(+), 47 deletions(-) diff --git a/config/jupyterhub/01-spawner.py b/config/jupyterhub/01-spawner.py index 4e215e11..00ce6dc6 100644 --- a/config/jupyterhub/01-spawner.py +++ b/config/jupyterhub/01-spawner.py @@ -321,18 +321,30 @@ def _setup_trust_bundle(spawner): # connection closes. Mirrors the hub idle culler so a lingering code-server # child (tab closed, laptop asleep) dies on the same schedule the hub would # cull the pod (issue #208). Values <= 60 are rejected by code-server at -# startup — skip them rather than break every pod's VS Code. -_cull_timeout = int(get_config("cull.timeout", 0) or 0) -if get_config("cull.enabled", False) and _cull_timeout > 60: - env["CODE_SERVER_IDLE_TIMEOUT_SECONDS"] = str(_cull_timeout) - -# Escape hatch for the interaction-based VS Code idle culling (issue #208): -# vscodeActivity.enabled=false reverts the vscode proxy route to counting -# raw proxied traffic as jupyter activity. The image's -# jupyter_server_config.py reads this env var when building -# c.ServerProxy.servers["vscode"]. -if not get_chart_config("vscode-activity-enabled", True): - env["VSCODE_PROXY_UPDATE_LAST_ACTIVITY"] = "true" +# startup, so skip them rather than break every pod's VS Code. cull.timeout +# is deployer-supplied and may not parse as an int (bad YAML, a stray +# string); guard the conversion so a bad value just disables this feature +# instead of raising and taking down the whole spawner config file. +if get_config("cull.enabled", False): + try: + _cull_timeout = int(get_config("cull.timeout", 0) or 0) + except (TypeError, ValueError): + _cull_timeout = 0 + if _cull_timeout > 60: + env["CODE_SERVER_IDLE_TIMEOUT_SECONDS"] = str(_cull_timeout) + +# Escape hatch for the interaction-based VS Code idle culling (issue #208). +# The image defaults to the OLD behavior (counting raw proxied traffic as +# activity) when this env var is absent, so chart/image skew fails safe +# (pods over-spend, rather than culling active users with no reporter +# installed). When vscodeActivity.enabled is true (the chart default), +# actively opt the pod into the new behavior by setting the env var to +# "false"; the image's jupyter_server_config.py reads it when building +# c.ServerProxy.servers["vscode"]. When the deployer sets +# vscodeActivity.enabled=false, set nothing so the image's fail-safe +# default (True) applies. +if get_chart_config("vscode-activity-enabled", True): + env["VSCODE_PROXY_UPDATE_LAST_ACTIVITY"] = "false" c.KubeSpawner.environment = env @@ -1026,11 +1038,19 @@ async def _setup_nss_wrapper(spawner, username, groups): # version). Wrapped in { ... || true; } so an install failure neither # CrashLoops the pod nor (via `&&`/`||` left-associativity) masks a # failure of the preceding nss-wrapper commands. Silent breakage is - # covered by the e2e extension-installed test. + # covered by the e2e extension-installed test. `timeout 60` bounds a + # hung install (e.g. a wedged extensions-dir mount) so it can't stall + # pod startup; timeout(1) is coreutils, present in the ubuntu base + # image. `${CODE_EXTENSIONSDIR:+--extensions-dir "$CODE_EXTENSIONSDIR"}` + # mirrors the --extensions-dir flag the vscode proxy entry + # (images/nebi/jupyter_server_config.py) passes when CODE_EXTENSIONSDIR + # is set, keeping the install location in sync with where code-server + # actually reads extensions from. nss_cmds.append( - "{ code-server --install-extension " - "/opt/code-server-extensions/nebari-activity-reporter.vsix " - "--force || true; }" + '{ timeout 60 code-server --install-extension ' + '/opt/code-server-extensions/nebari-activity-reporter.vsix ' + '${CODE_EXTENSIONSDIR:+--extensions-dir "$CODE_EXTENSIONSDIR"} ' + '--force || true; }' ) # Group membership changes between spawns (gain, lose, swap) are a diff --git a/docs/src/content/docs/configuration.md b/docs/src/content/docs/configuration.md index 788671cb..6ed2fbea 100644 --- a/docs/src/content/docs/configuration.md +++ b/docs/src/content/docs/configuration.md @@ -47,9 +47,17 @@ pack now handles VS Code idleness like notebook idleness: as `cullBusy: false` for kernels — provided the shell has VS Code shell integration (automatic for bash/zsh; exotic shells running long jobs are not detected). -- **Raw traffic does not.** The `/vscode/` proxy route runs with - `update_last_activity` disabled, so keepalives from an idle tab no longer - defeat `singleuserCuller` or the hub-level `jupyterhub.cull` culler. +- **Raw traffic no longer defeats the in-pod culler.** The `/vscode/` proxy + route runs with `update_last_activity` disabled, so keepalives from an + idle tab no longer keep jupyter-server's own activity clock fresh. The + hub-level `jupyterhub.cull` culler is **not** fixed by this: proxied + websocket traffic is still visible to configurable-http-proxy at the + route level, so the hub keeps seeing activity for as long as a tab stays + connected, regardless of `update_last_activity`. The setting that + actually culls an idle-tab pod is the in-pod + `singleuserCuller.server.shutdownNoActivityTimeout` (default `900` + seconds / 15 minutes), which jupyter-server evaluates from its own + activity clock; set it to `0` to disable this feature. - **Disconnected sessions exit promptly.** `CODE_SERVER_IDLE_TIMEOUT_SECONDS` is set to `jupyterhub.cull.timeout` (skipped when culling is disabled or the timeout is ≤ 60 seconds, which code-server rejects), so a code-server diff --git a/docs/superpowers/specs/2026-08-19-vscode-idle-culling-design.md b/docs/superpowers/specs/2026-08-19-vscode-idle-culling-design.md index d1a362ce..10bc53a5 100644 --- a/docs/superpowers/specs/2026-08-19-vscode-idle-culling-design.md +++ b/docs/superpowers/specs/2026-08-19-vscode-idle-culling-design.md @@ -101,12 +101,21 @@ package is the unambiguous path. The launcher icon SVG currently ships inside that package, so it gets baked into the image instead. With `update_last_activity: False`, an idle tab's keepalives no longer touch -`api_last_activity`, and the existing cullers govern VS Code pods exactly as -they do notebook pods: - -- in-pod: kernels/terminals cull at 900s idle; the server exits 900s after the - last kernel/terminal if no API activity (`singleuserCuller` values). -- hub: `jupyterhub.cull.timeout: 1800` culls on hub-side staleness. +`api_last_activity` inside the pod. This is what makes the in-pod culler +load-bearing; it is NOT what fixes the hub-level culler: + +- in-pod (load-bearing): `shutdown_no_activity_timeout` + (`singleuserCuller.server.shutdownNoActivityTimeout`, default 900s) reads + `api_last_activity` directly, so it now goes stale correctly on an idle + tab and fires on schedule. +- hub (`jupyterhub.cull.timeout: 1800`): NOT fixed by this change. + configurable-http-proxy (CHP) tracks route-level websocket activity + independent of jupyter-server-proxy's `update_last_activity` trait: an + open VS Code tab's keepalives still flow through the `/vscode/` route, + so CHP keeps the hub's last-activity fresh for as long as the tab is + connected. The hub-level culler therefore still will not fire while a + tab is open; the in-pod culler above is the mechanism that actually + terminates an idle-tab pod. ### 2. Activity-reporter extension @@ -233,6 +242,11 @@ tabs. working VS Code users; dealbreaker. - **Rejected as primary fix: `cull.maxAge`** — blunt hard cap that kills active users; documented as an optional backstop only. +- **Escape-hatch env var polarity flipped after final review**: + `VSCODE_PROXY_UPDATE_LAST_ACTIVITY` absent/empty now means the OLD + behavior (image default); the chart actively sets it to `"false"` to opt + pods into the new behavior. This makes chart/image skew fail safe + (over-spend, not cull-active-users). User decision, 2026-08-19. ## Verified upstream facts diff --git a/images/nebi/jupyter_server_config.py b/images/nebi/jupyter_server_config.py index 14d057bf..c00b8465 100644 --- a/images/nebi/jupyter_server_config.py +++ b/images/nebi/jupyter_server_config.py @@ -109,13 +109,17 @@ def _vscode_command(): return cmd -# Escape hatch: the spawner sets this env var when the deployer disables -# vscodeActivity in values.yaml, restoring the pre-#208 behavior of counting -# raw proxied traffic as activity. -_vscode_count_proxy_traffic = ( - os.environ.get("VSCODE_PROXY_UPDATE_LAST_ACTIVITY", "").lower() - in ("1", "true", "yes") -) +# Fail-safe default: absent/empty means the OLD behavior (count proxied +# traffic as activity) applies. The chart actively opts pods into the new +# interaction-based behavior by setting this env var to "false" when +# vscodeActivity.enabled is true (config/jupyterhub/01-spawner.py). This +# polarity means chart/image skew (e.g. a newer image tag paired with an +# older chart release that doesn't yet set the env var) degrades to the +# safe failure mode (pods over-spend on proxied traffic staying "active") +# rather than the dangerous one (culling active VS Code users who have no +# activity-reporter extension installed to keep them alive). +_value = os.environ.get("VSCODE_PROXY_UPDATE_LAST_ACTIVITY", "").strip().lower() +_vscode_count_proxy_traffic = _value not in ("0", "false", "no") c.ServerProxy.servers["vscode"] = { "command": _vscode_command(), diff --git a/tests/e2e/test_vscode_idle_culling.py b/tests/e2e/test_vscode_idle_culling.py index f2d18f24..1f6a7865 100644 --- a/tests/e2e/test_vscode_idle_culling.py +++ b/tests/e2e/test_vscode_idle_culling.py @@ -5,6 +5,21 @@ from inside the pod. Extension *activation* needs a real VS Code browser client, which this harness doesn't have; that path is validated by manual soak (see the design spec). + +These tests curl `127.0.0.1:8888` directly from inside the pod, bypassing +configurable-http-proxy (CHP) entirely. That means they cannot observe +CHP-level route activity tracking: the mechanism that keeps the hub-level +`jupyterhub.cull` culler's last-activity fresh independent of +`update_last_activity` while a tab stays connected (see the design spec's +corrected mental model). What they DO verify is the in-pod +`api_last_activity` signal that `singleuserCuller.server. +shutdownNoActivityTimeout` actually reads. Also: because the co-installed +`nebari-activity-reporter` extension never activates without a real VS Code +client in this harness, it never fires its own contents-API pings during +these tests, which is exactly why +`test_vscode_proxy_traffic_does_not_count_as_activity` below can assert a +stable `last_activity` across repeated proxied requests: nothing else in +the pod is nudging it forward. """ import json diff --git a/tests/unit/test_nss_wrapper_shared_dir.py b/tests/unit/test_nss_wrapper_shared_dir.py index 63484927..9ea06271 100644 --- a/tests/unit/test_nss_wrapper_shared_dir.py +++ b/tests/unit/test_nss_wrapper_shared_dir.py @@ -161,13 +161,25 @@ def test_poststart_installs_activity_reporter_extension_nonfatally(): PVC-backed extensions dir (idempotent; --force handles upgrades). The braces + `|| true` isolate the install: with a bare `a && b || true`, a failure of the nss-wrapper printf commands would ALSO be masked, - and a failed install would CrashLoop the pod without the guard.""" + and a failed install would CrashLoop the pod without the guard. + + Two additional properties pinned here: + * `timeout 60` bounds the install's runtime so a hung + `code-server --install-extension` (e.g. a wedged extensions-dir + mount) cannot stall pod startup indefinitely. + * `${CODE_EXTENSIONSDIR:+--extensions-dir "$CODE_EXTENSIONSDIR"}` + mirrors the --extensions-dir flag the vscode proxy entry + (images/nebi/jupyter_server_config.py) passes when + CODE_EXTENSIONSDIR is set, so the extension is installed into the + SAME directory VS Code itself reads extensions from. + """ mod = _load_spawner_module(shared_storage_enabled=False) spawner = FakeSpawner() asyncio.run(mod._setup_nss_wrapper(spawner, "alice", [])) cmd = _poststart_cmd(spawner) assert ( - "{ code-server --install-extension " - "/opt/code-server-extensions/nebari-activity-reporter.vsix " - "--force || true; }" in cmd + '{ timeout 60 code-server --install-extension ' + '/opt/code-server-extensions/nebari-activity-reporter.vsix ' + '${CODE_EXTENSIONSDIR:+--extensions-dir "$CODE_EXTENSIONSDIR"} ' + '--force || true; }' in cmd ) diff --git a/tests/unit/test_spawner_code_server_idle.py b/tests/unit/test_spawner_code_server_idle.py index baf44fc7..5efcab25 100644 --- a/tests/unit/test_spawner_code_server_idle.py +++ b/tests/unit/test_spawner_code_server_idle.py @@ -61,19 +61,38 @@ def test_idle_timeout_absent_when_60_or_less(): assert "CODE_SERVER_IDLE_TIMEOUT_SECONDS" not in c.KubeSpawner.environment -def test_proxy_activity_env_absent_by_default(): - """Default (vscodeActivity.enabled=true): the image config's default of - update_last_activity=False must apply, so no env var is set.""" +def test_idle_timeout_set_at_boundary_61(): + """61 is the smallest value code-server accepts; must be set verbatim.""" c = FakeConfig() - _load_spawner(c, chart_values={"vscode-activity-enabled": True}) - assert "VSCODE_PROXY_UPDATE_LAST_ACTIVITY" not in c.KubeSpawner.environment + _load_spawner(c, z2jh_values={"cull.enabled": True, "cull.timeout": 61}) + assert c.KubeSpawner.environment["CODE_SERVER_IDLE_TIMEOUT_SECONDS"] == "61" -def test_proxy_activity_env_set_when_vscode_activity_disabled(): - """vscodeActivity.enabled=false is the field escape hatch: proxied VS - Code traffic counts as activity again (pre-#208 behavior).""" +def test_idle_timeout_ignores_non_numeric_timeout(): + """cull.timeout is deployer-supplied and may not parse as an int; a bad + value must disable the feature rather than raise and take down the + whole spawner config file.""" c = FakeConfig() - _load_spawner(c, chart_values={"vscode-activity-enabled": False}) + _load_spawner(c, z2jh_values={"cull.enabled": True, "cull.timeout": "not-a-number"}) + assert "CODE_SERVER_IDLE_TIMEOUT_SECONDS" not in c.KubeSpawner.environment + + +def test_proxy_activity_env_set_false_by_default(): + """Default (vscodeActivity.enabled=true): the chart actively opts the + pod into the new interaction-based behavior by setting the env var to + "false". The image defaults to the OLD behavior (True) when the var is + absent, so this active opt-in is what the chart is responsible for.""" + c = FakeConfig() + _load_spawner(c, chart_values={"vscode-activity-enabled": True}) assert ( - c.KubeSpawner.environment["VSCODE_PROXY_UPDATE_LAST_ACTIVITY"] == "true" + c.KubeSpawner.environment["VSCODE_PROXY_UPDATE_LAST_ACTIVITY"] == "false" ) + + +def test_proxy_activity_env_absent_when_vscode_activity_disabled(): + """vscodeActivity.enabled=false is the field escape hatch: the chart + sets nothing, so the image's fail-safe default (True, pre-#208 + behavior, proxied traffic counts as activity again) applies.""" + c = FakeConfig() + _load_spawner(c, chart_values={"vscode-activity-enabled": False}) + assert "VSCODE_PROXY_UPDATE_LAST_ACTIVITY" not in c.KubeSpawner.environment diff --git a/tests/unit/test_vscode_server_registration.py b/tests/unit/test_vscode_server_registration.py index 1756d4f5..9774dca0 100644 --- a/tests/unit/test_vscode_server_registration.py +++ b/tests/unit/test_vscode_server_registration.py @@ -35,14 +35,29 @@ def test_vscode_entry_registered_alongside_nebi(monkeypatch): assert "vscode" in servers -def test_vscode_does_not_count_proxy_traffic_by_default(monkeypatch): +def test_vscode_counts_proxy_traffic_by_default_without_chart_plumbing(monkeypatch): + """Fail-safe default: with the env var absent (e.g. an image deployed + without the chart's opt-in plumbing), the image falls back to the OLD + behavior (counting proxied traffic as activity), so chart/image skew + over-spends rather than culling active users with no reporter.""" monkeypatch.delenv("VSCODE_PROXY_UPDATE_LAST_ACTIVITY", raising=False) c = FakeConfig() _load_image_config(c) + assert c.ServerProxy.servers["vscode"]["update_last_activity"] is True + + +def test_vscode_chart_optin_disables_activity_counting(monkeypatch): + """The chart opts pods into the new behavior by setting the env var to + "false" when vscodeActivity.enabled is true.""" + monkeypatch.setenv("VSCODE_PROXY_UPDATE_LAST_ACTIVITY", "false") + c = FakeConfig() + _load_image_config(c) assert c.ServerProxy.servers["vscode"]["update_last_activity"] is False def test_vscode_escape_hatch_env_restores_activity_counting(monkeypatch): + """An explicit "true" env var (e.g. set manually via extraEnv) restores + the old activity-counting behavior regardless of chart plumbing.""" monkeypatch.setenv("VSCODE_PROXY_UPDATE_LAST_ACTIVITY", "true") c = FakeConfig() _load_image_config(c) From 7258d3bd34e641f5036d04db12920a45bfde36c7 Mon Sep 17 00:00:00 2001 From: Tyler Potts <49161327+tylerpotts@users.noreply.github.com> Date: Wed, 19 Aug 2026 17:19:52 -0500 Subject: [PATCH 17/24] ci: point e2e at this branch's built image (sha-7a07d8e) The e2e job pulls the singleuser image tag pinned in values.yaml, so without this bump the two image-dependent VS Code idle-culling tests would run against the pre-branch image and fail. sha-7a07d8e is the Build Docker Images output for this PR's merge commit. --- values.yaml | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/values.yaml b/values.yaml index 72a753d4..2408bd59 100644 --- a/values.yaml +++ b/values.yaml @@ -514,7 +514,7 @@ jupyterhub: # The same value sits inside profile_options.image.choices.default # so the JupyterLab profile selector keeps showing it too. # scripts/bump_image_tags.py syncs all three on every bump. - image: quay.io/nebari/nebari-data-science-pack-jupyterlab:sha-16c1922 + image: quay.io/nebari/nebari-data-science-pack-jupyterlab:sha-7a07d8e cpu_limit: 1 cpu_guarantee: 0.5 mem_limit: "2G" @@ -524,15 +524,15 @@ jupyterhub: display_name: Image choices: default: - display_name: "nebari-data-science-pack-jupyterlab:sha-16c1922" + display_name: "nebari-data-science-pack-jupyterlab:sha-7a07d8e" default: true kubespawner_override: - image: quay.io/nebari/nebari-data-science-pack-jupyterlab:sha-16c1922 + image: quay.io/nebari/nebari-data-science-pack-jupyterlab:sha-7a07d8e - slug: medium-instance display_name: "Medium Instance" description: "4 CPU / 8 GB RAM — pandas / scikit-learn workloads on medium datasets." kubespawner_override: - image: quay.io/nebari/nebari-data-science-pack-jupyterlab:sha-16c1922 + image: quay.io/nebari/nebari-data-science-pack-jupyterlab:sha-7a07d8e cpu_limit: 4 cpu_guarantee: 2 mem_limit: "8G" @@ -542,10 +542,10 @@ jupyterhub: display_name: Image choices: default: - display_name: "nebari-data-science-pack-jupyterlab:sha-16c1922" + display_name: "nebari-data-science-pack-jupyterlab:sha-7a07d8e" default: true kubespawner_override: - image: quay.io/nebari/nebari-data-science-pack-jupyterlab:sha-16c1922 + image: quay.io/nebari/nebari-data-science-pack-jupyterlab:sha-7a07d8e # Terminal customization: controls Starship prompt in JupyterLab terminals. # When false, falls back to the default bash prompt. terminal-customization: true @@ -607,7 +607,7 @@ jupyterhub: # class clears current_user — id_token_hint now reaches KC). image: name: quay.io/nebari/nebari-data-science-pack-jupyterhub - tag: "sha-16c1922" + tag: "sha-7a07d8e" config: JupyterHub: @@ -700,7 +700,7 @@ jupyterhub: # keeps the two in sync on every automated bump instead. initContainers: - name: merge-ca-bundle - image: quay.io/nebari/nebari-data-science-pack-jupyterhub:sha-16c1922 + image: quay.io/nebari/nebari-data-science-pack-jupyterhub:sha-7a07d8e imagePullPolicy: IfNotPresent # z2jh's pod-level securityContext sets ``runAsNonRoot: true`` but # no explicit uid, and the hub image's default ``USER`` is root, @@ -767,7 +767,7 @@ jupyterhub: singleuser: image: name: quay.io/nebari/nebari-data-science-pack-jupyterlab - tag: "sha-16c1922" + tag: "sha-7a07d8e" defaultUrl: "/lab" extraEnv: JUPYTERHUB_SINGLEUSER_APP: "jupyter_server.serverapp.ServerApp" From d0383cb6024241b6f8189a1ed7b4b46f4f28ba82 Mon Sep 17 00:00:00 2001 From: Tyler Potts <49161327+tylerpotts@users.noreply.github.com> Date: Wed, 19 Aug 2026 17:34:38 -0500 Subject: [PATCH 18/24] fix(e2e): wait for the singleuser server before curling it spawn_user waits for the pod Ready condition, but singleuser pods have no readiness probe on the jupyter port, so kubectl exec raced jupyterhub-singleuser binding :8888 (curl rc=7 in CI). Poll /api/status until it answers before the server-dependent assertions. --- tests/e2e/test_vscode_idle_culling.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/tests/e2e/test_vscode_idle_culling.py b/tests/e2e/test_vscode_idle_culling.py index 1f6a7865..15e639cd 100644 --- a/tests/e2e/test_vscode_idle_culling.py +++ b/tests/e2e/test_vscode_idle_culling.py @@ -25,6 +25,8 @@ import json import time +import pytest + # JUPYTERHUB_SERVICE_PREFIX ends with "/" — concatenate with ${VAR} (no # added slash): the proxy route regex does not tolerate "//vscode/". CURL_STATUS = ( @@ -33,6 +35,28 @@ ) +def _wait_for_server(user, timeout_s=180): + """Block until the singleuser jupyter server answers on :8888. + + `spawn_user` waits for the POD Ready condition, but singleuser pods + have no readiness probe on the jupyter port, so `kubectl exec` can win + the race against `jupyterhub-singleuser` binding :8888 (first observed + as curl rc=7 in CI). Poll the status endpoint until it answers; every + other exec in these tests can then assume the server is up. + """ + deadline = time.time() + timeout_s + rc, out = 1, "" + while time.time() < deadline: + rc, out = user.exec("bash", "-c", CURL_STATUS) + if rc == 0: + return + time.sleep(3) + pytest.fail( + f"singleuser server never answered /api/status within {timeout_s}s " + f"(last rc={rc}: {out})" + ) + + def _last_activity(user): rc, out = user.exec("bash", "-c", CURL_STATUS) assert rc == 0, f"/api/status failed (rc={rc}): {out}" @@ -63,6 +87,7 @@ def test_vscode_proxy_traffic_does_not_count_as_activity(spawn_user): """The core #208 behavior: requests through /vscode/ (which is exactly what an open tab's keepalives are) must NOT advance last_activity.""" u = spawn_user("alice-data") + _wait_for_server(u) # First hit starts code-server via jupyter-server-proxy (timeout 300 in # the server entry; jsp blocks the request until the backend is up). rc, out = u.exec( @@ -91,6 +116,7 @@ def test_contents_api_ping_counts_as_activity(spawn_user): """The extension's reporting mechanism: an authenticated contents-API request must advance last_activity (ISO8601 compares lexicographically).""" u = spawn_user("alice-data") + _wait_for_server(u) before = _last_activity(u) time.sleep(1.1) # ensure a strictly later timestamp is observable rc, out = u.exec( From 950077d8ef7fe903a78f3762dd8333adf61c970b Mon Sep 17 00:00:00 2001 From: Tyler Potts <49161327+tylerpotts@users.noreply.github.com> Date: Thu, 20 Aug 2026 09:18:33 -0500 Subject: [PATCH 19/24] docs: drop superpowers working docs from the PR --- .../plans/2026-08-19-vscode-idle-culling.md | 1201 ----------------- .../specs/2026-06-29-apply-nb-umask-design.md | 143 -- .../2026-08-19-vscode-idle-culling-design.md | 267 ---- 3 files changed, 1611 deletions(-) delete mode 100644 docs/superpowers/plans/2026-08-19-vscode-idle-culling.md delete mode 100644 docs/superpowers/specs/2026-06-29-apply-nb-umask-design.md delete mode 100644 docs/superpowers/specs/2026-08-19-vscode-idle-culling-design.md diff --git a/docs/superpowers/plans/2026-08-19-vscode-idle-culling.md b/docs/superpowers/plans/2026-08-19-vscode-idle-culling.md deleted file mode 100644 index 4c0330b8..00000000 --- a/docs/superpowers/plans/2026-08-19-vscode-idle-culling.md +++ /dev/null @@ -1,1201 +0,0 @@ -# VS Code Interaction-Based Idle Culling Implementation Plan - -> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. - -**Goal:** Make VS Code (code-server) user pods idle-cull with the same semantics as notebook pods: real interaction or running work keeps the pod alive; an open-but-idle browser tab does not. Closes https://github.com/nebari-dev/data-science-pack/issues/208. - -**Architecture:** Two composing mechanisms. (1) The `vscode` jupyter-server-proxy entry is re-registered by this repo (replacing the `jupyter-vscode-proxy` package) with `update_last_activity: False`, so VS Code keepalive traffic stops feeding jupyter's `api_last_activity`; a bundled server-side VS Code extension (`nebari-activity-reporter`) reports *real* user interaction to the local jupyter API instead. (2) `CODE_SERVER_IDLE_TIMEOUT_SECONDS` (new in code-server 4.106.0; we bump to 4.133.0) is derived from the hub culler's `cull.timeout` so lingering code-server processes exit after all browser connections drop. - -**Tech Stack:** Helm chart + z2jh JupyterHub config (Python, exec'd config files), jupyter-server-proxy 4.5.0, code-server 4.133.0, plain-JavaScript VS Code extension (stable API only, no build step), stdlib-Python `.vsix` packager, pytest unit tests, kind-based e2e harness. - -**Spec:** `docs/superpowers/specs/2026-08-19-vscode-idle-culling-design.md` — read it first, especially the "Pre-implementation corrections" block. - -## Global Constraints - -- code-server rejects `--idle-timeout-seconds` ≤ 60 at startup: never set `CODE_SERVER_IDLE_TIMEOUT_SECONDS` unless the value is **> 60** and culling is enabled. -- `jupyter_server` handlers with `_track_activity = False` (`/api/status`, `/api/`) do NOT count as activity. The extension must ping `GET {service}/api/contents/?content=0` (tracked). -- The image config file `images/nebi/jupyter_server_config.py` owns `c.ServerProxy.servers` as a dict **assignment** and loads after the chart ConfigMap — the vscode entry must live there, not in the ConfigMap. -- postStart hook commands are joined with `" && "` in `_setup_nss_wrapper`; the extension install must be wrapped `{ ... || true; }` so its failure can't CrashLoop the pod and can't mask earlier commands' failures. -- Extension uses **stable** VS Code APIs only (`engines.vscode: ^1.93.0`; no `onDidWriteTerminalData`, which is proposed-API). -- Extension names: package `name: nebari-activity-reporter`, `publisher: nebari`, version `0.1.0`. Installed extension dir will be `nebari.nebari-activity-reporter-0.1.0`. Baked vsix path (version-independent): `/opt/code-server-extensions/nebari-activity-reporter.vsix`. -- Env var names (exact): `CODE_SERVER_IDLE_TIMEOUT_SECONDS`, `VSCODE_PROXY_UPDATE_LAST_ACTIVITY`. Chart-derived key (exact): `vscode-activity-enabled`. Values key (exact): `vscodeActivity.enabled`. -- Unit test environment (matches CI `.github/workflows/test.yaml`): - - ```bash - uv venv .venv-unit --python 3.10 - uv pip install --python .venv-unit/bin/python \ - jupyterhub==5.5.0 oauthenticator==17.4.0 jupyterhub-kubespawner==7.0.0 pytest - .venv-unit/bin/python -m pytest tests/unit -v - ``` - - `helm` must be on PATH for `tests/unit/test_chart_derived.py`-style tests (they skip otherwise — a skip is NOT a pass for the tasks below that add helm-rendering tests; install helm). -- Commit style: repo uses conventional commits (`feat:`, `test:`, `docs:`, `refactor:`). Do not add co-authors or "Generated by" lines. - ---- - -### Task 1: Bump code-server to 4.133.0 - -The idle-timeout flag landed in code-server 4.106.0 (coder/code-server PR 7539); the repo pins 4.104.3. `install.sh` is byte-identical between v4.104.3 and v4.133.0 (sha256 `e86784e9fec81106c74941e55dbbcb85dc963a06ad6c3f1a870d4a22cf432e1d`, verified 2026-08-19), so only the version string and URL tag change. - -**Files:** -- Modify: `images/scripts/install-code-server.sh` - -**Interfaces:** -- Produces: a singleuser image whose `code-server` honors `CODE_SERVER_IDLE_TIMEOUT_SECONDS` (consumed by Task 2's env var and Task 10's e2e). - -- [ ] **Step 1: Edit the version pin and URL** - -In `images/scripts/install-code-server.sh` change line 8 and line 14 (the sha256 on line 15 stays): - -```bash -CODE_SERVER_VERSION=4.133.0 -``` - -```bash -# Fetch the snapshot of https://code-server.dev/install.sh as of the time of writing -wget --quiet https://raw.githubusercontent.com/coder/code-server/v4.133.0/install.sh -``` - -- [ ] **Step 2: Verify the hash claim locally** - -Run: -```bash -curl -sL https://raw.githubusercontent.com/coder/code-server/v4.133.0/install.sh | shasum -a 256 -``` -Expected output: `e86784e9fec81106c74941e55dbbcb85dc963a06ad6c3f1a870d4a22cf432e1d -` (matches the `expected_sum` already in the script). - -- [ ] **Step 3: Commit** - -```bash -git add images/scripts/install-code-server.sh -git commit -m "feat: bump code-server to 4.133.0 for idle-timeout support" -``` - ---- - -### Task 2: Spawner sets CODE_SERVER_IDLE_TIMEOUT_SECONDS from cull.timeout - -**Files:** -- Modify: `config/jupyterhub/01-spawner.py` (env section, after the `NEBI_SERVER_ALLOWED_ORIGINS` block ~line 318, before `c.KubeSpawner.environment = env`) -- Test: `tests/unit/test_spawner_code_server_idle.py` (create) - -**Interfaces:** -- Consumes: `get_config` (z2jh) — `cull.enabled` / `cull.timeout` from the jupyterhub subchart values (`values.yaml` sets `enabled: true`, `timeout: 1800`). -- Produces: pod env `CODE_SERVER_IDLE_TIMEOUT_SECONDS` (string), read by code-server ≥ 4.106 (Task 1); asserted by Task 10 e2e. - -- [ ] **Step 1: Write the failing tests** - -Create `tests/unit/test_spawner_code_server_idle.py`: - -```python -"""CODE_SERVER_IDLE_TIMEOUT_SECONDS wiring in `01-spawner.py`. - -code-server >= 4.106 exits N seconds after its last browser connection -closes when this env var is set. It must mirror the hub idle culler's -`cull.timeout` (issue #208) — and must be ABSENT when culling is disabled -or the timeout is <= 60, because code-server refuses to start for values -<= 60 and that would take down every user pod's VS Code. -""" - -from __future__ import annotations - -import importlib.util -import sys -import types - -# 01-spawner.py imports `z2jh.get_config`; stub it so the module exec's standalone. -_z2jh = types.ModuleType("z2jh") -_z2jh.get_config = lambda key, default=None: default -sys.modules.setdefault("z2jh", _z2jh) - -from conftest import CONFIG_DIR, FakeConfig # noqa: E402 - - -def _load_spawner(c: FakeConfig, z2jh_values: dict | None = None, - chart_values: dict | None = None): - """Exec raw 01-spawner.py with per-test z2jh + chart config stubs.""" - z2jh_values = z2jh_values or {} - chart_values = chart_values or {} - z2jh = sys.modules["z2jh"] - orig = z2jh.get_config - z2jh.get_config = lambda key, default=None: z2jh_values.get(key, default) - try: - path = CONFIG_DIR / "01-spawner.py" - spec = importlib.util.spec_from_file_location("_spawner_idle", path) - module = importlib.util.module_from_spec(spec) - module.__dict__["c"] = c - module.__dict__["get_chart_config"] = ( - lambda key, default="": chart_values.get(key, default) - ) - spec.loader.exec_module(module) - finally: - z2jh.get_config = orig - - -def test_idle_timeout_matches_cull_timeout(): - c = FakeConfig() - _load_spawner(c, z2jh_values={"cull.enabled": True, "cull.timeout": 1800}) - assert c.KubeSpawner.environment["CODE_SERVER_IDLE_TIMEOUT_SECONDS"] == "1800" - - -def test_idle_timeout_absent_when_culling_disabled(): - c = FakeConfig() - _load_spawner(c, z2jh_values={"cull.enabled": False, "cull.timeout": 1800}) - assert "CODE_SERVER_IDLE_TIMEOUT_SECONDS" not in c.KubeSpawner.environment - - -def test_idle_timeout_absent_when_60_or_less(): - """code-server errors out at startup for values <= 60 — never set them.""" - c = FakeConfig() - _load_spawner(c, z2jh_values={"cull.enabled": True, "cull.timeout": 60}) - assert "CODE_SERVER_IDLE_TIMEOUT_SECONDS" not in c.KubeSpawner.environment -``` - -- [ ] **Step 2: Run tests to verify they fail** - -Run: `.venv-unit/bin/python -m pytest tests/unit/test_spawner_code_server_idle.py -v` -Expected: `test_idle_timeout_matches_cull_timeout` FAILS with `KeyError: 'CODE_SERVER_IDLE_TIMEOUT_SECONDS'`; the two absence tests PASS (that's fine — the positive test is the driver). - -- [ ] **Step 3: Implement in 01-spawner.py** - -Insert after the `NEBI_SERVER_ALLOWED_ORIGINS` block (after the `env["NEBI_SERVER_ALLOWED_ORIGINS"] = ...` conditional, before `c.KubeSpawner.environment = env`): - -```python -# code-server >= 4.106 exits this many seconds after its last browser -# connection closes. Mirrors the hub idle culler so a lingering code-server -# child (tab closed, laptop asleep) dies on the same schedule the hub would -# cull the pod (issue #208). Values <= 60 are rejected by code-server at -# startup — skip them rather than break every pod's VS Code. -_cull_timeout = int(get_config("cull.timeout", 0) or 0) -if get_config("cull.enabled", False) and _cull_timeout > 60: - env["CODE_SERVER_IDLE_TIMEOUT_SECONDS"] = str(_cull_timeout) -``` - -- [ ] **Step 4: Run tests to verify they pass** - -Run: `.venv-unit/bin/python -m pytest tests/unit/test_spawner_code_server_idle.py tests/unit -v` -Expected: all PASS (whole unit suite, to catch env-section regressions). - -- [ ] **Step 5: Commit** - -```bash -git add config/jupyterhub/01-spawner.py tests/unit/test_spawner_code_server_idle.py -git commit -m "feat: derive CODE_SERVER_IDLE_TIMEOUT_SECONDS from cull.timeout" -``` - ---- - -### Task 3: Chart value vscodeActivity.enabled + chart-derived key - -**Files:** -- Modify: `values.yaml` (insert after the `singleuserCuller` block that ends at `shutdownNoActivityTimeout: 900`, ~line 181) -- Modify: `templates/hub-config.yaml` (`_CHART_DERIVED` dict, after the `"shared-storage-enabled"` entry ~line 56) -- Test: `tests/unit/test_chart_derived.py` (extend) - -**Interfaces:** -- Produces: `get_chart_config("vscode-activity-enabled", True)` returns the Python bool rendered from `.Values.vscodeActivity.enabled` (default `True`). Consumed by Task 4. - -- [ ] **Step 1: Write the failing test** - -Append to `tests/unit/test_chart_derived.py` (it already has the `rendered_chart_derived` fixture and `_exec_chart_derived` helper): - -```python -def test_vscode_activity_enabled_defaults_true(rendered_chart_derived): - """`vscodeActivity.enabled` must reach the spawner via _CHART_DERIVED so - the update_last_activity escape hatch (issue #208) is wireable without - a jupyterhub.custom.* override.""" - ns = _exec_chart_derived(rendered_chart_derived, z2jh_values={}) - assert ns["get_chart_config"]("vscode-activity-enabled") is True -``` - -- [ ] **Step 2: Run test to verify it fails** - -Run: `.venv-unit/bin/python -m pytest tests/unit/test_chart_derived.py::test_vscode_activity_enabled_defaults_true -v` -Expected: FAIL — `get_chart_config("vscode-activity-enabled")` returns `""` (the helper's default) because the key is not in `_CHART_DERIVED`. If the test SKIPS, install helm; a skip does not satisfy this step. - -- [ ] **Step 3: Add the value and the chart-derived entry** - -In `values.yaml`, immediately after the `singleuserCuller:` block: - -```yaml -# VS Code (code-server) idle-culling behavior. When enabled (default), VS -# Code browser traffic does NOT count as jupyter activity — the bundled -# nebari-activity-reporter extension reports real user interaction (typing, -# scrolling, terminal use) instead, so idle VS Code tabs cull on the normal -# schedule (https://github.com/nebari-dev/data-science-pack/issues/208). -# Set enabled: false to revert to counting raw proxied traffic (the -# pre-#208 behavior, which keeps pods alive while any tab is open). -vscodeActivity: - enabled: true -``` - -In `templates/hub-config.yaml`, inside `_CHART_DERIVED` after the `"shared-storage-enabled"` line: - -``` - # Mirrors .Values.vscodeActivity.enabled — drives the vscode proxy - # route's update_last_activity escape hatch in 01-spawner.py. - "vscode-activity-enabled": {{ ternary "True" "False" .Values.vscodeActivity.enabled }}, -``` - -- [ ] **Step 4: Run test to verify it passes** - -Run: `.venv-unit/bin/python -m pytest tests/unit/test_chart_derived.py -v` -Expected: all PASS. - -- [ ] **Step 5: Commit** - -```bash -git add values.yaml templates/hub-config.yaml tests/unit/test_chart_derived.py -git commit -m "feat: add vscodeActivity.enabled value with chart-derived plumbing" -``` - ---- - -### Task 4: Spawner sets VSCODE_PROXY_UPDATE_LAST_ACTIVITY escape hatch - -**Files:** -- Modify: `config/jupyterhub/01-spawner.py` (env section, directly after Task 2's block) -- Test: `tests/unit/test_spawner_code_server_idle.py` (extend — reuses `_load_spawner`) - -**Interfaces:** -- Consumes: `get_chart_config("vscode-activity-enabled", True)` (Task 3). -- Produces: pod env `VSCODE_PROXY_UPDATE_LAST_ACTIVITY="true"` **only when the deployer disables** `vscodeActivity`; read by the image config (Task 5). - -- [ ] **Step 1: Write the failing tests** - -Append to `tests/unit/test_spawner_code_server_idle.py`: - -```python -def test_proxy_activity_env_absent_by_default(): - """Default (vscodeActivity.enabled=true): the image config's default of - update_last_activity=False must apply, so no env var is set.""" - c = FakeConfig() - _load_spawner(c, chart_values={"vscode-activity-enabled": True}) - assert "VSCODE_PROXY_UPDATE_LAST_ACTIVITY" not in c.KubeSpawner.environment - - -def test_proxy_activity_env_set_when_vscode_activity_disabled(): - """vscodeActivity.enabled=false is the field escape hatch: proxied VS - Code traffic counts as activity again (pre-#208 behavior).""" - c = FakeConfig() - _load_spawner(c, chart_values={"vscode-activity-enabled": False}) - assert ( - c.KubeSpawner.environment["VSCODE_PROXY_UPDATE_LAST_ACTIVITY"] == "true" - ) -``` - -- [ ] **Step 2: Run tests to verify the new one fails** - -Run: `.venv-unit/bin/python -m pytest tests/unit/test_spawner_code_server_idle.py -v` -Expected: `test_proxy_activity_env_set_when_vscode_activity_disabled` FAILS with `KeyError`; the absent-by-default test passes. - -- [ ] **Step 3: Implement in 01-spawner.py** - -Directly after Task 2's block: - -```python -# Escape hatch for the interaction-based VS Code idle culling (issue #208): -# vscodeActivity.enabled=false reverts the vscode proxy route to counting -# raw proxied traffic as jupyter activity. The image's -# jupyter_server_config.py reads this env var when building -# c.ServerProxy.servers["vscode"]. -if not get_chart_config("vscode-activity-enabled", True): - env["VSCODE_PROXY_UPDATE_LAST_ACTIVITY"] = "true" -``` - -- [ ] **Step 4: Run tests to verify they pass** - -Run: `.venv-unit/bin/python -m pytest tests/unit/test_spawner_code_server_idle.py -v` -Expected: all PASS. - -- [ ] **Step 5: Commit** - -```bash -git add config/jupyterhub/01-spawner.py tests/unit/test_spawner_code_server_idle.py -git commit -m "feat: escape hatch env var for vscode proxy activity counting" -``` - ---- - -### Task 5: Register vscode server in image config; drop jupyter-vscode-proxy - -**Files:** -- Modify: `images/nebi/jupyter_server_config.py` (append after the existing `c.ServerProxy.servers = {...}` assignment) -- Modify: `images/jupyterlab/pixi.toml` (remove line 75: `jupyter-vscode-proxy = { git = "https://github.com/betatim/vscode-binder.git" }`) -- Modify: `images/jupyterlab/pixi.lock` (regenerated) -- Create: `images/nebi/icons/code-server.svg` (downloaded) -- Test: `tests/unit/test_vscode_server_registration.py` (create) - -**Interfaces:** -- Consumes: env `VSCODE_PROXY_UPDATE_LAST_ACTIVITY` (Task 4), optional `CODE_WORKINGDIR` / `CODE_EXTENSIONSDIR` (pre-existing jupyter-vscode-proxy contract). -- Produces: `c.ServerProxy.servers["vscode"]` dict with keys `command` (list, `--port={port}` placeholder), `timeout`, `new_browser_tab`, `update_last_activity` (bool), `launcher_entry`. Route stays `/vscode/` (same name as before — user bookmarks keep working). - -- [ ] **Step 1: Write the failing tests** - -Create `tests/unit/test_vscode_server_registration.py`: - -```python -"""The image-owned jupyter_server_config.py must register the `vscode` -jupyter-server-proxy entry itself (the jupyter-vscode-proxy package was -dropped) with update_last_activity=False, so VS Code keepalive traffic -stops defeating the idle cullers (issue #208). - -This file exec's like JupyterHub does: with `c` in scope. -""" - -from __future__ import annotations - -import importlib.util -from pathlib import Path - -from conftest import FakeConfig - -REPO_ROOT = Path(__file__).resolve().parents[2] -IMAGE_CONFIG = REPO_ROOT / "images" / "nebi" / "jupyter_server_config.py" - - -def _load_image_config(c: FakeConfig): - spec = importlib.util.spec_from_file_location("_img_jsc", IMAGE_CONFIG) - module = importlib.util.module_from_spec(spec) - module.__dict__["c"] = c - spec.loader.exec_module(module) - return module - - -def test_vscode_entry_registered_alongside_nebi(monkeypatch): - monkeypatch.delenv("VSCODE_PROXY_UPDATE_LAST_ACTIVITY", raising=False) - monkeypatch.delenv("CODE_EXTENSIONSDIR", raising=False) - c = FakeConfig() - _load_image_config(c) - servers = c.ServerProxy.servers - assert "nebi" in servers, "vscode registration must not clobber nebi" - assert "vscode" in servers - - -def test_vscode_does_not_count_proxy_traffic_by_default(monkeypatch): - monkeypatch.delenv("VSCODE_PROXY_UPDATE_LAST_ACTIVITY", raising=False) - c = FakeConfig() - _load_image_config(c) - assert c.ServerProxy.servers["vscode"]["update_last_activity"] is False - - -def test_vscode_escape_hatch_env_restores_activity_counting(monkeypatch): - monkeypatch.setenv("VSCODE_PROXY_UPDATE_LAST_ACTIVITY", "true") - c = FakeConfig() - _load_image_config(c) - assert c.ServerProxy.servers["vscode"]["update_last_activity"] is True - - -def test_vscode_command_matches_previous_package_contract(monkeypatch): - """Drop-in replacement for jupyter-vscode-proxy's generated command.""" - monkeypatch.delenv("CODE_EXTENSIONSDIR", raising=False) - monkeypatch.delenv("CODE_WORKINGDIR", raising=False) - c = FakeConfig() - _load_image_config(c) - cmd = c.ServerProxy.servers["vscode"]["command"] - assert cmd[0] == "code-server" - assert "--auth" in cmd and "none" in cmd - assert "--disable-telemetry" in cmd - assert "--port={port}" in cmd - assert cmd[-1] == "." # CODE_WORKINGDIR default - - -def test_vscode_command_honors_code_extensionsdir(monkeypatch): - monkeypatch.setenv("CODE_EXTENSIONSDIR", "/custom/ext") - c = FakeConfig() - _load_image_config(c) - cmd = c.ServerProxy.servers["vscode"]["command"] - assert "--extensions-dir" in cmd - assert "/custom/ext" in cmd - - -def test_vscode_launcher_entry_and_icon_exist(monkeypatch): - monkeypatch.delenv("VSCODE_PROXY_UPDATE_LAST_ACTIVITY", raising=False) - c = FakeConfig() - _load_image_config(c) - entry = c.ServerProxy.servers["vscode"]["launcher_entry"] - assert entry["title"] == "VS Code" - assert Path(entry["icon_path"]).name == "code-server.svg" - assert (REPO_ROOT / "images" / "nebi" / "icons" / "code-server.svg").exists() -``` - -- [ ] **Step 2: Run tests to verify they fail** - -Run: `.venv-unit/bin/python -m pytest tests/unit/test_vscode_server_registration.py -v` -Expected: all 6 FAIL with `KeyError: 'vscode'` (or icon-missing assert). - -- [ ] **Step 3: Download the launcher icon** - -```bash -curl -fsSL https://raw.githubusercontent.com/betatim/vscode-binder/master/jupyter_vscode_proxy/icons/code-server.svg \ - -o images/nebi/icons/code-server.svg -``` -Verify it's an SVG: `head -c 200 images/nebi/icons/code-server.svg` should show ` { - res.resume(); // drain — only the request itself matters - if (res.statusCode < 200 || res.statusCode >= 300) { - output.appendLine(`activity ping (${reason}): HTTP ${res.statusCode}`); - } - }, - ); - req.on("error", (e) => { - // Never throw out of an event handler; next interaction retries. - output.appendLine(`activity ping (${reason}) failed: ${e.message}`); - }); -} - -function recordActivity(reason) { - const now = Date.now(); - if (now - lastPingMs < PING_INTERVAL_MS) { - return; - } - lastPingMs = now; - ping(reason); -} - -function activate(context) { - output = vscode.window.createOutputChannel("Nebari Activity Reporter"); - output.appendLine("activated"); - - const on = (event, reason) => { - context.subscriptions.push(event(() => recordActivity(reason))); - }; - on(vscode.workspace.onDidChangeTextDocument, "edit"); - on(vscode.window.onDidChangeTextEditorSelection, "selection"); - on(vscode.window.onDidChangeTextEditorVisibleRanges, "scroll"); - on(vscode.window.onDidChangeWindowState, "focus"); - on(vscode.window.onDidOpenTerminal, "terminal-open"); - on(vscode.window.onDidCloseTerminal, "terminal-close"); - - // Busy = active: a running terminal command keeps the pod alive, like - // cullBusy=false does for kernels. Requires shell integration (auto- - // injected for bash/zsh). Guarded: API is stable since 1.93 but cheap - // to feature-detect. - if (vscode.window.onDidStartTerminalShellExecution) { - context.subscriptions.push( - vscode.window.onDidStartTerminalShellExecution(() => { - busyExecutions += 1; - recordActivity("exec-start"); - }), - ); - context.subscriptions.push( - vscode.window.onDidEndTerminalShellExecution(() => { - busyExecutions = Math.max(0, busyExecutions - 1); - recordActivity("exec-end"); - }), - ); - } - - const busyTimer = setInterval(() => { - if (busyExecutions > 0) { - recordActivity("busy"); - } - }, PING_INTERVAL_MS); - context.subscriptions.push({ dispose: () => clearInterval(busyTimer) }); - - // A user just opened/reconnected VS Code — that is activity. - recordActivity("startup"); -} - -function deactivate() {} - -module.exports = { activate, deactivate }; -``` - -- [ ] **Step 3: Syntax-check** - -Run: `node --check images/jupyterlab/vscode-activity-reporter/extension.js && python3 -c "import json; json.load(open('images/jupyterlab/vscode-activity-reporter/package.json'))"` -Expected: no output, exit 0. If `node` is not installed locally, the python json check must still pass and Task 7's packaging test exercises the file read; note the skipped node check in the commit body. - -- [ ] **Step 4: Commit** - -```bash -git add images/jupyterlab/vscode-activity-reporter/ -git commit -m "feat: nebari-activity-reporter VS Code extension" -``` - ---- - -### Task 7: build-vsix.py packager - -A `.vsix` is a zip with `extension.vsixmanifest`, `[Content_Types].xml`, and the extension files under `extension/`. Stdlib-only — the image build has no node/npm. - -**Files:** -- Create: `images/scripts/build-vsix.py` -- Test: `tests/unit/test_build_vsix.py` (create) - -**Interfaces:** -- Consumes: an extension source dir containing `package.json` with `name`, `version`, `publisher` (Task 6's contract). -- Produces: CLI `python build-vsix.py `; the vsix installs via `code-server --install-extension` (Task 8 builds it, Task 9 installs it). - -- [ ] **Step 1: Write the failing test** - -Create `tests/unit/test_build_vsix.py`: - -```python -"""build-vsix.py packages an extension dir into a code-server-installable -.vsix (zip with manifest) without needing node/vsce in the image build.""" - -from __future__ import annotations - -import importlib.util -import json -import zipfile -from pathlib import Path - -REPO_ROOT = Path(__file__).resolve().parents[2] -SCRIPT = REPO_ROOT / "images" / "scripts" / "build-vsix.py" - - -def _build(tmp_path: Path) -> Path: - src = tmp_path / "ext" - src.mkdir() - (src / "package.json").write_text(json.dumps({ - "name": "nebari-activity-reporter", - "publisher": "nebari", - "version": "0.1.0", - "displayName": "Nebari Activity Reporter", - "description": "test fixture", - })) - (src / "extension.js").write_text("module.exports = {};\n") - dest = tmp_path / "out" / "ext.vsix" - - spec = importlib.util.spec_from_file_location("_build_vsix", SCRIPT) - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - module.main(str(src), str(dest)) - return dest - - -def test_vsix_layout(tmp_path): - dest = _build(tmp_path) - with zipfile.ZipFile(dest) as z: - names = set(z.namelist()) - assert "extension.vsixmanifest" in names - assert "[Content_Types].xml" in names - assert "extension/package.json" in names - assert "extension/extension.js" in names - - -def test_vsix_manifest_identity(tmp_path): - dest = _build(tmp_path) - with zipfile.ZipFile(dest) as z: - manifest = z.read("extension.vsixmanifest").decode() - assert 'Id="nebari-activity-reporter"' in manifest - assert 'Publisher="nebari"' in manifest - assert 'Version="0.1.0"' in manifest -``` - -- [ ] **Step 2: Run test to verify it fails** - -Run: `.venv-unit/bin/python -m pytest tests/unit/test_build_vsix.py -v` -Expected: FAIL — `FileNotFoundError` loading `images/scripts/build-vsix.py`. - -- [ ] **Step 3: Write build-vsix.py** - -```python -#!/usr/bin/env python3 -# Copyright (c) Nebari Development Team. -# Distributed under the terms of the Modified BSD License. -"""Package a VS Code extension directory as a .vsix, without vsce. - -A .vsix is a zip containing extension.vsixmanifest, [Content_Types].xml -and the extension files under extension/. `code-server ---install-extension` reads the manifest Identity plus -extension/package.json. Used at image build time because the build -environment has no node/npm toolchain. - -Usage: build-vsix.py -""" - -import json -import sys -import zipfile -from pathlib import Path - -MANIFEST = """ - - - - {display} - {description} - Other - - - - - - - - - -""" - -CONTENT_TYPES = """ - - - - - -""" - - -def main(src, dest): - src, dest = Path(src), Path(dest) - pkg = json.loads((src / "package.json").read_text()) - manifest = MANIFEST.format( - name=pkg["name"], - version=pkg["version"], - publisher=pkg["publisher"], - display=pkg.get("displayName", pkg["name"]), - description=pkg.get("description", ""), - ) - dest.parent.mkdir(parents=True, exist_ok=True) - with zipfile.ZipFile(dest, "w", zipfile.ZIP_DEFLATED) as z: - z.writestr("extension.vsixmanifest", manifest) - z.writestr("[Content_Types].xml", CONTENT_TYPES) - for f in sorted(src.rglob("*")): - if f.is_file(): - z.write(f, "extension/" + str(f.relative_to(src))) - - -if __name__ == "__main__": - if len(sys.argv) != 3: - sys.exit(__doc__) - main(sys.argv[1], sys.argv[2]) -``` - -- [ ] **Step 4: Run tests to verify they pass** - -Run: `.venv-unit/bin/python -m pytest tests/unit/test_build_vsix.py -v` -Expected: both PASS. - -- [ ] **Step 5: Commit** - -```bash -git add images/scripts/build-vsix.py tests/unit/test_build_vsix.py -git commit -m "feat: stdlib vsix packager for image builds" -``` - ---- - -### Task 8: Bake the vsix into the image - -**Files:** -- Modify: `images/jupyterlab/postBuild` (after the `install-code-server.sh` line, before `fix-permissions`) - -**Interfaces:** -- Consumes: Task 6's extension source at `/opt/jupyterlab/vscode-activity-reporter` (`COPY jupyterlab /opt/jupyterlab` already ships it — no Dockerfile change needed) and Task 7's script at `/opt/scripts/build-vsix.py` (`COPY scripts /opt/scripts` already ships it). -- Produces: `/opt/code-server-extensions/nebari-activity-reporter.vsix` in the image (consumed by Task 9's postStart). - -- [ ] **Step 1: Add the packaging step to postBuild** - -`images/jupyterlab/postBuild` becomes: - -```bash -#!/usr/bin/env bash -set -euo pipefail -set -x - -# install code-server extension -sh /opt/scripts/install-code-server.sh "/opt/jupyterlab/.pixi/envs/${DEFAULT_ENV}/share" - -# Package the activity-reporter extension as a vsix. Installed per-user by a -# postStart hook (01-spawner.py) because the extensions dir lives on the -# home PVC, which would shadow a build-time install. The pixi env's python -# is not on PATH at this point in the build — use it explicitly. -"/opt/jupyterlab/.pixi/envs/${DEFAULT_ENV}/bin/python" /opt/scripts/build-vsix.py \ - /opt/jupyterlab/vscode-activity-reporter \ - /opt/code-server-extensions/nebari-activity-reporter.vsix - -fix-permissions "/opt/jupyterlab/.pixi/envs/${DEFAULT_ENV}" -``` - -- [ ] **Step 2: Sanity-check the script parses** - -Run: `bash -n images/jupyterlab/postBuild` -Expected: no output, exit 0. (Full validation is the image build in CI — `build-images.yaml` builds on PR; do not attempt the multi-GB build locally unless something fails there.) - -- [ ] **Step 3: Commit** - -```bash -git add images/jupyterlab/postBuild -git commit -m "feat: bake nebari-activity-reporter vsix into singleuser image" -``` - ---- - -### Task 9: postStart installs the extension into the user pod - -**Files:** -- Modify: `config/jupyterhub/01-spawner.py` (inside `_setup_nss_wrapper`, append to `nss_cmds` immediately after the initial two printf commands, before the `REMOVE_SYMLINK_ONLY` logic) -- Test: `tests/unit/test_nss_wrapper_shared_dir.py` (extend — reuses its `FakeSpawner`, `_load_spawner_module`, `_poststart_cmd` helpers) - -**Interfaces:** -- Consumes: `/opt/code-server-extensions/nebari-activity-reporter.vsix` (Task 8); `code-server` CLI on PATH in the pod (Dockerfile already prepends its bin dir). -- Produces: extension installed under `~/.local/share/code-server/extensions/nebari.nebari-activity-reporter-` on every spawn (asserted by Task 10 e2e). - -- [ ] **Step 1: Write the failing test** - -Append to `tests/unit/test_nss_wrapper_shared_dir.py`: - -```python -def test_poststart_installs_activity_reporter_extension_nonfatally(): - """Every spawn installs the bundled activity-reporter vsix into the - PVC-backed extensions dir (idempotent; --force handles upgrades). The - braces + `|| true` isolate the install: with a bare `a && b || true`, - a failure of the nss-wrapper printf commands would ALSO be masked, - and a failed install would CrashLoop the pod without the guard.""" - mod = _load_spawner_module(shared_storage_enabled=False) - spawner = FakeSpawner() - asyncio.run(mod._setup_nss_wrapper(spawner, "alice", [])) - cmd = _poststart_cmd(spawner) - assert ( - "{ code-server --install-extension " - "/opt/code-server-extensions/nebari-activity-reporter.vsix " - "--force || true; }" in cmd - ) -``` - -- [ ] **Step 2: Run test to verify it fails** - -Run: `.venv-unit/bin/python -m pytest tests/unit/test_nss_wrapper_shared_dir.py -v` -Expected: the new test FAILS (substring not found); all pre-existing tests PASS. - -- [ ] **Step 3: Implement in _setup_nss_wrapper** - -In `config/jupyterhub/01-spawner.py`, right after the `nss_cmds = [...]` list is built (the two printf commands), insert: - -```python - # Install the bundled VS Code activity-reporter extension (issue #208) - # into the user's PVC-backed extensions dir. Runs every spawn: - # idempotent, and --force re-installs on image upgrades (new vsix - # version). Wrapped in { ... || true; } so an install failure neither - # CrashLoops the pod nor (via `&&`/`||` left-associativity) masks a - # failure of the preceding nss-wrapper commands. Silent breakage is - # covered by the e2e extension-installed test. - nss_cmds.append( - "{ code-server --install-extension " - "/opt/code-server-extensions/nebari-activity-reporter.vsix " - "--force || true; }" - ) -``` - -- [ ] **Step 4: Run tests to verify they pass** - -Run: `.venv-unit/bin/python -m pytest tests/unit/test_nss_wrapper_shared_dir.py tests/unit -v` -Expected: all PASS. - -- [ ] **Step 5: Commit** - -```bash -git add config/jupyterhub/01-spawner.py tests/unit/test_nss_wrapper_shared_dir.py -git commit -m "feat: install activity-reporter extension via postStart hook" -``` - ---- - -### Task 10: E2E tests - -The harness (`tests/e2e/`, kind + HTTP, no browser) can verify everything except extension *activation under a live VS Code client* (manual soak covers that). All assertions run inside the pod via `spawn_user(...).exec()`; `curl` is in the image. - -**Files:** -- Create: `tests/e2e/test_vscode_idle_culling.py` - -**Interfaces:** -- Consumes: `spawn_user` fixture (`tests/e2e/conftest.py` — returns `SpawnedUser` with `.exec(*cmd)` → `(rc, out)`), chart defaults (`cull.timeout: 1800`, `vscodeActivity.enabled: true`). - -- [ ] **Step 1: Write the e2e tests** - -Create `tests/e2e/test_vscode_idle_culling.py`: - -```python -"""VS Code idle-culling behavior (issue #208), verified inside a live pod. - -What e2e can and cannot cover: these tests exercise the proxy-activity -plumbing, the extension delivery, and the reporting endpoint — via HTTP -from inside the pod. Extension *activation* needs a real VS Code browser -client, which this harness doesn't have; that path is validated by manual -soak (see the design spec). -""" - -import json -import time - -# JUPYTERHUB_SERVICE_PREFIX ends with "/" — concatenate with ${VAR} (no -# added slash): the proxy route regex does not tolerate "//vscode/". -CURL_STATUS = ( - 'curl -sf -H "Authorization: token $JUPYTERHUB_API_TOKEN" ' - '"http://127.0.0.1:8888${JUPYTERHUB_SERVICE_PREFIX}api/status"' -) - - -def _last_activity(user): - rc, out = user.exec("bash", "-c", CURL_STATUS) - assert rc == 0, f"/api/status failed (rc={rc}): {out}" - return json.loads(out)["last_activity"] - - -def test_code_server_idle_timeout_env_matches_cull_timeout(spawn_user): - """Chart default cull.timeout=1800 must reach the pod env verbatim.""" - u = spawn_user("alice-data") - rc, out = u.exec("printenv", "CODE_SERVER_IDLE_TIMEOUT_SECONDS") - assert rc == 0, "CODE_SERVER_IDLE_TIMEOUT_SECONDS not set on the pod" - assert out.strip() == "1800" - - -def test_activity_reporter_extension_installed(spawn_user): - """postStart must install the bundled vsix. This is the tripwire for - the worst failure mode: silently-broken delivery would get active VS - Code users culled mid-session.""" - u = spawn_user("alice-data") - rc, out = u.exec( - "bash", "-c", "ls /home/jovyan/.local/share/code-server/extensions/" - ) - assert rc == 0, out - assert "nebari.nebari-activity-reporter" in out - - -def test_vscode_proxy_traffic_does_not_count_as_activity(spawn_user): - """The core #208 behavior: requests through /vscode/ (which is exactly - what an open tab's keepalives are) must NOT advance last_activity.""" - u = spawn_user("alice-data") - # First hit starts code-server via jupyter-server-proxy (timeout 300 in - # the server entry; jsp blocks the request until the backend is up). - rc, out = u.exec( - "bash", "-c", - 'curl -sf -o /dev/null -H "Authorization: token $JUPYTERHUB_API_TOKEN" ' - '"http://127.0.0.1:8888${JUPYTERHUB_SERVICE_PREFIX}vscode/"', - ) - assert rc == 0, f"vscode proxy route failed to start code-server: {out}" - - before = _last_activity(u) - for _ in range(3): - time.sleep(2) - u.exec( - "bash", "-c", - 'curl -s -o /dev/null -H "Authorization: token $JUPYTERHUB_API_TOKEN" ' - '"http://127.0.0.1:8888${JUPYTERHUB_SERVICE_PREFIX}vscode/"', - ) - after = _last_activity(u) - assert after == before, ( - f"proxied vscode traffic advanced last_activity {before} -> {after}; " - "update_last_activity=False is not applied on the vscode entry" - ) - - -def test_contents_api_ping_counts_as_activity(spawn_user): - """The extension's reporting mechanism: an authenticated contents-API - request must advance last_activity (ISO8601 compares lexicographically).""" - u = spawn_user("alice-data") - before = _last_activity(u) - time.sleep(1.1) # ensure a strictly later timestamp is observable - rc, out = u.exec( - "bash", "-c", - 'curl -sf -o /dev/null -H "Authorization: token $JUPYTERHUB_API_TOKEN" ' - '"http://127.0.0.1:8888${JUPYTERHUB_SERVICE_PREFIX}api/contents/?content=0"', - ) - assert rc == 0, out - after = _last_activity(u) - assert after > before, ( - "contents-API ping did not advance last_activity — the extension's " - "reporting endpoint would be ineffective" - ) -``` - -Note: `JUPYTERHUB_SERVICE_PREFIX` ends with `/`; every URL above concatenates `${JUPYTERHUB_SERVICE_PREFIX}` directly (no extra slash) and quotes the URL so `${...}` expands inside the `bash -c` string. - -- [ ] **Step 2: Sanity-check collection** - -Run: `.venv-unit/bin/python -m pytest tests/e2e/test_vscode_idle_culling.py --collect-only -q` -Expected: 4 tests collected, no import errors. - -- [ ] **Step 3: Run the e2e suite if a cluster is feasible locally, else rely on CI** - -Run (requires `kind`, `helm`, `kubectl`; heavy): -```bash -uvx pytest tests/e2e/test_vscode_idle_culling.py -v -``` -Expected: 4 PASS. **Important:** these tests exercise the freshly-built image (extension, code-server 4.133.0). CI's e2e job builds the image; locally you must have built it (`make jupyterlab` builds `jupyterlab:test`) and pointed the chart at it, or defer to CI. If deferring, state that explicitly in the task report — do not claim e2e passed. - -- [ ] **Step 4: Commit** - -```bash -git add tests/e2e/test_vscode_idle_culling.py -git commit -m "test: e2e coverage for VS Code idle-culling plumbing" -``` - ---- - -### Task 11: Documentation - -**Files:** -- Modify: `docs/src/content/docs/configuration.md` (values table row + new section) - -**Interfaces:** -- Consumes: names/behavior fixed by Tasks 2–9 (do not paraphrase env var or values keys — copy exactly). - -- [ ] **Step 1: Add the values-table row** - -In the configuration values table (the one whose row reads `| `singleuserCuller` | In-pod idle culling for kernels, terminals, and the server itself (separate from the hub-level `jupyterhub.cull`) |`), add directly below that row: - -```markdown -| `vscodeActivity` | Interaction-based idle culling for VS Code; `enabled: false` reverts to counting raw proxied traffic as activity | -``` - -- [ ] **Step 2: Add the explanatory section** - -Append this section to `docs/src/content/docs/configuration.md` (top-level heading level matching the document's existing section style): - -```markdown -## VS Code idle culling - -An open VS Code tab holds a websocket whose keepalives used to count as -Jupyter activity, so pods with an idle VS Code tab were never culled -([#208](https://github.com/nebari-dev/data-science-pack/issues/208)). The -pack now handles VS Code idleness like notebook idleness: - -- **Real interaction counts.** A bundled extension - (`nebari-activity-reporter`, installed automatically on every spawn) - reports typing, scrolling, terminal use, and window focus to the Jupyter - server. A running terminal command also counts as active — same policy - as `cullBusy: false` for kernels — provided the shell has VS Code shell - integration (automatic for bash/zsh; exotic shells running long jobs are - not detected). -- **Raw traffic does not.** The `/vscode/` proxy route runs with - `update_last_activity` disabled, so keepalives from an idle tab no longer - defeat `singleuserCuller` or the hub-level `jupyterhub.cull` culler. -- **Disconnected sessions exit promptly.** `CODE_SERVER_IDLE_TIMEOUT_SECONDS` - is set to `jupyterhub.cull.timeout` (skipped when culling is disabled or - the timeout is ≤ 60 seconds, which code-server rejects), so a code-server - process whose last browser connection has closed exits on the culler's - schedule instead of lingering. - -To revert to the previous behavior (any open tab keeps the pod alive), set: - -```yaml -vscodeActivity: - enabled: false -``` - -For a hard cost cap regardless of activity — e.g. a tab left open on an -always-awake machine — the hub culler's max-age is available separately: - -```yaml -jupyterhub: - cull: - maxAge: 86400 # kill servers after 24h no matter what -``` -``` - -- [ ] **Step 3: Commit** - -```bash -git add docs/src/content/docs/configuration.md -git commit -m "docs: VS Code idle culling behavior and escape hatches" -``` - ---- - -### Task 12: Final verification - -**Files:** -- No new files; runs and fixes only. - -- [ ] **Step 1: Full unit suite** - -Run: `.venv-unit/bin/python -m pytest tests/unit -v` -Expected: all PASS, zero skips among the tests added by this plan (helm-dependent tests must actually run). - -- [ ] **Step 2: Chart renders clean** - -Run: -```bash -helm dependency update . >/dev/null 2>&1 || true -helm template data-science-pack . --namespace jupyterhub \ - --set keycloak.hostname=keycloak.example.com >/dev/null && echo RENDER_OK -helm template data-science-pack . --namespace jupyterhub \ - --set keycloak.hostname=keycloak.example.com \ - --set vscodeActivity.enabled=false | grep -c '"vscode-activity-enabled": False' -``` -Expected: `RENDER_OK`, then `1` (the ternary renders `False` when disabled). - -- [ ] **Step 3: Lint (mirrors `.github/workflows/lint.yaml`)** - -```bash -helm lint . --set nebariapp.enabled=false -uvx ruff@0.16.0 check config/ -``` -Expected: helm lint reports 0 failures; ruff reports no findings. Fix anything reported. - -- [ ] **Step 4: Verification summary + push** - -Confirm every commit from Tasks 1–11 exists (`git log --oneline origin/main..HEAD`), then report: what was verified by tests, what was deferred to CI (image build, e2e), and what remains manual (soak test of extension activation under a real browser, per the spec's Testing section). diff --git a/docs/superpowers/specs/2026-06-29-apply-nb-umask-design.md b/docs/superpowers/specs/2026-06-29-apply-nb-umask-design.md deleted file mode 100644 index c5981e61..00000000 --- a/docs/superpowers/specs/2026-06-29-apply-nb-umask-design.md +++ /dev/null @@ -1,143 +0,0 @@ -# Apply `NB_UMASK` so the kernel actually uses it - -**Issue:** https://github.com/nebari-dev/data-science-pack/issues/144 - -> **Post-review update (PR #146):** review feedback pointed out that the -> `NB_UMASK` env var was set to a hardcoded `0002` and read in exactly one -> place, with no working override path. It was removed: the wrapper now applies -> `umask 0002` directly, and the `printenv NB_UMASK` e2e assertion was dropped. -> The env-var-based snippets below are the original design; the shipped code -> hardcodes the value. The rest of the reasoning (hub-side wrapper, `/proc` -> regression test, single-UID nuance) stands. - -## Problem - -`NB_UMASK=0002` is set on the singleuser pod environment (by -`config/jupyterhub/01-spawner.py`), but the JupyterLab kernel and terminal -processes run with the default umask `0022`. Files created by the kernel get -mode `644` instead of the intended `664`. - -### Root cause - -The comments in the spawner and the e2e tests assume "z2jh's `start.sh` applies -`NB_UMASK` before exec'ing the kernel." That is **false for this image**. The -singleuser image (`images/Dockerfile`, `jupyterlab` target) is a custom -Ubuntu/pixi build, **not** jupyter docker-stacks — there is no `start.sh`. -KubeSpawner launches `jupyterhub-singleuser` directly, and in Kubernetes the -pod's `command:` overrides any Dockerfile `ENTRYPOINT`. So `NB_UMASK` is an env -var that **nothing ever reads**. The kernel and terminals inherit the default -`0022`. - -### Severity nuance (corrected framing vs. the issue) - -The issue states the shared-storage collaboration story is "broken." That claim -is overstated for the **current** architecture: - -- Every singleuser pod runs as **UID 1000** — `01-spawner.py` hardcodes - `uid=1000` and nothing assigns per-user UIDs or overrides z2jh's default - `singleuser.uid: 1000`. So on the shared PVC every user-created file is owned - by UID 1000, and every user *is* UID 1000. -- Cross-user edits therefore already work via the **owner** write bit (the `6` - in `644`), independent of umask. The existing test - `test_files_are_visible_and_writable_to_groupmates` proves this: Carol appends - to Alice's file with a plain `exec` (no umask re-application) and it passes - today — because Carol is UID 1000, same as Alice. - -Where `0002` genuinely matters is files in `/shared` **not** owned by UID 1000 -(root-created, conda-store / service-written, or externally-synced content): -only the group-write bit makes those editable by group members. The fix is -still correct and worth doing — it honors the documented `664/2775` contract, -is correct defense-in-depth, and would be load-bearing the moment per-user UIDs -are introduced — but it is not the "collaboration is broken" emergency the -issue describes. - -## Fix - -Wrap the singleuser server command in `config/jupyterhub/01-spawner.py` so -`umask` runs before the server is exec'd: - -```python -c.KubeSpawner.cmd = [ - "sh", - "-c", - 'umask "${NB_UMASK:-0002}"; exec "$0" "$@"', - "jupyterhub-singleuser", -] -``` - -KubeSpawner appends its computed args after `command` in the pod spec, so the -final argv is `sh -c '